From 767cdc9ec110a7be571b35eed3c3d6fb2c8a5064 Mon Sep 17 00:00:00 2001 From: Oliver Date: Sat, 28 Nov 2026 20:23:42 +1100 Subject: [PATCH] Additional checks for password reset (#13402) * Additional checks for password reset Prevent leakage of information about user email addresses if password reset is disabled * fix for unit test --- .../InvenTree/InvenTree/auth_overrides.py | 79 ++++++++++++++- src/backend/InvenTree/InvenTree/urls.py | 8 +- src/backend/InvenTree/users/test_api.py | 98 +++++++++++++++++++ 3 files changed, 179 insertions(+), 6 deletions(-) diff --git a/src/backend/InvenTree/InvenTree/auth_overrides.py b/src/backend/InvenTree/InvenTree/auth_overrides.py index fe8a3e072f..f3052056e7 100644 --- a/src/backend/InvenTree/InvenTree/auth_overrides.py +++ b/src/backend/InvenTree/InvenTree/auth_overrides.py @@ -1,13 +1,14 @@ """Overrides for allauth and adjacent packages to enforce InvenTree specific auth settings and restirctions.""" +import functools from typing import Literal from django import forms from django.conf import settings from django.contrib.auth.models import Group from django.core.exceptions import PermissionDenied -from django.http import HttpResponseRedirect -from django.urls import reverse +from django.http import HttpResponseRedirect, JsonResponse +from django.urls import URLPattern, URLResolver, reverse from django.utils.translation import gettext_lazy as _ import structlog @@ -102,6 +103,67 @@ def registration_enabled(setting_name: RegistrationKeys = 'LOGIN_ENABLE_REG'): return False +def password_reset_enabled() -> bool: + """Return True if the 'forgot password' (password reset) functionality is enabled.""" + return str2bool(get_global_setting('LOGIN_ENABLE_PWD_FORGOT', True, cache=False)) + + +# Names of the allauth (headless) URL patterns which perform password reset +PASSWORD_RESET_URL_NAMES = ('request_password_reset', 'reset_password') + + +def password_reset_guard(view): + """Wrap a password reset view, rejecting all requests if password reset is disabled. + + The request is rejected *before* any account lookup is performed, and the + response is identical for every request. This prevents the endpoint from + revealing which email addresses are associated with an account. + + This covers both requesting a reset, and resetting the password from a key, + so that previously issued reset keys cannot be used while reset is disabled. + """ + + @functools.wraps(view) + def wrapped_view(request, *args, **kwargs): + if not password_reset_enabled(): + return JsonResponse( + { + 'status': 403, + 'errors': [ + { + 'message': str(_('Password reset is disabled')), + 'code': 'password_reset_disabled', + } + ], + }, + status=403, + ) + + return view(request, *args, **kwargs) + + return wrapped_view + + +def guard_password_reset_urls(patterns: list) -> list: + """Apply password_reset_guard to the password reset views in a list of URL patterns. + + Arguments: + patterns: List of URL patterns (e.g. from allauth.headless.urls.build_urlpatterns) + + Returns: + The same list of URL patterns, with the password reset views wrapped. + """ + for pattern in patterns: + if isinstance(pattern, URLResolver): + guard_password_reset_urls(pattern.url_patterns) + elif ( + isinstance(pattern, URLPattern) and pattern.name in PASSWORD_RESET_URL_NAMES + ): + pattern.callback = password_reset_guard(pattern.callback) + + return patterns + + class RegistrationMixin: """Mixin to check if registration should be enabled.""" @@ -188,9 +250,16 @@ class CustomAccountAdapter(RegistrationMixin, DefaultAccountAdapter): return False def send_password_reset_mail(self, user, email, context): - """Send the password reset mail.""" - if not get_global_setting('LOGIN_ENABLE_PWD_FORGOT'): - raise PermissionDenied('Password reset is disabled') + """Send the password reset mail. + + Note: Requests are rejected by password_reset_guard before this point if + password reset is disabled. This check is an additional safeguard - it returns + silently (rather than raising an error), as allauth only calls this method for + *existing* accounts, and an error here would reveal which accounts exist. + """ + if not password_reset_enabled(): + logger.warning('Password reset email not sent - password reset is disabled') + return return super().send_password_reset_mail(user, email, context) diff --git a/src/backend/InvenTree/InvenTree/urls.py b/src/backend/InvenTree/InvenTree/urls.py index ba7f7f9a4c..46a22c793c 100644 --- a/src/backend/InvenTree/InvenTree/urls.py +++ b/src/backend/InvenTree/InvenTree/urls.py @@ -43,6 +43,7 @@ from .api import ( VersionTextView, VersionView, ) +from .auth_overrides import guard_password_reset_urls from .config import get_setting from .magic_login import GetSimpleLoginView from .views import AccountLoginRedirectView, auth_request @@ -115,7 +116,12 @@ apipatterns = [ path( '', include( - (build_urlpatterns(Client.BROWSER), 'headless'), namespace='browser' + ( + # Password reset views are guarded by the LOGIN_ENABLE_PWD_FORGOT setting + guard_password_reset_urls(build_urlpatterns(Client.BROWSER)), + 'headless', + ), + namespace='browser', ), ), # Allauth headless logic (only the browser client is included as we only use sessions based auth there) ]), diff --git a/src/backend/InvenTree/users/test_api.py b/src/backend/InvenTree/users/test_api.py index 1124d6f478..bcaec153f2 100644 --- a/src/backend/InvenTree/users/test_api.py +++ b/src/backend/InvenTree/users/test_api.py @@ -1318,3 +1318,101 @@ class NewUserMfaOnboardingTests(InvenTreeAPITestCase): self.assertFalse( EmailAddress.objects.filter(user=new_user, verified=True).exists() ) + + +class PasswordResetDisabledTests(InvenTreeAPITestCase): + """Tests for the LOGIN_ENABLE_PWD_FORGOT setting. + + When password reset is disabled, the reset endpoints must reject every request + in the same way - regardless of whether the email address belongs to an account. + """ + + NEW_PASSWORD = 'Corr3ct-Horse-Battery-Staple!' + + def setUp(self): + """Create a user with a known email address, and log out.""" + super().setUp() + self.target = User.objects.create_user( + username='resetme', email='resetme@example.org', password='old-password' + ) + self.client.logout() + + def request_reset(self, email): + """Request a password reset for the given email address.""" + return self.client.post( + reverse('browser:account:request_password_reset'), + {'email': email}, + content_type='application/json', + ) + + def reset_with_key(self): + """Attempt to reset the target user's password using a valid key.""" + from allauth.account.forms import default_token_generator + from allauth.account.utils import user_pk_to_url_str + + key = f'{user_pk_to_url_str(self.target)}-{default_token_generator.make_token(self.target)}' + + return self.client.post( + reverse('browser:account:reset_password'), + {'key': key, 'password': self.NEW_PASSWORD}, + content_type='application/json', + ) + + def test_reset_enabled(self): + """With password reset enabled, known and unknown emails get the same response.""" + from django.core import mail + + from common.settings import set_global_setting + + set_global_setting('LOGIN_ENABLE_PWD_FORGOT', True) + mail.outbox = [] + + # CustomAccountAdapter only sends mail if EMAIL_HOST is configured + with self.settings(EMAIL_HOST='localhost', TESTING_BYPASS_MAILCHECK=True): + known = self.request_reset('resetme@example.org') + unknown = self.request_reset('nobody@example.org') + + self.assertEqual(known.status_code, unknown.status_code) + self.assertEqual(known.status_code, 200, known.content) + + # A reset email is sent to the known account + self.assertTrue( + any('resetme@example.org' in m.to for m in mail.outbox), mail.outbox + ) + + def test_reset_disabled(self): + """With password reset disabled, every request is rejected identically.""" + from django.core import mail + + from common.settings import set_global_setting + + set_global_setting('LOGIN_ENABLE_PWD_FORGOT', False) + mail.outbox = [] + + known = self.request_reset('resetme@example.org') + unknown = self.request_reset('nobody@example.org') + + # Responses do not reveal whether an account exists + self.assertEqual(known.status_code, 403, known.content) + self.assertEqual(unknown.status_code, 403, unknown.content) + self.assertEqual(known.json(), unknown.json()) + self.assertEqual(known.json()['errors'][0]['code'], 'password_reset_disabled') + + # No emails are sent + self.assertEqual(len(mail.outbox), 0) + + # A previously issued reset key cannot be used + response = self.reset_with_key() + self.assertEqual(response.status_code, 403, response.content) + + self.target.refresh_from_db() + self.assertTrue(self.target.check_password('old-password')) + + # Re-enable: the same key can now be used + set_global_setting('LOGIN_ENABLE_PWD_FORGOT', True) + + response = self.reset_with_key() + self.assertIn(response.status_code, [200, 401], response.content) + + self.target.refresh_from_db() + self.assertTrue(self.target.check_password(self.NEW_PASSWORD))