Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add account registration limit per 24 hours setting (#1940)
Leendert de Borst1fec6f4a5b05
diff --git a/apps/server/AliasVault.Admin/Main/Pages/Settings/Server.razor b/apps/server/AliasVault.Admin/Main/Pages/Settings/Server.razorindex a19dee2e8..fded7b6d1 100644--- a/apps/server/AliasVault.Admin/Main/Pages/Settings/Server.razor+++ b/apps/server/AliasVault.Admin/Main/Pages/Settings/Server.razor@@ -32,6 +32,11 @@<input type="number" @bind="Settings.RefreshTokenLifetimeLong" id="refreshTokenLong" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500"><p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Determines how long the user stays logged in after inactivity. Used when "Remember me" is checked during login.</p></div>+ <div>+ <label for="maxRegistrationsPerIp" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Max Registrations per IP per 24 Hours</label>+ <input type="number" @bind="Settings.MaxRegistrationsPerIpPer24Hours" id="maxRegistrationsPerIp" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500">+ <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Maximum number of new account registrations allowed from a single IP address (/24 range) within a 24 hour period. Set to 0 to disable rate limiting. Recommended: 5-10 for most deployments.</p>+ </div></div></div>diff --git a/apps/server/AliasVault.Admin/Services/StatisticsService.cs b/apps/server/AliasVault.Admin/Services/StatisticsService.csindex 3c1227893..745ed1986 100644--- a/apps/server/AliasVault.Admin/Services/StatisticsService.cs+++ b/apps/server/AliasVault.Admin/Services/StatisticsService.cs@@ -9,6 +9,7 @@ namespace AliasVault.Admin.Services;using AliasServerDb;using AliasVault.Admin.Main.Models;+using AliasVault.Auth;using AliasVault.Shared.Models.Enums;using Microsoft.EntityFrameworkCore;@@ -401,7 +402,7 @@ public class StatisticsServicereturn ipAddress[..lastColonIndex] + ":xxx";}- return "xxx.xxx.xxx.xxx";+ return IpAddressUtility.AnonymizedIp;}/// <summary>@@ -446,7 +447,7 @@ public class StatisticsService/// <summary>/// Gets the top 10 IP address ranges by number of associated user accounts.- /// Only includes non-anonymized IPs (not "xxx.xxx.xxx.xxx").+ /// Only includes non-anonymized IPs./// </summary>/// <returns>List of top IP addresses.</returns>private async Task<List<TopIpAddress>> GetTopIpAddressesAsync()@@ -455,7 +456,7 @@ public class StatisticsService// Get distinct IP addresses from successful auth logs only, excluding fully anonymized onesvar ipStats = await context.AuthLogs- .Where(al => al.IpAddress != null && al.IpAddress != "xxx.xxx.xxx.xxx" && al.IsSuccess)+ .Where(al => al.IpAddress != null && al.IpAddress != IpAddressUtility.AnonymizedIp && al.IsSuccess).GroupBy(al => al.IpAddress).Select(g => new{@@ -557,7 +558,7 @@ public class StatisticsServicevar topIps = await context.AuthLogs.Where(al => al.Timestamp >= cutoffDate &&al.IpAddress != null &&- al.IpAddress != "xxx.xxx.xxx.xxx" &&+ al.IpAddress != IpAddressUtility.AnonymizedIp &&al.IsSuccess &&al.EventType == AuthEventType.Register).GroupBy(al => al.IpAddress)@@ -591,7 +592,7 @@ public class StatisticsServicevar topIps = await context.MobileLoginRequests.Where(mlr => mlr.CreatedAt >= cutoffDate &&mlr.ClientIpAddress != null &&- mlr.ClientIpAddress != "xxx.xxx.xxx.xxx")+ mlr.ClientIpAddress != IpAddressUtility.AnonymizedIp).GroupBy(mlr => mlr.ClientIpAddress).Select(g => new{@@ -623,7 +624,7 @@ public class StatisticsServicevar topIps = await context.AuthLogs.Where(al => al.Timestamp >= cutoffDate &&al.IpAddress != null &&- al.IpAddress != "xxx.xxx.xxx.xxx" &&+ al.IpAddress != IpAddressUtility.AnonymizedIp &&al.IsSuccess &&al.EventType == AuthEventType.AccountDeletion).GroupBy(al => al.IpAddress)diff --git a/apps/server/AliasVault.Api/Controllers/AuthController.cs b/apps/server/AliasVault.Api/Controllers/AuthController.csindex 8f4c6f266..e0bd3a96f 100644--- a/apps/server/AliasVault.Api/Controllers/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/AuthController.cs@@ -45,10 +45,11 @@ using SecureRemotePassword;/// <param name="authLoggingService">AuthLoggingService instance. This is used to log auth attempts to the database.</param>/// <param name="config">Config instance.</param>/// <param name="settingsService">ServerSettingsService instance.</param>+/// <param name="registrationRateLimitService">RegistrationRateLimitService instance.</param>[Route("v{version:apiVersion}/[controller]")][ApiController][ApiVersion("1")]-public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, SignInManager<AliasVaultUser> signInManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService) : ControllerBase+public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, SignInManager<AliasVaultUser> signInManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, RegistrationRateLimitService registrationRateLimitService) : ControllerBase{/// <summary>/// Timeout in minutes for mobile login requests. Clients use 2 minutes for countdown, we use 3 here to give a bit of extra buffer time.@@ -455,6 +456,15 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMreturn BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PUBLIC_REGISTRATION_DISABLED, 400));}+ // Check IP-based registration rate limit+ var settings = await settingsService.GetAllSettingsAsync();+ var ipAddress = IpAddressUtility.GetIpFromContext(HttpContext, config.IpLoggingEnabled);+ if (await registrationRateLimitService.IsRateLimitExceededAsync(ipAddress, settings.MaxRegistrationsPerIpPer24Hours))+ {+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Register, AuthFailureReason.RegistrationRateLimitExceeded);+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.REGISTRATION_RATE_LIMIT_EXCEEDED, 429));+ }+// Validate the username.var (isValid, apiErrorCode) = await ValidateUsername(model.Username);if (!isValid)@@ -642,7 +652,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMId = requestId,ClientPublicKey = model.ClientPublicKey,CreatedAt = timeProvider.UtcNow,- ClientIpAddress = IpAddressUtility.GetIpFromContext(HttpContext),+ ClientIpAddress = IpAddressUtility.GetIpFromContext(HttpContext, config.IpLoggingEnabled),};context.MobileLoginRequests.Add(loginRequest);@@ -813,7 +823,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMloginRequest.EncryptedDecryptionKey = model.EncryptedDecryptionKey;loginRequest.UserId = user.Id;loginRequest.FulfilledAt = timeProvider.UtcNow;- loginRequest.MobileIpAddress = IpAddressUtility.GetIpFromContext(HttpContext);+ loginRequest.MobileIpAddress = IpAddressUtility.GetIpFromContext(HttpContext, config.IpLoggingEnabled);await context.SaveChangesAsync();@@ -1164,7 +1174,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM{UserId = user.Id,DeviceIdentifier = deviceIdentifier,- IpAddress = IpAddressUtility.GetIpFromContext(HttpContext),+ IpAddress = IpAddressUtility.GetIpFromContext(HttpContext, config.IpLoggingEnabled),Value = refreshToken,PreviousTokenValue = existingTokenValue,ExpireDate = timeProvider.UtcNow.Add(newTokenLifetime),diff --git a/apps/server/AliasVault.Api/Program.cs b/apps/server/AliasVault.Api/Program.csindex f597e42fc..6da98ce12 100644--- a/apps/server/AliasVault.Api/Program.cs+++ b/apps/server/AliasVault.Api/Program.cs@@ -68,6 +68,7 @@ builder.Services.AddSingleton<ITimeProvider, SystemTimeProvider>();builder.Services.AddScoped<TimeValidationJwtBearerEvents>();builder.Services.AddScoped<AuthLoggingService>();builder.Services.AddScoped<ServerSettingsService>();+builder.Services.AddScoped<RegistrationRateLimitService>();builder.Services.AddHttpContextAccessor();builder.Services.AddLogging(logging =>diff --git a/apps/server/Databases/AliasServerDb/AuthLog.cs b/apps/server/Databases/AliasServerDb/AuthLog.csindex 7a7738710..33f890626 100644--- a/apps/server/Databases/AliasServerDb/AuthLog.cs+++ b/apps/server/Databases/AliasServerDb/AuthLog.cs@@ -52,6 +52,11 @@ public enum AuthFailureReason/// </summary>AccountBlocked = 7,+ /// <summary>+ /// Indicates that the registration attempt was blocked due to IP-based rate limiting.+ /// </summary>+ RegistrationRateLimitExceeded = 8,+/// <summary>/// Indicates that the failure reason was unknown./// </summary>diff --git a/apps/server/Shared/AliasVault.Shared.Server/Models/ServerSettingsModel.cs b/apps/server/Shared/AliasVault.Shared.Server/Models/ServerSettingsModel.csindex 6cbe217f2..b7d7afd7f 100644--- a/apps/server/Shared/AliasVault.Shared.Server/Models/ServerSettingsModel.cs+++ b/apps/server/Shared/AliasVault.Shared.Server/Models/ServerSettingsModel.cs@@ -78,4 +78,10 @@ public class ServerSettingsModel/// Used when "Remember me" is checked./// </summary>public int RefreshTokenLifetimeLong { get; set; } = 336;++ /// <summary>+ /// Gets or sets the maximum number of registrations allowed per IP address (/24 range) within 24 hours. Defaults to 5.+ /// Set to 0 to disable IP-based registration rate limiting.+ /// </summary>+ public int MaxRegistrationsPerIpPer24Hours { get; set; } = 5;}diff --git a/apps/server/Shared/AliasVault.Shared.Server/Services/ServerSettingsService.cs b/apps/server/Shared/AliasVault.Shared.Server/Services/ServerSettingsService.csindex 49130d037..4fa8217ae 100644--- a/apps/server/Shared/AliasVault.Shared.Server/Services/ServerSettingsService.cs+++ b/apps/server/Shared/AliasVault.Shared.Server/Services/ServerSettingsService.cs@@ -170,6 +170,16 @@ public class ServerSettingsService(IAliasServerDbContextFactory dbContextFactorymodel.RefreshTokenLifetimeLong = longLifetime;}+ if (int.TryParse(settings.GetValueOrDefault("MaxRegistrationsPerIpPer24Hours"), out var maxRegistrations))+ {+ model.MaxRegistrationsPerIpPer24Hours = maxRegistrations;+ }++ if (int.TryParse(settings.GetValueOrDefault("MobileLoginLogRetentionDays"), out var mobileLoginDays))+ {+ model.MobileLoginLogRetentionDays = mobileLoginDays;+ }+return model;}@@ -191,5 +201,7 @@ public class ServerSettingsService(IAliasServerDbContextFactory dbContextFactoryawait SetSettingAsync("TaskRunnerDays", string.Join(",", model.TaskRunnerDays));await SetSettingAsync("RefreshTokenLifetimeShort", model.RefreshTokenLifetimeShort.ToString());await SetSettingAsync("RefreshTokenLifetimeLong", model.RefreshTokenLifetimeLong.ToString());+ await SetSettingAsync("MaxRegistrationsPerIpPer24Hours", model.MaxRegistrationsPerIpPer24Hours.ToString());+ await SetSettingAsync("MobileLoginLogRetentionDays", model.MobileLoginLogRetentionDays.ToString());}}diff --git a/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs b/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.csindex 137b0c5a4..9074f0061 100644--- a/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs@@ -143,4 +143,9 @@ public enum ApiErrorCode/// Mobile login request already fulfilled./// </summary>MOBILE_LOGIN_REQUEST_ALREADY_FULFILLED,++ /// <summary>+ /// Registration rate limit exceeded for this IP address.+ /// </summary>+ REGISTRATION_RATE_LIMIT_EXCEEDED,}diff --git a/apps/server/Tests/AliasVault.E2ETests/Tests/Client/Shard4/AuthTests.cs b/apps/server/Tests/AliasVault.E2ETests/Tests/Client/Shard4/AuthTests.csindex 3f99259aa..2a5e52bc4 100644--- a/apps/server/Tests/AliasVault.E2ETests/Tests/Client/Shard4/AuthTests.cs+++ b/apps/server/Tests/AliasVault.E2ETests/Tests/Client/Shard4/AuthTests.cs@@ -7,6 +7,7 @@namespace AliasVault.E2ETests.Tests.Client.Shard4;+using AliasVault.Auth;using AliasVault.Shared.Core;using AliasVault.Shared.Models.Enums;using Microsoft.EntityFrameworkCore;@@ -34,7 +35,7 @@ public class AuthTests : ClientPlaywrightTest// Check if the IP address is not anonymized as IP logging is disabled by default.// The opposite of this is tested in the IP logging test in ApiTests.cs.- Assert.That(authLogEntry.IpAddress, Is.EqualTo("xxx.xxx.xxx.xxx"), "Auth log entry IP address is not anonymized while IP logging should be disabled. Check test configuration.");+ Assert.That(authLogEntry.IpAddress, Is.EqualTo(IpAddressUtility.AnonymizedIp), "Auth log entry IP address is not anonymized while IP logging should be disabled. Check test configuration.");// Check if the refresh token is stored in the database and its expiration date is set to the long lifetime// after registration. The registration page does not have a "Remember me" checkbox, but it is assumed that@@ -322,4 +323,75 @@ public class AuthTests : ClientPlaywrightTestAssert.That(authLogEntry.Client, Does.Contain("web-" + currentVersion), "Auth log client header does not contain expected value.");});}++ /// <summary>+ /// Test that registration rate limiting works correctly.+ /// </summary>+ /// <returns>Async task.</returns>+ [Test]+ [Order(8)]+ public async Task RegistrationRateLimitingTest()+ {+ // Set the registration rate limit to 2 accounts per IP per 24 hours+ await ApiServerSettings.SetSettingAsync("MaxRegistrationsPerIpPer24Hours", "2");++ // Logout the current test user+ await Logout();++ // Register first account+ var user1 = "[email protected]";+ await Register(checkForSuccess: true, username: user1);+ await Logout();++ // Register second account+ var user2 = "[email protected]";+ await Register(checkForSuccess: true, username: user2);+ await Logout();++ // Attempt to register third account - should be blocked by rate limit+ var user3 = "[email protected]";+ await NavigateToRegistration();++ var emailField = await WaitForAndGetElement("input[id='email']");+ var passwordField = await WaitForAndGetElement("input[id='password']");+ var confirmPasswordField = await WaitForAndGetElement("input[id='confirm-password']");++ await emailField.FillAsync(user3);+ await passwordField.FillAsync(TestUserPassword);+ await confirmPasswordField.FillAsync(TestUserPassword);++ var registerButton = await WaitForAndGetElement("button[type='submit']");+ await registerButton.ClickAsync();++ // Wait for rate limit error message+ await Task.Delay(1000);+ var pageContent = await Page.TextContentAsync("body");++ // Check that registration was blocked (should still be on registration page with error)+ Assert.That(await Page.UrlAsync(), Does.Contain("user/register"), "Should still be on registration page after rate limit exceeded.");++ // Verify that the auth log contains a failed registration with the rate limit exceeded reason+ var failedRegistration = await ApiDbContext.AuthLogs.FirstOrDefaultAsync(x =>+ x.Username == user3 &&+ x.EventType == AuthEventType.Register &&+ !x.IsSuccess &&+ x.FailureReason == AuthFailureReason.RegistrationRateLimitExceeded);++ Assert.That(failedRegistration, Is.Not.Null, "Failed registration auth log entry with rate limit exceeded reason not found.");++ // Verify only 2 successful registrations were recorded+ var successfulRegistrations = await ApiDbContext.AuthLogs.CountAsync(x =>+ (x.Username == user1 || x.Username == user2 || x.Username == user3) &&+ x.EventType == AuthEventType.Register &&+ x.IsSuccess);++ Assert.That(successfulRegistrations, Is.EqualTo(2), "Expected exactly 2 successful registrations.");++ // Reset the rate limit setting back to default+ await ApiServerSettings.SetSettingAsync("MaxRegistrationsPerIpPer24Hours", "5");++ // Re-login as the original test user for subsequent tests+ await NavigateToLogin();+ await Login();+ }}diff --git a/apps/server/Utilities/AliasVault.Auth/AuthLoggingService.cs b/apps/server/Utilities/AliasVault.Auth/AuthLoggingService.csindex 0e7e89ae6..5d8208fd6 100644--- a/apps/server/Utilities/AliasVault.Auth/AuthLoggingService.cs+++ b/apps/server/Utilities/AliasVault.Auth/AuthLoggingService.cs@@ -35,7 +35,7 @@ public class AuthLoggingService(IServiceProvider serviceProvider, IHttpContextAcvar clientHeader = httpContext?.Request.Headers["X-AliasVault-Client"].FirstOrDefault();var config = scope.ServiceProvider.GetRequiredService<SharedConfig>();- var ipAddress = config.IpLoggingEnabled ? IpAddressUtility.GetIpFromContext(httpContext) : "xxx.xxx.xxx.xxx";+ var ipAddress = IpAddressUtility.GetIpFromContext(httpContext, config.IpLoggingEnabled);var authAttempt = new AuthLog{@@ -81,7 +81,7 @@ public class AuthLoggingService(IServiceProvider serviceProvider, IHttpContextAcvar clientHeader = httpContext?.Request.Headers["X-AliasVault-Client"].FirstOrDefault();var config = httpContext?.RequestServices.GetService<SharedConfig>();- var ipAddress = config?.IpLoggingEnabled == true ? IpAddressUtility.GetIpFromContext(httpContext) : "xxx.xxx.xxx.xxx";+ var ipAddress = IpAddressUtility.GetIpFromContext(httpContext, config?.IpLoggingEnabled == true);var authAttempt = new AuthLog{diff --git a/apps/server/Utilities/AliasVault.Auth/IpAddressUtility.cs b/apps/server/Utilities/AliasVault.Auth/IpAddressUtility.csindex 3c23c6e93..70c535ce0 100644--- a/apps/server/Utilities/AliasVault.Auth/IpAddressUtility.cs+++ b/apps/server/Utilities/AliasVault.Auth/IpAddressUtility.cs@@ -14,13 +14,24 @@ using Microsoft.AspNetCore.Http;/// </summary>public static class IpAddressUtility{+ /// <summary>+ /// Fully anonymized IP address constant used when IP logging is disabled.+ /// </summary>+ public const string AnonymizedIp = "xxx.xxx.xxx.xxx";+/// <summary>/// Extract IP address from HttpContext./// </summary>/// <param name="httpContext">HttpContext to extract the IP address from.</param>+ /// <param name="ipLoggingEnabled">Whether IP logging is enabled. If false, returns fully anonymized IP.</param>/// <returns>Ip address.</returns>- public static string GetIpFromContext(HttpContext? httpContext)+ public static string GetIpFromContext(HttpContext? httpContext, bool ipLoggingEnabled = true){+ if (!ipLoggingEnabled)+ {+ return AnonymizedIp;+ }+string ipAddress = string.Empty;if (httpContext == null)diff --git a/apps/server/Utilities/AliasVault.Auth/RegistrationRateLimitService.cs b/apps/server/Utilities/AliasVault.Auth/RegistrationRateLimitService.csnew file mode 100644index 000000000..67378b48b--- /dev/null+++ b/apps/server/Utilities/AliasVault.Auth/RegistrationRateLimitService.cs@@ -0,0 +1,69 @@+//-----------------------------------------------------------------------+// <copyright file="RegistrationRateLimitService.cs" company="aliasvault">+// Copyright (c) aliasvault. All rights reserved.+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------++namespace AliasVault.Auth;++using System;+using System.Linq;+using System.Threading.Tasks;+using AliasServerDb;+using AliasVault.Shared.Models.Enums;+using Microsoft.EntityFrameworkCore;++/// <summary>+/// Service for checking registration rate limits based on IP address.+/// </summary>+/// <param name="dbContextFactory">IDbContextFactory instance.</param>+public class RegistrationRateLimitService(IAliasServerDbContextFactory dbContextFactory)+{+ /// <summary>+ /// Checks if the given IP address has exceeded the registration rate limit.+ /// </summary>+ /// <param name="ipAddress">The IP address to check (should be /24 anonymized).</param>+ /// <param name="maxRegistrationsPerIpPer24Hours">Maximum number of registrations allowed per IP per 24 hours. Set to 0 to disable rate limiting.</param>+ /// <returns>True if the rate limit has been exceeded, false otherwise.</returns>+ public async Task<bool> IsRateLimitExceededAsync(string? ipAddress, int maxRegistrationsPerIpPer24Hours)+ {+ if (string.IsNullOrEmpty(ipAddress))+ {+ return false;+ }++ // If rate limiting is disabled (0), allow registration+ if (maxRegistrationsPerIpPer24Hours <= 0)+ {+ return false;+ }++ // Get the count of successful registrations from this IP in the last 24 hours+ var registrationCount = await GetRegistrationCountAsync(ipAddress);++ return registrationCount >= maxRegistrationsPerIpPer24Hours;+ }++ /// <summary>+ /// Gets the current count of successful registrations from the given IP in the last 24 hours.+ /// </summary>+ /// <param name="ipAddress">The IP address to check.</param>+ /// <returns>The count of successful registrations.</returns>+ public async Task<int> GetRegistrationCountAsync(string ipAddress)+ {+ await using var dbContext = await dbContextFactory.CreateDbContextAsync();++ var cutoffTime = DateTime.UtcNow.AddHours(-24);++ var count = await dbContext.AuthLogs+ .Where(x =>+ x.IpAddress == ipAddress &&+ x.EventType == AuthEventType.Register &&+ x.IsSuccess &&+ x.Timestamp >= cutoffTime)+ .CountAsync();++ return count;+ }+}