Skip to main content

keep_core/hidden/
volume.rs

1// SPDX-FileCopyrightText: © 2026 PrivKey LLC
2// SPDX-License-Identifier: MIT
3
4//! Hidden volume implementation for plausible deniability.
5//!
6//! # Architecture
7//!
8//! The hidden volume system provides two encrypted storage areas within a single vault file:
9//!
10//! - **Outer volume**: Standard encrypted storage, unlocked with the primary password
11//! - **Hidden volume**: Secondary encrypted storage, cryptographically indistinguishable from random data
12//!
13//! # File Layout
14//!
15//! ```text
16//! ┌─────────────────────┐  0
17//! │   Outer Header      │  512 bytes - salt, encrypted data key, argon2 params
18//! ├─────────────────────┤  512
19//! │   Hidden Header     │  512 bytes - fully encrypted (looks random)
20//! ├─────────────────────┤  1024 (DATA_START_OFFSET)
21//! │   Outer Data Area   │  Variable size - redb database for outer volume
22//! ├─────────────────────┤
23//! │   Hidden Data Area  │  Variable size - encrypted length + encrypted records + random padding
24//! └─────────────────────┘
25//! ```
26//!
27//! # Security Properties
28//!
29//! - Hidden header KDF salt is derived from password (not stored)
30//! - Hidden data length is encrypted (no plaintext size prefix)
31//! - Hidden header is encrypted and indistinguishable from random bytes
32//! - Wrong password for hidden volume produces same error as "no hidden volume"
33//! - Both volumes use independent Argon2id key derivation
34//! - Unlock attempts both decryptions to prevent timing attacks
35use std::fs::{self, File, OpenOptions};
36use std::io::{Read, Seek, SeekFrom, Write};
37use std::path::{Path, PathBuf};
38
39use rand::Rng;
40use redb::{Database, ReadableDatabase, ReadableTable, TableDefinition};
41
42use crate::crypto::{self, Argon2Params, EncryptedData, SecretKey};
43use crate::error::{KeepError, Result, StorageError};
44use crate::keys::KeyRecord;
45use crate::rate_limit;
46use crate::relay::{self, RelayConfig};
47
48use bincode::Options;
49
50use super::header::{
51    HiddenHeader, OuterHeader, DATA_START_OFFSET, HEADER_SIZE, HIDDEN_HEADER_OFFSET,
52};
53
54const KEYS_TABLE: TableDefinition<&[u8], &[u8]> = TableDefinition::new("keys");
55const RELAY_CONFIGS_TABLE: TableDefinition<&[u8], &[u8]> = TableDefinition::new("relay_configs");
56
57const MAX_RECORD_SIZE: u64 = 1024 * 1024;
58
59const MIN_HIDDEN_SIZE: u64 = (crypto::NONCE_SIZE + 8 + crypto::TAG_SIZE) as u64;
60
61fn derive_hidden_salt(outer_salt: &[u8; 32], password: &str) -> [u8; 32] {
62    let mut input = Vec::with_capacity(19 + 32 + password.len());
63    input.extend_from_slice(b"keep-hidden-salt-v1");
64    input.extend_from_slice(outer_salt);
65    input.extend_from_slice(password.as_bytes());
66    crypto::blake2b_256(&input)
67}
68
69fn write_random_padding(file: &mut File, size: u64) -> std::io::Result<()> {
70    let mut buffer = [0u8; 4096];
71    let mut written = 0u64;
72    while written < size {
73        let to_write = ((size - written) as usize).min(buffer.len());
74        rand::rng().fill_bytes(&mut buffer[..to_write]);
75        file.write_all(&buffer[..to_write])?;
76        written += to_write as u64;
77    }
78    Ok(())
79}
80
81/// Type of encrypted volume.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum VolumeType {
84    /// The primary outer volume.
85    Outer,
86    /// The hidden plausible-deniability volume.
87    Hidden,
88}
89
90/// Encrypted storage with optional hidden volume.
91pub struct HiddenStorage {
92    path: PathBuf,
93    outer_header: OuterHeader,
94    hidden_header: Option<HiddenHeader>,
95    outer_key: Option<SecretKey>,
96    hidden_key: Option<SecretKey>,
97    active_volume: Option<VolumeType>,
98    outer_db: Option<Database>,
99    /// Audit log attached on outer unlock so the `keep audit list/verify/...`
100    /// surface works on hidden-init vaults and `drain_pending_trips` can
101    /// flush rate-limit trip events queued by failed unlocks (#520).
102    /// Outer-volume scope only, paralleling the #507 relay-config decision.
103    outer_audit: Option<crate::audit::AuditLog>,
104}
105
106impl HiddenStorage {
107    /// Create a new hidden storage vault.
108    ///
109    /// `hidden_ratio` is the fraction of space for the hidden volume (0.0-1.0).
110    pub fn create(
111        path: &Path,
112        outer_password: &str,
113        hidden_password: Option<&str>,
114        total_size: u64,
115        hidden_ratio: f32,
116        params: Argon2Params,
117    ) -> Result<Self> {
118        if path.exists() {
119            return Err(KeepError::AlreadyExists(path.display().to_string()));
120        }
121
122        if !(0.0..=1.0).contains(&hidden_ratio) {
123            return Err(KeepError::InvalidInput(format!(
124                "hidden_ratio must be between 0.0 and 1.0, got {hidden_ratio}"
125            )));
126        }
127
128        let hidden_size = if hidden_password.is_some() {
129            ((total_size as f64) * (hidden_ratio as f64)) as u64
130        } else {
131            0
132        };
133
134        if hidden_password.is_some() && hidden_size < MIN_HIDDEN_SIZE {
135            return Err(KeepError::InvalidInput(format!(
136                "hidden volume size {hidden_size} too small, need at least {MIN_HIDDEN_SIZE} bytes"
137            )));
138        }
139
140        let required_min = DATA_START_OFFSET
141            .checked_add(hidden_size)
142            .ok_or_else(|| KeepError::InvalidInput("volume size overflow".into()))?;
143
144        if total_size < required_min {
145            return Err(KeepError::InvalidInput(format!(
146                "total size {total_size} too small, need at least {required_min} bytes (header: {DATA_START_OFFSET}, hidden: {hidden_size})"
147            )));
148        }
149
150        let outer_size = total_size - DATA_START_OFFSET - hidden_size;
151
152        let mut outer_header = OuterHeader::new(params, outer_size, total_size)?;
153
154        let outer_data_key = SecretKey::generate()?;
155        let outer_master_key =
156            crypto::derive_key(outer_password.as_bytes(), &outer_header.salt, params)?;
157        let outer_header_key = crypto::derive_subkey(&outer_master_key, b"keep-outer-header")?;
158
159        let outer_key_bytes = outer_data_key.decrypt()?;
160        let encrypted_outer = crypto::encrypt(&*outer_key_bytes, &outer_header_key)?;
161        outer_header.nonce.copy_from_slice(&encrypted_outer.nonce);
162        outer_header
163            .encrypted_data_key
164            .copy_from_slice(&encrypted_outer.ciphertext);
165
166        let (hidden_header, hidden_data_key, encrypted_hidden_header) =
167            if let Some(hp) = hidden_password {
168                let hidden_offset = DATA_START_OFFSET + outer_size;
169                let mut hh = HiddenHeader::new(hidden_offset, hidden_size)?;
170
171                let hidden_data_key = SecretKey::generate()?;
172                let kdf_salt = derive_hidden_salt(&outer_header.salt, hp);
173                let hidden_master_key = crypto::derive_key(hp.as_bytes(), &kdf_salt, params)?;
174
175                let hidden_header_key =
176                    crypto::derive_subkey(&hidden_master_key, b"keep-hidden-header")?;
177                let hidden_key_bytes = hidden_data_key.decrypt()?;
178                let encrypted_hidden = crypto::encrypt(&*hidden_key_bytes, &hidden_header_key)?;
179                hh.nonce.copy_from_slice(&encrypted_hidden.nonce);
180                hh.encrypted_data_key
181                    .copy_from_slice(&encrypted_hidden.ciphertext);
182                hh.checksum = hh.compute_checksum();
183
184                let hidden_header_enc_key =
185                    crypto::derive_subkey(&hidden_master_key, b"keep-hidden-header-enc")?;
186                let encrypted_hh = crypto::encrypt(&hh.to_bytes_compact(), &hidden_header_enc_key)?;
187
188                (Some(hh), Some(hidden_data_key), Some(encrypted_hh))
189            } else {
190                (None, None, None)
191            };
192
193        fs::create_dir_all(path)?;
194        #[cfg(unix)]
195        {
196            use std::os::unix::fs::PermissionsExt;
197            let _ = fs::set_permissions(path, fs::Permissions::from_mode(0o700));
198        }
199        let vault_path = path.join("keep.vault");
200        let mut file = {
201            #[cfg(unix)]
202            {
203                use std::os::unix::fs::OpenOptionsExt;
204                fs::OpenOptions::new()
205                    .write(true)
206                    .create_new(true)
207                    .mode(0o600)
208                    .open(&vault_path)?
209            }
210            #[cfg(not(unix))]
211            {
212                File::create(&vault_path)?
213            }
214        };
215
216        file.write_all(&outer_header.to_bytes())?;
217
218        let mut hidden_area: [u8; HEADER_SIZE] = crypto::try_random_bytes()?;
219        if let Some(encrypted_hh) = encrypted_hidden_header {
220            hidden_area[..24].copy_from_slice(&encrypted_hh.nonce);
221            hidden_area[24..24 + encrypted_hh.ciphertext.len()]
222                .copy_from_slice(&encrypted_hh.ciphertext);
223        }
224        file.write_all(&hidden_area)?;
225
226        write_random_padding(&mut file, total_size - DATA_START_OFFSET)?;
227        file.sync_all()?;
228        drop(file);
229
230        let db_path = path.join("keep.db");
231        let db = Database::create(&db_path)?;
232        #[cfg(unix)]
233        {
234            use std::os::unix::fs::PermissionsExt;
235            let _ = fs::set_permissions(&db_path, fs::Permissions::from_mode(0o600));
236        }
237
238        let wtxn = db.begin_write()?;
239        let _ = wtxn.open_table(KEYS_TABLE)?;
240        let _ = wtxn.open_table(RELAY_CONFIGS_TABLE)?;
241        wtxn.commit()?;
242
243        Ok(Self {
244            path: path.to_path_buf(),
245            outer_header,
246            hidden_header,
247            outer_key: Some(outer_data_key),
248            hidden_key: hidden_data_key,
249            active_volume: Some(VolumeType::Outer),
250            outer_db: Some(db),
251            outer_audit: None,
252        })
253    }
254
255    /// Open an existing hidden storage vault.
256    pub fn open(path: &Path) -> Result<Self> {
257        if !path.exists() {
258            return Err(KeepError::NotFound(path.display().to_string()));
259        }
260
261        let vault_path = path.join("keep.vault");
262        let mut file = File::open(&vault_path)?;
263
264        let mut header_bytes = [0u8; HEADER_SIZE];
265        file.read_exact(&mut header_bytes)?;
266        let outer_header = OuterHeader::from_bytes(&header_bytes)?;
267
268        Ok(Self {
269            path: path.to_path_buf(),
270            outer_header,
271            hidden_header: None,
272            outer_key: None,
273            hidden_key: None,
274            active_volume: None,
275            outer_db: None,
276            outer_audit: None,
277        })
278    }
279
280    fn try_unlock_outer(&mut self, password: &str) -> Result<()> {
281        if self.outer_key.is_some() {
282            return Ok(());
283        }
284
285        let master_key = crypto::derive_key(
286            password.as_bytes(),
287            &self.outer_header.salt,
288            self.outer_header.argon2_params(),
289        )?;
290
291        let header_key = crypto::derive_subkey(&master_key, b"keep-outer-header")?;
292
293        let encrypted = EncryptedData {
294            nonce: self.outer_header.nonce,
295            ciphertext: self.outer_header.encrypted_data_key.to_vec(),
296        };
297
298        let decrypted = crypto::decrypt(&encrypted, &header_key)?;
299        let decrypted_slice = decrypted.as_slice()?;
300        self.outer_key = Some(SecretKey::from_slice(&decrypted_slice)?);
301
302        let db_path = self.path.join("keep.db");
303        let db = match crate::backend::open_database_with_retry(&db_path) {
304            Ok(db) => db,
305            // Hidden vaults don't auto-upgrade the redb file format here; the
306            // outer-volume schema is owned by `RedbBackend::open`. Surface the
307            // upgrade requirement as a generic database error rather than
308            // silently half-migrating a hidden-init vault.
309            Err(crate::backend::OpenWithRetryError::UpgradeRequired(v)) => {
310                return Err(StorageError::database(format!(
311                    "hidden-vault outer redb requires file format upgrade from v{v}; not yet supported"
312                ))
313                .into());
314            }
315            Err(crate::backend::OpenWithRetryError::Other(e)) => {
316                return Err(crate::backend::map_open_failure(&db_path, e));
317            }
318        };
319
320        self.outer_db = Some(db);
321        self.active_volume = Some(VolumeType::Outer);
322
323        Ok(())
324    }
325
326    /// Unlock the outer volume.
327    pub fn unlock_outer(&mut self, password: &str) -> Result<()> {
328        if self.outer_key.is_some() {
329            return Ok(());
330        }
331
332        let hmac_key = rate_limit::derive_hmac_key(&self.outer_header.salt);
333        if let Err(remaining) = rate_limit::check_rate_limit(&self.path, &hmac_key) {
334            return Err(KeepError::RateLimited(remaining.as_secs().max(1)));
335        }
336
337        match self.try_unlock_outer(password) {
338            Ok(()) => {
339                rate_limit::record_success(&self.path);
340                // #520: open the audit log under the outer data key and flush
341                // any queued rate-limit trip events. Mirrors `Keep::unlock` so
342                // hidden-init vaults get the same `RateLimitTripped` audit
343                // surfacing that regular vaults do.
344                self.attach_outer_audit(&hmac_key)?;
345                Ok(())
346            }
347            Err(e) => {
348                if matches!(e, KeepError::InvalidPassword | KeepError::DecryptionFailed) {
349                    rate_limit::record_failure(&self.path, &hmac_key);
350                }
351                Err(e)
352            }
353        }
354    }
355
356    /// Open the outer-volume audit log and drain pending trip events. Called
357    /// from `unlock_outer` and the `unlock()` dispatcher after the data key is
358    /// in hand. Errors on the audit log are non-fatal to the unlock itself; we
359    /// log and continue so a corrupted audit log can't make the whole vault
360    /// inaccessible. Idempotent: a no-op once the log is already attached.
361    fn attach_outer_audit(&mut self, hmac_key: &[u8; 32]) -> Result<()> {
362        use crate::audit::{AuditEntry, AuditEventType};
363
364        if self.outer_audit.is_some() {
365            return Ok(());
366        }
367
368        let data_key = self.outer_key.as_ref().ok_or(KeepError::Locked)?;
369        let mut audit = match crate::audit::AuditLog::open(&self.path, data_key) {
370            Ok(log) => log,
371            Err(e) => {
372                tracing::warn!(error = %e, "could not open audit log on hidden vault outer unlock; trips will not flush this cycle");
373                return Ok(());
374            }
375        };
376
377        let trips = rate_limit::drain_pending_trips(&self.path, hmac_key);
378        for trip in trips {
379            let trip_ts = i64::try_from(trip.timestamp).unwrap_or(i64::MAX);
380            let reason = format!(
381                "rate limit threshold reached after {} failed attempts",
382                trip.failed_attempts
383            );
384            let mut entry = AuditEntry::new(AuditEventType::RateLimitTripped, audit.last_hash())
385                .with_success(false)
386                .with_reason(&reason);
387            entry.timestamp = trip_ts;
388            if let Err(e) = audit.log(entry, data_key) {
389                tracing::warn!(error = %e, "failed to flush RateLimitTripped audit entry on hidden vault");
390            }
391        }
392
393        // Emit VaultUnlock to mirror `Keep::unlock`.
394        let unlock_entry = AuditEntry::new(AuditEventType::VaultUnlock, audit.last_hash());
395        if let Err(e) = audit.log(unlock_entry, data_key) {
396            tracing::warn!(error = %e, "failed to log VaultUnlock audit entry on hidden vault");
397        }
398
399        self.outer_audit = Some(audit);
400        Ok(())
401    }
402
403    fn try_unlock_hidden(&mut self, password: &str) -> Result<()> {
404        if self.hidden_key.is_some() {
405            return Ok(());
406        }
407
408        let vault_path = self.path.join("keep.vault");
409        let mut file = File::open(&vault_path)?;
410        file.seek(SeekFrom::Start(HIDDEN_HEADER_OFFSET))?;
411
412        let mut hidden_area = [0u8; HEADER_SIZE];
413        file.read_exact(&mut hidden_area)?;
414
415        let kdf_salt = derive_hidden_salt(&self.outer_header.salt, password);
416        let master_key = crypto::derive_key(
417            password.as_bytes(),
418            &kdf_salt,
419            self.outer_header.argon2_params(),
420        )?;
421        let header_enc_key = crypto::derive_subkey(&master_key, b"keep-hidden-header-enc")?;
422
423        const ENCRYPTED_HEADER_SIZE: usize = HiddenHeader::COMPACT_SIZE + crypto::TAG_SIZE;
424        let encrypted = EncryptedData {
425            nonce: hidden_area[..24].try_into().expect("slice is 24 bytes"),
426            ciphertext: hidden_area[24..24 + ENCRYPTED_HEADER_SIZE].to_vec(),
427        };
428
429        let decrypted =
430            crypto::decrypt(&encrypted, &header_enc_key).map_err(|_| KeepError::InvalidPassword)?;
431
432        let decrypted_bytes = decrypted.as_slice()?;
433        let hidden_header = HiddenHeader::from_bytes_compact(&decrypted_bytes)?;
434
435        if !hidden_header.verify_checksum() {
436            return Err(KeepError::InvalidPassword);
437        }
438
439        let data_key_enc = crypto::derive_subkey(&master_key, b"keep-hidden-header")?;
440        let data_encrypted = EncryptedData {
441            nonce: hidden_header.nonce,
442            ciphertext: hidden_header.encrypted_data_key.to_vec(),
443        };
444
445        let data_key_bytes = crypto::decrypt(&data_encrypted, &data_key_enc)?;
446        let data_key_slice = data_key_bytes.as_slice()?;
447        self.hidden_key = Some(SecretKey::from_slice(&data_key_slice)?);
448        self.hidden_header = Some(hidden_header);
449        self.active_volume = Some(VolumeType::Hidden);
450
451        Ok(())
452    }
453
454    /// Unlock the hidden volume.
455    pub fn unlock_hidden(&mut self, password: &str) -> Result<()> {
456        if self.hidden_key.is_some() {
457            return Ok(());
458        }
459
460        let hmac_key = rate_limit::derive_hmac_key(&self.outer_header.salt);
461        if let Err(remaining) = rate_limit::check_rate_limit(&self.path, &hmac_key) {
462            return Err(KeepError::RateLimited(remaining.as_secs().max(1)));
463        }
464
465        match self.try_unlock_hidden(password) {
466            Ok(()) => {
467                rate_limit::record_success(&self.path);
468                Ok(())
469            }
470            Err(e) => {
471                if matches!(e, KeepError::InvalidPassword | KeepError::DecryptionFailed) {
472                    rate_limit::record_failure(&self.path, &hmac_key);
473                }
474                Err(e)
475            }
476        }
477    }
478
479    /// Unlock whichever volume the password matches.
480    /// Returns the type that was unlocked.
481    pub fn unlock(&mut self, password: &str) -> Result<VolumeType> {
482        let hmac_key = rate_limit::derive_hmac_key(&self.outer_header.salt);
483        if let Err(remaining) = rate_limit::check_rate_limit(&self.path, &hmac_key) {
484            return Err(KeepError::RateLimited(remaining.as_secs().max(1)));
485        }
486
487        let outer_result = self.try_unlock_outer(password);
488        let hidden_result = self.try_unlock_hidden(password);
489
490        match (outer_result, hidden_result) {
491            (Ok(()), _) => {
492                self.active_volume = Some(VolumeType::Outer);
493                rate_limit::record_success(&self.path);
494                // #520: the auto-detect path must flush trips and attach the
495                // outer audit log too, otherwise `audit_*` accessors see an
496                // unlocked vault with `outer_audit == None`. Mirror `unlock_outer`.
497                self.attach_outer_audit(&hmac_key)?;
498                Ok(VolumeType::Outer)
499            }
500            (Err(_), Ok(())) => {
501                self.active_volume = Some(VolumeType::Hidden);
502                rate_limit::record_success(&self.path);
503                Ok(VolumeType::Hidden)
504            }
505            (Err(outer_err), Err(hidden_err)) => {
506                let is_auth_error = |e: &KeepError| {
507                    matches!(e, KeepError::InvalidPassword | KeepError::DecryptionFailed)
508                };
509
510                if !is_auth_error(&outer_err) {
511                    return Err(outer_err);
512                }
513                if !is_auth_error(&hidden_err) {
514                    return Err(hidden_err);
515                }
516
517                rate_limit::record_failure(&self.path, &hmac_key);
518                Err(KeepError::InvalidPassword)
519            }
520        }
521    }
522
523    /// Lock and zeroize all keys.
524    pub fn lock(&mut self) {
525        self.outer_key = None;
526        self.hidden_key = None;
527        self.hidden_header = None;
528        self.active_volume = None;
529        self.outer_db = None;
530        self.outer_audit = None;
531    }
532
533    /// Returns true if any volume is unlocked.
534    pub fn is_unlocked(&self) -> bool {
535        self.active_volume.is_some()
536    }
537
538    /// The data encryption key for the active volume.
539    pub fn data_key(&self) -> Option<&SecretKey> {
540        match self.active_volume {
541            Some(VolumeType::Hidden) => self.hidden_key.as_ref(),
542            Some(VolumeType::Outer) => self.outer_key.as_ref(),
543            None => None,
544        }
545    }
546
547    /// The active volume type, if unlocked.
548    pub fn active_volume(&self) -> Option<VolumeType> {
549        self.active_volume
550    }
551
552    /// Returns true if the hidden volume is unlocked.
553    pub fn is_hidden_unlocked(&self) -> bool {
554        self.hidden_key.is_some()
555    }
556
557    /// Store a key record in the active volume.
558    pub fn store_key(&self, record: &KeyRecord) -> Result<()> {
559        match self.active_volume {
560            Some(VolumeType::Outer) => self.store_key_outer(record),
561            Some(VolumeType::Hidden) => self.store_key_hidden(record),
562            None => Err(KeepError::Locked),
563        }
564    }
565
566    fn store_key_outer(&self, record: &KeyRecord) -> Result<()> {
567        let data_key = self.outer_key.as_ref().ok_or(KeepError::Locked)?;
568        let db = self.outer_db.as_ref().ok_or(KeepError::Locked)?;
569
570        let serialized = bincode::options()
571            .with_fixint_encoding()
572            .serialize(record)?;
573
574        let encrypted = crypto::encrypt(&serialized, data_key)?;
575        let encrypted_bytes = encrypted.to_bytes();
576
577        let wtxn = db.begin_write()?;
578        {
579            let mut table = wtxn.open_table(KEYS_TABLE)?;
580            table.insert(record.id.as_slice(), encrypted_bytes.as_slice())?;
581        }
582        wtxn.commit()?;
583
584        Ok(())
585    }
586
587    fn store_key_hidden(&self, record: &KeyRecord) -> Result<()> {
588        let data_key = self.hidden_key.as_ref().ok_or(KeepError::Locked)?;
589        let hidden_header = self.hidden_header.as_ref().ok_or(KeepError::Locked)?;
590
591        let mut records = self.load_hidden_records()?;
592        records.retain(|r| r.id != record.id);
593        records.push(record.clone());
594
595        self.write_hidden_records(&records, data_key, hidden_header)
596    }
597
598    fn load_hidden_records(&self) -> Result<Vec<KeyRecord>> {
599        let data_key = self.hidden_key.as_ref().ok_or(KeepError::Locked)?;
600        let hidden_header = self.hidden_header.as_ref().ok_or(KeepError::Locked)?;
601
602        let vault_path = self.path.join("keep.vault");
603        let mut file = File::open(&vault_path)?;
604        file.seek(SeekFrom::Start(hidden_header.hidden_data_offset))?;
605
606        const ENCRYPTED_LENGTH_SIZE: usize = crypto::NONCE_SIZE + 8 + crypto::TAG_SIZE;
607        let mut length_blob = [0u8; ENCRYPTED_LENGTH_SIZE];
608        if file.read_exact(&mut length_blob).is_err() {
609            return Ok(Vec::new());
610        }
611
612        let data_size = (|| -> Option<u64> {
613            let encrypted_length = EncryptedData::from_bytes(&length_blob).ok()?;
614            let decrypted_length = crypto::decrypt(&encrypted_length, data_key).ok()?;
615            let length_bytes = decrypted_length.as_slice().ok()?;
616            let arr: [u8; 8] = length_bytes.as_slice().try_into().ok()?;
617            Some(u64::from_le_bytes(arr))
618        })();
619
620        let Some(data_size) = data_size else {
621            return Ok(Vec::new());
622        };
623
624        let max_data_size = hidden_header
625            .hidden_data_size
626            .saturating_sub(ENCRYPTED_LENGTH_SIZE as u64);
627        if data_size == 0 || data_size > max_data_size {
628            return Ok(Vec::new());
629        }
630
631        let mut encrypted_data = vec![0u8; data_size as usize];
632        file.read_exact(&mut encrypted_data)?;
633
634        let records = (|| -> Option<Vec<KeyRecord>> {
635            let encrypted = EncryptedData::from_bytes(&encrypted_data).ok()?;
636            let decrypted = crypto::decrypt(&encrypted, data_key).ok()?;
637            let decrypted_bytes = decrypted.as_slice().ok()?;
638            bincode::options()
639                .with_fixint_encoding()
640                .allow_trailing_bytes()
641                .with_limit(MAX_RECORD_SIZE)
642                .deserialize(&decrypted_bytes)
643                .ok()
644        })();
645
646        Ok(records.unwrap_or_default())
647    }
648
649    fn write_hidden_records(
650        &self,
651        records: &[KeyRecord],
652        data_key: &SecretKey,
653        hidden_header: &HiddenHeader,
654    ) -> Result<()> {
655        let serialized = bincode::options()
656            .with_fixint_encoding()
657            .serialize(records)?;
658        let encrypted = crypto::encrypt(&serialized, data_key)?;
659        let encrypted_bytes = encrypted.to_bytes();
660
661        let length_bytes = (encrypted_bytes.len() as u64).to_le_bytes();
662        let encrypted_length = crypto::encrypt(&length_bytes, data_key)?;
663        let encrypted_length_bytes = encrypted_length.to_bytes();
664
665        let total_size = encrypted_length_bytes.len() + encrypted_bytes.len();
666        if total_size as u64 > hidden_header.hidden_data_size {
667            return Err(StorageError::hidden_volume_full().into());
668        }
669
670        let vault_path = self.path.join("keep.vault");
671        let mut file = OpenOptions::new().write(true).open(&vault_path)?;
672        file.seek(SeekFrom::Start(hidden_header.hidden_data_offset))?;
673
674        file.write_all(&encrypted_length_bytes)?;
675        file.write_all(&encrypted_bytes)?;
676
677        let remaining = hidden_header.hidden_data_size - total_size as u64;
678        write_random_padding(&mut file, remaining)?;
679
680        file.sync_all()?;
681        Ok(())
682    }
683
684    /// List all keys in the active volume.
685    pub fn list_keys(&self) -> Result<Vec<KeyRecord>> {
686        match self.active_volume {
687            Some(VolumeType::Outer) => self.list_keys_outer(),
688            Some(VolumeType::Hidden) => self.load_hidden_records(),
689            None => Err(KeepError::Locked),
690        }
691    }
692
693    fn list_keys_outer(&self) -> Result<Vec<KeyRecord>> {
694        let data_key = self.outer_key.as_ref().ok_or(KeepError::Locked)?;
695        let db = self.outer_db.as_ref().ok_or(KeepError::Locked)?;
696
697        let rtxn = db.begin_read()?;
698        let table = rtxn.open_table(KEYS_TABLE)?;
699
700        let mut records = Vec::new();
701
702        for result in table.iter()? {
703            let (_, encrypted_bytes) = result?;
704            let encrypted = EncryptedData::from_bytes(encrypted_bytes.value())?;
705            let decrypted = crypto::decrypt(&encrypted, data_key)?;
706
707            let decrypted_bytes = decrypted.as_slice()?;
708            let record: KeyRecord = bincode::options()
709                .with_fixint_encoding()
710                .allow_trailing_bytes()
711                .with_limit(MAX_RECORD_SIZE)
712                .deserialize(&decrypted_bytes)?;
713
714            records.push(record);
715        }
716
717        Ok(records)
718    }
719
720    /// Delete a key from the active volume.
721    pub fn delete_key(&self, id: &[u8; 32]) -> Result<()> {
722        match self.active_volume {
723            Some(VolumeType::Outer) => self.delete_key_outer(id),
724            Some(VolumeType::Hidden) => self.delete_key_hidden(id),
725            None => Err(KeepError::Locked),
726        }
727    }
728
729    fn delete_key_outer(&self, id: &[u8; 32]) -> Result<()> {
730        let db = self.outer_db.as_ref().ok_or(KeepError::Locked)?;
731
732        let wtxn = db.begin_write()?;
733        let existed;
734        {
735            let mut table = wtxn.open_table(KEYS_TABLE)?;
736            existed = table.remove(id.as_slice())?.is_some();
737        }
738        wtxn.commit()?;
739
740        if !existed {
741            return Err(KeepError::KeyNotFound(hex::encode(id)));
742        }
743
744        Ok(())
745    }
746
747    fn delete_key_hidden(&self, id: &[u8; 32]) -> Result<()> {
748        let data_key = self.hidden_key.as_ref().ok_or(KeepError::Locked)?;
749        let hidden_header = self.hidden_header.as_ref().ok_or(KeepError::Locked)?;
750
751        let mut records = self.load_hidden_records()?;
752        let original_len = records.len();
753        records.retain(|r| &r.id != id);
754
755        if records.len() == original_len {
756            return Err(KeepError::KeyNotFound(hex::encode(id)));
757        }
758
759        self.write_hidden_records(&records, data_key, hidden_header)
760    }
761
762    /// Persist a relay configuration on the outer volume.
763    ///
764    /// Only the outer volume is currently supported; hidden-volume relay-config
765    /// storage is a documented follow-up so the headless NIP-46 bunker on the
766    /// outer side can load pre-grants without leaking the existence of a
767    /// hidden volume into the relay layer.
768    pub fn store_relay_config(&self, config: &RelayConfig) -> Result<()> {
769        match self.active_volume {
770            Some(VolumeType::Outer) => {}
771            Some(VolumeType::Hidden) => {
772                return Err(KeepError::NotImplemented(
773                    "relay config storage on the hidden volume is not yet implemented".into(),
774                ));
775            }
776            None => return Err(KeepError::Locked),
777        }
778        let (data_key, db) = self.outer_relay_handles()?;
779
780        let normalized = config.clone().normalize()?;
781        let encrypted_bytes = relay::encode_relay_config(&normalized, data_key)?;
782
783        let wtxn = db.begin_write()?;
784        {
785            let mut table = wtxn.open_table(RELAY_CONFIGS_TABLE)?;
786            table.insert(
787                normalized.group_pubkey.as_slice(),
788                encrypted_bytes.as_slice(),
789            )?;
790        }
791        wtxn.commit()?;
792        Ok(())
793    }
794
795    /// Load a relay configuration from the outer volume.
796    ///
797    /// Hidden volume callers get `Ok(None)` so a hidden-vault headless bunker
798    /// degrades cleanly to the interactive-approval path until hidden-volume
799    /// relay-config storage is implemented.
800    pub fn get_relay_config(&self, group_pubkey: &[u8; 32]) -> Result<Option<RelayConfig>> {
801        match self.active_volume {
802            Some(VolumeType::Outer) => {}
803            Some(VolumeType::Hidden) => return Ok(None),
804            None => return Err(KeepError::Locked),
805        }
806        let (data_key, db) = self.outer_relay_handles()?;
807
808        let rtxn = db.begin_read()?;
809        let table = match rtxn.open_table(RELAY_CONFIGS_TABLE) {
810            Ok(t) => t,
811            Err(redb::TableError::TableDoesNotExist(_)) => return Ok(None),
812            Err(e) => return Err(e.into()),
813        };
814        let Some(entry) = table.get(group_pubkey.as_slice())? else {
815            return Ok(None);
816        };
817        Ok(Some(relay::decode_relay_config(entry.value(), data_key)?))
818    }
819
820    /// Load a relay configuration or return a fresh default for `group_pubkey`.
821    pub fn get_relay_config_or_default(&self, group_pubkey: &[u8; 32]) -> Result<RelayConfig> {
822        Ok(self
823            .get_relay_config(group_pubkey)?
824            .unwrap_or_else(|| RelayConfig::with_defaults(*group_pubkey)))
825    }
826
827    fn outer_relay_handles(&self) -> Result<(&SecretKey, &Database)> {
828        let data_key = self.outer_key.as_ref().ok_or(KeepError::Locked)?;
829        let db = self.outer_db.as_ref().ok_or(KeepError::Locked)?;
830        Ok((data_key, db))
831    }
832
833    /// The vault directory path.
834    pub fn path(&self) -> &Path {
835        &self.path
836    }
837
838    /// Read every audit entry stored under the outer data key. Hidden-vault
839    /// scope is deliberately limited to the outer volume (#520, paralleling
840    /// the #507 relay-config decision); a hidden-active session has no
841    /// audit log of its own and returns `Ok(vec![])` rather than reading
842    /// the outer log's contents.
843    pub fn audit_read_all(&self) -> Result<Vec<crate::audit::AuditEntry>> {
844        match self.active_volume {
845            Some(VolumeType::Outer) => {}
846            Some(VolumeType::Hidden) => return Ok(Vec::new()),
847            None => return Err(KeepError::Locked),
848        }
849        let (data_key, audit) = self.outer_audit_handles()?;
850        audit.read_all(data_key)
851    }
852
853    /// Export the outer-volume audit log as JSON. Hidden-active sessions
854    /// return an empty array rather than the outer log's contents, matching
855    /// the deniability boundary `audit_read_all` enforces.
856    pub fn audit_export(&self) -> Result<String> {
857        match self.active_volume {
858            Some(VolumeType::Outer) => {}
859            Some(VolumeType::Hidden) => return Ok("[]".to_string()),
860            None => return Err(KeepError::Locked),
861        }
862        let (data_key, audit) = self.outer_audit_handles()?;
863        audit.export(data_key)
864    }
865
866    /// Verify the outer-volume audit log's hash chain. Hidden-active sessions
867    /// have no log of their own and return `Ok(true)` (vacuously valid).
868    pub fn audit_verify_chain(&self) -> Result<bool> {
869        match self.active_volume {
870            Some(VolumeType::Outer) => {}
871            Some(VolumeType::Hidden) => return Ok(true),
872            None => return Err(KeepError::Locked),
873        }
874        let (data_key, audit) = self.outer_audit_handles()?;
875        audit.verify_chain(data_key)
876    }
877
878    /// Resolve the outer data key and audit log for an outer-active session.
879    /// A `None` `outer_audit` despite an unlocked outer volume means
880    /// `attach_outer_audit` failed to open the on-disk audit log earlier and
881    /// logged the underlying error. Surface a descriptive error rather than
882    /// the misleading `Locked` so callers can distinguish "not unlocked yet"
883    /// from "unlocked but audit log unavailable" (see PR #540 review).
884    fn outer_audit_handles(&self) -> Result<(&SecretKey, &crate::audit::AuditLog)> {
885        let data_key = self.outer_key.as_ref().ok_or(KeepError::Locked)?;
886        let audit = self.outer_audit.as_ref().ok_or_else(|| {
887            KeepError::Other(
888                "outer-volume audit log is unavailable; check earlier logs for the underlying open failure (the unlock succeeded but `attach_outer_audit` did not attach an audit log)".into(),
889            )
890        })?;
891        Ok((data_key, audit))
892    }
893
894    /// Set the retention policy on the outer-volume audit log. No-op when
895    /// the active volume is hidden.
896    pub fn audit_set_retention(&mut self, policy: crate::audit::RetentionPolicy) {
897        if !matches!(self.active_volume, Some(VolumeType::Outer)) {
898            return;
899        }
900        if let Some(audit) = self.outer_audit.as_mut() {
901            audit.set_retention(policy);
902        }
903    }
904
905    /// Apply the retention policy on the outer-volume audit log. Errors on
906    /// hidden-active sessions since no audit log exists there.
907    pub fn audit_apply_retention(&mut self) -> Result<usize> {
908        match self.active_volume {
909            Some(VolumeType::Outer) => {}
910            Some(VolumeType::Hidden) => {
911                return Err(KeepError::Other(
912                    "audit retention is not yet supported on the hidden volume".into(),
913                ));
914            }
915            None => return Err(KeepError::Locked),
916        }
917        let data_key = self.outer_key.as_ref().ok_or(KeepError::Locked)?;
918        let audit = self.outer_audit.as_mut().ok_or_else(|| {
919            KeepError::Other(
920                "outer-volume audit log is unavailable; check earlier logs for the underlying open failure (the unlock succeeded but `attach_outer_audit` did not attach an audit log)".into(),
921            )
922        })?;
923        audit.apply_retention(data_key)
924    }
925}
926
927impl Drop for HiddenStorage {
928    fn drop(&mut self) {
929        self.lock();
930    }
931}
932
933#[cfg(test)]
934mod tests {
935    use super::*;
936    use crate::keys::KeyType;
937    use tempfile::tempdir;
938
939    #[test]
940    fn test_create_and_unlock_outer() {
941        let dir = tempdir().unwrap();
942        let path = dir.path().join("test-hidden");
943
944        {
945            let storage = HiddenStorage::create(
946                &path,
947                "outer_password",
948                Some("hidden_password"),
949                10 * 1024 * 1024,
950                0.2,
951                Argon2Params::TESTING,
952            )
953            .unwrap();
954
955            assert!(storage.active_volume() == Some(VolumeType::Outer));
956        }
957
958        {
959            let mut storage = HiddenStorage::open(&path).unwrap();
960            assert!(storage.active_volume().is_none());
961
962            storage.unlock_outer("outer_password").unwrap();
963            assert!(storage.active_volume() == Some(VolumeType::Outer));
964        }
965    }
966
967    #[test]
968    fn test_unlock_hidden() {
969        let dir = tempdir().unwrap();
970        let path = dir.path().join("test-hidden2");
971
972        HiddenStorage::create(
973            &path,
974            "outer",
975            Some("hidden"),
976            10 * 1024 * 1024,
977            0.2,
978            Argon2Params::TESTING,
979        )
980        .unwrap();
981
982        let mut storage = HiddenStorage::open(&path).unwrap();
983
984        storage.unlock_hidden("hidden").unwrap();
985        assert!(storage.active_volume() == Some(VolumeType::Hidden));
986        assert!(storage.is_hidden_unlocked());
987    }
988
989    #[test]
990    fn test_smart_unlock() {
991        let dir = tempdir().unwrap();
992        let path = dir.path().join("test-hidden3");
993
994        HiddenStorage::create(
995            &path,
996            "outer",
997            Some("hidden"),
998            10 * 1024 * 1024,
999            0.2,
1000            Argon2Params::TESTING,
1001        )
1002        .unwrap();
1003
1004        {
1005            let mut storage = HiddenStorage::open(&path).unwrap();
1006            let volume = storage.unlock("outer").unwrap();
1007            assert_eq!(volume, VolumeType::Outer);
1008        }
1009
1010        {
1011            let mut storage = HiddenStorage::open(&path).unwrap();
1012            let volume = storage.unlock("hidden").unwrap();
1013            assert_eq!(volume, VolumeType::Hidden);
1014        }
1015    }
1016
1017    #[test]
1018    fn test_wrong_password() {
1019        let dir = tempdir().unwrap();
1020        let path = dir.path().join("test-hidden4");
1021
1022        HiddenStorage::create(
1023            &path,
1024            "correct",
1025            None,
1026            10 * 1024 * 1024,
1027            0.0,
1028            Argon2Params::TESTING,
1029        )
1030        .unwrap();
1031
1032        let mut storage = HiddenStorage::open(&path).unwrap();
1033        let result = storage.unlock("wrong");
1034        assert!(result.is_err());
1035    }
1036
1037    #[test]
1038    fn test_outer_volume_key_operations() {
1039        let dir = tempdir().unwrap();
1040        let path = dir.path().join("test-hidden5");
1041
1042        let storage = HiddenStorage::create(
1043            &path,
1044            "password",
1045            None,
1046            10 * 1024 * 1024,
1047            0.0,
1048            Argon2Params::TESTING,
1049        )
1050        .unwrap();
1051
1052        let record = KeyRecord::new(
1053            crypto::random_bytes(),
1054            KeyType::Nostr,
1055            "test key".into(),
1056            vec![1, 2, 3, 4],
1057        );
1058
1059        storage.store_key(&record).unwrap();
1060
1061        let keys = storage.list_keys().unwrap();
1062        assert_eq!(keys.len(), 1);
1063        assert_eq!(keys[0].name, record.name);
1064
1065        storage.delete_key(&record.id).unwrap();
1066        let keys = storage.list_keys().unwrap();
1067        assert_eq!(keys.len(), 0);
1068    }
1069
1070    #[test]
1071    fn test_hidden_volume_key_operations() {
1072        let dir = tempdir().unwrap();
1073        let path = dir.path().join("test-hidden6");
1074
1075        HiddenStorage::create(
1076            &path,
1077            "outer",
1078            Some("hidden"),
1079            10 * 1024 * 1024,
1080            0.2,
1081            Argon2Params::TESTING,
1082        )
1083        .unwrap();
1084
1085        let mut storage = HiddenStorage::open(&path).unwrap();
1086        storage.unlock_hidden("hidden").unwrap();
1087
1088        let record = KeyRecord::new(
1089            crypto::random_bytes(),
1090            KeyType::Nostr,
1091            "hidden key".into(),
1092            vec![5, 6, 7, 8],
1093        );
1094
1095        storage.store_key(&record).unwrap();
1096
1097        let keys = storage.list_keys().unwrap();
1098        assert_eq!(keys.len(), 1);
1099        assert_eq!(keys[0].name, "hidden key");
1100
1101        storage.delete_key(&record.id).unwrap();
1102        let keys = storage.list_keys().unwrap();
1103        assert_eq!(keys.len(), 0);
1104    }
1105
1106    #[test]
1107    fn test_volume_isolation() {
1108        let dir = tempdir().unwrap();
1109        let path = dir.path().join("test-hidden7");
1110
1111        {
1112            let storage = HiddenStorage::create(
1113                &path,
1114                "outer",
1115                Some("hidden"),
1116                10 * 1024 * 1024,
1117                0.2,
1118                Argon2Params::TESTING,
1119            )
1120            .unwrap();
1121
1122            let outer_key = KeyRecord::new(
1123                crypto::random_bytes(),
1124                KeyType::Nostr,
1125                "outer key".into(),
1126                vec![1, 2, 3],
1127            );
1128            storage.store_key(&outer_key).unwrap();
1129        }
1130
1131        {
1132            let mut storage = HiddenStorage::open(&path).unwrap();
1133            storage.unlock_hidden("hidden").unwrap();
1134
1135            let hidden_key = KeyRecord::new(
1136                crypto::random_bytes(),
1137                KeyType::Nostr,
1138                "hidden key".into(),
1139                vec![4, 5, 6],
1140            );
1141            storage.store_key(&hidden_key).unwrap();
1142
1143            let hidden_keys = storage.list_keys().unwrap();
1144            assert_eq!(hidden_keys.len(), 1);
1145            assert_eq!(hidden_keys[0].name, "hidden key");
1146        }
1147
1148        {
1149            let mut storage = HiddenStorage::open(&path).unwrap();
1150            storage.unlock_outer("outer").unwrap();
1151
1152            let outer_keys = storage.list_keys().unwrap();
1153            assert_eq!(outer_keys.len(), 1);
1154            assert_eq!(outer_keys[0].name, "outer key");
1155        }
1156    }
1157
1158    #[test]
1159    fn test_sequential_key_operations() {
1160        let dir = tempdir().unwrap();
1161        let path = dir.path().join("test-sequential");
1162
1163        let storage = HiddenStorage::create(
1164            &path,
1165            "password",
1166            None,
1167            10 * 1024 * 1024,
1168            0.0,
1169            Argon2Params::TESTING,
1170        )
1171        .unwrap();
1172
1173        for i in 0..4 {
1174            let record = KeyRecord::new(
1175                crypto::random_bytes(),
1176                KeyType::Nostr,
1177                format!("key-{i}"),
1178                vec![i as u8],
1179            );
1180            storage.store_key(&record).unwrap();
1181        }
1182
1183        let keys = storage.list_keys().unwrap();
1184        assert_eq!(keys.len(), 4);
1185
1186        drop(storage);
1187
1188        let mut storage = HiddenStorage::open(&path).unwrap();
1189        storage.unlock_outer("password").unwrap();
1190        let keys = storage.list_keys().unwrap();
1191        assert_eq!(keys.len(), 4);
1192    }
1193
1194    #[test]
1195    fn test_volume_isolation_sequential() {
1196        let dir = tempdir().unwrap();
1197        let path = dir.path().join("test-isolation-sequential");
1198
1199        {
1200            let storage = HiddenStorage::create(
1201                &path,
1202                "outer",
1203                Some("hidden"),
1204                10 * 1024 * 1024,
1205                0.2,
1206                Argon2Params::TESTING,
1207            )
1208            .unwrap();
1209
1210            for i in 0..3 {
1211                let record = KeyRecord::new(
1212                    crypto::random_bytes(),
1213                    KeyType::Nostr,
1214                    format!("outer-{i}"),
1215                    vec![i as u8],
1216                );
1217                storage.store_key(&record).unwrap();
1218            }
1219        }
1220
1221        {
1222            let mut storage = HiddenStorage::open(&path).unwrap();
1223            storage.unlock_hidden("hidden").unwrap();
1224
1225            for i in 0..2 {
1226                let record = KeyRecord::new(
1227                    crypto::random_bytes(),
1228                    KeyType::Nostr,
1229                    format!("hidden-{i}"),
1230                    vec![100 + i as u8],
1231                );
1232                storage.store_key(&record).unwrap();
1233            }
1234        }
1235
1236        {
1237            let mut storage = HiddenStorage::open(&path).unwrap();
1238            storage.unlock_outer("outer").unwrap();
1239            let keys = storage.list_keys().unwrap();
1240            assert_eq!(keys.len(), 3);
1241            assert!(keys.iter().all(|k| k.name.starts_with("outer-")));
1242        }
1243
1244        {
1245            let mut storage = HiddenStorage::open(&path).unwrap();
1246            storage.unlock_hidden("hidden").unwrap();
1247            let keys = storage.list_keys().unwrap();
1248            assert_eq!(keys.len(), 2);
1249            assert!(keys.iter().all(|k| k.name.starts_with("hidden-")));
1250        }
1251    }
1252
1253    #[test]
1254    fn test_rate_limiting_outer() {
1255        let dir = tempdir().unwrap();
1256        let path = dir.path().join("test-rate-outer");
1257
1258        HiddenStorage::create(
1259            &path,
1260            "outer",
1261            Some("hidden"),
1262            10 * 1024 * 1024,
1263            0.2,
1264            Argon2Params::TESTING,
1265        )
1266        .unwrap();
1267
1268        // First 5 attempts - new storage each time to test persistence
1269        for _ in 0..5 {
1270            let mut storage = HiddenStorage::open(&path).unwrap();
1271            let result = storage.unlock_outer("wrong");
1272            assert!(result.is_err());
1273            assert!(!matches!(result, Err(KeepError::RateLimited(_))));
1274        }
1275
1276        // Attempts 6-8 on same instance for tight timing.
1277        // After 5 failures, delay=1s. After 6, delay=2s. After 7, delay=4s.
1278        // Three rapid attempts ensures we hit rate limiting even on very
1279        // slow CI runners where individual Argon2 calls take >1s.
1280        let mut storage = HiddenStorage::open(&path).unwrap();
1281        let _ = storage.unlock_outer("wrong");
1282        let _ = storage.unlock_outer("wrong");
1283        let result = storage.unlock_outer("wrong");
1284        assert!(matches!(result, Err(KeepError::RateLimited(_))));
1285    }
1286
1287    #[test]
1288    fn test_rate_limiting_hidden() {
1289        let dir = tempdir().unwrap();
1290        let path = dir.path().join("test-rate-hidden");
1291
1292        HiddenStorage::create(
1293            &path,
1294            "outer",
1295            Some("hidden"),
1296            10 * 1024 * 1024,
1297            0.2,
1298            Argon2Params::TESTING,
1299        )
1300        .unwrap();
1301
1302        // First 5 attempts - new storage each time to test persistence
1303        for _ in 0..5 {
1304            let mut storage = HiddenStorage::open(&path).unwrap();
1305            let result = storage.unlock_hidden("wrong");
1306            assert!(result.is_err());
1307            assert!(!matches!(result, Err(KeepError::RateLimited(_))));
1308        }
1309
1310        // Attempts 6-8 on same instance for tight timing.
1311        // After 5 failures, delay=1s. After 6, delay=2s. After 7, delay=4s.
1312        // Three rapid attempts ensures we hit rate limiting even on very
1313        // slow CI runners where individual Argon2 calls take >1s.
1314        let mut storage = HiddenStorage::open(&path).unwrap();
1315        let _ = storage.unlock_hidden("wrong");
1316        let _ = storage.unlock_hidden("wrong");
1317        let result = storage.unlock_hidden("wrong");
1318        assert!(matches!(result, Err(KeepError::RateLimited(_))));
1319    }
1320
1321    #[test]
1322    fn test_rate_limiting_combined_unlock() {
1323        let dir = tempdir().unwrap();
1324        let path = dir.path().join("test-rate-combined");
1325
1326        HiddenStorage::create(
1327            &path,
1328            "outer",
1329            Some("hidden"),
1330            10 * 1024 * 1024,
1331            0.2,
1332            Argon2Params::TESTING,
1333        )
1334        .unwrap();
1335
1336        // First 5 attempts - new storage each time to test persistence
1337        for _ in 0..5 {
1338            let mut storage = HiddenStorage::open(&path).unwrap();
1339            let result = storage.unlock("wrong");
1340            assert!(result.is_err());
1341            assert!(!matches!(result, Err(KeepError::RateLimited(_))));
1342        }
1343
1344        // Attempts 6-8 on same instance for tight timing.
1345        // After 5 failures, delay=1s. After 6, delay=2s. After 7, delay=4s.
1346        // Three rapid attempts ensures we hit rate limiting even on very
1347        // slow CI runners where individual Argon2 calls take >1s.
1348        let mut storage = HiddenStorage::open(&path).unwrap();
1349        let _ = storage.unlock("wrong");
1350        let _ = storage.unlock("wrong");
1351        let result = storage.unlock("wrong");
1352        assert!(matches!(result, Err(KeepError::RateLimited(_))));
1353    }
1354
1355    #[test]
1356    fn relay_config_round_trip_outer() {
1357        use crate::relay::{
1358            RelayConfig, StoredBunkerPermission, StoredPermissionDuration, GLOBAL_RELAY_KEY,
1359        };
1360
1361        let dir = tempdir().unwrap();
1362        let path = dir.path().join("test-relay-cfg-outer");
1363
1364        HiddenStorage::create(
1365            &path,
1366            "outer",
1367            Some("hidden"),
1368            10 * 1024 * 1024,
1369            0.2,
1370            Argon2Params::TESTING,
1371        )
1372        .unwrap();
1373
1374        let mut storage = HiddenStorage::open(&path).unwrap();
1375        storage.unlock_outer("outer").unwrap();
1376
1377        // Default until first write.
1378        let initial = storage
1379            .get_relay_config_or_default(&GLOBAL_RELAY_KEY)
1380            .unwrap();
1381        assert!(initial.bunker_permissions.is_empty());
1382
1383        let mut cfg = RelayConfig::with_defaults(GLOBAL_RELAY_KEY);
1384        cfg.bunker_permissions.push(StoredBunkerPermission {
1385            pubkey_hex: "a".repeat(64),
1386            name: "client".to_string(),
1387            permissions: 0b1111,
1388            auto_approve_kinds: vec![1, 7],
1389            duration: StoredPermissionDuration::Forever,
1390            connected_at: 100,
1391            timed_kind_grants: Vec::new(),
1392            explicitly_remembered: None,
1393        });
1394        cfg.auto_approve_kinds = vec![22242];
1395
1396        storage.store_relay_config(&cfg).unwrap();
1397
1398        let loaded = storage
1399            .get_relay_config(&GLOBAL_RELAY_KEY)
1400            .unwrap()
1401            .expect("stored config should round-trip");
1402        assert_eq!(loaded.bunker_permissions.len(), 1);
1403        assert_eq!(loaded.bunker_permissions[0].name, "client");
1404        assert_eq!(loaded.auto_approve_kinds, vec![22242]);
1405    }
1406
1407    #[test]
1408    fn relay_config_returns_none_on_hidden_volume() {
1409        use crate::relay::GLOBAL_RELAY_KEY;
1410
1411        let dir = tempdir().unwrap();
1412        let path = dir.path().join("test-relay-cfg-hidden");
1413
1414        HiddenStorage::create(
1415            &path,
1416            "outer",
1417            Some("hidden"),
1418            10 * 1024 * 1024,
1419            0.2,
1420            Argon2Params::TESTING,
1421        )
1422        .unwrap();
1423
1424        let mut storage = HiddenStorage::open(&path).unwrap();
1425        storage.unlock_hidden("hidden").unwrap();
1426
1427        // Hidden-active reads return Ok(None) so headless callers can degrade
1428        // cleanly until hidden-volume scope is implemented.
1429        let result = storage.get_relay_config(&GLOBAL_RELAY_KEY).unwrap();
1430        assert!(result.is_none());
1431
1432        // Writes from a hidden-active session are explicitly refused so they
1433        // never silently land in outer storage and leak hidden-volume activity.
1434        let cfg = crate::relay::RelayConfig::with_defaults(GLOBAL_RELAY_KEY);
1435        assert!(storage.store_relay_config(&cfg).is_err());
1436    }
1437
1438    #[test]
1439    fn relay_config_round_trip_persists_across_open() {
1440        use crate::relay::{RelayConfig, GLOBAL_RELAY_KEY};
1441
1442        let dir = tempdir().unwrap();
1443        let path = dir.path().join("test-relay-cfg-reopen");
1444
1445        HiddenStorage::create(
1446            &path,
1447            "outer",
1448            None,
1449            10 * 1024 * 1024,
1450            0.0,
1451            Argon2Params::TESTING,
1452        )
1453        .unwrap();
1454
1455        {
1456            let mut storage = HiddenStorage::open(&path).unwrap();
1457            storage.unlock_outer("outer").unwrap();
1458            let mut cfg = RelayConfig::with_defaults(GLOBAL_RELAY_KEY);
1459            cfg.auto_approve_kinds = vec![1, 2, 3];
1460            storage.store_relay_config(&cfg).unwrap();
1461        }
1462        {
1463            let mut storage = HiddenStorage::open(&path).unwrap();
1464            storage.unlock_outer("outer").unwrap();
1465            let loaded = storage
1466                .get_relay_config(&GLOBAL_RELAY_KEY)
1467                .unwrap()
1468                .unwrap();
1469            assert_eq!(loaded.auto_approve_kinds, vec![1, 2, 3]);
1470        }
1471    }
1472
1473    /// Pin that hidden-vault outer unlock surfaces the #422 lock-holder hint
1474    /// when the outer redb is already held (mirrors
1475    /// `backend::tests::second_open_surfaces_lock_holder_hint` for the
1476    /// HiddenStorage code path, which has its own retry+map_open_failure
1477    /// chain).
1478    #[test]
1479    fn hidden_outer_unlock_surfaces_lock_holder_hint() {
1480        let dir = tempdir().unwrap();
1481        let path = dir.path().join("test-locked-hidden");
1482
1483        HiddenStorage::create(
1484            &path,
1485            "outer",
1486            None,
1487            10 * 1024 * 1024,
1488            0.0,
1489            Argon2Params::TESTING,
1490        )
1491        .unwrap();
1492
1493        let mut first = HiddenStorage::open(&path).unwrap();
1494        first.unlock_outer("outer").unwrap();
1495
1496        let mut second = HiddenStorage::open(&path).unwrap();
1497        let err = match second.unlock_outer("outer") {
1498            Err(e) => e,
1499            Ok(_) => panic!("second outer unlock while first is held must fail"),
1500        };
1501        let msg = err.to_string();
1502        assert!(
1503            matches!(err, KeepError::VaultAlreadyOpen(_)),
1504            "expected VaultAlreadyOpen from map_open_failure, got {err:?}"
1505        );
1506        assert!(
1507            msg.contains("already opened by another process"),
1508            "got {msg}"
1509        );
1510        assert!(msg.contains("#422"), "got {msg}");
1511    }
1512
1513    /// #520 end-to-end on the hidden-vault outer path: trip the rate limiter
1514    /// with failed unlocks, then successfully unlock and observe the
1515    /// `RateLimitTripped` entry in the outer audit log. Mirrors the
1516    /// `rate_limit_trip_emits_audit_entry_on_next_unlock` test that proves
1517    /// this works on regular vaults.
1518    #[test]
1519    fn hidden_outer_unlock_flushes_rate_limit_trips_to_audit() {
1520        let dir = tempdir().unwrap();
1521        let path = dir.path().join("vault-trip-audit");
1522
1523        HiddenStorage::create(
1524            &path,
1525            "outer-password",
1526            None,
1527            10 * 1024 * 1024,
1528            0.0,
1529            Argon2Params::TESTING,
1530        )
1531        .unwrap();
1532
1533        // Five failed attempts trip the limiter.
1534        for _ in 0..5 {
1535            let mut storage = HiddenStorage::open(&path).unwrap();
1536            let _ = storage.unlock_outer("wrong-password");
1537        }
1538
1539        // Clear the rate-limit counter so the next attempt isn't gated by the
1540        // active back-off. The trip queue lives in a separate file the rate
1541        // limiter deliberately does NOT clear on success.
1542        crate::rate_limit::record_success(&path);
1543
1544        let mut storage = HiddenStorage::open(&path).unwrap();
1545        storage.unlock_outer("outer-password").unwrap();
1546
1547        let entries = storage.audit_read_all().unwrap();
1548        let trips: Vec<_> = entries
1549            .iter()
1550            .filter(|e| matches!(e.event_type, crate::audit::AuditEventType::RateLimitTripped))
1551            .collect();
1552        assert_eq!(
1553            trips.len(),
1554            1,
1555            "exactly one trip entry must surface after hidden-outer unlock; got {trips:#?}"
1556        );
1557        assert!(!trips[0].success, "trip entry must record success=false");
1558        assert!(
1559            trips[0]
1560                .reason
1561                .as_deref()
1562                .is_some_and(|r| r.contains("rate limit")),
1563            "trip entry must carry a descriptive reason"
1564        );
1565
1566        let trip_idx = entries
1567            .iter()
1568            .position(|e| matches!(e.event_type, crate::audit::AuditEventType::RateLimitTripped))
1569            .unwrap();
1570        let unlock_idx = entries
1571            .iter()
1572            .rposition(|e| matches!(e.event_type, crate::audit::AuditEventType::VaultUnlock))
1573            .unwrap();
1574        assert!(
1575            trip_idx < unlock_idx,
1576            "trip must precede the unlock it was observed by"
1577        );
1578
1579        assert!(storage.audit_verify_chain().unwrap());
1580    }
1581
1582    /// A hidden-active session must NOT surface the outer audit log's
1583    /// contents. Pin so a future refactor doesn't accidentally leak outer
1584    /// activity through the hidden-active read paths.
1585    #[test]
1586    fn hidden_active_audit_returns_empty() {
1587        let dir = tempdir().unwrap();
1588        let path = dir.path().join("vault-hidden-audit-empty");
1589
1590        HiddenStorage::create(
1591            &path,
1592            "outer",
1593            Some("hidden"),
1594            10 * 1024 * 1024,
1595            0.2,
1596            Argon2Params::TESTING,
1597        )
1598        .unwrap();
1599
1600        let mut storage = HiddenStorage::open(&path).unwrap();
1601        storage.unlock_hidden("hidden").unwrap();
1602
1603        assert!(storage.audit_read_all().unwrap().is_empty());
1604        assert!(storage.audit_verify_chain().unwrap());
1605        assert!(storage.audit_apply_retention().is_err());
1606        // Export must also surface the same deniability boundary — the outer
1607        // log's JSON must not appear under a hidden-active session.
1608        assert_eq!(storage.audit_export().unwrap(), "[]");
1609    }
1610
1611    /// `audit_export` on the outer-volume path must serialise the outer log
1612    /// as JSON. Pin so `keep audit export` against a hidden-init vault stops
1613    /// erroring (the explicit gap left open by PR #538 / closed here).
1614    #[test]
1615    fn hidden_outer_audit_export_returns_valid_json() {
1616        let dir = tempdir().unwrap();
1617        let path = dir.path().join("vault-outer-audit-export");
1618
1619        HiddenStorage::create(
1620            &path,
1621            "outer",
1622            None,
1623            10 * 1024 * 1024,
1624            0.0,
1625            Argon2Params::TESTING,
1626        )
1627        .unwrap();
1628
1629        let mut storage = HiddenStorage::open(&path).unwrap();
1630        storage.unlock_outer("outer").unwrap();
1631
1632        let json = storage.audit_export().unwrap();
1633        let parsed: serde_json::Value =
1634            serde_json::from_str(&json).expect("audit_export output must be valid JSON");
1635        let arr = parsed.as_array().expect("export root must be a JSON array");
1636
1637        // `AuditEventType` derives `Serialize` without a tag attribute, so a
1638        // `VaultUnlock` entry serializes as `{"event_type":"VaultUnlock", ...}`.
1639        // Pin the actual invariant — unlock emitted at least one such entry —
1640        // instead of a loose `!arr.is_empty()` check which would also pass on
1641        // a stray `RateLimitTripped` from an earlier session.
1642        let has_unlock = arr.iter().any(|entry| {
1643            entry
1644                .get("event_type")
1645                .and_then(|v| v.as_str())
1646                .is_some_and(|s| s == "VaultUnlock")
1647        });
1648        assert!(
1649            has_unlock,
1650            "expected exported audit to contain a VaultUnlock entry; got {arr:#?}"
1651        );
1652    }
1653
1654    /// Deniability boundary must hold even when the outer log is populated.
1655    /// Unlocking outer first fills `outer_key`/`outer_audit`; switching to the
1656    /// hidden volume must still yield "[]" from `audit_export`. Pins that the
1657    /// hidden-active guard, not a `None` outer key, enforces the boundary.
1658    #[test]
1659    fn hidden_active_audit_export_empty_with_populated_outer() {
1660        let dir = tempdir().unwrap();
1661        let path = dir.path().join("vault-outer-populated-then-hidden");
1662
1663        HiddenStorage::create(
1664            &path,
1665            "outer",
1666            Some("hidden"),
1667            10 * 1024 * 1024,
1668            0.2,
1669            Argon2Params::TESTING,
1670        )
1671        .unwrap();
1672
1673        let mut storage = HiddenStorage::open(&path).unwrap();
1674        storage.unlock_outer("outer").unwrap();
1675        // Outer export is non-empty here (VaultUnlock entry present).
1676        let outer_json = storage.audit_export().unwrap();
1677        let outer_parsed: serde_json::Value = serde_json::from_str(&outer_json).unwrap();
1678        assert!(!outer_parsed.as_array().unwrap().is_empty());
1679
1680        storage.unlock_hidden("hidden").unwrap();
1681        assert_eq!(storage.active_volume(), Some(VolumeType::Hidden));
1682        assert_eq!(storage.audit_export().unwrap(), "[]");
1683    }
1684
1685    /// #520 on the auto-detect `unlock()` path: tripping the limiter then
1686    /// unlocking via the dispatcher (not `unlock_outer`) must still flush the
1687    /// `RateLimitTripped` entry and attach the outer audit log. Pins the fix
1688    /// for the dispatcher arm that previously skipped `attach_outer_audit`.
1689    #[test]
1690    fn hidden_dispatch_unlock_flushes_rate_limit_trips_to_audit() {
1691        let dir = tempdir().unwrap();
1692        let path = dir.path().join("vault-dispatch-trip-audit");
1693
1694        HiddenStorage::create(
1695            &path,
1696            "outer-password",
1697            None,
1698            10 * 1024 * 1024,
1699            0.0,
1700            Argon2Params::TESTING,
1701        )
1702        .unwrap();
1703
1704        for _ in 0..5 {
1705            let mut storage = HiddenStorage::open(&path).unwrap();
1706            let _ = storage.unlock_outer("wrong-password");
1707        }
1708
1709        crate::rate_limit::record_success(&path);
1710
1711        let mut storage = HiddenStorage::open(&path).unwrap();
1712        assert_eq!(storage.unlock("outer-password").unwrap(), VolumeType::Outer);
1713
1714        let entries = storage.audit_read_all().unwrap();
1715        let trips: Vec<_> = entries
1716            .iter()
1717            .filter(|e| matches!(e.event_type, crate::audit::AuditEventType::RateLimitTripped))
1718            .collect();
1719        assert_eq!(
1720            trips.len(),
1721            1,
1722            "dispatcher unlock must flush exactly one trip entry; got {trips:#?}"
1723        );
1724        assert!(storage.audit_verify_chain().unwrap());
1725    }
1726}