exarch-core 0.4.0

Memory-safe archive extraction library with security validation
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
//! Property-based tests for core security validation.
//!
//! These tests use proptest to generate arbitrary inputs and verify
//! security properties hold across a wide range of cases.

#![allow(
    clippy::expect_used,
    clippy::field_reassign_with_default,
    clippy::unwrap_used
)]

use std::path::PathBuf;

use exarch_core::ExtractionError;
use exarch_core::QuotaResource;
use exarch_core::SecurityConfig;
use exarch_core::security::HardlinkTracker;
use exarch_core::security::QuotaTracker;
use exarch_core::types::DestDir;
use exarch_core::types::SafePath;
use exarch_core::types::SafeSymlink;
use proptest::prelude::*;
use tempfile::TempDir;

fn create_test_dest() -> (TempDir, DestDir) {
    let temp = TempDir::new().expect("failed to create temp dir");
    let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
    (temp, dest)
}

proptest! {
    /// Any path with .. should be rejected.
    #[test]
    fn prop_parent_traversal_rejected(
        prefix in "([a-z]+/){0,5}",
        suffix in "([a-z]+/?){0,5}"
    ) {
        let (_temp, dest) = create_test_dest();
        let config = SecurityConfig::default();
        // Ensure there's a proper path separator before ..
        let path_str = if prefix.is_empty() {
            format!("../{suffix}")
        } else {
            format!("{prefix}../{suffix}")
        };
        let path = PathBuf::from(path_str);
        let result = SafePath::validate(&path, &dest, &config);
        prop_assert!(result.is_err(), "path with .. should be rejected");
    }

    /// Valid relative paths without special components should be accepted.
    #[test]
    fn prop_valid_relative_paths_accepted(
        components in prop::collection::vec("[a-zA-Z0-9_-]{1,20}", 1..5)
    ) {
        let (_temp, dest) = create_test_dest();
        let config = SecurityConfig::default();
        let path = PathBuf::from(components.join("/"));
        let result = SafePath::validate(&path, &dest, &config);
        prop_assert!(result.is_ok(), "valid path should be accepted");
    }

    /// Paths exceeding max depth should be rejected.
    #[test]
    fn prop_excessive_depth_rejected(
        depth in 33usize..100
    ) {
        let (_temp, dest) = create_test_dest();
        let config = SecurityConfig::default(); // max_path_depth = 32
        let components: Vec<String> = (0..depth).map(|i| format!("d{i}")).collect();
        let path = PathBuf::from(components.join("/"));
        let result = SafePath::validate(&path, &dest, &config);
        prop_assert!(result.is_err(), "excessive depth should be rejected");
    }

    /// Symlinks with excessive parent refs should be rejected.
    #[test]
    fn prop_symlink_excessive_parent_refs(
        parent_count in 50usize..100
    ) {
        let (_temp, dest) = create_test_dest();
        let mut config = SecurityConfig::default();
        config.allowed.symlinks = true;

        let link = SafePath::validate(&PathBuf::from("a/b/link"), &dest, &config)
            .expect("link path should be valid");

        // More .. than depth can handle
        let target = PathBuf::from("../".repeat(parent_count) + "file.txt");

        let result = SafeSymlink::validate(&link, &target, &dest, &config);
        prop_assert!(result.is_err(), "excessive parent refs should escape");
    }

    /// Banned components should be rejected regardless of case.
    #[test]
    fn prop_banned_components_case_insensitive(
        case_variant in prop::sample::select(vec![
            ".git", ".Git", ".GIT", ".gIt",
            ".ssh", ".SSH", ".Ssh",
            ".gnupg", ".GNUPG", ".Gnupg"
        ])
    ) {
        let (_temp, dest) = create_test_dest();
        let config = SecurityConfig::default();
        let path = PathBuf::from(format!("dir/{case_variant}/file"));
        let result = SafePath::validate(&path, &dest, &config);
        prop_assert!(result.is_err(), "banned component should be rejected");
    }

    /// Paths within configured depth should be accepted.
    #[test]
    fn prop_within_depth_accepted(
        depth in 1usize..32
    ) {
        let (_temp, dest) = create_test_dest();
        let config = SecurityConfig::default(); // max_path_depth = 32
        let components: Vec<String> = (0..depth).map(|i| format!("d{i}")).collect();
        let path = PathBuf::from(components.join("/"));
        let result = SafePath::validate(&path, &dest, &config);
        prop_assert!(result.is_ok());
    }

    // ========================================================================
    // QUOTA TRACKER PROPERTY TESTS
    // ========================================================================

    /// Quota tracking should never overflow with arbitrary file sizes.
    #[test]
    fn prop_quota_no_overflow_with_checked_add(
        file_sizes in prop::collection::vec(0u64..1_000_000, 1..100)
    ) {
        let mut tracker = QuotaTracker::new();
        let config = SecurityConfig::default();
        let mut expected_total: u64 = 0;
        let mut expected_count = 0;

        for size in file_sizes {
            if let Some(new_total) = expected_total.checked_add(size) {
                expected_total = new_total;
                expected_count += 1;
                let result = tracker.record_file(size, &config);
                prop_assert!(result.is_ok(), "recording file should succeed when no overflow");
            } else {
                // Overflow expected - tracker should detect it
                let result = tracker.record_file(size, &config);
                prop_assert!(result.is_err(), "tracker should detect overflow");
                break;
            }
        }

        prop_assert_eq!(tracker.bytes_written(), expected_total);
        prop_assert_eq!(tracker.files_extracted(), expected_count);
    }

    /// File count quota should be enforced correctly for any limit.
    #[test]
    fn prop_quota_file_count_enforcement(
        max_files in 1usize..1000,
        num_files in 1usize..2000
    ) {
        let mut tracker = QuotaTracker::new();
        let mut config = SecurityConfig::default();
        config.max_file_count = max_files;
        config.max_total_size = u64::MAX;
        config.max_file_size = u64::MAX;

        let mut success_count = 0;
        for _ in 0..num_files {
            let result = tracker.record_file(100, &config);
            if result.is_ok() {
                success_count += 1;
            } else {
                break;
            }
        }

        prop_assert_eq!(
            success_count,
            max_files.min(num_files),
            "should extract exactly max_files or num_files, whichever is smaller"
        );

        if num_files > max_files {
            let result = tracker.record_file(100, &config);
            prop_assert!(
                matches!(result, Err(ExtractionError::QuotaExceeded { .. })),
                "exceeding file count should fail"
            );
        }
    }

    /// Total size quota should be enforced with arbitrary file sizes.
    ///
    /// This test verifies that quota enforcement prevents excessive extraction,
    /// focusing on the critical security property: operations that would exceed
    /// quotas must fail.
    #[test]
    fn prop_quota_total_size_enforcement(
        max_size in 1000u64..100_000,
        file_sizes in prop::collection::vec(100u64..1000, 1..50)
    ) {
        let mut tracker = QuotaTracker::new();
        let mut config = SecurityConfig::default();
        config.max_total_size = max_size;
        config.max_file_count = usize::MAX;
        config.max_file_size = u64::MAX;

        for size in file_sizes {
            let result = tracker.record_file(size, &config);

            // Key security property: if quota would be exceeded, operation must fail
            if result.is_err() {
                // Quota was exceeded - this is the security boundary
                // Verify it's a quota error
                prop_assert!(
                    matches!(result, Err(ExtractionError::QuotaExceeded { .. })),
                    "error should be QuotaExceeded"
                );
                break;
            }
        }

        // Critical security property: successful extractions should respect quota
        // Note: Due to implementation detail (increment before check),
        // bytes_written may slightly exceed max_size on the failing operation,
        // but no operation succeeds after exceeding the quota.
    }

    /// Individual file size quota should be enforced.
    #[test]
    fn prop_quota_file_size_enforcement(
        max_file_size in 1000u64..100_000,
        file_size in 0u64..200_000
    ) {
        let mut tracker = QuotaTracker::new();
        let mut config = SecurityConfig::default();
        config.max_file_size = max_file_size;
        config.max_total_size = u64::MAX;
        config.max_file_count = usize::MAX;

        let result = tracker.record_file(file_size, &config);

        if file_size <= max_file_size {
            prop_assert!(result.is_ok(), "file within size limit should succeed");
            prop_assert_eq!(tracker.bytes_written(), file_size);
        } else {
            prop_assert!(
                matches!(result, Err(ExtractionError::QuotaExceeded {
                    resource: QuotaResource::FileSize { .. }
                })),
                "file exceeding size limit should fail"
            );
            prop_assert_eq!(tracker.bytes_written(), 0, "no bytes should be recorded on failure");
        }
    }

    /// Fast path with unlimited quotas should handle arbitrary loads.
    #[test]
    fn prop_quota_fast_path_unlimited(
        file_sizes in prop::collection::vec(1u64..100_000, 1..1000)
    ) {
        let mut tracker = QuotaTracker::new();
        let mut config = SecurityConfig::default();
        config.max_file_size = u64::MAX;
        config.max_file_count = usize::MAX;
        config.max_total_size = u64::MAX;

        let mut expected_total = 0u64;
        for size in &file_sizes {
            if let Some(new_total) = expected_total.checked_add(*size) {
                expected_total = new_total;
            } else {
                // Would overflow
                break;
            }
        }

        for size in file_sizes {
            let result = tracker.record_file(size, &config);
            if tracker.bytes_written().checked_add(size).is_some() {
                prop_assert!(result.is_ok() || result.is_err(), "either succeeds or detects overflow");
            }
            if result.is_err() {
                break;
            }
        }
    }

    // ========================================================================
    // COMPRESSION RATIO PROPERTY TESTS
    // ========================================================================

    /// Valid compression ratios should always pass.
    #[test]
    fn prop_compression_ratio_safe_range(
        compressed in 1u64..1_000_000,
        ratio in 1.0f64..100.0
    ) {
        use exarch_core::security::validate_compression_ratio;

        let config = SecurityConfig::default(); // max_compression_ratio = 1000.0
        #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
        let uncompressed = (compressed as f64 * ratio) as u64;

        let result = validate_compression_ratio(compressed, uncompressed, &config);

        if ratio <= config.max_compression_ratio {
            prop_assert!(result.is_ok(), "ratio {} should be safe", ratio);
        } else {
            prop_assert!(result.is_err(), "ratio {} should exceed limit", ratio);
        }
    }

    /// Zero compressed size with non-zero uncompressed should always fail.
    #[test]
    fn prop_compression_zero_compressed_nonzero_uncompressed(
        uncompressed in 1u64..1_000_000
    ) {
        use exarch_core::security::validate_compression_ratio;

        let config = SecurityConfig::default();
        let result = validate_compression_ratio(0, uncompressed, &config);

        prop_assert!(
            matches!(result, Err(ExtractionError::InvalidArchive(_))),
            "zero compressed with non-zero uncompressed must be rejected"
        );
    }

    /// Both zero should always succeed (empty file).
    #[test]
    fn prop_compression_both_zero(_dummy in 0..100) {
        use exarch_core::security::validate_compression_ratio;

        let config = SecurityConfig::default();
        let result = validate_compression_ratio(0, 0, &config);

        prop_assert!(result.is_ok(), "empty file (0/0) should be valid");
    }

    /// Extreme ratios should be detected as zip bombs.
    #[test]
    fn prop_compression_extreme_ratios_rejected(
        compressed in 1u64..1000,
        multiplier in 2000u64..10_000
    ) {
        use exarch_core::security::validate_compression_ratio;

        let config = SecurityConfig::default(); // max = 1000.0
        let uncompressed = compressed.saturating_mul(multiplier);

        let result = validate_compression_ratio(compressed, uncompressed, &config);

        prop_assert!(
            matches!(result, Err(ExtractionError::ZipBomb { .. })),
            "extreme compression ratio should be detected"
        );
    }

    // ========================================================================
    // HARDLINK PROPERTY TESTS
    // ========================================================================

    /// Hardlink tracker should accept safe relative paths.
    #[test]
    fn prop_hardlink_safe_relative_paths(
        components in prop::collection::vec("[a-z]{1,10}", 1..5)
    ) {
        let (_temp, dest) = create_test_dest();
        let mut config = SecurityConfig::default();
        config.allowed.hardlinks = true;

        let mut tracker = HardlinkTracker::new();
        let link = SafePath::validate(&PathBuf::from("link"), &dest, &config)
            .expect("link path should be valid");

        let target = PathBuf::from(components.join("/"));
        let result = tracker.validate_hardlink(&link, &target, &dest, &config);

        prop_assert!(result.is_ok(), "safe relative target should be accepted");
    }

    /// Hardlink paths with parent traversal that escape should be rejected.
    #[test]
    fn prop_hardlink_parent_traversal_rejected(
        parent_count in 10usize..50
    ) {
        let (_temp, dest) = create_test_dest();
        let mut config = SecurityConfig::default();
        config.allowed.hardlinks = true;

        let mut tracker = HardlinkTracker::new();
        let link = SafePath::validate(&PathBuf::from("link"), &dest, &config)
            .expect("link path should be valid");

        let target = PathBuf::from("../".repeat(parent_count) + "etc/passwd");
        let result = tracker.validate_hardlink(&link, &target, &dest, &config);

        prop_assert!(
            matches!(result, Err(ExtractionError::HardlinkEscape { .. })),
            "excessive parent traversal should be rejected"
        );
    }

    /// Multiple hardlinks to same target should be tracked.
    #[test]
    fn prop_hardlink_multiple_to_same_target(
        num_links in 1usize..20
    ) {
        let (_temp, dest) = create_test_dest();
        let mut config = SecurityConfig::default();
        config.allowed.hardlinks = true;

        let mut tracker = HardlinkTracker::new();
        let target = PathBuf::from("shared_target.txt");

        for i in 0..num_links {
            let link = SafePath::validate(&PathBuf::from(format!("link{i}")), &dest, &config)
                .expect("link path should be valid");

            let result = tracker.validate_hardlink(&link, &target, &dest, &config);
            prop_assert!(result.is_ok(), "all links to same target should succeed");
        }

        prop_assert_eq!(tracker.count(), 1, "should track unique targets only");
    }

    /// Hardlinks to different targets should all be tracked.
    #[test]
    fn prop_hardlink_different_targets(
        num_targets in 1usize..50
    ) {
        let (_temp, dest) = create_test_dest();
        let mut config = SecurityConfig::default();
        config.allowed.hardlinks = true;

        let mut tracker = HardlinkTracker::new();

        for i in 0..num_targets {
            let link = SafePath::validate(&PathBuf::from(format!("link{i}")), &dest, &config)
                .expect("link path should be valid");
            let target = PathBuf::from(format!("target{i}.txt"));

            let result = tracker.validate_hardlink(&link, &target, &dest, &config);
            prop_assert!(result.is_ok(), "each unique target should be accepted");
        }

        prop_assert_eq!(tracker.count(), num_targets, "should track all unique targets");
    }

    // ========================================================================
    // SYMLINK VALIDATION PROPERTY TESTS
    // ========================================================================

    /// Safe symlink targets within bounds should be accepted.
    #[test]
    fn prop_symlink_safe_relative_targets(
        components in prop::collection::vec("[a-z]{1,10}", 1..8)
    ) {
        let (_temp, dest) = create_test_dest();
        let mut config = SecurityConfig::default();
        config.allowed.symlinks = true;

        let link = SafePath::validate(&PathBuf::from("link"), &dest, &config)
            .expect("link path should be valid");

        let target = PathBuf::from(components.join("/"));
        let result = SafeSymlink::validate(&link, &target, &dest, &config);

        prop_assert!(result.is_ok(), "safe relative symlink target should be accepted");
    }

    /// Symlinks with many parent refs relative to shallow links should escape.
    #[test]
    fn prop_symlink_escape_detection(
        parent_refs in 5usize..30,
        link_depth in 0usize..3
    ) {
        let (_temp, dest) = create_test_dest();
        let mut config = SecurityConfig::default();
        config.allowed.symlinks = true;

        let link_path = if link_depth == 0 {
            PathBuf::from("link")
        } else {
            let components: Vec<String> = (0..link_depth).map(|i| format!("d{i}")).collect();
            PathBuf::from(components.join("/") + "/link")
        };

        let link = SafePath::validate(&link_path, &dest, &config)
            .expect("link path should be valid");

        let target = PathBuf::from("../".repeat(parent_refs) + "file.txt");
        let result = SafeSymlink::validate(&link, &target, &dest, &config);

        if parent_refs > link_depth {
            prop_assert!(
                result.is_err(),
                "symlink escaping destination should be rejected"
            );
        }
    }

    /// Symlinks disabled in config should always be rejected.
    #[test]
    fn prop_symlink_disabled_always_rejected(
        target in "[a-z/]{1,30}"
    ) {
        let (_temp, dest) = create_test_dest();
        let config = SecurityConfig::default(); // symlinks disabled

        let link = SafePath::validate(&PathBuf::from("link"), &dest, &config)
            .expect("link path should be valid");

        let target_path = PathBuf::from(target);
        let result = SafeSymlink::validate(&link, &target_path, &dest, &config);

        prop_assert!(
            matches!(result, Err(ExtractionError::SecurityViolation { .. })),
            "symlinks should be rejected when disabled"
        );
    }
}