strict-path
The moment a path string enters your program from outside your code โ an HTTP request, a config file, an archive entry, a database row, an LLM tool call โ reach for strict-path. It pins that string to a directory you chose, so it can't escape via symlinks, encoding tricks, or platform quirks. 19+ real-world CVEs covered.
Prepared statements prevent SQL injection.
strict-pathprevents path injection. Same rule: data from outside never gets to act as structure.
๐ Why String Checking Isn't Enough
You strip .. and check for /. But attackers have a dozen other vectors:
| Attack vector | String filter | strict-path |
|---|---|---|
../../../etc/passwd |
โ Caught (if done right) | โ Blocked |
| Symlink inside boundary โ outside | โ Passes silently | โ Symlink resolved, escape blocked |
Windows 8.3: PROGRA~1 bypasses filter |
โ Passes silently | โ Short name resolved, escape blocked |
NTFS ADS: file.txt:secret:$DATA |
โ Passes silently | โ Blocked (CVE-2025-8088) |
Unicode tricks: ..โ (fraction slash U+2215) |
โ Passes silently | โ Blocked |
| Junction/mount point โ outside boundary | โ Passes silently | โ Resolved & blocked |
| TOCTOU race condition (CVE-2022-21658) | โ No defense | โก Mitigated at validation |
| Null byte injection | โ Truncation varies | โ Blocked |
Mixed separators: ..\../etc |
โ Often missed | โ Normalized & blocked |
How it works: strict-path resolves the path on disk โ follows symlinks, expands short names, normalizes encoding โ then checks whether the resolved path is inside the boundary. If it isn't, you get an Err. The input string is irrelevant. Only where the path actually leads matters.
String-matching libraries maintain lists of dangerous patterns โ .., %2e%2e, %c0%ae (overlong UTF-8), . (HTML entities), full-width Unicode dots, zero-width characters, and dozens more. Every new encoding trick requires a new blocklist entry, and a single miss is a bypass.
strict-path doesn't play that game. It asks the OS to resolve the path, then checks where it landed. URL-encoded %2e%2e isn't decoded โ it's a literal directory name containing percent signs. Overlong UTF-8 sequences, HTML entities, code-page homoglyphs (ยฅโ\ in CP932, โฉโ\ in CP949) โ none of these matter because the OS never interprets them as path separators or traversal sequences. The canonicalized result either falls inside the boundary or it doesn't.
This is the same principle behind SQL prepared statements: instead of escaping every dangerous character (and inevitably missing one), you separate code from data structurally. strict-path separates path resolution from path text, making the entire class of encoding-bypass attacks irrelevant by design.
โก Get Secure in 30 Seconds
[]
= "0.2"
use StrictPath;
// Untrusted input: user upload, API param, config value, AI agent output, archive entry...
let file = with_boundary?
.strict_join?; // Every attack vector above โ Err(PathEscapesBoundary)
let contents = file.read?; // Built-in safe I/O โ stays within the secure API
// Third-party crate needs AsRef<Path>?
process; // &OsStr (implements AsRef<Path>)
If the input resolves outside the boundary โ by any mechanism โ strict_join returns Err.
๐ฏ When to Use What
The trigger is the origin of the path string. Is the string something your code produced, or did it come from outside?
Path/PathBuf(std) โ the string is yours: a hardcoded constant, or assembled entirely from values your own code produced. There's no external input to validate.StrictPathโ the string came from outside (HTTP request, config file, archive entry, DB row, env var, LLM tool call, โฆ) and an escape attempt is an error you want to know about. Log it, deny the request, abort the operation. Silently substituting a different file would hide the problem.VirtualPathโ the string came from outside, and an escape attempt should be clamped. The caller is navigating a sandbox you gave them (their own "/"), and..off the top just lands them back at their root.
Choose StrictPath (โ 90% of cases):
- Archive extraction, config loading
- File uploads to shared storage (admin panels, CMS assets, single-tenant apps)
- LLM / AI agent file operations
- Shared system resources (logs, cache, assets)
- Any case where escaping a path boundary is considered malicious.
Choose VirtualPath (โ 10% of cases):
- Multi-tenant file storage (SaaS per-user directories, isolated views)
- Malware analysis sandboxes
- Container-like plugins
- Any case where you want freedom of operation under complete isolation.
- Not a sandbox or chroot โ your process still has whatever filesystem access the OS grants it.
- Not a replacement for filesystem permissions, SELinux/AppArmor, or
openat2(RESOLVE_BENEATH). Compose with those where you have them. - Not a URL or shell-argument sanitizer โ different injection class, different tool.
- Not a performance-tuned lexical normalizer โ canonicalization touches the disk. If every path is a hardcoded constant and you need nanoseconds,
std::pathis the right tool.
๐ Tutorial: Chapter 1 โ The Basic Promise โ ยท ๐ Complete Decision Matrix โ ยท ๐ More Examples โ
๐ Real-World Examples
Archive Extraction (Zip Slip Prevention)
PathBoundary in the signature names the legal boundary for this operation โ the directory that joined paths must stay inside.
use PathBoundary;
// Prevents CVE-2018-1000178 (Zip Slip) automatically (https://snyk.io/research/zip-slip-vulnerability)
The equivalent of
PathBoundaryforVirtualPathis theVirtualRoottype.
Multi-Tenant Isolation
use VirtualRoot;
// No path-traversal or symlinks can escape the tenant root.
// Everything is clamped to the virtual root, including symlink resolutions.
๐ง Compile-Time Safety with Markers
Tag a StrictPath with a marker type so a function can only accept paths from the boundary you meant. Mixing them up is a compile error:
use ;
;
;
let assets = try_new_create?;
let uploads = try_new_create?;
let css: = assets.strict_join?;
let avatar: = uploads.strict_join?;
serve_public_asset; // โ
OK โ PublicAssets matches
// serve_public_asset(&avatar); // โ Compile error โ UserUploads is not PublicAssets
๐ Complete Marker Tutorial โ โ authorization patterns, permission matrices,
change_marker()usage.
๐งฐ What You Get Beyond Path Validation
- ๐ก๏ธ Built-in I/O โ
read(),write(),create_dir_all(),read_dir()โ no need to drop tostd::fs - ๐ Compile-time markers โ
StrictPath<UserUploads>vsStrictPath<SystemConfig>can't be mixed up - ๐ Thread-safe โ all types are
Send + Sync; share across threads and async tasks - ๐ค LLM-ready โ doc comments and context files designed for AI agents with function calling
This crate combines Rust's type system with Python's "one obvious way to do it" philosophy to build an API where LLMs and humans naturally reach for the correct pattern โ wrong code either doesn't compile, or the compiler tells you exactly what to do instead.
- No
AsRef<Path>, noDerefโ implementing either would let anything call.join()on aStrictPathand build a new path that skips boundary validation. Not implementing them closes that accidental path. interop_path()returns&OsStr, not&Pathโ&Pathcarries.join()and.parent(), which would let callers build new unvalidated paths from a validated one.&OsStrdoesn't; it's a one-way exit to third-party APIs with no accidental re-entry into path manipulation.- One method per operation โ there is a single entry point for each operation (e.g.
strict_joinfor joining). No aliases, no convenience wrappers, no "which one is the secure version?". The wrong-overload failure mode doesn't exist because there are no overloads. #[must_use]with instructions โ themust_usemessages don't just say "unused Result", they say what to do (e.g. handle the result to detect traversal). When a caller โ human or model โ loops on compiler output, the message itself teaches the API.- Doc comments explain why, not just what โ non-trivial functions document what attack the check prevents or what invariant it enforces, so a reader working from source alone has the reasoning on hand.
๐ Security Methodology โ ยท ๐ Built-in I/O Methods โ ยท ๐ Anti-Patterns โ
๐ Zero Idle Dependencies
Every dependency in the default tree earns its place by closing a specific gap in cross-platform path resolution. Each is covered by cargo audit in CI, and the canonicalization engine has direct tests against the CVE payloads listed above.
| Crate | Platforms | Security role |
|---|---|---|
soft-canonicalize |
All | Canonicalization engine โ symlink resolution, 8.3 short-name expansion, cycle detection, null-byte rejection. Maintained as part of this project. |
dunce |
Windows | Strips \\?\ / \\.\ verbatim prefixes via std::path::Prefix pattern matching โ no lossy UTF-8 round-trip, refuses to strip when unsafe (reserved names, >260 chars, trailing dots). Zero transitive deps. |
junction |
Windows (opt-in junctions feature) |
NTFS junction creation and inspection for built-in junction helpers. |
On Unix the total runtime tree is 2 crates (soft-canonicalize + proc-canonicalize). On Windows it adds dunce (zero transitive deps). No idle dependencies โ if a crate is in the tree, it has a security job.
soft-canonicalize= low-level path resolution engine (returnsPathBufโ unchecked against a boundary)strict-path= higher-level API on top of it: returnsStrictPath<Marker>, which carries a checked boundary and a compile-time marker so paths from different trust zones can't be passed to the same function by mistake
๐ Ecosystem Integration
Compose with standard Rust crates for complete solutions:
| Integration | Purpose | Guide |
|---|---|---|
| tempfile | Secure temp directories | Guide |
| dirs | OS standard directories | Guide |
| app-path | Application directories | Guide |
| serde | Config bootstrap | Guide |
| Axum | Web server extractors | Tutorial |
| Archives | ZIP / TAR extraction | Guide |
Our doc comments and LLM_CONTEXT_FULL.md are designed for LLMs with function calling โ enabling AI agents to use this crate safely for file operations.
LLM agent prompt (copy/paste):
Fetch and follow this reference (single source of truth):
https://github.com/DK26/strict-path-rs/blob/main/LLM_CONTEXT_FULL.md
Context7 style:
Fetch and follow this reference (single source of truth):
https://github.com/DK26/strict-path-rs/blob/main/LLM_CONTEXT.md
๐ Learn More
๐ API Docs ยท ๐ User Guide ยท ๐ Anti-Patterns ยท ๐ Security Methodology ยท ๐งญ Canonicalized vs Lexical ยท ๐ ๏ธ soft-canonicalize
MSRV: Rust 1.76 ยท Releases: CHANGELOG.md
๐ License
MIT OR Apache-2.0