Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add user block checks to api and add tests (#342)
Leendert de Borst84b93924f5c5
diff --git a/src/AliasVault.Api/Controllers/AuthController.cs b/src/AliasVault.Api/Controllers/AuthController.csindex c7143e9d6..851694285 100644--- a/src/AliasVault.Api/Controllers/AuthController.cs+++ b/src/AliasVault.Api/Controllers/AuthController.cs@@ -60,9 +60,14 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFacprivate static readonly string[] InvalidRecoveryCode = ["Invalid recovery code."];/// <summary>- /// Error message for invalid 2-factor authentication recovery code.+ /// Error message for too many failed login attempts.+ /// </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>+ /// Error message for if user is (manually) blocked by admin./// </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.."];+ private static readonly string[] AccountBlocked = ["Your account has been disabled. If you believe this is a mistake, please contact support."];/// <summary>/// Semaphore to prevent concurrent access to the database when generating new tokens for a user.@@ -102,6 +107,13 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFacreturn BadRequest(ServerValidationErrorResponse.Create(AccountLocked, 400));}+ // Check if the account is blocked.+ if (user.Blocked)+ {+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.AccountBlocked);+ return BadRequest(ServerValidationErrorResponse.Create(AccountBlocked, 400));+ }+// Retrieve latest vault of user which contains the current salt and verifier.var latestVaultEncryptionSettings = AuthHelper.GetUserLatestVaultEncryptionSettings(user);@@ -262,6 +274,13 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFacreturn Unauthorized("User not found (name-2)");}+ // Check if the account is blocked.+ if (user.Blocked)+ {+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TokenRefresh, AuthFailureReason.AccountBlocked);+ return Unauthorized("Account blocked");+ }+// Generate new tokens for the user.var token = await GenerateNewTokensForUser(user, tokenModel.RefreshToken);if (token == null)@@ -603,6 +622,13 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFacreturn (null, null, BadRequest(ServerValidationErrorResponse.Create(AccountLocked, 400)));}+ // Check if the account is blocked.+ if (user.Blocked)+ {+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.AccountBlocked);+ return (null, null, BadRequest(ServerValidationErrorResponse.Create(AccountBlocked, 400)));+ }+// Validate the SRP session (actual password check).var serverSession = AuthHelper.ValidateSrpSession(cache, user, model.ClientPublicEphemeral, model.ClientSessionProof);if (serverSession is null)diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/Shard5/UserBlockedTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/Shard5/UserBlockedTests.csnew file mode 100644index 000000000..e65c72277--- /dev/null+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/Shard5/UserBlockedTests.cs@@ -0,0 +1,93 @@+//-----------------------------------------------------------------------+// <copyright file="UserBlockedTests.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.Shard5;++using Microsoft.EntityFrameworkCore;++/// <summary>+/// End-to-end tests for user block functionality.+/// </summary>+[Parallelizable(ParallelScope.Self)]+[Category("ClientTests")]+[TestFixture]+public class UserBlockedTests : ClientPlaywrightTest+{+ /// <summary>+ /// Test that a blocked user cannot log in.+ /// </summary>+ /// <returns>Async task.</returns>+ [Test]+ public async Task BlockedUserLoginTest()+ {+ // First logout the current user+ await Logout();++ // Find the current test user in the database and set their blocked status to true+ var user = await ApiDbContext.AliasVaultUsers.FirstAsync(x => x.UserName == TestUserUsername);+ user.Blocked = true;+ await ApiDbContext.SaveChangesAsync();++ // Attempt to log in with the blocked user's credentials+ await NavigateToLogin();++ // Try to log in with test credentials+ var emailField = await WaitForAndGetElement("input[id='email']");+ var passwordField = await WaitForAndGetElement("input[id='password']");+ await emailField.FillAsync(TestUserUsername);+ await passwordField.FillAsync(TestUserPassword);++ var loginButton = await WaitForAndGetElement("button[type='submit']");+ await loginButton.ClickAsync();++ // Check if we get an error message about the account being blocked+ await WaitForUrlAsync("user/login**", "Your account has been disabled");++ var pageContent = await Page.TextContentAsync("body");+ Assert.That(pageContent, Does.Contain("Your account has been disabled"), "No blocked account message shown when attempting to login with blocked account.");+ }++ /// <summary>+ /// Test that a blocked user gets logged out when their access token expires and cannot be refreshed.+ /// </summary>+ /// <returns>Async task.</returns>+ [Test]+ public async Task BlockedUserTokenRefreshTest()+ {+ // Make sure test user is not blocked.+ var user = await ApiDbContext.AliasVaultUsers.FirstAsync(x => x.UserName == TestUserUsername);+ user.Blocked = false;+ await ApiDbContext.SaveChangesAsync();++ // Make sure we're logged in.+ await Logout();+ await Login();++ // Wait for the index page to load which should show "Credentials" in the top menu.+ await WaitForUrlAsync("**", "Credentials");++ // First navigate to a test page to verify we're logged in+ await NavigateUsingBlazorRouter("test/1");+ await WaitForUrlAsync("test/1", "Test 1 OK");++ // Find the current test user in the database and set their blocked status to true+ user.Blocked = true;+ await ApiDbContext.SaveChangesAsync();++ // Increase the time by 1 hour to make the JWT token expire+ ApiTimeProvider.AdvanceBy(TimeSpan.FromHours(1));++ // Navigate to another test page which will trigger a token refresh attempt+ await NavigateUsingBlazorRouter("test/2");++ // We should be redirected to the login page with an error message+ await WaitForUrlAsync("user/login", "Log in to AliasVault");++ var pageContent = await Page.TextContentAsync("body");+ Assert.That(pageContent, Does.Contain("Log in to AliasVault"), "No login page shown after token refresh attempt with blocked account.");+ }+}