|
1 | 1 | //! Path safety validation logic. |
2 | 2 |
|
3 | 3 | use crate::errors::ProcessError; |
| 4 | +use std::fs; // Use fs::metadata |
4 | 5 | use std::io::ErrorKind; |
5 | 6 | use std::path::Path; |
6 | 7 |
|
7 | 8 | /// Checks if the target path is safely within the base directory. |
8 | | -/// Canonicalizes both paths for reliable comparison. |
| 9 | +/// Canonicalizes paths for reliable comparison. |
9 | 10 | pub(crate) fn ensure_path_safe(base_dir: &Path, target_path: &Path) -> Result<(), ProcessError> { |
10 | 11 | // Canonicalize base directory (must succeed as it's resolved in process_actions) |
11 | 12 | let canonical_base = base_dir |
12 | 13 | .canonicalize() |
13 | 14 | .map_err(|e| ProcessError::Io { source: e })?; |
14 | 15 |
|
15 | | - // Attempt to canonicalize the target path. |
16 | | - match target_path.canonicalize() { |
17 | | - Ok(canonical_target) => { |
18 | | - // If target exists and canonicalizes, check if it starts with the base |
19 | | - if canonical_target.starts_with(&canonical_base) { |
20 | | - Ok(()) // Path is safe |
21 | | - } else { |
22 | | - Err(ProcessError::PathNotSafe { |
23 | | - resolved_path: canonical_target, |
24 | | - base_path: canonical_base, |
25 | | - }) |
| 16 | + // Check if the target path *exists* first using metadata. |
| 17 | + match fs::metadata(target_path) { |
| 18 | + Ok(_) => { |
| 19 | + // Target exists. Canonicalize it for the safety check. |
| 20 | + match target_path.canonicalize() { |
| 21 | + Ok(canonical_target) => { |
| 22 | + if canonical_target.starts_with(&canonical_base) { |
| 23 | + Ok(()) // Path exists and is safe |
| 24 | + } else { |
| 25 | + Err(ProcessError::PathNotSafe { |
| 26 | + resolved_path: canonical_target, |
| 27 | + base_path: canonical_base, |
| 28 | + }) |
| 29 | + } |
| 30 | + } |
| 31 | + Err(e) => { |
| 32 | + // Error canonicalizing an *existing* path (permissions?) |
| 33 | + Err(ProcessError::PathResolution { |
| 34 | + path: target_path.to_path_buf(), |
| 35 | + details: format!("Failed to canonicalize existing target path: {}", e), |
| 36 | + }) |
| 37 | + } |
26 | 38 | } |
27 | 39 | } |
28 | 40 | Err(ref e) if e.kind() == ErrorKind::NotFound => { |
29 | 41 | // Target doesn't exist: Check safety based on its intended parent. |
30 | 42 | check_nonexistent_target_safety(target_path, &canonical_base) |
31 | 43 | } |
32 | 44 | Err(e) => { |
33 | | - // Other error during canonicalization (e.g., permission denied) |
34 | | - Err(ProcessError::PathResolution { |
35 | | - path: target_path.to_path_buf(), |
36 | | - details: format!("Failed to canonicalize target path: {}", e), |
37 | | - }) |
| 45 | + // Other error getting metadata (permissions?) |
| 46 | + Err(ProcessError::Io { source: e }) // Map other metadata errors to IO |
38 | 47 | } |
39 | 48 | } |
40 | 49 | } |
|
0 commit comments