tpfs_krypt 7.1.8

An interface for accessing secrets
Documentation
#[cfg(feature = "hashicorp-vault")]
use crate::hashicorp_vault_key_manager::HashicorpVaultKeyManager;
use crate::{
    config::{ConfigValidation, KeyManagerConfig, KryptConfig},
    errors::{KeyManagementError, Result},
    file_key_manager::FileKeyManager,
    in_memory_key_manager::InMemoryKeyManager,
    KeyManagement,
};
use cfg::{Config, Environment, File};
use std::path::PathBuf;

#[cfg(test)]
mod unit_tests;

/// Creates a KeyManager based on a file named krypt.toml from the path passed in.
///
/// # Examples
///
/// ```
/// use tpfs_krypt::from_config_path;
///
/// let result = from_config_path("/tmp/non/existent/path");
/// assert!(result.is_err());
/// ```
pub fn from_config_path(config_path: &str) -> Result<Box<dyn KeyManagement>> {
    let path = PathBuf::from(config_path);

    if !path.exists() || !path.is_dir() {
        return Err(KeyManagementError::ConfigFolderNotFound {
            path: config_path.to_string(),
        });
    }
    let path = path.join("krypt.toml");

    let file = File::from(path);
    let mut config = Config::default();

    config.merge(file)?;
    config.merge(Environment::with_prefix("krypt").separator("-"))?;

    let cfg: KryptConfig = serde_path_to_error::deserialize(config).map_err(|err| {
        KeyManagementError::ConfigDeserializationError {
            message: err.into_inner().to_string(),
        }
    })?;

    from_config(cfg)
}

/// Creates a KeyManager based on the `KryptConfig` struct that is passed in.
///
/// # Examples
///
/// ```
/// use tpfs_krypt::{
///     config::{KryptConfig, KeyManagerConfig},
///     from_config, InMemoryKeyManagerConfig,
/// };
///
/// let config = KryptConfig {
///     key_manager_config: KeyManagerConfig::InMemoryKeyManager(InMemoryKeyManagerConfig {
///         initial_keys: vec![],
///     }),
/// };
/// let result = from_config(config);
/// assert!(result.is_ok());
/// ```
pub fn from_config(config: KryptConfig) -> Result<Box<dyn KeyManagement>> {
    config.validate()?;

    match config.key_manager_config {
        KeyManagerConfig::FileKeyManager(file_key_config) => {
            Ok(Box::new(FileKeyManager::new(file_key_config)))
        }
        KeyManagerConfig::InMemoryKeyManager(in_memory_key_config) => {
            Ok(Box::new(InMemoryKeyManager::new(in_memory_key_config)))
        }
        #[cfg(feature = "hashicorp-vault")]
        KeyManagerConfig::HashicorpVaultKeyManager(vault_key_config) => {
            Ok(Box::new(HashicorpVaultKeyManager::new(vault_key_config)))
        }
    }
}