Skip to main content

keep_core/
rotation.rs

1// SPDX-FileCopyrightText: © 2026 PrivKey LLC
2// SPDX-License-Identifier: MIT
3
4use std::fs::{self, File, OpenOptions};
5use std::io::{Seek, SeekFrom, Write};
6use std::path::Path;
7
8use bincode::Options;
9use fs2::FileExt;
10use subtle::ConstantTimeEq;
11use tracing::warn;
12use zeroize::Zeroizing;
13
14use crate::backend::{
15    RedbBackend, StorageBackend, CONFIG_TABLE, DESCRIPTORS_TABLE, HEALTH_STATUS_TABLE, KEYS_TABLE,
16    RELAY_CONFIGS_TABLE, SECRETS_TABLE, SECRET_SEALS_TABLE, SHARES_TABLE,
17};
18use crate::crypto::{self, EncryptedData, SecretKey};
19use crate::error::{KeepError, Result};
20use crate::frost::StoredShare;
21use crate::keys::KeyRecord;
22use crate::relay::RelayConfig;
23use crate::storage::{
24    bincode_options, descriptor_storage_key, deserialize_stored_share, serialize_stored_share,
25    share_id, validate_new_password, Header, Storage,
26};
27use crate::wallet::WalletDescriptor;
28
29/// Tables whose values are opaque `EncryptedData` blobs sealed directly under the data key,
30/// with no typed collection path of their own. Rotation moves them verbatim: decrypt each row
31/// under the old key, re-encrypt under the new one. `STATE_VERSIONS_TABLE` is deliberately
32/// absent because it stores plaintext big-endian counters, not ciphertext.
33///
34/// `SECRETS_TABLE` qualifies: each row is `crypto::encrypt(bincode(SecretRecord))`, a single
35/// blob under the data key with no inner per-field encryption (unlike `KeyRecord`, whose
36/// separately-encrypted secret is why keys are rotated on their own typed path, not here).
37///
38/// `SECRET_SEALS_TABLE` likewise: each row is `crypto::encrypt(bincode(ThresholdSeal))`. Rotation
39/// re-wraps only this outer data-key layer; the inner DEK-ciphertext value and the OPRF-wrapped DEK
40/// are opaque bytes carried through untouched, so no OPRF quorum is needed to rotate the data key.
41const OPAQUE_TABLES: [&str; 4] = [
42    CONFIG_TABLE,
43    HEALTH_STATUS_TABLE,
44    SECRETS_TABLE,
45    SECRET_SEALS_TABLE,
46];
47
48/// One row of an [`OPAQUE_TABLES`] table, held decrypted across a rotation.
49struct OpaqueRow {
50    table: &'static str,
51    key: Vec<u8>,
52    plaintext: Zeroizing<Vec<u8>>,
53}
54
55fn secure_delete(path: &Path) -> std::io::Result<()> {
56    if let Ok(metadata) = fs::metadata(path) {
57        if let Ok(mut file) = OpenOptions::new().write(true).open(path) {
58            const CHUNK: usize = 8 * 1024;
59            let zeros = [0u8; CHUNK];
60            let mut remaining = metadata.len();
61            if file.seek(SeekFrom::Start(0)).is_ok() {
62                while remaining > 0 {
63                    let to_write = std::cmp::min(CHUNK as u64, remaining) as usize;
64                    if file.write_all(&zeros[..to_write]).is_err() {
65                        break;
66                    }
67                    remaining -= to_write as u64;
68                }
69            }
70            let _ = file.sync_all();
71        }
72    }
73    fs::remove_file(path)
74}
75
76#[cfg(not(windows))]
77fn fsync_dir(path: &Path) -> std::io::Result<()> {
78    let parent = path
79        .parent()
80        .ok_or_else(|| std::io::Error::other("path has no parent directory"))?;
81    let dir = File::open(parent)?;
82    dir.sync_all()
83}
84
85#[cfg(windows)]
86fn fsync_dir(_path: &Path) -> std::io::Result<()> {
87    Ok(())
88}
89
90fn copy_with_retry(from: &Path, to: &Path) -> std::io::Result<u64> {
91    const MAX_RETRIES: u32 = 10;
92    const RETRY_DELAY_MS: u64 = 50;
93
94    let mut last_err = None;
95    for _ in 0..MAX_RETRIES {
96        match fs::copy(from, to) {
97            Ok(n) => return Ok(n),
98            Err(e) => {
99                if e.kind() == std::io::ErrorKind::PermissionDenied {
100                    last_err = Some(e);
101                    std::thread::sleep(std::time::Duration::from_millis(RETRY_DELAY_MS));
102                    continue;
103                }
104                return Err(e);
105            }
106        }
107    }
108    Err(last_err.unwrap_or_else(|| {
109        std::io::Error::new(
110            std::io::ErrorKind::PermissionDenied,
111            "file copy failed after retries",
112        )
113    }))
114}
115
116fn acquire_rotation_lock(path: &Path) -> Result<File> {
117    let lock_path = path.join(".rotation.lock");
118    let lock_file = OpenOptions::new()
119        .read(true)
120        .write(true)
121        .create(true)
122        .truncate(false)
123        .open(&lock_path)?;
124    lock_file.lock_exclusive()?;
125    Ok(lock_file)
126}
127
128/// Non-blocking variant of `acquire_rotation_lock`. Returns `None` if the lock
129/// is already held (a rotation is in flight in another process/handle) or the
130/// lock file cannot be opened. Recovery uses this so it never mutates rotation
131/// files out from under a live `rotate_password`/`rotate_data_key`.
132fn try_acquire_rotation_lock(path: &Path) -> Option<File> {
133    let lock_path = path.join(".rotation.lock");
134    let lock_file = OpenOptions::new()
135        .read(true)
136        .write(true)
137        .create(true)
138        .truncate(false)
139        .open(&lock_path)
140        .ok()?;
141    lock_file.try_lock_exclusive().ok()?;
142    Some(lock_file)
143}
144
145/// Copy `from` over `to` and flush both the file and its directory entry to
146/// disk before returning, so a power loss after the caller deletes the source
147/// backup cannot leave `to` partially written.
148fn restore_file_durably(from: &Path, to: &Path) -> std::io::Result<()> {
149    copy_with_retry(from, to)?;
150    // Open with write access so `sync_all` maps to a working flush on every
151    // platform (Windows `FlushFileBuffers` requires a writable handle).
152    OpenOptions::new().write(true).open(to)?.sync_all()?;
153    fsync_dir(to)
154}
155
156fn cleanup_rotation_lock(_path: &Path) {
157    // No-op: we intentionally leave the lock file in place to avoid a race
158    // condition between drop(lock) and remove_file that could allow concurrent
159    // rotations. The file lock held by the lock object is sufficient.
160}
161
162/// Reconcile leftover artifacts from an interrupted rotation. Called by
163/// `Storage::open` before it reads `keep.hdr`, so a mid-rotation kill from
164/// either `rotate_password` or `rotate_data_key` (#565, #662) resolves to a
165/// consistent, openable state without operator intervention:
166///
167/// - `keep.hdr.tmp` is always stale: `write_header_atomically` only publishes
168///   via the atomic rename, so a leftover temp file never carries live state.
169/// - `keep.hdr.backup` + `keep.db.backup` present together mean
170///   `rotate_data_key` was in flight. If `keep.hdr` matches the backup byte
171///   for byte, the header rewrite never happened, which in turn means
172///   `reencrypt_database` had not finished either (it runs strictly before
173///   `write_header_atomically`). Restore `keep.db` from `keep.db.backup` so
174///   the DB matches the OLD DEK the header pins. If the header differs from
175///   the backup, the header rewrite succeeded, which means the reencrypt
176///   loop had run to completion first: `keep.db` is fully under the NEW DEK
177///   and the backups are stale.
178/// - `keep.hdr.backup` alone means `rotate_password` was in flight. Both
179///   possible header states (still-old, or already-rewritten to new) are
180///   durable and consistent on their own; the backup is stale.
181/// - `keep.db.backup` alone is a post-rotation leftover (a successful rotation
182///   deletes `keep.hdr.backup` before `keep.db.backup`); always stale.
183///
184/// Recovery first takes the rotation lock non-blockingly and does nothing if a
185/// rotation currently holds it, so it never mutates these files out from under
186/// a live rotation.
187///
188/// Errors are non-fatal on purpose: recovery must not turn a partially
189/// interrupted rotation into an unopenable vault. Crucially, a backup is only
190/// ever deleted once the reconciliation it feeds has provably completed, so a
191/// failed or skipped restore never destroys the sole pristine copy; the next
192/// `open` simply retries. Every write it performs is idempotent.
193pub(crate) fn recover_rotation_artifacts(path: &Path) {
194    // Serialize against a live rotation: `rotate_password`/`rotate_data_key`
195    // hold `.rotation.lock` while they mutate exactly these files. If a rotation
196    // owns the lock, it will clean up its own artifacts, so skip recovery
197    // entirely rather than racing its in-progress DB rewrite (which would
198    // corrupt `keep.db` and delete the backups it needs for its own rollback).
199    let lock = match try_acquire_rotation_lock(path) {
200        Some(lock) => lock,
201        None => return,
202    };
203
204    let hdr = path.join("keep.hdr");
205    let hdr_tmp = path.join("keep.hdr.tmp");
206    let hdr_backup = path.join("keep.hdr.backup");
207    let db = path.join("keep.db");
208    let db_backup = path.join("keep.db.backup");
209
210    let _ = fs::remove_file(&hdr_tmp);
211
212    let hdr_backup_exists = hdr_backup.exists();
213    let db_backup_exists = db_backup.exists();
214
215    if hdr_backup_exists && db_backup_exists {
216        match (fs::read(&hdr), fs::read(&hdr_backup)) {
217            (Ok(h), Ok(b)) if h == b => {
218                // Header still matches its backup: the rewrite never happened,
219                // so `reencrypt_database` had not committed either. `keep.db`
220                // is the sole readable copy only after being restored from the
221                // OLD-DEK backup the header still pins. If that restore fails,
222                // leave BOTH backups on disk untouched so the next open retries;
223                // never delete the pristine copy behind a failed restore.
224                if let Err(e) = restore_file_durably(&db_backup, &db) {
225                    warn!(
226                        error = %e,
227                        "rotation recovery: database restore failed; leaving backups for retry"
228                    );
229                    drop(lock);
230                    return;
231                }
232            }
233            (Ok(_), Ok(_)) => {
234                // Header differs from its backup: the rewrite completed, so
235                // `reencrypt_database` ran to completion first and `keep.db` is
236                // fully under the NEW DEK. The backups are stale; fall through
237                // and delete them.
238            }
239            _ => {
240                // Could not read the header or its backup. Do not touch the DB
241                // and do not delete the recovery input; retry on the next open.
242                drop(lock);
243                return;
244            }
245        }
246        let _ = secure_delete(&hdr_backup);
247        let _ = secure_delete(&db_backup);
248    } else if hdr_backup_exists {
249        // Lone header backup: a `rotate_password` artifact, always stale.
250        let _ = secure_delete(&hdr_backup);
251    } else if db_backup_exists {
252        // Lone DB backup: a post-rotation leftover (a successful rotation
253        // deletes `hdr.backup` before `db.backup`). Always stale; restoring it
254        // would be a downgrade, so only clean it up.
255        let _ = secure_delete(&db_backup);
256    }
257
258    drop(lock);
259}
260
261fn write_header_atomically(path: &Path, header: &Header) -> Result<()> {
262    let header_path = path.join("keep.hdr");
263    let tmp_path = path.join("keep.hdr.tmp");
264    let mut tmp_file = File::create(&tmp_path)?;
265    tmp_file.write_all(&header.to_bytes())?;
266    tmp_file.sync_all()?;
267    drop(tmp_file);
268    fs::rename(&tmp_path, &header_path)?;
269    fsync_dir(&header_path)?;
270    Ok(())
271}
272
273impl Storage {
274    /// Rotate the vault password.
275    ///
276    /// Re-encrypts the data encryption key with a new password-derived key.
277    /// Creates a backup of the header before rotation and restores it on failure.
278    pub fn rotate_password(&mut self, old_password: &str, new_password: &str) -> Result<()> {
279        validate_new_password(new_password)?;
280        let lock = acquire_rotation_lock(&self.path)?;
281
282        if !self.is_unlocked() {
283            self.unlock(old_password)?;
284        }
285
286        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
287        let data_key_bytes = data_key.decrypt()?;
288
289        // #581: verify `old_password` against the current header EVEN when the
290        // vault is already unlocked. Without this check, anyone with access to
291        // an unlocked Keep can re-wrap the data key under a new password
292        // without knowing the prior credential, and the PasswordRotate audit
293        // entry (#566) would attest a rotation that never proved knowledge of
294        // `old_password`.
295        self.verify_header_decryption(&self.header, old_password, &*data_key_bytes)?;
296        let old_header = self.header.clone();
297        let header_path = self.path.join("keep.hdr");
298        let backup_path = self.path.join("keep.hdr.backup");
299
300        copy_with_retry(&header_path, &backup_path)?;
301
302        let new_header = match self.create_header_with_key(new_password, data_key) {
303            Ok(h) => h,
304            Err(e) => {
305                let _ = secure_delete(&backup_path);
306                drop(lock);
307                cleanup_rotation_lock(&self.path);
308                return Err(e);
309            }
310        };
311        if let Err(e) = write_header_atomically(&self.path, &new_header) {
312            let _ = secure_delete(&backup_path);
313            drop(lock);
314            cleanup_rotation_lock(&self.path);
315            return Err(e);
316        }
317        self.header = new_header.clone();
318
319        if let Err(e) = self.verify_header_decryption(&new_header, new_password, &*data_key_bytes) {
320            self.header = old_header;
321            if let Err(restore_err) = copy_with_retry(&backup_path, &header_path) {
322                warn!(error = %restore_err, "failed to restore backup during rollback - vault may be corrupted");
323                drop(lock);
324                return Err(KeepError::RotationFailed(format!(
325                    "verification failed and backup restoration failed: {e} (restore error: {restore_err})"
326                )));
327            }
328            let _ = secure_delete(&backup_path);
329            drop(lock);
330            return Err(KeepError::RotationFailed(format!(
331                "verification failed: {e}"
332            )));
333        }
334
335        let _ = secure_delete(&backup_path);
336        drop(lock);
337        cleanup_rotation_lock(&self.path);
338        Ok(())
339    }
340
341    fn verify_header_decryption(
342        &self,
343        header: &Header,
344        password: &str,
345        expected_data_key: &[u8],
346    ) -> Result<()> {
347        let master_key =
348            crypto::derive_key(password.as_bytes(), &header.salt, header.argon2_params())?;
349        let header_key = crypto::derive_subkey(&master_key, b"keep-header-key")?;
350        let encrypted = EncryptedData {
351            nonce: header.nonce,
352            ciphertext: header.encrypted_data_key.to_vec(),
353        };
354        let decrypted = crypto::decrypt(&encrypted, &header_key)?;
355        let decrypted_bytes = decrypted.as_slice()?;
356        if !bool::from(decrypted_bytes.ct_eq(expected_data_key)) {
357            return Err(KeepError::DecryptionFailed);
358        }
359        Ok(())
360    }
361
362    fn create_header_with_key(&self, password: &str, data_key: &SecretKey) -> Result<Header> {
363        let mut header = Header::new(self.header.argon2_params())?;
364        let master_key =
365            crypto::derive_key(password.as_bytes(), &header.salt, header.argon2_params())?;
366        let header_key = crypto::derive_subkey(&master_key, b"keep-header-key")?;
367        let data_key_bytes = data_key.decrypt()?;
368        let encrypted = crypto::encrypt(&*data_key_bytes, &header_key)?;
369        header.nonce.copy_from_slice(&encrypted.nonce);
370        header
371            .encrypted_data_key
372            .copy_from_slice(&encrypted.ciphertext);
373        Ok(header)
374    }
375
376    /// Rotate the data encryption key.
377    ///
378    /// Generates a new data encryption key and re-encrypts all stored keys and shares.
379    /// Creates backups of the header and database before rotation and restores them on failure.
380    pub fn rotate_data_key(&mut self, password: &str) -> Result<()> {
381        let lock = acquire_rotation_lock(&self.path)?;
382
383        if !self.is_unlocked() {
384            self.unlock(password)?;
385        }
386
387        let old_data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?.clone();
388        let old_header = self.header.clone();
389
390        // #581: verify `password` against the current header even when the
391        // vault is already unlocked; same threat model as `rotate_password`.
392        {
393            let data_key_bytes = old_data_key.decrypt()?;
394            self.verify_header_decryption(&self.header, password, &*data_key_bytes)?;
395        }
396        let header_path = self.path.join("keep.hdr");
397        let backup_path = self.path.join("keep.hdr.backup");
398        let db_path = self.path.join("keep.db");
399        let db_backup_path = self.path.join("keep.db.backup");
400
401        let keys = self.list_keys()?;
402        let shares = self.list_shares()?;
403        let descriptors = self.list_all_descriptor_versions()?;
404        // Migration v4->v5 rekeys every legacy 32-byte descriptor row to a
405        // versioned 36-byte key, and `Storage::open` runs all pending
406        // migrations before rotation can be invoked. Guard that invariant
407        // here so the re-encrypt count equality below cannot be subverted by
408        // any straggler legacy row that would otherwise be silently skipped
409        // by versioned-key parsers post-rotation.
410        {
411            let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
412            let all_keys = backend.list_keys_with_prefix(DESCRIPTORS_TABLE, &[])?;
413            if let Some(bad) = all_keys.iter().find(|k| k.len() != 36) {
414                return Err(KeepError::RotationFailed(format!(
415                    "legacy descriptor row with key length {} remains pre-rotation; refusing to rotate",
416                    bad.len()
417                )));
418            }
419        }
420        let relay_configs = self.list_relay_configs()?;
421
422        let decrypted_keys = self.decrypt_all_keys(&keys, &old_data_key)?;
423        let decrypted_shares = self.decrypt_all_shares(&shares, &old_data_key)?;
424        // decrypt_opaque_rows lazily materializes any absent opaque table via a committed redb
425        // write. This is the sole live-DB mutation preceding the safety backup below; every other
426        // pre-backup step is read-only. It is safe: the create is idempotent, on a legacy vault
427        // lacking the table it at worst leaves an empty table, and the backup taken afterward
428        // captures that post-create state so a rollback stays consistent.
429        let opaque_rows = self.decrypt_opaque_rows(&old_data_key)?;
430
431        self.backend = None;
432
433        if let Err(e) = copy_with_retry(&header_path, &backup_path) {
434            self.backend = RedbBackend::open(&db_path)
435                .ok()
436                .map(|b| Box::new(b) as Box<dyn StorageBackend>);
437            return Err(KeepError::Io(e));
438        }
439        if let Err(e) = copy_with_retry(&db_path, &db_backup_path) {
440            self.backend = RedbBackend::open(&db_path)
441                .ok()
442                .map(|b| Box::new(b) as Box<dyn StorageBackend>);
443            return Err(KeepError::Io(e));
444        }
445
446        self.backend = Some(Box::new(match RedbBackend::open(&db_path) {
447            Ok(backend) => backend,
448            Err(e) => {
449                self.backend = RedbBackend::open(&db_path)
450                    .ok()
451                    .map(|b| Box::new(b) as Box<dyn StorageBackend>);
452                return Err(e);
453            }
454        }));
455
456        let result = (|| -> Result<()> {
457            let new_data_key = SecretKey::generate()?;
458            self.reencrypt_database(
459                &decrypted_keys,
460                &decrypted_shares,
461                &descriptors,
462                &relay_configs,
463                &opaque_rows,
464                &new_data_key,
465            )?;
466
467            let new_header = self.create_header_with_key(password, &new_data_key)?;
468            write_header_atomically(&self.path, &new_header)?;
469
470            self.header = new_header;
471            self.data_key = Some(new_data_key);
472
473            self.verify_rotation_integrity(
474                &decrypted_keys,
475                &decrypted_shares,
476                &descriptors,
477                &relay_configs,
478                &opaque_rows,
479            )?;
480
481            Ok(())
482        })();
483
484        if let Err(e) = result {
485            self.backend = None;
486            self.header = old_header;
487            self.data_key = Some(old_data_key.clone());
488            let header_err = copy_with_retry(&backup_path, &header_path).err();
489            let db_err = copy_with_retry(&db_backup_path, &db_path).err();
490            self.backend = RedbBackend::open(&db_path)
491                .ok()
492                .map(|b| Box::new(b) as Box<dyn StorageBackend>);
493            if let Some(ref err) = header_err {
494                warn!(error = %err, "failed to restore header backup during rollback - vault may be corrupted");
495            }
496            if let Some(ref err) = db_err {
497                warn!(error = %err, "failed to restore database backup during rollback - vault may be corrupted");
498            }
499            drop(lock);
500            if header_err.is_some() || db_err.is_some() {
501                return Err(KeepError::RotationFailed(format!(
502                    "rotation failed and backup restoration failed: {e} (header: {header_err:?}, db: {db_err:?})"
503                )));
504            }
505            if let Err(err) = secure_delete(&backup_path) {
506                warn!(path = %backup_path.display(), error = %err, "failed to securely delete backup file after rotation failure");
507            }
508            if let Err(err) = secure_delete(&db_backup_path) {
509                warn!(path = %db_backup_path.display(), error = %err, "failed to securely delete database backup after rotation failure");
510            }
511            return Err(e);
512        }
513
514        let _ = secure_delete(&backup_path);
515        let _ = secure_delete(&db_backup_path);
516        drop(lock);
517        cleanup_rotation_lock(&self.path);
518        Ok(())
519    }
520
521    fn decrypt_all_keys(
522        &self,
523        keys: &[KeyRecord],
524        data_key: &SecretKey,
525    ) -> Result<Vec<(KeyRecord, Zeroizing<Vec<u8>>)>> {
526        keys.iter()
527            .map(|record| {
528                let encrypted = EncryptedData::from_bytes(&record.encrypted_secret)?;
529                let secret = crypto::decrypt(&encrypted, data_key)?;
530                Ok((record.clone(), secret.as_slice()?))
531            })
532            .collect()
533    }
534
535    fn decrypt_all_shares(
536        &self,
537        shares: &[StoredShare],
538        data_key: &SecretKey,
539    ) -> Result<Vec<(StoredShare, Zeroizing<Vec<u8>>)>> {
540        shares
541            .iter()
542            .map(|stored| {
543                let encrypted = EncryptedData::from_bytes(&stored.encrypted_key_package)?;
544                let key_package_bytes =
545                    crypto::decrypt_with_aad(&encrypted, stored.ciphersuite.aad(), data_key)?;
546                Ok((stored.clone(), key_package_bytes.as_slice()?))
547            })
548            .collect()
549    }
550
551    fn decrypt_opaque_rows(&self, data_key: &SecretKey) -> Result<Vec<OpaqueRow>> {
552        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
553
554        let mut rows = Vec::new();
555        for table in OPAQUE_TABLES {
556            // A vault created before this table existed has no such table, and a redb read txn
557            // cannot create one. Same lazy-create idiom as `Storage::state_version`.
558            backend.create_table(table)?;
559            for (key, encrypted_bytes) in backend.list(table)? {
560                let encrypted = EncryptedData::from_bytes(&encrypted_bytes)?;
561                let plaintext = crypto::decrypt(&encrypted, data_key)?;
562                rows.push(OpaqueRow {
563                    table,
564                    key,
565                    plaintext: plaintext.as_slice()?,
566                });
567            }
568        }
569        Ok(rows)
570    }
571
572    fn reencrypt_database(
573        &self,
574        keys: &[(KeyRecord, Zeroizing<Vec<u8>>)],
575        shares: &[(StoredShare, Zeroizing<Vec<u8>>)],
576        descriptors: &[WalletDescriptor],
577        relay_configs: &[RelayConfig],
578        opaque_rows: &[OpaqueRow],
579        new_data_key: &SecretKey,
580    ) -> Result<()> {
581        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
582
583        for (record, secret_bytes) in keys {
584            let new_encrypted = crypto::encrypt(secret_bytes, new_data_key)?;
585            let mut new_record = record.clone();
586            new_record.encrypted_secret = new_encrypted.to_bytes();
587            let serialized = bincode::serialize(&new_record)?;
588            let record_encrypted = crypto::encrypt(&serialized, new_data_key)?;
589            backend.put(KEYS_TABLE, &new_record.id, &record_encrypted.to_bytes())?;
590        }
591
592        for (stored, key_package_bytes) in shares {
593            let package = crate::frost::SharePackage::from_bytes(
594                stored.metadata.clone(),
595                key_package_bytes.to_vec(),
596                stored.pubkey_package.clone(),
597            );
598            let new_stored =
599                StoredShare::encrypt_with_ciphersuite(&package, stored.ciphersuite, new_data_key)?;
600            let serialized = serialize_stored_share(&new_stored)?;
601            let record_encrypted = crypto::encrypt(&serialized, new_data_key)?;
602            let id = share_id(&stored.metadata.group_pubkey, stored.metadata.identifier);
603            backend.put(SHARES_TABLE, &id, &record_encrypted.to_bytes())?;
604        }
605
606        for descriptor in descriptors {
607            let serialized = serde_json::to_vec(descriptor)
608                .map_err(|e| KeepError::Other(format!("json serialization failed: {e}")))?;
609            let encrypted = crypto::encrypt(&serialized, new_data_key)?;
610            let key = descriptor_storage_key(&descriptor.group_pubkey, descriptor.version);
611            backend.put(DESCRIPTORS_TABLE, &key, &encrypted.to_bytes())?;
612        }
613
614        for config in relay_configs {
615            let serialized = serde_json::to_vec(config)
616                .map_err(|e| KeepError::Other(format!("json serialization failed: {e}")))?;
617            let encrypted = crypto::encrypt(&serialized, new_data_key)?;
618            backend.put(
619                RELAY_CONFIGS_TABLE,
620                &config.group_pubkey,
621                &encrypted.to_bytes(),
622            )?;
623        }
624
625        for row in opaque_rows {
626            let encrypted = crypto::encrypt(&row.plaintext, new_data_key)?;
627            backend.put(row.table, &row.key, &encrypted.to_bytes())?;
628        }
629
630        Ok(())
631    }
632
633    fn verify_rotation_integrity(
634        &self,
635        original_keys: &[(KeyRecord, Zeroizing<Vec<u8>>)],
636        original_shares: &[(StoredShare, Zeroizing<Vec<u8>>)],
637        original_descriptors: &[WalletDescriptor],
638        original_relay_configs: &[RelayConfig],
639        original_opaque_rows: &[OpaqueRow],
640    ) -> Result<()> {
641        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
642        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
643
644        let stored_keys = backend.list(KEYS_TABLE)?;
645        if stored_keys.len() != original_keys.len() {
646            return Err(KeepError::RotationFailed(format!(
647                "key count mismatch: expected {}, found {}",
648                original_keys.len(),
649                stored_keys.len()
650            )));
651        }
652
653        for (original_record, original_secret) in original_keys {
654            let encrypted_bytes =
655                backend
656                    .get(KEYS_TABLE, &original_record.id)?
657                    .ok_or_else(|| {
658                        KeepError::RotationFailed(format!(
659                            "key {} missing after rotation",
660                            hex::encode(original_record.id)
661                        ))
662                    })?;
663            let encrypted = EncryptedData::from_bytes(&encrypted_bytes)?;
664            let decrypted = crypto::decrypt(&encrypted, data_key)?;
665            let decrypted_bytes = decrypted.as_slice()?;
666            let record: KeyRecord = bincode_options().deserialize(&decrypted_bytes)?;
667            let inner_encrypted = EncryptedData::from_bytes(&record.encrypted_secret)?;
668            let inner_decrypted = crypto::decrypt(&inner_encrypted, data_key)?;
669            let inner_bytes = inner_decrypted.as_slice()?;
670            if !bool::from(inner_bytes.ct_eq(original_secret.as_slice())) {
671                return Err(KeepError::RotationFailed(format!(
672                    "key {} content mismatch after rotation",
673                    hex::encode(original_record.id)
674                )));
675            }
676        }
677
678        let stored_shares = backend.list(SHARES_TABLE)?;
679        if stored_shares.len() != original_shares.len() {
680            return Err(KeepError::RotationFailed(format!(
681                "share count mismatch: expected {}, found {}",
682                original_shares.len(),
683                stored_shares.len()
684            )));
685        }
686
687        for (original_stored, original_key_package) in original_shares {
688            let id = share_id(
689                &original_stored.metadata.group_pubkey,
690                original_stored.metadata.identifier,
691            );
692            let encrypted_bytes = backend.get(SHARES_TABLE, &id)?.ok_or_else(|| {
693                KeepError::RotationFailed(format!(
694                    "share {} missing after rotation",
695                    original_stored.metadata.identifier
696                ))
697            })?;
698            let encrypted = EncryptedData::from_bytes(&encrypted_bytes)?;
699            let decrypted = crypto::decrypt(&encrypted, data_key)?;
700            let decrypted_bytes = decrypted.as_slice()?;
701            let stored: StoredShare = deserialize_stored_share(&decrypted_bytes)?;
702            let inner_encrypted = EncryptedData::from_bytes(&stored.encrypted_key_package)?;
703            let inner_decrypted =
704                crypto::decrypt_with_aad(&inner_encrypted, stored.ciphersuite.aad(), data_key)?;
705            let inner_bytes = inner_decrypted.as_slice()?;
706            if !bool::from(inner_bytes.ct_eq(original_key_package.as_slice())) {
707                return Err(KeepError::RotationFailed(format!(
708                    "share {} content mismatch after rotation",
709                    original_stored.metadata.identifier
710                )));
711            }
712        }
713
714        let stored_descriptors = backend.list(DESCRIPTORS_TABLE)?;
715        if stored_descriptors.len() != original_descriptors.len() {
716            return Err(KeepError::RotationFailed(format!(
717                "descriptor count mismatch: expected {}, found {}",
718                original_descriptors.len(),
719                stored_descriptors.len()
720            )));
721        }
722
723        for original in original_descriptors {
724            let key = descriptor_storage_key(&original.group_pubkey, original.version);
725            let encrypted_bytes = backend.get(DESCRIPTORS_TABLE, &key)?.ok_or_else(|| {
726                KeepError::RotationFailed(format!(
727                    "descriptor for group {} version {} missing after rotation",
728                    hex::encode(original.group_pubkey),
729                    original.version
730                ))
731            })?;
732            let encrypted = EncryptedData::from_bytes(&encrypted_bytes)?;
733            let decrypted = crypto::decrypt(&encrypted, data_key)?;
734            let decrypted_bytes = decrypted.as_slice()?;
735            let descriptor: WalletDescriptor = serde_json::from_slice(&decrypted_bytes)
736                .map_err(|e| KeepError::Other(format!("json deserialization failed: {e}")))?;
737            if descriptor.group_pubkey != original.group_pubkey
738                || descriptor.external_descriptor != original.external_descriptor
739                || descriptor.internal_descriptor != original.internal_descriptor
740                || descriptor.network != original.network
741                || descriptor.created_at != original.created_at
742                || descriptor.version != original.version
743                || descriptor.previous_descriptor_hash != original.previous_descriptor_hash
744                || descriptor.policy_hash != original.policy_hash
745                || descriptor.device_registrations != original.device_registrations
746            {
747                return Err(KeepError::RotationFailed(format!(
748                    "descriptor for group {} version {} content mismatch after rotation",
749                    hex::encode(original.group_pubkey),
750                    original.version
751                )));
752            }
753        }
754
755        let stored_relay_configs = backend.list(RELAY_CONFIGS_TABLE)?;
756        if stored_relay_configs.len() != original_relay_configs.len() {
757            return Err(KeepError::RotationFailed(format!(
758                "relay config count mismatch: expected {}, found {}",
759                original_relay_configs.len(),
760                stored_relay_configs.len()
761            )));
762        }
763
764        for original in original_relay_configs {
765            let encrypted_bytes = backend
766                .get(RELAY_CONFIGS_TABLE, &original.group_pubkey)?
767                .ok_or_else(|| {
768                    KeepError::RotationFailed(format!(
769                        "relay config for group {} missing after rotation",
770                        hex::encode(original.group_pubkey)
771                    ))
772                })?;
773            let encrypted = EncryptedData::from_bytes(&encrypted_bytes)?;
774            let decrypted = crypto::decrypt(&encrypted, data_key)?;
775            let decrypted_bytes = decrypted.as_slice()?;
776            let config: RelayConfig = serde_json::from_slice(&decrypted_bytes)
777                .map_err(|e| KeepError::Other(format!("json deserialization failed: {e}")))?;
778            if config.group_pubkey != original.group_pubkey
779                || config.frost_relays != original.frost_relays
780                || config.profile_relays != original.profile_relays
781            {
782                return Err(KeepError::RotationFailed(format!(
783                    "relay config for group {} content mismatch after rotation",
784                    hex::encode(original.group_pubkey)
785                )));
786            }
787        }
788
789        for table in OPAQUE_TABLES {
790            let expected = original_opaque_rows
791                .iter()
792                .filter(|row| row.table == table)
793                .count();
794            let found = backend.list(table)?.len();
795            if found != expected {
796                return Err(KeepError::RotationFailed(format!(
797                    "{table} row count mismatch: expected {expected}, found {found}"
798                )));
799            }
800        }
801
802        for row in original_opaque_rows {
803            let encrypted_bytes = backend.get(row.table, &row.key)?.ok_or_else(|| {
804                KeepError::RotationFailed(format!(
805                    "{} row {} missing after rotation",
806                    row.table,
807                    hex::encode(&row.key)
808                ))
809            })?;
810            let encrypted = EncryptedData::from_bytes(&encrypted_bytes)?;
811            let decrypted = crypto::decrypt(&encrypted, data_key)?;
812            let decrypted_bytes = decrypted.as_slice()?;
813            if !bool::from(decrypted_bytes.ct_eq(row.plaintext.as_slice())) {
814                return Err(KeepError::RotationFailed(format!(
815                    "{} row {} content mismatch after rotation",
816                    row.table,
817                    hex::encode(&row.key)
818                )));
819            }
820        }
821
822        Ok(())
823    }
824}
825
826#[cfg(test)]
827mod tests {
828    use super::*;
829    use crate::crypto::Argon2Params;
830    use crate::storage::ProxyConfig;
831    use crate::wallet::KeyHealthStatus;
832    use tempfile::tempdir;
833
834    /// `rotate_data_key` must re-encrypt the `config` and `key_health_status` tables under the
835    /// new data key. It previously rewrote only keys/shares/descriptors/relay_configs, stranding
836    /// those rows under the old key and permanently breaking `get_kill_switch`, `get_proxy_config`,
837    /// `list_health_statuses`, and (via `get_kill_switch`) vault backup.
838    #[test]
839    fn rotate_data_key_reencrypts_config_and_health_status() {
840        let dir = tempdir().unwrap();
841        let path = dir.path().join("test-rotate-opaque");
842        let group_pubkey: [u8; 32] = crypto::random_bytes();
843
844        {
845            let mut storage = Storage::create(&path, "oldpass1", Argon2Params::TESTING).unwrap();
846            storage.set_kill_switch(true).unwrap();
847            storage
848                .set_proxy_config(&ProxyConfig {
849                    enabled: true,
850                    port: 9150,
851                })
852                .unwrap();
853            storage
854                .store_health_status(&KeyHealthStatus {
855                    group_pubkey,
856                    share_index: 3,
857                    last_check_timestamp: 1_700_000_000,
858                    responsive: true,
859                    created_at: Some(1_699_000_000),
860                })
861                .unwrap();
862
863            storage.rotate_data_key("oldpass1").unwrap();
864
865            assert!(storage.get_kill_switch().unwrap());
866        }
867
868        let mut storage = Storage::open(&path).unwrap();
869        storage.unlock("oldpass1").unwrap();
870
871        assert!(storage.get_kill_switch().unwrap());
872
873        let proxy = storage.get_proxy_config().unwrap();
874        assert!(proxy.enabled);
875        assert_eq!(proxy.port, 9150);
876
877        let statuses = storage.list_health_statuses().unwrap();
878        assert_eq!(statuses.len(), 1);
879        assert_eq!(statuses[0].group_pubkey, group_pubkey);
880        assert_eq!(statuses[0].share_index, 3);
881        assert_eq!(statuses[0].last_check_timestamp, 1_700_000_000);
882        assert!(statuses[0].responsive);
883        assert_eq!(statuses[0].created_at, Some(1_699_000_000));
884    }
885
886    /// A vault created before the `config`/`key_health_status` tables existed has neither table.
887    /// `decrypt_opaque_rows` must lazily create each absent table (a redb read txn cannot), so
888    /// rotation succeeds instead of failing on a missing table. Simulate the legacy layout by
889    /// dropping both tables from the redb file, then rotate.
890    #[test]
891    fn rotate_data_key_lazily_creates_missing_opaque_tables() {
892        let dir = tempdir().unwrap();
893        let path = dir.path().join("legacy-vault");
894
895        {
896            let storage = Storage::create(&path, "oldpass1", Argon2Params::TESTING).unwrap();
897            let pubkey: [u8; 32] = crypto::random_bytes();
898            let secret: Vec<u8> = vec![1, 2, 3, 4];
899            let encrypted = crypto::encrypt(&secret, storage.data_key().unwrap()).unwrap();
900            let record = KeyRecord::new(
901                pubkey,
902                crate::keys::KeyType::Nostr,
903                "legacy".into(),
904                encrypted.to_bytes(),
905            );
906            storage.store_key(&record).unwrap();
907        }
908
909        {
910            let config_def: redb::TableDefinition<&[u8], &[u8]> =
911                redb::TableDefinition::new(CONFIG_TABLE);
912            let health_def: redb::TableDefinition<&[u8], &[u8]> =
913                redb::TableDefinition::new(HEALTH_STATUS_TABLE);
914            let db = redb::Database::open(path.join("keep.db")).unwrap();
915            let wtxn = db.begin_write().unwrap();
916            assert!(
917                wtxn.delete_table(config_def).unwrap(),
918                "config table must exist before it can be dropped"
919            );
920            assert!(
921                wtxn.delete_table(health_def).unwrap(),
922                "key_health_status table must exist before it can be dropped"
923            );
924            wtxn.commit().unwrap();
925        }
926
927        let mut storage = Storage::open(&path).unwrap();
928        storage
929            .rotate_data_key("oldpass1")
930            .expect("rotation must lazily create the absent opaque tables");
931
932        assert!(!storage.get_kill_switch().unwrap());
933        assert!(storage.list_health_statuses().unwrap().is_empty());
934        assert_eq!(storage.list_keys().unwrap().len(), 1);
935    }
936
937    /// A rotation that fails after the safety backup is taken must roll back to the OLD data key.
938    /// With `config`/`key_health_status` rows present, those rows must remain readable under the
939    /// old key afterward. The failure is forced through an existing seam: `write_header_atomically`
940    /// creates `keep.hdr.tmp`, so a directory occupying that path makes the header write fail
941    /// mid-rotation, after `reencrypt_database` has run and the backup has been captured.
942    #[test]
943    fn rotate_data_key_rollback_preserves_opaque_rows() {
944        let dir = tempdir().unwrap();
945        let path = dir.path().join("rollback-vault");
946        let group_pubkey: [u8; 32] = crypto::random_bytes();
947
948        let mut storage = Storage::create(&path, "oldpass1", Argon2Params::TESTING).unwrap();
949        storage.set_kill_switch(true).unwrap();
950        storage
951            .set_proxy_config(&ProxyConfig {
952                enabled: true,
953                port: 9150,
954            })
955            .unwrap();
956        storage
957            .store_health_status(&KeyHealthStatus {
958                group_pubkey,
959                share_index: 3,
960                last_check_timestamp: 1_700_000_000,
961                responsive: true,
962                created_at: Some(1_699_000_000),
963            })
964            .unwrap();
965
966        // Occupy keep.hdr.tmp with a directory so the mid-rotation header write cannot create it.
967        fs::create_dir(path.join("keep.hdr.tmp")).unwrap();
968
969        let err = storage
970            .rotate_data_key("oldpass1")
971            .expect_err("header write must fail and force a rollback");
972        assert!(matches!(err, KeepError::Io(_)), "expected Io, got {err:?}");
973
974        assert!(storage.get_kill_switch().unwrap());
975        let proxy = storage.get_proxy_config().unwrap();
976        assert!(proxy.enabled);
977        assert_eq!(proxy.port, 9150);
978        let statuses = storage.list_health_statuses().unwrap();
979        assert_eq!(statuses.len(), 1);
980        assert_eq!(statuses[0].group_pubkey, group_pubkey);
981        assert_eq!(statuses[0].share_index, 3);
982        assert_eq!(statuses[0].created_at, Some(1_699_000_000));
983    }
984
985    #[test]
986    fn test_rotate_password() {
987        let dir = tempdir().unwrap();
988        let path = dir.path().join("test-rotate-pw");
989
990        {
991            let storage = Storage::create(&path, "oldpass1", Argon2Params::TESTING).unwrap();
992            let pubkey: [u8; 32] = crypto::random_bytes();
993            let secret: Vec<u8> = vec![1, 2, 3, 4, 5, 6, 7, 8];
994            let encrypted = crypto::encrypt(&secret, storage.data_key().unwrap()).unwrap();
995            let record = KeyRecord::new(
996                pubkey,
997                crate::keys::KeyType::Nostr,
998                "test".into(),
999                encrypted.to_bytes(),
1000            );
1001            storage.store_key(&record).unwrap();
1002        }
1003
1004        {
1005            let mut storage = Storage::open(&path).unwrap();
1006            storage.rotate_password("oldpass1", "newpass1").unwrap();
1007        }
1008
1009        {
1010            let mut storage = Storage::open(&path).unwrap();
1011            assert!(storage.unlock("oldpass1").is_err());
1012        }
1013
1014        {
1015            let mut storage = Storage::open(&path).unwrap();
1016            storage.unlock("newpass1").unwrap();
1017            let keys = storage.list_keys().unwrap();
1018            assert_eq!(keys.len(), 1);
1019            assert_eq!(keys[0].name, "test");
1020        }
1021    }
1022
1023    #[test]
1024    fn test_rotate_data_key() {
1025        let dir = tempdir().unwrap();
1026        let path = dir.path().join("test-rotate-dek");
1027
1028        {
1029            let storage = Storage::create(&path, "password", Argon2Params::TESTING).unwrap();
1030            let pubkey: [u8; 32] = crypto::random_bytes();
1031            let secret: Vec<u8> = vec![9, 10, 11, 12];
1032            let encrypted = crypto::encrypt(&secret, storage.data_key().unwrap()).unwrap();
1033            let record = KeyRecord::new(
1034                pubkey,
1035                crate::keys::KeyType::Nostr,
1036                "dek-test".into(),
1037                encrypted.to_bytes(),
1038            );
1039            storage.store_key(&record).unwrap();
1040        }
1041
1042        {
1043            let mut storage = Storage::open(&path).unwrap();
1044            storage.rotate_data_key("password").unwrap();
1045            let keys = storage.list_keys().unwrap();
1046            assert_eq!(keys.len(), 1);
1047            assert_eq!(keys[0].name, "dek-test");
1048        }
1049    }
1050
1051    // === #438: security-critical rotation property coverage ===
1052
1053    /// Create an empty vault under a fresh temp dir and return the temp dir
1054    /// (the caller must keep it alive) together with its path. Every #438
1055    /// rejection test starts from the same empty vault; the password stays an
1056    /// explicit argument so each test still shows what it unlocks with.
1057    fn create_empty_vault(password: &str) -> (tempfile::TempDir, std::path::PathBuf) {
1058        let dir = tempdir().unwrap();
1059        let path = dir.path().join("vault");
1060        let _ = Storage::create(&path, password, Argon2Params::TESTING).unwrap();
1061        (dir, path)
1062    }
1063
1064    /// `rotate_password` MUST reject a wrong old password without touching
1065    /// the header. A regression that accepts any input here would let
1066    /// anyone with file access change the password.
1067    #[test]
1068    fn test_rotate_password_rejects_wrong_old_password() {
1069        let (_dir, path) = create_empty_vault("correctpass");
1070
1071        let mut storage = Storage::open(&path).unwrap();
1072        let err = storage
1073            .rotate_password("WRONG_OLD_PASSWORD", "newpass1")
1074            .expect_err("wrong old password must be rejected");
1075        // Wrong old password fails at the unlock step inside rotate_password.
1076        // Pin the variant so a regression that rejects for an unrelated reason
1077        // (IO, lock contention, a future pre-unlock validation) doesn't pass
1078        // this test while the auth gate silently degrades.
1079        assert!(
1080            matches!(err, KeepError::DecryptionFailed),
1081            "expected DecryptionFailed, got {err:?}"
1082        );
1083
1084        // The original password must still unlock the vault unchanged.
1085        let mut storage = Storage::open(&path).unwrap();
1086        storage
1087            .unlock("correctpass")
1088            .expect("original password must still work after failed rotation");
1089    }
1090
1091    /// `rotate_password` MUST reject a new password that fails
1092    /// `validate_new_password` (too short). Without this, a rotation
1093    /// would silently weaken the vault to an empty-or-tiny password
1094    /// despite the create-time gate.
1095    #[test]
1096    fn test_rotate_password_rejects_short_new_password() {
1097        let (_dir, path) = create_empty_vault("validpass1");
1098
1099        let mut storage = Storage::open(&path).unwrap();
1100        let err = storage
1101            .rotate_password("validpass1", "")
1102            .expect_err("empty new password must be refused");
1103        assert!(
1104            matches!(err, KeepError::InvalidInput(_)),
1105            "expected InvalidInput, got {err:?}"
1106        );
1107
1108        let mut storage = Storage::open(&path).unwrap();
1109        let err = storage
1110            .rotate_password("validpass1", "a")
1111            .expect_err("too-short new password must be refused");
1112        assert!(
1113            matches!(err, KeepError::InvalidInput(_)),
1114            "expected InvalidInput, got {err:?}"
1115        );
1116
1117        // Original password still works.
1118        let mut storage = Storage::open(&path).unwrap();
1119        storage.unlock("validpass1").unwrap();
1120    }
1121
1122    /// `rotate_password` re-wraps the same data encryption key under the new
1123    /// password; it does not change the DEK or re-encrypt stored keys. This
1124    /// test confirms the DEK survives that re-wrap intact, so a stored secret
1125    /// still decrypts to the exact pre-rotation bytes under the new password.
1126    /// A regression that corrupted or replaced the DEK during the re-wrap
1127    /// would surface here as a decrypt failure or byte mismatch.
1128    #[test]
1129    fn test_rotate_password_preserves_decrypted_secret_bytes() {
1130        let dir = tempdir().unwrap();
1131        let path = dir.path().join("test-decrypt-after-pw");
1132        let original_secret: Vec<u8> = (0u8..32).collect();
1133        let pubkey: [u8; 32] = [0xAA; 32];
1134
1135        {
1136            let storage = Storage::create(&path, "oldpass1", Argon2Params::TESTING).unwrap();
1137            let encrypted = crypto::encrypt(&original_secret, storage.data_key().unwrap()).unwrap();
1138            let record = KeyRecord::new(
1139                pubkey,
1140                crate::keys::KeyType::Nostr,
1141                "decrypt-survives".into(),
1142                encrypted.to_bytes(),
1143            );
1144            storage.store_key(&record).unwrap();
1145        }
1146
1147        {
1148            let mut storage = Storage::open(&path).unwrap();
1149            storage.rotate_password("oldpass1", "newpass1").unwrap();
1150        }
1151
1152        let mut storage = Storage::open(&path).unwrap();
1153        storage.unlock("newpass1").unwrap();
1154        let data_key = storage.data_key().expect("unlocked has data_key");
1155        let keys = storage.list_keys().unwrap();
1156        assert_eq!(keys.len(), 1);
1157        let record = &keys[0];
1158        let encrypted =
1159            crypto::EncryptedData::from_bytes(&record.encrypted_secret).expect("decode encrypted");
1160        let decrypted = crypto::decrypt(&encrypted, data_key).expect("decrypt after rotation");
1161        let plaintext = decrypted.as_slice().expect("secret bytes");
1162        assert_eq!(
1163            plaintext.as_slice(),
1164            original_secret.as_slice(),
1165            "decrypted secret bytes MUST match the pre-rotation value"
1166        );
1167    }
1168
1169    /// A `rotate_data_key` (new random data key, every row re-encrypted) MUST
1170    /// carry `secrets` rows through: they are registered in `OPAQUE_TABLES`, so a
1171    /// missed registration would leave them under the OLD key and fail to decrypt
1172    /// here.
1173    #[test]
1174    fn rotate_data_key_preserves_secrets() {
1175        use crate::secret::{SecretKind, SecretRecord};
1176        let dir = tempdir().unwrap();
1177        let path = dir.path().join("secrets-survive-rotation");
1178        let id;
1179        {
1180            let storage = Storage::create(&path, "pass1234", Argon2Params::TESTING).unwrap();
1181            let rec = SecretRecord::new("api".into(), SecretKind::ApiToken, b"tok-secret".to_vec())
1182                .unwrap();
1183            id = rec.id;
1184            storage.store_secret(&rec).unwrap();
1185        }
1186        {
1187            let mut storage = Storage::open(&path).unwrap();
1188            storage.rotate_data_key("pass1234").unwrap();
1189        }
1190        let mut storage = Storage::open(&path).unwrap();
1191        storage.unlock("pass1234").unwrap();
1192        let loaded = storage
1193            .load_secret(&id)
1194            .expect("secret MUST survive a data-key rotation");
1195        assert_eq!(loaded.value, b"tok-secret");
1196        assert_eq!(loaded.name, "api");
1197        assert_eq!(loaded.kind, SecretKind::ApiToken);
1198    }
1199
1200    /// A threshold-sealed secret MUST survive a `rotate_data_key`: both the
1201    /// record (`SECRETS_TABLE`) and its seal (`SECRET_SEALS_TABLE`) are registered
1202    /// in `OPAQUE_TABLES`, so rotation re-wraps only the outer data-key layer and
1203    /// the value still unseals under the SAME OPRF key afterward (no quorum needed
1204    /// to rotate).
1205    #[test]
1206    fn rotate_data_key_preserves_sealed_secrets() {
1207        use crate::secret::{seal_value, unseal_value, SecretKind, SecretRecord};
1208        let dir = tempdir().unwrap();
1209        let path = dir.path().join("sealed-secrets-survive-rotation");
1210        let oprf_key = crypto::SecretKey::generate().unwrap();
1211        let id;
1212        {
1213            let storage = Storage::create(&path, "pass1234", Argon2Params::TESTING).unwrap();
1214            let mut rec =
1215                SecretRecord::new("vault-key".into(), SecretKind::Generic, Vec::new()).unwrap();
1216            id = rec.id;
1217            let (value_ct, seal) =
1218                seal_value(b"threshold-secret", &oprf_key, hex::encode(rec.id), 0).unwrap();
1219            rec.value = value_ct;
1220            storage.store_sealed_secret(&rec, &seal).unwrap();
1221        }
1222        {
1223            let mut storage = Storage::open(&path).unwrap();
1224            storage.rotate_data_key("pass1234").unwrap();
1225        }
1226        let mut storage = Storage::open(&path).unwrap();
1227        storage.unlock("pass1234").unwrap();
1228        let loaded = storage
1229            .load_secret(&id)
1230            .expect("sealed record MUST survive a data-key rotation");
1231        let seal = storage
1232            .load_secret_seal(&id)
1233            .expect("seal load ok")
1234            .expect("seal MUST survive a data-key rotation");
1235        let plaintext =
1236            unseal_value(&loaded.value, &seal, &oprf_key).expect("unseal after rotation");
1237        assert_eq!(
1238            &plaintext[..],
1239            b"threshold-secret",
1240            "value must still unseal under the same OPRF key post-rotation"
1241        );
1242    }
1243
1244    /// `rotate_data_key` MUST reject a wrong password. Without the gate,
1245    /// an attacker with file access could re-encrypt all stored secrets
1246    /// to a new key without ever proving they hold the password.
1247    #[test]
1248    fn test_rotate_data_key_rejects_wrong_password() {
1249        let (_dir, path) = create_empty_vault("correctpass");
1250
1251        let mut storage = Storage::open(&path).unwrap();
1252        let err = storage
1253            .rotate_data_key("WRONG_PASSWORD")
1254            .expect_err("wrong password to rotate_data_key must be refused");
1255        assert!(
1256            matches!(err, KeepError::DecryptionFailed),
1257            "expected DecryptionFailed, got {err:?}"
1258        );
1259
1260        // Original password still unlocks.
1261        let mut storage = Storage::open(&path).unwrap();
1262        storage
1263            .unlock("correctpass")
1264            .expect("original password must still work after failed dek rotation");
1265    }
1266
1267    /// `rotate_data_key` generates a fresh data encryption key and re-encrypts
1268    /// every stored secret under it. Verify three properties: the decrypted
1269    /// bytes round-trip unchanged, the on-disk ciphertext changes, and the OLD
1270    /// data key can no longer decrypt the new ciphertext. That last check is
1271    /// the proactive-security property, and unlike the ciphertext-changed
1272    /// check it cannot be satisfied by a fresh nonce alone, so it actually
1273    /// proves the key rotated rather than merely being re-encrypted in place.
1274    #[test]
1275    fn test_rotate_data_key_preserves_decrypted_secret_bytes() {
1276        let dir = tempdir().unwrap();
1277        let path = dir.path().join("test-decrypt-after-dek");
1278        let original_secret: Vec<u8> = (10u8..42).collect();
1279        let pubkey: [u8; 32] = [0xCC; 32];
1280
1281        let pre_ciphertext;
1282        let old_data_key;
1283        {
1284            let storage = Storage::create(&path, "password", Argon2Params::TESTING).unwrap();
1285            // Capture the pre-rotation data key so we can later prove it no
1286            // longer decrypts the rotated ciphertext.
1287            old_data_key = storage.data_key().unwrap().clone();
1288            let encrypted = crypto::encrypt(&original_secret, storage.data_key().unwrap()).unwrap();
1289            pre_ciphertext = encrypted.to_bytes();
1290            let record = KeyRecord::new(
1291                pubkey,
1292                crate::keys::KeyType::Nostr,
1293                "dek-decrypt-survives".into(),
1294                pre_ciphertext.clone(),
1295            );
1296            storage.store_key(&record).unwrap();
1297        }
1298
1299        {
1300            let mut storage = Storage::open(&path).unwrap();
1301            storage.rotate_data_key("password").unwrap();
1302        }
1303
1304        let mut storage = Storage::open(&path).unwrap();
1305        storage.unlock("password").unwrap();
1306        let data_key = storage.data_key().expect("unlocked has data_key");
1307        let keys = storage.list_keys().unwrap();
1308        assert_eq!(keys.len(), 1);
1309        let record = &keys[0];
1310
1311        // Ciphertext on disk MUST differ from pre-rotation. (Necessary but not
1312        // sufficient: a fresh nonce alone would change it, hence the old-key
1313        // check below.)
1314        assert_ne!(
1315            record.encrypted_secret, pre_ciphertext,
1316            "ciphertext must change after data-key rotation"
1317        );
1318
1319        let encrypted =
1320            crypto::EncryptedData::from_bytes(&record.encrypted_secret).expect("decode encrypted");
1321
1322        // The data key MUST have actually rotated: the OLD key can no longer
1323        // decrypt the post-rotation ciphertext (AEAD tag check fails under the
1324        // wrong key). This is the real proactive-security property.
1325        assert!(
1326            crypto::decrypt(&encrypted, &old_data_key).is_err(),
1327            "SECURITY VIOLATION: old data key still decrypts post-rotation \
1328             ciphertext; the data key was not actually rotated"
1329        );
1330
1331        // The new key decrypts to the identical plaintext.
1332        let decrypted = crypto::decrypt(&encrypted, data_key).expect("decrypt after rotation");
1333        let plaintext = decrypted.as_slice().expect("secret bytes");
1334        assert_eq!(
1335            plaintext.as_slice(),
1336            original_secret.as_slice(),
1337            "decrypted secret bytes MUST match the pre-rotation value"
1338        );
1339    }
1340
1341    // === #565: rotation crash-recovery / interleaving tests ===
1342    //
1343    // A real process kill during `rotate_password` or `rotate_data_key` can
1344    // only leave the vault in one of two durable states, plus some inert
1345    // crash-orphan files. `Storage::open` reads exactly `keep.hdr` and never
1346    // consults `keep.hdr.backup`, `keep.hdr.tmp`, or `keep.db.backup`, so:
1347    //
1348    //   * If the atomic `tmp` + rename of the new header never completed, the
1349    //     old header is intact and the OLD credential still unlocks.
1350    //   * Once the rename completed, the NEW credential unlocks.
1351    //
1352    // These tests reconstruct the on-disk artifacts each crash point would
1353    // leave behind and assert two properties: (1) the vault opens with exactly
1354    // the credential its durable state implies (never a half-rotated in-between,
1355    // never a leaked alternate credential from an orphan backup), and (2) a
1356    // crash-orphaned `.backup`/`.tmp` file is inert: it neither blocks open nor
1357    // wedges a subsequent rotation (whose own `File::create` / `copy_with_retry`
1358    // truncates the stale artifact).
1359    //
1360    // The one crash point `Storage::open` cannot make whole is a kill mid
1361    // `reencrypt_database` for `rotate_data_key`: rows are re-encrypted under
1362    // the new DEK while `keep.hdr` still pins the old DEK, and no auto-recovery
1363    // path exists today. `crash_mid_reencrypt_data_key_leaves_db_backup_intact`
1364    // pins that gap (fail-closed, `keep.db.backup` preserved) so a follow-up
1365    // that adds auto-recovery has a concrete test to move.
1366
1367    fn seed_key(storage: &Storage) -> (KeyRecord, Vec<u8>) {
1368        let pubkey: [u8; 32] = [0x77; 32];
1369        let secret: Vec<u8> = (0u8..24).collect();
1370        let encrypted = crypto::encrypt(&secret, storage.data_key().unwrap()).unwrap();
1371        let record = KeyRecord::new(
1372            pubkey,
1373            crate::keys::KeyType::Nostr,
1374            "crash-recovery-seed".into(),
1375            encrypted.to_bytes(),
1376        );
1377        storage.store_key(&record).unwrap();
1378        (record, secret)
1379    }
1380
1381    fn assert_secret_decrypts(storage: &Storage, expected: &[u8]) {
1382        let data_key = storage.data_key().expect("unlocked storage has data_key");
1383        let keys = storage.list_keys().expect("list keys post-crash");
1384        assert_eq!(keys.len(), 1, "seeded key must survive simulated crash");
1385        let encrypted = crypto::EncryptedData::from_bytes(&keys[0].encrypted_secret)
1386            .expect("encrypted secret parses");
1387        let decrypted = crypto::decrypt(&encrypted, data_key).expect("decrypt seeded key");
1388        let plaintext = decrypted.as_slice().expect("secret bytes");
1389        assert_eq!(plaintext.as_slice(), expected);
1390    }
1391
1392    /// #565 C1: crash-orphan `keep.hdr.backup` from an aborted `rotate_password`
1393    /// (written by `copy_with_retry` before `write_header_atomically` ran). The
1394    /// header was never touched, so the OLD password must still unlock, the
1395    /// never-committed new password must NOT unlock, and the stale backup must
1396    /// neither block open nor wedge a later rotation.
1397    #[test]
1398    fn crash_after_hdr_backup_leaves_vault_openable_with_old_pw() {
1399        let dir = tempdir().unwrap();
1400        let path = dir.path().join("vault");
1401        let old_pw = "old-password-1";
1402        let secret;
1403        {
1404            let storage = Storage::create(&path, old_pw, Argon2Params::TESTING).unwrap();
1405            let (_r, s) = seed_key(&storage);
1406            secret = s;
1407        }
1408
1409        // Simulate the copy_with_retry(&header_path, &backup_path) step
1410        // completing right before `write_header_atomically` would begin.
1411        fs::copy(path.join("keep.hdr"), path.join("keep.hdr.backup")).unwrap();
1412
1413        let mut storage = Storage::open(&path).expect("open with orphan .hdr.backup");
1414        storage.unlock(old_pw).expect("old password unlocks");
1415        assert_secret_decrypts(&storage, &secret);
1416
1417        // A never-committed new password must not accidentally work.
1418        drop(storage);
1419        let mut storage = Storage::open(&path).unwrap();
1420        assert!(storage.unlock("new-password-1").is_err());
1421
1422        // Recovery on open (#662) deletes the stale backup; a subsequent
1423        // rotation commits cleanly against a clean state.
1424        assert!(!path.join("keep.hdr.backup").exists());
1425        let mut storage = Storage::open(&path).unwrap();
1426        storage
1427            .rotate_password(old_pw, "committed-new-1")
1428            .expect("rotation succeeds after auto-cleanup of orphan .hdr.backup");
1429        drop(storage);
1430        let mut storage = Storage::open(&path).unwrap();
1431        storage
1432            .unlock("committed-new-1")
1433            .expect("committed new password unlocks after rotation over orphan backup");
1434        assert_secret_decrypts(&storage, &secret);
1435    }
1436
1437    /// #565 C2: crash inside `write_header_atomically` after the temp write but
1438    /// before the atomic rename. `keep.hdr` is untouched so the OLD password
1439    /// still unlocks, and the leftover `keep.hdr.tmp` is inert: it does not
1440    /// block open, and a later rotation (whose own `File::create` truncates the
1441    /// same tmp path) still succeeds.
1442    #[test]
1443    fn crash_between_tmp_write_and_rename_keeps_old_credential() {
1444        let dir = tempdir().unwrap();
1445        let path = dir.path().join("vault");
1446        let old_pw = "old-password-2";
1447        let secret;
1448        {
1449            let storage = Storage::create(&path, old_pw, Argon2Params::TESTING).unwrap();
1450            let (_r, s) = seed_key(&storage);
1451            secret = s;
1452        }
1453
1454        // Simulate: backup was made and a bogus (or partial) tmp header exists.
1455        fs::copy(path.join("keep.hdr"), path.join("keep.hdr.backup")).unwrap();
1456        fs::write(path.join("keep.hdr.tmp"), vec![0xFFu8; 32]).unwrap();
1457
1458        let mut storage = Storage::open(&path).expect("open ignores .hdr.tmp");
1459        storage.unlock(old_pw).expect("old password still unlocks");
1460        assert_secret_decrypts(&storage, &secret);
1461
1462        // Recovery on open (#662) deletes the stale tmp; a subsequent
1463        // rotation commits cleanly against a clean state.
1464        assert!(!path.join("keep.hdr.tmp").exists());
1465        drop(storage);
1466        let mut storage = Storage::open(&path).unwrap();
1467        storage
1468            .rotate_password(old_pw, "committed-new-2")
1469            .expect("rotation succeeds after auto-cleanup of orphan .hdr.tmp");
1470        drop(storage);
1471        let mut storage = Storage::open(&path).unwrap();
1472        storage
1473            .unlock("committed-new-2")
1474            .expect("committed new password unlocks after rotation over orphan tmp");
1475        assert_secret_decrypts(&storage, &secret);
1476    }
1477
1478    /// #565 C3/C4: crash in `rotate_password` after the new header has been
1479    /// renamed into place but before `verify_header_decryption` or the backup
1480    /// cleanup runs. From the caller's perspective the rotation has completed
1481    /// durably: the NEW password MUST unlock the vault. The orphan
1482    /// `keep.hdr.backup` (holding the OLD header) must not prevent open or leak
1483    /// an alternative credential.
1484    #[test]
1485    fn crash_after_header_rename_completes_rotation() {
1486        let dir = tempdir().unwrap();
1487        let path = dir.path().join("vault");
1488        let old_pw = "old-password-3";
1489        let new_pw = "new-password-3";
1490        let secret;
1491        {
1492            let storage = Storage::create(&path, old_pw, Argon2Params::TESTING).unwrap();
1493            let (_r, s) = seed_key(&storage);
1494            secret = s;
1495        }
1496
1497        // Snapshot the old header, run a full rotation, then reintroduce the
1498        // pre-rotation header as the orphan backup that a crash between the
1499        // rename and the backup-delete would leave behind.
1500        let old_hdr_bytes = fs::read(path.join("keep.hdr")).unwrap();
1501        {
1502            let mut storage = Storage::open(&path).unwrap();
1503            storage.rotate_password(old_pw, new_pw).unwrap();
1504        }
1505        fs::write(path.join("keep.hdr.backup"), &old_hdr_bytes).unwrap();
1506
1507        let mut storage = Storage::open(&path).expect("open with orphan pre-rotate backup");
1508        storage
1509            .unlock(new_pw)
1510            .expect("new password unlocks after rename-completed rotation");
1511        assert_secret_decrypts(&storage, &secret);
1512
1513        // The old password (present in the orphan backup) must NOT unlock:
1514        // `Storage::open` reads `keep.hdr`, not `keep.hdr.backup`.
1515        drop(storage);
1516        let mut storage = Storage::open(&path).unwrap();
1517        assert!(storage.unlock(old_pw).is_err());
1518    }
1519
1520    /// #565 D1: crash-orphan `keep.hdr.backup` from an aborted `rotate_data_key`
1521    /// (written before `keep.db.backup`). Nothing was mutated, so the password
1522    /// still unlocks under the OLD DEK, and the stale backup must not wedge a
1523    /// later data-key rotation.
1524    #[test]
1525    fn crash_after_hdr_backup_but_before_db_backup_keeps_old_dek() {
1526        let dir = tempdir().unwrap();
1527        let path = dir.path().join("vault");
1528        let pw = "same-password-4";
1529        let secret;
1530        {
1531            let storage = Storage::create(&path, pw, Argon2Params::TESTING).unwrap();
1532            let (_r, s) = seed_key(&storage);
1533            secret = s;
1534        }
1535
1536        fs::copy(path.join("keep.hdr"), path.join("keep.hdr.backup")).unwrap();
1537
1538        let mut storage = Storage::open(&path).unwrap();
1539        storage
1540            .unlock(pw)
1541            .expect("password unlocks pre-rotation vault");
1542        assert_secret_decrypts(&storage, &secret);
1543
1544        // Recovery on open (#662) deletes the stale header backup; the
1545        // subsequent data-key rotation commits cleanly and the seeded secret
1546        // round-trips under the new DEK.
1547        assert!(!path.join("keep.hdr.backup").exists());
1548        storage
1549            .rotate_data_key(pw)
1550            .expect("data-key rotation succeeds after auto-cleanup of orphan .hdr.backup");
1551        assert_secret_decrypts(&storage, &secret);
1552    }
1553
1554    /// #565 D2: the one crash point `Storage::open` cannot make whole. After a
1555    /// kill mid `reencrypt_database`, `keep.db` holds rows under the NEW DEK
1556    /// while `keep.hdr` still pins the OLD DEK. There is no in-process seam to
1557    /// stop `reencrypt_database` midway, so we reproduce the observable state
1558    /// after the fact: run a full rotation (every row now under the new DEK)
1559    /// and roll `keep.hdr` back to the old header. With a single seeded row
1560    /// this is indistinguishable from a genuine torn write.
1561    ///
1562    /// `Storage::open` calls `recover_rotation_artifacts` before reading the
1563    /// header (#662). Because `keep.hdr == keep.hdr.backup`, the recovery
1564    /// path knows the header rewrite never happened, which implies the
1565    /// reencrypt loop also had not finished (it runs strictly before
1566    /// `write_header_atomically`). It restores `keep.db` from
1567    /// `keep.db.backup` and deletes both backup files, so the caller sees a
1568    /// consistent OLD-credential vault that lists the seeded row unchanged.
1569    #[test]
1570    fn crash_mid_reencrypt_data_key_recovered_on_open() {
1571        let dir = tempdir().unwrap();
1572        let path = dir.path().join("vault");
1573        let pw = "same-password-5";
1574        let secret;
1575        {
1576            let storage = Storage::create(&path, pw, Argon2Params::TESTING).unwrap();
1577            let (_r, s) = seed_key(&storage);
1578            secret = s;
1579        }
1580
1581        // Snapshot pre-rotation state, run a full rotation, then reproduce a
1582        // mid-reencrypt kill by rolling `keep.hdr` back to old while leaving
1583        // `keep.db` under the new DEK. The `.backup` files are what real
1584        // rotation would have written before touching the DB.
1585        let old_hdr = fs::read(path.join("keep.hdr")).unwrap();
1586        let old_db = fs::read(path.join("keep.db")).unwrap();
1587        {
1588            let mut storage = Storage::open(&path).unwrap();
1589            storage.rotate_data_key(pw).unwrap();
1590        }
1591        fs::write(path.join("keep.hdr"), &old_hdr).unwrap();
1592        fs::write(path.join("keep.hdr.backup"), &old_hdr).unwrap();
1593        fs::write(path.join("keep.db.backup"), &old_db).unwrap();
1594
1595        let mut storage = Storage::open(&path).expect("open triggers recovery");
1596        storage
1597            .unlock(pw)
1598            .expect("OLD password unlocks after recovery");
1599        assert_secret_decrypts(&storage, &secret);
1600
1601        // Backups have been cleaned up.
1602        assert!(
1603            !path.join("keep.hdr.backup").exists(),
1604            "hdr backup deleted after recovery"
1605        );
1606        assert!(
1607            !path.join("keep.db.backup").exists(),
1608            "db backup deleted after recovery"
1609        );
1610    }
1611
1612    /// #565 D3: crash in `rotate_data_key` after the header rename but before
1613    /// `verify_rotation_integrity`. From the caller's perspective the rotation
1614    /// completed durably: the password unlocks the NEW header, the NEW DEK
1615    /// decrypts the DB rows, and the orphan `.backup` files (holding old-DEK
1616    /// snapshots) do not leak an alternative credential.
1617    #[test]
1618    fn crash_after_data_key_rotation_completes_before_backup_delete() {
1619        let dir = tempdir().unwrap();
1620        let path = dir.path().join("vault");
1621        let pw = "same-password-6";
1622        let secret;
1623        {
1624            let storage = Storage::create(&path, pw, Argon2Params::TESTING).unwrap();
1625            let (_r, s) = seed_key(&storage);
1626            secret = s;
1627        }
1628
1629        // Snapshot old header + db to place as the orphan `.backup` files
1630        // that a real crash-after-verify-before-delete would leave behind.
1631        let old_hdr = fs::read(path.join("keep.hdr")).unwrap();
1632        let old_db = fs::read(path.join("keep.db")).unwrap();
1633
1634        {
1635            let mut storage = Storage::open(&path).unwrap();
1636            storage.rotate_data_key(pw).unwrap();
1637        }
1638
1639        fs::write(path.join("keep.hdr.backup"), &old_hdr).unwrap();
1640        fs::write(path.join("keep.db.backup"), &old_db).unwrap();
1641
1642        let mut storage = Storage::open(&path).expect("open with orphan .backup files");
1643        storage
1644            .unlock(pw)
1645            .expect("password still unlocks after data-key rotation");
1646        assert_secret_decrypts(&storage, &secret);
1647    }
1648
1649    /// #565 concurrency: `acquire_rotation_lock` must serialize rotations via an
1650    /// exclusive flock on `.rotation.lock`. This drives one real rotation while
1651    /// the test thread holds that lock by hand, asserts the rotation blocks
1652    /// until the lock is released, then completes and commits the new password.
1653    /// It proves mutual exclusion (a rotation cannot proceed while the lock is
1654    /// held), not two-way convergence of two concurrent rotations.
1655    ///
1656    /// Depends on fs2 using flock(2), which is per-open-file-description on
1657    /// Unix: the test's handle and rotate_password's own handle contend even
1658    /// within this single process. If the lock ever moved to fcntl(2) record
1659    /// locks (per-process), same-process calls would stop blocking and this
1660    /// test would silently invert.
1661    #[test]
1662    fn concurrent_rotations_serialize_via_flock() {
1663        let dir = tempdir().unwrap();
1664        let path = dir.path().join("vault");
1665        let old_pw = "shared-old-7";
1666        {
1667            let _ = Storage::create(&path, old_pw, Argon2Params::TESTING).unwrap();
1668        }
1669
1670        let lock_path = path.join(".rotation.lock");
1671        let holder = OpenOptions::new()
1672            .read(true)
1673            .write(true)
1674            .create(true)
1675            .truncate(false)
1676            .open(&lock_path)
1677            .unwrap();
1678        holder.lock_exclusive().unwrap();
1679
1680        let path_bg = path.clone();
1681        let handle = std::thread::spawn(move || {
1682            let mut storage = Storage::open(&path_bg).unwrap();
1683            storage
1684                .rotate_password("shared-old-7", "shared-new-7")
1685                .map(|_| ())
1686        });
1687
1688        // Give the background thread time to reach `lock_exclusive()` inside
1689        // rotate_password and block. If the flock were not serializing us it
1690        // would race to completion here.
1691        std::thread::sleep(std::time::Duration::from_millis(200));
1692        assert!(
1693            !handle.is_finished(),
1694            "background rotate must block on the held lock"
1695        );
1696
1697        // Release the lock; the background thread's rotation should complete.
1698        drop(holder);
1699        let result = handle.join().expect("background thread joins");
1700        result.expect("background rotate succeeds once the lock is released");
1701
1702        // Vault is in a consistent post-rotation state.
1703        let mut storage = Storage::open(&path).unwrap();
1704        assert!(
1705            storage.unlock(old_pw).is_err(),
1706            "old password must not unlock after concurrent rotation"
1707        );
1708        let mut storage = Storage::open(&path).unwrap();
1709        storage
1710            .unlock("shared-new-7")
1711            .expect("new password unlocks the rotated vault");
1712    }
1713
1714    /// #662 recovery: when both backups are present but `keep.hdr` differs
1715    /// from `keep.hdr.backup`, the rotation had already completed its header
1716    /// rewrite. `reencrypt_database` runs strictly before that rewrite, so
1717    /// `keep.db` is fully under the NEW DEK. The recovery path MUST NOT
1718    /// restore the (stale) `keep.db.backup` in that case; it must only
1719    /// clean up the leftover backup files.
1720    #[test]
1721    fn recovery_does_not_overwrite_db_when_header_already_rotated() {
1722        let dir = tempdir().unwrap();
1723        let path = dir.path().join("vault");
1724        let old_pw = "recovery-old-8";
1725        let new_pw = "recovery-new-8";
1726        let secret;
1727        {
1728            let storage = Storage::create(&path, old_pw, Argon2Params::TESTING).unwrap();
1729            let (_r, s) = seed_key(&storage);
1730            secret = s;
1731        }
1732
1733        // Snapshot old header + db as the .backup files a crash post-verify,
1734        // pre-delete would have left behind after a full rotation.
1735        let old_hdr = fs::read(path.join("keep.hdr")).unwrap();
1736        let old_db = fs::read(path.join("keep.db")).unwrap();
1737        {
1738            let mut storage = Storage::open(&path).unwrap();
1739            storage.rotate_password(old_pw, new_pw).unwrap();
1740            storage.rotate_data_key(new_pw).unwrap();
1741        }
1742        fs::write(path.join("keep.hdr.backup"), &old_hdr).unwrap();
1743        fs::write(path.join("keep.db.backup"), &old_db).unwrap();
1744
1745        let mut storage = Storage::open(&path).expect("open triggers cleanup");
1746        // OLD password must not work — recovery must not have downgraded us.
1747        assert!(
1748            storage.unlock(old_pw).is_err(),
1749            "old credential must not unlock after post-rotation cleanup"
1750        );
1751        let mut storage = Storage::open(&path).unwrap();
1752        storage.unlock(new_pw).expect("new password still unlocks");
1753        assert_secret_decrypts(&storage, &secret);
1754
1755        assert!(!path.join("keep.hdr.backup").exists());
1756        assert!(!path.join("keep.db.backup").exists());
1757    }
1758
1759    /// #662 recovery: a lone `keep.hdr.backup` (rotate_password artifact) is
1760    /// always stale, since `keep.hdr` alone is authoritative for that
1761    /// rotation. Cleanup MUST remove it without touching anything else.
1762    #[test]
1763    fn recovery_cleans_up_lone_header_backup() {
1764        let dir = tempdir().unwrap();
1765        let path = dir.path().join("vault");
1766        let pw = "recovery-lone-9";
1767        let secret;
1768        {
1769            let storage = Storage::create(&path, pw, Argon2Params::TESTING).unwrap();
1770            let (_r, s) = seed_key(&storage);
1771            secret = s;
1772        }
1773
1774        // Simulate a rotate_password that got as far as writing the backup
1775        // but died before write_header_atomically completed.
1776        fs::copy(path.join("keep.hdr"), path.join("keep.hdr.backup")).unwrap();
1777
1778        let mut storage = Storage::open(&path).expect("open cleans up lone hdr backup");
1779        storage.unlock(pw).unwrap();
1780        assert_secret_decrypts(&storage, &secret);
1781        assert!(!path.join("keep.hdr.backup").exists());
1782    }
1783
1784    /// #662 recovery: `keep.hdr.tmp` from a torn `write_header_atomically`
1785    /// is always stale (rename is the commit point). Cleanup MUST delete
1786    /// it on every open, regardless of whether backups are present.
1787    #[test]
1788    fn recovery_deletes_stale_hdr_tmp() {
1789        let dir = tempdir().unwrap();
1790        let path = dir.path().join("vault");
1791        let pw = "recovery-tmp-10";
1792        {
1793            let _ = Storage::create(&path, pw, Argon2Params::TESTING).unwrap();
1794        }
1795        fs::write(path.join("keep.hdr.tmp"), vec![0xAB; 32]).unwrap();
1796
1797        let _ = Storage::open(&path).expect("open with stale .hdr.tmp");
1798        assert!(
1799            !path.join("keep.hdr.tmp").exists(),
1800            "stale .hdr.tmp must be deleted on open"
1801        );
1802    }
1803
1804    /// #662 recovery must never destroy the sole pristine copy. If the DB
1805    /// restore fails (here `keep.db` is made read-only so `copy_with_retry`
1806    /// cannot write it), BOTH `.backup` files must survive on disk so a later
1807    /// open can retry, and a subsequent open with the DB writable again must
1808    /// then recover cleanly.
1809    #[cfg(unix)]
1810    #[test]
1811    fn recovery_preserves_backups_when_db_restore_fails() {
1812        use std::os::unix::fs::PermissionsExt;
1813        let dir = tempdir().unwrap();
1814        let path = dir.path().join("vault");
1815        let pw = "recovery-failrestore-11";
1816        let secret;
1817        {
1818            let storage = Storage::create(&path, pw, Argon2Params::TESTING).unwrap();
1819            let (_r, s) = seed_key(&storage);
1820            secret = s;
1821        }
1822
1823        // Reproduce the mid-reencrypt state: full rotation, header rolled back
1824        // to old, both backups present.
1825        let old_hdr = fs::read(path.join("keep.hdr")).unwrap();
1826        let old_db = fs::read(path.join("keep.db")).unwrap();
1827        {
1828            let mut storage = Storage::open(&path).unwrap();
1829            storage.rotate_data_key(pw).unwrap();
1830        }
1831        fs::write(path.join("keep.hdr"), &old_hdr).unwrap();
1832        fs::write(path.join("keep.hdr.backup"), &old_hdr).unwrap();
1833        fs::write(path.join("keep.db.backup"), &old_db).unwrap();
1834
1835        // Make keep.db unwritable so the restore copy fails.
1836        let db = path.join("keep.db");
1837        let mut perms = fs::metadata(&db).unwrap().permissions();
1838        perms.set_mode(0o444);
1839        fs::set_permissions(&db, perms).unwrap();
1840
1841        // If the mode is ignored (e.g. running as root), the forced-failure
1842        // premise does not hold; skip rather than assert a false negative.
1843        if OpenOptions::new().write(true).open(&db).is_ok() {
1844            return;
1845        }
1846
1847        let _ = Storage::open(&path);
1848        assert!(
1849            path.join("keep.hdr.backup").exists(),
1850            "hdr backup must survive a failed restore"
1851        );
1852        assert!(
1853            path.join("keep.db.backup").exists(),
1854            "db backup must survive a failed restore"
1855        );
1856
1857        // Restore writability; the next open must now recover cleanly.
1858        let mut perms = fs::metadata(&db).unwrap().permissions();
1859        perms.set_mode(0o644);
1860        fs::set_permissions(&db, perms).unwrap();
1861        let mut storage = Storage::open(&path).expect("retry open recovers");
1862        storage
1863            .unlock(pw)
1864            .expect("old pw unlocks after successful retry");
1865        assert_secret_decrypts(&storage, &secret);
1866        assert!(!path.join("keep.hdr.backup").exists());
1867        assert!(!path.join("keep.db.backup").exists());
1868    }
1869
1870    /// #662 recovery: a lone `keep.db.backup` (post-rotation leftover, since a
1871    /// successful rotation deletes `hdr.backup` before `db.backup`) is always
1872    /// stale. It must be cleaned up, never restored over the live DB.
1873    #[test]
1874    fn recovery_cleans_up_lone_db_backup() {
1875        let dir = tempdir().unwrap();
1876        let path = dir.path().join("vault");
1877        let pw = "recovery-lonedb-12";
1878        let secret;
1879        {
1880            let storage = Storage::create(&path, pw, Argon2Params::TESTING).unwrap();
1881            let (_r, s) = seed_key(&storage);
1882            secret = s;
1883        }
1884
1885        // A stale db backup with no header backup: must be removed, and the
1886        // live vault (which restoring the backup would downgrade) left intact.
1887        fs::write(path.join("keep.db.backup"), b"stale-old-dek-db").unwrap();
1888
1889        let mut storage = Storage::open(&path).expect("open cleans up lone db backup");
1890        storage.unlock(pw).unwrap();
1891        assert_secret_decrypts(&storage, &secret);
1892        assert!(!path.join("keep.db.backup").exists());
1893    }
1894}