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 (fstaton 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§
- Opened
File - A successfully opened, validated input file.
- Path
Policy - Policy controlling how input paths are resolved and opened.
Enums§
- Path
Security Error - 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
limitbytes fromreader, erroring if more are available. - safe_
join - Lexically join a relative, attacker-influenced
candidateontobase, returningNoneif the candidate would escapebase. - write_
in_ dir - Write
bytesto a file namednameinside the directorydir, using a capability-scopedcap_std::fs::Dirhandle (seeskills/rust-path-security.md).