exarch-core 0.7.0

Memory-safe archive extraction library with security validation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
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
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
//! Security configuration for archive extraction.

use std::marker::PhantomData;
use std::num::NonZeroU64;
use std::ops::Deref;
use std::ops::DerefMut;

use crate::closed_enum::closed_enum;

/// Marker type for a [`SecurityConfig`] whose invariants have not yet been
/// checked.
///
/// This is the default type parameter for [`SecurityConfig`]. The fluent
/// `with_*` builder methods and [`SecurityConfig::validate`] are only
/// available in this state.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Unvalidated;

/// Marker type for a [`SecurityConfig`] whose invariants have been checked.
///
/// Reachable only through [`SecurityConfig::validate`]. Every entry point
/// that performs security-sensitive work — the
/// [`ArchiveFormat`](crate::formats::traits::ArchiveFormat) trait and
/// everything it calls — requires a `SecurityConfig<Validated>`, so an
/// unvalidated configuration (e.g. one with `max_file_size == 0`) can never
/// reach extraction, listing, or verification. The compiler enforces this;
/// it is not a convention callers must remember to follow.
///
/// Once validated, a config's fields can still be *read* (via [`Deref`]) but
/// no longer *written*: [`DerefMut`] is implemented only for
/// `SecurityConfig<Unvalidated>`, so `cfg.max_compression_ratio = f64::NAN`
/// on a `SecurityConfig<Validated>` is a compile error, not a runtime
/// invariant violation. This is what makes the typestate airtight — without
/// it, a caller could validate a config and then mutate it back into an
/// invalid state before passing it to `ArchiveFormat::extract`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Validated;

/// Feature flags controlling what archive features are allowed during
/// extraction.
///
/// All features default to `false` (deny-by-default security policy).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct AllowedFeatures {
    /// Allow symlinks in extracted archives.
    pub symlinks: bool,

    /// Allow hardlinks in extracted archives.
    pub hardlinks: bool,

    /// Allow absolute paths in archive entries.
    pub absolute_paths: bool,

    /// Allow world-writable files (mode 0o002).
    ///
    /// World-writable files pose security risks in multi-user environments.
    pub world_writable: bool,

    /// Allow Windows reserved device names (`CON`, `NUL`, `COM1`, ...) as path
    /// components.
    ///
    /// Only consulted when extracting on Windows; has no effect elsewhere.
    /// There is no CLI or binding opt-out, and the permissive preset does not
    /// enable it.
    pub windows_reserved_names: bool,
}

closed_enum! {
    /// How ZIP structure that different readers interpret differently is
    /// handled.
    ///
    /// A ZIP archive stores each entry's metadata twice, in a local header and
    /// in the central directory. Random-access readers follow the central
    /// directory and streaming readers follow the local headers, so an
    /// archive whose copies disagree, that hides records, repeats a name or
    /// overlaps entries is a parser differential ("Zip Cloaking").
    ///
    /// `Enforce` (the default, also for [`SecurityConfig::permissive`])
    /// rejects such archives in `extract` and `list` and reports them in
    /// `verify`. `Ignore` keeps the central-directory interpretation and
    /// raises no structural finding; resource limits still apply.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    /// use exarch_core::ZipConsistencyPolicy;
    ///
    /// assert_eq!(
    ///     SecurityConfig::default().zip_consistency,
    ///     ZipConsistencyPolicy::Enforce
    /// );
    /// let relaxed = SecurityConfig::default().with_zip_consistency(ZipConsistencyPolicy::Ignore);
    /// assert_eq!(relaxed.zip_consistency.as_str(), "ignore");
    /// ```
    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
    #[non_exhaustive]
    pub enum ZipConsistencyPolicy {
        /// Reject or report structurally ambiguous ZIP archives
        #[default]
        Enforce => "enforce",

        /// Use the central directory interpretation without structural findings
        Ignore => "ignore",
    }
}

/// How much extra memory a 7z block may use to decode LZMA2 runs ahead on
/// worker threads.
///
/// An LZMA2 stream written with multiple threads (7-Zip's default for large
/// inputs) consists of independent runs, so several can be decoded at once.
/// Decoded runs wait in memory until the consumer reaches them, so the
/// lookahead is bounded: `Bounded(n)` lets in-flight runs hold at most `n`
/// bytes on top of the decoder window that
/// [`max_decoder_memory`](SecurityConfigFields::max_decoder_memory) already
/// admits. `Sequential` decodes on the calling thread only.
///
/// Archives written with runs of a few MiB decode within about 10% of an
/// unbounded multi-threaded reader at the default; a stock 7-Zip archive has
/// 64 MiB runs and needs about 100 MiB of lookahead
/// per extra concurrent run.
///
/// A valid archive decodes to the same bytes in either mode, and a corrupt one
/// fails the same file with the same error kind; only how many leading bytes
/// that file received can differ.
///
/// # Concurrency
///
/// The limit applies to one extraction or verification. Each call may start
/// up to 16 worker threads and hold its own lookahead, so concurrent calls
/// (for example from several Python threads or Node promises) multiply both
/// the threads and the memory. Size the setting for the number of calls that
/// can run at once, or use `Sequential`.
///
/// # Examples
///
/// ```
/// use std::num::NonZeroU64;
///
/// use exarch_core::ParallelDecode;
/// use exarch_core::SecurityConfig;
///
/// assert_eq!(
///     SecurityConfig::default().parallel_decode,
///     ParallelDecode::Bounded(NonZeroU64::new(128 * 1024 * 1024).unwrap())
/// );
/// let config = SecurityConfig::default().with_parallel_decode(ParallelDecode::Sequential);
/// assert_eq!(config.parallel_decode, ParallelDecode::Sequential);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParallelDecode {
    /// Decode on the calling thread only
    Sequential,

    /// Decode runs ahead on worker threads, holding at most this many bytes
    Bounded(NonZeroU64),
}

/// Builds a non-zero constant; a zero literal fails compilation.
const fn non_zero(n: u64) -> NonZeroU64 {
    match NonZeroU64::new(n) {
        Some(n) => n,
        None => panic!("constant must be non-zero"),
    }
}

impl ParallelDecode {
    /// Default lookahead: 128 MiB.
    pub const DEFAULT_BYTES: NonZeroU64 = non_zero(128 * 1024 * 1024);

