Skip to content

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

4.8 KB
Raw Blame
//-----------------------------------------------------------------------
// <copyright file="VaultKeyController.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 AliasServerDb;
using AliasVault.Api.Controllers.Abstracts;
using AliasVault.Api.Helpers;
using AliasVault.Shared.Models.Enums;
using AliasVault.Shared.Models.WebApi.V2.Auth;
using Asp.Versioning;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

/// <summary>
/// Vault key controller. Serves the encrypted Account Key for an authenticated user.
/// </summary>
/// <param name="dbContextFactory">DbContext factory.</param>
/// <param name="userManager">UserManager.</param>
[ApiVersion("2")]
public class VaultKeyController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager) : AuthenticatedRequestController(userManager)
{
    /// <summary>
    /// Get the encrypted Account Key and KEK derivation parameters for the given unlock method.
    /// </summary>
    /// <param name="type">The unlock method type, e.g. "password".</param>
    /// <returns>The vault key envelope DTO.</returns>
    // Served under two routes while the rename from "vault key" to "unlock method" rolls out:
    // - v2/UnlockMethod/{type}: the new route, added in 0.32.0. Clients can switch to it once their minimum server version is 0.32.0 or higher.
    // - v2/VaultKey/{type}: deprecated since 0.32.0. Remove it (and rename this controller) once AppInfo.MinimumClientVersion only allows clients that use the new route.
    [HttpGet("~/v{version:apiVersion}/VaultKey/{type}")]
    [HttpGet("~/v{version:apiVersion}/UnlockMethod/{type}")]
    public async Task<IActionResult> Get(string type)
    {
        await using var context = await dbContextFactory.CreateDbContextAsync();
        var user = await GetCurrentUserAsync();
        if (user == null)
        {
            return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);
        }

        // An unknown unlock method token is a malformed request; a null key is reserved for "no key stored for this method".
        if (!UnlockMethodTypes.TryParse(type?.ToLowerInvariant(), out var parsedType))
        {
            return ApiError.Result(ApiErrorCode.INVALID_REQUEST, 400);
        }

        var unlockMethod = await context.UserUnlockMethods.FirstOrDefaultAsync(x => x.UserId == user.Id && x.Type == parsedType);
        if (unlockMethod == null)
        {
            return Ok(new VaultKeyGetResponse { VaultKey = null });
        }

        // Get the encrypted VEK of the newest key generation and the account keypair.
        var personalManifestId = await GroupHelper.GetPersonalManifestIdAsync(context, user.PersonalGroupId);
        var accessKey = personalManifestId is null ? null : await context.VaultManifestAccessKeys
            .Where(x => x.UserId == user.Id && x.Type == ManifestKeyType.AccountKey && x.VaultManifestId == personalManifestId.Value)
            .OrderByDescending(x => x.KeyVersion)
            .Select(x => new { x.EncryptedVek, x.KeyVersion })
            .FirstOrDefaultAsync();
        var accountKeypair = await context.UserGrantKeys
            .Where(x => x.UserId == user.Id && x.IsPrimary)
            .Select(x => new { x.PublicKey, x.EncryptedPrivateKey })
            .FirstOrDefaultAsync();
        var signingKeypair = await context.UserSigningKeys
            .Where(x => x.UserId == user.Id && x.IsPrimary)
            .Select(x => new { x.PublicKey, x.EncryptedPrivateKey })
            .FirstOrDefaultAsync();

        // Get the KEK derivation parameters.
        var credentials = VaultKeyMetadata.Parse(unlockMethod.Metadata).RequireSrpCredentials();

        return Ok(new VaultKeyGetResponse
        {
            VaultKey = new VaultKeyResponse
            {
                Type = UnlockMethodTypes.ToToken(unlockMethod.Type),
                EncryptedAccountKey = unlockMethod.EncryptedAccountKey,
                Algorithm = VaultKeyAlgorithms.ToToken(unlockMethod.Algorithm),
                EncryptedVek = accessKey?.EncryptedVek,
                KeyVersion = accessKey?.KeyVersion ?? 0,
                AccountPublicKey = accountKeypair?.PublicKey,
                EncryptedAccountPrivateKey = accountKeypair?.EncryptedPrivateKey,
                SigningPublicKey = signingKeypair?.PublicKey,
                EncryptedSigningPrivateKey = signingKeypair?.EncryptedPrivateKey,
                Salt = credentials.Salt,
                EncryptionType = credentials.EncryptionType,
                EncryptionSettings = credentials.EncryptionSettings,
            },
        });
    }
}