crypt_io/error.rs
1//! Error types for `crypt-io`.
2//!
3//! All fallible operations in the crate return [`Result<T>`], an alias for
4//! `core::result::Result<T, Error>`. [`Error`] is `#[non_exhaustive]` — match
5//! sites must include a wildcard arm so future minor releases can add
6//! variants without breaking downstream code.
7//!
8//! Error messages are redaction-clean: no key bytes, no plaintext, no nonce
9//! values, no ciphertext are ever included in a rendered error. Errors are
10//! safe to log, safe to ship to monitoring, safe to include in audit records.
11
12use alloc::string::String;
13use core::fmt;
14
15/// The error type for all `crypt-io` operations.
16///
17/// Authentication failures are deliberately collapsed into a single variant —
18/// distinguishing "wrong key" from "tampered ciphertext" would leak which
19/// failure mode an attacker is closer to, which is a side-channel.
20#[non_exhaustive]
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum Error {
23 /// The supplied key was not the correct size for the selected algorithm
24 /// (ChaCha20-Poly1305 and AES-256-GCM both require exactly 32 bytes).
25 InvalidKey {
26 /// The expected key length in bytes.
27 expected: usize,
28 /// The length actually supplied.
29 actual: usize,
30 },
31
32 /// The ciphertext was malformed (too short to contain a nonce + tag, or
33 /// the embedded length fields were inconsistent).
34 InvalidCiphertext(String),
35
36 /// Authentication of the ciphertext failed. This is the single
37 /// observable outcome of *any* corruption: wrong key, tampered bytes,
38 /// truncated message, or wrong associated data. The variant is opaque
39 /// by design.
40 AuthenticationFailed,
41
42 /// The requested algorithm is not enabled at compile time. Re-build
43 /// with the appropriate Cargo feature.
44 AlgorithmNotEnabled(&'static str),
45
46 /// The OS random source failed to produce a nonce. This is rare and
47 /// almost always indicates a misconfigured sandbox or exhausted
48 /// `getrandom` entropy on a freshly-booted VM.
49 RandomFailure(&'static str),
50}
51
52/// Type alias for `core::result::Result<T, Error>`.
53pub type Result<T> = core::result::Result<T, Error>;
54
55impl fmt::Display for Error {
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 match self {
58 Self::InvalidKey { expected, actual } => {
59 write!(
60 f,
61 "invalid key length: expected {expected} bytes, got {actual}"
62 )
63 }
64 Self::InvalidCiphertext(why) => write!(f, "invalid ciphertext: {why}"),
65 Self::AuthenticationFailed => f.write_str("authentication failed"),
66 Self::AlgorithmNotEnabled(name) => {
67 write!(f, "algorithm not enabled at compile time: {name}")
68 }
69 Self::RandomFailure(why) => write!(f, "OS random source failed: {why}"),
70 }
71 }
72}
73
74#[cfg(feature = "std")]
75impl std::error::Error for Error {}
76
77#[cfg(test)]
78#[allow(clippy::unwrap_used, clippy::expect_used)]
79mod tests {
80 use super::*;
81 use alloc::format;
82 use alloc::string::ToString;
83
84 #[test]
85 fn invalid_key_message_includes_lengths() {
86 let e = Error::InvalidKey {
87 expected: 32,
88 actual: 16,
89 };
90 let rendered = format!("{e}");
91 assert!(rendered.contains("32"));
92 assert!(rendered.contains("16"));
93 }
94
95 #[test]
96 fn authentication_failure_is_opaque() {
97 let rendered = Error::AuthenticationFailed.to_string();
98 assert_eq!(rendered, "authentication failed");
99 }
100
101 #[test]
102 fn debug_does_not_panic_for_any_variant() {
103 for e in [
104 Error::InvalidKey {
105 expected: 32,
106 actual: 0,
107 },
108 Error::InvalidCiphertext("x".to_string()),
109 Error::AuthenticationFailed,
110 Error::AlgorithmNotEnabled("none"),
111 Error::RandomFailure("ENOSYS"),
112 ] {
113 let _ = format!("{e:?}");
114 }
115 }
116}