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    // Env entries are expanded too: MCP host configs pass env blocks verbatim
81    // (no shell), so "$HOME/code" arrives literally there as well.
82    let v = std::env::var("LCTX_ALLOW_PATH")
83        .or_else(|_| std::env::var("LEAN_CTX_ALLOW_PATH"))
84        .unwrap_or_default();
85    if !v.trim().is_empty() {
86        for p in std::env::split_paths(&v) {
87            out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
88        }
89    }
90
91    let extra = std::env::var("LEAN_CTX_EXTRA_ROOTS").unwrap_or_default();
92    if !extra.trim().is_empty() {
93        for p in std::env::split_paths(&extra) {
94            out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
95        }
96    }
97
98    // Read-only roots are *readable* (the whole point is read access to sibling
99    // repos); writes into them are denied separately by `enforce_writable`
100    // (#475). Add them to the read allow-list so reads resolve, exactly like
101    // `extra_roots`, without granting write access.
102    out.extend(canonicalized_roots(
103        &cfg.read_only_roots,
104        "LEAN_CTX_READ_ONLY_ROOTS",
105    ));
106
107    out
108}
109
110/// Canonicalize a set of config-supplied root entries plus an env override
111/// (path-list separated), expanding `~`/`$VAR` first. Shared by the read
112/// allow-list and the read-only-roots collector so both tiers parse roots
113/// identically.
114fn canonicalized_roots(config_entries: &[String], env_var: &str) -> Vec<PathBuf> {
115    let mut out = Vec::new();
116    for p in config_entries {
117        out.push(canonicalize_secure(&expand_user_path(p)));
118    }
119    let v = std::env::var(env_var).unwrap_or_default();
120    if !v.trim().is_empty() {
121        for p in std::env::split_paths(&v) {
122            out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
123        }
124    }
125    out
126}
127
128/// A read-only root is a sibling subtree the agent may **read** but never
129/// **write** — e.g. a reference repo mounted next to the project. Empty by
130/// default, so [`is_read_only_path`]/[`enforce_writable`] are zero-cost no-ops
131/// for everyone who hasn't opted in (#475).
132pub fn read_only_roots_from_env_and_config() -> Vec<PathBuf> {
133    let cfg = crate::core::config::Config::load();
134    canonicalized_roots(&cfg.read_only_roots, "LEAN_CTX_READ_ONLY_ROOTS")
135}
136
137/// A single active relaxation of the path jail. Each one widens or disables what
138/// tools can reach beyond the project root, so it is surfaced loudly (GH security
139/// audit, finding 3): the MCP/HTTP server inherits its process env from the
140/// IDE/launchd, so a globally-set `LEAN_CTX_ALLOW_PATH` / `LEAN_CTX_EXTRA_ROOTS`
141/// / `LEAN_CTX_ALLOW_IDE_DIRS` (or `path_jail = false`) silently loosens the
142/// boundary with no in-band signal otherwise.
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub struct JailRelaxation {
145    /// The knob that activated it (env var name, config key, or build feature).
146    pub source: &'static str,
147    /// Human-readable effect of the relaxation.
148    pub detail: &'static str,
149}
150
151fn env_is_set(var: &str) -> bool {
152    std::env::var(var).is_ok_and(|v| !v.trim().is_empty())
153}
154
155/// Collect every currently-active path-jail relaxation. An empty result means
156/// the jail is fully in force. This is the single source of truth shared by the
157/// startup warning ([`warn_if_relaxed`]) and `lean-ctx doctor`.
158#[must_use]
159pub fn active_relaxations() -> Vec<JailRelaxation> {
160    let mut out = Vec::new();
161
162    if cfg!(feature = "no-jail") {
163        out.push(JailRelaxation {
164            source: "no-jail (build feature)",
165            detail: "path jail compiled out — every tool path is allowed",
166        });
167    }
168
169    if crate::core::config::Config::load().path_jail == Some(false) {
170        out.push(JailRelaxation {
171            source: "path_jail = false (config.toml)",
172            detail: "path jail disabled — every tool path is allowed",
173        });
174    }
175
176    if env_is_set("LEAN_CTX_ALLOW_PATH") || env_is_set("LCTX_ALLOW_PATH") {
177        out.push(JailRelaxation {
178            source: "LEAN_CTX_ALLOW_PATH",
179            detail: "widens the read/write allow-list beyond the project root",
180        });
181    }
182
183    if env_is_set("LEAN_CTX_EXTRA_ROOTS") {
184        out.push(JailRelaxation {
185            source: "LEAN_CTX_EXTRA_ROOTS",
186            detail: "adds extra accessible roots beyond the project root",
187        });
188    }
189
190    let ide_env = std::env::var("LEAN_CTX_ALLOW_IDE_DIRS").is_ok_and(|v| v == "1");
191    if ide_env
192        || crate::core::config::Config::load()
193            .allow_ide_config_dirs
194            .unwrap_or(false)
195    {
196        out.push(JailRelaxation {
197            source: if ide_env {
198                "LEAN_CTX_ALLOW_IDE_DIRS=1"
199            } else {
200                "allow_ide_config_dirs = true (config.toml)"
201            },
202            detail: "exposes ~/.cursor, ~/.claude, … (other agents' sessions/credentials) to tools",
203        });
204    }
205
206    out
207}
208
209/// Emit a loud `tracing::warn!` for every active path-jail relaxation. Called
210/// once at MCP/HTTP server startup so a trusted-but-loosening env/config leaves
211/// an in-band audit signal instead of silently defeating the jail (finding 3).
212pub fn warn_if_relaxed() {
213    for relaxation in active_relaxations() {
214        tracing::warn!(
215            "[SECURITY] path jail relaxed via {}: {} — intended for trusted local use only",
216            relaxation.source,
217            relaxation.detail
218        );
219    }
220}
221
222/// True when `candidate` resolves to a location inside a configured read-only
223/// root. The candidate's nearest existing ancestor is canonicalized (so a
224/// not-yet-existing file inherits the read-only status of the directory it
225/// would be created in — closing the "create a new file in a read-only repo"
226/// hole) and matched against the (symlink-resolved) read-only roots.
227///
228/// A `false` return is only authoritative when the roots list is empty or the
229/// path provably sits outside every root; an unresolvable candidate (no
230/// existing ancestor) is treated as *not* read-only here and is rejected later
231/// by the ordinary write/jail error, never silently written.
232pub fn is_read_only_path(candidate: &Path) -> bool {
233    let roots = read_only_roots_from_env_and_config();
234    if roots.is_empty() {
235        return false;
236    }
237
238    // Compare the canonicalized nearest-existing-ancestor (resolves symlinks so
239    // a symlink *into* a read-only root can't launder a write past the prefix
240    // check), reconstructing the full path for the comparison.
241    let base = match canonicalize_existing_ancestor(candidate) {
242        Some((base, remainder)) => {
243            let mut p = base;
244            for part in remainder.iter().rev() {
245                p.push(part);
246            }
247            p
248        }
249        None => canonicalize_or_self(candidate),
250    };
251
252    roots.iter().any(|r| is_under_prefix(&base, r))
253}
254
255/// Default-deny write guard for the read-only tier (#475): returns an error if
256/// `candidate` is inside a configured read-only root, `Ok(())` otherwise.
257///
258/// This is the single read-only-aware choke point. Every filesystem write that
259/// can target a caller-supplied path routes through it (the atomic writers in
260/// `ctx_edit`/`edit_apply`, the handoff/session export bundle writers, the
261/// in-place memory-compaction writer, and the refactor IDE pre-write gate), so
262/// a "read-only" root cannot be written through any tool. Reads are unaffected.
263pub fn enforce_writable(candidate: &Path) -> Result<(), String> {
264    if is_read_only_path(candidate) {
265        return Err(format!(
266            "path is inside a read-only root — writes are denied (read_only_roots): {}",
267            candidate.display()
268        ));
269    }
270    Ok(())
271}
272
273/// Foreign editor config dirs for the jail (~/.cursor, ~/.claude, VS Code, …).
274///
275/// These expose other projects' sessions, MCP configs and credentials to any
276/// agent, so they are opt-in only (config `allow_ide_config_dirs = true` or
277/// `LEAN_CTX_ALLOW_IDE_DIRS=1`). lean-ctx's *own* state dir is intentionally NOT
278/// handled here: the caller already adds it via the sanctioned `data_dir`
279/// resolver (the legacy `~/.lean-ctx` is just one resolution of it). Keeping this
280/// a pure foreign-editor list means no legacy `~/.lean-ctx` literal is built in
281/// this module, so the legacy-path firewall (tests/legacy_path_firewall) has
282/// nothing to flag.
283fn home_allow_dirs(home: &Path, ide_dirs_allowed: bool) -> Vec<PathBuf> {
284    let mut out = Vec::new();
285    if ide_dirs_allowed {
286        let targets = crate::core::editor_registry::build_targets(home);
287        collect_ide_allow_dirs(home, &targets, &mut out);
288    }
289    out
290}
291
292/// Collect the in-home config/detect directories of every supported editor.
293///
294/// Derived from the editor registry (the single source of truth) so it covers
295/// non-dotfile layouts too — VS Code's `Library/Application Support/Code/User`,
296/// Cline/Roo globalStorage, JetBrains — and never drifts as editors are added.
297/// A config file that sits directly in `$HOME` (`~/.claude.json`,
298/// `~/.jb-mcp.json`) resolves its parent to `$HOME`; those entries are skipped
299/// so the jail is never widened to the entire home directory.
300fn collect_ide_allow_dirs(
301    home: &Path,
302    targets: &[crate::core::editor_registry::EditorTarget],
303    out: &mut Vec<PathBuf>,
304) {
305    let mut seen: std::collections::HashSet<PathBuf> = out.iter().cloned().collect();
306    for target in targets {
307        let candidates = [
308            target.config_path.parent().map(Path::to_path_buf),
309            Some(target.detect_path.clone()),
310        ];
311        for cand in candidates.into_iter().flatten() {
312            if cand.as_path() == home || !cand.starts_with(home) || !cand.is_dir() {
313                continue;
314            }
315            let resolved = canonicalize_secure(&cand);
316            if seen.insert(resolved.clone()) {
317                out.push(resolved);
318            }
319        }
320    }
321}
322
323fn is_under_prefix(path: &Path, prefix: &Path) -> bool {
324    path.starts_with(prefix)
325}
326
327/// Heuristic canonicalize — honours the #356 TCC guard. Used by the
328/// jail-disabled bypass and by external callers (session/startup/server roots)
329/// that must not pop a privacy prompt on their own initiative.
330pub fn canonicalize_or_self(path: &Path) -> PathBuf {
331    super::pathutil::safe_canonicalize_bounded(path, 2000)
332}
333
334/// SECURITY canonicalize for the jail boundary itself (roots + candidate +
335/// escape re-check). Deliberately bypasses the #356 TCC guard: the jail must
336/// keep resolving symlinks to detect escapes, and it only ever runs on a path
337/// the client explicitly asked to access, where a one-time prompt is legitimate.
338fn canonicalize_secure(path: &Path) -> PathBuf {
339    super::pathutil::canonicalize_secure_bounded(path, 2000)
340}
341
342fn canonicalize_existing_ancestor(path: &Path) -> Option<(PathBuf, Vec<std::ffi::OsString>)> {
343    let mut cur = path.to_path_buf();
344    let mut remainder: Vec<std::ffi::OsString> = Vec::new();
345    loop {
346        if cur.exists() {
347            return Some((canonicalize_secure(&cur), remainder));
348        }
349        let name = cur.file_name()?.to_os_string();
350        remainder.push(name);
351        if !cur.pop() {
352            return None;
353        }
354    }
355}
356
357pub fn jail_path(candidate: &Path, jail_root: &Path) -> Result<PathBuf, PathJailError> {
358    jail_path_with_roots(candidate, jail_root, &[])
359}
360
361/// Like [`jail_path`], but also accepts paths under any of `extra_roots`.
362///
363/// `extra_roots` are session-scoped trusted roots (MCP `roots/list` and config
364/// `extra_roots`, surfaced via `session.extra_roots`) — e.g. sibling git
365/// worktrees the agent legitimately spans. They widen the allow-list for *this
366/// call only*, so an explicit `path` under a worktree resolves instead of
367/// failing with "path escapes project root", without loosening the global jail
368/// (#403). `path_jail = false` still bypasses entirely and an empty slice is
369/// byte-for-byte identical to the old single-root behaviour.
370pub fn jail_path_with_roots(
371    candidate: &Path,
372    jail_root: &Path,
373    extra_roots: &[String],
374) -> Result<PathBuf, PathJailError> {
375    if candidate.to_string_lossy().as_bytes().contains(&0) {
376        return Err(PathJailError::NullByte);
377    }
378
379    #[cfg(feature = "no-jail")]
380    {
381        let _ = (jail_root, extra_roots);
382        return Ok(canonicalize_or_self(candidate));
383    }
384
385    #[allow(unreachable_code)]
386    {
387        let cfg = crate::core::config::Config::load();
388        if cfg.path_jail == Some(false) {
389            return Ok(canonicalize_or_self(candidate));
390        }
391
392        let root = canonicalize_secure(jail_root);
393
394        // Resolve relative candidates against the (absolute) jail root — never the process
395        // CWD. The daemon's CWD is not the project, so CWD-relative resolution made
396        // graph-relative paths (e.g. auto-preload candidates like `rust/src/core/foo.rs`)
397        // spuriously fail with "no existing ancestor". Absolute candidates are unchanged.
398        let resolved: PathBuf;
399        let candidate: &Path = if candidate.is_absolute() {
400            candidate
401        } else {
402            resolved = root.join(candidate);
403            resolved.as_path()
404        };
405
406        let mut allow = allow_paths_from_env_and_config();
407        // Session-scoped roots widen the allow-list for this call only.
408        allow.extend(
409            extra_roots
410                .iter()
411                .filter(|r| !r.is_empty())
412                .map(|r| canonicalize_secure(Path::new(r))),
413        );
414
415        let (base, remainder) = canonicalize_existing_ancestor(candidate).ok_or_else(|| {
416            PathJailError::NoExistingAncestor {
417                path: candidate.to_path_buf(),
418            }
419        })?;
420
421        let allowed =
422            is_under_prefix(&base, &root) || allow.iter().any(|p| is_under_prefix(&base, p));
423
424        #[cfg(windows)]
425        let allowed = allowed || is_under_prefix_windows(&base, &root);
426
427        if !allowed {
428            let mut hint = if crate::core::protocol::meta_visible() {
429                let dir = candidate.parent().unwrap_or(candidate).display();
430                format!(
431                    ". Hint: set LEAN_CTX_READ_ONLY_ROOTS={dir} for read-only access, \
432                     or LEAN_CTX_ALLOW_PATH={dir} for read-write access, \
433                     or add entries to read_only_roots/allow_paths in ~/.config/lean-ctx/config.toml"
434                )
435            } else {
436                String::new()
437            };
438            // An untrusted workspace's project-local `allow_paths` is silently
439            // withheld; always surface that reason (the stderr warning is
440            // invisible over MCP, and the hint above is meta-gated off) (#540).
441            if let Some(notice) = crate::core::workspace_trust::untrusted_override_notice() {
442                hint.push_str(". ");
443                hint.push_str(&notice);
444            }
445            // The global config the runtime reads doesn't exist → on defaults, so
446            // an `allow_paths` edit made to a config.toml elsewhere (XDG vs legacy
447            // dir, or a sandboxed/container HOME) is never seen (#540).
448            if let Some(missing) = crate::core::config::Config::missing_config_path() {
449                hint.push_str(&format!(
450                    ". ⚠ lean-ctx reads no config file at {} (running on defaults) — an \
451                     allow_paths edit in a config.toml elsewhere is not read; \
452                     `lean-ctx doctor` shows the path in effect",
453                    missing.display()
454                ));
455            }
456            return Err(PathJailError::EscapesRoot {
457                path: candidate.to_path_buf(),
458                root,
459                hint,
460            });
461        }
462
463        #[cfg(windows)]
464        reject_symlink_on_windows(candidate)?;
465
466        let mut out = base;
467        for part in remainder.iter().rev() {
468            out.push(part);
469        }
470
471        // Re-validate after reconstruction: if the final path exists, canonicalize
472        // and re-check to close TOCTOU window (symlink created between check and use).
473        if out.exists() {
474            let final_canon = canonicalize_secure(&out);
475            let final_ok = is_under_prefix(&final_canon, &root)
476                || allow.iter().any(|p| is_under_prefix(&final_canon, p));
477            #[cfg(windows)]
478            let final_ok = final_ok || is_under_prefix_windows(&final_canon, &root);
479            if !final_ok {
480                return Err(PathJailError::PostCanonicalizeEscape {
481                    path: candidate.to_path_buf(),
482                    resolved: final_canon,
483                });
484            }
485        }
486
487        Ok(out)
488    }
489}
490
491#[cfg(windows)]
492fn is_under_prefix_windows(path: &Path, prefix: &Path) -> bool {
493    let path_str = normalize_windows_path(&path.to_string_lossy());
494    let prefix_str = normalize_windows_path(&prefix.to_string_lossy());
495    path_str.starts_with(&prefix_str)
496}
497
498#[cfg(windows)]
499fn normalize_windows_path(s: &str) -> String {
500    let stripped = super::pathutil::strip_verbatim_str(s).unwrap_or_else(|| s.to_string());
501    stripped.to_lowercase().replace('/', "\\")
502}
503
504#[cfg(windows)]
505fn reject_symlink_on_windows(path: &Path) -> Result<(), PathJailError> {
506    if let Ok(meta) = std::fs::symlink_metadata(path) {
507        // Junctions and other reparse points redirect like symlinks but are
508        // invisible to `is_symlink()` — reject them too (GL#442).
509        if super::pathutil::is_symlink_or_reparse(&meta) {
510            return Err(PathJailError::Symlink {
511                path: path.to_path_buf(),
512            });
513        }
514    }
515    Ok(())
516}
517
518#[cfg(test)]
519mod tests {
520    use super::*;
521
522    #[cfg(not(feature = "no-jail"))]
523    #[test]
524    fn rejects_path_outside_root() {
525        // Hermetic config (empty data dir => jail on) so a parallel test that
526        // flips `path_jail` cannot leak into this enforcement check. The guard
527        // holds the global test_env_lock, which also serializes against every
528        // `LEAN_CTX_ALLOW_PATH` mutation (all of them go through that lock).
529        let _iso = crate::core::data_dir::isolated_data_dir();
530        let tmp = tempfile::tempdir().unwrap();
531        let root = tmp.path().join("root");
532        let other = tmp.path().join("other");
533        std::fs::create_dir_all(&root).unwrap();
534        std::fs::create_dir_all(&other).unwrap();
535        std::fs::write(root.join("a.txt"), "ok").unwrap();
536        std::fs::write(other.join("b.txt"), "no").unwrap();
537
538        let ok = jail_path(&root.join("a.txt"), &root);
539        assert!(ok.is_ok());
540
541        let bad = jail_path(&other.join("b.txt"), &root);
542        assert!(bad.is_err());
543    }
544
545    /// #475: a configured read-only root is readable but never writable. Reads
546    /// resolve (the root joins the allow-list like an extra_root), while the
547    /// single write choke point `enforce_writable` default-denies every write
548    /// inside it — including a not-yet-existing file, which inherits the
549    /// directory's read-only status. `isolated_data_dir` holds `test_env_lock`,
550    /// serialising the `LEAN_CTX_READ_ONLY_ROOTS` mutation against other tests.
551    #[cfg(not(feature = "no-jail"))]
552    #[test]
553    fn read_only_roots_deny_writes_but_allow_reads() {
554        let _iso = crate::core::data_dir::isolated_data_dir();
555
556        let tmp = tempfile::tempdir().unwrap();
557        let project = tmp.path().join("project");
558        let refrepo = tmp.path().join("refrepo");
559        std::fs::create_dir_all(&project).unwrap();
560        std::fs::create_dir_all(refrepo.join("sub")).unwrap();
561        std::fs::write(refrepo.join("lib.rs"), "pub fn x() {}\n").unwrap();
562
563        // Canonicalize the configured root the same (symlink-resolving) way the
564        // guard does, so macOS /var → /private/var can't defeat the prefix match.
565        let ro_canon = canonicalize_secure(&refrepo);
566        crate::test_env::set_var(
567            "LEAN_CTX_READ_ONLY_ROOTS",
568            ro_canon.to_string_lossy().as_ref(),
569        );
570
571        let existing = refrepo.join("lib.rs");
572        let new_file = refrepo.join("sub").join("new.rs");
573        let proj_file = project.join("main.rs");
574
575        // Capture every decision while the env is live (it is cleared below).
576        let read_existing = jail_path(&existing, &project);
577        let deny_existing = enforce_writable(&existing);
578        let deny_new = enforce_writable(&new_file);
579        let allow_project = enforce_writable(&proj_file);
580        let ro_existing = is_read_only_path(&existing);
581        let ro_project = is_read_only_path(&proj_file);
582
583        crate::test_env::remove_var("LEAN_CTX_READ_ONLY_ROOTS");
584
585        assert!(
586            deny_existing.is_err(),
587            "write to an existing file in a read-only root must be denied"
588        );
589        assert!(
590            deny_new.is_err(),
591            "creating a new file in a read-only root must be denied"
592        );
593        assert!(
594            allow_project.is_ok(),
595            "writes into the project root must stay allowed: {allow_project:?}"
596        );
597        assert!(
598            read_existing.is_ok(),
599            "reads inside a read-only root must resolve (read allow-list): {read_existing:?}"
600        );
601        assert!(ro_existing, "the file is inside the read-only root");
602        assert!(!ro_project, "the project file is not read-only");
603    }
604
605    /// #406 regression: a long-lived process (the MCP server) must honor
606    /// `path_jail = false` written to config after startup. The config cache is
607    /// now keyed on content, so even an edit that preserves the file mtime takes
608    /// effect — a path outside the jail root is accepted once the flag flips.
609    /// (With the former mtime-only cache the stale `None` kept the jail on.)
610    #[cfg(not(feature = "no-jail"))]
611    #[test]
612    fn honors_path_jail_false_after_mtime_preserving_edit() {
613        let _iso = crate::core::data_dir::isolated_data_dir();
614        let cfg_path = crate::core::config::Config::path().unwrap();
615        if let Some(parent) = cfg_path.parent() {
616            std::fs::create_dir_all(parent).unwrap();
617        }
618
619        let tmp = tempfile::tempdir().unwrap();
620        let root = tmp.path().join("project");
621        let outside = tmp.path().join("outside");
622        std::fs::create_dir_all(&root).unwrap();
623        std::fs::create_dir_all(&outside).unwrap();
624        let secret = outside.join("secret.txt");
625        std::fs::write(&secret, "x").unwrap();
626
627        // Warm the config cache with the jail on (no path_jail key).
628        std::fs::write(&cfg_path, "# jail on\n").unwrap();
629        let mtime0 = std::fs::metadata(&cfg_path).unwrap().modified().unwrap();
630        assert_eq!(crate::core::config::Config::load().path_jail, None);
631
632        // Flip path_jail=false but restore the original mtime, so any mtime-only
633        // cache would keep serving the stale jail-on value.
634        std::fs::write(&cfg_path, "path_jail = false\n").unwrap();
635        filetime::set_file_mtime(&cfg_path, filetime::FileTime::from_system_time(mtime0)).unwrap();
636
637        assert!(
638            jail_path(&secret, &root).is_ok(),
639            "path_jail=false must take effect without a fresh process (#406)"
640        );
641    }
642
643    #[test]
644    fn allows_nonexistent_child_under_root() {
645        let tmp = tempfile::tempdir().unwrap();
646        let root = tmp.path().join("root");
647        std::fs::create_dir_all(&root).unwrap();
648        std::fs::write(root.join("a.txt"), "ok").unwrap();
649
650        let p = root.join("new").join("file.txt");
651        let ok = jail_path(&p, &root).unwrap();
652        assert!(ok.to_string_lossy().contains("file.txt"));
653    }
654
655    #[cfg(not(feature = "no-jail"))]
656    #[test]
657    fn relative_candidate_resolves_against_root_not_cwd() {
658        // Regression: in the daemon (CWD != project) a relative graph path like
659        // `sub/file.rs` must resolve under the jail root, not the process CWD.
660        let _iso = crate::core::data_dir::isolated_data_dir();
661        let tmp = tempfile::tempdir().unwrap();
662        let root = tmp.path().join("project");
663        std::fs::create_dir_all(root.join("sub")).unwrap();
664        std::fs::write(root.join("sub").join("file.rs"), "ok").unwrap();
665
666        let jailed = jail_path(Path::new("sub/file.rs"), &root)
667            .expect("relative candidate should resolve under the jail root");
668        assert!(jailed.ends_with("sub/file.rs"));
669        assert!(
670            is_under_prefix(&canonicalize_or_self(&jailed), &canonicalize_or_self(&root)),
671            "resolved path must live under the jail root: {jailed:?}"
672        );
673    }
674
675    #[test]
676    fn ide_allow_dirs_are_registry_derived_and_skip_home() {
677        use crate::core::editor_registry::{ConfigType, EditorTarget};
678
679        let home = tempfile::tempdir().unwrap();
680        let h = home.path();
681        // VS Code keeps its config outside a dotfile dir — the old hard-coded
682        // list missed this entirely.
683        std::fs::create_dir_all(h.join("Library/Application Support/Code/User")).unwrap();
684        std::fs::create_dir_all(h.join(".cursor")).unwrap();
685
686        let targets = vec![
687            EditorTarget {
688                name: "VS Code",
689                agent_key: "vscode".into(),
690                config_path: h.join("Library/Application Support/Code/User/mcp.json"),
691                detect_path: h.join("Library/Application Support/Code"),
692                config_type: ConfigType::VsCodeMcp,
693            },
694            EditorTarget {
695                name: "Cursor",
696                agent_key: "cursor".into(),
697                config_path: h.join(".cursor/mcp.json"),
698                detect_path: h.join(".cursor"),
699                config_type: ConfigType::McpJson,
700            },
701            // A $HOME-level config file: its parent is $HOME and must be skipped.
702            EditorTarget {
703                name: "Claude Code",
704                agent_key: "claude".into(),
705                config_path: h.join(".claude.json"),
706                detect_path: h.join(".no-such-dir"),
707                config_type: ConfigType::McpJson,
708            },
709        ];
710
711        let mut out = Vec::new();
712        collect_ide_allow_dirs(h, &targets, &mut out);
713
714        assert!(
715            out.iter().any(|p| p.ends_with("Code/User")),
716            "non-dotfile VS Code dir must be covered: {out:?}"
717        );
718        assert!(out.iter().any(|p| p.ends_with(".cursor")), "{out:?}");
719        let home_canon = canonicalize_secure(h);
720        assert!(
721            !out.contains(&home_canon),
722            "must never widen the jail to $HOME: {out:?}"
723        );
724    }
725
726    // P0-10 (#422): foreign editor config dirs are opt-in. lean-ctx's own state
727    // dir is added by the caller via the data_dir root, NOT by `home_allow_dirs`,
728    // so the default home allow-list is empty and `~/.lean-ctx` (not an editor)
729    // never appears here.
730    #[test]
731    fn ide_config_dirs_are_excluded_by_default() {
732        let home = tempfile::tempdir().unwrap();
733        for d in [".lean-ctx", ".cursor", ".codex"] {
734            std::fs::create_dir_all(home.path().join(d)).unwrap();
735        }
736
737        let denied = home_allow_dirs(home.path(), false);
738        assert!(
739            denied.is_empty(),
740            "foreign editor dirs must stay jailed by default: {denied:?}"
741        );
742
743        // Opt-in exposes the editor dirs that actually exist under this home.
744        // Entries are registry-derived (foreign real-$HOME paths are filtered out
745        // by the in-home guard), so the result stays hermetic — and `~/.lean-ctx`
746        // is never added here because it is not an editor.
747        let allowed = home_allow_dirs(home.path(), true);
748        assert!(
749            allowed.iter().any(|p| p.ends_with(".cursor")),
750            "opt-in must expose editor dirs: {allowed:?}"
751        );
752        assert!(
753            !allowed.iter().any(|p| p.ends_with(".lean-ctx")),
754            "lean-ctx's own dir is covered by the data_dir root, not home_allow_dirs: {allowed:?}"
755        );
756    }
757
758    #[test]
759    fn canonicalize_or_self_strips_verbatim() {
760        let tmp = tempfile::tempdir().unwrap();
761        let dir = tmp.path().join("project");
762        std::fs::create_dir_all(&dir).unwrap();
763
764        let result = canonicalize_or_self(&dir);
765        let s = result.to_string_lossy();
766        assert!(
767            !s.starts_with(r"\\?\"),
768            "canonicalize_or_self should strip verbatim prefix, got: {s}"
769        );
770    }
771
772    #[test]
773    fn jail_path_accepts_same_dir_different_format() {
774        let tmp = tempfile::tempdir().unwrap();
775        let root = tmp.path().join("project");
776        std::fs::create_dir_all(&root).unwrap();
777        std::fs::write(root.join("file.rs"), "ok").unwrap();
778
779        let result = jail_path(&root.join("file.rs"), &root);
780        assert!(result.is_ok(), "same dir should be accepted: {result:?}");
781    }
782
783    #[cfg(not(feature = "no-jail"))]
784    #[test]
785    fn error_message_contains_escape_info() {
786        // isolated_data_dir holds the global test_env_lock, serializing this
787        // against any parallel `LEAN_CTX_ALLOW_PATH="/"` mutation.
788        let _iso = crate::core::data_dir::isolated_data_dir();
789        let tmp = tempfile::tempdir().unwrap();
790        let root = tmp.path().join("root");
791        let other = tmp.path().join("other");
792        std::fs::create_dir_all(&root).unwrap();
793        std::fs::create_dir_all(&other).unwrap();
794        std::fs::write(other.join("b.txt"), "no").unwrap();
795
796        let err = jail_path(&other.join("b.txt"), &root).unwrap_err();
797        assert!(
798            err.to_string().contains("path escapes project root"),
799            "error should mention escape: {err}"
800        );
801    }
802
803    // GH #392: config entries like "$HOME/code" or "~/code" were taken
804    // literally and never matched.
805    #[test]
806    fn expand_user_path_expands_tilde_and_vars() {
807        let home = dirs::home_dir().expect("home dir");
808        let home_s = home.to_string_lossy().to_string();
809
810        assert_eq!(expand_user_path("~"), home);
811        assert_eq!(expand_user_path("~/code"), home.join("code"));
812        assert_eq!(expand_user_path("$HOME/code"), home.join("code"));
813        assert_eq!(expand_user_path("${HOME}/code"), home.join("code"));
814        // Multiple variables in one entry.
815        crate::test_env::set_var("LEAN_CTX_TEST_SUB", "sub");
816        assert_eq!(
817            expand_user_path("$HOME/$LEAN_CTX_TEST_SUB/x"),
818            PathBuf::from(format!("{home_s}/sub/x"))
819        );
820        crate::test_env::remove_var("LEAN_CTX_TEST_SUB");
821        // Absolute paths pass through untouched.
822        assert_eq!(expand_user_path("/etc"), PathBuf::from("/etc"));
823    }
824
825    #[test]
826    fn expand_user_path_leaves_unset_vars_verbatim() {
827        crate::test_env::remove_var("LEAN_CTX_TEST_UNSET_VAR");
828        let p = expand_user_path("$LEAN_CTX_TEST_UNSET_VAR/code");
829        assert_eq!(p, PathBuf::from("$LEAN_CTX_TEST_UNSET_VAR/code"));
830    }
831
832    // GH #392: `allow_paths = ["/"]` (via the same env-var channel) must grant
833    // access to any absolute path — "/" is a prefix of everything.
834    //
835    // Env-mutating tests here hold the process-global
836    // `data_dir::test_env_lock()` (directly, or via `isolated_data_dir()`
837    // which wraps it) — NOT a module-local mutex. test_env's SAFETY contract
838    // says *all* test env mutation serializes through that one lock; a local
839    // lock only serializes this module against itself, so e.g.
840    // `artifacts::external_corpus_requires_allow_list` (which holds the
841    // global lock) could observe this test's `LEAN_CTX_ALLOW_PATH="/"` and
842    // fail its jail-rejection assert (the pre-existing parallel-run flake
843    // reported in #695).
844    #[cfg(unix)]
845    #[test]
846    fn allow_path_root_slash_permits_everything() {
847        let _guard = crate::core::data_dir::test_env_lock();
848        let tmp = tempfile::tempdir().unwrap();
849        let root = tmp.path().join("root");
850        let other = tmp.path().join("other");
851        std::fs::create_dir_all(&root).unwrap();
852        std::fs::create_dir_all(&other).unwrap();
853        std::fs::write(other.join("b.txt"), "allowed").unwrap();
854
855        crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", "/");
856        let result = jail_path(&other.join("b.txt"), &root);
857        crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
858
859        assert!(result.is_ok(), "allow path '/' must permit all: {result:?}");
860    }
861
862    // Finding 3 (GH security audit): env-channel jail relaxations must be
863    // detectable so startup + doctor can surface them loudly.
864    #[test]
865    fn active_relaxations_detects_allow_path_env() {
866        let _iso = crate::core::data_dir::isolated_data_dir();
867        crate::test_env::remove_var("LEAN_CTX_EXTRA_ROOTS");
868        crate::test_env::remove_var("LEAN_CTX_ALLOW_IDE_DIRS");
869        crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", "/tmp");
870
871        let relaxed = active_relaxations();
872
873        crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
874
875        assert!(
876            relaxed.iter().any(|r| r.source == "LEAN_CTX_ALLOW_PATH"),
877            "LEAN_CTX_ALLOW_PATH must be reported as a jail relaxation: {relaxed:?}"
878        );
879    }
880
881    #[cfg(not(feature = "no-jail"))]
882    #[test]
883    fn active_relaxations_empty_when_jail_intact() {
884        let _iso = crate::core::data_dir::isolated_data_dir();
885        for var in [
886            "LEAN_CTX_ALLOW_PATH",
887            "LCTX_ALLOW_PATH",
888            "LEAN_CTX_EXTRA_ROOTS",
889            "LEAN_CTX_ALLOW_IDE_DIRS",
890        ] {
891            crate::test_env::remove_var(var);
892        }
893
894        assert!(
895            active_relaxations().is_empty(),
896            "an intact jail (clean config, no relaxation env) must report no relaxations: {:?}",
897            active_relaxations()
898        );
899    }
900
901    #[test]
902    fn allow_path_env_permits_outside_root() {
903        let _guard = crate::core::data_dir::test_env_lock();
904        let tmp = tempfile::tempdir().unwrap();
905        let root = tmp.path().join("root");
906        let other = tmp.path().join("other");
907        std::fs::create_dir_all(&root).unwrap();
908        std::fs::create_dir_all(&other).unwrap();
909        std::fs::write(other.join("b.txt"), "allowed").unwrap();
910
911        let canon = canonicalize_or_self(&other);
912        crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", canon.to_string_lossy().as_ref());
913        let result = jail_path(&other.join("b.txt"), &root);
914        crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
915
916        assert!(
917            result.is_ok(),
918            "LEAN_CTX_ALLOW_PATH should permit access: {result:?}"
919        );
920    }
921
922    #[cfg(all(unix, not(feature = "no-jail")))]
923    #[test]
924    fn rejects_symlink_escape_on_unix() {
925        use std::os::unix::fs::symlink;
926
927        // isolated_data_dir holds the global test_env_lock — no parallel test
928        // can set `LEAN_CTX_ALLOW_PATH="/"` and let this escape resolve.
929        let _iso = crate::core::data_dir::isolated_data_dir();
930        let tmp = tempfile::tempdir().unwrap();
931        let root = tmp.path().join("root");
932        let other = tmp.path().join("other");
933        std::fs::create_dir_all(&root).unwrap();
934        std::fs::create_dir_all(&other).unwrap();
935        std::fs::write(other.join("secret.txt"), "no").unwrap();
936
937        let link = root.join("link.txt");
938        symlink(other.join("secret.txt"), &link).unwrap();
939
940        let bad = jail_path(&link, &root);
941        assert!(bad.is_err(), "symlink escape must be rejected: {bad:?}");
942    }
943
944    #[test]
945    fn rejects_null_byte_in_path() {
946        let tmp = tempfile::tempdir().unwrap();
947        let root = tmp.path().join("root");
948        std::fs::create_dir_all(&root).unwrap();
949
950        let bad_path = PathBuf::from("file\0.txt");
951        let result = jail_path(&bad_path, &root);
952        assert!(result.is_err(), "null byte in path must be rejected");
953        assert!(
954            result.unwrap_err().to_string().contains("null byte"),
955            "error must mention null byte"
956        );
957    }
958
959    /// #403 Bug 1: an explicit path under a session-scoped `extra_root` (e.g. a
960    /// sibling git worktree from MCP `roots/list`) must resolve, while the same
961    /// path is rejected without it — and a path under *no* root is rejected even
962    /// when extra roots are present. Holds both env locks so neither a parallel
963    /// `path_jail` flip nor a `LEAN_CTX_ALLOW_PATH` mutation can leak in.
964    #[cfg(not(feature = "no-jail"))]
965    #[test]
966    fn extra_roots_permit_paths_outside_jail() {
967        let _iso = crate::core::data_dir::isolated_data_dir();
968
969        let tmp = tempfile::tempdir().unwrap();
970        let root = tmp.path().join("project");
971        let worktree = tmp.path().join("worktree");
972        let elsewhere = tmp.path().join("elsewhere");
973        for d in [&root, &worktree, &elsewhere] {
974            std::fs::create_dir_all(d).unwrap();
975        }
976        let in_worktree = worktree.join("a.txt");
977        std::fs::write(&in_worktree, "x").unwrap();
978        let outside = elsewhere.join("b.txt");
979        std::fs::write(&outside, "y").unwrap();
980
981        // Parity: with no extra roots, the worktree path escapes the jail.
982        assert!(jail_path(&in_worktree, &root).is_err());
983        assert!(jail_path_with_roots(&in_worktree, &root, &[]).is_err());
984
985        // The session-scoped extra root permits it — via the slice alone, with
986        // nothing in env/config.
987        let extra = vec![worktree.to_string_lossy().to_string()];
988        assert!(
989            jail_path_with_roots(&in_worktree, &root, &extra).is_ok(),
990            "path under a session extra_root must resolve (#403)"
991        );
992
993        // A path under neither the jail nor any extra root is still rejected.
994        assert!(
995            jail_path_with_roots(&outside, &root, &extra).is_err(),
996            "paths outside ALL roots must still be rejected"
997        );
998
999        // Empty entries are ignored (no accidental allow-all).
1000        assert!(jail_path_with_roots(&outside, &root, &[String::new()]).is_err());
1001    }
1002}