exarch-core 0.9.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
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
//! Bounds bytes the `tar` crate may read while searching for the next entry.
//!
//! # Background
//!
//! GNU long-name (`L`), GNU long-link (`K`), and PAX extended header (`x`/`g`)
//! records are read fully into memory by the `tar` crate's `Entries::next()`
//! (via `EntryFields::read_all()`) *before* any entry reaches the entry
//! validator or quota tracker. A crafted record declaring a multi-gigabyte
//! length backed by a tiny compressed stream causes unbounded allocation with
//! no quota enforcement (issue #414).
//!
//! An earlier fix re-parsed TAR headers in a shadow parser to reject an
//! oversized metadata record before the `tar` crate could buffer it. That
//! approach was abandoned after three rounds of adversarial review each found
//! a fresh case where the shadow parser's belief about entry framing
//! diverged from the `tar` crate's own (untracked PAX `size=` overrides,
//! typeflag-without-magic-gate framing, and a PAX global header draining
//! `tar`'s override state without draining the mirror's). Three independent
//! divergences in three rounds is a structural problem with maintaining a
//! second parser, not a fixable oversight.
//!
//! # Design: a read budget, not a second parser
//!
//! [`BudgetedReader`] never looks at a header, a typeflag, magic bytes, or a
//! PAX record. It only counts bytes, and it is told when to start/stop
//! counting by the `tar` crate's own iterator boundary — via [`TarReadBudget`]
//! ([`arm`](TarReadBudget::arm)/[`disarm`](TarReadBudget::disarm)), driven by
//! [`BudgetedEntries::next_entry`]. The invariant enforced:
//!
//! > Between the moment iteration asks for the next entry and the moment
//! > `tar` yields one, `tar` may read at most `limit` bytes from the
//! > underlying reader.
//!
//! That window contains exactly: sub-block padding, the `L`/`K`/`x` metadata
//! headers and bodies `tar` buffers via `read_all`, GNU sparse extension
//! blocks, and the final entry header. It contains *no* entry data, because
//! every yielded entry is fully drained — via [`TarEntryGuard`]'s `Drop` —
//! before the next iteration step. So the budget is a pure constant: no
//! declared size, from any header, ever feeds it. There is exactly one
//! parser (the `tar` crate's own), so there is nothing for a shadow parser to
//! disagree with.
//!
//! The drain must run to true completion for a *legitimate* unread entry —
//! `list`/`verify` never read entry content at all, so the drain is the
//! *only* thing that consumes a legitimate entry's real bytes to reach the
//! next header, no matter how large that entry is (`verify` in particular
//! lifts the per-file size limit precisely so a metadata-only listing
//! does not reject large files). A fixed cap on *total drained output* —
//! however generous — therefore either (a) truncates real bytes of some
//! legitimate large entry, misaligning the next header read and rejecting an
//! ordinary archive with a scary `SecurityViolation`, or (b) is raised high
//! enough to avoid that and stops bounding anything, since a GNU sparse
//! entry's synthesized zero-padding (`tar` allocates no backing bytes for
//! sparse gaps) can be driven past any fixed number via a `realsize` field up
//! to `u64::MAX`. An earlier version of this fix picked option (a) at
//! different fixed caps and was broken both ways in succession (issue #414's
//! C2/C3 findings) before this module was corrected to the design below.
//!
//! **The drain is bounded by *synthesized* bytes, not total output.** A
//! legitimate regular entry's drain consumes real bytes from the underlying
//! reader 1:1 with what it outputs — reading further only produces more
//! output if the reader actually had more to give. GNU sparse padding is the
//! opposite: `tar` yields it from `io::repeat(0)`, producing output with
//! **zero** corresponding reads from the underlying reader. [`BudgetedReader`]
//! tracks a monotonic, never-reset `total_read` count of bytes actually
//! delivered from `inner`, armed or disarmed; [`TarEntryGuard::drop`] drains
//! in a loop tracking `synthetic = output_so_far -
//! bytes_actually_read_during_this_drain` and stops once `synthetic` exceeds
//! [`SYNTHETIC_PAD_CAP_BYTES`]. A legitimate entry's `synthetic` stays at (or
//! within a chunk-size rounding of) zero regardless of how large the entry is,
//! so it always drains fully; a sparse bomb's `synthetic` grows by a full
//! read-chunk on every iteration once padding starts, tripping the cap almost
//! immediately regardless of how large the declared `realsize` is. This
//! distinguishes the two purely by *where the bytes came from*, never by
//! inspecting a header field.
//!
//! One known residual limitation, accepted (P3, tracked as a follow-up
//! issue) rather than fixed here: a *legitimate* GNU sparse file with real
//! holes larger than [`SYNTHETIC_PAD_CAP_BYTES`] (e.g. a multi-gigabyte
//! sparse disk image, mostly zero-filled) looks identical to an attack from
//! this module's perspective when such a file is skipped unread — both
//! produce output with no corresponding read. This affects `list_archive`
//! and `verify_archive` unconditionally (neither reads entry content at all,
//! so *every* entry hits this), and affects `extract_archive`/
//! `TarArchive::extract` whenever any pre-read skip causes the entry not to
//! be read at all — currently two such paths: a `SecurityConfig` extension
//! allowlist rejecting the entry (`ValidatorCore::screen_file_path_in`, see the
//! "Cumulative synthetic-byte budget" section below) and `skip_duplicates`
//! finding the destination path already exists
//! (`common::extract_file_with_permit`, `formats/common.rs`) — both return
//! before the entry's content is ever read. Only an extract call that
//! actually reads the entry (no pre-read skip of any kind) is unaffected,
//! since the guard's drain then finds nothing left to do.
//! [`CUMULATIVE_SYNTHETIC_CAP_BYTES`] below widens this same limitation
//! across entries: an archive containing more than roughly a hundred such
//! large-hole sparse entries, skipped unread by any of the paths above, is
//! now also rejected, not just a single oversized one.
//!
//! # Cumulative synthetic-byte budget (issue #422)
//!
//! [`SYNTHETIC_PAD_CAP_BYTES`] bounds the drain cost of any *single* unread
//! entry, but a caller with an extension allowlist configured
//! (`ValidatorCore::screen_file_path_in`) skips disallowed entries *before*
//! `QuotaTracker` ever sees them (intentional — see PR #421, which moved the
//! check there specifically to stop quota from double-counting files that
//! end up skipped); `skip_duplicates` skips an already-extracted path after
//! quota has run but still before the entry is read
//! (`common::extract_file_with_permit`); and `list_archive`/`verify_archive`
//! skip *every* entry unconditionally regardless of any allowlist.
//! `max_total_size`/`max_file_count` therefore provide no cumulative bound
//! across many such skips: an archive of many small GNU sparse entries, each
//! individually capped, could still sum to an arbitrarily large amount of
//! wasted drain work.
//!
//! [`TarReadBudget`] closes this with a second counter — `cumulative_synthetic`
//! on [`BudgetState`], summed across every [`TarEntryGuard::drop`] for the
//! lifetime of one `TarReadBudget` (i.e. one archive-open operation) — capped
//! at [`CUMULATIVE_SYNTHETIC_CAP_BYTES`]. [`BudgetedEntries::next_entry`]
//! checks it before asking `tar` for the next entry, so a caller that keeps
//! skipping synthetic-heavy entries fails fast on the next iteration rather
//! than continuing to drain. Because the check lives in `next_entry` (used by
//! `extract`, `list`, and — via `list` — `verify` alike), it applies
//! uniformly regardless of extension-filter ordering — at the cost of the
//! widened residual limitation described above.
//!
//! # Invariant: this module must never peek at archive content
//!
//! The one thing this module does with the bytes is copy them: while armed,
//! [`BudgetedReader`] appends every byte it delivers to a window that
//! [`TarEntryGuard::check`] hands to `tar_extension_headers`, which verifies it
//! against the framing `tar` itself reported. The copy is never interpreted
//! here, and `tar` stays the only authority on where entries begin and end.
//!
//! Nothing in this file reads a typeflag, checks magic bytes, or tracks a PAX
//! record — not even for a read-only "sanity check" or a diagnostic message.
//! That absence is not an implementation gap; it is the entire reason the
//! S1/S2/S3 bug class (three independent shadow-parser/`tar`-parser framing
//! disagreements, found in three separate rounds of adversarial review)
//! cannot recur here. **If a future change to this module adds any code path
//! that inspects header bytes to make a decision — even something as
//! innocuous-looking as "skip the budget check for typeflag `'g'`" or "trust
//! the declared size when it looks sane" — it reintroduces a second parser,
//! and with it the exact vulnerability class this redesign replaced.** Any
//! change that appears to need header awareness should be treated as a sign
//! the change belongs somewhere else (e.g. `EntryValidator`, which runs after
//! an entry is already fully framed by `tar` itself), not as a reason to add
//! a peek here.

use std::convert::Infallible;
use std::io;
use std::io::Read;
use std::marker::PhantomData;
use std::num::NonZeroU64;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::sync::PoisonError;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;

use super::source_fault::TapSource;
use super::tar_extension_headers::PrecedingEntry;
use super::tar_extension_headers::check_entry_headers;
use super::tar_extension_headers::check_trailing_headers;
use crate::Limit;
use crate::Result;
use crate::SecurityConfig;
use crate::Violation;
use crate::ZipBombDetails;
use crate::ZipBombScope;
use crate::error::violation::fmt_tar_read_budget;
use crate::error::violation::fmt_tar_synthetic_budget;
use crate::security::Compressed;
use crate::security::Uncompressed;

