geezipx-core 0.5.0

Compression/decompression core engine for GeeZipX
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
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
//! ZIP archive reader and writer implementations.
//!
//! Built on top of the [`zip`] crate (v2.x).  The reader is generic over
//! any `Read + Seek + Send` backend so callers can pass a file or a
//! memory buffer; individual entry extraction is streaming via
//! `std::io::copy`.  The writer is generic over any `Write + Seek` backend.

use std::fmt;
use std::io::{Read, Seek, Write};
use std::path::Path;

use zip::write::SimpleFileOptions;
use zip::AesMode;

use crate::archive::{
    check_entry_path_safety, normalize_path, ArchiveReader, ArchiveWriter, Entry, ExtractReport,
};
use crate::detect::ArchiveFormat;
use crate::error::{GeeZipError, GeeZipResult};

// ---------------------------------------------------------------------------
// ZipReader
// ---------------------------------------------------------------------------

/// ZIP archive reader.
///
/// Generic over any `R: Read + Seek + Send` (file, cursor, etc.).  The
/// [`ZipReader::from_buf`] convenience constructor is provided for the
/// common case of reading from an already-loaded byte buffer.
pub struct ZipReader<R: Read + Seek + Send> {
    archive: zip::ZipArchive<R>,
    format: ArchiveFormat,
    password: Option<String>,
}

impl<R: Read + Seek + Send> fmt::Debug for ZipReader<R> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ZipReader")
            .field("format", &self.format)
            .finish_non_exhaustive()
    }
}

impl<R: Read + Seek + Send> ZipReader<R> {
    /// Create a reader from any `Read + Seek + Send` source.
    ///
    /// The input is **not** buffered into memory — the source is passed
    /// directly to the underlying `zip::ZipArchive`.
    pub fn new(reader: R) -> GeeZipResult<Self> {
        let archive = zip::ZipArchive::new(reader).map_err(convert_zip_error)?;
        Ok(ZipReader {
            archive,
            format: ArchiveFormat::Zip,
            password: None,
        })
    }
}

impl<R: Read + Seek + Send> ZipReader<R> {
    /// Set a password for decrypting encrypted entries.
    pub fn set_password(&mut self, password: &str) {
        self.password = Some(password.to_owned());
    }
}

impl ZipReader<std::io::Cursor<Vec<u8>>> {
    /// Create a reader from an already-loaded byte buffer.
    ///
    /// Equivalent to `ZipReader::new(std::io::Cursor::new(buf))`.
    pub fn from_buf(buf: Vec<u8>) -> GeeZipResult<Self> {
        ZipReader::new(std::io::Cursor::new(buf))
    }
}

impl<R: Read + Seek + Send> ArchiveReader for ZipReader<R> {
    fn format(&self) -> ArchiveFormat {
        self.format
    }

    fn set_password(&mut self, password: &str) -> GeeZipResult<()> {
        self.password = Some(password.to_owned());
        Ok(())
    }

    fn entries(&mut self) -> GeeZipResult<Vec<Entry>> {
        let len = self.archive.len();
        let mut entries = Vec::with_capacity(len);

        for i in 0..len {
            let file = match &self.password {
                Some(pwd) => self
                    .archive
                    .by_index_decrypt(i, pwd.as_bytes())
                    .map_err(convert_zip_error)?,
                None => self.archive.by_index(i).map_err(convert_zip_error)?,
            };
            let modified = file.last_modified().map(|dt| {
                crate::archive::datetime_to_timestamp(
                    dt.year() as u64,
                    dt.month() as u64,
                    dt.day() as u64,
                    dt.hour() as u64,
                    dt.minute() as u64,
                    dt.second() as u64,
                )
            });
            entries.push(Entry {
                path: file.name().to_owned(),
                size: file.size(),
                compressed_size: file.compressed_size(),
                crc32: Some(file.crc32()),
                modified,
                is_dir: file.is_dir(),
            });
        }

        Ok(entries)
    }

