encypher-c2pa 1.8.0

Verification-only C2PA 2.4 and CAWG SDK, offline by default
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
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
// Copyright 2026 Encypher Corporation
// SPDX-License-Identifier: Apache-2.0

//! JUMBF (ISO 19566-5) box serializer and parser for C2PA manifest stores.
//!
//! The parser and serializer are byte-compatible with the C2PA JUMBF layout.
//! Box format:
//! `LBox(4 BE) | TBox(4) | payload`, with extended size when total >= 2^32
//! (LBox=1, then XLBox(8)).

use std::borrow::Cow;

use thiserror::Error;

/// C2PA JUMBF type UUID suffix shared by all C2PA box types.
const UUID_SUFFIX: [u8; 12] = [
    0x00, 0x11, 0x00, 0x10, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71,
];

/// Build a 16-byte C2PA type UUID from its 4-byte ASCII prefix.
const fn type_uuid(prefix: [u8; 4]) -> [u8; 16] {
    let mut u = [0u8; 16];
    u[0] = prefix[0];
    u[1] = prefix[1];
    u[2] = prefix[2];
    u[3] = prefix[3];
    let mut i = 0;
    while i < 12 {
        u[4 + i] = UUID_SUFFIX[i];
        i += 1;
    }
    u
}

/// Manifest store superbox UUID (`c2pa`).
pub const UUID_MANIFEST_STORE: [u8; 16] = type_uuid(*b"c2pa");
/// Manifest superbox UUID (`c2ma`).
pub const UUID_MANIFEST: [u8; 16] = type_uuid(*b"c2ma");
/// Legacy standard manifest superbox UUID (`c2md`), accepted for compatibility.
pub const UUID_LEGACY_MANIFEST: [u8; 16] = type_uuid(*b"c2md");
/// Update manifest superbox UUID (`c2um`).
pub const UUID_UPDATE_MANIFEST: [u8; 16] = type_uuid(*b"c2um");
/// Compressed manifest superbox UUID (`c2cm`).
pub const UUID_COMPRESSED_MANIFEST: [u8; 16] = type_uuid(*b"c2cm");
/// Assertion store superbox UUID (`c2as`).
pub const UUID_ASSERTION_STORE: [u8; 16] = type_uuid(*b"c2as");
/// Claim superbox UUID (`c2cl`).
pub const UUID_CLAIM: [u8; 16] = type_uuid(*b"c2cl");
/// Claim signature superbox UUID (`c2cs`).
pub const UUID_CLAIM_SIGNATURE: [u8; 16] = type_uuid(*b"c2cs");
/// CBOR-content assertion box UUID (`cbor`).
pub const UUID_CBOR_CONTENT: [u8; 16] = type_uuid(*b"cbor");
/// JSON-content assertion box UUID (`json`).
pub const UUID_JSON_CONTENT: [u8; 16] = type_uuid(*b"json");
/// The C2PA Redaction UUID (`CAA98EEE-9D4D-F80E-86AD-4DFFCA263973`).
///
/// C2PA 2.4 Architecture, Redaction of Assertions: a redaction may retain the
/// labelled assertion container and replace its JUMBF Content boxes with a
/// single UUID Content box carrying this ID and an all-zero `DATA` field.
pub const UUID_REDACTION: [u8; 16] = [
    0xCA, 0xA9, 0x8E, 0xEE, 0x9D, 0x4D, 0xF8, 0x0E, 0x86, 0xAD, 0x4D, 0xFF, 0xCA, 0x26, 0x39, 0x73,
];

const TYPE_JUMB: &[u8; 4] = b"jumb";
const TYPE_JUMD: &[u8; 4] = b"jumd";
const TYPE_CBOR: &[u8; 4] = b"cbor";
const TYPE_JSON: &[u8; 4] = b"json";
const TYPE_BROB: &[u8; 4] = b"brob";
const TYPE_FREE: &[u8; 4] = b"free";
const TYPE_UUID: &[u8; 4] = b"uuid";
const TYPE_SALT: &[u8; 4] = b"c2sh";
const LABEL_MANIFEST_STORE: &str = "c2pa";
const LABEL_ASSERTION_STORE: &str = "c2pa.assertions";
const LABEL_CLAIM_V1: &str = "c2pa.claim";
const LABEL_CLAIM_V2: &str = "c2pa.claim.v2";
const LABEL_CLAIM_SIGNATURE: &str = "c2pa.signature";
const MAX_MANIFESTS_PER_STORE: usize = 1_024;
const MAX_ASSERTIONS_PER_MANIFEST: usize = 4_096;
/// A C2PA assertion store may contain the maximum assertion count directly.
/// The same bound is conservative for manifest stores, manifests, and
/// individual assertion superboxes while preventing unbounded child vectors.
const MAX_CHILD_BOXES_PER_SUPERBOX: usize = MAX_ASSERTIONS_PER_MANIFEST;
const MAX_LABEL_BYTES: usize = 1_024;

/// Description box toggle: requestable.
const TOGGLE_REQUESTABLE: u8 = 0x01;
/// Description box toggle: label present.
const TOGGLE_LABEL_PRESENT: u8 = 0x02;
/// Description box toggle: private (salt sub-box present).
const TOGGLE_PRIVATE: u8 = 0x10;

