use std::path::PathBuf;
use crate::encryption::factory::Algorithm;
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "config-toml", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "config-toml",
serde(tag = "type", rename_all = "snake_case")
)]
pub enum KeyProviderConfig {
File {
path: PathBuf,
},
Env {
variable: String,
},
}
impl Default for KeyProviderConfig {
fn default() -> Self {
Self::Env {
variable: "ALETHEIADB_MEK".to_string(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[cfg_attr(feature = "config-toml", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "config-toml", serde(default))]
pub struct EncryptionConfig {
pub enabled: bool,
pub algorithm: Algorithm,
pub key_provider: KeyProviderConfig,
}
impl EncryptionConfig {
#[must_use]
pub fn disabled() -> Self {
Self::default()
}
#[must_use]
pub fn file_based(path: impl Into<PathBuf>) -> Self {
Self {
enabled: true,
algorithm: Algorithm::default(),
key_provider: KeyProviderConfig::File { path: path.into() },
}
}
#[must_use]
pub fn env_based(var_name: impl Into<String>) -> Self {
Self {
enabled: true,
algorithm: Algorithm::default(),
key_provider: KeyProviderConfig::Env {
variable: var_name.into(),
},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_is_disabled() {
let config = EncryptionConfig::default();
assert!(!config.enabled);
assert_eq!(config.algorithm, Algorithm::Auto);
assert_eq!(
config.key_provider,
KeyProviderConfig::Env {
variable: "ALETHEIADB_MEK".to_string()
}
);
}
#[test]
fn disabled_matches_default() {
assert_eq!(EncryptionConfig::disabled(), EncryptionConfig::default());
}
#[test]
fn file_based_is_enabled() {
let config = EncryptionConfig::file_based("/tmp/my.key");
assert!(config.enabled);
assert_eq!(config.algorithm, Algorithm::Auto);
assert_eq!(
config.key_provider,
KeyProviderConfig::File {
path: PathBuf::from("/tmp/my.key")
}
);
}
#[test]
fn env_based_is_enabled() {
let config = EncryptionConfig::env_based("MY_CUSTOM_KEY");
assert!(config.enabled);
assert_eq!(config.algorithm, Algorithm::Auto);
assert_eq!(
config.key_provider,
KeyProviderConfig::Env {
variable: "MY_CUSTOM_KEY".to_string()
}
);
}
}