1use std::path::{Path, PathBuf};
32
33const PROTECTED_HOME_DIRS: &[&str] = &["Library", "AppData", "snap"];
37
38const MAX_SESSION_WRITE_ROOTS: usize = 64;
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
43pub enum PathJailScope {
44 #[default]
46 Home,
47 Projects,
49 Project,
51}
52
53impl PathJailScope {
54 pub fn parse(value: &str) -> Option<Self> {
56 match value.trim().to_ascii_lowercase().as_str() {
57 "home" | "user" => Some(Self::Home),
58 "projects" | "workspace" => Some(Self::Projects),
59 "project" | "strict" | "root" => Some(Self::Project),
60 _ => None,
61 }
62 }
63
64 pub fn as_str(self) -> &'static str {
65 match self {
66 Self::Home => "home",
67 Self::Projects => "projects",
68 Self::Project => "project",
69 }
70 }
71
72 pub fn resolve() -> Self {
74 Self::explicit().unwrap_or_default()
75 }
76
77 fn explicit() -> Option<Self> {
79 if let Ok(raw) = std::env::var("LEAN_CTX_PATH_JAIL_SCOPE")
80 && let Some(scope) = Self::parse(&raw)
81 {
82 return Some(scope);
83 }
84 crate::core::config::Config::load()
85 .path_jail_scope
86 .as_deref()
87 .and_then(Self::parse)
88 }
89}
90
91fn zone_home() -> Option<PathBuf> {
94 let home = super::pathjail::canonicalize_secure(&dirs::home_dir()?);
95 home.parent().is_some().then_some(home)
96}
97
98fn scope_home() -> Option<PathBuf> {
104 let home = zone_home()?;
105 let depth = home
106 .components()
107 .filter(|c| matches!(c, std::path::Component::Normal(_)))
108 .count();
109 if depth < 2 {
110 return None;
111 }
112 #[cfg(unix)]
113 {
114 use std::os::unix::fs::MetadataExt;
115 if std::fs::metadata(&home).ok()?.uid() != unsafe { libc::geteuid() } {
117 return None;
118 }
119 }
120 Some(home)
121}
122
123fn first_component_below<'a>(path: &'a Path, home: &Path) -> Option<&'a std::ffi::OsStr> {
125 path.strip_prefix(home)
126 .ok()?
127 .components()
128 .next()
129 .map(std::path::Component::as_os_str)
130}
131
132fn protected_zone_in(path: &Path, home: &Path) -> Option<PathBuf> {
135 let first = first_component_below(path, home)?;
136 let name = first.to_string_lossy();
137 let protected = name.starts_with('.')
139 || name.to_ascii_lowercase().starts_with("ntuser.")
140 || PROTECTED_HOME_DIRS
141 .iter()
142 .any(|d| name.eq_ignore_ascii_case(d));
143 protected.then(|| home.join(first))
144}
145
146pub(crate) fn home_scope_admits(base: &Path) -> bool {
156 let scope = PathJailScope::resolve();
157 if scope == PathJailScope::Project {
158 return false;
159 }
160 let Some(home) = scope_home() else {
161 return false;
162 };
163 admits_below(base, &home)
164 && (scope == PathJailScope::Home || project_containing(base, &home).is_some())
165}
166
167fn admits_below(base: &Path, home: &Path) -> bool {
168 first_component_below(base, home).is_some() && protected_zone_in(base, home).is_none()
169}
170
171fn project_containing(path: &Path, home: &Path) -> Option<PathBuf> {
176 let mut cur = if path.is_dir() { path } else { path.parent()? };
177 while cur != home && cur.starts_with(home) {
178 if crate::core::pathutil::has_project_marker(cur) {
179 return Some(cur.to_path_buf());
180 }
181 cur = cur.parent()?;
182 }
183 None
184}
185
186pub(crate) fn in_protected_zone(path: &Path) -> bool {
189 zone_home().is_some_and(|home| protected_zone_in(path, &home).is_some())
190}
191
192pub(crate) fn protected_zone_permits(base: &Path, root: &Path, allow: &[PathBuf]) -> bool {
199 let Some(zone) = zone_home().and_then(|home| protected_zone_in(base, &home)) else {
200 return true;
201 };
202 (root.starts_with(&zone) && base.starts_with(root))
203 || allow
204 .iter()
205 .any(|p| p.starts_with(&zone) && base.starts_with(p))
206}
207
208fn session_write_roots() -> &'static std::sync::Mutex<Vec<PathBuf>> {
209 static ROOTS: std::sync::OnceLock<std::sync::Mutex<Vec<PathBuf>>> = std::sync::OnceLock::new();
210 ROOTS.get_or_init(|| std::sync::Mutex::new(Vec::new()))
211}
212
213pub fn register_session_root(root: &str) {
216 if root.trim().is_empty() {
217 return;
218 }
219 let path = super::pathjail::canonicalize_secure(Path::new(root));
220 if crate::core::pathutil::is_broad_or_unsafe_root(&path) {
221 return;
222 }
223 let mut roots = session_write_roots()
224 .lock()
225 .unwrap_or_else(std::sync::PoisonError::into_inner);
226 if roots.iter().any(|r| r == &path) {
227 return;
228 }
229 if roots.len() >= MAX_SESSION_WRITE_ROOTS {
230 roots.remove(0);
231 }
232 roots.push(path);
233}
234
235pub(crate) fn home_scope_write_denial(target: &Path) -> Option<String> {
242 if PathJailScope::resolve() != PathJailScope::Projects {
243 return None;
244 }
245 let home = scope_home()?;
246 if !admits_below(target, &home) {
247 return None;
248 }
249 let mut writable: Vec<PathBuf> = session_write_roots()
250 .lock()
251 .unwrap_or_else(std::sync::PoisonError::into_inner)
252 .clone();
253 writable.extend(super::pathjail::allow_paths_from_env_and_config());
254 if let Ok(state) = crate::core::paths::state_dir() {
255 writable.push(super::pathjail::canonicalize_secure(&state));
256 }
257 if let Ok(cwd) = std::env::current_dir() {
260 let cwd = super::pathjail::canonicalize_secure(&cwd);
261 if !crate::core::pathutil::is_broad_or_unsafe_root(&cwd) {
262 writable.push(cwd);
263 }
264 }
265 if writable.iter().any(|w| target.starts_with(w)) {
266 return None;
267 }
268 Some(format!(
269 "{} is outside the active project — path_jail_scope = projects opens other \
270 projects for reading only. To allow writes there, the user runs in their terminal: \
271 lean-ctx allow-path {} — or `lean-ctx config set path_jail_scope home` for all of ~ \
272 — takes effect immediately, no restart.",
273 target.display(),
274 suggested_allow_dir(target, Some(&home)).display()
275 ))
276}
277
278fn suggested_allow_dir(path: &Path, home: Option<&Path>) -> PathBuf {
283 let start = if path.is_dir() {
284 path.to_path_buf()
285 } else {
286 path.parent().unwrap_or(path).to_path_buf()
287 };
288 let mut cur = start.as_path();
289 loop {
290 if home.is_some_and(|h| cur == h) || cur.parent().is_none() {
291 break;
292 }
293 if crate::core::pathutil::has_project_marker(cur) {
294 return cur.to_path_buf();
295 }
296 match cur.parent() {
297 Some(p) => cur = p,
298 None => break,
299 }
300 }
301 start
302}
303
304pub(crate) fn escape_hint(candidate: &Path, base: &Path, root: &Path) -> String {
309 const TAIL: &str = " — the user runs this in their own terminal; it takes effect \
310 immediately, no restart.";
311 let home = zone_home();
312
313 if home.as_deref() == Some(base) {
314 return ". Your home directory itself is not a project root — it holds ~/.ssh, \
315 ~/Library and other protected locations. Point the tool at a project \
316 below it."
317 .to_string();
318 }
319 if let Some(zone) = home.as_deref().and_then(|h| protected_zone_in(base, h)) {
320 let dir = if base.is_dir() {
322 base
323 } else {
324 base.parent().unwrap_or(base)
325 };
326 return format!(
327 ". {} is a protected location (credentials and other programs' private data \
328 stay jailed). To allow it anyway: lean-ctx allow-path {}{TAIL}",
329 zone.display(),
330 dir.display()
331 );
332 }
333
334 let suggestion = suggested_allow_dir(base, home.as_deref());
335 let under_home = scope_home().is_some_and(|h| admits_below(base, &h));
336 if under_home && PathJailScope::resolve() == PathJailScope::Projects {
338 return format!(
339 ". {} is in your home directory but not inside a project (no .git, Cargo.toml, \
340 package.json, … above it), so path_jail_scope = projects does not open it. To \
341 allow it: lean-ctx allow-path {} — or all of ~: lean-ctx config set \
342 path_jail_scope home{TAIL}",
343 candidate.display(),
344 suggestion.display()
345 );
346 }
347 if under_home {
348 return format!(
349 ". {} is outside the active project ({}). Allow your whole home directory \
350 (protected locations stay jailed): lean-ctx config set path_jail_scope home — \
351 or only this one: lean-ctx allow-path {}{TAIL}",
352 candidate.display(),
353 root.display(),
354 suggestion.display()
355 );
356 }
357 format!(
358 ". {} is outside the active project ({}) and outside your home directory. To \
359 allow it: lean-ctx allow-path {}{TAIL}",
360 candidate.display(),
361 root.display(),
362 suggestion.display()
363 )
364}
365
366fn default_notice_text() -> String {
368 "\x1b[1mPathJail now opens your home directory:\x1b[0m agents may read and write \
369 anything below ~ except protected locations (~/.ssh, ~/.aws, ~/.config, every other \
370 dot folder, ~/Library, ~/AppData).\n \x1b[2mPrevious behaviour (other projects \
371 read-only): lean-ctx config set path_jail_scope projects · active project only: \
372 lean-ctx config set path_jail_scope project\x1b[0m\n"
373 .to_string()
374}
375
376pub fn maybe_show_default_notice() {
380 use std::io::IsTerminal;
381 if !(std::io::stdin().is_terminal() && std::io::stderr().is_terminal())
382 || PathJailScope::explicit().is_some()
383 || crate::core::config::Config::load().path_jail == Some(false)
384 {
385 return;
386 }
387 let Ok(marker) =
388 crate::core::paths::state_dir().map(|dir| dir.join("path_jail_home_default_notice"))
389 else {
390 return;
391 };
392 if marker.exists() {
393 return;
394 }
395 eprint!("{}", default_notice_text());
396 eprintln!();
397 if let Some(parent) = marker.parent() {
398 let _ = std::fs::create_dir_all(parent);
399 }
400 let _ = std::fs::write(marker, "1\n");
401}
402
403#[cfg(test)]
404mod tests {
405 use super::*;
406
407 #[test]
408 fn parse_accepts_canonical_names_and_aliases() {
409 assert_eq!(PathJailScope::parse("home"), Some(PathJailScope::Home));
410 assert_eq!(
411 PathJailScope::parse(" Project "),
412 Some(PathJailScope::Project)
413 );
414 assert_eq!(PathJailScope::parse("strict"), Some(PathJailScope::Project));
415 assert_eq!(
416 PathJailScope::parse("projects"),
417 Some(PathJailScope::Projects)
418 );
419 assert_eq!(PathJailScope::parse("anything"), None);
420 assert_eq!(PathJailScope::default(), PathJailScope::Home);
421 for s in [
422 PathJailScope::Home,
423 PathJailScope::Projects,
424 PathJailScope::Project,
425 ] {
426 assert_eq!(PathJailScope::parse(s.as_str()), Some(s));
427 }
428 }
429
430 #[test]
431 fn the_notice_names_the_protected_zones_and_both_ways_back() {
432 let text = default_notice_text();
433 for needle in [
434 "~/.ssh",
435 "~/.aws",
436 "~/Library",
437 "path_jail_scope projects",
438 "path_jail_scope project",
439 ] {
440 assert!(text.contains(needle), "{needle}");
441 }
442 }
443
444 #[test]
445 fn home_zone_admits_code_and_protects_secrets() {
446 let home = Path::new("/home/u");
447 assert!(admits_below(Path::new("/home/u/code/repo/src/a.rs"), home));
448 assert!(admits_below(Path::new("/home/u/Documents/p"), home));
449
450 for protected in [
451 "/home/u/.ssh/id_ed25519",
452 "/home/u/.aws/credentials",
453 "/home/u/.config/gh/hosts.yml",
454 "/home/u/.zshrc",
455 "/home/u/.claude/projects/x/session.jsonl",
456 "/home/u/Library/Keychains/login.keychain-db",
457 "/home/u/AppData/Roaming/x",
458 "/home/u/NTUSER.DAT",
459 ] {
460 assert!(!admits_below(Path::new(protected), home), "{protected}");
461 assert!(protected_zone_in(Path::new(protected), home).is_some());
462 }
463 assert!(!admits_below(home, home));
465 assert!(!admits_below(Path::new("/etc/passwd"), home));
466 assert!(!admits_below(Path::new("/home/user2/x"), home));
467 }
468
469 #[test]
470 fn protected_zone_is_the_top_level_entry() {
471 let home = Path::new("/home/u");
472 assert_eq!(
473 protected_zone_in(Path::new("/home/u/.config/gh/hosts.yml"), home),
474 Some(PathBuf::from("/home/u/.config"))
475 );
476 assert_eq!(
478 protected_zone_in(Path::new("/home/u/code/repo/.git/HEAD"), home),
479 None
480 );
481 }
482
483 #[cfg(all(unix, not(feature = "no-jail")))]
488 #[test]
489 fn jail_admits_sibling_projects_but_not_protected_zones() {
490 let _iso = crate::core::data_dir::isolated_data_dir();
491 let tmp = tempfile::tempdir().unwrap();
492 let home = super::super::pathjail::canonicalize_secure(tmp.path()).join("home");
493 let (a, b, ssh) = (home.join("code/a"), home.join("code/b"), home.join(".ssh"));
494 for dir in [&a, &b, &ssh] {
495 std::fs::create_dir_all(dir).unwrap();
496 }
497 std::fs::create_dir_all(a.join(".git")).unwrap();
498 std::fs::write(b.join("Cargo.toml"), "[package]").unwrap();
499 std::fs::create_dir_all(b.join("src")).unwrap();
500 std::fs::write(b.join("src/lib.rs"), "x").unwrap();
501 std::fs::write(b.join("lib.rs"), "x").unwrap();
502 std::fs::write(ssh.join("id_ed25519"), "secret").unwrap();
503 let docs = home.join("Documents/Steuern");
504 std::fs::create_dir_all(&docs).unwrap();
505 std::fs::write(docs.join("2025.pdf"), "private").unwrap();
506 let outside = tmp.path().join("outside.txt");
507 std::fs::write(&outside, "x").unwrap();
508
509 let old_home = std::env::var_os("HOME");
510 crate::test_env::set_var("HOME", &home);
511 crate::test_env::remove_var("LEAN_CTX_PATH_JAIL_SCOPE");
512 let jail = super::super::pathjail::jail_path;
513
514 assert!(
515 jail(&b.join("lib.rs"), &a).is_ok(),
516 "sibling project under ~"
517 );
518 assert!(
519 jail(&b.join("src/lib.rs"), &a).is_ok(),
520 "nested file of a sibling project"
521 );
522 assert!(
524 jail(&docs.join("2025.pdf"), &a).is_ok(),
525 "loose file under ~"
526 );
527 assert!(jail(&docs, &a).is_ok(), "a folder without a project");
528 assert!(jail(&home.join("code"), &a).is_ok(), "parent of projects");
529 let err = jail(&ssh.join("id_ed25519"), &a).unwrap_err().to_string();
530 assert!(err.contains("protected location"), "{err}");
531 let err = jail(&outside, &a).unwrap_err().to_string();
532 assert!(err.contains("outside your home directory"), "{err}");
533 let err = jail(&home, &a).unwrap_err().to_string();
534 assert!(err.contains("not a project root"), "{err}");
535
536 assert!(
539 jail(&ssh.join("id_ed25519"), &home).is_err(),
540 "zone is a deny"
541 );
542 assert!(
543 jail(&ssh.join("id_ed25519"), &ssh).is_ok(),
544 "root inside the zone"
545 );
546
547 let write = super::super::pathjail::enforce_writable;
550 assert!(write(&b.join("lib.rs")).is_ok(), "another project");
551 assert!(write(&docs.join("notes.md")).is_ok(), "a loose folder");
552 assert!(
553 jail(&ssh.join("authorized_keys"), &a).is_err(),
554 "protected zone"
555 );
556
557 crate::test_env::set_var("LEAN_CTX_PATH_JAIL_SCOPE", "projects");
559 assert!(jail(&b.join("lib.rs"), &a).is_ok(), "sibling project");
560 let err = jail(&docs.join("2025.pdf"), &a).unwrap_err().to_string();
561 assert!(err.contains("not inside a project"), "{err}");
562 assert!(jail(&home.join("code"), &a).is_err(), "parent of projects");
563 let err = write(&b.join("lib.rs")).unwrap_err();
564 assert!(
565 err.contains("for reading only") && err.contains("allow-path"),
566 "{err}"
567 );
568 assert!(write(&b.join(".git/hooks/pre-commit")).is_err());
569 register_session_root(&b.to_string_lossy());
570 assert!(write(&b.join("lib.rs")).is_ok(), "session root is writable");
571
572 crate::test_env::set_var("LEAN_CTX_PATH_JAIL_SCOPE", "project");
573 let err = jail(&b.join("lib.rs"), &a).unwrap_err().to_string();
574 assert!(
575 err.contains("path_jail_scope home") && err.contains("allow-path"),
576 "{err}"
577 );
578 crate::test_env::remove_var("LEAN_CTX_PATH_JAIL_SCOPE");
579
580 crate::test_env::set_var("HOME", "/");
582 assert!(
583 jail(&b.join("lib.rs"), &a).is_err(),
584 "HOME=/ falls back to the project"
585 );
586
587 match old_home {
588 Some(h) => crate::test_env::set_var("HOME", h),
589 None => crate::test_env::remove_var("HOME"),
590 }
591 }
592
593 #[test]
594 fn suggestion_prefers_the_enclosing_project() {
595 let tmp = tempfile::tempdir().unwrap();
596 let repo = tmp.path().join("repo");
597 std::fs::create_dir_all(repo.join("src/deep")).unwrap();
598 std::fs::create_dir_all(repo.join(".git")).unwrap();
599 let file = repo.join("src/deep/a.rs");
600 std::fs::write(&file, "x").unwrap();
601 assert_eq!(suggested_allow_dir(&file, None), repo);
602
603 let loose = tmp.path().join("loose");
604 std::fs::create_dir_all(&loose).unwrap();
605 assert_eq!(suggested_allow_dir(&loose, Some(tmp.path())), loose);
606 }
607}