fallow-types 3.49.0

Shared types and serde paths for fallow codebase intelligence
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! Bounded reads of project files.
//!
//! fallow reads project files such as a config file, a `tsconfig.json` or a
//! `CODEOWNERS` file in full. The helpers here read such a file only when it
//! resolves inside the project root, is a regular file, and fits a size
//! limit. A link that resolves inside the root stays allowed. A device or a
//! very large file is refused before the read, so the read cannot block or
//! fill memory.
//!
//! Each check fails closed: when the helper cannot decide, it refuses.

use std::fmt;
use std::io::Read;
use std::path::{Path, PathBuf};

/// The default size limit for a project file that fallow reads in full.
///
/// Config files, `tsconfig.json` files, rule packs and `CODEOWNERS` files of
/// large monorepos stay well below 1 MiB. 16 MiB leaves room for configs
/// that tools write, and still stops a read of a device or a multi-gigabyte
/// file.
pub const DEFAULT_MAX_READ_BYTES: u64 = 16 * 1024 * 1024;

/// The reason that a bounded read refused a file.
///
/// The `Display` text names the path and the reason. It never contains
/// content of the file.
#[derive(Debug)]
pub enum ReadRefusal {
    /// The path, after symlinks are resolved, is outside the root.
    OutsideRoot {
        /// The path as the caller gave it.
        path: PathBuf,
        /// The root that the path must stay in.
        root: PathBuf,
    },
    /// The path is not a regular file, for example a directory or a device.
    NotRegularFile {
        /// The path as the caller gave it.
        path: PathBuf,
    },
    /// The file is larger than the limit.
    TooLarge {
        /// The path as the caller gave it.
        path: PathBuf,
        /// The limit in bytes.
        max_bytes: u64,
    },
    /// The path or the root does not resolve, or the read failed.
    Io {
        /// The path as the caller gave it.
        path: PathBuf,
        /// The error of the file system call.
        source: std::io::Error,
    },
}

impl ReadRefusal {
    /// The path as the caller gave it.
    #[must_use]
    pub fn path(&self) -> &Path {
        match self {
            Self::OutsideRoot { path, .. }
            | Self::NotRegularFile { path }
            | Self::TooLarge { path, .. }
            | Self::Io { path, .. } => path,
        }
    }

    /// True when the file does not exist. A link on the path that does not
    /// resolve gives [`ReadRefusal::OutsideRoot`], not this state, so a
    /// dangling link and a link to a file outside the root look the same.
    #[must_use]
    pub fn is_not_found(&self) -> bool {
        matches!(self, Self::Io { source, .. } if source.kind() == std::io::ErrorKind::NotFound)
    }
}

impl fmt::Display for ReadRefusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::OutsideRoot { path, root } => write!(
                f,
                "refusing to read {}: it resolves to a location outside {}",
                path.display(),
                root.display()
            ),
            Self::NotRegularFile { path } => write!(
                f,
                "refusing to read {}: it is not a regular file",
                path.display()
            ),
            Self::TooLarge { path, max_bytes } => write!(
                f,
                "refusing to read {}: it is larger than {max_bytes} bytes",
                path.display()
            ),
            Self::Io { path, source } => {
                write!(f, "cannot read {}: {source}", path.display())
            }
        }
    }
}

impl std::error::Error for ReadRefusal {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            _ => None,
        }
    }
}

/// True when `path`, after symlinks are resolved, is `root` or a path below
/// the resolved `root`. A relative `path` is taken relative to `root`.
///
/// Returns `false` when `root` or `path` does not resolve, for example a
/// missing file, a dangling link or a path that is too long.
#[must_use]
pub fn is_inside_root(root: &Path, path: &Path) -> bool {
    let Ok(canonical_root) = std::fs::canonicalize(root) else {
        return false;
    };
    std::fs::canonicalize(root.join(path))
        .is_ok_and(|resolved| resolved.starts_with(&canonical_root))
}