/// Error parsing a JUMBF structure.
#[derive(Debug, Error, PartialEq)]
pub enum JumbfError {
    /// Not enough bytes for a box header at the given offset.
    #[error("truncated box header at offset {0}")]
    TruncatedHeader(usize),
    /// A declared box size ran past the end of the buffer.
    #[error("box length {0} overruns buffer")]
    LengthOverrun(u64),
    /// Expected a specific box type but found another.
    #[error("expected box type {expected:?}, found {found:?}")]
    UnexpectedType {
        /// The 4-byte type that was expected.
        expected: [u8; 4],
        /// The 4-byte type that was found.
        found: [u8; 4],
    },
    /// The superbox UUID did not match the expected C2PA type.
    #[error("unexpected superbox uuid")]
    UnexpectedUuid,
    /// Brotli decoding of a `brob` payload failed.
    #[error("brotli decompression failed")]
    DecompressionFailed,
    /// A `brob` payload inflated past [`MAX_DECOMPRESSED_MANIFEST_BYTES`].
    #[error("decompressed manifest exceeds {MAX_DECOMPRESSED_MANIFEST_BYTES} bytes")]
    DecompressedTooLarge,
    /// A `c2cm` superbox did not carry exactly one non-empty `brob` box.
    #[error("malformed compressed manifest: {0}")]
    CompressedManifestShape(&'static str),
    /// The `c2cm` label disagreed with the manifest it carries.
    #[error(
        "compressed manifest label {compressed:?} does not match carried manifest {manifest:?}"
    )]
    CompressedManifestLabelMismatch {
        /// Label on the `c2cm` superbox.
        compressed: String,
        /// Label on the decompressed manifest.
        manifest: String,
    },
    /// A decompressed box was not a standard or update manifest.
    #[error("not a C2PA manifest superbox")]
    NotAManifestSuperbox,
    /// A compressed manifest failed decompression or structural checks.
    #[error("compressed manifest {label:?} is invalid: {reason}")]
    CompressedManifestInvalid {
        /// Label on the rejected `c2cm` superbox.
        label: String,
        /// Structural or Brotli error.
        reason: Box<JumbfError>,
    },
    /// Bytes remained after the declared top-level box.
    #[error("{0} trailing bytes after top-level JUMBF box")]
    TrailingBytes(usize),
    /// A collection exceeded a verifier resource bound.
    #[error("{0}")]
    ResourceLimit(&'static str),
    /// A JUMBF path is ambiguous because a sibling label is duplicated.
    #[error("ambiguous JUMBF label: {0}")]
    AmbiguousLabel(String),
    /// A canonical C2PA superbox UUID appeared under the wrong JUMBF label.
    #[error("expected JUMBF label {expected}, found {found}")]
    UnexpectedLabel {
        /// Label required for this UUID.
        expected: &'static str,
        /// Label present in the description box.
        found: String,
    },
    /// Required C2PA JUMBF structure was absent or appeared more than once.
    #[error("invalid C2PA JUMBF structure: {0}")]
    InvalidStructure(&'static str),
    /// A standard-defined manifest kind is recognized but not implemented.
    #[error("unsupported C2PA manifest type: {0}")]
    UnsupportedManifestType(&'static str),
}

/// Wrap `payload` in an ISOBMFF box with a 4-byte type code.
fn box_bytes(box_type: &[u8; 4], payload: &[u8]) -> Vec<u8> {
    let total = 8 + payload.len();
    let mut out = Vec::with_capacity(total + 8);
    if (total as u64) < (1u64 << 32) {
        out.extend_from_slice(&(total as u32).to_be_bytes());
        out.extend_from_slice(box_type);
        out.extend_from_slice(payload);
    } else {
        out.extend_from_slice(&1u32.to_be_bytes());
        out.extend_from_slice(box_type);
        out.extend_from_slice(&((total + 8) as u64).to_be_bytes());
        out.extend_from_slice(payload);
    }
    out
}

/// Build a JUMBF description box (`jumd`). Write path only.
#[cfg(test)]
fn description_box(type_uuid: &[u8; 16], label: &str, salt: Option<&[u8]>) -> Vec<u8> {
    let mut toggles = TOGGLE_REQUESTABLE | TOGGLE_LABEL_PRESENT;
    if salt.is_some() {
        toggles |= TOGGLE_PRIVATE;
    }
    let mut payload = Vec::new();
    payload.extend_from_slice(type_uuid);
    payload.push(toggles);
    payload.extend_from_slice(label.as_bytes());
    payload.push(0x00);
    if let Some(s) = salt {
        payload.extend_from_slice(&box_bytes(b"c2sh", s));
    }
    box_bytes(TYPE_JUMD, &payload)
}

/// Build a JUMBF superbox (`jumb`): a description box followed by content boxes.
///
/// JUMBF assembly is not part of the verification surface. The reader parses
/// these structures; only in-repo fixture generation writes them. This module
/// is private to the crate and the item is `cfg(test)`, so it is unreachable
/// from a consumer and absent from the shipped build.
#[cfg(test)]
pub fn superbox(
    type_uuid: &[u8; 16],
    label: &str,
    content: &[Vec<u8>],
    salt: Option<&[u8]>,
) -> Vec<u8> {
    let mut inner = description_box(type_uuid, label, salt);
    for c in content {
        inner.extend_from_slice(c);
    }
    box_bytes(TYPE_JUMB, &inner)
}

/// Wrap CBOR bytes in a CBOR content box (`cbor`). Fixture generation only.
#[cfg(test)]
pub fn cbor_box(cbor: &[u8]) -> Vec<u8> {
    box_bytes(TYPE_CBOR, cbor)
}

/// Build an assertion superbox containing a single CBOR content box.
/// Fixture generation only.
#[cfg(test)]
pub fn assertion_box(label: &str, cbor: &[u8], salt: Option<&[u8]>) -> Vec<u8> {
    superbox(&UUID_CBOR_CONTENT, label, &[cbor_box(cbor)], salt)
}

/// Build a redacted assertion superbox: the labelled container is retained and
/// its content is a single UUID Content box carrying the C2PA Redaction UUID
/// and `zeros` zero bytes. Fixture generation only.
#[cfg(test)]
pub fn redacted_assertion_box(label: &str, zeros: usize) -> Vec<u8> {
    let mut content = UUID_REDACTION.to_vec();
    content.resize(UUID_REDACTION.len() + zeros, 0);
    superbox(
        &UUID_CBOR_CONTENT,
        label,
        &[box_bytes(TYPE_UUID, &content)],
        None,
    )
}

/// Return the JUMBF *content* of a superbox: its payload after its complete
/// `LBox+TBox` or `LBox+TBox+XLBox` header. This is the byte range hashed for
/// `assertion.hashedURI` bindings (C2PA spec 14.2.3).
///
/// The declared box length bounds the returned payload. Legal size-to-end boxes
/// consume the remaining input. Truncated, overrunning, and non-`jumb` boxes are
/// rejected rather than being hashed with an assumed 8-byte header.
pub fn superbox_content(superbox_bytes: &[u8]) -> Result<&[u8], JumbfError> {
    let parsed = parse_box(superbox_bytes, 0)?;
    if &parsed.box_type != TYPE_JUMB {
        return Err(JumbfError::UnexpectedType {
            expected: *TYPE_JUMB,
            found: parsed.box_type,
        });
    }
    Ok(parsed.payload)
}

/// Build a single C2PA manifest (assertion store + claim + signature) with a
/// v2 claim box (`c2pa.claim.v2`). Fixture generation only.
#[cfg(test)]
pub fn build_manifest(
    manifest_label: &str,
    assertion_boxes: &[Vec<u8>],
    claim_cbor: &[u8],
    signature_cose: &[u8],
) -> Vec<u8> {
    build_manifest_with_claim_label(
        manifest_label,
        assertion_boxes,
        claim_cbor,
        signature_cose,
        "c2pa.claim.v2",
    )
}

/// Build a single C2PA manifest with an explicit claim box label.
///
/// `claim_label` is `"c2pa.claim.v2"` for 2.x claims and `"c2pa.claim"` for
/// the legacy 1.x claim-v1 generation used by backward-compatibility fixtures.
/// Fixture generation only.
#[cfg(test)]
pub fn build_manifest_with_claim_label(
    manifest_label: &str,
    assertion_boxes: &[Vec<u8>],
    claim_cbor: &[u8],
    signature_cose: &[u8],
    claim_label: &str,
) -> Vec<u8> {
    let assertion_store = superbox(
        &UUID_ASSERTION_STORE,
        "c2pa.assertions",
        assertion_boxes,
        None,
    );
    let claim = superbox(&UUID_CLAIM, claim_label, &[cbor_box(claim_cbor)], None);
    let sig = superbox(
        &UUID_CLAIM_SIGNATURE,
        "c2pa.signature",
        &[cbor_box(signature_cose)],
        None,
    );
    superbox(
        &UUID_MANIFEST,
        manifest_label,
        &[assertion_store, claim, sig],
        None,
    )
}

/// Build a complete C2PA manifest store from manifest superboxes (active last).
/// Fixture generation only.
#[cfg(test)]
pub fn build_manifest_store(manifests: &[Vec<u8>]) -> Vec<u8> {
    superbox(&UUID_MANIFEST_STORE, "c2pa", manifests, None)
}

/// Extract raw manifest superboxes from a C2PA manifest store, preserving
/// store order.
pub fn manifest_superboxes_from_store(data: &[u8]) -> Result<Vec<&[u8]>, JumbfError> {
    let top = parse_manifest_store_box(data)?;
    if &top.box_type != TYPE_JUMB {
        return Err(JumbfError::UnexpectedType {
            expected: *TYPE_JUMB,
            found: top.box_type,
        });
    }
    let store = parse_superbox_description(top.payload)?;
    if store.type_uuid != UUID_MANIFEST_STORE {
        return Err(JumbfError::UnexpectedUuid);
    }
    if store.label != LABEL_MANIFEST_STORE {
        return Err(JumbfError::UnexpectedLabel {
            expected: LABEL_MANIFEST_STORE,
            found: store.label,
        });
    }

    let mut pos = store.content_offset;
    let mut child_count = 0usize;
    let mut manifests = Vec::new();
    while pos < top.payload.len() {
        if child_count >= MAX_CHILD_BOXES_PER_SUPERBOX {
            return Err(JumbfError::ResourceLimit(
                "superbox child count exceeds verifier bound",
            ));
        }
        child_count += 1;
        let b = parse_box(top.payload, pos)?;
        if b.box_type == *TYPE_JUMB {
            let child = parse_superbox_description(b.payload)?;
            if matches!(
                child.type_uuid,
                UUID_MANIFEST | UUID_LEGACY_MANIFEST | UUID_UPDATE_MANIFEST
            ) {
                if manifests.len() >= MAX_MANIFESTS_PER_STORE {
                    return Err(JumbfError::ResourceLimit(
                        "manifest count exceeds verifier bound",
                    ));
                }
                manifests.push(&top.payload[pos..b.next]);
            } else if child.type_uuid == UUID_COMPRESSED_MANIFEST {
                return Err(JumbfError::UnsupportedManifestType("c2cm"));
            }
        }
        pos = b.next;
    }
    Ok(manifests)
}

/// Present two C2PA Manifest Stores as one, appending `update`'s manifests
/// after `base`'s.
///
/// A BMFF asset whose active manifest is an update manifest carries two
/// `ContentProvenanceBox`es: the untouched standard store (`box_purpose` of
/// `original`) and the appended update store (`box_purpose` of `update`).
/// C2PA 2.4 Validation requires the active update manifest's parent chain to
/// be traced across both boxes, so the reader hands the validator a single
/// store. Every manifest superbox is copied verbatim, so manifest digests and
/// hashed-URI bindings are unaffected; only the enclosing store header is
/// rebuilt to cover the added bytes.
pub fn merge_manifest_stores(base: &[u8], update: &[u8]) -> Result<Vec<u8>, JumbfError> {
    let base_store = parse_manifest_store_box(base)?;
    let appended = manifest_superboxes_from_store(update)?;
    let total = appended
        .iter()
        .try_fold(base_store.payload.len(), |total, manifest| {
            total.checked_add(manifest.len())
        })
        .filter(|total| *total <= crate::MAX_MANIFEST_STORE_BYTES)
        .ok_or(JumbfError::ResourceLimit(
            "merged manifest store exceeds verifier byte bound",
        ))?;
    let mut payload = Vec::with_capacity(total);
    payload.extend_from_slice(base_store.payload);
    for manifest in appended {
        payload.extend_from_slice(manifest);
    }
    Ok(box_bytes(TYPE_JUMB, &payload))
}

// ---- Compressed manifests (`c2cm` / `brob`) ----

/// Hard cap on the bytes a single `brob` content box may inflate to.
pub const MAX_DECOMPRESSED_MANIFEST_BYTES: usize = 16 * 1024 * 1024;

struct BoundedSink {
    bytes: Vec<u8>,
    overflowed: bool,
}

impl std::io::Write for BoundedSink {
    fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
        if data.len() > MAX_DECOMPRESSED_MANIFEST_BYTES - self.bytes.len() {
            self.overflowed = true;
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "decompressed manifest exceeds bound",
            ));
        }
        self.bytes.extend_from_slice(data);
        Ok(data.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

fn brotli_decompress_bounded(stream: &[u8]) -> Result<Vec<u8>, JumbfError> {
    let mut sink = BoundedSink {
        bytes: Vec::new(),
        overflowed: false,
    };
    match brotli::BrotliDecompress(&mut std::io::Cursor::new(stream), &mut sink) {
        Ok(()) => Ok(sink.bytes),
        Err(_) if sink.overflowed => Err(JumbfError::DecompressedTooLarge),
        Err(_) => Err(JumbfError::DecompressionFailed),
    }
}

#[cfg(test)]
fn brotli_compress(data: &[u8]) -> Vec<u8> {
    let mut compressed = Vec::new();
    let params = brotli::enc::BrotliEncoderParams::default();
    brotli::BrotliCompress(&mut std::io::Cursor::new(data), &mut compressed, &params)
        .expect("fixture compression");
    compressed
}

/// Wrap a standard manifest as a compressed manifest. Fixture generation only.
#[cfg(test)]
pub fn compress_manifest(manifest_superbox: &[u8]) -> Result<Vec<u8>, JumbfError> {
    let parsed = parse_superbox(manifest_superbox)?;
    if !matches!(parsed.type_uuid, UUID_MANIFEST | UUID_LEGACY_MANIFEST) {
        return Err(JumbfError::NotAManifestSuperbox);
    }
    Ok(superbox(
        &UUID_COMPRESSED_MANIFEST,
        &parsed.label,
        &[box_bytes(TYPE_BROB, &brotli_compress(manifest_superbox))],
        None,
    ))
}

/// Wrap a standard manifest as a compressed manifest in the type-prefixed
/// `brob` layout the Encypher signer writes: `jumb`, then the Brotli stream
/// of the whole manifest superbox. Fixture generation only.
#[cfg(test)]
pub fn compress_manifest_type_prefixed(manifest_superbox: &[u8]) -> Result<Vec<u8>, JumbfError> {
    let parsed = parse_superbox(manifest_superbox)?;
    if !matches!(parsed.type_uuid, UUID_MANIFEST | UUID_LEGACY_MANIFEST) {
        return Err(JumbfError::NotAManifestSuperbox);
    }
    let mut payload = TYPE_JUMB.to_vec();
    payload.extend_from_slice(&brotli_compress(manifest_superbox));
    Ok(superbox(
        &UUID_COMPRESSED_MANIFEST,
        &parsed.label,
        &[box_bytes(TYPE_BROB, &payload)],
        None,
    ))
}

#[cfg(test)]
fn compress_manifest_kind(manifest_superbox: &[u8]) -> Result<Vec<u8>, JumbfError> {
    let parsed = parse_superbox(manifest_superbox)?;
    Ok(superbox(
        &UUID_COMPRESSED_MANIFEST,
        &parsed.label,
        &[box_bytes(TYPE_BROB, &brotli_compress(manifest_superbox))],
        None,
    ))
}

fn decompress_manifest_superbox(parsed: &Superbox<'_>) -> Result<(Vec<u8>, [u8; 16]), JumbfError> {
    if parsed.type_uuid != UUID_COMPRESSED_MANIFEST {
        return Err(JumbfError::UnexpectedUuid);
    }
    let [(box_type, stream)] = parsed.content.as_slice() else {
        return Err(JumbfError::CompressedManifestShape(
            "expected exactly one brob content box",
        ));
    };
    if box_type != TYPE_BROB {
        return Err(JumbfError::UnexpectedType {
            expected: *TYPE_BROB,
            found: *box_type,
        });
    }
    if stream.is_empty() {
        return Err(JumbfError::CompressedManifestShape("brob box is empty"));
    }
    let (manifest, inner) = inflate_brob_payload(stream, &parsed.label)?;
    if !matches!(
        inner.type_uuid,
        UUID_MANIFEST | UUID_LEGACY_MANIFEST | UUID_UPDATE_MANIFEST
    ) {
        return Err(JumbfError::NotAManifestSuperbox);
    }
    if inner.label != parsed.label {
        return Err(JumbfError::CompressedManifestLabelMismatch {
            compressed: parsed.label.clone(),
            manifest: inner.label,
        });
    }
    Ok((manifest, inner.type_uuid))
}

/// Inflate a `brob` payload in either layout C2PA producers write.
///
/// C2PA 2.4 11.2.4 says the payload is "the compressed bytes of the entire
/// manifest superbox"; 11.1.3.2 bases the box on the JPEG XL `brob` box,
/// which carries the original 4-byte box type before the Brotli stream. The
/// type-prefixed reading is tried first, and wins, when the payload starts
/// with `jumb` and the remainder inflates to one manifest superbox carrying
/// `label`. An inflate that exceeds the bound fails closed and is never
/// retried. Otherwise the whole payload is inflated.
fn inflate_brob_payload(
    stream: &[u8],
    label: &str,
) -> Result<(Vec<u8>, SuperboxHeader), JumbfError> {
    if let Some(rest) = stream.strip_prefix(TYPE_JUMB.as_slice()) {
        match brotli_decompress_bounded(rest) {
            Err(JumbfError::DecompressedTooLarge) => return Err(JumbfError::DecompressedTooLarge),
            Ok(manifest) => {
                if let Ok(inner) = superbox_header(&manifest) {
                    if inner.label == label
                        && matches!(
                            inner.type_uuid,
                            UUID_MANIFEST | UUID_LEGACY_MANIFEST | UUID_UPDATE_MANIFEST
                        )
                    {
                        return Ok((manifest, inner));
                    }
                }
            }
            Err(_) => {}
        }
    }
    let manifest = brotli_decompress_bounded(stream)?;
    let inner = superbox_header(&manifest)?;
    Ok((manifest, inner))
}

/// The type UUID and label of a superbox, owned so the bytes can move.
struct SuperboxHeader {
    type_uuid: [u8; 16],
    label: String,
}

fn superbox_header(bytes: &[u8]) -> Result<SuperboxHeader, JumbfError> {
    let parsed = parse_superbox(bytes)?;
    Ok(SuperboxHeader {
        type_uuid: parsed.type_uuid,
        label: parsed.label,
    })
}

/// Return whether a manifest store carries at least one compressed manifest.
pub fn store_has_compressed_manifest(store: &[u8]) -> bool {
    let Ok(top) = parse_manifest_store_box(store) else {
        return false;
    };
    let Ok(description) = parse_superbox_description(top.payload) else {
        return false;
    };
    if description.type_uuid != UUID_MANIFEST_STORE {
        return false;
    }
    let mut position = description.content_offset;
    while position < top.payload.len() {
        let Ok(child_box) = parse_box(top.payload, position) else {
            return false;
        };
        if child_box.box_type == *TYPE_JUMB
            && parse_superbox_payload(child_box.payload)
                .is_ok_and(|child| child.type_uuid == UUID_COMPRESSED_MANIFEST)
        {
            return true;
        }
        position = child_box.next;
    }
    false
}

/// Return whether a store carries a standard, legacy, update, or compressed manifest.
pub fn store_carries_manifest(store: &[u8]) -> bool {
    parse_manifest_store(store).is_ok_and(|parsed| !parsed.manifests.is_empty())
        || store_has_compressed_manifest(store)
}

/// A store with compressed manifests expanded for validation.
pub struct ExpandedStore<'a> {
    bytes: Cow<'a, [u8]>,
    stored_contents: Vec<Option<&'a [u8]>>,
}

impl<'a> ExpandedStore<'a> {
    /// Expanded store bytes, borrowed unchanged when no `c2cm` was present.
    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Whether at least one `c2cm` was expanded.
    pub fn expanded(&self) -> bool {
        matches!(self.bytes, Cow::Owned(_))
    }

    /// Stored `c2cm` superbox content for the manifest at `index`.
    pub fn stored_content(&self, index: usize) -> Option<&'a [u8]> {
        self.stored_contents.get(index).copied().flatten()
    }
}

