diff --git a/CHANGELOG.md b/CHANGELOG.md index 878cbaf02..5818c19b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1 +1,11 @@ # Changelog for the next release + +## New features + +### OAuth2 provider + +wger can now act as an OAuth2 provider itself, so that other applications can let +their users log in with their wger account and access the API on their behalf. This +is switched off by default unless configured, see the docs for the setup. + +* diff --git a/pyproject.toml b/pyproject.toml index 6dd4ce14a..23d673299 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -31,7 +31,7 @@ dependencies = [ "celery[redis]~=5.6.0", "crispy-bootstrap5~=2026.3", "django-activity-stream~=2.0.0", - "django-allauth[mfa]~=65.19.0", + "django-allauth[mfa,idp-oidc]~=65.19.0", "django-axes[ipware]~=8.3.1", "django-bootstrap-breadcrumbs2==1.0.0", "django-cors-headers~=4.9.0", diff --git a/settings/main.py b/settings/main.py index 6a2d34508..c27204242 100644 --- a/settings/main.py +++ b/settings/main.py @@ -120,6 +120,11 @@ if not DEBUG and not (JWT_PRIVATE_KEY and JWT_PUBLIC_KEY): stacklevel=1, ) +# Signing key for the OAuth2/OIDC provider, in PEM format. Only needed to act as +# an identity provider, so no warning when it is unset. Newlines can be written +# as "\n" in the environment. +IDP_OIDC_PRIVATE_KEY = env.str('IDP_OIDC_PRIVATE_KEY', '', multiline=True) + # Your reCaptcha keys RECAPTCHA_PUBLIC_KEY = env.str('RECAPTCHA_PUBLIC_KEY', '') diff --git a/settings/settings_global.py b/settings/settings_global.py index b4a8d2037..fa13d3dd6 100644 --- a/settings/settings_global.py +++ b/settings/settings_global.py @@ -139,6 +139,9 @@ INSTALLED_APPS = [ 'allauth.socialaccount', # Per-provider apps (allauth.socialaccount.providers.google, ...) are # added conditionally in main.py based on WGER_SOCIAL_PROVIDERS. + + # OAuth2/OIDC provider, used by API clients that log in as the user + 'allauth.idp.oidc', ] MIDDLEWARE = [ @@ -291,6 +294,20 @@ 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 = '' + +# 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): """ @@ -474,6 +491,10 @@ REST_FRAMEWORK = { 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', 'wger.utils.headless_auth.HeadlessJWTAuthentication', + # 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. + 'wger.utils.oidc_auth.OidcTokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ( diff --git a/uv.lock b/uv.lock index 243f5c8c1..7847ce214 100644 --- a/uv.lock +++ b/uv.lock @@ -535,6 +535,10 @@ wheels = [ ] [package.optional-dependencies] +idp-oidc = [ + { name = "oauthlib" }, + { name = "pyjwt", extra = ["crypto"] }, +] mfa = [ { name = "fido2" }, { name = "qrcode" }, @@ -1220,6 +1224,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7b/e5/7cafee2f0413ca4cb0ef3bd111e94d408a48810008b283ad8aee00dd1809/nh3-0.3.6-cp38-abi3-win_arm64.whl", hash = "sha256:69f365963f63a1e9bff53bdbb3c542c7c2efed3e163c9d5d83a772a2ac468c21", size = 603060, upload-time = "2026-06-22T00:47:00.596Z" }, ] +[[package]] +name = "oauthlib" +version = "3.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0b/5f/19930f824ffeb0ad4372da4812c50edbd1434f678c90c2733e1188edfc63/oauthlib-3.3.1.tar.gz", hash = "sha256:0f0f8aa759826a193cf66c12ea1af1637f87b9b4622d46e866952bb022e538c9", size = 185918, upload-time = "2025-06-19T22:48:08.269Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/be/9c/92789c596b8df838baa98fa71844d84283302f7604ed565dafe5a6b5041a/oauthlib-3.3.1-py3-none-any.whl", hash = "sha256:88119c938d2b8fb88561af5f6ee0eec8cc8d552b7bb1f712743136eb7523b7a1", size = 160065, upload-time = "2025-06-19T22:48:06.508Z" }, +] + [[package]] name = "openfoodfacts" version = "5.3.0" @@ -1519,6 +1532,11 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a3/5e/ecf12fdb62546d64385c158514e9b2b671f7832108ef2ecd2020ce0af2d1/pyjwt-2.13.0-py3-none-any.whl", hash = "sha256:66adcc2aff09b3f1bbd95fc1e1577df8ac8723c978552fd43304c8a290ac5728", size = 31274, upload-time = "2026-05-21T19:54:35.362Z" }, ] +[package.optional-dependencies] +crypto = [ + { name = "cryptography" }, +] + [[package]] name = "python-dateutil" version = "2.9.0.post0" @@ -1952,7 +1970,7 @@ dependencies = [ { name = "crispy-bootstrap5" }, { name = "django" }, { name = "django-activity-stream" }, - { name = "django-allauth", extra = ["mfa"] }, + { name = "django-allauth", extra = ["idp-oidc", "mfa"] }, { name = "django-axes", extra = ["ipware"] }, { name = "django-bootstrap-breadcrumbs2" }, { name = "django-cors-headers" }, @@ -2012,7 +2030,7 @@ requires-dist = [ { name = "crispy-bootstrap5", specifier = "~=2026.3" }, { name = "django", specifier = "~=6.0.7" }, { name = "django-activity-stream", specifier = "~=2.0.0" }, - { name = "django-allauth", extras = ["mfa"], specifier = "~=65.19.0" }, + { name = "django-allauth", extras = ["idp-oidc", "mfa"], specifier = "~=65.19.0" }, { name = "django-axes", extras = ["ipware"], specifier = "~=8.3.1" }, { name = "django-bootstrap-breadcrumbs2", specifier = "==1.0.0" }, { name = "django-cors-headers", specifier = "~=4.9.0" }, diff --git a/wger/core/management/commands/generate-oidc-key.py b/wger/core/management/commands/generate-oidc-key.py new file mode 100644 index 000000000..7dac73dc3 --- /dev/null +++ b/wger/core/management/commands/generate-oidc-key.py @@ -0,0 +1,66 @@ +# 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 . + +# Django +from django.core.management.base import BaseCommand + +# Third Party +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa + + +class Command(BaseCommand): + """ + Generates the RS256 signing key for the OAuth2/OIDC provider. + + This key signs the ID tokens and is published as a public key over the + provider's JWKS endpoint. It is only needed when acting as an identity + provider, the rest of the API is unaffected by it. + """ + + help = ( + 'Generate the RS256 signing key for the OAuth2/OIDC provider. The output ' + 'can be pasted into the docker compose env file.' + ) + + def add_arguments(self, parser): + parser.add_argument( + '--key-size', + type=int, + default=2048, + help='RSA key size in bits (default: 2048).', + ) + + def handle(self, *args, **options): + rsa_key = rsa.generate_private_key( + public_exponent=65537, + key_size=options['key_size'], + ) + pem = rsa_key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ).decode() + + self.stdout.write( + self.style.WARNING( + '# Paste this into your environment file (e.g. docker/config/prod.env).\n' + '# Keep it secret, never commit it to a public repo.' + ) + ) + self.stdout.write('') + # A PEM spans several lines, an env value doesn't + escaped_pem = pem.replace('\n', '\\n') + self.stdout.write(f'IDP_OIDC_PRIVATE_KEY={escaped_pem}') diff --git a/wger/core/tasks.py b/wger/core/tasks.py index 875627b0d..fdfeca4ed 100644 --- a/wger/core/tasks.py +++ b/wger/core/tasks.py @@ -52,6 +52,18 @@ def flush_expired_long_lived_sessions_task(): SessionStore.clear_expired() +@app.task +def flush_expired_oidc_tokens_task(): + """ + Delete expired access and refresh tokens of the OAuth2/OIDC provider. + + 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') + + @app.on_after_finalize.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task( @@ -70,3 +82,11 @@ def setup_periodic_tasks(sender, **kwargs): flush_expired_long_lived_sessions_task.s(), name='Flush expired long-lived sessions', ) + sender.add_periodic_task( + crontab( + hour=str(random.randint(0, 23)), + minute=str(random.randint(0, 59)), + ), + flush_expired_oidc_tokens_task.s(), + name='Flush expired OIDC tokens', + ) diff --git a/wger/core/templates/idp/oidc/authorization_form.html b/wger/core/templates/idp/oidc/authorization_form.html new file mode 100644 index 000000000..cfdb410c6 --- /dev/null +++ b/wger/core/templates/idp/oidc/authorization_form.html @@ -0,0 +1,50 @@ +{% extends "template.html" %} +{% load i18n crispy_forms_tags %} + +{% comment %} + Consent screen of the OAuth2 provider. Overrides allauth's own template, + which is styled for its stand-alone entrance layout. +{% endcomment %} + +{% block title %}{% translate "Authorize" %}{% endblock %} + + +{% block header %} +{% endblock %} + + +{% block template %} +
+
+
+
+

