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 let v = std::env::var("LCTX_ALLOW_PATH")
83 .or_else(|_| std::env::var("LEAN_CTX_ALLOW_PATH"))
84 .unwrap_or_default();
85 if !v.trim().is_empty() {
86 for p in std::env::split_paths(&v) {
87 out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
88 }
89 }
90
91 let extra = std::env::var("LEAN_CTX_EXTRA_ROOTS").unwrap_or_default();
92 if !extra.trim().is_empty() {
93 for p in std::env::split_paths(&extra) {
94 out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
95 }
96 }
97
98 out.extend(canonicalized_roots(
103 &cfg.read_only_roots,
104 "LEAN_CTX_READ_ONLY_ROOTS",
105 ));
106
107 out
108}
109
110fn canonicalized_roots(config_entries: &[String], env_var: &str) -> Vec<PathBuf> {
115 let mut out = Vec::new();
116 for p in config_entries {
117 out.push(canonicalize_secure(&expand_user_path(p)));
118 }
119 let v = std::env::var(env_var).unwrap_or_default();
120 if !v.trim().is_empty() {
121 for p in std::env::split_paths(&v) {
122 out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
123 }
124 }
125 out
126}
127
128pub fn read_only_roots_from_env_and_config() -> Vec<PathBuf> {
133 let cfg = crate::core::config::Config::load();
134 canonicalized_roots(&cfg.read_only_roots, "LEAN_CTX_READ_ONLY_ROOTS")
135}
136
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub struct JailRelaxation {
145 pub source: &'static str,
147 pub detail: &'static str,
149}
150
151fn env_is_set(var: &str) -> bool {
152 std::env::var(var).is_ok_and(|v| !v.trim().is_empty())
153}
154
155#[must_use]
159pub fn active_relaxations() -> Vec<JailRelaxation> {
160 let mut out = Vec::new();
161
162 if cfg!(feature = "no-jail") {
163 out.push(JailRelaxation {
164 source: "no-jail (build feature)",
165 detail: "path jail compiled out — every tool path is allowed",
166 });
167 }
168
169 if crate::core::config::Config::load().path_jail == Some(false) {
170 out.push(JailRelaxation {
171 source: "path_jail = false (config.toml)",
172 detail: "path jail disabled — every tool path is allowed",
173 });
174 }
175
176 if env_is_set("LEAN_CTX_ALLOW_PATH") || env_is_set("LCTX_ALLOW_PATH") {
177 out.push(JailRelaxation {
178 source: "LEAN_CTX_ALLOW_PATH",
179 detail: "widens the read/write allow-list beyond the project root",
180 });
181 }
182
183 if env_is_set("LEAN_CTX_EXTRA_ROOTS") {
184 out.push(JailRelaxation {
185 source: "LEAN_CTX_EXTRA_ROOTS",
186 detail: "adds extra accessible roots beyond the project root",
187 });
188 }
189
190 let ide_env = std::env::var("LEAN_CTX_ALLOW_IDE_DIRS").is_ok_and(|v| v == "1");
191 if ide_env
192 || crate::core::config::Config::load()
193 .allow_ide_config_dirs
194 .unwrap_or(false)
195 {
196 out.push(JailRelaxation {
197 source: if ide_env {
198 "LEAN_CTX_ALLOW_IDE_DIRS=1"
199 } else {
200 "allow_ide_config_dirs = true (config.toml)"
201 },
202 detail: "exposes ~/.cursor, ~/.claude, … (other agents' sessions/credentials) to tools",
203 });
204 }
205
206 out
207}
208
209pub fn warn_if_relaxed() {
213 for relaxation in active_relaxations() {
214 tracing::warn!(
215 "[SECURITY] path jail relaxed via {}: {} — intended for trusted local use only",
216 relaxation.source,
217 relaxation.detail
218 );
219 }
220}
221
222pub fn is_read_only_path(candidate: &Path) -> bool {
233 let roots = read_only_roots_from_env_and_config();
234 if roots.is_empty() {
235 return false;
236 }
237
238 let base = match canonicalize_existing_ancestor(candidate) {
242 Some((base, remainder)) => {
243 let mut p = base;
244 for part in remainder.iter().rev() {
245 p.push(part);
246 }
247 p
248 }
249 None => canonicalize_or_self(candidate),
250 };
251
252 roots.iter().any(|r| is_under_prefix(&base, r))
253}
254
255pub fn enforce_writable(candidate: &Path) -> Result<(), String> {
264 if is_read_only_path(candidate) {
265 return Err(format!(
266 "path is inside a read-only root — writes are denied (read_only_roots): {}",
267 candidate.display()
268 ));
269 }
270 Ok(())
271}
272
273fn home_allow_dirs(home: &Path, ide_dirs_allowed: bool) -> Vec<PathBuf> {
284 let mut out = Vec::new();
285 if ide_dirs_allowed {
286 let targets = crate::core::editor_registry::build_targets(home);
287 collect_ide_allow_dirs(home, &targets, &mut out);
288 }
289 out
290}
291
292fn collect_ide_allow_dirs(
301 home: &Path,
302 targets: &[crate::core::editor_registry::EditorTarget],
303 out: &mut Vec<PathBuf>,
304) {
305 let mut seen: std::collections::HashSet<PathBuf> = out.iter().cloned().collect();
306 for target in targets {
307 let candidates = [
308 target.config_path.parent().map(Path::to_path_buf),
309 Some(target.detect_path.clone()),
310 ];
311 for cand in candidates.into_iter().flatten() {
312 if cand.as_path() == home || !cand.starts_with(home) || !cand.is_dir() {
313 continue;
314 }
315 let resolved = canonicalize_secure(&cand);
316 if seen.insert(resolved.clone()) {
317 out.push(resolved);
318 }
319 }
320 }
321}
322
323fn is_under_prefix(path: &Path, prefix: &Path) -> bool {
324 path.starts_with(prefix)
325}
326
327pub fn canonicalize_or_self(path: &Path) -> PathBuf {
331 super::pathutil::safe_canonicalize_bounded(path, 2000)
332}
333
334fn canonicalize_secure(path: &Path) -> PathBuf {
339 super::pathutil::canonicalize_secure_bounded(path, 2000)
340}
341
342fn canonicalize_existing_ancestor(path: &Path) -> Option<(PathBuf, Vec<std::ffi::OsString>)> {
343 let mut cur = path.to_path_buf();
344 let mut remainder: Vec<std::ffi::OsString> = Vec::new();
345 loop {
346 if cur.exists() {
347 return Some((canonicalize_secure(&cur), remainder));
348 }
349 let name = cur.file_name()?.to_os_string();
350 remainder.push(name);
351 if !cur.pop() {
352 return None;
353 }
354 }
355}
356
357pub fn jail_path(candidate: &Path, jail_root: &Path) -> Result<PathBuf, PathJailError> {
358 jail_path_with_roots(candidate, jail_root, &[])
359}
360
361pub fn jail_path_with_roots(
371 candidate: &Path,
372 jail_root: &Path,
373 extra_roots: &[String],
374) -> Result<PathBuf, PathJailError> {
375 if candidate.to_string_lossy().as_bytes().contains(&0) {
376 return Err(PathJailError::NullByte);
377 }
378
379 #[cfg(feature = "no-jail")]
380 {
381 let _ = (jail_root, extra_roots);
382 return Ok(canonicalize_or_self(candidate));
383 }
384
385 #[allow(unreachable_code)]
386 {
387 let cfg = crate::core::config::Config::load();
388 if cfg.path_jail == Some(false) {
389 return Ok(canonicalize_or_self(candidate));
390 }
391
392 let root = canonicalize_secure(jail_root);
393
394 let resolved: PathBuf;
399 let candidate: &Path = if candidate.is_absolute() {
400 candidate
401 } else {
402 resolved = root.join(candidate);
403 resolved.as_path()
404 };
405
406 let mut allow = allow_paths_from_env_and_config();
407 allow.extend(
409 extra_roots
410 .iter()
411 .filter(|r| !r.is_empty())
412 .map(|r| canonicalize_secure(Path::new(r))),
413 );
414
415 let (base, remainder) = canonicalize_existing_ancestor(candidate).ok_or_else(|| {
416 PathJailError::NoExistingAncestor {
417 path: candidate.to_path_buf(),
418 }
419 })?;
420
421 let allowed =
422 is_under_prefix(&base, &root) || allow.iter().any(|p| is_under_prefix(&base, p));
423
424 #[cfg(windows)]
425 let allowed = allowed || is_under_prefix_windows(&base, &root);
426
427 if !allowed {
428 let mut hint = if crate::core::protocol::meta_visible() {
429 let dir = candidate.parent().unwrap_or(candidate).display();
430 format!(
431 ". Hint: set LEAN_CTX_READ_ONLY_ROOTS={dir} for read-only access, \
432 or LEAN_CTX_ALLOW_PATH={dir} for read-write access, \
433 or add entries to read_only_roots/allow_paths in ~/.config/lean-ctx/config.toml"
434 )
435 } else {
436 String::new()
437 };
438 if let Some(notice) = crate::core::workspace_trust::untrusted_override_notice() {
442 hint.push_str(". ");
443 hint.push_str(¬ice);
444 }
445 if let Some(missing) = crate::core::config::Config::missing_config_path() {
449 hint.push_str(&format!(
450 ". ⚠ lean-ctx reads no config file at {} (running on defaults) — an \
451 allow_paths edit in a config.toml elsewhere is not read; \
452 `lean-ctx doctor` shows the path in effect",
453 missing.display()
454 ));
455 }
456 return Err(PathJailError::EscapesRoot {
457 path: candidate.to_path_buf(),
458 root,
459 hint,
460 });
461 }
462
463 #[cfg(windows)]
464 reject_symlink_on_windows(candidate)?;
465
466 let mut out = base;
467 for part in remainder.iter().rev() {
468 out.push(part);
469 }
470
471 if out.exists() {
474 let final_canon = canonicalize_secure(&out);
475 let final_ok = is_under_prefix(&final_canon, &root)
476 || allow.iter().any(|p| is_under_prefix(&final_canon, p));
477 #[cfg(windows)]
478 let final_ok = final_ok || is_under_prefix_windows(&final_canon, &root);
479 if !final_ok {
480 return Err(PathJailError::PostCanonicalizeEscape {
481 path: candidate.to_path_buf(),
482 resolved: final_canon,
483 });
484 }
485 }
486
487 Ok(out)
488 }
489}
490
491#[cfg(windows)]
492fn is_under_prefix_windows(path: &Path, prefix: &Path) -> bool {
493 let path_str = normalize_windows_path(&path.to_string_lossy());
494 let prefix_str = normalize_windows_path(&prefix.to_string_lossy());
495 path_str.starts_with(&prefix_str)
496}
497
498#[cfg(windows)]
499fn normalize_windows_path(s: &str) -> String {
500 let stripped = super::pathutil::strip_verbatim_str(s).unwrap_or_else(|| s.to_string());
501 stripped.to_lowercase().replace('/', "\\")
502}
503
504#[cfg(windows)]
505fn reject_symlink_on_windows(path: &Path) -> Result<(), PathJailError> {
506 if let Ok(meta) = std::fs::symlink_metadata(path) {
507 if super::pathutil::is_symlink_or_reparse(&meta) {
510 return Err(PathJailError::Symlink {
511 path: path.to_path_buf(),
512 });
513 }
514 }
515 Ok(())
516}
517
518#[cfg(test)]
519mod tests {
520 use super::*;
521
522 #[cfg(not(feature = "no-jail"))]
523 #[test]
524 fn rejects_path_outside_root() {
525 let _iso = crate::core::data_dir::isolated_data_dir();
530 let tmp = tempfile::tempdir().unwrap();
531 let root = tmp.path().join("root");
532 let other = tmp.path().join("other");
533 std::fs::create_dir_all(&root).unwrap();
534 std::fs::create_dir_all(&other).unwrap();
535 std::fs::write(root.join("a.txt"), "ok").unwrap();
536 std::fs::write(other.join("b.txt"), "no").unwrap();
537
538 let ok = jail_path(&root.join("a.txt"), &root);
539 assert!(ok.is_ok());
540
541 let bad = jail_path(&other.join("b.txt"), &root);
542 assert!(bad.is_err());
543 }
544
545 #[cfg(not(feature = "no-jail"))]
552 #[test]
553 fn read_only_roots_deny_writes_but_allow_reads() {
554 let _iso = crate::core::data_dir::isolated_data_dir();
555
556 let tmp = tempfile::tempdir().unwrap();
557 let project = tmp.path().join("project");
558 let refrepo = tmp.path().join("refrepo");
559 std::fs::create_dir_all(&project).unwrap();
560 std::fs::create_dir_all(refrepo.join("sub")).unwrap();
561 std::fs::write(refrepo.join("lib.rs"), "pub fn x() {}\n").unwrap();
562
563 let ro_canon = canonicalize_secure(&refrepo);
566 crate::test_env::set_var(
567 "LEAN_CTX_READ_ONLY_ROOTS",
568 ro_canon.to_string_lossy().as_ref(),
569 );
570
571 let existing = refrepo.join("lib.rs");
572 let new_file = refrepo.join("sub").join("new.rs");
573 let proj_file = project.join("main.rs");
574
575 let read_existing = jail_path(&existing, &project);
577 let deny_existing = enforce_writable(&existing);
578 let deny_new = enforce_writable(&new_file);
579 let allow_project = enforce_writable(&proj_file);
580 let ro_existing = is_read_only_path(&existing);
581 let ro_project = is_read_only_path(&proj_file);
582
583 crate::test_env::remove_var("LEAN_CTX_READ_ONLY_ROOTS");
584
585 assert!(
586 deny_existing.is_err(),
587 "write to an existing file in a read-only root must be denied"
588 );
589 assert!(
590 deny_new.is_err(),
591 "creating a new file in a read-only root must be denied"
592 );
593 assert!(
594 allow_project.is_ok(),
595 "writes into the project root must stay allowed: {allow_project:?}"
596 );
597 assert!(
598 read_existing.is_ok(),
599 "reads inside a read-only root must resolve (read allow-list): {read_existing:?}"
600 );
601 assert!(ro_existing, "the file is inside the read-only root");
602 assert!(!ro_project, "the project file is not read-only");
603 }
604
605 #[cfg(not(feature = "no-jail"))]
611 #[test]
612 fn honors_path_jail_false_after_mtime_preserving_edit() {
613 let _iso = crate::core::data_dir::isolated_data_dir();
614 let cfg_path = crate::core::config::Config::path().unwrap();
615 if let Some(parent) = cfg_path.parent() {
616 std::fs::create_dir_all(parent).unwrap();
617 }
618
619 let tmp = tempfile::tempdir().unwrap();
620 let root = tmp.path().join("project");
621 let outside = tmp.path().join("outside");
622 std::fs::create_dir_all(&root).unwrap();
623 std::fs::create_dir_all(&outside).unwrap();
624 let secret = outside.join("secret.txt");
625 std::fs::write(&secret, "x").unwrap();
626
627 std::fs::write(&cfg_path, "# jail on\n").unwrap();
629 let mtime0 = std::fs::metadata(&cfg_path).unwrap().modified().unwrap();
630 assert_eq!(crate::core::config::Config::load().path_jail, None);
631
632 std::fs::write(&cfg_path, "path_jail = false\n").unwrap();
635 filetime::set_file_mtime(&cfg_path, filetime::FileTime::from_system_time(mtime0)).unwrap();
636
637 assert!(
638 jail_path(&secret, &root).is_ok(),
639 "path_jail=false must take effect without a fresh process (#406)"
640 );
641 }
642
643 #[test]
644 fn allows_nonexistent_child_under_root() {
645 let tmp = tempfile::tempdir().unwrap();
646 let root = tmp.path().join("root");
647 std::fs::create_dir_all(&root).unwrap();
648 std::fs::write(root.join("a.txt"), "ok").unwrap();
649
650 let p = root.join("new").join("file.txt");
651 let ok = jail_path(&p, &root).unwrap();
652 assert!(ok.to_string_lossy().contains("file.txt"));
653 }
654
655 #[cfg(not(feature = "no-jail"))]
656 #[test]
657 fn relative_candidate_resolves_against_root_not_cwd() {
658 let _iso = crate::core::data_dir::isolated_data_dir();
661 let tmp = tempfile::tempdir().unwrap();
662 let root = tmp.path().join("project");
663 std::fs::create_dir_all(root.join("sub")).unwrap();
664 std::fs::write(root.join("sub").join("file.rs"), "ok").unwrap();
665
666 let jailed = jail_path(Path::new("sub/file.rs"), &root)
667 .expect("relative candidate should resolve under the jail root");
668 assert!(jailed.ends_with("sub/file.rs"));
669 assert!(
670 is_under_prefix(&canonicalize_or_self(&jailed), &canonicalize_or_self(&root)),
671 "resolved path must live under the jail root: {jailed:?}"
672 );
673 }
674
675 #[test]
676 fn ide_allow_dirs_are_registry_derived_and_skip_home() {
677 use crate::core::editor_registry::{ConfigType, EditorTarget};
678
679 let home = tempfile::tempdir().unwrap();
680 let h = home.path();
681 std::fs::create_dir_all(h.join("Library/Application Support/Code/User")).unwrap();
684 std::fs::create_dir_all(h.join(".cursor")).unwrap();
685
686 let targets = vec![
687 EditorTarget {
688 name: "VS Code",
689 agent_key: "vscode".into(),
690 config_path: h.join("Library/Application Support/Code/User/mcp.json"),
691 detect_path: h.join("Library/Application Support/Code"),
692 config_type: ConfigType::VsCodeMcp,
693 },
694 EditorTarget {
695 name: "Cursor",
696 agent_key: "cursor".into(),
697 config_path: h.join(".cursor/mcp.json"),
698 detect_path: h.join(".cursor"),
699 config_type: ConfigType::McpJson,
700 },
701 EditorTarget {
703 name: "Claude Code",
704 agent_key: "claude".into(),
705 config_path: h.join(".claude.json"),
706 detect_path: h.join(".no-such-dir"),
707 config_type: ConfigType::McpJson,
708 },
709 ];
710
711 let mut out = Vec::new();
712 collect_ide_allow_dirs(h, &targets, &mut out);
713
714 assert!(
715 out.iter().any(|p| p.ends_with("Code/User")),
716 "non-dotfile VS Code dir must be covered: {out:?}"
717 );
718 assert!(out.iter().any(|p| p.ends_with(".cursor")), "{out:?}");
719 let home_canon = canonicalize_secure(h);
720 assert!(
721 !out.contains(&home_canon),
722 "must never widen the jail to $HOME: {out:?}"
723 );
724 }
725
726 #[test]
731 fn ide_config_dirs_are_excluded_by_default() {
732 let home = tempfile::tempdir().unwrap();
733 for d in [".lean-ctx", ".cursor", ".codex"] {
734 std::fs::create_dir_all(home.path().join(d)).unwrap();
735 }
736
737 let denied = home_allow_dirs(home.path(), false);
738 assert!(
739 denied.is_empty(),
740 "foreign editor dirs must stay jailed by default: {denied:?}"
741 );
742
743 let allowed = home_allow_dirs(home.path(), true);
748 assert!(
749 allowed.iter().any(|p| p.ends_with(".cursor")),
750 "opt-in must expose editor dirs: {allowed:?}"
751 );
752 assert!(
753 !allowed.iter().any(|p| p.ends_with(".lean-ctx")),
754 "lean-ctx's own dir is covered by the data_dir root, not home_allow_dirs: {allowed:?}"
755 );
756 }
757
758 #[test]
759 fn canonicalize_or_self_strips_verbatim() {
760 let tmp = tempfile::tempdir().unwrap();
761 let dir = tmp.path().join("project");
762 std::fs::create_dir_all(&dir).unwrap();
763
764 let result = canonicalize_or_self(&dir);
765 let s = result.to_string_lossy();
766 assert!(
767 !s.starts_with(r"\\?\"),
768 "canonicalize_or_self should strip verbatim prefix, got: {s}"
769 );
770 }
771
772 #[test]
773 fn jail_path_accepts_same_dir_different_format() {
774 let tmp = tempfile::tempdir().unwrap();
775 let root = tmp.path().join("project");
776 std::fs::create_dir_all(&root).unwrap();
777 std::fs::write(root.join("file.rs"), "ok").unwrap();
778
779 let result = jail_path(&root.join("file.rs"), &root);
780 assert!(result.is_ok(), "same dir should be accepted: {result:?}");
781 }
782
783 #[cfg(not(feature = "no-jail"))]
784 #[test]
785 fn error_message_contains_escape_info() {
786 let _iso = crate::core::data_dir::isolated_data_dir();
789 let tmp = tempfile::tempdir().unwrap();
790 let root = tmp.path().join("root");
791 let other = tmp.path().join("other");
792 std::fs::create_dir_all(&root).unwrap();
793 std::fs::create_dir_all(&other).unwrap();
794 std::fs::write(other.join("b.txt"), "no").unwrap();
795
796 let err = jail_path(&other.join("b.txt"), &root).unwrap_err();
797 assert!(
798 err.to_string().contains("path escapes project root"),
799 "error should mention escape: {err}"
800 );
801 }
802
803 #[test]
806 fn expand_user_path_expands_tilde_and_vars() {
807 let home = dirs::home_dir().expect("home dir");
808 let home_s = home.to_string_lossy().to_string();
809
810 assert_eq!(expand_user_path("~"), home);
811 assert_eq!(expand_user_path("~/code"), home.join("code"));
812 assert_eq!(expand_user_path("$HOME/code"), home.join("code"));
813 assert_eq!(expand_user_path("${HOME}/code"), home.join("code"));
814 crate::test_env::set_var("LEAN_CTX_TEST_SUB", "sub");
816 assert_eq!(
817 expand_user_path("$HOME/$LEAN_CTX_TEST_SUB/x"),
818 PathBuf::from(format!("{home_s}/sub/x"))
819 );
820 crate::test_env::remove_var("LEAN_CTX_TEST_SUB");
821 assert_eq!(expand_user_path("/etc"), PathBuf::from("/etc"));
823 }
824
825 #[test]
826 fn expand_user_path_leaves_unset_vars_verbatim() {
827 crate::test_env::remove_var("LEAN_CTX_TEST_UNSET_VAR");
828 let p = expand_user_path("$LEAN_CTX_TEST_UNSET_VAR/code");
829 assert_eq!(p, PathBuf::from("$LEAN_CTX_TEST_UNSET_VAR/code"));
830 }
831
832 #[cfg(unix)]
845 #[test]
846 fn allow_path_root_slash_permits_everything() {
847 let _guard = crate::core::data_dir::test_env_lock();
848 let tmp = tempfile::tempdir().unwrap();
849 let root = tmp.path().join("root");
850 let other = tmp.path().join("other");
851 std::fs::create_dir_all(&root).unwrap();
852 std::fs::create_dir_all(&other).unwrap();
853 std::fs::write(other.join("b.txt"), "allowed").unwrap();
854
855 crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", "/");
856 let result = jail_path(&other.join("b.txt"), &root);
857 crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
858
859 assert!(result.is_ok(), "allow path '/' must permit all: {result:?}");
860 }
861
862 #[test]
865 fn active_relaxations_detects_allow_path_env() {
866 let _iso = crate::core::data_dir::isolated_data_dir();
867 crate::test_env::remove_var("LEAN_CTX_EXTRA_ROOTS");
868 crate::test_env::remove_var("LEAN_CTX_ALLOW_IDE_DIRS");
869 crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", "/tmp");
870
871 let relaxed = active_relaxations();
872
873 crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
874
875 assert!(
876 relaxed.iter().any(|r| r.source == "LEAN_CTX_ALLOW_PATH"),
877 "LEAN_CTX_ALLOW_PATH must be reported as a jail relaxation: {relaxed:?}"
878 );
879 }
880
881 #[cfg(not(feature = "no-jail"))]
882 #[test]
883 fn active_relaxations_empty_when_jail_intact() {
884 let _iso = crate::core::data_dir::isolated_data_dir();
885 for var in [
886 "LEAN_CTX_ALLOW_PATH",
887 "LCTX_ALLOW_PATH",
888 "LEAN_CTX_EXTRA_ROOTS",
889 "LEAN_CTX_ALLOW_IDE_DIRS",
890 ] {
891 crate::test_env::remove_var(var);
892 }
893
894 assert!(
895 active_relaxations().is_empty(),
896 "an intact jail (clean config, no relaxation env) must report no relaxations: {:?}",
897 active_relaxations()
898 );
899 }
900
901 #[test]
902 fn allow_path_env_permits_outside_root() {
903 let _guard = crate::core::data_dir::test_env_lock();
904 let tmp = tempfile::tempdir().unwrap();
905 let root = tmp.path().join("root");
906 let other = tmp.path().join("other");
907 std::fs::create_dir_all(&root).unwrap();
908 std::fs::create_dir_all(&other).unwrap();
909 std::fs::write(other.join("b.txt"), "allowed").unwrap();
910
911 let canon = canonicalize_or_self(&other);
912 crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", canon.to_string_lossy().as_ref());
913 let result = jail_path(&other.join("b.txt"), &root);
914 crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
915
916 assert!(
917 result.is_ok(),
918 "LEAN_CTX_ALLOW_PATH should permit access: {result:?}"
919 );
920 }
921
922 #[cfg(all(unix, not(feature = "no-jail")))]
923 #[test]
924 fn rejects_symlink_escape_on_unix() {
925 use std::os::unix::fs::symlink;
926
927 let _iso = crate::core::data_dir::isolated_data_dir();
930 let tmp = tempfile::tempdir().unwrap();
931 let root = tmp.path().join("root");
932 let other = tmp.path().join("other");
933 std::fs::create_dir_all(&root).unwrap();
934 std::fs::create_dir_all(&other).unwrap();
935 std::fs::write(other.join("secret.txt"), "no").unwrap();
936
937 let link = root.join("link.txt");
938 symlink(other.join("secret.txt"), &link).unwrap();
939
940 let bad = jail_path(&link, &root);
941 assert!(bad.is_err(), "symlink escape must be rejected: {bad:?}");
942 }
943
944 #[test]
945 fn rejects_null_byte_in_path() {
946 let tmp = tempfile::tempdir().unwrap();
947 let root = tmp.path().join("root");
948 std::fs::create_dir_all(&root).unwrap();
949
950 let bad_path = PathBuf::from("file\0.txt");
951 let result = jail_path(&bad_path, &root);
952 assert!(result.is_err(), "null byte in path must be rejected");
953 assert!(
954 result.unwrap_err().to_string().contains("null byte"),
955 "error must mention null byte"
956 );
957 }
958
959 #[cfg(not(feature = "no-jail"))]
965 #[test]
966 fn extra_roots_permit_paths_outside_jail() {
967 let _iso = crate::core::data_dir::isolated_data_dir();
968
969 let tmp = tempfile::tempdir().unwrap();
970 let root = tmp.path().join("project");
971 let worktree = tmp.path().join("worktree");
972 let elsewhere = tmp.path().join("elsewhere");
973 for d in [&root, &worktree, &elsewhere] {
974 std::fs::create_dir_all(d).unwrap();
975 }
976 let in_worktree = worktree.join("a.txt");
977 std::fs::write(&in_worktree, "x").unwrap();
978 let outside = elsewhere.join("b.txt");
979 std::fs::write(&outside, "y").unwrap();
980
981 assert!(jail_path(&in_worktree, &root).is_err());
983 assert!(jail_path_with_roots(&in_worktree, &root, &[]).is_err());
984
985 let extra = vec![worktree.to_string_lossy().to_string()];
988 assert!(
989 jail_path_with_roots(&in_worktree, &root, &extra).is_ok(),
990 "path under a session extra_root must resolve (#403)"
991 );
992
993 assert!(
995 jail_path_with_roots(&outside, &root, &extra).is_err(),
996 "paths outside ALL roots must still be rejected"
997 );
998
999 assert!(jail_path_with_roots(&outside, &root, &[String::new()]).is_err());
1001 }
1002}