Skip to main content

incokit_e2ee/
error.rs

1//! Precise error type for the crypto layer.
2//!
3//! Library code uses `CryptoResult<T>` (= `Result<T, CryptoError>`). A blanket
4//! `From<CryptoError> for String` impl is provided so callers that need a flat
5//! string (e.g. an IPC/FFI boundary that serializes errors as text) can convert
6//! with `?` without losing the original `Display` message.
7//!
8//! Why not just `String` everywhere? Because "Encryption failed" collapses
9//! wrong-key, truncated-ciphertext, and malformed-base64 into one message,
10//! which makes debugging and telemetry harder. The enum preserves shape
11//! without changing the user-facing surface.
12
13use thiserror::Error;
14
15#[derive(Debug, Error)]
16pub enum CryptoError {
17    #[error("encryption is locked — unlock before retrying")]
18    NotUnlocked,
19
20    #[error("session belongs to a different user")]
21    UserIdMismatch,
22
23    #[error("invalid key length: expected {expected}, got {actual}")]
24    InvalidKeyLength { expected: usize, actual: usize },
25
26    #[error("AES-GCM encrypt failed")]
27    Encrypt,
28
29    #[error("AES-GCM decrypt failed (wrong key or corrupted data)")]
30    Decrypt,
31
32    #[error("ciphertext too short: need at least {min} bytes, got {actual}")]
33    CiphertextTooShort { min: usize, actual: usize },
34
35    #[error("Argon2 parameters error: {0}")]
36    Argon2Params(String),
37
38    #[error("Argon2 hash failed: {0}")]
39    Argon2Hash(String),
40
41    #[error("HKDF expand failed: {0}")]
42    Hkdf(String),
43
44    #[error("base64 decode: {0}")]
45    Base64(#[from] base64::DecodeError),
46
47    #[error("json: {0}")]
48    Json(#[from] serde_json::Error),
49
50    #[error("utf-8: {0}")]
51    Utf8(#[from] std::string::FromUtf8Error),
52
53    /// Returned by strict decrypt paths when input does not start with the
54    /// wire-format prefix `"e2ee:"`. Callers that want to tolerate legacy
55    /// plaintext rows should use `try_unseal_*` variants instead.
56    #[error("missing e2ee prefix — data is not encrypted")]
57    MissingE2eePrefix,
58}
59
60impl From<CryptoError> for String {
61    fn from(e: CryptoError) -> Self {
62        e.to_string()
63    }
64}
65
66pub type CryptoResult<T> = Result<T, CryptoError>;