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
mod display;
mod fs;
mod iter;
mod links;
mod traits;

pub use display::VirtualPathDisplay;
pub use iter::VirtualReadDir;

// Content copied from original src/path/virtual_path.rs
use crate::error::StrictPathError;
use crate::path::strict_path::StrictPath;
use crate::validator::path_history::{Canonicalized, PathHistory};
use crate::PathBoundary;
use crate::Result;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};

/// SUMMARY:
/// Hold a user‑facing path clamped to a virtual root (`"/"`) over a `PathBoundary`.
///
/// DETAILS:
/// `virtualpath_display()` shows rooted, forward‑slashed paths (e.g., `"/a/b.txt"`).
/// Use virtual manipulation methods to compose paths while preserving clamping, then convert to
/// `StrictPath` with `unvirtual()` for system‑facing I/O.
#[derive(Clone)]
pub struct VirtualPath<Marker = ()> {
    pub(crate) inner: StrictPath<Marker>,
    pub(crate) virtual_path: PathBuf,
}

#[inline]
fn clamp<Marker, H>(
    restriction: &PathBoundary<Marker>,
    anchored: PathHistory<(H, Canonicalized)>,
) -> crate::Result<crate::path::strict_path::StrictPath<Marker>> {
    restriction.strict_join(anchored.into_inner())
}

impl<Marker> VirtualPath<Marker> {
    /// SUMMARY:
    /// Create the virtual root (`"/"`) for the given filesystem root.
    pub fn with_root<P: AsRef<Path>>(root: P) -> Result<Self> {
        let vroot = crate::validator::virtual_root::VirtualRoot::try_new(root)?;
        vroot.into_virtualpath()
    }

    /// SUMMARY:
    /// Create the virtual root, creating the filesystem root if missing.
    pub fn with_root_create<P: AsRef<Path>>(root: P) -> Result<Self> {
        let vroot = crate::validator::virtual_root::VirtualRoot::try_new_create(root)?;
        vroot.into_virtualpath()
    }

    #[inline]
    pub(crate) fn new(strict_path: StrictPath<Marker>) -> Self {
        fn compute_virtual<Marker>(
            system_path: &std::path::Path,
            restriction: &crate::PathBoundary<Marker>,
        ) -> std::path::PathBuf {
            use std::ffi::OsString;
            use std::path::Component;

            #[cfg(windows)]
            fn strip_verbatim(p: &std::path::Path) -> std::path::PathBuf {
                let s = p.as_os_str().to_string_lossy();
                if let Some(trimmed) = s.strip_prefix("\\\\?\\") {
                    return std::path::PathBuf::from(trimmed);
                }
                if let Some(trimmed) = s.strip_prefix("\\\\.\\") {
                    return std::path::PathBuf::from(trimmed);
                }
                std::path::PathBuf::from(s.to_string())
            }

            #[cfg(not(windows))]
            fn strip_verbatim(p: &std::path::Path) -> std::path::PathBuf {
                p.to_path_buf()
            }

            let system_norm = strip_verbatim(system_path);
            let jail_norm = strip_verbatim(restriction.path());

            if let Ok(stripped) = system_norm.strip_prefix(&jail_norm) {
                let mut cleaned = std::path::PathBuf::new();
                for comp in stripped.components() {
                    if let Component::Normal(name) = comp {
                        let s = name.to_string_lossy();
                        let cleaned_s = s.replace(['\n', ';'], "_");
                        if cleaned_s == s {
                            cleaned.push(name);
                        } else {
                            cleaned.push(OsString::from(cleaned_s));
                        }
                    }
                }
                return cleaned;
            }

            let mut strictpath_comps: Vec<_> = system_norm
                .components()
                .filter(|c| !matches!(c, Component::Prefix(_) | Component::RootDir))
                .collect();
            let mut boundary_comps: Vec<_> = jail_norm
                .components()
                .filter(|c| !matches!(c, Component::Prefix(_) | Component::RootDir))
                .collect();

            #[cfg(windows)]
            fn comp_eq(a: &Component, b: &Component) -> bool {
                match (a, b) {
                    (Component::Normal(x), Component::Normal(y)) => {
                        x.to_string_lossy().to_ascii_lowercase()
                            == y.to_string_lossy().to_ascii_lowercase()
                    }
                    _ => false,
                }
            }

            #[cfg(not(windows))]
            fn comp_eq(a: &Component, b: &Component) -> bool {
                a == b
            }

            while !strictpath_comps.is_empty()
                && !boundary_comps.is_empty()
                && comp_eq(&strictpath_comps[0], &boundary_comps[0])
            {
                strictpath_comps.remove(0);
                boundary_comps.remove(0);
            }

            let mut vb = std::path::PathBuf::new();
            for c in strictpath_comps {
                if let Component::Normal(name) = c {
                    let s = name.to_string_lossy();
                    let cleaned = s.replace(['\n', ';'], "_");
                    if cleaned == s {
                        vb.push(name);
                    } else {
                        vb.push(OsString::from(cleaned));
                    }
                }
            }
            vb
        }

        let virtual_path = compute_virtual(strict_path.path(), strict_path.boundary());

        Self {
            inner: strict_path,
            virtual_path,
        }
    }

