strict_path/validator/
path_boundary.rs

1// Content copied from original src/validator/restriction.rs
2use crate::error::StrictPathError;
3use crate::path::strict_path::StrictPath;
4use crate::validator::path_history::*;
5use crate::Result;
6
7#[cfg(windows)]
8use std::ffi::OsStr;
9use std::io::{Error as IoError, ErrorKind};
10use std::marker::PhantomData;
11use std::path::Path;
12use std::sync::Arc;
13
14#[cfg(feature = "tempdir")]
15use tempfile::TempDir;
16
17#[cfg(windows)]
18use std::path::Component;
19
20#[cfg(windows)]
21fn is_potential_83_short_name(os: &OsStr) -> bool {
22    let s = os.to_string_lossy();
23    if let Some(pos) = s.find('~') {
24        s[pos + 1..]
25            .chars()
26            .next()
27            .is_some_and(|ch| ch.is_ascii_digit())
28    } else {
29        false
30    }
31}
32
33/// Canonicalize a candidate path and enforce the PathBoundary boundary, returning a `StrictPath`.
34///
35/// What this does:
36/// - Windows prefilter: rejects DOS 8.3 short-name segments (e.g., `PROGRA~1`) in relative inputs
37///   to avoid aliasing-based escapes before any filesystem calls.
38/// - Input interpretation: absolute inputs are validated as-is; relative inputs are joined under
39///   the PathBoundary root.
40/// - Resolution: canonicalizes the composed path, fully resolving `.`/`..`, symlinks/junctions,
41///   and platform prefixes.
42/// - Boundary enforcement: verifies the canonicalized result is strictly within the PathBoundary's
43///   canonicalized root; rejects any resolution that would escape the boundary.
44/// - Returns: a `StrictPath<Marker>` that borrows the PathBoundary and holds the validated system path.
45pub(crate) fn canonicalize_and_enforce_restriction_boundary<Marker>(
46    path: impl AsRef<Path>,
47    restriction: &PathBoundary<Marker>,
48) -> Result<StrictPath<Marker>> {
49    #[cfg(windows)]
50    {
51        let original_user_path = path.as_ref().to_path_buf();
52        if !path.as_ref().is_absolute() {
53            let mut probe = restriction.path().to_path_buf();
54            for comp in path.as_ref().components() {
55                match comp {
56                    Component::CurDir | Component::ParentDir => continue,
57                    Component::RootDir | Component::Prefix(_) => continue,
58                    Component::Normal(name) => {
59                        if is_potential_83_short_name(name) {
60                            return Err(StrictPathError::windows_short_name(
61                                name.to_os_string(),
62                                original_user_path,
63                                probe.clone(),
64                            ));
65                        }
66                        probe.push(name);
67                    }
68                }
69            }
70        }
71    }
72
73    let target_path = if path.as_ref().is_absolute() {
74        path.as_ref().to_path_buf()
75    } else {
76        restriction.path().join(path.as_ref())
77    };
78
79    let validated_path = PathHistory::<Raw>::new(target_path)
80        .canonicalize()?
81        .boundary_check(&restriction.path)?;
82
83    Ok(StrictPath::new(
84        Arc::new(restriction.clone()),
85        validated_path,
86    ))
87}
88
89/// A path boundary that serves as the secure foundation for validated path operations.
90///
91/// `PathBoundary` represents the trusted starting point (like `/home/users/alice`) from which
92/// all path operations begin. When you call `path_boundary.strict_join("documents/file.txt")`,
93/// you're building outward from this secure boundary with validated path construction.
94pub struct PathBoundary<Marker = ()> {
95    path: Arc<PathHistory<((Raw, Canonicalized), Exists)>>,
96    #[cfg(feature = "tempdir")]
97    _temp_dir: Option<Arc<TempDir>>,
98    _marker: PhantomData<Marker>,
99}
100
101impl<Marker> Clone for PathBoundary<Marker> {
102    fn clone(&self) -> Self {
103        Self {
104            path: self.path.clone(),
105            #[cfg(feature = "tempdir")]
106            _temp_dir: self._temp_dir.clone(),
107            _marker: PhantomData,
108        }
109    }
110}
111
112impl<Marker> PartialEq for PathBoundary<Marker> {
113    #[inline]
114    fn eq(&self, other: &Self) -> bool {
115        self.path() == other.path()
116    }
117}
118
119impl<Marker> Eq for PathBoundary<Marker> {}
120
121impl<Marker> std::hash::Hash for PathBoundary<Marker> {
122    #[inline]
123    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
124        self.path().hash(state);
125    }
126}
127
128impl<Marker> PartialOrd for PathBoundary<Marker> {
129    #[inline]
130    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
131        Some(self.cmp(other))
132    }
133}
134
135impl<Marker> Ord for PathBoundary<Marker> {
136    #[inline]
137    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
138        self.path().cmp(other.path())
139    }
140}
141
142impl<Marker> PartialEq<crate::validator::virtual_root::VirtualRoot<Marker>>
143    for PathBoundary<Marker>
144{
145    #[inline]
146    fn eq(&self, other: &crate::validator::virtual_root::VirtualRoot<Marker>) -> bool {
147        self.path() == other.path()
148    }
149}
150
151impl<Marker> PartialEq<Path> for PathBoundary<Marker> {
152    #[inline]
153    fn eq(&self, other: &Path) -> bool {
154        self.path() == other
155    }
156}
157
158impl<Marker> PartialEq<std::path::PathBuf> for PathBoundary<Marker> {
159    #[inline]
160    fn eq(&self, other: &std::path::PathBuf) -> bool {
161        self.eq(other.as_path())
162    }
163}
164
165impl<Marker> PartialEq<&std::path::Path> for PathBoundary<Marker> {
166    #[inline]
167    fn eq(&self, other: &&std::path::Path) -> bool {
168        self.eq(*other)
169    }
170}
171
172impl<Marker> PathBoundary<Marker> {
173    /// Private constructor that allows setting the temp_dir during construction
174    #[cfg(feature = "tempdir")]
175    fn new_with_temp_dir(
176        path: Arc<PathHistory<((Raw, Canonicalized), Exists)>>,
177        temp_dir: Option<Arc<TempDir>>,
178    ) -> Self {
179        Self {
180            path,
181            _temp_dir: temp_dir,
182            _marker: PhantomData,
183        }
184    }
185
186    /// Creates a new `PathBoundary` rooted at `restriction_path` (which must already exist and be a directory).
187    ///
188    /// Uses `AsRef<Path>` for maximum ergonomics, including direct `TempDir` support for clean shadowing patterns:
189    /// ```rust
190    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
191    /// use strict_path::PathBoundary;
192    /// let tmp_dir = tempfile::tempdir()?;
193    /// let tmp_dir = PathBoundary::<()>::try_new(tmp_dir)?; // Clean variable shadowing
194    /// # Ok(())
195    /// # }
196    /// ```
197    #[inline]
198    pub fn try_new<P: AsRef<Path>>(restriction_path: P) -> Result<Self> {
199        let restriction_path = restriction_path.as_ref();
200        let raw = PathHistory::<Raw>::new(restriction_path);
201
202        let canonicalized = raw.canonicalize()?;
203
204        let verified_exists = match canonicalized.verify_exists() {
205            Some(path) => path,
206            None => {
207                let io = IoError::new(
208                    ErrorKind::NotFound,
209                    "The specified PathBoundary path does not exist.",
210                );
211                return Err(StrictPathError::invalid_restriction(
212                    restriction_path.to_path_buf(),
213                    io,
214                ));
215            }
216        };
217
218        if !verified_exists.is_dir() {
219            let error = IoError::new(
220                ErrorKind::InvalidInput,
221                "The specified PathBoundary path exists but is not a directory.",
222            );
223            return Err(StrictPathError::invalid_restriction(
224                restriction_path.to_path_buf(),
225                error,
226            ));
227        }
228
229        #[cfg(feature = "tempdir")]
230        {
231            Ok(Self::new_with_temp_dir(Arc::new(verified_exists), None))
232        }
233        #[cfg(not(feature = "tempdir"))]
234        {
235            Ok(Self {
236                path: Arc::new(verified_exists),
237                _marker: PhantomData,
238            })
239        }
240    }
241
242    /// Creates the directory if missing, then constructs a new `PathBoundary`.
243    ///
244    /// Uses `AsRef<Path>` for maximum ergonomics, including direct `TempDir` support for clean shadowing patterns:
245    /// ```rust
246    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
247    /// use strict_path::PathBoundary;
248    /// let tmp_dir = tempfile::tempdir()?;
249    /// let tmp_dir = PathBoundary::<()>::try_new_create(tmp_dir)?; // Clean variable shadowing
250    /// # Ok(())
251    /// # }
252    /// ```
253    pub fn try_new_create<P: AsRef<Path>>(root: P) -> Result<Self> {
254        let root_path = root.as_ref();
255        if !root_path.exists() {
256            std::fs::create_dir_all(root_path)
257                .map_err(|e| StrictPathError::invalid_restriction(root_path.to_path_buf(), e))?;
258        }
259        Self::try_new(root_path)
260    }
261
262    /// Joins a path to this restrictor root and validates it remains within the restriction boundary.
263    ///
264    /// Accepts absolute or relative inputs; ensures the resulting path remains within the restriction.
265    #[inline]
266    pub fn strict_join(&self, candidate_path: impl AsRef<Path>) -> Result<StrictPath<Marker>> {
267        canonicalize_and_enforce_restriction_boundary(candidate_path, self)
268    }
269
270    /// Returns the canonicalized PathBoundary root path. Kept crate-private to avoid leaking raw path.
271    #[inline]
272    pub(crate) fn path(&self) -> &Path {
273        self.path.as_ref()
274    }
275
276    /// Internal: returns the canonicalized PathHistory of the PathBoundary root for boundary checks.
277    #[inline]
278    pub(crate) fn stated_path(&self) -> &PathHistory<((Raw, Canonicalized), Exists)> {
279        &self.path
280    }
281
282    /// Returns true if the PathBoundary root exists.
283    ///
284    /// This is always true for a constructed PathBoundary, but we query the filesystem for robustness.
285    #[inline]
286    pub fn exists(&self) -> bool {
287        self.path.exists()
288    }
289
290    /// Returns the PathBoundary root path for interop with `AsRef<Path>` APIs.
291    ///
292    /// This provides allocation-free, OS-native string access to the PathBoundary root
293    /// for use with standard library APIs that accept `AsRef<Path>`.
294    #[inline]
295    pub fn interop_path(&self) -> &std::ffi::OsStr {
296        self.path.as_os_str()
297    }
298
299    /// Returns a Display wrapper that shows the PathBoundary root system path.
300    #[inline]
301    pub fn strictpath_display(&self) -> std::path::Display<'_> {
302        self.path().display()
303    }
304
305    /// Converts this `PathBoundary` into a `VirtualRoot`.
306    ///
307    /// This creates a virtual root view of the PathBoundary, allowing virtual path operations
308    /// that treat the PathBoundary root as the virtual filesystem root "/".
309    #[inline]
310    pub fn virtualize(self) -> crate::VirtualRoot<Marker> {
311        crate::VirtualRoot {
312            root: self,
313            #[cfg(feature = "tempdir")]
314            _temp_dir: None,
315            _marker: PhantomData,
316        }
317    }
318
319    // Note: Do not add new crate-private helpers unless necessary; use existing flows.
320
321    // Convenience constructors for system and temporary directories
322
323    /// Creates a PathBoundary in the user's config directory for the given application.
324    ///
325    /// Creates `~/.config/{app_name}` on Linux/macOS or `%APPDATA%\{app_name}` on Windows.
326    /// The application directory is created if it doesn't exist.
327    /// Useful for validating config file paths before direct filesystem access.
328    ///
329    /// # Example
330    /// ```
331    /// # #[cfg(feature = "dirs")] {
332    /// use strict_path::PathBoundary;
333    ///
334    /// // Validate config file paths
335    /// let config_restriction = PathBoundary::<()>::try_new_config("myapp")?;
336    /// let user_config = config_restriction.strict_join("settings.toml")?; // Validate path
337    /// std::fs::write(user_config.interop_path(), "key = value")?; // Direct access
338    /// # }
339    /// # Ok::<(), Box<dyn std::error::Error>>(())
340    /// ```
341    #[cfg(feature = "dirs")]
342    pub fn try_new_config(app_name: &str) -> Result<Self> {
343        let config_dir = dirs::config_dir()
344            .ok_or_else(|| crate::StrictPathError::InvalidRestriction {
345                restriction: "system-config".into(),
346                source: std::io::Error::new(
347                    std::io::ErrorKind::NotFound,
348                    "No system config directory found",
349                ),
350            })?
351            .join(app_name);
352        Self::try_new_create(config_dir)
353    }
354
355    /// Creates a PathBoundary in the user's data directory for the given application.
356    ///
357    /// Creates `~/.local/share/{app_name}` on Linux, `~/Library/Application Support/{app_name}` on macOS,
358    /// or `%APPDATA%\{app_name}` on Windows.
359    /// The application directory is created if it doesn't exist.
360    #[cfg(feature = "dirs")]
361    pub fn try_new_data(app_name: &str) -> Result<Self> {
362        let data_dir = dirs::data_dir()
363            .ok_or_else(|| crate::StrictPathError::InvalidRestriction {
364                restriction: "system-data".into(),
365                source: std::io::Error::new(
366                    std::io::ErrorKind::NotFound,
367                    "No system data directory found",
368                ),
369            })?
370            .join(app_name);
371        Self::try_new_create(data_dir)
372    }
373
374    /// Creates a PathBoundary in the user's cache directory for the given application.
375    ///
376    /// Creates `~/.cache/{app_name}` on Linux, `~/Library/Caches/{app_name}` on macOS,
377    /// or `%LOCALAPPDATA%\{app_name}` on Windows.
378    /// The application directory is created if it doesn't exist.
379    #[cfg(feature = "dirs")]
380    pub fn try_new_cache(app_name: &str) -> Result<Self> {
381        let cache_dir = dirs::cache_dir()
382            .ok_or_else(|| crate::StrictPathError::InvalidRestriction {
383                restriction: "system-cache".into(),
384                source: std::io::Error::new(
385                    std::io::ErrorKind::NotFound,
386                    "No system cache directory found",
387                ),
388            })?
389            .join(app_name);
390        Self::try_new_create(cache_dir)
391    }
392
393    /// Creates a PathBoundary in a unique temporary directory with RAII cleanup.
394    ///
395    /// Returns a `StrictPath` pointing to the temp directory root. The directory
396    /// will be automatically cleaned up when the `StrictPath` is dropped.
397    ///
398    /// # Example
399    /// ```
400    /// # #[cfg(feature = "tempdir")] {
401    /// use strict_path::PathBoundary;
402    ///
403    /// // Get a validated temp directory path directly
404    /// let temp_root = PathBoundary::<()>::try_new_temp()?;
405    /// let user_input = "uploads/document.pdf";
406    /// let validated_path = temp_root.strict_join(user_input)?; // Returns StrictPath
407    /// // Ensure parent directories exist before writing
408    /// validated_path.create_parent_dir_all()?;
409    /// std::fs::write(validated_path.interop_path(), b"content")?; // Direct filesystem access
410    /// // temp_root is dropped here, directory gets cleaned up automatically
411    /// # }
412    /// # Ok::<(), Box<dyn std::error::Error>>(())
413    /// ```
414    #[cfg(feature = "tempdir")]
415    pub fn try_new_temp() -> Result<Self> {
416        let temp_dir =
417            tempfile::tempdir().map_err(|e| crate::StrictPathError::InvalidRestriction {
418                restriction: "temp".into(),
419                source: e,
420            })?;
421
422        let temp_path = temp_dir.path();
423        let raw = PathHistory::<Raw>::new(temp_path);
424        let canonicalized = raw.canonicalize()?;
425        let verified_exists = canonicalized.verify_exists().ok_or_else(|| {
426            crate::StrictPathError::InvalidRestriction {
427                restriction: "temp".into(),
428                source: std::io::Error::new(
429                    std::io::ErrorKind::NotFound,
430                    "Temp directory verification failed",
431                ),
432            }
433        })?;
434
435        Ok(Self::new_with_temp_dir(
436            Arc::new(verified_exists),
437            Some(Arc::new(temp_dir)),
438        ))
439    }
440
441    /// Creates a PathBoundary in a temporary directory with a custom prefix and RAII cleanup.
442    ///
443    /// Returns a `StrictPath` pointing to the temp directory root. The directory
444    /// will be automatically cleaned up when the `StrictPath` is dropped.
445    ///
446    /// # Example
447    /// ```
448    /// # #[cfg(feature = "tempdir")] {
449    /// use strict_path::PathBoundary;
450    ///
451    /// // Get a validated temp directory path with session prefix
452    /// let upload_root = PathBoundary::<()>::try_new_temp_with_prefix("upload_batch")?;
453    /// let user_file = upload_root.strict_join("user_document.pdf")?; // Validate path
454    /// // Process validated path with direct filesystem operations
455    /// // upload_root is dropped here, directory gets cleaned up automatically
456    /// # }
457    /// # Ok::<(), Box<dyn std::error::Error>>(())
458    /// ```
459    #[cfg(feature = "tempdir")]
460    pub fn try_new_temp_with_prefix(prefix: &str) -> Result<Self> {
461        let temp_dir = tempfile::Builder::new()
462            .prefix(prefix)
463            .tempdir()
464            .map_err(|e| crate::StrictPathError::InvalidRestriction {
465                restriction: "temp".into(),
466                source: e,
467            })?;
468
469        let temp_path = temp_dir.path();
470        let raw = PathHistory::<Raw>::new(temp_path);
471        let canonicalized = raw.canonicalize()?;
472        let verified_exists = canonicalized.verify_exists().ok_or_else(|| {
473            crate::StrictPathError::InvalidRestriction {
474                restriction: "temp".into(),
475                source: std::io::Error::new(
476                    std::io::ErrorKind::NotFound,
477                    "Temp directory verification failed",
478                ),
479            }
480        })?;
481
482        Ok(Self::new_with_temp_dir(
483            Arc::new(verified_exists),
484            Some(Arc::new(temp_dir)),
485        ))
486    }
487
488    /// Creates a PathBoundary using app-path for portable applications.
489    ///
490    /// Creates a directory relative to the executable location, with optional
491    /// environment variable override support for deployment flexibility.
492    ///
493    /// # Example
494    /// ```
495    /// # #[cfg(feature = "app-path")] {
496    /// use strict_path::PathBoundary;
497    ///
498    /// // Creates ./config/ relative to executable
499    /// let config_restriction = PathBoundary::<()>::try_new_app_path("config", None)?;
500    ///
501    /// // With environment override (checks MYAPP_CONFIG_DIR first)
502    /// let config_restriction = PathBoundary::<()>::try_new_app_path("config", Some("MYAPP_CONFIG_DIR"))?;
503    /// # }
504    /// # Ok::<(), Box<dyn std::error::Error>>(())
505    /// ```
506    #[cfg(feature = "app-path")]
507    pub fn try_new_app_path(subdir: &str, env_override: Option<&str>) -> Result<Self> {
508        let app_path = app_path::AppPath::try_with_override(subdir, env_override).map_err(|e| {
509            crate::StrictPathError::InvalidRestriction {
510                restriction: format!("app-path: {subdir}").into(),
511                source: std::io::Error::new(std::io::ErrorKind::InvalidInput, e),
512            }
513        })?;
514
515        Self::try_new_create(app_path)
516    }
517}
518
519impl<Marker> AsRef<Path> for PathBoundary<Marker> {
520    #[inline]
521    fn as_ref(&self) -> &Path {
522        // PathHistory implements AsRef<Path>, so forward to it
523        self.path.as_ref()
524    }
525}
526
527impl<Marker> std::fmt::Debug for PathBoundary<Marker> {
528    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
529        f.debug_struct("PathBoundary")
530            .field("path", &self.path.as_ref())
531            .field("marker", &std::any::type_name::<Marker>())
532            .finish()
533    }
534}
535
536impl<Marker: Default> std::str::FromStr for PathBoundary<Marker> {
537    type Err = crate::StrictPathError;
538
539    /// Parse a PathBoundary from a string path for universal ergonomics.
540    ///
541    /// Creates the directory if it doesn't exist, enabling seamless integration
542    /// with any string-parsing context (clap, config files, environment variables, etc.):
543    /// ```rust
544    /// # use strict_path::PathBoundary;
545    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
546    /// let temp_dir = tempfile::tempdir()?;
547    /// let safe_path = temp_dir.path().join("safe_dir");
548    /// let boundary: PathBoundary<()> = safe_path.to_string_lossy().parse()?;
549    /// assert!(safe_path.exists());
550    /// # Ok(())
551    /// # }
552    /// ```
553    #[inline]
554    fn from_str(path: &str) -> std::result::Result<Self, Self::Err> {
555        Self::try_new_create(path)
556    }
557}