fallow-types 3.50.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
//! 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) = canonicalize(root) else {
        return false;
    };
    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 canonical_root = canonicalize(root).map_err(|source| ReadRefusal::Io {
        path: path.to_path_buf(),
        source,
    })?;
    read_bytes_in(root, &canonical_root, path, max_bytes, |dir| {
        canonicalize(dir).ok()
    })
}

/// A root for many bounded reads, such as the probes of many candidate
/// files. The root resolves once, and each directory that holds a missing
/// candidate resolves once. So a missing candidate costs one `lstat` call.
/// A read gives the same result as [`read_bytes_inside`] with the same root.
///
/// A file system change after a directory resolves is not seen, so keep a
/// `ReadRoot` for one scan only.
#[derive(Debug)]
pub struct ReadRoot {
    root: PathBuf,
    canonical: Result<PathBuf, std::io::ErrorKind>,
    dirs: std::cell::RefCell<rustc_hash::FxHashMap<PathBuf, Option<PathBuf>>>,
}

impl ReadRoot {
    /// A read root for `root`.
    #[must_use]
    pub fn new(root: &Path) -> Self {
        Self {
            root: root.to_path_buf(),
            canonical: canonicalize(root).map_err(|error| error.kind()),
            dirs: std::cell::RefCell::default(),
        }
    }

    /// [`read_bytes_inside`] with this root.
    ///
    /// # Errors
    ///
    /// Returns a [`ReadRefusal`] when a check fails or the read fails.
    pub fn read_bytes(&self, path: &Path, max_bytes: u64) -> Result<Vec<u8>, ReadRefusal> {
        let canonical_root = self.canonical.as_ref().map_err(|kind| ReadRefusal::Io {
            path: path.to_path_buf(),
            source: std::io::Error::from(*kind),
        })?;
        read_bytes_in(&self.root, canonical_root, path, max_bytes, |dir| {
            self.dirs
                .borrow_mut()
                .entry(dir.to_path_buf())
                .or_insert_with(|| canonicalize(dir).ok())
                .clone()
        })
    }

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

    /// [`is_inside_root`] with this root.
    #[must_use]
    pub fn is_inside(&self, path: &Path) -> bool {
        let Ok(canonical_root) = &self.canonical else {
            return false;
        };
        let joined = self.root.join(path);
        // A path with no entry does not resolve, so one `lstat` call answers.
        if joined
            .symlink_metadata()
            .is_err_and(|error| error.kind() == std::io::ErrorKind::NotFound)
        {
            return false;
        }
        canonicalize(&joined).is_ok_and(|resolved| resolved.starts_with(canonical_root))
    }
}

/// The checks and the read of [`read_bytes_inside`] for the resolved root
/// `canonical_root`. `resolve_dir` resolves the directory that holds a
/// missing entry.
fn read_bytes_in(
    root: &Path,
    canonical_root: &Path,
    path: &Path,
    max_bytes: u64,
    resolve_dir: impl FnOnce(&Path) -> Option<PathBuf>,
) -> 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(),
    };
    if let Some(source) = missing_inside(root, canonical_root, &joined, resolve_dir) {
        return Err(io(source));
    }
    let resolved = match 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)
}

/// The `NotFound` error of `joined` when no entry, not even a link, has that
/// name and the nearest existing directory above it resolves inside
/// `canonical_root`. No link exists below a missing entry, so the full check
/// of [`unresolved_is_outside`] cannot find a link out of the root. The walk
/// up costs one `lstat` call for each missing directory. `None` sends the
/// path to the full check: an entry that exists, a dangling link, a `..`
/// component, a directory that does not resolve, or a directory outside the
/// root.
fn missing_inside(
    root: &Path,
    canonical_root: &Path,
    joined: &Path,
    resolve_dir: impl FnOnce(&Path) -> Option<PathBuf>,
) -> Option<std::io::Error> {
    use std::path::Component;
    let error = joined.symlink_metadata().err()?;
    if error.kind() != std::io::ErrorKind::NotFound {
        return None;
    }
    let mut missing = joined;
    loop {
        if !matches!(missing.components().next_back(), Some(Component::Normal(_))) {
            return None;
        }
        let dir = missing.parent()?;
        if dir == root {
            return Some(error);
        }
        match dir.symlink_metadata() {
            Err(dir_error) if dir_error.kind() == std::io::ErrorKind::NotFound => missing = dir,
            Err(_) => return None,
            Ok(_) => {
                let inside = resolve_dir(dir).is_some_and(|dir| dir.starts_with(canonical_root));
                return inside.then_some(error);
            }
        }
    }
}

