strict-path
📚 Complete Guide & Examples | 📖 API Docs | 🧭 Choosing Canonicalized vs Lexical Solution
Stop path attacks before they happen. This crate makes sure file paths can't escape where you want them to go.
Note: Our doc comments and LLM_API_REFERENCE.md are designed for LLMs with function calling—so an AI can use this crate safely and correctly for file and path 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_API_REFERENCE.md
What this crate does
- Blocks path attacks: Turn dangerous paths like
../../../etc/passwdinto either safe paths or clear errors - Handles the obscure edge cases: Windows 8.3 short names, symlink cycles, NTFS streams, UNC paths, encoding tricks—the stuff you'd never think to test for
- Compiler-enforced guarantees:
StrictPath<Marker>types prove at compile-time that paths stay within boundaries - Enables authorization architectures: When you design markers to require authorization for construction, the compiler mathematically proves that any use of those markers went through authorization first
- Safe builtin I/O operations: Complete filesystem API (read, write, create_dir, metadata, rename, copy, etc.) that eliminates the need for
.interop_path()calls in routine operations - Two modes to choose from:
- StrictPath: Rejects bad paths with an error (good for APIs and system access guarantees)
- VirtualPath: Clamps bad paths to safe ones (good for simulating virtual user spaces, extracting archives in isolation, etc.)
- Built on battle-tested foundations: Uses
soft-canonicalizewhich has been validated against 19+ real-world path-related CVEs - Easy to use: Drop-in replacement for standard file operations, same return values
- Works everywhere: Handles platform differences so you don't have to
What this crate is NOT
- Not just string checking: We actually follow filesystem links and resolve paths properly
- Not a simple wrapper: Built from the ground up for security, not a thin layer over existing types
- Not just removing "..": Handles symlinks, Windows short names, and other escape tricks
- Not a permission system: Works with your existing file permissions, doesn't replace them
- Not a sandbox: We secure paths at the path level, not at the OS level
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?;
📖 New to strict-path? Start with the Tutorial: Stage 1 - The Basic Promise → to learn the core concepts step-by-step.
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 that handles edge cases you'd never think to check:
- 🔧
soft-canonicalizefoundation: Heavily tested against 19+ globally known path-related CVEs—the battle-tested work you don't want to reimplement - 🚫 Advanced pattern detection: Catches encoding tricks, Windows 8.3 short names (
PROGRA~1), UNC paths, NTFS Alternate Data Streams, and malformed inputs that simple string checks miss - 🔗 Full canonicalization pipeline: Resolves symlinks, junctions,
.and..components, and handles filesystem race conditions—the complex stuff that's easy to get wrong - 📐 Mathematical correctness: Rust's type system provides compile-time proof of path boundaries
- 🔐 Authorization architecture: Enable compile-time authorization guarantees through marker types
- 👁️ Explicit operations: Method names like
strict_join()make security violations visible in code review - 🛡️ Safe builtin I/O operations: Complete filesystem API that reduces the need for
.interop_path()calls in routine operations - 🤖 LLM-aware design: Built specifically for untrusted AI-generated paths and modern threat models
- ⚡ 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 when needed
📖 Read our complete security methodology →
Deep dive into our 7-layer security approach: from CVE research to comprehensive testing
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.2"
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.
🧬 The Edge Cases You'd Never Think Of
"Security is hard because the edge cases are infinite—until now."
What would you check for when validating a file path? Most developers think: "I'll block ../ and call it a day." But real attackers use techniques you've probably never heard of:
- Windows 8.3 short names:
PROGRA~1→Program Files(filesystem aliases that bypass string checks) - NTFS Alternate Data Streams:
config.txt:hidden:$DATA(secret channels in "normal" files) - Unicode normalization:
..∕..∕etc∕passwd(visually identical but different bytes) - Symlink time-bombs: Links that resolve differently between validation and use (TOCTOU)
- Mixed path separators:
../\../etc/passwd(exploiting parser differences) - UNC path shenanigans:
\\?\C:\Windows\..\..\..\etc\passwd(Windows extended paths)
The reality: You'd need months of research, testing across platforms, and deep filesystem knowledge to handle these correctly.
Our approach: We've already done the research. strict-path is built on soft-canonicalize, which has been battle-tested against 19+ real CVEs. You get comprehensive protection without becoming a path security expert.
🧠 The Secret Weapon: StrictPath<Marker> Types
"Marker types: because your code deserves a secret identity."
The most powerful feature you haven't discovered yet: StrictPath<Marker> doesn't just prevent path attacks—the <Marker> part unlocks secret superpowers that make wrong path usage a compile error.
StrictPath = Promise of path security
<Marker> = Unlocks extra secret powers!
Basic superpower: Prevent cross-domain mix-ups forever. Advanced superpower: Encode authorization requirements into the type system.
Level 1: Basic Domain Separation
use ;
; // CSS, JS, images
; // User documents
let public_assets_dir: = try_new?;
let user_uploads_dir: = try_new?;
let css_file: = public_assets_dir.strict_join?;
let user_doc: = user_uploads_dir.strict_join?;
serve_public_asset; // ✅ Works
// serve_public_asset(&user_doc); // ❌ Compile error: wrong domain!
The power: Mix up user uploads with public assets? Impossible. The compiler catches domain violations.
📖 Tutorial: Stage 3 - Markers → explains marker fundamentals and domain separation patterns.
Level 2: Authorization Architecture
// Marker describes the user's home directory inside a shared filesystem
// Functions work with pre-authorized paths
The power: Access user home directories without authentication? Impossible. The compiler mathematically proves authorization happened first.
Level 3: Permission Matrix
use ;
// Resource types (what) + Permission levels (how)
;
// Authentication returns the complete tuple
let = authenticate_user?;
let system_files_dir: = try_new?;
let system_file: =
system_files_dir.strict_join?;
view_system_file?; // ✅ Has ReadOnly permission
// manage_system_file(&system_file)?; // ❌ Needs AdminPermission!
The power: Create authorization matrices at compile-time. Wrong permission level? Impossible. The type system enforces your security model.
Why This Changes Everything
- Zero runtime cost: All marker logic erased at compile time
- Refactoring safety: Change authorization requirements → get compile errors everywhere affected
- Self-documenting: Function signatures show exactly what permissions are needed
- Impossible to bypass: No runtime checks to forget or skip
Bottom line: Turn authorization bugs from "runtime disasters" into "won't compile" problems.
📚 Learn Authorization Patterns →: Step-by-step tutorial on encoding authorization in the type system with
change_marker(), tuple markers, and capability-based patterns.
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 Complete Guide:
- Tutorial Series - 6-stage progressive guide from basics to advanced patterns
- Best Practices - Full decision matrix and design rationale
- Anti-Patterns - What not to do, with fixes
- Real-World Examples - End-to-end realistic scenarios
- Type-System Guarantees - How markers prevent bugs at compile-time
🛡️ 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.
Unique capability: By making markers authorization-aware, strict-path becomes the foundation for compile-time authorization architectures - where the compiler mathematically proves that any path with an authorization-requiring marker went through proper authorization during construction.
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"
📖 Learn more: Tutorial: Stage 5 - Virtual Paths → explains user sandboxing and virtual root semantics.
⚔️ StrictPath - LLM Agents & System Boundaries
"Validate everything, trust nothing"
use PathBoundary;
// LLM Agent file operations
let ai_workspace_dir = try_new?;
let ai_request = llm.generate_path; // Could be anything malicious
let safe_path = ai_workspace_dir.strict_join?; // ✅ Attack = Explicit Error
safe_path.write?;
// Limited system access with clear boundaries
;
let app_config_dir = try_new?;
let user_config = app_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 directory 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)—including edge cases most developers miss:
- Basic path traversal:
../../../etc/passwd - Symlink escapes: Following links outside boundaries, including directory bombs and cycle detection
- Archive extraction attacks: Zip slip and similar archive-based traversal attempts
- Encoding bypass attempts: Unicode normalization attacks, null bytes, and other encoding tricks
- Windows platform-specific attacks:
- 8.3 short name aliasing (
PROGRA~1→Program Files) - UNC path manipulation (
\\?\C:\and\\server\share\) - NTFS Alternate Data Streams (
file.txt:hidden) - Drive-relative path forms and junction points
- 8.3 short name aliasing (
- Race conditions: TOCTOU (Time-of-Check-Time-of-Use) during path resolution
- Canonicalization edge cases: Mixed separators, redundant separators, current/parent directory references
The reality: These aren't theoretical attacks—they're real vulnerabilities found in production systems. Instead of researching each CVE and implementing custom defenses, you get comprehensive protection from day one.
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—and handles all the edge cases you'd probably forget to check.
🔐 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 app_config_dir = try_new_create?;
let safe_config = app_config_dir.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_dir = try_new?; // user uploads directory boundary
// ❌ 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 solely for unavoidable third-party 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)
📘 Complete Archive Extraction Guide → - Full patterns for ZIP/TAR handling, security rationale, and anti-patterns
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_dir = try_new?;
let ai_suggested_path = llm_generate_filename; // Could be anything!
let safe_ai_path = ai_workspace_dir.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. - Full Guide - 📄 Serde (
serdefeature): Safe serialization/deserialization of path types - Tutorial: Stage 6 Feature Integration - 🌐 Axum: Custom extractors for web servers - Complete Tutorial
- 📦 Archive Handling: Safe ZIP/TAR extraction - Extractor Guide
📄 License
MIT OR Apache-2.0