Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add HKDF logic to Rust core (#2469)
Leendert de Borstb43c9a3d5b25
diff --git a/core/rust/Cargo.lock b/core/rust/Cargo.lockindex 9b76f6c31..d7ccbb2f4 100644--- a/core/rust/Cargo.lock+++ b/core/rust/Cargo.lock@@ -56,6 +56,7 @@ dependencies = ["flate2","getrandom 0.2.17","getrandom 0.3.4",+ "hkdf","js-sys","mail-parser","num-bigint",@@ -616,6 +617,24 @@ version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"+[[package]]+name = "hkdf"+version = "0.12.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"+dependencies = [+ "hmac",+]++[[package]]+name = "hmac"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"+dependencies = [+ "digest",+]+[[package]]name = "indexmap"version = "2.14.0"diff --git a/core/rust/Cargo.toml b/core/rust/Cargo.tomlindex 920db0889..119a38b87 100644--- a/core/rust/Cargo.toml+++ b/core/rust/Cargo.toml@@ -50,6 +50,9 @@ getrandom = { version = "0.3", features = ["wasm_js"] }# Argon2 password hashingargon2 = "0.5"+# HKDF-SHA256 (SRP/KEK derivation from unlock key)+hkdf = "0.12"+# AES-256-GCM (vault blobs, key wrapping) and RSA-OAEP-SHA256 (manifest key grants)aes-gcm = "0.10"rsa = "0.9"diff --git a/core/rust/src/bindings/uniffi_api.rs b/core/rust/src/bindings/uniffi_api.rsindex 6620926b0..6083c3974 100644--- a/core/rust/src/bindings/uniffi_api.rs+++ b/core/rust/src/bindings/uniffi_api.rs@@ -4,6 +4,7 @@//! All functions use JSON strings for input/output to simplify cross-language marshalling.use crate::crypto::argon2::Argon2Error;+use crate::crypto::{KeyChainError, SrpInputError};use crate::crypto::srp::{SrpEphemeral, SrpError, SrpSession};use crate::common::error::{json_call, VaultError};use crate::sqlite_host::{MemoryDatabase, SqlResult, SqlValue};@@ -217,6 +218,44 @@ pub fn argon2_derive_key_bytes(password: Vec<u8>, salt: Vec<u8>, encryption_settcrate::crypto::argon2::argon2_derive_key_bytes_from_settings(&password, &salt, &encryption_settings)}+/// The KEK that wraps the Account Key, HKDF-derived from the unlock key.+#[uniffi::export]+pub fn derive_kek(unlock_key: Vec<u8>) -> Vec<u8> {+ crate::crypto::derive_kek(&unlock_key).to_vec()+}++/// The SRP `password_hash` (uppercase hex) for an account's `encryptionType`, from the unlock key.+#[uniffi::export]+pub fn derive_srp_password_hash(unlock_key: Vec<u8>, encryption_type: String) -> Result<String, SrpInputError> {+ crate::crypto::derive_srp_password_hash(&unlock_key, &encryption_type).map(|hash| hash.to_string())+}++/// The keys an opened chain gives.+#[derive(uniffi::Record)]+pub struct KeyChainKeys {+ pub vault_encryption_key: Vec<u8>,++ /// What the caller stores in place of the key it passed in.+ pub account_key: Vec<u8>,++ /// The account private key (JWK), none when the account has no keypair or it does not open.+ pub account_private_key: Option<String>,+}++/// Open a key chain with a stored key: the Account Key or an unlock key.+#[uniffi::export]+pub fn open_account_key_chain(stored_key: Vec<u8>, encrypted_account_key: String, encrypted_vek: String, encrypted_account_private_key: Option<String>) -> Result<KeyChainKeys, KeyChainError> {+ use crate::common::encoding::{base64_decode, base64_encode};+ let stored_key = zeroize::Zeroizing::new(base64_encode(&stored_key));+ let opened = crate::crypto::open_account_key_chain(&stored_key, &encrypted_account_key, &encrypted_vek, encrypted_account_private_key.as_deref())?;+ let decode = |key: &str| base64_decode(key).map_err(|e| KeyChainError::KeyChainUnreadable(e.to_string()));+ Ok(KeyChainKeys {+ vault_encryption_key: decode(&opened.vault_encryption_key)?,+ account_key: decode(&opened.account_key)?,+ account_private_key: opened.account_private_key.as_ref().map(|key| key.to_string()),+ })+}+// ═══════════════════════════════════════════════════════════════════════════════// SRP (Secure Remote Password) Functions// ═══════════════════════════════════════════════════════════════════════════════diff --git a/core/rust/src/bindings/wasm.rs b/core/rust/src/bindings/wasm.rsindex 822a1f1e2..4696ba6db 100644--- a/core/rust/src/bindings/wasm.rs+++ b/core/rust/src/bindings/wasm.rs@@ -225,6 +225,49 @@ pub fn argon2_derive_key_js(password: &str, salt: &str, encryption_settings: &stcrate::crypto::argon2::argon2_derive_key_from_settings(password, salt, encryption_settings).map_err(js_err)}+/// The KEK (base64) that wraps the Account Key, HKDF-derived from the base64 unlock key.+#[wasm_bindgen(js_name = deriveKek)]+pub fn derive_kek_js(unlock_key_base64: &str) -> Result<String, JsValue> {+ crate::crypto::derive_kek_base64(unlock_key_base64).map(|kek| kek.to_string()).map_err(js_err)+}++/// The SRP `password_hash` (uppercase hex) for an account's `encryptionType`, from the base64 unlock key.+#[wasm_bindgen(js_name = deriveSrpPasswordHash)]+pub fn derive_srp_password_hash_js(unlock_key_base64: &str, encryption_type: &str) -> Result<String, JsValue> {+ let unlock_key = zeroize::Zeroizing::new(crate::common::encoding::base64_decode(unlock_key_base64).map_err(js_err)?);+ crate::crypto::derive_srp_password_hash(&unlock_key, encryption_type).map(|hash| hash.to_string()).map_err(js_err)+}++/// The outcome of `openAccountKeyChain`: `status` is `opened`, `unlockKeyRejected` or `keyChainUnreadable`.+#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct KeyChainOpenResult {+ status: &'static str,+ vault_encryption_key: Option<String>,+ account_key: Option<String>,+ account_private_key: Option<String>,+ message: Option<String>,+}++/// Open a key chain with a stored key (the Account Key or an unlock key, base64). On success `accountKey` is what the+/// caller stores in place of the key it passed in.+#[wasm_bindgen(js_name = openAccountKeyChain)]+pub fn open_account_key_chain_js(stored_key: &str, encrypted_account_key: &str, encrypted_vek: &str, encrypted_account_private_key: Option<String>) -> Result<JsValue, JsValue> {+ use crate::crypto::KeyChainError;+ let result = match crate::crypto::open_account_key_chain(stored_key, encrypted_account_key, encrypted_vek, encrypted_account_private_key.as_deref()) {+ Ok(opened) => KeyChainOpenResult {+ status: "opened",+ vault_encryption_key: Some(opened.vault_encryption_key.to_string()),+ account_key: Some(opened.account_key.to_string()),+ account_private_key: opened.account_private_key.as_ref().map(|key| key.to_string()),+ message: None,+ },+ Err(KeyChainError::UnlockKeyRejected) => KeyChainOpenResult { status: "unlockKeyRejected", vault_encryption_key: None, account_key: None, account_private_key: None, message: None },+ Err(KeyChainError::KeyChainUnreadable(message)) => KeyChainOpenResult { status: "keyChainUnreadable", vault_encryption_key: None, account_key: None, account_private_key: None, message: Some(message) },+ };+ to_js(&result)+}+// ═══════════════════════════════════════════════════════════════════════════════// SRP (Secure Remote Password) WASM Bindings// ═══════════════════════════════════════════════════════════════════════════════diff --git a/core/rust/src/crypto/key_chain.rs b/core/rust/src/crypto/key_chain.rsindex 82f0d2fbf..c9230d153 100644--- a/core/rust/src/crypto/key_chain.rs+++ b/core/rust/src/crypto/key_chain.rs@@ -1,13 +1,16 @@-//! The account key hierarchy: KEK (password-derived) wraps the Account Key, which wraps the Vault Encryption-//! Key and the account's private key.+//! The account key hierarchy: the KEK encrypts the Account Key, which encrypts the Vault Encryption Key and account private key.+//! The KEK and SRP password hash are each HKDF-derived from the unlock key using separate labels.+use hkdf::Hkdf;use serde::{Deserialize, Serialize};+use sha2::Sha256;use std::fmt;+use thiserror::Error;use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};-use super::aes_gcm::{generate_key_base64, symmetric_decrypt_bytes, symmetric_encrypt, symmetric_encrypt_bytes};+use super::aes_gcm::{generate_key_base64, symmetric_decrypt, symmetric_decrypt_bytes, symmetric_encrypt, symmetric_encrypt_bytes};use super::rsa_oaep::generate_rsa_key_pair;-use crate::common::encoding::{base64_decode, base64_encode};+use crate::common::encoding::{base64_decode, base64_encode, hex_encode_upper};use crate::common::error::VaultResult;/// The wrapped halves of an account key hierarchy: what the server stores.@@ -41,6 +44,66 @@ impl fmt::Debug for AccountKeyHierarchy {}}+/// HKDF `info` that binds the derived key to its use as the KEK; changing it breaks every stored Account Key.+const KEK_INFO: &[u8] = b"AliasVault KEK v1";++/// HKDF `info` that binds the derived key to its use as the SRP input; changing it breaks every upgraded verifier.+const SRP_INFO: &[u8] = b"AliasVault SRP v1";++/// The `EncryptionType` of a verifier made from the unlock key itself (accounts created before 0.31.0).+pub const ENCRYPTION_TYPE_ARGON2ID: &str = "Argon2Id";++/// The `EncryptionType` of a verifier made from the HKDF-derived SRP input: every new account and password change.+pub const ENCRYPTION_TYPE_ARGON2ID_HKDF: &str = "Argon2IdHkdf";++/// Why an SRP password hash could not be derived.+#[derive(Error, Debug, Clone, PartialEq, Eq)]+#[cfg_attr(feature = "uniffi", derive(uniffi::Error))]+#[cfg_attr(feature = "uniffi", uniffi(flat_error))]+pub enum SrpInputError {+ /// The account uses an `EncryptionType` this build does not know (a newer client created it).+ #[error("Unsupported encryption type: {0}")]+ UnsupportedEncryptionType(String),+}++/// HKDF-SHA256 (no salt, 32 bytes) of an unlock key under one label.+fn hkdf_expand(unlock_key: &[u8], info: &[u8]) -> Zeroizing<Vec<u8>> {+ let mut output = Zeroizing::new(vec![0u8; 32]);+ Hkdf::<Sha256>::new(None, unlock_key).expand(info, &mut output).expect("32 bytes is a valid HKDF-SHA256 output length");+ output+}++/// The KEK that wraps the Account Key, derived from an unlock key with HKDF-SHA256 (no salt, 32 bytes).+pub fn derive_kek(unlock_key: &[u8]) -> Zeroizing<Vec<u8>> {+ hkdf_expand(unlock_key, KEK_INFO)+}++/// The SRP `password_hash` (uppercase hex) an account's verifier is made from, for its `EncryptionType`.+pub fn derive_srp_password_hash(unlock_key: &[u8], encryption_type: &str) -> Result<Zeroizing<String>, SrpInputError> {+ match encryption_type {+ ENCRYPTION_TYPE_ARGON2ID => Ok(Zeroizing::new(hex_encode_upper(unlock_key))),+ ENCRYPTION_TYPE_ARGON2ID_HKDF => Ok(Zeroizing::new(hex_encode_upper(&hkdf_expand(unlock_key, SRP_INFO)))),+ other => Err(SrpInputError::UnsupportedEncryptionType(other.to_string())),+ }+}++/// [`derive_kek`] over base64: the KEK as base64.+pub fn derive_kek_base64(unlock_key_base64: &str) -> VaultResult<Zeroizing<String>> {+ let unlock_key = Zeroizing::new(base64_decode(unlock_key_base64)?);+ Ok(Zeroizing::new(base64_encode(&derive_kek(&unlock_key))))+}++/// Wrap the Account Key with the KEK derived from an unlock key.+pub fn wrap_account_key(account_key_base64: &str, unlock_key_base64: &str) -> VaultResult<String> {+ wrap_key(account_key_base64, &derive_kek_base64(unlock_key_base64)?)+}++/// Unwrap the Account Key with the KEK derived from an unlock key. Fails when the unlock key is not the one it was+/// wrapped for (wrong password).+pub fn unwrap_account_key(encrypted_account_key: &str, unlock_key_base64: &str) -> VaultResult<Zeroizing<String>> {+ unwrap_key(encrypted_account_key, &derive_kek_base64(unlock_key_base64)?)+}+/// Wrap a base64 key with another base64 key. Returns base64 of `IV | ciphertext | tag`.pub fn wrap_key(key_base64: &str, wrapping_key_base64: &str) -> VaultResult<String> {symmetric_encrypt_bytes(&Zeroizing::new(base64_decode(key_base64)?), wrapping_key_base64)@@ -52,26 +115,53 @@ pub fn unwrap_key(wrapped_key_base64: &str, wrapping_key_base64: &str) -> VaultROk(Zeroizing::new(base64_encode(&raw[..])))}-/// Turn a password-derived key into the vault encryption key: KEK > Account Key > VEK. Returns the VEK and the-/// Account Key (base64).-pub fn resolve_vault_encryption_key(- encrypted_account_key: &str,- encrypted_vek: &str,- kek_base64: &str,-) -> VaultResult<(Zeroizing<String>, Zeroizing<String>)> {- let account_key = unwrap_key(encrypted_account_key, kek_base64)?;- let vek = unwrap_key(encrypted_vek, &account_key)?;- Ok((vek, account_key))+/// Why a key chain did not open.+#[derive(Error, Debug, Clone, PartialEq, Eq)]+#[cfg_attr(feature = "uniffi", derive(uniffi::Error))]+#[cfg_attr(feature = "uniffi", uniffi(flat_error))]+pub enum KeyChainError {+ /// The stored key is neither the Account Key nor an unlock key that opens it (wrong password or PIN).+ #[error("The key does not open the account key")]+ UnlockKeyRejected,++ /// The Account Key opened but the VEK does not open under it: a damaged chain, never a wrong password.+ #[error("The key chain is unreadable: {0}")]+ KeyChainUnreadable(String),+}++/// The keys an opened chain gives (base64, the private key as its JWK).+pub struct OpenedKeyChain {+ pub vault_encryption_key: Zeroizing<String>,++ /// The Account Key: what the caller stores for later unlocks, in place of the key it passed in.+ pub account_key: Zeroizing<String>,++ /// None when the account has no keypair or its private key does not open; grants then stay closed.+ pub account_private_key: Option<Zeroizing<String>>,}-/// Create a new account key hierarchy wrapped under the given KEK.-pub fn create_account_key_hierarchy(kek_base64: &str) -> VaultResult<AccountKeyHierarchy> {+/// Open a key chain with a stored key, which is either the Account Key or an unlock key (see the module docs).+pub fn open_account_key_chain(stored_key: &str, encrypted_account_key: &str, encrypted_vek: &str, encrypted_account_private_key: Option<&str>) -> Result<OpenedKeyChain, KeyChainError> {+ let (account_key, vault_encryption_key) = match unwrap_key(encrypted_vek, stored_key) {+ Ok(vek) => (Zeroizing::new(stored_key.to_string()), vek),+ Err(_) => {+ let account_key = unwrap_account_key(encrypted_account_key, stored_key).map_err(|_| KeyChainError::UnlockKeyRejected)?;+ let vek = unwrap_key(encrypted_vek, &account_key).map_err(|e| KeyChainError::KeyChainUnreadable(e.to_string()))?;+ (account_key, vek)+ }+ };+ let account_private_key = encrypted_account_private_key.filter(|e| !e.is_empty()).and_then(|e| symmetric_decrypt(e, &account_key).ok()).map(Zeroizing::new);+ Ok(OpenedKeyChain { vault_encryption_key, account_key, account_private_key })+}++/// Create a new account key hierarchy wrapped under the KEK derived from an unlock key.+pub fn create_account_key_hierarchy(unlock_key_base64: &str) -> VaultResult<AccountKeyHierarchy> {let vault_encryption_key = generate_key_base64();let account_key = Zeroizing::new(generate_key_base64());let key_pair = generate_rsa_key_pair()?;let account_keys = AccountKeyBlobs {- encrypted_account_key: wrap_key(&account_key, kek_base64)?,+ encrypted_account_key: wrap_account_key(&account_key, unlock_key_base64)?,encrypted_vek: wrap_key(&vault_encryption_key, &account_key)?,account_public_key: key_pair.public_key.clone(),encrypted_account_private_key: symmetric_encrypt(&key_pair.private_key, &account_key)?,@@ -83,22 +173,83 @@ pub fn create_account_key_hierarchy(kek_base64: &str) -> VaultResult<AccountKeyH#[cfg(test)]mod tests {use super::*;- use crate::crypto::aes_gcm::symmetric_decrypt;++ /// Known-answer vector: every host derives the KEK through this one function, and a changed output means no+ /// stored Account Key opens any more. Never regenerate it.+ #[test]+ fn derive_kek_known_answer() {+ let unlock_key: Vec<u8> = (0u8..32).collect();+ assert_eq!(crate::common::encoding::hex_encode_upper(&derive_kek(&unlock_key)), KEK_VECTOR);+ }++ /// HKDF-SHA256(ikm = 0x00..0x1f, salt = none, info = "AliasVault KEK v1", L = 32).+ const KEK_VECTOR: &str = "8103CACFCD107162AECCFAEDB26426F53FF28C5D4273D2440641A5FA3ADD39D2";++ /// Known-answer vector for the SRP input of an `Argon2IdHkdf` account: a changed output means no upgraded+ /// verifier matches any more. Never regenerate it.+ #[test]+ fn derive_srp_password_hash_known_answer() {+ let unlock_key: Vec<u8> = (0u8..32).collect();+ assert_eq!(*derive_srp_password_hash(&unlock_key, ENCRYPTION_TYPE_ARGON2ID_HKDF).unwrap(), SRP_VECTOR);+ assert_eq!(*derive_srp_password_hash(&unlock_key, ENCRYPTION_TYPE_ARGON2ID).unwrap(), crate::common::encoding::hex_encode_upper(&unlock_key));+ }++ /// HKDF-SHA256(ikm = 0x00..0x1f, salt = none, info = "AliasVault SRP v1", L = 32).+ const SRP_VECTOR: &str = "BC09E255E5425823B7347FD803F4C5DCE8F11A7BC23B6F78FCC3D6D87240D923";++ #[test]+ fn srp_input_and_kek_are_separate() {+ let unlock_key: Vec<u8> = (0u8..32).collect();+ let srp = derive_srp_password_hash(&unlock_key, ENCRYPTION_TYPE_ARGON2ID_HKDF).unwrap();+ assert_ne!(*srp, crate::common::encoding::hex_encode_upper(&derive_kek(&unlock_key)));+ assert!(matches!(derive_srp_password_hash(&unlock_key, "Scrypt"), Err(SrpInputError::UnsupportedEncryptionType(_))));+ }++ #[test]+ fn kek_differs_from_the_unlock_key() {+ let unlock_key = generate_key_base64();+ assert_ne!(*derive_kek_base64(&unlock_key).unwrap(), unlock_key);+ }++ #[test]+ fn account_key_is_not_wrapped_with_the_raw_unlock_key() {+ let unlock_key = generate_key_base64();+ let hierarchy = create_account_key_hierarchy(&unlock_key).unwrap();+ assert!(unwrap_key(&hierarchy.account_keys.encrypted_account_key, &unlock_key).is_err());+ assert!(unwrap_key(&hierarchy.account_keys.encrypted_account_key, &derive_kek_base64(&unlock_key).unwrap()).is_ok());+ }+#[test]- fn hierarchy_unwraps_back_to_its_plaintext_halves() {- let kek = generate_key_base64();- let hierarchy = create_account_key_hierarchy(&kek).unwrap();+ fn chain_opens_with_the_unlock_key_and_hands_back_the_account_key() {+ let unlock_key = generate_key_base64();+ let hierarchy = create_account_key_hierarchy(&unlock_key).unwrap();+ let blobs = &hierarchy.account_keys;++ let opened = open_account_key_chain(&unlock_key, &blobs.encrypted_account_key, &blobs.encrypted_vek, Some(&blobs.encrypted_account_private_key)).unwrap();+ assert_eq!(*opened.vault_encryption_key, hierarchy.vault_encryption_key);+ assert_eq!(opened.account_private_key.as_deref().map(String::as_str), Some(hierarchy.account_private_key.as_str()));+ assert_ne!(*opened.account_key, unlock_key);- let (vek, account_key) = resolve_vault_encryption_key(&hierarchy.account_keys.encrypted_account_key, &hierarchy.account_keys.encrypted_vek, &kek).unwrap();- assert_eq!(*vek, hierarchy.vault_encryption_key);- assert_eq!(symmetric_decrypt(&hierarchy.account_keys.encrypted_account_private_key, &account_key).unwrap(), hierarchy.account_private_key);+ let reopened = open_account_key_chain(&opened.account_key, &blobs.encrypted_account_key, &blobs.encrypted_vek, Some(&blobs.encrypted_account_private_key)).unwrap();+ assert_eq!(*reopened.vault_encryption_key, hierarchy.vault_encryption_key);+ assert_eq!(*reopened.account_key, *opened.account_key, "a stored Account Key is handed back unchanged");}#[test]- fn wrong_kek_does_not_unwrap() {+ fn chain_rejects_a_wrong_key() {let hierarchy = create_account_key_hierarchy(&generate_key_base64()).unwrap();- assert!(resolve_vault_encryption_key(&hierarchy.account_keys.encrypted_account_key, &hierarchy.account_keys.encrypted_vek, &generate_key_base64()).is_err());+ let blobs = &hierarchy.account_keys;+ assert_eq!(open_account_key_chain(&generate_key_base64(), &blobs.encrypted_account_key, &blobs.encrypted_vek, None).err(), Some(KeyChainError::UnlockKeyRejected));+ }++ #[test]+ fn chain_with_a_foreign_vek_is_unreadable() {+ let unlock_key = generate_key_base64();+ let hierarchy = create_account_key_hierarchy(&unlock_key).unwrap();+ let foreign_vek = wrap_key(&generate_key_base64(), &generate_key_base64()).unwrap();+ let result = open_account_key_chain(&unlock_key, &hierarchy.account_keys.encrypted_account_key, &foreign_vek, None);+ assert!(matches!(result, Err(KeyChainError::KeyChainUnreadable(_))));}#[test]diff --git a/core/rust/src/crypto/mod.rs b/core/rust/src/crypto/mod.rsindex c529a5a3f..5d942a6a1 100644--- a/core/rust/src/crypto/mod.rs+++ b/core/rust/src/crypto/mod.rs@@ -7,7 +7,10 @@ pub mod rsa_oaep;pub mod srp;pub use aes_gcm::{generate_key_base64, symmetric_decrypt, symmetric_decrypt_bytes, symmetric_encrypt, symmetric_encrypt_bytes};-pub use key_chain::{create_account_key_hierarchy, resolve_vault_encryption_key, unwrap_key, wrap_key, AccountKeyBlobs, AccountKeyHierarchy};+pub use key_chain::{+ create_account_key_hierarchy, derive_kek, derive_kek_base64, derive_srp_password_hash, open_account_key_chain, unwrap_account_key, unwrap_key, wrap_account_key, wrap_key, AccountKeyBlobs,+ AccountKeyHierarchy, KeyChainError, OpenedKeyChain, SrpInputError, ENCRYPTION_TYPE_ARGON2ID, ENCRYPTION_TYPE_ARGON2ID_HKDF,+};pub use rsa_oaep::{decrypt_with_private_key, encrypt_with_public_key, generate_rsa_key_pair, RsaKeyPair};pub use self::argon2::{argon2_derive_key, argon2_derive_key_bytes_from_settings, argon2_derive_key_from_settings, Argon2Error, Argon2Params};diff --git a/core/rust/src/vault_sync/keys.rs b/core/rust/src/vault_sync/keys.rsindex 98569b84a..a94c4411c 100644--- a/core/rust/src/vault_sync/keys.rs+++ b/core/rust/src/vault_sync/keys.rs@@ -126,7 +126,7 @@ fn is_server_unreachable(error: &SyncError) -> bool {matches!(error, SyncError::Network(_) | SyncError::Timeout(_) | SyncError::Http { .. })}-/// Clear the cached key chain: the account has none (legacy), so the password-derived key is the vault key.+/// Clear the cached key chain: the account has none (legacy), so the unlock key is the vault key.async fn clear_cached_chain(host: &Host) -> SyncResult<()> {for key in [state::ENCRYPTED_ACCOUNT_KEY, state::ENCRYPTED_VEK, state::ACCOUNT_PUBLIC_KEY, state::ENCRYPTED_ACCOUNT_PRIVATE_KEY] {state::remove(host, key).await?;@@ -134,43 +134,43 @@ async fn clear_cached_chain(host: &Host) -> SyncResult<()> {Ok(())}-/// Walk a key chain, telling a key that does not open the account key (wrong password) apart from a chain whose VEK-/// does not open under its own account key. Returns the VEK and the Account Key.-fn walk_chain(encrypted_account_key: &str, encrypted_vek: &str, kek: &str) -> SyncResult<(Zeroizing<String>, Zeroizing<String>)> {- let account_key = crypto::unwrap_key(encrypted_account_key, kek).map_err(|_| SyncError::UnlockKeyRejected)?;- let vek = crypto::unwrap_key(encrypted_vek, &account_key).map_err(|e| SyncError::KeyChainUnreadable(e.to_string()))?;- Ok((vek, account_key))+/// Walk a key chain with an unlock key or the stored Account Key, telling a key that does not open the account key+/// (wrong password) apart from a chain whose VEK does not open under its own account key. Returns the VEK and the+/// Account Key.+fn walk_chain(encrypted_account_key: &str, encrypted_vek: &str, unlock_key: &str) -> SyncResult<(Zeroizing<String>, Zeroizing<String>)> {+ let opened = crypto::open_account_key_chain(unlock_key, encrypted_account_key, encrypted_vek, None).map_err(|error| match error {+ crypto::KeyChainError::UnlockKeyRejected => SyncError::UnlockKeyRejected,+ crypto::KeyChainError::KeyChainUnreadable(message) => SyncError::KeyChainUnreadable(message),+ })?;+ Ok((opened.vault_encryption_key, opened.account_key))}-/// Open a key chain with the password-derived key: the VEK becomes the session key and the private key is staged.-async fn open_chain(ctx: &mut Ctx, encrypted_account_key: &str, encrypted_vek: &str, encrypted_private_key: Option<&str>, kek: &str) -> SyncResult<()> {- let (vek, account_key) = walk_chain(encrypted_account_key, encrypted_vek, kek)?;+/// Open a key chain with an unlock key or the stored Account Key: the VEK becomes the session key and the private key+/// is staged.+async fn open_chain(ctx: &mut Ctx, encrypted_account_key: &str, encrypted_vek: &str, encrypted_private_key: Option<&str>, unlock_key: &str) -> SyncResult<()> {+ let (vek, account_key) = walk_chain(encrypted_account_key, encrypted_vek, unlock_key)?;ctx.set_encryption_key(vek.to_string());stage_account_private_key(ctx, &account_key, encrypted_private_key).await;Ok(())}-/// The login-time key resolution (the `resolveVaultKey` operation). The request carries the password-derived key-/// (KEK); the account's key chain is fetched from the server (the cached one stands in when the server cannot be-/// reached or predates the endpoint), opened with the KEK, cached for offline unlock, and the VEK becomes the-/// session key. An account without a chain is a sqlite-blob legacy account whose KEK is the vault key itself; its-/// hierarchy is created later by the migration push. Returns whether the account has a chain.+/// The login-time key resolution (the `resolveVaultKey` operation).pub(crate) async fn resolve_vault_key(ctx: &mut Ctx) -> SyncResult<bool> {- let kek = ctx.encryption_key()?;+ let unlock_key = ctx.encryption_key()?;let fetched = http::get::<VaultKeyGetResponse>(&ctx.host, http::VAULT_KEY_PASSWORD_ENDPOINT, false).await;ctx.vault_key_probed = true;match fetched {Ok(response) => match response.vault_key {Some(vault_key) if vault_key.encrypted_vek.is_some() => {let encrypted_vek = vault_key.encrypted_vek.clone().unwrap_or_default();- open_chain(ctx, &vault_key.encrypted_account_key, &encrypted_vek, vault_key.encrypted_account_private_key.as_deref(), &kek).await?;+ open_chain(ctx, &vault_key.encrypted_account_key, &encrypted_vek, vault_key.encrypted_account_private_key.as_deref(), &unlock_key).await?;cache_vault_key_blobs(&ctx.host, &vault_key).await?;ctx.log("[VaultSync] Opened the account's key chain; the session key is the VEK.").await;Ok(true)}_ => {clear_cached_chain(&ctx.host).await?;- ctx.log("[VaultSync] The account has no key chain yet (legacy vault); the password-derived key is the vault key.").await;+ ctx.log("[VaultSync] The account has no key chain yet (legacy vault); the unlock key is the vault key.").await;Ok(false)}},@@ -178,7 +178,7 @@ pub(crate) async fn resolve_vault_key(ctx: &mut Ctx) -> SyncResult<bool> {ctx.warn(format!("[VaultSync] Could not fetch the key chain, opening the cached one: {}", error)).await;let Some((encrypted_account_key, encrypted_vek)) = cached_chain(&ctx.host).await? else { return Ok(false) };let encrypted_private_key = state::get::<String>(&ctx.host, state::ENCRYPTED_ACCOUNT_PRIVATE_KEY).await?;- open_chain(ctx, &encrypted_account_key, &encrypted_vek, encrypted_private_key.as_deref(), &kek).await?;+ open_chain(ctx, &encrypted_account_key, &encrypted_vek, encrypted_private_key.as_deref(), &unlock_key).await?;Ok(true)}Err(error) => Err(error),diff --git a/core/rust/src/vault_sync/push.rs b/core/rust/src/vault_sync/push.rsindex fb1c891ad..047eaad90 100644--- a/core/rust/src/vault_sync/push.rs+++ b/core/rust/src/vault_sync/push.rs@@ -499,12 +499,13 @@ async fn push_internal(ctx: &mut Ctx, cached: Option<CanonicalizedSet>, create_vOk((PushStatus::Ok, migration.map(|m| m.content_key.clone())))}-/// Generate the account key hierarchy for a migration push, when one is due.-async fn start_account_key_migration(ctx: &Ctx, kek: &str, create_vault_key: bool) -> SyncResult<Option<LegacyAccountKeyMigration>> {+/// Generate the account key hierarchy for a migration push, when one is due. The session key of a legacy account is+/// its unlock key, which the hierarchy derives its KEK from.+async fn start_account_key_migration(ctx: &Ctx, unlock_key: &str, create_vault_key: bool) -> SyncResult<Option<LegacyAccountKeyMigration>> {if !create_vault_key {return Ok(None);}- let hierarchy = crypto::create_account_key_hierarchy(kek)?;+ let hierarchy = crypto::create_account_key_hierarchy(unlock_key)?;ctx.log("[V2Push] Account-key migration: generated new VEK, AK and account keypair; vault content and all blobs will be re-encrypted and re-uploaded.").await;Ok(Some(LegacyAccountKeyMigration {content_key: hierarchy.vault_encryption_key.clone(),diff --git a/core/rust/src/vault_sync/tests/mod.rs b/core/rust/src/vault_sync/tests/mod.rsindex 31ad2ccd1..498f4f861 100644--- a/core/rust/src/vault_sync/tests/mod.rs+++ b/core/rust/src/vault_sync/tests/mod.rs@@ -628,27 +628,27 @@ fn password_changed_elsewhere_requires_logout() {#[test]fn legacy_account_without_vault_key_reports_the_manifest_migration() {- let kek = crypto::generate_key_base64();- let mut host = TestHost::new(&kek);+ let unlock_key = crypto::generate_key_base64();+ let mut host = TestHost::new(&unlock_key);host.state.insert(state::SERVER_MANIFEST_REVISIONS.to_string(), json!({ PERSONAL_MANIFEST_ID: 3 }));host.state.insert(state::VAULT_PERSONAL_MANIFEST_ID.to_string(), json!(PERSONAL_MANIFEST_ID));host.store_local_as_blob();host.respond("GET", "Status", json!({ "clientVersionSupported": true, "serverVersion": "0.31.0", "manifestRevisions": [{ "manifestId": PERSONAL_MANIFEST_ID, "revision": 3 }], "personalManifestId": PERSONAL_MANIFEST_ID, "srpSalt": "salt" }));- let result = host.drive(&SyncSession::new(&request("fullSync", &kek, false, 0)).unwrap());+ let result = host.drive(&SyncSession::new(&request("fullSync", &unlock_key, false, 0)).unwrap());assert_eq!(result["success"], true, "{}", result);assert_eq!(result["manifestMigrationRequired"], true);- let status = host.drive(&SyncSession::new(&request("migrationStatus", &kek, false, 0)).unwrap());+ let status = host.drive(&SyncSession::new(&request("migrationStatus", &unlock_key, false, 0)).unwrap());assert_eq!(status["kind"], "storageFormatUpgrade");}#[test]fn manifest_migration_generates_the_key_hierarchy_and_pushes() {- let kek = crypto::generate_key_base64();+ let unlock_key = crypto::generate_key_base64();let salt = vault_codec::generate_manifest_salt();- let mut host = TestHost::new(&kek);+ let mut host = TestHost::new(&unlock_key);insert_item(&host.local, "aaaaaaaa-0000-4000-8000-000000000001", "Old item", PERSONAL_MANIFEST_ID);host.store_local_as_blob();host.state.insert(state::SERVER_MANIFEST_REVISIONS.to_string(), json!({ PERSONAL_MANIFEST_ID: 3 }));@@ -658,17 +658,18 @@ fn manifest_migration_generates_the_key_hierarchy_and_pushes() {host.respond("POST", "Vault/blobs/missing", json!({ "missing": [] }));host.respond("POST", "Vault", json!({ "status": 0, "manifestRevisions": [{ "manifestId": PERSONAL_MANIFEST_ID, "revision": 4 }], "bucketRevisions": [], "missingBlobHashes": [] }));- let result = host.drive(&SyncSession::new(&request("migrateManifest", &kek, false, 0)).unwrap());+ let result = host.drive(&SyncSession::new(&request("migrateManifest", &unlock_key, false, 0)).unwrap());assert_eq!(result["success"], true, "{}", result);assert_eq!(result["pushed"], true);let new_key = host.vault_key.clone();- assert_ne!(new_key, kek, "the host receives the new VEK through the store command");+ assert_ne!(new_key, unlock_key, "the host receives the new VEK through the store command");let posts: Vec<_> = host.requests_to("Vault").into_iter().filter(|r| r.method == "POST").collect();let body = posts[0].body.as_ref().unwrap();assert!(body["migration"]["accountKeys"]["encryptedAccountKey"].is_string(), "the migration push carries the key hierarchy");- let (vek, _) = crypto::resolve_vault_encryption_key(body["migration"]["accountKeys"]["encryptedAccountKey"].as_str().unwrap(), body["migration"]["accountKeys"]["encryptedVek"].as_str().unwrap(), &kek).unwrap();- assert_eq!(*vek, new_key);+ assert!(crypto::unwrap_key(body["migration"]["accountKeys"]["encryptedAccountKey"].as_str().unwrap(), &unlock_key).is_err(), "the legacy vault key is not the KEK");+ let opened = crypto::open_account_key_chain(&unlock_key, body["migration"]["accountKeys"]["encryptedAccountKey"].as_str().unwrap(), body["migration"]["accountKeys"]["encryptedVek"].as_str().unwrap(), None).unwrap();+ assert_eq!(*opened.vault_encryption_key, new_key);assert!(host.state.contains_key(state::ENCRYPTED_ACCOUNT_KEY));assert!(host.state.contains_key(state::ENCRYPTED_ACCOUNT_PRIVATE_KEY));assert_eq!(host.rekeyed_stores_found_the_chain, vec![true], "the chain is cached before the vault is stored under the VEK");@@ -676,8 +677,8 @@ fn manifest_migration_generates_the_key_hierarchy_and_pushes() {#[test]fn account_upgrade_decodes_base64_text_that_0_30_merges_left_in_blob_columns() {- let kek = crypto::generate_key_base64();- let mut host = TestHost::new(&kek);+ let unlock_key = crypto::generate_key_base64();+ let mut host = TestHost::new(&unlock_key);let item = "aaaaaaaa-0000-4000-8000-000000000001";let bytes = vec![0x00u8, 0xFF, 0xC3, 0x28, 0x10];let text = crate::common::encoding::base64_encode(&bytes);@@ -694,7 +695,7 @@ fn account_upgrade_decodes_base64_text_that_0_30_merges_left_in_blob_columns() {host.respond("POST", "Vault/blobs", json!({}));host.respond("POST", "Vault", json!({ "status": 0, "manifestRevisions": [{ "manifestId": PERSONAL_MANIFEST_ID, "revision": 4 }], "bucketRevisions": [], "missingBlobHashes": [] }));- let result = host.drive(&SyncSession::new(&request("migrateManifest", &kek, false, 0)).unwrap());+ let result = host.drive(&SyncSession::new(&request("migrateManifest", &unlock_key, false, 0)).unwrap());assert_eq!(result["success"], true, "{} {:?}", result, host.logs);let cell = |sql: &str| host.local.query_row(sql, [], |row| Ok((row.get::<_, String>(0)?, row.get_ref(1)?.as_bytes().map(<[u8]>::to_vec).ok()))).unwrap();@@ -740,12 +741,12 @@ fn schema_rebuild_of_a_stale_vault_pushes_without_touching_the_key_hierarchy() {}/// A legacy sqlite-blob snapshot of the given database, as the server serves an account that has not migrated.-fn legacy_snapshot_of(conn: &rusqlite::Connection, kek: &str, revision: i64) -> Value {+fn legacy_snapshot_of(conn: &rusqlite::Connection, unlock_key: &str, revision: i64) -> Value {let bytes = conn.serialize(rusqlite::MAIN_DB).unwrap().to_vec();json!({"status": 0,"storageFormat": 0,- "legacyVaultBlob": crypto::symmetric_encrypt_bytes(&bytes, kek).unwrap(),+ "legacyVaultBlob": crypto::symmetric_encrypt_bytes(&bytes, unlock_key).unwrap(),"legacyRevision": revision,"personalManifestId": PERSONAL_MANIFEST_ID,"emailRouting": { "privateEmailDomainList": ["private.io"], "publicEmailDomainList": [], "hiddenPrivateEmailDomainList": [], "emailAddressList": [] },@@ -754,13 +755,13 @@ fn legacy_snapshot_of(conn: &rusqlite::Connection, kek: &str, revision: i64) ->/// A host as a client predating the manifest storage format leaves it: a sqlite blob under the KEK, no personal/// manifest id and no revision baseline, against a server that still holds the account as a legacy vault.-fn pre_format_session_host(kek: &str, local_item: &str, server_item: &str) -> TestHost {- let mut host = TestHost::new(kek);+fn pre_format_session_host(unlock_key: &str, local_item: &str, server_item: &str) -> TestHost {+ let mut host = TestHost::new(unlock_key);insert_item(&host.local, "aaaaaaaa-0000-4000-8000-000000000001", local_item, PERSONAL_MANIFEST_ID);host.store_local_as_blob();let server_db = test_host::open_schema_db(&host.schema_sql);insert_item(&server_db, "aaaaaaaa-0000-4000-8000-000000000002", server_item, PERSONAL_MANIFEST_ID);- host.respond("GET", "Vault", legacy_snapshot_of(&server_db, kek, 3));+ host.respond("GET", "Vault", legacy_snapshot_of(&server_db, unlock_key, 3));host.respond_with(Box::new(|method, path, _| if method == "GET" && path == "VaultKey/Password" { Some((200, json!({ "vaultKey": null }))) } else { None }));host.respond("POST", "Vault/blobs/missing", json!({ "missing": [] }));host.respond("POST", "Vault", json!({ "status": 0, "manifestRevisions": [{ "manifestId": PERSONAL_MANIFEST_ID, "revision": 4 }], "bucketRevisions": [], "missingBlobHashes": [] }));@@ -769,10 +770,10 @@ fn pre_format_session_host(kek: &str, local_item: &str, server_item: &str) -> Te#[test]fn manifest_migration_of_a_pre_format_session_pulls_the_server_vault_first() {- let kek = crypto::generate_key_base64();- let mut host = pre_format_session_host(&kek, "Local item", "Server item");+ let unlock_key = crypto::generate_key_base64();+ let mut host = pre_format_session_host(&unlock_key, "Local item", "Server item");- let result = host.drive(&SyncSession::new(&request("migrateManifest", &kek, false, 0)).unwrap());+ let result = host.drive(&SyncSession::new(&request("migrateManifest", &unlock_key, false, 0)).unwrap());assert_eq!(result["success"], true, "{}", result);assert_eq!(result["pushed"], true);@@ -788,11 +789,11 @@ fn manifest_migration_of_a_pre_format_session_pulls_the_server_vault_first() {#[test]fn manifest_migration_of_a_dirty_pre_format_session_keeps_the_local_vault() {- let kek = crypto::generate_key_base64();- let mut host = pre_format_session_host(&kek, "Local item", "Server item");+ let unlock_key = crypto::generate_key_base64();+ let mut host = pre_format_session_host(&unlock_key, "Local item", "Server item");host.is_dirty = true;- let result = host.drive(&SyncSession::new(&request("migrateManifest", &kek, true, 1)).unwrap());+ let result = host.drive(&SyncSession::new(&request("migrateManifest", &unlock_key, true, 1)).unwrap());assert_eq!(result["success"], true, "{}", result);assert_eq!(result["pushed"], true);@@ -853,10 +854,10 @@ fn vault_key_body(hierarchy: &crypto::AccountKeyHierarchy) -> Value {/// together with the VEK it is now encrypted under.#[test]fn a_hierarchy_created_on_another_device_is_accepted_on_the_next_pull() {- let kek = crypto::generate_key_base64();- let hierarchy = crypto::create_account_key_hierarchy(&kek).unwrap();+ let unlock_key = crypto::generate_key_base64();+ let hierarchy = crypto::create_account_key_hierarchy(&unlock_key).unwrap();let vek = hierarchy.vault_encryption_key.clone();- let mut host = TestHost::new(&kek);+ let mut host = TestHost::new(&unlock_key);let server_db = test_host::open_schema_db(&host.schema_sql);insert_item(&server_db, "aaaaaaaa-0000-4000-8000-000000000001", "Server item", PERSONAL_MANIFEST_ID);@@ -865,7 +866,7 @@ fn a_hierarchy_created_on_another_device_is_accepted_on_the_next_pull() {host.respond("GET", "VaultKey/Password", vault_key_body(&hierarchy));host.respond("GET", "Vault", vault);- let result = host.drive(&SyncSession::new(&request("fullSync", &kek, false, 0)).unwrap());+ let result = host.drive(&SyncSession::new(&request("fullSync", &unlock_key, false, 0)).unwrap());assert_eq!(result["success"], true, "{}", result);assert_eq!(host.vault_key, vek, "the store carried the VEK, so the host switched to it before opening the blob");@@ -880,12 +881,12 @@ fn a_hierarchy_created_on_another_device_is_accepted_on_the_next_pull() {/// cached for offline unlock, and the VEK comes back as the key to store.#[test]fn resolve_vault_key_opens_the_chain_from_the_server() {- let kek = crypto::generate_key_base64();- let hierarchy = crypto::create_account_key_hierarchy(&kek).unwrap();- let mut host = TestHost::new(&kek);+ let unlock_key = crypto::generate_key_base64();+ let hierarchy = crypto::create_account_key_hierarchy(&unlock_key).unwrap();+ let mut host = TestHost::new(&unlock_key);host.respond("GET", "VaultKey/Password", vault_key_body(&hierarchy));- let result = host.drive(&SyncSession::new(&request("resolveVaultKey", &kek, false, 0)).unwrap());+ let result = host.drive(&SyncSession::new(&request("resolveVaultKey", &unlock_key, false, 0)).unwrap());assert_eq!(result["success"], true, "{}", result);assert_eq!(result["hasVaultKey"], true);@@ -895,32 +896,48 @@ fn resolve_vault_key_opens_the_chain_from_the_server() {assert!(host.store_calls.is_empty(), "resolving a key never touches the stored vault");}+/// A device that stores the Account Key (Login with Mobile from a phone that converted its keychain) resolves with it+/// as well as with the unlock key.+#[test]+fn resolve_vault_key_opens_the_chain_with_a_stored_account_key() {+ let unlock_key = crypto::generate_key_base64();+ let hierarchy = crypto::create_account_key_hierarchy(&unlock_key).unwrap();+ let account_key = crypto::unwrap_account_key(&hierarchy.account_keys.encrypted_account_key, &unlock_key).unwrap();+ let mut host = TestHost::new(&account_key);+ host.respond("GET", "VaultKey/Password", vault_key_body(&hierarchy));++ let result = host.drive(&SyncSession::new(&request("resolveVaultKey", &account_key, false, 0)).unwrap());++ assert_eq!(result["success"], true, "{}", result);+ assert_eq!(result["encryptionKey"], hierarchy.vault_encryption_key);+}+/// A legacy account has no chain: the password-derived key is the vault key and any stale cached chain is dropped.#[test]fn resolve_vault_key_keeps_the_kek_for_a_legacy_account() {- let kek = crypto::generate_key_base64();- let mut host = TestHost::new(&kek);+ let unlock_key = crypto::generate_key_base64();+ let mut host = TestHost::new(&unlock_key);host.state.insert(state::ENCRYPTED_ACCOUNT_KEY.to_string(), json!("stale"));host.respond("GET", "VaultKey/Password", json!({ "vaultKey": null }));- let result = host.drive(&SyncSession::new(&request("resolveVaultKey", &kek, false, 0)).unwrap());+ let result = host.drive(&SyncSession::new(&request("resolveVaultKey", &unlock_key, false, 0)).unwrap());assert_eq!(result["success"], true, "{}", result);assert_eq!(result["hasVaultKey"], false);- assert_eq!(result["encryptionKey"], kek);+ assert_eq!(result["encryptionKey"], unlock_key);assert!(!host.state.contains_key(state::ENCRYPTED_ACCOUNT_KEY));}/// Offline, the cached chain opens with the password-derived key (a re-login after a forced logout).#[test]fn resolve_vault_key_opens_the_cached_chain_when_the_server_is_unreachable() {- let kek = crypto::generate_key_base64();- let hierarchy = crypto::create_account_key_hierarchy(&kek).unwrap();- let mut host = TestHost::new(&kek);+ let unlock_key = crypto::generate_key_base64();+ let hierarchy = crypto::create_account_key_hierarchy(&unlock_key).unwrap();+ let mut host = TestHost::new(&unlock_key);host.state.insert(state::ENCRYPTED_ACCOUNT_KEY.to_string(), json!(hierarchy.account_keys.encrypted_account_key));host.state.insert(state::ENCRYPTED_VEK.to_string(), json!(hierarchy.account_keys.encrypted_vek));- let result = host.drive(&SyncSession::new(&request("resolveVaultKey", &kek, false, 0)).unwrap());+ let result = host.drive(&SyncSession::new(&request("resolveVaultKey", &unlock_key, false, 0)).unwrap());assert_eq!(result["success"], true, "{}", result);assert_eq!(result["hasVaultKey"], true);@@ -945,13 +962,13 @@ fn resolve_vault_key_refuses_a_key_that_does_not_open_the_chain() {/// A chain whose VEK does not open under its own account key is not reported as a wrong password.#[test]fn resolve_vault_key_tells_an_unreadable_chain_apart_from_a_wrong_password() {- let kek = crypto::generate_key_base64();- let mut hierarchy = crypto::create_account_key_hierarchy(&kek).unwrap();+ let unlock_key = crypto::generate_key_base64();+ let mut hierarchy = crypto::create_account_key_hierarchy(&unlock_key).unwrap();hierarchy.account_keys.encrypted_vek = crypto::wrap_key(&crypto::generate_key_base64(), &crypto::generate_key_base64()).unwrap();- let mut host = TestHost::new(&kek);+ let mut host = TestHost::new(&unlock_key);host.respond("GET", "VaultKey/Password", vault_key_body(&hierarchy));- let result = host.drive(&SyncSession::new(&request("resolveVaultKey", &kek, false, 0)).unwrap());+ let result = host.drive(&SyncSession::new(&request("resolveVaultKey", &unlock_key, false, 0)).unwrap());assert_eq!(result["success"], false);assert_eq!(result["errorCode"], "E-207");@@ -961,8 +978,8 @@ fn resolve_vault_key_tells_an_unreadable_chain_apart_from_a_wrong_password() {/// so the run fails to open the vault instead of silently swapping keys. Resolving the key is the host's job.#[test]fn a_kek_session_on_a_migrated_device_is_not_upgraded_by_the_sync() {- let kek = crypto::generate_key_base64();- let hierarchy = crypto::create_account_key_hierarchy(&kek).unwrap();+ let unlock_key = crypto::generate_key_base64();+ let hierarchy = crypto::create_account_key_hierarchy(&unlock_key).unwrap();let vek = hierarchy.vault_encryption_key.clone();let mut host = TestHost::new(&vek);host.store_local_as_blob();@@ -971,7 +988,7 @@ fn a_kek_session_on_a_migrated_device_is_not_upgraded_by_the_sync() {host.state.insert(state::SERVER_MANIFEST_REVISIONS.to_string(), json!({ PERSONAL_MANIFEST_ID: 3 }));host.respond("GET", "Status", json!({ "clientVersionSupported": true, "serverVersion": "0.31.0", "manifestRevisions": [{ "manifestId": PERSONAL_MANIFEST_ID, "revision": 4 }], "personalManifestId": PERSONAL_MANIFEST_ID, "srpSalt": "salt" }));- host.drive(&SyncSession::new(&request("fullSync", &kek, false, 0)).unwrap());+ host.drive(&SyncSession::new(&request("fullSync", &unlock_key, false, 0)).unwrap());assert!(host.store_calls.iter().all(|c| matches!(c, Command::VaultStore { encryption_key: None, .. })), "no key swap reaches the host");assert!(host.requests_to("VaultKey/Password").is_empty(), "a device with a cached chain is never probed");@@ -980,8 +997,8 @@ fn a_kek_session_on_a_migrated_device_is_not_upgraded_by_the_sync() {/// The VEK itself opens nothing in the chain and stands as the session key.#[test]fn a_vek_session_key_is_left_alone() {- let kek = crypto::generate_key_base64();- let hierarchy = crypto::create_account_key_hierarchy(&kek).unwrap();+ let unlock_key = crypto::generate_key_base64();+ let hierarchy = crypto::create_account_key_hierarchy(&unlock_key).unwrap();let vek = hierarchy.vault_encryption_key.clone();let mut host = TestHost::new(&vek);host.store_local_as_blob();@@ -999,14 +1016,14 @@ fn a_vek_session_key_is_left_alone() {/// A legacy account that is clean and in sync is not probed for a vault key: the probe belongs to a pull or a push.#[test]fn clean_legacy_account_in_sync_is_not_probed_for_a_vault_key() {- let kek = crypto::generate_key_base64();- let mut host = TestHost::new(&kek);+ let unlock_key = crypto::generate_key_base64();+ let mut host = TestHost::new(&unlock_key);host.store_local_as_blob();host.state.insert(state::SERVER_MANIFEST_REVISIONS.to_string(), json!({ PERSONAL_MANIFEST_ID: 3 }));host.state.insert(state::VAULT_PERSONAL_MANIFEST_ID.to_string(), json!(PERSONAL_MANIFEST_ID));host.respond("GET", "Status", json!({ "clientVersionSupported": true, "serverVersion": "0.31.0", "manifestRevisions": [{ "manifestId": PERSONAL_MANIFEST_ID, "revision": 3 }], "personalManifestId": PERSONAL_MANIFEST_ID, "srpSalt": "salt" }));- let result = host.drive(&SyncSession::new(&request("fullSync", &kek, false, 0)).unwrap());+ let result = host.drive(&SyncSession::new(&request("fullSync", &unlock_key, false, 0)).unwrap());assert_eq!(result["success"], true, "{}", result);assert!(host.requests_to("VaultKey/Password").is_empty());@@ -1015,9 +1032,9 @@ fn clean_legacy_account_in_sync_is_not_probed_for_a_vault_key() {/// A dirty legacy account probes the server for a vault key once per run, not once per step.#[test]fn dirty_legacy_account_probes_for_a_vault_key_once_per_run() {- let kek = crypto::generate_key_base64();+ let unlock_key = crypto::generate_key_base64();let salt = vault_codec::generate_manifest_salt();- let mut host = TestHost::new(&kek);+ let mut host = TestHost::new(&unlock_key);insert_item(&host.local, "aaaaaaaa-0000-4000-8000-000000000001", "Local item", PERSONAL_MANIFEST_ID);host.store_local_as_blob();host.state.insert(state::SERVER_MANIFEST_REVISIONS.to_string(), json!({ PERSONAL_MANIFEST_ID: 3 }));@@ -1028,7 +1045,7 @@ fn dirty_legacy_account_probes_for_a_vault_key_once_per_run() {host.respond("POST", "Vault/blobs/missing", json!({ "missing": [] }));host.respond("POST", "Vault", json!({ "status": 0, "manifestRevisions": [{ "manifestId": PERSONAL_MANIFEST_ID, "revision": 4 }], "bucketRevisions": [], "missingBlobHashes": [] }));- let result = host.drive(&SyncSession::new(&request("fullSync", &kek, true, 1)).unwrap());+ let result = host.drive(&SyncSession::new(&request("fullSync", &unlock_key, true, 1)).unwrap());assert_eq!(result["success"], true, "{}", result);assert_eq!(host.requests_to("VaultKey/Password").len(), 1);