    /// The lookahead memory in bytes, or `None` for [`Sequential`].
    ///
    /// [`Sequential`]: ParallelDecode::Sequential
    ///
    /// # Examples
    ///
    /// ```
    /// use std::num::NonZeroU64;
    ///
    /// use exarch_core::ParallelDecode;
    ///
    /// assert_eq!(ParallelDecode::Sequential.lookahead(), None);
    /// let bytes = NonZeroU64::new(1 << 20).unwrap();
    /// assert_eq!(ParallelDecode::Bounded(bytes).lookahead(), Some(bytes));
    /// ```
    #[must_use]
    pub const fn lookahead(self) -> Option<NonZeroU64> {
        match self {
            Self::Sequential => None,
            Self::Bounded(bytes) => Some(bytes),
        }
    }
}

impl From<Option<NonZeroU64>> for ParallelDecode {
    /// `None` is [`ParallelDecode::Sequential`].
    fn from(lookahead: Option<NonZeroU64>) -> Self {
        lookahead.map_or(Self::Sequential, Self::Bounded)
    }
}

impl Default for ParallelDecode {
    fn default() -> Self {
        Self::Bounded(Self::DEFAULT_BYTES)
    }
}

/// The field data of a [`SecurityConfig`], reachable via [`Deref`]/[`DerefMut`]
/// regardless of (or gated by) validation state.
///
/// This type is not itself part of the sealing boundary — it is a plain data
/// bag with `pub` fields, and nothing stops external code from naming it or
/// cloning one out of a `&SecurityConfig`. The boundary is
/// [`SecurityConfig`]'s own private `fields` member: there is no public API
/// that takes a bare `SecurityConfigFields` and wraps it back into a
/// `SecurityConfig<Validated>`, so an externally-forged or externally-mutated
/// `SecurityConfigFields` value can never be smuggled into a `Validated`
/// config. It exists purely so [`SecurityConfig`] can implement `Deref`/
/// `DerefMut` and keep `cfg.max_file_size`-style field access working for
/// every existing caller instead of forcing a getter-method migration.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SecurityConfigFields {
    /// Maximum size for a single file in bytes.
    pub max_file_size: u64,

    /// Maximum total size for all extracted files in bytes.
    pub max_total_size: u64,

    /// Maximum compression ratio allowed (uncompressed / compressed).
    pub max_compression_ratio: f64,

    /// Maximum compression ratio of a whole solid 7z block (summed
    /// uncompressed size of its files / compressed size of its pack streams).
    ///
    /// Solid members share one compressed stream, so no per-file ratio exists;
    /// this limit replaces `max_compression_ratio` for them. It is not exposed
    /// by the CLI or the Python/Node bindings.
    pub max_solid_compression_ratio: f64,

    /// Maximum number of entries that can be extracted.
    ///
    /// The extraction API counts files, symlinks and hardlinks, not
    /// directories. `list` and `verify`, and the CLI's `extract` (which lists
    /// the archive first), count every entry.
    pub max_file_count: usize,

    /// Maximum path depth allowed.
    pub max_path_depth: usize,

    /// Feature flags controlling what archive features are allowed.
    ///
    /// Use this to enable symlinks, hardlinks, absolute paths, etc.
    pub allowed: AllowedFeatures,

    /// Preserve file permissions from archive.
    pub preserve_permissions: bool,

    /// List of allowed file extensions (empty = allow all).
    ///
    /// Extensions are matched case-insensitively (e.g., `"txt"` matches both
    /// `file.txt` and `file.TXT`). The leading dot must be omitted.
    ///
    /// When this list is non-empty, files without a file extension are treated
    /// as not allowed and will be skipped during extraction.
    pub allowed_extensions: Vec<String>,

    /// List of banned path components (e.g., ".git", ".ssh").
    pub banned_path_components: Vec<String>,

    /// Allow extraction from solid 7z archives.
    ///
    /// Solid archives compress multiple files together as a single block.
    /// While this provides better compression ratios, it has security
    /// implications:
    ///
    /// - **Memory exhaustion**: Extracting a single file requires decompressing
    ///   the entire solid block into memory
    /// - **Denial of service**: Malicious archives can create large solid
    ///   blocks that exhaust available memory
    ///
    /// **Security Recommendation**: Only enable for trusted archives.
    ///
    /// Default: `false` (solid archives rejected)
    pub allow_solid_archives: bool,

    /// Maximum memory for solid archive extraction (bytes).
    ///
    /// **7z Solid Archive Memory Model:**
    ///
    /// Solid compression in 7z stores multiple files in a single compressed
    /// block. Extracting ANY file requires decompressing the ENTIRE solid block
    /// into memory, which can cause memory exhaustion attacks.
    ///
    /// **Validation Strategy:**
    /// - Pre-validates total uncompressed size of all files in archive
    /// - This is a conservative heuristic (assumes single solid block)
    /// - Reason: `sevenz-rust2` v0.20 doesn't expose solid block boundaries
    ///
    /// **Security Guarantee:**
    /// - Total uncompressed data cannot exceed this limit
    /// - Combined with `max_file_size`, prevents unbounded memory growth
    /// - Enforced ONLY when `allow_solid_archives` is `true`
    ///
    /// **Note**: Only applies when `allow_solid_archives` is `true`.
    ///
    /// Default: 512 MB (536,870,912 bytes)
    ///
    /// **Recommendation:** Set to 1-2x available RAM for trusted archives only.
    pub max_solid_block_memory: u64,

    /// Maximum bytes the TAR reader may consume for headers and metadata
    /// records in the gap between two consecutive entries.
    ///
    /// **TAR Metadata Buffering Model:**
    ///
    /// GNU long-name (`L`), GNU long-link (`K`), and PAX extended header
    /// (`x`/`g`) records are buffered fully into memory by the underlying
    /// `tar` crate *before* any entry reaches the entry validator or quota
    /// tracker — a crafted record can declare a multi-gigabyte length backed
    /// by a tiny compressed stream, exhausting memory with no quota
    /// enforcement (metadata-entry decompression bomb).
    ///
    /// **Enforcement Strategy:**
    /// - A read-budget wrapper meters bytes the `tar` crate reads while
    ///   searching for the next entry (headers, long-name/long-link/PAX
    ///   records, GNU sparse extension blocks) and returns an error once
    ///   `max_tar_metadata_bytes` is exceeded, before any oversized allocation
    ///   completes
    /// - Applies uniformly to `extract`, `list`, and `verify`
    /// - The window this bounds contains no entry *data* — only metadata — so
    ///   it does not interact with `max_file_size`/`max_total_size`. Draining
    ///   an unread entry before the next header search is a separate concern
    ///   (see `formats::tar_metadata_limit`'s module docs) bounded by
    ///   synthesized-byte accounting, not by this or any other quota value
    /// - Legitimate long-path/xattr metadata records are at most a few
    ///   kilobytes each, and a GNU tar sparse file with heavy fragmentation can
    ///   use up to a few thousand 512-byte extension blocks; either or both
    ///   share this single budget (not "plus" each other), so the default
    ///   leaves headroom for either shape, not necessarily both at their
    ///   extremes simultaneously
    /// - The real peak memory this bounds is roughly 5x the configured value
    ///   (GNU sparse extension blocks expand into multiple `EntryIo` records
    ///   per block before the growth is charged against this budget), not an
    ///   exact multiple — treat it as an order-of-magnitude ceiling, not a
    ///   tight bound
    ///
    /// Default: 4 MiB (4,194,304 bytes)
    pub max_tar_metadata_bytes: u64,

    /// Maximum memory in bytes an xz decoder may use (dictionary and state).
    ///
    /// The xz block header declares the LZMA2 dictionary size (up to 4 GiB),
    /// so without a limit a tiny archive can drive resident memory far beyond
    /// what the output quotas allow. Archives that need more fail with
    /// `QuotaExceeded { DecoderMemory }`. Applies to `extract`, `list` and
    /// `verify` of `.tar.xz`. Other codecs are bounded by their format
    /// (bzip2 blocks of at most 900 KB; zstd windows above 128 MiB are
    /// rejected) and are not governed by this value. Not exposed through the
    /// CLI or language bindings. Also admits the 7z decoder window; the
    /// lookahead of parallel 7z decoding is budgeted separately by
    /// [`parallel_decode`](Self::parallel_decode).
    ///
    /// Default: 256 MiB (268,435,456 bytes)
    pub max_decoder_memory: u64,

    /// Lookahead memory for decoding independent LZMA2 runs of a 7z block on
    /// worker threads.
    ///
    /// Applies to `extract` and `verify` with integrity checking of 7z
    /// archives. It is separate from `max_decoder_memory`, which keeps
    /// bounding the decoder window. See [`ParallelDecode`].
    ///
    /// Default: `Bounded` at 128 MiB (1 GiB for [`SecurityConfig::permissive`])
    pub parallel_decode: ParallelDecode,

    /// How ZIP archives with ambiguous structure are handled.
    ///
    /// Default: [`ZipConsistencyPolicy::Enforce`], including for
    /// [`SecurityConfig::permissive`]. Pre-ZIP64 archives with more than
    /// 65535 entries (wrapped end-record count) and archives with orphaned
    /// local headers, or with a central directory signature in a gap before an
    /// entry (left by in-place updaters), are rejected under `Enforce`.
    pub zip_consistency: ZipConsistencyPolicy,
}

