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 let base = canonical_target(candidate);
291 roots.iter().any(|r| is_under_prefix(&base, r))
292}
293
294fn canonical_target(candidate: &Path) -> PathBuf {
298 match canonicalize_existing_ancestor(candidate) {
299 Some((mut p, remainder)) => {
300 for part in remainder.iter().rev() {
301 p.push(part);
302 }
303 p
304 }
305 None => canonicalize_or_self(candidate),
306 }
307}
308
309pub fn enforce_writable(candidate: &Path) -> Result<(), String> {
318 crate::cli::enforce_protected_store_path(candidate)?;
321 if crate::core::hive::effective_floor::is_policy_path(&canonical_target(candidate)) {
323 return Err(format!(
324 "Hive policy files are written by the engine only; agents cannot change them: {}",
325 candidate.display()
326 ));
327 }
328 match crate::core::workspace_authority::current() {
330 crate::core::workspace_authority::Authority::Legacy => {}
331 crate::core::workspace_authority::Authority::Unavailable(reason) => {
332 return Err(crate::core::workspace_authority::unavailable_reason(
333 &reason,
334 ));
335 }
336 crate::core::workspace_authority::Authority::Workspace(snapshot) => {
337 let target = canonical_target(candidate);
338 if snapshot.admits_write(&target) {
339 return Ok(());
340 }
341 return Err(format!(
342 "writes are denied outside the read-write roots of Workspace '{}' (rev {}): {}",
343 snapshot.id,
344 snapshot.revision,
345 candidate.display()
346 ));
347 }
348 }
349 if is_read_only_path(candidate) {
350 return Err(format!(
351 "path is inside a read-only root — writes are denied (read_only_roots): {}",
352 candidate.display()
353 ));
354 }
355 match super::pathjail_scope::home_scope_write_denial(&canonical_target(candidate)) {
356 Some(denial) => Err(denial),
357 None => Ok(()),
358 }
359}
360
361fn home_allow_dirs(home: &Path, ide_dirs_allowed: bool) -> Vec<PathBuf> {
372 let mut out = Vec::new();
373 if ide_dirs_allowed {
374 let targets = crate::core::editor_registry::build_targets(home);
375 collect_ide_allow_dirs(home, &targets, &mut out);
376 }
377 out
378}
379
380fn collect_ide_allow_dirs(
389 home: &Path,
390 targets: &[crate::core::editor_registry::EditorTarget],
391 out: &mut Vec<PathBuf>,
392) {
393 let mut seen: std::collections::HashSet<PathBuf> = out.iter().cloned().collect();
394 for target in targets {
395 let candidates = [
396 target.config_path.parent().map(Path::to_path_buf),
397 Some(target.detect_path.clone()),
398 ];
399 for cand in candidates.into_iter().flatten() {
400 if cand.as_path() == home || !cand.starts_with(home) || !cand.is_dir() {
401 continue;
402 }
403 let resolved = canonicalize_secure(&cand);
404 if seen.insert(resolved.clone()) {
405 out.push(resolved);
406 }
407 }
408 }
409}
410
411fn is_under_prefix(path: &Path, prefix: &Path) -> bool {
412 path.starts_with(prefix)
413}
414
415pub fn is_harness_auto_memory_path(path: &Path) -> bool {
424 let lower = path.to_string_lossy().replace('\\', "/").to_lowercase();
425 for marker in ["/.claude/projects/", "/.codebuddy/projects/"] {
426 if let Some(idx) = lower.find(marker) {
427 let after = &lower[idx + marker.len()..];
428 let mut parts = after.split('/');
429 let Some(_slug) = parts.next() else {
430 continue;
431 };
432 if parts.next() == Some("memory") {
433 return true;
434 }
435 }
436 }
437 false
438}
439
440fn path_allowed_by_jail(base: &Path, root: &Path, allow: &[PathBuf]) -> bool {
441 if is_harness_auto_memory_path(base) {
442 return true;
443 }
444 let allowed = is_under_prefix(base, root)
445 || allow.iter().any(|p| is_under_prefix(base, p))
446 || super::pathjail_scope::home_scope_admits(base);
447 #[cfg(windows)]
448 let allowed = allowed || is_under_prefix_windows(base, root);
449 allowed && super::pathjail_scope::protected_zone_permits(base, root, allow)
450}
451
452pub fn canonicalize_or_self(path: &Path) -> PathBuf {
456 super::pathutil::safe_canonicalize_bounded(path, 2000)
457}
458
459pub(crate) fn canonicalize_secure(path: &Path) -> PathBuf {
464 super::pathutil::canonicalize_secure_bounded(path, 2000)
465}
466
467fn canonicalize_existing_ancestor(path: &Path) -> Option<(PathBuf, Vec<std::ffi::OsString>)> {
468 let mut cur = path.to_path_buf();
469 let mut remainder: Vec<std::ffi::OsString> = Vec::new();
470 loop {
471 if cur.exists() {
472 return Some((canonicalize_secure(&cur), remainder));
473 }
474 let name = cur.file_name()?.to_os_string();
475 remainder.push(name);
476 if !cur.pop() {
477 return None;
478 }
479 }
480}
481
482pub fn jail_path(candidate: &Path, jail_root: &Path) -> Result<PathBuf, PathJailError> {
483 jail_path_with_roots(candidate, jail_root, &[])
484}
485
486fn jail_in_workspace(
494 candidate: &Path,
495 jail_root: &Path,
496 snapshot: &crate::core::workspace_authority::Snapshot,
497) -> Result<PathBuf, PathJailError> {
498 let canonical = |path: &Path| crate::core::pathutil::canonicalize_secure(path).ok();
499 let base_root = canonical(jail_root)
500 .filter(|root| snapshot.admits(root))
501 .unwrap_or_else(|| snapshot.primary.clone());
502 let candidate = if candidate.is_absolute() {
503 candidate.to_path_buf()
504 } else {
505 base_root.join(candidate)
506 };
507 let admitted = |path: &Path| snapshot.admits(path);
508 let outside = |path: &Path| PathJailError::OutsideWorkspace {
509 path: path.to_path_buf(),
510 workspace: snapshot.id.clone(),
511 revision: snapshot.revision,
512 roots: snapshot
513 .granting_roots()
514 .map(|(root, access)| format!("{} ({})", root.display(), access.as_str()))
515 .collect::<Vec<_>>()
516 .join(", "),
517 };
518
519 let mut existing = candidate.clone();
520 let mut remainder: Vec<std::ffi::OsString> = Vec::new();
521 while !existing.exists() {
522 let Some(name) = existing.file_name() else {
523 return Err(PathJailError::NoExistingAncestor { path: candidate });
524 };
525 remainder.push(name.to_os_string());
526 if !existing.pop() {
527 return Err(PathJailError::NoExistingAncestor { path: candidate });
528 }
529 }
530 if remainder
531 .iter()
532 .any(|part| part == std::ffi::OsStr::new("..") || part == std::ffi::OsStr::new("."))
533 {
534 return Err(outside(&candidate));
535 }
536 let base = canonical(&existing).ok_or_else(|| outside(&candidate))?;
539 if !admitted(&base) {
540 return Err(outside(&candidate));
541 }
542
543 #[cfg(windows)]
544 reject_symlink_on_windows(&candidate)?;
545
546 let mut out = base;
547 for part in remainder.iter().rev() {
548 out.push(part);
549 }
550 if out.exists() {
551 let resolved = canonical(&out).ok_or_else(|| outside(&candidate))?;
552 if !admitted(&resolved) {
553 return Err(PathJailError::PostCanonicalizeEscape {
554 path: candidate,
555 resolved,
556 });
557 }
558 }
559 crate::cli::enforce_protected_store_path(&out)
560 .map_err(|reason| PathJailError::ProtectedContext { reason })?;
561 Ok(out)
562}
563
564const LANGUAGE_CACHE_PATTERNS: &[(&str, &str, &str)] = &[
569 ("/go/pkg/mod/", "Go module cache", "~/go/pkg/mod"),
570 (
571 "/.cargo/registry/",
572 "Rust crate registry",
573 "~/.cargo/registry",
574 ),
575 (
576 "/site-packages/",
577 "Python site-packages",
578 "<venv>/lib/pythonX.Y/site-packages",
579 ),
580 ("/node_modules/", "Node modules", "<project>/node_modules"),
581 (
582 "/.m2/repository/",
583 "Maven local repository",
584 "~/.m2/repository",
585 ),
586 ("/.gradle/caches/", "Gradle cache", "~/.gradle/caches"),
587 (
588 "/.nuget/packages/",
589 "NuGet package cache",
590 "~/.nuget/packages",
591 ),
592 (
596 "/.rustup/toolchains/",
597 "Rust toolchain source",
598 "~/.rustup/toolchains",
599 ),
600 (
601 "/.cargo/git/checkouts/",
602 "Cargo git dependencies",
603 "~/.cargo/git/checkouts",
604 ),
605 (
606 "/.bun/install/cache/",
607 "Bun package cache",
608 "~/.bun/install/cache",
609 ),
610 (
611 "/.pub-cache/hosted/",
612 "Dart pub cache",
613 "~/.pub-cache/hosted",
614 ),
615 ("/.gem/ruby/", "Ruby gems", "~/.gem/ruby"),
616 (
619 "/.pyenv/versions/",
620 "pyenv Python installations",
621 "~/.pyenv/versions",
622 ),
623];
624
625const AGENT_INSTRUCTION_ROOTS: &[(&str, &str)] = &[
641 (".claude/skills", "Claude Code skills"),
642 (".claude/commands", "Claude Code commands"),
643 (".claude/agents", "Claude Code agents"),
644 (".claude/plans", "Claude Code plans"),
645 (".claude/rules", "Claude Code rules"),
646 (".claude/plugins/marketplaces", "Claude Code plugins"),
647 (".claude/plugins/cache", "Claude Code plugins"),
648 (".claude/CLAUDE.md", "Claude Code instructions"),
649 (".claude/settings.json", "Claude Code settings"),
650 (".claude/settings.local.json", "Claude Code settings"),
651 (".claude/keybindings.json", "Claude Code settings"),
652 (".codex/skills", "Codex skills"),
653 (".codex/prompts", "Codex prompts"),
654 (".codex/AGENTS.md", "Codex instructions"),
655 (".codex/config.toml", "Codex config"),
656 (".codex/hooks.json", "Codex config"),
657 (".agents/skills", "agent skills"),
658 (".cursor/rules", "Cursor rules"),
659 (".cursor/skills", "Cursor skills"),
660 (".cursor/commands", "Cursor commands"),
661 (".cursor/mcp.json", "Cursor config"),
662 (".cursor/hooks.json", "Cursor config"),
663 (".gemini/GEMINI.md", "Gemini instructions"),
664 (".gemini/commands", "Gemini commands"),
665 (".gemini/settings.json", "Gemini config"),
666 (".codebuddy/settings.json", "CodeBuddy settings"),
667 (".config/opencode/agent", "OpenCode agents"),
668 (".config/opencode/command", "OpenCode commands"),
669 (".config/opencode/AGENTS.md", "OpenCode instructions"),
670 (".config/opencode/opencode.json", "OpenCode config"),
671 (".config/opencode/opencode.jsonc", "OpenCode config"),
672 (".codeium/windsurf/mcp_config.json", "Windsurf config"),
673];
674
675const CURSOR_AGENT_OUTPUT_DIRS: &[&str] = &["agent-tools", "terminals"];
684const CURSOR_AGENT_OUTPUT_LABEL: &str = "Cursor agent output";
685
686fn cursor_workspace_slug(root: &Path) -> String {
690 let slug: String = root
691 .to_string_lossy()
692 .chars()
693 .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
694 .collect();
695 slug.trim_start_matches('-').to_string()
696}
697
698fn is_cursor_agent_output_root(path: &Path) -> bool {
702 let mut back = path.components().rev().map(std::path::Component::as_os_str);
703 let (Some(dir), Some(_workspace), Some(projects), Some(cursor)) =
704 (back.next(), back.next(), back.next(), back.next())
705 else {
706 return false;
707 };
708 cursor == ".cursor"
709 && projects == "projects"
710 && CURSOR_AGENT_OUTPUT_DIRS.iter().any(|d| dir == *d)
711}
712
713fn cursor_workspace_matches(
719 admitted_root: &Path,
720 jail_root: &Path,
721 extra_roots: &[String],
722) -> bool {
723 let Some(workspace) = admitted_root.parent().and_then(Path::file_name) else {
724 return false;
725 };
726 std::iter::once(jail_root.to_path_buf())
727 .chain(extra_roots.iter().map(PathBuf::from))
728 .flat_map(|root| [canonicalize_secure(&root), root])
729 .any(|root| workspace == cursor_workspace_slug(&root).as_str())
730}
731
732fn cursor_agent_output_root(rel: &Path) -> Option<PathBuf> {
735 let mut parts = rel.components().map(std::path::Component::as_os_str);
736 if parts.next()? != ".cursor" || parts.next()? != "projects" {
737 return None;
738 }
739 let workspace = parts.next()?;
740 let dir = parts.next()?;
741 CURSOR_AGENT_OUTPUT_DIRS
742 .iter()
743 .any(|d| dir == *d)
744 .then(|| Path::new(".cursor/projects").join(workspace).join(dir))
745}
746
747fn detect_agent_instruction_root(candidate: &Path) -> Option<(&'static str, PathBuf)> {
752 let home = dirs::home_dir()?;
753 let canon_home = canonicalize_secure(&home);
754 let rel = candidate
755 .strip_prefix(&home)
756 .or_else(|_| candidate.strip_prefix(&canon_home))
757 .ok()?;
758 if rel
760 .components()
761 .any(|c| !matches!(c, std::path::Component::Normal(_)))
762 {
763 return None;
764 }
765 AGENT_INSTRUCTION_ROOTS
766 .iter()
767 .find(|(root, _)| rel.starts_with(root))
768 .map(|&(root, label)| (label, canon_home.join(root)))
769 .or_else(|| detect_host_session_output_root(rel, &canon_home))
770 .or_else(|| {
771 cursor_agent_output_root(rel)
772 .map(|root| canon_home.join(root))
773 .filter(|root| canonicalize_secure(root) == *root)
777 .map(|root| (CURSOR_AGENT_OUTPUT_LABEL, root))
778 })
779}
780
781fn detect_host_session_output_root(
793 rel: &Path,
794 canon_home: &Path,
795) -> Option<(&'static str, PathBuf)> {
796 let parts: Vec<&str> = rel
797 .components()
798 .map(|c| c.as_os_str().to_str())
799 .collect::<Option<_>>()?;
800 let (depth, label) = match parts.as_slice() {
801 [
802 ".claude",
803 "projects",
804 _,
805 _,
806 "tool-results" | "subagents",
807 ..,
808 ] => (5, "Claude Code session output"),
809 _ => return None,
810 };
811 Some((
812 label,
813 canon_home.join(parts[..depth].iter().collect::<PathBuf>()),
814 ))
815}
816
817#[cfg(unix)]
823fn detect_host_scratch_root(candidate: &Path) -> Option<(&'static str, PathBuf)> {
824 use std::os::unix::fs::MetadataExt;
825 let uid = unsafe { libc::geteuid() };
827 let name = format!("claude-{uid}");
828 let (base, rest) = canonicalize_existing_ancestor(candidate)?;
831 let candidate = rest.iter().rev().fold(base, |path, part| path.join(part));
832 [std::env::temp_dir(), PathBuf::from("/tmp")]
833 .into_iter()
834 .map(|tmp| tmp.join(&name))
835 .find_map(|dir| {
836 let meta = std::fs::symlink_metadata(&dir).ok()?;
837 let root = canonicalize_secure(&dir);
838 (meta.is_dir()
839 && meta.uid() == uid
840 && meta.mode() & 0o022 == 0
841 && candidate.starts_with(&root))
842 .then_some(("Claude Code scratchpad", root))
843 })
844}
845
846#[cfg(not(unix))]
847fn detect_host_scratch_root(_candidate: &Path) -> Option<(&'static str, PathBuf)> {
848 None
849}
850
851pub fn register_symlink_target_read_only(candidate: &Path, root: &Path) -> bool {
864 if detect_agent_instruction_root(root)
865 .is_none_or(|(label, _)| label == CURSOR_AGENT_OUTPUT_LABEL)
866 || (!candidate.starts_with(root) && !candidate.starts_with(canonicalize_secure(root)))
867 {
868 return false;
869 }
870 let Ok(target) = std::fs::canonicalize(candidate) else {
871 return false;
872 };
873 let root = canonicalize_secure(root);
874 if target.starts_with(&root) {
875 return false;
876 }
877 if let Some((_, agent_root)) = detect_agent_instruction_root(&target) {
880 return register_session_read_only_root(&agent_root);
881 }
882 let dir = if target.is_dir() {
883 target
884 } else {
885 match target.parent() {
886 Some(parent) => parent.to_path_buf(),
887 None => return false,
888 }
889 };
890 let below_home =
891 dirs::home_dir().is_some_and(|home| dir.starts_with(canonicalize_secure(&home)));
892 if !below_home
893 || crate::core::pathutil::is_broad_or_unsafe_root(&dir)
894 || super::pathjail_scope::in_protected_zone(&dir)
895 {
896 return false;
897 }
898 register_session_read_only_root(&dir)
899}
900
901pub fn jail_path_auto_admitting(
909 candidate: &Path,
910 jail_root: &Path,
911 extra_roots: &[String],
912) -> Result<PathBuf, PathJailError> {
913 let first = jail_path_with_roots(candidate, jail_root, extra_roots);
914 let Err(refused) = first else {
915 return first;
916 };
917 if crate::core::workspace_authority::is_configured() {
920 return Err(refused);
921 }
922 let Some((label, root)) = detect_language_cache_root(candidate) else {
923 return Err(refused);
924 };
925 if label == CURSOR_AGENT_OUTPUT_LABEL
928 && !cursor_workspace_matches(&root, jail_root, extra_roots)
929 {
930 return Err(refused);
931 }
932 if register_session_read_only_root(&root) {
933 tracing::info!(
934 "auto-registered {label} at {} as a read-only root",
935 root.display()
936 );
937 }
938 let retry = jail_path_with_roots(candidate, jail_root, extra_roots);
939 if retry.is_err() && register_symlink_target_read_only(candidate, &root) {
943 return jail_path_with_roots(candidate, jail_root, extra_roots);
944 }
945 retry
946}
947
948fn detected_cache_hint(candidate: &std::path::Path) -> Option<String> {
952 let s = candidate.to_string_lossy();
953 for &(pattern, name, example) in LANGUAGE_CACHE_PATTERNS {
954 if s.contains(pattern) {
955 return Some(format!(
956 ". Detected {name} — add read_only_roots = [\"{example}\"] to \
957 ~/.config/lean-ctx/config.toml for cached, compressed reads without write access"
958 ));
959 }
960 }
961 None
962}
963
964pub fn detect_language_cache_root(candidate: &Path) -> Option<(&'static str, PathBuf)> {
969 if let Some(found) = detect_agent_instruction_root(candidate) {
970 return Some(found);
971 }
972 if let Some(found) = detect_host_scratch_root(candidate) {
973 return Some(found);
974 }
975 let s = candidate.to_string_lossy().replace('\\', "/");
976 for &(marker, label, _) in LANGUAGE_CACHE_PATTERNS {
977 if let Some(idx) = s.find(marker) {
978 let end = idx + marker.len() - 1; return Some((label, PathBuf::from(&s[..end])));
980 }
981 }
982 None
983}
984
985pub fn jail_path_with_roots(
995 candidate: &Path,
996 jail_root: &Path,
997 extra_roots: &[String],
998) -> Result<PathBuf, PathJailError> {
999 jail_path_checked(candidate, jail_root, extra_roots, true)
1000}
1001
1002pub fn jail_path_enforced(candidate: &Path, jail_root: &Path) -> Result<PathBuf, PathJailError> {
1011 jail_path_checked(candidate, jail_root, &[], false)
1012}
1013
1014fn jail_path_checked(
1015 candidate: &Path,
1016 jail_root: &Path,
1017 extra_roots: &[String],
1018 honor_off_switch: bool,
1019) -> Result<PathBuf, PathJailError> {
1020 if candidate.to_string_lossy().as_bytes().contains(&0) {
1021 return Err(PathJailError::NullByte);
1022 }
1023
1024 let absolute = if candidate.is_absolute() {
1028 candidate.to_path_buf()
1029 } else {
1030 jail_root.join(candidate)
1031 };
1032 crate::cli::enforce_protected_store_path(&absolute)
1033 .map_err(|reason| PathJailError::ProtectedContext { reason })?;
1034
1035 match crate::core::workspace_authority::current() {
1039 crate::core::workspace_authority::Authority::Legacy => {}
1040 crate::core::workspace_authority::Authority::Unavailable(reason) => {
1041 return Err(PathJailError::WorkspaceUnavailable {
1042 reason: crate::core::workspace_authority::unavailable_reason(&reason),
1043 });
1044 }
1045 crate::core::workspace_authority::Authority::Workspace(snapshot) => {
1046 return jail_in_workspace(candidate, jail_root, &snapshot);
1047 }
1048 }
1049
1050 #[cfg(feature = "no-jail")]
1054 {
1055 if honor_off_switch {
1056 return Ok(canonicalize_or_self(&absolute));
1057 }
1058 }
1059
1060 {
1061 let cfg = crate::core::config::Config::load();
1062 if honor_off_switch && cfg.path_jail == Some(false) {
1063 return Ok(canonicalize_or_self(&absolute));
1064 }
1065
1066 let root = canonicalize_secure(jail_root);
1067
1068 let resolved: PathBuf;
1073 let candidate: &Path = if candidate.is_absolute() {
1074 candidate
1075 } else {
1076 resolved = root.join(candidate);
1077 resolved.as_path()
1078 };
1079
1080 let mut allow = allow_paths_from_env_and_config();
1081 allow.extend(
1083 extra_roots
1084 .iter()
1085 .filter(|r| !r.is_empty())
1086 .map(|r| canonicalize_secure(Path::new(r))),
1087 );
1088
1089 if let Ok(state) = crate::core::paths::state_dir() {
1093 allow.push(canonicalize_secure(&state));
1094 }
1095 allow.extend(
1100 read_only_roots_from_env_and_config()
1101 .into_iter()
1102 .map(|p| canonicalize_secure(&p))
1103 .filter(|p| {
1104 !is_cursor_agent_output_root(p)
1105 || cursor_workspace_matches(p, jail_root, extra_roots)
1106 }),
1107 );
1108
1109 let (base, remainder) = canonicalize_existing_ancestor(candidate).ok_or_else(|| {
1110 PathJailError::NoExistingAncestor {
1111 path: candidate.to_path_buf(),
1112 }
1113 })?;
1114
1115 let allowed = path_allowed_by_jail(&base, &root, &allow);
1116
1117 if !allowed {
1118 let is_suspicious = crate::tools::startup::is_suspicious_root(&root);
1119 let mut hint = if is_suspicious || root == std::path::Path::new("/") {
1120 ". lean-ctx has not bound this session to a project yet (the host reported \
1121 no project directory). Relative paths cannot bind it: pass one \
1122 absolute path inside the project, e.g. /home/me/code/my-app/README.md, \
1123 and it stays the session project; if it persists: lean-ctx doctor --fix"
1124 .to_string()
1125 } else {
1126 super::pathjail_scope::escape_hint(candidate, &base, &root)
1127 };
1128 if let Some(notice) = crate::core::workspace_trust::untrusted_override_notice() {
1132 hint.push_str(". ");
1133 hint.push_str(¬ice);
1134 }
1135 if let Some(missing) = crate::core::config::Config::missing_config_path() {
1139 hint.push_str(&format!(
1140 ". ⚠ lean-ctx reads no config file at {} (running on defaults) — an \
1141 allow_paths edit in a config.toml elsewhere is not read; \
1142 `lean-ctx doctor` shows the path in effect",
1143 missing.display()
1144 ));
1145 }
1146 if let Some(cache_hint) = detected_cache_hint(candidate) {
1147 hint.push_str(&cache_hint);
1148 }
1149 return Err(PathJailError::EscapesRoot {
1150 path: candidate.to_path_buf(),
1151 root,
1152 hint,
1153 });
1154 }
1155
1156 #[cfg(windows)]
1157 reject_symlink_on_windows(candidate)?;
1158
1159 let mut out = base;
1160 for part in remainder.iter().rev() {
1161 out.push(part);
1162 }
1163
1164 if out.exists() {
1167 let final_canon = canonicalize_secure(&out);
1168 let final_ok = path_allowed_by_jail(&final_canon, &root, &allow);
1169 if !final_ok {
1170 return Err(PathJailError::PostCanonicalizeEscape {
1171 path: candidate.to_path_buf(),
1172 resolved: final_canon,
1173 });
1174 }
1175 }
1176
1177 crate::cli::enforce_protected_store_path(&out)
1178 .map_err(|reason| PathJailError::ProtectedContext { reason })?;
1179 Ok(out)
1180 }
1181}
1182
1183#[cfg(all(test, target_os = "macos"))]
1184mod protected_store_tests {
1185 use super::*;
1186
1187 #[test]
1188 fn runtime_store_is_not_reopened_by_implicit_or_explicit_roots() {
1189 let isolated = crate::core::data_dir::isolated_data_dir();
1190 let project = tempfile::tempdir().unwrap();
1191 let store = isolated.path().join("knowledge");
1192 std::fs::create_dir_all(&store).unwrap();
1193 let fact = store.join("facts.json");
1194 std::fs::write(&fact, "private stored context").unwrap();
1195 let code = project.path().join("main.rs");
1196 std::fs::write(&code, "fn main() {}\n").unwrap();
1197 assert!(
1198 jail_path(&fact, project.path()).is_ok(),
1199 "Community keeps its existing runtime access"
1200 );
1201 let _protected = crate::cli::pin_synthetic_session(isolated.path()).unwrap();
1202 let roots = vec![isolated.path().to_string_lossy().into_owned()];
1203 for candidate in [&fact, &store, &isolated.path().to_path_buf()] {
1204 assert!(
1205 matches!(
1206 jail_path_with_roots(candidate, project.path(), &roots),
1207 Err(PathJailError::ProtectedContext { .. })
1208 ),
1209 "{candidate:?}"
1210 );
1211 }
1212 assert!(jail_path(&code, project.path()).is_ok());
1213 assert!(jail_path_with_roots(Path::new("facts.json"), &store, &roots).is_err());
1214 for target in [&fact, &store.join("new/backup.json")] {
1217 assert!(
1218 crate::tools::edit_io::write_atomic_bytes_with_permissions(
1219 target,
1220 b"forged local context",
1221 None,
1222 )
1223 .is_err()
1224 );
1225 }
1226 assert_eq!(
1227 std::fs::read_to_string(&fact).unwrap(),
1228 "private stored context"
1229 );
1230 assert!(!store.join("new").exists());
1231 crate::tools::edit_io::write_atomic_bytes_with_permissions(&code, b"fn main() {}\n", None)
1232 .unwrap();
1233 std::fs::write(&fact, "retained internal update").unwrap();
1235 assert_eq!(
1236 std::fs::read_to_string(&fact).unwrap(),
1237 "retained internal update"
1238 );
1239 }
1240
1241 #[test]
1242 fn missing_child_profile_never_falls_back_to_the_normal_jail() {
1243 let isolated = crate::core::data_dir::isolated_data_dir();
1244 let project = tempfile::tempdir().unwrap();
1245 let code = project.path().join("main.rs");
1246 std::fs::write(&code, "fn main() {}\n").unwrap();
1247 let _protected = crate::cli::pin_synthetic_session(isolated.path()).unwrap();
1248 crate::test_env::remove_var(crate::cli::CHILD_PROFILE_ENV);
1249 assert!(matches!(
1250 jail_path(&code, project.path()),
1251 Err(PathJailError::ProtectedContext { .. })
1252 ));
1253 }
1254}
1255
1256#[cfg(windows)]
1257fn is_under_prefix_windows(path: &Path, prefix: &Path) -> bool {
1258 let path_str = normalize_windows_path(&path.to_string_lossy());
1259 let prefix_str = normalize_windows_path(&prefix.to_string_lossy());
1260 let prefix_str = prefix_str.trim_end_matches('\\');
1261 path_str == prefix_str
1263 || path_str
1264 .strip_prefix(prefix_str)
1265 .is_some_and(|rest| rest.starts_with('\\'))
1266}
1267
1268#[cfg(windows)]
1269fn normalize_windows_path(s: &str) -> String {
1270 let stripped = super::pathutil::strip_verbatim_str(s).unwrap_or_else(|| s.to_string());
1271 stripped.to_lowercase().replace('/', "\\")
1272}
1273
1274#[cfg(windows)]
1275fn reject_symlink_on_windows(path: &Path) -> Result<(), PathJailError> {
1276 if let Ok(meta) = std::fs::symlink_metadata(path) {
1277 if super::pathutil::is_symlink_or_reparse(&meta) {
1280 return Err(PathJailError::Symlink {
1281 path: path.to_path_buf(),
1282 });
1283 }
1284 }
1285 Ok(())
1286}
1287
1288#[cfg(all(test, windows))]
1289#[path = "pathjail_windows_tests.rs"]
1290mod windows_prefix_tests;
1291
1292#[cfg(test)]
1293#[path = "pathjail_tests.rs"]
1294mod tests;