    fn extract(&mut self, entry: &Entry, writer: &mut dyn Write) -> GeeZipResult<u64> {
        let mut file = match &self.password {
            Some(password) => self
                .archive
                .by_name_decrypt(&entry.path, password.as_bytes())
                .map_err(|e| match e {
                    zip::result::ZipError::FileNotFound => GeeZipError::EntryNotFound {
                        name: entry.path.clone(),
                    },
                    zip::result::ZipError::InvalidPassword => GeeZipError::Crypto {
                        message: format!("invalid password for '{}'", entry.path),
                    },
                    other => convert_zip_error(other),
                })?,
            None => self.archive.by_name(&entry.path).map_err(|e| match e {
                zip::result::ZipError::FileNotFound => GeeZipError::EntryNotFound {
                    name: entry.path.clone(),
                },
                other => convert_zip_error(other),
            })?,
        };

        let bytes = std::io::copy(&mut file, writer)
            .map_err(|e| GeeZipError::io(e, format!("extracting '{}'", entry.path)))?;

        Ok(bytes)
    }

    fn extract_all(&mut self, dest: &Path, overwrite: bool) -> GeeZipResult<ExtractReport> {
        let entries = self.entries()?;
        let mut report = ExtractReport::default();

        let dest = normalize_path(dest);

        for entry in &entries {
            let entry_path = Path::new(&entry.path);

            // --- Path safety checks (Zip Slip protection) ---
            let target = match check_entry_path_safety(entry_path, &entry.path, &dest) {
                Ok(t) => t,
                Err((name, err)) => {
                    report.errors.push((name, err));
                    continue;
                }
            };

            // Handle directory entries — create directory and skip file I/O.
            if entry.is_dir {
                if let Err(e) = std::fs::create_dir_all(&target) {
                    report
                        .errors
                        .push((entry.path.clone(), GeeZipError::io(e, "creating directory")));
                    continue;
                }
                report.files_extracted += 1;
                continue;
            }

            // Create parent directory.
            if let Some(parent) = target.parent() {
                if !parent.exists() {
                    if let Err(e) = std::fs::create_dir_all(parent) {
                        report.errors.push((
                            entry.path.clone(),
                            GeeZipError::io(e, "creating parent directory"),
                        ));
                        continue;
                    }
                }
            }

            // Write entry content — atomically create or fail (avoids TOCTOU
            // between path-exists check and file creation for the no-clobber path).
            let mut output = if overwrite {
                match std::fs::File::create(&target) {
                    Ok(f) => f,
                    Err(e) => {
                        report.errors.push((
                            entry.path.clone(),
                            GeeZipError::io(e, format!("creating '{}'", target.display())),
                        ));
                        continue;
                    }
                }
            } else {
                match std::fs::OpenOptions::new()
                    .write(true)
                    .create_new(true)
                    .open(&target)
                {
                    Ok(f) => f,
                    Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                        report.files_skipped += 1;
                        report.errors.push((
                            entry.path.clone(),
                            GeeZipError::clobber_denied(target.display().to_string()),
                        ));
                        continue;
                    }
                    Err(e) => {
                        report.errors.push((
                            entry.path.clone(),
                            GeeZipError::io(e, format!("creating '{}'", target.display())),
                        ));
                        continue;
                    }
                }
            };

            match self.extract(entry, &mut output) {
                Ok(bytes) => {
                    report.files_extracted += 1;
                    report.bytes_extracted += bytes;
                }
                Err(e) => {
                    report.errors.push((entry.path.clone(), e));
                }
            }
        }

        Ok(report)
    }
}

// ---------------------------------------------------------------------------
// ZipWriter
// ---------------------------------------------------------------------------

/// ZIP archive writer.
///
/// Generic over any `W: Write + Seek + Send`.  Construct via
/// [`ZipWriter::new`], add entries with
/// [`add_entry_from_reader`](ArchiveWriter::add_entry_from_reader), then
/// finalise with either:
///
/// - [`ZipWriter::finalize`] — returns `(total_bytes, inner_writer)`
/// - [`ArchiveWriter::finish`] — returns `total_bytes` (trait object-safe)
pub struct ZipWriter<W: Write + Seek> {
    inner: zip::ZipWriter<W>,
    start_pos: u64,
    format: ArchiveFormat,
    password: Option<String>,
}

impl<W: Write + Seek> ZipWriter<W> {
    /// Create a new ZIP writer targeting the given output.
    pub fn new(mut writer: W) -> Self {
        let start_pos = writer.stream_position().unwrap_or(0);
        ZipWriter {
            inner: zip::ZipWriter::new(writer),
            start_pos,
            format: ArchiveFormat::Zip,
            password: None,
        }
    }

    /// Set a password for AES-256 encryption.
    pub fn set_password(&mut self, password: &str) {
        self.password = Some(password.to_owned());
    }

