1use std::path::{Path, PathBuf};
2
3use crate::core::error::PathJailError;
4
5pub fn expand_user_path(raw: &str) -> PathBuf {
11 let mut s = raw.to_string();
12
13 if (s == "~" || s.starts_with("~/"))
14 && let Some(home) = dirs::home_dir()
15 {
16 s = format!("{}{}", home.to_string_lossy(), &s[1..]);
17 }
18
19 while let Some(start) = s.find('$') {
20 let rest = &s[start + 1..];
21 let (name, token_len) = if let Some(stripped) = rest.strip_prefix('{') {
22 match stripped.find('}') {
23 Some(end) => (stripped[..end].to_string(), end + 3),
24 None => break,
25 }
26 } else {
27 let end = rest
28 .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
29 .unwrap_or(rest.len());
30 (rest[..end].to_string(), end + 1)
31 };
32 if name.is_empty() {
33 break;
34 }
35 if let Ok(val) = std::env::var(&name) {
36 s.replace_range(start..start + token_len, &val);
37 } else {
38 tracing::warn!(
39 "allow_paths/extra_roots entry '{raw}' references unset variable ${name} — entry will never match"
40 );
41 break;
42 }
43 }
44
45 PathBuf::from(s)
46}
47
48pub fn allow_paths_from_env_and_config() -> Vec<PathBuf> {
49 let mut out = Vec::new();
50 let cfg = crate::core::config::Config::load();
51
52 if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
64 out.push(canonicalize_secure(&data_dir));
65 }
66
67 if let Some(home) = dirs::home_dir() {
68 let ide_dirs_allowed = cfg.allow_ide_config_dirs.unwrap_or(false)
69 || std::env::var("LEAN_CTX_ALLOW_IDE_DIRS").is_ok_and(|v| v == "1");
70 out.extend(home_allow_dirs(&home, ide_dirs_allowed));
71 }
72
73 for p in &cfg.allow_paths {
74 out.push(canonicalize_secure(&expand_user_path(p)));
75 }
76 for p in &cfg.extra_roots {
77 out.push(canonicalize_secure(&expand_user_path(p)));
78 }
79
80 for path in crate::core::runtime_flags::allow_paths() {
81 out.push(canonicalize_secure(&path));
82 }
83 let v = std::env::var("LCTX_ALLOW_PATH")
86 .or_else(|_| std::env::var("LEAN_CTX_ALLOW_PATH"))
87 .unwrap_or_default();
88 if !v.trim().is_empty() {
89 for p in std::env::split_paths(&v) {
90 out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
91 }
92 }
93
94 let extra = std::env::var("LEAN_CTX_EXTRA_ROOTS").unwrap_or_default();
95 if !extra.trim().is_empty() {
96 for p in std::env::split_paths(&extra) {
97 out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
98 }
99 }
100
101 out.extend(canonicalized_roots(
106 &cfg.read_only_roots,
107 "LEAN_CTX_READ_ONLY_ROOTS",
108 ));
109
110 out
111}
112
113fn canonicalized_roots(config_entries: &[String], env_var: &str) -> Vec<PathBuf> {
118 let mut out = Vec::new();
119 for p in config_entries {
120 out.push(canonicalize_secure(&expand_user_path(p)));
121 }
122 let v = std::env::var(env_var).unwrap_or_default();
123 if !v.trim().is_empty() {
124 for p in std::env::split_paths(&v) {
125 out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
126 }
127 }
128 out
129}
130
131pub fn read_only_roots_from_env_and_config() -> Vec<PathBuf> {
136 let cfg = crate::core::config::Config::load();
137 let mut roots = canonicalized_roots(&cfg.read_only_roots, "LEAN_CTX_READ_ONLY_ROOTS");
138 roots.extend(session_read_only_roots());
143 roots
144}
145
146static SESSION_READ_ONLY_ROOTS: std::sync::OnceLock<std::sync::Mutex<Vec<PathBuf>>> =
147 std::sync::OnceLock::new();
148
149fn session_read_only_roots_cell() -> &'static std::sync::Mutex<Vec<PathBuf>> {
150 SESSION_READ_ONLY_ROOTS.get_or_init(|| std::sync::Mutex::new(Vec::new()))
151}
152
153pub fn session_read_only_roots() -> Vec<PathBuf> {
155 session_read_only_roots_cell()
156 .lock()
157 .map(|g| g.clone())
158 .unwrap_or_default()
159}
160
161pub fn register_session_read_only_root(root: &Path) -> bool {
171 let canon = canonicalize_secure(root);
172 let mut guard = match session_read_only_roots_cell().lock() {
173 Ok(g) => g,
174 Err(poisoned) => poisoned.into_inner(),
175 };
176 if guard.iter().any(|r| r == &canon) {
177 return false;
178 }
179 guard.push(canon);
180 true
181}
182
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
190pub struct JailRelaxation {
191 pub source: &'static str,
193 pub detail: &'static str,
195}
196
197fn env_is_set(var: &str) -> bool {
198 std::env::var(var).is_ok_and(|v| !v.trim().is_empty())
199}
200
201#[must_use]
205pub fn active_relaxations() -> Vec<JailRelaxation> {
206 let mut out = Vec::new();
207
208 if cfg!(feature = "no-jail") {
209 out.push(JailRelaxation {
210 source: "no-jail (build feature)",
211 detail: "path jail compiled out — every tool path is allowed",
212 });
213 }
214
215 if crate::core::config::Config::load().path_jail == Some(false) {
216 out.push(JailRelaxation {
217 source: "path_jail = false (config.toml)",
218 detail: "path jail disabled — every tool path is allowed",
219 });
220 }
221
222 if crate::core::runtime_flags::allow_path_enabled() {
223 out.push(JailRelaxation {
224 source: "LEAN_CTX_ALLOW_PATH",
225 detail: "widens the read/write allow-list beyond the project root",
226 });
227 }
228
229 if env_is_set("LEAN_CTX_EXTRA_ROOTS") {
230 out.push(JailRelaxation {
231 source: "LEAN_CTX_EXTRA_ROOTS",
232 detail: "adds extra accessible roots beyond the project root",
233 });
234 }
235
236 let ide_env = std::env::var("LEAN_CTX_ALLOW_IDE_DIRS").is_ok_and(|v| v == "1");
237 if ide_env
238 || crate::core::config::Config::load()
239 .allow_ide_config_dirs
240 .unwrap_or(false)
241 {
242 out.push(JailRelaxation {
243 source: if ide_env {
244 "LEAN_CTX_ALLOW_IDE_DIRS=1"
245 } else {
246 "allow_ide_config_dirs = true (config.toml)"
247 },
248 detail: "exposes ~/.cursor, ~/.claude, … (other agents' sessions/credentials) to tools",
249 });
250 }
251
252 out
253}
254
255pub fn warn_if_relaxed() {
259 for relaxation in active_relaxations() {
260 tracing::warn!(
261 "[SECURITY] path jail relaxed via {}: {} — intended for trusted local use only",
262 relaxation.source,
263 relaxation.detail
264 );
265 }
266}
267
268pub fn is_read_only_path(candidate: &Path) -> bool {
279 let roots = read_only_roots_from_env_and_config();
280 if roots.is_empty() {
281 return false;
282 }
283
284 let base = match canonicalize_existing_ancestor(candidate) {
288 Some((base, remainder)) => {
289 let mut p = base;
290 for part in remainder.iter().rev() {
291 p.push(part);
292 }
293 p
294 }
295 None => canonicalize_or_self(candidate),
296 };
297
298 roots.iter().any(|r| is_under_prefix(&base, r))
299}
300
301pub fn enforce_writable(candidate: &Path) -> Result<(), String> {
310 if is_read_only_path(candidate) {
311 return Err(format!(
312 "path is inside a read-only root — writes are denied (read_only_roots): {}",
313 candidate.display()
314 ));
315 }
316 Ok(())
317}
318
319fn home_allow_dirs(home: &Path, ide_dirs_allowed: bool) -> Vec<PathBuf> {
330 let mut out = Vec::new();
331 if ide_dirs_allowed {
332 let targets = crate::core::editor_registry::build_targets(home);
333 collect_ide_allow_dirs(home, &targets, &mut out);
334 }
335 out
336}
337
338fn collect_ide_allow_dirs(
347 home: &Path,
348 targets: &[crate::core::editor_registry::EditorTarget],
349 out: &mut Vec<PathBuf>,
350) {
351 let mut seen: std::collections::HashSet<PathBuf> = out.iter().cloned().collect();
352 for target in targets {
353 let candidates = [
354 target.config_path.parent().map(Path::to_path_buf),
355 Some(target.detect_path.clone()),
356 ];
357 for cand in candidates.into_iter().flatten() {
358 if cand.as_path() == home || !cand.starts_with(home) || !cand.is_dir() {
359 continue;
360 }
361 let resolved = canonicalize_secure(&cand);
362 if seen.insert(resolved.clone()) {
363 out.push(resolved);
364 }
365 }
366 }
367}
368
369fn is_under_prefix(path: &Path, prefix: &Path) -> bool {
370 path.starts_with(prefix)
371}
372
373pub fn is_harness_auto_memory_path(path: &Path) -> bool {
382 let lower = path.to_string_lossy().replace('\\', "/").to_lowercase();
383 for marker in ["/.claude/projects/", "/.codebuddy/projects/"] {
384 if let Some(idx) = lower.find(marker) {
385 let after = &lower[idx + marker.len()..];
386 let mut parts = after.split('/');
387 let Some(_slug) = parts.next() else {
388 continue;
389 };
390 if parts.next() == Some("memory") {
391 return true;
392 }
393 }
394 }
395 false
396}
397
398fn path_allowed_by_jail(base: &Path, root: &Path, allow: &[PathBuf]) -> bool {
399 let allowed = is_under_prefix(base, root)
400 || allow.iter().any(|p| is_under_prefix(base, p))
401 || is_harness_auto_memory_path(base);
402 #[cfg(windows)]
403 let allowed = allowed || is_under_prefix_windows(base, root);
404 allowed
405}
406
407pub fn canonicalize_or_self(path: &Path) -> PathBuf {
411 super::pathutil::safe_canonicalize_bounded(path, 2000)
412}
413
414fn canonicalize_secure(path: &Path) -> PathBuf {
419 super::pathutil::canonicalize_secure_bounded(path, 2000)
420}
421
422fn canonicalize_existing_ancestor(path: &Path) -> Option<(PathBuf, Vec<std::ffi::OsString>)> {
423 let mut cur = path.to_path_buf();
424 let mut remainder: Vec<std::ffi::OsString> = Vec::new();
425 loop {
426 if cur.exists() {
427 return Some((canonicalize_secure(&cur), remainder));
428 }
429 let name = cur.file_name()?.to_os_string();
430 remainder.push(name);
431 if !cur.pop() {
432 return None;
433 }
434 }
435}
436
437pub fn jail_path(candidate: &Path, jail_root: &Path) -> Result<PathBuf, PathJailError> {
438 jail_path_with_roots(candidate, jail_root, &[])
439}
440
441const LANGUAGE_CACHE_PATTERNS: &[(&str, &str, &str)] = &[
446 ("/go/pkg/mod/", "Go module cache", "~/go/pkg/mod"),
447 (
448 "/.cargo/registry/",
449 "Rust crate registry",
450 "~/.cargo/registry",
451 ),
452 (
453 "/site-packages/",
454 "Python site-packages",
455 "<venv>/lib/pythonX.Y/site-packages",
456 ),
457 ("/node_modules/", "Node modules", "<project>/node_modules"),
458 (
459 "/.m2/repository/",
460 "Maven local repository",
461 "~/.m2/repository",
462 ),
463 ("/.gradle/caches/", "Gradle cache", "~/.gradle/caches"),
464 (
465 "/.nuget/packages/",
466 "NuGet package cache",
467 "~/.nuget/packages",
468 ),
469];
470
471fn detected_cache_hint(candidate: &std::path::Path) -> Option<String> {
475 let s = candidate.to_string_lossy();
476 for &(pattern, name, example) in LANGUAGE_CACHE_PATTERNS {
477 if s.contains(pattern) {
478 return Some(format!(
479 ". Detected {name} — add read_only_roots = [\"{example}\"] to \
480 ~/.config/lean-ctx/config.toml for cached, compressed reads without write access"
481 ));
482 }
483 }
484 None
485}
486
487pub fn detect_language_cache_root(candidate: &Path) -> Option<(&'static str, PathBuf)> {
492 let s = candidate.to_string_lossy().replace('\\', "/");
493 for &(marker, label, _) in LANGUAGE_CACHE_PATTERNS {
494 if let Some(idx) = s.find(marker) {
495 let end = idx + marker.len() - 1; return Some((label, PathBuf::from(&s[..end])));
497 }
498 }
499 None
500}
501
502pub fn jail_path_with_roots(
512 candidate: &Path,
513 jail_root: &Path,
514 extra_roots: &[String],
515) -> Result<PathBuf, PathJailError> {
516 if candidate.to_string_lossy().as_bytes().contains(&0) {
517 return Err(PathJailError::NullByte);
518 }
519
520 #[cfg(feature = "no-jail")]
521 {
522 let _ = (jail_root, extra_roots);
523 return Ok(canonicalize_or_self(candidate));
524 }
525
526 #[allow(unreachable_code)]
527 {
528 let cfg = crate::core::config::Config::load();
529 if cfg.path_jail == Some(false) {
530 return Ok(canonicalize_or_self(candidate));
531 }
532
533 let root = canonicalize_secure(jail_root);
534
535 let resolved: PathBuf;
540 let candidate: &Path = if candidate.is_absolute() {
541 candidate
542 } else {
543 resolved = root.join(candidate);
544 resolved.as_path()
545 };
546
547 let mut allow = allow_paths_from_env_and_config();
548 allow.extend(
550 extra_roots
551 .iter()
552 .filter(|r| !r.is_empty())
553 .map(|r| canonicalize_secure(Path::new(r))),
554 );
555
556 if let Ok(state) = crate::core::paths::state_dir() {
560 allow.push(canonicalize_secure(&state));
561 }
562 allow.extend(
565 read_only_roots_from_env_and_config()
566 .into_iter()
567 .map(|p| canonicalize_secure(&p)),
568 );
569
570 let (base, remainder) = canonicalize_existing_ancestor(candidate).ok_or_else(|| {
571 PathJailError::NoExistingAncestor {
572 path: candidate.to_path_buf(),
573 }
574 })?;
575
576 let allowed = path_allowed_by_jail(&base, &root, &allow);
577
578 if !allowed {
579 let dir = candidate.parent().unwrap_or(candidate).display();
580 let root_display = root.display();
581 let is_suspicious = crate::tools::startup::is_suspicious_root(&root);
582 let mut hint = if is_suspicious || root == std::path::Path::new("/") {
583 ". lean-ctx could not detect your project automatically. \
584 This usually resolves on the next tool call. \
585 If it persists: lean-ctx doctor --fix"
586 .to_string()
587 } else if crate::core::protocol::meta_visible() {
588 format!(
589 ". {dir} is outside the active project ({root_display}). \
590 To access other projects: open it in a new IDE window, \
591 or run: lean-ctx config set extra_roots {dir}"
592 )
593 } else {
594 format!(
595 ". Access denied: outside active project ({root_display}). \
596 To allow: open that project in a new window, \
597 or: LEAN_CTX_EXTRA_ROOTS={dir}"
598 )
599 };
600 if let Some(notice) = crate::core::workspace_trust::untrusted_override_notice() {
604 hint.push_str(". ");
605 hint.push_str(¬ice);
606 }
607 if let Some(missing) = crate::core::config::Config::missing_config_path() {
611 hint.push_str(&format!(
612 ". ⚠ lean-ctx reads no config file at {} (running on defaults) — an \
613 allow_paths edit in a config.toml elsewhere is not read; \
614 `lean-ctx doctor` shows the path in effect",
615 missing.display()
616 ));
617 }
618 if let Some(cache_hint) = detected_cache_hint(candidate) {
619 hint.push_str(&cache_hint);
620 }
621 return Err(PathJailError::EscapesRoot {
622 path: candidate.to_path_buf(),
623 root,
624 hint,
625 });
626 }
627
628 #[cfg(windows)]
629 reject_symlink_on_windows(candidate)?;
630
631 let mut out = base;
632 for part in remainder.iter().rev() {
633 out.push(part);
634 }
635
636 if out.exists() {
639 let final_canon = canonicalize_secure(&out);
640 let final_ok = path_allowed_by_jail(&final_canon, &root, &allow);
641 if !final_ok {
642 return Err(PathJailError::PostCanonicalizeEscape {
643 path: candidate.to_path_buf(),
644 resolved: final_canon,
645 });
646 }
647 }
648
649 Ok(out)
650 }
651}
652
653#[cfg(windows)]
654fn is_under_prefix_windows(path: &Path, prefix: &Path) -> bool {
655 let path_str = normalize_windows_path(&path.to_string_lossy());
656 let prefix_str = normalize_windows_path(&prefix.to_string_lossy());
657 path_str.starts_with(&prefix_str)
658}
659
660#[cfg(windows)]
661fn normalize_windows_path(s: &str) -> String {
662 let stripped = super::pathutil::strip_verbatim_str(s).unwrap_or_else(|| s.to_string());
663 stripped.to_lowercase().replace('/', "\\")
664}
665
666#[cfg(windows)]
667fn reject_symlink_on_windows(path: &Path) -> Result<(), PathJailError> {
668 if let Ok(meta) = std::fs::symlink_metadata(path) {
669 if super::pathutil::is_symlink_or_reparse(&meta) {
672 return Err(PathJailError::Symlink {
673 path: path.to_path_buf(),
674 });
675 }
676 }
677 Ok(())
678}
679
680#[cfg(test)]
681mod tests {
682 use super::*;
683
684 #[cfg(not(feature = "no-jail"))]
685 #[test]
686 fn rejects_path_outside_root() {
687 let _iso = crate::core::data_dir::isolated_data_dir();
692 let tmp = tempfile::tempdir().unwrap();
693 let root = tmp.path().join("root");
694 let other = tmp.path().join("other");
695 std::fs::create_dir_all(&root).unwrap();
696 std::fs::create_dir_all(&other).unwrap();
697 std::fs::write(root.join("a.txt"), "ok").unwrap();
698 std::fs::write(other.join("b.txt"), "no").unwrap();
699
700 let ok = jail_path(&root.join("a.txt"), &root);
701 assert!(ok.is_ok());
702
703 let bad = jail_path(&other.join("b.txt"), &root);
704 assert!(bad.is_err());
705 }
706
707 #[cfg(not(feature = "no-jail"))]
714 #[test]
715 fn read_only_roots_deny_writes_but_allow_reads() {
716 let _iso = crate::core::data_dir::isolated_data_dir();
719
720 let tmp = tempfile::tempdir().unwrap();
721 let project = tmp.path().join("project");
722 let refrepo = tmp.path().join("refrepo");
723 std::fs::create_dir_all(&project).unwrap();
724 std::fs::create_dir_all(refrepo.join("sub")).unwrap();
725 std::fs::write(refrepo.join("lib.rs"), "pub fn x() {}\n").unwrap();
726
727 let ro_canon = canonicalize_secure(&refrepo);
730 crate::test_env::set_var(
731 "LEAN_CTX_READ_ONLY_ROOTS",
732 ro_canon.to_string_lossy().as_ref(),
733 );
734
735 let existing = refrepo.join("lib.rs");
736 let new_file = refrepo.join("sub").join("new.rs");
737 let proj_file = project.join("main.rs");
738
739 let read_existing = jail_path(&existing, &project);
741 let deny_existing = enforce_writable(&existing);
742 let deny_new = enforce_writable(&new_file);
743 let allow_project = enforce_writable(&proj_file);
744 let ro_existing = is_read_only_path(&existing);
745 let ro_project = is_read_only_path(&proj_file);
746
747 crate::test_env::remove_var("LEAN_CTX_READ_ONLY_ROOTS");
748
749 assert!(
750 deny_existing.is_err(),
751 "write to an existing file in a read-only root must be denied"
752 );
753 assert!(
754 deny_new.is_err(),
755 "creating a new file in a read-only root must be denied"
756 );
757 assert!(
758 allow_project.is_ok(),
759 "writes into the project root must stay allowed: {allow_project:?}"
760 );
761 assert!(
762 read_existing.is_ok(),
763 "reads inside a read-only root must resolve (read allow-list): {read_existing:?}"
764 );
765 assert!(ro_existing, "the file is inside the read-only root");
766 assert!(!ro_project, "the project file is not read-only");
767 }
768
769 #[cfg(not(feature = "no-jail"))]
775 #[test]
776 fn honors_path_jail_false_after_mtime_preserving_edit() {
777 let _iso = crate::core::data_dir::isolated_data_dir();
778 let cfg_path = crate::core::config::Config::path().unwrap();
779 if let Some(parent) = cfg_path.parent() {
780 std::fs::create_dir_all(parent).unwrap();
781 }
782
783 let tmp = tempfile::tempdir().unwrap();
784 let root = tmp.path().join("project");
785 let outside = tmp.path().join("outside");
786 std::fs::create_dir_all(&root).unwrap();
787 std::fs::create_dir_all(&outside).unwrap();
788 let secret = outside.join("secret.txt");
789 std::fs::write(&secret, "x").unwrap();
790
791 std::fs::write(&cfg_path, "# jail on\n").unwrap();
793 let mtime0 = std::fs::metadata(&cfg_path).unwrap().modified().unwrap();
794 assert_eq!(crate::core::config::Config::load().path_jail, None);
795
796 std::fs::write(&cfg_path, "path_jail = false\n").unwrap();
799 filetime::set_file_mtime(&cfg_path, filetime::FileTime::from_system_time(mtime0)).unwrap();
800
801 assert!(
802 jail_path(&secret, &root).is_ok(),
803 "path_jail=false must take effect without a fresh process (#406)"
804 );
805 }
806
807 #[test]
808 fn allows_nonexistent_child_under_root() {
809 let tmp = tempfile::tempdir().unwrap();
810 let root = tmp.path().join("root");
811 std::fs::create_dir_all(&root).unwrap();
812 std::fs::write(root.join("a.txt"), "ok").unwrap();
813
814 let p = root.join("new").join("file.txt");
815 let ok = jail_path(&p, &root).unwrap();
816 assert!(ok.to_string_lossy().contains("file.txt"));
817 }
818
819 #[cfg(not(feature = "no-jail"))]
820 #[test]
821 fn relative_candidate_resolves_against_root_not_cwd() {
822 let _iso = crate::core::data_dir::isolated_data_dir();
825 let tmp = tempfile::tempdir().unwrap();
826 let root = tmp.path().join("project");
827 std::fs::create_dir_all(root.join("sub")).unwrap();
828 std::fs::write(root.join("sub").join("file.rs"), "ok").unwrap();
829
830 let jailed = jail_path(Path::new("sub/file.rs"), &root)
831 .expect("relative candidate should resolve under the jail root");
832 assert!(jailed.ends_with("sub/file.rs"));
833 assert!(
834 is_under_prefix(&canonicalize_or_self(&jailed), &canonicalize_or_self(&root)),
835 "resolved path must live under the jail root: {jailed:?}"
836 );
837 }
838
839 #[test]
840 fn ide_allow_dirs_are_registry_derived_and_skip_home() {
841 use crate::core::editor_registry::{ConfigType, EditorTarget};
842
843 let home = tempfile::tempdir().unwrap();
844 let h = home.path();
845 std::fs::create_dir_all(h.join("Library/Application Support/Code/User")).unwrap();
848 std::fs::create_dir_all(h.join(".cursor")).unwrap();
849
850 let targets = vec![
851 EditorTarget {
852 name: "VS Code",
853 agent_key: "vscode".into(),
854 config_path: h.join("Library/Application Support/Code/User/mcp.json"),
855 detect_path: h.join("Library/Application Support/Code"),
856 config_type: ConfigType::VsCodeMcp,
857 },
858 EditorTarget {
859 name: "Cursor",
860 agent_key: "cursor".into(),
861 config_path: h.join(".cursor/mcp.json"),
862 detect_path: h.join(".cursor"),
863 config_type: ConfigType::McpJson,
864 },
865 EditorTarget {
867 name: "Claude Code",
868 agent_key: "claude".into(),
869 config_path: h.join(".claude.json"),
870 detect_path: h.join(".no-such-dir"),
871 config_type: ConfigType::McpJson,
872 },
873 ];
874
875 let mut out = Vec::new();
876 collect_ide_allow_dirs(h, &targets, &mut out);
877
878 assert!(
879 out.iter().any(|p| p.ends_with("Code/User")),
880 "non-dotfile VS Code dir must be covered: {out:?}"
881 );
882 assert!(out.iter().any(|p| p.ends_with(".cursor")), "{out:?}");
883 let home_canon = canonicalize_secure(h);
884 assert!(
885 !out.contains(&home_canon),
886 "must never widen the jail to $HOME: {out:?}"
887 );
888 }
889
890 #[test]
895 fn ide_config_dirs_are_excluded_by_default() {
896 let home = tempfile::tempdir().unwrap();
897 for d in [".lean-ctx", ".cursor", ".codex"] {
898 std::fs::create_dir_all(home.path().join(d)).unwrap();
899 }
900
901 let denied = home_allow_dirs(home.path(), false);
902 assert!(
903 denied.is_empty(),
904 "foreign editor dirs must stay jailed by default: {denied:?}"
905 );
906
907 let allowed = home_allow_dirs(home.path(), true);
912 assert!(
913 allowed.iter().any(|p| p.ends_with(".cursor")),
914 "opt-in must expose editor dirs: {allowed:?}"
915 );
916 assert!(
917 !allowed.iter().any(|p| p.ends_with(".lean-ctx")),
918 "lean-ctx's own dir is covered by the data_dir root, not home_allow_dirs: {allowed:?}"
919 );
920 }
921
922 #[test]
923 fn canonicalize_or_self_strips_verbatim() {
924 let tmp = tempfile::tempdir().unwrap();
925 let dir = tmp.path().join("project");
926 std::fs::create_dir_all(&dir).unwrap();
927
928 let result = canonicalize_or_self(&dir);
929 let s = result.to_string_lossy();
930 assert!(
931 !s.starts_with(r"\\?\"),
932 "canonicalize_or_self should strip verbatim prefix, got: {s}"
933 );
934 }
935
936 #[test]
937 fn jail_path_accepts_same_dir_different_format() {
938 let tmp = tempfile::tempdir().unwrap();
939 let root = tmp.path().join("project");
940 std::fs::create_dir_all(&root).unwrap();
941 std::fs::write(root.join("file.rs"), "ok").unwrap();
942
943 let result = jail_path(&root.join("file.rs"), &root);
944 assert!(result.is_ok(), "same dir should be accepted: {result:?}");
945 }
946
947 #[cfg(not(feature = "no-jail"))]
948 #[test]
949 fn error_message_contains_escape_info() {
950 let _iso = crate::core::data_dir::isolated_data_dir();
953 let tmp = tempfile::tempdir().unwrap();
954 let root = tmp.path().join("root");
955 let other = tmp.path().join("other");
956 std::fs::create_dir_all(&root).unwrap();
957 std::fs::create_dir_all(&other).unwrap();
958 std::fs::write(other.join("b.txt"), "no").unwrap();
959
960 let err = jail_path(&other.join("b.txt"), &root).unwrap_err();
961 assert!(
962 err.to_string().contains("path escapes project root"),
963 "error should mention escape: {err}"
964 );
965 }
966
967 #[cfg(not(feature = "no-jail"))]
971 #[test]
972 fn escape_error_names_config_keys_without_meta() {
973 let _iso = crate::core::data_dir::isolated_data_dir();
974 crate::test_env::remove_var("LEAN_CTX_META");
975 crate::test_env::remove_var("LEAN_CTX_DIAGNOSTICS");
976 let tmp = tempfile::tempdir().unwrap();
977 let root = tmp.path().join("root");
978 let other = tmp.path().join("other");
979 std::fs::create_dir_all(&root).unwrap();
980 std::fs::create_dir_all(&other).unwrap();
981 std::fs::write(other.join("b.txt"), "no").unwrap();
982
983 let err = jail_path(&other.join("b.txt"), &root).unwrap_err();
984 let msg = err.to_string();
985 assert!(
986 msg.contains("outside active project") || msg.contains("LEAN_CTX_EXTRA_ROOTS"),
987 "agent-visible escape error should hint at resolution: {msg}"
988 );
989 }
990
991 #[test]
994 fn expand_user_path_expands_tilde_and_vars() {
995 let _env_lock = crate::core::data_dir::test_env_lock();
996 let home = dirs::home_dir().expect("home dir");
997 let home_s = home.to_string_lossy().to_string();
998
999 assert_eq!(expand_user_path("~"), home);
1000 assert_eq!(expand_user_path("~/code"), home.join("code"));
1001 assert_eq!(expand_user_path("$HOME/code"), home.join("code"));
1002 assert_eq!(expand_user_path("${HOME}/code"), home.join("code"));
1003 crate::test_env::set_var("LEAN_CTX_TEST_SUB", "sub");
1005 assert_eq!(
1006 expand_user_path("$HOME/$LEAN_CTX_TEST_SUB/x"),
1007 PathBuf::from(format!("{home_s}/sub/x"))
1008 );
1009 crate::test_env::remove_var("LEAN_CTX_TEST_SUB");
1010 assert_eq!(expand_user_path("/etc"), PathBuf::from("/etc"));
1012 }
1013
1014 #[test]
1015 fn expand_user_path_leaves_unset_vars_verbatim() {
1016 let _env_lock = crate::core::data_dir::test_env_lock();
1017 crate::test_env::remove_var("LEAN_CTX_TEST_UNSET_VAR");
1018 let p = expand_user_path("$LEAN_CTX_TEST_UNSET_VAR/code");
1019 assert_eq!(p, PathBuf::from("$LEAN_CTX_TEST_UNSET_VAR/code"));
1020 }
1021
1022 #[cfg(unix)]
1035 #[test]
1036 fn allow_path_root_slash_permits_everything() {
1037 let _guard = crate::core::data_dir::test_env_lock();
1038 let tmp = tempfile::tempdir().unwrap();
1039 let root = tmp.path().join("root");
1040 let other = tmp.path().join("other");
1041 std::fs::create_dir_all(&root).unwrap();
1042 std::fs::create_dir_all(&other).unwrap();
1043 std::fs::write(other.join("b.txt"), "allowed").unwrap();
1044
1045 crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", "/");
1046 let result = jail_path(&other.join("b.txt"), &root);
1047 crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
1048
1049 assert!(result.is_ok(), "allow path '/' must permit all: {result:?}");
1050 }
1051
1052 #[test]
1055 fn active_relaxations_detects_allow_path_env() {
1056 let _iso = crate::core::data_dir::isolated_data_dir();
1057 crate::test_env::remove_var("LEAN_CTX_EXTRA_ROOTS");
1058 crate::test_env::remove_var("LEAN_CTX_ALLOW_IDE_DIRS");
1059 crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", "/tmp");
1060
1061 let relaxed = active_relaxations();
1062
1063 crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
1064
1065 assert!(
1066 relaxed.iter().any(|r| r.source == "LEAN_CTX_ALLOW_PATH"),
1067 "LEAN_CTX_ALLOW_PATH must be reported as a jail relaxation: {relaxed:?}"
1068 );
1069 }
1070
1071 #[cfg(not(feature = "no-jail"))]
1072 #[test]
1073 fn active_relaxations_empty_when_jail_intact() {
1074 let _iso = crate::core::data_dir::isolated_data_dir();
1075 for var in [
1076 "LEAN_CTX_ALLOW_PATH",
1077 "LCTX_ALLOW_PATH",
1078 "LEAN_CTX_EXTRA_ROOTS",
1079 "LEAN_CTX_ALLOW_IDE_DIRS",
1080 ] {
1081 crate::test_env::remove_var(var);
1082 }
1083
1084 assert!(
1085 active_relaxations().is_empty(),
1086 "an intact jail (clean config, no relaxation env) must report no relaxations: {:?}",
1087 active_relaxations()
1088 );
1089 }
1090
1091 #[test]
1092 fn allow_path_env_permits_outside_root() {
1093 let _guard = crate::core::data_dir::test_env_lock();
1094 let tmp = tempfile::tempdir().unwrap();
1095 let root = tmp.path().join("root");
1096 let other = tmp.path().join("other");
1097 std::fs::create_dir_all(&root).unwrap();
1098 std::fs::create_dir_all(&other).unwrap();
1099 std::fs::write(other.join("b.txt"), "allowed").unwrap();
1100
1101 let canon = canonicalize_or_self(&other);
1102 crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", canon.to_string_lossy().as_ref());
1103 let result = jail_path(&other.join("b.txt"), &root);
1104 crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
1105
1106 assert!(
1107 result.is_ok(),
1108 "LEAN_CTX_ALLOW_PATH should permit access: {result:?}"
1109 );
1110 }
1111
1112 #[cfg(all(unix, not(feature = "no-jail")))]
1113 #[test]
1114 fn rejects_symlink_escape_on_unix() {
1115 use std::os::unix::fs::symlink;
1116
1117 let _iso = crate::core::data_dir::isolated_data_dir();
1120 let tmp = tempfile::tempdir().unwrap();
1121 let root = tmp.path().join("root");
1122 let other = tmp.path().join("other");
1123 std::fs::create_dir_all(&root).unwrap();
1124 std::fs::create_dir_all(&other).unwrap();
1125 std::fs::write(other.join("secret.txt"), "no").unwrap();
1126
1127 let link = root.join("link.txt");
1128 symlink(other.join("secret.txt"), &link).unwrap();
1129
1130 let bad = jail_path(&link, &root);
1131 assert!(bad.is_err(), "symlink escape must be rejected: {bad:?}");
1132 }
1133
1134 #[test]
1135 fn rejects_null_byte_in_path() {
1136 let tmp = tempfile::tempdir().unwrap();
1137 let root = tmp.path().join("root");
1138 std::fs::create_dir_all(&root).unwrap();
1139
1140 let bad_path = PathBuf::from("file\0.txt");
1141 let result = jail_path(&bad_path, &root);
1142 assert!(result.is_err(), "null byte in path must be rejected");
1143 assert!(
1144 result.unwrap_err().to_string().contains("null byte"),
1145 "error must mention null byte"
1146 );
1147 }
1148
1149 #[cfg(not(feature = "no-jail"))]
1155 #[test]
1156 fn extra_roots_permit_paths_outside_jail() {
1157 let _iso = crate::core::data_dir::isolated_data_dir();
1158
1159 let tmp = tempfile::tempdir().unwrap();
1160 let root = tmp.path().join("project");
1161 let worktree = tmp.path().join("worktree");
1162 let elsewhere = tmp.path().join("elsewhere");
1163 for d in [&root, &worktree, &elsewhere] {
1164 std::fs::create_dir_all(d).unwrap();
1165 }
1166 let in_worktree = worktree.join("a.txt");
1167 std::fs::write(&in_worktree, "x").unwrap();
1168 let outside = elsewhere.join("b.txt");
1169 std::fs::write(&outside, "y").unwrap();
1170
1171 assert!(jail_path(&in_worktree, &root).is_err());
1173 assert!(jail_path_with_roots(&in_worktree, &root, &[]).is_err());
1174
1175 let extra = vec![worktree.to_string_lossy().to_string()];
1178 assert!(
1179 jail_path_with_roots(&in_worktree, &root, &extra).is_ok(),
1180 "path under a session extra_root must resolve (#403)"
1181 );
1182
1183 assert!(
1185 jail_path_with_roots(&outside, &root, &extra).is_err(),
1186 "paths outside ALL roots must still be rejected"
1187 );
1188
1189 assert!(jail_path_with_roots(&outside, &root, &[String::new()]).is_err());
1191 }
1192
1193 #[cfg(not(feature = "no-jail"))]
1196 #[test]
1197 fn harness_auto_memory_path_is_allowed_without_extra_roots() {
1198 let _iso = crate::core::data_dir::isolated_data_dir();
1199 let tmp = tempfile::tempdir().unwrap();
1200 let root = tmp.path().join("project");
1201 let memory = tmp
1202 .path()
1203 .join(".claude")
1204 .join("projects")
1205 .join("-tmp-project")
1206 .join("memory");
1207 std::fs::create_dir_all(&root).unwrap();
1208 std::fs::create_dir_all(&memory).unwrap();
1209 let mem_file = memory.join("MEMORY.md");
1210 std::fs::write(&mem_file, "# index\n").unwrap();
1211
1212 assert!(is_harness_auto_memory_path(&mem_file));
1213 assert!(is_harness_auto_memory_path(&memory));
1214 assert!(!is_harness_auto_memory_path(
1215 &tmp.path()
1216 .join(".claude")
1217 .join("projects")
1218 .join("-tmp-project")
1219 .join("session.jsonl")
1220 ));
1221
1222 assert!(
1223 jail_path_with_roots(&mem_file, &root, &[]).is_ok(),
1224 "auto-memory file must pass PathJail without extra_roots"
1225 );
1226 }
1227
1228 #[test]
1230 fn state_dir_tee_files_pass_jail() {
1231 let _lock = crate::core::data_dir::test_env_lock();
1232 let state = crate::core::paths::state_dir().expect("state_dir must be available");
1233 let tee_path = state.join("tee").join("some_command_deadbeef.log");
1234 let fake_root = std::env::temp_dir().join("pathjail_test_820_root");
1236 std::fs::create_dir_all(&fake_root).ok();
1237 let result = jail_path_with_roots(&tee_path, &fake_root, &[]);
1240 if state.exists() {
1244 assert!(
1245 result.is_ok(),
1246 "tee-file path under lean-ctx state dir must be auto-allowed: {result:?}"
1247 );
1248 }
1249 std::fs::remove_dir_all(&fake_root).ok();
1250 }
1251
1252 #[test]
1253 fn detected_cache_hint_recognizes_go_cargo_python() {
1254 use std::path::Path;
1255 let go = detected_cache_hint(Path::new("/Users/x/go/pkg/mod/github.com/foo/bar/main.go"));
1256 assert!(go.is_some(), "Go module cache should be detected");
1257 assert!(go.unwrap().contains("Go module cache"));
1258
1259 let cargo = detected_cache_hint(Path::new(
1260 "/home/x/.cargo/registry/src/crates.io/serde-1.0/lib.rs",
1261 ));
1262 assert!(cargo.is_some(), "Rust cargo registry should be detected");
1263 assert!(cargo.unwrap().contains("Rust crate registry"));
1264
1265 let py = detected_cache_hint(Path::new(
1266 "/usr/lib/python3.12/site-packages/requests/api.py",
1267 ));
1268 assert!(py.is_some(), "Python site-packages should be detected");
1269
1270 let normal = detected_cache_hint(Path::new("/home/x/projects/myapp/src/main.rs"));
1271 assert!(normal.is_none(), "Normal project path should not match");
1272 }
1273
1274 #[test]
1275 fn detect_cache_root_extracts_marker_dir() {
1276 let cases = [
1277 (
1278 "/Users/x/go/pkg/mod/github.com/foo/bar@v1.2.3/baz.go",
1279 "Go module cache",
1280 "/Users/x/go/pkg/mod",
1281 ),
1282 (
1283 "/home/u/.cargo/registry/src/index-abc/serde-1.0/src/lib.rs",
1284 "Rust crate registry",
1285 "/home/u/.cargo/registry",
1286 ),
1287 (
1288 "/opt/venv/lib/python3.12/site-packages/requests/api.py",
1289 "Python site-packages",
1290 "/opt/venv/lib/python3.12/site-packages",
1291 ),
1292 (
1293 "/w/app/node_modules/react/index.js",
1294 "Node modules",
1295 "/w/app/node_modules",
1296 ),
1297 ];
1298 for (path, want_label, want_root) in cases {
1299 let (label, root) = detect_language_cache_root(Path::new(path))
1300 .unwrap_or_else(|| panic!("expected cache match for {path}"));
1301 assert_eq!(label, want_label, "label for {path}");
1302 assert_eq!(root, PathBuf::from(want_root), "root for {path}");
1303 }
1304 assert!(
1305 detect_language_cache_root(Path::new("/home/u/proj/src/main.rs")).is_none(),
1306 "a normal project path is not a cache"
1307 );
1308 }
1309
1310 #[cfg(not(feature = "no-jail"))]
1314 #[test]
1315 fn registered_cache_root_reads_allow_writes_deny() {
1316 let _iso = crate::core::data_dir::isolated_data_dir();
1317
1318 let tmp = tempfile::tempdir().unwrap();
1319 let dep = tmp.path().join("go/pkg/mod/example.com/lib@v1");
1321 std::fs::create_dir_all(&dep).unwrap();
1322 let file = dep.join("lib.go");
1323 std::fs::write(&file, "package lib").unwrap();
1324
1325 let project = tmp.path().join("project");
1327 std::fs::create_dir_all(&project).unwrap();
1328
1329 assert!(jail_path_with_roots(&file, &project, &[]).is_err());
1331
1332 let (_, root) = detect_language_cache_root(&file).expect("cache match");
1334 assert!(
1335 register_session_read_only_root(&root),
1336 "first register is new"
1337 );
1338 assert!(
1339 !register_session_read_only_root(&root),
1340 "re-register is a no-op"
1341 );
1342
1343 assert!(
1345 jail_path_with_roots(&file, &project, &[]).is_ok(),
1346 "registered cache root must be readable"
1347 );
1348 assert!(is_read_only_path(&file), "cache file is read-only");
1349 assert!(
1350 enforce_writable(&file).is_err(),
1351 "writes into the cache root must be denied"
1352 );
1353 }
1354}