Module fs
Expand description
Filesystem helpers that guard against path-traversal attacks.
Opening files whose path is influenced by untrusted input (an HTTP request
target, a query parameter, a header value, …) is a classic source of
path-traversal vulnerabilities: a request for ../../etc/passwd escapes the
directory the application meant to expose.
This module provides drop-in replacements for [tokio::fs::File::open] and
[tokio::fs::OpenOptions] that reject such paths:
safe_openopens a file read-only after rejecting..traversal, reserved device names and smuggled path prefixes. Use it when the base of the path is trusted but parts of it may be attacker-controlled.safe_open_in/OpenOptions::jailadditionally confine the opened file to a trusted root directory: absolute paths are rejected and symbolic links are resolved so they cannot point outside the root.
The underlying lexical check is exposed as sanitize_path for callers
that want to validate a path without opening it.
§Examples
Reject traversal while serving from a fixed directory:
use rama_core::fs;
// Whatever the request asks for, nothing outside `./public` is reachable.
assert!(fs::safe_open_in("./public", "../../etc/passwd").await.is_err());Open a (possibly absolute) trusted path while still rejecting ..:
use rama_core::fs;
assert!(fs::safe_open("/srv/data/report.bin").await.is_err()); // missing file -> NotFound
assert!(fs::safe_open("/srv/../etc/passwd").await.is_err()); // traversal -> InvalidInputStructs§
- Open
Options - Options to open a file with path-traversal protection.
Enums§
- Symlink
Policy - How symbolic links are treated when opening a file confined to a root
directory via
OpenOptions::jail. - Unsafe
Path Error - Error returned when a path is rejected as unsafe.
Functions§
- is_
reserved_ device_ name - Whether
namematches a reserved Windows device name (e.g.CON,NUL,COM1,LPT9), independent of the current platform. - safe_
open - Open
pathread-only with path-traversal protection. - safe_
open_ in - Open a file read-only, confined to within the trusted directory
root. - sanitize_
path - Validate
pathand return a cleaned, lexically-equivalent path that is safe from “dot-dot” traversal. - sanitize_
relative_ path - Like
sanitize_pathbut additionally requires the path to be relative, rejecting absolute paths and drive/UNC prefixes (UnsafePathError::Absolute).