Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Improve two-factor auth setup and disable flow in web app (#2448)
Leendert de Borst2e717a36f06d
diff --git a/apps/server/AliasVault.Api/Controllers/V1/Security/TwoFactorAuthController.cs b/apps/server/AliasVault.Api/Controllers/V1/Security/TwoFactorAuthController.csindex 750248b95..0b174ff10 100644--- a/apps/server/AliasVault.Api/Controllers/V1/Security/TwoFactorAuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V1/Security/TwoFactorAuthController.cs@@ -12,6 +12,7 @@ using AliasServerDb;using AliasVault.Api.Controllers.Abstracts;using AliasVault.Auth;using AliasVault.Shared.Models.Enums;+using AliasVault.Shared.Models.WebApi;using Asp.Versioning;using Microsoft.AspNetCore.Identity;using Microsoft.AspNetCore.Mvc;@@ -57,22 +58,22 @@ public class TwoFactorAuthController(IDbContextFactory<AliasServerDbContext> dbCreturn Unauthorized();}- string? authenticatorKey;- authenticatorKey = await GetUserManager().GetAuthenticatorKeyAsync(user);+ if (await GetUserManager().GetTwoFactorEnabledAsync(user))+ {+ return BadRequest("Two-factor authentication is already enabled.");+ }- // Only reset (create new keys) if no key exists yet, avoiding duplicate key errors.- if (string.IsNullOrEmpty(authenticatorKey))+ // Create a new key on every call.+ string? authenticatorKey;+ try{- try- {- await GetUserManager().ResetAuthenticatorKeyAsync(user);- authenticatorKey = await GetUserManager().GetAuthenticatorKeyAsync(user);- }- catch (DbUpdateException)- {- // Key was most likely created by concurrent request, just get it.- authenticatorKey = await GetUserManager().GetAuthenticatorKeyAsync(user);- }+ await GetUserManager().ResetAuthenticatorKeyAsync(user);+ authenticatorKey = await GetUserManager().GetAuthenticatorKeyAsync(user);+ }+ catch (DbUpdateException)+ {+ // Key was most likely created by concurrent request, just get it.+ authenticatorKey = await GetUserManager().GetAuthenticatorKeyAsync(user);}var encodedKey = urlEncoder.Encode(authenticatorKey!);@@ -95,10 +96,23 @@ public class TwoFactorAuthController(IDbContextFactory<AliasServerDbContext> dbCreturn Unauthorized();}+ if (await GetUserManager().GetTwoFactorEnabledAsync(user))+ {+ return BadRequest("Two-factor authentication is already enabled.");+ }++ if (await GetUserManager().IsLockedOutAsync(user))+ {+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthEnable, AuthFailureReason.AccountLocked);+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_LOCKED, 400));+ }+var isValid = await GetUserManager().VerifyTwoFactorTokenAsync(user, GetUserManager().Options.Tokens.AuthenticatorTokenProvider, code);if (isValid){+ await GetUserManager().ResetAccessFailedCountAsync(user);+try{await GetUserManager().SetTwoFactorEnabledAsync(user, true);@@ -118,15 +132,18 @@ public class TwoFactorAuthController(IDbContextFactory<AliasServerDbContext> dbC}}- return BadRequest("Invalid code.");+ await GetUserManager().AccessFailedAsync(user);+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthEnable, AuthFailureReason.InvalidTwoFactorCode);+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_AUTHENTICATOR_CODE, 400));}/// <summary>- /// Disable two-factor authentication for a user.+ /// Disable two-factor authentication for a user, after checking a current authenticator code or a recovery code./// </summary>+ /// <param name="code">A current authenticator code or an unused recovery code.</param>/// <returns>Task.</returns>[HttpPost("disable")]- public async Task<IActionResult> Disable()+ public async Task<IActionResult> Disable([FromBody] string code){var user = await GetCurrentUserAsync();if (user is null)@@ -134,6 +151,32 @@ public class TwoFactorAuthController(IDbContextFactory<AliasServerDbContext> dbCreturn Unauthorized();}+ if (!await GetUserManager().GetTwoFactorEnabledAsync(user))+ {+ return BadRequest("Two-factor authentication is not enabled.");+ }++ if (await GetUserManager().IsLockedOutAsync(user))+ {+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthDisable, AuthFailureReason.AccountLocked);+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_LOCKED, 400));+ }++ var sanitizedCode = code.Replace(" ", string.Empty);+ var isAuthenticatorCode = sanitizedCode.Length == 6 && sanitizedCode.All(char.IsAsciiDigit);+ var isValid = isAuthenticatorCode+ ? await GetUserManager().VerifyTwoFactorTokenAsync(user, GetUserManager().Options.Tokens.AuthenticatorTokenProvider, sanitizedCode)+ : sanitizedCode.Length > 0 && (await GetUserManager().RedeemTwoFactorRecoveryCodeAsync(user, sanitizedCode.ToUpperInvariant())).Succeeded;++ if (!isValid)+ {+ await GetUserManager().AccessFailedAsync(user);+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthDisable, isAuthenticatorCode ? AuthFailureReason.InvalidTwoFactorCode : AuthFailureReason.InvalidRecoveryCode);+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(isAuthenticatorCode ? ApiErrorCode.INVALID_AUTHENTICATOR_CODE : ApiErrorCode.INVALID_RECOVERY_CODE, 400));+ }++ await GetUserManager().ResetAccessFailedCountAsync(user);+await using var context = await dbContextFactory.CreateDbContextAsync();var strategy = context.Database.CreateExecutionStrategy();diff --git a/apps/server/AliasVault.Api/Controllers/V2/Security/TwoFactorAuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/Security/TwoFactorAuthController.csindex 19a83be4d..85c174dba 100644--- a/apps/server/AliasVault.Api/Controllers/V2/Security/TwoFactorAuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/Security/TwoFactorAuthController.cs@@ -12,6 +12,7 @@ using AliasServerDb;using AliasVault.Api.Controllers.Abstracts;using AliasVault.Auth;using AliasVault.Shared.Models.Enums;+using AliasVault.Shared.Models.WebApi;using Asp.Versioning;using Microsoft.AspNetCore.Identity;using Microsoft.AspNetCore.Mvc;@@ -57,22 +58,22 @@ public class TwoFactorAuthController(IDbContextFactory<AliasServerDbContext> dbCreturn Unauthorized();}- string? authenticatorKey;- authenticatorKey = await GetUserManager().GetAuthenticatorKeyAsync(user);+ if (await GetUserManager().GetTwoFactorEnabledAsync(user))+ {+ return BadRequest("Two-factor authentication is already enabled.");+ }- // Only reset (create new keys) if no key exists yet, avoiding duplicate key errors.- if (string.IsNullOrEmpty(authenticatorKey))+ // Create a new key on every call.+ string? authenticatorKey;+ try{- try- {- await GetUserManager().ResetAuthenticatorKeyAsync(user);- authenticatorKey = await GetUserManager().GetAuthenticatorKeyAsync(user);- }- catch (DbUpdateException)- {- // Key was most likely created by concurrent request, just get it.- authenticatorKey = await GetUserManager().GetAuthenticatorKeyAsync(user);- }+ await GetUserManager().ResetAuthenticatorKeyAsync(user);+ authenticatorKey = await GetUserManager().GetAuthenticatorKeyAsync(user);+ }+ catch (DbUpdateException)+ {+ // Key was most likely created by concurrent request, just get it.+ authenticatorKey = await GetUserManager().GetAuthenticatorKeyAsync(user);}var encodedKey = urlEncoder.Encode(authenticatorKey!);@@ -95,10 +96,23 @@ public class TwoFactorAuthController(IDbContextFactory<AliasServerDbContext> dbCreturn Unauthorized();}+ if (await GetUserManager().GetTwoFactorEnabledAsync(user))+ {+ return BadRequest("Two-factor authentication is already enabled.");+ }++ if (await GetUserManager().IsLockedOutAsync(user))+ {+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthEnable, AuthFailureReason.AccountLocked);+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_LOCKED, 400));+ }+var isValid = await GetUserManager().VerifyTwoFactorTokenAsync(user, GetUserManager().Options.Tokens.AuthenticatorTokenProvider, code);if (isValid){+ await GetUserManager().ResetAccessFailedCountAsync(user);+try{await GetUserManager().SetTwoFactorEnabledAsync(user, true);@@ -118,15 +132,18 @@ public class TwoFactorAuthController(IDbContextFactory<AliasServerDbContext> dbC}}- return BadRequest("Invalid code.");+ await GetUserManager().AccessFailedAsync(user);+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthEnable, AuthFailureReason.InvalidTwoFactorCode);+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_AUTHENTICATOR_CODE, 400));}/// <summary>- /// Disable two-factor authentication for a user.+ /// Disable two-factor authentication for a user, after checking a current authenticator code or a recovery code./// </summary>+ /// <param name="code">A current authenticator code or an unused recovery code.</param>/// <returns>Task.</returns>[HttpPost("disable")]- public async Task<IActionResult> Disable()+ public async Task<IActionResult> Disable([FromBody] string code){var user = await GetCurrentUserAsync();if (user is null)@@ -134,6 +151,32 @@ public class TwoFactorAuthController(IDbContextFactory<AliasServerDbContext> dbCreturn Unauthorized();}+ if (!await GetUserManager().GetTwoFactorEnabledAsync(user))+ {+ return BadRequest("Two-factor authentication is not enabled.");+ }++ if (await GetUserManager().IsLockedOutAsync(user))+ {+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthDisable, AuthFailureReason.AccountLocked);+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_LOCKED, 400));+ }++ var sanitizedCode = code.Replace(" ", string.Empty);+ var isAuthenticatorCode = sanitizedCode.Length == 6 && sanitizedCode.All(char.IsAsciiDigit);+ var isValid = isAuthenticatorCode+ ? await GetUserManager().VerifyTwoFactorTokenAsync(user, GetUserManager().Options.Tokens.AuthenticatorTokenProvider, sanitizedCode)+ : sanitizedCode.Length > 0 && (await GetUserManager().RedeemTwoFactorRecoveryCodeAsync(user, sanitizedCode.ToUpperInvariant())).Succeeded;++ if (!isValid)+ {+ await GetUserManager().AccessFailedAsync(user);+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthDisable, isAuthenticatorCode ? AuthFailureReason.InvalidTwoFactorCode : AuthFailureReason.InvalidRecoveryCode);+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(isAuthenticatorCode ? ApiErrorCode.INVALID_AUTHENTICATOR_CODE : ApiErrorCode.INVALID_RECOVERY_CODE, 400));+ }++ await GetUserManager().ResetAccessFailedCountAsync(user);+await using var context = await dbContextFactory.CreateDbContextAsync();var strategy = context.Database.CreateExecutionStrategy();diff --git a/apps/web/src/pages/settings/security/Disable2Fa.tsx b/apps/web/src/pages/settings/security/Disable2Fa.tsxindex fc65fa26c..fdd0f9b65 100644--- a/apps/web/src/pages/settings/security/Disable2Fa.tsx+++ b/apps/web/src/pages/settings/security/Disable2Fa.tsx@@ -1,3 +1,4 @@+import { apiErrorMessage } from '@aliasvault/client/api/errors/ApiErrorMessage';import React, { useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { useNavigate } from 'react-router-dom';@@ -5,6 +6,7 @@ import { useNavigate } from 'react-router-dom';import AlertMessageError from '@/components/alerts/AlertMessageError';import LoadingIndicator from '@/components/loading/LoadingIndicator';import Breadcrumb from '@/components/shared/Breadcrumb';+import Button from '@/components/shared/Button';import Card from '@/components/shared/Card';import H1 from '@/components/shared/H1';import { useNotifications } from '@/context/NotificationContext';@@ -22,6 +24,7 @@ const Disable2Fa: React.FC = () => {usePageTitle(t('settings.securitySettings.disable2fa.pageTitle'));const [isLoading, setIsLoading] = useState(true);+ const [code, setCode] = useState('');const hasStarted = useRef(false);useEffect(() => {@@ -50,16 +53,17 @@ const Disable2Fa: React.FC = () => {}, [navigate, notifications, t, webApi]);/**- * Switch two-factor off.+ * Switch two-factor off after the server checked the authenticator or recovery code.*/- const disableTwoFactor = async (): Promise<void> => {+ const disableTwoFactor = async (e: React.FormEvent): Promise<void> => {+ e.preventDefault();try {- await webApi.post<null, unknown>('TwoFactorAuth/disable', null, false);+ await webApi.post<string, unknown>('TwoFactorAuth/disable', code.trim(), false);notifications.addSuccessMessage(t('settings.securitySettings.disable2fa.twoFactorDisabledSuccess'));navigate('/settings/security');} catch (error) {console.error('Failed to disable 2FA:', error);- notifications.addErrorMessage(t('settings.securitySettings.disable2fa.failedToDisable2Fa'), true);+ notifications.addErrorMessage(apiErrorMessage(error, t, t('settings.securitySettings.disable2fa.failedToDisable2Fa')), true);}};@@ -80,9 +84,10 @@ const Disable2Fa: React.FC = () => {<Card><AlertMessageError hasTopMargin={false} message={t('settings.securitySettings.disable2fa.warningMessage')} /><div className="mb-3 mt-4 text-sm text-gray-600 dark:text-gray-400">{t('settings.securitySettings.disable2fa.statusMessage')}</div>- <button type="button" onClick={() => void disableTwoFactor()} className="bg-red-500 text-white py-2 px-4 rounded-md hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 transition duration-150 ease-in-out">- {t('settings.securitySettings.disable2fa.confirmDisableButton')}- </button>+ <form onSubmit={disableTwoFactor} className="space-y-4" av-enable="true" av-suppress-save="true">+ <input id="disableCode" type="text" value={code} onChange={e => setCode(e.target.value)} className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400" placeholder={t('settings.securitySettings.enable2fa.verificationCodePlaceholder')} autoComplete="one-time-code" required />+ <Button type="submit" color="danger">{t('settings.securitySettings.disable2fa.confirmDisableButton')}</Button>+ </form></Card></>);diff --git a/apps/web/tests/e2e/08-two-factor.spec.ts b/apps/web/tests/e2e/08-two-factor.spec.tsnew file mode 100644index 000000000..f1597b342--- /dev/null+++ b/apps/web/tests/e2e/08-two-factor.spec.ts@@ -0,0 +1,152 @@+/**+ * Category 8: Two-factor authentication (requires API)+ */+import * as OTPAuth from 'otpauth';++import { test, expect, type WebApp } from '../fixtures';+import { postTwoFactorAuth } from '../helpers/test-api';++/**+ * The authenticator an enabled account is set up with, plus its recovery codes.+ */+type TwoFactorSetup = {+ totp: OTPAuth.TOTP;+ recoveryCodes: string[];+};++/**+ * Open the security settings page via the user menu; a full page load would lock the vault.+ */+async function openSecuritySettings(app: WebApp): Promise<void> {+ await app.page.locator('#toggleMobileMenuButton').click();+ await app.page.locator('#mobileMenuDropdown').getByRole('link', { name: 'Security settings' }).click();+ await expect(app.page).toHaveURL(/\/settings\/security$/);+}++/**+ * Enable two-factor authentication through the settings pages and return the authenticator and recovery codes.+ */+async function enableTwoFactor(app: WebApp): Promise<TwoFactorSetup> {+ const { page } = app;+ await openSecuritySettings(app);+ await page.getByRole('button', { name: 'Enable two-factor authentication', exact: true }).click();+ await expect(page).toHaveURL(/\/settings\/security\/enable-2fa$/);++ await expect(page.locator('#authenticator-uri img')).toBeVisible();+ const secret = (await page.locator('#authenticator-secret').innerText()).replace(/\s/g, '').toUpperCase();+ expect(secret).not.toBe('');+ const totp = new OTPAuth.TOTP({ secret: OTPAuth.Secret.fromBase32(secret) });++ await page.locator('#verificationCode').fill(totp.generate());+ await page.getByRole('button', { name: 'Verify and Enable' }).click();+ await expect(page.getByText('Two-factor authentication is now successfully enabled.')).toBeVisible();++ const codes = page.locator('#recovery-codes code');+ await expect(codes).toHaveCount(10);+ return { totp, recoveryCodes: await codes.allInnerTexts() };+}++/**+ * Log out and submit the login form, stopping at the two-factor step.+ */+async function loginUntilTwoFactor(app: WebApp, username: string, password: string): Promise<void> {+ await app.logout();+ await app.submitLogin(username, password);+ await expect(app.page.locator('#two-factor-code')).toBeVisible();+}++/**+ * Open the disable page and submit the given code, without waiting for the result.+ */+async function submitDisableCode(app: WebApp, code: string): Promise<void> {+ const { page } = app;+ if (!page.url().endsWith('/settings/security/disable-2fa')) {+ await openSecuritySettings(app);+ await page.getByRole('button', { name: 'Disable two-factor authentication', exact: true }).click();+ await expect(page).toHaveURL(/\/settings\/security\/disable-2fa$/);+ }+ await page.locator('#disableCode').fill(code);+ await page.getByRole('button', { name: 'Confirm Disable Two-Factor Authentication' }).click();+}++/**+ * Wait until two-factor is off and the security page offers to enable it again.+ */+async function expectTwoFactorDisabled(app: WebApp): Promise<void> {+ await expect(app.page).toHaveURL(/\/settings\/security$/);+ await expect(app.page.getByText('Two-factor authentication is now successfully disabled.')).toBeVisible();+ await expect(app.page.getByRole('button', { name: 'Enable two-factor authentication', exact: true })).toBeVisible();+}++/**+ * A code the authenticator does not produce right now.+ */+function wrongCode(totp: OTPAuth.TOTP): string {+ return String((Number(totp.generate()) + 500000) % 1000000).padStart(6, '0');+}++test.describe('8. Two-factor authentication', () => {+ test('8.1 should enable 2FA, log in with an authenticator code and disable it again', async ({ app, testUser, apiUrl }) => {+ const { page } = app;+ await app.login(testUser.username, testUser.password);+ const { totp } = await enableTwoFactor(app);++ await test.step('the API no longer hands out the key or restarts setup once 2FA is on', async () => {+ const enable = await postTwoFactorAuth(apiUrl, testUser.token, 'enable');+ expect(enable.status).toBe(400);+ expect(await enable.text()).not.toContain(totp.secret.base32);+ expect((await postTwoFactorAuth(apiUrl, testUser.token, 'verify', totp.generate())).status).toBe(400);+ });++ await test.step('the API refuses to disable 2FA without a code', async () => {+ expect((await postTwoFactorAuth(apiUrl, testUser.token, 'disable', '')).status).toBe(400);+ });++ await test.step('log in with an authenticator code', async () => {+ await loginUntilTwoFactor(app, testUser.username, testUser.password);+ await page.locator('#two-factor-code').fill(totp.generate());+ await page.getByRole('button', { name: 'Log in', exact: true }).click();+ await app.expectVaultOpen(testUser.username);+ });++ await test.step('a wrong authenticator code does not disable 2FA', async () => {+ await submitDisableCode(app, wrongCode(totp));+ await expect(page.getByText('Invalid authenticator code. Please try again.')).toBeVisible();+ await expect(page).toHaveURL(/\/settings\/security\/disable-2fa$/);+ });++ await test.step('a current authenticator code disables 2FA', async () => {+ await submitDisableCode(app, totp.generate());+ await expectTwoFactorDisabled(app);+ });++ await test.step('log in with only the password', async () => {+ await app.logout();+ await app.login(testUser.username, testUser.password);+ });+ });++ test('8.2 should log in with a recovery code and disable 2FA with another one', async ({ app, testUser }) => {+ const { page } = app;+ await app.login(testUser.username, testUser.password);+ const { recoveryCodes } = await enableTwoFactor(app);++ await test.step('log in with a recovery code', async () => {+ await loginUntilTwoFactor(app, testUser.username, testUser.password);+ await page.getByRole('button', { name: 'Log in with a recovery code instead.' }).click();+ await page.locator('#recovery-code').fill(recoveryCodes[0]);+ await page.getByRole('button', { name: 'Log in', exact: true }).click();+ await app.expectVaultOpen(testUser.username);+ });++ await test.step('a used recovery code does not disable 2FA', async () => {+ await submitDisableCode(app, recoveryCodes[0]);+ await expect(page.getByText('Invalid recovery code. Please try again.')).toBeVisible();+ });++ await test.step('an unused recovery code disables 2FA', async () => {+ await submitDisableCode(app, recoveryCodes[1]);+ await expectTwoFactorDisabled(app);+ });+ });+});diff --git a/apps/web/tests/helpers/test-api.ts b/apps/web/tests/helpers/test-api.tsindex fc3d55946..8e610988e 100644--- a/apps/web/tests/helpers/test-api.ts+++ b/apps/web/tests/helpers/test-api.ts@@ -128,3 +128,14 @@ export async function restoreLegacyVault(apiUrl: string, username: string, fixtuthrow new Error(`Restoring the legacy vault via ${url} failed with status ${response.status}: ${await response.text()}`);}}++/**+ * Call a TwoFactorAuth endpoint directly with the given access token.+ */+export async function postTwoFactorAuth(apiUrl: string, token: string, action: 'enable' | 'verify' | 'disable', body?: string): Promise<Response> {+ return fetch(`${WebApiService.versionedBaseUrl(apiUrl)}TwoFactorAuth/${action}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },+ body: body === undefined ? undefined : JSON.stringify(body),+ });+}