/// Hard, non-configurable ceiling on how many *synthesized* bytes (drained
/// output with no corresponding read from the underlying reader)
/// [`TarEntryGuard::drop`] will tolerate before giving up on a drain.
///
/// This is **not** a cap on total drained output — a legitimate entry drains
/// fully regardless of size, since its output tracks real reads 1:1 and never
/// accumulates synthetic bytes. Only a run of GNU sparse zero-padding (or
/// anything else that yields output without a corresponding read) can push
/// `synthetic` past this. A few MiB is ample: real padding-heavy input trips
/// it within a handful of read-chunk iterations, while it is never reached at
/// all by 1:1 content.
const SYNTHETIC_PAD_CAP_BYTES: u64 = 8 * 1024 * 1024;

/// Hard, non-configurable ceiling on the *sum* of every entry's synthesized-
/// byte drain (see [`SYNTHETIC_PAD_CAP_BYTES`]) across a single archive-open
/// operation — i.e. the lifetime of one [`TarReadBudget`] handle, shared by
/// every [`TarEntryGuard`] it produces.
///
/// [`SYNTHETIC_PAD_CAP_BYTES`] alone bounds the cost of any one unread entry,
/// not the *count* of such entries — a caller with an extension allowlist
/// skips disallowed entries before `QuotaTracker` runs (issue #422), and
/// `list_archive`/`verify_archive` skip every entry unconditionally (they
/// never read entry content at all), so nothing else previously capped how
/// many synthetic-heavy entries an archive could contain.
///
/// Calibrated generously, not tightly: every entry that individually
/// saturates `SYNTHETIC_PAD_CAP_BYTES` — attack or legitimate large-hole
/// sparse file alike, since this module cannot tell the two apart by design
/// (see the module's residual-limitation docs) — consumes a full
/// `SYNTHETIC_PAD_CAP_BYTES` (8 MiB) of this budget. At 1 GiB, that is
/// roughly 128 such maximally-saturating entries (`1 GiB / 8 MiB`) before
/// this trips: generous headroom for a real archive holding dozens of large
/// sparse files, while still bounding the worst case to a fixed, small
/// amount of wasted `io::sink` throughput — well under a second even at the
/// cap (see `cumulative_synthetic_budget_trips_on_many_maximally_saturating_entries`
/// in this module's tests) — no matter how many more entries an attacker
/// piles on beyond that. The reported attack (a ~20 MB archive of 20,000
/// small sparse entries, issue #422) took ~1.4 s to fully drain with no
/// cumulative bound at all; this caps the equivalent cost near what ~128
/// entries would cost, regardless of how many entries the archive actually
/// contains. An earlier version of this constant used `8 *
/// SYNTHETIC_PAD_CAP_BYTES` (64 MiB); adversarial review found that gave
/// legitimate multi-entry sparse archives only 8 entries of headroom before
/// false-positiving, while raising the cap all the way to 1 GiB only adds
/// single-digit milliseconds to the worst case relative to the reported
/// attack's own baseline.
const CUMULATIVE_SYNTHETIC_CAP_BYTES: u64 = 1024 * 1024 * 1024;

/// Chunk size for the drain loop in [`TarEntryGuard::drop`]. Not a security
/// boundary — just an I/O granularity choice, small enough to keep the
/// worst-case overshoot past [`SYNTHETIC_PAD_CAP_BYTES`] negligible.
const DRAIN_CHUNK_BYTES: usize = 8192;

/// Sentinel `allowance` value meaning "disarmed" (no cap on reads).
const DISARMED: u64 = 0;

/// Shared, atomics-only state behind [`TarReadBudget`] and [`BudgetedReader`].
///
/// `Send + Sync` by construction (no `Rc`/`Cell`), so the read wrapper can
/// cross thread boundaries the same way the reader it wraps already can —
/// required by the Node.js binding's blocking-thread-pool usage.
struct BudgetState {
    /// The configured per-window byte limit; re-applied on every `arm()`.
    limit: NonZeroU64,
    /// The raw input behind the reader, when core metered it.
    source: TapSource,
    /// Sum of the declared sizes of every entry drained without a quota
    /// charge (see [`CheckedTarEntry::drain_skipped`]).
    skipped_declared: AtomicU64,
    /// Decoded bytes read from skipped entries under the ratio bound.
    skipped_decoded: AtomicU64,
    /// Whether the reader currently meters the payload of a skipped entry
    /// against `skip_limits`. Set by [`CheckedTarEntry::mark_skipped`], cleared
    /// by [`BudgetedEntries::next_entry`], the single reset point.
    metering: AtomicBool,
    /// The limits of the skipped-entry meter; identical for the whole archive.
    skip_limits: OnceLock<SkipLimits>,
    /// The bound the meter tripped on. Sticky: once set, `next_entry` refuses
    /// to go on.
    skip_trip: OnceLock<ZipBombDetails>,
    /// Set once an entry guard was abandoned: the stream may be mid-entry, so
    /// no further entry may be read.
    abandoned: AtomicBool,
    /// Bytes delivered through this reader since the most recent `arm()`.
    consumed: AtomicU64,
    /// `DISARMED`, or the number of bytes still allowed before the next
    /// `read()` must fail. Armed **from construction** (fail-closed): a call
    /// site that forgets to pair a `BudgetedReader` with `BudgetedEntries`
    /// trips on the very first read of real entry content instead of running
    /// unprotected.
    allowance: AtomicU64,
    /// Monotonic count of bytes actually read from the underlying reader,
    /// armed or disarmed alike — never reset by `arm()`/`disarm()`. Lets
    /// [`TarEntryGuard::drop`] distinguish real archive bytes from
    /// synthesized padding during its drain, regardless of the metered
    /// window's own state at the time.
    total_read: AtomicU64,
    /// Running sum of every [`TarEntryGuard::drop`]'s own synthesized-byte
    /// count, across the whole lifetime of this state (i.e. one archive-open
    /// operation) — never reset. Checked against
    /// [`CUMULATIVE_SYNTHETIC_CAP_BYTES`] in
    /// [`BudgetedEntries::next_entry`].
    cumulative_synthetic: AtomicU64,
    /// Copy of every byte delivered while armed, cleared by `arm()`. Bounded
    /// by `limit` because a read past it fails. Recorded only, never
    /// interpreted here.
    window: Mutex<Vec<u8>>,
    /// Whether the last checked entry was a global PAX header; accessed only
    /// through [`TarReadBudget::preceding`].
    after_global: AtomicBool,
}

impl BudgetState {
    fn record(&self, bytes: &[u8]) {
        self.window
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .extend_from_slice(bytes);
    }

    /// Raw archive bytes consumed so far; under an [`TapSource::Opaque`] or
    /// [`TapSource::Replay`] source this is the decoded byte count, so a
    /// decoded/consumed ratio is about one and never exceeds any ratio limit.
    fn source_consumed(&self) -> u64 {
        match &self.source {
            TapSource::Tapped(tap) => tap.consumed(),
            TapSource::Opaque | TapSource::Replay(_) => self.total_read.load(Ordering::Relaxed),
        }
    }

    /// Charges the `n` bytes just read to the skipped-entry meter while it is
    /// on, failing the read that crosses the bound.
    fn meter_skipped(&self, n: usize) -> io::Result<()> {
        if !self.metering.load(Ordering::Relaxed) {
            return Ok(());
        }
        let Some(limits) = self.skip_limits.get() else {
            return Ok(());
        };
        let decoded = saturating_add_counter(&self.skipped_decoded, n as u64);
        let consumed = self.source_consumed();
        if decoded <= limits.allowance(consumed) {
            return Ok(());
        }
        let details = ZipBombDetails::new(
            ZipBombScope::SkippedEntries,
            Compressed(consumed),
            Uncompressed(decoded),
        );
        self.metering.store(false, Ordering::Relaxed);
        let _ = self.skip_trip.set(details);
        Err(io::Error::new(
            io::ErrorKind::InvalidData,
            SkippedEntriesExceeded(details),
        ))
    }
}

/// Cheap, cloneable handle used to arm/disarm the budget around the gap
/// between two yielded TAR entries.
///
/// Obtained together with a [`BudgetedReader`] from [`budgeted_reader_with`];
/// both must wrap the *same* underlying reader passed to the *same*
/// [`BudgetedEntries`] for the invariant to hold.
#[derive(Clone)]
pub struct TarReadBudget(Arc<BudgetState>);

impl TarReadBudget {
    /// Starts (or restarts) counting: `consumed = 0`, `allowance = limit`.
    fn arm(&self) {
        self.0
            .window
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clear();
        self.0.consumed.store(0, Ordering::Relaxed);
        self.0
            .allowance
            .store(self.0.limit.get(), Ordering::Relaxed);
    }

    /// Stops counting: subsequent reads pass through unmetered until the next
    /// `arm()`. Called once `tar` has yielded an entry — reading that
    /// entry's *own* data must never count against the metadata budget.
    fn disarm(&self) {
        self.0.allowance.store(DISARMED, Ordering::Relaxed);
    }

