asupersync 0.3.6

Spec-first, cancel-correct, capability-secure async runtime for Rust.
Documentation
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
562
563
564
565
//! Secure path validation utilities for preventing directory traversal attacks.
//!
//! This module provides path canonicalization and bounds checking to ensure
//! user-supplied paths cannot escape intended directories or access sensitive
//! system files.
//!
//! # Security Model
//!
//! 1. **Canonicalization**: All paths are canonicalized to resolve ".." and "." components
//! 2. **Bounds checking**: Canonical paths must stay within allowed directories
//! 3. **Fail-safe**: Invalid or suspicious paths are rejected with clear error messages
//! 4. **Audit trail**: Security violations are logged for monitoring
//!
//! # Example
//!
//! ```ignore
//! use asupersync::util::path_security::{SecurePath, PathSecurityError};
//!
//! // Create a secure path validator with allowed base directory
//! let secure_path = SecurePath::new("/app/data")?;
//!
//! // Validate a user-supplied path
//! let validated = secure_path.validate_path("configs/app.toml")?;
//! assert_eq!(validated.as_path(), Path::new("/app/data/configs/app.toml"));
//!
//! // This would fail with PathTraversalAttempt error
//! let result = secure_path.validate_path("../../etc/passwd");
//! assert!(result.is_err());
//! ```

use std::fs::{self, File, OpenOptions};
use std::io::{self, Write};
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Component, Path, PathBuf};
use thiserror::Error;

/// Errors that can occur during path security validation.
#[derive(Error, Debug)]
pub enum PathSecurityError {
    /// Path contains directory traversal attempts (e.g., "../../../etc/passwd").
    #[error("Path traversal attempt detected: {path}")]
    PathTraversalAttempt { path: String },

    /// Path canonicalization failed due to I/O error.
    #[error("Failed to canonicalize path {path}: {source}")]
    CanonicalizationFailed {
        path: String,
        #[source]
        source: std::io::Error,
    },

    /// Canonical path is outside the allowed bounds.
    #[error("Path {path} is outside allowed bounds {allowed_base}")]
    OutsideAllowedBounds { path: String, allowed_base: String },

    /// Base directory does not exist or is not accessible.
    #[error("Base directory {base} is not accessible: {source}")]
    BaseDirectoryInaccessible {
        base: String,
        #[source]
        source: std::io::Error,
    },

    /// Path is empty or contains null bytes.
    #[error("Invalid path: {reason}")]
    InvalidPath { reason: String },
}

/// A validated and canonicalized secure path.
#[derive(Debug, Clone)]
pub struct ValidatedPath {
    /// The canonicalized path that has been validated as safe.
    canonical_path: PathBuf,
    /// The original user-supplied path for audit purposes.
    original_path: String,
}

impl ValidatedPath {
    /// Get the validated canonical path.
    pub fn as_path(&self) -> &Path {
        &self.canonical_path
    }

    /// Get the validated canonical path as PathBuf.
    pub fn to_path_buf(&self) -> PathBuf {
        self.canonical_path.clone()
    }

    /// Get the original user-supplied path for audit/logging.
    pub fn original_path(&self) -> &str {
        &self.original_path
    }
}

/// Secure path validator that prevents directory traversal attacks.
#[derive(Debug, Clone)]
pub struct SecurePath {
    /// The canonicalized base directory that constrains all validated paths.
    allowed_base: PathBuf,
}

impl SecurePath {
    /// Create a new secure path validator with the given base directory.
    ///
    /// The base directory must exist and be accessible. All validated paths
    /// will be constrained to stay within this directory tree.
    pub fn new<P: AsRef<Path>>(base_dir: P) -> Result<Self, PathSecurityError> {
        let base_path = base_dir.as_ref();

        // Canonicalize the base directory to ensure it's absolute and resolved
        let allowed_base =
            base_path
                .canonicalize()
                .map_err(|e| PathSecurityError::BaseDirectoryInaccessible {
                    base: base_path.display().to_string(),
                    source: e,
                })?;

        Ok(Self { allowed_base })
    }

