is_safe_path

Function is_safe_path 

Source
pub fn is_safe_path(base: &Path, path: &Path) -> bool
Expand description

Checks if a path is safe and doesn’t escape the base directory.

This function prevents directory traversal attacks by ensuring that the resolved path remains within the base directory. It handles both absolute and relative paths, normalizing them before comparison.

§Arguments

  • base - The base directory that should contain the path
  • path - The path to validate (can be absolute or relative)

§Returns

  • true if the path is safe and stays within the base directory
  • false if the path would escape the base directory

§Examples

use agpm_cli::utils::fs::is_safe_path;
use std::path::Path;

let base = Path::new("/home/user/project");

// Safe paths
assert!(is_safe_path(base, Path::new("src/main.rs")));
assert!(is_safe_path(base, Path::new("./config/settings.toml")));

// Unsafe paths (directory traversal)
assert!(!is_safe_path(base, Path::new("../../../etc/passwd")));
assert!(!is_safe_path(base, Path::new("/etc/passwd")));

§Security

This function is essential for preventing directory traversal vulnerabilities when processing user-provided paths. It should be used whenever:

  • Extracting archives or packages
  • Processing configuration files with path references
  • Handling user input that specifies file locations

§Implementation

The function normalizes both paths using normalize_path before comparison, ensuring that path traversal attempts using ../ are properly detected.