From cca4004f10224c7fba19014b5f1b08c6d16f4fe3 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 11 Aug 2026 00:23:35 +0200 Subject: [PATCH 1/9] Start adding an OAuth2/OIDC provider via allauth.idp.oidc --- pyproject.toml | 2 +- settings/settings_global.py | 7 + uv.lock | 47 ++++- wger/core/tests/test_oidc_provider.py | 242 ++++++++++++++++++++++++++ wger/urls.py | 3 + wger/utils/api_schema.py | 33 ++++ 6 files changed, 331 insertions(+), 3 deletions(-) create mode 100644 wger/core/tests/test_oidc_provider.py diff --git a/pyproject.toml b/pyproject.toml index d9f1b5852..1759bbd46 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -32,7 +32,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/settings_global.py b/settings/settings_global.py index b4a8d2037..4b840ce59 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 = [ @@ -474,6 +477,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. + 'allauth.idp.oidc.contrib.rest_framework.authentication.TokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ( diff --git a/uv.lock b/uv.lock index 20e8dc6fe..9a4e98eae 100644 --- a/uv.lock +++ b/uv.lock @@ -531,6 +531,10 @@ wheels = [ ] [package.optional-dependencies] +idp-oidc = [ + { name = "oauthlib" }, + { name = "pyjwt", extra = ["crypto"] }, +] mfa = [ { name = "fido2" }, { name = "qrcode" }, @@ -868,17 +872,42 @@ dependencies = [ { name = "zope-event" }, { name = "zope-interface" }, ] +sdist = { url = "https://files.pythonhosted.org/packages/b8/eb/5f2db8013f1a4a6df2c23201f384a066f13ff5764a9f62a608c8a50ac8cc/gevent-26.8.0.tar.gz", hash = "sha256:96039f41bbde6dcd72559e5ffbd408a04f46774b47d991d4cf032da8fa79e5a0", size = 6625998, upload-time = "2026-08-10T18:02:28.038Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/56/94/a5d38541f3a9fd77aa8defe8bb66698176be959cebda9c2be00fc5ad9e63/gevent-26.8.0-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:94544a0f5a1d14b711cd630eab0581a53f3ea89370f8963df9ced62ec6552ca9", size = 2968165, upload-time = "2026-08-10T16:56:19.816Z" }, + { url = "https://files.pythonhosted.org/packages/14/99/b82608b486cd9f79a4ebb480779900e7bb7dc095dc9217991fdb173b0084/gevent-26.8.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:108614bd47ec714ed93d141965bac8c17e44bbae08e238696da6261f013caa83", size = 1811374, upload-time = "2026-08-10T17:58:49.637Z" }, + { url = "https://files.pythonhosted.org/packages/ae/9b/cfbc57b758d0435889be2726a5ae1570e6563a24976f4b62e5ecf81b3c3d/gevent-26.8.0-cp312-cp312-manylinux_2_28_ppc64le.whl", hash = "sha256:102087dab60f43f52be74e4be7e42345de27d1968707ded31c785e91d41978b1", size = 1911009, upload-time = "2026-08-10T17:48:09.222Z" }, + { url = "https://files.pythonhosted.org/packages/c7/2a/82ab6a41a064792e3df4a9c03e1e90ccf622f8f3352d9a22c1e03e2f159e/gevent-26.8.0-cp312-cp312-manylinux_2_28_s390x.whl", hash = "sha256:c2730709f8e894c167415e1d3752d63e6ed40f28b60bdb2ba7bdf973fa29296a", size = 1858831, upload-time = "2026-08-10T17:54:27.214Z" }, + { url = "https://files.pythonhosted.org/packages/4f/f4/a49ac5d1b508dfcc9af2d08435d9c2c71fdc12d44fe75156c6441f6127de/gevent-26.8.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:8e2be34e41557387a422e78c0124e2b90a4df9f1cc87c891503bf34a95ae1ce5", size = 2143187, upload-time = "2026-08-10T17:19:21.507Z" }, + { url = "https://files.pythonhosted.org/packages/05/59/967712d5cbabb82fb0619914b82266d0150322966376430df4c73dfbfda4/gevent-26.8.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:946848924dd80d29184367c0c9a4fc809411d17afbe157128687df8d7d838560", size = 1824469, upload-time = "2026-08-10T17:42:38.125Z" }, + { url = "https://files.pythonhosted.org/packages/6d/16/f06ee39db14422d5f749cdcfeb7b8a7b426e087dace9d2c8675633fe6eb4/gevent-26.8.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2d2c9c23cf68e2d4565505f8b5cd31b269259e1fbfb57bcc3d4d1cd34ee274d1", size = 2170288, upload-time = "2026-08-10T17:23:49.646Z" }, { url = "https://files.pythonhosted.org/packages/1e/ef/783f68a240e17d95badc39087af62e2e4394f1e0fe24776d8bd8267d0877/gevent-26.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:f3f47e7a0c8e73a3c43072fdd997f6cf1e4d1623c43d619185aea9f8037f89ab", size = 1695386, upload-time = "2026-08-10T17:03:06.831Z" }, { url = "https://files.pythonhosted.org/packages/1a/d1/6bcb527be3fcf942d58e5f2f76730af391a01c762218285e9505bba07b05/gevent-26.8.0-cp312-cp312-win_arm64.whl", hash = "sha256:67bd80acf2f715ec1e197faff68241dea9499916ffe3783b24c70a1747c99e9c", size = 1568205, upload-time = "2026-08-10T16:59:16.35Z" }, { url = "https://files.pythonhosted.org/packages/36/b2/6fb10373605926a5cb65fedd11e3be2595889fa19c3c29587644271ffd4c/gevent-26.8.0-cp313-cp313-macosx_11_0_universal2.whl", hash = "sha256:8dde9ed35e3b8bc2c25dfa11c2c770ac526642bda6dc3b25ee7990224de58c90", size = 2990229, upload-time = "2026-08-10T16:57:16.417Z" }, + { url = "https://files.pythonhosted.org/packages/3a/dc/36355bb730c1390ddd235c5f5a216e8a282dde6bd224065ce5ea83193f71/gevent-26.8.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:7562e4ec86cbb89e457eac78aaceb0266459c24b033b6946322463f121d801e8", size = 1812656, upload-time = "2026-08-10T17:58:50.884Z" }, + { url = "https://files.pythonhosted.org/packages/af/5c/0d17c59b3d2ca04fa0841454bf57c31891056233885a433e137e423cadd6/gevent-26.8.0-cp313-cp313-manylinux_2_28_ppc64le.whl", hash = "sha256:e8bc413b9bcf7cd851b34b0f58608171f7e4ac76246175eebc15be1a3119f705", size = 1911448, upload-time = "2026-08-10T17:48:11.129Z" }, + { url = "https://files.pythonhosted.org/packages/78/fb/850ec40b05b0e63e4888403ebb5a8c7ba04402731fbd6a7604129f85fe65/gevent-26.8.0-cp313-cp313-manylinux_2_28_s390x.whl", hash = "sha256:4b89f12461c5aa0c7d98bebf9403db0bb6a7ff2f599420145a64c20f49fe1038", size = 1861150, upload-time = "2026-08-10T17:54:28.717Z" }, + { url = "https://files.pythonhosted.org/packages/ff/62/dfe2b89f28b7e4d99165d7b3fd239eac813dc5c03b6c06c7e58c5aaceda2/gevent-26.8.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:7644970428fcc32011ac562b5e6b646a505296a109165e2bc16f8b825ab4a809", size = 2141003, upload-time = "2026-08-10T17:19:22.988Z" }, + { url = "https://files.pythonhosted.org/packages/c9/3d/1afa2c2503ce9470b33c23098722c5082e47f22efd4464fcc1ff8cc0e2e2/gevent-26.8.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e403966ca6a3f556579f0a54eabd06ad6cc5b98d66488bc9d97a34989ad8c480", size = 1825210, upload-time = "2026-08-10T17:42:39.604Z" }, + { url = "https://files.pythonhosted.org/packages/d2/7f/804723cc1b0ba7407c7abb9dc0d06d9cd9283f67ab22b8375cd348eb21ae/gevent-26.8.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1494690813f476eca534ec8eca0a470013910279e6c019ccdad2ed543db391dd", size = 2167610, upload-time = "2026-08-10T17:23:51.043Z" }, { url = "https://files.pythonhosted.org/packages/70/a1/474a9f5401a79ec6f5595c31f126f2fc00377b55596e39d5e623311f6364/gevent-26.8.0-cp313-cp313-win_amd64.whl", hash = "sha256:9fd575d0091074028512437e08b77d05e265619b18becb22f87a827274262a12", size = 1692381, upload-time = "2026-08-10T16:59:07.205Z" }, { url = "https://files.pythonhosted.org/packages/92/3e/6dbbcadfd2b45e996636f0e72ec59891c4788d05c6300851687b91f5d977/gevent-26.8.0-cp313-cp313-win_arm64.whl", hash = "sha256:097c9ed26102f62dc1e7d974274752ce462b98ad01ac55d7b1044fcba3429a86", size = 1565147, upload-time = "2026-08-10T16:59:29.395Z" }, { url = "https://files.pythonhosted.org/packages/61/cb/1bed6675f6cba42bfe23c38eacf482e08dfaa7af251cb0cddfcbb084b757/gevent-26.8.0-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:e0f6a96cd5f9ad8f1f91d5d56d3e5534e15682b4a0abecd8396a18b836296426", size = 3006150, upload-time = "2026-08-10T16:56:41.378Z" }, + { url = "https://files.pythonhosted.org/packages/eb/f5/bb4f3272d419bc785ce6a39440f4d157a6f7c154fef93c77444579ee5f43/gevent-26.8.0-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:113d12a2d4276047980e491cc5856388954642eb555479c6962f52fb181eb1df", size = 1819363, upload-time = "2026-08-10T17:58:52.056Z" }, + { url = "https://files.pythonhosted.org/packages/bd/c3/351a5c6890804e39a109c7df8aa8f17f953d2f0acf8215e040670a0e573a/gevent-26.8.0-cp314-cp314-manylinux_2_28_ppc64le.whl", hash = "sha256:3ea7d0ff714ac9c634bfaaa3cfb25a5fcf7a272df47cad2261642323b16a3266", size = 1916853, upload-time = "2026-08-10T17:48:12.677Z" }, + { url = "https://files.pythonhosted.org/packages/80/81/a37201ced7b96eeba4554a1e656d040ad808f254a9f3d7b94f8ac4cfa82a/gevent-26.8.0-cp314-cp314-manylinux_2_28_s390x.whl", hash = "sha256:1bee3c0cb1aa2cee3369de46f8d952d10310166d7b4a744ae64a32ee1e14a1f5", size = 1865982, upload-time = "2026-08-10T17:54:30.173Z" }, + { url = "https://files.pythonhosted.org/packages/30/6d/e70113648ee1041070e6190389796414dd70b8cb86ff5ec8a9762284cb1a/gevent-26.8.0-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:64bc5c3302b02f9ad012243173e13705711dbbcc7590443d974f2961154d7077", size = 2147279, upload-time = "2026-08-10T17:19:24.24Z" }, + { url = "https://files.pythonhosted.org/packages/80/10/1af5f1910d5534bba338d954e77f401e167189c7af8b621104307e2e7e16/gevent-26.8.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:e544cba5810ec64056d78f0d3c79ceeafc91ac612b4e9008134645bc437dd885", size = 1832674, upload-time = "2026-08-10T17:42:41.002Z" }, + { url = "https://files.pythonhosted.org/packages/c1/23/bc09e7f2a0dc699269d5dd03a4860afa80f8d29c1f28a18859ebd06d4ab1/gevent-26.8.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:3445b3a8a51fcb7b881485b1089f7d64ca057aa921a78f146d702853650f958d", size = 2173988, upload-time = "2026-08-10T17:23:52.475Z" }, { url = "https://files.pythonhosted.org/packages/3c/21/44ebdb32eb5050c367c4ccf6d43627bf875847ef65d8455beff52044846c/gevent-26.8.0-cp314-cp314-win_amd64.whl", hash = "sha256:4fe56814f6d36d8fdfe0254909388fa58ccb61e7945d2f031a2dbd81f90ced4c", size = 1716724, upload-time = "2026-08-10T17:01:37.23Z" }, { url = "https://files.pythonhosted.org/packages/8d/71/6708a3aae223a326b648a01beb5244caa562d75f6515528a8241260763f3/gevent-26.8.0-cp314-cp314-win_arm64.whl", hash = "sha256:5914bab0ebe7fbd6077d703b61b2e74afec0436487f29b8154302c61f4d58502", size = 1594414, upload-time = "2026-08-10T17:00:51.867Z" }, { url = "https://files.pythonhosted.org/packages/a7/18/42a8129bdfe7285f35be21e6737a135462cb723a30952f06cb2203ecc8df/gevent-26.8.0-cp315-cp315-macosx_11_0_universal2.whl", hash = "sha256:9afd9fbccbcea0b803d554b9e7bac75382e919aa07a5cb98d04edeba10c6cf77", size = 3009619, upload-time = "2026-08-10T16:59:31.344Z" }, + { url = "https://files.pythonhosted.org/packages/5c/ff/f540c92d4c6ff3af5e60e990c7f417d1419a5a2aee5f5047612e708221c7/gevent-26.8.0-cp315-cp315-manylinux_2_28_aarch64.whl", hash = "sha256:cd225e954d57e7d8a994a8d152f0d76609c73fa701a3e27293cc46675b2dce77", size = 1821950, upload-time = "2026-08-10T17:58:53.313Z" }, + { url = "https://files.pythonhosted.org/packages/ca/eb/b40a8b9df1d4955cae3f600db416d6a8abb73f5f31d8a315cf2acf225462/gevent-26.8.0-cp315-cp315-manylinux_2_28_ppc64le.whl", hash = "sha256:8cb1402c0c7bdbd6d772fd5eb700b98b31ce0d8f613f68823f32cce5ec956d8c", size = 1921096, upload-time = "2026-08-10T17:48:14.477Z" }, + { url = "https://files.pythonhosted.org/packages/74/e4/59fc824207ac7f63ac83af7a7bed2707d6768488f1ae2c6c85794d614570/gevent-26.8.0-cp315-cp315-manylinux_2_28_s390x.whl", hash = "sha256:242d5e3622a39236f57a4e740c5480e86b6bc15c3a790e997b8cc99bee34ef27", size = 1868863, upload-time = "2026-08-10T17:54:31.624Z" }, + { url = "https://files.pythonhosted.org/packages/1c/8b/cb001b1906ce78c63a252ad5baaebba745ca819bd7239ff60417fbc0d24a/gevent-26.8.0-cp315-cp315-manylinux_2_28_x86_64.whl", hash = "sha256:b13173a992de43e92d15c6ac318f8ae019cf08eec15a78f99a0d4a917837052a", size = 2149188, upload-time = "2026-08-10T17:19:25.356Z" }, + { url = "https://files.pythonhosted.org/packages/c5/c6/3085b52ec0ecc8173de40fca1f5faf8d02761288e1712ffb34628cfab214/gevent-26.8.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:f431af3f2737ae01cf1c5a303f193cc2a8f726521e997ea8baf2d8567c6fe07c", size = 1835672, upload-time = "2026-08-10T17:42:42.296Z" }, + { url = "https://files.pythonhosted.org/packages/fa/99/ee5722f7d51ee4bd09396629802ae90c9e0bebef0e7938a4edf08eb92749/gevent-26.8.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:1d8b76e525d7e301db83d8124a27700c55ad23754f3efbbf15c7051d6fa19853", size = 2177315, upload-time = "2026-08-10T17:23:53.854Z" }, { url = "https://files.pythonhosted.org/packages/d4/cb/c2fea129f29ca114dc63f53178337845ba63532e07979c10fd70635a6dde/gevent-26.8.0-cp315-cp315-win_amd64.whl", hash = "sha256:b16931069d0044a23a566d16dc5787122e858fa9d591c81500b6e6ad2148cfec", size = 1716882, upload-time = "2026-08-10T17:00:09.172Z" }, { url = "https://files.pythonhosted.org/packages/29/f4/b4de17304026cbd6386d427bc5ece10ec65015e9bfd66e14672350ee5dfb/gevent-26.8.0-cp315-cp315-win_arm64.whl", hash = "sha256:42b8ed34f7aff517fac448ab57084e5e39d6a84a2b6c2b709223d5751c85e657", size = 1594517, upload-time = "2026-08-10T17:00:47.046Z" }, ] @@ -1191,6 +1220,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" @@ -1490,6 +1528,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" @@ -1923,7 +1966,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" }, @@ -1983,7 +2026,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/tests/test_oidc_provider.py b/wger/core/tests/test_oidc_provider.py new file mode 100644 index 000000000..3800b214c --- /dev/null +++ b/wger/core/tests/test_oidc_provider.py @@ -0,0 +1,242 @@ +# -*- 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 secrets +from urllib.parse import ( + parse_qs, + urlparse, +) + +# Django +from django.conf import settings +from django.test import override_settings +from django.urls import reverse +from django.utils.http import urlencode + +# Third Party +import jwt +from allauth.idp.oidc.models import Client +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa + +# wger +from wger.core.tests.base_testcase import WgerTestCase + + +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 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.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_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'): + """ + 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 = 'openid profile') -> 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') + + 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] + + 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): + with override_settings(IDP_OIDC_PRIVATE_KEY=self.private_key): + 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 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() + + 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, + ) + + self.assertEqual(token['token_type'], 'Bearer') + self.assertEqual(token['scope'], 'openid profile') + 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() + + 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, + }, + ) + + self.assertEqual(response.status_code, 400) + self.assertEqual(response.json()['error'], 'invalid_request') + + 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_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..1fc884c55 100644 --- a/wger/urls.py +++ b/wger/urls.py @@ -302,6 +302,9 @@ 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. + path('', include('allauth.idp.urls')), # API path( 'api/v2/exercise-submission/', diff --git a/wger/utils/api_schema.py b/wger/utils/api_schema.py index 61cda7e07..08e99b3b0 100644 --- a/wger/utils/api_schema.py +++ b/wger/utils/api_schema.py @@ -12,10 +12,43 @@ # # 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 OpenApiAuthenticationExtension from 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. From 95c47523e2197a3b88cf51aa126cba434f397897 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 11 Aug 2026 00:33:47 +0200 Subject: [PATCH 2/9] Add a command to generate the OIDC signing key --- settings/main.py | 5 ++ .../management/commands/generate-oidc-key.py | 66 +++++++++++++++++++ wger/core/tests/test_oidc_provider.py | 26 +++++++- 3 files changed, 96 insertions(+), 1 deletion(-) create mode 100644 wger/core/management/commands/generate-oidc-key.py 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/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/tests/test_oidc_provider.py b/wger/core/tests/test_oidc_provider.py index 3800b214c..1298d037a 100644 --- a/wger/core/tests/test_oidc_provider.py +++ b/wger/core/tests/test_oidc_provider.py @@ -19,6 +19,7 @@ import base64 import hashlib import secrets +from io import StringIO from urllib.parse import ( parse_qs, urlparse, @@ -26,7 +27,11 @@ from urllib.parse import ( # Django from django.conf import settings -from django.test import override_settings +from django.core.management import call_command +from django.test import ( + SimpleTestCase, + override_settings, +) from django.urls import reverse from django.utils.http import urlencode @@ -61,6 +66,25 @@ def generate_pkce_pair() -> tuple[str, str]: 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) From c44341319ad131a0f5bcf7ac95df9230daa9a09d Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 11 Aug 2026 11:41:38 +0200 Subject: [PATCH 3/9] Render the consent screen in wger's layout --- .../idp/oidc/authorization_form.html | 50 +++++++++++++++++++ wger/core/tests/test_oidc_provider.py | 4 ++ 2 files changed, 54 insertions(+) create mode 100644 wger/core/templates/idp/oidc/authorization_form.html 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 index 1298d037a..36c8812c8 100644 --- a/wger/core/tests/test_oidc_provider.py +++ b/wger/core/tests/test_oidc_provider.py @@ -131,6 +131,10 @@ class OidcProviderTestCase(WgerTestCase): 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'), { From 5071492cb408e9248ef68abb9032c42660367f23 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 11 Aug 2026 11:45:41 +0200 Subject: [PATCH 4/9] Clean up expired OIDC tokens periodically --- wger/core/tasks.py | 19 +++++++++++++++ wger/core/tests/test_oidc_provider.py | 34 ++++++++++++++++++++++++++- 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/wger/core/tasks.py b/wger/core/tasks.py index 875627b0d..306fcc7c7 100644 --- a/wger/core/tasks.py +++ b/wger/core/tasks.py @@ -52,6 +52,17 @@ 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. + + Tokens stay in the table after they expire, so without this the table + grows for as long as applications keep refreshing. + """ + call_command('oidc_cleartokens') + + @app.on_after_finalize.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task( @@ -70,3 +81,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/tests/test_oidc_provider.py b/wger/core/tests/test_oidc_provider.py index 36c8812c8..3b0df69d6 100644 --- a/wger/core/tests/test_oidc_provider.py +++ b/wger/core/tests/test_oidc_provider.py @@ -19,6 +19,7 @@ import base64 import hashlib import secrets +from datetime import timedelta from io import StringIO from urllib.parse import ( parse_qs, @@ -27,21 +28,27 @@ from urllib.parse import ( # Django from django.conf import settings +from django.contrib.auth.models import User from django.core.management import call_command from django.test import ( 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.models import Client +from allauth.idp.oidc.models import ( + Client, + Token, +) 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 @@ -246,6 +253,31 @@ class OidcProviderTestCase(WgerTestCase): self.assertEqual(response.status_code, 400) self.assertEqual(response.json()['error'], 'invalid_request') + 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() From e7fc803a971916b36237ed31e844408a48d7c6ea Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 11 Aug 2026 12:06:44 +0200 Subject: [PATCH 5/9] Restrict OIDC access tokens by scope --- settings/settings_global.py | 11 +- wger/core/tests/test_oidc_provider.py | 164 ++++++++++++++++++++------ wger/utils/api_schema.py | 33 ------ wger/utils/oidc_auth.py | 112 ++++++++++++++++++ 4 files changed, 249 insertions(+), 71 deletions(-) create mode 100644 wger/utils/oidc_auth.py diff --git a/settings/settings_global.py b/settings/settings_global.py index 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.py index 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 Party import jwt +from allauth.idp.oidc.adapter import get_adapter from allauth.idp.oidc.models import ( Client, Token, @@ -50,6 +51,10 @@ 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' @@ -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) + 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() - 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, - ) + 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 ones diff --git a/wger/utils/api_schema.py b/wger/utils/api_schema.py index 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 OpenApiAuthenticationExtension from 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.py new file mode 100644 index 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 . + +# 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()}, + } + }, + } From b699cc395b7b7592475430246e2814269304c1ba Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 11 Aug 2026 12:20:24 +0200 Subject: [PATCH 6/9] Add more tests --- wger/core/tests/test_oidc_provider.py | 322 ++++++++++++++++++++++++-- 1 file changed, 299 insertions(+), 23 deletions(-) diff --git a/wger/core/tests/test_oidc_provider.py b/wger/core/tests/test_oidc_provider.py index 8786f2c92..951ddab58 100644 --- a/wger/core/tests/test_oidc_provider.py +++ b/wger/core/tests/test_oidc_provider.py @@ -18,6 +18,7 @@ # Standard Library import base64 import hashlib +import re import secrets from datetime import timedelta from io import StringIO @@ -31,6 +32,7 @@ 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, ) @@ -45,6 +47,13 @@ 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 @@ -200,6 +209,19 @@ class OidcProviderTestCase(WgerTestCase): 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 @@ -208,16 +230,7 @@ class OidcProviderTestCase(WgerTestCase): verifier, challenge = generate_pkce_pair() 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, - }, - ) + response = self.redeem_code(code, code_verifier=verifier) self.assertEqual(response.status_code, 200, response.content) token = response.json() @@ -246,35 +259,269 @@ class OidcProviderTestCase(WgerTestCase): _, challenge = generate_pkce_pair() 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, - }, - ) + response = self.redeem_code(code) self.assertEqual(response.status_code, 400) self.assertEqual(response.json()['error'], 'invalid_request') - def create_access_token(self, scopes: list[str]) -> str: + 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): """ - Mints an access token directly, without running the whole flow + 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_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.ACCESS_TOKEN, + type=token_type, user=User.objects.get(username='test'), client=self.oidc_client, hash=get_adapter().hash_token(value), - expires_at=timezone.now() + timedelta(hours=1), + 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)) + + self.assertEqual(self.read_profile(token).status_code, 403) + + 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]) @@ -383,6 +630,35 @@ class OidcProviderTestCase(WgerTestCase): 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() From 5c3969f4f666fec8de60773cf04fe8bc655e48c5 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 11 Aug 2026 13:25:38 +0200 Subject: [PATCH 7/9] Harden the OAuth2 provider --- settings/settings_global.py | 5 +++ wger/core/tasks.py | 5 ++- wger/core/tests/test_oidc_provider.py | 56 ++++++++++++++++++++++++++- wger/urls.py | 5 ++- wger/utils/oidc_auth.py | 39 ++++++++++++++++--- 5 files changed, 99 insertions(+), 11 deletions(-) diff --git a/settings/settings_global.py b/settings/settings_global.py index 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.py index 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.py index 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 API diff --git a/wger/urls.py b/wger/urls.py index 1fc884c55..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 @@ -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')), # API path( diff --git a/wger/utils/oidc_auth.py b/wger/utils/oidc_auth.py index e7970b78d..338e66a02 100644 --- a/wger/utils/oidc_auth.py +++ b/wger/utils/oidc_auth.py @@ -17,12 +17,14 @@ # 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 @@ -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 None result = 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()}, } }, From 1f08d967856d3a329bc9951ecb7723c2f0a5bb6a Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 11 Aug 2026 13:27:55 +0200 Subject: [PATCH 8/9] Update CHANGELOG.md --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) 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. + +* From a358be2146b0cfdd8f2075b19d700c73b5e9b0aa Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 11 Aug 2026 13:28:02 +0200 Subject: [PATCH 9/9] Bump version --- wger/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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