1use std::path::{Path, PathBuf};
2
3use crate::core::error::PathJailError;
4
5pub fn expand_user_path(raw: &str) -> PathBuf {
13 let mut s = raw.to_string();
14
15 if (s == "~" || s.starts_with("~/"))
16 && let Some(home) = dirs::home_dir()
17 {
18 s = format!("{}{}", home.to_string_lossy(), &s[1..]);
19 }
20
21 while let Some(start) = s.find('$') {
22 let rest = &s[start + 1..];
23 let (name, token_len) = if let Some(stripped) = rest.strip_prefix('{') {
24 match stripped.find('}') {
25 Some(end) => (stripped[..end].to_string(), end + 3),
26 None => break,
27 }
28 } else {
29 let end = rest
30 .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
31 .unwrap_or(rest.len());
32 (rest[..end].to_string(), end + 1)
33 };
34 if name.is_empty() {
35 break;
36 }
37 if let Ok(val) = std::env::var(&name) {
38 s.replace_range(start..start + token_len, &val);
39 } else if name == "HOME"
40 && let Some(home) = dirs::home_dir()
41 {
42 let home = home.to_string_lossy();
43 s.replace_range(start..start + token_len, home.as_ref());
44 } else {
45 tracing::warn!(
46 "allow_paths/extra_roots entry '{raw}' references unset variable ${name} — entry will never match"
47 );
48 break;
49 }
50 }
51
52 PathBuf::from(s)
53}
54
55pub fn allow_paths_from_env_and_config() -> Vec<PathBuf> {
56 let mut out = Vec::new();
57 let cfg = crate::core::config::Config::load();
58
59 if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
71 out.push(canonicalize_secure(&data_dir));
72 }
73
74 if let Some(home) = dirs::home_dir() {
75 let ide_dirs_allowed = cfg.allow_ide_config_dirs.unwrap_or(false)
76 || std::env::var("LEAN_CTX_ALLOW_IDE_DIRS").is_ok_and(|v| v == "1");
77 out.extend(home_allow_dirs(&home, ide_dirs_allowed));
78 }
79
80 for p in &cfg.allow_paths {
81 out.push(canonicalize_secure(&expand_user_path(p)));
82 }
83 for p in &cfg.extra_roots {
84 out.push(canonicalize_secure(&expand_user_path(p)));
85 }
86
87 for path in crate::core::runtime_flags::allow_paths() {
88 out.push(canonicalize_secure(&path));
89 }
90 let v = std::env::var("LCTX_ALLOW_PATH")
93 .or_else(|_| std::env::var("LEAN_CTX_ALLOW_PATH"))
94 .unwrap_or_default();
95 if !v.trim().is_empty() {
96 for p in std::env::split_paths(&v) {
97 out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
98 }
99 }
100
101 let extra = std::env::var("LEAN_CTX_EXTRA_ROOTS").unwrap_or_default();
102 if !extra.trim().is_empty() {
103 for p in std::env::split_paths(&extra) {
104 out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
105 }
106 }
107
108 out.extend(canonicalized_roots(
113 &cfg.read_only_roots,
114 "LEAN_CTX_READ_ONLY_ROOTS",
115 ));
116
117 out
118}
119
120fn canonicalized_roots(config_entries: &[String], env_var: &str) -> Vec<PathBuf> {
125 let mut out = Vec::new();
126 for p in config_entries {
127 out.push(canonicalize_secure(&expand_user_path(p)));
128 }
129 let v = std::env::var(env_var).unwrap_or_default();
130 if !v.trim().is_empty() {
131 for p in std::env::split_paths(&v) {
132 out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
133 }
134 }
135 out
136}
137
138pub fn read_only_roots_from_env_and_config() -> Vec<PathBuf> {
143 let cfg = crate::core::config::Config::load();
144 let mut roots = canonicalized_roots(&cfg.read_only_roots, "LEAN_CTX_READ_ONLY_ROOTS");
145 roots.extend(session_read_only_roots());
150 roots
151}
152
153static SESSION_READ_ONLY_ROOTS: std::sync::OnceLock<std::sync::Mutex<Vec<PathBuf>>> =
154 std::sync::OnceLock::new();
155
156fn session_read_only_roots_cell() -> &'static std::sync::Mutex<Vec<PathBuf>> {
157 SESSION_READ_ONLY_ROOTS.get_or_init(|| std::sync::Mutex::new(Vec::new()))
158}
159
160pub fn session_read_only_roots() -> Vec<PathBuf> {
162 session_read_only_roots_cell()
163 .lock()
164 .map(|g| g.clone())
165 .unwrap_or_default()
166}
167
168pub fn register_session_read_only_root(root: &Path) -> bool {
178 let canon = canonicalize_secure(root);
179 let mut guard = match session_read_only_roots_cell().lock() {
180 Ok(g) => g,
181 Err(poisoned) => poisoned.into_inner(),
182 };
183 if guard.iter().any(|r| r == &canon) {
184 return false;
185 }
186 guard.push(canon);
187 true
188}
189
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
197pub struct JailRelaxation {
198 pub source: &'static str,
200 pub detail: &'static str,
202}
203
204fn env_is_set(var: &str) -> bool {
205 std::env::var(var).is_ok_and(|v| !v.trim().is_empty())
206}
207
208#[must_use]
212pub fn active_relaxations() -> Vec<JailRelaxation> {
213 let mut out = Vec::new();
214
215 if cfg!(feature = "no-jail") {
216 out.push(JailRelaxation {
217 source: "no-jail (build feature)",
218 detail: "path jail compiled out — every tool path is allowed",
219 });
220 }
221
222 if crate::core::config::Config::load().path_jail == Some(false) {
223 out.push(JailRelaxation {
224 source: "path_jail = false (config.toml)",
225 detail: "path jail disabled — every tool path is allowed",
226 });
227 }
228
229 if crate::core::runtime_flags::allow_path_enabled() {
230 out.push(JailRelaxation {
231 source: "LEAN_CTX_ALLOW_PATH",
232 detail: "widens the read/write allow-list beyond the project root",
233 });
234 }
235
236 if env_is_set("LEAN_CTX_EXTRA_ROOTS") {
237 out.push(JailRelaxation {
238 source: "LEAN_CTX_EXTRA_ROOTS",
239 detail: "adds extra accessible roots beyond the project root",
240 });
241 }
242
243 let ide_env = std::env::var("LEAN_CTX_ALLOW_IDE_DIRS").is_ok_and(|v| v == "1");
244 if ide_env
245 || crate::core::config::Config::load()
246 .allow_ide_config_dirs
247 .unwrap_or(false)
248 {
249 out.push(JailRelaxation {
250 source: if ide_env {
251 "LEAN_CTX_ALLOW_IDE_DIRS=1"
252 } else {
253 "allow_ide_config_dirs = true (config.toml)"
254 },
255 detail: "exposes ~/.cursor, ~/.claude, … (other agents' sessions/credentials) to tools",
256 });
257 }
258
259 out
260}
261
262pub fn warn_if_relaxed() {
266 for relaxation in active_relaxations() {
267 tracing::warn!(
268 "[SECURITY] path jail relaxed via {}: {} — intended for trusted local use only",
269 relaxation.source,
270 relaxation.detail
271 );
272 }
273}
274
275pub fn is_read_only_path(candidate: &Path) -> bool {
286 let roots = read_only_roots_from_env_and_config();
287 if roots.is_empty() {
288 return false;
289 }
290
291 let base = match canonicalize_existing_ancestor(candidate) {
295 Some((base, remainder)) => {
296 let mut p = base;
297 for part in remainder.iter().rev() {
298 p.push(part);
299 }
300 p
301 }
302 None => canonicalize_or_self(candidate),
303 };
304
305 roots.iter().any(|r| is_under_prefix(&base, r))
306}
307
308pub fn enforce_writable(candidate: &Path) -> Result<(), String> {
317 crate::cli::enforce_protected_store_path(candidate)?;
320 if is_read_only_path(candidate) {
321 return Err(format!(
322 "path is inside a read-only root — writes are denied (read_only_roots): {}",
323 candidate.display()
324 ));
325 }
326 Ok(())
327}
328
329fn home_allow_dirs(home: &Path, ide_dirs_allowed: bool) -> Vec<PathBuf> {
340 let mut out = Vec::new();
341 if ide_dirs_allowed {
342 let targets = crate::core::editor_registry::build_targets(home);
343 collect_ide_allow_dirs(home, &targets, &mut out);
344 }
345 out
346}
347
348fn collect_ide_allow_dirs(
357 home: &Path,
358 targets: &[crate::core::editor_registry::EditorTarget],
359 out: &mut Vec<PathBuf>,
360) {
361 let mut seen: std::collections::HashSet<PathBuf> = out.iter().cloned().collect();
362 for target in targets {
363 let candidates = [
364 target.config_path.parent().map(Path::to_path_buf),
365 Some(target.detect_path.clone()),
366 ];
367 for cand in candidates.into_iter().flatten() {
368 if cand.as_path() == home || !cand.starts_with(home) || !cand.is_dir() {
369 continue;
370 }
371 let resolved = canonicalize_secure(&cand);
372 if seen.insert(resolved.clone()) {
373 out.push(resolved);
374 }
375 }
376 }
377}
378
379fn is_under_prefix(path: &Path, prefix: &Path) -> bool {
380 path.starts_with(prefix)
381}
382
383pub fn is_harness_auto_memory_path(path: &Path) -> bool {
392 let lower = path.to_string_lossy().replace('\\', "/").to_lowercase();
393 for marker in ["/.claude/projects/", "/.codebuddy/projects/"] {
394 if let Some(idx) = lower.find(marker) {
395 let after = &lower[idx + marker.len()..];
396 let mut parts = after.split('/');
397 let Some(_slug) = parts.next() else {
398 continue;
399 };
400 if parts.next() == Some("memory") {
401 return true;
402 }
403 }
404 }
405 false
406}
407
408fn path_allowed_by_jail(base: &Path, root: &Path, allow: &[PathBuf]) -> bool {
409 let allowed = is_under_prefix(base, root)
410 || allow.iter().any(|p| is_under_prefix(base, p))
411 || is_harness_auto_memory_path(base);
412 #[cfg(windows)]
413 let allowed = allowed || is_under_prefix_windows(base, root);
414 allowed
415}
416
417pub fn canonicalize_or_self(path: &Path) -> PathBuf {
421 super::pathutil::safe_canonicalize_bounded(path, 2000)
422}
423
424fn canonicalize_secure(path: &Path) -> PathBuf {
429 super::pathutil::canonicalize_secure_bounded(path, 2000)
430}
431
432fn canonicalize_existing_ancestor(path: &Path) -> Option<(PathBuf, Vec<std::ffi::OsString>)> {
433 let mut cur = path.to_path_buf();
434 let mut remainder: Vec<std::ffi::OsString> = Vec::new();
435 loop {
436 if cur.exists() {
437 return Some((canonicalize_secure(&cur), remainder));
438 }
439 let name = cur.file_name()?.to_os_string();
440 remainder.push(name);
441 if !cur.pop() {
442 return None;
443 }
444 }
445}
446
447pub fn jail_path(candidate: &Path, jail_root: &Path) -> Result<PathBuf, PathJailError> {
448 jail_path_with_roots(candidate, jail_root, &[])
449}
450
451const LANGUAGE_CACHE_PATTERNS: &[(&str, &str, &str)] = &[
456 ("/go/pkg/mod/", "Go module cache", "~/go/pkg/mod"),
457 (
458 "/.cargo/registry/",
459 "Rust crate registry",
460 "~/.cargo/registry",
461 ),
462 (
463 "/site-packages/",
464 "Python site-packages",
465 "<venv>/lib/pythonX.Y/site-packages",
466 ),
467 ("/node_modules/", "Node modules", "<project>/node_modules"),
468 (
469 "/.m2/repository/",
470 "Maven local repository",
471 "~/.m2/repository",
472 ),
473 ("/.gradle/caches/", "Gradle cache", "~/.gradle/caches"),
474 (
475 "/.nuget/packages/",
476 "NuGet package cache",
477 "~/.nuget/packages",
478 ),
479];
480
481fn detected_cache_hint(candidate: &std::path::Path) -> Option<String> {
485 let s = candidate.to_string_lossy();
486 for &(pattern, name, example) in LANGUAGE_CACHE_PATTERNS {
487 if s.contains(pattern) {
488 return Some(format!(
489 ". Detected {name} — add read_only_roots = [\"{example}\"] to \
490 ~/.config/lean-ctx/config.toml for cached, compressed reads without write access"
491 ));
492 }
493 }
494 None
495}
496
497pub fn detect_language_cache_root(candidate: &Path) -> Option<(&'static str, PathBuf)> {
502 let s = candidate.to_string_lossy().replace('\\', "/");
503 for &(marker, label, _) in LANGUAGE_CACHE_PATTERNS {
504 if let Some(idx) = s.find(marker) {
505 let end = idx + marker.len() - 1; return Some((label, PathBuf::from(&s[..end])));
507 }
508 }
509 None
510}
511
512pub fn jail_path_with_roots(
522 candidate: &Path,
523 jail_root: &Path,
524 extra_roots: &[String],
525) -> Result<PathBuf, PathJailError> {
526 if candidate.to_string_lossy().as_bytes().contains(&0) {
527 return Err(PathJailError::NullByte);
528 }
529
530 let absolute = if candidate.is_absolute() {
534 candidate.to_path_buf()
535 } else {
536 jail_root.join(candidate)
537 };
538 crate::cli::enforce_protected_store_path(&absolute)
539 .map_err(|reason| PathJailError::ProtectedContext { reason })?;
540
541 #[cfg(feature = "no-jail")]
542 {
543 let _ = (jail_root, extra_roots);
544 return Ok(canonicalize_or_self(candidate));
545 }
546
547 #[allow(unreachable_code)]
548 {
549 let cfg = crate::core::config::Config::load();
550 if cfg.path_jail == Some(false) {
551 return Ok(canonicalize_or_self(candidate));
552 }
553
554 let root = canonicalize_secure(jail_root);
555
556 let resolved: PathBuf;
561 let candidate: &Path = if candidate.is_absolute() {
562 candidate
563 } else {
564 resolved = root.join(candidate);
565 resolved.as_path()
566 };
567
568 let mut allow = allow_paths_from_env_and_config();
569 allow.extend(
571 extra_roots
572 .iter()
573 .filter(|r| !r.is_empty())
574 .map(|r| canonicalize_secure(Path::new(r))),
575 );
576
577 if let Ok(state) = crate::core::paths::state_dir() {
581 allow.push(canonicalize_secure(&state));
582 }
583 allow.extend(
586 read_only_roots_from_env_and_config()
587 .into_iter()
588 .map(|p| canonicalize_secure(&p)),
589 );
590
591 let (base, remainder) = canonicalize_existing_ancestor(candidate).ok_or_else(|| {
592 PathJailError::NoExistingAncestor {
593 path: candidate.to_path_buf(),
594 }
595 })?;
596
597 let allowed = path_allowed_by_jail(&base, &root, &allow);
598
599 if !allowed {
600 let dir = candidate.parent().unwrap_or(candidate).display();
601 let root_display = root.display();
602 let is_suspicious = crate::tools::startup::is_suspicious_root(&root);
603 let mut hint = if is_suspicious || root == std::path::Path::new("/") {
604 ". lean-ctx could not detect your project automatically. \
605 This usually resolves on the next tool call. \
606 If it persists: lean-ctx doctor --fix"
607 .to_string()
608 } else if crate::core::protocol::meta_visible() {
609 format!(
610 ". {dir} is outside the active project ({root_display}). \
611 To access other projects: open it in a new IDE window, \
612 or run: lean-ctx config set extra_roots {dir}"
613 )
614 } else {
615 format!(
616 ". Access denied: outside active project ({root_display}). \
617 To allow: open that project in a new window, \
618 or: LEAN_CTX_EXTRA_ROOTS={dir}"
619 )
620 };
621 if let Some(notice) = crate::core::workspace_trust::untrusted_override_notice() {
625 hint.push_str(". ");
626 hint.push_str(¬ice);
627 }
628 if let Some(missing) = crate::core::config::Config::missing_config_path() {
632 hint.push_str(&format!(
633 ". ⚠ lean-ctx reads no config file at {} (running on defaults) — an \
634 allow_paths edit in a config.toml elsewhere is not read; \
635 `lean-ctx doctor` shows the path in effect",
636 missing.display()
637 ));
638 }
639 if let Some(cache_hint) = detected_cache_hint(candidate) {
640 hint.push_str(&cache_hint);
641 }
642 return Err(PathJailError::EscapesRoot {
643 path: candidate.to_path_buf(),
644 root,
645 hint,
646 });
647 }
648
649 #[cfg(windows)]
650 reject_symlink_on_windows(candidate)?;
651
652 let mut out = base;
653 for part in remainder.iter().rev() {
654 out.push(part);
655 }
656
657 if out.exists() {
660 let final_canon = canonicalize_secure(&out);
661 let final_ok = path_allowed_by_jail(&final_canon, &root, &allow);
662 if !final_ok {
663 return Err(PathJailError::PostCanonicalizeEscape {
664 path: candidate.to_path_buf(),
665 resolved: final_canon,
666 });
667 }
668 }
669
670 crate::cli::enforce_protected_store_path(&out)
671 .map_err(|reason| PathJailError::ProtectedContext { reason })?;
672 Ok(out)
673 }
674}
675
676#[cfg(all(test, target_os = "macos"))]
677mod protected_store_tests {
678 use super::*;
679
680 #[test]
681 fn runtime_store_is_not_reopened_by_implicit_or_explicit_roots() {
682 let isolated = crate::core::data_dir::isolated_data_dir();
683 let project = tempfile::tempdir().unwrap();
684 let store = isolated.path().join("knowledge");
685 std::fs::create_dir_all(&store).unwrap();
686 let fact = store.join("facts.json");
687 std::fs::write(&fact, "private stored context").unwrap();
688 let code = project.path().join("main.rs");
689 std::fs::write(&code, "fn main() {}\n").unwrap();
690 assert!(
691 jail_path(&fact, project.path()).is_ok(),
692 "Community keeps its existing runtime access"
693 );
694 let _protected = crate::cli::pin_synthetic_session(isolated.path()).unwrap();
695 let roots = vec![isolated.path().to_string_lossy().into_owned()];
696 for candidate in [&fact, &store, &isolated.path().to_path_buf()] {
697 assert!(
698 matches!(
699 jail_path_with_roots(candidate, project.path(), &roots),
700 Err(PathJailError::ProtectedContext { .. })
701 ),
702 "{candidate:?}"
703 );
704 }
705 assert!(jail_path(&code, project.path()).is_ok());
706 assert!(jail_path_with_roots(Path::new("facts.json"), &store, &roots).is_err());
707 for target in [&fact, &store.join("new/backup.json")] {
710 assert!(
711 crate::tools::edit_io::write_atomic_bytes_with_permissions(
712 target,
713 b"forged local context",
714 None,
715 )
716 .is_err()
717 );
718 }
719 assert_eq!(
720 std::fs::read_to_string(&fact).unwrap(),
721 "private stored context"
722 );
723 assert!(!store.join("new").exists());
724 crate::tools::edit_io::write_atomic_bytes_with_permissions(&code, b"fn main() {}\n", None)
725 .unwrap();
726 std::fs::write(&fact, "retained internal update").unwrap();
728 assert_eq!(
729 std::fs::read_to_string(&fact).unwrap(),
730 "retained internal update"
731 );
732 }
733
734 #[test]
735 fn missing_child_profile_never_falls_back_to_the_normal_jail() {
736 let isolated = crate::core::data_dir::isolated_data_dir();
737 let project = tempfile::tempdir().unwrap();
738 let code = project.path().join("main.rs");
739 std::fs::write(&code, "fn main() {}\n").unwrap();
740 let _protected = crate::cli::pin_synthetic_session(isolated.path()).unwrap();
741 crate::test_env::remove_var(crate::cli::CHILD_PROFILE_ENV);
742 assert!(matches!(
743 jail_path(&code, project.path()),
744 Err(PathJailError::ProtectedContext { .. })
745 ));
746 }
747}
748
749#[cfg(windows)]
750fn is_under_prefix_windows(path: &Path, prefix: &Path) -> bool {
751 let path_str = normalize_windows_path(&path.to_string_lossy());
752 let prefix_str = normalize_windows_path(&prefix.to_string_lossy());
753 let prefix_str = prefix_str.trim_end_matches('\\');
754 path_str == prefix_str
756 || path_str
757 .strip_prefix(prefix_str)
758 .is_some_and(|rest| rest.starts_with('\\'))
759}
760
761#[cfg(windows)]
762fn normalize_windows_path(s: &str) -> String {
763 let stripped = super::pathutil::strip_verbatim_str(s).unwrap_or_else(|| s.to_string());
764 stripped.to_lowercase().replace('/', "\\")
765}
766
767#[cfg(windows)]
768fn reject_symlink_on_windows(path: &Path) -> Result<(), PathJailError> {
769 if let Ok(meta) = std::fs::symlink_metadata(path) {
770 if super::pathutil::is_symlink_or_reparse(&meta) {
773 return Err(PathJailError::Symlink {
774 path: path.to_path_buf(),
775 });
776 }
777 }
778 Ok(())
779}
780
781#[cfg(all(test, windows))]
782#[path = "pathjail_windows_tests.rs"]
783mod windows_prefix_tests;
784
785#[cfg(test)]
786mod tests {
787 use super::*;
788
789 #[cfg(not(feature = "no-jail"))]
790 #[test]
791 fn rejects_path_outside_root() {
792 let _iso = crate::core::data_dir::isolated_data_dir();
797 let tmp = tempfile::tempdir().unwrap();
798 let root = tmp.path().join("root");
799 let other = tmp.path().join("other");
800 std::fs::create_dir_all(&root).unwrap();
801 std::fs::create_dir_all(&other).unwrap();
802 std::fs::write(root.join("a.txt"), "ok").unwrap();
803 std::fs::write(other.join("b.txt"), "no").unwrap();
804
805 let ok = jail_path(&root.join("a.txt"), &root);
806 assert!(ok.is_ok());
807
808 let bad = jail_path(&other.join("b.txt"), &root);
809 assert!(bad.is_err());
810 }
811
812 #[cfg(not(feature = "no-jail"))]
819 #[test]
820 fn read_only_roots_deny_writes_but_allow_reads() {
821 let _iso = crate::core::data_dir::isolated_data_dir();
824
825 let tmp = tempfile::tempdir().unwrap();
826 let project = tmp.path().join("project");
827 let refrepo = tmp.path().join("refrepo");
828 std::fs::create_dir_all(&project).unwrap();
829 std::fs::create_dir_all(refrepo.join("sub")).unwrap();
830 std::fs::write(refrepo.join("lib.rs"), "pub fn x() {}\n").unwrap();
831
832 let ro_canon = canonicalize_secure(&refrepo);
835 crate::test_env::set_var(
836 "LEAN_CTX_READ_ONLY_ROOTS",
837 ro_canon.to_string_lossy().as_ref(),
838 );
839
840 let existing = refrepo.join("lib.rs");
841 let new_file = refrepo.join("sub").join("new.rs");
842 let proj_file = project.join("main.rs");
843
844 let read_existing = jail_path(&existing, &project);
846 let deny_existing = enforce_writable(&existing);
847 let deny_new = enforce_writable(&new_file);
848 let allow_project = enforce_writable(&proj_file);
849 let ro_existing = is_read_only_path(&existing);
850 let ro_project = is_read_only_path(&proj_file);
851
852 crate::test_env::remove_var("LEAN_CTX_READ_ONLY_ROOTS");
853
854 assert!(
855 deny_existing.is_err(),
856 "write to an existing file in a read-only root must be denied"
857 );
858 assert!(
859 deny_new.is_err(),
860 "creating a new file in a read-only root must be denied"
861 );
862 assert!(
863 allow_project.is_ok(),
864 "writes into the project root must stay allowed: {allow_project:?}"
865 );
866 assert!(
867 read_existing.is_ok(),
868 "reads inside a read-only root must resolve (read allow-list): {read_existing:?}"
869 );
870 assert!(ro_existing, "the file is inside the read-only root");
871 assert!(!ro_project, "the project file is not read-only");
872 }
873
874 #[cfg(not(feature = "no-jail"))]
880 #[test]
881 fn honors_path_jail_false_after_mtime_preserving_edit() {
882 let _iso = crate::core::data_dir::isolated_data_dir();
883 let cfg_path = crate::core::config::Config::path().unwrap();
884 if let Some(parent) = cfg_path.parent() {
885 std::fs::create_dir_all(parent).unwrap();
886 }
887
888 let tmp = tempfile::tempdir().unwrap();
889 let root = tmp.path().join("project");
890 let outside = tmp.path().join("outside");
891 std::fs::create_dir_all(&root).unwrap();
892 std::fs::create_dir_all(&outside).unwrap();
893 let secret = outside.join("secret.txt");
894 std::fs::write(&secret, "x").unwrap();
895
896 std::fs::write(&cfg_path, "# jail on\n").unwrap();
898 let mtime0 = std::fs::metadata(&cfg_path).unwrap().modified().unwrap();
899 assert_eq!(crate::core::config::Config::load().path_jail, None);
900
901 std::fs::write(&cfg_path, "path_jail = false\n").unwrap();
904 filetime::set_file_mtime(&cfg_path, filetime::FileTime::from_system_time(mtime0)).unwrap();
905
906 assert!(
907 jail_path(&secret, &root).is_ok(),
908 "path_jail=false must take effect without a fresh process (#406)"
909 );
910 }
911
912 #[test]
913 fn allows_nonexistent_child_under_root() {
914 let _env = crate::core::data_dir::test_env_lock();
917 let tmp = tempfile::tempdir().unwrap();
918 let root = tmp.path().join("root");
919 std::fs::create_dir_all(&root).unwrap();
920 std::fs::write(root.join("a.txt"), "ok").unwrap();
921
922 let p = root.join("new").join("file.txt");
923 let ok = jail_path(&p, &root).unwrap();
924 assert!(ok.to_string_lossy().contains("file.txt"));
925 }
926
927 #[cfg(not(feature = "no-jail"))]
928 #[test]
929 fn relative_candidate_resolves_against_root_not_cwd() {
930 let _iso = crate::core::data_dir::isolated_data_dir();
933 let tmp = tempfile::tempdir().unwrap();
934 let root = tmp.path().join("project");
935 std::fs::create_dir_all(root.join("sub")).unwrap();
936 std::fs::write(root.join("sub").join("file.rs"), "ok").unwrap();
937
938 let jailed = jail_path(Path::new("sub/file.rs"), &root)
939 .expect("relative candidate should resolve under the jail root");
940 assert!(jailed.ends_with("sub/file.rs"));
941 assert!(
942 is_under_prefix(&canonicalize_or_self(&jailed), &canonicalize_or_self(&root)),
943 "resolved path must live under the jail root: {jailed:?}"
944 );
945 }
946
947 #[test]
948 fn ide_allow_dirs_are_registry_derived_and_skip_home() {
949 use crate::core::editor_registry::{ConfigType, EditorTarget};
950
951 let home = tempfile::tempdir().unwrap();
952 let h = home.path();
953 std::fs::create_dir_all(h.join("Library/Application Support/Code/User")).unwrap();
956 std::fs::create_dir_all(h.join(".cursor")).unwrap();
957
958 let targets = vec![
959 EditorTarget {
960 name: "VS Code",
961 agent_key: "vscode".into(),
962 config_path: h.join("Library/Application Support/Code/User/mcp.json"),
963 detect_path: h.join("Library/Application Support/Code"),
964 config_type: ConfigType::VsCodeMcp,
965 },
966 EditorTarget {
967 name: "Cursor",
968 agent_key: "cursor".into(),
969 config_path: h.join(".cursor/mcp.json"),
970 detect_path: h.join(".cursor"),
971 config_type: ConfigType::McpJson,
972 },
973 EditorTarget {
975 name: "Claude Code",
976 agent_key: "claude".into(),
977 config_path: h.join(".claude.json"),
978 detect_path: h.join(".no-such-dir"),
979 config_type: ConfigType::McpJson,
980 },
981 ];
982
983 let mut out = Vec::new();
984 collect_ide_allow_dirs(h, &targets, &mut out);
985
986 assert!(
987 out.iter().any(|p| p.ends_with("Code/User")),
988 "non-dotfile VS Code dir must be covered: {out:?}"
989 );
990 assert!(out.iter().any(|p| p.ends_with(".cursor")), "{out:?}");
991 let home_canon = canonicalize_secure(h);
992 assert!(
993 !out.contains(&home_canon),
994 "must never widen the jail to $HOME: {out:?}"
995 );
996 }
997
998 #[test]
1003 fn ide_config_dirs_are_excluded_by_default() {
1004 let home = tempfile::tempdir().unwrap();
1005 for d in [".lean-ctx", ".cursor", ".codex"] {
1006 std::fs::create_dir_all(home.path().join(d)).unwrap();
1007 }
1008
1009 let denied = home_allow_dirs(home.path(), false);
1010 assert!(
1011 denied.is_empty(),
1012 "foreign editor dirs must stay jailed by default: {denied:?}"
1013 );
1014
1015 let allowed = home_allow_dirs(home.path(), true);
1020 assert!(
1021 allowed.iter().any(|p| p.ends_with(".cursor")),
1022 "opt-in must expose editor dirs: {allowed:?}"
1023 );
1024 assert!(
1025 !allowed.iter().any(|p| p.ends_with(".lean-ctx")),
1026 "lean-ctx's own dir is covered by the data_dir root, not home_allow_dirs: {allowed:?}"
1027 );
1028 }
1029
1030 #[test]
1031 fn canonicalize_or_self_strips_verbatim() {
1032 let tmp = tempfile::tempdir().unwrap();
1033 let dir = tmp.path().join("project");
1034 std::fs::create_dir_all(&dir).unwrap();
1035
1036 let result = canonicalize_or_self(&dir);
1037 let s = result.to_string_lossy();
1038 assert!(
1039 !s.starts_with(r"\\?\"),
1040 "canonicalize_or_self should strip verbatim prefix, got: {s}"
1041 );
1042 }
1043
1044 #[test]
1045 fn jail_path_accepts_same_dir_different_format() {
1046 let _env = crate::core::data_dir::test_env_lock();
1047 let tmp = tempfile::tempdir().unwrap();
1048 let root = tmp.path().join("project");
1049 std::fs::create_dir_all(&root).unwrap();
1050 std::fs::write(root.join("file.rs"), "ok").unwrap();
1051
1052 let result = jail_path(&root.join("file.rs"), &root);
1053 assert!(result.is_ok(), "same dir should be accepted: {result:?}");
1054 }
1055
1056 #[cfg(not(feature = "no-jail"))]
1057 #[test]
1058 fn error_message_contains_escape_info() {
1059 let _iso = crate::core::data_dir::isolated_data_dir();
1062 let tmp = tempfile::tempdir().unwrap();
1063 let root = tmp.path().join("root");
1064 let other = tmp.path().join("other");
1065 std::fs::create_dir_all(&root).unwrap();
1066 std::fs::create_dir_all(&other).unwrap();
1067 std::fs::write(other.join("b.txt"), "no").unwrap();
1068
1069 let err = jail_path(&other.join("b.txt"), &root).unwrap_err();
1070 assert!(
1071 err.to_string().contains("path escapes project root"),
1072 "error should mention escape: {err}"
1073 );
1074 }
1075
1076 #[cfg(not(feature = "no-jail"))]
1080 #[test]
1081 fn escape_error_names_config_keys_without_meta() {
1082 let _iso = crate::core::data_dir::isolated_data_dir();
1083 crate::test_env::remove_var("LEAN_CTX_META");
1084 crate::test_env::remove_var("LEAN_CTX_DIAGNOSTICS");
1085 let tmp = tempfile::tempdir().unwrap();
1086 let root = tmp.path().join("root");
1087 let other = tmp.path().join("other");
1088 std::fs::create_dir_all(&root).unwrap();
1089 std::fs::create_dir_all(&other).unwrap();
1090 std::fs::write(other.join("b.txt"), "no").unwrap();
1091
1092 let err = jail_path(&other.join("b.txt"), &root).unwrap_err();
1093 let msg = err.to_string();
1094 assert!(
1095 msg.contains("outside active project") || msg.contains("LEAN_CTX_EXTRA_ROOTS"),
1096 "agent-visible escape error should hint at resolution: {msg}"
1097 );
1098 }
1099
1100 #[test]
1103 fn expand_user_path_expands_tilde_and_vars() {
1104 let _env_lock = crate::core::data_dir::test_env_lock();
1105 let home = dirs::home_dir().expect("home dir");
1106 let home_s = home.to_string_lossy().to_string();
1107
1108 assert_eq!(expand_user_path("~"), home);
1109 assert_eq!(expand_user_path("~/code"), home.join("code"));
1110 assert_eq!(expand_user_path("$HOME/code"), home.join("code"));
1111 assert_eq!(expand_user_path("${HOME}/code"), home.join("code"));
1112 crate::test_env::set_var("LEAN_CTX_TEST_SUB", "sub");
1114 assert_eq!(
1115 expand_user_path("$HOME/$LEAN_CTX_TEST_SUB/x"),
1116 PathBuf::from(format!("{home_s}/sub/x"))
1117 );
1118 crate::test_env::remove_var("LEAN_CTX_TEST_SUB");
1119 assert_eq!(expand_user_path("/etc"), PathBuf::from("/etc"));
1121 }
1122
1123 #[cfg(windows)]
1124 #[test]
1125 fn expand_user_path_home_falls_back_when_env_is_unset() {
1126 let _env_lock = crate::core::data_dir::test_env_lock();
1127 let expected_home = dirs::home_dir().expect("home dir");
1128 let previous_home = std::env::var_os("HOME");
1129
1130 struct RestoreHome(Option<std::ffi::OsString>);
1131
1132 impl Drop for RestoreHome {
1133 fn drop(&mut self) {
1134 match self.0.take() {
1135 Some(value) => crate::test_env::set_var("HOME", value),
1136 None => crate::test_env::remove_var("HOME"),
1137 }
1138 }
1139 }
1140
1141 let _restore_home = RestoreHome(previous_home);
1142 crate::test_env::remove_var("HOME");
1143
1144 assert_eq!(std::env::var_os("HOME"), None);
1145 assert_eq!(expand_user_path("$HOME/code"), expected_home.join("code"));
1146 assert_eq!(expand_user_path("${HOME}/code"), expected_home.join("code"));
1147 }
1148
1149 #[test]
1150 fn expand_user_path_leaves_unset_vars_verbatim() {
1151 let _env_lock = crate::core::data_dir::test_env_lock();
1152 crate::test_env::remove_var("LEAN_CTX_TEST_UNSET_VAR");
1153 let p = expand_user_path("$LEAN_CTX_TEST_UNSET_VAR/code");
1154 assert_eq!(p, PathBuf::from("$LEAN_CTX_TEST_UNSET_VAR/code"));
1155 }
1156
1157 #[cfg(unix)]
1170 #[test]
1171 fn allow_path_root_slash_permits_everything() {
1172 let _guard = crate::core::data_dir::test_env_lock();
1173 let tmp = tempfile::tempdir().unwrap();
1174 let root = tmp.path().join("root");
1175 let other = tmp.path().join("other");
1176 std::fs::create_dir_all(&root).unwrap();
1177 std::fs::create_dir_all(&other).unwrap();
1178 std::fs::write(other.join("b.txt"), "allowed").unwrap();
1179
1180 crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", "/");
1181 let result = jail_path(&other.join("b.txt"), &root);
1182 crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
1183
1184 assert!(result.is_ok(), "allow path '/' must permit all: {result:?}");
1185 }
1186
1187 #[test]
1190 fn active_relaxations_detects_allow_path_env() {
1191 let _iso = crate::core::data_dir::isolated_data_dir();
1192 crate::test_env::remove_var("LEAN_CTX_EXTRA_ROOTS");
1193 crate::test_env::remove_var("LEAN_CTX_ALLOW_IDE_DIRS");
1194 crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", "/tmp");
1195
1196 let relaxed = active_relaxations();
1197
1198 crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
1199
1200 assert!(
1201 relaxed.iter().any(|r| r.source == "LEAN_CTX_ALLOW_PATH"),
1202 "LEAN_CTX_ALLOW_PATH must be reported as a jail relaxation: {relaxed:?}"
1203 );
1204 }
1205
1206 #[cfg(not(feature = "no-jail"))]
1207 #[test]
1208 fn active_relaxations_empty_when_jail_intact() {
1209 let _iso = crate::core::data_dir::isolated_data_dir();
1210 for var in [
1211 "LEAN_CTX_ALLOW_PATH",
1212 "LCTX_ALLOW_PATH",
1213 "LEAN_CTX_EXTRA_ROOTS",
1214 "LEAN_CTX_ALLOW_IDE_DIRS",
1215 ] {
1216 crate::test_env::remove_var(var);
1217 }
1218
1219 assert!(
1220 active_relaxations().is_empty(),
1221 "an intact jail (clean config, no relaxation env) must report no relaxations: {:?}",
1222 active_relaxations()
1223 );
1224 }
1225
1226 #[test]
1227 fn allow_path_env_permits_outside_root() {
1228 let _guard = crate::core::data_dir::test_env_lock();
1229 let tmp = tempfile::tempdir().unwrap();
1230 let root = tmp.path().join("root");
1231 let other = tmp.path().join("other");
1232 std::fs::create_dir_all(&root).unwrap();
1233 std::fs::create_dir_all(&other).unwrap();
1234 std::fs::write(other.join("b.txt"), "allowed").unwrap();
1235
1236 let canon = canonicalize_or_self(&other);
1237 crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", canon.to_string_lossy().as_ref());
1238 let result = jail_path(&other.join("b.txt"), &root);
1239 crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
1240
1241 assert!(
1242 result.is_ok(),
1243 "LEAN_CTX_ALLOW_PATH should permit access: {result:?}"
1244 );
1245 }
1246
1247 #[cfg(all(unix, not(feature = "no-jail")))]
1248 #[test]
1249 fn rejects_symlink_escape_on_unix() {
1250 use std::os::unix::fs::symlink;
1251
1252 let _iso = crate::core::data_dir::isolated_data_dir();
1255 let tmp = tempfile::tempdir().unwrap();
1256 let root = tmp.path().join("root");
1257 let other = tmp.path().join("other");
1258 std::fs::create_dir_all(&root).unwrap();
1259 std::fs::create_dir_all(&other).unwrap();
1260 std::fs::write(other.join("secret.txt"), "no").unwrap();
1261
1262 let link = root.join("link.txt");
1263 symlink(other.join("secret.txt"), &link).unwrap();
1264
1265 let bad = jail_path(&link, &root);
1266 assert!(bad.is_err(), "symlink escape must be rejected: {bad:?}");
1267 }
1268
1269 #[test]
1270 fn rejects_null_byte_in_path() {
1271 let _env = crate::core::data_dir::test_env_lock();
1272 let tmp = tempfile::tempdir().unwrap();
1273 let root = tmp.path().join("root");
1274 std::fs::create_dir_all(&root).unwrap();
1275
1276 let bad_path = PathBuf::from("file\0.txt");
1277 let result = jail_path(&bad_path, &root);
1278 assert!(result.is_err(), "null byte in path must be rejected");
1279 assert!(
1280 result.unwrap_err().to_string().contains("null byte"),
1281 "error must mention null byte"
1282 );
1283 }
1284
1285 #[cfg(not(feature = "no-jail"))]
1291 #[test]
1292 fn extra_roots_permit_paths_outside_jail() {
1293 let _iso = crate::core::data_dir::isolated_data_dir();
1294
1295 let tmp = tempfile::tempdir().unwrap();
1296 let root = tmp.path().join("project");
1297 let worktree = tmp.path().join("worktree");
1298 let elsewhere = tmp.path().join("elsewhere");
1299 for d in [&root, &worktree, &elsewhere] {
1300 std::fs::create_dir_all(d).unwrap();
1301 }
1302 let in_worktree = worktree.join("a.txt");
1303 std::fs::write(&in_worktree, "x").unwrap();
1304 let outside = elsewhere.join("b.txt");
1305 std::fs::write(&outside, "y").unwrap();
1306
1307 assert!(jail_path(&in_worktree, &root).is_err());
1309 assert!(jail_path_with_roots(&in_worktree, &root, &[]).is_err());
1310
1311 let extra = vec![worktree.to_string_lossy().to_string()];
1314 assert!(
1315 jail_path_with_roots(&in_worktree, &root, &extra).is_ok(),
1316 "path under a session extra_root must resolve (#403)"
1317 );
1318
1319 assert!(
1321 jail_path_with_roots(&outside, &root, &extra).is_err(),
1322 "paths outside ALL roots must still be rejected"
1323 );
1324
1325 assert!(jail_path_with_roots(&outside, &root, &[String::new()]).is_err());
1327 }
1328
1329 #[cfg(not(feature = "no-jail"))]
1332 #[test]
1333 fn harness_auto_memory_path_is_allowed_without_extra_roots() {
1334 let _iso = crate::core::data_dir::isolated_data_dir();
1335 let tmp = tempfile::tempdir().unwrap();
1336 let root = tmp.path().join("project");
1337 let memory = tmp
1338 .path()
1339 .join(".claude")
1340 .join("projects")
1341 .join("-tmp-project")
1342 .join("memory");
1343 std::fs::create_dir_all(&root).unwrap();
1344 std::fs::create_dir_all(&memory).unwrap();
1345 let mem_file = memory.join("MEMORY.md");
1346 std::fs::write(&mem_file, "# index\n").unwrap();
1347
1348 assert!(is_harness_auto_memory_path(&mem_file));
1349 assert!(is_harness_auto_memory_path(&memory));
1350 assert!(!is_harness_auto_memory_path(
1351 &tmp.path()
1352 .join(".claude")
1353 .join("projects")
1354 .join("-tmp-project")
1355 .join("session.jsonl")
1356 ));
1357
1358 assert!(
1359 jail_path_with_roots(&mem_file, &root, &[]).is_ok(),
1360 "auto-memory file must pass PathJail without extra_roots"
1361 );
1362 }
1363
1364 #[test]
1366 fn state_dir_tee_files_pass_jail() {
1367 let _lock = crate::core::data_dir::test_env_lock();
1368 let state = crate::core::paths::state_dir().expect("state_dir must be available");
1369 let tee_path = state.join("tee").join("some_command_deadbeef.log");
1370 let fake_root = std::env::temp_dir().join("pathjail_test_820_root");
1372 std::fs::create_dir_all(&fake_root).ok();
1373 let result = jail_path_with_roots(&tee_path, &fake_root, &[]);
1376 if state.exists() {
1380 assert!(
1381 result.is_ok(),
1382 "tee-file path under lean-ctx state dir must be auto-allowed: {result:?}"
1383 );
1384 }
1385 std::fs::remove_dir_all(&fake_root).ok();
1386 }
1387
1388 #[test]
1389 fn detected_cache_hint_recognizes_go_cargo_python() {
1390 use std::path::Path;
1391 let go = detected_cache_hint(Path::new("/Users/x/go/pkg/mod/github.com/foo/bar/main.go"));
1392 assert!(go.is_some(), "Go module cache should be detected");
1393 assert!(go.unwrap().contains("Go module cache"));
1394
1395 let cargo = detected_cache_hint(Path::new(
1396 "/home/x/.cargo/registry/src/crates.io/serde-1.0/lib.rs",
1397 ));
1398 assert!(cargo.is_some(), "Rust cargo registry should be detected");
1399 assert!(cargo.unwrap().contains("Rust crate registry"));
1400
1401 let py = detected_cache_hint(Path::new(
1402 "/usr/lib/python3.12/site-packages/requests/api.py",
1403 ));
1404 assert!(py.is_some(), "Python site-packages should be detected");
1405
1406 let normal = detected_cache_hint(Path::new("/home/x/projects/myapp/src/main.rs"));
1407 assert!(normal.is_none(), "Normal project path should not match");
1408 }
1409
1410 #[test]
1411 fn detect_cache_root_extracts_marker_dir() {
1412 let cases = [
1413 (
1414 "/Users/x/go/pkg/mod/github.com/foo/bar@v1.2.3/baz.go",
1415 "Go module cache",
1416 "/Users/x/go/pkg/mod",
1417 ),
1418 (
1419 "/home/u/.cargo/registry/src/index-abc/serde-1.0/src/lib.rs",
1420 "Rust crate registry",
1421 "/home/u/.cargo/registry",
1422 ),
1423 (
1424 "/opt/venv/lib/python3.12/site-packages/requests/api.py",
1425 "Python site-packages",
1426 "/opt/venv/lib/python3.12/site-packages",
1427 ),
1428 (
1429 "/w/app/node_modules/react/index.js",
1430 "Node modules",
1431 "/w/app/node_modules",
1432 ),
1433 ];
1434 for (path, want_label, want_root) in cases {
1435 let (label, root) = detect_language_cache_root(Path::new(path))
1436 .unwrap_or_else(|| panic!("expected cache match for {path}"));
1437 assert_eq!(label, want_label, "label for {path}");
1438 assert_eq!(root, PathBuf::from(want_root), "root for {path}");
1439 }
1440 assert!(
1441 detect_language_cache_root(Path::new("/home/u/proj/src/main.rs")).is_none(),
1442 "a normal project path is not a cache"
1443 );
1444 }
1445
1446 #[cfg(not(feature = "no-jail"))]
1450 #[test]
1451 fn registered_cache_root_reads_allow_writes_deny() {
1452 let _iso = crate::core::data_dir::isolated_data_dir();
1453
1454 let tmp = tempfile::tempdir().unwrap();
1455 let dep = tmp.path().join("go/pkg/mod/example.com/lib@v1");
1457 std::fs::create_dir_all(&dep).unwrap();
1458 let file = dep.join("lib.go");
1459 std::fs::write(&file, "package lib").unwrap();
1460
1461 let project = tmp.path().join("project");
1463 std::fs::create_dir_all(&project).unwrap();
1464
1465 assert!(jail_path_with_roots(&file, &project, &[]).is_err());
1467
1468 let (_, root) = detect_language_cache_root(&file).expect("cache match");
1470 assert!(
1471 register_session_read_only_root(&root),
1472 "first register is new"
1473 );
1474 assert!(
1475 !register_session_read_only_root(&root),
1476 "re-register is a no-op"
1477 );
1478
1479 assert!(
1481 jail_path_with_roots(&file, &project, &[]).is_ok(),
1482 "registered cache root must be readable"
1483 );
1484 assert!(is_read_only_path(&file), "cache file is read-only");
1485 assert!(
1486 enforce_writable(&file).is_err(),
1487 "writes into the cache root must be denied"
1488 );
1489 }
1490}