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