Skip to main content

safe_chains/
pathctx.rs

1//! The directory context the harness supplies (HP-19): the working directory a command
2//! runs in, and the project root. It exists to make relative-path classification honest —
3//! `cd /etc && echo > ./x` must be seen as writing `/etc/x`, not a worktree file.
4//!
5//! The context is **ambient** for one command evaluation: a single `cwd`/`root` pair threads
6//! logically through the whole recursive verdict tree (script → pipeline → cmd → redirect →
7//! leaf). Rather than add a pass-through parameter to ~15 recursive functions across `cst`,
8//! `handlers`, and `engine`, it lives in a scoped thread-local, installed by
9//! [`enter`] at the top of an evaluation and read at exactly two leaves: legacy
10//! `is_safe_write_target` and engine `classify_locus`, both via [`resolve`].
11//!
12//! Everything is fail-open to *today's* behavior: with no `cwd`/`root` (or an unresolvable
13//! path) [`resolve`] returns the path unchanged, so the classifiers behave exactly as before
14//! — the signal tightens when present, never a regression when absent.
15
16use std::borrow::Cow;
17use std::cell::RefCell;
18
19pub mod anchor;
20pub mod folder;
21pub(crate) use folder::judging;
22mod home;
23pub mod item_shape;
24mod lexical;
25mod physical;
26mod placing;
27mod vars;
28pub use item_shape::{Binding, Facts, ItemShape, ItemShapeGuard, binding, enter_loop_shape, enter_stdin_shape, loop_shape, stdin_shape};
29use lexical::{expand_home, lexical_join, names_no_known_directory};
30pub(crate) use placing::on_the_link;
31use placing::resolve_placed;
32pub use vars::{LoopGuard, VarGuard, enter_loop_var, enter_var, expand_vars, names_a_loop_var};
33
34/// The working directory and project root for the command under evaluation. Both optional:
35/// a harness may supply neither (e.g. opencode), and classification falls back to the
36/// relative-is-worktree assumption.
37#[derive(Clone, Default)]
38pub struct PathCtx {
39    pub cwd: Option<String>,
40    pub root: Option<String>,
41    /// The harness's session id, when it supplies one. Only used to recognize this session's
42    /// SCRATCHPAD — see [`in_session_scratchpad`].
43    pub session_id: Option<String>,
44}
45
46thread_local! {
47    static CURRENT: RefCell<PathCtx> = RefCell::new(PathCtx::default());
48}
49
50/// Install `ctx` as the ambient context for the duration of the returned guard; the previous
51/// context is restored on drop (panic-safe, so a failing test can't leak into the next).
52#[must_use]
53pub fn enter(ctx: PathCtx) -> Guard {
54    Guard(CURRENT.with(|c| c.replace(ctx)))
55}
56
57/// Restores the previous [`PathCtx`] when dropped.
58pub struct Guard(PathCtx);
59
60impl Drop for Guard {
61    fn drop(&mut self) {
62        CURRENT.with(|c| *c.borrow_mut() = std::mem::take(&mut self.0));
63    }
64}
65
66/// Run `f` with the ambient `cwd` temporarily replaced (root unchanged) — used by intra-line
67/// `cd` tracking as it walks a chain's statements. Restored on drop.
68#[must_use]
69pub fn enter_cwd(cwd: Option<String>) -> Guard {
70    Guard(CURRENT.with(|c| {
71        let mut b = c.borrow_mut();
72        // `session_id` is carried through unchanged: a `cd` mid-chain must not drop scratchpad
73        // recognition (the session is the same session whatever directory it walks into).
74        PathCtx { cwd: std::mem::replace(&mut b.cwd, cwd), root: b.root.clone(), session_id: b.session_id.clone() }
75    }))
76}
77
78/// The ambient working directory, if known.
79pub fn cwd() -> Option<String> {
80    CURRENT.with(|c| c.borrow().cwd.clone())
81}
82
83/// The workspace ROOT (project dir), if known — falling back to `cwd` (the hook defaults root to
84/// cwd). Used by the adjacent-sibling classifier to find the workspace's parent.
85pub fn root() -> Option<String> {
86    CURRENT.with(|c| {
87        let b = c.borrow();
88        b.root.clone().or_else(|| b.cwd.clone())
89    })
90}
91
92/// Whether `path` lies inside THIS session's scratchpad — the harness's own per-session working
93/// directory (e.g. Claude Code's `/private/tmp/claude-<uid>/<project-slug>/<session-id>/scratchpad`).
94///
95/// The anchor is the **session id as a whole path component**, not the surrounding layout. That is
96/// deliberate and is what makes this safe *and* durable:
97///
98/// - **Unforgeable.** The session id arrives in the harness's own hook envelope, never from the
99///   agent's shell. An attacker cannot pre-plant `/tmp/<this-session-id>/evil.sh` because the id is
100///   unknown until the session exists (and it is unique per session). Compare a *layout* pattern
101///   ("anything under `/tmp/claude-*`"), which anyone can create.
102/// - **Durable.** It survives the harness reorganizing the parts around the id — the uid suffix,
103///   the slug, `/tmp` vs `/private/tmp`, the trailing directory name. Those are internal details
104///   (Claude Code does not document or expose the scratchpad path, and declined to; see
105///   docs/design/agent-scratchpad.md), so matching them exactly would be brittle.
106/// - **Fail-closed.** No session id, or a path that does not contain it, simply does not match:
107///   the path keeps its ordinary classification (`/tmp` → `temp`, i.e. foreign). A harness that
108///   supplies no id, or whose scratchpad omits it, is exactly as restricted as before — never worse.
109///
110/// Requiring a TEMP-root prefix as well keeps the id from blessing something outside the scratch
111/// area on a harness that happens to embed the id elsewhere (a log path under `$HOME`, say).
112pub fn in_session_scratchpad(path: &str) -> bool {
113    let Some(id) = CURRENT.with(|c| c.borrow().session_id.clone()) else {
114        return false;
115    };
116    // A short or trivial id could collide with an ordinary directory name; require something
117    // id-shaped before trusting it as an anchor.
118    if id.len() < 8 || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
119        return false;
120    }
121    if !under_temp_root(path) {
122        return false;
123    }
124    path.split('/').any(|seg| seg == id)
125}
126
127/// Whether `path` is under a temporary-filesystem root. macOS's `/tmp` is a symlink to
128/// `/private/tmp`, and harnesses report either spelling, so both are accepted (as is `$TMPDIR`).
129pub fn under_temp_root(path: &str) -> bool {
130    const ROOTS: &[&str] = &["/tmp/", "/private/tmp/", "/var/tmp/", "/private/var/tmp/"];
131    if ROOTS.iter().any(|r| path.starts_with(r)) {
132        return true;
133    }
134    std::env::var("TMPDIR").ok().is_some_and(|t| {
135        let t = t.trim_end_matches('/');
136        !t.is_empty() && t.starts_with('/') && path.starts_with(&format!("{t}/"))
137    })
138}
139
140thread_local! {
141    static STDIN_REPR: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
142}
143
144/// Bind the representative PATH of the items arriving on stdin, for the duration of the guard —
145/// set by the pipeline walker to the previous stage's output-path locus. An operand-injecting
146/// consumer (`xargs`) reads it so `find / | xargs cat` gates the injected operand at `/`, while
147/// `find ./src | xargs cat` gates it at the workspace (mirrors `find -exec`'s `{}` binding).
148#[must_use]
149pub fn enter_stdin_repr(repr: String) -> StdinReprGuard {
150    STDIN_REPR.with(|v| v.borrow_mut().push(repr));
151    StdinReprGuard
152}
153
154/// The current stdin-item representative, or `None` when the source is unknown (no pipe / an
155/// unmodeled producer) — in which case the consumer worst-cases the injected operand.
156pub fn stdin_item_repr() -> Option<String> {
157    STDIN_REPR.with(|v| v.borrow().last().cloned())
158}
159
160pub struct StdinReprGuard;
161
162impl Drop for StdinReprGuard {
163    fn drop(&mut self) {
164        STDIN_REPR.with(|v| {
165            v.borrow_mut().pop();
166        });
167    }
168}
169
170/// Resolve a path argument for classification against the ambient `cwd`/`root`. Returns a
171/// path the *existing* classifiers (`classify_locus`, `is_safe_write_target`) can score
172/// unchanged. When `cwd` and `root` are both known and absolute, a **relative** path is lexically
173/// joined onto `cwd` (no filesystem access) and an **absolute** path is normalized in place; then
174/// either way, if the result is inside `root` it comes back as a **root-relative** path (so the
175/// classifiers see "worktree"), and if it escaped `root` (e.g. `cwd` is `/etc`, or an absolute
176/// `/etc/hosts`) it comes back **absolute** (so they see `machine`/etc.). This makes the absolute
177/// and relative spellings of the SAME in-root file classify identically — safety on the OPERATION,
178/// not the SYNTAX. A `~/…` path that expands into `root` comes back root-relative too, as its
179/// `$HOME/…` spelling does; any other `~` path, a `$`-unpinnable one, or no context, is returned
180/// as-is for the home classifiers. In an unknown folder (`folder`), a placed path joins the root.
181pub fn resolve(path: &str) -> Cow<'_, str> {
182    resolve_placed(path, None)
183}
184
185/// As [`resolve`], for a path put to `use_`. A write or a rebind is recorded as one the command leaf
186/// being judged NAMED (`folder`).
187pub fn resolve_for(path: &str, use_: anchor::Use) -> Cow<'_, str> {
188    if use_.mutates() {
189        folder::note_named_write();
190    }
191    resolve_placed(path, Some(use_))
192}
193
194/// The cwd after a `cd` whose target cannot be pinned. It looks like a path AND is unpinnable, so
195/// every later relative path resolved against it worst-cases in both gate layers.
196pub(crate) const UNRESOLVED_CWD: &str = "/__SAFE_CHAINS_CMDSUB__";
197
198/// Resolve a `cd` target to a new working directory. `cur` is the current cwd, needed for a
199/// *relative* target. Used by intra-line `cd` tracking (HP-19 #2).
200///
201/// A target that cannot be pinned yields `UNRESOLVED_CWD`, NOT `None`. This used to return `None`
202/// for `~…` and `$VAR`, and the caller reads `None` as "no cd happened" and keeps the previous cwd
203/// — so the `cd` was silently ignored and every later relative path was judged against a workspace
204/// the shell had already left. `cd ~/.aws && cat credentials` and `cd ~/.claude && echo … >
205/// settings.json` both auto-approved that way, the second writing the very file the allowlist
206/// bridge trusts. `None` now means only what the caller can act on: `cd_target` already returned
207/// `None` for "not a cd" (bare `cd`, `cd -`), so reaching here means the shell definitely moved.
208///
209/// `~`/`~/…` are EXPANDED rather than blanket-refused, because they are pinnable — that keeps
210/// `cd ~/.aws && cat credentials` gated as the credential read it is instead of coarsely denying
211/// everything downstream.
212pub fn join_cwd(cur: Option<&str>, target: &str) -> Option<String> {
213    join_cwd_mode(cur, target, false)
214}
215
216pub fn join_cwd_mode(cur: Option<&str>, target: &str, physical: bool) -> Option<String> {
217    let expanded = match expand_home(target) {
218        Some(t) => t,
219        None => return Some(UNRESOLVED_CWD.to_string()), // `~` with no HOME
220    };
221    // Another user's home, a variable, an UNDECLARED substitution: the shell moved somewhere we
222    // cannot name. Fail closed rather than pretend it stayed put.
223    //
224    // A DECLARED substitution (`cd $(pwd)`) is deliberately not in that set. Its sentinel carries a
225    // locus, so letting it through the joins below keeps the cwd at that locus — `cd $(pwd) && cat
226    // f` stays a worktree read, while `cd $(fd d /etc) && cat f` is a machine one. Refusing both
227    // would have been sound but needlessly coarse.
228    if names_no_known_directory(&expanded) {
229        return Some(UNRESOLVED_CWD.to_string());
230    }
231    let raw = if expanded.starts_with('/') {
232        expanded.into_owned()
233    } else {
234        let c = cur.filter(|c| c.starts_with('/'))?;
235        format!("{c}/{expanded}")
236    };
237    Some(if physical { physical::resolve(&raw, true).unwrap_or_else(|| lexical_join("/", &raw)) } else { lexical_join("/", &raw) })
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    const SID: &str = "7676dbc5-a265-43b3-a0f8-49666792bd9b";
245
246    fn with_session<T>(id: Option<&str>, f: impl FnOnce() -> T) -> T {
247        let _g = enter(PathCtx { cwd: Some("/home/u/proj".into()), root: Some("/home/u/proj".into()), session_id: id.map(str::to_string) });
248        f()
249    }
250
251    /// The recognition rule is a SECURITY boundary: matching a path that is not really this
252    /// session's scratchpad would hand `sandbox-scope` (and therefore EXECUTE) to foreign code. So
253    /// enumerate the spoofing class rather than one example — every way a hostile or unrelated path
254    /// could try to look like the scratchpad must fail, and every legitimate spelling must match.
255    #[test]
256    fn only_this_sessions_scratchpad_is_recognized() {
257        let scratch = format!("/private/tmp/claude-501/-Users-u-proj/{SID}/scratchpad");
258        let matching: &[String] = &[
259            format!("{scratch}/build.sh"),
260            format!("{scratch}/nested/deep/gen.py"),
261            scratch.clone(),
262            // layout around the id varies by harness/platform — the id is the anchor, not the shape
263            format!("/tmp/{SID}/x.sh"),
264            format!("/tmp/some-other-harness/{SID}/work/x.sh"),
265            format!("/var/tmp/{SID}/x.sh"),
266        ];
267        let rejected: &[String] = &[
268            // a DIFFERENT session's scratchpad — same layout, wrong id
269            "/private/tmp/claude-501/-Users-u-proj/00000000-1111-2222-3333-444444444444/scratchpad/x.sh".into(),
270            // the id as a SUBSTRING of a component, not a component (the prefix/suffix attack)
271            format!("/tmp/{SID}-evil/x.sh"),
272            format!("/tmp/evil-{SID}/x.sh"),
273            format!("/tmp/a{SID}/x.sh"),
274            // right id, but OUTSIDE any temp root — the id must not bless arbitrary locations
275            format!("/home/u/{SID}/x.sh"),
276            format!("~/.ssh/{SID}/id_rsa"),
277            format!("/etc/{SID}/passwd"),
278            // anonymous temp files carry no id at all
279            "/tmp/evil.sh".into(),
280            "/private/tmp/downloaded.sh".into(),
281        ];
282        with_session(Some(SID), || {
283            for p in matching {
284                assert!(in_session_scratchpad(p), "should be recognized: {p}");
285            }
286            for p in rejected {
287                assert!(!in_session_scratchpad(p), "must NOT be recognized: {p}");
288            }
289        });
290    }
291
292    /// Fail closed on every degenerate session id: no harness id, or one too short/odd to be a
293    /// trustworthy anchor, must recognize NOTHING — never widen a path.
294    #[test]
295    fn a_missing_or_unusable_session_id_recognizes_nothing() {
296        let path = format!("/tmp/{SID}/x.sh");
297        with_session(None, || {
298            assert!(!in_session_scratchpad(&path), "no session id → no recognition");
299        });
300        for weak in ["", "abc", "1234567", "..", "/", "a/b", "id with space", "x*y"] {
301            with_session(Some(weak), || {
302                assert!(!in_session_scratchpad(&format!("/tmp/{weak}/x.sh")), "weak id {weak:?} must not anchor recognition",);
303            });
304        }
305    }
306
307    #[test]
308    fn no_context_leaves_paths_unchanged() {
309        assert_eq!(resolve("./x"), "./x");
310        assert_eq!(resolve("config"), "config");
311        assert_eq!(resolve("/etc/x"), "/etc/x");
312    }
313
314    #[test]
315    fn relative_inside_the_project_stays_worktree_relative() {
316        let _g = enter(PathCtx { cwd: Some("/home/u/proj/sub".into()), root: Some("/home/u/proj".into()), ..Default::default() });
317        assert_eq!(resolve("x"), "sub/x", "cwd under root → root-relative");
318        assert_eq!(resolve("./y"), "sub/y");
319        assert_eq!(resolve("../z"), "z", ".. that stays inside root");
320    }
321
322    #[test]
323    fn relative_outside_the_project_becomes_absolute() {
324        let _g = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/home/u/proj".into()), ..Default::default() });
325        assert_eq!(resolve("x"), "/etc/x", "cd /etc → the real target");
326        assert_eq!(resolve("passwd"), "/etc/passwd");
327        assert_eq!(resolve("no-such-dir/*"), "/etc/no-such-dir/*");
328    }
329
330    #[test]
331    fn dotdot_escaping_the_project_becomes_absolute() {
332        let _g = enter(PathCtx { cwd: Some("/home/u/proj".into()), root: Some("/home/u/proj".into()), ..Default::default() });
333        assert_eq!(resolve("../../../etc/x"), "/etc/x");
334    }
335
336    #[test]
337    fn absolute_in_root_becomes_root_relative_outside_stays_absolute() {
338        let _g = enter(PathCtx { cwd: Some("/home/u/proj/sub".into()), root: Some("/home/u/proj".into()), ..Default::default() });
339        // absolute INSIDE root → root-relative (worktree), matching the relative spelling
340        assert_eq!(resolve("/home/u/proj/main.rs"), "main.rs");
341        assert_eq!(resolve("/home/u/proj/sub/x"), "sub/x");
342        assert_eq!(resolve("/home/u/proj/a/../b"), "b", "normalized in place");
343        assert_eq!(resolve("/home/u/proj"), ".", "the project root itself");
344        // absolute OUTSIDE root → unchanged (classified as machine)
345        assert_eq!(resolve("/usr/bin/x"), "/usr/bin/x");
346        assert_eq!(resolve("/home/u/proj/../../etc/x"), "/home/etc/x", "climbs to /home, still outside root");
347        assert_eq!(resolve("/home/u/proj/../../../etc/x"), "/etc/x", "escapes to /etc via ..");
348        assert_eq!(
349            resolve("/home/u/proj-evil/secret"),
350            "/home/u/proj-evil/secret",
351            "a sibling dir is not confused for inside by bare string prefix",
352        );
353        // home / unpinnable → returned as-is (the classifiers handle these)
354        assert_eq!(resolve("$HOME/x"), "$HOME/x");
355        assert_eq!(resolve("~/x"), "~/x");
356    }
357
358    #[test]
359    fn a_home_spelled_path_inside_root_becomes_root_relative() {
360        let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
361            return;
362        };
363        let root = format!("{home}/projects/app");
364        let _g = enter(PathCtx { cwd: Some(format!("{root}/sub")), root: Some(root), ..Default::default() });
365        assert_eq!(resolve("~/projects/app/src/main.rs"), "src/main.rs");
366        assert_eq!(resolve("~/projects/app"), ".");
367        assert_eq!(resolve("~/projects/app/"), ".");
368        let under = |rest: &str| format!("~/projects/{rest}");
369        assert_eq!(resolve(&under("app/a/../b")), "b");
370        assert_eq!(resolve(&under("app/.git/hooks/pre-commit")), ".git/hooks/pre-commit");
371        for (outside, why) in [("peer/x", "a sibling"), ("app-evil/x", "no bare string prefix"), ("app/../../.ssh/id_rsa", "an escape")] {
372            assert_eq!(resolve(&under(outside)), under(outside), "{why} stays home-spelled");
373        }
374        assert_eq!(resolve("~/.ssh/id_rsa"), "~/.ssh/id_rsa");
375        assert_eq!(resolve("~"), "~");
376        assert_eq!(resolve("~bob/projects/app/x"), "~bob/projects/app/x", "another user's home is not ours");
377    }
378
379    #[test]
380    fn a_home_spelled_path_needs_an_absolute_root() {
381        let _none = enter(PathCtx { cwd: Some("/w".into()), root: None, ..Default::default() });
382        assert_eq!(resolve("~/x"), "~/x");
383        drop(_none);
384        let _rel = enter(PathCtx { cwd: Some("/w".into()), root: Some("w".into()), ..Default::default() });
385        assert_eq!(resolve("~/x"), "~/x");
386    }
387
388    #[test]
389    fn a_home_rooted_workspace_leaves_home_paths_to_the_home_classifiers() {
390        let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
391            return;
392        };
393        let _g = enter(PathCtx { cwd: Some(home.clone()), root: Some(home.clone()), ..Default::default() });
394        assert_eq!(resolve("~"), "~");
395        assert_eq!(resolve("~/notes.txt"), "~/notes.txt");
396        assert_eq!(resolve("notes.txt"), format!("{home}/notes.txt"));
397        assert_eq!(resolve("."), home);
398    }
399
400    #[test]
401    fn a_home_spelled_path_is_not_resolved_from_outside_the_root_or_through_a_glob() {
402        let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
403            return;
404        };
405        let root = format!("{home}/projects/app");
406        let outside = enter(PathCtx { cwd: Some("/etc".into()), root: Some(root.clone()), ..Default::default() });
407        assert_eq!(resolve("~/projects/app/x"), "~/projects/app/x", "a quoted `~` would name a directory under the cwd");
408        drop(outside);
409        let _g = enter(PathCtx { cwd: Some(root.clone()), root: Some(root), ..Default::default() });
410        for glob in ["app/.ss?/id_rsa", "app/*"].map(|rest| format!("~/projects/{rest}")) {
411            assert_eq!(resolve(&glob), glob);
412        }
413    }
414
415    #[test]
416    fn a_home_spelled_path_is_not_resolved_into_a_protected_root() {
417        let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
418            return;
419        };
420        let root = format!("{home}/.ssh");
421        let _g = enter(PathCtx { cwd: Some(root.clone()), root: Some(root), ..Default::default() });
422        assert_eq!(resolve("~/.ssh/id_rsa"), "~/.ssh/id_rsa");
423    }
424
425    #[test]
426    fn a_root_holding_a_protected_place_keeps_every_path_absolute() {
427        let _g = enter(PathCtx { cwd: Some("/".into()), root: Some("/".into()), ..Default::default() });
428        assert_eq!(resolve("/etc/shadow"), "/etc/shadow");
429        assert_eq!(resolve("etc/sudoers"), "/etc/sudoers");
430        assert_eq!(resolve("etc"), "/etc");
431        assert_eq!(resolve("/srv/app/x"), "/srv/app/x");
432        assert_eq!(resolve("."), "/");
433        drop(_g);
434        let _etc = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/etc".into()), ..Default::default() });
435        assert_eq!(resolve("hosts"), "hosts", "an unprotected file in a root below every home is the worktree");
436        assert_eq!(resolve("sudoers"), "/etc/sudoers");
437        assert_eq!(resolve("."), "/etc", "the root itself is above a protected place");
438        drop(_etc);
439        let _inside = enter(PathCtx { cwd: Some("/root/app".into()), root: Some("/root/app".into()), ..Default::default() });
440        assert_eq!(resolve("/root/app/x"), "x", "a root inside the protected place is where the user works");
441    }
442
443    #[test]
444    fn loop_var_expands_to_its_representative_per_face() {
445        let _g = enter_loop_var("f".into(), "read_item".into(), "write_item".into());
446        assert_eq!(expand_vars("$f", false), "read_item");
447        assert_eq!(expand_vars("$f", true), "write_item");
448        assert_eq!(expand_vars("${f}", false), "read_item");
449        assert_eq!(expand_vars("$f.bak", false), "read_item.bak", "compound suffix");
450        assert_eq!(expand_vars("pre/$f", false), "pre/read_item");
451        assert_eq!(expand_vars("$foo", false), "$foo", "$foo is not $f");
452        assert_eq!(expand_vars("$g", false), "$g", "unbound var untouched");
453        assert_eq!(expand_vars("plain", false), "plain");
454    }
455
456    #[test]
457    fn loop_var_binding_is_scoped_and_nests() {
458        assert_eq!(expand_vars("$f", false), "$f", "no binding");
459        {
460            let _outer = enter_loop_var("f".into(), "outer".into(), "outer".into());
461            {
462                let _inner = enter_loop_var("f".into(), "inner".into(), "inner".into());
463                assert_eq!(expand_vars("$f", false), "inner", "innermost wins");
464            }
465            assert_eq!(expand_vars("$f", false), "outer", "inner popped on drop");
466        }
467        assert_eq!(expand_vars("$f", false), "$f", "all popped");
468    }
469
470    #[test]
471    fn the_guard_restores_on_drop() {
472        {
473            let _g = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/r".into()), ..Default::default() });
474            assert_eq!(resolve("x"), "/etc/x");
475        }
476        assert_eq!(resolve("x"), "x", "context cleared after the guard drops");
477    }
478
479    const PROBE_VAR: &str = "SAFE_CHAINS_TMPDIR_PROBE_PATH";
480
481    fn tmpdir_verdict(tmpdir: &str, path: &str) -> bool {
482        let out = std::process::Command::new(std::env::current_exe().expect("test exe"))
483            .args(["--exact", "pathctx::tests::tmpdir_probe", "--nocapture", "--test-threads=1"])
484            .env("TMPDIR", tmpdir)
485            .env(PROBE_VAR, path)
486            .output()
487            .expect("spawn probe");
488        let stdout = String::from_utf8_lossy(&out.stdout);
489        assert!(out.status.success(), "probe failed for TMPDIR={tmpdir:?} path={path:?}: {stdout}");
490        match (stdout.contains("PROBE_VERDICT=true"), stdout.contains("PROBE_VERDICT=false")) {
491            (true, false) => true,
492            (false, true) => false,
493            _ => panic!("probe did not run for TMPDIR={tmpdir:?} path={path:?}: {stdout}"),
494        }
495    }
496
497    #[test]
498    fn tmpdir_probe() {
499        let Ok(path) = std::env::var(PROBE_VAR) else {
500            return;
501        };
502        println!("PROBE_VERDICT={}", under_temp_root(&path));
503    }
504
505    #[test]
506    fn a_tmpdir_root_counts_only_when_absolute_and_non_empty() {
507        for (tmpdir, path, expected) in [
508            ("/work/scratch", "/work/scratch/x.sh", true),
509            ("/work/scratch/", "/work/scratch/x.sh", true),
510            ("/work/scratch//", "/work/scratch/nested/x.sh", true),
511            ("/work/scratch", "/work/scratch", false),
512            ("/work/scratch", "/work/scratchy/x.sh", false),
513            ("/work/scratch", "/work/other/x.sh", false),
514            ("/work/scratch", "work/scratch/x.sh", false),
515            ("", "/x.sh", false),
516            ("", "/", false),
517            ("/", "/x.sh", false),
518            ("//", "/x.sh", false),
519            ("scratch", "scratch/x.sh", false),
520            ("scratch/", "scratch/x.sh", false),
521            ("./scratch", "./scratch/x.sh", false),
522            ("$SCRATCH", "$SCRATCH/x.sh", false),
523            ("relative/dir", "relative/dir/x.sh", false),
524        ] {
525            assert_eq!(tmpdir_verdict(tmpdir, path), expected, "TMPDIR={tmpdir:?} path={path:?}");
526        }
527    }
528
529    #[test]
530    fn the_fixed_temp_roots_hold_whatever_tmpdir_says() {
531        for tmpdir in ["", "scratch", "/work/scratch"] {
532            for path in ["/tmp/x", "/private/tmp/x", "/var/tmp/x", "/private/var/tmp/x"] {
533                assert!(tmpdir_verdict(tmpdir, path), "TMPDIR={tmpdir:?} path={path:?}");
534            }
535            assert!(!tmpdir_verdict(tmpdir, "/tmp"), "the bare root is not under itself");
536        }
537    }
538}