Skip to main content

lean_ctx/core/
pathjail.rs

1use std::path::{Path, PathBuf};
2
3use crate::core::error::PathJailError;
4
5/// `allow_paths` / `extra_roots` come from `config.toml`, where no shell ever
6/// runs — users writing `"$HOME/code"` or `"~/code"` got a literal,
7/// never-matching prefix and concluded the whole option was broken (GH #392).
8/// Unset variables are left verbatim (and warned about) so the entry fails
9/// loudly in `lean-ctx doctor` instead of silently matching something else.
10/// `HOME` falls back to the platform home directory when the environment
11/// variable is absent, as is common in native Windows shells.
12pub fn expand_user_path(raw: &str) -> PathBuf {
13    let mut s = raw.to_string();
14
15    if (s == "~" || s.starts_with("~/"))
16        && let Some(home) = dirs::home_dir()
17    {
18        s = format!("{}{}", home.to_string_lossy(), &s[1..]);
19    }
20
21    while let Some(start) = s.find('$') {
22        let rest = &s[start + 1..];
23        let (name, token_len) = if let Some(stripped) = rest.strip_prefix('{') {
24            match stripped.find('}') {
25                Some(end) => (stripped[..end].to_string(), end + 3),
26                None => break,
27            }
28        } else {
29            let end = rest
30                .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
31                .unwrap_or(rest.len());
32            (rest[..end].to_string(), end + 1)
33        };
34        if name.is_empty() {
35            break;
36        }
37        if let Ok(val) = std::env::var(&name) {
38            s.replace_range(start..start + token_len, &val);
39        } else if name == "HOME"
40            && let Some(home) = dirs::home_dir()
41        {
42            let home = home.to_string_lossy();
43            s.replace_range(start..start + token_len, home.as_ref());
44        } else {
45            tracing::warn!(
46                "allow_paths/extra_roots entry '{raw}' references unset variable ${name} — entry will never match"
47            );
48            break;
49        }
50    }
51
52    PathBuf::from(s)
53}
54
55pub fn allow_paths_from_env_and_config() -> Vec<PathBuf> {
56    let mut out = Vec::new();
57    let cfg = crate::core::config::Config::load();
58
59    // The allow-list defines the jail boundary, so it must be canonicalized the
60    // same (security, symlink-resolving) way as the candidate it is compared
61    // against — otherwise a guarded (lexical) root vs a resolved candidate would
62    // break `is_under_prefix`. These entries are data_dir / IDE-config dirs /
63    // user-configured paths, virtually never under ~/Documents.
64    //
65    // This is also lean-ctx's own state dir (sessions, knowledge, …) — always
66    // readable even while foreign editor dirs stay jailed. On a legacy install
67    // the resolver returns `~/.lean-ctx`; on a split install it returns the XDG
68    // data dir. Going through the resolver (not a hardcoded `~/.lean-ctx` join)
69    // is what keeps `home_allow_dirs` free of the legacy-path firewall trip.
70    if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
71        out.push(canonicalize_secure(&data_dir));
72    }
73
74    if let Some(home) = dirs::home_dir() {
75        let ide_dirs_allowed = cfg.allow_ide_config_dirs.unwrap_or(false)
76            || std::env::var("LEAN_CTX_ALLOW_IDE_DIRS").is_ok_and(|v| v == "1");
77        out.extend(home_allow_dirs(&home, ide_dirs_allowed));
78    }
79
80    for p in &cfg.allow_paths {
81        out.push(canonicalize_secure(&expand_user_path(p)));
82    }
83    for p in &cfg.extra_roots {
84        out.push(canonicalize_secure(&expand_user_path(p)));
85    }
86
87    for path in crate::core::runtime_flags::allow_paths() {
88        out.push(canonicalize_secure(&path));
89    }
90    // Env entries are expanded too: MCP host configs pass env blocks verbatim
91    // (no shell), so "$HOME/code" arrives literally there as well.
92    let v = std::env::var("LCTX_ALLOW_PATH")
93        .or_else(|_| std::env::var("LEAN_CTX_ALLOW_PATH"))
94        .unwrap_or_default();
95    if !v.trim().is_empty() {
96        for p in std::env::split_paths(&v) {
97            out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
98        }
99    }
100
101    let extra = std::env::var("LEAN_CTX_EXTRA_ROOTS").unwrap_or_default();
102    if !extra.trim().is_empty() {
103        for p in std::env::split_paths(&extra) {
104            out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
105        }
106    }
107
108    // Read-only roots are *readable* (the whole point is read access to sibling
109    // repos); writes into them are denied separately by `enforce_writable`
110    // (#475). Add them to the read allow-list so reads resolve, exactly like
111    // `extra_roots`, without granting write access.
112    out.extend(canonicalized_roots(
113        &cfg.read_only_roots,
114        "LEAN_CTX_READ_ONLY_ROOTS",
115    ));
116
117    out
118}
119
120/// Canonicalize a set of config-supplied root entries plus an env override
121/// (path-list separated), expanding `~`/`$VAR` first. Shared by the read
122/// allow-list and the read-only-roots collector so both tiers parse roots
123/// identically.
124fn canonicalized_roots(config_entries: &[String], env_var: &str) -> Vec<PathBuf> {
125    let mut out = Vec::new();
126    for p in config_entries {
127        out.push(canonicalize_secure(&expand_user_path(p)));
128    }
129    let v = std::env::var(env_var).unwrap_or_default();
130    if !v.trim().is_empty() {
131        for p in std::env::split_paths(&v) {
132            out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
133        }
134    }
135    out
136}
137
138/// A read-only root is a sibling subtree the agent may **read** but never
139/// **write** — e.g. a reference repo mounted next to the project. Empty by
140/// default, so [`is_read_only_path`]/[`enforce_writable`] are zero-cost no-ops
141/// for everyone who hasn't opted in (#475).
142pub fn read_only_roots_from_env_and_config() -> Vec<PathBuf> {
143    let cfg = crate::core::config::Config::load();
144    let mut roots = canonicalized_roots(&cfg.read_only_roots, "LEAN_CTX_READ_ONLY_ROOTS");
145    // #899: session-scoped roots auto-detected from language caches. Consulted
146    // by both the read allow-list (jail) and `is_read_only_path` (write-deny),
147    // so a cache root is readable but never writable — exactly like a configured
148    // read-only root, minus the config-file edit.
149    roots.extend(session_read_only_roots());
150    roots
151}
152
153static SESSION_READ_ONLY_ROOTS: std::sync::OnceLock<std::sync::Mutex<Vec<PathBuf>>> =
154    std::sync::OnceLock::new();
155
156fn session_read_only_roots_cell() -> &'static std::sync::Mutex<Vec<PathBuf>> {
157    SESSION_READ_ONLY_ROOTS.get_or_init(|| std::sync::Mutex::new(Vec::new()))
158}
159
160/// The session-scoped read-only roots auto-registered this process (#899).
161pub fn session_read_only_roots() -> Vec<PathBuf> {
162    session_read_only_roots_cell()
163        .lock()
164        .map(|g| g.clone())
165        .unwrap_or_default()
166}
167
168/// Register a session-scoped read-only root (an auto-detected language cache).
169/// Returns `true` when newly added. Idempotent on the canonicalized path.
170///
171/// ponytail: process-global set, not per-session — language caches
172/// (`~/go/pkg/mod`, `~/.cargo/registry`, …) are machine-global read-only dirs,
173/// so sharing read access across sessions grants nothing a session couldn't
174/// already get by reading them; per-session isolation would be plumbing for no
175/// security gain. Upgrade to a session-keyed map only if writable roots ever go
176/// down this path.
177pub fn register_session_read_only_root(root: &Path) -> bool {
178    let canon = canonicalize_secure(root);
179    let mut guard = match session_read_only_roots_cell().lock() {
180        Ok(g) => g,
181        Err(poisoned) => poisoned.into_inner(),
182    };
183    if guard.iter().any(|r| r == &canon) {
184        return false;
185    }
186    guard.push(canon);
187    true
188}
189
190/// A single active relaxation of the path jail. Each one widens or disables what
191/// tools can reach beyond the project root, so it is surfaced loudly (GH security
192/// audit, finding 3): the MCP/HTTP server inherits its process env from the
193/// IDE/launchd, so a globally-set `LEAN_CTX_ALLOW_PATH` / `LEAN_CTX_EXTRA_ROOTS`
194/// / `LEAN_CTX_ALLOW_IDE_DIRS` (or `path_jail = false`) silently loosens the
195/// boundary with no in-band signal otherwise.
196#[derive(Debug, Clone, Copy, PartialEq, Eq)]
197pub struct JailRelaxation {
198    /// The knob that activated it (env var name, config key, or build feature).
199    pub source: &'static str,
200    /// Human-readable effect of the relaxation.
201    pub detail: &'static str,
202}
203
204fn env_is_set(var: &str) -> bool {
205    std::env::var(var).is_ok_and(|v| !v.trim().is_empty())
206}
207
208/// Collect every currently-active path-jail relaxation. An empty result means
209/// the jail is fully in force. This is the single source of truth shared by the
210/// startup warning ([`warn_if_relaxed`]) and `lean-ctx doctor`.
211#[must_use]
212pub fn active_relaxations() -> Vec<JailRelaxation> {
213    let mut out = Vec::new();
214
215    if cfg!(feature = "no-jail") {
216        out.push(JailRelaxation {
217            source: "no-jail (build feature)",
218            detail: "path jail compiled out — every tool path is allowed",
219        });
220    }
221
222    if crate::core::config::Config::load().path_jail == Some(false) {
223        out.push(JailRelaxation {
224            source: "path_jail = false (config.toml)",
225            detail: "path jail disabled — every tool path is allowed",
226        });
227    }
228
229    if crate::core::runtime_flags::allow_path_enabled() {
230        out.push(JailRelaxation {
231            source: "LEAN_CTX_ALLOW_PATH",
232            detail: "widens the read/write allow-list beyond the project root",
233        });
234    }
235
236    if env_is_set("LEAN_CTX_EXTRA_ROOTS") {
237        out.push(JailRelaxation {
238            source: "LEAN_CTX_EXTRA_ROOTS",
239            detail: "adds extra accessible roots beyond the project root",
240        });
241    }
242
243    let ide_env = std::env::var("LEAN_CTX_ALLOW_IDE_DIRS").is_ok_and(|v| v == "1");
244    if ide_env
245        || crate::core::config::Config::load()
246            .allow_ide_config_dirs
247            .unwrap_or(false)
248    {
249        out.push(JailRelaxation {
250            source: if ide_env {
251                "LEAN_CTX_ALLOW_IDE_DIRS=1"
252            } else {
253                "allow_ide_config_dirs = true (config.toml)"
254            },
255            detail: "exposes ~/.cursor, ~/.claude, … (other agents' sessions/credentials) to tools",
256        });
257    }
258
259    out
260}
261
262/// Emit a loud `tracing::warn!` for every active path-jail relaxation. Called
263/// once at MCP/HTTP server startup so a trusted-but-loosening env/config leaves
264/// an in-band audit signal instead of silently defeating the jail (finding 3).
265pub fn warn_if_relaxed() {
266    for relaxation in active_relaxations() {
267        tracing::warn!(
268            "[SECURITY] path jail relaxed via {}: {} — intended for trusted local use only",
269            relaxation.source,
270            relaxation.detail
271        );
272    }
273}
274
275/// True when `candidate` resolves to a location inside a configured read-only
276/// root. The candidate's nearest existing ancestor is canonicalized (so a
277/// not-yet-existing file inherits the read-only status of the directory it
278/// would be created in — closing the "create a new file in a read-only repo"
279/// hole) and matched against the (symlink-resolved) read-only roots.
280///
281/// A `false` return is only authoritative when the roots list is empty or the
282/// path provably sits outside every root; an unresolvable candidate (no
283/// existing ancestor) is treated as *not* read-only here and is rejected later
284/// by the ordinary write/jail error, never silently written.
285pub fn is_read_only_path(candidate: &Path) -> bool {
286    let roots = read_only_roots_from_env_and_config();
287    if roots.is_empty() {
288        return false;
289    }
290    let base = canonical_target(candidate);
291    roots.iter().any(|r| is_under_prefix(&base, r))
292}
293
294/// The canonicalized nearest-existing-ancestor of `candidate` with the
295/// not-yet-existing remainder re-appended. Resolves symlinks so a symlink
296/// *into* a guarded root cannot launder a write past a prefix check.
297fn canonical_target(candidate: &Path) -> PathBuf {
298    match canonicalize_existing_ancestor(candidate) {
299        Some((mut p, remainder)) => {
300            for part in remainder.iter().rev() {
301                p.push(part);
302            }
303            p
304        }
305        None => canonicalize_or_self(candidate),
306    }
307}
308
309/// Default-deny write guard for the read-only tier (#475): returns an error if
310/// `candidate` is inside a configured read-only root, `Ok(())` otherwise.
311///
312/// This is the single read-only-aware choke point. Every filesystem write that
313/// can target a caller-supplied path routes through it (the atomic writers in
314/// `ctx_edit`/`edit_apply`, the handoff/session export bundle writers, the
315/// in-place memory-compaction writer, and the refactor IDE pre-write gate), so
316/// a "read-only" root cannot be written through any tool. Reads are unaffected.
317pub fn enforce_writable(candidate: &Path) -> Result<(), String> {
318    // This boundary covers caller-selected edit/backup/export destinations.
319    // Engine-owned knowledge persistence uses its own authorized store writer.
320    crate::cli::enforce_protected_store_path(candidate)?;
321    if is_read_only_path(candidate) {
322        return Err(format!(
323            "path is inside a read-only root — writes are denied (read_only_roots): {}",
324            candidate.display()
325        ));
326    }
327    match super::pathjail_scope::home_scope_write_denial(&canonical_target(candidate)) {
328        Some(denial) => Err(denial),
329        None => Ok(()),
330    }
331}
332
333/// Foreign editor config dirs for the jail (~/.cursor, ~/.claude, VS Code, …).
334///
335/// These expose other projects' sessions, MCP configs and credentials to any
336/// agent, so they are opt-in only (config `allow_ide_config_dirs = true` or
337/// `LEAN_CTX_ALLOW_IDE_DIRS=1`). lean-ctx's *own* state dir is intentionally NOT
338/// handled here: the caller already adds it via the sanctioned `data_dir`
339/// resolver (the legacy `~/.lean-ctx` is just one resolution of it). Keeping this
340/// a pure foreign-editor list means no legacy `~/.lean-ctx` literal is built in
341/// this module, so the legacy-path firewall (tests/legacy_path_firewall) has
342/// nothing to flag.
343fn home_allow_dirs(home: &Path, ide_dirs_allowed: bool) -> Vec<PathBuf> {
344    let mut out = Vec::new();
345    if ide_dirs_allowed {
346        let targets = crate::core::editor_registry::build_targets(home);
347        collect_ide_allow_dirs(home, &targets, &mut out);
348    }
349    out
350}
351
352/// Collect the in-home config/detect directories of every supported editor.
353///
354/// Derived from the editor registry (the single source of truth) so it covers
355/// non-dotfile layouts too — VS Code's `Library/Application Support/Code/User`,
356/// Cline/Roo globalStorage, JetBrains — and never drifts as editors are added.
357/// A config file that sits directly in `$HOME` (`~/.claude.json`,
358/// `~/.jb-mcp.json`) resolves its parent to `$HOME`; those entries are skipped
359/// so the jail is never widened to the entire home directory.
360fn collect_ide_allow_dirs(
361    home: &Path,
362    targets: &[crate::core::editor_registry::EditorTarget],
363    out: &mut Vec<PathBuf>,
364) {
365    let mut seen: std::collections::HashSet<PathBuf> = out.iter().cloned().collect();
366    for target in targets {
367        let candidates = [
368            target.config_path.parent().map(Path::to_path_buf),
369            Some(target.detect_path.clone()),
370        ];
371        for cand in candidates.into_iter().flatten() {
372            if cand.as_path() == home || !cand.starts_with(home) || !cand.is_dir() {
373                continue;
374            }
375            let resolved = canonicalize_secure(&cand);
376            if seen.insert(resolved.clone()) {
377                out.push(resolved);
378            }
379        }
380    }
381}
382
383fn is_under_prefix(path: &Path, prefix: &Path) -> bool {
384    path.starts_with(prefix)
385}
386
387/// True for Claude Code / CodeBuddy auto-memory files under
388/// `~/.claude/projects/<slug>/memory/` (and the CodeBuddy twin).
389///
390/// Auto memory uses the host's native Read/Edit/Write on these paths
391/// (code.claude.com/docs/en/memory). Replace-mode PathJail must not force
392/// agents to shell out or hit MCP `resources/read` with file URIs (GH #1228).
393/// Scoped to the `memory/` subdirectory only — session transcripts and
394/// credentials under `projects/<slug>/` stay jailed.
395pub fn is_harness_auto_memory_path(path: &Path) -> bool {
396    let lower = path.to_string_lossy().replace('\\', "/").to_lowercase();
397    for marker in ["/.claude/projects/", "/.codebuddy/projects/"] {
398        if let Some(idx) = lower.find(marker) {
399            let after = &lower[idx + marker.len()..];
400            let mut parts = after.split('/');
401            let Some(_slug) = parts.next() else {
402                continue;
403            };
404            if parts.next() == Some("memory") {
405                return true;
406            }
407        }
408    }
409    false
410}
411
412fn path_allowed_by_jail(base: &Path, root: &Path, allow: &[PathBuf]) -> bool {
413    if is_harness_auto_memory_path(base) {
414        return true;
415    }
416    let allowed = is_under_prefix(base, root)
417        || allow.iter().any(|p| is_under_prefix(base, p))
418        || super::pathjail_scope::home_scope_admits(base);
419    #[cfg(windows)]
420    let allowed = allowed || is_under_prefix_windows(base, root);
421    allowed && super::pathjail_scope::protected_zone_permits(base, root, allow)
422}
423
424/// Heuristic canonicalize — honours the #356 TCC guard. Used by the
425/// jail-disabled bypass and by external callers (session/startup/server roots)
426/// that must not pop a privacy prompt on their own initiative.
427pub fn canonicalize_or_self(path: &Path) -> PathBuf {
428    super::pathutil::safe_canonicalize_bounded(path, 2000)
429}
430
431/// SECURITY canonicalize for the jail boundary itself (roots + candidate +
432/// escape re-check). Deliberately bypasses the #356 TCC guard: the jail must
433/// keep resolving symlinks to detect escapes, and it only ever runs on a path
434/// the client explicitly asked to access, where a one-time prompt is legitimate.
435pub(crate) fn canonicalize_secure(path: &Path) -> PathBuf {
436    super::pathutil::canonicalize_secure_bounded(path, 2000)
437}
438
439fn canonicalize_existing_ancestor(path: &Path) -> Option<(PathBuf, Vec<std::ffi::OsString>)> {
440    let mut cur = path.to_path_buf();
441    let mut remainder: Vec<std::ffi::OsString> = Vec::new();
442    loop {
443        if cur.exists() {
444            return Some((canonicalize_secure(&cur), remainder));
445        }
446        let name = cur.file_name()?.to_os_string();
447        remainder.push(name);
448        if !cur.pop() {
449            return None;
450        }
451    }
452}
453
454pub fn jail_path(candidate: &Path, jail_root: &Path) -> Result<PathBuf, PathJailError> {
455    jail_path_with_roots(candidate, jail_root, &[])
456}
457
458/// Known language-cache markers (#899): (path substring, human label, config
459/// example). Single source of truth shared by [`detected_cache_hint`] (the
460/// jail-error suggestion) and [`detect_language_cache_root`] (session
461/// auto-registration), so the two never drift.
462const LANGUAGE_CACHE_PATTERNS: &[(&str, &str, &str)] = &[
463    ("/go/pkg/mod/", "Go module cache", "~/go/pkg/mod"),
464    (
465        "/.cargo/registry/",
466        "Rust crate registry",
467        "~/.cargo/registry",
468    ),
469    (
470        "/site-packages/",
471        "Python site-packages",
472        "<venv>/lib/pythonX.Y/site-packages",
473    ),
474    ("/node_modules/", "Node modules", "<project>/node_modules"),
475    (
476        "/.m2/repository/",
477        "Maven local repository",
478        "~/.m2/repository",
479    ),
480    ("/.gradle/caches/", "Gradle cache", "~/.gradle/caches"),
481    (
482        "/.nuget/packages/",
483        "NuGet package cache",
484        "~/.nuget/packages",
485    ),
486    // Dependency source agents look up as often as the registry: the Rust
487    // standard library and git dependencies, and the Bun, Dart and Ruby
488    // package stores. Package source only — no credentials live here.
489    (
490        "/.rustup/toolchains/",
491        "Rust toolchain source",
492        "~/.rustup/toolchains",
493    ),
494    (
495        "/.cargo/git/checkouts/",
496        "Cargo git dependencies",
497        "~/.cargo/git/checkouts",
498    ),
499    (
500        "/.bun/install/cache/",
501        "Bun package cache",
502        "~/.bun/install/cache",
503    ),
504    (
505        "/.pub-cache/hosted/",
506        "Dart pub cache",
507        "~/.pub-cache/hosted",
508    ),
509    ("/.gem/ruby/", "Ruby gems", "~/.gem/ruby"),
510];
511
512/// Detect well-known language cache paths and return a targeted hint. Used for
513/// jail callers that don't auto-register (e.g. batch reads); the single-path
514/// ctx_read flow instead auto-registers via [`detect_language_cache_root`].
515fn detected_cache_hint(candidate: &std::path::Path) -> Option<String> {
516    let s = candidate.to_string_lossy();
517    for &(pattern, name, example) in LANGUAGE_CACHE_PATTERNS {
518        if s.contains(pattern) {
519            return Some(format!(
520                ". Detected {name} — add read_only_roots = [\"{example}\"] to \
521                 ~/.config/lean-ctx/config.toml for cached, compressed reads without write access"
522            ));
523        }
524    }
525    None
526}
527
528/// If `candidate` sits inside a known language cache, return `(label, root)`
529/// where `root` is the path truncated at the end of the marker directory (no
530/// trailing slash). resolve_path uses this to auto-register a session read-only
531/// root so the retry resolves without a config edit or a subprocess (#899).
532pub fn detect_language_cache_root(candidate: &Path) -> Option<(&'static str, PathBuf)> {
533    let s = candidate.to_string_lossy().replace('\\', "/");
534    for &(marker, label, _) in LANGUAGE_CACHE_PATTERNS {
535        if let Some(idx) = s.find(marker) {
536            let end = idx + marker.len() - 1; // keep the marker dir, drop trailing '/'
537            return Some((label, PathBuf::from(&s[..end])));
538        }
539    }
540    None
541}
542
543/// Like [`jail_path`], but also accepts paths under any of `extra_roots`.
544///
545/// `extra_roots` are session-scoped trusted roots (MCP `roots/list` and config
546/// `extra_roots`, surfaced via `session.extra_roots`) — e.g. sibling git
547/// worktrees the agent legitimately spans. They widen the allow-list for *this
548/// call only*, so an explicit `path` under a worktree resolves instead of
549/// failing with "path escapes project root", without loosening the global jail
550/// (#403). `path_jail = false` still bypasses entirely and an empty slice is
551/// byte-for-byte identical to the old single-root behaviour.
552pub fn jail_path_with_roots(
553    candidate: &Path,
554    jail_root: &Path,
555    extra_roots: &[String],
556) -> Result<PathBuf, PathJailError> {
557    if candidate.to_string_lossy().as_bytes().contains(&0) {
558        return Err(PathJailError::NullByte);
559    }
560
561    // Runtime context is reached through authorized knowledge/recovery APIs,
562    // never by widening a model-directed file read to the Engine's own store.
563    // Apply this before no-jail/config/implicit runtime allow-list shortcuts.
564    let absolute = if candidate.is_absolute() {
565        candidate.to_path_buf()
566    } else {
567        jail_root.join(candidate)
568    };
569    crate::cli::enforce_protected_store_path(&absolute)
570        .map_err(|reason| PathJailError::ProtectedContext { reason })?;
571
572    #[cfg(feature = "no-jail")]
573    {
574        let _ = (jail_root, extra_roots);
575        return Ok(canonicalize_or_self(candidate));
576    }
577
578    #[allow(unreachable_code)]
579    {
580        let cfg = crate::core::config::Config::load();
581        if cfg.path_jail == Some(false) {
582            return Ok(canonicalize_or_self(candidate));
583        }
584
585        let root = canonicalize_secure(jail_root);
586
587        // Resolve relative candidates against the (absolute) jail root — never the process
588        // CWD. The daemon's CWD is not the project, so CWD-relative resolution made
589        // graph-relative paths (e.g. auto-preload candidates like `rust/src/core/foo.rs`)
590        // spuriously fail with "no existing ancestor". Absolute candidates are unchanged.
591        let resolved: PathBuf;
592        let candidate: &Path = if candidate.is_absolute() {
593            candidate
594        } else {
595            resolved = root.join(candidate);
596            resolved.as_path()
597        };
598
599        let mut allow = allow_paths_from_env_and_config();
600        // Session-scoped roots widen the allow-list for this call only.
601        allow.extend(
602            extra_roots
603                .iter()
604                .filter(|r| !r.is_empty())
605                .map(|r| canonicalize_secure(Path::new(r))),
606        );
607
608        // #820: lean-ctx's own state dir (tee files, artifacts, tool-results)
609        // must be readable even when outside the project root. ctx_shell
610        // tells agents to read tee-file paths, so the jail must allow them.
611        if let Ok(state) = crate::core::paths::state_dir() {
612            allow.push(canonicalize_secure(&state));
613        }
614        // Read-only roots are also allowed for reads (they only block writes
615        // via enforce_writable, not reads via the jail).
616        allow.extend(
617            read_only_roots_from_env_and_config()
618                .into_iter()
619                .map(|p| canonicalize_secure(&p)),
620        );
621
622        let (base, remainder) = canonicalize_existing_ancestor(candidate).ok_or_else(|| {
623            PathJailError::NoExistingAncestor {
624                path: candidate.to_path_buf(),
625            }
626        })?;
627
628        let allowed = path_allowed_by_jail(&base, &root, &allow);
629
630        if !allowed {
631            let is_suspicious = crate::tools::startup::is_suspicious_root(&root);
632            let mut hint = if is_suspicious || root == std::path::Path::new("/") {
633                ". lean-ctx has not bound this session to a project yet (the host reported \
634                     no project directory). Any path inside a project binds it; if it \
635                     persists: lean-ctx doctor --fix"
636                    .to_string()
637            } else {
638                super::pathjail_scope::escape_hint(candidate, &base, &root)
639            };
640            // An untrusted workspace's project-local `allow_paths` is silently
641            // withheld; always surface that reason (the stderr warning is
642            // invisible over MCP, and the hint above is meta-gated off) (#540).
643            if let Some(notice) = crate::core::workspace_trust::untrusted_override_notice() {
644                hint.push_str(". ");
645                hint.push_str(&notice);
646            }
647            // The global config the runtime reads doesn't exist → on defaults, so
648            // an `allow_paths` edit made to a config.toml elsewhere (XDG vs legacy
649            // dir, or a sandboxed/container HOME) is never seen (#540).
650            if let Some(missing) = crate::core::config::Config::missing_config_path() {
651                hint.push_str(&format!(
652                    ". ⚠ lean-ctx reads no config file at {} (running on defaults) — an \
653                     allow_paths edit in a config.toml elsewhere is not read; \
654                     `lean-ctx doctor` shows the path in effect",
655                    missing.display()
656                ));
657            }
658            if let Some(cache_hint) = detected_cache_hint(candidate) {
659                hint.push_str(&cache_hint);
660            }
661            return Err(PathJailError::EscapesRoot {
662                path: candidate.to_path_buf(),
663                root,
664                hint,
665            });
666        }
667
668        #[cfg(windows)]
669        reject_symlink_on_windows(candidate)?;
670
671        let mut out = base;
672        for part in remainder.iter().rev() {
673            out.push(part);
674        }
675
676        // Re-validate after reconstruction: if the final path exists, canonicalize
677        // and re-check to close TOCTOU window (symlink created between check and use).
678        if out.exists() {
679            let final_canon = canonicalize_secure(&out);
680            let final_ok = path_allowed_by_jail(&final_canon, &root, &allow);
681            if !final_ok {
682                return Err(PathJailError::PostCanonicalizeEscape {
683                    path: candidate.to_path_buf(),
684                    resolved: final_canon,
685                });
686            }
687        }
688
689        crate::cli::enforce_protected_store_path(&out)
690            .map_err(|reason| PathJailError::ProtectedContext { reason })?;
691        Ok(out)
692    }
693}
694
695#[cfg(all(test, target_os = "macos"))]
696mod protected_store_tests {
697    use super::*;
698
699    #[test]
700    fn runtime_store_is_not_reopened_by_implicit_or_explicit_roots() {
701        let isolated = crate::core::data_dir::isolated_data_dir();
702        let project = tempfile::tempdir().unwrap();
703        let store = isolated.path().join("knowledge");
704        std::fs::create_dir_all(&store).unwrap();
705        let fact = store.join("facts.json");
706        std::fs::write(&fact, "private stored context").unwrap();
707        let code = project.path().join("main.rs");
708        std::fs::write(&code, "fn main() {}\n").unwrap();
709        assert!(
710            jail_path(&fact, project.path()).is_ok(),
711            "Community keeps its existing runtime access"
712        );
713        let _protected = crate::cli::pin_synthetic_session(isolated.path()).unwrap();
714        let roots = vec![isolated.path().to_string_lossy().into_owned()];
715        for candidate in [&fact, &store, &isolated.path().to_path_buf()] {
716            assert!(
717                matches!(
718                    jail_path_with_roots(candidate, project.path(), &roots),
719                    Err(PathJailError::ProtectedContext { .. })
720                ),
721                "{candidate:?}"
722            );
723        }
724        assert!(jail_path(&code, project.path()).is_ok());
725        assert!(jail_path_with_roots(Path::new("facts.json"), &store, &roots).is_err());
726        // Raw backup paths enter the shared atomic writer without the dispatch
727        // resolver; they must not overwrite a hidden record or create a sibling.
728        for target in [&fact, &store.join("new/backup.json")] {
729            assert!(
730                crate::tools::edit_io::write_atomic_bytes_with_permissions(
731                    target,
732                    b"forged local context",
733                    None,
734                )
735                .is_err()
736            );
737        }
738        assert_eq!(
739            std::fs::read_to_string(&fact).unwrap(),
740            "private stored context"
741        );
742        assert!(!store.join("new").exists());
743        crate::tools::edit_io::write_atomic_bytes_with_permissions(&code, b"fn main() {}\n", None)
744            .unwrap();
745        // Internal storage is unaffected by the model-directed path resolver.
746        std::fs::write(&fact, "retained internal update").unwrap();
747        assert_eq!(
748            std::fs::read_to_string(&fact).unwrap(),
749            "retained internal update"
750        );
751    }
752
753    #[test]
754    fn missing_child_profile_never_falls_back_to_the_normal_jail() {
755        let isolated = crate::core::data_dir::isolated_data_dir();
756        let project = tempfile::tempdir().unwrap();
757        let code = project.path().join("main.rs");
758        std::fs::write(&code, "fn main() {}\n").unwrap();
759        let _protected = crate::cli::pin_synthetic_session(isolated.path()).unwrap();
760        crate::test_env::remove_var(crate::cli::CHILD_PROFILE_ENV);
761        assert!(matches!(
762            jail_path(&code, project.path()),
763            Err(PathJailError::ProtectedContext { .. })
764        ));
765    }
766}
767
768#[cfg(windows)]
769fn is_under_prefix_windows(path: &Path, prefix: &Path) -> bool {
770    let path_str = normalize_windows_path(&path.to_string_lossy());
771    let prefix_str = normalize_windows_path(&prefix.to_string_lossy());
772    let prefix_str = prefix_str.trim_end_matches('\\');
773    // Component boundary: `c:\proj` must not admit `c:\proj-evil\x`.
774    path_str == prefix_str
775        || path_str
776            .strip_prefix(prefix_str)
777            .is_some_and(|rest| rest.starts_with('\\'))
778}
779
780#[cfg(windows)]
781fn normalize_windows_path(s: &str) -> String {
782    let stripped = super::pathutil::strip_verbatim_str(s).unwrap_or_else(|| s.to_string());
783    stripped.to_lowercase().replace('/', "\\")
784}
785
786#[cfg(windows)]
787fn reject_symlink_on_windows(path: &Path) -> Result<(), PathJailError> {
788    if let Ok(meta) = std::fs::symlink_metadata(path) {
789        // Junctions and other reparse points redirect like symlinks but are
790        // invisible to `is_symlink()` — reject them too (GL#442).
791        if super::pathutil::is_symlink_or_reparse(&meta) {
792            return Err(PathJailError::Symlink {
793                path: path.to_path_buf(),
794            });
795        }
796    }
797    Ok(())
798}
799
800#[cfg(all(test, windows))]
801#[path = "pathjail_windows_tests.rs"]
802mod windows_prefix_tests;
803
804#[cfg(test)]
805#[path = "pathjail_tests.rs"]
806mod tests;