Skip to main content

secrets_rs/sources/
env.rs

1use crate::{error::SourceError, source::Source};
2
3/// A [`Source`] that retrieves secrets from environment variables.
4///
5/// The secret `name` is used directly as the environment variable name.
6/// Case sensitivity therefore matches the OS (case-sensitive on Unix,
7/// case-insensitive on Windows).
8pub struct EnvSource;
9
10impl Source for EnvSource {
11    fn get(&self, name: &str) -> Result<Vec<u8>, SourceError> {
12        std::env::var(name)
13            .map(|v| v.into_bytes())
14            .map_err(|_| SourceError::NotFound {
15                name: name.to_owned(),
16            })
17    }
18}
19
20#[cfg(test)]
21mod tests {
22    use super::*;
23
24    #[test]
25    fn returns_bytes_for_present_var() {
26        unsafe { std::env::set_var("SECRETS_RS_TEST_PRESENT", "hello") };
27        let result = EnvSource.get("SECRETS_RS_TEST_PRESENT").unwrap();
28        assert_eq!(result, b"hello");
29        unsafe { std::env::remove_var("SECRETS_RS_TEST_PRESENT") };
30    }
31
32    #[test]
33    fn returns_not_found_for_absent_var() {
34        unsafe { std::env::remove_var("SECRETS_RS_TEST_ABSENT") };
35        let err = EnvSource.get("SECRETS_RS_TEST_ABSENT").unwrap_err();
36        assert!(matches!(err, SourceError::NotFound { .. }));
37    }
38}