Skip to main content

keep_core/
storage.rs

1// SPDX-FileCopyrightText: © 2026 PrivKey LLC
2// SPDX-License-Identifier: MIT
3
4//! Persistent encrypted storage backend.
5use std::fs;
6use std::path::{Path, PathBuf};
7
8use tracing::{debug, trace, warn};
9
10use crate::backend::{
11    AtomicOp, RedbBackend, StorageBackend, CONFIG_TABLE, DESCRIPTORS_TABLE, HEALTH_STATUS_TABLE,
12    KEYS_TABLE, RELAY_CONFIGS_TABLE, SECRETS_TABLE, SECRET_SEALS_TABLE, SHARES_TABLE,
13    STATE_VERSIONS_TABLE,
14};
15use crate::crypto::{self, Argon2Params, EncryptedData, SecretKey, SALT_SIZE};
16use crate::error::{KeepError, Result, StorageError};
17use crate::frost::StoredShare;
18use crate::keys::KeyRecord;
19use crate::rate_limit;
20use crate::relay::{self, RelayConfig};
21use crate::secret::{SecretRecord, ThresholdSeal};
22use crate::wallet::{KeyHealthStatus, WalletDescriptor};
23
24use bincode::Options;
25use serde::{Deserialize, Serialize};
26use zeroize::Zeroizing;
27
28/// SOCKS5 proxy configuration stored in the vault.
29#[derive(Clone, Debug, Serialize, Deserialize)]
30pub struct ProxyConfig {
31    /// Whether the proxy is enabled.
32    pub enabled: bool,
33    /// The proxy port (host is always 127.0.0.1).
34    pub port: u16,
35}
36
37impl Default for ProxyConfig {
38    fn default() -> Self {
39        Self {
40            enabled: false,
41            port: 9050,
42        }
43    }
44}
45
46const MAX_RECORD_SIZE: u64 = 1024 * 1024;
47const MIN_PASSWORD_LEN: usize = 8;
48const MAX_PASSWORD_LEN: usize = 4096;
49
50pub(crate) fn bincode_options() -> impl Options {
51    bincode::options()
52        .with_fixint_encoding()
53        .allow_trailing_bytes()
54        .with_limit(MAX_RECORD_SIZE)
55}
56
57const HEADER_MAGIC: &[u8; 8] = b"KEEPVALT";
58const HEADER_VERSION: u16 = 1;
59const HEADER_SIZE: usize = 256;
60
61struct Argon2Bounds {
62    min: u32,
63    max: u32,
64}
65
66const ARGON2_MEMORY_KIB: Argon2Bounds = Argon2Bounds {
67    min: 1024,
68    max: 4_194_304,
69};
70const ARGON2_ITERATIONS: Argon2Bounds = Argon2Bounds { min: 1, max: 20 };
71const ARGON2_PARALLELISM: Argon2Bounds = Argon2Bounds { min: 1, max: 64 };
72
73fn validate_argon2_param(value: u32, bounds: &Argon2Bounds, name: &str) -> Result<()> {
74    if value < bounds.min || value > bounds.max {
75        return Err(KeepError::InvalidInput(format!(
76            "argon2 {} parameter: {} (must be {}-{})",
77            name, value, bounds.min, bounds.max
78        )));
79    }
80    Ok(())
81}
82
83fn validate_password_max_len(password: &str) -> Result<()> {
84    if password.len() > MAX_PASSWORD_LEN {
85        return Err(KeepError::InvalidInput(
86            "password too long (max 4096 bytes)".into(),
87        ));
88    }
89    Ok(())
90}
91
92pub(crate) fn validate_new_password(password: &str) -> Result<()> {
93    if password.len() < MIN_PASSWORD_LEN {
94        return Err(KeepError::InvalidInput(format!(
95            "password too short (min {MIN_PASSWORD_LEN} bytes)"
96        )));
97    }
98    validate_password_max_len(password)
99}
100
101/// Storage file header containing encryption metadata.
102#[repr(C)]
103#[derive(Clone)]
104pub(crate) struct Header {
105    pub(crate) magic: [u8; 8],
106    pub(crate) version: u16,
107    pub(crate) flags: u16,
108    pub(crate) salt: [u8; SALT_SIZE],
109    pub(crate) nonce: [u8; 24],
110    pub(crate) encrypted_data_key: [u8; 48],
111    pub(crate) argon2_memory_kib: u32,
112    pub(crate) argon2_iterations: u32,
113    pub(crate) argon2_parallelism: u32,
114    pub(crate) _padding: [u8; 140],
115}
116
117impl Header {
118    pub(crate) fn new(params: Argon2Params) -> Result<Self> {
119        Ok(Self {
120            magic: *HEADER_MAGIC,
121            version: HEADER_VERSION,
122            flags: 0,
123            salt: crypto::try_random_bytes()?,
124            nonce: crypto::try_random_bytes()?,
125            encrypted_data_key: [0; 48],
126            argon2_memory_kib: params.memory_kib,
127            argon2_iterations: params.iterations,
128            argon2_parallelism: params.parallelism,
129            _padding: [0; 140],
130        })
131    }
132
133    pub(crate) fn argon2_params(&self) -> Argon2Params {
134        Argon2Params {
135            memory_kib: self.argon2_memory_kib,
136            iterations: self.argon2_iterations,
137            parallelism: self.argon2_parallelism,
138        }
139    }
140
141    pub(crate) fn to_bytes(&self) -> [u8; HEADER_SIZE] {
142        let mut bytes = [0u8; HEADER_SIZE];
143        bytes[0..8].copy_from_slice(&self.magic);
144        bytes[8..10].copy_from_slice(&self.version.to_le_bytes());
145        bytes[10..12].copy_from_slice(&self.flags.to_le_bytes());
146        bytes[12..44].copy_from_slice(&self.salt);
147        bytes[44..68].copy_from_slice(&self.nonce);
148        bytes[68..116].copy_from_slice(&self.encrypted_data_key);
149        bytes[116..120].copy_from_slice(&self.argon2_memory_kib.to_le_bytes());
150        bytes[120..124].copy_from_slice(&self.argon2_iterations.to_le_bytes());
151        bytes[124..128].copy_from_slice(&self.argon2_parallelism.to_le_bytes());
152        bytes
153    }
154
155    pub(crate) fn from_bytes(bytes: &[u8; HEADER_SIZE]) -> Result<Self> {
156        let mut magic = [0u8; 8];
157        magic.copy_from_slice(&bytes[0..8]);
158
159        if magic != *HEADER_MAGIC {
160            return Err(StorageError::invalid_format("invalid keep file magic").into());
161        }
162
163        let version = u16::from_le_bytes([bytes[8], bytes[9]]);
164        if version > HEADER_VERSION {
165            return Err(StorageError::invalid_format("unsupported version").into());
166        }
167
168        let mut salt = [0u8; SALT_SIZE];
169        salt.copy_from_slice(&bytes[12..44]);
170
171        let mut nonce = [0u8; 24];
172        nonce.copy_from_slice(&bytes[44..68]);
173
174        let mut encrypted_data_key = [0u8; 48];
175        encrypted_data_key.copy_from_slice(&bytes[68..116]);
176
177        let argon2_memory_kib =
178            u32::from_le_bytes([bytes[116], bytes[117], bytes[118], bytes[119]]);
179        let argon2_iterations =
180            u32::from_le_bytes([bytes[120], bytes[121], bytes[122], bytes[123]]);
181        let argon2_parallelism =
182            u32::from_le_bytes([bytes[124], bytes[125], bytes[126], bytes[127]]);
183
184        validate_argon2_param(argon2_memory_kib, &ARGON2_MEMORY_KIB, "memory")?;
185        validate_argon2_param(argon2_iterations, &ARGON2_ITERATIONS, "iterations")?;
186        validate_argon2_param(argon2_parallelism, &ARGON2_PARALLELISM, "parallelism")?;
187
188        Ok(Self {
189            magic,
190            version,
191            flags: u16::from_le_bytes([bytes[10], bytes[11]]),
192            salt,
193            nonce,
194            encrypted_data_key,
195            argon2_memory_kib,
196            argon2_iterations,
197            argon2_parallelism,
198            _padding: [0; 140],
199        })
200    }
201}
202
203/// Sink for vault-state changes so a node can replicate its redb records to a standby (the
204/// keep-state-over-wisp design). keep-web installs an implementation that publishes each change as a
205/// Nostr event; keep-core only signals table/record/bytes and never touches the network. `on_record`
206/// carries the record's already-encrypted redb bytes -- the exact bytes stored -- so a peer that
207/// shares the vault key stores them verbatim. Called from inside the write path, so an implementation
208/// MUST NOT block: enqueue and return.
209pub trait StatePublisher: Send + Sync {
210    /// A record was written: `table` is one of keys/descriptors/relay_configs, `record_id` is its
211    /// hex redb key, and `encrypted` is the vault-encrypted bytes as stored.
212    fn on_record(&self, table: &str, record_id: &str, encrypted: &[u8]);
213    /// A record (`table`, hex `record_id`) was deleted.
214    fn on_delete(&self, table: &str, record_id: &str);
215}
216
217/// Maximum seconds a replicated event's `created_at` may exceed local wall-clock before it is rejected
218/// as a poison attempt. Must exceed the publisher's legitimate future drift (same-second bumps advance
219/// `created_at` ~1s each) plus genuine inter-node clock skew, and stay within the NIP-11
220/// `created_at_upper_limit` range. Without it, a validly-signed event (which requires the shared cluster
221/// key) with `created_at` near `u64::MAX` would freeze a record's high-water-mark forever -- dropping
222/// every later update AND its revocation tombstone, across restarts and identity rotation.
223const MAX_FUTURE_SKEW_SECS: u64 = 300;
224
225/// Outcome of applying a replicated keep-state event on the standby.
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum ReplicatedApply {
228    /// Applied; the per-d-tag high-water-mark advanced.
229    Applied,
230    /// Ignored: not strictly newer than the mark already applied (a stale event or replay).
231    IgnoredStale,
232    /// Rejected: `created_at` is implausibly far in the future (a poison attempt requiring the cluster
233    /// key). The mark is NOT advanced, so a legitimate later event still applies.
234    RejectedFuture,
235}
236
237/// Encrypted persistent storage for keys and FROST shares.
238pub struct Storage {
239    pub(crate) path: PathBuf,
240    pub(crate) header: Header,
241    pub(crate) data_key: Option<SecretKey>,
242    pub(crate) backend: Option<Box<dyn StorageBackend>>,
243    /// Serializes read-modify-write sequences on wallet descriptors so that
244    /// e.g. two concurrent `upsert_device_registration` calls cannot drop
245    /// one another's updates.
246    pub(crate) descriptor_lock: std::sync::Mutex<()>,
247    /// Optional replication sink; see [`StatePublisher`]. `RwLock` so keep-web can install it after
248    /// construction (via [`Storage::set_state_publisher`]) while storage methods take `&self`.
249    pub(crate) state_publisher: std::sync::RwLock<Option<std::sync::Arc<dyn StatePublisher>>>,
250}
251
252fn create_storage_dir(path: &Path) -> Result<()> {
253    if path.exists() {
254        return Err(KeepError::AlreadyExists(path.display().to_string()));
255    }
256    fs::create_dir_all(path)?;
257    #[cfg(unix)]
258    {
259        use std::os::unix::fs::PermissionsExt;
260        fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
261    }
262    Ok(())
263}
264
265/// Write a vault data file with 0o600 perms on Unix. Defense-in-depth: even
266/// if the containing 0o700 directory is ever loosened (umask, restore-from-tar,
267/// rsync to a less-strict filesystem), the file itself stays owner-readable.
268fn write_vault_file_secure(path: &Path, data: &[u8]) -> Result<()> {
269    #[cfg(unix)]
270    {
271        use std::os::unix::fs::OpenOptionsExt;
272        let mut file = fs::OpenOptions::new()
273            .write(true)
274            .create(true)
275            .truncate(true)
276            .mode(0o600)
277            .open(path)?;
278        std::io::Write::write_all(&mut file, data)?;
279        file.sync_all()?;
280    }
281    #[cfg(not(unix))]
282    fs::write(path, data)?;
283    Ok(())
284}
285
286/// Apply 0o600 perms to an existing file (best-effort). Used to bring
287/// pre-existing redb-created files in line with the rest of the vault.
288#[cfg(unix)]
289fn chmod_secure(path: &Path) -> std::io::Result<()> {
290    use std::os::unix::fs::PermissionsExt;
291    fs::set_permissions(path, fs::Permissions::from_mode(0o600))
292}
293
294impl Storage {
295    /// Install the replication sink (keep-web). A later call replaces the previous sink.
296    pub fn set_state_publisher(&self, publisher: std::sync::Arc<dyn StatePublisher>) {
297        if let Ok(mut slot) = self.state_publisher.write() {
298            *slot = Some(publisher);
299        }
300    }
301
302    fn notify_record(&self, table: &str, record_id: &str, encrypted: &[u8]) {
303        if let Ok(slot) = self.state_publisher.read() {
304            if let Some(p) = slot.as_ref() {
305                p.on_record(table, record_id, encrypted);
306            }
307        }
308    }
309
310    fn notify_delete(&self, table: &str, record_id: &str) {
311        if let Ok(slot) = self.state_publisher.read() {
312            if let Some(p) = slot.as_ref() {
313                p.on_delete(table, record_id);
314            }
315        }
316    }
317
318    /// Apply a record replicated from a peer (the keep-state consumer / standby side). Stores the
319    /// already-vault-encrypted `encrypted` bytes verbatim under `table`, keyed by hex `record_id` --
320    /// the standby shares the vault key, so it later decrypts them like its own. Never notifies the
321    /// publisher, so a consumed record is not echoed back to the relay. Rejects any table but the three
322    /// replicated ones, so a hostile or buggy peer cannot write `shares` or node-local state.
323    /// `created_at` is the replicated event's signed timestamp; the record is applied only if it is
324    /// strictly newer than the highest already applied for this d-tag (rollback/replay guard). Returns
325    /// `true` if applied, `false` if ignored as stale.
326    pub fn apply_replicated_record(
327        &self,
328        table: &str,
329        record_id: &str,
330        encrypted: &[u8],
331        created_at: u64,
332        now: u64,
333    ) -> Result<ReplicatedApply> {
334        let (table_name, key) = Self::replicated_key(table, record_id)?;
335        // Reject an implausibly future-dated event before it can advance the mark. `created_at` is
336        // signed (a relay cannot forge it), but a holder of the shared cluster key could otherwise stamp
337        // a mark near u64::MAX and permanently freeze this record; the mark is left untouched so a
338        // legitimate later event still applies.
339        if created_at > now.saturating_add(MAX_FUTURE_SKEW_SECS) {
340            return Ok(ReplicatedApply::RejectedFuture);
341        }
342        let vkey = Self::state_version_key(table_name, &key);
343        if !self.state_version_is_newer(&vkey, created_at)? {
344            return Ok(ReplicatedApply::IgnoredStale);
345        }
346        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
347        // Write the data row and advance the high-water-mark in ONE atomic transaction: if these were
348        // two writes a crash between them would strand the mark BEHIND the data, and an untrusted relay
349        // could then replay an intermediate validly-signed version to roll the record back.
350        let ts = created_at.to_be_bytes();
351        backend.write_atomic(&[
352            AtomicOp {
353                table: table_name,
354                key: &key,
355                value: Some(encrypted),
356            },
357            AtomicOp {
358                table: STATE_VERSIONS_TABLE,
359                key: &vkey,
360                value: Some(&ts),
361            },
362        ])?;
363        Ok(ReplicatedApply::Applied)
364    }
365
366    /// Apply a replicated delete (tombstone) from a peer. Never notifies the publisher. Same rollback +
367    /// future-bound guards as `apply_replicated_record`.
368    pub fn apply_replicated_delete(
369        &self,
370        table: &str,
371        record_id: &str,
372        created_at: u64,
373        now: u64,
374    ) -> Result<ReplicatedApply> {
375        let (table_name, key) = Self::replicated_key(table, record_id)?;
376        if created_at > now.saturating_add(MAX_FUTURE_SKEW_SECS) {
377            return Ok(ReplicatedApply::RejectedFuture);
378        }
379        let vkey = Self::state_version_key(table_name, &key);
380        if !self.state_version_is_newer(&vkey, created_at)? {
381            return Ok(ReplicatedApply::IgnoredStale);
382        }
383        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
384        // Tombstone and mark advance in one atomic transaction; see `apply_replicated_record`.
385        let ts = created_at.to_be_bytes();
386        backend.write_atomic(&[
387            AtomicOp {
388                table: table_name,
389                key: &key,
390                value: None,
391            },
392            AtomicOp {
393                table: STATE_VERSIONS_TABLE,
394                key: &vkey,
395                value: Some(&ts),
396            },
397        ])?;
398        Ok(ReplicatedApply::Applied)
399    }
400
401    /// The rollback-guard high-water-mark key for a replicated record: the backend table name joined to
402    /// the DECODED record key bytes (not the hex string), so it can never diverge from the storage row
403    /// key for a non-canonically-encoded id. Table names are a fixed allowlist with no `:`, so the join
404    /// is unambiguous.
405    fn state_version_key(table_name: &str, key: &[u8]) -> Vec<u8> {
406        let mut vkey = Vec::with_capacity(table_name.len() + 1 + key.len());
407        vkey.extend_from_slice(table_name.as_bytes());
408        vkey.push(b':');
409        vkey.extend_from_slice(key);
410        vkey
411    }
412
413    /// keep-state rollback guard (read-only): `true` if `created_at` is strictly newer than the highest
414    /// previously applied for this d-tag, `false` if it is stale or a replay and must be ignored.
415    /// `created_at` lives in the SIGNED event, so a malicious relay cannot forge a newer one.
416    fn state_version_is_newer(&self, vkey: &[u8], created_at: u64) -> Result<bool> {
417        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
418        // Lazily ensure the table exists so a vault created before this guard migrates transparently.
419        backend.create_table(STATE_VERSIONS_TABLE)?;
420        if let Some(prev) = backend.get(STATE_VERSIONS_TABLE, vkey)? {
421            let prev_ts = u64::from_be_bytes(prev.as_slice().try_into().map_err(|_| {
422                KeepError::Other("corrupt keep-state version high-water-mark".to_string())
423            })?);
424            if created_at <= prev_ts {
425                return Ok(false);
426            }
427        }
428        Ok(true)
429    }
430
431    /// The persisted keep-state high-water-mark for a single replicated record's d-tag, or `None` if it
432    /// has never been applied. A promoted standby seeds its publisher's monotonic floor PER RECORD from
433    /// this (not from a global maximum), so a quiet record is not future-dated to the newest record's
434    /// timestamp. Uses the same key derivation as the consumer's guard, so it reads exactly the mark that
435    /// guard wrote. A corrupt (non-8-byte) entry propagates a decode error.
436    pub fn state_version(&self, table: &str, record_id: &str) -> Result<Option<u64>> {
437        let (table_name, key) = Self::replicated_key(table, record_id)?;
438        let vkey = Self::state_version_key(table_name, &key);
439        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
440        // The read path cannot create the table (redb read txns cannot), so ensure it exists first.
441        backend.create_table(STATE_VERSIONS_TABLE)?;
442        match backend.get(STATE_VERSIONS_TABLE, &vkey)? {
443            Some(v) => Ok(Some(u64::from_be_bytes(v.as_slice().try_into().map_err(
444                |_| KeepError::Other("corrupt keep-state version high-water-mark".to_string()),
445            )?))),
446            None => Ok(None),
447        }
448    }
449
450    /// Resolve a replicated `(table, record_id)` to its backend table and raw key: maps the logical
451    /// table name and hex-decodes the id. Descriptor keys are fixed 36-byte `group||version`, and the
452    /// listing/lookup path fails closed on any other length, so a malformed descriptor key would poison
453    /// `list_descriptors` for the whole vault -- reject it here at the trust boundary.
454    fn replicated_key(table: &str, record_id: &str) -> Result<(&'static str, Vec<u8>)> {
455        let table_name = Self::replicated_table(table)?;
456        let key = hex::decode(record_id)
457            .map_err(|e| KeepError::Other(format!("replicated record id not hex: {e}")))?;
458        if table_name == DESCRIPTORS_TABLE && key.len() != 36 {
459            return Err(KeepError::Other(format!(
460                "replicated descriptor key has length {} (expected 36)",
461                key.len()
462            )));
463        }
464        Ok((table_name, key))
465    }
466
467    /// Map a replicated logical table name (as it appears in the event `d`-tag) to its backend table.
468    fn replicated_table(table: &str) -> Result<&'static str> {
469        match table {
470            "keys" => Ok(KEYS_TABLE),
471            "descriptors" => Ok(DESCRIPTORS_TABLE),
472            "relay_configs" => Ok(RELAY_CONFIGS_TABLE),
473            other => Err(KeepError::Other(format!("table {other} is not replicable"))),
474        }
475    }
476
477    /// Snapshot every replicable record currently in storage as `(logical table, hex record id, at-rest
478    /// encrypted bytes)` -- the same shape the [`StatePublisher`] hook emits for a live write. The
479    /// keep-state publisher replays this once at startup so records written BEFORE replication was wired
480    /// (which the write-time hook never observed) reach a fresh standby instead of being stranded.
481    ///
482    /// Reads the raw stored ciphertext (`hex(backend key)` is the record id, the stored value is the
483    /// encrypted blob), so it matches the hook byte-for-byte and needs neither decryption nor the data
484    /// key. The three logical tables mirror [`replicated_table`].
485    pub fn snapshot_replicable_records(&self) -> Result<Vec<(&'static str, String, Vec<u8>)>> {
486        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
487        let mut out = Vec::new();
488        for table in ["keys", "descriptors", "relay_configs"] {
489            let backend_table = Self::replicated_table(table)?;
490            for (key, encrypted) in backend.list(backend_table)? {
491                out.push((table, hex::encode(key), encrypted));
492            }
493        }
494        Ok(out)
495    }
496    /// Create new storage with the given password.
497    pub fn create(path: &Path, password: &str, params: Argon2Params) -> Result<Self> {
498        create_storage_dir(path)?;
499        let db_path = path.join("keep.db");
500        let backend = RedbBackend::create(&db_path)?;
501        #[cfg(unix)]
502        let _ = chmod_secure(&db_path);
503        Self::create_inner(path, password, params, Box::new(backend), None)
504    }
505
506    /// Create new storage whose data key is the caller-provided `data_key` rather than a fresh random
507    /// one, so every node in a cluster shares one vault key (keep-state replication).
508    pub fn create_with_shared_data_key(
509        path: &Path,
510        password: &str,
511        params: Argon2Params,
512        data_key: Zeroizing<[u8; crypto::KEY_SIZE]>,
513    ) -> Result<Self> {
514        create_storage_dir(path)?;
515        let db_path = path.join("keep.db");
516        let backend = RedbBackend::create(&db_path)?;
517        #[cfg(unix)]
518        let _ = chmod_secure(&db_path);
519        Self::create_inner(path, password, params, Box::new(backend), Some(data_key))
520    }
521
522    /// Create new storage with a custom backend.
523    pub fn create_with_backend(
524        path: &Path,
525        password: &str,
526        params: Argon2Params,
527        backend: Box<dyn StorageBackend>,
528    ) -> Result<Self> {
529        create_storage_dir(path)?;
530        Self::create_inner(path, password, params, backend, None)
531    }
532
533    fn create_inner(
534        path: &Path,
535        password: &str,
536        params: Argon2Params,
537        backend: Box<dyn StorageBackend>,
538        shared_data_key: Option<Zeroizing<[u8; crypto::KEY_SIZE]>>,
539    ) -> Result<Self> {
540        validate_new_password(password)?;
541
542        let mut header = Header::new(params)?;
543        // The data key encrypts every record and is normally random per vault. A cluster can instead
544        // seed the SAME data key on every node (keep-state replication), so a standby decrypts records
545        // the active shipped: each node still wraps it under its OWN password+salt in its own header.
546        // `from_slice` stages the seed in its own zeroizing buffer (and `SecretKey::new` wipes its
547        // by-value copy), so no un-zeroized bare `[u8; 32]` of the raw key outlives this call.
548        let data_key = match shared_data_key {
549            Some(k) => SecretKey::from_slice(k.as_slice())?,
550            None => SecretKey::generate()?,
551        };
552        let master_key = crypto::derive_key(password.as_bytes(), &header.salt, params)?;
553        let header_key = crypto::derive_subkey(&master_key, b"keep-header-key")?;
554
555        let data_key_bytes = data_key.decrypt()?;
556        let encrypted = crypto::encrypt(&*data_key_bytes, &header_key)?;
557        header.nonce.copy_from_slice(&encrypted.nonce);
558        header
559            .encrypted_data_key
560            .copy_from_slice(&encrypted.ciphertext);
561
562        write_vault_file_secure(&path.join("keep.hdr"), &header.to_bytes())?;
563
564        backend.create_table(KEYS_TABLE)?;
565        backend.create_table(SHARES_TABLE)?;
566        backend.create_table(DESCRIPTORS_TABLE)?;
567        backend.create_table(RELAY_CONFIGS_TABLE)?;
568        backend.create_table(CONFIG_TABLE)?;
569        backend.create_table(HEALTH_STATUS_TABLE)?;
570        backend.create_table(SECRETS_TABLE)?;
571        backend.create_table(SECRET_SEALS_TABLE)?;
572        backend.create_table(STATE_VERSIONS_TABLE)?;
573
574        Ok(Self {
575            path: path.to_path_buf(),
576            header,
577            data_key: Some(data_key),
578            backend: Some(backend),
579            descriptor_lock: std::sync::Mutex::new(()),
580            state_publisher: std::sync::RwLock::new(None),
581        })
582    }
583
584    /// Open existing storage.
585    pub fn open(path: &Path) -> Result<Self> {
586        if !path.exists() {
587            return Err(KeepError::NotFound(path.display().to_string()));
588        }
589
590        // Reconcile any leftover rotation artifacts (`.hdr.tmp`, `.hdr.backup`,
591        // `.db.backup`) before reading the header. Handles the mid-rotation
592        // kill gap surfaced by #565's tests: without this, a crash inside
593        // `reencrypt_database` for `rotate_data_key` leaves `keep.db` with
594        // rows partially rewritten under the new DEK while `keep.hdr` still
595        // pins the old DEK, and every list post-open fails. See #662.
596        crate::rotation::recover_rotation_artifacts(path);
597
598        let header_path = path.join("keep.hdr");
599        let header_bytes = fs::read(&header_path)?;
600
601        if header_bytes.len() != HEADER_SIZE {
602            return Err(StorageError::invalid_format("invalid header size").into());
603        }
604
605        let mut bytes = [0u8; HEADER_SIZE];
606        bytes.copy_from_slice(&header_bytes);
607        let header = Header::from_bytes(&bytes)?;
608
609        Ok(Self {
610            path: path.to_path_buf(),
611            header,
612            data_key: None,
613            backend: None,
614            descriptor_lock: std::sync::Mutex::new(()),
615            state_publisher: std::sync::RwLock::new(None),
616        })
617    }
618
619    /// Unlock with the given password.
620    pub fn unlock(&mut self, password: &str) -> Result<()> {
621        if self.data_key.is_some() {
622            return Ok(());
623        }
624
625        self.unlock_inner(password)?;
626
627        let backend = RedbBackend::open(&self.path.join("keep.db"))?;
628        self.backend = Some(Box::new(backend));
629        Ok(())
630    }
631
632    /// Unlock with the given password using a custom backend.
633    pub fn unlock_with_backend(
634        &mut self,
635        password: &str,
636        backend: Box<dyn StorageBackend>,
637    ) -> Result<()> {
638        if self.data_key.is_some() {
639            return Ok(());
640        }
641
642        self.unlock_inner(password)?;
643        self.backend = Some(backend);
644        Ok(())
645    }
646
647    /// Verify a password without changing the unlock state.
648    pub fn verify_password(&self, password: &str) -> Result<()> {
649        validate_password_max_len(password)?;
650
651        let hmac_key = rate_limit::derive_hmac_key(&self.header.salt);
652        if let Err(remaining) = rate_limit::check_rate_limit(&self.path, &hmac_key) {
653            return Err(KeepError::RateLimited(remaining.as_secs().max(1)));
654        }
655
656        let master_key = crypto::derive_key(
657            password.as_bytes(),
658            &self.header.salt,
659            self.header.argon2_params(),
660        )?;
661        let header_key = crypto::derive_subkey(&master_key, b"keep-header-key")?;
662        let encrypted = EncryptedData {
663            nonce: self.header.nonce,
664            ciphertext: self.header.encrypted_data_key.to_vec(),
665        };
666        match crypto::decrypt(&encrypted, &header_key) {
667            Ok(_) => {
668                rate_limit::record_success(&self.path);
669                Ok(())
670            }
671            Err(e) => {
672                if matches!(e, KeepError::DecryptionFailed) {
673                    rate_limit::record_failure(&self.path, &hmac_key);
674                }
675                Err(e)
676            }
677        }
678    }
679
680    /// Check whether `password` decrypts the vault header, WITHOUT touching the
681    /// rate limiter, the audit log, the keyring, or the unlock state. Returns
682    /// `Ok(true)` if it matches, `Ok(false)` if it is simply the wrong password,
683    /// and `Err` only if the check could not be performed (a crypto/KDF error).
684    ///
685    /// This is a read-only pre-flight primitive, NOT an unlock path. Unlike
686    /// [`Self::verify_password`] / [`Self::unlock`] it deliberately bypasses the
687    /// rate limiter: it neither consumes a real-unlock attempt (so a pre-flight
688    /// check cannot self-inflict a lockout) nor is defeated by an active backoff
689    /// (so it cannot be silently skipped when the vault is rate-limited). Because
690    /// it does not rate-limit, callers MUST keep it on a local, operator-driven
691    /// path (it needs the vault file already, same as an offline attacker) and
692    /// MUST NOT expose it as a remote or automated unlock oracle.
693    pub(crate) fn password_matches(&self, password: &str) -> Result<bool> {
694        validate_password_max_len(password)?;
695        let master_key = crypto::derive_key(
696            password.as_bytes(),
697            &self.header.salt,
698            self.header.argon2_params(),
699        )?;
700        let header_key = crypto::derive_subkey(&master_key, b"keep-header-key")?;
701        let encrypted = EncryptedData {
702            nonce: self.header.nonce,
703            ciphertext: self.header.encrypted_data_key.to_vec(),
704        };
705        match crypto::decrypt(&encrypted, &header_key) {
706            Ok(_) => Ok(true),
707            Err(KeepError::DecryptionFailed) => Ok(false),
708            Err(e) => Err(e),
709        }
710    }
711
712    fn unlock_inner(&mut self, password: &str) -> Result<()> {
713        validate_password_max_len(password)?;
714
715        let hmac_key = rate_limit::derive_hmac_key(&self.header.salt);
716        if let Err(remaining) = rate_limit::check_rate_limit(&self.path, &hmac_key) {
717            return Err(KeepError::RateLimited(remaining.as_secs().max(1)));
718        }
719
720        debug!("deriving master key");
721        let master_key = crypto::derive_key(
722            password.as_bytes(),
723            &self.header.salt,
724            self.header.argon2_params(),
725        )?;
726
727        let header_key = crypto::derive_subkey(&master_key, b"keep-header-key")?;
728
729        let encrypted = EncryptedData {
730            nonce: self.header.nonce,
731            ciphertext: self.header.encrypted_data_key.to_vec(),
732        };
733
734        debug!("decrypting data key");
735        let decrypted = match crypto::decrypt(&encrypted, &header_key) {
736            Ok(d) => d,
737            Err(e) => {
738                if matches!(e, KeepError::DecryptionFailed) {
739                    rate_limit::record_failure(&self.path, &hmac_key);
740                }
741                return Err(e);
742            }
743        };
744        let decrypted_bytes = decrypted.as_slice()?;
745        self.data_key = Some(SecretKey::from_slice(&decrypted_bytes)?);
746
747        rate_limit::record_success(&self.path);
748        debug!("storage unlocked");
749        Ok(())
750    }
751
752    /// Lock and clear keys from memory.
753    pub fn lock(&mut self) {
754        self.data_key = None;
755        self.backend = None;
756    }
757
758    /// Drain rate-limit trip events queued by failed unlock attempts on this
759    /// vault. The caller is expected to be holding an open audit log so the
760    /// trips can be flushed as `RateLimitTripped` entries.
761    pub(crate) fn drain_pending_trips(&self) -> Vec<crate::rate_limit::PendingTrip> {
762        let hmac_key = crate::rate_limit::derive_hmac_key(&self.header.salt);
763        crate::rate_limit::drain_pending_trips(&self.path, &hmac_key)
764    }
765
766    /// Returns true if unlocked.
767    pub fn is_unlocked(&self) -> bool {
768        self.data_key.is_some()
769    }
770
771    /// The vault's Argon2id parameters (from the header, readable before unlock).
772    /// These are non-secret; callers use them to reproduce an unlock's KDF cost
773    /// (e.g. a timing equalizer) without unlocking the vault.
774    pub fn argon2_params(&self) -> Argon2Params {
775        self.header.argon2_params()
776    }
777
778    /// The data encryption key, if unlocked.
779    pub fn data_key(&self) -> Option<&SecretKey> {
780        self.data_key.as_ref()
781    }
782
783    /// Store a key record.
784    pub fn store_key(&self, record: &KeyRecord) -> Result<()> {
785        debug!(name = %record.name, "storing key");
786        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
787        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
788
789        let serialized = bincode::serialize(record)?;
790        let encrypted = crypto::encrypt(&serialized, data_key)?;
791        let encrypted_bytes = encrypted.to_bytes();
792
793        backend.put(KEYS_TABLE, &record.id, &encrypted_bytes)?;
794        self.notify_record("keys", &hex::encode(record.id), &encrypted_bytes);
795        Ok(())
796    }
797
798    /// Load a key record.
799    pub fn load_key(&self, id: &[u8; 32]) -> Result<KeyRecord> {
800        trace!(id = %hex::encode(id), "loading key");
801        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
802        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
803
804        let encrypted_bytes = backend
805            .get(KEYS_TABLE, id)?
806            .ok_or_else(|| KeepError::KeyNotFound(hex::encode(id)))?;
807
808        let encrypted = EncryptedData::from_bytes(&encrypted_bytes)?;
809        let decrypted = crypto::decrypt(&encrypted, data_key)?;
810
811        let decrypted_bytes = decrypted.as_slice()?;
812        Ok(bincode_options().deserialize(&decrypted_bytes)?)
813    }
814
815    /// List all stored key records.
816    pub fn list_keys(&self) -> Result<Vec<KeyRecord>> {
817        trace!("listing keys");
818        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
819        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
820
821        let entries = backend.list(KEYS_TABLE)?;
822        let mut records = Vec::new();
823
824        for (_, encrypted_bytes) in entries {
825            let encrypted = EncryptedData::from_bytes(&encrypted_bytes)?;
826            let decrypted = crypto::decrypt(&encrypted, data_key)?;
827            let decrypted_bytes = decrypted.as_slice()?;
828            records.push(bincode_options().deserialize(&decrypted_bytes)?);
829        }
830
831        Ok(records)
832    }
833
834    /// Delete a key record.
835    pub fn delete_key(&self, id: &[u8; 32]) -> Result<()> {
836        debug!(id = %hex::encode(id), "deleting key");
837        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
838        if backend.delete(KEYS_TABLE, id)? {
839            self.notify_delete("keys", &hex::encode(id));
840            Ok(())
841        } else {
842            Err(KeepError::KeyNotFound(hex::encode(id)))
843        }
844    }
845
846    /// Store (insert or overwrite) an arbitrary-secret record, keyed by its
847    /// random `id`. The whole record -- name, kind, AND plaintext value -- is
848    /// bincode-serialized then encrypted under the vault data key, so nothing is
849    /// on disk in the clear and the entry title is protected too. Unlike
850    /// `store_key` this never notifies the replication sink: secrets are not
851    /// replicable (see [`Self::replicated_table`]).
852    pub fn store_secret(&self, record: &SecretRecord) -> Result<()> {
853        debug!(id = %hex::encode(record.id), "storing secret");
854        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
855        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
856
857        let serialized = Zeroizing::new(bincode::serialize(record)?);
858        let encrypted = crypto::encrypt(&serialized, data_key)?;
859        let encrypted_bytes = encrypted.to_bytes();
860        // A seal row is what marks a secret's `value` as DEK-ciphertext. Overwriting
861        // an id that was previously threshold-sealed via this plain path must clear
862        // that stale seal atomically, else the new plaintext `value` would be misread
863        // as ciphertext and `reveal_sealed_secret` would fail. Deleting an absent
864        // seal row (the common case) is a no-op.
865        backend.write_atomic(&[
866            AtomicOp {
867                table: SECRETS_TABLE,
868                key: &record.id,
869                value: Some(&encrypted_bytes),
870            },
871            AtomicOp {
872                table: SECRET_SEALS_TABLE,
873                key: &record.id,
874                value: None,
875            },
876        ])?;
877        Ok(())
878    }
879
880    /// Load a secret record by its 32-byte `id`.
881    pub fn load_secret(&self, id: &[u8; 32]) -> Result<SecretRecord> {
882        trace!(id = %hex::encode(id), "loading secret");
883        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
884        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
885
886        let encrypted_bytes = backend
887            .get(SECRETS_TABLE, id)?
888            .ok_or_else(|| KeepError::NotFound(hex::encode(id)))?;
889        let encrypted = EncryptedData::from_bytes(&encrypted_bytes)?;
890        let decrypted = crypto::decrypt(&encrypted, data_key)?;
891        let decrypted_bytes = decrypted.as_slice()?;
892        Ok(bincode_options().deserialize(&decrypted_bytes)?)
893    }
894
895    /// List all stored secret records. O(n) full decrypt, matching `list_keys`;
896    /// fine for the modest counts a first-pass secret store holds.
897    pub fn list_secrets(&self) -> Result<Vec<SecretRecord>> {
898        trace!("listing secrets");
899        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
900        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
901
902        let entries = backend.list(SECRETS_TABLE)?;
903        let mut records = Vec::with_capacity(entries.len());
904        for (_, encrypted_bytes) in entries {
905            let encrypted = EncryptedData::from_bytes(&encrypted_bytes)?;
906            let decrypted = crypto::decrypt(&encrypted, data_key)?;
907            let decrypted_bytes = decrypted.as_slice()?;
908            records.push(bincode_options().deserialize(&decrypted_bytes)?);
909        }
910        Ok(records)
911    }
912
913    /// Store a secret whose VALUE is sealed behind a t-of-n OPRF quorum. The
914    /// record's `value` must already be the DEK-ciphertext produced by
915    /// [`crate::secret::seal_value`]; `seal` is its matching wrapped DEK + OPRF
916    /// params. The record (name/kind/DEK-ciphertext) and the seal are each
917    /// encrypted under the vault data key and written in ONE atomic transaction,
918    /// so a crash can never leave a sealed value without its wrapped DEK (which
919    /// would make the value permanently undecryptable). Like `store_secret`, it
920    /// never notifies the replication sink: secrets are not replicable.
921    pub fn store_sealed_secret(&self, record: &SecretRecord, seal: &ThresholdSeal) -> Result<()> {
922        debug!(id = %hex::encode(record.id), "storing sealed secret");
923        // The seal's OPRF label MUST be the record's own id: it is the quorum's
924        // domain-separation input and is bound as AAD. Rejecting a mismatch at this
925        // boundary (which also guards backup restore) prevents an identity-confused
926        // or unrecoverable sealed record from ever being persisted.
927        if seal.oprf_id != hex::encode(record.id) {
928            return Err(KeepError::invalid_input(
929                "threshold seal OPRF id does not match secret id",
930            ));
931        }
932        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
933        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
934
935        let rec_serialized = Zeroizing::new(bincode::serialize(record)?);
936        let rec_encrypted = crypto::encrypt(&rec_serialized, data_key)?.to_bytes();
937        let seal_serialized = Zeroizing::new(bincode::serialize(seal)?);
938        let seal_encrypted = crypto::encrypt(&seal_serialized, data_key)?.to_bytes();
939
940        backend.write_atomic(&[
941            AtomicOp {
942                table: SECRETS_TABLE,
943                key: &record.id,
944                value: Some(&rec_encrypted),
945            },
946            AtomicOp {
947                table: SECRET_SEALS_TABLE,
948                key: &record.id,
949                value: Some(&seal_encrypted),
950            },
951        ])?;
952        Ok(())
953    }
954
955    /// Load the [`ThresholdSeal`] for a secret `id`, or `None` when the secret is
956    /// not threshold-sealed (an ordinary plaintext-value secret). The presence of
957    /// a seal is what marks a secret as threshold-gated; its `value` is then the
958    /// DEK-ciphertext rather than plaintext.
959    pub fn load_secret_seal(&self, id: &[u8; 32]) -> Result<Option<ThresholdSeal>> {
960        trace!(id = %hex::encode(id), "loading secret seal");
961        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
962        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
963
964        let Some(encrypted_bytes) = backend.get(SECRET_SEALS_TABLE, id)? else {
965            return Ok(None);
966        };
967        let encrypted = EncryptedData::from_bytes(&encrypted_bytes)?;
968        let decrypted = crypto::decrypt(&encrypted, data_key)?;
969        let decrypted_bytes = decrypted.as_slice()?;
970        Ok(Some(bincode_options().deserialize(&decrypted_bytes)?))
971    }
972
973    /// Delete a secret record by `id`, along with its threshold seal if it has
974    /// one, in a single atomic transaction. Errors if no such secret exists.
975    pub fn delete_secret(&self, id: &[u8; 32]) -> Result<()> {
976        debug!(id = %hex::encode(id), "deleting secret");
977        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
978        // The secret row must exist; the seal is optional, so gate on the record.
979        if backend.get(SECRETS_TABLE, id)?.is_none() {
980            return Err(KeepError::NotFound(hex::encode(id)));
981        }
982        backend.write_atomic(&[
983            AtomicOp {
984                table: SECRETS_TABLE,
985                key: id,
986                value: None,
987            },
988            AtomicOp {
989                table: SECRET_SEALS_TABLE,
990                key: id,
991                value: None,
992            },
993        ])?;
994        Ok(())
995    }
996
997    /// The storage directory path.
998    pub fn path(&self) -> &Path {
999        &self.path
1000    }
1001
1002    /// Get the current schema version.
1003    pub fn schema_version(&self) -> Result<u32> {
1004        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1005        backend.schema_version()
1006    }
1007
1008    /// Check if migrations are needed.
1009    pub fn needs_migration(&self) -> Result<bool> {
1010        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1011        backend.needs_migration()
1012    }
1013
1014    /// Run pending migrations.
1015    pub fn run_migrations(&self) -> Result<crate::migration::MigrationResult> {
1016        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1017        backend.run_migrations()
1018    }
1019
1020    /// Store a FROST share.
1021    pub fn store_share(&self, share: &StoredShare) -> Result<()> {
1022        debug!(name = %share.metadata.name, "storing FROST share");
1023        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
1024        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1025
1026        let serialized = serialize_stored_share(share)?;
1027        let encrypted = crypto::encrypt(&serialized, data_key)?;
1028        let encrypted_bytes = encrypted.to_bytes();
1029
1030        let id = share_id(&share.metadata.group_pubkey, share.metadata.identifier);
1031        backend.put(SHARES_TABLE, &id, &encrypted_bytes)?;
1032
1033        Ok(())
1034    }
1035
1036    /// Store multiple FROST shares atomically.
1037    pub fn store_shares_atomic(&self, shares: &[StoredShare]) -> Result<()> {
1038        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
1039        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1040
1041        let mut entries_data: Vec<(Vec<u8>, Vec<u8>)> = Vec::with_capacity(shares.len());
1042        for share in shares {
1043            let serialized = serialize_stored_share(share)?;
1044            let encrypted = crypto::encrypt(&serialized, data_key)?;
1045            let id = share_id(&share.metadata.group_pubkey, share.metadata.identifier);
1046            entries_data.push((id.to_vec(), encrypted.to_bytes()));
1047        }
1048
1049        let entries_refs: Vec<(&[u8], &[u8])> = entries_data
1050            .iter()
1051            .map(|(k, v)| (k.as_slice(), v.as_slice()))
1052            .collect();
1053
1054        backend.put_batch(SHARES_TABLE, &entries_refs)
1055    }
1056
1057    /// List all stored FROST shares.
1058    pub fn list_shares(&self) -> Result<Vec<StoredShare>> {
1059        trace!("listing FROST shares");
1060        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
1061        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1062
1063        let entries = backend.list(SHARES_TABLE)?;
1064        let mut shares = Vec::new();
1065
1066        for (_, encrypted_bytes) in entries {
1067            let encrypted = EncryptedData::from_bytes(&encrypted_bytes)?;
1068            let decrypted = crypto::decrypt(&encrypted, data_key)?;
1069            let decrypted_bytes = decrypted.as_slice()?;
1070            shares.push(deserialize_stored_share(&decrypted_bytes)?);
1071        }
1072
1073        Ok(shares)
1074    }
1075
1076    /// Delete a FROST share.
1077    pub fn delete_share(&self, group_pubkey: &[u8; 32], identifier: u16) -> Result<()> {
1078        debug!(id = identifier, "deleting FROST share");
1079        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1080        let id = share_id(group_pubkey, identifier);
1081        if backend.delete(SHARES_TABLE, &id)? {
1082            Ok(())
1083        } else {
1084            Err(KeepError::KeyNotFound(format!(
1085                "share {identifier} not found"
1086            )))
1087        }
1088    }
1089
1090    /// Store a wallet descriptor. The storage key is
1091    /// `group_pubkey || version_be(version)` so multiple versions for the
1092    /// same group can coexist; replacing an existing version is a no-op
1093    /// upsert against the same key.
1094    pub fn store_descriptor(&self, descriptor: &WalletDescriptor) -> Result<()> {
1095        debug!(
1096            group = %hex::encode(descriptor.group_pubkey),
1097            version = descriptor.version,
1098            "storing wallet descriptor"
1099        );
1100        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
1101        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1102
1103        let serialized = Zeroizing::new(
1104            serde_json::to_vec(descriptor)
1105                .map_err(|e| KeepError::Other(format!("json serialization failed: {e}")))?,
1106        );
1107        let encrypted = crypto::encrypt(&serialized, data_key)?;
1108        let encrypted_bytes = encrypted.to_bytes();
1109
1110        let key = descriptor_storage_key(&descriptor.group_pubkey, descriptor.version);
1111        backend.put(DESCRIPTORS_TABLE, &key, &encrypted_bytes)?;
1112        self.notify_record("descriptors", &hex::encode(key), &encrypted_bytes);
1113        Ok(())
1114    }
1115
1116    /// Get the latest-version wallet descriptor for a group public key.
1117    /// Returns `None` if no descriptor is stored for the group.
1118    ///
1119    /// Only one row is decrypted (the highest-versioned one) regardless of
1120    /// how many versions exist for the group. The latest version is
1121    /// determined by the trailing 4 big-endian bytes of the key, so the
1122    /// payload only needs to be touched once we know which row to read.
1123    pub fn get_descriptor(&self, group_pubkey: &[u8; 32]) -> Result<Option<WalletDescriptor>> {
1124        trace!(group = %hex::encode(group_pubkey), "loading latest wallet descriptor");
1125        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1126
1127        let keys = backend.list_keys_with_prefix(DESCRIPTORS_TABLE, group_pubkey.as_slice())?;
1128        let mut latest_version: Option<u32> = None;
1129        for k in &keys {
1130            let version = require_versioned_descriptor_key(k)?;
1131            if latest_version.is_none_or(|cur| version > cur) {
1132                latest_version = Some(version);
1133            }
1134        }
1135        match latest_version {
1136            Some(v) => self.get_descriptor_version(group_pubkey, v),
1137            None => Ok(None),
1138        }
1139    }
1140
1141    /// Get a specific version of the wallet descriptor for a group.
1142    pub fn get_descriptor_version(
1143        &self,
1144        group_pubkey: &[u8; 32],
1145        version: u32,
1146    ) -> Result<Option<WalletDescriptor>> {
1147        trace!(
1148            group = %hex::encode(group_pubkey),
1149            version,
1150            "loading wallet descriptor version"
1151        );
1152        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
1153        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1154
1155        let key = descriptor_storage_key(group_pubkey, version);
1156        let Some(encrypted_bytes) = backend.get(DESCRIPTORS_TABLE, &key)? else {
1157            return Ok(None);
1158        };
1159
1160        let encrypted = EncryptedData::from_bytes(&encrypted_bytes)?;
1161        let decrypted = crypto::decrypt(&encrypted, data_key)?;
1162        let decrypted_bytes = decrypted.as_slice()?;
1163        let descriptor: WalletDescriptor = serde_json::from_slice(&decrypted_bytes)
1164            .map_err(|e| KeepError::Other(format!("json deserialization failed: {e}")))?;
1165        Ok(Some(descriptor))
1166    }
1167
1168    /// List the latest-version wallet descriptor for every group. Older
1169    /// versions are not returned; use [`list_all_descriptor_versions`] when
1170    /// every row is required (e.g. backup, rotation).
1171    ///
1172    /// [`list_all_descriptor_versions`]: Self::list_all_descriptor_versions
1173    pub fn list_descriptors(&self) -> Result<Vec<WalletDescriptor>> {
1174        trace!("listing latest wallet descriptors (one per group)");
1175        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1176
1177        let keys = backend.list_keys_with_prefix(DESCRIPTORS_TABLE, &[])?;
1178        // Pick the highest-versioned key per group from the trailing 4 BE
1179        // bytes of each row key, then decrypt only those rows.
1180        let mut latest: std::collections::HashMap<[u8; 32], u32> = std::collections::HashMap::new();
1181        for key in &keys {
1182            // Mirror `get_descriptor`: fail closed on unexpected key lengths
1183            // rather than silently hiding a group whose row survived an
1184            // incomplete v4->v5 migration.
1185            let version = require_versioned_descriptor_key(key)?;
1186            let mut group = [0u8; 32];
1187            group.copy_from_slice(&key[..32]);
1188            latest
1189                .entry(group)
1190                .and_modify(|cur| {
1191                    if version > *cur {
1192                        *cur = version;
1193                    }
1194                })
1195                .or_insert(version);
1196        }
1197        let mut descriptors = Vec::with_capacity(latest.len());
1198        for (group, version) in latest {
1199            if let Some(desc) = self.get_descriptor_version(&group, version)? {
1200                descriptors.push(desc);
1201            }
1202        }
1203        Ok(descriptors)
1204    }
1205
1206    /// List every stored wallet descriptor row across all groups and
1207    /// versions. Decrypts every row; prefer [`list_descriptors`] when only the
1208    /// latest version per group is needed.
1209    ///
1210    /// [`list_descriptors`]: Self::list_descriptors
1211    pub fn list_all_descriptor_versions(&self) -> Result<Vec<WalletDescriptor>> {
1212        trace!("listing all wallet descriptor versions");
1213        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
1214        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1215
1216        let entries = backend.list(DESCRIPTORS_TABLE)?;
1217        let mut descriptors = Vec::new();
1218
1219        for (_, encrypted_bytes) in entries {
1220            let encrypted = EncryptedData::from_bytes(&encrypted_bytes)?;
1221            let decrypted = crypto::decrypt(&encrypted, data_key)?;
1222            let decrypted_bytes = decrypted.as_slice()?;
1223            let descriptor: WalletDescriptor = serde_json::from_slice(&decrypted_bytes)
1224                .map_err(|e| KeepError::Other(format!("json deserialization failed: {e}")))?;
1225            descriptors.push(descriptor);
1226        }
1227
1228        Ok(descriptors)
1229    }
1230
1231    /// List all stored descriptor versions for a single group public key,
1232    /// sorted ascending by version. Decrypts only rows whose key prefix
1233    /// matches the group, avoiding a full-table scan.
1234    pub fn list_descriptors_for_group(
1235        &self,
1236        group_pubkey: &[u8; 32],
1237    ) -> Result<Vec<WalletDescriptor>> {
1238        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1239
1240        let keys = backend.list_keys_with_prefix(DESCRIPTORS_TABLE, group_pubkey.as_slice())?;
1241        let mut versions: Vec<u32> = keys
1242            .iter()
1243            .filter_map(|k| parse_versioned_descriptor_key(k, group_pubkey, "list"))
1244            .collect();
1245        versions.sort_unstable();
1246
1247        let mut out = Vec::with_capacity(versions.len());
1248        for v in versions {
1249            if let Some(d) = self.get_descriptor_version(group_pubkey, v)? {
1250                out.push(d);
1251            }
1252        }
1253        Ok(out)
1254    }
1255
1256    /// Atomically insert or update a device registration on the latest
1257    /// descriptor for the given group. Serialized under `descriptor_lock` so
1258    /// concurrent callers cannot lose each other's updates across the
1259    /// read-modify-write.
1260    ///
1261    /// Only the latest version row is mutated: registrations on superseded
1262    /// descriptor versions are not reachable through this path. This matches
1263    /// the protocol's "latest descriptor is authoritative" invariant. No
1264    /// other path iterates `list_descriptors` and re-stores entries, so older
1265    /// versions remain frozen at the registrations they captured at the time
1266    /// of the corresponding descriptor finalization.
1267    pub fn upsert_device_registration(
1268        &self,
1269        group_pubkey: &[u8; 32],
1270        registration: crate::wallet::DeviceRegistration,
1271    ) -> Result<()> {
1272        let _guard = self
1273            .descriptor_lock
1274            .lock()
1275            .map_err(|_| StorageError::database("descriptor lock poisoned"))?;
1276        let mut descriptor = self.get_descriptor(group_pubkey)?.ok_or_else(|| {
1277            KeepError::KeyNotFound(format!(
1278                "wallet descriptor for group {} not found",
1279                hex::encode(group_pubkey)
1280            ))
1281        })?;
1282        descriptor.upsert_device_registration(registration);
1283        self.store_descriptor(&descriptor)
1284    }
1285
1286    /// Delete every stored version of the wallet descriptor for a group.
1287    /// All version rows are removed via the backend's `delete_batch`; on
1288    /// backends that implement it atomically (redb does) a crash mid-delete
1289    /// cannot leave a partial set behind.
1290    pub fn delete_descriptor(&self, group_pubkey: &[u8; 32]) -> Result<()> {
1291        debug!(group = %hex::encode(group_pubkey), "deleting wallet descriptor (all versions)");
1292        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1293
1294        let keys = backend.list_keys_with_prefix(DESCRIPTORS_TABLE, group_pubkey.as_slice())?;
1295        // Delete every row under the group prefix regardless of key length:
1296        // skipping a stray legacy 32-byte row here would leave it behind
1297        // forever and make subsequent reads inconsistent. The v4->v5
1298        // migration is expected to have rewritten such rows, so the only way
1299        // we observe one is partial migration; the safest action is to drop
1300        // it along with the versioned rows.
1301        if keys.is_empty() {
1302            return Err(KeepError::KeyNotFound(format!(
1303                "wallet descriptor for group {} not found",
1304                hex::encode(group_pubkey)
1305            )));
1306        }
1307
1308        let refs: Vec<&[u8]> = keys.iter().map(|k| k.as_slice()).collect();
1309        backend.delete_batch(DESCRIPTORS_TABLE, &refs)?;
1310        for k in &keys {
1311            self.notify_delete("descriptors", &hex::encode(k));
1312        }
1313        Ok(())
1314    }
1315
1316    /// Delete a single version of a wallet descriptor for a group.
1317    pub fn delete_descriptor_version(&self, group_pubkey: &[u8; 32], version: u32) -> Result<()> {
1318        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1319        let key = descriptor_storage_key(group_pubkey, version);
1320        if backend.delete(DESCRIPTORS_TABLE, &key)? {
1321            self.notify_delete("descriptors", &hex::encode(key));
1322            Ok(())
1323        } else {
1324            Err(KeepError::KeyNotFound(format!(
1325                "wallet descriptor for group {} version {} not found",
1326                hex::encode(group_pubkey),
1327                version
1328            )))
1329        }
1330    }
1331
1332    /// Store a relay configuration.
1333    pub fn store_relay_config(&self, config: &RelayConfig) -> Result<()> {
1334        debug!(group = %hex::encode(config.group_pubkey), "storing relay config");
1335        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
1336        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1337
1338        let normalized = config.clone().normalize()?;
1339        let encrypted_bytes = relay::encode_relay_config(&normalized, data_key)?;
1340        backend.put(
1341            RELAY_CONFIGS_TABLE,
1342            &normalized.group_pubkey,
1343            &encrypted_bytes,
1344        )?;
1345        self.notify_record(
1346            "relay_configs",
1347            &hex::encode(normalized.group_pubkey),
1348            &encrypted_bytes,
1349        );
1350        Ok(())
1351    }
1352
1353    /// Get a relay configuration by group public key.
1354    pub fn get_relay_config(&self, group_pubkey: &[u8; 32]) -> Result<Option<RelayConfig>> {
1355        trace!(group = %hex::encode(group_pubkey), "loading relay config");
1356        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
1357        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1358
1359        let Some(encrypted_bytes) = backend.get(RELAY_CONFIGS_TABLE, group_pubkey)? else {
1360            return Ok(None);
1361        };
1362
1363        Ok(Some(relay::decode_relay_config(
1364            &encrypted_bytes,
1365            data_key,
1366        )?))
1367    }
1368
1369    /// List all stored relay configurations.
1370    pub fn list_relay_configs(&self) -> Result<Vec<RelayConfig>> {
1371        trace!("listing relay configs");
1372        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
1373        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1374
1375        let entries = backend.list(RELAY_CONFIGS_TABLE)?;
1376        let mut configs = Vec::new();
1377
1378        for (_, encrypted_bytes) in entries {
1379            configs.push(relay::decode_relay_config(&encrypted_bytes, data_key)?);
1380        }
1381
1382        Ok(configs)
1383    }
1384
1385    /// Delete a relay configuration.
1386    pub fn delete_relay_config(&self, group_pubkey: &[u8; 32]) -> Result<()> {
1387        debug!(group = %hex::encode(group_pubkey), "deleting relay config");
1388        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1389        if backend.delete(RELAY_CONFIGS_TABLE, group_pubkey)? {
1390            self.notify_delete("relay_configs", &hex::encode(group_pubkey));
1391            Ok(())
1392        } else {
1393            Err(KeepError::KeyNotFound(format!(
1394                "relay config for group {} not found",
1395                hex::encode(group_pubkey)
1396            )))
1397        }
1398    }
1399
1400    /// Get the kill switch state from the vault.
1401    pub fn get_kill_switch(&self) -> Result<bool> {
1402        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
1403        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1404
1405        let Some(encrypted_bytes) = backend.get(CONFIG_TABLE, b"kill_switch")? else {
1406            return Ok(false);
1407        };
1408
1409        let encrypted = EncryptedData::from_bytes(&encrypted_bytes)?;
1410        let decrypted = crypto::decrypt(&encrypted, data_key)?;
1411        let bytes = decrypted.as_slice()?;
1412        Ok(bytes.first().copied() == Some(1))
1413    }
1414
1415    /// Set the kill switch state in the vault.
1416    pub fn set_kill_switch(&self, active: bool) -> Result<()> {
1417        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
1418        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1419
1420        let value = if active { [1u8] } else { [0u8] };
1421        let encrypted = crypto::encrypt(&value, data_key)?;
1422        let encrypted_bytes = encrypted.to_bytes();
1423
1424        backend.put(CONFIG_TABLE, b"kill_switch", &encrypted_bytes)?;
1425        Ok(())
1426    }
1427
1428    /// Get the proxy configuration from the vault.
1429    pub fn get_proxy_config(&self) -> Result<ProxyConfig> {
1430        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
1431        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1432
1433        let Some(encrypted_bytes) = backend.get(CONFIG_TABLE, b"proxy_config")? else {
1434            return Ok(ProxyConfig::default());
1435        };
1436
1437        let encrypted = EncryptedData::from_bytes(&encrypted_bytes)?;
1438        let decrypted = crypto::decrypt(&encrypted, data_key)?;
1439        let decrypted_bytes = decrypted.as_slice()?;
1440        serde_json::from_slice(&decrypted_bytes)
1441            .map_err(|e| KeepError::Other(format!("json deserialization failed: {e}")))
1442    }
1443
1444    /// Set the proxy configuration in the vault.
1445    pub fn set_proxy_config(&self, config: &ProxyConfig) -> Result<()> {
1446        if config.port == 0 {
1447            return Err(KeepError::InvalidInput(
1448                "proxy port must be non-zero".into(),
1449            ));
1450        }
1451        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
1452        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1453
1454        let serialized = serde_json::to_vec(config)
1455            .map_err(|e| KeepError::Other(format!("json serialization failed: {e}")))?;
1456        let encrypted = crypto::encrypt(&serialized, data_key)?;
1457        let encrypted_bytes = encrypted.to_bytes();
1458
1459        backend.put(CONFIG_TABLE, b"proxy_config", &encrypted_bytes)?;
1460        Ok(())
1461    }
1462
1463    /// Store a key health status record.
1464    pub fn store_health_status(&self, status: &KeyHealthStatus) -> Result<()> {
1465        debug!(
1466            group = %hex::encode(status.group_pubkey),
1467            share = status.share_index,
1468            responsive = status.responsive,
1469            "storing health status"
1470        );
1471        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
1472        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1473
1474        let key = health_status_key(&status.group_pubkey, status.share_index);
1475        let serialized = serde_json::to_vec(status)
1476            .map_err(|e| KeepError::Other(format!("json serialization failed: {e}")))?;
1477        let encrypted = crypto::encrypt(&serialized, data_key)?;
1478        backend.put(HEALTH_STATUS_TABLE, key.as_bytes(), &encrypted.to_bytes())?;
1479        Ok(())
1480    }
1481
1482    /// Get a key health status record.
1483    pub fn get_health_status(
1484        &self,
1485        group_pubkey: &[u8; 32],
1486        share_index: u16,
1487    ) -> Result<Option<KeyHealthStatus>> {
1488        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
1489        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1490
1491        let key = health_status_key(group_pubkey, share_index);
1492        let Some(encrypted_bytes) = backend.get(HEALTH_STATUS_TABLE, key.as_bytes())? else {
1493            return Ok(None);
1494        };
1495
1496        let encrypted = EncryptedData::from_bytes(&encrypted_bytes)?;
1497        let decrypted = crypto::decrypt(&encrypted, data_key)?;
1498        let decrypted_bytes = decrypted.as_slice()?;
1499        let status: KeyHealthStatus = serde_json::from_slice(&decrypted_bytes)
1500            .map_err(|e| KeepError::Other(format!("json deserialization failed: {e}")))?;
1501        Ok(Some(status))
1502    }
1503
1504    /// List all key health status records.
1505    pub fn list_health_statuses(&self) -> Result<Vec<KeyHealthStatus>> {
1506        let data_key = self.data_key.as_ref().ok_or(KeepError::Locked)?;
1507        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1508
1509        let entries = backend.list(HEALTH_STATUS_TABLE)?;
1510        let mut statuses = Vec::new();
1511
1512        for (_, encrypted_bytes) in entries {
1513            let encrypted = EncryptedData::from_bytes(&encrypted_bytes)?;
1514            let decrypted = crypto::decrypt(&encrypted, data_key)?;
1515            let decrypted_bytes = decrypted.as_slice()?;
1516            let status: KeyHealthStatus = serde_json::from_slice(&decrypted_bytes)
1517                .map_err(|e| KeepError::Other(format!("json deserialization failed: {e}")))?;
1518            statuses.push(status);
1519        }
1520
1521        Ok(statuses)
1522    }
1523
1524    /// Delete a key health status record.
1525    pub fn delete_health_status(&self, group_pubkey: &[u8; 32], share_index: u16) -> Result<()> {
1526        let backend = self.backend.as_ref().ok_or(KeepError::Locked)?;
1527        let key = health_status_key(group_pubkey, share_index);
1528        if backend.delete(HEALTH_STATUS_TABLE, key.as_bytes())? {
1529            Ok(())
1530        } else {
1531            Err(KeepError::KeyNotFound(format!(
1532                "health status for share {share_index} not found"
1533            )))
1534        }
1535    }
1536}
1537
1538fn health_status_key(group_pubkey: &[u8; 32], share_index: u16) -> String {
1539    format!("{}:{}", hex::encode(group_pubkey), share_index)
1540}
1541
1542/// Compose the storage key for a wallet descriptor row:
1543/// `group_pubkey (32) || version_be (4)`.
1544pub(crate) fn descriptor_storage_key(group_pubkey: &[u8; 32], version: u32) -> [u8; 36] {
1545    let mut key = [0u8; 36];
1546    key[..32].copy_from_slice(group_pubkey);
1547    key[32..36].copy_from_slice(&version.to_be_bytes());
1548    key
1549}
1550
1551/// Extract the version from the trailing 4 big-endian bytes of a descriptor
1552/// row key. Caller must have verified `key.len() == 36`.
1553fn descriptor_key_version(key: &[u8]) -> u32 {
1554    let mut v_bytes = [0u8; 4];
1555    v_bytes.copy_from_slice(&key[32..36]);
1556    u32::from_be_bytes(v_bytes)
1557}
1558
1559/// Strictly parse a descriptor row key, returning its version. Fails closed on
1560/// any non-36-byte key: post-migration every row is `group||version_be`, so an
1561/// unexpected length means the v4->v5 migration did not complete and the caller
1562/// must not silently miss data.
1563fn require_versioned_descriptor_key(key: &[u8]) -> Result<u32> {
1564    if key.len() != 36 {
1565        return Err(KeepError::Other(format!(
1566            "wallet_descriptors row has unexpected key length {} (expected 36); migration to v5 incomplete",
1567            key.len()
1568        )));
1569    }
1570    Ok(descriptor_key_version(key))
1571}
1572
1573/// Parse a descriptor row key produced by [`descriptor_storage_key`] and
1574/// return its version. Returns `None` for any legacy 32-byte row that
1575/// matches the group prefix; the v4->v5 migration was expected to rewrite
1576/// those, so a remaining row is logged as a warning rather than silently
1577/// dropped. `op` tags the call site (e.g. `"lookup"`, `"delete"`) so log
1578/// readers can tell which scan surfaced the leftover.
1579fn parse_versioned_descriptor_key(
1580    key: &[u8],
1581    group_pubkey: &[u8; 32],
1582    op: &'static str,
1583) -> Option<u32> {
1584    if key.len() != 36 {
1585        warn!(
1586            group = %hex::encode(group_pubkey),
1587            key_len = key.len(),
1588            op,
1589            "skipping non-versioned descriptor row under group prefix (expected migration to v5)"
1590        );
1591        return None;
1592    }
1593    Some(descriptor_key_version(key))
1594}
1595
1596/// Self-describing version prefix on the persisted `StoredShare` blob.
1597///
1598/// bincode is not self-describing, so a `#[serde(default)]` field appended to
1599/// `StoredShare` cannot be filled in from an older blob that lacks it. Rather
1600/// than guess the layout by trying multiple deserializations, new writes carry
1601/// an explicit `magic || version` prefix that unambiguously identifies the
1602/// layout. Blobs without the prefix are pre-versioning data (v0), which is
1603/// always secp256k1.
1604const SHARE_FORMAT_MAGIC: &[u8; 4] = b"KSH1";
1605const SHARE_FORMAT_V1: u8 = 1;
1606
1607/// Serialize a `StoredShare` with the explicit version prefix.
1608pub(crate) fn serialize_stored_share(share: &StoredShare) -> Result<Vec<u8>> {
1609    let body = bincode_options().serialize(share)?;
1610    let mut out = Vec::with_capacity(SHARE_FORMAT_MAGIC.len() + 1 + body.len());
1611    out.extend_from_slice(SHARE_FORMAT_MAGIC);
1612    out.push(SHARE_FORMAT_V1);
1613    out.extend_from_slice(&body);
1614    Ok(out)
1615}
1616
1617/// Deserialize a `StoredShare`, dispatching on the explicit version prefix.
1618///
1619/// A blob carrying the `KSH1` magic is parsed strictly as the current
1620/// `StoredShare` layout (ciphersuite tag included). A blob without the magic is
1621/// pre-versioning data: it is parsed as the legacy three-field layout and the
1622/// tag defaults to `Secp256k1Tr`. This is parse-don't-guess: the prefix names
1623/// the layout instead of inferring it from a failed deserialization. The
1624/// ciphersuite tag stays bound in the AEAD AAD, so a misclassification (e.g. an
1625/// adversarially prefixed legacy blob) still fails closed at the MAC rather
1626/// than yielding a wrong key.
1627pub(crate) fn deserialize_stored_share(bytes: &[u8]) -> Result<StoredShare> {
1628    if let Some([SHARE_FORMAT_V1, body @ ..]) = bytes.strip_prefix(SHARE_FORMAT_MAGIC.as_slice()) {
1629        return Ok(bincode_options().deserialize::<StoredShare>(body)?);
1630    }
1631
1632    #[derive(serde::Deserialize)]
1633    struct LegacyStoredShare {
1634        metadata: crate::frost::ShareMetadata,
1635        encrypted_key_package: Vec<u8>,
1636        pubkey_package: Vec<u8>,
1637    }
1638
1639    let legacy: LegacyStoredShare = bincode_options().deserialize(bytes)?;
1640    Ok(StoredShare {
1641        metadata: legacy.metadata,
1642        encrypted_key_package: legacy.encrypted_key_package,
1643        pubkey_package: legacy.pubkey_package,
1644        ciphersuite: crate::frost::Ciphersuite::Secp256k1Tr,
1645    })
1646}
1647
1648pub(crate) fn share_id(group_pubkey: &[u8; 32], identifier: u16) -> [u8; 32] {
1649    let mut data = [0u8; 34];
1650    data[..32].copy_from_slice(group_pubkey);
1651    data[32..34].copy_from_slice(&identifier.to_le_bytes());
1652    crypto::blake2b_256(&data)
1653}
1654
1655impl Drop for Storage {
1656    fn drop(&mut self) {
1657        self.lock();
1658    }
1659}
1660
1661#[cfg(test)]
1662mod tests {
1663    use super::*;
1664    use tempfile::tempdir;
1665
1666    #[test]
1667    fn test_legacy_stored_share_blob_loads_as_secp256k1() {
1668        use bincode::Options;
1669
1670        #[derive(serde::Serialize)]
1671        struct LegacyStoredShare {
1672            metadata: crate::frost::ShareMetadata,
1673            encrypted_key_package: Vec<u8>,
1674            pubkey_package: Vec<u8>,
1675        }
1676
1677        let legacy = LegacyStoredShare {
1678            metadata: crate::frost::ShareMetadata::new(1, 2, 3, [3u8; 32], "old".into()),
1679            encrypted_key_package: vec![1u8; 64],
1680            pubkey_package: vec![2u8; 33],
1681        };
1682
1683        let opts = || {
1684            bincode::options()
1685                .with_fixint_encoding()
1686                .allow_trailing_bytes()
1687        };
1688
1689        // A blob written by the old default-options path and the configured path.
1690        for blob in [
1691            bincode::serialize(&legacy).unwrap(),
1692            opts().serialize(&legacy).unwrap(),
1693        ] {
1694            let loaded = deserialize_stored_share(&blob).unwrap();
1695            assert_eq!(loaded.ciphersuite, crate::frost::Ciphersuite::Secp256k1Tr);
1696            assert_eq!(loaded.metadata.identifier, 1);
1697            assert_eq!(loaded.encrypted_key_package, vec![1u8; 64]);
1698            assert_eq!(loaded.pubkey_package, vec![2u8; 33]);
1699        }
1700    }
1701
1702    #[test]
1703    fn test_new_stored_share_blob_roundtrips() {
1704        let share = StoredShare {
1705            metadata: crate::frost::ShareMetadata::new(2, 2, 3, [4u8; 32], "new".into()),
1706            encrypted_key_package: vec![7u8; 50],
1707            pubkey_package: vec![8u8; 33],
1708            ciphersuite: crate::frost::Ciphersuite::Ed25519,
1709        };
1710
1711        let blob = serialize_stored_share(&share).unwrap();
1712        assert!(blob.starts_with(SHARE_FORMAT_MAGIC));
1713        assert_eq!(blob[SHARE_FORMAT_MAGIC.len()], SHARE_FORMAT_V1);
1714
1715        let loaded = deserialize_stored_share(&blob).unwrap();
1716        assert_eq!(loaded.ciphersuite, crate::frost::Ciphersuite::Ed25519);
1717        assert_eq!(loaded.metadata.identifier, 2);
1718        assert_eq!(loaded.encrypted_key_package, vec![7u8; 50]);
1719    }
1720
1721    #[test]
1722    fn test_versioned_blob_does_not_parse_as_legacy() {
1723        // A v1-prefixed Ed25519 blob must never be silently read through the
1724        // legacy (always-secp256k1) path. The magic dispatches it strictly to
1725        // the current layout, preserving its real ciphersuite tag.
1726        let share = StoredShare {
1727            metadata: crate::frost::ShareMetadata::new(5, 2, 3, [6u8; 32], "v1".into()),
1728            encrypted_key_package: vec![1u8; 40],
1729            pubkey_package: vec![2u8; 32],
1730            ciphersuite: crate::frost::Ciphersuite::Ed25519,
1731        };
1732        let blob = serialize_stored_share(&share).unwrap();
1733        let loaded = deserialize_stored_share(&blob).unwrap();
1734        assert_eq!(loaded.ciphersuite, crate::frost::Ciphersuite::Ed25519);
1735    }
1736
1737    #[test]
1738    fn test_legacy_blob_cannot_be_misread_as_ed25519() {
1739        // A legacy (unprefixed) blob is always loaded as secp256k1; there is no
1740        // input shape that makes the legacy path yield a different ciphersuite.
1741        use bincode::Options;
1742
1743        #[derive(serde::Serialize)]
1744        struct LegacyStoredShare {
1745            metadata: crate::frost::ShareMetadata,
1746            encrypted_key_package: Vec<u8>,
1747            pubkey_package: Vec<u8>,
1748        }
1749
1750        let legacy = LegacyStoredShare {
1751            metadata: crate::frost::ShareMetadata::new(9, 2, 3, [1u8; 32], "legacy".into()),
1752            encrypted_key_package: vec![3u8; 48],
1753            pubkey_package: vec![4u8; 33],
1754        };
1755        let blob = bincode::options()
1756            .with_fixint_encoding()
1757            .allow_trailing_bytes()
1758            .serialize(&legacy)
1759            .unwrap();
1760
1761        let loaded = deserialize_stored_share(&blob).unwrap();
1762        assert_eq!(loaded.ciphersuite, crate::frost::Ciphersuite::Secp256k1Tr);
1763    }
1764
1765    #[test]
1766    fn test_stored_share_envelope_byte_identity_preserved() {
1767        // The version prefix lives on the plaintext StoredShare serialization,
1768        // independent of the AEAD envelope. A secp256k1 share's encrypted_key_package
1769        // (empty AAD) is byte-identical to what plain crypto::encrypt produces.
1770        let key = crypto::SecretKey::generate().unwrap();
1771        let pkg = crate::frost::SharePackage::from_bytes(
1772            crate::frost::ShareMetadata::new(1, 2, 3, [7u8; 32], "x".into()),
1773            vec![1, 2, 3, 4],
1774            vec![9, 9, 9],
1775        );
1776        let stored = StoredShare::encrypt(&pkg, &key).unwrap();
1777        let restored = stored.decrypt(&key).unwrap();
1778        assert_eq!(restored.key_package_bytes(), pkg.key_package_bytes());
1779        assert_eq!(stored.ciphersuite, crate::frost::Ciphersuite::Secp256k1Tr);
1780    }
1781
1782    #[test]
1783    fn test_storage_create_and_unlock() {
1784        let dir = tempdir().unwrap();
1785        let path = dir.path().join("test-keep");
1786
1787        {
1788            let storage = Storage::create(&path, "password", Argon2Params::TESTING).unwrap();
1789            assert!(storage.is_unlocked());
1790        }
1791
1792        {
1793            let mut storage = Storage::open(&path).unwrap();
1794            assert!(!storage.is_unlocked());
1795
1796            storage.unlock("password").unwrap();
1797            assert!(storage.is_unlocked());
1798        }
1799    }
1800
1801    #[test]
1802    fn test_storage_wrong_password() {
1803        let dir = tempdir().unwrap();
1804        let path = dir.path().join("test-keep");
1805
1806        Storage::create(&path, "correctpass", Argon2Params::TESTING).unwrap();
1807
1808        let mut storage = Storage::open(&path).unwrap();
1809        let result = storage.unlock("wrongpass");
1810        assert!(result.is_err());
1811    }
1812
1813    #[test]
1814    fn secret_store_load_list_delete_round_trips() {
1815        use crate::secret::{SecretKind, SecretRecord};
1816        let dir = tempdir().unwrap();
1817        let storage =
1818            Storage::create(&dir.path().join("v"), "password", Argon2Params::TESTING).unwrap();
1819
1820        let rec = SecretRecord::new(
1821            "GitHub login".into(),
1822            SecretKind::Password,
1823            b"hunter2".to_vec(),
1824        )
1825        .unwrap();
1826        let id = rec.id;
1827        storage.store_secret(&rec).unwrap();
1828
1829        let loaded = storage.load_secret(&id).unwrap();
1830        assert_eq!(loaded.id, id);
1831        assert_eq!(loaded.name, "GitHub login");
1832        assert_eq!(loaded.kind, SecretKind::Password);
1833        assert_eq!(loaded.value, b"hunter2");
1834
1835        assert_eq!(storage.list_secrets().unwrap().len(), 1);
1836
1837        storage.delete_secret(&id).unwrap();
1838        assert!(storage.load_secret(&id).is_err());
1839        assert!(storage.list_secrets().unwrap().is_empty());
1840        // Deleting a missing secret errors rather than silently succeeding.
1841        assert!(storage.delete_secret(&id).is_err());
1842    }
1843
1844    #[test]
1845    fn sealed_secret_store_load_seal_and_delete_removes_both() {
1846        use crate::secret::{seal_value, unseal_value, SecretKind, SecretRecord};
1847        let dir = tempdir().unwrap();
1848        let storage =
1849            Storage::create(&dir.path().join("v"), "password", Argon2Params::TESTING).unwrap();
1850        let oprf_key = crypto::SecretKey::generate().unwrap();
1851
1852        let mut rec = SecretRecord::new("api".into(), SecretKind::ApiToken, Vec::new()).unwrap();
1853        let id = rec.id;
1854        let (value_ct, seal) = seal_value(b"tok", &oprf_key, hex::encode(id), 2).unwrap();
1855        rec.value = value_ct;
1856        storage.store_sealed_secret(&rec, &seal).unwrap();
1857
1858        // A normal load returns the DEK-ciphertext (still gated); the seal loads
1859        // and the value unseals under the OPRF key.
1860        let loaded = storage.load_secret(&id).unwrap();
1861        assert_ne!(loaded.value, b"tok", "stored value must be DEK-ciphertext");
1862        let loaded_seal = storage
1863            .load_secret_seal(&id)
1864            .unwrap()
1865            .expect("seal present");
1866        assert_eq!(loaded_seal.epoch, 2);
1867        let plaintext = unseal_value(&loaded.value, &loaded_seal, &oprf_key).unwrap();
1868        assert_eq!(&plaintext[..], b"tok");
1869
1870        // A plain (unsealed) secret reports no seal.
1871        let plain = SecretRecord::new("p".into(), SecretKind::Generic, b"v".to_vec()).unwrap();
1872        storage.store_secret(&plain).unwrap();
1873        assert!(storage.load_secret_seal(&plain.id).unwrap().is_none());
1874
1875        // Deleting a sealed secret drops its seal row atomically too.
1876        storage.delete_secret(&id).unwrap();
1877        assert!(storage.load_secret(&id).is_err());
1878        assert!(storage.load_secret_seal(&id).unwrap().is_none());
1879    }
1880
1881    #[test]
1882    fn overwriting_a_sealed_id_via_plain_store_clears_the_stale_seal() {
1883        use crate::secret::{seal_value, SecretKind, SecretRecord};
1884        let dir = tempdir().unwrap();
1885        let storage =
1886            Storage::create(&dir.path().join("v"), "password", Argon2Params::TESTING).unwrap();
1887        let oprf_key = crypto::SecretKey::generate().unwrap();
1888
1889        let mut rec = SecretRecord::new("s".into(), SecretKind::Generic, Vec::new()).unwrap();
1890        let id = rec.id;
1891        let (value_ct, seal) = seal_value(b"sealed", &oprf_key, hex::encode(id), 0).unwrap();
1892        rec.value = value_ct;
1893        storage.store_sealed_secret(&rec, &seal).unwrap();
1894        assert!(storage.load_secret_seal(&id).unwrap().is_some());
1895
1896        // Overwrite the SAME id with a plain (unsealed) record: the stale seal must
1897        // be gone so `value` is read as plaintext, not ciphertext.
1898        let plain = SecretRecord {
1899            id,
1900            name: "s".into(),
1901            kind: SecretKind::Generic,
1902            value: b"now-plain".to_vec(),
1903            created_at: 0,
1904            updated_at: 0,
1905        };
1906        storage.store_secret(&plain).unwrap();
1907        assert!(storage.load_secret_seal(&id).unwrap().is_none());
1908        assert_eq!(storage.load_secret(&id).unwrap().value, b"now-plain");
1909    }
1910
1911    #[test]
1912    fn store_sealed_secret_rejects_mismatched_oprf_id() {
1913        use crate::secret::{seal_value, SecretKind, SecretRecord};
1914        let dir = tempdir().unwrap();
1915        let storage =
1916            Storage::create(&dir.path().join("v"), "password", Argon2Params::TESTING).unwrap();
1917        let oprf_key = crypto::SecretKey::generate().unwrap();
1918
1919        let mut rec = SecretRecord::new("s".into(), SecretKind::Generic, Vec::new()).unwrap();
1920        // Seal built for a DIFFERENT id than the record it is stored against.
1921        let (value_ct, seal) = seal_value(b"v", &oprf_key, hex::encode([9u8; 32]), 0).unwrap();
1922        rec.value = value_ct;
1923        assert!(
1924            storage.store_sealed_secret(&rec, &seal).is_err(),
1925            "a seal whose oprf_id != record id must be rejected"
1926        );
1927    }
1928
1929    #[test]
1930    fn secrets_get_distinct_random_ids() {
1931        use crate::secret::{SecretKind, SecretRecord};
1932        let dir = tempdir().unwrap();
1933        let storage =
1934            Storage::create(&dir.path().join("v"), "password", Argon2Params::TESTING).unwrap();
1935
1936        // The same title + value stored twice yields two rows: a secret has no
1937        // pubkey to derive a stable id from, so ids are random (see SecretRecord).
1938        let a = SecretRecord::new("dup".into(), SecretKind::Generic, b"same".to_vec()).unwrap();
1939        let b = SecretRecord::new("dup".into(), SecretKind::Generic, b"same".to_vec()).unwrap();
1940        assert_ne!(a.id, b.id);
1941        storage.store_secret(&a).unwrap();
1942        storage.store_secret(&b).unwrap();
1943        assert_eq!(storage.list_secrets().unwrap().len(), 2);
1944    }
1945
1946    #[test]
1947    fn secrets_table_is_not_replicable() {
1948        // A password vault must never sync to public relays. `replicated_table`
1949        // fails loudly for "secrets" rather than silently allowing it.
1950        assert!(Storage::replicated_table("secrets").is_err());
1951    }
1952
1953    #[test]
1954    fn test_storage_key_operations() {
1955        let dir = tempdir().unwrap();
1956        let path = dir.path().join("test-keep");
1957
1958        let storage = Storage::create(&path, "password", Argon2Params::TESTING).unwrap();
1959
1960        let record = KeyRecord::new(
1961            crypto::random_bytes(),
1962            crate::keys::KeyType::Nostr,
1963            "test key".into(),
1964            vec![1, 2, 3, 4],
1965        );
1966
1967        storage.store_key(&record).unwrap();
1968
1969        let loaded = storage.load_key(&record.id).unwrap();
1970        assert_eq!(loaded.name, record.name);
1971        assert_eq!(loaded.pubkey, record.pubkey);
1972
1973        let keys = storage.list_keys().unwrap();
1974        assert_eq!(keys.len(), 1);
1975
1976        storage.delete_key(&record.id).unwrap();
1977        let keys = storage.list_keys().unwrap();
1978        assert_eq!(keys.len(), 0);
1979    }
1980
1981    #[test]
1982    fn test_storage_rate_limiting() {
1983        let dir = tempdir().unwrap();
1984        let path = dir.path().join("test-rate-limit");
1985
1986        Storage::create(&path, "correctpass", Argon2Params::TESTING).unwrap();
1987
1988        for _ in 0..5 {
1989            let mut storage = Storage::open(&path).unwrap();
1990            let result = storage.unlock("wrongpass");
1991            assert!(matches!(result, Err(KeepError::DecryptionFailed)));
1992        }
1993
1994        // Bump failure count higher so the delay (4s) won't expire during test
1995        // execution. Without this, the 1s delay at exactly 5 failures can expire
1996        // on slow CI (Windows) between record_failure and check_rate_limit.
1997        {
1998            let storage = Storage::open(&path).unwrap();
1999            let hmac_key = rate_limit::derive_hmac_key(&storage.header.salt);
2000            for _ in 0..2 {
2001                rate_limit::record_failure(&path, &hmac_key);
2002            }
2003        }
2004
2005        let mut storage = Storage::open(&path).unwrap();
2006        let result = storage.unlock("wrongpass");
2007        assert!(matches!(result, Err(KeepError::RateLimited(_))));
2008    }
2009
2010    #[test]
2011    fn test_storage_rate_limit_resets_on_success() {
2012        let dir = tempdir().unwrap();
2013        let path = dir.path().join("test-rate-limit-reset");
2014
2015        Storage::create(&path, "correctpass", Argon2Params::TESTING).unwrap();
2016
2017        for _ in 0..4 {
2018            let mut storage = Storage::open(&path).unwrap();
2019            let _ = storage.unlock("wrongpass");
2020        }
2021
2022        {
2023            let mut storage = Storage::open(&path).unwrap();
2024            storage.unlock("correctpass").unwrap();
2025        }
2026
2027        for _ in 0..4 {
2028            let mut storage = Storage::open(&path).unwrap();
2029            let result = storage.unlock("wrongpass");
2030            assert!(matches!(result, Err(KeepError::DecryptionFailed)));
2031        }
2032    }
2033
2034    #[test]
2035    fn test_storage_with_memory_backend() {
2036        use crate::backend::MemoryBackend;
2037
2038        let dir = tempdir().unwrap();
2039        let path = dir.path().join("test-mem-backend");
2040
2041        let backend = Box::new(MemoryBackend::new());
2042        let storage =
2043            Storage::create_with_backend(&path, "password", Argon2Params::TESTING, backend)
2044                .unwrap();
2045        assert!(storage.is_unlocked());
2046
2047        let record = KeyRecord::new(
2048            crypto::random_bytes(),
2049            crate::keys::KeyType::Nostr,
2050            "mem test key".into(),
2051            vec![1, 2, 3, 4],
2052        );
2053
2054        storage.store_key(&record).unwrap();
2055        let loaded = storage.load_key(&record.id).unwrap();
2056        assert_eq!(loaded.name, record.name);
2057
2058        let keys = storage.list_keys().unwrap();
2059        assert_eq!(keys.len(), 1);
2060    }
2061
2062    #[derive(Default)]
2063    struct RecordingPublisher {
2064        records: std::sync::Mutex<Vec<(String, String)>>,
2065        deletes: std::sync::Mutex<Vec<(String, String)>>,
2066        last_bytes: std::sync::Mutex<Vec<u8>>,
2067    }
2068    impl StatePublisher for RecordingPublisher {
2069        fn on_record(&self, table: &str, record_id: &str, encrypted: &[u8]) {
2070            self.records
2071                .lock()
2072                .unwrap()
2073                .push((table.into(), record_id.into()));
2074            *self.last_bytes.lock().unwrap() = encrypted.to_vec();
2075        }
2076        fn on_delete(&self, table: &str, record_id: &str) {
2077            self.deletes
2078                .lock()
2079                .unwrap()
2080                .push((table.into(), record_id.into()));
2081        }
2082    }
2083
2084    #[test]
2085    fn apply_replicated_record_round_trips_and_rejects_nonreplicable_tables() {
2086        use crate::backend::MemoryBackend;
2087
2088        let dir = tempdir().unwrap();
2089        let path = dir.path().join("test-apply");
2090        let backend = Box::new(MemoryBackend::new());
2091        let storage =
2092            Storage::create_with_backend(&path, "password", Argon2Params::TESTING, backend)
2093                .unwrap();
2094
2095        let publisher = std::sync::Arc::new(RecordingPublisher::default());
2096        storage.set_state_publisher(publisher.clone());
2097
2098        let record = KeyRecord::new(
2099            crypto::random_bytes(),
2100            crate::keys::KeyType::Nostr,
2101            "replicated".into(),
2102            vec![7, 7, 7],
2103        );
2104        // Store, capture the exact bytes the publisher shipped, then delete so the vault no longer has
2105        // the record locally.
2106        storage.store_key(&record).unwrap();
2107        let encrypted = publisher.last_bytes.lock().unwrap().clone();
2108        storage.delete_key(&record.id).unwrap();
2109        assert!(storage.load_key(&record.id).is_err());
2110
2111        // Applying the replicated bytes reconstructs a loadable record (same vault key decrypts them).
2112        storage
2113            .apply_replicated_record("keys", &hex::encode(record.id), &encrypted, 1, 1_000_000)
2114            .unwrap();
2115        assert_eq!(storage.load_key(&record.id).unwrap().name, "replicated");
2116
2117        // A non-replicable table (shares / node-local / unknown) is refused, so a peer cannot write it.
2118        assert!(storage
2119            .apply_replicated_record("shares", &hex::encode(record.id), &encrypted, 1, 1_000_000)
2120            .is_err());
2121        assert!(storage
2122            .apply_replicated_record("bogus", &hex::encode(record.id), &encrypted, 1, 1_000_000)
2123            .is_err());
2124
2125        // A descriptor key of the wrong length is refused: the listing/lookup path fails closed on any
2126        // non-36-byte descriptor row, so accepting one would poison list_descriptors for the vault.
2127        assert!(storage
2128            .apply_replicated_record(
2129                "descriptors",
2130                &hex::encode([0u8; 20]),
2131                &encrypted,
2132                1,
2133                1_000_000
2134            )
2135            .is_err());
2136        assert!(storage
2137            .apply_replicated_delete("descriptors", &hex::encode([0u8; 20]), 1, 1_000_000)
2138            .is_err());
2139        // A correctly-sized 36-byte descriptor key is accepted.
2140        assert!(storage
2141            .apply_replicated_record(
2142                "descriptors",
2143                &hex::encode([0u8; 36]),
2144                &encrypted,
2145                1,
2146                1_000_000
2147            )
2148            .is_ok());
2149
2150        // A replicated delete removes it, and never echoes to the publisher: the only recorded delete
2151        // is the earlier real delete_key, not this apply.
2152        let deletes_before = publisher.deletes.lock().unwrap().len();
2153        storage
2154            .apply_replicated_delete("keys", &hex::encode(record.id), 2, 1_000_000)
2155            .unwrap();
2156        assert!(storage.load_key(&record.id).is_err());
2157        assert_eq!(publisher.deletes.lock().unwrap().len(), deletes_before);
2158    }
2159
2160    #[test]
2161    fn replicated_apply_rejects_stale_created_at() {
2162        // The rollback guard: an event not strictly newer than the highest applied for its d-tag is
2163        // ignored, so an untrusted relay cannot replay a stale record/delete to roll a standby back.
2164        // created_at is the SIGNED event timestamp and cannot be forged to look newer.
2165        let dir = tempdir().unwrap();
2166        let storage =
2167            Storage::create(&dir.path().join("v"), "passwordX", Argon2Params::TESTING).unwrap();
2168
2169        let publisher = std::sync::Arc::new(RecordingPublisher::default());
2170        storage.set_state_publisher(publisher.clone());
2171        let mk = |name: &str| {
2172            KeyRecord::new(
2173                [9u8; 32],
2174                crate::keys::KeyType::Nostr,
2175                name.into(),
2176                vec![1, 2, 3],
2177            )
2178        };
2179        storage.store_key(&mk("v1")).unwrap();
2180        let enc_v1 = publisher.last_bytes.lock().unwrap().clone();
2181        storage.store_key(&mk("v2")).unwrap();
2182        let enc_v2 = publisher.last_bytes.lock().unwrap().clone();
2183        let id = hex::encode([9u8; 32]);
2184
2185        // Apply v2 at created_at=100.
2186        assert_eq!(
2187            storage
2188                .apply_replicated_record("keys", &id, &enc_v2, 100, 1_000_000)
2189                .unwrap(),
2190            ReplicatedApply::Applied
2191        );
2192        assert_eq!(storage.load_key(&[9u8; 32]).unwrap().name, "v2");
2193
2194        // An older replay is rejected and does NOT roll the record back to v1.
2195        assert_eq!(
2196            storage
2197                .apply_replicated_record("keys", &id, &enc_v1, 50, 1_000_000)
2198                .unwrap(),
2199            ReplicatedApply::IgnoredStale
2200        );
2201        assert_eq!(storage.load_key(&[9u8; 32]).unwrap().name, "v2");
2202        // The SAME created_at is also rejected (idempotent, no rollback).
2203        assert_eq!(
2204            storage
2205                .apply_replicated_record("keys", &id, &enc_v1, 100, 1_000_000)
2206                .unwrap(),
2207            ReplicatedApply::IgnoredStale
2208        );
2209        assert_eq!(storage.load_key(&[9u8; 32]).unwrap().name, "v2");
2210
2211        // A strictly-newer delete IS applied, and a stale record cannot resurrect the deleted row.
2212        assert_eq!(
2213            storage
2214                .apply_replicated_delete("keys", &id, 200, 1_000_000)
2215                .unwrap(),
2216            ReplicatedApply::Applied
2217        );
2218        assert!(storage.load_key(&[9u8; 32]).is_err());
2219        assert_eq!(
2220            storage
2221                .apply_replicated_record("keys", &id, &enc_v1, 150, 1_000_000)
2222                .unwrap(),
2223            ReplicatedApply::IgnoredStale
2224        );
2225        assert!(storage.load_key(&[9u8; 32]).is_err());
2226    }
2227
2228    #[test]
2229    fn replicated_apply_rejects_implausibly_future_created_at() {
2230        // A validly-signed event (would require the cluster key) with created_at far in the future must
2231        // be rejected and must NOT advance the mark, or it would freeze the record forever (GH #708).
2232        let dir = tempdir().unwrap();
2233        let storage =
2234            Storage::create(&dir.path().join("v"), "passwordF", Argon2Params::TESTING).unwrap();
2235        let publisher = std::sync::Arc::new(RecordingPublisher::default());
2236        storage.set_state_publisher(publisher.clone());
2237        storage
2238            .store_key(&KeyRecord::new(
2239                [3u8; 32],
2240                crate::keys::KeyType::Nostr,
2241                "x".into(),
2242                vec![1],
2243            ))
2244            .unwrap();
2245        let enc = publisher.last_bytes.lock().unwrap().clone();
2246        let id = hex::encode([3u8; 32]);
2247        let now = 1_000_000u64;
2248
2249        // Far-future (now + ~1 year) and u64::MAX are rejected without persisting a mark.
2250        for future in [now + 31_536_000, u64::MAX] {
2251            assert_eq!(
2252                storage
2253                    .apply_replicated_record("keys", &id, &enc, future, now)
2254                    .unwrap(),
2255                ReplicatedApply::RejectedFuture
2256            );
2257            assert_eq!(storage.state_version("keys", &id).unwrap(), None);
2258        }
2259        // The poison did not freeze the record: a legitimate near-now event still applies, and the
2260        // boundary (now + margin) is accepted.
2261        assert_eq!(
2262            storage
2263                .apply_replicated_record("keys", &id, &enc, now, now)
2264                .unwrap(),
2265            ReplicatedApply::Applied
2266        );
2267        assert_eq!(
2268            storage
2269                .apply_replicated_record("keys", &id, &enc, now + MAX_FUTURE_SKEW_SECS, now)
2270                .unwrap(),
2271            ReplicatedApply::Applied
2272        );
2273    }
2274
2275    #[test]
2276    fn snapshot_replicable_records_matches_publisher_hook() {
2277        let dir = tempdir().unwrap();
2278        let storage =
2279            Storage::create(&dir.path().join("v"), "password", Argon2Params::TESTING).unwrap();
2280        let publisher = std::sync::Arc::new(RecordingPublisher::default());
2281        storage.set_state_publisher(publisher.clone());
2282
2283        let rec = KeyRecord::new(
2284            [7u8; 32],
2285            crate::keys::KeyType::Nostr,
2286            "snap".into(),
2287            vec![9, 8, 7],
2288        );
2289        storage.store_key(&rec).unwrap();
2290
2291        // The write-time hook and the startup snapshot must agree on (table, id, bytes) exactly, or a
2292        // snapshot-published record would land under a different d-tag than the hook's and fail to
2293        // supersede it on the standby.
2294        let hook_id = hex::encode(rec.id);
2295        let hook_bytes = publisher.last_bytes.lock().unwrap().clone();
2296
2297        let snap = storage.snapshot_replicable_records().unwrap();
2298        let entry = snap
2299            .iter()
2300            .find(|(t, id, _)| *t == "keys" && *id == hook_id)
2301            .expect("snapshot must include the stored key");
2302        assert_eq!(
2303            entry.2, hook_bytes,
2304            "snapshot bytes must equal the hook's on_record bytes"
2305        );
2306        // Exactly one record was stored, so empty tables contribute no phantom rows.
2307        assert_eq!(snap.len(), 1);
2308    }
2309
2310    #[test]
2311    fn password_matches_is_rate_limit_free() {
2312        let dir = tempdir().unwrap();
2313        let storage = Storage::create(
2314            &dir.path().join("v"),
2315            "rightpassword",
2316            Argon2Params::TESTING,
2317        )
2318        .unwrap();
2319
2320        // Correct classification: right password matches, wrong password does not.
2321        assert!(storage.password_matches("rightpassword").unwrap());
2322        assert!(!storage.password_matches("wrongpassword").unwrap());
2323
2324        // Hammer wrong passwords well past MAX_ATTEMPTS (5): password_matches must
2325        // record no failures, so the rate limiter never trips. If it did, the real
2326        // verify below would return RateLimited before decrypting.
2327        for _ in 0..8 {
2328            assert!(!storage.password_matches("nope").unwrap());
2329        }
2330        assert!(
2331            storage.verify_password("rightpassword").is_ok(),
2332            "password_matches must not touch the rate limiter (a pre-flight check cannot self-lock the vault)"
2333        );
2334    }
2335
2336    #[test]
2337    fn state_version_is_per_record_not_global() {
2338        // The publisher seeds each d-tag's floor from its OWN mark, so verify the getter returns
2339        // per-record marks: a quiet record is not inflated to a busier record's timestamp.
2340        let dir = tempdir().unwrap();
2341        let storage =
2342            Storage::create(&dir.path().join("v"), "passwordP", Argon2Params::TESTING).unwrap();
2343        let publisher = std::sync::Arc::new(RecordingPublisher::default());
2344        storage.set_state_publisher(publisher.clone());
2345        storage
2346            .store_key(&KeyRecord::new(
2347                [1u8; 32],
2348                crate::keys::KeyType::Nostr,
2349                "a".into(),
2350                vec![1],
2351            ))
2352            .unwrap();
2353        let enc = publisher.last_bytes.lock().unwrap().clone();
2354        let a = hex::encode([1u8; 32]);
2355        let b = hex::encode([2u8; 32]);
2356
2357        assert_eq!(storage.state_version("keys", &a).unwrap(), None);
2358        storage
2359            .apply_replicated_record("keys", &a, &enc, 100, 1_000_000)
2360            .unwrap();
2361        storage
2362            .apply_replicated_record("keys", &b, &enc, 500, 1_000_000)
2363            .unwrap();
2364        // Record a's mark stays 100 even though b was applied at 500 (no global-max contamination).
2365        assert_eq!(storage.state_version("keys", &a).unwrap(), Some(100));
2366        assert_eq!(storage.state_version("keys", &b).unwrap(), Some(500));
2367    }
2368
2369    #[test]
2370    fn apply_replicated_record_fails_closed_on_corrupt_high_water_mark() {
2371        // A non-8-byte high-water-mark cannot be decoded to a u64: the guard must propagate the decode
2372        // error (fail closed) rather than silently treating it as first-sync and applying the event.
2373        let dir = tempdir().unwrap();
2374        let storage =
2375            Storage::create(&dir.path().join("v"), "passwordX", Argon2Params::TESTING).unwrap();
2376
2377        let record = KeyRecord::new(
2378            [3u8; 32],
2379            crate::keys::KeyType::Nostr,
2380            "corrupt".into(),
2381            vec![1, 2, 3],
2382        );
2383        let id = hex::encode([3u8; 32]);
2384        let vkey = Storage::state_version_key(KEYS_TABLE, &[3u8; 32]);
2385        storage
2386            .backend
2387            .as_ref()
2388            .unwrap()
2389            .put(STATE_VERSIONS_TABLE, &vkey, &[1, 2, 3])
2390            .unwrap();
2391
2392        let publisher = std::sync::Arc::new(RecordingPublisher::default());
2393        storage.set_state_publisher(publisher.clone());
2394        storage.store_key(&record).unwrap();
2395        let encrypted = publisher.last_bytes.lock().unwrap().clone();
2396        storage.delete_key(&record.id).unwrap();
2397
2398        let err = storage
2399            .apply_replicated_record("keys", &id, &encrypted, 100, 1_000_000)
2400            .unwrap_err();
2401        assert!(
2402            matches!(&err, KeepError::Other(m) if m == "corrupt keep-state version high-water-mark"),
2403            "got {err:?}"
2404        );
2405    }
2406
2407    #[test]
2408    fn shared_data_key_cross_decrypts_across_vaults() {
2409        // Two independent vaults with DIFFERENT passwords but the SAME seeded data key: a record
2410        // encrypted by one must decrypt in the other. This is the cluster invariant keep-state
2411        // replication relies on (the standby reads what the active shipped).
2412        let shared: Zeroizing<[u8; 32]> = Zeroizing::new(crypto::random_bytes());
2413        let dir = tempdir().unwrap();
2414
2415        let a = Storage::create_with_shared_data_key(
2416            &dir.path().join("a"),
2417            "passwordA",
2418            Argon2Params::TESTING,
2419            shared.clone(),
2420        )
2421        .unwrap();
2422        let b = Storage::create_with_shared_data_key(
2423            &dir.path().join("b"),
2424            "differentB",
2425            Argon2Params::TESTING,
2426            shared.clone(),
2427        )
2428        .unwrap();
2429
2430        let publisher = std::sync::Arc::new(RecordingPublisher::default());
2431        a.set_state_publisher(publisher.clone());
2432
2433        let record = KeyRecord::new(
2434            crypto::random_bytes(),
2435            crate::keys::KeyType::Nostr,
2436            "shared".into(),
2437            vec![1, 2, 3],
2438        );
2439        a.store_key(&record).unwrap();
2440        let encrypted = publisher.last_bytes.lock().unwrap().clone();
2441
2442        b.apply_replicated_record("keys", &hex::encode(record.id), &encrypted, 1, 1_000_000)
2443            .unwrap();
2444        assert_eq!(b.load_key(&record.id).unwrap().name, "shared");
2445
2446        // Sanity: WITHOUT the shared key, a third vault cannot decrypt the same bytes.
2447        let c = Storage::create(&dir.path().join("c"), "passwordC", Argon2Params::TESTING).unwrap();
2448        c.apply_replicated_record("keys", &hex::encode(record.id), &encrypted, 1, 1_000_000)
2449            .unwrap();
2450        assert!(c.load_key(&record.id).is_err());
2451    }
2452
2453    #[test]
2454    fn state_publisher_fires_on_key_writes() {
2455        use crate::backend::MemoryBackend;
2456
2457        let dir = tempdir().unwrap();
2458        let path = dir.path().join("test-publish");
2459        let backend = Box::new(MemoryBackend::new());
2460        let storage =
2461            Storage::create_with_backend(&path, "password", Argon2Params::TESTING, backend)
2462                .unwrap();
2463
2464        let publisher = std::sync::Arc::new(RecordingPublisher::default());
2465        storage.set_state_publisher(publisher.clone());
2466
2467        let record = KeyRecord::new(
2468            crypto::random_bytes(),
2469            crate::keys::KeyType::Nostr,
2470            "k".into(),
2471            vec![1, 2, 3],
2472        );
2473        storage.store_key(&record).unwrap();
2474        storage.delete_key(&record.id).unwrap();
2475
2476        // The write hook fires with the record's table + hex id; the encrypted-bytes payload is the
2477        // same bytes stored (asserted non-empty). Shares are intentionally NOT hooked (per-node, per
2478        // the qmc design), which is enforced by construction: store_share carries no notify call.
2479        let records = publisher.records.lock().unwrap();
2480        let deletes = publisher.deletes.lock().unwrap();
2481        assert_eq!(*records, vec![("keys".to_string(), hex::encode(record.id))]);
2482        assert_eq!(*deletes, vec![("keys".to_string(), hex::encode(record.id))]);
2483    }
2484
2485    #[test]
2486    fn test_header_rejects_malicious_argon2_params() {
2487        let valid_header = Header::new(Argon2Params::TESTING).unwrap();
2488        let valid_bytes = valid_header.to_bytes();
2489
2490        Header::from_bytes(&valid_bytes).expect("valid header should parse");
2491
2492        let mut bad_memory_high = valid_bytes;
2493        bad_memory_high[116..120].copy_from_slice(&u32::MAX.to_le_bytes());
2494        match Header::from_bytes(&bad_memory_high) {
2495            Err(e) => assert!(e.to_string().contains("memory")),
2496            Ok(_) => panic!("expected error for extreme memory"),
2497        }
2498
2499        let mut bad_memory_low = valid_bytes;
2500        bad_memory_low[116..120].copy_from_slice(&0u32.to_le_bytes());
2501        assert!(Header::from_bytes(&bad_memory_low).is_err());
2502
2503        let mut bad_iterations_high = valid_bytes;
2504        bad_iterations_high[120..124].copy_from_slice(&u32::MAX.to_le_bytes());
2505        match Header::from_bytes(&bad_iterations_high) {
2506            Err(e) => assert!(e.to_string().contains("iterations")),
2507            Ok(_) => panic!("expected error for extreme iterations"),
2508        }
2509
2510        let mut bad_iterations_low = valid_bytes;
2511        bad_iterations_low[120..124].copy_from_slice(&0u32.to_le_bytes());
2512        assert!(Header::from_bytes(&bad_iterations_low).is_err());
2513
2514        let mut bad_parallelism_high = valid_bytes;
2515        bad_parallelism_high[124..128].copy_from_slice(&u32::MAX.to_le_bytes());
2516        match Header::from_bytes(&bad_parallelism_high) {
2517            Err(e) => assert!(e.to_string().contains("parallelism")),
2518            Ok(_) => panic!("expected error for extreme parallelism"),
2519        }
2520
2521        let mut bad_parallelism_low = valid_bytes;
2522        bad_parallelism_low[124..128].copy_from_slice(&0u32.to_le_bytes());
2523        assert!(Header::from_bytes(&bad_parallelism_low).is_err());
2524    }
2525
2526    #[test]
2527    fn proxy_config_roundtrip() {
2528        let dir = tempfile::tempdir().unwrap();
2529        let path = dir.path().join("test-keep");
2530        let storage = Storage::create(&path, "testpassword", Default::default()).unwrap();
2531
2532        let config = ProxyConfig {
2533            enabled: true,
2534            port: 9051,
2535        };
2536        storage.set_proxy_config(&config).unwrap();
2537        let loaded = storage.get_proxy_config().unwrap();
2538        assert!(loaded.enabled);
2539        assert_eq!(loaded.port, 9051);
2540    }
2541
2542    #[test]
2543    fn proxy_config_default_when_absent() {
2544        let dir = tempfile::tempdir().unwrap();
2545        let path = dir.path().join("test-keep");
2546        let storage = Storage::create(&path, "testpassword", Default::default()).unwrap();
2547
2548        let loaded = storage.get_proxy_config().unwrap();
2549        assert!(!loaded.enabled);
2550        assert_eq!(loaded.port, 9050);
2551    }
2552
2553    #[test]
2554    fn relay_config_bunker_relays_roundtrip() {
2555        let dir = tempfile::tempdir().unwrap();
2556        let path = dir.path().join("test-keep");
2557        let storage = Storage::create(&path, "testpassword", Default::default()).unwrap();
2558
2559        let key = [1u8; 32];
2560        let mut config = RelayConfig::new(key);
2561        config.bunker_relays = vec!["wss://relay.nsec.app/".into()];
2562        storage.store_relay_config(&config).unwrap();
2563
2564        let loaded = storage.get_relay_config(&key).unwrap().unwrap();
2565        assert_eq!(loaded.bunker_relays, vec!["wss://relay.nsec.app/"]);
2566    }
2567
2568    #[test]
2569    fn relay_config_bunker_relays_backward_compat() {
2570        let json = r#"{"group_pubkey":[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"frost_relays":[],"profile_relays":[]}"#;
2571        let config: RelayConfig = serde_json::from_str(json).unwrap();
2572        assert!(config.bunker_relays.is_empty());
2573    }
2574
2575    #[test]
2576    fn relay_config_peer_policies_backward_compat() {
2577        let json = r#"{"group_pubkey":[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"frost_relays":[],"profile_relays":[]}"#;
2578        let config: RelayConfig = serde_json::from_str(json).unwrap();
2579        assert!(config.peer_policies.is_empty());
2580    }
2581
2582    #[test]
2583    fn relay_config_peer_policies_roundtrip() {
2584        use crate::relay::PeerPolicyEntry;
2585
2586        let dir = tempfile::tempdir().unwrap();
2587        let path = dir.path().join("test-keep");
2588        let storage = Storage::create(&path, "testpassword", Default::default()).unwrap();
2589
2590        let mut config = RelayConfig::new([2u8; 32]);
2591        config.peer_policies.push(PeerPolicyEntry {
2592            pubkey_hex: "ab".repeat(32),
2593            allow_send: false,
2594            allow_receive: true,
2595        });
2596        storage.store_relay_config(&config).unwrap();
2597
2598        let loaded = storage.get_relay_config(&[2u8; 32]).unwrap().unwrap();
2599        assert_eq!(loaded.peer_policies.len(), 1);
2600        assert_eq!(loaded.peer_policies[0].pubkey_hex, "ab".repeat(32));
2601        assert!(!loaded.peer_policies[0].allow_send);
2602        assert!(loaded.peer_policies[0].allow_receive);
2603    }
2604
2605    #[test]
2606    fn global_relay_key_sentinel() {
2607        use crate::relay::GLOBAL_RELAY_KEY;
2608
2609        let dir = tempfile::tempdir().unwrap();
2610        let path = dir.path().join("test-keep");
2611        let storage = Storage::create(&path, "testpassword", Default::default()).unwrap();
2612
2613        let global = RelayConfig::new_global();
2614        storage.store_relay_config(&global).unwrap();
2615
2616        let loaded = storage
2617            .get_relay_config(&GLOBAL_RELAY_KEY)
2618            .unwrap()
2619            .unwrap();
2620        assert!(!loaded.frost_relays.is_empty());
2621        assert_eq!(loaded.group_pubkey, GLOBAL_RELAY_KEY);
2622    }
2623}