1use std::path::{Path, PathBuf};
29
30const PROTECTED_HOME_DIRS: &[&str] = &["Library", "AppData", "snap"];
34
35const MAX_SESSION_WRITE_ROOTS: usize = 64;
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
40pub enum PathJailScope {
41 #[default]
43 Home,
44 Project,
46}
47
48impl PathJailScope {
49 pub fn parse(value: &str) -> Option<Self> {
51 match value.trim().to_ascii_lowercase().as_str() {
52 "home" | "user" | "workspace" => Some(Self::Home),
53 "project" | "strict" | "root" => Some(Self::Project),
54 _ => None,
55 }
56 }
57
58 pub fn as_str(self) -> &'static str {
59 match self {
60 Self::Home => "home",
61 Self::Project => "project",
62 }
63 }
64
65 pub fn resolve() -> Self {
67 if let Ok(raw) = std::env::var("LEAN_CTX_PATH_JAIL_SCOPE")
68 && let Some(scope) = Self::parse(&raw)
69 {
70 return scope;
71 }
72 crate::core::config::Config::load()
73 .path_jail_scope
74 .as_deref()
75 .and_then(Self::parse)
76 .unwrap_or_default()
77 }
78}
79
80fn zone_home() -> Option<PathBuf> {
83 let home = super::pathjail::canonicalize_secure(&dirs::home_dir()?);
84 home.parent().is_some().then_some(home)
85}
86
87fn scope_home() -> Option<PathBuf> {
93 let home = zone_home()?;
94 let depth = home
95 .components()
96 .filter(|c| matches!(c, std::path::Component::Normal(_)))
97 .count();
98 if depth < 2 {
99 return None;
100 }
101 #[cfg(unix)]
102 {
103 use std::os::unix::fs::MetadataExt;
104 if std::fs::metadata(&home).ok()?.uid() != unsafe { libc::geteuid() } {
106 return None;
107 }
108 }
109 Some(home)
110}
111
112fn first_component_below<'a>(path: &'a Path, home: &Path) -> Option<&'a std::ffi::OsStr> {
114 path.strip_prefix(home)
115 .ok()?
116 .components()
117 .next()
118 .map(std::path::Component::as_os_str)
119}
120
121fn protected_zone_in(path: &Path, home: &Path) -> Option<PathBuf> {
124 let first = first_component_below(path, home)?;
125 let name = first.to_string_lossy();
126 let protected = name.starts_with('.')
128 || name.to_ascii_lowercase().starts_with("ntuser.")
129 || PROTECTED_HOME_DIRS
130 .iter()
131 .any(|d| name.eq_ignore_ascii_case(d));
132 protected.then(|| home.join(first))
133}
134
135pub(crate) fn home_scope_admits(base: &Path) -> bool {
146 if PathJailScope::resolve() != PathJailScope::Home {
147 return false;
148 }
149 let Some(home) = scope_home() else {
150 return false;
151 };
152 admits_below(base, &home) && project_containing(base, &home).is_some()
153}
154
155fn admits_below(base: &Path, home: &Path) -> bool {
156 first_component_below(base, home).is_some() && protected_zone_in(base, home).is_none()
157}
158
159fn project_containing(path: &Path, home: &Path) -> Option<PathBuf> {
164 let mut cur = if path.is_dir() { path } else { path.parent()? };
165 while cur != home && cur.starts_with(home) {
166 if crate::core::pathutil::has_project_marker(cur) {
167 return Some(cur.to_path_buf());
168 }
169 cur = cur.parent()?;
170 }
171 None
172}
173
174pub(crate) fn protected_zone_permits(base: &Path, root: &Path, allow: &[PathBuf]) -> bool {
181 let Some(zone) = zone_home().and_then(|home| protected_zone_in(base, &home)) else {
182 return true;
183 };
184 (root.starts_with(&zone) && base.starts_with(root))
185 || allow
186 .iter()
187 .any(|p| p.starts_with(&zone) && base.starts_with(p))
188}
189
190fn session_write_roots() -> &'static std::sync::Mutex<Vec<PathBuf>> {
191 static ROOTS: std::sync::OnceLock<std::sync::Mutex<Vec<PathBuf>>> = std::sync::OnceLock::new();
192 ROOTS.get_or_init(|| std::sync::Mutex::new(Vec::new()))
193}
194
195pub fn register_session_root(root: &str) {
198 if root.trim().is_empty() {
199 return;
200 }
201 let path = super::pathjail::canonicalize_secure(Path::new(root));
202 if crate::core::pathutil::is_broad_or_unsafe_root(&path) {
203 return;
204 }
205 let mut roots = session_write_roots()
206 .lock()
207 .unwrap_or_else(std::sync::PoisonError::into_inner);
208 if roots.iter().any(|r| r == &path) {
209 return;
210 }
211 if roots.len() >= MAX_SESSION_WRITE_ROOTS {
212 roots.remove(0);
213 }
214 roots.push(path);
215}
216
217pub(crate) fn home_scope_write_denial(target: &Path) -> Option<String> {
224 if PathJailScope::resolve() != PathJailScope::Home {
225 return None;
226 }
227 let home = scope_home()?;
228 if !admits_below(target, &home) {
229 return None;
230 }
231 let mut writable: Vec<PathBuf> = session_write_roots()
232 .lock()
233 .unwrap_or_else(std::sync::PoisonError::into_inner)
234 .clone();
235 writable.extend(super::pathjail::allow_paths_from_env_and_config());
236 if let Ok(state) = crate::core::paths::state_dir() {
237 writable.push(super::pathjail::canonicalize_secure(&state));
238 }
239 if let Ok(cwd) = std::env::current_dir() {
242 let cwd = super::pathjail::canonicalize_secure(&cwd);
243 if !crate::core::pathutil::is_broad_or_unsafe_root(&cwd) {
244 writable.push(cwd);
245 }
246 }
247 if writable.iter().any(|w| target.starts_with(w)) {
248 return None;
249 }
250 Some(format!(
251 "{} is outside the active project — path_jail_scope = home opens other projects \
252 for reading only. To allow writes there, the user runs in their terminal: \
253 lean-ctx allow-path {} — takes effect immediately, no restart.",
254 target.display(),
255 suggested_allow_dir(target, Some(&home)).display()
256 ))
257}
258
259fn suggested_allow_dir(path: &Path, home: Option<&Path>) -> PathBuf {
264 let start = if path.is_dir() {
265 path.to_path_buf()
266 } else {
267 path.parent().unwrap_or(path).to_path_buf()
268 };
269 let mut cur = start.as_path();
270 loop {
271 if home.is_some_and(|h| cur == h) || cur.parent().is_none() {
272 break;
273 }
274 if crate::core::pathutil::has_project_marker(cur) {
275 return cur.to_path_buf();
276 }
277 match cur.parent() {
278 Some(p) => cur = p,
279 None => break,
280 }
281 }
282 start
283}
284
285pub(crate) fn escape_hint(candidate: &Path, base: &Path, root: &Path) -> String {
290 const TAIL: &str = " — the user runs this in their own terminal; it takes effect \
291 immediately, no restart.";
292 let home = zone_home();
293
294 if home.as_deref() == Some(base) {
295 return ". Your home directory itself is not a project root — it holds ~/.ssh, \
296 ~/Library and other protected locations. Point the tool at a project \
297 below it."
298 .to_string();
299 }
300 if let Some(zone) = home.as_deref().and_then(|h| protected_zone_in(base, h)) {
301 let dir = if base.is_dir() {
303 base
304 } else {
305 base.parent().unwrap_or(base)
306 };
307 return format!(
308 ". {} is a protected location (credentials and other programs' private data \
309 stay jailed). To allow it anyway: lean-ctx allow-path {}{TAIL}",
310 zone.display(),
311 dir.display()
312 );
313 }
314
315 let suggestion = suggested_allow_dir(base, home.as_deref());
316 let under_home = scope_home().is_some_and(|h| admits_below(base, &h));
317 if under_home && PathJailScope::resolve() == PathJailScope::Home {
319 return format!(
320 ". {} is in your home directory but not inside a project (no .git, Cargo.toml, \
321 package.json, … above it), so the home scope does not open it — loose \
322 personal files stay private. To allow it: lean-ctx allow-path {}{TAIL}",
323 candidate.display(),
324 suggestion.display()
325 );
326 }
327 if under_home {
328 return format!(
329 ". {} is outside the active project ({}). Allow every project in your home \
330 directory: lean-ctx config set path_jail_scope home — or only this one: \
331 lean-ctx allow-path {}{TAIL}",
332 candidate.display(),
333 root.display(),
334 suggestion.display()
335 );
336 }
337 format!(
338 ". {} is outside the active project ({}) and outside your home directory. To \
339 allow it: lean-ctx allow-path {}{TAIL}",
340 candidate.display(),
341 root.display(),
342 suggestion.display()
343 )
344}
345
346#[cfg(test)]
347mod tests {
348 use super::*;
349
350 #[test]
351 fn parse_accepts_canonical_names_and_aliases() {
352 assert_eq!(PathJailScope::parse("home"), Some(PathJailScope::Home));
353 assert_eq!(
354 PathJailScope::parse(" Project "),
355 Some(PathJailScope::Project)
356 );
357 assert_eq!(PathJailScope::parse("strict"), Some(PathJailScope::Project));
358 assert_eq!(PathJailScope::parse("anything"), None);
359 assert_eq!(PathJailScope::default(), PathJailScope::Home);
360 for s in [PathJailScope::Home, PathJailScope::Project] {
361 assert_eq!(PathJailScope::parse(s.as_str()), Some(s));
362 }
363 }
364
365 #[test]
366 fn home_zone_admits_code_and_protects_secrets() {
367 let home = Path::new("/home/u");
368 assert!(admits_below(Path::new("/home/u/code/repo/src/a.rs"), home));
369 assert!(admits_below(Path::new("/home/u/Documents/p"), home));
370
371 for protected in [
372 "/home/u/.ssh/id_ed25519",
373 "/home/u/.aws/credentials",
374 "/home/u/.config/gh/hosts.yml",
375 "/home/u/.zshrc",
376 "/home/u/.claude/projects/x/session.jsonl",
377 "/home/u/Library/Keychains/login.keychain-db",
378 "/home/u/AppData/Roaming/x",
379 "/home/u/NTUSER.DAT",
380 ] {
381 assert!(!admits_below(Path::new(protected), home), "{protected}");
382 assert!(protected_zone_in(Path::new(protected), home).is_some());
383 }
384 assert!(!admits_below(home, home));
386 assert!(!admits_below(Path::new("/etc/passwd"), home));
387 assert!(!admits_below(Path::new("/home/user2/x"), home));
388 }
389
390 #[test]
391 fn protected_zone_is_the_top_level_entry() {
392 let home = Path::new("/home/u");
393 assert_eq!(
394 protected_zone_in(Path::new("/home/u/.config/gh/hosts.yml"), home),
395 Some(PathBuf::from("/home/u/.config"))
396 );
397 assert_eq!(
399 protected_zone_in(Path::new("/home/u/code/repo/.git/HEAD"), home),
400 None
401 );
402 }
403
404 #[cfg(all(unix, not(feature = "no-jail")))]
408 #[test]
409 fn jail_admits_sibling_projects_but_not_protected_zones() {
410 let _iso = crate::core::data_dir::isolated_data_dir();
411 let tmp = tempfile::tempdir().unwrap();
412 let home = super::super::pathjail::canonicalize_secure(tmp.path()).join("home");
413 let (a, b, ssh) = (home.join("code/a"), home.join("code/b"), home.join(".ssh"));
414 for dir in [&a, &b, &ssh] {
415 std::fs::create_dir_all(dir).unwrap();
416 }
417 std::fs::create_dir_all(a.join(".git")).unwrap();
418 std::fs::write(b.join("Cargo.toml"), "[package]").unwrap();
419 std::fs::create_dir_all(b.join("src")).unwrap();
420 std::fs::write(b.join("src/lib.rs"), "x").unwrap();
421 std::fs::write(b.join("lib.rs"), "x").unwrap();
422 std::fs::write(ssh.join("id_ed25519"), "secret").unwrap();
423 let docs = home.join("Documents/Steuern");
424 std::fs::create_dir_all(&docs).unwrap();
425 std::fs::write(docs.join("2025.pdf"), "private").unwrap();
426 let outside = tmp.path().join("outside.txt");
427 std::fs::write(&outside, "x").unwrap();
428
429 let old_home = std::env::var_os("HOME");
430 crate::test_env::set_var("HOME", &home);
431 crate::test_env::remove_var("LEAN_CTX_PATH_JAIL_SCOPE");
432 let jail = super::super::pathjail::jail_path;
433
434 assert!(
435 jail(&b.join("lib.rs"), &a).is_ok(),
436 "sibling project under ~"
437 );
438 assert!(
439 jail(&b.join("src/lib.rs"), &a).is_ok(),
440 "nested file of a sibling project"
441 );
442 let err = jail(&docs.join("2025.pdf"), &a).unwrap_err().to_string();
445 assert!(err.contains("not inside a project"), "{err}");
446 assert!(jail(&docs, &a).is_err(), "a folder without a project");
447 assert!(jail(&home.join("code"), &a).is_err(), "parent of projects");
448 let err = jail(&ssh.join("id_ed25519"), &a).unwrap_err().to_string();
449 assert!(err.contains("protected location"), "{err}");
450 let err = jail(&outside, &a).unwrap_err().to_string();
451 assert!(err.contains("outside your home directory"), "{err}");
452 let err = jail(&home, &a).unwrap_err().to_string();
453 assert!(err.contains("not a project root"), "{err}");
454
455 assert!(
458 jail(&ssh.join("id_ed25519"), &home).is_err(),
459 "zone is a deny"
460 );
461 assert!(
462 jail(&ssh.join("id_ed25519"), &ssh).is_ok(),
463 "root inside the zone"
464 );
465
466 let write = super::super::pathjail::enforce_writable;
468 let err = write(&b.join("lib.rs")).unwrap_err();
469 assert!(
470 err.contains("for reading only") && err.contains("allow-path"),
471 "{err}"
472 );
473 assert!(write(&b.join(".git/hooks/pre-commit")).is_err());
474 register_session_root(&b.to_string_lossy());
475 assert!(write(&b.join("lib.rs")).is_ok(), "session root is writable");
476
477 crate::test_env::set_var("LEAN_CTX_PATH_JAIL_SCOPE", "project");
478 let err = jail(&b.join("lib.rs"), &a).unwrap_err().to_string();
479 assert!(
480 err.contains("path_jail_scope home") && err.contains("allow-path"),
481 "{err}"
482 );
483 crate::test_env::remove_var("LEAN_CTX_PATH_JAIL_SCOPE");
484
485 crate::test_env::set_var("HOME", "/");
487 assert!(
488 jail(&b.join("lib.rs"), &a).is_err(),
489 "HOME=/ falls back to the project"
490 );
491
492 match old_home {
493 Some(h) => crate::test_env::set_var("HOME", h),
494 None => crate::test_env::remove_var("HOME"),
495 }
496 }
497
498 #[test]
499 fn suggestion_prefers_the_enclosing_project() {
500 let tmp = tempfile::tempdir().unwrap();
501 let repo = tmp.path().join("repo");
502 std::fs::create_dir_all(repo.join("src/deep")).unwrap();
503 std::fs::create_dir_all(repo.join(".git")).unwrap();
504 let file = repo.join("src/deep/a.rs");
505 std::fs::write(&file, "x").unwrap();
506 assert_eq!(suggested_allow_dir(&file, None), repo);
507
508 let loose = tmp.path().join("loose");
509 std::fs::create_dir_all(&loose).unwrap();
510 assert_eq!(suggested_allow_dir(&loose, Some(tmp.path())), loose);
511 }
512}