Skip to main content

is_safe_path

Function is_safe_path 

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

Checks if a given path is safe to use.

Validates that the provided path does not contain directory traversal attempts or other potential security risks.

§Arguments

  • path - The path to validate

§Returns

  • Ok(true) - If the path is safe to use
  • Ok(false) - If the path contains unsafe elements
  • Err - If path validation fails

§Security

This function prevents directory traversal attacks by:

  • Checking for parent directory references (..) as genuine path components (via Path::components), not a substring match — so a literal .. inside a filename (e.g. notes..final.md) is never a false positive, and no encoding trick produces a false negative.
  • Rejecting any such component unconditionally, whether or not the path currently exists. A prior version of this check only ran for non-existent paths, so a traversal payload that happened to resolve to a real file (e.g. ../../etc/passwd, which exists on every Unix system) skipped the traversal check entirely and fell through to canonicalize(), which succeeds for any real file — silently reporting a genuine traversal attempt as safe.
  • Resolving symbolic links for paths that do exist and pass the component check, surfacing a broken symlink as unsafe.

This function alone does not confine a path to a particular directory tree — a path with no .. components can still resolve (via a symlink) to an arbitrary location. Callers that need that stronger guarantee should also use is_path_within_root.

§Examples

use ssg::fs_ops::is_safe_path;
use std::path::Path;

assert!(is_safe_path(Path::new("safe/path")).unwrap());
assert!(!is_safe_path(Path::new("../escape")).unwrap());