/// `std::fs::canonicalize`, counted in test builds (see
/// `canonicalize_calls`).
fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
    #[cfg(any(test, feature = "testing"))]
    CANONICALIZE_CALLS.with(|calls| calls.set(calls.get() + 1));
    std::fs::canonicalize(path)
}

#[cfg(any(test, feature = "testing"))]
std::thread_local! {
    static CANONICALIZE_CALLS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}

/// The number of path resolutions that the bounded read helpers made on this
/// thread. A test compares two counts to check the cost of a scan.
#[cfg(any(test, feature = "testing"))]
#[must_use]
pub fn canonicalize_calls() -> u64 {
    CANONICALIZE_CALLS.with(std::cell::Cell::get)
}

/// 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();
        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 not_regular = || ReadRefusal::NotRegularFile {
        path: path.to_path_buf(),
    };
    let too_large = || ReadRefusal::TooLarge {
        path: path.to_path_buf(),
        max_bytes,
    };
    // The check before the open skips a device or a FIFO without opening it.
    // The path can change between that check and the open, so the opened
    // file is checked again. The open does not wait for a FIFO writer.
    if !std::fs::metadata(resolved).map_err(io)?.is_file() {
        return Err(not_regular());
    }
    let file = open_without_blocking(resolved).map_err(io)?;
    let meta = file.metadata().map_err(io)?;
    if !meta.is_file() {
        return Err(not_regular());
    }
    if meta.len() > max_bytes {
        return Err(too_large());
    }
    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)
}

