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 `place`.
11//!
12//! Everything is fail-open to *today's* behavior: with no `cwd`/`root` (or an unresolvable
13//! path) `place` returns the path as written, so the classifiers behave exactly as before
14//! — the signal tightens when present, never a regression when absent.
15
16use std::cell::RefCell;
17
18pub mod anchor;
19pub mod folder;
20mod root;
21mod temp_root;
22pub(crate) use folder::judging;
23pub(crate) use root::folder_on_disk;
24pub use root::{Root, root};
25mod home;
26pub mod item_shape;
27mod lexical;
28mod place;
29mod vars;
30pub use item_shape::{Binding, Facts, ItemShape, ItemShapeGuard, binding, enter_loop_shape, enter_stdin_shape, loop_shape, stdin_shape};
31pub(crate) use lexical::home_dir;
32#[cfg(test)]
33pub(crate) use lexical::{enter_home, guard_listing, walks_real_home};
34use lexical::{expand_home, lexical_join, names_no_known_directory};
35use place::physical;
36pub(crate) use place::{Here, Placed, here, on_the_link, place};
37pub use vars::{LoopGuard, VarGuard, enter_loop_var, enter_var, expand_vars, names_a_loop_var};
38
39/// The working directory and project root for the command under evaluation. Both optional:
40/// a harness may supply neither (e.g. opencode), and classification falls back to the
41/// relative-is-worktree assumption.
42#[derive(Clone, Default)]
43pub struct PathCtx {
44    pub cwd: Option<String>,
45    pub root: Option<String>,
46    /// The harness's session id, when it supplies one. Only used to recognize this session's
47    /// SCRATCHPAD — see [`in_session_scratchpad`].
48    pub session_id: Option<String>,
49}
50
51thread_local! {
52    static CURRENT: RefCell<PathCtx> = RefCell::new(PathCtx::default());
53    static REPORTED: RefCell<Option<String>> = const { RefCell::new(None) };
54    static REPORTED_RAW: RefCell<Option<String>> = const { RefCell::new(None) };
55}
56
57#[must_use]
58pub fn enter(ctx: PathCtx) -> Guard {
59    let reported = REPORTED.with(|r| r.replace(ctx.cwd.clone()));
60    let raw = REPORTED_RAW.with(|r| r.replace(None));
61    let here = place::swap_here(None);
62    physical::evaluation_begins();
63    Guard(CURRENT.with(|c| c.replace(ctx)), Some((reported, raw, here)))
64}
65
66/// Record the folder the harness reported. `runs_there` is whether the harness runs the command in
67/// it (`HookFormat::cwd_is_the_commands`); when not, the folder is never taken for where it runs.
68pub fn note_reported_cwd(cwd: Option<String>, runs_there: bool) {
69    place::note_here(cwd.as_deref(), runs_there);
70    REPORTED_RAW.with(|r| *r.borrow_mut() = cwd);
71}
72
73pub(crate) fn display_cwd() -> Option<String> {
74    if let Some(c) = cwd().filter(|c| !folder::is_unknown(c) && c != UNRESOLVED_CWD) {
75        return Some(c);
76    }
77    REPORTED_RAW.with(|r| r.borrow().clone()).filter(|c| !folder::is_unknown(c) && c != UNRESOLVED_CWD)
78}
79
80pub(crate) fn reported_is_secret() -> bool {
81    use crate::engine::resolve::regions::names_a_secret_text;
82    let spelled = REPORTED_RAW.with(|r| r.borrow().as_deref().is_some_and(names_a_secret_text));
83    spelled || here().is_some_and(|here| names_a_secret_text(&here.physical))
84}
85
86type Saved = (Option<String>, Option<String>, Option<Here>);
87
88pub struct Guard(PathCtx, Option<Saved>);
89
90impl Drop for Guard {
91    fn drop(&mut self) {
92        CURRENT.with(|c| *c.borrow_mut() = std::mem::take(&mut self.0));
93        if let Some((reported, raw, here)) = self.1.take() {
94            REPORTED.with(|r| *r.borrow_mut() = reported);
95            REPORTED_RAW.with(|r| *r.borrow_mut() = raw);
96            place::swap_here(here);
97            physical::evaluation_ends();
98        }
99    }
100}
101
102/// Run `f` with the ambient `cwd` temporarily replaced (root unchanged) — used by intra-line
103/// `cd` tracking as it walks a chain's statements. Restored on drop.
104#[must_use]
105pub fn enter_cwd(cwd: Option<String>) -> Guard {
106    Guard(
107        CURRENT.with(|c| {
108            let mut b = c.borrow_mut();
109            // `session_id` is carried through unchanged: a `cd` mid-chain must not drop scratchpad
110            // recognition (the session is the same session whatever directory it walks into).
111            PathCtx { cwd: std::mem::replace(&mut b.cwd, cwd), root: b.root.clone(), session_id: b.session_id.clone() }
112        }),
113        None,
114    )
115}
116
117/// Whether a `cd` earlier on the line moved the working directory away from the one the harness
118/// reported.
119pub(crate) fn moved_by_cd() -> bool {
120    REPORTED.with(|r| *r.borrow() != cwd())
121}
122
123/// The ambient working directory, if known.
124pub fn cwd() -> Option<String> {
125    CURRENT.with(|c| c.borrow().cwd.clone())
126}
127
128/// Whether the absolute, already placed `abs` lies at or below the project root as the kernel sees
129/// it, including a root that is itself a protected place.
130pub(crate) fn placed_in_root(placed: &Placed) -> bool {
131    match root() {
132        Root::Known(root) if root.starts_with('/') => crate::engine::resolve::regions::lies_in_root(placed, &physical::root(&root)),
133        Root::Known(_) | Root::Unknown => false,
134    }
135}
136
137pub fn in_session_scratchpad(path: &str) -> bool {
138    let Some(id) = CURRENT.with(|c| c.borrow().session_id.clone()) else {
139        return false;
140    };
141    if id.len() < 8 || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') || !under_temp_root(path) {
142        return false;
143    }
144    path.split('/').any(|seg| seg == id)
145}
146
147const TEMP_ROOTS: &[&str] = &["/tmp/", "/var/tmp/"];
148const MACOS_TEMP_ROOTS: &[&str] = &["/private/tmp/", "/private/var/tmp/"];
149const TEMP_ROOTS_ANY_CASE: &[&str] =
150    &["/tmp/", "/private/tmp/", "/var/tmp/", "/private/var/tmp/", "/var/folders/", "/private/var/folders/"];
151
152/// Whether `path` is under a temporary-filesystem root. `/tmp` and `/var/tmp` count on every
153/// platform. On macOS, so do `/private/tmp`, `/private/var/tmp`, and
154/// `/var/folders/<segment>/<segment>/T` with its `/private` spelling. `$TMPDIR` counts too.
155///
156/// The match is exact, including case. Scratchpad recognition uses this and not [`under_temp`]:
157/// folding `/TMP` into the scratchpad on a case-sensitive volume would treat a different directory
158/// as this session's.
159pub fn under_temp_root(path: &str) -> bool {
160    if TEMP_ROOTS.iter().any(|r| path.starts_with(r)) {
161        return true;
162    }
163    if crate::engine::resolve::regions::current_os() == "macos"
164        && (MACOS_TEMP_ROOTS.iter().any(|r| path.starts_with(r)) || temp_root::macos_user_temporary(path))
165    {
166        return true;
167    }
168    std::env::var("TMPDIR").ok().is_some_and(|t| {
169        let t = t.trim_end_matches('/');
170        !t.is_empty() && t.starts_with('/') && path.starts_with(&format!("{t}/"))
171    })
172}
173
174/// Whether `path` names a temporary directory, including a case variant, the macOS data-volume
175/// firmlink spelling (`/System/Volumes/Data/tmp`), and `/var/folders`. Shared by folder-code,
176/// config-dir and locus checks. This recognizes a place to refuse; it does not admit the path
177/// as scratch storage. A case variant of `/tmp` stays `machine` for writes on a case-sensitive volume.
178pub fn under_temp(path: &str) -> bool {
179    let folded = strip_data_volume(path).to_ascii_lowercase();
180    let dir = if folded.ends_with('/') { folded } else { format!("{folded}/") };
181    TEMP_ROOTS_ANY_CASE.iter().any(|root| dir.starts_with(root)) || tmpdir_spellings().iter().any(|root| dir.starts_with(root))
182}
183
184fn strip_data_volume(path: &str) -> String {
185    let mut rest = path;
186    const PREFIX: &str = "/system/volumes/data";
187    // `get`, not a slice: a multi-byte character can straddle the prefix length.
188    while rest.get(..PREFIX.len()).is_some_and(|head| head.eq_ignore_ascii_case(PREFIX)) {
189        let after = &rest[PREFIX.len()..];
190        if after.is_empty() || after.starts_with('/') {
191            rest = after;
192            continue;
193        }
194        break;
195    }
196    rest.to_string()
197}
198
199fn tmpdir_spellings() -> Vec<String> {
200    let Ok(raw) = std::env::var("TMPDIR") else { return Vec::new() };
201    let dir = raw.trim_end_matches('/').to_ascii_lowercase();
202    if dir.len() <= 1 || !dir.starts_with('/') {
203        return Vec::new();
204    }
205    let mut out = vec![format!("{dir}/")];
206    if let Some(rest) = dir.strip_prefix("/private/") {
207        out.push(format!("/{rest}/"));
208    } else if dir == "/tmp" || dir.starts_with("/tmp/") || dir == "/var" || dir.starts_with("/var/") {
209        out.push(format!("/private{dir}/"));
210    }
211    out
212}
213
214/// The directory the kernel would open for absolute `path`, or `path` when nothing on it is a link.
215pub(crate) fn physical_directory(path: &str) -> String {
216    if !path.starts_with('/') {
217        return path.to_string();
218    }
219    physical::resolve(path, true).unwrap_or_else(|| path.to_string())
220}
221
222thread_local! {
223    static STDIN_REPR: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
224}
225
226/// Bind the representative PATH of the items arriving on stdin, for the duration of the guard —
227/// set by the pipeline walker to the previous stage's output-path locus. An operand-injecting
228/// consumer (`xargs`) reads it so `find / | xargs cat` gates the injected operand at `/`, while
229/// `find ./src | xargs cat` gates it at the workspace (mirrors `find -exec`'s `{}` binding).
230#[must_use]
231pub fn enter_stdin_repr(repr: String) -> StdinReprGuard {
232    STDIN_REPR.with(|v| v.borrow_mut().push(repr));
233    StdinReprGuard
234}
235
236/// The current stdin-item representative, or `None` when the source is unknown (no pipe / an
237/// unmodeled producer) — in which case the consumer worst-cases the injected operand.
238pub fn stdin_item_repr() -> Option<String> {
239    STDIN_REPR.with(|v| v.borrow().last().cloned())
240}
241
242pub struct StdinReprGuard;
243
244impl Drop for StdinReprGuard {
245    fn drop(&mut self) {
246        STDIN_REPR.with(|v| {
247            v.borrow_mut().pop();
248        });
249    }
250}
251
252thread_local! {
253    static RIPGREP_CONFIG: RefCell<Vec<bool>> = const { RefCell::new(Vec::new()) };
254}
255
256pub(crate) const RIPGREP_CONFIG_PATH: &str = "RIPGREP_CONFIG_PATH";
257
258#[must_use]
259pub(crate) fn bind_ripgrep_config(follows: Option<bool>) -> RipgrepConfigGuard {
260    if let Some(follows) = follows {
261        RIPGREP_CONFIG.with(|v| v.borrow_mut().push(follows));
262    }
263    RipgrepConfigGuard { pushed: follows.is_some() }
264}
265
266/// Whether rg's config file makes it follow links: the one its own prefix names, or else the one
267/// named in the environment it inherits from us.
268pub(crate) fn ripgrep_config_follows() -> bool {
269    RIPGREP_CONFIG
270        .with(|v| v.borrow().last().copied())
271        .unwrap_or_else(|| config_file_follows(std::env::var_os(RIPGREP_CONFIG_PATH), cwd().as_deref()))
272}
273
274/// A config file that cannot be read may say anything, so it counts as following.
275fn config_file_follows(path: Option<std::ffi::OsString>, cwd: Option<&str>) -> bool {
276    let Some(path) = path.filter(|path| !path.is_empty()).map(std::path::PathBuf::from) else {
277        return false;
278    };
279    let path = match cwd {
280        _ if path.is_absolute() => path,
281        Some(cwd) => std::path::Path::new(cwd).join(path),
282        None => return true,
283    };
284    std::fs::read_to_string(path).map_or(true, |text| {
285        text.lines()
286            .map(str::trim)
287            .any(|line| line.starts_with("--follow") || (line.starts_with('-') && !line.starts_with("--") && line.contains('L')))
288    })
289}
290
291pub(crate) struct RipgrepConfigGuard {
292    pushed: bool,
293}
294
295impl Drop for RipgrepConfigGuard {
296    fn drop(&mut self) {
297        if self.pushed {
298            RIPGREP_CONFIG.with(|v| {
299                v.borrow_mut().pop();
300            });
301        }
302    }
303}
304
305/// Place a path argument put to `use_`. A write or a rebind is recorded as one the command leaf
306/// being judged NAMED (`folder`).
307pub(crate) fn place_for(path: &str, use_: anchor::Use) -> Placed {
308    if use_.mutates() {
309        folder::note_named_write();
310    }
311    place(path, Some(use_))
312}
313
314/// The cwd after a `cd` whose target cannot be pinned. It looks like a path AND is unpinnable, so
315/// every later relative path resolved against it worst-cases in both gate layers.
316pub(crate) const UNRESOLVED_CWD: &str = "/__SAFE_CHAINS_CMDSUB__";
317
318/// Resolve a `cd` target to a new working directory. `cur` is the current cwd, needed for a
319/// *relative* target. Used by intra-line `cd` tracking (HP-19 #2).
320///
321/// A target that cannot be pinned yields `UNRESOLVED_CWD`, NOT `None`. This used to return `None`
322/// for `~…` and `$VAR`, and the caller reads `None` as "no cd happened" and keeps the previous cwd
323/// — so the `cd` was silently ignored and every later relative path was judged against a workspace
324/// the shell had already left. `cd ~/.aws && cat credentials` and `cd ~/.claude && echo … >
325/// settings.json` both auto-approved that way, the second writing the very file the allowlist
326/// bridge trusts. `None` now means only what the caller can act on: `cd_target` already returned
327/// `None` for "not a cd" (bare `cd`, `cd -`), so reaching here means the shell definitely moved.
328///
329/// `~`/`~/…` are EXPANDED rather than blanket-refused, because they are pinnable — that keeps
330/// `cd ~/.aws && cat credentials` gated as the credential read it is instead of coarsely denying
331/// everything downstream.
332pub fn join_cwd(cur: Option<&str>, target: &str) -> Option<String> {
333    join_cwd_mode(cur, target, false)
334}
335
336/// The cwd after a command that calls `chdir(2)` on `target` (`git -C`, `tmux -c`, `find -execdir`):
337/// the kernel climbs `..` from where a link leads, not from the link, and a command in the unknown
338/// folder starts from the reported folder on disk. `cd` is different: the shell joins `..` on the
339/// spelling (`cd -L`), and [`join_cwd`] does that.
340pub(crate) fn join_cwd_chdir(cur: Option<&str>, target: &str) -> Option<String> {
341    let on_disk = cur.filter(|c| folder::is_unknown(c)).and_then(place::folder_below);
342    join_cwd_mode(on_disk.as_deref().or(cur), target, true)
343}
344
345pub fn join_cwd_mode(cur: Option<&str>, target: &str, physical: bool) -> Option<String> {
346    let expanded = match expand_home(target) {
347        Some(t) => t,
348        None => return Some(UNRESOLVED_CWD.to_string()), // `~` with no HOME
349    };
350    // Another user's home, a variable, an UNDECLARED substitution: the shell moved somewhere we
351    // cannot name. Fail closed rather than pretend it stayed put.
352    //
353    // A DECLARED substitution (`cd $(pwd)`) is deliberately not in that set. Its sentinel carries a
354    // locus. When that locus is the directory we are already in, the `cd` is identity — appending
355    // the sentinel would invent a child whose tag can later outrank the real directory. A tag that
356    // would move a directory from outside the execute band into it is unresolvable.
357    if names_no_known_directory(&expanded) {
358        return Some(UNRESOLVED_CWD.to_string());
359    }
360    let raw = if let Some(landed) = declared_substitution_directory(cur, &expanded) {
361        landed
362    } else if expanded.starts_with('/') {
363        expanded.into_owned()
364    } else {
365        let c = cur.filter(|c| c.starts_with('/'))?;
366        format!("{c}/{expanded}")
367    };
368    Some(if physical { physical::resolve(&raw, true).unwrap_or_else(|| lexical_join("/", &raw)) } else { lexical_join("/", &raw) })
369}
370
371/// Where `cd` of a declared substitution lands. `None` when `expanded` is not one of those sentinels.
372fn declared_substitution_directory(cur: Option<&str>, expanded: &str) -> Option<String> {
373    use crate::engine::facet::{FacetTerm, LocalLocus};
374    let after = expanded.strip_prefix(crate::cst::eval::TAGGED_PREFIX)?;
375    let (term, tail) = after.split_once("__").unwrap_or(("", ""));
376    let Some(tag) = LocalLocus::from_term(&term.to_lowercase().replace('_', "-")) else {
377        return Some(UNRESOLVED_CWD.to_string());
378    };
379    let Some(cur) = cur.filter(|c| c.starts_with('/') && *c != UNRESOLVED_CWD) else {
380        return Some(UNRESOLVED_CWD.to_string());
381    };
382    let here = crate::engine::resolve::locus::read_locus(cur);
383    if here == tag {
384        let rel = tail.trim_start_matches('/');
385        return Some(if rel.is_empty() { cur.to_string() } else { lexical::lexical_join(cur, rel) });
386    }
387    let in_band = |locus: LocalLocus| locus >= LocalLocus::SandboxScope && locus <= LocalLocus::WorktreeTrusted;
388    if in_band(tag) && !in_band(here) {
389        return Some(UNRESOLVED_CWD.to_string());
390    }
391    let base = match tag {
392        LocalLocus::Temp => "/tmp",
393        _ => return Some(UNRESOLVED_CWD.to_string()),
394    };
395    let rel = tail.trim_start_matches('/');
396    Some(if rel.is_empty() { base.to_string() } else { lexical::lexical_join(base, rel) })
397}
398
399#[cfg(test)]
400#[path = "pathctx/place_tests.rs"]
401mod place_tests;
402
403#[cfg(test)]
404#[path = "pathctx/root_consumers_tests.rs"]
405mod root_consumers_tests;
406
407#[cfg(test)]
408mod tests {
409    use super::*;
410
411    fn resolve(path: &str) -> String {
412        place(path, None).into_judged()
413    }
414
415    #[test]
416    fn an_inherited_ripgrep_config_follows_when_it_says_so_or_cannot_be_read() {
417        let dir = tempfile::tempdir().expect("scratch");
418        let cwd = dir.path().to_str().expect("utf-8");
419        for (name, text) in [
420            ("long", "--follow\n"),
421            ("short", "  -iL\n"),
422            ("plain", "--smart-case\n--max-columns=10\n"),
423            ("glob", "--glob=*L*\n--type-add=L:*.l\n"),
424        ] {
425            std::fs::write(dir.path().join(name), text).expect("config");
426        }
427        let follows = |path: Option<&str>, cwd: Option<&str>| config_file_follows(path.map(Into::into), cwd);
428        assert!(follows(Some("long"), Some(cwd)));
429        assert!(follows(Some("short"), Some(cwd)));
430        assert!(follows(Some("missing"), Some(cwd)));
431        assert!(follows(Some("plain"), None));
432        assert!(!follows(Some("plain"), Some(cwd)));
433        assert!(!follows(Some("glob"), Some(cwd)));
434        assert!(!follows(Some(dir.path().join("plain").to_str().expect("utf-8")), None));
435        assert!(!follows(Some(""), Some(cwd)));
436        assert!(!follows(None, Some(cwd)));
437    }
438
439    const SID: &str = "7676dbc5-a265-43b3-a0f8-49666792bd9b";
440
441    fn with_session<T>(id: Option<&str>, f: impl FnOnce() -> T) -> T {
442        let _g = enter(PathCtx { cwd: Some("/home/u/proj".into()), root: Some("/home/u/proj".into()), session_id: id.map(str::to_string) });
443        f()
444    }
445
446    /// The recognition rule is a SECURITY boundary: matching a path that is not really this
447    /// session's scratchpad would hand `sandbox-scope` (and therefore EXECUTE) to foreign code. So
448    /// enumerate the spoofing class rather than one example — every way a hostile or unrelated path
449    /// could try to look like the scratchpad must fail, and every legitimate spelling must match.
450    /// A macOS temp root is a legitimate spelling only on macOS.
451    #[test]
452    fn only_this_sessions_scratchpad_is_recognized() {
453        let scratch = format!("/private/tmp/claude-501/-Users-u-proj/{SID}/scratchpad");
454        let shared = [format!("/tmp/{SID}/x.sh"), format!("/tmp/some-other-harness/{SID}/work/x.sh"), format!("/var/tmp/{SID}/x.sh")];
455        let macos = [
456            format!("{scratch}/build.sh"),
457            format!("{scratch}/nested/deep/gen.py"),
458            scratch,
459            format!("/var/folders/xx/yy/T/{SID}/x.sh"),
460            format!("/private/var/folders/xx/yy/T/{SID}/x.sh"),
461        ];
462        let rejected = [
463            "/private/tmp/claude-501/-Users-u-proj/00000000-1111-2222-3333-444444444444/scratchpad/x.sh".to_string(),
464            format!("/tmp/{SID}-evil/x.sh"),
465            format!("/tmp/evil-{SID}/x.sh"),
466            format!("/tmp/a{SID}/x.sh"),
467            format!("/home/u/{SID}/x.sh"),
468            format!("~/.ssh/{SID}/id_rsa"),
469            format!("/etc/{SID}/passwd"),
470            "/tmp/evil.sh".to_string(),
471            "/private/tmp/downloaded.sh".to_string(),
472            format!("/TMP/{SID}/x.sh"),
473            format!("/System/Volumes/Data/tmp/{SID}/x.sh"),
474            format!("/VAR/folders/xx/yy/T/{SID}/x.sh"),
475            format!("/System/Volumes/Data/private/var/folders/xx/yy/T/{SID}/x.sh"),
476        ];
477        let recognize = |paths: &[String], yes: bool| {
478            with_session(Some(SID), || {
479                for p in paths {
480                    assert_eq!(in_session_scratchpad(p), yes, "{p}");
481                }
482            });
483        };
484        recognize(&shared, true);
485        recognize(&rejected, false);
486        crate::engine::resolve::regions::with_os("macos", || recognize(&macos, true));
487        crate::engine::resolve::regions::with_os("linux", || {
488            recognize(&shared, true);
489            recognize(&macos, false);
490        });
491    }
492
493    /// Fail closed on every degenerate session id: no harness id, or one too short/odd to be a
494    /// trustworthy anchor, must recognize NOTHING — never widen a path.
495    #[test]
496    fn a_missing_or_unusable_session_id_recognizes_nothing() {
497        let path = format!("/tmp/{SID}/x.sh");
498        with_session(None, || {
499            assert!(!in_session_scratchpad(&path), "no session id → no recognition");
500        });
501        for weak in ["", "abc", "1234567", "..", "/", "a/b", "id with space", "x*y"] {
502            with_session(Some(weak), || {
503                assert!(!in_session_scratchpad(&format!("/tmp/{weak}/x.sh")), "weak id {weak:?} must not anchor recognition",);
504            });
505        }
506    }
507
508    #[test]
509    fn under_temp_never_slices_inside_a_multibyte_character() {
510        let prefix = "/system/volumes/data";
511        for filler in ["\u{fffd}", "\u{e9}", "\u{1f600}"] {
512            for cut in 0..=prefix.len() {
513                let path = format!("{}{filler}{}", &prefix[..cut], &prefix[cut..]);
514                assert!(!under_temp(&path), "{path}");
515            }
516        }
517        assert!(under_temp("/System/Volumes/Data/tmp/x"));
518    }
519
520    #[test]
521    fn under_temp_folds_case_and_firmlinks_without_making_them_temp_roots() {
522        for path in [
523            "/TMP/y", "/Tmp/y", "/PRIVATE/TMP/y", "/private/TMP/y", "/System/Volumes/Data/tmp/y", "/System/Volumes/Data/private/tmp/y",
524            "/VAR/folders/xx/yy/T/y", "/Var/Folders/xx/yy/T/y",
525        ] {
526            assert!(under_temp(path), "{path}");
527            assert!(crate::engine::resolve::locus::under_temp(path), "locus: {path}");
528            assert!(!under_temp_root(path), "exact prefix must stay strict: {path}");
529        }
530        assert!(under_temp("/tmp/y"));
531        assert!(under_temp_root("/tmp/y"));
532        assert!(!under_temp("/etc/y"));
533        assert!(!under_temp("/tmpfile/y"));
534    }
535
536    /// `C/`, `0/` and `X/` hold caches and state. Only the per-user temporary directory is a temp
537    /// root, and only on macOS, where that directory exists.
538    #[test]
539    fn only_the_user_temporary_directory_under_var_folders_is_a_temp_root() {
540        let accepted = format!("/var/folders/xx/yy/T/{SID}/x.sh");
541        let private_accepted = format!("/private/var/folders/xx/yy/T/{SID}/x.sh");
542        let cache = format!("/var/folders/xx/yy/C/{SID}/x.sh");
543        let private_cache = format!("/private/var/folders/xx/yy/C/{SID}/x.sh");
544        let rejected = [
545            cache.clone(),
546            private_cache,
547            "/var/folders/xx/yy/0/x".to_string(),
548            "/private/var/folders/xx/yy/0/x".to_string(),
549            "/var/folders/xx/yy/X/x".to_string(),
550            "/private/var/folders/xx/yy/X/x".to_string(),
551            "/var/folders/xx/T/x.sh".to_string(),
552            format!("/var/folders/xx/yy/zz/T/{SID}/x.sh"),
553        ];
554        crate::engine::resolve::regions::with_os("macos", || {
555            with_session(Some(SID), || {
556                assert!(under_temp_root(&accepted), "{accepted}");
557                assert!(in_session_scratchpad(&accepted), "{accepted}");
558                assert!(under_temp_root(&private_accepted), "{private_accepted}");
559                assert!(in_session_scratchpad(&private_accepted), "{private_accepted}");
560                for path in &rejected {
561                    assert!(!under_temp_root(path), "must not be a temp root: {path}");
562                    assert!(!in_session_scratchpad(path), "must not be a scratchpad: {path}");
563                    assert!(under_temp(path), "the broad check still sees it: {path}");
564                }
565            });
566        });
567        crate::engine::resolve::regions::with_os("linux", || {
568            with_session(Some(SID), || {
569                for path in [&accepted, &private_accepted].into_iter().chain(rejected.iter()) {
570                    assert!(!under_temp_root(path), "linux: {path}");
571                    assert!(!in_session_scratchpad(path), "linux: {path}");
572                }
573                assert!(under_temp(&accepted));
574                assert!(under_temp_root("/tmp/x"));
575                assert!(under_temp_root("/var/tmp/x"));
576                assert!(!under_temp_root("/private/tmp/x"));
577                assert!(!under_temp_root("/private/var/tmp/x"));
578            });
579        });
580    }
581
582    #[test]
583    fn a_shallow_var_folders_path_is_not_a_temp_root() {
584        for path in ["/var/folders/xx/yy/T/y", "/private/var/folders/xx/yy/T/y", "/var/folders/x", "/private/var/folders/x"] {
585            assert!(under_temp(path), "{path}");
586        }
587        for path in ["/var/folders/x", "/private/var/folders/x", "/var/folders", "/private/var/folders", "/var/folders-extra/y"] {
588            assert!(!under_temp_root(path), "{path}");
589        }
590    }
591
592    #[test]
593    fn no_context_leaves_paths_unchanged() {
594        assert_eq!(resolve("./x"), "./x");
595        assert_eq!(resolve("config"), "config");
596        assert_eq!(resolve("/etc/x"), "/etc/x");
597    }
598
599    #[test]
600    fn relative_inside_the_project_stays_worktree_relative() {
601        let _g = enter(PathCtx { cwd: Some("/home/u/proj/sub".into()), root: Some("/home/u/proj".into()), ..Default::default() });
602        assert_eq!(resolve("x"), "sub/x", "cwd under root → root-relative");
603        assert_eq!(resolve("./y"), "sub/y");
604        assert_eq!(resolve("../z"), "z", ".. that stays inside root");
605    }
606
607    #[test]
608    fn relative_outside_the_project_becomes_absolute() {
609        let _g = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/home/u/proj".into()), ..Default::default() });
610        assert_eq!(resolve("x"), "/etc/x", "cd /etc → the real target");
611        assert_eq!(resolve("passwd"), "/etc/passwd");
612        assert_eq!(resolve("no-such-dir/*"), "/etc/no-such-dir/*");
613    }
614
615    #[test]
616    fn dotdot_escaping_the_project_becomes_absolute() {
617        let _g = enter(PathCtx { cwd: Some("/home/u/proj".into()), root: Some("/home/u/proj".into()), ..Default::default() });
618        assert_eq!(resolve("../../../etc/x"), "/etc/x");
619    }
620
621    #[test]
622    fn absolute_in_root_becomes_root_relative_outside_stays_absolute() {
623        let _g = enter(PathCtx { cwd: Some("/home/u/proj/sub".into()), root: Some("/home/u/proj".into()), ..Default::default() });
624        // absolute INSIDE root → root-relative (worktree), matching the relative spelling
625        assert_eq!(resolve("/home/u/proj/main.rs"), "main.rs");
626        assert_eq!(resolve("/home/u/proj/sub/x"), "sub/x");
627        assert_eq!(resolve("/home/u/proj/a/../b"), "b", "normalized in place");
628        assert_eq!(resolve("/home/u/proj"), ".", "the project root itself");
629        // absolute OUTSIDE root → unchanged (classified as machine)
630        assert_eq!(resolve("/usr/bin/x"), "/usr/bin/x");
631        assert_eq!(resolve("/home/u/proj/../../etc/x"), "/home/etc/x", "climbs to /home, still outside root");
632        assert_eq!(resolve("/home/u/proj/../../../etc/x"), "/etc/x", "escapes to /etc via ..");
633        assert_eq!(
634            resolve("/home/u/proj-evil/secret"),
635            "/home/u/proj-evil/secret",
636            "a sibling dir is not confused for inside by bare string prefix",
637        );
638        // home / unpinnable → returned as-is (the classifiers handle these)
639        assert_eq!(resolve("$HOME/x"), "$HOME/x");
640        assert_eq!(resolve("~/x"), "~/x");
641    }
642
643    #[test]
644    fn a_home_spelled_path_inside_root_becomes_root_relative() {
645        let Some(home) = crate::process_home::var().ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
646            return;
647        };
648        let root = format!("{home}/projects/app");
649        let _g = enter(PathCtx { cwd: Some(format!("{root}/sub")), root: Some(root), ..Default::default() });
650        assert_eq!(resolve("~/projects/app/src/main.rs"), "src/main.rs");
651        assert_eq!(resolve("~/projects/app"), ".");
652        assert_eq!(resolve("~/projects/app/"), ".");
653        let under = |rest: &str| format!("~/projects/{rest}");
654        assert_eq!(resolve(&under("app/a/../b")), "b");
655        assert_eq!(resolve(&under("app/.git/hooks/pre-commit")), ".git/hooks/pre-commit");
656        for (outside, why) in [("peer/x", "a sibling"), ("app-evil/x", "no bare string prefix"), ("app/../../.ssh/id_rsa", "an escape")] {
657            assert_eq!(resolve(&under(outside)), under(outside), "{why} stays home-spelled");
658        }
659        assert_eq!(resolve("~/.ssh/id_rsa"), "~/.ssh/id_rsa");
660        assert_eq!(resolve("~"), "~");
661        assert_eq!(resolve("~bob/projects/app/x"), "~bob/projects/app/x", "another user's home is not ours");
662    }
663
664    #[test]
665    fn a_home_spelled_path_needs_an_absolute_root() {
666        let _none = enter(PathCtx { cwd: Some("/w".into()), root: None, ..Default::default() });
667        assert_eq!(resolve("~/x"), "~/x");
668        drop(_none);
669        let _rel = enter(PathCtx { cwd: Some("/w".into()), root: Some("w".into()), ..Default::default() });
670        assert_eq!(resolve("~/x"), "~/x");
671    }
672
673    #[test]
674    fn a_home_rooted_workspace_leaves_home_paths_to_the_home_classifiers() {
675        let Some(home) = crate::process_home::var().ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
676            return;
677        };
678        let _g = enter(PathCtx { cwd: Some(home.clone()), root: Some(home.clone()), ..Default::default() });
679        assert_eq!(resolve("~"), "~");
680        assert_eq!(resolve("~/notes.txt"), "~/notes.txt");
681        assert_eq!(resolve("notes.txt"), format!("{home}/notes.txt"));
682        assert_eq!(resolve("."), home);
683    }
684
685    #[test]
686    fn a_home_spelled_path_is_not_resolved_from_outside_the_root_or_through_a_glob() {
687        let Some(home) = crate::process_home::var().ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
688            return;
689        };
690        let root = format!("{home}/projects/app");
691        let outside = enter(PathCtx { cwd: Some("/etc".into()), root: Some(root.clone()), ..Default::default() });
692        assert_eq!(resolve("~/projects/app/x"), "~/projects/app/x", "a quoted `~` would name a directory under the cwd");
693        drop(outside);
694        let _g = enter(PathCtx { cwd: Some(root.clone()), root: Some(root), ..Default::default() });
695        for glob in ["app/.ss?/id_rsa", "app/*"].map(|rest| format!("~/projects/{rest}")) {
696            assert_eq!(resolve(&glob), glob);
697        }
698    }
699
700    #[test]
701    fn a_home_spelled_path_is_not_resolved_into_a_protected_root() {
702        let Some(home) = crate::process_home::var().ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
703            return;
704        };
705        let root = format!("{home}/.ssh");
706        let _g = enter(PathCtx { cwd: Some(root.clone()), root: Some(root), ..Default::default() });
707        assert_eq!(resolve("~/.ssh/id_rsa"), "~/.ssh/id_rsa");
708    }
709
710    #[test]
711    fn a_root_holding_a_protected_place_keeps_every_path_absolute() {
712        let _g = enter(PathCtx { cwd: Some("/".into()), root: Some("/".into()), ..Default::default() });
713        assert_eq!(resolve("/etc/shadow"), "/etc/shadow");
714        assert_eq!(resolve("etc/sudoers"), "/etc/sudoers");
715        assert_eq!(resolve("etc"), "/etc");
716        assert_eq!(resolve("/srv/app/x"), "/srv/app/x");
717        assert_eq!(resolve("."), "/");
718        drop(_g);
719        let _etc = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/etc".into()), ..Default::default() });
720        assert_eq!(resolve("hosts"), "hosts", "an unprotected file in a root below every home is the worktree");
721        assert_eq!(resolve("sudoers"), "/etc/sudoers");
722        assert_eq!(resolve("."), "/etc", "the root itself is above a protected place");
723        drop(_etc);
724        let _inside = enter(PathCtx { cwd: Some("/root/app".into()), root: Some("/root/app".into()), ..Default::default() });
725        assert_eq!(resolve("/root/app/x"), "/root/app/x");
726    }
727
728    #[test]
729    fn loop_var_expands_to_its_representative_per_face() {
730        let _g = enter_loop_var("f".into(), "read_item".into(), "write_item".into());
731        assert_eq!(expand_vars("$f", false), "read_item");
732        assert_eq!(expand_vars("$f", true), "write_item");
733        assert_eq!(expand_vars("${f}", false), "read_item");
734        assert_eq!(expand_vars("$f.bak", false), "read_item.bak", "compound suffix");
735        assert_eq!(expand_vars("pre/$f", false), "pre/read_item");
736        assert_eq!(expand_vars("$foo", false), "$foo", "$foo is not $f");
737        assert_eq!(expand_vars("$g", false), "$g", "unbound var untouched");
738        assert_eq!(expand_vars("plain", false), "plain");
739    }
740
741    #[test]
742    fn loop_var_binding_is_scoped_and_nests() {
743        assert_eq!(expand_vars("$f", false), "$f", "no binding");
744        {
745            let _outer = enter_loop_var("f".into(), "outer".into(), "outer".into());
746            {
747                let _inner = enter_loop_var("f".into(), "inner".into(), "inner".into());
748                assert_eq!(expand_vars("$f", false), "inner", "innermost wins");
749            }
750            assert_eq!(expand_vars("$f", false), "outer", "inner popped on drop");
751        }
752        assert_eq!(expand_vars("$f", false), "$f", "all popped");
753    }
754
755    #[test]
756    fn the_guard_restores_on_drop() {
757        {
758            let _g = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/r".into()), ..Default::default() });
759            assert_eq!(resolve("x"), "/etc/x");
760        }
761        assert_eq!(resolve("x"), "x", "context cleared after the guard drops");
762    }
763
764    const PROBE_VAR: &str = "SAFE_CHAINS_TMPDIR_PROBE_PATH";
765
766    fn tmpdir_verdict(tmpdir: &str, path: &str) -> bool {
767        let out = std::process::Command::new(std::env::current_exe().expect("test exe"))
768            .args(["--exact", "pathctx::tests::tmpdir_probe", "--nocapture", "--test-threads=1"])
769            .env("TMPDIR", tmpdir)
770            .env(PROBE_VAR, path)
771            .output()
772            .expect("spawn probe");
773        let stdout = String::from_utf8_lossy(&out.stdout);
774        assert!(out.status.success(), "probe failed for TMPDIR={tmpdir:?} path={path:?}: {stdout}");
775        match (stdout.contains("PROBE_VERDICT=true"), stdout.contains("PROBE_VERDICT=false")) {
776            (true, false) => true,
777            (false, true) => false,
778            _ => panic!("probe did not run for TMPDIR={tmpdir:?} path={path:?}: {stdout}"),
779        }
780    }
781
782    #[test]
783    fn tmpdir_probe() {
784        let Ok(path) = std::env::var(PROBE_VAR) else {
785            return;
786        };
787        println!("PROBE_VERDICT={}", under_temp_root(&path));
788    }
789
790    #[test]
791    fn a_tmpdir_root_counts_only_when_absolute_and_non_empty() {
792        for (tmpdir, path, expected) in [
793            ("/work/scratch", "/work/scratch/x.sh", true),
794            ("/work/scratch/", "/work/scratch/x.sh", true),
795            ("/work/scratch//", "/work/scratch/nested/x.sh", true),
796            ("/work/scratch", "/work/scratch", false),
797            ("/work/scratch", "/work/scratchy/x.sh", false),
798            ("/work/scratch", "/work/other/x.sh", false),
799            ("/work/scratch", "work/scratch/x.sh", false),
800            ("", "/x.sh", false),
801            ("", "/", false),
802            ("/", "/x.sh", false),
803            ("//", "/x.sh", false),
804            ("scratch", "scratch/x.sh", false),
805            ("scratch/", "scratch/x.sh", false),
806            ("./scratch", "./scratch/x.sh", false),
807            ("$SCRATCH", "$SCRATCH/x.sh", false),
808            ("relative/dir", "relative/dir/x.sh", false),
809        ] {
810            assert_eq!(tmpdir_verdict(tmpdir, path), expected, "TMPDIR={tmpdir:?} path={path:?}");
811        }
812    }
813
814    #[test]
815    fn the_fixed_temp_roots_hold_whatever_tmpdir_says() {
816        let mut roots = vec!["/tmp/x", "/var/tmp/x"];
817        if cfg!(target_os = "macos") {
818            roots.extend(["/private/tmp/x", "/private/var/tmp/x", "/var/folders/xx/yy/T/x"]);
819        }
820        for tmpdir in ["", "scratch", "/work/scratch"] {
821            for path in &roots {
822                assert!(tmpdir_verdict(tmpdir, path), "TMPDIR={tmpdir:?} path={path:?}");
823            }
824            for path in ["/var/folders/x", "/private/var/folders/x"] {
825                assert!(!tmpdir_verdict(tmpdir, path), "TMPDIR={tmpdir:?} path={path:?}");
826            }
827            if !cfg!(target_os = "macos") {
828                assert!(!tmpdir_verdict(tmpdir, "/private/tmp/x"), "TMPDIR={tmpdir:?}");
829                assert!(!tmpdir_verdict(tmpdir, "/private/var/tmp/x"), "TMPDIR={tmpdir:?}");
830                assert!(!tmpdir_verdict(tmpdir, "/var/folders/xx/yy/T/x"), "TMPDIR={tmpdir:?}");
831            }
832            assert!(!tmpdir_verdict(tmpdir, "/tmp"), "the bare root is not under itself");
833            assert!(!tmpdir_verdict(tmpdir, "/var/folders"), "the bare macOS root is not under itself");
834            assert!(!tmpdir_verdict(tmpdir, "/VAR/folders/x"), "a case variant is a different directory");
835        }
836    }
837}