1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
//! Shared helpers for tests that need process-global environment isolation.
//!
//! `HOME`, `USERPROFILE`, `XDG_CONFIG_HOME`, `GIT_CONFIG_GLOBAL`, and
//! `GIT_CONFIG_SYSTEM` are process-global. The libtest runner executes unit tests
//! concurrently within one process, so any test that mutates or depends on these
//! variables must serialize on the SAME lock — module-local mutexes only protect
//! against siblings in the same file, not against an env-mutating test in another
//! module running in parallel.
use std::cell::{Cell, RefCell};
use std::ffi::{OsStr, OsString};
use std::process::Command;
use std::sync::{Mutex, MutexGuard, OnceLock};
/// Return inherited credential-shaped names so test child processes can omit them.
/// AFT's co-author setting is not a secret, but it is dropped too so a test
/// child never adds the operator's co-author trailer to fixture commits.
pub fn secret_named_environment_keys(is_secret_environment_key: fn(&str) -> bool) -> Vec<OsString> {
std::env::vars_os()
.map(|(key, _)| key)
.filter(|key| {
key.to_str()
.is_some_and(|key| is_secret_environment_key(key) || key == "AFT_GIT_CO_AUTHOR")
})
.collect()
}
fn process_env_mutex() -> &'static Mutex<()> {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
LOCK.get_or_init(|| Mutex::new(()))
}
/// Probe from a sibling test thread without waiting on the process-settings
/// guard. Used to verify that an environment fixture holds the shared mutex.
#[allow(dead_code)] // The integration helper copy uses this probe.
pub fn process_env_lock_is_available() -> bool {
!matches!(
process_env_mutex().try_lock(),
Err(std::sync::TryLockError::WouldBlock)
)
}
/// Acquire a test-only serialization mutex without cascading a prior test panic.
/// These locks serialize test setup rather than protect data invariants, so the
/// next test must proceed after a poisoned holder instead of manufacturing a
/// wall of unrelated failures.
pub fn lock_test_mutex<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
thread_local! {
static PROCESS_ENV_LOCK_DEPTH: Cell<usize> = const { Cell::new(0) };
static PROCESS_ENV_LOCK_GUARD: RefCell<Option<MutexGuard<'static, ()>>> = const { RefCell::new(None) };
}
/// Reentrant guard for the process-wide env-mutation lock.
///
/// Some tests already hold the shared env lock for `HOME` / `XDG_*` isolation and
/// then need to install hermetic git-config vars inside the same thread. A plain
/// `MutexGuard` would deadlock on that nested acquisition, so this guard keeps the
/// underlying mutex in thread-local storage and only releases it when the outermost
/// acquisition drops.
pub struct ProcessEnvLockGuard;
impl Drop for ProcessEnvLockGuard {
fn drop(&mut self) {
PROCESS_ENV_LOCK_DEPTH.with(|depth| {
let current = depth.get();
debug_assert!(current > 0, "process env lock depth underflow");
let next = current.saturating_sub(1);
depth.set(next);
if next == 0 {
PROCESS_ENV_LOCK_GUARD.with(|slot| {
slot.borrow_mut().take();
});
}
});
}
}
/// Acquire the process-wide env-mutation lock. Poison is ignored: a panicking
/// test already restored (or failed to restore) the env; letting the next test
/// proceed keeps one failure from cascading into every env-dependent test.
pub fn process_env_lock() -> ProcessEnvLockGuard {
PROCESS_ENV_LOCK_DEPTH.with(|depth| {
if depth.get() == 0 {
let guard = lock_test_mutex(process_env_mutex());
PROCESS_ENV_LOCK_GUARD.with(|slot| {
*slot.borrow_mut() = Some(guard);
});
}
depth.set(depth.get() + 1);
});
ProcessEnvLockGuard
}
pub struct StorageOverrideGuard {
previous: Option<OsString>,
_lock: ProcessEnvLockGuard,
}
impl Drop for StorageOverrideGuard {
fn drop(&mut self) {
if let Some(value) = &self.previous {
std::env::set_var("AFT_STORAGE_DIR", value);
} else {
std::env::remove_var("AFT_STORAGE_DIR");
}
}
}
/// Fixtures with explicit temporary namespaces must not inherit a worker's
/// process-wide override when testing their configured-path behavior.
pub fn without_storage_override() -> StorageOverrideGuard {
let lock = process_env_lock();
let previous = std::env::var_os("AFT_STORAGE_DIR");
std::env::remove_var("AFT_STORAGE_DIR");
StorageOverrideGuard {
previous,
_lock: lock,
}
}
/// Keep transport fixtures from starting project watchers unrelated to their
/// protocol assertions. Restore the setting before releasing the shared env lock.
pub struct ProjectWatcherDisabledGuard {
_setting: ScopedEnvVar,
_lock: ProcessEnvLockGuard,
}
pub fn without_project_watcher() -> ProjectWatcherDisabledGuard {
let lock = process_env_lock();
ProjectWatcherDisabledGuard {
_setting: ScopedEnvVar::set("AFT_TEST_DISABLE_FILE_WATCHER", "1"),
_lock: lock,
}
}
struct ScopedEnvVar {
key: &'static str,
previous: Option<OsString>,
}
impl ScopedEnvVar {
fn set(key: &'static str, value: impl AsRef<OsStr>) -> Self {
let previous = std::env::var_os(key);
unsafe { std::env::set_var(key, value) };
Self { key, previous }
}
}
impl Drop for ScopedEnvVar {
fn drop(&mut self) {
if let Some(previous) = self.previous.take() {
unsafe { std::env::set_var(self.key, previous) };
} else {
unsafe { std::env::remove_var(self.key) };
}
}
}
/// An empty git config file. Git for Windows refuses the `NUL` device as a
/// config path ("unable to access 'NUL': Invalid argument"), so Windows uses
/// a real empty file; elsewhere `/dev/null` reads as empty.
fn hermetic_git_config_path() -> &'static OsStr {
#[cfg(windows)]
{
static PATH: OnceLock<std::path::PathBuf> = OnceLock::new();
PATH.get_or_init(|| {
let path = std::env::temp_dir()
.join(format!("aft-test-empty-gitconfig-{}", std::process::id()));
std::fs::write(&path, b"").expect("write empty hermetic git config");
path
})
.as_os_str()
}
#[cfg(not(windows))]
{
OsStr::new("/dev/null")
}
}
/// Test-only git env overrides that suppress user/system config reads.
#[allow(dead_code)]
pub fn hermetic_git_env() -> [(&'static str, &'static OsStr); 2] {
[
("GIT_CONFIG_GLOBAL", hermetic_git_config_path()),
("GIT_CONFIG_SYSTEM", hermetic_git_config_path()),
]
}
/// Apply hermetic git-config env vars to one child process, including removal
/// of command-scope config inherited through `GIT_CONFIG_COUNT`.
#[allow(dead_code)]
pub fn apply_hermetic_git_env(command: &mut Command) -> &mut Command {
command
.envs(hermetic_git_env())
.env("GIT_CONFIG_COUNT", "0")
}
/// Hold hermetic git-config env vars for the current test thread.
///
/// Fields drop in declaration order, so `_lock` is last: the env vars must be
/// restored before another test can take the lock and observe them.
#[allow(dead_code)]
pub struct HermeticGitEnvGuard {
_global: ScopedEnvVar,
_system: ScopedEnvVar,
_config_count: ScopedEnvVar,
_lock: ProcessEnvLockGuard,
}
/// Install hermetic git-config env vars for in-process git executions during a
/// test. This is for code-under-test paths that shell `git` internally and
/// therefore cannot receive per-command env injection from the caller.
#[allow(dead_code)]
pub fn hermetic_git_env_guard() -> HermeticGitEnvGuard {
let lock = process_env_lock();
let [(global_key, global_value), (system_key, system_value)] = hermetic_git_env();
HermeticGitEnvGuard {
_lock: lock,
_global: ScopedEnvVar::set(global_key, global_value),
_system: ScopedEnvVar::set(system_key, system_value),
// Agent children on hosts with git.co_author enabled carry
// GIT_CONFIG_COUNT/KEY_0/VALUE_0 (core.hooksPath injection), and git's
// env scope outranks a test repo's local config - zeroing the count
// neutralizes the whole injected block for in-process git spawns.
_config_count: ScopedEnvVar::set("GIT_CONFIG_COUNT", OsStr::new("0")),
}
}
/// Keep in-process gh-shim tests away from the operator's state directory.
/// The shared lock is held for the complete lifetime of the override because
/// libtest runs these tests concurrently with other env-sensitive modules.
/// As above, `_lock` is declared last so the override is gone before the lock
/// is released.
pub struct GhShimStateGuard {
_state: ScopedEnvVar,
_temp: tempfile::TempDir,
_lock: ProcessEnvLockGuard,
}
pub fn gh_shim_state_guard() -> GhShimStateGuard {
let lock = process_env_lock();
let temp = tempfile::tempdir().expect("create gh-shim test state directory");
let state = ScopedEnvVar::set("AFT_GH_SHIM_STATE_DIR", temp.path());
GhShimStateGuard {
_lock: lock,
_state: state,
_temp: temp,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_mutex_lock_recovers_after_a_panicking_holder() {
let mutex = Mutex::new(());
let panic = std::panic::catch_unwind(|| {
let _guard = lock_test_mutex(&mutex);
panic!("deliberately poison the test serialization mutex");
});
assert!(panic.is_err());
assert!(mutex.is_poisoned());
drop(lock_test_mutex(&mutex));
}
#[test]
fn per_command_git_env_discards_inherited_command_scope_config() {
let mut command = Command::new("git");
command
.env("GIT_CONFIG_COUNT", "1")
.env("GIT_CONFIG_KEY_0", "core.fsyncMethod")
.env("GIT_CONFIG_VALUE_0", "batch");
let output = apply_hermetic_git_env(&mut command)
.args(["config", "--get", "core.fsyncMethod"])
.output()
.expect("query hermetic git config");
assert_eq!(output.status.code(), Some(1));
assert!(output.stdout.is_empty());
}
#[test]
fn gh_shim_state_guard_scopes_a_temp_override() {
let previous = std::env::var_os("AFT_GH_SHIM_STATE_DIR");
{
let _guard = gh_shim_state_guard();
let selected = std::env::var_os("AFT_GH_SHIM_STATE_DIR")
.expect("gh-shim guard installs a state override");
assert!(std::path::Path::new(&selected).is_absolute());
}
assert_eq!(std::env::var_os("AFT_GH_SHIM_STATE_DIR"), previous);
}
}