exarch-core 0.11.0

Memory-safe archive extraction library with security validation
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
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
//! High-level public API for archive extraction, creation, and inspection.

use std::path::Path;

use crate::ArchiveError;
use crate::ArchiveReader;
use crate::CreateRequest;
use crate::EntrySink;
use crate::ExtractRequest;
use crate::ExtractionReport;
use crate::OutputFile;
use crate::OutputFormat;
use crate::ProgressCallback;
use crate::Result;
use crate::SecurityConfig;
use crate::config::ExtractionOptions;
use crate::creation::CreationConfig;
use crate::creation::CreationReport;
use crate::encryption::Credentials;
use crate::formats::SevenZArchive;
use crate::formats::ZipArchive;
use crate::formats::common::open_archive;
use crate::formats::compression::CompressionCodec;
use crate::formats::compression::DecoderLimits;
use crate::formats::detect::CreatableFormat;
use crate::formats::detect::FormatFamily;
use crate::formats::detect::detect_format;
use crate::formats::detect::detect_format_from_extension;
use crate::formats::detect::is_zip_family_alias;
use crate::formats::output_root::OutputRoot;
use crate::formats::source_fault::TapSource;
use crate::inspection::ArchiveManifest;
use crate::inspection::VerificationReport;
use crate::inspection::integrity::TarTrailer;
use crate::mark::MarkScope;
use crate::reader::SeekableFormat;
use crate::reader::Source;
use crate::reader::decode_tar_stream;
use crate::reader::tar_archive;
use crate::sink::SinkOptions;
use crate::sink::SinkReuse;
use crate::sink::SinkTarget;

/// Extracts an archive to the specified output directory.
///
/// This is the main high-level API for extracting archives with security
/// validation. The archive format is automatically detected.
///
/// # Arguments
///
/// * `archive_path` - Path to the archive file
/// * `output_dir` - Directory where files will be extracted
/// * `config` - Security configuration for the extraction
///
/// # Errors
///
/// Returns an error if:
/// - Archive file cannot be opened
/// - Archive format is unsupported
/// - Security validation fails
/// - I/O operations fail
///
/// # Examples
///
/// ```no_run
/// use exarch_core::SecurityConfig;
/// use exarch_core::extract_archive;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = SecurityConfig::default();
/// let report = extract_archive("archive.tar.gz", "/tmp/output", &config)?;
/// println!("Extracted {} files", report.files_extracted);
/// # Ok(())
/// # }
/// ```
pub fn extract_archive<P: AsRef<Path>, Q: AsRef<Path>>(
    archive_path: P,
    output_dir: Q,
    config: &SecurityConfig,
) -> Result<ExtractionReport> {
    ExtractRequest::new(config).extract(archive_path, output_dir)
}

/// Extracts `archive_path` under a config that is already validated.
pub(crate) fn extract_validated<P: AsRef<Path>>(
    archive_path: P,
    output_dir: OutputRoot<'_>,
    config: &SecurityConfig,
    options: &ExtractionOptions,
    progress: &mut dyn ProgressCallback,
    credentials: Credentials,
) -> Result<ExtractionReport> {
    let archive_path = archive_path.as_ref();

    // Detect archive format from file extension
    let format = detect_format(archive_path)?;

    // Dispatch to format-specific extraction
    match format.family() {
        FormatFamily::Tar(codec) => {
            extract_tar(archive_path, output_dir, config, options, progress, codec)
        }
        FormatFamily::Seekable(SeekableFormat::Zip) => extract_zip(
            archive_path,
            output_dir,
            config,
            options,
            progress,
            credentials,
        ),
        FormatFamily::Seekable(SeekableFormat::SevenZ) => extract_7z(
            archive_path,
            output_dir,
            config,
            options,
            progress,
            &credentials,
        ),
    }
}

/// Opens `archive_path` as a TAR stream (decoded with `codec` when present)
/// and extracts it.
fn extract_tar(
    archive_path: &Path,
    output_dir: OutputRoot<'_>,
    config: &SecurityConfig,
    options: &ExtractionOptions,
    progress: &mut dyn ProgressCallback,
    codec: Option<CompressionCodec>,
) -> Result<ExtractionReport> {
    let file = open_archive(archive_path)?;
    let scope = MarkScope::open(options.mark_propagation, &file);
    let decoded = decode_tar_stream(file, codec, DecoderLimits::of(config))?;
    let trailer = TarTrailer::for_codec(codec);
    let source = decoded.source();
    scope.around(|mark| {
        extract_tar_stream(
            decoded.stream,
            source,
            trailer,
            output_dir.with_mark(mark),
            config,
            options,
            progress,
        )
    })
}

/// Extracts a TAR stream that is already decoded; `source` meters its raw
/// input and `trailer` says how the bytes after the end-of-archive marker are
/// checked.
pub(crate) fn extract_tar_stream<R: std::io::Read>(
    stream: R,
    source: TapSource,
    trailer: TarTrailer,
    output_dir: OutputRoot<'_>,
    config: &SecurityConfig,
    options: &ExtractionOptions,
    progress: &mut dyn ProgressCallback,
) -> Result<ExtractionReport> {
    use crate::formats::TarArchive;
    use crate::formats::traits::ArchiveFormat;

    TarArchive::with_source(stream, source, trailer, config).extract(output_dir, options, progress)
}

