Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add locking to rate limited endpoints
Leendert de Borstda78cf068ab9
diff --git a/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V1/AuthController.csindex b75309acb..2bf518bcf 100644--- a/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs@@ -476,6 +476,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM/// </summary>/// <returns>IActionResult.</returns>[HttpPost("register")]+ [EnableRateLimiting(RegistrationCheckRateLimit.PolicyName)]public IActionResult Register(){// v1 registration is intentionally disabled. Clients must use the v2 API to create accounts.diff --git a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V1/VaultController.csindex e7a940bb7..cfa994de9 100644--- a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs+++ b/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs@@ -190,10 +190,17 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbContawait ApplyVaultRetention(context, currentManifest, archivedRevision);await context.SaveChangesAsync();- // Update user email claims if email addresses have been supplied.+ // Update user email claims under the same quota lock the v2 push takes.if (model.EmailAddressList.Count > 0){- await UpdateEmailClaims(context, user, currentManifest.ManifestId, model.EmailAddressList);+ var strategy = context.Database.CreateExecutionStrategy();+ await strategy.ExecuteAsync(async () =>+ {+ await using var transaction = await context.Database.BeginTransactionAsync();+ await context.Database.ExecuteSqlInterpolatedAsync($"SELECT pg_advisory_xact_lock(hashtextextended({"alias-quota:" + user.PersonalGroupId}, 0))");+ await UpdateEmailClaims(context, user, currentManifest.ManifestId, model.EmailAddressList);+ await transaction.CommitAsync();+ });}// Sync user public key if supplied, scoped to the personal manifest (every key row is manifest-scoped).diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.csindex f77799505..21532e379 100644--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs@@ -393,6 +393,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM/// <param name="registrationRateLimitService">RegistrationRateLimitService instance.</param>/// <returns>IActionResult.</returns>[HttpPost("register")]+ [EnableRateLimiting(RegistrationCheckRateLimit.PolicyName)]public async Task<IActionResult> Register([FromBody] RegisterRequest model, [FromServices] RegistrationRateLimitService registrationRateLimitService){// Without public registration only an invite code holder may register. The invite use is taken right before the account is created.@@ -410,15 +411,23 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMreturn ApiError.Result(ApiErrorCode.REGISTRATION_FAILED, 400);}- // Check IP-based registration rate limit+ // Check IP-based registration rate limit.var settings = await settingsService.GetAllSettingsAsync();var ipAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled);+ using var ipLock = await registrationRateLimitService.LockAsync(ipAddress);if (await registrationRateLimitService.IsRateLimitExceededAsync(ipAddress, settings.MaxRegistrationsPerIpPer24Hours)){await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Register, AuthFailureReason.RegistrationRateLimitExceeded);return ApiError.Result(ApiErrorCode.REGISTRATION_RATE_LIMIT_EXCEEDED, 429);}+ // Check the invite code before the username.+ if (requiresInvite && !await registrationInviteService.IsValidAsync(model.InviteCode))+ {+ await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Register, AuthFailureReason.InvalidInviteCode);+ return ApiError.Result(ApiErrorCode.INVITE_CODE_INVALID, 400);+ }+// Validate the username.var (isValid, apiErrorCode) = await tokenService.ValidateUsernameAsync(model.Username);if (!isValid)@@ -791,6 +800,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM// Check IP-based mobile login rate limit.var settings = await settingsService.GetAllSettingsAsync();var ipAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled);+ using var ipLock = await mobileLoginRateLimitService.LockAsync(ipAddress);if (await mobileLoginRateLimitService.IsRateLimitExceededAsync(ipAddress, settings.MaxMobileLoginRequestsPerIpPerMinute)){await authLoggingService.LogAuthEventFailAsync("n/a", AuthEventType.MobileLogin, AuthFailureReason.MobileLoginRateLimitExceeded);diff --git a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.csindex da3bcd489..59b66f87f 100644--- a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs@@ -24,6 +24,7 @@ using Asp.Versioning;using Microsoft.AspNetCore.Identity;using Microsoft.AspNetCore.Mvc;using Microsoft.EntityFrameworkCore;+using Microsoft.EntityFrameworkCore.Storage;using Microsoft.Extensions.Caching.Memory;/// <summary>@@ -187,13 +188,6 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Usereturn ApiError.Result(ApiErrorCode.SIGNATURE_INVALID, 400);}- // A family holds a handful of manifests, enough to keep e.g. streaming and banking apart without growing without bound.- if (await context.VaultManifests.CountAsync(x => x.OwnerGroupId == groupId) >= MaxSharedVaults)- {- return ApiError.Result(ApiErrorCode.GROUP_MANIFEST_LIMIT_REACHED, 400);- }-- // Create the empty manifest.var manifest = new VaultManifest{ManifestId = model.ManifestId,@@ -206,18 +200,44 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, UseCreatedAt = timeProvider.GetUtcNow().UtcDateTime,UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,};- context.VaultManifests.Add(manifest);- context.VaultManifestShareDetails.Add(new VaultManifestShareDetails { ManifestId = manifest.ManifestId, EncryptedName = model.EncryptedName, CreatedAt = timeProvider.GetUtcNow().UtcDateTime, UpdatedAt = timeProvider.GetUtcNow().UtcDateTime });- context.VaultManifestAccessKeys.Add(GrantHelper.BuildGrant(manifest.ManifestId, me.Id, selfPublicKeyId.Value, model.SelfEncryptedVek, algorithm, manifest.KeyVersion, model.SelfGrantSignature, me.Id, signerPublicKey!, timeProvider.GetUtcNow().UtcDateTime));- try+ var shareDetails = new VaultManifestShareDetails { ManifestId = manifest.ManifestId, EncryptedName = model.EncryptedName, CreatedAt = timeProvider.GetUtcNow().UtcDateTime, UpdatedAt = timeProvider.GetUtcNow().UtcDateTime };+ var selfGrant = GrantHelper.BuildGrant(manifest.ManifestId, me.Id, selfPublicKeyId.Value, model.SelfEncryptedVek, algorithm, manifest.KeyVersion, model.SelfGrantSignature, me.Id, signerPublicKey!, timeProvider.GetUtcNow().UtcDateTime);++ // Count and insert under the group lock, so concurrent creations cannot both pass the cap.+ var strategy = context.Database.CreateExecutionStrategy();+ var result = await strategy.ExecuteAsync<IActionResult?>(async () =>{- await context.SaveChangesAsync();- }- catch (DbUpdateException)+ await using var transaction = await context.Database.BeginTransactionAsync();+ await LockGroupManifestsAsync(context, groupId);++ if (await context.VaultManifests.CountAsync(x => x.OwnerGroupId == groupId) >= MaxSharedVaults)+ {+ return ApiError.Result(ApiErrorCode.GROUP_MANIFEST_LIMIT_REACHED, 400);+ }++ // Create the empty manifest.+ context.VaultManifests.Add(manifest);+ context.VaultManifestShareDetails.Add(shareDetails);+ context.VaultManifestAccessKeys.Add(selfGrant);++ try+ {+ await context.SaveChangesAsync();+ }+ catch (DbUpdateException)+ {+ // The client-generated manifest id is already taken, which a fresh id makes vanishingly unlikely; the client asks again.+ return ApiError.Result(ApiErrorCode.MANIFEST_ID_TAKEN, 400);+ }++ await transaction.CommitAsync();+ return null;+ });++ if (result is not null){- // The client-generated manifest id is already taken, which a fresh id makes vanishingly unlikely; the client asks again.- return ApiError.Result(ApiErrorCode.MANIFEST_ID_TAKEN, 400);+ return result;}await authLoggingService.LogAuthEventSuccessAsync(me.UserName!, AuthEventType.SharedVaultCreation);@@ -383,16 +403,17 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Usereturn ApiError.Result(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404);}- if (await GrantHelper.IsLastGrantHolderAsync(context, manifestId, userId))- {- return ApiError.Result(ApiErrorCode.LAST_MANIFEST_GRANT_HOLDER, 400);- }-- // Create a transaction to ensure the invitation and grant are closed together.+ // Close the invitation and the grant in one transaction; the lock keeps the last-holder check true until commit.var strategy = context.Database.CreateExecutionStrategy();- await strategy.ExecuteAsync(async () =>+ return await strategy.ExecuteAsync<IActionResult>(async () =>{await using var transaction = await context.Database.BeginTransactionAsync();+ await LockManifestGrantsAsync(context, manifestId);++ if (await GrantHelper.IsLastGrantHolderAsync(context, manifestId, userId))+ {+ return ApiError.Result(ApiErrorCode.LAST_MANIFEST_GRANT_HOLDER, 400);+ }foreach (var invitation in await context.GroupInvitations.Where(i => i.VaultManifestId == manifestId && i.InviteeUserId == userId && i.State == GroupInvitationState.Pending).ToListAsync()){@@ -406,9 +427,8 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Useawait context.SaveChangesAsync();await transaction.CommitAsync();+ return Ok();});-- return Ok();}/// <summary>@@ -588,71 +608,85 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Usereturn ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);}- var invitation = await context.GroupInvitations.FirstOrDefaultAsync(i => i.Id == invitationId && i.InviteeUserId == me.Id && i.State == GroupInvitationState.Pending);- if (invitation is null)+ // Read the offer's manifest only to know which lock to take; the offer itself is read again under the lock.+ var offeredManifestId = await context.GroupInvitations+ .Where(i => i.Id == invitationId && i.InviteeUserId == me.Id && i.State == GroupInvitationState.Pending)+ .Select(i => i.VaultManifestId)+ .FirstOrDefaultAsync();++ if (offeredManifestId is null){return ApiError.Result(ApiErrorCode.INVITATION_NOT_FOUND, 404);}- // Accepting no longer joins anything: the roster decided that, and a member who was taken off it in the- // meantime has nothing left to accept.- if (!await GroupHelper.IsSharedGroupMemberAsync(context, invitation.GroupId, me.Id))+ // Under the manifest's grant lock, so a concurrent revoke either closes the offer first or sees the new grant.+ var strategy = context.Database.CreateExecutionStrategy();+ return await strategy.ExecuteAsync<IActionResult>(async () =>{- return ApiError.Result(ApiErrorCode.INVITATION_NOT_FOUND, 404);- }+ await using var transaction = await context.Database.BeginTransactionAsync();+ await LockManifestGrantsAsync(context, offeredManifestId.Value);- var manifestKeyVersion = invitation.VaultManifestId is null ? null : await context.VaultManifests- .Where(m => m.ManifestId == invitation.VaultManifestId.Value && m.OwnerGroupId == invitation.GroupId)- .Select(m => (int?)m.KeyVersion)- .FirstOrDefaultAsync();+ var invitation = await context.GroupInvitations.FirstOrDefaultAsync(i => i.Id == invitationId && i.InviteeUserId == me.Id && i.State == GroupInvitationState.Pending);+ if (invitation is null)+ {+ return ApiError.Result(ApiErrorCode.INVITATION_NOT_FOUND, 404);+ }- if (manifestKeyVersion is null)- {- return ApiError.Result(ApiErrorCode.INVITATION_NOT_FOUND, 404);- }+ // Accepting no longer joins anything: the roster decided that, and a member who was taken off it in the+ // meantime has nothing left to accept.+ if (!await GroupHelper.IsSharedGroupMemberAsync(context, invitation.GroupId, me.Id))+ {+ return ApiError.Result(ApiErrorCode.INVITATION_NOT_FOUND, 404);+ }- // If the current manifest key version is different from the one the invitation was encrypted under, it is no longer valid.- if (manifestKeyVersion.Value != invitation.VaultKeyVersion)- {- CloseInvitation(invitation, GroupInvitationState.Stale);- await context.SaveChangesAsync();- return ApiError.Result(ApiErrorCode.INVITATION_KEY_OUTDATED, 400);- }+ var manifestKeyVersion = invitation.VaultManifestId is null ? null : await context.VaultManifests+ .Where(m => m.ManifestId == invitation.VaultManifestId.Value && m.OwnerGroupId == invitation.GroupId)+ .Select(m => (int?)m.KeyVersion)+ .FirstOrDefaultAsync();- if (invitation.CreatedAt < InvitationCutoff())- {- CloseInvitation(invitation, GroupInvitationState.Expired);- await context.SaveChangesAsync();- return ApiError.Result(ApiErrorCode.INVITATION_NOT_FOUND, 404);- }+ if (manifestKeyVersion is null)+ {+ return ApiError.Result(ApiErrorCode.INVITATION_NOT_FOUND, 404);+ }- // The offer is only as good as the inviter's right to make it, checked again now and not only when it was sent.- if (!await InviterMayStillGrantAsync(context, invitation))- {- CloseInvitation(invitation, GroupInvitationState.Revoked);- await context.SaveChangesAsync();- return ApiError.Result(ApiErrorCode.INVITATION_NOT_FOUND, 404);- }+ // If the current manifest key version is different from the one the invitation was encrypted under, it is no longer valid.+ if (manifestKeyVersion.Value != invitation.VaultKeyVersion)+ {+ return await CloseAndCommitAsync(context, transaction, invitation, GroupInvitationState.Stale, ApiErrorCode.INVITATION_KEY_OUTDATED, 400);+ }- if (!await PromoteInvitationGrantAsync(context, invitation, me.Id, manifestKeyVersion.Value))- {- return ApiError.Result(ApiErrorCode.INVITATION_NOT_FOUND, 404);- }+ if (invitation.CreatedAt < InvitationCutoff())+ {+ return await CloseAndCommitAsync(context, transaction, invitation, GroupInvitationState.Expired, ApiErrorCode.INVITATION_NOT_FOUND, 404);+ }- invitation.State = GroupInvitationState.Accepted;- invitation.RespondedAt = timeProvider.GetUtcNow().UtcDateTime;- invitation.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;+ // The offer is only as good as the inviter's right to make it, checked again now and not only when it was sent.+ if (!await InviterMayStillGrantAsync(context, invitation))+ {+ return await CloseAndCommitAsync(context, transaction, invitation, GroupInvitationState.Revoked, ApiErrorCode.INVITATION_NOT_FOUND, 404);+ }- // The encrypted copy has become the grant, so it stops being a second copy of the key lying around.- invitation.EncryptedVek = null;- invitation.EncryptedName = null;- invitation.EncryptedNameSignature = null;- invitation.UserGrantKeyId = null;- invitation.GrantSignature = null;- invitation.GrantSignerPublicKey = null;+ if (!await PromoteInvitationGrantAsync(context, invitation, me.Id, manifestKeyVersion.Value))+ {+ return ApiError.Result(ApiErrorCode.INVITATION_NOT_FOUND, 404);+ }- await context.SaveChangesAsync();- return Ok();+ invitation.State = GroupInvitationState.Accepted;+ invitation.RespondedAt = timeProvider.GetUtcNow().UtcDateTime;+ invitation.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;++ // The encrypted copy has become the grant, so it stops being a second copy of the key lying around.+ invitation.EncryptedVek = null;+ invitation.EncryptedName = null;+ invitation.EncryptedNameSignature = null;+ invitation.UserGrantKeyId = null;+ invitation.GrantSignature = null;+ invitation.GrantSignerPublicKey = null;++ await context.SaveChangesAsync();+ await transaction.CommitAsync();+ return Ok();+ });}/// <summary>@@ -802,6 +836,26 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use&& await ManifestAccessHelper.HoldsGrantAsync(context, invitation.InviterUserId, manifestId);}+ /// <summary>+ /// Take a transaction-scoped lock on a group's set of manifests.+ /// </summary>+ /// <param name="context">Database context, inside an open transaction.</param>+ /// <param name="groupId">The group.</param>+ private static async Task LockGroupManifestsAsync(AliasServerDbContext context, Guid groupId)+ {+ await context.Database.ExecuteSqlInterpolatedAsync($"SELECT pg_advisory_xact_lock(hashtextextended({"group-manifests:" + groupId}, 0))");+ }++ /// <summary>+ /// Take a transaction-scoped lock on a manifest's grants.+ /// </summary>+ /// <param name="context">Database context, inside an open transaction.</param>+ /// <param name="manifestId">The shared manifest.</param>+ private static async Task LockManifestGrantsAsync(AliasServerDbContext context, Guid manifestId)+ {+ await context.Database.ExecuteSqlInterpolatedAsync($"SELECT pg_advisory_xact_lock(hashtextextended({"manifest-grants:" + manifestId}, 0))");+ }+/// <summary>/// Close an offer of access, dropping the manifest key encrypted inside it./// </summary>@@ -846,6 +900,24 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Usereturn true;}+ /// <summary>+ /// Close an offer, commit, and return the given error.+ /// </summary>+ /// <param name="context">The database context.</param>+ /// <param name="transaction">The open transaction to commit.</param>+ /// <param name="invitation">The offer to close.</param>+ /// <param name="state">The state it ends in.</param>+ /// <param name="errorCode">The error to answer with.</param>+ /// <param name="statusCode">The HTTP status to answer with.</param>+ /// <returns>The error result.</returns>+ private async Task<IActionResult> CloseAndCommitAsync(AliasServerDbContext context, IDbContextTransaction transaction, GroupInvitation invitation, GroupInvitationState state, ApiErrorCode errorCode, int statusCode)+ {+ CloseInvitation(invitation, state);+ await context.SaveChangesAsync();+ await transaction.CommitAsync();+ return ApiError.Result(errorCode, statusCode);+ }+/// <summary>/// The creation moment before which an open offer of access has expired./// </summary>diff --git a/apps/server/AliasVault.Api/Program.cs b/apps/server/AliasVault.Api/Program.csindex 0d4be3346..f1aa2d670 100644--- a/apps/server/AliasVault.Api/Program.cs+++ b/apps/server/AliasVault.Api/Program.cs@@ -92,6 +92,7 @@ builder.Services.AddSingleton(TimeProvider.System);builder.Services.AddScoped<TimeValidationJwtBearerEvents>();builder.Services.AddScoped<AuthLoggingService>();builder.Services.AddScoped<ServerSettingsService>();+builder.Services.AddSingleton<KeyedAsyncLock>();builder.Services.AddScoped<RegistrationRateLimitService>();builder.Services.AddScoped<RegistrationInviteService>();builder.Services.AddScoped<IpBlockListService>();diff --git a/apps/server/Utilities/AliasVault.Auth/KeyedAsyncLock.cs b/apps/server/Utilities/AliasVault.Auth/KeyedAsyncLock.csnew file mode 100644index 000000000..300cbe264--- /dev/null+++ b/apps/server/Utilities/AliasVault.Auth/KeyedAsyncLock.cs@@ -0,0 +1,95 @@+//-----------------------------------------------------------------------+// <copyright file="KeyedAsyncLock.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.Collections.Generic;+using System.Threading;+using System.Threading.Tasks;++/// <summary>+/// In-process async lock per key; it does not span API instances.+/// </summary>+public sealed class KeyedAsyncLock+{+ private readonly object gate = new();+ private readonly Dictionary<string, Entry> entries = new(StringComparer.Ordinal);++ /// <summary>+ /// Wait for the lock on a key. Dispose the result to release it.+ /// </summary>+ /// <param name="key">The key to lock.</param>+ /// <returns>The handle that releases the lock when disposed.</returns>+ public async Task<IDisposable> AcquireAsync(string key)+ {+ Entry entry;+ lock (gate)+ {+ if (!entries.TryGetValue(key, out var existing))+ {+ existing = new Entry();+ entries[key] = existing;+ }++ existing.Holders++;+ entry = existing;+ }++ await entry.Semaphore.WaitAsync();+ return new Releaser(this, key, entry);+ }++ private void Release(string key, Entry entry)+ {+ lock (gate)+ {+ entry.Holders--;+ if (entry.Holders == 0)+ {+ entries.Remove(key);+ entry.Semaphore.Dispose();+ return;+ }+ }++ entry.Semaphore.Release();+ }++ /// <summary>+ /// The lock of one key and how many callers hold or wait for it.+ /// </summary>+ private sealed class Entry+ {+ /// <summary>+ /// Gets the semaphore callers wait on.+ /// </summary>+ public SemaphoreSlim Semaphore { get; } = new(1, 1);++ /// <summary>+ /// Gets or sets the number of callers holding or waiting for the lock.+ /// </summary>+ public int Holders { get; set; }+ }++ /// <summary>+ /// Releases a held lock once, on dispose.+ /// </summary>+ private sealed class Releaser(KeyedAsyncLock owner, string key, Entry entry) : IDisposable+ {+ private int disposed;++ /// <inheritdoc />+ public void Dispose()+ {+ if (Interlocked.Exchange(ref disposed, 1) == 0)+ {+ owner.Release(key, entry);+ }+ }+ }+}diff --git a/apps/server/Utilities/AliasVault.Auth/MobileLoginRateLimitService.cs b/apps/server/Utilities/AliasVault.Auth/MobileLoginRateLimitService.csindex 462ade8e4..3303d74b5 100644--- a/apps/server/Utilities/AliasVault.Auth/MobileLoginRateLimitService.cs+++ b/apps/server/Utilities/AliasVault.Auth/MobileLoginRateLimitService.cs@@ -18,13 +18,24 @@ using Microsoft.EntityFrameworkCore;/// Service for checking mobile login request rate limits based on IP address./// </summary>/// <param name="dbContextFactory">IDbContextFactory instance.</param>-public class MobileLoginRateLimitService(IAliasServerDbContextFactory dbContextFactory)+/// <param name="keyedLock">The per-IP lock.</param>+public class MobileLoginRateLimitService(IAliasServerDbContextFactory dbContextFactory, KeyedAsyncLock keyedLock){/// <summary>/// Length of the window the limit is enforced over./// </summary>private const int WindowMinutes = 1;+ /// <summary>+ /// Lock an IP address until its request is written.+ /// </summary>+ /// <param name="ipAddress">The IP address to lock (should be /24 anonymized).</param>+ /// <returns>The handle that releases the lock when disposed.</returns>+ public Task<IDisposable> LockAsync(string? ipAddress)+ {+ return keyedLock.AcquireAsync("mobile-login:" + ipAddress);+ }+/// <summary>/// Checks if the given IP address has exceeded the mobile login request rate limit./// </summary>diff --git a/apps/server/Utilities/AliasVault.Auth/RegistrationRateLimitService.cs b/apps/server/Utilities/AliasVault.Auth/RegistrationRateLimitService.csindex 67378b48b..ed897da8a 100644--- a/apps/server/Utilities/AliasVault.Auth/RegistrationRateLimitService.cs+++ b/apps/server/Utilities/AliasVault.Auth/RegistrationRateLimitService.cs@@ -18,8 +18,19 @@ using Microsoft.EntityFrameworkCore;/// Service for checking registration rate limits based on IP address./// </summary>/// <param name="dbContextFactory">IDbContextFactory instance.</param>-public class RegistrationRateLimitService(IAliasServerDbContextFactory dbContextFactory)+/// <param name="keyedLock">The per-IP lock.</param>+public class RegistrationRateLimitService(IAliasServerDbContextFactory dbContextFactory, KeyedAsyncLock keyedLock){+ /// <summary>+ /// Lock an IP address until its registration is written.+ /// </summary>+ /// <param name="ipAddress">The IP address to lock (should be /24 anonymized).</param>+ /// <returns>The handle that releases the lock when disposed.</returns>+ public Task<IDisposable> LockAsync(string? ipAddress)+ {+ return keyedLock.AcquireAsync("registration:" + ipAddress);+ }+/// <summary>/// Checks if the given IP address has exceeded the registration rate limit./// </summary>