impl Default for SecurityConfigFields {
    fn default() -> Self {
        Self {
            max_file_size: 50 * 1024 * 1024,   // 50 MB
            max_total_size: 500 * 1024 * 1024, // 500 MB
            max_compression_ratio: 100.0,
            max_solid_compression_ratio: 1000.0,
            max_file_count: 10_000,
            max_path_depth: 32,
            allowed: AllowedFeatures::default(), // All false
            preserve_permissions: false,
            allowed_extensions: Vec::new(),
            banned_path_components: vec![
                ".git".to_string(),
                ".ssh".to_string(),
                ".gnupg".to_string(),
                ".aws".to_string(),
                ".kube".to_string(),
                ".docker".to_string(),
                ".env".to_string(),
            ],
            allow_solid_archives: false,
            max_solid_block_memory: 512 * 1024 * 1024, // 512 MB
            max_tar_metadata_bytes: 4 * 1024 * 1024,   // 4 MiB
            max_decoder_memory: 256 * 1024 * 1024,     // 256 MiB
            parallel_decode: ParallelDecode::Bounded(ParallelDecode::DEFAULT_BYTES),
            zip_consistency: ZipConsistencyPolicy::Enforce,
        }
    }
}

/// Security configuration with default-deny settings.
///
/// This configuration controls various security checks performed during
/// archive extraction to prevent common vulnerabilities.
///
/// # Performance Note
///
/// This struct contains heap-allocated collections (`Vec<String>`). For
/// performance, pass by reference (`&SecurityConfig`) rather than cloning. If
/// shared ownership is needed across threads, consider wrapping in
/// `Arc<SecurityConfig>`.
///
/// # Examples
///
/// ```
/// use exarch_core::SecurityConfig;
///
/// // Use secure defaults
/// let config = SecurityConfig::default();
///
/// // Customize via fluent builder
/// let custom = SecurityConfig::default()
///     .with_max_file_size(100 * 1024 * 1024)
///     .with_max_total_size(1024 * 1024 * 1024)
///     .with_allow_symlinks(true);
/// ```
///
/// # Typestate
///
/// `SecurityConfig` carries a phantom `State` type parameter — [`Unvalidated`]
/// (the default) or [`Validated`] — that tracks whether
/// [`validate`](SecurityConfig::validate) has been called. Builder methods
/// are only available in the `Unvalidated` state; security-sensitive APIs
/// (the [`ArchiveFormat`](crate::formats::traits::ArchiveFormat) trait and
/// everything downstream of it) require `SecurityConfig<Validated>`. This
/// makes skipping validation a compile error instead of a runtime gap.
///
/// # Sealing
///
/// Fields are private and reachable only through
/// <code>[Deref]<Target = [SecurityConfigFields]></code>, so
/// `cfg.max_file_size` continues to work as plain field access for both states.
/// [`DerefMut`] is implemented only for
/// `SecurityConfig<Unvalidated>`, so a `SecurityConfig<Validated>`'s fields
/// cannot be reassigned after the fact — the only way to produce one is
/// [`validate`](SecurityConfig::validate) itself, and it stays that way for
/// its entire lifetime.
#[derive(Debug, Clone)]
pub struct SecurityConfig<State = Unvalidated> {
    fields: SecurityConfigFields,

    /// Typestate marker — see the "Typestate" section on the type-level docs.
    _marker: PhantomData<State>,
}

impl<State> Deref for SecurityConfig<State> {
    type Target = SecurityConfigFields;

    #[inline]
    fn deref(&self) -> &SecurityConfigFields {
        &self.fields
    }
}

/// Only `Unvalidated` configs are mutable — see the "Sealing" section on
/// [`SecurityConfig`]'s type-level docs for why this is the crux of the
/// typestate guarantee.
impl DerefMut for SecurityConfig<Unvalidated> {
    fn deref_mut(&mut self) -> &mut SecurityConfigFields {
        &mut self.fields
    }
}

