use std::io;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct PathValidator {
restrict_root: Option<PathBuf>,
}
impl PathValidator {
#[allow(dead_code)]
pub fn new(restrict_root: Option<PathBuf>) -> io::Result<Self> {
let restrict_root = match restrict_root {
Some(root) => {
let canonical = root.canonicalize()?;
Some(canonical)
}
None => None,
};
Ok(PathValidator { restrict_root })
}
#[allow(dead_code)]
pub fn validate_path(&self, path: &Path) -> io::Result<PathBuf> {
let canonical = path.canonicalize()?;
let Some(ref root) = self.restrict_root else {
return Ok(canonical);
};
if canonical.starts_with(root) {
Ok(canonical)
} else {
Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!(
"Path '{}' escapes restricted root '{}'",
path.display(),
root.display()
),
))
}
}
#[allow(dead_code)]
pub fn would_be_valid(&self, path: &Path) -> bool {
let Some(ref root) = self.restrict_root else {
return true;
};
let abs_path = if path.is_relative() {
std::env::current_dir()
.ok()
.map(|cwd| cwd.join(path))
.unwrap_or_else(|| path.to_path_buf())
} else {
path.to_path_buf()
};
abs_path.starts_with(root)
}
#[allow(dead_code)]
pub fn restrict_root(&self) -> Option<&Path> {
self.restrict_root.as_deref()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::env;
#[test]
fn test_no_restriction() {
let validator = PathValidator::new(None).unwrap();
let current_dir = env::current_dir().unwrap();
assert!(validator.validate_path(¤t_dir).is_ok());
}
#[test]
fn test_with_restriction() {
let current_dir = env::current_dir().unwrap();
let validator = PathValidator::new(Some(current_dir.clone())).unwrap();
assert!(validator.validate_path(¤t_dir).is_ok());
if let Some(parent) = current_dir.parent() {
assert!(validator.validate_path(parent).is_err());
}
}
#[test]
fn test_would_be_valid() {
let current_dir = env::current_dir().unwrap();
let validator = PathValidator::new(Some(current_dir.clone())).unwrap();
assert!(validator.would_be_valid(Path::new("src/main.rs")));
assert!(!validator.would_be_valid(Path::new("/etc/passwd")));
}
}