    /// Hands out the bytes recorded since the last `arm()`.
    ///
    /// The buffer goes back through [`return_window`](Self::return_window) so
    /// its capacity is reused by the next window.
    fn take_window(&self) -> Vec<u8> {
        std::mem::take(&mut *self.0.window.lock().unwrap_or_else(PoisonError::into_inner))
    }

    fn return_window(&self, bytes: Vec<u8>) {
        *self.0.window.lock().unwrap_or_else(PoisonError::into_inner) = bytes;
    }

    fn preceding(&self) -> PrecedingEntry {
        if self.0.after_global.load(Ordering::Relaxed) {
            PrecedingEntry::GlobalPax
        } else {
            PrecedingEntry::Other
        }
    }

    fn set_preceding(&self, kind: PrecedingEntry) {
        self.0
            .after_global
            .store(kind == PrecedingEntry::GlobalPax, Ordering::Relaxed);
    }

    /// Total bytes read from the underlying reader so far — monotonic,
    /// never reset by `arm()`/`disarm()`.
    fn total_read(&self) -> u64 {
        self.0.total_read.load(Ordering::Relaxed)
    }

    /// The bound the skipped-entry meter tripped on, if it did.
    fn skip_trip(&self) -> Option<ZipBombDetails> {
        self.0.skip_trip.get().copied()
    }

    /// Classifies an error `tar` raised while reading toward the next entry.
    fn classify(&self, e: &io::Error) -> crate::ArchiveError {
        budget_violation(e).unwrap_or_else(|| {
            self.prefer_fault(crate::ArchiveError::InvalidArchive(
                crate::Malformation::TarEntryUnreadable {
                    detail: e.to_string().into(),
                },
            ))
        })
    }

    /// Reports a read fault the source raised as [`crate::ArchiveError::Io`],
    /// in place of the format verdict `error` draws from it.
    ///
    /// Only [`crate::ArchiveError::InvalidArchive`] is replaced: a budget,
    /// security or ambiguity refusal is about the bytes `tar` did read, and
    /// stays as it is.
    pub(crate) fn prefer_fault(&self, error: crate::ArchiveError) -> crate::ArchiveError {
        match (&error, self.0.source.fault()) {
            (crate::ArchiveError::InvalidArchive(_), Some(fault)) => crate::ArchiveError::Io(fault),
            _ => error,
        }
    }

    /// Adds `declared` to the sum of skipped entries' declared sizes and
    /// returns the new sum, saturating.
    fn charge_skipped_declared(&self, declared: u64) -> u64 {
        saturating_add_counter(&self.0.skipped_declared, declared)
    }

    /// Adds `synthetic` to the running cross-entry synthetic-byte sum.
    /// Called once per [`TarEntryGuard::drop`], with that guard's own final
    /// `synthetic` count.
    fn add_cumulative_synthetic(&self, synthetic: u64) {
        if synthetic > 0 {
            self.0
                .cumulative_synthetic
                .fetch_add(synthetic, Ordering::Relaxed);
        }
    }

    /// Returns a [`TarCumulativeSyntheticBudgetExceeded`] I/O error if the
    /// running cross-entry synthetic-byte sum has exceeded
    /// [`CUMULATIVE_SYNTHETIC_CAP_BYTES`], else `None`.
    fn cumulative_synthetic_violation(&self) -> Option<io::Error> {
        let total = self.0.cumulative_synthetic.load(Ordering::Relaxed);
        (total > CUMULATIVE_SYNTHETIC_CAP_BYTES).then(|| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                TarCumulativeSyntheticBudgetExceeded {
                    limit: CUMULATIVE_SYNTHETIC_CAP_BYTES,
                },
            )
        })
    }
}

/// Adds `by` to `counter`, saturating at `u64::MAX`, and returns the new value.
fn saturating_add_counter(counter: &AtomicU64, by: u64) -> u64 {
    let previous = counter
        .try_update(Ordering::Relaxed, Ordering::Relaxed, |v| {
            Some(v.saturating_add(by))
        })
        .unwrap_or_else(|v| v);
    previous.saturating_add(by)
}

/// Marker error surfaced when more than the configured limit is read from a
/// [`BudgetedReader`] while armed. Recovered via [`budget_violation`] and
/// converted into an `ArchiveError::SecurityViolation`.
#[derive(Debug)]
struct TarReadBudgetExceeded {
    limit: u64,
}

impl std::fmt::Display for TarReadBudgetExceeded {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fmt_tar_read_budget(f, self.limit)
    }
}

impl std::error::Error for TarReadBudgetExceeded {}

/// Marker error surfaced when the cross-entry
/// [`CUMULATIVE_SYNTHETIC_CAP_BYTES`] budget is exceeded. Recovered via
/// [`budget_violation`] and converted into
/// an `ArchiveError::SecurityViolation`, the same as
/// [`TarReadBudgetExceeded`].
#[derive(Debug)]
struct TarCumulativeSyntheticBudgetExceeded {
    limit: u64,
}

impl std::fmt::Display for TarCumulativeSyntheticBudgetExceeded {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fmt_tar_synthetic_budget(f, self.limit)
    }
}

impl std::error::Error for TarCumulativeSyntheticBudgetExceeded {}

/// Marker error surfaced when the payload of a skipped entry decodes past the
/// ratio bound. Recovered via [`budget_violation`] and converted into
/// `ZipBomb { SkippedEntries }`.
#[derive(Debug)]
struct SkippedEntriesExceeded(ZipBombDetails);

impl std::fmt::Display for SkippedEntriesExceeded {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "skipped entries decode past the compression ratio bound")
    }
}

impl std::error::Error for SkippedEntriesExceeded {}

/// Marker error raised by the xz decoder wrapper when the stream needs more
/// memory than `max_decoder_memory` allows. Recovered via [`budget_violation`]
/// and converted into `QuotaExceeded { DecoderMemory }`.
#[derive(Debug)]
pub struct DecoderMemoryExceeded {
    pub max: u64,
}

impl std::fmt::Display for DecoderMemoryExceeded {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "decoder memory limit of {} bytes exceeded", self.max)
    }
}

impl std::error::Error for DecoderMemoryExceeded {}

/// Marker error raised when a gzip or bzip2 stream starts more members than
/// its allowance admits. Recovered via [`budget_violation`] and converted into
/// `QuotaExceeded { CompressedMembers }`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CompressedMembersExceeded {
    /// The member that was refused, counting from one.
    pub members: u64,
    /// The most members the stream could have started at that point.
    pub allowance: u64,
}

impl std::fmt::Display for CompressedMembersExceeded {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "compressed member {} exceeds the allowance of {}",
            self.members, self.allowance
        )
    }
}

impl std::error::Error for CompressedMembersExceeded {}

/// Classifies a stream error raised while decoding or reading an archive.
///
/// Walks the error chain (`get_ref()` through each `io::Error`, `source()`
/// through everything else, so the `tar` crate's wrapper is transparent) and
/// recovers a TAR read-budget, cumulative synthetic-byte budget, or decoder
/// memory violation, converting it into the matching `ArchiveError`.
///
/// Returns `None` for any other error, so callers can fall back to their
/// usual generic error mapping.
pub fn budget_violation(e: &io::Error) -> Option<crate::ArchiveError> {
    let mut current: Option<&(dyn std::error::Error + 'static)> = Some(e);
    while let Some(err) = current {
        if let Some(exceeded) = err.downcast_ref::<TarReadBudgetExceeded>() {
            return Some(
                Violation::TarMetadataBudget {
                    limit: exceeded.limit,
                }
                .into(),
            );
        }
        if let Some(exceeded) = err.downcast_ref::<TarCumulativeSyntheticBudgetExceeded>() {
            return Some(
                Violation::TarSyntheticBudget {
                    limit: exceeded.limit,
                }
                .into(),
            );
        }
        if let Some(exceeded) = err.downcast_ref::<SkippedEntriesExceeded>() {
            return Some(crate::ArchiveError::ZipBomb(exceeded.0));
        }
        if let Some(exceeded) = err.downcast_ref::<DecoderMemoryExceeded>() {
            return Some(crate::ArchiveError::QuotaExceeded {
                resource: crate::QuotaResource::DecoderMemory { max: exceeded.max },
            });
        }
        if let Some(exceeded) = err.downcast_ref::<CompressedMembersExceeded>() {
            return Some(crate::ArchiveError::QuotaExceeded {
                resource: crate::QuotaResource::CompressedMembers {
                    members: exceeded.members,
                    allowance: exceeded.allowance,
                },
            });
        }
        current = err.downcast_ref::<io::Error>().map_or_else(
            || err.source(),
            |io_err| {
                io_err
                    .get_ref()
                    .map(|inner| inner as &(dyn std::error::Error + 'static))
            },
        );
    }
    None
}

/// Read wrapper that meters bytes against a [`TarReadBudget`] while armed and
/// passes them through unmetered while disarmed.
///
/// Never buffers, drops, reorders, or fabricates bytes: every byte returned
/// came from `inner`, in the same order. The only behavior beyond plain
/// passthrough is refusing to deliver more than `limit` bytes per armed
/// window, and it refuses by returning `Err`, never `Ok(0)` — a clamp to a
/// zero-length read would masquerade as clean end-of-archive to callers like
/// `tar`'s own `try_read_all`, turning a budget trip into a silently
/// truncated (but "successful") listing.
pub struct BudgetedReader<R> {
    inner: R,
    state: Arc<BudgetState>,
}

impl<R: Read> Read for BudgetedReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let allowance = self.state.allowance.load(Ordering::Relaxed);
        if allowance == DISARMED {
            let n = self.inner.read(buf)?;
            self.state.total_read.fetch_add(n as u64, Ordering::Relaxed);
            self.state.meter_skipped(n)?;
            return Ok(n);
        }

        let consumed = self.state.consumed.load(Ordering::Relaxed);
        if consumed >= allowance {
            // The budget is exhausted, but a well-formed archive whose
            // metadata happens to end exactly at the configured limit must
            // not be rejected: distinguish "the underlying stream also ends
            // here" (safe — nothing was hidden) from "there is more real
            // data beyond the budget" (a genuine violation) with a minimal
            // probe read, rather than assuming a violation outright.
            let mut probe = [0u8; 1];
            return match self.inner.read(&mut probe) {
                Ok(0) => Ok(0),
                Ok(n) => {
                    self.state.total_read.fetch_add(n as u64, Ordering::Relaxed);
                    Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        TarReadBudgetExceeded { limit: allowance },
                    ))
                }
                Err(e) => Err(e),
            };
        }

        let remaining = allowance - consumed;
        let want = usize::try_from(remaining)
            .unwrap_or(usize::MAX)
            .min(buf.len());
        let n = self.inner.read(&mut buf[..want])?;
        self.state.record(&buf[..n]);
        self.state.consumed.fetch_add(n as u64, Ordering::Relaxed);
        self.state.total_read.fetch_add(n as u64, Ordering::Relaxed);
        self.state.meter_skipped(n)?;
        Ok(n)
    }
}

