-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpath_utils.rs
More file actions
561 lines (497 loc) · 17.9 KB
/
path_utils.rs
File metadata and controls
561 lines (497 loc) · 17.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! Path utilities for safe path handling and validation.
//!
//! This module provides utilities for:
//! - Normalizing paths (resolving `.` and `..` components)
//! - Expanding home directory (`~`)
//! - Validating paths are within allowed roots
//! - Ensuring parent directories exist
//!
//! # Security
//! These utilities help prevent path traversal attacks by:
//! - Normalizing paths before validation
//! - Checking paths stay within allowed roots
//! - Validating symlink targets
//!
//! # Examples
//!
//! ```rust,ignore
//! use cortex_common::path_utils::*;
//! use std::path::Path;
//!
//! // Normalize a path
//! let normalized = normalize_path(Path::new("/a/b/../c"));
//! assert_eq!(normalized, std::path::PathBuf::from("/a/c"));
//!
//! // Expand home directory
//! let expanded = expand_home_path(Path::new("~/documents"));
//! // Returns something like /home/user/documents
//!
//! // Validate path is safe
//! let root = Path::new("/workspace");
//! let safe = validate_path_safe(Path::new("/workspace/src/main.rs"), root)?;
//! ```
use std::io;
use std::path::{Component, Path, PathBuf};
/// Errors that can occur during path operations.
#[derive(Debug, Clone)]
pub enum PathError {
/// Path traversal detected outside allowed root.
PathTraversal { path: String, root: String },
/// Failed to canonicalize path.
CanonicalizationFailed { path: String, reason: String },
/// Failed to create parent directory.
CreateDirFailed { path: String, reason: String },
/// Symlink points outside allowed root.
SymlinkEscape {
link: String,
target: String,
root: String,
},
/// Path does not exist and allow_nonexistent is false.
PathNotFound { path: String },
}
impl std::fmt::Display for PathError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PathError::PathTraversal { path, root } => {
write!(f, "Path '{}' is outside allowed root '{}'", path, root)
}
PathError::CanonicalizationFailed { path, reason } => {
write!(f, "Failed to canonicalize '{}': {}", path, reason)
}
PathError::CreateDirFailed { path, reason } => {
write!(f, "Failed to create directory '{}': {}", path, reason)
}
PathError::SymlinkEscape { link, target, root } => {
write!(
f,
"Symlink '{}' points to '{}' which is outside root '{}'",
link, target, root
)
}
PathError::PathNotFound { path } => {
write!(f, "Path '{}' does not exist", path)
}
}
}
}
impl std::error::Error for PathError {}
/// Result type for path operations.
pub type PathResult<T> = Result<T, PathError>;
/// Normalizes a path by resolving `.` and `..` components without filesystem access.
///
/// This function:
/// - Removes `.` (current directory) components
/// - Resolves `..` (parent directory) components
/// - Does NOT access the filesystem
/// - Works with both absolute and relative paths
///
/// # Arguments
/// * `path` - The path to normalize
///
/// # Returns
/// A normalized `PathBuf` with traversal sequences resolved.
///
/// # Examples
/// ```rust,ignore
/// use cortex_common::path_utils::normalize_path;
/// use std::path::Path;
///
/// let path = Path::new("/a/b/../c/./d");
/// let normalized = normalize_path(path);
/// assert_eq!(normalized, std::path::PathBuf::from("/a/c/d"));
/// ```
pub fn normalize_path(path: &Path) -> PathBuf {
let mut normalized = PathBuf::new();
for component in path.components() {
match component {
Component::ParentDir => {
// Go up one level, but don't go above root
if !normalized.pop() {
// If we can't pop, we're at root level
// For relative paths this could be problematic
if !path.is_absolute() {
normalized.push("..");
}
}
}
Component::CurDir => {
// Current directory - skip it
}
_ => {
normalized.push(component);
}
}
}
normalized
}
/// Expands the home directory (`~`) in a path.
///
/// This function:
/// - Replaces `~` at the start of a path with the user's home directory
/// - Returns the path unchanged if it doesn't start with `~`
/// - Returns an error if home directory cannot be determined
///
/// # Arguments
/// * `path` - The path to expand
///
/// # Returns
/// * `Ok(PathBuf)` - The path with `~` expanded to home directory
/// * `Err(PathError)` - If home directory cannot be determined
///
/// # Examples
/// ```rust,ignore
/// use cortex_common::path_utils::expand_home_path;
/// use std::path::Path;
///
/// let path = Path::new("~/documents/file.txt");
/// let expanded = expand_home_path(path)?;
/// // Returns something like /home/user/documents/file.txt
/// ```
pub fn expand_home_path(path: &Path) -> PathResult<PathBuf> {
let path_str = path.to_string_lossy();
if !path_str.starts_with('~') {
return Ok(path.to_path_buf());
}
let home = dirs::home_dir().ok_or_else(|| PathError::CanonicalizationFailed {
path: path.display().to_string(),
reason: "Could not determine home directory".to_string(),
})?;
if path_str == "~" {
Ok(home)
} else if path_str.starts_with("~/") {
Ok(home.join(&path_str[2..]))
} else {
// Path like ~user/something - not supported, return as-is
Ok(path.to_path_buf())
}
}
/// Validates that a path is within a specified root directory.
///
/// This function:
/// 1. Normalizes both paths to resolve `.` and `..`
/// 2. Checks that the normalized path starts with the root
/// 3. Optionally validates symlinks don't escape
/// 4. Optionally requires the path to exist
///
/// # Arguments
/// * `path` - The path to validate
/// * `root` - The allowed root directory
///
/// # Returns
/// * `Ok(PathBuf)` - The validated safe path
/// * `Err(PathError)` - If validation fails
///
/// # Examples
/// ```rust,ignore
/// use cortex_common::path_utils::validate_path_safe;
/// use std::path::Path;
///
/// let root = Path::new("/workspace");
/// let safe = validate_path_safe(Path::new("/workspace/src/main.rs"), root)?;
/// ```
pub fn validate_path_safe(path: &Path, root: &Path) -> PathResult<PathBuf> {
// Get canonical root if it exists, otherwise normalize
let canonical_root = if root.exists() {
root.canonicalize()
.map_err(|e| PathError::CanonicalizationFailed {
path: root.display().to_string(),
reason: e.to_string(),
})?
} else {
normalize_path(root)
};
// Handle the target path
let validated_path = if path.exists() {
// Path exists - canonicalize it
path.canonicalize()
.map_err(|e| PathError::CanonicalizationFailed {
path: path.display().to_string(),
reason: e.to_string(),
})?
} else {
// Path doesn't exist - normalize it
// If the path is relative, make it absolute relative to root
let absolute_path = if path.is_absolute() {
path.to_path_buf()
} else {
canonical_root.join(path)
};
normalize_path(&absolute_path)
};
// Final validation: ensure path is within root
if !validated_path.starts_with(&canonical_root) {
return Err(PathError::PathTraversal {
path: validated_path.display().to_string(),
root: canonical_root.display().to_string(),
});
}
// Check symlinks for existing paths
if path.exists() {
if let Ok(metadata) = std::fs::symlink_metadata(path) {
if metadata.file_type().is_symlink() {
if let Ok(target) = std::fs::read_link(path) {
let absolute_target = if target.is_absolute() {
target
} else {
path.parent().map(|p| p.join(&target)).unwrap_or(target)
};
let target_canonical = if absolute_target.exists() {
absolute_target.canonicalize().map_err(|e| {
PathError::CanonicalizationFailed {
path: absolute_target.display().to_string(),
reason: e.to_string(),
}
})?
} else {
normalize_path(&absolute_target)
};
if !target_canonical.starts_with(&canonical_root) {
return Err(PathError::SymlinkEscape {
link: path.display().to_string(),
target: target_canonical.display().to_string(),
root: canonical_root.display().to_string(),
});
}
}
}
}
}
Ok(validated_path)
}
/// Ensures that the parent directory of a path exists, creating it if necessary.
///
/// This function:
/// - Creates all parent directories if they don't exist
/// - Does nothing if parent already exists
/// - Returns the path if successful
/// - Returns an error if creation fails
///
/// # Arguments
/// * `path` - The path whose parent directory should be ensured
///
/// # Returns
/// * `Ok(PathBuf)` - The original path
/// * `Err(PathError)` - If parent directory creation fails
///
/// # Examples
/// ```rust,ignore
/// use cortex_common::path_utils::ensure_parent_dir;
/// use std::path::Path;
///
/// let path = Path::new("/tmp/new_dir/file.txt");
/// let result = ensure_parent_dir(path)?;
/// // /tmp/new_dir/ now exists
/// ```
pub fn ensure_parent_dir(path: &Path) -> PathResult<PathBuf> {
if let Some(parent) = path.parent() {
if !parent.as_os_str().is_empty() && !parent.exists() {
std::fs::create_dir_all(parent).map_err(|e| PathError::CreateDirFailed {
path: parent.display().to_string(),
reason: e.to_string(),
})?;
}
}
Ok(path.to_path_buf())
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::TempDir;
#[test]
#[cfg_attr(windows, ignore = "Unix path format not applicable on Windows")]
fn test_normalize_path_simple() {
let path = Path::new("/a/b/../c");
assert_eq!(normalize_path(path), PathBuf::from("/a/c"));
}
#[test]
#[cfg_attr(windows, ignore = "Unix path format not applicable on Windows")]
fn test_normalize_path_multiple_parent_dirs() {
let path = Path::new("/a/b/c/../../d");
assert_eq!(normalize_path(path), PathBuf::from("/a/d"));
}
#[test]
#[cfg_attr(windows, ignore = "Unix path format not applicable on Windows")]
fn test_normalize_path_current_dir() {
let path = Path::new("/a/./b/./c");
assert_eq!(normalize_path(path), PathBuf::from("/a/b/c"));
}
#[test]
#[cfg_attr(windows, ignore = "Unix path format not applicable on Windows")]
fn test_normalize_path_mixed() {
let path = Path::new("/a/./b/../c/./d/../e");
assert_eq!(normalize_path(path), PathBuf::from("/a/c/e"));
}
#[test]
fn test_normalize_path_relative() {
let path = Path::new("a/b/../c");
assert_eq!(normalize_path(path), PathBuf::from("a/c"));
}
#[test]
fn test_normalize_path_relative_parent() {
let path = Path::new("a/b/../../c");
// When we go above the root of a relative path, we can't go further
// So a/b/../../c becomes c (we pop a, then b, then try to pop again but can't)
assert_eq!(normalize_path(path), PathBuf::from("c"));
}
#[test]
fn test_expand_home_path_no_tilde() {
let path = Path::new("/home/user/documents");
let expanded = expand_home_path(path).unwrap();
assert_eq!(expanded, PathBuf::from("/home/user/documents"));
}
#[test]
fn test_expand_home_path_with_tilde() {
let path = Path::new("~/documents");
let expanded = expand_home_path(path).unwrap();
let home = dirs::home_dir().unwrap();
assert_eq!(expanded, home.join("documents"));
}
#[test]
fn test_expand_home_path_tilde_only() {
let path = Path::new("~");
let expanded = expand_home_path(path).unwrap();
let home = dirs::home_dir().unwrap();
assert_eq!(expanded, home);
}
#[test]
fn test_expand_home_path_tilde_in_middle() {
// Tilde in the middle of a path should NOT be expanded
// This tests the case where a username contains a tilde (e.g., /home/test~user)
let path = Path::new("/home/test~user/.cortex");
let expanded = expand_home_path(path).unwrap();
// Path should be unchanged since tilde is not at the start
assert_eq!(expanded, PathBuf::from("/home/test~user/.cortex"));
}
#[test]
fn test_expand_home_path_tilde_in_filename() {
// Tilde in a filename should NOT be expanded
let path = Path::new("/home/user/backup~file.txt");
let expanded = expand_home_path(path).unwrap();
assert_eq!(expanded, PathBuf::from("/home/user/backup~file.txt"));
}
#[test]
fn test_validate_path_safe_within_root() {
let temp_dir = TempDir::new().unwrap();
let root = temp_dir.path();
// Create test file
fs::write(root.join("file.txt"), "test").unwrap();
// Valid path should pass
let result = validate_path_safe(&root.join("file.txt"), root);
assert!(result.is_ok());
}
#[test]
fn test_validate_path_safe_traversal_attempt() {
let temp_dir = TempDir::new().unwrap();
let root = temp_dir.path();
// Create test structure
fs::create_dir_all(root.join("subdir")).unwrap();
// Path traversal should fail
let traversal = root.join("subdir/../../../etc/passwd");
let result = validate_path_safe(&traversal, root);
assert!(result.is_err());
}
#[test]
fn test_validate_path_safe_nonexistent_within_root() {
let temp_dir = TempDir::new().unwrap();
let root = temp_dir.path();
// Non-existent but valid path should pass
let new_file = root.join("new_file.txt");
let result = validate_path_safe(&new_file, root);
assert!(result.is_ok());
}
#[test]
fn test_validate_path_safe_nonexistent_traversal() {
let temp_dir = TempDir::new().unwrap();
let root = temp_dir.path();
// Non-existent path with traversal should fail
let traversal = root.join("../outside.txt");
let result = validate_path_safe(&traversal, root);
assert!(result.is_err());
}
#[test]
fn test_validate_path_safe_relative_path() {
let temp_dir = TempDir::new().unwrap();
let root = temp_dir.path();
// Create subdir
fs::create_dir_all(root.join("subdir")).unwrap();
// Relative path within root should pass
let result = validate_path_safe(Path::new("file.txt"), root);
assert!(result.is_ok());
}
#[test]
fn test_ensure_parent_dir_creates_single_level() {
let temp_dir = TempDir::new().unwrap();
let path = temp_dir.path().join("newdir").join("file.txt");
// Parent should not exist yet
assert!(!path.parent().unwrap().exists());
// Ensure parent
let result = ensure_parent_dir(&path);
assert!(result.is_ok());
// Parent should now exist
assert!(path.parent().unwrap().exists());
}
#[test]
fn test_ensure_parent_dir_creates_multiple_levels() {
let temp_dir = TempDir::new().unwrap();
let path = temp_dir
.path()
.join("a")
.join("b")
.join("c")
.join("file.txt");
// Ensure parent
let result = ensure_parent_dir(&path);
assert!(result.is_ok());
// All parents should exist
assert!(path.parent().unwrap().exists());
}
#[test]
fn test_ensure_parent_dir_already_exists() {
let temp_dir = TempDir::new().unwrap();
let path = temp_dir.path().join("file.txt");
// Parent already exists
assert!(path.parent().unwrap().exists());
// Ensure parent should still succeed
let result = ensure_parent_dir(&path);
assert!(result.is_ok());
}
#[test]
#[cfg_attr(windows, ignore = "Unix root path not applicable on Windows")]
fn test_ensure_parent_dir_root_path() {
let path = Path::new("/file.txt");
// Root path should succeed (parent is root)
let result = ensure_parent_dir(path);
assert!(result.is_ok());
}
#[test]
#[cfg(unix)]
fn test_validate_path_safe_symlink_within_root() {
let temp_dir = TempDir::new().unwrap();
let root = temp_dir.path();
// Create a file and a symlink within root
let file = root.join("file.txt");
fs::write(&file, "test").unwrap();
let symlink = root.join("link.txt");
std::os::unix::fs::symlink(&file, &symlink).unwrap();
// Symlink within root should pass
let result = validate_path_safe(&symlink, root);
assert!(result.is_ok());
}
#[test]
#[cfg(unix)]
fn test_validate_path_safe_symlink_escape() {
let temp_dir = TempDir::new().unwrap();
let root = temp_dir.path();
// Create a file outside root
let outside_file = temp_dir.path().parent().unwrap().join("outside.txt");
fs::write(&outside_file, "outside").unwrap();
// Create a symlink inside root pointing outside
let escape_link = root.join("escape_link.txt");
std::os::unix::fs::symlink(&outside_file, &escape_link).unwrap();
// Symlink escaping root should fail
let result = validate_path_safe(&escape_link, root);
assert!(result.is_err());
}
}