/// Expand each `c2cm` exactly once, retaining its stored hash domain.
pub fn expand_store(store: &[u8]) -> Result<ExpandedStore<'_>, JumbfError> {
    let top = parse_manifest_store_box(store)?;
    let description = parse_superbox_description(top.payload)?;
    if description.type_uuid != UUID_MANIFEST_STORE {
        return Err(JumbfError::UnexpectedUuid);
    }
    if description.label != LABEL_MANIFEST_STORE {
        return Err(JumbfError::UnexpectedLabel {
            expected: LABEL_MANIFEST_STORE,
            found: description.label,
        });
    }

    let mut compressed_seen = false;
    let mut rebuilt_payload = top.payload[..description.content_offset].to_vec();
    let mut stored_contents = Vec::new();
    let mut position = description.content_offset;
    while position < top.payload.len() {
        let child_box = parse_box(top.payload, position)?;
        if child_box.box_type != *TYPE_JUMB {
            rebuilt_payload.extend_from_slice(&top.payload[position..child_box.next]);
            position = child_box.next;
            continue;
        }
        let child = parse_superbox_payload(child_box.payload)?;
        if child.type_uuid == UUID_COMPRESSED_MANIFEST {
            compressed_seen = true;
            let (manifest, manifest_type) =
                decompress_manifest_superbox(&child).map_err(|reason| {
                    JumbfError::CompressedManifestInvalid {
                        label: child.label.clone(),
                        reason: Box::new(reason),
                    }
                })?;
            if matches!(
                manifest_type,
                UUID_MANIFEST | UUID_LEGACY_MANIFEST | UUID_UPDATE_MANIFEST
            ) {
                stored_contents.push(Some(child_box.payload));
            }
            rebuilt_payload.extend_from_slice(&manifest);
        } else {
            if matches!(
                child.type_uuid,
                UUID_MANIFEST | UUID_LEGACY_MANIFEST | UUID_UPDATE_MANIFEST
            ) {
                stored_contents.push(None);
            }
            rebuilt_payload.extend_from_slice(&top.payload[position..child_box.next]);
        }
        position = child_box.next;
    }

    if !compressed_seen {
        return Ok(ExpandedStore {
            bytes: Cow::Borrowed(store),
            stored_contents: Vec::new(),
        });
    }
    Ok(ExpandedStore {
        bytes: Cow::Owned(box_bytes(TYPE_JUMB, &rebuilt_payload)),
        stored_contents,
    })
}

// ---- Parser ----

/// A parsed ISOBMFF box: type, payload slice, and offset of the next box.
struct ParsedBox<'a> {
    box_type: [u8; 4],
    payload: &'a [u8],
    next: usize,
}

