validate_path

Function validate_path 

Source
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:

  1. The path doesn’t contain “..” sequences (directory traversal)
  2. The path is not absolute (must be relative)
  3. The path resolves to a location within the specified base directory
  4. The path doesn’t contain suspicious patterns

§Arguments

  • path - The relative path to validate
  • base_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());