/// [`budgeted_reader_with`] over a stream whose raw input is not metered.
// A test helper: a zero budget is a bug in the test itself.
#[cfg(test)]
#[allow(clippy::expect_used)]
#[must_use]
pub fn budgeted_reader<R: Read>(inner: R, limit: u64) -> (BudgetedReader<R>, TarReadBudget) {
    let limit = NonZeroU64::new(limit).expect("a test budget is non-zero");
    budgeted_reader_with(inner, limit, TapSource::Opaque)
}

/// Wraps `inner` in a [`BudgetedReader`] and returns it alongside the
/// [`TarReadBudget`] handle used to arm/disarm it.
///
/// The budget starts **armed** with `limit` (fail-closed): any read before
/// the first explicit `arm()`/`disarm()` cycle — e.g. a call site that never
/// wires up [`BudgetedEntries`] — is metered, not silently unlimited.
///
/// `source` meters the raw input behind `inner`, which lets the budget judge
/// skipped entries against the input that produced them (see
/// [`CheckedTarEntry::drain_skipped`]).
// No runnable `# Examples` here: this module is `pub(crate)` (an
// implementation detail of the `tar`/`inspection::list` wiring, not public
// API), so a doctest importing it via `exarch_core::formats::...` would not
// link — doctests only see the crate's public surface.
#[must_use]
pub fn budgeted_reader_with<R: Read>(
    inner: R,
    limit: NonZeroU64,
    source: TapSource,
) -> (BudgetedReader<R>, TarReadBudget) {
    let state = Arc::new(BudgetState {
        limit,
        source,
        skipped_declared: AtomicU64::new(0),
        skipped_decoded: AtomicU64::new(0),
        metering: AtomicBool::new(false),
        skip_limits: OnceLock::new(),
        skip_trip: OnceLock::new(),
        abandoned: AtomicBool::new(false),
        consumed: AtomicU64::new(0),
        allowance: AtomicU64::new(limit.get()),
        total_read: AtomicU64::new(0),
        cumulative_synthetic: AtomicU64::new(0),
        window: Mutex::new(Vec::new()),
        after_global: AtomicBool::new(false),
    });
    let reader = BudgetedReader {
        inner,
        state: Arc::clone(&state),
    };
    (reader, TarReadBudget(state))
}

/// The bytes `tar` consumed between two entries: padding, extension headers
/// and their bodies, and the header of the entry that was yielded.
///
/// Captured verbatim by [`BudgetedReader`] while the budget is armed, so its
/// size is bounded by the metadata limit. `start` is the offset of the first
/// byte from the beginning of the archive.
pub struct MetadataWindow<'a> {
    start: u64,
    bytes: &'a [u8],
}

impl<'a> MetadataWindow<'a> {
    /// Wraps `bytes` that were read starting at offset `start`.
    pub const fn new(start: u64, bytes: &'a [u8]) -> Self {
        Self { start, bytes }
    }

    /// Offset of the first captured byte from the start of the archive.
    pub const fn start(&self) -> u64 {
        self.start
    }

    /// The captured bytes.
    pub const fn bytes(&self) -> &'a [u8] {
        self.bytes
    }

    /// Offset one past the last captured byte.
    pub const fn end(&self) -> u64 {
        self.start.saturating_add(self.bytes.len() as u64)
    }
}

/// A `tar::Entry` on loan from [`BudgetedEntries::next_entry`], guaranteed
/// fully drained (up to a bound) when dropped.
///
/// The `'s` lifetime ties this guard to the `&mut BudgetedEntries` borrow
/// that produced it, making it a compile error to call `next_entry()` again
/// (or to hold two guards at once) while a guard is alive — the "every entry
/// is drained before the next iteration step" invariant the whole module
/// depends on is therefore enforced by the borrow checker, not by review
/// convention.
///
/// The guard is the *unchecked* state: it gives no access to the entry. The
/// only way to a `tar::Entry` is [`check`](Self::check), which verifies the
/// bytes `tar` consumed to reach it.
pub struct TarEntryGuard<'a, 's, R: Read> {
    entry: tar::Entry<'a, BudgetedReader<R>>,
    window_start: u64,
    budget: TarReadBudget,
    abandoned: bool,
    skip_marked: bool,
    _borrow: PhantomData<&'s mut ()>,
}

impl<'a, 's, R: Read> TarEntryGuard<'a, 's, R> {
    /// Suppresses the bounded drain this guard would otherwise perform on
    /// drop.
    ///
    /// Call this only when abandoning the whole operation (returning an
    /// error and never calling `next_entry()` again) — draining is then
    /// pointless I/O, not a correctness requirement, since the bounded drain
    /// is safe to skip precisely because no further reads will happen.
    ///
    /// The stream may then sit mid-entry, so the shared budget is marked and
    /// a later [`BudgetedEntries::next_entry`] refuses to read on.
    pub fn abandon(&mut self) {
        self.abandoned = true;
        self.budget.0.abandoned.store(true, Ordering::Relaxed);
    }

    /// Reads the rest of the entry, calling `on_chunk` with each chunk's
    /// length; an error from it stops the read and is returned.
    ///
    /// Bounded by *synthesized* bytes, not total output (see module docs): a
    /// legitimate entry's `synthetic` stays ~0 regardless of size, so it
    /// drains to completion, while a run of GNU sparse zero-padding pushes
    /// `synthetic` up by a full chunk on every iteration and trips
    /// `SYNTHETIC_PAD_CAP_BYTES` almost immediately. A partial drain leaves
    /// the stream in a well-defined position: the shortfall is read on the
    /// *next* header search, either misaligning into a checksum error or
    /// exceeding the metadata budget, both loud failures, never silent. A read
    /// error ends the drain the same way.
    fn drain<E>(
        &mut self,
        mut on_chunk: impl FnMut(u64) -> std::result::Result<(), E>,
    ) -> std::result::Result<(), E> {
        let total_read_at_start = self.budget.total_read();
        let mut output_so_far: u64 = 0;
        let mut synthetic: u64 = 0;
        let mut outcome = Ok(());
        let mut buf = [0u8; DRAIN_CHUNK_BYTES];
        loop {
            let n = match self.entry.read(&mut buf) {
                Ok(0) | Err(_) => break,
                Ok(n) => n as u64,
            };
            output_so_far += n;
            let read_since_start = self.budget.total_read() - total_read_at_start;
            synthetic = output_so_far.saturating_sub(read_since_start);
            if let Err(e) = on_chunk(n) {
                outcome = Err(e);
                break;
            }
            if synthetic > SYNTHETIC_PAD_CAP_BYTES {
                break;
            }
        }
        // Feeds the cross-entry cumulative budget (issue #422): this
        // entry's own synthesized-byte count, summed with every other
        // entry's over the lifetime of this `TarReadBudget`, is what
        // `BudgetedEntries::next_entry` checks before yielding the next
        // entry — bounding total drain work across many small
        // synthetic-heavy entries, not just any single one.
        self.budget.add_cumulative_synthetic(synthetic);
        // The drain is done; `Drop` has nothing left to read.
        self.abandoned = true;
        outcome
    }

    /// Verifies the entry's headers and the bytes `tar` consumed to reach
    /// it, and unlocks the entry.
    ///
    /// `metadata_limit` bounds how much of a global PAX header is read.
    ///
    /// # Errors
    ///
    /// Returns [`crate::ArchiveError::InvalidArchive`] when the headers are
    /// ambiguous; the guard is then abandoned, as no further entry is read.
    pub fn check(mut self, metadata_limit: u64) -> Result<CheckedTarEntry<'a, 's, R>> {
        let bytes = self.budget.take_window();
        let window = MetadataWindow::new(self.window_start, &bytes);
        let checked = check_entry_headers(
            &mut self.entry,
            &window,
            metadata_limit,
            self.budget.preceding(),
        );
        self.budget.return_window(bytes);
        match checked {
            Ok(kind) => {
                self.budget.set_preceding(kind);
                Ok(CheckedTarEntry(self))
            }
            Err(e) => {
                self.abandon();
                Err(self.budget.prefer_fault(e))
            }
        }
    }
}

