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