strict-path 0.1.2

Handle paths from external or unknown sources securely. Defends against 19+ real-world CVEs including symlinks, Windows 8.3 short names, and encoding tricks and exploits.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
// Content copied from original src/validator/virtual_root.rs
use crate::path::virtual_path::VirtualPath;
use crate::validator::path_history::PathHistory;
use crate::PathBoundary;
use crate::Result;
use std::marker::PhantomData;
use std::path::Path;

/// SUMMARY:
/// Provide a user‑facing virtual root that produces `VirtualPath` values clamped to a boundary.
#[derive(Clone)]
pub struct VirtualRoot<Marker = ()> {
    pub(crate) root: PathBoundary<Marker>,
    pub(crate) _marker: PhantomData<Marker>,
}

impl<Marker> VirtualRoot<Marker> {
    // no extra constructors; use PathBoundary::virtualize() or VirtualRoot::try_new
    /// SUMMARY:
    /// Create a `VirtualRoot` from an existing directory.
    ///
    /// PARAMETERS:
    /// - `root_path` (`AsRef<Path>`): Existing directory to anchor the virtual root.
    ///
    /// RETURNS:
    /// - `Result<VirtualRoot<Marker>>`: New virtual root with clamped operations.
    ///
    /// ERRORS:
    /// - `StrictPathError::InvalidRestriction`: Root invalid or cannot be canonicalized.
    ///
    /// EXAMPLE:
    /// ```rust
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use strict_path::VirtualRoot;
    /// let vroot = VirtualRoot::<()>::try_new("./data")?;
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn try_new<P: AsRef<Path>>(root_path: P) -> Result<Self> {
        let root = PathBoundary::try_new(root_path)?;
        Ok(Self {
            root,
            _marker: PhantomData,
        })
    }

    /// SUMMARY:
    /// Return filesystem metadata for the underlying root directory.
    #[inline]
    pub fn metadata(&self) -> std::io::Result<std::fs::Metadata> {
        self.root.metadata()
    }

    /// SUMMARY:
    /// Consume this virtual root and return the rooted `VirtualPath` ("/").
    ///
    /// PARAMETERS:
    /// - _none_
    ///
    /// RETURNS:
    /// - `Result<VirtualPath<Marker>>`: Virtual root path clamped to this boundary.
    ///
    /// ERRORS:
    /// - `StrictPathError::PathResolutionError`: Canonicalization fails (root removed or inaccessible).
    /// - `StrictPathError::PathEscapesBoundary`: Root moved outside the boundary between checks.
    ///
    /// EXAMPLE:
    /// ```rust
    /// # use strict_path::{VirtualPath, VirtualRoot};
    /// # let root = std::env::temp_dir().join("into-virtualpath-example");
    /// # std::fs::create_dir_all(&root)?;
    /// let vroot: VirtualRoot = VirtualRoot::try_new(&root)?;
    /// let root_virtual: VirtualPath = vroot.into_virtualpath()?;
    /// assert_eq!(root_virtual.virtualpath_display().to_string(), "/");
    /// # std::fs::remove_dir_all(&root)?;
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    #[inline]
    pub fn into_virtualpath(self) -> Result<VirtualPath<Marker>> {
        let strict_root = self.root.into_strictpath()?;
        Ok(strict_root.virtualize())
    }

