Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Hard delete old revisions and keys that are no longer usable after key rotation (#2524)
Leendert de Borst1c2b4d979393
diff --git a/apps/server/AliasVault.Api/Controllers/V2/KeyRotationController.cs b/apps/server/AliasVault.Api/Controllers/V2/KeyRotationController.csindex 8accb5bc8..54ddf4eef 100644--- a/apps/server/AliasVault.Api/Controllers/V2/KeyRotationController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/KeyRotationController.cs@@ -38,9 +38,8 @@ using Microsoft.Extensions.Caching.Memory;/// <param name="cache">IMemoryCache instance for persisting SRP values between the initiate and the rotation call.</param>/// <param name="timeProvider">TimeProvider.</param>/// <param name="authLoggingService">AuthLoggingService.</param>-/// <param name="settingsService">ServerSettingsService.</param>[ApiVersion("2")]-public class KeyRotationController(ILogger<KeyRotationController> logger, IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IMemoryCache cache, TimeProvider timeProvider, AuthLoggingService authLoggingService, ServerSettingsService settingsService) : AuthenticatedRequestController(userManager)+public class KeyRotationController(ILogger<KeyRotationController> logger, IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IMemoryCache cache, TimeProvider timeProvider, AuthLoggingService authLoggingService) : AuthenticatedRequestController(userManager){/// <summary>/// Starts a key rotation: the SRP challenge for the current password, plus the key generations the rotation starts from.@@ -125,7 +124,6 @@ public class KeyRotationController(ILogger<KeyRotationController> logger, IAlias}var now = timeProvider.GetUtcNow().UtcDateTime;- var settings = await settingsService.GetAllSettingsAsync();var currentRefreshTokenId = Guid.TryParse(User.FindFirstValue(TokenService.RefreshTokenIdClaim), out var tokenId) ? tokenId : Guid.Empty;var client = ClientHeaderInfo.GetRawValue(Request);@@ -179,9 +177,9 @@ public class KeyRotationController(ILogger<KeyRotationController> logger, IAliasvar newAccountKeyVersion = method.AccountKeyVersion + 1;var newKeyVersion = manifest.KeyVersion + 1;- // 1) The master-password unlock method: archived like a password change, then rewritten for the new Account Key.- await UnlockMethodHistoryPolicy.ArchiveAsync(writeContext, method, settings.UnlockMethodHistoryRetentionDays, now, client);- await writeContext.SaveChangesAsync();+ // 1) The master-password unlock method, rewritten for the new Account Key. Archived passwords open an older Account Key,+ // which no longer reaches any vault key, so the password history is dropped instead of extended.+ await writeContext.UserUnlockMethodsHistory.Where(x => x.UserId == user.Id).ExecuteDeleteAsync();var metadata = VaultKeyMetadata.Parse(method.Metadata);metadata.Salt = model.UnlockMethod.Salt;metadata.SrpVerifier = model.UnlockMethod.Verifier;@@ -193,12 +191,8 @@ public class KeyRotationController(ILogger<KeyRotationController> logger, IAliasmethod.AccountKeyVersion = newAccountKeyVersion;method.UpdatedAt = now;- // 2) The personal VEK: the retired generation stays, rewrapped under the new Account Key, next to the new one.- var currentAccessKey = personalAccessKeys.OrderByDescending(k => k.KeyVersion).First();- currentAccessKey.EncryptedVek = model.AccountKeys.RetiredEncryptedVek;- currentAccessKey.AccountKeyVersion = newAccountKeyVersion;- currentAccessKey.UpdatedAt = now;- writeContext.VaultManifestAccessKeys.RemoveRange(personalAccessKeys.Where(k => k != currentAccessKey));+ // 2) The personal VEK: the new generation replaces every previous one, as nothing under an older one is kept (see 5).+ writeContext.VaultManifestAccessKeys.RemoveRange(personalAccessKeys);writeContext.VaultManifestAccessKeys.Add(new VaultManifestAccessKey{Id = Guid.NewGuid(),@@ -213,8 +207,9 @@ public class KeyRotationController(ILogger<KeyRotationController> logger, IAliasUpdatedAt = now,});- // 3) The account keypairs: the previous ones are demoted first, as only one primary may exist per user.- await writeContext.UserGrantKeys.Where(k => k.UserId == user.Id && k.IsPrimary).ExecuteUpdateAsync(s => s.SetProperty(k => k.IsPrimary, false).SetProperty(k => k.UpdatedAt, now));+ // 3) The account keypairs. Old encryption keypairs are deleted: every grant is rewrapped below and stale invitations are+ // emptied, so nothing references them. Old signing keys stay demoted, as their public halves chain to the new one.+ await writeContext.UserGrantKeys.Where(k => k.UserId == user.Id).ExecuteDeleteAsync();await writeContext.UserSigningKeys.Where(k => k.UserId == user.Id && k.IsPrimary).ExecuteUpdateAsync(s => s.SetProperty(k => k.IsPrimary, false).SetProperty(k => k.UpdatedAt, now));var grantKey = new UserGrantKey{@@ -257,12 +252,11 @@ public class KeyRotationController(ILogger<KeyRotationController> logger, IAliasgrant.UpdatedAt = now;}- // 5) The personal manifest, as a new revision under the new VEK, with the same blob set.- var archivedRevision = manifest.HasContent ? VaultManifestsHistory.CreateFrom(manifest) : null;- if (archivedRevision != null)- {- writeContext.VaultManifestsHistory.Add(archivedRevision);- }+ // 5) The personal manifest, as a new revision under the new VEK, with the same blob set. Earlier revisions of the manifest+ // and its buckets are encrypted with the old VEK, which no client holds anymore, so they are deleted instead of archived.+ await writeContext.VaultBlobReferences.Where(r => r.ManifestId == manifest.ManifestId).ExecuteDeleteAsync();+ await writeContext.VaultManifestsHistory.Where(h => h.ManifestId == manifest.ManifestId).ExecuteDeleteAsync();+ await writeContext.VaultDataBucketsHistory.Where(h => h.ManifestId == manifest.ManifestId).ExecuteDeleteAsync();manifest.VaultBlob = null;manifest.StorageFormat = VaultManifestBase.ManifestStorageFormat;@@ -276,7 +270,6 @@ public class KeyRotationController(ILogger<KeyRotationController> logger, IAliasmanifest.Client = client;manifest.UpdatedByUserId = user.Id;manifest.UpdatedAt = now;- await VaultRevisionWriter.ApplyManifestRetentionAsync(writeContext, now, manifest, archivedRevision);foreach (var hash in referencedHashes){writeContext.VaultBlobReferences.Add(new VaultBlobReference { ManifestId = manifest.ManifestId, RevisionNumber = manifest.RevisionNumber, BlobHash = hash });@@ -291,7 +284,7 @@ public class KeyRotationController(ILogger<KeyRotationController> logger, IAliasvar bucketRevisions = new List<BucketRevision>();foreach (var bucket in model.Buckets){- var revision = await VaultRevisionWriter.UpsertBucketAsync(writeContext, now, manifest.ManifestId, bucket.Category, bucket.Data, bucket.CiphertextHash, bucket.CurrentRevision, buckets.FirstOrDefault(b => b.Category == bucket.Category), newKeyVersion);+ var revision = await VaultRevisionWriter.UpsertBucketAsync(writeContext, now, manifest.ManifestId, bucket.Category, bucket.Data, bucket.CiphertextHash, bucket.CurrentRevision, buckets.FirstOrDefault(b => b.Category == bucket.Category), newKeyVersion, archive: false);bucketRevisions.Add(new BucketRevision { ManifestId = manifest.ManifestId, Category = bucket.Category, Revision = revision });}diff --git a/apps/server/AliasVault.Api/Helpers/VaultRevisionWriter.cs b/apps/server/AliasVault.Api/Helpers/VaultRevisionWriter.csindex f0372d33f..740eedce6 100644--- a/apps/server/AliasVault.Api/Helpers/VaultRevisionWriter.cs+++ b/apps/server/AliasVault.Api/Helpers/VaultRevisionWriter.cs@@ -58,8 +58,9 @@ public static class VaultRevisionWriter/// <param name="currentRevision">The revision the client believes is current, used to seed a first write.</param>/// <param name="existing">The current row, already loaded by the revision gate, or null when none exists yet.</param>/// <param name="keyVersion">The VEK generation the payload is encrypted with, or null to keep the row's.</param>+ /// <param name="archive">Whether the outgoing revision is kept in history.</param>/// <returns>The new revision number.</returns>- public static async Task<long> UpsertBucketAsync(AliasServerDbContext context, DateTime now, Guid manifestId, VaultDataBucketCategory kind, byte[] encryptedData, string? ciphertextHash, long? currentRevision, VaultDataBucket? existing, int? keyVersion = null)+ public static async Task<long> UpsertBucketAsync(AliasServerDbContext context, DateTime now, Guid manifestId, VaultDataBucketCategory kind, byte[] encryptedData, string? ciphertextHash, long? currentRevision, VaultDataBucket? existing, int? keyVersion = null, bool archive = true){if (existing is null){@@ -79,8 +80,11 @@ public static class VaultRevisionWriter}// Archive the outgoing revision before overwriting it, exactly as the manifest write path does.- var archived = VaultDataBucketsHistory.CreateFrom(existing);- context.VaultDataBucketsHistory.Add(archived);+ var archived = archive ? VaultDataBucketsHistory.CreateFrom(existing) : null;+ if (archived is not null)+ {+ context.VaultDataBucketsHistory.Add(archived);+ }var newRev = existing.RevisionNumber + 1;existing.EncryptedData = encryptedData;@@ -89,7 +93,11 @@ public static class VaultRevisionWriterexisting.KeyVersion = keyVersion ?? existing.KeyVersion;existing.UpdatedAt = now;- await ApplyBucketRetentionAsync(context, now, manifestId, kind, archived);+ if (archived is not null)+ {+ await ApplyBucketRetentionAsync(context, now, manifestId, kind, archived);+ }+return newRev;}diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/KeyRotation/KeyRotationAccountKeys.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/KeyRotation/KeyRotationAccountKeys.csindex 8cdac7a93..8d9dc9867 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/KeyRotation/KeyRotationAccountKeys.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/KeyRotation/KeyRotationAccountKeys.cs@@ -20,11 +20,6 @@ public class KeyRotationAccountKeys/// </summary>public required string EncryptedVek { get; set; }- /// <summary>- /// Gets or sets the previous VEK encrypted with the new Account Key, which keeps older manifest revisions readable.- /// </summary>- public required string RetiredEncryptedVek { get; set; }-/// <summary>/// Gets or sets the new account encryption public key (JWK)./// </summary>@@ -59,7 +54,7 @@ public class KeyRotationAccountKeys/// Gets a value indicating whether every value is present and within the stored size limits./// </summary>[JsonIgnore]- public bool FitsStorageLimits => EncryptedVek.Length <= AccountKeysUpload.MaxWrappedKeyLength && RetiredEncryptedVek.Length <= AccountKeysUpload.MaxWrappedKeyLength && AccountPublicKey.Length <= AccountKeysUpload.MaxPublicKeyLength+ public bool FitsStorageLimits => EncryptedVek.Length <= AccountKeysUpload.MaxWrappedKeyLength && AccountPublicKey.Length <= AccountKeysUpload.MaxPublicKeyLength&& EncryptedAccountPrivateKey.Length <= AccountKeysUpload.MaxEncryptedPrivateKeyLength && AccountPublicKeySignature.Length <= AccountKeysUpload.MaxSigningValueLength && SigningPublicKey.Length <= AccountKeysUpload.MaxSigningPublicKeyLength&& EncryptedSigningPrivateKey.Length <= AccountKeysUpload.MaxSigningValueLength && PreviousSigningKeySignature.Length <= AccountKeysUpload.MaxSigningValueLength;}diff --git a/core/rust/src/crypto/key_chain.rs b/core/rust/src/crypto/key_chain.rsindex 28bd973d6..46885612f 100644--- a/core/rust/src/crypto/key_chain.rs+++ b/core/rust/src/crypto/key_chain.rs@@ -233,10 +233,6 @@ pub struct RotatedAccountKeys {#[zeroize(skip)]pub account_keys: AccountKeyBlobs,- /// The previous VEK encrypted with the new Account Key, which keeps older manifest revisions readable.- #[zeroize(skip)]- pub retired_encrypted_vek: String,-/// The previous signing key's signature over the new signing public key (see [`signing::SIGNING_KEY_ROTATION_LABEL`]).#[zeroize(skip)]pub previous_signing_key_signature: String,@@ -244,17 +240,15 @@ pub struct RotatedAccountKeys {impl fmt::Debug for RotatedAccountKeys {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {- f.debug_struct("RotatedAccountKeys").field("account_keys", &self.account_keys).field("retired_encrypted_vek", &self.retired_encrypted_vek).finish_non_exhaustive()+ f.debug_struct("RotatedAccountKeys").field("account_keys", &self.account_keys).finish_non_exhaustive()}}/// Rotate an account's keys: a new Account Key, VEK and signing keypair around an account keypair the host generated,-/// wrapped under the KEK of `new_unlock_key_base64`. The previous VEK rides along under the new Account Key, and the-/// previous signing key is used to confirm the new one.-pub fn rotate_account_keys(current_vek_base64: &str, current_signing_private_key_base64: &str, user_id: &str, new_unlock_key_base64: &str, key_pair: &RsaKeyPair) -> VaultResult<RotatedAccountKeys> {+/// wrapped under the KEK of `new_unlock_key_base64`. The previous signing key is used to confirm the new one.+pub fn rotate_account_keys(current_signing_private_key_base64: &str, user_id: &str, new_unlock_key_base64: &str, key_pair: &RsaKeyPair) -> VaultResult<RotatedAccountKeys> {let hierarchy = create_account_key_hierarchy_with_key_pair(new_unlock_key_base64, key_pair)?;let account_key = unwrap_account_key(&hierarchy.account_keys.encrypted_account_key, new_unlock_key_base64)?;- let retired_encrypted_vek = wrap_key(current_vek_base64, &account_key, aad::PERSONAL_VEK)?;let rotation_message = signing::signing_key_rotation_message(user_id, &hierarchy.account_keys.signing_public_key);let previous_signing_key_signature = signing::sign(current_signing_private_key_base64, &rotation_message)?;Ok(RotatedAccountKeys {@@ -263,7 +257,6 @@ pub fn rotate_account_keys(current_vek_base64: &str, current_signing_private_keyaccount_private_key: hierarchy.account_private_key.clone(),signing_private_key: hierarchy.signing_private_key.clone(),account_keys: hierarchy.account_keys.clone(),- retired_encrypted_vek,previous_signing_key_signature,})}@@ -278,7 +271,7 @@ mod tests {let new_unlock_key = generate_key_base64();let key_pair = generate_rsa_key_pair().unwrap();- let rotated = rotate_account_keys(&old_hierarchy.vault_encryption_key, &old_hierarchy.signing_private_key, "user-1", &new_unlock_key, &key_pair).unwrap();+ let rotated = rotate_account_keys(&old_hierarchy.signing_private_key, "user-1", &new_unlock_key, &key_pair).unwrap();let blobs = &rotated.account_keys;// The new chain opens with the new unlock key and yields the new VEK and private keys.@@ -289,10 +282,6 @@ mod tests {assert_ne!(rotated.vault_encryption_key, old_hierarchy.vault_encryption_key);assert_ne!(blobs.signing_public_key, old_hierarchy.account_keys.signing_public_key);- // The retired VEK opens under the new Account Key, in the VEK slot only.- assert_eq!(*unwrap_key(&rotated.retired_encrypted_vek, &rotated.account_key, aad::PERSONAL_VEK).unwrap(), old_hierarchy.vault_encryption_key);- assert!(unwrap_key(&rotated.retired_encrypted_vek, &rotated.account_key, aad::ACCOUNT_KEY).is_err());-// The old signing key vouches for the new one, bound to the account.let message = signing::signing_key_rotation_message("user-1", &blobs.signing_public_key);assert!(signing::verify(&old_hierarchy.account_keys.signing_public_key, &message, &rotated.previous_signing_key_signature));diff --git a/core/rust/src/vault_sync/rotation.rs b/core/rust/src/vault_sync/rotation.rsindex 0b4fe40e4..dc43d95a7 100644--- a/core/rust/src/vault_sync/rotation.rs+++ b/core/rust/src/vault_sync/rotation.rs@@ -80,7 +80,6 @@ struct UnlockMethodWrite {#[serde(rename_all = "camelCase")]struct AccountKeysWrite {encrypted_vek: String,- retired_encrypted_vek: String,account_public_key: String,encrypted_account_private_key: String,account_public_key_signature: String,@@ -179,7 +178,7 @@ async fn rotate(ctx: &mut Ctx) -> Outcome {let blob_keys: BlobKeysResponse = http::with_outdated_server_guard(http::get(&ctx.host, &format!("Vault/blob-keys/{}", personal_manifest_id), false).await)?;let key_pair = crypto::RsaKeyPair { public_key: params.new_account_public_key.clone(), private_key: params.new_account_private_key.expose_secret().to_string() };- let rotated = crypto::rotate_account_keys(vek.expose_secret(), signing_key.expose_secret(), ¶ms.user_id, params.new_unlock_key.expose_secret(), &key_pair)?;+ let rotated = crypto::rotate_account_keys(signing_key.expose_secret(), ¶ms.user_id, params.new_unlock_key.expose_secret(), &key_pair)?;let new_vek = SecretString::from(rotated.vault_encryption_key.as_str());ctx.log("[KeyRotation] Generated the new Account Key, VEK, account keypair and signing keypair.").await;@@ -280,7 +279,7 @@ async fn build_and_post(ctx: &mut Ctx, params: &KeyRotationParams, personal_manirecord.algorithm = ALGORITHM_RSA_OAEP_SHA256.to_string();}- ensure_key_chain_opens(params, rotated, new_vek, old_vek)?;+ ensure_key_chain_opens(params, rotated, new_vek)?;let delivery_key_signature = crypto::signing::sign(&rotated.signing_private_key, &crypto::signing::delivery_key_message(personal_manifest_id, delivery_public_key, current_revision))?;let mut request = KeyRotationRequest {@@ -297,7 +296,6 @@ async fn build_and_post(ctx: &mut Ctx, params: &KeyRotationParams, personal_mani},account_keys: AccountKeysWrite {encrypted_vek: rotated.account_keys.encrypted_vek.clone(),- retired_encrypted_vek: rotated.retired_encrypted_vek.clone(),account_public_key: rotated.account_keys.account_public_key.clone(),encrypted_account_private_key: rotated.account_keys.encrypted_account_private_key.clone(),account_public_key_signature: rotated.account_keys.account_public_key_signature.clone(),@@ -344,13 +342,12 @@ async fn build_and_post(ctx: &mut Ctx, params: &KeyRotationParams, personal_mani/// Refuse to send a rotation whose new key chain does not open from the new password down to the VEKs: once the/// server applies it, the old password no longer reaches any key, so a broken chain could not be recovered.-fn ensure_key_chain_opens(params: &KeyRotationParams, rotated: &crypto::RotatedAccountKeys, new_vek: &SecretString, old_vek: &SecretString) -> SyncResult<()> {+fn ensure_key_chain_opens(params: &KeyRotationParams, rotated: &crypto::RotatedAccountKeys, new_vek: &SecretString) -> SyncResult<()> {let blobs = &rotated.account_keys;let account_key = crypto::unwrap_account_key(&blobs.encrypted_account_key, params.new_unlock_key.expose_secret()).ok().filter(|key| **key == rotated.account_key);ensure_opens(account_key.is_some(), "the new Account Key")?;- let opens_to = |wrapped: &str, expected: &str| crypto::unwrap_key(wrapped, &rotated.account_key, crypto::aad::PERSONAL_VEK).is_ok_and(|key| *key == expected);- ensure_opens(opens_to(&blobs.encrypted_vek, new_vek.expose_secret()), "the new vault key")?;- ensure_opens(opens_to(&rotated.retired_encrypted_vek, old_vek.expose_secret()), "the retired vault key")?;+ let vek_opens = crypto::unwrap_key(&blobs.encrypted_vek, &rotated.account_key, crypto::aad::PERSONAL_VEK).is_ok_and(|key| *key == new_vek.expose_secret());+ ensure_opens(vek_opens, "the new vault key")?;ensure_opens(crypto::open_account_private_key(&blobs.encrypted_account_private_key, &rotated.account_key).is_ok_and(|key| key == rotated.account_private_key), "the new account private key")?;ensure_opens(crypto::open_account_signing_private_key(&blobs.encrypted_signing_private_key, &rotated.account_key).is_ok_and(|key| *key == rotated.signing_private_key), "the new signing private key")}