Update Doc & Fallback improvement

This commit is contained in:
2025-06-22 16:49:54 +02:00
parent 4369d9209d
commit ee6b992c8e
3 changed files with 96 additions and 85 deletions

2
Cargo.lock generated
View File

@@ -4,4 +4,4 @@ version = 4
[[package]] [[package]]
name = "merlin_env_helper" name = "merlin_env_helper"
version = "0.3.0" version = "0.4.0"

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "merlin_env_helper" name = "merlin_env_helper"
version = "0.3.0" version = "0.4.0"
edition = "2024" edition = "2024"
publish = ["merlin"] publish = ["merlin"]
description = "Utility functions to read environment with fallback and values from a file" description = "Utility functions to read environment with fallback and values from a file"

View File

@@ -30,13 +30,17 @@
//! } //! }
//! ``` //! ```
use core::fmt; use core::fmt;
use std::{error::Error, fmt::{Display, Formatter}, io::{self, Read}, path::Path}; use std::{
error::Error,
fmt::{Display, Formatter},
io::{self, Read},
path::Path,
};
use crate::config::types::EnvKey; use crate::config::types::EnvKey;
pub type Result<T, E = ConfigError> = std::result::Result<T, E>; pub type Result<T, E = ConfigError> = std::result::Result<T, E>;
#[derive(Debug)] #[derive(Debug)]
#[non_exhaustive] #[non_exhaustive]
pub struct ConfigError { pub struct ConfigError {
@@ -60,7 +64,6 @@ impl Error for ConfigError {
} }
} }
/// The kind of error that can occur when reading a configuration key. /// The kind of error that can occur when reading a configuration key.
#[derive(Debug)] #[derive(Debug)]
pub enum ConfigErrorKind { pub enum ConfigErrorKind {
@@ -82,17 +85,26 @@ impl Display for ConfigErrorMessage {
} }
} }
impl Error for ConfigErrorMessage { impl Error for ConfigErrorMessage {}
}
/// Retrieves the value of an environment variable or a secure file-based secret.
/// If not specified, a fallback value is returned if one is specified, otherwise an error is returned.
pub fn get_env_value(env_key: &EnvKey) -> Result<String> { pub fn get_env_value(env_key: &EnvKey) -> Result<String> {
if let Some(sec_key) = &env_key.sec_key { if let Some(sec_key) = &env_key.sec_key {
let key = std::env::var(&sec_key); let key = std::env::var(&sec_key);
if let Ok(path_file) = key { if let Ok(path_file) = key {
return read_secure_value(&env_key.key, &path_file); let result = read_secure_value(&env_key.key, &path_file);
if let Ok(value) = result {
return Ok(value);
}
if let Some(fallback) = &env_key.fallback {
return Ok(fallback.to_string());
}
return result;
} }
} }
@@ -102,7 +114,6 @@ pub fn get_env_value(env_key : &EnvKey) -> Result<String> {
fn read_key_value(key: &str, fallback: &Option<String>) -> Result<String> { fn read_key_value(key: &str, fallback: &Option<String>) -> Result<String> {
let env_value = std::env::var(key); let env_value = std::env::var(key);
println!("env_value: {:?}", env_value);
if let Ok(value) = env_value { if let Ok(value) = env_value {
return Ok(value); return Ok(value);
} }
@@ -111,21 +122,16 @@ fn read_key_value(key: &str, fallback: &Option<String>) -> Result<String> {
return Ok(fallback.to_string()); return Ok(fallback.to_string());
} }
Err( Err(ConfigError {
ConfigError {
key: key.to_string(), key: key.to_string(),
kind: ConfigErrorKind::NotFound, kind: ConfigErrorKind::NotFound,
})
} }
)
}
fn read_secure_value(key: &str, path_file: &str) -> Result<String> { fn read_secure_value(key: &str, path_file: &str) -> Result<String> {
let path = Path::new(path_file); let path = Path::new(path_file);
let exists = path.try_exists().map_err(|e| -> ConfigError { let exists = path.try_exists().map_err(|e| -> ConfigError {
println!("path.try_exists(): {:?}", e);
ConfigError { ConfigError {
key: format!("{}: {} File not found.", key.to_string(), path_file), key: format!("{}: {} File not found.", key.to_string(), path_file),
kind: ConfigErrorKind::IO(e), kind: ConfigErrorKind::IO(e),
@@ -133,18 +139,15 @@ fn read_secure_value(key: &str, path_file: &str) -> Result<String> {
})?; })?;
if !exists { if !exists {
return Err( return Err(ConfigError {
ConfigError {
key: format!("{}: {} File not found.", key.to_string(), path_file), key: format!("{}: {} File not found.", key.to_string(), path_file),
kind: ConfigErrorKind::FileNotFound(ConfigErrorMessage { kind: ConfigErrorKind::FileNotFound(ConfigErrorMessage {
msg: format!("File not found: {}", path_file), msg: format!("File not found: {}", path_file),
}), }),
} });
);
} }
let file = std::fs::File::open(path).map_err(|e| -> ConfigError { let file = std::fs::File::open(path).map_err(|e| -> ConfigError {
println!("std::fs::File::open(path_file): {:?}", e);
ConfigError { ConfigError {
key: key.to_string(), key: key.to_string(),
kind: ConfigErrorKind::IO(e), kind: ConfigErrorKind::IO(e),
@@ -154,7 +157,9 @@ fn read_secure_value(key: &str, path_file: &str) -> Result<String> {
let mut reader = std::io::BufReader::new(file); let mut reader = std::io::BufReader::new(file);
let mut content = String::new(); let mut content = String::new();
reader.read_to_string(&mut content).map_err(|e| -> ConfigError { reader
.read_to_string(&mut content)
.map_err(|e| -> ConfigError {
ConfigError { ConfigError {
key: key.to_string(), key: key.to_string(),
kind: ConfigErrorKind::IO(e), kind: ConfigErrorKind::IO(e),
@@ -164,7 +169,6 @@ fn read_secure_value(key: &str, path_file: &str) -> Result<String> {
Ok(content) Ok(content)
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -179,8 +183,9 @@ mod tests {
} }
fn run_test<T, U>(env_key: &str, test: T, clean_up: U) -> () fn run_test<T, U>(env_key: &str, test: T, clean_up: U) -> ()
where T: FnOnce() -> () + std::panic::UnwindSafe where
, U: FnOnce(&Option<String>) -> () T: FnOnce() -> () + std::panic::UnwindSafe,
U: FnOnce(&Option<String>) -> (),
{ {
let old_value = std::env::var(env_key); let old_value = std::env::var(env_key);
let mut reset_value = None; let mut reset_value = None;
@@ -200,8 +205,9 @@ mod tests {
#[test] #[test]
fn test_get_env_value() { fn test_get_env_value() {
run_test(
run_test("TEST_KEY", || { "TEST_KEY",
|| {
let key = "TEST_KEY"; let key = "TEST_KEY";
let value = "test_value"; let value = "test_value";
unsafe { std::env::set_var(key, value) }; unsafe { std::env::set_var(key, value) };
@@ -209,16 +215,16 @@ mod tests {
let result = get_env_value(&env_key); let result = get_env_value(&env_key);
assert_eq!(result.is_ok(), true); assert_eq!(result.is_ok(), true);
assert_eq!(result.unwrap(), value); assert_eq!(result.unwrap(), value);
}, },
clean_up clean_up,
); );
} }
#[test] #[test]
fn test_get_env_value_with_fallback() { fn test_get_env_value_with_fallback() {
run_test("TEST_KEY", || { run_test(
"TEST_KEY",
|| {
let key = "TEST_KEY"; let key = "TEST_KEY";
let fallback_value = "fallback_value"; let fallback_value = "fallback_value";
@@ -227,16 +233,20 @@ mod tests {
assert_eq!(result.is_ok(), true); assert_eq!(result.is_ok(), true);
assert_eq!(result.unwrap(), fallback_value); assert_eq!(result.unwrap(), fallback_value);
}, },
clean_up); clean_up,
);
} }
#[test] #[test]
fn test_get_env_value_with_secure_key() { fn test_get_env_value_with_secure_key() {
run_test("TEST_KEY", || { run_test(
"TEST_KEY",
|| {
let key = "TEST_KEY"; let key = "TEST_KEY";
let value = "test_value"; let value = "test_value";
let secure_key = "TEST_KEY_FILE"; let secure_key = "TEST_KEY_FILE";
let secure_value = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/test_secret.txt"); let secure_value = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("resources/test/test_secret.txt");
unsafe { std::env::set_var(key, value) }; unsafe { std::env::set_var(key, value) };
unsafe { std::env::set_var(secure_key, &secure_value) }; unsafe { std::env::set_var(secure_key, &secure_value) };
@@ -248,6 +258,7 @@ mod tests {
assert_eq!(result.is_ok(), true); assert_eq!(result.is_ok(), true);
assert_eq!(result.unwrap(), "my_secret"); assert_eq!(result.unwrap(), "my_secret");
}, },
clean_up); clean_up,
);
} }
} }