Skip to content

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

46.1 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.V1;

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using AliasServerDb;
using AliasVault.Api.Filters;
using AliasVault.Api.Headers;
using AliasVault.Api.Helpers;
using AliasVault.Api.Models;
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.V1.Auth;
using AliasVault.Shared.Models.WebApi.V1.PasswordChange;
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 Microsoft.IdentityModel.Tokens;
using SecureRemotePassword;

/// <summary>
/// Auth controller for handling authentication.
/// </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>
/// <param name="config">Config instance.</param>
/// <param name="settingsService">ServerSettingsService instance.</param>
/// <param name="ipBlockListService">IpBlockListService instance.</param>
[Route("v{version:apiVersion}/[controller]")]
[ApiController]
[ApiVersion("1")]
public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IConfiguration configuration, IMemoryCache cache, TimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, IpBlockListService ipBlockListService) : ControllerBase
{
    /// <summary>
    /// Access token validity in minutes.
    /// </summary>
    /// <remarks>
    /// This is the time period for which the access token is valid.
    /// It 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.
    /// </remarks>
    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 yields 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>
    /// Status endpoint called by client to check if user is still authenticated and get sync status.
    /// </summary>
    /// <returns>Returns status response if valid authentication is provided, otherwise it will return 401 unauthorized.</returns>
    [AllowAfterV2Migration]
    [Authorize]
    [HttpGet("status")]
    public async Task<IActionResult> Status()
    {
        var user = await userManager.GetUserAsync(User);
        if (user == null)
        {
            return Unauthorized();
        }

        // Check if the user account is blocked
        if (user.Blocked)
        {
            return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 401));
        }

        // Get latest vault revision number and salt.
        await using var context = await dbContextFactory.CreateDbContextAsync();
        var latestVault = await context.VaultManifests
            .Where(x => x.OwnerGroupId == user.PersonalGroupId)
            .Select(x => new { x.RevisionNumber, x.Salt })
            .FirstOrDefaultAsync();

        // Check client version compatibility if header is provided
        var clientSupported = false;
        var clientInfo = ClientHeaderInfo.Parse(ClientHeaderInfo.GetRawValue(Request));
        if (!string.IsNullOrEmpty(clientInfo.ClientVersion)
            && Version.TryParse(clientInfo.ClientVersion, out _)
            && AppInfo.MinimumClientVersions.TryGetValue(clientInfo.ClientName, out var minimumVersion))
        {
            var meetsMinimum = VersionHelper.IsVersionEqualOrNewer(clientInfo.ClientVersion, minimumVersion);
            var isBlocked = VersionHelper.IsVersionBlocked(clientInfo.ClientName, clientInfo.ClientVersion, AppInfo.UnsupportedClientVersions);
            clientSupported = meetsMinimum && !isBlocked;
        }

        // A caller on this v1 endpoint cannot serve a user whose vault has moved to the v2 storage format. Reporting
        // the client as unsupported makes it show its built-in "please update" message and log out cleanly, instead
        // of running into a hard failure on the vault endpoints later on.
        clientSupported = clientSupported && !await LegacyVaultHelper.HasMigratedToV2Async(context, cache, user.Id);

        return Ok(new StatusResponse
        {
            ClientVersionSupported = clientSupported,
            ServerVersion = AppInfo.GetFullVersion(),
            VaultRevision = latestVault?.RevisionNumber ?? 0,
            SrpSalt = latestVault?.Salt ?? string.Empty,
        });
    }

    /// <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 BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(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 StatusCode(429, ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.RATE_LIMIT_EXCEEDED, 429));
        }

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

        // A non-existent user answers like an upgraded account (as v2 does), to prevent user enumeration attacks.
        if (user == null)
        {
            // Log the attempt internally
            await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.InvalidUsername);
            return LegacyVaultHelper.UpgradeRequiredResult();
        }

        // Check if the account is locked out.
        if (await userManager.IsLockedOutAsync(user))
        {
            await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.TwoFactorAuthentication, AuthFailureReason.AccountLocked);
            return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_LOCKED, 400));
        }

        // Check if the account is blocked.
        if (user.Blocked)
        {
            await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.AccountBlocked);
            return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(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);

        // A v1 client can only answer a legacy verifier; for an upgraded one it would report a wrong password.
        if (latestVaultEncryptionSettings.EncryptionType != Defaults.LegacyEncryptionType)
        {
            return LegacyVaultHelper.UpgradeRequiredResult();
        }

        var srpIdentity = AuthHelper.GetSrpIdentity(user);

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

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

    /// <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, error) = await ValidateUserAndPassword(model);
        if (error is not null)
        {
            // Error occured during validation, return the error.
            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, null))
        {
            return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400));
        }

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

        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, error) = await ValidateUserAndPassword(model);
        if (error is not null)
        {
            // Error occured during validation, return the error.
            return error;
        }

        if (user == null || serverSession == null)
        {
            // Expected variables are not set, return generic error.
            return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(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 BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_AUTHENTICATOR_CODE, 400));
        }

        // Spend the login exchange so its proof cannot be replayed.
        if (!AuthHelper.ConsumeSrpSession(cache, user, null))
        {
            return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(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);

        // 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, error) = await ValidateUserAndPassword(model);
        if (error is not null)
        {
            // Error occured during validation, return the error.
            return error;
        }

        if (user == null || serverSession == null)
        {
            // Expected variables are not set, return generic error.
            return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(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 BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_RECOVERY_CODE, 400));
        }

        // Spend the login exchange so its proof cannot be replayed.
        if (!AuthHelper.ConsumeSrpSession(cache, user, null))
        {
            return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400));
        }

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

        // 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 BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.REFRESH_TOKEN_REQUIRED, 400));
        }

        ClaimsPrincipal principal;
        try
        {
            principal = 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 Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.INVALID_REFRESH_TOKEN, 401));
        }

        if (principal.FindFirst(ClaimTypes.NameIdentifier)?.Value == null)
        {
            return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USER_NOT_FOUND, 401));
        }

        var user = await userManager.FindByIdAsync(principal.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty);
        if (user == null)
        {
            return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USER_NOT_FOUND, 401));
        }

        // Check if the account is blocked.
        if (user.Blocked)
        {
            await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TokenRefresh, AuthFailureReason.AccountBlocked);
            return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(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 Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(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 Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(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>
    [AllowAfterV2Migration]
    [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 BadRequest(ApiErrorCodeHelper.CreateErrorResponse(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>
    [AllowAfterV2Migration]
    [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 BadRequest(ApiErrorCodeHelper.CreateErrorResponse(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 (v1). Account creation via the v1 API is no longer supported: starting from
    /// this release only v2-capable clients are allowed to create accounts. The account-creation logic
    /// has been intentionally removed so that outdated clients (and old tests) can no longer register via v1.
    /// </summary>
    /// <returns>IActionResult.</returns>
    [HttpPost("register")]
    [EnableRateLimiting(RegistrationCheckRateLimit.PolicyName)]
    public IActionResult Register()
    {
        // v1 registration is intentionally disabled. Clients must use the v2 API to create accounts.
        return StatusCode(410, ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.REGISTRATION_FAILED, 410));
    }

    /// <summary>
    /// Password change request is done by verifying the current password and then saving the new password via SRP.
    /// </summary>
    /// <remarks>The submit handler for the change password logic is in VaultController.UpdateChangePassword()
    /// because changing the password of the AliasVault user also requires a new vault encrypted with that same
    /// password in order for things to work properly.</remarks>
    /// <returns>Task.</returns>
    [HttpGet("change-password/initiate")]
    [Authorize]
    public async Task<IActionResult> InitiatePasswordChange()
    {
        var user = await userManager.GetUserAsync(User);
        if (user == null)
        {
            return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 404));
        }

        // 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>
    /// 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)
    {
        // Check if public registration is disabled in the configuration.
        // This prevents username enumeration when registration is disabled.
        if (!config.PublicRegistrationEnabled)
        {
            return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.PUBLIC_REGISTRATION_DISABLED, 400));
        }

        if (string.IsNullOrWhiteSpace(model.Username))
        {
            return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USERNAME_REQUIRED, 400));
        }

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

        if (existingUser != null)
        {
            return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USERNAME_ALREADY_IN_USE, 400));
        }

        // Validate the username
        var (isValid, apiErrorCode) = await ValidateUsername(normalizedUsername);

        if (!isValid)
        {
            return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(apiErrorCode, 400));
        }

        return Ok(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USERNAME_AVAILABLE, 200));
    }

    /// <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 NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 404));
        }

        // Verify the username matches the current user.
        if (!string.Equals(user.UserName, model.Username, StringComparison.OrdinalIgnoreCase))
        {
            return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(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>
    /// Mobile login initiate endpoint (v1). Removed, use the v2 API instead.
    /// </summary>
    /// <returns>IActionResult.</returns>
    [HttpPost("mobile-login/initiate")]
    [AllowAnonymous]
    public IActionResult InitiateMobileLogin()
    {
        return MobileLoginGone();
    }

    /// <summary>
    /// Mobile login poll endpoint (v1). Removed, use the v2 API instead.
    /// </summary>
    /// <param name="requestId">The unique identifier for the login request.</param>
    /// <returns>IActionResult.</returns>
    [HttpGet("mobile-login/poll/{requestId}")]
    [AllowAnonymous]
    public IActionResult PollMobileLogin(string requestId)
    {
        return MobileLoginGone();
    }

    /// <summary>
    /// Mobile login request details endpoint (v1). Removed, use the v2 API instead.
    /// </summary>
    /// <param name="requestId">The unique identifier for the login request.</param>
    /// <returns>IActionResult.</returns>
    [HttpGet("mobile-login/request/{requestId}")]
    [AllowAnonymous]
    public IActionResult GetMobileLoginRequest(string requestId)
    {
        return MobileLoginGone();
    }

    /// <summary>
    /// Mobile login submit endpoint (v1). Removed, use the v2 API instead.
    /// </summary>
    /// <returns>IActionResult.</returns>
    [HttpPost("mobile-login/submit")]
    [AllowAnonymous]
    public IActionResult SubmitMobileLogin()
    {
        return MobileLoginGone();
    }

    /// <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 NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 404));
        }

        // Verify the username matches the current user.
        if (!string.Equals(user.UserName, model.Username, StringComparison.OrdinalIgnoreCase))
        {
            return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(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 BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(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 user and their personal group.
        var personalGroup = await context.Groups.FirstAsync(g => g.Id == user.PersonalGroupId);
        context.AliasVaultUsers.Remove(user);
        context.Groups.Remove(personalGroup);
        await context.SaveChangesAsync();

        return Ok(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.ACCOUNT_SUCCESSFULLY_DELETED, 200));
    }

    /// <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>
    /// The answer every v1 mobile login route gives now that the flow only exists in v2. The error code is one
    /// the clients that still call these routes already understand, so they end the attempt instead of hanging.
    /// </summary>
    /// <returns>IActionResult.</returns>
    private IActionResult MobileLoginGone()
    {
        return StatusCode(410, ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 410));
    }

    /// <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.
    /// </summary>
    /// <param name="model">ValidateLoginRequest model.</param>
    /// <returns>User and SrpSession object if validation succeeded, IActionResult as error on error.</returns>
    private async Task<(AliasVaultUser? User, SrpSession? ServerSession, 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, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400)));
        }

        // Check if the account is locked out.
        if (await userManager.IsLockedOutAsync(user))
        {
            await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthentication, AuthFailureReason.AccountLocked);
            return (null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(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, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(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);
        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, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400)));
        }

        return (user, srpResult.Session, null);
    }

    /// <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>
    /// <returns>Access token as string.</returns>
    private string GenerateJwtToken(AliasVaultUser user)
    {
        var claims = new List<Claim>
        {
            new(ClaimTypes.NameIdentifier, user.Id),
            new(ClaimTypes.Name, user.UserName ?? string.Empty),
            new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().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.
    /// </summary>
    /// <param name="user">The user to generate the tokens for.</param>
    /// <param name="extendedLifetime">If true, the refresh token will have an extended lifetime (remember me option).</param>
    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();
        }
    }

    /// <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="existingTokenValue">The existing token value that is being replaced (optional).</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), 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);
        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 };
    }
}