fn extract_zip(
    archive_path: &Path,
    output_dir: OutputRoot<'_>,
    config: &SecurityConfig,
    options: &ExtractionOptions,
    progress: &mut dyn ProgressCallback,
    credentials: Credentials,
) -> Result<ExtractionReport> {
    use crate::formats::ZipArchive;
    use crate::formats::traits::ArchiveFormat;
    let file = open_archive(archive_path)?;
    let scope = MarkScope::open(options.mark_propagation, &file);
    let archive = ZipArchive::for_extraction(file, config, options.decode_reuse, credentials)?;
    scope.around(|mark| archive.extract(output_dir.with_mark(mark), options, progress))
}

fn extract_7z(
    archive_path: &Path,
    output_dir: OutputRoot<'_>,
    config: &SecurityConfig,
    options: &ExtractionOptions,
    progress: &mut dyn ProgressCallback,
    credentials: &Credentials,
) -> Result<ExtractionReport> {
    use crate::formats::SevenZArchive;
    use crate::formats::traits::ArchiveFormat;
    let file = open_archive(archive_path)?;
    let scope = MarkScope::open(options.mark_propagation, &file);
    let archive = SevenZArchive::open(file, config, credentials)?;
    scope.around(|mark| archive.extract(output_dir.with_mark(mark), options, progress))
}

/// Creates an archive from source files and directories.
///
/// The format is detected from the output file extension; use
/// [`CreateRequest`] with an [`OutputFile`] to state it. An existing output
/// is replaced atomically once the archive is complete, and a failed creation
/// leaves the output as it was.
///
/// # Arguments
///
/// * `output_path` - Path to the output archive file
/// * `sources` - Source files and directories to include
/// * `config` - Creation configuration
///
/// # Errors
///
/// Returns an error if:
/// - Cannot determine archive format
/// - Source files don't exist
/// - I/O operations fail
/// - Configuration is invalid
///
/// # Examples
///
/// ```no_run
/// use exarch_core::CreationConfig;
/// use exarch_core::create_archive;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = CreationConfig::default();
/// let report = create_archive("output.tar.gz", &["src/", "Cargo.toml"], &config)?;
/// println!("Created archive with {} files", report.files_added);
/// # Ok(())
/// # }
/// ```
pub fn create_archive<P: AsRef<Path>, Q: AsRef<Path>>(
    output_path: P,
    sources: &[Q],
    config: &CreationConfig,
) -> Result<CreationReport> {
    CreateRequest::new(config).create(&OutputFile::replace(output_path.as_ref()), sources)
}

/// Lists archive contents without extracting.
///
/// Returns a manifest containing metadata for all entries in the archive.
/// No files are written to disk during this operation.
///
/// # Arguments
///
/// * `archive_path` - Path to archive file
/// * `config` - Security configuration (quota limits apply)
///
/// # Errors
///
/// Returns error if:
/// - Archive file cannot be opened
/// - Archive format is unsupported or corrupted
/// - Quota limits exceeded (file count, total size, single file size)
/// - A ZIP archive's structure is read differently by different tools
///   ([`ArchiveError::ZipInconsistency`], unless `zip_consistency` is `Ignore`)
/// - A link target exceeds the host's name limits
///
/// # Examples
///
/// ```no_run
/// use exarch_core::SecurityConfig;
/// use exarch_core::list_archive;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = SecurityConfig::default();
/// let manifest = list_archive("archive.tar.gz", &config)?;
///
/// println!("Archive contains {} files", manifest.total_entries());
/// for entry in manifest.entries() {
///     println!("{}: {} bytes", entry.path.display(), entry.size());
/// }
/// # Ok(())
/// # }
/// ```
pub fn list_archive<P: AsRef<Path>>(
    archive_path: P,
    config: &SecurityConfig,
) -> Result<ArchiveManifest> {
    crate::inspection::list_archive(archive_path, config)
}

