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