Self hosted FLOSS fitness/workout, nutrition and weight tracker
Restrict OIDC access tokens by scope
Roland Geidere7fc803a9719
diff --git a/settings/settings_global.py b/settings/settings_global.pyindex 4b840ce59..1d37de28a 100644--- a/settings/settings_global.py+++ b/settings/settings_global.py@@ -294,6 +294,15 @@ HEADLESS_TOKEN_STRATEGY = 'wger.utils.headless_auth.WgerJWTTokenStrategy'HEADLESS_JWT_ALGORITHM = 'RS256'HEADLESS_JWT_REFRESH_TOKEN_EXPIRES_IN = 120 * 24 * 3600+#+# allauth.idp.oidc — OAuth2/OIDC provider+#+IDP_OIDC_ADAPTER = 'wger.utils.oidc_auth.WgerOIDCAdapter'++# Empty means the provider is switched off, installations that want to act as+# one set it themselves (see settings/main.py)+IDP_OIDC_PRIVATE_KEY = ''+def jwk_b64_to_pem(b64_jwk_str: str):"""@@ -480,7 +489,7 @@ REST_FRAMEWORK = {# Also uses Bearer, but with opaque tokens, so it has to run before# simplejwt, which raises instead of passing the token on. Placed after# the headless class so app requests don't pay for the token lookup.- 'allauth.idp.oidc.contrib.rest_framework.authentication.TokenAuthentication',+ 'wger.utils.oidc_auth.OidcTokenAuthentication','rest_framework_simplejwt.authentication.JWTAuthentication',),'DEFAULT_FILTER_BACKENDS': (diff --git a/wger/core/tests/test_oidc_provider.py b/wger/core/tests/test_oidc_provider.pyindex 3b0df69d6..8786f2c92 100644--- a/wger/core/tests/test_oidc_provider.py+++ b/wger/core/tests/test_oidc_provider.py@@ -40,6 +40,7 @@ from django.utils.http import urlencode# Third Partyimport jwt+from allauth.idp.oidc.adapter import get_adapterfrom allauth.idp.oidc.models import (Client,Token,@@ -50,6 +51,10 @@ from cryptography.hazmat.primitives.asymmetric import rsa# wgerfrom wger.core.tasks import flush_expired_oidc_tokens_taskfrom wger.core.tests.base_testcase import WgerTestCase+from wger.utils.oidc_auth import (+ SCOPE_READ,+ SCOPE_WRITE,+)REDIRECT_URI = 'https://client.example.com/callback'@@ -104,16 +109,18 @@ class OidcProviderTestCase(WgerTestCase):def setUp(self):super().setUp()+ self.enterContext(override_settings(IDP_OIDC_PRIVATE_KEY=self.private_key))+self.oidc_client = Client(type=Client.Type.PUBLIC, name='Test client')self.oidc_client.set_redirect_uris([REDIRECT_URI])- self.oidc_client.set_scopes(['openid', 'profile', 'email'])+ self.oidc_client.set_scopes(['openid', 'profile', 'email', SCOPE_READ, SCOPE_WRITE])self.oidc_client.set_grant_types([Client.GrantType.AUTHORIZATION_CODE, Client.GrantType.REFRESH_TOKEN])self.oidc_client.set_response_types([Client.ResponseType.CODE])self.oidc_client.save()- def request_authorization(self, challenge: str, scope: str = 'openid profile'):+ def request_authorization(self, challenge: str, scope: str = f'openid profile {SCOPE_READ}'):"""Opens the consent screen, returns its response"""@@ -130,7 +137,9 @@ class OidcProviderTestCase(WgerTestCase):)return self.client.get(f'{reverse("idp:oidc:authorization")}?{query}')- def grant_authorization(self, challenge: str, scope: str = 'openid profile') -> str:+ def grant_authorization(+ self, challenge: str, scope: str = f'openid profile {SCOPE_READ}'+ ) -> str:"""Runs the browser part of the flow, returns the authorization code"""@@ -157,6 +166,7 @@ class OidcProviderTestCase(WgerTestCase):self.assertEqual(params['state'][0], 'some-state')return params['code'][0]+ @override_settings(IDP_OIDC_PRIVATE_KEY='')def test_discovery_without_signing_key(self):"""Discovery answers without a signing key configured, the key set is empty@@ -181,8 +191,7 @@ class OidcProviderTestCase(WgerTestCase):self.assertEqual(response.json()['keys'], [])def test_jwks_publishes_the_signing_key(self):- with override_settings(IDP_OIDC_PRIVATE_KEY=self.private_key):- response = self.client.get(reverse('idp:oidc:jwks'))+ response = self.client.get(reverse('idp:oidc:jwks'))self.assertEqual(response.status_code, 200)keys = response.json()['keys']@@ -198,30 +207,28 @@ class OidcProviderTestCase(WgerTestCase):self.user_login('test')verifier, challenge = generate_pkce_pair()- with override_settings(IDP_OIDC_PRIVATE_KEY=self.private_key):- code = self.grant_authorization(challenge)-- response = self.client.post(- reverse('idp:oidc:token'),- {- 'grant_type': 'authorization_code',- 'code': code,- 'client_id': self.oidc_client.id,- 'redirect_uri': REDIRECT_URI,- 'code_verifier': verifier,- },- )- self.assertEqual(response.status_code, 200, response.content)- token = response.json()-- id_token = jwt.decode(- token['id_token'],- options={'verify_signature': False},- audience=self.oidc_client.id,- )+ code = self.grant_authorization(challenge)+ response = self.client.post(+ reverse('idp:oidc:token'),+ {+ 'grant_type': 'authorization_code',+ 'code': code,+ 'client_id': self.oidc_client.id,+ 'redirect_uri': REDIRECT_URI,+ 'code_verifier': verifier,+ },+ )+ self.assertEqual(response.status_code, 200, response.content)+ token = response.json()++ id_token = jwt.decode(+ token['id_token'],+ options={'verify_signature': False},+ audience=self.oidc_client.id,+ )self.assertEqual(token['token_type'], 'Bearer')- self.assertEqual(token['scope'], 'openid profile')+ self.assertEqual(token['scope'], f'openid profile {SCOPE_READ}')self.assertEqual(id_token['preferred_username'], 'test')# The access token authenticates a regular API request as the user that@@ -238,21 +245,104 @@ class OidcProviderTestCase(WgerTestCase):self.user_login('test')_, challenge = generate_pkce_pair()- with override_settings(IDP_OIDC_PRIVATE_KEY=self.private_key):- code = self.grant_authorization(challenge)- response = self.client.post(- reverse('idp:oidc:token'),- {- 'grant_type': 'authorization_code',- 'code': code,- 'client_id': self.oidc_client.id,- 'redirect_uri': REDIRECT_URI,- },- )+ code = self.grant_authorization(challenge)+ response = self.client.post(+ reverse('idp:oidc:token'),+ {+ 'grant_type': 'authorization_code',+ 'code': code,+ 'client_id': self.oidc_client.id,+ 'redirect_uri': REDIRECT_URI,+ },+ )self.assertEqual(response.status_code, 400)self.assertEqual(response.json()['error'], 'invalid_request')+ def create_access_token(self, scopes: list[str]) -> str:+ """+ Mints an access token directly, without running the whole flow+ """+ value = secrets.token_urlsafe(32)+ token = Token(+ type=Token.Type.ACCESS_TOKEN,+ user=User.objects.get(username='test'),+ client=self.oidc_client,+ hash=get_adapter().hash_token(value),+ expires_at=timezone.now() + timedelta(hours=1),+ )+ token.set_scopes(scopes)+ token.save()+ return value++ def test_read_scope_allows_reading(self):+ token = self.create_access_token([SCOPE_READ])++ response = self.client.get(+ reverse('userprofile-list'),+ HTTP_AUTHORIZATION=f'Bearer {token}',+ )++ self.assertEqual(response.status_code, 200)++ def test_read_scope_does_not_allow_writing(self):+ token = self.create_access_token([SCOPE_READ])++ response = self.client.post(+ reverse('measurement-category-list'),+ data={'name': 'Biceps', 'unit': 'cm'},+ HTTP_AUTHORIZATION=f'Bearer {token}',+ )++ self.assertEqual(response.status_code, 403)+ self.assertIn(SCOPE_WRITE, response.json()['detail'])++ def test_write_scope_allows_writing(self):+ token = self.create_access_token([SCOPE_READ, SCOPE_WRITE])++ response = self.client.post(+ reverse('measurement-category-list'),+ data={'name': 'Biceps', 'unit': 'cm'},+ HTTP_AUTHORIZATION=f'Bearer {token}',+ )++ self.assertEqual(response.status_code, 201)++ @override_settings(IDP_OIDC_PRIVATE_KEY='')+ def test_tokens_stop_working_without_a_signing_key(self):+ """+ No key means the provider is off, tokens it handed out are not accepted+ """+ token = self.create_access_token([SCOPE_READ])++ response = self.client.get(+ reverse('userprofile-list'),+ HTTP_AUTHORIZATION=f'Bearer {token}',+ )++ self.assertEqual(response.status_code, 403)++ def test_identity_scopes_alone_grant_no_api_access(self):+ """+ openid and friends identify the user, they don't open the API+ """+ token = self.create_access_token(['openid', 'profile', 'email'])++ response = self.client.get(+ reverse('userprofile-list'),+ HTTP_AUTHORIZATION=f'Bearer {token}',+ )++ self.assertEqual(response.status_code, 403)++ def test_scopes_are_advertised(self):+ response = self.client.get(reverse('idp:oidc:configuration'))++ self.assertEqual(+ response.json()['scopes_supported'],+ [SCOPE_READ, SCOPE_WRITE, 'email', 'openid', 'profile'],+ )+def test_flush_expired_oidc_tokens_task(self):"""The periodic cleanup task deletes expired tokens and keeps valid onesdiff --git a/wger/utils/api_schema.py b/wger/utils/api_schema.pyindex 08e99b3b0..61cda7e07 100644--- a/wger/utils/api_schema.py+++ b/wger/utils/api_schema.py@@ -12,43 +12,10 @@## You should have received a copy of the GNU Affero General Public License-# Django-from django.urls import reverse-# Third Party-from drf_spectacular.extensions import OpenApiAuthenticationExtensionfrom rest_framework import serializers-class OidcTokenScheme(OpenApiAuthenticationExtension):- """- Schema entry for allauth's OIDC access tokens.-- Without this, drf-spectacular can't resolve the authentication class and- leaves the endpoints without the security scheme.- """-- target_class = 'allauth.idp.oidc.contrib.rest_framework.authentication.TokenAuthentication'- name = 'oidcAuth'-- def get_security_definition(self, auto_schema):- return {- 'type': 'oauth2',- 'description': 'Access token issued by the OAuth2/OIDC provider',- 'flows': {- 'authorizationCode': {- 'authorizationUrl': reverse('idp:oidc:authorization'),- 'tokenUrl': reverse('idp:oidc:token'),- 'scopes': {- 'openid': 'Identify the account',- 'profile': 'Read the username',- 'email': 'Read the email address',- },- }- },- }--class ThumbnailsSerializer(serializers.Serializer):"""Shape of the ``thumbnails`` field, used for schema generation only.diff --git a/wger/utils/oidc_auth.py b/wger/utils/oidc_auth.pynew file mode 100644index 000000000..e7970b78d--- /dev/null+++ b/wger/utils/oidc_auth.py@@ -0,0 +1,112 @@+# -*- coding: utf-8 -*-++# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.++# Django+from django.conf import settings+from django.urls import reverse+from django.utils.translation import gettext_lazy as _++# Third Party+from allauth.idp.oidc.adapter import DefaultOIDCAdapter+from allauth.idp.oidc.contrib.rest_framework.authentication import TokenAuthentication+from drf_spectacular.extensions import OpenApiAuthenticationExtension+from rest_framework.exceptions import PermissionDenied+from rest_framework.permissions import SAFE_METHODS+++SCOPE_READ = 'api:read'+SCOPE_WRITE = 'api:write'++API_SCOPES = {+ SCOPE_READ: _('View your training, nutrition and body data'),+ SCOPE_WRITE: _('Add and change your training, nutrition and body data'),+}+++class OidcTokenAuthentication(TokenAuthentication):+ """+ Access tokens of the OAuth2/OIDC provider, restricted by scope.++ The check happens here and not in a permission class because a good two+ dozen viewsets set ``permission_classes`` themselves and would silently+ skip a default one. Reads need ``api:read``, everything else ``api:write``,+ so no endpoint can be forgotten and new ones are covered as they are added.+ """++ 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)):+ return None++ result = super().authenticate(request)+ if result is None:+ return None++ user, token = result+ scope = SCOPE_READ if request.method in SAFE_METHODS else SCOPE_WRITE+ if token is None or scope not in token.get_scopes():+ raise PermissionDenied(+ f'The access token is missing the "{scope}" scope.',+ code='insufficient_scope',+ )++ return user, token+++class WgerOIDCAdapter(DefaultOIDCAdapter):+ """+ Teaches allauth about the API scopes.++ ``scope_display`` provides the labels on the consent screen, without it the+ users are asked to grant a raw "api:write". The metadata hook adds them to+ the discovery document, which only knows the identity scopes.+ """++ scope_display = {+ **DefaultOIDCAdapter.scope_display,+ **API_SCOPES,+ }++ def populate_server_metadata(self, data: dict) -> None:+ data['scopes_supported'] = sorted({*data['scopes_supported'], *API_SCOPES})+++class OidcTokenScheme(OpenApiAuthenticationExtension):+ """+ Schema entry for the OIDC access tokens.++ Without this, drf-spectacular can't resolve the authentication class and+ leaves the endpoints without the security scheme.+ """++ target_class = 'wger.utils.oidc_auth.OidcTokenAuthentication'+ name = 'oidcAuth'++ def get_security_definition(self, auto_schema):+ return {+ 'type': 'oauth2',+ 'description': 'Access token issued by the OAuth2/OIDC provider',+ 'flows': {+ 'authorizationCode': {+ 'authorizationUrl': reverse('idp:oidc:authorization'),+ 'tokenUrl': reverse('idp:oidc:token'),+ 'scopes': {str(name): str(label) for name, label in API_SCOPES.items()},+ }+ },+ }