impl Default for SecurityConfig<Unvalidated> {
    /// Creates a `SecurityConfig` with secure default settings.
    ///
    /// Default values:
    /// - `max_file_size`: 50 MB
    /// - `max_total_size`: 500 MB
    /// - `max_compression_ratio`: 100.0
    /// - `max_solid_compression_ratio`: 1000.0
    /// - `max_file_count`: 10,000
    /// - `max_path_depth`: 32
    /// - `allowed`: All features disabled (deny-by-default)
    /// - `preserve_permissions`: false
    /// - `allowed_extensions`: empty (allow all)
    /// - `banned_path_components`: `[".git", ".ssh", ".gnupg", ".aws", ".kube",
    ///   ".docker", ".env"]`
    /// - `allow_solid_archives`: false (solid archives rejected)
    /// - `max_solid_block_memory`: 512 MB
    /// - `max_tar_metadata_bytes`: 4 MiB
    /// - `max_decoder_memory`: 256 MiB
    /// - `parallel_decode`: `Bounded` at 128 MiB
    /// - `zip_consistency`: `Enforce`
    fn default() -> Self {
        Self {
            fields: SecurityConfigFields::default(),
            _marker: PhantomData,
        }
    }
}

/// Lookahead memory of [`SecurityConfig::permissive`]: 1 GiB.
const PERMISSIVE_PARALLEL_DECODE: NonZeroU64 = non_zero(1024 * 1024 * 1024);

impl SecurityConfig<Unvalidated> {
    /// Creates a permissive configuration for trusted archives.
    ///
    /// This configuration allows symlinks, hardlinks, absolute paths, and
    /// solid archives. Use only when extracting archives from trusted sources.
    #[must_use]
    pub fn permissive() -> Self {
        Self {
            fields: SecurityConfigFields {
                allowed: AllowedFeatures {
                    symlinks: true,
                    hardlinks: true,
                    absolute_paths: true,
                    world_writable: true,
                    windows_reserved_names: false,
                },
                preserve_permissions: true,
                max_compression_ratio: 1000.0,
                max_solid_compression_ratio: 10_000.0,
                banned_path_components: Vec::new(),
                allow_solid_archives: true,
                max_solid_block_memory: 1024 * 1024 * 1024, // 1 GB for permissive
                max_tar_metadata_bytes: 16 * 1024 * 1024,   // 16 MiB for permissive
                max_decoder_memory: 1024 * 1024 * 1024,     // 1 GiB for permissive
                parallel_decode: ParallelDecode::Bounded(PERMISSIVE_PARALLEL_DECODE),
                ..SecurityConfigFields::default()
            },
            _marker: PhantomData,
        }
    }

    /// Validates that the configuration values are logically consistent,
    /// transitioning to the [`Validated`] typestate on success.
    ///
    /// Returns an error if any field has a value that would make security
    /// enforcement impossible (zero limits or non-positive ratio). Consumes
    /// `self`: the only way to obtain a `SecurityConfig<Validated>`, which is
    /// what every security-sensitive API in this crate requires. Once
    /// returned, the `Validated` config's fields can no longer be reassigned
    /// (see the "Sealing" section on the type-level docs), so this check can
    /// never be silently invalidated afterward.
    ///
    /// # Errors
    ///
    /// Returns `ArchiveError::InvalidConfiguration` if:
    /// - `max_compression_ratio` or `max_solid_compression_ratio` is not
    ///   positive and finite
    /// - `max_file_size` is zero
    /// - `max_total_size` is zero
    /// - `max_path_depth` is zero
    /// - `max_file_count` is zero
    /// - `max_solid_block_memory` is zero
    /// - `max_tar_metadata_bytes` is zero
    /// - `max_decoder_memory` is zero
    /// - any entry in `allowed_extensions` or `banned_path_components` is
    ///   empty, contains a null byte, or exceeds
    ///   [`crate::MAX_CONFIG_ENTRY_LENGTH`] bytes
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default();
    /// assert!(config.validate().is_ok());
    ///
    /// let bad = SecurityConfig::default().with_max_file_size(0);
    /// assert!(bad.validate().is_err());
    /// ```
    pub fn validate(self) -> crate::Result<SecurityConfig<Validated>> {
        if !self.max_compression_ratio.is_finite() || self.max_compression_ratio <= 0.0 {
            return Err(crate::ArchiveError::InvalidConfiguration {
                reason: "max_compression_ratio must be positive".into(),
            });
        }
        if !self.max_solid_compression_ratio.is_finite() || self.max_solid_compression_ratio <= 0.0
        {
            return Err(crate::ArchiveError::InvalidConfiguration {
                reason: "max_solid_compression_ratio must be positive".into(),
            });
        }
        if self.max_file_size == 0 {
            return Err(crate::ArchiveError::InvalidConfiguration {
                reason: "max_file_size must not be zero".into(),
            });
        }
        if self.max_total_size == 0 {
            return Err(crate::ArchiveError::InvalidConfiguration {
                reason: "max_total_size must not be zero".into(),
            });
        }
        if self.max_path_depth == 0 {
            return Err(crate::ArchiveError::InvalidConfiguration {
                reason: "max_path_depth must not be zero".into(),
            });
        }
        if self.max_file_count == 0 {
            return Err(crate::ArchiveError::InvalidConfiguration {
                reason: "max_file_count must not be zero".into(),
            });
        }
        if self.max_solid_block_memory == 0 {
            return Err(crate::ArchiveError::InvalidConfiguration {
                reason: "max_solid_block_memory must not be zero".into(),
            });
        }
        if self.max_tar_metadata_bytes == 0 {
            return Err(crate::ArchiveError::InvalidConfiguration {
                reason: "max_tar_metadata_bytes must not be zero".into(),
            });
        }
        if self.max_decoder_memory == 0 {
            return Err(crate::ArchiveError::InvalidConfiguration {
                reason: "max_decoder_memory must not be zero".into(),
            });
        }
        for extension in &self.fields.allowed_extensions {
            crate::security::boundary::validate_config_entry(extension, "allowed extension")?;
        }
        for component in &self.fields.banned_path_components {
            crate::security::boundary::validate_config_entry(component, "banned path component")?;
        }
        Ok(SecurityConfig {
            fields: self.fields,
            _marker: PhantomData,
        })
    }

