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**, since 3.11.3): everything below the user's home
10//!   directory is admitted for reading and writing, except the protected zones
11//!   where credentials and other programs' private state live (every
12//!   top-level dot entry such as `~/.ssh`, `~/.aws`, `~/.config`, `~/.zshrc` or
13//!   other agents' `~/.claude`, plus `~/Library` on macOS, `~/AppData` and the
14//!   `NTUSER.DAT*` registry hive on Windows). Paths outside the home directory
15//!   stay jailed.
16//! - `projects` (the default of 3.11.1 and 3.11.2): only paths inside a
17//!   project below `~` (a directory between it and `~` holds `.git`,
18//!   `Cargo.toml`, …) are admitted, for reading; loose personal files are not,
19//!   and writes stay in the session's project.
20//! - `project`: the classic boundary — the project root plus allow-lists.
21//!
22//! Explicit allow-lists (`allow_paths`, `extra_roots`, `read_only_roots`) and
23//! lean-ctx's own state dir still widen every scope, so `lean-ctx allow-path
24//! ~/.config/foo` reopens one protected directory without dropping the zone.
25//! `path_jail = false` keeps disabling the jail entirely.
26//!
27//! Resolution precedence (first hit wins): `LEAN_CTX_PATH_JAIL_SCOPE` env →
28//! `path_jail_scope` in the global `config.toml` → `home`. Like `path_jail` it
29//! is global-only: a project-local `.lean-ctx.toml` is never merged for it.
30
31use std::path::{Path, PathBuf};
32
33/// Top-level home entries (besides every dot entry) holding other programs'
34/// private data: keychains, browser profiles, mail, app containers (Linux
35/// snaps keep each app's dot dirs — cookies, logins — under `~/snap/<app>`).
36const PROTECTED_HOME_DIRS: &[&str] = &["Library", "AppData", "snap"];
37
38tokio::task_local! {
39    /// The roots the tool call being served may write in: its project and its
40    /// session's host-declared roots. Set per call and never accumulated, so a
41    /// root one call (or one client) declared is not writable for the next
42    /// (AP04-G9).
43    static REQUEST_WRITE_ROOTS: Vec<PathBuf>;
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
47pub enum PathJailScope {
48    /// Everything below `$HOME` except the protected zones, read and write.
49    #[default]
50    Home,
51    /// Projects below `$HOME`, read-only outside the session's project.
52    Projects,
53    /// Only the project root plus the configured allow-lists.
54    Project,
55}
56
57impl PathJailScope {
58    /// Lenient parse; unknown text returns `None` so callers fall back to the default.
59    pub fn parse(value: &str) -> Option<Self> {
60        match value.trim().to_ascii_lowercase().as_str() {
61            "home" | "user" => Some(Self::Home),
62            "projects" | "workspace" => Some(Self::Projects),
63            "project" | "strict" | "root" => Some(Self::Project),
64            _ => None,
65        }
66    }
67
68    pub fn as_str(self) -> &'static str {
69        match self {
70            Self::Home => "home",
71            Self::Projects => "projects",
72            Self::Project => "project",
73        }
74    }
75
76    /// Active scope: env override → config → default (`home`). A
77    /// launcher-bound Workspace (#2120) always means `project`: its roots,
78    /// not the home directory, bound every path.
79    pub fn resolve() -> Self {
80        if crate::core::workspace_authority::is_configured() {
81            return Self::Project;
82        }
83        Self::explicit().unwrap_or_default()
84    }
85
86    /// The scope the user chose (env or config), if any.
87    fn explicit() -> Option<Self> {
88        if let Ok(raw) = std::env::var("LEAN_CTX_PATH_JAIL_SCOPE")
89            && let Some(scope) = Self::parse(&raw)
90        {
91            return Some(scope);
92        }
93        crate::core::config::Config::load()
94            .path_jail_scope
95            .as_deref()
96            .and_then(Self::parse)
97    }
98}
99
100/// Canonical home directory for the protected-zone checks; `None` when `$HOME`
101/// is the filesystem root.
102fn zone_home() -> Option<PathBuf> {
103    let home = super::pathjail::canonicalize_secure(&dirs::home_dir()?);
104    home.parent().is_some().then_some(home)
105}
106
107/// Home directory the `home` scope may open. `$HOME` is only an env var: in
108/// containers and CI it is often `/`, `/root` or `/tmp`, where "everything
109/// below home" would mean the whole system or other users' files. Require at
110/// least two normal components and, on Unix, ownership by this user;
111/// otherwise the jail falls back to the project boundary.
112fn scope_home() -> Option<PathBuf> {
113    let home = zone_home()?;
114    let depth = home
115        .components()
116        .filter(|c| matches!(c, std::path::Component::Normal(_)))
117        .count();
118    if depth < 2 {
119        return None;
120    }
121    #[cfg(unix)]
122    {
123        use std::os::unix::fs::MetadataExt;
124        // SAFETY: geteuid has no arguments or failure state.
125        if std::fs::metadata(&home).ok()?.uid() != unsafe { libc::geteuid() } {
126            return None;
127        }
128    }
129    Some(home)
130}
131
132/// The first path component below `home`, when `path` lies strictly inside it.
133fn first_component_below<'a>(path: &'a Path, home: &Path) -> Option<&'a std::ffi::OsStr> {
134    path.strip_prefix(home)
135        .ok()?
136        .components()
137        .next()
138        .map(std::path::Component::as_os_str)
139}
140
141/// The protected zone (e.g. `~/.ssh`) containing `path`, if any. `path` must
142/// already be canonical; `home` is the canonical home directory.
143fn protected_zone_in(path: &Path, home: &Path) -> Option<PathBuf> {
144    let first = first_component_below(path, home)?;
145    let name = first.to_string_lossy();
146    // Windows keeps the user's registry hive (`NTUSER.DAT*`) directly in home.
147    let protected = name.starts_with('.')
148        || name.to_ascii_lowercase().starts_with("ntuser.")
149        || PROTECTED_HOME_DIRS
150            .iter()
151            .any(|d| name.eq_ignore_ascii_case(d));
152    protected.then(|| home.join(first))
153}
154
155/// True when the active scope admits the canonical path `base`: below the home
156/// directory and outside every protected zone; for `projects` also inside a
157/// project.
158///
159/// "Inside a project" — some directory between `base` and `~` (not `~`
160/// itself) carries a project marker (`.git`, `Cargo.toml`, `package.json`, …).
161/// The `projects` scope keeps loose personal files (`~/Documents/taxes.pdf`)
162/// jailed; `home` admits them. The home directory itself is never admitted
163/// — a tree walk rooted there would descend into `~/Library`.
164pub(crate) fn home_scope_admits(base: &Path) -> bool {
165    let scope = PathJailScope::resolve();
166    if scope == PathJailScope::Project {
167        return false;
168    }
169    let Some(home) = scope_home() else {
170        return false;
171    };
172    admits_below(base, &home)
173        && (scope == PathJailScope::Home || project_containing(base, &home).is_some())
174}
175
176fn admits_below(base: &Path, home: &Path) -> bool {
177    first_component_below(base, home).is_some() && protected_zone_in(base, home).is_none()
178}
179
180/// The nearest directory at or above `path`, strictly below `home`, that
181/// carries a project marker. `has_project_marker` keeps its TCC guard: a
182/// launchd-owned process never probes `~/Documents` & co., so there the scope
183/// admits nothing and the project boundary applies (fail closed).
184fn project_containing(path: &Path, home: &Path) -> Option<PathBuf> {
185    let mut cur = if path.is_dir() { path } else { path.parent()? };
186    while cur != home && cur.starts_with(home) {
187        if crate::core::pathutil::has_project_marker(cur) {
188            return Some(cur.to_path_buf());
189        }
190        cur = cur.parent()?;
191    }
192    None
193}
194
195/// True when the canonical `path` lies in a protected home zone (`~/.ssh`,
196/// `~/Library`, any other dot folder, …).
197pub(crate) fn in_protected_zone(path: &Path) -> bool {
198    zone_home().is_some_and(|home| protected_zone_in(path, &home).is_some())
199}
200
201/// Protected zones are a deny, not only a gap in the widening: a root or allow
202/// entry that merely *contains* a zone (a project rooted at `~` for a dotfiles
203/// repo, an `extra_roots` entry of `~`, a host reporting `~` as its root) must
204/// not open `~/.ssh`. A zone is reachable only through a root or allow entry
205/// located inside it — `~/.codex/worktrees/x`, lean-ctx's own `~/.local/...`
206/// state, `allow-path ~/.config/myapp`, a registered `~/.cargo/registry`.
207pub(crate) fn protected_zone_permits(base: &Path, root: &Path, allow: &[PathBuf]) -> bool {
208    let Some(zone) = zone_home().and_then(|home| protected_zone_in(base, &home)) else {
209        return true;
210    };
211    (root.starts_with(&zone) && base.starts_with(root))
212        || allow
213            .iter()
214            .any(|p| p.starts_with(&zone) && base.starts_with(p))
215}
216
217/// A declared root as a write root; broad roots (`/`, `~`, temp dirs) never are.
218fn write_root(root: &str) -> Option<PathBuf> {
219    if root.trim().is_empty() {
220        return None;
221    }
222    let path = super::pathjail::canonicalize_secure(Path::new(root));
223    (!crate::core::pathutil::is_broad_or_unsafe_root(&path)).then_some(path)
224}
225
226/// Runs one tool call with its project and host-declared roots writable.
227pub(crate) fn with_request_write_roots<T>(roots: &[String], operation: impl FnOnce() -> T) -> T {
228    let roots = roots.iter().filter_map(|root| write_root(root)).collect();
229    REQUEST_WRITE_ROOTS.sync_scope(roots, operation)
230}
231
232/// The `projects` scope opens *reads* across your projects; writes stay in the
233/// session's project, host-declared roots and explicit allow entries, so a
234/// prompt-injected agent in repo A cannot plant `~/code/B/.git/hooks/pre-commit`.
235/// The `home` scope admits writes wherever it admits reads. `target` is the
236/// canonical write target. Returns the refusal, or `None` when the write may
237/// proceed (including every path the scope did not admit — the jail decided those).
238pub(crate) fn home_scope_write_denial(target: &Path) -> Option<String> {
239    if PathJailScope::resolve() != PathJailScope::Projects {
240        return None;
241    }
242    let home = scope_home()?;
243    if !admits_below(target, &home) {
244        return None;
245    }
246    // A tool call writes in its own roots; work it hands to another thread
247    // keeps at least its request project. CLI invocations (`lean-ctx pack`,
248    // `lean-ctx call`) have no session; the directory the user ran them in is
249    // their project.
250    let mut writable: Vec<PathBuf> = REQUEST_WRITE_ROOTS
251        .try_with(Clone::clone)
252        .ok()
253        .or_else(|| {
254            crate::core::policy::runtime::REQUEST_PROJECT
255                .try_with(|slot| slot.borrow().clone())
256                .ok()
257                .map(|project| {
258                    project
259                        .and_then(|root| write_root(&root.to_string_lossy()))
260                        .into_iter()
261                        .collect()
262                })
263        })
264        .unwrap_or_else(|| {
265            std::env::current_dir()
266                .ok()
267                .and_then(|cwd| write_root(&cwd.to_string_lossy()))
268                .into_iter()
269                .collect()
270        });
271    writable.extend(super::pathjail::allow_paths_from_env_and_config());
272    if let Ok(state) = crate::core::paths::state_dir() {
273        writable.push(super::pathjail::canonicalize_secure(&state));
274    }
275    if writable.iter().any(|w| target.starts_with(w)) {
276        return None;
277    }
278    Some(format!(
279        "{} is outside the active project — path_jail_scope = projects opens other \
280         projects for reading only. To allow writes there, the user runs in their terminal: \
281         lean-ctx allow-path {} — or `lean-ctx config set path_jail_scope home` for all of ~ \
282         — takes effect immediately, no restart.",
283        target.display(),
284        suggested_allow_dir(target, Some(&home)).display()
285    ))
286}
287
288/// Nearest ancestor of `path` (inclusive) carrying a project marker, below
289/// `home` when it lies there. Falls back to the containing directory. This is
290/// the directory `lean-ctx allow-path` should be offered for: allowing the
291/// whole project beats a second rejection on the neighbouring file.
292fn suggested_allow_dir(path: &Path, home: Option<&Path>) -> PathBuf {
293    let start = if path.is_dir() {
294        path.to_path_buf()
295    } else {
296        path.parent().unwrap_or(path).to_path_buf()
297    };
298    let mut cur = start.as_path();
299    loop {
300        if home.is_some_and(|h| cur == h) || cur.parent().is_none() {
301            break;
302        }
303        if crate::core::pathutil::has_project_marker(cur) {
304            return cur.to_path_buf();
305        }
306        match cur.parent() {
307            Some(p) => cur = p,
308            None => break,
309        }
310    }
311    start
312}
313
314/// Agent-facing explanation for a path the jail rejected, naming the one
315/// command the *user* runs to admit it (agent shells refuse it, see
316/// `shell_allowlist::self_config`). `candidate` is the requested path, `base`
317/// its canonical existing ancestor, `root` the active project.
318pub(crate) fn escape_hint(candidate: &Path, base: &Path, root: &Path) -> String {
319    // Agents looped on the same refusal (99 identical calls in one Cursor
320    // session): say outright that a retry cannot succeed.
321    const TAIL: &str = " — the user runs this in their own terminal; it takes effect \
322                        immediately, no restart. Until then every call on this path is \
323                        refused the same way: do not retry it, ask the user or continue \
324                        without it.";
325    let home = zone_home();
326
327    if home.as_deref() == Some(base) {
328        return ". Your home directory itself is not a project root — it holds ~/.ssh, \
329                ~/Library and other protected locations. Point the tool at a project \
330                below it."
331            .to_string();
332    }
333    if let Some(zone) = home.as_deref().and_then(|h| protected_zone_in(base, h)) {
334        // Offer the narrowest directory, never the whole zone by default.
335        let dir = if base.is_dir() {
336            base
337        } else {
338            base.parent().unwrap_or(base)
339        };
340        return format!(
341            ". {} is a protected location (credentials and other programs' private data \
342             stay jailed). To allow it anyway: lean-ctx allow-path {}{TAIL}",
343            zone.display(),
344            dir.display()
345        );
346    }
347
348    let suggestion = suggested_allow_dir(base, home.as_deref());
349    let under_home = scope_home().is_some_and(|h| admits_below(base, &h));
350    // `projects` scope: below ~ but not inside any project — loose personal files.
351    if under_home && PathJailScope::resolve() == PathJailScope::Projects {
352        return format!(
353            ". {} is in your home directory but not inside a project (no .git, Cargo.toml, \
354             package.json, … above it), so path_jail_scope = projects does not open it. To \
355             allow it: lean-ctx allow-path {} — or all of ~: lean-ctx config set \
356             path_jail_scope home{TAIL}",
357            candidate.display(),
358            suggestion.display()
359        );
360    }
361    if under_home {
362        return format!(
363            ". {} is outside the active project ({}). Allow your whole home directory \
364             (protected locations stay jailed): lean-ctx config set path_jail_scope home — \
365             or only this one: lean-ctx allow-path {}{TAIL}",
366            candidate.display(),
367            root.display(),
368            suggestion.display()
369        );
370    }
371    format!(
372        ". {} is outside the active project ({}) and outside your home directory. To \
373         allow it: lean-ctx allow-path {}{TAIL}",
374        candidate.display(),
375        root.display(),
376        suggestion.display()
377    )
378}
379
380/// What the one-time notice says about the widened default.
381fn default_notice_text() -> String {
382    "\x1b[1mPathJail now opens your home directory:\x1b[0m agents may read and write \
383     anything below ~ except protected locations (~/.ssh, ~/.aws, ~/.config, every other \
384     dot folder, ~/Library, ~/AppData).\n  \x1b[2mPrevious behaviour (other projects \
385     read-only): lean-ctx config set path_jail_scope projects · active project only: \
386     lean-ctx config set path_jail_scope project\x1b[0m\n"
387        .to_string()
388}
389
390/// Tells a user once that the default scope widened in 3.11.3, on the first
391/// interactive command. Never for MCP, hooks or piped use, and never when the
392/// user chose a scope or turned the jail off: an explicit choice is kept.
393pub fn maybe_show_default_notice() {
394    use std::io::IsTerminal;
395    if !(std::io::stdin().is_terminal() && std::io::stderr().is_terminal())
396        || PathJailScope::explicit().is_some()
397        || crate::core::config::Config::load().path_jail == Some(false)
398    {
399        return;
400    }
401    let Ok(marker) =
402        crate::core::paths::state_dir().map(|dir| dir.join("path_jail_home_default_notice"))
403    else {
404        return;
405    };
406    if marker.exists() {
407        return;
408    }
409    eprint!("{}", default_notice_text());
410    eprintln!();
411    if let Some(parent) = marker.parent() {
412        let _ = std::fs::create_dir_all(parent);
413    }
414    let _ = std::fs::write(marker, "1\n");
415}
416
417#[cfg(test)]
418mod tests {
419    use super::*;
420
421    #[test]
422    fn parse_accepts_canonical_names_and_aliases() {
423        assert_eq!(PathJailScope::parse("home"), Some(PathJailScope::Home));
424        assert_eq!(
425            PathJailScope::parse(" Project "),
426            Some(PathJailScope::Project)
427        );
428        assert_eq!(PathJailScope::parse("strict"), Some(PathJailScope::Project));
429        assert_eq!(
430            PathJailScope::parse("projects"),
431            Some(PathJailScope::Projects)
432        );
433        assert_eq!(PathJailScope::parse("anything"), None);
434        assert_eq!(PathJailScope::default(), PathJailScope::Home);
435        for s in [
436            PathJailScope::Home,
437            PathJailScope::Projects,
438            PathJailScope::Project,
439        ] {
440            assert_eq!(PathJailScope::parse(s.as_str()), Some(s));
441        }
442    }
443
444    #[test]
445    fn the_notice_names_the_protected_zones_and_both_ways_back() {
446        let text = default_notice_text();
447        for needle in [
448            "~/.ssh",
449            "~/.aws",
450            "~/Library",
451            "path_jail_scope projects",
452            "path_jail_scope project",
453        ] {
454            assert!(text.contains(needle), "{needle}");
455        }
456    }
457
458    #[test]
459    fn home_zone_admits_code_and_protects_secrets() {
460        let home = Path::new("/home/u");
461        assert!(admits_below(Path::new("/home/u/code/repo/src/a.rs"), home));
462        assert!(admits_below(Path::new("/home/u/Documents/p"), home));
463
464        for protected in [
465            "/home/u/.ssh/id_ed25519",
466            "/home/u/.aws/credentials",
467            "/home/u/.config/gh/hosts.yml",
468            "/home/u/.zshrc",
469            "/home/u/.claude/projects/x/session.jsonl",
470            "/home/u/Library/Keychains/login.keychain-db",
471            "/home/u/AppData/Roaming/x",
472            "/home/u/NTUSER.DAT",
473        ] {
474            assert!(!admits_below(Path::new(protected), home), "{protected}");
475            assert!(protected_zone_in(Path::new(protected), home).is_some());
476        }
477        // The home dir itself and anything outside it are never admitted.
478        assert!(!admits_below(home, home));
479        assert!(!admits_below(Path::new("/etc/passwd"), home));
480        assert!(!admits_below(Path::new("/home/user2/x"), home));
481    }
482
483    #[test]
484    fn protected_zone_is_the_top_level_entry() {
485        let home = Path::new("/home/u");
486        assert_eq!(
487            protected_zone_in(Path::new("/home/u/.config/gh/hosts.yml"), home),
488            Some(PathBuf::from("/home/u/.config"))
489        );
490        // Dot entries deeper in the tree (a repo's .git) are ordinary code.
491        assert_eq!(
492            protected_zone_in(Path::new("/home/u/code/repo/.git/HEAD"), home),
493            None
494        );
495    }
496
497    /// End-to-end through the real jail with a throwaway `$HOME`: `home` opens
498    /// all of ~ for reading and writing except protected zones, `projects`
499    /// restores the read-only project scope, and `project` the single-project
500    /// boundary.
501    #[cfg(all(unix, not(feature = "no-jail")))]
502    #[test]
503    fn jail_admits_sibling_projects_but_not_protected_zones() {
504        let _iso = crate::core::data_dir::isolated_data_dir();
505        let tmp = tempfile::tempdir().unwrap();
506        let home = super::super::pathjail::canonicalize_secure(tmp.path()).join("home");
507        let (a, b, ssh) = (home.join("code/a"), home.join("code/b"), home.join(".ssh"));
508        for dir in [&a, &b, &ssh] {
509            std::fs::create_dir_all(dir).unwrap();
510        }
511        std::fs::create_dir_all(a.join(".git")).unwrap();
512        std::fs::write(b.join("Cargo.toml"), "[package]").unwrap();
513        std::fs::create_dir_all(b.join("src")).unwrap();
514        std::fs::write(b.join("src/lib.rs"), "x").unwrap();
515        std::fs::write(b.join("lib.rs"), "x").unwrap();
516        std::fs::write(ssh.join("id_ed25519"), "secret").unwrap();
517        let docs = home.join("Documents/Steuern");
518        std::fs::create_dir_all(&docs).unwrap();
519        std::fs::write(docs.join("2025.pdf"), "private").unwrap();
520        let outside = tmp.path().join("outside.txt");
521        std::fs::write(&outside, "x").unwrap();
522
523        let old_home = std::env::var_os("HOME");
524        crate::test_env::set_var("HOME", &home);
525        crate::test_env::remove_var("LEAN_CTX_PATH_JAIL_SCOPE");
526        let jail = super::super::pathjail::jail_path;
527
528        assert!(
529            jail(&b.join("lib.rs"), &a).is_ok(),
530            "sibling project under ~"
531        );
532        assert!(
533            jail(&b.join("src/lib.rs"), &a).is_ok(),
534            "nested file of a sibling project"
535        );
536        // The default `home` scope opens all of ~, loose files included.
537        assert!(
538            jail(&docs.join("2025.pdf"), &a).is_ok(),
539            "loose file under ~"
540        );
541        assert!(jail(&docs, &a).is_ok(), "a folder without a project");
542        assert!(jail(&home.join("code"), &a).is_ok(), "parent of projects");
543        let err = jail(&ssh.join("id_ed25519"), &a).unwrap_err().to_string();
544        assert!(err.contains("protected location"), "{err}");
545        let err = jail(&outside, &a).unwrap_err().to_string();
546        assert!(err.contains("outside your home directory"), "{err}");
547        let err = jail(&home, &a).unwrap_err().to_string();
548        assert!(err.contains("not a project root"), "{err}");
549
550        // A root or allow entry that merely contains a zone does not open it
551        // (dotfiles repo at ~); a root inside the zone does.
552        assert!(
553            jail(&ssh.join("id_ed25519"), &home).is_err(),
554            "zone is a deny"
555        );
556        assert!(
557            jail(&ssh.join("id_ed25519"), &ssh).is_ok(),
558            "root inside the zone"
559        );
560
561        // `home` writes wherever it reads; protected zones stay closed because
562        // every write resolves its path through the jail first.
563        let write = super::super::pathjail::enforce_writable;
564        assert!(write(&b.join("lib.rs")).is_ok(), "another project");
565        assert!(write(&docs.join("notes.md")).is_ok(), "a loose folder");
566        assert!(
567            jail(&ssh.join("authorized_keys"), &a).is_err(),
568            "protected zone"
569        );
570
571        // `projects`: reads across projects only, writes in the session's project.
572        crate::test_env::set_var("LEAN_CTX_PATH_JAIL_SCOPE", "projects");
573        assert!(jail(&b.join("lib.rs"), &a).is_ok(), "sibling project");
574        let err = jail(&docs.join("2025.pdf"), &a).unwrap_err().to_string();
575        assert!(err.contains("not inside a project"), "{err}");
576        assert!(jail(&home.join("code"), &a).is_err(), "parent of projects");
577        let err = write(&b.join("lib.rs")).unwrap_err();
578        assert!(
579            err.contains("for reading only") && err.contains("allow-path"),
580            "{err}"
581        );
582        assert!(write(&b.join(".git/hooks/pre-commit")).is_err());
583        let as_call = |roots: &[&Path], target: &Path| {
584            let roots: Vec<String> = roots.iter().map(|r| r.to_string_lossy().into()).collect();
585            with_request_write_roots(&roots, || write(target))
586        };
587        assert!(
588            as_call(&[b.as_path()], &b.join("lib.rs")).is_ok(),
589            "session root is writable"
590        );
591        // AP04-G9: a root an earlier call (another client) declared is not
592        // writable for the next call in another project.
593        assert!(as_call(&[a.as_path()], &b.join("lib.rs")).is_err());
594
595        crate::test_env::set_var("LEAN_CTX_PATH_JAIL_SCOPE", "project");
596        let err = jail(&b.join("lib.rs"), &a).unwrap_err().to_string();
597        assert!(
598            err.contains("path_jail_scope home") && err.contains("allow-path"),
599            "{err}"
600        );
601        crate::test_env::remove_var("LEAN_CTX_PATH_JAIL_SCOPE");
602
603        // An implausible $HOME never turns into "everything below /".
604        crate::test_env::set_var("HOME", "/");
605        assert!(
606            jail(&b.join("lib.rs"), &a).is_err(),
607            "HOME=/ falls back to the project"
608        );
609
610        match old_home {
611            Some(h) => crate::test_env::set_var("HOME", h),
612            None => crate::test_env::remove_var("HOME"),
613        }
614    }
615
616    #[test]
617    fn suggestion_prefers_the_enclosing_project() {
618        let tmp = tempfile::tempdir().unwrap();
619        let repo = tmp.path().join("repo");
620        std::fs::create_dir_all(repo.join("src/deep")).unwrap();
621        std::fs::create_dir_all(repo.join(".git")).unwrap();
622        let file = repo.join("src/deep/a.rs");
623        std::fs::write(&file, "x").unwrap();
624        assert_eq!(suggested_allow_dir(&file, None), repo);
625
626        let loose = tmp.path().join("loose");
627        std::fs::create_dir_all(&loose).unwrap();
628        assert_eq!(suggested_allow_dir(&loose, Some(tmp.path())), loose);
629    }
630}