/// Parse a single ISOBMFF box at `offset`.
fn parse_box(data: &[u8], offset: usize) -> Result<ParsedBox<'_>, JumbfError> {
    if offset + 8 > data.len() {
        return Err(JumbfError::TruncatedHeader(offset));
    }
    let size = u32::from_be_bytes([
        data[offset],
        data[offset + 1],
        data[offset + 2],
        data[offset + 3],
    ]);
    let mut box_type = [0u8; 4];
    box_type.copy_from_slice(&data[offset + 4..offset + 8]);

    if size == 1 {
        if offset + 16 > data.len() {
            return Err(JumbfError::TruncatedHeader(offset));
        }
        let xl = u64::from_be_bytes([
            data[offset + 8],
            data[offset + 9],
            data[offset + 10],
            data[offset + 11],
            data[offset + 12],
            data[offset + 13],
            data[offset + 14],
            data[offset + 15],
        ]);
        let xl_size = usize::try_from(xl).map_err(|_| JumbfError::LengthOverrun(xl))?;
        let end = offset
            .checked_add(xl_size)
            .ok_or(JumbfError::LengthOverrun(xl))?;
        if end > data.len() || xl_size < 16 {
            return Err(JumbfError::LengthOverrun(xl));
        }
        Ok(ParsedBox {
            box_type,
            payload: &data[offset + 16..end],
            next: end,
        })
    } else if size == 0 {
        Ok(ParsedBox {
            box_type,
            payload: &data[offset + 8..],
            next: data.len(),
        })
    } else {
        let end = offset
            .checked_add(size as usize)
            .ok_or(JumbfError::LengthOverrun(size as u64))?;
        if end > data.len() || (size as usize) < 8 {
            return Err(JumbfError::LengthOverrun(size as u64));
        }
        Ok(ParsedBox {
            box_type,
            payload: &data[offset + 8..end],
            next: end,
        })
    }
}

/// Parse a carrier containing one store superbox and, optionally, one trailing
/// well-formed `free` box. No other trailing bytes are accepted.
fn parse_manifest_store_box(data: &[u8]) -> Result<ParsedBox<'_>, JumbfError> {
    let top = parse_box(data, 0)?;
    if &top.box_type != TYPE_JUMB {
        return Err(JumbfError::UnexpectedType {
            expected: *TYPE_JUMB,
            found: top.box_type,
        });
    }
    if top.next == data.len() {
        return Ok(top);
    }
    let trailing =
        parse_box(data, top.next).map_err(|_| JumbfError::TrailingBytes(data.len() - top.next))?;
    if trailing.box_type != *TYPE_FREE || trailing.next != data.len() {
        return Err(JumbfError::TrailingBytes(data.len() - top.next));
    }
    Ok(top)
}

struct ParsedSuperboxDescription {
    type_uuid: [u8; 16],
    label: String,
    content_offset: usize,
}

fn parse_superbox_description(payload: &[u8]) -> Result<ParsedSuperboxDescription, JumbfError> {
    let desc = parse_box(payload, 0)?;
    if &desc.box_type != TYPE_JUMD {
        return Err(JumbfError::UnexpectedType {
            expected: *TYPE_JUMD,
            found: desc.box_type,
        });
    }
    if desc.payload.len() < 18 {
        return Err(JumbfError::TruncatedHeader(0));
    }
    let mut type_uuid = [0u8; 16];
    type_uuid.copy_from_slice(&desc.payload[..16]);
    let toggles = desc.payload[16];
    if toggles & (TOGGLE_REQUESTABLE | TOGGLE_LABEL_PRESENT)
        != TOGGLE_REQUESTABLE | TOGGLE_LABEL_PRESENT
    {
        return Err(JumbfError::InvalidStructure(
            "C2PA JUMBF description is not labelled and requestable",
        ));
    }
    let label_bytes = &desc.payload[17..];
    let null = label_bytes
        .iter()
        .position(|&b| b == 0)
        .ok_or(JumbfError::InvalidStructure(
            "JUMBF label is not null-terminated",
        ))?;
    if null > MAX_LABEL_BYTES {
        return Err(JumbfError::ResourceLimit(
            "JUMBF label exceeds verifier bound",
        ));
    }
    let label = std::str::from_utf8(&label_bytes[..null])
        .map_err(|_| JumbfError::InvalidStructure("JUMBF label is not valid UTF-8"))?;
    if label.is_empty()
        || label.chars().any(|character| {
            character <= '\u{001f}'
                || ('\u{007f}'..='\u{009f}').contains(&character)
                || matches!(character, '/' | ';' | '?' | '#' | '\u{feff}' | '\u{ffff}')
        })
    {
        return Err(JumbfError::InvalidStructure(
            "JUMBF label contains a forbidden character",
        ));
    }
    if toggles & TOGGLE_PRIVATE != 0 {
        let salt_offset = 17 + null + 1;
        let salt = parse_box(desc.payload, salt_offset).map_err(|_| {
            JumbfError::InvalidStructure(
                "private JUMBF description requires one 16- or 32-byte c2sh box",
            )
        })?;
        if salt.box_type != *TYPE_SALT
            || salt.next != desc.payload.len()
            || !matches!(salt.payload.len(), 16 | 32)
        {
            return Err(JumbfError::InvalidStructure(
                "private JUMBF description requires one 16- or 32-byte c2sh box",
            ));
        }
    }
    Ok(ParsedSuperboxDescription {
        type_uuid,
        label: label.to_owned(),
        content_offset: desc.next,
    })
}

/// A parsed JUMBF superbox: its type UUID, label, and content boxes.
pub struct Superbox<'a> {
    /// 16-byte type UUID from the description box.
    pub type_uuid: [u8; 16],
    /// Null-terminated UTF-8 label.
    pub label: String,
    /// Content boxes as (type, payload) pairs.
    pub content: Vec<([u8; 4], &'a [u8])>,
}

/// Parse the inner payload of a `jumb` superbox (after the `jumb` header).
fn parse_superbox_payload(payload: &[u8]) -> Result<Superbox<'_>, JumbfError> {
    let description = parse_superbox_description(payload)?;
    let mut content = Vec::new();
    let mut pos = description.content_offset;
    while pos < payload.len() {
        if content.len() >= MAX_CHILD_BOXES_PER_SUPERBOX {
            return Err(JumbfError::ResourceLimit(
                "superbox child count exceeds verifier bound",
            ));
        }
        let b = parse_box(payload, pos)?;
        content.push((b.box_type, b.payload));
        pos = b.next;
    }
    Ok(Superbox {
        type_uuid: description.type_uuid,
        label: description.label,
        content,
    })
}

/// The serialization carried by an assertion superbox.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AssertionContentType {
    /// CBOR JUMBF content box.
    Cbor,
    /// JSON or JSON-LD JUMBF content box.
    Json,
}

/// Parse a top-level `jumb` superbox from raw bytes.
pub fn parse_superbox(data: &[u8]) -> Result<Superbox<'_>, JumbfError> {
    let b = parse_box(data, 0)?;
    if &b.box_type != TYPE_JUMB {
        return Err(JumbfError::UnexpectedType {
            expected: *TYPE_JUMB,
            found: b.box_type,
        });
    }
    if b.next != data.len() {
        return Err(JumbfError::TrailingBytes(data.len() - b.next));
    }
    parse_superbox_payload(b.payload)
}

/// The C2PA manifest form carried by a parsed manifest superbox.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ManifestKind {
    /// A standard manifest (`c2ma`, or legacy `c2md`) with its own hard binding.
    Standard,
    /// An update manifest (`c2um`) whose hard binding comes from its parent.
    Update,
}

/// A parsed C2PA manifest: label, assertions (label -> CBOR bytes), raw
/// assertion JUMBF (label -> superbox payload, for hash verification), claim
/// CBOR, and signature COSE bytes.
pub struct ParsedManifest<'a> {
    /// Manifest URN label.
    pub label: String,
    /// Raw manifest JUMBF superbox payload (for ingredient `activeManifest` hashes).
    pub manifest_jumbf: &'a [u8],
    /// Assertion label -> CBOR content bytes.
    pub assertions: Vec<(String, &'a [u8])>,
    /// Assertion label -> raw superbox payload (for `assertion.hashedURI`).
    pub assertion_jumbf: Vec<(String, &'a [u8])>,
    /// Claim CBOR bytes.
    pub claim_cbor: Option<&'a [u8]>,
    /// Claim signature COSE_Sign1 bytes.
    pub signature_cose: Option<&'a [u8]>,
    /// Number of claim boxes found in this manifest. A conforming manifest has
    /// exactly one; more than one is a `claim.multiple` violation.
    pub claim_count: usize,
    /// Label of the (first) claim box: `"c2pa.claim.v2"` for 2.x claims,
    /// `"c2pa.claim"` for the legacy 1.x claim-v1 generation.
    pub claim_box_label: Option<String>,
}

/// A parsed manifest store: the active manifest is the last entry.
pub struct ParsedStore<'a> {
    /// Manifests in store order.
    pub manifests: Vec<ParsedManifest<'a>>,
}

/// Parse a C2PA manifest store from JUMBF bytes.
pub fn parse_manifest_store(data: &[u8]) -> Result<ParsedStore<'_>, JumbfError> {
    if data.len() > crate::MAX_MANIFEST_STORE_BYTES {
        return Err(JumbfError::ResourceLimit(
            "manifest store exceeds verifier byte bound",
        ));
    }
    let top = parse_manifest_store_box(data)?;
    let store = parse_superbox_payload(top.payload)?;
    if store.type_uuid != UUID_MANIFEST_STORE {
        return Err(JumbfError::UnexpectedUuid);
    }
    if store.label != LABEL_MANIFEST_STORE {
        return Err(JumbfError::UnexpectedLabel {
            expected: LABEL_MANIFEST_STORE,
            found: store.label,
        });
    }
    let mut manifests = Vec::new();
    let mut manifest_labels = std::collections::BTreeSet::new();
    for (ctype, cpayload) in &store.content {
        if ctype == TYPE_JUMB {
            if let Some(manifest) = parse_manifest(cpayload)? {
                if manifests.len() >= MAX_MANIFESTS_PER_STORE {
                    return Err(JumbfError::ResourceLimit(
                        "manifest count exceeds verifier bound",
                    ));
                }
                if !manifest_labels.insert(manifest.label.clone()) {
                    return Err(JumbfError::AmbiguousLabel(manifest.label));
                }
                manifests.push(manifest);
            }
        }
    }
    Ok(ParsedStore { manifests })
}

