Skip to content

Commit b09645f

Browse files
committed
fix: Ensure thread-safe environment variable mutations with mutex lock
Signed-off-by: “niladrix719” <niladrix719@gmail.com>
1 parent c317271 commit b09645f

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

src/config_loader.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@ use std::{
44
ffi::{OsStr, OsString},
55
fs,
66
path::{Path, PathBuf},
7+
sync::Mutex,
78
};
89

910
use anyhow::{Context, Result, anyhow};
1011
use clap::{Error, Parser, error::ErrorKind};
11-
#[cfg(test)]
1212
use once_cell::sync::Lazy;
1313
use serde::Deserialize;
1414
use toml::Value;
@@ -32,6 +32,8 @@ pub fn parse_cli_with_config() -> Cli {
3232
Cli::parse_from(adjusted_args)
3333
}
3434

35+
static ENV_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));
36+
3537
#[derive(Debug, Deserialize, Default)]
3638
struct FileConfig {
3739
storage: Option<String>,
@@ -43,14 +45,16 @@ struct FileConfig {
4345
}
4446

4547
fn set_env_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V) {
48+
let _guard = ENV_LOCK.lock().unwrap();
4649
// SAFETY: std::env marks mutations as unsafe because concurrent writes can
47-
// lead to data races. We invoke these helpers before worker threads start
48-
// (or under a test mutex), matching std's documented safety guarantee.
50+
// lead to data races. Serializing through ENV_LOCK ensures only one thread
51+
// mutates the environment at a time, matching std's documented guarantee.
4952
unsafe { std_env::set_var(key, value) }
5053
}
5154

5255
#[cfg(test)]
5356
fn remove_env_var<K: AsRef<OsStr>>(key: K) {
57+
let _guard = ENV_LOCK.lock().unwrap();
5458
unsafe { std_env::remove_var(key) }
5559
}
5660

0 commit comments

Comments
 (0)