mirror of
https://github.com/inventree/InvenTree.git
synced 2026-11-25 09:13:08 +00:00
* MFA workflow fixes - Fixes https://github.com/inventree/InvenTree/issues/13238 - Verify email on successful password reset - Invalidate password on account creation - Fix MFA workflows - Add regression tests * Update docs * Update OTP secret expectation to use exact match * Attempt to fix flaky test --------- Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
1 parent
d51720e8e1
commit
4210fc95a8
7 files changed
+386
-13
No files matched your search
@@ -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,
|
||||
|
||||
@@ -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<boolean>(false);
|
||||
const [sending, setSending] = useState<boolean>(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 (
|
||||
<Wrapper titleText={t`MFA Setup Required`} logOff>
|
||||
<Stack aria-label='mfa-unverified-email'>
|
||||
<Alert color='orange' title={t`Email verification required`}>
|
||||
<Text>
|
||||
<Trans>
|
||||
Your email address must be verified before multi-factor
|
||||
authentication can be set up.
|
||||
</Trans>
|
||||
</Text>
|
||||
<Text>
|
||||
<Trans>
|
||||
Send a verification email, follow the link it contains, then
|
||||
return here and try again.
|
||||
</Trans>
|
||||
</Text>
|
||||
</Alert>
|
||||
<Group justify='space-between'>
|
||||
<Button
|
||||
aria-label='mfa-send-verification'
|
||||
loading={sending}
|
||||
onClick={sendVerification}
|
||||
>
|
||||
<Trans>Send Verification Email</Trans>
|
||||
</Button>
|
||||
<Button
|
||||
aria-label='mfa-retry-setup'
|
||||
variant='outline'
|
||||
onClick={fetchSecret}
|
||||
>
|
||||
<Trans>Try Again</Trans>
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Wrapper>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Wrapper titleText={t`MFA Setup Required`} logOff>
|
||||
<QrRegistrationForm
|
||||
|
||||
@@ -433,6 +433,27 @@ test('Login - Change Password', async ({ page }) => {
|
||||
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);
|
||||
});
|
||||
Reference in new issue
Block a user