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`. A `.git` file can name a Git directory with any
206/// name, so the second test covers a linked worktree, a submodule and a
207/// separate Git directory.
208///
209/// The rule is for links only. A direct path into `.git`, such as a hook that
210/// `fallow hooks install` writes on purpose, does not go through it.
211#[must_use]
212pub fn is_protected_link_target(within: &Path, resolved: &Path) -> bool {
213    protected_kind(within, resolved).is_some()
214}
215
216/// The refusal of [`is_protected_link_target`], or `None`.
217fn protected_kind(within: &Path, resolved: &Path) -> Option<Refusal> {
218    let below = resolved.strip_prefix(within).unwrap_or(resolved);
219    let names = || {
220        below.components().filter_map(|component| match component {
221            Component::Normal(name) => name.to_str(),
222            _ => None,
223        })
224    };
225    if names().any(|name| name.eq_ignore_ascii_case(PACKAGE_DIR)) {
226        return Some(Refusal::Packages);
227    }
228    if names().any(|name| name.eq_ignore_ascii_case(GIT_ENTRY)) {
229        return Some(Refusal::GitMetadata);
230    }
231    GitDirs::of(within)
232        .holds(resolved)
233        .then_some(Refusal::GitMetadata)
234}
235
236/// The canonical Git directory and common Git directory of the work tree
237/// that contains a directory. The two can be outside the work tree, for a
238/// separate Git directory or a worktree of a bare repository.
239#[derive(Clone, Debug, Default)]
240pub struct GitDirs {
241    /// The canonical top of the work tree.
242    work_tree: Option<PathBuf>,
243    dirs: Vec<PathBuf>,
244    /// The `commondir` file exists but cannot be read or resolved, so the
245    /// common Git directory is not known.
246    unknown: bool,
247}
248
249impl GitDirs {
250    /// The Git directories of the work tree that contains `dir`. Empty when
251    /// no ancestor of `dir` has a `.git` entry, or when the entry names no
252    /// Git directory that exists.
253    #[must_use]
254    pub fn of(dir: &Path) -> Self {
255        let Some(top) = work_tree_top(dir) else {
256            return Self::default();
257        };
258        let work_tree = std::fs::canonicalize(top).ok();
259        let Some(git_dir) = git_dir_of_entry(&top.join(GIT_ENTRY)) else {
260            return Self {
261                work_tree,
262                ..Self::default()
263            };
264        };
265        let common = common_dir_of(&git_dir);
266        let unknown = common.is_none();
267        let mut dirs = vec![git_dir];
268        if let Some(common) = common
269            && !dirs.contains(&common)
270        {
271            dirs.push(common);
272        }
273        Self {
274            work_tree,
275            dirs,
276            unknown,
277        }
278    }
279
280    /// Whether the canonical `path` is in one of the Git directories. A
281    /// path in the work tree does not count when the work tree itself is in
282    /// that Git directory, as for a worktree inside a bare repository. When
283    /// the common Git directory is not known, every path counts.
284    #[must_use]
285    pub fn holds(&self, path: &Path) -> bool {
286        if self.unknown {
287            return true;
288        }
289        let in_work_tree_of = |dir: &Path| {
290            self.work_tree
291                .as_deref()
292                .is_some_and(|tree| tree.starts_with(dir) && path.starts_with(tree))
293        };
294        self.dirs
295            .iter()
296            .any(|dir| path.starts_with(dir) && !in_work_tree_of(dir))
297    }
298}
299
300/// The nearest ancestor of `dir`, `dir` included, with a `.git` entry. The
301/// entry counts when it exists as an entry, also as a dangling link.
302#[must_use]
303pub fn work_tree_top(dir: &Path) -> Option<&Path> {
304    dir.ancestors()
305        .find(|ancestor| ancestor.join(GIT_ENTRY).symlink_metadata().is_ok())
306}
307
308/// The canonical Git directory that the `.git` entry `entry` stands for: the
309/// directory itself, or the directory that a `.git` file names.
310fn git_dir_of_entry(entry: &Path) -> Option<PathBuf> {
311    let meta = std::fs::metadata(entry).ok()?;
312    if meta.is_dir() {
313        return std::fs::canonicalize(entry).ok();
314    }
315    let text = std::fs::read_to_string(entry).ok()?;
316    let named = text
317        .lines()
318        .find_map(|line| line.strip_prefix(GITDIR_PREFIX))?
319        .trim();
320    let parent = entry.parent()?;
321    std::fs::canonicalize(parent.join(named)).ok()
322}
323
324/// The canonical common Git directory of the Git directory `git_dir`: the
325/// directory that its `commondir` file names, or `git_dir` itself when it
326/// has no `commondir` file. `None` when the file cannot be read or names a
327/// directory that does not resolve.
328fn common_dir_of(git_dir: &Path) -> Option<PathBuf> {
329    match std::fs::read_to_string(git_dir.join(COMMONDIR_FILE)) {
330        Ok(text) => std::fs::canonicalize(git_dir.join(text.trim())).ok(),
331        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Some(git_dir.to_path_buf()),
332        Err(_) => None,
333    }
334}
335
336/// The directory that cache writes must stay in.
337///
338/// - A cache directory inside the project root is checked from the root, so
339///   a committed `.fallow` link is refused.
340/// - A cache directory in the same Git repository as the root, but not below
341///   the root, is checked from the top of its work tree. This covers a cache
342///   above a subdirectory root, and the cache in the checkout of an audit
343///   that runs in a linked worktree (`audit --staged`, the base snapshot).
344/// - Any other cache directory comes from the user, such as
345///   `FALLOW_CACHE_DIR` on a CI runner, so only the entries below it are
346///   checked.
347///
348/// A `..` in the cache directory is resolved by text first, so
349/// `FALLOW_CACHE_DIR=../shared` counts as a directory outside the root.
350#[must_use]
351pub fn cache_write_base(root: &Path, cache_dir: &Path) -> PathBuf {
352    let normalized = lexically_normalized(cache_dir);
353    if normalized.starts_with(root) {
354        return root.to_path_buf();
355    }
356    same_repository_top(root, &normalized).unwrap_or_else(|| cache_dir.to_path_buf())
357}
358
359/// The top of a work tree of the repository that contains `root`, as an
360/// ancestor of `cache_dir`, when `cache_dir` is below one.
361///
362/// A work tree counts when its `.git` entry (a directory or a file) has the
363/// same common Git directory as the work tree of the root. This covers the
364/// main checkout, a linked worktree, a submodule and a worktree of a bare
365/// repository. An ancestor that is a symlink never counts.
366///
367/// When more than one ancestor counts, the lowest one is the top, so a link
368/// in a worktree inside the main checkout is checked from that worktree and
369/// cannot lead up into the main checkout. An ancestor that is below a
370/// symlink, seen from the highest ancestor that counts, is skipped, so the
371/// base is never reached through a link. The links below the top are checked
372/// later, from the top.
373fn same_repository_top(root: &Path, cache_dir: &Path) -> Option<PathBuf> {
374    let root_common = common_dir_of_work_tree(work_tree_top(root)?)?;
375    let tops: Vec<&Path> = cache_dir
376        .ancestors()
377        .skip(1)
378        .filter(|ancestor| {
379            ancestor
380                .symlink_metadata()
381                .is_ok_and(|meta| !meta.file_type().is_symlink())
382                && ancestor.join(GIT_ENTRY).symlink_metadata().is_ok()
383                && common_dir_of_work_tree(ancestor).as_ref() == Some(&root_common)
384        })
385        .collect();
386    let highest = *tops.last()?;
387    tops.into_iter()
388        .find(|top| !has_link_between(highest, top))
389        .map(Path::to_path_buf)
390}
391
392/// Whether an entry below `upper`, down to and including `lower`, is a
393/// symlink or cannot be read. `lower` must be below `upper`.
394fn has_link_between(upper: &Path, lower: &Path) -> bool {
395    let Ok(relative) = lower.strip_prefix(upper) else {
396        return true;
397    };
398    let mut current = upper.to_path_buf();
399    relative.components().any(|component| {
400        current.push(component);
401        !current
402            .symlink_metadata()
403            .is_ok_and(|meta| !meta.file_type().is_symlink())
404    })
405}
406
407/// The canonical common Git directory of the work tree at `top`.
408fn common_dir_of_work_tree(top: &Path) -> Option<PathBuf> {
409    git_dir_of_entry(&top.join(GIT_ENTRY)).and_then(|git_dir| common_dir_of(&git_dir))
410}
411
412/// `path` with each `..` applied to the component before it, and each `.`
413/// dropped, without a file system read.
414#[must_use]
415pub fn lexically_normalized(path: &Path) -> PathBuf {
416    let mut normalized = PathBuf::new();
417    for component in path.components() {
418        match component {
419            Component::CurDir => {}
420            Component::ParentDir => {
421                normalized.pop();
422            }
423            other => normalized.push(other),
424        }
425    }
426    normalized
427}
428
429/// Fail when a write to `path` would follow a symlink that leaves `base`.
430///
431/// Call this before each create, write, rename or delete under a cache
432/// directory, with the base from [`cache_write_base`]. A base that does not
433/// exist yet has no link below it, so the first save into a new cache
434/// directory passes. A dangling link at the base itself exists, so it is
435/// still checked. A `..` in `path` is applied to the resolved path, as the
436/// file system does, so `FALLOW_CACHE_DIR=../shared` from a subdirectory
437/// root works and a link before the `..` is still checked.
438///
439/// # Errors
440///
441/// Returns a `PermissionDenied` error that names the refused entry and the
442/// reason.
443pub fn ensure_no_outside_link(base: &Path, path: &Path) -> std::io::Result<()> {
444    if base.symlink_metadata().is_err() {
445        return Ok(());
446    }
447    match find_refusal(base, path, ParentSteps::Resolve) {
448        None => Ok(()),
449        Some(refused) => Err(std::io::Error::new(
450            std::io::ErrorKind::PermissionDenied,
451            format!(
452                "refusing to write {}: {}",
453                path.display(),
454                refused.reason.describe(&refused.entry, base)
455            ),
456        )),
457    }
458}
459
460/// A cache directory and the directory that its writes must stay in.
461///
462/// Every cache writer takes this type instead of a bare directory, so a
463/// writer cannot skip the symlink check.
464#[derive(Clone, Copy, Debug)]
465pub struct CacheTarget<'a> {
466    dir: &'a Path,
467    /// The cache directory that the base is computed from. A subdirectory
468    /// from [`Self::with_dir`] keeps the base of its parent.
469    anchor: &'a Path,
470    /// The project root, or `None` when the anchor is its own base.
471    root: Option<&'a Path>,
472}
473
474impl<'a> CacheTarget<'a> {
475    /// The cache directory `dir` of the project at `root`.
476    #[must_use]
477    pub const fn new(root: &'a Path, dir: &'a Path) -> Self {
478        Self {
479            dir,
480            anchor: dir,
481            root: Some(root),
482        }
483    }
484
485    /// A cache directory that is its own base, such as a directory that the
486    /// user chose.
487    #[must_use]
488    pub const fn inside(dir: &'a Path) -> Self {
489        Self {
490            dir,
491            anchor: dir,
492            root: None,
493        }
494    }
495
496    /// The cache directory.
497    #[must_use]
498    pub const fn dir(&self) -> &'a Path {
499        self.dir
500    }
501
502    /// The same base with `dir` as the cache directory, for a subdirectory.
503    #[must_use]
504    pub const fn with_dir(&self, dir: &'a Path) -> Self {
505        Self {
506            dir,
507            anchor: self.anchor,
508            root: self.root,
509        }
510    }
511
512    /// The directory that the writes must stay in, from
513    /// [`cache_write_base`].
514    #[must_use]
515    pub fn write_base(&self) -> PathBuf {
516        self.root.map_or_else(
517            || self.anchor.to_path_buf(),
518            |root| cache_write_base(root, self.anchor),
519        )
520    }
521
522    /// Fail when a write to `path` would follow a symlink that leaves the
523    /// base.
524    ///
525    /// # Errors
526    ///
527    /// Returns the error of [`ensure_no_outside_link`].
528    pub fn check(&self, path: &Path) -> std::io::Result<()> {
529        ensure_no_outside_link(&self.write_base(), path)
530    }
531
532    /// Create the cache directory and replace the file `name` in it with
533    /// `data` through [`crate::atomic_file::write_atomic`], after the
534    /// symlink check.
535    ///
536    /// # Errors
537    ///
538    /// Returns the error of the check, of the directory creation, or of the
539    /// write.
540    pub fn write_file(&self, name: &str, data: &[u8]) -> std::io::Result<()> {
541        let path = self.dir.join(name);
542        self.check(&path)?;
543        std::fs::create_dir_all(self.dir)?;
544        crate::atomic_file::write_atomic(&path, data)
545    }
546
547    /// Write `.gitignore` with `*`, so the cache directory is never
548    /// committed. An equal file stays as it is.
549    ///
550    /// # Errors
551    ///
552    /// Returns the error of [`Self::write_file`].
553    pub fn write_gitignore(&self) -> std::io::Result<()> {
554        let path = self.dir.join(".gitignore");
555        self.check(&path)?;
556        if std::fs::read(&path).is_ok_and(|content| content == b"*\n") {
557            return Ok(());
558        }
559        self.write_file(".gitignore", b"*\n")
560    }
561}
562
563#[cfg(all(test, unix, not(miri)))]
564mod tests {
565    use super::*;
566    use std::os::unix::fs::symlink;
567
568    struct Fixture {
569        _dir: tempfile::TempDir,
570        root: PathBuf,
571        outside: PathBuf,
572    }
573
574    fn fixture() -> Fixture {
575        let dir = tempfile::tempdir().expect("tempdir");
576        let root = dir.path().join("project");
577        let outside = dir.path().join("outside");
578        std::fs::create_dir_all(&root).expect("root");
579        std::fs::create_dir_all(&outside).expect("outside");
580        Fixture {
581            _dir: dir,
582            root,
583            outside,
584        }
585    }
586
587    #[test]
588    fn a_plain_path_passes() {
589        let f = fixture();
590        let path = f.root.join(".fallow/cache/x/cache.bin");
591        assert_eq!(outside_link(&f.root, &path), None);
592        assert!(ensure_no_outside_link(&f.root, &path).is_ok());
593    }
594
595    #[test]
596    fn a_linked_cache_dir_is_refused() {
597        let f = fixture();
598        symlink(&f.outside, f.root.join(".fallow")).expect("link");
599        let path = f.root.join(".fallow/.gitignore");
600        assert_eq!(outside_link(&f.root, &path), Some(f.root.join(".fallow")));
601        let error = ensure_no_outside_link(&f.root, &path).expect_err("refused");
602        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
603    }
604
605    #[test]
606    fn a_dangling_file_link_is_refused() {
607        let f = fixture();
608        std::fs::create_dir_all(f.root.join(".fallow")).expect("cache");
609        let link = f.root.join(".fallow/.gitignore");
610        symlink(f.outside.join("missing"), &link).expect("link");
611        assert_eq!(outside_link(&f.root, &link), Some(link.clone()));
612        let error = ensure_no_outside_link(&f.root, &link).expect_err("refused");
613        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
614    }
615
616    #[test]
617    fn a_link_inside_the_base_passes() {
618        let f = fixture();
619        std::fs::create_dir_all(f.root.join("build/cache")).expect("target");
620        symlink(f.root.join("build/cache"), f.root.join(".fallow")).expect("link");
621        assert_eq!(
622            outside_link(&f.root, &f.root.join(".fallow/cache.bin")),
623            None
624        );
625    }
626
627    #[test]
628    fn a_path_outside_the_base_is_refused() {
629        let f = fixture();
630        let path = f.outside.join("cache.bin");
631        assert_eq!(outside_link(&f.root, &path), Some(path));
632    }
633
634    #[test]
635    fn the_base_follows_where_the_cache_dir_is() {
636        let root = Path::new("/p");
637        assert_eq!(cache_write_base(root, Path::new("/p/.fallow")), root);
638        assert_eq!(
639            cache_write_base(root, Path::new("/ci/cache")),
640            Path::new("/ci/cache")
641        );
642    }
643
644    #[test]
645    fn a_target_writes_the_file_and_the_gitignore() {
646        let f = fixture();
647        let dir = f.root.join(".fallow/cache");
648        let target = CacheTarget::new(&f.root, &dir);
649        target.write_gitignore().expect("gitignore");
650        target.write_file("cache.bin", b"data").expect("file");
651        assert_eq!(std::fs::read(dir.join(".gitignore")).expect("read"), b"*\n");
652        assert_eq!(std::fs::read(dir.join("cache.bin")).expect("read"), b"data");
653    }
654
655    #[test]
656    fn a_target_refuses_a_linked_cache_dir_and_writes_nothing() {
657        let f = fixture();
658        symlink(&f.outside, f.root.join(".fallow")).expect("link");
659        let dir = f.root.join(".fallow");
660        let target = CacheTarget::new(&f.root, &dir);
661        assert!(target.write_gitignore().is_err());
662        assert!(target.write_file("cache.bin", b"data").is_err());
663        assert_eq!(std::fs::read_dir(&f.outside).expect("outside").count(), 0);
664    }
665
666    #[test]
667    fn a_target_refuses_a_dangling_gitignore_link() {
668        let f = fixture();
669        let dir = f.root.join(".fallow");
670        std::fs::create_dir_all(&dir).expect("cache");
671        symlink(f.outside.join("victim"), dir.join(".gitignore")).expect("link");
672        assert!(CacheTarget::new(&f.root, &dir).write_gitignore().is_err());
673        assert!(!f.outside.join("victim").exists());
674    }
675
676    #[test]
677    fn a_relative_cache_dir_above_the_root_is_its_own_base() {
678        let root = Path::new("/p/project");
679        let shared = Path::new("/p/project/../shared");
680        assert_eq!(cache_write_base(root, shared), shared);
681        let inside = Path::new("/p/project/sub/../.fallow");
682        assert_eq!(cache_write_base(root, inside), root);
683    }
684
685    #[test]
686    fn a_relative_cache_dir_above_the_root_gets_its_cache() {
687        let f = fixture();
688        let dir = f.root.join("../shared");
689        let target = CacheTarget::new(&f.root, &dir);
690        target.write_file("cache.bin", b"data").expect("file");
691        assert!(f.outside.join("../shared/cache.bin").exists());
692    }
693
694    #[test]
695    fn a_missing_base_passes_the_check() {
696        let f = fixture();
697        let base = f.outside.join("new");
698        assert!(ensure_no_outside_link(&base, &base.join("cache.bin")).is_ok());
699    }
700
701    #[test]
702    fn a_target_writes_into_a_new_cache_dir() {
703        let f = fixture();
704        let dir = f.outside.join("new/cache");
705        CacheTarget::inside(&dir)
706            .write_gitignore()
707            .expect("gitignore");
708        assert!(dir.join(".gitignore").exists());
709    }
710
711    #[test]
712    fn a_dir_link_into_the_git_dir_below_the_base_is_refused() {
713        let f = fixture();
714        std::fs::create_dir_all(f.root.join(".git")).expect("git dir");
715        symlink(f.root.join(".git"), f.root.join("conf")).expect("link");
716        let path = f.root.join("conf/config");
717        assert_eq!(outside_link(&f.root, &path), Some(f.root.join("conf")));
718        let error = ensure_no_outside_link(&f.root, &path).expect_err("refused");
719        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
720        assert!(error.to_string().contains("Git metadata"), "{error}");
721    }
722
723    #[test]
724    fn a_file_link_into_a_nested_git_dir_is_refused() {
725        let f = fixture();
726        std::fs::create_dir_all(f.root.join("sub/.GIT")).expect("git dir");
727        std::fs::write(f.root.join("sub/.GIT/HEAD"), "ref").expect("head");
728        symlink(f.root.join("sub/.GIT/HEAD"), f.root.join("head")).expect("link");
729        let path = f.root.join("head");
730        assert_eq!(outside_link(&f.root, &path), Some(path));
731    }
732
733    #[test]
734    fn a_link_into_the_dir_that_a_git_file_names_is_refused() {
735        let f = fixture();
736        std::fs::create_dir_all(f.root.join("meta")).expect("meta");
737        std::fs::write(f.root.join(".git"), "gitdir: meta\n").expect("git file");
738        symlink(f.root.join("meta"), f.root.join("m")).expect("link");
739        let path = f.root.join("m/config");
740        assert_eq!(outside_link(&f.root, &path), Some(f.root.join("m")));
741    }
742
743    #[test]
744    fn a_base_that_links_into_the_git_dir_is_refused() {
745        let f = fixture();
746        std::fs::create_dir_all(f.root.join(".git/hooks")).expect("git dir");
747        let base = f.root.join("alias");
748        symlink(f.root.join(".git/hooks"), &base).expect("link");
749        let path = base.join("pre-commit");
750        assert_eq!(outside_link(&base, &path), Some(base));
751    }
752
753    #[test]
754    fn a_plain_path_into_the_git_dir_passes() {
755        let f = fixture();
756        std::fs::create_dir_all(f.root.join(".git/hooks")).expect("git dir");
757        let path = f.root.join(".git/hooks/pre-commit");
758        assert_eq!(outside_link(&f.root, &path), None);
759    }
760
761    #[test]
762    fn a_link_into_node_modules_is_refused() {
763        let f = fixture();
764        std::fs::create_dir_all(f.root.join("node_modules/left-pad")).expect("package");
765        std::fs::write(f.root.join("node_modules/left-pad/index.js"), "x").expect("file");
766        let path = f.root.join(".gitignore");
767        symlink(f.root.join("node_modules/left-pad/index.js"), &path).expect("link");
768        assert_eq!(outside_link(&f.root, &path), Some(path));
769    }
770
771    #[test]
772    fn a_named_pipe_target_is_refused() {
773        let f = fixture();
774        let fifo = f.root.join("report");
775        let made = std::process::Command::new("mkfifo")
776            .arg(&fifo)
777            .status()
778            .expect("run mkfifo");
779        assert!(made.success());
780        assert_eq!(outside_link(&f.root, &fifo), Some(fifo));
781    }
782
783    /// A staged audit runs in a linked worktree outside the checkout and
784    /// keeps its cache in the checkout. A link at the cache directory of the
785    /// checkout must not take the writes out of the checkout.
786    #[test]
787    fn a_cache_dir_in_the_checkout_of_a_linked_worktree_is_checked_from_the_checkout() {
788        let f = fixture();
789        let host = f.root.join("host");
790        std::fs::create_dir_all(host.join(".git/worktrees/staged")).expect("host git");
791        std::fs::write(host.join(".git/worktrees/staged/commondir"), "../..\n").expect("common");
792        std::fs::create_dir_all(host.join("packages/app")).expect("host app");
793        let staged = f.root.join("staged");
794        std::fs::create_dir_all(staged.join("packages/app")).expect("staged app");
795        std::fs::write(
796            staged.join(".git"),
797            format!("gitdir: {}\n", host.join(".git/worktrees/staged").display()),
798        )
799        .expect("git file");
800        symlink(&f.outside, host.join("packages/app/buildcache")).expect("link");
801        let root = staged.join("packages/app");
802        let dir = host.join("packages/app/buildcache");
803        let target = CacheTarget::new(&root, &dir);
804        assert!(target.check(&dir.join("cache.bin")).is_err());
805        assert!(target.write_file("cache.bin", b"data").is_err());
806        assert_eq!(std::fs::read_dir(&f.outside).expect("outside").count(), 0);
807    }
808
809    /// A folder in the checkout that links to another Git checkout does not
810    /// make that checkout the base of the cache.
811    #[test]
812    fn a_cache_dir_through_a_link_to_another_checkout_is_checked_from_the_checkout() {
813        let f = fixture();
814        let host = f.root.join("host");
815        std::fs::create_dir_all(host.join(".git/worktrees/staged")).expect("host git");
816        std::fs::write(host.join(".git/worktrees/staged/commondir"), "../..\n").expect("common");
817        std::fs::create_dir_all(host.join("packages/app")).expect("host app");
818        let other = f.outside.join("other");
819        std::fs::create_dir_all(other.join(".git")).expect("other git");
820        symlink(&other, host.join("packages/app/link")).expect("link");
821        let staged = f.root.join("staged");
822        std::fs::create_dir_all(staged.join("packages/app")).expect("staged app");
823        std::fs::write(
824            staged.join(".git"),
825            format!("gitdir: {}\n", host.join(".git/worktrees/staged").display()),
826        )
827        .expect("git file");
828        let root = staged.join("packages/app");
829        let dir = host.join("packages/app/link/cache");
830        let target = CacheTarget::new(&root, &dir);
831        assert!(target.write_file("cache.bin", b"data").is_err());
832        assert!(!other.join("cache").exists());
833    }
834
835    /// A staged audit of a linked worktree keeps its cache in that worktree,
836    /// not below the main checkout. A link in it is still checked.
837    #[test]
838    fn a_cache_dir_in_a_linked_worktree_host_is_checked_from_the_worktree() {
839        let f = fixture();
840        let main = f.root.join("repo");
841        std::fs::create_dir_all(main.join(".git/worktrees/feature")).expect("main git");
842        std::fs::create_dir_all(main.join(".git/worktrees/staged")).expect("staged git");
843        for name in ["feature", "staged"] {
844            std::fs::write(
845                main.join(format!(".git/worktrees/{name}/commondir")),
846                "../..\n",
847            )
848            .expect("common");
849        }
850        let host = f.root.join("wt/feature");
851        std::fs::create_dir_all(host.join("packages/app")).expect("host app");
852        std::fs::write(
853            host.join(".git"),
854            format!(
855                "gitdir: {}\n",
856                main.join(".git/worktrees/feature").display()
857            ),
858        )
859        .expect("host git file");
860        let staged = f.root.join("staged");
861        std::fs::create_dir_all(staged.join("packages/app")).expect("staged app");
862        std::fs::write(
863            staged.join(".git"),
864            format!("gitdir: {}\n", main.join(".git/worktrees/staged").display()),
865        )
866        .expect("staged git file");
867        symlink(&f.outside, host.join("packages/app/build")).expect("link");
868        let root = staged.join("packages/app");
869        let dir = host.join("packages/app/build/cache");
870        assert!(
871            CacheTarget::new(&root, &dir)
872                .write_file("cache.bin", b"data")
873                .is_err()
874        );
875        assert_eq!(std::fs::read_dir(&f.outside).expect("outside").count(), 0);
876    }
877
878    /// The same for a submodule, whose Git directory is below the Git
879    /// directory of the superproject.
880    #[test]
881    fn a_cache_dir_in_a_submodule_host_is_checked_from_the_submodule() {
882        let f = fixture();
883        let modules = f.root.join("super/.git/modules/sub");
884        std::fs::create_dir_all(modules.join("worktrees/staged")).expect("module git");
885        std::fs::write(modules.join("worktrees/staged/commondir"), "../..\n").expect("common");
886        let host = f.root.join("super/sub");
887        std::fs::create_dir_all(host.join("packages/app")).expect("host app");
888        std::fs::write(
889            host.join(".git"),
890            format!("gitdir: {}\n", modules.display()),
891        )
892        .expect("host git file");
893        let staged = f.root.join("staged");
894        std::fs::create_dir_all(staged.join("packages/app")).expect("staged app");
895        std::fs::write(
896            staged.join(".git"),
897            format!("gitdir: {}\n", modules.join("worktrees/staged").display()),
898        )
899        .expect("staged git file");
900        symlink(&f.outside, host.join("packages/app/build")).expect("link");
901        let root = staged.join("packages/app");
902        let dir = host.join("packages/app/build/cache");
903        assert!(
904            CacheTarget::new(&root, &dir)
905                .write_file("cache.bin", b"data")
906                .is_err()
907        );
908        assert_eq!(std::fs::read_dir(&f.outside).expect("outside").count(), 0);
909    }
910
911    /// Write a `.git` file at `top` that names the linked Git directory
912    /// `name` below the common Git directory `common`, with its `commondir`.
913    fn linked_work_tree(common: &Path, top: &Path, name: &str) {
914        let git_dir = common.join("worktrees").join(name);
915        std::fs::create_dir_all(&git_dir).expect("linked git dir");
916        std::fs::write(git_dir.join("commondir"), "../..\n").expect("common");
917        std::fs::create_dir_all(top).expect("work tree");
918        std::fs::write(top.join(".git"), format!("gitdir: {}\n", git_dir.display()))
919            .expect("git file");
920    }
921
922    /// A linked worktree can live inside the main checkout. A link in it
923    /// that leads up into the main checkout must not take the cache writes
924    /// of a staged audit there.
925    #[test]
926    fn a_link_from_a_worktree_inside_the_main_checkout_up_into_it_is_refused() {
927        let f = fixture();
928        let repo = f.root.join("repo");
929        std::fs::create_dir_all(repo.join(".git")).expect("main git");
930        let host = repo.join(".worktrees/feature");
931        linked_work_tree(&repo.join(".git"), &host, "feature");
932        let staged = f.root.join("staged");
933        linked_work_tree(&repo.join(".git"), &staged, "staged");
934        symlink("../..", host.join("build")).expect("link");
935        let dir = host.join("build/cache");
936        for root in [&staged, &host] {
937            let target = CacheTarget::new(root, &dir);
938            assert!(target.write_gitignore().is_err());
939            assert!(target.write_file("cache.bin", b"data").is_err());
940        }
941        assert!(!repo.join("cache").exists());
942    }
943
944    /// The same for two worktrees of a bare repository, one inside the
945    /// other. The bare repository has no work tree of its own.
946    #[test]
947    fn a_link_from_a_nested_worktree_of_a_bare_repository_is_refused() {
948        let f = fixture();
949        let bare = f.root.join("repo.git");
950        let outer = f.root.join("trees/main");
951        linked_work_tree(&bare, &outer, "main");
952        let host = outer.join(".worktrees/feature");
953        linked_work_tree(&bare, &host, "feature");
954        let staged = f.root.join("staged");
955        linked_work_tree(&bare, &staged, "staged");
956        symlink("../..", host.join("build")).expect("link");
957        let dir = host.join("build/cache");
958        assert!(
959            CacheTarget::new(&staged, &dir)
960                .write_file("cache.bin", b"data")
961                .is_err()
962        );
963        assert!(!outer.join("cache").exists());
964    }
965
966    /// A work tree that is reached through a link is never the base, so the
967    /// link is checked from the work tree above it.
968    #[test]
969    fn a_work_tree_behind_a_link_is_not_the_base() {
970        let f = fixture();
971        let repo = f.root.join("repo");
972        std::fs::create_dir_all(repo.join(".git")).expect("main git");
973        let host = f.root.join("host");
974        linked_work_tree(&repo.join(".git"), &host, "host");
975        let other = f.outside.join("other");
976        linked_work_tree(&repo.join(".git"), &other, "other");
977        linked_work_tree(&repo.join(".git"), &other.join("nested"), "nested");
978        let staged = f.root.join("staged");
979        linked_work_tree(&repo.join(".git"), &staged, "staged");
980        symlink(&other, host.join("shared")).expect("link");
981        let dir = host.join("shared/nested/cache");
982        assert!(
983            CacheTarget::new(&staged, &dir)
984                .write_file("cache.bin", b"data")
985                .is_err()
986        );
987        assert!(!other.join("nested/cache").exists());
988    }
989
990    /// A worktree of a bare repository lies inside the common Git directory.
991    /// Its files are not Git metadata, but the Git directory still is.
992    #[test]
993    fn a_worktree_inside_a_bare_repository_is_not_git_metadata() {
994        let f = fixture();
995        let bare = f.root.join("proj.git");
996        let main = bare.join("main");
997        linked_work_tree(&bare, &main, "main");
998        std::fs::create_dir_all(main.join("src")).expect("src");
999        std::fs::create_dir_all(bare.join("hooks")).expect("hooks");
1000        let canonical_main = std::fs::canonicalize(&main).expect("main");
1001        let canonical_bare = std::fs::canonicalize(&bare).expect("bare");
1002        assert!(!is_protected_link_target(
1003            &canonical_main,
1004            &canonical_main.join("src/a.ts")
1005        ));
1006        assert!(is_protected_link_target(
1007            &canonical_main,
1008            &canonical_bare.join("hooks/pre-commit")
1009        ));
1010        assert!(is_protected_link_target(
1011            &canonical_main,
1012            &canonical_bare.join("worktrees/main/HEAD")
1013        ));
1014        std::fs::create_dir_all(main.join("build/cache")).expect("cache");
1015        symlink("build/cache", main.join(".fallow")).expect("link");
1016        let dir = main.join(".fallow");
1017        CacheTarget::new(&main, &dir)
1018            .write_file("cache.bin", b"data")
1019            .expect("file");
1020        symlink(bare.join("hooks"), main.join("hooks")).expect("hooks link");
1021        let error =
1022            ensure_no_outside_link(&main, &main.join("hooks/pre-commit")).expect_err("refused");
1023        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1024    }
1025
1026    /// A `commondir` file that cannot be read leaves the common Git
1027    /// directory unknown, so every link target counts as protected.
1028    #[test]
1029    fn an_unreadable_commondir_protects_every_link_target() {
1030        let f = fixture();
1031        let repo = f.root.join("repo");
1032        std::fs::create_dir_all(repo.join(".git/worktrees/main/commondir")).expect("git dir");
1033        let main = f.root.join("main");
1034        std::fs::create_dir_all(&main).expect("main");
1035        std::fs::write(
1036            main.join(".git"),
1037            format!("gitdir: {}\n", repo.join(".git/worktrees/main").display()),
1038        )
1039        .expect("git file");
1040        let canonical = std::fs::canonicalize(&main).expect("main");
1041        assert!(is_protected_link_target(
1042            &canonical,
1043            &canonical.join("src/a.ts")
1044        ));
1045    }
1046
1047    /// `FALLOW_CACHE_DIR=../shared` from a subdirectory root names a folder
1048    /// in the same work tree. The `..` is resolved on disk, so the save
1049    /// writes, and a link before the `..` is still checked.
1050    #[test]
1051    fn a_user_cache_dir_with_a_parent_step_in_the_work_tree_writes() {
1052        let f = fixture();
1053        std::fs::create_dir_all(f.root.join(".git")).expect("git dir");
1054        let root = f.root.join("pkg");
1055        std::fs::create_dir_all(&root).expect("pkg");
1056        let dir = root.join("../shared");
1057        assert_eq!(cache_write_base(&root, &dir), f.root);
1058        CacheTarget::new(&root, &dir)
1059            .write_file("cache.bin", b"data")
1060            .expect("file");
1061        assert!(f.root.join("shared/cache.bin").exists());
1062
1063        std::fs::create_dir_all(f.outside.join("sub")).expect("sub");
1064        symlink(f.outside.join("sub"), root.join("link")).expect("link");
1065        let through = root.join("link/../elsewhere");
1066        let error = CacheTarget::new(&root, &through)
1067            .write_file("cache.bin", b"data")
1068            .expect_err("refused");
1069        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1070        assert!(error.to_string().contains("outside"), "{error}");
1071        assert!(!f.outside.join("elsewhere").exists());
1072    }
1073
1074    /// The refusal names the real reason.
1075    #[test]
1076    fn the_refusal_names_the_reason() {
1077        let f = fixture();
1078        std::fs::create_dir_all(f.root.join("node_modules/pkg")).expect("packages");
1079        symlink(f.root.join("node_modules/pkg"), f.root.join(".fallow")).expect("link");
1080        let error = ensure_no_outside_link(&f.root, &f.root.join(".fallow/cache.bin"))
1081            .expect_err("refused");
1082        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1083        assert!(error.to_string().contains("node_modules"), "{error}");
1084        assert!(!error.to_string().contains("outside"), "{error}");
1085    }
1086
1087    #[test]
1088    fn a_cache_dir_above_a_subdirectory_root_is_checked_from_the_work_tree() {
1089        let f = fixture();
1090        std::fs::create_dir_all(f.root.join(".git")).expect("git dir");
1091        std::fs::create_dir_all(f.root.join("packages/app")).expect("app");
1092        symlink(&f.outside, f.root.join(".cache")).expect("link");
1093        let root = f.root.join("packages/app");
1094        let dir = f.root.join(".cache");
1095        assert!(
1096            CacheTarget::new(&root, &dir)
1097                .check(&dir.join("cache.bin"))
1098                .is_err()
1099        );
1100    }
1101
1102    #[test]
1103    fn a_cache_dir_in_another_checkout_is_its_own_base() {
1104        let f = fixture();
1105        std::fs::create_dir_all(f.root.join(".git")).expect("git dir");
1106        let other = f.outside.join("home");
1107        std::fs::create_dir_all(other.join(".git")).expect("other git");
1108        let elsewhere = f.outside.join("disk");
1109        std::fs::create_dir_all(&elsewhere).expect("disk");
1110        symlink(&elsewhere, other.join(".cache")).expect("link");
1111        let dir = other.join(".cache/fallow");
1112        let target = CacheTarget::new(&f.root, &dir);
1113        target.write_file("cache.bin", b"data").expect("file");
1114        assert!(elsewhere.join("fallow/cache.bin").exists());
1115    }
1116
1117    #[test]
1118    fn a_user_cache_dir_outside_the_root_is_checked_from_itself() {
1119        let f = fixture();
1120        let target = CacheTarget::new(&f.root, &f.outside);
1121        target.write_file("cache.bin", b"data").expect("file");
1122        assert!(f.outside.join("cache.bin").exists());
1123    }
1124}