/// The limits that bound decoding an entry whose data is read only to reach
/// the next header (an entry the extension allowlist or a duplicate skipped).
///
/// See [`CheckedTarEntry::drain_skipped`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SkipLimits {
    per_file: Limit<NonZeroU64>,
    total: Limit<NonZeroU64>,
    ratio: f64,
}

impl SkipLimits {
    /// Extra decoded bytes admitted on top of the ratio bound, so tiny
    /// archives with a few small skipped entries never trip it.
    const SLACK_BYTES: u64 = 1024 * 1024;

    /// Takes the limits from a validated config.
    pub(crate) fn of(config: &SecurityConfig) -> Self {
        Self {
            per_file: config.max_file_size,
            total: config.max_total_size,
            ratio: config.max_compression_ratio.get(),
        }
    }

    /// Decoded bytes a skipped entry may yield once `consumed` raw bytes were
    /// read.
    #[expect(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "the allowance is an approximate bound; a validated ratio is finite and positive, and the float-to-int cast saturates"
    )]
    fn allowance(&self, consumed: u64) -> u64 {
        let by_ratio = (consumed as f64 * self.ratio) as u64;
        by_ratio.saturating_add(Self::SLACK_BYTES)
    }
}

/// A [`TarEntryGuard`] whose headers passed [`TarEntryGuard::check`].
///
/// Constructible only by `check`, so holding a `tar::Entry` through this type
/// proves the checks ran. Dropping it drains the entry like the guard does.
pub struct CheckedTarEntry<'a, 's, R: Read>(TarEntryGuard<'a, 's, R>);

impl<R: Read> CheckedTarEntry<'_, '_, R> {
    /// Suppresses the bounded drain on drop; see [`TarEntryGuard::abandon`].
    pub fn abandon(&mut self) {
        self.0.abandon();
    }

    /// Runs `step` on the entry and abandons it when `step` fails, so a
    /// refused entry is never decoded to its end on the way out.
    ///
    /// # Errors
    ///
    /// Returns the error `step` returned.
    pub fn settle<T>(&mut self, step: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
        step(self).inspect_err(|_| self.abandon())
    }

    /// Reads the entry to its end without charging it to the extraction quota,
    /// so the next header can be reached.
    ///
    /// The entry's declared size is charged to a cumulative skipped total. An
    /// entry the quota would have admitted anyway (`max_file_size` per entry,
    /// `max_total_size` over all skipped entries) drains with no further check,
    /// so filtering an archive never refuses what extracting it whole would
    /// accept. Any other entry is read under
    /// `skipped decoded <= max_compression_ratio x raw input consumed + 1 MiB`,
    /// checked per chunk, which bounds the decode work by the input that
    /// produced it. The input counted is everything read so far, extracted
    /// entries included. Plain TAR decodes at a ratio of one and always
    /// passes; a stream the caller already decoded (`TarArchive::new`) is
    /// never refused, because core cannot see its compression.
    ///
    /// # Errors
    ///
    /// Returns [`crate::ArchiveError::ZipBomb`] with
    /// [`ZipBombScope::SkippedEntries`] when the bound is exceeded.
    pub fn drain_skipped(&mut self, limits: &SkipLimits) -> Result<()> {
        if self.mark_skipped(limits) == SkipAdmission::Admitted {
            return Ok(());
        }
        let Ok(()) = self.0.drain::<Infallible>(|_| Ok(()));
        self.0
            .budget
            .skip_trip()
            .map_or(Ok(()), |details| Err(crate::ArchiveError::ZipBomb(details)))
    }

    /// Declares the entry skipped without reading it, for a caller that reads
    /// its payload itself (an integrity decode).
    ///
    /// Charges the declared size once, however often it is called. An entry
    /// the quota would have admitted is left alone; any other has its payload
    /// metered by the reader, under the bound [`drain_skipped`] documents,
    /// until the next [`BudgetedEntries::next_entry`]. A read that crosses the
    /// bound fails with an error [`budget_violation`] maps to
    /// [`ZipBombScope::SkippedEntries`].
    ///
    /// [`drain_skipped`]: Self::drain_skipped
    pub fn mark_skipped(&mut self, limits: &SkipLimits) -> SkipAdmission {
        let budget = &self.0.budget;
        if self.0.skip_marked {
            return if budget.0.metering.load(Ordering::Relaxed) {
                SkipAdmission::Metered
            } else {
                SkipAdmission::Admitted
            };
        }
        self.0.skip_marked = true;
        let declared = self.0.entry.size();
        let skipped_declared = budget.charge_skipped_declared(declared);
        if limits.per_file.admits(declared) && limits.total.admits(skipped_declared) {
            return SkipAdmission::Admitted;
        }
        let first = budget.0.skip_limits.get_or_init(|| *limits);
        debug_assert_eq!(first, limits);
        budget.0.metering.store(true, Ordering::Relaxed);
        SkipAdmission::Metered
    }
}

/// How [`CheckedTarEntry::mark_skipped`] treats the payload of a skipped
/// entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SkipAdmission {
    /// The quota admits the entry anyway; its payload is not metered.
    Admitted,
    /// The reader meters the payload against the skipped-entry bound.
    Metered,
}

impl<'a, R: Read> std::ops::Deref for CheckedTarEntry<'a, '_, R> {
    type Target = tar::Entry<'a, BudgetedReader<R>>;

    fn deref(&self) -> &Self::Target {
        &self.0.entry
    }
}

impl<R: Read> std::ops::DerefMut for CheckedTarEntry<'_, '_, R> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0.entry
    }
}

impl<R: Read> Drop for TarEntryGuard<'_, '_, R> {
    fn drop(&mut self) {
        if self.abandoned {
            return;
        }
        let Ok(()) = self.drain::<Infallible>(|_| Ok(()));
    }
}

/// Lending iterator over `tar` entries with a read budget armed for every gap
/// between entries.
///
/// Deliberately does **not** implement `std::iter::Iterator`: `Iterator::next`
/// cannot return a value borrowing `&mut self`, so an `Iterator` impl would
/// let a caller hold two [`TarEntryGuard`]s (or collect them into a `Vec`)
/// simultaneously — compiling, but silently defeating the "always drained
/// before the next entry" guarantee this type exists to enforce. Use
/// `while let Some(entry) = entries.next_entry() { ... }`.
pub struct BudgetedEntries<'a, R: Read> {
    entries: tar::Entries<'a, BudgetedReader<R>>,
    budget: TarReadBudget,
    /// `total_read` when iteration began; window offsets are relative to it.
    origin: u64,
    /// Set once `next_entry` has yielded an `Err`; latches further calls to
    /// `None` instead of re-yielding (or re-deriving) an error. Without
    /// this, a hypothetical caller that logs an error from `next_entry` and
    /// keeps calling it in a loop — rather than propagating with `?` as
    /// every current call site does — would spin forever once the
    /// cumulative budget trips, since the violation condition never clears
    /// itself.
    poisoned: bool,
    /// Window start of the read that found the end of the archive; consumed
    /// by [`finish`](Self::finish).
    end_window_start: Option<u64>,
}

impl<'a, R: Read> BudgetedEntries<'a, R> {
    fn new(entries: tar::Entries<'a, BudgetedReader<R>>, budget: TarReadBudget) -> Self {
        Self {
            entries,
            origin: budget.total_read(),
            budget,
            poisoned: false,
            end_window_start: None,
        }
    }

    /// Verifies the bytes `tar` read after the last entry.
    ///
    /// Call it once `next_entry` has returned `None`: the padding after a
    /// trailing global PAX header is only read there, so skipping this call
    /// leaves it unchecked.
    ///
    /// # Errors
    ///
    /// Returns [`crate::ArchiveError::InvalidArchive`] when that padding is
    /// not zero.
    pub fn finish(&mut self) -> Result<()> {
        let Some(start) = self.end_window_start.take() else {
            return Ok(());
        };
        let bytes = self.budget.take_window();
        let checked =
            check_trailing_headers(&MetadataWindow::new(start, &bytes), self.budget.preceding());
        self.budget.return_window(bytes);
        checked
    }

