strict_path/
lib.rs

1//! # strict-path
2//!
3//! Prevent directory traversal with cross-platform, CVE-hardened path restriction and safe symlinks.
4//!
5//! This crate is not a thin wrapper over `std::path` or a naive path comparison.
6//! It performs full normalization/canonicalization and boundary enforcement with:
7//! - Safe symlink/junction handling (including cycle detection)
8//! - Windows-specific quirks (8.3 short names, UNC and verbatim prefixes, ADS)
9//! - Robust Unicode normalization and mixed-separator handling across platforms
10//! - Canonicalized path proofs encoded in the type system
11//!
12//! If a `StrictPath<Marker>` value exists, it is already proven to be inside its
13//! designated boundary by construction — not by best-effort string checks.
14//!
15//! 📚 **[Complete Guide & Examples](https://dk26.github.io/strict-path-rs/)** | 📖 **[API Reference](https://docs.rs/strict-path)**
16//!
17//! ## Quick start: one‑liners
18//!
19//! Most apps can start with these constructors and chain joins:
20//!
21//! ```rust
22//! # use strict_path::{StrictPath, VirtualPath};
23//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
24//! // Use temporary directories in doctests so paths exist
25//! let d1 = tempfile::tempdir()?;
26//! let sp: StrictPath = StrictPath::with_boundary(d1.path())?    // validated strict root
27//!     .strict_join("users/alice.txt")?;                        // stays inside root
28//!
29//! let d2 = tempfile::tempdir()?;
30//! let vp: VirtualPath = VirtualPath::with_root(d2.path())?      // virtual root "/"
31//!     .virtual_join("assets/logo.png")?;                       // clamped to root
32//! // Create the file before inspecting/removing it in the example
33//! sp.create_parent_dir_all()?;
34//! sp.write("hello")?;
35//! sp.metadata()?;                      // inspect filesystem metadata safely
36//! sp.remove_file()?;                   // remove files through the wrapper
37//! # Ok(()) }
38//! ```
39//!
40//! For reusable policy and advanced flows (OS dirs, serde with context),
41//! use `PathBoundary`/`VirtualRoot` directly.
42//!
43//! ## Core Security Foundation: `StrictPath`
44//!
45//! **`StrictPath` is the fundamental security primitive** that provides our core guarantee: every
46//! `StrictPath` is mathematically proven to be within its designated boundary. This is not just
47//! validation — it's a type-level security contract that makes path traversal attacks impossible,
48//! including attacks relying on symlink aliasing, Windows path forms, or encoding tricks.
49//!
50//! Everything else in this crate builds upon `StrictPath`:
51//! - `PathBoundary` creates and validates `StrictPath` instances from external input
52//! - `VirtualPath` extends `StrictPath` with user-friendly virtual root semantics
53//! - `VirtualRoot` provides a root context for creating `VirtualPath` instances
54//!
55//! **The security model:** If you have a `StrictPath<Marker>` in your code, it cannot reference
56//! anything outside its boundary - this is enforced by the type system and cryptographic-grade
57//! path canonicalization.
58//!
59//! ## Why naive approaches fail (and CVEs they miss)
60//!
61//! String checks and one-off normalizers don’t compose into a secure system. Common pitfalls:
62//!
63//! - Checking for "../" misses double-encodings, mixed separators, and absolute replacements.
64//! - Blind `canonicalize()` checks fail on non-existent files and enable TOCTOU races (e.g., symlink swaps) between resolution and use.
65//! - Lexical normalization ignores platform aliasing (Windows 8.3 short names), ADS streams, and UNC/verbatim quirks.
66//!
67//! Illustrative (simplified) examples — these are intentionally non-runnable here:
68//!
69//! ```rust,ignore
70//! // ❌ Rejecting only "../" is bypassable via encoding
71//! if candidate.contains("../") { return Err("nope"); }
72//! // "..%2F..%2Fetc%2Fpasswd" or mixed separators can slip through
73//! ```
74//!
75//! ```rust,ignore
76//! // ❌ Canonicalize‑then‑check is subject to TOCTOU (CVE‑2022‑21658 class)
77//! let real = std::fs::canonicalize(&candidate)?;
78//! if !real.starts_with(root) { return Err("escape"); }
79//! // Attacker swaps a symlink between these calls
80//! std::fs::read(real)?;
81//! ```
82//!
83//! ```rust,ignore
84//! // ❌ Lexical only: misses Windows 8.3 short name aliasing (e.g., PROGRA~1)
85//! // CVEs: 2019‑9855, 2020‑12279 class of issues around aliasing/normalization
86//! let norm = candidate.replace("\\", "/");
87//! if norm.starts_with("/safe/") { /* ... */ }
88//! ```
89//!
90//! strict‑path centralizes normalization, canonicalization, and boundary checks in a single auditable
91//! pipeline, with anchored canonicalization for virtual roots and explicit APIs that make the intended
92//! dimension (strict vs virtual) visible. The result is a type‑level guarantee: if a `StrictPath<Marker>`
93//! exists, it is proven to be within its boundary.
94//!
95//! ## Path Types and Their Relationships
96//!
97//! - **`StrictPath`**: The core security primitive - a validated, system-facing path that proves
98//!   the wrapped filesystem path is within the predefined boundary. If a `StrictPath` exists,
99//!   it is mathematical proof that the path is safe.
100//! - **`VirtualPath`**: Extends `StrictPath` with a virtual-root view (treating the PathBoundary
101//!   as "/"), adding user-friendly operations while preserving all `StrictPath` security guarantees.
102//!
103//! ## Design Philosophy: PathBoundary as Foundation
104//!
105//! The `PathBoundary` represents the secure foundation or starting point from which all path operations begin.
106//! Think of it as establishing a safe boundary (like `/home/users/alice`) and then performing validated
107//! operations from that foundation. When you call `path_boundary.strict_join("documents/file.txt")`,
108//! you're building outward from the secure boundary with validated path construction.
109//!
110//! ## When to Use Which Type
111//!
112//! **Use `VirtualRoot`/`VirtualPath` for isolation and sandboxing:**
113//! - User uploads, per-user data directories, tenant-specific storage
114//! - Web applications serving user files, document management systems
115//! - Plugin systems, template engines, user-generated content
116//! - Any case where users should see a clean "/" root and not the real filesystem structure
117//!
118//! **Use `PathBoundary`/`StrictPath` for shared system spaces:**
119//! - Application configuration, shared caches, system logs
120//! - Temporary directories, build outputs, asset processing
121//! - Cases where you need the real system path for interoperability or debugging
122//! - When working with existing APIs that expect system paths
123//!
124//! Both types support I/O. The key difference is the user experience: `VirtualPath` provides isolation
125//! and clean virtual paths, while `StrictPath` maintains system path semantics for shared resources.
126//!
127//! ## 🔑 Critical Design Decision: StrictPath vs Path/PathBuf
128//!
129//! **The Key Principle: Use `StrictPath` when you DON'T control the path source**
130//!
131//! ```rust
132//! # use strict_path::{PathBoundary, StrictPath, VirtualRoot, VirtualPath};
133//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
134//! // ✅ USE StrictPath - External/untrusted input (you don't control the source)
135//! // Encode guarantees in the signature: pass the boundary and the untrusted segment
136//! fn handle_user_config(boundary: &PathBoundary, config_name: &str) -> Result<(), Box<dyn std::error::Error>> {
137//!     let config_path: StrictPath = boundary.strict_join(config_name)?;  // Validate!
138//!     let _content = config_path.read_to_string()?;
139//!     Ok(())
140//! }
141//!
142//! // ✅ USE VirtualRoot - External/untrusted input for user-facing paths
143//! // Encode guarantees in the signature: pass the virtual root and the untrusted segment
144//! fn process_upload(uploads: &VirtualRoot, user_filename: &str) -> Result<(), Box<dyn std::error::Error>> {
145//!     let safe_file: VirtualPath = uploads.virtual_join(user_filename)?;  // Sandbox!
146//!     safe_file.write(b"data")?;
147//!     Ok(())
148//! }
149//!
150//! // ✅ USE Path/PathBuf - Internal/controlled paths (you generate the path)
151//! fn create_backup() -> std::path::PathBuf {
152//!     use std::path::PathBuf;
153//!     let timestamp = "20240101_120000"; // Simulated timestamp
154//!     PathBuf::from(format!("backups/backup_{}.sql", timestamp))  // You control this
155//! }
156//!
157//! fn get_log_file() -> &'static std::path::Path {
158//!     std::path::Path::new("/var/log/myapp/app.log")  // Hardcoded, you control this
159//! }
160//! # Ok(()) }
161//! ```
162//!
163//! **Decision Matrix:**
164//! - **External Input** (config files, CLI args, API requests, user uploads) → `StrictPath`/`VirtualPath`
165//! - **Internal Generation** (timestamps, IDs, hardcoded paths, system APIs) → `Path`/`PathBuf`
166//! - **Unknown Origin** → `StrictPath`/`VirtualPath` (err on the side of security)
167//! - **Performance Critical + Trusted** → `Path`/`PathBuf` (avoid validation overhead)
168//!
169//! This principle ensures security where it matters while avoiding unnecessary overhead for paths you generate and control.
170//!
171//! ### Analogy: Prepared statements for paths
172//!
173//! Think of `StrictPath`/`VirtualPath` like prepared statements for SQL:
174//! - The `PathBoundary`/`VirtualRoot` you construct is the prepared statement — it encodes the policy and allowable scope.
175//! - The untrusted filename/path segment is the bound parameter — passed into `strict_join`/`virtual_join` where it’s validated or clamped.
176//! - Injection attempts become inert — attackers can’t “change the query” or escape the boundary; inputs are treated as data, not structure.
177//!
178//! ### Example: Isolation vs Shared System Space
179//!
180//! ```rust
181//! use strict_path::{StrictPath, VirtualPath};
182//!
183//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
184//! // ISOLATION: User upload directory - users see clean "/" paths
185//! // Note: `.with_root()` requires the directory to already exist. Use
186//! // `.with_root_create()` if you want it to be created automatically.
187//! # std::fs::create_dir_all("uploads/user_42")?; // hidden setup
188//! let user_root: VirtualPath = VirtualPath::with_root("uploads/user_42")?;
189//! let user_file: VirtualPath = user_root.virtual_join("documents/report.pdf")?;
190//!
191//! // User sees: "/documents/report.pdf" (clean, isolated)
192//! println!("User sees: {}", user_file.virtualpath_display());
193//! user_file.create_parent_dir_all()?;
194//! user_file.write(b"user content")?;
195//!
196//! // SHARED SYSTEM: Application cache - you see real system paths
197//! // Note: `.with_boundary()` requires an existing directory. Prefer
198//! // `.with_boundary_create()` to auto-create the boundary as needed.
199//! # std::fs::create_dir_all("app_cache")?; // hidden setup
200//! let cache_root: StrictPath = StrictPath::with_boundary("app_cache")?;
201//! let cache_file: StrictPath = cache_root.strict_join("build/output.json")?;
202//!
203//! // Developer sees: "app_cache/build/output.json" (real system path)  
204//! println!("System path: {}", cache_file.strictpath_display());
205//! cache_file.create_parent_dir_all()?;
206//! cache_file.write(b"cache data")?;
207//!
208//! # user_root.remove_dir_all().ok(); cache_root.remove_dir_all().ok();
209//! # Ok(()) }
210//! ```
211//!
212//! ## Filter vs Sandbox: Conceptual Difference
213//!
214//! **`StrictPath` acts like a security filter** - it validates that a specific path is safe and
215//! within boundaries, but operates on actual filesystem paths. Perfect for **shared system spaces**
216//! where you need safety while maintaining system-level path semantics (logs, configs, caches).
217//!
218//! **`VirtualPath` acts like a complete sandbox** - it encapsulates the filtering (via the underlying
219//! `StrictPath`) while presenting a virtualized, user-friendly view where the PathBoundary root appears as "/".
220//! Users can specify any path they want, and it gets automatically clamped to stay safe. Perfect for
221//! **isolation scenarios** where you want to hide the underlying filesystem structure from users
222//! (uploads, per-user directories, tenant storage).
223//!
224//! ## Unified Signatures (Explicit Borrow)
225//!
226//! Prefer marker-specific signatures that accept `&StrictPath<Marker>` and borrow strict view with `as_unvirtual()`.
227//! This keeps conversions explicit and avoids vague conversions.
228//!
229//!
230//! ```rust
231//! use strict_path::{StrictPath, VirtualPath};
232//!
233//! // Write ONE function that works with both types
234//! fn process_file(path: &StrictPath) -> std::io::Result<String> {
235//!     path.read_to_string()
236//! }
237//!
238//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
239//! let jpath: StrictPath = StrictPath::with_boundary("./data")?.strict_join("config.toml")?;
240//! let vpath: VirtualPath = VirtualPath::with_root("./data")?.virtual_join("config.toml")?;
241//!
242//! let _ = process_file(&jpath)?;               // StrictPath
243//! process_file(vpath.as_unvirtual())?; // VirtualPath -> borrow strict view explicitly
244//! # Ok(()) }
245//! ```
246//!
247//! This keeps conversions explicit by dimension and aligns with the crate's security model.
248//!
249//! The core security guarantee is that all paths are mathematically proven to stay within their
250//! designated boundaries, neutralizing traversal attacks like `../../../etc/passwd`.
251//!
252//! ## Type-System Guarantees in Function Signatures
253//!
254//! Use marker types to encode policy directly in your APIs. Callers must supply the right
255//! `StrictPath<Marker>` or the code simply won’t compile.
256//!
257//! ```rust
258//! # use strict_path::{PathBoundary, StrictPath};
259//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
260//! // Define semantic markers
261//! struct PublicAssets;
262//! struct UserUploads;
263//!
264//! // Policy roots
265//! # std::fs::create_dir_all("./assets")?;
266//! # std::fs::create_dir_all("./uploads")?;
267//! let assets = PathBoundary::<PublicAssets>::try_new("./assets")?;
268//! let uploads = PathBoundary::<UserUploads>::try_new("./uploads")?;
269//!
270//! // Safe paths — existence itself proves they’re inside their boundary
271//! let css: StrictPath<PublicAssets> = assets.strict_join("style.css")?;
272//! let avatar: StrictPath<UserUploads> = uploads.strict_join("avatar.jpg")?;
273//!
274//! // Encode guarantees in the signature
275//! fn serve_public_asset(file: &StrictPath<PublicAssets>) { /* ... */ }
276//!
277//! serve_public_asset(&css);       // ✅ OK
278//! // serve_public_asset(&avatar); // ❌ Compile error (wrong marker)
279//! # std::fs::remove_dir_all("./assets").ok();
280//! # std::fs::remove_dir_all("./uploads").ok();
281//! # Ok(()) }
282//! ```
283//!
284//! Contracts like these push policy to the type system: if a `StrictPath<Marker>` exists,
285//! it cannot reference anything outside the associated boundary.
286//!
287//! ## About This Crate: StrictPath and VirtualPath
288//!
289//! `StrictPath` is a system-facing filesystem path type, mathematically proven (via
290//! canonicalization, boundary checks, and type-state) to remain inside a configured PathBoundary directory.
291//! `VirtualPath` wraps a `StrictPath` and therefore guarantees everything a `StrictPath` guarantees -
292//! plus a rooted, forward-slashed virtual view (treating the PathBoundary as "/") and safe virtual
293//! operations (joins/parents/file-name/ext) that preserve clamping and hide the real system path.
294//! With `VirtualPath`, users are free to specify any path they like while you still guarantee it
295//! cannot leak outside the underlying restriction.
296//!
297//! Construct them via the sugar constructors (`StrictPath::with_boundary(_create)`,
298//! `VirtualPath::with_root(_create)`) for most flows. Use `PathBoundary`/`VirtualRoot` directly when
299//! you need to reuse policy across many paths or pass the policy as a parameter. Ingest untrusted
300//! paths as `VirtualPath` for UI/UX and safe joins; perform I/O from either type.
301//!
302//! ## Security Foundation
303//!
304//! Built on [`soft-canonicalize`](https://crates.io/crates/soft-canonicalize), this crate inherits
305//! protection against documented CVEs including:
306//! - **CVE-2025-8088** (NTFS ADS path traversal), **CVE-2022-21658** (TOCTOU attacks)
307//! - **CVE-2019-9855, CVE-2020-12279** and others (Windows 8.3 short name vulnerabilities)  
308//! - Path traversal, symlink attacks, Unicode normalization bypasses, and race conditions
309//!
310//! This isn't simple string comparison-paths are fully canonicalized and boundary-checked
311//! against known attack patterns from real-world vulnerabilities.
312//!
313//! Guidance
314//! - Accept untrusted input via `VirtualPath::with_root(..).virtual_join(..)` (or keep a `VirtualRoot`
315//!   and call `virtual_join(..)`) to obtain a `VirtualPath`.
316//! - Perform I/O directly on `VirtualPath` or on `StrictPath`. Unvirtualize only when you need a
317//!   `StrictPath` explicitly (e.g., for a signature that requires it or for system-facing logs).
318//! - For `AsRef<Path>` interop, pass `interop_path()` from either type (no allocation).
319//!
320//! Switching views (upgrade/downgrade)
321//! - Prefer staying in one dimension for a given flow:
322//!   - Virtual view: `VirtualPath` + `virtualpath_*` ops and direct I/O.
323//!   - System view: `StrictPath` + `StrictPath_*` ops and direct I/O.
324//! - Edge cases: upgrade with `StrictPath::virtualize()` or downgrade with `VirtualPath::unvirtual()`
325//!   to access the other view's operations explicitly.
326//!
327//! Markers and type inference
328//! - All public types are generic over a `Marker` with a default of `()`.
329//! - Inference usually works once a value is bound:
330//!   - `let vp: VirtualPath = VirtualPath::with_root("root")?.virtual_join("a.txt")?;`
331//! - When inference needs help, annotate the type or use an empty turbofish:
332//!   - Or use explicit `VirtualRoot` when you want to reuse policy across paths: `let vroot: VirtualRoot<()> = VirtualRoot::try_new("root")?;`
333//! - With custom markers, annotate as needed:
334//!   - `struct UserFiles; let vroot: VirtualRoot<UserFiles> = VirtualRoot::try_new("uploads")?;`
335//!   - `let uploads = VirtualRoot::try_new::<UserFiles>("uploads")?;`
336
337//! ### Examples: Encode Guarantees in Signatures
338//!
339//! ```rust
340//! # use strict_path::VirtualPath;
341//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
342//! // Cloud storage per-user PathBoundary
343//! let user_id = 42u32;
344//! let root = format!("./cloud_user_{user_id}");
345//! let vp_root: VirtualPath = VirtualPath::with_root_create(&root)?;
346//!
347//! // Accept untrusted input, then pass VirtualPath by reference to functions
348//! let requested = "projects/2025/report.pdf";
349//! let vp: VirtualPath = vp_root.virtual_join(requested)?;  // Stays inside ./cloud_user_42
350//! // Ensure parent directory exists before writing
351//! vp.create_parent_dir_all()?;
352//!
353//! fn save_doc(p: &VirtualPath) -> std::io::Result<()> { p.write(b"user file content") }
354//! save_doc(&vp)?; // Compiler enforces correct usage via the type
355//! println!("virtual: {}", vp.virtualpath_display());
356//!
357//! # // Cleanup
358//! # vp_root.remove_dir_all().ok();
359//! # Ok(()) }
360//! ```
361//!
362//! ```rust
363//! # use strict_path::VirtualPath;
364//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
365//! // Web/E-mail templates resolved in a user-scoped virtual root
366//! # let user_id = 7u32;
367//! let tpl_root = format!("./tpl_space_{user_id}");
368//! let templates: VirtualPath = VirtualPath::with_root_create(&tpl_root)?;
369//! let tpl: VirtualPath = templates.virtual_join("emails/welcome.html")?;
370//! fn render(p: &VirtualPath) -> std::io::Result<String> { p.read_to_string() }
371//! let _ = render(&tpl);
372//!
373//! # templates.remove_dir_all().ok();
374//! # Ok(()) }
375//! ```
376//!
377//! ## Quickstart: User-Facing Virtual Paths (with signatures)
378//!
379//! ```rust
380//! use strict_path::VirtualPath;
381//!
382//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
383//! // 1. Create a virtual root (sugar), which corresponds to a real directory.
384//! let root = VirtualPath::with_root_create("user_data")?;
385//!
386//! // 2. Create a virtual path from user input. Traversal attacks are neutralized.
387//! let virtual_path: VirtualPath = root.virtual_join("documents/report.pdf")?;
388//! let attack_path: VirtualPath = root.virtual_join("../../../etc/hosts")?;
389//!
390//! // 3. Displaying the path is always safe and shows the virtual view.
391//! assert_eq!(virtual_path.virtualpath_display().to_string(), "/documents/report.pdf");
392//! assert_eq!(attack_path.virtualpath_display().to_string(), "/etc/hosts"); // Clamped, not escaped
393//!
394//! // 4. Prefer signatures requiring `VirtualPath` for operations.
395//! fn ensure_dir(p: &VirtualPath) -> std::io::Result<()> { p.create_dir_all() }
396//! ensure_dir(&virtual_path)?;
397//! assert!(virtual_path.exists());
398//!
399//! root.remove_dir_all()?;
400//! # Ok(())
401//! # }
402//! ```
403//!
404//! ## Key Features
405//!
406//! - Two Views: `VirtualPath` extends `StrictPath` with a virtual-root UX; both support I/O.
407//! - Mathematical Guarantees: Rust's type system proves security at compile time.
408//! - Zero Attack Surface: No `Deref` to `Path`, validation cannot be bypassed.
409//! - Built-in Safe I/O: `StrictPath` provides safe file operations.
410//! - Multi-PathBoundary Safety: Marker types prevent cross-PathBoundary contamination at compile time.
411//! - Type-History Design: Internal pattern ensures paths carry proof of validation stages.
412//! - Cross-Platform: Works on Windows, macOS, and Linux.
413//!
414//! Display/Debug semantics
415//! - No implicit `Display` on `VirtualPath`. Use the explicit wrapper: `vpath.virtualpath_display()`
416//!   to show a rooted, forward‑slashed virtual path (e.g., "/a/b.txt").
417//! - `Debug` for `VirtualPath` is developer‑facing and verbose (derived): it includes the inner
418//!   `StrictPath` (system path and PathBoundary root) and the virtual view for diagnostics.
419//!
420//! ### Example: Display vs Debug
421//! ```rust
422//! # use strict_path::{VirtualRoot, VirtualPath};
423//!
424//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
425//! let vp_root: VirtualPath = VirtualPath::with_root_create("vp_demo")?;
426//! let vp: VirtualPath = vp_root.virtual_join("users/alice/report.txt")?;
427//!
428//! // Display is user-facing, rooted, forward-slashed
429//! assert_eq!(vp.virtualpath_display().to_string(), "/users/alice/report.txt");
430//!
431//! // Debug is developer-facing and verbose
432//! let dbg = format!("{:?}", vp);
433//! assert!(dbg.contains("VirtualPath"));
434//! assert!(dbg.contains("system_path"));
435//! assert!(dbg.contains("virtual"));
436//!
437//! # vp_root.remove_dir_all().ok();
438//! # Ok(()) }
439//! ```
440//!
441//! ## When to Use Which Type
442//!
443//! | Use Case                               | Type                       | Example                                                     |
444//! | -------------------------------------- | -------------------------- | ----------------------------------------------------------- |
445//! | Displaying a path in a UI or log       | `VirtualPath`              | `println!("File: {}", virtual_path.virtualpath_display());` |
446//! | Manipulating a path based on user view | `VirtualPath`              | `virtual_path.virtualpath_parent()`                         |
447//! | Reading or writing a file              | `VirtualPath` or `StrictPath` | `virtual_path.read()?` or `strict_path.read()?` |
448//! | Integrating with an external API       | Either (borrow `&OsStr`)   | `external_api(virtual_path.interop_path())`         |
449//!
450//! ## Multi-PathBoundary Type Safety
451//!
452//! Use marker types to prevent paths from different restrictions from being used interchangeably.
453//!
454//! ```rust
455//! use strict_path::{PathBoundary, StrictPath, VirtualPath};
456//!
457//! struct StaticAssets;
458//! struct UserUploads;
459//!
460//! fn serve_asset(asset: &StrictPath<StaticAssets>) -> Result<Vec<u8>, std::io::Error> {
461//!     asset.read()
462//! }
463//!
464//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
465//! # let css_root: VirtualPath<StaticAssets> = VirtualPath::with_root_create("assets")?;
466//! # let css_pre: VirtualPath<StaticAssets> = css_root.virtual_join("style.css")?;
467//! # css_pre.create_parent_dir_all()?; css_pre.write("body{}")?;
468//! # let uploads_root: VirtualPath<UserUploads> = VirtualPath::with_root_create("uploads")?;
469//! let css_file: VirtualPath<StaticAssets> =
470//!     VirtualPath::with_root("assets")?.virtual_join("style.css")?;
471//! let avatar_file: VirtualPath<UserUploads> =
472//!     VirtualPath::with_root("uploads")?.virtual_join("avatar.jpg")?;
473//!
474//! serve_asset(css_file.as_unvirtual())?; // ✅ Correct type
475//! // serve_asset(avatar_file.as_unvirtual())?; // ❌ Compile error: wrong marker type!
476//! # css_root.remove_dir_all().ok(); uploads_root.remove_dir_all().ok();
477//! # Ok(())
478//! # }
479//! ```
480//!
481//! ## Security Guarantees
482//!
483//! All `..` components are clamped, symbolic links are resolved, and the final real path is
484//! validated against the PathBoundary boundary. Path traversal attacks are prevented by construction.
485//!
486//! ## Security Limitations
487//!
488//! This library operates at the **path level**, not the operating system level. While it provides
489//! strong protection against path traversal attacks using symlinks and standard directory
490//! navigation, it **cannot protect against** certain privileged operations:
491//!
492//! - **Hard Links**: If a file is hard-linked outside the restricted path, accessing it through the
493//!   PathBoundary will still reach the original file data. Hard links create multiple filesystem entries
494//!   pointing to the same inode.
495//! - **Mount Points**: If a filesystem mount is introduced (by a system administrator or attacker
496//!   with sufficient privileges) that redirects a path within the PathBoundary to an external location,
497//!   this library cannot detect or prevent access through that mount.
498//!
499//! **Important**: These attack vectors require **high system privileges** (typically
500//! root/administrator access) to execute. If an attacker has such privileges on your system, they
501//! can bypass most application-level security measures anyway. This library effectively protects
502//! against the much more common and practical symlink-based traversal attacks that don't require
503//! special privileges.
504//!
505//! Our symlink resolution via [`soft-canonicalize`](https://crates.io/crates/soft-canonicalize)
506//! handles the most accessible attack vectors that malicious users can create without elevated
507//! system access.
508//!
509//! ### Windows-only hardening: DOS 8.3 short names
510//!
511//! On Windows, paths like `PROGRA~1` are DOS 8.3 short-name aliases. To prevent ambiguity,
512//! this crate rejects paths containing non-existent components that look like 8.3 short names
513//! with a dedicated error, `StrictPathError::WindowsShortName`.
514//!
515//! ## Why We Don't Expose `Path`/`PathBuf`
516//!
517//! Exposing raw `Path` or `PathBuf` encourages use of std path methods (`join`, `parent`, ...)
518//! that bypass this crate's virtual-root clamping and boundary checks.
519//!
520//! - `join` danger: `std::path::Path::join` has no notion of a virtual root. Joining an
521//!   absolute path, or a path with enough `..` components, can override or conceptually
522//!   escape the intended root. That undermines the guarantees of `StrictPath`/`VirtualPath`.
523//!   **Critical:** `std::path::Path::join("/absolute")` completely replaces the base path,
524//!   making it the #1 cause of path traversal vulnerabilities. Our `strict_join` validates
525//!   the result stays within PathBoundary bounds, while `virtual_join` clamps absolute paths
526//!   to the virtual root.
527//!   Use `StrictPath::strict_join(...)` or `VirtualPath::virtual_join(...)` instead.
528//! - `parent` ambiguity: `Path::parent` ignores PathBoundary/virtual semantics; our
529//!   `strictpath_parent()` and `virtualpath_parent()` preserve the correct behavior.
530//! - Predictability: Users unfamiliar with the crate may accidentally mix virtual and
531//!   system semantics if they are handed a raw `Path`.
532//!
533//! What to use instead:
534//! - Passing to external APIs: Prefer `strict_path.interop_path()` which borrows the
535//!   inner system-facing path as `&OsStr` (implements `AsRef<Path>`). This is the cheapest and most
536//!   correct way to interoperate without exposing risky methods.
537//! - Ownership escape hatches: Use `.unvirtual()` (to get a `StrictPath`) or `.unstrict()`
538//!   (to get an owned `PathBuf`) explicitly and sparingly. These are deliberate, opt-in
539//!   operations to make potential risk obvious in code review.
540//!
541//! Explicit method names (rationale)
542//! - Operation names encode their dimension so intent is obvious:
543//!   - `p.join(..)` (std) - unsafe on untrusted input; can escape the restriction.
544//!   - `jp.strict_join(..)` - safe, validated system-path join.
545//!   - `vp.virtual_join(..)` - safe, clamped virtual-path join.
546//! - This naming applies broadly: `*_parent`, `*_with_file_name`, `*_with_extension`,
547//!   `*_starts_with`, `*_ends_with`, etc.
548//! - This makes API abuse easy to spot even when type declarations aren't visible.
549//!
550//! Safe rename/move
551//! ```rust
552//! # use strict_path::PathBoundary;
553//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
554//! // Strict (system-facing): validate destination via strict_join, then rename
555//! let td = tempfile::tempdir()?;
556//! let boundary: PathBoundary = PathBoundary::try_new_create(td.path())?;
557//! let file = boundary.strict_join("logs/app.log")?;
558//! file.create_parent_dir_all()?;
559//! file.write("ok")?;
560//!
561//! // Rename within the same directory (no implicit parent creation)
562//! // Relative destinations are resolved against the parent (sibling rename)
563//! file.strict_rename("app.old")?;
564//! let renamed = boundary.strict_join("logs/app.old")?;
565//! assert_eq!(renamed.read_to_string()?, "ok");
566//!
567//! // Virtual (user-facing): clamp + validate destination before rename
568//! let v = renamed.clone().virtualize();
569//! v.virtual_rename("app.archived")?;
570//! let v2 = boundary.strict_join("logs/app.archived")?.virtualize();
571//! assert!(v2.exists());
572//! # Ok(()) }
573//! ```
574//!
575//! Safe copy
576//! ```rust
577//! # use strict_path::PathBoundary;
578//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
579//! // Strict (system-facing): copy a file to a sibling name (no implicit parent creation)
580//! let td = tempfile::tempdir()?;
581//! let boundary: PathBoundary = PathBoundary::try_new_create(td.path())?;
582//! let src = boundary.strict_join("docs/a.txt")?;
583//! src.create_parent_dir_all()?;
584//! src.write("copy me")?;
585//!
586//! let bytes = src.strict_copy("b.txt")?; // resolved against parent directory
587//! assert_eq!(bytes, "copy me".len() as u64);
588//! let dst = boundary.strict_join("docs/b.txt")?;
589//! assert_eq!(dst.read_to_string()?, "copy me");
590//!
591//! // Virtual (user-facing): clamp + validate destination before copy
592//! let v = dst.clone().virtualize();
593//! let bytes = v.virtual_copy("c.txt")?; // sibling within the same virtual parent
594//! assert_eq!(bytes, "copy me".len() as u64);
595//! let vcopy = boundary.strict_join("docs/c.txt")?.virtualize();
596//! assert!(vcopy.exists());
597//! assert_eq!(vcopy.read_to_string()?, "copy me");
598//! # Ok(()) }
599//! ```
600//!
601//! Why `&OsStr` works well:
602//! - `OsStr`/`OsString` are OS-native string types; you don't lose platform-specific data.
603//! - `Path` is just a thin wrapper over `OsStr`. Borrowing `&OsStr` is the straightest,
604//!   allocation-free, and semantically correct way to pass a path to `AsRef<Path>` APIs.
605//!
606//! ## Common Pitfalls (and How to Avoid Them)
607//!
608//! - **NEVER wrap our secure types in `Path::new()` or `PathBuf::from()`**.
609//!   This is a critical anti-pattern that bypasses all security guarantees.
610//!   ```rust,no_run
611//!   # use strict_path::*;
612//!   # let restriction = PathBoundary::<()>::try_new(".").unwrap();
613//!   # let safe_path = restriction.strict_join("file.txt").unwrap();
614//!   // ❌ DANGEROUS: Wrapping secure types defeats the purpose
615//!   let dangerous = std::path::Path::new(safe_path.interop_path());
616//!   let also_bad = std::path::PathBuf::from(safe_path.interop_path());
617//!   
618//!   // ✅ CORRECT: Use interop_path() directly for external APIs
619//!   # fn some_external_api<P: AsRef<std::path::Path>>(_path: P) {}
620//!   some_external_api(safe_path.interop_path()); // AsRef<Path> satisfied
621//!   
622//!   // ✅ CORRECT: Use our secure operations
623//!   let child = safe_path.strict_join("subfile.txt")?;
624//!   # Ok::<(), Box<dyn std::error::Error>>(())
625//!   ```
626//! - **NEVER use `.interop_path().to_string_lossy()` for display purposes**.
627//!   This mixes interop concerns with display concerns. Use proper display methods:
628//!   ```rust,no_run
629//!   # use strict_path::*;
630//!   # let restriction = PathBoundary::<()>::try_new(".").unwrap();
631//!   # let safe_path = restriction.strict_join("file.txt").unwrap();
632//!   // ❌ ANTI-PATTERN: Wrong method for display
633//!   println!("{}", safe_path.interop_path().to_string_lossy());
634//!   
635//!   // ✅ CORRECT: Use proper display methods
636//!   println!("{}", safe_path.strictpath_display());
637//!   # Ok::<(), Box<dyn std::error::Error>>(())
638//!   ```
639//!   
640//!   ### Tell‑offs and fixes
641//!   - Validating only constants → validate real external segments (HTTP/DB/manifest/archive entries); use `boundary.interop_path()` for root discovery.
642//!   - Constructing boundaries/roots inside helpers → accept `&PathBoundary`/`&VirtualRoot` and the untrusted segment, or a `&StrictPath`/`&VirtualPath`.
643//!   - Wrapping secure types (`Path::new(sp.interop_path())`) → pass `interop_path()` directly.
644//!   - `interop_path().as_ref()` or `as_unvirtual().interop_path()` → `interop_path()` is enough; both `VirtualRoot`/`VirtualPath` expose it.
645//!   - Using std path ops on leaked values → use `strict_join`/`virtual_join`, `strictpath_parent`/`virtualpath_parent`.
646//!   - Raw `&str` parameters for safe helpers → take `&StrictPath<_>`/`&VirtualPath<_>` or (boundary/root + segment).
647//!   - Do not leak raw `Path`/`PathBuf` from `StrictPath` or `VirtualPath`.
648//!     Use `interop_path()` when an external API needs `AsRef<Path>`.
649//! - Do not call `Path::join`/`Path::parent` on leaked paths — they ignore PathBoundary/virtual semantics.
650//!   Use `strict_join`/`strictpath_parent` and `virtual_join`/`virtualpath_parent`.
651//! - Avoid `.unvirtual()`/`.unstrict()` unless you explicitly need ownership for the specific type.
652//!   Prefer borrowing with `interop_path()` for interop.
653//! - Virtual strings are rooted. For UI/logging, use `vp.virtualpath_display()` or `vp.virtualpath_display().to_string()`.
654//!   No borrowed `&str` accessors are exposed for virtual paths.
655//! - Creating a restriction: `PathBoundary::try_new(..)` requires the directory to exist.
656//!   Use `PathBoundary::try_new_create(..)` if it may be missing.
657//! - Windows: 8.3 short names (e.g., `PROGRA~1`) are rejected to avoid ambiguous resolution.
658//! - Markers matter. Functions should take `StrictPath<MyMarker>` for their domain to prevent cross-PathBoundary mixing.
659//!
660//! ## Escape Hatches and Best Practices
661//!
662//! Prefer passing references to the inner system path instead of taking ownership:
663//! - If an external API accepts `AsRef<Path>`, pass `strict_path.interop_path()`.
664//! - Avoid `.unstrict()` unless you explicitly need an owned `PathBuf`.
665//!
666//! ```rust
667//! # use strict_path::PathBoundary;
668//! # fn external_api<P: AsRef<std::path::Path>>(_p: P) {}
669//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
670//! let restriction = PathBoundary::try_new_create("./safe")?;
671//! let jp = restriction.strict_join("file.txt")?;
672//!
673//! // Preferred: borrow as &OsStr (implements AsRef<Path>)
674//! external_api(jp.interop_path());
675//!
676//! // Escape hatches (use sparingly):
677//! let owned: std::path::PathBuf = jp.clone().unstrict();
678//! let v: strict_path::VirtualPath = jp.clone().virtualize();
679//! let back: strict_path::StrictPath = v.clone().unvirtual();
680//! let owned_again: std::path::PathBuf = v.unvirtual().unstrict();
681//! # // Cleanup created PathBoundary directory for doctest hygiene
682//! # let root_cleanup: strict_path::StrictPath = strict_path::StrictPath::with_boundary("./safe")?;
683//! # root_cleanup.remove_dir_all().ok();
684//! # Ok(()) }
685//! ```
686//!
687//! ## API Reference (Concise)
688//!
689//! For a minimal, copy-pastable guide to the API (optimized for both humans and LLMs),
690//! see the repository reference:
691//! <https://github.com/DK26/strict-path-rs/blob/main/LLM_API_REFERENCE.md>
692//!
693//! This link is provided here so readers coming from docs.rs can easily discover it.
694#![forbid(unsafe_code)]
695
696pub mod error;
697pub mod path;
698pub mod validator;
699#[cfg(feature = "serde")]
700pub mod serde_ext {
701    //! Serde helpers and notes.
702    //!
703    //! Built‑in `Serialize` (feature `serde`):
704    //! - `StrictPath` → system path string
705    //! - `VirtualPath` → virtual root string (e.g., "/a/b.txt")
706    //!
707    //! Deserialization requires context (a `PathBoundary` or `VirtualRoot`). Use the context helpers
708    //! below to deserialize with context, or deserialize to `String` and validate explicitly.
709    //!
710    //! Example: Deserialize a single `StrictPath` with context
711    //! ```rust
712    //! use strict_path::{PathBoundary, StrictPath};
713    //! use strict_path::serde_ext::WithBoundary;
714    //! use serde::de::DeserializeSeed;
715    //! # fn main() -> Result<(), Box<dyn std::error::Error>> {
716    //! # let td = tempfile::tempdir()?;
717    //! let boundary: PathBoundary = PathBoundary::try_new(td.path())?;
718    //! let mut de = serde_json::Deserializer::from_str("\"a/b.txt\"");
719    //! let jp: StrictPath = WithBoundary(&boundary).deserialize(&mut de)?;
720    //! // OS-agnostic assertion: file name should be "b.txt"
721    //! assert_eq!(jp.strictpath_file_name().unwrap().to_string_lossy(), "b.txt");
722    //! # Ok(()) }
723    //! ```
724    //!
725    //! Example: Deserialize a single `VirtualPath` with context
726    //! ```rust
727    //! use strict_path::{VirtualPath, VirtualRoot};
728    //! use strict_path::serde_ext::WithVirtualRoot;
729    //! use serde::de::DeserializeSeed;
730    //! # fn main() -> Result<(), Box<dyn std::error::Error>> {
731    //! # let td = tempfile::tempdir()?;
732    //! let vroot: VirtualRoot = VirtualRoot::try_new(td.path())?;
733    //! let mut de = serde_json::Deserializer::from_str("\"a/b.txt\"");
734    //! let vp: VirtualPath = WithVirtualRoot(&vroot).deserialize(&mut de)?;
735    //! assert_eq!(vp.virtualpath_display().to_string(), "/a/b.txt");
736    //! # Ok(()) }
737    //! ```
738
739    use crate::{
740        path::strict_path::StrictPath, path::virtual_path::VirtualPath,
741        validator::virtual_root::VirtualRoot, PathBoundary,
742    };
743    use serde::de::DeserializeSeed;
744    use serde::Deserialize;
745
746    /// Deserialize a `StrictPath` with PathBoundary context.
747    pub struct WithBoundary<'a, Marker>(pub &'a PathBoundary<Marker>);
748
749    impl<'a, 'de, Marker> DeserializeSeed<'de> for WithBoundary<'a, Marker> {
750        type Value = StrictPath<Marker>;
751        fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
752        where
753            D: serde::Deserializer<'de>,
754        {
755            let s = String::deserialize(deserializer)?;
756            self.0.strict_join(s).map_err(serde::de::Error::custom)
757        }
758    }
759
760    /// Deserialize a `VirtualPath` with virtual root context.
761    pub struct WithVirtualRoot<'a, Marker>(pub &'a VirtualRoot<Marker>);
762
763    impl<'a, 'de, Marker> DeserializeSeed<'de> for WithVirtualRoot<'a, Marker> {
764        type Value = VirtualPath<Marker>;
765        fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
766        where
767            D: serde::Deserializer<'de>,
768        {
769            let s = String::deserialize(deserializer)?;
770            self.0.virtual_join(s).map_err(serde::de::Error::custom)
771        }
772    }
773}
774
775// Public exports
776pub use error::StrictPathError;
777pub use path::{strict_path::StrictPath, virtual_path::VirtualPath};
778pub use validator::path_boundary::PathBoundary;
779pub use validator::virtual_root::VirtualRoot;
780
781/// Result type alias for this crate's operations.
782pub type Result<T> = std::result::Result<T, StrictPathError>;
783
784#[cfg(test)]
785mod tests;