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    static REPORTED: RefCell<Option<String>> = const { RefCell::new(None) };
49}
50
51/// Install `ctx` as the ambient context for the duration of the returned guard; the previous
52/// context is restored on drop (panic-safe, so a failing test can't leak into the next).
53#[must_use]
54pub fn enter(ctx: PathCtx) -> Guard {
55    let reported = REPORTED.with(|r| r.replace(ctx.cwd.clone()));
56    Guard(CURRENT.with(|c| c.replace(ctx)), Some(reported))
57}
58
59/// Restores the previous [`PathCtx`] when dropped.
60pub struct Guard(PathCtx, Option<Option<String>>);
61
62impl Drop for Guard {
63    fn drop(&mut self) {
64        CURRENT.with(|c| *c.borrow_mut() = std::mem::take(&mut self.0));
65        if let Some(reported) = self.1.take() {
66            REPORTED.with(|r| *r.borrow_mut() = reported);
67        }
68    }
69}
70
71/// Run `f` with the ambient `cwd` temporarily replaced (root unchanged) — used by intra-line
72/// `cd` tracking as it walks a chain's statements. Restored on drop.
73#[must_use]
74pub fn enter_cwd(cwd: Option<String>) -> Guard {
75    Guard(
76        CURRENT.with(|c| {
77            let mut b = c.borrow_mut();
78            // `session_id` is carried through unchanged: a `cd` mid-chain must not drop scratchpad
79            // recognition (the session is the same session whatever directory it walks into).
80            PathCtx { cwd: std::mem::replace(&mut b.cwd, cwd), root: b.root.clone(), session_id: b.session_id.clone() }
81        }),
82        None,
83    )
84}
85
86/// Whether a `cd` earlier on the line moved the working directory away from the one the harness
87/// reported.
88pub(crate) fn moved_by_cd() -> bool {
89    REPORTED.with(|r| *r.borrow() != cwd())
90}
91
92/// The ambient working directory, if known.
93pub fn cwd() -> Option<String> {
94    CURRENT.with(|c| c.borrow().cwd.clone())
95}
96
97/// The workspace ROOT (project dir), if known — falling back to `cwd` (the hook defaults root to
98/// cwd). Used by the adjacent-sibling classifier to find the workspace's parent.
99pub fn root() -> Option<String> {
100    CURRENT.with(|c| {
101        let b = c.borrow();
102        b.root.clone().or_else(|| b.cwd.clone())
103    })
104}
105
106/// Whether the absolute, already placed `abs` lies at or below the project root as the kernel sees
107/// it, including a root that is itself a protected place.
108pub(crate) fn placed_in_root(abs: &str) -> bool {
109    root()
110        .filter(|root| root.starts_with('/'))
111        .is_some_and(|root| crate::engine::resolve::regions::lies_in_root(abs, &physical::root(&root)))
112}
113
114/// Whether `path` lies inside THIS session's scratchpad — the harness's own per-session working
115/// directory (e.g. Claude Code's `/private/tmp/claude-<uid>/<project-slug>/<session-id>/scratchpad`).
116///
117/// The anchor is the **session id as a whole path component**, not the surrounding layout. That is
118/// deliberate and is what makes this safe *and* durable:
119///
120/// - **Unforgeable.** The session id arrives in the harness's own hook envelope, never from the
121///   agent's shell. An attacker cannot pre-plant `/tmp/<this-session-id>/evil.sh` because the id is
122///   unknown until the session exists (and it is unique per session). Compare a *layout* pattern
123///   ("anything under `/tmp/claude-*`"), which anyone can create.
124/// - **Durable.** It survives the harness reorganizing the parts around the id — the uid suffix,
125///   the slug, `/tmp` vs `/private/tmp`, the trailing directory name. Those are internal details
126///   (Claude Code does not document or expose the scratchpad path, and declined to; see
127///   docs/design/agent-scratchpad.md), so matching them exactly would be brittle.
128/// - **Fail-closed.** No session id, or a path that does not contain it, simply does not match:
129///   the path keeps its ordinary classification (`/tmp` → `temp`, i.e. foreign). A harness that
130///   supplies no id, or whose scratchpad omits it, is exactly as restricted as before — never worse.
131///
132/// Requiring a TEMP-root prefix as well keeps the id from blessing something outside the scratch
133/// area on a harness that happens to embed the id elsewhere (a log path under `$HOME`, say).
134pub fn in_session_scratchpad(path: &str) -> bool {
135    let Some(id) = CURRENT.with(|c| c.borrow().session_id.clone()) else {
136        return false;
137    };
138    // A short or trivial id could collide with an ordinary directory name; require something
139    // id-shaped before trusting it as an anchor.
140    if id.len() < 8 || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
141        return false;
142    }
143    if !under_temp_root(path) {
144        return false;
145    }
146    path.split('/').any(|seg| seg == id)
147}
148
149const TEMP_ROOTS: &[&str] = &["/tmp/", "/private/tmp/", "/var/tmp/", "/private/var/tmp/"];
150const TEMP_ROOTS_ANY_CASE: &[&str] =
151    &["/tmp/", "/private/tmp/", "/var/tmp/", "/private/var/tmp/", "/var/folders/", "/private/var/folders/"];
152
153/// Whether `path` is under a temporary-filesystem root. macOS's `/tmp` is a symlink to
154/// `/private/tmp`, and harnesses report either spelling, so both are accepted (as is `$TMPDIR`).
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    std::env::var("TMPDIR").ok().is_some_and(|t| {
164        let t = t.trim_end_matches('/');
165        !t.is_empty() && t.starts_with('/') && path.starts_with(&format!("{t}/"))
166    })
167}
168
169/// Whether `path` names a temporary directory, including a case variant, the macOS data-volume
170/// firmlink spelling (`/System/Volumes/Data/tmp`), and `/var/folders`. Shared by folder-code,
171/// config-dir and locus checks. This recognizes a place to refuse; it does not admit the path
172/// as scratch storage. A case variant of `/tmp` stays `machine` for writes on a case-sensitive volume.
173pub fn under_temp(path: &str) -> bool {
174    let folded = strip_data_volume(path).to_ascii_lowercase();
175    let dir = if folded.ends_with('/') { folded } else { format!("{folded}/") };
176    TEMP_ROOTS_ANY_CASE.iter().any(|root| dir.starts_with(root)) || tmpdir_spellings().iter().any(|root| dir.starts_with(root))
177}
178
179fn strip_data_volume(path: &str) -> String {
180    let mut rest = path;
181    const PREFIX: &str = "/system/volumes/data";
182    // `get`, not a slice: a multi-byte character can straddle the prefix length.
183    while rest.get(..PREFIX.len()).is_some_and(|head| head.eq_ignore_ascii_case(PREFIX)) {
184        let after = &rest[PREFIX.len()..];
185        if after.is_empty() || after.starts_with('/') {
186            rest = after;
187            continue;
188        }
189        break;
190    }
191    rest.to_string()
192}
193
194fn tmpdir_spellings() -> Vec<String> {
195    let Ok(raw) = std::env::var("TMPDIR") else { return Vec::new() };
196    let dir = raw.trim_end_matches('/').to_ascii_lowercase();
197    if dir.len() <= 1 || !dir.starts_with('/') {
198        return Vec::new();
199    }
200    let mut out = vec![format!("{dir}/")];
201    if let Some(rest) = dir.strip_prefix("/private/") {
202        out.push(format!("/{rest}/"));
203    } else if dir == "/tmp" || dir.starts_with("/tmp/") || dir == "/var" || dir.starts_with("/var/") {
204        out.push(format!("/private{dir}/"));
205    }
206    out
207}
208
209/// The directory the kernel would open for absolute `path`, or `path` when nothing on it is a link.
210pub(crate) fn physical_directory(path: &str) -> String {
211    if !path.starts_with('/') {
212        return path.to_string();
213    }
214    physical::resolve(path, true).unwrap_or_else(|| path.to_string())
215}
216
217thread_local! {
218    static STDIN_REPR: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
219}
220
221/// Bind the representative PATH of the items arriving on stdin, for the duration of the guard —
222/// set by the pipeline walker to the previous stage's output-path locus. An operand-injecting
223/// consumer (`xargs`) reads it so `find / | xargs cat` gates the injected operand at `/`, while
224/// `find ./src | xargs cat` gates it at the workspace (mirrors `find -exec`'s `{}` binding).
225#[must_use]
226pub fn enter_stdin_repr(repr: String) -> StdinReprGuard {
227    STDIN_REPR.with(|v| v.borrow_mut().push(repr));
228    StdinReprGuard
229}
230
231/// The current stdin-item representative, or `None` when the source is unknown (no pipe / an
232/// unmodeled producer) — in which case the consumer worst-cases the injected operand.
233pub fn stdin_item_repr() -> Option<String> {
234    STDIN_REPR.with(|v| v.borrow().last().cloned())
235}
236
237pub struct StdinReprGuard;
238
239impl Drop for StdinReprGuard {
240    fn drop(&mut self) {
241        STDIN_REPR.with(|v| {
242            v.borrow_mut().pop();
243        });
244    }
245}
246
247thread_local! {
248    static RIPGREP_CONFIG: RefCell<Vec<bool>> = const { RefCell::new(Vec::new()) };
249}
250
251pub(crate) const RIPGREP_CONFIG_PATH: &str = "RIPGREP_CONFIG_PATH";
252
253#[must_use]
254pub(crate) fn bind_ripgrep_config(follows: Option<bool>) -> RipgrepConfigGuard {
255    if let Some(follows) = follows {
256        RIPGREP_CONFIG.with(|v| v.borrow_mut().push(follows));
257    }
258    RipgrepConfigGuard { pushed: follows.is_some() }
259}
260
261/// Whether rg's config file makes it follow links: the one its own prefix names, or else the one
262/// named in the environment it inherits from us.
263pub(crate) fn ripgrep_config_follows() -> bool {
264    RIPGREP_CONFIG
265        .with(|v| v.borrow().last().copied())
266        .unwrap_or_else(|| config_file_follows(std::env::var_os(RIPGREP_CONFIG_PATH), cwd().as_deref()))
267}
268
269/// A config file that cannot be read may say anything, so it counts as following.
270fn config_file_follows(path: Option<std::ffi::OsString>, cwd: Option<&str>) -> bool {
271    let Some(path) = path.filter(|path| !path.is_empty()).map(std::path::PathBuf::from) else {
272        return false;
273    };
274    let path = match cwd {
275        _ if path.is_absolute() => path,
276        Some(cwd) => std::path::Path::new(cwd).join(path),
277        None => return true,
278    };
279    std::fs::read_to_string(path).map_or(true, |text| {
280        text.lines()
281            .map(str::trim)
282            .any(|line| line.starts_with("--follow") || (line.starts_with('-') && !line.starts_with("--") && line.contains('L')))
283    })
284}
285
286pub(crate) struct RipgrepConfigGuard {
287    pushed: bool,
288}
289
290impl Drop for RipgrepConfigGuard {
291    fn drop(&mut self) {
292        if self.pushed {
293            RIPGREP_CONFIG.with(|v| {
294                v.borrow_mut().pop();
295            });
296        }
297    }
298}
299
300/// Resolve a path argument for classification against the ambient `cwd`/`root`. Returns a
301/// path the *existing* classifiers (`classify_locus`, `is_safe_write_target`) can score
302/// unchanged. When `cwd` and `root` are both known and absolute, a **relative** path is lexically
303/// joined onto `cwd` (no filesystem access) and an **absolute** path is normalized in place; then
304/// either way, if the result is inside `root` it comes back as a **root-relative** path (so the
305/// classifiers see "worktree"), and if it escaped `root` (e.g. `cwd` is `/etc`, or an absolute
306/// `/etc/hosts`) it comes back **absolute** (so they see `machine`/etc.). This makes the absolute
307/// and relative spellings of the SAME in-root file classify identically — safety on the OPERATION,
308/// not the SYNTAX. A `~/…` path that expands into `root` comes back root-relative too, as its
309/// `$HOME/…` spelling does; any other `~` path, a `$`-unpinnable one, or no context, is returned
310/// as-is for the home classifiers. In an unknown folder (`folder`), a placed path joins the root.
311pub fn resolve(path: &str) -> Cow<'_, str> {
312    resolve_placed(path, None)
313}
314
315/// As [`resolve`], for a path put to `use_`. A write or a rebind is recorded as one the command leaf
316/// being judged NAMED (`folder`).
317pub fn resolve_for(path: &str, use_: anchor::Use) -> Cow<'_, str> {
318    if use_.mutates() {
319        folder::note_named_write();
320    }
321    resolve_placed(path, Some(use_))
322}
323
324/// The cwd after a `cd` whose target cannot be pinned. It looks like a path AND is unpinnable, so
325/// every later relative path resolved against it worst-cases in both gate layers.
326pub(crate) const UNRESOLVED_CWD: &str = "/__SAFE_CHAINS_CMDSUB__";
327
328/// Resolve a `cd` target to a new working directory. `cur` is the current cwd, needed for a
329/// *relative* target. Used by intra-line `cd` tracking (HP-19 #2).
330///
331/// A target that cannot be pinned yields `UNRESOLVED_CWD`, NOT `None`. This used to return `None`
332/// for `~…` and `$VAR`, and the caller reads `None` as "no cd happened" and keeps the previous cwd
333/// — so the `cd` was silently ignored and every later relative path was judged against a workspace
334/// the shell had already left. `cd ~/.aws && cat credentials` and `cd ~/.claude && echo … >
335/// settings.json` both auto-approved that way, the second writing the very file the allowlist
336/// bridge trusts. `None` now means only what the caller can act on: `cd_target` already returned
337/// `None` for "not a cd" (bare `cd`, `cd -`), so reaching here means the shell definitely moved.
338///
339/// `~`/`~/…` are EXPANDED rather than blanket-refused, because they are pinnable — that keeps
340/// `cd ~/.aws && cat credentials` gated as the credential read it is instead of coarsely denying
341/// everything downstream.
342pub fn join_cwd(cur: Option<&str>, target: &str) -> Option<String> {
343    join_cwd_mode(cur, target, false)
344}
345
346pub fn join_cwd_mode(cur: Option<&str>, target: &str, physical: bool) -> Option<String> {
347    let expanded = match expand_home(target) {
348        Some(t) => t,
349        None => return Some(UNRESOLVED_CWD.to_string()), // `~` with no HOME
350    };
351    // Another user's home, a variable, an UNDECLARED substitution: the shell moved somewhere we
352    // cannot name. Fail closed rather than pretend it stayed put.
353    //
354    // A DECLARED substitution (`cd $(pwd)`) is deliberately not in that set. Its sentinel carries a
355    // locus. When that locus is the directory we are already in, the `cd` is identity — appending
356    // the sentinel would invent a child whose tag can later outrank the real directory. A tag that
357    // would move a directory from outside the execute band into it is unresolvable.
358    if names_no_known_directory(&expanded) {
359        return Some(UNRESOLVED_CWD.to_string());
360    }
361    let raw = if let Some(landed) = declared_substitution_directory(cur, &expanded) {
362        landed
363    } else if expanded.starts_with('/') {
364        expanded.into_owned()
365    } else {
366        let c = cur.filter(|c| c.starts_with('/'))?;
367        format!("{c}/{expanded}")
368    };
369    Some(if physical { physical::resolve(&raw, true).unwrap_or_else(|| lexical_join("/", &raw)) } else { lexical_join("/", &raw) })
370}
371
372/// Where `cd` of a declared substitution lands. `None` when `expanded` is not one of those sentinels.
373fn declared_substitution_directory(cur: Option<&str>, expanded: &str) -> Option<String> {
374    use crate::engine::facet::{FacetTerm, LocalLocus};
375    let after = expanded.strip_prefix(crate::cst::eval::TAGGED_PREFIX)?;
376    let (term, tail) = after.split_once("__").unwrap_or(("", ""));
377    let Some(tag) = LocalLocus::from_term(&term.to_lowercase().replace('_', "-")) else {
378        return Some(UNRESOLVED_CWD.to_string());
379    };
380    let Some(cur) = cur.filter(|c| c.starts_with('/') && *c != UNRESOLVED_CWD) else {
381        return Some(UNRESOLVED_CWD.to_string());
382    };
383    let here = crate::engine::resolve::locus::read_locus(cur);
384    if here == tag {
385        let rel = tail.trim_start_matches('/');
386        return Some(if rel.is_empty() { cur.to_string() } else { lexical::lexical_join(cur, rel) });
387    }
388    let in_band = |locus: LocalLocus| locus >= LocalLocus::SandboxScope && locus <= LocalLocus::WorktreeTrusted;
389    if in_band(tag) && !in_band(here) {
390        return Some(UNRESOLVED_CWD.to_string());
391    }
392    let base = match tag {
393        LocalLocus::Temp => "/tmp",
394        _ => return Some(UNRESOLVED_CWD.to_string()),
395    };
396    let rel = tail.trim_start_matches('/');
397    Some(if rel.is_empty() { base.to_string() } else { lexical::lexical_join(base, rel) })
398}
399
400#[cfg(test)]
401mod tests {
402    use super::*;
403
404    #[test]
405    fn an_inherited_ripgrep_config_follows_when_it_says_so_or_cannot_be_read() {
406        let dir = tempfile::tempdir().expect("scratch");
407        let cwd = dir.path().to_str().expect("utf-8");
408        for (name, text) in [
409            ("long", "--follow\n"),
410            ("short", "  -iL\n"),
411            ("plain", "--smart-case\n--max-columns=10\n"),
412            ("glob", "--glob=*L*\n--type-add=L:*.l\n"),
413        ] {
414            std::fs::write(dir.path().join(name), text).expect("config");
415        }
416        let follows = |path: Option<&str>, cwd: Option<&str>| config_file_follows(path.map(Into::into), cwd);
417        assert!(follows(Some("long"), Some(cwd)));
418        assert!(follows(Some("short"), Some(cwd)));
419        assert!(follows(Some("missing"), Some(cwd)));
420        assert!(follows(Some("plain"), None));
421        assert!(!follows(Some("plain"), Some(cwd)));
422        assert!(!follows(Some("glob"), Some(cwd)));
423        assert!(!follows(Some(dir.path().join("plain").to_str().expect("utf-8")), None));
424        assert!(!follows(Some(""), Some(cwd)));
425        assert!(!follows(None, Some(cwd)));
426    }
427
428    const SID: &str = "7676dbc5-a265-43b3-a0f8-49666792bd9b";
429
430    fn with_session<T>(id: Option<&str>, f: impl FnOnce() -> T) -> T {
431        let _g = enter(PathCtx { cwd: Some("/home/u/proj".into()), root: Some("/home/u/proj".into()), session_id: id.map(str::to_string) });
432        f()
433    }
434
435    /// The recognition rule is a SECURITY boundary: matching a path that is not really this
436    /// session's scratchpad would hand `sandbox-scope` (and therefore EXECUTE) to foreign code. So
437    /// enumerate the spoofing class rather than one example — every way a hostile or unrelated path
438    /// could try to look like the scratchpad must fail, and every legitimate spelling must match.
439    #[test]
440    fn only_this_sessions_scratchpad_is_recognized() {
441        let scratch = format!("/private/tmp/claude-501/-Users-u-proj/{SID}/scratchpad");
442        let matching: &[String] = &[
443            format!("{scratch}/build.sh"),
444            format!("{scratch}/nested/deep/gen.py"),
445            scratch.clone(),
446            // layout around the id varies by harness/platform — the id is the anchor, not the shape
447            format!("/tmp/{SID}/x.sh"),
448            format!("/tmp/some-other-harness/{SID}/work/x.sh"),
449            format!("/var/tmp/{SID}/x.sh"),
450        ];
451        let rejected: &[String] = &[
452            // a DIFFERENT session's scratchpad — same layout, wrong id
453            "/private/tmp/claude-501/-Users-u-proj/00000000-1111-2222-3333-444444444444/scratchpad/x.sh".into(),
454            // the id as a SUBSTRING of a component, not a component (the prefix/suffix attack)
455            format!("/tmp/{SID}-evil/x.sh"),
456            format!("/tmp/evil-{SID}/x.sh"),
457            format!("/tmp/a{SID}/x.sh"),
458            // right id, but OUTSIDE any temp root — the id must not bless arbitrary locations
459            format!("/home/u/{SID}/x.sh"),
460            format!("~/.ssh/{SID}/id_rsa"),
461            format!("/etc/{SID}/passwd"),
462            // anonymous temp files carry no id at all
463            "/tmp/evil.sh".into(),
464            "/private/tmp/downloaded.sh".into(),
465            // a case variant, a firmlink spelling, or /var/folders is a different directory on a
466            // case-sensitive volume, so the id there must not become this session's scratchpad
467            format!("/TMP/{SID}/x.sh"),
468            format!("/System/Volumes/Data/tmp/{SID}/x.sh"),
469            format!("/private/var/folders/xx/yy/T/{SID}/x.sh"),
470        ];
471        with_session(Some(SID), || {
472            for p in matching {
473                assert!(in_session_scratchpad(p), "should be recognized: {p}");
474            }
475            for p in rejected {
476                assert!(!in_session_scratchpad(p), "must NOT be recognized: {p}");
477            }
478        });
479    }
480
481    /// Fail closed on every degenerate session id: no harness id, or one too short/odd to be a
482    /// trustworthy anchor, must recognize NOTHING — never widen a path.
483    #[test]
484    fn a_missing_or_unusable_session_id_recognizes_nothing() {
485        let path = format!("/tmp/{SID}/x.sh");
486        with_session(None, || {
487            assert!(!in_session_scratchpad(&path), "no session id → no recognition");
488        });
489        for weak in ["", "abc", "1234567", "..", "/", "a/b", "id with space", "x*y"] {
490            with_session(Some(weak), || {
491                assert!(!in_session_scratchpad(&format!("/tmp/{weak}/x.sh")), "weak id {weak:?} must not anchor recognition",);
492            });
493        }
494    }
495
496    #[test]
497    fn under_temp_never_slices_inside_a_multibyte_character() {
498        let prefix = "/system/volumes/data";
499        for filler in ["\u{fffd}", "\u{e9}", "\u{1f600}"] {
500            for cut in 0..=prefix.len() {
501                let path = format!("{}{filler}{}", &prefix[..cut], &prefix[cut..]);
502                assert!(!under_temp(&path), "{path}");
503            }
504        }
505        assert!(under_temp("/System/Volumes/Data/tmp/x"));
506    }
507
508    #[test]
509    fn under_temp_folds_case_firmlinks_and_var_folders_without_admitting_them() {
510        for path in [
511            "/TMP/y", "/Tmp/y", "/PRIVATE/TMP/y", "/private/TMP/y", "/System/Volumes/Data/tmp/y", "/System/Volumes/Data/private/tmp/y",
512            "/private/var/folders/xx/yy/T/y", "/var/folders/xx/yy/T/y", "/VAR/folders/xx/yy/T/y", "/Var/Folders/xx/yy/T/y",
513        ] {
514            assert!(under_temp(path), "{path}");
515            assert!(crate::engine::resolve::locus::under_temp(path), "locus: {path}");
516            assert!(!under_temp_root(path), "exact prefix must stay strict: {path}");
517        }
518        assert!(under_temp("/tmp/y"));
519        assert!(under_temp_root("/tmp/y"));
520        assert!(!under_temp("/etc/y"));
521        assert!(!under_temp("/tmpfile/y"));
522    }
523
524    #[test]
525    fn no_context_leaves_paths_unchanged() {
526        assert_eq!(resolve("./x"), "./x");
527        assert_eq!(resolve("config"), "config");
528        assert_eq!(resolve("/etc/x"), "/etc/x");
529    }
530
531    #[test]
532    fn relative_inside_the_project_stays_worktree_relative() {
533        let _g = enter(PathCtx { cwd: Some("/home/u/proj/sub".into()), root: Some("/home/u/proj".into()), ..Default::default() });
534        assert_eq!(resolve("x"), "sub/x", "cwd under root → root-relative");
535        assert_eq!(resolve("./y"), "sub/y");
536        assert_eq!(resolve("../z"), "z", ".. that stays inside root");
537    }
538
539    #[test]
540    fn relative_outside_the_project_becomes_absolute() {
541        let _g = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/home/u/proj".into()), ..Default::default() });
542        assert_eq!(resolve("x"), "/etc/x", "cd /etc → the real target");
543        assert_eq!(resolve("passwd"), "/etc/passwd");
544        assert_eq!(resolve("no-such-dir/*"), "/etc/no-such-dir/*");
545    }
546
547    #[test]
548    fn dotdot_escaping_the_project_becomes_absolute() {
549        let _g = enter(PathCtx { cwd: Some("/home/u/proj".into()), root: Some("/home/u/proj".into()), ..Default::default() });
550        assert_eq!(resolve("../../../etc/x"), "/etc/x");
551    }
552
553    #[test]
554    fn absolute_in_root_becomes_root_relative_outside_stays_absolute() {
555        let _g = enter(PathCtx { cwd: Some("/home/u/proj/sub".into()), root: Some("/home/u/proj".into()), ..Default::default() });
556        // absolute INSIDE root → root-relative (worktree), matching the relative spelling
557        assert_eq!(resolve("/home/u/proj/main.rs"), "main.rs");
558        assert_eq!(resolve("/home/u/proj/sub/x"), "sub/x");
559        assert_eq!(resolve("/home/u/proj/a/../b"), "b", "normalized in place");
560        assert_eq!(resolve("/home/u/proj"), ".", "the project root itself");
561        // absolute OUTSIDE root → unchanged (classified as machine)
562        assert_eq!(resolve("/usr/bin/x"), "/usr/bin/x");
563        assert_eq!(resolve("/home/u/proj/../../etc/x"), "/home/etc/x", "climbs to /home, still outside root");
564        assert_eq!(resolve("/home/u/proj/../../../etc/x"), "/etc/x", "escapes to /etc via ..");
565        assert_eq!(
566            resolve("/home/u/proj-evil/secret"),
567            "/home/u/proj-evil/secret",
568            "a sibling dir is not confused for inside by bare string prefix",
569        );
570        // home / unpinnable → returned as-is (the classifiers handle these)
571        assert_eq!(resolve("$HOME/x"), "$HOME/x");
572        assert_eq!(resolve("~/x"), "~/x");
573    }
574
575    #[test]
576    fn a_home_spelled_path_inside_root_becomes_root_relative() {
577        let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
578            return;
579        };
580        let root = format!("{home}/projects/app");
581        let _g = enter(PathCtx { cwd: Some(format!("{root}/sub")), root: Some(root), ..Default::default() });
582        assert_eq!(resolve("~/projects/app/src/main.rs"), "src/main.rs");
583        assert_eq!(resolve("~/projects/app"), ".");
584        assert_eq!(resolve("~/projects/app/"), ".");
585        let under = |rest: &str| format!("~/projects/{rest}");
586        assert_eq!(resolve(&under("app/a/../b")), "b");
587        assert_eq!(resolve(&under("app/.git/hooks/pre-commit")), ".git/hooks/pre-commit");
588        for (outside, why) in [("peer/x", "a sibling"), ("app-evil/x", "no bare string prefix"), ("app/../../.ssh/id_rsa", "an escape")] {
589            assert_eq!(resolve(&under(outside)), under(outside), "{why} stays home-spelled");
590        }
591        assert_eq!(resolve("~/.ssh/id_rsa"), "~/.ssh/id_rsa");
592        assert_eq!(resolve("~"), "~");
593        assert_eq!(resolve("~bob/projects/app/x"), "~bob/projects/app/x", "another user's home is not ours");
594    }
595
596    #[test]
597    fn a_home_spelled_path_needs_an_absolute_root() {
598        let _none = enter(PathCtx { cwd: Some("/w".into()), root: None, ..Default::default() });
599        assert_eq!(resolve("~/x"), "~/x");
600        drop(_none);
601        let _rel = enter(PathCtx { cwd: Some("/w".into()), root: Some("w".into()), ..Default::default() });
602        assert_eq!(resolve("~/x"), "~/x");
603    }
604
605    #[test]
606    fn a_home_rooted_workspace_leaves_home_paths_to_the_home_classifiers() {
607        let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
608            return;
609        };
610        let _g = enter(PathCtx { cwd: Some(home.clone()), root: Some(home.clone()), ..Default::default() });
611        assert_eq!(resolve("~"), "~");
612        assert_eq!(resolve("~/notes.txt"), "~/notes.txt");
613        assert_eq!(resolve("notes.txt"), format!("{home}/notes.txt"));
614        assert_eq!(resolve("."), home);
615    }
616
617    #[test]
618    fn a_home_spelled_path_is_not_resolved_from_outside_the_root_or_through_a_glob() {
619        let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
620            return;
621        };
622        let root = format!("{home}/projects/app");
623        let outside = enter(PathCtx { cwd: Some("/etc".into()), root: Some(root.clone()), ..Default::default() });
624        assert_eq!(resolve("~/projects/app/x"), "~/projects/app/x", "a quoted `~` would name a directory under the cwd");
625        drop(outside);
626        let _g = enter(PathCtx { cwd: Some(root.clone()), root: Some(root), ..Default::default() });
627        for glob in ["app/.ss?/id_rsa", "app/*"].map(|rest| format!("~/projects/{rest}")) {
628            assert_eq!(resolve(&glob), glob);
629        }
630    }
631
632    #[test]
633    fn a_home_spelled_path_is_not_resolved_into_a_protected_root() {
634        let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
635            return;
636        };
637        let root = format!("{home}/.ssh");
638        let _g = enter(PathCtx { cwd: Some(root.clone()), root: Some(root), ..Default::default() });
639        assert_eq!(resolve("~/.ssh/id_rsa"), "~/.ssh/id_rsa");
640    }
641
642    #[test]
643    fn a_root_holding_a_protected_place_keeps_every_path_absolute() {
644        let _g = enter(PathCtx { cwd: Some("/".into()), root: Some("/".into()), ..Default::default() });
645        assert_eq!(resolve("/etc/shadow"), "/etc/shadow");
646        assert_eq!(resolve("etc/sudoers"), "/etc/sudoers");
647        assert_eq!(resolve("etc"), "/etc");
648        assert_eq!(resolve("/srv/app/x"), "/srv/app/x");
649        assert_eq!(resolve("."), "/");
650        drop(_g);
651        let _etc = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/etc".into()), ..Default::default() });
652        assert_eq!(resolve("hosts"), "hosts", "an unprotected file in a root below every home is the worktree");
653        assert_eq!(resolve("sudoers"), "/etc/sudoers");
654        assert_eq!(resolve("."), "/etc", "the root itself is above a protected place");
655        drop(_etc);
656        let _inside = enter(PathCtx { cwd: Some("/root/app".into()), root: Some("/root/app".into()), ..Default::default() });
657        assert_eq!(resolve("/root/app/x"), "x", "a root inside the protected place is where the user works");
658    }
659
660    #[test]
661    fn loop_var_expands_to_its_representative_per_face() {
662        let _g = enter_loop_var("f".into(), "read_item".into(), "write_item".into());
663        assert_eq!(expand_vars("$f", false), "read_item");
664        assert_eq!(expand_vars("$f", true), "write_item");
665        assert_eq!(expand_vars("${f}", false), "read_item");
666        assert_eq!(expand_vars("$f.bak", false), "read_item.bak", "compound suffix");
667        assert_eq!(expand_vars("pre/$f", false), "pre/read_item");
668        assert_eq!(expand_vars("$foo", false), "$foo", "$foo is not $f");
669        assert_eq!(expand_vars("$g", false), "$g", "unbound var untouched");
670        assert_eq!(expand_vars("plain", false), "plain");
671    }
672
673    #[test]
674    fn loop_var_binding_is_scoped_and_nests() {
675        assert_eq!(expand_vars("$f", false), "$f", "no binding");
676        {
677            let _outer = enter_loop_var("f".into(), "outer".into(), "outer".into());
678            {
679                let _inner = enter_loop_var("f".into(), "inner".into(), "inner".into());
680                assert_eq!(expand_vars("$f", false), "inner", "innermost wins");
681            }
682            assert_eq!(expand_vars("$f", false), "outer", "inner popped on drop");
683        }
684        assert_eq!(expand_vars("$f", false), "$f", "all popped");
685    }
686
687    #[test]
688    fn the_guard_restores_on_drop() {
689        {
690            let _g = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/r".into()), ..Default::default() });
691            assert_eq!(resolve("x"), "/etc/x");
692        }
693        assert_eq!(resolve("x"), "x", "context cleared after the guard drops");
694    }
695
696    const PROBE_VAR: &str = "SAFE_CHAINS_TMPDIR_PROBE_PATH";
697
698    fn tmpdir_verdict(tmpdir: &str, path: &str) -> bool {
699        let out = std::process::Command::new(std::env::current_exe().expect("test exe"))
700            .args(["--exact", "pathctx::tests::tmpdir_probe", "--nocapture", "--test-threads=1"])
701            .env("TMPDIR", tmpdir)
702            .env(PROBE_VAR, path)
703            .output()
704            .expect("spawn probe");
705        let stdout = String::from_utf8_lossy(&out.stdout);
706        assert!(out.status.success(), "probe failed for TMPDIR={tmpdir:?} path={path:?}: {stdout}");
707        match (stdout.contains("PROBE_VERDICT=true"), stdout.contains("PROBE_VERDICT=false")) {
708            (true, false) => true,
709            (false, true) => false,
710            _ => panic!("probe did not run for TMPDIR={tmpdir:?} path={path:?}: {stdout}"),
711        }
712    }
713
714    #[test]
715    fn tmpdir_probe() {
716        let Ok(path) = std::env::var(PROBE_VAR) else {
717            return;
718        };
719        println!("PROBE_VERDICT={}", under_temp_root(&path));
720    }
721
722    #[test]
723    fn a_tmpdir_root_counts_only_when_absolute_and_non_empty() {
724        for (tmpdir, path, expected) in [
725            ("/work/scratch", "/work/scratch/x.sh", true),
726            ("/work/scratch/", "/work/scratch/x.sh", true),
727            ("/work/scratch//", "/work/scratch/nested/x.sh", true),
728            ("/work/scratch", "/work/scratch", false),
729            ("/work/scratch", "/work/scratchy/x.sh", false),
730            ("/work/scratch", "/work/other/x.sh", false),
731            ("/work/scratch", "work/scratch/x.sh", false),
732            ("", "/x.sh", false),
733            ("", "/", false),
734            ("/", "/x.sh", false),
735            ("//", "/x.sh", false),
736            ("scratch", "scratch/x.sh", false),
737            ("scratch/", "scratch/x.sh", false),
738            ("./scratch", "./scratch/x.sh", false),
739            ("$SCRATCH", "$SCRATCH/x.sh", false),
740            ("relative/dir", "relative/dir/x.sh", false),
741        ] {
742            assert_eq!(tmpdir_verdict(tmpdir, path), expected, "TMPDIR={tmpdir:?} path={path:?}");
743        }
744    }
745
746    #[test]
747    fn the_fixed_temp_roots_hold_whatever_tmpdir_says() {
748        for tmpdir in ["", "scratch", "/work/scratch"] {
749            for path in ["/tmp/x", "/private/tmp/x", "/var/tmp/x", "/private/var/tmp/x"] {
750                assert!(tmpdir_verdict(tmpdir, path), "TMPDIR={tmpdir:?} path={path:?}");
751            }
752            assert!(!tmpdir_verdict(tmpdir, "/tmp"), "the bare root is not under itself");
753        }
754    }
755}