    /// SUMMARY:
    /// Convert this `VirtualPath` back into a system‑facing `StrictPath`.
    #[inline]
    pub fn unvirtual(self) -> StrictPath<Marker> {
        self.inner
    }

    /// SUMMARY:
    /// Change the compile-time marker while keeping the virtual and strict views in sync.
    ///
    /// WHEN TO USE:
    /// - After authenticating/authorizing a user and granting them access to a virtual path
    /// - When escalating or downgrading permissions (e.g., ReadOnly → ReadWrite)
    /// - When reinterpreting a path's domain (e.g., TempStorage → UserUploads)
    ///
    /// WHEN NOT TO USE:
    /// - When converting between path types - conversions preserve markers automatically
    /// - When the current marker already matches your needs - no transformation needed
    /// - When you haven't verified authorization - NEVER change markers without checking permissions
    ///
    /// PARAMETERS:
    /// - `_none_`
    ///
    /// RETURNS:
    /// - `VirtualPath<NewMarker>`: Same clamped path encoded with the new marker.
    ///
    /// ERRORS:
    /// - `_none_`
    ///
    /// SECURITY:
    /// This method performs no permission checks. Only elevate markers after verifying real
    /// authorization out-of-band.
    ///
    /// EXAMPLE:
    /// ```rust
    /// # use strict_path::VirtualPath;
    /// # struct GuestAccess;
    /// # struct UserAccess;
    /// # let root_dir = std::env::temp_dir().join("virtual-change-marker-example");
    /// # std::fs::create_dir_all(&root_dir)?;
    /// # let guest_root: VirtualPath<GuestAccess> = VirtualPath::with_root(&root_dir)?;
    /// // Simulated authorization: verify user credentials before granting access
    /// fn grant_user_access(user_token: &str, path: VirtualPath<GuestAccess>) -> Option<VirtualPath<UserAccess>> {
    ///     if user_token == "valid-token-12345" {
    ///         Some(path.change_marker())  // ✅ Only after token validation
    ///     } else {
    ///         None  // ❌ Invalid token
    ///     }
    /// }
    ///
    /// // Untrusted input from request/CLI/config/etc.
    /// let requested_file = "docs/readme.md";
    /// let guest_path: VirtualPath<GuestAccess> = guest_root.virtual_join(requested_file)?;
    /// let user_path = grant_user_access("valid-token-12345", guest_path).expect("authorized");
    /// assert_eq!(user_path.virtualpath_display().to_string(), "/docs/readme.md");
    /// # std::fs::remove_dir_all(&root_dir)?;
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// **Type Safety Guarantee:**
    ///
    /// The following code **fails to compile** because you cannot pass a path with one marker
    /// type to a function expecting a different marker type. This compile-time check enforces
    /// that permission changes are explicit and cannot be bypassed accidentally.
    ///
    /// ```compile_fail
    /// # use strict_path::VirtualPath;
    /// # struct GuestAccess;
    /// # struct EditorAccess;
    /// # let root_dir = std::env::temp_dir().join("virtual-change-marker-deny");
    /// # std::fs::create_dir_all(&root_dir).unwrap();
    /// # let guest_root: VirtualPath<GuestAccess> = VirtualPath::with_root(&root_dir).unwrap();
    /// fn require_editor(_: VirtualPath<EditorAccess>) {}
    /// let guest_file = guest_root.virtual_join("docs/manual.txt").unwrap();
    /// // ❌ Compile error: expected `VirtualPath<EditorAccess>`, found `VirtualPath<GuestAccess>`
    /// require_editor(guest_file);
    /// ```
    #[inline]
    pub fn change_marker<NewMarker>(self) -> VirtualPath<NewMarker> {
        let VirtualPath {
            inner,
            virtual_path,
        } = self;

        VirtualPath {
            inner: inner.change_marker(),
            virtual_path,
        }
    }

