1use std::path::{Path, PathBuf};
27
28const PROTECTED_HOME_DIRS: &[&str] = &["Library", "AppData", "snap"];
32
33const MAX_SESSION_WRITE_ROOTS: usize = 64;
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
38pub enum PathJailScope {
39 #[default]
41 Home,
42 Project,
44}
45
46impl PathJailScope {
47 pub fn parse(value: &str) -> Option<Self> {
49 match value.trim().to_ascii_lowercase().as_str() {
50 "home" | "user" | "workspace" => Some(Self::Home),
51 "project" | "strict" | "root" => Some(Self::Project),
52 _ => None,
53 }
54 }
55
56 pub fn as_str(self) -> &'static str {
57 match self {
58 Self::Home => "home",
59 Self::Project => "project",
60 }
61 }
62
63 pub fn resolve() -> Self {
65 if let Ok(raw) = std::env::var("LEAN_CTX_PATH_JAIL_SCOPE")
66 && let Some(scope) = Self::parse(&raw)
67 {
68 return scope;
69 }
70 crate::core::config::Config::load()
71 .path_jail_scope
72 .as_deref()
73 .and_then(Self::parse)
74 .unwrap_or_default()
75 }
76}
77
78fn zone_home() -> Option<PathBuf> {
81 let home = super::pathjail::canonicalize_secure(&dirs::home_dir()?);
82 home.parent().is_some().then_some(home)
83}
84
85fn scope_home() -> Option<PathBuf> {
91 let home = zone_home()?;
92 let depth = home
93 .components()
94 .filter(|c| matches!(c, std::path::Component::Normal(_)))
95 .count();
96 if depth < 2 {
97 return None;
98 }
99 #[cfg(unix)]
100 {
101 use std::os::unix::fs::MetadataExt;
102 if std::fs::metadata(&home).ok()?.uid() != unsafe { libc::geteuid() } {
104 return None;
105 }
106 }
107 Some(home)
108}
109
110fn first_component_below<'a>(path: &'a Path, home: &Path) -> Option<&'a std::ffi::OsStr> {
112 path.strip_prefix(home)
113 .ok()?
114 .components()
115 .next()
116 .map(std::path::Component::as_os_str)
117}
118
119fn protected_zone_in(path: &Path, home: &Path) -> Option<PathBuf> {
122 let first = first_component_below(path, home)?;
123 let name = first.to_string_lossy();
124 let protected = name.starts_with('.')
126 || name.to_ascii_lowercase().starts_with("ntuser.")
127 || PROTECTED_HOME_DIRS
128 .iter()
129 .any(|d| name.eq_ignore_ascii_case(d));
130 protected.then(|| home.join(first))
131}
132
133pub(crate) fn home_scope_admits(base: &Path) -> bool {
138 if PathJailScope::resolve() != PathJailScope::Home {
139 return false;
140 }
141 let Some(home) = scope_home() else {
142 return false;
143 };
144 admits_below(base, &home)
145}
146
147fn admits_below(base: &Path, home: &Path) -> bool {
148 first_component_below(base, home).is_some() && protected_zone_in(base, home).is_none()
149}
150
151pub(crate) fn protected_zone_permits(base: &Path, root: &Path, allow: &[PathBuf]) -> bool {
158 let Some(zone) = zone_home().and_then(|home| protected_zone_in(base, &home)) else {
159 return true;
160 };
161 (root.starts_with(&zone) && base.starts_with(root))
162 || allow
163 .iter()
164 .any(|p| p.starts_with(&zone) && base.starts_with(p))
165}
166
167fn session_write_roots() -> &'static std::sync::Mutex<Vec<PathBuf>> {
168 static ROOTS: std::sync::OnceLock<std::sync::Mutex<Vec<PathBuf>>> = std::sync::OnceLock::new();
169 ROOTS.get_or_init(|| std::sync::Mutex::new(Vec::new()))
170}
171
172pub fn register_session_root(root: &str) {
175 if root.trim().is_empty() {
176 return;
177 }
178 let path = super::pathjail::canonicalize_secure(Path::new(root));
179 if crate::core::pathutil::is_broad_or_unsafe_root(&path) {
180 return;
181 }
182 let mut roots = session_write_roots()
183 .lock()
184 .unwrap_or_else(std::sync::PoisonError::into_inner);
185 if roots.iter().any(|r| r == &path) {
186 return;
187 }
188 if roots.len() >= MAX_SESSION_WRITE_ROOTS {
189 roots.remove(0);
190 }
191 roots.push(path);
192}
193
194pub(crate) fn home_scope_write_denial(target: &Path) -> Option<String> {
201 if PathJailScope::resolve() != PathJailScope::Home {
202 return None;
203 }
204 let home = scope_home()?;
205 if !admits_below(target, &home) {
206 return None;
207 }
208 let mut writable: Vec<PathBuf> = session_write_roots()
209 .lock()
210 .unwrap_or_else(std::sync::PoisonError::into_inner)
211 .clone();
212 writable.extend(super::pathjail::allow_paths_from_env_and_config());
213 if let Ok(state) = crate::core::paths::state_dir() {
214 writable.push(super::pathjail::canonicalize_secure(&state));
215 }
216 if let Ok(cwd) = std::env::current_dir() {
219 let cwd = super::pathjail::canonicalize_secure(&cwd);
220 if !crate::core::pathutil::is_broad_or_unsafe_root(&cwd) {
221 writable.push(cwd);
222 }
223 }
224 if writable.iter().any(|w| target.starts_with(w)) {
225 return None;
226 }
227 Some(format!(
228 "{} is outside the active project — path_jail_scope = home opens other projects \
229 for reading only. To allow writes there, the user runs in their terminal: \
230 lean-ctx allow-path {} — takes effect immediately, no restart.",
231 target.display(),
232 suggested_allow_dir(target, Some(&home)).display()
233 ))
234}
235
236fn suggested_allow_dir(path: &Path, home: Option<&Path>) -> PathBuf {
241 let start = if path.is_dir() {
242 path.to_path_buf()
243 } else {
244 path.parent().unwrap_or(path).to_path_buf()
245 };
246 let mut cur = start.as_path();
247 loop {
248 if home.is_some_and(|h| cur == h) || cur.parent().is_none() {
249 break;
250 }
251 if crate::core::pathutil::has_project_marker(cur) {
252 return cur.to_path_buf();
253 }
254 match cur.parent() {
255 Some(p) => cur = p,
256 None => break,
257 }
258 }
259 start
260}
261
262pub(crate) fn escape_hint(candidate: &Path, base: &Path, root: &Path) -> String {
267 const TAIL: &str = " — the user runs this in their own terminal; it takes effect \
268 immediately, no restart.";
269 let home = zone_home();
270
271 if home.as_deref() == Some(base) {
272 return ". Your home directory itself is not a project root — it holds ~/.ssh, \
273 ~/Library and other protected locations. Point the tool at a project \
274 below it."
275 .to_string();
276 }
277 if let Some(zone) = home.as_deref().and_then(|h| protected_zone_in(base, h)) {
278 let dir = if base.is_dir() {
280 base
281 } else {
282 base.parent().unwrap_or(base)
283 };
284 return format!(
285 ". {} is a protected location (credentials and other programs' private data \
286 stay jailed). To allow it anyway: lean-ctx allow-path {}{TAIL}",
287 zone.display(),
288 dir.display()
289 );
290 }
291
292 let suggestion = suggested_allow_dir(base, home.as_deref());
293 let under_home = scope_home().is_some_and(|h| admits_below(base, &h));
294 if under_home {
296 return format!(
297 ". {} is outside the active project ({}). Allow every project in your home \
298 directory: lean-ctx config set path_jail_scope home — or only this one: \
299 lean-ctx allow-path {}{TAIL}",
300 candidate.display(),
301 root.display(),
302 suggestion.display()
303 );
304 }
305 format!(
306 ". {} is outside the active project ({}) and outside your home directory. To \
307 allow it: lean-ctx allow-path {}{TAIL}",
308 candidate.display(),
309 root.display(),
310 suggestion.display()
311 )
312}
313
314#[cfg(test)]
315mod tests {
316 use super::*;
317
318 #[test]
319 fn parse_accepts_canonical_names_and_aliases() {
320 assert_eq!(PathJailScope::parse("home"), Some(PathJailScope::Home));
321 assert_eq!(
322 PathJailScope::parse(" Project "),
323 Some(PathJailScope::Project)
324 );
325 assert_eq!(PathJailScope::parse("strict"), Some(PathJailScope::Project));
326 assert_eq!(PathJailScope::parse("anything"), None);
327 assert_eq!(PathJailScope::default(), PathJailScope::Home);
328 for s in [PathJailScope::Home, PathJailScope::Project] {
329 assert_eq!(PathJailScope::parse(s.as_str()), Some(s));
330 }
331 }
332
333 #[test]
334 fn home_zone_admits_code_and_protects_secrets() {
335 let home = Path::new("/home/u");
336 assert!(admits_below(Path::new("/home/u/code/repo/src/a.rs"), home));
337 assert!(admits_below(Path::new("/home/u/Documents/p"), home));
338
339 for protected in [
340 "/home/u/.ssh/id_ed25519",
341 "/home/u/.aws/credentials",
342 "/home/u/.config/gh/hosts.yml",
343 "/home/u/.zshrc",
344 "/home/u/.claude/projects/x/session.jsonl",
345 "/home/u/Library/Keychains/login.keychain-db",
346 "/home/u/AppData/Roaming/x",
347 "/home/u/NTUSER.DAT",
348 ] {
349 assert!(!admits_below(Path::new(protected), home), "{protected}");
350 assert!(protected_zone_in(Path::new(protected), home).is_some());
351 }
352 assert!(!admits_below(home, home));
354 assert!(!admits_below(Path::new("/etc/passwd"), home));
355 assert!(!admits_below(Path::new("/home/user2/x"), home));
356 }
357
358 #[test]
359 fn protected_zone_is_the_top_level_entry() {
360 let home = Path::new("/home/u");
361 assert_eq!(
362 protected_zone_in(Path::new("/home/u/.config/gh/hosts.yml"), home),
363 Some(PathBuf::from("/home/u/.config"))
364 );
365 assert_eq!(
367 protected_zone_in(Path::new("/home/u/code/repo/.git/HEAD"), home),
368 None
369 );
370 }
371
372 #[cfg(all(unix, not(feature = "no-jail")))]
376 #[test]
377 fn jail_admits_sibling_projects_but_not_protected_zones() {
378 let _iso = crate::core::data_dir::isolated_data_dir();
379 let tmp = tempfile::tempdir().unwrap();
380 let home = super::super::pathjail::canonicalize_secure(tmp.path()).join("home");
381 let (a, b, ssh) = (home.join("code/a"), home.join("code/b"), home.join(".ssh"));
382 for dir in [&a, &b, &ssh] {
383 std::fs::create_dir_all(dir).unwrap();
384 }
385 std::fs::create_dir_all(a.join(".git")).unwrap();
386 std::fs::write(b.join("lib.rs"), "x").unwrap();
387 std::fs::write(ssh.join("id_ed25519"), "secret").unwrap();
388 let outside = tmp.path().join("outside.txt");
389 std::fs::write(&outside, "x").unwrap();
390
391 let old_home = std::env::var_os("HOME");
392 crate::test_env::set_var("HOME", &home);
393 crate::test_env::remove_var("LEAN_CTX_PATH_JAIL_SCOPE");
394 let jail = super::super::pathjail::jail_path;
395
396 assert!(
397 jail(&b.join("lib.rs"), &a).is_ok(),
398 "sibling project under ~"
399 );
400 let err = jail(&ssh.join("id_ed25519"), &a).unwrap_err().to_string();
401 assert!(err.contains("protected location"), "{err}");
402 let err = jail(&outside, &a).unwrap_err().to_string();
403 assert!(err.contains("outside your home directory"), "{err}");
404 let err = jail(&home, &a).unwrap_err().to_string();
405 assert!(err.contains("not a project root"), "{err}");
406
407 assert!(
410 jail(&ssh.join("id_ed25519"), &home).is_err(),
411 "zone is a deny"
412 );
413 assert!(
414 jail(&ssh.join("id_ed25519"), &ssh).is_ok(),
415 "root inside the zone"
416 );
417
418 let write = super::super::pathjail::enforce_writable;
420 let err = write(&b.join("lib.rs")).unwrap_err();
421 assert!(
422 err.contains("for reading only") && err.contains("allow-path"),
423 "{err}"
424 );
425 assert!(write(&b.join(".git/hooks/pre-commit")).is_err());
426 register_session_root(&b.to_string_lossy());
427 assert!(write(&b.join("lib.rs")).is_ok(), "session root is writable");
428
429 crate::test_env::set_var("LEAN_CTX_PATH_JAIL_SCOPE", "project");
430 let err = jail(&b.join("lib.rs"), &a).unwrap_err().to_string();
431 assert!(
432 err.contains("path_jail_scope home") && err.contains("allow-path"),
433 "{err}"
434 );
435 crate::test_env::remove_var("LEAN_CTX_PATH_JAIL_SCOPE");
436
437 crate::test_env::set_var("HOME", "/");
439 assert!(
440 jail(&b.join("lib.rs"), &a).is_err(),
441 "HOME=/ falls back to the project"
442 );
443
444 match old_home {
445 Some(h) => crate::test_env::set_var("HOME", h),
446 None => crate::test_env::remove_var("HOME"),
447 }
448 }
449
450 #[test]
451 fn suggestion_prefers_the_enclosing_project() {
452 let tmp = tempfile::tempdir().unwrap();
453 let repo = tmp.path().join("repo");
454 std::fs::create_dir_all(repo.join("src/deep")).unwrap();
455 std::fs::create_dir_all(repo.join(".git")).unwrap();
456 let file = repo.join("src/deep/a.rs");
457 std::fs::write(&file, "x").unwrap();
458 assert_eq!(suggested_allow_dir(&file, None), repo);
459
460 let loose = tmp.path().join("loose");
461 std::fs::create_dir_all(&loose).unwrap();
462 assert_eq!(suggested_allow_dir(&loose, Some(tmp.path())), loose);
463 }
464}