/// Verifies archive security without extracting.
///
/// Performs metadata-only validation:
/// - Security checks (path traversal, zip bombs, CVEs)
/// - Policy checks (file types, permissions)
///
/// Payload integrity (checksums, decode-to-end) is not verified: the report's
/// `integrity_status` is
/// [`IntegrityStatus::Skipped`](crate::IntegrityStatus::Skipped);
/// use [`VerifyRequest`](crate::VerifyRequest) with `VerificationOptions` to
/// request it.
///
/// # Arguments
///
/// * `archive_path` - Path to archive file
/// * `config` - Security configuration for validation
///
/// # Errors
///
/// Returns error if:
/// - Archive file cannot be opened
/// - Archive is severely corrupted (cannot read structure)
/// - Declared compressed sizes exceed the archive length
/// - A ZIP central directory holds more records than `max_file_count`, counting
///   records the `zip` crate collapses or the end record does not count
/// - An entry name is a path traversal (`..` component, or an absolute path
///   unless `allowed.absolute_paths` is set): the listing step rejects it with
///   [`ArchiveError::PathTraversal`] before a report exists
///
/// The targets of 7z symlinks are stored in compressed entry data, so they are
/// validated only when an integrity check decodes the archive. Without one,
/// each such target stays unread and the report carries a single Medium issue
/// counting them (status at least `WARNING`); entries that would land beneath
/// an unread link are still reported. With an integrity check whose budget
/// cannot cover a link, the target stays unread in the same way.
///
/// Other security violations are reported in `VerificationReport::issues`
/// instead: disallowed links, link targets that escape the destination,
/// hardlinks whose target never appears, quota and compression-ratio
/// violations, NUL bytes, banned components, unsafe permissions and, for ZIP
/// under `zip_consistency = Enforce`, headers that disagree with the central
/// directory, duplicate names, overlapping entries and hidden records or
/// headers. The report's total is the ZIP's raw central directory count.
///
/// # Limitations
///
/// Verification models only the archive's own entries; it cannot account for
/// files, directories or links already present in the extraction destination,
/// so a PASS does not guarantee that extraction into a non-empty destination
/// succeeds. Symlink chains are cut off after a per-OS number of hops that
/// matches `std::fs::canonicalize` on macOS (33), glibc (40) and musl (39)
/// hosts; Windows (63) is unverified and other Unix hosts assume 32, where a
/// low guess can only give a false FAIL.
///
/// On macOS entry names are compared after NFD and a per-character case fold,
/// on Windows after the same fold without normalisation, and elsewhere
/// exactly. Two names that differ exactly but compare equal under that fold
/// are reported as a
/// [`IssueCategory::NameCollision`](crate::IssueCategory::NameCollision) (High
/// when the kinds differ or a symlink is involved, Medium for two files or for
/// directories that hold entries, Low for two directories that hold none), so a
/// merge is never silent. The fold approximates the host
/// table, so a pair it merges that the host keeps apart is reported too.
/// Windows component checks (reserved names, `:`, trailing dot or space,
/// `<>"|?*`, control characters) run only on Windows hosts.
///
/// Verification models extraction that skips an existing entry. With
/// overwrite semantics extraction keeps the last entry at a path, which
/// verification cannot model. A symlink entry over a path an earlier entry
/// created as a file is reported as a security finding, since overwriting
/// replaces the file and changes what the path resolves to. Where overwriting
/// fails closed and replaces nothing (a symlink over a symlink or directory,
/// a file over a directory or symlink, a hardlink over any earlier entry; a
/// symlink repeating an earlier symlink's target is not noted at all) the
/// entry is only noted as a Low
/// [`IssueCategory::InvalidArchive`](crate::IssueCategory::InvalidArchive)
/// issue, so the status stays `PASS`.
///
/// Hardlinks are materialized after every other entry, so their path and
/// target are validated against the final tree.
///
/// Name lengths are checked on the entry's relative path. Extraction adds the
/// destination prefix, so a long destination can make extraction fail with
/// `File name too long` for an entry `verify` accepted.
///
/// # Examples
///
/// ```no_run
/// use exarch_core::SecurityConfig;
/// use exarch_core::VerificationStatus;
/// use exarch_core::verify_archive;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = SecurityConfig::default();
/// let report = verify_archive("archive.tar.gz", &config)?;
///
/// if report.status() == VerificationStatus::Pass {
///     println!("Archive is safe to extract");
/// } else {
///     eprintln!("Security issues found:");
///     for issue in report.issues() {
///         eprintln!("  [{}] {}", issue.severity(), issue.message());
///     }
/// }
/// # Ok(())
/// # }
/// ```
pub fn verify_archive<P: AsRef<Path>>(
    archive_path: P,
    config: &SecurityConfig,
) -> Result<VerificationReport> {
    crate::inspection::verify_archive(archive_path, config)
}

/// A sink extraction, with a ZIP archive's census output kept
/// within `reuse` when the sink is one that shares its memory limit.
pub(crate) fn extract_to_sink_reusing<S: EntrySink>(
    reader: ArchiveReader<'_>,
    sink: &mut S,
    config: &SecurityConfig,
    options: SinkOptions,
    progress: &mut dyn ProgressCallback,
    reuse: Option<SinkReuse>,
    credentials: Credentials,
) -> Result<ExtractionReport> {
    match reader.into_source() {
        Source::Tar { stream, codec } => {
            let archive = tar_archive(stream, codec, config)?;
            let mut target = SinkTarget::new(sink, config);
            archive.extract_into(&mut target, config, options, progress)
        }
        Source::Seekable {
            reader,
            format: SeekableFormat::Zip,
        } => {
            let mut archive = match reuse {
                Some(reuse) => ZipArchive::for_sink(reader, config, &reuse, credentials)?,
                None => {
                    ZipArchive::for_extraction(reader, config, options.decode_reuse, credentials)?
                }
            };
            archive.check_structure(config)?.extract_with(
                |config| Ok(SinkTarget::new(sink, config)),
                options,
                progress,
            )
        }
        Source::Seekable {
            reader,
            format: SeekableFormat::SevenZ,
        } => {
            let mut archive = SevenZArchive::open(reader, config, &credentials)?;
            archive.admit(config)?.extract_with(
                |config| Ok(SinkTarget::new(sink, config)),
                options,
                progress,
            )
        }
    }
}

