Skip to main content

safe_chains/
pathctx.rs

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