Skip to main content

Module path_security

Module path_security 

Source
Expand description

Hardened file access for untrusted path arguments.

A CLI that opens arbitrary user-supplied paths must defend against a number of classic attacks. This module centralises that policy so the rest of the program never touches the filesystem directly:

  • Path traversal — when a base directory is configured, a .. component is rejected lexically and the fully resolved path is verified to stay inside the base directory.
  • Symlink escapes / TOCTOU — paths are canonicalized (resolving symlinks and ..) before the containment check, and symlinks can be denied outright. The opened file handle’s own metadata is then re-checked (fstat on the descriptor) so the type/size decision is made on the object we actually opened, not on a name that may have been swapped.
  • Non-regular files — directories, devices, FIFOs and sockets are rejected; only regular files are accepted.
  • Resource exhaustion — reads are hard-capped at a configurable byte limit, independent of the size the filesystem metadata claims.

The entry points are PathPolicy::open / PathPolicy::read for files on disk, read_capped for arbitrary readers such as standard input, write_in_dir for capability-scoped writes (via cap-std), and the lexical safe_join primitive for confining attacker-influenced relative paths to a base directory.

Structs§

OpenedFile
A successfully opened, validated input file.
PathPolicy
Policy controlling how input paths are resolved and opened.

Enums§

PathSecurityError
Errors that can occur while securely resolving and opening an input path.

Constants§

DEFAULT_MAX_FILE_SIZE
Default upper bound on the number of bytes read from a single input (64 MiB).

Functions§

read_capped
Read at most limit bytes from reader, erroring if more are available.
safe_join
Lexically join a relative, attacker-influenced candidate onto base, returning None if the candidate would escape base.
write_in_dir
Write bytes to a file named name inside the directory dir, using a capability-scoped cap_std::fs::Dir handle (see skills/rust-path-security.md).