exarch-core 0.2.9

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
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
//! Common extraction utilities shared between archive formats.
//!
//! This module provides shared functionality for TAR and ZIP extractors
//! to avoid code duplication. It is an internal module not exposed in
//! the public API.
//!
//! # Functions
//!
//! - [`extract_file_generic`]: Generic file extraction with buffered I/O
//! - [`create_directory`]: Directory creation (idempotent)
//! - [`create_symlink`]: Symbolic link creation (Unix only)

use rustc_hash::FxHashSet;
use std::fs::File;
use std::fs::create_dir_all;
use std::io::BufWriter;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;

use crate::ExtractionError;
use crate::ExtractionReport;
use crate::Result;
use crate::copy::CopyBuffer;
use crate::copy::copy_with_buffer;
use crate::error::QuotaResource;
use crate::security::validator::ValidatedEntry;
use crate::types::DestDir;
use crate::types::SafeSymlink;

/// Cache for tracking created directories during extraction.
///
/// Reduces redundant mkdir syscalls for nested archive structures.
/// For example, extracting 1000 files in nested directories without caching
/// can result in ~3000 mkdir syscalls. With caching, this reduces to ~150.
///
/// # Implementation
///
/// Uses an in-memory `FxHashSet<PathBuf>` to track all created directory paths.
/// `FxHashSet` is a faster non-cryptographic hash from rustc, optimized for
/// performance when hash DOS protection is not needed.
///
/// When a directory needs to be created, we first check the cache to avoid
/// redundant syscalls.
///
/// # Performance
///
/// - Reduces syscalls by ~95% for deeply nested archives
/// - Memory overhead: O(d) where d is number of unique directories
/// - Lookup cost: O(1) average with `FxHasher` (faster than `SipHash`)
/// - Default capacity: 128 directories (tunable via `with_capacity`)
///
/// # TOCTOU Safety
///
/// This cache creates a potential Time-Of-Check-Time-Of-Use (TOCTOU) race:
/// another process could delete cached directories between our check and use.
/// However, this is NOT a security concern because:
///
/// 1. **Fail-safe**: If a cached directory is deleted, subsequent file creation
///    will fail with ENOENT, causing extraction to abort cleanly.
/// 2. **No privilege escalation**: Cache only tracks directories we created,
///    not arbitrary filesystem state.
/// 3. **Defense in depth**: Path validation happens before caching (blocks
///    traversal, absolute paths, etc.).
/// 4. **Industry standard**: TAR, ZIP, and other extractors use similar caching
///    without additional synchronization.
///
/// # Future Work
///
/// Potential quota features for future versions:
/// - `max_directory_depth`: Limit nesting depth (`DoS` protection)
/// - `max_unique_directories`: Limit total directory count (memory limit)
///
/// These are deferred because:
/// - Current `max_total_size` quota provides sufficient `DoS` protection
/// - Real-world archives rarely exceed reasonable directory counts
/// - Simpler implementation reduces attack surface
///
/// # Examples
///
/// ```ignore
/// use exarch_core::formats::common::DirCache;
/// use std::path::Path;
///
/// let mut cache = DirCache::new();
///
/// // First call creates directory and caches all ancestors
/// cache.ensure_parent_dir(Path::new("a/b/c/file.txt"))?;
///
/// // Second call skips mkdir - already cached
/// cache.ensure_parent_dir(Path::new("a/b/c/file2.txt"))?;
/// # Ok::<(), std::io::Error>(())
/// ```
#[derive(Debug)]
pub struct DirCache {
    created: FxHashSet<PathBuf>,
}

impl DirCache {
    /// Creates a new directory cache with default capacity (128).
    ///
    /// This is sufficient for most archives. Use [`with_capacity`] if you
    /// know the archive has significantly more unique directories.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let cache = DirCache::new();
    /// ```
    ///
    /// [`with_capacity`]: Self::with_capacity
    #[must_use]
    #[inline]
    pub fn new() -> Self {
        Self::with_capacity(128)
    }

