pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("password cannot be empty")]
EmptyPassword,
#[error("value cannot be empty")]
EmptyValue,
#[error("invalid encrypted format, expected ENC(...)")]
InvalidEncFormat,
#[error("invalid jasypt encrypted data")]
InvalidJasyptData,
#[error("decryption failed")]
DecryptionFailed,
#[error("base64 decode error: {0}")]
Base64(#[from] base64::DecodeError),
#[error("io error: {0}")]
Io(#[from] std::io::Error),
#[cfg(feature = "config")]
#[error("json error: {0}")]
Json(#[from] serde_json::Error),
#[error("failed to decrypt key {key}: {source}")]
KeyDecrypt {
key: String,
#[source]
source: Box<Error>,
},
#[error("invalid parameter: {0}")]
InvalidParameter(String),
}
impl Error {
pub(crate) fn key_decrypt(key: impl Into<String>, source: Error) -> Self {
Error::KeyDecrypt {
key: key.into(),
source: Box::new(source),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn display_messages_match_gocrypt() {
assert_eq!(Error::EmptyPassword.to_string(), "password cannot be empty");
assert_eq!(Error::EmptyValue.to_string(), "value cannot be empty");
assert_eq!(
Error::InvalidEncFormat.to_string(),
"invalid encrypted format, expected ENC(...)"
);
assert_eq!(
Error::InvalidJasyptData.to_string(),
"invalid jasypt encrypted data"
);
assert_eq!(Error::DecryptionFailed.to_string(), "decryption failed");
assert_eq!(
Error::InvalidParameter("key size must be 16, 24 or 32".into()).to_string(),
"invalid parameter: key size must be 16, 24 or 32"
);
}
#[test]
fn key_decrypt_wraps_source() {
let err = Error::key_decrypt("DB_PASS", Error::DecryptionFailed);
assert_eq!(
err.to_string(),
"failed to decrypt key DB_PASS: decryption failed"
);
let source = std::error::Error::source(&err).expect("source");
assert_eq!(source.to_string(), "decryption failed");
}
#[test]
fn base64_error_converts() {
use base64::Engine;
let err: Error = base64::engine::general_purpose::STANDARD
.decode("not base64!")
.unwrap_err()
.into();
assert!(matches!(err, Error::Base64(_)));
assert!(err.to_string().starts_with("base64 decode error: "));
}
}