1use std::path::{Path, PathBuf};
2
3use crate::core::error::PathJailError;
4
5pub use crate::core::pathjail_write::{rebuild_below, write_below};
6
7pub fn expand_user_path(raw: &str) -> PathBuf {
15 let mut s = raw.to_string();
16
17 if (s == "~" || s.starts_with("~/"))
18 && let Some(home) = dirs::home_dir()
19 {
20 s = format!("{}{}", home.to_string_lossy(), &s[1..]);
21 }
22
23 while let Some(start) = s.find('$') {
24 let rest = &s[start + 1..];
25 let (name, token_len) = if let Some(stripped) = rest.strip_prefix('{') {
26 match stripped.find('}') {
27 Some(end) => (stripped[..end].to_string(), end + 3),
28 None => break,
29 }
30 } else {
31 let end = rest
32 .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
33 .unwrap_or(rest.len());
34 (rest[..end].to_string(), end + 1)
35 };
36 if name.is_empty() {
37 break;
38 }
39 if let Ok(val) = std::env::var(&name) {
40 s.replace_range(start..start + token_len, &val);
41 } else if name == "HOME"
42 && let Some(home) = dirs::home_dir()
43 {
44 let home = home.to_string_lossy();
45 s.replace_range(start..start + token_len, home.as_ref());
46 } else {
47 tracing::warn!(
48 "allow_paths/extra_roots entry '{raw}' references unset variable ${name} — entry will never match"
49 );
50 break;
51 }
52 }
53
54 PathBuf::from(s)
55}
56
57pub fn allow_paths_from_env_and_config() -> Vec<PathBuf> {
58 let mut out = Vec::new();
59 let cfg = crate::core::config::Config::load();
60
61 if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
73 out.push(canonicalize_secure(&data_dir));
74 }
75
76 if let Some(home) = dirs::home_dir() {
77 let ide_dirs_allowed = cfg.allow_ide_config_dirs.unwrap_or(false)
78 || std::env::var("LEAN_CTX_ALLOW_IDE_DIRS").is_ok_and(|v| v == "1");
79 out.extend(home_allow_dirs(&home, ide_dirs_allowed));
80 }
81
82 for p in &cfg.allow_paths {
83 out.push(canonicalize_secure(&expand_user_path(p)));
84 }
85 for p in &cfg.extra_roots {
86 out.push(canonicalize_secure(&expand_user_path(p)));
87 }
88
89 for path in crate::core::runtime_flags::allow_paths() {
90 out.push(canonicalize_secure(&path));
91 }
92 let v = std::env::var("LCTX_ALLOW_PATH")
95 .or_else(|_| std::env::var("LEAN_CTX_ALLOW_PATH"))
96 .unwrap_or_default();
97 if !v.trim().is_empty() {
98 for p in std::env::split_paths(&v) {
99 out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
100 }
101 }
102
103 let extra = std::env::var("LEAN_CTX_EXTRA_ROOTS").unwrap_or_default();
104 if !extra.trim().is_empty() {
105 for p in std::env::split_paths(&extra) {
106 out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
107 }
108 }
109
110 out.extend(canonicalized_roots(
115 &cfg.read_only_roots,
116 "LEAN_CTX_READ_ONLY_ROOTS",
117 ));
118
119 out
120}
121
122fn canonicalized_roots(config_entries: &[String], env_var: &str) -> Vec<PathBuf> {
127 let mut out = Vec::new();
128 for p in config_entries {
129 out.push(canonicalize_secure(&expand_user_path(p)));
130 }
131 let v = std::env::var(env_var).unwrap_or_default();
132 if !v.trim().is_empty() {
133 for p in std::env::split_paths(&v) {
134 out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
135 }
136 }
137 out
138}
139
140pub fn read_only_roots_from_env_and_config() -> Vec<PathBuf> {
145 let cfg = crate::core::config::Config::load();
146 let mut roots = canonicalized_roots(&cfg.read_only_roots, "LEAN_CTX_READ_ONLY_ROOTS");
147 roots.extend(session_read_only_roots());
152 roots
153}
154
155static SESSION_READ_ONLY_ROOTS: std::sync::OnceLock<std::sync::Mutex<Vec<PathBuf>>> =
156 std::sync::OnceLock::new();
157
158fn session_read_only_roots_cell() -> &'static std::sync::Mutex<Vec<PathBuf>> {
159 SESSION_READ_ONLY_ROOTS.get_or_init(|| std::sync::Mutex::new(Vec::new()))
160}
161
162pub fn session_read_only_roots() -> Vec<PathBuf> {
164 session_read_only_roots_cell()
165 .lock()
166 .map(|g| g.clone())
167 .unwrap_or_default()
168}
169
170pub fn register_session_read_only_root(root: &Path) -> bool {
180 let canon = canonicalize_secure(root);
181 let mut guard = match session_read_only_roots_cell().lock() {
182 Ok(g) => g,
183 Err(poisoned) => poisoned.into_inner(),
184 };
185 if guard.iter().any(|r| r == &canon) {
186 return false;
187 }
188 guard.push(canon);
189 true
190}
191
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
199pub struct JailRelaxation {
200 pub source: &'static str,
202 pub detail: &'static str,
204}
205
206fn env_is_set(var: &str) -> bool {
207 std::env::var(var).is_ok_and(|v| !v.trim().is_empty())
208}
209
210#[must_use]
214pub fn active_relaxations() -> Vec<JailRelaxation> {
215 let mut out = Vec::new();
216
217 if cfg!(feature = "no-jail") {
218 out.push(JailRelaxation {
219 source: "no-jail (build feature)",
220 detail: "path jail compiled out — every tool path is allowed",
221 });
222 }
223
224 if crate::core::config::Config::load().path_jail == Some(false) {
225 out.push(JailRelaxation {
226 source: "path_jail = false (config.toml)",
227 detail: "path jail disabled — every tool path is allowed",
228 });
229 }
230
231 if crate::core::runtime_flags::allow_path_enabled() {
232 out.push(JailRelaxation {
233 source: "LEAN_CTX_ALLOW_PATH",
234 detail: "widens the read/write allow-list beyond the project root",
235 });
236 }
237
238 if env_is_set("LEAN_CTX_EXTRA_ROOTS") {
239 out.push(JailRelaxation {
240 source: "LEAN_CTX_EXTRA_ROOTS",
241 detail: "adds extra accessible roots beyond the project root",
242 });
243 }
244
245 let ide_env = std::env::var("LEAN_CTX_ALLOW_IDE_DIRS").is_ok_and(|v| v == "1");
246 if ide_env
247 || crate::core::config::Config::load()
248 .allow_ide_config_dirs
249 .unwrap_or(false)
250 {
251 out.push(JailRelaxation {
252 source: if ide_env {
253 "LEAN_CTX_ALLOW_IDE_DIRS=1"
254 } else {
255 "allow_ide_config_dirs = true (config.toml)"
256 },
257 detail: "exposes ~/.cursor, ~/.claude, … (other agents' sessions/credentials) to tools",
258 });
259 }
260
261 if super::pathjail_scope::PathJailScope::resolve() == super::pathjail_scope::PathJailScope::Home
264 {
265 out.push(JailRelaxation {
266 source: if std::env::var("LEAN_CTX_PATH_JAIL_SCOPE")
267 .ok()
268 .and_then(|v| super::pathjail_scope::PathJailScope::parse(&v))
269 .is_some()
270 {
271 "LEAN_CTX_PATH_JAIL_SCOPE=home"
272 } else {
273 "path_jail_scope = home (config.toml)"
274 },
275 detail: "reads and writes anywhere below ~ outside protected zones, not only in the active project",
276 });
277 }
278
279 out
280}
281
282pub fn warn_if_relaxed() {
286 for relaxation in active_relaxations() {
287 tracing::warn!(
288 "[SECURITY] path jail relaxed via {}: {} — intended for trusted local use only",
289 relaxation.source,
290 relaxation.detail
291 );
292 }
293}
294
295pub fn is_read_only_path(candidate: &Path) -> bool {
306 let roots = read_only_roots_from_env_and_config();
307 if roots.is_empty() {
308 return false;
309 }
310 let base = canonical_target(candidate);
311 roots.iter().any(|r| is_under_prefix(&base, r))
312}
313
314pub(crate) fn canonical_target(candidate: &Path) -> PathBuf {
318 match canonicalize_existing_ancestor(candidate) {
319 Some((mut p, remainder)) => {
320 for part in remainder.iter().rev() {
321 p.push(part);
322 }
323 p
324 }
325 None => canonicalize_or_self(candidate),
326 }
327}
328
329pub fn enforce_writable(candidate: &Path) -> Result<(), String> {
338 crate::core::protected_store::enforce_protected_store_path(candidate)?;
341 if crate::core::policy::cloud_floor::is_policy_path(&canonical_target(candidate)) {
343 return Err(format!(
344 "LeanCTX Cloud policy files are written by the instance only; agents cannot change them: {}",
345 candidate.display()
346 ));
347 }
348 crate::core::session_rights::check_write(candidate)?;
351 if let Some(denial) =
354 super::pathjail_autobind::adopted_write_denial(&canonical_target(candidate))
355 {
356 return Err(denial);
357 }
358 match crate::core::workspace_authority::current() {
360 crate::core::workspace_authority::Authority::Legacy => {}
361 crate::core::workspace_authority::Authority::Unavailable(reason) => {
362 return Err(crate::core::workspace_authority::unavailable_reason(
363 &reason,
364 ));
365 }
366 crate::core::workspace_authority::Authority::Workspace(snapshot) => {
367 let target = canonical_target(candidate);
368 if snapshot.admits_write(&target) {
369 return Ok(());
370 }
371 return Err(format!(
372 "writes are denied outside the read-write roots of Workspace '{}' (rev {}): {}",
373 snapshot.id,
374 snapshot.revision,
375 candidate.display()
376 ));
377 }
378 }
379 if is_read_only_path(candidate) {
380 return Err(format!(
381 "path is inside a read-only root — writes are denied (read_only_roots): {}",
382 candidate.display()
383 ));
384 }
385 match super::pathjail_scope::home_scope_write_denial(&canonical_target(candidate)) {
386 Some(denial) => Err(denial),
387 None => Ok(()),
388 }
389}
390
391fn home_allow_dirs(home: &Path, ide_dirs_allowed: bool) -> Vec<PathBuf> {
402 let mut out = Vec::new();
403 if ide_dirs_allowed {
404 let targets = ide_dirs::editor_targets(home);
406 collect_ide_allow_dirs(home, &targets, &mut out);
407 }
408 out
409}
410
411fn collect_ide_allow_dirs(
420 home: &Path,
421 targets: &[crate::core::editor_registry::EditorTarget],
422 out: &mut Vec<PathBuf>,
423) {
424 let mut seen: std::collections::HashSet<PathBuf> = out.iter().cloned().collect();
425 for target in targets {
426 let candidates = [
427 target.config_path.parent().map(Path::to_path_buf),
428 Some(target.detect_path.clone()),
429 ];
430 for cand in candidates.into_iter().flatten() {
431 if cand.as_path() == home || !cand.starts_with(home) || !cand.is_dir() {
432 continue;
433 }
434 let resolved = canonicalize_secure(&cand);
435 if seen.insert(resolved.clone()) {
436 out.push(resolved);
437 }
438 }
439 }
440}
441
442fn is_under_prefix(path: &Path, prefix: &Path) -> bool {
443 path.starts_with(prefix)
444}
445
446pub fn is_harness_auto_memory_path(path: &Path) -> bool {
460 use std::path::Component;
461 harness_project_dirs().iter().any(|projects| {
462 let Ok(rest) = path.strip_prefix(projects) else {
463 return false;
464 };
465 if rest
466 .components()
467 .any(|c| !matches!(c, Component::Normal(_)))
468 {
469 return false;
470 }
471 let mut parts = rest.components();
472 parts.next().is_some()
473 && parts
474 .next()
475 .is_some_and(|c| c.as_os_str().eq_ignore_ascii_case("memory"))
476 })
477}
478
479fn harness_project_dirs() -> Vec<PathBuf> {
482 let mut configs = Vec::new();
483 if let Some(home) = dirs::home_dir() {
484 configs.push(home.join(".claude"));
485 configs.push(home.join(".codebuddy"));
486 }
487 if let Some(dir) = std::env::var_os("CLAUDE_CONFIG_DIR").filter(|v| !v.is_empty()) {
488 configs.push(PathBuf::from(dir));
489 }
490 let mut out = Vec::new();
491 for config in configs.into_iter().filter(|c| c.is_absolute()) {
492 let projects = config.join("projects");
493 let canonical = canonicalize_secure(&projects);
494 if canonical != projects {
495 out.push(canonical);
496 }
497 out.push(projects);
498 }
499 out
500}
501
502fn path_allowed_by_jail(base: &Path, root: &Path, allow: &[PathBuf]) -> bool {
503 if is_harness_auto_memory_path(base) {
504 return true;
505 }
506 let allowed = is_under_prefix(base, root)
507 || allow.iter().any(|p| is_under_prefix(base, p))
508 || super::pathjail_scope::home_scope_admits(base);
509 #[cfg(windows)]
510 let allowed = allowed || is_under_prefix_windows(base, root);
511 allowed && super::pathjail_scope::protected_zone_permits(base, root, allow)
512}
513
514pub fn canonicalize_or_self(path: &Path) -> PathBuf {
518 super::pathutil::safe_canonicalize_bounded(path, 2000)
519}
520
521pub(crate) fn canonicalize_secure(path: &Path) -> PathBuf {
526 super::pathutil::canonicalize_secure_bounded(path, 2000)
527}
528
529fn canonicalize_existing_ancestor(path: &Path) -> Option<(PathBuf, Vec<std::ffi::OsString>)> {
530 let mut cur = path.to_path_buf();
531 let mut remainder: Vec<std::ffi::OsString> = Vec::new();
532 loop {
533 if cur.exists() {
534 return Some((canonicalize_secure(&cur), remainder));
535 }
536 let name = cur.file_name()?.to_os_string();
537 remainder.push(name);
538 if !cur.pop() {
539 return None;
540 }
541 }
542}
543
544pub fn jail_path(candidate: &Path, jail_root: &Path) -> Result<PathBuf, PathJailError> {
545 jail_path_with_roots(candidate, jail_root, &[])
546}
547
548fn jail_in_workspace(
556 candidate: &Path,
557 jail_root: &Path,
558 snapshot: &crate::core::workspace_authority::Snapshot,
559) -> Result<PathBuf, PathJailError> {
560 let canonical = |path: &Path| crate::core::pathutil::canonicalize_secure(path).ok();
561 let base_root = canonical(jail_root)
562 .filter(|root| snapshot.admits(root))
563 .unwrap_or_else(|| snapshot.primary.clone());
564 let candidate = if candidate.is_absolute() {
565 candidate.to_path_buf()
566 } else {
567 base_root.join(candidate)
568 };
569 let admitted = |path: &Path| snapshot.admits(path);
570 let outside = |path: &Path| PathJailError::OutsideWorkspace {
571 path: path.to_path_buf(),
572 workspace: snapshot.id.clone(),
573 revision: snapshot.revision,
574 roots: snapshot
575 .granting_roots()
576 .map(|(root, access)| format!("{} ({})", root.display(), access.as_str()))
577 .collect::<Vec<_>>()
578 .join(", "),
579 };
580
581 let mut existing = candidate.clone();
582 let mut remainder: Vec<std::ffi::OsString> = Vec::new();
583 while !existing.exists() {
584 let Some(name) = existing.file_name() else {
585 return Err(PathJailError::NoExistingAncestor { path: candidate });
586 };
587 remainder.push(name.to_os_string());
588 if !existing.pop() {
589 return Err(PathJailError::NoExistingAncestor { path: candidate });
590 }
591 }
592 if remainder
593 .iter()
594 .any(|part| part == std::ffi::OsStr::new("..") || part == std::ffi::OsStr::new("."))
595 {
596 return Err(outside(&candidate));
597 }
598 let base = canonical(&existing).ok_or_else(|| outside(&candidate))?;
601 if !admitted(&base) {
602 return Err(outside(&candidate));
603 }
604
605 #[cfg(windows)]
606 reject_symlink_on_windows(&candidate)?;
607
608 let mut out = base;
609 for part in remainder.iter().rev() {
610 out.push(part);
611 }
612 if out.exists() {
613 let resolved = canonical(&out).ok_or_else(|| outside(&candidate))?;
614 if !admitted(&resolved) {
615 return Err(PathJailError::PostCanonicalizeEscape {
616 path: candidate,
617 resolved,
618 });
619 }
620 }
621 crate::core::protected_store::enforce_protected_store_path(&out)
622 .map_err(|reason| PathJailError::ProtectedContext { reason })?;
623 Ok(out)
624}
625
626const LANGUAGE_CACHE_PATTERNS: &[(&str, &str, &str)] = &[
631 ("/go/pkg/mod/", "Go module cache", "~/go/pkg/mod"),
632 (
633 "/.cargo/registry/",
634 "Rust crate registry",
635 "~/.cargo/registry",
636 ),
637 (
638 "/site-packages/",
639 "Python site-packages",
640 "<venv>/lib/pythonX.Y/site-packages",
641 ),
642 ("/node_modules/", "Node modules", "<project>/node_modules"),
643 (
644 "/.m2/repository/",
645 "Maven local repository",
646 "~/.m2/repository",
647 ),
648 ("/.gradle/caches/", "Gradle cache", "~/.gradle/caches"),
649 (
650 "/.nuget/packages/",
651 "NuGet package cache",
652 "~/.nuget/packages",
653 ),
654 (
658 "/.rustup/toolchains/",
659 "Rust toolchain source",
660 "~/.rustup/toolchains",
661 ),
662 (
663 "/.cargo/git/checkouts/",
664 "Cargo git dependencies",
665 "~/.cargo/git/checkouts",
666 ),
667 (
668 "/.bun/install/cache/",
669 "Bun package cache",
670 "~/.bun/install/cache",
671 ),
672 (
673 "/.pub-cache/hosted/",
674 "Dart pub cache",
675 "~/.pub-cache/hosted",
676 ),
677 ("/.gem/ruby/", "Ruby gems", "~/.gem/ruby"),
678 (
681 "/.pyenv/versions/",
682 "pyenv Python installations",
683 "~/.pyenv/versions",
684 ),
685];
686
687const AGENT_INSTRUCTION_ROOTS: &[(&str, &str)] = &[
703 (".claude/skills", "Claude Code skills"),
704 (".claude/commands", "Claude Code commands"),
705 (".claude/agents", "Claude Code agents"),
706 (".claude/plans", "Claude Code plans"),
707 (".claude/rules", "Claude Code rules"),
708 (".claude/plugins/marketplaces", "Claude Code plugins"),
709 (".claude/plugins/cache", "Claude Code plugins"),
710 (".claude/CLAUDE.md", "Claude Code instructions"),
711 (".claude/settings.json", "Claude Code settings"),
712 (".claude/settings.local.json", "Claude Code settings"),
713 (".claude/keybindings.json", "Claude Code settings"),
714 (".codex/skills", "Codex skills"),
715 (".codex/prompts", "Codex prompts"),
716 (".codex/AGENTS.md", "Codex instructions"),
717 (".codex/config.toml", "Codex config"),
718 (".codex/hooks.json", "Codex config"),
719 (".agents/skills", "agent skills"),
720 (".cursor/rules", "Cursor rules"),
721 (".cursor/skills", "Cursor skills"),
722 (".cursor/commands", "Cursor commands"),
723 (".cursor/mcp.json", "Cursor config"),
724 (".cursor/hooks.json", "Cursor config"),
725 (".gemini/GEMINI.md", "Gemini instructions"),
726 (".gemini/commands", "Gemini commands"),
727 (".gemini/settings.json", "Gemini config"),
728 (".codebuddy/settings.json", "CodeBuddy settings"),
729 (".config/opencode/agent", "OpenCode agents"),
730 (".config/opencode/command", "OpenCode commands"),
731 (".config/opencode/AGENTS.md", "OpenCode instructions"),
732 (".config/opencode/opencode.json", "OpenCode config"),
733 (".config/opencode/opencode.jsonc", "OpenCode config"),
734 (".codeium/windsurf/mcp_config.json", "Windsurf config"),
735];
736
737const CURSOR_AGENT_OUTPUT_DIRS: &[&str] = &["agent-tools", "terminals"];
746const CURSOR_AGENT_OUTPUT_LABEL: &str = "Cursor agent output";
747
748fn cursor_workspace_slug(root: &Path) -> String {
752 let slug: String = root
753 .to_string_lossy()
754 .chars()
755 .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
756 .collect();
757 slug.trim_start_matches('-').to_string()
758}
759
760fn is_cursor_agent_output_root(path: &Path) -> bool {
764 let mut back = path.components().rev().map(std::path::Component::as_os_str);
765 let (Some(dir), Some(_workspace), Some(projects), Some(cursor)) =
766 (back.next(), back.next(), back.next(), back.next())
767 else {
768 return false;
769 };
770 cursor == ".cursor"
771 && projects == "projects"
772 && CURSOR_AGENT_OUTPUT_DIRS.iter().any(|d| dir == *d)
773}
774
775fn cursor_workspace_matches(
781 admitted_root: &Path,
782 jail_root: &Path,
783 extra_roots: &[String],
784) -> bool {
785 let Some(workspace) = admitted_root.parent().and_then(Path::file_name) else {
786 return false;
787 };
788 std::iter::once(jail_root.to_path_buf())
789 .chain(extra_roots.iter().map(PathBuf::from))
790 .flat_map(|root| [canonicalize_secure(&root), root])
791 .any(|root| workspace == cursor_workspace_slug(&root).as_str())
792}
793
794fn cursor_agent_output_root(rel: &Path) -> Option<PathBuf> {
797 let mut parts = rel.components().map(std::path::Component::as_os_str);
798 if parts.next()? != ".cursor" || parts.next()? != "projects" {
799 return None;
800 }
801 let workspace = parts.next()?;
802 let dir = parts.next()?;
803 CURSOR_AGENT_OUTPUT_DIRS
804 .iter()
805 .any(|d| dir == *d)
806 .then(|| Path::new(".cursor/projects").join(workspace).join(dir))
807}
808
809fn detect_agent_instruction_root(candidate: &Path) -> Option<(&'static str, PathBuf)> {
814 let home = dirs::home_dir()?;
815 let canon_home = canonicalize_secure(&home);
816 let rel = candidate
817 .strip_prefix(&home)
818 .or_else(|_| candidate.strip_prefix(&canon_home))
819 .ok()?;
820 if rel
822 .components()
823 .any(|c| !matches!(c, std::path::Component::Normal(_)))
824 {
825 return None;
826 }
827 AGENT_INSTRUCTION_ROOTS
828 .iter()
829 .find(|(root, _)| rel.starts_with(root))
830 .map(|&(root, label)| (label, canon_home.join(root)))
831 .or_else(|| detect_host_session_output_root(rel, &canon_home))
832 .or_else(|| {
833 cursor_agent_output_root(rel)
834 .map(|root| canon_home.join(root))
835 .filter(|root| canonicalize_secure(root) == *root)
839 .map(|root| (CURSOR_AGENT_OUTPUT_LABEL, root))
840 })
841}
842
843fn detect_host_session_output_root(
855 rel: &Path,
856 canon_home: &Path,
857) -> Option<(&'static str, PathBuf)> {
858 let parts: Vec<&str> = rel
859 .components()
860 .map(|c| c.as_os_str().to_str())
861 .collect::<Option<_>>()?;
862 let (depth, label) = match parts.as_slice() {
863 [
864 ".claude",
865 "projects",
866 _,
867 _,
868 "tool-results" | "subagents",
869 ..,
870 ] => (5, "Claude Code session output"),
871 _ => return None,
872 };
873 Some((
874 label,
875 canon_home.join(parts[..depth].iter().collect::<PathBuf>()),
876 ))
877}
878
879#[cfg(unix)]
885fn detect_host_scratch_root(candidate: &Path) -> Option<(&'static str, PathBuf)> {
886 use std::os::unix::fs::MetadataExt;
887 let uid = unsafe { libc::geteuid() };
889 let name = format!("claude-{uid}");
890 let (base, rest) = canonicalize_existing_ancestor(candidate)?;
893 let candidate = rest.iter().rev().fold(base, |path, part| path.join(part));
894 [std::env::temp_dir(), PathBuf::from("/tmp")]
895 .into_iter()
896 .map(|tmp| tmp.join(&name))
897 .find_map(|dir| {
898 let meta = std::fs::symlink_metadata(&dir).ok()?;
899 let root = canonicalize_secure(&dir);
900 (meta.is_dir()
901 && meta.uid() == uid
902 && meta.mode() & 0o022 == 0
903 && candidate.starts_with(&root))
904 .then_some(("Claude Code scratchpad", root))
905 })
906}
907
908#[cfg(not(unix))]
909fn detect_host_scratch_root(_candidate: &Path) -> Option<(&'static str, PathBuf)> {
910 None
911}
912
913pub fn register_symlink_target_read_only(candidate: &Path, root: &Path) -> bool {
926 if detect_agent_instruction_root(root)
927 .is_none_or(|(label, _)| label == CURSOR_AGENT_OUTPUT_LABEL)
928 || (!candidate.starts_with(root) && !candidate.starts_with(canonicalize_secure(root)))
929 {
930 return false;
931 }
932 let Ok(target) = std::fs::canonicalize(candidate) else {
933 return false;
934 };
935 let root = canonicalize_secure(root);
936 if target.starts_with(&root) {
937 return false;
938 }
939 if let Some((_, agent_root)) = detect_agent_instruction_root(&target) {
942 return register_session_read_only_root(&agent_root);
943 }
944 let dir = if target.is_dir() {
945 target
946 } else {
947 match target.parent() {
948 Some(parent) => parent.to_path_buf(),
949 None => return false,
950 }
951 };
952 let below_home =
953 dirs::home_dir().is_some_and(|home| dir.starts_with(canonicalize_secure(&home)));
954 if !below_home
955 || crate::core::pathutil::is_broad_or_unsafe_root(&dir)
956 || super::pathjail_scope::in_protected_zone(&dir)
957 {
958 return false;
959 }
960 register_session_read_only_root(&dir)
961}
962
963pub fn jail_path_auto_admitting(
971 candidate: &Path,
972 jail_root: &Path,
973 extra_roots: &[String],
974) -> Result<PathBuf, PathJailError> {
975 let first = jail_path_with_roots(candidate, jail_root, extra_roots);
976 let Err(refused) = first else {
977 return first;
978 };
979 if crate::core::workspace_authority::is_configured() {
982 return Err(refused);
983 }
984 let Some((label, root)) = detect_language_cache_root(candidate) else {
985 return Err(refused);
986 };
987 if label == CURSOR_AGENT_OUTPUT_LABEL
990 && !cursor_workspace_matches(&root, jail_root, extra_roots)
991 {
992 return Err(refused);
993 }
994 if register_session_read_only_root(&root) {
995 tracing::info!(
996 "auto-registered {label} at {} as a read-only root",
997 root.display()
998 );
999 }
1000 let retry = jail_path_with_roots(candidate, jail_root, extra_roots);
1001 if retry.is_err() && register_symlink_target_read_only(candidate, &root) {
1005 return jail_path_with_roots(candidate, jail_root, extra_roots);
1006 }
1007 retry
1008}
1009
1010fn detected_cache_hint(candidate: &std::path::Path) -> Option<String> {
1014 let s = candidate.to_string_lossy();
1015 for &(pattern, name, example) in LANGUAGE_CACHE_PATTERNS {
1016 if s.contains(pattern) {
1017 return Some(format!(
1018 ". Detected {name} — add read_only_roots = [\"{example}\"] to \
1019 ~/.config/lean-ctx/config.toml for cached, compressed reads without write access"
1020 ));
1021 }
1022 }
1023 None
1024}
1025
1026pub fn detect_language_cache_root(candidate: &Path) -> Option<(&'static str, PathBuf)> {
1031 if let Some(found) = detect_agent_instruction_root(candidate) {
1032 return Some(found);
1033 }
1034 if let Some(found) = detect_host_scratch_root(candidate) {
1035 return Some(found);
1036 }
1037 let s = candidate.to_string_lossy().replace('\\', "/");
1038 for &(marker, label, _) in LANGUAGE_CACHE_PATTERNS {
1039 if let Some(idx) = s.find(marker) {
1040 let end = idx + marker.len() - 1; return Some((label, PathBuf::from(&s[..end])));
1042 }
1043 }
1044 None
1045}
1046
1047pub fn jail_path_with_roots(
1057 candidate: &Path,
1058 jail_root: &Path,
1059 extra_roots: &[String],
1060) -> Result<PathBuf, PathJailError> {
1061 jail_path_checked(candidate, jail_root, extra_roots, true)
1062}
1063
1064pub fn jail_path_enforced(candidate: &Path, jail_root: &Path) -> Result<PathBuf, PathJailError> {
1073 jail_path_checked(candidate, jail_root, &[], false)
1074}
1075
1076fn jail_path_checked(
1077 candidate: &Path,
1078 jail_root: &Path,
1079 extra_roots: &[String],
1080 honor_off_switch: bool,
1081) -> Result<PathBuf, PathJailError> {
1082 if candidate.to_string_lossy().as_bytes().contains(&0) {
1083 return Err(PathJailError::NullByte);
1084 }
1085
1086 let absolute = if candidate.is_absolute() {
1090 candidate.to_path_buf()
1091 } else {
1092 jail_root.join(candidate)
1093 };
1094 crate::core::protected_store::enforce_protected_store_path(&absolute)
1095 .map_err(|reason| PathJailError::ProtectedContext { reason })?;
1096
1097 match crate::core::workspace_authority::current() {
1101 crate::core::workspace_authority::Authority::Legacy => {}
1102 crate::core::workspace_authority::Authority::Unavailable(reason) => {
1103 return Err(PathJailError::WorkspaceUnavailable {
1104 reason: crate::core::workspace_authority::unavailable_reason(&reason),
1105 });
1106 }
1107 crate::core::workspace_authority::Authority::Workspace(snapshot) => {
1108 return jail_in_workspace(candidate, jail_root, &snapshot);
1109 }
1110 }
1111
1112 #[cfg(feature = "no-jail")]
1116 {
1117 if honor_off_switch {
1118 return Ok(canonicalize_or_self(&absolute));
1119 }
1120 }
1121
1122 {
1123 let cfg = crate::core::config::Config::load();
1124 if honor_off_switch && cfg.path_jail == Some(false) {
1125 return Ok(canonicalize_or_self(&absolute));
1126 }
1127
1128 let root = canonicalize_secure(jail_root);
1129
1130 let resolved: PathBuf;
1135 let candidate: &Path = if candidate.is_absolute() {
1136 candidate
1137 } else {
1138 resolved = root.join(candidate);
1139 resolved.as_path()
1140 };
1141
1142 let mut allow = allow_paths_from_env_and_config();
1143 allow.extend(
1145 extra_roots
1146 .iter()
1147 .filter(|r| !r.is_empty())
1148 .map(|r| canonicalize_secure(Path::new(r))),
1149 );
1150
1151 if let Ok(state) = crate::core::paths::state_dir() {
1155 allow.push(canonicalize_secure(&state));
1156 }
1157 allow.extend(
1162 read_only_roots_from_env_and_config()
1163 .into_iter()
1164 .map(|p| canonicalize_secure(&p))
1165 .filter(|p| {
1166 !is_cursor_agent_output_root(p)
1167 || cursor_workspace_matches(p, jail_root, extra_roots)
1168 }),
1169 );
1170
1171 let (base, remainder) = canonicalize_existing_ancestor(candidate).ok_or_else(|| {
1172 PathJailError::NoExistingAncestor {
1173 path: candidate.to_path_buf(),
1174 }
1175 })?;
1176
1177 let allowed = path_allowed_by_jail(&base, &root, &allow);
1178
1179 if !allowed {
1180 let is_suspicious = crate::core::pathutil::is_suspicious_root(&root);
1181 let mut hint = if is_suspicious || root == std::path::Path::new("/") {
1182 format!(
1183 ". {}. lean-ctx has not bound this session to a project yet (the host \
1184 reported no project directory). Relative paths cannot bind it: one \
1185 absolute path inside the project, e.g. /home/me/code/my-app/README.md, \
1186 binds it and it stays the session project; if it persists, the user \
1187 runs: lean-ctx doctor --fix",
1188 super::pathjail_scope::AGENT_BIND_ACTION
1189 )
1190 } else {
1191 super::pathjail_scope::escape_hint(candidate, &base, &root)
1192 };
1193 if let Some(notice) = crate::core::workspace_trust::untrusted_override_notice() {
1197 hint.push_str(". ");
1198 hint.push_str(¬ice);
1199 }
1200 if let Some(missing) = crate::core::config::Config::missing_config_path() {
1204 hint.push_str(&format!(
1205 ". ⚠ lean-ctx reads no config file at {} (running on defaults) — an \
1206 allow_paths edit in a config.toml elsewhere is not read; \
1207 `lean-ctx doctor` shows the path in effect",
1208 missing.display()
1209 ));
1210 }
1211 if let Some(cache_hint) = detected_cache_hint(candidate) {
1212 hint.push_str(&cache_hint);
1213 }
1214 return Err(PathJailError::EscapesRoot {
1215 path: candidate.to_path_buf(),
1216 root,
1217 hint,
1218 });
1219 }
1220
1221 #[cfg(windows)]
1222 reject_symlink_on_windows(candidate)?;
1223
1224 let mut out = base;
1225 for part in remainder.iter().rev() {
1226 out.push(part);
1227 }
1228
1229 if out.exists() {
1232 let final_canon = canonicalize_secure(&out);
1233 let final_ok = path_allowed_by_jail(&final_canon, &root, &allow);
1234 if !final_ok {
1235 return Err(PathJailError::PostCanonicalizeEscape {
1236 path: candidate.to_path_buf(),
1237 resolved: final_canon,
1238 });
1239 }
1240 }
1241
1242 crate::core::protected_store::enforce_protected_store_path(&out)
1243 .map_err(|reason| PathJailError::ProtectedContext { reason })?;
1244 Ok(out)
1245 }
1246}
1247
1248#[cfg(all(test, target_os = "macos"))]
1249mod protected_store_tests {
1250 use super::*;
1251
1252 #[test]
1253 fn runtime_store_is_not_reopened_by_implicit_or_explicit_roots() {
1254 let isolated = crate::core::data_dir::isolated_data_dir();
1255 let project = tempfile::tempdir().unwrap();
1256 let store = isolated.path().join("knowledge");
1257 std::fs::create_dir_all(&store).unwrap();
1258 let fact = store.join("facts.json");
1259 std::fs::write(&fact, "private stored context").unwrap();
1260 let code = project.path().join("main.rs");
1261 std::fs::write(&code, "fn main() {}\n").unwrap();
1262 assert!(
1263 jail_path(&fact, project.path()).is_ok(),
1264 "Community keeps its existing runtime access"
1265 );
1266 let _protected =
1267 crate::core::protected_store::pin_synthetic_session(isolated.path()).unwrap();
1268 let roots = vec![isolated.path().to_string_lossy().into_owned()];
1269 for candidate in [&fact, &store, &isolated.path().to_path_buf()] {
1270 assert!(
1271 matches!(
1272 jail_path_with_roots(candidate, project.path(), &roots),
1273 Err(PathJailError::ProtectedContext { .. })
1274 ),
1275 "{candidate:?}"
1276 );
1277 }
1278 assert!(jail_path(&code, project.path()).is_ok());
1279 assert!(jail_path_with_roots(Path::new("facts.json"), &store, &roots).is_err());
1280 for target in [&fact, &store.join("new/backup.json")] {
1284 assert!(enforce_writable(target).is_err(), "{target:?}");
1285 }
1286 assert_eq!(
1287 std::fs::read_to_string(&fact).unwrap(),
1288 "private stored context"
1289 );
1290 assert!(!store.join("new").exists());
1291 enforce_writable(&code).unwrap();
1292 std::fs::write(&fact, "retained internal update").unwrap();
1294 assert_eq!(
1295 std::fs::read_to_string(&fact).unwrap(),
1296 "retained internal update"
1297 );
1298 }
1299
1300 #[test]
1301 fn missing_child_profile_never_falls_back_to_the_normal_jail() {
1302 let isolated = crate::core::data_dir::isolated_data_dir();
1303 let project = tempfile::tempdir().unwrap();
1304 let code = project.path().join("main.rs");
1305 std::fs::write(&code, "fn main() {}\n").unwrap();
1306 let _protected =
1307 crate::core::protected_store::pin_synthetic_session(isolated.path()).unwrap();
1308 crate::test_env::remove_var(crate::core::protected_store::CHILD_PROFILE_ENV);
1309 assert!(matches!(
1310 jail_path(&code, project.path()),
1311 Err(PathJailError::ProtectedContext { .. })
1312 ));
1313 }
1314}
1315
1316#[cfg(windows)]
1317fn is_under_prefix_windows(path: &Path, prefix: &Path) -> bool {
1318 let path_str = normalize_windows_path(&path.to_string_lossy());
1319 let prefix_str = normalize_windows_path(&prefix.to_string_lossy());
1320 let prefix_str = prefix_str.trim_end_matches('\\');
1321 path_str == prefix_str
1323 || path_str
1324 .strip_prefix(prefix_str)
1325 .is_some_and(|rest| rest.starts_with('\\'))
1326}
1327
1328#[cfg(windows)]
1329fn normalize_windows_path(s: &str) -> String {
1330 let stripped = super::pathutil::strip_verbatim_str(s).unwrap_or_else(|| s.to_string());
1331 stripped.to_lowercase().replace('/', "\\")
1332}
1333
1334#[cfg(windows)]
1335fn reject_symlink_on_windows(path: &Path) -> Result<(), PathJailError> {
1336 if let Ok(meta) = std::fs::symlink_metadata(path) {
1337 if super::pathutil::is_symlink_or_reparse(&meta) {
1340 return Err(PathJailError::Symlink {
1341 path: path.to_path_buf(),
1342 });
1343 }
1344 }
1345 Ok(())
1346}
1347
1348#[path = "pathjail_ide_dirs.rs"]
1349mod ide_dirs;
1350
1351#[cfg(all(test, windows))]
1352#[path = "pathjail_windows_tests.rs"]
1353mod windows_prefix_tests;
1354
1355#[cfg(test)]
1356#[path = "pathjail_tests.rs"]
1357mod tests;