/// Read `path` in full when it resolves inside `root`, is a regular file and
/// has at most `max_bytes` bytes. A relative `path` is taken relative to
/// `root`. Use [`DEFAULT_MAX_READ_BYTES`] when no other limit applies.
///
/// # Errors
///
/// Returns a [`ReadRefusal`] when a check fails or the read fails.
pub fn read_bytes_inside(root: &Path, path: &Path, max_bytes: u64) -> Result<Vec<u8>, ReadRefusal> {
    let joined = root.join(path);
    let io = |source: std::io::Error| ReadRefusal::Io {
        path: path.to_path_buf(),
        source,
    };
    let outside = || ReadRefusal::OutsideRoot {
        path: path.to_path_buf(),
        root: root.to_path_buf(),
    };
    let canonical_root = std::fs::canonicalize(root).map_err(io)?;
    let resolved = match std::fs::canonicalize(&joined) {
        Ok(resolved) => resolved,
        Err(_) if unresolved_is_outside(&canonical_root, &joined) => return Err(outside()),
        Err(source) => return Err(io(source)),
    };
    if !resolved.starts_with(&canonical_root) {
        return Err(outside());
    }
    read_resolved(path, &resolved, max_bytes)
}

/// True when `joined`, a path that does not resolve, names a place outside
/// `canonical_root` or ends in a dangling link. The longest leading part of
/// `joined` that resolves is resolved, and the rest is taken by text, because
/// no link exists below a missing entry. A dangling link at the first missing
/// entry counts as outside, so a caller cannot tell a dangling link from a
/// link to a file outside the root.
fn unresolved_is_outside(canonical_root: &Path, joined: &Path) -> bool {
    use std::path::Component;
    let components: Vec<Component<'_>> = joined.components().collect();
    let Some((resolved_len, mut current)) = (0..=components.len()).rev().find_map(|len| {
        let prefix: PathBuf = components[..len].iter().collect();
        std::fs::canonicalize(&prefix)
            .ok()
            .map(|resolved| (len, resolved))
    }) else {
        return true;
    };
    if !current.starts_with(canonical_root) {
        return true;
    }
    for (index, component) in components[resolved_len..].iter().enumerate() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                current.pop();
                if !current.starts_with(canonical_root) {
                    return true;
                }
            }
            Component::Normal(name) => {
                current.push(name);
                let dangling = index == 0
                    && current
                        .symlink_metadata()
                        .is_ok_and(|meta| meta.file_type().is_symlink());
                if dangling {
                    return true;
                }
            }
            Component::RootDir | Component::Prefix(_) => return true,
        }
    }
    !current.starts_with(canonical_root)
}

/// [`read_bytes_inside`] that also requires valid UTF-8.
///
/// # Errors
///
/// Returns a [`ReadRefusal`] when a check fails, the read fails, or the
/// content is not valid UTF-8.
pub fn read_to_string_inside(
    root: &Path,
    path: &Path,
    max_bytes: u64,
) -> Result<String, ReadRefusal> {
    let bytes = read_bytes_inside(root, path, max_bytes)?;
    into_string(path, bytes)
}

/// Read `path` in full when it is a regular file with at most `max_bytes`
/// bytes, with no root check. Use this only for a path that may leave the
/// project by design, for example an absolute `extends` value of the user.
///
/// # Errors
///
/// Returns a [`ReadRefusal`] when a check fails, the read fails, or the
/// content is not valid UTF-8.
pub fn read_to_string_bounded(path: &Path, max_bytes: u64) -> Result<String, ReadRefusal> {
    let bytes = read_resolved(path, path, max_bytes)?;
    into_string(path, bytes)
}

/// [`read_to_string_bounded`] for bytes: read `path` in full when it is a
/// regular file with at most `max_bytes` bytes, with no root check.
///
/// # Errors
///
/// Returns a [`ReadRefusal`] when a check fails or the read fails.
pub fn read_bytes_bounded(path: &Path, max_bytes: u64) -> Result<Vec<u8>, ReadRefusal> {
    read_resolved(path, path, max_bytes)
}

