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) = std::fs::canonicalize(root) else {
122        return false;
123    };
124    std::fs::canonicalize(root.join(path))
125        .is_ok_and(|resolved| resolved.starts_with(&canonical_root))
126}
127
128/// Read `path` in full when it resolves inside `root`, is a regular file and
129/// has at most `max_bytes` bytes. A relative `path` is taken relative to
130/// `root`. Use [`DEFAULT_MAX_READ_BYTES`] when no other limit applies.
131///
132/// # Errors
133///
134/// Returns a [`ReadRefusal`] when a check fails or the read fails.
135pub fn read_bytes_inside(root: &Path, path: &Path, max_bytes: u64) -> Result<Vec<u8>, ReadRefusal> {
136    let joined = root.join(path);
137    let io = |source: std::io::Error| ReadRefusal::Io {
138        path: path.to_path_buf(),
139        source,
140    };
141    let outside = || ReadRefusal::OutsideRoot {
142        path: path.to_path_buf(),
143        root: root.to_path_buf(),
144    };
145    let canonical_root = std::fs::canonicalize(root).map_err(io)?;
146    let resolved = match std::fs::canonicalize(&joined) {
147        Ok(resolved) => resolved,
148        Err(_) if unresolved_is_outside(&canonical_root, &joined) => return Err(outside()),
149        Err(source) => return Err(io(source)),
150    };
151    if !resolved.starts_with(&canonical_root) {
152        return Err(outside());
153    }
154    read_resolved(path, &resolved, max_bytes)
155}
156
157/// True when `joined`, a path that does not resolve, names a place outside
158/// `canonical_root` or ends in a dangling link. The longest leading part of
159/// `joined` that resolves is resolved, and the rest is taken by text, because
160/// no link exists below a missing entry. A dangling link at the first missing
161/// entry counts as outside, so a caller cannot tell a dangling link from a
162/// link to a file outside the root.
163fn unresolved_is_outside(canonical_root: &Path, joined: &Path) -> bool {
164    use std::path::Component;
165    let components: Vec<Component<'_>> = joined.components().collect();
166    let Some((resolved_len, mut current)) = (0..=components.len()).rev().find_map(|len| {
167        let prefix: PathBuf = components[..len].iter().collect();
168        std::fs::canonicalize(&prefix)
169            .ok()
170            .map(|resolved| (len, resolved))
171    }) else {
172        return true;
173    };
174    if !current.starts_with(canonical_root) {
175        return true;
176    }
177    for (index, component) in components[resolved_len..].iter().enumerate() {
178        match component {
179            Component::CurDir => {}
180            Component::ParentDir => {
181                current.pop();
182                if !current.starts_with(canonical_root) {
183                    return true;
184                }
185            }
186            Component::Normal(name) => {
187                current.push(name);
188                let dangling = index == 0
189                    && current
190                        .symlink_metadata()
191                        .is_ok_and(|meta| meta.file_type().is_symlink());
192                if dangling {
193                    return true;
194                }
195            }
196            Component::RootDir | Component::Prefix(_) => return true,
197        }
198    }
199    !current.starts_with(canonical_root)
200}
201
202/// [`read_bytes_inside`] that also requires valid UTF-8.
203///
204/// # Errors
205///
206/// Returns a [`ReadRefusal`] when a check fails, the read fails, or the
207/// content is not valid UTF-8.
208pub fn read_to_string_inside(
209    root: &Path,
210    path: &Path,
211    max_bytes: u64,
212) -> Result<String, ReadRefusal> {
213    let bytes = read_bytes_inside(root, path, max_bytes)?;
214    into_string(path, bytes)
215}
216
217/// Read `path` in full when it is a regular file with at most `max_bytes`
218/// bytes, with no root check. Use this only for a path that may leave the
219/// project by design, for example an absolute `extends` value of the user.
220///
221/// # Errors
222///
223/// Returns a [`ReadRefusal`] when a check fails, the read fails, or the
224/// content is not valid UTF-8.
225pub fn read_to_string_bounded(path: &Path, max_bytes: u64) -> Result<String, ReadRefusal> {
226    let bytes = read_resolved(path, path, max_bytes)?;
227    into_string(path, bytes)
228}
229
230/// [`read_to_string_bounded`] for bytes: read `path` in full when it is a
231/// regular file with at most `max_bytes` bytes, with no root check.
232///
233/// # Errors
234///
235/// Returns a [`ReadRefusal`] when a check fails or the read fails.
236pub fn read_bytes_bounded(path: &Path, max_bytes: u64) -> Result<Vec<u8>, ReadRefusal> {
237    read_resolved(path, path, max_bytes)
238}
239
240/// Whether `path` is a regular file with at most `max_bytes` bytes, after a
241/// link resolves. A bounded read of such a file does not refuse it for its
242/// type or size.
243#[must_use]
244pub fn is_bounded_regular_file(path: &Path, max_bytes: u64) -> bool {
245    std::fs::metadata(path).is_ok_and(|meta| meta.is_file() && meta.len() <= max_bytes)
246}
247
248fn read_resolved(path: &Path, resolved: &Path, max_bytes: u64) -> Result<Vec<u8>, ReadRefusal> {
249    let io = |source: std::io::Error| ReadRefusal::Io {
250        path: path.to_path_buf(),
251        source,
252    };
253    let meta = std::fs::metadata(resolved).map_err(io)?;
254    if !meta.is_file() {
255        return Err(ReadRefusal::NotRegularFile {
256            path: path.to_path_buf(),
257        });
258    }
259    let too_large = || ReadRefusal::TooLarge {
260        path: path.to_path_buf(),
261        max_bytes,
262    };
263    if meta.len() > max_bytes {
264        return Err(too_large());
265    }
266    let file = std::fs::File::open(resolved).map_err(io)?;
267    let mut bytes = Vec::new();
268    // The file can grow after the metadata call, so the read stops one byte
269    // past the limit and refuses the file when it reaches that byte.
270    file.take(max_bytes.saturating_add(1))
271        .read_to_end(&mut bytes)
272        .map_err(io)?;
273    if bytes.len() as u64 > max_bytes {
274        return Err(too_large());
275    }
276    Ok(bytes)
277}
278
279fn into_string(path: &Path, bytes: Vec<u8>) -> Result<String, ReadRefusal> {
280    String::from_utf8(bytes).map_err(|_| ReadRefusal::Io {
281        path: path.to_path_buf(),
282        source: std::io::Error::new(
283            std::io::ErrorKind::InvalidData,
284            "stream did not contain valid UTF-8",
285        ),
286    })
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292
293    #[test]
294    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
295    fn reads_a_regular_file_inside_the_root() {
296        let dir = tempfile::tempdir().unwrap();
297        std::fs::write(dir.path().join("a.json"), "{}").unwrap();
298        let text = read_to_string_inside(dir.path(), Path::new("a.json"), 16).unwrap();
299        assert_eq!(text, "{}");
300        let abs = dir.path().join("a.json");
301        assert_eq!(read_bytes_inside(dir.path(), &abs, 16).unwrap(), b"{}");
302        assert!(is_inside_root(dir.path(), &abs));
303    }
304
305    #[test]
306    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
307    fn bounded_bytes_read_takes_regular_files_within_the_limit_only() {
308        let dir = tempfile::tempdir().unwrap();
309        let file = dir.path().join("a.json");
310        std::fs::write(&file, "{}").unwrap();
311        assert_eq!(read_bytes_bounded(&file, 16).unwrap(), b"{}");
312        assert!(is_bounded_regular_file(&file, 16));
313        assert!(read_bytes_bounded(&file, 1).is_err());
314        assert!(!is_bounded_regular_file(&file, 1));
315        assert!(read_bytes_bounded(dir.path(), 16).is_err());
316        assert!(!is_bounded_regular_file(dir.path(), 16));
317    }
318
319    #[test]
320    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
321    fn refuses_a_file_over_the_limit() {
322        let dir = tempfile::tempdir().unwrap();
323        std::fs::write(dir.path().join("a.json"), "0123456789").unwrap();
324        let err = read_to_string_inside(dir.path(), Path::new("a.json"), 4).unwrap_err();
325        assert!(matches!(err, ReadRefusal::TooLarge { max_bytes: 4, .. }));
326        assert!(!err.to_string().contains("0123"));
327        let err = read_to_string_bounded(&dir.path().join("a.json"), 4).unwrap_err();
328        assert!(matches!(err, ReadRefusal::TooLarge { .. }));
329    }
330
331    #[test]
332    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
333    fn refuses_a_directory() {
334        let dir = tempfile::tempdir().unwrap();
335        std::fs::create_dir(dir.path().join("sub")).unwrap();
336        let err = read_to_string_inside(dir.path(), Path::new("sub"), 16).unwrap_err();
337        assert!(matches!(err, ReadRefusal::NotRegularFile { .. }));
338    }
339
340    #[test]
341    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
342    fn refuses_a_missing_file_and_reports_not_found() {
343        let dir = tempfile::tempdir().unwrap();
344        let err = read_to_string_inside(dir.path(), Path::new("none.json"), 16).unwrap_err();
345        assert!(err.is_not_found());
346        assert!(!is_inside_root(dir.path(), Path::new("none.json")));
347        assert!(!is_inside_root(&dir.path().join("no-root"), Path::new("x")));
348    }
349
350    #[test]
351    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
352    fn refuses_a_dot_dot_path_that_leaves_the_root() {
353        let outer = tempfile::tempdir().unwrap();
354        let root = outer.path().join("project");
355        std::fs::create_dir(&root).unwrap();
356        std::fs::write(outer.path().join("other.txt"), "content-7531").unwrap();
357        let err = read_to_string_inside(&root, Path::new("../other.txt"), 16).unwrap_err();
358        assert!(matches!(err, ReadRefusal::OutsideRoot { .. }));
359        assert!(!err.to_string().contains("content-7531"));
360        assert!(!is_inside_root(&root, Path::new("../other.txt")));
361    }
362
363    #[cfg(unix)]
364    #[test]
365    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
366    fn refuses_a_link_that_leaves_the_root() {
367        let outer = tempfile::tempdir().unwrap();
368        let root = outer.path().join("project");
369        std::fs::create_dir(&root).unwrap();
370        std::fs::write(outer.path().join("other.txt"), "content-7531").unwrap();
371        std::os::unix::fs::symlink(outer.path().join("other.txt"), root.join("a.json")).unwrap();
372        let err = read_to_string_inside(&root, Path::new("a.json"), 16).unwrap_err();
373        assert!(matches!(err, ReadRefusal::OutsideRoot { .. }));
374        assert!(!is_inside_root(&root, Path::new("a.json")));
375    }
376
377    #[cfg(unix)]
378    #[test]
379    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
380    fn allows_a_link_that_stays_inside_the_root() {
381        let dir = tempfile::tempdir().unwrap();
382        std::fs::write(dir.path().join("real.json"), "{}").unwrap();
383        std::os::unix::fs::symlink("real.json", dir.path().join("a.json")).unwrap();
384        let text = read_to_string_inside(dir.path(), Path::new("a.json"), 16).unwrap();
385        assert_eq!(text, "{}");
386    }
387
388    #[cfg(unix)]
389    #[test]
390    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
391    fn refuses_a_dangling_link_as_outside_the_root() {
392        let dir = tempfile::tempdir().unwrap();
393        std::os::unix::fs::symlink("/nonexistent/fallow/target", dir.path().join("a.json"))
394            .unwrap();
395        let err = read_to_string_inside(dir.path(), Path::new("a.json"), 16).unwrap_err();
396        assert!(matches!(err, ReadRefusal::OutsideRoot { .. }), "{err:?}");
397        assert!(!err.is_not_found());
398        std::fs::create_dir(dir.path().join("sub")).unwrap();
399        std::os::unix::fs::symlink("missing-dir", dir.path().join("sub/link")).unwrap();
400        let err = read_to_string_inside(dir.path(), Path::new("sub/link/a.json"), 16).unwrap_err();
401        assert!(matches!(err, ReadRefusal::OutsideRoot { .. }), "{err:?}");
402    }
403
404    #[test]
405    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
406    fn a_missing_file_inside_the_root_stays_not_found() {
407        let dir = tempfile::tempdir().unwrap();
408        std::fs::create_dir(dir.path().join("sub")).unwrap();
409        for path in ["sub/none.json", "sub/../none.json", "none/a.json"] {
410            let err = read_to_string_inside(dir.path(), Path::new(path), 16).unwrap_err();
411            assert!(err.is_not_found(), "{path}: {err:?}");
412        }
413        let err = read_to_string_inside(dir.path(), Path::new("../none.json"), 16).unwrap_err();
414        assert!(matches!(err, ReadRefusal::OutsideRoot { .. }), "{err:?}");
415    }
416
417    #[cfg(unix)]
418    #[test]
419    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
420    fn a_missing_file_through_another_spelling_of_the_root_stays_not_found() {
421        let dir = tempfile::tempdir().unwrap();
422        let root = dir.path().join("real");
423        std::fs::create_dir(&root).unwrap();
424        std::os::unix::fs::symlink(&root, dir.path().join("alias")).unwrap();
425        let path = dir.path().join("alias/none.json");
426        let err = read_to_string_inside(&root, &path, 16).unwrap_err();
427        assert!(err.is_not_found(), "{err:?}");
428    }
429
430    #[cfg(unix)]
431    #[test]
432    #[cfg_attr(miri, ignore = "file system access is blocked by Miri isolation")]
433    fn refuses_a_device_even_without_a_root_check() {
434        let err = read_to_string_bounded(Path::new("/dev/zero"), 16).unwrap_err();
435        assert!(matches!(err, ReadRefusal::NotRegularFile { .. }));
436    }
437}