pub fn validate_path(path: &Path, base_dir: &Path) -> Result<PathBuf>Expand description
Validate and sanitize a file path to prevent path traversal attacks
This function ensures that:
- The path doesn’t contain “..” sequences (directory traversal)
- The path is not absolute (must be relative)
- The path resolves to a location within the specified base directory
- The path doesn’t contain suspicious patterns
§Arguments
path- The relative path to validatebase_dir- The base directory that the path must resolve within
§Returns
Returns the canonical absolute path if validation succeeds, or an error if validation fails.
§Examples
use path_security::validate_path;
use std::path::Path;
// Safe path - allowed
let safe_path = validate_path(Path::new("safe/file.txt"), base_dir)?;
// Dangerous path - rejected
let result = validate_path(Path::new("../etc/passwd"), base_dir);
assert!(result.is_err());