Skip to main content

fallow_types/
path_guard.rs

1//! Refuse writes through a symlink that leaves a trusted directory.
2//!
3//! A cloned repository can commit a symlink where fallow writes a file, for
4//! example `.fallow/.gitignore` or the `.fallow` directory itself. A write
5//! through that link reaches a file outside the project. A link that resolves
6//! inside the base directory is safe and stays allowed, unless it leads into
7//! Git metadata or into an installed package (see
8//! [`is_protected_link_target`](crate::path_guard::is_protected_link_target)).
9
10use std::path::{Component, Path, PathBuf};
11
12/// The name of the Git metadata entry of a work tree.
13const GIT_ENTRY: &str = ".git";
14
15/// The name of the directory that package managers install into. Its files
16/// can be hard links into a store that other projects use too, so fallow
17/// does not write through a link into it.
18const PACKAGE_DIR: &str = "node_modules";
19
20/// The prefix of the line in a `.git` file that names the Git directory.
21const GITDIR_PREFIX: &str = "gitdir:";
22
23/// The file in a linked Git directory that names the common Git directory.
24const COMMONDIR_FILE: &str = "commondir";
25
26/// Why a write under a base directory is refused.
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28enum Refusal {
29    /// The path is not below the base, or a `..` takes it out of the base.
30    NotBelowBase,
31    /// A symlink resolves outside the base, or does not resolve.
32    LinkOutside,
33    /// A symlink resolves into Git metadata.
34    GitMetadata,
35    /// A symlink resolves into a `node_modules` directory.
36    Packages,
37    /// The target is not a regular file or a directory.
38    NotRegular,
39    /// An entry on the path cannot be read.
40    Unreadable,
41}
42
43impl Refusal {
44    /// The reason, as a sentence about `entry`.
45    fn describe(self, entry: &Path, base: &Path) -> String {
46        let entry = entry.display();
47        match self {
48            Self::NotBelowBase => format!("{entry} is not below {}", base.display()),
49            Self::LinkOutside => format!(
50                "{entry} is a symlink that resolves outside {} or does not resolve",
51                base.display()
52            ),
53            Self::GitMetadata => format!("{entry} is a symlink that resolves into Git metadata"),
54            Self::Packages => {
55                format!("{entry} is a symlink that resolves into a node_modules directory")
56            }
57            Self::NotRegular => format!("{entry} is not a regular file or directory"),
58            Self::Unreadable => format!("{entry} cannot be read"),
59        }
60    }
61}
62
63/// The entry that a write is refused at, and why.
64struct Refused {
65    entry: PathBuf,
66    reason: Refusal,
67}
68
69/// How a walk treats a `..` or `.` component.
70#[derive(Clone, Copy, PartialEq, Eq)]
71enum ParentSteps {
72    /// Refuse the path.
73    Refuse,
74    /// Apply the step to the resolved path, as the file system does.
75    Resolve,
76}
77
78/// The first entry below `base`, up to and including `path`, that is a
79/// symlink whose resolved target is outside the canonical `base`, or that
80/// [`is_protected_link_target`] refuses. A dangling link also counts, because
81/// its target can appear outside `base` later. A `base` that is itself a link
82/// into a protected directory returns `base`. An existing `path` that is not
83/// a regular file or a directory (a device, a named pipe or a socket) returns
84/// `path`. A path outside `base`, one with a `..` or `.` component, a `base`
85/// that does not resolve, or an entry whose metadata cannot be read returns
86/// that path. A missing entry ends the walk, because nothing below it exists
87/// yet.
88#[must_use]
89pub fn outside_link(base: &Path, path: &Path) -> Option<PathBuf> {
90    find_refusal(base, path, ParentSteps::Refuse).map(|refused| refused.entry)
91}
92
93/// The walk of [`outside_link`]. With [`ParentSteps::Resolve`], a `..` steps
94/// up from the resolved path, so a link before it is checked and the walk
95/// goes on below a missing entry.
96fn find_refusal(base: &Path, path: &Path, steps: ParentSteps) -> Option<Refused> {
97    let refuse = |entry: &Path, reason| {
98        Some(Refused {
99            entry: entry.to_path_buf(),
100            reason,
101        })
102    };
103    let Ok(relative) = path.strip_prefix(base) else {
104        return refuse(path, Refusal::NotBelowBase);
105    };
106    let Ok(canonical_base) = std::fs::canonicalize(base) else {
107        return refuse(path, Refusal::Unreadable);
108    };
109    if let Some(reason) = base_protected_link(base, &canonical_base) {
110        return refuse(base, reason);
111    }
112    let mut current = base.to_path_buf();
113    let mut resolved = canonical_base.clone();
114    for component in relative.components() {
115        let name = match component {
116            Component::Normal(name) => name,
117            Component::CurDir if steps == ParentSteps::Resolve => continue,
118            Component::ParentDir if steps == ParentSteps::Resolve => {
119                current.push(component);
120                resolved.pop();
121                if !resolved.starts_with(&canonical_base) {
122                    return refuse(&current, Refusal::NotBelowBase);
123                }
124                continue;
125            }
126            _ => return refuse(path, Refusal::NotBelowBase),
127        };
128        current.push(name);
129        match step_into(&canonical_base, &resolved, name, steps) {
130            Ok(Some(next)) => resolved = next,
131            Ok(None) => return None,
132            Err(reason) => return refuse(&current, reason),
133        }
134    }
135    is_special_file(&resolved).then(|| Refused {
136        entry: path.to_path_buf(),
137        reason: Refusal::NotRegular,
138    })
139}
140
141/// The resolved path after the entry `name` below the resolved `parent`.
142/// `None` ends the walk at a missing entry with [`ParentSteps::Refuse`].
143fn step_into(
144    canonical_base: &Path,
145    parent: &Path,
146    name: &std::ffi::OsStr,
147    steps: ParentSteps,
148) -> Result<Option<PathBuf>, Refusal> {
149    let candidate = parent.join(name);
150    match candidate.symlink_metadata() {
151        Ok(meta) if meta.file_type().is_symlink() => {
152            link_target_in(canonical_base, &candidate).map(Some)
153        }
154        Ok(_) => Ok(Some(candidate)),
155        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
156            Ok((steps == ParentSteps::Resolve).then_some(candidate))
157        }
158        Err(_) => Err(Refusal::Unreadable),
159    }
160}
161
162/// The canonical target of the symlink `link`, when it is inside the
163/// canonical base and not protected.
164fn link_target_in(canonical_base: &Path, link: &Path) -> Result<PathBuf, Refusal> {
165    let target = std::fs::canonicalize(link).map_err(|_| Refusal::LinkOutside)?;
166    if !target.starts_with(canonical_base) {
167        return Err(Refusal::LinkOutside);
168    }
169    match protected_kind(canonical_base, &target) {
170        Some(reason) => Err(reason),
171        None => Ok(target),
172    }
173}
174
175/// Whether `path` exists and is not a regular file or a directory.
176fn is_special_file(path: &Path) -> bool {
177    std::fs::metadata(path).is_ok_and(|meta| !meta.is_file() && !meta.is_dir())
178}
179
180/// Why `base` is refused when it is a symlink whose target is a protected
181/// directory, seen from the directory that contains the link.
182fn base_protected_link(base: &Path, canonical_base: &Path) -> Option<Refusal> {
183    if !base
184        .symlink_metadata()
185        .is_ok_and(|meta| meta.file_type().is_symlink())
186    {
187        return None;
188    }
189    let Some(parent) = base
190        .parent()
191        .and_then(|parent| std::fs::canonicalize(parent).ok())
192    else {
193        return Some(Refusal::Unreadable);
194    };
195    protected_kind(&parent, canonical_base)
196}
197
198/// Whether a symlink whose canonical target is `resolved` leads into Git
199/// metadata or into an installed package, so fallow must not write through
200/// it. `within` is the canonical directory the link was found in.
201///
202/// The target is protected when the part of it below `within` (all of it when
203/// it is not below `within`) has a `.git` component (in any case) or a
204/// `node_modules` component, or when [`GitDirs::holds`] it for the work tree
205/// that contains `within` and the work trees above it. A `.git` file can
206/// name a Git directory with any name, so the second test covers a linked
207/// worktree, a submodule, the superproject of a submodule and a separate Git
208/// directory.
209///
210/// The rule is for links only. A direct path into `.git`, such as a hook that
211/// `fallow hooks install` writes on purpose, does not go through it.
212#[must_use]
213pub fn is_protected_link_target(within: &Path, resolved: &Path) -> bool {
214    protected_kind(within, resolved).is_some()
215}
216
217/// The refusal of [`is_protected_link_target`], or `None`.
218fn protected_kind(within: &Path, resolved: &Path) -> Option<Refusal> {
219    let below = resolved.strip_prefix(within).unwrap_or(resolved);
220    let names = || {
221        below.components().filter_map(|component| match component {
222            Component::Normal(name) => name.to_str(),
223            _ => None,
224        })
225    };
226    if names().any(|name| name.eq_ignore_ascii_case(PACKAGE_DIR)) {
227        return Some(Refusal::Packages);
228    }
229    if names().any(|name| name.eq_ignore_ascii_case(GIT_ENTRY)) {
230        return Some(Refusal::GitMetadata);
231    }
232    GitDirs::of(within)
233        .holds(resolved)
234        .then_some(Refusal::GitMetadata)
235}
236
237/// The canonical Git directories of the work tree that contains a directory
238/// and of each work tree above it: for each, the Git directory and the common
239/// Git directory. The directories can be outside the work trees, for a
240/// separate Git directory, a worktree of a bare repository, or a submodule
241/// whose superproject keeps its Git directory elsewhere.
242#[derive(Clone, Debug, Default)]
243pub struct GitDirs {
244    /// The canonical top of the nearest work tree.
245    work_tree: Option<PathBuf>,
246    dirs: Vec<PathBuf>,
247    /// A `.git` file or a `commondir` file exists but cannot be read or
248    /// resolved, so a Git directory is not known.
249    unknown: bool,
250}
251
252impl GitDirs {
253    /// The Git directories of the work tree that contains `dir` and of each
254    /// enclosing work tree, such as the superproject of a submodule. Empty
255    /// when no ancestor of `dir` has a `.git` entry, or when each entry names
256    /// no Git directory that exists.
257    #[must_use]
258    pub fn of(dir: &Path) -> Self {
259        let Some(top) = work_tree_top(dir) else {
260            return Self::default();
261        };
262        let mut git_dirs = Self {
263            work_tree: std::fs::canonicalize(top).ok(),
264            ..Self::default()
265        };
266        let mut next = Some(top);
267        while let Some(tree) = next {
268            git_dirs.add_entry(&tree.join(GIT_ENTRY));
269            next = tree.parent().and_then(work_tree_top);
270        }
271        git_dirs
272    }
273
274    /// Add the Git directory and the common Git directory that the `.git`
275    /// entry `entry` stands for.
276    fn add_entry(&mut self, entry: &Path) {
277        let git_dir = match read_git_entry(entry) {
278            Ok(Some(git_dir)) => git_dir,
279            Ok(None) => return,
280            Err(Unreadable) => {
281                self.unknown = true;
282                return;
283            }
284        };
285        let common = common_dir_of(&git_dir);
286        self.add(git_dir);
287        match common {
288            Some(common) => self.add(common),
289            None => self.unknown = true,
290        }
291    }
292
293    fn add(&mut self, dir: PathBuf) {
294        if !self.dirs.contains(&dir) {
295            self.dirs.push(dir);
296        }
297    }
298
299    /// Whether the canonical `path` is in one of the Git directories. A
300    /// path in the work tree does not count when the work tree itself is in
301    /// that Git directory, as for a worktree inside a bare repository. When
302    /// a Git directory is not known, every path counts.
303    #[must_use]
304    pub fn holds(&self, path: &Path) -> bool {
305        if self.unknown {
306            return true;
307        }
308        let in_work_tree_of = |dir: &Path| {
309            self.work_tree
310                .as_deref()
311                .is_some_and(|tree| tree.starts_with(dir) && path.starts_with(tree))
312        };
313        self.dirs
314            .iter()
315            .any(|dir| path.starts_with(dir) && !in_work_tree_of(dir))
316    }
317}
318
319/// The nearest ancestor of `dir`, `dir` included, with a `.git` entry. The
320/// entry counts when it exists as an entry, also as a dangling link.
321#[must_use]
322pub fn work_tree_top(dir: &Path) -> Option<&Path> {
323    dir.ancestors()
324        .find(|ancestor| ancestor.join(GIT_ENTRY).symlink_metadata().is_ok())
325}
326
327/// A `.git` entry or a `commondir` file that exists but cannot be read,
328/// is not a regular file, or names no Git directory.
329struct Unreadable;
330
331/// The size limit for a `.git` file or a `commondir` file. Git writes one
332/// short line, so a larger file is not Git metadata.
333const GIT_FILE_MAX_BYTES: u64 = 64 * 1024;
334
335/// The canonical Git directory that the `.git` entry `entry` stands for: the
336/// directory itself, or the directory that a `.git` file names.
337fn git_dir_of_entry(entry: &Path) -> Option<PathBuf> {
338    read_git_entry(entry).ok().flatten()
339}
340
341/// [`git_dir_of_entry`] that tells a missing entry from one that cannot be
342/// read. `Ok(None)` when the entry does not resolve, or when it names a Git
343/// directory that does not exist.
344fn read_git_entry(entry: &Path) -> Result<Option<PathBuf>, Unreadable> {
345    let meta = match std::fs::metadata(entry) {
346        Ok(meta) => meta,
347        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
348        Err(_) => return Err(Unreadable),
349    };
350    if meta.is_dir() {
351        return std::fs::canonicalize(entry)
352            .map(Some)
353            .map_err(|_| Unreadable);
354    }
355    let text = crate::read_guard::read_to_string_bounded(entry, GIT_FILE_MAX_BYTES)
356        .map_err(|_| Unreadable)?;
357    let named = text
358        .lines()
359        .find_map(|line| line.strip_prefix(GITDIR_PREFIX))
360        .map(str::trim)
361        .filter(|named| !named.is_empty())
362        .ok_or(Unreadable)?;
363    let parent = entry.parent().ok_or(Unreadable)?;
364    Ok(std::fs::canonicalize(parent.join(named)).ok())
365}
366
367/// The canonical common Git directory of the Git directory `git_dir`: the
368/// directory that its `commondir` file names, or `git_dir` itself when it
369/// has no `commondir` file. `None` when the file cannot be read or names a
370/// directory that does not resolve.
371fn common_dir_of(git_dir: &Path) -> Option<PathBuf> {
372    match crate::read_guard::read_to_string_bounded(
373        &git_dir.join(COMMONDIR_FILE),
374        GIT_FILE_MAX_BYTES,
375    ) {
376        Ok(text) => std::fs::canonicalize(git_dir.join(text.trim())).ok(),
377        Err(error) if error.is_not_found() => Some(git_dir.to_path_buf()),
378        Err(_) => None,
379    }
380}
381
382/// The directory that cache writes must stay in.
383///
384/// - A cache directory inside the project root is checked from the root, so
385///   a committed `.fallow` link is refused.
386/// - A cache directory in the same Git repository as the root, but not below
387///   the root, is checked from the top of its work tree. This covers a cache
388///   above a subdirectory root, and the cache in the checkout of an audit
389///   that runs in a linked worktree (`audit --staged`, the base snapshot).
390/// - Any other cache directory comes from the user, such as
391///   `FALLOW_CACHE_DIR` on a CI runner, so only the entries below it are
392///   checked.
393///
394/// A `..` in the cache directory is resolved by text first, so
395/// `FALLOW_CACHE_DIR=../shared` counts as a directory outside the root.
396#[must_use]
397pub fn cache_write_base(root: &Path, cache_dir: &Path) -> PathBuf {
398    let normalized = lexically_normalized(cache_dir);
399    if normalized.starts_with(root) {
400        return root.to_path_buf();
401    }
402    same_repository_top(root, &normalized).unwrap_or_else(|| cache_dir.to_path_buf())
403}
404
405/// The top of a work tree of the repository that contains `root`, as an
406/// ancestor of `cache_dir`, when `cache_dir` is below one.
407///
408/// A work tree counts when its `.git` entry (a directory or a file) has the
409/// same common Git directory as the work tree of the root. This covers the
410/// main checkout, a linked worktree, a submodule and a worktree of a bare
411/// repository. An ancestor that is a symlink never counts.
412///
413/// When more than one ancestor counts, the lowest one is the top, so a link
414/// in a worktree inside the main checkout is checked from that worktree and
415/// cannot lead up into the main checkout. An ancestor that is below a
416/// symlink, seen from the highest ancestor that counts, is skipped, so the
417/// base is never reached through a link. The links below the top are checked
418/// later, from the top.
419fn same_repository_top(root: &Path, cache_dir: &Path) -> Option<PathBuf> {
420    let root_common = common_dir_of_work_tree(work_tree_top(root)?)?;
421    let tops: Vec<&Path> = cache_dir
422        .ancestors()
423        .skip(1)
424        .filter(|ancestor| {
425            ancestor
426                .symlink_metadata()
427                .is_ok_and(|meta| !meta.file_type().is_symlink())
428                && ancestor.join(GIT_ENTRY).symlink_metadata().is_ok()
429                && common_dir_of_work_tree(ancestor).as_ref() == Some(&root_common)
430        })
431        .collect();
432    let highest = *tops.last()?;
433    tops.into_iter()
434        .find(|top| !has_link_between(highest, top))
435        .map(Path::to_path_buf)
436}
437
438/// Whether an entry below `upper`, down to and including `lower`, is a
439/// symlink or cannot be read. `lower` must be below `upper`.
440fn has_link_between(upper: &Path, lower: &Path) -> bool {
441    let Ok(relative) = lower.strip_prefix(upper) else {
442        return true;
443    };
444    let mut current = upper.to_path_buf();
445    relative.components().any(|component| {
446        current.push(component);
447        !current
448            .symlink_metadata()
449            .is_ok_and(|meta| !meta.file_type().is_symlink())
450    })
451}
452
453/// The canonical common Git directory of the work tree at `top`.
454fn common_dir_of_work_tree(top: &Path) -> Option<PathBuf> {
455    git_dir_of_entry(&top.join(GIT_ENTRY)).and_then(|git_dir| common_dir_of(&git_dir))
456}
457
458/// `path` with each `..` applied to the component before it, and each `.`
459/// dropped, without a file system read.
460#[must_use]
461pub fn lexically_normalized(path: &Path) -> PathBuf {
462    let mut normalized = PathBuf::new();
463    for component in path.components() {
464        match component {
465            Component::CurDir => {}
466            Component::ParentDir => {
467                normalized.pop();
468            }
469            other => normalized.push(other),
470        }
471    }
472    normalized
473}
474
475/// Fail when a write to `path` would follow a symlink that leaves `base`.
476///
477/// Call this before each create, write, rename or delete under a cache
478/// directory, with the base from [`cache_write_base`]. A base that does not
479/// exist yet has no link below it, so the first save into a new cache
480/// directory passes. A dangling link at the base itself exists, so it is
481/// still checked. A `..` in `path` is applied to the resolved path, as the
482/// file system does, so `FALLOW_CACHE_DIR=../shared` from a subdirectory
483/// root works and a link before the `..` is still checked.
484///
485/// # Errors
486///
487/// Returns a `PermissionDenied` error that names the refused entry and the
488/// reason.
489pub fn ensure_no_outside_link(base: &Path, path: &Path) -> std::io::Result<()> {
490    if base.symlink_metadata().is_err() {
491        return Ok(());
492    }
493    match find_refusal(base, path, ParentSteps::Resolve) {
494        None => Ok(()),
495        Some(refused) => Err(std::io::Error::new(
496            std::io::ErrorKind::PermissionDenied,
497            format!(
498                "refusing to write {}: {}",
499                path.display(),
500                refused.reason.describe(&refused.entry, base)
501            ),
502        )),
503    }
504}
505
506/// A cache directory and the directory that its writes must stay in.
507///
508/// Every cache writer takes this type instead of a bare directory, so a
509/// writer cannot skip the symlink check.
510#[derive(Clone, Copy, Debug)]
511pub struct CacheTarget<'a> {
512    dir: &'a Path,
513    /// The cache directory that the base is computed from. A subdirectory
514    /// from [`Self::with_dir`] keeps the base of its parent.
515    anchor: &'a Path,
516    /// The project root, or `None` when the anchor is its own base.
517    root: Option<&'a Path>,
518}
519
520impl<'a> CacheTarget<'a> {
521    /// The cache directory `dir` of the project at `root`.
522    #[must_use]
523    pub const fn new(root: &'a Path, dir: &'a Path) -> Self {
524        Self {
525            dir,
526            anchor: dir,
527            root: Some(root),
528        }
529    }
530
531    /// A cache directory that is its own base, such as a directory that the
532    /// user chose.
533    #[must_use]
534    pub const fn inside(dir: &'a Path) -> Self {
535        Self {
536            dir,
537            anchor: dir,
538            root: None,
539        }
540    }
541
542    /// The cache directory.
543    #[must_use]
544    pub const fn dir(&self) -> &'a Path {
545        self.dir
546    }
547
548    /// The same base with `dir` as the cache directory, for a subdirectory.
549    #[must_use]
550    pub const fn with_dir(&self, dir: &'a Path) -> Self {
551        Self {
552            dir,
553            anchor: self.anchor,
554            root: self.root,
555        }
556    }
557
558    /// The directory that the writes must stay in, from
559    /// [`cache_write_base`].
560    #[must_use]
561    pub fn write_base(&self) -> PathBuf {
562        self.root.map_or_else(
563            || self.anchor.to_path_buf(),
564            |root| cache_write_base(root, self.anchor),
565        )
566    }
567
568    /// Fail when a write to `path` would follow a symlink that leaves the
569    /// base.
570    ///
571    /// # Errors
572    ///
573    /// Returns the error of [`ensure_no_outside_link`].
574    pub fn check(&self, path: &Path) -> std::io::Result<()> {
575        ensure_no_outside_link(&self.write_base(), path)
576    }
577
578    /// Create the cache directory and replace the file `name` in it with
579    /// `data` through [`crate::atomic_file::write_atomic`], after the
580    /// symlink check.
581    ///
582    /// # Errors
583    ///
584    /// Returns the error of the check, of the directory creation, or of the
585    /// write.
586    pub fn write_file(&self, name: &str, data: &[u8]) -> std::io::Result<()> {
587        let path = self.dir.join(name);
588        self.check(&path)?;
589        std::fs::create_dir_all(self.dir)?;
590        crate::atomic_file::write_atomic(&path, data)
591    }
592
593    /// Write `.gitignore` with `*`, so the cache directory is never
594    /// committed. An equal file stays as it is.
595    ///
596    /// # Errors
597    ///
598    /// Returns the error of [`Self::write_file`].
599    pub fn write_gitignore(&self) -> std::io::Result<()> {
600        let path = self.dir.join(".gitignore");
601        self.check(&path)?;
602        if std::fs::read(&path).is_ok_and(|content| content == b"*\n") {
603            return Ok(());
604        }
605        self.write_file(".gitignore", b"*\n")
606    }
607}
608
609#[cfg(all(test, unix, not(miri)))]
610mod tests {
611    use super::*;
612    use std::os::unix::fs::symlink;
613
614    struct Fixture {
615        _dir: tempfile::TempDir,
616        root: PathBuf,
617        outside: PathBuf,
618    }
619
620    fn fixture() -> Fixture {
621        let dir = tempfile::tempdir().expect("tempdir");
622        let root = dir.path().join("project");
623        let outside = dir.path().join("outside");
624        std::fs::create_dir_all(&root).expect("root");
625        std::fs::create_dir_all(&outside).expect("outside");
626        Fixture {
627            _dir: dir,
628            root,
629            outside,
630        }
631    }
632
633    #[test]
634    fn a_plain_path_passes() {
635        let f = fixture();
636        let path = f.root.join(".fallow/cache/x/cache.bin");
637        assert_eq!(outside_link(&f.root, &path), None);
638        assert!(ensure_no_outside_link(&f.root, &path).is_ok());
639    }
640
641    #[test]
642    fn a_linked_cache_dir_is_refused() {
643        let f = fixture();
644        symlink(&f.outside, f.root.join(".fallow")).expect("link");
645        let path = f.root.join(".fallow/.gitignore");
646        assert_eq!(outside_link(&f.root, &path), Some(f.root.join(".fallow")));
647        let error = ensure_no_outside_link(&f.root, &path).expect_err("refused");
648        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
649    }
650
651    #[test]
652    fn a_dangling_file_link_is_refused() {
653        let f = fixture();
654        std::fs::create_dir_all(f.root.join(".fallow")).expect("cache");
655        let link = f.root.join(".fallow/.gitignore");
656        symlink(f.outside.join("missing"), &link).expect("link");
657        assert_eq!(outside_link(&f.root, &link), Some(link.clone()));
658        let error = ensure_no_outside_link(&f.root, &link).expect_err("refused");
659        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
660    }
661
662    #[test]
663    fn a_link_inside_the_base_passes() {
664        let f = fixture();
665        std::fs::create_dir_all(f.root.join("build/cache")).expect("target");
666        symlink(f.root.join("build/cache"), f.root.join(".fallow")).expect("link");
667        assert_eq!(
668            outside_link(&f.root, &f.root.join(".fallow/cache.bin")),
669            None
670        );
671    }
672
673    #[test]
674    fn a_path_outside_the_base_is_refused() {
675        let f = fixture();
676        let path = f.outside.join("cache.bin");
677        assert_eq!(outside_link(&f.root, &path), Some(path));
678    }
679
680    #[test]
681    fn the_base_follows_where_the_cache_dir_is() {
682        let root = Path::new("/p");
683        assert_eq!(cache_write_base(root, Path::new("/p/.fallow")), root);
684        assert_eq!(
685            cache_write_base(root, Path::new("/ci/cache")),
686            Path::new("/ci/cache")
687        );
688    }
689
690    #[test]
691    fn a_target_writes_the_file_and_the_gitignore() {
692        let f = fixture();
693        let dir = f.root.join(".fallow/cache");
694        let target = CacheTarget::new(&f.root, &dir);
695        target.write_gitignore().expect("gitignore");
696        target.write_file("cache.bin", b"data").expect("file");
697        assert_eq!(std::fs::read(dir.join(".gitignore")).expect("read"), b"*\n");
698        assert_eq!(std::fs::read(dir.join("cache.bin")).expect("read"), b"data");
699    }
700
701    #[test]
702    fn a_target_refuses_a_linked_cache_dir_and_writes_nothing() {
703        let f = fixture();
704        symlink(&f.outside, f.root.join(".fallow")).expect("link");
705        let dir = f.root.join(".fallow");
706        let target = CacheTarget::new(&f.root, &dir);
707        assert!(target.write_gitignore().is_err());
708        assert!(target.write_file("cache.bin", b"data").is_err());
709        assert_eq!(std::fs::read_dir(&f.outside).expect("outside").count(), 0);
710    }
711
712    #[test]
713    fn a_target_refuses_a_dangling_gitignore_link() {
714        let f = fixture();
715        let dir = f.root.join(".fallow");
716        std::fs::create_dir_all(&dir).expect("cache");
717        symlink(f.outside.join("victim"), dir.join(".gitignore")).expect("link");
718        assert!(CacheTarget::new(&f.root, &dir).write_gitignore().is_err());
719        assert!(!f.outside.join("victim").exists());
720    }
721
722    #[test]
723    fn a_relative_cache_dir_above_the_root_is_its_own_base() {
724        let root = Path::new("/p/project");
725        let shared = Path::new("/p/project/../shared");
726        assert_eq!(cache_write_base(root, shared), shared);
727        let inside = Path::new("/p/project/sub/../.fallow");
728        assert_eq!(cache_write_base(root, inside), root);
729    }
730
731    #[test]
732    fn a_relative_cache_dir_above_the_root_gets_its_cache() {
733        let f = fixture();
734        let dir = f.root.join("../shared");
735        let target = CacheTarget::new(&f.root, &dir);
736        target.write_file("cache.bin", b"data").expect("file");
737        assert!(f.outside.join("../shared/cache.bin").exists());
738    }
739
740    #[test]
741    fn a_missing_base_passes_the_check() {
742        let f = fixture();
743        let base = f.outside.join("new");
744        assert!(ensure_no_outside_link(&base, &base.join("cache.bin")).is_ok());
745    }
746
747    #[test]
748    fn a_target_writes_into_a_new_cache_dir() {
749        let f = fixture();
750        let dir = f.outside.join("new/cache");
751        CacheTarget::inside(&dir)
752            .write_gitignore()
753            .expect("gitignore");
754        assert!(dir.join(".gitignore").exists());
755    }
756
757    #[test]
758    fn a_dir_link_into_the_git_dir_below_the_base_is_refused() {
759        let f = fixture();
760        std::fs::create_dir_all(f.root.join(".git")).expect("git dir");
761        symlink(f.root.join(".git"), f.root.join("conf")).expect("link");
762        let path = f.root.join("conf/config");
763        assert_eq!(outside_link(&f.root, &path), Some(f.root.join("conf")));
764        let error = ensure_no_outside_link(&f.root, &path).expect_err("refused");
765        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
766        assert!(error.to_string().contains("Git metadata"), "{error}");
767    }
768
769    #[test]
770    fn a_file_link_into_a_nested_git_dir_is_refused() {
771        let f = fixture();
772        std::fs::create_dir_all(f.root.join("sub/.GIT")).expect("git dir");
773        std::fs::write(f.root.join("sub/.GIT/HEAD"), "ref").expect("head");
774        symlink(f.root.join("sub/.GIT/HEAD"), f.root.join("head")).expect("link");
775        let path = f.root.join("head");
776        assert_eq!(outside_link(&f.root, &path), Some(path));
777    }
778
779    #[test]
780    fn a_link_into_the_dir_that_a_git_file_names_is_refused() {
781        let f = fixture();
782        std::fs::create_dir_all(f.root.join("meta")).expect("meta");
783        std::fs::write(f.root.join(".git"), "gitdir: meta\n").expect("git file");
784        symlink(f.root.join("meta"), f.root.join("m")).expect("link");
785        let path = f.root.join("m/config");
786        assert_eq!(outside_link(&f.root, &path), Some(f.root.join("m")));
787    }
788
789    #[test]
790    fn a_base_that_links_into_the_git_dir_is_refused() {
791        let f = fixture();
792        std::fs::create_dir_all(f.root.join(".git/hooks")).expect("git dir");
793        let base = f.root.join("alias");
794        symlink(f.root.join(".git/hooks"), &base).expect("link");
795        let path = base.join("pre-commit");
796        assert_eq!(outside_link(&base, &path), Some(base));
797    }
798
799    #[test]
800    fn a_plain_path_into_the_git_dir_passes() {
801        let f = fixture();
802        std::fs::create_dir_all(f.root.join(".git/hooks")).expect("git dir");
803        let path = f.root.join(".git/hooks/pre-commit");
804        assert_eq!(outside_link(&f.root, &path), None);
805    }
806
807    #[test]
808    fn a_link_into_node_modules_is_refused() {
809        let f = fixture();
810        std::fs::create_dir_all(f.root.join("node_modules/left-pad")).expect("package");
811        std::fs::write(f.root.join("node_modules/left-pad/index.js"), "x").expect("file");
812        let path = f.root.join(".gitignore");
813        symlink(f.root.join("node_modules/left-pad/index.js"), &path).expect("link");
814        assert_eq!(outside_link(&f.root, &path), Some(path));
815    }
816
817    #[test]
818    fn a_named_pipe_target_is_refused() {
819        let f = fixture();
820        let fifo = f.root.join("report");
821        let made = std::process::Command::new("mkfifo")
822            .arg(&fifo)
823            .status()
824            .expect("run mkfifo");
825        assert!(made.success());
826        assert_eq!(outside_link(&f.root, &fifo), Some(fifo));
827    }
828
829    /// A staged audit runs in a linked worktree outside the checkout and
830    /// keeps its cache in the checkout. A link at the cache directory of the
831    /// checkout must not take the writes out of the checkout.
832    #[test]
833    fn a_cache_dir_in_the_checkout_of_a_linked_worktree_is_checked_from_the_checkout() {
834        let f = fixture();
835        let host = f.root.join("host");
836        std::fs::create_dir_all(host.join(".git/worktrees/staged")).expect("host git");
837        std::fs::write(host.join(".git/worktrees/staged/commondir"), "../..\n").expect("common");
838        std::fs::create_dir_all(host.join("packages/app")).expect("host app");
839        let staged = f.root.join("staged");
840        std::fs::create_dir_all(staged.join("packages/app")).expect("staged app");
841        std::fs::write(
842            staged.join(".git"),
843            format!("gitdir: {}\n", host.join(".git/worktrees/staged").display()),
844        )
845        .expect("git file");
846        symlink(&f.outside, host.join("packages/app/buildcache")).expect("link");
847        let root = staged.join("packages/app");
848        let dir = host.join("packages/app/buildcache");
849        let target = CacheTarget::new(&root, &dir);
850        assert!(target.check(&dir.join("cache.bin")).is_err());
851        assert!(target.write_file("cache.bin", b"data").is_err());
852        assert_eq!(std::fs::read_dir(&f.outside).expect("outside").count(), 0);
853    }
854
855    /// A folder in the checkout that links to another Git checkout does not
856    /// make that checkout the base of the cache.
857    #[test]
858    fn a_cache_dir_through_a_link_to_another_checkout_is_checked_from_the_checkout() {
859        let f = fixture();
860        let host = f.root.join("host");
861        std::fs::create_dir_all(host.join(".git/worktrees/staged")).expect("host git");
862        std::fs::write(host.join(".git/worktrees/staged/commondir"), "../..\n").expect("common");
863        std::fs::create_dir_all(host.join("packages/app")).expect("host app");
864        let other = f.outside.join("other");
865        std::fs::create_dir_all(other.join(".git")).expect("other git");
866        symlink(&other, host.join("packages/app/link")).expect("link");
867        let staged = f.root.join("staged");
868        std::fs::create_dir_all(staged.join("packages/app")).expect("staged app");
869        std::fs::write(
870            staged.join(".git"),
871            format!("gitdir: {}\n", host.join(".git/worktrees/staged").display()),
872        )
873        .expect("git file");
874        let root = staged.join("packages/app");
875        let dir = host.join("packages/app/link/cache");
876        let target = CacheTarget::new(&root, &dir);
877        assert!(target.write_file("cache.bin", b"data").is_err());
878        assert!(!other.join("cache").exists());
879    }
880
881    /// A staged audit of a linked worktree keeps its cache in that worktree,
882    /// not below the main checkout. A link in it is still checked.
883    #[test]
884    fn a_cache_dir_in_a_linked_worktree_host_is_checked_from_the_worktree() {
885        let f = fixture();
886        let main = f.root.join("repo");
887        std::fs::create_dir_all(main.join(".git/worktrees/feature")).expect("main git");
888        std::fs::create_dir_all(main.join(".git/worktrees/staged")).expect("staged git");
889        for name in ["feature", "staged"] {
890            std::fs::write(
891                main.join(format!(".git/worktrees/{name}/commondir")),
892                "../..\n",
893            )
894            .expect("common");
895        }
896        let host = f.root.join("wt/feature");
897        std::fs::create_dir_all(host.join("packages/app")).expect("host app");
898        std::fs::write(
899            host.join(".git"),
900            format!(
901                "gitdir: {}\n",
902                main.join(".git/worktrees/feature").display()
903            ),
904        )
905        .expect("host git file");
906        let staged = f.root.join("staged");
907        std::fs::create_dir_all(staged.join("packages/app")).expect("staged app");
908        std::fs::write(
909            staged.join(".git"),
910            format!("gitdir: {}\n", main.join(".git/worktrees/staged").display()),
911        )
912        .expect("staged git file");
913        symlink(&f.outside, host.join("packages/app/build")).expect("link");
914        let root = staged.join("packages/app");
915        let dir = host.join("packages/app/build/cache");
916        assert!(
917            CacheTarget::new(&root, &dir)
918                .write_file("cache.bin", b"data")
919                .is_err()
920        );
921        assert_eq!(std::fs::read_dir(&f.outside).expect("outside").count(), 0);
922    }
923
924    /// The same for a submodule, whose Git directory is below the Git
925    /// directory of the superproject.
926    #[test]
927    fn a_cache_dir_in_a_submodule_host_is_checked_from_the_submodule() {
928        let f = fixture();
929        let modules = f.root.join("super/.git/modules/sub");
930        std::fs::create_dir_all(modules.join("worktrees/staged")).expect("module git");
931        std::fs::write(modules.join("worktrees/staged/commondir"), "../..\n").expect("common");
932        let host = f.root.join("super/sub");
933        std::fs::create_dir_all(host.join("packages/app")).expect("host app");
934        std::fs::write(
935            host.join(".git"),
936            format!("gitdir: {}\n", modules.display()),
937        )
938        .expect("host git file");
939        let staged = f.root.join("staged");
940        std::fs::create_dir_all(staged.join("packages/app")).expect("staged app");
941        std::fs::write(
942            staged.join(".git"),
943            format!("gitdir: {}\n", modules.join("worktrees/staged").display()),
944        )
945        .expect("staged git file");
946        symlink(&f.outside, host.join("packages/app/build")).expect("link");
947        let root = staged.join("packages/app");
948        let dir = host.join("packages/app/build/cache");
949        assert!(
950            CacheTarget::new(&root, &dir)
951                .write_file("cache.bin", b"data")
952                .is_err()
953        );
954        assert_eq!(std::fs::read_dir(&f.outside).expect("outside").count(), 0);
955    }
956
957    /// Write a `.git` file at `top` that names the linked Git directory
958    /// `name` below the common Git directory `common`, with its `commondir`.
959    fn linked_work_tree(common: &Path, top: &Path, name: &str) {
960        let git_dir = common.join("worktrees").join(name);
961        std::fs::create_dir_all(&git_dir).expect("linked git dir");
962        std::fs::write(git_dir.join("commondir"), "../..\n").expect("common");
963        std::fs::create_dir_all(top).expect("work tree");
964        std::fs::write(top.join(".git"), format!("gitdir: {}\n", git_dir.display()))
965            .expect("git file");
966    }
967
968    /// A linked worktree can live inside the main checkout. A link in it
969    /// that leads up into the main checkout must not take the cache writes
970    /// of a staged audit there.
971    #[test]
972    fn a_link_from_a_worktree_inside_the_main_checkout_up_into_it_is_refused() {
973        let f = fixture();
974        let repo = f.root.join("repo");
975        std::fs::create_dir_all(repo.join(".git")).expect("main git");
976        let host = repo.join(".worktrees/feature");
977        linked_work_tree(&repo.join(".git"), &host, "feature");
978        let staged = f.root.join("staged");
979        linked_work_tree(&repo.join(".git"), &staged, "staged");
980        symlink("../..", host.join("build")).expect("link");
981        let dir = host.join("build/cache");
982        for root in [&staged, &host] {
983            let target = CacheTarget::new(root, &dir);
984            assert!(target.write_gitignore().is_err());
985            assert!(target.write_file("cache.bin", b"data").is_err());
986        }
987        assert!(!repo.join("cache").exists());
988    }
989
990    /// The same for two worktrees of a bare repository, one inside the
991    /// other. The bare repository has no work tree of its own.
992    #[test]
993    fn a_link_from_a_nested_worktree_of_a_bare_repository_is_refused() {
994        let f = fixture();
995        let bare = f.root.join("repo.git");
996        let outer = f.root.join("trees/main");
997        linked_work_tree(&bare, &outer, "main");
998        let host = outer.join(".worktrees/feature");
999        linked_work_tree(&bare, &host, "feature");
1000        let staged = f.root.join("staged");
1001        linked_work_tree(&bare, &staged, "staged");
1002        symlink("../..", host.join("build")).expect("link");
1003        let dir = host.join("build/cache");
1004        assert!(
1005            CacheTarget::new(&staged, &dir)
1006                .write_file("cache.bin", b"data")
1007                .is_err()
1008        );
1009        assert!(!outer.join("cache").exists());
1010    }
1011
1012    /// A work tree that is reached through a link is never the base, so the
1013    /// link is checked from the work tree above it.
1014    #[test]
1015    fn a_work_tree_behind_a_link_is_not_the_base() {
1016        let f = fixture();
1017        let repo = f.root.join("repo");
1018        std::fs::create_dir_all(repo.join(".git")).expect("main git");
1019        let host = f.root.join("host");
1020        linked_work_tree(&repo.join(".git"), &host, "host");
1021        let other = f.outside.join("other");
1022        linked_work_tree(&repo.join(".git"), &other, "other");
1023        linked_work_tree(&repo.join(".git"), &other.join("nested"), "nested");
1024        let staged = f.root.join("staged");
1025        linked_work_tree(&repo.join(".git"), &staged, "staged");
1026        symlink(&other, host.join("shared")).expect("link");
1027        let dir = host.join("shared/nested/cache");
1028        assert!(
1029            CacheTarget::new(&staged, &dir)
1030                .write_file("cache.bin", b"data")
1031                .is_err()
1032        );
1033        assert!(!other.join("nested/cache").exists());
1034    }
1035
1036    /// A worktree of a bare repository lies inside the common Git directory.
1037    /// Its files are not Git metadata, but the Git directory still is.
1038    #[test]
1039    fn a_worktree_inside_a_bare_repository_is_not_git_metadata() {
1040        let f = fixture();
1041        let bare = f.root.join("proj.git");
1042        let main = bare.join("main");
1043        linked_work_tree(&bare, &main, "main");
1044        std::fs::create_dir_all(main.join("src")).expect("src");
1045        std::fs::create_dir_all(bare.join("hooks")).expect("hooks");
1046        let canonical_main = std::fs::canonicalize(&main).expect("main");
1047        let canonical_bare = std::fs::canonicalize(&bare).expect("bare");
1048        assert!(!is_protected_link_target(
1049            &canonical_main,
1050            &canonical_main.join("src/a.ts")
1051        ));
1052        assert!(is_protected_link_target(
1053            &canonical_main,
1054            &canonical_bare.join("hooks/pre-commit")
1055        ));
1056        assert!(is_protected_link_target(
1057            &canonical_main,
1058            &canonical_bare.join("worktrees/main/HEAD")
1059        ));
1060        std::fs::create_dir_all(main.join("build/cache")).expect("cache");
1061        symlink("build/cache", main.join(".fallow")).expect("link");
1062        let dir = main.join(".fallow");
1063        CacheTarget::new(&main, &dir)
1064            .write_file("cache.bin", b"data")
1065            .expect("file");
1066        symlink(bare.join("hooks"), main.join("hooks")).expect("hooks link");
1067        let error =
1068            ensure_no_outside_link(&main, &main.join("hooks/pre-commit")).expect_err("refused");
1069        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1070    }
1071
1072    /// A `commondir` file that cannot be read leaves the common Git
1073    /// directory unknown, so every link target counts as protected.
1074    #[test]
1075    fn an_unreadable_commondir_protects_every_link_target() {
1076        let f = fixture();
1077        let repo = f.root.join("repo");
1078        std::fs::create_dir_all(repo.join(".git/worktrees/main/commondir")).expect("git dir");
1079        let main = f.root.join("main");
1080        std::fs::create_dir_all(&main).expect("main");
1081        std::fs::write(
1082            main.join(".git"),
1083            format!("gitdir: {}\n", repo.join(".git/worktrees/main").display()),
1084        )
1085        .expect("git file");
1086        let canonical = std::fs::canonicalize(&main).expect("main");
1087        assert!(is_protected_link_target(
1088            &canonical,
1089            &canonical.join("src/a.ts")
1090        ));
1091    }
1092
1093    /// `FALLOW_CACHE_DIR=../shared` from a subdirectory root names a folder
1094    /// in the same work tree. The `..` is resolved on disk, so the save
1095    /// writes, and a link before the `..` is still checked.
1096    #[test]
1097    fn a_user_cache_dir_with_a_parent_step_in_the_work_tree_writes() {
1098        let f = fixture();
1099        std::fs::create_dir_all(f.root.join(".git")).expect("git dir");
1100        let root = f.root.join("pkg");
1101        std::fs::create_dir_all(&root).expect("pkg");
1102        let dir = root.join("../shared");
1103        assert_eq!(cache_write_base(&root, &dir), f.root);
1104        CacheTarget::new(&root, &dir)
1105            .write_file("cache.bin", b"data")
1106            .expect("file");
1107        assert!(f.root.join("shared/cache.bin").exists());
1108
1109        std::fs::create_dir_all(f.outside.join("sub")).expect("sub");
1110        symlink(f.outside.join("sub"), root.join("link")).expect("link");
1111        let through = root.join("link/../elsewhere");
1112        let error = CacheTarget::new(&root, &through)
1113            .write_file("cache.bin", b"data")
1114            .expect_err("refused");
1115        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1116        assert!(error.to_string().contains("outside"), "{error}");
1117        assert!(!f.outside.join("elsewhere").exists());
1118    }
1119
1120    /// The refusal names the real reason.
1121    #[test]
1122    fn the_refusal_names_the_reason() {
1123        let f = fixture();
1124        std::fs::create_dir_all(f.root.join("node_modules/pkg")).expect("packages");
1125        symlink(f.root.join("node_modules/pkg"), f.root.join(".fallow")).expect("link");
1126        let error = ensure_no_outside_link(&f.root, &f.root.join(".fallow/cache.bin"))
1127            .expect_err("refused");
1128        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1129        assert!(error.to_string().contains("node_modules"), "{error}");
1130        assert!(!error.to_string().contains("outside"), "{error}");
1131    }
1132
1133    #[test]
1134    fn a_cache_dir_above_a_subdirectory_root_is_checked_from_the_work_tree() {
1135        let f = fixture();
1136        std::fs::create_dir_all(f.root.join(".git")).expect("git dir");
1137        std::fs::create_dir_all(f.root.join("packages/app")).expect("app");
1138        symlink(&f.outside, f.root.join(".cache")).expect("link");
1139        let root = f.root.join("packages/app");
1140        let dir = f.root.join(".cache");
1141        assert!(
1142            CacheTarget::new(&root, &dir)
1143                .check(&dir.join("cache.bin"))
1144                .is_err()
1145        );
1146    }
1147
1148    #[test]
1149    fn a_cache_dir_in_another_checkout_is_its_own_base() {
1150        let f = fixture();
1151        std::fs::create_dir_all(f.root.join(".git")).expect("git dir");
1152        let other = f.outside.join("home");
1153        std::fs::create_dir_all(other.join(".git")).expect("other git");
1154        let elsewhere = f.outside.join("disk");
1155        std::fs::create_dir_all(&elsewhere).expect("disk");
1156        symlink(&elsewhere, other.join(".cache")).expect("link");
1157        let dir = other.join(".cache/fallow");
1158        let target = CacheTarget::new(&f.root, &dir);
1159        target.write_file("cache.bin", b"data").expect("file");
1160        assert!(elsewhere.join("fallow/cache.bin").exists());
1161    }
1162
1163    #[test]
1164    fn a_user_cache_dir_outside_the_root_is_checked_from_itself() {
1165        let f = fixture();
1166        let target = CacheTarget::new(&f.root, &f.outside);
1167        target.write_file("cache.bin", b"data").expect("file");
1168        assert!(f.outside.join("cache.bin").exists());
1169    }
1170
1171    /// A submodule below a superproject whose Git directory is outside its
1172    /// work tree (`git init --separate-git-dir`). The submodule keeps its
1173    /// own Git directory below `modules/` of that directory. Returns the
1174    /// canonical submodule root and the canonical Git directory of the
1175    /// superproject.
1176    fn submodule_of_separate_git_dir(f: &Fixture) -> (PathBuf, PathBuf) {
1177        let git_dir = f.outside.join("super.git");
1178        let module = git_dir.join("modules/lib");
1179        std::fs::create_dir_all(git_dir.join("hooks")).expect("super hooks");
1180        std::fs::create_dir_all(module.join("hooks")).expect("module hooks");
1181        let superproject = f.root.join("super");
1182        let submodule = superproject.join("vendor/lib");
1183        std::fs::create_dir_all(submodule.join("src")).expect("submodule");
1184        std::fs::write(
1185            superproject.join(".git"),
1186            format!("gitdir: {}\n", git_dir.display()),
1187        )
1188        .expect("super git file");
1189        std::fs::write(
1190            submodule.join(".git"),
1191            format!("gitdir: {}\n", module.display()),
1192        )
1193        .expect("submodule git file");
1194        (
1195            std::fs::canonicalize(&submodule).expect("submodule"),
1196            std::fs::canonicalize(&git_dir).expect("super git dir"),
1197        )
1198    }
1199
1200    /// The Git directory of the superproject holds its hooks and config.
1201    /// A link target there counts as Git metadata also from the submodule.
1202    #[test]
1203    fn a_link_into_the_git_dir_of_the_superproject_is_refused() {
1204        let f = fixture();
1205        let (submodule, git_dir) = submodule_of_separate_git_dir(&f);
1206        assert!(is_protected_link_target(
1207            &submodule,
1208            &git_dir.join("hooks/pre-commit")
1209        ));
1210        assert!(is_protected_link_target(
1211            &submodule.join("src"),
1212            &git_dir.join("config")
1213        ));
1214    }
1215
1216    /// The Git directory of the submodule itself stays protected, and a link
1217    /// to an ordinary file of the submodule stays allowed.
1218    #[test]
1219    fn a_submodule_root_protects_its_own_git_dir_only() {
1220        let f = fixture();
1221        let (submodule, git_dir) = submodule_of_separate_git_dir(&f);
1222        assert!(is_protected_link_target(
1223            &submodule,
1224            &git_dir.join("modules/lib/hooks/pre-commit")
1225        ));
1226        assert!(!is_protected_link_target(
1227            &submodule,
1228            &submodule.join("src/a.ts")
1229        ));
1230        let other = std::fs::canonicalize(&f.outside).expect("outside");
1231        assert!(!is_protected_link_target(
1232            &submodule,
1233            &other.join("report.json")
1234        ));
1235    }
1236
1237    /// The common Git directory of a worktree of the superproject is
1238    /// protected for a submodule in that worktree.
1239    #[test]
1240    fn a_link_into_the_common_dir_of_the_superproject_is_refused() {
1241        let f = fixture();
1242        let common = f.outside.join("super.git");
1243        std::fs::create_dir_all(common.join("hooks")).expect("hooks");
1244        let superproject = f.root.join("wt");
1245        linked_work_tree(&common, &superproject, "wt");
1246        let submodule = superproject.join("lib");
1247        let module = common.join("worktrees/wt/modules/lib");
1248        std::fs::create_dir_all(&module).expect("module");
1249        std::fs::create_dir_all(&submodule).expect("submodule");
1250        std::fs::write(
1251            submodule.join(".git"),
1252            format!("gitdir: {}\n", module.display()),
1253        )
1254        .expect("git file");
1255        let submodule = std::fs::canonicalize(&submodule).expect("submodule");
1256        let common = std::fs::canonicalize(&common).expect("common");
1257        assert!(is_protected_link_target(
1258            &submodule,
1259            &common.join("hooks/pre-commit")
1260        ));
1261    }
1262
1263    /// A `.git` file that names no Git directory leaves the Git directory
1264    /// unknown, so every link target counts as protected. The same holds
1265    /// for such a file in a superproject.
1266    #[test]
1267    fn a_git_file_without_a_gitdir_line_protects_every_link_target() {
1268        let f = fixture();
1269        let superproject = f.root.join("super");
1270        let submodule = superproject.join("lib");
1271        std::fs::create_dir_all(&submodule).expect("submodule");
1272        std::fs::create_dir_all(submodule.join(".git")).expect("submodule git dir");
1273        std::fs::write(superproject.join(".git"), "not a git file\n").expect("git file");
1274        let submodule = std::fs::canonicalize(&submodule).expect("submodule");
1275        assert!(is_protected_link_target(
1276            &submodule,
1277            &submodule.join("src/a.ts")
1278        ));
1279    }
1280
1281    /// A `.git` file that is not text leaves the Git directory unknown too.
1282    #[test]
1283    fn an_unreadable_git_file_protects_every_link_target() {
1284        let f = fixture();
1285        let root = f.root.join("repo");
1286        std::fs::create_dir_all(&root).expect("repo");
1287        std::fs::write(root.join(".git"), [0xff, 0xfe, b'\n']).expect("git file");
1288        let root = std::fs::canonicalize(&root).expect("repo");
1289        assert!(is_protected_link_target(&root, &root.join("src/a.ts")));
1290    }
1291
1292    /// A `.git` entry that is a named pipe is not read, because the read
1293    /// would block. The Git directory stays unknown.
1294    #[test]
1295    fn a_named_pipe_git_entry_protects_every_link_target() {
1296        let f = fixture();
1297        let root = f.root.join("repo");
1298        std::fs::create_dir_all(&root).expect("repo");
1299        let made = std::process::Command::new("mkfifo")
1300            .arg(root.join(".git"))
1301            .status()
1302            .expect("run mkfifo");
1303        assert!(made.success());
1304        let root = std::fs::canonicalize(&root).expect("repo");
1305        assert!(is_protected_link_target(&root, &root.join("src/a.ts")));
1306    }
1307}