Skip to main content

adotenv_process/
lib.rs

1//! Sets values loaded by [`adotenv`] in the current process environment.
2//!
3//! [`adotenv::load`] reads `.env` files into a [`LoadedEnvironment`] but never
4//! changes the process environment. This crate adds that step: [`apply`]. It is
5//! a separate crate because changing the environment is unsafe. The
6//! environment is shared by every thread of the process, and on some platforms
7//! reading it while another thread writes it is undefined behavior. The core
8//! `adotenv` crate forbids unsafe code.
9//!
10//! ```toml
11//! [dependencies]
12//! adotenv = { version = "1", features = ["load"] }
13//! adotenv-process = "1"
14//! ```
15//!
16//! The crate has no features of its own and needs Rust 1.81 or later.
17//!
18//! # Prefer passing values explicitly
19//!
20//! Most programs do not need to change their own environment. Read values
21//! with [`LoadedEnvironment::get`], deserialize them with the `serde` feature
22//! of `adotenv`, or pass them to a child process:
23//!
24//! ```no_run
25//! use std::process::Command;
26//!
27//! use adotenv::load::load_cascade;
28//!
29//! let loaded = load_cascade("/srv/my-app", "production")?;
30//! let status = Command::new("my-server").envs(loaded.values()).status()?;
31//! # let _ = status;
32//! # Ok::<(), Box<dyn std::error::Error>>(())
33//! ```
34//!
35//! Use [`apply`] only when code you do not control reads the process
36//! environment, such as a library that calls [`std::env::var`].
37//!
38//! # Applying a loaded environment
39//!
40//! [`apply`] checks every key and value, then sets each loaded key. A loaded
41//! key replaces a variable of the same name. Other variables are kept and
42//! nothing is removed. Values are set as loaded: `${HOME}` is not expanded.
43//! The changes cannot be rolled back.
44//!
45//! The caller must guarantee that no other thread reads or writes the process
46//! environment while [`apply`] runs. In practice, call it at the start of
47//! `main`, before starting threads or an async runtime.
48//!
49//! ```
50//! use adotenv::load::load_cascade;
51//!
52//! # let dir = std::env::temp_dir().join(format!("adotenv-process-doc-crate-{}", std::process::id()));
53//! # std::fs::create_dir_all(&dir)?;
54//! # std::fs::write(dir.join(".env"), "APP_PORT=3000\n")?;
55//! # std::fs::write(dir.join(".env.production"), "APP_PORT=8080\n")?;
56//! let loaded = load_cascade(&dir, "production")?;
57//!
58//! // SAFETY: called at startup, before any other thread exists.
59//! unsafe { adotenv_process::apply(&loaded)? };
60//! assert_eq!(std::env::var("APP_PORT")?, "8080");
61//! # std::fs::remove_dir_all(&dir)?;
62//! # Ok::<(), Box<dyn std::error::Error>>(())
63//! ```
64//!
65//! [`validate`] runs the same checks without changing anything, and is safe
66//! to call from any thread. Both return an [`ApplyError`] for the first key or
67//! value that the process environment cannot hold.
68//!
69//! `apply` takes a [`LoadedEnvironment`]. To set resolved values, resolve them
70//! with [`LoadedEnvironment::resolve_contextual`] and set them yourself.
71
72use std::{env, fmt};
73
74use adotenv::load::LoadedEnvironment;
75
76#[cfg(windows)]
77const WINDOWS_VALUE_LIMIT: usize = 32_767;
78
79/// A key or value that the process environment cannot hold.
80///
81/// Returned by [`validate`], and by [`apply`] before it changes anything. It
82/// reports the first problem, in key order. These are the inputs for which
83/// [`std::env::set_var`] may panic. The error names the key but never includes
84/// the value.
85///
86/// # Examples
87///
88/// Python dotenv lets a quoted key contain `=`. With `'APP=PORT'=8080` in
89/// `.env`:
90///
91/// ```
92/// use adotenv::load::load_cascade_with;
93/// use adotenv::Dialect;
94/// use adotenv_process::{validate, ApplyError};
95///
96/// # let dir = std::env::temp_dir().join(format!("adotenv-process-doc-ApplyError-{}", std::process::id()));
97/// # std::fs::create_dir_all(&dir)?;
98/// # std::fs::write(dir.join(".env"), "'APP=PORT'=8080\n")?;
99/// let loaded = load_cascade_with(&dir, "", Dialect::PYTHON_DOTENV)?;
100/// match validate(&loaded) {
101///     Err(ApplyError::InvalidKey { key }) => assert_eq!(key, "APP=PORT"),
102///     other => panic!("expected an invalid key, got {other:?}"),
103/// }
104/// # std::fs::remove_dir_all(&dir)?;
105/// # Ok::<(), Box<dyn std::error::Error>>(())
106/// ```
107#[derive(Debug, Clone, PartialEq, Eq)]
108#[non_exhaustive]
109pub enum ApplyError {
110    /// A key is empty.
111    ///
112    /// The `adotenv` loaders skip empty keys, so a loaded environment does not
113    /// produce this error; the check is a safeguard.
114    EmptyKey,
115    /// A key contains NUL or `=`.
116    InvalidKey {
117        /// The key, as loaded.
118        key: String,
119    },
120    /// A value contains NUL.
121    InvalidValue {
122        /// The key whose value contains NUL.
123        key: String,
124    },
125    /// Two keys collide on a case-insensitive platform.
126    ///
127    /// Windows environment variable names are case-insensitive. This variant
128    /// is returned only on Windows.
129    DuplicateKey {
130        /// The later key in sorted order.
131        key: String,
132    },
133    /// A value is too long for the platform.
134    ///
135    /// Windows accepts at most 32,767 UTF-16 code units per value. This variant
136    /// is returned only on Windows.
137    ValueTooLong {
138        /// The key whose value is too long.
139        key: String,
140        /// The platform limit.
141        limit: usize,
142    },
143}
144
145impl fmt::Display for ApplyError {
146    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
147        match self {
148            Self::EmptyKey => formatter.write_str("environment key is empty"),
149            Self::InvalidKey { key } => {
150                write!(formatter, "environment key contains NUL or '=': {key:?}")
151            }
152            Self::InvalidValue { key } => {
153                write!(formatter, "environment value for {key:?} contains NUL")
154            }
155            Self::DuplicateKey { key } => {
156                write!(
157                    formatter,
158                    "environment key collides case-insensitively: {key:?}"
159                )
160            }
161            Self::ValueTooLong { key, limit } => {
162                write!(
163                    formatter,
164                    "environment value for {key:?} exceeds {limit} UTF-16 code units"
165                )
166            }
167        }
168    }
169}
170
171impl std::error::Error for ApplyError {}
172
173/// Checks that the process environment can hold every loaded key and value.
174///
175/// Runs the checks of [`apply`] without changing anything, so it is safe to
176/// call from any thread, for example to report a bad `.env` file early. A key
177/// must not be empty and must not contain NUL or `=`. A value must not contain
178/// NUL. Keys are checked in sorted order.
179///
180/// # Errors
181///
182/// Returns the first problem found:
183///
184/// - [`ApplyError::EmptyKey`] if a key is empty.
185/// - [`ApplyError::InvalidKey`] if a key contains NUL or `=`.
186/// - [`ApplyError::InvalidValue`] if a value contains NUL.
187/// - On Windows, [`ApplyError::DuplicateKey`] if two keys differ only by case,
188///   and [`ApplyError::ValueTooLong`] if a value exceeds 32,767 UTF-16 code
189///   units.
190///
191/// # Examples
192///
193/// With `PORT=8080` and a `TOKEN` value that contains a NUL byte in `.env`:
194///
195/// ```
196/// use adotenv::load::load_cascade;
197/// use adotenv_process::{validate, ApplyError};
198///
199/// # let dir = std::env::temp_dir().join(format!("adotenv-process-doc-validate-{}", std::process::id()));
200/// # std::fs::create_dir_all(&dir)?;
201/// # std::fs::write(dir.join(".env"), "PORT=8080\nTOKEN=abc\0def\n")?;
202/// let loaded = load_cascade(&dir, "")?;
203/// let error = validate(&loaded).unwrap_err();
204/// assert_eq!(error, ApplyError::InvalidValue { key: "TOKEN".to_string() });
205/// assert_eq!(error.to_string(), r#"environment value for "TOKEN" contains NUL"#);
206/// # std::fs::remove_dir_all(&dir)?;
207/// # Ok::<(), Box<dyn std::error::Error>>(())
208/// ```
209pub fn validate(environment: &LoadedEnvironment) -> Result<(), ApplyError> {
210    #[cfg(windows)]
211    let mut seen = std::collections::BTreeSet::new();
212    for (key, value) in environment.values() {
213        if key.is_empty() {
214            return Err(ApplyError::EmptyKey);
215        }
216        if key.bytes().any(|byte| byte == 0 || byte == b'=') {
217            return Err(ApplyError::InvalidKey {
218                key: key.to_string(),
219            });
220        }
221        if value.as_bytes().contains(&0) {
222            return Err(ApplyError::InvalidValue {
223                key: key.to_string(),
224            });
225        }
226        #[cfg(windows)]
227        {
228            if !seen.insert(key.to_lowercase()) {
229                return Err(ApplyError::DuplicateKey {
230                    key: key.to_string(),
231                });
232            }
233            if value.encode_utf16().count() > WINDOWS_VALUE_LIMIT {
234                return Err(ApplyError::ValueTooLong {
235                    key: key.to_string(),
236                    limit: WINDOWS_VALUE_LIMIT,
237                });
238            }
239        }
240    }
241    Ok(())
242}
243
244/// Sets every loaded key to its loaded value in the current process
245/// environment.
246///
247/// First runs [`validate`], so an environment it rejects changes nothing. Then
248/// sets each key with [`std::env::set_var`], in sorted order. A loaded key
249/// replaces a variable of the same name. Other variables are kept and nothing
250/// is removed. Values are set as loaded, without expanding references such as
251/// `${HOME}`. The changes cannot be rolled back.
252///
253/// Prefer passing [`LoadedEnvironment::values`] to a child process, or reading
254/// the values directly, unless code you do not control reads the process
255/// environment. See the [crate documentation](crate).
256///
257/// # Errors
258///
259/// Returns the [`ApplyError`] from [`validate`], before changing anything.
260///
261/// # Safety
262///
263/// No other thread may read or write the process environment while `apply`
264/// runs. That includes [`std::env::var`] and C functions such as `getenv` and
265/// `setenv` called by libraries. On some platforms such concurrent access is
266/// undefined behavior. In practice, call `apply` at the start of `main`, before
267/// starting threads or an async runtime.
268///
269/// # Examples
270///
271/// With `APP_PORT=8080` and `APP_HOST=0.0.0.0` in `.env`:
272///
273/// ```
274/// use adotenv::load::load_cascade;
275/// use adotenv_process::apply;
276///
277/// # let dir = std::env::temp_dir().join(format!("adotenv-process-doc-apply-{}", std::process::id()));
278/// # std::fs::create_dir_all(&dir)?;
279/// # std::fs::write(dir.join(".env"), "APP_PORT=8080\nAPP_HOST=0.0.0.0\n")?;
280/// let loaded = load_cascade(&dir, "")?;
281///
282/// // SAFETY: called at startup, before any other thread exists.
283/// unsafe { apply(&loaded)? };
284/// assert_eq!(std::env::var("APP_PORT")?, "8080");
285/// assert_eq!(std::env::var("APP_HOST")?, "0.0.0.0");
286/// # std::fs::remove_dir_all(&dir)?;
287/// # Ok::<(), Box<dyn std::error::Error>>(())
288/// ```
289pub unsafe fn apply(environment: &LoadedEnvironment) -> Result<(), ApplyError> {
290    validate(environment)?;
291    for (key, value) in environment.values() {
292        unsafe { env::set_var(key, value) };
293    }
294    Ok(())
295}
296
297#[cfg(test)]
298mod tests {
299    use std::{
300        fs,
301        path::PathBuf,
302        sync::{
303            atomic::{AtomicU64, Ordering},
304            Mutex,
305        },
306    };
307
308    use super::*;
309    use adotenv::load::load_cascade;
310
311    static NEXT: AtomicU64 = AtomicU64::new(0);
312    /// The process environment is global; serialize tests that touch it.
313    static ENV_LOCK: Mutex<()> = Mutex::new(());
314
315    struct TempDir(PathBuf);
316
317    impl TempDir {
318        fn new() -> Self {
319            let path = std::env::temp_dir().join(format!(
320                "adotenv-process-{}-{}",
321                std::process::id(),
322                NEXT.fetch_add(1, Ordering::Relaxed)
323            ));
324            fs::create_dir_all(&path).unwrap();
325            Self(path)
326        }
327        fn path(&self) -> &std::path::Path {
328            &self.0
329        }
330    }
331
332    impl Drop for TempDir {
333        fn drop(&mut self) {
334            let _ = fs::remove_dir_all(&self.0);
335        }
336    }
337
338    fn environment(key: &str, value: &str) -> (TempDir, LoadedEnvironment) {
339        let dir = TempDir::new();
340        fs::write(dir.path().join(".env"), format!("{key}={value}\n")).unwrap();
341        let loaded = load_cascade(dir.path(), "").unwrap();
342        (dir, loaded)
343    }
344
345    #[test]
346    fn apply_sets_loaded_values_and_can_be_removed() {
347        let _guard = ENV_LOCK.lock().unwrap();
348        let key = format!(
349            "ADOTENV_PROCESS_{}_{}",
350            std::process::id(),
351            NEXT.fetch_add(1, Ordering::Relaxed)
352        );
353        let (_dir, loaded) = environment(&key, "value");
354        unsafe { apply(&loaded).unwrap() };
355        assert_eq!(std::env::var(&key).as_deref(), Ok("value"));
356        std::env::remove_var(&key);
357    }
358
359    #[test]
360    fn validation_rejects_nul_values_before_mutation() {
361        let _guard = ENV_LOCK.lock().unwrap();
362        let key = format!(
363            "ADOTENV_PROCESS_BAD_{}_{}",
364            std::process::id(),
365            NEXT.fetch_add(1, Ordering::Relaxed)
366        );
367        let (_dir, loaded) = environment(&key, "bad\0value");
368        assert!(matches!(
369            validate(&loaded),
370            Err(ApplyError::InvalidValue { .. })
371        ));
372        assert!(matches!(
373            unsafe { apply(&loaded) },
374            Err(ApplyError::InvalidValue { .. })
375        ));
376        assert!(std::env::var_os(&key).is_none());
377    }
378
379    #[test]
380    fn validation_rejects_nul_keys_before_mutation() {
381        let _guard = ENV_LOCK.lock().unwrap();
382        let dir = TempDir::new();
383        let key = "ADOTENV_PROCESS_NUL\0KEY";
384        fs::write(dir.path().join(".env"), format!("{key}=value\n")).unwrap();
385        let loaded =
386            adotenv::load::load_files([dir.path().join(".env")], adotenv::Dialect::DOCKER_RAW)
387                .unwrap();
388        assert_eq!(loaded.get(key), Some("value"));
389        assert!(matches!(
390            validate(&loaded),
391            Err(ApplyError::InvalidKey { ref key }) if key == "ADOTENV_PROCESS_NUL\0KEY"
392        ));
393        assert!(matches!(
394            unsafe { apply(&loaded) },
395            Err(ApplyError::InvalidKey { .. })
396        ));
397    }
398
399    #[test]
400    fn all_apply_errors_have_descriptive_messages() {
401        assert_eq!(ApplyError::EmptyKey.to_string(), "environment key is empty");
402        assert_eq!(
403            ApplyError::InvalidKey { key: "A=B".into() }.to_string(),
404            "environment key contains NUL or '=': \"A=B\""
405        );
406        assert_eq!(
407            ApplyError::InvalidValue { key: "A".into() }.to_string(),
408            "environment value for \"A\" contains NUL"
409        );
410        assert_eq!(
411            ApplyError::DuplicateKey { key: "Path".into() }.to_string(),
412            "environment key collides case-insensitively: \"Path\""
413        );
414        assert_eq!(
415            ApplyError::ValueTooLong {
416                key: "A".into(),
417                limit: 32_767,
418            }
419            .to_string(),
420            "environment value for \"A\" exceeds 32767 UTF-16 code units"
421        );
422    }
423
424    #[cfg(windows)]
425    #[test]
426    fn windows_apply_rejects_duplicates_before_mutation() {
427        let _guard = ENV_LOCK.lock().unwrap();
428        let key = format!(
429            "ADOTENV_PROCESS_CASE_{}_{}",
430            std::process::id(),
431            NEXT.fetch_add(1, Ordering::Relaxed)
432        );
433        let other = key.to_ascii_lowercase();
434        let dir = TempDir::new();
435        fs::write(dir.path().join(".env"), format!("{key}=one\n{other}=two\n")).unwrap();
436        let loaded = load_cascade(dir.path(), "").unwrap();
437        assert!(std::env::var_os(&key).is_none());
438        assert!(std::env::var_os(&other).is_none());
439        assert!(matches!(
440            unsafe { apply(&loaded) },
441            Err(ApplyError::DuplicateKey { .. })
442        ));
443        assert!(std::env::var_os(&key).is_none());
444        assert!(std::env::var_os(&other).is_none());
445    }
446
447    #[cfg(windows)]
448    #[test]
449    fn windows_accepts_the_value_length_boundary() {
450        let dir = TempDir::new();
451        let value = "x".repeat(32_767);
452        fs::write(dir.path().join(".env"), format!("A={value}\n")).unwrap();
453        let loaded = load_cascade(dir.path(), "").unwrap();
454        assert!(validate(&loaded).is_ok());
455    }
456
457    #[cfg(windows)]
458    #[test]
459    fn windows_rejects_case_insensitive_duplicate_keys() {
460        let dir = TempDir::new();
461        fs::write(dir.path().join(".env"), "PATH=one\nPath=two\n").unwrap();
462        let loaded = load_cascade(dir.path(), "").unwrap();
463        assert!(matches!(
464            validate(&loaded),
465            Err(ApplyError::DuplicateKey { ref key }) if key.eq_ignore_ascii_case("path")
466        ));
467    }
468
469    #[cfg(windows)]
470    #[test]
471    fn windows_rejects_too_long_values() {
472        let dir = TempDir::new();
473        let value = "x".repeat(32_768);
474        fs::write(dir.path().join(".env"), format!("A={value}\n")).unwrap();
475        let loaded = load_cascade(dir.path(), "").unwrap();
476        assert!(matches!(
477            validate(&loaded),
478            Err(ApplyError::ValueTooLong {
479                ref key,
480                limit: 32_767
481            }) if key == "A"
482        ));
483    }
484
485    #[test]
486    fn error_messages_include_the_key() {
487        let error = ApplyError::InvalidKey { key: "A=B".into() };
488        assert!(error.to_string().contains("A=B"));
489    }
490}