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