Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add E2E tests for account lockout for password, 2fa and recovery (#80)
Leendert de Borst95949508ba79
diff --git a/src/AliasVault.Api/Controllers/AuthController.cs b/src/AliasVault.Api/Controllers/AuthController.csindex 84c49022c..bacca317a 100644--- a/src/AliasVault.Api/Controllers/AuthController.cs+++ b/src/AliasVault.Api/Controllers/AuthController.cs@@ -56,6 +56,11 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac/// </summary>private static readonly string[] InvalidRecoveryCode = ["Invalid recovery code."];+ /// <summary>+ /// Error message for invalid 2-factor authentication recovery code.+ /// </summary>+ private static readonly string[] AccountLocked = ["You have entered an incorrect password too many times and your account has now been locked out. You can try again in 30 minutes.."];+/// <summary>/// Login endpoint used to process login attempt using credentials./// </summary>@@ -71,6 +76,13 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFacreturn BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400));}+ // Check if the account is locked out+ if (await userManager.IsLockedOutAsync(user))+ {+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.TwoFactorAuthentication, AuthFailureReason.AccountLocked);+ return BadRequest(ServerValidationErrorResponse.Create(AccountLocked, 400));+ }+// Server creates ephemeral and sends to clientvar ephemeral = Cryptography.Srp.GenerateEphemeralServer(user.Verifier);@@ -88,25 +100,28 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac[HttpPost("validate")]public async Task<IActionResult> Validate([FromBody] ValidateLoginRequest model){- var result = await ValidateSrpSession(model.Username, model.ClientPublicEphemeral, model.ClientSessionProof);- if (result is null)+ var (user, serverSession, error) = await ValidateUserAndPassword(model);+ if (error is not null){- await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.InvalidPassword);- return BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400));+ // Error occured during validation, return the error.+ return error;}await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.Login);- var (user, serverSession) = result.Value;// If 2FA is required, return that status and no JWT token yet.- if (user.TwoFactorEnabled)+ if (user!.TwoFactorEnabled){return Ok(new ValidateLoginResponse(true, string.Empty, null));}- // If 2FA is not required, return the JWT token immediately.+ // If 2FA is not required, then it means the user is successfully authenticated at this point.++ // Reset failed login attempts.+ await userManager.ResetAccessFailedCountAsync(user!);+var tokenModel = await GenerateNewTokensForUser(user);- return Ok(new ValidateLoginResponse(false, serverSession.Proof, tokenModel));+ return Ok(new ValidateLoginResponse(false, serverSession!.Proof, tokenModel));}/// <summary>@@ -117,28 +132,33 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac[HttpPost("validate-2fa")]public async Task<IActionResult> Validate2Fa([FromBody] ValidateLoginRequest2Fa model){- var result = await ValidateSrpSession(model.Username, model.ClientPublicEphemeral, model.ClientSessionProof);- if (result is null)+ var (user, serverSession, error) = await ValidateUserAndPassword(model);+ if (error is not null){- await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.InvalidPassword);- return BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400));+ // Error occured during validation, return the error.+ return error;}- var (user, serverSession) = result.Value;-// Verify 2-factor code.- var verifyResult = await userManager.VerifyTwoFactorTokenAsync(user, userManager.Options.Tokens.AuthenticatorTokenProvider, model.Code2Fa);+ var verifyResult = await userManager.VerifyTwoFactorTokenAsync(user!, userManager.Options.Tokens.AuthenticatorTokenProvider, model.Code2Fa);if (!verifyResult){+ // Increment failed login attempts in order to lock out the account when the limit is reached.+ await userManager.AccessFailedAsync(user!);+await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.TwoFactorAuthentication, AuthFailureReason.InvalidTwoFactorCode);return BadRequest(ServerValidationErrorResponse.Create(Invalid2FaCode, 400));}+ // Validation of 2-FA token is successful, user is authenticated.await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.TwoFactorAuthentication);+ // Reset failed login attempts.+ await userManager.ResetAccessFailedCountAsync(user!);+// Generate and return the JWT token.- var tokenModel = await GenerateNewTokensForUser(user);- return Ok(new ValidateLoginResponse(false, serverSession.Proof, tokenModel));+ var tokenModel = await GenerateNewTokensForUser(user!);+ return Ok(new ValidateLoginResponse(false, serverSession!.Proof, tokenModel));}/// <summary>@@ -149,31 +169,37 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac[HttpPost("validate-recovery-code")]public async Task<IActionResult> ValidateRecoveryCode([FromBody] ValidateLoginRequestRecoveryCode model){- var result = await ValidateSrpSession(model.Username, model.ClientPublicEphemeral, model.ClientSessionProof);- if (result is null)+ var (user, serverSession, error) = await ValidateUserAndPassword(model);+ if (error is not null){- return BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400));+ // Error occured during validation, return the error.+ return error;}- var (user, serverSession) = result.Value;-// Sanitize recovery code.var recoveryCode = model.RecoveryCode.Replace(" ", string.Empty).ToUpper();// Attempt to redeem the recovery code- var redeemResult = await userManager.RedeemTwoFactorRecoveryCodeAsync(user, recoveryCode);+ var redeemResult = await userManager.RedeemTwoFactorRecoveryCodeAsync(user!, recoveryCode);if (!redeemResult.Succeeded){+ // Increment failed login attempts in order to lock out the account when the limit is reached.+ await userManager.AccessFailedAsync(user!);+await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.TwoFactorAuthentication, AuthFailureReason.InvalidRecoveryCode);return BadRequest(ServerValidationErrorResponse.Create(InvalidRecoveryCode, 400));}+ // Recovery code is valid, user is authenticated.await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.TwoFactorAuthentication);+ // Reset failed login attempts.+ await userManager.ResetAccessFailedCountAsync(user!);+// Generate and return the JWT token.- var tokenModel = await GenerateNewTokensForUser(user);- return Ok(new ValidateLoginResponse(false, serverSession.Proof, tokenModel));+ var tokenModel = await GenerateNewTokensForUser(user!);+ return Ok(new ValidateLoginResponse(false, serverSession!.Proof, tokenModel));}/// <summary>@@ -377,6 +403,42 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFacreturn principal;}+ /// <summary>+ /// Validates the user and SRP session (password). If the user is not found or the password is invalid an+ /// action result is returned with the appropriate error message. If everything is valid nothing is returned.+ /// </summary>+ /// <param name="model">ValidateLoginRequest model.</param>+ /// <returns>User and SrpSession object if validation succeeded, IActionResult as error on error.</returns>+ private async Task<(AliasVaultUser? User, SrpSession? ServerSession, IActionResult? Error)> ValidateUserAndPassword(ValidateLoginRequest model)+ {+ var user = await userManager.FindByNameAsync(model.Username);+ if (user == null)+ {+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.InvalidUsername);+ return (null, null, BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400)));+ }++ // Check if the account is locked out+ if (await userManager.IsLockedOutAsync(user))+ {+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.TwoFactorAuthentication, AuthFailureReason.AccountLocked);+ return (null, null, BadRequest(ServerValidationErrorResponse.Create(AccountLocked, 400)));+ }++ // Validate the SRP session (actual password check).+ var serverSession = await ValidateSrpSession(model.Username, model.ClientPublicEphemeral, model.ClientSessionProof);+ if (serverSession is null)+ {+ // Increment failed login attempts in order to lock out the account when the limit is reached.+ await userManager.AccessFailedAsync(user);++ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.InvalidPassword);+ return (null, null, BadRequest(ServerValidationErrorResponse.Create(InvalidUsernameOrPasswordError, 400)));+ }++ return (user, serverSession, null);+ }+/// <summary>/// Helper method that validates the SRP session based on provided username, ephemeral and proof./// </summary>@@ -384,7 +446,7 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac/// <param name="clientEphemeral">The client ephemeral value.</param>/// <param name="clientSessionProof">The client session proof.</param>/// <returns>Tuple.</returns>- private async Task<(AliasVaultUser User, SrpSession ServerSession)?> ValidateSrpSession(string username, string clientEphemeral, string clientSessionProof)+ private async Task<SrpSession?> ValidateSrpSession(string username, string clientEphemeral, string clientSessionProof){var user = await userManager.FindByNameAsync(username);if (user == null)@@ -410,7 +472,7 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFacreturn null;}- return (user, serverSession);+ return serverSession;}/// <summary>diff --git a/src/Databases/AliasServerDb/AuthLog.cs b/src/Databases/AliasServerDb/AuthLog.csindex 6e6eb6c4e..02601dfe4 100644--- a/src/Databases/AliasServerDb/AuthLog.cs+++ b/src/Databases/AliasServerDb/AuthLog.cs@@ -8,6 +8,7 @@namespace AliasServerDb;using System.ComponentModel.DataAnnotations;+using System.ComponentModel.DataAnnotations.Schema;using AliasVault.Shared.Models.Enums;using Microsoft.EntityFrameworkCore;@@ -85,6 +86,7 @@ public class AuthLog/// Gets or sets the type of authentication event (e.g., Login, Logout, FailedLogin)./// </summary>[Required]+ [Column(TypeName = "nvarchar(50)")]public AuthEventType EventType { get; set; }/// <summary>diff --git a/src/Databases/AliasServerDb/Migrations/20240827205612_AddAuthLogTable.Designer.cs b/src/Databases/AliasServerDb/Migrations/20240830190840_AddAuthLogTable.Designer.cssimilarity index 99%rename from src/Databases/AliasServerDb/Migrations/20240827205612_AddAuthLogTable.Designer.csrename to src/Databases/AliasServerDb/Migrations/20240830190840_AddAuthLogTable.Designer.csindex d58053720..9f715d3e0 100644--- a/src/Databases/AliasServerDb/Migrations/20240827205612_AddAuthLogTable.Designer.cs+++ b/src/Databases/AliasServerDb/Migrations/20240830190840_AddAuthLogTable.Designer.cs@@ -11,7 +11,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion;namespace AliasServerDb.Migrations{[DbContext(typeof(AliasServerDbContext))]- [Migration("20240827205612_AddAuthLogTable")]+ [Migration("20240830190840_AddAuthLogTable")]partial class AddAuthLogTable{/// <inheritdoc />@@ -243,7 +243,7 @@ namespace AliasServerDb.Migrations.HasColumnType("TEXT");b.Property<int>("EventType")- .HasColumnType("INTEGER");+ .HasColumnType("nvarchar(50)");b.Property<int?>("FailureReason").HasColumnType("INTEGER");diff --git a/src/Databases/AliasServerDb/Migrations/20240827205612_AddAuthLogTable.cs b/src/Databases/AliasServerDb/Migrations/20240830190840_AddAuthLogTable.cssimilarity index 97%rename from src/Databases/AliasServerDb/Migrations/20240827205612_AddAuthLogTable.csrename to src/Databases/AliasServerDb/Migrations/20240830190840_AddAuthLogTable.csindex 65485cc6e..9a5357b61 100644--- a/src/Databases/AliasServerDb/Migrations/20240827205612_AddAuthLogTable.cs+++ b/src/Databases/AliasServerDb/Migrations/20240830190840_AddAuthLogTable.cs@@ -19,7 +19,7 @@ namespace AliasServerDb.Migrations.Annotation("Sqlite:Autoincrement", true),Timestamp = table.Column<DateTime>(type: "TEXT", nullable: false),Username = table.Column<string>(type: "TEXT", maxLength: 255, nullable: false),- EventType = table.Column<int>(type: "INTEGER", nullable: false),+ EventType = table.Column<int>(type: "nvarchar(50)", nullable: false),IsSuccess = table.Column<bool>(type: "INTEGER", nullable: false),FailureReason = table.Column<int>(type: "INTEGER", nullable: true),IpAddress = table.Column<string>(type: "TEXT", maxLength: 50, nullable: true),diff --git a/src/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs b/src/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.csindex d1986e50d..c215c2425 100644--- a/src/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs+++ b/src/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs@@ -240,7 +240,7 @@ namespace AliasServerDb.Migrations.HasColumnType("TEXT");b.Property<int>("EventType")- .HasColumnType("INTEGER");+ .HasColumnType("nvarchar(50)");b.Property<int?>("FailureReason").HasColumnType("INTEGER");diff --git a/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs b/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.csindex f06912f34..c56c00837 100644--- a/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs+++ b/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs@@ -164,7 +164,7 @@ public abstract class PlaywrightTest.First.WaitForAsync(new LocatorWaitForOptions{- Timeout = 300000,+ Timeout = 15000,State = WaitForSelectorState.Attached,});}diff --git a/src/Tests/AliasVault.E2ETests/Tests/Admin/TwoFactorLockoutTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Admin/TwoFactorAuthLockoutTests.cssimilarity index 96%rename from src/Tests/AliasVault.E2ETests/Tests/Admin/TwoFactorLockoutTests.csrename to src/Tests/AliasVault.E2ETests/Tests/Admin/TwoFactorAuthLockoutTests.csindex 17f31833f..be0aa3494 100644--- a/src/Tests/AliasVault.E2ETests/Tests/Admin/TwoFactorLockoutTests.cs+++ b/src/Tests/AliasVault.E2ETests/Tests/Admin/TwoFactorAuthLockoutTests.cs@@ -1,5 +1,5 @@//------------------------------------------------------------------------// <copyright file="TwoFactorLockoutTests.cs" company="lanedirt">+// <copyright file="TwoFactorAuthLockoutTests.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>@@ -13,7 +13,7 @@ namespace AliasVault.E2ETests.Tests.Admin;[Parallelizable(ParallelScope.Self)][Category("AdminTests")][TestFixture]-public class TwoFactorLockoutTests : AdminPlaywrightTest+public class TwoFactorAuthLockoutTests : AdminPlaywrightTest{/// <summary>/// Test if entering a wrong two-factor auth code too many times locks the account.diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/ApiLoggingTest.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/ApiLoggingTests.cssimilarity index 93%rename from src/Tests/AliasVault.E2ETests/Tests/Client/ApiLoggingTest.csrename to src/Tests/AliasVault.E2ETests/Tests/Client/ApiLoggingTests.csindex feb2f715c..cc312b0f7 100644--- a/src/Tests/AliasVault.E2ETests/Tests/Client/ApiLoggingTest.cs+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/ApiLoggingTests.cs@@ -1,5 +1,5 @@//------------------------------------------------------------------------// <copyright file="ApiLoggingTest.cs" company="lanedirt">+// <copyright file="ApiLoggingTests.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>@@ -15,7 +15,7 @@ using Microsoft.EntityFrameworkCore;[TestFixture][Category("ClientTests")][NonParallelizable]-public class ApiLoggingTest : ClientPlaywrightTest+public class ApiLoggingTests : ClientPlaywrightTest{/// <summary>/// Test if an error in the API is logged to the database.diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/AuthTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/AuthTests.csindex b174e0f7d..baf1720a1 100644--- a/src/Tests/AliasVault.E2ETests/Tests/Client/AuthTests.cs+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/AuthTests.cs@@ -20,6 +20,7 @@ public class AuthTests : ClientPlaywrightTest/// </summary>/// <returns>Async task.</returns>[Test]+ [Order(1)]public async Task LogoutAndLoginTest(){// Logout.@@ -37,6 +38,7 @@ public class AuthTests : ClientPlaywrightTest/// </summary>/// <returns>Async task.</returns>[Test]+ [Order(2)]public async Task RegisterFormWarningTest(){// Logout.@@ -71,6 +73,43 @@ public class AuthTests : ClientPlaywrightTestAssert.That(warning, Does.Contain("is already taken."), "No visible warning when registering with existing email address.");}+ /// <summary>+ /// Test if entering a wrong password too many times locks the account.+ /// </summary>+ /// <returns>Async task.</returns>+ [Test]+ [Order(3)]+ public async Task PasswordAuthLockoutTest()+ {+ // Logout.+ await NavigateUsingBlazorRouter("user/logout");+ await WaitForUrlAsync("user/login", "AliasVault");++ // Fill in wrong password 11 times. After 11 times, the account should be locked.+ // Note: the actual lockout happens on the 10th wrong attempt, but the lockout message is only displayed+ // on the next attempt, so we need to try 11 times to see the lockout message.+ for (var i = 0; i < 11; i++)+ {+ var emailField = Page.Locator("input[id='email']");+ var passwordField = Page.Locator("input[id='password']");+ await emailField.FillAsync(TestUserUsername);+ await passwordField.FillAsync("wrongpassword");++ var loginButton = Page.Locator("button[type='submit']");+ await loginButton.ClickAsync();++ if (i == 10)+ {+ break;+ }++ await WaitForUrlAsync("user/login**", "Invalid username or password.");+ }++ // Wait for account lockout message.+ await WaitForUrlAsync("user/login**", "locked out");+ }+/// <summary>/// Test if logging in works./// </summary>diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/CredentialTest.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/CredentialTests.cssimilarity index 98%rename from src/Tests/AliasVault.E2ETests/Tests/Client/CredentialTest.csrename to src/Tests/AliasVault.E2ETests/Tests/Client/CredentialTests.csindex 52d150d11..f97f5c34f 100644--- a/src/Tests/AliasVault.E2ETests/Tests/Client/CredentialTest.cs+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/CredentialTests.cs@@ -1,5 +1,5 @@//------------------------------------------------------------------------// <copyright file="CredentialTest.cs" company="lanedirt">+// <copyright file="CredentialTests.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>@@ -13,7 +13,7 @@ namespace AliasVault.E2ETests.Tests.Client;[TestFixture][Category("ClientTests")][Parallelizable(ParallelScope.Self)]-public class CredentialTest : ClientPlaywrightTest+public class CredentialTests : ClientPlaywrightTest{/// <summary>/// Test if the credential listing index page works.diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/DbPersistTest.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/DbPersistTests.cssimilarity index 94%rename from src/Tests/AliasVault.E2ETests/Tests/Client/DbPersistTest.csrename to src/Tests/AliasVault.E2ETests/Tests/Client/DbPersistTests.csindex b3ae1153f..831d2a50b 100644--- a/src/Tests/AliasVault.E2ETests/Tests/Client/DbPersistTest.cs+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/DbPersistTests.cs@@ -1,5 +1,5 @@//------------------------------------------------------------------------// <copyright file="DbPersistTest.cs" company="lanedirt">+// <copyright file="DbPersistTests.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>@@ -13,7 +13,7 @@ namespace AliasVault.E2ETests.Tests.Client;[TestFixture][Category("ClientTests")][NonParallelizable]-public class DbPersistTest : ClientPlaywrightTest+public class DbPersistTests : ClientPlaywrightTest{/// <summary>/// Test if a created credential is still present after a hard page refresh which causesdiff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/DbUpgradeTest.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/DbUpgradeTests.cssimilarity index 97%rename from src/Tests/AliasVault.E2ETests/Tests/Client/DbUpgradeTest.csrename to src/Tests/AliasVault.E2ETests/Tests/Client/DbUpgradeTests.csindex ce60bbfc8..b015ce639 100644--- a/src/Tests/AliasVault.E2ETests/Tests/Client/DbUpgradeTest.cs+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/DbUpgradeTests.cs@@ -1,5 +1,5 @@//------------------------------------------------------------------------// <copyright file="DbUpgradeTest.cs" company="lanedirt">+// <copyright file="DbUpgradeTests.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>@@ -15,7 +15,7 @@ using AliasServerDb;[TestFixture][Category("ClientTests")][NonParallelizable]-public class DbUpgradeTest : ClientPlaywrightTest+public class DbUpgradeTests : ClientPlaywrightTest{/// <summary>/// Gets or sets user email (override).diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/EmailDecryptionTest.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/EmailDecryptionTests.cssimilarity index 98%rename from src/Tests/AliasVault.E2ETests/Tests/Client/EmailDecryptionTest.csrename to src/Tests/AliasVault.E2ETests/Tests/Client/EmailDecryptionTests.csindex cdc364047..6909cfddc 100644--- a/src/Tests/AliasVault.E2ETests/Tests/Client/EmailDecryptionTest.cs+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/EmailDecryptionTests.cs@@ -1,5 +1,5 @@//------------------------------------------------------------------------// <copyright file="EmailDecryptionTest.cs" company="lanedirt">+// <copyright file="EmailDecryptionTests.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>@@ -20,7 +20,7 @@ using MimeKit;[TestFixture][Category("ClientTests")][NonParallelizable]-public class EmailDecryptionTest : ClientPlaywrightTest+public class EmailDecryptionTests : ClientPlaywrightTest{/// <summary>/// The test host instance.diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/GeneralSettingsTest.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/GeneralSettingsTests.cssimilarity index 93%rename from src/Tests/AliasVault.E2ETests/Tests/Client/GeneralSettingsTest.csrename to src/Tests/AliasVault.E2ETests/Tests/Client/GeneralSettingsTests.csindex 3dfefb4b5..832f736c9 100644--- a/src/Tests/AliasVault.E2ETests/Tests/Client/GeneralSettingsTest.cs+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/GeneralSettingsTests.cs@@ -1,5 +1,5 @@//------------------------------------------------------------------------// <copyright file="GeneralSettingsTest.cs" company="lanedirt">+// <copyright file="GeneralSettingsTests.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>@@ -13,7 +13,7 @@ namespace AliasVault.E2ETests.Tests.Client;[TestFixture][Category("ClientTests")][Parallelizable(ParallelScope.Self)]-public class GeneralSettingsTest : ClientPlaywrightTest+public class GeneralSettingsTests : ClientPlaywrightTest{/// <summary>/// Test if mutating the default email domain works.diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/SearchTest.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/SearchTests.cssimilarity index 95%rename from src/Tests/AliasVault.E2ETests/Tests/Client/SearchTest.csrename to src/Tests/AliasVault.E2ETests/Tests/Client/SearchTests.csindex 79f3899d9..2fa22c4d3 100644--- a/src/Tests/AliasVault.E2ETests/Tests/Client/SearchTest.cs+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/SearchTests.cs@@ -1,5 +1,5 @@//------------------------------------------------------------------------// <copyright file="SearchTest.cs" company="lanedirt">+// <copyright file="SearchTests.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>@@ -13,7 +13,7 @@ namespace AliasVault.E2ETests.Tests.Client;[TestFixture][Category("ClientTests")][Parallelizable(ParallelScope.Self)]-public class SearchTest : ClientPlaywrightTest+public class SearchTests : ClientPlaywrightTest{/// <summary>/// Test if the global search bar works.diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuth/Abstracts/TwoFactorAuthBase.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuth/Abstracts/TwoFactorAuthBase.csnew file mode 100644index 000000000..eb5abed41--- /dev/null+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuth/Abstracts/TwoFactorAuthBase.cs@@ -0,0 +1,114 @@+//-----------------------------------------------------------------------+// <copyright file="TwoFactorAuthBase.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.TwoFactorAuth.Abstracts;++/// <summary>+/// Abstract base class for two factor auth test which contains common methods.+/// </summary>+public class TwoFactorAuthBase : ClientPlaywrightTest+{+ /// <summary>+ /// Helper method to disable two factor authentication in the client GUI if it is enabled.+ /// </summary>+ /// <returns>Task.</returns>+ protected async Task DisableTwoFactorIfEnabled()+ {+ // Ensure that two factor auth is not enabled (in case the test is run after the previous test).+ await NavigateUsingBlazorRouter("settings/security");+ await WaitForUrlAsync("settings/security", "Two factor authentication is currently");++ // Check if two factor auth is enabled.+ var enableButton = Page.Locator("button:has-text('Enable Two-Factor Authentication')");+ var isTwoFactorAuthEnabled = await enableButton.IsVisibleAsync();+ if (!isTwoFactorAuthEnabled)+ {+ // Disable two factor auth.+ var disableButton = Page.Locator("button:has-text('Disable Two-Factor Authentication')");+ await disableButton.ClickAsync();++ // Wait for the confirm disable button to be displayed.+ var confirmButton = Page.Locator("button:has-text('Confirm Disable Two-Factor Authentication')");+ await confirmButton.WaitForAsync(new LocatorWaitForOptions+ {+ State = WaitForSelectorState.Visible,+ Timeout = 5000,+ });++ // Press the confirm disable button as well.+ await confirmButton.ClickAsync();++ // Check if the success message is displayed.+ var expectedMessage = "Two-factor authentication is now successfully disabled.";+ var successMessageLocator = Page.Locator($"div[role='alert']:has-text('{expectedMessage}')");+ await successMessageLocator.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 disabled."), "No two-factor auth disable success message displayed.");+ }+ }++ /// <summary>+ /// Helper method to enable two factor authentication in the client GUI.+ /// </summary>+ /// <returns>A tuple containing the TOTP code and the first recovery code.</returns>+ protected async Task<(string TotpCode, string RecoveryCode)> EnableTwoFactor()+ {+ // Setup two-factor auth.+ await NavigateUsingBlazorRouter("settings/security");+ await WaitForUrlAsync("settings/security", "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 recovery codes are displayed by id "recovery-codes"+ // wait for the recovery codes to be displayed.+ var recoveryCodesElement = Page.Locator("div[id='recovery-codes']");+ await recoveryCodesElement.WaitForAsync(new LocatorWaitForOptions+ {+ State = WaitForSelectorState.Visible,+ Timeout = 5000,+ });++ // Get the first recovery code.+ var recoveryCode = await Page.TextContentAsync("div[id='recovery-codes'] div:first-child");+ Assert.That(recoveryCode, Is.Not.Null.Or.Empty, "Recovery codes displayed but first value could not be extracted.");++ return (totpCode, recoveryCode!);+ }+}diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuth/CodeLockoutTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuth/CodeLockoutTests.csnew file mode 100644index 000000000..7fa35da00--- /dev/null+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuth/CodeLockoutTests.cs@@ -0,0 +1,67 @@+//-----------------------------------------------------------------------+// <copyright file="CodeLockoutTests.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.TwoFactorAuth;++using AliasVault.E2ETests.Tests.Client.TwoFactorAuth.Abstracts;++/// <summary>+/// End-to-end tests for user two-factor authentication code lockout behavior.+/// </summary>+[Parallelizable(ParallelScope.Self)]+[Category("ClientTests")]+[TestFixture]+public class CodeLockoutTests : TwoFactorAuthBase+{+ /// <summary>+ /// Test if entering a wrong two-factor auth code too many times locks the account.+ /// </summary>+ /// <returns>Async task.</returns>+ [Test]+ public async Task TwoFactorAuthLockoutTest()+ {+ await DisableTwoFactorIfEnabled();+ await EnableTwoFactor();++ // Logout.+ await NavigateUsingBlazorRouter("user/logout");+ await WaitForUrlAsync("user/login", "AliasVault");++ // Attempt to log in 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.");++ // Fill in wrong code 11 times. After 11 times, the account should be locked.+ // Note: the actual lockout happens on the 10th wrong attempt, but the lockout message is only displayed+ // on the next attempt, so we need to try 11 times to see the lockout message.+ for (var i = 0; i < 11; i++)+ {+ await Page.Locator("input[id='two-factor-code']").FillAsync("000000");+ var submitButton = Page.Locator("button[type='submit']");+ await submitButton.ClickAsync();++ if (i == 10)+ {+ break;+ }++ await WaitForUrlAsync("user/login**", "Invalid authenticator code.");+ }++ // Wait for account lockout message.+ await WaitForUrlAsync("user/login**", "locked out");+ }+}diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuth/RecoveryLockoutTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuth/RecoveryLockoutTests.csnew file mode 100644index 000000000..be78f6c64--- /dev/null+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuth/RecoveryLockoutTests.cs@@ -0,0 +1,71 @@+//-----------------------------------------------------------------------+// <copyright file="RecoveryLockoutTests.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.TwoFactorAuth;++using AliasVault.E2ETests.Tests.Client.TwoFactorAuth.Abstracts;++/// <summary>+/// End-to-end tests for user two-factor authentication recovery code lockout behavior.+/// </summary>+[Parallelizable(ParallelScope.Self)]+[Category("ClientTests")]+[TestFixture]+public class RecoveryLockoutTests : TwoFactorAuthBase+{+ /// <summary>+ /// Test if entering a wrong two-factor auth code too many times locks the account.+ /// </summary>+ /// <returns>Async task.</returns>+ [Test]+ public async Task TwoFactorAuthLockoutTest()+ {+ await DisableTwoFactorIfEnabled();+ await EnableTwoFactor();++ // Logout.+ await NavigateUsingBlazorRouter("user/logout");+ await WaitForUrlAsync("user/login", "AliasVault");++ // Attempt to log in 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.");++ // Click the "log in with a recovery code" button.+ var useRecoveryCodeButton = Page.Locator("button:has-text('log in with a recovery code')");+ await useRecoveryCodeButton.ClickAsync();++ // Fill in wrong recovery code 11 times. After 11 times, the account should be locked.+ // Note: the actual lockout happens on the 10th wrong attempt, but the lockout message is only displayed+ // on the next attempt, so we need to try 11 times to see the lockout message.+ for (var i = 0; i < 11; i++)+ {+ await Page.Locator("input[id='recovery-code']").FillAsync("000000");+ var submitButton = Page.Locator("button[type='submit']");+ await submitButton.ClickAsync();++ if (i == 10)+ {+ break;+ }++ await WaitForUrlAsync("user/login**", "Invalid recovery code.");+ }++ // Wait for account lockout message.+ await WaitForUrlAsync("user/login**", "locked out");+ }+}diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuth/TwoFactorAuthTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuth/TwoFactorAuthTests.csnew file mode 100644index 000000000..eca43afc9--- /dev/null+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuth/TwoFactorAuthTests.cs@@ -0,0 +1,109 @@+//-----------------------------------------------------------------------+// <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.TwoFactorAuth;++using AliasVault.E2ETests.Tests.Client.TwoFactorAuth.Abstracts;++/// <summary>+/// End-to-end tests for user two-factor authentication.+/// </summary>+[Parallelizable(ParallelScope.Self)]+[Category("ClientTests")]+[TestFixture]+public class TwoFactorAuthTests : TwoFactorAuthBase+{+ /// <summary>+ /// Test if setting up two-factor authentication and then logging in works.+ /// </summary>+ /// <returns>Async task.</returns>+ [Test]+ public async Task Setup2FactorAuthAndLogin()+ {+ await DisableTwoFactorIfEnabled();+ var (totpCode, _) = await EnableTwoFactor();++ // 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.");++ // Fill in the 2FA code and submit the form.+ var totpField = Page.Locator("input[id='two-factor-code']");+ await totpField.FillAsync(totpCode);++ var submitButton = Page.Locator("button[type='submit']");+ await submitButton.ClickAsync();++ // Check if we get redirected to the index page.+ await WaitForUrlAsync(AppBaseUrl, "Welcome to AliasVault");+ }++ /// <summary>+ /// Test if setting up two-factor authentication and then using a recovery code to login works.+ /// </summary>+ /// <returns>Async task.</returns>+ [Test]+ public async Task Setup2FactorAuthAndLoginWithRecoveryCode()+ {+ await DisableTwoFactorIfEnabled();+ var (_, recoveryCode) = await EnableTwoFactor();++ // Logout.+ await NavigateUsingBlazorRouter("user/logout");+ await WaitForUrlAsync("user/login", "AliasVault");++ // Attempt to log in 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.");++ // Click the "log in with a recovery code" button.+ var useRecoveryCodeButton = Page.Locator("button:has-text('log in with a recovery code')");+ await useRecoveryCodeButton.ClickAsync();++ // Fill in the recovery code and submit the form.+ var recoveryCodeField = Page.Locator("input[id='recovery-code']");+ await recoveryCodeField.FillAsync(recoveryCode);++ var submitButton = Page.Locator("button[type='submit']");+ await submitButton.ClickAsync();++ // Check if we get redirected to the index page.+ await WaitForUrlAsync(AppBaseUrl, "Welcome to AliasVault");+ }+}diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuthTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuthTests.csdeleted file mode 100644index 4c5b261f3..000000000--- a/src/Tests/AliasVault.E2ETests/Tests/Client/TwoFactorAuthTests.cs+++ /dev/null@@ -1,233 +0,0 @@-//------------------------------------------------------------------------// <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()- {- await DisableTwoFactorIfEnabled();-- // Setup two-factor auth.- await NavigateUsingBlazorRouter("settings/security");- await WaitForUrlAsync("settings/security", "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");- }-- /// <summary>- /// Test if setting up two-factor authentication and then using a recovery code to login works.- /// </summary>- /// <returns>Async task.</returns>- [Test]- public async Task Setup2FactorAuthAndLoginWithRecoveryCode()- {- await DisableTwoFactorIfEnabled();-- // Setup two-factor auth.- await NavigateUsingBlazorRouter("settings/security");- await WaitForUrlAsync("settings/security", "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 recovery codes are displayed by id "recovery-codes"- // wait for the recovery codes to be displayed.- var recoveryCodesElement = Page.Locator("div[id='recovery-codes']");- await recoveryCodesElement.WaitForAsync(new LocatorWaitForOptions- {- State = WaitForSelectorState.Visible,- Timeout = 5000,- });-- // Get the first recovery code.- var recoveryCode = await Page.TextContentAsync("div[id='recovery-codes'] div:first-child");- Assert.That(recoveryCode, Is.Not.Null.Or.Empty, "Recovery codes displayed but first value could not be extracted.");-- // 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.");-- // Click the "log in with a recovery code" button.- var useRecoveryCodeButton = Page.Locator("button:has-text('log in with a recovery code')");- await useRecoveryCodeButton.ClickAsync();-- // Fill in the recovery code and submit the form.- var recoveryCodeField = Page.Locator("input[id='recovery-code']");- await recoveryCodeField.FillAsync(recoveryCode);-- submitButton = Page.Locator("button[type='submit']");- await submitButton.ClickAsync();-- // Check if we get redirected to the index page.- await WaitForUrlAsync(AppBaseUrl, "Welcome to AliasVault");- }-- /// <summary>- /// Helper method to disable two factor authentication in the client GUI if it is enabled.- /// </summary>- private async Task DisableTwoFactorIfEnabled()- {- // Ensure that two factor auth is not enabled (in case the test is run after the previous test).- await NavigateUsingBlazorRouter("settings/security");- await WaitForUrlAsync("settings/security", "Two factor authentication is currently");-- // Check if two factor auth is enabled.- var enableButton = Page.Locator("button:has-text('Enable Two-Factor Authentication')");- var isTwoFactorAuthEnabled = await enableButton.IsVisibleAsync();- if (!isTwoFactorAuthEnabled)- {- // Disable two factor auth.- var disableButton = Page.Locator("button:has-text('Disable Two-Factor Authentication')");- await disableButton.ClickAsync();-- // Wait for the confirm disable button to be displayed.- var confirmButton = Page.Locator("button:has-text('Confirm Disable Two-Factor Authentication')");- await confirmButton.WaitForAsync(new LocatorWaitForOptions- {- State = WaitForSelectorState.Visible,- Timeout = 5000,- });-- // Press the confirm disable button as well.- await confirmButton.ClickAsync();-- // Check if the success message is displayed.- var expectedMessage = "Two-factor authentication is now successfully disabled.";- var successMessageLocator = Page.Locator($"div[role='alert']:has-text('{expectedMessage}')");- await successMessageLocator.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 disabled."), "No two-factor auth disable success message displayed.");- }- }-}