    /// Validate a user-supplied path to ensure it's safe for file operations.
    ///
    /// This method performs the following security checks:
    /// 1. Validates the path is not empty and contains no null bytes
    /// 2. Joins the path with the allowed base directory
    /// 3. Canonicalizes the result to resolve any ".." or "." components
    /// 4. Verifies the canonical path stays within the allowed base
    ///
    /// Returns a `ValidatedPath` if the path is safe, or an error if validation fails.
    pub fn validate_path<P: AsRef<Path>>(
        &self,
        user_path: P,
    ) -> Result<ValidatedPath, PathSecurityError> {
        let user_path_ref = user_path.as_ref();
        let user_path_str = user_path_ref.to_string_lossy().to_string();

        // Check for empty path or null bytes
        if user_path_str.is_empty() {
            return Err(PathSecurityError::InvalidPath {
                reason: "Path is empty".to_string(),
            });
        }

        if user_path_str.contains('\0') {
            return Err(PathSecurityError::InvalidPath {
                reason: "Path contains null bytes".to_string(),
            });
        }

        // Pre-check for obvious traversal attempts before canonicalization
        if user_path_str.contains("..") {
            // This is a preliminary check; canonicalization will be the final arbiter
            #[cfg(feature = "tracing-integration")]
            tracing::warn!(
                "Potential path traversal attempt detected: {}",
                user_path_str
            );
        }

        let joined_path = if user_path_ref.is_absolute() {
            user_path_ref.to_path_buf()
        } else {
            self.allowed_base.join(user_path_ref)
        };
        let normalized_path = normalize_lexically(&joined_path);

        if !normalized_path.starts_with(&self.allowed_base) {
            return Err(PathSecurityError::OutsideAllowedBounds {
                path: normalized_path.display().to_string(),
                allowed_base: self.allowed_base.display().to_string(),
            });
        }

        let canonical_path = self.resolve_existing_ancestor(&normalized_path, &user_path_str)?;

        // Verify the canonical path is within the allowed bounds
        if !canonical_path.starts_with(&self.allowed_base) {
            return Err(PathSecurityError::OutsideAllowedBounds {
                path: canonical_path.display().to_string(),
                allowed_base: self.allowed_base.display().to_string(),
            });
        }

        // Log successful validation for audit purposes
        #[cfg(feature = "tracing-integration")]
        tracing::debug!(
            "Path validation successful: {} -> {}",
            user_path_str,
            canonical_path.display()
        );

        Ok(ValidatedPath {
            canonical_path,
            original_path: user_path_str,
        })
    }

    /// Get the base directory for this secure path validator.
    pub fn base_directory(&self) -> &Path {
        &self.allowed_base
    }

    fn resolve_existing_ancestor(
        &self,
        normalized_path: &Path,
        original_path: &str,
    ) -> Result<PathBuf, PathSecurityError> {
        let mut probe = normalized_path.to_path_buf();
        let mut missing_suffix = PathBuf::new();

        loop {
            if probe.exists() {
                let canonical_probe = probe.canonicalize().map_err(|e| {
                    PathSecurityError::CanonicalizationFailed {
                        path: original_path.to_string(),
                        source: e,
                    }
                })?;
                if !canonical_probe.starts_with(&self.allowed_base) {
                    return Err(PathSecurityError::OutsideAllowedBounds {
                        path: canonical_probe.display().to_string(),
                        allowed_base: self.allowed_base.display().to_string(),
                    });
                }
                // When the whole path already exists, `missing_suffix` is empty.
                // `PathBuf::join("")` appends a trailing separator, yielding e.g.
                // `.../test.txt/`, which the OS treats as a directory request and
                // rejects file reads with `NotADirectory`. Only join when there is
                // an actually-missing tail to append.
                if missing_suffix.as_os_str().is_empty() {
                    return Ok(canonical_probe);
                }
                return Ok(canonical_probe.join(missing_suffix));
            }

            let Some(name) = probe.file_name() else {
                return Err(PathSecurityError::CanonicalizationFailed {
                    path: original_path.to_string(),
                    source: std::io::Error::new(
                        std::io::ErrorKind::NotFound,
                        "no existing ancestor found",
                    ),
                });
            };

            let mut next_suffix = PathBuf::from(name);
            if !missing_suffix.as_os_str().is_empty() {
                next_suffix.push(missing_suffix);
            }
            missing_suffix = next_suffix;

            if !probe.pop() {
                return Err(PathSecurityError::CanonicalizationFailed {
                    path: original_path.to_string(),
                    source: std::io::Error::new(
                        std::io::ErrorKind::NotFound,
                        "no existing ancestor found",
                    ),
                });
            }
        }
    }

    fn prepare_write_path<P: AsRef<Path>>(
        &self,
        user_path: P,
    ) -> Result<ValidatedPath, PathSecurityError> {
        let validated = self.validate_path(user_path)?;
        self.prepare_validated_write_path(&validated)
    }