    /// Arms the budget, asks `tar` for the next entry, disarms the budget,
    /// and (on success) wraps the result in a draining guard.
    ///
    /// Arming happens *before* asking `tar`, so the metered window covers the
    /// entire gap: sub-block padding, any `L`/`K`/`x` metadata records, GNU
    /// sparse extension blocks, and the final header — including the
    /// trailing gap after the last real entry, which is exactly where an
    /// archive consisting of nothing but oversized metadata records would
    /// otherwise buffer unbounded before `tar` gives up with "members found
    /// describing a future member but no future member found".
    ///
    /// Before any of that, checks the cross-entry cumulative synthetic-byte
    /// budget (issue #422): if prior entries' drains have already summed
    /// past [`CUMULATIVE_SYNTHETIC_CAP_BYTES`], fails immediately rather than
    /// asking `tar` for (and then draining) yet another entry.
    ///
    /// Once this has returned `Some(Err(_))` once, every subsequent call
    /// returns `None` rather than repeating (or re-deriving) the error.
    ///
    /// An error is classified here: a budget violation as such, a read fault
    /// the source itself raised as [`crate::ArchiveError::Io`], anything else
    /// as [`crate::ArchiveError::InvalidArchive`].
    pub fn next_entry(&mut self) -> Option<Result<TarEntryGuard<'a, '_, R>>> {
        if self.poisoned {
            return None;
        }
        if self.budget.0.abandoned.load(Ordering::Relaxed) {
            self.poisoned = true;
            return Some(Err(crate::ArchiveError::InvalidArchive(
                crate::Malformation::TarReadAfterAbandonedEntry,
            )));
        }
        if let Some(details) = self.budget.skip_trip() {
            self.poisoned = true;
            return Some(Err(crate::ArchiveError::ZipBomb(details)));
        }
        self.budget.0.metering.store(false, Ordering::Relaxed);
        if let Some(err) = self.budget.cumulative_synthetic_violation() {
            self.poisoned = true;
            return Some(Err(self.budget.classify(&err)));
        }
        let start = self.budget.total_read() - self.origin;
        self.budget.arm();
        let result = self.entries.next();
        self.budget.disarm();

        match result {
            None => {
                self.end_window_start = Some(start);
                None
            }
            Some(Err(e)) => {
                self.poisoned = true;
                Some(Err(self.budget.classify(&e)))
            }
            Some(Ok(entry)) => Some(Ok(TarEntryGuard {
                entry,
                window_start: start,
                budget: self.budget.clone(),
                abandoned: false,
                skip_marked: false,
                _borrow: PhantomData,
            })),
        }
    }
}

