1use crate::utils::error::{Error, Result};
34use std::collections::HashSet;
35use std::path::{Path, PathBuf};
36
37#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum PathValidationError {
44 PathTraversal { path: String },
46 AbsolutePath { path: String },
48 DepthExceeded {
50 path: String,
51 depth: usize,
52 max: usize,
53 },
54 NullByte { path: String },
56 InvalidExtension { path: String, expected: Vec<String> },
58 SymlinkEscape { link: String, target: String },
60 WorkspaceEscape { path: String, workspace: String },
62 EmptyPath,
64 InvalidUtf8 { path: String },
66 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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
133pub struct SafePath {
134 inner: PathBuf,
136 absolute: PathBuf,
138}
139
140impl SafePath {
141 #[must_use]
143 pub fn as_path(&self) -> &Path {
144 &self.inner
145 }
146
147 #[must_use]
149 pub fn absolute(&self) -> &Path {
150 &self.absolute
151 }
152
153 #[must_use]
155 pub fn to_path_buf(&self) -> PathBuf {
156 self.inner.clone()
157 }
158
159 #[must_use]
161 pub fn extension(&self) -> Option<&str> {
162 self.inner.extension().and_then(|s| s.to_str())
163 }
164
165 #[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#[derive(Debug, Clone)]
198pub struct PathValidator {
199 workspace_root: PathBuf,
201 max_depth: Option<usize>,
203 allowed_extensions: HashSet<String>,
205 allow_absolute: bool,
207 follow_symlinks: bool,
209}
210
211impl PathValidator {
212 #[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 #[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 #[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 #[must_use]
249 pub fn with_absolute_paths(mut self, allow: bool) -> Self {
250 self.allow_absolute = allow;
251 self
252 }
253
254 #[must_use]
256 pub fn with_follow_symlinks(mut self, follow: bool) -> Self {
257 self.follow_symlinks = follow;
258 self
259 }
260
261 pub fn validate(&self, path: impl AsRef<Path>) -> Result<SafePath> {
274 let path = path.as_ref();
275
276 if path.as_os_str().is_empty() {
278 return Err(PathValidationError::EmptyPath.into());
279 }
280
281 let path_str = path
283 .to_str()
284 .ok_or_else(|| PathValidationError::InvalidUtf8 {
285 path: path.display().to_string(),
286 })?;
287
288 if path_str.contains('\0') {
290 return Err(PathValidationError::NullByte {
291 path: path_str.to_string(),
292 }
293 .into());
294 }
295
296 self.check_path_traversal(path)?;
298
299 if path.is_absolute() && !self.allow_absolute {
301 return Err(PathValidationError::AbsolutePath {
302 path: path_str.to_string(),
303 }
304 .into());
305 }
306
307 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 if !self.allowed_extensions.is_empty() {
322 self.check_extension(path)?;
323 }
324
325 let absolute = self.resolve_safely(path)?;
327
328 self.check_workspace_bounds(&absolute)?;
330
331 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 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 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 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 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 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 return Err(PathValidationError::PathTraversal {
414 path: path.display().to_string(),
415 }
416 .into());
417 }
418 _ => {}
419 }
420 }
421 Ok(absolute)
422 }
423 }
424
425 fn check_workspace_bounds(&self, absolute: &Path) -> Result<()> {
427 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 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 fn check_symlink(&self, path: &Path) -> Result<()> {
450 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 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 self.check_workspace_bounds(&target_absolute)?;
467 }
468
469 Ok(())
470 }
471
472 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 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 #[test]
502 fn test_valid_relative_path() {
503 let workspace = tempdir().expect("Failed to create temp dir");
505 let validator = PathValidator::new(workspace.path());
506
507 let result = validator.validate("templates/example.tera");
509
510 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 let workspace = tempdir().expect("Failed to create temp dir");
520 let validator = PathValidator::new(workspace.path());
521
522 let result = validator.validate("../../../etc/passwd");
524
525 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 let workspace = tempdir().expect("Failed to create temp dir");
535 let validator = PathValidator::new(workspace.path());
536
537 let result = validator.validate("file\0.txt");
539
540 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 let workspace = tempdir().expect("Failed to create temp dir");
550 let validator = PathValidator::new(workspace.path());
551
552 let result = validator.validate("/etc/passwd");
554
555 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 let workspace = tempdir().expect("Failed to create temp dir");
565 let validator = PathValidator::new(workspace.path()).with_absolute_paths(true);
566
567 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!(result.is_ok());
574 }
575
576 #[test]
577 fn test_depth_limit_enforced() {
578 let workspace = tempdir().expect("Failed to create temp dir");
580 let validator = PathValidator::new(workspace.path()).with_max_depth(3);
581
582 let deep_path = "a/b/c/d/e/f/g.txt";
584 let result = validator.validate(deep_path);
585
586 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 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 let result_valid = validator.validate("template.tera");
601 assert!(result_valid.is_ok());
602
603 let result_invalid = validator.validate("script.sh");
605
606 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 let workspace = tempdir().expect("Failed to create temp dir");
616 let validator = PathValidator::new(workspace.path());
617
618 let result = validator.validate("");
620
621 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 let workspace = tempdir().expect("Failed to create temp dir");
631 let validator = PathValidator::new(workspace.path()).with_absolute_paths(true);
632
633 let result = validator.validate("/etc/passwd");
635
636 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 let workspace = tempdir().expect("Failed to create temp dir");
646 let validator = PathValidator::new(workspace.path());
647
648 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 #[cfg(unix)]
658 let result = validator.validate("link.txt");
659
660 #[cfg(unix)]
662 assert!(result.is_ok());
663 }
664
665 #[test]
666 fn test_batch_validation() {
667 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 let result = validator.validate_batch(&paths);
675
676 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 let workspace = tempdir().expect("Failed to create temp dir");
686 let validator = PathValidator::new(workspace.path());
687
688 let safe_path = validator
690 .validate("templates/example.tera")
691 .expect("Should validate");
692
693 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 let workspace = tempdir().expect("Failed to create temp dir");
703 let validator = PathValidator::new(workspace.path());
704
705 let result = validator.validate("templates/例え.tera");
707
708 assert!(result.is_ok());
710 }
711
712 #[test]
713 fn test_validate_relative_rejects_absolute() {
714 let workspace = tempdir().expect("Failed to create temp dir");
716 let validator = PathValidator::new(workspace.path());
717
718 let result = validator.validate_relative("/etc/passwd");
720
721 assert!(result.is_err());
723 let err = result.unwrap_err();
724 assert!(err.to_string().contains("Absolute path"));
725 }
726}