    fn prepare_validated_write_path(
        &self,
        validated: &ValidatedPath,
    ) -> Result<ValidatedPath, PathSecurityError> {
        if let Some(parent) = validated.as_path().parent() {
            fs::create_dir_all(parent).map_err(|e| PathSecurityError::CanonicalizationFailed {
                path: validated.original_path().to_string(),
                source: e,
            })?;
        }

        let revalidated = self.validate_path(validated.original_path())?;
        if let Some(parent) = revalidated.as_path().parent() {
            let canonical_parent =
                parent
                    .canonicalize()
                    .map_err(|e| PathSecurityError::CanonicalizationFailed {
                        path: validated.original_path().to_string(),
                        source: e,
                    })?;
            if !canonical_parent.starts_with(&self.allowed_base) {
                return Err(PathSecurityError::OutsideAllowedBounds {
                    path: canonical_parent.display().to_string(),
                    allowed_base: self.allowed_base.display().to_string(),
                });
            }
        }

        Ok(revalidated)
    }
}

fn create_no_follow_file(path: &Path) -> io::Result<File> {
    let mut options = OpenOptions::new();
    options.write(true).create(true).truncate(true);
    #[cfg(unix)]
    options.custom_flags(libc::O_NOFOLLOW);
    options.open(path)
}

fn write_all_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
    let mut file = create_no_follow_file(path)?;
    file.write_all(bytes)
}

fn normalize_lexically(path: &Path) -> PathBuf {
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            Component::Prefix(prefix) => normalized.push(prefix.as_os_str()),
            Component::RootDir => normalized.push(component.as_os_str()),
            Component::CurDir => {}
            Component::ParentDir => {
                let _ = normalized.pop();
            }
            Component::Normal(part) => normalized.push(part),
        }
    }
    normalized
}

/// Secure wrapper functions for common file operations.
impl SecurePath {
    /// Securely read a file to a string with path validation.
    pub fn read_to_string<P: AsRef<Path>>(
        &self,
        user_path: P,
    ) -> Result<String, Box<dyn std::error::Error>> {
        let validated = self.validate_path(user_path)?;
        let content = fs::read_to_string(validated.as_path())?;
        Ok(content)
    }

    /// Securely write a string to a file with path validation.
    pub fn write_string<P: AsRef<Path>, C: AsRef<str>>(
        &self,
        user_path: P,
        content: C,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let validated = self.prepare_write_path(user_path)?;
        write_all_no_follow(validated.as_path(), content.as_ref().as_bytes())?;
        Ok(())
    }

