Skip to main content

sanitize_path

Function sanitize_path 

pub fn sanitize_path(path: impl AsRef<Path>) -> Result<PathBuf, UnsafePathError>
Expand description

Validate path and return a cleaned, lexically-equivalent path that is safe from “dot-dot” traversal.

. (current-dir) components are dropped and .. (parent-dir) components are rejected (UnsafePathError::ParentDir). Components that smuggle in a path prefix (e.g. a Windows drive letter in foo/c:/bar) and reserved device names (Windows CON, NUL, COM1, …) are rejected too.

Absolute paths are permitted: a leading root/prefix is preserved. The guarantee is only that the result never points above its own starting point. When the path must stay within a known directory, use safe_open_in / OpenOptions::jail, which additionally reject absolute paths and resolve symlinks against the root.

Note: this works on already-decoded paths. Percent-decoding (e.g. of an HTTP target like %2e%2e%2f) is the caller’s responsibility and must happen before calling this function.