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