use std::path::{Component, Path, PathBuf};
use soft_canonicalize::soft_canonicalize;
use super::error::{SecurityError, SecurityResult};
fn validate_components(user_path: &str) -> SecurityResult<PathBuf> {
if user_path.is_empty() {
return Err(SecurityError::AbsolutePathNotAllowed);
}
let path = Path::new(user_path);
for component in path.components() {
match component {
Component::ParentDir => return Err(SecurityError::TraversalAttempt),
Component::RootDir | Component::Prefix(_) => {
return Err(SecurityError::AbsolutePathNotAllowed);
}
_ => {}
}
}
Ok(path.to_path_buf())
}
pub struct PathSanitizer {
root: PathBuf,
}
impl PathSanitizer {
pub fn new(root: impl AsRef<Path>) -> std::io::Result<Self> {
let root = soft_canonicalize(root)?;
Ok(PathSanitizer { root })
}
pub fn join(&self, user_path: &str) -> SecurityResult<PathBuf> {
let path = validate_components(user_path)?;
let joined = self.root.join(path);
let parent = joined.parent().unwrap_or(&self.root);
self.ensure_within_root(parent)?;
Ok(joined)
}
pub(crate) fn join_preverified(&self, user_path: &str) -> SecurityResult<PathBuf> {
let path = validate_components(user_path)?;
Ok(self.root.join(path))
}
pub(crate) fn verify_parent(&self, path: &Path) -> SecurityResult<()> {
self.ensure_within_root(path)
}
fn ensure_within_root(&self, path: &Path) -> SecurityResult<()> {
let real = soft_canonicalize(path).map_err(|_| SecurityError::TraversalAttempt)?;
if !real.starts_with(&self.root) {
return Err(SecurityError::TraversalAttempt);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_fuzz::FuzzRng;
use tempfile::TempDir;
#[test]
fn test_join_rejects_absolute() {
let temp = TempDir::new().unwrap();
let sanitizer = PathSanitizer::new(temp.path()).unwrap();
assert!(matches!(
sanitizer.join("/etc/passwd"),
Err(SecurityError::AbsolutePathNotAllowed)
));
}
#[test]
fn test_join_rejects_traversal() {
let temp = TempDir::new().unwrap();
let sanitizer = PathSanitizer::new(temp.path()).unwrap();
assert!(matches!(
sanitizer.join("../../etc/passwd"),
Err(SecurityError::TraversalAttempt)
));
assert!(matches!(
sanitizer.join("sub/../escape.txt"),
Err(SecurityError::TraversalAttempt)
));
assert!(matches!(
sanitizer.join("a/b/../../escape.txt"),
Err(SecurityError::TraversalAttempt)
));
}
#[test]
fn test_join_allows_valid_relative_path() {
let temp = TempDir::new().unwrap();
let sanitizer = PathSanitizer::new(temp.path()).unwrap();
let result = sanitizer.join("subdir/file.txt");
assert!(result.is_ok());
assert!(
result
.unwrap()
.starts_with(soft_canonicalize(temp.path()).unwrap())
);
}
#[test]
fn test_join_allows_dots_in_names() {
let temp = TempDir::new().unwrap();
let sanitizer = PathSanitizer::new(temp.path()).unwrap();
assert!(sanitizer.join("a..b.txt").is_ok());
assert!(sanitizer.join("sub/..hidden").is_ok());
assert!(sanitizer.join("sub/./file.txt").is_ok());
}
#[test]
fn test_join_rejects_empty() {
let temp = TempDir::new().unwrap();
let sanitizer = PathSanitizer::new(temp.path()).unwrap();
assert!(matches!(
sanitizer.join(""),
Err(SecurityError::AbsolutePathNotAllowed)
));
}
#[test]
fn fuzz_join_never_panics_and_stays_contained() {
let temp = TempDir::new().unwrap();
let sanitizer = PathSanitizer::new(temp.path()).unwrap();
let root = soft_canonicalize(temp.path()).unwrap();
let mut rng = FuzzRng::new(0x5A17_1E2E_0F0D_CAFE);
for _ in 0..2_000 {
let s = rng.string(48);
if let Ok(path) = sanitizer.join(&s) {
assert!(path.starts_with(&root), "join({s:?}) escaped: {path:?}");
assert!(
!path.components().any(|c| matches!(c, Component::ParentDir)),
"join({s:?}) introduced a parent component: {path:?}"
);
}
}
}
#[cfg(unix)]
#[test]
fn test_join_rejects_symlink_escape() {
let temp = TempDir::new().unwrap();
let outside = TempDir::new().unwrap();
std::fs::write(outside.path().join("escaped.txt"), b"x").unwrap();
std::os::unix::fs::symlink(outside.path(), temp.path().join("link")).unwrap();
let sanitizer = PathSanitizer::new(temp.path()).unwrap();
assert!(matches!(
sanitizer.join("link/escaped.txt"),
Err(SecurityError::TraversalAttempt)
));
std::os::unix::fs::symlink(temp.path().join("sub"), temp.path().join("link2")).unwrap();
std::fs::create_dir(temp.path().join("sub")).unwrap();
assert!(sanitizer.join("link2/file.txt").is_ok());
}
#[cfg(unix)]
#[test]
fn test_join_rechecks_after_dir_replaced_by_symlink() {
let temp = TempDir::new().unwrap();
let outside = TempDir::new().unwrap();
let sanitizer = PathSanitizer::new(temp.path()).unwrap();
std::fs::create_dir(temp.path().join("a")).unwrap();
assert!(sanitizer.join("a/b.txt").is_ok());
std::fs::remove_dir(temp.path().join("a")).unwrap();
std::os::unix::fs::symlink(outside.path(), temp.path().join("a")).unwrap();
assert!(matches!(
sanitizer.join("a/c.txt"),
Err(SecurityError::TraversalAttempt)
));
}
}