Skip to content

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

Update encryption key extract method (#2159)

Leendert de Borstff0667172d2a
diff --git a/apps/browser-extension/src/utils/RustCore.ts b/apps/browser-extension/src/utils/RustCore.ts
index ab9f2ddc7..9bb376120 100644
--- a/apps/browser-extension/src/utils/RustCore.ts
+++ b/apps/browser-extension/src/utils/RustCore.ts
@@ -274,14 +274,12 @@ export async function vaultCodecMaterializeAsSqlite(manifest: CodecManifest, dat
}
/**
- * Extract the primary encryption-key row (the user's asymmetric keypair) from the decrypted
- * `EncryptionKeys` data bucket — the small, independently-decryptable bucket the keypair now lives in.
- * Used to unwrap shared-folder VEKs during pull without materializing the full root manifest.
- * Returns null when the bucket carries no primary key.
+ * Extract the encryption-key row whose `PublicKey` matches `publicKey` from the decrypted `EncryptionKeys`
+ * data bucket. Returns null when no live row carries that key.
*/
-export async function vaultCodecExtractPrimaryEncryptionKeyFromBucket(bucket: CodecDataBucket): Promise<Record<string, unknown> | null> {
+export async function vaultCodecExtractEncryptionKeyForPublicKeyFromBucket(bucket: CodecDataBucket, publicKey: string): Promise<Record<string, unknown> | null> {
await initRustCore();
- return (core.vaultCodecExtractPrimaryEncryptionKeyFromBucket(bucket) ?? null) as Record<string, unknown> | null;
+ return (core.vaultCodecExtractEncryptionKeyForPublicKeyFromBucket(bucket, publicKey) ?? null) as Record<string, unknown> | null;
}
/**
diff --git a/core/rust/src/ffi.rs b/core/rust/src/ffi.rs
index 47c3ac3a6..9f4e126e3 100644
--- a/core/rust/src/ffi.rs
+++ b/core/rust/src/ffi.rs
@@ -271,14 +271,20 @@ pub unsafe extern "C" fn vault_codec_validate_data_bucket_ffi(input_json: *const
codec_json_ffi(input_json, "input_json", crate::vault_codec::validate_data_bucket_json)
}
-/// Extract the primary encryption-key row from the decrypted `EncryptionKeys` data bucket.
-/// Input: `DataBucket` JSON. Output: the `EncryptionKeys` row JSON object, or `null` when absent.
+/// Extract the encryption-key row whose `PublicKey` matches `public_key` from the decrypted `EncryptionKeys`
+/// data bucket. Input: `DataBucket` JSON + the target public key. Output: the matching row JSON object, or
+/// `null` when no live row carries that key.
///
/// # Safety
-/// `input_json` must be a valid null-terminated C string; free the result with `free_string`.
+/// `input_json` and `public_key` must be valid null-terminated C strings; free the result with `free_string`.
#[no_mangle]
-pub unsafe extern "C" fn vault_codec_extract_primary_encryption_key_from_bucket_ffi(input_json: *const c_char) -> *mut c_char {
- codec_json_ffi(input_json, "input_json", crate::vault_codec::extract_primary_encryption_key_from_bucket_json)
+pub unsafe extern "C" fn vault_codec_extract_encryption_key_for_public_key_from_bucket_ffi(input_json: *const c_char, public_key: *const c_char) -> *mut c_char {
+ let bucket = ffi_read_str!(input_json, "input_json");
+ let key = ffi_read_str!(public_key, "public_key");
+ match crate::vault_codec::extract_encryption_key_for_public_key_from_bucket_json(bucket, key) {
+ Ok(json) => string_to_c_char(json),
+ Err(e) => create_error_response(&format!("vault_codec error: {}", e)),
+ }
}
/// The bucket layout: `[{ category, tables: [<name>] }]` JSON.
diff --git a/core/rust/src/uniffi_api.rs b/core/rust/src/uniffi_api.rs
index 20178c037..9492af96a 100644
--- a/core/rust/src/uniffi_api.rs
+++ b/core/rust/src/uniffi_api.rs
@@ -210,11 +210,13 @@ pub fn vault_codec_compute_ciphertext_hash(base64_ciphertext: String) -> String
crate::vault_codec::compute_ciphertext_hash(&base64_ciphertext)
}
-/// Extract the primary encryption-key row from the decrypted `EncryptionKeys` data bucket.
-/// Input: `DataBucket` JSON. Output: the `EncryptionKeys` row JSON object, or `null` when absent.
+/// Extract the encryption-key row whose `PublicKey` matches `public_key` from the decrypted `EncryptionKeys`
+/// data bucket. Input: `DataBucket` JSON + the target public key. Output: the matching row JSON object, or
+/// `null` when no live row carries that key. Chosen over the primary key so a shared-folder VEK wrapped for
+/// an older key still unwraps after key rotation.
#[uniffi::export]
-pub fn vault_codec_extract_primary_encryption_key_from_bucket(bucket_json: String) -> Result<String, VaultError> {
- crate::vault_codec::extract_primary_encryption_key_from_bucket_json(&bucket_json)
+pub fn vault_codec_extract_encryption_key_for_public_key_from_bucket(bucket_json: String, public_key: String) -> Result<String, VaultError> {
+ crate::vault_codec::extract_encryption_key_for_public_key_from_bucket_json(&bucket_json, &public_key)
}
// ═══════════════════════════════════════════════════════════════════════════════
diff --git a/core/rust/src/vault_codec/mod.rs b/core/rust/src/vault_codec/mod.rs
index cbd5d97f8..656cfb358 100644
--- a/core/rust/src/vault_codec/mod.rs
+++ b/core/rust/src/vault_codec/mod.rs
@@ -28,7 +28,7 @@ pub use manifest::{
BlobEntry, BucketLayoutEntry, CanonicalizeInput, CanonicalizedVault, CodecOverflow, DataBucket,
Manifest, MaterializeInput, MaterializedTables, CodecRecord, CodecTableData, SharedFolderSpec, SharedVault,
};
-pub use sharing::extract_primary_encryption_key_from_bucket;
+pub use sharing::extract_encryption_key_for_public_key_from_bucket;
pub use types::{
bucket_categories, bucket_category_for, is_personal_table, tables_for_category, BLOB_COLUMNS, BUCKET_TABLES,
OVERFLOW_ROW_ID, OVERFLOW_TABLE, PERSONAL_TABLES, SCHEMA_VERSION, SKIP_TABLES,
@@ -137,12 +137,11 @@ pub fn validate_data_bucket(b: &DataBucket) -> ValidationResult {
validate::validate_data_bucket(b)
}
-/// Extract the primary encryption-key row from the decrypted `EncryptionKeys` data bucket — used to
-/// unwrap shared-folder VEKs during pull, decrypting only the small keypair bucket rather than the
-/// full root manifest.
-pub fn extract_primary_encryption_key_from_bucket_json(bucket_json: &str) -> VaultResult<String> {
+/// Extract the encryption-key row whose `PublicKey` matches `public_key` from the decrypted
+/// `EncryptionKeys` data bucket.
+pub fn extract_encryption_key_for_public_key_from_bucket_json(bucket_json: &str, public_key: &str) -> VaultResult<String> {
let b: DataBucket = serde_json::from_str(bucket_json)?;
- Ok(serde_json::to_string(&extract_primary_encryption_key_from_bucket(&b))?)
+ Ok(serde_json::to_string(&extract_encryption_key_for_public_key_from_bucket(&b, public_key))?)
}
/// SHA-256 (lowercase hex) of a base64 ciphertext string — storage-layer integrity.
diff --git a/core/rust/src/vault_codec/sharing.rs b/core/rust/src/vault_codec/sharing.rs
index 7616c6642..7d9c0803d 100644
--- a/core/rust/src/vault_codec/sharing.rs
+++ b/core/rust/src/vault_codec/sharing.rs
@@ -244,21 +244,17 @@ fn null_dangling_parent_folders(tables: &mut HashMap<String, Vec<CodecRecord>>)
}
}
-/// Pick the current primary key row out of an `EncryptionKeys` table: the first non-deleted primary row.
-fn primary_key_row(tables: &HashMap<String, Vec<CodecRecord>>) -> Option<CodecRecord> {
- tables
+/// Extract the encryption-key row whose `PublicKey` matches `public_key`, straight from the decrypted
+/// `EncryptionKeys` data bucket. Deleted rows are skipped. Returns `None` when no live row carries that key.
+pub fn extract_encryption_key_for_public_key_from_bucket(bucket: &DataBucket, public_key: &str) -> Option<CodecRecord> {
+ bucket
+ .tables
.get("EncryptionKeys")?
.iter()
- .find(|row| is_truthy(row.get("IsPrimary")) && !is_truthy(row.get("IsDeleted")))
+ .find(|row| str_col(row, "PublicKey") == Some(public_key) && !is_truthy(row.get("IsDeleted")))
.cloned()
}
-/// Extract the primary encryption-key row (the user's asymmetric keypair, e.g. for unwrapping shared-folder VEKs)
-/// straight from the decrypted `EncryptionKeys` data bucket.
-pub fn extract_primary_encryption_key_from_bucket(bucket: &DataBucket) -> Option<CodecRecord> {
- primary_key_row(&bucket.tables)
-}
-
/// Map every folder inside a spec's subtree (root included) to that spec's index. Errors when one
/// spec's folder lies inside another spec's subtree (nested shares are not supported).
fn compute_subtrees(folder_rows: &[CodecRecord], specs: &[SharedFolderSpec]) -> VaultResult<HashMap<String, usize>> {
diff --git a/core/rust/src/wasm.rs b/core/rust/src/wasm.rs
index 703fd614d..691713fc7 100644
--- a/core/rust/src/wasm.rs
+++ b/core/rust/src/wasm.rs
@@ -214,13 +214,14 @@ pub fn vault_codec_compute_ciphertext_hash_js(base64_ciphertext: &str) -> String
vault_codec::compute_ciphertext_hash(base64_ciphertext)
}
-/// Extract the primary encryption-key row from the decrypted `EncryptionKeys` data bucket.
-/// Input: `DataBucket`. Output: the `EncryptionKeys` row object, or null when the bucket has none.
-#[wasm_bindgen(js_name = vaultCodecExtractPrimaryEncryptionKeyFromBucket)]
-pub fn vault_codec_extract_primary_encryption_key_from_bucket_js(bucket: JsValue) -> Result<JsValue, JsValue> {
+/// Extract the encryption-key row whose `PublicKey` matches `public_key` from the decrypted `EncryptionKeys`
+/// data bucket. Input: `DataBucket` + the target public key. Output: the matching row object, or null when
+/// no live row carries that key.
+#[wasm_bindgen(js_name = vaultCodecExtractEncryptionKeyForPublicKeyFromBucket)]
+pub fn vault_codec_extract_encryption_key_for_public_key_from_bucket_js(bucket: JsValue, public_key: &str) -> Result<JsValue, JsValue> {
let b: DataBucket = serde_wasm_bindgen::from_value(bucket)
.map_err(|e| JsValue::from_str(&format!("Failed to parse data bucket: {}", e)))?;
- codec_to_js(&vault_codec::extract_primary_encryption_key_from_bucket(&b))
+ codec_to_js(&vault_codec::extract_encryption_key_for_public_key_from_bucket(&b, public_key))
}
// ═══════════════════════════════════════════════════════════════════════════════