Skip to main content

lean_ctx/core/
pathjail.rs

1use std::path::{Path, PathBuf};
2
3use crate::core::error::PathJailError;
4
5/// `allow_paths` / `extra_roots` come from `config.toml`, where no shell ever
6/// runs — users writing `"$HOME/code"` or `"~/code"` got a literal,
7/// never-matching prefix and concluded the whole option was broken (GH #392).
8/// Unset variables are left verbatim (and warned about) so the entry fails
9/// loudly in `lean-ctx doctor` instead of silently matching something else.
10/// `HOME` falls back to the platform home directory when the environment
11/// variable is absent, as is common in native Windows shells.
12pub 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    // The allow-list defines the jail boundary, so it must be canonicalized the
60    // same (security, symlink-resolving) way as the candidate it is compared
61    // against — otherwise a guarded (lexical) root vs a resolved candidate would
62    // break `is_under_prefix`. These entries are data_dir / IDE-config dirs /
63    // user-configured paths, virtually never under ~/Documents.
64    //
65    // This is also lean-ctx's own state dir (sessions, knowledge, …) — always
66    // readable even while foreign editor dirs stay jailed. On a legacy install
67    // the resolver returns `~/.lean-ctx`; on a split install it returns the XDG
68    // data dir. Going through the resolver (not a hardcoded `~/.lean-ctx` join)
69    // is what keeps `home_allow_dirs` free of the legacy-path firewall trip.
70    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    // Env entries are expanded too: MCP host configs pass env blocks verbatim
91    // (no shell), so "$HOME/code" arrives literally there as well.
92    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    // Read-only roots are *readable* (the whole point is read access to sibling
109    // repos); writes into them are denied separately by `enforce_writable`
110    // (#475). Add them to the read allow-list so reads resolve, exactly like
111    // `extra_roots`, without granting write access.
112    out.extend(canonicalized_roots(
113        &cfg.read_only_roots,
114        "LEAN_CTX_READ_ONLY_ROOTS",
115    ));
116
117    out
118}
119
120/// Canonicalize a set of config-supplied root entries plus an env override
121/// (path-list separated), expanding `~`/`$VAR` first. Shared by the read
122/// allow-list and the read-only-roots collector so both tiers parse roots
123/// identically.
124fn 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
138/// A read-only root is a sibling subtree the agent may **read** but never
139/// **write** — e.g. a reference repo mounted next to the project. Empty by
140/// default, so [`is_read_only_path`]/[`enforce_writable`] are zero-cost no-ops
141/// for everyone who hasn't opted in (#475).
142pub 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    // #899: session-scoped roots auto-detected from language caches. Consulted
146    // by both the read allow-list (jail) and `is_read_only_path` (write-deny),
147    // so a cache root is readable but never writable — exactly like a configured
148    // read-only root, minus the config-file edit.
149    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
160/// The session-scoped read-only roots auto-registered this process (#899).
161pub 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
168/// Register a session-scoped read-only root (an auto-detected language cache).
169/// Returns `true` when newly added. Idempotent on the canonicalized path.
170///
171/// ponytail: process-global set, not per-session — language caches
172/// (`~/go/pkg/mod`, `~/.cargo/registry`, …) are machine-global read-only dirs,
173/// so sharing read access across sessions grants nothing a session couldn't
174/// already get by reading them; per-session isolation would be plumbing for no
175/// security gain. Upgrade to a session-keyed map only if writable roots ever go
176/// down this path.
177pub 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/// A single active relaxation of the path jail. Each one widens or disables what
191/// tools can reach beyond the project root, so it is surfaced loudly (GH security
192/// audit, finding 3): the MCP/HTTP server inherits its process env from the
193/// IDE/launchd, so a globally-set `LEAN_CTX_ALLOW_PATH` / `LEAN_CTX_EXTRA_ROOTS`
194/// / `LEAN_CTX_ALLOW_IDE_DIRS` (or `path_jail = false`) silently loosens the
195/// boundary with no in-band signal otherwise.
196#[derive(Debug, Clone, Copy, PartialEq, Eq)]
197pub struct JailRelaxation {
198    /// The knob that activated it (env var name, config key, or build feature).
199    pub source: &'static str,
200    /// Human-readable effect of the relaxation.
201    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/// Collect every currently-active path-jail relaxation. An empty result means
209/// the jail is fully in force. This is the single source of truth shared by the
210/// startup warning ([`warn_if_relaxed`]) and `lean-ctx doctor`.
211#[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
262/// Emit a loud `tracing::warn!` for every active path-jail relaxation. Called
263/// once at MCP/HTTP server startup so a trusted-but-loosening env/config leaves
264/// an in-band audit signal instead of silently defeating the jail (finding 3).
265pub 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
275/// True when `candidate` resolves to a location inside a configured read-only
276/// root. The candidate's nearest existing ancestor is canonicalized (so a
277/// not-yet-existing file inherits the read-only status of the directory it
278/// would be created in — closing the "create a new file in a read-only repo"
279/// hole) and matched against the (symlink-resolved) read-only roots.
280///
281/// A `false` return is only authoritative when the roots list is empty or the
282/// path provably sits outside every root; an unresolvable candidate (no
283/// existing ancestor) is treated as *not* read-only here and is rejected later
284/// by the ordinary write/jail error, never silently written.
285pub 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
294/// The canonicalized nearest-existing-ancestor of `candidate` with the
295/// not-yet-existing remainder re-appended. Resolves symlinks so a symlink
296/// *into* a guarded root cannot launder a write past a prefix check.
297fn 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
309/// Default-deny write guard for the read-only tier (#475): returns an error if
310/// `candidate` is inside a configured read-only root, `Ok(())` otherwise.
311///
312/// This is the single read-only-aware choke point. Every filesystem write that
313/// can target a caller-supplied path routes through it (the atomic writers in
314/// `ctx_edit`/`edit_apply`, the handoff/session export bundle writers, the
315/// in-place memory-compaction writer, and the refactor IDE pre-write gate), so
316/// a "read-only" root cannot be written through any tool. Reads are unaffected.
317pub fn enforce_writable(candidate: &Path) -> Result<(), String> {
318    // This boundary covers caller-selected edit/backup/export destinations.
319    // Engine-owned knowledge persistence uses its own authorized store writer.
320    crate::cli::enforce_protected_store_path(candidate)?;
321    if is_read_only_path(candidate) {
322        return Err(format!(
323            "path is inside a read-only root — writes are denied (read_only_roots): {}",
324            candidate.display()
325        ));
326    }
327    match super::pathjail_scope::home_scope_write_denial(&canonical_target(candidate)) {
328        Some(denial) => Err(denial),
329        None => Ok(()),
330    }
331}
332
333/// Foreign editor config dirs for the jail (~/.cursor, ~/.claude, VS Code, …).
334///
335/// These expose other projects' sessions, MCP configs and credentials to any
336/// agent, so they are opt-in only (config `allow_ide_config_dirs = true` or
337/// `LEAN_CTX_ALLOW_IDE_DIRS=1`). lean-ctx's *own* state dir is intentionally NOT
338/// handled here: the caller already adds it via the sanctioned `data_dir`
339/// resolver (the legacy `~/.lean-ctx` is just one resolution of it). Keeping this
340/// a pure foreign-editor list means no legacy `~/.lean-ctx` literal is built in
341/// this module, so the legacy-path firewall (tests/legacy_path_firewall) has
342/// nothing to flag.
343fn home_allow_dirs(home: &Path, ide_dirs_allowed: bool) -> Vec<PathBuf> {
344    let mut out = Vec::new();
345    if ide_dirs_allowed {
346        let targets = crate::core::editor_registry::build_targets(home);
347        collect_ide_allow_dirs(home, &targets, &mut out);
348    }
349    out
350}
351
352/// Collect the in-home config/detect directories of every supported editor.
353///
354/// Derived from the editor registry (the single source of truth) so it covers
355/// non-dotfile layouts too — VS Code's `Library/Application Support/Code/User`,
356/// Cline/Roo globalStorage, JetBrains — and never drifts as editors are added.
357/// A config file that sits directly in `$HOME` (`~/.claude.json`,
358/// `~/.jb-mcp.json`) resolves its parent to `$HOME`; those entries are skipped
359/// so the jail is never widened to the entire home directory.
360fn collect_ide_allow_dirs(
361    home: &Path,
362    targets: &[crate::core::editor_registry::EditorTarget],
363    out: &mut Vec<PathBuf>,
364) {
365    let mut seen: std::collections::HashSet<PathBuf> = out.iter().cloned().collect();
366    for target in targets {
367        let candidates = [
368            target.config_path.parent().map(Path::to_path_buf),
369            Some(target.detect_path.clone()),
370        ];
371        for cand in candidates.into_iter().flatten() {
372            if cand.as_path() == home || !cand.starts_with(home) || !cand.is_dir() {
373                continue;
374            }
375            let resolved = canonicalize_secure(&cand);
376            if seen.insert(resolved.clone()) {
377                out.push(resolved);
378            }
379        }
380    }
381}
382
383fn is_under_prefix(path: &Path, prefix: &Path) -> bool {
384    path.starts_with(prefix)
385}
386
387/// True for Claude Code / CodeBuddy auto-memory files under
388/// `~/.claude/projects/<slug>/memory/` (and the CodeBuddy twin).
389///
390/// Auto memory uses the host's native Read/Edit/Write on these paths
391/// (code.claude.com/docs/en/memory). Replace-mode PathJail must not force
392/// agents to shell out or hit MCP `resources/read` with file URIs (GH #1228).
393/// Scoped to the `memory/` subdirectory only — session transcripts and
394/// credentials under `projects/<slug>/` stay jailed.
395pub fn is_harness_auto_memory_path(path: &Path) -> bool {
396    let lower = path.to_string_lossy().replace('\\', "/").to_lowercase();
397    for marker in ["/.claude/projects/", "/.codebuddy/projects/"] {
398        if let Some(idx) = lower.find(marker) {
399            let after = &lower[idx + marker.len()..];
400            let mut parts = after.split('/');
401            let Some(_slug) = parts.next() else {
402                continue;
403            };
404            if parts.next() == Some("memory") {
405                return true;
406            }
407        }
408    }
409    false
410}
411
412fn path_allowed_by_jail(base: &Path, root: &Path, allow: &[PathBuf]) -> bool {
413    if is_harness_auto_memory_path(base) {
414        return true;
415    }
416    let allowed = is_under_prefix(base, root)
417        || allow.iter().any(|p| is_under_prefix(base, p))
418        || super::pathjail_scope::home_scope_admits(base);
419    #[cfg(windows)]
420    let allowed = allowed || is_under_prefix_windows(base, root);
421    allowed && super::pathjail_scope::protected_zone_permits(base, root, allow)
422}
423
424/// Heuristic canonicalize — honours the #356 TCC guard. Used by the
425/// jail-disabled bypass and by external callers (session/startup/server roots)
426/// that must not pop a privacy prompt on their own initiative.
427pub fn canonicalize_or_self(path: &Path) -> PathBuf {
428    super::pathutil::safe_canonicalize_bounded(path, 2000)
429}
430
431/// SECURITY canonicalize for the jail boundary itself (roots + candidate +
432/// escape re-check). Deliberately bypasses the #356 TCC guard: the jail must
433/// keep resolving symlinks to detect escapes, and it only ever runs on a path
434/// the client explicitly asked to access, where a one-time prompt is legitimate.
435pub(crate) fn canonicalize_secure(path: &Path) -> PathBuf {
436    super::pathutil::canonicalize_secure_bounded(path, 2000)
437}
438
439fn canonicalize_existing_ancestor(path: &Path) -> Option<(PathBuf, Vec<std::ffi::OsString>)> {
440    let mut cur = path.to_path_buf();
441    let mut remainder: Vec<std::ffi::OsString> = Vec::new();
442    loop {
443        if cur.exists() {
444            return Some((canonicalize_secure(&cur), remainder));
445        }
446        let name = cur.file_name()?.to_os_string();
447        remainder.push(name);
448        if !cur.pop() {
449            return None;
450        }
451    }
452}
453
454pub fn jail_path(candidate: &Path, jail_root: &Path) -> Result<PathBuf, PathJailError> {
455    jail_path_with_roots(candidate, jail_root, &[])
456}
457
458/// Known language-cache markers (#899): (path substring, human label, config
459/// example). Single source of truth shared by [`detected_cache_hint`] (the
460/// jail-error suggestion) and [`detect_language_cache_root`] (session
461/// auto-registration), so the two never drift.
462const LANGUAGE_CACHE_PATTERNS: &[(&str, &str, &str)] = &[
463    ("/go/pkg/mod/", "Go module cache", "~/go/pkg/mod"),
464    (
465        "/.cargo/registry/",
466        "Rust crate registry",
467        "~/.cargo/registry",
468    ),
469    (
470        "/site-packages/",
471        "Python site-packages",
472        "<venv>/lib/pythonX.Y/site-packages",
473    ),
474    ("/node_modules/", "Node modules", "<project>/node_modules"),
475    (
476        "/.m2/repository/",
477        "Maven local repository",
478        "~/.m2/repository",
479    ),
480    ("/.gradle/caches/", "Gradle cache", "~/.gradle/caches"),
481    (
482        "/.nuget/packages/",
483        "NuGet package cache",
484        "~/.nuget/packages",
485    ),
486];
487
488/// Detect well-known language cache paths and return a targeted hint. Used for
489/// jail callers that don't auto-register (e.g. batch reads); the single-path
490/// ctx_read flow instead auto-registers via [`detect_language_cache_root`].
491fn detected_cache_hint(candidate: &std::path::Path) -> Option<String> {
492    let s = candidate.to_string_lossy();
493    for &(pattern, name, example) in LANGUAGE_CACHE_PATTERNS {
494        if s.contains(pattern) {
495            return Some(format!(
496                ". Detected {name} — add read_only_roots = [\"{example}\"] to \
497                 ~/.config/lean-ctx/config.toml for cached, compressed reads without write access"
498            ));
499        }
500    }
501    None
502}
503
504/// If `candidate` sits inside a known language cache, return `(label, root)`
505/// where `root` is the path truncated at the end of the marker directory (no
506/// trailing slash). resolve_path uses this to auto-register a session read-only
507/// root so the retry resolves without a config edit or a subprocess (#899).
508pub fn detect_language_cache_root(candidate: &Path) -> Option<(&'static str, PathBuf)> {
509    let s = candidate.to_string_lossy().replace('\\', "/");
510    for &(marker, label, _) in LANGUAGE_CACHE_PATTERNS {
511        if let Some(idx) = s.find(marker) {
512            let end = idx + marker.len() - 1; // keep the marker dir, drop trailing '/'
513            return Some((label, PathBuf::from(&s[..end])));
514        }
515    }
516    None
517}
518
519/// Like [`jail_path`], but also accepts paths under any of `extra_roots`.
520///
521/// `extra_roots` are session-scoped trusted roots (MCP `roots/list` and config
522/// `extra_roots`, surfaced via `session.extra_roots`) — e.g. sibling git
523/// worktrees the agent legitimately spans. They widen the allow-list for *this
524/// call only*, so an explicit `path` under a worktree resolves instead of
525/// failing with "path escapes project root", without loosening the global jail
526/// (#403). `path_jail = false` still bypasses entirely and an empty slice is
527/// byte-for-byte identical to the old single-root behaviour.
528pub fn jail_path_with_roots(
529    candidate: &Path,
530    jail_root: &Path,
531    extra_roots: &[String],
532) -> Result<PathBuf, PathJailError> {
533    if candidate.to_string_lossy().as_bytes().contains(&0) {
534        return Err(PathJailError::NullByte);
535    }
536
537    // Runtime context is reached through authorized knowledge/recovery APIs,
538    // never by widening a model-directed file read to the Engine's own store.
539    // Apply this before no-jail/config/implicit runtime allow-list shortcuts.
540    let absolute = if candidate.is_absolute() {
541        candidate.to_path_buf()
542    } else {
543        jail_root.join(candidate)
544    };
545    crate::cli::enforce_protected_store_path(&absolute)
546        .map_err(|reason| PathJailError::ProtectedContext { reason })?;
547
548    #[cfg(feature = "no-jail")]
549    {
550        let _ = (jail_root, extra_roots);
551        return Ok(canonicalize_or_self(candidate));
552    }
553
554    #[allow(unreachable_code)]
555    {
556        let cfg = crate::core::config::Config::load();
557        if cfg.path_jail == Some(false) {
558            return Ok(canonicalize_or_self(candidate));
559        }
560
561        let root = canonicalize_secure(jail_root);
562
563        // Resolve relative candidates against the (absolute) jail root — never the process
564        // CWD. The daemon's CWD is not the project, so CWD-relative resolution made
565        // graph-relative paths (e.g. auto-preload candidates like `rust/src/core/foo.rs`)
566        // spuriously fail with "no existing ancestor". Absolute candidates are unchanged.
567        let resolved: PathBuf;
568        let candidate: &Path = if candidate.is_absolute() {
569            candidate
570        } else {
571            resolved = root.join(candidate);
572            resolved.as_path()
573        };
574
575        let mut allow = allow_paths_from_env_and_config();
576        // Session-scoped roots widen the allow-list for this call only.
577        allow.extend(
578            extra_roots
579                .iter()
580                .filter(|r| !r.is_empty())
581                .map(|r| canonicalize_secure(Path::new(r))),
582        );
583
584        // #820: lean-ctx's own state dir (tee files, artifacts, tool-results)
585        // must be readable even when outside the project root. ctx_shell
586        // tells agents to read tee-file paths, so the jail must allow them.
587        if let Ok(state) = crate::core::paths::state_dir() {
588            allow.push(canonicalize_secure(&state));
589        }
590        // Read-only roots are also allowed for reads (they only block writes
591        // via enforce_writable, not reads via the jail).
592        allow.extend(
593            read_only_roots_from_env_and_config()
594                .into_iter()
595                .map(|p| canonicalize_secure(&p)),
596        );
597
598        let (base, remainder) = canonicalize_existing_ancestor(candidate).ok_or_else(|| {
599            PathJailError::NoExistingAncestor {
600                path: candidate.to_path_buf(),
601            }
602        })?;
603
604        let allowed = path_allowed_by_jail(&base, &root, &allow);
605
606        if !allowed {
607            let is_suspicious = crate::tools::startup::is_suspicious_root(&root);
608            let mut hint = if is_suspicious || root == std::path::Path::new("/") {
609                ". lean-ctx has not bound this session to a project yet (the host reported \
610                     no project directory). Any path inside a project binds it; if it \
611                     persists: lean-ctx doctor --fix"
612                    .to_string()
613            } else {
614                super::pathjail_scope::escape_hint(candidate, &base, &root)
615            };
616            // An untrusted workspace's project-local `allow_paths` is silently
617            // withheld; always surface that reason (the stderr warning is
618            // invisible over MCP, and the hint above is meta-gated off) (#540).
619            if let Some(notice) = crate::core::workspace_trust::untrusted_override_notice() {
620                hint.push_str(". ");
621                hint.push_str(&notice);
622            }
623            // The global config the runtime reads doesn't exist → on defaults, so
624            // an `allow_paths` edit made to a config.toml elsewhere (XDG vs legacy
625            // dir, or a sandboxed/container HOME) is never seen (#540).
626            if let Some(missing) = crate::core::config::Config::missing_config_path() {
627                hint.push_str(&format!(
628                    ". ⚠ lean-ctx reads no config file at {} (running on defaults) — an \
629                     allow_paths edit in a config.toml elsewhere is not read; \
630                     `lean-ctx doctor` shows the path in effect",
631                    missing.display()
632                ));
633            }
634            if let Some(cache_hint) = detected_cache_hint(candidate) {
635                hint.push_str(&cache_hint);
636            }
637            return Err(PathJailError::EscapesRoot {
638                path: candidate.to_path_buf(),
639                root,
640                hint,
641            });
642        }
643
644        #[cfg(windows)]
645        reject_symlink_on_windows(candidate)?;
646
647        let mut out = base;
648        for part in remainder.iter().rev() {
649            out.push(part);
650        }
651
652        // Re-validate after reconstruction: if the final path exists, canonicalize
653        // and re-check to close TOCTOU window (symlink created between check and use).
654        if out.exists() {
655            let final_canon = canonicalize_secure(&out);
656            let final_ok = path_allowed_by_jail(&final_canon, &root, &allow);
657            if !final_ok {
658                return Err(PathJailError::PostCanonicalizeEscape {
659                    path: candidate.to_path_buf(),
660                    resolved: final_canon,
661                });
662            }
663        }
664
665        crate::cli::enforce_protected_store_path(&out)
666            .map_err(|reason| PathJailError::ProtectedContext { reason })?;
667        Ok(out)
668    }
669}
670
671#[cfg(all(test, target_os = "macos"))]
672mod protected_store_tests {
673    use super::*;
674
675    #[test]
676    fn runtime_store_is_not_reopened_by_implicit_or_explicit_roots() {
677        let isolated = crate::core::data_dir::isolated_data_dir();
678        let project = tempfile::tempdir().unwrap();
679        let store = isolated.path().join("knowledge");
680        std::fs::create_dir_all(&store).unwrap();
681        let fact = store.join("facts.json");
682        std::fs::write(&fact, "private stored context").unwrap();
683        let code = project.path().join("main.rs");
684        std::fs::write(&code, "fn main() {}\n").unwrap();
685        assert!(
686            jail_path(&fact, project.path()).is_ok(),
687            "Community keeps its existing runtime access"
688        );
689        let _protected = crate::cli::pin_synthetic_session(isolated.path()).unwrap();
690        let roots = vec![isolated.path().to_string_lossy().into_owned()];
691        for candidate in [&fact, &store, &isolated.path().to_path_buf()] {
692            assert!(
693                matches!(
694                    jail_path_with_roots(candidate, project.path(), &roots),
695                    Err(PathJailError::ProtectedContext { .. })
696                ),
697                "{candidate:?}"
698            );
699        }
700        assert!(jail_path(&code, project.path()).is_ok());
701        assert!(jail_path_with_roots(Path::new("facts.json"), &store, &roots).is_err());
702        // Raw backup paths enter the shared atomic writer without the dispatch
703        // resolver; they must not overwrite a hidden record or create a sibling.
704        for target in [&fact, &store.join("new/backup.json")] {
705            assert!(
706                crate::tools::edit_io::write_atomic_bytes_with_permissions(
707                    target,
708                    b"forged local context",
709                    None,
710                )
711                .is_err()
712            );
713        }
714        assert_eq!(
715            std::fs::read_to_string(&fact).unwrap(),
716            "private stored context"
717        );
718        assert!(!store.join("new").exists());
719        crate::tools::edit_io::write_atomic_bytes_with_permissions(&code, b"fn main() {}\n", None)
720            .unwrap();
721        // Internal storage is unaffected by the model-directed path resolver.
722        std::fs::write(&fact, "retained internal update").unwrap();
723        assert_eq!(
724            std::fs::read_to_string(&fact).unwrap(),
725            "retained internal update"
726        );
727    }
728
729    #[test]
730    fn missing_child_profile_never_falls_back_to_the_normal_jail() {
731        let isolated = crate::core::data_dir::isolated_data_dir();
732        let project = tempfile::tempdir().unwrap();
733        let code = project.path().join("main.rs");
734        std::fs::write(&code, "fn main() {}\n").unwrap();
735        let _protected = crate::cli::pin_synthetic_session(isolated.path()).unwrap();
736        crate::test_env::remove_var(crate::cli::CHILD_PROFILE_ENV);
737        assert!(matches!(
738            jail_path(&code, project.path()),
739            Err(PathJailError::ProtectedContext { .. })
740        ));
741    }
742}
743
744#[cfg(windows)]
745fn is_under_prefix_windows(path: &Path, prefix: &Path) -> bool {
746    let path_str = normalize_windows_path(&path.to_string_lossy());
747    let prefix_str = normalize_windows_path(&prefix.to_string_lossy());
748    let prefix_str = prefix_str.trim_end_matches('\\');
749    // Component boundary: `c:\proj` must not admit `c:\proj-evil\x`.
750    path_str == prefix_str
751        || path_str
752            .strip_prefix(prefix_str)
753            .is_some_and(|rest| rest.starts_with('\\'))
754}
755
756#[cfg(windows)]
757fn normalize_windows_path(s: &str) -> String {
758    let stripped = super::pathutil::strip_verbatim_str(s).unwrap_or_else(|| s.to_string());
759    stripped.to_lowercase().replace('/', "\\")
760}
761
762#[cfg(windows)]
763fn reject_symlink_on_windows(path: &Path) -> Result<(), PathJailError> {
764    if let Ok(meta) = std::fs::symlink_metadata(path) {
765        // Junctions and other reparse points redirect like symlinks but are
766        // invisible to `is_symlink()` — reject them too (GL#442).
767        if super::pathutil::is_symlink_or_reparse(&meta) {
768            return Err(PathJailError::Symlink {
769                path: path.to_path_buf(),
770            });
771        }
772    }
773    Ok(())
774}
775
776#[cfg(all(test, windows))]
777#[path = "pathjail_windows_tests.rs"]
778mod windows_prefix_tests;
779
780#[cfg(test)]
781mod tests {
782    use super::*;
783
784    #[cfg(not(feature = "no-jail"))]
785    #[test]
786    fn rejects_path_outside_root() {
787        // Hermetic config (empty data dir => jail on) so a parallel test that
788        // flips `path_jail` cannot leak into this enforcement check. The guard
789        // holds the global test_env_lock, which also serializes against every
790        // `LEAN_CTX_ALLOW_PATH` mutation (all of them go through that lock).
791        let _iso = crate::core::data_dir::isolated_data_dir();
792        let tmp = tempfile::tempdir().unwrap();
793        let root = tmp.path().join("root");
794        let other = tmp.path().join("other");
795        std::fs::create_dir_all(&root).unwrap();
796        std::fs::create_dir_all(&other).unwrap();
797        std::fs::write(root.join("a.txt"), "ok").unwrap();
798        std::fs::write(other.join("b.txt"), "no").unwrap();
799
800        let ok = jail_path(&root.join("a.txt"), &root);
801        assert!(ok.is_ok());
802
803        let bad = jail_path(&other.join("b.txt"), &root);
804        assert!(bad.is_err());
805    }
806
807    /// #475: a configured read-only root is readable but never writable. Reads
808    /// resolve (the root joins the allow-list like an extra_root), while the
809    /// single write choke point `enforce_writable` default-denies every write
810    /// inside it — including a not-yet-existing file, which inherits the
811    /// directory's read-only status. `isolated_data_dir` holds `test_env_lock`,
812    /// serialising the `LEAN_CTX_READ_ONLY_ROOTS` mutation against other tests.
813    #[cfg(not(feature = "no-jail"))]
814    #[test]
815    fn read_only_roots_deny_writes_but_allow_reads() {
816        // `isolated_data_dir` already holds `test_env_lock` for its lifetime —
817        // taking it again here would self-deadlock on a non-reentrant Mutex.
818        let _iso = crate::core::data_dir::isolated_data_dir();
819
820        let tmp = tempfile::tempdir().unwrap();
821        let project = tmp.path().join("project");
822        let refrepo = tmp.path().join("refrepo");
823        std::fs::create_dir_all(&project).unwrap();
824        std::fs::create_dir_all(refrepo.join("sub")).unwrap();
825        std::fs::write(refrepo.join("lib.rs"), "pub fn x() {}\n").unwrap();
826
827        // Canonicalize the configured root the same (symlink-resolving) way the
828        // guard does, so macOS /var → /private/var can't defeat the prefix match.
829        let ro_canon = canonicalize_secure(&refrepo);
830        crate::test_env::set_var(
831            "LEAN_CTX_READ_ONLY_ROOTS",
832            ro_canon.to_string_lossy().as_ref(),
833        );
834
835        let existing = refrepo.join("lib.rs");
836        let new_file = refrepo.join("sub").join("new.rs");
837        let proj_file = project.join("main.rs");
838
839        // Capture every decision while the env is live (it is cleared below).
840        let read_existing = jail_path(&existing, &project);
841        let deny_existing = enforce_writable(&existing);
842        let deny_new = enforce_writable(&new_file);
843        let allow_project = enforce_writable(&proj_file);
844        let ro_existing = is_read_only_path(&existing);
845        let ro_project = is_read_only_path(&proj_file);
846
847        crate::test_env::remove_var("LEAN_CTX_READ_ONLY_ROOTS");
848
849        assert!(
850            deny_existing.is_err(),
851            "write to an existing file in a read-only root must be denied"
852        );
853        assert!(
854            deny_new.is_err(),
855            "creating a new file in a read-only root must be denied"
856        );
857        assert!(
858            allow_project.is_ok(),
859            "writes into the project root must stay allowed: {allow_project:?}"
860        );
861        assert!(
862            read_existing.is_ok(),
863            "reads inside a read-only root must resolve (read allow-list): {read_existing:?}"
864        );
865        assert!(ro_existing, "the file is inside the read-only root");
866        assert!(!ro_project, "the project file is not read-only");
867    }
868
869    /// #406 regression: a long-lived process (the MCP server) must honor
870    /// `path_jail = false` written to config after startup. The config cache is
871    /// now keyed on content, so even an edit that preserves the file mtime takes
872    /// effect — a path outside the jail root is accepted once the flag flips.
873    /// (With the former mtime-only cache the stale `None` kept the jail on.)
874    #[cfg(not(feature = "no-jail"))]
875    #[test]
876    fn honors_path_jail_false_after_mtime_preserving_edit() {
877        let _iso = crate::core::data_dir::isolated_data_dir();
878        let cfg_path = crate::core::config::Config::path().unwrap();
879        if let Some(parent) = cfg_path.parent() {
880            std::fs::create_dir_all(parent).unwrap();
881        }
882
883        let tmp = tempfile::tempdir().unwrap();
884        let root = tmp.path().join("project");
885        let outside = tmp.path().join("outside");
886        std::fs::create_dir_all(&root).unwrap();
887        std::fs::create_dir_all(&outside).unwrap();
888        let secret = outside.join("secret.txt");
889        std::fs::write(&secret, "x").unwrap();
890
891        // Warm the config cache with the jail on (no path_jail key).
892        std::fs::write(&cfg_path, "# jail on\n").unwrap();
893        let mtime0 = std::fs::metadata(&cfg_path).unwrap().modified().unwrap();
894        assert_eq!(crate::core::config::Config::load().path_jail, None);
895
896        // Flip path_jail=false but restore the original mtime, so any mtime-only
897        // cache would keep serving the stale jail-on value.
898        std::fs::write(&cfg_path, "path_jail = false\n").unwrap();
899        filetime::set_file_mtime(&cfg_path, filetime::FileTime::from_system_time(mtime0)).unwrap();
900
901        assert!(
902            jail_path(&secret, &root).is_ok(),
903            "path_jail=false must take effect without a fresh process (#406)"
904        );
905    }
906
907    #[test]
908    fn allows_nonexistent_child_under_root() {
909        // jail_path reads the protected-session env, which the macOS
910        // write_guard tests set process-wide under this lock.
911        let _env = crate::core::data_dir::test_env_lock();
912        let tmp = tempfile::tempdir().unwrap();
913        let root = tmp.path().join("root");
914        std::fs::create_dir_all(&root).unwrap();
915        std::fs::write(root.join("a.txt"), "ok").unwrap();
916
917        let p = root.join("new").join("file.txt");
918        let ok = jail_path(&p, &root).unwrap();
919        assert!(ok.to_string_lossy().contains("file.txt"));
920    }
921
922    #[cfg(not(feature = "no-jail"))]
923    #[test]
924    fn relative_candidate_resolves_against_root_not_cwd() {
925        // Regression: in the daemon (CWD != project) a relative graph path like
926        // `sub/file.rs` must resolve under the jail root, not the process CWD.
927        let _iso = crate::core::data_dir::isolated_data_dir();
928        let tmp = tempfile::tempdir().unwrap();
929        let root = tmp.path().join("project");
930        std::fs::create_dir_all(root.join("sub")).unwrap();
931        std::fs::write(root.join("sub").join("file.rs"), "ok").unwrap();
932
933        let jailed = jail_path(Path::new("sub/file.rs"), &root)
934            .expect("relative candidate should resolve under the jail root");
935        assert!(jailed.ends_with("sub/file.rs"));
936        assert!(
937            is_under_prefix(&canonicalize_or_self(&jailed), &canonicalize_or_self(&root)),
938            "resolved path must live under the jail root: {jailed:?}"
939        );
940    }
941
942    #[test]
943    fn ide_allow_dirs_are_registry_derived_and_skip_home() {
944        use crate::core::editor_registry::{ConfigType, EditorTarget};
945
946        let home = tempfile::tempdir().unwrap();
947        let h = home.path();
948        // VS Code keeps its config outside a dotfile dir — the old hard-coded
949        // list missed this entirely.
950        std::fs::create_dir_all(h.join("Library/Application Support/Code/User")).unwrap();
951        std::fs::create_dir_all(h.join(".cursor")).unwrap();
952
953        let targets = vec![
954            EditorTarget {
955                name: "VS Code",
956                agent_key: "vscode".into(),
957                config_path: h.join("Library/Application Support/Code/User/mcp.json"),
958                detect_path: h.join("Library/Application Support/Code"),
959                config_type: ConfigType::VsCodeMcp,
960            },
961            EditorTarget {
962                name: "Cursor",
963                agent_key: "cursor".into(),
964                config_path: h.join(".cursor/mcp.json"),
965                detect_path: h.join(".cursor"),
966                config_type: ConfigType::McpJson,
967            },
968            // A $HOME-level config file: its parent is $HOME and must be skipped.
969            EditorTarget {
970                name: "Claude Code",
971                agent_key: "claude".into(),
972                config_path: h.join(".claude.json"),
973                detect_path: h.join(".no-such-dir"),
974                config_type: ConfigType::McpJson,
975            },
976        ];
977
978        let mut out = Vec::new();
979        collect_ide_allow_dirs(h, &targets, &mut out);
980
981        assert!(
982            out.iter().any(|p| p.ends_with("Code/User")),
983            "non-dotfile VS Code dir must be covered: {out:?}"
984        );
985        assert!(out.iter().any(|p| p.ends_with(".cursor")), "{out:?}");
986        let home_canon = canonicalize_secure(h);
987        assert!(
988            !out.contains(&home_canon),
989            "must never widen the jail to $HOME: {out:?}"
990        );
991    }
992
993    // P0-10 (#422): foreign editor config dirs are opt-in. lean-ctx's own state
994    // dir is added by the caller via the data_dir root, NOT by `home_allow_dirs`,
995    // so the default home allow-list is empty and `~/.lean-ctx` (not an editor)
996    // never appears here.
997    #[test]
998    fn ide_config_dirs_are_excluded_by_default() {
999        let home = tempfile::tempdir().unwrap();
1000        for d in [".lean-ctx", ".cursor", ".codex"] {
1001            std::fs::create_dir_all(home.path().join(d)).unwrap();
1002        }
1003
1004        let denied = home_allow_dirs(home.path(), false);
1005        assert!(
1006            denied.is_empty(),
1007            "foreign editor dirs must stay jailed by default: {denied:?}"
1008        );
1009
1010        // Opt-in exposes the editor dirs that actually exist under this home.
1011        // Entries are registry-derived (foreign real-$HOME paths are filtered out
1012        // by the in-home guard), so the result stays hermetic — and `~/.lean-ctx`
1013        // is never added here because it is not an editor.
1014        let allowed = home_allow_dirs(home.path(), true);
1015        assert!(
1016            allowed.iter().any(|p| p.ends_with(".cursor")),
1017            "opt-in must expose editor dirs: {allowed:?}"
1018        );
1019        assert!(
1020            !allowed.iter().any(|p| p.ends_with(".lean-ctx")),
1021            "lean-ctx's own dir is covered by the data_dir root, not home_allow_dirs: {allowed:?}"
1022        );
1023    }
1024
1025    #[test]
1026    fn canonicalize_or_self_strips_verbatim() {
1027        let tmp = tempfile::tempdir().unwrap();
1028        let dir = tmp.path().join("project");
1029        std::fs::create_dir_all(&dir).unwrap();
1030
1031        let result = canonicalize_or_self(&dir);
1032        let s = result.to_string_lossy();
1033        assert!(
1034            !s.starts_with(r"\\?\"),
1035            "canonicalize_or_self should strip verbatim prefix, got: {s}"
1036        );
1037    }
1038
1039    #[test]
1040    fn jail_path_accepts_same_dir_different_format() {
1041        let _env = crate::core::data_dir::test_env_lock();
1042        let tmp = tempfile::tempdir().unwrap();
1043        let root = tmp.path().join("project");
1044        std::fs::create_dir_all(&root).unwrap();
1045        std::fs::write(root.join("file.rs"), "ok").unwrap();
1046
1047        let result = jail_path(&root.join("file.rs"), &root);
1048        assert!(result.is_ok(), "same dir should be accepted: {result:?}");
1049    }
1050
1051    #[cfg(not(feature = "no-jail"))]
1052    #[test]
1053    fn error_message_contains_escape_info() {
1054        // isolated_data_dir holds the global test_env_lock, serializing this
1055        // against any parallel `LEAN_CTX_ALLOW_PATH="/"` mutation.
1056        let _iso = crate::core::data_dir::isolated_data_dir();
1057        let tmp = tempfile::tempdir().unwrap();
1058        let root = tmp.path().join("root");
1059        let other = tmp.path().join("other");
1060        std::fs::create_dir_all(&root).unwrap();
1061        std::fs::create_dir_all(&other).unwrap();
1062        std::fs::write(other.join("b.txt"), "no").unwrap();
1063
1064        let err = jail_path(&other.join("b.txt"), &root).unwrap_err();
1065        assert!(
1066            err.to_string().contains("path escapes project root"),
1067            "error should mention escape: {err}"
1068        );
1069    }
1070
1071    // GH #887: over MCP (meta hints gated off) the rejection was bare, so
1072    // agents shelled out to work around the jail instead of widening it via
1073    // config. The agent-visible error must name the sanctioned config keys.
1074    #[cfg(not(feature = "no-jail"))]
1075    #[test]
1076    fn escape_error_names_config_keys_without_meta() {
1077        let _iso = crate::core::data_dir::isolated_data_dir();
1078        crate::test_env::remove_var("LEAN_CTX_META");
1079        crate::test_env::remove_var("LEAN_CTX_DIAGNOSTICS");
1080        let tmp = tempfile::tempdir().unwrap();
1081        let root = tmp.path().join("root");
1082        let other = tmp.path().join("other");
1083        std::fs::create_dir_all(&root).unwrap();
1084        std::fs::create_dir_all(&other).unwrap();
1085        std::fs::write(other.join("b.txt"), "no").unwrap();
1086
1087        let err = jail_path(&other.join("b.txt"), &root).unwrap_err();
1088        let msg = err.to_string();
1089        // One command that resolves it without a restart — never "open a new
1090        // IDE window" or an env var the running server cannot see.
1091        assert!(
1092            msg.contains("lean-ctx allow-path") && msg.contains("no restart"),
1093            "agent-visible escape error should hint at resolution: {msg}"
1094        );
1095        assert!(!msg.contains("LEAN_CTX_EXTRA_ROOTS="), "{msg}");
1096    }
1097
1098    // GH #392: config entries like "$HOME/code" or "~/code" were taken
1099    // literally and never matched.
1100    #[test]
1101    fn expand_user_path_expands_tilde_and_vars() {
1102        let _env_lock = crate::core::data_dir::test_env_lock();
1103        let home = dirs::home_dir().expect("home dir");
1104        let home_s = home.to_string_lossy().to_string();
1105
1106        assert_eq!(expand_user_path("~"), home);
1107        assert_eq!(expand_user_path("~/code"), home.join("code"));
1108        assert_eq!(expand_user_path("$HOME/code"), home.join("code"));
1109        assert_eq!(expand_user_path("${HOME}/code"), home.join("code"));
1110        // Multiple variables in one entry.
1111        crate::test_env::set_var("LEAN_CTX_TEST_SUB", "sub");
1112        assert_eq!(
1113            expand_user_path("$HOME/$LEAN_CTX_TEST_SUB/x"),
1114            PathBuf::from(format!("{home_s}/sub/x"))
1115        );
1116        crate::test_env::remove_var("LEAN_CTX_TEST_SUB");
1117        // Absolute paths pass through untouched.
1118        assert_eq!(expand_user_path("/etc"), PathBuf::from("/etc"));
1119    }
1120
1121    #[cfg(windows)]
1122    #[test]
1123    fn expand_user_path_home_falls_back_when_env_is_unset() {
1124        let _env_lock = crate::core::data_dir::test_env_lock();
1125        let expected_home = dirs::home_dir().expect("home dir");
1126        let previous_home = std::env::var_os("HOME");
1127
1128        struct RestoreHome(Option<std::ffi::OsString>);
1129
1130        impl Drop for RestoreHome {
1131            fn drop(&mut self) {
1132                match self.0.take() {
1133                    Some(value) => crate::test_env::set_var("HOME", value),
1134                    None => crate::test_env::remove_var("HOME"),
1135                }
1136            }
1137        }
1138
1139        let _restore_home = RestoreHome(previous_home);
1140        crate::test_env::remove_var("HOME");
1141
1142        assert_eq!(std::env::var_os("HOME"), None);
1143        assert_eq!(expand_user_path("$HOME/code"), expected_home.join("code"));
1144        assert_eq!(expand_user_path("${HOME}/code"), expected_home.join("code"));
1145    }
1146
1147    #[test]
1148    fn expand_user_path_leaves_unset_vars_verbatim() {
1149        let _env_lock = crate::core::data_dir::test_env_lock();
1150        crate::test_env::remove_var("LEAN_CTX_TEST_UNSET_VAR");
1151        let p = expand_user_path("$LEAN_CTX_TEST_UNSET_VAR/code");
1152        assert_eq!(p, PathBuf::from("$LEAN_CTX_TEST_UNSET_VAR/code"));
1153    }
1154
1155    // GH #392: `allow_paths = ["/"]` (via the same env-var channel) must grant
1156    // access to any absolute path — "/" is a prefix of everything.
1157    //
1158    // Env-mutating tests here hold the process-global
1159    // `data_dir::test_env_lock()` (directly, or via `isolated_data_dir()`
1160    // which wraps it) — NOT a module-local mutex. test_env's SAFETY contract
1161    // says *all* test env mutation serializes through that one lock; a local
1162    // lock only serializes this module against itself, so e.g.
1163    // `artifacts::external_corpus_requires_allow_list` (which holds the
1164    // global lock) could observe this test's `LEAN_CTX_ALLOW_PATH="/"` and
1165    // fail its jail-rejection assert (the pre-existing parallel-run flake
1166    // reported in #695).
1167    #[cfg(unix)]
1168    #[test]
1169    fn allow_path_root_slash_permits_everything() {
1170        let _guard = crate::core::data_dir::test_env_lock();
1171        let tmp = tempfile::tempdir().unwrap();
1172        let root = tmp.path().join("root");
1173        let other = tmp.path().join("other");
1174        std::fs::create_dir_all(&root).unwrap();
1175        std::fs::create_dir_all(&other).unwrap();
1176        std::fs::write(other.join("b.txt"), "allowed").unwrap();
1177
1178        crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", "/");
1179        let result = jail_path(&other.join("b.txt"), &root);
1180        crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
1181
1182        assert!(result.is_ok(), "allow path '/' must permit all: {result:?}");
1183    }
1184
1185    // Finding 3 (GH security audit): env-channel jail relaxations must be
1186    // detectable so startup + doctor can surface them loudly.
1187    #[test]
1188    fn active_relaxations_detects_allow_path_env() {
1189        let _iso = crate::core::data_dir::isolated_data_dir();
1190        crate::test_env::remove_var("LEAN_CTX_EXTRA_ROOTS");
1191        crate::test_env::remove_var("LEAN_CTX_ALLOW_IDE_DIRS");
1192        crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", "/tmp");
1193
1194        let relaxed = active_relaxations();
1195
1196        crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
1197
1198        assert!(
1199            relaxed.iter().any(|r| r.source == "LEAN_CTX_ALLOW_PATH"),
1200            "LEAN_CTX_ALLOW_PATH must be reported as a jail relaxation: {relaxed:?}"
1201        );
1202    }
1203
1204    #[cfg(not(feature = "no-jail"))]
1205    #[test]
1206    fn active_relaxations_empty_when_jail_intact() {
1207        let _iso = crate::core::data_dir::isolated_data_dir();
1208        for var in [
1209            "LEAN_CTX_ALLOW_PATH",
1210            "LCTX_ALLOW_PATH",
1211            "LEAN_CTX_EXTRA_ROOTS",
1212            "LEAN_CTX_ALLOW_IDE_DIRS",
1213        ] {
1214            crate::test_env::remove_var(var);
1215        }
1216
1217        assert!(
1218            active_relaxations().is_empty(),
1219            "an intact jail (clean config, no relaxation env) must report no relaxations: {:?}",
1220            active_relaxations()
1221        );
1222    }
1223
1224    #[test]
1225    fn allow_path_env_permits_outside_root() {
1226        let _guard = crate::core::data_dir::test_env_lock();
1227        let tmp = tempfile::tempdir().unwrap();
1228        let root = tmp.path().join("root");
1229        let other = tmp.path().join("other");
1230        std::fs::create_dir_all(&root).unwrap();
1231        std::fs::create_dir_all(&other).unwrap();
1232        std::fs::write(other.join("b.txt"), "allowed").unwrap();
1233
1234        let canon = canonicalize_or_self(&other);
1235        crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", canon.to_string_lossy().as_ref());
1236        let result = jail_path(&other.join("b.txt"), &root);
1237        crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
1238
1239        assert!(
1240            result.is_ok(),
1241            "LEAN_CTX_ALLOW_PATH should permit access: {result:?}"
1242        );
1243    }
1244
1245    #[cfg(all(unix, not(feature = "no-jail")))]
1246    #[test]
1247    fn rejects_symlink_escape_on_unix() {
1248        use std::os::unix::fs::symlink;
1249
1250        // isolated_data_dir holds the global test_env_lock — no parallel test
1251        // can set `LEAN_CTX_ALLOW_PATH="/"` and let this escape resolve.
1252        let _iso = crate::core::data_dir::isolated_data_dir();
1253        let tmp = tempfile::tempdir().unwrap();
1254        let root = tmp.path().join("root");
1255        let other = tmp.path().join("other");
1256        std::fs::create_dir_all(&root).unwrap();
1257        std::fs::create_dir_all(&other).unwrap();
1258        std::fs::write(other.join("secret.txt"), "no").unwrap();
1259
1260        let link = root.join("link.txt");
1261        symlink(other.join("secret.txt"), &link).unwrap();
1262
1263        let bad = jail_path(&link, &root);
1264        assert!(bad.is_err(), "symlink escape must be rejected: {bad:?}");
1265    }
1266
1267    #[test]
1268    fn rejects_null_byte_in_path() {
1269        let _env = crate::core::data_dir::test_env_lock();
1270        let tmp = tempfile::tempdir().unwrap();
1271        let root = tmp.path().join("root");
1272        std::fs::create_dir_all(&root).unwrap();
1273
1274        let bad_path = PathBuf::from("file\0.txt");
1275        let result = jail_path(&bad_path, &root);
1276        assert!(result.is_err(), "null byte in path must be rejected");
1277        assert!(
1278            result.unwrap_err().to_string().contains("null byte"),
1279            "error must mention null byte"
1280        );
1281    }
1282
1283    /// #403 Bug 1: an explicit path under a session-scoped `extra_root` (e.g. a
1284    /// sibling git worktree from MCP `roots/list`) must resolve, while the same
1285    /// path is rejected without it — and a path under *no* root is rejected even
1286    /// when extra roots are present. Holds both env locks so neither a parallel
1287    /// `path_jail` flip nor a `LEAN_CTX_ALLOW_PATH` mutation can leak in.
1288    #[cfg(not(feature = "no-jail"))]
1289    #[test]
1290    fn extra_roots_permit_paths_outside_jail() {
1291        let _iso = crate::core::data_dir::isolated_data_dir();
1292
1293        let tmp = tempfile::tempdir().unwrap();
1294        let root = tmp.path().join("project");
1295        let worktree = tmp.path().join("worktree");
1296        let elsewhere = tmp.path().join("elsewhere");
1297        for d in [&root, &worktree, &elsewhere] {
1298            std::fs::create_dir_all(d).unwrap();
1299        }
1300        let in_worktree = worktree.join("a.txt");
1301        std::fs::write(&in_worktree, "x").unwrap();
1302        let outside = elsewhere.join("b.txt");
1303        std::fs::write(&outside, "y").unwrap();
1304
1305        // Parity: with no extra roots, the worktree path escapes the jail.
1306        assert!(jail_path(&in_worktree, &root).is_err());
1307        assert!(jail_path_with_roots(&in_worktree, &root, &[]).is_err());
1308
1309        // The session-scoped extra root permits it — via the slice alone, with
1310        // nothing in env/config.
1311        let extra = vec![worktree.to_string_lossy().to_string()];
1312        assert!(
1313            jail_path_with_roots(&in_worktree, &root, &extra).is_ok(),
1314            "path under a session extra_root must resolve (#403)"
1315        );
1316
1317        // A path under neither the jail nor any extra root is still rejected.
1318        assert!(
1319            jail_path_with_roots(&outside, &root, &extra).is_err(),
1320            "paths outside ALL roots must still be rejected"
1321        );
1322
1323        // Empty entries are ignored (no accidental allow-all).
1324        assert!(jail_path_with_roots(&outside, &root, &[String::new()]).is_err());
1325    }
1326
1327    /// GH #1228: Claude Code auto-memory under `…/.claude/projects/<slug>/memory/`
1328    /// must be readable/writable via ctx_* without a manual extra_roots edit.
1329    #[cfg(not(feature = "no-jail"))]
1330    #[test]
1331    fn harness_auto_memory_path_is_allowed_without_extra_roots() {
1332        let _iso = crate::core::data_dir::isolated_data_dir();
1333        let tmp = tempfile::tempdir().unwrap();
1334        let root = tmp.path().join("project");
1335        let memory = tmp
1336            .path()
1337            .join(".claude")
1338            .join("projects")
1339            .join("-tmp-project")
1340            .join("memory");
1341        std::fs::create_dir_all(&root).unwrap();
1342        std::fs::create_dir_all(&memory).unwrap();
1343        let mem_file = memory.join("MEMORY.md");
1344        std::fs::write(&mem_file, "# index\n").unwrap();
1345
1346        assert!(is_harness_auto_memory_path(&mem_file));
1347        assert!(is_harness_auto_memory_path(&memory));
1348        assert!(!is_harness_auto_memory_path(
1349            &tmp.path()
1350                .join(".claude")
1351                .join("projects")
1352                .join("-tmp-project")
1353                .join("session.jsonl")
1354        ));
1355
1356        assert!(
1357            jail_path_with_roots(&mem_file, &root, &[]).is_ok(),
1358            "auto-memory file must pass PathJail without extra_roots"
1359        );
1360    }
1361
1362    /// #820: lean-ctx state dir (tee files) is implicitly allowed by the jail.
1363    #[test]
1364    fn state_dir_tee_files_pass_jail() {
1365        let _lock = crate::core::data_dir::test_env_lock();
1366        let state = crate::core::paths::state_dir().expect("state_dir must be available");
1367        let tee_path = state.join("tee").join("some_command_deadbeef.log");
1368        // Use a root that is clearly NOT the state dir's parent
1369        let fake_root = std::env::temp_dir().join("pathjail_test_820_root");
1370        std::fs::create_dir_all(&fake_root).ok();
1371        // The tee path is outside the fake root, but the state dir allowance
1372        // should make it pass (the state dir itself exists on disk).
1373        let result = jail_path_with_roots(&tee_path, &fake_root, &[]);
1374        // If state_dir exists on disk (it does in dev), the path should be allowed.
1375        // If the tee file itself doesn't exist, canonicalize_existing_ancestor
1376        // resolves to the state_dir (which does exist) + remainder.
1377        if state.exists() {
1378            assert!(
1379                result.is_ok(),
1380                "tee-file path under lean-ctx state dir must be auto-allowed: {result:?}"
1381            );
1382        }
1383        std::fs::remove_dir_all(&fake_root).ok();
1384    }
1385
1386    #[test]
1387    fn detected_cache_hint_recognizes_go_cargo_python() {
1388        use std::path::Path;
1389        let go = detected_cache_hint(Path::new("/Users/x/go/pkg/mod/github.com/foo/bar/main.go"));
1390        assert!(go.is_some(), "Go module cache should be detected");
1391        assert!(go.unwrap().contains("Go module cache"));
1392
1393        let cargo = detected_cache_hint(Path::new(
1394            "/home/x/.cargo/registry/src/crates.io/serde-1.0/lib.rs",
1395        ));
1396        assert!(cargo.is_some(), "Rust cargo registry should be detected");
1397        assert!(cargo.unwrap().contains("Rust crate registry"));
1398
1399        let py = detected_cache_hint(Path::new(
1400            "/usr/lib/python3.12/site-packages/requests/api.py",
1401        ));
1402        assert!(py.is_some(), "Python site-packages should be detected");
1403
1404        let normal = detected_cache_hint(Path::new("/home/x/projects/myapp/src/main.rs"));
1405        assert!(normal.is_none(), "Normal project path should not match");
1406    }
1407
1408    #[test]
1409    fn detect_cache_root_extracts_marker_dir() {
1410        let cases = [
1411            (
1412                "/Users/x/go/pkg/mod/github.com/foo/bar@v1.2.3/baz.go",
1413                "Go module cache",
1414                "/Users/x/go/pkg/mod",
1415            ),
1416            (
1417                "/home/u/.cargo/registry/src/index-abc/serde-1.0/src/lib.rs",
1418                "Rust crate registry",
1419                "/home/u/.cargo/registry",
1420            ),
1421            (
1422                "/opt/venv/lib/python3.12/site-packages/requests/api.py",
1423                "Python site-packages",
1424                "/opt/venv/lib/python3.12/site-packages",
1425            ),
1426            (
1427                "/w/app/node_modules/react/index.js",
1428                "Node modules",
1429                "/w/app/node_modules",
1430            ),
1431        ];
1432        for (path, want_label, want_root) in cases {
1433            let (label, root) = detect_language_cache_root(Path::new(path))
1434                .unwrap_or_else(|| panic!("expected cache match for {path}"));
1435            assert_eq!(label, want_label, "label for {path}");
1436            assert_eq!(root, PathBuf::from(want_root), "root for {path}");
1437        }
1438        assert!(
1439            detect_language_cache_root(Path::new("/home/u/proj/src/main.rs")).is_none(),
1440            "a normal project path is not a cache"
1441        );
1442    }
1443
1444    /// The core #899 guarantee: once a detected cache root is registered, a path
1445    /// under it *reads* (jail resolves) but never *writes* (enforce_writable
1446    /// denies), and registration is idempotent.
1447    #[cfg(not(feature = "no-jail"))]
1448    #[test]
1449    fn registered_cache_root_reads_allow_writes_deny() {
1450        let _iso = crate::core::data_dir::isolated_data_dir();
1451
1452        let tmp = tempfile::tempdir().unwrap();
1453        // A fake Go module cache so detect_language_cache_root matches the path.
1454        let dep = tmp.path().join("go/pkg/mod/example.com/lib@v1");
1455        std::fs::create_dir_all(&dep).unwrap();
1456        let file = dep.join("lib.go");
1457        std::fs::write(&file, "package lib").unwrap();
1458
1459        // A project jail that does NOT contain the cache.
1460        let project = tmp.path().join("project");
1461        std::fs::create_dir_all(&project).unwrap();
1462
1463        // Before registration: the read escapes the jail.
1464        assert!(jail_path_with_roots(&file, &project, &[]).is_err());
1465
1466        // Register the detected root; the second call is a no-op.
1467        let (_, root) = detect_language_cache_root(&file).expect("cache match");
1468        assert!(
1469            register_session_read_only_root(&root),
1470            "first register is new"
1471        );
1472        assert!(
1473            !register_session_read_only_root(&root),
1474            "re-register is a no-op"
1475        );
1476
1477        // After: the read resolves, but writes are denied (read-only tier).
1478        assert!(
1479            jail_path_with_roots(&file, &project, &[]).is_ok(),
1480            "registered cache root must be readable"
1481        );
1482        assert!(is_read_only_path(&file), "cache file is read-only");
1483        assert!(
1484            enforce_writable(&file).is_err(),
1485            "writes into the cache root must be denied"
1486        );
1487    }
1488}