Self hosted FLOSS fitness/workout, nutrition and weight tracker
Harden the OAuth2 provider
Roland Geider5c3969f4f666
diff --git a/settings/settings_global.py b/settings/settings_global.pyindex 1d37de28a..fa13d3dd6 100644--- a/settings/settings_global.py+++ b/settings/settings_global.py@@ -303,6 +303,11 @@ IDP_OIDC_ADAPTER = 'wger.utils.oidc_auth.WgerOIDCAdapter'# one set it themselves (see settings/main.py)IDP_OIDC_PRIVATE_KEY = ''+# Without this refresh tokens never expire, and since only tokens with an expiry+# are cleaned up, abandoned grants would pile up forever. Same lifetime as the+# tokens the app gets.+IDP_OIDC_REFRESH_TOKEN_EXPIRES_IN = HEADLESS_JWT_REFRESH_TOKEN_EXPIRES_IN+def jwk_b64_to_pem(b64_jwk_str: str):"""diff --git a/wger/core/tasks.py b/wger/core/tasks.pyindex 306fcc7c7..fdfeca4ed 100644--- a/wger/core/tasks.py+++ b/wger/core/tasks.py@@ -57,8 +57,9 @@ def flush_expired_oidc_tokens_task():"""Delete expired access and refresh tokens of the OAuth2/OIDC provider.- Tokens stay in the table after they expire, so without this the table- grows for as long as applications keep refreshing.+ Rotation already drops the previous refresh token on every refresh, what+ stays behind are abandoned grants: tokens of applications that a user+ connected once and never used again."""call_command('oidc_cleartokens')diff --git a/wger/core/tests/test_oidc_provider.py b/wger/core/tests/test_oidc_provider.pyindex 951ddab58..a07bfe8ef 100644--- a/wger/core/tests/test_oidc_provider.py+++ b/wger/core/tests/test_oidc_provider.py@@ -234,9 +234,13 @@ class OidcProviderTestCase(WgerTestCase):self.assertEqual(response.status_code, 200, response.content)token = response.json()+ # Verified against the published key set, a mismatch between the two+ # would break every relying party+ jwks = self.client.get(reverse('idp:oidc:jwks')).json()id_token = jwt.decode(token['id_token'],- options={'verify_signature': False},+ key=jwt.PyJWK.from_dict(jwks['keys'][0], algorithm='RS256').key,+ algorithms=['RS256'],audience=self.oidc_client.id,)@@ -337,6 +341,27 @@ class OidcProviderTestCase(WgerTestCase):self.assertEqual(params['error'], ['invalid_scope'])self.assertNotIn('code', params)+ def test_consent_cannot_grant_more_than_was_asked_for(self):+ """+ A tampered consent post cannot widen the scopes beyond the request+ """+ self.user_login('test')+ _, challenge = generate_pkce_pair()++ response = self.request_authorization(challenge, SCOPE_READ)+ response = self.client.post(+ reverse('idp:oidc:authorization'),+ {+ 'request': response.context['form']['request'].value(),+ 'scopes': [SCOPE_READ, SCOPE_WRITE],+ 'action': 'grant',+ },+ )++ self.assertEqual(response.status_code, 200)+ self.assertIn('scopes', response.context['form'].errors)+ self.assertFalse(Token.objects.exists())+def test_user_can_grant_less_than_the_application_asked_for(self):"""Unchecking a permission on the consent screen limits the token@@ -506,7 +531,22 @@ class OidcProviderTestCase(WgerTestCase):def test_expired_token_is_rejected(self):token = self.create_access_token([SCOPE_READ], expires_in=-timedelta(seconds=1))- self.assertEqual(self.read_profile(token).status_code, 403)+ # The chain falls through to simplejwt, which answers, and+ # SessionAuthentication turns DRF's 401 into a 403+ self.assertIn(self.read_profile(token).status_code, (401, 403))++ def test_refresh_tokens_expire(self):+ """+ Only tokens with an expiry are ever cleaned up+ """+ self.user_login('test')+ verifier, challenge = generate_pkce_pair()+ code = self.grant_authorization(challenge)+ self.redeem_code(code, code_verifier=verifier)++ refresh_token = Token.objects.get(type=Token.Type.REFRESH_TOKEN)++ self.assertIsNotNone(refresh_token.expires_at)def test_token_of_a_deactivated_user_is_rejected(self):"""@@ -569,6 +609,18 @@ class OidcProviderTestCase(WgerTestCase):self.assertEqual(response.status_code, 403)+ @override_settings(IDP_OIDC_PRIVATE_KEY='')+ def test_the_flow_does_not_start_without_a_signing_key(self):+ """+ Otherwise users would consent to something that cannot be completed+ """+ self.user_login('test')+ _, challenge = generate_pkce_pair()++ response = self.request_authorization(challenge)++ self.assertEqual(response.status_code, 404)+def test_identity_scopes_alone_grant_no_api_access(self):"""openid and friends identify the user, they don't open the APIdiff --git a/wger/urls.py b/wger/urls.pyindex 1fc884c55..ecc77251f 100644--- a/wger/urls.py+++ b/wger/urls.py@@ -47,6 +47,7 @@ from wger.manager.api import views as manager_api_viewsfrom wger.measurements.api import views as measurements_api_viewsfrom wger.nutrition.api import views as nutrition_api_viewsfrom wger.trophies.api import views as trophies_api_views+from wger.utils import oidc_authfrom wger.utils.generic_views import TextTemplateViewfrom wger.weight.api import views as weight_api_views@@ -303,7 +304,9 @@ urlpatterns += [# REST auth API consumed by the Flutter app.path('allauth/', include('allauth.headless.urls')),# OAuth2/OIDC provider. Mounted at the root, the paths (/.well-known/... and- # /identity/o/...) are part of the include.+ # /identity/o/...) are part of the include. The authorization endpoint is+ # wrapped to keep the flow from starting when the provider isn't configured.+ path('identity/o/authorize', oidc_auth.authorization_view, name='oidc-authorize'),path('', include('allauth.idp.urls')),# APIpath(diff --git a/wger/utils/oidc_auth.py b/wger/utils/oidc_auth.pyindex e7970b78d..338e66a02 100644--- a/wger/utils/oidc_auth.py+++ b/wger/utils/oidc_auth.py@@ -17,12 +17,14 @@# Djangofrom django.conf import settings+from django.http import Http404from django.urls import reversefrom django.utils.translation import gettext_lazy as _# Third Partyfrom allauth.idp.oidc.adapter import DefaultOIDCAdapterfrom allauth.idp.oidc.contrib.rest_framework.authentication import TokenAuthentication+from allauth.idp.oidc.views import authorizationfrom drf_spectacular.extensions import OpenApiAuthenticationExtensionfrom rest_framework.exceptions import PermissionDeniedfrom rest_framework.permissions import SAFE_METHODS@@ -37,6 +39,27 @@ API_SCOPES = {}+def is_provider_configured() -> bool:+ """+ Whether this installation acts as an OAuth2/OIDC provider+ """+ return bool(settings.IDP_OIDC_PRIVATE_KEY or getattr(settings, 'IDP_OIDC_PRIVATE_KEYS', None))+++def authorization_view(request, *args, **kwargs):+ """+ allauth's authorization view, but only if the provider is set up.++ Without a signing key the flow would run all the way through the consent+ screen and only fail afterwards, when the token endpoint tries to sign an+ ID token. Users would grant access to something that cannot work.+ """+ if not is_provider_configured():+ raise Http404('The OAuth2 provider is not configured')++ return authorization(request, *args, **kwargs)++class OidcTokenAuthentication(TokenAuthentication):"""Access tokens of the OAuth2/OIDC provider, restricted by scope.@@ -48,10 +71,10 @@ class OidcTokenAuthentication(TokenAuthentication):"""def authenticate(self, request):- # Without a signing key the provider is switched off. Checked first so- # that installations not using it don't pay for the token lookup, which- # every request with a bearer token would otherwise trigger.- if not (settings.IDP_OIDC_PRIVATE_KEY or getattr(settings, 'IDP_OIDC_PRIVATE_KEYS', None)):+ # Checked first so that installations without the provider don't pay for+ # the token lookup, which every request with a bearer token would+ # otherwise trigger.+ if not is_provider_configured():return Noneresult = super().authenticate(request)@@ -84,6 +107,7 @@ class WgerOIDCAdapter(DefaultOIDCAdapter):}def populate_server_metadata(self, data: dict) -> None:+ super().populate_server_metadata(data)data['scopes_supported'] = sorted({*data['scopes_supported'], *API_SCOPES})@@ -99,13 +123,16 @@ class OidcTokenScheme(OpenApiAuthenticationExtension):name = 'oidcAuth'def get_security_definition(self, auto_schema):+ # OpenAPI 3.0 wants absolute URLs here, a relative path makes code+ # generators build a broken one+ site = settings.SITE_URL.rstrip('/')return {'type': 'oauth2','description': 'Access token issued by the OAuth2/OIDC provider','flows': {'authorizationCode': {- 'authorizationUrl': reverse('idp:oidc:authorization'),- 'tokenUrl': reverse('idp:oidc:token'),+ 'authorizationUrl': f'{site}{reverse("idp:oidc:authorization")}',+ 'tokenUrl': f'{site}{reverse("idp:oidc:token")}','scopes': {str(name): str(label) for name, label in API_SCOPES.items()},}},