    /// Sets the maximum size for a single extracted file in bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default().with_max_file_size(100 * 1024 * 1024);
    /// assert_eq!(config.max_file_size, 100 * 1024 * 1024);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_max_file_size(mut self, size: u64) -> Self {
        self.fields.max_file_size = size;
        self
    }

    /// Sets the maximum total size for all extracted files in bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default().with_max_total_size(1024 * 1024 * 1024);
    /// assert_eq!(config.max_total_size, 1024 * 1024 * 1024);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_max_total_size(mut self, size: u64) -> Self {
        self.fields.max_total_size = size;
        self
    }

    /// Sets the maximum allowed compression ratio (uncompressed / compressed).
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default().with_max_compression_ratio(50.0);
    /// assert_eq!(config.max_compression_ratio, 50.0);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_max_compression_ratio(mut self, ratio: f64) -> Self {
        self.fields.max_compression_ratio = ratio;
        self
    }

    /// Sets the maximum compression ratio of a whole solid 7z block.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default().with_max_solid_compression_ratio(5000.0);
    /// assert_eq!(config.max_solid_compression_ratio, 5000.0);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_max_solid_compression_ratio(mut self, ratio: f64) -> Self {
        self.fields.max_solid_compression_ratio = ratio;
        self
    }

    /// Sets the maximum number of files that can be extracted.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default().with_max_file_count(500);
    /// assert_eq!(config.max_file_count, 500);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_max_file_count(mut self, count: usize) -> Self {
        self.fields.max_file_count = count;
        self
    }

    /// Sets the maximum path depth allowed.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default().with_max_path_depth(16);
    /// assert_eq!(config.max_path_depth, 16);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_max_path_depth(mut self, depth: usize) -> Self {
        self.fields.max_path_depth = depth;
        self
    }

    /// Sets the feature flags controlling allowed archive features.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    /// use exarch_core::config::AllowedFeatures;
    ///
    /// let features = AllowedFeatures::default();
    /// let config = SecurityConfig::default().with_allowed(features);
    /// assert!(!config.allowed.symlinks);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_allowed(mut self, allowed: AllowedFeatures) -> Self {
        self.fields.allowed = allowed;
        self
    }

    /// Enables or disables symlinks in extracted archives.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default().with_allow_symlinks(true);
    /// assert!(config.allowed.symlinks);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_allow_symlinks(mut self, allow: bool) -> Self {
        self.fields.allowed.symlinks = allow;
        self
    }

    /// Enables or disables hardlinks in extracted archives.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default().with_allow_hardlinks(true);
    /// assert!(config.allowed.hardlinks);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_allow_hardlinks(mut self, allow: bool) -> Self {
        self.fields.allowed.hardlinks = allow;
        self
    }

    /// Enables or disables absolute paths in archive entries.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default().with_allow_absolute_paths(true);
    /// assert!(config.allowed.absolute_paths);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_allow_absolute_paths(mut self, allow: bool) -> Self {
        self.fields.allowed.absolute_paths = allow;
        self
    }

    /// Enables or disables world-writable files.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default().with_allow_world_writable(true);
    /// assert!(config.allowed.world_writable);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_allow_world_writable(mut self, allow: bool) -> Self {
        self.fields.allowed.world_writable = allow;
        self
    }

    /// Enables or disables Windows reserved device names (`CON`, `NUL`,
    /// `COM1`, ...) as path components. Only consulted on Windows.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default().with_allow_windows_reserved_names(true);
    /// assert!(config.allowed.windows_reserved_names);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_allow_windows_reserved_names(mut self, allow: bool) -> Self {
        self.fields.allowed.windows_reserved_names = allow;
        self
    }

    /// Enables or disables preserving file permissions from the archive.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default().with_preserve_permissions(true);
    /// assert!(config.preserve_permissions);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_preserve_permissions(mut self, preserve: bool) -> Self {
        self.fields.preserve_permissions = preserve;
        self
    }

    /// Sets the list of allowed file extensions.
    ///
    /// An empty list allows all extensions.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default()
    ///     .with_allowed_extensions(vec!["txt".to_string(), "pdf".to_string()]);
    /// assert!(config.is_extension_allowed("txt"));
    /// assert!(!config.is_extension_allowed("exe"));
    /// ```
    #[must_use]
    #[inline]
    pub fn with_allowed_extensions(mut self, extensions: Vec<String>) -> Self {
        self.fields.allowed_extensions = extensions;
        self
    }

    /// Sets the list of banned path components.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default().with_banned_path_components(vec![".git".to_string()]);
    /// assert!(!config.is_path_component_allowed(".git"));
    /// assert!(config.is_path_component_allowed(".ssh"));
    /// ```
    #[must_use]
    #[inline]
    pub fn with_banned_path_components(mut self, components: Vec<String>) -> Self {
        self.fields.banned_path_components = components;
        self
    }

    /// Enables or disables extraction from solid 7z archives.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default().with_allow_solid_archives(true);
    /// assert!(config.allow_solid_archives);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_allow_solid_archives(mut self, allow: bool) -> Self {
        self.fields.allow_solid_archives = allow;
        self
    }

    /// Sets the maximum memory for solid archive extraction in bytes.
    ///
    /// Only applies when `allow_solid_archives` is `true`.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default()
    ///     .with_allow_solid_archives(true)
    ///     .with_max_solid_block_memory(1024 * 1024 * 1024);
    /// assert_eq!(config.max_solid_block_memory, 1024 * 1024 * 1024);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_max_solid_block_memory(mut self, size: u64) -> Self {
        self.fields.max_solid_block_memory = size;
        self
    }

    /// Sets the maximum bytes the TAR reader may consume for headers and
    /// metadata records (GNU long-name/long-link, PAX extended headers, GNU
    /// sparse extension blocks) in the gap between two consecutive entries.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default().with_max_tar_metadata_bytes(64 * 1024);
    /// assert_eq!(config.max_tar_metadata_bytes, 64 * 1024);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_max_tar_metadata_bytes(mut self, size: u64) -> Self {
        self.fields.max_tar_metadata_bytes = size;
        self
    }

    /// Sets the maximum memory an xz decoder may use, in bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default().with_max_decoder_memory(64 * 1024 * 1024);
    /// assert_eq!(config.max_decoder_memory, 64 * 1024 * 1024);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_max_decoder_memory(mut self, size: u64) -> Self {
        self.fields.max_decoder_memory = size;
        self
    }

    /// Sets the lookahead memory for parallel 7z LZMA2 decoding.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::ParallelDecode;
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default().with_parallel_decode(ParallelDecode::Sequential);
    /// assert_eq!(config.parallel_decode, ParallelDecode::Sequential);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_parallel_decode(mut self, mode: ParallelDecode) -> Self {
        self.fields.parallel_decode = mode;
        self
    }

    /// Sets how ZIP archives with ambiguous structure are handled.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    /// use exarch_core::ZipConsistencyPolicy;
    ///
    /// let config = SecurityConfig::default().with_zip_consistency(ZipConsistencyPolicy::Ignore);
    /// assert_eq!(config.zip_consistency, ZipConsistencyPolicy::Ignore);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_zip_consistency(mut self, policy: ZipConsistencyPolicy) -> Self {
        self.fields.zip_consistency = policy;
        self
    }
}

