Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Use SecretString (#2468)
Leendert de Borstc6432ab3c4ec
diff --git a/core/rust/Cargo.lock b/core/rust/Cargo.lockindex 25caf9106..83970a50b 100644--- a/core/rust/Cargo.lock+++ b/core/rust/Cargo.lock@@ -66,6 +66,7 @@ dependencies = ["rand_core 0.6.4","rsa","rusqlite",+ "secrecy","serde","serde-wasm-bindgen","serde_json",@@ -1296,6 +1297,16 @@ dependencies = ["zeroize",]+[[package]]+name = "secrecy"+version = "0.10.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e891af845473308773346dc847b2c23ee78fe442e0472ac50e22a18a93d3ae5a"+dependencies = [+ "serde",+ "zeroize",+]+[[package]]name = "semver"version = "1.0.28"diff --git a/core/rust/Cargo.toml b/core/rust/Cargo.tomlindex f8f87aa5e..49713df25 100644--- a/core/rust/Cargo.toml+++ b/core/rust/Cargo.toml@@ -67,6 +67,8 @@ rand_core06 = { package = "rand_core", version = "0.6", features = ["getrandom"]# Wipes key material from memory on dropzeroize = { version = "1.8", features = ["derive"] }+# Secret strings: wiped on drop, redacted in Debug, read only via expose_secret()+secrecy = { version = "0.10", features = ["serde"] }# gzip for the vault_codec packaged format and stored email sourcesflate2 = { version = "1.0", default-features = false, features = ["rust_backend"] }diff --git a/core/rust/src/common/mod.rs b/core/rust/src/common/mod.rsindex 67e5427e4..020a28d2a 100644--- a/core/rust/src/common/mod.rs+++ b/core/rust/src/common/mod.rs@@ -1,7 +1,8 @@-//! Crate-wide helpers the feature modules share: errors, byte encodings, gzip, randomness and timestamps.+//! Crate-wide helpers the feature modules share: errors, byte encodings, gzip, randomness, secret strings and timestamps.pub(crate) mod encoding;pub mod error;pub(crate) mod gzip;pub(crate) mod rng;+pub(crate) mod secret;pub mod timestamp;diff --git a/core/rust/src/common/secret.rs b/core/rust/src/common/secret.rsnew file mode 100644index 000000000..73df0c3d4--- /dev/null+++ b/core/rust/src/common/secret.rs@@ -0,0 +1,37 @@+//! Helpers for `SecretString`: moving key text in without a copy, and writing it back out over the JSON boundary.++use secrecy::{ExposeSecret, SecretString};+use serde::Serializer;+use zeroize::Zeroizing;++/// Moves a zeroizing string into a `SecretString` without copying the text.+pub fn from_zeroizing(mut value: Zeroizing<String>) -> SecretString {+ SecretString::from(std::mem::take(&mut *value))+}++/// Writes an optional secret as a plain JSON string, for `#[serde(serialize_with = ...)]`.+pub fn serialize_option<S: Serializer>(value: &Option<SecretString>, serializer: S) -> Result<S::Ok, S::Error> {+ match value {+ Some(secret) => serializer.serialize_some(secret.expose_secret()),+ None => serializer.serialize_none(),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde::{Deserialize, Serialize};++ #[derive(Debug, Serialize, Deserialize)]+ struct Holder {+ #[serde(serialize_with = "serialize_option")]+ key: Option<SecretString>,+ }++ #[test]+ fn round_trips_as_a_plain_string_and_never_prints() {+ let holder: Holder = serde_json::from_str(r#"{"key":"k"}"#).unwrap();+ assert_eq!(serde_json::to_string(&holder).unwrap(), r#"{"key":"k"}"#);+ assert!(format!("{:?}", holder).contains("[REDACTED]"));+ }+}diff --git a/core/rust/src/vault_sync/engine.rs b/core/rust/src/vault_sync/engine.rsindex 4caa6df79..be8a4573d 100644--- a/core/rust/src/vault_sync/engine.rs+++ b/core/rust/src/vault_sync/engine.rs@@ -1,6 +1,7 @@//! The sync flow: status check, server-directed changes, then pull (and merge) or push as the revisions decide.use std::collections::HashMap;+use secrecy::ExposeSecret;use serde_json::Value;@@ -331,7 +332,7 @@ async fn refresh_manifest_names(ctx: &mut Ctx, status: &StatusResponse, needs_pufor record in records.values_mut() {let Some(served) = ctx.served_manifest_names.get(&id_key(&record.manifest_id)).filter(|served| record.encrypted_name.as_ref() != Some(*served)).cloned() else { continue };let Some(vek) = keys::open_shared_manifest_vek(ctx, record).await? else { continue };- match pull::open_manifest_name(&served, &record.manifest_id, &vek) {+ match pull::open_manifest_name(&served, &record.manifest_id, vek.expose_secret()) {Some(name) => drop(opened.insert(id_key(&record.manifest_id), name)),None => ctx.warn(format!("[Sharing] The name of shared manifest {} did not open with its key.", record.manifest_id)).await,}@@ -344,7 +345,7 @@ async fn refresh_manifest_names(ctx: &mut Ctx, status: &StatusResponse, needs_pulet key = ctx.encryption_key()?;db::apply_manifest_names(&ctx.host, super::types::Db::Local, &opened).await?;ctx.persist_local_vault(false).await?;- keys::set_shared_manifest_records(ctx, &records, &key).await?;+ keys::set_shared_manifest_records(ctx, &records, key.expose_secret()).await?;ctx.log(format!("[Sharing] Refreshed the name of {} shared manifest(s).", opened.len())).await;Ok(true)}diff --git a/core/rust/src/vault_sync/keys.rs b/core/rust/src/vault_sync/keys.rsindex e19051c41..df5a058f5 100644--- a/core/rust/src/vault_sync/keys.rs+++ b/core/rust/src/vault_sync/keys.rs@@ -2,11 +2,15 @@use std::collections::HashMap;+use zeroize::Zeroizing;+use super::errors::{SyncError, SyncResult};use super::session::Host;use super::state::{self, Ctx};use super::types::{ManifestDto, SharedManifestDto, VaultKeyGetResponse, VaultKeyResponse, ALGORITHM_AES256_GCM, ALGORITHM_RSA_OAEP_SHA256};use super::http;+use crate::common::secret::from_zeroizing;+use secrecy::{ExposeSecret, SecretString};use crate::crypto;/// Whether this device has the account's key chain cached (the encrypted Account Key).@@ -56,20 +60,21 @@ async fn clear_cached_chain(host: &Host) -> SyncResult<()> {/// Open a key chain with the unlock key or the stored Account Key: stages the Account Key and the account private key/// for this run and returns the VEK, which the caller makes the session key.-async fn open_chain(ctx: &mut Ctx, encrypted_account_key: &str, encrypted_vek: &str, encrypted_private_key: Option<&str>, unlock_key: &str) -> SyncResult<String> {- let opened = crypto::open_account_key_chain(unlock_key, encrypted_account_key, encrypted_vek, None)?;- ctx.account_key = Some(opened.account_key.to_string());+async fn open_chain(ctx: &mut Ctx, encrypted_account_key: &str, encrypted_vek: &str, encrypted_private_key: Option<&str>, unlock_key: &str) -> SyncResult<SecretString> {+ let mut opened = crypto::open_account_key_chain(unlock_key, encrypted_account_key, encrypted_vek, None)?;+ let account_key = from_zeroizing(std::mem::take(&mut opened.account_key));+ ctx.account_key = Some(account_key.clone());if let Some(encrypted) = encrypted_private_key.filter(|e| !e.is_empty()) {- match crypto::open_account_private_key(encrypted, &opened.account_key) {- Ok(private_key) => ctx.account_private_key = Some(private_key),+ match crypto::open_account_private_key(encrypted, account_key.expose_secret()) {+ Ok(private_key) => ctx.account_private_key = Some(SecretString::from(private_key)),Err(error) => ctx.warn(format!("[Keys] The cached account private key did not open; shared grants stay closed. {}", error)).await,}}- Ok(opened.vault_encryption_key.to_string())+ Ok(from_zeroizing(std::mem::take(&mut opened.vault_encryption_key)))}/// Open the chain of a server vault-key response with `unlock_key`, refusing an unknown unlock algorithm first.-async fn open_server_chain(ctx: &mut Ctx, vault_key: &VaultKeyResponse, unlock_key: &str) -> SyncResult<String> {+async fn open_server_chain(ctx: &mut Ctx, vault_key: &VaultKeyResponse, unlock_key: &str) -> SyncResult<SecretString> {ensure_known_unlock_algorithm(vault_key)?;open_chain(ctx, &vault_key.encrypted_account_key, vault_key.encrypted_vek.as_deref().unwrap_or_default(), vault_key.encrypted_account_private_key.as_deref(), unlock_key).await}@@ -81,7 +86,7 @@ pub(crate) async fn resolve_vault_key(ctx: &mut Ctx) -> SyncResult<bool> {ctx.vault_key_probed = true;match http::get::<VaultKeyGetResponse>(&ctx.host, http::VAULT_KEY_PASSWORD_ENDPOINT, false).await {Ok(VaultKeyGetResponse { vault_key: Some(vault_key) }) if vault_key.encrypted_vek.is_some() => {- let vek = open_server_chain(ctx, &vault_key, &unlock_key).await?;+ let vek = open_server_chain(ctx, &vault_key, unlock_key.expose_secret()).await?;ctx.set_encryption_key(vek);cache_vault_key_blobs(&ctx.host, &vault_key).await?;ctx.log("[Keys] Opened the account's key chain; the session key is the VEK.").await;@@ -96,7 +101,7 @@ pub(crate) async fn resolve_vault_key(ctx: &mut Ctx) -> SyncResult<bool> {ctx.warn(format!("[Keys] Could not fetch the key chain, opening the cached one: {}", error)).await;let (Some(encrypted_account_key), Some(encrypted_vek)) = (state::get::<String>(&ctx.host, state::ENCRYPTED_ACCOUNT_KEY).await?, state::get::<String>(&ctx.host, state::ENCRYPTED_VEK).await?) else { return Ok(false) };let encrypted_private_key = state::get::<String>(&ctx.host, state::ENCRYPTED_ACCOUNT_PRIVATE_KEY).await?;- let vek = open_chain(ctx, &encrypted_account_key, &encrypted_vek, encrypted_private_key.as_deref(), &unlock_key).await?;+ let vek = open_chain(ctx, &encrypted_account_key, &encrypted_vek, encrypted_private_key.as_deref(), unlock_key.expose_secret()).await?;ctx.set_encryption_key(vek);Ok(true)}@@ -118,7 +123,7 @@ pub(crate) async fn accept_hierarchy_created_elsewhere(ctx: &mut Ctx) -> SyncResSome(vault_key) if vault_key.encrypted_vek.is_some() => vault_key,_ => return Ok(true),};- let vek = match open_server_chain(ctx, &vault_key, &session_key).await {+ let vek = match open_server_chain(ctx, &vault_key, session_key.expose_secret()).await {Ok(vek) => vek,Err(SyncError::UnlockKeyRejected) => {ctx.warn("[Keys] The session key does not open the key hierarchy the server holds; a re-login is needed.").await;@@ -130,10 +135,10 @@ pub(crate) async fn accept_hierarchy_created_elsewhere(ctx: &mut Ctx) -> SyncRes// The chain is cached before the vault is stored under the VEK: hosts hold the unlock key and derive the vault key from it.cache_vault_key_blobs(&ctx.host, &vault_key).await?;if let Some(encrypted_vault) = state::load_vault(&ctx.host).await? {- let plaintext = state::decrypt_vault_blob(&encrypted_vault, &session_key)?;- state::store_vault_with_key(&ctx.host, &state::encrypt_vault_blob(&plaintext, &vek)?, false, None, None, Some(vek.clone())).await?;+ let plaintext = state::decrypt_vault_blob(&encrypted_vault, session_key.expose_secret())?;+ state::store_vault_with_key(&ctx.host, &state::encrypt_vault_blob(&plaintext, vek.expose_secret())?, false, None, None, Some(vek.clone())).await?;}- re_encrypt_shared_manifest_records(ctx, &vek).await?;+ re_encrypt_shared_manifest_records(ctx, vek.expose_secret()).await?;ctx.set_encryption_key(vek);ctx.log("[Keys] Another device created the account's key hierarchy; accepted it and swapped the session key to the VEK.").await;Ok(true)@@ -152,13 +157,13 @@ pub(crate) async fn ensure_key_chain_accepted(ctx: &mut Ctx) -> SyncResult<bool>/// The account signing private key, opened on first use from the cached encrypted copy with the session's Account Key./// None when that key or the cached copy is missing or does not open it.-pub(crate) async fn signing_private_key(ctx: &mut Ctx) -> SyncResult<Option<String>> {+pub(crate) async fn signing_private_key(ctx: &mut Ctx) -> SyncResult<Option<SecretString>> {if ctx.signing_private_key.is_some() {return Ok(ctx.signing_private_key.clone());}let (Some(account_key), Some(encrypted)) = (ctx.account_key.clone(), state::get::<String>(&ctx.host, state::ENCRYPTED_SIGNING_PRIVATE_KEY).await?) else { return Ok(None) };- match crypto::open_account_signing_private_key(&encrypted, &account_key) {- Ok(private_key) => ctx.signing_private_key = Some(private_key.to_string()),+ match crypto::open_account_signing_private_key(&encrypted, account_key.expose_secret()) {+ Ok(private_key) => ctx.signing_private_key = Some(from_zeroizing(private_key)),Err(error) => ctx.warn(format!("[Keys] The cached signing private key did not open; nothing can be signed this run. {}", error)).await,}Ok(ctx.signing_private_key.clone())@@ -172,7 +177,7 @@ pub(crate) async fn signing_private_key(ctx: &mut Ctx) -> SyncResult<Option<Stripub(crate) async fn shared_manifest_records(ctx: &Ctx) -> SyncResult<HashMap<String, SharedManifestDto>> {let Some(ciphertext) = state::get::<String>(&ctx.host, state::SHARED_MANIFESTS).await? else { return Ok(HashMap::new()) };let Some(key) = &ctx.encryption_key else { return Ok(HashMap::new()) };- match crypto::symmetric_decrypt(&ciphertext, key).and_then(|json| serde_json::from_str(&json).map_err(Into::into)) {+ match crypto::symmetric_decrypt(&ciphertext, key.expose_secret()).and_then(|json| serde_json::from_str(&json).map_err(Into::into)) {Ok(records) => Ok(records),Err(error) => {ctx.warn(format!("[Sharing] The stored shared-manifest key records did not decrypt (re-keyed vault?); treating them as absent. {}", error)).await;@@ -199,7 +204,7 @@ pub(crate) async fn re_encrypt_shared_manifest_records(ctx: &Ctx, new_key: &str)}/// The private key that opens a grant made out to `public_key`.-pub(crate) fn resolve_grant_private_key(ctx: &Ctx, public_key: &str) -> Option<String> {+pub(crate) fn resolve_grant_private_key(ctx: &Ctx, public_key: &str) -> Option<SecretString> {if ctx.account_public_key.as_deref() != Some(public_key) {return None;}@@ -212,13 +217,13 @@ pub(crate) fn encrypt_manifest_vek(manifest_vek: &str, manifest_id: &str, recipi}/// Decrypt a manifest's VEK from a grant made out to this private key for that manifest.-pub(crate) fn decrypt_manifest_vek(encrypted_vek: &str, manifest_id: &str, private_key_jwk: &str) -> SyncResult<String> {- let plaintext = crypto::decrypt_with_private_key_and_label(encrypted_vek, private_key_jwk, &crypto::aad::grant(manifest_id))?;- String::from_utf8(plaintext).map_err(|_| SyncError::Other("Decrypted manifest key is not valid text".to_string()))+pub(crate) fn decrypt_manifest_vek(encrypted_vek: &str, manifest_id: &str, private_key_jwk: &str) -> SyncResult<SecretString> {+ let plaintext = Zeroizing::new(crypto::decrypt_with_private_key_and_label(encrypted_vek, private_key_jwk, &crypto::aad::grant(manifest_id))?);+ std::str::from_utf8(&plaintext).map(SecretString::from).map_err(|_| SyncError::Other("Decrypted manifest key is not valid text".to_string()))}/// Unwrap one shared manifest's VEK from the grant this account holds on it.-pub(crate) async fn open_shared_manifest_vek(ctx: &Ctx, record: &SharedManifestDto) -> SyncResult<Option<String>> {+pub(crate) async fn open_shared_manifest_vek(ctx: &Ctx, record: &SharedManifestDto) -> SyncResult<Option<SecretString>> {if record.algorithm != ALGORITHM_RSA_OAEP_SHA256 {ctx.warn(format!("[Sharing] Manifest {} grants its key under an unsupported algorithm \"{}\" (newer server?); leaving it closed.", record.manifest_id, record.algorithm)).await;return Ok(None);@@ -227,7 +232,7 @@ pub(crate) async fn open_shared_manifest_vek(ctx: &Ctx, record: &SharedManifestDctx.warn(format!("[Sharing] This session holds no account private key that opens the grant on manifest {}; leaving it closed.", record.manifest_id)).await;return Ok(None);};- match decrypt_manifest_vek(&record.encrypted_vek, &record.manifest_id, &private_key) {+ match decrypt_manifest_vek(&record.encrypted_vek, &record.manifest_id, private_key.expose_secret()) {Ok(vek) => Ok(Some(vek)),Err(error) => {ctx.warn(format!("[Sharing] Failed to unwrap the key of manifest {}; leaving it closed. {}", record.manifest_id, error)).await;@@ -237,7 +242,7 @@ pub(crate) async fn open_shared_manifest_vek(ctx: &Ctx, record: &SharedManifestD}/// The VEK of every shared manifest this account holds a grant on, keyed by manifest id. Unwrapped once per run.-pub(crate) async fn open_shared_manifest_veks(ctx: &Ctx) -> SyncResult<HashMap<String, String>> {+pub(crate) async fn open_shared_manifest_veks(ctx: &Ctx) -> SyncResult<HashMap<String, SecretString>> {if let Some(cached) = ctx.cached_shared_veks() {return Ok(cached);}diff --git a/core/rust/src/vault_sync/merge.rs b/core/rust/src/vault_sync/merge.rsindex 102ecf45d..c9d248fbd 100644--- a/core/rust/src/vault_sync/merge.rs+++ b/core/rust/src/vault_sync/merge.rs@@ -2,6 +2,7 @@//! manifest at a time, and materializes the result.use std::collections::{HashMap, HashSet};+use secrecy::ExposeSecret;use crate::vault_model::{id_key, ids_equal};use super::errors::SyncResult;@@ -38,7 +39,7 @@ pub(crate) async fn pull_and_merge(ctx: &mut Ctx) -> SyncResult<PullAndMergeOutcSnapshot::Manifest(snapshot) => snapshot,};- let opened = pull::open_manifests_and_record_sync_state(ctx, &snapshot, &vek).await?;+ let opened = pull::open_manifests_and_record_sync_state(ctx, &snapshot, vek.expose_secret()).await?;let local_side = canonicalize_vault(ctx, None).await?;let local_side = match ground_moved_under_canonicalize(&local_side.manifest_records, &opened) {None => local_side,@@ -48,13 +49,13 @@ pub(crate) async fn pull_and_merge(ctx: &mut Ctx) -> SyncResult<PullAndMergeOutc}};- match merge_onto_opened_manifests(ctx, &opened, local_side, &vek).await {+ match merge_onto_opened_manifests(ctx, &opened, local_side, vek.expose_secret()).await {Ok(outcome) => Ok(outcome),Err(merge_error) => {// The merge-failure fallback, from the same snapshot: the server vault stands, local changes are dropped.ctx.warn(format!("[Merge] Canonical merge failed, falling back to the server vault: {}", merge_error)).await;let sqlite_bytes = pull::materialize_to_sqlite(ctx, &opened.manifests(), &opened.data_buckets, &opened.blob_map, &opened.manifest_names).await?;- Ok(PullAndMergeOutcome::ServerOnly(opened.pulled_vault(state::encrypt_vault_blob(&sqlite_bytes, &vek)?)))+ Ok(PullAndMergeOutcome::ServerOnly(opened.pulled_vault(state::encrypt_vault_blob(&sqlite_bytes, vek.expose_secret())?)))}}}diff --git a/core/rust/src/vault_sync/migration.rs b/core/rust/src/vault_sync/migration.rsindex ef6acbf1b..b8d8b724a 100644--- a/core/rust/src/vault_sync/migration.rs+++ b/core/rust/src/vault_sync/migration.rs@@ -2,6 +2,7 @@//! operations the upgrade gate drives (`migrationStatus`, `migrateManifest`).use std::collections::HashMap;+use secrecy::ExposeSecret;use super::db::{self, SchemaState};use super::errors::{Failure, SyncError, SyncResult};@@ -126,7 +127,7 @@ pub(crate) async fn rebuild_local_schema(ctx: &mut Ctx, stamp_unstamped_into: Oplet bytes = pull::materialize_to_sqlite(ctx, &manifests, &set.canonicalized.data_buckets, &blob_map, &HashMap::new()).await?;ctx.log(format!("[Migration] Migration complete: {} blobs re-embedded, {} bytes.", blob_map.len(), bytes.len())).await;- let stored = ctx.store_vault(&state::encrypt_vault_blob(&bytes, &ctx.encryption_key()?)?, true, None, None).await?;+ let stored = ctx.store_vault(&state::encrypt_vault_blob(&bytes, (ctx.encryption_key()?).expose_secret())?, true, None, None).await?;ctx.mutation_sequence = stored.mutation_sequence;ctx.is_dirty = true;ctx.vault_changed = true;diff --git a/core/rust/src/vault_sync/pull.rs b/core/rust/src/vault_sync/pull.rsindex 34e995dc4..a53214cb6 100644--- a/core/rust/src/vault_sync/pull.rs+++ b/core/rust/src/vault_sync/pull.rs@@ -2,6 +2,7 @@//! referenced blobs and materialize the whole into a fresh SQLite database.use std::collections::HashMap;+use secrecy::{ExposeSecret, SecretString};use crate::vault_model::{id_key, ids_equal};use super::errors::{SyncError, SyncResult};@@ -20,7 +21,7 @@ pub(crate) struct ResolvedManifest {pub manifest_id: String,pub is_personal: bool,pub manifest: Manifest,- pub vek: String,+ pub vek: SecretString,pub revision: i64,pub blob_references: Vec<StoredBlobRef>,pub content_fingerprint: String,@@ -131,10 +132,10 @@ pub(crate) async fn pull(ctx: &mut Ctx) -> SyncResult<PulledVault> {};ctx.log("[Pull] Decrypting the manifests and reassembling the local SQLite...").await;- let opened = open_manifests_and_record_sync_state(ctx, &snapshot, &vek).await?;+ let opened = open_manifests_and_record_sync_state(ctx, &snapshot, vek.expose_secret()).await?;let sqlite_bytes = materialize_to_sqlite(ctx, &opened.manifests(), &opened.data_buckets, &opened.blob_map, &opened.manifest_names).await?;ctx.log(format!("[Pull] Materialized SQLite ({} bytes); re-encrypting for local storage...", sqlite_bytes.len())).await;- Ok(opened.pulled_vault(state::encrypt_vault_blob(&sqlite_bytes, &vek)?))+ Ok(opened.pulled_vault(state::encrypt_vault_blob(&sqlite_bytes, vek.expose_secret())?))}/// Open every manifest a snapshot carries, personal first, and record the snapshot as this device's sync state.@@ -161,9 +162,9 @@ pub(crate) async fn open_manifests_and_record_sync_state(ctx: &mut Ctx, snapshotif is_personal {let entry = if personal_needs_first_write {ctx.log("[Pull] Personal manifest has no content yet (new account); starting from an empty vault.").await;- empty_personal_manifest(ctx, dto, &manifest_key).await?+ empty_personal_manifest(ctx, dto, manifest_key.expose_secret()).await?} else {- open_logged_manifest(ctx, dto, &manifest_key, true).await?+ open_logged_manifest(ctx, dto, manifest_key.expose_secret(), true).await?};state::set(&ctx.host, state::VAULT_MANIFEST_SALT, &entry.manifest.manifest_salt).await?;state::set(&ctx.host, state::VAULT_PERSONAL_MANIFEST_ID, &entry.manifest_id).await?;@@ -179,11 +180,11 @@ pub(crate) async fn open_manifests_and_record_sync_state(ctx: &mut Ctx, snapshotcontinue;}- let entry = open_logged_manifest(ctx, dto, &manifest_key, false).await?;+ let entry = open_logged_manifest(ctx, dto, manifest_key.expose_secret(), false).await?;let (encrypted_vek, account_public_key, algorithm) = grant_of(dto).ok_or_else(|| SyncError::Snapshot(format!("shared manifest {} carries no grant this account can re-open, refusing to assemble", entry.manifest_id)))?;let encrypted_name = served_encrypted_name(ctx, &previous_records, &entry.manifest_id);if let Some(ciphertext) = &encrypted_name {- match open_manifest_name(ciphertext, &entry.manifest_id, &manifest_key) {+ match open_manifest_name(ciphertext, &entry.manifest_id, manifest_key.expose_secret()) {Some(name) => drop(manifest_names.insert(id_key(&entry.manifest_id), name)),None => ctx.warn(format!("[Pull] The name of shared manifest {} did not open with its key; leaving it unnamed.", entry.manifest_id)).await,}@@ -260,7 +261,7 @@ pub(crate) async fn commit_revisions(ctx: &Ctx, pulled: &PulledVault) -> SyncRes/// Open every data bucket a snapshot carries, record the snapshot's bucket revisions.async fn open_data_buckets(ctx: &Ctx, snapshot: &GetResponse, resolved: &[ResolvedManifest]) -> SyncResult<(Vec<DataBucket>, HashMap<String, String>, HashMap<String, i64>)> {- let key_by_manifest: HashMap<&str, &str> = resolved.iter().map(|m| (m.manifest_id.as_str(), m.vek.as_str())).collect();+ let key_by_manifest: HashMap<&str, &str> = resolved.iter().map(|m| (m.manifest_id.as_str(), m.vek.expose_secret())).collect();let mut buckets = Vec::new();let mut fingerprints = HashMap::new();let mut revisions = HashMap::new();@@ -330,7 +331,7 @@ async fn download_referenced_blobs(ctx: &Ctx, resolved: &[ResolvedManifest]) ->continue;};let owner = owners[&reference.hash];- match blob_keys::decrypt_blob(encrypted, &owner.vek, &owner.manifest_id, &reference.hash) {+ match blob_keys::decrypt_blob(encrypted, owner.vek.expose_secret(), &owner.manifest_id, &reference.hash) {Ok(bytes) => {blob_map.insert(reference.hash.clone(), bytes);pruned_cache.insert(reference.hash.clone(), encrypted.clone());@@ -379,7 +380,7 @@ fn open_manifest(dto: &ManifestDto, vek: &str, is_personal: bool) -> SyncResult<manifest_id: dto.manifest_id.clone(),is_personal,manifest,- vek: vek.to_string(),+ vek: SecretString::from(vek),revision: dto.revision,blob_references: dto.blob_references.clone(),content_fingerprint: vault_codec::compute_content_fingerprint(&manifest_json),@@ -394,11 +395,11 @@ async fn empty_personal_manifest(ctx: &Ctx, dto: &ManifestDto, vek: &str) -> Synlet spec = ManifestSpec { manifest_id: dto.manifest_id.clone(), manifest_salt, name: None };let canonicalized = vault_codec::canonicalize_from_sqlite(CanonicalizeInput { tables, canonicalized_at: crate::common::timestamp::now_iso_utc(), manifests: vec![spec], stamp_unstamped_into: None })?;let manifest = canonicalized.manifests.into_iter().next().map(|m| m.manifest).ok_or_else(|| SyncError::Other("canonicalize returned no manifest for the empty vault".to_string()))?;- Ok(ResolvedManifest { manifest_id: dto.manifest_id.clone(), is_personal: true, manifest, vek: vek.to_string(), revision: dto.revision, blob_references: Vec::new(), content_fingerprint: String::new() })+ Ok(ResolvedManifest { manifest_id: dto.manifest_id.clone(), is_personal: true, manifest, vek: SecretString::from(vek), revision: dto.revision, blob_references: Vec::new(), content_fingerprint: String::new() })}/// The key that opens one snapshot manifest.-async fn resolve_manifest_vek(ctx: &Ctx, dto: &ManifestDto, personal_manifest_id: &str, personal_vek: &str, is_personal: bool) -> SyncResult<String> {+async fn resolve_manifest_vek(ctx: &Ctx, dto: &ManifestDto, personal_manifest_id: &str, personal_vek: &str, is_personal: bool) -> SyncResult<SecretString> {// Only a personal manifest that predates the account key hierarchy has no key type; a shared one always states it.let key_type = match dto.key_type.clone() {Some(key_type) => key_type,@@ -409,7 +410,7 @@ async fn resolve_manifest_vek(ctx: &Ctx, dto: &ManifestDto, personal_manifest_idif dto.manifest_id != personal_manifest_id {return Err(SyncError::Snapshot(format!("manifest {} is unlocked by the account key hierarchy, but this session holds no key for it, refusing to assemble", dto.manifest_id)));}- return Ok(personal_vek.to_string());+ return Ok(SecretString::from(personal_vek));}if key_type != types::KEY_TYPE_GRANT_KEY {return Err(SyncError::VaultVersionIncompatible(format!("manifest {} states an unknown key type \"{}\"; update the app", dto.manifest_id, key_type)));@@ -417,7 +418,7 @@ async fn resolve_manifest_vek(ctx: &Ctx, dto: &ManifestDto, personal_manifest_idresolve_granted_vek(ctx, dto).await}-async fn resolve_granted_vek(ctx: &Ctx, dto: &ManifestDto) -> SyncResult<String> {+async fn resolve_granted_vek(ctx: &Ctx, dto: &ManifestDto) -> SyncResult<SecretString> {let (encrypted_vek, public_key, algorithm) = grant_of(dto).ok_or_else(|| SyncError::Snapshot(format!("shared manifest {} carries no grant to open it with, refusing to assemble", dto.manifest_id)))?;if algorithm != types::ALGORITHM_RSA_OAEP_SHA256 {return Err(SyncError::VaultVersionIncompatible(format!("shared manifest {} grants its VEK under an unsupported algorithm \"{}\"; update the app", dto.manifest_id, algorithm)));@@ -428,5 +429,5 @@ async fn resolve_granted_vek(ctx: &Ctx, dto: &ManifestDto) -> SyncResult<String>}// Sanity check: no key this session holds opens the grant, so the session is behind the server.let private_key = keys::resolve_grant_private_key(ctx, &public_key).ok_or(SyncError::KeyOutOfSync)?;- keys::decrypt_manifest_vek(&encrypted_vek, &dto.manifest_id, &private_key).map_err(|e| SyncError::ServerVaultUnreadable(format!("failed to decrypt the VEK of shared manifest {}, refusing to assemble: {}", dto.manifest_id, e)))+ keys::decrypt_manifest_vek(&encrypted_vek, &dto.manifest_id, private_key.expose_secret()).map_err(|e| SyncError::ServerVaultUnreadable(format!("failed to decrypt the VEK of shared manifest {}, refusing to assemble: {}", dto.manifest_id, e)))}diff --git a/core/rust/src/vault_sync/push.rs b/core/rust/src/vault_sync/push.rsindex 642942634..4da34630b 100644--- a/core/rust/src/vault_sync/push.rs+++ b/core/rust/src/vault_sync/push.rs@@ -14,6 +14,7 @@ use super::types::{BlobDto, BlobHashesRequest, BlobRef, BlobUploadRequest, Buckeuse super::blob_keys::{self, EncryptedBlob};use super::write_set::{self, ManifestRecord, SkipReason};use super::{db, http, keys};+use secrecy::{ExposeSecret, SecretString};use crate::crypto;use crate::vault_codec::{self, BlobEntry, CanonicalizeInput, CanonicalizedVault, DataBucket, Manifest, ManifestSpec};@@ -110,7 +111,7 @@ pub(crate) async fn resolve_personal_manifest_id(ctx: &Ctx) -> SyncResult<String}/// The key each writable manifest encrypts with, the personal one under the session key.-async fn resolve_write_keys(ctx: &Ctx) -> SyncResult<HashMap<String, String>> {+async fn resolve_write_keys(ctx: &Ctx) -> SyncResult<HashMap<String, SecretString>> {let mut keys_by_manifest = keys::open_shared_manifest_veks(ctx).await?;keys_by_manifest.insert(resolve_personal_manifest_id(ctx).await?, ctx.encryption_key()?);Ok(keys_by_manifest)@@ -261,12 +262,12 @@ async fn write_whole_vault(ctx: &mut Ctx, cached: Option<CanonicalizedSet>, kindlet (status, new_key) = http::with_outdated_server_guard(write_manifests_and_buckets(ctx, cached, kind).await)?;if let Some(new_key) = new_key {// Migration succeeded: from now on the session key is the VEK, not the password-derived key.- keys::re_encrypt_shared_manifest_records(ctx, &new_key).await?;+ keys::re_encrypt_shared_manifest_records(ctx, new_key.expose_secret()).await?;ctx.set_encryption_key(new_key);}// Store the vault again only when it changed or its key did.- if vault_rewritten || ctx.encryption_key()? != key_before {+ if vault_rewritten || ctx.encryption_key()?.expose_secret() != key_before.expose_secret() {ctx.persist_local_vault(false).await?;}Ok((status, vault_rewritten))@@ -317,7 +318,7 @@ impl PushBaselines {struct Candidate<'a> {record: &'a ManifestRecord,manifest: &'a Manifest,- vek: String,+ vek: SecretString,blobs: &'a HashMap<String, BlobEntry>,current_revision: i64,}@@ -337,7 +338,7 @@ struct UploadBlobEntry {manifest_id: String,bytes: Vec<u8>,kind: String,- vek: String,+ vek: SecretString,from_personal: bool,}@@ -369,7 +370,7 @@ impl UploadBlobs {/// The freshly generated key hierarchy for one migration push.#[derive(zeroize::Zeroize, zeroize::ZeroizeOnDrop)]struct LegacyAccountKeyMigration {- content_key: String,+ content_key: SecretString,/// Ciphertext only, so there is nothing here to wipe.#[zeroize(skip)]@@ -414,7 +415,7 @@ async fn encrypt_payload(ctx: &Ctx, label: &str, plaintext: &str, key: &str, aad/// Canonicalize, gate by content fingerprint, encrypt and `POST v2/Vault`. Returns the outcome and, on a/// migration push, the new content key the session switches to.-async fn write_manifests_and_buckets(ctx: &mut Ctx, cached: Option<CanonicalizedSet>, kind: WriteKind) -> SyncResult<(PushStatus, Option<String>)> {+async fn write_manifests_and_buckets(ctx: &mut Ctx, cached: Option<CanonicalizedSet>, kind: WriteKind) -> SyncResult<(PushStatus, Option<SecretString>)> {let vek = ctx.encryption_key()?;let unwritable = find_unwritable_manifests(ctx).await?;@@ -423,7 +424,7 @@ async fn write_manifests_and_buckets(ctx: &mut Ctx, cached: Option<Canonicalizedreturn Ok((PushStatus::Outdated, None));}- let migration = start_account_key_migration(ctx, &vek, kind).await?;+ let migration = start_account_key_migration(ctx, vek.expose_secret(), kind).await?;let content_key = migration.as_ref().map(|m| m.content_key.clone()).unwrap_or_else(|| vek.clone());let set = match cached {@@ -442,15 +443,15 @@ async fn write_manifests_and_buckets(ctx: &mut Ctx, cached: Option<Canonicalizedif migration.is_some() {refuse_overwrite_without_bytes(&candidates, &blobs)?;}- let keys_by_manifest: HashMap<String, String> = candidates.iter().map(|c| (c.record.manifest_id.clone(), c.vek.clone())).collect();+ let keys_by_manifest: HashMap<String, SecretString> = candidates.iter().map(|c| (c.record.manifest_id.clone(), c.vek.clone())).collect();let mut written = WrittenFingerprints::default();let bucket_writes = encrypt_changed_buckets(ctx, &canonicalized.data_buckets, &keys_by_manifest, &baselines, kind, &mut written).await?;// An upgrade push signs with the signing key it creates, which the server stores in the same write.let signing_key = match &migration {- Some(migration) => Some(migration.signing_private_key.clone()),+ Some(migration) => Some(SecretString::from(migration.signing_private_key.as_str())),None => keys::signing_private_key(ctx).await?,};- let manifest_writes = encrypt_changed_manifests(ctx, &candidates, &baselines, kind, signing_key.as_deref(), &mut written).await?;+ let manifest_writes = encrypt_changed_manifests(ctx, &candidates, &baselines, kind, signing_key.as_ref().map(|key| key.expose_secret()), &mut written).await?;if manifest_writes.is_empty() && bucket_writes.is_empty() {ctx.log("[Push] No content changes detected (every manifest and data bucket matches the server baselines); skipping upload.").await;@@ -487,7 +488,7 @@ async fn start_account_key_migration(ctx: &Ctx, unlock_key: &str, kind: WriteKinlet hierarchy = crypto::create_account_key_hierarchy(unlock_key)?;ctx.log("[Push] Account-key migration: generated new VEK, AK, account keypair and signing keypair; vault content and all blobs will be re-encrypted and re-uploaded.").await;Ok(Some(LegacyAccountKeyMigration {- content_key: hierarchy.vault_encryption_key.clone(),+ content_key: SecretString::from(hierarchy.vault_encryption_key.as_str()),account_keys: hierarchy.account_keys.clone(),account_private_key: hierarchy.account_private_key.clone(),signing_private_key: hierarchy.signing_private_key.clone(),@@ -495,14 +496,14 @@ async fn start_account_key_migration(ctx: &Ctx, unlock_key: &str, kind: WriteKin}/// Every canonicalized manifest a record exists for, with the key it encrypts under.-fn collect_candidates<'a>(canonicalized: &'a CanonicalizedVault, records: &'a [ManifestRecord], content_key: &str, baselines: &PushBaselines) -> Vec<Candidate<'a>> {+fn collect_candidates<'a>(canonicalized: &'a CanonicalizedVault, records: &'a [ManifestRecord], content_key: &SecretString, baselines: &PushBaselines) -> Vec<Candidate<'a>> {let record_by_id: HashMap<&str, &ManifestRecord> = records.iter().map(|r| (r.manifest_id.as_str(), r)).collect();canonicalized.manifests.iter().filter_map(|entry| {let record = record_by_id.get(entry.manifest.manifest_id.as_str())?;- Some(Candidate { record, manifest: &entry.manifest, vek: record.vek.clone().unwrap_or_else(|| content_key.to_string()), blobs: &entry.blobs, current_revision: baselines.manifest_revisions.get(&record.manifest_id).copied().unwrap_or(0) })+ Some(Candidate { record, manifest: &entry.manifest, vek: record.vek.clone().unwrap_or_else(|| content_key.clone()), blobs: &entry.blobs, current_revision: baselines.manifest_revisions.get(&record.manifest_id).copied().unwrap_or(0) })}).collect()}@@ -533,7 +534,7 @@ fn refuse_overwrite_without_bytes(candidates: &[Candidate], blobs: &UploadBlobs)}/// Gate, validate, pack and encrypt each changed bucket under the key of the manifest that owns it.-async fn encrypt_changed_buckets(ctx: &Ctx, buckets: &[DataBucket], keys_by_manifest: &HashMap<String, String>, baselines: &PushBaselines, kind: WriteKind, written: &mut WrittenFingerprints) -> SyncResult<Vec<BucketWrite>> {+async fn encrypt_changed_buckets(ctx: &Ctx, buckets: &[DataBucket], keys_by_manifest: &HashMap<String, SecretString>, baselines: &PushBaselines, kind: WriteKind, written: &mut WrittenFingerprints) -> SyncResult<Vec<BucketWrite>> {let mut writes = Vec::new();for bucket in buckets {let label = format!("Data bucket \"{}\" of manifest {}", bucket.category, bucket.manifest_id);@@ -551,7 +552,7 @@ async fn encrypt_changed_buckets(ctx: &Ctx, buckets: &[DataBucket], keys_by_maniif !validation.ok {return Err(SyncError::UploadRejected(vec![format!("{} validation failed: {}. {}", label, validation.failed_rules.join(", "), validation.message).trim().to_string()]));}- let encrypted = encrypt_payload(ctx, &label, &plaintext, bucket_key, &crypto::aad::bucket(&bucket.manifest_id, &bucket.category)).await?;+ let encrypted = encrypt_payload(ctx, &label, &plaintext, bucket_key.expose_secret(), &crypto::aad::bucket(&bucket.manifest_id, &bucket.category)).await?;writes.push(BucketWrite { manifest_id: bucket.manifest_id.clone(), category: bucket.category.clone(), ciphertext: encrypted.ciphertext.into(), ciphertext_hash: encrypted.hash, current_revision: baselines.bucket_revision(bucket) });written.insert(fingerprint_key, fingerprint);}@@ -577,7 +578,7 @@ async fn encrypt_changed_manifests(ctx: &Ctx, candidates: &[Candidate<'_>], basectx.warn(format!("[Push] {} failed validation ({}), dropping it from this write.", label, validation.failed_rules.join(", "))).await;continue;}- let encrypted = encrypt_payload(ctx, &label, &plaintext, &candidate.vek, &crypto::aad::manifest(&candidate.record.manifest_id)).await?;+ let encrypted = encrypt_payload(ctx, &label, &plaintext, candidate.vek.expose_secret(), &crypto::aad::manifest(&candidate.record.manifest_id)).await?;// Publish the public half of this manifest's mail delivery keypair; only admins may publish a shared one.let may_publish = candidate.record.is_personal || candidate.record.can_administer;@@ -709,8 +710,8 @@ async fn complete_account_key_migration(ctx: &mut Ctx, migration: &LegacyAccountstate::set(&ctx.host, state::SIGNING_PUBLIC_KEY, &blobs.signing_public_key).await?;state::set(&ctx.host, state::ENCRYPTED_SIGNING_PRIVATE_KEY, &blobs.encrypted_signing_private_key).await?;ctx.account_public_key = Some(blobs.account_public_key.clone());- ctx.account_private_key = Some(migration.account_private_key.clone());- ctx.signing_private_key = Some(migration.signing_private_key.clone());+ ctx.account_private_key = Some(migration.account_private_key.as_str().into());+ ctx.signing_private_key = Some(migration.signing_private_key.as_str().into());Ok(())}@@ -722,7 +723,7 @@ async fn upload_blobs(ctx: &Ctx, blobs: &UploadBlobs, hashes: &[String], overwrilet mut dtos = Vec::new();for hash in hashes {let entry = &blobs.entries[&hash];- let encrypted = blob_keys::encrypt_blob(&entry.bytes, &entry.vek, &manifest_id, &hash)?;+ let encrypted = blob_keys::encrypt_blob(&entry.bytes, entry.vek.expose_secret(), &manifest_id, &hash)?;encrypted_blobs.insert(hash.clone(), encrypted.clone());dtos.push(BlobDto { hash, category: entry.kind.clone(), ciphertext: encrypted.encrypted_data.into(), encrypted_blob_key: encrypted.encrypted_blob_key });}diff --git a/core/rust/src/vault_sync/sharing.rs b/core/rust/src/vault_sync/sharing.rsindex 81951a59c..d23dc93ee 100644--- a/core/rust/src/vault_sync/sharing.rs+++ b/core/rust/src/vault_sync/sharing.rs@@ -1,6 +1,7 @@//! The sharing operations that take vault keys: creating a group's shared manifest, updating one and inviting a member to one.use std::collections::HashMap;+use secrecy::ExposeSecret;use serde::{Deserialize, Serialize};@@ -216,7 +217,7 @@ async fn create_shared_manifest(ctx: &mut Ctx) -> Outcome {let requested_id = db::new_id();let self_encrypted_vek = keys::encrypt_manifest_vek(&manifest_vek, &requested_id, &self_public_key)?;// A new manifest starts at key version 0.- let self_grant_signature = crypto::signing::sign(&signing_key, &crypto::signing::grant_message(&requested_id, 0, &own_user_id(ctx, &group)?, &self_public_key, ALGORITHM_RSA_OAEP_SHA256, &self_encrypted_vek))?;+ let self_grant_signature = crypto::signing::sign(signing_key.expose_secret(), &crypto::signing::grant_message(&requested_id, 0, &own_user_id(ctx, &group)?, &self_public_key, ALGORITHM_RSA_OAEP_SHA256, &self_encrypted_vek))?;let encrypted_name = pull::encrypt_manifest_name(&name, &requested_id, &manifest_vek)?;let response: CreateSharedManifestResponse = http::post(&ctx.host,@@ -243,7 +244,7 @@ async fn create_shared_manifest(ctx: &mut Ctx) -> Outcome {can_administer: true,},);- keys::set_shared_manifest_records(ctx, &records, &key).await?;+ keys::set_shared_manifest_records(ctx, &records, key.expose_secret()).await?;let mut revisions: HashMap<String, i64> = state::get(&ctx.host, state::SERVER_MANIFEST_REVISIONS).await?.unwrap_or_default();revisions.insert(manifest_id.clone(), response.revision_number);@@ -274,14 +275,14 @@ async fn update_shared_manifest(ctx: &mut Ctx) -> Outcome {let manifest_vek = keys::open_shared_manifest_vek(ctx, &record).await?.ok_or_else(|| SyncError::Other("The key of the shared manifest did not open".to_string()))?;// The server decides who may change a shared manifest; it only ever sees the name encrypted.- let encrypted_name = pull::encrypt_manifest_name(&name, &record.manifest_id, &manifest_vek)?;+ let encrypted_name = pull::encrypt_manifest_name(&name, &record.manifest_id, manifest_vek.expose_secret())?;http::post_no_content(&ctx.host, &format!("Groups/{}/manifests/{}", target.group_id, record.manifest_id), &UpdateSharedManifestRequest { encrypted_name: Some(&encrypted_name) }).await?;let mut records = keys::shared_manifest_records(ctx).await?;if let Some(held) = records.get_mut(&record.manifest_id) {held.encrypted_name = Some(encrypted_name);}- keys::set_shared_manifest_records(ctx, &records, &key).await?;+ keys::set_shared_manifest_records(ctx, &records, key.expose_secret()).await?;// Show the new name right away; every other member fetches it on their next sync.if ctx.has_local_vault().await? {@@ -326,13 +327,13 @@ async fn invite_to_shared_manifest(ctx: &mut Ctx) -> Outcome {// The name travels encrypted in the invitation, so the recipient sees what they are invited to; one too long to fit is left out.let name = db::manifest_display_names(&ctx.host).await?.get(&id_key(&manifest.manifest_id)).cloned().filter(|name| !name.is_empty() && name.len() <= MAX_SHARED_MANIFEST_NAME_BYTES);let own_user_id = own_user_id(ctx, &group)?;- let encrypted_vek = keys::encrypt_manifest_vek(&manifest_vek, &manifest.manifest_id, &recipient_public_key)?;+ let encrypted_vek = keys::encrypt_manifest_vek(manifest_vek.expose_secret(), &manifest.manifest_id, &recipient_public_key)?;let encrypted_name = name.map(|name| crypto::encrypt_with_public_key(name.as_bytes(), &recipient_public_key)).transpose()?;let grant = ManifestGrant {recipient_user_id: member.user_id.clone(),recipient_account_public_key_id: recipient_public_key_id,- signature: crypto::signing::sign(&signing_key, &crypto::signing::grant_message(&manifest.manifest_id, manifest.key_version, &own_user_id, &recipient_public_key, ALGORITHM_RSA_OAEP_SHA256, &encrypted_vek))?,- encrypted_name_signature: encrypted_name.as_deref().map(|name| crypto::signing::sign(&signing_key, &crypto::signing::invitation_name_message(&manifest.manifest_id, &own_user_id, &recipient_public_key, name))).transpose()?,+ signature: crypto::signing::sign(signing_key.expose_secret(), &crypto::signing::grant_message(&manifest.manifest_id, manifest.key_version, &own_user_id, &recipient_public_key, ALGORITHM_RSA_OAEP_SHA256, &encrypted_vek))?,+ encrypted_name_signature: encrypted_name.as_deref().map(|name| crypto::signing::sign(signing_key.expose_secret(), &crypto::signing::invitation_name_message(&manifest.manifest_id, &own_user_id, &recipient_public_key, name))).transpose()?,encrypted_vek,encrypted_name,};diff --git a/core/rust/src/vault_sync/state.rs b/core/rust/src/vault_sync/state.rsindex 67ca37d7b..fe68f2418 100644--- a/core/rust/src/vault_sync/state.rs+++ b/core/rust/src/vault_sync/state.rs@@ -11,21 +11,22 @@ use super::db;use super::errors::{SyncError, SyncResult};use super::session::Host;use super::types::{Ack, CleanOutcome, Command, Db, LogLevel, StateValue, StoreOutcome, StoredVault, SyncRequest};+use secrecy::{ExposeSecret, SecretString};use crate::crypto;/// The mutable state of one engine run.pub(crate) struct Ctx {pub host: Host,pub request: SyncRequest,- pub encryption_key: Option<String>,+ pub encryption_key: Option<SecretString>,pub account_public_key: Option<String>,- pub account_private_key: Option<String>,- pub account_key: Option<String>,- pub signing_private_key: Option<String>,+ pub account_private_key: Option<SecretString>,+ pub account_key: Option<SecretString>,+ pub signing_private_key: Option<SecretString>,pub is_dirty: bool,pub mutation_sequence: u64,/// The session key this run switched to; the next vault store hands it to the host.- pub new_encryption_key: Option<String>,+ pub new_encryption_key: Option<SecretString>,pub vault_changed: bool,pub schema: Option<SchemaInfo>,pub vault_key_probed: bool,@@ -34,7 +35,7 @@ pub(crate) struct Ctx {/// The stored vault did not decrypt with the session key, so this run treats it as absent until a store replaces it.local_vault_discarded: bool,/// The VEK of every shared manifest this account holds a grant on, unwrapped once per run.- shared_veks: Mutex<Option<HashMap<String, String>>>,+ shared_veks: Mutex<Option<HashMap<String, SecretString>>>,}/// What a fresh staging database tells about the current client schema.@@ -85,12 +86,12 @@ impl Ctx {}/// The session's vault encryption key, or the locked-vault error.- pub fn encryption_key(&self) -> SyncResult<String> {+ pub fn encryption_key(&self) -> SyncResult<SecretString> {self.encryption_key.clone().ok_or(SyncError::VaultLocked)}/// Set a new session encryption key; the next vault store hands it to the host.- pub fn set_encryption_key(&mut self, key: String) {+ pub fn set_encryption_key(&mut self, key: SecretString) {self.new_encryption_key = Some(key.clone());self.encryption_key = Some(key);}@@ -122,7 +123,7 @@ impl Ctx {pub async fn persist_local_vault(&mut self, dirty: bool) -> SyncResult<()> {let key = self.encryption_key()?;let bytes = db::export(&self.host, Db::Local).await?;- let stored = self.store_vault(&encrypt_vault_blob(&bytes, &key)?, dirty, None, None).await?;+ let stored = self.store_vault(&encrypt_vault_blob(&bytes, key.expose_secret())?, dirty, None, None).await?;if dirty {self.is_dirty = true;self.mutation_sequence = stored.mutation_sequence;@@ -143,12 +144,12 @@ impl Ctx {}/// The shared-manifest keys unwrapped earlier in this run, if any.- pub fn cached_shared_veks(&self) -> Option<HashMap<String, String>> {+ pub fn cached_shared_veks(&self) -> Option<HashMap<String, SecretString>> {self.shared_veks.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()}/// Remember the unwrapped shared-manifest keys; `None` forgets them (the records changed).- pub fn cache_shared_veks(&self, veks: Option<HashMap<String, String>>) {+ pub fn cache_shared_veks(&self, veks: Option<HashMap<String, SecretString>>) {*self.shared_veks.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = veks;}@@ -222,7 +223,7 @@ pub(crate) async fn load_vault(host: &Host) -> SyncResult<Option<String>> {}/// Persist the at-rest vault blob, telling the host the (new) key it is encrypted under.-pub(crate) async fn store_vault_with_key(host: &Host, encrypted_blob: &str, mark_dirty: bool, expected_mutation_seq: Option<u64>, revision: Option<i64>, encryption_key: Option<String>) -> SyncResult<StoreOutcome> {+pub(crate) async fn store_vault_with_key(host: &Host, encrypted_blob: &str, mark_dirty: bool, expected_mutation_seq: Option<u64>, revision: Option<i64>, encryption_key: Option<SecretString>) -> SyncResult<StoreOutcome> {host.call(Command::VaultStore { encrypted_blob: encrypted_blob.to_string(), mark_dirty, encryption_key, expected_mutation_seq, revision }).await}diff --git a/core/rust/src/vault_sync/tests/keys.rs b/core/rust/src/vault_sync/tests/keys.rsindex d0fde903b..ad0f04c30 100644--- a/core/rust/src/vault_sync/tests/keys.rs+++ b/core/rust/src/vault_sync/tests/keys.rs@@ -8,6 +8,7 @@ use super::{insert_item, legacy_device, server_with_item, state, ITEM_A, PERSONAuse crate::crypto;use crate::vault_codec;use crate::vault_sync::types::Command;+use secrecy::ExposeSecret;/// Login: the host hands the password-derived key to `resolveVaultKey`; the server's chain opens with it, is/// cached for offline unlock, and the VEK comes back as the key to store.@@ -118,7 +119,7 @@ fn a_hierarchy_created_on_another_device_is_accepted_on_the_next_pull() {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");- assert!(matches!(&host.store_calls[0], Command::VaultStore { encryption_key: Some(key), .. } if *key == vek));+ assert!(matches!(&host.store_calls[0], Command::VaultStore { encryption_key: Some(key), .. } if key.expose_secret() == vek));assert_eq!(host.item_names(), vec!["Server item"]);assert_eq!(host.state[state::ENCRYPTED_ACCOUNT_KEY], hierarchy.account_keys.encrypted_account_key);assert_eq!(host.state[state::ACCOUNT_PUBLIC_KEY], hierarchy.account_keys.account_public_key);diff --git a/core/rust/src/vault_sync/tests/test_host.rs b/core/rust/src/vault_sync/tests/test_host.rsindex a76b30d1f..bf358f414 100644--- a/core/rust/src/vault_sync/tests/test_host.rs+++ b/core/rust/src/vault_sync/tests/test_host.rs@@ -4,6 +4,7 @@use std::collections::HashMap;use rusqlite::{Connection, MAIN_DB};+use secrecy::ExposeSecret;use serde_json::{json, Map, Value};use super::fake_server::Server;@@ -249,7 +250,7 @@ impl TestHost {let found_the_chain = self.state.contains_key(state::ENCRYPTED_ACCOUNT_KEY) && self.state.contains_key(state::ENCRYPTED_VEK);assert!(found_the_chain, "a vault stored under a new key needs the chain that opens it cached first");self.rekeyed_stores += 1;- self.vault_key = key;+ self.vault_key = key.expose_secret().to_string();}if expected_mutation_seq.is_some() {if let Some(change) = self.edit_before_next_sync_store.take() {diff --git a/core/rust/src/vault_sync/write_set.rs b/core/rust/src/vault_sync/write_set.rsindex 5265d29d3..e6369dd36 100644--- a/core/rust/src/vault_sync/write_set.rs+++ b/core/rust/src/vault_sync/write_set.rs@@ -4,6 +4,7 @@use std::collections::HashMap;use super::types::SharedManifestDto;+use secrecy::SecretString;use crate::vault_model::{id_key, ids_equal};/// One manifest this session can write, personal manifest first in every write set.@@ -16,7 +17,7 @@ pub(crate) struct ManifestRecord {/// Whether this account may publish the manifest's email delivery key.pub can_administer: bool,/// The key this manifest encrypts with; None for the personal manifest, whose key the push supplies.- pub vek: Option<String>,+ pub vek: Option<SecretString>,}/// Why a held shared manifest is left out of a write.@@ -30,7 +31,7 @@ pub(crate) enum SkipReason {/// The manifests the next push writes, personal first, plus the held shared manifests left out and why. A shared/// manifest is written when the vault holds rows for it (`stamped`) and its key opened (`opened`, id to VEK).-pub(crate) fn resolve_write_set(personal_manifest_id: &str, personal_salt: &str, stamped: &[String], opened: &HashMap<String, String>, held: &HashMap<String, SharedManifestDto>) -> (Vec<ManifestRecord>, Vec<(String, SkipReason)>) {+pub(crate) fn resolve_write_set(personal_manifest_id: &str, personal_salt: &str, stamped: &[String], opened: &HashMap<String, SecretString>, held: &HashMap<String, SharedManifestDto>) -> (Vec<ManifestRecord>, Vec<(String, SkipReason)>) {let mut records = vec![ManifestRecord { manifest_id: personal_manifest_id.to_string(), is_personal: true, salt: personal_salt.to_string(), can_administer: false, vek: None }];let mut skipped = Vec::new();let mut held: Vec<&SharedManifestDto> = held.values().collect();@@ -54,13 +55,14 @@ pub(crate) fn unwritable_manifests(in_vault: &[String], writable: &[String]) ->#[cfg(test)]mod tests {use super::*;+ use secrecy::ExposeSecret;fn held(ids: &[&str]) -> HashMap<String, SharedManifestDto> {ids.iter().map(|id| (id.to_string(), SharedManifestDto { manifest_id: id.to_string(), encrypted_vek: String::new(), account_public_key: String::new(), algorithm: String::new(), salt: format!("salt-{}", id), encrypted_name: None, can_administer: true })).collect()}- fn opened(ids: &[&str]) -> HashMap<String, String> {- ids.iter().map(|id| (id.to_string(), format!("vek-{}", id))).collect()+ fn opened(ids: &[&str]) -> HashMap<String, SecretString> {+ ids.iter().map(|id| (id.to_string(), SecretString::from(format!("vek-{}", id)))).collect()}fn strings(ids: &[&str]) -> Vec<String> {@@ -71,7 +73,7 @@ mod tests {fn the_write_set_leads_with_the_personal_manifest_and_names_what_it_left_out() {let (records, skipped) = resolve_write_set("PERSONAL", "personal-salt", &strings(&["PERSONAL", "man-1", "MAN-3"]), &opened(&["MAN-1", "MAN-2"]), &held(&["MAN-1", "MAN-2", "MAN-3"]));- let written: Vec<(&str, bool, &str, Option<&str>)> = records.iter().map(|r| (r.manifest_id.as_str(), r.is_personal, r.salt.as_str(), r.vek.as_deref())).collect();+ let written: Vec<(&str, bool, &str, Option<&str>)> = records.iter().map(|r| (r.manifest_id.as_str(), r.is_personal, r.salt.as_str(), r.vek.as_ref().map(|vek| vek.expose_secret()))).collect();assert_eq!(written, vec![("PERSONAL", true, "personal-salt", None), ("MAN-1", false, "salt-MAN-1", Some("vek-MAN-1"))], "ids match regardless of casing and the record's own spelling comes back");assert!(!records[0].can_administer, "a personal manifest is not administered through a group");assert_eq!(skipped, vec![("MAN-2".to_string(), SkipReason::NoRowsInVault), ("MAN-3".to_string(), SkipReason::KeyDidNotOpen)]);