    /// SUMMARY:
    /// Consume and return the `VirtualRoot` for its boundary (no directory creation).
    ///
    /// RETURNS:
    /// - `Result<VirtualRoot<Marker>>`: Virtual root anchored at the strict path's directory.
    ///
    /// ERRORS:
    /// - `StrictPathError::InvalidRestriction`: Propagated from `try_into_boundary` when the
    ///   strict path does not exist or is not a directory.
    #[inline]
    pub fn try_into_root(self) -> Result<crate::validator::virtual_root::VirtualRoot<Marker>> {
        Ok(self.inner.try_into_boundary()?.virtualize())
    }

    /// SUMMARY:
    /// Consume and return a `VirtualRoot`, creating the underlying directory if missing.
    ///
    /// RETURNS:
    /// - `Result<VirtualRoot<Marker>>`: Virtual root anchored at the strict path's directory
    ///   (created if necessary).
    ///
    /// ERRORS:
    /// - `StrictPathError::InvalidRestriction`: Propagated from `try_into_boundary` or directory
    ///   creation failures wrapped in `InvalidRestriction`.
    #[inline]
    pub fn try_into_root_create(
        self,
    ) -> Result<crate::validator::virtual_root::VirtualRoot<Marker>> {
        let strict_path = self.inner;
        let validated_dir = strict_path.try_into_boundary_create()?;
        Ok(validated_dir.virtualize())
    }

    /// SUMMARY:
    /// Borrow the underlying system‑facing `StrictPath` (no allocation).
    #[inline]
    pub fn as_unvirtual(&self) -> &StrictPath<Marker> {
        &self.inner
    }

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

    /// SUMMARY:
    /// Join a virtual path segment (virtual semantics) and re‑validate within the same restriction.
    ///
    /// DETAILS:
    /// Applies virtual path clamping: absolute paths are interpreted relative to the virtual root,
    /// and traversal attempts are clamped to prevent escaping the boundary. This method maintains
    /// the security guarantee that all `VirtualPath` instances stay within their virtual root.
    ///
    /// PARAMETERS:
    /// - `path` (`impl AsRef<Path>`): Path segment to join. Absolute paths are clamped to virtual root.
    ///
    /// RETURNS:
    /// - `Result<VirtualPath<Marker>>`: New virtual path within the same restriction.
    ///
    /// EXAMPLE:
    /// ```rust
    /// # use strict_path::VirtualRoot;
    /// # let td = tempfile::tempdir().unwrap();
    /// let vroot: VirtualRoot = VirtualRoot::try_new_create(td.path())?;
    /// let base = vroot.virtual_join("data")?;
    ///
    /// // Absolute paths are clamped to virtual root
    /// let abs = base.virtual_join("/etc/config")?;
    /// assert_eq!(abs.virtualpath_display().to_string(), "/etc/config");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[inline]
    pub fn virtual_join<P: AsRef<Path>>(&self, path: P) -> Result<Self> {
        // Compose candidate in virtual space (do not pre-normalize lexically to preserve symlink semantics)
        let candidate = self.virtual_path.join(path.as_ref());
        let anchored = crate::validator::path_history::PathHistory::new(candidate)
            .canonicalize_anchored(self.inner.boundary())?;
        let boundary_path = clamp(self.inner.boundary(), anchored)?;
        Ok(VirtualPath::new(boundary_path))
    }