impl ParsedManifest<'_> {
    /// Return whether this is a standard or update manifest.
    ///
    /// Parsed manifests always carry a valid description box. In-crate tests
    /// also construct empty synthetic manifests directly; those retain the
    /// historical standard-manifest behavior.
    pub fn kind(&self) -> ManifestKind {
        parse_superbox_payload(self.manifest_jumbf)
            .ok()
            .filter(|manifest| manifest.type_uuid == UUID_UPDATE_MANIFEST)
            .map_or(ManifestKind::Standard, |_| ManifestKind::Update)
    }

    /// Return the JUMBF content type for a stored assertion label.
    pub fn assertion_content_type(&self, label: &str) -> Option<AssertionContentType> {
        let (_, payload) = self
            .assertion_jumbf
            .iter()
            .find(|(candidate, _)| candidate == label)?;
        let assertion = parse_superbox_payload(payload).ok()?;
        match assertion.type_uuid {
            UUID_CBOR_CONTENT => Some(AssertionContentType::Cbor),
            UUID_JSON_CONTENT => Some(AssertionContentType::Json),
            _ => None,
        }
    }

    /// Whether the assertion box labelled `label` is present but carries no
    /// content other than zeros, i.e. it was redacted in place.
    ///
    /// `None` means the manifest carries no such assertion box at all (the
    /// other lawful redaction form, where the whole box is removed).
    ///
    /// C2PA 2.4 Validation, Validate the Ingredients: a redacted assertion is
    /// "present and any JUMBF Content box or padding box within it contains
    /// anything other than zero or more `0x00` bytes". The redaction form the
    /// Architecture clause defines wraps those zeros in a UUID Content box
    /// whose 16-byte `ID` field is [`UUID_REDACTION`], so that identifier is
    /// part of the box framing and is not counted as content.
    pub fn assertion_content_is_zeroed(&self, label: &str) -> Option<bool> {
        let (_, payload) = self
            .assertion_jumbf
            .iter()
            .find(|(candidate, _)| candidate == label)?;
        let Ok(assertion) = parse_superbox_payload(payload) else {
            // Unparseable framing is not a zeroed box.
            return Some(false);
        };
        Some(assertion.content.iter().all(|(box_type, content)| {
            let data = match (box_type == TYPE_UUID, content.split_at_checked(16)) {
                (true, Some((id, rest))) if id == UUID_REDACTION => rest,
                _ => *content,
            };
            data.iter().all(|byte| *byte == 0)
        }))
    }
}

