Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add a command to generate the OIDC signing key
Roland Geider95c47523e219
diff --git a/settings/main.py b/settings/main.pyindex 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 keysRECAPTCHA_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.pynew file mode 100644index 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 <http://www.gnu.org/licenses/>.++# 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.pyindex 3800b214c..1298d037a 100644--- a/wger/core/tests/test_oidc_provider.py+++ b/wger/core/tests/test_oidc_provider.py@@ -19,6 +19,7 @@import base64import hashlibimport secrets+from io import StringIOfrom urllib.parse import (parse_qs,urlparse,@@ -26,7 +27,11 @@ from urllib.parse import (# Djangofrom 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 reversefrom 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)