    // No local clamping helpers; virtual flows should route through
    // PathHistory::virtualize_to_jail + PathBoundary::strict_join to avoid drift.

    /// SUMMARY:
    /// Return the parent virtual path, or `None` at the virtual root.
    pub fn virtualpath_parent(&self) -> Result<Option<Self>> {
        match self.virtual_path.parent() {
            Some(parent_virtual_path) => {
                let anchored = crate::validator::path_history::PathHistory::new(
                    parent_virtual_path.to_path_buf(),
                )
                .canonicalize_anchored(self.inner.boundary())?;
                let validated_path = clamp(self.inner.boundary(), anchored)?;
                Ok(Some(VirtualPath::new(validated_path)))
            }
            None => Ok(None),
        }
    }

    /// SUMMARY:
    /// Return a new virtual path with file name changed, preserving clamping.
    #[inline]
    pub fn virtualpath_with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> Result<Self> {
        let candidate = self.virtual_path.with_file_name(file_name);
        let anchored = crate::validator::path_history::PathHistory::new(candidate)
            .canonicalize_anchored(self.inner.boundary())?;
        let validated_path = clamp(self.inner.boundary(), anchored)?;
        Ok(VirtualPath::new(validated_path))
    }

    /// SUMMARY:
    /// Return a new virtual path with the extension changed, preserving clamping.
    pub fn virtualpath_with_extension<S: AsRef<OsStr>>(&self, extension: S) -> Result<Self> {
        if self.virtual_path.file_name().is_none() {
            return Err(StrictPathError::path_escapes_boundary(
                self.virtual_path.clone(),
                self.inner.boundary().path().to_path_buf(),
            ));
        }

        let candidate = self.virtual_path.with_extension(extension);
        let anchored = crate::validator::path_history::PathHistory::new(candidate)
            .canonicalize_anchored(self.inner.boundary())?;
        let validated_path = clamp(self.inner.boundary(), anchored)?;
        Ok(VirtualPath::new(validated_path))
    }

    /// SUMMARY:
    /// Return the file name component of the virtual path, if any.
    #[inline]
    pub fn virtualpath_file_name(&self) -> Option<&OsStr> {
        self.virtual_path.file_name()
    }

    /// SUMMARY:
    /// Return the file stem of the virtual path, if any.
    #[inline]
    pub fn virtualpath_file_stem(&self) -> Option<&OsStr> {
        self.virtual_path.file_stem()
    }

    /// SUMMARY:
    /// Return the extension of the virtual path, if any.
    #[inline]
    pub fn virtualpath_extension(&self) -> Option<&OsStr> {
        self.virtual_path.extension()
    }

    /// SUMMARY:
    /// Return `true` if the virtual path starts with the given prefix (virtual semantics).
    #[inline]
    pub fn virtualpath_starts_with<P: AsRef<Path>>(&self, p: P) -> bool {
        self.virtual_path.starts_with(p)
    }

    /// SUMMARY:
    /// Return `true` if the virtual path ends with the given suffix (virtual semantics).
    #[inline]
    pub fn virtualpath_ends_with<P: AsRef<Path>>(&self, p: P) -> bool {
        self.virtual_path.ends_with(p)
    }

