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