{{ client.name }}

+ {# Keep the string on one line, it has to match allauth's catalog #} +

+ {% blocktranslate with client_name=client.name site_name=site.name %}{{ client_name }} wants to access your {{ site_name }} account.{% endblocktranslate %} +

+ +
+ {% csrf_token %} + {{ form|crispy }} + +
+ + +
+
+
+
+
+
+{% endblock %} diff --git a/wger/core/tests/test_oidc_provider.py b/wger/core/tests/test_oidc_provider.py new file mode 100644 index 000000000..a07bfe8ef --- /dev/null +++ b/wger/core/tests/test_oidc_provider.py @@ -0,0 +1,720 @@ +# -*- 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 . + +# Standard Library +import base64 +import hashlib +import re +import secrets +from datetime import timedelta +from io import StringIO +from urllib.parse import ( + parse_qs, + urlparse, +) + +# Django +from django.conf import settings +from django.contrib.auth.models import User +from django.core.management import call_command +from django.test import ( + Client as TestClient, + SimpleTestCase, + override_settings, +) +from django.urls import reverse +from django.utils import timezone +from django.utils.http import urlencode + +# Third Party +import jwt +from allauth.idp.oidc.adapter import get_adapter +from allauth.idp.oidc.models import ( + Client, + Token, +) +from allauth.mfa.totp.internal.auth import ( + TOTP, + format_hotp_value, + generate_totp_secret, + hotp_value, + yield_hotp_counters_from_time, +) +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa + +# wger +from wger.core.tasks import flush_expired_oidc_tokens_task +from wger.core.tests.base_testcase import WgerTestCase +from wger.utils.oidc_auth import ( + SCOPE_READ, + SCOPE_WRITE, +) + + +REDIRECT_URI = 'https://client.example.com/callback' + + +def generate_private_key() -> str: + key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + return key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ).decode() + + +def generate_pkce_pair() -> tuple[str, str]: + """ + Returns a code verifier and its S256 challenge + """ + verifier = secrets.token_urlsafe(96) + digest = hashlib.sha256(verifier.encode('ascii')).digest() + return verifier, base64.urlsafe_b64encode(digest).rstrip(b'=').decode() + + +class GenerateOidcKeyTestCase(SimpleTestCase): + """ + Test the generate-oidc-key management command + """ + + def test_output_is_a_usable_env_value(self): + out = StringIO() + call_command('generate-oidc-key', '--key-size', '1024', stdout=out) + + name, _, value = out.getvalue().splitlines()[-1].partition('=') + self.assertEqual(name, 'IDP_OIDC_PRIVATE_KEY') + self.assertNotIn('\n', value) + + # The escaped newlines are what django-environ turns back into a PEM + pem = value.replace('\\n', '\n') + key = serialization.load_pem_private_key(pem.encode(), password=None) + self.assertEqual(key.key_size, 1024) + + +class OidcProviderTestCase(WgerTestCase): + """ + End-to-end test for the OAuth2/OIDC provider (allauth.idp.oidc) + """ + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.private_key = generate_private_key() + + 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', 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 = f'openid profile {SCOPE_READ}'): + """ + Opens the consent screen, returns its response + """ + query = urlencode( + { + 'client_id': self.oidc_client.id, + 'redirect_uri': REDIRECT_URI, + 'response_type': 'code', + 'scope': scope, + 'state': 'some-state', + 'code_challenge': challenge, + 'code_challenge_method': 'S256', + } + ) + return self.client.get(f'{reverse("idp:oidc:authorization")}?{query}') + + 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 + """ + response = self.request_authorization(challenge, scope) + self.assertEqual(response.status_code, 200) + self.assertTemplateUsed(response, 'idp/oidc/authorization_form.html') + + # allauth's own template renders no action attribute, so this also + # asserts that wger's override is the one being used + self.assertContains(response, f'action="{reverse("idp:oidc:authorization")}"') + + response = self.client.post( + reverse('idp:oidc:authorization'), + { + 'request': response.context['form']['request'].value(), + 'scopes': scope.split(' '), + 'action': 'grant', + }, + ) + self.assertEqual(response.status_code, 302) + self.assertTrue(response['location'].startswith(REDIRECT_URI)) + + params = parse_qs(urlparse(response['location']).query) + 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 + """ + response = self.client.get(reverse('idp:oidc:configuration')) + self.assertEqual(response.status_code, 200) + data = response.json() + self.assertEqual(data['issuer'], 'http://testserver') + self.assertEqual( + data['authorization_endpoint'], + f'http://testserver{reverse("idp:oidc:authorization")}', + ) + self.assertEqual(data['token_endpoint'], f'http://testserver{reverse("idp:oidc:token")}') + self.assertIn('S256', data['code_challenge_methods_supported']) + + # Both need an explicit opt-in + self.assertNotIn('registration_endpoint', data) + self.assertNotIn('introspection_endpoint', data) + + response = self.client.get(reverse('idp:oidc:jwks')) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()['keys'], []) + + def test_jwks_publishes_the_signing_key(self): + response = self.client.get(reverse('idp:oidc:jwks')) + + self.assertEqual(response.status_code, 200) + keys = response.json()['keys'] + self.assertEqual(len(keys), 1) + self.assertEqual(keys[0]['kty'], 'RSA') + self.assertEqual(keys[0]['key_ops'], ['verify']) + self.assertIn('n', keys[0]) + + def redeem_code(self, code: str, **overrides): + """ + Exchanges an authorization code for tokens + """ + payload = { + 'grant_type': 'authorization_code', + 'code': code, + 'client_id': self.oidc_client.id, + 'redirect_uri': REDIRECT_URI, + } + payload.update(overrides) + return self.client.post(reverse('idp:oidc:token'), payload) + + def test_authorization_code_flow(self): + """ + Authorization code flow with PKCE, the access token acts as the user + """ + self.user_login('test') + verifier, challenge = generate_pkce_pair() + + code = self.grant_authorization(challenge) + response = self.redeem_code(code, code_verifier=verifier) + 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'], + key=jwt.PyJWK.from_dict(jwks['keys'][0], algorithm='RS256').key, + algorithms=['RS256'], + audience=self.oidc_client.id, + ) + + self.assertEqual(token['token_type'], 'Bearer') + 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 + # granted it. Log out first, otherwise SessionAuthentication answers. + self.client.logout() + response = self.client.get( + reverse('userprofile-list'), + HTTP_AUTHORIZATION=f'Bearer {token["access_token"]}', + ) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()['username'], 'test') + + def test_code_is_rejected_without_the_verifier(self): + self.user_login('test') + _, challenge = generate_pkce_pair() + + code = self.grant_authorization(challenge) + response = self.redeem_code(code) + + self.assertEqual(response.status_code, 400) + self.assertEqual(response.json()['error'], 'invalid_request') + + def test_code_is_rejected_with_a_wrong_verifier(self): + self.user_login('test') + _, challenge = generate_pkce_pair() + other_verifier, _ = generate_pkce_pair() + + code = self.grant_authorization(challenge) + response = self.redeem_code(code, code_verifier=other_verifier) + + self.assertEqual(response.status_code, 400) + + def test_code_cannot_be_redeemed_twice(self): + self.user_login('test') + verifier, challenge = generate_pkce_pair() + + code = self.grant_authorization(challenge) + self.assertEqual(self.redeem_code(code, code_verifier=verifier).status_code, 200) + response = self.redeem_code(code, code_verifier=verifier) + + self.assertEqual(response.status_code, 400) + + def test_code_is_rejected_for_another_redirect_uri(self): + self.user_login('test') + verifier, challenge = generate_pkce_pair() + + code = self.grant_authorization(challenge) + response = self.redeem_code( + code, + code_verifier=verifier, + redirect_uri='https://attacker.example.com/callback', + ) + + self.assertEqual(response.status_code, 400) + + def test_unknown_redirect_uri_never_redirects(self): + """ + An unregistered redirect URI has to fail on the provider, redirecting to + it would hand the authorization code to whoever asked for it + """ + self.user_login('test') + _, challenge = generate_pkce_pair() + query = urlencode( + { + 'client_id': self.oidc_client.id, + 'redirect_uri': 'https://attacker.example.com/callback', + 'response_type': 'code', + 'scope': SCOPE_READ, + 'code_challenge': challenge, + 'code_challenge_method': 'S256', + } + ) + + response = self.client.get(f'{reverse("idp:oidc:authorization")}?{query}') + + self.assertNotIn('Location', response.headers) + self.assertTemplateUsed(response, 'idp/oidc/error.html') + + def test_client_cannot_request_a_scope_it_has_not_been_given(self): + """ + The error goes back to the registered address, the user sees no consent + """ + self.user_login('test') + self.oidc_client.set_scopes(['openid', SCOPE_READ]) + self.oidc_client.save() + _, challenge = generate_pkce_pair() + + response = self.request_authorization(challenge, scope=f'openid {SCOPE_WRITE}') + + self.assertEqual(response.status_code, 302) + self.assertTrue(response['location'].startswith(REDIRECT_URI)) + params = parse_qs(urlparse(response['location']).query) + 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 + """ + self.user_login('test') + verifier, challenge = generate_pkce_pair() + + response = self.request_authorization(challenge, f'{SCOPE_READ} {SCOPE_WRITE}') + response = self.client.post( + reverse('idp:oidc:authorization'), + { + 'request': response.context['form']['request'].value(), + 'scopes': [SCOPE_READ], + 'action': 'grant', + }, + ) + code = parse_qs(urlparse(response['location']).query)['code'][0] + token = self.redeem_code(code, code_verifier=verifier).json() + + self.assertEqual(token['scope'], SCOPE_READ) + + self.client.logout() + response = self.client.post( + reverse('measurement-category-list'), + data={'name': 'Biceps', 'unit': 'cm'}, + HTTP_AUTHORIZATION=f'Bearer {token["access_token"]}', + ) + self.assertEqual(response.status_code, 403) + + def test_consent_form_carries_a_csrf_token(self): + """ + Without it a third party page could grant itself access in the + background, using the session of a logged-in user + """ + csrf_client = TestClient(enforce_csrf_checks=True) + csrf_client.force_login(User.objects.get(username='test')) + _, challenge = generate_pkce_pair() + query = urlencode( + { + 'client_id': self.oidc_client.id, + 'redirect_uri': REDIRECT_URI, + 'response_type': 'code', + 'scope': SCOPE_READ, + 'code_challenge': challenge, + 'code_challenge_method': 'S256', + } + ) + response = csrf_client.get(f'{reverse("idp:oidc:authorization")}?{query}') + + # Read the token out of the consent form itself, not out of the context + # and not out of some other form on the page, so that this fails if the + # form ever loses its {% csrf_token %} + form = re.search( + rf']*action="{reverse("idp:oidc:authorization")}".*?', + response.content.decode(), + re.DOTALL, + ) + self.assertIsNotNone(form) + match = re.search(r'name="csrfmiddlewaretoken" value="([^"]+)"', form.group()) + self.assertIsNotNone(match) + + response = csrf_client.post( + reverse('idp:oidc:authorization'), + { + 'csrfmiddlewaretoken': match.group(1), + 'request': response.context['form']['request'].value(), + 'scopes': [SCOPE_READ], + 'action': 'grant', + }, + ) + + self.assertEqual(response.status_code, 302) + self.assertIn('code', parse_qs(urlparse(response['location']).query)) + + def test_code_cannot_be_redeemed_by_another_client(self): + self.user_login('test') + other_client = Client(type=Client.Type.PUBLIC, name='Other client') + other_client.set_redirect_uris([REDIRECT_URI]) + other_client.set_scopes([SCOPE_READ]) + other_client.set_grant_types([Client.GrantType.AUTHORIZATION_CODE]) + other_client.set_response_types([Client.ResponseType.CODE]) + other_client.save() + verifier, challenge = generate_pkce_pair() + + code = self.grant_authorization(challenge) + response = self.redeem_code(code, code_verifier=verifier, client_id=other_client.id) + + self.assertEqual(response.status_code, 400) + + def test_client_cannot_use_a_grant_type_it_has_not_been_given(self): + """ + client_credentials would act without any user behind it + """ + response = self.client.post( + reverse('idp:oidc:token'), + { + 'grant_type': 'client_credentials', + 'client_id': self.oidc_client.id, + 'scope': SCOPE_READ, + }, + ) + + self.assertEqual(response.status_code, 401) + self.assertNotIn('access_token', response.json()) + + def test_refresh_token_grant_issues_a_usable_access_token(self): + self.user_login('test') + verifier, challenge = generate_pkce_pair() + code = self.grant_authorization(challenge) + refresh_token = self.redeem_code(code, code_verifier=verifier).json()['refresh_token'] + + response = self.client.post( + reverse('idp:oidc:token'), + { + 'grant_type': 'refresh_token', + 'refresh_token': refresh_token, + 'client_id': self.oidc_client.id, + }, + ) + self.assertEqual(response.status_code, 200, response.content) + + self.client.logout() + self.assertEqual(self.read_profile(response.json()['access_token']).status_code, 200) + + def test_revoked_token_stops_working(self): + self.user_login('test') + verifier, challenge = generate_pkce_pair() + code = self.grant_authorization(challenge) + access_token = self.redeem_code(code, code_verifier=verifier).json()['access_token'] + self.client.logout() + + response = self.client.post( + reverse('idp:oidc:revoke'), + {'token': access_token, 'client_id': self.oidc_client.id}, + ) + self.assertEqual(response.status_code, 200, response.content) + + self.assertEqual(self.read_profile(access_token).status_code, 403) + + def create_access_token( + self, + scopes: list[str], + token_type: str = Token.Type.ACCESS_TOKEN, + expires_in: timedelta = timedelta(hours=1), + ) -> str: + """ + Mints a token directly, without running the whole flow + """ + value = secrets.token_urlsafe(32) + token = Token( + type=token_type, + user=User.objects.get(username='test'), + client=self.oidc_client, + hash=get_adapter().hash_token(value), + expires_at=timezone.now() + expires_in, + ) + token.set_scopes(scopes) + token.save() + return value + + def read_profile(self, token: str): + return self.client.get( + reverse('userprofile-list'), + HTTP_AUTHORIZATION=f'Bearer {token}', + ) + + def test_expired_token_is_rejected(self): + token = self.create_access_token([SCOPE_READ], expires_in=-timedelta(seconds=1)) + + # 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): + """ + Deactivating an account locks it out immediately, not at token expiry + """ + token = self.create_access_token([SCOPE_READ]) + User.objects.filter(username='test').update(is_active=False) + + self.assertEqual(self.read_profile(token).status_code, 403) + + def test_refresh_token_is_not_accepted_as_a_bearer(self): + token = self.create_access_token([SCOPE_READ], token_type=Token.Type.REFRESH_TOKEN) + + self.assertEqual(self.read_profile(token).status_code, 403) + + 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) + + @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 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 ones + """ + user = User.objects.get(username='test') + expired = Token.objects.create( + type=Token.Type.ACCESS_TOKEN, + client=self.oidc_client, + user=user, + hash='expired', + expires_at=timezone.now() - timedelta(days=1), + ) + valid = Token.objects.create( + type=Token.Type.ACCESS_TOKEN, + client=self.oidc_client, + user=user, + hash='valid', + expires_at=timezone.now() + timedelta(days=1), + ) + + flush_expired_oidc_tokens_task() + + self.assertFalse(Token.objects.filter(pk=expired.pk).exists()) + self.assertTrue(Token.objects.filter(pk=valid.pk).exists()) + + def test_cancelled_authorization_issues_no_code(self): + self.user_login('test') + _, challenge = generate_pkce_pair() + + response = self.request_authorization(challenge) + response = self.client.post( + reverse('idp:oidc:authorization'), + {'request': response.context['form']['request'].value()}, + ) + + self.assertEqual(response.status_code, 302) + params = parse_qs(urlparse(response['location']).query) + self.assertEqual(params['error'], ['access_denied']) + self.assertNotIn('code', params) + + def test_consent_is_only_reached_after_passing_mfa(self): + """ + The browser flow runs through the regular login, two-factor included + """ + user = User.objects.get(username='test') + secret = generate_totp_secret() + TOTP.activate(user, secret) + _, challenge = generate_pkce_pair() + + response = self.request_authorization(challenge) + self.assertEqual(response.status_code, 302) + # LOGIN_URL carries no language prefix, posting to it would only yield + # the redirect that adds one + next_url = parse_qs(urlparse(response['location']).query)['next'][0] + + # Username and password alone stop at the second factor + response = self.client.post( + reverse('core:user:login'), + {'login': 'test', 'password': 'testtest', 'next': next_url}, + ) + self.assertEqual(response.status_code, 302) + self.assertTrue(response['location'].startswith(reverse('mfa_authenticate'))) + + counters = list(yield_hotp_counters_from_time()) + code = format_hotp_value(hotp_value(secret, counters[len(counters) // 2])) + response = self.client.post(response['location'], {'code': code}, follow=True) + + self.assertTemplateUsed(response, 'idp/oidc/authorization_form.html') + + def test_anonymous_authorization_redirects_to_login(self): + _, challenge = generate_pkce_pair() + + response = self.request_authorization(challenge) + + self.assertEqual(response.status_code, 302) + self.assertTrue(response['location'].startswith(f'{settings.LOGIN_URL}?next=')) diff --git a/wger/urls.py b/wger/urls.py index cb4cc4487..ecc77251f 100644 --- a/wger/urls.py +++ b/wger/urls.py @@ -47,6 +47,7 @@ from wger.manager.api import views as manager_api_views from wger.measurements.api import views as measurements_api_views from wger.nutrition.api import views as nutrition_api_views from wger.trophies.api import views as trophies_api_views +from wger.utils import oidc_auth from wger.utils.generic_views import TextTemplateView from wger.weight.api import views as weight_api_views @@ -302,6 +303,11 @@ urlpatterns += [ path('account/', include('allauth.urls')), # 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. 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')), # API path( 'api/v2/exercise-submission/', diff --git a/wger/utils/oidc_auth.py b/wger/utils/oidc_auth.py new file mode 100644 index 000000000..338e66a02 --- /dev/null +++ b/wger/utils/oidc_auth.py @@ -0,0 +1,139 @@ +# -*- 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 . + +# Django +from django.conf import settings +from django.http import Http404 +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 allauth.idp.oidc.views import authorization +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'), +} + + +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. + + 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): + # 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 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: + super().populate_server_metadata(data) + 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): + # 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': 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()}, + } + }, + } diff --git a/wger/version.py b/wger/version.py index fa1e7c3f2..4364feaa8 100644 --- a/wger/version.py +++ b/wger/version.py @@ -35,7 +35,7 @@ Always use versions in the x.y.z format, without any suffixes like "beta1" or su MIN_SERVER_VERSION = Version('2.5.0') """Minimum version of the server required to run sync commands on this server""" -VERSION = Version('2.7.0-alpha1') +VERSION = Version('2.7.0-alpha2') """ Current version of the app