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/// Protected zones are a deny, not only a gap in the widening: a root or allow
187/// entry that merely *contains* a zone (a project rooted at `~` for a dotfiles
188/// repo, an `extra_roots` entry of `~`, a host reporting `~` as its root) must
189/// not open `~/.ssh`. A zone is reachable only through a root or allow entry
190/// located inside it — `~/.codex/worktrees/x`, lean-ctx's own `~/.local/...`
191/// state, `allow-path ~/.config/myapp`, a registered `~/.cargo/registry`.
192pub(crate) fn protected_zone_permits(base: &Path, root: &Path, allow: &[PathBuf]) -> bool {
193    let Some(zone) = zone_home().and_then(|home| protected_zone_in(base, &home)) else {
194        return true;
195    };
196    (root.starts_with(&zone) && base.starts_with(root))
197        || allow
198            .iter()
199            .any(|p| p.starts_with(&zone) && base.starts_with(p))
200}
201
202fn session_write_roots() -> &'static std::sync::Mutex<Vec<PathBuf>> {
203    static ROOTS: std::sync::OnceLock<std::sync::Mutex<Vec<PathBuf>>> = std::sync::OnceLock::new();
204    ROOTS.get_or_init(|| std::sync::Mutex::new(Vec::new()))
205}
206
207/// Records a session's project (or host-declared) root as writable. Called
208/// for every tool call; broad roots (`/`, `~`, temp dirs) are never recorded.
209pub fn register_session_root(root: &str) {
210    if root.trim().is_empty() {
211        return;
212    }
213    let path = super::pathjail::canonicalize_secure(Path::new(root));
214    if crate::core::pathutil::is_broad_or_unsafe_root(&path) {
215        return;
216    }
217    let mut roots = session_write_roots()
218        .lock()
219        .unwrap_or_else(std::sync::PoisonError::into_inner);
220    if roots.iter().any(|r| r == &path) {
221        return;
222    }
223    if roots.len() >= MAX_SESSION_WRITE_ROOTS {
224        roots.remove(0);
225    }
226    roots.push(path);
227}
228
229/// The `projects` scope opens *reads* across your projects; writes stay in the
230/// session's project, host-declared roots and explicit allow entries, so a
231/// prompt-injected agent in repo A cannot plant `~/code/B/.git/hooks/pre-commit`.
232/// The `home` scope admits writes wherever it admits reads. `target` is the
233/// canonical write target. Returns the refusal, or `None` when the write may
234/// proceed (including every path the scope did not admit — the jail decided those).
235pub(crate) fn home_scope_write_denial(target: &Path) -> Option<String> {
236    if PathJailScope::resolve() != PathJailScope::Projects {
237        return None;
238    }
239    let home = scope_home()?;
240    if !admits_below(target, &home) {
241        return None;
242    }
243    let mut writable: Vec<PathBuf> = session_write_roots()
244        .lock()
245        .unwrap_or_else(std::sync::PoisonError::into_inner)
246        .clone();
247    writable.extend(super::pathjail::allow_paths_from_env_and_config());
248    if let Ok(state) = crate::core::paths::state_dir() {
249        writable.push(super::pathjail::canonicalize_secure(&state));
250    }
251    // CLI invocations (`lean-ctx pack`, `lean-ctx call`) have no session; the
252    // directory the user ran them in is their project.
253    if let Ok(cwd) = std::env::current_dir() {
254        let cwd = super::pathjail::canonicalize_secure(&cwd);
255        if !crate::core::pathutil::is_broad_or_unsafe_root(&cwd) {
256            writable.push(cwd);
257        }
258    }
259    if writable.iter().any(|w| target.starts_with(w)) {
260        return None;
261    }
262    Some(format!(
263        "{} is outside the active project — path_jail_scope = projects opens other \
264         projects for reading only. To allow writes there, the user runs in their terminal: \
265         lean-ctx allow-path {} — or `lean-ctx config set path_jail_scope home` for all of ~ \
266         — takes effect immediately, no restart.",
267        target.display(),
268        suggested_allow_dir(target, Some(&home)).display()
269    ))
270}
271
272/// Nearest ancestor of `path` (inclusive) carrying a project marker, below
273/// `home` when it lies there. Falls back to the containing directory. This is
274/// the directory `lean-ctx allow-path` should be offered for: allowing the
275/// whole project beats a second rejection on the neighbouring file.
276fn suggested_allow_dir(path: &Path, home: Option<&Path>) -> PathBuf {
277    let start = if path.is_dir() {
278        path.to_path_buf()
279    } else {
280        path.parent().unwrap_or(path).to_path_buf()
281    };
282    let mut cur = start.as_path();
283    loop {
284        if home.is_some_and(|h| cur == h) || cur.parent().is_none() {
285            break;
286        }
287        if crate::core::pathutil::has_project_marker(cur) {
288            return cur.to_path_buf();
289        }
290        match cur.parent() {
291            Some(p) => cur = p,
292            None => break,
293        }
294    }
295    start
296}
297
298/// Agent-facing explanation for a path the jail rejected, naming the one
299/// command the *user* runs to admit it (agent shells refuse it, see
300/// `shell_allowlist::self_config`). `candidate` is the requested path, `base`
301/// its canonical existing ancestor, `root` the active project.
302pub(crate) fn escape_hint(candidate: &Path, base: &Path, root: &Path) -> String {
303    const TAIL: &str = " — the user runs this in their own terminal; it takes effect \
304                        immediately, no restart.";
305    let home = zone_home();
306
307    if home.as_deref() == Some(base) {
308        return ". Your home directory itself is not a project root — it holds ~/.ssh, \
309                ~/Library and other protected locations. Point the tool at a project \
310                below it."
311            .to_string();
312    }
313    if let Some(zone) = home.as_deref().and_then(|h| protected_zone_in(base, h)) {
314        // Offer the narrowest directory, never the whole zone by default.
315        let dir = if base.is_dir() {
316            base
317        } else {
318            base.parent().unwrap_or(base)
319        };
320        return format!(
321            ". {} is a protected location (credentials and other programs' private data \
322             stay jailed). To allow it anyway: lean-ctx allow-path {}{TAIL}",
323            zone.display(),
324            dir.display()
325        );
326    }
327
328    let suggestion = suggested_allow_dir(base, home.as_deref());
329    let under_home = scope_home().is_some_and(|h| admits_below(base, &h));
330    // `projects` scope: below ~ but not inside any project — loose personal files.
331    if under_home && PathJailScope::resolve() == PathJailScope::Projects {
332        return format!(
333            ". {} is in your home directory but not inside a project (no .git, Cargo.toml, \
334             package.json, … above it), so path_jail_scope = projects does not open it. To \
335             allow it: lean-ctx allow-path {} — or all of ~: lean-ctx config set \
336             path_jail_scope home{TAIL}",
337            candidate.display(),
338            suggestion.display()
339        );
340    }
341    if under_home {
342        return format!(
343            ". {} is outside the active project ({}). Allow your whole home directory \
344             (protected locations stay jailed): lean-ctx config set path_jail_scope home — \
345             or only this one: lean-ctx allow-path {}{TAIL}",
346            candidate.display(),
347            root.display(),
348            suggestion.display()
349        );
350    }
351    format!(
352        ". {} is outside the active project ({}) and outside your home directory. To \
353         allow it: lean-ctx allow-path {}{TAIL}",
354        candidate.display(),
355        root.display(),
356        suggestion.display()
357    )
358}
359
360/// What the one-time notice says about the widened default.
361fn default_notice_text() -> String {
362    "\x1b[1mPathJail now opens your home directory:\x1b[0m agents may read and write \
363     anything below ~ except protected locations (~/.ssh, ~/.aws, ~/.config, every other \
364     dot folder, ~/Library, ~/AppData).\n  \x1b[2mPrevious behaviour (other projects \
365     read-only): lean-ctx config set path_jail_scope projects · active project only: \
366     lean-ctx config set path_jail_scope project\x1b[0m\n"
367        .to_string()
368}
369
370/// Tells a user once that the default scope widened in 3.11.3, on the first
371/// interactive command. Never for MCP, hooks or piped use, and never when the
372/// user chose a scope or turned the jail off: an explicit choice is kept.
373pub fn maybe_show_default_notice() {
374    use std::io::IsTerminal;
375    if !(std::io::stdin().is_terminal() && std::io::stderr().is_terminal())
376        || PathJailScope::explicit().is_some()
377        || crate::core::config::Config::load().path_jail == Some(false)
378    {
379        return;
380    }
381    let Ok(marker) =
382        crate::core::paths::state_dir().map(|dir| dir.join("path_jail_home_default_notice"))
383    else {
384        return;
385    };
386    if marker.exists() {
387        return;
388    }
389    eprint!("{}", default_notice_text());
390    eprintln!();
391    if let Some(parent) = marker.parent() {
392        let _ = std::fs::create_dir_all(parent);
393    }
394    let _ = std::fs::write(marker, "1\n");
395}
396
397#[cfg(test)]
398mod tests {
399    use super::*;
400
401    #[test]
402    fn parse_accepts_canonical_names_and_aliases() {
403        assert_eq!(PathJailScope::parse("home"), Some(PathJailScope::Home));
404        assert_eq!(
405            PathJailScope::parse(" Project "),
406            Some(PathJailScope::Project)
407        );
408        assert_eq!(PathJailScope::parse("strict"), Some(PathJailScope::Project));
409        assert_eq!(
410            PathJailScope::parse("projects"),
411            Some(PathJailScope::Projects)
412        );
413        assert_eq!(PathJailScope::parse("anything"), None);
414        assert_eq!(PathJailScope::default(), PathJailScope::Home);
415        for s in [
416            PathJailScope::Home,
417            PathJailScope::Projects,
418            PathJailScope::Project,
419        ] {
420            assert_eq!(PathJailScope::parse(s.as_str()), Some(s));
421        }
422    }
423
424    #[test]
425    fn the_notice_names_the_protected_zones_and_both_ways_back() {
426        let text = default_notice_text();
427        for needle in [
428            "~/.ssh",
429            "~/.aws",
430            "~/Library",
431            "path_jail_scope projects",
432            "path_jail_scope project",
433        ] {
434            assert!(text.contains(needle), "{needle}");
435        }
436    }
437
438    #[test]
439    fn home_zone_admits_code_and_protects_secrets() {
440        let home = Path::new("/home/u");
441        assert!(admits_below(Path::new("/home/u/code/repo/src/a.rs"), home));
442        assert!(admits_below(Path::new("/home/u/Documents/p"), home));
443
444        for protected in [
445            "/home/u/.ssh/id_ed25519",
446            "/home/u/.aws/credentials",
447            "/home/u/.config/gh/hosts.yml",
448            "/home/u/.zshrc",
449            "/home/u/.claude/projects/x/session.jsonl",
450            "/home/u/Library/Keychains/login.keychain-db",
451            "/home/u/AppData/Roaming/x",
452            "/home/u/NTUSER.DAT",
453        ] {
454            assert!(!admits_below(Path::new(protected), home), "{protected}");
455            assert!(protected_zone_in(Path::new(protected), home).is_some());
456        }
457        // The home dir itself and anything outside it are never admitted.
458        assert!(!admits_below(home, home));
459        assert!(!admits_below(Path::new("/etc/passwd"), home));
460        assert!(!admits_below(Path::new("/home/user2/x"), home));
461    }
462
463    #[test]
464    fn protected_zone_is_the_top_level_entry() {
465        let home = Path::new("/home/u");
466        assert_eq!(
467            protected_zone_in(Path::new("/home/u/.config/gh/hosts.yml"), home),
468            Some(PathBuf::from("/home/u/.config"))
469        );
470        // Dot entries deeper in the tree (a repo's .git) are ordinary code.
471        assert_eq!(
472            protected_zone_in(Path::new("/home/u/code/repo/.git/HEAD"), home),
473            None
474        );
475    }
476
477    /// End-to-end through the real jail with a throwaway `$HOME`: `home` opens
478    /// all of ~ for reading and writing except protected zones, `projects`
479    /// restores the read-only project scope, and `project` the single-project
480    /// boundary.
481    #[cfg(all(unix, not(feature = "no-jail")))]
482    #[test]
483    fn jail_admits_sibling_projects_but_not_protected_zones() {
484        let _iso = crate::core::data_dir::isolated_data_dir();
485        let tmp = tempfile::tempdir().unwrap();
486        let home = super::super::pathjail::canonicalize_secure(tmp.path()).join("home");
487        let (a, b, ssh) = (home.join("code/a"), home.join("code/b"), home.join(".ssh"));
488        for dir in [&a, &b, &ssh] {
489            std::fs::create_dir_all(dir).unwrap();
490        }
491        std::fs::create_dir_all(a.join(".git")).unwrap();
492        std::fs::write(b.join("Cargo.toml"), "[package]").unwrap();
493        std::fs::create_dir_all(b.join("src")).unwrap();
494        std::fs::write(b.join("src/lib.rs"), "x").unwrap();
495        std::fs::write(b.join("lib.rs"), "x").unwrap();
496        std::fs::write(ssh.join("id_ed25519"), "secret").unwrap();
497        let docs = home.join("Documents/Steuern");
498        std::fs::create_dir_all(&docs).unwrap();
499        std::fs::write(docs.join("2025.pdf"), "private").unwrap();
500        let outside = tmp.path().join("outside.txt");
501        std::fs::write(&outside, "x").unwrap();
502
503        let old_home = std::env::var_os("HOME");
504        crate::test_env::set_var("HOME", &home);
505        crate::test_env::remove_var("LEAN_CTX_PATH_JAIL_SCOPE");
506        let jail = super::super::pathjail::jail_path;
507
508        assert!(
509            jail(&b.join("lib.rs"), &a).is_ok(),
510            "sibling project under ~"
511        );
512        assert!(
513            jail(&b.join("src/lib.rs"), &a).is_ok(),
514            "nested file of a sibling project"
515        );
516        // The default `home` scope opens all of ~, loose files included.
517        assert!(
518            jail(&docs.join("2025.pdf"), &a).is_ok(),
519            "loose file under ~"
520        );
521        assert!(jail(&docs, &a).is_ok(), "a folder without a project");
522        assert!(jail(&home.join("code"), &a).is_ok(), "parent of projects");
523        let err = jail(&ssh.join("id_ed25519"), &a).unwrap_err().to_string();
524        assert!(err.contains("protected location"), "{err}");
525        let err = jail(&outside, &a).unwrap_err().to_string();
526        assert!(err.contains("outside your home directory"), "{err}");
527        let err = jail(&home, &a).unwrap_err().to_string();
528        assert!(err.contains("not a project root"), "{err}");
529
530        // A root or allow entry that merely contains a zone does not open it
531        // (dotfiles repo at ~); a root inside the zone does.
532        assert!(
533            jail(&ssh.join("id_ed25519"), &home).is_err(),
534            "zone is a deny"
535        );
536        assert!(
537            jail(&ssh.join("id_ed25519"), &ssh).is_ok(),
538            "root inside the zone"
539        );
540
541        // `home` writes wherever it reads; protected zones stay closed because
542        // every write resolves its path through the jail first.
543        let write = super::super::pathjail::enforce_writable;
544        assert!(write(&b.join("lib.rs")).is_ok(), "another project");
545        assert!(write(&docs.join("notes.md")).is_ok(), "a loose folder");
546        assert!(
547            jail(&ssh.join("authorized_keys"), &a).is_err(),
548            "protected zone"
549        );
550
551        // `projects`: reads across projects only, writes in the session's project.
552        crate::test_env::set_var("LEAN_CTX_PATH_JAIL_SCOPE", "projects");
553        assert!(jail(&b.join("lib.rs"), &a).is_ok(), "sibling project");
554        let err = jail(&docs.join("2025.pdf"), &a).unwrap_err().to_string();
555        assert!(err.contains("not inside a project"), "{err}");
556        assert!(jail(&home.join("code"), &a).is_err(), "parent of projects");
557        let err = write(&b.join("lib.rs")).unwrap_err();
558        assert!(
559            err.contains("for reading only") && err.contains("allow-path"),
560            "{err}"
561        );
562        assert!(write(&b.join(".git/hooks/pre-commit")).is_err());
563        register_session_root(&b.to_string_lossy());
564        assert!(write(&b.join("lib.rs")).is_ok(), "session root is writable");
565
566        crate::test_env::set_var("LEAN_CTX_PATH_JAIL_SCOPE", "project");
567        let err = jail(&b.join("lib.rs"), &a).unwrap_err().to_string();
568        assert!(
569            err.contains("path_jail_scope home") && err.contains("allow-path"),
570            "{err}"
571        );
572        crate::test_env::remove_var("LEAN_CTX_PATH_JAIL_SCOPE");
573
574        // An implausible $HOME never turns into "everything below /".
575        crate::test_env::set_var("HOME", "/");
576        assert!(
577            jail(&b.join("lib.rs"), &a).is_err(),
578            "HOME=/ falls back to the project"
579        );
580
581        match old_home {
582            Some(h) => crate::test_env::set_var("HOME", h),
583            None => crate::test_env::remove_var("HOME"),
584        }
585    }
586
587    #[test]
588    fn suggestion_prefers_the_enclosing_project() {
589        let tmp = tempfile::tempdir().unwrap();
590        let repo = tmp.path().join("repo");
591        std::fs::create_dir_all(repo.join("src/deep")).unwrap();
592        std::fs::create_dir_all(repo.join(".git")).unwrap();
593        let file = repo.join("src/deep/a.rs");
594        std::fs::write(&file, "x").unwrap();
595        assert_eq!(suggested_allow_dir(&file, None), repo);
596
597        let loose = tmp.path().join("loose");
598        std::fs::create_dir_all(&loose).unwrap();
599        assert_eq!(suggested_allow_dir(&loose, Some(tmp.path())), loose);
600    }
601}