/// Read-only queries and crate-internal helpers available regardless of
/// validation state.
impl<State> SecurityConfig<State> {
    /// Validates whether a path component is allowed.
    ///
    /// Comparison is case-insensitive to prevent bypass on case-insensitive
    /// filesystems (Windows, macOS default).
    #[must_use]
    pub fn is_path_component_allowed(&self, component: &str) -> bool {
        !self
            .banned_path_components
            .iter()
            .any(|banned| banned.eq_ignore_ascii_case(component))
    }

    /// Validates whether a file extension is allowed.
    ///
    /// When `allowed_extensions` is empty, all extensions are permitted.
    /// When it is non-empty, only listed extensions are permitted.
    #[must_use]
    pub fn is_extension_allowed(&self, extension: &str) -> bool {
        if self.allowed_extensions.is_empty() {
            return true;
        }
        self.allowed_extensions
            .iter()
            .any(|ext| ext.eq_ignore_ascii_case(extension))
    }

    /// Returns `true` if a file with the given optional extension may be
    /// extracted.
    ///
    /// When `allowed_extensions` is non-empty and `extension` is `None`
    /// (the file has no extension), the file is treated as not allowed.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SecurityConfig;
    ///
    /// let config = SecurityConfig::default().with_allowed_extensions(vec!["txt".to_string()]);
    ///
    /// assert!(config.is_path_extension_allowed(Some("txt")));
    /// assert!(!config.is_path_extension_allowed(Some("exe")));
    /// // Files without an extension are blocked when the allowlist is non-empty.
    /// assert!(!config.is_path_extension_allowed(None));
    ///
    /// // Empty allowlist permits everything, including extension-less files.
    /// let permissive = SecurityConfig::default();
    /// assert!(permissive.is_path_extension_allowed(None));
    /// ```
    #[must_use]
    pub fn is_path_extension_allowed(&self, extension: Option<&str>) -> bool {
        if self.allowed_extensions.is_empty() {
            return true;
        }
        extension.is_some_and(|ext| self.is_extension_allowed(ext))
    }
}

/// Options controlling extraction behavior (non-security).
///
/// Separate from `SecurityConfig` to keep security settings focused.
/// These options control operational behavior like atomicity.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ExtractionOptions {
    /// Extract atomically: use a temp dir in the same parent as the output
    /// directory, rename on success, and delete on failure.
    ///
    /// When enabled, extraction is all-or-nothing: if extraction fails,
    /// the output directory will not be created. This prevents partial
    /// extraction artifacts from remaining on disk.
    ///
    /// Note: cleanup is best-effort if the process is terminated via SIGKILL.
    pub atomic: bool,

    /// Skip duplicate entries silently instead of aborting.
    ///
    /// When `true` (default), if an archive contains two entries with the same
    /// destination path, the second entry is skipped and a warning is recorded
    /// in `ExtractionReport`. When `false`, duplicate entries cause an error.
    pub skip_duplicates: bool,
}

impl Default for ExtractionOptions {
    fn default() -> Self {
        Self {
            atomic: false,
            skip_duplicates: true,
        }
    }
}

impl ExtractionOptions {
    /// Enables or disables atomic extraction.
    ///
    /// When enabled, extraction is all-or-nothing: the output directory is not
    /// created if extraction fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::ExtractionOptions;
    ///
    /// let opts = ExtractionOptions::default().with_atomic(true);
    /// assert!(opts.atomic);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_atomic(mut self, atomic: bool) -> Self {
        self.atomic = atomic;
        self
    }

    /// Enables or disables skipping duplicate entries silently.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::ExtractionOptions;
    ///
    /// let opts = ExtractionOptions::default().with_skip_duplicates(false);
    /// assert!(!opts.skip_duplicates);
    /// ```
    #[must_use]
    #[inline]
    pub fn with_skip_duplicates(mut self, skip: bool) -> Self {
        self.skip_duplicates = skip;
        self
    }
}

/// Upper bound on the bytes `verify` decodes to check payload integrity.
///
/// The budget bounds the work done **beyond what listing already does**: ZIP
/// entries and 7z blocks are charged their declared uncompressed size before
/// they are decoded, and for compressed TAR it bounds the read from the end
/// marker to decoder EOF. TAR entry content is never charged because listing
/// decodes it anyway. The default is a fixed 500 MiB, equal to the default
/// `max_total_size`; it does not follow a raised `max_total_size`.
///
/// # Examples
///
/// ```
/// use exarch_core::DecompressionBudget;
///
/// assert!(DecompressionBudget::try_from_bytes(0).is_err());
/// let budget = DecompressionBudget::try_from_bytes(1024)?;
/// assert_eq!(budget.get(), 1024);
/// assert_eq!(DecompressionBudget::default(), DecompressionBudget::DEFAULT);
/// # Ok::<(), exarch_core::ArchiveError>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DecompressionBudget(std::num::NonZeroU64);

impl DecompressionBudget {
    /// The default budget: 500 MiB.
    pub const DEFAULT: Self = match std::num::NonZeroU64::new(500 * 1024 * 1024) {
        Some(bytes) => Self(bytes),
        None => unreachable!(),
    };

    /// Creates a budget from a non-zero byte count.
    #[must_use]
    pub const fn new(bytes: std::num::NonZeroU64) -> Self {
        Self(bytes)
    }

    /// Creates a budget from a byte count.
    ///
    /// # Errors
    ///
    /// Returns [`ArchiveError::InvalidConfiguration`](crate::ArchiveError) when
    /// `bytes` is zero.
    pub fn try_from_bytes(bytes: u64) -> crate::Result<Self> {
        std::num::NonZeroU64::new(bytes).map(Self).ok_or_else(|| {
            crate::ArchiveError::InvalidConfiguration {
                reason: "decompression budget must be greater than zero".into(),
            }
        })
    }

    /// Returns the budget in bytes.
    #[must_use]
    pub const fn get(self) -> u64 {
        self.0.get()
    }
}

impl Default for DecompressionBudget {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// Whether `verify` checks payload integrity.
///
/// A budget without the check is unrepresentable: the budget lives inside the
/// [`DecodeToEof`](Self::DecodeToEof) variant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum IntegrityCheck {
    /// Metadata-only verification (the default).
    #[default]
    Skip,

    /// Decode payload to the decoder's EOF so checksums and codec framing are
    /// verified, spending at most the given budget on extra decoding.
    DecodeToEof(DecompressionBudget),
}

