Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor API to use shared TokenService.cs (#2468)
Leendert de Borst248c11eb9370
diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.csindex fcc001d47..7ca2dd4b3 100644--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs@@ -7,16 +7,16 @@namespace AliasVault.Api.Controllers.V2;-using System.IdentityModel.Tokens.Jwt;+using System.Buffers.Text;using System.Security.Claims;using System.Security.Cryptography;-using System.Text;using System.Text.Json;using AliasServerDb;using AliasServerDb.Retention;using AliasVault.Api.Headers;using AliasVault.Api.Helpers;using AliasVault.Api.Models;+using AliasVault.Api.Services;using AliasVault.Auth;using AliasVault.Auth.IpAddress;using AliasVault.Cryptography;@@ -34,7 +34,6 @@ using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.RateLimiting;using Microsoft.EntityFrameworkCore;using Microsoft.Extensions.Caching.Memory;-using Microsoft.IdentityModel.Tokens;using SecureRemotePassword;/// <summary>@@ -42,7 +41,6 @@ using SecureRemotePassword;/// </summary>/// <param name="dbContextFactory">AliasServerDbContext instance.</param>/// <param name="userManager">UserManager instance.</param>-/// <param name="configuration">IConfiguration instance.</param>/// <param name="cache">IMemoryCache instance for persisting SRP values during multistep login process.</param>/// <param name="timeProvider">TimeProvider instance.</param>/// <param name="authLoggingService">AuthLoggingService instance. This is used to log auth attempts to the database.</param>@@ -50,21 +48,12 @@ using SecureRemotePassword;/// <param name="settingsService">ServerSettingsService instance.</param>/// <param name="ipBlockListService">IpBlockListService instance.</param>/// <param name="registrationInviteService">RegistrationInviteService instance.</param>+/// <param name="tokenService">TokenService instance.</param>[Route("v{version:apiVersion}/[controller]")][ApiController][ApiVersion("2")]-public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IConfiguration configuration, IMemoryCache cache, TimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, IpBlockListService ipBlockListService, RegistrationInviteService registrationInviteService) : ControllerBase+public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IMemoryCache cache, TimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, IpBlockListService ipBlockListService, RegistrationInviteService registrationInviteService, TokenService tokenService) : ControllerBase{- /// <summary>- /// Access token validity in minutes.- /// </summary>- private const int AccessTokenValiditySeconds = 600;-- /// <summary>- /// Access token claim with the id of the refresh token it was issued with.- /// </summary>- private const string RefreshTokenIdClaim = "rtid";-/// <summary>/// Maximum accepted length of a password salt./// </summary>@@ -80,21 +69,6 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM/// </summary>private const int MaxEncryptionSettingsLength = 255;- /// <summary>- /// Cache prefix for the successor of a rotated refresh token, followed by the user id and the hash of the rotated token.- /// </summary>- private const string CachePrefixRefreshTokenSuccessor = "RefreshTokenSuccessor_";-- /// <summary>- /// How long after a rotation the replaced refresh token still returns the token that replaced it, so concurrent client refreshes do not log the device out.- /// </summary>- private static readonly TimeSpan RefreshTokenReuseWindow = TimeSpan.FromSeconds(30);-- /// <summary>- /// Semaphore to prevent concurrent access to the database when generating new tokens for a user.- /// </summary>- private static readonly SemaphoreSlim Semaphore = new(1, 1);-/// <summary>/// Login endpoint used to process login attempt using credentials./// </summary>@@ -302,7 +276,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMClaimsPrincipal principal;try{- principal = GetPrincipalFromToken(tokenModel.Token);+ principal = TokenService.GetPrincipalFromToken(tokenModel.Token);}catch (Exception){@@ -461,7 +435,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}// Validate the username.- var (isValid, apiErrorCode) = await ValidateUsername(model.Username);+ var (isValid, apiErrorCode) = await tokenService.ValidateUsernameAsync(model.Username);if (!isValid){return ApiError.Result(apiErrorCode, 400);@@ -469,19 +443,11 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM// Every new account is created on the account-key model, so the client must generate the whole hierarchy up front.// Reject an incomplete or oversized one before any row is written, so a rejected attempt leaves no account behind.- if (!model.HasCompleteAccountKeys)- {- return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);- }-- if (!model.AccountKeysFitStorageLimits || !RsaPublicKeyValidator.IsValid(model.AccountPublicKey) || !Signing.VerifyAccountPublicKey(model.SigningPublicKey, model.AccountPublicKey, model.AccountPublicKeySignature))- {- return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);- }-- if (!VaultKeyAlgorithms.TryParse(model.EncryptedAccountKeyAlgorithm, out var unlockKeyAlgorithm) || VaultKeyAlgorithms.IsAsymmetric(unlockKeyAlgorithm))+ var accountKeys = model.ToAccountKeysUpload();+ var accountKeysError = AccountKeyHierarchyHelper.Validate(accountKeys, out var unlockKeyAlgorithm);+ if (accountKeysError is not null){- return ApiError.Result(ApiErrorCode.INVALID_ALGORITHM, 400);+ return ApiError.Result(accountKeysError.Value, 400);}if (!IsValidKekDerivationParams(model.EncryptionType, model.EncryptionSettings) || !WithinSrpCredentialLimits(model.Salt, model.Verifier) || !IsValidSrpIdentity(model.SrpIdentity))@@ -553,61 +519,8 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMUpdatedAt = timeProvider.GetUtcNow().UtcDateTime,});- context.UserUnlockKeys.Add(new UserUnlockKey- {- Id = Guid.NewGuid(),- UserId = user.Id,- Type = UnlockMethodType.Password,- Algorithm = unlockKeyAlgorithm,- EncryptedAccountKey = model.EncryptedAccountKey!,- Metadata = new VaultKeyMetadata- {- Salt = model.Salt,- SrpVerifier = model.Verifier,- EncryptionType = model.EncryptionType,- EncryptionSettings = model.EncryptionSettings,- }.ToJson(),- CreatedAt = timeProvider.GetUtcNow().UtcDateTime,- UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,- });-- context.UserGrantKeys.Add(new UserGrantKey- {- Id = Guid.NewGuid(),- UserId = user.Id,- Algorithm = VaultKeyAlgorithm.RsaOaepSha256,- PublicKey = model.AccountPublicKey!,- EncryptedPrivateKey = model.EncryptedAccountPrivateKey!,- PublicKeySignature = model.AccountPublicKeySignature!,- IsPrimary = true,- CreatedAt = timeProvider.GetUtcNow().UtcDateTime,- UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,- });-- context.UserSigningKeys.Add(new UserSigningKey- {- Id = Guid.NewGuid(),- UserId = user.Id,- Algorithm = SigningKeyAlgorithm.Ed25519,- PublicKey = model.SigningPublicKey!,- EncryptedPrivateKey = model.EncryptedSigningPrivateKey!,- IsPrimary = true,- CreatedAt = timeProvider.GetUtcNow().UtcDateTime,- UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,- });-- context.VaultManifestAccessKeys.Add(new VaultManifestAccessKey- {- Id = Guid.NewGuid(),- UserId = user.Id,- VaultManifestId = personalManifestId,- Type = ManifestKeyType.AccountKey,- Algorithm = VaultKeyAlgorithm.Aes256Gcm,- EncryptedVek = model.EncryptedVek!,- AccountKeyVersion = 0,- CreatedAt = timeProvider.GetUtcNow().UtcDateTime,- UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,- });+ var srpCredentials = new VaultKeyMetadata { Salt = model.Salt, SrpVerifier = model.Verifier, EncryptionType = model.EncryptionType, EncryptionSettings = model.EncryptionSettings };+ AccountKeyHierarchyHelper.AddEntities(context, user.Id, personalManifestId, accountKeys, unlockKeyAlgorithm, srpCredentials, timeProvider.GetUtcNow().UtcDateTime);await context.SaveChangesAsync();}@@ -706,7 +619,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMvar now = timeProvider.GetUtcNow().UtcDateTime;var settings = await settingsService.GetAllSettingsAsync();- var currentRefreshTokenId = Guid.TryParse(User.FindFirstValue(RefreshTokenIdClaim), out var tokenId) ? tokenId : Guid.Empty;+ var currentRefreshTokenId = Guid.TryParse(User.FindFirstValue(TokenService.RefreshTokenIdClaim), out var tokenId) ? tokenId : Guid.Empty;var newMetadata = VaultKeyMetadata.Parse(unlockKey.Metadata);newMetadata.Salt = model.NewPasswordSalt;@@ -722,7 +635,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMawait using var writeContext = await dbContextFactory.CreateDbContextAsync();await using var transaction = await writeContext.Database.BeginTransactionAsync();- await ArchiveSupersededUnlockKeyAsync(writeContext, unlockKey, settings.UnlockKeyHistoryRetentionDays, now, ClientHeaderInfo.GetRawValue(Request));+ await UnlockKeyHistoryPolicy.ArchiveAsync(writeContext, unlockKey, settings.UnlockKeyHistoryRetentionDays, now, ClientHeaderInfo.GetRawValue(Request));await writeContext.SaveChangesAsync();await writeContext.UserUnlockKeys.Where(x => x.Id == unlockKey.Id).ExecuteUpdateAsync(s => s@@ -784,7 +697,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}// Validate the username- var (isValid, apiErrorCode) = await ValidateUsername(normalizedUsername);+ var (isValid, apiErrorCode) = await tokenService.ValidateUsernameAsync(normalizedUsername);if (!isValid){@@ -890,7 +803,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM// The request id travels through the QR code, the poll secret stays with the initiating client. Only its hash is stored.var requestId = Guid.NewGuid().ToString("N");- var pollSecret = Base64UrlEncoder.Encode(RandomNumberGenerator.GetBytes(32));+ var pollSecret = Base64Url.EncodeToString(RandomNumberGenerator.GetBytes(32));var loginRequest = new MobileLoginRequest{@@ -1184,39 +1097,6 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM_ => ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_EXPIRED, 410),};- /// <summary>- /// Archives the unlock key that is about to be overwritten so it can be reverted to in case of a password change failure.- /// Archived rows are pruned automatically on each archive attempt and by TaskRunner daily as well.- /// </summary>- /// <param name="context">Database context, inside the caller's transaction.</param>- /// <param name="unlockKey">The unlock key about to receive new credentials.</param>- /// <param name="retentionDays">The configured retention window; 0 switches archiving off.</param>- /// <param name="now">The current time.</param>- /// <param name="client">The client performing the credential change, recorded on the archived row.</param>- /// <returns>Task.</returns>- private static async Task ArchiveSupersededUnlockKeyAsync(AliasServerDbContext context, UserUnlockKey unlockKey, int retentionDays, DateTime now, string? client)- {- if (UnlockKeyHistoryPolicy.EffectiveRetentionDays(retentionDays) == 0)- {- return;- }-- // Prune first, leaving room for the row added below: the limit counts that row, so one fewer is skipped here.- var supersededIds = await context.UserUnlockKeysHistory- .Where(x => x.UserId == unlockKey.UserId && x.Type == unlockKey.Type)- .OrderByDescending(x => x.ArchivedAt)- .Skip(UnlockKeyHistoryPolicy.MaxRowsPerMethod - 1)- .Select(x => x.Id)- .ToListAsync();-- if (supersededIds.Count > 0)- {- await context.UserUnlockKeysHistory.Where(x => supersededIds.Contains(x.Id)).ExecuteDeleteAsync();- }-- context.UserUnlockKeysHistory.Add(UserUnlockKeysHistory.CreateFrom(unlockKey, now, client));- }-/// <summary>/// Whether a client-supplied SRP salt and verifier are present and within the stored size limits./// </summary>@@ -1287,177 +1167,23 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}/// <summary>- /// Generate a refresh token for a user. This token is used to request a new access token when the current- /// access token expires. The refresh token is long-lived by design.- /// </summary>- /// <returns>Random string to be used as refresh token.</returns>- private static string GenerateRefreshToken()- {- var randomNumber = new byte[32];- using var rng = RandomNumberGenerator.Create();-- rng.GetBytes(randomNumber);- return Convert.ToBase64String(randomNumber);- }-- /// <summary>- /// Cache key under which the successor of a rotated refresh token is kept for the reuse window.- /// </summary>- /// <param name="user">The owner of the token.</param>- /// <param name="rotatedTokenHash">The hash of the token that was rotated away.</param>- /// <returns>The cache key.</returns>- private static string RefreshTokenSuccessorCacheKey(AliasVaultUser user, string rotatedTokenHash) => $"{CachePrefixRefreshTokenSuccessor}{user.Id}_{rotatedTokenHash}";-- /// <summary>- /// Get the JWT key from the container secrets or environment variables.- /// </summary>- /// <returns>JWT key as string.</returns>- /// <exception cref="KeyNotFoundException">Thrown if JWT key cannot be found.</exception>- private static string GetJwtKey()- {- return SecretReader.GetJwtKey();- }-- /// <summary>- /// Get the principal from a token. This is used to validate the token and extract the user.- /// </summary>- /// <param name="token">The token as string.</param>- /// <returns>Claims principal.</returns>- /// <exception cref="SecurityTokenException">Thrown if provided token is invalid.</exception>- private static ClaimsPrincipal GetPrincipalFromToken(string token)- {- var tokenValidationParameters = new TokenValidationParameters- {- ValidateAudience = false,- ValidateIssuer = false,- ValidateIssuerSigningKey = true,- IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(GetJwtKey())),-- // We don't validate the token lifetime here, as we only use it for refresh tokens.- ValidateLifetime = false,- };-- var tokenHandler = new JwtSecurityTokenHandler();- var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken securityToken);- if (securityToken is not JwtSecurityToken jwtSecurityToken || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))- {- throw new SecurityTokenException("Invalid token");- }-- return principal;- }-- /// <summary>- /// Validates if a given username meets the required criteria.- /// </summary>- /// <param name="username">The username to validate.</param>- /// <returns>A tuple containing a boolean indicating if the username is valid, and an error message if it's invalid.</returns>- private async Task<(bool IsValid, ApiErrorCode ApiErrorCode)> ValidateUsername(string username)- {- const int minimumUsernameLength = 3;- const int maximumUsernameLength = 40;- const string adminUsername = "admin";-- if (string.IsNullOrWhiteSpace(username))- {- return (false, ApiErrorCode.USERNAME_EMPTY_OR_WHITESPACE);- }-- if (username.Length < minimumUsernameLength)- {- return (false, ApiErrorCode.USERNAME_TOO_SHORT);- }-- if (username.Length > maximumUsernameLength)- {- return (false, ApiErrorCode.USERNAME_TOO_LONG);- }-- // Disallow admin username to prevent conflicts with the default admin user- if (string.Equals(username, adminUsername, StringComparison.OrdinalIgnoreCase))- {- return (false, ApiErrorCode.USERNAME_ALREADY_IN_USE);- }-- // Check if username is not taken already- var existingUser = await userManager.FindByNameAsync(username);- if (existingUser != null)- {- return (false, ApiErrorCode.USERNAME_ALREADY_IN_USE);- }-- // Check if it's a valid email address- if (username.Contains('@'))- {- try- {- var addr = new System.Net.Mail.MailAddress(username);- return (addr.Address == username, ApiErrorCode.USERNAME_INVALID_EMAIL);- }- catch- {- return (false, ApiErrorCode.USERNAME_INVALID_EMAIL);- }- }-- // If it's not an email, check if it only contains letters and digits- if (!username.All(char.IsLetterOrDigit))- {- return (false, ApiErrorCode.USERNAME_INVALID_CHARACTERS);- }-- return (true, ApiErrorCode.USERNAME_AVAILABLE);- }-- /// <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.+ /// Validates the user and SRP session (password), then records usage of the proven unlock key./// </summary>/// <param name="model">ValidateLoginRequest model.</param>/// <returns>User, SrpSession and the proven unlock key if validation succeeded, IActionResult as error on error.</returns>private async Task<(AliasVaultUser? User, SrpSession? ServerSession, Guid? UnlockKeyId, 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, null, ApiError.Result(ApiErrorCode.USER_NOT_FOUND, 400));- }-- // Check if the account is locked out.- if (await userManager.IsLockedOutAsync(user))+ var result = await tokenService.ValidateUserAndPasswordAsync(model.Username, model.ClientPublicEphemeral, model.ClientSessionProof, model.LoginSessionId);+ if (result.Error is not null){- await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthentication, AuthFailureReason.AccountLocked);- return (null, null, null, ApiError.Result(ApiErrorCode.ACCOUNT_LOCKED, 400));- }-- // Check if the account is blocked.- if (user.Blocked)- {- await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.AccountBlocked);- return (null, null, null, ApiError.Result(ApiErrorCode.ACCOUNT_BLOCKED, 400));- }-- // Validate the SRP session (actual password check).- await using var context = await dbContextFactory.CreateDbContextAsync();- var srpResult = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, SrpPurpose.Login, model.ClientPublicEphemeral, model.ClientSessionProof, model.LoginSessionId);- if (srpResult.Session is null)- {- if (srpResult.ActiveSessionFound)- {- // Incorrect password: increment failed login attempts which then locks out- // the account when the limit is reached.- await userManager.AccessFailedAsync(user);- }-- await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.Login, srpResult.FailureReason);- return (null, null, null, ApiError.Result(ApiErrorCode.USER_NOT_FOUND, 400));+ return (null, null, null, ApiError.Result(result.Error.Value, 400));}// Record usage of this unlock method for statistics purposes.- await AuthHelper.TouchUnlockKeyLastUsedAsync(context, srpResult.UnlockKeyId, timeProvider.GetUtcNow().UtcDateTime);+ await using var context = await dbContextFactory.CreateDbContextAsync();+ await AuthHelper.TouchUnlockKeyLastUsedAsync(context, result.UnlockKeyId, timeProvider.GetUtcNow().UtcDateTime);- return (user, srpResult.Session, srpResult.UnlockKeyId, null);+ return (result.User, result.ServerSession, result.UnlockKeyId, null);}/// <summary>@@ -1496,151 +1222,27 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}/// <summary>- /// Generate a Jwt access token for a user. This token is used to authenticate the user for a limited time- /// and is short-lived by design. With the separate refresh token, the user can request a new access token- /// when this access token expires.- /// </summary>- /// <param name="user">The user to generate the Jwt access token for.</param>- /// <param name="refreshTokenId">The id of the refresh token issued with this access token.</param>- /// <returns>Access token as string.</returns>- private string GenerateJwtToken(AliasVaultUser user, Guid refreshTokenId)- {- var claims = new List<Claim>- {- new(ClaimTypes.NameIdentifier, user.Id),- new(ClaimTypes.Name, user.UserName ?? string.Empty),- new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),- new(RefreshTokenIdClaim, refreshTokenId.ToString()),- };-- var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(GetJwtKey()));- var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);-- var token = new JwtSecurityToken(- issuer: configuration["Jwt:Issuer"] ?? string.Empty,- audience: configuration["Jwt:Issuer"] ?? string.Empty,- claims: claims,- expires: timeProvider.GetUtcNow().UtcDateTime.AddSeconds(AccessTokenValiditySeconds),- signingCredentials: credentials);-- return new JwtSecurityTokenHandler().WriteToken(token);- }-- /// <summary>- /// Generates a new access and refresh token for a user and persists the refresh token- /// to the database.+ /// Issues a new access and refresh token pair, the access token bound to its refresh token id./// </summary>- /// <param name="user">The user to generate the tokens for.</param>+ /// <param name="user">The user to issue the tokens for.</param>/// <param name="extendedLifetime">If true, the refresh token will have an extended lifetime (remember me option).</param>+ /// <returns>TokenModel which includes new access and refresh token.</returns>private async Task<TokenModel> GenerateNewTokensForUser(AliasVaultUser user, bool extendedLifetime = false){- await using var context = await dbContextFactory.CreateDbContextAsync();- var settings = await settingsService.GetAllSettingsAsync();-- await Semaphore.WaitAsync();- try- {- // Use server settings for refresh token lifetime.- var refreshTokenLifetimeHours = extendedLifetime ? settings.RefreshTokenLifetimeLong : settings.RefreshTokenLifetimeShort;- var refreshTokenLifetime = TimeSpan.FromHours(refreshTokenLifetimeHours);-- // Return new refresh token.- return await GenerateRefreshToken(user, refreshTokenLifetime);- }- finally- {- Semaphore.Release();- }+ var tokens = await tokenService.IssueTokensAsync(user, HttpContext, extendedLifetime, includeRefreshTokenIdClaim: true);+ return new TokenModel { Token = tokens.Token, RefreshToken = tokens.RefreshToken };}/// <summary>- /// Generates a new access and refresh token for a user and persists the refresh token- /// to the database.+ /// Rotates a refresh token and issues a new access token bound to the new refresh token id./// </summary>/// <param name="user">The user to generate the tokens for.</param>- /// <param name="existingTokenValue">The existing token value that is being replaced (optional).</param>+ /// <param name="existingTokenValue">The existing refresh token value that is being replaced.</param>/// <returns>TokenModel which includes new access and refresh token. Returns null if provided refresh token is invalid.</returns>private async Task<TokenModel?> GenerateNewTokensForUser(AliasVaultUser user, string existingTokenValue){- await using var context = await dbContextFactory.CreateDbContextAsync();- await Semaphore.WaitAsync();-- try- {- // Token reuse window: if this token was rotated in the last 30 seconds, hand out the token that replaced it- // again, so concurrent refreshes from one client do not log it out. The stored row only has the hash, so the- // successor comes from memory and is forgotten when the window closes.- var existingTokenHash = RefreshTokenHasher.Hash(existingTokenValue);- if (cache.TryGetValue(RefreshTokenSuccessorCacheKey(user, existingTokenHash), out RefreshTokenSuccessor? successor) && successor is not null)- {- return new TokenModel { Token = GenerateJwtToken(user, successor.Id), RefreshToken = successor.RefreshToken };- }-- // Check if the refresh token still exists and is not expired.- var existingToken = await context.AliasVaultUserRefreshTokens.FirstOrDefaultAsync(t => t.UserId == user.Id && t.TokenHash == existingTokenHash);- if (existingToken == null || existingToken.ExpireDate < timeProvider.GetUtcNow().UtcDateTime)- {- return null;- }-- context.AliasVaultUserRefreshTokens.Remove(existingToken);-- // New refresh token lifetime is the same as the existing one.- var existingTokenLifetime = existingToken.ExpireDate - existingToken.CreatedAt;-- // Retrieve new refresh token.- var newRefreshToken = await GenerateRefreshToken(user, existingTokenLifetime, existingToken.TokenHash);-- // After successfully retrieving new refresh token, remove the existing one by saving changes.- await context.SaveChangesAsync();-- // Return new refresh token.- return newRefreshToken;- }- finally- {- Semaphore.Release();- }- }-- /// <summary>- /// Generates a new access and refresh token for a user and persists the refresh token- /// to the database.- /// </summary>- /// <param name="user">The user to generate the tokens for.</param>- /// <param name="newTokenLifetime">The lifetime of the new token.</param>- /// <param name="existingTokenHash">The hash of the existing token that is being replaced (optional).</param>- /// <returns>TokenModel which includes new access and refresh token.</returns>- private async Task<TokenModel> GenerateRefreshToken(AliasVaultUser user, TimeSpan newTokenLifetime, string? existingTokenHash = null)- {- await using var context = await dbContextFactory.CreateDbContextAsync();-- var refreshTokenId = Guid.NewGuid();- var accessToken = GenerateJwtToken(user, refreshTokenId);- var refreshToken = GenerateRefreshToken();- var deviceIdentifier = AuthHelper.GenerateDeviceIdentifier(Request);-- // Add new refresh token.- context.AliasVaultUserRefreshTokens.Add(new AliasVaultUserRefreshToken- {- Id = refreshTokenId,- UserId = user.Id,- DeviceIdentifier = deviceIdentifier,- IpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled),- TokenHash = RefreshTokenHasher.Hash(refreshToken),- PreviousTokenHash = existingTokenHash,- ExpireDate = timeProvider.GetUtcNow().UtcDateTime.Add(newTokenLifetime),- CreatedAt = timeProvider.GetUtcNow().UtcDateTime,- });-- await context.SaveChangesAsync();-- if (existingTokenHash is not null)- {- cache.Set(RefreshTokenSuccessorCacheKey(user, existingTokenHash), new RefreshTokenSuccessor(refreshTokenId, refreshToken), RefreshTokenReuseWindow);- }-- return new TokenModel { Token = accessToken, RefreshToken = refreshToken };+ var tokens = await tokenService.RotateRefreshTokenAsync(user, existingTokenValue, HttpContext, includeRefreshTokenIdClaim: true);+ return tokens is null ? null : new TokenModel { Token = tokens.Token, RefreshToken = tokens.RefreshToken };}/// <summary>diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultController.csindex 377f84e2b..cb2f6a892 100644--- a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs@@ -388,19 +388,15 @@ public class VaultController(return ApiError.Result(ApiErrorCode.VAULT_KEY_ALREADY_EXISTS, 400);}- if (personalWrite == null || !accountKeys.IsComplete)+ if (personalWrite == null){return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);}- if (!accountKeys.FitsStorageLimits || !RsaPublicKeyValidator.IsValid(accountKeys.AccountPublicKey) || !Signing.VerifyAccountPublicKey(accountKeys.SigningPublicKey, accountKeys.AccountPublicKey, accountKeys.AccountPublicKeySignature))+ var accountKeysError = AccountKeyHierarchyHelper.Validate(accountKeys, out _);+ if (accountKeysError is not null){- return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);- }-- if (!VaultKeyAlgorithms.TryParse(accountKeys.EncryptedAccountKeyAlgorithm, out var unlockKeyAlgorithm) || VaultKeyAlgorithms.IsAsymmetric(unlockKeyAlgorithm))- {- return ApiError.Result(ApiErrorCode.INVALID_ALGORITHM, 400);+ return ApiError.Result(accountKeysError.Value, 400);}}else if (personalWrite != null && !hasExistingUnlockKey)@@ -535,61 +531,9 @@ public class VaultController(// the client re-encrypted the vault under a fresh VEK).if (accountKeys != null){- context.UserUnlockKeys.Add(new UserUnlockKey- {- Id = Guid.NewGuid(),- UserId = user.Id,- Type = UnlockMethodType.Password,- Algorithm = VaultKeyAlgorithms.Parse(accountKeys.EncryptedAccountKeyAlgorithm),- EncryptedAccountKey = accountKeys.EncryptedAccountKey!,- Metadata = new VaultKeyMetadata- {- Salt = row.Salt,- SrpVerifier = row.Verifier,- EncryptionType = row.EncryptionType,- EncryptionSettings = row.EncryptionSettings,- }.ToJson(),- CreatedAt = timeProvider.GetUtcNow().UtcDateTime,- UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,- });-- context.UserGrantKeys.Add(new UserGrantKey- {- Id = Guid.NewGuid(),- UserId = user.Id,- Algorithm = VaultKeyAlgorithm.RsaOaepSha256,- PublicKey = accountKeys.AccountPublicKey!,- EncryptedPrivateKey = accountKeys.EncryptedAccountPrivateKey!,- PublicKeySignature = accountKeys.AccountPublicKeySignature!,- IsPrimary = true,- CreatedAt = timeProvider.GetUtcNow().UtcDateTime,- UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,- });-- context.UserSigningKeys.Add(new UserSigningKey- {- Id = Guid.NewGuid(),- UserId = user.Id,- Algorithm = SigningKeyAlgorithm.Ed25519,- PublicKey = accountKeys.SigningPublicKey!,- EncryptedPrivateKey = accountKeys.EncryptedSigningPrivateKey!,- IsPrimary = true,- CreatedAt = timeProvider.GetUtcNow().UtcDateTime,- UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,- });-- context.VaultManifestAccessKeys.Add(new VaultManifestAccessKey- {- Id = Guid.NewGuid(),- UserId = user.Id,- VaultManifestId = row.ManifestId,- Type = ManifestKeyType.AccountKey,- Algorithm = VaultKeyAlgorithm.Aes256Gcm,- EncryptedVek = accountKeys.EncryptedVek!,- AccountKeyVersion = 0,- CreatedAt = timeProvider.GetUtcNow().UtcDateTime,- UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,- });+ var srpCredentials = new VaultKeyMetadata { Salt = row.Salt, SrpVerifier = row.Verifier, EncryptionType = row.EncryptionType, EncryptionSettings = row.EncryptionSettings };+ var unlockKeyAlgorithm = VaultKeyAlgorithms.Parse(accountKeys.EncryptedAccountKeyAlgorithm);+ AccountKeyHierarchyHelper.AddEntities(context, user.Id, row.ManifestId, accountKeys, unlockKeyAlgorithm, srpCredentials, timeProvider.GetUtcNow().UtcDateTime);row.Salt = null;row.Verifier = null;diff --git a/apps/server/AliasVault.Api/Helpers/AccountKeyHierarchyHelper.cs b/apps/server/AliasVault.Api/Helpers/AccountKeyHierarchyHelper.csnew file mode 100644index 000000000..afc0cdebc--- /dev/null+++ b/apps/server/AliasVault.Api/Helpers/AccountKeyHierarchyHelper.cs@@ -0,0 +1,111 @@+//-----------------------------------------------------------------------+// <copyright file="AccountKeyHierarchyHelper.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.Api.Helpers;++using AliasServerDb;+using AliasVault.Cryptography;+using AliasVault.Shared.Models.Enums;+using AliasVault.Shared.Models.WebApi.V2.Vault;++/// <summary>+/// Validates and stores a client-uploaded account key hierarchy, for registration and the legacy vault migration.+/// </summary>+public static class AccountKeyHierarchyHelper+{+ /// <summary>+ /// Validates an uploaded account key hierarchy, including the signing key's signature over the account public key.+ /// </summary>+ /// <param name="keys">The uploaded keys.</param>+ /// <param name="unlockKeyAlgorithm">The parsed algorithm of the encrypted Account Key, when valid.</param>+ /// <returns>Null when valid, else the error code to answer with.</returns>+ public static ApiErrorCode? Validate(AccountKeysUpload keys, out VaultKeyAlgorithm unlockKeyAlgorithm)+ {+ unlockKeyAlgorithm = default;++ // Reject an incomplete or oversized hierarchy before any row is written.+ if (!keys.IsComplete || !keys.FitsStorageLimits || !RsaPublicKeyValidator.IsValid(keys.AccountPublicKey))+ {+ return ApiErrorCode.INVALID_REQUEST;+ }++ if (!Signing.VerifyAccountPublicKey(keys.SigningPublicKey, keys.AccountPublicKey, keys.AccountPublicKeySignature))+ {+ return ApiErrorCode.INVALID_REQUEST;+ }++ if (!VaultKeyAlgorithms.TryParse(keys.EncryptedAccountKeyAlgorithm, out unlockKeyAlgorithm) || VaultKeyAlgorithms.IsAsymmetric(unlockKeyAlgorithm))+ {+ return ApiErrorCode.INVALID_ALGORITHM;+ }++ return null;+ }++ /// <summary>+ /// Adds the password unlock key, grant key, signing key and personal manifest access key rows of a validated hierarchy to the context.+ /// </summary>+ /// <param name="context">Database context, inside the caller's unit of work.</param>+ /// <param name="userId">The account owning the keys.</param>+ /// <param name="personalManifestId">The account's personal manifest.</param>+ /// <param name="keys">The keys, already accepted by <see cref="Validate"/>.</param>+ /// <param name="unlockKeyAlgorithm">The algorithm returned by <see cref="Validate"/>.</param>+ /// <param name="srpCredentials">The password unlock key's KDF parameters and SRP credentials.</param>+ /// <param name="now">The creation time.</param>+ public static void AddEntities(AliasServerDbContext context, string userId, Guid personalManifestId, AccountKeysUpload keys, VaultKeyAlgorithm unlockKeyAlgorithm, VaultKeyMetadata srpCredentials, DateTime now)+ {+ context.UserUnlockKeys.Add(new UserUnlockKey+ {+ Id = Guid.NewGuid(),+ UserId = userId,+ Type = UnlockMethodType.Password,+ Algorithm = unlockKeyAlgorithm,+ EncryptedAccountKey = keys.EncryptedAccountKey!,+ Metadata = srpCredentials.ToJson(),+ CreatedAt = now,+ UpdatedAt = now,+ });++ context.UserGrantKeys.Add(new UserGrantKey+ {+ Id = Guid.NewGuid(),+ UserId = userId,+ Algorithm = VaultKeyAlgorithm.RsaOaepSha256,+ PublicKey = keys.AccountPublicKey!,+ EncryptedPrivateKey = keys.EncryptedAccountPrivateKey!,+ PublicKeySignature = keys.AccountPublicKeySignature!,+ IsPrimary = true,+ CreatedAt = now,+ UpdatedAt = now,+ });++ context.UserSigningKeys.Add(new UserSigningKey+ {+ Id = Guid.NewGuid(),+ UserId = userId,+ Algorithm = SigningKeyAlgorithm.Ed25519,+ PublicKey = keys.SigningPublicKey!,+ EncryptedPrivateKey = keys.EncryptedSigningPrivateKey!,+ IsPrimary = true,+ CreatedAt = now,+ UpdatedAt = now,+ });++ context.VaultManifestAccessKeys.Add(new VaultManifestAccessKey+ {+ Id = Guid.NewGuid(),+ UserId = userId,+ VaultManifestId = personalManifestId,+ Type = ManifestKeyType.AccountKey,+ Algorithm = VaultKeyAlgorithm.Aes256Gcm,+ EncryptedVek = keys.EncryptedVek!,+ AccountKeyVersion = 0,+ CreatedAt = now,+ UpdatedAt = now,+ });+ }+}diff --git a/apps/server/AliasVault.Api/Models/IssuedTokens.cs b/apps/server/AliasVault.Api/Models/IssuedTokens.csnew file mode 100644index 000000000..1de7bc0b9--- /dev/null+++ b/apps/server/AliasVault.Api/Models/IssuedTokens.cs@@ -0,0 +1,15 @@+//-----------------------------------------------------------------------+// <copyright file="IssuedTokens.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.Api.Models;++/// <summary>+/// An access token and refresh token pair issued by the token service.+/// </summary>+/// <param name="Token">The access token (JWT).</param>+/// <param name="RefreshToken">The refresh token as handed to the client.</param>+public sealed record IssuedTokens(string Token, string RefreshToken);diff --git a/apps/server/AliasVault.Api/Models/LoginProofResult.cs b/apps/server/AliasVault.Api/Models/LoginProofResult.csnew file mode 100644index 000000000..5ccad0d87--- /dev/null+++ b/apps/server/AliasVault.Api/Models/LoginProofResult.cs@@ -0,0 +1,21 @@+//-----------------------------------------------------------------------+// <copyright file="LoginProofResult.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.Api.Models;++using AliasServerDb;+using AliasVault.Shared.Models.Enums;+using SecureRemotePassword;++/// <summary>+/// Outcome of checking a login's user state and SRP proof: the user and session on success, an error code otherwise.+/// </summary>+/// <param name="User">The user, set on success.</param>+/// <param name="ServerSession">The SRP server session, set on success.</param>+/// <param name="UnlockKeyId">The unlock key the proof was checked against; null for a legacy account.</param>+/// <param name="Error">The error code to answer with, null on success.</param>+public sealed record LoginProofResult(AliasVaultUser? User, SrpSession? ServerSession, Guid? UnlockKeyId, ApiErrorCode? Error);diff --git a/apps/server/AliasVault.Api/Program.cs b/apps/server/AliasVault.Api/Program.csindex bd698578f..0d4be3346 100644--- a/apps/server/AliasVault.Api/Program.cs+++ b/apps/server/AliasVault.Api/Program.cs@@ -100,6 +100,7 @@ builder.Services.AddSingleton<FaviconRateLimitService>();builder.Services.AddSingleton<TakenAliasLookupRateLimitService>();builder.Services.AddScoped<RateLimitService>();builder.Services.AddScoped<CapabilityService>();+builder.Services.AddScoped<TokenService>();builder.Services.AddHttpContextAccessor();builder.Services.AddRateLimiter(options => RegistrationCheckRateLimit.Configure(options, builder.Environment.IsDevelopment()));diff --git a/apps/server/AliasVault.Api/Services/TokenService.cs b/apps/server/AliasVault.Api/Services/TokenService.csnew file mode 100644index 000000000..235c45064--- /dev/null+++ b/apps/server/AliasVault.Api/Services/TokenService.cs@@ -0,0 +1,371 @@+//-----------------------------------------------------------------------+// <copyright file="TokenService.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.Api.Services;++using System.IdentityModel.Tokens.Jwt;+using System.Security.Claims;+using System.Security.Cryptography;+using System.Text;+using AliasServerDb;+using AliasVault.Api.Helpers;+using AliasVault.Api.Models;+using AliasVault.Auth;+using AliasVault.Auth.IpAddress;+using AliasVault.Shared.Models.Enums;+using AliasVault.Shared.Models.WebApi;+using AliasVault.Shared.Server.Services;+using AliasVault.Shared.Server.Utilities;+using Microsoft.AspNetCore.Identity;+using Microsoft.EntityFrameworkCore;+using Microsoft.Extensions.Caching.Memory;+using Microsoft.IdentityModel.Tokens;++/// <summary>+/// Issues and rotates access and refresh tokens, and checks login proofs, for the v2 auth controller.+/// </summary>+/// <param name="dbContextFactory">AliasServerDbContext factory.</param>+/// <param name="userManager">UserManager instance.</param>+/// <param name="configuration">IConfiguration instance.</param>+/// <param name="cache">IMemoryCache instance holding SRP exchanges and refresh token successors.</param>+/// <param name="timeProvider">TimeProvider instance.</param>+/// <param name="authLoggingService">AuthLoggingService instance.</param>+/// <param name="config">Config instance.</param>+/// <param name="settingsService">ServerSettingsService instance.</param>+public class TokenService(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IConfiguration configuration, IMemoryCache cache, TimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService)+{+ /// <summary>+ /// Access token claim with the id of the refresh token it was issued with.+ /// </summary>+ public const string RefreshTokenIdClaim = "rtid";++ /// <summary>+ /// Access token validity in seconds.+ /// </summary>+ private const int AccessTokenValiditySeconds = 600;++ /// <summary>+ /// Cache prefix for the successor of a rotated refresh token, followed by the user id and the hash of the rotated token.+ /// </summary>+ private const string CachePrefixRefreshTokenSuccessor = "RefreshTokenSuccessor_";++ /// <summary>+ /// How long after a rotation the replaced refresh token still returns the token that replaced it, so concurrent client refreshes do not log the device out.+ /// </summary>+ private static readonly TimeSpan RefreshTokenReuseWindow = TimeSpan.FromSeconds(30);++ /// <summary>+ /// Serialises token issuing and refresh token rotation across all requests.+ /// </summary>+ private static readonly SemaphoreSlim Semaphore = new(1, 1);++ /// <summary>+ /// Validates an access token's HS256 signature only (no issuer, audience or lifetime check), for the refresh flow.+ /// </summary>+ /// <param name="token">The access token.</param>+ /// <returns>Claims principal.</returns>+ /// <exception cref="SecurityTokenException">Thrown if provided token is invalid.</exception>+ public static ClaimsPrincipal GetPrincipalFromToken(string token)+ {+ var tokenValidationParameters = new TokenValidationParameters+ {+ ValidateAudience = false,+ ValidateIssuer = false,+ ValidateIssuerSigningKey = true,+ IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecretReader.GetJwtKey())),++ // We don't validate the token lifetime here, as we only use it for refresh tokens.+ ValidateLifetime = false,+ };++ var tokenHandler = new JwtSecurityTokenHandler();+ var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken securityToken);+ if (securityToken is not JwtSecurityToken jwtSecurityToken || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))+ {+ throw new SecurityTokenException("Invalid token");+ }++ return principal;+ }++ /// <summary>+ /// Issues a new access token and refresh token for a user and stores the refresh token.+ /// </summary>+ /// <param name="user">The user to issue the tokens for.</param>+ /// <param name="httpContext">The current request, for the device identifier and IP address.</param>+ /// <param name="extendedLifetime">Whether the refresh token gets the long (remember me) lifetime.</param>+ /// <param name="includeRefreshTokenIdClaim">Whether the access token carries the <see cref="RefreshTokenIdClaim"/> claim (v2 only).</param>+ /// <returns>The issued tokens.</returns>+ public async Task<IssuedTokens> IssueTokensAsync(AliasVaultUser user, HttpContext httpContext, bool extendedLifetime, bool includeRefreshTokenIdClaim)+ {+ var settings = await settingsService.GetAllSettingsAsync();++ await Semaphore.WaitAsync();+ try+ {+ var refreshTokenLifetimeHours = extendedLifetime ? settings.RefreshTokenLifetimeLong : settings.RefreshTokenLifetimeShort;+ return await CreateRefreshTokenAsync(user, httpContext, TimeSpan.FromHours(refreshTokenLifetimeHours), includeRefreshTokenIdClaim);+ }+ finally+ {+ Semaphore.Release();+ }+ }++ /// <summary>+ /// Rotates a refresh token: replaces it with a new one of the same lifetime, or returns its successor within the reuse window.+ /// </summary>+ /// <param name="user">The owner of the refresh token.</param>+ /// <param name="existingTokenValue">The refresh token presented by the client.</param>+ /// <param name="httpContext">The current request, for the device identifier and IP address.</param>+ /// <param name="includeRefreshTokenIdClaim">Whether the access token carries the <see cref="RefreshTokenIdClaim"/> claim (v2 only).</param>+ /// <returns>The issued tokens, or null when the refresh token is unknown or expired.</returns>+ public async Task<IssuedTokens?> RotateRefreshTokenAsync(AliasVaultUser user, string existingTokenValue, HttpContext httpContext, bool includeRefreshTokenIdClaim)+ {+ await using var context = await dbContextFactory.CreateDbContextAsync();+ await Semaphore.WaitAsync();++ try+ {+ // Token reuse window: if this token was rotated in the last 30 seconds, hand out the token that replaced it+ // again, so concurrent refreshes from one client do not log it out. The stored row only has the hash, so the+ // successor comes from memory and is forgotten when the window closes.+ var existingTokenHash = RefreshTokenHasher.Hash(existingTokenValue);+ if (cache.TryGetValue(RefreshTokenSuccessorCacheKey(user, existingTokenHash), out RefreshTokenSuccessor? successor) && successor is not null)+ {+ return new IssuedTokens(GenerateJwtToken(user, includeRefreshTokenIdClaim ? successor.Id : null), successor.RefreshToken);+ }++ // Check if the refresh token still exists and is not expired.+ var existingToken = await context.AliasVaultUserRefreshTokens.FirstOrDefaultAsync(t => t.UserId == user.Id && t.TokenHash == existingTokenHash);+ if (existingToken == null || existingToken.ExpireDate < timeProvider.GetUtcNow().UtcDateTime)+ {+ return null;+ }++ context.AliasVaultUserRefreshTokens.Remove(existingToken);++ // New refresh token lifetime is the same as the existing one.+ var existingTokenLifetime = existingToken.ExpireDate - existingToken.CreatedAt;+ var newTokens = await CreateRefreshTokenAsync(user, httpContext, existingTokenLifetime, includeRefreshTokenIdClaim, existingToken.TokenHash);++ // After successfully storing the new refresh token, remove the existing one by saving changes.+ await context.SaveChangesAsync();++ return newTokens;+ }+ finally+ {+ Semaphore.Release();+ }+ }++ /// <summary>+ /// Validates whether a username meets the registration criteria and is not taken.+ /// </summary>+ /// <param name="username">The username to validate.</param>+ /// <returns>Whether the username is valid, and the error code (or USERNAME_AVAILABLE) to answer with.</returns>+ public async Task<(bool IsValid, ApiErrorCode ApiErrorCode)> ValidateUsernameAsync(string username)+ {+ const int minimumUsernameLength = 3;+ const int maximumUsernameLength = 40;+ const string adminUsername = "admin";++ if (string.IsNullOrWhiteSpace(username))+ {+ return (false, ApiErrorCode.USERNAME_EMPTY_OR_WHITESPACE);+ }++ if (username.Length < minimumUsernameLength)+ {+ return (false, ApiErrorCode.USERNAME_TOO_SHORT);+ }++ if (username.Length > maximumUsernameLength)+ {+ return (false, ApiErrorCode.USERNAME_TOO_LONG);+ }++ // Disallow admin username to prevent conflicts with the default admin user+ if (string.Equals(username, adminUsername, StringComparison.OrdinalIgnoreCase))+ {+ return (false, ApiErrorCode.USERNAME_ALREADY_IN_USE);+ }++ // Check if username is not taken already+ var existingUser = await userManager.FindByNameAsync(username);+ if (existingUser != null)+ {+ return (false, ApiErrorCode.USERNAME_ALREADY_IN_USE);+ }++ // Check if it's a valid email address+ if (username.Contains('@'))+ {+ try+ {+ var addr = new System.Net.Mail.MailAddress(username);+ return (addr.Address == username, ApiErrorCode.USERNAME_INVALID_EMAIL);+ }+ catch+ {+ return (false, ApiErrorCode.USERNAME_INVALID_EMAIL);+ }+ }++ // If it's not an email, check if it only contains letters and digits+ if (!username.All(char.IsLetterOrDigit))+ {+ return (false, ApiErrorCode.USERNAME_INVALID_CHARACTERS);+ }++ return (true, ApiErrorCode.USERNAME_AVAILABLE);+ }++ /// <summary>+ /// Checks the user's lockout and blocked state and the SRP login proof; a wrong proof counts towards lockout.+ /// </summary>+ /// <param name="username">The username.</param>+ /// <param name="clientPublicEphemeral">The client's public ephemeral.</param>+ /// <param name="clientSessionProof">The client's session proof.</param>+ /// <param name="loginSessionId">The login session id (v2), or null for the per-identity v1 exchange.</param>+ /// <returns>The user and session on success, the error code otherwise.</returns>+ public async Task<LoginProofResult> ValidateUserAndPasswordAsync(string username, string clientPublicEphemeral, string clientSessionProof, string? loginSessionId)+ {+ var user = await userManager.FindByNameAsync(username);+ if (user == null)+ {+ await authLoggingService.LogAuthEventFailAsync(username, AuthEventType.Login, AuthFailureReason.InvalidUsername);+ return new LoginProofResult(null, null, null, ApiErrorCode.USER_NOT_FOUND);+ }++ // Check if the account is locked out.+ if (await userManager.IsLockedOutAsync(user))+ {+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthentication, AuthFailureReason.AccountLocked);+ return new LoginProofResult(null, null, null, ApiErrorCode.ACCOUNT_LOCKED);+ }++ // Check if the account is blocked.+ if (user.Blocked)+ {+ await authLoggingService.LogAuthEventFailAsync(username, AuthEventType.Login, AuthFailureReason.AccountBlocked);+ return new LoginProofResult(null, null, null, ApiErrorCode.ACCOUNT_BLOCKED);+ }++ // Validate the SRP session (actual password check).+ await using var context = await dbContextFactory.CreateDbContextAsync();+ var srpResult = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, SrpPurpose.Login, clientPublicEphemeral, clientSessionProof, loginSessionId);+ if (srpResult.Session is null)+ {+ if (srpResult.ActiveSessionFound)+ {+ // Incorrect password: increment failed login attempts which then locks out the account when the limit is reached.+ await userManager.AccessFailedAsync(user);+ }++ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.Login, srpResult.FailureReason);+ return new LoginProofResult(null, null, null, ApiErrorCode.USER_NOT_FOUND);+ }++ return new LoginProofResult(user, srpResult.Session, srpResult.UnlockKeyId, null);+ }++ /// <summary>+ /// Cache key under which the successor of a rotated refresh token is kept for the reuse window.+ /// </summary>+ /// <param name="user">The owner of the token.</param>+ /// <param name="rotatedTokenHash">The hash of the token that was rotated away.</param>+ /// <returns>The cache key.</returns>+ private static string RefreshTokenSuccessorCacheKey(AliasVaultUser user, string rotatedTokenHash) => $"{CachePrefixRefreshTokenSuccessor}{user.Id}_{rotatedTokenHash}";++ /// <summary>+ /// Generates a new refresh token value: 32 random bytes, base64.+ /// </summary>+ /// <returns>Random string to be used as refresh token.</returns>+ private static string GenerateRefreshTokenValue()+ {+ var randomNumber = new byte[32];+ using var rng = RandomNumberGenerator.Create();++ rng.GetBytes(randomNumber);+ return Convert.ToBase64String(randomNumber);+ }++ /// <summary>+ /// Generates a short-lived HS256 access token for a user.+ /// </summary>+ /// <param name="user">The user to generate the access token for.</param>+ /// <param name="refreshTokenId">The id of the refresh token issued with it, added as <see cref="RefreshTokenIdClaim"/>; null leaves the claim out.</param>+ /// <returns>Access token as string.</returns>+ private string GenerateJwtToken(AliasVaultUser user, Guid? refreshTokenId)+ {+ var claims = new List<Claim>+ {+ new(ClaimTypes.NameIdentifier, user.Id),+ new(ClaimTypes.Name, user.UserName ?? string.Empty),+ new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),+ };++ if (refreshTokenId is not null)+ {+ claims.Add(new(RefreshTokenIdClaim, refreshTokenId.Value.ToString()));+ }++ var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecretReader.GetJwtKey()));+ var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);++ var token = new JwtSecurityToken(+ issuer: configuration["Jwt:Issuer"] ?? string.Empty,+ audience: configuration["Jwt:Issuer"] ?? string.Empty,+ claims: claims,+ expires: timeProvider.GetUtcNow().UtcDateTime.AddSeconds(AccessTokenValiditySeconds),+ signingCredentials: credentials);++ return new JwtSecurityTokenHandler().WriteToken(token);+ }++ /// <summary>+ /// Stores a new refresh token row and returns it with a matching access token; caller holds the semaphore.+ /// </summary>+ /// <param name="user">The user to generate the tokens for.</param>+ /// <param name="httpContext">The current request, for the device identifier and IP address.</param>+ /// <param name="newTokenLifetime">The lifetime of the new refresh token.</param>+ /// <param name="includeRefreshTokenIdClaim">Whether the access token carries the <see cref="RefreshTokenIdClaim"/> claim.</param>+ /// <param name="existingTokenHash">The hash of the refresh token being replaced, if any.</param>+ /// <returns>The issued tokens.</returns>+ private async Task<IssuedTokens> CreateRefreshTokenAsync(AliasVaultUser user, HttpContext httpContext, TimeSpan newTokenLifetime, bool includeRefreshTokenIdClaim, string? existingTokenHash = null)+ {+ await using var context = await dbContextFactory.CreateDbContextAsync();++ var refreshTokenId = Guid.NewGuid();+ var accessToken = GenerateJwtToken(user, includeRefreshTokenIdClaim ? refreshTokenId : null);+ var refreshToken = GenerateRefreshTokenValue();+ var deviceIdentifier = AuthHelper.GenerateDeviceIdentifier(httpContext.Request);++ context.AliasVaultUserRefreshTokens.Add(new AliasVaultUserRefreshToken+ {+ Id = refreshTokenId,+ UserId = user.Id,+ DeviceIdentifier = deviceIdentifier,+ IpAddress = IpAddressUtility.GetAnonymizedIpFromContext(httpContext, config.IpLoggingEnabled),+ TokenHash = RefreshTokenHasher.Hash(refreshToken),+ PreviousTokenHash = existingTokenHash,+ ExpireDate = timeProvider.GetUtcNow().UtcDateTime.Add(newTokenLifetime),+ CreatedAt = timeProvider.GetUtcNow().UtcDateTime,+ });++ await context.SaveChangesAsync();++ if (existingTokenHash is not null)+ {+ cache.Set(RefreshTokenSuccessorCacheKey(user, existingTokenHash), new RefreshTokenSuccessor(refreshTokenId, refreshToken), RefreshTokenReuseWindow);+ }++ return new IssuedTokens(accessToken, refreshToken);+ }+}diff --git a/apps/server/Databases/AliasServerDb/Retention/UnlockKeyHistoryPolicy.cs b/apps/server/Databases/AliasServerDb/Retention/UnlockKeyHistoryPolicy.csindex 72ca4718d..53bde2510 100644--- a/apps/server/Databases/AliasServerDb/Retention/UnlockKeyHistoryPolicy.cs+++ b/apps/server/Databases/AliasServerDb/Retention/UnlockKeyHistoryPolicy.cs@@ -25,6 +25,38 @@ public static class UnlockKeyHistoryPolicy/// <returns>The retention window in days, never negative.</returns>public static int EffectiveRetentionDays(int configuredDays) => Math.Max(configuredDays, 0);+ /// <summary>+ /// Archives an unlock key that is about to be overwritten and prunes older rows of that method to stay within <see cref="MaxRowsPerMethod"/>.+ /// </summary>+ /// <param name="context">Database context, inside the caller's transaction; the caller saves the added row.</param>+ /// <param name="unlockKey">The unlock key as it is before being overwritten.</param>+ /// <param name="configuredDays">The configured UnlockKeyHistoryRetentionDays value.</param>+ /// <param name="now">The current time.</param>+ /// <param name="client">The client (or marker such as "admin-revert") recorded on the archived row.</param>+ /// <returns>Task.</returns>+ public static async Task ArchiveAsync(AliasServerDbContext context, UserUnlockKey unlockKey, int configuredDays, DateTime now, string? client)+ {+ if (EffectiveRetentionDays(configuredDays) == 0)+ {+ return;+ }++ // Prune first, leaving room for the row added below: the limit counts that row, so one fewer is skipped here.+ var supersededIds = await context.UserUnlockKeysHistory+ .Where(x => x.UserId == unlockKey.UserId && x.Type == unlockKey.Type)+ .OrderByDescending(x => x.ArchivedAt)+ .Skip(MaxRowsPerMethod - 1)+ .Select(x => x.Id)+ .ToListAsync();++ if (supersededIds.Count > 0)+ {+ await context.UserUnlockKeysHistory.Where(x => supersededIds.Contains(x.Id)).ExecuteDeleteAsync();+ }++ context.UserUnlockKeysHistory.Add(UserUnlockKeysHistory.CreateFrom(unlockKey, now, client));+ }+/// <summary>/// Narrows a query to the archived rows that are still within the retention window. Returns an empty query when archiving is off./// </summary>diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.csindex f2c55ed35..747e68d64 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/RegisterRequest.cs@@ -123,14 +123,18 @@ public class RegisterRequestpublic string? InviteCode { get; init; }/// <summary>- /// Gets a value indicating whether the client sent the complete account key hierarchy. A partial one is not usable.+ /// Returns the account key fields as an <see cref="AccountKeysUpload"/>./// </summary>- public bool HasCompleteAccountKeys => !string.IsNullOrEmpty(EncryptedVek) && !string.IsNullOrEmpty(EncryptedAccountKey) && !string.IsNullOrEmpty(EncryptedAccountKeyAlgorithm) && !string.IsNullOrEmpty(AccountPublicKey) && !string.IsNullOrEmpty(EncryptedAccountPrivateKey)- && !string.IsNullOrEmpty(SigningPublicKey) && !string.IsNullOrEmpty(EncryptedSigningPrivateKey) && !string.IsNullOrEmpty(AccountPublicKeySignature);-- /// <summary>- /// Gets a value indicating whether every account key fits its storage column, so an oversized value is a validation error instead of a half-created account.- /// </summary>- public bool AccountKeysFitStorageLimits => (EncryptedVek?.Length ?? 0) <= AccountKeysUpload.MaxWrappedKeyLength && (EncryptedAccountKey?.Length ?? 0) <= AccountKeysUpload.MaxWrappedKeyLength && (AccountPublicKey?.Length ?? 0) <= AccountKeysUpload.MaxPublicKeyLength && (EncryptedAccountPrivateKey?.Length ?? 0) <= AccountKeysUpload.MaxEncryptedPrivateKeyLength- && (SigningPublicKey?.Length ?? 0) <= AccountKeysUpload.MaxSigningPublicKeyLength && (EncryptedSigningPrivateKey?.Length ?? 0) <= AccountKeysUpload.MaxSigningValueLength && (AccountPublicKeySignature?.Length ?? 0) <= AccountKeysUpload.MaxSigningValueLength;+ /// <returns>The account key hierarchy of this request.</returns>+ public AccountKeysUpload ToAccountKeysUpload() => new()+ {+ EncryptedAccountKey = EncryptedAccountKey,+ EncryptedAccountKeyAlgorithm = EncryptedAccountKeyAlgorithm,+ EncryptedVek = EncryptedVek,+ AccountPublicKey = AccountPublicKey,+ EncryptedAccountPrivateKey = EncryptedAccountPrivateKey,+ SigningPublicKey = SigningPublicKey,+ EncryptedSigningPrivateKey = EncryptedSigningPrivateKey,+ AccountPublicKeySignature = AccountPublicKeySignature,+ };}