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