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 if is_read_only_path(candidate) {
318 return Err(format!(
319 "path is inside a read-only root — writes are denied (read_only_roots): {}",
320 candidate.display()
321 ));
322 }
323 Ok(())
324}
325
326fn home_allow_dirs(home: &Path, ide_dirs_allowed: bool) -> Vec<PathBuf> {
337 let mut out = Vec::new();
338 if ide_dirs_allowed {
339 let targets = crate::core::editor_registry::build_targets(home);
340 collect_ide_allow_dirs(home, &targets, &mut out);
341 }
342 out
343}
344
345fn collect_ide_allow_dirs(
354 home: &Path,
355 targets: &[crate::core::editor_registry::EditorTarget],
356 out: &mut Vec<PathBuf>,
357) {
358 let mut seen: std::collections::HashSet<PathBuf> = out.iter().cloned().collect();
359 for target in targets {
360 let candidates = [
361 target.config_path.parent().map(Path::to_path_buf),
362 Some(target.detect_path.clone()),
363 ];
364 for cand in candidates.into_iter().flatten() {
365 if cand.as_path() == home || !cand.starts_with(home) || !cand.is_dir() {
366 continue;
367 }
368 let resolved = canonicalize_secure(&cand);
369 if seen.insert(resolved.clone()) {
370 out.push(resolved);
371 }
372 }
373 }
374}
375
376fn is_under_prefix(path: &Path, prefix: &Path) -> bool {
377 path.starts_with(prefix)
378}
379
380pub fn is_harness_auto_memory_path(path: &Path) -> bool {
389 let lower = path.to_string_lossy().replace('\\', "/").to_lowercase();
390 for marker in ["/.claude/projects/", "/.codebuddy/projects/"] {
391 if let Some(idx) = lower.find(marker) {
392 let after = &lower[idx + marker.len()..];
393 let mut parts = after.split('/');
394 let Some(_slug) = parts.next() else {
395 continue;
396 };
397 if parts.next() == Some("memory") {
398 return true;
399 }
400 }
401 }
402 false
403}
404
405fn path_allowed_by_jail(base: &Path, root: &Path, allow: &[PathBuf]) -> bool {
406 let allowed = is_under_prefix(base, root)
407 || allow.iter().any(|p| is_under_prefix(base, p))
408 || is_harness_auto_memory_path(base);
409 #[cfg(windows)]
410 let allowed = allowed || is_under_prefix_windows(base, root);
411 allowed
412}
413
414pub fn canonicalize_or_self(path: &Path) -> PathBuf {
418 super::pathutil::safe_canonicalize_bounded(path, 2000)
419}
420
421fn canonicalize_secure(path: &Path) -> PathBuf {
426 super::pathutil::canonicalize_secure_bounded(path, 2000)
427}
428
429fn canonicalize_existing_ancestor(path: &Path) -> Option<(PathBuf, Vec<std::ffi::OsString>)> {
430 let mut cur = path.to_path_buf();
431 let mut remainder: Vec<std::ffi::OsString> = Vec::new();
432 loop {
433 if cur.exists() {
434 return Some((canonicalize_secure(&cur), remainder));
435 }
436 let name = cur.file_name()?.to_os_string();
437 remainder.push(name);
438 if !cur.pop() {
439 return None;
440 }
441 }
442}
443
444pub fn jail_path(candidate: &Path, jail_root: &Path) -> Result<PathBuf, PathJailError> {
445 jail_path_with_roots(candidate, jail_root, &[])
446}
447
448const LANGUAGE_CACHE_PATTERNS: &[(&str, &str, &str)] = &[
453 ("/go/pkg/mod/", "Go module cache", "~/go/pkg/mod"),
454 (
455 "/.cargo/registry/",
456 "Rust crate registry",
457 "~/.cargo/registry",
458 ),
459 (
460 "/site-packages/",
461 "Python site-packages",
462 "<venv>/lib/pythonX.Y/site-packages",
463 ),
464 ("/node_modules/", "Node modules", "<project>/node_modules"),
465 (
466 "/.m2/repository/",
467 "Maven local repository",
468 "~/.m2/repository",
469 ),
470 ("/.gradle/caches/", "Gradle cache", "~/.gradle/caches"),
471 (
472 "/.nuget/packages/",
473 "NuGet package cache",
474 "~/.nuget/packages",
475 ),
476];
477
478fn detected_cache_hint(candidate: &std::path::Path) -> Option<String> {
482 let s = candidate.to_string_lossy();
483 for &(pattern, name, example) in LANGUAGE_CACHE_PATTERNS {
484 if s.contains(pattern) {
485 return Some(format!(
486 ". Detected {name} — add read_only_roots = [\"{example}\"] to \
487 ~/.config/lean-ctx/config.toml for cached, compressed reads without write access"
488 ));
489 }
490 }
491 None
492}
493
494pub fn detect_language_cache_root(candidate: &Path) -> Option<(&'static str, PathBuf)> {
499 let s = candidate.to_string_lossy().replace('\\', "/");
500 for &(marker, label, _) in LANGUAGE_CACHE_PATTERNS {
501 if let Some(idx) = s.find(marker) {
502 let end = idx + marker.len() - 1; return Some((label, PathBuf::from(&s[..end])));
504 }
505 }
506 None
507}
508
509pub fn jail_path_with_roots(
519 candidate: &Path,
520 jail_root: &Path,
521 extra_roots: &[String],
522) -> Result<PathBuf, PathJailError> {
523 if candidate.to_string_lossy().as_bytes().contains(&0) {
524 return Err(PathJailError::NullByte);
525 }
526
527 #[cfg(feature = "no-jail")]
528 {
529 let _ = (jail_root, extra_roots);
530 return Ok(canonicalize_or_self(candidate));
531 }
532
533 #[allow(unreachable_code)]
534 {
535 let cfg = crate::core::config::Config::load();
536 if cfg.path_jail == Some(false) {
537 return Ok(canonicalize_or_self(candidate));
538 }
539
540 let root = canonicalize_secure(jail_root);
541
542 let resolved: PathBuf;
547 let candidate: &Path = if candidate.is_absolute() {
548 candidate
549 } else {
550 resolved = root.join(candidate);
551 resolved.as_path()
552 };
553
554 let mut allow = allow_paths_from_env_and_config();
555 allow.extend(
557 extra_roots
558 .iter()
559 .filter(|r| !r.is_empty())
560 .map(|r| canonicalize_secure(Path::new(r))),
561 );
562
563 if let Ok(state) = crate::core::paths::state_dir() {
567 allow.push(canonicalize_secure(&state));
568 }
569 allow.extend(
572 read_only_roots_from_env_and_config()
573 .into_iter()
574 .map(|p| canonicalize_secure(&p)),
575 );
576
577 let (base, remainder) = canonicalize_existing_ancestor(candidate).ok_or_else(|| {
578 PathJailError::NoExistingAncestor {
579 path: candidate.to_path_buf(),
580 }
581 })?;
582
583 let allowed = path_allowed_by_jail(&base, &root, &allow);
584
585 if !allowed {
586 let dir = candidate.parent().unwrap_or(candidate).display();
587 let root_display = root.display();
588 let is_suspicious = crate::tools::startup::is_suspicious_root(&root);
589 let mut hint = if is_suspicious || root == std::path::Path::new("/") {
590 ". lean-ctx could not detect your project automatically. \
591 This usually resolves on the next tool call. \
592 If it persists: lean-ctx doctor --fix"
593 .to_string()
594 } else if crate::core::protocol::meta_visible() {
595 format!(
596 ". {dir} is outside the active project ({root_display}). \
597 To access other projects: open it in a new IDE window, \
598 or run: lean-ctx config set extra_roots {dir}"
599 )
600 } else {
601 format!(
602 ". Access denied: outside active project ({root_display}). \
603 To allow: open that project in a new window, \
604 or: LEAN_CTX_EXTRA_ROOTS={dir}"
605 )
606 };
607 if let Some(notice) = crate::core::workspace_trust::untrusted_override_notice() {
611 hint.push_str(". ");
612 hint.push_str(¬ice);
613 }
614 if let Some(missing) = crate::core::config::Config::missing_config_path() {
618 hint.push_str(&format!(
619 ". ⚠ lean-ctx reads no config file at {} (running on defaults) — an \
620 allow_paths edit in a config.toml elsewhere is not read; \
621 `lean-ctx doctor` shows the path in effect",
622 missing.display()
623 ));
624 }
625 if let Some(cache_hint) = detected_cache_hint(candidate) {
626 hint.push_str(&cache_hint);
627 }
628 return Err(PathJailError::EscapesRoot {
629 path: candidate.to_path_buf(),
630 root,
631 hint,
632 });
633 }
634
635 #[cfg(windows)]
636 reject_symlink_on_windows(candidate)?;
637
638 let mut out = base;
639 for part in remainder.iter().rev() {
640 out.push(part);
641 }
642
643 if out.exists() {
646 let final_canon = canonicalize_secure(&out);
647 let final_ok = path_allowed_by_jail(&final_canon, &root, &allow);
648 if !final_ok {
649 return Err(PathJailError::PostCanonicalizeEscape {
650 path: candidate.to_path_buf(),
651 resolved: final_canon,
652 });
653 }
654 }
655
656 Ok(out)
657 }
658}
659
660#[cfg(windows)]
661fn is_under_prefix_windows(path: &Path, prefix: &Path) -> bool {
662 let path_str = normalize_windows_path(&path.to_string_lossy());
663 let prefix_str = normalize_windows_path(&prefix.to_string_lossy());
664 path_str.starts_with(&prefix_str)
665}
666
667#[cfg(windows)]
668fn normalize_windows_path(s: &str) -> String {
669 let stripped = super::pathutil::strip_verbatim_str(s).unwrap_or_else(|| s.to_string());
670 stripped.to_lowercase().replace('/', "\\")
671}
672
673#[cfg(windows)]
674fn reject_symlink_on_windows(path: &Path) -> Result<(), PathJailError> {
675 if let Ok(meta) = std::fs::symlink_metadata(path) {
676 if super::pathutil::is_symlink_or_reparse(&meta) {
679 return Err(PathJailError::Symlink {
680 path: path.to_path_buf(),
681 });
682 }
683 }
684 Ok(())
685}
686
687#[cfg(test)]
688mod tests {
689 use super::*;
690
691 #[cfg(not(feature = "no-jail"))]
692 #[test]
693 fn rejects_path_outside_root() {
694 let _iso = crate::core::data_dir::isolated_data_dir();
699 let tmp = tempfile::tempdir().unwrap();
700 let root = tmp.path().join("root");
701 let other = tmp.path().join("other");
702 std::fs::create_dir_all(&root).unwrap();
703 std::fs::create_dir_all(&other).unwrap();
704 std::fs::write(root.join("a.txt"), "ok").unwrap();
705 std::fs::write(other.join("b.txt"), "no").unwrap();
706
707 let ok = jail_path(&root.join("a.txt"), &root);
708 assert!(ok.is_ok());
709
710 let bad = jail_path(&other.join("b.txt"), &root);
711 assert!(bad.is_err());
712 }
713
714 #[cfg(not(feature = "no-jail"))]
721 #[test]
722 fn read_only_roots_deny_writes_but_allow_reads() {
723 let _iso = crate::core::data_dir::isolated_data_dir();
726
727 let tmp = tempfile::tempdir().unwrap();
728 let project = tmp.path().join("project");
729 let refrepo = tmp.path().join("refrepo");
730 std::fs::create_dir_all(&project).unwrap();
731 std::fs::create_dir_all(refrepo.join("sub")).unwrap();
732 std::fs::write(refrepo.join("lib.rs"), "pub fn x() {}\n").unwrap();
733
734 let ro_canon = canonicalize_secure(&refrepo);
737 crate::test_env::set_var(
738 "LEAN_CTX_READ_ONLY_ROOTS",
739 ro_canon.to_string_lossy().as_ref(),
740 );
741
742 let existing = refrepo.join("lib.rs");
743 let new_file = refrepo.join("sub").join("new.rs");
744 let proj_file = project.join("main.rs");
745
746 let read_existing = jail_path(&existing, &project);
748 let deny_existing = enforce_writable(&existing);
749 let deny_new = enforce_writable(&new_file);
750 let allow_project = enforce_writable(&proj_file);
751 let ro_existing = is_read_only_path(&existing);
752 let ro_project = is_read_only_path(&proj_file);
753
754 crate::test_env::remove_var("LEAN_CTX_READ_ONLY_ROOTS");
755
756 assert!(
757 deny_existing.is_err(),
758 "write to an existing file in a read-only root must be denied"
759 );
760 assert!(
761 deny_new.is_err(),
762 "creating a new file in a read-only root must be denied"
763 );
764 assert!(
765 allow_project.is_ok(),
766 "writes into the project root must stay allowed: {allow_project:?}"
767 );
768 assert!(
769 read_existing.is_ok(),
770 "reads inside a read-only root must resolve (read allow-list): {read_existing:?}"
771 );
772 assert!(ro_existing, "the file is inside the read-only root");
773 assert!(!ro_project, "the project file is not read-only");
774 }
775
776 #[cfg(not(feature = "no-jail"))]
782 #[test]
783 fn honors_path_jail_false_after_mtime_preserving_edit() {
784 let _iso = crate::core::data_dir::isolated_data_dir();
785 let cfg_path = crate::core::config::Config::path().unwrap();
786 if let Some(parent) = cfg_path.parent() {
787 std::fs::create_dir_all(parent).unwrap();
788 }
789
790 let tmp = tempfile::tempdir().unwrap();
791 let root = tmp.path().join("project");
792 let outside = tmp.path().join("outside");
793 std::fs::create_dir_all(&root).unwrap();
794 std::fs::create_dir_all(&outside).unwrap();
795 let secret = outside.join("secret.txt");
796 std::fs::write(&secret, "x").unwrap();
797
798 std::fs::write(&cfg_path, "# jail on\n").unwrap();
800 let mtime0 = std::fs::metadata(&cfg_path).unwrap().modified().unwrap();
801 assert_eq!(crate::core::config::Config::load().path_jail, None);
802
803 std::fs::write(&cfg_path, "path_jail = false\n").unwrap();
806 filetime::set_file_mtime(&cfg_path, filetime::FileTime::from_system_time(mtime0)).unwrap();
807
808 assert!(
809 jail_path(&secret, &root).is_ok(),
810 "path_jail=false must take effect without a fresh process (#406)"
811 );
812 }
813
814 #[test]
815 fn allows_nonexistent_child_under_root() {
816 let tmp = tempfile::tempdir().unwrap();
817 let root = tmp.path().join("root");
818 std::fs::create_dir_all(&root).unwrap();
819 std::fs::write(root.join("a.txt"), "ok").unwrap();
820
821 let p = root.join("new").join("file.txt");
822 let ok = jail_path(&p, &root).unwrap();
823 assert!(ok.to_string_lossy().contains("file.txt"));
824 }
825
826 #[cfg(not(feature = "no-jail"))]
827 #[test]
828 fn relative_candidate_resolves_against_root_not_cwd() {
829 let _iso = crate::core::data_dir::isolated_data_dir();
832 let tmp = tempfile::tempdir().unwrap();
833 let root = tmp.path().join("project");
834 std::fs::create_dir_all(root.join("sub")).unwrap();
835 std::fs::write(root.join("sub").join("file.rs"), "ok").unwrap();
836
837 let jailed = jail_path(Path::new("sub/file.rs"), &root)
838 .expect("relative candidate should resolve under the jail root");
839 assert!(jailed.ends_with("sub/file.rs"));
840 assert!(
841 is_under_prefix(&canonicalize_or_self(&jailed), &canonicalize_or_self(&root)),
842 "resolved path must live under the jail root: {jailed:?}"
843 );
844 }
845
846 #[test]
847 fn ide_allow_dirs_are_registry_derived_and_skip_home() {
848 use crate::core::editor_registry::{ConfigType, EditorTarget};
849
850 let home = tempfile::tempdir().unwrap();
851 let h = home.path();
852 std::fs::create_dir_all(h.join("Library/Application Support/Code/User")).unwrap();
855 std::fs::create_dir_all(h.join(".cursor")).unwrap();
856
857 let targets = vec![
858 EditorTarget {
859 name: "VS Code",
860 agent_key: "vscode".into(),
861 config_path: h.join("Library/Application Support/Code/User/mcp.json"),
862 detect_path: h.join("Library/Application Support/Code"),
863 config_type: ConfigType::VsCodeMcp,
864 },
865 EditorTarget {
866 name: "Cursor",
867 agent_key: "cursor".into(),
868 config_path: h.join(".cursor/mcp.json"),
869 detect_path: h.join(".cursor"),
870 config_type: ConfigType::McpJson,
871 },
872 EditorTarget {
874 name: "Claude Code",
875 agent_key: "claude".into(),
876 config_path: h.join(".claude.json"),
877 detect_path: h.join(".no-such-dir"),
878 config_type: ConfigType::McpJson,
879 },
880 ];
881
882 let mut out = Vec::new();
883 collect_ide_allow_dirs(h, &targets, &mut out);
884
885 assert!(
886 out.iter().any(|p| p.ends_with("Code/User")),
887 "non-dotfile VS Code dir must be covered: {out:?}"
888 );
889 assert!(out.iter().any(|p| p.ends_with(".cursor")), "{out:?}");
890 let home_canon = canonicalize_secure(h);
891 assert!(
892 !out.contains(&home_canon),
893 "must never widen the jail to $HOME: {out:?}"
894 );
895 }
896
897 #[test]
902 fn ide_config_dirs_are_excluded_by_default() {
903 let home = tempfile::tempdir().unwrap();
904 for d in [".lean-ctx", ".cursor", ".codex"] {
905 std::fs::create_dir_all(home.path().join(d)).unwrap();
906 }
907
908 let denied = home_allow_dirs(home.path(), false);
909 assert!(
910 denied.is_empty(),
911 "foreign editor dirs must stay jailed by default: {denied:?}"
912 );
913
914 let allowed = home_allow_dirs(home.path(), true);
919 assert!(
920 allowed.iter().any(|p| p.ends_with(".cursor")),
921 "opt-in must expose editor dirs: {allowed:?}"
922 );
923 assert!(
924 !allowed.iter().any(|p| p.ends_with(".lean-ctx")),
925 "lean-ctx's own dir is covered by the data_dir root, not home_allow_dirs: {allowed:?}"
926 );
927 }
928
929 #[test]
930 fn canonicalize_or_self_strips_verbatim() {
931 let tmp = tempfile::tempdir().unwrap();
932 let dir = tmp.path().join("project");
933 std::fs::create_dir_all(&dir).unwrap();
934
935 let result = canonicalize_or_self(&dir);
936 let s = result.to_string_lossy();
937 assert!(
938 !s.starts_with(r"\\?\"),
939 "canonicalize_or_self should strip verbatim prefix, got: {s}"
940 );
941 }
942
943 #[test]
944 fn jail_path_accepts_same_dir_different_format() {
945 let tmp = tempfile::tempdir().unwrap();
946 let root = tmp.path().join("project");
947 std::fs::create_dir_all(&root).unwrap();
948 std::fs::write(root.join("file.rs"), "ok").unwrap();
949
950 let result = jail_path(&root.join("file.rs"), &root);
951 assert!(result.is_ok(), "same dir should be accepted: {result:?}");
952 }
953
954 #[cfg(not(feature = "no-jail"))]
955 #[test]
956 fn error_message_contains_escape_info() {
957 let _iso = crate::core::data_dir::isolated_data_dir();
960 let tmp = tempfile::tempdir().unwrap();
961 let root = tmp.path().join("root");
962 let other = tmp.path().join("other");
963 std::fs::create_dir_all(&root).unwrap();
964 std::fs::create_dir_all(&other).unwrap();
965 std::fs::write(other.join("b.txt"), "no").unwrap();
966
967 let err = jail_path(&other.join("b.txt"), &root).unwrap_err();
968 assert!(
969 err.to_string().contains("path escapes project root"),
970 "error should mention escape: {err}"
971 );
972 }
973
974 #[cfg(not(feature = "no-jail"))]
978 #[test]
979 fn escape_error_names_config_keys_without_meta() {
980 let _iso = crate::core::data_dir::isolated_data_dir();
981 crate::test_env::remove_var("LEAN_CTX_META");
982 crate::test_env::remove_var("LEAN_CTX_DIAGNOSTICS");
983 let tmp = tempfile::tempdir().unwrap();
984 let root = tmp.path().join("root");
985 let other = tmp.path().join("other");
986 std::fs::create_dir_all(&root).unwrap();
987 std::fs::create_dir_all(&other).unwrap();
988 std::fs::write(other.join("b.txt"), "no").unwrap();
989
990 let err = jail_path(&other.join("b.txt"), &root).unwrap_err();
991 let msg = err.to_string();
992 assert!(
993 msg.contains("outside active project") || msg.contains("LEAN_CTX_EXTRA_ROOTS"),
994 "agent-visible escape error should hint at resolution: {msg}"
995 );
996 }
997
998 #[test]
1001 fn expand_user_path_expands_tilde_and_vars() {
1002 let _env_lock = crate::core::data_dir::test_env_lock();
1003 let home = dirs::home_dir().expect("home dir");
1004 let home_s = home.to_string_lossy().to_string();
1005
1006 assert_eq!(expand_user_path("~"), home);
1007 assert_eq!(expand_user_path("~/code"), home.join("code"));
1008 assert_eq!(expand_user_path("$HOME/code"), home.join("code"));
1009 assert_eq!(expand_user_path("${HOME}/code"), home.join("code"));
1010 crate::test_env::set_var("LEAN_CTX_TEST_SUB", "sub");
1012 assert_eq!(
1013 expand_user_path("$HOME/$LEAN_CTX_TEST_SUB/x"),
1014 PathBuf::from(format!("{home_s}/sub/x"))
1015 );
1016 crate::test_env::remove_var("LEAN_CTX_TEST_SUB");
1017 assert_eq!(expand_user_path("/etc"), PathBuf::from("/etc"));
1019 }
1020
1021 #[cfg(windows)]
1022 #[test]
1023 fn expand_user_path_home_falls_back_when_env_is_unset() {
1024 let _env_lock = crate::core::data_dir::test_env_lock();
1025 let expected_home = dirs::home_dir().expect("home dir");
1026 let previous_home = std::env::var_os("HOME");
1027
1028 struct RestoreHome(Option<std::ffi::OsString>);
1029
1030 impl Drop for RestoreHome {
1031 fn drop(&mut self) {
1032 match self.0.take() {
1033 Some(value) => crate::test_env::set_var("HOME", value),
1034 None => crate::test_env::remove_var("HOME"),
1035 }
1036 }
1037 }
1038
1039 let _restore_home = RestoreHome(previous_home);
1040 crate::test_env::remove_var("HOME");
1041
1042 assert_eq!(std::env::var_os("HOME"), None);
1043 assert_eq!(expand_user_path("$HOME/code"), expected_home.join("code"));
1044 assert_eq!(expand_user_path("${HOME}/code"), expected_home.join("code"));
1045 }
1046
1047 #[test]
1048 fn expand_user_path_leaves_unset_vars_verbatim() {
1049 let _env_lock = crate::core::data_dir::test_env_lock();
1050 crate::test_env::remove_var("LEAN_CTX_TEST_UNSET_VAR");
1051 let p = expand_user_path("$LEAN_CTX_TEST_UNSET_VAR/code");
1052 assert_eq!(p, PathBuf::from("$LEAN_CTX_TEST_UNSET_VAR/code"));
1053 }
1054
1055 #[cfg(unix)]
1068 #[test]
1069 fn allow_path_root_slash_permits_everything() {
1070 let _guard = crate::core::data_dir::test_env_lock();
1071 let tmp = tempfile::tempdir().unwrap();
1072 let root = tmp.path().join("root");
1073 let other = tmp.path().join("other");
1074 std::fs::create_dir_all(&root).unwrap();
1075 std::fs::create_dir_all(&other).unwrap();
1076 std::fs::write(other.join("b.txt"), "allowed").unwrap();
1077
1078 crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", "/");
1079 let result = jail_path(&other.join("b.txt"), &root);
1080 crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
1081
1082 assert!(result.is_ok(), "allow path '/' must permit all: {result:?}");
1083 }
1084
1085 #[test]
1088 fn active_relaxations_detects_allow_path_env() {
1089 let _iso = crate::core::data_dir::isolated_data_dir();
1090 crate::test_env::remove_var("LEAN_CTX_EXTRA_ROOTS");
1091 crate::test_env::remove_var("LEAN_CTX_ALLOW_IDE_DIRS");
1092 crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", "/tmp");
1093
1094 let relaxed = active_relaxations();
1095
1096 crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
1097
1098 assert!(
1099 relaxed.iter().any(|r| r.source == "LEAN_CTX_ALLOW_PATH"),
1100 "LEAN_CTX_ALLOW_PATH must be reported as a jail relaxation: {relaxed:?}"
1101 );
1102 }
1103
1104 #[cfg(not(feature = "no-jail"))]
1105 #[test]
1106 fn active_relaxations_empty_when_jail_intact() {
1107 let _iso = crate::core::data_dir::isolated_data_dir();
1108 for var in [
1109 "LEAN_CTX_ALLOW_PATH",
1110 "LCTX_ALLOW_PATH",
1111 "LEAN_CTX_EXTRA_ROOTS",
1112 "LEAN_CTX_ALLOW_IDE_DIRS",
1113 ] {
1114 crate::test_env::remove_var(var);
1115 }
1116
1117 assert!(
1118 active_relaxations().is_empty(),
1119 "an intact jail (clean config, no relaxation env) must report no relaxations: {:?}",
1120 active_relaxations()
1121 );
1122 }
1123
1124 #[test]
1125 fn allow_path_env_permits_outside_root() {
1126 let _guard = crate::core::data_dir::test_env_lock();
1127 let tmp = tempfile::tempdir().unwrap();
1128 let root = tmp.path().join("root");
1129 let other = tmp.path().join("other");
1130 std::fs::create_dir_all(&root).unwrap();
1131 std::fs::create_dir_all(&other).unwrap();
1132 std::fs::write(other.join("b.txt"), "allowed").unwrap();
1133
1134 let canon = canonicalize_or_self(&other);
1135 crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", canon.to_string_lossy().as_ref());
1136 let result = jail_path(&other.join("b.txt"), &root);
1137 crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
1138
1139 assert!(
1140 result.is_ok(),
1141 "LEAN_CTX_ALLOW_PATH should permit access: {result:?}"
1142 );
1143 }
1144
1145 #[cfg(all(unix, not(feature = "no-jail")))]
1146 #[test]
1147 fn rejects_symlink_escape_on_unix() {
1148 use std::os::unix::fs::symlink;
1149
1150 let _iso = crate::core::data_dir::isolated_data_dir();
1153 let tmp = tempfile::tempdir().unwrap();
1154 let root = tmp.path().join("root");
1155 let other = tmp.path().join("other");
1156 std::fs::create_dir_all(&root).unwrap();
1157 std::fs::create_dir_all(&other).unwrap();
1158 std::fs::write(other.join("secret.txt"), "no").unwrap();
1159
1160 let link = root.join("link.txt");
1161 symlink(other.join("secret.txt"), &link).unwrap();
1162
1163 let bad = jail_path(&link, &root);
1164 assert!(bad.is_err(), "symlink escape must be rejected: {bad:?}");
1165 }
1166
1167 #[test]
1168 fn rejects_null_byte_in_path() {
1169 let tmp = tempfile::tempdir().unwrap();
1170 let root = tmp.path().join("root");
1171 std::fs::create_dir_all(&root).unwrap();
1172
1173 let bad_path = PathBuf::from("file\0.txt");
1174 let result = jail_path(&bad_path, &root);
1175 assert!(result.is_err(), "null byte in path must be rejected");
1176 assert!(
1177 result.unwrap_err().to_string().contains("null byte"),
1178 "error must mention null byte"
1179 );
1180 }
1181
1182 #[cfg(not(feature = "no-jail"))]
1188 #[test]
1189 fn extra_roots_permit_paths_outside_jail() {
1190 let _iso = crate::core::data_dir::isolated_data_dir();
1191
1192 let tmp = tempfile::tempdir().unwrap();
1193 let root = tmp.path().join("project");
1194 let worktree = tmp.path().join("worktree");
1195 let elsewhere = tmp.path().join("elsewhere");
1196 for d in [&root, &worktree, &elsewhere] {
1197 std::fs::create_dir_all(d).unwrap();
1198 }
1199 let in_worktree = worktree.join("a.txt");
1200 std::fs::write(&in_worktree, "x").unwrap();
1201 let outside = elsewhere.join("b.txt");
1202 std::fs::write(&outside, "y").unwrap();
1203
1204 assert!(jail_path(&in_worktree, &root).is_err());
1206 assert!(jail_path_with_roots(&in_worktree, &root, &[]).is_err());
1207
1208 let extra = vec![worktree.to_string_lossy().to_string()];
1211 assert!(
1212 jail_path_with_roots(&in_worktree, &root, &extra).is_ok(),
1213 "path under a session extra_root must resolve (#403)"
1214 );
1215
1216 assert!(
1218 jail_path_with_roots(&outside, &root, &extra).is_err(),
1219 "paths outside ALL roots must still be rejected"
1220 );
1221
1222 assert!(jail_path_with_roots(&outside, &root, &[String::new()]).is_err());
1224 }
1225
1226 #[cfg(not(feature = "no-jail"))]
1229 #[test]
1230 fn harness_auto_memory_path_is_allowed_without_extra_roots() {
1231 let _iso = crate::core::data_dir::isolated_data_dir();
1232 let tmp = tempfile::tempdir().unwrap();
1233 let root = tmp.path().join("project");
1234 let memory = tmp
1235 .path()
1236 .join(".claude")
1237 .join("projects")
1238 .join("-tmp-project")
1239 .join("memory");
1240 std::fs::create_dir_all(&root).unwrap();
1241 std::fs::create_dir_all(&memory).unwrap();
1242 let mem_file = memory.join("MEMORY.md");
1243 std::fs::write(&mem_file, "# index\n").unwrap();
1244
1245 assert!(is_harness_auto_memory_path(&mem_file));
1246 assert!(is_harness_auto_memory_path(&memory));
1247 assert!(!is_harness_auto_memory_path(
1248 &tmp.path()
1249 .join(".claude")
1250 .join("projects")
1251 .join("-tmp-project")
1252 .join("session.jsonl")
1253 ));
1254
1255 assert!(
1256 jail_path_with_roots(&mem_file, &root, &[]).is_ok(),
1257 "auto-memory file must pass PathJail without extra_roots"
1258 );
1259 }
1260
1261 #[test]
1263 fn state_dir_tee_files_pass_jail() {
1264 let _lock = crate::core::data_dir::test_env_lock();
1265 let state = crate::core::paths::state_dir().expect("state_dir must be available");
1266 let tee_path = state.join("tee").join("some_command_deadbeef.log");
1267 let fake_root = std::env::temp_dir().join("pathjail_test_820_root");
1269 std::fs::create_dir_all(&fake_root).ok();
1270 let result = jail_path_with_roots(&tee_path, &fake_root, &[]);
1273 if state.exists() {
1277 assert!(
1278 result.is_ok(),
1279 "tee-file path under lean-ctx state dir must be auto-allowed: {result:?}"
1280 );
1281 }
1282 std::fs::remove_dir_all(&fake_root).ok();
1283 }
1284
1285 #[test]
1286 fn detected_cache_hint_recognizes_go_cargo_python() {
1287 use std::path::Path;
1288 let go = detected_cache_hint(Path::new("/Users/x/go/pkg/mod/github.com/foo/bar/main.go"));
1289 assert!(go.is_some(), "Go module cache should be detected");
1290 assert!(go.unwrap().contains("Go module cache"));
1291
1292 let cargo = detected_cache_hint(Path::new(
1293 "/home/x/.cargo/registry/src/crates.io/serde-1.0/lib.rs",
1294 ));
1295 assert!(cargo.is_some(), "Rust cargo registry should be detected");
1296 assert!(cargo.unwrap().contains("Rust crate registry"));
1297
1298 let py = detected_cache_hint(Path::new(
1299 "/usr/lib/python3.12/site-packages/requests/api.py",
1300 ));
1301 assert!(py.is_some(), "Python site-packages should be detected");
1302
1303 let normal = detected_cache_hint(Path::new("/home/x/projects/myapp/src/main.rs"));
1304 assert!(normal.is_none(), "Normal project path should not match");
1305 }
1306
1307 #[test]
1308 fn detect_cache_root_extracts_marker_dir() {
1309 let cases = [
1310 (
1311 "/Users/x/go/pkg/mod/github.com/foo/bar@v1.2.3/baz.go",
1312 "Go module cache",
1313 "/Users/x/go/pkg/mod",
1314 ),
1315 (
1316 "/home/u/.cargo/registry/src/index-abc/serde-1.0/src/lib.rs",
1317 "Rust crate registry",
1318 "/home/u/.cargo/registry",
1319 ),
1320 (
1321 "/opt/venv/lib/python3.12/site-packages/requests/api.py",
1322 "Python site-packages",
1323 "/opt/venv/lib/python3.12/site-packages",
1324 ),
1325 (
1326 "/w/app/node_modules/react/index.js",
1327 "Node modules",
1328 "/w/app/node_modules",
1329 ),
1330 ];
1331 for (path, want_label, want_root) in cases {
1332 let (label, root) = detect_language_cache_root(Path::new(path))
1333 .unwrap_or_else(|| panic!("expected cache match for {path}"));
1334 assert_eq!(label, want_label, "label for {path}");
1335 assert_eq!(root, PathBuf::from(want_root), "root for {path}");
1336 }
1337 assert!(
1338 detect_language_cache_root(Path::new("/home/u/proj/src/main.rs")).is_none(),
1339 "a normal project path is not a cache"
1340 );
1341 }
1342
1343 #[cfg(not(feature = "no-jail"))]
1347 #[test]
1348 fn registered_cache_root_reads_allow_writes_deny() {
1349 let _iso = crate::core::data_dir::isolated_data_dir();
1350
1351 let tmp = tempfile::tempdir().unwrap();
1352 let dep = tmp.path().join("go/pkg/mod/example.com/lib@v1");
1354 std::fs::create_dir_all(&dep).unwrap();
1355 let file = dep.join("lib.go");
1356 std::fs::write(&file, "package lib").unwrap();
1357
1358 let project = tmp.path().join("project");
1360 std::fs::create_dir_all(&project).unwrap();
1361
1362 assert!(jail_path_with_roots(&file, &project, &[]).is_err());
1364
1365 let (_, root) = detect_language_cache_root(&file).expect("cache match");
1367 assert!(
1368 register_session_read_only_root(&root),
1369 "first register is new"
1370 );
1371 assert!(
1372 !register_session_read_only_root(&root),
1373 "re-register is a no-op"
1374 );
1375
1376 assert!(
1378 jail_path_with_roots(&file, &project, &[]).is_ok(),
1379 "registered cache root must be readable"
1380 );
1381 assert!(is_read_only_path(&file), "cache file is read-only");
1382 assert!(
1383 enforce_writable(&file).is_err(),
1384 "writes into the cache root must be denied"
1385 );
1386 }
1387}