Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update VaultBlobReference owner to be scoped to manifest instead of user (#2159)
Leendert de Borstcd0ac187c7ad
diff --git a/apps/server/AliasVault.Admin/Main/Pages/Users/View/Index.razor b/apps/server/AliasVault.Admin/Main/Pages/Users/View/Index.razorindex ada5b41b5..1a053976d 100644--- a/apps/server/AliasVault.Admin/Main/Pages/Users/View/Index.razor+++ b/apps/server/AliasVault.Admin/Main/Pages/Users/View/Index.razor@@ -397,7 +397,7 @@ else.ToListAsync();// Load the storage breakdown of the user's personal vault: manifest and bucket revisions plus blob usage.- StorageOverview = await VaultStorageQueries.GetPersonalVaultStorageAsync(dbContext, User.Id, User.PersonalGroupId);+ StorageOverview = await VaultStorageQueries.GetPersonalVaultStorageAsync(dbContext, User.PersonalGroupId);// Whether the user is on the key model where the vault manifest no longer carries the login credentials.HasManifestAccessKeys = await dbContext.VaultManifestAccessKeys.AnyAsync(x => x.UserId == User.Id);diff --git a/apps/server/AliasVault.Admin/Services/VaultStorageQueries.cs b/apps/server/AliasVault.Admin/Services/VaultStorageQueries.csindex 0cba47a1e..b1d7d33aa 100644--- a/apps/server/AliasVault.Admin/Services/VaultStorageQueries.cs+++ b/apps/server/AliasVault.Admin/Services/VaultStorageQueries.cs@@ -19,7 +19,7 @@ public static class VaultStorageQueries{/// <summary>/// Projects each user together with the kilobytes their personal vault occupies: every manifest and data bucket- /// revision owned by their personal group, plus the blob objects they own.+ /// revision owned by their personal group, plus the blob objects of those manifests./// </summary>/// <param name="users">The users to project.</param>/// <param name="context">The database context the users query belongs to.</param>@@ -33,7 +33,7 @@ public static class VaultStorageQueries+ context.VaultManifestsHistory.Where(h => h.Manifest.OwnerGroupId == u.PersonalGroupId).Sum(h => (long)h.FileSize)+ ((context.VaultDataBuckets.Where(b => b.Manifest.OwnerGroupId == u.PersonalGroupId).Sum(b => (long)b.EncryptedData.Length)+ context.VaultDataBucketsHistory.Where(b => b.Bucket.Manifest.OwnerGroupId == u.PersonalGroupId).Sum(b => (long)b.EncryptedData.Length)- + context.VaultBlobObjects.Where(b => b.OwnerUserId == u.Id).Sum(b => (long)b.SizeBytes)) / 1024),+ + context.VaultBlobObjects.Where(b => b.Manifest.OwnerGroupId == u.PersonalGroupId).Sum(b => (long)b.SizeBytes)) / 1024),});}@@ -42,20 +42,15 @@ public static class VaultStorageQueries/// the blob objects behind them./// </summary>/// <param name="context">Database context.</param>- /// <param name="userId">The user whose blob objects to account for.</param>/// <param name="personalGroupId">The user's personal group, which owns their manifests.</param>/// <returns>The storage breakdown.</returns>- public static async Task<VaultStorageOverview> GetPersonalVaultStorageAsync(AliasServerDbContext context, string userId, Guid personalGroupId)+ public static async Task<VaultStorageOverview> GetPersonalVaultStorageAsync(AliasServerDbContext context, Guid personalGroupId){// Blob usage a manifest revision references, keyed by (manifest, revision). Blobs are content-addressed and// shared between revisions, so this is reference usage per revision.var blobUsageByRevision = (await context.VaultBlobReferences.Where(r => r.Manifest.OwnerGroupId == personalGroupId)- .Join(- context.VaultBlobObjects.Where(b => b.OwnerUserId == userId),- r => r.BlobHash,- b => b.Hash,- (r, b) => new { r.ManifestId, r.RevisionNumber, b.SizeBytes })+ .Join(context.VaultBlobObjects, r => new { r.ManifestId, Hash = r.BlobHash }, b => new { b.ManifestId, b.Hash }, (r, b) => new { r.ManifestId, r.RevisionNumber, b.SizeBytes }).GroupBy(x => new { x.ManifestId, x.RevisionNumber }).Select(g => new { g.Key.ManifestId, g.Key.RevisionNumber, Count = g.Count(), Bytes = g.Sum(x => (long)x.SizeBytes) }).ToListAsync())@@ -143,25 +138,25 @@ public static class VaultStorageQueries{ManifestRevisions = manifestRevisions,BucketRevisions = [.. currentBuckets, .. historyBuckets],- BlobCategories = await GetBlobCategoryUsageAsync(context, userId),+ BlobCategories = await GetBlobCategoryUsageAsync(context, personalGroupId),};}/// <summary>- /// Aggregates a user's blob objects per category, separating out the ones no manifest revision references anymore.+ /// Aggregates the blob objects of a personal vault per category, separating out the ones no manifest revision references anymore./// </summary>/// <param name="context">Database context.</param>- /// <param name="userId">The user who owns the blob objects.</param>+ /// <param name="personalGroupId">The personal group that owns the manifests the blob objects belong to.</param>/// <returns>Usage per blob category.</returns>- private static async Task<List<VaultBlobCategoryUsage>> GetBlobCategoryUsageAsync(AliasServerDbContext context, string userId)+ private static async Task<List<VaultBlobCategoryUsage>> GetBlobCategoryUsageAsync(AliasServerDbContext context, Guid personalGroupId){var totals = await context.VaultBlobObjects- .Where(b => b.OwnerUserId == userId)+ .Where(b => b.Manifest.OwnerGroupId == personalGroupId).GroupBy(b => b.Category).Select(g => new { Category = g.Key, Count = g.Count(), Bytes = g.Sum(x => (long)x.SizeBytes) }).ToListAsync();- var unreferenced = (await VaultBlobRetentionPolicy.Unreferenced(context.VaultBlobObjects.Where(b => b.OwnerUserId == userId), context.VaultBlobReferences)+ var unreferenced = (await VaultBlobRetentionPolicy.Unreferenced(context.VaultBlobObjects.Where(b => b.Manifest.OwnerGroupId == personalGroupId), context.VaultBlobReferences).GroupBy(b => b.Category).Select(g => new { Category = g.Key, Count = g.Count(), Bytes = g.Sum(x => (long)x.SizeBytes) }).ToListAsync())diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultController.csindex 06a71d7df..8271b75f7 100644--- a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs@@ -130,11 +130,11 @@ public class VaultController(var currentRevisionByManifest = latestManifests.ToDictionary(m => m.ManifestId, m => m.RevisionNumber);var refsByManifest = (await context.VaultBlobReferences.Where(r => manifestIds.Contains(r.ManifestId))- .Join(context.VaultBlobObjects, r => r.BlobHash, b => b.Hash, (r, b) => new { r.ManifestId, r.RevisionNumber, b.Hash, b.Category, b.SizeBytes })+ .Join(context.VaultBlobObjects, r => new { r.ManifestId, Hash = r.BlobHash }, b => new { b.ManifestId, b.Hash }, (r, b) => new { r.ManifestId, r.RevisionNumber, b.Hash, b.Category, b.SizeBytes }).ToListAsync()).Where(x => currentRevisionByManifest.TryGetValue(x.ManifestId, out var rev) && rev == x.RevisionNumber).GroupBy(x => x.ManifestId)- .ToDictionary(g => g.Key, g => g.GroupBy(x => x.Hash, StringComparer.Ordinal).Select(h => new BlobReference { Hash = h.Key, Category = h.First().Category, SizeBytes = h.First().SizeBytes }).ToList());+ .ToDictionary(g => g.Key, g => g.Select(x => new BlobReference { Hash = x.Hash, Category = x.Category, SizeBytes = x.SizeBytes }).ToList());var accessKeysByManifest = await GetAccessKeysAsync(context, user.Id, manifestIds);var encryptionPublicKeys = await GetEncryptionPublicKeysAsync(context, accessKeysByManifest.Values.Where(g => g.UserGrantKeyId != null).Select(g => g.UserGrantKeyId!.Value));@@ -199,8 +199,7 @@ public class VaultController(var blobRefs = (await context.VaultBlobReferences.Where(r => r.ManifestId == latest.ManifestId && r.RevisionNumber == latest.RevisionNumber)- .Join(context.VaultBlobObjects, r => r.BlobHash, b => b.Hash, (r, b) => new { b.Hash, b.Category, b.SizeBytes })- .Distinct()+ .Join(context.VaultBlobObjects, r => new { r.ManifestId, Hash = r.BlobHash }, b => new { b.ManifestId, b.Hash }, (r, b) => new { b.Hash, b.Category, b.SizeBytes }).ToListAsync()).Select(x => new BlobReference { Hash = x.Hash, Category = x.Category, SizeBytes = x.SizeBytes }).ToList();@@ -372,35 +371,38 @@ public class VaultController({await using var tx = await context.Database.BeginTransactionAsync();- // 1) Upsert any new blob objects.+ // 1) Upsert any new blob objects, each under the manifests in this write that reference it.if (model.NewBlobs.Count > 0){- if (!await TryUpsertBlobObjectsAsync(context, user.Id, model.NewBlobs, overwrite: accountKeys != null))+ foreach (var (mw, row) in resolved){- await tx.RollbackAsync();- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_NOT_UP_TO_DATE, 400));+ var referenced = mw.BlobReferences.Select(br => br.Hash).ToHashSet(StringComparer.Ordinal);+ var manifestBlobs = model.NewBlobs.Where(b => referenced.Contains(b.Hash)).ToList();+ if (!await TryUpsertBlobObjectsAsync(context, row.ManifestId, manifestBlobs, overwrite: accountKeys != null && row.OwnerGroupId == user.PersonalGroupId))+ {+ await tx.RollbackAsync();+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_NOT_UP_TO_DATE, 400));+ }}await context.SaveChangesAsync();}- // 2) Validate every referenced hash exists.- var ownScopeHashes = resolved.Where(r => r.Row.OwnerGroupId == user.PersonalGroupId).SelectMany(r => r.Write.BlobReferences).Select(br => br.Hash).Distinct().ToList();- var anyScopeHashes = resolved.Where(r => r.Row.OwnerGroupId != user.PersonalGroupId).SelectMany(r => r.Write.BlobReferences).Select(br => br.Hash).Distinct().ToList();+ // 2) Validate every referenced hash exists in the store of the manifest that references it.+ var referencedHashes = resolved.SelectMany(r => r.Write.BlobReferences).Select(br => br.Hash).Distinct().ToList();var missing = new List<string>();- if (ownScopeHashes.Count > 0)- {- var present = await context.VaultBlobObjects.Where(b => b.OwnerUserId == user.Id && ownScopeHashes.Contains(b.Hash)).Select(b => b.Hash).ToListAsync();- missing.AddRange(ownScopeHashes.Except(present));- }-- if (anyScopeHashes.Count > 0)+ if (referencedHashes.Count > 0){- var present = await context.VaultBlobObjects.Where(b => anyScopeHashes.Contains(b.Hash)).Select(b => b.Hash).Distinct().ToListAsync();- missing.AddRange(anyScopeHashes.Except(present));+ var writtenManifestIds = resolved.Select(r => r.Row.ManifestId).ToList();+ var present = (await context.VaultBlobObjects+ .Where(b => writtenManifestIds.Contains(b.ManifestId) && referencedHashes.Contains(b.Hash))+ .Select(b => new { b.ManifestId, b.Hash })+ .ToListAsync())+ .Select(b => (b.ManifestId, b.Hash))+ .ToHashSet();+ missing = resolved.SelectMany(r => r.Write.BlobReferences.Where(br => !present.Contains((r.Row.ManifestId, br.Hash))).Select(br => br.Hash)).Distinct().ToList();}- missing = missing.Distinct().ToList();if (missing.Count > 0){await tx.RollbackAsync();@@ -592,7 +594,7 @@ public class VaultController(}/// <summary>- /// Batch-upload encrypted blobs ahead of a manifest upload. Idempotent per blob on (hash, user). Clients chunk+ /// Batch-upload encrypted blobs ahead of a manifest upload. Idempotent per blob on (manifest, hash). Clients chunk/// large blob sets across multiple calls to keep individual request bodies within server limits. A blob uploaded/// here but never referenced by a manifest is cleaned up by the task runner after its grace period./// </summary>@@ -608,12 +610,25 @@ public class VaultController(return Unauthorized();}+ var ownerGroupId = await GetBlobManifestOwnerGroupIdAsync(context, user, model.ManifestId);+ if (ownerGroupId == null)+ {+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));+ }++ // Replacing ciphertext is only part of the caller's own KEK/VEK migration, a shared manifest's key change is not implemented+ // yet. TODO: when implementing shared manifest key change, update this check too.+ if (model.Overwrite && ownerGroupId != user.PersonalGroupId)+ {+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_ERROR, 400));+ }+if (model.Blobs.Count == 0){return Ok(new BlobUploadResponse { AcceptedCount = 0 });}- if (!await TryUpsertBlobObjectsAsync(context, user.Id, model.Blobs, model.Overwrite))+ if (!await TryUpsertBlobObjectsAsync(context, model.ManifestId, model.Blobs, model.Overwrite)){return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_NOT_UP_TO_DATE, 400));}@@ -623,7 +638,7 @@ public class VaultController(}/// <summary>- /// Returns the subset of the supplied hashes the server is missing for this user. Lets a client upload only+ /// Returns the subset of the supplied hashes the server is missing for this manifest. Lets a client upload only/// the blob bytes the server doesn't already have. POST with a body (not GET with a query string) because a/// vault can reference hundreds of 64-char hashes, which would exceed URL length limits./// </summary>@@ -639,6 +654,12 @@ public class VaultController(return Unauthorized();}+ var ownerGroupId = await GetBlobManifestOwnerGroupIdAsync(context, user, model.ManifestId);+ if (ownerGroupId == null)+ {+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));+ }+var hashes = model.Hashes.Distinct().ToList();if (hashes.Count == 0){@@ -646,7 +667,7 @@ public class VaultController(}var present = await context.VaultBlobObjects- .Where(b => b.OwnerUserId == user.Id && hashes.Contains(b.Hash))+ .Where(b => b.ManifestId == model.ManifestId && hashes.Contains(b.Hash)).Select(b => b.Hash).ToListAsync();@@ -654,7 +675,7 @@ public class VaultController(}/// <summary>- /// Download a batch of encrypted blobs by hash. TODO: Returns base64-encoded payloads in JSON+ /// Download a batch of one manifest's encrypted blobs by hash. TODO: Returns base64-encoded payloads in JSON/// because for now we kept the codec language-agnostic. Look into switching to multipart binary in the future./// </summary>/// <param name="model">Hash list request.</param>@@ -669,6 +690,12 @@ public class VaultController(return Unauthorized();}+ var ownerGroupId = await GetBlobManifestOwnerGroupIdAsync(context, user, model.ManifestId);+ if (ownerGroupId == null)+ {+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));+ }+var wanted = model.Hashes.Distinct().ToList();if (wanted.Count == 0){@@ -676,7 +703,7 @@ public class VaultController(}var rows = await context.VaultBlobObjects- .Where(b => b.OwnerUserId == user.Id && wanted.Contains(b.Hash))+ .Where(b => b.ManifestId == model.ManifestId && wanted.Contains(b.Hash)).Select(b => new Blob{Hash = b.Hash,@@ -685,47 +712,6 @@ public class VaultController(}).ToListAsync();- // Hashes not in the caller's own store may belong to a shared manifest: any blob referenced by the current- // revision of a manifest the caller can access (granted to them, or a manifest they own that another member- // pushed blobs for) is downloadable regardless of which member's store holds the ciphertext.- var missing = wanted.Except(rows.Select(r => r.Hash), StringComparer.Ordinal).ToList();- if (missing.Count > 0)- {- var accessScope = await ManifestAccessHelper.ResolveScopeAsync(context, user.Id, user.PersonalGroupId);- var accessibleManifests = await AccessibleManifests(context, accessScope)- .Where(m => m.OwnerGroup.Type == GroupType.Shared)- .Select(m => new { m.ManifestId, m.RevisionNumber })- .ToListAsync();- var accessibleIds = accessibleManifests.Select(m => m.ManifestId).ToList();- var currentRevisionById = accessibleManifests.ToDictionary(m => m.ManifestId, m => m.RevisionNumber);-- if (accessibleIds.Count > 0)- {- var referencedHashes = (await context.VaultBlobReferences- .Where(r => accessibleIds.Contains(r.ManifestId) && missing.Contains(r.BlobHash))- .Select(r => new { r.ManifestId, r.RevisionNumber, r.BlobHash })- .ToListAsync())- .Where(r => currentRevisionById.TryGetValue(r.ManifestId, out var rev) && rev == r.RevisionNumber)- .Select(r => r.BlobHash)- .Distinct()- .ToList();-- if (referencedHashes.Count > 0)- {- var sharedRows = await context.VaultBlobObjects- .Where(b => referencedHashes.Contains(b.Hash))- .Select(b => new Blob- {- Hash = b.Hash,- Category = b.Category,- EncryptedDataBase64 = Convert.ToBase64String(b.EncryptedData),- })- .ToListAsync();- rows.AddRange(sharedRows.GroupBy(b => b.Hash, StringComparer.Ordinal).Select(g => g.First()));- }- }- }-return Ok(rows);}@@ -782,6 +768,19 @@ public class VaultController(return ManifestAccessHelper.AccessibleManifests(context, scope).Where(m => m.StorageFormat == ManifestFormat);}+ /// <summary>+ /// Gets the owner group of the manifest a blob request is scoped to, when the caller can access that manifest.+ /// </summary>+ /// <param name="context">Database context.</param>+ /// <param name="user">The calling user.</param>+ /// <param name="manifestId">The manifest named by the request.</param>+ /// <returns>The owner group id, or null when the manifest does not exist or the caller cannot access it.</returns>+ private static async Task<Guid?> GetBlobManifestOwnerGroupIdAsync(AliasServerDbContext context, AliasVaultUser user, Guid manifestId)+ {+ var accessScope = await ManifestAccessHelper.ResolveScopeAsync(context, user.Id, user.PersonalGroupId);+ return await ManifestAccessHelper.AccessibleManifests(context, accessScope).Where(x => x.ManifestId == manifestId).Select(x => (Guid?)x.OwnerGroupId).FirstOrDefaultAsync();+ }+/// <summary>/// Gets the caller's key row on each of the given manifests, whichever way that manifest's VEK is encrypted for/// them: an account-key row (unlocked through their password chain) or a grant encrypted to one of their public@@ -871,21 +870,21 @@ public class VaultController(}/// <summary>- /// Upserts a batch of encrypted blob objects for a user in one round-trip. Existing blobs (same hash) are left+ /// Upserts a batch of encrypted blob objects for a manifest in one round-trip. Existing blobs (same hash) are left/// as they are, unless <paramref name="overwrite"/> is set (KEK/VEK migration) in which case their ciphertext is/// replaced with the re-encrypted bytes. The caller of this method should call SaveChanges after calling this method./// </summary>/// <param name="context">DbContext to operate on.</param>- /// <param name="userId">Owning user id.</param>+ /// <param name="manifestId">The manifest the blobs belong to.</param>/// <param name="blobs">Blobs to upsert.</param>/// <param name="overwrite">When true, existing blobs with the same hash get their ciphertext replaced.</param>/// <returns>True when every payload is structurally valid; false when any is malformed (caller should 400).</returns>- private async Task<bool> TryUpsertBlobObjectsAsync(AliasServerDbContext context, string userId, List<Blob> blobs, bool overwrite = false)+ private async Task<bool> TryUpsertBlobObjectsAsync(AliasServerDbContext context, Guid manifestId, List<Blob> blobs, bool overwrite = false){var nowUtc = timeProvider.UtcNow;var hashes = blobs.Select(b => b.Hash).Distinct().ToList();var existing = await context.VaultBlobObjects- .Where(b => b.OwnerUserId == userId && hashes.Contains(b.Hash))+ .Where(b => b.ManifestId == manifestId && hashes.Contains(b.Hash)).ToDictionaryAsync(b => b.Hash, StringComparer.Ordinal);foreach (var dto in blobs)@@ -914,7 +913,7 @@ public class VaultController(var entity = new VaultBlobObject{Hash = dto.Hash,- OwnerUserId = userId,+ ManifestId = manifestId,Category = dto.Category,EncryptedData = data!,SizeBytes = data!.Length,diff --git a/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncService.cs b/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncService.csindex 9d3f43925..af54dd2ce 100644--- a/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncService.cs+++ b/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncService.cs@@ -280,7 +280,7 @@ public sealed class VaultSyncService(HttpClient httpClient, AuthService authServ{foreach (var (hash, blob) in manifest.Blobs){- blobEntries.TryAdd(hash, new UploadBlobEntry(blob.Kind, blob.Bytes, manifest.Record.VaultEncryptionKey, manifest.Record.IsPersonal));+ blobEntries.TryAdd(hash, new UploadBlobEntry(manifest.Record.ManifestId, blob.Kind, blob.Bytes, manifest.Record.VaultEncryptionKey, manifest.Record.IsPersonal));}var label = manifest.Record.IsPersonal ? "Personal manifest" : $"Shared manifest \"{manifest.Record.Name ?? manifest.Record.ManifestId.ToString()}\"";@@ -343,11 +343,11 @@ public sealed class VaultSyncService(HttpClient httpClient, AuthService authServif (migration is not null){personalToUpload = personalHashes;- sharedToUpload = await MissingOnServerAsync(sharedHashes.Where(hash => !state.ServerBlobHashes.Contains(hash)));+ sharedToUpload = await MissingOnServerAsync(blobEntries, sharedHashes.Where(hash => !state.ServerBlobHashes.Contains(hash)));}else{- var toUpload = new HashSet<string>(await MissingOnServerAsync(allBlobHashes.Where(hash => !state.ServerBlobHashes.Contains(hash))), StringComparer.Ordinal);+ var toUpload = new HashSet<string>(await MissingOnServerAsync(blobEntries, allBlobHashes.Where(hash => !state.ServerBlobHashes.Contains(hash))), StringComparer.Ordinal);personalToUpload = personalHashes.Where(toUpload.Contains).ToList();sharedToUpload = sharedHashes.Where(toUpload.Contains).ToList();}@@ -1060,12 +1060,15 @@ public sealed class VaultSyncService(HttpClient httpClient, AuthService authServvar missingRefs = refs.Where(reference => !cache.ContainsKey(reference.Hash)).ToList();logger.LogInformation("[V2Pull] Blob refs: {Referenced} referenced, {Cached} cached, {Missing} to download.", refs.Count, refs.Count - missingRefs.Count, missingRefs.Count);- // Batch downloads by the bytes each blob adds to the response, not by hash count.- var batches = BatchByTransferCost(missingRefs, reference => Base64Chars(reference.SizeBytes));+ // Batch downloads per owning manifest, by the bytes each blob adds to the response, not by hash count.+ var batches = missingRefs+ .GroupBy(reference => refOwners[reference.Hash].ManifestId)+ .SelectMany(group => BatchByTransferCost(group.ToList(), reference => Base64Chars(reference.SizeBytes)).Select(batch => (ManifestId: group.Key, Refs: batch)))+ .ToList();for (var index = 0; index < batches.Count; index++){- var batch = batches[index];- using var response = await httpClient.PostAsJsonAsync(BlobsDownloadEndpoint, new BlobHashesRequest { Hashes = batch.Select(reference => reference.Hash).ToList() });+ var (batchManifestId, batch) = batches[index];+ using var response = await httpClient.PostAsJsonAsync(BlobsDownloadEndpoint, new BlobHashesRequest { ManifestId = batchManifestId, Hashes = batch.Select(reference => reference.Hash).ToList() });response.EnsureSuccessStatusCode();var blobs = await response.Content.ReadFromJsonAsync<List<Blob>>() ?? [];foreach (var blob in blobs)@@ -1437,27 +1440,28 @@ public sealed class VaultSyncService(HttpClient httpClient, AuthService authServ}/// <summary>- /// Ask the server which of the given blobs it does not hold.+ /// Ask the server which of the given blobs it does not hold, one request per manifest that owns them./// </summary>+ /// <param name="entries">Every staged blob, by hash.</param>/// <param name="hashes">The candidate hashes.</param>/// <returns>The hashes unknown to the server.</returns>- private async Task<List<string>> MissingOnServerAsync(IEnumerable<string> hashes)+ private async Task<List<string>> MissingOnServerAsync(Dictionary<string, UploadBlobEntry> entries, IEnumerable<string> hashes){- var candidates = hashes.ToList();- if (candidates.Count == 0)+ var missing = new List<string>();+ foreach (var group in hashes.Where(entries.ContainsKey).GroupBy(hash => entries[hash].ManifestId)){- return [];+ using var response = await httpClient.PostAsJsonAsync(BlobsMissingEndpoint, new BlobHashesRequest { ManifestId = group.Key, Hashes = group.ToList() });+ response.EnsureSuccessStatusCode();+ var body = await response.Content.ReadFromJsonAsync<MissingBlobsResponse>();+ missing.AddRange(body?.Missing ?? []);}- using var response = await httpClient.PostAsJsonAsync(BlobsMissingEndpoint, new BlobHashesRequest { Hashes = candidates });- response.EnsureSuccessStatusCode();- var body = await response.Content.ReadFromJsonAsync<MissingBlobsResponse>();- return body?.Missing ?? [];+ return missing;}/// <summary>/// Encrypt the given blobs, each with the key of the manifest that owns it, and upload them in size-capped batches- /// ahead of the manifest write.+ /// per manifest ahead of the manifest write./// </summary>/// <param name="entries">Every staged blob, by hash.</param>/// <param name="hashes">The subset to upload.</param>@@ -1466,46 +1470,46 @@ public sealed class VaultSyncService(HttpClient httpClient, AuthService authServ/// <returns>Task.</returns>private async Task UploadBlobsAsync(Dictionary<string, UploadBlobEntry> entries, IEnumerable<string> hashes, bool overwrite, Dictionary<string, string> uploaded){- var batch = new List<Blob>();- var batchChars = 0;- foreach (var hash in hashes)+ foreach (var group in hashes.Where(entries.ContainsKey).GroupBy(hash => entries[hash].ManifestId)){- if (!entries.TryGetValue(hash, out var entry))+ var batch = new List<Blob>();+ var batchChars = 0;+ foreach (var hash in group){- continue;- }+ var entry = entries[hash];+ var ciphertext = Convert.ToBase64String(await jsInteropService.SymmetricEncryptBytes(entry.Bytes, Convert.FromBase64String(entry.VaultEncryptionKey)));+ uploaded[hash] = ciphertext;- var ciphertext = Convert.ToBase64String(await jsInteropService.SymmetricEncryptBytes(entry.Bytes, Convert.FromBase64String(entry.VaultEncryptionKey)));- uploaded[hash] = ciphertext;+ // Flush before adding when this blob would take the request past either bound.+ if (batch.Count > 0 && (batchChars + ciphertext.Length > BlobTransferBatchMaxChars || batch.Count >= BlobTransferBatchMaxCount))+ {+ await PostBlobBatchAsync(group.Key, batch, overwrite);+ batch = [];+ batchChars = 0;+ }- // Flush before adding when this blob would take the request past either bound.- if (batch.Count > 0 && (batchChars + ciphertext.Length > BlobTransferBatchMaxChars || batch.Count >= BlobTransferBatchMaxCount))- {- await PostBlobBatchAsync(batch, overwrite);- batch = [];- batchChars = 0;+ batch.Add(new Blob { Hash = hash, Category = entry.Kind, EncryptedDataBase64 = ciphertext });+ batchChars += ciphertext.Length;}- batch.Add(new Blob { Hash = hash, Category = entry.Kind, EncryptedDataBase64 = ciphertext });- batchChars += ciphertext.Length;- }-- if (batch.Count > 0)- {- await PostBlobBatchAsync(batch, overwrite);+ if (batch.Count > 0)+ {+ await PostBlobBatchAsync(group.Key, batch, overwrite);+ }}}/// <summary>/// Upload one batch of encrypted blobs./// </summary>+ /// <param name="manifestId">The manifest the blobs belong to.</param>/// <param name="batch">The blobs.</param>/// <param name="overwrite">Whether the server replaces ciphertext it already holds.</param>/// <returns>Task.</returns>- private async Task PostBlobBatchAsync(List<Blob> batch, bool overwrite)+ private async Task PostBlobBatchAsync(Guid manifestId, List<Blob> batch, bool overwrite){logger.LogInformation("[V2Push] Uploading blob batch: {Count} blob(s).", batch.Count);- using var response = await httpClient.PostAsJsonAsync(BlobsEndpoint, new BlobUploadRequest { Blobs = batch, Overwrite = overwrite });+ using var response = await httpClient.PostAsJsonAsync(BlobsEndpoint, new BlobUploadRequest { ManifestId = manifestId, Blobs = batch, Overwrite = overwrite });await EnsureUploadSucceededAsync(response, "Blob upload");}@@ -1579,9 +1583,10 @@ public sealed class VaultSyncService(HttpClient httpClient, AuthService authServ/// <summary>/// A plaintext blob staged for upload: its bytes plus the key that encrypts it./// </summary>+ /// <param name="ManifestId">The manifest that owns it.</param>/// <param name="Kind">The blob kind.</param>/// <param name="Bytes">The plaintext bytes.</param>/// <param name="VaultEncryptionKey">The key of the manifest that owns it.</param>/// <param name="FromPersonal">Whether the personal manifest owns it.</param>- private sealed record UploadBlobEntry(string Kind, byte[] Bytes, string VaultEncryptionKey, bool FromPersonal);+ private sealed record UploadBlobEntry(Guid ManifestId, string Kind, byte[] Bytes, string VaultEncryptionKey, bool FromPersonal);}diff --git a/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs b/apps/server/Databases/AliasServerDb/AliasServerDbContext.csindex c07aa287a..0e61847fd 100644--- a/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs+++ b/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs@@ -591,14 +591,13 @@ public class AliasServerDbContext : WorkerStatusDbContext, IDataProtectionKeyCon.OnDelete(DeleteBehavior.Cascade);});- // Configure VaultBlobObject - composite key (Hash, UserId).+ // Configure VaultBlobObject - composite key (ManifestId, Hash). Cascades with the manifest.modelBuilder.Entity<VaultBlobObject>(builder =>{- builder.HasKey(e => new { e.Hash, e.OwnerUserId });- builder.HasIndex(e => new { e.OwnerUserId, e.Category });- builder.HasOne(e => e.User)+ builder.HasKey(e => new { e.ManifestId, e.Hash });+ builder.HasOne(e => e.Manifest).WithMany()- .HasForeignKey(e => e.OwnerUserId)+ .HasForeignKey(e => e.ManifestId).OnDelete(DeleteBehavior.Cascade);});diff --git a/apps/server/Databases/AliasServerDb/Legacy/LegacyVaultRollback.cs b/apps/server/Databases/AliasServerDb/Legacy/LegacyVaultRollback.csindex 129c1c7f1..5f3d9ed48 100644--- a/apps/server/Databases/AliasServerDb/Legacy/LegacyVaultRollback.cs+++ b/apps/server/Databases/AliasServerDb/Legacy/LegacyVaultRollback.cs@@ -52,7 +52,7 @@ public static class LegacyVaultRollback// Blob objects only exist on the manifest format; the legacy format carries its attachments inside the// vault blob itself. The stored bytes go with the references rather than waiting for the sweeper.await context.VaultBlobReferences.Where(x => x.ManifestId == manifestId).ExecuteDeleteAsync();- await context.VaultBlobObjects.Where(x => x.OwnerUserId == userId).ExecuteDeleteAsync();+ await context.VaultBlobObjects.Where(x => x.ManifestId == manifestId).ExecuteDeleteAsync();// Data buckets only exist on the manifest format; their superseded revisions cascade with them. Leaving// them behind would also block the next migration, whose first push writes each bucket from revision 0.diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260917141654_RekeyVaultBlobObjectsOnManifest.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260917141654_RekeyVaultBlobObjectsOnManifest.Designer.csnew file mode 100644index 000000000..2b0177411--- /dev/null+++ b/apps/server/Databases/AliasServerDb/Migrations/20260917141654_RekeyVaultBlobObjectsOnManifest.Designer.cs@@ -0,0 +1,2008 @@+// <auto-generated />+using System;+using AliasServerDb;+using Microsoft.EntityFrameworkCore;+using Microsoft.EntityFrameworkCore.Infrastructure;+using Microsoft.EntityFrameworkCore.Migrations;+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;+using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;++#nullable disable++namespace AliasServerDb.Migrations+{+ [DbContext(typeof(AliasServerDbContext))]+ [Migration("20260917141654_RekeyVaultBlobObjectsOnManifest")]+ partial class RekeyVaultBlobObjectsOnManifest+ {+ /// <inheritdoc />+ protected override void BuildTargetModel(ModelBuilder modelBuilder)+ {+#pragma warning disable 612, 618+ modelBuilder+ .HasAnnotation("ProductVersion", "10.0.10")+ .HasAnnotation("Proxies:ChangeTracking", false)+ .HasAnnotation("Proxies:CheckEquality", false)+ .HasAnnotation("Proxies:LazyLoading", true)+ .HasAnnotation("Relational:MaxIdentifierLength", 63);++ NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);++ modelBuilder.Entity("AliasServerDb.AdminUser", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("text");++ b.Property<int>("AccessFailedCount")+ .HasColumnType("integer");++ b.Property<string>("ConcurrencyStamp")+ .HasColumnType("text");++ b.Property<string>("Email")+ .HasColumnType("text");++ b.Property<bool>("EmailConfirmed")+ .HasColumnType("boolean");++ b.Property<DateTime?>("LastPasswordChanged")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("LockoutEnabled")+ .HasColumnType("boolean");++ b.Property<DateTimeOffset?>("LockoutEnd")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("NormalizedEmail")+ .HasColumnType("text");++ b.Property<string>("NormalizedUserName")+ .HasColumnType("text");++ b.Property<string>("PasswordHash")+ .HasColumnType("text");++ b.Property<string>("PhoneNumber")+ .HasColumnType("text");++ b.Property<bool>("PhoneNumberConfirmed")+ .HasColumnType("boolean");++ b.Property<string>("SecurityStamp")+ .HasColumnType("text");++ b.Property<bool>("TwoFactorEnabled")+ .HasColumnType("boolean");++ b.Property<string>("UserName")+ .HasColumnType("text");++ b.HasKey("Id");++ b.ToTable("AdminUsers");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("text");++ b.Property<int>("AccessFailedCount")+ .HasColumnType("integer");++ b.Property<bool>("Blocked")+ .HasColumnType("boolean");++ b.Property<DateTime?>("BlockedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("ConcurrencyStamp")+ .HasColumnType("text");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Email")+ .HasColumnType("text");++ b.Property<bool>("EmailConfirmed")+ .HasColumnType("boolean");++ b.Property<DateTime?>("LastActivityDate")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("LockoutEnabled")+ .HasColumnType("boolean");++ b.Property<DateTimeOffset?>("LockoutEnd")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("NormalizedEmail")+ .HasColumnType("text");++ b.Property<string>("NormalizedUserName")+ .HasColumnType("text");++ b.Property<DateTime>("PasswordChangedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("PasswordHash")+ .HasColumnType("text");++ b.Property<Guid>("PersonalGroupId")+ .HasColumnType("uuid");++ b.Property<string>("PhoneNumber")+ .HasColumnType("text");++ b.Property<bool>("PhoneNumberConfirmed")+ .HasColumnType("boolean");++ b.Property<string>("SecurityStamp")+ .HasColumnType("text");++ b.Property<string>("SrpIdentity")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<bool>("TwoFactorEnabled")+ .HasColumnType("boolean");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserName")+ .HasColumnType("text");++ b.HasKey("Id");++ b.HasIndex("PersonalGroupId")+ .IsUnique()+ .HasDatabaseName("UX_AliasVaultUsers_PersonalGroupId");++ b.ToTable("AliasVaultUsers");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUserRefreshToken", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("DeviceIdentifier")+ .IsRequired()+ .HasColumnType("text");++ b.Property<DateTime>("ExpireDate")+ .HasMaxLength(255)+ .HasColumnType("timestamp with time zone");++ b.Property<string>("IpAddress")+ .HasMaxLength(45)+ .HasColumnType("character varying(45)");++ b.Property<string>("PreviousTokenValue")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("Value")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("UserId");++ b.ToTable("AliasVaultUserRefreshTokens");+ });++ modelBuilder.Entity("AliasServerDb.AuthLog", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("AdditionalInfo")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("Browser")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("Client")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("Country")+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<string>("DeviceType")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<int>("EventType")+ .HasColumnType("integer");++ b.Property<int?>("FailureReason")+ .HasColumnType("integer");++ b.Property<string>("IpAddress")+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<bool>("IsSuccess")+ .HasColumnType("boolean");++ b.Property<bool>("IsSuspiciousActivity")+ .HasColumnType("boolean");++ b.Property<string>("OperatingSystem")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("RequestPath")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("Timestamp")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Username")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex(new[] { "EventType" }, "IX_EventType");++ b.HasIndex(new[] { "IpAddress" }, "IX_IpAddress");++ b.HasIndex(new[] { "Timestamp" }, "IX_Timestamp");++ b.HasIndex(new[] { "Username", "IsSuccess", "Timestamp" }, "IX_Username_IsSuccess_Timestamp")+ .IsDescending(false, false, true);++ b.HasIndex(new[] { "Username", "Timestamp" }, "IX_Username_Timestamp")+ .IsDescending(false, true);++ b.ToTable("AuthLogs");+ });++ modelBuilder.Entity("AliasServerDb.BlockedIpRange", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<bool>("BlockLogin")+ .HasColumnType("boolean");++ b.Property<bool>("BlockRegistration")+ .HasColumnType("boolean");++ b.Property<bool>("BlockShadow")+ .HasColumnType("boolean");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("CreatedBy")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<bool>("Enabled")+ .HasColumnType("boolean");++ b.Property<string>("IpRange")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<string>("Reason")+ .HasMaxLength(500)+ .HasColumnType("character varying(500)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("Id");++ b.HasIndex(new[] { "Enabled" }, "IX_BlockedIpRange_Enabled");++ b.HasIndex(new[] { "IpRange" }, "IX_BlockedIpRange_IpRange")+ .IsUnique();++ b.ToTable("BlockedIpRanges");+ });++ modelBuilder.Entity("AliasServerDb.CapabilityRule", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<string>("CapabilityKey")+ .IsRequired()+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("ClientName")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("CreatedBy")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime?>("EffectiveFrom")+ .HasColumnType("timestamp with time zone");++ b.Property<DateTime?>("EffectiveUntil")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("Enabled")+ .HasColumnType("boolean");++ b.Property<Guid?>("GroupId")+ .HasColumnType("uuid");++ b.Property<string>("Kind")+ .IsRequired()+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.Property<string>("Notes")+ .HasMaxLength(1000)+ .HasColumnType("character varying(1000)");++ b.Property<string>("Tier")+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("Value")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("GroupId");++ b.HasIndex("Tier");++ b.HasIndex("UserId");++ b.HasIndex("CapabilityKey", "Enabled");++ b.ToTable("CapabilityRules");+ });++ modelBuilder.Entity("AliasServerDb.ClientAction", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<Guid?>("ManifestId")+ .HasColumnType("uuid");++ b.Property<string>("Payload")+ .HasColumnType("jsonb");++ b.Property<Guid?>("TargetGroupId")+ .HasColumnType("uuid");++ b.Property<string>("TargetUserId")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("Type")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("Id");++ b.HasIndex("TargetGroupId");++ b.HasIndex("TargetUserId");++ b.ToTable("ClientActions");+ });++ modelBuilder.Entity("AliasServerDb.Email", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<int>("AttachmentCount")+ .HasColumnType("integer");++ b.Property<DateTime>("Date")+ .HasColumnType("timestamp with time zone");++ b.Property<DateTime>("DateSystem")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("From")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("FromDomain")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("FromLocal")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("MessageHtml")+ .HasColumnType("text");++ b.Property<string>("MessagePlain")+ .HasColumnType("text");++ b.Property<string>("MessagePreview")+ .HasColumnType("text");++ b.Property<string>("MessageSource")+ .HasColumnType("text");++ b.Property<byte[]>("MessageSourceBytes")+ .HasColumnType("bytea");++ b.Property<bool>("PushNotificationSent")+ .HasColumnType("boolean");++ b.Property<string>("Subject")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("To")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("ToDomain")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("ToLocal")+ .IsRequired()+ .HasColumnType("text");++ b.Property<bool>("Visible")+ .HasColumnType("boolean");++ b.HasKey("Id");++ b.HasIndex("Date");++ b.HasIndex("DateSystem");++ b.HasIndex("PushNotificationSent");++ b.HasIndex("Visible");++ b.HasIndex("To", "DateSystem");++ b.ToTable("Emails");+ });++ modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<byte[]>("Bytes")+ .IsRequired()+ .HasColumnType("bytea");++ b.Property<DateTime>("Date")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("EmailId")+ .HasColumnType("integer");++ b.Property<string>("Filename")+ .IsRequired()+ .HasColumnType("text");++ b.Property<int>("Filesize")+ .HasColumnType("integer");++ b.Property<string>("MimeType")+ .IsRequired()+ .HasColumnType("text");++ b.HasKey("Id");++ b.HasIndex("EmailId");++ b.ToTable("EmailAttachments");+ });++ modelBuilder.Entity("AliasServerDb.EmailClaim", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<string>("Address")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("AddressDomain")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("AddressLocal")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<bool>("AnonymizedSenderCounted")+ .HasColumnType("boolean");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("Id");++ b.HasIndex("Address")+ .IsUnique();++ b.ToTable("EmailClaims");+ });++ modelBuilder.Entity("AliasServerDb.EmailClaimLink", b =>+ {+ b.Property<Guid>("EmailClaimId")+ .HasColumnType("uuid");++ b.Property<Guid>("VaultManifestId")+ .HasColumnType("uuid");++ b.Property<string>("State")+ .IsRequired()+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.HasKey("EmailClaimId", "VaultManifestId");++ b.HasIndex("EmailClaimId")+ .HasDatabaseName("IX_EmailClaimLinks_EmailClaimId_Live")+ .HasFilter("\"State\" <> 'Removed'");++ b.HasIndex("VaultManifestId", "EmailClaimId");++ b.ToTable("EmailClaimLinks");+ });++ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>+ {+ b.Property<int>("EmailId")+ .HasColumnType("integer");++ b.Property<Guid>("VaultManifestDeliveryKeyId")+ .HasColumnType("uuid");++ b.Property<string>("EncryptedSymmetricKey")+ .IsRequired()+ .HasColumnType("text");++ b.HasKey("EmailId", "VaultManifestDeliveryKeyId");++ b.HasIndex("VaultManifestDeliveryKeyId", "EmailId");++ b.ToTable("EmailDecryptionKeys");+ });++ modelBuilder.Entity("AliasServerDb.EmailPart", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<byte[]>("Bytes")+ .IsRequired()+ .HasColumnType("bytea");++ b.Property<int>("EmailId")+ .HasColumnType("integer");++ b.Property<int>("PartIndex")+ .HasColumnType("integer");++ b.HasKey("Id");++ b.HasIndex("EmailId", "PartIndex")+ .IsUnique();++ b.ToTable("EmailParts");+ });++ modelBuilder.Entity("AliasServerDb.Group", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.PrimitiveCollection<int[]>("AnonymizedEmailAliasSenderCounts")+ .IsRequired()+ .ValueGeneratedOnAdd()+ .HasColumnType("integer[]")+ .HasDefaultValueSql("array_fill(0, ARRAY[64])");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("EmailsReceived")+ .HasColumnType("integer");++ b.Property<int>("MaxEmailAgeDays")+ .HasColumnType("integer");++ b.Property<int>("MaxEmails")+ .HasColumnType("integer");++ b.Property<string>("Name")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<bool>("ShadowBlocked")+ .HasColumnType("boolean");++ b.Property<DateTime?>("ShadowBlockedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("Type")+ .HasColumnType("integer");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("Id");++ b.ToTable("Groups");+ });++ modelBuilder.Entity("AliasServerDb.GroupInvitation", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<string>("Algorithm")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedName")+ .HasColumnType("text");++ b.Property<string>("EncryptedVek")+ .HasColumnType("text");++ b.Property<Guid>("GroupId")+ .HasColumnType("uuid");++ b.Property<string>("InviteeUserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("InviterUserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime?>("RespondedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("Role")+ .HasColumnType("integer");++ b.Property<string>("State")+ .IsRequired()+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<Guid?>("UserGrantKeyId")+ .HasColumnType("uuid");++ b.Property<int>("VaultKeyVersion")+ .HasColumnType("integer");++ b.Property<Guid?>("VaultManifestId")+ .HasColumnType("uuid");++ b.HasKey("Id");++ b.HasIndex("GroupId");++ b.HasIndex("InviterUserId");++ b.HasIndex("UserGrantKeyId");++ b.HasIndex("InviteeUserId", "State");++ b.HasIndex("VaultManifestId", "InviteeUserId")+ .IsUnique()+ .HasDatabaseName("UX_GroupInvitations_Manifest_Invitee_Pending")+ .HasFilter("\"State\" = 'Pending'");++ b.ToTable("GroupInvitations");+ });++ modelBuilder.Entity("AliasServerDb.GroupMember", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<Guid>("GroupId")+ .HasColumnType("uuid");++ b.Property<int>("Role")+ .HasColumnType("integer");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("UserId");++ b.HasIndex("GroupId", "UserId")+ .IsUnique();++ b.ToTable("GroupMembers");+ });++ modelBuilder.Entity("AliasServerDb.Log", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("Application")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<string>("Exception")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("Level")+ .IsRequired()+ .HasMaxLength(128)+ .HasColumnType("character varying(128)");++ b.Property<string>("LogEvent")+ .IsRequired()+ .HasColumnType("text")+ .HasColumnName("LogEvent");++ b.Property<string>("Message")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("MessageTemplate")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("Properties")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("SourceContext")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("TimeStamp")+ .HasColumnType("timestamp with time zone");++ b.HasKey("Id");++ b.HasIndex("Application");++ b.HasIndex("TimeStamp");++ b.ToTable("Logs", (string)null);+ });++ modelBuilder.Entity("AliasServerDb.MobileLoginRequest", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("text");++ b.Property<string>("Algorithm")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime?>("ClearedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("ClientIpAddress")+ .HasColumnType("text");++ b.Property<string>("ClientPublicKey")+ .IsRequired()+ .HasColumnType("text");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedDecryptionKey")+ .HasColumnType("text");++ b.Property<DateTime?>("FulfilledAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("MobileIpAddress")+ .HasColumnType("text");++ b.Property<DateTime?>("RetrievedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .HasColumnType("text");++ b.HasKey("Id");++ b.HasIndex(new[] { "ClientIpAddress" }, "IX_ClientIpAddress");++ b.HasIndex(new[] { "CreatedAt" }, "IX_CreatedAt");++ b.HasIndex(new[] { "MobileIpAddress" }, "IX_MobileIpAddress");++ b.HasIndex(new[] { "RetrievedAt", "ClearedAt", "FulfilledAt" }, "IX_RetrievedAt_ClearedAt_FulfilledAt");++ b.HasIndex(new[] { "UserId" }, "IX_UserId");++ b.ToTable("MobileLoginRequests");+ });++ modelBuilder.Entity("AliasServerDb.RateLimit", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<int?>("AppliesToAccountAgeMaxDays")+ .HasColumnType("integer");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("CreatedBy")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime?>("EffectiveFrom")+ .HasColumnType("timestamp with time zone");++ b.Property<DateTime?>("EffectiveUntil")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("Enabled")+ .HasColumnType("boolean");++ b.Property<Guid?>("GroupId")+ .HasColumnType("uuid");++ b.Property<int>("LimitType")+ .HasColumnType("integer");++ b.Property<int>("MaxCount")+ .HasColumnType("integer");++ b.Property<string>("Notes")+ .HasMaxLength(1000)+ .HasColumnType("character varying(1000)");++ b.Property<int?>("Tier")+ .HasColumnType("integer");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("WindowSeconds")+ .HasColumnType("integer");++ b.HasKey("Id");++ b.HasIndex("GroupId");++ b.HasIndex("Tier");++ b.HasIndex("LimitType", "Enabled");++ b.ToTable("RateLimits");+ });++ modelBuilder.Entity("AliasServerDb.ServerSetting", b =>+ {+ b.Property<string>("Key")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Value")+ .HasColumnType("text");++ b.HasKey("Key");++ b.ToTable("ServerSettings");+ });++ modelBuilder.Entity("AliasServerDb.TaskRunnerJob", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<TimeOnly?>("EndTime")+ .HasColumnType("time without time zone");++ b.Property<string>("ErrorMessage")+ .HasColumnType("text");++ b.Property<bool>("IsOnDemand")+ .HasColumnType("boolean");++ b.Property<string>("Name")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<DateTime>("RunDate")+ .HasColumnType("timestamp with time zone");++ b.Property<TimeOnly>("StartTime")+ .HasColumnType("time without time zone");++ b.Property<int>("Status")+ .HasColumnType("integer");++ b.HasKey("Id");++ b.ToTable("TaskRunnerJobs");+ });++ modelBuilder.Entity("AliasServerDb.UserGrantKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<int>("AccountKeyVersion")+ .HasColumnType("integer");++ b.Property<string>("Algorithm")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedPrivateKey")+ .IsRequired()+ .HasMaxLength(4000)+ .HasColumnType("character varying(4000)");++ b.Property<bool>("IsPrimary")+ .HasColumnType("boolean");++ b.Property<string>("PublicKey")+ .IsRequired()+ .HasMaxLength(2000)+ .HasColumnType("character varying(2000)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("UserId")+ .IsUnique()+ .HasDatabaseName("UX_UserGrantKeys_User_Primary")+ .HasFilter("\"IsPrimary\"");++ b.ToTable("UserGrantKeys");+ });++ modelBuilder.Entity("AliasServerDb.UserUnlockKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<int>("AccountKeyVersion")+ .HasColumnType("integer");++ b.Property<string>("Algorithm")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedAccountKey")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("Label")+ .IsRequired()+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<DateTime?>("LastUsedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Metadata")+ .HasColumnType("jsonb");++ b.Property<string>("Type")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("UserId", "Type", "Label")+ .IsUnique()+ .HasDatabaseName("UX_UserUnlockKeys_UserId_Type_Label");++ b.ToTable("UserUnlockKeys");+ });++ modelBuilder.Entity("AliasServerDb.UserUnlockKeysHistory", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<int>("AccountKeyVersion")+ .HasColumnType("integer");++ b.Property<string>("Algorithm")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("ArchivedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("ArchivedByClient")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedAccountKey")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("Label")+ .IsRequired()+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("Metadata")+ .HasColumnType("jsonb");++ b.Property<string>("Type")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<Guid>("UnlockKeyId")+ .HasColumnType("uuid");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("ArchivedAt")+ .HasDatabaseName("IX_UserUnlockKeysHistory_ArchivedAt");++ b.HasIndex("UserId", "Type", "ArchivedAt")+ .HasDatabaseName("IX_UserUnlockKeysHistory_UserId_Type_ArchivedAt");++ b.ToTable("UserUnlockKeysHistory", (string)null);+ });++ modelBuilder.Entity("AliasServerDb.VaultBlobObject", b =>+ {+ b.Property<Guid>("ManifestId")+ .HasColumnType("uuid");++ b.Property<string>("Hash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<string>("Category")+ .IsRequired()+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<byte[]>("EncryptedData")+ .IsRequired()+ .HasColumnType("bytea");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<int>("SizeBytes")+ .HasColumnType("integer");++ b.HasKey("ManifestId", "Hash");++ b.ToTable("VaultBlobObjects");+ });++ modelBuilder.Entity("AliasServerDb.VaultBlobReference", b =>+ {+ b.Property<Guid>("ManifestId")+ .HasColumnType("uuid");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<string>("BlobHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.HasKey("ManifestId", "RevisionNumber", "BlobHash");++ b.ToTable("VaultBlobReferences");+ });++ modelBuilder.Entity("AliasServerDb.VaultDataBucket", b =>+ {+ b.Property<Guid>("ManifestId")+ .HasColumnType("uuid");++ b.Property<string>("Category")+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<string>("CiphertextHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<byte[]>("EncryptedData")+ .IsRequired()+ .HasColumnType("bytea");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("ManifestId", "Category");++ b.ToTable("VaultDataBuckets");+ });++ modelBuilder.Entity("AliasServerDb.VaultDataBucketsHistory", b =>+ {+ b.Property<Guid>("ManifestId")+ .HasColumnType("uuid");++ b.Property<string>("Category")+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<string>("CiphertextHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<byte[]>("EncryptedData")+ .IsRequired()+ .HasColumnType("bytea");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("ManifestId", "Category", "RevisionNumber");++ b.ToTable("VaultDataBucketsHistory");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifest", b =>+ {+ b.Property<Guid>("ManifestId")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<string>("Client")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("CredentialsCount")+ .HasColumnType("integer");++ b.Property<int>("EmailClaimsCount")+ .HasColumnType("integer");++ b.Property<string>("EncryptionSettings")+ .HasColumnType("text");++ b.Property<string>("EncryptionType")+ .HasColumnType("text");++ b.Property<int>("FileSize")+ .HasColumnType("integer");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<byte[]>("ManifestBlob")+ .HasColumnType("bytea");++ b.Property<string>("ManifestCiphertextHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<Guid>("OwnerGroupId")+ .HasColumnType("uuid");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<string>("Salt")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("StorageFormat")+ .IsRequired()+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("VaultBlob")+ .HasColumnType("text");++ b.Property<string>("Verifier")+ .HasMaxLength(1000)+ .HasColumnType("character varying(1000)");++ b.Property<string>("Version")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("ManifestId");++ b.HasIndex("OwnerGroupId");++ b.ToTable("VaultManifests");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestAccessKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<int?>("AccountKeyVersion")+ .HasColumnType("integer");++ b.Property<string>("Algorithm")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedVek")+ .IsRequired()+ .HasColumnType("text");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<DateTime?>("LastUsedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Metadata")+ .HasColumnType("jsonb");++ b.Property<string>("Type")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<Guid?>("UserGrantKeyId")+ .HasColumnType("uuid");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<Guid>("VaultManifestId")+ .HasColumnType("uuid");++ b.HasKey("Id");++ b.HasIndex("UserGrantKeyId");++ b.HasIndex("VaultManifestId")+ .HasDatabaseName("IX_VaultManifestAccessKeys_VaultManifestId");++ b.HasIndex("UserId", "Type", "VaultManifestId", "KeyVersion")+ .IsUnique()+ .HasDatabaseName("UX_VaultManifestAccessKeys_UserId_Type_Manifest_Version");++ b.ToTable("VaultManifestAccessKeys");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<string>("Algorithm")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("IsPrimary")+ .HasColumnType("boolean");++ b.Property<string>("PublicKey")+ .IsRequired()+ .HasMaxLength(2000)+ .HasColumnType("character varying(2000)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<Guid>("VaultManifestId")+ .HasColumnType("uuid");++ b.HasKey("Id");++ b.HasIndex("VaultManifestId")+ .IsUnique()+ .HasDatabaseName("UX_VaultManifestDeliveryKeys_Manifest_Primary")+ .HasFilter("\"IsPrimary\"");++ b.HasIndex("VaultManifestId", "IsPrimary");++ b.ToTable("VaultManifestDeliveryKeys");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestsHistory", b =>+ {+ b.Property<Guid>("ManifestId")+ .HasColumnType("uuid");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<string>("Client")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("CredentialsCount")+ .HasColumnType("integer");++ b.Property<int>("EmailClaimsCount")+ .HasColumnType("integer");++ b.Property<string>("EncryptionSettings")+ .HasColumnType("text");++ b.Property<string>("EncryptionType")+ .HasColumnType("text");++ b.Property<int>("FileSize")+ .HasColumnType("integer");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<byte[]>("ManifestBlob")+ .HasColumnType("bytea");++ b.Property<string>("ManifestCiphertextHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<string>("Salt")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("StorageFormat")+ .IsRequired()+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("VaultBlob")+ .HasColumnType("text");++ b.Property<string>("Verifier")+ .HasMaxLength(1000)+ .HasColumnType("character varying(1000)");++ b.Property<string>("Version")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("ManifestId", "RevisionNumber");++ b.ToTable("VaultManifestsHistory", (string)null);+ });++ modelBuilder.Entity("AliasVault.WorkerStatus.Database.WorkerServiceStatus", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("CurrentStatus")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<DateTime>("Heartbeat")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("ServiceName")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.ToTable("WorkerServiceStatuses");+ });++ modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("FriendlyName")+ .HasColumnType("text");++ b.Property<string>("Xml")+ .HasColumnType("text");++ b.HasKey("Id");++ b.ToTable("DataProtectionKeys");+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("ClaimType")+ .HasColumnType("text");++ b.Property<string>("ClaimValue")+ .HasColumnType("text");++ b.Property<string>("UserId")+ .HasColumnType("text");++ b.HasKey("Id");++ b.ToTable("UserClaims", (string)null);+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>+ {+ b.Property<string>("UserId")+ .HasColumnType("text");++ b.Property<string>("LoginProvider")+ .HasColumnType("text");++ b.Property<string>("Name")+ .HasColumnType("text");++ b.Property<string>("Value")+ .HasColumnType("text");++ b.HasKey("UserId", "LoginProvider", "Name");++ b.ToTable("UserTokens", (string)null);+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>+ {+ b.HasOne("AliasServerDb.Group", "PersonalGroup")+ .WithOne()+ .HasForeignKey("AliasServerDb.AliasVaultUser", "PersonalGroupId")+ .OnDelete(DeleteBehavior.Restrict)+ .IsRequired();++ b.Navigation("PersonalGroup");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUserRefreshToken", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.CapabilityRule", b =>+ {+ b.HasOne("AliasServerDb.Group", "Group")+ .WithMany()+ .HasForeignKey("GroupId")+ .OnDelete(DeleteBehavior.Cascade);++ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade);++ b.Navigation("Group");++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.ClientAction", b =>+ {+ b.HasOne("AliasServerDb.Group", "TargetGroup")+ .WithMany()+ .HasForeignKey("TargetGroupId")+ .OnDelete(DeleteBehavior.Cascade);++ b.HasOne("AliasServerDb.AliasVaultUser", "TargetUser")+ .WithMany()+ .HasForeignKey("TargetUserId")+ .OnDelete(DeleteBehavior.Cascade);++ b.Navigation("TargetGroup");++ b.Navigation("TargetUser");+ });++ modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>+ {+ b.HasOne("AliasServerDb.Email", "Email")+ .WithMany("Attachments")+ .HasForeignKey("EmailId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Email");+ });++ modelBuilder.Entity("AliasServerDb.EmailClaimLink", b =>+ {+ b.HasOne("AliasServerDb.EmailClaim", "EmailClaim")+ .WithMany("Links")+ .HasForeignKey("EmailClaimId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.VaultManifest", "VaultManifest")+ .WithMany()+ .HasForeignKey("VaultManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("EmailClaim");++ b.Navigation("VaultManifest");+ });++ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>+ {+ b.HasOne("AliasServerDb.Email", "Email")+ .WithMany("DecryptionKeys")+ .HasForeignKey("EmailId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "VaultManifestDeliveryKey")+ .WithMany("DecryptionKeys")+ .HasForeignKey("VaultManifestDeliveryKeyId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired()+ .HasConstraintName("FK_EmailDecryptionKeys_VaultManifestDeliveryKeys_DeliveryKeyId");++ b.Navigation("Email");++ b.Navigation("VaultManifestDeliveryKey");+ });++ modelBuilder.Entity("AliasServerDb.EmailPart", b =>+ {+ b.HasOne("AliasServerDb.Email", "Email")+ .WithMany("Parts")+ .HasForeignKey("EmailId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Email");+ });++ modelBuilder.Entity("AliasServerDb.GroupInvitation", b =>+ {+ b.HasOne("AliasServerDb.Group", "Group")+ .WithMany()+ .HasForeignKey("GroupId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.AliasVaultUser", "Invitee")+ .WithMany()+ .HasForeignKey("InviteeUserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.AliasVaultUser", "Inviter")+ .WithMany()+ .HasForeignKey("InviterUserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.UserGrantKey", "UserGrantKey")+ .WithMany()+ .HasForeignKey("UserGrantKeyId")+ .OnDelete(DeleteBehavior.SetNull);++ b.Navigation("Group");++ b.Navigation("Invitee");++ b.Navigation("Inviter");++ b.Navigation("UserGrantKey");+ });++ modelBuilder.Entity("AliasServerDb.GroupMember", b =>+ {+ b.HasOne("AliasServerDb.Group", "Group")+ .WithMany("Members")+ .HasForeignKey("GroupId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Group");++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.MobileLoginRequest", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade);++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.RateLimit", b =>+ {+ b.HasOne("AliasServerDb.Group", "Group")+ .WithMany()+ .HasForeignKey("GroupId")+ .OnDelete(DeleteBehavior.Cascade);++ b.Navigation("Group");+ });++ modelBuilder.Entity("AliasServerDb.UserGrantKey", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.UserUnlockKey", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.UserUnlockKeysHistory", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.VaultBlobObject", b =>+ {+ b.HasOne("AliasServerDb.VaultManifest", "Manifest")+ .WithMany()+ .HasForeignKey("ManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Manifest");+ });++ modelBuilder.Entity("AliasServerDb.VaultBlobReference", b =>+ {+ b.HasOne("AliasServerDb.VaultManifest", "Manifest")+ .WithMany()+ .HasForeignKey("ManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Manifest");+ });++ modelBuilder.Entity("AliasServerDb.VaultDataBucket", b =>+ {+ b.HasOne("AliasServerDb.VaultManifest", "Manifest")+ .WithMany()+ .HasForeignKey("ManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Manifest");+ });++ modelBuilder.Entity("AliasServerDb.VaultDataBucketsHistory", b =>+ {+ b.HasOne("AliasServerDb.VaultDataBucket", "Bucket")+ .WithMany()+ .HasForeignKey("ManifestId", "Category")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Bucket");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifest", b =>+ {+ b.HasOne("AliasServerDb.Group", "OwnerGroup")+ .WithMany()+ .HasForeignKey("OwnerGroupId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("OwnerGroup");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestAccessKey", b =>+ {+ b.HasOne("AliasServerDb.UserGrantKey", "UserGrantKey")+ .WithMany()+ .HasForeignKey("UserGrantKeyId")+ .OnDelete(DeleteBehavior.SetNull);++ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany("VaultManifestAccessKeys")+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");++ b.Navigation("UserGrantKey");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>+ {+ b.HasOne("AliasServerDb.VaultManifest", "VaultManifest")+ .WithMany()+ .HasForeignKey("VaultManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("VaultManifest");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestsHistory", b =>+ {+ b.HasOne("AliasServerDb.VaultManifest", "Manifest")+ .WithMany()+ .HasForeignKey("ManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Manifest");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>+ {+ b.Navigation("VaultManifestAccessKeys");+ });++ modelBuilder.Entity("AliasServerDb.Email", b =>+ {+ b.Navigation("Attachments");++ b.Navigation("DecryptionKeys");++ b.Navigation("Parts");+ });++ modelBuilder.Entity("AliasServerDb.EmailClaim", b =>+ {+ b.Navigation("Links");+ });++ modelBuilder.Entity("AliasServerDb.Group", b =>+ {+ b.Navigation("Members");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>+ {+ b.Navigation("DecryptionKeys");+ });+#pragma warning restore 612, 618+ }+ }+}diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260917141654_RekeyVaultBlobObjectsOnManifest.cs b/apps/server/Databases/AliasServerDb/Migrations/20260917141654_RekeyVaultBlobObjectsOnManifest.csnew file mode 100644index 000000000..a7c29b899--- /dev/null+++ b/apps/server/Databases/AliasServerDb/Migrations/20260917141654_RekeyVaultBlobObjectsOnManifest.cs@@ -0,0 +1,140 @@+using System;+using Microsoft.EntityFrameworkCore.Migrations;++#nullable disable++namespace AliasServerDb.Migrations+{+ /// <inheritdoc />+ public partial class RekeyVaultBlobObjectsOnManifest : Migration+ {+ /// <inheritdoc />+ protected override void Up(MigrationBuilder migrationBuilder)+ {+ migrationBuilder.DropForeignKey(+ name: "FK_VaultBlobObjects_AliasVaultUsers_OwnerUserId",+ table: "VaultBlobObjects");++ migrationBuilder.DropPrimaryKey(+ name: "PK_VaultBlobObjects",+ table: "VaultBlobObjects");++ migrationBuilder.DropIndex(+ name: "IX_VaultBlobObjects_OwnerUserId_Category",+ table: "VaultBlobObjects");++ migrationBuilder.AddColumn<Guid>(+ name: "ManifestId",+ table: "VaultBlobObjects",+ type: "uuid",+ nullable: true);++ // A blob moves to every manifest that references its hash. When several members stored the same hash, the+ // copy of the manifest's own user wins, then the oldest. A personal manifest only takes its own user's copy.+ migrationBuilder.Sql("""+ INSERT INTO "VaultBlobObjects" ("Hash", "OwnerUserId", "ManifestId", "Category", "EncryptedData", "SizeBytes", "KeyVersion", "CreatedAt")+ SELECT DISTINCT ON (r."ManifestId", b."Hash") b."Hash", b."OwnerUserId", r."ManifestId", b."Category", b."EncryptedData", b."SizeBytes", b."KeyVersion", b."CreatedAt"+ FROM "VaultBlobObjects" b+ JOIN (SELECT DISTINCT "ManifestId", "BlobHash" FROM "VaultBlobReferences") r ON r."BlobHash" = b."Hash"+ JOIN "VaultManifests" m ON m."ManifestId" = r."ManifestId"+ JOIN "Groups" g ON g."Id" = m."OwnerGroupId"+ JOIN "AliasVaultUsers" u ON u."Id" = b."OwnerUserId"+ WHERE g."Type" = 1 OR u."PersonalGroupId" = m."OwnerGroupId"+ ORDER BY r."ManifestId", b."Hash", (u."PersonalGroupId" = m."OwnerGroupId") DESC, b."CreatedAt";+ """);++ // The user-keyed originals go, and with them any blob no revision references: those are what the sweeper+ // deletes anyway, and a client that still wants one is told it is missing and uploads it again.+ migrationBuilder.Sql("""DELETE FROM "VaultBlobObjects" WHERE "ManifestId" IS NULL;""");++ migrationBuilder.DropColumn(+ name: "OwnerUserId",+ table: "VaultBlobObjects");++ migrationBuilder.AlterColumn<Guid>(+ name: "ManifestId",+ table: "VaultBlobObjects",+ type: "uuid",+ nullable: false,+ oldClrType: typeof(Guid),+ oldType: "uuid",+ oldNullable: true);++ migrationBuilder.AddPrimaryKey(+ name: "PK_VaultBlobObjects",+ table: "VaultBlobObjects",+ columns: new[] { "ManifestId", "Hash" });++ migrationBuilder.AddForeignKey(+ name: "FK_VaultBlobObjects_VaultManifests_ManifestId",+ table: "VaultBlobObjects",+ column: "ManifestId",+ principalTable: "VaultManifests",+ principalColumn: "ManifestId",+ onDelete: ReferentialAction.Cascade);+ }++ /// <inheritdoc />+ protected override void Down(MigrationBuilder migrationBuilder)+ {+ migrationBuilder.DropForeignKey(+ name: "FK_VaultBlobObjects_VaultManifests_ManifestId",+ table: "VaultBlobObjects");++ migrationBuilder.DropPrimaryKey(+ name: "PK_VaultBlobObjects",+ table: "VaultBlobObjects");++ migrationBuilder.AddColumn<string>(+ name: "OwnerUserId",+ table: "VaultBlobObjects",+ type: "character varying(255)",+ maxLength: 255,+ nullable: true);++ // Each blob goes back to the earliest owner of the group that owns its manifest.+ migrationBuilder.Sql("""+ UPDATE "VaultBlobObjects" b SET "OwnerUserId" = (+ SELECT gm."UserId" FROM "VaultManifests" m+ JOIN "GroupMembers" gm ON gm."GroupId" = m."OwnerGroupId"+ WHERE m."ManifestId" = b."ManifestId" AND gm."Role" = 0+ ORDER BY gm."CreatedAt", gm."UserId" LIMIT 1);+ DELETE FROM "VaultBlobObjects" WHERE "OwnerUserId" IS NULL;+ DELETE FROM "VaultBlobObjects" a USING "VaultBlobObjects" b WHERE a."Hash" = b."Hash" AND a."OwnerUserId" = b."OwnerUserId" AND a."ManifestId" > b."ManifestId";+ """);++ migrationBuilder.DropColumn(+ name: "ManifestId",+ table: "VaultBlobObjects");++ migrationBuilder.AlterColumn<string>(+ name: "OwnerUserId",+ table: "VaultBlobObjects",+ type: "character varying(255)",+ maxLength: 255,+ nullable: false,+ oldClrType: typeof(string),+ oldType: "character varying(255)",+ oldMaxLength: 255,+ oldNullable: true);++ migrationBuilder.AddPrimaryKey(+ name: "PK_VaultBlobObjects",+ table: "VaultBlobObjects",+ columns: new[] { "Hash", "OwnerUserId" });++ migrationBuilder.CreateIndex(+ name: "IX_VaultBlobObjects_OwnerUserId_Category",+ table: "VaultBlobObjects",+ columns: new[] { "OwnerUserId", "Category" });++ migrationBuilder.AddForeignKey(+ name: "FK_VaultBlobObjects_AliasVaultUsers_OwnerUserId",+ table: "VaultBlobObjects",+ column: "OwnerUserId",+ principalTable: "AliasVaultUsers",+ principalColumn: "Id",+ onDelete: ReferentialAction.Cascade);+ }+ }+}diff --git a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.csindex c7abb6d44..4ee9002ae 100644--- a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs+++ b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs@@ -1207,14 +1207,13 @@ namespace AliasServerDb.MigrationsmodelBuilder.Entity("AliasServerDb.VaultBlobObject", b =>{+ b.Property<Guid>("ManifestId")+ .HasColumnType("uuid");+b.Property<string>("Hash").HasMaxLength(64).HasColumnType("character varying(64)");- b.Property<string>("OwnerUserId")- .HasMaxLength(255)- .HasColumnType("character varying(255)");-b.Property<string>("Category").IsRequired().HasMaxLength(20)@@ -1233,9 +1232,7 @@ namespace AliasServerDb.Migrationsb.Property<int>("SizeBytes").HasColumnType("integer");- b.HasKey("Hash", "OwnerUserId");-- b.HasIndex("OwnerUserId", "Category");+ b.HasKey("ManifestId", "Hash");b.ToTable("VaultBlobObjects");});@@ -1881,13 +1878,13 @@ namespace AliasServerDb.MigrationsmodelBuilder.Entity("AliasServerDb.VaultBlobObject", b =>{- b.HasOne("AliasServerDb.AliasVaultUser", "User")+ b.HasOne("AliasServerDb.VaultManifest", "Manifest").WithMany()- .HasForeignKey("OwnerUserId")+ .HasForeignKey("ManifestId").OnDelete(DeleteBehavior.Cascade).IsRequired();- b.Navigation("User");+ b.Navigation("Manifest");});modelBuilder.Entity("AliasServerDb.VaultBlobReference", b =>diff --git a/apps/server/Databases/AliasServerDb/Retention/VaultBlobRetentionPolicy.cs b/apps/server/Databases/AliasServerDb/Retention/VaultBlobRetentionPolicy.csindex 4ea1b3a59..3546222e3 100644--- a/apps/server/Databases/AliasServerDb/Retention/VaultBlobRetentionPolicy.cs+++ b/apps/server/Databases/AliasServerDb/Retention/VaultBlobRetentionPolicy.cs@@ -11,7 +11,7 @@ using Microsoft.EntityFrameworkCore;/// <summary>/// The garbage collection rule for <see cref="VaultBlobObject"/> rows.///-/// A blob is reachable as long as any manifest revision, current or in history, still references it.+/// A blob is reachable as long as any revision of its manifest, current or in history, still references it./// </summary>public static class VaultBlobRetentionPolicy{@@ -23,14 +23,14 @@ public static class VaultBlobRetentionPolicypublic static int EffectiveGraceHours(int configuredHours) => Math.Max(configuredHours, 0);/// <summary>- /// Narrows a query to the blob objects that no manifest revision references anymore.+ /// Narrows a query to the blob objects that no revision of their manifest references anymore./// </summary>/// <param name="blobs">The query over blob objects to narrow.</param>/// <param name="references">The references to check against.</param>/// <returns>The query narrowed to unreferenced blobs.</returns>public static IQueryable<VaultBlobObject> Unreferenced(IQueryable<VaultBlobObject> blobs, IQueryable<VaultBlobReference> references){- return blobs.Where(b => !references.Any(r => r.BlobHash == b.Hash));+ return blobs.Where(b => !references.Any(r => r.ManifestId == b.ManifestId && r.BlobHash == b.Hash));}/// <summary>diff --git a/apps/server/Databases/AliasServerDb/VaultBlobObject.cs b/apps/server/Databases/AliasServerDb/VaultBlobObject.csindex ec2c65d57..0d66f549a 100644--- a/apps/server/Databases/AliasServerDb/VaultBlobObject.cs+++ b/apps/server/Databases/AliasServerDb/VaultBlobObject.cs@@ -15,22 +15,21 @@ using System.ComponentModel.DataAnnotations.Schema;public class VaultBlobObject{/// <summary>- /// Gets or sets the per-user salted SHA-256 (hex) of the plaintext payload.+ /// Gets or sets the manifest this blob belongs to. Part of the composite PK./// </summary>- [StringLength(64)]- public string Hash { get; set; } = null!;+ public Guid ManifestId { get; set; }/// <summary>- /// Gets or sets the user ID.+ /// Gets or sets the navigation property to the manifest./// </summary>- [StringLength(255)]- public string OwnerUserId { get; set; } = null!;+ [ForeignKey("ManifestId")]+ public virtual VaultManifest Manifest { get; set; } = null!;/// <summary>- /// Gets or sets the navigation property to the user.+ /// Gets or sets the per-manifest salted SHA-256 (hex) of the plaintext payload. Part of the composite PK./// </summary>- [ForeignKey("OwnerUserId")]- public virtual AliasVaultUser User { get; set; } = null!;+ [StringLength(64)]+ public string Hash { get; set; } = null!;/// <summary>/// Gets or sets the blob category.diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/Blob.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/Blob.csindex 43d8f9ad9..660c8bfa0 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/Blob.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/Blob.cs@@ -12,7 +12,7 @@ namespace AliasVault.Shared.Models.WebApi.V2.Vault;/// </summary>public class Blob{- /// <summary>Gets or sets the per-user salted SHA-256 hex of the plaintext.</summary>+ /// <summary>Gets or sets the per-manifest salted SHA-256 hex of the plaintext.</summary>public required string Hash { get; set; }/// <summary>Gets or sets the blob category ("favicon" or "attachment").</summary>diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobHashesRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobHashesRequest.csindex 29c20cbd1..881d90dc9 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobHashesRequest.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobHashesRequest.cs@@ -14,6 +14,9 @@ namespace AliasVault.Shared.Models.WebApi.V2.Vault;/// </summary>public class BlobHashesRequest{- /// <summary>Gets or sets the per-user salted SHA-256 hex hashes.</summary>+ /// <summary>Gets or sets the manifest the hashes belong to.</summary>+ public required Guid ManifestId { get; set; }++ /// <summary>Gets or sets the per-manifest salted SHA-256 hex hashes.</summary>public required List<string> Hashes { get; set; }}diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobReference.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobReference.csindex 8c55ddea8..6bfebaaaf 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobReference.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobReference.cs@@ -12,7 +12,7 @@ namespace AliasVault.Shared.Models.WebApi.V2.Vault;/// </summary>public class BlobReference{- /// <summary>Gets or sets the per-user salted SHA-256 hex of the plaintext.</summary>+ /// <summary>Gets or sets the per-manifest salted SHA-256 hex of the plaintext.</summary>public required string Hash { get; set; }/// <summary>Gets or sets the blob category (e.g. "favicon" or "attachment").</summary>diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobUploadRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobUploadRequest.csindex 341a2f348..0016b9133 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobUploadRequest.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/BlobUploadRequest.cs@@ -9,10 +9,13 @@ namespace AliasVault.Shared.Models.WebApi.V2.Vault;/// <summary>/// POST /v2/Vault/blobs. Batch-upload encrypted blobs ahead of a manifest upload. Idempotent per blob on-/// (hash, user). Clients chunk large blob sets across multiple calls to keep request bodies within server limits.+/// (manifest, hash). Clients chunk large blob sets across multiple calls to keep request bodies within server limits./// </summary>public class BlobUploadRequest{+ /// <summary>Gets or sets the manifest the blobs belong to.</summary>+ public required Guid ManifestId { get; set; }+/// <summary>Gets or sets the encrypted blobs to store.</summary>public required List<Blob> Blobs { get; set; }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 e9c961db1..e81ff29b2 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@@ -21,7 +21,8 @@ public class VaultWriteRequest/// <summary>Gets or sets the data buckets to upsert.</summary>public List<BucketWrite> Buckets { get; set; } = [];- /// <summary>Gets or sets the new blob objects the client is uploading for this write.</summary>+ /// <summary>Gets or sets the new blob objects the client is uploading for this write. Each is stored under every+ /// manifest in this write that references its hash.</summary>public List<Blob> NewBlobs { get; set; } = [];/// <summary>Gets or sets the email routing data to update server-side.</summary>diff --git a/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/Helpers/SeedData.cs b/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/Helpers/SeedData.csindex c49df6bae..95d8962a1 100644--- a/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/Helpers/SeedData.cs+++ b/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/Helpers/SeedData.cs@@ -47,7 +47,7 @@ public static class SeedDataawait SeedLogs(dbContext);await SeedAuthLogs(dbContext);await SeedUnlockKeyHistory(dbContext, testUser.User.Id);- SeedVaultBlobs(dbContext, testUser.Manifest, testUser.User.Id);+ SeedVaultBlobs(dbContext, testUser.Manifest);await dbContext.SaveChangesAsync();}@@ -149,9 +149,8 @@ public static class SeedData/// Seeds encrypted vault blobs together with the references that decide which of them the sweeper may delete./// </summary>/// <param name="dbContext">The database context.</param>- /// <param name="manifest">The test user's vault manifest.</param>- /// <param name="userId">The user that owns the blobs.</param>- private static void SeedVaultBlobs(AliasServerDbContext dbContext, VaultManifest manifest, string userId)+ /// <param name="manifest">The test user's vault manifest, which the blobs belong to.</param>+ private static void SeedVaultBlobs(AliasServerDbContext dbContext, VaultManifest manifest){// Move the current revision up so revision 1 can sit in history as a superseded revision.manifest.RevisionNumber = 2;@@ -165,11 +164,11 @@ public static class SeedData});dbContext.VaultBlobObjects.AddRange(- CreateTestBlob(userId, "referenced-current", TimeSpan.FromDays(-30)),- CreateTestBlob(userId, "referenced-history", TimeSpan.FromDays(-30)),- CreateTestBlob(userId, "stale-reference", TimeSpan.FromDays(-30)),- CreateTestBlob(userId, "orphan-expired", TimeSpan.FromDays(-30)),- CreateTestBlob(userId, "orphan-just-uploaded", TimeSpan.FromHours(-2)));+ CreateTestBlob(manifest.ManifestId, "referenced-current", TimeSpan.FromDays(-30)),+ CreateTestBlob(manifest.ManifestId, "referenced-history", TimeSpan.FromDays(-30)),+ CreateTestBlob(manifest.ManifestId, "stale-reference", TimeSpan.FromDays(-30)),+ CreateTestBlob(manifest.ManifestId, "orphan-expired", TimeSpan.FromDays(-30)),+ CreateTestBlob(manifest.ManifestId, "orphan-just-uploaded", TimeSpan.FromHours(-2)));dbContext.VaultBlobReferences.AddRange(new VaultBlobReference { ManifestId = manifest.ManifestId, RevisionNumber = 2, BlobHash = "referenced-current" },@@ -180,17 +179,17 @@ public static class SeedData/// <summary>/// Creates an encrypted vault blob for the tests./// </summary>- /// <param name="userId">The user that owns the blob.</param>+ /// <param name="manifestId">The manifest the blob belongs to.</param>/// <param name="hash">The blob hash, also identifying the row in assertions.</param>/// <param name="uploadedAgo">How long ago the blob was uploaded.</param>/// <returns>VaultBlobObject.</returns>- private static VaultBlobObject CreateTestBlob(string userId, string hash, TimeSpan uploadedAgo)+ private static VaultBlobObject CreateTestBlob(Guid manifestId, string hash, TimeSpan uploadedAgo){var uploadedAt = DateTime.UtcNow.Add(uploadedAgo);return new VaultBlobObject{+ ManifestId = manifestId,Hash = hash,- OwnerUserId = userId,Category = "logo",EncryptedData = [1, 2, 3, 4],SizeBytes = 4,diff --git a/apps/server/Tests/AliasVault.UnitTests/Vault/VaultBlobRetentionPolicyTests.cs b/apps/server/Tests/AliasVault.UnitTests/Vault/VaultBlobRetentionPolicyTests.csindex 9164f87d6..1ca0b56dc 100644--- a/apps/server/Tests/AliasVault.UnitTests/Vault/VaultBlobRetentionPolicyTests.cs+++ b/apps/server/Tests/AliasVault.UnitTests/Vault/VaultBlobRetentionPolicyTests.cs@@ -31,23 +31,24 @@ public class VaultBlobRetentionPolicyTests}/// <summary>- /// Test that a blob stays reachable while any revision references it, whichever revision that is, and that the- /// owner of the stored copy plays no part: a shared manifest's members derive the same hash for the same bytes.+ /// Test that a blob stays reachable while any revision of its own manifest references it, whichever revision+ /// that is, and that a reference from another manifest does not keep it alive./// </summary>[Test]public void UnreferencedOnlyMatchesBlobsNoRevisionHolds(){- var blobs = new[] { Blob("current"), Blob("history"), Blob("other-user"), Blob("orphan") }.AsQueryable();+ var manifestId = Guid.NewGuid();+ var blobs = new[] { Blob(manifestId, "current"), Blob(manifestId, "history"), Blob(manifestId, "other-manifest"), Blob(manifestId, "orphan") }.AsQueryable();var references = new[]{- Reference(Guid.Empty, 2, "current"),- Reference(Guid.Empty, 1, "history"),- Reference(Guid.NewGuid(), 5, "other-user"),+ Reference(manifestId, 2, "current"),+ Reference(manifestId, 1, "history"),+ Reference(Guid.NewGuid(), 5, "other-manifest"),}.AsQueryable();var unreferenced = VaultBlobRetentionPolicy.Unreferenced(blobs, references).Select(b => b.Hash);- Assert.That(unreferenced, Is.EquivalentTo(new[] { "orphan" }));+ Assert.That(unreferenced, Is.EquivalentTo(new[] { "other-manifest", "orphan" }));}/// <summary>@@ -77,14 +78,15 @@ public class VaultBlobRetentionPolicyTests/// <summary>/// Creates a blob object for the tests./// </summary>+ /// <param name="manifestId">The manifest the blob belongs to.</param>/// <param name="hash">The blob hash, also identifying the row in assertions.</param>/// <returns>VaultBlobObject.</returns>- private static VaultBlobObject Blob(string hash)+ private static VaultBlobObject Blob(Guid manifestId, string hash){return new VaultBlobObject{+ ManifestId = manifestId,Hash = hash,- OwnerUserId = "user",Category = "logo",EncryptedData = [1, 2, 3, 4],SizeBytes = 4,