Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Apply generic VEK wrapping for shared manifest owner too for consistency (#2159)
Leendert de Borst2a919226ec99
diff --git a/apps/browser-extension/src/utils/db/repositories/FolderRepository.ts b/apps/browser-extension/src/utils/db/repositories/FolderRepository.tsindex 0ed75034f..c80d3da3b 100644--- a/apps/browser-extension/src/utils/db/repositories/FolderRepository.ts+++ b/apps/browser-extension/src/utils/db/repositories/FolderRepository.ts@@ -19,11 +19,13 @@ export class FolderRepository extends BaseRepository {* Create a new folder.* @param name - The name of the folder* @param parentFolderId - Optional parent folder ID for nested folders+ * @param id - Optional explicit folder ID (used when the id must be known before creation, e.g. a shared folder+ * whose id is embedded in its server-side manifest); a new GUID is generated when omitted.* @returns The ID of the created folder*/- public async create(name: string, parentFolderId?: string | null): Promise<string> {+ public async create(name: string, parentFolderId?: string | null, id?: string): Promise<string> {return this.withTransaction(async () => {- const folderId = crypto.randomUUID().toUpperCase();+ const folderId = id ?? crypto.randomUUID().toUpperCase();const currentDateTime = this.now();this.client.executeUpdate(FolderQueries.INSERT, [diff --git a/apps/server/AliasVault.Api/Controllers/V2/SharingController.cs b/apps/server/AliasVault.Api/Controllers/V2/SharingController.csindex df8549f15..70ec3f959 100644--- a/apps/server/AliasVault.Api/Controllers/V2/SharingController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/SharingController.cs@@ -22,9 +22,8 @@ using Microsoft.EntityFrameworkCore;/// <summary>/// Vault sharing. A shared folder is a non-root <see cref="VaultManifest"/> owned by a user and-/// encrypted with its own VEK. Access is granted by persisting that VEK wrapped with a recipient's public key as a-/// <c>shared</c> <see cref="VaultKey"/> row. The owner keeps their own copy of the folder VEK client-side-/// (inside their main vault).+/// encrypted with its own VEK. Access is granted by persisting that VEK wrapped with a member's public key as a+/// <c>shared</c> <see cref="VaultKey"/> row./// </summary>/// <param name="dbContextFactory">DbContext factory.</param>/// <param name="userManager">UserManager.</param>@@ -69,8 +68,8 @@ public class SharingController(}/// <summary>- /// Create a new shared folder manifest owned by the caller. The folder VEK is generated and kept- /// client-side; the server only stores the encrypted manifest. Access is granted afterwards via <see cref="Grant"/>.+ /// Create a new shared folder manifest owned by the caller, plus the caller's own <c>shared</c> grant (the+ /// folder VEK wrapped with their own public key)./// </summary>/// <param name="model">The create request.</param>/// <param name="clientHeader">The client identifier header.</param>@@ -85,6 +84,19 @@ public class SharingController(return Unauthorized();}+ // The owner's self-grant must be wrapped asymmetrically for their own public key.+ if (!AuthHelper.AsymmetricWrapSchemes.Contains(model.WrapScheme))+ {+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_WRAP_SCHEME, 400));+ }++ // The key wrapped for must be the caller's own public key.+ var keyOwnedByMe = await context.UserEncryptionKeys.AnyAsync(x => x.Id == model.SelfPublicKeyId && x.UserId == me.Id);+ if (!keyOwnedByMe)+ {+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.RECIPIENT_KEY_NOT_FOUND, 404));+ }+var manifest = new VaultManifest{ManifestId = Guid.NewGuid(),@@ -107,6 +119,18 @@ public class SharingController(UpdatedAt = timeProvider.UtcNow,};context.VaultManifests.Add(manifest);+ context.VaultKeys.Add(new VaultKey+ {+ Id = Guid.NewGuid(),+ UserId = me.Id,+ VaultManifestId = manifest.ManifestId,+ KeyType = AuthHelper.VaultKeyTypeShared,+ WrapScheme = model.WrapScheme,+ WrappedVek = model.SelfWrappedVek,+ RecipientPublicKeyId = model.SelfPublicKeyId,+ CreatedAt = timeProvider.UtcNow,+ UpdatedAt = timeProvider.UtcNow,+ });await context.SaveChangesAsync();return Ok(new CreateSharedFolderResponse { ManifestId = manifest.ManifestId, RevisionNumber = manifest.RevisionNumber });@@ -226,8 +250,10 @@ public class SharingController(return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));}+ // The owner holds a self-grant too (their own wrapped VEK), but it is surfaced as the synthetic owner+ // entry below, not as a recipient. So exclude it from the recipient list.var grants = await context.VaultKeys- .Where(x => x.VaultManifestId == manifestId && x.KeyType == AuthHelper.VaultKeyTypeShared)+ .Where(x => x.VaultManifestId == manifestId && x.KeyType == AuthHelper.VaultKeyTypeShared && x.UserId != me.Id).ToListAsync();var recipientIds = grants.Select(g => g.UserId).ToList();@@ -254,7 +280,7 @@ public class SharingController(/// <summary>/// Upload a new revision of a shared-folder manifest. Allowed for the owner and for every user holding a- /// <c>shared</c> grant on it — all members write the same manifest, guarded by the optimistic revision check+ /// <c>shared</c> grant on it. All members write the same manifest, guarded by the optimistic revision check/// (a stale writer gets <see cref="VaultStatus.Outdated"/> and must re-pull + merge, like the root manifest)./// Blob bytes are uploaded beforehand via <c>POST /v2/Vault/blobs</c> into the pusher's own store; the manifest/// snapshot endpoints resolve referenced blobs across member stores.diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultController.csindex 13945dd6a..7a46f2985 100644--- a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs@@ -183,6 +183,15 @@ public class VaultController(.GroupBy(x => x.ManifestId).ToDictionary(g => g.Key, g => g.Select(x => new BlobReference { Hash = x.Hash, Category = x.Category }).ToList());+ // The caller's own grants on the non-root manifests they own: the folder VEK wrapped with their own public+ // key.+ var ownedNonRootIds = latestManifests.Where(m => !m.IsRoot).Select(m => m.ManifestId).ToList();+ var selfGrantsByManifest = ownedNonRootIds.Count == 0+ ? new Dictionary<Guid, VaultKey>()+ : await context.VaultKeys+ .Where(k => k.UserId == user.Id && k.KeyType == AuthHelper.VaultKeyTypeShared && k.VaultManifestId != null && ownedNonRootIds.Contains(k.VaultManifestId.Value))+ .ToDictionaryAsync(k => k.VaultManifestId!.Value);+var manifests = latestManifests.Select(m => new Manifest{ManifestId = m.ManifestId,@@ -192,10 +201,13 @@ public class VaultController(CiphertextHash = m.ManifestCiphertextHash,Revision = m.RevisionNumber,BlobReferences = refsByManifest.TryGetValue(m.ManifestId, out var refs) ? refs : [],+ WrappedVek = selfGrantsByManifest.TryGetValue(m.ManifestId, out var selfGrant) ? selfGrant.WrappedVek : null,+ WrapScheme = selfGrantsByManifest.TryGetValue(m.ManifestId, out var selfGrant2) ? selfGrant2.WrapScheme : null,}).ToList();// Append manifests shared with this user by other owners, each carrying the wrapped VEK the caller- // unwraps with its private key.+ // unwraps with its private key. (OwnerUsername left null on the caller's own manifests above marks them+ // as owned rather than shared-with-me.)manifests.AddRange(await BuildSharedWithMeManifestsAsync(context, user.Id));return Ok(new GetResponse@@ -255,14 +267,17 @@ public class VaultController(BlobReferences = blobRefs,};- // Not the owner: enrich with the caller's grant (wrapped VEK + owner identity), same shape as the snapshot.- if (latest.OwnerUserId != user.Id)+ // A non-root manifest is unlocked via the caller's grant (their wrapped VEK), whether they own it (self-grant)+ // or another user shared it with them. Attach that grant; only stamp OwnerUsername when it is shared with them.+ if (!latest.IsRoot){var grant = await context.VaultKeys.FirstOrDefaultAsync(k => k.UserId == user.Id && k.KeyType == AuthHelper.VaultKeyTypeShared && k.VaultManifestId == latest.ManifestId);- var ownerUsername = await context.AliasVaultUsers.Where(u => u.Id == latest.OwnerUserId).Select(u => u.UserName).FirstOrDefaultAsync();manifest.WrappedVek = grant?.WrappedVek;manifest.WrapScheme = grant?.WrapScheme;- manifest.OwnerUsername = ownerUsername;+ if (latest.OwnerUserId != user.Id)+ {+ manifest.OwnerUsername = await context.AliasVaultUsers.Where(u => u.Id == latest.OwnerUserId).Select(u => u.UserName).FirstOrDefaultAsync();+ }}return Ok(manifest);@@ -669,12 +684,14 @@ public class VaultController(}/// <summary>- /// The ids of manifests other users have granted to <paramref name="userId"/> via a <c>shared</c> VaultKey row.+ /// The ids of manifests <b>other</b> users have granted to <paramref name="userId"/> via a <c>shared</c> VaultKey+ /// row. The user's own self-grants are excluded, those manifests are already covered as owned manifests./// </summary>private static async Task<List<Guid>> GetGrantedManifestIdsAsync(AliasServerDbContext context, string userId){return await context.VaultKeys- .Where(k => k.UserId == userId && k.KeyType == AuthHelper.VaultKeyTypeShared && k.VaultManifestId != null)+ .Where(k => k.UserId == userId && k.KeyType == AuthHelper.VaultKeyTypeShared && k.VaultManifestId != null+ && context.VaultManifests.Any(m => m.ManifestId == k.VaultManifestId && m.OwnerUserId != userId)).Select(k => k.VaultManifestId!.Value).ToListAsync();}@@ -686,8 +703,12 @@ public class VaultController(/// </summary>private static async Task<List<Manifest>> BuildSharedWithMeManifestsAsync(AliasServerDbContext context, string userId){+ // Only manifests owned by OTHER users. The user's own self-grant (their own shared folders) must be+ // excluded here — those are already returned as owned manifests, and re-listing them as shared-with-me+ // would stamp them with an OwnerUsername, flipping the owner's own share detection off.var grants = await context.VaultKeys- .Where(k => k.UserId == userId && k.KeyType == AuthHelper.VaultKeyTypeShared && k.VaultManifestId != null)+ .Where(k => k.UserId == userId && k.KeyType == AuthHelper.VaultKeyTypeShared && k.VaultManifestId != null+ && context.VaultManifests.Any(m => m.ManifestId == k.VaultManifestId && m.OwnerUserId != userId)).ToListAsync();if (grants.Count == 0){diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Sharing/CreateSharedFolderRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Sharing/CreateSharedFolderRequest.csindex c350749f2..46707f30d 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Sharing/CreateSharedFolderRequest.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Sharing/CreateSharedFolderRequest.cs@@ -9,8 +9,8 @@ namespace AliasVault.Shared.Models.WebApi.V2.Sharing;/// <summary>/// Request for POST /v2/Sharing/folders. Creates a new non-root (shareable) manifest owned by the caller. The-/// folder's VEK is generated and kept client-side (wrapped into the owner's own vault); the server only stores the-/// encrypted folder manifest. Access is granted to other users afterwards via POST /v2/Sharing/grant.+/// folder's VEK is generated client-side and wrapped for the caller's *own* public key, persisted as a+/// <c>shared</c> grant in the same call./// </summary>public class CreateSharedFolderRequest{@@ -25,4 +25,13 @@ public class CreateSharedFolderRequest/// <summary>Gets or sets the vault data model version string.</summary>public required string Version { get; set; }++ /// <summary>Gets or sets the folder VEK wrapped with the caller's own public key (base64), decryptable only by the caller.</summary>+ public required string SelfWrappedVek { get; set; }++ /// <summary>Gets or sets the id of the caller's own public key used to wrap (from GET /v2/Sharing/recipient for their own username).</summary>+ public required Guid SelfPublicKeyId { get; set; }++ /// <summary>Gets or sets the asymmetric wrap scheme used, e.g. "rsa-oaep".</summary>+ public required string WrapScheme { get; set; }}