1use std::path::{Path, PathBuf};
36
37const PROTECTED_HOME_DIRS: &[&str] = &["Library", "AppData", "snap"];
41
42tokio::task_local! {
43 static REQUEST_WRITE_ROOTS: Vec<PathBuf>;
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
51pub enum PathJailScope {
52 Home,
54 #[default]
56 Projects,
57 Project,
59}
60
61impl PathJailScope {
62 pub fn parse(value: &str) -> Option<Self> {
64 match value.trim().to_ascii_lowercase().as_str() {
65 "home" | "user" => Some(Self::Home),
66 "projects" | "workspace" => Some(Self::Projects),
67 "project" | "strict" | "root" => Some(Self::Project),
68 _ => None,
69 }
70 }
71
72 pub fn as_str(self) -> &'static str {
73 match self {
74 Self::Home => "home",
75 Self::Projects => "projects",
76 Self::Project => "project",
77 }
78 }
79
80 pub fn resolve() -> Self {
84 if crate::core::workspace_authority::is_configured() {
85 return Self::Project;
86 }
87 Self::explicit().unwrap_or_default()
88 }
89
90 fn explicit() -> Option<Self> {
92 if let Ok(raw) = std::env::var("LEAN_CTX_PATH_JAIL_SCOPE")
93 && let Some(scope) = Self::parse(&raw)
94 {
95 return Some(scope);
96 }
97 crate::core::config::Config::load()
98 .path_jail_scope
99 .as_deref()
100 .and_then(Self::parse)
101 }
102}
103
104fn zone_home() -> Option<PathBuf> {
107 let home = super::pathjail::canonicalize_secure(&dirs::home_dir()?);
108 home.parent().is_some().then_some(home)
109}
110
111fn scope_home() -> Option<PathBuf> {
117 let home = zone_home()?;
118 let depth = home
119 .components()
120 .filter(|c| matches!(c, std::path::Component::Normal(_)))
121 .count();
122 if depth < 2 {
123 return None;
124 }
125 #[cfg(unix)]
126 {
127 use std::os::unix::fs::MetadataExt;
128 if std::fs::metadata(&home).ok()?.uid() != unsafe { libc::geteuid() } {
130 return None;
131 }
132 }
133 Some(home)
134}
135
136fn first_component_below<'a>(path: &'a Path, home: &Path) -> Option<&'a std::ffi::OsStr> {
138 path.strip_prefix(home)
139 .ok()?
140 .components()
141 .next()
142 .map(std::path::Component::as_os_str)
143}
144
145pub(crate) fn protected_zone_in(path: &Path, home: &Path) -> Option<PathBuf> {
148 let first = first_component_below(path, home)?;
149 let name = first.to_string_lossy();
150 let protected = name.starts_with('.')
152 || name.to_ascii_lowercase().starts_with("ntuser.")
153 || PROTECTED_HOME_DIRS
154 .iter()
155 .any(|d| name.eq_ignore_ascii_case(d));
156 protected.then(|| home.join(first))
157}
158
159pub(crate) fn home_scope_admits(base: &Path) -> bool {
169 let scope = PathJailScope::resolve();
170 if scope == PathJailScope::Project {
171 return false;
172 }
173 let Some(home) = scope_home() else {
174 return false;
175 };
176 admits_below(base, &home)
177 && (scope == PathJailScope::Home || project_containing(base, &home).is_some())
178}
179
180fn admits_below(base: &Path, home: &Path) -> bool {
181 first_component_below(base, home).is_some() && protected_zone_in(base, home).is_none()
182}
183
184fn project_containing(path: &Path, home: &Path) -> Option<PathBuf> {
189 let mut cur = if path.is_dir() { path } else { path.parent()? };
190 while cur != home && cur.starts_with(home) {
191 if crate::core::pathutil::has_project_marker(cur) {
192 return Some(cur.to_path_buf());
193 }
194 cur = cur.parent()?;
195 }
196 None
197}
198
199pub(crate) fn in_protected_zone(path: &Path) -> bool {
202 zone_home().is_some_and(|home| protected_zone_in(path, &home).is_some())
203}
204
205pub(crate) fn protected_zone_permits(base: &Path, root: &Path, allow: &[PathBuf]) -> bool {
212 let Some(zone) = zone_home().and_then(|home| protected_zone_in(base, &home)) else {
213 return true;
214 };
215 (root.starts_with(&zone) && base.starts_with(root))
216 || allow
217 .iter()
218 .any(|p| p.starts_with(&zone) && base.starts_with(p))
219}
220
221fn write_root(root: &str) -> Option<PathBuf> {
223 if root.trim().is_empty() {
224 return None;
225 }
226 let path = super::pathjail::canonicalize_secure(Path::new(root));
227 (!crate::core::pathutil::is_broad_or_unsafe_root(&path)).then_some(path)
228}
229
230pub fn with_request_write_roots<T>(roots: &[String], operation: impl FnOnce() -> T) -> T {
232 let roots = roots.iter().filter_map(|root| write_root(root)).collect();
233 REQUEST_WRITE_ROOTS.sync_scope(roots, operation)
234}
235
236pub(crate) fn home_scope_write_denial(target: &Path) -> Option<String> {
243 if PathJailScope::resolve() != PathJailScope::Projects {
244 return None;
245 }
246 let home = scope_home()?;
247 if !admits_below(target, &home) {
248 return None;
249 }
250 let mut writable: Vec<PathBuf> = REQUEST_WRITE_ROOTS
255 .try_with(Clone::clone)
256 .ok()
257 .or_else(|| {
258 crate::core::policy::runtime::REQUEST_PROJECT
259 .try_with(|slot| slot.borrow().clone())
260 .ok()
261 .map(|project| {
262 project
263 .and_then(|root| write_root(&root.to_string_lossy()))
264 .into_iter()
265 .collect()
266 })
267 })
268 .unwrap_or_else(|| {
269 std::env::current_dir()
270 .ok()
271 .and_then(|cwd| write_root(&cwd.to_string_lossy()))
272 .into_iter()
273 .collect()
274 });
275 writable.extend(super::pathjail::allow_paths_from_env_and_config());
276 if let Ok(state) = crate::core::paths::state_dir() {
277 writable.push(super::pathjail::canonicalize_secure(&state));
278 }
279 if writable.iter().any(|w| target.starts_with(w)) {
280 return None;
281 }
282 Some(format!(
283 "Write refused: {} is outside the active project, and path_jail_scope = projects \
284 opens other projects for reading only. {AGENT_BIND_ACTION} and write inside that \
285 project. To allow writes there, the user runs in their terminal: \
286 lean-ctx allow-path {} — or `lean-ctx config set path_jail_scope home` for all of ~ \
287 — takes effect immediately, no restart.",
288 target.display(),
289 suggested_allow_dir(target, Some(&home)).display()
290 ))
291}
292
293fn suggested_allow_dir(path: &Path, home: Option<&Path>) -> PathBuf {
298 let start = if path.is_dir() {
299 path.to_path_buf()
300 } else {
301 path.parent().unwrap_or(path).to_path_buf()
302 };
303 let mut cur = start.as_path();
304 loop {
305 if home.is_some_and(|h| cur == h) || cur.parent().is_none() {
306 break;
307 }
308 if crate::core::pathutil::has_project_marker(cur) {
309 return cur.to_path_buf();
310 }
311 match cur.parent() {
312 Some(p) => cur = p,
313 None => break,
314 }
315 }
316 start
317}
318
319pub const AGENT_BIND_ACTION: &str = "Agent: pass the project directory as path=<abs project dir>";
323
324pub(crate) fn escape_hint(candidate: &Path, base: &Path, root: &Path) -> String {
329 const TAIL: &str = " — the user runs this in their own terminal; it takes effect \
332 immediately, no restart. Until then every call on this path is \
333 refused the same way: do not retry it, ask the user or continue \
334 without it.";
335 let home = zone_home();
336
337 if home.as_deref() == Some(base) {
338 return format!(
339 ". {AGENT_BIND_ACTION}. Your home directory itself is not a project root — it \
340 holds ~/.ssh, ~/Library and other protected locations. Point the tool at a \
341 project below it."
342 );
343 }
344 if let Some(zone) = home.as_deref().and_then(|h| protected_zone_in(base, h)) {
345 let dir = if base.is_dir() {
347 base
348 } else {
349 base.parent().unwrap_or(base)
350 };
351 return format!(
352 ". {AGENT_BIND_ACTION}. {} is a protected location (credentials and other programs' private data \
353 stay jailed). To allow it anyway: lean-ctx allow-path {}{TAIL}",
354 zone.display(),
355 dir.display()
356 );
357 }
358
359 let suggestion = suggested_allow_dir(base, home.as_deref());
360 let under_home = scope_home().is_some_and(|h| admits_below(base, &h));
361 if under_home && PathJailScope::resolve() == PathJailScope::Projects {
363 return format!(
364 ". {AGENT_BIND_ACTION}. {} is in your home directory but not inside a project (no .git, Cargo.toml, \
365 package.json, … above it), so path_jail_scope = projects does not open it. To \
366 allow it: lean-ctx allow-path {} — or all of ~: lean-ctx config set \
367 path_jail_scope home{TAIL}",
368 candidate.display(),
369 suggestion.display()
370 );
371 }
372 if under_home {
373 return format!(
374 ". {AGENT_BIND_ACTION}. {} is outside the active project ({}). Allow your whole home directory \
375 (protected locations stay jailed): lean-ctx config set path_jail_scope home — \
376 or only this one: lean-ctx allow-path {}{TAIL}",
377 candidate.display(),
378 root.display(),
379 suggestion.display()
380 );
381 }
382 format!(
383 ". {AGENT_BIND_ACTION}. {} is outside the active project ({}) and outside your \
384 home directory. To \
385 allow it: lean-ctx allow-path {}{TAIL}",
386 candidate.display(),
387 root.display(),
388 suggestion.display()
389 )
390}
391
392fn default_notice_text() -> String {
394 "\x1b[1mPathJail now writes only in the active project:\x1b[0m agents may read every \
395 project below ~, but write only in the session's project and allowed paths; \
396 protected locations (~/.ssh, ~/.aws, ~/.config, every other dot folder, ~/Library, \
397 ~/AppData) stay closed.\n \x1b[2mPrevious behaviour (read and write all of ~): \
398 lean-ctx config set path_jail_scope home · active project only: \
399 lean-ctx config set path_jail_scope project\x1b[0m\n"
400 .to_string()
401}
402
403pub fn maybe_show_default_notice() {
407 use std::io::IsTerminal;
408 if !(std::io::stderr().is_terminal() && crate::core::host_env::stdin_is_terminal())
409 || PathJailScope::explicit().is_some()
410 || crate::core::config::Config::load().path_jail == Some(false)
411 {
412 return;
413 }
414 let Ok(marker) =
415 crate::core::paths::state_dir().map(|dir| dir.join("path_jail_projects_default_notice"))
416 else {
417 return;
418 };
419 if marker.exists() {
420 return;
421 }
422 eprint!("{}", default_notice_text());
423 eprintln!();
424 if let Some(parent) = marker.parent() {
425 let _ = std::fs::create_dir_all(parent);
426 }
427 let _ = std::fs::write(marker, "1\n");
428}
429
430#[cfg(test)]
431mod tests {
432 use super::*;
433
434 #[test]
435 fn parse_accepts_canonical_names_and_aliases() {
436 assert_eq!(PathJailScope::parse("home"), Some(PathJailScope::Home));
437 assert_eq!(
438 PathJailScope::parse(" Project "),
439 Some(PathJailScope::Project)
440 );
441 assert_eq!(PathJailScope::parse("strict"), Some(PathJailScope::Project));
442 assert_eq!(
443 PathJailScope::parse("projects"),
444 Some(PathJailScope::Projects)
445 );
446 assert_eq!(PathJailScope::parse("anything"), None);
447 assert_eq!(PathJailScope::default(), PathJailScope::Projects);
448 for s in [
449 PathJailScope::Home,
450 PathJailScope::Projects,
451 PathJailScope::Project,
452 ] {
453 assert_eq!(PathJailScope::parse(s.as_str()), Some(s));
454 }
455 }
456
457 #[test]
458 fn the_notice_names_the_protected_zones_and_both_ways_back() {
459 let text = default_notice_text();
460 for needle in [
461 "~/.ssh",
462 "~/.aws",
463 "~/Library",
464 "path_jail_scope home",
465 "path_jail_scope project",
466 ] {
467 assert!(text.contains(needle), "{needle}");
468 }
469 }
470
471 #[test]
472 fn home_zone_admits_code_and_protects_secrets() {
473 let home = Path::new("/home/u");
474 assert!(admits_below(Path::new("/home/u/code/repo/src/a.rs"), home));
475 assert!(admits_below(Path::new("/home/u/Documents/p"), home));
476
477 for protected in [
478 "/home/u/.ssh/id_ed25519",
479 "/home/u/.aws/credentials",
480 "/home/u/.config/gh/hosts.yml",
481 "/home/u/.zshrc",
482 "/home/u/.claude/projects/x/session.jsonl",
483 "/home/u/Library/Keychains/login.keychain-db",
484 "/home/u/AppData/Roaming/x",
485 "/home/u/NTUSER.DAT",
486 ] {
487 assert!(!admits_below(Path::new(protected), home), "{protected}");
488 assert!(protected_zone_in(Path::new(protected), home).is_some());
489 }
490 assert!(!admits_below(home, home));
492 assert!(!admits_below(Path::new("/etc/passwd"), home));
493 assert!(!admits_below(Path::new("/home/user2/x"), home));
494 }
495
496 #[test]
497 fn protected_zone_is_the_top_level_entry() {
498 let home = Path::new("/home/u");
499 assert_eq!(
500 protected_zone_in(Path::new("/home/u/.config/gh/hosts.yml"), home),
501 Some(PathBuf::from("/home/u/.config"))
502 );
503 assert_eq!(
505 protected_zone_in(Path::new("/home/u/code/repo/.git/HEAD"), home),
506 None
507 );
508 }
509
510 #[cfg(all(unix, not(feature = "no-jail")))]
515 #[test]
516 fn jail_admits_sibling_projects_but_not_protected_zones() {
517 let _iso = crate::core::data_dir::isolated_data_dir();
518 let tmp = tempfile::tempdir().unwrap();
519 let home = super::super::pathjail::canonicalize_secure(tmp.path()).join("home");
520 let (a, b, ssh) = (home.join("code/a"), home.join("code/b"), home.join(".ssh"));
521 for dir in [&a, &b, &ssh] {
522 std::fs::create_dir_all(dir).unwrap();
523 }
524 std::fs::create_dir_all(a.join(".git")).unwrap();
525 std::fs::write(b.join("Cargo.toml"), "[package]").unwrap();
526 std::fs::create_dir_all(b.join("src")).unwrap();
527 std::fs::write(b.join("src/lib.rs"), "x").unwrap();
528 std::fs::write(b.join("lib.rs"), "x").unwrap();
529 std::fs::write(ssh.join("id_ed25519"), "secret").unwrap();
530 let docs = home.join("Documents/Steuern");
531 std::fs::create_dir_all(&docs).unwrap();
532 std::fs::write(docs.join("2025.pdf"), "private").unwrap();
533 let outside = tmp.path().join("outside.txt");
534 std::fs::write(&outside, "x").unwrap();
535
536 let old_home = std::env::var_os("HOME");
537 crate::test_env::set_var("HOME", &home);
538 crate::test_env::remove_var("LEAN_CTX_PATH_JAIL_SCOPE");
539 let jail = super::super::pathjail::jail_path;
540 let write = super::super::pathjail::enforce_writable;
541
542 assert_eq!(PathJailScope::resolve(), PathJailScope::Projects);
545 assert!(jail(&b.join("lib.rs"), &a).is_ok(), "reads across projects");
546 assert!(write(&b.join(".git/hooks/pre-commit")).is_err());
547 assert!(write(&b.join("lib.rs")).is_err());
548 assert!(
549 super::super::pathjail::active_relaxations()
550 .iter()
551 .all(|r| !r.source.contains("path_jail_scope")),
552 "the default scope is not a relaxation"
553 );
554
555 crate::test_env::set_var("LEAN_CTX_PATH_JAIL_SCOPE", "home");
556 assert!(
557 super::super::pathjail::active_relaxations()
558 .iter()
559 .any(|r| r.source.contains("LEAN_CTX_PATH_JAIL_SCOPE")),
560 "the home scope is reported as a relaxation"
561 );
562 assert!(
563 jail(&b.join("lib.rs"), &a).is_ok(),
564 "sibling project under ~"
565 );
566 assert!(
567 jail(&b.join("src/lib.rs"), &a).is_ok(),
568 "nested file of a sibling project"
569 );
570 assert!(
572 jail(&docs.join("2025.pdf"), &a).is_ok(),
573 "loose file under ~"
574 );
575 assert!(jail(&docs, &a).is_ok(), "a folder without a project");
576 assert!(jail(&home.join("code"), &a).is_ok(), "parent of projects");
577 let err = jail(&ssh.join("id_ed25519"), &a).unwrap_err().to_string();
578 assert!(err.contains("protected location"), "{err}");
579 let agent_first = |err: &str| {
581 let agent = err.find(AGENT_BIND_ACTION);
582 agent.is_some() && err.find("allow-path").is_none_or(|user| agent < Some(user))
583 };
584 assert!(agent_first(&err), "{err}");
585 let err = jail(&outside, &a).unwrap_err().to_string();
586 assert!(agent_first(&err), "{err}");
587 assert!(err.contains("outside your home directory"), "{err}");
588 let err = jail(&home, &a).unwrap_err().to_string();
589 assert!(err.contains("not a project root"), "{err}");
590
591 assert!(
594 jail(&ssh.join("id_ed25519"), &home).is_err(),
595 "zone is a deny"
596 );
597 assert!(
598 jail(&ssh.join("id_ed25519"), &ssh).is_ok(),
599 "root inside the zone"
600 );
601
602 assert!(write(&b.join("lib.rs")).is_ok(), "another project");
605 assert!(write(&docs.join("notes.md")).is_ok(), "a loose folder");
606 assert!(
607 jail(&ssh.join("authorized_keys"), &a).is_err(),
608 "protected zone"
609 );
610
611 crate::test_env::set_var("LEAN_CTX_PATH_JAIL_SCOPE", "projects");
613 assert!(jail(&b.join("lib.rs"), &a).is_ok(), "sibling project");
614 let err = jail(&docs.join("2025.pdf"), &a).unwrap_err().to_string();
615 assert!(err.contains("not inside a project"), "{err}");
616 assert!(jail(&home.join("code"), &a).is_err(), "parent of projects");
617 let err = write(&b.join("lib.rs")).unwrap_err();
618 assert!(
619 err.contains("for reading only") && err.contains("allow-path"),
620 "{err}"
621 );
622 assert!(agent_first(&err), "{err}");
623 assert!(write(&b.join(".git/hooks/pre-commit")).is_err());
624 let as_call = |roots: &[&Path], target: &Path| {
625 let roots: Vec<String> = roots.iter().map(|r| r.to_string_lossy().into()).collect();
626 with_request_write_roots(&roots, || write(target))
627 };
628 assert!(
629 as_call(&[b.as_path()], &b.join("lib.rs")).is_ok(),
630 "session root is writable"
631 );
632 assert!(as_call(&[a.as_path()], &b.join("lib.rs")).is_err());
635
636 crate::test_env::set_var("LEAN_CTX_PATH_JAIL_SCOPE", "project");
637 let err = jail(&b.join("lib.rs"), &a).unwrap_err().to_string();
638 assert!(
639 err.contains("path_jail_scope home") && err.contains("allow-path"),
640 "{err}"
641 );
642 crate::test_env::remove_var("LEAN_CTX_PATH_JAIL_SCOPE");
643
644 crate::test_env::set_var("HOME", "/");
646 assert!(
647 jail(&b.join("lib.rs"), &a).is_err(),
648 "HOME=/ falls back to the project"
649 );
650
651 match old_home {
652 Some(h) => crate::test_env::set_var("HOME", h),
653 None => crate::test_env::remove_var("HOME"),
654 }
655 }
656
657 #[test]
658 fn suggestion_prefers_the_enclosing_project() {
659 let tmp = tempfile::tempdir().unwrap();
660 let repo = tmp.path().join("repo");
661 std::fs::create_dir_all(repo.join("src/deep")).unwrap();
662 std::fs::create_dir_all(repo.join(".git")).unwrap();
663 let file = repo.join("src/deep/a.rs");
664 std::fs::write(&file, "x").unwrap();
665 assert_eq!(suggested_allow_dir(&file, None), repo);
666
667 let loose = tmp.path().join("loose");
668 std::fs::create_dir_all(&loose).unwrap();
669 assert_eq!(suggested_allow_dir(&loose, Some(tmp.path())), loose);
670 }
671}