strict-path
📚 Complete Guide & Examples | 📖 API Docs | 🧭 Choosing Canonicalized vs Lexical Solution
Note: Our doc comments and
LLM_API_REFERENCE.mdare designed for LLMs with function calling—so an AI can use this crate safely and correctly for file and path operations.
More than path comparisons: full, cross‑platform path security with type‑level guarantees.
This crate is not a thin wrapper around Path or a naive string comparison.
It performs full normalization, canonicalization, and boundary enforcement with
symlink/junction handling, Windows‑specific edge cases (8.3 short names, UNC,
verbatim prefixes, ADS), and robust encoding/normalization behavior across
platforms. The type system encodes these guarantees: if a StrictPath<Marker>
exists, it’s already proven to be inside its allowed boundary — not by hope,
but by construction.
Quick start
"If you can read this, you passed the PathBoundary checkpoint."
use ;
// Strict system path rooted at ./data
let alice_file = with_boundary?
.strict_join?;
// Virtual view rooted at ./public (displays as "/...")
let logo_file = with_root?
.virtual_join?;
The Type-State Police have set up PathBoundary checkpoints
because your LLM is running wild
🚨 One Line of Code Away from Disaster
"One does not simply walk into /etc/passwd."
// ❌ This single line can destroy your server
write?; // user_input = "../../../etc/passwd"
// ✅ This single line makes it mathematically impossible
with_boundary?
.strict_join?
.write?;
The Reality: Every web server, LLM agent, and file processor faces the same vulnerability. One unvalidated path from user input, config files, or AI responses can grant attackers full filesystem access.
The Solution: Comprehensive path security with mathematical guarantees — including symlink safety, Windows path quirks, and encoding pitfalls — not just string checks.
Analogy:
StrictPathis to paths what a prepared statement is to SQL.
- The boundary/root you create is like preparing a statement: it encodes the policy (what’s allowed).
- The untrusted filename or path segment is like a bound parameter: it’s validated/clamped safely via
strict_join/virtual_join.- The API makes injection attempts inert: hostile inputs can’t escape the boundary, just like SQL parameters can’t change the query.
🛡️ How We Solve The Entire Problem Class
"Symlinks: the ninja assassins of your filesystem."
strict-path isn't just validation—it's a complete solution to path security:
- 🔧
soft-canonicalizefoundation: Heavily tested against 19+ globally known path-related CVEs - 🚫 Hacky string rejection: Advanced pattern detection blocks encoding tricks and malformed inputs
- 📐 Mathematical correctness: Rust's type system provides compile-time proof of path boundaries
- 👁️ Explicit operations: Method names like
strict_join()make security violations visible in code review - 🤖 LLM-aware design: Built specifically for untrusted AI-generated paths and modern threat models
- 🔗 Symlink resolution: Safe handling of symbolic links with cycle detection and boundary enforcement
- ⚡ Dual protection modes: Choose Strict (validate & reject) or Virtual (clamp & contain) based on your use case
- 🏗️ Battle-tested architecture: Prototyped and refined across real-world production systems
- 🎯 Zero-allocation interop: Seamless integration with existing
std::pathecosystems
Recently Addressed CVEs
- CVE-2025-8088 (WinRAR ADS): NTFS Alternate Data Stream traversal prevention
- CVE-2022-21658 (TOCTOU): Race condition protection during path resolution
- CVE-2019-9855, CVE-2020-12279, CVE-2017-17793: Windows 8.3 short name vulnerabilities
Your security audit becomes: "We use strict-path for comprehensive path security." ✅
⚡ Get Secure in 30 Seconds
[]
= "0.1.0-beta.1"
use StrictPath;
// 1. Create a boundary (your security perimeter)
// Use sugar for simple flows; switch to PathBoundary when you need reusable policy
let safe_root = with_boundary?;
// 2. ANY external input becomes safe
let safe_path = safe_root.strict_join?; // Attack = Error
// 3. Use normal file operations - guaranteed secure
safe_path.write?;
let info = safe_path.metadata?; // Inspect filesystem metadata when needed
safe_path.remove_file?; // Remove when cleanup is required
That's it. No complex validation logic. No CVE research. No security expertise required.
🧠 Type-System Guarantees in Signatures
"Marker types: because your code deserves a secret identity."
Use marker types in your function signatures to encode policy and prevent mix-ups across storage domains. The compiler enforces that only the correct paths reach each function.
Example A: StrictPath with markers
use ;
; // CSS, JS, images
; // Uploaded documents
// Create type-safe boundaries (policy)
let public_assets_root = try_new?;
let user_uploads_root = try_new?;
// Produce mathematically safe paths (cannot exist outside their boundary)
let css_file: = public_assets_root.strict_join?;
let avatar_file: = user_uploads_root.strict_join?;
// Encode guarantees in signatures — prevents cross-domain mix-ups at compile time
serve_public_asset; // ✅ OK
// serve_public_asset(&avatar_file); // ❌ Compile error: wrong marker
Example B: VirtualPath for user-facing flows (per-user root)
use ;
; // Uploaded documents
let user_id = 42; // Example unique user identifier
let user_uploads_root = try_new?; // per-user root
let avatar_file: = user_uploads_root.virtual_join?;
process_upload; // ✅ OK
Example C: One common helper shared by both
use ;
;
;
// A common helper that works with any StrictPath marker
// Prepare one strict and one virtual path
let public_assets_root = try_new?;
let css_file: = public_assets_root.strict_join?;
let user_id = 42;
let user_uploads_root = try_new?;
let avatar_file: = user_uploads_root.virtual_join?;
// Call with either type
let _ = process_common?; // StrictPath
let _ = process_common?; // Borrow strict view from VirtualPath
Why this matters:
StrictPath<Marker>andVirtualPath<Marker>are boundary-checked — construction proves containment.- Function signatures become policy — the type system rejects misuse and cross-domain mix-ups.
- Prefer simple, dimension-specific helpers; when needed, borrow a strict view from a virtual path with
as_unvirtual().
Where This Makes Sense
"LLMs: great at generating paths, terrible at keeping secrets."
- Usefulness for LLM agents: LLMs can produce arbitrary paths;
StrictPath/VirtualPathmake those suggestions safe by validation (strict) or clamping (virtual) before any I/O. PathBoundary/VirtualRoot: When you want the compiler to enforce that a value is anchored to the initial root/boundary. Keeping the policy type separate from path values prevents helpers from “picking a root” silently. With features enabled, you also get ergonomic, policy‑aware constructors (e.g.,dirs,tempfile,app-path).- Marker types: Add domain context for the compiler and reviewers (e.g.,
PublicAssets,UserUploads). They read like documentation and prevent cross‑domain mix‑ups at compile time.
Trade‑offs you can choose explicitly:
- Zero‑trust, CVE‑aware approach: Prefer canonicalized solutions (this crate) to resolve to absolute, normalized system paths with symlink handling and platform quirks addressed. This defends against entire classes of traversal and aliasing attacks.
- Lexical approach (performance‑first, limited scope): If you’re absolutely certain there are no symlinks, junctions, mounts, or platform‑specific aliases and your inputs are already normalized, a lexical solution from another crate may be faster. Use this only when the invariants are guaranteed by your environment and tests.
🎯 Decision Guide: When to Use What
Golden Rule: If you didn't create the path yourself, secure it first.
| Source/Input | Choose | Why | Notes |
|---|---|---|---|
| HTTP/CLI args/config/LLM/DB (untrusted segments) | StrictPath |
Reject attacks explicitly before I/O | Validate with PathBoundary.strict_join(...) |
| Archive contents, user uploads (user-facing UX) | VirtualPath |
Clamp hostile paths safely; rooted "/" display | Per-user VirtualRoot; use .virtual_join(...) |
| UI-only path display | VirtualPath |
Show clean rooted paths | virtualpath_display(); no system leakage |
| Your own code/hardcoded paths | Path/PathBuf |
You control the value | Never for untrusted input |
| External APIs/webhooks/inter-service messages | StrictPath |
System-facing interop/I/O requires validation | Validate on consume before touching FS |
| (See the full decision matrix in the book) |
Notes that matter:
- This isn’t StrictPath vs VirtualPath.
VirtualPathconceptually extendsStrictPathwith a virtual "/" view; both support I/O and interop. Choose based on whether you need virtual, user-facing semantics (VirtualPath) or raw system-facing validation (StrictPath). - Unified helpers: Prefer dimension-specific signatures. When sharing a helper across both, accept
&StrictPath<_>and call withvpath.as_unvirtual()as needed.
At‑a‑glance: API Modes
| Feature | Path/PathBuf |
StrictPath |
VirtualPath |
|---|---|---|---|
| Security | None 💥 | Validates & rejects ✅ | Clamps any input ✅ |
| Join safety | Unsafe (can escape) | Boundary-checked | Boundary-clamped |
| Example attack | "../../../etc/passwd" → System breach |
"../../../etc/passwd" → Error |
"../../../etc/passwd" → /etc/passwd (safe) |
| Best for | Known-safe paths | System boundaries | User interfaces |
Further reading in the book:
- Best Practices (full decision matrix and rationale): https://dk26.github.io/strict-path-rs/best_practices.html
- Anti-Patterns (what not to do, with fixes): https://dk26.github.io/strict-path-rs/anti_patterns.html
- Examples (end-to-end realistic scenarios): https://dk26.github.io/strict-path-rs/examples.html
🛡️ Core Security Foundation
"StrictPath: the vault door, not just a velvet rope."
At the heart of this crate is StrictPath - the fundamental security primitive that provides our ironclad guarantee: every StrictPath is mathematically proven to be within its boundary.
Everything in this crate builds upon StrictPath:
PathBoundarycreates and validatesStrictPathinstancesVirtualPathextendsStrictPathwith user-friendly virtual root semanticsVirtualRootprovides a root context for creatingVirtualPathinstances
The core promise: If you have a StrictPath<Marker>, it is impossible for it to reference anything outside its designated boundary. This isn't just validation - it's a type-level guarantee backed by cryptographic-grade path canonicalization.
Core Security Principle: Secure Every External Path
Any path from untrusted sources (HTTP, CLI, config, DB, LLMs, archives) must be validated into a boundary‑enforced type (StrictPath or VirtualPath) before I/O.
🧪 Examples by Mode
"Choose wisely: not all paths lead to safety."
🌐 VirtualPath - User Sandboxes & Cloud Storage
"Give users their own private universe"
use VirtualPath;
// Archive extraction - hostile names get clamped, not rejected
let extract_root = with_root?;
for entry_name in malicious_zip_entries
// User cloud storage - users see friendly paths
let doc = with_root?
.virtual_join?;
println!; // Shows "/My Documents/report.pdf"
⚔️ StrictPath - LLM Agents & System Boundaries
"Validate everything, trust nothing"
use PathBoundary;
// LLM Agent file operations
let ai_workspace = try_new?;
let ai_request = llm.generate_path; // Could be anything malicious
let safe_path = ai_workspace.strict_join?; // ✅ Attack = Explicit Error
safe_path.write?;
// Limited system access with clear boundaries
;
let config_dir = try_new?;
let user_config = config_dir.strict_join?; // ✅ Validated
🔓 Path/PathBuf - Controlled Access
"When you control the source"
use PathBuf;
// ✅ You control the input - no validation needed
let log_file = from;
let app_config = new; // Hardcoded = safe
// ❌ NEVER with external input
let user_file = new; // 🚨 SECURITY DISASTER
🚀 Real-World Examples
"Every example here survived a close encounter with an LLM."
LLM Agent File Manager
use PathBoundary;
// Encode guarantees in signature: pass workspace boundary and untrusted request
async
Zip Extraction (Zip Slip Prevention)
use VirtualPath;
// Encode guarantees in signature: construct a root once; pass untrusted entry names
Web File Server
use PathBoundary;
;
async
// Function signature prevents bypass - no validation needed inside!
async
Configuration Manager
use PathBoundary;
;
⚠️ Security Scope
"If your attacker has root, strict-path can't save you—but it can make them work for it."
What this protects against (99% of attacks):
- Path traversal (
../../../etc/passwd) - Symlink escapes and directory bombs
- Archive extraction attacks (zip slip)
- Unicode/encoding bypass attempts
- Windows-specific attacks (8.3 names, UNC paths)
- Race conditions during path resolution
What requires system-level privileges (rare):
- Hard links: Multiple filesystem entries to same file data
- Mount points: Admin/root can redirect paths via filesystem mounts
Bottom line: If attackers have root/admin access, they've already won. This library stops the 99% of practical attacks that don't require special privileges.
🔐 Advanced: Type-Safe Context Separation
"Type safety: because mixing up user files and web assets is so 2005."
Use markers to prevent mixing different storage contexts at compile time:
use ;
; // CSS, JS, images
; // Uploaded documents
// Functions enforce context via type system
// Create context-specific roots
let public_assets_root: = try_new?;
let user_uploads_root: = try_new?;
let css_file: = public_assets_root.virtual_join?;
let report_file: = user_uploads_root.virtual_join?;
// Type system prevents context mixing
serve_asset; // ✅ Correct context
// serve_asset(report_file.as_unvirtual()); // ❌ Compile error!
Your IDE and compiler become security guards.
App Configuration with app_path:
// ❌ Vulnerable - app dirs + user paths
use AppPath;
let app_dir = new.get_app_dir;
let config_file = app_dir.join; // 🚨 Potential escape
write?;
// ✅ Protected - bounded app directories
use PathBoundary;
let boundary = try_new_create?;
let safe_config = boundary.strict_join?; // ✅ Validated
safe_config.write?;
⚠️ Anti-Patterns (Tell‑offs and Fixes)
"Don't be that developer: use the right display method."
DON'T Mix Interop with Display
use PathBoundary;
let user_uploads_root = try_new?; // user uploads root
// ❌ ANTI-PATTERN: Wrong method for display
println!;
// ✅ CORRECT: Use proper display methods
println!;
// For virtual flows, prefer `VirtualPath` and borrow strict view when needed:
use VirtualPath;
let user_uploads_vroot = with_root?; // user uploads root
let profile_avatar_file = user_uploads_vroot.virtual_join?; // file by domain role
println!;
println!;
Why this matters:
interop_path()is designed for external API interop (AsRef<Path>)*_display()methods are designed for human-readable output- Mixing concerns makes code harder to understand and maintain
Web Server File Serving
; // Marker for static assets
async
// Caller handles validation once:
let static_files_dir = try_new?;
let safe_path = static_files_dir.strict_join?; // ✅ Validated
serve_static_file.await?;
Archive Extraction (Zip Slip Prevention)
See the mdBook archive extractors guide for the full example and rationale: https://dk26.github.io/strict-path-rs/archive_extractors.html
Cloud Storage API
// User chooses any path - always safe
let user_cloud_root = with_root?;
let user_cloud_file = user_cloud_root.virtual_join?; // ✅ Always safe
user_cloud_file.write?;
Configuration Files
use PathBoundary;
// Encode guarantees via the signature: pass the boundary and an untrusted name
LLM/AI File Operations
// AI suggests file operations - always validated
let ai_workspace = try_new?;
let ai_suggested_path = llm_generate_filename; // Could be anything!
let safe_ai_path = ai_workspace.strict_join?; // ✅ Guaranteed safe
safe_ai_path.write?;
📚 Documentation & Resources
"If you read the docs, you get +10 security points."
- 📖 Complete API Reference - Comprehensive API documentation
- 📚 User Guide & Examples - In-depth tutorials and patterns
- Best Practices (detailed decision matrix): https://dk26.github.io/strict-path-rs/best_practices.html
- Anti-Patterns (don’t-do list with fixes): https://dk26.github.io/strict-path-rs/anti_patterns.html
- Examples (copy/pasteable scenarios): https://dk26.github.io/strict-path-rs/examples.html
- 🔧 LLM_API_REFERENCE.md - Quick reference for all methods (LLM-focused)
- 🛠️
soft-canonicalize- The underlying path resolution engine
🔌 Integrations
"Integrate like a pro: strict-path plays nice with everyone except attackers."
- 🗂️ OS Directories (
dirsfeature):PathBoundary::try_new_os_config(),try_new_os_downloads(), etc. - 📄 Serde (
serdefeature): Safe serialization/deserialization of path types - 🌐 Axum: Custom extractors for web servers (see
demos/for examples)
📄 License
MIT OR Apache-2.0