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