use std::fmt;
use std::io::Read;
use std::path::{Path, PathBuf};
pub const DEFAULT_MAX_READ_BYTES: u64 = 16 * 1024 * 1024;
#[derive(Debug)]
pub enum ReadRefusal {
OutsideRoot {
path: PathBuf,
root: PathBuf,
},
NotRegularFile {
path: PathBuf,
},
TooLarge {
path: PathBuf,
max_bytes: u64,
},
Io {
path: PathBuf,
source: std::io::Error,
},
}
impl ReadRefusal {
#[must_use]
pub fn path(&self) -> &Path {
match self {
Self::OutsideRoot { path, .. }
| Self::NotRegularFile { path }
| Self::TooLarge { path, .. }
| Self::Io { path, .. } => path,
}
}
#[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,
}
}
}
#[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))
}
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()
})
}
#[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 {
#[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(),
}
}
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()
})
}
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)
}
#[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);
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))
}
}
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)
}
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);
}
}
}
}
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) };
}
#[cfg(any(test, feature = "testing"))]
#[must_use]
pub fn canonicalize_calls() -> u64 {
CANONICALIZE_CALLS.with(std::cell::Cell::get)
}
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)
}
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)
}
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)
}
pub fn read_bytes_bounded(path: &Path, max_bytes: u64) -> Result<Vec<u8>, ReadRefusal> {
read_resolved(path, path, max_bytes)
}
#[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,
};
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();
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 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::*;
#[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:?}");
}
#[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:?}");
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:?}");
}
assert_eq!(canonicalize_calls() - before, 1);
}
#[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()),
}
}
#[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"
);
}
#[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 { .. }));
}
}