    /// Creates a new directory cache with specified capacity.
    ///
    /// Pre-allocating capacity avoids rehashing during extraction.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// // For archives with many unique directories
    /// let cache = DirCache::with_capacity(1000);
    /// ```
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        use rustc_hash::FxBuildHasher;
        Self {
            created: FxHashSet::with_capacity_and_hasher(capacity, FxBuildHasher),
        }
    }

    /// Private helper to cache all ancestor directories of a path.
    ///
    /// This avoids duplicating the ancestor-walking logic in both
    /// `ensure_parent_dir` and `ensure_dir`.
    fn cache_ancestors(&mut self, path: &Path) {
        let mut current = path;
        while !current.as_os_str().is_empty() {
            self.created.insert(current.to_path_buf());
            match current.parent() {
                Some(p) if !p.as_os_str().is_empty() => current = p,
                _ => break,
            }
        }
    }

    /// Checks if a path is in the cache (i.e., was created by us).
    #[inline]
    pub fn contains(&self, path: &Path) -> bool {
        self.created.contains(path)
    }

    /// Ensures parent directory exists, using cache to skip redundant mkdir
    /// calls.
    ///
    /// This function creates the parent directory of the given file path if it
    /// does not exist. All ancestor directories are also created and cached.
    ///
    /// # Performance
    ///
    /// - First call for a directory: Creates directory and caches all ancestors
    /// - Subsequent calls for same directory: O(1) cache lookup, no syscall
    ///
    /// # Returns
    ///
    /// - `Ok(true)` if directory was created
    /// - `Ok(false)` if directory already existed (cached or no parent)
    ///
    /// # Errors
    ///
    /// Returns an I/O error if directory creation fails.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let mut cache = DirCache::new();
    /// let created = cache.ensure_parent_dir(Path::new("a/b/file.txt"))?;
    /// assert!(created); // First call creates directory
    ///
    /// let created = cache.ensure_parent_dir(Path::new("a/b/file2.txt"))?;
    /// assert!(!created); // Second call finds cached directory
    /// ```
    #[inline]
    pub fn ensure_parent_dir(&mut self, file_path: &Path) -> std::io::Result<bool> {
        if let Some(parent) = file_path.parent() {
            if parent.as_os_str().is_empty() {
                return Ok(false);
            }
            if !self.created.contains(parent) {
                create_dir_all(parent)?;
                self.cache_ancestors(parent);
                return Ok(true);
            }
        }
        Ok(false)
    }

    /// Ensures a directory exists (for directory entries in archives).
    ///
    /// This function creates the directory if it does not exist. All ancestor
    /// directories are also created and cached.
    ///
    /// # Performance
    ///
    /// - First call for a directory: Creates directory and caches all ancestors
    /// - Subsequent calls for same directory: O(1) cache lookup, no syscall
    ///
    /// # Returns
    ///
    /// - `Ok(true)` if directory was created
    /// - `Ok(false)` if directory already existed (cached or empty path)
    ///
    /// # Errors
    ///
    /// Returns an I/O error if directory creation fails.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let mut cache = DirCache::new();
    /// let created = cache.ensure_dir(Path::new("a/b/c"))?;
    /// assert!(created); // First call creates directory
    ///
    /// let created = cache.ensure_dir(Path::new("a/b/c"))?;
    /// assert!(!created); // Second call finds cached directory
    /// ```
    #[inline]
    pub fn ensure_dir(&mut self, dir_path: &Path) -> std::io::Result<bool> {
        if dir_path.as_os_str().is_empty() {
            return Ok(false);
        }
        if !self.created.contains(dir_path) {
            create_dir_all(dir_path)?;
            self.cache_ancestors(dir_path);
            return Ok(true);
        }
        Ok(false)
    }
}

impl Default for DirCache {
    fn default() -> Self {
        Self::new()
    }
}

