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 = "tempfile")]
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 = "tempfile")]
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 = "tempfile")]
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 = "tempfile")]
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 = "tempfile")]
230 {
231 Ok(Self::new_with_temp_dir(Arc::new(verified_exists), None))
232 }
233 #[cfg(not(feature = "tempfile"))]
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 = "tempfile")]
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 // OS Standard Directory Constructors
322 //
323 // These constructors provide secure access to operating system standard directories
324 // following platform-specific conventions (XDG on Linux, Known Folder API on Windows,
325 // Apple Standard Directories on macOS). Each creates an app-specific subdirectory
326 // and enforces path boundaries for secure file operations.
327
328 /// Creates a PathBoundary in the OS standard config directory for the given application.
329 ///
330 /// **Cross-Platform Behavior:**
331 /// - **Linux**: `~/.config/{app_name}` (XDG Base Directory Specification)
332 /// - **Windows**: `%APPDATA%\{app_name}` (Known Folder API - Roaming AppData)
333 /// - **macOS**: `~/Library/Application Support/{app_name}` (Apple Standard Directories)
334 ///
335 /// Respects environment variables like `$XDG_CONFIG_HOME` on Linux systems.
336 #[cfg(feature = "dirs")]
337 pub fn try_new_os_config(app_name: &str) -> Result<Self> {
338 let config_dir = dirs::config_dir()
339 .ok_or_else(|| crate::StrictPathError::InvalidRestriction {
340 restriction: "os-config".into(),
341 source: std::io::Error::new(
342 std::io::ErrorKind::NotFound,
343 "OS config directory not available",
344 ),
345 })?
346 .join(app_name);
347 Self::try_new_create(config_dir)
348 }
349
350 /// Creates a PathBoundary in the OS standard data directory for the given application.
351 ///
352 /// **Cross-Platform Behavior:**
353 /// - **Linux**: `~/.local/share/{app_name}` (XDG Base Directory Specification)
354 /// - **Windows**: `%APPDATA%\{app_name}` (Known Folder API - Roaming AppData)
355 /// - **macOS**: `~/Library/Application Support/{app_name}` (Apple Standard Directories)
356 ///
357 /// Respects environment variables like `$XDG_DATA_HOME` on Linux systems.
358 #[cfg(feature = "dirs")]
359 pub fn try_new_os_data(app_name: &str) -> Result<Self> {
360 let data_dir = dirs::data_dir()
361 .ok_or_else(|| crate::StrictPathError::InvalidRestriction {
362 restriction: "os-data".into(),
363 source: std::io::Error::new(
364 std::io::ErrorKind::NotFound,
365 "OS data directory not available",
366 ),
367 })?
368 .join(app_name);
369 Self::try_new_create(data_dir)
370 }
371
372 /// Creates a PathBoundary in the OS standard cache directory for the given application.
373 ///
374 /// **Cross-Platform Behavior:**
375 /// - **Linux**: `~/.cache/{app_name}` (XDG Base Directory Specification)
376 /// - **Windows**: `%LOCALAPPDATA%\{app_name}` (Known Folder API - Local AppData)
377 /// - **macOS**: `~/Library/Caches/{app_name}` (Apple Standard Directories)
378 ///
379 /// Respects environment variables like `$XDG_CACHE_HOME` on Linux systems.
380 #[cfg(feature = "dirs")]
381 pub fn try_new_os_cache(app_name: &str) -> Result<Self> {
382 let cache_dir = dirs::cache_dir()
383 .ok_or_else(|| crate::StrictPathError::InvalidRestriction {
384 restriction: "os-cache".into(),
385 source: std::io::Error::new(
386 std::io::ErrorKind::NotFound,
387 "OS cache directory not available",
388 ),
389 })?
390 .join(app_name);
391 Self::try_new_create(cache_dir)
392 }
393
394 /// Creates a PathBoundary in the OS local config directory (non-roaming on Windows).
395 ///
396 /// **Cross-Platform Behavior:**
397 /// - **Linux**: `~/.config/{app_name}` (same as config_dir)
398 /// - **Windows**: `%LOCALAPPDATA%\{app_name}` (Known Folder API - Local AppData)
399 /// - **macOS**: `~/Library/Application Support/{app_name}` (same as config_dir)
400 #[cfg(feature = "dirs")]
401 pub fn try_new_os_config_local(app_name: &str) -> Result<Self> {
402 let config_dir = dirs::config_local_dir()
403 .ok_or_else(|| crate::StrictPathError::InvalidRestriction {
404 restriction: "os-config-local".into(),
405 source: std::io::Error::new(
406 std::io::ErrorKind::NotFound,
407 "OS local config directory not available",
408 ),
409 })?
410 .join(app_name);
411 Self::try_new_create(config_dir)
412 }
413
414 /// Creates a PathBoundary in the OS local data directory.
415 ///
416 /// **Cross-Platform Behavior:**
417 /// - **Linux**: `~/.local/share/{app_name}` (same as data_dir)
418 /// - **Windows**: `%LOCALAPPDATA%\{app_name}` (Known Folder API - Local AppData)
419 /// - **macOS**: `~/Library/Application Support/{app_name}` (same as data_dir)
420 #[cfg(feature = "dirs")]
421 pub fn try_new_os_data_local(app_name: &str) -> Result<Self> {
422 let data_dir = dirs::data_local_dir()
423 .ok_or_else(|| crate::StrictPathError::InvalidRestriction {
424 restriction: "os-data-local".into(),
425 source: std::io::Error::new(
426 std::io::ErrorKind::NotFound,
427 "OS local data directory not available",
428 ),
429 })?
430 .join(app_name);
431 Self::try_new_create(data_dir)
432 }
433
434 /// Creates a PathBoundary in the user's home directory.
435 ///
436 /// **Cross-Platform Behavior:**
437 /// - **Linux**: `$HOME`
438 /// - **Windows**: `%USERPROFILE%` (e.g., `C:\Users\Username`)
439 /// - **macOS**: `$HOME`
440 #[cfg(feature = "dirs")]
441 pub fn try_new_os_home() -> Result<Self> {
442 let home_dir =
443 dirs::home_dir().ok_or_else(|| crate::StrictPathError::InvalidRestriction {
444 restriction: "os-home".into(),
445 source: std::io::Error::new(
446 std::io::ErrorKind::NotFound,
447 "OS home directory not available",
448 ),
449 })?;
450 Self::try_new(home_dir)
451 }
452
453 /// Creates a PathBoundary in the user's desktop directory.
454 ///
455 /// **Cross-Platform Behavior:**
456 /// - **Linux**: `$HOME/Desktop` or XDG_DESKTOP_DIR
457 /// - **Windows**: `%USERPROFILE%\Desktop`
458 /// - **macOS**: `$HOME/Desktop`
459 #[cfg(feature = "dirs")]
460 pub fn try_new_os_desktop() -> Result<Self> {
461 let desktop_dir =
462 dirs::desktop_dir().ok_or_else(|| crate::StrictPathError::InvalidRestriction {
463 restriction: "os-desktop".into(),
464 source: std::io::Error::new(
465 std::io::ErrorKind::NotFound,
466 "OS desktop directory not available",
467 ),
468 })?;
469 Self::try_new(desktop_dir)
470 }
471
472 /// Creates a PathBoundary in the user's documents directory.
473 ///
474 /// **Cross-Platform Behavior:**
475 /// - **Linux**: `$HOME/Documents` or XDG_DOCUMENTS_DIR
476 /// - **Windows**: `%USERPROFILE%\Documents`
477 /// - **macOS**: `$HOME/Documents`
478 #[cfg(feature = "dirs")]
479 pub fn try_new_os_documents() -> Result<Self> {
480 let docs_dir =
481 dirs::document_dir().ok_or_else(|| crate::StrictPathError::InvalidRestriction {
482 restriction: "os-documents".into(),
483 source: std::io::Error::new(
484 std::io::ErrorKind::NotFound,
485 "OS documents directory not available",
486 ),
487 })?;
488 Self::try_new(docs_dir)
489 }
490
491 /// Creates a PathBoundary in the user's downloads directory.
492 ///
493 /// **Cross-Platform Behavior:**
494 /// - **Linux**: `$HOME/Downloads` or XDG_DOWNLOAD_DIR
495 /// - **Windows**: `%USERPROFILE%\Downloads`
496 /// - **macOS**: `$HOME/Downloads`
497 #[cfg(feature = "dirs")]
498 pub fn try_new_os_downloads() -> Result<Self> {
499 let downloads_dir =
500 dirs::download_dir().ok_or_else(|| crate::StrictPathError::InvalidRestriction {
501 restriction: "os-downloads".into(),
502 source: std::io::Error::new(
503 std::io::ErrorKind::NotFound,
504 "OS downloads directory not available",
505 ),
506 })?;
507 Self::try_new(downloads_dir)
508 }
509
510 /// Creates a PathBoundary in the user's pictures directory.
511 ///
512 /// **Cross-Platform Behavior:**
513 /// - **Linux**: `$HOME/Pictures` or XDG_PICTURES_DIR
514 /// - **Windows**: `%USERPROFILE%\Pictures`
515 /// - **macOS**: `$HOME/Pictures`
516 #[cfg(feature = "dirs")]
517 pub fn try_new_os_pictures() -> Result<Self> {
518 let pictures_dir =
519 dirs::picture_dir().ok_or_else(|| crate::StrictPathError::InvalidRestriction {
520 restriction: "os-pictures".into(),
521 source: std::io::Error::new(
522 std::io::ErrorKind::NotFound,
523 "OS pictures directory not available",
524 ),
525 })?;
526 Self::try_new(pictures_dir)
527 }
528
529 /// Creates a PathBoundary in the user's music/audio directory.
530 ///
531 /// **Cross-Platform Behavior:**
532 /// - **Linux**: `$HOME/Music` or XDG_MUSIC_DIR
533 /// - **Windows**: `%USERPROFILE%\Music`
534 /// - **macOS**: `$HOME/Music`
535 #[cfg(feature = "dirs")]
536 pub fn try_new_os_audio() -> Result<Self> {
537 let audio_dir =
538 dirs::audio_dir().ok_or_else(|| crate::StrictPathError::InvalidRestriction {
539 restriction: "os-audio".into(),
540 source: std::io::Error::new(
541 std::io::ErrorKind::NotFound,
542 "OS audio directory not available",
543 ),
544 })?;
545 Self::try_new(audio_dir)
546 }
547
548 /// Creates a PathBoundary in the user's videos directory.
549 ///
550 /// **Cross-Platform Behavior:**
551 /// - **Linux**: `$HOME/Videos` or XDG_VIDEOS_DIR
552 /// - **Windows**: `%USERPROFILE%\Videos`
553 /// - **macOS**: `$HOME/Movies`
554 #[cfg(feature = "dirs")]
555 pub fn try_new_os_videos() -> Result<Self> {
556 let videos_dir =
557 dirs::video_dir().ok_or_else(|| crate::StrictPathError::InvalidRestriction {
558 restriction: "os-videos".into(),
559 source: std::io::Error::new(
560 std::io::ErrorKind::NotFound,
561 "OS videos directory not available",
562 ),
563 })?;
564 Self::try_new(videos_dir)
565 }
566
567 /// Creates a PathBoundary in the OS executable directory (Linux only).
568 ///
569 /// **Platform Availability:**
570 /// - **Linux**: `~/.local/bin` or $XDG_BIN_HOME
571 /// - **Windows**: Returns error (not available)
572 /// - **macOS**: Returns error (not available)
573 #[cfg(feature = "dirs")]
574 pub fn try_new_os_executables() -> Result<Self> {
575 let exec_dir =
576 dirs::executable_dir().ok_or_else(|| crate::StrictPathError::InvalidRestriction {
577 restriction: "os-executables".into(),
578 source: std::io::Error::new(
579 std::io::ErrorKind::NotFound,
580 "OS executables directory not available on this platform",
581 ),
582 })?;
583 Self::try_new(exec_dir)
584 }
585
586 /// Creates a PathBoundary in the OS runtime directory (Linux only).
587 ///
588 /// **Platform Availability:**
589 /// - **Linux**: `$XDG_RUNTIME_DIR` (session-specific, user-only access)
590 /// - **Windows**: Returns error (not available)
591 /// - **macOS**: Returns error (not available)
592 #[cfg(feature = "dirs")]
593 pub fn try_new_os_runtime() -> Result<Self> {
594 let runtime_dir =
595 dirs::runtime_dir().ok_or_else(|| crate::StrictPathError::InvalidRestriction {
596 restriction: "os-runtime".into(),
597 source: std::io::Error::new(
598 std::io::ErrorKind::NotFound,
599 "OS runtime directory not available on this platform",
600 ),
601 })?;
602 Self::try_new(runtime_dir)
603 }
604
605 /// Creates a PathBoundary in the OS state directory (Linux only).
606 ///
607 /// **Platform Availability:**
608 /// - **Linux**: `~/.local/state/{app_name}` or $XDG_STATE_HOME/{app_name}
609 /// - **Windows**: Returns error (not available)
610 /// - **macOS**: Returns error (not available)
611 #[cfg(feature = "dirs")]
612 pub fn try_new_os_state(app_name: &str) -> Result<Self> {
613 let state_dir = dirs::state_dir()
614 .ok_or_else(|| crate::StrictPathError::InvalidRestriction {
615 restriction: "os-state".into(),
616 source: std::io::Error::new(
617 std::io::ErrorKind::NotFound,
618 "OS state directory not available on this platform",
619 ),
620 })?
621 .join(app_name);
622 Self::try_new_create(state_dir)
623 }
624
625 /// Creates a PathBoundary in a unique temporary directory with RAII cleanup.
626 ///
627 /// Returns a `StrictPath` pointing to the temp directory root. The directory
628 /// will be automatically cleaned up when the `StrictPath` is dropped.
629 ///
630 /// # Example
631 /// ```
632 /// # #[cfg(feature = "tempfile")] {
633 /// use strict_path::PathBoundary;
634 ///
635 /// // Get a validated temp directory path directly
636 /// let temp_root = PathBoundary::<()>::try_new_temp()?;
637 /// let user_input = "uploads/document.pdf";
638 /// let validated_path = temp_root.strict_join(user_input)?; // Returns StrictPath
639 /// // Ensure parent directories exist before writing
640 /// validated_path.create_parent_dir_all()?;
641 /// std::fs::write(validated_path.interop_path(), b"content")?; // Direct filesystem access
642 /// // temp_root is dropped here, directory gets cleaned up automatically
643 /// # }
644 /// # Ok::<(), Box<dyn std::error::Error>>(())
645 /// ```
646 #[cfg(feature = "tempfile")]
647 pub fn try_new_temp() -> Result<Self> {
648 let temp_dir =
649 tempfile::tempdir().map_err(|e| crate::StrictPathError::InvalidRestriction {
650 restriction: "temp".into(),
651 source: e,
652 })?;
653
654 let temp_path = temp_dir.path();
655 let raw = PathHistory::<Raw>::new(temp_path);
656 let canonicalized = raw.canonicalize()?;
657 let verified_exists = canonicalized.verify_exists().ok_or_else(|| {
658 crate::StrictPathError::InvalidRestriction {
659 restriction: "temp".into(),
660 source: std::io::Error::new(
661 std::io::ErrorKind::NotFound,
662 "Temp directory verification failed",
663 ),
664 }
665 })?;
666
667 Ok(Self::new_with_temp_dir(
668 Arc::new(verified_exists),
669 Some(Arc::new(temp_dir)),
670 ))
671 }
672
673 /// Creates a PathBoundary in a temporary directory with a custom prefix and RAII cleanup.
674 ///
675 /// Returns a `StrictPath` pointing to the temp directory root. The directory
676 /// will be automatically cleaned up when the `StrictPath` is dropped.
677 ///
678 /// # Example
679 /// ```
680 /// # #[cfg(feature = "tempfile")] {
681 /// use strict_path::PathBoundary;
682 ///
683 /// // Get a validated temp directory path with session prefix
684 /// let upload_root = PathBoundary::<()>::try_new_temp_with_prefix("upload_batch")?;
685 /// let user_file = upload_root.strict_join("user_document.pdf")?; // Validate path
686 /// // Process validated path with direct filesystem operations
687 /// // upload_root is dropped here, directory gets cleaned up automatically
688 /// # }
689 /// # Ok::<(), Box<dyn std::error::Error>>(())
690 /// ```
691 #[cfg(feature = "tempfile")]
692 pub fn try_new_temp_with_prefix(prefix: &str) -> Result<Self> {
693 let temp_dir = tempfile::Builder::new()
694 .prefix(prefix)
695 .tempdir()
696 .map_err(|e| crate::StrictPathError::InvalidRestriction {
697 restriction: "temp".into(),
698 source: e,
699 })?;
700
701 let temp_path = temp_dir.path();
702 let raw = PathHistory::<Raw>::new(temp_path);
703 let canonicalized = raw.canonicalize()?;
704 let verified_exists = canonicalized.verify_exists().ok_or_else(|| {
705 crate::StrictPathError::InvalidRestriction {
706 restriction: "temp".into(),
707 source: std::io::Error::new(
708 std::io::ErrorKind::NotFound,
709 "Temp directory verification failed",
710 ),
711 }
712 })?;
713
714 Ok(Self::new_with_temp_dir(
715 Arc::new(verified_exists),
716 Some(Arc::new(temp_dir)),
717 ))
718 }
719
720 /// Creates a PathBoundary using app-path for portable applications.
721 ///
722 /// Creates a directory relative to the executable location, with optional
723 /// environment variable override support for deployment flexibility.
724 ///
725 /// # Example
726 /// ```
727 /// # #[cfg(feature = "app-path")] {
728 /// use strict_path::PathBoundary;
729 ///
730 /// // Creates ./config/ relative to executable
731 /// let config_restriction = PathBoundary::<()>::try_new_app_path("config", None)?;
732 ///
733 /// // With environment override (checks MYAPP_CONFIG_DIR first)
734 /// let config_restriction = PathBoundary::<()>::try_new_app_path("config", Some("MYAPP_CONFIG_DIR"))?;
735 /// # }
736 /// # Ok::<(), Box<dyn std::error::Error>>(())
737 /// ```
738 #[cfg(feature = "app-path")]
739 pub fn try_new_app_path(subdir: &str, env_override: Option<&str>) -> Result<Self> {
740 let app_path = app_path::AppPath::try_with_override(subdir, env_override).map_err(|e| {
741 crate::StrictPathError::InvalidRestriction {
742 restriction: format!("app-path: {subdir}").into(),
743 source: std::io::Error::new(std::io::ErrorKind::InvalidInput, e),
744 }
745 })?;
746
747 Self::try_new_create(app_path)
748 }
749}
750
751impl<Marker> AsRef<Path> for PathBoundary<Marker> {
752 #[inline]
753 fn as_ref(&self) -> &Path {
754 // PathHistory implements AsRef<Path>, so forward to it
755 self.path.as_ref()
756 }
757}
758
759impl<Marker> std::fmt::Debug for PathBoundary<Marker> {
760 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
761 f.debug_struct("PathBoundary")
762 .field("path", &self.path.as_ref())
763 .field("marker", &std::any::type_name::<Marker>())
764 .finish()
765 }
766}
767
768impl<Marker: Default> std::str::FromStr for PathBoundary<Marker> {
769 type Err = crate::StrictPathError;
770
771 /// Parse a PathBoundary from a string path for universal ergonomics.
772 ///
773 /// Creates the directory if it doesn't exist, enabling seamless integration
774 /// with any string-parsing context (clap, config files, environment variables, etc.):
775 /// ```rust
776 /// # use strict_path::PathBoundary;
777 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
778 /// let temp_dir = tempfile::tempdir()?;
779 /// let safe_path = temp_dir.path().join("safe_dir");
780 /// let boundary: PathBoundary<()> = safe_path.to_string_lossy().parse()?;
781 /// assert!(safe_path.exists());
782 /// # Ok(())
783 /// # }
784 /// ```
785 #[inline]
786 fn from_str(path: &str) -> std::result::Result<Self, Self::Err> {
787 Self::try_new_create(path)
788 }
789}