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) = std::fs::canonicalize(root) else {
return false;
};
std::fs::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 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)
}
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)
}
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 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();
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 { .. }));
}
}