diff --git a/docs/docs/settings/MFA.md b/docs/docs/settings/MFA.md index 56262a75c3..e1f72d7923 100644 --- a/docs/docs/settings/MFA.md +++ b/docs/docs/settings/MFA.md @@ -14,6 +14,12 @@ To make MFA mandatory for all users: 1. Enable it in the [global settings](../settings/global.md). +### Email Verification + +Setting up MFA requires a verified email address. Users created by an administrator start with an unverified address; completing the password reset from their welcome email verifies it, after which they can set up MFA on first login. + +If a user's email address is still unverified (for example, if their account has more than one address), the MFA setup page offers to resend the verification email. As a last resort, an admin can mark the address as verified in the [Database Admin interface](../settings/db_admin.md) (*Accounts* → *Email addresses*). + ### Security Consideration Password based [basic authentication](../api/index.md#basic-auth) against the API is refused for users with MFA configured, and for all users while MFA is enforced. API clients should use tokens (generated in the user interface) or OAuth2 instead. diff --git a/src/backend/InvenTree/users/models.py b/src/backend/InvenTree/users/models.py index ab6f98f098..6f4c554256 100644 --- a/src/backend/InvenTree/users/models.py +++ b/src/backend/InvenTree/users/models.py @@ -23,6 +23,7 @@ from django.utils.translation import gettext_lazy as _ import structlog from allauth.account.models import EmailAddress +from allauth.account.signals import password_reset from rest_framework.authtoken.models import Token as AuthToken import InvenTree.helpers @@ -404,6 +405,36 @@ def api_token_notification(sender, instance: ApiToken, created, **kwargs): notify_api_token(instance) +@receiver(password_reset, dispatch_uid='verify_email_on_password_reset') +def verify_email_on_password_reset(sender, request, user, **kwargs): + """Mark the user's email address as verified after a successful password reset. + + Completing a password reset proves control of the mailbox the reset link (or code) + was sent to. Without this, users created by an administrator (whose email address + is stored as unverified) cannot register an MFA device, which locks them out + entirely when MFA is enforced. + + To avoid verifying an address the user did not prove control of, this only applies + when the user has exactly one email address and it matches their account email. + """ + if not user or not user.email: + return + + addresses = list(EmailAddress.objects.filter(user=user)[:2]) + + if len(addresses) != 1: + return + + address = addresses[0] + + if address.verified or address.email.lower() != user.email.lower(): + return + + address.verified = True + address.save(update_fields=['verified']) + logger.info('Email address verified via password reset for user %s', user.pk) + + class RuleSet(models.Model): """A RuleSet is somewhat like a superset of the django permission class, in that in encapsulates a bunch of permissions. diff --git a/src/backend/InvenTree/users/serializers.py b/src/backend/InvenTree/users/serializers.py index c9d5a93926..624204276f 100644 --- a/src/backend/InvenTree/users/serializers.py +++ b/src/backend/InvenTree/users/serializers.py @@ -616,6 +616,7 @@ class UserCreateSerializer(ExtendedUserSerializer): # Make sure the user cannot login until they have set a password instance.set_unusable_password() + instance.save(update_fields=['password']) message = ( _('Your account has been created.') diff --git a/src/backend/InvenTree/users/test_api.py b/src/backend/InvenTree/users/test_api.py index f551211345..154bcace34 100644 --- a/src/backend/InvenTree/users/test_api.py +++ b/src/backend/InvenTree/users/test_api.py @@ -966,3 +966,126 @@ class RuleSetPermissionTests(InvenTreeAPITestCase): self.patch(group_url, {'name': 'renamed-group'}, expected_code=403) self.patch(ruleset_url, {'can_change': True}, expected_code=403) + + +class NewUserMfaOnboardingTests(InvenTreeAPITestCase): + """Regression tests for onboarding admin-created users while MFA is enforced. + + Ref: https://github.com/inventree/InvenTree/issues/13238 + """ + + NEW_PASSWORD = 'Corr3ct-Horse-Battery-Staple!' + + def setUp(self): + """Allow the test user to create other users.""" + super().setUp() + self.user.is_staff = True + self.user.save() + self.assignRole('admin.add') + + def create_user(self, username='newbie', email='newbie@example.org'): + """Create a new user via the API, as an administrator would.""" + self.post( + reverse('api-user-list'), + data={ + 'username': username, + 'first_name': 'New', + 'last_name': 'User', + 'email': email, + }, + expected_code=201, + ) + return User.objects.get(username=username) + + def reset_password(self, user): + """Complete the headless password reset flow using a valid reset 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(user)}-{default_token_generator.make_token(user)}' + + response = self.client.post( + reverse('browser:account:reset_password'), + {'key': key, 'password': self.NEW_PASSWORD}, + content_type='application/json', + ) + # Password reset does not log the user in -> 401 'unauthenticated' response + self.assertIn(response.status_code, [200, 401], response.content) + + def get_totp(self): + """Request a TOTP secret (first step of MFA registration).""" + return self.client.get(reverse('browser:mfa:manage_totp')) + + def test_new_user_can_register_mfa(self): + """A new user must be able to register MFA after resetting their password.""" + new_user = self.create_user() + + email = EmailAddress.objects.get(user=new_user) + self.assertFalse(email.verified) + self.assertFalse(new_user.has_usable_password()) + + self.client.logout() + + with mock.patch.dict('os.environ', {'INVENTREE_LOGIN_ENFORCE_MFA': 'True'}): + self.reset_password(new_user) + + # Completing the reset proves ownership of the mailbox + email.refresh_from_db() + self.assertTrue(email.verified) + + # The new user can now log in with their new password... + response = self.client.post( + reverse('browser:account:login'), + {'username': 'newbie', 'password': self.NEW_PASSWORD}, + content_type='application/json', + ) + self.assertEqual(response.status_code, 200, response.content) + + # ...is still blocked from the API until MFA is set up... + response = self.client.get(reverse('api-part-list')) + self.assertEqual(response.status_code, 401) + self.assertEqual(response.json()['id'], 'mfa_register') + + # ...but can obtain a TOTP secret to register MFA + response = self.get_totp() + self.assertEqual(response.status_code, 404, response.content) + self.assertIn('secret', response.json()['meta']) + + def test_unverified_email_blocks_mfa_registration(self): + """Without a verified email, MFA registration is refused (the original bug).""" + new_user = self.create_user() + new_user.set_password(self.NEW_PASSWORD) + new_user.save() + + self.client.logout() + self.client.login(username='newbie', password=self.NEW_PASSWORD) + + response = self.get_totp() + self.assertEqual(response.status_code, 409, response.content) + self.assertEqual(response.json()['errors'][0]['code'], 'unverified_email') + + def test_reset_with_multiple_addresses(self): + """Do not verify any address if the user has more than one.""" + new_user = self.create_user() + EmailAddress.objects.create( + user=new_user, email='other@example.org', primary=False, verified=False + ) + + self.client.logout() + self.reset_password(new_user) + + self.assertFalse( + EmailAddress.objects.filter(user=new_user, verified=True).exists() + ) + + def test_reset_with_mismatched_address(self): + """Do not verify an address which does not match the account email.""" + new_user = self.create_user() + EmailAddress.objects.filter(user=new_user).update(email='stale@example.org') + + self.client.logout() + self.reset_password(new_user) + + self.assertFalse( + EmailAddress.objects.filter(user=new_user, verified=True).exists() + ) diff --git a/src/frontend/src/functions/auth.tsx b/src/frontend/src/functions/auth.tsx index 5c8f4c1406..e84be3aa45 100644 --- a/src/frontend/src/functions/auth.tsx +++ b/src/frontend/src/functions/auth.tsx @@ -599,23 +599,65 @@ export function authApi( return api(url, requestConfig); } -export const getTotpSecret = async (setTotpQr: any) => { +export const getTotpSecret = async ( + setTotpQr: any, + onUnverifiedEmail?: () => void +) => { await authApi(apiUrl(ApiEndpoints.auth_totp), undefined, 'get').catch( (err) => { - if (err.status == 404 && err.response.data.meta.secret) { + if (err.status == 404 && err.response?.data?.meta?.secret) { setTotpQr(err.response.data.meta); - } else { - const msg = err.response.data.errors[0].message; - showNotification({ - title: t`Failed to set up MFA`, - message: msg, - color: 'red' - }); + return; } + + const error = err.response?.data?.errors?.[0]; + + // MFA cannot be registered until all email addresses are verified + if (error?.code == 'unverified_email' && onUnverifiedEmail) { + onUnverifiedEmail(); + return; + } + + showNotification({ + title: t`Failed to set up MFA`, + message: error?.message ?? t`An unknown error occurred`, + color: 'red' + }); } ); }; +/** + * Request a new verification email for each unverified email address of the current user. + */ +export async function resendEmailVerification() { + try { + const response = await authApi(apiUrl(ApiEndpoints.auth_email)); + const addresses: { email: string; verified: boolean }[] = + response.data?.data ?? []; + + const unverified = addresses.filter((address) => !address.verified); + + for (const address of unverified) { + await authApi(apiUrl(ApiEndpoints.auth_email), undefined, 'put', { + email: address.email + }); + } + + showNotification({ + title: t`Verification email sent`, + message: t`Check your inbox for a link to verify your email address`, + color: 'green' + }); + } catch { + showNotification({ + title: t`Error`, + message: t`Verification email could not be sent`, + color: 'red' + }); + } +} + export function handleVerifyTotp( value: string, navigate: NavigateFunction, diff --git a/src/frontend/src/pages/Auth/MFASetup.tsx b/src/frontend/src/pages/Auth/MFASetup.tsx index 9a99e30312..c55c67a043 100644 --- a/src/frontend/src/pages/Auth/MFASetup.tsx +++ b/src/frontend/src/pages/Auth/MFASetup.tsx @@ -1,10 +1,14 @@ import { t } from '@lingui/core/macro'; import { Trans } from '@lingui/react/macro'; -import { getTotpSecret, handleVerifyTotp } from '../../functions/auth'; +import { + getTotpSecret, + handleVerifyTotp, + resendEmailVerification +} from '../../functions/auth'; import { Wrapper } from './Layout'; -import { Button } from '@mantine/core'; -import { useEffect, useState } from 'react'; +import { Alert, Button, Group, Stack, Text } from '@mantine/core'; +import { useCallback, useEffect, useState } from 'react'; import { useLocation, useNavigate } from 'react-router-dom'; import { QrRegistrationForm } from '../Index/Settings/AccountSettings/QrRegistrationForm'; @@ -14,11 +18,62 @@ export default function MFASetup() { const [totpQr, setTotpQr] = useState<{ totp_url: string; secret: string }>(); const [value, setValue] = useState(''); + const [unverifiedEmail, setUnverifiedEmail] = useState(false); + const [sending, setSending] = useState(false); + + const fetchSecret = useCallback(() => { + setUnverifiedEmail(false); + getTotpSecret(setTotpQr, () => setUnverifiedEmail(true)); + }, []); useEffect(() => { - getTotpSecret(setTotpQr); + fetchSecret(); + }, [fetchSecret]); + + const sendVerification = useCallback(() => { + setSending(true); + resendEmailVerification().finally(() => setSending(false)); }, []); + if (unverifiedEmail) { + return ( + + + + + + Your email address must be verified before multi-factor + authentication can be set up. + + + + + Send a verification email, follow the link it contains, then + return here and try again. + + + + + + + + + + ); + } + return ( { await page.getByText('The password was set successfully').waitFor(); }); +/** + * Wait (if required) until there is enough time left in the current TOTP period. + * + * The server does not allow any clock tolerance (MFA_TOTP_TOLERANCE = 0), + * so a code generated near the end of a period may have expired by the time + * the server validates it (especially on a slow CI runner). + * + * @param minRemaining - Minimum number of seconds which must remain in the period + */ +async function waitForFreshTotpPeriod( + page: Page, + minRemaining = 10, + period = 30 +) { + const remaining = period - (Math.floor(Date.now() / 1000) % period); + + if (remaining < minRemaining) { + await page.waitForTimeout((remaining + 1) * 1000); + } +} + // Tests for assigning MFA tokens to users test('Login - MFA - TOTP', async ({ page }) => { await doLogin(page, { @@ -478,6 +499,8 @@ test('Login - MFA - TOTP', async ({ page }) => { period: 30 }); + // Avoid generating a code which expires before the server validates it + await waitForFreshTotpPeriod(page); const token = totp.generate(); await page.getByRole('textbox', { name: 'text-input-otp-code' }).fill(token); @@ -701,3 +724,95 @@ test('Login - MFA - Token Reauthentication', async ({ page }) => { .click(); await page.getByRole('cell', { name: tokenName }).waitFor(); }); + +/** + * Regression test: a user with an unverified email address who is forced to set up MFA + * must be offered a way to verify their email (instead of a broken QR code page). + * + * Ref: https://github.com/inventree/InvenTree/issues/13238 + */ +test('Login - MFA - Setup with unverified email', async ({ page }) => { + await doLogin(page, { user: noaccessuser }); + + const totpEndpoint = /auth\/v1\/account\/authenticators\/totp/; + const emailEndpoint = /auth\/v1\/account\/email/; + const unverified = `${noaccessuser.username}@example.org`; + const verificationRequests: string[] = []; + + // Simulate allauth refusing MFA registration due to an unverified email + await page.route(totpEndpoint, (route) => + route.fulfill({ + status: 409, + contentType: 'application/json', + body: JSON.stringify({ + status: 409, + errors: [ + { + code: 'unverified_email', + message: + 'You cannot add an authenticator until you have verified your email address.' + } + ] + }) + }) + ); + + await page.route(emailEndpoint, (route) => { + const request = route.request(); + + if (request.method() === 'PUT') { + verificationRequests.push(request.postDataJSON()?.email); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ status: 200 }) + }); + } + + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + status: 200, + data: [ + { email: 'verified@example.org', verified: true, primary: false }, + { email: unverified, verified: false, primary: true } + ] + }) + }); + }); + + await navigate(page, 'mfa-setup'); + + // The user is told why MFA setup is blocked, rather than shown an empty QR code + await page.getByLabel('mfa-unverified-email').waitFor(); + await page.getByText('Email verification required').waitFor(); + await expect(page.getByLabel('otp-secret-container')).toHaveCount(0); + + // Request a verification email - only unverified addresses are sent one + await page.getByRole('button', { name: 'mfa-send-verification' }).click(); + await page.getByText('Verification email sent').waitFor(); + expect(verificationRequests).toEqual([unverified]); + + // Once the email is verified, retrying shows the TOTP registration form + await page.unroute(totpEndpoint); + await page.route(totpEndpoint, (route) => + route.fulfill({ + status: 404, + contentType: 'application/json', + body: JSON.stringify({ + status: 404, + meta: { + secret: 'MOCKSECRET234567', + totp_url: 'otpauth://totp/InvenTree?secret=MOCKSECRET234567' + } + }) + }) + ); + + await page.getByRole('button', { name: 'mfa-retry-setup' }).click(); + await expect(page.getByLabel('otp-secret', { exact: true })).toHaveText( + 'MOCKSECRET234567' + ); + await expect(page.getByLabel('mfa-unverified-email')).toHaveCount(0); +});