Skip to main content

adotenv_process/
lib.rs

1//! Explicit process-environment application for loaded `.env` values.
2//!
3//! This crate deliberately lives outside `adotenv`: the core forbids unsafe code
4//! and never mutates the process environment. Callers must use [`apply`]
5//! deliberately, after loading has completed and validation has succeeded.
6
7use std::{env, fmt};
8
9use adotenv::load::LoadedEnvironment;
10
11/// Validation or application failure.
12#[derive(Debug, Clone, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum ApplyError {
15    /// A key was empty.
16    EmptyKey,
17    /// A key contained a NUL or `=`.
18    InvalidKey {
19        /// Offending key.
20        key: String,
21    },
22    /// A value contained a NUL.
23    InvalidValue {
24        /// Key whose value is invalid.
25        key: String,
26    },
27}
28
29impl fmt::Display for ApplyError {
30    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
31        match self {
32            Self::EmptyKey => formatter.write_str("environment key is empty"),
33            Self::InvalidKey { key } => {
34                write!(formatter, "environment key contains NUL or '=': {key:?}")
35            }
36            Self::InvalidValue { key } => {
37                write!(formatter, "environment value for {key:?} contains NUL")
38            }
39        }
40    }
41}
42
43impl std::error::Error for ApplyError {}
44
45/// Validate every loaded key and value without mutating the environment.
46///
47/// # Errors
48/// Returns [`ApplyError`] when a key is empty or contains NUL/`=`, or a value
49/// contains NUL.
50pub fn validate(environment: &LoadedEnvironment) -> Result<(), ApplyError> {
51    for (key, value) in environment.values() {
52        if key.is_empty() {
53            return Err(ApplyError::EmptyKey);
54        }
55        if key.bytes().any(|byte| byte == 0 || byte == b'=') {
56            return Err(ApplyError::InvalidKey { key: key.clone() });
57        }
58        if value.as_bytes().contains(&0) {
59            return Err(ApplyError::InvalidValue { key: key.clone() });
60        }
61    }
62    Ok(())
63}
64
65/// Apply every loaded value to the current process environment.
66///
67/// This sets only the keys present in the loaded environment. It does not clear
68/// or remove any existing process variables. Every key and value is validated
69/// before the first mutation.
70///
71/// # Safety
72/// The process environment is global and not thread-safe on all platforms. The
73/// caller must ensure that no other thread is concurrently reading or writing
74/// the process environment and must accept that process-environment changes
75/// cannot be rolled back. Prefer consuming [`LoadedEnvironment::values`] as a
76/// map unless process-global mutation is actually required.
77///
78/// # Errors
79/// Returns [`ApplyError`] before changing anything when validation fails.
80pub unsafe fn apply(environment: &LoadedEnvironment) -> Result<(), ApplyError> {
81    validate(environment)?;
82    for (key, value) in environment.values() {
83        unsafe { env::set_var(key, value) };
84    }
85    Ok(())
86}
87
88#[cfg(test)]
89mod tests {
90    use std::{
91        fs,
92        path::PathBuf,
93        sync::atomic::{AtomicU64, Ordering},
94    };
95
96    use super::*;
97    use adotenv::load::load_cascade;
98
99    static NEXT: AtomicU64 = AtomicU64::new(0);
100
101    struct TempDir(PathBuf);
102
103    impl TempDir {
104        fn new() -> Self {
105            let path = std::env::temp_dir().join(format!(
106                "adotenv-process-{}-{}",
107                std::process::id(),
108                NEXT.fetch_add(1, Ordering::Relaxed)
109            ));
110            fs::create_dir_all(&path).unwrap();
111            Self(path)
112        }
113        fn path(&self) -> &std::path::Path {
114            &self.0
115        }
116    }
117
118    impl Drop for TempDir {
119        fn drop(&mut self) {
120            let _ = fs::remove_dir_all(&self.0);
121        }
122    }
123
124    fn environment(key: &str, value: &str) -> (TempDir, LoadedEnvironment) {
125        let dir = TempDir::new();
126        fs::write(dir.path().join(".env"), format!("{key}={value}\n")).unwrap();
127        let loaded = load_cascade(dir.path(), "").unwrap();
128        (dir, loaded)
129    }
130
131    #[test]
132    fn apply_sets_loaded_values_and_can_be_removed() {
133        let key = format!(
134            "ADOTENV_PROCESS_{}_{}",
135            std::process::id(),
136            NEXT.fetch_add(1, Ordering::Relaxed)
137        );
138        let (_dir, loaded) = environment(&key, "value");
139        unsafe { apply(&loaded).unwrap() };
140        assert_eq!(std::env::var(&key).as_deref(), Ok("value"));
141        std::env::remove_var(&key);
142    }
143
144    #[test]
145    fn validation_rejects_nul_values_before_mutation() {
146        let key = format!(
147            "ADOTENV_PROCESS_BAD_{}_{}",
148            std::process::id(),
149            NEXT.fetch_add(1, Ordering::Relaxed)
150        );
151        let (_dir, loaded) = environment(&key, "bad\0value");
152        assert!(matches!(
153            validate(&loaded),
154            Err(ApplyError::InvalidValue { .. })
155        ));
156        assert!(matches!(
157            unsafe { apply(&loaded) },
158            Err(ApplyError::InvalidValue { .. })
159        ));
160        assert!(std::env::var_os(&key).is_none());
161    }
162
163    #[test]
164    fn error_messages_include_the_key() {
165        let error = ApplyError::InvalidKey { key: "A=B".into() };
166        assert!(error.to_string().contains("A=B"));
167    }
168}