Skip to content

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

Update sharing/group API handlers (#2159)

Leendert de Borstb6e5bdf6d20e
diff --git a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs
new file mode 100644
index 000000000..df4d1de63
--- /dev/null
+++ b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs
@@ -0,0 +1,585 @@
+//-----------------------------------------------------------------------
+// <copyright file="GroupsController.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;
+using AliasVault.Shared.Models.WebApi.V2.Groups;
+using AliasVault.Shared.Providers.Time;
+using Asp.Versioning;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+
+/// <summary>
+/// Groups controller which manages shared groups and their related manifests.
+/// </summary>
+/// <param name="dbContextFactory">The database context factory.</param>
+/// <param name="userManager">The user manager.</param>
+/// <param name="timeProvider">Time provider.</param>
+[ApiVersion("2")]
+public class GroupsController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, ITimeProvider timeProvider) : AuthenticatedRequestController(userManager)
+{
+ private const string ManifestFormat = "manifest-v1";
+
+ /// <summary>
+ /// Get the overview of the caller's shared groups and invitations.
+ /// </summary>
+ /// <returns>The overview.</returns>
+ [HttpGet]
+ public async Task<IActionResult> Overview()
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var me = await GetCurrentUserAsync();
+ if (me == null)
+ {
+ return Unauthorized();
+ }
+
+ var memberships = await context.GroupMembers
+ .Where(gm => gm.UserId == me.Id && gm.Group.Type == GroupType.Shared)
+ .Select(gm => new { gm.GroupId, gm.Group.Name, gm.Role })
+ .ToListAsync();
+
+ var response = new GroupOverviewResponse
+ {
+ ReceivedInvitations = await GetReceivedInvitationsAsync(context, me.Id),
+ };
+
+ if (memberships.Count == 0)
+ {
+ return Ok(response);
+ }
+
+ var groupIds = memberships.ConvertAll(m => m.GroupId);
+ var administeredGroupIds = memberships.Where(m => m.Role is GroupRole.Owner or GroupRole.Admin).Select(m => m.GroupId).ToList();
+ var allMembers = await context.GroupMembers
+ .Where(gm => groupIds.Contains(gm.GroupId))
+ .Select(gm => new { gm.GroupId, gm.UserId, gm.Role })
+ .ToListAsync();
+ var manifestByGroup = await context.VaultManifests
+ .Where(m => groupIds.Contains(m.OwnerGroupId))
+ .ToDictionaryAsync(m => m.OwnerGroupId, m => m.ManifestId);
+ var grantHolders = await GrantHelper.GetGrantHoldersByManifestAsync(context, [.. manifestByGroup.Values]);
+
+ var allMemberIds = allMembers.Select(m => m.UserId).Distinct(StringComparer.Ordinal).ToList();
+ var usernames = await context.AliasVaultUsers
+ .Where(u => allMemberIds.Contains(u.Id))
+ .ToDictionaryAsync(u => u.Id, u => u.UserName ?? string.Empty);
+
+ // Open invitations are only shown to admins.
+ var openInvitations = administeredGroupIds.Count > 0 ? await GetOpenInvitationsByGroupAsync(context, administeredGroupIds) : [];
+
+ foreach (var membership in memberships)
+ {
+ var canAdminister = membership.Role is GroupRole.Owner or GroupRole.Admin;
+ var manifestId = manifestByGroup.TryGetValue(membership.GroupId, out var id) ? id : (Guid?)null;
+
+ var group = new GroupInfo
+ {
+ GroupId = membership.GroupId,
+ Name = membership.Name,
+ Role = membership.Role.ToString(),
+ ManifestId = manifestId,
+ Members = [.. allMembers.Where(m => m.GroupId == membership.GroupId).Select(m => new GroupMemberInfo
+ {
+ UserId = m.UserId,
+ Username = usernames.GetValueOrDefault(m.UserId, string.Empty),
+ Role = m.Role.ToString(),
+ })],
+ };
+
+ // Only admins can see the group's open invitations.
+ if (canAdminister)
+ {
+ group.PendingInvitations = openInvitations.TryGetValue(membership.GroupId, out var invitations) ? invitations : [];
+ }
+
+ response.Groups.Add(group);
+ }
+
+ return Ok(response);
+ }
+
+ /// <summary>
+ /// Create the shared group's vault, together with the caller's own grant on it.
+ /// </summary>
+ /// <param name="groupId">The shared group ID.</param>
+ /// <param name="model">The create manifest request.</param>
+ /// <param name="clientHeader">The client header.</param>
+ /// <returns>The created manifest id and its revision.</returns>
+ [HttpPost("{groupId:guid}/manifest")]
+ public async Task<IActionResult> CreateManifest(Guid groupId, [FromBody] CreateSharedManifestRequest model, [FromHeader(Name = "X-AliasVault-Client")] string? clientHeader)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var me = await GetCurrentUserAsync();
+ if (me == null)
+ {
+ return Unauthorized();
+ }
+
+ // The user's copy of the VEK must be encrypted asymmetrically.
+ if (!VaultKeyAlgorithms.TryParse(model.Algorithm, out var algorithm) || !VaultKeyAlgorithms.IsAsymmetric(algorithm))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_ALGORITHM, 400));
+ }
+
+ if (model.ManifestId == Guid.Empty)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.MANIFEST_ID_INVALID, 400));
+ }
+
+ // The manifest ciphertext is base64-encoded but stored as raw bytes.
+ if (!CiphertextHelper.TryDecode(model.ManifestBlob, out var manifestBlob))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_ERROR, 400));
+ }
+
+ if (!await GroupHelper.IsSharedGroupAdminAsync(context, groupId, me.Id))
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.GROUP_NOT_FOUND, 404));
+ }
+
+ // The public key the user's own grant is encrypted for must be one of theirs.
+ var selfPublicKeyId = await context.UserGrantKeys
+ .Where(x => x.UserId == me.Id && x.PublicKey == model.SelfPublicKey)
+ .Select(x => (Guid?)x.Id)
+ .FirstOrDefaultAsync();
+
+ if (selfPublicKeyId is null)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.RECIPIENT_KEY_NOT_FOUND, 404));
+ }
+
+ // A group (currently) holds exactly one vault.
+ if (await context.VaultManifests.AnyAsync(x => x.OwnerGroupId == groupId))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.GROUP_MANIFEST_EXISTS, 400));
+ }
+
+ var manifest = new VaultManifest
+ {
+ ManifestId = model.ManifestId,
+ OwnerGroupId = groupId,
+ Name = model.Name,
+ StorageFormat = ManifestFormat,
+ ManifestBlob = manifestBlob,
+ ManifestCiphertextHash = model.ManifestCiphertextHash,
+ RevisionNumber = 1,
+ FileSize = FileHelper.BytesToKilobytes(manifestBlob.Length),
+ Client = clientHeader,
+ CreatedAt = timeProvider.UtcNow,
+ UpdatedAt = timeProvider.UtcNow,
+ };
+ context.VaultManifests.Add(manifest);
+ context.VaultManifestAccessKeys.Add(GrantHelper.BuildGrant(manifest.ManifestId, me.Id, selfPublicKeyId.Value, model.SelfEncryptedVek, algorithm, timeProvider.UtcNow));
+
+ try
+ {
+ await context.SaveChangesAsync();
+ }
+ catch (DbUpdateException)
+ {
+ // The client-minted manifest id is already taken, which a fresh id makes vanishingly unlikely; the client asks again.
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.MANIFEST_ID_TAKEN, 400));
+ }
+
+ return Ok(new CreateSharedManifestResponse { ManifestId = manifest.ManifestId, RevisionNumber = manifest.RevisionNumber });
+ }
+
+ /// <summary>
+ /// Resolve the account behind a username, together with the public key an invitation to it must be sealed for.
+ /// </summary>
+ /// <param name="groupId">The group to invite into.</param>
+ /// <param name="model">The username to look up.</param>
+ /// <returns>The recipient and the key to seal for.</returns>
+ [HttpPost("{groupId:guid}/invitations/recipient")]
+ public async Task<IActionResult> ResolveInvitationRecipient(Guid groupId, [FromBody] GroupInvitationRecipientRequest model)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var me = await GetCurrentUserAsync();
+ if (me == null)
+ {
+ return Unauthorized();
+ }
+
+ var (invitee, failure) = await ResolveInviteeAsync(context, groupId, me.Id, () => GetUserManager().FindByNameAsync(model.Username.Trim()));
+ if (failure is not null)
+ {
+ return failure;
+ }
+
+ var recipient = (await GrantHelper.GetPrimaryKeysAsync(context, [invitee!.Id])).GetValueOrDefault(invitee.Id);
+ if (recipient is null)
+ {
+ // The account has never published a keypair (which can happen if user is still on sqlite-blob legacy storage format), return error.
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITE_RECIPIENT_NOT_READY, 400));
+ }
+
+ return Ok(new GroupInvitationRecipientResponse { Recipient = recipient });
+ }
+
+ /// <summary>
+ /// Invite an account to join a shared group, handing over the group's vault key sealed for them in the same call.
+ /// </summary>
+ /// <param name="groupId">The group ID.</param>
+ /// <param name="model">The create invitation request.</param>
+ /// <returns>The created invitation id.</returns>
+ [HttpPost("{groupId:guid}/invitations")]
+ public async Task<IActionResult> CreateInvitation(Guid groupId, [FromBody] CreateGroupInvitationRequest model)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var me = await GetCurrentUserAsync();
+ if (me == null)
+ {
+ return Unauthorized();
+ }
+
+ if (!VaultKeyAlgorithms.TryParse(model.Algorithm, out var algorithm) || !VaultKeyAlgorithms.IsAsymmetric(algorithm))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_ALGORITHM, 400));
+ }
+
+ var (invitee, failure) = await ResolveInviteeAsync(context, groupId, me.Id, () => GetUserManager().FindByIdAsync(model.UserId));
+ if (failure is not null)
+ {
+ return failure;
+ }
+
+ // The sealed key and the invitation have to be about the same person.
+ if (!string.Equals(model.Grant.RecipientUserId, invitee!.Id, StringComparison.Ordinal))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.RECIPIENT_KEY_NOT_FOUND, 400));
+ }
+
+ // The key it was sealed for must really be theirs.
+ if (!await context.UserGrantKeys.AnyAsync(k => k.Id == model.Grant.RecipientPublicKeyId && k.UserId == invitee.Id))
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.RECIPIENT_KEY_NOT_FOUND, 404));
+ }
+
+ var manifestId = await context.VaultManifests.Where(m => m.OwnerGroupId == groupId).Select(m => (Guid?)m.ManifestId).FirstOrDefaultAsync();
+ if (manifestId is null)
+ {
+ // Nothing to seal, so there is nothing an accept could hand over.
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.GROUP_HAS_NO_VAULT, 400));
+ }
+
+ var invitation = new GroupInvitation
+ {
+ Id = Guid.NewGuid(),
+ GroupId = groupId,
+ InviterUserId = me.Id,
+ InviteeUserId = invitee.Id,
+ Role = GroupRole.Member,
+ State = GroupInvitationState.Pending,
+ VaultManifestId = manifestId,
+ EncryptedVek = model.Grant.EncryptedVek,
+ UserGrantKeyId = model.Grant.RecipientPublicKeyId,
+ Algorithm = algorithm,
+ CreatedAt = timeProvider.UtcNow,
+ UpdatedAt = timeProvider.UtcNow,
+ };
+ context.GroupInvitations.Add(invitation);
+
+ try
+ {
+ await context.SaveChangesAsync();
+ }
+ catch (DbUpdateException)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITATION_ALREADY_EXISTS, 400));
+ }
+
+ return Ok(new CreateGroupInvitationResponse { InvitationId = invitation.Id });
+ }
+
+ /// <summary>
+ /// Accept an invitation addressed to the current user.
+ /// </summary>
+ /// <param name="invitationId">The invitation ID.</param>
+ /// <returns>Ok on success.</returns>
+ [HttpPost("invitations/{invitationId:guid}/accept")]
+ public async Task<IActionResult> AcceptInvitation(Guid invitationId)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var me = await GetCurrentUserAsync();
+ if (me == null)
+ {
+ return Unauthorized();
+ }
+
+ var invitation = await context.GroupInvitations.FirstOrDefaultAsync(i => i.Id == invitationId && i.InviteeUserId == me.Id && i.State == GroupInvitationState.Pending);
+ if (invitation is null)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITATION_NOT_FOUND, 404));
+ }
+
+ if (!await PromoteSealedGrantAsync(context, invitation, me.Id))
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITATION_NOT_FOUND, 404));
+ }
+
+ invitation.State = GroupInvitationState.Accepted;
+ invitation.RespondedAt = timeProvider.UtcNow;
+ invitation.UpdatedAt = timeProvider.UtcNow;
+
+ // Idempotent in the one way that matters: a membership added in the meantime (by an admin elsewhere) is kept.
+ if (!await context.GroupMembers.AnyAsync(gm => gm.GroupId == invitation.GroupId && gm.UserId == me.Id))
+ {
+ context.GroupMembers.Add(new GroupMember
+ {
+ Id = Guid.NewGuid(),
+ GroupId = invitation.GroupId,
+ UserId = me.Id,
+ Role = invitation.Role,
+ CreatedAt = timeProvider.UtcNow,
+ UpdatedAt = timeProvider.UtcNow,
+ });
+ }
+
+ // The sealed copy has become the grant, so it stops being a second copy of the key lying around.
+ invitation.EncryptedVek = null;
+ invitation.UserGrantKeyId = null;
+
+ await context.SaveChangesAsync();
+ return Ok();
+ }
+
+ /// <summary>
+ /// Decline an invitation addressed to the current user.
+ /// </summary>
+ /// <param name="invitationId">The invitation to decline.</param>
+ /// <returns>Ok on success.</returns>
+ [HttpPost("invitations/{invitationId:guid}/decline")]
+ public async Task<IActionResult> DeclineInvitation(Guid invitationId)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var me = await GetCurrentUserAsync();
+ if (me == null)
+ {
+ return Unauthorized();
+ }
+
+ var invitation = await context.GroupInvitations.FirstOrDefaultAsync(i => i.Id == invitationId && i.InviteeUserId == me.Id && i.State == GroupInvitationState.Pending);
+ if (invitation is null)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITATION_NOT_FOUND, 404));
+ }
+
+ CloseInvitation(invitation, GroupInvitationState.Declined);
+ await context.SaveChangesAsync();
+
+ return Ok();
+ }
+
+ /// <summary>
+ /// Withdraw an invitation the current user's group sent but that has not been answered yet.
+ /// </summary>
+ /// <param name="invitationId">The invitation ID.</param>
+ /// <returns>Ok on success.</returns>
+ [HttpDelete("invitations/{invitationId:guid}")]
+ public async Task<IActionResult> WithdrawInvitation(Guid invitationId)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var me = await GetCurrentUserAsync();
+ if (me == null)
+ {
+ return Unauthorized();
+ }
+
+ var invitation = await context.GroupInvitations.FirstOrDefaultAsync(i => i.Id == invitationId && i.State == GroupInvitationState.Pending);
+ if (invitation is null || !await GroupHelper.IsGroupAdminAsync(context, invitation.GroupId, me.Id))
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITATION_NOT_FOUND, 404));
+ }
+
+ CloseInvitation(invitation, GroupInvitationState.Revoked);
+ await context.SaveChangesAsync();
+
+ return Ok();
+ }
+
+ /// <summary>
+ /// Remove a member from a shared group.
+ /// </summary>
+ /// <param name="groupId">The group ID.</param>
+ /// <param name="userId">The user ID to remove.</param>
+ /// <returns>Ok on success.</returns>
+ [HttpDelete("{groupId:guid}/members/{userId}")]
+ public async Task<IActionResult> RemoveMember(Guid groupId, string userId)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var me = await GetCurrentUserAsync();
+ if (me == null)
+ {
+ return Unauthorized();
+ }
+
+ var membership = await context.GroupMembers.FirstOrDefaultAsync(gm => gm.GroupId == groupId && gm.UserId == userId && gm.Group.Type == GroupType.Shared);
+ if (membership is null)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.GROUP_NOT_FOUND, 404));
+ }
+
+ var isSelf = string.Equals(userId, me.Id, StringComparison.Ordinal);
+ if (!isSelf && !await GroupHelper.IsGroupAdminAsync(context, groupId, me.Id))
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.GROUP_NOT_FOUND, 404));
+ }
+
+ // The owner is the group's anchor: losing them would leave a group nobody can administer or delete.
+ if (membership.Role == GroupRole.Owner)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.CANNOT_REMOVE_GROUP_OWNER, 400));
+ }
+
+ // Start a transaction to ensure all operations are atomic.
+ await using var transaction = await context.Database.BeginTransactionAsync();
+ context.GroupMembers.Remove(membership);
+
+ // Sanity check: revoke any open invitations of this user for this group.
+ foreach (var invitation in await context.GroupInvitations.Where(i => i.GroupId == groupId && i.InviteeUserId == userId && i.State == GroupInvitationState.Pending).ToListAsync())
+ {
+ CloseInvitation(invitation, GroupInvitationState.Revoked);
+ }
+
+ var manifestId = await context.VaultManifests.Where(m => m.OwnerGroupId == groupId).Select(m => (Guid?)m.ManifestId).FirstOrDefaultAsync();
+ if (manifestId is not null && await GrantHelper.RevokeAccessAsync(context, manifestId.Value, userId))
+ {
+ await ClientActionHelper.EnqueueForGroupAsync(context, ClientActionType.RotateManifestDeliveryKey, groupId, manifestId, timeProvider.UtcNow);
+ }
+
+ await context.SaveChangesAsync();
+ await transaction.CommitAsync();
+
+ return Ok();
+ }
+
+ /// <summary>
+ /// The open invitations of each group, for the admins who may withdraw them.
+ /// </summary>
+ /// <param name="context">Database context.</param>
+ /// <param name="groupIds">The groups to list invitations of.</param>
+ /// <returns>Group id to its open invitations.</returns>
+ private static async Task<Dictionary<Guid, List<SentGroupInvitation>>> GetOpenInvitationsByGroupAsync(AliasServerDbContext context, List<Guid> groupIds)
+ {
+ return (await context.GroupInvitations
+ .Where(i => groupIds.Contains(i.GroupId) && i.State == GroupInvitationState.Pending)
+ .Select(i => new { i.GroupId, Invitation = new SentGroupInvitation { Id = i.Id, InviteeUsername = i.Invitee.UserName ?? string.Empty, CreatedAt = i.CreatedAt } })
+ .ToListAsync())
+ .GroupBy(i => i.GroupId)
+ .ToDictionary(g => g.Key, g => g.Select(i => i.Invitation).ToList());
+ }
+
+ /// <summary>
+ /// The open invitations addressed to one user.
+ /// </summary>
+ /// <param name="context">Database context.</param>
+ /// <param name="userId">The invitee.</param>
+ /// <returns>Their open invitations.</returns>
+ private static async Task<List<ReceivedGroupInvitation>> GetReceivedInvitationsAsync(AliasServerDbContext context, string userId)
+ {
+ return await context.GroupInvitations
+ .Where(i => i.InviteeUserId == userId && i.State == GroupInvitationState.Pending && i.Group.Type == GroupType.Shared)
+ .OrderBy(i => i.CreatedAt)
+ .Select(i => new ReceivedGroupInvitation
+ {
+ Id = i.Id,
+ GroupId = i.GroupId,
+ GroupName = i.Group.Name,
+ InviterUsername = i.Inviter.UserName ?? string.Empty,
+ CreatedAt = i.CreatedAt,
+ })
+ .ToListAsync();
+ }
+
+ /// <summary>
+ /// Close an invitation, dropping the vault key sealed inside it.
+ /// </summary>
+ /// <param name="invitation">The invitation to close.</param>
+ /// <param name="state">The state it ends in.</param>
+ private void CloseInvitation(GroupInvitation invitation, GroupInvitationState state)
+ {
+ invitation.State = state;
+ invitation.EncryptedVek = null;
+ invitation.UserGrantKeyId = null;
+ invitation.RespondedAt = timeProvider.UtcNow;
+ invitation.UpdatedAt = timeProvider.UtcNow;
+ }
+
+ /// <summary>
+ /// Turn the vault key sealed into an invitation into the accepting member's grant on the group's vault.
+ /// </summary>
+ /// <param name="context">The database context.</param>
+ /// <param name="invitation">The invitation being accepted.</param>
+ /// <param name="userId">The accepting user.</param>
+ /// <returns>Whether the accepting user ends up holding a grant on the group's vault.</returns>
+ private async Task<bool> PromoteSealedGrantAsync(AliasServerDbContext context, GroupInvitation invitation, string userId)
+ {
+ if (invitation.EncryptedVek is null || invitation.UserGrantKeyId is null || invitation.VaultManifestId is null)
+ {
+ return false;
+ }
+
+ var currentManifestId = await context.VaultManifests.Where(m => m.OwnerGroupId == invitation.GroupId).Select(m => (Guid?)m.ManifestId).FirstOrDefaultAsync();
+ if (currentManifestId != invitation.VaultManifestId)
+ {
+ return false;
+ }
+
+ if (await context.VaultManifestAccessKeys.AnyAsync(k => k.VaultManifestId == currentManifestId.Value && k.UserId == userId && k.Type == ManifestKeyType.GrantKey))
+ {
+ return true;
+ }
+
+ context.VaultManifestAccessKeys.Add(GrantHelper.BuildGrant(currentManifestId.Value, userId, invitation.UserGrantKeyId.Value, invitation.EncryptedVek, invitation.Algorithm, timeProvider.UtcNow));
+
+ return true;
+ }
+
+ /// <summary>
+ /// Resolve who an invitation is for and whether it may be sent at all.
+ /// </summary>
+ /// <param name="context">The database context.</param>
+ /// <param name="groupId">The group ID.</param>
+ /// <param name="callerId">The inviting user.</param>
+ /// <param name="findInvitee">How to look the invitee up.</param>
+ /// <returns>The invitee, or the failure to return instead.</returns>
+ private async Task<(AliasVaultUser? Invitee, IActionResult? Failure)> ResolveInviteeAsync(AliasServerDbContext context, Guid groupId, string callerId, Func<Task<AliasVaultUser?>> findInvitee)
+ {
+ var group = await context.Groups.FirstOrDefaultAsync(g => g.Id == groupId && g.Type == GroupType.Shared);
+ if (group is null || !await GroupHelper.IsGroupAdminAsync(context, groupId, callerId))
+ {
+ return (null, NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.GROUP_NOT_FOUND, 404)));
+ }
+
+ var invitee = await findInvitee();
+ if (invitee is null || invitee.Blocked)
+ {
+ return (null, NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITE_RECIPIENT_NOT_FOUND, 404)));
+ }
+
+ // Sanity check: the invitee must not already be a member of the group.
+ if (await context.GroupMembers.AnyAsync(gm => gm.GroupId == groupId && gm.UserId == invitee.Id))
+ {
+ return (null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ALREADY_GROUP_MEMBER, 400)));
+ }
+
+ // Sanity check: the invitee must not already have an open invitation for this group.
+ if (await context.GroupInvitations.AnyAsync(i => i.GroupId == groupId && i.InviteeUserId == invitee.Id && i.State == GroupInvitationState.Pending))
+ {
+ return (null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVITATION_ALREADY_EXISTS, 400)));
+ }
+
+ return (invitee, null);
+ }
+}
diff --git a/apps/server/AliasVault.Api/Controllers/V2/SharingController.cs b/apps/server/AliasVault.Api/Controllers/V2/SharingController.cs
deleted file mode 100644
index 736baa2c6..000000000
--- a/apps/server/AliasVault.Api/Controllers/V2/SharingController.cs
+++ /dev/null
@@ -1,363 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="SharingController.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.Auth;
-using AliasVault.Shared.Models.Enums;
-using AliasVault.Shared.Models.WebApi;
-using AliasVault.Shared.Models.WebApi.V2.Sharing;
-using AliasVault.Shared.Providers.Time;
-using Asp.Versioning;
-using Microsoft.AspNetCore.Identity;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.EntityFrameworkCore;
-
-/// <summary>
-/// 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>
-/// <param name="dbContextFactory">DbContext factory.</param>
-/// <param name="userManager">UserManager.</param>
-/// <param name="timeProvider">Time provider.</param>
-[ApiVersion("2")]
-public class SharingController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, ITimeProvider timeProvider) : AuthenticatedRequestController(userManager)
-{
- private const string ManifestFormat = "manifest-v1";
-
- /// <summary>
- /// Look up a recipient by username and return their primary public key, which the caller uses to encrypt a shared
- /// manifest's VEK before granting access.
- /// </summary>
- /// <param name="username">The recipient's username.</param>
- /// <returns>The recipient's id and primary public key.</returns>
- [HttpGet("recipient")]
- public async Task<IActionResult> GetRecipient([FromQuery] string username)
- {
- await using var context = await dbContextFactory.CreateDbContextAsync();
- var me = await GetCurrentUserAsync();
- if (me == null)
- {
- return Unauthorized();
- }
-
- var recipient = await GetUserManager().FindByNameAsync(UsernameHelper.NormalizeUsername(username ?? string.Empty));
- if (recipient == null)
- {
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 404));
- }
-
- // The recipient's grant public key.
- var key = await context.UserGrantKeys.FirstOrDefaultAsync(x => x.UserId == recipient.Id && x.IsPrimary);
- if (key is null)
- {
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.RECIPIENT_KEY_NOT_FOUND, 404));
- }
-
- return Ok(new RecipientLookupResponse { UserId = recipient.Id, PublicKeyId = key.Id, PublicKey = key.PublicKey });
- }
-
- /// <summary>
- /// Create a new shared manifest owned by the caller, plus the caller's own grant (the manifest VEK encrypted with their grant public key).
- /// </summary>
- /// <param name="model">The create request.</param>
- /// <param name="clientHeader">The client identifier header.</param>
- /// <returns>The created manifest id.</returns>
- [HttpPost("manifests")]
- public async Task<IActionResult> CreateManifest([FromBody] CreateSharedManifestRequest model, [FromHeader(Name = "X-AliasVault-Client")] string? clientHeader)
- {
- await using var context = await dbContextFactory.CreateDbContextAsync();
- var me = await GetCurrentUserAsync();
- if (me == null)
- {
- return Unauthorized();
- }
-
- // The owner's self-grant must be encrypted asymmetrically for their own public key.
- if (!VaultKeyAlgorithms.TryParse(model.Algorithm, out var selfAlgorithm) || !VaultKeyAlgorithms.IsAsymmetric(selfAlgorithm))
- {
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_ALGORITHM, 400));
- }
-
- // The public key encrypted for must be an account keypair the caller owns.
- var keyOwnedByMe = await context.UserGrantKeys.AnyAsync(x => x.Id == model.SelfPublicKeyId && x.UserId == me.Id);
- if (!keyOwnedByMe)
- {
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.RECIPIENT_KEY_NOT_FOUND, 404));
- }
-
- if (model.ManifestId == Guid.Empty)
- {
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.MANIFEST_ID_INVALID, 400));
- }
-
- // Ciphertext travels base64-encoded but is stored as raw bytes.
- if (!CiphertextHelper.TryDecode(model.ManifestBlob, out var manifestBlob))
- {
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_ERROR, 400));
- }
-
- var ownerGroupId = await GroupHelper.ResolveShareTargetGroupIdAsync(context, me.Id, model.GroupId);
- if (ownerGroupId is null)
- {
- 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,
- OwnerGroupId = ownerGroupId.Value,
- Name = model.Name,
- StorageFormat = ManifestFormat,
- ManifestBlob = manifestBlob,
- ManifestCiphertextHash = model.ManifestCiphertextHash,
- RevisionNumber = 1,
- FileSize = FileHelper.BytesToKilobytes(manifestBlob.Length),
- Client = clientHeader,
- CreatedAt = timeProvider.UtcNow,
- UpdatedAt = timeProvider.UtcNow,
- };
- context.VaultManifests.Add(manifest);
- context.VaultManifestAccessKeys.Add(new VaultManifestAccessKey
- {
- Id = Guid.NewGuid(),
- UserId = me.Id,
- VaultManifestId = manifest.ManifestId,
- Type = ManifestKeyType.GrantKey,
- Algorithm = selfAlgorithm,
- EncryptedVek = model.SelfEncryptedVek,
- UserGrantKeyId = model.SelfPublicKeyId,
- CreatedAt = timeProvider.UtcNow,
- UpdatedAt = timeProvider.UtcNow,
- });
-
- 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 });
- }
-
- /// <summary>
- /// Grant a recipient access to a shared manifest the caller owns, by persisting the manifest VEK encrypted with the
- /// recipient's grant public key.
- /// </summary>
- /// <param name="model">The grant request.</param>
- /// <returns>Ok on success.</returns>
- [HttpPost("grant")]
- public async Task<IActionResult> Grant([FromBody] GrantAccessRequest model)
- {
- await using var context = await dbContextFactory.CreateDbContextAsync();
- var me = await GetCurrentUserAsync();
- if (me == null)
- {
- return Unauthorized();
- }
-
- // A shared manifest's VEK must be encrypted for the recipient asymmetrically.
- if (!VaultKeyAlgorithms.TryParse(model.Algorithm, out var grantAlgorithm) || !VaultKeyAlgorithms.IsAsymmetric(grantAlgorithm))
- {
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_ALGORITHM, 400));
- }
-
- // 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));
- }
-
- // The referenced public key must exist and be an account keypair of the named recipient (guards against
- // encrypting for the wrong key, or for a manifest delivery key every member of that manifest could decrypt).
- var keyOwnedByRecipient = await context.UserGrantKeys.AnyAsync(x => x.Id == model.RecipientPublicKeyId && x.UserId == model.RecipientUserId);
- if (!keyOwnedByRecipient)
- {
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.RECIPIENT_KEY_NOT_FOUND, 404));
- }
-
- var alreadyGranted = await context.VaultManifestAccessKeys.AnyAsync(x => x.UserId == model.RecipientUserId && x.VaultManifestId == model.ManifestId && x.Type == ManifestKeyType.GrantKey);
- if (alreadyGranted)
- {
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARE_ALREADY_EXISTS, 400));
- }
-
- // Receiving a manifest implies belonging to the group that owns it, so keep membership in step with the
- // grant.
- await GroupHelper.EnsureMembershipAsync(context, manifest.OwnerGroupId, model.RecipientUserId, timeProvider.UtcNow);
-
- context.VaultManifestAccessKeys.Add(new VaultManifestAccessKey
- {
- Id = Guid.NewGuid(),
- UserId = model.RecipientUserId,
- VaultManifestId = model.ManifestId,
- Type = ManifestKeyType.GrantKey,
- Algorithm = grantAlgorithm,
- EncryptedVek = model.EncryptedVek,
- UserGrantKeyId = model.RecipientPublicKeyId,
- CreatedAt = timeProvider.UtcNow,
- UpdatedAt = timeProvider.UtcNow,
- });
- await context.SaveChangesAsync();
-
- return Ok();
- }
-
- /// <summary>
- /// Revoke a recipient's access to a shared manifest the caller owns. Deleting the grant stops the recipient from
- /// fetching a usable encrypted VEK. TODO: implement enforced VEK rotation policy on every shared manifest revocation.
- /// </summary>
- /// <param name="model">The revoke request.</param>
- /// <returns>Ok on success.</returns>
- [HttpPost("revoke")]
- public async Task<IActionResult> Revoke([FromBody] RevokeAccessRequest model)
- {
- await using var context = await dbContextFactory.CreateDbContextAsync();
- var me = await GetCurrentUserAsync();
- if (me == null)
- {
- return Unauthorized();
- }
-
- if (!await GroupHelper.CanAdministerManifestAsync(context, model.ManifestId, me.Id))
- {
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));
- }
-
- var grant = await context.VaultManifestAccessKeys.FirstOrDefaultAsync(x => x.UserId == model.RecipientUserId && x.VaultManifestId == model.ManifestId && x.Type == ManifestKeyType.GrantKey);
- if (grant == null)
- {
- return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARE_NOT_FOUND, 404));
- }
-
- context.VaultManifestAccessKeys.Remove(grant);
-
- // Remove any recipient's personal claim that also exists on the shared manifest.
- // TODO: verify design that this is correct in terms of sharing and revocation logic.
- var recipientPersonalGroupId = await context.AliasVaultUsers.Where(u => u.Id == model.RecipientUserId).Select(u => u.PersonalGroupId).FirstOrDefaultAsync();
- await context.EmailClaimLinks
- .Where(l => l.VaultManifest.OwnerGroupId == recipientPersonalGroupId && context.EmailClaimLinks.Any(s => s.EmailClaimId == l.EmailClaimId && s.VaultManifestId == model.ManifestId))
- .ExecuteUpdateAsync(s => s.SetProperty(l => l.State, EmailClaimLinkState.Removed));
-
- await context.SaveChangesAsync();
-
- return Ok();
- }
-
- /// <summary>
- /// List who has access to a shared manifest: the owner of the group that owns it, plus every recipient holding a grant.
- /// </summary>
- /// <param name="manifestId">The shared manifest id.</param>
- /// <returns>The member list.</returns>
- [HttpGet("manifests/{manifestId:guid}/members")]
- public async Task<IActionResult> Members(Guid manifestId)
- {
- await using var context = await dbContextFactory.CreateDbContextAsync();
- var me = await GetCurrentUserAsync();
- if (me == null)
- {
- return Unauthorized();
- }
-
- if (!await GroupHelper.CanAdministerManifestAsync(context, manifestId, me.Id))
- {
- return 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.
- */
- 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)
- .FirstOrDefaultAsync();
-
- var grants = (await context.VaultManifestAccessKeys
- .Where(x => x.VaultManifestId == manifestId && x.Type == ManifestKeyType.GrantKey)
- .ToListAsync())
- .Where(x => x.UserId != ownerUserId)
- .ToList();
-
- var lookupIds = grants.Select(g => g.UserId).ToList();
- if (ownerUserId is not null)
- {
- lookupIds.Add(ownerUserId);
- }
-
- var usernamesById = await context.AliasVaultUsers
- .Where(u => lookupIds.Contains(u.Id))
- .ToDictionaryAsync(u => u.Id, u => u.UserName);
-
- var response = new ShareMembersResponse();
- 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
- {
- UserId = g.UserId,
- Username = usernamesById.GetValueOrDefault(g.UserId),
- IsOwner = false,
- Algorithm = VaultKeyAlgorithms.ToToken(g.Algorithm),
- GrantedAt = g.CreatedAt,
- });
- }
-
- return 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/StatusController.cs b/apps/server/AliasVault.Api/Controllers/V2/StatusController.cs
index 9cd6d2cc9..948fb16d0 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/StatusController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/StatusController.cs
@@ -85,6 +85,7 @@ public class StatusController(IAliasServerDbContextFactory dbContextFactory, Use
ManifestRevisions = manifestRevisions,
PersonalManifestId = personalManifestId,
BucketRevisions = bucketRevisions,
+ PendingActions = await ClientActionHelper.GetPendingActionsAsync(context, user.Id),
});
}
}
diff --git a/apps/server/AliasVault.Api/Helpers/GrantHelper.cs b/apps/server/AliasVault.Api/Helpers/GrantHelper.cs
new file mode 100644
index 000000000..97ff39c7d
--- /dev/null
+++ b/apps/server/AliasVault.Api/Helpers/GrantHelper.cs
@@ -0,0 +1,111 @@
+//-----------------------------------------------------------------------
+// <copyright file="GrantHelper.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.Helpers;
+
+using AliasServerDb;
+using AliasVault.Shared.Models.Enums;
+using AliasVault.Shared.Models.WebApi.V2.Groups;
+using Microsoft.EntityFrameworkCore;
+
+/// <summary>
+/// Grant helper for shared manifests.
+/// </summary>
+public static class GrantHelper
+{
+ /// <summary>
+ /// Build one recipient's grant on a manifest.
+ /// </summary>
+ /// <param name="manifestId">The manifest ID.</param>
+ /// <param name="userId">The recipient user ID.</param>
+ /// <param name="publicKeyId">The recipient public key ID.</param>
+ /// <param name="encryptedVek">The encrypted VEK.</param>
+ /// <param name="algorithm">The algorithm it was encrypted with.</param>
+ /// <param name="now">Current time.</param>
+ /// <returns>The unpersisted grant.</returns>
+ public static VaultManifestAccessKey BuildGrant(Guid manifestId, string userId, Guid publicKeyId, string encryptedVek, VaultKeyAlgorithm algorithm, DateTime now)
+ {
+ return new VaultManifestAccessKey
+ {
+ Id = Guid.NewGuid(),
+ UserId = userId,
+ VaultManifestId = manifestId,
+ Type = ManifestKeyType.GrantKey,
+ Algorithm = algorithm,
+ EncryptedVek = encryptedVek,
+ UserGrantKeyId = publicKeyId,
+ CreatedAt = now,
+ UpdatedAt = now,
+ };
+ }
+
+ /// <summary>
+ /// Get the users holding a grant on each of the given manifests.
+ /// </summary>
+ /// <param name="context">The database context.</param>
+ /// <param name="manifestIds">The manifests to look at.</param>
+ /// <returns>Manifest id to the user ids holding a grant on it.</returns>
+ public static async Task<Dictionary<Guid, HashSet<string>>> GetGrantHoldersByManifestAsync(AliasServerDbContext context, List<Guid> manifestIds)
+ {
+ return (await context.VaultManifestAccessKeys
+ .Where(k => manifestIds.Contains(k.VaultManifestId) && k.Type == ManifestKeyType.GrantKey)
+ .Select(k => new { k.VaultManifestId, k.UserId })
+ .ToListAsync())
+ .GroupBy(k => k.VaultManifestId)
+ .ToDictionary(g => g.Key, g => g.Select(k => k.UserId).ToHashSet(StringComparer.Ordinal));
+ }
+
+ /// <summary>
+ /// Get the primary public key of each given user.
+ /// </summary>
+ /// <param name="context">The database context.</param>
+ /// <param name="userIds">The user IDs to look up.</param>
+ /// <returns>User ID to their grant recipient details.</returns>
+ public static async Task<Dictionary<string, GrantRecipient>> GetPrimaryKeysAsync(AliasServerDbContext context, IEnumerable<string> userIds)
+ {
+ var ids = userIds.Distinct(StringComparer.Ordinal).ToList();
+ if (ids.Count == 0)
+ {
+ return [];
+ }
+
+ return await context.UserGrantKeys
+ .Where(k => ids.Contains(k.UserId) && k.IsPrimary)
+ .ToDictionaryAsync(k => k.UserId, k => new GrantRecipient { UserId = k.UserId, PublicKeyId = k.Id, PublicKey = k.PublicKey });
+ }
+
+ /// <summary>
+ /// Take a user's access to a shared manifest away.
+ /// </summary>
+ /// <param name="context">Database context.</param>
+ /// <param name="manifestId">The shared manifest.</param>
+ /// <param name="userId">The user losing access.</param>
+ /// <returns>True when the user actually held a grant, i.e. when something was revoked.</returns>
+ public static async Task<bool> RevokeAccessAsync(AliasServerDbContext context, Guid manifestId, string userId)
+ {
+ var grants = await context.VaultManifestAccessKeys
+ .Where(k => k.VaultManifestId == manifestId && k.UserId == userId && k.Type == ManifestKeyType.GrantKey)
+ .ToListAsync();
+
+ if (grants.Count == 0)
+ {
+ return false;
+ }
+
+ context.VaultManifestAccessKeys.RemoveRange(grants);
+
+ var personalGroupId = await GroupHelper.GetPersonalGroupIdAsync(context, userId);
+ if (personalGroupId is not null)
+ {
+ await context.EmailClaimLinks
+ .Where(l => l.VaultManifest.OwnerGroupId == personalGroupId.Value && context.EmailClaimLinks.Any(s => s.EmailClaimId == l.EmailClaimId && s.VaultManifestId == manifestId))
+ .ExecuteUpdateAsync(s => s.SetProperty(l => l.State, EmailClaimLinkState.Removed));
+ }
+
+ return true;
+ }
+}
diff --git a/apps/server/AliasVault.Api/Helpers/GroupHelper.cs b/apps/server/AliasVault.Api/Helpers/GroupHelper.cs
index 3e34e4ae1..8fca269ce 100644
--- a/apps/server/AliasVault.Api/Helpers/GroupHelper.cs
+++ b/apps/server/AliasVault.Api/Helpers/GroupHelper.cs
@@ -48,23 +48,17 @@ 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. 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"/>).
+ /// Check whether the caller may administer a <see cref="GroupType.Shared"/> group.
/// </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 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)
+ /// <param name="groupId">The shared group ID.</param>
+ /// <param name="userId">The user ID.</param>
+ /// <returns>False when the group does not exist, is not a shared group, or the caller may not administer it.</returns>
+ public static async Task<bool> IsSharedGroupAdminAsync(AliasServerDbContext context, Guid groupId, string userId)
{
- var resolved = await context.Groups.AnyAsync(g => g.Id == groupId
+ return 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>
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/CreateGroupInvitationRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/CreateGroupInvitationRequest.cs
index 29d544074..38c5c21e4 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/CreateGroupInvitationRequest.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/CreateGroupInvitationRequest.cs
@@ -7,8 +7,6 @@
namespace AliasVault.Shared.Models.WebApi.V2.Groups;
-using AliasVault.Shared.Models.WebApi.V2.Sharing;
-
/// <summary>
/// Request for POST /v2/Groups/{groupId}/invitations: invite an account to join the group, handing it the group's
/// vault key sealed for that account in the same call.
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Sharing/CreateSharedManifestRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/CreateSharedManifestRequest.cs
similarity index 74%
rename from apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Sharing/CreateSharedManifestRequest.cs
rename to apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/CreateSharedManifestRequest.cs
index a5c5cb330..b40a166c3 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Sharing/CreateSharedManifestRequest.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/CreateSharedManifestRequest.cs
@@ -5,10 +5,10 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace AliasVault.Shared.Models.WebApi.V2.Sharing;
+namespace AliasVault.Shared.Models.WebApi.V2.Groups;
/// <summary>
-/// Request for POST /v2/Sharing/manifests. Creates a new shared (non-personal) manifest filed under a group.
+/// Request for POST /v2/Groups/{groupId}/manifest.
/// </summary>
public class CreateSharedManifestRequest
{
@@ -18,22 +18,17 @@ public class CreateSharedManifestRequest
/// <summary>Gets or sets the plaintext display name of the manifest.</summary>
public required string Name { get; set; }
- /// <summary>
- /// Gets or sets the shared group to file this manifest under.
- /// </summary>
- public required Guid GroupId { get; set; }
-
/// <summary>Gets or sets the encrypted manifest blob (AES-GCM ciphertext under the manifest VEK, base64).</summary>
public required string ManifestBlob { get; set; }
/// <summary>Gets or sets the SHA-256 (hex) of the manifest ciphertext, for storage-layer integrity verification.</summary>
public string? ManifestCiphertextHash { get; set; }
- /// <summary>Gets or sets the manifest VEK encrypted with the caller's own public key (base64), decryptable only by the caller.</summary>
+ /// <summary>Gets or sets the manifest VEK encrypted with the user's own public key (base64), decryptable only by the user.</summary>
public required string SelfEncryptedVek { get; set; }
/// <summary>
- /// Gets or sets the caller's own account public key (JWK) the <see cref="SelfEncryptedVek"/> was encrypted with.
+ /// Gets or sets the user's own account public key (JWK) the <see cref="SelfEncryptedVek"/> was encrypted with.
/// </summary>
public required string SelfPublicKey { get; set; }
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Sharing/CreateSharedManifestResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/CreateSharedManifestResponse.cs
similarity index 83%
rename from apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Sharing/CreateSharedManifestResponse.cs
rename to apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/CreateSharedManifestResponse.cs
index 8da9540bd..fb77b220e 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Sharing/CreateSharedManifestResponse.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/CreateSharedManifestResponse.cs
@@ -5,10 +5,10 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace AliasVault.Shared.Models.WebApi.V2.Sharing;
+namespace AliasVault.Shared.Models.WebApi.V2.Groups;
/// <summary>
-/// Response for POST /v2/Sharing/manifests. Identifies the newly created shared manifest.
+/// Response for POST /v2/Groups/{groupId}/manifest. Identifies the newly created shared manifest.
/// </summary>
public class CreateSharedManifestResponse
{
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Sharing/GrantRecipient.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/GrantRecipient.cs
similarity index 90%
rename from apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Sharing/GrantRecipient.cs
rename to apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/GrantRecipient.cs
index 53d75e931..c2100cfba 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Sharing/GrantRecipient.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/GrantRecipient.cs
@@ -5,7 +5,7 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace AliasVault.Shared.Models.WebApi.V2.Sharing;
+namespace AliasVault.Shared.Models.WebApi.V2.Groups;
/// <summary>
/// A user a shared manifest's VEK can be encrypted for, with the public key to encrypt it with.
@@ -15,7 +15,7 @@ public class GrantRecipient
/// <summary>Gets or sets the user id.</summary>
public required string UserId { get; set; }
- /// <summary>Gets or sets the id of the user's primary public key, echoed back on the grant.</summary>
+ /// <summary>Gets or sets the id of the user's primary public key.</summary>
public required Guid PublicKeyId { get; set; }
/// <summary>Gets or sets the public key itself (JWK).</summary>
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/GroupInvitationRecipientResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/GroupInvitationRecipientResponse.cs
index b0222bd1f..aabddab0f 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/GroupInvitationRecipientResponse.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/GroupInvitationRecipientResponse.cs
@@ -7,8 +7,6 @@
namespace AliasVault.Shared.Models.WebApi.V2.Groups;
-using AliasVault.Shared.Models.WebApi.V2.Sharing;
-
/// <summary>
/// Response for POST /v2/Groups/{groupId}/invitations/recipient: the account behind a username together with the
/// public key an invitation to it has to be sealed for.
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Sharing/ManifestGrant.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/ManifestGrant.cs
similarity index 95%
rename from apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Sharing/ManifestGrant.cs
rename to apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/ManifestGrant.cs
index 859c76fa4..f7620c039 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Sharing/ManifestGrant.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/ManifestGrant.cs
@@ -5,7 +5,7 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace AliasVault.Shared.Models.WebApi.V2.Sharing;
+namespace AliasVault.Shared.Models.WebApi.V2.Groups;
/// <summary>
/// One recipient's access to a shared manifest: the manifest's VEK encrypted with a public key of theirs.