    /// SUMMARY:
    /// Consume this virtual root and substitute a new marker type.
    ///
    /// DETAILS:
    /// Mirrors [`crate::PathBoundary::change_marker`], [`crate::StrictPath::change_marker`], and
    /// [`crate::VirtualPath::change_marker`]. Use this when encoding proven authorization
    /// into the type system (e.g., after validating a user's permissions). The
    /// consumption makes marker changes explicit during code review.
    ///
    /// PARAMETERS:
    /// - `NewMarker` (type parameter): Marker to associate with the virtual root.
    ///
    /// RETURNS:
    /// - `VirtualRoot<NewMarker>`: Same underlying root, rebranded with `NewMarker`.
    ///
    /// EXAMPLE:
    /// ```rust
    /// # use strict_path::VirtualRoot;
    /// # let root_dir = std::env::temp_dir().join("vroot-change-marker-example");
    /// # std::fs::create_dir_all(&root_dir)?;
    /// struct UserFiles;
    /// struct ReadOnly;
    /// struct ReadWrite;
    ///
    /// let read_root: VirtualRoot<(UserFiles, ReadOnly)> = VirtualRoot::try_new(&root_dir)?;
    ///
    /// // After authorization check...
    /// let write_root: VirtualRoot<(UserFiles, ReadWrite)> = read_root.change_marker();
    /// # std::fs::remove_dir_all(&root_dir)?;
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    #[inline]
    pub fn change_marker<NewMarker>(self) -> VirtualRoot<NewMarker> {
        let VirtualRoot { root, .. } = self;

        VirtualRoot {
            root: root.change_marker(),
            _marker: PhantomData,
        }
    }

    /// SUMMARY:
    /// Create a symbolic link at `link_path` pointing to this root's underlying directory.
    ///
    /// DETAILS:
    /// `link_path` is interpreted in the virtual dimension and resolved via `virtual_join()`
    /// so that absolute virtual paths ("/links/a") are clamped within this virtual root and
    /// relative paths are resolved relative to the virtual root.
    pub fn virtual_symlink<P: AsRef<Path>>(&self, link_path: P) -> std::io::Result<()> {
        // Resolve the link location in virtual space first (clamps/anchors under this root)
        let link_ref = link_path.as_ref();
        let validated_link = self
            .virtual_join(link_ref)
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;

        // Obtain the strict target for the root directory
        let root = self
            .root
            .clone()
            .into_strictpath()
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;

        root.strict_symlink(validated_link.as_unvirtual().path())
    }

    /// SUMMARY:
    /// Create a hard link at `link_path` pointing to this root's underlying directory.
    ///
    /// DETAILS:
    /// The link location is resolved via `virtual_join()` to clamp/anchor within this root.
    /// Note: Most platforms forbid directory hard links; expect an error from the OS.
    pub fn virtual_hard_link<P: AsRef<Path>>(&self, link_path: P) -> std::io::Result<()> {
        let link_ref = link_path.as_ref();
        let validated_link = self
            .virtual_join(link_ref)
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;

        let root = self
            .root
            .clone()
            .into_strictpath()
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;

        root.strict_hard_link(validated_link.as_unvirtual().path())
    }

    /// SUMMARY:
    /// Create a Windows NTFS directory junction at `link_path` pointing to this virtual root's directory.
    ///
    /// DETAILS:
    /// - Windows-only and behind the `junctions` feature.
    #[cfg(all(windows, feature = "junctions"))]
    pub fn virtual_junction<P: AsRef<Path>>(&self, link_path: P) -> std::io::Result<()> {
        let link_ref = link_path.as_ref();
        let validated_link = self
            .virtual_join(link_ref)
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;

        let root = self
            .root
            .clone()
            .into_strictpath()
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;

        root.strict_junction(validated_link.as_unvirtual().path())
    }

    /// SUMMARY:
    /// Read directory entries at the virtual root (discovery). Re‑join names through virtual/strict APIs before I/O.
    #[inline]
    pub fn read_dir(&self) -> std::io::Result<std::fs::ReadDir> {
        self.root.read_dir()
    }

