Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add separate encryption key to vault blobs (#2159)
Leendert de Borstcda74242fae3
diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultController.csindex a1b973f0a..d32933ece 100644--- a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs@@ -624,7 +624,6 @@ public class VaultController(}// Only allow overwriting the ciphertext if the user has no unlock key yet (as part of one-time legacy migration).- // TODO: when adding VEK rotation, overwrite will need to be made possible as well for the rotation flow itself.if (model.Overwrite && await context.UserUnlockKeys.AnyAsync(x => x.UserId == user.Id && x.Type == UnlockMethodType.Password)){return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_KEY_ALREADY_EXISTS, 400));@@ -716,6 +715,7 @@ public class VaultController(Hash = b.Hash,Category = b.Category,EncryptedDataBase64 = Convert.ToBase64String(b.EncryptedData),+ EncryptedBlobKey = b.EncryptedBlobKey,}).ToListAsync();@@ -911,6 +911,7 @@ public class VaultController({row.Category = dto.Category;row.EncryptedData = data!;+ row.EncryptedBlobKey = dto.EncryptedBlobKey;row.SizeBytes = data!.Length;}@@ -923,6 +924,7 @@ public class VaultController(ManifestId = manifestId,Category = dto.Category,EncryptedData = data!,+ EncryptedBlobKey = dto.EncryptedBlobKey,SizeBytes = data!.Length,CreatedAt = nowUtc,};diff --git a/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncService.cs b/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncService.csindex 4b0db7996..c97c77221 100644--- a/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncService.cs+++ b/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncService.cs@@ -9,6 +9,7 @@ namespace AliasVault.Client.Services.VaultSync;using System.Net;using System.Net.Http.Json;+using System.Security.Cryptography;using System.Text;using System.Text.Json;using AliasVault.Client.Services.Auth;@@ -353,7 +354,7 @@ public sealed class VaultSyncService(HttpClient httpClient, AuthService authServ}logger.LogInformation("[V2Push] Blob diff: {Total} blob(s) across {Manifests} manifest(s), uploading {Personal} personal and {Shared} shared.", allBlobHashes.Count, vault.Manifests.Count, personalToUpload.Count, sharedToUpload.Count);- var uploadedCiphertexts = new Dictionary<string, string>(StringComparer.Ordinal);+ var uploadedCiphertexts = new Dictionary<string, Blob>(StringComparer.Ordinal);await UploadBlobsAsync(blobEntries, personalToUpload, migration is not null, uploadedCiphertexts);await UploadBlobsAsync(blobEntries, sharedToUpload, false, uploadedCiphertexts);@@ -417,7 +418,7 @@ public sealed class VaultSyncService(HttpClient httpClient, AuthService authServ// Every referenced hash is now known to be on the server; refresh the diff baseline and the cache.state.ServerBlobHashes.Clear();state.ServerBlobHashes.UnionWith(allBlobHashes);- var refreshedCache = new Dictionary<string, string>(StringComparer.Ordinal);+ var refreshedCache = new Dictionary<string, Blob>(StringComparer.Ordinal);foreach (var hash in allBlobHashes){if (uploadedCiphertexts.TryGetValue(hash, out var uploaded))@@ -431,9 +432,9 @@ public sealed class VaultSyncService(HttpClient httpClient, AuthService authServ}state.BlobCipherCache.Clear();- foreach (var (hash, ciphertext) in refreshedCache)+ foreach (var (hash, blob) in refreshedCache){- state.BlobCipherCache[hash] = ciphertext;+ state.BlobCipherCache[hash] = blob;}state.LastSnapshotWasLegacySqliteBlob = false;@@ -1073,19 +1074,19 @@ public sealed class VaultSyncService(HttpClient httpClient, AuthService authServvar blobs = await response.Content.ReadFromJsonAsync<List<Blob>>() ?? [];foreach (var blob in blobs){- cache[blob.Hash] = blob.EncryptedDataBase64;+ cache[blob.Hash] = blob;}logger.LogInformation("[V2Pull] Downloaded blob batch {Index}/{Total}: requested {Requested}, received {Received}.", index + 1, batches.Count, batch.Count, blobs.Count);}// Decrypt the referenced blobs and prune the cache to the referenced set, so it stays bounded by the current vault size.- var prunedCache = new Dictionary<string, string>(StringComparer.Ordinal);+ var prunedCache = new Dictionary<string, Blob>(StringComparer.Ordinal);var blobMap = new Dictionary<string, byte[]>(StringComparer.Ordinal);foreach (var reference in refs){var owner = refOwners[reference.Hash];- if (!cache.TryGetValue(reference.Hash, out var ciphertext))+ if (!cache.TryGetValue(reference.Hash, out var blob)){HandleUnavailableBlob(reference, owner, "is missing on the server");continue;@@ -1093,8 +1094,8 @@ public sealed class VaultSyncService(HttpClient httpClient, AuthService authServtry{- blobMap[reference.Hash] = await jsInteropService.SymmetricDecryptBase64ToBytes(ciphertext, owner.VaultEncryptionKey);- prunedCache[reference.Hash] = ciphertext;+ blobMap[reference.Hash] = await DecryptBlobAsync(blob, owner.VaultEncryptionKey);+ prunedCache[reference.Hash] = blob;}catch (JSException){@@ -1103,9 +1104,9 @@ public sealed class VaultSyncService(HttpClient httpClient, AuthService authServ}cache.Clear();- foreach (var (hash, ciphertext) in prunedCache)+ foreach (var (hash, blob) in prunedCache){- cache[hash] = ciphertext;+ cache[hash] = blob;}// The server demonstrably has every blob it just served or referenced, seed the upload diff with them.@@ -1114,6 +1115,18 @@ public sealed class VaultSyncService(HttpClient httpClient, AuthService authServreturn blobMap;}+ /// <summary>+ /// Decrypt a stored blob: its bytes open with the blob's own key, which opens with the manifest's VEK.+ /// </summary>+ /// <param name="blob">The blob as the server stores it.</param>+ /// <param name="vaultEncryptionKey">The VEK of the manifest that owns the blob (base64).</param>+ /// <returns>The plaintext bytes.</returns>+ private async Task<byte[]> DecryptBlobAsync(Blob blob, string vaultEncryptionKey)+ {+ var blobKey = await jsInteropService.SymmetricDecryptBase64ToBytes(blob.EncryptedBlobKey, vaultEncryptionKey);+ return await jsInteropService.SymmetricDecryptBase64ToBytes(blob.EncryptedDataBase64, Convert.ToBase64String(blobKey));+ }+/// <summary>/// A referenced blob that cannot be materialized. A personal attachment is fatal: materializing it as empty would/// propagate silent data loss on the next push. A favicon or a shared manifest's blob is skipped with a warning.@@ -1459,15 +1472,15 @@ public sealed class VaultSyncService(HttpClient httpClient, AuthService authServ}/// <summary>- /// Encrypt the given blobs, each with the key of the manifest that owns it, and upload them in size-capped batches- /// per manifest ahead of the manifest write.+ /// Encrypt the given blobs, each with a fresh key of its own that is itself encrypted with the VEK of the manifest+ /// that owns it, and upload them in size-capped batches 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>/// <param name="overwrite">Ask the server to replace the ciphertext of blobs it already has (the migration re-keys them).</param>- /// <param name="uploaded">Receives the uploaded ciphertext per hash, for the local cipher cache.</param>+ /// <param name="uploaded">Receives the uploaded blob per hash, for the local cipher cache.</param>/// <returns>Task.</returns>- private async Task UploadBlobsAsync(Dictionary<string, UploadBlobEntry> entries, IEnumerable<string> hashes, bool overwrite, Dictionary<string, string> uploaded)+ private async Task UploadBlobsAsync(Dictionary<string, UploadBlobEntry> entries, IEnumerable<string> hashes, bool overwrite, Dictionary<string, Blob> uploaded){foreach (var group in hashes.Where(entries.ContainsKey).GroupBy(hash => entries[hash].ManifestId)){@@ -1476,8 +1489,11 @@ public sealed class VaultSyncService(HttpClient httpClient, AuthService authServforeach (var hash in group){var entry = entries[hash];- var ciphertext = Convert.ToBase64String(await jsInteropService.SymmetricEncryptBytes(entry.Bytes, Convert.FromBase64String(entry.VaultEncryptionKey)));- uploaded[hash] = ciphertext;+ var blobKey = RandomNumberGenerator.GetBytes(32);+ var ciphertext = Convert.ToBase64String(await jsInteropService.SymmetricEncryptBytes(entry.Bytes, blobKey));+ var encryptedBlobKey = Convert.ToBase64String(await jsInteropService.SymmetricEncryptBytes(blobKey, Convert.FromBase64String(entry.VaultEncryptionKey)));+ var blob = new Blob { Hash = hash, Category = entry.Kind, EncryptedDataBase64 = ciphertext, EncryptedBlobKey = encryptedBlobKey };+ uploaded[hash] = blob;// Flush before adding when this blob would take the request past either bound.if (batch.Count > 0 && (batchChars + ciphertext.Length > BlobTransferBatchMaxChars || batch.Count >= BlobTransferBatchMaxCount))@@ -1487,7 +1503,7 @@ public sealed class VaultSyncService(HttpClient httpClient, AuthService authServbatchChars = 0;}- batch.Add(new Blob { Hash = hash, Category = entry.Kind, EncryptedDataBase64 = ciphertext });+ batch.Add(blob);batchChars += ciphertext.Length;}diff --git a/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncState.cs b/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncState.csindex d20f969bc..ec9bcc1de 100644--- a/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncState.cs+++ b/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncState.cs@@ -8,6 +8,7 @@namespace AliasVault.Client.Services.VaultSync;using AliasVault.Client.Services.VaultSync.Models;+using AliasVault.Shared.Models.WebApi.V2.Vault;/// <summary>/// The client's sync state as recorded by the last pull.@@ -51,9 +52,9 @@ public sealed class VaultSyncStatepublic HashSet<string> ServerBlobHashes { get; } = new(StringComparer.Ordinal);/// <summary>- /// Gets the encrypted blob cache (hash to base64 ciphertext), pruned to the referenced set on every pull.+ /// Gets the encrypted blob cache (hash to the blob as the server stores it), pruned to the referenced set on every pull./// </summary>- public Dictionary<string, string> BlobCipherCache { get; } = new(StringComparer.Ordinal);+ public Dictionary<string, Blob> BlobCipherCache { get; } = new(StringComparer.Ordinal);/// <summary>/// Gets the shared manifests this session holds a grant on, keyed by manifest id.diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260810093922_ManifestStorageAndGroupOwnership.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260810093922_ManifestStorageAndGroupOwnership.Designer.csindex 42eece32a..713c1a768 100644--- a/apps/server/Databases/AliasServerDb/Migrations/20260810093922_ManifestStorageAndGroupOwnership.Designer.cs+++ b/apps/server/Databases/AliasServerDb/Migrations/20260810093922_ManifestStorageAndGroupOwnership.Designer.cs@@ -1015,6 +1015,11 @@ namespace AliasServerDb.Migrationsb.Property<DateTime>("CreatedAt").HasColumnType("timestamp with time zone");+ b.Property<string>("EncryptedBlobKey")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");+b.Property<byte[]>("EncryptedData").IsRequired().HasColumnType("bytea");diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260810093922_ManifestStorageAndGroupOwnership.cs b/apps/server/Databases/AliasServerDb/Migrations/20260810093922_ManifestStorageAndGroupOwnership.csindex e0121c9fc..10f7fc3e3 100644--- a/apps/server/Databases/AliasServerDb/Migrations/20260810093922_ManifestStorageAndGroupOwnership.cs+++ b/apps/server/Databases/AliasServerDb/Migrations/20260810093922_ManifestStorageAndGroupOwnership.cs@@ -563,6 +563,7 @@ namespace AliasServerDb.MigrationsHash = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),Category = table.Column<string>(type: "character varying(20)", maxLength: 20, nullable: false),EncryptedData = table.Column<byte[]>(type: "bytea", nullable: false),+ EncryptedBlobKey = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: false),SizeBytes = table.Column<int>(type: "integer", nullable: false),KeyVersion = table.Column<int>(type: "integer", nullable: false, defaultValue: 0),CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260810154523_EmailMultiManifestAndStorageV2.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260810154523_EmailMultiManifestAndStorageV2.Designer.csindex 00de722b5..7e75d803f 100644--- a/apps/server/Databases/AliasServerDb/Migrations/20260810154523_EmailMultiManifestAndStorageV2.Designer.cs+++ b/apps/server/Databases/AliasServerDb/Migrations/20260810154523_EmailMultiManifestAndStorageV2.Designer.cs@@ -1040,6 +1040,11 @@ namespace AliasServerDb.Migrationsb.Property<DateTime>("CreatedAt").HasColumnType("timestamp with time zone");+ b.Property<string>("EncryptedBlobKey")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");+b.Property<byte[]>("EncryptedData").IsRequired().HasColumnType("bytea");diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260817222545_ReorderTableColumns.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260817222545_ReorderTableColumns.Designer.csindex 57147d1c7..cad9f2044 100644--- a/apps/server/Databases/AliasServerDb/Migrations/20260817222545_ReorderTableColumns.Designer.cs+++ b/apps/server/Databases/AliasServerDb/Migrations/20260817222545_ReorderTableColumns.Designer.cs@@ -1040,6 +1040,11 @@ namespace AliasServerDb.Migrationsb.Property<DateTime>("CreatedAt").HasColumnType("timestamp with time zone");+ b.Property<string>("EncryptedBlobKey")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");+b.Property<byte[]>("EncryptedData").IsRequired().HasColumnType("bytea");diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260820120455_AddGroupInvitationsClientActionsAndCapabilityRules.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260820120455_AddGroupInvitationsClientActionsAndCapabilityRules.Designer.csindex fcf860fea..23f6c749f 100644--- a/apps/server/Databases/AliasServerDb/Migrations/20260820120455_AddGroupInvitationsClientActionsAndCapabilityRules.Designer.cs+++ b/apps/server/Databases/AliasServerDb/Migrations/20260820120455_AddGroupInvitationsClientActionsAndCapabilityRules.Designer.cs@@ -1225,6 +1225,11 @@ namespace AliasServerDb.Migrationsb.Property<DateTime>("CreatedAt").HasColumnType("timestamp with time zone");+ b.Property<string>("EncryptedBlobKey")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");+b.Property<byte[]>("EncryptedData").IsRequired().HasColumnType("bytea");diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260917154825_MobileLoginRequestVerification.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260917154825_MobileLoginRequestVerification.Designer.csindex e541cb521..e6a9164bf 100644--- a/apps/server/Databases/AliasServerDb/Migrations/20260917154825_MobileLoginRequestVerification.Designer.cs+++ b/apps/server/Databases/AliasServerDb/Migrations/20260917154825_MobileLoginRequestVerification.Designer.cs@@ -1245,6 +1245,11 @@ namespace AliasServerDb.Migrationsb.Property<DateTime>("CreatedAt").HasColumnType("timestamp with time zone");+ b.Property<string>("EncryptedBlobKey")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");+b.Property<byte[]>("EncryptedData").IsRequired().HasColumnType("bytea");diff --git a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.csindex 0a53a0109..8ed92f225 100644--- a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs+++ b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs@@ -1242,6 +1242,11 @@ namespace AliasServerDb.Migrationsb.Property<DateTime>("CreatedAt").HasColumnType("timestamp with time zone");+ b.Property<string>("EncryptedBlobKey")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");+b.Property<byte[]>("EncryptedData").IsRequired().HasColumnType("bytea");diff --git a/apps/server/Databases/AliasServerDb/VaultBlobObject.cs b/apps/server/Databases/AliasServerDb/VaultBlobObject.csindex 0d66f549a..c6cccbe64 100644--- a/apps/server/Databases/AliasServerDb/VaultBlobObject.cs+++ b/apps/server/Databases/AliasServerDb/VaultBlobObject.cs@@ -38,17 +38,23 @@ public class VaultBlobObjectpublic required string Category { get; set; }/// <summary>- /// Gets or sets the encrypted blob payload (AES-GCM ciphertext bytes).+ /// Gets or sets the encrypted blob payload (AES-GCM ciphertext bytes), encrypted with the blob's own key./// </summary>public required byte[] EncryptedData { get; set; }+ /// <summary>+ /// Gets or sets the blob's own key, encrypted with the manifest's VEK.+ /// </summary>+ [StringLength(255)]+ public required string EncryptedBlobKey { get; set; }+/// <summary>/// Gets or sets the size of the encrypted payload in bytes (cached for cheap metrics)./// </summary>public int SizeBytes { get; set; }/// <summary>- /// Gets or sets the version of the VEK that <see cref="EncryptedData"/> is encrypted with.+ /// Gets or sets the version of the VEK that <see cref="EncryptedBlobKey"/> is encrypted with./// </summary>public int KeyVersion { get; set; }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 660c8bfa0..721900fc9 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@@ -7,6 +7,8 @@namespace AliasVault.Shared.Models.WebApi.V2.Vault;+using System.ComponentModel.DataAnnotations;+/// <summary>/// Single encrypted blob payload./// </summary>@@ -18,6 +20,10 @@ public class Blob/// <summary>Gets or sets the blob category ("favicon" or "attachment").</summary>public required string Category { get; set; }- /// <summary>Gets or sets the encrypted bytes, base64-encoded for transport.</summary>+ /// <summary>Gets or sets the bytes encrypted with the blob's own key, base64-encoded for transport.</summary>public required string EncryptedDataBase64 { get; set; }++ /// <summary>Gets or sets the blob's own key, encrypted with the manifest's VEK.</summary>+ [StringLength(255, MinimumLength = 1)]+ public required string EncryptedBlobKey { get; set; }}diff --git a/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/Helpers/SeedData.cs b/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/Helpers/SeedData.csindex 95d8962a1..765ba0a06 100644--- a/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/Helpers/SeedData.cs+++ b/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/Helpers/SeedData.cs@@ -192,6 +192,7 @@ public static class SeedDataHash = hash,Category = "logo",EncryptedData = [1, 2, 3, 4],+ EncryptedBlobKey = "key",SizeBytes = 4,CreatedAt = uploadedAt,};diff --git a/apps/server/Tests/AliasVault.UnitTests/Vault/VaultBlobRetentionPolicyTests.cs b/apps/server/Tests/AliasVault.UnitTests/Vault/VaultBlobRetentionPolicyTests.csindex 1ca0b56dc..8ecec25e6 100644--- a/apps/server/Tests/AliasVault.UnitTests/Vault/VaultBlobRetentionPolicyTests.cs+++ b/apps/server/Tests/AliasVault.UnitTests/Vault/VaultBlobRetentionPolicyTests.cs@@ -89,6 +89,7 @@ public class VaultBlobRetentionPolicyTestsHash = hash,Category = "logo",EncryptedData = [1, 2, 3, 4],+ EncryptedBlobKey = "key",SizeBytes = 4,};}diff --git a/core/rust/src/vault_sync/blob_keys.rs b/core/rust/src/vault_sync/blob_keys.rsnew file mode 100644index 000000000..df3489349--- /dev/null+++ b/core/rust/src/vault_sync/blob_keys.rs@@ -0,0 +1,63 @@+//! Blob keys: every blob is encrypted with a random key of its own which is then encrypted with the manifest's VEK.++use serde::{Deserialize, Serialize};++use crate::crypto;+use crate::encoding::base64_decode;+use crate::error::VaultResult;++/// A blob as the server stores it.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub(crate) struct EncryptedBlob {+ /// Base64 of the bytes, encrypted with the blob key.+ pub encrypted_data_base64: String,+ /// The blob key, encrypted with the manifest's VEK.+ pub encrypted_blob_key: String,+}++/// Encrypt blob bytes with a fresh blob key, and that key with the manifest's VEK.+pub(crate) fn encrypt_blob(bytes: &[u8], vek: &str) -> VaultResult<EncryptedBlob> {+ let blob_key = zeroize::Zeroizing::new(crypto::generate_key_base64());+ Ok(EncryptedBlob { encrypted_data_base64: crypto::symmetric_encrypt_bytes(bytes, &blob_key)?, encrypted_blob_key: crypto::wrap_key(&blob_key, vek)? })+}++/// Decrypt a stored blob with the manifest's VEK.+pub(crate) fn decrypt_blob(blob: &EncryptedBlob, vek: &str) -> VaultResult<Vec<u8>> {+ let blob_key = crypto::unwrap_key(&blob.encrypted_blob_key, vek)?;+ crypto::symmetric_decrypt_bytes(&base64_decode(&blob.encrypted_data_base64)?, &blob_key)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_blob_opens_with_the_vek_through_its_own_key() {+ let vek = crypto::generate_key_base64();+ let blob = encrypt_blob(&[1, 2, 3, 4], &vek).unwrap();++ assert_eq!(decrypt_blob(&blob, &vek).unwrap(), vec![1, 2, 3, 4]);+ assert!(crypto::symmetric_decrypt_bytes(&base64_decode(&blob.encrypted_data_base64).unwrap(), &vek).is_err(), "the bytes are not encrypted with the VEK itself");+ assert!(decrypt_blob(&blob, &crypto::generate_key_base64()).is_err());+ }++ #[test]+ fn changing_the_vek_only_encrypts_the_blob_key_again() {+ let (old_vek, new_vek) = (crypto::generate_key_base64(), crypto::generate_key_base64());+ let blob = encrypt_blob(&[9; 64], &old_vek).unwrap();++ let blob_key = crypto::unwrap_key(&blob.encrypted_blob_key, &old_vek).unwrap();+ let rekeyed = EncryptedBlob { encrypted_data_base64: blob.encrypted_data_base64.clone(), encrypted_blob_key: crypto::wrap_key(&blob_key, &new_vek).unwrap() };++ assert_eq!(decrypt_blob(&rekeyed, &new_vek).unwrap(), vec![9; 64]);+ assert!(decrypt_blob(&rekeyed, &old_vek).is_err());+ }++ #[test]+ fn a_cached_blob_reads_back_as_it_was_written() {+ let blob = encrypt_blob(&[5], &crypto::generate_key_base64()).unwrap();+ let read: EncryptedBlob = serde_json::from_value(serde_json::to_value(&blob).unwrap()).unwrap();+ assert_eq!(read, blob);+ }+}diff --git a/core/rust/src/vault_sync/mod.rs b/core/rust/src/vault_sync/mod.rsindex 2c4ca5718..f3c7b2503 100644--- a/core/rust/src/vault_sync/mod.rs+++ b/core/rust/src/vault_sync/mod.rs@@ -1,5 +1,6 @@//! The vault sync engine that all AliasVault clients use to synchronize their vaults with the server.+mod blob_keys;pub(crate) mod db;mod email_routing;mod engine;diff --git a/core/rust/src/vault_sync/pull.rs b/core/rust/src/vault_sync/pull.rsindex 72fa159e0..9aba45e53 100644--- a/core/rust/src/vault_sync/pull.rs+++ b/core/rust/src/vault_sync/pull.rs@@ -7,6 +7,7 @@ use crate::vault_model::{id_key, ids_equal};use super::errors::{SyncError, SyncResult};use super::state::{self, Ctx};use super::types::{self, BlobDto, BlobHashesRequest, Db, EmailRoutingDto, GetResponse, ManifestDto, SharedManifestDto, StoredBlobRef};+use super::blob_keys::{self, EncryptedBlob};use super::{db, http, keys, legacy};use crate::crypto;use crate::vault_codec::{self, DataBucket, Manifest, MaterializeInput};@@ -253,7 +254,7 @@ async fn download_referenced_blobs(ctx: &Ctx, resolved: &[ResolvedManifest], fal}}- let mut cache: HashMap<String, String> = state::get(&ctx.host, state::VAULT_BLOB_CIPHER_CACHE).await?.unwrap_or_default();+ let mut cache: HashMap<String, EncryptedBlob> = state::get(&ctx.host, state::VAULT_BLOB_CIPHER_CACHE).await?.unwrap_or_default();let missing: Vec<StoredBlobRef> = refs.iter().filter(|r| !cache.contains_key(&r.hash)).cloned().collect();ctx.log(format!("[V2Pull] Blob refs: {} referenced, {} cached locally, {} to download.", refs.len(), refs.len() - missing.len(), missing.len())).await;@@ -268,22 +269,22 @@ async fn download_referenced_blobs(ctx: &Ctx, resolved: &[ResolvedManifest], fallet blobs: Vec<BlobDto> = http::post(&ctx.host, BLOBS_DOWNLOAD_ENDPOINT, &BlobHashesRequest { manifest_id, hashes: chunk.iter().map(|r| r.hash.clone()).collect() }, true).await?;ctx.log(format!("[V2Pull] Downloaded blob batch {}/{}: requested {}, received {}.", index + 1, batch_count, chunk.len(), blobs.len())).await;for dto in blobs {- cache.insert(dto.hash, dto.encrypted_data_base64);+ cache.insert(dto.hash, EncryptedBlob { encrypted_data_base64: dto.encrypted_data_base64, encrypted_blob_key: dto.encrypted_blob_key });}}- let mut pruned_cache: HashMap<String, String> = HashMap::new();+ let mut pruned_cache: HashMap<String, EncryptedBlob> = HashMap::new();let mut blob_map = HashMap::new();for reference in &refs {- let Some(ciphertext) = cache.get(&reference.hash) else {+ let Some(encrypted) = cache.get(&reference.hash) else {ctx.warn(format!("[V2Sync] Referenced {} blob {} was not served; its row stays not loaded and keeps the reference.", reference.category, reference.hash)).await;continue;};let key = owners.get(&reference.hash).map(|o| o.vek.as_str()).unwrap_or(fallback_vek);- match crate::encoding::base64_decode(ciphertext).and_then(|bytes| crypto::symmetric_decrypt_bytes(&bytes, key)) {+ match blob_keys::decrypt_blob(encrypted, key) {Ok(bytes) => {blob_map.insert(reference.hash.clone(), bytes);- pruned_cache.insert(reference.hash.clone(), ciphertext.clone());+ pruned_cache.insert(reference.hash.clone(), encrypted.clone());}Err(_) => ctx.warn(format!("[V2Sync] Referenced {} blob {} did not decrypt with the manifest key; its row stays not loaded and keeps the reference.", reference.category, reference.hash)).await,}diff --git a/core/rust/src/vault_sync/push.rs b/core/rust/src/vault_sync/push.rsindex 87c5cb74e..6a64347e4 100644--- a/core/rust/src/vault_sync/push.rs+++ b/core/rust/src/vault_sync/push.rs@@ -9,6 +9,7 @@ use super::email_routing::build_email_routing;use super::errors::{SyncError, SyncResult};use super::state::{self, Ctx};use super::types::{BlobDto, BlobHashesRequest, BlobRef, BlobUploadRequest, BucketRevision, BucketWrite, Db, ManifestRevision, ManifestWrite, MissingBlobsResponse, VaultWriteRequest, VaultWriteResponse};+use super::blob_keys::{self, EncryptedBlob};use super::{db, http, keys};use crate::crypto;use crate::vault_codec::{self, BlobEntry, CanonicalizeInput, CanonicalizedVault, DataBucket, Manifest, ManifestSpec};@@ -606,7 +607,7 @@ async fn encrypt_changed_manifests(ctx: &Ctx, candidates: &[Candidate<'_>], base/// Encrypt and upload only the blobs the server does not already have. On a migration push every personal/// blob is re-encrypted under the new key and overwritten. Returns hash to ciphertext for the local cache.-async fn upload_missing_blobs(ctx: &Ctx, blobs: &UploadBlobs, baselines: &PushBaselines, gate: WriteGate) -> SyncResult<HashMap<String, String>> {+async fn upload_missing_blobs(ctx: &Ctx, blobs: &UploadBlobs, baselines: &PushBaselines, gate: WriteGate) -> SyncResult<HashMap<String, EncryptedBlob>> {let personal_hashes = blobs.hashes(true);let shared_hashes = blobs.hashes(false);let unknown_to_server = |hashes: &[String]| -> Vec<String> { hashes.iter().filter(|h| !baselines.known_server_hashes.contains(*h)).cloned().collect() };@@ -635,7 +636,7 @@ async fn missing_on_server(ctx: &Ctx, blobs: &UploadBlobs, hashes: &[String]) ->/// `POST v2/Vault`. When the server reports blobs it lacks (stale local knowledge of its blob set), upload/// them and retry the identical write once; blobs this client cannot supply fail the push.-async fn write_vault(ctx: &Ctx, payload: &VaultWriteRequest, blobs: &UploadBlobs, gate: WriteGate, uploaded: &mut HashMap<String, String>) -> SyncResult<VaultWriteResponse> {+async fn write_vault(ctx: &Ctx, payload: &VaultWriteRequest, blobs: &UploadBlobs, gate: WriteGate, uploaded: &mut HashMap<String, EncryptedBlob>) -> SyncResult<VaultWriteResponse> {let response: VaultWriteResponse = http::post(&ctx.host, http::VAULT_ENDPOINT, payload, true).await?;if response.missing_blob_hashes.is_empty() {return Ok(response);@@ -675,13 +676,13 @@ async fn commit_push_baselines(ctx: &Ctx, baselines: PushBaselines, manifest_rev}/// Record the server's blob set as this write left it, and keep the encrypted blob cache to what is still referenced.-async fn commit_blob_baselines(ctx: &Ctx, blobs: &UploadBlobs, uploaded: &HashMap<String, String>) -> SyncResult<()> {+async fn commit_blob_baselines(ctx: &Ctx, blobs: &UploadBlobs, uploaded: &HashMap<String, EncryptedBlob>) -> SyncResult<()> {state::set(&ctx.host, state::VAULT_SERVER_BLOB_HASHES, &blobs.order).await?;- let cache: HashMap<String, String> = state::get(&ctx.host, state::VAULT_BLOB_CIPHER_CACHE).await?.unwrap_or_default();- let mut new_cache: HashMap<String, String> = HashMap::new();+ let cache: HashMap<String, EncryptedBlob> = state::get(&ctx.host, state::VAULT_BLOB_CIPHER_CACHE).await?.unwrap_or_default();+ let mut new_cache: HashMap<String, EncryptedBlob> = HashMap::new();for hash in &blobs.order {- if let Some(ciphertext) = uploaded.get(hash).or_else(|| cache.get(hash)) {- new_cache.insert(hash.clone(), ciphertext.clone());+ if let Some(encrypted) = uploaded.get(hash).or_else(|| cache.get(hash)) {+ new_cache.insert(hash.clone(), encrypted.clone());}}state::set(&ctx.host, state::VAULT_BLOB_CIPHER_CACHE, &new_cache).await@@ -701,15 +702,15 @@ async fn complete_account_key_migration(ctx: &mut Ctx, migration: &LegacyAccount/// Encrypt the given blobs (each under its own key) and upload them in size-capped batches per owning manifest./// Returns hash to ciphertext for the local encrypted blob cache.-async fn upload_blobs(ctx: &Ctx, blobs: &UploadBlobs, hashes: &[String], overwrite: bool) -> SyncResult<HashMap<String, String>> {- let mut ciphertexts = HashMap::new();+async fn upload_blobs(ctx: &Ctx, blobs: &UploadBlobs, hashes: &[String], overwrite: bool) -> SyncResult<HashMap<String, EncryptedBlob>> {+ let mut encrypted_blobs = HashMap::new();for (manifest_id, hashes) in blobs.by_manifest(hashes) {let mut dtos = Vec::new();for hash in hashes {let entry = &blobs.entries[&hash];- let ciphertext = crypto::symmetric_encrypt_bytes(&entry.bytes, &entry.vek)?;- ciphertexts.insert(hash.clone(), ciphertext.clone());- dtos.push(BlobDto { hash, category: entry.kind.clone(), encrypted_data_base64: ciphertext });+ let encrypted = blob_keys::encrypt_blob(&entry.bytes, &entry.vek)?;+ encrypted_blobs.insert(hash.clone(), encrypted.clone());+ dtos.push(BlobDto { hash, category: entry.kind.clone(), encrypted_data_base64: encrypted.encrypted_data_base64, encrypted_blob_key: encrypted.encrypted_blob_key });}for batch in http::batch_by_transfer_cost(dtos, |dto| dto.encrypted_data_base64.len()) {let chars: usize = batch.iter().map(|dto| dto.encrypted_data_base64.len()).sum();@@ -717,7 +718,7 @@ async fn upload_blobs(ctx: &Ctx, blobs: &UploadBlobs, hashes: &[String], overwrihttp::post_no_content(&ctx.host, BLOBS_ENDPOINT, &BlobUploadRequest { manifest_id: manifest_id.clone(), blobs: batch, overwrite }).await?;}}- Ok(ciphertexts)+ Ok(encrypted_blobs)}/*diff --git a/core/rust/src/vault_sync/tests/mod.rs b/core/rust/src/vault_sync/tests/mod.rsindex 2e5ef8708..665369613 100644--- a/core/rust/src/vault_sync/tests/mod.rs+++ b/core/rust/src/vault_sync/tests/mod.rs@@ -227,6 +227,12 @@ fn pushed_blobs_name_the_manifest_that_owns_them() {assert_eq!(upload["manifestId"], PERSONAL_MANIFEST_ID);assert_eq!(upload["blobs"].as_array().unwrap().len(), 1);assert_eq!(upload["blobs"][0]["hash"], missing_checks[0].body.as_ref().unwrap()["hashes"][0]);++ // The bytes are encrypted with the blob's own key, which travels encrypted with the VEK.+ let ciphertext = crate::encoding::base64_decode(upload["blobs"][0]["encryptedDataBase64"].as_str().unwrap()).unwrap();+ assert!(crypto::symmetric_decrypt_bytes(&ciphertext, &vek).is_err());+ let blob_key = crypto::unwrap_key(upload["blobs"][0]["encryptedBlobKey"].as_str().unwrap(), &vek).unwrap();+ assert_eq!(crypto::symmetric_decrypt_bytes(&ciphertext, &blob_key).unwrap(), vec![1u8, 2, 3, 4]);}#[test]diff --git a/core/rust/src/vault_sync/tests/unloaded_blobs.rs b/core/rust/src/vault_sync/tests/unloaded_blobs.rsindex 41dbbaa92..9610bf446 100644--- a/core/rust/src/vault_sync/tests/unloaded_blobs.rs+++ b/core/rust/src/vault_sync/tests/unloaded_blobs.rs@@ -7,6 +7,7 @@ use super::test_host::{self, query, TestHost};use super::{insert_item, item_names, read_tables, request, PERSONAL_MANIFEST_ID};use crate::crypto;use crate::vault_codec::{self, CanonicalizeInput, ManifestSpec};+use crate::vault_sync::blob_keys;use crate::vault_sync::session::SyncSession;use crate::vault_sync::state;@@ -17,6 +18,14 @@ struct ServerBlob {hash: String,kind: String,ciphertext: String,+ encrypted_blob_key: String,+}++impl ServerBlob {+ /// The blob as the download endpoint serves it.+ fn served(&self) -> Value {+ json!({ "hash": self.hash, "category": self.kind, "encryptedDataBase64": self.ciphertext, "encryptedBlobKey": self.encrypted_blob_key })+ }}/// A server vault holding one item with a logo and an attachment.@@ -30,7 +39,7 @@ fn server_db(host: &TestHost) -> rusqlite::Connection {db}-/// The status and vault responses of a server holding `conn` at `revision`, and its blobs encrypted with `blob_key`.+/// The status and vault responses of a server holding `conn` at `revision`, and its blobs, their keys encrypted with `blob_key`.fn snapshot(conn: &rusqlite::Connection, vek: &str, blob_key: &str, salt: &str, revision: i64) -> (Value, Value, Vec<ServerBlob>) {let canonicalized = vault_codec::canonicalize_from_sqlite(CanonicalizeInput {tables: read_tables(conn),@@ -41,7 +50,14 @@ fn snapshot(conn: &rusqlite::Connection, vek: &str, blob_key: &str, salt: &str,.unwrap();let entry = &canonicalized.manifests[0];let blob = crypto::symmetric_encrypt_bytes(&vault_codec::pack_payload(&serde_json::to_string(&entry.manifest).unwrap()).unwrap(), vek).unwrap();- let blobs: Vec<ServerBlob> = entry.blobs.iter().map(|(hash, b)| ServerBlob { hash: hash.clone(), kind: b.kind.clone(), ciphertext: crypto::symmetric_encrypt_bytes(&crate::encoding::base64_decode(&b.bytes_base64).unwrap(), blob_key).unwrap() }).collect();+ let blobs: Vec<ServerBlob> = entry+ .blobs+ .iter()+ .map(|(hash, b)| {+ let encrypted = blob_keys::encrypt_blob(&crate::encoding::base64_decode(&b.bytes_base64).unwrap(), blob_key).unwrap();+ ServerBlob { hash: hash.clone(), kind: b.kind.clone(), ciphertext: encrypted.encrypted_data_base64, encrypted_blob_key: encrypted.encrypted_blob_key }+ })+ .collect();let references: Vec<Value> = blobs.iter().map(|b| json!({ "hash": b.hash, "category": b.kind, "sizeBytes": 64 })).collect();let status = json!({"clientVersionSupported": true,@@ -72,7 +88,7 @@ fn host_with_unloaded_blobs(vek: &str, serve_undecryptable: bool) -> (TestHost,let (status, vault, blobs) = snapshot(&server_db(&host), vek, &blob_key, &vault_codec::generate_manifest_salt(), 7);host.respond("GET", "Status", status);host.respond("GET", "Vault", vault);- let served: Vec<Value> = if serve_undecryptable { blobs.iter().map(|b| json!({ "hash": b.hash, "category": b.kind, "encryptedDataBase64": b.ciphertext })).collect() } else { Vec::new() };+ let served: Vec<Value> = if serve_undecryptable { blobs.iter().map(ServerBlob::served).collect() } else { Vec::new() };host.respond("POST", "Vault/blobs/download", json!(served));let pulled = host.drive(&SyncSession::new(&request("fullSync", vek, false, 0)).unwrap());@@ -118,6 +134,27 @@ fn blobs_the_server_does_not_serve_neither_fail_the_pull_nor_lose_their_referencassert!(host.requests_to("Vault/blobs").is_empty(), "there are no bytes to upload for a blob this device never loaded");}+/// Pull the server vault at revision 7 with `served` as the download response, and return the loaded attachment bytes.+fn pull_attachment_bytes(vek: &str, serve: impl Fn(&[ServerBlob]) -> Vec<Value>) -> Vec<Value> {+ let mut host = TestHost::new(vek);+ host.state.insert(state::ENCRYPTED_ACCOUNT_KEY.to_string(), json!("wrapped"));+ let (status, vault, blobs) = snapshot(&server_db(&host), vek, vek, &vault_codec::generate_manifest_salt(), 7);+ host.respond("GET", "Status", status);+ host.respond("GET", "Vault", vault);+ host.respond("POST", "Vault/blobs/download", json!(serve(&blobs)));++ let pulled = host.drive(&SyncSession::new(&request("fullSync", vek, false, 0)).unwrap());+ assert_eq!(pulled["success"], true, "{}", pulled);+ query(&host.local, "SELECT hex(Blob) AS Bytes FROM Attachments WHERE IsDeleted = 0", &[]).unwrap().into_iter().map(|row| row["Bytes"].clone()).collect()+}++#[test]+fn a_pulled_blob_opens_through_its_own_key() {+ let vek = crypto::generate_key_base64();+ let loaded = pull_attachment_bytes(&vek, |blobs| blobs.iter().map(ServerBlob::served).collect());+ assert_eq!(loaded, vec![json!("09".repeat(64))]);+}+#[test]fn blobs_that_do_not_decrypt_neither_fail_the_pull_nor_lose_their_reference() {let vek = crypto::generate_key_base64();diff --git a/core/rust/src/vault_sync/types.rs b/core/rust/src/vault_sync/types.rsindex 91c603edc..dff636c89 100644--- a/core/rust/src/vault_sync/types.rs+++ b/core/rust/src/vault_sync/types.rs@@ -528,7 +528,6 @@ pub struct StatusResponse {pub struct ManifestRevision {pub manifest_id: String,pub revision: i64,- /// The name of a shared manifest, encrypted with the manifest's own key.#[serde(default, skip_serializing_if = "Option::is_none")]pub encrypted_name: Option<String>,}@@ -674,6 +673,7 @@ pub struct BlobDto {pub hash: String,pub category: String,pub encrypted_data_base64: String,+ pub encrypted_blob_key: String,}#[derive(Debug, Clone, Serialize)]