fn parse_manifest(payload: &[u8]) -> Result<Option<ParsedManifest<'_>>, JumbfError> {
    let parsed = parse_superbox_payload(payload)?;
    if parsed.type_uuid == UUID_COMPRESSED_MANIFEST {
        return Err(JumbfError::UnsupportedManifestType("c2cm"));
    }
    if !matches!(
        parsed.type_uuid,
        UUID_MANIFEST | UUID_LEGACY_MANIFEST | UUID_UPDATE_MANIFEST
    ) {
        return Ok(None);
    }
    let mut manifest = ParsedManifest {
        label: parsed.label.clone(),
        manifest_jumbf: payload,
        assertions: Vec::new(),
        assertion_jumbf: Vec::new(),
        claim_cbor: None,
        signature_cose: None,
        claim_count: 0,
        claim_box_label: None,
    };
    let mut assertion_labels = std::collections::BTreeSet::new();
    let mut direct_child_labels = std::collections::BTreeSet::new();
    let mut assertion_store_count = 0usize;
    for (content_type, content_payload) in &parsed.content {
        if content_type != TYPE_JUMB {
            continue;
        }
        let inner = parse_superbox_payload(content_payload)?;
        if inner.type_uuid == UUID_ASSERTION_STORE {
            assertion_store_count += 1;
            if assertion_store_count > 1 {
                return Err(JumbfError::InvalidStructure(
                    "manifest contains multiple assertion store superboxes",
                ));
            }
            if inner.label != LABEL_ASSERTION_STORE {
                return Err(JumbfError::UnexpectedLabel {
                    expected: LABEL_ASSERTION_STORE,
                    found: inner.label,
                });
            }
        } else if inner.type_uuid == UUID_CLAIM
            && inner.label != LABEL_CLAIM_V1
            && inner.label != LABEL_CLAIM_V2
        {
            return Err(JumbfError::UnexpectedLabel {
                expected: "c2pa.claim or c2pa.claim.v2",
                found: inner.label,
            });
        } else if inner.type_uuid == UUID_CLAIM_SIGNATURE && inner.label != LABEL_CLAIM_SIGNATURE {
            return Err(JumbfError::UnexpectedLabel {
                expected: LABEL_CLAIM_SIGNATURE,
                found: inner.label,
            });
        }
        if !direct_child_labels.insert(inner.label.clone()) {
            return Err(JumbfError::AmbiguousLabel(inner.label));
        }
        if inner.type_uuid == UUID_ASSERTION_STORE {
            for (assertion_type, assertion_payload) in &inner.content {
                if assertion_type != TYPE_JUMB {
                    continue;
                }
                let assertion = parse_superbox_payload(assertion_payload)?;
                if manifest.assertion_jumbf.len() >= MAX_ASSERTIONS_PER_MANIFEST {
                    return Err(JumbfError::ResourceLimit(
                        "assertion count exceeds verifier bound",
                    ));
                }
                if !assertion_labels.insert(assertion.label.clone()) {
                    return Err(JumbfError::AmbiguousLabel(assertion.label));
                }
                manifest
                    .assertion_jumbf
                    .push((assertion.label.clone(), assertion_payload));
                let expected_content_type = match assertion.type_uuid {
                    UUID_CBOR_CONTENT => Some(TYPE_CBOR),
                    UUID_JSON_CONTENT => Some(TYPE_JSON),
                    _ => None,
                };
                if let Some(expected_content_type) = expected_content_type {
                    if let Some((_, payload)) = assertion
                        .content
                        .iter()
                        .find(|(box_type, _)| box_type == expected_content_type)
                    {
                        manifest.assertions.push((assertion.label.clone(), payload));
                    }
                }
            }
        } else if inner.type_uuid == UUID_CLAIM {
            manifest.claim_count += 1;
            if inner.content.len() != 1 || inner.content[0].0 != *TYPE_CBOR {
                return Err(JumbfError::InvalidStructure(
                    "claim superbox must contain exactly one CBOR content box",
                ));
            }
            if manifest.claim_box_label.is_none() {
                manifest.claim_cbor = Some(inner.content[0].1);
                manifest.claim_box_label = Some(inner.label.clone());
            }
        } else if inner.type_uuid == UUID_CLAIM_SIGNATURE {
            if inner.content.len() != 1 || inner.content[0].0 != *TYPE_CBOR {
                return Err(JumbfError::InvalidStructure(
                    "claim signature superbox must contain exactly one CBOR content box",
                ));
            }
            manifest.signature_cose = Some(inner.content[0].1);
        }
    }
    if assertion_store_count == 0 {
        return Err(JumbfError::InvalidStructure(
            "manifest is missing required c2pa.assertions assertion store",
        ));
    }
    Ok(Some(manifest))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn extended_box_bytes(ordinary: &[u8]) -> Vec<u8> {
        assert_eq!(
            u32::from_be_bytes(ordinary[..4].try_into().unwrap()) as usize,
            ordinary.len()
        );
        let extended_size = u64::try_from(ordinary.len().checked_add(8).unwrap()).unwrap();
        let mut extended = Vec::with_capacity(ordinary.len() + 8);
        extended.extend_from_slice(&1u32.to_be_bytes());
        extended.extend_from_slice(&ordinary[4..8]);
        extended.extend_from_slice(&extended_size.to_be_bytes());
        extended.extend_from_slice(&ordinary[8..]);
        extended
    }

    fn relabel_unique(data: &mut [u8], from: &str, to: &str) {
        assert_eq!(from.len(), to.len());
        let offset = {
            let mut matches = data
                .windows(from.len())
                .enumerate()
                .filter_map(|(offset, candidate)| (candidate == from.as_bytes()).then_some(offset));
            let offset = matches.next().expect("source label must be present");
            assert!(matches.next().is_none(), "source label must be unique");
            offset
        };
        data[offset..offset + to.len()].copy_from_slice(to.as_bytes());
    }

    #[test]
    fn superbox_content_parses_ordinary_extended_and_size_to_end() {
        let payload = b"manifest payload";
        let ordinary = box_bytes(TYPE_JUMB, payload);
        assert_eq!(superbox_content(&ordinary).unwrap(), payload);
        let mut ordinary_with_trailing_box = ordinary.clone();
        ordinary_with_trailing_box.extend_from_slice(b"ignored");
        assert_eq!(
            superbox_content(&ordinary_with_trailing_box).unwrap(),
            payload
        );

        let extended = extended_box_bytes(&ordinary);
        assert_eq!(superbox_content(&extended).unwrap(), payload);
        let mut extended_with_trailing_box = extended.clone();
        extended_with_trailing_box.extend_from_slice(b"ignored");
        assert_eq!(
            superbox_content(&extended_with_trailing_box).unwrap(),
            payload
        );

        let mut size_to_end = Vec::with_capacity(payload.len() + 8);
        size_to_end.extend_from_slice(&0u32.to_be_bytes());
        size_to_end.extend_from_slice(TYPE_JUMB);
        size_to_end.extend_from_slice(payload);
        assert_eq!(superbox_content(&size_to_end).unwrap(), payload);
    }

    #[test]
    fn superbox_content_rejects_malformed_headers_and_lengths() {
        assert!(matches!(
            superbox_content(&[0, 0, 0]),
            Err(JumbfError::TruncatedHeader(0))
        ));

        let wrong_type = box_bytes(b"free", b"payload");
        assert!(matches!(
            superbox_content(&wrong_type),
            Err(JumbfError::UnexpectedType { .. })
        ));

        let ordinary_overrun = [0, 0, 0, 9, b'j', b'u', b'm', b'b'];
        assert!(matches!(
            superbox_content(&ordinary_overrun),
            Err(JumbfError::LengthOverrun(9))
        ));

        let mut extended_overrun = Vec::new();
        extended_overrun.extend_from_slice(&1u32.to_be_bytes());
        extended_overrun.extend_from_slice(TYPE_JUMB);
        extended_overrun.extend_from_slice(&17u64.to_be_bytes());
        assert!(matches!(
            superbox_content(&extended_overrun),
            Err(JumbfError::LengthOverrun(17))
        ));
    }

    #[test]
    fn manifest_superboxes_borrow_store_bytes() {
        let manifest = build_manifest("urn:c2pa:borrowed", &[], &[0xa0], &[0xd2, 0x84]);
        let store = build_manifest_store(std::slice::from_ref(&manifest));

        let spans = manifest_superboxes_from_store(&store).unwrap();

        assert_eq!(spans.as_slice(), &[manifest.as_slice()]);
        let store_start = store.as_ptr() as usize;
        let store_end = store_start + store.len();
        let span_start = spans[0].as_ptr() as usize;
        let span_end = span_start + spans[0].len();
        assert!(span_start >= store_start && span_end <= store_end);
    }

    #[test]
    fn superbox_parser_rejects_excessive_label() {
        let label = "x".repeat(MAX_LABEL_BYTES + 1);
        let store = superbox(&UUID_MANIFEST_STORE, &label, &[], None);

        assert!(matches!(
            parse_manifest_store(&store),
            Err(JumbfError::ResourceLimit(
                "JUMBF label exceeds verifier bound"
            ))
        ));
    }

    #[test]
    fn manifest_superboxes_enforce_manifest_count() {
        let manifests = (0..=MAX_MANIFESTS_PER_STORE)
            .map(|index| {
                superbox(
                    &UUID_MANIFEST,
                    &format!("urn:c2pa:manifest-{index}"),
                    &[],
                    None,
                )
            })
            .collect::<Vec<_>>();
        let store = build_manifest_store(&manifests);

        assert!(matches!(
            manifest_superboxes_from_store(&store),
            Err(JumbfError::ResourceLimit(
                "manifest count exceeds verifier bound"
            ))
        ));
    }

    #[test]
    fn superbox_parser_rejects_excessive_children() {
        let child = box_bytes(b"free", &[]);
        let children = vec![child; MAX_CHILD_BOXES_PER_SUPERBOX + 1];
        let store = superbox(&UUID_MANIFEST_STORE, "c2pa", &children, None);

        assert!(matches!(
            parse_manifest_store(&store),
            Err(JumbfError::ResourceLimit(
                "superbox child count exceeds verifier bound"
            ))
        ));
    }

    #[test]
    fn roundtrip_manifest_store() {
        let assertion = assertion_box("c2pa.actions.v2", &[0xa0], None); // empty CBOR map
        let claim = &[0xbf, 0xff]; // indefinite empty map
        let sig = &[0xd2, 0x84]; // dummy COSE-ish
        let manifest = build_manifest("urn:c2pa:test", &[assertion], claim, sig);
        let store = build_manifest_store(&[manifest]);

        let parsed = parse_manifest_store(&store).unwrap();
        assert_eq!(parsed.manifests.len(), 1);
        let m = &parsed.manifests[0];
        assert_eq!(m.label, "urn:c2pa:test");
        assert_eq!(m.assertions.len(), 1);
        assert_eq!(m.assertions[0].0, "c2pa.actions.v2");
        assert_eq!(m.claim_cbor, Some(&[0xbf, 0xff][..]));
        assert_eq!(m.signature_cose, Some(&[0xd2, 0x84][..]));
    }

    #[test]
    fn manifest_store_requires_exact_top_level_framing() {
        let manifest = build_manifest("urn:c2pa:framing", &[], &[0xa0], &[0xd2, 0x84]);
        let ordinary = build_manifest_store(&[manifest]);
        let extended = extended_box_bytes(&ordinary);

        assert_eq!(parse_manifest_store(&extended).unwrap().manifests.len(), 1);

        for mut framed in [ordinary.clone(), extended] {
            framed.extend_from_slice(b"suffix");
            assert!(matches!(
                parse_manifest_store(&framed),
                Err(JumbfError::TrailingBytes(6))
            ));
        }

        let mut size_to_end = ordinary;
        size_to_end[..4].copy_from_slice(&0u32.to_be_bytes());
        assert_eq!(
            parse_manifest_store(&size_to_end).unwrap().manifests.len(),
            1
        );
        size_to_end.extend_from_slice(b"suffix");
        assert!(parse_manifest_store(&size_to_end).is_err());
    }

    #[test]
    fn rejects_relabelled_manifest_store_root() {
        let manifest = build_manifest("urn:c2pa:root-label", &[], &[0xa0], &[0xd2, 0x84]);
        let store = superbox(&UUID_MANIFEST_STORE, "evil", &[manifest], None);

        assert!(matches!(
            parse_manifest_store(&store),
            Err(JumbfError::UnexpectedLabel {
                expected: LABEL_MANIFEST_STORE,
                found,
            }) if found == "evil"
        ));
        assert!(matches!(
            manifest_superboxes_from_store(&store),
            Err(JumbfError::UnexpectedLabel {
                expected: LABEL_MANIFEST_STORE,
                found,
            }) if found == "evil"
        ));
    }

    #[test]
    fn rejects_relabelled_assertion_store() {
        let manifest = build_manifest("urn:c2pa:assertion-label", &[], &[0xa0], &[0xd2, 0x84]);
        let mut store = build_manifest_store(&[manifest]);
        relabel_unique(&mut store, LABEL_ASSERTION_STORE, "evil.assertions");

        assert!(matches!(
            parse_manifest_store(&store),
            Err(JumbfError::UnexpectedLabel {
                expected: LABEL_ASSERTION_STORE,
                found,
            }) if found == "evil.assertions"
        ));
    }

    #[test]
    fn rejects_absent_assertion_store() {
        let claim = superbox(&UUID_CLAIM, LABEL_CLAIM_V2, &[cbor_box(&[0xa0])], None);
        let signature = superbox(
            &UUID_CLAIM_SIGNATURE,
            LABEL_CLAIM_SIGNATURE,
            &[cbor_box(&[0xd2, 0x84])],
            None,
        );
        let manifest = superbox(
            &UUID_MANIFEST,
            "urn:c2pa:missing-assertion-store",
            &[claim, signature],
            None,
        );
        let store = build_manifest_store(&[manifest]);

        assert!(matches!(
            parse_manifest_store(&store),
            Err(JumbfError::InvalidStructure(
                "manifest is missing required c2pa.assertions assertion store"
            ))
        ));
    }

    #[test]
    fn rejects_multiple_assertion_stores() {
        let first = superbox(&UUID_ASSERTION_STORE, LABEL_ASSERTION_STORE, &[], None);
        let second = superbox(&UUID_ASSERTION_STORE, LABEL_ASSERTION_STORE, &[], None);
        let claim = superbox(&UUID_CLAIM, LABEL_CLAIM_V2, &[cbor_box(&[0xa0])], None);
        let signature = superbox(
            &UUID_CLAIM_SIGNATURE,
            LABEL_CLAIM_SIGNATURE,
            &[cbor_box(&[0xd2, 0x84])],
            None,
        );
        let manifest = superbox(
            &UUID_MANIFEST,
            "urn:c2pa:multiple-assertion-stores",
            &[first, second, claim, signature],
            None,
        );
        let store = build_manifest_store(&[manifest]);

        assert!(matches!(
            parse_manifest_store(&store),
            Err(JumbfError::InvalidStructure(
                "manifest contains multiple assertion store superboxes"
            ))
        ));
    }

    #[test]
    fn rejects_relabelled_claim() {
        let manifest = build_manifest("urn:c2pa:claim-label", &[], &[0xa0], &[0xd2, 0x84]);
        let mut store = build_manifest_store(&[manifest]);
        relabel_unique(&mut store, LABEL_CLAIM_V2, "evil.claim.v2");

        assert!(matches!(
            parse_manifest_store(&store),
            Err(JumbfError::UnexpectedLabel {
                expected: "c2pa.claim or c2pa.claim.v2",
                found,
            }) if found == "evil.claim.v2"
        ));
    }

    #[test]
    fn rejects_relabelled_claim_signature() {
        let manifest = build_manifest("urn:c2pa:signature-label", &[], &[0xa0], &[0xd2, 0x84]);
        let mut store = build_manifest_store(&[manifest]);
        relabel_unique(&mut store, LABEL_CLAIM_SIGNATURE, "evil.signature");

        assert!(matches!(
            parse_manifest_store(&store),
            Err(JumbfError::UnexpectedLabel {
                expected: LABEL_CLAIM_SIGNATURE,
                found,
            }) if found == "evil.signature"
        ));
    }

    #[test]
    fn parses_canonical_v1_and_v2_claim_boxes() {
        for claim_label in [LABEL_CLAIM_V1, LABEL_CLAIM_V2] {
            let manifest = build_manifest_with_claim_label(
                &format!("urn:c2pa:{claim_label}"),
                &[],
                &[0xa0],
                &[0xd2, 0x84],
                claim_label,
            );
            let store = build_manifest_store(&[manifest]);

            let parsed = parse_manifest_store(&store).unwrap();
            let manifest = &parsed.manifests[0];
            assert_eq!(manifest.claim_count, 1);
            assert_eq!(manifest.claim_box_label.as_deref(), Some(claim_label));
            assert_eq!(manifest.claim_cbor, Some(&[0xa0][..]));
            assert_eq!(manifest.signature_cose, Some(&[0xd2, 0x84][..]));
        }
    }

    #[test]
    fn rejects_duplicate_signatures_in_any_order() {
        let assertion_store = superbox(&UUID_ASSERTION_STORE, "c2pa.assertions", &[], None);
        let claim = superbox(&UUID_CLAIM, "c2pa.claim.v2", &[cbor_box(&[0xa0])], None);
        let injected = superbox(
            &UUID_CLAIM_SIGNATURE,
            "c2pa.signature",
            &[cbor_box(&[0x01])],
            None,
        );
        let authentic = superbox(
            &UUID_CLAIM_SIGNATURE,
            "c2pa.signature",
            &[cbor_box(&[0xd2, 0x84])],
            None,
        );

        for (first, second) in [(injected.clone(), authentic.clone()), (authentic, injected)] {
            let manifest = superbox(
                &UUID_MANIFEST,
                "urn:c2pa:duplicate-signature",
                &[assertion_store.clone(), claim.clone(), first, second],
                None,
            );
            let store = build_manifest_store(&[manifest]);
            assert!(matches!(
                parse_manifest_store(&store),
                Err(JumbfError::AmbiguousLabel(label)) if label == "c2pa.signature"
            ));
        }
    }

    #[test]
    fn rejects_duplicate_direct_child_labels() {
        let assertion_store = superbox(&UUID_ASSERTION_STORE, "c2pa.assertions", &[], None);
        let claim = superbox(&UUID_CLAIM, "c2pa.claim.v2", &[cbor_box(&[0xa0])], None);
        let signature = superbox(
            &UUID_CLAIM_SIGNATURE,
            "c2pa.signature",
            &[cbor_box(&[0xd2, 0x84])],
            None,
        );
        let shared_first = superbox(&UUID_CBOR_CONTENT, "shared", &[], None);
        let shared_second = superbox(&UUID_CBOR_CONTENT, "shared", &[], None);

        let cases = [
            (
                "c2pa.claim.v2",
                vec![assertion_store.clone(), claim.clone(), claim, signature],
            ),
            ("shared", vec![shared_first, shared_second]),
        ];

        for (duplicate_label, children) in cases {
            let manifest = superbox(&UUID_MANIFEST, "urn:c2pa:duplicate-child", &children, None);
            let store = build_manifest_store(&[manifest]);
            assert!(matches!(
                parse_manifest_store(&store),
                Err(JumbfError::AmbiguousLabel(label)) if label == duplicate_label
            ));
        }
    }

    #[test]
    fn accepts_legacy_standard_manifest_uuid() {
        let standard = build_manifest("urn:c2pa:legacy", &[], &[0xa0], &[0xd2, 0x84]);
        let payload = parse_box(&standard, 0).unwrap().payload;
        let parsed = parse_superbox_payload(payload).unwrap();
        let assertion_store = superbox(&UUID_ASSERTION_STORE, LABEL_ASSERTION_STORE, &[], None);
        let claim = superbox(&UUID_CLAIM, LABEL_CLAIM_V2, &[cbor_box(&[0xa0])], None);
        let signature = superbox(
            &UUID_CLAIM_SIGNATURE,
            LABEL_CLAIM_SIGNATURE,
            &[cbor_box(&[0xd2, 0x84])],
            None,
        );
        assert_eq!(parsed.label, "urn:c2pa:legacy");
        let legacy = superbox(
            &UUID_LEGACY_MANIFEST,
            "urn:c2pa:legacy",
            &[assertion_store, claim, signature],
            None,
        );
        let store = build_manifest_store(&[legacy]);
        assert_eq!(parse_manifest_store(&store).unwrap().manifests.len(), 1);
    }

    #[test]
    fn parses_update_manifest_and_retains_its_kind() {
        let standard = build_manifest("urn:c2pa:update", &[], &[0xa0], &[0xd2, 0x84]);
        let payload = parse_box(&standard, 0).unwrap().payload;
        let parsed = parse_superbox_payload(payload).unwrap();
        let update = superbox(
            &UUID_UPDATE_MANIFEST,
            "urn:c2pa:update",
            &parsed
                .content
                .iter()
                .map(|(box_type, payload)| box_bytes(box_type, payload))
                .collect::<Vec<_>>(),
            None,
        );
        let store = build_manifest_store(&[update]);
        let parsed = parse_manifest_store(&store).unwrap();

        assert_eq!(parsed.manifests.len(), 1);
        assert_eq!(parsed.manifests[0].kind(), ManifestKind::Update);
    }

    #[test]
    fn rejects_unexpanded_compressed_manifest() {
        let manifest = superbox(&UUID_COMPRESSED_MANIFEST, "urn:c2pa:unsupported", &[], None);
        let store = build_manifest_store(&[manifest]);
        assert!(matches!(
            parse_manifest_store(&store),
            Err(JumbfError::UnsupportedManifestType("c2cm"))
        ));
    }

    #[test]
    fn rejects_non_requestable_or_illegal_labels() {
        let manifest = build_manifest("urn:c2pa:toggles", &[], &[0xa0], &[0xd2, 0x84]);
        let mut store = build_manifest_store(&[manifest]);
        let label_offset = store
            .windows(LABEL_ASSERTION_STORE.len())
            .position(|bytes| bytes == LABEL_ASSERTION_STORE.as_bytes())
            .unwrap();
        store[label_offset - 1] &= !TOGGLE_REQUESTABLE;
        assert!(matches!(
            parse_manifest_store(&store),
            Err(JumbfError::InvalidStructure(
                "C2PA JUMBF description is not labelled and requestable"
            ))
        ));

        let manifest = build_manifest("urn:c2pa:illegal", &[], &[0xa0], &[0xd2, 0x84]);
        let mut store = build_manifest_store(&[manifest]);
        relabel_unique(&mut store, "urn:c2pa:illegal", "urn/c2pa:illegal");
        assert!(matches!(
            parse_manifest_store(&store),
            Err(JumbfError::InvalidStructure(
                "JUMBF label contains a forbidden character"
            ))
        ));
    }

    #[test]
    fn rejects_multiple_claim_or_signature_content_boxes() {
        let assertion_store = superbox(&UUID_ASSERTION_STORE, LABEL_ASSERTION_STORE, &[], None);
        for (uuid, label, expected) in [
            (
                UUID_CLAIM,
                LABEL_CLAIM_V2,
                "claim superbox must contain exactly one CBOR content box",
            ),
            (
                UUID_CLAIM_SIGNATURE,
                LABEL_CLAIM_SIGNATURE,
                "claim signature superbox must contain exactly one CBOR content box",
            ),
        ] {
            let malformed = superbox(&uuid, label, &[cbor_box(&[0xa0]), cbor_box(&[0xa1])], None);
            let counterpart = if uuid == UUID_CLAIM {
                superbox(
                    &UUID_CLAIM_SIGNATURE,
                    LABEL_CLAIM_SIGNATURE,
                    &[cbor_box(&[0xd2, 0x84])],
                    None,
                )
            } else {
                superbox(&UUID_CLAIM, LABEL_CLAIM_V2, &[cbor_box(&[0xa0])], None)
            };
            let manifest = superbox(
                &UUID_MANIFEST,
                "urn:c2pa:extra-content",
                &[assertion_store.clone(), malformed, counterpart],
                None,
            );
            let store = build_manifest_store(&[manifest]);
            assert!(matches!(
                parse_manifest_store(&store),
                Err(JumbfError::InvalidStructure(detail)) if detail == expected
            ));
        }
    }

    #[test]
    fn uuid_prefixes_correct() {
        assert_eq!(&UUID_MANIFEST_STORE[..4], b"c2pa");
        assert_eq!(&UUID_MANIFEST[..4], b"c2ma");
        assert_eq!(&UUID_CLAIM[..4], b"c2cl");
        assert_eq!(&UUID_MANIFEST_STORE[4..], &UUID_SUFFIX);
    }

    #[test]
    fn rejects_truncated() {
        assert!(matches!(
            parse_box(&[0, 0, 0], 0),
            Err(JumbfError::TruncatedHeader(_))
        ));
    }

    #[test]
    fn rejects_length_overrun() {
        // claims size 0xffff but only a few bytes present
        let data = [0x00, 0x00, 0xff, 0xff, b'j', b'u', b'm', b'b'];
        assert!(matches!(
            parse_box(&data, 0),
            Err(JumbfError::LengthOverrun(_))
        ));
    }

    #[test]
    fn rejects_duplicate_manifest_labels() {
        let claim = &[0xa0];
        let sig = &[0xd2, 0x84];
        let first = build_manifest("urn:c2pa:duplicate", &[], claim, sig);
        let second = build_manifest("urn:c2pa:duplicate", &[], claim, sig);
        let store = build_manifest_store(&[first, second]);
        assert!(matches!(
            parse_manifest_store(&store),
            Err(JumbfError::AmbiguousLabel(label)) if label == "urn:c2pa:duplicate"
        ));
    }

    #[test]
    fn rejects_duplicate_assertion_labels() {
        let first = assertion_box("c2pa.actions.v2", &[0xa0], None);
        let second = assertion_box("c2pa.actions.v2", &[0xa0], None);
        let manifest = build_manifest("urn:c2pa:test", &[first, second], &[0xa0], &[0xd2, 0x84]);
        let store = build_manifest_store(&[manifest]);
        assert!(matches!(
            parse_manifest_store(&store),
            Err(JumbfError::AmbiguousLabel(label)) if label == "c2pa.actions.v2"
        ));
    }

    #[test]
    fn manifest_store_accepts_exactly_one_trailing_free_box() {
        let manifest = build_manifest("urn:c2pa:padded", &[], &[0xa0], &[0xd2, 0x84]);
        let store = build_manifest_store(&[manifest]);
        let mut padded = store.clone();
        padded.extend_from_slice(&8u32.to_be_bytes());
        padded.extend_from_slice(b"free");

        assert_eq!(parse_manifest_store(&padded).unwrap().manifests.len(), 1);

        let mut wrong_type = store.clone();
        wrong_type.extend_from_slice(&8u32.to_be_bytes());
        wrong_type.extend_from_slice(b"skip");
        assert!(parse_manifest_store(&wrong_type).is_err());

        let mut two_free = padded;
        two_free.extend_from_slice(&8u32.to_be_bytes());
        two_free.extend_from_slice(b"free");
        assert!(parse_manifest_store(&two_free).is_err());
    }

    #[test]
    fn private_description_requires_one_valid_salt_box() {
        for salt_len in [0, 15, 17, 31, 33] {
            let salt = vec![7u8; salt_len];
            let assertion = assertion_box("c2pa.actions.v2", &[0xa0], Some(&salt));
            let manifest =
                build_manifest("urn:c2pa:bad-salt", &[assertion], &[0xa0], &[0xd2, 0x84]);
            let store = build_manifest_store(&[manifest]);
            assert!(
                matches!(
                    parse_manifest_store(&store),
                    Err(JumbfError::InvalidStructure(_))
                ),
                "salt length {salt_len} must be rejected"
            );
        }

        for salt_len in [16, 32] {
            let salt = vec![7u8; salt_len];
            let assertion = assertion_box("c2pa.actions.v2", &[0xa0], Some(&salt));
            let manifest =
                build_manifest("urn:c2pa:good-salt", &[assertion], &[0xa0], &[0xd2, 0x84]);
            let store = build_manifest_store(&[manifest]);
            assert!(
                parse_manifest_store(&store).is_ok(),
                "salt length {salt_len} must be accepted"
            );
        }

        let assertion = assertion_box("c2pa.actions.v2", &[0xa0], None);
        let manifest = build_manifest(
            "urn:c2pa:missing-salt",
            &[assertion],
            &[0xa0],
            &[0xd2, 0x84],
        );
        let mut store = build_manifest_store(&[manifest]);
        let label_offset = store
            .windows(b"c2pa.actions.v2".len())
            .position(|bytes| bytes == b"c2pa.actions.v2")
            .unwrap();
        store[label_offset - 1] |= TOGGLE_PRIVATE;
        assert!(matches!(
            parse_manifest_store(&store),
            Err(JumbfError::InvalidStructure(_))
        ));
    }

    #[test]
    fn json_assertion_content_is_exposed_with_its_type() {
        let json = br#"{"@context":"https://schema.org"}"#;
        let assertion = superbox(
            &UUID_JSON_CONTENT,
            "c2pa.metadata",
            &[box_bytes(TYPE_JSON, json)],
            None,
        );
        let manifest = build_manifest("urn:c2pa:json", &[assertion], &[0xa0], &[0xd2, 0x84]);
        let store = build_manifest_store(&[manifest]);
        let parsed = parse_manifest_store(&store).unwrap();
        let manifest = &parsed.manifests[0];

        assert_eq!(manifest.assertions[0].1, json);
        assert_eq!(
            manifest.assertion_content_type("c2pa.metadata"),
            Some(AssertionContentType::Json)
        );
    }

    #[test]
    fn compressed_store_expands_raw_brotli_and_preserves_hash_domains() {
        let manifest = build_manifest("urn:c2pa:compressed", &[], &[0xa0], &[0xd2, 0x84]);
        let compressed = compress_manifest(&manifest).unwrap();
        let stored_content = superbox_content(&compressed).unwrap().to_vec();
        let store = build_manifest_store(&[compressed]);

        let expanded = expand_store(&store).unwrap();
        assert!(expanded.expanded());
        assert_eq!(
            parse_manifest_store(expanded.bytes()).unwrap().manifests[0].label,
            "urn:c2pa:compressed"
        );
        assert_eq!(expanded.stored_content(0), Some(stored_content.as_slice()));
    }

    #[test]
    fn compressed_update_follows_the_plain_update_path() {
        let update = superbox(
            &UUID_UPDATE_MANIFEST,
            "urn:c2pa:update",
            &[superbox(
                &UUID_ASSERTION_STORE,
                LABEL_ASSERTION_STORE,
                &[],
                None,
            )],
            None,
        );
        let compressed = compress_manifest_kind(&update).unwrap();
        let stored_content = superbox_content(&compressed).unwrap().to_vec();
        let store = build_manifest_store(&[compressed]);
        let expanded = expand_store(&store).unwrap();

        let parsed = parse_manifest_store(expanded.bytes()).unwrap();
        assert_eq!(parsed.manifests[0].kind(), ManifestKind::Update);
        assert_eq!(expanded.stored_content(0), Some(stored_content.as_slice()));

        let plain_store = build_manifest_store(&[update]);
        let plain = parse_manifest_store(&plain_store).unwrap();
        assert_eq!(plain.manifests[0].kind(), ManifestKind::Update);
    }

    #[test]
    fn corrupt_or_recursive_compressed_manifest_is_rejected_without_recursion() {
        let corrupt = superbox(
            &UUID_COMPRESSED_MANIFEST,
            "urn:c2pa:corrupt",
            &[box_bytes(TYPE_BROB, b"not a brotli stream")],
            None,
        );
        assert!(matches!(
            expand_store(&build_manifest_store(&[corrupt])),
            Err(JumbfError::CompressedManifestInvalid { .. })
        ));

        let inner = superbox(
            &UUID_COMPRESSED_MANIFEST,
            "urn:c2pa:recursive",
            &[box_bytes(TYPE_BROB, b"nested")],
            None,
        );
        let recursive = compress_manifest_kind(&inner).unwrap();
        assert!(matches!(
            expand_store(&build_manifest_store(&[recursive])),
            Err(JumbfError::CompressedManifestInvalid { .. })
        ));
    }

    #[test]
    fn compressed_manifest_inflate_is_bounded_and_label_bound() {
        let oversized = vec![0u8; MAX_DECOMPRESSED_MANIFEST_BYTES + 1];
        let compressed = superbox(
            &UUID_COMPRESSED_MANIFEST,
            "urn:c2pa:oversized",
            &[box_bytes(TYPE_BROB, &brotli_compress(&oversized))],
            None,
        );
        let error = match expand_store(&build_manifest_store(&[compressed])) {
            Err(error) => error,
            Ok(_) => panic!("oversized expansion must fail"),
        };
        assert!(matches!(
            error,
            JumbfError::CompressedManifestInvalid { reason, .. }
                if matches!(reason.as_ref(), JumbfError::DecompressedTooLarge)
        ));

        let manifest = build_manifest("urn:c2pa:inner", &[], &[0xa0], &[0xd2, 0x84]);
        let mismatched = superbox(
            &UUID_COMPRESSED_MANIFEST,
            "urn:c2pa:outer",
            &[box_bytes(TYPE_BROB, &brotli_compress(&manifest))],
            None,
        );
        let error = match expand_store(&build_manifest_store(&[mismatched])) {
            Err(error) => error,
            Ok(_) => panic!("mismatched labels must fail"),
        };
        assert!(matches!(
            error,
            JumbfError::CompressedManifestInvalid { reason, .. }
                if matches!(
                    reason.as_ref(),
                    JumbfError::CompressedManifestLabelMismatch { .. }
                )
        ));
    }

    /// The Encypher signer writes the `brob` payload in the JPEG XL form: the
    /// 4-byte original box type (`jumb`) followed by the Brotli stream of the
    /// whole manifest superbox. That layout expands too, with the same stored
    /// hash domain as the literal layout.
    #[test]
    fn type_prefixed_brob_payload_expands_with_its_stored_hash_domain() {
        let manifest = build_manifest("urn:c2pa:prefixed", &[], &[0xa0], &[0xd2, 0x84]);
        let compressed = compress_manifest_type_prefixed(&manifest).unwrap();
        let stored_content = superbox_content(&compressed).unwrap().to_vec();
        let store = build_manifest_store(&[compressed]);

        let expanded = expand_store(&store).unwrap();
        let parsed = parse_manifest_store(expanded.bytes()).unwrap();
        assert_eq!(parsed.manifests[0].label, "urn:c2pa:prefixed");
        assert_eq!(expanded.stored_content(0), Some(stored_content.as_slice()));
    }

    /// A prefixed payload that inflates past the bound fails closed: it is
    /// never retried as a literal payload.
    #[test]
    fn type_prefixed_brob_payload_is_bounded() {
        let oversized = vec![0u8; MAX_DECOMPRESSED_MANIFEST_BYTES + 1];
        let mut payload = TYPE_JUMB.to_vec();
        payload.extend_from_slice(&brotli_compress(&oversized));
        let compressed = superbox(
            &UUID_COMPRESSED_MANIFEST,
            "urn:c2pa:prefixed-oversized",
            &[box_bytes(TYPE_BROB, &payload)],
            None,
        );
        let error = match expand_store(&build_manifest_store(&[compressed])) {
            Err(error) => error,
            Ok(_) => panic!("oversized expansion must fail"),
        };
        assert!(matches!(
            error,
            JumbfError::CompressedManifestInvalid { reason, .. }
                if matches!(reason.as_ref(), JumbfError::DecompressedTooLarge)
        ));
    }
}