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