    /// SUMMARY:
    /// Iterate directory entries at the virtual root, yielding validated `VirtualPath` values.
    ///
    /// DETAILS:
    /// Unlike `read_dir()` which returns raw `std::fs::DirEntry` values requiring manual
    /// re-validation, this method yields `VirtualPath` entries directly. Each entry is
    /// automatically validated through `virtual_join()` so you can use it immediately
    /// for I/O operations without additional validation.
    ///
    /// RETURNS:
    /// - `io::Result<VirtualRootReadDir<Marker>>`: Iterator over validated `VirtualPath` entries.
    ///
    /// EXAMPLE:
    /// ```rust
    /// use strict_path::VirtualRoot;
    ///
    /// # let temp = tempfile::tempdir()?;
    /// let vroot: VirtualRoot = VirtualRoot::try_new(temp.path())?;
    /// # vroot.virtual_join("file.txt")?.write("test")?;
    ///
    /// // Auto-validated iteration - no manual re-join needed!
    /// for entry in vroot.virtual_read_dir()? {
    ///     let child = entry?;
    ///     println!("Virtual: {}", child.virtualpath_display());
    /// }
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    #[inline]
    pub fn virtual_read_dir(&self) -> std::io::Result<VirtualRootReadDir<'_, Marker>> {
        Ok(VirtualRootReadDir {
            inner: self.root.read_dir()?,
            vroot: self,
        })
    }

    /// SUMMARY:
    /// Remove the underlying root directory (non‑recursive); fails if not empty.
    #[inline]
    pub fn remove_dir(&self) -> std::io::Result<()> {
        self.root.remove_dir()
    }

    /// SUMMARY:
    /// Recursively remove the underlying root directory and all its contents.
    #[inline]
    pub fn remove_dir_all(&self) -> std::io::Result<()> {
        self.root.remove_dir_all()
    }

    /// SUMMARY:
    /// Ensure the directory exists (create if missing), then return a `VirtualRoot`.
    ///
    /// EXAMPLE:
    /// Uses `AsRef<Path>` for maximum ergonomics, including direct `TempDir` support for clean shadowing patterns:
    /// ```rust
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use strict_path::VirtualRoot;
    /// let vroot = VirtualRoot::<()>::try_new_create("./data")?;
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn try_new_create<P: AsRef<Path>>(root_path: P) -> Result<Self> {
        let root = PathBoundary::try_new_create(root_path)?;
        Ok(Self {
            root,
            _marker: PhantomData,
        })
    }

    /// SUMMARY:
    /// Join a candidate path to this virtual root, producing a clamped `VirtualPath`.
    ///
    /// DETAILS:
    /// This is the security gateway for virtual paths. Absolute paths (starting with `"/"`) are
    /// automatically clamped to the virtual root, ensuring paths cannot escape the sandbox.
    /// For example, `"/etc/config"` becomes `vroot/etc/config`, and traversal attempts like
    /// `"../../../../etc/passwd"` are clamped to `vroot/etc/passwd`. This clamping behavior is
    /// what makes the `virtual_` dimension safe for user-facing operations.
    ///
    /// PARAMETERS:
    /// - `candidate_path` (`AsRef<Path>`): Virtual path to resolve and clamp. Absolute paths
    ///   are interpreted relative to the virtual root, not the system root.
    ///
    /// RETURNS:
    /// - `Result<VirtualPath<Marker>>`: Clamped, validated path within the virtual root.
    ///
    /// ERRORS:
    /// - `StrictPathError::PathResolutionError`, `StrictPathError::PathEscapesBoundary`.
    ///
    /// EXAMPLE:
    /// ```rust
    /// # use strict_path::VirtualRoot;
    /// # let td = tempfile::tempdir().unwrap();
    /// let vroot: VirtualRoot = VirtualRoot::try_new_create(td.path())?;
    ///
    /// // Absolute paths are clamped to virtual root, not system root
    /// let user_input_abs = "/etc/config"; // Untrusted input
    /// let path1 = vroot.virtual_join(user_input_abs)?;
    /// assert_eq!(path1.virtualpath_display().to_string(), "/etc/config");
    ///
    /// // Traversal attempts are also clamped
    /// let attack_input = "../../../etc/passwd"; // Untrusted input
    /// let path2 = vroot.virtual_join(attack_input)?;
    /// assert_eq!(path2.virtualpath_display().to_string(), "/etc/passwd");
    ///
    /// // Both paths are safely within the virtual root on the actual filesystem
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[inline]
    pub fn virtual_join<P: AsRef<Path>>(&self, candidate_path: P) -> Result<VirtualPath<Marker>> {
        // 1) Anchor in virtual space (clamps virtual root and resolves relative parts)
        let user_candidate = candidate_path.as_ref().to_path_buf();
        let anchored = PathHistory::new(user_candidate).canonicalize_anchored(&self.root)?;

        // 2) Boundary-check once against the PathBoundary's canonicalized root (no re-canonicalization)
        let validated = anchored.boundary_check(self.root.stated_path())?;

        // 3) Construct a StrictPath directly and then virtualize
        let jp = crate::path::strict_path::StrictPath::new(
            std::sync::Arc::new(self.root.clone()),
            validated,
        );
        Ok(jp.virtualize())
    }

    /// Returns the underlying path boundary root as a system path.
    #[inline]
    pub(crate) fn path(&self) -> &Path {
        self.root.path()
    }

    /// SUMMARY:
    /// Return the virtual root path as `&OsStr` for unavoidable third-party `AsRef<Path>` interop.
    #[inline]
    pub fn interop_path(&self) -> &std::ffi::OsStr {
        self.root.interop_path()
    }

    /// Returns true if the underlying path boundary root exists.
    #[inline]
    pub fn exists(&self) -> bool {
        self.root.exists()
    }

    /// SUMMARY:
    /// Borrow the underlying `PathBoundary`.
    #[inline]
    pub fn as_unvirtual(&self) -> &PathBoundary<Marker> {
        &self.root
    }

    /// SUMMARY:
    /// Consume this `VirtualRoot` and return the underlying `PathBoundary` (symmetry with `virtualize`).
    #[inline]
    pub fn unvirtual(self) -> PathBoundary<Marker> {
        self.root
    }

    // OS Standard Directory Constructors
    //
    // Creates virtual roots in OS standard directories following platform conventions.
    // Applications see clean virtual paths ("/config.toml") while the system manages
    // the actual location (e.g., "~/.config/myapp/config.toml").
}