/// Creates a file with permissions enforced after creation to bypass umask.
///
/// On Unix platforms, this function uses `OpenOptions::mode()` to hint the
/// desired mode during `open()`, then calls `set_permissions()` to enforce
/// the exact sanitized mode. The second call is required because
/// `OpenOptions::mode()` is subject to the process umask and the resulting
/// permissions may be narrower than requested.
///
/// On non-Unix platforms, permissions are not supported and mode is ignored.
///
/// # Performance
///
/// - Unix: 2 syscalls (open with mode hint + `set_permissions` to bypass umask)
/// - Non-Unix: 1 syscall (create)
///
/// For archives with 1000 files, this reduces 2000 syscalls to 1000 syscalls
/// (50% reduction in permission-related syscalls).
///
/// # Security - Mode Sanitization Requirement
///
/// **CRITICAL**: This function trusts the caller to provide safe mode values.
/// The `mode` parameter MUST be sanitized before calling this function to:
///
/// - Strip setuid bit (0o4000) if required by security policy
/// - Strip setgid bit (0o2000) if required by security policy
/// - Strip sticky bit (0o1000) if required by security policy
/// - Ensure world-writable permissions are only set if allowed
///
/// Mode sanitization MUST be performed by the caller (typically in the
/// validation layer via `SecurityConfig::sanitize_mode()`). This function
/// does NOT perform any sanitization and will apply the mode value directly.
///
/// # Arguments
///
/// * `path` - Path where file should be created
/// * `mode` - Optional Unix file mode (must be pre-sanitized by caller)
///
/// # Errors
///
/// Returns an I/O error if file creation fails.
#[inline]
#[cfg(unix)]
fn create_file_with_mode(path: &Path, mode: Option<u32>) -> std::io::Result<File> {
    use std::fs::OpenOptions;
    use std::fs::Permissions;
    use std::os::unix::fs::OpenOptionsExt;
    use std::os::unix::fs::PermissionsExt;

    let mut opts = OpenOptions::new();
    opts.write(true).create(true).truncate(true);

    if let Some(m) = mode {
        // Apply sanitized mode during open (already stripped setuid/setgid)
        opts.mode(m);
    }

    let file = opts.open(path)?;

    // OpenOptions::mode() is subject to the process umask, which may reduce
    // the requested permissions. Call set_permissions() explicitly to enforce
    // the exact sanitized mode, bypassing umask.
    if let Some(m) = mode {
        std::fs::set_permissions(path, Permissions::from_mode(m))?;
    }

    Ok(file)
}

/// Creates a file (non-Unix platforms ignore mode parameter).
///
/// This is the fallback implementation for platforms that do not support
/// Unix-style file permissions.
///
/// # Arguments
///
/// * `path` - Path where file should be created
/// * `_mode` - Ignored on non-Unix platforms
///
/// # Errors
///
/// Returns an I/O error if file creation fails.
#[inline]
#[cfg(not(unix))]
fn create_file_with_mode(path: &Path, _mode: Option<u32>) -> std::io::Result<File> {
    File::create(path)
}

/// Generic file extraction implementation used by all format adapters.
///
/// This function consolidates file extraction logic to ensure consistent:
/// - Directory creation with caching
/// - Buffered I/O (64KB buffer)
/// - Permission preservation (Unix only, set atomically during file creation)
/// - Quota tracking with overflow protection
///
/// # Permission Enforcement
///
/// On Unix, file permissions are enforced via `set_permissions()` after
/// creation to bypass the process umask. This ensures the exact sanitized
/// mode from `SecurityConfig` is applied, regardless of the caller's umask.
///
/// # Correctness
///
/// Quota is checked BEFORE writing to prevent partial files on overflow.
/// This fixes the inconsistency where TAR was checking AFTER write.
///
/// # Type Parameters
///
/// - `R`: Reader type that implements `Read`
///
/// # Arguments
///
/// * `reader` - Source data stream
/// * `validated` - Validated entry metadata (path, mode, etc.)
/// * `dest` - Destination directory
/// * `report` - Extraction statistics (updated)
/// * `expected_size` - Expected file size (if known) for quota pre-check
/// * `copy_buffer` - Reusable buffer for I/O operations
/// * `dir_cache` - Directory cache to reduce redundant mkdir syscalls
///
/// # Errors
///
/// Returns error if:
/// - Parent directory creation fails
/// - Quota would be exceeded (checked before write)
/// - File creation fails
/// - I/O error during copy
#[allow(clippy::too_many_arguments)]
#[inline]
pub fn extract_file_generic<R: Read>(
    reader: &mut R,
    validated: &ValidatedEntry,
    dest: &DestDir,
    report: &mut ExtractionReport,
    expected_size: Option<u64>,
    copy_buffer: &mut CopyBuffer,
    dir_cache: &mut DirCache,
    skip_duplicates: bool,
) -> Result<()> {
    let output_path = dest.join(&validated.safe_path);

    // Create parent directories if needed using cache
    dir_cache.ensure_parent_dir(&output_path)?;

    if output_path.exists() {
        if skip_duplicates {
            report.files_skipped += 1;
            report.warnings.push(format!(
                "skipped duplicate entry: {}",
                validated.safe_path.as_path().display()
            ));
            return Ok(());
        }
        return Err(ExtractionError::InvalidArchive(format!(
            "duplicate entry: {}",
            validated.safe_path.as_path().display()
        )));
    }

    // CRITICAL: Check quota BEFORE writing (prevents partial files on overflow)
    if let Some(size) = expected_size {
        report
            .bytes_written
            .checked_add(size)
            .ok_or(ExtractionError::QuotaExceeded {
                resource: QuotaResource::IntegerOverflow,
            })?;
    }

    // Create file and enforce exact sanitized permissions (Unix only).
    // set_permissions() is called inside create_file_with_mode to bypass umask.
    let output_file = create_file_with_mode(&output_path, validated.mode)?;
    let mut buffered_writer = BufWriter::with_capacity(64 * 1024, output_file);
    let bytes_written = copy_with_buffer(reader, &mut buffered_writer, copy_buffer)?;
    buffered_writer.flush()?;

    report.files_extracted += 1;
    report.bytes_written =
        report
            .bytes_written
            .checked_add(bytes_written)
            .ok_or(ExtractionError::QuotaExceeded {
                resource: QuotaResource::IntegerOverflow,
            })?;

    Ok(())
}

