pub fn validate_path(
base_path: &Path,
target_path: &Path,
) -> Result<PathBuf, ToolError>Expand description
Validates that a path is within the base directory, preventing directory traversal attacks.
This function is the security foundation for all filesystem tools. It ensures that
user-provided paths cannot escape the configured base directory, even when using
tricks like .. components, absolute paths, or symlinks.
§Arguments
base_path- The root directory that all paths must stay withintarget_path- The user-provided path to validate (relative or absolute)
§Returns
Ok(PathBuf)- The validated path, canonicalized if the file existsErr(ToolError::PathValidation)- If the path escapes the base directory
§Security Properties
- Symlink resolution: Symlinks are resolved via canonicalization, so a symlink
pointing outside
base_pathwill be rejected - Parent traversal: Paths like
foo/../../../etcare caught after canonicalization - Absolute paths: Absolute paths outside
base_pathare rejected - Non-existent paths: For paths that don’t exist yet (e.g., for write operations), the nearest existing ancestor is validated instead
§Example
use mixtape_tools::filesystem::validate_path;
use std::path::Path;
let base = Path::new("/home/user/documents");
// Relative path within base - OK
let result = validate_path(base, Path::new("report.txt"));
// Returns Ok with resolved path
// Traversal attempt - REJECTED
let result = validate_path(base, Path::new("../../../etc/passwd"));
assert!(result.is_err());
// Absolute path outside base - REJECTED
let result = validate_path(base, Path::new("/etc/passwd"));
assert!(result.is_err());