/// Rejects creation for ZIP-family extensions that aren't plain `.zip`.
///
/// They're all ZIP underneath but add extra requirements - signing
/// (apk/aab/ipa/appx/msix), checksum manifests (whl), ordering and
/// stored-compression rules (epub), descriptor files (war/ear/vsix/nbm) - which
/// exarch doesn't produce. Silently emitting a bare ZIP with one of these
/// extensions would be misleading, so creation errors instead; a caller who
/// needs it states [`CreatableFormat::Zip`] on the [`OutputFile`].
///
/// Returns `Ok(())` for anything else - `.zip`, tar variants, unknown
/// extensions (those get caught later by `detect_format`).
fn reject_zip_family_creation(output: &Path) -> Result<()> {
    let Some(ext) = output.extension().and_then(|e| e.to_str()) else {
        return Ok(());
    };
    if is_zip_family_alias(ext) {
        let ext_lower = ext.to_ascii_lowercase();
        return Err(ArchiveError::unclassified(format!(
            "creation for .{ext_lower} isn't supported: the format is ZIP-based but \
             requires extra structure (signing, manifests, ordering) that exarch \
             doesn't produce. Use .zip, or state the format with \
             OutputFile::with_format(exarch_core::CreatableFormat::Zip) \
             to override."
        )));
    }
    Ok(())
}