impl<Marker> std::fmt::Display for VirtualRoot<Marker> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let display = self.path().display();
        write!(f, "{display}")
    }
}

impl<Marker> AsRef<Path> for VirtualRoot<Marker> {
    fn as_ref(&self) -> &Path {
        self.path()
    }
}

impl<Marker> std::fmt::Debug for VirtualRoot<Marker> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VirtualRoot")
            .field("root", &self.path())
            .field("marker", &std::any::type_name::<Marker>())
            .finish()
    }
}

impl<Marker> Eq for VirtualRoot<Marker> {}

impl<M1, M2> PartialEq<VirtualRoot<M2>> for VirtualRoot<M1> {
    #[inline]
    fn eq(&self, other: &VirtualRoot<M2>) -> bool {
        self.path() == other.path()
    }
}

impl<Marker> std::hash::Hash for VirtualRoot<Marker> {
    #[inline]
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.path().hash(state);
    }
}

impl<Marker> PartialOrd for VirtualRoot<Marker> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<Marker> Ord for VirtualRoot<Marker> {
    #[inline]
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.path().cmp(other.path())
    }
}

impl<M1, M2> PartialEq<crate::PathBoundary<M2>> for VirtualRoot<M1> {
    #[inline]
    fn eq(&self, other: &crate::PathBoundary<M2>) -> bool {
        self.path() == other.path()
    }
}

impl<Marker> PartialEq<std::path::Path> for VirtualRoot<Marker> {
    #[inline]
    fn eq(&self, other: &std::path::Path) -> bool {
        // Compare as virtual root path (always "/")
        // VirtualRoot represents the virtual "/" regardless of underlying system path
        let other_str = other.to_string_lossy();

        #[cfg(windows)]
        let other_normalized = other_str.replace('\\', "/");
        #[cfg(not(windows))]
        let other_normalized = other_str.to_string();

        let normalized_other = if other_normalized.starts_with('/') {
            other_normalized
        } else {
            format!("/{other_normalized}")
        };

        "/" == normalized_other
    }
}

impl<Marker> PartialEq<std::path::PathBuf> for VirtualRoot<Marker> {
    #[inline]
    fn eq(&self, other: &std::path::PathBuf) -> bool {
        self.eq(other.as_path())
    }
}

impl<Marker> PartialEq<&std::path::Path> for VirtualRoot<Marker> {
    #[inline]
    fn eq(&self, other: &&std::path::Path) -> bool {
        self.eq(*other)
    }
}

