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 supports Rust 1.81.
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/// A key or value that the process environment cannot hold.
77///
78/// Returned by [`validate`], and by [`apply`] before it changes anything. It
79/// reports the first problem, in key order. These are the inputs for which
80/// [`std::env::set_var`] may panic. The error names the key but never includes
81/// the value.
82///
83/// # Examples
84///
85/// Python dotenv lets a quoted key contain `=`. With `'APP=PORT'=8080` in
86/// `.env`:
87///
88/// ```
89/// use adotenv::load::load_cascade_with;
90/// use adotenv::Dialect;
91/// use adotenv_process::{validate, ApplyError};
92///
93/// # let dir = std::env::temp_dir().join(format!("adotenv-process-doc-ApplyError-{}", std::process::id()));
94/// # std::fs::create_dir_all(&dir)?;
95/// # std::fs::write(dir.join(".env"), "'APP=PORT'=8080\n")?;
96/// let loaded = load_cascade_with(&dir, "", Dialect::PYTHON_DOTENV)?;
97/// match validate(&loaded) {
98/// Err(ApplyError::InvalidKey { key }) => assert_eq!(key, "APP=PORT"),
99/// other => panic!("expected an invalid key, got {other:?}"),
100/// }
101/// # std::fs::remove_dir_all(&dir)?;
102/// # Ok::<(), Box<dyn std::error::Error>>(())
103/// ```
104#[derive(Debug, Clone, PartialEq, Eq)]
105#[non_exhaustive]
106pub enum ApplyError {
107 /// A key is empty.
108 ///
109 /// The `adotenv` loaders skip empty keys, so a loaded environment does not
110 /// produce this error; the check is a safeguard.
111 EmptyKey,
112 /// A key contains NUL or `=`.
113 InvalidKey {
114 /// The key, as loaded.
115 key: String,
116 },
117 /// A value contains NUL.
118 InvalidValue {
119 /// The key whose value contains NUL.
120 key: String,
121 },
122}
123
124impl fmt::Display for ApplyError {
125 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
126 match self {
127 Self::EmptyKey => formatter.write_str("environment key is empty"),
128 Self::InvalidKey { key } => {
129 write!(formatter, "environment key contains NUL or '=': {key:?}")
130 }
131 Self::InvalidValue { key } => {
132 write!(formatter, "environment value for {key:?} contains NUL")
133 }
134 }
135 }
136}
137
138impl std::error::Error for ApplyError {}
139
140/// Checks that the process environment can hold every loaded key and value.
141///
142/// Runs the checks of [`apply`] without changing anything, so it is safe to
143/// call from any thread, for example to report a bad `.env` file early. A key
144/// must not be empty and must not contain NUL or `=`. A value must not contain
145/// NUL. Keys are checked in sorted order.
146///
147/// # Errors
148///
149/// Returns the first problem found:
150///
151/// - [`ApplyError::EmptyKey`] if a key is empty.
152/// - [`ApplyError::InvalidKey`] if a key contains NUL or `=`.
153/// - [`ApplyError::InvalidValue`] if a value contains NUL.
154///
155/// # Examples
156///
157/// With `PORT=8080` and a `TOKEN` value that contains a NUL byte in `.env`:
158///
159/// ```
160/// use adotenv::load::load_cascade;
161/// use adotenv_process::{validate, ApplyError};
162///
163/// # let dir = std::env::temp_dir().join(format!("adotenv-process-doc-validate-{}", std::process::id()));
164/// # std::fs::create_dir_all(&dir)?;
165/// # std::fs::write(dir.join(".env"), "PORT=8080\nTOKEN=abc\0def\n")?;
166/// let loaded = load_cascade(&dir, "")?;
167/// let error = validate(&loaded).unwrap_err();
168/// assert_eq!(error, ApplyError::InvalidValue { key: "TOKEN".to_string() });
169/// assert_eq!(error.to_string(), r#"environment value for "TOKEN" contains NUL"#);
170/// # std::fs::remove_dir_all(&dir)?;
171/// # Ok::<(), Box<dyn std::error::Error>>(())
172/// ```
173pub fn validate(environment: &LoadedEnvironment) -> Result<(), ApplyError> {
174 for (key, value) in environment.values() {
175 if key.is_empty() {
176 return Err(ApplyError::EmptyKey);
177 }
178 if key.bytes().any(|byte| byte == 0 || byte == b'=') {
179 return Err(ApplyError::InvalidKey {
180 key: key.to_string(),
181 });
182 }
183 if value.as_bytes().contains(&0) {
184 return Err(ApplyError::InvalidValue {
185 key: key.to_string(),
186 });
187 }
188 }
189 Ok(())
190}
191
192/// Sets every loaded key to its loaded value in the current process
193/// environment.
194///
195/// First runs [`validate`], so an environment it rejects changes nothing. Then
196/// sets each key with [`std::env::set_var`], in sorted order. A loaded key
197/// replaces a variable of the same name. Other variables are kept and nothing
198/// is removed. Values are set as loaded, without expanding references such as
199/// `${HOME}`. The changes cannot be rolled back.
200///
201/// Prefer passing [`LoadedEnvironment::values`] to a child process, or reading
202/// the values directly, unless code you do not control reads the process
203/// environment. See the [crate documentation](crate).
204///
205/// # Errors
206///
207/// Returns the [`ApplyError`] from [`validate`], before changing anything.
208///
209/// # Safety
210///
211/// No other thread may read or write the process environment while `apply`
212/// runs. That includes [`std::env::var`] and C functions such as `getenv` and
213/// `setenv` called by libraries. On some platforms such concurrent access is
214/// undefined behavior. In practice, call `apply` at the start of `main`, before
215/// starting threads or an async runtime.
216///
217/// # Examples
218///
219/// With `APP_PORT=8080` and `APP_HOST=0.0.0.0` in `.env`:
220///
221/// ```
222/// use adotenv::load::load_cascade;
223/// use adotenv_process::apply;
224///
225/// # let dir = std::env::temp_dir().join(format!("adotenv-process-doc-apply-{}", std::process::id()));
226/// # std::fs::create_dir_all(&dir)?;
227/// # std::fs::write(dir.join(".env"), "APP_PORT=8080\nAPP_HOST=0.0.0.0\n")?;
228/// let loaded = load_cascade(&dir, "")?;
229///
230/// // SAFETY: called at startup, before any other thread exists.
231/// unsafe { apply(&loaded)? };
232/// assert_eq!(std::env::var("APP_PORT")?, "8080");
233/// assert_eq!(std::env::var("APP_HOST")?, "0.0.0.0");
234/// # std::fs::remove_dir_all(&dir)?;
235/// # Ok::<(), Box<dyn std::error::Error>>(())
236/// ```
237pub unsafe fn apply(environment: &LoadedEnvironment) -> Result<(), ApplyError> {
238 validate(environment)?;
239 for (key, value) in environment.values() {
240 unsafe { env::set_var(key, value) };
241 }
242 Ok(())
243}
244
245#[cfg(test)]
246mod tests {
247 use std::{
248 fs,
249 path::PathBuf,
250 sync::atomic::{AtomicU64, Ordering},
251 };
252
253 use super::*;
254 use adotenv::load::load_cascade;
255
256 static NEXT: AtomicU64 = AtomicU64::new(0);
257
258 struct TempDir(PathBuf);
259
260 impl TempDir {
261 fn new() -> Self {
262 let path = std::env::temp_dir().join(format!(
263 "adotenv-process-{}-{}",
264 std::process::id(),
265 NEXT.fetch_add(1, Ordering::Relaxed)
266 ));
267 fs::create_dir_all(&path).unwrap();
268 Self(path)
269 }
270 fn path(&self) -> &std::path::Path {
271 &self.0
272 }
273 }
274
275 impl Drop for TempDir {
276 fn drop(&mut self) {
277 let _ = fs::remove_dir_all(&self.0);
278 }
279 }
280
281 fn environment(key: &str, value: &str) -> (TempDir, LoadedEnvironment) {
282 let dir = TempDir::new();
283 fs::write(dir.path().join(".env"), format!("{key}={value}\n")).unwrap();
284 let loaded = load_cascade(dir.path(), "").unwrap();
285 (dir, loaded)
286 }
287
288 #[test]
289 fn apply_sets_loaded_values_and_can_be_removed() {
290 let key = format!(
291 "ADOTENV_PROCESS_{}_{}",
292 std::process::id(),
293 NEXT.fetch_add(1, Ordering::Relaxed)
294 );
295 let (_dir, loaded) = environment(&key, "value");
296 unsafe { apply(&loaded).unwrap() };
297 assert_eq!(std::env::var(&key).as_deref(), Ok("value"));
298 std::env::remove_var(&key);
299 }
300
301 #[test]
302 fn validation_rejects_nul_values_before_mutation() {
303 let key = format!(
304 "ADOTENV_PROCESS_BAD_{}_{}",
305 std::process::id(),
306 NEXT.fetch_add(1, Ordering::Relaxed)
307 );
308 let (_dir, loaded) = environment(&key, "bad\0value");
309 assert!(matches!(
310 validate(&loaded),
311 Err(ApplyError::InvalidValue { .. })
312 ));
313 assert!(matches!(
314 unsafe { apply(&loaded) },
315 Err(ApplyError::InvalidValue { .. })
316 ));
317 assert!(std::env::var_os(&key).is_none());
318 }
319
320 #[test]
321 fn validation_rejects_nul_keys_before_mutation() {
322 let dir = TempDir::new();
323 let key = "ADOTENV_PROCESS_NUL\0KEY";
324 fs::write(dir.path().join(".env"), format!("{key}=value\n")).unwrap();
325 let loaded =
326 adotenv::load::load_files([dir.path().join(".env")], adotenv::Dialect::DOCKER_RAW)
327 .unwrap();
328 assert_eq!(loaded.get(key), Some("value"));
329 assert!(matches!(
330 validate(&loaded),
331 Err(ApplyError::InvalidKey { ref key }) if key == "ADOTENV_PROCESS_NUL\0KEY"
332 ));
333 assert!(matches!(
334 unsafe { apply(&loaded) },
335 Err(ApplyError::InvalidKey { .. })
336 ));
337 }
338
339 #[test]
340 fn all_apply_errors_have_descriptive_messages() {
341 assert_eq!(ApplyError::EmptyKey.to_string(), "environment key is empty");
342 assert_eq!(
343 ApplyError::InvalidKey { key: "A=B".into() }.to_string(),
344 "environment key contains NUL or '=': \"A=B\""
345 );
346 assert_eq!(
347 ApplyError::InvalidValue { key: "A".into() }.to_string(),
348 "environment value for \"A\" contains NUL"
349 );
350 }
351
352 #[test]
353 fn error_messages_include_the_key() {
354 let error = ApplyError::InvalidKey { key: "A=B".into() };
355 assert!(error.to_string().contains("A=B"));
356 }
357}