    /// Securely read file bytes with path validation.
    pub fn read_bytes<P: AsRef<Path>>(
        &self,
        user_path: P,
    ) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        let validated = self.validate_path(user_path)?;
        let bytes = fs::read(validated.as_path())?;
        Ok(bytes)
    }

    /// Securely write bytes to a file with path validation.
    pub fn write_bytes<P: AsRef<Path>, B: AsRef<[u8]>>(
        &self,
        user_path: P,
        bytes: B,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let validated = self.prepare_write_path(user_path)?;
        write_all_no_follow(validated.as_path(), bytes.as_ref())?;
        Ok(())
    }

    /// Securely copy a file with source and destination path validation.
    pub fn copy_file<P1: AsRef<Path>, P2: AsRef<Path>>(
        &self,
        src: P1,
        dst: P2,
    ) -> Result<u64, Box<dyn std::error::Error>> {
        let validated_src = self.validate_path(src)?;
        let validated_dst = self.prepare_write_path(dst)?;

        let bytes = fs::read(validated_src.as_path())?;
        write_all_no_follow(validated_dst.as_path(), &bytes)?;
        Ok(bytes.len() as u64)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_secure_path_creation() {
        let temp_dir = TempDir::new().unwrap();
        let secure_path = SecurePath::new(temp_dir.path()).unwrap();
        assert_eq!(
            secure_path.base_directory(),
            temp_dir.path().canonicalize().unwrap()
        );
    }

    #[test]
    fn test_invalid_base_directory() {
        let result = SecurePath::new("/nonexistent/directory");
        assert!(result.is_err());
        match result.unwrap_err() {
            PathSecurityError::BaseDirectoryInaccessible { .. } => (),
            other => panic!("Expected BaseDirectoryInaccessible, got {:?}", other),
        }
    }

    #[test]
    fn test_valid_path_validation() {
        let temp_dir = TempDir::new().unwrap();
        let secure_path = SecurePath::new(temp_dir.path()).unwrap();

        let validated = secure_path.validate_path("configs/app.toml").unwrap();
        let expected = temp_dir
            .path()
            .canonicalize()
            .unwrap()
            .join("configs/app.toml");
        assert_eq!(validated.as_path(), expected);
        assert_eq!(validated.original_path(), "configs/app.toml");
    }

    #[test]
    fn test_path_traversal_attack() {
        let temp_dir = TempDir::new().unwrap();
        let secure_path = SecurePath::new(temp_dir.path()).unwrap();

        let result = secure_path.validate_path("../../etc/passwd");
        assert!(result.is_err());
        match result.unwrap_err() {
            PathSecurityError::OutsideAllowedBounds { .. } => (),
            other => panic!("Expected OutsideAllowedBounds, got {:?}", other),
        }
    }

    #[test]
    fn test_empty_path() {
        let temp_dir = TempDir::new().unwrap();
        let secure_path = SecurePath::new(temp_dir.path()).unwrap();

        let result = secure_path.validate_path("");
        assert!(result.is_err());
        match result.unwrap_err() {
            PathSecurityError::InvalidPath { .. } => (),
            other => panic!("Expected InvalidPath, got {:?}", other),
        }
    }

    #[test]
    fn test_null_byte_path() {
        let temp_dir = TempDir::new().unwrap();
        let secure_path = SecurePath::new(temp_dir.path()).unwrap();

        let result = secure_path.validate_path("file\0.txt");
        assert!(result.is_err());
        match result.unwrap_err() {
            PathSecurityError::InvalidPath { .. } => (),
            other => panic!("Expected InvalidPath, got {:?}", other),
        }
    }

    #[test]
    fn test_secure_file_operations() {
        let temp_dir = TempDir::new().unwrap();
        let secure_path = SecurePath::new(temp_dir.path()).unwrap();

        // Test write and read
        let content = "Hello, secure world!";
        secure_path.write_string("test.txt", content).unwrap();
        let read_content = secure_path.read_to_string("test.txt").unwrap();
        assert_eq!(read_content, content);

        // Test bytes operations
        let bytes = b"Binary data";
        secure_path.write_bytes("binary.dat", bytes).unwrap();
        let read_bytes = secure_path.read_bytes("binary.dat").unwrap();
        assert_eq!(read_bytes, bytes);
    }

    #[test]
    fn test_secure_copy_operation() {
        let temp_dir = TempDir::new().unwrap();
        let secure_path = SecurePath::new(temp_dir.path()).unwrap();

        // Create source file
        let content = "File to copy";
        secure_path.write_string("source.txt", content).unwrap();

        // Copy file
        let bytes_copied = secure_path
            .copy_file("source.txt", "destination.txt")
            .unwrap();
        assert!(bytes_copied > 0);

        // Verify copy
        let copied_content = secure_path.read_to_string("destination.txt").unwrap();
        assert_eq!(copied_content, content);
    }

    #[test]
    fn test_directory_creation() {
        let temp_dir = TempDir::new().unwrap();
        let secure_path = SecurePath::new(temp_dir.path()).unwrap();

        // Writing to nested path should create directories
        secure_path
            .write_string("nested/dirs/file.txt", "content")
            .unwrap();

        // Verify the file was created
        let content = secure_path.read_to_string("nested/dirs/file.txt").unwrap();
        assert_eq!(content, "content");
    }

    #[cfg(unix)]
    #[test]
    fn write_preparation_revalidates_parent_after_creation() {
        let temp_dir = TempDir::new().unwrap();
        let outside_dir = TempDir::new().unwrap();
        let secure_path = SecurePath::new(temp_dir.path()).unwrap();
        let validated = secure_path.validate_path("staged/file.txt").unwrap();

        std::os::unix::fs::symlink(outside_dir.path(), temp_dir.path().join("staged")).unwrap();

        let error = secure_path
            .prepare_validated_write_path(&validated)
            .expect_err("parent symlink swap must be rejected");
        match error {
            PathSecurityError::OutsideAllowedBounds { path, allowed_base } => {
                assert!(path.starts_with(&outside_dir.path().display().to_string()));
                assert_eq!(
                    allowed_base,
                    secure_path.base_directory().display().to_string()
                );
            }
            other => panic!("Expected OutsideAllowedBounds, got {:?}", other),
        }
    }

    #[cfg(unix)]
    #[test]
    fn no_follow_write_rejects_final_symlink_swap() {
        let temp_dir = TempDir::new().unwrap();
        let outside_dir = TempDir::new().unwrap();
        let link_path = temp_dir.path().join("target.txt");
        let escaped_path = outside_dir.path().join("escaped.txt");
        std::os::unix::fs::symlink(&escaped_path, &link_path).unwrap();

        let error =
            write_all_no_follow(&link_path, b"blocked").expect_err("symlink write must fail");
        assert_eq!(error.raw_os_error(), Some(libc::ELOOP));
        assert!(!escaped_path.exists());
    }
}