1use std::borrow::Cow;
17use std::cell::RefCell;
18
19pub mod anchor;
20pub mod folder;
21pub(crate) use folder::judging;
22mod home;
23pub mod item_shape;
24mod lexical;
25mod vars;
26use home::home_path_inside_root;
27pub use item_shape::{Binding, Facts, ItemShape, ItemShapeGuard, binding, enter_loop_shape, enter_stdin_shape, loop_shape, stdin_shape};
28use lexical::{expand_home, express_relative_to_root, lexical_join, names_no_known_directory};
29pub use vars::{LoopGuard, VarGuard, enter_loop_var, enter_var, expand_vars, names_a_loop_var};
30
31#[derive(Clone, Default)]
35pub struct PathCtx {
36 pub cwd: Option<String>,
37 pub root: Option<String>,
38 pub session_id: Option<String>,
41}
42
43thread_local! {
44 static CURRENT: RefCell<PathCtx> = RefCell::new(PathCtx::default());
45}
46
47#[must_use]
50pub fn enter(ctx: PathCtx) -> Guard {
51 Guard(CURRENT.with(|c| c.replace(ctx)))
52}
53
54pub struct Guard(PathCtx);
56
57impl Drop for Guard {
58 fn drop(&mut self) {
59 CURRENT.with(|c| *c.borrow_mut() = std::mem::take(&mut self.0));
60 }
61}
62
63#[must_use]
66pub fn enter_cwd(cwd: Option<String>) -> Guard {
67 Guard(CURRENT.with(|c| {
68 let mut b = c.borrow_mut();
69 PathCtx { cwd: std::mem::replace(&mut b.cwd, cwd), root: b.root.clone(), session_id: b.session_id.clone() }
72 }))
73}
74
75pub fn cwd() -> Option<String> {
77 CURRENT.with(|c| c.borrow().cwd.clone())
78}
79
80pub fn root() -> Option<String> {
83 CURRENT.with(|c| {
84 let b = c.borrow();
85 b.root.clone().or_else(|| b.cwd.clone())
86 })
87}
88
89pub fn in_session_scratchpad(path: &str) -> bool {
110 let Some(id) = CURRENT.with(|c| c.borrow().session_id.clone()) else {
111 return false;
112 };
113 if id.len() < 8 || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
116 return false;
117 }
118 if !under_temp_root(path) {
119 return false;
120 }
121 path.split('/').any(|seg| seg == id)
122}
123
124pub fn under_temp_root(path: &str) -> bool {
127 const ROOTS: &[&str] = &["/tmp/", "/private/tmp/", "/var/tmp/", "/private/var/tmp/"];
128 if ROOTS.iter().any(|r| path.starts_with(r)) {
129 return true;
130 }
131 std::env::var("TMPDIR").ok().is_some_and(|t| {
132 let t = t.trim_end_matches('/');
133 !t.is_empty() && t.starts_with('/') && path.starts_with(&format!("{t}/"))
134 })
135}
136
137thread_local! {
138 static STDIN_REPR: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
139}
140
141#[must_use]
146pub fn enter_stdin_repr(repr: String) -> StdinReprGuard {
147 STDIN_REPR.with(|v| v.borrow_mut().push(repr));
148 StdinReprGuard
149}
150
151pub fn stdin_item_repr() -> Option<String> {
154 STDIN_REPR.with(|v| v.borrow().last().cloned())
155}
156
157pub struct StdinReprGuard;
158
159impl Drop for StdinReprGuard {
160 fn drop(&mut self) {
161 STDIN_REPR.with(|v| {
162 v.borrow_mut().pop();
163 });
164 }
165}
166
167pub fn resolve(path: &str) -> Cow<'_, str> {
179 resolve_placed(path, None)
180}
181
182pub fn resolve_for(path: &str, use_: anchor::Use) -> Cow<'_, str> {
185 if use_.mutates() {
186 folder::note_named_write();
187 }
188 resolve_placed(path, Some(use_))
189}
190
191fn resolve_placed(path: &str, use_: Option<anchor::Use>) -> Cow<'_, str> {
192 if path.is_empty() || path.contains('$') {
193 return Cow::Borrowed(path);
194 }
195 if path.starts_with('~') {
196 return home_path_inside_root(path).map_or(Cow::Borrowed(path), Cow::Owned);
197 }
198 let resolved = CURRENT.with(|c| {
199 let ctx = c.borrow();
200 match (ctx.cwd.as_deref(), ctx.root.as_deref()) {
201 (Some(cwd), Some(root)) if cwd.starts_with('/') && root.starts_with('/') => {
202 let abs = if path.starts_with('/') {
205 lexical_join("/", path)
206 } else {
207 folder::place(cwd, path, use_).map_or_else(|| lexical_join(cwd, path), |placed| lexical_join(root, &placed))
208 };
209 Some(express_relative_to_root(&abs, root))
210 }
211 _ => None,
212 }
213 });
214 resolved.map_or(Cow::Borrowed(path), Cow::Owned)
215}
216
217pub(crate) const UNRESOLVED_CWD: &str = "/__SAFE_CHAINS_CMDSUB__";
220
221pub fn join_cwd(cur: Option<&str>, target: &str) -> Option<String> {
236 let expanded = match expand_home(target) {
237 Some(t) => t,
238 None => return Some(UNRESOLVED_CWD.to_string()), };
240 if names_no_known_directory(&expanded) {
248 return Some(UNRESOLVED_CWD.to_string());
249 }
250 if expanded.starts_with('/') {
251 return Some(lexical_join("/", &expanded)); }
253 cur.filter(|c| c.starts_with('/')).map(|c| lexical_join(c, &expanded))
257}
258
259#[cfg(test)]
260mod tests {
261 use super::*;
262
263 const SID: &str = "7676dbc5-a265-43b3-a0f8-49666792bd9b";
264
265 fn with_session<T>(id: Option<&str>, f: impl FnOnce() -> T) -> T {
266 let _g = enter(PathCtx { cwd: Some("/home/u/proj".into()), root: Some("/home/u/proj".into()), session_id: id.map(str::to_string) });
267 f()
268 }
269
270 #[test]
275 fn only_this_sessions_scratchpad_is_recognized() {
276 let scratch = format!("/private/tmp/claude-501/-Users-u-proj/{SID}/scratchpad");
277 let matching: &[String] = &[
278 format!("{scratch}/build.sh"),
279 format!("{scratch}/nested/deep/gen.py"),
280 scratch.clone(),
281 format!("/tmp/{SID}/x.sh"),
283 format!("/tmp/some-other-harness/{SID}/work/x.sh"),
284 format!("/var/tmp/{SID}/x.sh"),
285 ];
286 let rejected: &[String] = &[
287 "/private/tmp/claude-501/-Users-u-proj/00000000-1111-2222-3333-444444444444/scratchpad/x.sh".into(),
289 format!("/tmp/{SID}-evil/x.sh"),
291 format!("/tmp/evil-{SID}/x.sh"),
292 format!("/tmp/a{SID}/x.sh"),
293 format!("/home/u/{SID}/x.sh"),
295 format!("~/.ssh/{SID}/id_rsa"),
296 format!("/etc/{SID}/passwd"),
297 "/tmp/evil.sh".into(),
299 "/private/tmp/downloaded.sh".into(),
300 ];
301 with_session(Some(SID), || {
302 for p in matching {
303 assert!(in_session_scratchpad(p), "should be recognized: {p}");
304 }
305 for p in rejected {
306 assert!(!in_session_scratchpad(p), "must NOT be recognized: {p}");
307 }
308 });
309 }
310
311 #[test]
314 fn a_missing_or_unusable_session_id_recognizes_nothing() {
315 let path = format!("/tmp/{SID}/x.sh");
316 with_session(None, || {
317 assert!(!in_session_scratchpad(&path), "no session id → no recognition");
318 });
319 for weak in ["", "abc", "1234567", "..", "/", "a/b", "id with space", "x*y"] {
320 with_session(Some(weak), || {
321 assert!(!in_session_scratchpad(&format!("/tmp/{weak}/x.sh")), "weak id {weak:?} must not anchor recognition",);
322 });
323 }
324 }
325
326 #[test]
327 fn no_context_leaves_paths_unchanged() {
328 assert_eq!(resolve("./x"), "./x");
329 assert_eq!(resolve("config"), "config");
330 assert_eq!(resolve("/etc/x"), "/etc/x");
331 }
332
333 #[test]
334 fn relative_inside_the_project_stays_worktree_relative() {
335 let _g = enter(PathCtx { cwd: Some("/home/u/proj/sub".into()), root: Some("/home/u/proj".into()), ..Default::default() });
336 assert_eq!(resolve("x"), "sub/x", "cwd under root → root-relative");
337 assert_eq!(resolve("./y"), "sub/y");
338 assert_eq!(resolve("../z"), "z", ".. that stays inside root");
339 }
340
341 #[test]
342 fn relative_outside_the_project_becomes_absolute() {
343 let _g = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/home/u/proj".into()), ..Default::default() });
344 assert_eq!(resolve("x"), "/etc/x", "cd /etc → the real target");
345 assert_eq!(resolve("passwd"), "/etc/passwd");
346 assert_eq!(resolve("*"), "/etc/*");
347 }
348
349 #[test]
350 fn dotdot_escaping_the_project_becomes_absolute() {
351 let _g = enter(PathCtx { cwd: Some("/home/u/proj".into()), root: Some("/home/u/proj".into()), ..Default::default() });
352 assert_eq!(resolve("../../../etc/x"), "/etc/x");
353 }
354
355 #[test]
356 fn absolute_in_root_becomes_root_relative_outside_stays_absolute() {
357 let _g = enter(PathCtx { cwd: Some("/home/u/proj/sub".into()), root: Some("/home/u/proj".into()), ..Default::default() });
358 assert_eq!(resolve("/home/u/proj/main.rs"), "main.rs");
360 assert_eq!(resolve("/home/u/proj/sub/x"), "sub/x");
361 assert_eq!(resolve("/home/u/proj/a/../b"), "b", "normalized in place");
362 assert_eq!(resolve("/home/u/proj"), ".", "the project root itself");
363 assert_eq!(resolve("/usr/bin/x"), "/usr/bin/x");
365 assert_eq!(resolve("/home/u/proj/../../etc/x"), "/home/etc/x", "climbs to /home, still outside root");
366 assert_eq!(resolve("/home/u/proj/../../../etc/x"), "/etc/x", "escapes to /etc via ..");
367 assert_eq!(
368 resolve("/home/u/proj-evil/secret"),
369 "/home/u/proj-evil/secret",
370 "a sibling dir is not confused for inside by bare string prefix",
371 );
372 assert_eq!(resolve("$HOME/x"), "$HOME/x");
374 assert_eq!(resolve("~/x"), "~/x");
375 }
376
377 #[test]
378 fn a_home_spelled_path_inside_root_becomes_root_relative() {
379 let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
380 return;
381 };
382 let root = format!("{home}/projects/app");
383 let _g = enter(PathCtx { cwd: Some(format!("{root}/sub")), root: Some(root), ..Default::default() });
384 assert_eq!(resolve("~/projects/app/src/main.rs"), "src/main.rs");
385 assert_eq!(resolve("~/projects/app"), ".");
386 assert_eq!(resolve("~/projects/app/"), ".");
387 let under = |rest: &str| format!("~/projects/{rest}");
388 assert_eq!(resolve(&under("app/a/../b")), "b");
389 assert_eq!(resolve(&under("app/.git/hooks/pre-commit")), ".git/hooks/pre-commit");
390 for (outside, why) in [("peer/x", "a sibling"), ("app-evil/x", "no bare string prefix"), ("app/../../.ssh/id_rsa", "an escape")] {
391 assert_eq!(resolve(&under(outside)), under(outside), "{why} stays home-spelled");
392 }
393 assert_eq!(resolve("~/.ssh/id_rsa"), "~/.ssh/id_rsa");
394 assert_eq!(resolve("~"), "~");
395 assert_eq!(resolve("~bob/projects/app/x"), "~bob/projects/app/x", "another user's home is not ours");
396 }
397
398 #[test]
399 fn a_home_spelled_path_needs_an_absolute_root() {
400 let _none = enter(PathCtx { cwd: Some("/w".into()), root: None, ..Default::default() });
401 assert_eq!(resolve("~/x"), "~/x");
402 drop(_none);
403 let _rel = enter(PathCtx { cwd: Some("/w".into()), root: Some("w".into()), ..Default::default() });
404 assert_eq!(resolve("~/x"), "~/x");
405 }
406
407 #[test]
408 fn a_home_rooted_workspace_leaves_home_paths_to_the_home_classifiers() {
409 let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
410 return;
411 };
412 let _g = enter(PathCtx { cwd: Some(home.clone()), root: Some(home.clone()), ..Default::default() });
413 assert_eq!(resolve("~"), "~");
414 assert_eq!(resolve("~/notes.txt"), "~/notes.txt");
415 assert_eq!(resolve("notes.txt"), format!("{home}/notes.txt"));
416 assert_eq!(resolve("."), home);
417 }
418
419 #[test]
420 fn a_home_spelled_path_is_not_resolved_from_outside_the_root_or_through_a_glob() {
421 let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
422 return;
423 };
424 let root = format!("{home}/projects/app");
425 let outside = enter(PathCtx { cwd: Some("/etc".into()), root: Some(root.clone()), ..Default::default() });
426 assert_eq!(resolve("~/projects/app/x"), "~/projects/app/x", "a quoted `~` would name a directory under the cwd");
427 drop(outside);
428 let _g = enter(PathCtx { cwd: Some(root.clone()), root: Some(root), ..Default::default() });
429 for glob in ["app/.ss?/id_rsa", "app/*"].map(|rest| format!("~/projects/{rest}")) {
430 assert_eq!(resolve(&glob), glob);
431 }
432 }
433
434 #[test]
435 fn a_home_spelled_path_is_not_resolved_into_a_protected_root() {
436 let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
437 return;
438 };
439 let root = format!("{home}/.ssh");
440 let _g = enter(PathCtx { cwd: Some(root.clone()), root: Some(root), ..Default::default() });
441 assert_eq!(resolve("~/.ssh/id_rsa"), "~/.ssh/id_rsa");
442 }
443
444 #[test]
445 fn a_root_holding_a_protected_place_keeps_every_path_absolute() {
446 let _g = enter(PathCtx { cwd: Some("/".into()), root: Some("/".into()), ..Default::default() });
447 assert_eq!(resolve("/etc/shadow"), "/etc/shadow");
448 assert_eq!(resolve("etc/sudoers"), "/etc/sudoers");
449 assert_eq!(resolve("etc"), "/etc");
450 assert_eq!(resolve("/srv/app/x"), "/srv/app/x");
451 assert_eq!(resolve("."), "/");
452 drop(_g);
453 let _etc = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/etc".into()), ..Default::default() });
454 assert_eq!(resolve("hosts"), "hosts", "an unprotected file in a root below every home is the worktree");
455 assert_eq!(resolve("sudoers"), "/etc/sudoers");
456 assert_eq!(resolve("."), "/etc", "the root itself is above a protected place");
457 drop(_etc);
458 let _inside = enter(PathCtx { cwd: Some("/root/app".into()), root: Some("/root/app".into()), ..Default::default() });
459 assert_eq!(resolve("/root/app/x"), "x", "a root inside the protected place is where the user works");
460 }
461
462 #[test]
463 fn loop_var_expands_to_its_representative_per_face() {
464 let _g = enter_loop_var("f".into(), "read_item".into(), "write_item".into());
465 assert_eq!(expand_vars("$f", false), "read_item");
466 assert_eq!(expand_vars("$f", true), "write_item");
467 assert_eq!(expand_vars("${f}", false), "read_item");
468 assert_eq!(expand_vars("$f.bak", false), "read_item.bak", "compound suffix");
469 assert_eq!(expand_vars("pre/$f", false), "pre/read_item");
470 assert_eq!(expand_vars("$foo", false), "$foo", "$foo is not $f");
471 assert_eq!(expand_vars("$g", false), "$g", "unbound var untouched");
472 assert_eq!(expand_vars("plain", false), "plain");
473 }
474
475 #[test]
476 fn loop_var_binding_is_scoped_and_nests() {
477 assert_eq!(expand_vars("$f", false), "$f", "no binding");
478 {
479 let _outer = enter_loop_var("f".into(), "outer".into(), "outer".into());
480 {
481 let _inner = enter_loop_var("f".into(), "inner".into(), "inner".into());
482 assert_eq!(expand_vars("$f", false), "inner", "innermost wins");
483 }
484 assert_eq!(expand_vars("$f", false), "outer", "inner popped on drop");
485 }
486 assert_eq!(expand_vars("$f", false), "$f", "all popped");
487 }
488
489 #[test]
490 fn the_guard_restores_on_drop() {
491 {
492 let _g = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/r".into()), ..Default::default() });
493 assert_eq!(resolve("x"), "/etc/x");
494 }
495 assert_eq!(resolve("x"), "x", "context cleared after the guard drops");
496 }
497
498 const PROBE_VAR: &str = "SAFE_CHAINS_TMPDIR_PROBE_PATH";
499
500 fn tmpdir_verdict(tmpdir: &str, path: &str) -> bool {
501 let out = std::process::Command::new(std::env::current_exe().expect("test exe"))
502 .args(["--exact", "pathctx::tests::tmpdir_probe", "--nocapture", "--test-threads=1"])
503 .env("TMPDIR", tmpdir)
504 .env(PROBE_VAR, path)
505 .output()
506 .expect("spawn probe");
507 let stdout = String::from_utf8_lossy(&out.stdout);
508 assert!(out.status.success(), "probe failed for TMPDIR={tmpdir:?} path={path:?}: {stdout}");
509 match (stdout.contains("PROBE_VERDICT=true"), stdout.contains("PROBE_VERDICT=false")) {
510 (true, false) => true,
511 (false, true) => false,
512 _ => panic!("probe did not run for TMPDIR={tmpdir:?} path={path:?}: {stdout}"),
513 }
514 }
515
516 #[test]
517 fn tmpdir_probe() {
518 let Ok(path) = std::env::var(PROBE_VAR) else {
519 return;
520 };
521 println!("PROBE_VERDICT={}", under_temp_root(&path));
522 }
523
524 #[test]
525 fn a_tmpdir_root_counts_only_when_absolute_and_non_empty() {
526 for (tmpdir, path, expected) in [
527 ("/work/scratch", "/work/scratch/x.sh", true),
528 ("/work/scratch/", "/work/scratch/x.sh", true),
529 ("/work/scratch//", "/work/scratch/nested/x.sh", true),
530 ("/work/scratch", "/work/scratch", false),
531 ("/work/scratch", "/work/scratchy/x.sh", false),
532 ("/work/scratch", "/work/other/x.sh", false),
533 ("/work/scratch", "work/scratch/x.sh", false),
534 ("", "/x.sh", false),
535 ("", "/", false),
536 ("/", "/x.sh", false),
537 ("//", "/x.sh", false),
538 ("scratch", "scratch/x.sh", false),
539 ("scratch/", "scratch/x.sh", false),
540 ("./scratch", "./scratch/x.sh", false),
541 ("$SCRATCH", "$SCRATCH/x.sh", false),
542 ("relative/dir", "relative/dir/x.sh", false),
543 ] {
544 assert_eq!(tmpdir_verdict(tmpdir, path), expected, "TMPDIR={tmpdir:?} path={path:?}");
545 }
546 }
547
548 #[test]
549 fn the_fixed_temp_roots_hold_whatever_tmpdir_says() {
550 for tmpdir in ["", "scratch", "/work/scratch"] {
551 for path in ["/tmp/x", "/private/tmp/x", "/var/tmp/x", "/private/var/tmp/x"] {
552 assert!(tmpdir_verdict(tmpdir, path), "TMPDIR={tmpdir:?} path={path:?}");
553 }
554 assert!(!tmpdir_verdict(tmpdir, "/tmp"), "the bare root is not under itself");
555 }
556 }
557}