Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Harden the jwt token strategy against None-Users

Roland Geider3dc83e175912
diff --git a/settings/settings_global.py b/settings/settings_global.py
index c922d4242..cd508d969 100644
--- a/settings/settings_global.py
+++ b/settings/settings_global.py
@@ -283,7 +283,7 @@ SOCIALACCOUNT_QUERY_EMAIL = True
# 'app' client is enabled.
#
HEADLESS_CLIENTS = ('app',)
-HEADLESS_TOKEN_STRATEGY = 'allauth.headless.tokens.strategies.jwt.strategy.JWTTokenStrategy'
+HEADLESS_TOKEN_STRATEGY = 'wger.utils.headless_auth.WgerJWTTokenStrategy'
HEADLESS_JWT_ALGORITHM = 'RS256'
HEADLESS_JWT_REFRESH_TOKEN_EXPIRES_IN = 120 * 24 * 3600
diff --git a/wger/core/tests/test_apikey.py b/wger/core/tests/test_apikey.py
index 7e650920c..6c2e4ed04 100644
--- a/wger/core/tests/test_apikey.py
+++ b/wger/core/tests/test_apikey.py
@@ -274,6 +274,29 @@ class LongLivedRefreshTokenTestCase(WgerTestCase):
body = response.json()
self.assertIn('access_token', body['data'])
+ def test_refresh_for_session_without_user_is_rejected(self):
+ """
+ A refresh token whose session no longer resolves to a user (here: a
+ password change rotates the session auth hash) is rejected with a 4xx
+ instead of raising a 500.
+ """
+ self.user_login('test')
+ user = User.objects.get(username='test')
+
+ token = mint_long_lived_refresh_token(user, lifetime_seconds=120 * 86400)
+
+ user.set_password('a-different-password')
+ user.save()
+
+ api = APIClient()
+ response = api.post(
+ reverse('headless:app:tokens:refresh'),
+ data=json.dumps({'refresh_token': token}),
+ content_type='application/json',
+ )
+ self.assertGreaterEqual(response.status_code, 400)
+ self.assertLess(response.status_code, 500)
+
@override_settings(SESSION_ENGINE='django.contrib.sessions.backends.cached_db')
def test_refresh_works_under_cache_backed_engine(self):
"""
diff --git a/wger/utils/headless_auth.py b/wger/utils/headless_auth.py
index cf74ee6f3..93c549aad 100644
--- a/wger/utils/headless_auth.py
+++ b/wger/utils/headless_auth.py
@@ -17,6 +17,8 @@
# Third Party
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
from rest_framework.exceptions import AuthenticationFailed
@@ -35,3 +37,25 @@ class HeadlessJWTAuthentication(JWTTokenAuthentication):
return super().authenticate(request)
except AuthenticationFailed:
return None
+
+
+class WgerJWTTokenStrategy(JWTTokenStrategy):
+ """
+ Hardened variant of allauth's JWTTokenStrategy.
+
+ ``internal.validate_refresh_token`` returns a ``(None, session, payload)``
+ tuple when the refresh token and its backing session are valid but the
+ session no longer resolves to a user, e.g. after a password change rotates
+ the session auth hash, or the user was deleted/deactivated.
+
+ Allauth's ``refresh_token`` logic hands the None-User to ``create_access_token``,
+ 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.
+ """
+
+ 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)