/// Options controlling `verify` behavior.
///
/// # Examples
///
/// ```
/// use exarch_core::DecompressionBudget;
/// use exarch_core::IntegrityCheck;
/// use exarch_core::VerificationOptions;
///
/// let options = VerificationOptions::default();
/// assert_eq!(options.integrity, IntegrityCheck::Skip);
///
/// let options = options.with_integrity(IntegrityCheck::DecodeToEof(DecompressionBudget::DEFAULT));
/// assert_ne!(options.integrity, IntegrityCheck::Skip);
/// ```
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct VerificationOptions {
    /// Payload integrity check mode.
    pub integrity: IntegrityCheck,
}

impl VerificationOptions {
    /// Sets the payload integrity check mode.
    #[must_use]
    pub fn with_integrity(mut self, integrity: IntegrityCheck) -> Self {
        self.integrity = integrity;
        self
    }
}

/// Whether listing reads the symlink targets a format keeps in compressed
/// entry data.
///
/// 7z keeps link targets in compressed entry data, so reading them decodes
/// part of the archive, which in a solid block can be most of it. Listing
/// therefore skips them by default. Other formats always report their targets:
/// TAR keeps them in headers, and ZIP reads them from a small local entry. This
/// is a Rust API option only; the Python and Node `list_archive` skip 7z
/// targets.
///
/// # Examples
///
/// ```
/// use exarch_core::StoredTargets;
///
/// assert_eq!(StoredTargets::default(), StoredTargets::Skip);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum StoredTargets {
    /// Leave 7z link targets unread, so listing decodes no entry data (the
    /// default).
    #[default]
    Skip,

    /// Read the targets, decoding the blocks that hold them.
    Read,
}

/// Options controlling `list` behavior.
///
/// # Examples
///
/// ```
/// use exarch_core::ListOptions;
/// use exarch_core::StoredTargets;
///
/// let options = ListOptions::default();
/// assert_eq!(options.stored_targets, StoredTargets::Skip);
///
/// let options = options.with_stored_targets(StoredTargets::Read);
/// assert_eq!(options.stored_targets, StoredTargets::Read);
/// ```
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct ListOptions {
    /// Whether to read the link targets a format keeps in entry data.
    pub stored_targets: StoredTargets,
}

impl ListOptions {
    /// Sets whether link targets kept in entry data are read.
    #[must_use]
    pub fn with_stored_targets(mut self, stored_targets: StoredTargets) -> Self {
        self.stored_targets = stored_targets;
        self
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::field_reassign_with_default
)]
mod tests {
    use super::*;

    #[test]
    fn test_default_config() {
        let config = SecurityConfig::default();
        assert!(!config.allowed.symlinks);
        assert!(!config.allowed.hardlinks);
        assert!(!config.allowed.absolute_paths);
        assert_eq!(config.max_file_size, 50 * 1024 * 1024);
    }

    #[test]
    fn test_permissive_config() {
        let config = SecurityConfig::permissive();
        assert!(config.allowed.symlinks);
        assert!(config.allowed.hardlinks);
        assert!(config.allowed.absolute_paths);
    }

    #[test]
    fn test_extension_allowed_empty_list() {
        let config = SecurityConfig::default();
        assert!(config.is_extension_allowed("txt"));
        assert!(config.is_extension_allowed("pdf"));
    }

    #[test]
    fn test_extension_allowed_with_list() {
        let mut config = SecurityConfig::default();
        config.allowed_extensions = vec!["txt".to_string(), "pdf".to_string()];
        assert!(config.is_extension_allowed("txt"));
        assert!(config.is_extension_allowed("TXT"));
        assert!(!config.is_extension_allowed("exe"));
    }

    #[test]
    fn test_path_component_allowed() {
        let config = SecurityConfig::default();
        assert!(config.is_path_component_allowed("src"));
        assert!(!config.is_path_component_allowed(".git"));
        assert!(!config.is_path_component_allowed(".ssh"));

        // Case-insensitive matching prevents bypass
        assert!(!config.is_path_component_allowed(".Git"));
        assert!(!config.is_path_component_allowed(".GIT"));
        assert!(!config.is_path_component_allowed(".SSH"));
        assert!(!config.is_path_component_allowed(".Gnupg"));
    }

    // M-TEST-3: Config field validation
    #[test]
    fn test_config_default_security_flags() {
        let config = SecurityConfig::default();

        // All security-sensitive flags should be false by default
        // (deny-by-default)
        assert!(
            !config.allowed.symlinks,
            "symlinks should be denied by default"
        );
        assert!(
            !config.allowed.hardlinks,
            "hardlinks should be denied by default"
        );
        assert!(
            !config.allowed.absolute_paths,
            "absolute paths should be denied by default"
        );
        assert!(
            !config.preserve_permissions,
            "permissions should not be preserved by default"
        );
        assert!(
            !config.allowed.world_writable,
            "world-writable should be denied by default"
        );
    }

    #[test]
    fn test_config_permissive_security_flags() {
        let config = SecurityConfig::permissive();

        // Permissive config should allow all features
        assert!(config.allowed.symlinks, "permissive allows symlinks");
        assert!(config.allowed.hardlinks, "permissive allows hardlinks");
        assert!(
            config.allowed.absolute_paths,
            "permissive allows absolute paths"
        );
        assert!(
            config.preserve_permissions,
            "permissive preserves permissions"
        );
        assert!(
            config.allowed.world_writable,
            "permissive allows world-writable"
        );
    }

    #[test]
    fn test_config_quota_limits() {
        let config = SecurityConfig::default();

        // Verify default quota values are sensible
        assert_eq!(config.max_file_size, 50 * 1024 * 1024, "50 MB file limit");
        assert_eq!(
            config.max_total_size,
            500 * 1024 * 1024,
            "500 MB total limit"
        );
        assert_eq!(config.max_file_count, 10_000, "10k file count limit");
        assert_eq!(config.max_path_depth, 32, "32 level depth limit");
        #[allow(clippy::float_cmp)]
        {
            assert_eq!(
                config.max_compression_ratio, 100.0,
                "100x compression ratio limit"
            );
        }
    }

    #[test]
    fn test_config_banned_components_not_empty() {
        let config = SecurityConfig::default();

        // Default should ban common sensitive directories
        assert!(
            !config.banned_path_components.is_empty(),
            "should have banned components by default"
        );
        assert!(
            config.banned_path_components.contains(&".git".to_string()),
            "should ban .git"
        );
        assert!(
            config.banned_path_components.contains(&".ssh".to_string()),
            "should ban .ssh"
        );
    }

