Skip to main content

keep_core/
lib.rs

1// SPDX-FileCopyrightText: (C) 2026 PrivKey LLC
2// SPDX-License-Identifier: MIT
3
4#![deny(unsafe_code)]
5
6//! Sovereign key management for Nostr and Bitcoin.
7//!
8//! This crate provides encrypted key storage with the following features:
9//!
10//! - **Encrypted storage** using Redb with XChaCha20-Poly1305
11//! - **Key derivation** using Argon2id with configurable parameters
12//! - **Nostr keypair management** with nsec/npub support
13//! - **FROST threshold signatures** for distributed key management
14//! - **Hidden volumes** for plausible deniability
15//!
16//! # Example
17//!
18//! ```no_run
19//! use std::path::Path;
20//! use keep_core::Keep;
21//!
22//! // Create a new Keep
23//! let mut keep = Keep::create(Path::new("/tmp/my-keep"), "password")?;
24//!
25//! // Generate a new key
26//! let pubkey = keep.generate_key("my-key")?;
27//!
28//! // Lock when done
29//! keep.lock();
30//! # Ok::<(), keep_core::error::KeepError>(())
31//! ```
32
33#![deny(missing_docs)]
34
35/// Tamper-evident audit logging with hash chain integrity.
36pub mod audit;
37/// Pluggable storage backends.
38pub mod backend;
39/// Portable encrypted vault backup and restore.
40pub mod backup;
41/// Cryptographic primitives for encryption, key derivation, and hashing.
42pub mod crypto;
43/// Shared text-level helpers for output descriptor strings.
44pub mod descriptor;
45/// Display formatting helpers for truncation and timestamps.
46pub mod display;
47/// Multi-source entropy mixing for defense-in-depth randomness.
48pub mod entropy;
49/// Error types and result aliases.
50pub mod error;
51/// FROST threshold signature implementation.
52pub mod frost;
53/// BIP-32 unhardened child-key primitives for FROST group keys (#487).
54pub mod frost_bip32;
55/// Hidden volume storage for plausible deniability.
56pub mod hidden;
57/// In-memory keyring for unlocked keys.
58pub mod keyring;
59/// Key types and Nostr keypair operations.
60pub mod keys;
61pub mod migration;
62
63/// BIP-39 mnemonic generation and validation.
64pub mod mnemonic;
65/// NIP-06 key derivation from mnemonic seed phrase.
66pub mod nip06;
67/// Threshold-OPRF unlock primitive (frost-gate v2). Opt-in via the `oprf` feature.
68#[cfg(feature = "oprf")]
69pub mod oprf;
70pub(crate) mod rate_limit;
71/// Relay configuration for FROST shares.
72pub mod relay;
73mod rotation;
74/// Arbitrary-secret records (passwords, API tokens, notes) stored in the vault.
75pub mod secret;
76/// Persistent encrypted storage backend.
77pub mod storage;
78/// Ephemeral time-limited secret vault.
79pub mod vault;
80/// Wallet descriptor types for FROST group spending policies.
81pub mod wallet;
82
83use std::path::{Path, PathBuf};
84
85use tracing::debug;
86use zeroize::Zeroizing;
87
88use crate::audit::{
89    AuditEntry, AuditEventType, AuditLog, RetentionPolicy, SigningAuditEntry, SigningAuditLog,
90};
91use crate::crypto::{Argon2Params, SecretKey};
92use crate::error::{KeepError, Result};
93use crate::frost::{ShareExport, SharePackage, StoredShare, ThresholdConfig, TrustedDealer};
94use crate::keyring::Keyring;
95use crate::keys::{KeyRecord, KeyType, NostrKeypair};
96pub use crate::relay::{PeerPolicyEntry, RelayConfig, GLOBAL_RELAY_KEY};
97pub use crate::storage::ProxyConfig;
98use crate::storage::Storage;
99pub use crate::storage::{ReplicatedApply, StatePublisher};
100pub use crate::wallet::{DeviceRegistration, WalletDescriptor};
101
102/// The main Keep type for encrypted key management.
103pub struct Keep {
104    storage: Storage,
105    keyring: Keyring,
106    audit: Option<AuditLog>,
107    signing_audit: Option<SigningAuditLog>,
108}
109
110impl Keep {
111    /// Install the keep-state replication sink on the underlying storage (keep-web wires this to a
112    /// publisher that ships each vault-state change to the state relay). See [`StatePublisher`].
113    pub fn set_state_publisher(&self, publisher: std::sync::Arc<dyn StatePublisher>) {
114        self.storage.set_state_publisher(publisher);
115    }
116
117    /// Apply a record replicated from a peer into storage (the standby consumer side). Delegates to
118    /// [`Storage::apply_replicated_record`]; never echoes back to the relay.
119    pub fn apply_replicated_record(
120        &self,
121        table: &str,
122        record_id: &str,
123        encrypted: &[u8],
124        created_at: u64,
125        now: u64,
126    ) -> Result<ReplicatedApply> {
127        self.storage
128            .apply_replicated_record(table, record_id, encrypted, created_at, now)
129    }
130
131    /// Apply a replicated delete (tombstone) from a peer. `now` is local wall-clock, used to reject an
132    /// implausibly future-dated event (see [`Storage::apply_replicated_delete`]).
133    pub fn apply_replicated_delete(
134        &self,
135        table: &str,
136        record_id: &str,
137        created_at: u64,
138        now: u64,
139    ) -> Result<ReplicatedApply> {
140        self.storage
141            .apply_replicated_delete(table, record_id, created_at, now)
142    }
143
144    /// The persisted rollback high-water-mark for one replicated record's d-tag (`None` if never
145    /// applied), for seeding the publisher's per-d-tag floor. See [`Storage::state_version`].
146    pub fn state_version(&self, table: &str, record_id: &str) -> Result<Option<u64>> {
147        self.storage.state_version(table, record_id)
148    }
149
150    /// Snapshot all replicable records for the keep-state publisher to replay at startup, so records
151    /// written before the replication hook was installed still reach a fresh standby. See
152    /// [`Storage::snapshot_replicable_records`].
153    pub fn snapshot_replicable_records(&self) -> Result<Vec<(&'static str, String, Vec<u8>)>> {
154        self.storage.snapshot_replicable_records()
155    }
156
157    /// Create a new Keep with the given password.
158    ///
159    /// # Example
160    ///
161    /// ```no_run
162    /// use std::path::Path;
163    /// use keep_core::Keep;
164    ///
165    /// let keep = Keep::create(Path::new("/tmp/my-keep"), "password")?;
166    /// assert!(keep.is_unlocked());
167    /// # Ok::<(), keep_core::error::KeepError>(())
168    /// ```
169    ///
170    /// # Errors
171    ///
172    /// Returns [`KeepError::AlreadyExists`] if a Keep already exists at the path.
173    pub fn create(path: &Path, password: &str) -> Result<Self> {
174        Self::create_with_params(path, password, Argon2Params::DEFAULT)
175    }
176
177    /// Create a new Keep with custom Argon2 parameters.
178    pub fn create_with_params(path: &Path, password: &str, params: Argon2Params) -> Result<Self> {
179        let storage = Storage::create(path, password, params)?;
180        Ok(Self {
181            storage,
182            keyring: Keyring::new(),
183            audit: None,
184            signing_audit: None,
185        })
186    }
187
188    /// Like [`Self::create_with_params`] but seeds a shared record-encryption key, so every node in a
189    /// cluster shares one vault key (keep-state replication) and a standby decrypts what the active
190    /// shipped. Each node still wraps the key under its own password+salt.
191    pub fn create_with_shared_data_key(
192        path: &Path,
193        password: &str,
194        params: Argon2Params,
195        data_key: Zeroizing<[u8; crypto::KEY_SIZE]>,
196    ) -> Result<Self> {
197        let storage = Storage::create_with_shared_data_key(path, password, params, data_key)?;
198        Ok(Self {
199            storage,
200            keyring: Keyring::new(),
201            audit: None,
202            signing_audit: None,
203        })
204    }
205
206    /// Open an existing Keep.
207    ///
208    /// # Example
209    ///
210    /// ```no_run
211    /// use std::path::Path;
212    /// use keep_core::Keep;
213    ///
214    /// let mut keep = Keep::open(Path::new("~/.keep"))?;
215    /// keep.unlock("password")?;
216    /// # Ok::<(), keep_core::error::KeepError>(())
217    /// ```
218    ///
219    /// # Errors
220    ///
221    /// Returns [`KeepError::NotFound`] if no Keep exists at the path.
222    pub fn open(path: &Path) -> Result<Self> {
223        let storage = Storage::open(path)?;
224        Ok(Self {
225            storage,
226            keyring: Keyring::new(),
227            audit: None,
228            signing_audit: None,
229        })
230    }
231
232    /// Unlock with the given password.
233    ///
234    /// # Errors
235    ///
236    /// Returns [`KeepError::InvalidPassword`] if the password is incorrect.
237    /// Returns [`KeepError::RateLimited`] after too many failed attempts.
238    pub fn unlock(&mut self, password: &str) -> Result<()> {
239        self.storage.unlock(password)?;
240
241        let data_key = self.get_data_key()?;
242        self.audit = Some(AuditLog::open(self.storage.path(), &data_key)?);
243        self.signing_audit = Some(SigningAuditLog::open(self.storage.path(), &data_key)?);
244
245        // Flush any rate-limit trip events queued by prior failed unlocks
246        // before recording this success, so the audit chain reflects the
247        // chronological order: lock-out events first, then the successful
248        // unlock that observed and cleared them. The drain consumes the trip
249        // file before the audit writes, so emission is best-effort: a failed
250        // audit write loses that event at-most-once with no retry.
251        let trips = self.storage.drain_pending_trips();
252        for trip in trips {
253            let trip_ts = i64::try_from(trip.timestamp).unwrap_or(i64::MAX);
254            let reason = format!(
255                "rate limit threshold reached after {} failed attempts",
256                trip.failed_attempts
257            );
258            self.audit_event(AuditEventType::RateLimitTripped, |mut e| {
259                e.timestamp = trip_ts;
260                e.with_success(false).with_reason(&reason)
261            });
262        }
263
264        self.audit_event(AuditEventType::VaultUnlock, |e| e);
265        debug!("loading keys to keyring");
266        self.load_keys_to_keyring()
267    }
268
269    /// Verify a password without changing the unlock state.
270    pub fn verify_password(&self, password: &str) -> Result<()> {
271        self.storage.verify_password(password)
272    }
273
274    /// Read-only pre-flight check of whether `password` is this vault's password,
275    /// WITHOUT touching the rate limiter, audit log, keyring, or unlock state.
276    /// `Ok(true)` = matches, `Ok(false)` = wrong password, `Err` = could not check.
277    /// Unlike [`Self::verify_password`] it does not record a rate-limit attempt and
278    /// is not blocked by an active backoff, so a pre-flight check cannot self-inflict
279    /// a lockout nor be silently skipped. Because it does not rate-limit, use it only
280    /// on local, operator-driven paths (e.g. the duress-provision anti-brick guard),
281    /// never as a remote or automated unlock oracle.
282    pub fn password_matches(&self, password: &str) -> Result<bool> {
283        self.storage.password_matches(password)
284    }
285
286    /// Lock and clear all keys from memory.
287    pub fn lock(&mut self) {
288        self.audit_event(AuditEventType::VaultLock, |e| e);
289        self.keyring.clear();
290        self.audit = None;
291        self.signing_audit = None;
292        self.storage.lock();
293    }
294
295    /// Returns true if unlocked.
296    pub fn is_unlocked(&self) -> bool {
297        self.storage.is_unlocked()
298    }
299
300    /// The vault's Argon2id parameters (from the header, readable before unlock).
301    /// Non-secret; used to reproduce an unlock's KDF cost without unlocking.
302    pub fn argon2_params(&self) -> crate::crypto::Argon2Params {
303        self.storage.argon2_params()
304    }
305
306    /// Generate a new Nostr keypair and store it.
307    ///
308    /// # Example
309    ///
310    /// ```no_run
311    /// # use std::path::Path;
312    /// # use keep_core::Keep;
313    /// # let mut keep = Keep::create(Path::new("/tmp/k"), "pw")?;
314    /// let pubkey = keep.generate_key("my-nostr-key")?;
315    /// println!("Created key: {}", hex::encode(pubkey));
316    /// # Ok::<(), keep_core::error::KeepError>(())
317    /// ```
318    ///
319    /// # Errors
320    ///
321    /// Returns [`KeepError::Locked`] if the Keep is not unlocked.
322    pub fn generate_key(&mut self, name: &str) -> Result<[u8; 32]> {
323        if !self.is_unlocked() {
324            return Err(KeepError::Locked);
325        }
326
327        let keypair = NostrKeypair::generate()?;
328        let pubkey = *keypair.public_bytes();
329
330        let data_key = self.get_data_key()?;
331        let encrypted = crypto::encrypt(keypair.secret_bytes(), &data_key)?;
332
333        let record = KeyRecord::new(
334            pubkey,
335            KeyType::Nostr,
336            name.to_string(),
337            encrypted.to_bytes(),
338        );
339
340        self.storage.store_key(&record)?;
341
342        self.keyring.load_key(
343            pubkey,
344            *keypair.secret_bytes(),
345            KeyType::Nostr,
346            name.to_string(),
347        )?;
348
349        self.audit_event(AuditEventType::KeyGenerate, |e| {
350            e.with_pubkey(&pubkey).with_key_type("nostr")
351        });
352
353        Ok(pubkey)
354    }
355
356    /// Import an nsec and store it.
357    ///
358    /// # Example
359    ///
360    /// ```no_run
361    /// # use std::path::Path;
362    /// # use keep_core::Keep;
363    /// # let mut keep = Keep::create(Path::new("/tmp/k"), "pw")?;
364    /// let nsec = "nsec1...";
365    /// let pubkey = keep.import_nsec(nsec, "imported-key")?;
366    /// # Ok::<(), keep_core::error::KeepError>(())
367    /// ```
368    ///
369    /// # Errors
370    ///
371    /// Returns [`KeepError::Locked`] if the Keep is not unlocked.
372    /// Returns [`KeepError::InvalidNsec`] if the nsec format is invalid.
373    /// Returns [`KeepError::KeyAlreadyExists`] if the key is already stored.
374    pub fn import_nsec(&mut self, nsec: &str, name: &str) -> Result<[u8; 32]> {
375        if !self.is_unlocked() {
376            return Err(KeepError::Locked);
377        }
378
379        let name = name.trim();
380        if name.is_empty() {
381            return Err(KeepError::InvalidInput("name cannot be empty".into()));
382        }
383        if name.chars().count() > 64 {
384            return Err(KeepError::InvalidInput(
385                "name must be 64 characters or fewer".into(),
386            ));
387        }
388
389        let keypair = NostrKeypair::from_nsec(nsec)?;
390        let pubkey = *keypair.public_bytes();
391
392        if self.keyring.get(&pubkey).is_some() {
393            return Err(KeepError::KeyAlreadyExists(keypair.to_npub()));
394        }
395
396        let data_key = self.get_data_key()?;
397        let encrypted = crypto::encrypt(keypair.secret_bytes(), &data_key)?;
398
399        let record = KeyRecord::new(
400            pubkey,
401            KeyType::Nostr,
402            name.to_string(),
403            encrypted.to_bytes(),
404        );
405
406        self.storage.store_key(&record)?;
407
408        self.keyring.load_key(
409            pubkey,
410            *keypair.secret_bytes(),
411            KeyType::Nostr,
412            name.to_string(),
413        )?;
414
415        self.audit_event(AuditEventType::KeyImport, |e| {
416            e.with_pubkey(&pubkey).with_key_type("nostr")
417        });
418
419        Ok(pubkey)
420    }
421
422    /// Import a Nostr key from raw secret bytes.
423    pub fn import_secret_bytes(&mut self, secret: &mut [u8; 32], name: &str) -> Result<[u8; 32]> {
424        if !self.is_unlocked() {
425            return Err(KeepError::Locked);
426        }
427
428        let name = name.trim();
429        if name.is_empty() {
430            return Err(KeepError::InvalidInput("name cannot be empty".into()));
431        }
432        if name.chars().count() > 64 {
433            return Err(KeepError::InvalidInput(
434                "name must be 64 characters or fewer".into(),
435            ));
436        }
437
438        let keypair = NostrKeypair::from_secret_bytes(secret)?;
439        let pubkey = *keypair.public_bytes();
440
441        if self.keyring.get(&pubkey).is_some() {
442            return Err(KeepError::KeyAlreadyExists(keypair.to_npub()));
443        }
444
445        let data_key = self.get_data_key()?;
446        let encrypted = crypto::encrypt(keypair.secret_bytes(), &data_key)?;
447
448        let record = KeyRecord::new(
449            pubkey,
450            KeyType::Nostr,
451            name.to_string(),
452            encrypted.to_bytes(),
453        );
454
455        self.storage.store_key(&record)?;
456
457        self.keyring.load_key(
458            pubkey,
459            *keypair.secret_bytes(),
460            KeyType::Nostr,
461            name.to_string(),
462        )?;
463
464        self.audit_event(AuditEventType::KeyImport, |e| {
465            e.with_pubkey(&pubkey).with_key_type("nostr")
466        });
467
468        Ok(pubkey)
469    }
470
471    /// The primary key slot, if set.
472    pub fn get_primary_key(&self) -> Option<&keyring::KeySlot> {
473        self.keyring.get_primary()
474    }
475
476    /// List all stored key records.
477    pub fn list_keys(&self) -> Result<Vec<KeyRecord>> {
478        self.storage.list_keys()
479    }
480
481    /// Store (insert or overwrite by id) an arbitrary-secret record (password,
482    /// API token, note). The whole record, including its plaintext value and
483    /// title, is encrypted under the vault data key at rest. See
484    /// [`storage::Storage::store_secret`]. Records a `SecretCreate` audit event
485    /// (tagged with the non-sensitive random id, never the name or value) so
486    /// secret mutations leave a forensic trail like every other sensitive op.
487    pub fn store_secret(&mut self, record: &crate::secret::SecretRecord) -> Result<()> {
488        self.storage.store_secret(record)?;
489        self.audit_event(AuditEventType::SecretCreate, |e| e.with_pubkey(&record.id));
490        Ok(())
491    }
492
493    /// Load a secret record by its 32-byte id.
494    pub fn load_secret(&self, id: &[u8; 32]) -> Result<crate::secret::SecretRecord> {
495        self.storage.load_secret(id)
496    }
497
498    /// List all stored secret records.
499    pub fn list_secrets(&self) -> Result<Vec<crate::secret::SecretRecord>> {
500        self.storage.list_secrets()
501    }
502
503    /// Delete a secret record by its 32-byte id. Records a `SecretDelete` audit
504    /// event tagged with the id.
505    pub fn delete_secret(&mut self, id: &[u8; 32]) -> Result<()> {
506        self.storage.delete_secret(id)?;
507        self.audit_event(AuditEventType::SecretDelete, |e| e.with_pubkey(id));
508        Ok(())
509    }
510
511    /// Restore a secret WITHOUT emitting an audit event, for the backup-restore
512    /// path only. Restore re-establishes the source vault's audit log verbatim
513    /// (see `VaultBackup::audit_entries`), so re-auditing each restored row would
514    /// double-count. Mirrors `restore_key_record`.
515    pub fn restore_secret(&self, record: &crate::secret::SecretRecord) -> Result<()> {
516        self.storage.store_secret(record)
517    }
518
519    /// Store a secret whose value can only be revealed with a t-of-n OPRF quorum.
520    ///
521    /// Takes a caller-minted `record` (via [`crate::secret::SecretRecord::new`])
522    /// carrying the plaintext in `record.value`. The caller must mint the record
523    /// FIRST so it knows the id, then derive `oprf_key` from the quorum for that id
524    /// (`oprf_id = hex(record.id)`, `epoch`) BEFORE calling this: the seal records
525    /// `oprf_id`, and a reveal re-derives the key for the same id, so a key derived
526    /// for any other id would seal a value no quorum could ever reopen.
527    ///
528    /// `oprf_key` is the quorum-derived key ([`crate::oprf::derive_luks_key`]
529    /// output); `epoch` its OPRF rotation counter. The value is sealed under a fresh
530    /// per-secret DEK wrapped by `oprf_key`, so a single device that never assembles
531    /// the quorum cannot decrypt it even with the vault unlocked. The record's
532    /// name/kind stay readable with the vault data key. Returns the stored record
533    /// (its `value` now the DEK-ciphertext). Records a `SecretCreate` audit event.
534    pub fn store_sealed_secret(
535        &mut self,
536        mut record: crate::secret::SecretRecord,
537        oprf_key: &crate::crypto::SecretKey,
538        epoch: u32,
539    ) -> Result<crate::secret::SecretRecord> {
540        let oprf_id = hex::encode(record.id);
541        // Take the plaintext out of the record and seal it; `record.value` becomes
542        // the DEK-ciphertext. The lifted plaintext is zeroized when this scope ends.
543        let plaintext = zeroize::Zeroizing::new(std::mem::take(&mut record.value));
544        let (value_ciphertext, seal) =
545            crate::secret::seal_value(&plaintext, oprf_key, oprf_id, epoch)?;
546        record.value = value_ciphertext;
547        self.storage.store_sealed_secret(&record, &seal)?;
548        self.audit_event(AuditEventType::SecretCreate, |e| e.with_pubkey(&record.id));
549        Ok(record)
550    }
551
552    /// Load the threshold seal for a secret id, or `None` if the secret is an
553    /// ordinary plaintext-value secret. The seal carries the OPRF params
554    /// (`oprf_id`, `epoch`) the quorum needs to re-derive the unwrapping key.
555    pub fn load_secret_seal(&self, id: &[u8; 32]) -> Result<Option<crate::secret::ThresholdSeal>> {
556        self.storage.load_secret_seal(id)
557    }
558
559    /// Reveal a threshold-sealed secret's plaintext value given the OPRF-quorum
560    /// -derived key. Errors if the secret is not sealed, or if `oprf_key` is wrong
561    /// (a single-device caller that never assembled the quorum cannot derive it).
562    ///
563    /// Records a `SecretReveal` audit event (tagged with the id) only on a
564    /// successful unseal: revealing a quorum-gated plaintext is the most sensitive
565    /// read in the store, audited like `KeyExport`. A wrong-key attempt leaves no
566    /// entry (it never yields the value).
567    pub fn reveal_sealed_secret(
568        &mut self,
569        id: &[u8; 32],
570        oprf_key: &crate::crypto::SecretKey,
571    ) -> Result<zeroize::Zeroizing<Vec<u8>>> {
572        let record = self.storage.load_secret(id)?;
573        let seal = self
574            .storage
575            .load_secret_seal(id)?
576            .ok_or_else(|| KeepError::invalid_input("secret is not threshold-sealed"))?;
577        let plaintext = crate::secret::unseal_value(&record.value, &seal, oprf_key)?;
578        self.audit_event(AuditEventType::SecretReveal, |e| e.with_pubkey(id));
579        Ok(plaintext)
580    }
581
582    /// Restore a threshold-sealed secret (record + seal) WITHOUT emitting an audit
583    /// event, for the backup-restore path only. Mirrors [`Self::restore_secret`].
584    pub fn restore_sealed_secret(
585        &self,
586        record: &crate::secret::SecretRecord,
587        seal: &crate::secret::ThresholdSeal,
588    ) -> Result<()> {
589        self.storage.store_sealed_secret(record, seal)
590    }
591
592    /// Export a stored nsec key as NIP-49 ncryptsec.
593    pub fn export_ncryptsec(&mut self, pubkey: &[u8; 32], password: &str) -> Result<String> {
594        if !self.is_unlocked() {
595            return Err(KeepError::Locked);
596        }
597
598        let slot = self
599            .keyring
600            .get(pubkey)
601            .ok_or_else(|| KeepError::KeyNotFound(hex::encode(pubkey)))?;
602
603        if slot.key_type != KeyType::Nostr {
604            return Err(KeepError::InvalidInput("not a Nostr key".into()));
605        }
606
607        let result = keys::nip49::encrypt(slot.expose_secret(), password, None)?;
608        self.audit_event(AuditEventType::KeyExport, |e| e.with_pubkey(pubkey));
609        Ok(result)
610    }
611
612    /// Delete a key.
613    pub fn delete_key(&mut self, pubkey: &[u8; 32]) -> Result<()> {
614        let id = crypto::blake2b_256(pubkey);
615        self.storage.delete_key(&id)?;
616        self.keyring.remove(pubkey)?;
617        self.audit_event(AuditEventType::KeyDelete, |e| e.with_pubkey(pubkey));
618        Ok(())
619    }
620
621    /// The keyring.
622    pub fn keyring(&self) -> &Keyring {
623        &self.keyring
624    }
625
626    /// Decrypted audit log entries for this vault, in chronological order.
627    /// Returns an empty vec if the audit log file does not exist yet.
628    ///
629    /// # Errors
630    /// Returns [`KeepError::Locked`] if the vault is not unlocked.
631    pub fn read_audit_entries(&self) -> Result<Vec<AuditEntry>> {
632        if !self.is_unlocked() {
633            return Err(KeepError::Locked);
634        }
635        let data_key = self.get_data_key()?;
636        let audit = AuditLog::open(self.storage.path(), &data_key)?;
637        audit.read_all(&data_key)
638    }
639
640    /// Mutable access to the keyring.
641    pub fn keyring_mut(&mut self) -> &mut Keyring {
642        &mut self.keyring
643    }
644
645    /// Generate a new FROST key with the given threshold and total shares.
646    pub fn frost_generate(
647        &mut self,
648        threshold: u16,
649        total_shares: u16,
650        name: &str,
651    ) -> Result<Vec<SharePackage>> {
652        if !self.is_unlocked() {
653            return Err(KeepError::Locked);
654        }
655
656        let config = ThresholdConfig::new(threshold, total_shares)?;
657        let dealer = TrustedDealer::new(config);
658        let (shares, _) = dealer.generate(name)?;
659
660        let data_key = self.get_data_key()?;
661        for share in &shares {
662            let stored = StoredShare::encrypt(share, &data_key)?;
663            self.storage.store_share(&stored)?;
664        }
665
666        let group_pubkey = *shares[0].group_pubkey();
667        let participants: Vec<u16> = (1..=total_shares).collect();
668        self.audit_event(AuditEventType::FrostGenerate, |e| {
669            e.with_group(&group_pubkey)
670                .with_threshold(threshold)
671                .with_participants(participants)
672        });
673
674        Ok(shares)
675    }
676
677    /// Split an existing key into FROST shares.
678    pub fn frost_split(
679        &mut self,
680        key_name: &str,
681        threshold: u16,
682        total_shares: u16,
683    ) -> Result<Vec<SharePackage>> {
684        if !self.is_unlocked() {
685            return Err(KeepError::Locked);
686        }
687
688        let slot = self
689            .keyring
690            .get_by_name(key_name)
691            .ok_or_else(|| KeepError::KeyNotFound(key_name.to_string()))?;
692
693        let secret = Zeroizing::new(*slot.expose_secret());
694
695        let config = ThresholdConfig::new(threshold, total_shares)?;
696        let dealer = TrustedDealer::new(config);
697        let (shares, _) = dealer.split_existing(&secret, key_name)?;
698
699        let data_key = self.get_data_key()?;
700        for share in &shares {
701            let stored = StoredShare::encrypt(share, &data_key)?;
702            self.storage.store_share(&stored)?;
703        }
704
705        let group_pubkey = *shares[0].group_pubkey();
706        let participants: Vec<u16> = (1..=total_shares).collect();
707        self.audit_event(AuditEventType::FrostSplit, |e| {
708            e.with_group(&group_pubkey)
709                .with_threshold(threshold)
710                .with_participants(participants)
711        });
712
713        Ok(shares)
714    }
715
716    /// List all stored FROST shares.
717    pub fn frost_list_shares(&self) -> Result<Vec<StoredShare>> {
718        self.storage.list_shares()
719    }
720
721    fn find_stored_share(
722        &self,
723        group_pubkey: &[u8; 32],
724        identifier: u16,
725        ciphersuite: Option<crate::frost::Ciphersuite>,
726    ) -> Result<StoredShare> {
727        let shares = self.storage.list_shares()?;
728        shares
729            .into_iter()
730            .find(|s| {
731                s.metadata.group_pubkey == *group_pubkey
732                    && s.metadata.identifier == identifier
733                    && ciphersuite.is_none_or(|cs| s.ciphersuite == cs)
734            })
735            .ok_or_else(|| KeepError::KeyNotFound(format!("No share {identifier} for group")))
736    }
737
738    /// Export a FROST share encrypted with a passphrase.
739    pub fn frost_export_share(
740        &mut self,
741        group_pubkey: &[u8; 32],
742        identifier: u16,
743        passphrase: &str,
744    ) -> Result<ShareExport> {
745        if !self.is_unlocked() {
746            return Err(KeepError::Locked);
747        }
748
749        let mut stored = self.find_stored_share(group_pubkey, identifier, None)?;
750        let data_key = self.get_data_key()?;
751        let share = stored.decrypt(&data_key)?;
752
753        self.audit_event(AuditEventType::FrostShareExport, |e| {
754            e.with_group(group_pubkey)
755                .with_participants(vec![identifier])
756        });
757
758        let export =
759            ShareExport::from_share_with_ciphersuite(&share, stored.ciphersuite, passphrase)?;
760
761        // Exporting is the backup action: record it so the UI/clients can stop
762        // nagging "not backed up". Best-effort; a storage error here must not
763        // fail the export the caller already holds.
764        if !stored.metadata.did_backup {
765            stored.metadata.mark_backed_up();
766            if let Err(e) = self.storage.store_share(&stored) {
767                tracing::warn!(error = %e, "failed to persist did_backup after export");
768            }
769        }
770
771        Ok(export)
772    }
773
774    /// Import a FROST share from an encrypted export.
775    pub fn frost_import_share(
776        &mut self,
777        export: &ShareExport,
778        passphrase: &str,
779        name: &str,
780    ) -> Result<()> {
781        if !self.is_unlocked() {
782            return Err(KeepError::Locked);
783        }
784        let name = name.trim();
785        if name.is_empty() {
786            return Err(KeepError::InvalidInput("name cannot be empty".into()));
787        }
788        if name.chars().count() > 64 {
789            return Err(KeepError::InvalidInput(
790                "name must be 64 characters or fewer".into(),
791            ));
792        }
793
794        let share = export.to_share(passphrase, name)?;
795        let data_key = self.get_data_key()?;
796        let stored = StoredShare::encrypt_with_ciphersuite(&share, export.ciphersuite, &data_key)?;
797        self.storage.store_share(&stored)?;
798
799        let group = hex::decode(&export.group_pubkey)
800            .ok()
801            .and_then(|bytes| <[u8; 32]>::try_from(bytes.as_slice()).ok())
802            .unwrap_or_else(|| crypto::blake2b_256(export.group_pubkey.as_bytes()));
803        self.audit_event(AuditEventType::FrostShareImport, |e| {
804            e.with_group(&group)
805                .with_participants(vec![export.identifier])
806        });
807
808        Ok(())
809    }
810
811    /// Persist a share produced by [`frost::dkg::SoftwareDkgSession::finalize`]
812    /// (#454). Wraps the finalized `KeyPackage` + `PublicKeyPackage` into a
813    /// [`SharePackage`] with fresh metadata, encrypts under the vault's data
814    /// key, stores it, and writes a `FrostShareImport` audit entry.
815    pub fn frost_store_dkg_share(
816        &mut self,
817        result: &crate::frost::dkg::SoftwareDkgResult,
818        threshold: u16,
819        total_shares: u16,
820        name: &str,
821    ) -> Result<()> {
822        if !self.is_unlocked() {
823            return Err(KeepError::Locked);
824        }
825        let name = name.trim();
826        if name.is_empty() {
827            return Err(KeepError::InvalidInput("name cannot be empty".into()));
828        }
829        if name.chars().count() > 64 {
830            return Err(KeepError::InvalidInput(
831                "name must be 64 characters or fewer".into(),
832            ));
833        }
834
835        let metadata = crate::frost::ShareMetadata::new(
836            result.our_index,
837            threshold,
838            total_shares,
839            result.group_pubkey,
840            name.to_string(),
841        );
842        let share = crate::frost::SharePackage::new(
843            metadata,
844            &result.key_package,
845            &result.public_key_package,
846        )?;
847
848        let data_key = self.get_data_key()?;
849        let stored = StoredShare::encrypt(&share, &data_key)?;
850        self.storage.store_share(&stored)?;
851
852        self.audit_event(AuditEventType::FrostShareImport, |e| {
853            e.with_group(&result.group_pubkey)
854                .with_threshold(threshold)
855                .with_participants(vec![result.our_index])
856        });
857
858        Ok(())
859    }
860
861    /// Refresh all FROST shares for a group, invalidating old shares.
862    pub fn frost_refresh(&mut self, group_pubkey: &[u8; 32]) -> Result<Vec<frost::ShareMetadata>> {
863        if !self.is_unlocked() {
864            return Err(KeepError::Locked);
865        }
866
867        let data_key = self.get_data_key()?;
868        let all_shares = self.storage.list_shares()?;
869        let group_shares: Vec<_> = all_shares
870            .into_iter()
871            .filter(|s| {
872                s.metadata.group_pubkey == *group_pubkey
873                    && s.ciphersuite == crate::frost::Ciphersuite::Secp256k1Tr
874            })
875            .collect();
876
877        if group_shares.is_empty() {
878            return Err(KeepError::KeyNotFound("No shares for group".into()));
879        }
880
881        let threshold = group_shares[0].metadata.threshold;
882        let total = group_shares[0].metadata.total_shares;
883
884        let share_count: u16 = group_shares
885            .len()
886            .try_into()
887            .map_err(|_| KeepError::Frost("Too many shares".into()))?;
888        if share_count != total {
889            return Err(KeepError::Frost(format!(
890                "refresh requires the full set of {total} shares; only {share_count} available. \
891                 A partial refresh would orphan the absent shares (#586)."
892            )));
893        }
894
895        let decrypted: Vec<SharePackage> = group_shares
896            .iter()
897            .map(|s| s.decrypt(&data_key))
898            .collect::<Result<_>>()?;
899
900        let (refreshed, _) = frost::refresh_shares(&decrypted)?;
901
902        let encrypted_shares: Vec<StoredShare> = refreshed
903            .iter()
904            .map(|share| StoredShare::encrypt(share, &data_key))
905            .collect::<Result<_>>()?;
906
907        self.storage.store_shares_atomic(&encrypted_shares)?;
908
909        let metadata: Vec<_> = refreshed.iter().map(|s| s.metadata.clone()).collect();
910        let participants: Vec<u16> = metadata.iter().map(|m| m.identifier).collect();
911        self.audit_event(AuditEventType::FrostShareRefresh, |e| {
912            e.with_group(group_pubkey)
913                .with_threshold(threshold)
914                .with_participants(participants)
915        });
916
917        Ok(metadata)
918    }
919
920    /// Delete a FROST share.
921    pub fn frost_delete_share(&mut self, group_pubkey: &[u8; 32], identifier: u16) -> Result<()> {
922        self.storage.delete_share(group_pubkey, identifier)?;
923        self.audit_event(AuditEventType::FrostShareDelete, |e| {
924            e.with_group(group_pubkey)
925                .with_participants(vec![identifier])
926        });
927        Ok(())
928    }
929
930    /// Rename a stored FROST share (updates its display name only).
931    pub fn frost_rename_share(
932        &mut self,
933        group_pubkey: &[u8; 32],
934        identifier: u16,
935        name: &str,
936    ) -> Result<()> {
937        if !self.is_unlocked() {
938            return Err(KeepError::Locked);
939        }
940        let name = name.trim();
941        if name.is_empty() {
942            return Err(KeepError::InvalidInput(
943                "share name must not be empty".into(),
944            ));
945        }
946        if name.chars().count() > 64 {
947            return Err(KeepError::InvalidInput(
948                "share name must not exceed 64 characters".into(),
949            ));
950        }
951        let mut stored = self.find_stored_share(group_pubkey, identifier, None)?;
952        stored.metadata.name = name.to_string();
953        self.storage.store_share(&stored)?;
954        Ok(())
955    }
956
957    /// Get the hex-encoded group pubkey of the active share, if set.
958    pub fn get_active_share_key(&self) -> Option<String> {
959        std::fs::read_to_string(self.active_share_path())
960            .ok()
961            .map(|s| s.trim().to_string())
962            .filter(|s| is_valid_hex_pubkey(s))
963    }
964
965    /// Set the active share by hex-encoded group pubkey. Pass `None` to clear.
966    pub fn set_active_share_key(&self, key: Option<&str>) -> Result<()> {
967        if !self.is_unlocked() {
968            return Err(KeepError::Locked);
969        }
970        let path = self.active_share_path();
971        match key {
972            Some(k) => {
973                if !is_valid_hex_pubkey(k) {
974                    return Err(KeepError::InvalidInput(
975                        "Group pubkey must be 64 hex characters".into(),
976                    ));
977                }
978                let normalized = k.to_ascii_lowercase();
979                write_restricted(&path, normalized.as_bytes())?;
980            }
981            None => {
982                if let Err(e) = std::fs::remove_file(&path) {
983                    if e.kind() != std::io::ErrorKind::NotFound {
984                        return Err(e.into());
985                    }
986                }
987            }
988        }
989        Ok(())
990    }
991
992    fn active_share_path(&self) -> PathBuf {
993        self.storage.path.join("active_share")
994    }
995
996    /// Store a finalized wallet descriptor, associated with a FROST group.
997    pub fn store_wallet_descriptor(&self, descriptor: &WalletDescriptor) -> Result<()> {
998        if !self.is_unlocked() {
999            return Err(KeepError::Locked);
1000        }
1001        self.storage.store_descriptor(descriptor)
1002    }
1003
1004    /// Get the wallet descriptor for a FROST group.
1005    pub fn get_wallet_descriptor(
1006        &self,
1007        group_pubkey: &[u8; 32],
1008    ) -> Result<Option<WalletDescriptor>> {
1009        if !self.is_unlocked() {
1010            return Err(KeepError::Locked);
1011        }
1012        self.storage.get_descriptor(group_pubkey)
1013    }
1014
1015    /// List the latest-version wallet descriptor for every group. Older
1016    /// descriptor versions are not returned; use
1017    /// [`list_all_wallet_descriptor_versions`] when every row is required
1018    /// (backup, rotation re-encryption verification, etc.).
1019    ///
1020    /// [`list_all_wallet_descriptor_versions`]: Self::list_all_wallet_descriptor_versions
1021    pub fn list_wallet_descriptors(&self) -> Result<Vec<WalletDescriptor>> {
1022        if !self.is_unlocked() {
1023            return Err(KeepError::Locked);
1024        }
1025        self.storage.list_descriptors()
1026    }
1027
1028    /// List every persisted wallet descriptor row across all groups and
1029    /// versions. Used by backup and rotation paths that must round-trip every
1030    /// stored record.
1031    pub fn list_all_wallet_descriptor_versions(&self) -> Result<Vec<WalletDescriptor>> {
1032        if !self.is_unlocked() {
1033            return Err(KeepError::Locked);
1034        }
1035        self.storage.list_all_descriptor_versions()
1036    }
1037
1038    /// Delete a wallet descriptor.
1039    pub fn delete_wallet_descriptor(&self, group_pubkey: &[u8; 32]) -> Result<()> {
1040        if !self.is_unlocked() {
1041            return Err(KeepError::Locked);
1042        }
1043        self.storage.delete_descriptor(group_pubkey)
1044    }
1045
1046    /// Atomically insert or update a device registration on the descriptor for
1047    /// the given FROST group. Performs the load-modify-store under the
1048    /// storage's descriptor write lock so concurrent callers cannot drop each
1049    /// other's updates.
1050    pub fn upsert_device_registration(
1051        &self,
1052        group_pubkey: &[u8; 32],
1053        registration: DeviceRegistration,
1054    ) -> Result<()> {
1055        if !self.is_unlocked() {
1056            return Err(KeepError::Locked);
1057        }
1058        self.storage
1059            .upsert_device_registration(group_pubkey, registration)
1060    }
1061
1062    /// Store a key health status record.
1063    pub fn store_health_status(&self, status: &wallet::KeyHealthStatus) -> Result<()> {
1064        if !self.is_unlocked() {
1065            return Err(KeepError::Locked);
1066        }
1067        self.storage.store_health_status(status)
1068    }
1069
1070    /// Get a key health status record.
1071    pub fn get_health_status(
1072        &self,
1073        group_pubkey: &[u8; 32],
1074        share_index: u16,
1075    ) -> Result<Option<wallet::KeyHealthStatus>> {
1076        if !self.is_unlocked() {
1077            return Err(KeepError::Locked);
1078        }
1079        self.storage.get_health_status(group_pubkey, share_index)
1080    }
1081
1082    /// List all key health status records.
1083    pub fn list_health_statuses(&self) -> Result<Vec<wallet::KeyHealthStatus>> {
1084        if !self.is_unlocked() {
1085            return Err(KeepError::Locked);
1086        }
1087        self.storage.list_health_statuses()
1088    }
1089
1090    /// List health statuses that are stale (not checked within the threshold).
1091    pub fn list_stale_health_statuses(&self, now: u64) -> Result<Vec<wallet::KeyHealthStatus>> {
1092        if !self.is_unlocked() {
1093            return Err(KeepError::Locked);
1094        }
1095        let all = self.storage.list_health_statuses()?;
1096        Ok(all.into_iter().filter(|s| s.is_stale(now)).collect())
1097    }
1098
1099    /// Store relay configuration for a FROST share.
1100    pub fn store_relay_config(&self, config: &RelayConfig) -> Result<()> {
1101        if !self.is_unlocked() {
1102            return Err(KeepError::Locked);
1103        }
1104        let normalized_config = config.clone().normalize()?;
1105        self.storage.store_relay_config(&normalized_config)
1106    }
1107
1108    /// Get relay configuration for a FROST share.
1109    pub fn get_relay_config(&self, group_pubkey: &[u8; 32]) -> Result<Option<RelayConfig>> {
1110        if !self.is_unlocked() {
1111            return Err(KeepError::Locked);
1112        }
1113        self.storage.get_relay_config(group_pubkey)
1114    }
1115
1116    /// Get relay configuration for a FROST share, returning defaults if none stored.
1117    pub fn get_relay_config_or_default(&self, group_pubkey: &[u8; 32]) -> Result<RelayConfig> {
1118        if !self.is_unlocked() {
1119            return Err(KeepError::Locked);
1120        }
1121        Ok(self
1122            .storage
1123            .get_relay_config(group_pubkey)?
1124            .unwrap_or_else(|| RelayConfig::with_defaults(*group_pubkey)))
1125    }
1126
1127    /// List all stored relay configurations.
1128    pub fn list_relay_configs(&self) -> Result<Vec<RelayConfig>> {
1129        if !self.is_unlocked() {
1130            return Err(KeepError::Locked);
1131        }
1132        self.storage.list_relay_configs()
1133    }
1134
1135    /// Delete relay configuration for a FROST share.
1136    pub fn delete_relay_config(&self, group_pubkey: &[u8; 32]) -> Result<()> {
1137        if !self.is_unlocked() {
1138            return Err(KeepError::Locked);
1139        }
1140        self.storage.delete_relay_config(group_pubkey)
1141    }
1142
1143    /// Get the kill switch state from the vault.
1144    pub fn get_kill_switch(&self) -> Result<bool> {
1145        if !self.is_unlocked() {
1146            return Err(KeepError::Locked);
1147        }
1148        self.storage.get_kill_switch()
1149    }
1150
1151    /// Set the kill switch state in the vault.
1152    pub fn set_kill_switch(&self, active: bool) -> Result<()> {
1153        if !self.is_unlocked() {
1154            return Err(KeepError::Locked);
1155        }
1156        self.storage.set_kill_switch(active)
1157    }
1158
1159    /// Get the proxy configuration.
1160    pub fn get_proxy_config(&self) -> Result<ProxyConfig> {
1161        if !self.is_unlocked() {
1162            return Err(KeepError::Locked);
1163        }
1164        self.storage.get_proxy_config()
1165    }
1166
1167    /// Set the proxy configuration.
1168    pub fn set_proxy_config(&self, config: &ProxyConfig) -> Result<()> {
1169        if !self.is_unlocked() {
1170            return Err(KeepError::Locked);
1171        }
1172        self.storage.set_proxy_config(config)
1173    }
1174
1175    /// Get a FROST share by group public key.
1176    pub fn frost_get_share(&self, group_pubkey: &[u8; 32]) -> Result<frost::SharePackage> {
1177        if !self.is_unlocked() {
1178            return Err(KeepError::Locked);
1179        }
1180
1181        let data_key = self.get_data_key()?;
1182        let shares = self.storage.list_shares()?;
1183        let stored = shares
1184            .iter()
1185            .find(|s| {
1186                s.metadata.group_pubkey == *group_pubkey
1187                    && s.ciphersuite == crate::frost::Ciphersuite::Secp256k1Tr
1188            })
1189            .ok_or_else(|| KeepError::KeyNotFound("No shares for group".into()))?;
1190
1191        stored.decrypt(&data_key)
1192    }
1193
1194    /// Get a FROST share by group public key and identifier index.
1195    pub fn frost_get_share_by_index(
1196        &self,
1197        group_pubkey: &[u8; 32],
1198        identifier: u16,
1199    ) -> Result<frost::SharePackage> {
1200        if !self.is_unlocked() {
1201            return Err(KeepError::Locked);
1202        }
1203
1204        let stored = self.find_stored_share(group_pubkey, identifier, None)?;
1205        let data_key = self.get_data_key()?;
1206        stored.decrypt(&data_key)
1207    }
1208
1209    /// Sign using local FROST shares. Requires threshold shares locally.
1210    pub fn frost_sign(&mut self, group_pubkey: &[u8; 32], message: &[u8]) -> Result<[u8; 64]> {
1211        if !self.is_unlocked() {
1212            return Err(KeepError::Locked);
1213        }
1214
1215        let data_key = self.get_data_key()?;
1216        let shares = self.storage.list_shares()?;
1217        let our_shares: Vec<_> = shares
1218            .iter()
1219            .filter(|s| {
1220                s.metadata.group_pubkey == *group_pubkey
1221                    && s.ciphersuite == crate::frost::Ciphersuite::Secp256k1Tr
1222            })
1223            .collect();
1224
1225        if our_shares.is_empty() {
1226            return Err(KeepError::KeyNotFound("No shares for group".into()));
1227        }
1228
1229        let threshold = our_shares[0].metadata.threshold;
1230
1231        if our_shares.len() < threshold as usize {
1232            self.audit_event(AuditEventType::FrostSignFailed, |e| {
1233                e.with_group(group_pubkey)
1234                    .with_message_hash(message)
1235                    .with_success(false)
1236                    .with_reason("Insufficient shares")
1237            });
1238            return Err(KeepError::Frost(format!(
1239                "Need {} shares to sign, only {} available",
1240                threshold,
1241                our_shares.len()
1242            )));
1243        }
1244
1245        let mut decrypted_shares = Vec::new();
1246        for stored in our_shares.iter().take(threshold as usize) {
1247            decrypted_shares.push(stored.decrypt(&data_key)?);
1248        }
1249
1250        match frost::sign_with_local_shares(&decrypted_shares, message) {
1251            Ok(sig) => {
1252                self.audit_event(AuditEventType::FrostSign, |e| {
1253                    e.with_group(group_pubkey)
1254                        .with_message_hash(message)
1255                        .with_threshold(threshold)
1256                });
1257                Ok(sig)
1258            }
1259            Err(e) => {
1260                self.audit_event(AuditEventType::FrostSignFailed, |e| {
1261                    e.with_group(group_pubkey)
1262                        .with_message_hash(message)
1263                        .with_success(false)
1264                });
1265                Err(e)
1266            }
1267        }
1268    }
1269
1270    /// Generate a FROST-Ed25519 threshold key and store its shares.
1271    ///
1272    /// Shares are tagged with [`Ciphersuite::Ed25519`], which is bound into the
1273    /// at-rest AEAD AAD so they cannot be confused with secp256k1 shares.
1274    #[cfg(feature = "ed25519")]
1275    pub fn frost_generate_ed25519(
1276        &mut self,
1277        threshold: u16,
1278        total_shares: u16,
1279        name: &str,
1280    ) -> Result<Vec<SharePackage>> {
1281        if !self.is_unlocked() {
1282            return Err(KeepError::Locked);
1283        }
1284
1285        let config = ThresholdConfig::new(threshold, total_shares)?;
1286        let dealer = crate::frost::ed25519::TrustedDealer::new(config);
1287        let (shares, _) = dealer.generate(name)?;
1288
1289        let data_key = self.get_data_key()?;
1290        for share in &shares {
1291            let stored = StoredShare::encrypt_with_ciphersuite(
1292                share,
1293                crate::frost::Ciphersuite::Ed25519,
1294                &data_key,
1295            )?;
1296            self.storage.store_share(&stored)?;
1297        }
1298
1299        let group_pubkey = *shares[0].group_pubkey();
1300        let participants: Vec<u16> = shares.iter().map(|s| s.metadata.identifier).collect();
1301        self.audit_event(AuditEventType::FrostGenerate, |e| {
1302            e.with_group(&group_pubkey)
1303                .with_threshold(threshold)
1304                .with_participants(participants)
1305        });
1306
1307        Ok(shares)
1308    }
1309
1310    /// Sign a message with a threshold of local FROST-Ed25519 shares.
1311    ///
1312    /// Returns a detached 64-byte Ed25519 signature over the raw message
1313    /// (RFC 8032), verifiable by [`Keep::frost_verify_ed25519`] and by any
1314    /// standard Ed25519 verifier against the group public key.
1315    #[cfg(feature = "ed25519")]
1316    pub fn frost_sign_ed25519(
1317        &mut self,
1318        group_pubkey: &[u8; 32],
1319        message: &[u8],
1320    ) -> Result<[u8; 64]> {
1321        if !self.is_unlocked() {
1322            return Err(KeepError::Locked);
1323        }
1324
1325        let decrypted_shares = match self.frost_ed25519_decrypt_threshold_shares(group_pubkey) {
1326            Ok(shares) => shares,
1327            Err(e) => {
1328                self.audit_event(AuditEventType::FrostSignFailed, |ev| {
1329                    ev.with_group(group_pubkey)
1330                        .with_message_hash(message)
1331                        .with_success(false)
1332                        .with_reason("Insufficient shares")
1333                });
1334                return Err(e);
1335            }
1336        };
1337        let threshold = decrypted_shares[0].metadata.threshold;
1338
1339        match crate::frost::ed25519::sign_with_local_shares(&decrypted_shares, message) {
1340            Ok(sig) => {
1341                self.audit_event(AuditEventType::FrostSign, |e| {
1342                    e.with_group(group_pubkey)
1343                        .with_message_hash(message)
1344                        .with_threshold(threshold)
1345                });
1346                Ok(sig)
1347            }
1348            Err(e) => {
1349                self.audit_event(AuditEventType::FrostSignFailed, |e| {
1350                    e.with_group(group_pubkey)
1351                        .with_message_hash(message)
1352                        .with_success(false)
1353                });
1354                Err(e)
1355            }
1356        }
1357    }
1358
1359    /// Decrypt the threshold set of local Ed25519 shares for a group.
1360    ///
1361    /// Returns exactly `threshold` decrypted shares or a `KeyNotFound`/`Frost`
1362    /// error. Does not emit audit events; callers own audit semantics.
1363    #[cfg(feature = "ed25519")]
1364    fn frost_ed25519_decrypt_threshold_shares(
1365        &self,
1366        group_pubkey: &[u8; 32],
1367    ) -> Result<Vec<SharePackage>> {
1368        let data_key = self.get_data_key()?;
1369        let shares = self.storage.list_shares()?;
1370        let our_shares: Vec<_> = shares
1371            .iter()
1372            .filter(|s| {
1373                s.metadata.group_pubkey == *group_pubkey
1374                    && s.ciphersuite == crate::frost::Ciphersuite::Ed25519
1375            })
1376            .collect();
1377
1378        if our_shares.is_empty() {
1379            return Err(KeepError::KeyNotFound("No Ed25519 shares for group".into()));
1380        }
1381
1382        let threshold = our_shares[0].metadata.threshold;
1383        if our_shares.len() < threshold as usize {
1384            return Err(KeepError::Frost(format!(
1385                "Need {} shares to sign, only {} available",
1386                threshold,
1387                our_shares.len()
1388            )));
1389        }
1390
1391        let mut decrypted_shares = Vec::with_capacity(threshold as usize);
1392        for stored in our_shares.iter().take(threshold as usize) {
1393            decrypted_shares.push(stored.decrypt(&data_key)?);
1394        }
1395        Ok(decrypted_shares)
1396    }
1397
1398    /// Verify a detached Ed25519 signature against a group public key.
1399    #[cfg(feature = "ed25519")]
1400    pub fn frost_verify_ed25519(
1401        group_pubkey: &[u8; 32],
1402        message: &[u8],
1403        signature: &[u8; 64],
1404    ) -> Result<()> {
1405        crate::frost::ed25519::verify(group_pubkey, message, signature)
1406    }
1407
1408    /// Sign `message` and produce a minisign-compatible detached signature.
1409    ///
1410    /// Runs two FROST-Ed25519 threshold signing sessions: one over the
1411    /// BLAKE2b-512 prehash of the message (the `"ED"` file signature) and one
1412    /// over `file_signature || trusted_comment` (the global signature). The
1413    /// result verifies with the standard `minisign -V` tool against the
1414    /// exported group public key.
1415    #[cfg(feature = "ed25519")]
1416    pub fn frost_sign_ed25519_minisign(
1417        &mut self,
1418        group_pubkey: &[u8; 32],
1419        message: &[u8],
1420        untrusted_comment: String,
1421        trusted_comment: String,
1422    ) -> Result<crate::frost::ed25519::minisign::MinisignSignature> {
1423        use crate::frost::ed25519::minisign;
1424
1425        if !self.is_unlocked() {
1426            return Err(KeepError::Locked);
1427        }
1428
1429        minisign::validate_comment("untrusted", &untrusted_comment)?;
1430        minisign::validate_comment("trusted", &trusted_comment)?;
1431
1432        let decrypted_shares = match self.frost_ed25519_decrypt_threshold_shares(group_pubkey) {
1433            Ok(shares) => shares,
1434            Err(e) => {
1435                self.audit_event(AuditEventType::FrostSignFailed, |ev| {
1436                    ev.with_group(group_pubkey)
1437                        .with_message_hash(message)
1438                        .with_success(false)
1439                        .with_reason("Insufficient shares")
1440                });
1441                return Err(e);
1442            }
1443        };
1444        let threshold = decrypted_shares[0].metadata.threshold;
1445
1446        // Two independent threshold sessions over the same decrypted share set:
1447        // fresh nonces per session keep each signature secure.
1448        let prehash = minisign::prehash(message);
1449        let sign_both = (|| {
1450            let signature =
1451                crate::frost::ed25519::sign_with_local_shares(&decrypted_shares, &prehash)?;
1452            let global_bytes = minisign::global_signed_bytes(&signature, &trusted_comment);
1453            let global_signature =
1454                crate::frost::ed25519::sign_with_local_shares(&decrypted_shares, &global_bytes)?;
1455            Ok::<_, KeepError>((signature, global_signature))
1456        })();
1457
1458        let (signature, global_signature) = match sign_both {
1459            Ok(pair) => {
1460                self.audit_event(AuditEventType::FrostSign, |e| {
1461                    e.with_group(group_pubkey)
1462                        .with_message_hash(message)
1463                        .with_threshold(threshold)
1464                });
1465                pair
1466            }
1467            Err(e) => {
1468                self.audit_event(AuditEventType::FrostSignFailed, |ev| {
1469                    ev.with_group(group_pubkey)
1470                        .with_message_hash(message)
1471                        .with_success(false)
1472                });
1473                return Err(e);
1474            }
1475        };
1476
1477        Ok(minisign::MinisignSignature {
1478            sig_alg: minisign::ALG_PREHASHED,
1479            key_id: minisign::key_id(group_pubkey),
1480            signature,
1481            global_signature,
1482            untrusted_comment,
1483            trusted_comment,
1484        })
1485    }
1486
1487    /// Verify a minisign-compatible detached signature against a group public
1488    /// key, checking both the file signature and the global signature using
1489    /// minisign's semantics (key-id match, prehash for `"ED"`, RFC 8032 strict
1490    /// cofactorless verification via frost-ed25519).
1491    #[cfg(feature = "ed25519")]
1492    pub fn frost_verify_ed25519_minisign(
1493        group_pubkey: &[u8; 32],
1494        message: &[u8],
1495        sig: &crate::frost::ed25519::minisign::MinisignSignature,
1496    ) -> Result<()> {
1497        use crate::frost::ed25519::minisign;
1498
1499        if sig.key_id != minisign::key_id(group_pubkey) {
1500            return Err(KeepError::InvalidInput(
1501                "signature key id does not match group public key".into(),
1502            ));
1503        }
1504
1505        let signed_message = match sig.sig_alg {
1506            minisign::ALG_PREHASHED => minisign::prehash(message).to_vec(),
1507            minisign::ALG_LEGACY => message.to_vec(),
1508            _ => {
1509                return Err(KeepError::InvalidInput(
1510                    "unknown signature algorithm".into(),
1511                ))
1512            }
1513        };
1514
1515        crate::frost::ed25519::verify(group_pubkey, &signed_message, &sig.signature)?;
1516
1517        let global_bytes = minisign::global_signed_bytes(&sig.signature, &sig.trusted_comment);
1518        crate::frost::ed25519::verify(group_pubkey, &global_bytes, &sig.global_signature)
1519    }
1520
1521    fn load_keys_to_keyring(&mut self) -> Result<()> {
1522        let data_key = self.get_data_key()?;
1523        let records = self.storage.list_keys()?;
1524
1525        for record in records {
1526            let encrypted = crypto::EncryptedData::from_bytes(&record.encrypted_secret)?;
1527            let secret_bytes = crypto::decrypt(&encrypted, &data_key)?;
1528
1529            let mut secret = Zeroizing::new([0u8; 32]);
1530            let decrypted = secret_bytes.as_slice()?;
1531            secret.copy_from_slice(&decrypted);
1532
1533            self.keyring
1534                .load_key(record.pubkey, *secret, record.key_type, record.name)?;
1535        }
1536
1537        Ok(())
1538    }
1539
1540    fn get_data_key(&self) -> Result<SecretKey> {
1541        self.storage.data_key().cloned().ok_or(KeepError::Locked)
1542    }
1543
1544    /// Rotate the vault password.
1545    ///
1546    /// Re-encrypts the data encryption key with a new password-derived key.
1547    /// The data encryption key itself is unchanged, so stored secrets remain intact.
1548    ///
1549    /// Closes #579 (every post-storage-rotation failure path now emits a
1550    /// failure audit entry before propagating) and #580 (the success path
1551    /// uses `audit_event_required`, so a silent audit-write failure is
1552    /// surfaced as `KeepError::AuditWriteFailed`).
1553    pub fn rotate_password(&mut self, old_password: &str, new_password: &str) -> Result<()> {
1554        let result = self.rotate_password_inner(old_password, new_password);
1555        match &result {
1556            Ok(()) => self.audit_event_required(AuditEventType::PasswordRotate, |e| e),
1557            Err(e) => {
1558                // Failed attempts are observable only when the vault was
1559                // unlocked before the call (audit log needs the data key).
1560                let reason = e.to_string();
1561                self.audit_event(AuditEventType::PasswordRotateFailed, |entry| {
1562                    entry.with_success(false).with_reason(&reason)
1563                });
1564                result
1565            }
1566        }
1567    }
1568
1569    fn rotate_password_inner(&mut self, old_password: &str, new_password: &str) -> Result<()> {
1570        self.storage.rotate_password(old_password, new_password)?;
1571        self.keyring.clear();
1572        self.load_keys_to_keyring()?;
1573        Ok(())
1574    }
1575
1576    /// Rotate the data encryption key.
1577    ///
1578    /// Generates a new data encryption key and re-encrypts all stored keys and shares.
1579    ///
1580    /// Closes #579 (a failure before the storage commit audits
1581    /// DataKeyRotateFailed) and #580 (success path uses `audit_event_required`).
1582    pub fn rotate_data_key(&mut self, password: &str) -> Result<()> {
1583        // A locked vault has no data key, so the failure entry cannot be
1584        // encrypted/recorded here; `audit_event` no-ops in that case.
1585        let old_data_key = self.get_data_key()?;
1586
1587        // Pre-commit phase. `storage.rotate_data_key` rolls back internally on
1588        // failure, so the on-disk data key is unchanged and the audit chains
1589        // still match `old_data_key` == the current data key. The failure entry
1590        // therefore encrypts under the key matching the on-disk chain (#579).
1591        if let Err(e) = self.storage.rotate_data_key(password) {
1592            let reason = e.to_string();
1593            self.audit_event(AuditEventType::DataKeyRotateFailed, |entry| {
1594                entry.with_success(false).with_reason(&reason)
1595            });
1596            return Err(e);
1597        }
1598
1599        // Post-commit phase. Storage has durably committed the new data key, so
1600        // the rotation has already succeeded on disk; the audit chains are still
1601        // under `old_data_key` until re-encrypted below. A failure here must NOT
1602        // emit a DataKeyRotateFailed entry: it would be encrypted under the new
1603        // key and appended to a chain still under the old key (corrupting it,
1604        // since `reencrypt` is atomic and leaves the file under the old key on
1605        // failure), and it would misreport a rotation that already committed.
1606        let new_data_key = self.get_data_key()?;
1607        if let Some(ref mut audit) = self.audit {
1608            audit.reencrypt(&old_data_key, &new_data_key)?;
1609        }
1610        if let Some(ref mut signing_audit) = self.signing_audit {
1611            signing_audit.reencrypt(&old_data_key, &new_data_key)?;
1612        }
1613
1614        // Both chains are now under `new_data_key`, so record the success entry
1615        // before reloading the keyring (#580 fails closed). The rotation has
1616        // already committed; the keyring is in-memory and rebuilt on the next
1617        // unlock, so a reload failure must not leave the rotation unrecorded.
1618        self.audit_event_required(AuditEventType::DataKeyRotate, |e| e)?;
1619
1620        self.keyring.clear();
1621        self.load_keys_to_keyring()
1622    }
1623
1624    /// Returns the data encryption key used to encrypt stored secrets.
1625    ///
1626    /// # Errors
1627    /// Returns [`KeepError::Locked`] if [`unlock()`](Self::unlock) has not been called.
1628    ///
1629    /// Exposed for FROST/FrostSigner integration to decrypt stored shares.
1630    pub fn data_key(&self) -> Result<SecretKey> {
1631        self.get_data_key()
1632    }
1633
1634    /// Store a pre-encrypted key record directly (for backup restore).
1635    pub(crate) fn restore_key_record(&self, record: &KeyRecord) -> Result<()> {
1636        self.get_data_key()?;
1637        self.storage.store_key(record)
1638    }
1639
1640    /// Store a pre-encrypted share directly (for backup restore).
1641    pub(crate) fn restore_stored_share(&self, share: &StoredShare) -> Result<()> {
1642        self.get_data_key()?;
1643        self.storage.store_share(share)
1644    }
1645
1646    fn audit_event<F>(&mut self, event_type: AuditEventType, builder: F)
1647    where
1648        F: FnOnce(AuditEntry) -> AuditEntry,
1649    {
1650        let data_key = match self.get_data_key() {
1651            Ok(k) => k,
1652            Err(_) => return,
1653        };
1654        if let Some(ref mut audit) = self.audit {
1655            let entry = builder(AuditEntry::new(event_type, audit.last_hash()));
1656            if let Err(e) = audit.log(entry, &data_key) {
1657                tracing::warn!("Failed to write audit log entry for {}: {}", event_type, e);
1658            }
1659        }
1660    }
1661
1662    /// Audit-write that propagates failure to the caller. Used for
1663    /// security-critical events where a silent best-effort log (#580) is
1664    /// unacceptable: a successful return MUST mean the audit entry was
1665    /// persisted. Fails closed when the vault is locked or the audit log is
1666    /// unavailable.
1667    fn audit_event_required<F>(&mut self, event_type: AuditEventType, builder: F) -> Result<()>
1668    where
1669        F: FnOnce(AuditEntry) -> AuditEntry,
1670    {
1671        let data_key = self.get_data_key()?;
1672        let audit = self.audit.as_mut().ok_or_else(|| {
1673            KeepError::AuditWriteFailed(format!(
1674                "audit log not initialized; cannot record required event {event_type}"
1675            ))
1676        })?;
1677        let entry = builder(AuditEntry::new(event_type, audit.last_hash()));
1678        audit
1679            .log(entry, &data_key)
1680            .map_err(|e| KeepError::AuditWriteFailed(format!("{event_type}: {e}")))
1681    }
1682
1683    /// Read all audit log entries.
1684    pub fn audit_read_all(&self) -> Result<Vec<AuditEntry>> {
1685        let (audit, data_key) = self.audit_with_key()?;
1686        audit.read_all(&data_key)
1687    }
1688
1689    /// Verify the integrity of the audit log chain.
1690    pub fn audit_verify_chain(&self) -> Result<bool> {
1691        let (audit, data_key) = self.audit_with_key()?;
1692        audit.verify_chain(&data_key)
1693    }
1694
1695    /// Export the audit log as JSON.
1696    pub fn audit_export(&self) -> Result<String> {
1697        let (audit, data_key) = self.audit_with_key()?;
1698        audit.export(&data_key)
1699    }
1700
1701    fn audit_with_key(&self) -> Result<(&AuditLog, SecretKey)> {
1702        let audit = self.audit.as_ref().ok_or(KeepError::Locked)?;
1703        let data_key = self.get_data_key()?;
1704        Ok((audit, data_key))
1705    }
1706
1707    /// Set the retention policy for the audit log.
1708    pub fn audit_set_retention(&mut self, policy: RetentionPolicy) {
1709        if let Some(ref mut audit) = self.audit {
1710            audit.set_retention(policy);
1711        }
1712    }
1713
1714    /// Apply the retention policy and return the number of entries removed.
1715    pub fn audit_apply_retention(&mut self) -> Result<usize> {
1716        let data_key = self.get_data_key()?;
1717        let audit = self.audit.as_mut().ok_or(KeepError::Locked)?;
1718        audit.apply_retention(&data_key)
1719    }
1720
1721    /// Log a signing audit entry.
1722    pub fn signing_audit_log(&mut self, entry: SigningAuditEntry) -> Result<()> {
1723        let data_key = self.get_data_key()?;
1724        let log = self.signing_audit.as_mut().ok_or(KeepError::Locked)?;
1725        log.log(entry, &data_key)
1726    }
1727
1728    /// Get the last hash of the signing audit chain.
1729    pub fn signing_audit_last_hash(&self) -> Result<[u8; 32]> {
1730        let log = self.signing_audit.as_ref().ok_or(KeepError::Locked)?;
1731        Ok(log.last_hash())
1732    }
1733
1734    /// Read a page of signing audit entries with metadata in a single decryption pass.
1735    pub fn signing_audit_read_page_with_metadata(
1736        &self,
1737        offset: usize,
1738        limit: usize,
1739        caller_filter: Option<&str>,
1740    ) -> Result<(Vec<SigningAuditEntry>, Vec<String>, usize)> {
1741        let (log, data_key) = self.signing_audit_with_key()?;
1742        log.read_page_with_metadata(&data_key, offset, limit, caller_filter)
1743    }
1744
1745    /// Verify the integrity of the signing audit chain and return the entry count.
1746    pub fn signing_audit_verify_chain(&self) -> Result<(bool, usize)> {
1747        let (log, data_key) = self.signing_audit_with_key()?;
1748        log.verify_chain(&data_key)
1749    }
1750
1751    fn signing_audit_with_key(&self) -> Result<(&SigningAuditLog, SecretKey)> {
1752        let log = self.signing_audit.as_ref().ok_or(KeepError::Locked)?;
1753        let data_key = self.get_data_key()?;
1754        Ok((log, data_key))
1755    }
1756}
1757
1758fn is_valid_hex_pubkey(s: &str) -> bool {
1759    s.len() == 64 && s.chars().all(|c| c.is_ascii_hexdigit())
1760}
1761
1762fn write_restricted(path: &Path, data: &[u8]) -> std::io::Result<()> {
1763    use std::io::Write;
1764    let mut opts = std::fs::OpenOptions::new();
1765    opts.write(true).create(true).truncate(true);
1766    #[cfg(unix)]
1767    {
1768        use std::os::unix::fs::OpenOptionsExt;
1769        opts.mode(0o600);
1770    }
1771    let mut file = opts.open(path)?;
1772    file.write_all(data)
1773}
1774
1775/// Returns the default path to the Keep directory (~/.keep).
1776/// Override with the `KEEP_HOME` environment variable.
1777pub fn default_keep_path() -> Result<PathBuf> {
1778    match std::env::var("KEEP_HOME") {
1779        Ok(val) if !val.trim().is_empty() => {
1780            let path = PathBuf::from(&val);
1781            if path.is_absolute() {
1782                Ok(path)
1783            } else {
1784                Err(KeepError::InvalidInput(
1785                    "KEEP_HOME must be an absolute path".into(),
1786                ))
1787            }
1788        }
1789        _ => dirs::home_dir()
1790            .map(|p| p.join(".keep"))
1791            .ok_or(KeepError::HomeNotFound),
1792    }
1793}
1794
1795#[cfg(test)]
1796mod tests {
1797    use super::*;
1798    use tempfile::tempdir;
1799
1800    fn test_keep(path: &Path) -> Keep {
1801        Storage::create(path, "testpass", crypto::Argon2Params::TESTING).unwrap();
1802        let mut keep = Keep::open(path).unwrap();
1803        keep.unlock("testpass").unwrap();
1804        keep
1805    }
1806
1807    #[test]
1808    fn rate_limit_trip_emits_audit_entry_on_next_unlock() {
1809        // The rate limiter trips after MAX_ATTEMPTS (5) failed unlocks. The
1810        // trip event must surface as a `RateLimitTripped` audit entry the
1811        // next time the operator successfully unlocks (#495).
1812        let dir = tempdir().unwrap();
1813        let path = dir.path().join("keep");
1814
1815        Storage::create(&path, "right-password", crypto::Argon2Params::TESTING).unwrap();
1816
1817        // Five failed attempts trips the limiter.
1818        for _ in 0..5 {
1819            let mut keep = Keep::open(&path).unwrap();
1820            let _ = keep.unlock("wrong-password");
1821        }
1822
1823        // The sixth attempt would hit the back-off; wait it out by clearing
1824        // the active rate-limit counter (the trip event lives in a separate
1825        // file that record_success deliberately does NOT touch).
1826        crate::rate_limit::record_success(&path);
1827
1828        let mut keep = Keep::open(&path).unwrap();
1829        keep.unlock("right-password").unwrap();
1830
1831        let entries = keep.audit_read_all().unwrap();
1832        let trips: Vec<_> = entries
1833            .iter()
1834            .filter(|e| matches!(e.event_type, AuditEventType::RateLimitTripped))
1835            .collect();
1836        assert_eq!(trips.len(), 1, "expected one trip entry, got {trips:#?}");
1837        assert!(!trips[0].success, "trip entry must record success=false");
1838        assert!(
1839            trips[0]
1840                .reason
1841                .as_deref()
1842                .is_some_and(|r| r.contains("rate limit")),
1843            "trip entry must carry a descriptive reason, got {:?}",
1844            trips[0].reason
1845        );
1846
1847        // Chronological order: RateLimitTripped precedes the VaultUnlock it
1848        // was discovered by, so the audit chain reflects the actual sequence
1849        // of lockout then recovery.
1850        let trip_idx = entries
1851            .iter()
1852            .position(|e| matches!(e.event_type, AuditEventType::RateLimitTripped))
1853            .unwrap();
1854        let unlock_idx = entries
1855            .iter()
1856            .rposition(|e| matches!(e.event_type, AuditEventType::VaultUnlock))
1857            .unwrap();
1858        assert!(trip_idx < unlock_idx);
1859
1860        // Subsequent unlocks don't re-emit the same trip.
1861        keep.lock();
1862        let mut keep = Keep::open(&path).unwrap();
1863        keep.unlock("right-password").unwrap();
1864        let entries = keep.audit_read_all().unwrap();
1865        let trip_count = entries
1866            .iter()
1867            .filter(|e| matches!(e.event_type, AuditEventType::RateLimitTripped))
1868            .count();
1869        assert_eq!(
1870            trip_count, 1,
1871            "trip entry must not duplicate on later unlocks"
1872        );
1873    }
1874
1875    #[test]
1876    fn test_keep_create_and_unlock() {
1877        let dir = tempdir().unwrap();
1878        let path = dir.path().join("keep");
1879
1880        {
1881            let keep = Keep::create(&path, "password").unwrap();
1882            assert!(keep.is_unlocked());
1883        }
1884
1885        {
1886            let mut keep = Keep::open(&path).unwrap();
1887            assert!(!keep.is_unlocked());
1888            keep.unlock("password").unwrap();
1889            assert!(keep.is_unlocked());
1890        }
1891    }
1892
1893    #[test]
1894    fn test_keep_generate_key() {
1895        let dir = tempdir().unwrap();
1896        let path = dir.path().join("keep");
1897
1898        let mut keep = test_keep(&path);
1899        let pubkey = keep.generate_key("test").unwrap();
1900
1901        assert_eq!(keep.keyring().len(), 1);
1902        assert!(keep.keyring().get(&pubkey).is_some());
1903        assert!(keep.keyring().get_by_name("test").is_some());
1904    }
1905
1906    #[test]
1907    fn test_keep_lock() {
1908        let dir = tempdir().unwrap();
1909        let path = dir.path().join("keep");
1910
1911        let mut keep = test_keep(&path);
1912        keep.generate_key("test").unwrap();
1913        assert!(keep.is_unlocked());
1914
1915        keep.lock();
1916        assert!(!keep.is_unlocked());
1917        assert_eq!(keep.keyring().len(), 0);
1918    }
1919
1920    #[test]
1921    fn test_keep_primary_key() {
1922        let dir = tempdir().unwrap();
1923        let path = dir.path().join("keep");
1924
1925        let mut keep = test_keep(&path);
1926        assert!(keep.get_primary_key().is_none());
1927
1928        keep.generate_key("first").unwrap();
1929        let primary = keep.get_primary_key().unwrap();
1930        assert_eq!(primary.name, "first");
1931    }
1932
1933    #[test]
1934    fn test_frost_generate_and_sign() {
1935        let dir = tempdir().unwrap();
1936        let path = dir.path().join("keep");
1937
1938        let mut keep = test_keep(&path);
1939
1940        let shares = keep.frost_generate(2, 3, "frost-test").unwrap();
1941        assert_eq!(shares.len(), 3);
1942
1943        let group_pubkey = *shares[0].group_pubkey();
1944
1945        let message = b"test message to sign with FROST";
1946        let signature = keep.frost_sign(&group_pubkey, message).unwrap();
1947
1948        assert_eq!(signature.len(), 64);
1949
1950        let stored_shares = keep.frost_list_shares().unwrap();
1951        assert_eq!(stored_shares.len(), 3);
1952    }
1953
1954    #[test]
1955    fn test_frost_split_preserves_npub() {
1956        let dir = tempdir().unwrap();
1957        let path = dir.path().join("keep");
1958
1959        let mut keep = test_keep(&path);
1960
1961        let pubkey = keep.generate_key("to-split").unwrap();
1962
1963        let shares = keep.frost_split("to-split", 2, 3).unwrap();
1964        assert_eq!(shares.len(), 3);
1965
1966        let frost_pubkey = *shares[0].group_pubkey();
1967        assert_eq!(frost_pubkey, pubkey);
1968
1969        let message = b"sign with split key";
1970        let signature = keep.frost_sign(&frost_pubkey, message).unwrap();
1971        assert_eq!(signature.len(), 64);
1972    }
1973
1974    #[cfg(feature = "ed25519")]
1975    #[test]
1976    fn test_frost_ed25519_generate_sign_verify() {
1977        let dir = tempdir().unwrap();
1978        let path = dir.path().join("keep");
1979        let mut keep = test_keep(&path);
1980
1981        let shares = keep.frost_generate_ed25519(2, 3, "release").unwrap();
1982        assert_eq!(shares.len(), 3);
1983        let group_pubkey = *shares[0].group_pubkey();
1984
1985        let message = b"release artifact v1.0";
1986        let signature = keep.frost_sign_ed25519(&group_pubkey, message).unwrap();
1987        assert_eq!(signature.len(), 64);
1988
1989        Keep::frost_verify_ed25519(&group_pubkey, message, &signature).unwrap();
1990        assert!(Keep::frost_verify_ed25519(&group_pubkey, b"tampered", &signature).is_err());
1991
1992        // Shares persisted across reopen carry the Ed25519 ciphersuite tag and
1993        // still sign after the versioned-blob round-trip through storage.
1994        drop(keep);
1995        let mut keep = Keep::open(&path).unwrap();
1996        keep.unlock("testpass").unwrap();
1997        let sig2 = keep.frost_sign_ed25519(&group_pubkey, message).unwrap();
1998        Keep::frost_verify_ed25519(&group_pubkey, message, &sig2).unwrap();
1999    }
2000
2001    #[cfg(feature = "ed25519")]
2002    #[test]
2003    fn test_frost_ed25519_export_import_sign() {
2004        let src_dir = tempdir().unwrap();
2005        let src_path = src_dir.path().join("keep");
2006        let mut src = test_keep(&src_path);
2007
2008        let shares = src.frost_generate_ed25519(2, 3, "release").unwrap();
2009        let group_pubkey = *shares[0].group_pubkey();
2010
2011        let exports: Vec<_> = shares
2012            .iter()
2013            .take(2)
2014            .map(|s| {
2015                let export = src
2016                    .frost_export_share(&group_pubkey, s.metadata.identifier, "transfer-pass")
2017                    .unwrap();
2018                assert_eq!(export.ciphersuite, crate::frost::Ciphersuite::Ed25519);
2019                export
2020            })
2021            .collect();
2022
2023        let dst_dir = tempdir().unwrap();
2024        let dst_path = dst_dir.path().join("keep");
2025        let mut dst = test_keep(&dst_path);
2026
2027        for (i, export) in exports.iter().enumerate() {
2028            dst.frost_import_share(export, "transfer-pass", &format!("imported-{i}"))
2029                .unwrap();
2030        }
2031
2032        let message = b"exported then imported";
2033        let sig = dst.frost_sign_ed25519(&group_pubkey, message).unwrap();
2034        Keep::frost_verify_ed25519(&group_pubkey, message, &sig).unwrap();
2035    }
2036
2037    #[cfg(feature = "ed25519")]
2038    #[test]
2039    fn test_frost_ed25519_data_key_rotation() {
2040        let dir = tempdir().unwrap();
2041        let path = dir.path().join("keep");
2042        let mut keep = test_keep(&path);
2043
2044        let shares = keep.frost_generate_ed25519(2, 3, "release").unwrap();
2045        let group_pubkey = *shares[0].group_pubkey();
2046
2047        // Rotation re-encrypts the inner key package under the ciphersuite AAD
2048        // and verifies it; an Ed25519 vault must rotate without failing.
2049        keep.rotate_data_key("testpass").unwrap();
2050
2051        let message = b"after rotation";
2052        let sig = keep.frost_sign_ed25519(&group_pubkey, message).unwrap();
2053        Keep::frost_verify_ed25519(&group_pubkey, message, &sig).unwrap();
2054    }
2055
2056    #[cfg(feature = "ed25519")]
2057    #[test]
2058    fn test_frost_ed25519_minisign_round_trip() {
2059        use crate::frost::ed25519::minisign::MinisignSignature;
2060
2061        let dir = tempdir().unwrap();
2062        let path = dir.path().join("keep");
2063        let mut keep = test_keep(&path);
2064
2065        let shares = keep.frost_generate_ed25519(2, 3, "release").unwrap();
2066        let group_pubkey = *shares[0].group_pubkey();
2067
2068        let message = b"release artifact v2.0";
2069        let sig = keep
2070            .frost_sign_ed25519_minisign(
2071                &group_pubkey,
2072                message,
2073                "untrusted".into(),
2074                "trusted:abc".into(),
2075            )
2076            .unwrap();
2077
2078        // Full struct verifies (file + global signatures).
2079        Keep::frost_verify_ed25519_minisign(&group_pubkey, message, &sig).unwrap();
2080
2081        // Survives encode/parse round-trip.
2082        let encoded = sig.encode().unwrap();
2083        let parsed = MinisignSignature::parse(&encoded).unwrap();
2084        Keep::frost_verify_ed25519_minisign(&group_pubkey, message, &parsed).unwrap();
2085
2086        // Tampered message rejected.
2087        assert!(Keep::frost_verify_ed25519_minisign(&group_pubkey, b"tampered", &parsed).is_err());
2088
2089        // Tampered trusted comment breaks the global signature.
2090        let mut bad = MinisignSignature::parse(&encoded).unwrap();
2091        bad.trusted_comment = "trusted:evil".into();
2092        assert!(Keep::frost_verify_ed25519_minisign(&group_pubkey, message, &bad).is_err());
2093
2094        // Wrong group public key fails the key-id check.
2095        let wrong = [0u8; 32];
2096        assert!(Keep::frost_verify_ed25519_minisign(&wrong, message, &parsed).is_err());
2097    }
2098
2099    #[cfg(feature = "ed25519")]
2100    #[test]
2101    fn test_frost_ed25519_minisign_external_binary() {
2102        use crate::frost::ed25519::minisign::MinisignPublicKey;
2103        use std::process::Command;
2104
2105        // Prefer the C minisign binary; fall back to rsign2 (rsign), which is
2106        // byte-format compatible with minisign. Skip if neither is installed.
2107        let verifier = if Command::new("minisign").arg("-v").output().is_ok() {
2108            "minisign"
2109        } else if Command::new("rsign").arg("--help").output().is_ok() {
2110            "rsign"
2111        } else {
2112            eprintln!("no minisign/rsign binary installed; skipping external cross-check");
2113            return;
2114        };
2115
2116        let dir = tempdir().unwrap();
2117        let path = dir.path().join("keep");
2118        let mut keep = test_keep(&path);
2119
2120        let shares = keep.frost_generate_ed25519(2, 3, "release").unwrap();
2121        let group_pubkey = *shares[0].group_pubkey();
2122
2123        let data_path = dir.path().join("artifact.bin");
2124        std::fs::write(&data_path, b"external minisign cross-check payload").unwrap();
2125        let message = std::fs::read(&data_path).unwrap();
2126
2127        let sig = keep
2128            .frost_sign_ed25519_minisign(
2129                &group_pubkey,
2130                &message,
2131                "keep test".into(),
2132                "timestamp:0\tfile:artifact.bin".into(),
2133            )
2134            .unwrap();
2135        let sig_path = dir.path().join("artifact.bin.minisig");
2136        std::fs::write(&sig_path, sig.encode().unwrap()).unwrap();
2137
2138        let pk = MinisignPublicKey::from_group_pubkey(&group_pubkey, "keep test".into());
2139        let pk_path = dir.path().join("keep.pub");
2140        std::fs::write(&pk_path, pk.encode().unwrap()).unwrap();
2141
2142        let output = match verifier {
2143            "minisign" => Command::new("minisign")
2144                .arg("-V")
2145                .arg("-p")
2146                .arg(&pk_path)
2147                .arg("-m")
2148                .arg(&data_path)
2149                .output()
2150                .expect("run minisign -V"),
2151            _ => Command::new("rsign")
2152                .arg("verify")
2153                .arg("-p")
2154                .arg(&pk_path)
2155                .arg("-x")
2156                .arg(&sig_path)
2157                .arg(&data_path)
2158                .output()
2159                .expect("run rsign verify"),
2160        };
2161        assert!(
2162            output.status.success(),
2163            "external verify ({verifier}) failed: {}{}",
2164            String::from_utf8_lossy(&output.stdout),
2165            String::from_utf8_lossy(&output.stderr),
2166        );
2167    }
2168
2169    #[test]
2170    fn test_frost_insufficient_shares_fails() {
2171        use crate::frost::{SigningSession, ThresholdConfig, TrustedDealer};
2172
2173        let config = ThresholdConfig::two_of_three();
2174        let dealer = TrustedDealer::new(config);
2175        let (shares, _) = dealer.generate("test").unwrap();
2176
2177        let message = b"test".to_vec();
2178        let kp0 = shares[0].key_package().unwrap();
2179
2180        let mut session = SigningSession::new(message, 2).unwrap();
2181        session.generate_commitment(&kp0).unwrap();
2182
2183        assert_eq!(session.commitments_needed(), 1);
2184        assert!(!session.is_complete());
2185    }
2186
2187    #[test]
2188    fn test_keep_rotate_password() {
2189        let dir = tempdir().unwrap();
2190        let path = dir.path().join("keep");
2191
2192        {
2193            let mut keep = test_keep(&path);
2194            keep.generate_key("rotatetest").unwrap();
2195        }
2196
2197        {
2198            let mut keep = Keep::open(&path).unwrap();
2199            keep.unlock("testpass").unwrap();
2200            keep.rotate_password("testpass", "newpass1").unwrap();
2201        }
2202
2203        {
2204            let mut keep = Keep::open(&path).unwrap();
2205            assert!(keep.unlock("testpass").is_err());
2206        }
2207
2208        {
2209            let mut keep = Keep::open(&path).unwrap();
2210            keep.unlock("newpass1").unwrap();
2211            assert!(keep.keyring().get_by_name("rotatetest").is_some());
2212        }
2213    }
2214
2215    #[test]
2216    fn test_is_valid_hex_pubkey() {
2217        let valid = "a".repeat(64);
2218        assert!(is_valid_hex_pubkey(&valid));
2219
2220        let mixed_hex = "0123456789abcdef".repeat(4);
2221        assert!(is_valid_hex_pubkey(&mixed_hex));
2222
2223        // is_ascii_hexdigit accepts A-F; set_active_share_key normalizes
2224        // to lowercase before persisting.
2225        let upper = "A".repeat(64);
2226        assert!(is_valid_hex_pubkey(&upper));
2227
2228        assert!(!is_valid_hex_pubkey(&"a".repeat(63)));
2229        assert!(!is_valid_hex_pubkey(&"a".repeat(65)));
2230        assert!(!is_valid_hex_pubkey(""));
2231        assert!(!is_valid_hex_pubkey(
2232            "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
2233        ));
2234    }
2235
2236    #[test]
2237    fn test_keep_rotate_data_key() {
2238        let dir = tempdir().unwrap();
2239        let path = dir.path().join("keep");
2240
2241        let pubkey;
2242        {
2243            let mut keep = test_keep(&path);
2244            pubkey = keep.generate_key("dektest").unwrap();
2245        }
2246
2247        {
2248            let mut keep = Keep::open(&path).unwrap();
2249            keep.unlock("testpass").unwrap();
2250            keep.rotate_data_key("testpass").unwrap();
2251            assert!(keep.keyring().get(&pubkey).is_some());
2252        }
2253
2254        {
2255            let mut keep = Keep::open(&path).unwrap();
2256            keep.unlock("testpass").unwrap();
2257            let slot = keep.keyring().get(&pubkey).unwrap();
2258            assert_eq!(slot.name, "dektest");
2259        }
2260    }
2261
2262    // === #566: audit-log entries for rotation security operations ===
2263
2264    /// `Keep::rotate_password` MUST emit a `PasswordRotate` audit entry on
2265    /// success. Without this, security-sensitive password rotations leave no
2266    /// observable trace for the operator or for post-incident review.
2267    #[test]
2268    fn rotate_password_emits_success_audit_entry() {
2269        let dir = tempdir().unwrap();
2270        let path = dir.path().join("keep");
2271        {
2272            let mut keep = test_keep(&path);
2273            keep.generate_key("audited").unwrap();
2274            keep.rotate_password("testpass", "newpass1").unwrap();
2275            let entries = keep.audit_read_all().unwrap();
2276            assert!(
2277                entries
2278                    .iter()
2279                    .any(|e| e.event_type == AuditEventType::PasswordRotate),
2280                "PasswordRotate entry missing from audit log: {:?}",
2281                entries.iter().map(|e| e.event_type).collect::<Vec<_>>()
2282            );
2283        }
2284        // Re-open with the NEW password to confirm the audit log survived the
2285        // header rotation and still chain-verifies.
2286        let mut keep = Keep::open(&path).unwrap();
2287        keep.unlock("newpass1").unwrap();
2288        keep.audit_verify_chain().unwrap();
2289        let entries = keep.audit_read_all().unwrap();
2290        assert!(entries
2291            .iter()
2292            .any(|e| e.event_type == AuditEventType::PasswordRotate));
2293    }
2294
2295    /// `Keep::rotate_password` MUST emit a `PasswordRotateFailed` audit entry
2296    /// when the call is rejected, so failed attacker attempts are observable.
2297    /// Failed attempts on an already-locked vault cannot be recorded (data
2298    /// key unavailable); this test exercises the unlocked path and uses an
2299    /// invalid new password as the failure trigger because Storage's
2300    /// `rotate_password` short-circuits the wrong-old-password check when
2301    /// the vault is already unlocked (which is the path that admits audit
2302    /// writes), while `validate_new_password` is enforced unconditionally.
2303    #[test]
2304    fn rotate_password_emits_failure_audit_entry_when_unlocked() {
2305        let dir = tempdir().unwrap();
2306        let path = dir.path().join("keep");
2307        let mut keep = test_keep(&path);
2308        keep.generate_key("audited").unwrap();
2309
2310        let pre = keep.audit_read_all().unwrap().len();
2311
2312        // Empty new password: validate_new_password rejects.
2313        assert!(keep.rotate_password("testpass", "").is_err());
2314        let after_empty = keep.audit_read_all().unwrap();
2315        assert!(
2316            after_empty.len() > pre,
2317            "audit log should grow on empty-new-password rejection"
2318        );
2319        let failure = after_empty
2320            .iter()
2321            .find(|e| e.event_type == AuditEventType::PasswordRotateFailed)
2322            .expect("PasswordRotateFailed entry missing after empty-new-password rejection");
2323        assert!(
2324            !failure.success,
2325            "PasswordRotateFailed entry must be marked success=false"
2326        );
2327        assert!(
2328            failure.reason.is_some(),
2329            "PasswordRotateFailed entry must record a failure reason"
2330        );
2331
2332        // Too-short new password: same rejection.
2333        let pre2 = keep.audit_read_all().unwrap().len();
2334        assert!(keep.rotate_password("testpass", "a").is_err());
2335        let entries = keep.audit_read_all().unwrap();
2336        assert!(
2337            entries.len() > pre2,
2338            "audit log should grow on too-short-new-password rejection"
2339        );
2340        // The original password still unlocks: failure paths don't corrupt
2341        // the header. Drop the first handle before reopening so the vault
2342        // file lock is released.
2343        drop(keep);
2344        let mut reopened = Keep::open(&path).unwrap();
2345        reopened.unlock("testpass").unwrap();
2346    }
2347
2348    /// `Keep::rotate_data_key` MUST emit a `DataKeyRotate` audit entry on
2349    /// success. The entry's payload is encrypted under the NEW data key (the
2350    /// log gets re-encrypted as part of rotation); this test confirms the
2351    /// entry is readable after rotation and the chain still verifies.
2352    #[test]
2353    fn rotate_data_key_emits_success_audit_entry() {
2354        let dir = tempdir().unwrap();
2355        let path = dir.path().join("keep");
2356        {
2357            let mut keep = test_keep(&path);
2358            keep.generate_key("dek-audit").unwrap();
2359            keep.rotate_data_key("testpass").unwrap();
2360            let entries = keep.audit_read_all().unwrap();
2361            assert!(
2362                entries
2363                    .iter()
2364                    .any(|e| e.event_type == AuditEventType::DataKeyRotate),
2365                "DataKeyRotate entry missing from audit log: {:?}",
2366                entries.iter().map(|e| e.event_type).collect::<Vec<_>>()
2367            );
2368            // The audit log was re-encrypted under the new data key during
2369            // rotation; the chain over both pre- and post-rotation entries
2370            // must remain valid.
2371            keep.audit_verify_chain().unwrap();
2372        }
2373        // Confirm persistence: re-open and the entry is still there.
2374        let mut keep = Keep::open(&path).unwrap();
2375        keep.unlock("testpass").unwrap();
2376        let entries = keep.audit_read_all().unwrap();
2377        assert!(entries
2378            .iter()
2379            .any(|e| e.event_type == AuditEventType::DataKeyRotate));
2380    }
2381
2382    // === #581 / #579 / #580: rotation hardening ===
2383
2384    /// `Keep::rotate_password` MUST reject a wrong `old_password` even when the
2385    /// vault is already unlocked (#581). Without this, anyone with access to
2386    /// an unlocked Keep could re-wrap the data key without proving knowledge
2387    /// of the prior credential.
2388    #[test]
2389    fn rotate_password_rejects_wrong_old_password_when_already_unlocked() {
2390        let dir = tempdir().unwrap();
2391        let path = dir.path().join("keep");
2392        let mut keep = test_keep(&path);
2393
2394        // Vault is unlocked. The rotation should still refuse without the
2395        // correct old password.
2396        let err = keep
2397            .rotate_password("NOT_THE_OLD_PASSWORD", "newpass1")
2398            .expect_err("wrong old password must be refused even when unlocked");
2399        let _ = err; // shape varies, pin only on error path
2400
2401        // The original password still unlocks: failure paths do not corrupt
2402        // the header.
2403        drop(keep);
2404        let mut reopened = Keep::open(&path).unwrap();
2405        reopened.unlock("testpass").unwrap();
2406    }
2407
2408    /// Same gap on `rotate_data_key`: wrong password rejected even when
2409    /// already unlocked (#581).
2410    #[test]
2411    fn rotate_data_key_rejects_wrong_password_when_already_unlocked() {
2412        let dir = tempdir().unwrap();
2413        let path = dir.path().join("keep");
2414        let mut keep = test_keep(&path);
2415
2416        let err = keep
2417            .rotate_data_key("WRONG_PASSWORD")
2418            .expect_err("wrong password must be refused even when unlocked");
2419        let _ = err;
2420
2421        drop(keep);
2422        let mut reopened = Keep::open(&path).unwrap();
2423        reopened.unlock("testpass").unwrap();
2424    }
2425
2426    /// `Keep::rotate_password` MUST emit a `PasswordRotateFailed` audit entry
2427    /// when the wrong-old-password gate (#581) fires on an unlocked vault.
2428    /// Without this, an attacker's failed rotation attempts on a hijacked
2429    /// unlocked Keep would be unobservable.
2430    #[test]
2431    fn rotate_password_wrong_old_password_emits_failure_audit_entry() {
2432        let dir = tempdir().unwrap();
2433        let path = dir.path().join("keep");
2434        let mut keep = test_keep(&path);
2435
2436        let pre = keep.audit_read_all().unwrap().len();
2437        assert!(keep
2438            .rotate_password("WRONG_OLD_PASSWORD", "newpass1")
2439            .is_err());
2440        let entries = keep.audit_read_all().unwrap();
2441        assert!(
2442            entries.len() > pre,
2443            "audit log must grow on a rejected rotation"
2444        );
2445        assert!(
2446            entries
2447                .iter()
2448                .any(|e| e.event_type == AuditEventType::PasswordRotateFailed),
2449            "PasswordRotateFailed entry missing after wrong-old-password rejection"
2450        );
2451    }
2452
2453    #[test]
2454    fn test_default_keep_path_from_env() {
2455        let abs_path = if cfg!(windows) {
2456            "C:\\tmp\\my-keep"
2457        } else {
2458            "/tmp/my-keep"
2459        };
2460        temp_env::with_var("KEEP_HOME", Some(abs_path), || {
2461            let p = default_keep_path().unwrap();
2462            assert_eq!(p, PathBuf::from(abs_path));
2463        });
2464    }
2465
2466    #[test]
2467    fn test_default_keep_path_relative_env_rejected() {
2468        temp_env::with_var("KEEP_HOME", Some("relative/path"), || {
2469            let result = default_keep_path();
2470            assert!(result.is_err());
2471        });
2472    }
2473
2474    #[test]
2475    fn test_default_keep_path_empty_env_falls_back() {
2476        temp_env::with_var("KEEP_HOME", Some(""), || {
2477            let p = default_keep_path().unwrap();
2478            let expected = dirs::home_dir().unwrap().join(".keep");
2479            assert_eq!(p, expected);
2480        });
2481    }
2482
2483    #[test]
2484    fn test_default_keep_path_blank_env_falls_back() {
2485        temp_env::with_var("KEEP_HOME", Some("   "), || {
2486            let p = default_keep_path().unwrap();
2487            let expected = dirs::home_dir().unwrap().join(".keep");
2488            assert_eq!(p, expected);
2489        });
2490    }
2491
2492    /// Run a software DKG group in-process, persist every finalized share via
2493    /// `frost_store_dkg_share`, and confirm the shares reload with intact
2494    /// metadata and can be exported. Covers the finalize -> SharePackage ->
2495    /// encrypt -> store -> reload bridge that the DKG unit tests do not touch.
2496    #[test]
2497    fn test_frost_store_dkg_share_roundtrip() {
2498        use crate::frost::dkg::{SoftwareDkgSession, SoftwareRound1Wire, SoftwareRound2Wire};
2499
2500        let (threshold, participants): (u16, u16) = (2, 3);
2501
2502        let mut sessions: Vec<SoftwareDkgSession> = (1..=participants)
2503            .map(|idx| SoftwareDkgSession::init(threshold, participants, idx).unwrap())
2504            .collect();
2505
2506        let round1_wires: Vec<SoftwareRound1Wire> =
2507            sessions.iter_mut().map(|s| s.round1().unwrap()).collect();
2508        for (i, session) in sessions.iter_mut().enumerate() {
2509            for (j, wire) in round1_wires.iter().enumerate() {
2510                if i != j {
2511                    session.round1_peer(wire).unwrap();
2512                }
2513            }
2514        }
2515
2516        let mut per_session_round2: Vec<Vec<(u16, SoftwareRound2Wire)>> =
2517            sessions.iter_mut().map(|s| s.round2().unwrap()).collect();
2518        for (sender_i, wires) in per_session_round2.drain(..).enumerate() {
2519            for (recipient_index, wire) in wires {
2520                let recipient_i = (recipient_index - 1) as usize;
2521                assert_ne!(recipient_i, sender_i);
2522                sessions[recipient_i].receive_share(&wire).unwrap();
2523            }
2524        }
2525
2526        let results: Vec<_> = sessions.iter_mut().map(|s| s.finalize().unwrap()).collect();
2527        let group_pubkey = results[0].group_pubkey;
2528
2529        let dir = tempdir().unwrap();
2530        let path = dir.path().join("keep");
2531        let mut keep = test_keep(&path);
2532
2533        for r in &results {
2534            keep.frost_store_dkg_share(r, threshold, participants, "dkg-group")
2535                .unwrap();
2536        }
2537
2538        let shares = keep.frost_list_shares().unwrap();
2539        assert_eq!(shares.len(), participants as usize);
2540        for share in &shares {
2541            assert_eq!(share.metadata.group_pubkey, group_pubkey);
2542            assert_eq!(share.metadata.threshold, threshold);
2543            assert_eq!(share.metadata.total_shares, participants);
2544            assert_eq!(share.metadata.name, "dkg-group");
2545        }
2546        let indices: std::collections::BTreeSet<u16> =
2547            shares.iter().map(|s| s.metadata.identifier).collect();
2548        assert_eq!(indices, (1..=participants).collect());
2549
2550        // A stored share decrypts and exports under a passphrase.
2551        let export = keep
2552            .frost_export_share(&group_pubkey, results[0].our_index, "export-pass")
2553            .unwrap();
2554        drop(export);
2555
2556        // A locked vault refuses to store.
2557        keep.lock();
2558        assert!(matches!(
2559            keep.frost_store_dkg_share(&results[0], threshold, participants, "dkg-group"),
2560            Err(KeepError::Locked)
2561        ));
2562    }
2563}