Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Keep a refresh token valid until its successor is used

Roland Geider2ae608ec7adb
diff --git a/wger/core/tests/test_headless.py b/wger/core/tests/test_headless.py
index 6b9385fb4..03a7183de 100644
--- a/wger/core/tests/test_headless.py
+++ b/wger/core/tests/test_headless.py
@@ -20,6 +20,7 @@ import json
# Django
from django.contrib.auth.models import User
+from django.test import Client
from django.urls import reverse
# Third Party
@@ -182,6 +183,54 @@ class HeadlessSmokeTestCase(WgerTestCase):
)
self.assertNotEqual(response.status_code, 200, response.content)
+ def _login_refresh_token(self) -> str:
+ response = self.client.post(
+ reverse('headless:app:account:login'),
+ data=json.dumps({'username': 'test', 'password': 'testtest'}),
+ content_type='application/json',
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+ return response.json()['meta']['refresh_token']
+
+ def _refresh(self, refresh_token: str):
+ # A cookie-less client, like the app
+ return Client().post(
+ reverse('headless:app:tokens:refresh'),
+ data=json.dumps({'refresh_token': refresh_token}),
+ content_type='application/json',
+ )
+
+ def test_refresh_token_survives_a_lost_response(self):
+ """
+ When the answer to a refresh never reaches the client, it still holds the
+ token it sent. That token has to keep working, and the successor the
+ client never saw is dropped in favour of the new one.
+ """
+ first = self._login_refresh_token()
+
+ lost = self._refresh(first)
+ self.assertEqual(lost.status_code, 200, lost.content)
+ lost_token = lost.json()['data']['refresh_token']
+
+ retry = self._refresh(first)
+ self.assertEqual(retry.status_code, 200, retry.content)
+ self.assertNotEqual(retry.json()['data']['refresh_token'], lost_token)
+
+ self.assertEqual(self._refresh(lost_token).status_code, 400)
+
+ def test_refresh_token_is_retired_once_its_successor_is_used(self):
+ """
+ Rotation still happens: after the successor has been used once, the
+ token it replaced is rejected.
+ """
+ first = self._login_refresh_token()
+
+ second = self._refresh(first).json()['data']['refresh_token']
+ response = self._refresh(second)
+ self.assertEqual(response.status_code, 200, response.content)
+
+ self.assertEqual(self._refresh(first).status_code, 400)
+
def test_invalid_jwt_does_not_break_auth_chain(self):
"""
A malformed Bearer token must not raise AuthenticationFailed in our
diff --git a/wger/utils/headless_auth.py b/wger/utils/headless_auth.py
index e1f304f04..1ef5b85fa 100644
--- a/wger/utils/headless_auth.py
+++ b/wger/utils/headless_auth.py
@@ -19,6 +19,7 @@
from django.contrib.auth import get_user_model
# Third Party
+from allauth.headless import app_settings
from allauth.headless.contrib.rest_framework.authentication import JWTTokenAuthentication
from allauth.headless.tokens.strategies.jwt import internal
from allauth.headless.tokens.strategies.jwt.strategy import JWTTokenStrategy
@@ -29,6 +30,11 @@ from rest_framework.exceptions import AuthenticationFailed
from wger.utils.timezone_auth import activate_user_timezone
+# Session key mapping the jti of each not yet used refresh token to the jti of
+# the token it replaced
+REFRESH_TOKEN_PREDECESSORS = 'wger_refresh_token_predecessors'
+
+
class HeadlessJWTAuthentication(JWTTokenAuthentication):
"""
Lenient variant of allauth's JWTTokenAuthentication.
@@ -101,10 +107,38 @@ class WgerJWTTokenStrategy(JWTTokenStrategy):
which asserts ``user.is_authenticated`` and raises a 500. Reject the token
cleanly instead, so the endpoint answers with the same error a client already
handles for an expired token.
+
+ Rotation is delayed: a refresh token stays valid until its successor has been
+ used once. Allauth drops it immediately, so a response lost on the way to the
+ client (timeout, network switch, app suspended) left it without a usable token.
"""
def refresh_token(self, refresh_token: str) -> tuple[str, str] | None:
validated = internal.validate_refresh_token(refresh_token)
if validated is None or validated[0] is None:
return None
- return super().refresh_token(refresh_token)
+ if not app_settings.JWT_ROTATE_REFRESH_TOKEN:
+ return super().refresh_token(refresh_token)
+
+ user, session, payload = validated
+ jti = payload['jti']
+ predecessors = session.setdefault(REFRESH_TOKEN_PREDECESSORS, {})
+
+ # Using a successor proves it arrived, the token it replaced can go
+ predecessor = predecessors.pop(jti, None)
+ if predecessor is not None:
+ internal.invalidate_refresh_token(session, {'jti': predecessor})
+
+ # A token used again after it was already replaced means that answer never
+ # arrived, so the unused successor is dropped in favour of the new one
+ for successor, replaced in list(predecessors.items()):
+ if replaced == jti:
+ del predecessors[successor]
+ internal.invalidate_refresh_token(session, {'jti': successor})
+
+ access_token = internal.create_access_token(user, session, self.get_claims(user))
+ next_refresh_token = internal.create_refresh_token(user, session)
+ next_jti = internal.decode_token(next_refresh_token, 'refresh')['jti']
+ predecessors[next_jti] = jti
+ session.save()
+ return access_token, next_refresh_token