Skip to main content

strict_path/validator/
path_boundary.rs

1//! `PathBoundary<Marker>` — the security perimeter for validated path operations.
2//!
3//! A `PathBoundary` represents a trusted filesystem directory. All `StrictPath` values
4//! produced through it are guaranteed, at construction time, to resolve inside that
5//! directory. This guarantee is provided by `canonicalize_and_enforce_restriction_boundary`,
6//! which canonicalizes the candidate path (resolving symlinks and `..`) and then verifies
7//! it starts with the canonicalized boundary. Any path that would escape is rejected with
8//! `PathEscapesBoundary` before any I/O occurs.
9use crate::error::StrictPathError;
10use crate::path::strict_path::StrictPath;
11use crate::validator::path_history::*;
12use crate::Result;
13
14use std::io::{Error as IoError, ErrorKind};
15use std::marker::PhantomData;
16use std::path::Path;
17use std::sync::Arc;
18
19/// Canonicalize a candidate path and enforce the `PathBoundary` boundary, returning a `StrictPath`.
20///
21/// # Errors
22///
23/// - `StrictPathError::PathResolutionError`: Canonicalization fails (I/O or resolution error).
24/// - `StrictPathError::PathEscapesBoundary`: Resolved path would escape the boundary.
25///
26/// # Examples
27///
28/// ```rust
29/// # use strict_path::{PathBoundary, Result};
30/// # fn main() -> Result<()> {
31/// let sandbox = PathBoundary::<()>::try_new_create("./sandbox")?;
32/// // Untrusted input from request/CLI/config/etc.
33/// let user_input = "sub/file.txt";
34/// // Use the public API that exercises the same validation pipeline
35/// // as this internal helper.
36/// let file = sandbox.strict_join(user_input)?;
37/// assert!(file.strictpath_display().to_string().contains("sandbox"));
38/// # Ok(())
39/// # }
40/// ```
41pub(crate) fn canonicalize_and_enforce_restriction_boundary<Marker>(
42    path: impl AsRef<Path>,
43    restriction: &PathBoundary<Marker>,
44) -> Result<StrictPath<Marker>> {
45    // Relative paths are anchored to the boundary so they cannot be
46    // interpreted relative to the process CWD (which is outside our control).
47    // Absolute paths are accepted as-is because canonicalization + boundary_check
48    // will still reject any path that resolves outside the boundary.
49    let target_path = if path.as_ref().is_absolute() {
50        path.as_ref().to_path_buf()
51    } else {
52        restriction.path().join(path.as_ref())
53    };
54
55    let canonicalized = PathHistory::<Raw>::new(target_path).canonicalize()?;
56
57    let validated_path = canonicalized.boundary_check(&restriction.path)?;
58
59    Ok(StrictPath::new(
60        Arc::new(restriction.clone()),
61        validated_path,
62    ))
63}
64
65/// A path boundary that serves as the secure foundation for validated path operations.
66///
67/// Represent the trusted filesystem boundary directory for all strict and virtual path
68/// operations. All `StrictPath`/`VirtualPath` values derived from a `PathBoundary` are
69/// guaranteed to remain within this boundary.
70///
71/// # Examples
72///
73/// ```rust
74/// # use strict_path::PathBoundary;
75/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
76/// let data_dir = PathBoundary::<()>::try_new_create("./data")?;
77/// // Untrusted input from request/CLI/config/etc.
78/// let requested_file = "logs/app.log";
79/// let file = data_dir.strict_join(requested_file)?;
80/// let file_display = file.strictpath_display();
81/// println!("{file_display}");
82/// # Ok(())
83/// # }
84/// ```
85#[must_use = "a PathBoundary is validated and ready to enforce path restrictions — call .strict_join() to validate untrusted input, .into_strictpath() to get the boundary path, or pass to functions that accept &PathBoundary<Marker>"]
86pub struct PathBoundary<Marker = ()> {
87    path: Arc<PathHistory<((Raw, Canonicalized), Exists)>>,
88    _marker: PhantomData<Marker>,
89}
90
91impl<Marker> Clone for PathBoundary<Marker> {
92    fn clone(&self) -> Self {
93        Self {
94            path: self.path.clone(),
95            _marker: PhantomData,
96        }
97    }
98}
99
100impl<Marker> Eq for PathBoundary<Marker> {}
101
102impl<M1, M2> PartialEq<PathBoundary<M2>> for PathBoundary<M1> {
103    #[inline]
104    fn eq(&self, other: &PathBoundary<M2>) -> bool {
105        self.path() == other.path()
106    }
107}
108
109impl<Marker> std::hash::Hash for PathBoundary<Marker> {
110    #[inline]
111    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
112        self.path().hash(state);
113    }
114}
115
116impl<Marker> PartialOrd for PathBoundary<Marker> {
117    #[inline]
118    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
119        Some(self.cmp(other))
120    }
121}
122
123impl<Marker> Ord for PathBoundary<Marker> {
124    #[inline]
125    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
126        self.path().cmp(other.path())
127    }
128}
129
130#[cfg(feature = "virtual-path")]
131impl<M1, M2> PartialEq<crate::validator::virtual_root::VirtualRoot<M2>> for PathBoundary<M1> {
132    #[inline]
133    fn eq(&self, other: &crate::validator::virtual_root::VirtualRoot<M2>) -> bool {
134        self.path() == other.path()
135    }
136}
137
138impl<Marker> PartialEq<Path> for PathBoundary<Marker> {
139    #[inline]
140    fn eq(&self, other: &Path) -> bool {
141        self.path() == other
142    }
143}
144
145impl<Marker> PartialEq<std::path::PathBuf> for PathBoundary<Marker> {
146    #[inline]
147    fn eq(&self, other: &std::path::PathBuf) -> bool {
148        self.eq(other.as_path())
149    }
150}
151
152impl<Marker> PartialEq<&std::path::Path> for PathBoundary<Marker> {
153    #[inline]
154    fn eq(&self, other: &&std::path::Path) -> bool {
155        self.eq(*other)
156    }
157}
158
159impl<Marker> PathBoundary<Marker> {
160    /// Creates a new `PathBoundary` anchored at `restriction_path` (which must already exist and be a directory).
161    ///
162    /// Create a boundary anchored at an existing directory (must exist and be a directory).
163    ///
164    /// # Errors
165    ///
166    /// - `StrictPathError::InvalidRestriction`: Boundary directory is missing, not a directory, or cannot be canonicalized.
167    ///
168    /// # Examples
169    ///
170    /// ```rust
171    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
172    /// use strict_path::PathBoundary;
173    /// let data_dir = PathBoundary::<()>::try_new("./data")?;
174    /// # Ok(())
175    /// # }
176    /// ```
177    #[must_use = "this returns a Result containing the validated PathBoundary — handle the Result to detect invalid boundary directories"]
178    #[inline]
179    pub fn try_new<P: AsRef<Path>>(restriction_path: P) -> Result<Self> {
180        let restriction_path = restriction_path.as_ref();
181        let raw = PathHistory::<Raw>::new(restriction_path);
182
183        let canonicalized = raw.canonicalize()?;
184
185        let verified_exists = match canonicalized.verify_exists() {
186            Some(path) => path,
187            None => {
188                let io = IoError::new(
189                    ErrorKind::NotFound,
190                    "The specified PathBoundary path does not exist.",
191                );
192                return Err(StrictPathError::invalid_restriction(
193                    restriction_path.to_path_buf(),
194                    io,
195                ));
196            }
197        };
198
199        if !verified_exists.is_dir() {
200            let error = IoError::new(
201                ErrorKind::InvalidInput,
202                "The specified PathBoundary path exists but is not a directory.",
203            );
204            return Err(StrictPathError::invalid_restriction(
205                restriction_path.to_path_buf(),
206                error,
207            ));
208        }
209
210        Ok(Self {
211            path: Arc::new(verified_exists),
212            _marker: PhantomData,
213        })
214    }
215
216    /// Creates the directory if missing, then constructs a new `PathBoundary`.
217    ///
218    /// Ensure the boundary directory exists (create if missing) and construct a new boundary.
219    ///
220    /// # Errors
221    ///
222    /// - `StrictPathError::InvalidRestriction`: Directory creation/canonicalization fails.
223    ///
224    /// # Examples
225    ///
226    /// ```rust
227    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
228    /// use strict_path::PathBoundary;
229    /// let data_dir = PathBoundary::<()>::try_new_create("./data")?;
230    /// # Ok(())
231    /// # }
232    /// ```
233    #[must_use = "this returns a Result containing the validated PathBoundary — handle the Result to detect invalid boundary directories"]
234    pub fn try_new_create<P: AsRef<Path>>(boundary_dir: P) -> Result<Self> {
235        let boundary_path = boundary_dir.as_ref();
236        if !boundary_path.exists() {
237            std::fs::create_dir_all(boundary_path).map_err(|e| {
238                StrictPathError::invalid_restriction(boundary_path.to_path_buf(), e)
239            })?;
240        }
241        Self::try_new(boundary_path)
242    }
243
244    /// Join a candidate path to the boundary and return a validated `StrictPath`.
245    ///
246    /// # Errors
247    ///
248    /// - `StrictPathError::PathResolutionError`, `StrictPathError::PathEscapesBoundary`.
249    #[must_use = "strict_join() validates untrusted input against the boundary — always handle the Result to detect path traversal attacks"]
250    #[inline]
251    pub fn strict_join(&self, candidate_path: impl AsRef<Path>) -> Result<StrictPath<Marker>> {
252        canonicalize_and_enforce_restriction_boundary(candidate_path, self)
253    }
254
255    /// Consume this boundary and substitute a new marker type.
256    ///
257    /// Mirrors [`crate::StrictPath::change_marker`] and [`crate::VirtualPath::change_marker`], enabling
258    /// marker transformation after authorization checks. Use this when encoding proven
259    /// authorization into the type system (e.g., after validating a user's permissions).
260    /// The consumption makes marker changes explicit during code review.
261    ///
262    /// # Examples
263    ///
264    /// ```rust
265    /// # use strict_path::PathBoundary;
266    /// struct ReadOnly;
267    /// struct ReadWrite;
268    ///
269    /// let read_only_dir: PathBoundary<ReadOnly> = PathBoundary::try_new_create("./data")?;
270    ///
271    /// // After authorization check...
272    /// let write_access_dir: PathBoundary<ReadWrite> = read_only_dir.change_marker();
273    /// # Ok::<_, Box<dyn std::error::Error>>(())
274    /// ```
275    #[must_use = "change_marker() consumes self — the original PathBoundary is moved; use the returned PathBoundary<NewMarker>"]
276    #[inline]
277    pub fn change_marker<NewMarker>(self) -> PathBoundary<NewMarker> {
278        PathBoundary {
279            path: self.path,
280            _marker: PhantomData,
281        }
282    }
283
284    /// Consume this boundary and return a `StrictPath` anchored at the boundary directory.
285    ///
286    /// # Errors
287    ///
288    /// - `StrictPathError::PathResolutionError`: Canonicalization fails (directory removed or inaccessible).
289    /// - `StrictPathError::PathEscapesBoundary`: Guard against race conditions that move the directory.
290    ///
291    /// # Examples
292    ///
293    /// ```rust
294    /// # use strict_path::{PathBoundary, StrictPath};
295    /// let data_dir: PathBoundary = PathBoundary::try_new_create("./data")?;
296    /// let data_path: StrictPath = data_dir.into_strictpath()?;
297    /// assert!(data_path.is_dir());
298    /// # Ok::<_, Box<dyn std::error::Error>>(())
299    /// ```
300    #[must_use = "into_strictpath() consumes the PathBoundary — use the returned StrictPath for I/O operations"]
301    #[inline]
302    pub fn into_strictpath(self) -> Result<StrictPath<Marker>> {
303        let root_history = self.path.clone();
304        let validated = PathHistory::<Raw>::new(root_history.as_ref().to_path_buf())
305            .canonicalize()?
306            .boundary_check(root_history.as_ref())?;
307        Ok(StrictPath::new(Arc::new(self), validated))
308    }
309
310    /// Returns the canonicalized PathBoundary directory path. Kept crate-private to avoid leaking raw path.
311    #[inline]
312    pub(crate) fn path(&self) -> &Path {
313        self.path.as_ref()
314    }
315
316    /// Internal: returns the canonicalized PathHistory of the PathBoundary directory for boundary checks.
317    #[cfg(feature = "virtual-path")]
318    #[inline]
319    pub(crate) fn stated_path(&self) -> &PathHistory<((Raw, Canonicalized), Exists)> {
320        &self.path
321    }
322
323    /// Returns true if the PathBoundary directory exists.
324    ///
325    /// This is always true for a constructed PathBoundary, but we query the filesystem for robustness.
326    #[must_use]
327    #[inline]
328    pub fn exists(&self) -> bool {
329        self.path.exists()
330    }
331
332    /// Return the boundary directory path as `&OsStr` for unavoidable third-party `AsRef<Path>` interop (no allocation).
333    #[must_use = "pass interop_path() directly to third-party APIs requiring AsRef<Path> — never wrap it in Path::new() or PathBuf::from() as that defeats boundary safety"]
334    #[inline]
335    pub fn interop_path(&self) -> &std::ffi::OsStr {
336        self.path.as_os_str()
337    }
338
339    /// Returns a Display wrapper that shows the PathBoundary directory system path.
340    #[must_use = "strictpath_display() shows the real system path (admin/debug use) — for user-facing output prefer VirtualPath::virtualpath_display() which hides internal paths"]
341    #[inline]
342    pub fn strictpath_display(&self) -> std::path::Display<'_> {
343        self.path().display()
344    }
345
346    /// Return filesystem metadata for the boundary directory.
347    #[inline]
348    pub fn metadata(&self) -> std::io::Result<std::fs::Metadata> {
349        std::fs::metadata(self.path())
350    }
351
352    /// Create a symbolic link at `link_path` pointing to this boundary's directory.
353    ///
354    pub fn strict_symlink<P: AsRef<Path>>(&self, link_path: P) -> std::io::Result<()> {
355        let root = self
356            .clone()
357            .into_strictpath()
358            .map_err(std::io::Error::other)?;
359
360        root.strict_symlink(link_path)
361    }
362
363    /// Create a hard link at `link_path` pointing to this boundary's directory.
364    ///
365    /// Accepts the same `link_path: impl AsRef<Path>` parameter as `strict_symlink` and returns `io::Result<()>`.
366    pub fn strict_hard_link<P: AsRef<Path>>(&self, link_path: P) -> std::io::Result<()> {
367        let root = self
368            .clone()
369            .into_strictpath()
370            .map_err(std::io::Error::other)?;
371
372        root.strict_hard_link(link_path)
373    }
374
375    /// Create a Windows NTFS directory junction at `link_path` pointing to this boundary's directory.
376    ///
377    /// - Windows-only and behind the `junctions` crate feature.
378    /// - Junctions are directory-only.
379    #[cfg(all(windows, feature = "junctions"))]
380    pub fn strict_junction<P: AsRef<Path>>(&self, link_path: P) -> std::io::Result<()> {
381        let root = self
382            .clone()
383            .into_strictpath()
384            .map_err(std::io::Error::other)?;
385
386        root.strict_junction(link_path)
387    }
388
389    /// Read directory entries under the boundary directory (discovery only).
390    #[inline]
391    pub fn read_dir(&self) -> std::io::Result<std::fs::ReadDir> {
392        std::fs::read_dir(self.path())
393    }
394
395    /// Iterate directory entries under the boundary, yielding validated `StrictPath` values.
396    ///
397    /// Unlike `read_dir()` which returns raw `std::fs::DirEntry` values requiring manual
398    /// re-validation, this method yields `StrictPath` entries directly. Each entry is
399    /// automatically validated through `strict_join()` so you can use it immediately
400    /// for I/O operations without additional validation.
401    ///
402    /// # Examples
403    ///
404    /// ```rust
405    /// use strict_path::PathBoundary;
406    ///
407    /// # let temp = tempfile::tempdir()?;
408    /// let data_dir: PathBoundary = PathBoundary::try_new(temp.path())?;
409    /// # data_dir.strict_join("file.txt")?.write("test")?;
410    ///
411    /// // Auto-validated iteration - no manual re-join needed!
412    /// for entry in data_dir.strict_read_dir()? {
413    ///     let child = entry?;
414    ///     println!("Found: {}", child.strictpath_display());
415    /// }
416    /// # Ok::<_, Box<dyn std::error::Error>>(())
417    /// ```
418    #[inline]
419    pub fn strict_read_dir(&self) -> std::io::Result<BoundaryReadDir<'_, Marker>> {
420        Ok(BoundaryReadDir {
421            inner: std::fs::read_dir(self.path())?,
422            boundary: self,
423        })
424    }
425
426    /// Remove the boundary directory (non-recursive); fails if not empty.
427    #[inline]
428    pub fn remove_dir(&self) -> std::io::Result<()> {
429        std::fs::remove_dir(self.path())
430    }
431
432    /// Recursively remove the boundary directory and its contents.
433    #[inline]
434    pub fn remove_dir_all(&self) -> std::io::Result<()> {
435        std::fs::remove_dir_all(self.path())
436    }
437
438    /// Convert this boundary into a `VirtualRoot` for virtual path operations.
439    #[must_use = "virtualize() consumes self — use the returned VirtualRoot for virtual path operations (.virtual_join(), .into_virtualpath())"]
440    #[cfg(feature = "virtual-path")]
441    #[inline]
442    pub fn virtualize(self) -> crate::VirtualRoot<Marker> {
443        crate::VirtualRoot {
444            root: self,
445            _marker: PhantomData,
446        }
447    }
448
449    // Note: Do not add new crate-private helpers unless necessary; use existing flows.
450}
451
452impl<Marker> std::fmt::Debug for PathBoundary<Marker> {
453    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
454        f.debug_struct("PathBoundary")
455            .field("path", &self.path.as_ref())
456            .field("marker", &std::any::type_name::<Marker>())
457            .finish()
458    }
459}
460
461impl<Marker: Default> std::str::FromStr for PathBoundary<Marker> {
462    type Err = crate::StrictPathError;
463
464    /// Parse a PathBoundary from a string path for universal ergonomics.
465    ///
466    /// Creates the directory if it doesn't exist, enabling seamless integration
467    /// with any string-parsing context (clap, config files, environment variables, etc.):
468    /// ```rust
469    /// # use strict_path::PathBoundary;
470    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
471    /// let data_dir: PathBoundary<()> = "./data".parse()?;
472    /// assert!(data_dir.exists());
473    /// # Ok(())
474    /// # }
475    /// ```
476    #[inline]
477    fn from_str(path: &str) -> std::result::Result<Self, Self::Err> {
478        Self::try_new_create(path)
479    }
480}
481
482// ============================================================
483// BoundaryReadDir — Iterator for validated directory entries
484// ============================================================
485
486/// Iterator over directory entries that yields validated `StrictPath` values.
487///
488/// Created by `PathBoundary::strict_read_dir()`. Each iteration automatically validates
489/// the directory entry through `strict_join()`, so you get `StrictPath` values directly
490/// instead of raw `std::fs::DirEntry` that would require manual re-validation.
491///
492/// # Examples
493///
494/// ```rust
495/// # use strict_path::PathBoundary;
496/// # let temp = tempfile::tempdir()?;
497/// let data_dir: PathBoundary = PathBoundary::try_new(temp.path())?;
498/// # data_dir.strict_join("readme.md")?.write("# Docs")?;
499/// for entry in data_dir.strict_read_dir()? {
500///     let child = entry?;
501///     if child.is_file() {
502///         println!("File: {}", child.strictpath_display());
503///     }
504/// }
505/// # Ok::<_, Box<dyn std::error::Error>>(())
506/// ```
507pub struct BoundaryReadDir<'a, Marker> {
508    inner: std::fs::ReadDir,
509    boundary: &'a PathBoundary<Marker>,
510}
511
512impl<Marker> std::fmt::Debug for BoundaryReadDir<'_, Marker> {
513    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
514        f.debug_struct("BoundaryReadDir")
515            .field("boundary", &self.boundary.strictpath_display())
516            .finish_non_exhaustive()
517    }
518}
519
520impl<Marker: Clone> Iterator for BoundaryReadDir<'_, Marker> {
521    type Item = std::io::Result<crate::StrictPath<Marker>>;
522
523    fn next(&mut self) -> Option<Self::Item> {
524        match self.inner.next()? {
525            Ok(entry) => {
526                let file_name = entry.file_name();
527                match self.boundary.strict_join(file_name) {
528                    Ok(strict_path) => Some(Ok(strict_path)),
529                    Err(e) => Some(Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e))),
530                }
531            }
532            Err(e) => Some(Err(e)),
533        }
534    }
535}
536//