Skip to main content

Keep

Struct Keep 

Source
pub struct Keep { /* private fields */ }
Expand description

The main Keep type for encrypted key management.

Implementations§

Source§

impl Keep

Source

pub fn set_state_publisher(&self, publisher: Arc<dyn StatePublisher>)

Install the keep-state replication sink on the underlying storage (keep-web wires this to a publisher that ships each vault-state change to the state relay). See StatePublisher.

Source

pub fn apply_replicated_record( &self, table: &str, record_id: &str, encrypted: &[u8], created_at: u64, now: u64, ) -> Result<ReplicatedApply>

Apply a record replicated from a peer into storage (the standby consumer side). Delegates to Storage::apply_replicated_record; never echoes back to the relay.

Source

pub fn apply_replicated_delete( &self, table: &str, record_id: &str, created_at: u64, now: u64, ) -> Result<ReplicatedApply>

Apply a replicated delete (tombstone) from a peer. now is local wall-clock, used to reject an implausibly future-dated event (see Storage::apply_replicated_delete).

Source

pub fn state_version(&self, table: &str, record_id: &str) -> Result<Option<u64>>

The persisted rollback high-water-mark for one replicated record’s d-tag (None if never applied), for seeding the publisher’s per-d-tag floor. See Storage::state_version.

Source