/// Builds a [`BudgetedEntries`] iterator from an already budget-wrapped
/// archive, using the *same* [`TarReadBudget`] handle that reader was created
/// with.
///
/// Keeping construction to this one function (rather than callers manually
/// pairing `archive.entries()` with a `TarReadBudget` obtained separately) is
/// what makes it hard to accidentally iterate the raw `tar::Entries` and
/// bypass arming entirely.
///
/// # Errors
///
/// Returns an error if `tar` cannot begin reading entries (e.g. the archive
/// was already fully consumed).
pub fn budgeted_tar_entries<R: Read>(
    archive: &mut tar::Archive<BudgetedReader<R>>,
    budget: TarReadBudget,
) -> io::Result<BudgetedEntries<'_, R>> {
    let entries = archive.entries()?;
    Ok(BudgetedEntries::new(entries, budget))
}

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

    #[test]
    fn disarmed_reader_passes_bytes_through_unchanged() {
        let (mut reader, budget) = budgeted_reader(Cursor::new(b"hello world".to_vec()), 4);
        budget.disarm();
        let mut out = Vec::new();
        reader.read_to_end(&mut out).unwrap();
        assert_eq!(out, b"hello world");
    }

    #[test]
    fn armed_reader_allows_exactly_the_limit() {
        let (mut reader, budget) = budgeted_reader(Cursor::new(vec![b'a'; 10]), 10);
        budget.arm();
        let mut out = Vec::new();
        reader.read_to_end(&mut out).unwrap();
        assert_eq!(out.len(), 10);
    }

    #[test]
    fn armed_reader_trips_at_limit_plus_one_with_err_not_ok_zero() {
        // Regression for critic finding S4: a naive clamp-to-empty-slice at
        // exhaustion returns `Ok(0)`, which `tar`'s own `try_read_all` (and
        // any other EOF-sensing consumer) treats as clean end-of-archive —
        // silently truncating output instead of failing loudly.
        let (mut reader, budget) = budgeted_reader(Cursor::new(vec![b'a'; 11]), 10);
        budget.arm();
        let mut out = Vec::new();
        let err = reader
            .read_to_end(&mut out)
            .expect_err("must error, not silently truncate");
        assert!(
            budget_violation(&err).is_some(),
            "must be recognizable as a budget violation, got: {err:?}"
        );
    }

    #[test]
    fn new_reader_is_armed_from_construction() {
        // Regression for critic finding S3: if the budget started disarmed,
        // a call site that forgets to pair the reader with `BudgetedEntries`
        // (never calling `arm()`/`disarm()` itself) would run unprotected —
        // exactly the regression this whole redesign exists to prevent.
        let (mut reader, _budget) = budgeted_reader(Cursor::new(vec![b'a'; 11]), 10);
        let mut out = Vec::new();
        let err = reader
            .read_to_end(&mut out)
            .expect_err("a freshly constructed reader must already be armed");
        assert!(budget_violation(&err).is_some());
    }

    #[test]
    fn rearming_resets_consumed_bytes() {
        let (mut reader, budget) = budgeted_reader(Cursor::new(vec![b'a'; 20]), 10);
        budget.arm();
        let mut buf = [0u8; 10];
        reader.read_exact(&mut buf).unwrap();
        // Disarm, do something unmetered, then arm again: the fresh window
        // must not inherit the previous window's consumed count.
        budget.disarm();
        budget.arm();
        let mut out = Vec::new();
        reader.read_to_end(&mut out).unwrap();
        assert_eq!(
            out.len(),
            10,
            "re-armed window must allow a fresh `limit` bytes"
        );
    }

    /// Builds a minimal one-entry TAR archive (ustar) around `content`.
    fn one_entry_tar(name: &str, content: &[u8]) -> Vec<u8> {
        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_cksum();
        builder.append_data(&mut header, name, content).unwrap();
        builder.into_inner().unwrap()
    }

    #[test]
    fn budgeted_entries_yields_a_well_formed_archive_normally() {
        let data = one_entry_tar("file.txt", b"hello");
        let (reader, budget) = budgeted_reader(Cursor::new(data), 4096);
        let mut archive = tar::Archive::new(reader);
        let mut entries = budgeted_tar_entries(&mut archive, budget).unwrap();

        let mut guard = entries
            .next_entry()
            .expect("one entry")
            .expect("no io error")
            .check(4096)
            .unwrap();
        let mut content = Vec::new();
        guard.read_to_end(&mut content).unwrap();
        assert_eq!(content, b"hello");
        drop(guard);

        assert!(entries.next_entry().is_none(), "exactly one entry");
    }

    #[test]
    fn drop_drains_unread_entry_so_the_next_header_is_found() {
        let mut data = one_entry_tar("skipped.txt", b"unread content");
        // Append a second entry after the first.
        let mut builder = tar::Builder::new(Vec::new());
        let mut header = tar::Header::new_gnu();
        header.set_size(5);
        header.set_mode(0o644);
        header.set_cksum();
        builder
            .append_data(&mut header, "after.txt", &b"hello"[..])
            .unwrap();
        let second = builder.into_inner().unwrap();
        // Splice: first entry's header+data (without its own EOF markers)
        // followed by the second archive's single entry and its EOF markers.
        data.truncate(data.len() - 1024); // drop first archive's EOF markers
        data.extend_from_slice(&second);

        let (reader, budget) = budgeted_reader(Cursor::new(data), 4096);
        let mut archive = tar::Archive::new(reader);
        let mut entries = budgeted_tar_entries(&mut archive, budget).unwrap();

        let guard = entries.next_entry().unwrap().unwrap();
        // Deliberately never read `guard`'s content — the Drop below must
        // still leave the stream correctly positioned for the next header.
        drop(guard);

        let mut second_guard = entries
            .next_entry()
            .expect("second entry must still be reachable")
            .expect("no io error")
            .check(4096)
            .unwrap();
        let mut content = Vec::new();
        second_guard.read_to_end(&mut content).unwrap();
        assert_eq!(content, b"hello");
    }

    #[test]
    fn window_holds_the_bytes_read_between_two_entries() {
        let mut data = one_entry_tar("first.txt", b"unread content");
        data.truncate(data.len() - 1024);
        data.extend_from_slice(&one_entry_tar("second.txt", b"hello"));

        let (reader, budget) = budgeted_reader(Cursor::new(data), 4096);
        let handle = budget.clone();
        let mut archive = tar::Archive::new(reader);
        let mut entries = budgeted_tar_entries(&mut archive, budget).unwrap();

        let first = entries.next_entry().unwrap().unwrap();
        assert_eq!(first.window_start, 0);
        assert_eq!(handle.take_window().len(), 512);
        drop(first);

        let second = entries.next_entry().unwrap().unwrap();
        assert_eq!(second.window_start, 512 + 14);
        let window = handle.take_window();
        assert_eq!(window.len(), (512 - 14) + 512);
        assert_eq!(
            MetadataWindow::new(second.window_start, &window).end(),
            1536
        );
        handle.return_window(window);
        second.check(4096).unwrap();
    }

    #[test]
    fn abandon_suppresses_the_drain() {
        let data = one_entry_tar("file.txt", b"hello");
        let (reader, budget) = budgeted_reader(Cursor::new(data), 4096);
        let mut archive = tar::Archive::new(reader);
        let mut entries = budgeted_tar_entries(&mut archive, budget).unwrap();

        let mut guard = entries.next_entry().unwrap().unwrap();
        guard.abandon();
        // No assertion beyond "does not panic and drops cleanly": abandon()
        // only affects whether Drop performs I/O, which has no externally
        // observable effect once the whole `BudgetedEntries` is discarded.
        drop(guard);
    }

    #[test]
    fn reading_on_after_an_abandoned_entry_is_refused() {
        let mut data = one_entry_tar("first.txt", b"unread content");
        data.truncate(data.len() - 1024);
        data.extend_from_slice(&one_entry_tar("second.txt", b"hello"));
        let (reader, budget) = budgeted_reader(Cursor::new(data), 4096);
        let mut archive = tar::Archive::new(reader);
        let mut entries = budgeted_tar_entries(&mut archive, budget).unwrap();

        let mut guard = entries.next_entry().unwrap().unwrap();
        guard.abandon();
        drop(guard);

        let refused = entries.next_entry().unwrap().err().unwrap();
        assert!(refused.to_string().contains("abandoned entry"), "{refused}");
        assert!(entries.next_entry().is_none(), "the error latches");
    }

    #[test]
    fn a_drop_drain_trip_makes_the_next_entry_a_skipped_entries_bomb() {
        use crate::formats::source_fault::SourceRead;
        use crate::formats::source_fault::SourceTap;
        use std::io::Write as _;

        let tar = one_entry_tar("big.bin", &vec![0u8; 4 << 20]);
        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
        encoder.write_all(&tar).unwrap();
        let gz = encoder.finish().unwrap();

        let tap = SourceTap::default();
        let decoder = flate2::read::GzDecoder::new(SourceRead::new(Cursor::new(gz), tap.clone()));
        let (reader, budget) =
            budgeted_reader_with(decoder, crate::non_zero!(4096), TapSource::Tapped(tap));
        let mut archive = tar::Archive::new(reader);
        let mut entries = budgeted_tar_entries(&mut archive, budget).unwrap();
        let limits = SkipLimits {
            per_file: crate::non_zero!(1024).into(),
            total: crate::non_zero!(1024).into(),
            ratio: 10.0,
        };

        let mut entry = entries.next_entry().unwrap().unwrap().check(4096).unwrap();
        assert_eq!(entry.mark_skipped(&limits), SkipAdmission::Metered);
        drop(entry);

        let refused = entries.next_entry().unwrap().err().unwrap();
        assert_matches!(
            refused,
            crate::ArchiveError::ZipBomb(d) if d.scope() == ZipBombScope::SkippedEntries
        );
        assert!(entries.next_entry().is_none(), "the error latches");
    }

    #[test]
    fn settle_abandons_the_entry_when_the_step_fails() {
        let data = one_entry_tar("file.txt", b"hello");
        let (reader, budget) = budgeted_reader(Cursor::new(data), 4096);
        let mut archive = tar::Archive::new(reader);
        let mut entries = budgeted_tar_entries(&mut archive, budget).unwrap();

        let mut entry = entries.next_entry().unwrap().unwrap().check(4096).unwrap();
        let failed = entry
            .settle(|_| Err::<(), _>(crate::ArchiveError::from(Violation::SymlinksUnsupported)));
        assert!(failed.is_err());
        drop(entry);

        assert!(entries.next_entry().unwrap().is_err());
    }

    #[test]
    fn a_fault_replaces_only_a_format_verdict_and_not_after_a_recovered_read() {
        use crate::ArchiveError;
        use crate::TarAmbiguity;
        use crate::formats::source_fault::SourceRead;
        use crate::formats::source_fault::SourceTap;
        use std::assert_matches;

        struct EioThenData(bool);
        impl Read for EioThenData {
            fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
                if std::mem::replace(&mut self.0, true) {
                    buf[0] = 0;
                    Ok(1)
                } else {
                    Err(io::Error::from_raw_os_error(5))
                }
            }
        }

        let tap = SourceTap::default();
        let mut source = SourceRead::new(EioThenData(false), tap.clone());
        let (_reader, budget) = budgeted_reader_with(
            Cursor::new(Vec::new()),
            crate::non_zero!(16),
            TapSource::Tapped(tap),
        );
        let verdict = || ArchiveError::unclassified("bad header");

        source.read(&mut [0u8; 4]).unwrap_err();
        assert_matches!(
            budget.prefer_fault(verdict()),
            ArchiveError::Io(e) if e.raw_os_error() == Some(5)
        );
        assert_matches!(
            budget.prefer_fault(ArchiveError::TarAmbiguity(TarAmbiguity::LocalBeforeGlobal)),
            ArchiveError::TarAmbiguity(_)
        );

        assert_eq!(source.read(&mut [0u8; 4]).unwrap(), 1);
        assert_matches!(
            budget.prefer_fault(verdict()),
            ArchiveError::InvalidArchive(_)
        );
    }

    #[test]
    fn oversized_metadata_record_trips_the_budget() {
        // A GNU long-name record whose real (delivered) bytes exceed the
        // configured budget must trip before `tar` finishes buffering it.
        let long_name = "x".repeat(2048);
        let mut builder = tar::Builder::new(Vec::new());
        let mut header = tar::Header::new_gnu();
        header.set_size(5);
        header.set_mode(0o644);
        header.set_cksum();
        builder
            .append_data(&mut header, long_name.as_str(), &b"hello"[..])
            .unwrap();
        let data = builder.into_inner().unwrap();

        let (reader, budget) = budgeted_reader(Cursor::new(data), 512);
        let mut archive = tar::Archive::new(reader);
        let mut entries = budgeted_tar_entries(&mut archive, budget).unwrap();

        // `.err()` first: `TarEntryGuard` (the `Ok` side) does not implement
        // `Debug` (it holds a `tar::Entry`, which does not either), so
        // `Result::expect_err` (which requires `T: Debug`) does not apply —
        // `Option::expect` on the converted `Option<io::Error>` does not
        // need the discarded `Ok` value to implement anything.
        let result = entries.next_entry().expect("an entry attempt");
        let err = result
            .err()
            .expect("the long-name record exceeds the 512-byte budget");
        assert_matches!(
            err,
            crate::ArchiveError::SecurityViolation { .. },
            "got: {err:?}"
        );
    }

    /// Reader that counts total bytes yielded by `inner`, used below to
    /// observe how much `TarEntryGuard::drop` actually drains without relying
    /// on heap-allocation measurement (which a `Take`-limited `io::sink` drain
    /// would not show regardless of how large the drain is).
    struct CountingReader<R> {
        inner: R,
        count: Arc<AtomicU64>,
    }

    impl<R: Read> Read for CountingReader<R> {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            let n = self.inner.read(buf)?;
            self.count.fetch_add(n as u64, Ordering::Relaxed);
            Ok(n)
        }
    }

    #[test]
    fn drop_fully_drains_a_legitimate_large_entry_regardless_of_size() {
        // Regression for critic findings C2/C3: a fixed cap on *total*
        // drained output (the earlier, broken designs) rejects any ordinary
        // archive whose unread entry exceeds that cap — worse than the
        // original bug, since no crafting is needed to trip it. A
        // legitimate entry's drain consumes real bytes 1:1 with its output,
        // so `synthetic` never grows and this must drain to completion no
        // matter how large the entry is (here: comfortably larger than
        // `SYNTHETIC_PAD_CAP_BYTES`).
        let content_len = usize::try_from(SYNTHETIC_PAD_CAP_BYTES).unwrap() * 3;
        let data = one_entry_tar("legit_large.bin", &vec![b'A'; content_len]);

        let read_count = Arc::new(AtomicU64::new(0));
        let counting = CountingReader {
            inner: Cursor::new(data),
            count: Arc::clone(&read_count),
        };

        let (reader, budget) = budgeted_reader(counting, 4096);
        let mut archive = tar::Archive::new(reader);
        let mut entries = budgeted_tar_entries(&mut archive, budget).unwrap();

        let guard = entries.next_entry().unwrap().unwrap();
        // Deliberately never read `guard`'s content — the drop must still
        // fully drain it, exactly like the "skip an unread entry" case on
        // `list`/`verify`/extension-filtered `extract`.
        drop(guard);

        let drained = read_count.load(Ordering::Relaxed);
        // The one-entry archive is: 512-byte header + content (block-padded)
        // + two 512-byte zero blocks (end-of-archive trailer). The drain
        // must consume at least the full content, proving it was not cut
        // short by any fixed output cap.
        assert!(
            drained >= 512 + u64::try_from(content_len).unwrap(),
            "drop must fully drain a legitimate large entry, drained only {drained} bytes of a \
             {content_len}-byte entry"
        );
    }

    fn octal_field(n: u64, width: usize) -> Option<Vec<u8>> {
        let digits = format!("{n:o}").into_bytes();
        if digits.len() > width - 1 {
            return None;
        }
        let mut out = vec![b'0'; width - 1 - digits.len()];
        out.extend_from_slice(&digits);
        out.push(0);
        Some(out)
    }
    fn base256_field(n: u64, width: usize) -> Vec<u8> {
        let mut out = vec![0u8; width];
        let bytes = n.to_be_bytes();
        out[width - bytes.len()..].copy_from_slice(&bytes);
        out[0] |= 0x80;
        out
    }
    fn num_field(n: u64, width: usize) -> Vec<u8> {
        octal_field(n, width).unwrap_or_else(|| base256_field(n, width))
    }

    const HDR_BLOCK: usize = 512;

    /// Builds a raw GNU old-format sparse header + one-block physical
    /// backing (typeflag `'S'`) whose `realsize` vastly exceeds that one
    /// block — the same on-disk shape as issue #414's C1 `PoC` — *without* a
    /// trailing end-of-archive trailer, so several can be concatenated into
    /// one multi-entry archive.
    fn gnu_sparse_bomb_entry(name: &[u8], realsize: u64) -> Vec<u8> {
        assert!(
            name.len() <= 100,
            "test helper: name field is 100 bytes, {name:?} does not fit"
        );
        let gap = realsize - HDR_BLOCK as u64;
        let mut h = vec![0u8; HDR_BLOCK];
        h[..name.len()].copy_from_slice(name);
        h[100..108].copy_from_slice(&num_field(0o644, 8));
        h[108..116].copy_from_slice(&num_field(0, 8));
        h[116..124].copy_from_slice(&num_field(0, 8));
        h[124..136].copy_from_slice(&num_field(HDR_BLOCK as u64, 12));
        h[136..148].copy_from_slice(&num_field(0, 12));
        h[156] = b'S';
        h[257..263].copy_from_slice(b"ustar ");
        h[263..265].copy_from_slice(b" \0");
        h[386..398].copy_from_slice(&num_field(gap, 12));
        h[398..410].copy_from_slice(&num_field(HDR_BLOCK as u64, 12));
        h[482] = 0;
        h[483..495].copy_from_slice(&num_field(realsize, 12));
        h[148..156].copy_from_slice(b"        ");
        let sum: u32 = h.iter().map(|b| u32::from(*b)).sum();
        h[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes());

        let mut out = h;
        out.extend(std::iter::repeat_n(0u8, HDR_BLOCK)); // one real backing block
        out
    }

    /// Builds a raw one-entry TAR archive around a single
    /// [`gnu_sparse_bomb_entry`], closed with an end-of-archive trailer.
    fn gnu_sparse_bomb_tar(realsize: u64) -> Vec<u8> {
        let mut out = gnu_sparse_bomb_entry(b"sparsebomb.bin", realsize);
        out.extend(std::iter::repeat_n(0u8, HDR_BLOCK * 2)); // end-of-archive trailer
        out
    }

    #[test]
    fn drop_drain_stops_quickly_on_gnu_sparse_synthesized_padding() {
        // Regression for critic finding C1 (and confirms C2's fix did not
        // reopen it): a GNU sparse entry's zero-padding produces output with
        // no corresponding read, so `synthetic` grows immediately and the
        // drain must stop within a small, bounded number of bytes actually
        // read from the underlying reader — regardless of how large
        // `realsize` claims to be.
        let data = gnu_sparse_bomb_tar(1u64 << 50);

        let read_count = Arc::new(AtomicU64::new(0));
        let counting = CountingReader {
            inner: Cursor::new(data),
            count: Arc::clone(&read_count),
        };

        let (reader, budget) = budgeted_reader(counting, 4096);
        let mut archive = tar::Archive::new(reader);
        let mut entries = budgeted_tar_entries(&mut archive, budget).unwrap();

        let guard = entries.next_entry().unwrap().unwrap();
        drop(guard);

        let drained = read_count.load(Ordering::Relaxed);
        // The header (512 B) plus the one real backing block (512 B) plus a
        // generous margin for the synthetic cap's own chunking — nowhere
        // near the exabyte `realsize` the entry claims.
        assert!(
            drained
                <= 512 + 512 + SYNTHETIC_PAD_CAP_BYTES + u64::try_from(DRAIN_CHUNK_BYTES).unwrap(),
            "drop must stop draining almost immediately on synthesized padding, drained {drained} \
             bytes"
        );
    }

    /// Drives `entries` to completion or a violation, draining every
    /// yielded guard exactly like a real skip loop would. Returns the count
    /// of entries yielded before either running out or hitting an error.
    fn drain_all_entries<R: Read>(
        entries: &mut BudgetedEntries<'_, R>,
    ) -> (usize, Option<crate::ArchiveError>) {
        let mut yielded = 0usize;
        while let Some(result) = entries.next_entry() {
            match result {
                Ok(guard) => {
                    yielded += 1;
                    drop(guard);
                }
                Err(e) => return (yielded, Some(e)),
            }
        }
        (yielded, None)
    }

    #[test]
    fn cumulative_synthetic_budget_trips_on_many_maximally_saturating_entries() {
        // Regression for issue #422: SYNTHETIC_PAD_CAP_BYTES bounds any one
        // entry's drain, but nothing previously bounded the *count* of such
        // entries — a caller that keeps skipping synthetic-heavy entries
        // (e.g. all extension-filtered pre-quota, per PR #421's ordering)
        // could drain an unbounded total. This is the worst case the
        // cumulative cap has to bound: every entry individually saturates
        // SYNTHETIC_PAD_CAP_BYTES, the maximum any single entry can
        // contribute, so this is also the *fewest* entries that can trip
        // CUMULATIVE_SYNTHETIC_CAP_BYTES — computed from the real constants
        // (not a hardcoded entry count) so this stays correct if either cap
        // is retuned. Also validates the wall-clock claim in
        // CUMULATIVE_SYNTHETIC_CAP_BYTES's own doc comment: even this worst
        // case must stay fast, not scale with an attacker's entry count.
        const WORST_CASE_BOUND: std::time::Duration = std::time::Duration::from_secs(5);
        let entries_needed = CUMULATIVE_SYNTHETIC_CAP_BYTES / SYNTHETIC_PAD_CAP_BYTES + 1;
        let entry_count = usize::try_from(entries_needed).unwrap() + 5; // margin past the trip

        let mut data = Vec::new();
        for i in 0..entry_count {
            data.extend(gnu_sparse_bomb_entry(
                format!("spam{i}.bin").as_bytes(),
                1u64 << 40,
            ));
        }
        data.extend(std::iter::repeat_n(0u8, HDR_BLOCK * 2)); // end-of-archive trailer

        let (reader, budget) = budgeted_reader(Cursor::new(data), 4096);
        let mut archive = tar::Archive::new(reader);
        let mut entries = budgeted_tar_entries(&mut archive, budget).unwrap();

        let start = std::time::Instant::now();
        let (yielded, violation) = drain_all_entries(&mut entries);
        let elapsed = start.elapsed();

        let err = violation.expect(
            "the cumulative synthetic budget must trip before every entry is drained, not \
             silently allow all of them",
        );
        assert_matches!(
            err,
            crate::ArchiveError::SecurityViolation { .. },
            "must be recognizable as a budget violation, got: {err:?}"
        );
        assert!(
            yielded < entry_count,
            "must fail fast well before draining all {entry_count} entries, but yielded \
             {yielded} of them"
        );
        assert!(
            elapsed < WORST_CASE_BOUND,
            "the worst case (every entry maximally saturating) took {elapsed:?} to trip, \
             expected well under {WORST_CASE_BOUND:?}"
        );
    }

    #[test]
    fn cumulative_synthetic_budget_trips_from_many_sub_cap_contributions() {
        // Regression for critic finding S3: the test above only proves the
        // budget trips when every entry individually saturates
        // SYNTHETIC_PAD_CAP_BYTES. The issue's actual reported shape is
        // different — many small entries, each producing far less
        // synthesized output than the per-entry cap on its own — and a
        // buggy accumulation (e.g. one that only counted entries which
        // individually tripped SYNTHETIC_PAD_CAP_BYTES) would let this
        // archive drain in full. Each entry here contributes a fixed,
        // well-under-cap `GAP` to the cumulative sum; only their sum, not
        // any single one of them, exceeds CUMULATIVE_SYNTHETIC_CAP_BYTES.
        const GAP: u64 = 4 * 1024 * 1024;
        const _: () = assert!(
            GAP < SYNTHETIC_PAD_CAP_BYTES,
            "test premise: each entry must stay well under the per-entry cap on its own"
        );
        let entries_needed = CUMULATIVE_SYNTHETIC_CAP_BYTES / GAP + 1;
        let entry_count = usize::try_from(entries_needed).unwrap() + 20; // margin past the trip

        let mut data = Vec::new();
        for i in 0..entry_count {
            data.extend(gnu_sparse_bomb_entry(
                format!("small{i}.bin").as_bytes(),
                HDR_BLOCK as u64 + GAP,
            ));
        }
        data.extend(std::iter::repeat_n(0u8, HDR_BLOCK * 2)); // end-of-archive trailer

        let (reader, budget) = budgeted_reader(Cursor::new(data), 4096);
        let mut archive = tar::Archive::new(reader);
        let mut entries = budgeted_tar_entries(&mut archive, budget).unwrap();

        let (yielded, violation) = drain_all_entries(&mut entries);

        let err = violation.expect(
            "many sub-cap synthetic contributions must still sum past the cumulative budget, \
             not silently drain in full",
        );
        assert_matches!(
            err,
            crate::ArchiveError::SecurityViolation { .. },
            "must be recognizable as a budget violation, got: {err:?}"
        );
        assert!(
            yielded < entry_count,
            "must fail before draining every one of the {entry_count} sub-cap entries, yielded \
             {yielded}"
        );
        // Proves the accumulation is real (many sub-cap entries actually
        // summed), not a fluke of some unrelated check firing on entry one.
        assert!(
            yielded >= 2,
            "expected several sub-cap entries to be individually drained before the cumulative \
             cap trips, only {yielded} were"
        );
    }
}