/// Open `path` for reading. On Unix the open does not wait for the writer of
/// a FIFO, so a FIFO that replaces a checked file cannot hang the read.
fn open_without_blocking(path: &Path) -> std::io::Result<std::fs::File> {
    let mut options = std::fs::OpenOptions::new();
    options.read(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.custom_flags(rustix::fs::OFlags::NONBLOCK.bits().cast_signed());
    }
    options.open(path)
}

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::*;

    /// The checked open does not wait for a FIFO writer, and the check of
    /// the opened file refuses what is not a regular file.
    #[test]
    #[cfg(unix)]
    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
    fn the_open_does_not_wait_for_a_fifo_and_checks_the_opened_file() {
        let dir = tempfile::tempdir().unwrap();
        let fifo = dir.path().join("pipe.json");
        let status = std::process::Command::new("mkfifo")
            .arg(&fifo)
            .status()
            .unwrap();
        assert!(status.success());
        let file = open_without_blocking(&fifo).unwrap();
        assert!(!file.metadata().unwrap().is_file());
        assert!(matches!(
            read_to_string_bounded(&fifo, 16),
            Err(ReadRefusal::NotRegularFile { .. })
        ));
    }

    #[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:?}");
    }

    /// A missing file inside the root costs no path resolution beyond the
    /// one of its directory, and a read root resolves that directory once.
    #[test]
    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
    fn a_missing_file_inside_the_root_costs_no_prefix_walk() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join("sub")).unwrap();
        let before = canonicalize_calls();
        let err = read_to_string_inside(dir.path(), Path::new("none.json"), 16).unwrap_err();
        assert!(err.is_not_found(), "{err:?}");
        // The root only.
        assert_eq!(canonicalize_calls() - before, 1);

        let reader = ReadRoot::new(dir.path());
        let before = canonicalize_calls();
        for name in [
            "a.json",
            "b.json",
            "sub/a.json",
            "sub/b.json",
            "sub/c.json",
            "none/a.json",
            "none/deeper/b.json",
        ] {
            let err = reader.read_to_string(Path::new(name), 16).unwrap_err();
            assert!(err.is_not_found(), "{name}: {err:?}");
        }
        // The `sub` directory only.
        assert_eq!(canonicalize_calls() - before, 1);
    }

    /// The kind of a read result, to compare two reads of one path.
    #[cfg(unix)]
    fn kind(result: Result<Vec<u8>, ReadRefusal>) -> String {
        match result {
            Ok(bytes) => format!("ok {bytes:?}"),
            Err(ReadRefusal::OutsideRoot { .. }) => "outside".to_string(),
            Err(ReadRefusal::NotRegularFile { .. }) => "not regular".to_string(),
            Err(ReadRefusal::TooLarge { .. }) => "too large".to_string(),
            Err(ReadRefusal::Io { source, .. }) => format!("io {:?}", source.kind()),
        }
    }

    /// A read root refuses each path that the free read refuses, with the
    /// same kind of refusal, and reads each file that the free read reads.
    #[cfg(unix)]
    #[test]
    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
    fn a_read_root_gives_the_results_of_the_free_read() {
        let outer = tempfile::tempdir().unwrap();
        let root = outer.path().join("project");
        let elsewhere = outer.path().join("elsewhere");
        std::fs::create_dir_all(root.join("sub")).unwrap();
        std::fs::create_dir(&elsewhere).unwrap();
        std::fs::write(root.join("own.json"), "{}").unwrap();
        std::fs::write(outer.path().join("other.json"), "{}").unwrap();
        std::fs::write(root.join("big.json"), "0123456789").unwrap();
        let link = |target: &Path, name: &str| {
            std::os::unix::fs::symlink(target, root.join(name)).unwrap();
        };
        link(&outer.path().join("other.json"), "out.json");
        link(&elsewhere, "linked");
        link(Path::new("/nonexistent/fallow/target"), "dangling.json");
        link(Path::new("missing-dir"), "sub/dangling-dir");
        link(Path::new("own.json"), "inner.json");
        link(Path::new("/dev/zero"), "zero.json");
        let reader = ReadRoot::new(&root);
        let paths = [
            "own.json",
            "none.json",
            "big.json",
            "sub",
            "sub/none.json",
            "sub/../none.json",
            "none/a.json",
            "none/deeper/a.json",
            "sub/none/a.json",
            "linked/none/a.json",
            "../none.json",
            "../other.json",
            "out.json",
            "linked/none.json",
            "linked/../other.json",
            "dangling.json",
            "sub/dangling-dir/a.json",
            "inner.json",
            "zero.json",
            "own.json/a.json",
        ];
        let canonical = std::fs::canonicalize(&root).unwrap();
        let absolute = [
            canonical.join("own.json"),
            canonical.join("none.json"),
            canonical.join("none/a.json"),
            canonical.join("out.json"),
            canonical.join("linked/none.json"),
        ];
        let paths = paths
            .iter()
            .map(Path::new)
            .chain(absolute.iter().map(PathBuf::as_path));
        for path in paths {
            let free = kind(read_bytes_inside(&root, path, 4));
            assert_eq!(kind(reader.read_bytes(path, 4)), free, "{}", path.display());
            assert_eq!(
                reader.is_inside(path),
                is_inside_root(&root, path),
                "{}",
                path.display()
            );
        }
        assert_eq!(
            kind(read_bytes_inside(&root, Path::new("out.json"), 4)),
            "outside"
        );
        assert_eq!(
            kind(read_bytes_inside(&root, Path::new("linked/none.json"), 4)),
            "outside"
        );
        assert_eq!(
            kind(read_bytes_inside(&root, Path::new("linked/none/a.json"), 4)),
            "outside"
        );
        assert_eq!(
            kind(read_bytes_inside(
                &root,
                Path::new("sub/dangling-dir/a.json"),
                4
            )),
            "outside"
        );
        assert_eq!(
            kind(read_bytes_inside(&root, Path::new("dangling.json"), 4)),
            "outside"
        );
        assert_eq!(
            kind(read_bytes_inside(&root, Path::new("sub"), 4)),
            "not regular"
        );
        assert_eq!(
            kind(read_bytes_inside(&root, Path::new("big.json"), 4)),
            "too large"
        );
    }

    /// A read root of a root that does not resolve refuses each read.
    #[test]
    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
    fn a_read_root_that_does_not_resolve_refuses_each_read() {
        let dir = tempfile::tempdir().unwrap();
        let reader = ReadRoot::new(&dir.path().join("none"));
        let err = reader.read_bytes(Path::new("a.json"), 16).unwrap_err();
        assert!(err.is_not_found(), "{err:?}");
        assert!(!reader.is_inside(Path::new("a.json")));
    }

    #[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 { .. }));
    }
}