impl<Marker> PartialOrd<std::path::Path> for VirtualRoot<Marker> {
    #[inline]
    fn partial_cmp(&self, other: &std::path::Path) -> Option<std::cmp::Ordering> {
        // Compare as virtual root path (always "/")
        let other_str = other.to_string_lossy();

        // Handle empty path specially - "/" is greater than ""
        if other_str.is_empty() {
            return Some(std::cmp::Ordering::Greater);
        }

        #[cfg(windows)]
        let other_normalized = other_str.replace('\\', "/");
        #[cfg(not(windows))]
        let other_normalized = other_str.to_string();

        let normalized_other = if other_normalized.starts_with('/') {
            other_normalized
        } else {
            format!("/{other_normalized}")
        };

        Some("/".cmp(&normalized_other))
    }
}

impl<Marker> PartialOrd<&std::path::Path> for VirtualRoot<Marker> {
    #[inline]
    fn partial_cmp(&self, other: &&std::path::Path) -> Option<std::cmp::Ordering> {
        self.partial_cmp(*other)
    }
}

impl<Marker> PartialOrd<std::path::PathBuf> for VirtualRoot<Marker> {
    #[inline]
    fn partial_cmp(&self, other: &std::path::PathBuf) -> Option<std::cmp::Ordering> {
        self.partial_cmp(other.as_path())
    }
}

impl<Marker: Default> std::str::FromStr for VirtualRoot<Marker> {
    type Err = crate::StrictPathError;

    /// Parse a VirtualRoot from a string path for universal ergonomics.
    ///
    /// Creates the directory if it doesn't exist, enabling seamless integration
    /// with any string-parsing context (clap, config files, environment variables, etc.):
    /// ```rust
    /// # use strict_path::VirtualRoot;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let temp_dir = tempfile::tempdir()?;
    /// let virtual_path = temp_dir.path().join("virtual_dir");
    /// let vroot: VirtualRoot<()> = virtual_path.to_string_lossy().parse()?;
    /// assert!(virtual_path.exists());
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    fn from_str(path: &str) -> std::result::Result<Self, Self::Err> {
        Self::try_new_create(path)
    }
}

// ============================================================
// VirtualRootReadDir — Iterator for validated virtual directory entries
// ============================================================

/// SUMMARY:
/// Iterator over directory entries that yields validated `VirtualPath` values.
///
/// DETAILS:
/// Created by `VirtualRoot::virtual_read_dir()`. Each iteration automatically validates
/// the directory entry through `virtual_join()`, so you get `VirtualPath` values directly
/// instead of raw `std::fs::DirEntry` that would require manual re-validation.
///
/// EXAMPLE:
/// ```rust
/// # use strict_path::VirtualRoot;
/// # let temp = tempfile::tempdir()?;
/// let vroot: VirtualRoot = VirtualRoot::try_new(temp.path())?;
/// # vroot.virtual_join("readme.md")?.write("# Docs")?;
/// for entry in vroot.virtual_read_dir()? {
///     let child = entry?;
///     if child.is_file() {
///         println!("Virtual: {}", child.virtualpath_display());
///     }
/// }
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
pub struct VirtualRootReadDir<'a, Marker> {
    inner: std::fs::ReadDir,
    vroot: &'a VirtualRoot<Marker>,
}

impl<Marker> std::fmt::Debug for VirtualRootReadDir<'_, Marker> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VirtualRootReadDir")
            .field("vroot", &"/")
            .finish_non_exhaustive()
    }
}

impl<Marker: Clone> Iterator for VirtualRootReadDir<'_, Marker> {
    type Item = std::io::Result<crate::path::virtual_path::VirtualPath<Marker>>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.inner.next()? {
            Ok(entry) => {
                let file_name = entry.file_name();
                match self.vroot.virtual_join(file_name) {
                    Ok(virtual_path) => Some(Ok(virtual_path)),
                    Err(e) => Some(Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e))),
                }
            }
            Err(e) => Some(Err(e)),
        }
    }
}