Skip to main content

keep_core/
backup.rs

1// SPDX-FileCopyrightText: © 2026 PrivKey LLC
2// SPDX-License-Identifier: MIT
3
4//! Portable encrypted vault backup and restore.
5
6use std::path::Path;
7
8use serde::{Deserialize, Serialize};
9use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
10
11use crate::audit::{AuditEntry, AuditLog};
12use crate::crypto::{self, Argon2Params, EncryptedData, NONCE_SIZE, SALT_SIZE};
13use crate::entropy;
14use crate::error::{KeepError, Result};
15use crate::frost::StoredShare;
16use crate::keys::{KeyRecord, KeyType};
17use crate::relay::RelayConfig;
18use crate::secret::{SecretKind, SecretRecord};
19use crate::storage::ProxyConfig;
20use crate::wallet::{KeyHealthStatus, WalletDescriptor};
21use crate::Keep;
22
23fn decode_hex_32(hex_str: &str, label: &str) -> Result<[u8; 32]> {
24    let bytes =
25        hex::decode(hex_str).map_err(|e| KeepError::Other(format!("hex decode {label}: {e}")))?;
26    <[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| {
27        KeepError::InvalidInput(format!(
28            "invalid {label} length: {} (expected 32)",
29            bytes.len()
30        ))
31    })
32}
33
34const MAGIC: &[u8; 8] = b"KEEPBACK";
35const VERSION: u16 = 1;
36const HEADER_SIZE: usize = 224;
37/// Minimum passphrase length for backup encryption.
38pub const MIN_PASSPHRASE_LEN: usize = 8;
39
40/// Maximum backup file size (64 MiB).
41pub const MAX_BACKUP_SIZE: usize = 64 * 1024 * 1024;
42
43#[derive(Serialize, Deserialize)]
44struct VaultBackup {
45    version: u16,
46    created_at: String,
47    keys: Vec<BackupKey>,
48    shares: Vec<BackupShare>,
49    wallet_descriptors: Vec<WalletDescriptor>,
50    relay_configs: Vec<RelayConfig>,
51    health_statuses: Vec<KeyHealthStatus>,
52    config: BackupConfig,
53    /// Decrypted audit entries from the source vault. Re-encrypted under
54    /// the restored vault's new data key on restore; the hash chain is
55    /// re-derived from a fresh root, so individual entry hashes will
56    /// differ from the source but the timeline of events is preserved.
57    #[serde(default, skip_serializing_if = "Vec::is_empty")]
58    audit_entries: Vec<AuditEntry>,
59    /// Arbitrary secrets (passwords, API tokens, notes). `#[serde(default)]` so
60    /// a backup written before this field existed restores with none.
61    #[serde(default, skip_serializing_if = "Vec::is_empty")]
62    secrets: Vec<BackupSecret>,
63}
64
65/// A key entry in a backup file.
66#[derive(Serialize, Deserialize, Clone, Zeroize, ZeroizeOnDrop)]
67pub struct BackupKey {
68    /// Hex-encoded public key.
69    pub pubkey: String,
70    /// Key type string (e.g. "Nostr", "Bitcoin").
71    pub key_type: String,
72    /// Human-readable name.
73    pub name: String,
74    /// Unix timestamp when the key was created.
75    pub created_at: i64,
76    /// Unix timestamp when the key was last used.
77    pub last_used: Option<i64>,
78    /// Number of signatures produced.
79    pub sign_count: u64,
80    /// Hex-encoded secret key bytes.
81    pub secret: String,
82}
83
84/// A FROST share entry in a backup file.
85#[derive(Serialize, Deserialize, Clone, Zeroize, ZeroizeOnDrop)]
86pub struct BackupShare {
87    /// Share identifier index.
88    pub identifier: u16,
89    /// Signing threshold.
90    pub threshold: u16,
91    /// Total number of shares.
92    pub total_shares: u16,
93    /// Hex-encoded group public key.
94    pub group_pubkey: String,
95    /// Human-readable name.
96    pub name: String,
97    /// Unix timestamp when the share was created.
98    pub created_at: i64,
99    /// Unix timestamp when the share was last used.
100    pub last_used: Option<i64>,
101    /// Number of signatures produced.
102    pub sign_count: u64,
103    /// Whether this share has been backed up.
104    #[serde(default)]
105    pub did_backup: bool,
106    /// Hex-encoded serialized key package.
107    pub key_package: String,
108    /// Hex-encoded serialized public key package.
109    pub pubkey_package: String,
110    /// FROST ciphersuite of this share.
111    ///
112    /// Defaults to `Secp256k1Tr` so backups written before this field existed
113    /// restore unchanged.
114    #[serde(default)]
115    #[zeroize(skip)]
116    pub ciphersuite: crate::frost::Ciphersuite,
117}
118
119/// Configuration stored in a backup file.
120#[derive(Serialize, Deserialize, Clone, Debug)]
121pub struct BackupConfig {
122    /// Whether the kill switch is enabled.
123    pub kill_switch: bool,
124    /// Optional proxy configuration.
125    pub proxy: Option<ProxyConfig>,
126}
127
128impl std::fmt::Debug for BackupKey {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        f.debug_struct("BackupKey")
131            .field("pubkey", &self.pubkey)
132            .field("key_type", &self.key_type)
133            .field("name", &self.name)
134            .field("secret", &"[REDACTED]")
135            .finish()
136    }
137}
138
139impl std::fmt::Debug for BackupShare {
140    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141        f.debug_struct("BackupShare")
142            .field("identifier", &self.identifier)
143            .field("group_pubkey", &self.group_pubkey)
144            .field("name", &self.name)
145            .field("key_package", &"[REDACTED]")
146            .finish_non_exhaustive()
147    }
148}
149
150/// A secret entry (password, API token, note) in a backup file. Omitting these
151/// from backups would be silent data loss, so a full-vault backup includes them.
152/// The backup file is itself passphrase-encrypted; `name` and `value` are also
153/// scrubbed from memory on drop and never printed.
154#[derive(Serialize, Deserialize, Clone, Zeroize, ZeroizeOnDrop)]
155pub struct BackupSecret {
156    /// Hex-encoded 32-byte secret id (preserved so the restored row keeps its identity).
157    #[zeroize(skip)]
158    pub id: String,
159    /// Human-readable title.
160    pub name: String,
161    /// Secret kind string (e.g. "Password", "ApiToken").
162    #[zeroize(skip)]
163    pub kind: String,
164    /// Hex-encoded plaintext secret value.
165    pub value: String,
166    /// Unix timestamp when the secret was created.
167    #[zeroize(skip)]
168    pub created_at: i64,
169    /// Unix timestamp of the last update.
170    #[zeroize(skip)]
171    pub updated_at: i64,
172    /// Present only for a threshold-sealed secret: the wrapped DEK + OPRF params.
173    /// When present, `value` is the DEK-CIPHERTEXT (hex), not plaintext, and the
174    /// value stays gated behind the OPRF quorum after restore (the OPRF root is
175    /// never in a backup). `#[serde(default)]` so older backups decode as `None`.
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub seal: Option<BackupSeal>,
178}
179
180/// Threshold seal carried in a backup: the wrapped DEK plus the OPRF params
181/// needed to re-derive the unwrapping key. Only ciphertext/params, never
182/// plaintext, so a backup never contains a threshold secret's value in the clear.
183#[derive(Serialize, Deserialize, Clone, Zeroize, ZeroizeOnDrop)]
184pub struct BackupSeal {
185    /// Hex-encoded wrapped DEK (the per-secret key encrypted under the OPRF key).
186    pub wrapped_dek: String,
187    /// OPRF domain-separation label (hex secret id).
188    #[zeroize(skip)]
189    pub oprf_id: String,
190    /// OPRF epoch (rotation counter for the derived key).
191    #[zeroize(skip)]
192    pub epoch: u32,
193}
194
195impl std::fmt::Debug for BackupSecret {
196    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197        f.debug_struct("BackupSecret")
198            .field("id", &self.id)
199            .field("kind", &self.kind)
200            .field("name", &"[REDACTED]")
201            .field("value", &"[REDACTED]")
202            .field("sealed", &self.seal.is_some())
203            .finish()
204    }
205}
206
207/// Summary information about a backup file.
208#[derive(Debug, Clone)]
209pub struct BackupInfo {
210    /// Number of keys in the backup.
211    pub key_count: usize,
212    /// Number of FROST shares in the backup.
213    pub share_count: usize,
214    /// Number of wallet descriptors in the backup.
215    pub descriptor_count: usize,
216    /// ISO-8601 timestamp when the backup was created.
217    pub created_at: String,
218    /// Size of the backup file in bytes.
219    pub file_size: usize,
220}
221
222/// Decrypted backup data with all vault contents.
223pub struct DecryptedBackup {
224    /// Standalone keys.
225    pub keys: Vec<BackupKey>,
226    /// FROST shares.
227    pub shares: Vec<BackupShare>,
228    /// Wallet descriptors.
229    pub wallet_descriptors: Vec<WalletDescriptor>,
230    /// Relay configurations.
231    pub relay_configs: Vec<RelayConfig>,
232    /// Key health statuses.
233    pub health_statuses: Vec<KeyHealthStatus>,
234    /// Backup configuration (kill switch, proxy).
235    pub config: BackupConfig,
236    /// Decrypted audit entries from the source vault.
237    pub audit_entries: Vec<AuditEntry>,
238    /// Arbitrary secrets (passwords, API tokens, notes).
239    pub secrets: Vec<BackupSecret>,
240    /// ISO-8601 timestamp when the backup was created.
241    pub created_at: String,
242}
243
244impl Drop for DecryptedBackup {
245    fn drop(&mut self) {
246        self.keys.zeroize();
247        self.shares.zeroize();
248        self.secrets.zeroize();
249    }
250}
251
252fn key_type_to_string(kt: &KeyType) -> String {
253    match kt {
254        KeyType::Nostr => "Nostr".into(),
255        KeyType::Bitcoin => "Bitcoin".into(),
256        KeyType::FrostShare => "FrostShare".into(),
257    }
258}
259
260fn string_to_key_type(s: &str) -> Result<KeyType> {
261    match s {
262        "Nostr" => Ok(KeyType::Nostr),
263        "Bitcoin" => Ok(KeyType::Bitcoin),
264        "FrostShare" => Ok(KeyType::FrostShare),
265        other => Err(KeepError::InvalidInput(format!(
266            "unknown key type: {other}"
267        ))),
268    }
269}
270
271fn secret_kind_to_string(k: SecretKind) -> String {
272    match k {
273        SecretKind::Password => "Password".into(),
274        SecretKind::ApiToken => "ApiToken".into(),
275        SecretKind::Note => "Note".into(),
276        SecretKind::Generic => "Generic".into(),
277    }
278}
279
280fn string_to_secret_kind(s: &str) -> Result<SecretKind> {
281    match s {
282        "Password" => Ok(SecretKind::Password),
283        "ApiToken" => Ok(SecretKind::ApiToken),
284        "Note" => Ok(SecretKind::Note),
285        "Generic" => Ok(SecretKind::Generic),
286        other => Err(KeepError::InvalidInput(format!(
287            "unknown secret kind: {other}"
288        ))),
289    }
290}
291
292/// Create an encrypted backup from pre-gathered data.
293#[allow(clippy::too_many_arguments)]
294pub fn create_backup_from_data(
295    keys: Vec<BackupKey>,
296    shares: Vec<BackupShare>,
297    wallet_descriptors: Vec<WalletDescriptor>,
298    relay_configs: Vec<RelayConfig>,
299    health_statuses: Vec<KeyHealthStatus>,
300    config: BackupConfig,
301    audit_entries: Vec<AuditEntry>,
302    passphrase: &str,
303) -> Result<Vec<u8>> {
304    // External callers (e.g. keep-mobile) that do not hold a secret store back up
305    // no secrets. The full-vault `create_backup` path threads them in explicitly.
306    let backup = VaultBackup {
307        version: VERSION,
308        created_at: chrono::Utc::now().to_rfc3339(),
309        keys,
310        shares,
311        wallet_descriptors,
312        relay_configs,
313        health_statuses,
314        config,
315        audit_entries,
316        secrets: Vec::new(),
317    };
318    encode_backup(&backup, passphrase)
319}
320
321/// Passphrase-check, serialize, Argon2-derive, and encrypt a [`VaultBackup`] into
322/// the on-disk backup format. Shared by [`create_backup_from_data`] and
323/// [`create_backup`] so the header/encryption layout stays in one place.
324fn encode_backup(backup: &VaultBackup, passphrase: &str) -> Result<Vec<u8>> {
325    if passphrase.chars().count() < MIN_PASSPHRASE_LEN {
326        return Err(KeepError::InvalidInput(format!(
327            "passphrase must be at least {MIN_PASSPHRASE_LEN} characters"
328        )));
329    }
330
331    let mut json_bytes = serde_json::to_vec(backup)
332        .map_err(|e| KeepError::Other(format!("backup serialization failed: {e}")))?;
333
334    let salt: [u8; SALT_SIZE] = entropy::try_random_bytes()?;
335    let params = Argon2Params::DEFAULT;
336    let key = crypto::derive_key(passphrase.as_bytes(), &salt, params)?;
337    let encrypted = crypto::encrypt(&json_bytes, &key)?;
338    json_bytes.zeroize();
339
340    let mut output = Vec::with_capacity(HEADER_SIZE + encrypted.to_bytes().len());
341
342    output.extend_from_slice(MAGIC);
343    output.extend_from_slice(&VERSION.to_le_bytes());
344    output.extend_from_slice(&0u16.to_le_bytes());
345    output.extend_from_slice(&salt);
346    output.extend_from_slice(&params.memory_kib.to_le_bytes());
347    output.extend_from_slice(&params.iterations.to_le_bytes());
348    output.extend_from_slice(&params.parallelism.to_le_bytes());
349    output.extend_from_slice(&encrypted.nonce);
350    output.extend_from_slice(&[0u8; 32]);
351    output.extend_from_slice(&[0u8; 112]);
352
353    output.extend_from_slice(&encrypted.ciphertext);
354
355    Ok(output)
356}
357
358/// Create an encrypted backup of all vault data.
359pub fn create_backup(keep: &Keep, passphrase: &str) -> Result<Vec<u8>> {
360    if !keep.is_unlocked() {
361        return Err(KeepError::Locked);
362    }
363
364    let data_key = keep.data_key()?;
365
366    let key_records = keep.list_keys()?;
367    let mut backup_keys = Vec::with_capacity(key_records.len());
368    for record in &key_records {
369        let encrypted = EncryptedData::from_bytes(&record.encrypted_secret)?;
370        let decrypted = crypto::decrypt(&encrypted, &data_key)?;
371        let secret_bytes = decrypted.as_slice()?;
372        backup_keys.push(BackupKey {
373            pubkey: hex::encode(record.pubkey),
374            key_type: key_type_to_string(&record.key_type),
375            name: record.name.clone(),
376            created_at: record.created_at,
377            last_used: record.last_used,
378            sign_count: record.sign_count,
379            secret: hex::encode(secret_bytes.as_slice()),
380        });
381    }
382
383    let stored_shares = keep.frost_list_shares()?;
384    let mut backup_shares = Vec::with_capacity(stored_shares.len());
385    for share in &stored_shares {
386        let decrypted = share.decrypt(&data_key)?;
387        backup_shares.push(BackupShare {
388            identifier: share.metadata.identifier,
389            threshold: share.metadata.threshold,
390            total_shares: share.metadata.total_shares,
391            group_pubkey: hex::encode(share.metadata.group_pubkey),
392            name: share.metadata.name.clone(),
393            created_at: share.metadata.created_at,
394            last_used: share.metadata.last_used,
395            sign_count: share.metadata.sign_count,
396            did_backup: share.metadata.did_backup,
397            key_package: hex::encode(decrypted.key_package_bytes()),
398            pubkey_package: hex::encode(&share.pubkey_package),
399            ciphersuite: share.ciphersuite,
400        });
401    }
402
403    let secret_records = keep.list_secrets()?;
404    let mut backup_secrets = Vec::with_capacity(secret_records.len());
405    for record in &secret_records {
406        // For a threshold-sealed secret `record.value` is the DEK-ciphertext (not
407        // plaintext); the seal carries the wrapped DEK + OPRF params. Backing both
408        // up preserves the quorum gate without ever holding the plaintext.
409        let seal = keep.load_secret_seal(&record.id)?.map(|s| BackupSeal {
410            wrapped_dek: hex::encode(&s.wrapped_dek),
411            oprf_id: s.oprf_id.clone(),
412            epoch: s.epoch,
413        });
414        backup_secrets.push(BackupSecret {
415            id: hex::encode(record.id),
416            name: record.name.clone(),
417            kind: secret_kind_to_string(record.kind),
418            value: hex::encode(&record.value),
419            created_at: record.created_at,
420            updated_at: record.updated_at,
421            seal,
422        });
423    }
424
425    let descriptors = keep.list_all_wallet_descriptor_versions()?;
426    let relay_configs = keep.list_relay_configs()?;
427    let health_statuses = keep.list_health_statuses()?;
428    let kill_switch = keep.get_kill_switch()?;
429    let proxy = keep.get_proxy_config()?;
430    let audit_entries = keep.read_audit_entries()?;
431
432    let backup = VaultBackup {
433        version: VERSION,
434        created_at: chrono::Utc::now().to_rfc3339(),
435        keys: backup_keys,
436        shares: backup_shares,
437        wallet_descriptors: descriptors,
438        relay_configs,
439        health_statuses,
440        config: BackupConfig {
441            kill_switch,
442            proxy: if proxy.enabled { Some(proxy) } else { None },
443        },
444        audit_entries,
445        secrets: backup_secrets,
446    };
447    encode_backup(&backup, passphrase)
448}
449
450struct ParsedHeader {
451    salt: [u8; SALT_SIZE],
452    params: Argon2Params,
453    nonce: [u8; NONCE_SIZE],
454}
455
456fn parse_header(data: &[u8]) -> Result<ParsedHeader> {
457    if data.len() < HEADER_SIZE {
458        return Err(KeepError::InvalidInput("backup file too small".into()));
459    }
460    if data.len() > MAX_BACKUP_SIZE {
461        return Err(KeepError::InvalidInput(format!(
462            "backup file too large ({} bytes, max {MAX_BACKUP_SIZE})",
463            data.len()
464        )));
465    }
466
467    if &data[0..8] != MAGIC {
468        return Err(KeepError::InvalidInput("invalid backup file magic".into()));
469    }
470
471    let version = u16::from_le_bytes([data[8], data[9]]);
472    if version != VERSION {
473        return Err(KeepError::InvalidInput(format!(
474            "unsupported backup version: {version}"
475        )));
476    }
477
478    let flags = u16::from_le_bytes([data[10], data[11]]);
479    if flags != 0 {
480        return Err(KeepError::InvalidInput(format!(
481            "unsupported backup flags: {flags}"
482        )));
483    }
484
485    let mut salt = [0u8; SALT_SIZE];
486    salt.copy_from_slice(&data[12..44]);
487
488    let le32 = |offset: usize| -> Result<u32> {
489        let slice = data
490            .get(offset..offset + 4)
491            .ok_or_else(|| KeepError::InvalidInput("backup header truncated".into()))?;
492        Ok(u32::from_le_bytes(slice.try_into().unwrap()))
493    };
494    let memory_kib = le32(44)?;
495    let iterations = le32(48)?;
496    let parallelism = le32(52)?;
497
498    const MIN_MEMORY_KIB: u32 = 65_536; // 64 MiB
499    const MAX_MEMORY_KIB: u32 = 256 * 1024; // 256 MiB
500    const MIN_ITERATIONS: u32 = 2;
501    const MAX_ITERATIONS: u32 = 64;
502    const MAX_PARALLELISM: u32 = 16;
503    if !(MIN_MEMORY_KIB..=MAX_MEMORY_KIB).contains(&memory_kib) {
504        return Err(KeepError::InvalidInput(format!(
505            "backup argon2 memory out of range: {memory_kib} KiB (min {MIN_MEMORY_KIB}, max {MAX_MEMORY_KIB})"
506        )));
507    }
508    if !(MIN_ITERATIONS..=MAX_ITERATIONS).contains(&iterations) {
509        return Err(KeepError::InvalidInput(format!(
510            "backup argon2 iterations out of range: {iterations} (min {MIN_ITERATIONS}, max {MAX_ITERATIONS})"
511        )));
512    }
513    if parallelism == 0 || parallelism > MAX_PARALLELISM {
514        return Err(KeepError::InvalidInput(format!(
515            "backup argon2 parallelism out of range: {parallelism}"
516        )));
517    }
518
519    let mut nonce = [0u8; NONCE_SIZE];
520    nonce.copy_from_slice(&data[56..80]);
521
522    Ok(ParsedHeader {
523        salt,
524        params: Argon2Params {
525            memory_kib,
526            iterations,
527            parallelism,
528        },
529        nonce,
530    })
531}
532
533/// Decrypt a backup file and return its contents.
534pub fn decrypt_backup(data: &[u8], passphrase: &str) -> Result<DecryptedBackup> {
535    let header = parse_header(data)?;
536    let key = crypto::derive_key(passphrase.as_bytes(), &header.salt, header.params)?;
537
538    let encrypted = EncryptedData {
539        nonce: header.nonce,
540        ciphertext: data[HEADER_SIZE..].to_vec(),
541    };
542
543    let decrypted = crypto::decrypt(&encrypted, &key)?;
544    let json_bytes = decrypted.as_slice()?;
545
546    let vault: VaultBackup = serde_json::from_slice(json_bytes.as_ref())
547        .map_err(|e| KeepError::Other(format!("backup deserialization failed: {e}")))?;
548
549    Ok(DecryptedBackup {
550        keys: vault.keys,
551        shares: vault.shares,
552        wallet_descriptors: vault.wallet_descriptors,
553        relay_configs: vault.relay_configs,
554        health_statuses: vault.health_statuses,
555        config: vault.config,
556        audit_entries: vault.audit_entries,
557        secrets: vault.secrets,
558        created_at: vault.created_at,
559    })
560}
561
562/// Verify a backup file and return summary information.
563pub fn verify_backup(data: &[u8], passphrase: &str) -> Result<BackupInfo> {
564    let file_size = data.len();
565    let decrypted = decrypt_backup(data, passphrase)?;
566    Ok(BackupInfo {
567        key_count: decrypted.keys.len(),
568        share_count: decrypted.shares.len(),
569        descriptor_count: decrypted.wallet_descriptors.len(),
570        created_at: decrypted.created_at.clone(),
571        file_size,
572    })
573}
574
575fn restore_to_path(backup: &DecryptedBackup, path: &Path, vault_password: &str) -> Result<()> {
576    let keep = Keep::create(path, vault_password)?;
577    let data_key = keep.data_key()?;
578
579    for bk in &backup.keys {
580        let secret = decode_hex_32(&bk.secret, "secret")?;
581        let encrypted = crypto::encrypt(&secret, &data_key)?;
582        let pubkey = decode_hex_32(&bk.pubkey, "pubkey")?;
583
584        let record = KeyRecord {
585            id: crypto::blake2b_256(&pubkey),
586            pubkey,
587            key_type: string_to_key_type(&bk.key_type)?,
588            name: bk.name.clone(),
589            created_at: bk.created_at,
590            last_used: bk.last_used,
591            sign_count: bk.sign_count,
592            encrypted_secret: encrypted.to_bytes(),
593        };
594        keep.restore_key_record(&record)?;
595    }
596
597    for bs in &backup.shares {
598        let key_package_bytes = hex::decode(&bs.key_package)
599            .map_err(|e| KeepError::Other(format!("hex decode key_package: {e}")))?;
600
601        let pubkey_package = hex::decode(&bs.pubkey_package)
602            .map_err(|e| KeepError::Other(format!("hex decode pubkey_package: {e}")))?;
603
604        let group_pubkey = decode_hex_32(&bs.group_pubkey, "group pubkey")?;
605
606        let metadata = crate::frost::ShareMetadata {
607            identifier: bs.identifier,
608            threshold: bs.threshold,
609            total_shares: bs.total_shares,
610            group_pubkey,
611            name: bs.name.clone(),
612            created_at: bs.created_at,
613            last_used: bs.last_used,
614            sign_count: bs.sign_count,
615            did_backup: bs.did_backup,
616        };
617        let package =
618            crate::frost::SharePackage::from_bytes(metadata, key_package_bytes, pubkey_package);
619        let share = StoredShare::encrypt_with_ciphersuite(&package, bs.ciphersuite, &data_key)?;
620        keep.restore_stored_share(&share)?;
621    }
622
623    for d in &backup.wallet_descriptors {
624        keep.store_wallet_descriptor(d)?;
625    }
626
627    for c in &backup.relay_configs {
628        keep.store_relay_config(c)?;
629    }
630
631    for h in &backup.health_statuses {
632        keep.store_health_status(h)?;
633    }
634
635    for bs in &backup.secrets {
636        let id: [u8; 32] = decode_hex_32(&bs.id, "secret id")?;
637        let value = Zeroizing::new(
638            hex::decode(&bs.value)
639                .map_err(|e| KeepError::Other(format!("hex decode secret value: {e}")))?,
640        );
641        // Preserve the original id/timestamps so a restored secret keeps its
642        // identity; only `SecretRecord::new` mints a fresh id, which we bypass.
643        let record = SecretRecord {
644            id,
645            name: bs.name.clone(),
646            kind: string_to_secret_kind(&bs.kind)?,
647            value: value.to_vec(),
648            created_at: bs.created_at,
649            updated_at: bs.updated_at,
650        };
651        match &bs.seal {
652            // Threshold-sealed: `value` is the DEK-ciphertext; restore it with the
653            // seal so the value stays gated behind the OPRF quorum.
654            Some(bseal) => {
655                let seal = crate::secret::ThresholdSeal {
656                    wrapped_dek: hex::decode(&bseal.wrapped_dek)
657                        .map_err(|e| KeepError::Other(format!("hex decode wrapped dek: {e}")))?,
658                    oprf_id: bseal.oprf_id.clone(),
659                    epoch: bseal.epoch,
660                };
661                keep.restore_sealed_secret(&record, &seal)?;
662            }
663            None => keep.restore_secret(&record)?,
664        }
665    }
666
667    keep.set_kill_switch(backup.config.kill_switch)?;
668    if let Some(proxy) = &backup.config.proxy {
669        keep.set_proxy_config(proxy)?;
670    }
671
672    if !backup.audit_entries.is_empty() {
673        let data_key = keep.data_key()?;
674        let mut audit = AuditLog::open(path, &data_key)?;
675        for entry in &backup.audit_entries {
676            audit.log(entry.clone(), &data_key)?;
677        }
678    }
679
680    drop(keep);
681    Ok(())
682}
683
684/// Restore a backup to a new vault at the target path.
685pub fn restore_backup(
686    data: &[u8],
687    passphrase: &str,
688    target: &Path,
689    vault_password: &str,
690) -> Result<BackupInfo> {
691    let backup = decrypt_backup(data, passphrase)?;
692
693    let info = BackupInfo {
694        key_count: backup.keys.len(),
695        share_count: backup.shares.len(),
696        descriptor_count: backup.wallet_descriptors.len(),
697        created_at: backup.created_at.clone(),
698        file_size: data.len(),
699    };
700
701    if target.exists() {
702        return Err(KeepError::AlreadyExists(target.display().to_string()));
703    }
704
705    let rand_suffix: [u8; 8] = entropy::try_random_bytes()?;
706    let temp_name = format!(
707        "{}.restore-{}",
708        target
709            .file_name()
710            .map(|f| f.to_string_lossy().into_owned())
711            .unwrap_or_else(|| "vault".into()),
712        hex::encode(rand_suffix)
713    );
714    let temp_target = target.with_file_name(temp_name);
715
716    if let Err(e) = restore_to_path(&backup, &temp_target, vault_password) {
717        let _ = std::fs::remove_dir_all(&temp_target);
718        return Err(e);
719    }
720
721    std::fs::rename(&temp_target, target).map_err(|e| {
722        let _ = std::fs::remove_dir_all(&temp_target);
723        KeepError::Other(format!("failed to finalize restore: {e}"))
724    })?;
725
726    Ok(info)
727}
728
729#[cfg(test)]
730mod tests {
731    use super::*;
732    use crate::crypto::Argon2Params;
733    use tempfile::tempdir;
734
735    fn create_test_keep(path: &Path) -> Keep {
736        Keep::create_with_params(path, "test-password-123", Argon2Params::TESTING)
737            .expect("create keep")
738    }
739
740    #[test]
741    fn test_backup_roundtrip() {
742        let dir = tempdir().unwrap();
743        let vault_path = dir.path().join("source");
744        let mut keep = create_test_keep(&vault_path);
745        keep.generate_key("test-key").expect("generate key");
746
747        let backup_data = create_backup(&keep, "backup-passphrase-ok").unwrap();
748        assert!(backup_data.len() > HEADER_SIZE);
749
750        let info = verify_backup(&backup_data, "backup-passphrase-ok").unwrap();
751        assert_eq!(info.key_count, 1);
752        assert_eq!(info.share_count, 0);
753        assert_eq!(info.descriptor_count, 0);
754
755        let restore_path = dir.path().join("restored");
756        let info = restore_backup(
757            &backup_data,
758            "backup-passphrase-ok",
759            &restore_path,
760            "new-password-123",
761        )
762        .unwrap();
763        assert_eq!(info.key_count, 1);
764
765        let mut restored = Keep::open(&restore_path).unwrap();
766        restored.unlock("new-password-123").unwrap();
767        let keys = restored.list_keys().unwrap();
768        assert_eq!(keys.len(), 1);
769        assert_eq!(keys[0].name, "test-key");
770    }
771
772    #[test]
773    fn test_wrong_passphrase() {
774        let dir = tempdir().unwrap();
775        let vault_path = dir.path().join("source");
776        let keep = create_test_keep(&vault_path);
777
778        let backup_data = create_backup(&keep, "correct-passphrase").unwrap();
779        let result = verify_backup(&backup_data, "wrong-passphrase");
780        assert!(result.is_err());
781    }
782
783    #[test]
784    fn test_short_passphrase_rejected() {
785        let dir = tempdir().unwrap();
786        let vault_path = dir.path().join("source");
787        let keep = create_test_keep(&vault_path);
788        let result = create_backup(&keep, "short");
789        assert!(result.is_err());
790        assert!(result.unwrap_err().to_string().contains("at least"));
791    }
792
793    #[test]
794    fn test_invalid_magic() {
795        let mut data = vec![0u8; HEADER_SIZE + 100];
796        data[0..8].copy_from_slice(b"BADMAGIC");
797        let result = verify_backup(&data, "any-pass");
798        assert!(result.is_err());
799        assert!(result.unwrap_err().to_string().contains("magic"));
800    }
801
802    #[test]
803    fn test_audit_log_preserved_across_backup_restore() {
804        // Backup must ship decrypted audit entries; restore must re-encrypt
805        // them under the new vault's data key and emit a hash chain that
806        // verifies cleanly. Without this, `audit list` / `audit verify` on a
807        // restored vault sees zero history (the silent regression from #447).
808        let dir = tempdir().unwrap();
809        let src_path = dir.path().join("src");
810        let mut keep = create_test_keep(&src_path);
811        // `Keep::create_with_params` returns unlocked but with audit = None.
812        // Call unlock so subsequent operations write audit entries (matches
813        // the CLI flow which does Keep::open + unlock).
814        keep.unlock("test-password-123").unwrap();
815        keep.generate_key("k1").unwrap();
816        keep.generate_key("k2").unwrap();
817
818        let source_entries = keep.read_audit_entries().unwrap();
819        let source_count = source_entries.len();
820        assert!(source_count >= 2, "source audit must have entries");
821
822        let backup_data = create_backup(&keep, "backup-passphrase-ok").unwrap();
823
824        let dst_path = dir.path().join("dst");
825        restore_backup(
826            &backup_data,
827            "backup-passphrase-ok",
828            &dst_path,
829            "new-password-456",
830        )
831        .unwrap();
832
833        let mut restored = Keep::open(&dst_path).unwrap();
834        restored.unlock("new-password-456").unwrap();
835        let restored_entries = restored.read_audit_entries().unwrap();
836
837        // Restored vault must contain at least every source entry, in source
838        // order, before any post-restore entries the unlock above appended.
839        assert!(
840            restored_entries.len() >= source_count,
841            "restored audit must include all source entries (have {}, want >= {})",
842            restored_entries.len(),
843            source_count
844        );
845        for (i, src) in source_entries.iter().enumerate() {
846            let dst = &restored_entries[i];
847            assert_eq!(dst.event_type, src.event_type, "entry {i} event_type");
848            assert_eq!(dst.pubkey, src.pubkey, "entry {i} pubkey");
849            assert_eq!(dst.timestamp, src.timestamp, "entry {i} timestamp");
850        }
851    }
852
853    #[test]
854    fn backup_roundtrip_preserves_secrets() {
855        use crate::secret::{SecretKind, SecretRecord};
856        let dir = tempdir().unwrap();
857        let src_path = dir.path().join("src");
858        let mut keep = create_test_keep(&src_path);
859        keep.unlock("test-password-123").unwrap();
860
861        let rec = SecretRecord::new(
862            "db password".into(),
863            SecretKind::Password,
864            b"s3cr3t".to_vec(),
865        )
866        .unwrap();
867        let id = rec.id;
868        let created = rec.created_at;
869        keep.store_secret(&rec).unwrap();
870
871        let backup_data = create_backup(&keep, "backup-passphrase-ok").unwrap();
872
873        let dst_path = dir.path().join("dst");
874        restore_backup(
875            &backup_data,
876            "backup-passphrase-ok",
877            &dst_path,
878            "new-password-456",
879        )
880        .unwrap();
881
882        let mut restored = Keep::open(&dst_path).unwrap();
883        restored.unlock("new-password-456").unwrap();
884        let loaded = restored
885            .load_secret(&id)
886            .expect("secret MUST survive backup + restore");
887        assert_eq!(loaded.name, "db password");
888        assert_eq!(loaded.kind, SecretKind::Password);
889        assert_eq!(loaded.value, b"s3cr3t");
890        // Restore preserves the original id and timestamps, not fresh ones.
891        assert_eq!(loaded.created_at, created);
892    }
893
894    /// A threshold-sealed secret MUST survive backup + restore with its value
895    /// still gated behind the OPRF quorum: the backup carries the DEK-ciphertext
896    /// and the wrapped DEK (never plaintext), so after restore the value only
897    /// unseals under the SAME OPRF key -- exactly as before the backup.
898    #[test]
899    fn backup_roundtrip_preserves_sealed_secrets() {
900        let dir = tempdir().unwrap();
901        let src_path = dir.path().join("src");
902        let mut keep = create_test_keep(&src_path);
903        keep.unlock("test-password-123").unwrap();
904
905        let oprf_key = crypto::SecretKey::generate().unwrap();
906        let to_seal = crate::secret::SecretRecord::new(
907            "quorum note".into(),
908            crate::secret::SecretKind::Note,
909            b"only-with-a-quorum".to_vec(),
910        )
911        .unwrap();
912        let record = keep.store_sealed_secret(to_seal, &oprf_key, 0).unwrap();
913        let id = record.id;
914
915        let backup_data = create_backup(&keep, "backup-passphrase-ok").unwrap();
916
917        // The plaintext must NOT appear anywhere in the encrypted-then-decoded
918        // backup path; but more strongly, the value in the backup is DEK-ciphertext.
919        let dst_path = dir.path().join("dst");
920        restore_backup(
921            &backup_data,
922            "backup-passphrase-ok",
923            &dst_path,
924            "new-password-456",
925        )
926        .unwrap();
927
928        let mut restored = Keep::open(&dst_path).unwrap();
929        restored.unlock("new-password-456").unwrap();
930
931        // Metadata survives and is readable without a quorum.
932        let loaded = restored.load_secret(&id).expect("sealed record survives");
933        assert_eq!(loaded.name, "quorum note");
934        assert_eq!(loaded.kind, crate::secret::SecretKind::Note);
935        assert_ne!(
936            loaded.value, b"only-with-a-quorum",
937            "value must stay sealed"
938        );
939
940        // The value only comes back with the OPRF key; a wrong key stays sealed.
941        let revealed = restored
942            .reveal_sealed_secret(&id, &oprf_key)
943            .expect("value unseals with the OPRF key after restore");
944        assert_eq!(&revealed[..], b"only-with-a-quorum");
945        let wrong = crypto::SecretKey::generate().unwrap();
946        assert!(
947            restored.reveal_sealed_secret(&id, &wrong).is_err(),
948            "single-device (wrong OPRF key) must fail after restore too"
949        );
950    }
951
952    #[test]
953    fn secret_create_and_delete_are_audited() {
954        use crate::audit::AuditEventType;
955        use crate::secret::{SecretKind, SecretRecord};
956        let dir = tempdir().unwrap();
957        let mut keep = create_test_keep(&dir.path().join("v"));
958        keep.unlock("test-password-123").unwrap();
959
960        let rec = SecretRecord::new("t".into(), SecretKind::Note, b"v".to_vec()).unwrap();
961        let id = rec.id;
962        keep.store_secret(&rec).unwrap();
963        keep.delete_secret(&id).unwrap();
964
965        let entries = keep.audit_read_all().unwrap();
966        assert!(
967            entries
968                .iter()
969                .any(|e| matches!(e.event_type, AuditEventType::SecretCreate)),
970            "store_secret must emit a SecretCreate audit event"
971        );
972        assert!(
973            entries
974                .iter()
975                .any(|e| matches!(e.event_type, AuditEventType::SecretDelete)),
976            "delete_secret must emit a SecretDelete audit event"
977        );
978    }
979
980    #[test]
981    fn sealed_secret_create_and_reveal_are_audited() {
982        use crate::audit::AuditEventType;
983        let dir = tempdir().unwrap();
984        let mut keep = create_test_keep(&dir.path().join("v"));
985        keep.unlock("test-password-123").unwrap();
986
987        let oprf_key = crypto::SecretKey::generate().unwrap();
988        let record = crate::secret::SecretRecord::new(
989            "t".into(),
990            crate::secret::SecretKind::Note,
991            b"quorum-only".to_vec(),
992        )
993        .unwrap();
994        let rec = keep.store_sealed_secret(record, &oprf_key, 0).unwrap();
995
996        // A wrong-key reveal must NOT audit (it never yields the value).
997        let wrong = crypto::SecretKey::generate().unwrap();
998        assert!(keep.reveal_sealed_secret(&rec.id, &wrong).is_err());
999        // A successful reveal audits.
1000        keep.reveal_sealed_secret(&rec.id, &oprf_key).unwrap();
1001
1002        let entries = keep.audit_read_all().unwrap();
1003        assert!(
1004            entries
1005                .iter()
1006                .any(|e| matches!(e.event_type, AuditEventType::SecretCreate)),
1007            "store_sealed_secret must emit a SecretCreate audit event"
1008        );
1009        let reveals = entries
1010            .iter()
1011            .filter(|e| matches!(e.event_type, AuditEventType::SecretReveal))
1012            .count();
1013        assert_eq!(
1014            reveals, 1,
1015            "exactly one SecretReveal (only the successful unseal), not the wrong-key attempt"
1016        );
1017    }
1018
1019    /// Pin that backup + restore preserves every stored row type — not just
1020    /// keys (already covered by `test_backup_roundtrip`). #437's acceptance
1021    /// criterion is "verify in-place migration succeeds without data loss",
1022    /// and the migration unit underneath restore is the whole vault. A future
1023    /// refactor that drops shares, descriptors, or relay configs from the
1024    /// backup envelope would have shipped past the existing tests.
1025    #[test]
1026    fn backup_roundtrip_preserves_shares_descriptors_and_relay_config() {
1027        use crate::relay::{
1028            RelayConfig, StoredBunkerPermission, StoredPermissionDuration, GLOBAL_RELAY_KEY,
1029        };
1030        use crate::wallet::{WalletDescriptor, INITIAL_DESCRIPTOR_VERSION};
1031
1032        let dir = tempdir().unwrap();
1033        let src_path = dir.path().join("src");
1034        let mut keep = create_test_keep(&src_path);
1035        keep.unlock("test-password-123").unwrap();
1036
1037        // Populate every row type the backup envelope ships.
1038        let key_pubkey = keep.generate_key("primary").unwrap();
1039        let shares = keep.frost_split("primary", 2, 3).unwrap();
1040        assert_eq!(shares.len(), 3, "split should produce 3 shares");
1041        let group_pubkey = shares[0].metadata.group_pubkey;
1042
1043        let descriptor = WalletDescriptor {
1044            group_pubkey,
1045            external_descriptor: format!("tr({})/0/*)", hex::encode(group_pubkey)),
1046            internal_descriptor: format!("tr({})/1/*)", hex::encode(group_pubkey)),
1047            network: "signet".into(),
1048            created_at: 1_700_000_000,
1049            device_registrations: Vec::new(),
1050            policy_hash: [0x22; 32],
1051            version: INITIAL_DESCRIPTOR_VERSION,
1052            previous_descriptor_hash: None,
1053            policy: None,
1054        };
1055        keep.store_wallet_descriptor(&descriptor).unwrap();
1056
1057        let mut relay_cfg = RelayConfig::with_defaults(GLOBAL_RELAY_KEY);
1058        relay_cfg.bunker_permissions.push(StoredBunkerPermission {
1059            pubkey_hex: "a".repeat(64),
1060            name: "test-app".to_string(),
1061            permissions: 0b1111,
1062            auto_approve_kinds: vec![1, 7],
1063            duration: StoredPermissionDuration::Forever,
1064            connected_at: 1_700_000_000,
1065            timed_kind_grants: Vec::new(),
1066            explicitly_remembered: None,
1067        });
1068        relay_cfg.auto_approve_kinds = vec![22242];
1069        keep.store_relay_config(&relay_cfg).unwrap();
1070
1071        let backup_data = create_backup(&keep, "backup-passphrase-ok").unwrap();
1072
1073        let dst_path = dir.path().join("dst");
1074        let info = restore_backup(
1075            &backup_data,
1076            "backup-passphrase-ok",
1077            &dst_path,
1078            "new-password-456",
1079        )
1080        .unwrap();
1081        assert_eq!(info.key_count, 1);
1082        assert_eq!(info.share_count, 3);
1083        assert_eq!(info.descriptor_count, 1);
1084
1085        let mut restored = Keep::open(&dst_path).unwrap();
1086        restored.unlock("new-password-456").unwrap();
1087
1088        // Key survived (already covered by test_backup_roundtrip but pin
1089        // alongside the new assertions so a failure localizes here).
1090        let keys = restored.list_keys().unwrap();
1091        assert_eq!(keys.len(), 1);
1092        assert_eq!(keys[0].name, "primary");
1093        assert_eq!(keys[0].pubkey, key_pubkey);
1094
1095        // All three shares survived with intact metadata.
1096        let restored_shares = restored.frost_list_shares().unwrap();
1097        assert_eq!(restored_shares.len(), 3);
1098        for share in &restored_shares {
1099            assert_eq!(share.metadata.group_pubkey, group_pubkey);
1100            assert_eq!(share.metadata.threshold, 2);
1101            assert_eq!(share.metadata.total_shares, 3);
1102        }
1103
1104        // Descriptor survived with the same canonical hash.
1105        let restored_descs = restored.list_wallet_descriptors().unwrap();
1106        assert_eq!(restored_descs.len(), 1);
1107        assert_eq!(
1108            restored_descs[0].canonical_hash(),
1109            descriptor.canonical_hash(),
1110            "descriptor canonical hash must survive restore"
1111        );
1112
1113        // Relay config + bunker grants survived (without this, every NIP-46
1114        // pre-grant would silently vanish on restore).
1115        let restored_cfg = restored
1116            .get_relay_config(&GLOBAL_RELAY_KEY)
1117            .unwrap()
1118            .expect("relay config must survive restore");
1119        assert_eq!(restored_cfg.bunker_permissions.len(), 1);
1120        assert_eq!(restored_cfg.bunker_permissions[0].name, "test-app");
1121        assert_eq!(restored_cfg.auto_approve_kinds, vec![22242]);
1122    }
1123}