Skip to main content

fallow_engine/
write_guard.rs

1//! Confine the files that a run writes on request (baselines, snapshots and
2//! report files) to the project.
3//!
4//! A path must resolve inside the project root, or inside the Git work tree
5//! that contains the root when the working directory is inside that tree too,
6//! or inside a shared directory: the CI workspace (`GITHUB_WORKSPACE`, GitLab
7//! `CI_PROJECT_DIR`) and the temp directories (`RUNNER_TEMP`, the system temp
8//! directory, and `/tmp` on Unix), each when it is set. An existing character device or named
9//! pipe (`/dev/null`, `/dev/stdout`, process substitution) is also allowed,
10//! because a write to it cannot put a file anywhere. On Windows the null
11//! device (`NUL`) is allowed for the same reason.
12//!
13//! The command line layer checks each path before the analysis starts and
14//! then records the scope with [`confine`]. The writers call [`create_file`]
15//! or [`write_file`], which resolve and check the path again right before the
16//! write and do not follow a symlink at the final component.
17//!
18//! This narrows the window for a path that another local user swaps for a
19//! symlink, from the whole analysis to the moment of the write. It does not
20//! close the window for an intermediate directory: a directory swapped
21//! between the last parent check and the open call is still followed. On
22//! Windows the final component is checked just before the open, so a small
23//! window stays there too.
24//!
25//! Symlinks are resolved on both sides: on the part of the path that exists,
26//! and on each allowed directory. So a link inside the root that points
27//! outside it does not open a way out, and `/var` and `/private/var` on macOS
28//! compare equal.
29
30use std::fs::File;
31use std::io::{self, Write};
32use std::path::{Component, Path, PathBuf};
33use std::sync::OnceLock;
34
35/// The directories a run may write into.
36#[derive(Debug, Clone)]
37pub struct WriteScope {
38    root: PathBuf,
39    work_tree: Option<PathBuf>,
40    /// The Git work tree that contains the root, wherever the run starts.
41    /// A symlink in it is a link that the repository controls.
42    checkout: Option<PathBuf>,
43    /// The Git directory and common Git directory of the root and of each
44    /// superproject above it. No symlink may resolve into them, wherever
45    /// they are.
46    git_dirs: fallow_types::path_guard::GitDirs,
47    shared_dirs: Vec<PathBuf>,
48}
49
50/// Why [`WriteScope`] refuses a path.
51enum Refusal {
52    /// The path resolves outside the allowed directories.
53    Outside,
54    /// A symlink in the project leads out of the project, or into a `.git`
55    /// or `node_modules` directory.
56    Link {
57        link: PathBuf,
58        target: PathBuf,
59        kind: LinkTarget,
60    },
61    /// The path names a file that is not a regular file or a directory, and
62    /// is not a character device or named pipe that the user named directly.
63    Special,
64}
65
66/// Where a refused symlink in the project leads.
67#[derive(Clone, Copy)]
68enum LinkTarget {
69    /// Out of the project root and its allowed Git work tree.
70    Outside,
71    /// Into a `node_modules` directory.
72    Packages,
73    /// Into a `.git` directory, or the Git directory that a `.git` file names.
74    GitMetadata,
75}
76
77impl LinkTarget {
78    /// The place, as the end of a sentence that starts with "resolves".
79    const fn phrase(self) -> &'static str {
80        match self {
81            Self::Outside => "outside the project",
82            Self::Packages => "into a node_modules directory",
83            Self::GitMetadata => "into Git metadata",
84        }
85    }
86
87    fn of(within: Option<&Path>, target: &Path) -> Option<Self> {
88        let Some(within) = within else {
89            return Some(Self::Outside);
90        };
91        if !fallow_types::path_guard::is_protected_link_target(within, target) {
92            return None;
93        }
94        let below = target.strip_prefix(within).unwrap_or(target);
95        let in_packages = below.components().any(|component| {
96            component
97                .as_os_str()
98                .to_str()
99                .is_some_and(|name| name.eq_ignore_ascii_case("node_modules"))
100        });
101        Some(if in_packages {
102            Self::Packages
103        } else {
104            Self::GitMetadata
105        })
106    }
107}
108
109impl WriteScope {
110    /// Build the scope for a project root.
111    ///
112    /// The Git work tree that contains the root counts only when `cwd` is
113    /// inside it too. That is the monorepo case the allowance exists for. It
114    /// keeps a Git repository at `$HOME` (a dotfiles setup) from allowing
115    /// every home path to a run started outside that tree.
116    ///
117    /// # Errors
118    ///
119    /// Returns a message when the root cannot be resolved, so a caller fails
120    /// closed.
121    pub fn new(root: &Path, cwd: &Path, shared_dirs: Vec<PathBuf>) -> Result<Self, String> {
122        let root = root.canonicalize().map_err(|err| {
123            format!(
124                "the project root {} cannot be resolved ({err})",
125                root.display()
126            )
127        })?;
128        let cwd = cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf());
129        let checkout = fallow_types::path_guard::work_tree_top(&root).map(Path::to_path_buf);
130        let work_tree = checkout.clone().filter(|tree| cwd.starts_with(tree));
131        let git_dirs = fallow_types::path_guard::GitDirs::of(&root);
132        Ok(Self {
133            root,
134            work_tree,
135            checkout,
136            git_dirs,
137            shared_dirs,
138        })
139    }
140
141    /// Whether a write to the absolute path `path`, as written, stays in the
142    /// scope. See [`Self::check`] for the rules.
143    #[must_use]
144    pub fn contains(&self, path: &Path) -> bool {
145        walk(path).is_ok_and(|walk| self.refusal(&walk).is_none())
146    }
147
148    /// Return an error message when a write to `path`, relative to `cwd`,
149    /// leaves the scope. `flag` names the option that asked for the write.
150    ///
151    /// - The path must resolve inside one of the allowed directories, or be
152    ///   an existing character device or named pipe.
153    /// - Each symlink on the way that lies in the project root or its Git
154    ///   work tree must resolve inside the root or the allowed work tree.
155    /// - No symlink on the way, wherever it lies, may resolve into a `.git`
156    ///   or `node_modules` directory
157    ///   ([`fallow_types::path_guard::is_protected_link_target`]), or into
158    ///   the Git directory or common Git directory of the root or of a
159    ///   superproject above it, also when that directory is outside the work
160    ///   tree. A shared
161    ///   directory or a device is allowed only for a path that reaches it
162    ///   without such a link.
163    /// - An existing target that is not a regular file or a directory is
164    ///   refused, except a character device or named pipe that is reached
165    ///   without such a link.
166    /// - A path component that cannot be read for a reason other than "not
167    ///   found" is refused.
168    #[must_use]
169    pub fn check(&self, flag: &str, path: &Path, cwd: &Path) -> Option<String> {
170        if is_null_device(path) {
171            return None;
172        }
173        let walk = match walk(&cwd.join(path)) {
174            Ok(walk) => walk,
175            Err(err) => {
176                return Some(format!(
177                    "{flag} {} cannot be resolved ({err}). Choose a path that fallow can read.",
178                    path.display()
179                ));
180            }
181        };
182        let refusal = self.refusal(&walk)?;
183        Some(match refusal {
184            Refusal::Outside => format!(
185                "{flag} {} resolves to {}, which is outside the project root {}. Choose a path inside the project root{}, or inside the CI workspace (GITHUB_WORKSPACE or CI_PROJECT_DIR) or a temp directory (RUNNER_TEMP, the system temp directory, or /tmp on Unix).",
186                path.display(),
187                walk.resolved.display(),
188                self.root.display(),
189                self.work_tree
190                    .as_deref()
191                    .filter(|tree| *tree != self.root)
192                    .map(|tree| format!(" or its Git work tree {}", tree.display()))
193                    .unwrap_or_default(),
194            ),
195            Refusal::Link { link, target, kind } => format!(
196                "{flag} {} goes through the symlink {}, which resolves {} ({}). No symlink on the path may resolve into a .git or node_modules directory, and a symlink in the project must resolve inside the project. Choose a path without the symlink.",
197                path.display(),
198                link.display(),
199                kind.phrase(),
200                target.display(),
201            ),
202            Refusal::Special => format!(
203                "{flag} {} resolves to {}, which is not a regular file. Choose a path to a regular file.",
204                path.display(),
205                walk.resolved.display(),
206            ),
207        })
208    }
209
210    fn refusal(&self, walk: &Walk) -> Option<Refusal> {
211        let mut through_project_link = false;
212        for link in &walk.links {
213            let kind = if self.git_dirs.holds(&link.target) {
214                Some(LinkTarget::GitMetadata)
215            } else if self.in_checkout(&link.location) {
216                through_project_link = true;
217                let within = if link.target.starts_with(&self.root) {
218                    Some(self.root.as_path())
219                } else {
220                    self.work_tree
221                        .as_deref()
222                        .filter(|tree| link.target.starts_with(tree))
223                };
224                LinkTarget::of(within, &link.target)
225            } else {
226                // A link elsewhere may lead anywhere outside the project, but
227                // not into Git metadata or installed packages.
228                LinkTarget::of(Some(self.protected_scope_for(link)), &link.target)
229                    .filter(|kind| !matches!(kind, LinkTarget::Outside))
230            };
231            if let Some(kind) = kind {
232                return Some(Refusal::Link {
233                    link: link.location.clone(),
234                    target: link.target.clone(),
235                    kind,
236                });
237            }
238        }
239        match std::fs::metadata(&walk.resolved) {
240            Ok(meta) if !meta.is_file() && !meta.is_dir() => {
241                return (through_project_link || !is_stream_target(&walk.resolved))
242                    .then_some(Refusal::Special);
243            }
244            Ok(_) => {}
245            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
246            Err(_) => return Some(Refusal::Special),
247        }
248        let path = walk.resolved.as_path();
249        let inside = path.starts_with(&self.root)
250            || self
251                .work_tree
252                .as_deref()
253                .is_some_and(|tree| path.starts_with(tree))
254            || self.shared_dirs.iter().any(|dir| path.starts_with(dir));
255        (!inside).then_some(Refusal::Outside)
256    }
257
258    /// Why a write to the absolute path `path` leaves the scope, as the end
259    /// of a sentence that starts with "resolves", or `None` when it stays in
260    /// the scope.
261    #[must_use]
262    pub fn refusal_reason(&self, path: &Path) -> Option<&'static str> {
263        let Ok(walk) = walk(path) else {
264            return Some("to a path that cannot be read");
265        };
266        Some(match self.refusal(&walk)? {
267            Refusal::Outside => "outside the project",
268            Refusal::Link { kind, .. } => kind.phrase(),
269            Refusal::Special => "to a file that is not a regular file",
270        })
271    }
272
273    /// The directory that the protected names of the target of a link
274    /// outside the checkout are read below: the root or the checkout when the
275    /// target is inside one, else the folder of the link.
276    fn protected_scope_for<'a>(&'a self, link: &'a Link) -> &'a Path {
277        if link.target.starts_with(&self.root) {
278            return &self.root;
279        }
280        if let Some(tree) = self
281            .checkout
282            .as_deref()
283            .filter(|tree| link.target.starts_with(tree))
284        {
285            return tree;
286        }
287        link.location.parent().unwrap_or(&link.location)
288    }
289
290    fn in_checkout(&self, path: &Path) -> bool {
291        path.starts_with(&self.root)
292            || self
293                .checkout
294                .as_deref()
295                .is_some_and(|tree| path.starts_with(tree))
296    }
297
298    fn refusal_error(&self, requested: &Path, walk: &Walk) -> Option<io::Error> {
299        let reason = match self.refusal(walk)? {
300            Refusal::Outside => format!(
301                "{} resolves to {}, which is outside the directories this run may write to",
302                requested.display(),
303                walk.resolved.display()
304            ),
305            Refusal::Link { link, target, kind } => format!(
306                "{} goes through the symlink {}, which resolves {} ({}), so fallow did not write it",
307                requested.display(),
308                link.display(),
309                kind.phrase(),
310                target.display()
311            ),
312            Refusal::Special => format!(
313                "{} resolves to {}, which is not a regular file, so fallow did not write it",
314                requested.display(),
315                walk.resolved.display()
316            ),
317        };
318        Some(io::Error::new(io::ErrorKind::PermissionDenied, reason))
319    }
320}
321
322/// The environment variables that name a shared directory a run may write
323/// into: the GitHub Actions workspace and temp directory, and the GitLab
324/// project directory.
325const SHARED_DIR_VARIABLES: [&str; 3] = ["GITHUB_WORKSPACE", "CI_PROJECT_DIR", "RUNNER_TEMP"];
326
327/// The shared directories a run may write into: each directory in
328/// `GITHUB_WORKSPACE`, `CI_PROJECT_DIR` and `RUNNER_TEMP` that is set and not
329/// empty, and the system temp directories (see [`system_temp_dirs`]). The CI
330/// workspace keeps a job working that checks the repository out into a
331/// subdirectory and writes its report beside it. A directory that does not
332/// exist is skipped, because it cannot be resolved.
333#[must_use]
334pub fn shared_dirs() -> Vec<PathBuf> {
335    shared_dirs_for(std::env::temp_dir())
336}
337
338fn shared_dirs_for(temp_dir: PathBuf) -> Vec<PathBuf> {
339    SHARED_DIR_VARIABLES
340        .iter()
341        .filter_map(std::env::var_os)
342        .filter(|value| !value.is_empty())
343        .map(PathBuf::from)
344        .chain(temp_dirs_with(temp_dir))
345        .filter_map(|dir| dir.canonicalize().ok())
346        .collect()
347}
348
349/// The system temp directory on Unix. It is listed on its own because macOS
350/// sets `TMPDIR` to a per-user folder, so `std::env::temp_dir()` is not
351/// `/tmp` there.
352const UNIX_SYSTEM_TEMP_DIR: &str = "/tmp";
353
354/// The system temp directories: `std::env::temp_dir()`, and on Unix also
355/// `/tmp`. The paths are not resolved. `/var/tmp` is not in the list: Linux
356/// keeps it across reboots, and people keep long-lived clones there.
357#[must_use]
358pub fn system_temp_dirs() -> Vec<PathBuf> {
359    temp_dirs_with(std::env::temp_dir())
360}
361
362fn temp_dirs_with(temp_dir: PathBuf) -> Vec<PathBuf> {
363    let mut dirs = vec![temp_dir];
364    if cfg!(unix) {
365        dirs.push(PathBuf::from(UNIX_SYSTEM_TEMP_DIR));
366    }
367    dirs
368}
369
370/// Whether `path` is an existing character device or named pipe. A write to
371/// one cannot create or replace a file, so it needs no confinement.
372#[cfg(unix)]
373fn is_stream_target(path: &Path) -> bool {
374    use std::os::unix::fs::FileTypeExt;
375    std::fs::metadata(path).is_ok_and(|meta| {
376        let file_type = meta.file_type();
377        file_type.is_char_device() || file_type.is_fifo()
378    })
379}
380
381#[cfg(not(unix))]
382const fn is_stream_target(_path: &Path) -> bool {
383    false
384}
385
386/// The device path of the Windows null device.
387#[cfg(windows)]
388const WINDOWS_NULL_DEVICE: &str = r"\\.\NUL";
389
390/// Whether `path`, as the command line gave it, names the null device on
391/// this platform. Only Windows has a device name that the path check must
392/// know: the resolved path of `NUL` is a normal path in the working
393/// directory, where the device name no longer applies.
394fn is_null_device(path: &Path) -> bool {
395    cfg!(windows) && names_windows_null_device(path)
396}
397
398/// Whether `path` names the Windows null device: `NUL` alone, in any case,
399/// with an optional colon, or the device path `\\.\NUL`.
400///
401/// A name with an extension (`NUL.txt`) and `NUL` inside a directory are not
402/// included. Windows versions do not agree on them, so they stay normal
403/// paths and get the normal check.
404fn names_windows_null_device(path: &Path) -> bool {
405    let Some(text) = path.to_str() else {
406        return false;
407    };
408    let name = text
409        .strip_prefix(r"\\.\")
410        .or_else(|| text.strip_prefix("//./"))
411        .unwrap_or_else(|| text.strip_suffix(':').unwrap_or(text));
412    name.eq_ignore_ascii_case("NUL")
413}
414
415/// What kind of file a write targets. The kind selects the scope that the
416/// write is checked against.
417#[derive(Debug, Clone, Copy, PartialEq, Eq)]
418pub enum WriteTarget {
419    /// A path from the command line, or a default destination in the root.
420    Path,
421    /// The config file that fallow discovered and read for the project. The
422    /// Git work tree of the root counts for it wherever the run starts.
423    DiscoveredConfig,
424}
425
426/// The scopes recorded for this process.
427#[derive(Debug)]
428struct Confinement {
429    cwd: PathBuf,
430    paths: WriteScope,
431    config: WriteScope,
432}
433
434static CONFINEMENT: OnceLock<Confinement> = OnceLock::new();
435
436/// Record the scopes that later writes are checked against. The first call
437/// wins. Without a call, writes are not confined, but they still do not
438/// follow a symlink at the final component that appears after the path was
439/// resolved.
440pub fn confine(cwd: PathBuf, paths: WriteScope, config: WriteScope) {
441    let _ = CONFINEMENT.set(Confinement { cwd, paths, config });
442}
443
444/// Why a confined write did not happen.
445#[derive(Debug)]
446pub enum WriteFailure {
447    /// A missing parent directory could not be created.
448    Directory(io::Error),
449    /// The file could not be created or written, or the path resolved
450    /// outside the recorded scope, or a path component changed after the
451    /// check.
452    File(io::Error),
453}
454
455impl WriteFailure {
456    /// Whether the failure happened while the parent directories were
457    /// created, so nothing was written.
458    #[must_use]
459    pub const fn is_directory(&self) -> bool {
460        matches!(self, Self::Directory(_))
461    }
462}
463
464impl std::fmt::Display for WriteFailure {
465    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
466        match self {
467            Self::Directory(error) | Self::File(error) => error.fmt(f),
468        }
469    }
470}
471
472impl std::error::Error for WriteFailure {}
473
474impl From<WriteFailure> for io::Error {
475    fn from(failure: WriteFailure) -> Self {
476        match failure {
477            WriteFailure::Directory(error) | WriteFailure::File(error) => error,
478        }
479    }
480}
481
482/// Create or truncate `path` for writing, after the checks this module
483/// describes. Missing parent directories are created.
484///
485/// # Errors
486///
487/// Returns [`WriteFailure::Directory`] when a parent directory cannot be
488/// created. Returns [`WriteFailure::File`] with `PermissionDenied` when the
489/// path resolves outside the recorded scope, or when a path component changed
490/// while the parent directories were created, and with the error of the open
491/// call when the final component became a symlink after the path was resolved
492/// (Unix) or the file cannot be created.
493pub fn create_file(path: &Path, target: WriteTarget) -> Result<File, WriteFailure> {
494    let confinement = CONFINEMENT.get();
495    let absolute = match confinement {
496        Some(confinement) => confinement.cwd.join(path),
497        None => std::env::current_dir().map_or_else(|_| path.to_path_buf(), |cwd| cwd.join(path)),
498    };
499    let scope = confinement.map(|confinement| match target {
500        WriteTarget::Path => &confinement.paths,
501        WriteTarget::DiscoveredConfig => &confinement.config,
502    });
503    create_checked(path, &absolute, scope)
504}
505
506/// Write `contents` to `path` through [`create_file`].
507///
508/// # Errors
509///
510/// Returns the errors of [`create_file`], and a write or flush error as
511/// [`WriteFailure::File`].
512pub fn write_file(path: &Path, contents: &[u8], target: WriteTarget) -> Result<(), WriteFailure> {
513    let mut file = create_file(path, target)?;
514    file.write_all(contents).map_err(WriteFailure::File)?;
515    file.flush().map_err(WriteFailure::File)
516}
517
518fn create_checked(
519    requested: &Path,
520    absolute: &Path,
521    scope: Option<&WriteScope>,
522) -> Result<File, WriteFailure> {
523    if is_null_device(requested) {
524        return open_null_device().map_err(WriteFailure::File);
525    }
526    let walk = walk(absolute).map_err(WriteFailure::File)?;
527    if let Some(error) = scope.and_then(|scope| scope.refusal_error(requested, &walk)) {
528        return Err(WriteFailure::File(error));
529    }
530    let resolved = walk.resolved;
531    if is_stream_target(&resolved) {
532        return open_stream(&resolved).map_err(WriteFailure::File);
533    }
534    if let Some(parent) = resolved.parent()
535        && !parent.as_os_str().is_empty()
536    {
537        std::fs::create_dir_all(parent).map_err(WriteFailure::Directory)?;
538        // A missing component can become a symlink between the resolve and
539        // the create. The parent must still resolve to the same directory.
540        let real_parent = parent.canonicalize().map_err(WriteFailure::File)?;
541        if real_parent != parent {
542            return Err(WriteFailure::File(io::Error::new(
543                io::ErrorKind::PermissionDenied,
544                format!(
545                    "{} changed while fallow prepared the write, so fallow did not write it",
546                    requested.display()
547                ),
548            )));
549        }
550    }
551    open_no_follow(&resolved).map_err(WriteFailure::File)
552}
553
554/// Open an existing character device or named pipe for writing. It is not
555/// created and not truncated. On Unix the open does not follow a symlink at
556/// the final component, and the opened handle must still be a character
557/// device or named pipe, so a path swapped after the check is refused.
558fn open_stream(path: &Path) -> io::Result<File> {
559    let mut options = std::fs::OpenOptions::new();
560    options.write(true);
561    #[cfg(unix)]
562    {
563        use std::os::unix::fs::OpenOptionsExt;
564        options.custom_flags(libc::O_NOFOLLOW);
565    }
566    let file = options.open(path)?;
567    #[cfg(unix)]
568    ensure_stream_handle(&file, path)?;
569    Ok(file)
570}
571
572/// Open the Windows null device for writing through its device path.
573#[cfg(windows)]
574fn open_null_device() -> io::Result<File> {
575    std::fs::OpenOptions::new()
576        .write(true)
577        .open(WINDOWS_NULL_DEVICE)
578}
579
580/// Only Windows has a null device name that [`is_null_device`] accepts.
581#[cfg(not(windows))]
582fn open_null_device() -> io::Result<File> {
583    Err(io::Error::new(
584        io::ErrorKind::Unsupported,
585        "only Windows has a null device name",
586    ))
587}
588
589/// Refuse a handle that is not a character device or named pipe.
590#[cfg(unix)]
591fn ensure_stream_handle(file: &File, path: &Path) -> io::Result<()> {
592    use std::os::unix::fs::FileTypeExt;
593    let file_type = file.metadata()?.file_type();
594    if file_type.is_char_device() || file_type.is_fifo() {
595        return Ok(());
596    }
597    Err(io::Error::new(
598        io::ErrorKind::PermissionDenied,
599        format!(
600            "{} is no longer a device or a named pipe, so fallow did not write it",
601            path.display()
602        ),
603    ))
604}
605
606/// Open `path` for writing without following a symlink at the final
607/// component. On Unix the open call refuses the link itself. Elsewhere the
608/// final component is checked right before the open.
609fn open_no_follow(path: &Path) -> io::Result<File> {
610    let mut options = std::fs::OpenOptions::new();
611    options.write(true).create(true).truncate(true);
612    #[cfg(unix)]
613    {
614        use std::os::unix::fs::OpenOptionsExt;
615        options.custom_flags(libc::O_NOFOLLOW);
616    }
617    // This check and the open are two steps, so a link that appears between
618    // them is still followed. Only the Unix open closes that window.
619    #[cfg(not(unix))]
620    if path
621        .symlink_metadata()
622        .is_ok_and(|meta| meta.file_type().is_symlink())
623    {
624        return Err(io::Error::new(
625            io::ErrorKind::PermissionDenied,
626            format!(
627                "{} became a symlink after fallow checked it, so fallow did not write it",
628                path.display()
629            ),
630        ));
631    }
632    options.open(path)
633}
634
635/// How many symlinks [`resolve`] follows before it gives up.
636const MAX_LINK_HOPS: usize = 40;
637
638/// Resolve `path` the way a write would reach it: each component that exists
639/// is resolved by the file system, one at a time, so a symlink after a `..`
640/// is resolved too, and the rest, which a write would create, is kept as
641/// written. A dangling symlink is followed to its target, because a write
642/// through it lands there. When a component cannot be read, the path is
643/// normalised from its longest existing part.
644#[must_use]
645pub fn resolve(path: &Path) -> PathBuf {
646    walk(path).map_or_else(|_| canonical_form(path, 0), |walk| walk.resolved)
647}
648
649/// A symlink that a walk followed.
650struct Link {
651    /// Where the link is: its resolved parent directory and its name.
652    location: PathBuf,
653    /// Where the link leads, resolved.
654    target: PathBuf,
655}
656
657/// Where a write to a path lands, and the symlinks on the way.
658struct Walk {
659    resolved: PathBuf,
660    links: Vec<Link>,
661}
662
663/// Resolve `path` one component at a time, and record each symlink on the
664/// way. A relative path is relative to the working directory.
665///
666/// # Errors
667///
668/// Returns the error of a component that cannot be read for a reason other
669/// than "not found", an error after [`MAX_LINK_HOPS`] symlinks, and the error
670/// of the working directory for a relative path.
671fn walk(path: &Path) -> io::Result<Walk> {
672    let absolute;
673    let path = if path.is_absolute() {
674        path
675    } else {
676        absolute = std::env::current_dir()?.join(path);
677        &absolute
678    };
679    let mut links = Vec::new();
680    let mut hops = 0;
681    let walked = walk_components(path, &mut links, &mut hops)?;
682    Ok(Walk {
683        resolved: canonical_form(&walked, 0),
684        links,
685    })
686}
687
688fn walk_components(path: &Path, links: &mut Vec<Link>, hops: &mut usize) -> io::Result<PathBuf> {
689    let mut resolved = PathBuf::new();
690    for component in path.components() {
691        let name = match component {
692            Component::Prefix(_) | Component::RootDir => {
693                resolved.push(component.as_os_str());
694                continue;
695            }
696            Component::CurDir => continue,
697            Component::ParentDir => {
698                resolved.pop();
699                continue;
700            }
701            Component::Normal(name) => name,
702        };
703        let candidate = resolved.join(name);
704        match candidate.symlink_metadata() {
705            Ok(meta) if meta.file_type().is_symlink() => {
706                *hops += 1;
707                if *hops > MAX_LINK_HOPS {
708                    return Err(io::Error::new(
709                        io::ErrorKind::InvalidInput,
710                        format!("{} goes through too many symlinks", path.display()),
711                    ));
712                }
713                let target = std::fs::read_link(&candidate)?;
714                let followed = walk_components(&resolved.join(target), links, hops)?;
715                links.push(Link {
716                    location: canonical_form(&resolved, 0).join(name),
717                    target: canonical_form(&followed, 0),
718                });
719                resolved = followed;
720            }
721            Ok(_) => resolved = candidate,
722            Err(error) if error.kind() == io::ErrorKind::NotFound => resolved = candidate,
723            Err(error) => return Err(error),
724        }
725    }
726    Ok(resolved)
727}
728
729/// `path` with its longest existing part canonicalized and the rest appended
730/// as written. For a path from [`walk_components`] this only gives the
731/// spelling that `canonicalize` uses on this platform, so it compares equal
732/// with the canonical allowed directories.
733fn canonical_form(path: &Path, hops: usize) -> PathBuf {
734    let mut existing = path;
735    let mut missing = Vec::new();
736    loop {
737        if let Ok(real) = existing.canonicalize() {
738            return append_missing(real, &missing);
739        }
740        if hops < MAX_LINK_HOPS
741            && let Ok(target) = std::fs::read_link(existing)
742        {
743            let base = existing.parent().unwrap_or_else(|| Path::new(""));
744            let followed = canonical_form(&base.join(target), hops + 1);
745            return append_missing(followed, &missing);
746        }
747        let (Some(parent), Some(last)) = (existing.parent(), existing.components().next_back())
748        else {
749            return append_missing(PathBuf::new(), &missing);
750        };
751        missing.push(last);
752        existing = parent;
753    }
754}
755
756/// Append the components that do not exist yet, innermost last.
757fn append_missing(mut resolved: PathBuf, missing: &[Component<'_>]) -> PathBuf {
758    for component in missing.iter().rev() {
759        match component {
760            Component::ParentDir => {
761                resolved.pop();
762            }
763            Component::CurDir => {}
764            other => resolved.push(other.as_os_str()),
765        }
766    }
767    resolved
768}
769
770#[cfg(test)]
771mod tests {
772    use std::path::Path;
773
774    use super::{WriteScope, create_checked, names_windows_null_device, resolve};
775
776    /// macOS sets `TMPDIR` to a per-user folder, but a user who passes
777    /// `/tmp/x.json` means the system temp directory. Each Unix allows it,
778    /// whatever `TMPDIR` names.
779    #[cfg(unix)]
780    #[test]
781    fn scope_accepts_the_unix_system_temp_dir_when_tmpdir_names_another_folder() {
782        use super::shared_dirs_for;
783
784        let project = tempfile::tempdir().expect("project dir");
785        let other_temp = tempfile::tempdir().expect("temp dir");
786        let scope = WriteScope::new(
787            project.path(),
788            project.path(),
789            shared_dirs_for(other_temp.path().to_path_buf()),
790        )
791        .expect("scope");
792        assert_eq!(
793            scope.check("--save-baseline", Path::new("/tmp/x.json"), project.path()),
794            None
795        );
796    }
797
798    /// The Windows null device is named by `NUL` alone, in any case, with an
799    /// optional colon, or by its device path. A file name that only starts
800    /// with `NUL`, or `NUL` in a directory, is a normal file name.
801    #[test]
802    fn the_windows_null_device_is_named_by_nul_alone() {
803        for name in [
804            "NUL", "nul", "Nul", "NUL:", r"\\.\NUL", r"\\.\nul", "//./NUL",
805        ] {
806            assert!(names_windows_null_device(Path::new(name)), "{name}");
807        }
808        for name in [
809            "NUL.txt",
810            "nul.sarif",
811            "null",
812            "NULL",
813            "report",
814            r"dir\NUL",
815            "dir/nul",
816            r".\NUL",
817            r"C:\NUL",
818            "",
819        ] {
820            assert!(!names_windows_null_device(Path::new(name)), "{name}");
821        }
822    }
823
824    #[test]
825    fn resolve_normalises_the_missing_part() {
826        let dir = tempfile::tempdir().expect("temp dir");
827        let base = dir.path().canonicalize().unwrap();
828        assert_eq!(
829            resolve(&base.join("a/b/../c.json")),
830            base.join("a").join("c.json")
831        );
832        assert_eq!(
833            resolve(&base.join("a/../../x.json")),
834            base.parent().unwrap().join("x.json")
835        );
836    }
837
838    #[cfg(unix)]
839    #[test]
840    fn a_dangling_link_resolves_to_its_target() {
841        let dir = tempfile::tempdir().expect("temp dir");
842        let base = dir.path().canonicalize().unwrap();
843        let root = base.join("project");
844        std::fs::create_dir_all(&root).unwrap();
845        std::os::unix::fs::symlink(base.join("elsewhere.json"), root.join("b.json")).unwrap();
846        assert_eq!(resolve(&root.join("b.json")), base.join("elsewhere.json"));
847    }
848
849    #[test]
850    fn scope_accepts_a_temp_dir_through_a_symlinked_spelling() {
851        let dir = tempfile::tempdir().expect("temp dir");
852        let root = dir.path().join("project");
853        let temp = dir.path().join("temp");
854        std::fs::create_dir_all(&root).unwrap();
855        std::fs::create_dir_all(&temp).unwrap();
856        let scope =
857            WriteScope::new(&root, &root, vec![temp.canonicalize().unwrap()]).expect("scope");
858        // `dir.path()` is not canonical on macOS (`/var` links to
859        // `/private/var`), so this also checks that both sides are resolved.
860        assert!(
861            scope
862                .check("--save-baseline", &temp.join("b.json"), &root)
863                .is_none()
864        );
865        assert!(
866            scope
867                .check("--save-baseline", &dir.path().join("b.json"), &root)
868                .is_some()
869        );
870    }
871
872    #[test]
873    fn a_root_that_cannot_be_resolved_fails_closed() {
874        let dir = tempfile::tempdir().expect("temp dir");
875        let missing = dir.path().join("missing");
876        assert!(WriteScope::new(&missing, dir.path(), Vec::new()).is_err());
877    }
878
879    #[test]
880    fn the_work_tree_needs_the_working_directory_inside_it() {
881        let dir = tempfile::tempdir().expect("temp dir");
882        let home = dir.path().join("home");
883        let root = home.join("project");
884        let elsewhere = dir.path().join("elsewhere");
885        std::fs::create_dir_all(&root).unwrap();
886        std::fs::create_dir_all(&elsewhere).unwrap();
887        std::fs::create_dir_all(home.join(".git")).unwrap();
888        let target = home.join(".config").join("x.json");
889        let from_outside = WriteScope::new(&root, &elsewhere, Vec::new()).expect("scope");
890        assert!(
891            from_outside
892                .check("--save-baseline", &target, &elsewhere)
893                .is_some()
894        );
895        let from_inside = WriteScope::new(&root, &home, Vec::new()).expect("scope");
896        assert!(
897            from_inside
898                .check("--save-baseline", &target, &home)
899                .is_none()
900        );
901    }
902
903    #[test]
904    fn scope_accepts_the_root_and_rejects_a_sibling() {
905        let dir = tempfile::tempdir().expect("temp dir");
906        let root = dir.path().join("project");
907        std::fs::create_dir_all(&root).unwrap();
908        let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
909        assert!(
910            scope
911                .check("--save-baseline", "nested/b.json".as_ref(), &root)
912                .is_none()
913        );
914        let message = scope
915            .check("--save-baseline", "../b.json".as_ref(), &root)
916            .expect("outside");
917        assert!(message.contains("outside the project root"), "{message}");
918    }
919
920    #[test]
921    fn scope_accepts_the_git_work_tree_of_the_root() {
922        let dir = tempfile::tempdir().expect("temp dir");
923        let repo = dir.path().join("repo");
924        let root = repo.join("packages/app");
925        std::fs::create_dir_all(&root).unwrap();
926        std::fs::create_dir_all(repo.join(".git")).unwrap();
927        let scope = WriteScope::new(&root, &repo, Vec::new()).expect("scope");
928        assert!(
929            scope
930                .check("--save-baseline", "baselines/b.json".as_ref(), &repo)
931                .is_none()
932        );
933        let message = scope
934            .check("--save-baseline", "../b.json".as_ref(), &repo)
935            .expect("outside");
936        assert!(message.contains("Git work tree"), "{message}");
937    }
938
939    #[test]
940    fn a_checked_write_lands_inside_the_scope() {
941        let dir = tempfile::tempdir().expect("temp dir");
942        let root = dir.path().join("project");
943        std::fs::create_dir_all(&root).unwrap();
944        let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
945        let target = root.join("out/nested/report.json");
946        assert!(scope.check("--output-file", &target, &root).is_none());
947        let file = create_checked(&target, &target, Some(&scope)).expect("write inside");
948        drop(file);
949        assert!(target.is_file());
950    }
951
952    /// A character device is allowed and written through.
953    #[cfg(unix)]
954    #[test]
955    fn a_character_device_is_allowed_outside_the_scope() {
956        let dir = tempfile::tempdir().expect("temp dir");
957        let root = dir.path().join("project");
958        std::fs::create_dir_all(&root).unwrap();
959        let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
960        let null = std::path::Path::new("/dev/null");
961        assert!(scope.check("--output-file", null, &root).is_none());
962        let file = create_checked(null, null, Some(&scope)).expect("write to /dev/null");
963        drop(file);
964    }
965
966    /// A named pipe outside the scope is allowed, and the write reaches the
967    /// reader.
968    #[cfg(unix)]
969    #[test]
970    fn a_named_pipe_is_allowed_outside_the_scope() {
971        use std::io::Write as _;
972        let dir = tempfile::tempdir().expect("temp dir");
973        let root = dir.path().join("project");
974        std::fs::create_dir_all(&root).unwrap();
975        let fifo = dir.path().join("report.fifo");
976        let made = std::process::Command::new("mkfifo")
977            .arg(&fifo)
978            .status()
979            .expect("run mkfifo");
980        assert!(made.success());
981        let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
982        assert!(scope.check("--sarif-file", &fifo, &root).is_none());
983        let reader_path = fifo.clone();
984        let reader = std::thread::spawn(move || std::fs::read_to_string(reader_path));
985        let mut file = create_checked(&fifo, &fifo, Some(&scope)).expect("write to fifo");
986        file.write_all(b"sarif").unwrap();
987        drop(file);
988        assert_eq!(reader.join().unwrap().unwrap(), "sarif");
989    }
990
991    /// A stream target is refused when the path is a symlink at the open, or
992    /// when the opened handle is a regular file.
993    #[cfg(unix)]
994    #[test]
995    fn a_stream_target_swapped_after_the_check_is_refused() {
996        use super::{ensure_stream_handle, open_stream};
997        let dir = tempfile::tempdir().expect("temp dir");
998        let link = dir.path().join("null-link");
999        std::os::unix::fs::symlink("/dev/null", &link).unwrap();
1000        assert!(open_stream(&link).is_err(), "a symlink is not followed");
1001
1002        let regular = dir.path().join("regular.json");
1003        std::fs::write(&regular, "keep").unwrap();
1004        assert!(open_stream(&regular).is_err(), "a regular file is refused");
1005        let handle = std::fs::File::open(&regular).unwrap();
1006        assert!(ensure_stream_handle(&handle, &regular).is_err());
1007        assert_eq!(std::fs::read_to_string(&regular).unwrap(), "keep");
1008
1009        let null = std::fs::File::open("/dev/null").unwrap();
1010        assert!(ensure_stream_handle(&null, std::path::Path::new("/dev/null")).is_ok());
1011    }
1012
1013    /// A directory that passed the check and then became a symlink to a
1014    /// place outside the project does not carry the write out.
1015    #[cfg(unix)]
1016    #[test]
1017    fn a_directory_swapped_for_a_symlink_after_the_check_is_refused() {
1018        let dir = tempfile::tempdir().expect("temp dir");
1019        let root = dir.path().join("project");
1020        let elsewhere = dir.path().join("elsewhere");
1021        std::fs::create_dir_all(root.join("out")).unwrap();
1022        std::fs::create_dir_all(&elsewhere).unwrap();
1023        let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1024        let target = root.join("out/report.json");
1025        assert!(scope.check("--output-file", &target, &root).is_none());
1026
1027        std::fs::remove_dir(root.join("out")).unwrap();
1028        std::os::unix::fs::symlink(&elsewhere, root.join("out")).unwrap();
1029
1030        let error = std::io::Error::from(
1031            create_checked(&target, &target, Some(&scope)).expect_err("refused"),
1032        );
1033        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1034        assert!(!elsewhere.join("report.json").exists());
1035    }
1036
1037    /// A final component that became a symlink after the check is refused,
1038    /// also when the link points outside the project.
1039    #[cfg(unix)]
1040    #[test]
1041    fn a_file_swapped_for_a_symlink_after_the_check_is_refused() {
1042        let dir = tempfile::tempdir().expect("temp dir");
1043        let root = dir.path().join("project");
1044        std::fs::create_dir_all(&root).unwrap();
1045        let outside = dir.path().join("outside.json");
1046        let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1047        let target = root.join("report.json");
1048        assert!(scope.check("--output-file", &target, &root).is_none());
1049
1050        std::os::unix::fs::symlink(&outside, &target).unwrap();
1051
1052        assert!(create_checked(&target, &target, Some(&scope)).is_err());
1053        assert!(!outside.exists());
1054    }
1055
1056    /// A `..` after a folder that does not exist yet returns to a folder that
1057    /// exists, so a link after it is resolved too. Nothing is created
1058    /// outside the project.
1059    #[cfg(unix)]
1060    #[test]
1061    fn a_link_after_a_parent_step_is_resolved() {
1062        let dir = tempfile::tempdir().expect("temp dir");
1063        let root = dir.path().join("project");
1064        let elsewhere = dir.path().join("elsewhere");
1065        std::fs::create_dir_all(&root).unwrap();
1066        std::fs::create_dir_all(&elsewhere).unwrap();
1067        std::os::unix::fs::symlink(&elsewhere, root.join("away")).unwrap();
1068        let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1069        let requested = Path::new("build/../away/x/r.json");
1070        assert!(scope.check("--output-file", requested, &root).is_some());
1071        let absolute = root.join(requested);
1072        assert!(create_checked(requested, &absolute, Some(&scope)).is_err());
1073        assert!(!elsewhere.join("x").exists());
1074        assert!(!root.join("build").exists());
1075    }
1076
1077    /// A link in the project that leads into a shared directory, such as the
1078    /// temp directory or the CI workspace, does not carry a write there.
1079    #[cfg(unix)]
1080    #[test]
1081    fn a_project_link_into_a_shared_dir_is_refused() {
1082        let dir = tempfile::tempdir().expect("temp dir");
1083        let root = dir.path().join("project");
1084        let shared = dir.path().join("workspace");
1085        std::fs::create_dir_all(&root).unwrap();
1086        std::fs::create_dir_all(&shared).unwrap();
1087        std::fs::write(shared.join("run.sh"), "keep").unwrap();
1088        std::os::unix::fs::symlink(shared.join("run.sh"), root.join("report.sarif")).unwrap();
1089        let scope =
1090            WriteScope::new(&root, &root, vec![shared.canonicalize().unwrap()]).expect("scope");
1091        let target = root.join("report.sarif");
1092        assert!(scope.check("--sarif-file", &target, &root).is_some());
1093        assert!(create_checked(&target, &target, Some(&scope)).is_err());
1094        assert_eq!(
1095            std::fs::read_to_string(shared.join("run.sh")).unwrap(),
1096            "keep"
1097        );
1098        assert!(
1099            scope
1100                .check("--sarif-file", &shared.join("report.sarif"), &root)
1101                .is_none()
1102        );
1103    }
1104
1105    /// A link in the project to a named pipe is refused, while a pipe that
1106    /// the user names directly stays allowed.
1107    #[cfg(unix)]
1108    #[test]
1109    fn a_project_link_to_a_named_pipe_is_refused() {
1110        let dir = tempfile::tempdir().expect("temp dir");
1111        let root = dir.path().join("project");
1112        std::fs::create_dir_all(&root).unwrap();
1113        let fifo = dir.path().join("report.fifo");
1114        let made = std::process::Command::new("mkfifo")
1115            .arg(&fifo)
1116            .status()
1117            .expect("run mkfifo");
1118        assert!(made.success());
1119        std::os::unix::fs::symlink(&fifo, root.join("report.json")).unwrap();
1120        let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1121        assert!(
1122            scope
1123                .check("--output-file", &root.join("report.json"), &root)
1124                .is_some()
1125        );
1126        assert!(scope.check("--output-file", &fifo, &root).is_none());
1127    }
1128
1129    /// A link that stays in the project but leads into `.git` or
1130    /// `node_modules` is refused. A link to another project folder passes.
1131    #[cfg(unix)]
1132    #[test]
1133    fn a_project_link_into_git_or_node_modules_is_refused() {
1134        let dir = tempfile::tempdir().expect("temp dir");
1135        let root = dir.path().join("project");
1136        std::fs::create_dir_all(root.join(".git")).unwrap();
1137        std::fs::create_dir_all(root.join("node_modules/pkg")).unwrap();
1138        std::fs::create_dir_all(root.join("reports")).unwrap();
1139        std::os::unix::fs::symlink(root.join(".git"), root.join("meta")).unwrap();
1140        std::os::unix::fs::symlink(root.join("node_modules/pkg"), root.join("pkg")).unwrap();
1141        std::os::unix::fs::symlink(root.join("reports"), root.join("out")).unwrap();
1142        let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1143        for refused in ["meta/config", "pkg/index.js"] {
1144            assert!(
1145                scope
1146                    .check("--output-file", Path::new(refused), &root)
1147                    .is_some(),
1148                "{refused}"
1149            );
1150            let absolute = root.join(refused);
1151            assert!(create_checked(Path::new(refused), &absolute, Some(&scope)).is_err());
1152        }
1153        assert!(!root.join(".git/config").exists());
1154        assert!(
1155            scope
1156                .check("--output-file", Path::new("out/r.json"), &root)
1157                .is_none()
1158        );
1159    }
1160
1161    /// A link outside the project that leads into the `.git` directory of
1162    /// the project is refused too, and the hook keeps its content.
1163    #[cfg(unix)]
1164    #[test]
1165    fn an_outside_link_into_git_metadata_is_refused() {
1166        let dir = tempfile::tempdir().expect("temp dir");
1167        let root = dir.path().join("project");
1168        let shared = dir.path().join("shared");
1169        std::fs::create_dir_all(root.join(".git/hooks")).unwrap();
1170        std::fs::create_dir_all(&shared).unwrap();
1171        let hook = root.join(".git/hooks/pre-commit");
1172        std::fs::write(&hook, "keep").unwrap();
1173        let link = shared.join("r.json");
1174        std::os::unix::fs::symlink(&hook, &link).unwrap();
1175        let scope =
1176            WriteScope::new(&root, &root, vec![shared.canonicalize().unwrap()]).expect("scope");
1177        assert!(scope.check("--output-file", &link, &root).is_some());
1178        assert!(create_checked(&link, &link, Some(&scope)).is_err());
1179        assert_eq!(std::fs::read_to_string(&hook).unwrap(), "keep");
1180    }
1181
1182    /// A project whose Git directory is outside the work tree
1183    /// (`git init --separate-git-dir`) keeps its hooks there. A link outside
1184    /// the project into that Git directory is refused too.
1185    #[cfg(unix)]
1186    #[test]
1187    fn an_outside_link_into_a_separate_git_dir_is_refused() {
1188        let dir = tempfile::tempdir().expect("temp dir");
1189        let root = dir.path().join("project");
1190        let shared = dir.path().join("shared");
1191        let git_dir = shared.join("gd");
1192        std::fs::create_dir_all(git_dir.join("hooks")).unwrap();
1193        std::fs::create_dir_all(&root).unwrap();
1194        std::fs::write(
1195            root.join(".git"),
1196            format!("gitdir: {}\n", git_dir.display()),
1197        )
1198        .unwrap();
1199        let hook = git_dir.join("hooks/pre-commit");
1200        std::fs::write(&hook, "keep").unwrap();
1201        let link = shared.join("r.json");
1202        std::os::unix::fs::symlink(&hook, &link).unwrap();
1203        let scope =
1204            WriteScope::new(&root, &root, vec![shared.canonicalize().unwrap()]).expect("scope");
1205        assert!(scope.check("--output-file", &link, &root).is_some());
1206        assert!(!scope.contains(&link));
1207        assert!(create_checked(&link, &link, Some(&scope)).is_err());
1208        assert_eq!(std::fs::read_to_string(&hook).unwrap(), "keep");
1209    }
1210
1211    /// The same for a worktree of a bare repository: the link leads into the
1212    /// common Git directory, which holds the hooks.
1213    #[cfg(unix)]
1214    #[test]
1215    fn an_outside_link_into_the_common_git_dir_of_a_worktree_is_refused() {
1216        let dir = tempfile::tempdir().expect("temp dir");
1217        let shared = dir.path().join("shared");
1218        let bare = shared.join("repo.git");
1219        let linked = bare.join("worktrees/project");
1220        std::fs::create_dir_all(&linked).unwrap();
1221        std::fs::create_dir_all(bare.join("hooks")).unwrap();
1222        std::fs::write(linked.join("commondir"), "../..\n").unwrap();
1223        let root = dir.path().join("project");
1224        std::fs::create_dir_all(&root).unwrap();
1225        std::fs::write(root.join(".git"), format!("gitdir: {}\n", linked.display())).unwrap();
1226        let hook = bare.join("hooks/pre-commit");
1227        std::fs::write(&hook, "keep").unwrap();
1228        let link = shared.join("r.json");
1229        std::os::unix::fs::symlink(&hook, &link).unwrap();
1230        let scope =
1231            WriteScope::new(&root, &root, vec![shared.canonicalize().unwrap()]).expect("scope");
1232        assert!(scope.check("--output-file", &link, &root).is_some());
1233        assert_eq!(std::fs::read_to_string(&hook).unwrap(), "keep");
1234    }
1235
1236    /// A worktree of a bare repository lies inside the common Git directory.
1237    /// A link in it to another file of the same worktree is allowed, and a
1238    /// link into the Git directory is still refused.
1239    #[cfg(unix)]
1240    #[test]
1241    fn a_link_inside_a_worktree_of_a_bare_repository_is_allowed() {
1242        let dir = tempfile::tempdir().expect("temp dir");
1243        let bare = dir.path().join("proj.git");
1244        let linked = bare.join("worktrees/main");
1245        std::fs::create_dir_all(&linked).unwrap();
1246        std::fs::create_dir_all(bare.join("hooks")).unwrap();
1247        std::fs::write(linked.join("commondir"), "../..\n").unwrap();
1248        let root = bare.join("main");
1249        std::fs::create_dir_all(root.join("reports")).unwrap();
1250        std::fs::write(root.join(".git"), format!("gitdir: {}\n", linked.display())).unwrap();
1251        std::os::unix::fs::symlink(root.join("reports"), root.join("out")).unwrap();
1252        std::os::unix::fs::symlink(bare.join("hooks"), root.join("hooks")).unwrap();
1253        let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1254        assert!(scope.contains(&root.join("out/r.json")));
1255        assert!(scope.contains(&root.join("reports/r.json")));
1256        assert!(!scope.contains(&root.join("hooks/pre-commit")));
1257    }
1258
1259    /// A `.git` entry counts for the checkout when it exists as an entry,
1260    /// also as a dangling link, the same rule that the cache guard uses.
1261    #[cfg(unix)]
1262    #[test]
1263    fn a_dangling_git_link_marks_the_checkout() {
1264        let dir = tempfile::tempdir().expect("temp dir");
1265        let repo = dir.path().join("repo");
1266        std::fs::create_dir_all(repo.join("pkg")).unwrap();
1267        std::os::unix::fs::symlink(dir.path().join("missing"), repo.join(".git")).unwrap();
1268        let scope = WriteScope::new(&repo.join("pkg"), &repo, Vec::new()).expect("scope");
1269        assert!(scope.contains(&repo.join("r.json")));
1270    }
1271
1272    /// A socket is not a regular file, so a write to it is refused.
1273    #[cfg(unix)]
1274    #[test]
1275    fn a_socket_target_is_refused() {
1276        let dir = tempfile::tempdir().expect("temp dir");
1277        let root = dir.path().join("project");
1278        std::fs::create_dir_all(&root).unwrap();
1279        let socket = root.join("s.sock");
1280        let _listener = std::os::unix::net::UnixListener::bind(&socket).expect("bind");
1281        let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1282        assert!(scope.check("--output-file", &socket, &root).is_some());
1283    }
1284
1285    /// A folder that cannot be read is refused instead of treated as
1286    /// missing.
1287    #[cfg(unix)]
1288    #[test]
1289    fn a_component_that_cannot_be_read_is_refused() {
1290        use std::os::unix::fs::PermissionsExt;
1291        let dir = tempfile::tempdir().expect("temp dir");
1292        let root = dir.path().join("project");
1293        let closed = root.join("closed");
1294        std::fs::create_dir_all(&closed).unwrap();
1295        std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o000)).unwrap();
1296        let readable = closed.join("probe").symlink_metadata();
1297        let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
1298        let result = scope.check("--output-file", Path::new("closed/sub/r.json"), &root);
1299        std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o755)).unwrap();
1300        // A superuser reads the folder anyway, so the case does not apply.
1301        if readable.is_err_and(|error| error.kind() == std::io::ErrorKind::PermissionDenied) {
1302            assert!(result.is_some());
1303        }
1304    }
1305
1306    /// The open itself refuses a symlink at the final component, which covers
1307    /// a link that appears after the path was resolved.
1308    #[cfg(unix)]
1309    #[test]
1310    fn the_open_does_not_follow_a_final_symlink() {
1311        let dir = tempfile::tempdir().expect("temp dir");
1312        let real = dir.path().join("real.json");
1313        std::fs::write(&real, "keep").unwrap();
1314        let link = dir.path().join("link.json");
1315        std::os::unix::fs::symlink(&real, &link).unwrap();
1316
1317        assert!(super::open_no_follow(&link).is_err());
1318        assert_eq!(std::fs::read_to_string(&real).unwrap(), "keep");
1319    }
1320
1321    /// Run a fixture `git` command in `dir` and require that it succeeds.
1322    #[cfg(unix)]
1323    fn git(dir: &Path, args: &[&str]) {
1324        let output = crate::git_fixture::fixture_git_command(dir)
1325            .args([
1326                "-c",
1327                "protocol.file.allow=always",
1328                "-c",
1329                "init.defaultBranch=main",
1330            ])
1331            .args(args)
1332            .output()
1333            .expect("run git");
1334        assert!(
1335            output.status.success(),
1336            "git {args:?}: {}",
1337            String::from_utf8_lossy(&output.stderr)
1338        );
1339    }
1340
1341    /// A superproject with its Git directory in `shared`
1342    /// (`git init --separate-git-dir`) and a submodule at `vendor/lib`.
1343    /// Returns the submodule root and the Git directory of the superproject.
1344    #[cfg(unix)]
1345    fn submodule_with_separate_superproject_git_dir(
1346        dir: &Path,
1347        shared: &Path,
1348    ) -> (std::path::PathBuf, std::path::PathBuf) {
1349        let lib = dir.join("lib");
1350        std::fs::create_dir_all(&lib).unwrap();
1351        git(&lib, &["init", "-q"]);
1352        std::fs::write(lib.join("index.ts"), "export const a = 1;\n").unwrap();
1353        git(&lib, &["add", "."]);
1354        git(&lib, &["commit", "-q", "-m", "lib"]);
1355        let superproject = dir.join("super");
1356        let git_dir = shared.join("super.git");
1357        std::fs::create_dir_all(&superproject).unwrap();
1358        git(
1359            &superproject,
1360            &[
1361                "init",
1362                "-q",
1363                "--separate-git-dir",
1364                git_dir.to_str().unwrap(),
1365            ],
1366        );
1367        git(
1368            &superproject,
1369            &[
1370                "submodule",
1371                "add",
1372                "-q",
1373                lib.to_str().unwrap(),
1374                "vendor/lib",
1375            ],
1376        );
1377        (superproject.join("vendor/lib"), git_dir)
1378    }
1379
1380    /// The analysis root is a submodule, and the superproject keeps its Git
1381    /// directory in a shared directory. A link in the shared directory into
1382    /// the hooks of the superproject is refused.
1383    #[cfg(unix)]
1384    #[test]
1385    fn an_outside_link_into_the_git_dir_of_the_superproject_is_refused() {
1386        let dir = tempfile::tempdir().expect("temp dir");
1387        let shared = dir.path().join("shared");
1388        std::fs::create_dir_all(&shared).unwrap();
1389        let (root, git_dir) = submodule_with_separate_superproject_git_dir(dir.path(), &shared);
1390        let hook = git_dir.join("hooks/pre-commit");
1391        std::fs::write(&hook, "keep").unwrap();
1392        let link = shared.join("r.json");
1393        std::os::unix::fs::symlink(&hook, &link).unwrap();
1394        let config_link = shared.join("c.json");
1395        std::os::unix::fs::symlink(git_dir.join("config"), &config_link).unwrap();
1396        let module_link = shared.join("m.json");
1397        std::os::unix::fs::symlink(git_dir.join("modules/vendor/lib/config"), &module_link)
1398            .unwrap();
1399        let scope =
1400            WriteScope::new(&root, &root, vec![shared.canonicalize().unwrap()]).expect("scope");
1401        assert!(scope.check("--output-file", &link, &root).is_some());
1402        assert!(scope.check("--output-file", &config_link, &root).is_some());
1403        assert!(scope.check("--output-file", &module_link, &root).is_some());
1404        assert!(create_checked(&link, &link, Some(&scope)).is_err());
1405        assert_eq!(std::fs::read_to_string(&hook).unwrap(), "keep");
1406    }
1407
1408    /// In a submodule, a link to an ordinary file of the submodule and a
1409    /// plain path in the shared directory stay allowed.
1410    #[cfg(unix)]
1411    #[test]
1412    fn a_link_inside_a_submodule_is_allowed() {
1413        let dir = tempfile::tempdir().expect("temp dir");
1414        let shared = dir.path().join("shared");
1415        std::fs::create_dir_all(&shared).unwrap();
1416        let (root, _) = submodule_with_separate_superproject_git_dir(dir.path(), &shared);
1417        std::fs::create_dir_all(root.join("reports")).unwrap();
1418        std::os::unix::fs::symlink("reports", root.join("out")).unwrap();
1419        let scope =
1420            WriteScope::new(&root, &root, vec![shared.canonicalize().unwrap()]).expect("scope");
1421        assert_eq!(
1422            scope.check("--output-file", Path::new("out/r.json"), &root),
1423            None
1424        );
1425        assert!(scope.contains(&shared.join("r.json")));
1426    }
1427}