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    shared_dirs: Vec<PathBuf>,
41}
42
43impl WriteScope {
44    /// Build the scope for a project root.
45    ///
46    /// The Git work tree that contains the root counts only when `cwd` is
47    /// inside it too. That is the monorepo case the allowance exists for. It
48    /// keeps a Git repository at `$HOME` (a dotfiles setup) from allowing
49    /// every home path to a run started outside that tree.
50    ///
51    /// # Errors
52    ///
53    /// Returns a message when the root cannot be resolved, so a caller fails
54    /// closed.
55    pub fn new(root: &Path, cwd: &Path, shared_dirs: Vec<PathBuf>) -> Result<Self, String> {
56        let root = root.canonicalize().map_err(|err| {
57            format!(
58                "the project root {} cannot be resolved ({err})",
59                root.display()
60            )
61        })?;
62        let cwd = cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf());
63        let work_tree = root
64            .ancestors()
65            .find(|dir| dir.join(".git").exists())
66            .filter(|tree| cwd.starts_with(tree))
67            .map(Path::to_path_buf);
68        Ok(Self {
69            root,
70            work_tree,
71            shared_dirs,
72        })
73    }
74
75    /// Whether a resolved path lies inside one of the allowed directories, or
76    /// is an existing character device or named pipe.
77    #[must_use]
78    pub fn contains(&self, path: &Path) -> bool {
79        is_stream_target(path)
80            || path.starts_with(&self.root)
81            || self
82                .work_tree
83                .as_deref()
84                .is_some_and(|tree| path.starts_with(tree))
85            || self.shared_dirs.iter().any(|dir| path.starts_with(dir))
86    }
87
88    /// Return an error message when `path`, relative to `cwd`, resolves
89    /// outside the allowed directories. `flag` names the option that asked
90    /// for the write.
91    #[must_use]
92    pub fn check(&self, flag: &str, path: &Path, cwd: &Path) -> Option<String> {
93        if is_null_device(path) {
94            return None;
95        }
96        let resolved = resolve(&cwd.join(path));
97        if self.contains(&resolved) {
98            return None;
99        }
100        Some(format!(
101            "{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).",
102            path.display(),
103            resolved.display(),
104            self.root.display(),
105            self.work_tree
106                .as_deref()
107                .filter(|tree| *tree != self.root)
108                .map(|tree| format!(" or its Git work tree {}", tree.display()))
109                .unwrap_or_default(),
110        ))
111    }
112}
113
114/// The environment variables that name a shared directory a run may write
115/// into: the GitHub Actions workspace and temp directory, and the GitLab
116/// project directory.
117const SHARED_DIR_VARIABLES: [&str; 3] = ["GITHUB_WORKSPACE", "CI_PROJECT_DIR", "RUNNER_TEMP"];
118
119/// The shared directories a run may write into: each directory in
120/// `GITHUB_WORKSPACE`, `CI_PROJECT_DIR` and `RUNNER_TEMP` that is set and not
121/// empty, and the system temp directories (see [`system_temp_dirs`]). The CI
122/// workspace keeps a job working that checks the repository out into a
123/// subdirectory and writes its report beside it. A directory that does not
124/// exist is skipped, because it cannot be resolved.
125#[must_use]
126pub fn shared_dirs() -> Vec<PathBuf> {
127    shared_dirs_for(std::env::temp_dir())
128}
129
130fn shared_dirs_for(temp_dir: PathBuf) -> Vec<PathBuf> {
131    SHARED_DIR_VARIABLES
132        .iter()
133        .filter_map(std::env::var_os)
134        .filter(|value| !value.is_empty())
135        .map(PathBuf::from)
136        .chain(temp_dirs_with(temp_dir))
137        .filter_map(|dir| dir.canonicalize().ok())
138        .collect()
139}
140
141/// The system temp directory on Unix. It is listed on its own because macOS
142/// sets `TMPDIR` to a per-user folder, so `std::env::temp_dir()` is not
143/// `/tmp` there.
144const UNIX_SYSTEM_TEMP_DIR: &str = "/tmp";
145
146/// The system temp directories: `std::env::temp_dir()`, and on Unix also
147/// `/tmp`. The paths are not resolved. `/var/tmp` is not in the list: Linux
148/// keeps it across reboots, and people keep long-lived clones there.
149#[must_use]
150pub fn system_temp_dirs() -> Vec<PathBuf> {
151    temp_dirs_with(std::env::temp_dir())
152}
153
154fn temp_dirs_with(temp_dir: PathBuf) -> Vec<PathBuf> {
155    let mut dirs = vec![temp_dir];
156    if cfg!(unix) {
157        dirs.push(PathBuf::from(UNIX_SYSTEM_TEMP_DIR));
158    }
159    dirs
160}
161
162/// Whether `path` is an existing character device or named pipe. A write to
163/// one cannot create or replace a file, so it needs no confinement.
164#[cfg(unix)]
165fn is_stream_target(path: &Path) -> bool {
166    use std::os::unix::fs::FileTypeExt;
167    std::fs::metadata(path).is_ok_and(|meta| {
168        let file_type = meta.file_type();
169        file_type.is_char_device() || file_type.is_fifo()
170    })
171}
172
173#[cfg(not(unix))]
174const fn is_stream_target(_path: &Path) -> bool {
175    false
176}
177
178/// The device path of the Windows null device.
179#[cfg(windows)]
180const WINDOWS_NULL_DEVICE: &str = r"\\.\NUL";
181
182/// Whether `path`, as the command line gave it, names the null device on
183/// this platform. Only Windows has a device name that the path check must
184/// know: the resolved path of `NUL` is a normal path in the working
185/// directory, where the device name no longer applies.
186fn is_null_device(path: &Path) -> bool {
187    cfg!(windows) && names_windows_null_device(path)
188}
189
190/// Whether `path` names the Windows null device: `NUL` alone, in any case,
191/// with an optional colon, or the device path `\\.\NUL`.
192///
193/// A name with an extension (`NUL.txt`) and `NUL` inside a directory are not
194/// included. Windows versions do not agree on them, so they stay normal
195/// paths and get the normal check.
196fn names_windows_null_device(path: &Path) -> bool {
197    let Some(text) = path.to_str() else {
198        return false;
199    };
200    let name = text
201        .strip_prefix(r"\\.\")
202        .or_else(|| text.strip_prefix("//./"))
203        .unwrap_or_else(|| text.strip_suffix(':').unwrap_or(text));
204    name.eq_ignore_ascii_case("NUL")
205}
206
207/// What kind of file a write targets. The kind selects the scope that the
208/// write is checked against.
209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub enum WriteTarget {
211    /// A path from the command line, or a default destination in the root.
212    Path,
213    /// The config file that fallow discovered and read for the project. The
214    /// Git work tree of the root counts for it wherever the run starts.
215    DiscoveredConfig,
216}
217
218/// The scopes recorded for this process.
219#[derive(Debug)]
220struct Confinement {
221    cwd: PathBuf,
222    paths: WriteScope,
223    config: WriteScope,
224}
225
226static CONFINEMENT: OnceLock<Confinement> = OnceLock::new();
227
228/// Record the scopes that later writes are checked against. The first call
229/// wins. Without a call, writes are not confined, but they still do not
230/// follow a symlink at the final component that appears after the path was
231/// resolved.
232pub fn confine(cwd: PathBuf, paths: WriteScope, config: WriteScope) {
233    let _ = CONFINEMENT.set(Confinement { cwd, paths, config });
234}
235
236/// Why a confined write did not happen.
237#[derive(Debug)]
238pub enum WriteFailure {
239    /// A missing parent directory could not be created.
240    Directory(io::Error),
241    /// The file could not be created or written, or the path resolved
242    /// outside the recorded scope, or a path component changed after the
243    /// check.
244    File(io::Error),
245}
246
247impl WriteFailure {
248    /// Whether the failure happened while the parent directories were
249    /// created, so nothing was written.
250    #[must_use]
251    pub const fn is_directory(&self) -> bool {
252        matches!(self, Self::Directory(_))
253    }
254}
255
256impl std::fmt::Display for WriteFailure {
257    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
258        match self {
259            Self::Directory(error) | Self::File(error) => error.fmt(f),
260        }
261    }
262}
263
264impl std::error::Error for WriteFailure {}
265
266impl From<WriteFailure> for io::Error {
267    fn from(failure: WriteFailure) -> Self {
268        match failure {
269            WriteFailure::Directory(error) | WriteFailure::File(error) => error,
270        }
271    }
272}
273
274/// Create or truncate `path` for writing, after the checks this module
275/// describes. Missing parent directories are created.
276///
277/// # Errors
278///
279/// Returns [`WriteFailure::Directory`] when a parent directory cannot be
280/// created. Returns [`WriteFailure::File`] with `PermissionDenied` when the
281/// path resolves outside the recorded scope, or when a path component changed
282/// while the parent directories were created, and with the error of the open
283/// call when the final component became a symlink after the path was resolved
284/// (Unix) or the file cannot be created.
285pub fn create_file(path: &Path, target: WriteTarget) -> Result<File, WriteFailure> {
286    let confinement = CONFINEMENT.get();
287    let absolute = match confinement {
288        Some(confinement) => confinement.cwd.join(path),
289        None => std::env::current_dir().map_or_else(|_| path.to_path_buf(), |cwd| cwd.join(path)),
290    };
291    let scope = confinement.map(|confinement| match target {
292        WriteTarget::Path => &confinement.paths,
293        WriteTarget::DiscoveredConfig => &confinement.config,
294    });
295    create_checked(path, &absolute, scope)
296}
297
298/// Write `contents` to `path` through [`create_file`].
299///
300/// # Errors
301///
302/// Returns the errors of [`create_file`], and a write or flush error as
303/// [`WriteFailure::File`].
304pub fn write_file(path: &Path, contents: &[u8], target: WriteTarget) -> Result<(), WriteFailure> {
305    let mut file = create_file(path, target)?;
306    file.write_all(contents).map_err(WriteFailure::File)?;
307    file.flush().map_err(WriteFailure::File)
308}
309
310fn create_checked(
311    requested: &Path,
312    absolute: &Path,
313    scope: Option<&WriteScope>,
314) -> Result<File, WriteFailure> {
315    if is_null_device(requested) {
316        return open_null_device().map_err(WriteFailure::File);
317    }
318    let resolved = resolve(absolute);
319    if is_stream_target(&resolved) {
320        return open_stream(&resolved).map_err(WriteFailure::File);
321    }
322    if scope.is_some_and(|scope| !scope.contains(&resolved)) {
323        return Err(WriteFailure::File(io::Error::new(
324            io::ErrorKind::PermissionDenied,
325            format!(
326                "{} resolves to {}, which is outside the directories this run may write to",
327                requested.display(),
328                resolved.display()
329            ),
330        )));
331    }
332    if let Some(parent) = resolved.parent()
333        && !parent.as_os_str().is_empty()
334    {
335        std::fs::create_dir_all(parent).map_err(WriteFailure::Directory)?;
336        // A missing component can become a symlink between the resolve and
337        // the create. The parent must still resolve to the same directory.
338        let real_parent = parent.canonicalize().map_err(WriteFailure::File)?;
339        if real_parent != parent {
340            return Err(WriteFailure::File(io::Error::new(
341                io::ErrorKind::PermissionDenied,
342                format!(
343                    "{} changed while fallow prepared the write, so fallow did not write it",
344                    requested.display()
345                ),
346            )));
347        }
348    }
349    open_no_follow(&resolved).map_err(WriteFailure::File)
350}
351
352/// Open an existing character device or named pipe for writing. It is not
353/// created and not truncated. On Unix the open does not follow a symlink at
354/// the final component, and the opened handle must still be a character
355/// device or named pipe, so a path swapped after the check is refused.
356fn open_stream(path: &Path) -> io::Result<File> {
357    let mut options = std::fs::OpenOptions::new();
358    options.write(true);
359    #[cfg(unix)]
360    {
361        use std::os::unix::fs::OpenOptionsExt;
362        options.custom_flags(libc::O_NOFOLLOW);
363    }
364    let file = options.open(path)?;
365    #[cfg(unix)]
366    ensure_stream_handle(&file, path)?;
367    Ok(file)
368}
369
370/// Open the Windows null device for writing through its device path.
371#[cfg(windows)]
372fn open_null_device() -> io::Result<File> {
373    std::fs::OpenOptions::new()
374        .write(true)
375        .open(WINDOWS_NULL_DEVICE)
376}
377
378/// Only Windows has a null device name that [`is_null_device`] accepts.
379#[cfg(not(windows))]
380fn open_null_device() -> io::Result<File> {
381    Err(io::Error::new(
382        io::ErrorKind::Unsupported,
383        "only Windows has a null device name",
384    ))
385}
386
387/// Refuse a handle that is not a character device or named pipe.
388#[cfg(unix)]
389fn ensure_stream_handle(file: &File, path: &Path) -> io::Result<()> {
390    use std::os::unix::fs::FileTypeExt;
391    let file_type = file.metadata()?.file_type();
392    if file_type.is_char_device() || file_type.is_fifo() {
393        return Ok(());
394    }
395    Err(io::Error::new(
396        io::ErrorKind::PermissionDenied,
397        format!(
398            "{} is no longer a device or a named pipe, so fallow did not write it",
399            path.display()
400        ),
401    ))
402}
403
404/// Open `path` for writing without following a symlink at the final
405/// component. On Unix the open call refuses the link itself. Elsewhere the
406/// final component is checked right before the open.
407fn open_no_follow(path: &Path) -> io::Result<File> {
408    let mut options = std::fs::OpenOptions::new();
409    options.write(true).create(true).truncate(true);
410    #[cfg(unix)]
411    {
412        use std::os::unix::fs::OpenOptionsExt;
413        options.custom_flags(libc::O_NOFOLLOW);
414    }
415    // This check and the open are two steps, so a link that appears between
416    // them is still followed. Only the Unix open closes that window.
417    #[cfg(not(unix))]
418    if path
419        .symlink_metadata()
420        .is_ok_and(|meta| meta.file_type().is_symlink())
421    {
422        return Err(io::Error::new(
423            io::ErrorKind::PermissionDenied,
424            format!(
425                "{} became a symlink after fallow checked it, so fallow did not write it",
426                path.display()
427            ),
428        ));
429    }
430    options.open(path)
431}
432
433/// How many dangling symlinks [`resolve`] follows before it gives up.
434const MAX_LINK_HOPS: usize = 40;
435
436/// Resolve `path` the way a write would reach it: symlinks and `..` in the
437/// part that exists are resolved by the file system, and the rest, which a
438/// write would create, is normalised lexically. A dangling symlink is followed
439/// to its target, because a write through it lands there.
440#[must_use]
441pub fn resolve(path: &Path) -> PathBuf {
442    resolve_with_hops(path, 0)
443}
444
445fn resolve_with_hops(path: &Path, hops: usize) -> PathBuf {
446    let mut existing = path;
447    let mut missing = Vec::new();
448    loop {
449        if let Ok(real) = existing.canonicalize() {
450            return append_missing(real, &missing);
451        }
452        if hops < MAX_LINK_HOPS
453            && let Ok(target) = std::fs::read_link(existing)
454        {
455            let base = existing.parent().unwrap_or_else(|| Path::new(""));
456            let followed = resolve_with_hops(&base.join(target), hops + 1);
457            return append_missing(followed, &missing);
458        }
459        let (Some(parent), Some(last)) = (existing.parent(), existing.components().next_back())
460        else {
461            return append_missing(PathBuf::new(), &missing);
462        };
463        missing.push(last);
464        existing = parent;
465    }
466}
467
468/// Append the components that do not exist yet, innermost last.
469fn append_missing(mut resolved: PathBuf, missing: &[Component<'_>]) -> PathBuf {
470    for component in missing.iter().rev() {
471        match component {
472            Component::ParentDir => {
473                resolved.pop();
474            }
475            Component::CurDir => {}
476            other => resolved.push(other.as_os_str()),
477        }
478    }
479    resolved
480}
481
482#[cfg(test)]
483mod tests {
484    use std::path::Path;
485
486    use super::{WriteScope, create_checked, names_windows_null_device, resolve};
487
488    /// macOS sets `TMPDIR` to a per-user folder, but a user who passes
489    /// `/tmp/x.json` means the system temp directory. Each Unix allows it,
490    /// whatever `TMPDIR` names.
491    #[cfg(unix)]
492    #[test]
493    fn scope_accepts_the_unix_system_temp_dir_when_tmpdir_names_another_folder() {
494        use super::shared_dirs_for;
495
496        let project = tempfile::tempdir().expect("project dir");
497        let other_temp = tempfile::tempdir().expect("temp dir");
498        let scope = WriteScope::new(
499            project.path(),
500            project.path(),
501            shared_dirs_for(other_temp.path().to_path_buf()),
502        )
503        .expect("scope");
504        assert_eq!(
505            scope.check("--save-baseline", Path::new("/tmp/x.json"), project.path()),
506            None
507        );
508    }
509
510    /// The Windows null device is named by `NUL` alone, in any case, with an
511    /// optional colon, or by its device path. A file name that only starts
512    /// with `NUL`, or `NUL` in a directory, is a normal file name.
513    #[test]
514    fn the_windows_null_device_is_named_by_nul_alone() {
515        for name in [
516            "NUL", "nul", "Nul", "NUL:", r"\\.\NUL", r"\\.\nul", "//./NUL",
517        ] {
518            assert!(names_windows_null_device(Path::new(name)), "{name}");
519        }
520        for name in [
521            "NUL.txt",
522            "nul.sarif",
523            "null",
524            "NULL",
525            "report",
526            r"dir\NUL",
527            "dir/nul",
528            r".\NUL",
529            r"C:\NUL",
530            "",
531        ] {
532            assert!(!names_windows_null_device(Path::new(name)), "{name}");
533        }
534    }
535
536    #[test]
537    fn resolve_normalises_the_missing_part() {
538        let dir = tempfile::tempdir().expect("temp dir");
539        let base = dir.path().canonicalize().unwrap();
540        assert_eq!(
541            resolve(&base.join("a/b/../c.json")),
542            base.join("a").join("c.json")
543        );
544        assert_eq!(
545            resolve(&base.join("a/../../x.json")),
546            base.parent().unwrap().join("x.json")
547        );
548    }
549
550    #[cfg(unix)]
551    #[test]
552    fn a_dangling_link_resolves_to_its_target() {
553        let dir = tempfile::tempdir().expect("temp dir");
554        let base = dir.path().canonicalize().unwrap();
555        let root = base.join("project");
556        std::fs::create_dir_all(&root).unwrap();
557        std::os::unix::fs::symlink(base.join("elsewhere.json"), root.join("b.json")).unwrap();
558        assert_eq!(resolve(&root.join("b.json")), base.join("elsewhere.json"));
559    }
560
561    #[test]
562    fn scope_accepts_a_temp_dir_through_a_symlinked_spelling() {
563        let dir = tempfile::tempdir().expect("temp dir");
564        let root = dir.path().join("project");
565        let temp = dir.path().join("temp");
566        std::fs::create_dir_all(&root).unwrap();
567        std::fs::create_dir_all(&temp).unwrap();
568        let scope =
569            WriteScope::new(&root, &root, vec![temp.canonicalize().unwrap()]).expect("scope");
570        // `dir.path()` is not canonical on macOS (`/var` links to
571        // `/private/var`), so this also checks that both sides are resolved.
572        assert!(
573            scope
574                .check("--save-baseline", &temp.join("b.json"), &root)
575                .is_none()
576        );
577        assert!(
578            scope
579                .check("--save-baseline", &dir.path().join("b.json"), &root)
580                .is_some()
581        );
582    }
583
584    #[test]
585    fn a_root_that_cannot_be_resolved_fails_closed() {
586        let dir = tempfile::tempdir().expect("temp dir");
587        let missing = dir.path().join("missing");
588        assert!(WriteScope::new(&missing, dir.path(), Vec::new()).is_err());
589    }
590
591    #[test]
592    fn the_work_tree_needs_the_working_directory_inside_it() {
593        let dir = tempfile::tempdir().expect("temp dir");
594        let home = dir.path().join("home");
595        let root = home.join("project");
596        let elsewhere = dir.path().join("elsewhere");
597        std::fs::create_dir_all(&root).unwrap();
598        std::fs::create_dir_all(&elsewhere).unwrap();
599        std::fs::create_dir_all(home.join(".git")).unwrap();
600        let target = home.join(".config").join("x.json");
601        let from_outside = WriteScope::new(&root, &elsewhere, Vec::new()).expect("scope");
602        assert!(
603            from_outside
604                .check("--save-baseline", &target, &elsewhere)
605                .is_some()
606        );
607        let from_inside = WriteScope::new(&root, &home, Vec::new()).expect("scope");
608        assert!(
609            from_inside
610                .check("--save-baseline", &target, &home)
611                .is_none()
612        );
613    }
614
615    #[test]
616    fn scope_accepts_the_root_and_rejects_a_sibling() {
617        let dir = tempfile::tempdir().expect("temp dir");
618        let root = dir.path().join("project");
619        std::fs::create_dir_all(&root).unwrap();
620        let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
621        assert!(
622            scope
623                .check("--save-baseline", "nested/b.json".as_ref(), &root)
624                .is_none()
625        );
626        let message = scope
627            .check("--save-baseline", "../b.json".as_ref(), &root)
628            .expect("outside");
629        assert!(message.contains("outside the project root"), "{message}");
630    }
631
632    #[test]
633    fn scope_accepts_the_git_work_tree_of_the_root() {
634        let dir = tempfile::tempdir().expect("temp dir");
635        let repo = dir.path().join("repo");
636        let root = repo.join("packages/app");
637        std::fs::create_dir_all(&root).unwrap();
638        std::fs::create_dir_all(repo.join(".git")).unwrap();
639        let scope = WriteScope::new(&root, &repo, Vec::new()).expect("scope");
640        assert!(
641            scope
642                .check("--save-baseline", "baselines/b.json".as_ref(), &repo)
643                .is_none()
644        );
645        let message = scope
646            .check("--save-baseline", "../b.json".as_ref(), &repo)
647            .expect("outside");
648        assert!(message.contains("Git work tree"), "{message}");
649    }
650
651    #[test]
652    fn a_checked_write_lands_inside_the_scope() {
653        let dir = tempfile::tempdir().expect("temp dir");
654        let root = dir.path().join("project");
655        std::fs::create_dir_all(&root).unwrap();
656        let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
657        let target = root.join("out/nested/report.json");
658        assert!(scope.check("--output-file", &target, &root).is_none());
659        let file = create_checked(&target, &target, Some(&scope)).expect("write inside");
660        drop(file);
661        assert!(target.is_file());
662    }
663
664    /// A character device is allowed and written through.
665    #[cfg(unix)]
666    #[test]
667    fn a_character_device_is_allowed_outside_the_scope() {
668        let dir = tempfile::tempdir().expect("temp dir");
669        let root = dir.path().join("project");
670        std::fs::create_dir_all(&root).unwrap();
671        let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
672        let null = std::path::Path::new("/dev/null");
673        assert!(scope.check("--output-file", null, &root).is_none());
674        let file = create_checked(null, null, Some(&scope)).expect("write to /dev/null");
675        drop(file);
676    }
677
678    /// A named pipe outside the scope is allowed, and the write reaches the
679    /// reader.
680    #[cfg(unix)]
681    #[test]
682    fn a_named_pipe_is_allowed_outside_the_scope() {
683        use std::io::Write as _;
684        let dir = tempfile::tempdir().expect("temp dir");
685        let root = dir.path().join("project");
686        std::fs::create_dir_all(&root).unwrap();
687        let fifo = dir.path().join("report.fifo");
688        let made = std::process::Command::new("mkfifo")
689            .arg(&fifo)
690            .status()
691            .expect("run mkfifo");
692        assert!(made.success());
693        let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
694        assert!(scope.check("--sarif-file", &fifo, &root).is_none());
695        let reader_path = fifo.clone();
696        let reader = std::thread::spawn(move || std::fs::read_to_string(reader_path));
697        let mut file = create_checked(&fifo, &fifo, Some(&scope)).expect("write to fifo");
698        file.write_all(b"sarif").unwrap();
699        drop(file);
700        assert_eq!(reader.join().unwrap().unwrap(), "sarif");
701    }
702
703    /// A stream target is refused when the path is a symlink at the open, or
704    /// when the opened handle is a regular file.
705    #[cfg(unix)]
706    #[test]
707    fn a_stream_target_swapped_after_the_check_is_refused() {
708        use super::{ensure_stream_handle, open_stream};
709        let dir = tempfile::tempdir().expect("temp dir");
710        let link = dir.path().join("null-link");
711        std::os::unix::fs::symlink("/dev/null", &link).unwrap();
712        assert!(open_stream(&link).is_err(), "a symlink is not followed");
713
714        let regular = dir.path().join("regular.json");
715        std::fs::write(&regular, "keep").unwrap();
716        assert!(open_stream(&regular).is_err(), "a regular file is refused");
717        let handle = std::fs::File::open(&regular).unwrap();
718        assert!(ensure_stream_handle(&handle, &regular).is_err());
719        assert_eq!(std::fs::read_to_string(&regular).unwrap(), "keep");
720
721        let null = std::fs::File::open("/dev/null").unwrap();
722        assert!(ensure_stream_handle(&null, std::path::Path::new("/dev/null")).is_ok());
723    }
724
725    /// A directory that passed the check and then became a symlink to a
726    /// place outside the project does not carry the write out.
727    #[cfg(unix)]
728    #[test]
729    fn a_directory_swapped_for_a_symlink_after_the_check_is_refused() {
730        let dir = tempfile::tempdir().expect("temp dir");
731        let root = dir.path().join("project");
732        let elsewhere = dir.path().join("elsewhere");
733        std::fs::create_dir_all(root.join("out")).unwrap();
734        std::fs::create_dir_all(&elsewhere).unwrap();
735        let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
736        let target = root.join("out/report.json");
737        assert!(scope.check("--output-file", &target, &root).is_none());
738
739        std::fs::remove_dir(root.join("out")).unwrap();
740        std::os::unix::fs::symlink(&elsewhere, root.join("out")).unwrap();
741
742        let error = std::io::Error::from(
743            create_checked(&target, &target, Some(&scope)).expect_err("refused"),
744        );
745        assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
746        assert!(!elsewhere.join("report.json").exists());
747    }
748
749    /// A final component that became a symlink after the check is refused,
750    /// also when the link points outside the project.
751    #[cfg(unix)]
752    #[test]
753    fn a_file_swapped_for_a_symlink_after_the_check_is_refused() {
754        let dir = tempfile::tempdir().expect("temp dir");
755        let root = dir.path().join("project");
756        std::fs::create_dir_all(&root).unwrap();
757        let outside = dir.path().join("outside.json");
758        let scope = WriteScope::new(&root, &root, Vec::new()).expect("scope");
759        let target = root.join("report.json");
760        assert!(scope.check("--output-file", &target, &root).is_none());
761
762        std::os::unix::fs::symlink(&outside, &target).unwrap();
763
764        assert!(create_checked(&target, &target, Some(&scope)).is_err());
765        assert!(!outside.exists());
766    }
767
768    /// The open itself refuses a symlink at the final component, which covers
769    /// a link that appears after the path was resolved.
770    #[cfg(unix)]
771    #[test]
772    fn the_open_does_not_follow_a_final_symlink() {
773        let dir = tempfile::tempdir().expect("temp dir");
774        let real = dir.path().join("real.json");
775        std::fs::write(&real, "keep").unwrap();
776        let link = dir.path().join("link.json");
777        std::os::unix::fs::symlink(&real, &link).unwrap();
778
779        assert!(super::open_no_follow(&link).is_err());
780        assert_eq!(std::fs::read_to_string(&real).unwrap(), "keep");
781    }
782}