use std::collections::BTreeMap;
use std::path::{Component, Path, PathBuf};
use crate::error::{BlobError, Result};
pub(crate) fn sanitize_rel_path(path: &str) -> Result<PathBuf> {
if path.is_empty() {
return Err(BlobError::UnsafePath("empty entry path".into()));
}
let p = Path::new(path);
let mut out = PathBuf::new();
for comp in p.components() {
match comp {
Component::Normal(c) => out.push(c),
other => {
return Err(BlobError::UnsafePath(format!(
"unsafe path component {other:?} in entry path {path:?}"
)));
}
}
}
if out.as_os_str().is_empty() {
return Err(BlobError::UnsafePath(format!("empty entry path {path:?}")));
}
Ok(out)
}
pub(crate) fn sanitize_symlink_target(link_rel: &Path, target: &str) -> Result<()> {
let t = Path::new(target);
if t.is_absolute() || t.components().any(|c| matches!(c, Component::Prefix(_))) {
return Err(BlobError::UnsafePath(format!(
"absolute symlink target {target:?}"
)));
}
let mut depth: i64 = link_rel.components().count() as i64 - 1;
for comp in t.components() {
match comp {
Component::Normal(_) => depth += 1,
Component::ParentDir => {
depth -= 1;
if depth < 0 {
return Err(BlobError::UnsafePath(format!(
"symlink target {target:?} escapes the tree root"
)));
}
}
Component::CurDir => {}
other => {
return Err(BlobError::UnsafePath(format!(
"unsafe symlink target component {other:?}"
)));
}
}
}
Ok(())
}
const MAX_SYMLINK_HOPS: u32 = 32;
pub(crate) fn assert_symlinks_confined(links: &BTreeMap<Vec<String>, String>) -> Result<()> {
for (link, target) in links {
let base = &link[..link.len() - 1];
let mut budget = MAX_SYMLINK_HOPS;
resolve_confined(base, target, links, &mut budget, link)?;
}
Ok(())
}
fn resolve_confined(
base: &[String],
target: &str,
links: &BTreeMap<Vec<String>, String>,
budget: &mut u32,
origin: &[String],
) -> Result<Vec<String>> {
if *budget == 0 {
return Err(BlobError::UnsafePath(format!(
"symlink {:?} exceeds {MAX_SYMLINK_HOPS} resolution hops (cycle?)",
origin.join("/")
)));
}
*budget -= 1;
let mut cur = base.to_vec();
for comp in Path::new(target).components() {
match comp {
Component::CurDir => {}
Component::ParentDir => {
if cur.pop().is_none() {
return Err(BlobError::UnsafePath(format!(
"symlink {:?} resolves outside the tree root via {target:?}",
origin.join("/")
)));
}
}
Component::Normal(c) => {
let name = c.to_str().ok_or_else(|| {
BlobError::UnsafePath(format!("non-UTF-8 symlink component in {target:?}"))
})?;
cur.push(name.to_string());
if let Some(next) = links.get(&cur) {
let parent = cur[..cur.len() - 1].to_vec();
cur = resolve_confined(&parent, next, links, budget, origin)?;
}
}
other => {
return Err(BlobError::UnsafePath(format!(
"unsafe symlink target component {other:?} in {target:?}"
)));
}
}
}
Ok(cur)
}
pub(crate) fn assert_parent_within(canonical_root: &Path, path: &Path) -> Result<()> {
let parent = path.parent().unwrap_or(canonical_root);
let canon = parent.canonicalize()?;
if !canon.starts_with(canonical_root) {
return Err(BlobError::UnsafePath(format!(
"entry path {path:?} resolves outside the destination root"
)));
}
Ok(())
}
pub(crate) fn create_dir_confined(root: &Path, rel: &Path) -> Result<std::path::PathBuf> {
let mut cur = root.to_path_buf();
for comp in rel.components() {
cur.push(comp);
match std::fs::symlink_metadata(&cur) {
Ok(meta) if meta.file_type().is_symlink() => {
return Err(BlobError::UnsafePath(format!(
"refusing to traverse symlink at {cur:?} while materializing {rel:?}"
)));
}
Ok(meta) if meta.is_dir() => {}
Ok(_) => {
return Err(BlobError::UnsafePath(format!(
"non-directory in the way at {cur:?} while materializing {rel:?}"
)));
}
Err(_) => {
std::fs::create_dir(&cur)?;
}
}
}
Ok(cur)
}
#[cfg(unix)]
pub(crate) fn fsync_dir(dir: &Path) -> std::io::Result<()> {
std::fs::File::open(dir)?.sync_all()
}
#[cfg(not(unix))]
pub(crate) fn fsync_dir(_dir: &Path) -> std::io::Result<()> {
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rel_paths_sanitized() {
assert_eq!(
sanitize_rel_path("a/b/c.txt").unwrap(),
Path::new("a/b/c.txt")
);
assert_eq!(sanitize_rel_path("x").unwrap(), Path::new("x"));
for bad in ["", "/etc/passwd", "../x", "a/../../x", "a/..", ".", "./"] {
assert!(sanitize_rel_path(bad).is_err(), "should reject {bad:?}");
}
}
#[cfg(unix)]
#[test]
fn confined_dir_creation_refuses_symlinks() {
let root = tempfile::tempdir().unwrap();
let leaf = create_dir_confined(root.path(), Path::new("a/b/c")).unwrap();
assert!(leaf.is_dir());
std::os::unix::fs::symlink(root.path().join("a"), root.path().join("link")).unwrap();
assert!(create_dir_confined(root.path(), Path::new("link/x")).is_err());
std::fs::write(root.path().join("f"), b"x").unwrap();
assert!(create_dir_confined(root.path(), Path::new("f/child")).is_err());
}
#[test]
fn symlink_targets_checked() {
let link = Path::new("sub/link");
assert!(sanitize_symlink_target(link, "hello.txt").is_ok());
assert!(sanitize_symlink_target(link, "../big.bin").is_ok()); assert!(sanitize_symlink_target(link, "../../evil").is_err()); assert!(sanitize_symlink_target(link, "/etc/passwd").is_err());
let root_link = Path::new("link");
assert!(sanitize_symlink_target(root_link, "file").is_ok());
assert!(sanitize_symlink_target(root_link, "../x").is_err());
}
}