rust_config_secrets/
error.rs

1use std::fmt;
2
3/// Errors that can occur during configuration secret management.
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub enum ConfigSecretsError {
6    /// Failed to encrypt the data.
7    EncryptionFailed,
8    /// Failed to decrypt the data (e.g., wrong key or tampered ciphertext).
9    DecryptionFailed,
10    /// The ciphertext is too short to contain a valid nonce.
11    CiphertextTooShort,
12    /// The provided string is not valid alphanumeric encoding.
13    InvalidEncoding(String),
14    /// The provided key has an invalid length (expected 32 bytes).
15    InvalidKeyLength(usize),
16    /// The decrypted data is not valid UTF-8.
17    InvalidUtf8(String),
18    /// A marker block (e.g., `ENCRYPT(` or `SECRET(`) was not properly closed.
19    UnclosedBlock(String),
20    /// An I/O error occurred while reading or writing a file.
21    IoError(String),
22}
23
24impl fmt::Display for ConfigSecretsError {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        match self {
27            Self::EncryptionFailed => write!(f, "Encryption failed"),
28            Self::DecryptionFailed => write!(f, "Decryption failed"),
29            Self::CiphertextTooShort => write!(f, "Ciphertext too short"),
30            Self::InvalidEncoding(e) => write!(f, "Invalid encoding: {}", e),
31            Self::InvalidKeyLength(l) => write!(f, "Invalid key length: {} (expected 32)", l),
32            Self::InvalidUtf8(e) => write!(f, "Invalid UTF-8: {}", e),
33            Self::UnclosedBlock(m) => write!(f, "Unclosed block: {}", m),
34            Self::IoError(e) => write!(f, "IO error: {}", e),
35        }
36    }
37}
38
39impl std::error::Error for ConfigSecretsError {}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn test_display_impl() {
47        assert_eq!(
48            ConfigSecretsError::EncryptionFailed.to_string(),
49            "Encryption failed"
50        );
51        assert_eq!(
52            ConfigSecretsError::DecryptionFailed.to_string(),
53            "Decryption failed"
54        );
55        assert_eq!(
56            ConfigSecretsError::CiphertextTooShort.to_string(),
57            "Ciphertext too short"
58        );
59        assert_eq!(
60            ConfigSecretsError::InvalidEncoding("bad".into()).to_string(),
61            "Invalid encoding: bad"
62        );
63        assert_eq!(
64            ConfigSecretsError::InvalidKeyLength(10).to_string(),
65            "Invalid key length: 10 (expected 32)"
66        );
67        assert_eq!(
68            ConfigSecretsError::InvalidUtf8("bad utf8".into()).to_string(),
69            "Invalid UTF-8: bad utf8"
70        );
71        assert_eq!(
72            ConfigSecretsError::UnclosedBlock("tag".into()).to_string(),
73            "Unclosed block: tag"
74        );
75        assert_eq!(
76            ConfigSecretsError::IoError("oops".into()).to_string(),
77            "IO error: oops"
78        );
79    }
80}