strict_path/
lib.rs

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