    #[test]
    fn test_config_solid_archives_default() {
        let config = SecurityConfig::default();

        // Solid archives should be denied by default (security)
        assert!(
            !config.allow_solid_archives,
            "solid archives should be denied by default"
        );
        assert_eq!(
            config.max_solid_block_memory,
            512 * 1024 * 1024,
            "max solid block memory should be 512 MB"
        );
    }

    #[test]
    fn test_config_permissive_solid_archives() {
        let config = SecurityConfig::permissive();

        // Permissive config should allow solid archives
        assert!(
            config.allow_solid_archives,
            "permissive config should allow solid archives"
        );
        assert_eq!(
            config.max_solid_block_memory,
            1024 * 1024 * 1024,
            "permissive should have 1 GB solid block limit"
        );
    }

    #[test]
    fn test_config_tar_metadata_bytes_default() {
        let config = SecurityConfig::default();
        assert_eq!(
            config.max_tar_metadata_bytes,
            4 * 1024 * 1024,
            "max TAR metadata bytes should be 4 MiB by default"
        );
    }

    #[test]
    fn test_config_permissive_tar_metadata_bytes() {
        let config = SecurityConfig::permissive();
        assert_eq!(
            config.max_tar_metadata_bytes,
            16 * 1024 * 1024,
            "permissive should have 16 MiB TAR metadata budget"
        );
    }

    #[test]
    fn test_with_max_tar_metadata_bytes_builder() {
        let config = SecurityConfig::default().with_max_tar_metadata_bytes(2048);
        assert_eq!(config.max_tar_metadata_bytes, 2048);
    }

    // Regression tests for #172: SecurityConfig::validate() must reject configs
    // that would make security enforcement impossible.

    #[test]
    fn test_validate_default_is_ok() {
        assert!(SecurityConfig::default().validate().is_ok());
    }

    #[test]
    fn test_validate_rejects_negative_compression_ratio() {
        let mut cfg = SecurityConfig::default();
        cfg.max_compression_ratio = -1.0;
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_validate_rejects_zero_compression_ratio() {
        let mut cfg = SecurityConfig::default();
        cfg.max_compression_ratio = 0.0;
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_validate_rejects_invalid_solid_compression_ratio() {
        for ratio in [0.0, -1.0, f64::NAN, f64::INFINITY] {
            let mut cfg = SecurityConfig::default();
            cfg.max_solid_compression_ratio = ratio;
            assert!(cfg.validate().is_err(), "{ratio} must be rejected");
        }
    }

    #[test]
    fn test_solid_compression_ratio_defaults() {
        assert_eq!(
            SecurityConfig::default().max_solid_compression_ratio,
            1000.0
        );
        assert_eq!(
            SecurityConfig::permissive().max_solid_compression_ratio,
            10_000.0
        );
    }

    #[test]
    fn test_validate_rejects_zero_max_file_size() {
        let mut cfg = SecurityConfig::default();
        cfg.max_file_size = 0;
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_validate_rejects_zero_max_total_size() {
        let mut cfg = SecurityConfig::default();
        cfg.max_total_size = 0;
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_validate_rejects_zero_max_path_depth() {
        let mut cfg = SecurityConfig::default();
        cfg.max_path_depth = 0;
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_validate_rejects_nan_compression_ratio() {
        let mut cfg = SecurityConfig::default();
        cfg.max_compression_ratio = f64::NAN;
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_validate_rejects_infinite_compression_ratio() {
        let mut cfg = SecurityConfig::default();
        cfg.max_compression_ratio = f64::INFINITY;
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_validate_rejects_zero_max_file_count() {
        let mut cfg = SecurityConfig::default();
        cfg.max_file_count = 0;
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_validate_rejects_zero_max_solid_block_memory() {
        let mut cfg = SecurityConfig::default();
        cfg.max_solid_block_memory = 0;
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_validate_rejects_zero_max_tar_metadata_bytes() {
        let mut cfg = SecurityConfig::default();
        cfg.max_tar_metadata_bytes = 0;
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_validate_rejects_zero_max_decoder_memory() {
        let mut cfg = SecurityConfig::default();
        cfg.max_decoder_memory = 0;
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_parallel_decode_defaults() {
        let bytes = |config: SecurityConfig| match config.parallel_decode {
            ParallelDecode::Bounded(n) => n.get(),
            ParallelDecode::Sequential => 0,
        };
        assert_eq!(bytes(SecurityConfig::default()), 128 * 1024 * 1024);
        assert_eq!(bytes(SecurityConfig::permissive()), 1024 * 1024 * 1024);
    }

    #[test]
    fn test_max_decoder_memory_defaults() {
        assert_eq!(
            SecurityConfig::default().max_decoder_memory,
            256 * 1024 * 1024
        );
        assert_eq!(
            SecurityConfig::permissive().max_decoder_memory,
            1024 * 1024 * 1024
        );
    }

    // Regression tests for #449: SecurityConfig::validate() must reject
    // malformed allowed_extensions/banned_path_components entries.

    #[test]
    fn test_validate_permissive_is_ok() {
        assert!(SecurityConfig::permissive().validate().is_ok());
    }

    #[test]
    fn test_validate_accepts_empty_allowed_extensions_vec() {
        let cfg = SecurityConfig::default().with_allowed_extensions(Vec::new());
        assert!(cfg.validate().is_ok());
    }

    #[test]
    fn test_validate_rejects_empty_allowed_extension_entry() {
        let cfg = SecurityConfig::default().with_allowed_extensions(vec![String::new()]);
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_validate_rejects_empty_banned_path_component_entry() {
        let cfg = SecurityConfig::default().with_banned_path_components(vec![String::new()]);
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_validate_rejects_null_byte_in_allowed_extension() {
        let cfg = SecurityConfig::default().with_allowed_extensions(vec!["bad\0ext".to_string()]);
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_validate_rejects_overlong_banned_path_component() {
        let long_component = "x".repeat(256);
        let cfg = SecurityConfig::default().with_banned_path_components(vec![long_component]);
        assert!(cfg.validate().is_err());
    }

    // Regression test for the C1 finding on #433/#434/#435: a
    // `SecurityConfig<Validated>` must not be mutable. `DerefMut` is only
    // implemented for `SecurityConfig<Unvalidated>`, so this is enforced at
    // compile time — see `tests/ui/validated_config_field_mutation.rs` for
    // the corresponding compile-fail fixture. This test only pins the
    // read-side behavior: fields remain readable after validation.
    #[test]
    fn test_validated_config_fields_remain_readable() {
        let validated = SecurityConfig::default()
            .with_max_file_size(123)
            .validate()
            .expect("valid config");
        assert_eq!(validated.max_file_size, 123);
    }
}