Skip to main content

fallow_types/
read_guard.rs

1//! Bounded reads of project files.
2//!
3//! fallow reads project files such as a config file, a `tsconfig.json` or a
4//! `CODEOWNERS` file in full. The helpers here read such a file only when it
5//! resolves inside the project root, is a regular file, and fits a size
6//! limit. A link that resolves inside the root stays allowed. A device or a
7//! very large file is refused before the read, so the read cannot block or
8//! fill memory.
9//!
10//! Each check fails closed: when the helper cannot decide, it refuses.
11
12use std::fmt;
13use std::io::Read;
14use std::path::{Path, PathBuf};
15
16use crate::link_walk::{Stop, resolve_below};
17
18/// The default size limit for a project file that fallow reads in full.
19///
20/// Config files, `tsconfig.json` files, rule packs and `CODEOWNERS` files of
21/// large monorepos stay well below 1 MiB. 16 MiB leaves room for configs
22/// that tools write, and still stops a read of a device or a multi-gigabyte
23/// file.
24pub const DEFAULT_MAX_READ_BYTES: u64 = 16 * 1024 * 1024;
25
26/// The reason that a bounded read refused a file.
27///
28/// The `Display` text names the path and the reason. It never contains
29/// content of the file.
30#[derive(Debug)]
31pub enum ReadRefusal {
32    /// The path, after symlinks are resolved, is outside the root.
33    OutsideRoot {
34        /// The path as the caller gave it.
35        path: PathBuf,
36        /// The root that the path must stay in.
37        root: PathBuf,
38    },
39    /// The path is not a regular file, for example a directory or a device.
40    NotRegularFile {
41        /// The path as the caller gave it.
42        path: PathBuf,
43    },
44    /// The file is larger than the limit.
45    TooLarge {
46        /// The path as the caller gave it.
47        path: PathBuf,
48        /// The limit in bytes.
49        max_bytes: u64,
50    },
51    /// The path or the root does not resolve, or the read failed.
52    Io {
53        /// The path as the caller gave it.
54        path: PathBuf,
55        /// The error of the file system call.
56        source: std::io::Error,
57    },
58}
59
60impl ReadRefusal {
61    /// The path as the caller gave it.
62    #[must_use]
63    pub fn path(&self) -> &Path {
64        match self {
65            Self::OutsideRoot { path, .. }
66            | Self::NotRegularFile { path }
67            | Self::TooLarge { path, .. }
68            | Self::Io { path, .. } => path,
69        }
70    }
71
72    /// True when the file does not exist. A link on the path that does not
73    /// resolve gives [`ReadRefusal::OutsideRoot`], not this state, so a
74    /// dangling link and a link to a file outside the root look the same.
75    #[must_use]
76    pub fn is_not_found(&self) -> bool {
77        matches!(self, Self::Io { source, .. } if source.kind() == std::io::ErrorKind::NotFound)
78    }
79}
80
81impl fmt::Display for ReadRefusal {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        match self {
84            Self::OutsideRoot { path, root } => write!(
85                f,
86                "refusing to read {}: it resolves to a location outside {}",
87                path.display(),
88                root.display()
89            ),
90            Self::NotRegularFile { path } => write!(
91                f,
92                "refusing to read {}: it is not a regular file",
93                path.display()
94            ),
95            Self::TooLarge { path, max_bytes } => write!(
96                f,
97                "refusing to read {}: it is larger than {max_bytes} bytes",
98                path.display()
99            ),
100            Self::Io { path, source } => {
101                write!(f, "cannot read {}: {source}", path.display())
102            }
103        }
104    }
105}
106
107impl std::error::Error for ReadRefusal {
108    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
109        match self {
110            Self::Io { source, .. } => Some(source),
111            _ => None,
112        }
113    }
114}
115
116/// True when `path`, after symlinks are resolved, is `root` or a path below
117/// the resolved `root`. A relative `path` is taken relative to `root`.
118///
119/// Each component and each symlink target resolves in turn, and a step that
120/// leaves the root gives `false`, also when a later `..` would come back. So
121/// the answer depends only on entries inside the root.
122///
123/// Returns `false` when `root` or `path` does not resolve, for example a
124/// missing file, a dangling link or a path that is too long.
125#[must_use]
126pub fn is_inside_root(root: &Path, path: &Path) -> bool {
127    let Ok(canonical_root) = canonicalize(root) else {
128        return false;
129    };
130    resolve_below(root, &canonical_root, path).is_ok()
131}
132
133/// Read `path` in full when it resolves inside `root`, is a regular file and
134/// has at most `max_bytes` bytes. A relative `path` is taken relative to
135/// `root`. Use [`DEFAULT_MAX_READ_BYTES`] when no other limit applies.
136///
137/// # Errors
138///
139/// Returns a [`ReadRefusal`] when a check fails or the read fails.
140pub fn read_bytes_inside(root: &Path, path: &Path, max_bytes: u64) -> Result<Vec<u8>, ReadRefusal> {
141    let canonical_root = canonicalize(root).map_err(|source| ReadRefusal::Io {
142        path: path.to_path_buf(),
143        source,
144    })?;
145    read_bytes_in(root, &canonical_root, path, max_bytes, |dir| {
146        canonicalize(dir).ok()
147    })
148}
149
150/// A root for many bounded reads, such as the probes of many candidate
151/// files. The root resolves once, and each directory that holds a missing
152/// candidate resolves once. So a missing candidate costs one `lstat` call.
153/// A read gives the same result as [`read_bytes_inside`] with the same root.
154///
155/// A file system change after a directory resolves is not seen, so keep a
156/// `ReadRoot` for one scan only.
157#[derive(Debug)]
158pub struct ReadRoot {
159    root: PathBuf,
160    canonical: Result<PathBuf, std::io::ErrorKind>,
161    dirs: std::cell::RefCell<rustc_hash::FxHashMap<PathBuf, Option<PathBuf>>>,
162}
163
164impl ReadRoot {
165    /// A read root for `root`.
166    #[must_use]
167    pub fn new(root: &Path) -> Self {
168        Self {
169            root: root.to_path_buf(),
170            canonical: canonicalize(root).map_err(|error| error.kind()),
171            dirs: std::cell::RefCell::default(),
172        }
173    }
174
175    /// [`read_bytes_inside`] with this root.
176    ///
177    /// # Errors
178    ///
179    /// Returns a [`ReadRefusal`] when a check fails or the read fails.
180    pub fn read_bytes(&self, path: &Path, max_bytes: u64) -> Result<Vec<u8>, ReadRefusal> {
181        let canonical_root = self.canonical.as_ref().map_err(|kind| ReadRefusal::Io {
182            path: path.to_path_buf(),
183            source: std::io::Error::from(*kind),
184        })?;
185        read_bytes_in(&self.root, canonical_root, path, max_bytes, |dir| {
186            self.dirs
187                .borrow_mut()
188                .entry(dir.to_path_buf())
189                .or_insert_with(|| canonicalize(dir).ok())
190                .clone()
191        })
192    }
193
194    /// [`read_to_string_inside`] with this root.
195    ///
196    /// # Errors
197    ///
198    /// Returns a [`ReadRefusal`] when a check fails, the read fails, or the
199    /// content is not valid UTF-8.
200    pub fn read_to_string(&self, path: &Path, max_bytes: u64) -> Result<String, ReadRefusal> {
201        let bytes = self.read_bytes(path, max_bytes)?;
202        into_string(path, bytes)
203    }
204
205    /// [`is_inside_root`] with this root.
206    #[must_use]
207    pub fn is_inside(&self, path: &Path) -> bool {
208        let Ok(canonical_root) = &self.canonical else {
209            return false;
210        };
211        let joined = self.root.join(path);
212        // A path with no entry does not resolve, so one `lstat` call answers.
213        if joined
214            .symlink_metadata()
215            .is_err_and(|error| error.kind() == std::io::ErrorKind::NotFound)
216        {
217            return false;
218        }
219        resolve_below(&self.root, canonical_root, path).is_ok()
220    }
221}
222
223/// The checks and the read of [`read_bytes_inside`] for the resolved root
224/// `canonical_root`. `resolve_dir` resolves the directory that holds a
225/// missing entry.
226fn read_bytes_in(
227    root: &Path,
228    canonical_root: &Path,
229    path: &Path,
230    max_bytes: u64,
231    resolve_dir: impl FnOnce(&Path) -> Option<PathBuf>,
232) -> Result<Vec<u8>, ReadRefusal> {
233    let joined = root.join(path);
234    let io = |source: std::io::Error| ReadRefusal::Io {
235        path: path.to_path_buf(),
236        source,
237    };
238    let outside = || ReadRefusal::OutsideRoot {
239        path: path.to_path_buf(),
240        root: root.to_path_buf(),
241    };
242    if let Some(source) = missing_inside(root, canonical_root, &joined, resolve_dir) {
243        return Err(io(source));
244    }
245    let resolved = match resolve_below(root, canonical_root, path) {
246        Ok(resolved) => resolved,
247        Err(Stop::Outside | Stop::Missing { in_link: true }) => return Err(outside()),
248        Err(Stop::Missing { in_link: false }) => {
249            return Err(io(std::io::ErrorKind::NotFound.into()));
250        }
251        Err(Stop::Unreadable(source)) => return Err(io(source)),
252    };
253    read_resolved(path, &resolved, max_bytes)
254}
255
256/// The `NotFound` error of `joined` when no entry, not even a link, has that
257/// name and the nearest existing directory above it resolves inside
258/// `canonical_root`. No link exists below a missing entry, so the full walk
259/// of [`resolve_below`] cannot find a link out of the root. The walk up
260/// costs one `lstat` call for each missing directory. `None` sends the path
261/// to the full walk: an entry that exists, a dangling link, a `..`
262/// component, a directory that does not resolve, or a directory outside the
263/// root.
264fn missing_inside(
265    root: &Path,
266    canonical_root: &Path,
267    joined: &Path,
268    resolve_dir: impl FnOnce(&Path) -> Option<PathBuf>,
269) -> Option<std::io::Error> {
270    use std::path::Component;
271    let error = joined.symlink_metadata().err()?;
272    if error.kind() != std::io::ErrorKind::NotFound {
273        return None;
274    }
275    let mut missing = joined;
276    loop {
277        if !matches!(missing.components().next_back(), Some(Component::Normal(_))) {
278            return None;
279        }
280        let dir = missing.parent()?;
281        if dir == root {
282            return Some(error);
283        }
284        match dir.symlink_metadata() {
285            Err(dir_error) if dir_error.kind() == std::io::ErrorKind::NotFound => missing = dir,
286            Err(_) => return None,
287            Ok(_) => {
288                let inside = resolve_dir(dir).is_some_and(|dir| dir.starts_with(canonical_root));
289                return inside.then_some(error);
290            }
291        }
292    }
293}
294
295/// `std::fs::canonicalize`, counted in test builds (see
296/// `canonicalize_calls`).
297fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
298    #[cfg(any(test, feature = "testing"))]
299    CANONICALIZE_CALLS.with(|calls| calls.set(calls.get() + 1));
300    std::fs::canonicalize(path)
301}
302
303#[cfg(any(test, feature = "testing"))]
304std::thread_local! {
305    static CANONICALIZE_CALLS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
306}
307
308/// The number of path resolutions that the bounded read helpers made on this
309/// thread. A test compares two counts to check the cost of a scan.
310#[cfg(any(test, feature = "testing"))]
311#[must_use]
312pub fn canonicalize_calls() -> u64 {
313    CANONICALIZE_CALLS.with(std::cell::Cell::get)
314}
315
316/// [`read_bytes_inside`] that also requires valid UTF-8.
317///
318/// # Errors
319///
320/// Returns a [`ReadRefusal`] when a check fails, the read fails, or the
321/// content is not valid UTF-8.
322pub fn read_to_string_inside(
323    root: &Path,
324    path: &Path,
325    max_bytes: u64,
326) -> Result<String, ReadRefusal> {
327    let bytes = read_bytes_inside(root, path, max_bytes)?;
328    into_string(path, bytes)
329}
330
331/// Read `path` in full when it is a regular file with at most `max_bytes`
332/// bytes, with no root check. Use this only for a path that may leave the
333/// project by design, for example an absolute `extends` value of the user.
334///
335/// # Errors
336///
337/// Returns a [`ReadRefusal`] when a check fails, the read fails, or the
338/// content is not valid UTF-8.
339pub fn read_to_string_bounded(path: &Path, max_bytes: u64) -> Result<String, ReadRefusal> {
340    let bytes = read_resolved(path, path, max_bytes)?;
341    into_string(path, bytes)
342}
343
344/// [`read_to_string_bounded`] for bytes: read `path` in full when it is a
345/// regular file with at most `max_bytes` bytes, with no root check.
346///
347/// # Errors
348///
349/// Returns a [`ReadRefusal`] when a check fails or the read fails.
350pub fn read_bytes_bounded(path: &Path, max_bytes: u64) -> Result<Vec<u8>, ReadRefusal> {
351    read_resolved(path, path, max_bytes)
352}
353
354/// Whether `path` is a regular file with at most `max_bytes` bytes, after a
355/// link resolves. A bounded read of such a file does not refuse it for its
356/// type or size.
357#[must_use]
358pub fn is_bounded_regular_file(path: &Path, max_bytes: u64) -> bool {
359    std::fs::metadata(path).is_ok_and(|meta| meta.is_file() && meta.len() <= max_bytes)
360}
361
362fn read_resolved(path: &Path, resolved: &Path, max_bytes: u64) -> Result<Vec<u8>, ReadRefusal> {
363    let io = |source: std::io::Error| ReadRefusal::Io {
364        path: path.to_path_buf(),
365        source,
366    };
367    let not_regular = || ReadRefusal::NotRegularFile {
368        path: path.to_path_buf(),
369    };
370    let too_large = || ReadRefusal::TooLarge {
371        path: path.to_path_buf(),
372        max_bytes,
373    };
374    // The check before the open skips a device or a FIFO without opening it.
375    // The path can change between that check and the open, so the opened
376    // file is checked again. The open does not wait for a FIFO writer.
377    if !std::fs::metadata(resolved).map_err(io)?.is_file() {
378        return Err(not_regular());
379    }
380    let file = open_without_blocking(resolved).map_err(io)?;
381    let meta = file.metadata().map_err(io)?;
382    if !meta.is_file() {
383        return Err(not_regular());
384    }
385    if meta.len() > max_bytes {
386        return Err(too_large());
387    }
388    let mut bytes = Vec::new();
389    // The file can grow after the metadata call, so the read stops one byte
390    // past the limit and refuses the file when it reaches that byte.
391    file.take(max_bytes.saturating_add(1))
392        .read_to_end(&mut bytes)
393        .map_err(io)?;
394    if bytes.len() as u64 > max_bytes {
395        return Err(too_large());
396    }
397    Ok(bytes)
398}
399
400/// Open `path` for reading. On Unix the open does not wait for the writer of
401/// a FIFO, so a FIFO that replaces a checked file cannot hang the read.
402fn open_without_blocking(path: &Path) -> std::io::Result<std::fs::File> {
403    let mut options = std::fs::OpenOptions::new();
404    options.read(true);
405    #[cfg(unix)]
406    {
407        use std::os::unix::fs::OpenOptionsExt;
408        options.custom_flags(rustix::fs::OFlags::NONBLOCK.bits().cast_signed());
409    }
410    options.open(path)
411}
412
413fn into_string(path: &Path, bytes: Vec<u8>) -> Result<String, ReadRefusal> {
414    String::from_utf8(bytes).map_err(|_| ReadRefusal::Io {
415        path: path.to_path_buf(),
416        source: std::io::Error::new(
417            std::io::ErrorKind::InvalidData,
418            "stream did not contain valid UTF-8",
419        ),
420    })
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426
427    /// The checked open does not wait for a FIFO writer, and the check of
428    /// the opened file refuses what is not a regular file.
429    #[test]
430    #[cfg(unix)]
431    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
432    fn the_open_does_not_wait_for_a_fifo_and_checks_the_opened_file() {
433        let dir = tempfile::tempdir().unwrap();
434        let fifo = dir.path().join("pipe.json");
435        let status = std::process::Command::new("mkfifo")
436            .arg(&fifo)
437            .status()
438            .unwrap();
439        assert!(status.success());
440        let file = open_without_blocking(&fifo).unwrap();
441        assert!(!file.metadata().unwrap().is_file());
442        assert!(matches!(
443            read_to_string_bounded(&fifo, 16),
444            Err(ReadRefusal::NotRegularFile { .. })
445        ));
446    }
447
448    #[test]
449    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
450    fn reads_a_regular_file_inside_the_root() {
451        let dir = tempfile::tempdir().unwrap();
452        std::fs::write(dir.path().join("a.json"), "{}").unwrap();
453        let text = read_to_string_inside(dir.path(), Path::new("a.json"), 16).unwrap();
454        assert_eq!(text, "{}");
455        let abs = dir.path().join("a.json");
456        assert_eq!(read_bytes_inside(dir.path(), &abs, 16).unwrap(), b"{}");
457        assert!(is_inside_root(dir.path(), &abs));
458    }
459
460    #[test]
461    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
462    fn bounded_bytes_read_takes_regular_files_within_the_limit_only() {
463        let dir = tempfile::tempdir().unwrap();
464        let file = dir.path().join("a.json");
465        std::fs::write(&file, "{}").unwrap();
466        assert_eq!(read_bytes_bounded(&file, 16).unwrap(), b"{}");
467        assert!(is_bounded_regular_file(&file, 16));
468        assert!(read_bytes_bounded(&file, 1).is_err());
469        assert!(!is_bounded_regular_file(&file, 1));
470        assert!(read_bytes_bounded(dir.path(), 16).is_err());
471        assert!(!is_bounded_regular_file(dir.path(), 16));
472    }
473
474    #[test]
475    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
476    fn refuses_a_file_over_the_limit() {
477        let dir = tempfile::tempdir().unwrap();
478        std::fs::write(dir.path().join("a.json"), "0123456789").unwrap();
479        let err = read_to_string_inside(dir.path(), Path::new("a.json"), 4).unwrap_err();
480        assert!(matches!(err, ReadRefusal::TooLarge { max_bytes: 4, .. }));
481        assert!(!err.to_string().contains("0123"));
482        let err = read_to_string_bounded(&dir.path().join("a.json"), 4).unwrap_err();
483        assert!(matches!(err, ReadRefusal::TooLarge { .. }));
484    }
485
486    #[test]
487    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
488    fn refuses_a_directory() {
489        let dir = tempfile::tempdir().unwrap();
490        std::fs::create_dir(dir.path().join("sub")).unwrap();
491        let err = read_to_string_inside(dir.path(), Path::new("sub"), 16).unwrap_err();
492        assert!(matches!(err, ReadRefusal::NotRegularFile { .. }));
493    }
494
495    #[test]
496    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
497    fn refuses_a_missing_file_and_reports_not_found() {
498        let dir = tempfile::tempdir().unwrap();
499        let err = read_to_string_inside(dir.path(), Path::new("none.json"), 16).unwrap_err();
500        assert!(err.is_not_found());
501        assert!(!is_inside_root(dir.path(), Path::new("none.json")));
502        assert!(!is_inside_root(&dir.path().join("no-root"), Path::new("x")));
503    }
504
505    #[test]
506    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
507    fn refuses_a_dot_dot_path_that_leaves_the_root() {
508        let outer = tempfile::tempdir().unwrap();
509        let root = outer.path().join("project");
510        std::fs::create_dir(&root).unwrap();
511        std::fs::write(outer.path().join("other.txt"), "content-7531").unwrap();
512        let err = read_to_string_inside(&root, Path::new("../other.txt"), 16).unwrap_err();
513        assert!(matches!(err, ReadRefusal::OutsideRoot { .. }));
514        assert!(!err.to_string().contains("content-7531"));
515        assert!(!is_inside_root(&root, Path::new("../other.txt")));
516    }
517
518    /// A link that leaves the root and comes back through `..` is outside
519    /// the root. The answer does not depend on whether the directory outside
520    /// the root exists.
521    #[cfg(unix)]
522    #[test]
523    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
524    fn refuses_a_link_that_leaves_the_root_and_comes_back() {
525        for middle_exists in [true, false] {
526            let outer = tempfile::tempdir().unwrap();
527            let root = outer.path().join("project");
528            std::fs::create_dir(&root).unwrap();
529            std::fs::write(root.join("real.json"), "{}").unwrap();
530            if middle_exists {
531                std::fs::create_dir(outer.path().join("probe")).unwrap();
532            }
533            std::os::unix::fs::symlink("../probe/../project/real.json", root.join("a.json"))
534                .unwrap();
535            std::os::unix::fs::symlink(
536                outer.path().join("probe/../project/real.json"),
537                root.join("b.json"),
538            )
539            .unwrap();
540            for name in ["a.json", "b.json"] {
541                let path = Path::new(name);
542                assert!(
543                    !is_inside_root(&root, path),
544                    "{name}, middle exists: {middle_exists}"
545                );
546                assert!(!ReadRoot::new(&root).is_inside(path), "{name}");
547                assert!(
548                    matches!(
549                        read_bytes_inside(&root, path, 16),
550                        Err(ReadRefusal::OutsideRoot { .. })
551                    ),
552                    "{name}, middle exists: {middle_exists}"
553                );
554            }
555        }
556    }
557
558    #[cfg(unix)]
559    #[test]
560    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
561    fn refuses_a_link_that_leaves_the_root() {
562        let outer = tempfile::tempdir().unwrap();
563        let root = outer.path().join("project");
564        std::fs::create_dir(&root).unwrap();
565        std::fs::write(outer.path().join("other.txt"), "content-7531").unwrap();
566        std::os::unix::fs::symlink(outer.path().join("other.txt"), root.join("a.json")).unwrap();
567        let err = read_to_string_inside(&root, Path::new("a.json"), 16).unwrap_err();
568        assert!(matches!(err, ReadRefusal::OutsideRoot { .. }));
569        assert!(!is_inside_root(&root, Path::new("a.json")));
570    }
571
572    #[cfg(unix)]
573    #[test]
574    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
575    fn allows_a_link_that_stays_inside_the_root() {
576        let dir = tempfile::tempdir().unwrap();
577        std::fs::write(dir.path().join("real.json"), "{}").unwrap();
578        std::os::unix::fs::symlink("real.json", dir.path().join("a.json")).unwrap();
579        let text = read_to_string_inside(dir.path(), Path::new("a.json"), 16).unwrap();
580        assert_eq!(text, "{}");
581    }
582
583    #[cfg(unix)]
584    #[test]
585    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
586    fn refuses_a_dangling_link_as_outside_the_root() {
587        let dir = tempfile::tempdir().unwrap();
588        std::os::unix::fs::symlink("/nonexistent/fallow/target", dir.path().join("a.json"))
589            .unwrap();
590        let err = read_to_string_inside(dir.path(), Path::new("a.json"), 16).unwrap_err();
591        assert!(matches!(err, ReadRefusal::OutsideRoot { .. }), "{err:?}");
592        assert!(!err.is_not_found());
593        std::fs::create_dir(dir.path().join("sub")).unwrap();
594        std::os::unix::fs::symlink("missing-dir", dir.path().join("sub/link")).unwrap();
595        let err = read_to_string_inside(dir.path(), Path::new("sub/link/a.json"), 16).unwrap_err();
596        assert!(matches!(err, ReadRefusal::OutsideRoot { .. }), "{err:?}");
597    }
598
599    #[test]
600    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
601    fn a_missing_file_inside_the_root_stays_not_found() {
602        let dir = tempfile::tempdir().unwrap();
603        std::fs::create_dir(dir.path().join("sub")).unwrap();
604        for path in ["sub/none.json", "sub/../none.json", "none/a.json"] {
605            let err = read_to_string_inside(dir.path(), Path::new(path), 16).unwrap_err();
606            assert!(err.is_not_found(), "{path}: {err:?}");
607        }
608        let err = read_to_string_inside(dir.path(), Path::new("../none.json"), 16).unwrap_err();
609        assert!(matches!(err, ReadRefusal::OutsideRoot { .. }), "{err:?}");
610    }
611
612    #[cfg(unix)]
613    #[test]
614    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
615    fn a_missing_file_through_another_spelling_of_the_root_stays_not_found() {
616        let dir = tempfile::tempdir().unwrap();
617        let root = dir.path().join("real");
618        std::fs::create_dir(&root).unwrap();
619        std::os::unix::fs::symlink(&root, dir.path().join("alias")).unwrap();
620        let path = dir.path().join("alias/none.json");
621        let err = read_to_string_inside(&root, &path, 16).unwrap_err();
622        assert!(err.is_not_found(), "{err:?}");
623    }
624
625    /// A missing file inside the root costs no path resolution beyond the
626    /// one of its directory, and a read root resolves that directory once.
627    #[test]
628    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
629    fn a_missing_file_inside_the_root_costs_no_prefix_walk() {
630        let dir = tempfile::tempdir().unwrap();
631        std::fs::create_dir(dir.path().join("sub")).unwrap();
632        let before = canonicalize_calls();
633        let err = read_to_string_inside(dir.path(), Path::new("none.json"), 16).unwrap_err();
634        assert!(err.is_not_found(), "{err:?}");
635        // The root only.
636        assert_eq!(canonicalize_calls() - before, 1);
637
638        let reader = ReadRoot::new(dir.path());
639        let before = canonicalize_calls();
640        for name in [
641            "a.json",
642            "b.json",
643            "sub/a.json",
644            "sub/b.json",
645            "sub/c.json",
646            "none/a.json",
647            "none/deeper/b.json",
648        ] {
649            let err = reader.read_to_string(Path::new(name), 16).unwrap_err();
650            assert!(err.is_not_found(), "{name}: {err:?}");
651        }
652        // The `sub` directory only.
653        assert_eq!(canonicalize_calls() - before, 1);
654    }
655
656    /// The kind of a read result, to compare two reads of one path.
657    #[cfg(unix)]
658    fn kind(result: Result<Vec<u8>, ReadRefusal>) -> String {
659        match result {
660            Ok(bytes) => format!("ok {bytes:?}"),
661            Err(ReadRefusal::OutsideRoot { .. }) => "outside".to_string(),
662            Err(ReadRefusal::NotRegularFile { .. }) => "not regular".to_string(),
663            Err(ReadRefusal::TooLarge { .. }) => "too large".to_string(),
664            Err(ReadRefusal::Io { source, .. }) => format!("io {:?}", source.kind()),
665        }
666    }
667
668    /// A read root refuses each path that the free read refuses, with the
669    /// same kind of refusal, and reads each file that the free read reads.
670    #[cfg(unix)]
671    #[test]
672    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
673    fn a_read_root_gives_the_results_of_the_free_read() {
674        let outer = tempfile::tempdir().unwrap();
675        let root = outer.path().join("project");
676        let elsewhere = outer.path().join("elsewhere");
677        std::fs::create_dir_all(root.join("sub")).unwrap();
678        std::fs::create_dir(&elsewhere).unwrap();
679        std::fs::write(root.join("own.json"), "{}").unwrap();
680        std::fs::write(outer.path().join("other.json"), "{}").unwrap();
681        std::fs::write(root.join("big.json"), "0123456789").unwrap();
682        let link = |target: &Path, name: &str| {
683            std::os::unix::fs::symlink(target, root.join(name)).unwrap();
684        };
685        link(&outer.path().join("other.json"), "out.json");
686        link(&elsewhere, "linked");
687        link(Path::new("/nonexistent/fallow/target"), "dangling.json");
688        link(Path::new("missing-dir"), "sub/dangling-dir");
689        link(Path::new("own.json"), "inner.json");
690        link(Path::new("/dev/zero"), "zero.json");
691        let reader = ReadRoot::new(&root);
692        let paths = [
693            "own.json",
694            "none.json",
695            "big.json",
696            "sub",
697            "sub/none.json",
698            "sub/../none.json",
699            "none/a.json",
700            "none/deeper/a.json",
701            "sub/none/a.json",
702            "linked/none/a.json",
703            "../none.json",
704            "../other.json",
705            "out.json",
706            "linked/none.json",
707            "linked/../other.json",
708            "dangling.json",
709            "sub/dangling-dir/a.json",
710            "inner.json",
711            "zero.json",
712            "own.json/a.json",
713        ];
714        let canonical = std::fs::canonicalize(&root).unwrap();
715        let absolute = [
716            canonical.join("own.json"),
717            canonical.join("none.json"),
718            canonical.join("none/a.json"),
719            canonical.join("out.json"),
720            canonical.join("linked/none.json"),
721        ];
722        let paths = paths
723            .iter()
724            .map(Path::new)
725            .chain(absolute.iter().map(PathBuf::as_path));
726        for path in paths {
727            let free = kind(read_bytes_inside(&root, path, 4));
728            assert_eq!(kind(reader.read_bytes(path, 4)), free, "{}", path.display());
729            assert_eq!(
730                reader.is_inside(path),
731                is_inside_root(&root, path),
732                "{}",
733                path.display()
734            );
735        }
736        assert_eq!(
737            kind(read_bytes_inside(&root, Path::new("out.json"), 4)),
738            "outside"
739        );
740        assert_eq!(
741            kind(read_bytes_inside(&root, Path::new("linked/none.json"), 4)),
742            "outside"
743        );
744        assert_eq!(
745            kind(read_bytes_inside(&root, Path::new("linked/none/a.json"), 4)),
746            "outside"
747        );
748        assert_eq!(
749            kind(read_bytes_inside(
750                &root,
751                Path::new("sub/dangling-dir/a.json"),
752                4
753            )),
754            "outside"
755        );
756        assert_eq!(
757            kind(read_bytes_inside(&root, Path::new("dangling.json"), 4)),
758            "outside"
759        );
760        assert_eq!(
761            kind(read_bytes_inside(&root, Path::new("sub"), 4)),
762            "not regular"
763        );
764        assert_eq!(
765            kind(read_bytes_inside(&root, Path::new("big.json"), 4)),
766            "too large"
767        );
768    }
769
770    /// A read root of a root that does not resolve refuses each read.
771    #[test]
772    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
773    fn a_read_root_that_does_not_resolve_refuses_each_read() {
774        let dir = tempfile::tempdir().unwrap();
775        let reader = ReadRoot::new(&dir.path().join("none"));
776        let err = reader.read_bytes(Path::new("a.json"), 16).unwrap_err();
777        assert!(err.is_not_found(), "{err:?}");
778        assert!(!reader.is_inside(Path::new("a.json")));
779    }
780
781    #[cfg(unix)]
782    #[test]
783    #[cfg_attr(miri, ignore = "file system access is blocked by Miri isolation")]
784    fn refuses_a_device_even_without_a_root_check() {
785        let err = read_to_string_bounded(Path::new("/dev/zero"), 16).unwrap_err();
786        assert!(matches!(err, ReadRefusal::NotRegularFile { .. }));
787    }
788}