Self hosted FLOSS fitness/workout, nutrition and weight tracker
Separate auth proxy support into middleware and backend
Roland Geiderfbb19b5729e9
diff --git a/extras/docker/production/settings.py b/extras/docker/production/settings.pyindex 86521b057..c9a501597 100644--- a/extras/docker/production/settings.py+++ b/extras/docker/production/settings.py@@ -101,7 +101,13 @@ WGER_SETTINGS["SYNC_INGREDIENTS_CELERY"] = env.bool("SYNC_INGREDIENTS_CELERY", FWGER_SETTINGS["SYNC_OFF_DAILY_DELTA_CELERY"] = env.bool("SYNC_OFF_DAILY_DELTA_CELERY", False)WGER_SETTINGS["USE_RECAPTCHA"] = env.bool("USE_RECAPTCHA", False)WGER_SETTINGS["USE_CELERY"] = env.bool("USE_CELERY", False)-WGER_SETTINGS["AUTH_PROXY_HEADER"] = env.str("AUTH_PROXY_HEADER", '')++#+# Auth Proxy Authentication+# https://wger.readthedocs.io/en/latest/administration/auth_proxy.html+AUTH_PROXY_HEADER = env.str("AUTH_PROXY_HEADER", '')+AUTH_PROXY_TRUSTED_IPS = env.list("AUTH_PROXY_TRUSTED_IPS", default=[])+AUTH_PROXY_CREATE_UNKNOWN_USER = env.bool("AUTH_PROXY_CREATE_UNKNOWN_USER", False)# Cacheif os.environ.get("DJANGO_CACHE_BACKEND"):diff --git a/wger/core/backends.py b/wger/core/backends.pynew file mode 100644index 000000000..76260f146--- /dev/null+++ b/wger/core/backends.py@@ -0,0 +1,75 @@+# 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++# Standard Library+import logging++# Django+from django.conf import settings+from django.contrib.auth import get_user_model+from django.contrib.auth.backends import BaseBackend+++logger = logging.getLogger(__name__)+User = get_user_model()+++class AuthProxyUserBackend(BaseBackend):+ """+ Authenticates against a username passed in the request meta (header).+ Relies on the middleware to ensure the header comes from a trusted source.+ """++ def authenticate(self, request, username=None):+ """+ Authenticate the user based on the username provided.+ The middleware ensures this is only called when the source is trusted.+ """+ if not username:+ # This backend requires a username passed explicitly+ return None++ create_unknown_user = getattr(settings, 'AUTH_PROXY_CREATE_UNKNOWN_USER', True)++ user = None+ try:+ user = User.objects.get(username=username)+ logger.debug(f"AuthProxy: Found existing user '{username}'")+ except User.DoesNotExist:+ if create_unknown_user:+ try:+ user = User.objects.create_user(username=username)+ logger.info(f"AuthProxy: Created new user '{username}'")+ except Exception as e:+ logger.error(f"AuthProxy: Failed to create user '{username}': {e}")+ return None+ else:+ logger.warning(+ f"AuthProxy: User '{username}' not found and auto-creation is disabled."+ )+ return None+ except Exception as e:+ logger.error(f"AuthProxy: Error fetching user '{username}': {e}")+ return None++ return user++ def get_user(self, user_id):+ """+ Standard Django method to retrieve a user by ID.+ """+ try:+ return User.objects.get(pk=user_id)+ except User.DoesNotExist:+ return Nonediff --git a/wger/core/middleware.py b/wger/core/middleware.pynew file mode 100644index 000000000..c3b51d2ca--- /dev/null+++ b/wger/core/middleware.py@@ -0,0 +1,115 @@+# 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++# Standard Library+import logging++# Django+from django.conf import settings+from django.contrib.auth import (+ authenticate,+ get_user_model,+ login,+ logout,+)+from django.utils.deprecation import MiddlewareMixin++logger = logging.getLogger(__name__)+User = get_user_model()+++class AuthProxyHeaderMiddleware(MiddlewareMixin):+ """+ Middleware to authenticate users based on a header set by a trusted proxy.++ Relies on settings:+ - AUTH_PROXY_HEADER: The request.META key containing the username.+ - AUTH_PROXY_TRUSTED_IPS: List of IPs allowed to set the header.+ """++ def process_request(self, request):+ header_key = getattr(settings, 'AUTH_PROXY_HEADER', None)+ trusted_ips = set(getattr(settings, 'AUTH_PROXY_TRUSTED_IPS', []))++ # Skip processing if not configured+ if not header_key or not trusted_ips:+ # logger.debug(+ # 'AuthProxyMiddleware: AUTH_PROXY_HEADER or AUTH_PROXY_TRUSTED_IPS not configured.'+ # )+ return None++ # Get the client IP address.+ # Use REMOTE_ADDR as it's the direct connection IP (should be the proxy).+ client_ip = request.META.get('REMOTE_ADDR')++ # Check if the request comes from a trusted IP+ if not client_ip or client_ip not in trusted_ips:+ # If the header *is* present but the IP is not trusted, log a warning+ # as this might indicate a misconfiguration or security probing.+ if header_key in request.META:+ logger.warning(+ f"AuthProxyMiddleware: Header '{header_key}' received from "+ f"untrusted IP '{client_ip}'. Ignoring header."+ )+ # Not a trusted IP, do nothing.+ return None++ username = request.META.get(header_key)+ if not username:+ # Trusted IP, but no header. Could mean proxy auth failed upstream.+ # Log, but otherwise do nothing.+ logger.debug(+ f"AuthProxyMiddleware: No username found in header '{header_key}' from "+ f"trusted IP '{client_ip}'."+ )++ return None++ # If user is already authenticated and matches the header, do nothing.+ if request.user.is_authenticated:++ if request.user.get_username() == username:+ return None++ # Logged in as someone else? This shouldn't usually happen if the+ # proxy is forcing the user, but we should log out the old session+ # and log in the header user for consistency.+ else:+ logger.warning(+ f"AuthProxyMiddleware: User mismatch. Session user '{request.user.get_username()}' "+ f"differs from proxy header user '{username}'. Logging out old user."+ )+ logout(request)++ # Authenticate using our custom backend+ user = authenticate(request, username=username)++ if user:+ # Authentication successful, log the user in.+ login(request, user)+ logger.info(+ f"AuthProxyMiddleware: User '{username}' authenticated via header from "+ f"trusted IP '{client_ip}'."+ )+ else:+ # Authentication failed (e.g., user couldn't be found/created by backend)+ logger.error(+ f"AuthProxyMiddleware: Authentication failed for username '{username}' "+ f"from header '{header_key}' (Trusted IP: {client_ip})."+ )++ # Explicitly clear any potentially lingering user object+ request.user = None++ return Nonediff --git a/wger/core/tests/test_auch_proxy_middleware.py b/wger/core/tests/test_auch_proxy_middleware.pynew file mode 100644index 000000000..fd86f7ad8--- /dev/null+++ b/wger/core/tests/test_auch_proxy_middleware.py@@ -0,0 +1,157 @@+# 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++# Django+from django.contrib.auth import get_user_model+from django.test import (+ Client,+ TestCase,+ override_settings,+)+from django.urls import reverse+++User = get_user_model()++TRUSTED_IP = '192.0.2.1'+UNTRUSTED_IP = '198.51.100.5'++PROXY_HEADER_KEY = 'HTTP_X_REMOTE_USER'+USERNAME = 'admin'+NEW_USER_VALUE = 'auth_proxy_user'+++class AuthProxyMiddlewareTests(TestCase):+ fixtures = (+ 'test-languages',+ 'gym_config',+ )++ def setUp(self):+ self.client = Client()+ self.existing_user = User.objects.create_user(+ username=USERNAME,+ password='password123',+ )+ self.protected_url = reverse('core:dashboard')++ self.login_url = reverse('core:user:login')[3:]+ """Login URL without the /en/ part"""++ # Helper to make requests with specific IP and header+ def make_request(self, ip_addr, header_value=None):+ headers = {}+ if header_value:+ headers[PROXY_HEADER_KEY] = header_value++ # Use REMOTE_ADDR to spoof the IP+ self.client.get(self.protected_url, REMOTE_ADDR=ip_addr, **headers)+ return self.client.get(self.protected_url)++ @override_settings(+ AUTH_PROXY_TRUSTED_IPS=[TRUSTED_IP],+ AUTH_PROXY_HEADER=PROXY_HEADER_KEY,+ )+ def test_success_trusted_ip_existing_user(self):+ response = self.make_request(TRUSTED_IP, USERNAME)+ self.assertEqual(response.status_code, 200)++ # Check if the correct user is logged into the session+ self.assertEqual(int(self.client.session['_auth_user_id']), self.existing_user.pk)++ @override_settings(+ AUTH_PROXY_TRUSTED_IPS=[TRUSTED_IP],+ AUTH_PROXY_HEADER=PROXY_HEADER_KEY,+ AUTH_PROXY_CREATE_UNKNOWN_USER=True,+ )+ def test_success_trusted_ip_new_user_created(self):+ self.assertFalse(User.objects.filter(username=NEW_USER_VALUE).exists())+ response = self.make_request(TRUSTED_IP, NEW_USER_VALUE)+ self.assertEqual(response.status_code, 200)++ # Verify user was created+ newly_created_user = User.objects.filter(username=NEW_USER_VALUE).first()+ self.assertIsNotNone(newly_created_user)+ self.assertEqual(int(self.client.session['_auth_user_id']), newly_created_user.pk)++ @override_settings(+ AUTH_PROXY_HEADER=PROXY_HEADER_KEY,+ AUTH_PROXY_TRUSTED_IPS=[TRUSTED_IP],+ )+ def test_failure_untrusted_ip_header_present(self):+ """Should redirect to login because the middleware shouldn't authenticate"""++ response = self.make_request(UNTRUSTED_IP, USERNAME)++ self.assertEqual(response.status_code, 302)+ self.assertTrue(response.url.startswith(self.login_url))+ self.assertNotIn('_auth_user_id', self.client.session)++ @override_settings(+ AUTH_PROXY_HEADER=PROXY_HEADER_KEY,+ AUTH_PROXY_TRUSTED_IPS=[TRUSTED_IP],+ )+ def test_failure_trusted_ip_header_missing(self):+ """Should redirect to login"""+ response = self.make_request(TRUSTED_IP, header_value=None)++ self.assertEqual(response.status_code, 302)+ self.assertTrue(response.url.startswith(self.login_url))+ self.assertNotIn('_auth_user_id', self.client.session)++ @override_settings(+ AUTH_PROXY_HEADER=PROXY_HEADER_KEY,+ AUTH_PROXY_TRUSTED_IPS=[TRUSTED_IP],+ AUTH_PROXY_CREATE_UNKNOWN_USER=False,+ )+ def test_failure_trusted_ip_new_user_creation_disabled(self):+ self.assertFalse(User.objects.filter(username=NEW_USER_VALUE).exists())+ response = self.make_request(TRUSTED_IP, NEW_USER_VALUE)++ # Should redirect to login+ self.assertEqual(response.status_code, 302)+ self.assertTrue(response.url.startswith(self.login_url))++ # Verify user was NOT created+ self.assertFalse(User.objects.filter(username=NEW_USER_VALUE).exists())+ self.assertNotIn('_auth_user_id', self.client.session)++ @override_settings(+ AUTH_PROXY_TRUSTED_IPS=[TRUSTED_IP],+ AUTH_PROXY_HEADER='HTTP_X_DIFFERENT_USER',+ )+ def test_alternate_header_name(self):+ # Request using the *correctly* configured header name+ self.client.get(+ self.protected_url,+ REMOTE_ADDR=TRUSTED_IP,+ HTTP_X_DIFFERENT_USER=USERNAME,+ )+ response_correct = self.client.get(self.protected_url)+ self.assertEqual(response_correct.status_code, 200)+ self.assertEqual(int(self.client.session['_auth_user_id']), self.existing_user.pk)++ # Clear session before next request+ self.client.logout()++ # Request using the *default/wrong* header name should fail+ response_wrong1 = self.client.get(+ self.protected_url,+ REMOTE_ADDR=TRUSTED_IP,+ HTTP_X_REMOTE_USER=USERNAME,+ )+ response_wrong2 = self.client.get(self.protected_url)+ self.assertEqual(response_wrong1.status_code, 302)+ self.assertEqual(response_wrong2.status_code, 302)+ self.assertNotIn('_auth_user_id', self.client.session)diff --git a/wger/settings_global.py b/wger/settings_global.pyindex 68f5a7d1b..266dba548 100644--- a/wger/settings_global.py+++ b/wger/settings_global.py@@ -126,6 +126,9 @@ MIDDLEWARE = [# Django Admin'django.contrib.auth.middleware.AuthenticationMiddleware',+ # Auth proxy middleware+ 'wger.core.middleware.AuthProxyHeaderMiddleware',+# Javascript Header. Sends helper headers for AJAX'wger.utils.middleware.JavascriptAJAXRedirectionMiddleware',@@ -150,6 +153,8 @@ MIDDLEWARE = [AUTHENTICATION_BACKENDS = ('axes.backends.AxesStandaloneBackend', # should be the first one in the list++ 'wger.core.backends.AuthProxyUserBackend','django.contrib.auth.backends.ModelBackend','wger.utils.helpers.EmailAuthBackend',)@@ -548,9 +553,18 @@ WGER_SETTINGS = {'USE_CELERY': False,'USE_RECAPTCHA': False,'WGER_INSTANCE': 'https://wger.de',- 'AUTH_PROXY_HEADER': ''}+#+# Auth Proxy Authentication+#+# Please read the documentation before enabling this feature:+# https://wger.readthedocs.io/en/latest/administration/auth_proxy.html+#+AUTH_PROXY_HEADER = ''+AUTH_PROXY_TRUSTED_IPS = []+AUTH_PROXY_CREATE_UNKNOWN_USER = False+## Prometheus metrics#diff --git a/wger/utils/middleware.py b/wger/utils/middleware.pyindex 50dd25040..fdde69f6a 100644--- a/wger/utils/middleware.py+++ b/wger/utils/middleware.py@@ -22,7 +22,6 @@ import loggingfrom django.conf import settingsfrom django.contrib import authfrom django.contrib.auth import login as django_login-from django.contrib.auth.models import Userfrom django.utils.deprecation import MiddlewareMixinfrom django.utils.functional import SimpleLazyObject@@ -63,25 +62,8 @@ def get_user(request):if not request.session.get('has_demo_data'):request.session['has_demo_data'] = False- # if auth proxy header is setup, then create the user- # as authentication has already happened.- auth_proxy_header = settings.WGER_SETTINGS.get("AUTH_PROXY_HEADER")- if auth_proxy_header:- auth_proxy_header_django = "HTTP_" + auth_proxy_header.replace("-", "_").upper()- username = request.META.get(auth_proxy_header_django)- logger.debug(f'using auth_proxy_header "{auth_proxy_header}" got username "{username}"')-- if username:- user_query = User.objects.filter(username=username)- if user_query.exists():- user = user_query.first()- else:- user = User.objects.create_user(username)- user.save()-- django_login(request, user, backend='django.contrib.auth.backends.ModelBackend')# Django didn't find a user, so create one now- elif (+ if (settings.WGER_SETTINGS['ALLOW_GUEST_USERS']and request.method == 'GET'and create_userdiff --git a/wger/utils/tests/test_auth_proxy_header.py b/wger/utils/tests/test_auth_proxy_header.pydeleted file mode 100644index 9a030e77e..000000000--- a/wger/utils/tests/test_auth_proxy_header.py+++ /dev/null@@ -1,29 +0,0 @@-# Django-from django.urls import reverse--# wger-from wger.core.tests.base_testcase import WgerTestCase---class ProxyAuthHeaderTestCase(WgerTestCase):- """- Tests using proxy auth for authentication- """-- def test_basic_auth_proxy_header(self):- """- Tests that the proxy auth header works for authenticating- the user- """- with self.settings(- WGER_SETTINGS={- "AUTH_PROXY_HEADER": "Remote-User",- "ALLOW_REGISTRATION": False,- "ALLOW_GUEST_USERS": False,- 'TWITTER': False,- 'MASTODON': False,- 'MIN_ACCOUNT_AGE_TO_TRUST': 21,- }- ):- response = self.client.get(reverse("core:dashboard"), HTTP_REMOTE_USER="testuser")- self.assertEqual(response.status_code, 200)