/// Determines the archive format of `output`.
///
/// Extension-only detection; magic-byte detection is intentionally excluded so
/// that a pre-existing output file with stale bytes cannot override the
/// caller's intended format.
pub(crate) fn resolve_output_format(output: &OutputFile) -> Result<CreatableFormat> {
    match output.format() {
        OutputFormat::Explicit(format) => Ok(format),
        OutputFormat::FromExtension => {
            reject_zip_family_creation(output.path())?;
            CreatableFormat::try_from(detect_format_from_extension(output.path())?)
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::NoopProgress;
    use crate::raw_zip::RawEntry;
    use crate::raw_zip::RawZip;
    use std::assert_matches;
    use std::path::PathBuf;

    #[test]
    fn test_extract_archive_nonexistent_file() {
        let config = SecurityConfig::default();
        let result = extract_archive(
            PathBuf::from("nonexistent_test.tar"),
            PathBuf::from("/tmp/test"),
            &config,
        );
        // Should fail because file doesn't exist
        assert!(result.is_err());
    }

    #[test]
    fn test_determine_creation_format_tar() {
        let path = PathBuf::from("archive.tar");
        let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
        assert_eq!(format, CreatableFormat::Tar);
    }

    #[test]
    fn test_determine_creation_format_tar_gz() {
        let path = PathBuf::from("archive.tar.gz");
        let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
        assert_eq!(format, CreatableFormat::TarGz);

        let path2 = PathBuf::from("archive.tgz");
        let format2 = resolve_output_format(&OutputFile::replace(&path2)).unwrap();
        assert_eq!(format2, CreatableFormat::TarGz);
    }

    #[test]
    fn test_determine_creation_format_tar_bz2() {
        let path = PathBuf::from("archive.tar.bz2");
        let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
        assert_eq!(format, CreatableFormat::TarBz2);
    }

    #[test]
    fn test_determine_creation_format_tar_xz() {
        let path = PathBuf::from("archive.tar.xz");
        let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
        assert_eq!(format, CreatableFormat::TarXz);
    }

    #[test]
    fn test_determine_creation_format_tar_zst() {
        let path = PathBuf::from("archive.tar.zst");
        let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
        assert_eq!(format, CreatableFormat::TarZst);
    }

    #[test]
    fn test_determine_creation_format_zip() {
        let path = PathBuf::from("archive.zip");
        let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
        assert_eq!(format, CreatableFormat::Zip);
    }

    #[test]
    fn test_determine_creation_format_explicit() {
        let path = PathBuf::from("archive.xyz");
        let output = OutputFile::replace(&path).with_format(CreatableFormat::TarGz);
        let format = resolve_output_format(&output).unwrap();
        assert_eq!(format, CreatableFormat::TarGz);
    }

    #[test]
    fn test_determine_creation_format_unknown() {
        let path = PathBuf::from("archive.rar");
        let result = resolve_output_format(&OutputFile::replace(&path));
        assert!(result.is_err());
    }

    #[test]
    fn test_determine_creation_format_ignores_stale_magic_bytes() {
        // Regression for C1: a pre-existing output file whose bytes match a
        // different format must not override the extension-derived format.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("backup.zip");
        // Write gzip magic bytes into a file named .zip
        std::fs::write(&path, b"\x1f\x8b\x08\x00\x00\x00\x00\x00").unwrap();

        let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
        assert_eq!(
            format,
            CreatableFormat::Zip,
            "creation format must follow extension, not stale on-disk magic bytes"
        );
    }

    #[test]
    fn test_extract_archive_7z_not_implemented() {
        let dest = tempfile::TempDir::new().unwrap();
        let path = PathBuf::from("test.7z");

        let result = extract_archive(&path, dest.path(), &SecurityConfig::default());

        assert!(result.is_err());
    }

    #[test]
    fn test_create_archive_zip_family_not_supported() {
        // Mirrors test_create_archive_7z_not_supported. Spot-checks a couple
        // of extensions rather than every one - the integration test
        // covers the full list.
        let dest = tempfile::TempDir::new().unwrap();
        for ext in ["apk", "whl", "EPUB"] {
            let archive_path = dest.path().join(format!("output.{ext}"));
            let result = create_archive(&archive_path, &[] as &[&str], &CreationConfig::default());
            assert_matches!(
                result,
                Err(ArchiveError::InvalidArchive(_)),
                ".{ext} should be rejected, got {result:?}",
            );
        }
    }

    #[test]
    fn test_create_archive_zip_family_override_bypasses_guard() {
        // An explicit OutputFile format is the escape hatch -
        // skips the ZIP-family guard. Caller takes responsibility for the
        // resulting file not being spec-valid.
        let dest = tempfile::TempDir::new().unwrap();
        let src = dest.path().join("source.txt");
        std::fs::write(&src, b"hello").unwrap();
        let archive_path = dest.path().join("output.apk");
        let result = CreateRequest::new(&CreationConfig::default()).create(
            &OutputFile::replace(&archive_path).with_format(CreatableFormat::Zip),
            &[&src],
        );
        assert!(
            result.is_ok(),
            "explicit format override should bypass the guard, got {result:?}",
        );
    }

    #[test]
    fn test_create_archive_7z_not_supported() {
        let dest = tempfile::TempDir::new().unwrap();
        let archive_path = dest.path().join("output.7z");

        let result = create_archive(&archive_path, &[] as &[&str], &CreationConfig::default());

        assert!(result.is_err());
        assert_matches!(
            result.unwrap_err(),
            ArchiveError::InvalidConfiguration { .. }
        );
    }

    #[test]
    fn test_extract_archive_with_options_and_progress_non_atomic_delegates_to_normal() {
        let dest = tempfile::TempDir::new().unwrap();
        let options = ExtractionOptions {
            staging: crate::Staging::InPlace,
            existing_files: crate::ExistingFiles::Skip,
            ..ExtractionOptions::default()
        };
        let result = ExtractRequest::new(&SecurityConfig::default())
            .with_options(options)
            .with_progress(&mut NoopProgress)
            .extract(PathBuf::from("nonexistent.tar.gz"), dest.path());
        assert!(result.is_err());
    }

    #[test]
    fn test_extract_archive_with_options_delegates() {
        let dest = tempfile::TempDir::new().unwrap();
        let options = ExtractionOptions {
            staging: crate::Staging::InPlace,
            existing_files: crate::ExistingFiles::Skip,
            ..ExtractionOptions::default()
        };
        let result = ExtractRequest::new(&SecurityConfig::default())
            .with_options(options)
            .extract(PathBuf::from("nonexistent.tar.gz"), dest.path());
        assert!(result.is_err());
    }

    #[test]
    fn test_extract_atomic_success() {
        use crate::create_archive;
        use crate::creation::CreationConfig;

        // Create a valid tar.gz to extract
        let archive_dir = tempfile::TempDir::new().unwrap();
        let archive_path = archive_dir.path().join("test.tar.gz");

        // Create a simple archive with one file
        let src_dir = tempfile::TempDir::new().unwrap();
        std::fs::write(src_dir.path().join("hello.txt"), b"hello world").unwrap();
        create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();

        let parent = tempfile::TempDir::new().unwrap();
        let output_dir = parent.path().join("extracted");

        let options = ExtractionOptions {
            staging: crate::Staging::Atomic,
            existing_files: crate::ExistingFiles::Skip,
            ..ExtractionOptions::default()
        };
        let result = ExtractRequest::new(&SecurityConfig::default())
            .with_options(options)
            .extract(&archive_path, &output_dir);

        assert!(result.is_ok());
        assert!(output_dir.exists());
        // No temp dir remnants
        let temp_entries: Vec<_> = std::fs::read_dir(parent.path()).unwrap().collect();
        assert_eq!(
            temp_entries.len(),
            1,
            "Expected only the output dir, found temp remnants"
        );
    }

    #[test]
    fn test_extract_atomic_failure_cleans_up() {
        let parent = tempfile::TempDir::new().unwrap();
        let output_dir = parent.path().join("extracted");

        let options = ExtractionOptions {
            staging: crate::Staging::Atomic,
            existing_files: crate::ExistingFiles::Skip,
            ..ExtractionOptions::default()
        };
        let result = ExtractRequest::new(&SecurityConfig::default())
            .with_options(options)
            .extract(PathBuf::from("nonexistent_archive.tar.gz"), &output_dir);

        assert!(result.is_err());
        // Output dir must not exist
        assert!(!output_dir.exists());
        // No temp dir remnants in parent
        let temp_entries: Vec<_> = std::fs::read_dir(parent.path()).unwrap().collect();
        assert!(
            temp_entries.is_empty(),
            "Temp dir not cleaned up after failure"
        );
    }

    #[test]
    fn test_extract_atomic_output_already_exists_fails() {
        use crate::create_archive;
        use crate::creation::CreationConfig;

        let parent = tempfile::TempDir::new().unwrap();
        let output_dir = parent.path().join("extracted");
        std::fs::create_dir_all(&output_dir).unwrap();
        // Create a file in output_dir so it's non-empty (rename over non-empty
        // dir fails on most OSes)
        std::fs::write(output_dir.join("existing.txt"), b"old content").unwrap();

        let archive_dir = tempfile::TempDir::new().unwrap();
        let archive_path = archive_dir.path().join("test.tar.gz");
        let src_dir = tempfile::TempDir::new().unwrap();
        std::fs::write(src_dir.path().join("new.txt"), b"new content").unwrap();
        create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();

        let options = ExtractionOptions {
            staging: crate::Staging::Atomic,
            existing_files: crate::ExistingFiles::Skip,
            ..ExtractionOptions::default()
        };
        let result = ExtractRequest::new(&SecurityConfig::default())
            .with_options(options)
            .extract(&archive_path, &output_dir);

        // Should fail with OutputExists or Io (platform dependent rename
        // semantics)
        assert!(result.is_err());
        // Output dir must still have old content (not corrupted)
        assert!(output_dir.join("existing.txt").exists());
    }

    // Regression test for issue #170: progress callback silently dropped
    #[test]
    fn test_progress_callback_invoked_during_extraction() {
        use crate::ProgressCallback;
        use std::path::Path;

        struct TrackingProgress {
            started: usize,
            completed: usize,
            finished: bool,
        }

        impl ProgressCallback for TrackingProgress {
            fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {
                self.started += 1;
            }

            fn on_bytes_written(&mut self, _bytes: u64) {}

            fn on_entry_complete(&mut self, _path: &Path) {
                self.completed += 1;
            }

            fn on_complete(&mut self) {
                self.finished = true;
            }
        }

        let archive_dir = tempfile::TempDir::new().unwrap();
        let archive_path = archive_dir.path().join("test.tar.gz");
        let src_dir = tempfile::TempDir::new().unwrap();
        std::fs::write(src_dir.path().join("a.txt"), b"hello").unwrap();
        std::fs::write(src_dir.path().join("b.txt"), b"world").unwrap();
        create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();

        let dest = tempfile::TempDir::new().unwrap();
        let mut progress = TrackingProgress {
            started: 0,
            completed: 0,
            finished: false,
        };

        let report = ExtractRequest::new(&SecurityConfig::default())
            .with_progress(&mut progress)
            .extract(&archive_path, dest.path())
            .unwrap();

        assert!(report.files_extracted >= 2, "expected at least 2 files");
        assert!(progress.started >= 2, "on_entry_start not called");
        assert!(progress.completed >= 2, "on_entry_complete not called");
        assert!(progress.finished, "on_complete not called");
    }

    // Regression test for issue #170: ZIP format
    #[test]
    fn test_progress_callback_invoked_during_zip_extraction() {
        use crate::ProgressCallback;
        use std::path::Path;

        struct TrackingProgress {
            started: usize,
            completed: usize,
            finished: bool,
        }

        impl ProgressCallback for TrackingProgress {
            fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {
                self.started += 1;
            }

            fn on_bytes_written(&mut self, _bytes: u64) {}

            fn on_entry_complete(&mut self, _path: &Path) {
                self.completed += 1;
            }

            fn on_complete(&mut self) {
                self.finished = true;
            }
        }

        let tmp = tempfile::TempDir::new().unwrap();
        let archive_path = tmp.path().join("test.zip");
        let src_dir = tempfile::TempDir::new().unwrap();
        std::fs::write(src_dir.path().join("x.txt"), b"foo").unwrap();
        std::fs::write(src_dir.path().join("y.txt"), b"bar").unwrap();
        create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();

        let dest = tempfile::TempDir::new().unwrap();
        let mut progress = TrackingProgress {
            started: 0,
            completed: 0,
            finished: false,
        };
        let report = ExtractRequest::new(&SecurityConfig::default())
            .with_progress(&mut progress)
            .extract(&archive_path, dest.path())
            .unwrap();

        assert!(report.files_extracted >= 2, "expected at least 2 files");
        assert!(progress.started >= 2, "on_entry_start not called for ZIP");
        assert!(
            progress.completed >= 2,
            "on_entry_complete not called for ZIP"
        );
        assert!(progress.finished, "on_complete not called for ZIP");
    }

    // Regression test for issue #170: 7z format
    #[test]
    fn test_progress_callback_invoked_during_sevenz_extraction() {
        use crate::ProgressCallback;
        use std::path::Path;

        struct TrackingProgress {
            started: usize,
            completed: usize,
            finished: bool,
        }

        impl ProgressCallback for TrackingProgress {
            fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {
                self.started += 1;
            }

            fn on_bytes_written(&mut self, _bytes: u64) {}

            fn on_entry_complete(&mut self, _path: &Path) {
                self.completed += 1;
            }

            fn on_complete(&mut self) {
                self.finished = true;
            }
        }

        let fixture =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/simple.7z");

        let dest = tempfile::TempDir::new().unwrap();
        let mut progress = TrackingProgress {
            started: 0,
            completed: 0,
            finished: false,
        };
        let report = ExtractRequest::new(&SecurityConfig::default())
            .with_progress(&mut progress)
            .extract(&fixture, dest.path())
            .unwrap();

        assert!(
            report.files_extracted >= 1,
            "expected at least 1 file from simple.7z"
        );
        assert!(progress.started >= 1, "on_entry_start not called for 7z");
        assert!(
            progress.completed >= 1,
            "on_entry_complete not called for 7z"
        );
        assert!(progress.finished, "on_complete not called for 7z");
    }

    // Regression test for issue #304: on_bytes_written must be called with > 0
    // bytes when extracting non-empty files from TAR archives.
    #[test]
    fn test_on_bytes_written_called_for_tar() {
        use crate::ProgressCallback;
        use std::path::Path;

        struct ByteTracker {
            total: u64,
        }

        impl ProgressCallback for ByteTracker {
            fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {}

            fn on_bytes_written(&mut self, bytes: u64) {
                self.total += bytes;
            }

            fn on_entry_complete(&mut self, _path: &Path) {}

            fn on_complete(&mut self) {}
        }

        let archive_dir = tempfile::TempDir::new().unwrap();
        let archive_path = archive_dir.path().join("test.tar.gz");
        let src_dir = tempfile::TempDir::new().unwrap();
        std::fs::write(src_dir.path().join("hello.txt"), b"hello world").unwrap();
        create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();

        let dest = tempfile::TempDir::new().unwrap();
        let mut progress = ByteTracker { total: 0 };
        let report = ExtractRequest::new(&SecurityConfig::default())
            .with_progress(&mut progress)
            .extract(&archive_path, dest.path())
            .unwrap();

        assert!(
            report.bytes_written > 0,
            "report.bytes_written must be > 0, got {}",
            report.bytes_written
        );
        assert!(
            progress.total > 0,
            "on_bytes_written must be called with > 0 bytes for TAR, got {}",
            progress.total
        );
    }

    // Regression test for issue #304: on_bytes_written must be called with > 0
    // bytes when extracting non-empty files from ZIP archives.
    #[test]
    fn test_on_bytes_written_called_for_zip() {
        use crate::ProgressCallback;
        use std::path::Path;

        struct ByteTracker {
            total: u64,
        }

        impl ProgressCallback for ByteTracker {
            fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {}

            fn on_bytes_written(&mut self, bytes: u64) {
                self.total += bytes;
            }

            fn on_entry_complete(&mut self, _path: &Path) {}

            fn on_complete(&mut self) {}
        }

        let tmp = tempfile::TempDir::new().unwrap();
        let archive_path = tmp.path().join("test.zip");
        let src_dir = tempfile::TempDir::new().unwrap();
        std::fs::write(src_dir.path().join("data.txt"), b"hello world").unwrap();
        create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();

        let dest = tempfile::TempDir::new().unwrap();
        let mut progress = ByteTracker { total: 0 };
        let report = ExtractRequest::new(&SecurityConfig::default())
            .with_progress(&mut progress)
            .extract(&archive_path, dest.path())
            .unwrap();

        assert!(
            report.bytes_written > 0,
            "report.bytes_written must be > 0, got {}",
            report.bytes_written
        );
        assert!(
            progress.total > 0,
            "on_bytes_written must be called with > 0 bytes for ZIP, got {}",
            progress.total
        );
    }

    // Regression test for issue #304: on_bytes_written must be called with > 0
    // bytes when extracting non-empty files from 7z archives.
    #[test]
    fn test_on_bytes_written_called_for_sevenz() {
        use crate::ProgressCallback;
        use std::path::Path;

        struct ByteTracker {
            total: u64,
        }

        impl ProgressCallback for ByteTracker {
            fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {}

            fn on_bytes_written(&mut self, bytes: u64) {
                self.total += bytes;
            }

            fn on_entry_complete(&mut self, _path: &Path) {}

            fn on_complete(&mut self) {}
        }

        let fixture =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/simple.7z");

        let dest = tempfile::TempDir::new().unwrap();
        let mut progress = ByteTracker { total: 0 };
        let report = ExtractRequest::new(&SecurityConfig::default())
            .with_progress(&mut progress)
            .extract(&fixture, dest.path())
            .unwrap();

        assert!(
            report.bytes_written > 0,
            "report.bytes_written must be > 0, got {}",
            report.bytes_written
        );
        assert!(
            progress.total > 0,
            "on_bytes_written must be called with > 0 bytes for 7z, got {}",
            progress.total
        );
    }

    // Regression test for BYTES-1: on_bytes_written must be called when TAR
    // hardlinks are extracted (copy path in create_hardlink).
    #[test]
    fn test_tar_hardlink_calls_on_bytes_written() {
        use crate::ProgressCallback;
        use crate::formats::TarArchive;
        use crate::formats::traits::ArchiveFormat;
        use std::io::Cursor;
        use std::path::Path;

        struct ByteTracker {
            total: u64,
        }

        impl ProgressCallback for ByteTracker {
            fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {}

            fn on_bytes_written(&mut self, bytes: u64) {
                self.total += bytes;
            }

            fn on_entry_complete(&mut self, _path: &Path) {}

            fn on_complete(&mut self) {}
        }

        // Build a TAR with one regular file and one hardlink pointing to it.
        let content = b"hello hardlink";
        let tar_data = {
            let mut builder = tar::Builder::new(Vec::new());

            let mut header = tar::Header::new_gnu();
            header.set_size(content.len() as u64);
            header.set_mode(0o644);
            header.set_entry_type(tar::EntryType::Regular);
            header.set_cksum();
            builder
                .append_data(&mut header, "original.txt", content.as_ref())
                .unwrap();

            let mut hdr = tar::Header::new_gnu();
            hdr.set_size(0);
            hdr.set_mode(0o644);
            hdr.set_entry_type(tar::EntryType::Link);
            hdr.set_link_name("original.txt").unwrap();
            hdr.set_cksum();
            builder
                .append_data(&mut hdr, "link.txt", std::io::empty())
                .unwrap();

            builder.into_inner().unwrap()
        };

        let temp = tempfile::TempDir::new().unwrap();
        let mut config = SecurityConfig::default();
        config.allowed.hardlinks = crate::Admit::Allow;

        let archive = TarArchive::new(Cursor::new(tar_data), &config);
        let mut progress = ByteTracker { total: 0 };
        let report = archive
            .extract(temp.path(), &ExtractionOptions::default(), &mut progress)
            .unwrap();

        // The hardlink copies the file content — bytes should be reported
        // twice.
        let expected = (content.len() as u64) * 2;
        assert_eq!(
            progress.total, expected,
            "on_bytes_written must report bytes for both original and hardlink copy, \
             got {} (report.bytes_written={})",
            progress.total, report.bytes_written
        );
    }

    // Regression test for issue #305: on_entry_complete must be called even
    // when TAR extraction fails mid-entry due to a path traversal violation.
    #[test]
    fn test_tar_on_entry_complete_called_on_path_traversal_error() {
        use crate::ProgressCallback;
        use crate::formats::TarArchive;
        use crate::formats::traits::ArchiveFormat;
        use std::io::Cursor;
        use std::path::Path;

        struct SymmetryTracker {
            started: usize,
            completed: usize,
        }

        impl ProgressCallback for SymmetryTracker {
            fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {
                self.started += 1;
            }

            fn on_bytes_written(&mut self, _bytes: u64) {}

            fn on_entry_complete(&mut self, _path: &Path) {
                self.completed += 1;
            }

            fn on_complete(&mut self) {}
        }

        // Build a minimal TAR with a path-traversal entry at raw bytes level
        // (bypassing the `tar` crate's sanitization).
        let tar_data = make_raw_tar_single(b"../../etc/passwd", b"evil");

        let temp = tempfile::TempDir::new().unwrap();
        let archive = TarArchive::new(Cursor::new(tar_data), &SecurityConfig::default());
        let mut progress = SymmetryTracker {
            started: 0,
            completed: 0,
        };
        let result = archive.extract(temp.path(), &ExtractionOptions::default(), &mut progress);

        assert!(result.is_err(), "traversal entry must be rejected");
        assert_eq!(
            progress.started, progress.completed,
            "on_entry_complete must be called for every on_entry_start, \
             even when extraction fails: started={}, completed={}",
            progress.started, progress.completed
        );
    }

    // Regression test for issue #305: on_entry_complete must be called even
    // when ZIP extraction fails mid-entry due to a path traversal violation.
    #[test]
    fn test_zip_on_entry_complete_called_on_path_traversal_error() {
        use crate::ProgressCallback;
        use crate::formats::ZipArchive;
        use crate::formats::traits::ArchiveFormat;
        use std::io::Cursor;
        use std::path::Path;

        struct SymmetryTracker {
            started: usize,
            completed: usize,
        }

        impl ProgressCallback for SymmetryTracker {
            fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {
                self.started += 1;
            }

            fn on_bytes_written(&mut self, _bytes: u64) {}

            fn on_entry_complete(&mut self, _path: &Path) {
                self.completed += 1;
            }

            fn on_complete(&mut self) {}
        }

        // Build a ZIP with a traversal path using zip::ZipWriter.
        let zip_data = make_zip_with_traversal(b"../../etc/passwd", b"evil");

        let temp = tempfile::TempDir::new().unwrap();
        let archive = ZipArchive::new(Cursor::new(zip_data), &SecurityConfig::default()).unwrap();
        let mut progress = SymmetryTracker {
            started: 0,
            completed: 0,
        };
        let result = archive.extract(temp.path(), &ExtractionOptions::default(), &mut progress);

        assert!(result.is_err(), "traversal entry must be rejected");
        assert_eq!(
            progress.started, progress.completed,
            "on_entry_complete must be called for every on_entry_start in ZIP, \
             even when extraction fails: started={}, completed={}",
            progress.started, progress.completed
        );
    }

    // Builds a single-entry POSIX ustar TAR with an arbitrary raw path,
    // bypassing the `tar` crate's path sanitization.
    fn make_raw_tar_single(path: &[u8], data: &[u8]) -> Vec<u8> {
        let mut out = Vec::new();
        let mut header = [0u8; 512];

        let path_len = path.len().min(100);
        header[..path_len].copy_from_slice(&path[..path_len]);
        header[100..108].copy_from_slice(b"0000644\0");
        header[108..116].copy_from_slice(b"0000000\0");
        header[116..124].copy_from_slice(b"0000000\0");
        let size_str = format!("{:011o}\0", data.len());
        header[124..136].copy_from_slice(size_str.as_bytes());
        header[136..148].copy_from_slice(b"00000000000\0");
        header[156] = b'0';
        header[257..263].copy_from_slice(b"ustar ");
        header[263..265].copy_from_slice(b" \0");
        header[148..156].copy_from_slice(b"        ");
        let checksum: u32 = header.iter().map(|&b| u32::from(b)).sum();
        let ck_str = format!("{checksum:06o}\0 ");
        header[148..156].copy_from_slice(ck_str.as_bytes());

        out.extend_from_slice(&header);
        out.extend_from_slice(data);
        let rem = data.len() % 512;
        if rem != 0 {
            out.extend(std::iter::repeat_n(0u8, 512 - rem));
        }
        out.extend(std::iter::repeat_n(0u8, 1024));
        out
    }

    // Builds a single-entry ZIP whose name is written verbatim, so a traversal
    // path survives into the headers.
    fn make_zip_with_traversal(path: &[u8], data: &[u8]) -> Vec<u8> {
        let entry = RawEntry {
            name: path.to_vec(),
            date: 0,
            ..RawEntry::stored("", data)
        };
        RawZip::new(vec![entry]).build().bytes
    }
}