Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

63.4 KB
Raw Blame
//-----------------------------------------------------------------------
// <copyright file="AuthController.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.Controllers.V2;

using System.Buffers.Text;
using System.Security.Claims;
using System.Security.Cryptography;
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.Api.Services.RateLimiting;
using AliasVault.Api.Services.RateLimiting.Helpers;
using AliasVault.Auth;
using AliasVault.Auth.IpAddress;
using AliasVault.Cryptography;
using AliasVault.Shared;
using AliasVault.Shared.Models.Enums;
using AliasVault.Shared.Models.WebApi;
using AliasVault.Shared.Models.WebApi.V2.Auth;
using AliasVault.Shared.Models.WebApi.V2.Vault;
using AliasVault.Shared.Server.Services;
using AliasVault.Shared.Server.Utilities;
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using SecureRemotePassword;

/// <summary>
/// Login, registration, password change, session tokens, Login with Mobile and account deletion.
/// </summary>
/// <param name="dbContextFactory">AliasServerDbContext instance.</param>
/// <param name="userManager">UserManager 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>
/// <param name="config">Config instance.</param>
/// <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, IMemoryCache cache, TimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, IpBlockListService ipBlockListService, RegistrationInviteService registrationInviteService, TokenService tokenService) : ControllerBase
{
    /// <summary>
    /// Login endpoint used to process login attempt using credentials.
    /// </summary>
    /// <param name="model">Login model.</param>
    /// <param name="loginRateLimitService">LoginRateLimitService instance.</param>
    /// <returns>IActionResult.</returns>
    [HttpPost("login")]
    public async Task<IActionResult> Login([FromBody] LoginInitiateRequest model, [FromServices] LoginRateLimitService loginRateLimitService)
    {
        // Check the IP blocklist.
        if (await ipBlockListService.IsBlockedForLoginAsync(IpAddressUtility.GetRawIpAddressFromContext(HttpContext)))
        {
            await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.IpBlocked);
            return ApiError.Result(ApiErrorCode.ACCOUNT_BLOCKED, 400);
        }

        // Cap the logins one IP starts across accounts.
        if (!loginRateLimitService.TryRecordLogin(HttpContext, (await settingsService.GetAllSettingsAsync()).MaxLoginAttemptsPerIpPerMinute))
        {
            await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.LoginRateLimitExceeded);
            return ApiError.Result(ApiErrorCode.RATE_LIMIT_EXCEEDED, 429);
        }

        var user = await userManager.FindByNameAsync(model.Username);

        // If user doesn't exist, generate or retrieve fake data to prevent user enumeration attacks.
        if (user == null)
        {
            // Log the attempt internally
            await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.InvalidUsername);
            return FakeLoginResponse(FakeLoginHelper.Create(model.Username));
        }

        // Check if the account is locked out.
        if (await userManager.IsLockedOutAsync(user))
        {
            await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.TwoFactorAuthentication, AuthFailureReason.AccountLocked);
            return 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 ApiError.Result(ApiErrorCode.ACCOUNT_BLOCKED, 400);
        }

        // Retrieve latest vault of user which contains the current salt and verifier.
        await using var context = await dbContextFactory.CreateDbContextAsync();
        var latestVaultEncryptionSettings = await AuthHelper.GetUserLatestVaultEncryptionSettingsAsync(context, user);

        var srpIdentity = AuthHelper.GetSrpIdentity(user);

        var loginSessionId = AuthHelper.CreateSrpSessionId();
        var serverEphemeral = AuthHelper.CreateSrpEphemeral(cache, user, SrpPurpose.Login, latestVaultEncryptionSettings, loginSessionId);

        return Ok(new LoginInitiateResponse(latestVaultEncryptionSettings.Salt, serverEphemeral, latestVaultEncryptionSettings.EncryptionType, latestVaultEncryptionSettings.EncryptionSettings, srpIdentity, loginSessionId));
    }

    /// <summary>
    /// Validate endpoint used to validate the client's proof and generate the server's proof.
    /// </summary>
    /// <param name="model">ValidateLoginRequest model.</param>
    /// <returns>IActionResult.</returns>
    [HttpPost("validate")]
    public async Task<IActionResult> Validate([FromBody] ValidateLoginRequest model)
    {
        var (user, serverSession, unlockMethodId, error) = await ValidateUserAndPassword(model);
        if (error is not null)
        {
            return error;
        }

        // If 2FA is required, return that status and no JWT token yet.
        if (user!.TwoFactorEnabled)
        {
            await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.Login);
            return Ok(new ValidateLoginResponse(true, string.Empty, null));
        }

        // Spend the login exchange so its proof cannot be replayed.
        if (!AuthHelper.ConsumeSrpSession(cache, user, model.LoginSessionId))
        {
            return ApiError.Result(ApiErrorCode.USER_NOT_FOUND, 400);
        }

        // Reset failed login attempts.
        await userManager.ResetAccessFailedCountAsync(user);
        await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.Login);
        await UpgradeLegacySrpVerifierAsync(unlockMethodId, model);

        var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: model.RememberMe);
        return Ok(new ValidateLoginResponse(false, serverSession!.Proof, tokenModel));
    }

    /// <summary>
    /// Validate login including two-factor authentication code check.
    /// </summary>
    /// <param name="model">ValidateLoginRequest2Fa model.</param>
    /// <returns>Task.</returns>
    [HttpPost("validate-2fa")]
    public async Task<IActionResult> Validate2Fa([FromBody] ValidateLoginRequest2Fa model)
    {
        var (user, serverSession, unlockMethodId, error) = await ValidateUserAndPassword(model);
        if (error is not null)
        {
            return error;
        }

        if (user == null || serverSession == null)
        {
            return ApiError.Result(ApiErrorCode.USER_NOT_FOUND, 400);
        }

        // Verify 2-factor code.
        var verifyResult = await userManager.VerifyTwoFactorTokenAsync(user, userManager.Options.Tokens.AuthenticatorTokenProvider, model.Code2Fa.ToString());
        if (!verifyResult)
        {
            // Increment failed login attempts in order to lock out the account when the limit is reached.
            await userManager.AccessFailedAsync(user);

            await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.TwoFactorAuthentication, AuthFailureReason.InvalidTwoFactorCode);
            return ApiError.Result(ApiErrorCode.INVALID_AUTHENTICATOR_CODE, 400);
        }

        // Spend the login exchange so its proof cannot be replayed.
        if (!AuthHelper.ConsumeSrpSession(cache, user, model.LoginSessionId))
        {
            return ApiError.Result(ApiErrorCode.USER_NOT_FOUND, 400);
        }

        // Validation of 2-FA token is successful, user is authenticated.
        await userManager.ResetAccessFailedCountAsync(user);
        await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.TwoFactorAuthentication);
        await UpgradeLegacySrpVerifierAsync(unlockMethodId, model);

        // Generate and return the JWT token.
        var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: model.RememberMe);
        return Ok(new ValidateLoginResponse(false, serverSession.Proof, tokenModel));
    }

    /// <summary>
    /// Validate login including two-factor authentication recovery code check.
    /// </summary>
    /// <param name="model">ValidateLoginRequestRecoveryCode model.</param>
    /// <returns>Task.</returns>
    [HttpPost("validate-recovery-code")]
    public async Task<IActionResult> ValidateRecoveryCode([FromBody] ValidateLoginRequestRecoveryCode model)
    {
        var (user, serverSession, unlockMethodId, error) = await ValidateUserAndPassword(model);
        if (error is not null)
        {
            return error;
        }

        if (user == null || serverSession == null)
        {
            return ApiError.Result(ApiErrorCode.USER_NOT_FOUND, 400);
        }

        // Sanitize recovery code.
        var recoveryCode = model.RecoveryCode.Replace(" ", string.Empty).ToUpper();

        // Attempt to redeem the recovery code
        var redeemResult = await userManager.RedeemTwoFactorRecoveryCodeAsync(user, recoveryCode);

        if (!redeemResult.Succeeded)
        {
            // Increment failed login attempts in order to lock out the account when the limit is reached.
            await userManager.AccessFailedAsync(user);

            await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.TwoFactorAuthentication, AuthFailureReason.InvalidRecoveryCode);
            return ApiError.Result(ApiErrorCode.INVALID_RECOVERY_CODE, 400);
        }

        // Spend the login exchange so its proof cannot be replayed.
        if (!AuthHelper.ConsumeSrpSession(cache, user, model.LoginSessionId))
        {
            return ApiError.Result(ApiErrorCode.USER_NOT_FOUND, 400);
        }

        // Recovery code is valid, user is authenticated.
        await userManager.ResetAccessFailedCountAsync(user);
        await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.TwoFactorAuthentication);
        await UpgradeLegacySrpVerifierAsync(unlockMethodId, model);

        // Generate and return the JWT token.
        var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: model.RememberMe);
        return Ok(new ValidateLoginResponse(false, serverSession.Proof, tokenModel));
    }

    /// <summary>
    /// Refresh endpoint used to refresh an expired access token using a valid refresh token.
    /// </summary>
    /// <param name="tokenModel">Token model.</param>
    /// <returns>IActionResult.</returns>
    [HttpPost("refresh")]
    public async Task<IActionResult> Refresh([FromBody] TokenModel tokenModel)
    {
        await using var context = await dbContextFactory.CreateDbContextAsync();

        // If the token is not provided, return bad request.
        if (string.IsNullOrWhiteSpace(tokenModel.RefreshToken))
        {
            return ApiError.Result(ApiErrorCode.REFRESH_TOKEN_REQUIRED, 400);
        }

        ClaimsPrincipal principal;
        try
        {
            principal = TokenService.GetPrincipalFromToken(tokenModel.Token);
        }
        catch (Exception)
        {
            // If token validation fails (expired, malformed, or invalid signature),
            // return unauthorized as we cannot identify the user from the access token.
            return ApiError.Result(ApiErrorCode.INVALID_REFRESH_TOKEN, 401);
        }

        if (principal.FindFirst(ClaimTypes.NameIdentifier)?.Value == null)
        {
            return ApiError.Result(ApiErrorCode.INVALID_REFRESH_TOKEN, 401);
        }

        var user = await userManager.FindByIdAsync(principal.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty);
        if (user == null)
        {
            return ApiError.Result(ApiErrorCode.INVALID_REFRESH_TOKEN, 401);
        }

        // Check if the account is blocked.
        if (user.Blocked)
        {
            await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TokenRefresh, AuthFailureReason.AccountBlocked);
            return ApiError.Result(ApiErrorCode.ACCOUNT_BLOCKED, 401);
        }

        // Check the IP blocklist.
        if (await ipBlockListService.IsBlockedForLoginAsync(IpAddressUtility.GetRawIpAddressFromContext(HttpContext)))
        {
            await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TokenRefresh, AuthFailureReason.IpBlocked);
            return ApiError.Result(ApiErrorCode.ACCOUNT_BLOCKED, 401);
        }

        // Generate new tokens for the user.
        var token = await GenerateNewTokensForUser(user, tokenModel.RefreshToken);
        if (token == null)
        {
            await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TokenRefresh, AuthFailureReason.InvalidRefreshToken);
            return ApiError.Result(ApiErrorCode.INVALID_REFRESH_TOKEN, 401);
        }

        await context.SaveChangesAsync();

        await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.TokenRefresh);
        return Ok(new TokenModel() { Token = token.Token, RefreshToken = token.RefreshToken });
    }

    /// <summary>
    /// Revoke endpoint used to revoke all refresh tokens for the current device.
    /// </summary>
    /// <param name="model">Token model.</param>
    /// <returns>IActionResult.</returns>
    [HttpPost("revoke")]
    public async Task<IActionResult> Revoke([FromBody] TokenModel model)
    {
        await using var context = await dbContextFactory.CreateDbContextAsync();

        // If the refresh token is not provided, return bad request.
        if (string.IsNullOrWhiteSpace(model.RefreshToken))
        {
            return ApiError.Result(ApiErrorCode.REFRESH_TOKEN_REQUIRED, 400);
        }

        // Look up the refresh token directly - we don't need to validate the access token
        // since the refresh token itself contains the user information we need.
        var tokenHash = RefreshTokenHasher.Hash(model.RefreshToken);
        var refreshTokenEntry = await context.AliasVaultUserRefreshTokens.Include(t => t.User).FirstOrDefaultAsync(t => t.TokenHash == tokenHash);

        if (refreshTokenEntry == null)
        {
            // Token doesn't exist: could already be revoked or never existed.
            // Return success to avoid leaking information about token validity.
            return Ok();
        }

        var user = refreshTokenEntry.User;

        // Remove the provided refresh token and any other existing refresh tokens that are issued to the current device ID.
        // This to make sure all tokens are revoked for this device that user is "logging out" from.
        var deviceIdentifier = AuthHelper.GenerateDeviceIdentifier(Request);
        var allDeviceTokens = await context.AliasVaultUserRefreshTokens.Where(t => t.UserId == user.Id && (t.TokenHash == tokenHash || t.DeviceIdentifier == deviceIdentifier)).ToListAsync();
        context.AliasVaultUserRefreshTokens.RemoveRange(allDeviceTokens);
        await context.SaveChangesAsync();

        await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.Logout);
        return Ok();
    }

    /// <summary>
    /// Revoke endpoint used to revoke only a specific refresh token (not all device tokens).
    /// This is useful for scenarios like mobile unlock where we want to revoke the old token
    /// before receiving a new one, without affecting other sessions.
    /// </summary>
    /// <param name="model">Token model.</param>
    /// <returns>IActionResult.</returns>
    [HttpPost("revoke-token")]
    public async Task<IActionResult> RevokeToken([FromBody] TokenModel model)
    {
        await using var context = await dbContextFactory.CreateDbContextAsync();

        // If the refresh token is not provided, return bad request.
        if (string.IsNullOrWhiteSpace(model.RefreshToken))
        {
            return ApiError.Result(ApiErrorCode.REFRESH_TOKEN_REQUIRED, 400);
        }

        // Look up the refresh token directly.
        var tokenHash = RefreshTokenHasher.Hash(model.RefreshToken);
        var refreshTokenEntry = await context.AliasVaultUserRefreshTokens.Include(t => t.User).FirstOrDefaultAsync(t => t.TokenHash == tokenHash);

        if (refreshTokenEntry == null)
        {
            // Token doesn't exist - could already be revoked or never existed.
            // Return success to avoid leaking information about token validity.
            return Ok();
        }

        // Remove only the specific token, not other device tokens
        context.AliasVaultUserRefreshTokens.Remove(refreshTokenEntry);
        await context.SaveChangesAsync();

        return Ok();
    }

    /// <summary>
    /// Register endpoint used to register a new user.
    /// </summary>
    /// <param name="model">Register request model.</param>
    /// <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.
        var requiresInvite = !config.PublicRegistrationEnabled;
        if (requiresInvite && string.IsNullOrWhiteSpace(model.InviteCode))
        {
            return ApiError.Result(ApiErrorCode.PUBLIC_REGISTRATION_DISABLED, 400);
        }

        // Check the IP blocklist using the raw IP address.
        var rawIpAddress = IpAddressUtility.GetRawIpAddressFromContext(HttpContext);
        if (await ipBlockListService.IsBlockedForRegistrationAsync(rawIpAddress))
        {
            await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Register, AuthFailureReason.IpBlocked);
            return ApiError.Result(ApiErrorCode.REGISTRATION_FAILED, 400);
        }

        // 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)
        {
            return ApiError.Result(apiErrorCode, 400);
        }

        // 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.
        var accountKeys = model.ToAccountKeysUpload();
        var accountKeysError = AccountKeyHierarchyHelper.Validate(accountKeys, out var accountKeyAlgorithm);
        if (accountKeysError is not null)
        {
            return ApiError.Result(accountKeysError.Value, 400);
        }

        if (!UnlockMethodParameterValidator.IsValidKekDerivationParams(model.EncryptionType, model.EncryptionSettings) || !UnlockMethodParameterValidator.WithinSrpCredentialLimits(model.Salt, model.Verifier) || !UnlockMethodParameterValidator.IsValidSrpIdentity(model.SrpIdentity))
        {
            return ApiError.Result(ApiErrorCode.INVALID_ENCRYPTION_PARAMETERS, 400);
        }

        var user = new AliasVaultUser
        {
            UserName = UsernameHelper.NormalizeUsername(model.Username),
            SrpIdentity = model.SrpIdentity,
            CreatedAt = timeProvider.GetUtcNow().UtcDateTime,
            UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,
            PasswordChangedAt = timeProvider.GetUtcNow().UtcDateTime,
        };

        Guid? inviteId = null;
        if (requiresInvite)
        {
            inviteId = await registrationInviteService.TryConsumeAsync(model.InviteCode);
            if (inviteId is null)
            {
                await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Register, AuthFailureReason.InvalidInviteCode);
                return ApiError.Result(ApiErrorCode.INVITE_CODE_INVALID, 400);
            }
        }

        var personalManifestId = Guid.NewGuid();

        // Create the personal group before the user row.
        var personalGroup = GroupHelper.CreatePersonalGroup(user, timeProvider.GetUtcNow().UtcDateTime);
        await using (var context = await dbContextFactory.CreateDbContextAsync())
        {
            context.Groups.Add(personalGroup);
            await context.SaveChangesAsync();
        }

        IdentityResult result;
        try
        {
            result = await userManager.CreateAsync(user);
        }
        catch (DbUpdateException)
        {
            result = IdentityResult.Failed(userManager.ErrorDescriber.DuplicateUserName(user.UserName!));
        }

        if (result.Succeeded)
        {
            // Create the owner membership and personal manifest.
            await using (var context = await dbContextFactory.CreateDbContextAsync())
            {
                context.GroupMembers.Add(GroupHelper.CreateOwnerMembership(personalGroup, user.Id, timeProvider.GetUtcNow().UtcDateTime));

                // Create placeholder manifest for the account which is empty and will be replaced by the first real manifest push by the client.
                context.VaultManifests.Add(new AliasServerDb.VaultManifest
                {
                    ManifestId = personalManifestId,
                    OwnerGroupId = personalGroup.Id,
                    StorageFormat = VaultManifestBase.ManifestStorageFormat,
                    Version = null,
                    RevisionNumber = 0,
                    Salt = null,
                    Verifier = null,
                    EncryptionType = null,
                    EncryptionSettings = null,
                    FileSize = 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, accountKeyAlgorithm, srpCredentials, timeProvider.GetUtcNow().UtcDateTime);

                await context.SaveChangesAsync();
            }

            await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.Register);

            // Return the token.
            var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: true);
            return Ok(tokenModel);
        }

        // Identity creation failed: remove the personal group written ahead of the user row above and give the invite use back.
        await using (var context = await dbContextFactory.CreateDbContextAsync())
        {
            await context.Groups.Where(g => g.Id == personalGroup.Id).ExecuteDeleteAsync();
        }

        if (inviteId is not null)
        {
            await registrationInviteService.ReleaseAsync(inviteId.Value);
        }

        // A concurrent registration can take the username between the availability check and the insert.
        var usernameTaken = result.Errors.Any(e => e.Code == nameof(IdentityErrorDescriber.DuplicateUserName));
        return ApiError.Result(usernameTaken ? ApiErrorCode.USERNAME_ALREADY_IN_USE : ApiErrorCode.REGISTRATION_FAILED, 400);
    }

    /// <summary>
    /// Password change request is done by verifying the current password and then saving the new password via SRP.
    /// </summary>
    /// <returns>Task.</returns>
    [HttpGet("change-password/initiate")]
    [Authorize]
    public async Task<IActionResult> InitiatePasswordChange()
    {
        var user = await userManager.GetUserAsync(User);
        if (user == null)
        {
            return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
        }

        // Retrieve latest vault of user which contains the current salt and verifier.
        await using var context = await dbContextFactory.CreateDbContextAsync();
        var latestVaultEncryptionSettings = await AuthHelper.GetUserLatestVaultEncryptionSettingsAsync(context, user);

        var srpIdentity = AuthHelper.GetSrpIdentity(user);

        var serverEphemeral = AuthHelper.CreateSrpEphemeral(cache, user, SrpPurpose.PasswordChange, latestVaultEncryptionSettings);

        return Ok(new PasswordChangeInitiateResponse(latestVaultEncryptionSettings.Salt, serverEphemeral, latestVaultEncryptionSettings.EncryptionType, latestVaultEncryptionSettings.EncryptionSettings, srpIdentity));
    }

    /// <summary>
    /// Password change submit. Verifies the current password via SRP, then atomically updates the password
    /// unlock-method row with the new salt/verifier and the Account Key re-encrypted with the new KEK.
    /// </summary>
    /// <param name="model">Password change request model.</param>
    /// <returns>IActionResult.</returns>
    [HttpPost("change-password")]
    [Authorize]
    public async Task<IActionResult> ChangePassword([FromBody] PasswordChangeRequest model)
    {
        var user = await userManager.GetUserAsync(User);
        if (user == null)
        {
            return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
        }

        await using var context = await dbContextFactory.CreateDbContextAsync();
        var unlockMethod = await context.UserUnlockMethods.FirstOrDefaultAsync(x => x.UserId == user.Id && x.Type == UnlockMethodType.Password);
        if (unlockMethod == null)
        {
            // Legacy users that have not migrated to v2 yet need to use the v1 flow (or migrate first).
            return ApiError.Result(ApiErrorCode.VAULT_KEY_NOT_FOUND, 400);
        }

        // Validate the new KDF parameters and the size of the new credentials.
        var accountKeyFits = !string.IsNullOrEmpty(model.NewEncryptedAccountKey) && model.NewEncryptedAccountKey.Length <= AccountKeysUpload.MaxWrappedKeyLength;
        if (!UnlockMethodParameterValidator.IsValidKekDerivationParams(model.NewEncryptionType, model.NewEncryptionSettings) || !UnlockMethodParameterValidator.WithinSrpCredentialLimits(model.NewPasswordSalt, model.NewPasswordVerifier) || !accountKeyFits)
        {
            return ApiError.Result(ApiErrorCode.INVALID_ENCRYPTION_PARAMETERS, 400);
        }

        if (!VaultKeyAlgorithms.TryParse(model.NewEncryptedAccountKeyAlgorithm, out var newAccountKeyAlgorithm) || VaultKeyAlgorithms.IsAsymmetric(newAccountKeyAlgorithm))
        {
            return ApiError.Result(ApiErrorCode.INVALID_ALGORITHM, 400);
        }

        // Validate the SRP session (actual current password check).
        var srpResult = await AuthHelper.ValidateStepUpAsync(cache, context, userManager, user, SrpPurpose.PasswordChange, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);
        if (srpResult.Session is null)
        {
            await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.PasswordChange, srpResult.FailureReason);
            return ApiError.Result(srpResult.LockedOut ? ApiErrorCode.ACCOUNT_LOCKED : ApiErrorCode.PASSWORD_MISMATCH, 400);
        }

        var now = timeProvider.GetUtcNow().UtcDateTime;
        var settings = await settingsService.GetAllSettingsAsync();
        var currentRefreshTokenId = Guid.TryParse(User.FindFirstValue(TokenService.RefreshTokenIdClaim), out var tokenId) ? tokenId : Guid.Empty;

        var newMetadata = VaultKeyMetadata.Parse(unlockMethod.Metadata);
        newMetadata.Salt = model.NewPasswordSalt;
        newMetadata.SrpVerifier = model.NewPasswordVerifier;
        newMetadata.EncryptionType = model.NewEncryptionType;
        newMetadata.EncryptionSettings = model.NewEncryptionSettings;
        var newMetadataJson = newMetadata.ToJson();

        // Archive the superseded unlock method and update the current unlock method with the new credentials in a single transaction.
        var strategy = context.Database.CreateExecutionStrategy();
        var changed = await strategy.ExecuteAsync(async () =>
        {
            await using var writeContext = await dbContextFactory.CreateDbContextAsync();
            await using var transaction = await writeContext.Database.BeginTransactionAsync();

            await UnlockMethodHistoryPolicy.ArchiveAsync(writeContext, unlockMethod, settings.UnlockMethodHistoryRetentionDays, now, ClientHeaderInfo.GetRawValue(Request));
            await writeContext.SaveChangesAsync();

            // Only while the Account Key is the one the client re-encrypted: a key rotation committed meanwhile would otherwise be overwritten with the old key.
            var updated = await writeContext.UserUnlockMethods.Where(x => x.Id == unlockMethod.Id && x.AccountKeyVersion == unlockMethod.AccountKeyVersion).ExecuteUpdateAsync(s => s
                .SetProperty(x => x.Metadata, newMetadataJson)
                .SetProperty(x => x.EncryptedAccountKey, model.NewEncryptedAccountKey)
                .SetProperty(x => x.Algorithm, newAccountKeyAlgorithm)
                .SetProperty(x => x.UpdatedAt, now));
            if (updated == 0)
            {
                await transaction.RollbackAsync();
                return false;
            }

            // Update the password last changed at timestamp for user.
            await writeContext.AliasVaultUsers.Where(x => x.Id == user.Id).ExecuteUpdateAsync(s => s.SetProperty(x => x.PasswordChangedAt, now));

            // Revoke every session except the caller's own refresh token; an access token without that claim keeps none.
            await writeContext.AliasVaultUserRefreshTokens.Where(x => x.UserId == user.Id && x.Id != currentRefreshTokenId).ExecuteDeleteAsync();
            await transaction.CommitAsync();
            return true;
        });

        if (!changed)
        {
            await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.PasswordChange, AuthFailureReason.InvalidPassword);
            return ApiError.Result(ApiErrorCode.PASSWORD_MISMATCH, 400);
        }

        user.PasswordChangedAt = now;

        await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.PasswordChange);

        return Ok();
    }

    /// <summary>
    /// Start a key derivation upgrade: the SRP handshake material for the current password.
    /// </summary>
    /// <returns>IActionResult.</returns>
    [HttpGet("key-derivation-upgrade/initiate")]
    [Authorize]
    public async Task<IActionResult> InitiateKeyDerivationUpgrade()
    {
        var user = await userManager.GetUserAsync(User);
        if (user == null)
        {
            return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
        }

        await using var context = await dbContextFactory.CreateDbContextAsync();
        var credentials = await AuthHelper.GetUserLatestVaultEncryptionSettingsAsync(context, user);
        var serverEphemeral = AuthHelper.CreateSrpEphemeral(cache, user, SrpPurpose.KeyDerivationUpgrade, credentials);

        return Ok(new PasswordChangeInitiateResponse(credentials.Salt, serverEphemeral, credentials.EncryptionType, credentials.EncryptionSettings, AuthHelper.GetSrpIdentity(user)));
    }

    /// <summary>
    /// Raise the key derivation settings of the password to the current defaults, keeping the password and salt.
    /// </summary>
    /// <param name="model">Key derivation upgrade request model.</param>
    /// <returns>IActionResult.</returns>
    [HttpPost("key-derivation-upgrade")]
    [Authorize]
    public async Task<IActionResult> UpgradeKeyDerivation([FromBody] KeyDerivationUpgradeRequest model)
    {
        var user = await userManager.GetUserAsync(User);
        if (user == null)
        {
            return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
        }

        await using var context = await dbContextFactory.CreateDbContextAsync();
        var unlockMethod = await context.UserUnlockMethods.FirstOrDefaultAsync(x => x.UserId == user.Id && x.Type == UnlockMethodType.Password);
        if (unlockMethod == null)
        {
            return ApiError.Result(ApiErrorCode.VAULT_KEY_NOT_FOUND, 400);
        }

        /*
         * Only moves the settings up: the stored settings must be below the defaults and the new ones at or above them.
         * Unlike a password change it keeps the salt, archives nothing and revokes no sessions, as other devices keep
         * working with the same password.
         */
        var metadata = VaultKeyMetadata.Parse(unlockMethod.Metadata);
        var accountKeyFits = !string.IsNullOrEmpty(model.NewEncryptedAccountKey) && model.NewEncryptedAccountKey.Length <= AccountKeysUpload.MaxWrappedKeyLength;
        if (!UnlockMethodParameterValidator.IsBelowDefaults(metadata.EncryptionSettings ?? string.Empty) || !UnlockMethodParameterValidator.IsValidKekDerivationParams(model.NewEncryptionType, model.NewEncryptionSettings) || !UnlockMethodParameterValidator.WithinSrpCredentialLimits(metadata.Salt, model.NewPasswordVerifier) || !accountKeyFits)
        {
            return ApiError.Result(ApiErrorCode.INVALID_ENCRYPTION_PARAMETERS, 400);
        }

        if (!VaultKeyAlgorithms.TryParse(model.NewEncryptedAccountKeyAlgorithm, out var newAccountKeyAlgorithm) || VaultKeyAlgorithms.IsAsymmetric(newAccountKeyAlgorithm))
        {
            return ApiError.Result(ApiErrorCode.INVALID_ALGORITHM, 400);
        }

        var srpResult = await AuthHelper.ValidateStepUpAsync(cache, context, userManager, user, SrpPurpose.KeyDerivationUpgrade, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);
        if (srpResult.Session is null)
        {
            await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.KeyDerivationUpgrade, srpResult.FailureReason);
            return ApiError.Result(srpResult.LockedOut ? ApiErrorCode.ACCOUNT_LOCKED : ApiErrorCode.PASSWORD_MISMATCH, 400);
        }

        metadata.SrpVerifier = model.NewPasswordVerifier;
        metadata.EncryptionType = model.NewEncryptionType;
        metadata.EncryptionSettings = model.NewEncryptionSettings;
        var newMetadataJson = metadata.ToJson();
        var now = timeProvider.GetUtcNow().UtcDateTime;

        // Only while the row is the one the proof was checked against: a password change or key rotation committed meanwhile wins.
        var updated = await context.UserUnlockMethods.Where(x => x.Id == unlockMethod.Id && x.AccountKeyVersion == unlockMethod.AccountKeyVersion && x.Metadata == unlockMethod.Metadata).ExecuteUpdateAsync(s => s
            .SetProperty(x => x.Metadata, newMetadataJson)
            .SetProperty(x => x.EncryptedAccountKey, model.NewEncryptedAccountKey)
            .SetProperty(x => x.Algorithm, newAccountKeyAlgorithm)
            .SetProperty(x => x.UpdatedAt, now));
        if (updated == 0)
        {
            await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.KeyDerivationUpgrade, AuthFailureReason.InvalidPassword);
            return ApiError.Result(ApiErrorCode.PASSWORD_MISMATCH, 400);
        }

        await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.KeyDerivationUpgrade);
        return Ok();
    }

    /// <summary>
    /// Validate username endpoint used to check if a username is available.
    /// </summary>
    /// <param name="model">ValidateUsernameRequest model.</param>
    /// <returns>IActionResult.</returns>
    [HttpPost("validate-username")]
    [EnableRateLimiting(RegistrationCheckRateLimit.PolicyName)]
    [AllowAnonymous]
    public async Task<IActionResult> ValidateUsername([FromBody] ValidateUsernameRequest model)
    {
        // Without public registration only an invite code holder may check usernames, which prevents username enumeration.
        if (!config.PublicRegistrationEnabled)
        {
            if (string.IsNullOrWhiteSpace(model.InviteCode))
            {
                return ApiError.Result(ApiErrorCode.PUBLIC_REGISTRATION_DISABLED, 400);
            }

            if (!await registrationInviteService.IsValidAsync(model.InviteCode))
            {
                return ApiError.Result(ApiErrorCode.INVITE_CODE_INVALID, 400);
            }
        }

        if (string.IsNullOrWhiteSpace(model.Username))
        {
            return ApiError.Result(ApiErrorCode.USERNAME_REQUIRED, 400);
        }

        var normalizedUsername = UsernameHelper.NormalizeUsername(model.Username);
        var existingUser = await userManager.FindByNameAsync(normalizedUsername);

        if (existingUser != null)
        {
            return ApiError.Result(ApiErrorCode.USERNAME_ALREADY_IN_USE, 400);
        }

        // Validate the username
        var (isValid, apiErrorCode) = await tokenService.ValidateUsernameAsync(normalizedUsername);

        if (!isValid)
        {
            return ApiError.Result(apiErrorCode, 400);
        }

        return Ok();
    }

    /// <summary>
    /// Check whether a registration invite code can be used.
    /// </summary>
    /// <param name="model">ValidateInviteCodeRequest model.</param>
    /// <returns>IActionResult.</returns>
    [HttpPost("validate-invite-code")]
    [EnableRateLimiting(RegistrationCheckRateLimit.PolicyName)]
    [AllowAnonymous]
    public async Task<IActionResult> ValidateInviteCode([FromBody] ValidateInviteCodeRequest model)
    {
        if (!await registrationInviteService.IsValidAsync(model.InviteCode))
        {
            return ApiError.Result(ApiErrorCode.INVITE_CODE_INVALID, 400);
        }

        return Ok();
    }

    /// <summary>
    /// Initiates the account deletion process.
    /// </summary>
    /// <param name="model">The login initiate request model.</param>
    /// <returns>IActionResult.</returns>
    [HttpPost("delete-account/initiate")]
    [Authorize]
    public async Task<IActionResult> InitiateAccountDeletion([FromBody] LoginInitiateRequest model)
    {
        var user = await userManager.GetUserAsync(User);
        if (user == null)
        {
            return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
        }

        // Verify the username matches the current user.
        if (!string.Equals(user.UserName, model.Username, StringComparison.OrdinalIgnoreCase))
        {
            return ApiError.Result(ApiErrorCode.USERNAME_MISMATCH, 400);
        }

        // Retrieve latest vault of user which contains the current salt and verifier.
        await using var context = await dbContextFactory.CreateDbContextAsync();
        var latestVaultEncryptionSettings = await AuthHelper.GetUserLatestVaultEncryptionSettingsAsync(context, user);

        var srpIdentity = AuthHelper.GetSrpIdentity(user);

        var serverEphemeral = AuthHelper.CreateSrpEphemeral(cache, user, SrpPurpose.AccountDeletion, latestVaultEncryptionSettings);

        return Ok(new LoginInitiateResponse(
            latestVaultEncryptionSettings.Salt,
            serverEphemeral,
            latestVaultEncryptionSettings.EncryptionType,
            latestVaultEncryptionSettings.EncryptionSettings,
            srpIdentity));
    }

    /// <summary>
    /// Initiates a mobile login request. The client shows the returned request id as a QR code and keeps the poll secret to itself.
    /// </summary>
    /// <param name="model">The mobile login initiate request model.</param>
    /// <param name="mobileLoginRateLimitService">MobileLoginRateLimitService instance.</param>
    /// <returns>IActionResult.</returns>
    [HttpPost("mobile-login/initiate")]
    [AllowAnonymous]
    public async Task<IActionResult> InitiateMobileLogin([FromBody] MobileLoginInitiateRequest model, [FromServices] MobileLoginRateLimitService mobileLoginRateLimitService)
    {
        // Reject invalid public key structure.
        if (!RsaPublicKeyValidator.IsValid(model.ClientPublicKey))
        {
            return ApiError.Result(ApiErrorCode.MOBILE_LOGIN_INVALID_PUBLIC_KEY, 400);
        }

        if (!VaultKeyAlgorithms.TryParse(model.Algorithm, out var algorithm) || !VaultKeyAlgorithms.IsAsymmetric(algorithm))
        {
            return ApiError.Result(ApiErrorCode.INVALID_ALGORITHM, 400);
        }

        // Check the IP blocklist.
        if (await ipBlockListService.IsBlockedForLoginAsync(IpAddressUtility.GetRawIpAddressFromContext(HttpContext)))
        {
            await authLoggingService.LogAuthEventFailAsync("n/a", AuthEventType.MobileLogin, AuthFailureReason.IpBlocked);
            return ApiError.Result(ApiErrorCode.ACCOUNT_BLOCKED, 400);
        }

        // 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);
            return ApiError.Result(ApiErrorCode.MOBILE_LOGIN_RATE_LIMIT_EXCEEDED, 429);
        }

        await using var context = await dbContextFactory.CreateDbContextAsync();

        // 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 = Base64Url.EncodeToString(RandomNumberGenerator.GetBytes(32));

        var loginRequest = new MobileLoginRequest
        {
            Id = requestId,
            ClientPublicKey = model.ClientPublicKey,
            Algorithm = algorithm,
            PollSecretHash = MobileLoginRequestHelper.HashPollSecret(pollSecret),
            CreatedAt = timeProvider.GetUtcNow().UtcDateTime,
            ClientIpAddress = ipAddress,
            ClientName = MobileLoginRequestHelper.SanitizeClientName(ClientHeaderInfo.GetRawValue(Request)),
            ClientBrowser = RequestClientInfo.DetermineBrowser(HttpContext),
            ClientOperatingSystem = RequestClientInfo.DetermineOperatingSystem(HttpContext),
        };

        context.MobileLoginRequests.Add(loginRequest);
        await context.SaveChangesAsync();

        return Ok(new MobileLoginInitiateResponse
        {
            RequestId = requestId,
            PollSecret = pollSecret,
        });
    }

    /// <summary>
    /// Polls the status of a mobile login request. Only the client that initiated the request holds the poll secret.
    /// </summary>
    /// <param name="model">The mobile login poll request model.</param>
    /// <returns>IActionResult.</returns>
    [HttpPost("mobile-login/poll")]
    [AllowAnonymous]
    public async Task<IActionResult> PollMobileLogin([FromBody] MobileLoginPollRequest model)
    {
        await using var context = await dbContextFactory.CreateDbContextAsync();

        var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == model.RequestId);

        // An unknown request and a wrong poll secret get the same answer.
        if (loginRequest == null || !MobileLoginRequestHelper.IsPollSecretValid(loginRequest, model.PollSecret))
        {
            return ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404);
        }

        if (loginRequest.DeclinedAt != null)
        {
            return Ok(new MobileLoginPollResponse { Status = MobileLoginStatus.Declined });
        }

        if (loginRequest.FulfilledAt == null)
        {
            if (MobileLoginRequestHelper.IsApprovalWindowClosed(loginRequest, timeProvider.GetUtcNow().UtcDateTime))
            {
                return ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_EXPIRED, 410);
            }

            return Ok(new MobileLoginPollResponse { Status = MobileLoginStatus.Pending });
        }

        // One-time use: an approved request is handed out once, and only shortly after the approval.
        if (loginRequest.RetrievedAt != null || loginRequest.EncryptedAccountKey == null || MobileLoginRequestHelper.IsRetrievalWindowClosed(loginRequest, timeProvider.GetUtcNow().UtcDateTime))
        {
            return ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_EXPIRED, 410);
        }

        // The approving user must still exist, be unblocked and not locked out.
        var user = await userManager.FindByIdAsync(loginRequest.UserId!);
        if (user == null)
        {
            await authLoggingService.LogAuthEventFailAsync("n/a", AuthEventType.MobileLogin, AuthFailureReason.InvalidUsername);
            return ApiError.Result(ApiErrorCode.USER_NOT_FOUND, 400);
        }

        if (user.Blocked)
        {
            await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.MobileLogin, AuthFailureReason.AccountBlocked);
            return ApiError.Result(ApiErrorCode.ACCOUNT_BLOCKED, 400);
        }

        if (await userManager.IsLockedOutAsync(user))
        {
            await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.MobileLogin, AuthFailureReason.AccountLocked);
            return ApiError.Result(ApiErrorCode.ACCOUNT_LOCKED, 400);
        }

        // Claim the request and clear its key material in one transaction.
        var clientPublicKey = loginRequest.ClientPublicKey;
        var encryptedAccountKey = loginRequest.EncryptedAccountKey;
        var retrievedAt = timeProvider.GetUtcNow().UtcDateTime;
        var claimed = await context.MobileLoginRequests
            .Where(r => r.Id == loginRequest.Id && r.RetrievedAt == null)
            .ExecuteUpdateAsync(u => u.SetProperty(r => r.RetrievedAt, retrievedAt).SetProperty(r => r.ClientPublicKey, string.Empty).SetProperty(r => r.EncryptedAccountKey, (string?)null));
        if (claimed != 1)
        {
            return ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_EXPIRED, 410);
        }

        // The client needs the key derivation parameters next to the Account Key to be able to unlock offline later.
        var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: true);
        var encryptionSettings = await AuthHelper.GetUserLatestVaultEncryptionSettingsAsync(context, user);
        var payload = new MobileLoginPayload
        {
            Username = user.UserName!,
            Token = tokenModel.Token,
            RefreshToken = tokenModel.RefreshToken,
            Salt = encryptionSettings.Salt,
            EncryptionType = encryptionSettings.EncryptionType,
            EncryptionSettings = encryptionSettings.EncryptionSettings,
        };

        // The payload is encrypted with a one-off symmetric key, which in turn is encrypted with the client's RSA public key.
        var symmetricKey = Cryptography.Encryption.GenerateRandomSymmetricKey();
        var encryptedPayload = Cryptography.Encryption.SymmetricEncrypt(JsonSerializer.Serialize(payload, MobileLoginRequestHelper.PayloadJsonOptions), symmetricKey);
        var encryptedSymmetricKey = Cryptography.Encryption.EncryptSymmetricKeyWithRsa(symmetricKey, clientPublicKey, Cryptography.Encryption.MobileLoginPayloadKeyLabel);

        await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.MobileLogin);

        return Ok(new MobileLoginPollResponse
        {
            Status = MobileLoginStatus.Approved,
            EncryptedSymmetricKey = encryptedSymmetricKey,
            EncryptedPayload = encryptedPayload,
            EncryptedAccountKey = encryptedAccountKey,
        });
    }

    /// <summary>
    /// Gets details about a mobile login request that the mobile app shows to the user before they approve.
    /// </summary>
    /// <param name="model">The request to describe.</param>
    /// <returns>IActionResult.</returns>
    [HttpPost("mobile-login/details")]
    [Authorize]
    public async Task<IActionResult> GetMobileLoginDetails([FromBody] MobileLoginRequestReference model)
    {
        await using var context = await dbContextFactory.CreateDbContextAsync();

        var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == model.RequestId);
        if (loginRequest == null || !MobileLoginRequestHelper.IsAwaitingApproval(loginRequest, timeProvider.GetUtcNow().UtcDateTime))
        {
            return MobileLoginNotAwaitingApproval(loginRequest);
        }

        return Ok(new MobileLoginDetailsResponse
        {
            ClientPublicKey = loginRequest.ClientPublicKey,
            Algorithm = VaultKeyAlgorithms.ToToken(loginRequest.Algorithm),
            IpAddress = loginRequest.ClientIpAddress,
            Location = RequestClientInfo.DetermineCountry(),
            ClientName = loginRequest.ClientName,
            Browser = loginRequest.ClientBrowser,
            OperatingSystem = loginRequest.ClientOperatingSystem,
            CreatedAt = loginRequest.CreatedAt,
        });
    }

    /// <summary>
    /// Approves a mobile login request: the mobile app hands in the Account Key, encrypted with the client's public key.
    /// </summary>
    /// <param name="model">The mobile login submit request model.</param>
    /// <returns>IActionResult.</returns>
    [HttpPost("mobile-login/submit")]
    [Authorize]
    public async Task<IActionResult> SubmitMobileLogin([FromBody] MobileLoginSubmitRequest model)
    {
        await using var context = await dbContextFactory.CreateDbContextAsync();

        var user = await userManager.GetUserAsync(User);
        if (user == null)
        {
            return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
        }

        // An approval creates a new session, so the approving session must still exist: a leftover access token of a revoked
        // session cannot be used to log in again.
        var sessionId = Guid.TryParse(User.FindFirstValue(TokenService.RefreshTokenIdClaim), out var refreshTokenId) ? refreshTokenId : Guid.Empty;
        if (!await context.AliasVaultUserRefreshTokens.AnyAsync(t => t.Id == sessionId && t.UserId == user.Id))
        {
            return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
        }

        var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == model.RequestId);
        if (loginRequest == null || !MobileLoginRequestHelper.IsAwaitingApproval(loginRequest, timeProvider.GetUtcNow().UtcDateTime))
        {
            return MobileLoginNotAwaitingApproval(loginRequest);
        }

        // The Account Key must be encrypted with the algorithm the initiating client asked for.
        if (model.Algorithm != VaultKeyAlgorithms.ToToken(loginRequest.Algorithm))
        {
            return ApiError.Result(ApiErrorCode.INVALID_ALGORITHM, 400);
        }

        // A signed approval proves the signing key, which a session token alone does not. Unsigned approvals from older app
        // versions are still accepted; make the signature required once those versions are no longer supported.
        if (model.Signature is not null)
        {
            var signingKey = await GrantHelper.GetPrimarySigningKeyAsync(context, user.Id);
            if (signingKey is null || !Signing.Verify(signingKey, Signing.MobileLoginApprovalMessage(model.RequestId, model.Algorithm, model.EncryptedAccountKey), model.Signature))
            {
                return ApiError.Result(ApiErrorCode.SIGNATURE_INVALID, 400);
            }
        }

        // Store the answer in one transaction.
        var fulfilledAt = timeProvider.GetUtcNow().UtcDateTime;
        var mobileIpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled);
        var updated = await context.MobileLoginRequests
            .Where(r => r.Id == loginRequest.Id && r.FulfilledAt == null && r.DeclinedAt == null)
            .ExecuteUpdateAsync(u => u.SetProperty(r => r.EncryptedAccountKey, model.EncryptedAccountKey).SetProperty(r => r.UserId, user.Id).SetProperty(r => r.FulfilledAt, fulfilledAt).SetProperty(r => r.MobileIpAddress, mobileIpAddress));
        if (updated != 1)
        {
            return ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_ALREADY_FULFILLED, 400);
        }

        return Ok();
    }

    /// <summary>
    /// Declines a mobile login request.
    /// </summary>
    /// <param name="model">The request to decline.</param>
    /// <returns>IActionResult.</returns>
    [HttpPost("mobile-login/decline")]
    [Authorize]
    public async Task<IActionResult> DeclineMobileLogin([FromBody] MobileLoginRequestReference model)
    {
        await using var context = await dbContextFactory.CreateDbContextAsync();

        var user = await userManager.GetUserAsync(User);
        if (user == null)
        {
            return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
        }

        var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == model.RequestId);
        if (loginRequest == null || !MobileLoginRequestHelper.IsAwaitingApproval(loginRequest, timeProvider.GetUtcNow().UtcDateTime))
        {
            return MobileLoginNotAwaitingApproval(loginRequest);
        }

        loginRequest.ClientPublicKey = string.Empty;
        loginRequest.UserId = user.Id;
        loginRequest.DeclinedAt = timeProvider.GetUtcNow().UtcDateTime;
        loginRequest.MobileIpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled);
        await context.SaveChangesAsync();

        await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.MobileLogin, AuthFailureReason.MobileLoginDeclined);

        return Ok();
    }

    /// <summary>
    /// Confirms the account deletion process.
    /// </summary>
    /// <param name="model">The login initiate request model.</param>
    /// <returns>IActionResult.</returns>
    [HttpPost("delete-account/confirm")]
    [Authorize]
    public async Task<IActionResult> ConfirmAccountDeletion([FromBody] DeleteAccountRequest model)
    {
        var user = await userManager.GetUserAsync(User);
        if (user == null)
        {
            return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
        }

        // Verify the username matches the current user.
        if (!string.Equals(user.UserName, model.Username, StringComparison.OrdinalIgnoreCase))
        {
            return ApiError.Result(ApiErrorCode.USERNAME_MISMATCH, 400);
        }

        // Validate the SRP session (actual password check).
        await using var context = await dbContextFactory.CreateDbContextAsync();
        var srpResult = await AuthHelper.ValidateStepUpAsync(cache, context, userManager, user, SrpPurpose.AccountDeletion, model.ClientPublicEphemeral, model.ClientSessionProof);
        if (srpResult.Session is null)
        {
            await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.AccountDeletion, srpResult.FailureReason);
            return ApiError.Result(srpResult.LockedOut ? ApiErrorCode.ACCOUNT_LOCKED : ApiErrorCode.PASSWORD_MISMATCH, 400);
        }

        // Log the successful account deletion.
        await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.AccountDeletion);

        // The 2FA tokens have no foreign key to the user, so they are deleted explicitly.
        context.UserTokens.RemoveRange(await context.UserTokens.Where(t => t.UserId == user.Id).ToListAsync());

        // Delete the personal group and user.
        var personalGroup = await context.Groups.FirstAsync(g => g.Id == user.PersonalGroupId);
        context.Groups.Remove(personalGroup);
        context.AliasVaultUsers.Remove(user);
        await context.SaveChangesAsync();

        return Ok();
    }

    /// <summary>
    /// The error for a mobile login request that does not exist or no longer awaits approval.
    /// </summary>
    /// <param name="request">The request, or null when it does not exist.</param>
    /// <returns>The error result.</returns>
    private static ObjectResult MobileLoginNotAwaitingApproval(MobileLoginRequest? request) => request switch
    {
        null => ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404),
        { DeclinedAt: not null } => ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_DECLINED, 410),
        { FulfilledAt: not null } => ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_ALREADY_FULFILLED, 400),
        _ => ApiError.Result(ApiErrorCode.MOBILE_LOGIN_REQUEST_EXPIRED, 410),
    };

    /// <summary>
    /// Validates the user and SRP session (password), then records usage of the proven unlock method.
    /// </summary>
    /// <param name="model">ValidateLoginRequest model.</param>
    /// <returns>User, SrpSession and the proven unlock method if validation succeeded, IActionResult as error on error.</returns>
    private async Task<(AliasVaultUser? User, SrpSession? ServerSession, Guid? UnlockMethodId, IActionResult? Error)> ValidateUserAndPassword(ValidateLoginRequest model)
    {
        var result = await tokenService.ValidateUserAndPasswordAsync(model.Username, model.ClientPublicEphemeral, model.ClientSessionProof, model.LoginSessionId);
        if (result.Error is not null)
        {
            return (null, null, null, ApiError.Result(result.Error.Value, 400));
        }

        // Record usage of this unlock method for statistics purposes.
        await using var context = await dbContextFactory.CreateDbContextAsync();
        await AuthHelper.TouchUnlockMethodLastUsedAsync(context, result.UnlockMethodId, timeProvider.GetUtcNow().UtcDateTime);

        return (result.User, result.ServerSession, result.UnlockMethodId, null);
    }

    /// <summary>
    /// Replace the legacy verifier of the unlock method a completed login proved with the upgraded one the client sent.
    /// </summary>
    /// <param name="unlockMethodId">The unlock method the login proved; null for a legacy account, which keeps its verifier.</param>
    /// <param name="model">The validate request carrying the upgraded verifier.</param>
    /// <returns>Task.</returns>
    private async Task UpgradeLegacySrpVerifierAsync(Guid? unlockMethodId, ValidateLoginRequest model)
    {
        /*
         * Only after the whole login (2FA included): the proof shows the client holds the password, and the upgraded
         * verifier keeps that same password and salt, so this is no password change. A legacy account (no unlock method
         * row) is skipped on purpose: v1 clients can still sign in to it and only know the legacy verifier.
         */
        var upgrade = model.LegacyVerifierUpgrade;
        if (unlockMethodId is null || upgrade is null || upgrade.EncryptionType != Defaults.EncryptionType || string.IsNullOrEmpty(upgrade.SrpVerifier) || upgrade.SrpVerifier.Length > UnlockMethodParameterValidator.MaxVerifierLength)
        {
            return;
        }

        await using var context = await dbContextFactory.CreateDbContextAsync();
        var unlockMethod = await context.UserUnlockMethods.FirstOrDefaultAsync(x => x.Id == unlockMethodId.Value);
        var metadata = VaultKeyMetadata.Parse(unlockMethod?.Metadata);
        if (unlockMethod is null || metadata.EncryptionType != Defaults.LegacyEncryptionType)
        {
            return;
        }

        metadata.SrpVerifier = upgrade.SrpVerifier;
        metadata.EncryptionType = Defaults.EncryptionType;
        var newMetadataJson = metadata.ToJson();

        // Conditional on the row being unchanged since it was read (a password change bumps UpdatedAt), so a concurrent change wins.
        await context.UserUnlockMethods.Where(x => x.Id == unlockMethod.Id && x.UpdatedAt == unlockMethod.UpdatedAt).ExecuteUpdateAsync(s => s.SetProperty(x => x.Metadata, newMetadataJson));
    }

    /// <summary>
    /// Issues a new access and refresh token pair, the access token bound to its refresh token id.
    /// </summary>
    /// <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)
    {
        var tokens = await tokenService.IssueTokensAsync(user, HttpContext, extendedLifetime, includeRefreshTokenIdClaim: true);
        return new TokenModel { Token = tokens.Token, RefreshToken = tokens.RefreshToken };
    }

    /// <summary>
    /// 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 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)
    {
        var tokens = await tokenService.RotateRefreshTokenAsync(user, existingTokenValue, HttpContext, includeRefreshTokenIdClaim: true);
        return tokens is null ? null : new TokenModel { Token = tokens.Token, RefreshToken = tokens.RefreshToken };
    }

    /// <summary>
    /// Generate the login response of a user that does not exist, from its fake profile, to prevent user enumeration attacks.
    /// </summary>
    /// <param name="profile">The fake login profile of the username.</param>
    /// <returns>IActionResult.</returns>
    private OkObjectResult FakeLoginResponse(FakeLoginProfile profile)
    {
        // Always generate a new ephemeral, as this is also done for existing users.
        var fakeEphemeral = Srp.GenerateEphemeralServer(profile.Verifier);
        return Ok(new LoginInitiateResponse(profile.Salt, fakeEphemeral.Public, Defaults.EncryptionType, Defaults.EncryptionSettings, profile.SrpIdentity, AuthHelper.CreateSrpSessionId()));
    }
}