    /// Finalize the ZIP archive and return the inner writer alongside
    /// the total number of bytes written.
    ///
    /// This is the "rich" version of [`ArchiveWriter::finish`] that lets
    /// callers recover the underlying writer (e.g. to inspect the
    /// buffer contents).
    pub fn finalize(self) -> GeeZipResult<(u64, W)> {
        let start_pos = self.start_pos;
        let mut writer = self.inner.finish().map_err(convert_zip_error)?;
        let end_pos = writer
            .stream_position()
            .map_err(|e| GeeZipError::io(e, "getting final archive size"))?;
        Ok((end_pos - start_pos, writer))
    }
}

impl<W: Write + Seek + Send> ArchiveWriter for ZipWriter<W> {
    fn format(&self) -> ArchiveFormat {
        self.format
    }

    fn add_entry_from_reader(&mut self, path: &Path, reader: &mut dyn Read) -> GeeZipResult<()> {
        let name = path.to_str().ok_or_else(|| GeeZipError::Format {
            message: format!("non-UTF-8 path: {}", path.display()),
            format: ArchiveFormat::Zip,
        })?;

        let mut options =
            SimpleFileOptions::default().compression_method(zip::CompressionMethod::DEFLATE);
        if let Some(password) = &self.password {
            options = options.with_aes_encryption(AesMode::Aes256, password);
        }

        self.inner
            .start_file(name, options)
            .map_err(convert_zip_error)?;

        std::io::copy(reader, &mut self.inner)
            .map_err(|e| GeeZipError::io(e, format!("writing entry '{}'", name)))?;

        Ok(())
    }

    fn add_directory(&mut self, path: &Path) -> GeeZipResult<()> {
        // ZIP stores directories implicitly via a trailing slash in the entry
        // path. Write an empty entry with trailing slash.
        let dir_path = format!("{}/", path.display());
        let _name = path.to_str().ok_or_else(|| GeeZipError::Format {
            message: format!("non-UTF-8 path: {}", path.display()),
            format: ArchiveFormat::Zip,
        })?;

        let mut options = zip::write::FileOptions::<()>::default()
            .compression_method(zip::CompressionMethod::Stored);
        if let Some(password) = &self.password {
            options = options.with_aes_encryption(AesMode::Aes256, password);
        }
        self.inner
            .start_file(&dir_path, options)
            .map_err(|e| GeeZipError::Format {
                message: format!("starting ZIP directory entry: {e}"),
                format: ArchiveFormat::Zip,
            })?;

        Ok(())
    }

    fn finish(self: Box<Self>) -> GeeZipResult<u64> {
        // Deref the box and call the inherent finalize, discarding
        // the writer.
        let (bytes, _writer) = (*self).finalize()?;
        Ok(bytes)
    }
}

// ---------------------------------------------------------------------------
// Error conversion
// ---------------------------------------------------------------------------

