Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add E2E test for client two-factor auth setup (#70)
Leendert de Borste058990e319c
diff --git a/aliasvault.sln b/aliasvault.slnindex 9396197d1..958a75c9c 100644--- a/aliasvault.sln+++ b/aliasvault.sln@@ -51,6 +51,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AliasVault.RazorComponents"EndProjectProject("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AliasVault.WorkerStatus", "src\Utilities\AliasVault.WorkerStatus\AliasVault.WorkerStatus.csproj", "{951C3DF8-DF22-4B2B-839F-FBA26DDD8ABD}"EndProject+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TotpGenerator", "src\Utilities\TotpGenerator\TotpGenerator.csproj", "{E8D9C551-67D2-4651-8EDF-4262DF7375CE}"+EndProjectGlobalGlobalSection(SolutionConfigurationPlatforms) = preSolutionDebug|Any CPU = Debug|Any CPU@@ -133,6 +135,10 @@ Global{951C3DF8-DF22-4B2B-839F-FBA26DDD8ABD}.Debug|Any CPU.Build.0 = Debug|Any CPU{951C3DF8-DF22-4B2B-839F-FBA26DDD8ABD}.Release|Any CPU.ActiveCfg = Release|Any CPU{951C3DF8-DF22-4B2B-839F-FBA26DDD8ABD}.Release|Any CPU.Build.0 = Release|Any CPU+ {E8D9C551-67D2-4651-8EDF-4262DF7375CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU+ {E8D9C551-67D2-4651-8EDF-4262DF7375CE}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {E8D9C551-67D2-4651-8EDF-4262DF7375CE}.Release|Any CPU.ActiveCfg = Release|Any CPU+ {E8D9C551-67D2-4651-8EDF-4262DF7375CE}.Release|Any CPU.Build.0 = Release|Any CPUEndGlobalSectionGlobalSection(SolutionProperties) = preSolutionHideSolutionNode = FALSE@@ -153,6 +159,7 @@ Global{FF0B0E64-1AE2-415C-A404-0EB78010821A} = {01AB9389-2F89-4F8E-A688-BF4BF1FC42C8}{59642CEF-D90A-4A6B-AD3F-9C6300D1E3FC} = {01AB9389-2F89-4F8E-A688-BF4BF1FC42C8}{951C3DF8-DF22-4B2B-839F-FBA26DDD8ABD} = {01AB9389-2F89-4F8E-A688-BF4BF1FC42C8}+ {E8D9C551-67D2-4651-8EDF-4262DF7375CE} = {01AB9389-2F89-4F8E-A688-BF4BF1FC42C8}EndGlobalSectionGlobalSection(ExtensibilityGlobals) = postSolutionSolutionGuid = {FEE82475-C009-4762-8113-A6563D9DC49E}diff --git a/src/AliasVault.Client/Main/Pages/Settings/Totp.razor b/src/AliasVault.Client/Main/Pages/Settings/Totp.razorindex 216d017e8..1765ef83e 100644--- a/src/AliasVault.Client/Main/Pages/Settings/Totp.razor+++ b/src/AliasVault.Client/Main/Pages/Settings/Totp.razor@@ -15,7 +15,7 @@<p class="text-sm text-gray-600 text-center">Scan this QR code with your authenticator app or enter the following secret manually:</p>- <p class="text-lg font-mono text-center bg-gray-100 p-2 rounded">@Secret</p>+ <div class="text-lg font-mono text-center bg-gray-100 p-2 rounded" id="authenticator-secret">@Secret</div><EditForm Model="@VerifyModel" OnValidSubmit="@VerifySetup" class="space-y-4"><div>@@ -70,7 +70,7 @@// You might want to navigate the user or show a success messageGlobalNotificationService.AddSuccessMessage("Two-factor authentication is now successfully enabled. On your " +"next login you will need to enter your 2FA code.");- NavigationManager.NavigateTo("/credentials");+ NavigationManager.NavigateTo("/settings/general");}else{diff --git a/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj b/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csprojindex 60a00fd54..aace354ce 100644--- a/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj+++ b/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj@@ -50,6 +50,7 @@<ProjectReference Include="..\..\AliasVault.Admin\AliasVault.Admin.csproj" /><ProjectReference Include="..\..\AliasVault.Api\AliasVault.Api.csproj" /><ProjectReference Include="..\..\Databases\AliasServerDb\AliasServerDb.csproj" />+ <ProjectReference Include="..\..\Utilities\TotpGenerator\TotpGenerator.csproj" /><ProjectReference Include="..\AliasVault.IntegrationTests\AliasVault.IntegrationTests.csproj" /><ProjectReference Include="..\Server\AliasVault.E2ETests.Client.Server\AliasVault.E2ETests.Client.Server.csproj" /></ItemGroup>diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuthTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuthTests.csnew file mode 100644index 000000000..ee35c1c11--- /dev/null+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuthTests.cs@@ -0,0 +1,102 @@+//-----------------------------------------------------------------------+// <copyright file="TwoFactorAuthTests.cs" company="lanedirt">+// Copyright (c) lanedirt. All rights reserved.+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------++namespace AliasVault.E2ETests.Tests.Client;++/// <summary>+/// End-to-end tests for user two-factor authentication.+/// </summary>+[Parallelizable(ParallelScope.Self)]+[Category("ClientTests")]+[TestFixture]+public class TwoFactorAuthTests : ClientPlaywrightTest+{+ /// <summary>+ /// Test if setting up two factor authentication and then logging in works.+ /// </summary>+ /// <returns>Async task.</returns>+ [Test]+ public async Task Setup2FactorAuthAndLogin()+ {+ // Setup two factor auth.+ await NavigateUsingBlazorRouter("settings/totp");+ await WaitForUrlAsync("settings/totp", "Set Up Two-Factor Authentication");++ // Press the enable button with text "Enable Two-Factor Authentication"+ var enableButton = Page.Locator("button:has-text('Enable Two-Factor Authentication')");+ await enableButton.ClickAsync();++ // Wait for the secret to be displayed with ID "authenticator-secret"+ var secretElement = Page.Locator("div[id='authenticator-secret']");+ await secretElement.WaitForAsync(new LocatorWaitForOptions+ {+ State = WaitForSelectorState.Visible,+ Timeout = 5000,+ });++ var secret = await Page.TextContentAsync("div[id='authenticator-secret']");+ Assert.That(secret, Is.Not.Null.Or.Empty, "No secret displayed.");++ // Verify that a QR code image is displayed: #qrcode-authenticator-uri > img+ var qrCode = await Page.Locator("#qrcode-authenticator-uri img").GetAttributeAsync("src");+ Assert.That(qrCode, Does.Contain("data:image/png;base64"), "No QR code displayed.");++ // Generate a 2FA code using the secret.+ var totpCode = TotpGenerator.TotpGenerator.GenerateTotpCode(secret);+ Assert.That(totpCode, Is.Not.Null.Or.Empty, "No 2FA code generated.");++ // Fill in the 2FA code and submit the form.+ var totpField = Page.Locator("input[id='verificationCode']");+ await totpField.FillAsync(totpCode);++ var submitButton = Page.Locator("button:has-text('Verify and Enable')");+ await submitButton.ClickAsync();++ // Check if the success message is displayed.+ var successMessage = Page.Locator("div[role='alert']");+ await successMessage.WaitForAsync(new LocatorWaitForOptions+ {+ State = WaitForSelectorState.Visible,+ Timeout = 5000,+ });+ var message = await Page.TextContentAsync("div[role='alert']");+ Assert.That(message, Does.Contain("Two-factor authentication is now successfully enabled."), "No success message displayed.");++ // Logout.+ await NavigateUsingBlazorRouter("user/logout");+ await WaitForUrlAsync("user/login", "AliasVault");++ // Attempt to login again with test credentials.+ var emailField = Page.Locator("input[id='email']");+ var passwordField = Page.Locator("input[id='password']");+ await emailField.FillAsync(TestUserUsername);+ await passwordField.FillAsync(TestUserPassword);++ var loginButton = Page.Locator("button[type='submit']");+ await loginButton.ClickAsync();++ // Check if we get a 2FA code prompt by checking for text "Authenticator code".+ var prompt = await Page.TextContentAsync("label:has-text('Authenticator code')");+ Assert.That(prompt, Does.Contain("Authenticator code"), "No 2FA code prompt displayed.");++ // Generate a 2FA code using the secret.+ totpCode = TotpGenerator.TotpGenerator.GenerateTotpCode(secret);+ Assert.That(totpCode, Is.Not.Null.Or.Empty, "No 2FA code generated.");++ // Fill in the 2FA code and submit the form.+ totpField = Page.Locator("input[id='two-factor-code']");+ await totpField.FillAsync(totpCode);++ submitButton = Page.Locator("button[type='submit']");+ await submitButton.ClickAsync();++ // Check if we get redirected to the index page.+ await WaitForUrlAsync(AppBaseUrl, "Welcome to AliasVault");++ await Task.Delay(5000);+ }+}diff --git a/src/Utilities/TotpGenerator/TotpGenerator.cs b/src/Utilities/TotpGenerator/TotpGenerator.csnew file mode 100644index 000000000..7d74357c6--- /dev/null+++ b/src/Utilities/TotpGenerator/TotpGenerator.cs@@ -0,0 +1,62 @@+//-----------------------------------------------------------------------+// <copyright file="TotpGenerator.cs" company="lanedirt">+// Copyright (c) lanedirt. All rights reserved.+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------++namespace TotpGenerator;++using OtpNet;++/// <summary>+/// Helper class to generate time based one-time passwords.+/// </summary>+public class TotpGenerator+{+ /// <summary>+ /// Generates a Time-based One-Time Password (TOTP) for the given secret key.+ /// </summary>+ /// <param name="secretKey">The secret key in Base32 encoding.</param>+ /// <param name="digits">The number of digits in the generated code. Default is 6.</param>+ /// <param name="step">The time step in seconds. Default is 30.</param>+ /// <returns>The generated TOTP code.</returns>+ public static string GenerateTotpCode(string secretKey, int digits = 6, int step = 30)+ {+ // Remove any whitespace and hyphens from the secret key+ secretKey = secretKey.Replace(" ", string.Empty).Replace("-", string.Empty);++ // Convert the secret key from Base32 to byte array+ byte[] keyBytes = Base32Encoding.ToBytes(secretKey);++ // Create a new TOTP instance+ var totp = new Totp(keyBytes, step: step, totpSize: digits);++ // Generate and return the current TOTP code+ return totp.ComputeTotp();+ }++ /// <summary>+ /// Verifies a given TOTP code against the secret key.+ /// </summary>+ /// <param name="secretKey">The secret key in Base32 encoding.</param>+ /// <param name="totpCode">The TOTP code to verify.</param>+ /// <param name="digits">The number of digits in the code. Default is 6.</param>+ /// <param name="step">The time step in seconds. Default is 30.</param>+ /// <param name="timeWindowOffset">The time window offset for verification. Default is 1 (allows 1 step before and after).</param>+ /// <returns>True if the code is valid, false otherwise.</returns>+ public static bool VerifyTotpCode(string secretKey, string totpCode, int digits = 6, int step = 30, int timeWindowOffset = 1)+ {+ // Remove any whitespace and hyphens from the secret key+ secretKey = secretKey.Replace(" ", string.Empty).Replace("-", string.Empty);++ // Convert the secret key from Base32 to byte array+ byte[] keyBytes = Base32Encoding.ToBytes(secretKey);++ // Create a new TOTP instance+ var totp = new Totp(keyBytes, step: step, totpSize: digits);++ // Verify the TOTP code+ return totp.VerifyTotp(totpCode, out _, new VerificationWindow(previous: timeWindowOffset, future: timeWindowOffset));+ }+}diff --git a/src/Utilities/TotpGenerator/TotpGenerator.csproj b/src/Utilities/TotpGenerator/TotpGenerator.csprojnew file mode 100644index 000000000..ea4f23bc5--- /dev/null+++ b/src/Utilities/TotpGenerator/TotpGenerator.csproj@@ -0,0 +1,31 @@+<Project Sdk="Microsoft.NET.Sdk">++ <PropertyGroup>+ <TargetFramework>net8.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ </PropertyGroup>++ <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">+ <TreatWarningsAsErrors>true</TreatWarningsAsErrors>+ </PropertyGroup>++ <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">+ <TreatWarningsAsErrors>true</TreatWarningsAsErrors>+ </PropertyGroup>++ <ItemGroup>+ <PackageReference Include="Otp.NET" Version="1.4.0" />+ <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556">+ <PrivateAssets>all</PrivateAssets>+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>+ </PackageReference>+ </ItemGroup>++ <ItemGroup>+ <AdditionalFiles Include="..\..\stylecop.json">+ <Link>stylecop.json</Link>+ </AdditionalFiles>+ </ItemGroup>++</Project>