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 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#[derive(Clone, Default)]
38pub struct PathCtx {
39 pub cwd: Option<String>,
40 pub root: Option<String>,
41 pub session_id: Option<String>,
44}
45
46thread_local! {
47 static CURRENT: RefCell<PathCtx> = RefCell::new(PathCtx::default());
48}
49
50#[must_use]
53pub fn enter(ctx: PathCtx) -> Guard {
54 Guard(CURRENT.with(|c| c.replace(ctx)))
55}
56
57pub 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#[must_use]
69pub fn enter_cwd(cwd: Option<String>) -> Guard {
70 Guard(CURRENT.with(|c| {
71 let mut b = c.borrow_mut();
72 PathCtx { cwd: std::mem::replace(&mut b.cwd, cwd), root: b.root.clone(), session_id: b.session_id.clone() }
75 }))
76}
77
78pub fn cwd() -> Option<String> {
80 CURRENT.with(|c| c.borrow().cwd.clone())
81}
82
83pub 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
92pub 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 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
127pub fn under_temp_root(path: &str) -> bool {
130 const ROOTS: &[&str] = &["/tmp/", "/private/tmp/", "/var/tmp/", "/private/var/tmp/"];
131 if ROOTS.iter().any(|r| path.starts_with(r)) {
132 return true;
133 }
134 std::env::var("TMPDIR").ok().is_some_and(|t| {
135 let t = t.trim_end_matches('/');
136 !t.is_empty() && t.starts_with('/') && path.starts_with(&format!("{t}/"))
137 })
138}
139
140thread_local! {
141 static STDIN_REPR: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
142}
143
144#[must_use]
149pub fn enter_stdin_repr(repr: String) -> StdinReprGuard {
150 STDIN_REPR.with(|v| v.borrow_mut().push(repr));
151 StdinReprGuard
152}
153
154pub fn stdin_item_repr() -> Option<String> {
157 STDIN_REPR.with(|v| v.borrow().last().cloned())
158}
159
160pub struct StdinReprGuard;
161
162impl Drop for StdinReprGuard {
163 fn drop(&mut self) {
164 STDIN_REPR.with(|v| {
165 v.borrow_mut().pop();
166 });
167 }
168}
169
170pub fn resolve(path: &str) -> Cow<'_, str> {
182 resolve_placed(path, None)
183}
184
185pub fn resolve_for(path: &str, use_: anchor::Use) -> Cow<'_, str> {
188 if use_.mutates() {
189 folder::note_named_write();
190 }
191 resolve_placed(path, Some(use_))
192}
193
194pub(crate) const UNRESOLVED_CWD: &str = "/__SAFE_CHAINS_CMDSUB__";
197
198pub fn join_cwd(cur: Option<&str>, target: &str) -> Option<String> {
213 join_cwd_mode(cur, target, false)
214}
215
216pub fn join_cwd_mode(cur: Option<&str>, target: &str, physical: bool) -> Option<String> {
217 let expanded = match expand_home(target) {
218 Some(t) => t,
219 None => return Some(UNRESOLVED_CWD.to_string()), };
221 if names_no_known_directory(&expanded) {
229 return Some(UNRESOLVED_CWD.to_string());
230 }
231 let raw = if expanded.starts_with('/') {
232 expanded.into_owned()
233 } else {
234 let c = cur.filter(|c| c.starts_with('/'))?;
235 format!("{c}/{expanded}")
236 };
237 Some(if physical { physical::resolve(&raw, true).unwrap_or_else(|| lexical_join("/", &raw)) } else { lexical_join("/", &raw) })
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243
244 const SID: &str = "7676dbc5-a265-43b3-a0f8-49666792bd9b";
245
246 fn with_session<T>(id: Option<&str>, f: impl FnOnce() -> T) -> T {
247 let _g = enter(PathCtx { cwd: Some("/home/u/proj".into()), root: Some("/home/u/proj".into()), session_id: id.map(str::to_string) });
248 f()
249 }
250
251 #[test]
256 fn only_this_sessions_scratchpad_is_recognized() {
257 let scratch = format!("/private/tmp/claude-501/-Users-u-proj/{SID}/scratchpad");
258 let matching: &[String] = &[
259 format!("{scratch}/build.sh"),
260 format!("{scratch}/nested/deep/gen.py"),
261 scratch.clone(),
262 format!("/tmp/{SID}/x.sh"),
264 format!("/tmp/some-other-harness/{SID}/work/x.sh"),
265 format!("/var/tmp/{SID}/x.sh"),
266 ];
267 let rejected: &[String] = &[
268 "/private/tmp/claude-501/-Users-u-proj/00000000-1111-2222-3333-444444444444/scratchpad/x.sh".into(),
270 format!("/tmp/{SID}-evil/x.sh"),
272 format!("/tmp/evil-{SID}/x.sh"),
273 format!("/tmp/a{SID}/x.sh"),
274 format!("/home/u/{SID}/x.sh"),
276 format!("~/.ssh/{SID}/id_rsa"),
277 format!("/etc/{SID}/passwd"),
278 "/tmp/evil.sh".into(),
280 "/private/tmp/downloaded.sh".into(),
281 ];
282 with_session(Some(SID), || {
283 for p in matching {
284 assert!(in_session_scratchpad(p), "should be recognized: {p}");
285 }
286 for p in rejected {
287 assert!(!in_session_scratchpad(p), "must NOT be recognized: {p}");
288 }
289 });
290 }
291
292 #[test]
295 fn a_missing_or_unusable_session_id_recognizes_nothing() {
296 let path = format!("/tmp/{SID}/x.sh");
297 with_session(None, || {
298 assert!(!in_session_scratchpad(&path), "no session id → no recognition");
299 });
300 for weak in ["", "abc", "1234567", "..", "/", "a/b", "id with space", "x*y"] {
301 with_session(Some(weak), || {
302 assert!(!in_session_scratchpad(&format!("/tmp/{weak}/x.sh")), "weak id {weak:?} must not anchor recognition",);
303 });
304 }
305 }
306
307 #[test]
308 fn no_context_leaves_paths_unchanged() {
309 assert_eq!(resolve("./x"), "./x");
310 assert_eq!(resolve("config"), "config");
311 assert_eq!(resolve("/etc/x"), "/etc/x");
312 }
313
314 #[test]
315 fn relative_inside_the_project_stays_worktree_relative() {
316 let _g = enter(PathCtx { cwd: Some("/home/u/proj/sub".into()), root: Some("/home/u/proj".into()), ..Default::default() });
317 assert_eq!(resolve("x"), "sub/x", "cwd under root → root-relative");
318 assert_eq!(resolve("./y"), "sub/y");
319 assert_eq!(resolve("../z"), "z", ".. that stays inside root");
320 }
321
322 #[test]
323 fn relative_outside_the_project_becomes_absolute() {
324 let _g = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/home/u/proj".into()), ..Default::default() });
325 assert_eq!(resolve("x"), "/etc/x", "cd /etc → the real target");
326 assert_eq!(resolve("passwd"), "/etc/passwd");
327 assert_eq!(resolve("no-such-dir/*"), "/etc/no-such-dir/*");
328 }
329
330 #[test]
331 fn dotdot_escaping_the_project_becomes_absolute() {
332 let _g = enter(PathCtx { cwd: Some("/home/u/proj".into()), root: Some("/home/u/proj".into()), ..Default::default() });
333 assert_eq!(resolve("../../../etc/x"), "/etc/x");
334 }
335
336 #[test]
337 fn absolute_in_root_becomes_root_relative_outside_stays_absolute() {
338 let _g = enter(PathCtx { cwd: Some("/home/u/proj/sub".into()), root: Some("/home/u/proj".into()), ..Default::default() });
339 assert_eq!(resolve("/home/u/proj/main.rs"), "main.rs");
341 assert_eq!(resolve("/home/u/proj/sub/x"), "sub/x");
342 assert_eq!(resolve("/home/u/proj/a/../b"), "b", "normalized in place");
343 assert_eq!(resolve("/home/u/proj"), ".", "the project root itself");
344 assert_eq!(resolve("/usr/bin/x"), "/usr/bin/x");
346 assert_eq!(resolve("/home/u/proj/../../etc/x"), "/home/etc/x", "climbs to /home, still outside root");
347 assert_eq!(resolve("/home/u/proj/../../../etc/x"), "/etc/x", "escapes to /etc via ..");
348 assert_eq!(
349 resolve("/home/u/proj-evil/secret"),
350 "/home/u/proj-evil/secret",
351 "a sibling dir is not confused for inside by bare string prefix",
352 );
353 assert_eq!(resolve("$HOME/x"), "$HOME/x");
355 assert_eq!(resolve("~/x"), "~/x");
356 }
357
358 #[test]
359 fn a_home_spelled_path_inside_root_becomes_root_relative() {
360 let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
361 return;
362 };
363 let root = format!("{home}/projects/app");
364 let _g = enter(PathCtx { cwd: Some(format!("{root}/sub")), root: Some(root), ..Default::default() });
365 assert_eq!(resolve("~/projects/app/src/main.rs"), "src/main.rs");
366 assert_eq!(resolve("~/projects/app"), ".");
367 assert_eq!(resolve("~/projects/app/"), ".");
368 let under = |rest: &str| format!("~/projects/{rest}");
369 assert_eq!(resolve(&under("app/a/../b")), "b");
370 assert_eq!(resolve(&under("app/.git/hooks/pre-commit")), ".git/hooks/pre-commit");
371 for (outside, why) in [("peer/x", "a sibling"), ("app-evil/x", "no bare string prefix"), ("app/../../.ssh/id_rsa", "an escape")] {
372 assert_eq!(resolve(&under(outside)), under(outside), "{why} stays home-spelled");
373 }
374 assert_eq!(resolve("~/.ssh/id_rsa"), "~/.ssh/id_rsa");
375 assert_eq!(resolve("~"), "~");
376 assert_eq!(resolve("~bob/projects/app/x"), "~bob/projects/app/x", "another user's home is not ours");
377 }
378
379 #[test]
380 fn a_home_spelled_path_needs_an_absolute_root() {
381 let _none = enter(PathCtx { cwd: Some("/w".into()), root: None, ..Default::default() });
382 assert_eq!(resolve("~/x"), "~/x");
383 drop(_none);
384 let _rel = enter(PathCtx { cwd: Some("/w".into()), root: Some("w".into()), ..Default::default() });
385 assert_eq!(resolve("~/x"), "~/x");
386 }
387
388 #[test]
389 fn a_home_rooted_workspace_leaves_home_paths_to_the_home_classifiers() {
390 let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
391 return;
392 };
393 let _g = enter(PathCtx { cwd: Some(home.clone()), root: Some(home.clone()), ..Default::default() });
394 assert_eq!(resolve("~"), "~");
395 assert_eq!(resolve("~/notes.txt"), "~/notes.txt");
396 assert_eq!(resolve("notes.txt"), format!("{home}/notes.txt"));
397 assert_eq!(resolve("."), home);
398 }
399
400 #[test]
401 fn a_home_spelled_path_is_not_resolved_from_outside_the_root_or_through_a_glob() {
402 let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
403 return;
404 };
405 let root = format!("{home}/projects/app");
406 let outside = enter(PathCtx { cwd: Some("/etc".into()), root: Some(root.clone()), ..Default::default() });
407 assert_eq!(resolve("~/projects/app/x"), "~/projects/app/x", "a quoted `~` would name a directory under the cwd");
408 drop(outside);
409 let _g = enter(PathCtx { cwd: Some(root.clone()), root: Some(root), ..Default::default() });
410 for glob in ["app/.ss?/id_rsa", "app/*"].map(|rest| format!("~/projects/{rest}")) {
411 assert_eq!(resolve(&glob), glob);
412 }
413 }
414
415 #[test]
416 fn a_home_spelled_path_is_not_resolved_into_a_protected_root() {
417 let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
418 return;
419 };
420 let root = format!("{home}/.ssh");
421 let _g = enter(PathCtx { cwd: Some(root.clone()), root: Some(root), ..Default::default() });
422 assert_eq!(resolve("~/.ssh/id_rsa"), "~/.ssh/id_rsa");
423 }
424
425 #[test]
426 fn a_root_holding_a_protected_place_keeps_every_path_absolute() {
427 let _g = enter(PathCtx { cwd: Some("/".into()), root: Some("/".into()), ..Default::default() });
428 assert_eq!(resolve("/etc/shadow"), "/etc/shadow");
429 assert_eq!(resolve("etc/sudoers"), "/etc/sudoers");
430 assert_eq!(resolve("etc"), "/etc");
431 assert_eq!(resolve("/srv/app/x"), "/srv/app/x");
432 assert_eq!(resolve("."), "/");
433 drop(_g);
434 let _etc = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/etc".into()), ..Default::default() });
435 assert_eq!(resolve("hosts"), "hosts", "an unprotected file in a root below every home is the worktree");
436 assert_eq!(resolve("sudoers"), "/etc/sudoers");
437 assert_eq!(resolve("."), "/etc", "the root itself is above a protected place");
438 drop(_etc);
439 let _inside = enter(PathCtx { cwd: Some("/root/app".into()), root: Some("/root/app".into()), ..Default::default() });
440 assert_eq!(resolve("/root/app/x"), "x", "a root inside the protected place is where the user works");
441 }
442
443 #[test]
444 fn loop_var_expands_to_its_representative_per_face() {
445 let _g = enter_loop_var("f".into(), "read_item".into(), "write_item".into());
446 assert_eq!(expand_vars("$f", false), "read_item");
447 assert_eq!(expand_vars("$f", true), "write_item");
448 assert_eq!(expand_vars("${f}", false), "read_item");
449 assert_eq!(expand_vars("$f.bak", false), "read_item.bak", "compound suffix");
450 assert_eq!(expand_vars("pre/$f", false), "pre/read_item");
451 assert_eq!(expand_vars("$foo", false), "$foo", "$foo is not $f");
452 assert_eq!(expand_vars("$g", false), "$g", "unbound var untouched");
453 assert_eq!(expand_vars("plain", false), "plain");
454 }
455
456 #[test]
457 fn loop_var_binding_is_scoped_and_nests() {
458 assert_eq!(expand_vars("$f", false), "$f", "no binding");
459 {
460 let _outer = enter_loop_var("f".into(), "outer".into(), "outer".into());
461 {
462 let _inner = enter_loop_var("f".into(), "inner".into(), "inner".into());
463 assert_eq!(expand_vars("$f", false), "inner", "innermost wins");
464 }
465 assert_eq!(expand_vars("$f", false), "outer", "inner popped on drop");
466 }
467 assert_eq!(expand_vars("$f", false), "$f", "all popped");
468 }
469
470 #[test]
471 fn the_guard_restores_on_drop() {
472 {
473 let _g = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/r".into()), ..Default::default() });
474 assert_eq!(resolve("x"), "/etc/x");
475 }
476 assert_eq!(resolve("x"), "x", "context cleared after the guard drops");
477 }
478
479 const PROBE_VAR: &str = "SAFE_CHAINS_TMPDIR_PROBE_PATH";
480
481 fn tmpdir_verdict(tmpdir: &str, path: &str) -> bool {
482 let out = std::process::Command::new(std::env::current_exe().expect("test exe"))
483 .args(["--exact", "pathctx::tests::tmpdir_probe", "--nocapture", "--test-threads=1"])
484 .env("TMPDIR", tmpdir)
485 .env(PROBE_VAR, path)
486 .output()
487 .expect("spawn probe");
488 let stdout = String::from_utf8_lossy(&out.stdout);
489 assert!(out.status.success(), "probe failed for TMPDIR={tmpdir:?} path={path:?}: {stdout}");
490 match (stdout.contains("PROBE_VERDICT=true"), stdout.contains("PROBE_VERDICT=false")) {
491 (true, false) => true,
492 (false, true) => false,
493 _ => panic!("probe did not run for TMPDIR={tmpdir:?} path={path:?}: {stdout}"),
494 }
495 }
496
497 #[test]
498 fn tmpdir_probe() {
499 let Ok(path) = std::env::var(PROBE_VAR) else {
500 return;
501 };
502 println!("PROBE_VERDICT={}", under_temp_root(&path));
503 }
504
505 #[test]
506 fn a_tmpdir_root_counts_only_when_absolute_and_non_empty() {
507 for (tmpdir, path, expected) in [
508 ("/work/scratch", "/work/scratch/x.sh", true),
509 ("/work/scratch/", "/work/scratch/x.sh", true),
510 ("/work/scratch//", "/work/scratch/nested/x.sh", true),
511 ("/work/scratch", "/work/scratch", false),
512 ("/work/scratch", "/work/scratchy/x.sh", false),
513 ("/work/scratch", "/work/other/x.sh", false),
514 ("/work/scratch", "work/scratch/x.sh", false),
515 ("", "/x.sh", false),
516 ("", "/", false),
517 ("/", "/x.sh", false),
518 ("//", "/x.sh", false),
519 ("scratch", "scratch/x.sh", false),
520 ("scratch/", "scratch/x.sh", false),
521 ("./scratch", "./scratch/x.sh", false),
522 ("$SCRATCH", "$SCRATCH/x.sh", false),
523 ("relative/dir", "relative/dir/x.sh", false),
524 ] {
525 assert_eq!(tmpdir_verdict(tmpdir, path), expected, "TMPDIR={tmpdir:?} path={path:?}");
526 }
527 }
528
529 #[test]
530 fn the_fixed_temp_roots_hold_whatever_tmpdir_says() {
531 for tmpdir in ["", "scratch", "/work/scratch"] {
532 for path in ["/tmp/x", "/private/tmp/x", "/var/tmp/x", "/private/var/tmp/x"] {
533 assert!(tmpdir_verdict(tmpdir, path), "TMPDIR={tmpdir:?} path={path:?}");
534 }
535 assert!(!tmpdir_verdict(tmpdir, "/tmp"), "the bare root is not under itself");
536 }
537 }
538}