fn convert_zip_error(e: zip::result::ZipError) -> GeeZipError {
    match e {
        zip::result::ZipError::Io(inner) => GeeZipError::Io {
            source: inner,
            context: "ZIP operation failed".into(),
        },
        zip::result::ZipError::InvalidArchive(msg) => GeeZipError::Format {
            message: format!("invalid ZIP archive: {msg}"),
            format: ArchiveFormat::Zip,
        },
        zip::result::ZipError::FileNotFound => GeeZipError::EntryNotFound {
            name: "(unknown)".into(),
        },
        zip::result::ZipError::UnsupportedArchive(msg) => GeeZipError::Format {
            message: format!("unsupported ZIP feature: {msg}"),
            format: ArchiveFormat::Zip,
        },
        zip::result::ZipError::InvalidPassword => GeeZipError::Crypto {
            message: "invalid ZIP password".into(),
        },
        _ => GeeZipError::Format {
            message: "unknown ZIP error".into(),
            format: ArchiveFormat::Zip,
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;
    use std::path::PathBuf;

    /// Create a minimal valid ZIP archive in memory containing the given
    /// file entries (stored, not compressed).
    fn create_test_zip(files: &[(&str, &[u8])]) -> Vec<u8> {
        let mut buf = Cursor::new(Vec::new());
        {
            let mut zip = zip::ZipWriter::new(&mut buf);
            let options =
                SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);

            for (name, data) in files {
                zip.start_file(*name, options).unwrap();
                zip.write_all(data).unwrap();
            }
            zip.finish().unwrap();
        }
        buf.into_inner()
    }

    // -------------------------------------------------------------------
    // Round-trip: write to Cursor -> read back from Vec
    // -------------------------------------------------------------------

    #[test]
    fn zip_roundtrip_single_file() {
        let content = b"hello world";
        let data = create_test_zip(&[("hello.txt", content)]);

        let mut reader = ZipReader::from_buf(data).unwrap();
        let entries = reader.entries().unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].path, "hello.txt");
        assert_eq!(entries[0].size, content.len() as u64);

        let mut output = Vec::new();
        let bytes = reader.extract(&entries[0], &mut output).unwrap();
        assert_eq!(bytes, content.len() as u64);
        assert_eq!(output, content);
    }

    #[test]
    fn zip_roundtrip_multiple_files() {
        let files = [
            ("a.txt", b"aaa" as &[u8]),
            ("b.txt", b"bbb" as &[u8]),
            ("c.txt", b"ccc" as &[u8]),
        ];
        let data = create_test_zip(&files);

        let mut reader = ZipReader::from_buf(data).unwrap();
        let entries = reader.entries().unwrap();
        assert_eq!(entries.len(), 3);

        for (i, (name, content)) in files.iter().enumerate() {
            assert_eq!(entries[i].path, *name);
            let mut output = Vec::new();
            reader.extract(&entries[i], &mut output).unwrap();
            assert_eq!(output, *content);
        }
    }

    #[test]
    fn zip_roundtrip_nested_path() {
        let content = b"nested content";
        let data = create_test_zip(&[("dir/subdir/file.txt", content)]);

        let mut reader = ZipReader::from_buf(data).unwrap();
        let entries = reader.entries().unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].path, "dir/subdir/file.txt");

        let mut output = Vec::new();
        let bytes = reader.extract(&entries[0], &mut output).unwrap();
        assert_eq!(output, content);
        assert_eq!(bytes, content.len() as u64);
    }

    #[test]
    fn zip_unicode_filename() {
        let content = b"unicode content";
        let data = create_test_zip(&[("\u{4e2d}\u{6587}.txt", content)]); // 中文.txt

        let mut reader = ZipReader::from_buf(data).unwrap();
        let entries = reader.entries().unwrap();
        assert_eq!(entries.len(), 1);
        assert!(entries[0].path.contains('\u{4e2d}'));
    }

    // -------------------------------------------------------------------
    // Empty / malformed archives
    // -------------------------------------------------------------------

    #[test]
    fn zip_empty_archive_fails() {
        let err = ZipReader::from_buf(vec![]).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.to_lowercase().contains("zip") || msg.to_lowercase().contains("invalid"),
            "expected ZIP-related error, got: {msg}"
        );
    }

    #[test]
    fn zip_corrupted_archive_fails() {
        let bad_data = b"this is not a zip file at all";
        let err = ZipReader::from_buf(bad_data.to_vec()).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.to_lowercase().contains("zip") || msg.to_lowercase().contains("invalid"),
            "expected ZIP-related error, got: {msg}"
        );
    }

    // -------------------------------------------------------------------
    // Zip Slip protection
    // -------------------------------------------------------------------

    #[test]
    fn zip_slip_detection() {
        use std::io::Write as IoWrite;

        // Create a ZIP with a path-traversal entry manually.
        let mut buf = Cursor::new(Vec::new());
        {
            let inner = Cursor::new(Vec::new());
            let mut zip = zip::ZipWriter::new(inner);
            let name = "../escape.txt";
            let options =
                SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
            zip.start_file(name, options).unwrap();
            zip.write_all(b"malicious").unwrap();
            let inner = zip.finish().unwrap();
            buf.write_all(&inner.into_inner()).unwrap();
        }

        let mut reader = ZipReader::from_buf(buf.into_inner()).unwrap();
        let entries = reader.entries().unwrap();
        assert!(entries[0].path.contains(".."));

        let dest = tempfile::tempdir().unwrap();
        let report = reader.extract_all(dest.path(), true).unwrap();
        assert!(
            report
                .errors
                .iter()
                .any(|(_, e)| matches!(e, GeeZipError::PathTraversal { .. })),
            "expected PathTraversal error, got: {report:?}"
        );
        assert_eq!(report.files_extracted, 0);
    }

    #[test]
    fn zip_slip_dotdot_in_middle() {
        use std::io::Write as IoWrite;

        // foo/../../bar must be detected as PathTraversal.
        let mut buf = Cursor::new(Vec::new());
        {
            let inner = Cursor::new(Vec::new());
            let mut zip = zip::ZipWriter::new(inner);
            let options =
                SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
            zip.start_file("subdir/../../../escape.txt", options)
                .unwrap();
            zip.write_all(b"escape").unwrap();
            let inner = zip.finish().unwrap();
            buf.write_all(&inner.into_inner()).unwrap();
        }

        let mut reader = ZipReader::from_buf(buf.into_inner()).unwrap();
        let dest = tempfile::tempdir().unwrap();
        let report = reader.extract_all(dest.path(), true).unwrap();
        assert!(
            report
                .errors
                .iter()
                .any(|(_, e)| matches!(e, GeeZipError::PathTraversal { .. })),
            "expected PathTraversal for foo/../../bar, got: {report:?}"
        );
        assert_eq!(report.files_extracted, 0);
    }

    #[test]
    fn zip_slip_absolute_path() {
        use std::io::Write as IoWrite;

        // Entries with absolute paths must be rejected.
        let mut buf = Cursor::new(Vec::new());
        {
            let inner = Cursor::new(Vec::new());
            let mut zip = zip::ZipWriter::new(inner);
            let options =
                SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
            zip.start_file("/etc/passwd", options).unwrap();
            zip.write_all(b"leak").unwrap();
            let inner = zip.finish().unwrap();
            buf.write_all(&inner.into_inner()).unwrap();
        }

        let mut reader = ZipReader::from_buf(buf.into_inner()).unwrap();
        let dest = tempfile::tempdir().unwrap();
        let report = reader.extract_all(dest.path(), true).unwrap();
        assert!(
            report
                .errors
                .iter()
                .any(|(_, e)| matches!(e, GeeZipError::PathTraversal { .. })),
            "expected PathTraversal for absolute path, got: {report:?}"
        );
        assert_eq!(report.files_extracted, 0);
    }

    #[test]
    fn zip_extract_all_to_curdir() {
        use std::io::Write as IoWrite;

        let mut buf = Cursor::new(Vec::new());
        {
            let inner = Cursor::new(Vec::new());
            let mut zip = zip::ZipWriter::new(inner);
            let options =
                SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
            zip.start_file("file_a.txt", options).unwrap();
            zip.write_all(b"AAA").unwrap();
            let inner = zip.finish().unwrap();
            buf.write_all(&inner.into_inner()).unwrap();
        }

        let tmp = tempfile::tempdir().unwrap();
        let orig_cwd = std::env::current_dir().unwrap();

        std::env::set_current_dir(tmp.path()).unwrap();
        let mut reader = ZipReader::from_buf(buf.into_inner()).unwrap();
        let report = reader.extract_all(Path::new("."), true).unwrap();
        std::env::set_current_dir(orig_cwd).unwrap();

        assert_eq!(report.files_extracted, 1);
        assert!(report.errors.is_empty(), "errors: {report:#?}");
        assert!(
            tmp.path().join("file_a.txt").exists(),
            "file_a.txt should exist in {}",
            tmp.path().display()
        );
    }

    // -------------------------------------------------------------------
    // Writer
    // -------------------------------------------------------------------

    #[test]
    fn zip_writer_roundtrip() {
        let buf = Cursor::new(Vec::new());
        let mut zip_writer = ZipWriter::new(buf);
        zip_writer
            .add_entry_from_reader(
                &PathBuf::from("test.txt"),
                &mut Cursor::new(b"hello from writer"),
            )
            .unwrap();

        // Use inherent finalize to get the writer back, then read back.
        let (bytes_written, writer) = zip_writer.finalize().unwrap();
        assert!(bytes_written > 0, "should have written something");

        let data = writer.into_inner();
        let mut reader = ZipReader::from_buf(data).unwrap();
        let entries = reader.entries().unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].path, "test.txt");
        let mut output = Vec::new();
        let extracted = reader.extract(&entries[0], &mut output).unwrap();
        assert_eq!(extracted, b"hello from writer".len() as u64);
        assert_eq!(output, b"hello from writer");
    }

    #[test]
    fn zip_writer_multiple_files_roundtrip() {
        let buf = Cursor::new(Vec::new());
        let mut zip_writer = ZipWriter::new(buf);

        let files = [
            ("f1.txt", b"content 1" as &[u8]),
            ("f2.txt", b"content 2" as &[u8]),
            ("sub/f3.txt", b"nested content" as &[u8]),
        ];

        for (name, content) in &files {
            zip_writer
                .add_entry_from_reader(&PathBuf::from(name), &mut Cursor::new(content))
                .unwrap();
        }

        // finalize through trait to exercise that path too
        let boxed: Box<dyn ArchiveWriter> = Box::new(zip_writer);
        let _bytes_written = boxed.finish().unwrap();
    }

    #[test]
    fn zip_writer_add_directory_roundtrip() {
        let buf = Cursor::new(Vec::new());
        let mut zip_writer = ZipWriter::new(buf);

        // Add a regular file.
        zip_writer
            .add_entry_from_reader(
                &PathBuf::from("file.txt"),
                &mut Cursor::new(b"hello from file"),
            )
            .unwrap();

        // Add an empty directory.
        zip_writer.add_directory(Path::new("emptydir")).unwrap();

        let (bytes_written, writer) = zip_writer.finalize().unwrap();
        assert!(bytes_written > 0, "should have written something");

        let data = writer.into_inner();
        let mut reader = ZipReader::from_buf(data).unwrap();
        let entries = reader.entries().unwrap();
        assert_eq!(entries.len(), 2, "should have file + directory entries");

        // Verify the directory entry.
        let dir_entry = entries.iter().find(|e| e.is_dir).expect("directory entry");
        assert!(dir_entry.path.contains("emptydir"));
        assert!(dir_entry.is_dir);

        // Verify the file entry.
        let file_entry = entries.iter().find(|e| !e.is_dir).expect("file entry");
        assert_eq!(file_entry.path, "file.txt");
        assert!(!file_entry.is_dir);

        // Extract all to a tempdir.
        let dest = tempfile::tempdir().unwrap();
        let report = reader.extract_all(dest.path(), true).unwrap();
        assert_eq!(report.files_extracted, 2);
        assert!(report.errors.is_empty(), "extract_all errors: {report:?}");

        // Verify directory exists.
        assert!(dest.path().join("emptydir").is_dir());

        // Verify file content.
        let file_content = std::fs::read_to_string(dest.path().join("file.txt")).unwrap();
        assert_eq!(file_content, "hello from file");
    }

    #[test]
    fn zip_writer_finish_returns_bytes() {
        let buf = Cursor::new(Vec::new());
        let mut zip_writer = ZipWriter::new(buf);
        zip_writer
            .add_entry_from_reader(&PathBuf::from("data.bin"), &mut Cursor::new(b"data"))
            .unwrap();
        let boxed: Box<dyn ArchiveWriter> = Box::new(zip_writer);
        let bytes = boxed.finish().unwrap();
        assert!(bytes > 0, "should report bytes written");
    }

    // -------------------------------------------------------------------
    // Edge cases
    // -------------------------------------------------------------------

    #[test]
    fn zip_entry_not_found() {
        let data = create_test_zip(&[("exists.txt", b"data")]);
        let mut reader = ZipReader::from_buf(data).unwrap();

        let fake_entry = Entry {
            path: "does_not_exist.txt".into(),
            size: 0,
            compressed_size: 0,
            crc32: None,
            modified: None,
            is_dir: false,
        };

        let mut output = Vec::new();
        let err = reader.extract(&fake_entry, &mut output).unwrap_err();
        assert!(matches!(err, GeeZipError::EntryNotFound { .. }));
    }

    #[test]
    fn zip_extract_all_basic() {
        let data = create_test_zip(&[("file_a.txt", b"AAA"), ("file_b.txt", b"BBB")]);

        let mut reader = ZipReader::from_buf(data).unwrap();
        let dest = tempfile::tempdir().unwrap();

        let report = reader.extract_all(dest.path(), true).unwrap();
        assert_eq!(report.files_extracted, 2);
        assert_eq!(report.bytes_extracted, 6);
        assert!(report.errors.is_empty());

        // Verify files exist on disk.
        assert!(dest.path().join("file_a.txt").exists());
        assert!(dest.path().join("file_b.txt").exists());
    }

    // -------------------------------------------------------------------
    // No-clobber tests
    // -------------------------------------------------------------------

    #[test]
    fn zip_no_clobber_skips_existing_files() {
        let data = create_test_zip(&[("file_a.txt", b"AAA"), ("file_b.txt", b"BBB")]);

        let mut reader = ZipReader::from_buf(data).unwrap();
        let dest = tempfile::tempdir().unwrap();

        // First extract (creates files).
        let report = reader.extract_all(dest.path(), true).unwrap();
        assert_eq!(report.files_extracted, 2);
        assert!(report.errors.is_empty());

        // Modify one extracted file.
        let modified_path = dest.path().join("file_a.txt");
        std::fs::write(&modified_path, b"MODIFIED").unwrap();

        // Second extract with overwrite=false: should skip existing files.
        let mut reader2 = ZipReader::from_buf(create_test_zip(&[
            ("file_a.txt", b"AAA"),
            ("file_b.txt", b"BBB"),
        ]))
        .unwrap();
        let report2 = reader2.extract_all(dest.path(), false).unwrap();
        assert_eq!(
            report2.files_extracted, 0,
            "existing files should be skipped"
        );
        assert_eq!(
            report2.files_skipped, 2,
            "both files should be counted as skipped"
        );

        // Verify existing file was NOT overwritten.
        assert_eq!(
            std::fs::read_to_string(&modified_path).unwrap(),
            "MODIFIED",
            "existing file content should be preserved"
        );

        // Verify clobber-denied errors are recorded.
        assert!(
            report2
                .errors
                .iter()
                .any(|(_, e)| matches!(e, GeeZipError::ClobberDenied { .. })),
            "expected at least one ClobberDenied error"
        );
    }

    // -------------------------------------------------------------------
    // extract_all_with_cancel
    // -------------------------------------------------------------------

    #[test]
    fn zip_extract_all_with_cancel_normal() {
        let data = create_test_zip(&[("a.txt", b"aaa"), ("b.txt", b"bbb")]);
        let mut reader = ZipReader::from_buf(data).unwrap();
        let dest = tempfile::tempdir().unwrap();

        let report = reader
            .extract_all_with_cancel(dest.path(), true, &|| false)
            .unwrap();
        assert_eq!(report.files_extracted, 2);
        assert_eq!(report.bytes_extracted, 6);
        assert!(report.errors.is_empty());

        // Verify file contents.
        assert_eq!(
            std::fs::read_to_string(dest.path().join("a.txt")).unwrap(),
            "aaa"
        );
        assert_eq!(
            std::fs::read_to_string(dest.path().join("b.txt")).unwrap(),
            "bbb"
        );
    }

    #[test]
    fn zip_extract_all_with_cancel_before_first_entry() {
        let data = create_test_zip(&[("only.txt", b"data")]);
        let mut reader = ZipReader::from_buf(data).unwrap();
        let dest = tempfile::tempdir().unwrap();

        let err = reader
            .extract_all_with_cancel(dest.path(), true, &|| true)
            .unwrap_err();
        assert!(matches!(err, GeeZipError::Cancelled));

        // Ensure no file was extracted.
        assert!(!dest.path().join("only.txt").exists());
    }

    #[test]
    fn zip_extract_all_with_cancel_between_entries() {
        use std::cell::Cell;

        let data = create_test_zip(&[("first.txt", b"AAA"), ("second.txt", b"BBB")]);
        let mut reader = ZipReader::from_buf(data).unwrap();
        let dest = tempfile::tempdir().unwrap();

        let call_count = Cell::new(0u32);
        let is_cancelled = || {
            call_count.set(call_count.get() + 1);
            // Pre-entry check for entry 1 -> proceed (count 1)
            // Write check for entry 1 (CancellableWriter) -> proceed (count 2)
            // Pre-entry check for entry 2 -> cancel (count 3)
            call_count.get() > 2
        };

        let result = reader.extract_all_with_cancel(dest.path(), true, &is_cancelled);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), GeeZipError::Cancelled));

        // First file should exist and have correct content.
        assert_eq!(
            std::fs::read_to_string(dest.path().join("first.txt")).unwrap(),
            "AAA"
        );
        // Second file should NOT exist.
        assert!(!dest.path().join("second.txt").exists());
    }

    // -------------------------------------------------------------------
    // Trait object safety (compile-time checks)
    // -------------------------------------------------------------------

    #[test]
    fn archive_reader_trait_object() {
        fn use_reader(_r: &mut dyn ArchiveReader) {}
        let data = create_test_zip(&[("dummy.txt", b"x")]);
        let mut reader = ZipReader::from_buf(data).unwrap();
        use_reader(&mut reader);
    }

    #[test]
    fn archive_writer_trait_object() {
        fn use_writer(_w: Box<dyn ArchiveWriter>) {}
        let buf = Cursor::new(Vec::new());
        let writer = ZipWriter::new(buf);
        use_writer(Box::new(writer));
    }
}

