Skip to main content

Module fs

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_open opens 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::jail additionally 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 -> InvalidInput

Structs§

OpenOptions
Options to open a file with path-traversal protection.

Enums§

SymlinkPolicy
How symbolic links are treated when opening a file confined to a root directory via OpenOptions::jail.
UnsafePathError
Error returned when a path is rejected as unsafe.

Functions§

is_reserved_device_name
Whether name matches a reserved Windows device name (e.g. CON, NUL, COM1, LPT9), independent of the current platform.
safe_open
Open path read-only with path-traversal protection.
safe_open_in
Open a file read-only, confined to within the trusted directory root.
sanitize_path
Validate path and return a cleaned, lexically-equivalent path that is safe from “dot-dot” traversal.
sanitize_relative_path
Like sanitize_path but additionally requires the path to be relative, rejecting absolute paths and drive/UNC prefixes (UnsafePathError::Absolute).