/// Creates a directory from a validated entry.
///
/// This is a shared helper used by both TAR and ZIP extractors.
///
/// # Idempotent Behavior
///
/// This function is idempotent - calling it multiple times for the same
/// directory has no effect thanks to the directory cache.
///
/// # Quota Tracking
///
/// Directory creation increments the `directories_created` counter but
/// does NOT count toward the byte quota (`bytes_written`). Only regular
/// file data counts toward byte quotas.
///
/// # Arguments
///
/// * `validated` - Validated entry metadata
/// * `dest` - Destination directory
/// * `report` - Extraction statistics (updated)
/// * `dir_cache` - Directory cache to reduce redundant mkdir syscalls
///
/// # Errors
///
/// Returns an error if directory creation fails due to I/O errors.
pub fn create_directory(
    validated: &ValidatedEntry,
    dest: &DestDir,
    report: &mut ExtractionReport,
    dir_cache: &mut DirCache,
) -> Result<()> {
    let dir_path = dest.join(&validated.safe_path);

    // Use cache to avoid redundant mkdir syscalls
    dir_cache.ensure_dir(&dir_path)?;

    report.directories_created += 1;

    Ok(())
}

/// Creates a symbolic link from a validated symlink entry.
///
/// This is a shared helper used by both TAR and ZIP extractors.
/// Parent directories are created automatically if needed using the directory
/// cache.
///
/// # Platform Support
///
/// - **Unix**: Full symlink support via `std::os::unix::fs::symlink`
/// - **Other platforms**: Returns `SecurityViolation` error
///
/// # Error Behavior
///
/// If the symlink already exists, the function will fail with an I/O error.
/// Unlike `create_directory`, this function is NOT idempotent - it does not
/// overwrite existing symlinks or files at the target path.
///
/// # Arguments
///
/// * `safe_symlink` - Validated symlink entry
/// * `dest` - Destination directory
/// * `report` - Extraction statistics (updated)
/// * `dir_cache` - Directory cache to reduce redundant mkdir syscalls
///
/// # Errors
///
/// Returns an error if:
/// - Platform does not support symlinks
/// - Parent directory creation fails
/// - Symlink creation fails (including when target path already exists)
/// - A file or symlink already exists at the link path and `skip_duplicates` is
///   false
#[allow(unused_variables)]
pub fn create_symlink(
    safe_symlink: &SafeSymlink,
    dest: &DestDir,
    report: &mut ExtractionReport,
    dir_cache: &mut DirCache,
    skip_duplicates: bool,
) -> Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::symlink;

        let link_path = dest.join_path(safe_symlink.link_path());
        let target_path = safe_symlink.target_path();

        // Create parent directories using cache
        dir_cache.ensure_parent_dir(&link_path)?;

        if link_path.exists() || link_path.symlink_metadata().is_ok() {
            if skip_duplicates {
                report.files_skipped += 1;
                report.warnings.push(format!(
                    "skipped duplicate symlink: {}",
                    safe_symlink.link_path().display()
                ));
                return Ok(());
            }
            return Err(ExtractionError::InvalidArchive(format!(
                "duplicate entry: {}",
                safe_symlink.link_path().display()
            )));
        }

        // Create symlink
        symlink(target_path, &link_path)?;

        report.symlinks_created += 1;

        Ok(())
    }

    #[cfg(not(unix))]
    {
        Err(ExtractionError::SecurityViolation {
            reason: "symlinks are not supported on this platform".into(),
        })
    }
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::ExtractionError;
    use crate::ExtractionReport;
    use crate::SecurityConfig;
    use crate::copy::CopyBuffer;
    use crate::security::validator::ValidatedEntry;
    use crate::security::validator::ValidatedEntryType;
    use crate::types::SafePath;
    use std::io::Cursor;
    use std::path::PathBuf;
    use tempfile::TempDir;

    #[test]
    fn test_extract_file_generic_integer_overflow_check() {
        let temp = TempDir::new().expect("failed to create temp dir");
        let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
        let mut report = ExtractionReport::default();
        let mut copy_buffer = CopyBuffer::new();
        let mut dir_cache = DirCache::new();

        // Set bytes_written to a value close to u64::MAX
        report.bytes_written = u64::MAX - 100;

        // Try to extract a file with size that would overflow
        let expected_size = Some(200u64); // This would overflow when added

        let config = SecurityConfig::default();
        let validated = ValidatedEntry {
            safe_path: SafePath::validate(&PathBuf::from("test.txt"), &dest, &config)
                .expect("path should be valid"),
            mode: Some(0o644),
            entry_type: ValidatedEntryType::File,
        };

        let mut reader = Cursor::new(b"test data");

        let result = extract_file_generic(
            &mut reader,
            &validated,
            &dest,
            &mut report,
            expected_size,
            &mut copy_buffer,
            &mut dir_cache,
            true,
        );

        // Should return QuotaExceeded with IntegerOverflow
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ExtractionError::QuotaExceeded {
                resource: QuotaResource::IntegerOverflow
            }
        ));
    }

    /// Test `DirCache` basic functionality
    #[test]
    fn test_dir_cache_basic() {
        let temp = TempDir::new().expect("failed to create temp dir");
        let mut cache = DirCache::new();

        let file_path = temp.path().join("a/b/c/file.txt");

        // First call creates directory
        let created = cache
            .ensure_parent_dir(&file_path)
            .expect("should create dir");
        assert!(created, "first call should create directory");
        assert!(temp.path().join("a/b/c").exists());

        // Second call finds cached directory
        let created = cache
            .ensure_parent_dir(&file_path)
            .expect("should use cache");
        assert!(!created, "second call should use cache");
    }

    /// Test `DirCache` with nested paths
    #[test]
    fn test_dir_cache_nested_paths() {
        let temp = TempDir::new().expect("failed to create temp dir");
        let mut cache = DirCache::new();

        // Create deep nested directory
        let file1 = temp.path().join("a/b/c/d/file1.txt");
        cache.ensure_parent_dir(&file1).expect("should create");
        assert!(temp.path().join("a/b/c/d").exists());

        // All ancestors should be cached
        let file2 = temp.path().join("a/b/other.txt");
        let created = cache.ensure_parent_dir(&file2).expect("should use cache");
        assert!(!created, "ancestor should be cached");
    }

    /// Test `DirCache` `ensure_dir` method
    #[test]
    fn test_dir_cache_ensure_dir() {
        let temp = TempDir::new().expect("failed to create temp dir");
        let mut cache = DirCache::new();

        let dir_path = temp.path().join("a/b/c");

        // First call creates directory
        let created = cache.ensure_dir(&dir_path).expect("should create dir");
        assert!(created, "first call should create directory");
        assert!(dir_path.exists());

        // Second call finds cached directory
        let created = cache.ensure_dir(&dir_path).expect("should use cache");
        assert!(!created, "second call should use cache");
    }

    /// Test `DirCache` with empty parent path
    #[test]
    fn test_dir_cache_empty_parent() {
        use std::path::PathBuf;
        let mut cache = DirCache::new();

        // Relative file path with no parent directory
        let file_path = PathBuf::from("file.txt");
        let created = cache
            .ensure_parent_dir(&file_path)
            .expect("should handle empty parent");
        assert!(!created, "file with no directory should return false");
    }

    /// Test `DirCache` with single component path
    #[test]
    fn test_dir_cache_single_component() {
        let temp = TempDir::new().expect("failed to create temp dir");
        let mut cache = DirCache::new();

        // Path with single component (no parent except current dir)
        let file_path = temp.path().join("file.txt");
        let created = cache
            .ensure_parent_dir(&file_path)
            .expect("should handle single component");

        // Parent is temp.path(), which was not in cache, so it gets created/cached
        assert!(created, "parent directory gets cached on first call");

        // Second call should use cache
        let file_path2 = temp.path().join("file2.txt");
        let created = cache
            .ensure_parent_dir(&file_path2)
            .expect("should use cache");
        assert!(!created, "second call uses cached parent");
    }

    /// Test `DirCache` with pre-existing directory
    #[test]
    fn test_dir_cache_preexisting_directory() {
        let temp = TempDir::new().expect("failed to create temp dir");
        let mut cache = DirCache::new();

        // Create directory manually first
        let dir_path = temp.path().join("existing/dir");
        std::fs::create_dir_all(&dir_path).expect("should create dir");

        // First call should still return true (not in cache)
        let created = cache.ensure_dir(&dir_path).expect("should succeed");
        assert!(created, "first call creates cache entry even if dir exists");

        // Second call should return false (cached)
        let created = cache.ensure_dir(&dir_path).expect("should succeed");
        assert!(!created, "second call uses cache");
    }

    /// Test `DirCache` with deep nesting (stress test)
    #[test]
    fn test_dir_cache_deep_nesting() {
        let temp = TempDir::new().expect("failed to create temp dir");
        let mut cache = DirCache::new();

        // Create path with 100 levels of nesting
        let mut path = temp.path().to_path_buf();
        for i in 0..100 {
            path.push(format!("level{i}"));
        }
        path.push("file.txt");

        // First call creates all 100 levels
        let created = cache
            .ensure_parent_dir(&path)
            .expect("should create deep nesting");
        assert!(created, "deep nesting should be created");

        // Verify all levels exist
        let parent = path.parent().expect("should have parent");
        assert!(parent.exists(), "all levels should exist");

        // Second call should use cache
        let created = cache.ensure_parent_dir(&path).expect("should use cache");
        assert!(!created, "deep nesting should be cached");
    }

    /// Test `DirCache` with multiple files in same directory
    #[test]
    fn test_dir_cache_multiple_files_same_dir() {
        let temp = TempDir::new().expect("failed to create temp dir");
        let mut cache = DirCache::new();

        let dir = temp.path().join("shared/directory");

        // First file creates directory
        let file1 = dir.join("file1.txt");
        let created = cache.ensure_parent_dir(&file1).expect("should create dir");
        assert!(created, "first file creates directory");

        // Subsequent files in same directory use cache
        for i in 2..=10 {
            let file = dir.join(format!("file{i}.txt"));
            let created = cache.ensure_parent_dir(&file).expect("should use cache");
            assert!(!created, "file {i} should use cached directory");
        }
    }

    /// Test `DirCache::with_capacity` constructor
    #[test]
    fn test_dir_cache_with_capacity() {
        let cache = DirCache::with_capacity(1000);
        // Just verify it constructs without panic
        assert_eq!(cache.created.len(), 0, "should start empty");
    }

    /// Test `DirCache::contains` method
    #[test]
    fn test_dir_cache_contains() {
        let temp = TempDir::new().expect("failed to create temp dir");
        let mut cache = DirCache::new();

        let dir_path = temp.path().join("a/b/c");

        // Before creation, should not contain
        assert!(
            !cache.contains(&dir_path),
            "should not contain before creation"
        );

        // Create directory
        cache.ensure_dir(&dir_path).expect("should create dir");

        // After creation, should contain
        assert!(cache.contains(&dir_path), "should contain after creation");

        // Ancestors should also be cached
        assert!(
            cache.contains(&temp.path().join("a/b")),
            "ancestor should be cached"
        );
        assert!(
            cache.contains(&temp.path().join("a")),
            "ancestor should be cached"
        );
    }

    /// H1: Test `create_file_with_mode()` with Unix mode 0o644
    #[cfg(unix)]
    #[test]
    fn test_create_file_with_mode_0o644() {
        use std::os::unix::fs::PermissionsExt;

        let temp = TempDir::new().expect("failed to create temp dir");
        let file_path = temp.path().join("test_0o644.txt");

        // Create file with mode 0o644
        let file = create_file_with_mode(&file_path, Some(0o644)).expect("should create file");
        drop(file);

        // Verify file exists
        assert!(file_path.exists(), "file should exist");

        // Verify permissions
        let metadata = std::fs::metadata(&file_path).expect("should read metadata");
        let mode = metadata.permissions().mode();

        // Mask to get only permission bits (remove file type bits)
        let permission_bits = mode & 0o777;
        assert_eq!(
            permission_bits, 0o644,
            "file should have permissions 0o644, got 0o{permission_bits:o}"
        );
    }

    /// H1: Test `create_file_with_mode()` with Unix mode 0o755
    #[cfg(unix)]
    #[test]
    fn test_create_file_with_mode_0o755() {
        use std::os::unix::fs::PermissionsExt;

        let temp = TempDir::new().expect("failed to create temp dir");
        let file_path = temp.path().join("test_0o755.txt");

        // Create file with mode 0o755
        let file = create_file_with_mode(&file_path, Some(0o755)).expect("should create file");
        drop(file);

        // Verify file exists
        assert!(file_path.exists(), "file should exist");

        // Verify permissions
        let metadata = std::fs::metadata(&file_path).expect("should read metadata");
        let mode = metadata.permissions().mode();

        // Mask to get only permission bits
        let permission_bits = mode & 0o777;
        assert_eq!(
            permission_bits, 0o755,
            "file should have permissions 0o755, got 0o{permission_bits:o}"
        );
    }

    /// H1: Test `create_file_with_mode()` with Unix mode 0o600
    #[cfg(unix)]
    #[test]
    fn test_create_file_with_mode_0o600() {
        use std::os::unix::fs::PermissionsExt;

        let temp = TempDir::new().expect("failed to create temp dir");
        let file_path = temp.path().join("test_0o600.txt");

        // Create file with mode 0o600
        let file = create_file_with_mode(&file_path, Some(0o600)).expect("should create file");
        drop(file);

        // Verify file exists
        assert!(file_path.exists(), "file should exist");

        // Verify permissions
        let metadata = std::fs::metadata(&file_path).expect("should read metadata");
        let mode = metadata.permissions().mode();

        // Mask to get only permission bits
        let permission_bits = mode & 0o777;
        assert_eq!(
            permission_bits, 0o600,
            "file should have permissions 0o600, got 0o{permission_bits:o}"
        );
    }

    /// H2: Test `create_file_with_mode()` with None (system default
    /// permissions)
    #[test]
    fn test_create_file_with_mode_none() {
        let temp = TempDir::new().expect("failed to create temp dir");
        let file_path = temp.path().join("test_none.txt");

        // Create file with mode=None (should use system defaults)
        let file = create_file_with_mode(&file_path, None).expect("should create file");
        drop(file);

        // Verify file exists
        assert!(file_path.exists(), "file should exist");

        // File should have been created successfully with default permissions
        // The exact permissions depend on umask and platform, so we just verify
        // creation
    }

    /// H2: Test `create_file_with_mode()` with None on Unix (verify umask-based
    /// default)
    #[cfg(unix)]
    #[test]
    fn test_create_file_with_mode_none_unix() {
        use std::os::unix::fs::PermissionsExt;

        let temp = TempDir::new().expect("failed to create temp dir");
        let file_path = temp.path().join("test_none_unix.txt");

        // Create file with mode=None
        let file = create_file_with_mode(&file_path, None).expect("should create file");
        drop(file);

        // Verify file exists
        assert!(file_path.exists(), "file should exist");

        // Verify file has some permission bits set (not zero)
        let metadata = std::fs::metadata(&file_path).expect("should read metadata");
        let mode = metadata.permissions().mode();
        let permission_bits = mode & 0o777;

        // Should have some permissions (not completely locked)
        // Typical defaults are 0o644 or 0o666 & !umask
        assert_ne!(
            permission_bits, 0,
            "file should have non-zero permissions with mode=None"
        );
    }

    /// Verify that extracted file permissions match the sanitized mode even
    /// when the process umask would otherwise reduce them.
    ///
    /// A file with mode 0o777 in the archive is sanitized to 0o775 by default
    /// (world-writable bit stripped). The extracted file must have exactly
    /// 0o775, not 0o755 (which would happen if umask 022 were applied on top).
    #[cfg(unix)]
    #[test]
    fn test_extract_file_permissions_bypass_umask() {
        use std::os::unix::fs::PermissionsExt;

        let temp = TempDir::new().expect("failed to create temp dir");
        let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
        let mut report = ExtractionReport::default();
        let mut copy_buffer = CopyBuffer::new();
        let mut dir_cache = DirCache::new();

        let config = SecurityConfig::default();

        // Mode 0o777 in archive, sanitized to 0o775 (world-writable stripped)
        let sanitized_mode = 0o775u32;
        let validated = ValidatedEntry {
            safe_path: SafePath::validate(&PathBuf::from("perm_test.txt"), &dest, &config)
                .expect("path should be valid"),
            mode: Some(sanitized_mode),
            entry_type: ValidatedEntryType::File,
        };

        let mut reader = Cursor::new(b"content");

        extract_file_generic(
            &mut reader,
            &validated,
            &dest,
            &mut report,
            None,
            &mut copy_buffer,
            &mut dir_cache,
            true,
        )
        .expect("extraction should succeed");

        let extracted = temp.path().join("perm_test.txt");
        assert!(extracted.exists(), "file should exist");

        let metadata = std::fs::metadata(&extracted).expect("should read metadata");
        let permission_bits = metadata.permissions().mode() & 0o777;

        assert_eq!(
            permission_bits, 0o775,
            "extracted file must have exact sanitized mode 0o775, got 0o{permission_bits:o}; \
             umask may have incorrectly reduced permissions"
        );
    }

    /// Verify that `create_file_with_mode` bypasses umask by explicitly setting
    /// a strict umask (0o077) before creating the file. Without the
    /// `set_permissions` call, umask 0o077 would reduce 0o755 to 0o700.
    /// With the fix, the file must retain the full 0o755 mode.
    ///
    /// Uses `libc::umask` to set and restore the process umask around the test.
    /// nextest runs each test in its own process, so umask mutation is safe.
    #[cfg(unix)]
    #[test]
    #[allow(unsafe_code)]
    fn test_create_file_with_mode_bypasses_strict_umask() {
        use std::os::unix::fs::PermissionsExt;

        let temp = TempDir::new().expect("failed to create temp dir");
        let file_path = temp.path().join("strict_umask_test.txt");

        // Set a strict umask that would strip group+other bits entirely.
        // Without set_permissions(), 0o755 & ~0o077 = 0o700.
        // SAFETY: single-threaded test process (nextest isolation), umask is
        // process-global but safe to mutate here. Restored unconditionally.
        let previous_umask = unsafe { libc::umask(0o077) };

        let result = create_file_with_mode(&file_path, Some(0o755));

        // Restore previous umask unconditionally before any assert.
        unsafe { libc::umask(previous_umask) };

        let file = result.expect("should create file under strict umask");
        drop(file);

        let metadata = std::fs::metadata(&file_path).expect("should read metadata");
        let permission_bits = metadata.permissions().mode() & 0o777;

        assert_eq!(
            permission_bits, 0o755,
            "file must have exact mode 0o755 despite strict umask 0o077; \
             got 0o{permission_bits:o} — set_permissions bypass not working"
        );
    }
}