#[test]
fn zip_truncated_not_panic() {
    // Empty local file header (50 4B 03 04) followed by nothing more.
    // Must NOT panic; should return a proper error.
    let err = ZipReader::from_buf(vec![0x50, 0x4B, 0x03, 0x04]).unwrap_err();
    let msg = err.to_string().to_lowercase();
    assert!(
        msg.contains("zip") || msg.contains("invalid"),
        "expected ZIP error for truncated zip, got: {err}"
    );
}

// ---------------------------------------------------------------------------
// AES-256 password tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod aes_tests {
    use super::*;
    use std::io::Cursor;

    /// Helper: create an AES-256 encrypted ZIP in memory.
    fn create_encrypted_zip(files: &[(&str, &[u8])], password: &str) -> Vec<u8> {
        let mut buf = Cursor::new(Vec::new());
        {
            let mut zip = zip::ZipWriter::new(&mut buf);
            for (name, data) in files {
                let options = SimpleFileOptions::default()
                    .compression_method(zip::CompressionMethod::Stored)
                    .with_aes_encryption(AesMode::Aes256, password);
                zip.start_file(*name, options).unwrap();
                zip.write_all(data).unwrap();
            }
            zip.finish().unwrap();
        }
        buf.into_inner()
    }

    #[test]
    fn encrypted_roundtrip_correct_password() {
        let content = b"secret data";
        let data = create_encrypted_zip(&[("secret.txt", content)], "mypassword");

        // Decrypt with correct password
        let mut reader = ZipReader::from_buf(data).unwrap();
        reader.set_password("mypassword");
        let entries = reader.entries().unwrap();
        assert_eq!(entries.len(), 1);

        let mut output = Vec::new();
        let bytes = reader.extract(&entries[0], &mut output).unwrap();
        assert_eq!(bytes, content.len() as u64);
        assert_eq!(output, content);
    }

    #[test]
    fn encrypted_wrong_password_fails() {
        let content = b"secret data";
        let data = create_encrypted_zip(&[("secret.txt", content)], "correctpw");

        let mut reader = ZipReader::from_buf(data).unwrap();
        reader.set_password("wrongpw");
        // entries() may succeed (zip crate validates password during read, not during listing)
        let entries_result = reader.entries();
        let err = match entries_result {
            Ok(entries) => reader.extract(&entries[0], &mut Vec::new()).unwrap_err(),
            Err(e) => e,
        };
        let msg = err.to_string().to_lowercase();
        assert!(
            msg.contains("password") || msg.contains("crypto"),
            "expected password/crypto error, got: {err}"
        );
    }

    #[test]
    fn encrypted_no_password_fails() {
        let content = b"secret data";
        let data = create_encrypted_zip(&[("secret.txt", content)], "secret123");

        let mut reader = ZipReader::from_buf(data).unwrap();
        let err = reader.entries().unwrap_err();
        let msg = err.to_string().to_lowercase();
        assert!(
            msg.contains("password") || msg.contains("crypto"),
            "expected password/crypto error, got: {err}"
        );
    }

    #[test]
    fn encrypted_list_entries_with_password() {
        let content = b"secret data";
        let data = create_encrypted_zip(
            &[("file1.txt", content), ("file2.txt", b"more data")],
            "mypassword",
        );

        // listing entries requires the password
        let mut reader = ZipReader::from_buf(data).unwrap();
        reader.set_password("mypassword");
        let entries = reader.entries().unwrap();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].path, "file1.txt");
        assert_eq!(entries[1].path, "file2.txt");
    }

    #[test]
    fn encrypted_empty_password_roundtrip() {
        // Try to use empty password in writer
        let mut buf = Cursor::new(Vec::new());
        {
            let mut zip = zip::ZipWriter::new(&mut buf);
            let options = SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored)
                .with_aes_encryption(AesMode::Aes256, "");
            zip.start_file("test.txt", options).unwrap();
            zip.write_all(b"data").unwrap();
            zip.finish().unwrap();
        }
        let data = buf.into_inner();

        // Decrypt with empty password - should fail or succeed depends on crate
        let mut reader = ZipReader::from_buf(data).unwrap();
        reader.set_password("");
        let entries = reader.entries().unwrap();
        let mut output = Vec::new();
        // Might fail depending on how zip crate handles empty passwords
        let _ = reader.extract(&entries[0], &mut output);
        // At minimum, verify we can list entries
        assert_eq!(entries[0].path, "test.txt");
    }
}