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 protected_zone_permits(base: &Path, root: &Path, allow: &[PathBuf]) -> bool {
193 let Some(zone) = zone_home().and_then(|home| protected_zone_in(base, &home)) else {
194 return true;
195 };
196 (root.starts_with(&zone) && base.starts_with(root))
197 || allow
198 .iter()
199 .any(|p| p.starts_with(&zone) && base.starts_with(p))
200}
201
202fn session_write_roots() -> &'static std::sync::Mutex<Vec<PathBuf>> {
203 static ROOTS: std::sync::OnceLock<std::sync::Mutex<Vec<PathBuf>>> = std::sync::OnceLock::new();
204 ROOTS.get_or_init(|| std::sync::Mutex::new(Vec::new()))
205}
206
207pub fn register_session_root(root: &str) {
210 if root.trim().is_empty() {
211 return;
212 }
213 let path = super::pathjail::canonicalize_secure(Path::new(root));
214 if crate::core::pathutil::is_broad_or_unsafe_root(&path) {
215 return;
216 }
217 let mut roots = session_write_roots()
218 .lock()
219 .unwrap_or_else(std::sync::PoisonError::into_inner);
220 if roots.iter().any(|r| r == &path) {
221 return;
222 }
223 if roots.len() >= MAX_SESSION_WRITE_ROOTS {
224 roots.remove(0);
225 }
226 roots.push(path);
227}
228
229pub(crate) fn home_scope_write_denial(target: &Path) -> Option<String> {
236 if PathJailScope::resolve() != PathJailScope::Projects {
237 return None;
238 }
239 let home = scope_home()?;
240 if !admits_below(target, &home) {
241 return None;
242 }
243 let mut writable: Vec<PathBuf> = session_write_roots()
244 .lock()
245 .unwrap_or_else(std::sync::PoisonError::into_inner)
246 .clone();
247 writable.extend(super::pathjail::allow_paths_from_env_and_config());
248 if let Ok(state) = crate::core::paths::state_dir() {
249 writable.push(super::pathjail::canonicalize_secure(&state));
250 }
251 if let Ok(cwd) = std::env::current_dir() {
254 let cwd = super::pathjail::canonicalize_secure(&cwd);
255 if !crate::core::pathutil::is_broad_or_unsafe_root(&cwd) {
256 writable.push(cwd);
257 }
258 }
259 if writable.iter().any(|w| target.starts_with(w)) {
260 return None;
261 }
262 Some(format!(
263 "{} is outside the active project — path_jail_scope = projects opens other \
264 projects for reading only. To allow writes there, the user runs in their terminal: \
265 lean-ctx allow-path {} — or `lean-ctx config set path_jail_scope home` for all of ~ \
266 — takes effect immediately, no restart.",
267 target.display(),
268 suggested_allow_dir(target, Some(&home)).display()
269 ))
270}
271
272fn suggested_allow_dir(path: &Path, home: Option<&Path>) -> PathBuf {
277 let start = if path.is_dir() {
278 path.to_path_buf()
279 } else {
280 path.parent().unwrap_or(path).to_path_buf()
281 };
282 let mut cur = start.as_path();
283 loop {
284 if home.is_some_and(|h| cur == h) || cur.parent().is_none() {
285 break;
286 }
287 if crate::core::pathutil::has_project_marker(cur) {
288 return cur.to_path_buf();
289 }
290 match cur.parent() {
291 Some(p) => cur = p,
292 None => break,
293 }
294 }
295 start
296}
297
298pub(crate) fn escape_hint(candidate: &Path, base: &Path, root: &Path) -> String {
303 const TAIL: &str = " — the user runs this in their own terminal; it takes effect \
304 immediately, no restart.";
305 let home = zone_home();
306
307 if home.as_deref() == Some(base) {
308 return ". Your home directory itself is not a project root — it holds ~/.ssh, \
309 ~/Library and other protected locations. Point the tool at a project \
310 below it."
311 .to_string();
312 }
313 if let Some(zone) = home.as_deref().and_then(|h| protected_zone_in(base, h)) {
314 let dir = if base.is_dir() {
316 base
317 } else {
318 base.parent().unwrap_or(base)
319 };
320 return format!(
321 ". {} is a protected location (credentials and other programs' private data \
322 stay jailed). To allow it anyway: lean-ctx allow-path {}{TAIL}",
323 zone.display(),
324 dir.display()
325 );
326 }
327
328 let suggestion = suggested_allow_dir(base, home.as_deref());
329 let under_home = scope_home().is_some_and(|h| admits_below(base, &h));
330 if under_home && PathJailScope::resolve() == PathJailScope::Projects {
332 return format!(
333 ". {} is in your home directory but not inside a project (no .git, Cargo.toml, \
334 package.json, … above it), so path_jail_scope = projects does not open it. To \
335 allow it: lean-ctx allow-path {} — or all of ~: lean-ctx config set \
336 path_jail_scope home{TAIL}",
337 candidate.display(),
338 suggestion.display()
339 );
340 }
341 if under_home {
342 return format!(
343 ". {} is outside the active project ({}). Allow your whole home directory \
344 (protected locations stay jailed): lean-ctx config set path_jail_scope home — \
345 or only this one: lean-ctx allow-path {}{TAIL}",
346 candidate.display(),
347 root.display(),
348 suggestion.display()
349 );
350 }
351 format!(
352 ". {} is outside the active project ({}) and outside your home directory. To \
353 allow it: lean-ctx allow-path {}{TAIL}",
354 candidate.display(),
355 root.display(),
356 suggestion.display()
357 )
358}
359
360fn default_notice_text() -> String {
362 "\x1b[1mPathJail now opens your home directory:\x1b[0m agents may read and write \
363 anything below ~ except protected locations (~/.ssh, ~/.aws, ~/.config, every other \
364 dot folder, ~/Library, ~/AppData).\n \x1b[2mPrevious behaviour (other projects \
365 read-only): lean-ctx config set path_jail_scope projects · active project only: \
366 lean-ctx config set path_jail_scope project\x1b[0m\n"
367 .to_string()
368}
369
370pub fn maybe_show_default_notice() {
374 use std::io::IsTerminal;
375 if !(std::io::stdin().is_terminal() && std::io::stderr().is_terminal())
376 || PathJailScope::explicit().is_some()
377 || crate::core::config::Config::load().path_jail == Some(false)
378 {
379 return;
380 }
381 let Ok(marker) =
382 crate::core::paths::state_dir().map(|dir| dir.join("path_jail_home_default_notice"))
383 else {
384 return;
385 };
386 if marker.exists() {
387 return;
388 }
389 eprint!("{}", default_notice_text());
390 eprintln!();
391 if let Some(parent) = marker.parent() {
392 let _ = std::fs::create_dir_all(parent);
393 }
394 let _ = std::fs::write(marker, "1\n");
395}
396
397#[cfg(test)]
398mod tests {
399 use super::*;
400
401 #[test]
402 fn parse_accepts_canonical_names_and_aliases() {
403 assert_eq!(PathJailScope::parse("home"), Some(PathJailScope::Home));
404 assert_eq!(
405 PathJailScope::parse(" Project "),
406 Some(PathJailScope::Project)
407 );
408 assert_eq!(PathJailScope::parse("strict"), Some(PathJailScope::Project));
409 assert_eq!(
410 PathJailScope::parse("projects"),
411 Some(PathJailScope::Projects)
412 );
413 assert_eq!(PathJailScope::parse("anything"), None);
414 assert_eq!(PathJailScope::default(), PathJailScope::Home);
415 for s in [
416 PathJailScope::Home,
417 PathJailScope::Projects,
418 PathJailScope::Project,
419 ] {
420 assert_eq!(PathJailScope::parse(s.as_str()), Some(s));
421 }
422 }
423
424 #[test]
425 fn the_notice_names_the_protected_zones_and_both_ways_back() {
426 let text = default_notice_text();
427 for needle in [
428 "~/.ssh",
429 "~/.aws",
430 "~/Library",
431 "path_jail_scope projects",
432 "path_jail_scope project",
433 ] {
434 assert!(text.contains(needle), "{needle}");
435 }
436 }
437
438 #[test]
439 fn home_zone_admits_code_and_protects_secrets() {
440 let home = Path::new("/home/u");
441 assert!(admits_below(Path::new("/home/u/code/repo/src/a.rs"), home));
442 assert!(admits_below(Path::new("/home/u/Documents/p"), home));
443
444 for protected in [
445 "/home/u/.ssh/id_ed25519",
446 "/home/u/.aws/credentials",
447 "/home/u/.config/gh/hosts.yml",
448 "/home/u/.zshrc",
449 "/home/u/.claude/projects/x/session.jsonl",
450 "/home/u/Library/Keychains/login.keychain-db",
451 "/home/u/AppData/Roaming/x",
452 "/home/u/NTUSER.DAT",
453 ] {
454 assert!(!admits_below(Path::new(protected), home), "{protected}");
455 assert!(protected_zone_in(Path::new(protected), home).is_some());
456 }
457 assert!(!admits_below(home, home));
459 assert!(!admits_below(Path::new("/etc/passwd"), home));
460 assert!(!admits_below(Path::new("/home/user2/x"), home));
461 }
462
463 #[test]
464 fn protected_zone_is_the_top_level_entry() {
465 let home = Path::new("/home/u");
466 assert_eq!(
467 protected_zone_in(Path::new("/home/u/.config/gh/hosts.yml"), home),
468 Some(PathBuf::from("/home/u/.config"))
469 );
470 assert_eq!(
472 protected_zone_in(Path::new("/home/u/code/repo/.git/HEAD"), home),
473 None
474 );
475 }
476
477 #[cfg(all(unix, not(feature = "no-jail")))]
482 #[test]
483 fn jail_admits_sibling_projects_but_not_protected_zones() {
484 let _iso = crate::core::data_dir::isolated_data_dir();
485 let tmp = tempfile::tempdir().unwrap();
486 let home = super::super::pathjail::canonicalize_secure(tmp.path()).join("home");
487 let (a, b, ssh) = (home.join("code/a"), home.join("code/b"), home.join(".ssh"));
488 for dir in [&a, &b, &ssh] {
489 std::fs::create_dir_all(dir).unwrap();
490 }
491 std::fs::create_dir_all(a.join(".git")).unwrap();
492 std::fs::write(b.join("Cargo.toml"), "[package]").unwrap();
493 std::fs::create_dir_all(b.join("src")).unwrap();
494 std::fs::write(b.join("src/lib.rs"), "x").unwrap();
495 std::fs::write(b.join("lib.rs"), "x").unwrap();
496 std::fs::write(ssh.join("id_ed25519"), "secret").unwrap();
497 let docs = home.join("Documents/Steuern");
498 std::fs::create_dir_all(&docs).unwrap();
499 std::fs::write(docs.join("2025.pdf"), "private").unwrap();
500 let outside = tmp.path().join("outside.txt");
501 std::fs::write(&outside, "x").unwrap();
502
503 let old_home = std::env::var_os("HOME");
504 crate::test_env::set_var("HOME", &home);
505 crate::test_env::remove_var("LEAN_CTX_PATH_JAIL_SCOPE");
506 let jail = super::super::pathjail::jail_path;
507
508 assert!(
509 jail(&b.join("lib.rs"), &a).is_ok(),
510 "sibling project under ~"
511 );
512 assert!(
513 jail(&b.join("src/lib.rs"), &a).is_ok(),
514 "nested file of a sibling project"
515 );
516 assert!(
518 jail(&docs.join("2025.pdf"), &a).is_ok(),
519 "loose file under ~"
520 );
521 assert!(jail(&docs, &a).is_ok(), "a folder without a project");
522 assert!(jail(&home.join("code"), &a).is_ok(), "parent of projects");
523 let err = jail(&ssh.join("id_ed25519"), &a).unwrap_err().to_string();
524 assert!(err.contains("protected location"), "{err}");
525 let err = jail(&outside, &a).unwrap_err().to_string();
526 assert!(err.contains("outside your home directory"), "{err}");
527 let err = jail(&home, &a).unwrap_err().to_string();
528 assert!(err.contains("not a project root"), "{err}");
529
530 assert!(
533 jail(&ssh.join("id_ed25519"), &home).is_err(),
534 "zone is a deny"
535 );
536 assert!(
537 jail(&ssh.join("id_ed25519"), &ssh).is_ok(),
538 "root inside the zone"
539 );
540
541 let write = super::super::pathjail::enforce_writable;
544 assert!(write(&b.join("lib.rs")).is_ok(), "another project");
545 assert!(write(&docs.join("notes.md")).is_ok(), "a loose folder");
546 assert!(
547 jail(&ssh.join("authorized_keys"), &a).is_err(),
548 "protected zone"
549 );
550
551 crate::test_env::set_var("LEAN_CTX_PATH_JAIL_SCOPE", "projects");
553 assert!(jail(&b.join("lib.rs"), &a).is_ok(), "sibling project");
554 let err = jail(&docs.join("2025.pdf"), &a).unwrap_err().to_string();
555 assert!(err.contains("not inside a project"), "{err}");
556 assert!(jail(&home.join("code"), &a).is_err(), "parent of projects");
557 let err = write(&b.join("lib.rs")).unwrap_err();
558 assert!(
559 err.contains("for reading only") && err.contains("allow-path"),
560 "{err}"
561 );
562 assert!(write(&b.join(".git/hooks/pre-commit")).is_err());
563 register_session_root(&b.to_string_lossy());
564 assert!(write(&b.join("lib.rs")).is_ok(), "session root is writable");
565
566 crate::test_env::set_var("LEAN_CTX_PATH_JAIL_SCOPE", "project");
567 let err = jail(&b.join("lib.rs"), &a).unwrap_err().to_string();
568 assert!(
569 err.contains("path_jail_scope home") && err.contains("allow-path"),
570 "{err}"
571 );
572 crate::test_env::remove_var("LEAN_CTX_PATH_JAIL_SCOPE");
573
574 crate::test_env::set_var("HOME", "/");
576 assert!(
577 jail(&b.join("lib.rs"), &a).is_err(),
578 "HOME=/ falls back to the project"
579 );
580
581 match old_home {
582 Some(h) => crate::test_env::set_var("HOME", h),
583 None => crate::test_env::remove_var("HOME"),
584 }
585 }
586
587 #[test]
588 fn suggestion_prefers_the_enclosing_project() {
589 let tmp = tempfile::tempdir().unwrap();
590 let repo = tmp.path().join("repo");
591 std::fs::create_dir_all(repo.join("src/deep")).unwrap();
592 std::fs::create_dir_all(repo.join(".git")).unwrap();
593 let file = repo.join("src/deep/a.rs");
594 std::fs::write(&file, "x").unwrap();
595 assert_eq!(suggested_allow_dir(&file, None), repo);
596
597 let loose = tmp.path().join("loose");
598 std::fs::create_dir_all(&loose).unwrap();
599 assert_eq!(suggested_allow_dir(&loose, Some(tmp.path())), loose);
600 }
601}