Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update API controllers (#2159)
Leendert de Borste8f6adbe6c56
diff --git a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V1/VaultController.csindex 594ef0a6d..0e471ce98 100644--- a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs+++ b/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs@@ -1,4 +1,4 @@-//-----------------------------------------------------------------------+//-----------------------------------------------------------------------// <copyright file="VaultController.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.@@ -82,7 +82,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont}// Logic to retrieve vault for the user: the current revision of the user's root manifest.- var vault = await context.VaultManifests.FirstOrDefaultAsync(x => x.OwnerUserId == user.Id && x.IsRoot);+ var vault = await context.VaultManifests.FirstOrDefaultAsync(x => x.IsRoot && x.OwnerGroupId == user.PersonalGroupId);// If no vault is found on server, return an empty object. This means the client will use an empty vault// as starting point.@@ -164,7 +164,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont}// Retrieve the current revision of the user's root manifest, which contains the current encryption settings.- var currentManifest = await context.VaultManifests.FirstAsync(x => x.OwnerUserId == user.Id && x.IsRoot);+ var currentManifest = await context.VaultManifests.FirstAsync(x => x.IsRoot && x.OwnerGroupId == user.PersonalGroupId);// Reject vaults with a version that is lower than the last vault version.if (VersionHelper.IsVersionOlder(model.Version, currentManifest.Version))@@ -206,13 +206,13 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont// Update user email claims if email addresses have been supplied.if (model.EmailAddressList.Count > 0){- await UpdateUserEmailClaims(context, user, model.EmailAddressList);+ await UpdateEmailClaims(context, user, currentManifest.ManifestId, model.EmailAddressList);}- // Sync user public key if supplied.+ // Sync user public key if supplied, scoped to the root manifest (every key row is manifest-scoped).if (!string.IsNullOrEmpty(model.EncryptionPublicKey)){- await UpdateUserPublicKey(context, user.Id, model.EncryptionPublicKey);+ await UpdateUserPublicKey(context, currentManifest.ManifestId, model.EncryptionPublicKey);}return Ok(new VaultUpdateResponse { Status = VaultStatus.Ok, NewRevisionNumber = newRevisionNumber });@@ -252,7 +252,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont}// Validate the SRP session (actual password check).- var serverSession = AuthHelper.ValidateSrpSession(cache, user, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);+ var serverSession = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);if (serverSession is null){// Increment failed login attempts in order to lock out the account when the limit is reached.@@ -264,7 +264,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont// Check if the provided revision number is equal to the latest revision number.// If not, then the client is trying to update an older vault which we don't allow to prevent data loss.- var currentManifest = await context.VaultManifests.FirstAsync(x => x.OwnerUserId == user.Id && x.IsRoot);+ var currentManifest = await context.VaultManifests.FirstAsync(x => x.IsRoot && x.OwnerGroupId == user.PersonalGroupId);if (VersionHelper.IsVersionOlder(model.Version, currentManifest.Version)){return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_NOT_UP_TO_DATE, 400));@@ -324,8 +324,8 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont/// </summary>private static async Task<bool> HasMigratedToV2(AliasServerDbContext context, string userId){- return await context.VaultManifests.AnyAsync(x => x.OwnerUserId == userId && x.StorageFormat == "manifest-v1")- || await context.VaultKeys.AnyAsync(x => x.UserId == userId);+ return await context.VaultManifests.AnyAsync(x => x.StorageFormat == "manifest-v1" && context.AliasVaultUsers.Any(u => u.Id == userId && u.PersonalGroupId == x.OwnerGroupId))+ || await context.VaultManifestAccessKeys.AnyAsync(x => x.UserId == userId);}/// <summary>@@ -359,7 +359,6 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont.Select(x => new AliasServerDb.VaultManifestsHistory{ManifestId = x.ManifestId,- OwnerUserId = x.OwnerUserId,VaultBlob = string.Empty,ManifestBlob = null,StorageFormat = x.StorageFormat,@@ -395,17 +394,18 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont/// </summary>/// <param name="context">The database context.</param>/// <param name="user">The user object.</param>+ /// <param name="rootManifestId">The caller's root manifest, which every claim is filed against.</param>/// <param name="newEmailAddresses">The list of new email addresses to claim.</param>/// <returns>A task representing the asynchronous operation.</returns>- private async Task UpdateUserEmailClaims(AliasServerDbContext context, AliasVaultUser user, List<string> newEmailAddresses)+ private async Task UpdateEmailClaims(AliasServerDbContext context, AliasVaultUser user, Guid rootManifestId, List<string> newEmailAddresses){// Deduplicate email addresses to prevent unique constraint violations when// multiple credentials share the same private email address.newEmailAddresses = newEmailAddresses.Select(EmailHelper.SanitizeEmail).Distinct().ToList();- // Get all existing user email claims.- var userOwnedEmailClaims = await context.UserEmailClaims- .Where(x => x.UserId == user.Id)+ // Get list of email claims owned by the user (v1 only supports personal claims in the root manifest).+ var userOwnedEmailClaims = await context.EmailClaims+ .Where(x => x.VaultManifestId == rootManifestId).ToListAsync();// Keep track of processed and sanitized email addresses to know which ones still exist.@@ -424,14 +424,14 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbContint baseCount;if (limit.WindowSeconds == 0){- // Global absolute cap: every claim the user has ever made (including disabled ones).- baseCount = userOwnedEmailClaims.Count;+ // Global absolute cap: every claim ever billed to the caller's group (including disabled ones).+ baseCount = await context.EmailClaims.CountAsync(x => x.VaultManifest!.OwnerGroupId == user.PersonalGroupId);}else{// Time-based cap: aliases created within the rolling window (create-then-delete still counts).var windowStart = timeProvider.UtcNow.AddSeconds(-limit.WindowSeconds);- baseCount = await context.UserEmailClaims.CountAsync(x => x.UserId == user.Id && x.CreatedAt >= windowStart);+ baseCount = await context.EmailClaims.CountAsync(x => x.CreatedAt >= windowStart && x.VaultManifest!.OwnerGroupId == user.PersonalGroupId);}limitUsages.Add((limit.MaxCount, baseCount));@@ -480,8 +480,8 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont}// Check if the email address is already claimed (by another user).- var existingForeignClaim = await context.UserEmailClaims.FirstOrDefaultAsync(x => x.Address == sanitizedEmail);- if (existingForeignClaim != null && existingForeignClaim.UserId != user.Id)+ var existingForeignClaim = await context.EmailClaims.FirstOrDefaultAsync(x => x.Address == sanitizedEmail);+ if (existingForeignClaim != null){// Email address is already claimed by another user. Log the error and continue.logger.LogWarning("{User} tried to claim email address: {Email} but it is already claimed by another user.", user.UserName, sanitizedEmail);@@ -503,9 +503,9 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont// If we get to this point, the email address is new and not claimed by another user, so we can add it.try{- context.UserEmailClaims.Add(new UserEmailClaim+ context.EmailClaims.Add(new EmailClaim{- UserId = user.Id,+ VaultManifestId = rootManifestId,Address = sanitizedEmail,AddressLocal = sanitizedEmail.Split('@')[0],AddressDomain = sanitizedEmail.Split('@')[1],@@ -517,7 +517,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbContcatch (DbUpdateException ex){// Error while adding email claim. Log the error and continue.- logger.LogWarning(ex, "Error while adding UserEmailClaim with email: {Email} for user: {UserId}.", sanitizedEmail, user.UserName);+ logger.LogWarning(ex, "Error while adding EmailClaim with email: {Email} for user: {UserId}.", sanitizedEmail, user.UserName);}}@@ -542,13 +542,13 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont/// Updates the user's public key based on the provided public key. If it already exists, do nothing./// </summary>/// <param name="context">The database context.</param>- /// <param name="userId">The ID of the user.</param>+ /// <param name="rootManifestId">The caller's root manifest, which their personal keys are scoped to.</param>/// <param name="newPublicKey">The new public key to sync and set as default.</param>/// <returns>A task representing the asynchronous operation.</returns>- private async Task UpdateUserPublicKey(AliasServerDbContext context, string userId, string newPublicKey)+ private async Task UpdateUserPublicKey(AliasServerDbContext context, Guid rootManifestId, string newPublicKey){- var publicKeyExists = await context.UserEncryptionKeys- .AnyAsync(x => x.UserId == userId && x.VaultManifestId == null && x.IsPrimary && x.PublicKey == newPublicKey);+ var publicKeyExists = await context.VaultManifestDeliveryKeys+ .AnyAsync(x => x.VaultManifestId == rootManifestId && x.IsPrimary && x.PublicKey == newPublicKey);// If the public key already exists and is marked as primary (default), do nothing.if (publicKeyExists)@@ -557,8 +557,8 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont}// Update all existing personal keys to not be primary.- var otherKeys = await context.UserEncryptionKeys- .Where(x => x.UserId == userId && x.VaultManifestId == null)+ var otherKeys = await context.VaultManifestDeliveryKeys+ .Where(x => x.VaultManifestId == rootManifestId).ToListAsync();foreach (var key in otherKeys)@@ -568,9 +568,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont}// Check if the new public key already exists but is not marked as primary.- var existingPublicKey = await context.UserEncryptionKeys- .FirstOrDefaultAsync(x => x.UserId == userId && x.VaultManifestId == null && x.PublicKey == newPublicKey);-+ var existingPublicKey = otherKeys.FirstOrDefault(x => x.PublicKey == newPublicKey);if (existingPublicKey is not null){// Set the existing key to be primary.@@ -581,15 +579,15 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont}// Public key is new, so create it.- var newPublicKeyEntry = new UserEncryptionKey+ var newPublicKeyEntry = new VaultManifestDeliveryKey{- UserId = userId,+ VaultManifestId = rootManifestId,PublicKey = newPublicKey,IsPrimary = true,CreatedAt = timeProvider.UtcNow,UpdatedAt = timeProvider.UtcNow,};- context.UserEncryptionKeys.Add(newPublicKeyEntry);+ context.VaultManifestDeliveryKeys.Add(newPublicKeyEntry);await context.SaveChangesAsync();}diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.csindex 23221f3c8..e56fe12b2 100644--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs@@ -1,4 +1,4 @@-//-----------------------------------------------------------------------+//-----------------------------------------------------------------------// <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.@@ -64,12 +64,6 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM/// <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>@@ -110,7 +104,8 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}// Retrieve latest vault of user which contains the current salt and verifier.- var latestVaultEncryptionSettings = AuthHelper.GetUserLatestVaultEncryptionSettings(user);+ await using var context = await dbContextFactory.CreateDbContextAsync();+ var latestVaultEncryptionSettings = await AuthHelper.GetUserLatestVaultEncryptionSettingsAsync(context, user);// Get or create SRP identity. For existing users without SrpIdentity, fall back to username (lowercase).var srpIdentity = user.SrpIdentity ?? user.UserName!.ToLowerInvariant();@@ -431,51 +426,98 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMPasswordChangedAt = timeProvider.UtcNow,};- // KEK/VEK registration: the SRP credentials live on the VaultKey row and the manifest row carries none.- // Legacy registration (no wrapped VEK supplied): the SRP credentials live on the manifest row.- var createsVaultKey = !string.IsNullOrEmpty(model.WrappedVek);-- var rootManifest = new AliasServerDb.VaultManifest- {- ManifestId = Guid.NewGuid(),- IsRoot = true,- VaultBlob = string.Empty,- StorageFormat = "sqlite-blob",- Version = "0.0.0",- RevisionNumber = 0,- Salt = createsVaultKey ? string.Empty : model.Salt,- Verifier = createsVaultKey ? string.Empty : model.Verifier,- EncryptionType = createsVaultKey ? string.Empty : model.EncryptionType,- EncryptionSettings = createsVaultKey ? string.Empty : model.EncryptionSettings,- FileSize = 0,- CreatedAt = timeProvider.UtcNow,- UpdatedAt = timeProvider.UtcNow,- };- user.VaultManifests.Add(rootManifest);+ // Check if all account key fields are provided.+ var accountKeyFields = new[] { model.EncryptedAccountKey, model.EncryptedVek, model.AccountPublicKey, model.EncryptedAccountPrivateKey };+ var createsVaultKey = accountKeyFields.Any(f => !string.IsNullOrEmpty(f));+ if (createsVaultKey && accountKeyFields.Any(string.IsNullOrEmpty))+ {+ return BadRequest(ServerValidationErrorResponse.Create(["Account key registration requires encryptedAccountKey, encryptedVek, accountPublicKey and encryptedAccountPrivateKey."], 400));+ }++ var rootManifestId = Guid.NewGuid();- if (createsVaultKey)+ // Create the personal group before the user row.+ var personalGroup = GroupHelper.CreatePersonalGroup(user, timeProvider.UtcNow);+ await using (var context = await dbContextFactory.CreateDbContextAsync()){- user.VaultKeys.Add(new VaultKey- {- Id = Guid.NewGuid(),- UserId = user.Id,- VaultManifestId = rootManifest.ManifestId,- KeyType = AuthHelper.VaultKeyTypePassword,- WrapScheme = AuthHelper.WrapSchemeAesGcmKek,- WrappedVek = model.WrappedVek!,- Salt = model.Salt,- Verifier = model.Verifier,- EncryptionType = model.EncryptionType,- EncryptionSettings = model.EncryptionSettings,- CreatedAt = timeProvider.UtcNow,- UpdatedAt = timeProvider.UtcNow,- });+ context.Groups.Add(personalGroup);+ await context.SaveChangesAsync();}var result = await userManager.CreateAsync(user);if (result.Succeeded){+ // Create the owner membership and root manifest.+ await using (var context = await dbContextFactory.CreateDbContextAsync())+ {+ context.GroupMembers.Add(GroupHelper.CreateOwnerMembership(personalGroup, user.Id, timeProvider.UtcNow));++ context.VaultManifests.Add(new AliasServerDb.VaultManifest+ {+ ManifestId = rootManifestId,+ IsRoot = true,+ OwnerGroupId = personalGroup.Id,+ VaultBlob = string.Empty,+ StorageFormat = "sqlite-blob",+ Version = "0.0.0",+ RevisionNumber = 0,+ Salt = createsVaultKey ? string.Empty : model.Salt,+ Verifier = createsVaultKey ? string.Empty : model.Verifier,+ EncryptionType = createsVaultKey ? string.Empty : model.EncryptionType,+ EncryptionSettings = createsVaultKey ? string.Empty : model.EncryptionSettings,+ FileSize = 0,+ CreatedAt = timeProvider.UtcNow,+ UpdatedAt = timeProvider.UtcNow,+ });++ if (createsVaultKey)+ {+ context.UserUnlockKeys.Add(new UserUnlockKey+ {+ Id = Guid.NewGuid(),+ UserId = user.Id,+ Type = UnlockMethodType.Password,+ Algorithm = VaultKeyAlgorithm.Aes256Gcm,+ EncryptedAccountKey = model.EncryptedAccountKey!,+ Metadata = new VaultKeyMetadata+ {+ Salt = model.Salt,+ SrpVerifier = model.Verifier,+ EncryptionType = model.EncryptionType,+ EncryptionSettings = model.EncryptionSettings,+ }.ToJson(),+ CreatedAt = timeProvider.UtcNow,+ UpdatedAt = timeProvider.UtcNow,+ });++ context.UserGrantKeys.Add(new UserGrantKey+ {+ Id = Guid.NewGuid(),+ UserId = user.Id,+ PublicKey = model.AccountPublicKey!,+ EncryptedPrivateKey = model.EncryptedAccountPrivateKey!,+ IsPrimary = true,+ CreatedAt = timeProvider.UtcNow,+ UpdatedAt = timeProvider.UtcNow,+ });++ context.VaultManifestAccessKeys.Add(new VaultManifestAccessKey+ {+ Id = Guid.NewGuid(),+ UserId = user.Id,+ VaultManifestId = rootManifestId,+ Type = ManifestKeyType.AccountKey,+ Algorithm = VaultKeyAlgorithm.Aes256Gcm,+ EncryptedVek = model.EncryptedVek!,+ CreatedAt = timeProvider.UtcNow,+ UpdatedAt = timeProvider.UtcNow,+ });+ }++ await context.SaveChangesAsync();+ }+await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.Register);// When a user is registered, they are automatically signed in.@@ -486,6 +528,12 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMreturn Ok(tokenModel);}+ // Identity creation failed: remove the personal group written ahead of the user row above.+ await using (var context = await dbContextFactory.CreateDbContextAsync())+ {+ await context.Groups.Where(g => g.Id == personalGroup.Id).ExecuteDeleteAsync();+ }+var errors = result.Errors.Select(e => e.Description).ToArray();return BadRequest(ServerValidationErrorResponse.Create(errors, 400));}@@ -505,7 +553,8 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}// Retrieve latest vault of user which contains the current salt and verifier.- var latestVaultEncryptionSettings = AuthHelper.GetUserLatestVaultEncryptionSettings(user);+ await using var context = await dbContextFactory.CreateDbContextAsync();+ var latestVaultEncryptionSettings = await AuthHelper.GetUserLatestVaultEncryptionSettingsAsync(context, user);// Get or create SRP identity. For existing users without SrpIdentity, fall back to username (lowercase).var srpIdentity = user.SrpIdentity ?? user.UserName!.ToLowerInvariant();@@ -521,8 +570,8 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}/// <summary>- /// Password change submit. Verifies the current password via SRP, then atomically updates the- /// password VaultKey row with the new salt/verifier and the rewrapped VEK.+ /// 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>@@ -537,15 +586,15 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}await using var context = await dbContextFactory.CreateDbContextAsync();- var vaultKey = await context.VaultKeys.FirstOrDefaultAsync(x => x.UserId == user.Id && x.KeyType == AuthHelper.VaultKeyTypePassword);- if (vaultKey == null)+ var unlockKey = await context.UserUnlockKeys.FirstOrDefaultAsync(x => x.UserId == user.Id && x.Type == UnlockMethodType.Password);+ if (unlockKey == null){// Legacy users that have not migrated to v2 yet need to use the v1 flow (or migrate first).return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_KEY_NOT_FOUND, 400));}// Validate the SRP session (actual current password check).- var serverSession = AuthHelper.ValidateSrpSession(cache, user, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);+ var serverSession = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);if (serverSession is null){// Increment failed login attempts in order to lock out the account when the limit is reached.@@ -555,12 +604,15 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMreturn BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PASSWORD_MISMATCH, 400));}- vaultKey.Salt = model.NewPasswordSalt;- vaultKey.Verifier = model.NewPasswordVerifier;- vaultKey.WrappedVek = model.NewWrappedVek;- vaultKey.EncryptionType = Defaults.EncryptionType;- vaultKey.EncryptionSettings = Defaults.EncryptionSettings;- vaultKey.UpdatedAt = timeProvider.UtcNow;+ // Read-modify-write so any per-method fields this build does not know about survive the credential swap.+ var unlockKeyMetadata = VaultKeyMetadata.Parse(unlockKey.Metadata);+ unlockKeyMetadata.Salt = model.NewPasswordSalt;+ unlockKeyMetadata.SrpVerifier = model.NewPasswordVerifier;+ unlockKeyMetadata.EncryptionType = Defaults.EncryptionType;+ unlockKeyMetadata.EncryptionSettings = Defaults.EncryptionSettings;+ unlockKey.Metadata = unlockKeyMetadata.ToJson();+ unlockKey.EncryptedAccountKey = model.NewEncryptedAccountKey;+ unlockKey.UpdatedAt = timeProvider.UtcNow;await context.SaveChangesAsync();// Update the password last changed at timestamp for user.@@ -570,7 +622,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMawait authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.PasswordChange);// Force revoke all logged-in sessions except the current one so other clients re-authenticate with the- // new password and rederive their KEK. Their locally cached vault stays decryptable: the VEK is unchanged.+ // new password and rederive their KEK. Their locally cached vault stays decryptable: the AK is unchanged.var deviceIdentifier = AuthHelper.GenerateDeviceIdentifier(Request);await context.AliasVaultUserRefreshTokens.Where(x => x.UserId == user.Id && x.DeviceIdentifier != deviceIdentifier).ExecuteDeleteAsync();@@ -639,7 +691,8 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}// Retrieve latest vault of user which contains the current salt and verifier.- var latestVaultEncryptionSettings = AuthHelper.GetUserLatestVaultEncryptionSettings(user);+ await using var context = await dbContextFactory.CreateDbContextAsync();+ var latestVaultEncryptionSettings = await AuthHelper.GetUserLatestVaultEncryptionSettingsAsync(context, user);// Get or create SRP identity. For existing users without SrpIdentity, fall back to username (lowercase).var srpIdentity = user.SrpIdentity ?? user.UserName!.ToLowerInvariant();@@ -879,7 +932,8 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}// Validate the SRP session (actual password check).- var serverSession = AuthHelper.ValidateSrpSession(cache, user, model.ClientPublicEphemeral, model.ClientSessionProof);+ await using var context = await dbContextFactory.CreateDbContextAsync();+ var serverSession = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.ClientPublicEphemeral, model.ClientSessionProof);if (serverSession is null){await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.AccountDeletion, AuthFailureReason.InvalidPassword);@@ -890,7 +944,10 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMawait authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.AccountDeletion);// Delete the user and their data.- await using var context = await dbContextFactory.CreateDbContextAsync();++ // 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();@@ -1042,7 +1099,8 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}// Validate the SRP session (actual password check).- var serverSession = AuthHelper.ValidateSrpSession(cache, user, model.ClientPublicEphemeral, model.ClientSessionProof);+ await using var context = await dbContextFactory.CreateDbContextAsync();+ var serverSession = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, model.ClientPublicEphemeral, model.ClientSessionProof);if (serverSession is null){// Increment failed login attempts in order to lock out the account when the limit is reached.diff --git a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.csindex 51eb36592..9b5dc6696 100644--- a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs@@ -9,6 +9,7 @@ namespace AliasVault.Api.Controllers.V2.Email;using AliasServerDb;using AliasVault.Api.Controllers.Abstracts;+using AliasVault.Api.Helpers;using AliasVault.Auth.IpAddress;using AliasVault.Shared.Models.Spamok;using AliasVault.Shared.Models.WebApi;@@ -51,7 +52,7 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, Uvar sanitizedEmail = to.Trim().ToLower();// See if this user has a valid claim to the email address.- var emailClaim = await context.UserEmailClaims+ var emailClaim = await context.EmailClaims.FirstOrDefaultAsync(x => x.Address == sanitizedEmail);if (emailClaim is null || emailClaim.Disabled)@@ -66,7 +67,8 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U});}- if (emailClaim.UserId != user.Id)+ // Check if the user has access to the email address.+ if (!await EmailAccessHelper.CanReadClaimAsync(context, emailClaim, user.Id)){return BadRequest(new ApiErrorResponse{@@ -78,8 +80,9 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U});}- // Retrieve emails from database (excluding any received after a shadow-block took effect).- var emailQuery = context.Emails.AsNoTracking().Where(x => x.To == sanitizedEmail);+ // Retrieve emails from database.+ var decryptableKeyIds = await EmailAccessHelper.ResolveDecryptableKeyIdsAsync(context, user.Id);+ var emailQuery = context.Emails.AsNoTracking().Where(x => x.To == sanitizedEmail && decryptableKeyIds.Contains(x.EncryptionKeyId));if (shadowCutoff is not null){emailQuery = emailQuery.Where(x => x.DateSystem <= shadowCutoff.Value);@@ -139,23 +142,22 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, Umodel.Addresses = model.Addresses.Select(x => x.Trim().ToLower()).ToList();model.PageSize = Math.Min(model.PageSize, 50);- // Load all email addresses that the user has a claim to where the address is in the list.- var validAddresses = await context.UserEmailClaims- .Where(claim => claim.UserId == user.Id && model.Addresses.Contains(claim.Address) && !claim.Disabled)- .Select(claim => claim.Address)- .ToListAsync();+ // Check if the user has access to the email addresses.+ var validAddresses = await EmailAccessHelper.FilterReadableAddressesAsync(context, model.Addresses, user.Id);var page = Math.Max(model.Page, 1);- // Fetch the newest emails for each address individually via a LATERAL join. This lets- // PostgreSQL use the (To, DateSystem) index to read only the top rows per address.+ // Restrict to emails this user holds a key for.+ var decryptableKeyIds = await EmailAccessHelper.ResolveDecryptableKeyIdsAsync(context, user.Id);++ // Fetch the newest emails for each address individually.var cutoffClause = shadowCutoff is null ? string.Empty : @" AND e2.""DateSystem"" <= @cutoff";var pageSql = $@"SELECT e.*FROM unnest(@addresses) AS addr(email)CROSS JOIN LATERAL (SELECT * FROM ""Emails"" AS e2- WHERE e2.""To"" = addr.email{cutoffClause}+ WHERE e2.""To"" = addr.email AND e2.""EncryptionKeyId"" = ANY(@keyids){cutoffClause}ORDER BY e2.""DateSystem"" DESCLIMIT @limit) AS e";@@ -163,6 +165,7 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, UList<NpgsqlParameter> parameters =[new("addresses", validAddresses.ToArray()),+ new("keyids", decryptableKeyIds.ToArray()),new("limit", page * model.PageSize),];@@ -197,8 +200,8 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U}).ToListAsync();- // Total count for pagination- var countQuery = context.Emails.Where(email => validAddresses.Contains(email.To));+ // Count the total number of emails.+ var countQuery = context.Emails.Where(email => validAddresses.Contains(email.To) && decryptableKeyIds.Contains(email.EncryptionKeyId));if (shadowCutoff is not null){countQuery = countQuery.Where(email => email.DateSystem <= shadowCutoff.Value);diff --git a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.csindex ca607fc14..df704a1ca 100644--- a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs@@ -9,6 +9,7 @@ namespace AliasVault.Api.Controllers.V2.Email;using AliasServerDb;using AliasVault.Api.Controllers.Abstracts;+using AliasVault.Api.Helpers;using AliasVault.Auth.IpAddress;using AliasVault.Shared.Models.Spamok;using Asp.Versioning;@@ -172,15 +173,22 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbContreturn (null, NotFound());}- // See if this user has a valid claim to the email address.+ // Check if the user has access to the email address.var normalizedEmailAddress = email.To.Trim().ToLower();- var emailClaim = await context.UserEmailClaims.FirstOrDefaultAsync(x => x.UserId == user.Id && x.Address == normalizedEmailAddress && !x.Disabled);+ var emailClaim = await context.EmailClaims.FirstOrDefaultAsync(x => x.Address == normalizedEmailAddress && !x.Disabled);- if (emailClaim is null)+ if (emailClaim is null || !await EmailAccessHelper.CanReadClaimAsync(context, emailClaim, user.Id)){return (null, Unauthorized("User does not have a claim to this email address."));}+ // Check if the user has access to the email.+ var decryptableKeyIds = await EmailAccessHelper.ResolveDecryptableKeyIdsAsync(context, user.Id);+ if (!decryptableKeyIds.Contains(email.EncryptionKeyId))+ {+ return (null, NotFound("Email not found."));+ }+return (email, null);}}diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.csindex 6c759fcca..4c72410d4 100644--- a/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultKeyController.cs@@ -1,4 +1,4 @@-//-----------------------------------------------------------------------+//-----------------------------------------------------------------------// <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.@@ -9,6 +9,7 @@ namespace AliasVault.Api.Controllers.V2;using AliasServerDb;using AliasVault.Api.Controllers.Abstracts;+using AliasVault.Api.Helpers;using AliasVault.Shared.Models.WebApi.V2.Auth;using Asp.Versioning;using Microsoft.AspNetCore.Identity;@@ -16,8 +17,7 @@ using Microsoft.AspNetCore.Mvc;using Microsoft.EntityFrameworkCore;/// <summary>-/// Vault key controller. Serves the encrypted VEK for an authenticated user so a client that has derived the KEK-/// from the unlock secret can decrypt the vault encryption key.+/// Vault key controller. Serves the encrypted Account Key for an authenticated user./// </summary>/// <param name="dbContextFactory">DbContext factory.</param>/// <param name="userManager">UserManager.</param>@@ -25,10 +25,9 @@ using Microsoft.EntityFrameworkCore;public class VaultKeyController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager) : AuthenticatedRequestController(userManager){/// <summary>- /// Get the encrypted VEK and KEK derivation parameters for the given key type. Always returns HTTP 200;- /// the payload's VaultKey is null when the user has no such vault key (legacy user, or unknown key type).+ /// 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" — the <see cref="VaultKeyType"/> member name, case-insensitive.</param>+ /// <param name="type">The unlock method type, e.g. "password".</param>/// <returns>The vault key envelope DTO.</returns>[HttpGet("{type}")]public async Task<IActionResult> Get(string type)@@ -40,29 +39,41 @@ public class VaultKeyController(IAliasServerDbContextFactory dbContextFactory, Ureturn Unauthorized();}- // A method this build does not know about is "no such key" rather than an error, so a newer client asking- // for one it supports and this server does not degrades to the same path as a legacy user with no key.- if (!Enum.TryParse<VaultKeyType>(type, true, out var parsedType) || !Enum.IsDefined(parsedType))+ // Check if the unlock method type is valid.+ if (!Enum.TryParse<UnlockMethodType>(type, true, out var parsedType) || !Enum.IsDefined(parsedType)){return Ok(new VaultKeyGetResponse { VaultKey = null });}- var vaultKey = await context.VaultKeys.FirstOrDefaultAsync(x => x.UserId == user.Id && x.Type == parsedType);- if (vaultKey == null)+ var unlockKey = await context.UserUnlockKeys.FirstOrDefaultAsync(x => x.UserId == user.Id && x.Type == parsedType);+ if (unlockKey == null){return Ok(new VaultKeyGetResponse { VaultKey = null });}- // The verifier stays server-side; only the KEK derivation inputs are served.- var (salt, _, encryptionType, encryptionSettings) = VaultKeyMetadata.Parse(vaultKey.Metadata).RequireSrpCredentials();+ // Get the encrypted VEK and account keypair.+ var rootManifestId = await GroupHelper.GetRootManifestIdAsync(context, user.PersonalGroupId);+ var encryptedVek = rootManifestId is null ? null : await context.VaultManifestAccessKeys+ .Where(x => x.UserId == user.Id && x.Type == ManifestKeyType.AccountKey && x.VaultManifestId == rootManifestId.Value)+ .Select(x => x.EncryptedVek)+ .FirstOrDefaultAsync();+ var accountKeypair = await context.UserGrantKeys+ .Where(x => x.UserId == user.Id && x.IsPrimary)+ .Select(x => new { x.PublicKey, x.EncryptedPrivateKey })+ .FirstOrDefaultAsync();++ // Get the KEK derivation parameters.+ var (salt, _, encryptionType, encryptionSettings) = VaultKeyMetadata.Parse(unlockKey.Metadata).RequireSrpCredentials();return Ok(new VaultKeyGetResponse{VaultKey = new VaultKeyResponse{- // The wire contract is the lowercased member name; clients match on the literal "password".- Type = vaultKey.Type.ToString().ToLowerInvariant(),- EncryptedVek = vaultKey.EncryptedVek,+ Type = unlockKey.Type.ToString().ToLowerInvariant(),+ EncryptedAccountKey = unlockKey.EncryptedAccountKey,+ EncryptedVek = encryptedVek,+ AccountPublicKey = accountKeypair?.PublicKey,+ EncryptedAccountPrivateKey = accountKeypair?.EncryptedPrivateKey,Salt = salt,EncryptionType = encryptionType,EncryptionSettings = encryptionSettings,diff --git a/apps/server/AliasVault.Api/Helpers/AuthHelper.cs b/apps/server/AliasVault.Api/Helpers/AuthHelper.csindex 4c2df6537..8cd4b7001 100644--- a/apps/server/AliasVault.Api/Helpers/AuthHelper.cs+++ b/apps/server/AliasVault.Api/Helpers/AuthHelper.cs@@ -1,4 +1,4 @@-//-----------------------------------------------------------------------+//-----------------------------------------------------------------------// <copyright file="AuthHelper.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.@@ -70,23 +70,21 @@ public static class AuthHelper}/// <summary>- /// Get the user's current SRP salt/verifier and key derivation settings. For users migrated to the KEK/VEK- /// model these live on the password VaultKey row; for legacy users they live on the root vault manifest,- /// which is resolved through the user's personal group — the group is the only ownership path to a manifest.+ /// Get the user's current SRP salt/verifier and key derivation settings./// </summary>/// <param name="context">Database context.</param>/// <param name="user">User object.</param>/// <returns>Tuple with salt, verifier, encryption type and encryption settings.</returns>public static async Task<(string Salt, string Verifier, string EncryptionType, string EncryptionSettings)> GetUserLatestVaultEncryptionSettingsAsync(AliasServerDbContext context, AliasVaultUser user){- // KEK/VEK model: the password VaultKey row is the authority for SRP credentials once it exists.- var passwordKey = await context.VaultKeys.FirstOrDefaultAsync(x => x.UserId == user.Id && x.Type == VaultKeyType.Password);+ // Get the user's current SRP salt/verifier and key derivation settings for the account-key KEK/VEK model.+ var passwordKey = await context.UserUnlockKeys.FirstOrDefaultAsync(x => x.UserId == user.Id && x.Type == UnlockMethodType.Password);if (passwordKey is not null){return VaultKeyMetadata.Parse(passwordKey.Metadata).RequireSrpCredentials();}- // Legacy model: the root manifest carries the current encryption settings. TODO: delete once all users have migrated to the KEK/VEK model.+ // Get the user's current SRP salt/verifier and key derivation settings for the legacy model.var latestVault = await context.VaultManifests.Where(m => m.IsRoot && m.OwnerGroupId == user.PersonalGroupId).Select(x => new { x.Salt, x.Verifier, x.EncryptionType, x.EncryptionSettings })diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/VaultKeyResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/VaultKeyResponse.csindex fb5356a36..82fb4ed01 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/VaultKeyResponse.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/VaultKeyResponse.cs@@ -8,15 +8,20 @@namespace AliasVault.Shared.Models.WebApi.V2.Auth;/// <summary>-/// Response for GET /v2/VaultKey/{type}.+/// Response for GET /v2/VaultKey/{type}: the encrypted Account Key and KEK derivation parameters for the given unlock method./// </summary>public class VaultKeyResponse{/// <summary>Gets or sets the unlock method type.</summary>public required string Type { get; set; }- /// <summary>Gets or sets the encrypted VEK: base64(IV | ciphertext | authTag) of the VEK encrypted with the KEK.</summary>- public required string EncryptedVek { get; set; }+ /// <summary>Gets or sets the Account Key encrypted with the KEK derived from the unlock method.</summary>+ public required string EncryptedAccountKey { get; set; }++ /// <summary>+ /// Gets or sets the encrypted VEK.+ /// </summary>+ public string? EncryptedVek { get; set; }/// <summary>Gets or sets the salt used for KEK derivation.</summary>public required string Salt { get; set; }diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/AccountKeysUpload.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/AccountKeysUpload.csnew file mode 100644index 000000000..d49b05fe1--- /dev/null+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/AccountKeysUpload.cs@@ -0,0 +1,23 @@+//-----------------------------------------------------------------------+// <copyright file="AccountKeysUpload.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.Shared.Models.WebApi.V2.Vault;++/// <summary>+/// Upload request for the encrypted Account Key and KEK derivation parameters for the given unlock method.+/// </summary>+public class AccountKeysUpload+{+ /// <summary>Gets or sets the Account Key encrypted with the KEK derived from the unlock method.</summary>+ public string? EncryptedAccountKey { get; set; }++ /// <summary>Gets or sets the encrypted VEK.</summary>+ public string? AccountPublicKey { get; set; }++ /// <summary>Gets or sets the account private key encrypted with the Account Key.</summary>+ public string? EncryptedAccountPrivateKey { get; set; }+}diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/GetResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/GetResponse.csindex faaef22a8..99dcf245d 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/GetResponse.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/GetResponse.cs@@ -1,4 +1,4 @@-//-----------------------------------------------------------------------+//-----------------------------------------------------------------------// <copyright file="GetResponse.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.@@ -31,6 +31,11 @@ public class GetResponse/// <summary>Gets or sets the legacy sqlite-blob revision number. Set only when StorageFormat = SqliteBlob.</summary>public long? LegacyRevision { get; set; }+ /// <summary>+ /// Gets or sets the caller's root manifest id.+ /// </summary>+ public Guid? RootManifestId { get; set; }+/// <summary>/// Gets or sets the manifests that make up the user's logical vault. Empty for legacy sqlite-blobs./// </summary>diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/VaultWriteRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/VaultWriteRequest.csindex 131723e7d..b42ff7112 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/VaultWriteRequest.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/VaultWriteRequest.cs@@ -1,4 +1,4 @@-//-----------------------------------------------------------------------+//-----------------------------------------------------------------------// <copyright file="VaultWriteRequest.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.@@ -27,12 +27,18 @@ public class VaultWriteRequest/// <summary>Gets or sets the email routing data to update server-side.</summary>public EmailRouting? EmailRouting { get; set; }- /// <summary>Gets or sets the public half of the user's own encryption keypair (client table `EncryptionKeys`).</summary>+ /// <summary>+ /// Gets or sets the user's public encryption key.+ /// </summary>public string? UserEncryptionPublicKey { get; set; }/// <summary>- /// Gets or sets the public halves of the shared folders' own encryption keypairs (client table- /// `SharedFolderEncryptionKeys`).+ /// Gets or sets the shared folders' public encryption keys./// </summary>public List<SharedFolderEncryptionPublicKey> SharedFolderEncryptionPublicKeys { get; set; } = [];++ /// <summary>+ /// Gets or sets the encrypted Account Key and KEK derivation parameters for the given unlock method.+ /// </summary>+ public AccountKeysUpload? AccountKeys { get; set; }}