/// Whether `path` is a regular file with at most `max_bytes` bytes, after a
/// link resolves. A bounded read of such a file does not refuse it for its
/// type or size.
#[must_use]
pub fn is_bounded_regular_file(path: &Path, max_bytes: u64) -> bool {
    std::fs::metadata(path).is_ok_and(|meta| meta.is_file() && meta.len() <= max_bytes)
}

fn read_resolved(path: &Path, resolved: &Path, max_bytes: u64) -> Result<Vec<u8>, ReadRefusal> {
    let io = |source: std::io::Error| ReadRefusal::Io {
        path: path.to_path_buf(),
        source,
    };
    let meta = std::fs::metadata(resolved).map_err(io)?;
    if !meta.is_file() {
        return Err(ReadRefusal::NotRegularFile {
            path: path.to_path_buf(),
        });
    }
    let too_large = || ReadRefusal::TooLarge {
        path: path.to_path_buf(),
        max_bytes,
    };
    if meta.len() > max_bytes {
        return Err(too_large());
    }
    let file = std::fs::File::open(resolved).map_err(io)?;
    let mut bytes = Vec::new();
    // The file can grow after the metadata call, so the read stops one byte
    // past the limit and refuses the file when it reaches that byte.
    file.take(max_bytes.saturating_add(1))
        .read_to_end(&mut bytes)
        .map_err(io)?;
    if bytes.len() as u64 > max_bytes {
        return Err(too_large());
    }
    Ok(bytes)
}