    /// SUMMARY:
    /// Return a Display wrapper that shows a rooted virtual path (e.g., `"/a/b.txt").
    #[inline]
    pub fn virtualpath_display(&self) -> VirtualPathDisplay<'_, Marker> {
        VirtualPathDisplay(self)
    }

    /// SUMMARY:
    /// Return `true` if the underlying system path exists.
    #[inline]
    pub fn exists(&self) -> bool {
        self.inner.exists()
    }

    /// SUMMARY:
    /// Return `true` if the underlying system path is a file.
    #[inline]
    pub fn is_file(&self) -> bool {
        self.inner.is_file()
    }

    /// SUMMARY:
    /// Return `true` if the underlying system path is a directory.
    #[inline]
    pub fn is_dir(&self) -> bool {
        self.inner.is_dir()
    }

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

    /// SUMMARY:
    /// Read the file contents as `String` from the underlying system path.
    #[inline]
    pub fn read_to_string(&self) -> std::io::Result<String> {
        self.inner.read_to_string()
    }

    /// SUMMARY:
    /// Read raw bytes from the underlying system path.
    #[inline]
    pub fn read(&self) -> std::io::Result<Vec<u8>> {
        self.inner.read()
    }

    /// SUMMARY:
    /// Return metadata for the underlying system path without following symlinks.
    #[inline]
    pub fn symlink_metadata(&self) -> std::io::Result<std::fs::Metadata> {
        self.inner.symlink_metadata()
    }

    /// SUMMARY:
    /// Set permissions on the file or directory at this path.
    ///
    /// PARAMETERS:
    /// - `perm` (`std::fs::Permissions`): The permissions to set.
    ///
    /// RETURNS:
    /// - `io::Result<()>`: Success or I/O error.
    #[inline]
    pub fn set_permissions(&self, perm: std::fs::Permissions) -> std::io::Result<()> {
        self.inner.set_permissions(perm)
    }

    /// SUMMARY:
    /// Check if the path exists, returning an error on permission issues.
    ///
    /// DETAILS:
    /// Unlike `exists()` which returns `false` on permission errors, this method
    /// distinguishes between "path does not exist" (`Ok(false)`) and "cannot check
    /// due to permission error" (`Err(...)`).
    ///
    /// RETURNS:
    /// - `Ok(true)`: Path exists
    /// - `Ok(false)`: Path does not exist
    /// - `Err(...)`: Permission or other I/O error prevented the check
    #[inline]
    pub fn try_exists(&self) -> std::io::Result<bool> {
        self.inner.try_exists()
    }

    /// SUMMARY:
    /// Create an empty file if it doesn't exist, or update the modification time if it does.
    ///
    /// DETAILS:
    /// This is a convenience method combining file creation and mtime update.
    /// Uses `OpenOptions` with `create(true).write(true)` which creates the file
    /// if missing or opens it for writing if it exists, updating mtime on close.
    ///
    /// RETURNS:
    /// - `io::Result<()>`: Success or I/O error.
    pub fn touch(&self) -> std::io::Result<()> {
        self.inner.touch()
    }

    /// SUMMARY:
    /// Read directory entries (discovery). Re‑join names with `virtual_join(...)` to preserve clamping.
    pub fn read_dir(&self) -> std::io::Result<std::fs::ReadDir> {
        self.inner.read_dir()
    }

    /// SUMMARY:
    /// Read directory entries as validated `VirtualPath` values (auto re-joins each entry).
    ///
    /// DETAILS:
    /// Unlike `read_dir()` which returns raw `std::fs::DirEntry`, this method automatically
    /// validates each directory entry through `virtual_join()`, returning an iterator of
    /// `Result<VirtualPath<Marker>>`. This eliminates the need for manual re-validation loops
    /// while preserving the virtual path semantics.
    ///
    /// PARAMETERS:
    /// - _none_
    ///
    /// RETURNS:
    /// - `io::Result<VirtualReadDir<Marker>>`: Iterator yielding validated `VirtualPath` entries.
    ///
    /// ERRORS:
    /// - `std::io::Error`: If the directory cannot be read.
    /// - Each yielded item may also be `Err` if validation fails for that entry.
    ///
    /// EXAMPLE:
    /// ```rust
    /// # use strict_path::{VirtualRoot, VirtualPath};
    /// # let temp = tempfile::tempdir()?;
    /// # let vroot: VirtualRoot = VirtualRoot::try_new(temp.path())?;
    /// # let dir = vroot.virtual_join("uploads")?;
    /// # dir.create_dir_all()?;
    /// # vroot.virtual_join("uploads/file1.txt")?.write("a")?;
    /// # vroot.virtual_join("uploads/file2.txt")?.write("b")?;
    /// // Iterate with automatic validation
    /// for entry in dir.virtual_read_dir()? {
    ///     let child: VirtualPath = entry?;
    ///     println!("{}", child.virtualpath_display());
    /// }
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    pub fn virtual_read_dir(&self) -> std::io::Result<VirtualReadDir<'_, Marker>> {
        let inner = std::fs::read_dir(self.inner.path())?;
        Ok(VirtualReadDir {
            inner,
            parent: self,
        })
    }
}