Skip to content

Commit 59e42a7

Browse files
matt2eclaude
andcommitted
test(desktop): panic when a unit test reaches the real ~/.buzz nest
nest_dir() fell back to ~/.buzz whenever init_nest_dir had not run, which is always true in unit tests, so a test that reached nest code read the real nest and could rewrite ~/.buzz/AGENTS.md. Under cfg(test) that fallback now panics. The message says how to pin the nest: pin_temp_nest_dir_for_thread() for work on the test thread, or pin_nest_dir_for_test in a child-process test for work on other threads. The new thread pin returns a guard that owns a TempDir; dropping it unpins the thread and deletes the dir. A process-wide pin does not fit in-process tests, because cargo test runs them all in one process and the OnceLock can be set only once. Seven tests reached the fallback, all through default_agent_workdir(): auth_command_uses_augmented_path_for_node_adapter, test_prepared_install_command_uses_default_workdir and five provider_deploy_* tests. They now pin a temp nest. Under cfg!(test) default_agent_workdir() resolves on every call instead of caching for the process, because a cached per-test nest would be deleted before the next test used it. nest_dir_is_under_home and init_nest_dir_prod_sets_buzz could only pass by reaching the fallback. They are replaced by a should_panic test of the guard and a test that the thread pin and its dir go away on drop. Production behaviour is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Matt Toohey <[email protected]>
1 parent cc04cdc commit 59e42a7

6 files changed

Lines changed: 92 additions & 40 deletions

File tree