fn into_string(path: &Path, bytes: Vec<u8>) -> Result<String, ReadRefusal> {
    String::from_utf8(bytes).map_err(|_| ReadRefusal::Io {
        path: path.to_path_buf(),
        source: std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "stream did not contain valid UTF-8",
        ),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
    fn reads_a_regular_file_inside_the_root() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("a.json"), "{}").unwrap();
        let text = read_to_string_inside(dir.path(), Path::new("a.json"), 16).unwrap();
        assert_eq!(text, "{}");
        let abs = dir.path().join("a.json");
        assert_eq!(read_bytes_inside(dir.path(), &abs, 16).unwrap(), b"{}");
        assert!(is_inside_root(dir.path(), &abs));
    }

    #[test]
    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
    fn bounded_bytes_read_takes_regular_files_within_the_limit_only() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("a.json");
        std::fs::write(&file, "{}").unwrap();
        assert_eq!(read_bytes_bounded(&file, 16).unwrap(), b"{}");
        assert!(is_bounded_regular_file(&file, 16));
        assert!(read_bytes_bounded(&file, 1).is_err());
        assert!(!is_bounded_regular_file(&file, 1));
        assert!(read_bytes_bounded(dir.path(), 16).is_err());
        assert!(!is_bounded_regular_file(dir.path(), 16));
    }

    #[test]
    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
    fn refuses_a_file_over_the_limit() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("a.json"), "0123456789").unwrap();
        let err = read_to_string_inside(dir.path(), Path::new("a.json"), 4).unwrap_err();
        assert!(matches!(err, ReadRefusal::TooLarge { max_bytes: 4, .. }));
        assert!(!err.to_string().contains("0123"));
        let err = read_to_string_bounded(&dir.path().join("a.json"), 4).unwrap_err();
        assert!(matches!(err, ReadRefusal::TooLarge { .. }));
    }

    #[test]
    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
    fn refuses_a_directory() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join("sub")).unwrap();
        let err = read_to_string_inside(dir.path(), Path::new("sub"), 16).unwrap_err();
        assert!(matches!(err, ReadRefusal::NotRegularFile { .. }));
    }

    #[test]
    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
    fn refuses_a_missing_file_and_reports_not_found() {
        let dir = tempfile::tempdir().unwrap();
        let err = read_to_string_inside(dir.path(), Path::new("none.json"), 16).unwrap_err();
        assert!(err.is_not_found());
        assert!(!is_inside_root(dir.path(), Path::new("none.json")));
        assert!(!is_inside_root(&dir.path().join("no-root"), Path::new("x")));
    }

    #[test]
    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
    fn refuses_a_dot_dot_path_that_leaves_the_root() {
        let outer = tempfile::tempdir().unwrap();
        let root = outer.path().join("project");
        std::fs::create_dir(&root).unwrap();
        std::fs::write(outer.path().join("other.txt"), "content-7531").unwrap();
        let err = read_to_string_inside(&root, Path::new("../other.txt"), 16).unwrap_err();
        assert!(matches!(err, ReadRefusal::OutsideRoot { .. }));
        assert!(!err.to_string().contains("content-7531"));
        assert!(!is_inside_root(&root, Path::new("../other.txt")));
    }

    #[cfg(unix)]
    #[test]
    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
    fn refuses_a_link_that_leaves_the_root() {
        let outer = tempfile::tempdir().unwrap();
        let root = outer.path().join("project");
        std::fs::create_dir(&root).unwrap();
        std::fs::write(outer.path().join("other.txt"), "content-7531").unwrap();
        std::os::unix::fs::symlink(outer.path().join("other.txt"), root.join("a.json")).unwrap();
        let err = read_to_string_inside(&root, Path::new("a.json"), 16).unwrap_err();
        assert!(matches!(err, ReadRefusal::OutsideRoot { .. }));
        assert!(!is_inside_root(&root, Path::new("a.json")));
    }

    #[cfg(unix)]
    #[test]
    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
    fn allows_a_link_that_stays_inside_the_root() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("real.json"), "{}").unwrap();
        std::os::unix::fs::symlink("real.json", dir.path().join("a.json")).unwrap();
        let text = read_to_string_inside(dir.path(), Path::new("a.json"), 16).unwrap();
        assert_eq!(text, "{}");
    }

    #[cfg(unix)]
    #[test]
    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
    fn refuses_a_dangling_link_as_outside_the_root() {
        let dir = tempfile::tempdir().unwrap();
        std::os::unix::fs::symlink("/nonexistent/fallow/target", dir.path().join("a.json"))
            .unwrap();
        let err = read_to_string_inside(dir.path(), Path::new("a.json"), 16).unwrap_err();
        assert!(matches!(err, ReadRefusal::OutsideRoot { .. }), "{err:?}");
        assert!(!err.is_not_found());
        std::fs::create_dir(dir.path().join("sub")).unwrap();
        std::os::unix::fs::symlink("missing-dir", dir.path().join("sub/link")).unwrap();
        let err = read_to_string_inside(dir.path(), Path::new("sub/link/a.json"), 16).unwrap_err();
        assert!(matches!(err, ReadRefusal::OutsideRoot { .. }), "{err:?}");
    }

    #[test]
    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
    fn a_missing_file_inside_the_root_stays_not_found() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join("sub")).unwrap();
        for path in ["sub/none.json", "sub/../none.json", "none/a.json"] {
            let err = read_to_string_inside(dir.path(), Path::new(path), 16).unwrap_err();
            assert!(err.is_not_found(), "{path}: {err:?}");
        }
        let err = read_to_string_inside(dir.path(), Path::new("../none.json"), 16).unwrap_err();
        assert!(matches!(err, ReadRefusal::OutsideRoot { .. }), "{err:?}");
    }

    #[cfg(unix)]
    #[test]
    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
    fn a_missing_file_through_another_spelling_of_the_root_stays_not_found() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("real");
        std::fs::create_dir(&root).unwrap();
        std::os::unix::fs::symlink(&root, dir.path().join("alias")).unwrap();
        let path = dir.path().join("alias/none.json");
        let err = read_to_string_inside(&root, &path, 16).unwrap_err();
        assert!(err.is_not_found(), "{err:?}");
    }

    #[cfg(unix)]
    #[test]
    #[cfg_attr(miri, ignore = "file system access is blocked by Miri isolation")]
    fn refuses_a_device_even_without_a_root_check() {
        let err = read_to_string_bounded(Path::new("/dev/zero"), 16).unwrap_err();
        assert!(matches!(err, ReadRefusal::NotRegularFile { .. }));
    }
}