1use std::fmt;
13use std::io::Read;
14use std::path::{Path, PathBuf};
15
16use crate::link_walk::{Stop, resolve_below};
17
18pub const DEFAULT_MAX_READ_BYTES: u64 = 16 * 1024 * 1024;
25
26#[derive(Debug)]
31pub enum ReadRefusal {
32 OutsideRoot {
34 path: PathBuf,
36 root: PathBuf,
38 },
39 NotRegularFile {
41 path: PathBuf,
43 },
44 TooLarge {
46 path: PathBuf,
48 max_bytes: u64,
50 },
51 Io {
53 path: PathBuf,
55 source: std::io::Error,
57 },
58}
59
60impl ReadRefusal {
61 #[must_use]
63 pub fn path(&self) -> &Path {
64 match self {
65 Self::OutsideRoot { path, .. }
66 | Self::NotRegularFile { path }
67 | Self::TooLarge { path, .. }
68 | Self::Io { path, .. } => path,
69 }
70 }
71
72 #[must_use]
76 pub fn is_not_found(&self) -> bool {
77 matches!(self, Self::Io { source, .. } if source.kind() == std::io::ErrorKind::NotFound)
78 }
79}
80
81impl fmt::Display for ReadRefusal {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 match self {
84 Self::OutsideRoot { path, root } => write!(
85 f,
86 "refusing to read {}: it resolves to a location outside {}",
87 path.display(),
88 root.display()
89 ),
90 Self::NotRegularFile { path } => write!(
91 f,
92 "refusing to read {}: it is not a regular file",
93 path.display()
94 ),
95 Self::TooLarge { path, max_bytes } => write!(
96 f,
97 "refusing to read {}: it is larger than {max_bytes} bytes",
98 path.display()
99 ),
100 Self::Io { path, source } => {
101 write!(f, "cannot read {}: {source}", path.display())
102 }
103 }
104 }
105}
106
107impl std::error::Error for ReadRefusal {
108 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
109 match self {
110 Self::Io { source, .. } => Some(source),
111 _ => None,
112 }
113 }
114}
115
116#[must_use]
126pub fn is_inside_root(root: &Path, path: &Path) -> bool {
127 let Ok(canonical_root) = canonicalize(root) else {
128 return false;
129 };
130 resolve_below(root, &canonical_root, path).is_ok()
131}
132
133pub fn read_bytes_inside(root: &Path, path: &Path, max_bytes: u64) -> Result<Vec<u8>, ReadRefusal> {
141 let canonical_root = canonicalize(root).map_err(|source| ReadRefusal::Io {
142 path: path.to_path_buf(),
143 source,
144 })?;
145 read_bytes_in(root, &canonical_root, path, max_bytes, |dir| {
146 canonicalize(dir).ok()
147 })
148}
149
150#[derive(Debug)]
158pub struct ReadRoot {
159 root: PathBuf,
160 canonical: Result<PathBuf, std::io::ErrorKind>,
161 dirs: std::cell::RefCell<rustc_hash::FxHashMap<PathBuf, Option<PathBuf>>>,
162}
163
164impl ReadRoot {
165 #[must_use]
167 pub fn new(root: &Path) -> Self {
168 Self {
169 root: root.to_path_buf(),
170 canonical: canonicalize(root).map_err(|error| error.kind()),
171 dirs: std::cell::RefCell::default(),
172 }
173 }
174
175 pub fn read_bytes(&self, path: &Path, max_bytes: u64) -> Result<Vec<u8>, ReadRefusal> {
181 let canonical_root = self.canonical.as_ref().map_err(|kind| ReadRefusal::Io {
182 path: path.to_path_buf(),
183 source: std::io::Error::from(*kind),
184 })?;
185 read_bytes_in(&self.root, canonical_root, path, max_bytes, |dir| {
186 self.dirs
187 .borrow_mut()
188 .entry(dir.to_path_buf())
189 .or_insert_with(|| canonicalize(dir).ok())
190 .clone()
191 })
192 }
193
194 pub fn read_to_string(&self, path: &Path, max_bytes: u64) -> Result<String, ReadRefusal> {
201 let bytes = self.read_bytes(path, max_bytes)?;
202 into_string(path, bytes)
203 }
204
205 #[must_use]
207 pub fn is_inside(&self, path: &Path) -> bool {
208 let Ok(canonical_root) = &self.canonical else {
209 return false;
210 };
211 let joined = self.root.join(path);
212 if joined
214 .symlink_metadata()
215 .is_err_and(|error| error.kind() == std::io::ErrorKind::NotFound)
216 {
217 return false;
218 }
219 resolve_below(&self.root, canonical_root, path).is_ok()
220 }
221}
222
223fn read_bytes_in(
227 root: &Path,
228 canonical_root: &Path,
229 path: &Path,
230 max_bytes: u64,
231 resolve_dir: impl FnOnce(&Path) -> Option<PathBuf>,
232) -> Result<Vec<u8>, ReadRefusal> {
233 let joined = root.join(path);
234 let io = |source: std::io::Error| ReadRefusal::Io {
235 path: path.to_path_buf(),
236 source,
237 };
238 let outside = || ReadRefusal::OutsideRoot {
239 path: path.to_path_buf(),
240 root: root.to_path_buf(),
241 };
242 if let Some(source) = missing_inside(root, canonical_root, &joined, resolve_dir) {
243 return Err(io(source));
244 }
245 let resolved = match resolve_below(root, canonical_root, path) {
246 Ok(resolved) => resolved,
247 Err(Stop::Outside | Stop::Missing { in_link: true }) => return Err(outside()),
248 Err(Stop::Missing { in_link: false }) => {
249 return Err(io(std::io::ErrorKind::NotFound.into()));
250 }
251 Err(Stop::Unreadable(source)) => return Err(io(source)),
252 };
253 read_resolved(path, &resolved, max_bytes)
254}
255
256fn missing_inside(
265 root: &Path,
266 canonical_root: &Path,
267 joined: &Path,
268 resolve_dir: impl FnOnce(&Path) -> Option<PathBuf>,
269) -> Option<std::io::Error> {
270 use std::path::Component;
271 let error = joined.symlink_metadata().err()?;
272 if error.kind() != std::io::ErrorKind::NotFound {
273 return None;
274 }
275 let mut missing = joined;
276 loop {
277 if !matches!(missing.components().next_back(), Some(Component::Normal(_))) {
278 return None;
279 }
280 let dir = missing.parent()?;
281 if dir == root {
282 return Some(error);
283 }
284 match dir.symlink_metadata() {
285 Err(dir_error) if dir_error.kind() == std::io::ErrorKind::NotFound => missing = dir,
286 Err(_) => return None,
287 Ok(_) => {
288 let inside = resolve_dir(dir).is_some_and(|dir| dir.starts_with(canonical_root));
289 return inside.then_some(error);
290 }
291 }
292 }
293}
294
295fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
298 #[cfg(any(test, feature = "testing"))]
299 CANONICALIZE_CALLS.with(|calls| calls.set(calls.get() + 1));
300 std::fs::canonicalize(path)
301}
302
303#[cfg(any(test, feature = "testing"))]
304std::thread_local! {
305 static CANONICALIZE_CALLS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
306}
307
308#[cfg(any(test, feature = "testing"))]
311#[must_use]
312pub fn canonicalize_calls() -> u64 {
313 CANONICALIZE_CALLS.with(std::cell::Cell::get)
314}
315
316pub fn read_to_string_inside(
323 root: &Path,
324 path: &Path,
325 max_bytes: u64,
326) -> Result<String, ReadRefusal> {
327 let bytes = read_bytes_inside(root, path, max_bytes)?;
328 into_string(path, bytes)
329}
330
331pub fn read_to_string_bounded(path: &Path, max_bytes: u64) -> Result<String, ReadRefusal> {
340 let bytes = read_resolved(path, path, max_bytes)?;
341 into_string(path, bytes)
342}
343
344pub fn read_bytes_bounded(path: &Path, max_bytes: u64) -> Result<Vec<u8>, ReadRefusal> {
351 read_resolved(path, path, max_bytes)
352}
353
354#[must_use]
358pub fn is_bounded_regular_file(path: &Path, max_bytes: u64) -> bool {
359 std::fs::metadata(path).is_ok_and(|meta| meta.is_file() && meta.len() <= max_bytes)
360}
361
362fn read_resolved(path: &Path, resolved: &Path, max_bytes: u64) -> Result<Vec<u8>, ReadRefusal> {
363 let io = |source: std::io::Error| ReadRefusal::Io {
364 path: path.to_path_buf(),
365 source,
366 };
367 let not_regular = || ReadRefusal::NotRegularFile {
368 path: path.to_path_buf(),
369 };
370 let too_large = || ReadRefusal::TooLarge {
371 path: path.to_path_buf(),
372 max_bytes,
373 };
374 if !std::fs::metadata(resolved).map_err(io)?.is_file() {
378 return Err(not_regular());
379 }
380 let file = open_without_blocking(resolved).map_err(io)?;
381 let meta = file.metadata().map_err(io)?;
382 if !meta.is_file() {
383 return Err(not_regular());
384 }
385 if meta.len() > max_bytes {
386 return Err(too_large());
387 }
388 let mut bytes = Vec::new();
389 file.take(max_bytes.saturating_add(1))
392 .read_to_end(&mut bytes)
393 .map_err(io)?;
394 if bytes.len() as u64 > max_bytes {
395 return Err(too_large());
396 }
397 Ok(bytes)
398}
399
400fn open_without_blocking(path: &Path) -> std::io::Result<std::fs::File> {
403 let mut options = std::fs::OpenOptions::new();
404 options.read(true);
405 #[cfg(unix)]
406 {
407 use std::os::unix::fs::OpenOptionsExt;
408 options.custom_flags(rustix::fs::OFlags::NONBLOCK.bits().cast_signed());
409 }
410 options.open(path)
411}
412
413fn into_string(path: &Path, bytes: Vec<u8>) -> Result<String, ReadRefusal> {
414 String::from_utf8(bytes).map_err(|_| ReadRefusal::Io {
415 path: path.to_path_buf(),
416 source: std::io::Error::new(
417 std::io::ErrorKind::InvalidData,
418 "stream did not contain valid UTF-8",
419 ),
420 })
421}
422
423#[cfg(test)]
424mod tests {
425 use super::*;
426
427 #[test]
430 #[cfg(unix)]
431 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
432 fn the_open_does_not_wait_for_a_fifo_and_checks_the_opened_file() {
433 let dir = tempfile::tempdir().unwrap();
434 let fifo = dir.path().join("pipe.json");
435 let status = std::process::Command::new("mkfifo")
436 .arg(&fifo)
437 .status()
438 .unwrap();
439 assert!(status.success());
440 let file = open_without_blocking(&fifo).unwrap();
441 assert!(!file.metadata().unwrap().is_file());
442 assert!(matches!(
443 read_to_string_bounded(&fifo, 16),
444 Err(ReadRefusal::NotRegularFile { .. })
445 ));
446 }
447
448 #[test]
449 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
450 fn reads_a_regular_file_inside_the_root() {
451 let dir = tempfile::tempdir().unwrap();
452 std::fs::write(dir.path().join("a.json"), "{}").unwrap();
453 let text = read_to_string_inside(dir.path(), Path::new("a.json"), 16).unwrap();
454 assert_eq!(text, "{}");
455 let abs = dir.path().join("a.json");
456 assert_eq!(read_bytes_inside(dir.path(), &abs, 16).unwrap(), b"{}");
457 assert!(is_inside_root(dir.path(), &abs));
458 }
459
460 #[test]
461 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
462 fn bounded_bytes_read_takes_regular_files_within_the_limit_only() {
463 let dir = tempfile::tempdir().unwrap();
464 let file = dir.path().join("a.json");
465 std::fs::write(&file, "{}").unwrap();
466 assert_eq!(read_bytes_bounded(&file, 16).unwrap(), b"{}");
467 assert!(is_bounded_regular_file(&file, 16));
468 assert!(read_bytes_bounded(&file, 1).is_err());
469 assert!(!is_bounded_regular_file(&file, 1));
470 assert!(read_bytes_bounded(dir.path(), 16).is_err());
471 assert!(!is_bounded_regular_file(dir.path(), 16));
472 }
473
474 #[test]
475 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
476 fn refuses_a_file_over_the_limit() {
477 let dir = tempfile::tempdir().unwrap();
478 std::fs::write(dir.path().join("a.json"), "0123456789").unwrap();
479 let err = read_to_string_inside(dir.path(), Path::new("a.json"), 4).unwrap_err();
480 assert!(matches!(err, ReadRefusal::TooLarge { max_bytes: 4, .. }));
481 assert!(!err.to_string().contains("0123"));
482 let err = read_to_string_bounded(&dir.path().join("a.json"), 4).unwrap_err();
483 assert!(matches!(err, ReadRefusal::TooLarge { .. }));
484 }
485
486 #[test]
487 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
488 fn refuses_a_directory() {
489 let dir = tempfile::tempdir().unwrap();
490 std::fs::create_dir(dir.path().join("sub")).unwrap();
491 let err = read_to_string_inside(dir.path(), Path::new("sub"), 16).unwrap_err();
492 assert!(matches!(err, ReadRefusal::NotRegularFile { .. }));
493 }
494
495 #[test]
496 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
497 fn refuses_a_missing_file_and_reports_not_found() {
498 let dir = tempfile::tempdir().unwrap();
499 let err = read_to_string_inside(dir.path(), Path::new("none.json"), 16).unwrap_err();
500 assert!(err.is_not_found());
501 assert!(!is_inside_root(dir.path(), Path::new("none.json")));
502 assert!(!is_inside_root(&dir.path().join("no-root"), Path::new("x")));
503 }
504
505 #[test]
506 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
507 fn refuses_a_dot_dot_path_that_leaves_the_root() {
508 let outer = tempfile::tempdir().unwrap();
509 let root = outer.path().join("project");
510 std::fs::create_dir(&root).unwrap();
511 std::fs::write(outer.path().join("other.txt"), "content-7531").unwrap();
512 let err = read_to_string_inside(&root, Path::new("../other.txt"), 16).unwrap_err();
513 assert!(matches!(err, ReadRefusal::OutsideRoot { .. }));
514 assert!(!err.to_string().contains("content-7531"));
515 assert!(!is_inside_root(&root, Path::new("../other.txt")));
516 }
517
518 #[cfg(unix)]
522 #[test]
523 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
524 fn refuses_a_link_that_leaves_the_root_and_comes_back() {
525 for middle_exists in [true, false] {
526 let outer = tempfile::tempdir().unwrap();
527 let root = outer.path().join("project");
528 std::fs::create_dir(&root).unwrap();
529 std::fs::write(root.join("real.json"), "{}").unwrap();
530 if middle_exists {
531 std::fs::create_dir(outer.path().join("probe")).unwrap();
532 }
533 std::os::unix::fs::symlink("../probe/../project/real.json", root.join("a.json"))
534 .unwrap();
535 std::os::unix::fs::symlink(
536 outer.path().join("probe/../project/real.json"),
537 root.join("b.json"),
538 )
539 .unwrap();
540 for name in ["a.json", "b.json"] {
541 let path = Path::new(name);
542 assert!(
543 !is_inside_root(&root, path),
544 "{name}, middle exists: {middle_exists}"
545 );
546 assert!(!ReadRoot::new(&root).is_inside(path), "{name}");
547 assert!(
548 matches!(
549 read_bytes_inside(&root, path, 16),
550 Err(ReadRefusal::OutsideRoot { .. })
551 ),
552 "{name}, middle exists: {middle_exists}"
553 );
554 }
555 }
556 }
557
558 #[cfg(unix)]
559 #[test]
560 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
561 fn refuses_a_link_that_leaves_the_root() {
562 let outer = tempfile::tempdir().unwrap();
563 let root = outer.path().join("project");
564 std::fs::create_dir(&root).unwrap();
565 std::fs::write(outer.path().join("other.txt"), "content-7531").unwrap();
566 std::os::unix::fs::symlink(outer.path().join("other.txt"), root.join("a.json")).unwrap();
567 let err = read_to_string_inside(&root, Path::new("a.json"), 16).unwrap_err();
568 assert!(matches!(err, ReadRefusal::OutsideRoot { .. }));
569 assert!(!is_inside_root(&root, Path::new("a.json")));
570 }
571
572 #[cfg(unix)]
573 #[test]
574 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
575 fn allows_a_link_that_stays_inside_the_root() {
576 let dir = tempfile::tempdir().unwrap();
577 std::fs::write(dir.path().join("real.json"), "{}").unwrap();
578 std::os::unix::fs::symlink("real.json", dir.path().join("a.json")).unwrap();
579 let text = read_to_string_inside(dir.path(), Path::new("a.json"), 16).unwrap();
580 assert_eq!(text, "{}");
581 }
582
583 #[cfg(unix)]
584 #[test]
585 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
586 fn refuses_a_dangling_link_as_outside_the_root() {
587 let dir = tempfile::tempdir().unwrap();
588 std::os::unix::fs::symlink("/nonexistent/fallow/target", dir.path().join("a.json"))
589 .unwrap();
590 let err = read_to_string_inside(dir.path(), Path::new("a.json"), 16).unwrap_err();
591 assert!(matches!(err, ReadRefusal::OutsideRoot { .. }), "{err:?}");
592 assert!(!err.is_not_found());
593 std::fs::create_dir(dir.path().join("sub")).unwrap();
594 std::os::unix::fs::symlink("missing-dir", dir.path().join("sub/link")).unwrap();
595 let err = read_to_string_inside(dir.path(), Path::new("sub/link/a.json"), 16).unwrap_err();
596 assert!(matches!(err, ReadRefusal::OutsideRoot { .. }), "{err:?}");
597 }
598
599 #[test]
600 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
601 fn a_missing_file_inside_the_root_stays_not_found() {
602 let dir = tempfile::tempdir().unwrap();
603 std::fs::create_dir(dir.path().join("sub")).unwrap();
604 for path in ["sub/none.json", "sub/../none.json", "none/a.json"] {
605 let err = read_to_string_inside(dir.path(), Path::new(path), 16).unwrap_err();
606 assert!(err.is_not_found(), "{path}: {err:?}");
607 }
608 let err = read_to_string_inside(dir.path(), Path::new("../none.json"), 16).unwrap_err();
609 assert!(matches!(err, ReadRefusal::OutsideRoot { .. }), "{err:?}");
610 }
611
612 #[cfg(unix)]
613 #[test]
614 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
615 fn a_missing_file_through_another_spelling_of_the_root_stays_not_found() {
616 let dir = tempfile::tempdir().unwrap();
617 let root = dir.path().join("real");
618 std::fs::create_dir(&root).unwrap();
619 std::os::unix::fs::symlink(&root, dir.path().join("alias")).unwrap();
620 let path = dir.path().join("alias/none.json");
621 let err = read_to_string_inside(&root, &path, 16).unwrap_err();
622 assert!(err.is_not_found(), "{err:?}");
623 }
624
625 #[test]
628 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
629 fn a_missing_file_inside_the_root_costs_no_prefix_walk() {
630 let dir = tempfile::tempdir().unwrap();
631 std::fs::create_dir(dir.path().join("sub")).unwrap();
632 let before = canonicalize_calls();
633 let err = read_to_string_inside(dir.path(), Path::new("none.json"), 16).unwrap_err();
634 assert!(err.is_not_found(), "{err:?}");
635 assert_eq!(canonicalize_calls() - before, 1);
637
638 let reader = ReadRoot::new(dir.path());
639 let before = canonicalize_calls();
640 for name in [
641 "a.json",
642 "b.json",
643 "sub/a.json",
644 "sub/b.json",
645 "sub/c.json",
646 "none/a.json",
647 "none/deeper/b.json",
648 ] {
649 let err = reader.read_to_string(Path::new(name), 16).unwrap_err();
650 assert!(err.is_not_found(), "{name}: {err:?}");
651 }
652 assert_eq!(canonicalize_calls() - before, 1);
654 }
655
656 #[cfg(unix)]
658 fn kind(result: Result<Vec<u8>, ReadRefusal>) -> String {
659 match result {
660 Ok(bytes) => format!("ok {bytes:?}"),
661 Err(ReadRefusal::OutsideRoot { .. }) => "outside".to_string(),
662 Err(ReadRefusal::NotRegularFile { .. }) => "not regular".to_string(),
663 Err(ReadRefusal::TooLarge { .. }) => "too large".to_string(),
664 Err(ReadRefusal::Io { source, .. }) => format!("io {:?}", source.kind()),
665 }
666 }
667
668 #[cfg(unix)]
671 #[test]
672 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
673 fn a_read_root_gives_the_results_of_the_free_read() {
674 let outer = tempfile::tempdir().unwrap();
675 let root = outer.path().join("project");
676 let elsewhere = outer.path().join("elsewhere");
677 std::fs::create_dir_all(root.join("sub")).unwrap();
678 std::fs::create_dir(&elsewhere).unwrap();
679 std::fs::write(root.join("own.json"), "{}").unwrap();
680 std::fs::write(outer.path().join("other.json"), "{}").unwrap();
681 std::fs::write(root.join("big.json"), "0123456789").unwrap();
682 let link = |target: &Path, name: &str| {
683 std::os::unix::fs::symlink(target, root.join(name)).unwrap();
684 };
685 link(&outer.path().join("other.json"), "out.json");
686 link(&elsewhere, "linked");
687 link(Path::new("/nonexistent/fallow/target"), "dangling.json");
688 link(Path::new("missing-dir"), "sub/dangling-dir");
689 link(Path::new("own.json"), "inner.json");
690 link(Path::new("/dev/zero"), "zero.json");
691 let reader = ReadRoot::new(&root);
692 let paths = [
693 "own.json",
694 "none.json",
695 "big.json",
696 "sub",
697 "sub/none.json",
698 "sub/../none.json",
699 "none/a.json",
700 "none/deeper/a.json",
701 "sub/none/a.json",
702 "linked/none/a.json",
703 "../none.json",
704 "../other.json",
705 "out.json",
706 "linked/none.json",
707 "linked/../other.json",
708 "dangling.json",
709 "sub/dangling-dir/a.json",
710 "inner.json",
711 "zero.json",
712 "own.json/a.json",
713 ];
714 let canonical = std::fs::canonicalize(&root).unwrap();
715 let absolute = [
716 canonical.join("own.json"),
717 canonical.join("none.json"),
718 canonical.join("none/a.json"),
719 canonical.join("out.json"),
720 canonical.join("linked/none.json"),
721 ];
722 let paths = paths
723 .iter()
724 .map(Path::new)
725 .chain(absolute.iter().map(PathBuf::as_path));
726 for path in paths {
727 let free = kind(read_bytes_inside(&root, path, 4));
728 assert_eq!(kind(reader.read_bytes(path, 4)), free, "{}", path.display());
729 assert_eq!(
730 reader.is_inside(path),
731 is_inside_root(&root, path),
732 "{}",
733 path.display()
734 );
735 }
736 assert_eq!(
737 kind(read_bytes_inside(&root, Path::new("out.json"), 4)),
738 "outside"
739 );
740 assert_eq!(
741 kind(read_bytes_inside(&root, Path::new("linked/none.json"), 4)),
742 "outside"
743 );
744 assert_eq!(
745 kind(read_bytes_inside(&root, Path::new("linked/none/a.json"), 4)),
746 "outside"
747 );
748 assert_eq!(
749 kind(read_bytes_inside(
750 &root,
751 Path::new("sub/dangling-dir/a.json"),
752 4
753 )),
754 "outside"
755 );
756 assert_eq!(
757 kind(read_bytes_inside(&root, Path::new("dangling.json"), 4)),
758 "outside"
759 );
760 assert_eq!(
761 kind(read_bytes_inside(&root, Path::new("sub"), 4)),
762 "not regular"
763 );
764 assert_eq!(
765 kind(read_bytes_inside(&root, Path::new("big.json"), 4)),
766 "too large"
767 );
768 }
769
770 #[test]
772 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
773 fn a_read_root_that_does_not_resolve_refuses_each_read() {
774 let dir = tempfile::tempdir().unwrap();
775 let reader = ReadRoot::new(&dir.path().join("none"));
776 let err = reader.read_bytes(Path::new("a.json"), 16).unwrap_err();
777 assert!(err.is_not_found(), "{err:?}");
778 assert!(!reader.is_inside(Path::new("a.json")));
779 }
780
781 #[cfg(unix)]
782 #[test]
783 #[cfg_attr(miri, ignore = "file system access is blocked by Miri isolation")]
784 fn refuses_a_device_even_without_a_root_check() {
785 let err = read_to_string_bounded(Path::new("/dev/zero"), 16).unwrap_err();
786 assert!(matches!(err, ReadRefusal::NotRegularFile { .. }));
787 }
788}