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