1use std::borrow::Cow;
17use std::cell::RefCell;
18
19mod home;
20mod lexical;
21use home::home_path_inside_root;
22use lexical::{expand_home, express_relative_to_root, lexical_join};
23
24#[derive(Clone, Default)]
28pub struct PathCtx {
29 pub cwd: Option<String>,
30 pub root: Option<String>,
31 pub session_id: Option<String>,
34}
35
36thread_local! {
37 static CURRENT: RefCell<PathCtx> = RefCell::new(PathCtx::default());
38}
39
40#[must_use]
43pub fn enter(ctx: PathCtx) -> Guard {
44 Guard(CURRENT.with(|c| c.replace(ctx)))
45}
46
47pub struct Guard(PathCtx);
49
50impl Drop for Guard {
51 fn drop(&mut self) {
52 CURRENT.with(|c| *c.borrow_mut() = std::mem::take(&mut self.0));
53 }
54}
55
56#[must_use]
59pub fn enter_cwd(cwd: Option<String>) -> Guard {
60 Guard(CURRENT.with(|c| {
61 let mut b = c.borrow_mut();
62 PathCtx { cwd: std::mem::replace(&mut b.cwd, cwd), root: b.root.clone(), session_id: b.session_id.clone() }
65 }))
66}
67
68pub fn cwd() -> Option<String> {
70 CURRENT.with(|c| c.borrow().cwd.clone())
71}
72
73pub fn root() -> Option<String> {
76 CURRENT.with(|c| {
77 let b = c.borrow();
78 b.root.clone().or_else(|| b.cwd.clone())
79 })
80}
81
82pub fn in_session_scratchpad(path: &str) -> bool {
103 let Some(id) = CURRENT.with(|c| c.borrow().session_id.clone()) else {
104 return false;
105 };
106 if id.len() < 8 || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
109 return false;
110 }
111 if !under_temp_root(path) {
112 return false;
113 }
114 path.split('/').any(|seg| seg == id)
115}
116
117pub fn under_temp_root(path: &str) -> bool {
120 const ROOTS: &[&str] = &["/tmp/", "/private/tmp/", "/var/tmp/", "/private/var/tmp/"];
121 if ROOTS.iter().any(|r| path.starts_with(r)) {
122 return true;
123 }
124 std::env::var("TMPDIR").ok().is_some_and(|t| {
125 let t = t.trim_end_matches('/');
126 !t.is_empty() && t.starts_with('/') && path.starts_with(&format!("{t}/"))
127 })
128}
129
130struct LoopVar {
134 name: String,
135 read_repr: String,
136 write_repr: String,
137}
138
139thread_local! {
140 static LOOP_VARS: RefCell<Vec<LoopVar>> = const { RefCell::new(Vec::new()) };
141}
142
143struct VarBinding {
146 name: String,
147 value: String,
148}
149
150thread_local! {
151 static VARS: RefCell<Vec<VarBinding>> = const { RefCell::new(Vec::new()) };
152}
153
154#[must_use]
160pub fn enter_var(name: String, value: String) -> VarGuard {
161 VARS.with(|v| v.borrow_mut().push(VarBinding { name, value }));
162 VarGuard
163}
164
165pub struct VarGuard;
166
167impl Drop for VarGuard {
168 fn drop(&mut self) {
169 VARS.with(|v| {
170 v.borrow_mut().pop();
171 });
172 }
173}
174
175#[must_use]
178pub fn enter_loop_var(name: String, read_repr: String, write_repr: String) -> LoopGuard {
179 LOOP_VARS.with(|v| v.borrow_mut().push(LoopVar { name, read_repr, write_repr }));
180 LoopGuard
181}
182
183pub struct LoopGuard;
185
186impl Drop for LoopGuard {
187 fn drop(&mut self) {
188 LOOP_VARS.with(|v| {
189 v.borrow_mut().pop();
190 });
191 }
192}
193
194thread_local! {
195 static STDIN_REPR: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
196}
197
198#[must_use]
203pub fn enter_stdin_repr(repr: String) -> StdinReprGuard {
204 STDIN_REPR.with(|v| v.borrow_mut().push(repr));
205 StdinReprGuard
206}
207
208pub fn stdin_item_repr() -> Option<String> {
211 STDIN_REPR.with(|v| v.borrow().last().cloned())
212}
213
214pub struct StdinReprGuard;
215
216impl Drop for StdinReprGuard {
217 fn drop(&mut self) {
218 STDIN_REPR.with(|v| {
219 v.borrow_mut().pop();
220 });
221 }
222}
223
224pub fn expand_vars(path: &str, want_write: bool) -> Cow<'_, str> {
229 if !path.contains('$') {
230 return Cow::Borrowed(path);
231 }
232 let replaced = LOOP_VARS.with(|lv| {
233 VARS.with(|v| {
234 let loops = lv.borrow();
235 let vars = v.borrow();
236 if loops.is_empty() && vars.is_empty() { None } else { expand_with(path, &loops, &vars, want_write) }
237 })
238 });
239 replaced.map_or(Cow::Borrowed(path), Cow::Owned)
240}
241
242fn expand_with(path: &str, loops: &[LoopVar], vars: &[VarBinding], want_write: bool) -> Option<String> {
243 let mut out = String::with_capacity(path.len());
244 let mut rest = path;
245 let mut replaced = false;
246 while let Some(dollar) = rest.find('$') {
247 out.push_str(&rest[..dollar]);
248 let after = &rest[dollar + 1..];
249 match parse_var(after) {
250 Some((name, consumed)) => {
251 if let Some(lv) = loops.iter().rev().find(|v| v.name == name) {
254 out.push_str(if want_write { &lv.write_repr } else { &lv.read_repr });
255 replaced = true;
256 } else if let Some(vb) = vars.iter().rev().find(|v| v.name == name) {
257 out.push_str(&vb.value);
258 replaced = true;
259 } else {
260 out.push('$');
261 out.push_str(&after[..consumed]);
262 }
263 rest = &after[consumed..];
264 }
265 None => {
266 out.push('$');
267 rest = after;
268 }
269 }
270 }
271 out.push_str(rest);
272 replaced.then_some(out)
273}
274
275fn parse_var(after: &str) -> Option<(&str, usize)> {
279 if let Some(braced) = after.strip_prefix('{') {
280 let close = braced.find('}')?;
281 let name = &braced[..close];
282 is_var_name(name).then_some((name, close + 2)) } else if after.as_bytes().first().is_some_and(u8::is_ascii_digit) {
284 Some((&after[..1], 1)) } else {
286 let len = after.bytes().take_while(|&b| b.is_ascii_alphanumeric() || b == b'_').count();
287 let name = &after[..len];
288 is_var_name(name).then_some((name, len))
289 }
290}
291
292fn is_var_name(s: &str) -> bool {
295 if s.is_empty() {
296 return false;
297 }
298 if s.bytes().all(|b| b.is_ascii_digit()) {
299 return true;
300 }
301 let mut bytes = s.bytes();
302 matches!(bytes.next(), Some(b) if b.is_ascii_alphabetic() || b == b'_') && bytes.all(|b| b.is_ascii_alphanumeric() || b == b'_')
303}
304
305pub fn resolve(path: &str) -> Cow<'_, str> {
317 if path.is_empty() || path.contains('$') {
318 return Cow::Borrowed(path);
319 }
320 if path.starts_with('~') {
321 return home_path_inside_root(path).map_or(Cow::Borrowed(path), Cow::Owned);
322 }
323 let resolved = CURRENT.with(|c| {
324 let ctx = c.borrow();
325 match (ctx.cwd.as_deref(), ctx.root.as_deref()) {
326 (Some(cwd), Some(root)) if cwd.starts_with('/') && root.starts_with('/') => {
327 let abs = if path.starts_with('/') { lexical_join("/", path) } else { lexical_join(cwd, path) };
330 Some(express_relative_to_root(&abs, root))
331 }
332 _ => None,
333 }
334 });
335 resolved.map_or(Cow::Borrowed(path), Cow::Owned)
336}
337
338pub(crate) const UNRESOLVED_CWD: &str = "/__SAFE_CHAINS_CMDSUB__";
341
342pub fn join_cwd(cur: Option<&str>, target: &str) -> Option<String> {
357 let expanded = match expand_home(target) {
358 Some(t) => t,
359 None => return Some(UNRESOLVED_CWD.to_string()), };
361 if expanded.starts_with('~') || expanded.contains('$') || crate::cst::check::is_opaque_value(&expanded) {
369 return Some(UNRESOLVED_CWD.to_string());
370 }
371 if expanded.starts_with('/') {
372 return Some(lexical_join("/", &expanded)); }
374 cur.filter(|c| c.starts_with('/')).map(|c| lexical_join(c, &expanded))
378}
379
380#[cfg(test)]
381mod tests {
382 use super::*;
383
384 const SID: &str = "7676dbc5-a265-43b3-a0f8-49666792bd9b";
385
386 fn with_session<T>(id: Option<&str>, f: impl FnOnce() -> T) -> T {
387 let _g = enter(PathCtx { cwd: Some("/home/u/proj".into()), root: Some("/home/u/proj".into()), session_id: id.map(str::to_string) });
388 f()
389 }
390
391 #[test]
396 fn only_this_sessions_scratchpad_is_recognized() {
397 let scratch = format!("/private/tmp/claude-501/-Users-u-proj/{SID}/scratchpad");
398 let matching: &[String] = &[
399 format!("{scratch}/build.sh"),
400 format!("{scratch}/nested/deep/gen.py"),
401 scratch.clone(),
402 format!("/tmp/{SID}/x.sh"),
404 format!("/tmp/some-other-harness/{SID}/work/x.sh"),
405 format!("/var/tmp/{SID}/x.sh"),
406 ];
407 let rejected: &[String] = &[
408 "/private/tmp/claude-501/-Users-u-proj/00000000-1111-2222-3333-444444444444/scratchpad/x.sh".into(),
410 format!("/tmp/{SID}-evil/x.sh"),
412 format!("/tmp/evil-{SID}/x.sh"),
413 format!("/tmp/a{SID}/x.sh"),
414 format!("/home/u/{SID}/x.sh"),
416 format!("~/.ssh/{SID}/id_rsa"),
417 format!("/etc/{SID}/passwd"),
418 "/tmp/evil.sh".into(),
420 "/private/tmp/downloaded.sh".into(),
421 ];
422 with_session(Some(SID), || {
423 for p in matching {
424 assert!(in_session_scratchpad(p), "should be recognized: {p}");
425 }
426 for p in rejected {
427 assert!(!in_session_scratchpad(p), "must NOT be recognized: {p}");
428 }
429 });
430 }
431
432 #[test]
435 fn a_missing_or_unusable_session_id_recognizes_nothing() {
436 let path = format!("/tmp/{SID}/x.sh");
437 with_session(None, || {
438 assert!(!in_session_scratchpad(&path), "no session id → no recognition");
439 });
440 for weak in ["", "abc", "1234567", "..", "/", "a/b", "id with space", "x*y"] {
441 with_session(Some(weak), || {
442 assert!(!in_session_scratchpad(&format!("/tmp/{weak}/x.sh")), "weak id {weak:?} must not anchor recognition",);
443 });
444 }
445 }
446
447 #[test]
448 fn no_context_leaves_paths_unchanged() {
449 assert_eq!(resolve("./x"), "./x");
450 assert_eq!(resolve("config"), "config");
451 assert_eq!(resolve("/etc/x"), "/etc/x");
452 }
453
454 #[test]
455 fn relative_inside_the_project_stays_worktree_relative() {
456 let _g = enter(PathCtx { cwd: Some("/home/u/proj/sub".into()), root: Some("/home/u/proj".into()), ..Default::default() });
457 assert_eq!(resolve("x"), "sub/x", "cwd under root → root-relative");
458 assert_eq!(resolve("./y"), "sub/y");
459 assert_eq!(resolve("../z"), "z", ".. that stays inside root");
460 }
461
462 #[test]
463 fn relative_outside_the_project_becomes_absolute() {
464 let _g = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/home/u/proj".into()), ..Default::default() });
465 assert_eq!(resolve("x"), "/etc/x", "cd /etc → the real target");
466 assert_eq!(resolve("passwd"), "/etc/passwd");
467 assert_eq!(resolve("*"), "/etc/*");
468 }
469
470 #[test]
471 fn dotdot_escaping_the_project_becomes_absolute() {
472 let _g = enter(PathCtx { cwd: Some("/home/u/proj".into()), root: Some("/home/u/proj".into()), ..Default::default() });
473 assert_eq!(resolve("../../../etc/x"), "/etc/x");
474 }
475
476 #[test]
477 fn absolute_in_root_becomes_root_relative_outside_stays_absolute() {
478 let _g = enter(PathCtx { cwd: Some("/home/u/proj/sub".into()), root: Some("/home/u/proj".into()), ..Default::default() });
479 assert_eq!(resolve("/home/u/proj/main.rs"), "main.rs");
481 assert_eq!(resolve("/home/u/proj/sub/x"), "sub/x");
482 assert_eq!(resolve("/home/u/proj/a/../b"), "b", "normalized in place");
483 assert_eq!(resolve("/home/u/proj"), ".", "the project root itself");
484 assert_eq!(resolve("/usr/bin/x"), "/usr/bin/x");
486 assert_eq!(resolve("/home/u/proj/../../etc/x"), "/home/etc/x", "climbs to /home, still outside root");
487 assert_eq!(resolve("/home/u/proj/../../../etc/x"), "/etc/x", "escapes to /etc via ..");
488 assert_eq!(
489 resolve("/home/u/proj-evil/secret"),
490 "/home/u/proj-evil/secret",
491 "a sibling dir is not confused for inside by bare string prefix",
492 );
493 assert_eq!(resolve("$HOME/x"), "$HOME/x");
495 assert_eq!(resolve("~/x"), "~/x");
496 }
497
498 #[test]
499 fn a_home_spelled_path_inside_root_becomes_root_relative() {
500 let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
501 return;
502 };
503 let root = format!("{home}/projects/app");
504 let _g = enter(PathCtx { cwd: Some(format!("{root}/sub")), root: Some(root), ..Default::default() });
505 assert_eq!(resolve("~/projects/app/src/main.rs"), "src/main.rs");
506 assert_eq!(resolve("~/projects/app"), ".");
507 assert_eq!(resolve("~/projects/app/"), ".");
508 let under = |rest: &str| format!("~/projects/{rest}");
509 assert_eq!(resolve(&under("app/a/../b")), "b");
510 assert_eq!(resolve(&under("app/.git/hooks/pre-commit")), ".git/hooks/pre-commit");
511 for (outside, why) in [("peer/x", "a sibling"), ("app-evil/x", "no bare string prefix"), ("app/../../.ssh/id_rsa", "an escape")] {
512 assert_eq!(resolve(&under(outside)), under(outside), "{why} stays home-spelled");
513 }
514 assert_eq!(resolve("~/.ssh/id_rsa"), "~/.ssh/id_rsa");
515 assert_eq!(resolve("~"), "~");
516 assert_eq!(resolve("~bob/projects/app/x"), "~bob/projects/app/x", "another user's home is not ours");
517 }
518
519 #[test]
520 fn a_home_spelled_path_needs_an_absolute_root() {
521 let _none = enter(PathCtx { cwd: Some("/w".into()), root: None, ..Default::default() });
522 assert_eq!(resolve("~/x"), "~/x");
523 drop(_none);
524 let _rel = enter(PathCtx { cwd: Some("/w".into()), root: Some("w".into()), ..Default::default() });
525 assert_eq!(resolve("~/x"), "~/x");
526 }
527
528 #[test]
529 fn a_home_rooted_workspace_leaves_home_paths_to_the_home_classifiers() {
530 let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
531 return;
532 };
533 let _g = enter(PathCtx { cwd: Some(home.clone()), root: Some(home.clone()), ..Default::default() });
534 assert_eq!(resolve("~"), "~");
535 assert_eq!(resolve("~/notes.txt"), "~/notes.txt");
536 assert_eq!(resolve("notes.txt"), format!("{home}/notes.txt"));
537 assert_eq!(resolve("."), home);
538 }
539
540 #[test]
541 fn a_home_spelled_path_is_not_resolved_from_outside_the_root_or_through_a_glob() {
542 let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
543 return;
544 };
545 let root = format!("{home}/projects/app");
546 let outside = enter(PathCtx { cwd: Some("/etc".into()), root: Some(root.clone()), ..Default::default() });
547 assert_eq!(resolve("~/projects/app/x"), "~/projects/app/x", "a quoted `~` would name a directory under the cwd");
548 drop(outside);
549 let _g = enter(PathCtx { cwd: Some(root.clone()), root: Some(root), ..Default::default() });
550 for glob in ["app/.ss?/id_rsa", "app/*"].map(|rest| format!("~/projects/{rest}")) {
551 assert_eq!(resolve(&glob), glob);
552 }
553 }
554
555 #[test]
556 fn a_home_spelled_path_is_not_resolved_into_a_protected_root() {
557 let Some(home) = std::env::var("HOME").ok().filter(|h| h.starts_with('/') && h.len() > 1) else {
558 return;
559 };
560 let root = format!("{home}/.ssh");
561 let _g = enter(PathCtx { cwd: Some(root.clone()), root: Some(root), ..Default::default() });
562 assert_eq!(resolve("~/.ssh/id_rsa"), "~/.ssh/id_rsa");
563 }
564
565 #[test]
566 fn a_root_holding_a_protected_place_keeps_every_path_absolute() {
567 let _g = enter(PathCtx { cwd: Some("/".into()), root: Some("/".into()), ..Default::default() });
568 assert_eq!(resolve("/etc/shadow"), "/etc/shadow");
569 assert_eq!(resolve("etc/sudoers"), "/etc/sudoers");
570 assert_eq!(resolve("etc"), "/etc");
571 assert_eq!(resolve("/srv/app/x"), "/srv/app/x");
572 assert_eq!(resolve("."), "/");
573 drop(_g);
574 let _etc = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/etc".into()), ..Default::default() });
575 assert_eq!(resolve("hosts"), "hosts", "an unprotected file in a root below every home is the worktree");
576 assert_eq!(resolve("sudoers"), "/etc/sudoers");
577 assert_eq!(resolve("."), "/etc", "the root itself is above a protected place");
578 drop(_etc);
579 let _inside = enter(PathCtx { cwd: Some("/root/app".into()), root: Some("/root/app".into()), ..Default::default() });
580 assert_eq!(resolve("/root/app/x"), "x", "a root inside the protected place is where the user works");
581 }
582
583 #[test]
584 fn loop_var_expands_to_its_representative_per_face() {
585 let _g = enter_loop_var("f".into(), "read_item".into(), "write_item".into());
586 assert_eq!(expand_vars("$f", false), "read_item");
587 assert_eq!(expand_vars("$f", true), "write_item");
588 assert_eq!(expand_vars("${f}", false), "read_item");
589 assert_eq!(expand_vars("$f.bak", false), "read_item.bak", "compound suffix");
590 assert_eq!(expand_vars("pre/$f", false), "pre/read_item");
591 assert_eq!(expand_vars("$foo", false), "$foo", "$foo is not $f");
592 assert_eq!(expand_vars("$g", false), "$g", "unbound var untouched");
593 assert_eq!(expand_vars("plain", false), "plain");
594 }
595
596 #[test]
597 fn loop_var_binding_is_scoped_and_nests() {
598 assert_eq!(expand_vars("$f", false), "$f", "no binding");
599 {
600 let _outer = enter_loop_var("f".into(), "outer".into(), "outer".into());
601 {
602 let _inner = enter_loop_var("f".into(), "inner".into(), "inner".into());
603 assert_eq!(expand_vars("$f", false), "inner", "innermost wins");
604 }
605 assert_eq!(expand_vars("$f", false), "outer", "inner popped on drop");
606 }
607 assert_eq!(expand_vars("$f", false), "$f", "all popped");
608 }
609
610 #[test]
611 fn the_guard_restores_on_drop() {
612 {
613 let _g = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/r".into()), ..Default::default() });
614 assert_eq!(resolve("x"), "/etc/x");
615 }
616 assert_eq!(resolve("x"), "x", "context cleared after the guard drops");
617 }
618}