Skip to main content

lean_ctx/core/
pathjail_scope.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Path-jail scope: which directories the jail treats as the user's own code.
3//!
4//! The jail used to admit only the session's project root (plus allow-lists).
5//! Anyone working on several repositories at once hit "path escapes project
6//! root" on every cross-project read, and the suggested fixes — one allow entry
7//! per directory, or env vars that need an MCP restart — did not scale.
8//!
9//! - `home` (**default**): every path inside a project below the user's home
10//!   directory is admitted for reading (a directory between it and `~` holds
11//!   `.git`, `Cargo.toml`, … — loose personal files are not), except the
12//!   protected zones where credentials and other
13//!   programs' private state live (every top-level dot entry such as `~/.ssh`,
14//!   `~/.aws`, `~/.config`, `~/.zshrc` or other agents' `~/.claude`, plus
15//!   `~/Library` on macOS, `~/AppData` and the `NTUSER.DAT*` registry hive on
16//!   Windows). Paths outside the home directory stay jailed.
17//! - `project`: the classic boundary — the project root plus allow-lists.
18//!
19//! Explicit allow-lists (`allow_paths`, `extra_roots`, `read_only_roots`) and
20//! lean-ctx's own state dir still widen either scope, so `lean-ctx allow-path
21//! ~/.config/foo` reopens one protected directory without dropping the zone.
22//! `path_jail = false` keeps disabling the jail entirely.
23//!
24//! Resolution precedence (first hit wins): `LEAN_CTX_PATH_JAIL_SCOPE` env →
25//! `path_jail_scope` in the global `config.toml` → `home`. Like `path_jail` it
26//! is global-only: a project-local `.lean-ctx.toml` is never merged for it.
27
28use std::path::{Path, PathBuf};
29
30/// Top-level home entries (besides every dot entry) holding other programs'
31/// private data: keychains, browser profiles, mail, app containers (Linux
32/// snaps keep each app's dot dirs — cookies, logins — under `~/snap/<app>`).
33const PROTECTED_HOME_DIRS: &[&str] = &["Library", "AppData", "snap"];
34
35/// Upper bound on remembered session roots; a long-lived daemon serving many
36/// sessions keeps the most recent ones.
37const MAX_SESSION_WRITE_ROOTS: usize = 64;
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
40pub enum PathJailScope {
41    /// Everything below `$HOME` except the protected zones.
42    #[default]
43    Home,
44    /// Only the project root plus the configured allow-lists.
45    Project,
46}
47
48impl PathJailScope {
49    /// Lenient parse; unknown text returns `None` so callers fall back to the default.
50    pub fn parse(value: &str) -> Option<Self> {
51        match value.trim().to_ascii_lowercase().as_str() {
52            "home" | "user" | "workspace" => Some(Self::Home),
53            "project" | "strict" | "root" => Some(Self::Project),
54            _ => None,
55        }
56    }
57
58    pub fn as_str(self) -> &'static str {
59        match self {
60            Self::Home => "home",
61            Self::Project => "project",
62        }
63    }
64
65    /// Active scope: env override → config → default (`home`).
66    pub fn resolve() -> Self {
67        if let Ok(raw) = std::env::var("LEAN_CTX_PATH_JAIL_SCOPE")
68            && let Some(scope) = Self::parse(&raw)
69        {
70            return scope;
71        }
72        crate::core::config::Config::load()
73            .path_jail_scope
74            .as_deref()
75            .and_then(Self::parse)
76            .unwrap_or_default()
77    }
78}
79
80/// Canonical home directory for the protected-zone checks; `None` when `$HOME`
81/// is the filesystem root.
82fn zone_home() -> Option<PathBuf> {
83    let home = super::pathjail::canonicalize_secure(&dirs::home_dir()?);
84    home.parent().is_some().then_some(home)
85}
86
87/// Home directory the `home` scope may open. `$HOME` is only an env var: in
88/// containers and CI it is often `/`, `/root` or `/tmp`, where "everything
89/// below home" would mean the whole system or other users' files. Require at
90/// least two normal components and, on Unix, ownership by this user;
91/// otherwise the jail falls back to the project boundary.
92fn scope_home() -> Option<PathBuf> {
93    let home = zone_home()?;
94    let depth = home
95        .components()
96        .filter(|c| matches!(c, std::path::Component::Normal(_)))
97        .count();
98    if depth < 2 {
99        return None;
100    }
101    #[cfg(unix)]
102    {
103        use std::os::unix::fs::MetadataExt;
104        // SAFETY: geteuid has no arguments or failure state.
105        if std::fs::metadata(&home).ok()?.uid() != unsafe { libc::geteuid() } {
106            return None;
107        }
108    }
109    Some(home)
110}
111
112/// The first path component below `home`, when `path` lies strictly inside it.
113fn first_component_below<'a>(path: &'a Path, home: &Path) -> Option<&'a std::ffi::OsStr> {
114    path.strip_prefix(home)
115        .ok()?
116        .components()
117        .next()
118        .map(std::path::Component::as_os_str)
119}
120
121/// The protected zone (e.g. `~/.ssh`) containing `path`, if any. `path` must
122/// already be canonical; `home` is the canonical home directory.
123fn protected_zone_in(path: &Path, home: &Path) -> Option<PathBuf> {
124    let first = first_component_below(path, home)?;
125    let name = first.to_string_lossy();
126    // Windows keeps the user's registry hive (`NTUSER.DAT*`) directly in home.
127    let protected = name.starts_with('.')
128        || name.to_ascii_lowercase().starts_with("ntuser.")
129        || PROTECTED_HOME_DIRS
130            .iter()
131            .any(|d| name.eq_ignore_ascii_case(d));
132    protected.then(|| home.join(first))
133}
134
135/// True when the `home` scope admits the canonical path `base`: it lies inside
136/// a project below the home directory and outside every protected zone.
137///
138/// "Inside a project" — some directory between `base` and `~` (not `~`
139/// itself) carries a project marker (`.git`, `Cargo.toml`, `package.json`, …).
140/// The scope exists so agents can read the user's other repositories; loose
141/// personal files (`~/Documents/taxes.pdf`, `~/Downloads/contract.pdf`,
142/// `~/Desktop`) are not code and stay jailed, so a prompt-injected agent cannot
143/// pull them into the model context. The home directory itself is never
144/// admitted — a tree walk rooted there would descend into `~/Library`.
145pub(crate) fn home_scope_admits(base: &Path) -> bool {
146    if PathJailScope::resolve() != PathJailScope::Home {
147        return false;
148    }
149    let Some(home) = scope_home() else {
150        return false;
151    };
152    admits_below(base, &home) && project_containing(base, &home).is_some()
153}
154
155fn admits_below(base: &Path, home: &Path) -> bool {
156    first_component_below(base, home).is_some() && protected_zone_in(base, home).is_none()
157}
158
159/// The nearest directory at or above `path`, strictly below `home`, that
160/// carries a project marker. `has_project_marker` keeps its TCC guard: a
161/// launchd-owned process never probes `~/Documents` & co., so there the scope
162/// admits nothing and the project boundary applies (fail closed).
163fn project_containing(path: &Path, home: &Path) -> Option<PathBuf> {
164    let mut cur = if path.is_dir() { path } else { path.parent()? };
165    while cur != home && cur.starts_with(home) {
166        if crate::core::pathutil::has_project_marker(cur) {
167            return Some(cur.to_path_buf());
168        }
169        cur = cur.parent()?;
170    }
171    None
172}
173
174/// Protected zones are a deny, not only a gap in the widening: a root or allow
175/// entry that merely *contains* a zone (a project rooted at `~` for a dotfiles
176/// repo, an `extra_roots` entry of `~`, a host reporting `~` as its root) must
177/// not open `~/.ssh`. A zone is reachable only through a root or allow entry
178/// located inside it — `~/.codex/worktrees/x`, lean-ctx's own `~/.local/...`
179/// state, `allow-path ~/.config/myapp`, a registered `~/.cargo/registry`.
180pub(crate) fn protected_zone_permits(base: &Path, root: &Path, allow: &[PathBuf]) -> bool {
181    let Some(zone) = zone_home().and_then(|home| protected_zone_in(base, &home)) else {
182        return true;
183    };
184    (root.starts_with(&zone) && base.starts_with(root))
185        || allow
186            .iter()
187            .any(|p| p.starts_with(&zone) && base.starts_with(p))
188}
189
190fn session_write_roots() -> &'static std::sync::Mutex<Vec<PathBuf>> {
191    static ROOTS: std::sync::OnceLock<std::sync::Mutex<Vec<PathBuf>>> = std::sync::OnceLock::new();
192    ROOTS.get_or_init(|| std::sync::Mutex::new(Vec::new()))
193}
194
195/// Records a session's project (or host-declared) root as writable. Called
196/// for every tool call; broad roots (`/`, `~`, temp dirs) are never recorded.
197pub fn register_session_root(root: &str) {
198    if root.trim().is_empty() {
199        return;
200    }
201    let path = super::pathjail::canonicalize_secure(Path::new(root));
202    if crate::core::pathutil::is_broad_or_unsafe_root(&path) {
203        return;
204    }
205    let mut roots = session_write_roots()
206        .lock()
207        .unwrap_or_else(std::sync::PoisonError::into_inner);
208    if roots.iter().any(|r| r == &path) {
209        return;
210    }
211    if roots.len() >= MAX_SESSION_WRITE_ROOTS {
212        roots.remove(0);
213    }
214    roots.push(path);
215}
216
217/// The `home` scope opens *reads* across your projects; writes stay where they
218/// were before it: the session's project, host-declared roots and explicit
219/// allow entries. Otherwise a prompt-injected agent in repo A could plant
220/// `~/code/B/.git/hooks/pre-commit` or `~/bin/git`. `target` is the canonical
221/// write target. Returns the refusal, or `None` when the write may proceed
222/// (including every path the home scope did not admit — the jail decided those).
223pub(crate) fn home_scope_write_denial(target: &Path) -> Option<String> {
224    if PathJailScope::resolve() != PathJailScope::Home {
225        return None;
226    }
227    let home = scope_home()?;
228    if !admits_below(target, &home) {
229        return None;
230    }
231    let mut writable: Vec<PathBuf> = session_write_roots()
232        .lock()
233        .unwrap_or_else(std::sync::PoisonError::into_inner)
234        .clone();
235    writable.extend(super::pathjail::allow_paths_from_env_and_config());
236    if let Ok(state) = crate::core::paths::state_dir() {
237        writable.push(super::pathjail::canonicalize_secure(&state));
238    }
239    // CLI invocations (`lean-ctx pack`, `lean-ctx call`) have no session; the
240    // directory the user ran them in is their project.
241    if let Ok(cwd) = std::env::current_dir() {
242        let cwd = super::pathjail::canonicalize_secure(&cwd);
243        if !crate::core::pathutil::is_broad_or_unsafe_root(&cwd) {
244            writable.push(cwd);
245        }
246    }
247    if writable.iter().any(|w| target.starts_with(w)) {
248        return None;
249    }
250    Some(format!(
251        "{} is outside the active project — path_jail_scope = home opens other projects \
252         for reading only. To allow writes there, the user runs in their terminal: \
253         lean-ctx allow-path {} — takes effect immediately, no restart.",
254        target.display(),
255        suggested_allow_dir(target, Some(&home)).display()
256    ))
257}
258
259/// Nearest ancestor of `path` (inclusive) carrying a project marker, below
260/// `home` when it lies there. Falls back to the containing directory. This is
261/// the directory `lean-ctx allow-path` should be offered for: allowing the
262/// whole project beats a second rejection on the neighbouring file.
263fn suggested_allow_dir(path: &Path, home: Option<&Path>) -> PathBuf {
264    let start = if path.is_dir() {
265        path.to_path_buf()
266    } else {
267        path.parent().unwrap_or(path).to_path_buf()
268    };
269    let mut cur = start.as_path();
270    loop {
271        if home.is_some_and(|h| cur == h) || cur.parent().is_none() {
272            break;
273        }
274        if crate::core::pathutil::has_project_marker(cur) {
275            return cur.to_path_buf();
276        }
277        match cur.parent() {
278            Some(p) => cur = p,
279            None => break,
280        }
281    }
282    start
283}
284
285/// Agent-facing explanation for a path the jail rejected, naming the one
286/// command the *user* runs to admit it (agent shells refuse it, see
287/// `shell_allowlist::self_config`). `candidate` is the requested path, `base`
288/// its canonical existing ancestor, `root` the active project.
289pub(crate) fn escape_hint(candidate: &Path, base: &Path, root: &Path) -> String {
290    const TAIL: &str = " — the user runs this in their own terminal; it takes effect \
291                        immediately, no restart.";
292    let home = zone_home();
293
294    if home.as_deref() == Some(base) {
295        return ". Your home directory itself is not a project root — it holds ~/.ssh, \
296                ~/Library and other protected locations. Point the tool at a project \
297                below it."
298            .to_string();
299    }
300    if let Some(zone) = home.as_deref().and_then(|h| protected_zone_in(base, h)) {
301        // Offer the narrowest directory, never the whole zone by default.
302        let dir = if base.is_dir() {
303            base
304        } else {
305            base.parent().unwrap_or(base)
306        };
307        return format!(
308            ". {} is a protected location (credentials and other programs' private data \
309             stay jailed). To allow it anyway: lean-ctx allow-path {}{TAIL}",
310            zone.display(),
311            dir.display()
312        );
313    }
314
315    let suggestion = suggested_allow_dir(base, home.as_deref());
316    let under_home = scope_home().is_some_and(|h| admits_below(base, &h));
317    // `home` scope: below ~ but not inside any project — loose personal files.
318    if under_home && PathJailScope::resolve() == PathJailScope::Home {
319        return format!(
320            ". {} is in your home directory but not inside a project (no .git, Cargo.toml, \
321             package.json, … above it), so the home scope does not open it — loose \
322             personal files stay private. To allow it: lean-ctx allow-path {}{TAIL}",
323            candidate.display(),
324            suggestion.display()
325        );
326    }
327    if under_home {
328        return format!(
329            ". {} is outside the active project ({}). Allow every project in your home \
330             directory: lean-ctx config set path_jail_scope home — or only this one: \
331             lean-ctx allow-path {}{TAIL}",
332            candidate.display(),
333            root.display(),
334            suggestion.display()
335        );
336    }
337    format!(
338        ". {} is outside the active project ({}) and outside your home directory. To \
339         allow it: lean-ctx allow-path {}{TAIL}",
340        candidate.display(),
341        root.display(),
342        suggestion.display()
343    )
344}
345
346#[cfg(test)]
347mod tests {
348    use super::*;
349
350    #[test]
351    fn parse_accepts_canonical_names_and_aliases() {
352        assert_eq!(PathJailScope::parse("home"), Some(PathJailScope::Home));
353        assert_eq!(
354            PathJailScope::parse(" Project "),
355            Some(PathJailScope::Project)
356        );
357        assert_eq!(PathJailScope::parse("strict"), Some(PathJailScope::Project));
358        assert_eq!(PathJailScope::parse("anything"), None);
359        assert_eq!(PathJailScope::default(), PathJailScope::Home);
360        for s in [PathJailScope::Home, PathJailScope::Project] {
361            assert_eq!(PathJailScope::parse(s.as_str()), Some(s));
362        }
363    }
364
365    #[test]
366    fn home_zone_admits_code_and_protects_secrets() {
367        let home = Path::new("/home/u");
368        assert!(admits_below(Path::new("/home/u/code/repo/src/a.rs"), home));
369        assert!(admits_below(Path::new("/home/u/Documents/p"), home));
370
371        for protected in [
372            "/home/u/.ssh/id_ed25519",
373            "/home/u/.aws/credentials",
374            "/home/u/.config/gh/hosts.yml",
375            "/home/u/.zshrc",
376            "/home/u/.claude/projects/x/session.jsonl",
377            "/home/u/Library/Keychains/login.keychain-db",
378            "/home/u/AppData/Roaming/x",
379            "/home/u/NTUSER.DAT",
380        ] {
381            assert!(!admits_below(Path::new(protected), home), "{protected}");
382            assert!(protected_zone_in(Path::new(protected), home).is_some());
383        }
384        // The home dir itself and anything outside it are never admitted.
385        assert!(!admits_below(home, home));
386        assert!(!admits_below(Path::new("/etc/passwd"), home));
387        assert!(!admits_below(Path::new("/home/user2/x"), home));
388    }
389
390    #[test]
391    fn protected_zone_is_the_top_level_entry() {
392        let home = Path::new("/home/u");
393        assert_eq!(
394            protected_zone_in(Path::new("/home/u/.config/gh/hosts.yml"), home),
395            Some(PathBuf::from("/home/u/.config"))
396        );
397        // Dot entries deeper in the tree (a repo's .git) are ordinary code.
398        assert_eq!(
399            protected_zone_in(Path::new("/home/u/code/repo/.git/HEAD"), home),
400            None
401        );
402    }
403
404    /// End-to-end through the real jail with a throwaway `$HOME`: a sibling
405    /// project is admitted, protected zones and the outside world are not, and
406    /// the `project` scope restores the single-project boundary.
407    #[cfg(all(unix, not(feature = "no-jail")))]
408    #[test]
409    fn jail_admits_sibling_projects_but_not_protected_zones() {
410        let _iso = crate::core::data_dir::isolated_data_dir();
411        let tmp = tempfile::tempdir().unwrap();
412        let home = super::super::pathjail::canonicalize_secure(tmp.path()).join("home");
413        let (a, b, ssh) = (home.join("code/a"), home.join("code/b"), home.join(".ssh"));
414        for dir in [&a, &b, &ssh] {
415            std::fs::create_dir_all(dir).unwrap();
416        }
417        std::fs::create_dir_all(a.join(".git")).unwrap();
418        std::fs::write(b.join("Cargo.toml"), "[package]").unwrap();
419        std::fs::create_dir_all(b.join("src")).unwrap();
420        std::fs::write(b.join("src/lib.rs"), "x").unwrap();
421        std::fs::write(b.join("lib.rs"), "x").unwrap();
422        std::fs::write(ssh.join("id_ed25519"), "secret").unwrap();
423        let docs = home.join("Documents/Steuern");
424        std::fs::create_dir_all(&docs).unwrap();
425        std::fs::write(docs.join("2025.pdf"), "private").unwrap();
426        let outside = tmp.path().join("outside.txt");
427        std::fs::write(&outside, "x").unwrap();
428
429        let old_home = std::env::var_os("HOME");
430        crate::test_env::set_var("HOME", &home);
431        crate::test_env::remove_var("LEAN_CTX_PATH_JAIL_SCOPE");
432        let jail = super::super::pathjail::jail_path;
433
434        assert!(
435            jail(&b.join("lib.rs"), &a).is_ok(),
436            "sibling project under ~"
437        );
438        assert!(
439            jail(&b.join("src/lib.rs"), &a).is_ok(),
440            "nested file of a sibling project"
441        );
442        // Loose personal files and folders that only *contain* projects stay
443        // jailed: the scope opens code, not the home directory.
444        let err = jail(&docs.join("2025.pdf"), &a).unwrap_err().to_string();
445        assert!(err.contains("not inside a project"), "{err}");
446        assert!(jail(&docs, &a).is_err(), "a folder without a project");
447        assert!(jail(&home.join("code"), &a).is_err(), "parent of projects");
448        let err = jail(&ssh.join("id_ed25519"), &a).unwrap_err().to_string();
449        assert!(err.contains("protected location"), "{err}");
450        let err = jail(&outside, &a).unwrap_err().to_string();
451        assert!(err.contains("outside your home directory"), "{err}");
452        let err = jail(&home, &a).unwrap_err().to_string();
453        assert!(err.contains("not a project root"), "{err}");
454
455        // A root or allow entry that merely contains a zone does not open it
456        // (dotfiles repo at ~); a root inside the zone does.
457        assert!(
458            jail(&ssh.join("id_ed25519"), &home).is_err(),
459            "zone is a deny"
460        );
461        assert!(
462            jail(&ssh.join("id_ed25519"), &ssh).is_ok(),
463            "root inside the zone"
464        );
465
466        // Reads across projects, writes only in the session's own project.
467        let write = super::super::pathjail::enforce_writable;
468        let err = write(&b.join("lib.rs")).unwrap_err();
469        assert!(
470            err.contains("for reading only") && err.contains("allow-path"),
471            "{err}"
472        );
473        assert!(write(&b.join(".git/hooks/pre-commit")).is_err());
474        register_session_root(&b.to_string_lossy());
475        assert!(write(&b.join("lib.rs")).is_ok(), "session root is writable");
476
477        crate::test_env::set_var("LEAN_CTX_PATH_JAIL_SCOPE", "project");
478        let err = jail(&b.join("lib.rs"), &a).unwrap_err().to_string();
479        assert!(
480            err.contains("path_jail_scope home") && err.contains("allow-path"),
481            "{err}"
482        );
483        crate::test_env::remove_var("LEAN_CTX_PATH_JAIL_SCOPE");
484
485        // An implausible $HOME never turns into "everything below /".
486        crate::test_env::set_var("HOME", "/");
487        assert!(
488            jail(&b.join("lib.rs"), &a).is_err(),
489            "HOME=/ falls back to the project"
490        );
491
492        match old_home {
493            Some(h) => crate::test_env::set_var("HOME", h),
494            None => crate::test_env::remove_var("HOME"),
495        }
496    }
497
498    #[test]
499    fn suggestion_prefers_the_enclosing_project() {
500        let tmp = tempfile::tempdir().unwrap();
501        let repo = tmp.path().join("repo");
502        std::fs::create_dir_all(repo.join("src/deep")).unwrap();
503        std::fs::create_dir_all(repo.join(".git")).unwrap();
504        let file = repo.join("src/deep/a.rs");
505        std::fs::write(&file, "x").unwrap();
506        assert_eq!(suggested_allow_dir(&file, None), repo);
507
508        let loose = tmp.path().join("loose");
509        std::fs::create_dir_all(&loose).unwrap();
510        assert_eq!(suggested_allow_dir(&loose, Some(tmp.path())), loose);
511    }
512}