Skip to main content

keep_core/
error.rs

1// SPDX-FileCopyrightText: © 2026 PrivKey LLC
2// SPDX-License-Identifier: MIT
3
4//! Error types for keep-core operations.
5use thiserror::Error;
6
7/// Machine-readable error codes for programmatic handling.
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9#[non_exhaustive]
10#[allow(missing_docs)]
11pub enum ErrorCode {
12    E1001,
13    E1002,
14    E1003,
15    E1004,
16    E1005,
17    E1006,
18    E1007,
19    E1008,
20    E1009,
21    E1010,
22    E2001,
23    E2002,
24    E2003,
25    E2004,
26    E2005,
27    E2006,
28    E3001,
29    E3002,
30    E3003,
31    E3004,
32    E3005,
33    E3006,
34    E3007,
35    E3008,
36    E3009,
37    E4001,
38    E4002,
39    E4003,
40    E4004,
41    E4005,
42    E4006,
43    E4007,
44    E4008,
45    E4009,
46}
47
48impl std::fmt::Display for ErrorCode {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        write!(f, "{self:?}")
51    }
52}
53
54/// Storage operation errors.
55#[derive(Error, Debug)]
56#[non_exhaustive]
57#[allow(missing_docs)]
58pub enum StorageError {
59    #[error("[{code}] File not found")]
60    FileNotFound { code: ErrorCode, path: String },
61    #[error("[{code}] File already exists")]
62    FileAlreadyExists { code: ErrorCode, path: String },
63    #[error("[{code}] Permission denied")]
64    PermissionDenied { code: ErrorCode, path: String },
65    #[error("[{code}] Invalid file format: {reason}")]
66    InvalidFormat { code: ErrorCode, reason: String },
67    #[error("[{code}] Database error: {message}")]
68    Database { code: ErrorCode, message: String },
69    #[error("[{code}] IO error: {message}")]
70    Io { code: ErrorCode, message: String },
71    #[error("[{code}] Home directory not found")]
72    HomeNotFound { code: ErrorCode },
73    #[error("[{code}] Migration failed: {message}")]
74    Migration { code: ErrorCode, message: String },
75    #[error("[{code}] Serialization failed: {message}")]
76    Serialization { code: ErrorCode, message: String },
77    #[error("[{code}] Hidden volume full")]
78    HiddenVolumeFull { code: ErrorCode },
79}
80
81#[allow(missing_docs)]
82impl StorageError {
83    pub fn file_not_found(path: impl Into<String>) -> Self {
84        Self::FileNotFound {
85            code: ErrorCode::E1001,
86            path: path.into(),
87        }
88    }
89
90    pub fn file_already_exists(path: impl Into<String>) -> Self {
91        Self::FileAlreadyExists {
92            code: ErrorCode::E1002,
93            path: path.into(),
94        }
95    }
96
97    pub fn permission_denied(path: impl Into<String>) -> Self {
98        Self::PermissionDenied {
99            code: ErrorCode::E1003,
100            path: path.into(),
101        }
102    }
103
104    pub fn invalid_format(reason: impl Into<String>) -> Self {
105        Self::InvalidFormat {
106            code: ErrorCode::E1004,
107            reason: reason.into(),
108        }
109    }
110
111    pub fn corrupted(message: impl Into<String>) -> Self {
112        Self::invalid_format(message)
113    }
114
115    pub fn database(message: impl Into<String>) -> Self {
116        Self::Database {
117            code: ErrorCode::E1005,
118            message: message.into(),
119        }
120    }
121
122    pub fn io(message: impl Into<String>) -> Self {
123        Self::Io {
124            code: ErrorCode::E1006,
125            message: message.into(),
126        }
127    }
128
129    pub fn home_not_found() -> Self {
130        Self::HomeNotFound {
131            code: ErrorCode::E1007,
132        }
133    }
134
135    pub fn migration(message: impl Into<String>) -> Self {
136        Self::Migration {
137            code: ErrorCode::E1008,
138            message: message.into(),
139        }
140    }
141
142    pub fn serialization(message: impl Into<String>) -> Self {
143        Self::Serialization {
144            code: ErrorCode::E1009,
145            message: message.into(),
146        }
147    }
148
149    pub fn hidden_volume_full() -> Self {
150        Self::HiddenVolumeFull {
151            code: ErrorCode::E1010,
152        }
153    }
154
155    pub fn code(&self) -> ErrorCode {
156        match self {
157            Self::FileNotFound { code, .. }
158            | Self::FileAlreadyExists { code, .. }
159            | Self::PermissionDenied { code, .. }
160            | Self::InvalidFormat { code, .. }
161            | Self::Database { code, .. }
162            | Self::Io { code, .. }
163            | Self::HomeNotFound { code }
164            | Self::Migration { code, .. }
165            | Self::Serialization { code, .. }
166            | Self::HiddenVolumeFull { code } => *code,
167        }
168    }
169
170    pub fn path(&self) -> Option<&str> {
171        match self {
172            Self::FileNotFound { path, .. }
173            | Self::FileAlreadyExists { path, .. }
174            | Self::PermissionDenied { path, .. } => Some(path.as_str()),
175            _ => None,
176        }
177    }
178}
179
180/// Cryptographic operation errors.
181#[derive(Error, Debug)]
182#[non_exhaustive]
183#[allow(missing_docs)]
184pub enum CryptoError {
185    #[error("[{code}] Encryption failed: {message}")]
186    Encryption { code: ErrorCode, message: String },
187    #[error("[{code}] Decryption failed: {message}")]
188    Decryption { code: ErrorCode, message: String },
189    #[error("[{code}] Invalid key: {message}")]
190    InvalidKey { code: ErrorCode, message: String },
191    #[error("[{code}] Key derivation failed: {message}")]
192    KeyDerivation { code: ErrorCode, message: String },
193    #[error("[{code}] Signature verification failed: {message}")]
194    SignatureVerification { code: ErrorCode, message: String },
195    #[error("[{code}] Invalid signature: {message}")]
196    InvalidSignature { code: ErrorCode, message: String },
197}
198
199#[allow(missing_docs)]
200impl CryptoError {
201    pub fn encryption(message: impl Into<String>) -> Self {
202        Self::Encryption {
203            code: ErrorCode::E2001,
204            message: message.into(),
205        }
206    }
207
208    pub fn decryption(message: impl Into<String>) -> Self {
209        Self::Decryption {
210            code: ErrorCode::E2002,
211            message: message.into(),
212        }
213    }
214
215    pub fn invalid_key(message: impl Into<String>) -> Self {
216        Self::InvalidKey {
217            code: ErrorCode::E2003,
218            message: message.into(),
219        }
220    }
221
222    pub fn key_derivation(message: impl Into<String>) -> Self {
223        Self::KeyDerivation {
224            code: ErrorCode::E2004,
225            message: message.into(),
226        }
227    }
228
229    pub fn kdf(message: impl Into<String>) -> Self {
230        Self::key_derivation(message)
231    }
232
233    pub fn signature_verification(message: impl Into<String>) -> Self {
234        Self::SignatureVerification {
235            code: ErrorCode::E2005,
236            message: message.into(),
237        }
238    }
239
240    pub fn invalid_signature(message: impl Into<String>) -> Self {
241        Self::InvalidSignature {
242            code: ErrorCode::E2006,
243            message: message.into(),
244        }
245    }
246
247    pub fn code(&self) -> ErrorCode {
248        match self {
249            Self::Encryption { code, .. }
250            | Self::Decryption { code, .. }
251            | Self::InvalidKey { code, .. }
252            | Self::KeyDerivation { code, .. }
253            | Self::SignatureVerification { code, .. }
254            | Self::InvalidSignature { code, .. } => *code,
255        }
256    }
257}
258
259/// FROST protocol errors.
260#[derive(Error, Debug)]
261#[non_exhaustive]
262#[allow(missing_docs)]
263pub enum FrostError {
264    #[error("[{code}] Threshold not met: need {needed}, have {available}")]
265    ThresholdNotMet {
266        code: ErrorCode,
267        needed: u16,
268        available: u16,
269    },
270    #[error("[{code}] Invalid share: {message}")]
271    InvalidShare { code: ErrorCode, message: String },
272    #[error("[{code}] Session error: {message}")]
273    Session { code: ErrorCode, message: String },
274    #[error("[{code}] Commitment error: {message}")]
275    Commitment { code: ErrorCode, message: String },
276    #[error("[{code}] Signature aggregation failed: {message}")]
277    Aggregation { code: ErrorCode, message: String },
278    #[error("[{code}] Invalid configuration: {message}")]
279    InvalidConfig { code: ErrorCode, message: String },
280    #[error("[{code}] DKG failed: {message}")]
281    Dkg { code: ErrorCode, message: String },
282    #[error("[{code}] Duplicate participant: {identifier}")]
283    DuplicateParticipant { code: ErrorCode, identifier: u16 },
284    #[error("[{code}] Unknown participant: {identifier}")]
285    UnknownParticipant { code: ErrorCode, identifier: u16 },
286}
287
288#[allow(missing_docs)]
289impl FrostError {
290    pub fn threshold_not_met(needed: u16, available: u16) -> Self {
291        Self::ThresholdNotMet {
292            code: ErrorCode::E3001,
293            needed,
294            available,
295        }
296    }
297
298    pub fn invalid_share(message: impl Into<String>) -> Self {
299        Self::InvalidShare {
300            code: ErrorCode::E3002,
301            message: message.into(),
302        }
303    }
304
305    pub fn session(message: impl Into<String>) -> Self {
306        Self::Session {
307            code: ErrorCode::E3003,
308            message: message.into(),
309        }
310    }
311
312    pub fn commitment(message: impl Into<String>) -> Self {
313        Self::Commitment {
314            code: ErrorCode::E3004,
315            message: message.into(),
316        }
317    }
318
319    pub fn aggregation(message: impl Into<String>) -> Self {
320        Self::Aggregation {
321            code: ErrorCode::E3005,
322            message: message.into(),
323        }
324    }
325
326    pub fn invalid_config(message: impl Into<String>) -> Self {
327        Self::InvalidConfig {
328            code: ErrorCode::E3006,
329            message: message.into(),
330        }
331    }
332
333    pub fn dkg(message: impl Into<String>) -> Self {
334        Self::Dkg {
335            code: ErrorCode::E3007,
336            message: message.into(),
337        }
338    }
339
340    pub fn duplicate_participant(identifier: u16) -> Self {
341        Self::DuplicateParticipant {
342            code: ErrorCode::E3008,
343            identifier,
344        }
345    }
346
347    pub fn unknown_participant(identifier: u16) -> Self {
348        Self::UnknownParticipant {
349            code: ErrorCode::E3009,
350            identifier,
351        }
352    }
353
354    pub fn code(&self) -> ErrorCode {
355        match self {
356            Self::ThresholdNotMet { code, .. }
357            | Self::InvalidShare { code, .. }
358            | Self::Session { code, .. }
359            | Self::Commitment { code, .. }
360            | Self::Aggregation { code, .. }
361            | Self::InvalidConfig { code, .. }
362            | Self::Dkg { code, .. }
363            | Self::DuplicateParticipant { code, .. }
364            | Self::UnknownParticipant { code, .. } => *code,
365        }
366    }
367}
368
369/// Network operation errors.
370#[derive(Error, Debug)]
371#[non_exhaustive]
372#[allow(missing_docs)]
373pub enum NetworkError {
374    #[error("[{code}] Connection failed: {message}")]
375    Connection { code: ErrorCode, message: String },
376    #[error("[{code}] Relay error: {message}")]
377    Relay { code: ErrorCode, message: String },
378    #[error("[{code}] Request failed: {message}")]
379    Request { code: ErrorCode, message: String },
380    #[error("[{code}] Response error: {message}")]
381    Response { code: ErrorCode, message: String },
382    #[error("[{code}] Timeout: {message}")]
383    Timeout { code: ErrorCode, message: String },
384    #[error("[{code}] Attestation failed: {message}")]
385    Attestation { code: ErrorCode, message: String },
386    #[error("[{code}] Subscribe failed: {message}")]
387    Subscribe { code: ErrorCode, message: String },
388    #[error("[{code}] Publish failed: {message}")]
389    Publish { code: ErrorCode, message: String },
390    #[error("[{code}] Warden error: {message}")]
391    Warden { code: ErrorCode, message: String },
392}
393
394#[allow(missing_docs)]
395impl NetworkError {
396    pub fn connection(message: impl Into<String>) -> Self {
397        Self::Connection {
398            code: ErrorCode::E4001,
399            message: message.into(),
400        }
401    }
402
403    pub fn relay(message: impl Into<String>) -> Self {
404        Self::Relay {
405            code: ErrorCode::E4002,
406            message: message.into(),
407        }
408    }
409
410    pub fn request(message: impl Into<String>) -> Self {
411        Self::Request {
412            code: ErrorCode::E4003,
413            message: message.into(),
414        }
415    }
416
417    pub fn response(message: impl Into<String>) -> Self {
418        Self::Response {
419            code: ErrorCode::E4004,
420            message: message.into(),
421        }
422    }
423
424    pub fn timeout(message: impl Into<String>) -> Self {
425        Self::Timeout {
426            code: ErrorCode::E4005,
427            message: message.into(),
428        }
429    }
430
431    pub fn attestation(message: impl Into<String>) -> Self {
432        Self::Attestation {
433            code: ErrorCode::E4006,
434            message: message.into(),
435        }
436    }
437
438    pub fn subscribe(message: impl Into<String>) -> Self {
439        Self::Subscribe {
440            code: ErrorCode::E4007,
441            message: message.into(),
442        }
443    }
444
445    pub fn publish(message: impl Into<String>) -> Self {
446        Self::Publish {
447            code: ErrorCode::E4008,
448            message: message.into(),
449        }
450    }
451
452    pub fn warden(message: impl Into<String>) -> Self {
453        Self::Warden {
454            code: ErrorCode::E4009,
455            message: message.into(),
456        }
457    }
458
459    pub fn code(&self) -> ErrorCode {
460        match self {
461            Self::Connection { code, .. }
462            | Self::Relay { code, .. }
463            | Self::Request { code, .. }
464            | Self::Response { code, .. }
465            | Self::Timeout { code, .. }
466            | Self::Attestation { code, .. }
467            | Self::Subscribe { code, .. }
468            | Self::Publish { code, .. }
469            | Self::Warden { code, .. } => *code,
470        }
471    }
472}
473
474/// Keep operation errors.
475#[derive(Error, Debug)]
476#[non_exhaustive]
477#[allow(missing_docs)]
478pub enum KeepError {
479    #[error("Invalid password")]
480    InvalidPassword,
481    #[error("Rate limited after repeated unlock failures; try again in {0}s. Exponential backoff is active (1s, 2s, 4s, ..., capped at 300s).")]
482    RateLimited(u64),
483    #[error("Decryption failed - wrong password or corrupted data")]
484    DecryptionFailed,
485    #[error("Key not found: {0}")]
486    KeyNotFound(String),
487    #[error("Key already exists: {0}")]
488    KeyAlreadyExists(String),
489    #[error("Invalid mnemonic: {0}")]
490    InvalidMnemonic(String),
491    #[error("Invalid nsec format")]
492    InvalidNsec,
493    #[error("Invalid npub: {0}")]
494    InvalidNpub(String),
495    #[error("Keyring full (max {0} keys)")]
496    KeyringFull(usize),
497    #[error("Keep is locked")]
498    Locked,
499    #[error("Keep already exists at {0}")]
500    AlreadyExists(String),
501    #[error("Keep not found at {0}")]
502    NotFound(String),
503    #[error("Invalid network: {0}")]
504    InvalidNetwork(String),
505    #[error("Rotation failed: {0}")]
506    RotationFailed(String),
507    /// Audit-log write failed for a security-critical event. Distinct from
508    /// best-effort audit failures (those are only warn-logged): operations
509    /// that return this variant performed their side effect (e.g. password /
510    /// data-key rotation) but the audit entry could not be persisted, so the
511    /// operation is observable only via this error.
512    #[error("Audit write failed: {0}")]
513    AuditWriteFailed(String),
514    #[error("Encryption error: {0}")]
515    Encryption(String),
516    #[error("Database error: {0}")]
517    Database(String),
518    /// The vault's redb file is already opened (exclusive lock) by another
519    /// process, typically a running `keep serve` daemon. Distinct from `Database`
520    /// so read-only CLI commands can detect it and route through the daemon's
521    /// inspect socket instead of failing (#533). The payload is a
522    /// ready-to-display hint.
523    #[error("{0}")]
524    VaultAlreadyOpen(String),
525    #[error("Migration error: {0}")]
526    Migration(String),
527    #[error("Home directory not found")]
528    HomeNotFound,
529    #[error("Permission denied: {0}")]
530    PermissionDenied(String),
531    #[error("User rejected operation")]
532    UserRejected,
533    #[error("Invalid input: {0}")]
534    InvalidInput(String),
535    #[error("Not implemented: {0}")]
536    NotImplemented(String),
537    #[error("Runtime error: {0}")]
538    Runtime(String),
539    #[error("Configuration error: {0}")]
540    Config(String),
541    #[error("FROST error: {0}")]
542    Frost(String),
543    #[error(transparent)]
544    StorageErr(#[from] StorageError),
545    #[error(transparent)]
546    CryptoErr(#[from] CryptoError),
547    #[error(transparent)]
548    FrostErr(#[from] FrostError),
549    #[error(transparent)]
550    NetworkErr(#[from] NetworkError),
551    #[error("Serialization error: {0}")]
552    Serialization(#[from] bincode::Error),
553    #[error("IO error: {0}")]
554    Io(#[from] std::io::Error),
555    #[error("Capacity exceeded: {0}")]
556    CapacityExceeded(String),
557    #[error("{0}")]
558    Other(String),
559}
560
561impl From<crate::entropy::EntropyHealthError> for KeepError {
562    fn from(e: crate::entropy::EntropyHealthError) -> Self {
563        KeepError::Encryption(e.to_string())
564    }
565}
566
567#[allow(missing_docs)]
568impl KeepError {
569    pub fn code(&self) -> Option<ErrorCode> {
570        match self {
571            Self::StorageErr(e) => Some(e.code()),
572            Self::CryptoErr(e) => Some(e.code()),
573            Self::FrostErr(e) => Some(e.code()),
574            Self::NetworkErr(e) => Some(e.code()),
575            _ => None,
576        }
577    }
578
579    pub fn permission_denied(msg: impl Into<String>) -> Self {
580        Self::PermissionDenied(msg.into())
581    }
582
583    pub fn invalid_input(msg: impl Into<String>) -> Self {
584        Self::InvalidInput(msg.into())
585    }
586
587    pub fn not_implemented(msg: impl Into<String>) -> Self {
588        Self::NotImplemented(msg.into())
589    }
590
591    pub fn runtime(msg: impl Into<String>) -> Self {
592        Self::Runtime(msg.into())
593    }
594
595    pub fn config(msg: impl Into<String>) -> Self {
596        Self::Config(msg.into())
597    }
598}
599
600impl From<redb::DatabaseError> for KeepError {
601    fn from(e: redb::DatabaseError) -> Self {
602        KeepError::Database(e.to_string())
603    }
604}
605
606impl From<redb::TransactionError> for KeepError {
607    fn from(e: redb::TransactionError) -> Self {
608        KeepError::Database(e.to_string())
609    }
610}
611
612impl From<redb::TableError> for KeepError {
613    fn from(e: redb::TableError) -> Self {
614        KeepError::Database(e.to_string())
615    }
616}
617
618impl From<redb::StorageError> for KeepError {
619    fn from(e: redb::StorageError) -> Self {
620        KeepError::Database(e.to_string())
621    }
622}
623
624impl From<redb::CommitError> for KeepError {
625    fn from(e: redb::CommitError) -> Self {
626        KeepError::Database(e.to_string())
627    }
628}
629
630/// Result type alias for Keep operations.
631pub type Result<T> = std::result::Result<T, KeepError>;