Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update GroupHelper.cs (#2159)
Leendert de Borst2a647ed21404
diff --git a/apps/server/AliasVault.Api/Controllers/V2/SharingController.cs b/apps/server/AliasVault.Api/Controllers/V2/SharingController.csindex ca4f18ff3..d710067f9 100644--- a/apps/server/AliasVault.Api/Controllers/V2/SharingController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/SharingController.cs@@ -21,7 +21,7 @@ using Microsoft.AspNetCore.Mvc;using Microsoft.EntityFrameworkCore;/// <summary>-/// Vault sharing. A shared manifest is a non-root <see cref="VaultManifest"/> owned by a <see cref="Group"/> and+/// Vault sharing. A shared manifest is a non-personal <see cref="VaultManifest"/> owned by a <see cref="Group"/> and/// encrypted with its own VEK. Access is granted by persisting that VEK encrypted with a member's public key as a/// <c>shared</c> <see cref="VaultManifestAccessKey"/> row./// </summary>@@ -94,22 +94,28 @@ public class SharingController(IAliasServerDbContextFactory dbContextFactory, Usreturn NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.RECIPIENT_KEY_NOT_FOUND, 404));}- /*- * The manifest id is generated by the client: the encrypted placeholder manifest already carries it as its- * identity (the codec refuses id-less manifests), and the server cannot rewrite an encrypted blob.- * Uniqueness is enforced here (and by the primary key) so a colliding id cannot hijack an existing- * manifest.- */- if (model.ManifestId == Guid.Empty || await context.VaultManifests.AnyAsync(x => x.ManifestId == model.ManifestId))+ if (model.ManifestId == Guid.Empty)+ {+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.MANIFEST_ID_INVALID, 400));+ }++ var ownerGroupId = await GroupHelper.ResolveShareTargetGroupIdAsync(context, me.Id, model.GroupId);+ if (ownerGroupId is null){- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_NOT_UP_TO_DATE, 400));+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.GROUP_NOT_FOUND, 404));+ }++ // The manifest id must be unique.+ var duplicate = await ResolveDuplicateAsync(context, model, ownerGroupId.Value);+ if (duplicate is not null)+ {+ return duplicate;}var manifest = new VaultManifest{ManifestId = model.ManifestId,- IsRoot = false,- OwnerGroupId = me.PersonalGroupId,+ OwnerGroupId = ownerGroupId.Value,Name = model.Name,StorageFormat = ManifestFormat,ManifestBlob = model.ManifestBlob,@@ -133,7 +139,18 @@ public class SharingController(IAliasServerDbContextFactory dbContextFactory, UsCreatedAt = timeProvider.UtcNow,UpdatedAt = timeProvider.UtcNow,});- await context.SaveChangesAsync();++ try+ {+ await context.SaveChangesAsync();+ }+ catch (DbUpdateException)+ {+ // A duplicate manifest id was found, so retry the operation with a fresh context.+ await using var retryContext = await dbContextFactory.CreateDbContextAsync();+ return await ResolveDuplicateAsync(retryContext, model, ownerGroupId.Value)+ ?? BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.MANIFEST_ID_TAKEN, 400));+ }return Ok(new CreateSharedManifestResponse { ManifestId = manifest.ManifestId, RevisionNumber = manifest.RevisionNumber });}@@ -160,8 +177,8 @@ public class SharingController(IAliasServerDbContextFactory dbContextFactory, Usreturn BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_ALGORITHM, 400));}- // The caller must be an admin of the group that owns the (non-root) manifest being shared.- var manifest = await context.VaultManifests.FirstOrDefaultAsync(x => x.ManifestId == model.ManifestId && !x.IsRoot);+ // The caller must be an admin of the group that owns the (non-personal) manifest being shared.+ var manifest = await GroupHelper.SharedManifests(context).FirstOrDefaultAsync(x => x.ManifestId == model.ManifestId);if (manifest is null || !await GroupHelper.IsGroupAdminAsync(context, manifest.OwnerGroupId, me.Id)){return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));@@ -255,26 +272,39 @@ public class SharingController(IAliasServerDbContextFactory dbContextFactory, Usreturn NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));}- // The owner is the group's owner, which is not necessarily the caller: an admin may be listing a manifest belonging to a group someone else owns.+ /*+ * The owner is the group's owner, which is not necessarily the caller: an admin may be listing a manifest belonging to a group+ * someone else owns.+ */var ownerUserId = await context.VaultManifests.Where(m => m.ManifestId == manifestId).Join(context.GroupMembers.Where(gm => gm.Role == GroupRole.Owner), m => m.OwnerGroupId, gm => gm.GroupId, (m, gm) => new { gm.UserId, gm.CreatedAt }).OrderBy(x => x.CreatedAt).ThenBy(x => x.UserId).Select(x => x.UserId)- .FirstAsync();+ .FirstOrDefaultAsync();++ var grants = (await context.VaultManifestAccessKeys+ .Where(x => x.VaultManifestId == manifestId && x.Type == ManifestKeyType.GrantKey)+ .ToListAsync())+ .Where(x => x.UserId != ownerUserId)+ .ToList();- // The owner holds a self-grant too (their own encrypted VEK), but it is surfaced as the owner entry below, not as a recipient. So exclude it from the recipient list.- var grants = await context.VaultManifestAccessKeys- .Where(x => x.VaultManifestId == manifestId && x.Type == ManifestKeyType.GrantKey && x.UserId != ownerUserId)- .ToListAsync();+ var lookupIds = grants.Select(g => g.UserId).ToList();+ if (ownerUserId is not null)+ {+ lookupIds.Add(ownerUserId);+ }- var lookupIds = grants.Select(g => g.UserId).Append(ownerUserId).ToList();var usernamesById = await context.AliasVaultUsers.Where(u => lookupIds.Contains(u.Id)).ToDictionaryAsync(u => u.Id, u => u.UserName);var response = new ShareMembersResponse();- response.Members.Add(new ShareMember { UserId = ownerUserId, Username = usernamesById.GetValueOrDefault(ownerUserId), IsOwner = true });+ if (ownerUserId is not null)+ {+ response.Members.Add(new ShareMember { UserId = ownerUserId, Username = usernamesById.GetValueOrDefault(ownerUserId), IsOwner = true });+ }+foreach (var g in grants){response.Members.Add(new ShareMember@@ -289,4 +319,31 @@ public class SharingController(IAliasServerDbContextFactory dbContextFactory, Usreturn Ok(response);}++ /// <summary>+ /// Resolve what an already-taken manifest id means for a create request.+ /// </summary>+ /// <param name="context">DbContext to resolve against.</param>+ /// <param name="model">The create request.</param>+ /// <param name="ownerGroupId">The shared group the manifest is being filed under.</param>+ /// <returns>The response to return, or null when no manifest holds this id.</returns>+ private static async Task<IActionResult?> ResolveDuplicateAsync(AliasServerDbContext context, CreateSharedManifestRequest model, Guid ownerGroupId)+ {+ var existing = await GroupHelper.SharedManifests(context).FirstOrDefaultAsync(x => x.ManifestId == model.ManifestId);+ if (existing is null)+ {+ // Either no such manifest, or the id names a personal manifest.+ return await context.VaultManifests.AnyAsync(x => x.ManifestId == model.ManifestId)+ ? new BadRequestObjectResult(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.MANIFEST_ID_TAKEN, 400))+ : null;+ }++ // Once the manifest has moved on from its placeholder revision the hash differs, so a late replay stops matching and is reported as a collision.+ if (existing.OwnerGroupId == ownerGroupId && existing.ManifestCiphertextHash == model.ManifestCiphertextHash)+ {+ return new OkObjectResult(new CreateSharedManifestResponse { ManifestId = existing.ManifestId, RevisionNumber = existing.RevisionNumber });+ }++ return new BadRequestObjectResult(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.MANIFEST_ID_TAKEN, 400));+ }}diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultController.csindex f340a5d42..db1ae9e13 100644--- a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs@@ -721,8 +721,8 @@ public class VaultController(return [];}- var administered = await context.VaultManifests- .Where(m => ids.Contains(m.ManifestId) && m.OwnerGroup.Type == GroupType.Shared+ var administered = await GroupHelper.SharedManifests(context)+ .Where(m => ids.Contains(m.ManifestId)&& context.GroupMembers.Any(gm => gm.GroupId == m.OwnerGroupId && gm.UserId == userId && (gm.Role == GroupRole.Admin || gm.Role == GroupRole.Owner))).Select(m => m.ManifestId).ToListAsync();diff --git a/apps/server/AliasVault.Api/Helpers/EmailAccessHelper.cs b/apps/server/AliasVault.Api/Helpers/EmailAccessHelper.csindex bb967e3c9..36d913fb5 100644--- a/apps/server/AliasVault.Api/Helpers/EmailAccessHelper.cs+++ b/apps/server/AliasVault.Api/Helpers/EmailAccessHelper.cs@@ -37,8 +37,10 @@ public static class EmailAccessHelperreturn true;}- // TODO: legacy fallback — pre-KEK/VEK accounts have no AccountKey row on their personal manifest yet, so owning the manifest's group is their only proof of access. Delete once all clients have migrated.- return await context.VaultManifests.AnyAsync(m => m.ManifestId == claim.VaultManifestId && context.GroupMembers.Any(gm => gm.GroupId == m.OwnerGroupId && gm.UserId == userId && gm.Role == GroupRole.Owner));+ // TODO: legacy fallback: pre-KEK/VEK accounts have no AccountKey row on their personal manifest yet, so the manifest being filed+ // under their personal group is their only proof of access. Personal groups only: a shared manifest is grants-only, so a group owner+ // whose grant was revoked must not read its mail. Delete once all clients have migrated.+ return await context.VaultManifests.AnyAsync(m => m.ManifestId == claim.VaultManifestId && context.AliasVaultUsers.Any(u => u.Id == userId && u.PersonalGroupId == m.OwnerGroupId));}/// <summary>@@ -73,11 +75,12 @@ public static class EmailAccessHelper.Select(k => k.VaultManifestId).ToListAsync()).ToHashSet();- // Legacy fallback: pre-KEK/VEK accounts have no AccountKey row on their personal manifest yet- // so owning the manifest's group is their only proof of access. TODO: delete once all clients have migrated.- var ownedGroupIds = (await GroupHelper.GetOwnedGroupIdsAsync(context, userId)).ToHashSet();+ // Legacy fallback: pre-KEK/VEK accounts have no AccountKey row on their personal manifest yet, so the manifest being filed under+ // their personal group is their only proof of access. Personal group only: a shared manifest is grants-only, so a group owner whose+ // grant was revoked must not read its mail. TODO: delete once all clients have migrated.+ var personalGroupId = await GroupHelper.GetPersonalGroupIdAsync(context, userId);- return claims.Where(c => keyedManifestIds.Contains(c.ManifestId) || ownedGroupIds.Contains(c.OwnerGroupId)).Select(c => c.Address).ToList();+ return claims.Where(c => keyedManifestIds.Contains(c.ManifestId) || c.OwnerGroupId == personalGroupId).Select(c => c.Address).ToList();}/// <summary>diff --git a/apps/server/AliasVault.Api/Helpers/GroupHelper.cs b/apps/server/AliasVault.Api/Helpers/GroupHelper.csindex 4ff3a4e51..44f4853d7 100644--- a/apps/server/AliasVault.Api/Helpers/GroupHelper.cs+++ b/apps/server/AliasVault.Api/Helpers/GroupHelper.cs@@ -61,16 +61,21 @@ public static class GroupHelper/// <summary>/// Resolve the <see cref="GroupType.Shared"/> group a new shared manifest is filed under. The caller always names/// the group and it must already exist: creating a group is an explicit action of its own, never a side effect of- /// sharing something, so there is no implicit "the caller's own family group" to fall back to.+ /// sharing something, so there is no implicit "the caller's own family group" to fall back to. Refusing a+ /// <see cref="GroupType.Personal"/> group here is also what keeps a personal group at exactly one manifest, which+ /// every personal-manifest lookup relies on (see <see cref="GetPersonalManifestIdAsync"/>)./// </summary>/// <param name="context">Database context.</param>/// <param name="userId">The caller.</param>/// <param name="groupId">The shared group named by the caller.</param>- /// <returns>The group to own the manifest, or null when it does not exist, is not a shared group, or the caller may not administer it.</returns>- public static async Task<Group?> ResolveShareTargetGroupAsync(AliasServerDbContext context, string userId, Guid groupId)+ /// <returns>The group id, or null when it does not exist, is not a shared group, or the caller may not administer it.</returns>+ public static async Task<Guid?> ResolveShareTargetGroupIdAsync(AliasServerDbContext context, string userId, Guid groupId){- var group = await context.Groups.FirstOrDefaultAsync(g => g.Id == groupId && g.Type == GroupType.Shared);- return group is not null && await IsGroupAdminAsync(context, group.Id, userId) ? group : null;+ var resolved = await context.Groups.AnyAsync(g => g.Id == groupId+ && g.Type == GroupType.Shared+ && g.Members.Any(m => m.UserId == userId && (m.Role == GroupRole.Owner || m.Role == GroupRole.Admin)));++ return resolved ? groupId : null;}/// <summary>@@ -117,8 +122,20 @@ public static class GroupHelper}/// <summary>- /// Get the personal manifest of a personal group, i.e. the manifest a user's personal keys and- /// personal aliases are scoped to. A personal group owns exactly one manifest by construction.+ /// Get the id of the user's personal group, the group owning everything that is theirs alone. Every user has+ /// exactly one, created with the account and enforced by the unique <c>UX_AliasVaultUsers_PersonalGroupId</c>.+ /// </summary>+ /// <param name="context">Database context.</param>+ /// <param name="userId">The user.</param>+ /// <returns>The personal group id, or null when the user does not exist.</returns>+ public static async Task<Guid?> GetPersonalGroupIdAsync(AliasServerDbContext context, string userId)+ {+ return await context.AliasVaultUsers.Where(u => u.Id == userId).Select(u => (Guid?)u.PersonalGroupId).FirstOrDefaultAsync();+ }++ /// <summary>+ /// Get the personal manifest of a personal group, i.e. the manifest a user's personal keys and personal aliases+ /// are scoped to./// </summary>/// <param name="context">Database context.</param>/// <param name="personalGroupId">The user's personal group.</param>diff --git a/apps/server/AliasVault.Api/Helpers/ManifestAccessHelper.cs b/apps/server/AliasVault.Api/Helpers/ManifestAccessHelper.csindex f60393fbf..7c5038798 100644--- a/apps/server/AliasVault.Api/Helpers/ManifestAccessHelper.cs+++ b/apps/server/AliasVault.Api/Helpers/ManifestAccessHelper.cs@@ -15,7 +15,7 @@ using AliasServerDb;public static class ManifestAccessHelper{/// <summary>- /// Every manifest the user can access.+ /// Every manifest the user can access: their own personal manifest, plus every shared manifest they hold a grant on./// </summary>/// <param name="context">Database context.</param>/// <param name="userId">The calling user.</param>@@ -23,7 +23,7 @@ public static class ManifestAccessHelperpublic static IQueryable<VaultManifest> AccessibleManifests(AliasServerDbContext context, string userId){return context.VaultManifests- .Where(m => context.GroupMembers.Any(gm => gm.GroupId == m.OwnerGroupId && gm.UserId == userId && gm.Role == GroupRole.Owner)+ .Where(m => context.AliasVaultUsers.Any(u => u.Id == userId && u.PersonalGroupId == m.OwnerGroupId)|| context.VaultManifestAccessKeys.Any(k => k.UserId == userId && k.Type == ManifestKeyType.GrantKey && k.VaultManifestId == m.ManifestId));}}