‎desktop/src-tauri/src/commands/agent_auth.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,7 @@ mod tests {
502502
#[cfg(unix)]
503503
#[test]
504504
fn auth_command_uses_augmented_path_for_node_adapter() {
505+
let _nest = crate::managed_agents::pin_temp_nest_dir_for_thread();
505506
use std::fs;
506507
use std::os::unix::fs::PermissionsExt;
507508

‎desktop/src-tauri/src/commands/agent_discovery/install_exec.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -619,6 +619,7 @@ mod tests {
619619
/// would start a real login shell, which is neither hermetic nor fast.
620620
#[test]
621621
fn test_prepared_install_command_uses_default_workdir() {
622+
let _nest = crate::managed_agents::pin_temp_nest_dir_for_thread();
622623
let expected = crate::managed_agents::default_agent_workdir()
623624
.expect("a default workdir must resolve on any test host");
624625

‎desktop/src-tauri/src/managed_agents/backend_tests.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ fn write_test_provider(path: &Path, body: &str) {
145145
#[cfg(unix)]
146146
#[test]
147147
fn provider_deploy_negotiates_and_deploys_the_same_staged_bytes() {
148+
let _nest = crate::managed_agents::pin_temp_nest_dir_for_thread();
148149
let directory = tempfile::tempdir().unwrap();
149150
let provider = directory.path().join("provider");
150151
let log = directory.path().join("invocations");
@@ -191,6 +192,7 @@ esac
191192
#[cfg(unix)]
192193
#[test]
193194
fn provider_deploy_uses_staged_bytes_after_same_inode_source_rewrite() {
195+
let _nest = crate::managed_agents::pin_temp_nest_dir_for_thread();
194196
use std::os::unix::fs::MetadataExt;
195197

196198
let directory = tempfile::tempdir().unwrap();
@@ -233,6 +235,7 @@ esac"#,
233235
#[cfg(unix)]
234236
#[test]
235237
fn provider_deploy_uses_staged_bytes_after_source_pathname_replacement() {
238+
let _nest = crate::managed_agents::pin_temp_nest_dir_for_thread();
236239
use std::os::unix::fs::{MetadataExt, PermissionsExt};
237240

238241
let directory = tempfile::tempdir().unwrap();
@@ -274,6 +277,7 @@ esac"#,
274277
#[cfg(unix)]
275278
#[test]
276279
fn provider_deploy_refuses_mismatch_before_sending_agent_secret() {
280+
let _nest = crate::managed_agents::pin_temp_nest_dir_for_thread();
277281
let directory = tempfile::tempdir().unwrap();
278282
let provider = directory.path().join("provider");
279283
let marker = directory.path().join("deploy-received");
@@ -301,6 +305,7 @@ esac"#,
301305
#[cfg(unix)]
302306
#[test]
303307
fn provider_deploy_requires_an_explicit_integer_protocol_version() {
308+
let _nest = crate::managed_agents::pin_temp_nest_dir_for_thread();
304309
let directory = tempfile::tempdir().unwrap();
305310
let provider = directory.path().join("provider");
306311
write_test_provider(

‎desktop/src-tauri/src/managed_agents/mod.rs‎

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -127,24 +127,28 @@ pub(crate) use teams::delete_catalog_team_at;
127127
/// `ensure_nest()` must be called during app setup before this is first
128128
/// invoked, so that `~/.buzz` exists and gets cached.
129129
///
130-
/// Cached for the process lifetime via `OnceLock`.
130+
/// Cached for the process lifetime via `OnceLock`, except in unit tests.
131131
/// Returns `None` in sandboxed/containerized environments where `$HOME` is
132132
/// unset or points to a non-existent path; callers fall back to inheriting
133133
/// the parent's CWD.
134134
pub fn default_agent_workdir() -> Option<std::path::PathBuf> {
135135
use std::sync::OnceLock;
136136
static WORKDIR: OnceLock<Option<std::path::PathBuf>> = OnceLock::new();
137-
WORKDIR
138-
.get_or_init(|| {
139-
// Prefer ~/.buzz if it exists (created by ensure_nest()).
140-
// Reject symlinks to prevent redirect attacks — is_dir()
141-
// follows symlinks, so check symlink_metadata() first.
142-
// Fall back to $HOME for resilience.
143-
nest_dir()
144-
.filter(|p| is_real_dir(p))
145-
.or_else(|| dirs::home_dir().filter(|p| p.is_dir()))
146-
})
147-
.clone()
137+
let resolve = || {
138+
// Prefer ~/.buzz if it exists (created by ensure_nest()).
139+
// Reject symlinks to prevent redirect attacks — is_dir()
140+
// follows symlinks, so check symlink_metadata() first.
141+
// Fall back to $HOME for resilience.
142+
nest_dir()
143+
.filter(|p| is_real_dir(p))
144+
.or_else(|| dirs::home_dir().filter(|p| p.is_dir()))
145+
};
146+
// Tests pin a temp nest per thread, so a process-wide cache would hand a
147+
// later test an earlier test's deleted nest.
148+
if cfg!(test) {
149+
return resolve();
150+
}
151+
WORKDIR.get_or_init(resolve).clone()
148152
}
149153

150154
/// Returns `true` if `path` is a real directory (not a symlink).

‎desktop/src-tauri/src/managed_agents/nest.rs‎

Lines changed: 58 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,10 +68,18 @@ const NEST_DIR_PROD: &str = ".buzz";
6868
///
6969
/// `None` inside the `OnceLock` means "home dir was unresolvable at init time".
7070
/// The outer `None` from `OnceLock::get` means "not initialized yet" —
71-
/// [`nest_dir`] falls back to the prod path in that case, ensuring test code
72-
/// that never calls [`init_nest_dir`] still works.
71+
/// [`nest_dir`] falls back to the prod path in that case, and panics instead
72+
/// in unit tests so they cannot reach the user's real nest.
7373
static NEST_DIR: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new();
7474

75+
#[cfg(test)]
76+
thread_local! {
77+
/// Temp nest pinned for the current test thread by
78+
/// [`pin_temp_nest_dir_for_thread`]. Checked before [`NEST_DIR`].
79+
static THREAD_NEST_DIR: std::cell::RefCell<Option<PathBuf>> =
80+
const { std::cell::RefCell::new(None) };
81+
}
82+
7583
/// Initialize the process-lifetime nest directory.
7684
///
7785
/// Must be called once at app startup (before any call to [`nest_dir`] that
@@ -98,16 +106,61 @@ pub(crate) fn pin_nest_dir_for_test(path: PathBuf) {
98106
.expect("nest dir pinned before first use");
99107
}
100108

109+
/// A temp nest that [`nest_dir`] returns on the thread that pinned it.
110+
/// Dropping it unpins the thread and deletes the directory.
111+
#[cfg(test)]
112+
pub(crate) struct ThreadNestDir(tempfile::TempDir);
113+
114+
#[cfg(test)]
115+
impl ThreadNestDir {
116+
pub(crate) fn path(&self) -> &Path {
117+
self.0.path()
118+
}
119+
}
120+
121+
#[cfg(test)]
122+
impl Drop for ThreadNestDir {
123+
fn drop(&mut self) {
124+
THREAD_NEST_DIR.with(|pinned| pinned.borrow_mut().take());
125+
}
126+
}
127+
128+
/// Pin the nest root to a fresh temp dir for an in-process test. Only nest
129+
/// work on the calling thread sees the pin; work on other threads still
130+
/// panics, so pin those tests in a child process with [`pin_nest_dir_for_test`].
131+
#[cfg(test)]
132+
pub(crate) fn pin_temp_nest_dir_for_thread() -> ThreadNestDir {
133+
let dir = tempfile::tempdir().expect("create temp nest dir");
134+
THREAD_NEST_DIR.with(|pinned| {
135+
let previous = pinned.borrow_mut().replace(dir.path().to_path_buf());
136+
assert!(previous.is_none(), "nest dir already pinned on this thread");
137+
});
138+
ThreadNestDir(dir)
139+
}
140+
101141
/// Returns the nest root path (`~/.buzz` for prod, `~/.buzz-dev` for dev),
102142
/// or `None` if the home directory cannot be resolved.
103143
///
104-
/// If [`init_nest_dir`] has not been called yet (e.g. in unit tests), falls
105-
/// back to the production path `~/.buzz`.
144+
/// If [`init_nest_dir`] has not been called yet, falls back to the production
145+
/// path `~/.buzz`. Unit tests panic there instead and must pin the nest first.
106146
pub fn nest_dir() -> Option<PathBuf> {
147+
#[cfg(test)]
148+
if let Some(dir) = THREAD_NEST_DIR.with(|pinned| pinned.borrow().clone()) {
149+
return Some(dir);
150+
}
107151
match NEST_DIR.get() {
108152
Some(path) => path.clone(),
109-
// Not yet initialized — fall back to prod path. Covers test code.
153+
// Not yet initialized — fall back to prod path.
154+
#[cfg(not(test))]
110155
None => dirs::home_dir().map(|h| h.join(NEST_DIR_PROD)),
156+
#[cfg(test)]
157+
None => panic!(
158+
"nest_dir() is not pinned, so it would fall back to the real ~/{NEST_DIR_PROD}. \
159+
Pin it to a temp dir first: `let _nest = \
160+
crate::managed_agents::pin_temp_nest_dir_for_thread();` when the nest work \
161+
runs on the test thread, or `pin_nest_dir_for_test(path)` in a child-process \
162+
test (see nest/regen_trigger_tests.rs) when it runs on other threads"
163+
),
111164
}
112165
}
113166

‎desktop/src-tauri/src/managed_agents/nest/tests.rs‎

Lines changed: 11 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,20 @@
11
use super::*;
22

33
#[test]
4-
fn nest_dir_is_under_home() {
5-
if let Some(dir) = nest_dir() {
6-
// Accepts both .buzz (prod) and .buzz-dev (dev) depending on
7-
// whether init_nest_dir was called before this test ran.
8-
let name = dir.file_name().and_then(|n| n.to_str()).unwrap_or("");
9-
assert!(
10-
name == NEST_DIR_PROD || name == crate::build_identity::nest_name(true),
11-
"nest_dir must end with .buzz or .buzz-dev, got {dir:?}"
12-
);
13-
}
4+
#[should_panic(expected = "nest_dir() is not pinned")]
5+
fn unpinned_nest_dir_panics_instead_of_using_the_real_nest() {
6+
nest_dir();
147
}
158

169
#[test]
17-
fn init_nest_dir_prod_sets_buzz() {
18-
// init_nest_dir is idempotent (OnceLock) — once set, subsequent calls
19-
// are no-ops. We can only test the fallback path if the OnceLock is
20-
// unset, which is only true in a fresh process. Instead, verify that
21-
// nest_dir() always returns a path ending with a valid nest suffix.
22-
let dir = nest_dir();
23-
if let Some(d) = dir {
24-
let name = d.file_name().and_then(|n| n.to_str()).unwrap_or("");
25-
assert!(
26-
name == NEST_DIR_PROD || name == crate::build_identity::nest_name(true),
27-
"nest_dir suffix must be .buzz or .buzz-dev, got {d:?}"
28-
);
29-
}
10+
fn thread_nest_pin_is_removed_with_its_temp_dir() {
11+
let nest = pin_temp_nest_dir_for_thread();
12+
let path = nest.path().to_path_buf();
13+
assert_eq!(nest_dir(), Some(path.clone()));
14+
15+
drop(nest);
16+
assert!(!path.exists(), "temp nest must be deleted");
17+
assert!(THREAD_NEST_DIR.with(|pinned| pinned.borrow().is_none()));
3018
}
3119

3220
#[test]

0 commit comments

Comments
 (0)