pub fn snapshot_replicable_records( &self, ) -> Result<Vec<(&'static str, String, Vec<u8>)>>

Snapshot all replicable records for the keep-state publisher to replay at startup, so records written before the replication hook was installed still reach a fresh standby. See Storage::snapshot_replicable_records.

Source

pub fn create(path: &Path, password: &str) -> Result<Self>

Create a new Keep with the given password.

§Example
use std::path::Path;
use keep_core::Keep;

let keep = Keep::create(Path::new("/tmp/my-keep"), "password")?;
assert!(keep.is_unlocked());
§Errors

Returns KeepError::AlreadyExists if a Keep already exists at the path.

Source

pub fn create_with_params( path: &Path, password: &str, params: Argon2Params, ) -> Result<Self>

Create a new Keep with custom Argon2 parameters.

Source

pub fn create_with_shared_data_key( path: &Path, password: &str, params: Argon2Params, data_key: Zeroizing<[u8; 32]>, ) -> Result<Self>

Like Self::create_with_params but seeds a shared record-encryption key, so every node in a cluster shares one vault key (keep-state replication) and a standby decrypts what the active shipped. Each node still wraps the key under its own password+salt.

Source

pub fn open(path: &Path) -> Result<Self>

Open an existing Keep.

§Example
use std::path::Path;
use keep_core::Keep;

let mut keep = Keep::open(Path::new("~/.keep"))?;
keep.unlock("password")?;
§Errors

Returns KeepError::NotFound if no Keep exists at the path.

Source

pub fn unlock(&mut self, password: &str) -> Result<()>

Unlock with the given password.

§Errors

Returns KeepError::InvalidPassword if the password is incorrect. Returns KeepError::RateLimited after too many failed attempts.

Source

pub fn verify_password(&self, password: &str) -> Result<()>

Verify a password without changing the unlock state.

Source

pub fn password_matches(&self, password: &str) -> Result<bool>

Read-only pre-flight check of whether password is this vault’s password, WITHOUT touching the rate limiter, audit log, keyring, or unlock state. Ok(true) = matches, Ok(false) = wrong password, Err = could not check. Unlike Self::verify_password it does not record a rate-limit attempt and is not blocked by an active backoff, so a pre-flight check cannot self-inflict a lockout nor be silently skipped. Because it does not rate-limit, use it only on local, operator-driven paths (e.g. the duress-provision anti-brick guard), never as a remote or automated unlock oracle.

Source

pub fn lock(&mut self)

Lock and clear all keys from memory.

Source

pub fn is_unlocked(&self) -> bool

Returns true if unlocked.

Source

pub fn argon2_params(&self) -> Argon2Params

The vault’s Argon2id parameters (from the header, readable before unlock). Non-secret; used to reproduce an unlock’s KDF cost without unlocking.

Source

pub fn generate_key(&mut self, name: &str) -> Result<[u8; 32]>

Generate a new Nostr keypair and store it.

§Example
let pubkey = keep.generate_key("my-nostr-key")?;
println!("Created key: {}", hex::encode(pubkey));
§Errors

Returns KeepError::Locked if the Keep is not unlocked.

Source

pub fn import_nsec(&mut self, nsec: &str, name: &str) -> Result<[u8; 32]>

Import an nsec and store it.

§Example
let nsec = "nsec1...";
let pubkey = keep.import_nsec(nsec, "imported-key")?;
§Errors

Returns KeepError::Locked if the Keep is not unlocked. Returns KeepError::InvalidNsec if the nsec format is invalid. Returns KeepError::KeyAlreadyExists if the key is already stored.

Source

pub fn import_secret_bytes( &mut self, secret: &mut [u8; 32], name: &str, ) -> Result<[u8; 32]>

Import a Nostr key from raw secret bytes.

Source

pub fn get_primary_key(&self) -> Option<&KeySlot>

The primary key slot, if set.

Source

pub fn list_keys(&self) -> Result<Vec<KeyRecord>>

List all stored key records.

Source

pub fn store_secret(&mut self, record: &SecretRecord) -> Result<()>

Store (insert or overwrite by id) an arbitrary-secret record (password, API token, note). The whole record, including its plaintext value and title, is encrypted under the vault data key at rest. See storage::Storage::store_secret. Records a SecretCreate audit event (tagged with the non-sensitive random id, never the name or value) so secret mutations leave a forensic trail like every other sensitive op.

Source

pub fn load_secret(&self, id: &[u8; 32]) -> Result<SecretRecord>

Load a secret record by its 32-byte id.

Source

pub fn list_secrets(&self) -> Result<Vec<SecretRecord>>

List all stored secret records.

Source

pub fn delete_secret(&mut self, id: &[u8; 32]) -> Result<()>

Delete a secret record by its 32-byte id. Records a SecretDelete audit event tagged with the id.

Source

pub fn restore_secret(&self, record: &SecretRecord) -> Result<()>

Restore a secret WITHOUT emitting an audit event, for the backup-restore path only. Restore re-establishes the source vault’s audit log verbatim (see VaultBackup::audit_entries), so re-auditing each restored row would double-count. Mirrors restore_key_record.

Source

pub fn store_sealed_secret( &mut self, record: SecretRecord, oprf_key: &SecretKey, epoch: u32, ) -> Result<SecretRecord>

Store a secret whose value can only be revealed with a t-of-n OPRF quorum.

Takes a caller-minted record (via crate::secret::SecretRecord::new) carrying the plaintext in record.value. The caller must mint the record FIRST so it knows the id, then derive oprf_key from the quorum for that id (oprf_id = hex(record.id), epoch) BEFORE calling this: the seal records oprf_id, and a reveal re-derives the key for the same id, so a key derived for any other id would seal a value no quorum could ever reopen.

oprf_key is the quorum-derived key ([crate::oprf::derive_luks_key] output); epoch its OPRF rotation counter. The value is sealed under a fresh per-secret DEK wrapped by oprf_key, so a single device that never assembles the quorum cannot decrypt it even with the vault unlocked. The record’s name/kind stay readable with the vault data key. Returns the stored record (its value now the DEK-ciphertext). Records a SecretCreate audit event.

Source

pub fn load_secret_seal(&self, id: &[u8; 32]) -> Result<Option<ThresholdSeal>>

Load the threshold seal for a secret id, or None if the secret is an ordinary plaintext-value secret. The seal carries the OPRF params (oprf_id, epoch) the quorum needs to re-derive the unwrapping key.

Source

pub fn reveal_sealed_secret( &mut self, id: &[u8; 32], oprf_key: &SecretKey, ) -> Result<Zeroizing<Vec<u8>>>

Reveal a threshold-sealed secret’s plaintext value given the OPRF-quorum -derived key. Errors if the secret is not sealed, or if oprf_key is wrong (a single-device caller that never assembled the quorum cannot derive it).

Records a SecretReveal audit event (tagged with the id) only on a successful unseal: revealing a quorum-gated plaintext is the most sensitive read in the store, audited like KeyExport. A wrong-key attempt leaves no entry (it never yields the value).

Source

pub fn restore_sealed_secret( &self, record: &SecretRecord, seal: &ThresholdSeal, ) -> Result<()>

Restore a threshold-sealed secret (record + seal) WITHOUT emitting an audit event, for the backup-restore path only. Mirrors Self::restore_secret.

Source

pub fn export_ncryptsec( &mut self, pubkey: &[u8; 32], password: &str, ) -> Result<String>

Export a stored nsec key as NIP-49 ncryptsec.

Source

pub fn delete_key(&mut self, pubkey: &[u8; 32]) -> Result<()>

Delete a key.

Source

pub fn keyring(&self) -> &Keyring

The keyring.

Source

pub fn read_audit_entries(&self) -> Result<Vec<AuditEntry>>

Decrypted audit log entries for this vault, in chronological order. Returns an empty vec if the audit log file does not exist yet.

§Errors

Returns KeepError::Locked if the vault is not unlocked.

Source

pub fn keyring_mut(&mut self) -> &mut Keyring

Mutable access to the keyring.

Source

pub fn frost_generate( &mut self, threshold: u16, total_shares: u16, name: &str, ) -> Result<Vec<SharePackage>>

Generate a new FROST key with the given threshold and total shares.

Source

pub fn frost_split( &mut self, key_name: &str, threshold: u16, total_shares: u16, ) -> Result<Vec<SharePackage>>

Split an existing key into FROST shares.

Source

pub fn frost_list_shares(&self) -> Result<Vec<StoredShare>>

List all stored FROST shares.

Source

pub fn frost_export_share( &mut self, group_pubkey: &[u8; 32], identifier: u16, passphrase: &str, ) -> Result<ShareExport>

Export a FROST share encrypted with a passphrase.

Source

pub fn frost_import_share( &mut self, export: &ShareExport, passphrase: &str, name: &str, ) -> Result<()>

Import a FROST share from an encrypted export.

Source

pub fn frost_store_dkg_share( &mut self, result: &SoftwareDkgResult, threshold: u16, total_shares: u16, name: &str, ) -> Result<()>

Persist a share produced by frost::dkg::SoftwareDkgSession::finalize (#454). Wraps the finalized KeyPackage + PublicKeyPackage into a SharePackage with fresh metadata, encrypts under the vault’s data key, stores it, and writes a FrostShareImport audit entry.

Source

pub fn frost_refresh( &mut self, group_pubkey: &[u8; 32], ) -> Result<Vec<ShareMetadata>>

Refresh all FROST shares for a group, invalidating old shares.

Source

pub fn frost_delete_share( &mut self, group_pubkey: &[u8; 32], identifier: u16, ) -> Result<()>

Delete a FROST share.

Source

pub fn frost_rename_share( &mut self, group_pubkey: &[u8; 32], identifier: u16, name: &str, ) -> Result<()>

Rename a stored FROST share (updates its display name only).

Source

pub fn get_active_share_key(&self) -> Option<String>

Get the hex-encoded group pubkey of the active share, if set.

Source

pub fn set_active_share_key(&self, key: Option<&str>) -> Result<()>

Set the active share by hex-encoded group pubkey. Pass None to clear.

Source

pub fn store_wallet_descriptor( &self, descriptor: &WalletDescriptor, ) -> Result<()>

Store a finalized wallet descriptor, associated with a FROST group.

Source

pub fn get_wallet_descriptor( &self, group_pubkey: &[u8; 32], ) -> Result<Option<WalletDescriptor>>

Get the wallet descriptor for a FROST group.

Source

pub fn list_wallet_descriptors(&self) -> Result<Vec<WalletDescriptor>>

List the latest-version wallet descriptor for every group. Older descriptor versions are not returned; use list_all_wallet_descriptor_versions when every row is required (backup, rotation re-encryption verification, etc.).

Source

pub fn list_all_wallet_descriptor_versions( &self, ) -> Result<Vec<WalletDescriptor>>

List every persisted wallet descriptor row across all groups and versions. Used by backup and rotation paths that must round-trip every stored record.

Source

pub fn delete_wallet_descriptor(&self, group_pubkey: &[u8; 32]) -> Result<()>

Delete a wallet descriptor.

Source

pub fn upsert_device_registration( &self, group_pubkey: &[u8; 32], registration: DeviceRegistration, ) -> Result<()>

Atomically insert or update a device registration on the descriptor for the given FROST group. Performs the load-modify-store under the storage’s descriptor write lock so concurrent callers cannot drop each other’s updates.

Source

pub fn store_health_status(&self, status: &KeyHealthStatus) -> Result<()>

Store a key health status record.

Source

pub fn get_health_status( &self, group_pubkey: &[u8; 32], share_index: u16, ) -> Result<Option<KeyHealthStatus>>

Get a key health status record.

Source

pub fn list_health_statuses(&self) -> Result<Vec<KeyHealthStatus>>

List all key health status records.

Source

pub fn list_stale_health_statuses( &self, now: u64, ) -> Result<Vec<KeyHealthStatus>>

List health statuses that are stale (not checked within the threshold).

Source

pub fn store_relay_config(&self, config: &RelayConfig) -> Result<()>

Store relay configuration for a FROST share.

Source

pub fn get_relay_config( &self, group_pubkey: &[u8; 32], ) -> Result<Option<RelayConfig>>

Get relay configuration for a FROST share.

Source

pub fn get_relay_config_or_default( &self, group_pubkey: &[u8; 32], ) -> Result<RelayConfig>

Get relay configuration for a FROST share, returning defaults if none stored.

Source

pub fn list_relay_configs(&self) -> Result<Vec<RelayConfig>>

List all stored relay configurations.

Source

pub fn delete_relay_config(&self, group_pubkey: &[u8; 32]) -> Result<()>

Delete relay configuration for a FROST share.

Source

pub fn get_kill_switch(&self) -> Result<bool>

Get the kill switch state from the vault.

Source

pub fn set_kill_switch(&self, active: bool) -> Result<()>

Set the kill switch state in the vault.

Source

pub fn get_proxy_config(&self) -> Result<ProxyConfig>

Get the proxy configuration.

Source

pub fn set_proxy_config(&self, config: &ProxyConfig) -> Result<()>

Set the proxy configuration.

Source

pub fn frost_get_share(&self, group_pubkey: &[u8; 32]) -> Result<SharePackage>

Get a FROST share by group public key.

Source

pub fn frost_get_share_by_index( &self, group_pubkey: &[u8; 32], identifier: u16, ) -> Result<SharePackage>

Get a FROST share by group public key and identifier index.

Source

pub fn frost_sign( &mut self, group_pubkey: &[u8; 32], message: &[u8], ) -> Result<[u8; 64]>

Sign using local FROST shares. Requires threshold shares locally.

Source

pub fn rotate_password( &mut self, old_password: &str, new_password: &str, ) -> Result<()>

Rotate the vault password.

Re-encrypts the data encryption key with a new password-derived key. The data encryption key itself is unchanged, so stored secrets remain intact.

Closes #579 (every post-storage-rotation failure path now emits a failure audit entry before propagating) and #580 (the success path uses audit_event_required, so a silent audit-write failure is surfaced as KeepError::AuditWriteFailed).

Source

pub fn rotate_data_key(&mut self, password: &str) -> Result<()>

Rotate the data encryption key.

Generates a new data encryption key and re-encrypts all stored keys and shares.

Closes #579 (a failure before the storage commit audits DataKeyRotateFailed) and #580 (success path uses audit_event_required).

Source

pub fn data_key(&self) -> Result<SecretKey>

Returns the data encryption key used to encrypt stored secrets.

§Errors

Returns KeepError::Locked if unlock() has not been called.

Exposed for FROST/FrostSigner integration to decrypt stored shares.

Source

pub fn audit_read_all(&self) -> Result<Vec<AuditEntry>>

Read all audit log entries.

Source

pub fn audit_verify_chain(&self) -> Result<bool>

Verify the integrity of the audit log chain.

Source

pub fn audit_export(&self) -> Result<String>

Export the audit log as JSON.

Source

pub fn audit_set_retention(&mut self, policy: RetentionPolicy)

Set the retention policy for the audit log.

Source

pub fn audit_apply_retention(&mut self) -> Result<usize>

Apply the retention policy and return the number of entries removed.

Source

pub fn signing_audit_log(&mut self, entry: SigningAuditEntry) -> Result<()>

Log a signing audit entry.

Source

pub fn signing_audit_last_hash(&self) -> Result<[u8; 32]>

Get the last hash of the signing audit chain.

Source

pub fn signing_audit_read_page_with_metadata( &self, offset: usize, limit: usize, caller_filter: Option<&str>, ) -> Result<(Vec<SigningAuditEntry>, Vec<String>, usize)>

Read a page of signing audit entries with metadata in a single decryption pass.

Source

pub fn signing_audit_verify_chain(&self) -> Result<(bool, usize)>

Verify the integrity of the signing audit chain and return the entry count.

Auto Trait Implementations§

§

impl !Freeze for Keep

§

impl !RefUnwindSafe for Keep

§

impl !UnwindSafe for Keep

§

impl Forget for Keep

§

impl Move for Keep

§

impl Send for Keep

§

impl Sync for Keep

§

impl Unpin for Keep

§

impl UnsafeUnpin for Keep

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more