Skip to main content

ggen_core/utils/
path_validator.rs

1//! Comprehensive Path Validation for Security-Critical File Operations
2//!
3//! This module provides enterprise-grade path validation to prevent:
4//! - Path traversal attacks (../, ../../etc/passwd)
5//! - Symlink attacks (following links outside workspace)
6//! - Null byte injection
7//! - Unicode normalization attacks
8//! - Absolute path escapes
9//! - Depth limit violations
10//! - Extension mismatch attacks
11//!
12//! ## Usage
13//!
14//! ```rust,no_run
15//! use crate::utils::path_validator::{PathValidator, SafePath};
16//! use std::path::Path;
17//!
18//! # fn main() -> crate::utils::error::Result<()> {
19//! // Create validator with workspace root
20//! let validator = PathValidator::new(Path::new("/workspace"))
21//!     .with_max_depth(10)
22//!     .with_allowed_extensions(vec!["tmpl", "tera", "ttl", "rdf"]);
23//!
24//! // Validate a path
25//! let safe_path = validator.validate("templates/example.tera")?;
26//!
27//! // Use safe path for file operations
28//! let content = std::fs::read_to_string(safe_path.as_path())?;
29//! # Ok(())
30//! # }
31//! ```
32
33use crate::utils::error::{Error, Result};
34use std::collections::HashSet;
35use std::path::{Path, PathBuf};
36
37// ============================================================================
38// Error Types
39// ============================================================================
40
41/// Path validation error types
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum PathValidationError {
44    /// Path contains ".." components (path traversal attempt)
45    PathTraversal { path: String },
46    /// Path is absolute when relative was expected
47    AbsolutePath { path: String },
48    /// Path exceeds maximum allowed depth
49    DepthExceeded {
50        path: String,
51        depth: usize,
52        max: usize,
53    },
54    /// Path contains null bytes
55    NullByte { path: String },
56    /// Path has invalid extension
57    InvalidExtension { path: String, expected: Vec<String> },
58    /// Symlink points outside allowed workspace
59    SymlinkEscape { link: String, target: String },
60    /// Path escapes workspace root
61    WorkspaceEscape { path: String, workspace: String },
62    /// Path is empty
63    EmptyPath,
64    /// Invalid UTF-8 in path
65    InvalidUtf8 { path: String },
66    /// Unicode normalization issue
67    UnicodeNormalization { path: String, reason: String },
68}
69
70impl std::fmt::Display for PathValidationError {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        match self {
73            Self::PathTraversal { path } => {
74                write!(f, "Path traversal detected: {path} contains '..'")
75            }
76            Self::AbsolutePath { path } => {
77                write!(f, "Absolute path not allowed: {path}")
78            }
79            Self::DepthExceeded { path, depth, max } => {
80                write!(f, "Path depth {depth} exceeds maximum {max}: {path}")
81            }
82            Self::NullByte { path } => {
83                write!(f, "Path contains null byte: {path}")
84            }
85            Self::InvalidExtension { path, expected } => {
86                write!(
87                    f,
88                    "Invalid extension for {path}, expected one of: {}",
89                    expected.join(", ")
90                )
91            }
92            Self::SymlinkEscape { link, target } => {
93                write!(f, "Symlink {link} points outside workspace: {target}")
94            }
95            Self::WorkspaceEscape { path, workspace } => {
96                write!(f, "Path {path} escapes workspace {workspace}")
97            }
98            Self::EmptyPath => {
99                write!(f, "Path cannot be empty")
100            }
101            Self::InvalidUtf8 { path } => {
102                write!(f, "Path contains invalid UTF-8: {path}")
103            }
104            Self::UnicodeNormalization { path, reason } => {
105                write!(f, "Unicode normalization issue in {path}: {reason}")
106            }
107        }
108    }
109}
110
111impl std::error::Error for PathValidationError {}
112
113impl From<PathValidationError> for Error {
114    fn from(err: PathValidationError) -> Self {
115        Error::new(&err.to_string())
116    }
117}
118
119// ============================================================================
120// SafePath - Type-safe validated path
121// ============================================================================
122
123/// A path that has been validated and is safe to use for file operations
124///
125/// This type guarantees:
126/// - No path traversal components (..)
127/// - Within workspace bounds
128/// - Valid UTF-8
129/// - No null bytes
130/// - Extension matches expectations (if configured)
131/// - Depth within limits (if configured)
132#[derive(Debug, Clone, PartialEq, Eq, Hash)]
133pub struct SafePath {
134    /// The validated path (relative to workspace root)
135    inner: PathBuf,
136    /// Absolute path (resolved and validated)
137    absolute: PathBuf,
138}
139
140impl SafePath {
141    /// Get the relative path
142    #[must_use]
143    pub fn as_path(&self) -> &Path {
144        &self.inner
145    }
146
147    /// Get the absolute path
148    #[must_use]
149    pub fn absolute(&self) -> &Path {
150        &self.absolute
151    }
152
153    /// Convert to PathBuf
154    #[must_use]
155    pub fn to_path_buf(&self) -> PathBuf {
156        self.inner.clone()
157    }
158
159    /// Get file extension
160    #[must_use]
161    pub fn extension(&self) -> Option<&str> {
162        self.inner.extension().and_then(|s| s.to_str())
163    }
164
165    /// Get file name
166    #[must_use]
167    pub fn file_name(&self) -> Option<&str> {
168        self.inner.file_name().and_then(|s| s.to_str())
169    }
170}
171
172impl AsRef<Path> for SafePath {
173    fn as_ref(&self) -> &Path {
174        &self.inner
175    }
176}
177
178impl std::fmt::Display for SafePath {
179    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180        write!(f, "{}", self.inner.display())
181    }
182}
183
184// ============================================================================
185// PathValidator
186// ============================================================================
187
188/// Validates paths for security-critical file operations
189///
190/// Prevents common attack vectors:
191/// - Path traversal (../)
192/// - Symlink escapes
193/// - Null byte injection
194/// - Unicode normalization attacks
195/// - Absolute path escapes
196/// - Depth limit violations
197#[derive(Debug, Clone)]
198pub struct PathValidator {
199    /// Workspace root (all paths must be within this)
200    workspace_root: PathBuf,
201    /// Maximum path depth (number of components)
202    max_depth: Option<usize>,
203    /// Allowed file extensions (empty means all)
204    allowed_extensions: HashSet<String>,
205    /// Allow absolute paths
206    allow_absolute: bool,
207    /// Follow symlinks (with validation)
208    follow_symlinks: bool,
209}
210
211impl PathValidator {
212    /// Create a new validator with workspace root
213    ///
214    /// # Example
215    ///
216    /// ```rust
217    /// use crate::utils::path_validator::PathValidator;
218    /// use std::path::Path;
219    ///
220    /// let validator = PathValidator::new(Path::new("/workspace"));
221    /// ```
222    #[must_use]
223    pub fn new(workspace_root: &Path) -> Self {
224        Self {
225            workspace_root: workspace_root.to_path_buf(),
226            max_depth: None,
227            allowed_extensions: HashSet::new(),
228            allow_absolute: false,
229            follow_symlinks: true,
230        }
231    }
232
233    /// Set maximum path depth
234    #[must_use]
235    pub fn with_max_depth(mut self, max_depth: usize) -> Self {
236        self.max_depth = Some(max_depth);
237        self
238    }
239
240    /// Set allowed file extensions
241    #[must_use]
242    pub fn with_allowed_extensions(mut self, extensions: Vec<&str>) -> Self {
243        self.allowed_extensions = extensions.into_iter().map(|s| s.to_string()).collect();
244        self
245    }
246
247    /// Allow absolute paths
248    #[must_use]
249    pub fn with_absolute_paths(mut self, allow: bool) -> Self {
250        self.allow_absolute = allow;
251        self
252    }
253
254    /// Set whether to follow symlinks
255    #[must_use]
256    pub fn with_follow_symlinks(mut self, follow: bool) -> Self {
257        self.follow_symlinks = follow;
258        self
259    }
260
261    /// Validate a path and return a SafePath
262    ///
263    /// # Errors
264    ///
265    /// Returns error if path:
266    /// - Contains null bytes
267    /// - Contains ".." components
268    /// - Is absolute (unless allowed)
269    /// - Exceeds max depth
270    /// - Has invalid extension
271    /// - Escapes workspace
272    /// - Is a symlink pointing outside workspace
273    pub fn validate(&self, path: impl AsRef<Path>) -> Result<SafePath> {
274        let path = path.as_ref();
275
276        // Check for empty path
277        if path.as_os_str().is_empty() {
278            return Err(PathValidationError::EmptyPath.into());
279        }
280
281        // Validate UTF-8
282        let path_str = path
283            .to_str()
284            .ok_or_else(|| PathValidationError::InvalidUtf8 {
285                path: path.display().to_string(),
286            })?;
287
288        // Check for null bytes
289        if path_str.contains('\0') {
290            return Err(PathValidationError::NullByte {
291                path: path_str.to_string(),
292            }
293            .into());
294        }
295
296        // Check for path traversal
297        self.check_path_traversal(path)?;
298
299        // Check if absolute
300        if path.is_absolute() && !self.allow_absolute {
301            return Err(PathValidationError::AbsolutePath {
302                path: path_str.to_string(),
303            }
304            .into());
305        }
306
307        // Check depth
308        if let Some(max_depth) = self.max_depth {
309            let depth = path.components().count();
310            if depth > max_depth {
311                return Err(PathValidationError::DepthExceeded {
312                    path: path_str.to_string(),
313                    depth,
314                    max: max_depth,
315                }
316                .into());
317            }
318        }
319
320        // Check extension
321        if !self.allowed_extensions.is_empty() {
322            self.check_extension(path)?;
323        }
324
325        // Resolve to absolute path
326        let absolute = self.resolve_safely(path)?;
327
328        // Check workspace bounds
329        self.check_workspace_bounds(&absolute)?;
330
331        // Check symlinks
332        if self.follow_symlinks {
333            self.check_symlink(&absolute)?;
334        }
335
336        Ok(SafePath {
337            inner: path.to_path_buf(),
338            absolute,
339        })
340    }
341
342    /// Check for path traversal components
343    fn check_path_traversal(&self, path: &Path) -> Result<()> {
344        for component in path.components() {
345            if let std::path::Component::ParentDir = component {
346                return Err(PathValidationError::PathTraversal {
347                    path: path.display().to_string(),
348                }
349                .into());
350            }
351        }
352        Ok(())
353    }
354
355    /// Check file extension
356    fn check_extension(&self, path: &Path) -> Result<()> {
357        let ext = path.extension().and_then(|s| s.to_str()).ok_or_else(|| {
358            PathValidationError::InvalidExtension {
359                path: path.display().to_string(),
360                expected: self.allowed_extensions.iter().cloned().collect(),
361            }
362        })?;
363
364        if !self.allowed_extensions.contains(ext) {
365            return Err(PathValidationError::InvalidExtension {
366                path: path.display().to_string(),
367                expected: self.allowed_extensions.iter().cloned().collect(),
368            }
369            .into());
370        }
371
372        Ok(())
373    }
374
375    /// Resolve path safely to absolute path
376    fn resolve_safely(&self, path: &Path) -> Result<PathBuf> {
377        let base = if path.is_absolute() {
378            path.to_path_buf()
379        } else {
380            self.workspace_root.join(path)
381        };
382
383        // Canonicalize if exists, otherwise construct absolute path
384        if base.exists() {
385            base.canonicalize().map_err(|e| {
386                Error::new(&format!(
387                    "Failed to canonicalize path {}: {}",
388                    base.display(),
389                    e
390                ))
391            })
392        } else {
393            // For non-existent paths, manually construct absolute path against the
394            // CANONICAL workspace root. `check_workspace_bounds` canonicalizes the
395            // workspace before the containment check, so building on a non-canonical
396            // root (e.g. macOS `/tmp`, a symlink to `/private/tmp`) would make a
397            // perfectly valid path spuriously report a workspace escape.
398            let mut absolute = self
399                .workspace_root
400                .canonicalize()
401                .unwrap_or_else(|_| self.workspace_root.clone());
402            for component in path.components() {
403                match component {
404                    std::path::Component::Normal(c) => {
405                        absolute.push(c);
406                    }
407                    std::path::Component::RootDir if self.allow_absolute => {
408                        absolute = PathBuf::from("/");
409                    }
410                    std::path::Component::RootDir => {}
411                    std::path::Component::ParentDir => {
412                        // Already checked, should not reach here
413                        return Err(PathValidationError::PathTraversal {
414                            path: path.display().to_string(),
415                        }
416                        .into());
417                    }
418                    _ => {}
419                }
420            }
421            Ok(absolute)
422        }
423    }
424
425    /// Check if path is within workspace bounds
426    fn check_workspace_bounds(&self, absolute: &Path) -> Result<()> {
427        // Canonicalize workspace root
428        let workspace_canonical = self.workspace_root.canonicalize().map_err(|e| {
429            Error::new(&format!(
430                "Failed to canonicalize workspace root {}: {}",
431                self.workspace_root.display(),
432                e
433            ))
434        })?;
435
436        // Check if absolute path starts with workspace root
437        if !absolute.starts_with(&workspace_canonical) {
438            return Err(PathValidationError::WorkspaceEscape {
439                path: absolute.display().to_string(),
440                workspace: workspace_canonical.display().to_string(),
441            }
442            .into());
443        }
444
445        Ok(())
446    }
447
448    /// Check symlink target
449    fn check_symlink(&self, path: &Path) -> Result<()> {
450        // If path is a symlink, check where it points
451        if path.is_symlink() {
452            let target = std::fs::read_link(path).map_err(|e| {
453                Error::new(&format!("Failed to read symlink {}: {}", path.display(), e))
454            })?;
455
456            // Resolve target to absolute path
457            let target_absolute = if target.is_absolute() {
458                target
459            } else {
460                path.parent()
461                    .ok_or_else(|| Error::new("Symlink has no parent"))?
462                    .join(target)
463            };
464
465            // Check if target is within workspace
466            self.check_workspace_bounds(&target_absolute)?;
467        }
468
469        Ok(())
470    }
471
472    /// Validate a relative path doesn't escape workspace
473    ///
474    /// This is a convenience method for validating paths that should be relative.
475    pub fn validate_relative(&self, path: impl AsRef<Path>) -> Result<SafePath> {
476        let path = path.as_ref();
477
478        if path.is_absolute() {
479            return Err(PathValidationError::AbsolutePath {
480                path: path.display().to_string(),
481            }
482            .into());
483        }
484
485        self.validate(path)
486    }
487
488    /// Batch validate multiple paths
489    pub fn validate_batch(&self, paths: &[impl AsRef<Path>]) -> Result<Vec<SafePath>> {
490        paths.iter().map(|p| self.validate(p)).collect()
491    }
492}
493
494#[cfg(test)]
495mod tests {
496    use super::*;
497    use tempfile::tempdir;
498
499    // Arrange-Act-Assert pattern (Chicago TDD)
500
501    #[test]
502    fn test_valid_relative_path() {
503        // Arrange
504        let workspace = tempdir().expect("Failed to create temp dir");
505        let validator = PathValidator::new(workspace.path());
506
507        // Act
508        let result = validator.validate("templates/example.tera");
509
510        // Assert
511        assert!(result.is_ok());
512        let safe_path = result.expect("Should validate");
513        assert_eq!(safe_path.extension(), Some("tera"));
514    }
515
516    #[test]
517    fn test_path_traversal_blocked() {
518        // Arrange
519        let workspace = tempdir().expect("Failed to create temp dir");
520        let validator = PathValidator::new(workspace.path());
521
522        // Act
523        let result = validator.validate("../../../etc/passwd");
524
525        // Assert
526        assert!(result.is_err());
527        let err = result.unwrap_err();
528        assert!(err.to_string().contains("Path traversal"));
529    }
530
531    #[test]
532    fn test_null_byte_blocked() {
533        // Arrange
534        let workspace = tempdir().expect("Failed to create temp dir");
535        let validator = PathValidator::new(workspace.path());
536
537        // Act
538        let result = validator.validate("file\0.txt");
539
540        // Assert
541        assert!(result.is_err());
542        let err = result.unwrap_err();
543        assert!(err.to_string().contains("null byte"));
544    }
545
546    #[test]
547    fn test_absolute_path_blocked_by_default() {
548        // Arrange
549        let workspace = tempdir().expect("Failed to create temp dir");
550        let validator = PathValidator::new(workspace.path());
551
552        // Act
553        let result = validator.validate("/etc/passwd");
554
555        // Assert
556        assert!(result.is_err());
557        let err = result.unwrap_err();
558        assert!(err.to_string().contains("Absolute path"));
559    }
560
561    #[test]
562    fn test_absolute_path_allowed_when_configured() {
563        // Arrange
564        let workspace = tempdir().expect("Failed to create temp dir");
565        let validator = PathValidator::new(workspace.path()).with_absolute_paths(true);
566
567        // Act
568        let test_file = workspace.path().join("test.txt");
569        std::fs::write(&test_file, "test").expect("Failed to create test file");
570        let result = validator.validate(&test_file);
571
572        // Assert
573        assert!(result.is_ok());
574    }
575
576    #[test]
577    fn test_depth_limit_enforced() {
578        // Arrange
579        let workspace = tempdir().expect("Failed to create temp dir");
580        let validator = PathValidator::new(workspace.path()).with_max_depth(3);
581
582        // Act
583        let deep_path = "a/b/c/d/e/f/g.txt";
584        let result = validator.validate(deep_path);
585
586        // Assert
587        assert!(result.is_err());
588        let err = result.unwrap_err();
589        assert!(err.to_string().contains("depth"));
590    }
591
592    #[test]
593    fn test_extension_validation() {
594        // Arrange
595        let workspace = tempdir().expect("Failed to create temp dir");
596        let validator =
597            PathValidator::new(workspace.path()).with_allowed_extensions(vec!["tera", "tmpl"]);
598
599        // Act - valid extension
600        let result_valid = validator.validate("template.tera");
601        assert!(result_valid.is_ok());
602
603        // Act - invalid extension
604        let result_invalid = validator.validate("script.sh");
605
606        // Assert
607        assert!(result_invalid.is_err());
608        let err = result_invalid.unwrap_err();
609        assert!(err.to_string().contains("Invalid extension"));
610    }
611
612    #[test]
613    fn test_empty_path_blocked() {
614        // Arrange
615        let workspace = tempdir().expect("Failed to create temp dir");
616        let validator = PathValidator::new(workspace.path());
617
618        // Act
619        let result = validator.validate("");
620
621        // Assert
622        assert!(result.is_err());
623        let err = result.unwrap_err();
624        assert!(err.to_string().contains("empty"));
625    }
626
627    #[test]
628    fn test_workspace_escape_blocked() {
629        // Arrange
630        let workspace = tempdir().expect("Failed to create temp dir");
631        let validator = PathValidator::new(workspace.path()).with_absolute_paths(true);
632
633        // Act - try to access outside workspace
634        let result = validator.validate("/etc/passwd");
635
636        // Assert
637        assert!(result.is_err());
638        let err = result.unwrap_err();
639        assert!(err.to_string().contains("workspace"));
640    }
641
642    #[test]
643    fn test_symlink_validation() {
644        // Arrange
645        let workspace = tempdir().expect("Failed to create temp dir");
646        let validator = PathValidator::new(workspace.path());
647
648        // Create a file and symlink inside workspace
649        let target = workspace.path().join("target.txt");
650        std::fs::write(&target, "content").expect("Failed to create target file");
651
652        let link = workspace.path().join("link.txt");
653        #[cfg(unix)]
654        std::os::unix::fs::symlink(&target, &link).expect("Failed to create symlink");
655
656        // Act
657        #[cfg(unix)]
658        let result = validator.validate("link.txt");
659
660        // Assert
661        #[cfg(unix)]
662        assert!(result.is_ok());
663    }
664
665    #[test]
666    fn test_batch_validation() {
667        // Arrange
668        let workspace = tempdir().expect("Failed to create temp dir");
669        let validator = PathValidator::new(workspace.path());
670
671        let paths = vec!["file1.txt", "file2.txt", "templates/example.tera"];
672
673        // Act
674        let result = validator.validate_batch(&paths);
675
676        // Assert
677        assert!(result.is_ok());
678        let safe_paths = result.expect("Should validate all");
679        assert_eq!(safe_paths.len(), 3);
680    }
681
682    #[test]
683    fn test_safe_path_accessors() {
684        // Arrange
685        let workspace = tempdir().expect("Failed to create temp dir");
686        let validator = PathValidator::new(workspace.path());
687
688        // Act
689        let safe_path = validator
690            .validate("templates/example.tera")
691            .expect("Should validate");
692
693        // Assert
694        assert_eq!(safe_path.extension(), Some("tera"));
695        assert_eq!(safe_path.file_name(), Some("example.tera"));
696        assert_eq!(safe_path.as_path(), Path::new("templates/example.tera"));
697    }
698
699    #[test]
700    fn test_unicode_path_handling() {
701        // Arrange
702        let workspace = tempdir().expect("Failed to create temp dir");
703        let validator = PathValidator::new(workspace.path());
704
705        // Act - Unicode characters in path
706        let result = validator.validate("templates/例え.tera");
707
708        // Assert
709        assert!(result.is_ok());
710    }
711
712    #[test]
713    fn test_validate_relative_rejects_absolute() {
714        // Arrange
715        let workspace = tempdir().expect("Failed to create temp dir");
716        let validator = PathValidator::new(workspace.path());
717
718        // Act
719        let result = validator.validate_relative("/etc/passwd");
720
721        // Assert
722        assert!(result.is_err());
723        let err = result.unwrap_err();
724        assert!(err.to_string().contains("Absolute path"));
725    }
726}