encypher-c2pa 1.10.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
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
// Copyright 2026 Encypher Corporation
// SPDX-License-Identifier: Apache-2.0

//! Local-first, verification-only C2PA SDK.
//!
//! The public facade reads caller-provided bytes and reports integrity separately
//! from trust. Network access occurs only after saved failure telemetry consent
//! or an explicit per-call override.

#![forbid(unsafe_code)]
// The six modules below are the verification kernel. They derive from the
// engine that runs in Encypher's production signing service, and are kept as
// six crate-named directories so the two trees stay readable side by side.
//
// They are a derivative, not a copy, and the difference is the point of this
// repository: the production tree carries manifest construction and container
// writing, and this one does not. The line counts differ accordingly and by
// design - production `c2pa-formats` is roughly twice this one.
//
// No automated comparison exists between the two trees. An earlier version of
// this comment said a private drift gate compared them; there is no such gate
// in the monorepo, and saying otherwise credited this code with a control
// nobody had written. Divergence is currently caught by review alone. If that
// is not good enough - and for a security boundary it probably is not - the
// thing to build is a projection that maps production paths onto this layout
// and diffs the shared functions, which would have to model the intended
// removals rather than expect equality.
//
// They were separate published crates until this change. That made 22,890 lines
// of implementation into semver-bound public API with no consumer - 81% of the
// reviewed public surface - and it is why manifest construction needed a Cargo
// feature to hide it. As private modules they are unreachable by construction,
// so the writers are simply `cfg(test)` and no feature can expose them.
//
// Suppressing `dead_code`/`unused_imports` here is deliberate and narrow to
// these mirrors.
// The public verifier exercises a subset of the kernel: the rest is reached by
// the production signer (`c2pa-sign`, `c2pa-cli` on the private side). Deleting
// what this crate happens not to call would fork the shared source and destroy
// the property the mirror exists for.
//
// `allow` rather than `expect`, which would be preferable: the dead set differs
// between the two compilations of this crate. Under `cargo build` the writers
// are absent and much of the kernel is unused; under `cargo test` the
// `cfg(test)` code exercises them. A single `expect` cannot be fulfilled in
// both, so it fails the `--all-targets` lint run. `allow` is scoped to these
// six mirrors and to these two lints only; nothing else in the crate is
// exempted, and the surface gate is what actually holds the boundary.
#[path = "c2pa-cbor/lib.rs"]
#[allow(dead_code, reason = "production kernel mirror")]
mod c2pa_cbor;
#[path = "c2pa-core/lib.rs"]
#[allow(dead_code, unused_imports, reason = "production kernel mirror")]
mod c2pa_core;
#[path = "c2pa-crypto/lib.rs"]
#[allow(dead_code, unused_imports, reason = "production kernel mirror")]
mod c2pa_crypto;
#[path = "c2pa-formats/lib.rs"]
#[allow(dead_code, unused_imports, reason = "production kernel mirror")]
mod c2pa_formats;
#[path = "c2pa-trust/lib.rs"]
#[allow(dead_code, unused_imports, reason = "production kernel mirror")]
mod c2pa_trust;
#[path = "c2pa-validate/lib.rs"]
#[allow(dead_code, unused_imports, reason = "production kernel mirror")]
mod c2pa_validate;
pub use c2pa_validate::external_discovery::{
    locate_external_resources, locate_external_resources_with_manifest_store,
    ExternalDidDocumentRequest, ExternalResourceKind, ExternalResourcePlan,
    ExternalResourceRequest, ExternalResourceStopReason, GraphLimitKind,
};
pub use c2pa_validate::ingredient_graph::{GraphInputs, GraphLimits};
pub use c2pa_validate::refs::{ExternalResource, ExternalResources};
mod config_dir;
mod default_trust;
mod ertmp;
mod ertmp_wire;
mod native_online;
mod online;
mod online_consent;
pub use ertmp::{
    verify_ertmp, verify_ertmp_with_options, ErtmpEvent, ErtmpInput, ErtmpManifestReport,
    ErtmpMediaType, ErtmpSegmentReport, ErtmpTrack, ErtmpVerificationReport,
};
pub use ertmp_wire::{
    ertmp_input_from_flv, ertmp_input_from_rtmp_connections, ErtmpConnectionContext,
    ErtmpWireError, ErtmpWireEventContext, ErtmpWireInput, ErtmpWireLimits, FlvWireOptions,
    RtmpWireConnection,
};
mod soft_binding;
pub use soft_binding::{
    request_soft_binding_receipt_verification, resolve_soft_binding, RecoveredSoftBindingManifest,
    SoftBindingAlgorithm, SoftBindingAlgorithms, SoftBindingCapabilities,
    SoftBindingDisclosureConsent, SoftBindingDiscovery, SoftBindingFetchRequest,
    SoftBindingHttpMethod, SoftBindingMatch, SoftBindingQuery, SoftBindingReceiptEvidence,
    SoftBindingReceiptVerificationSession, SoftBindingResolution, SoftBindingResolverOptions,
    SoftBindingResolverSession,
};
mod stream;
pub use stream::{
    verify_stream, verify_stream_with_options, SegmentReport, StreamEncapsulation, StreamMethod,
    StreamVerificationReport,
};
#[cfg(feature = "caller-verified-binding")]
mod caller_verified_binding;
mod telemetry;
mod telemetry_consent;
pub use c2pa_trust::TrustSource;
#[cfg(feature = "caller-verified-binding")]
pub use caller_verified_binding::{
    binding_target, verify_fragmented_with_cawg, verify_manifest_store_only_with_cawg,
    verify_with_caller_verified_binding, verify_with_caller_verified_binding_and_cawg,
    verify_with_cawg, verify_with_manifest_store_and_cawg, CallerBindingEvidence,
    CallerBindingVerdict, CawgEvaluation, CawgEvaluator, CawgProfile, CawgStoreHost,
    ManifestBindingTarget,
};
pub use config_dir::config_directory;
pub use default_trust::SNAPSHOT_DATE as DEFAULT_TRUST_SNAPSHOT_DATE;

pub use online::{NetworkReport, NetworkRequest};
pub use online_consent::{
    allow_interactive_online_consent, online_preference, set_online_preference, OnlinePreference,
    OnlinePreferenceError,
};
pub use telemetry::{
    validation_failure_telemetry, TelemetryOptions, ValidationFailureTelemetry,
    DEFAULT_TELEMETRY_ENDPOINT,
};
pub use telemetry_consent::{
    prompt_for_telemetry_consent, set_telemetry_enabled, telemetry_preference,
    TelemetryPreferenceError,
};

use std::collections::HashMap;
use std::fs::{self, OpenOptions};
use std::io::{self, Read};
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use std::path::Path;

use crate::c2pa_core::{
    spec::{canonicalize_mime, mimes_for_version},
    ComplianceLevel, EngineProfile, OperatingMode, SpecVersion,
};
use crate::c2pa_trust::{AnchorPurpose, CawgTrustSource, TrustList};
use crate::c2pa_validate::{
    verify_fragmented_with_cawg_options_and_expected_seeks_safe as verify_fragmented_safe,
    verify_with_cawg_options_and_graph_inputs_safe as verify_graph_safe,
    verify_with_cawg_options_safe as verify_safe, StatusCode as CoreStatus,
    ValidationResults as CoreResults, VerifyInput, ASSERTION_BMFF_HASH_MALFORMED,
    ASSERTION_BMFF_HASH_MATCH, ASSERTION_BMFF_HASH_MISMATCH, ASSERTION_BOXES_HASH_MALFORMED,
    ASSERTION_BOXES_HASH_MATCH, ASSERTION_BOXES_HASH_MISMATCH, ASSERTION_COLLECTION_HASH_MALFORMED,
    ASSERTION_COLLECTION_HASH_MATCH, ASSERTION_COLLECTION_HASH_MISMATCH, ASSERTION_DATA_HASH_MATCH,
    ASSERTION_DATA_HASH_MISMATCH, ASSERTION_MULTI_ASSET_HASH_MALFORMED,
    ASSERTION_MULTI_ASSET_HASH_MATCH, ASSERTION_MULTI_ASSET_HASH_MISMATCH,
    CLAIM_HARD_BINDINGS_MISSING, CLAIM_SIGNATURE_MISMATCH, CLAIM_SIGNATURE_MISSING,
    CLAIM_SIGNATURE_VALIDATED, SIGNING_CREDENTIAL_INVALID, SIGNING_CREDENTIAL_OCSP_NOT_REVOKED,
    SIGNING_CREDENTIAL_OCSP_REVOKED, SIGNING_CREDENTIAL_TRUSTED, SIGNING_CREDENTIAL_UNTRUSTED,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use time::{format_description::well_known::Rfc3339, OffsetDateTime};

pub const REPORT_SCHEMA_VERSION: &str = "1.0";
/// Report `profile` of the explicitly selected C2PA 2.2 policy.
pub const C2PA_PROFILE_2_2: &str = "c2pa-2.2";
/// Report `profile` of the default C2PA 2.4 validation policy.
pub const C2PA_PROFILE: &str = "c2pa-2.4";
/// Report `profile` of the explicitly selected C2PA 2.5 policy.
pub const C2PA_PROFILE_2_5: &str = "c2pa-2.5";
/// Every value [`VerifyOptions::spec_version`] accepts. `None` means `"2.4"`.
pub const SPEC_VERSIONS: &[&str] = &SpecVersion::PUBLIC_POLICY_STRINGS;
const MAX_MANIFEST_STORE_BYTES: usize = 64 * 1024 * 1024;
const MAX_PATH_ASSET_BYTES: u64 = 128 * 1024 * 1024;
/// Largest DER `OCSPResponse` accepted as caller-supplied evidence.
const MAX_OCSP_EVIDENCE_BYTES: usize = 64 * 1024;
/// Largest external-data payload accepted as caller-supplied evidence.
const MAX_EXTERNAL_DATA_EVIDENCE_BYTES: usize = 64 * 1024 * 1024;

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct VerifyOptions {
    /// PEM bundle of claim-signing trust anchors.
    pub trust_pem: Option<String>,
    /// Claim-signing trust lists with reliable source metadata for C2PA 2.5
    /// crJSON. Each source remains separate until the matching anchor is known.
    pub claim_trust_sources: Option<Vec<TrustListSource>>,
    /// PEM bundle of timestamp-authority trust anchors.
    pub tsa_trust_pem: Option<String>,
    /// Timestamp-authority trust lists with reliable source metadata for C2PA
    /// 2.5 crJSON. These certificates never enter the claim-signing store.
    pub tsa_trust_sources: Option<Vec<TrustListSource>>,
    /// PEM bundle of directly allowed end-entity certificates.
    pub allowed_list_pem: Option<String>,
    /// PEM bundle of trust anchors for CAWG named-actor (identity) X.509
    /// credentials. `None` leaves identity signers untrusted (their
    /// well-formedness is still validated).
    pub cawg_trust_pem: Option<String>,
    /// PEM bundle of directly allowed CAWG end-entity certificates.
    pub cawg_allowed_certs_pem: Option<String>,
    /// Require an `id-kp-documentSigning` CAWG credential to chain to a
    /// configured anchor or appear on the allowed list. `None` keeps the
    /// default, `true`.
    pub cawg_document_signing_require_anchor: Option<bool>,
    /// Typed CAWG trust configurations, one per source. Each carries its
    /// profile and its own trust window; see [`CawgTrustConfiguration`].
    /// Appended after `cawg_trust_pem`/`cawg_allowed_certs_pem`, in order.
    pub cawg_trust_configurations: Option<Vec<CawgTrustConfiguration>>,
    /// RFC 3339 start of trust for caller-supplied PEM anchors. Before this
    /// instant those anchors do not validate a signature, whatever the anchor
    /// certificate's own `notBefore` says. Bundled snapshots and typed
    /// `cawg_trust_configurations` are unaffected.
    pub trust_anchor_not_before: Option<String>,
    /// RFC 3339 end of trust for caller-supplied PEM anchors. After this
    /// instant those anchors no longer validate a signature. Bundled snapshots
    /// and typed `cawg_trust_configurations` are unaffected.
    pub trust_anchor_not_after: Option<String>,
    /// Disable the bundled C2PA, IPTC, and Encypher trust snapshots. By
    /// default, caller-supplied PEM bundles extend those snapshots; setting
    /// this to `true` evaluates only caller-supplied trust material.
    pub no_default_trust: bool,
    /// Pinned offline DID-document store for CAWG ICA issuers, keyed by
    /// primary DID (no fragment). Resolution never touches the network.
    pub cawg_did_documents: Option<HashMap<String, Value>>,
    /// ICA issuer DIDs trusted directly by the caller.
    pub cawg_ica_trusted_issuers: Option<Vec<String>>,
    /// Trusted DID controller anchors. Issuers may trace to these anchors
    /// through `controller` links in caller-pinned DID documents.
    pub cawg_ica_trust_anchors: Option<Vec<String>>,
    /// Offline, decompressed revocation bitstrings keyed by
    /// `credentialStatus.statusListCredential` URI and encoded as standard
    /// base64. Missing lists fail closed without network access.
    pub cawg_ica_status_lists: Option<HashMap<String, String>>,
    /// OCSP responses a caller obtained online, keyed by the lowercase hex
    /// SHA-256 of the certificate's DER and encoded as standard base64 of the
    /// DER `OCSPResponse`. An empty decoded value is the sentinel for a
    /// response body that arrived but was discarded under a size bound; it is
    /// received, unusable evidence rather than an unreachable responder.
    ///
    /// The SDK never fetches these for you at this layer: supply them from
    /// your own OCSP client, or let the SDK's consent-gated fetcher do it. A
    /// response is trusted no further than any other input - it must still be
    /// signed by an authorized responder for the certificate in question, and
    /// it is evaluated under the C2PA 2.4 and CAWG 1.3 online rules.
    pub ocsp_responses: Option<HashMap<String, String>>,
    /// Certificates whose OCSP responder was queried but delivered no
    /// response, by the same lowercase hex SHA-256 key. A response that
    /// arrived but was unusable belongs in `ocsp_responses`.
    ///
    /// Each entry registers `signingCredential.ocsp.inaccessible` or, for a
    /// CAWG identity, `cawg.x509.ocsp.inaccessible`, in place of the
    /// `ocsp.skipped` code a purely offline run reports.
    pub ocsp_unreachable: Option<Vec<String>>,
    /// Content of cloud-data and hashed external-reference assertions, keyed
    /// by the URI the assertion declares and encoded as standard base64.
    ///
    /// The bytes are hashed against the assertion's own `alg`/`hash` pair
    /// before anything else is done with them.
    pub external_data: Option<HashMap<String, String>>,
    /// Media types observed while retrieving `external_data`, keyed by the
    /// same URI. Linked-resource integrity uses this to evaluate `dc:format`;
    /// bytes without an observed type cannot be reported as a format match.
    pub external_data_media_types: Option<HashMap<String, String>>,
    /// External-resource URIs for which retrieval was attempted but yielded no
    /// usable body. Linked-resource integrity reports these as `inaccessible`
    /// rather than as resources the validator chose to skip.
    pub external_data_unreachable: Option<Vec<String>>,
    /// Zero-based indexes into supplied fragments or stream segments where the
    /// player expects a discontinuity. Values must be unique, strictly
    /// increasing, and in bounds. Ignored by single-asset verification.
    pub expected_seek_positions: Vec<usize>,
    /// C2PA validation policy: `"2.2"`, `"2.4"`, or `"2.5"`. `None` is the
    /// default and is identical to `"2.4"`, preserving current behavior and
    /// report bytes. The caller selects this policy; a claim's declared
    /// `specVersion` never selects or upgrades it.
    ///
    /// `"2.5"` validates under the published C2PA 2.5 standard (specs-core
    /// tag `2.5`, `d538a737`): its text-carrier locating rules, padding admission,
    /// action and assertion-metadata time checks, `relatedAssertions`, linked
    /// resource integrity, `claim.actions.missing`,
    /// `manifest.inaccessible.malformed`, BMFF hash rules, and the ESP claim
    /// signature algorithms. Reports carry `profile: "c2pa-2.5"`. With
    /// `strict_conformance`, 2.5 uses strict technical validation under the
    /// core-spec compliance bar; this is not a certified or published
    /// Conformance Program profile. It also reads the carriers 2.5 adds
    /// (append-only text, WARC, MIDI, TTML, ONNX, SafeTensors, Parquet,
    /// BlockFact, WebVTT and other structured text) and validates
    /// `c2pa.hash.segment` bindings; see [`supported_mime_types_for`].
    ///
    /// Any other value fails with [`Error::UnsupportedSpecVersion`] before
    /// asset I/O. The policy is never inferred from what a manifest declares.
    pub spec_version: Option<String>,
    /// Apply strict technical validation. Under the default 2.4 policy this is
    /// the C2PA 2.4 Conformance Program posture, including its upgraded SHOULD
    /// requirements. Under the 2.5 policy it selects conformance mode with the
    /// core-spec compliance bar and strict diagnostics; it does not claim
    /// certified scope or an unpublished 2.5 Conformance Program. The flag
    /// also requires CAWG Identity 1.3 deterministic `signer_payload` CBOR; the
    /// default accepts the CAWG 1.1 field order with
    /// `com.encypher.cawg.legacyProfile`.
    pub strict_conformance: bool,
    /// Refuse the CAWG field-order `signer_payload` encoding that c2pa-rs
    /// writes, without applying the rest of the conformance posture. When
    /// unset, the default accepts it with the informational
    /// `com.encypher.cawg.legacyProfile`; `strict_conformance` refuses it
    /// either way.
    pub cawg_strict_encoding: bool,
    /// RFC 3339 validation instant. Current UTC time is used when omitted.
    pub validation_time: Option<String>,
    /// Trusted presentation-assessment instants for stream segments, RFC 3339,
    /// exactly one per supplied segment and in the same order. Entry `i` is
    /// the instant at which segment `i`'s C2PA 2.4 session-key validity window
    /// is judged. `validation_time` still governs certificate and trust-list
    /// evaluation of the init manifest; these instants never move that clock.
    ///
    /// The caller vouches for every entry. Supply each from your own trusted
    /// record of when that segment was presented, such as an ingest log or a
    /// packager clock you operate. The verifier never derives them from a
    /// segment's own signed `iat`: that self-asserted time remains an
    /// additional check inside the key window and never substitutes for the
    /// caller's instant. `None` assesses every segment at `validation_time`,
    /// which itself defaults to now. A time stamp on the init manifest proves
    /// when the init segment was signed; it does not time stamp later
    /// segments, so a historical archive needs these instants to verify
    /// segments whose keys have since expired.
    ///
    /// Sequence continuity is still enforced across the whole supplied run, so
    /// segments signed under different session keys, each valid at its own
    /// instant, verify as one unbroken stream. Applies only to session-key
    /// live streams verified through [`verify_stream_with_options`]; a
    /// Merkle-bound or per-segment stream refuses it, as does
    /// [`verify_fragmented_with_options`]. Single-asset verification ignores
    /// it. A malformed entry, or a count that differs from the number of
    /// segments supplied, fails the call before any segment is judged.
    pub stream_presentation_times: Option<Vec<String>>,
    /// Failure telemetry override. `None` uses the saved per-user preference.
    pub telemetry: TelemetryOptions,
    /// Allow this verification to fetch what the asset references: a manifest
    /// store held elsewhere, certificate revocation status, a `did:web`
    /// document, externally stored assertion content. `None` reads the
    /// `ENCYPHER_C2PA_ONLINE` environment variable and otherwise stays
    /// offline.
    ///
    /// A library call never consults the saved per-user choice and never
    /// prompts: the caller decides here, or the operator decides through the
    /// environment. Whatever is fetched is used as evidence only. The verdict
    /// is still reached by the same offline kernel.
    pub online: Option<bool>,
    /// Intranet mode: let online checks contact loopback, private, and
    /// link-local addresses, and accept plaintext `http` for every purpose
    /// rather than for OCSP alone.
    ///
    /// Off by default: a file that names an internal host would otherwise turn
    /// this verifier into a probe of the network it runs on. Turn it on for a
    /// deployment whose manifest repository or OCSP responder lives on a
    /// private address, and for tests that serve from `127.0.0.1`. Setting it
    /// declares that this machine's own network is trusted; do not set it on a
    /// host that verifies files sent in by strangers.
    pub online_allow_private_networks: bool,
}

/// Caller-supplied external resource evidence decoded while validating all
/// verification options.
///
/// Network adapters that retain an owned [`ExternalResources`] provider use
/// this to avoid decoding large base64 bodies again before final verification.
#[derive(Debug, Default)]
pub struct ValidatedExternalData {
    /// Decoded bodies keyed by the URI declared in signed manifest content.
    pub data: HashMap<String, Vec<u8>>,
    /// Observed media types keyed by the same URI.
    pub media_types: HashMap<String, String>,
    /// URIs the caller attempted but could not retrieve.
    pub unreachable: Vec<String>,
}

impl VerifyOptions {
    /// Resolve and validate every option without reading or parsing an asset.
    ///
    /// Path-based adapters call this before opening asset files so malformed
    /// trust material and invalid validation instants fail deterministically.
    /// The per-segment count of `stream_presentation_times` needs the segments
    /// and is checked by the stream entry point itself.
    pub fn validate(&self) -> Result<(), Error> {
        self.resolve_and_validate()?;
        Ok(())
    }

    /// Validate every option and retain decoded external-data evidence.
    ///
    /// This has the same error ordering and checks as [`Self::validate`].
    pub fn validate_with_external_data(&self) -> Result<ValidatedExternalData, Error> {
        let resolved = self.resolve_and_validate()?;
        Ok(ValidatedExternalData {
            data: resolved.external_data,
            media_types: resolved.external_data_media_types,
            unreachable: resolved.external_data_unreachable,
        })
    }

    fn resolve_and_validate(&self) -> Result<ResolvedOptions, Error> {
        let resolved = ResolvedOptions::resolve(self)?;
        for (index, raw) in self.stream_presentation_times.iter().flatten().enumerate() {
            parse_stream_presentation_time(raw, index)?;
        }
        Ok(resolved)
    }
}

/// One caller-supplied trust list with provenance retained for C2PA 2.5 crJSON.
///
/// `uri` identifies the list and is never fetched. `source_type` is emitted as
/// the required `type` member. Only a source whose certificate actually
/// accepted the claim signer or timestamp signer may be reported.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TrustListSource {
    /// URI identifying this trust list. It need not be resolvable.
    pub uri: String,
    /// Standard trust-list type, read from the `type` JSON member.
    #[serde(rename = "type")]
    pub source_type: String,
    /// Optional list-specific identifier.
    #[serde(default)]
    pub identifier: Option<String>,
    /// PEM certificates supplied by this source.
    pub certificates_pem: String,
    /// Inclusive RFC 3339 start of this source's trust window.
    #[serde(default)]
    pub not_before: Option<String>,
    /// Inclusive RFC 3339 end of this source's trust window.
    #[serde(default)]
    pub not_after: Option<String>,
}

/// One entry of the CAWG Identity 1.3 trust configuration a caller supplies.
///
/// Certificates are placed by what they are, not by the list they came from:
/// a CA certificate, or a self-issued X.509 v1 certificate without
/// BasicConstraints, anchors chains; any other certificate is accepted only
/// by direct match.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CawgTrustConfiguration {
    /// Which trust-model rules this entry is accepted under.
    pub profile: CawgTrustProfile,
    /// PEM bundle of the entry's certificates. CA and end-entity certificates
    /// may be mixed. Must hold at least one certificate.
    pub certificates_pem: String,
    /// RFC 3339 start of this entry's trust. A signature whose time stamp, or
    /// without one the validation time, precedes it is not validated by it.
    #[serde(default)]
    pub not_before: Option<String>,
    /// RFC 3339 end of this entry's trust. A signature whose time stamp, or
    /// without one the validation time, follows it is not validated by it.
    #[serde(default)]
    pub not_after: Option<String>,
}

/// The CAWG Identity 1.3 rules a [`CawgTrustConfiguration`] is accepted under.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CawgTrustProfile {
    /// An entry the validator configured itself. Accepts
    /// `id-kp-documentSigning`, and, as local validator policy,
    /// `id-kp-emailProtection` with one of the six CA/Browser Forum S/MIME
    /// policies, without the interim time conditions. A direct certificate
    /// match reports `trust_source: allowed_list`; an anchored
    /// `id-kp-documentSigning` match reports `document_signing`; an anchored
    /// `id-kp-emailProtection` match reports `caller_supplied`.
    Base,
    /// One of the two sources the interim trust model additions name: the
    /// Mozilla root store with the email trust bit, or the IPTC Verified News
    /// Publishers lists. Accepts only `id-kp-emailProtection` with one of the
    /// six policies, and only while the validation time, or a trusted time
    /// stamp, is on or before 31 March 2027. A direct certificate match reports
    /// `trust_source: allowed_list`; an anchored match reports
    /// `smime_interim`.
    SmimeInterim,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct VerificationStatus {
    pub code: String,
    #[serde(default)]
    pub url: String,
    /// Linked resource URI for a per-entry LRI status, serialized as `resourceUrl`.
    #[serde(default, rename = "resourceUrl")]
    pub resource_url: Option<String>,
    pub explanation: String,
    /// Machine-readable evidence for extension status codes (e.g. the CAWG
    /// `payload_encoding` detail).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub details: Option<Value>,
}

impl Serialize for VerificationStatus {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        crate::c2pa_validate::serialize_status(
            serializer,
            &self.code,
            &self.url,
            self.resource_url.as_deref(),
            &self.explanation,
            self.details.as_ref(),
        )
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ValidationResults {
    pub success: Vec<VerificationStatus>,
    pub informational: Vec<VerificationStatus>,
    pub failure: Vec<VerificationStatus>,
    /// Trust lists whose anchors accepted the active claim or timestamp.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub trust_list_sources: Vec<TrustSource>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RevocationReport {
    pub status: String,
    pub source: String,
    pub responder_signature: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FreshnessReport {
    pub status: String,
    pub as_of: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TrustReport {
    pub status: String,
    pub basis: String,
    pub validation_time: String,
    pub revocation: RevocationReport,
    pub freshness: FreshnessReport,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerificationReport {
    pub schema_version: String,
    pub profile: String,
    pub mime_type: String,
    pub present: bool,
    pub integrity: String,
    pub signature: String,
    pub hard_binding: String,
    pub trust: TrustReport,
    pub policy: Option<Value>,
    pub managed_receipt: Option<Value>,
    pub validation_state: String,
    pub validation_results: ValidationResults,
    pub manifest_report: Value,
    pub content_credentials: Option<Value>,
    /// What this verification did, or could have done, on the network.
    #[serde(default)]
    pub network: NetworkReport,
}
/// Raw, read-only evidence needed to validate an embedded manifest remotely
/// without uploading the host asset.
///
/// `carrier` is the single contiguous format carrier that contains
/// `manifest_store`. Formats whose manifest spans multiple disjoint carriers
/// return no detached evidence; local verification still covers them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DetachedManifestEvidence {
    pub manifest_store: Vec<u8>,
    pub manifest_store_sha256: String,
    pub carrier: Vec<u8>,
}

/// One local verification plus what a service needs to re-verify the same
/// manifest store without receiving the asset.
///
/// Every field comes from a single verification pass. `manifest_store` is the
/// exact embedded store that pass read, so a remote verifier checks the bytes
/// the local verdict was computed over, not a second extraction.
#[derive(Debug, Clone, Serialize)]
pub struct LocalEvidence {
    /// Exactly what [`verify_with_options`] returns for the same inputs.
    pub report: VerificationReport,
    /// The embedded manifest-store bytes that were verified. `None` when the
    /// asset carries no embedded store, or when the verdict came from a store
    /// fetched from a remote reference the asset declares.
    #[serde(serialize_with = "serialize_optional_bytes")]
    pub manifest_store: Option<Vec<u8>>,
    /// Lowercase hex SHA-256 of `manifest_store`.
    pub manifest_store_sha256: Option<String>,
    /// Lowercase hex SHA-256 of the whole asset.
    pub asset_sha256: String,
    /// The active manifest's hard binding and this pass's verdict on it.
    pub hard_binding: LocalHardBinding,
    /// Label of the store's active manifest, when `manifest_store` parses.
    pub active_manifest_label: Option<String>,
    /// Every manifest of `manifest_store` with the expanded-domain SHA-256 an
    /// ingredient reference to it uses, in store order. Empty without a
    /// readable store.
    pub store_manifests: Vec<ManifestDigest>,
}

/// One manifest of a store and its expanded-domain SHA-256, the digest an
/// ingredient's `activeManifest` reference to it carries.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ManifestDigest {
    /// The manifest's label.
    pub label: String,
    /// Lowercase hex SHA-256 over the manifest's expanded JUMBF content.
    pub sha256: String,
}

/// The active label and manifest digests of `manifest_store`; empty when it
/// does not parse (the report then already carries the reason).
fn manifest_identity(manifest_store: Option<&[u8]>) -> (Option<String>, Vec<ManifestDigest>) {
    let Some(store) = manifest_store else {
        return (None, Vec::new());
    };
    match std::panic::catch_unwind(|| crate::c2pa_validate::store_manifest_identity(store)) {
        Ok(Ok((active, digests))) => (
            active,
            digests
                .into_iter()
                .map(|digest| ManifestDigest {
                    label: digest.label,
                    sha256: hex::encode(digest.sha256),
                })
                .collect(),
        ),
        _ => (None, Vec::new()),
    }
}

/// The hard binding a [`LocalEvidence`] pass checked.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct LocalHardBinding {
    /// Label of the active manifest's sole hard-binding assertion, such as
    /// `c2pa.hash.boxes`. An update manifest reports the binding it inherits
    /// from its parent standard manifest. `None` when there is no store, the
    /// claim cannot be decoded, or it does not declare exactly one.
    pub algorithm: Option<String>,
    /// `match`, `mismatch`, or `unknown`, from the same pass's status codes.
    pub status: String,
}

/// What one manifest store proves with no asset: claim, assertion,
/// ingredient, signature, time-stamp, revocation, trust and identity
/// validation, and nothing about content.
///
/// This is the evidence a writer records for a source or ingredient it holds
/// only as a store. `report.hard_binding` is `not_evaluated`, and
/// `report.integrity` is `unbound` when no failure invalidates the claim
/// (`invalid` otherwise): no asset bytes were compared, so the result never
/// says the asset is intact.
#[derive(Debug, Clone, Serialize)]
pub struct StoreOnlyValidation {
    /// The report of the store-level pass.
    pub report: VerificationReport,
    /// Label of the store's active manifest.
    pub active_manifest_label: Option<String>,
    /// Every manifest of the store with its expanded-domain SHA-256.
    pub store_manifests: Vec<ManifestDigest>,
}

/// Bytes go to `serialize_bytes`, so a JavaScript binding receives a
/// `Uint8Array` rather than an array of numbers.
fn serialize_optional_bytes<S: serde::Serializer>(
    value: &Option<Vec<u8>>,
    serializer: S,
) -> Result<S::Ok, S::Error> {
    match value {
        Some(bytes) => serializer.serialize_bytes(bytes),
        None => serializer.serialize_none(),
    }
}

/// What one verification pass read besides its report.
#[derive(Default)]
struct PassCapture {
    manifest_store: Option<Vec<u8>>,
    hard_binding_label: Option<String>,
}

impl PassCapture {
    fn take(output: &mut crate::c2pa_validate::VerifyOutput) -> Self {
        Self {
            manifest_store: output.manifest_store.take(),
            hard_binding_label: output.hard_binding_label.take(),
        }
    }
}

impl VerificationReport {
    pub fn to_json(&self) -> Result<String, Error> {
        serde_json::to_string(self).map_err(Error::Serialize)
    }

    pub fn to_pretty_json(&self) -> Result<String, Error> {
        serde_json::to_string_pretty(self).map_err(Error::Serialize)
    }

    /// All CAWG identity / ICA credential statuses (`cawg.*` codes), across
    /// the success, informational, and failure sections. CAWG failures are
    /// assertion-scoped: they never invalidate C2PA manifest integrity.
    pub fn cawg_statuses(&self) -> Vec<&VerificationStatus> {
        self.validation_results
            .success
            .iter()
            .chain(&self.validation_results.informational)
            .chain(&self.validation_results.failure)
            .filter(|status| status.code.starts_with("cawg."))
            .collect()
    }
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("unsupported MIME type: {0}")]
    UnsupportedMime(String),
    #[error("invalid trust material: {0}")]
    InvalidTrust(String),
    #[error("invalid validation time: {0}")]
    InvalidValidationTime(String),
    #[error("unsupported spec version: {0}")]
    UnsupportedSpecVersion(String),
    #[error("verification failed: {0}")]
    Verification(String),
    #[error("could not read asset: {0}")]
    Io(#[from] std::io::Error),
    #[error(transparent)]
    TelemetryPreference(#[from] TelemetryPreferenceError),
    #[error(transparent)]
    OnlinePreference(#[from] OnlinePreferenceError),
    #[error("could not serialize report: {0}")]
    Serialize(serde_json::Error),
}

impl Error {
    pub fn code(&self) -> &'static str {
        match self {
            Self::UnsupportedMime(_) => "unsupported_mime",
            Self::InvalidTrust(_) => "invalid_trust_material",
            Self::InvalidValidationTime(_) => "invalid_validation_time",
            Self::UnsupportedSpecVersion(_) => "unsupported_spec_version",
            Self::Verification(_) => "verification_error",
            Self::Io(_) => "io_error",
            Self::OnlinePreference(_) => "online_preference_error",
            Self::TelemetryPreference(_) => "telemetry_preference_error",
            Self::Serialize(_) => "serialization_error",
        }
    }
}

/// Verify asset bytes with default options. Parsing and validation stay offline;
/// saved failure-telemetry consent may emit one bounded request. For guaranteed
/// no egress, disable the `telemetry` feature or call [`verify_with_options`]
/// with `telemetry.enabled` set to `Some(false)`.
pub fn verify(data: &[u8], mime_type: &str) -> Result<VerificationReport, Error> {
    verify_with_options(data, mime_type, &VerifyOptions::default())
}

/// Verify a fragmented ISO BMFF stream with default options.
///
/// `init_segment` carries the manifest. Each entry in `fragments` is one media
/// segment (`.m4s`). Any contiguous subset may be supplied: each segment's
/// Merkle-tree location is authenticated and adjacency is enforced.
pub fn verify_fragmented(
    init_segment: &[u8],
    fragments: &[&[u8]],
    mime_type: &str,
) -> Result<VerificationReport, Error> {
    verify_fragmented_with_options(
        init_segment,
        fragments,
        mime_type,
        &VerifyOptions::default(),
    )
}
/// Extract the signed manifest store and its contiguous carrier for detached
/// server validation, locating it under the default C2PA 2.4 policy.
///
/// This is read-only. It never performs network I/O and never constructs or
/// writes a manifest. `Ok(None)` means the asset has no embedded manifest or
/// its format cannot represent the manifest as one contiguous carrier.
pub fn detached_manifest_evidence(
    data: &[u8],
    mime_type: &str,
) -> Result<Option<DetachedManifestEvidence>, Error> {
    detached_manifest_evidence_with_options(data, mime_type, &VerifyOptions::default())
}

/// [`detached_manifest_evidence`] under the policy `options.spec_version`
/// selects. A 2.5 extraction therefore returns exactly the store and carrier
/// span that a 2.5 verification reads.
///
/// Only `spec_version` and `strict_conformance` are read; an unknown policy
/// fails with [`Error::UnsupportedSpecVersion`] before the asset is parsed.
pub fn detached_manifest_evidence_with_options(
    data: &[u8],
    mime_type: &str,
    options: &VerifyOptions,
) -> Result<Option<DetachedManifestEvidence>, Error> {
    let profile = resolve_profile(options.spec_version.as_deref(), options.strict_conformance)?;
    let mime = canonicalize_mime(mime_type);
    require_embedded_mime(&mime, profile)?;
    let format = crate::c2pa_formats::AssetFormat::from_canonical_mime(&mime)
        .ok_or_else(|| Error::UnsupportedMime(mime.clone()))?;
    if !crate::c2pa_formats::supports_hash_mode(&mime) {
        return Ok(None);
    }
    let Some(manifest_store) =
        crate::c2pa_formats::extract_manifest_for_spec(format, data, profile.version)
            .map_err(|error| Error::Verification(error.to_string()))?
    else {
        return Ok(None);
    };
    let spans =
        crate::c2pa_formats::compute_data_hash_exclusions_for_spec(format, data, profile.version)
            .map_err(|error| Error::Verification(error.to_string()))?;
    let [span] = spans.as_slice() else {
        return Ok(None);
    };
    let end = span
        .start
        .checked_add(span.length)
        .filter(|end| *end <= data.len())
        .ok_or_else(|| Error::Verification("manifest carrier exceeds asset bounds".into()))?;
    let manifest_store_sha256 = hex::encode(Sha256::digest(&manifest_store));
    Ok(Some(DetachedManifestEvidence {
        manifest_store,
        manifest_store_sha256,
        carrier: data[span.start..end].to_vec(),
    }))
}

/// Verify one asset against a manifest store the caller supplies separately.
///
/// This is the entry point for provenance that does not travel inside the
/// asset: a `.c2pa` sidecar, a manifest fetched from the URI an asset declares
/// in its XMP `dcterms:provenance` key, or a store held in a repository. The
/// SDK never fetches any of those. It reads what the caller hands it.
///
/// The manifest binds to `asset` through its ordinary hard binding, evaluated
/// exactly as it would be for an embedded manifest, so a store paired with the
/// wrong or altered asset fails on the hash rather than on a weaker check.
/// Trust material, validation instant, CAWG identity configuration, and the
/// conformance posture all come from `options`, as they do for
/// [`verify_with_options`].
///
/// `mime_type` describes `asset`, not the store. `application/c2pa` is
/// rejected: the content side must be a real asset.
/// WebM, ICO, BMP, raw AAC, and WOFF media are supported only on this explicit
/// sidecar path, using a whole-file data hash without exclusions.
pub fn verify_with_manifest_store(
    asset: &[u8],
    manifest_store: &[u8],
    mime_type: &str,
    options: &VerifyOptions,
) -> Result<VerificationReport, Error> {
    let telemetry_enabled = telemetry_consent::resolve_telemetry_enabled(options.telemetry.enabled);
    let result = verify_with_manifest_store_inner(asset, manifest_store, mime_type, options);
    enqueue_failure_telemetry(mime_type, &result, options, telemetry_enabled);
    result
}

/// [`verify_with_manifest_store`] with caller-controlled external resource
/// resolution and lowered graph ceilings. The manifest store and external
/// resources are supplied by the caller; this function performs no network
/// I/O and completes the graph and CAWG checks in one verification pass.
pub fn verify_with_manifest_store_and_graph_inputs(
    asset: &[u8],
    manifest_store: &[u8],
    mime_type: &str,
    options: &VerifyOptions,
    graph_inputs: GraphInputs<'_>,
) -> Result<VerificationReport, Error> {
    let telemetry_enabled = telemetry_consent::resolve_telemetry_enabled(options.telemetry.enabled);
    let result = (|| {
        let profile = resolve_profile(options.spec_version.as_deref(), options.strict_conformance)?;
        let mime = resolve_detached_mime(mime_type, profile)?;
        detached_pass(asset, manifest_store, &mime, options, graph_inputs)
            .map(|(report, _, _)| report)
    })();
    enqueue_failure_telemetry(mime_type, &result, options, telemetry_enabled);
    result
}

fn verify_with_manifest_store_inner(
    asset: &[u8],
    manifest_store: &[u8],
    mime_type: &str,
    options: &VerifyOptions,
) -> Result<VerificationReport, Error> {
    let profile = resolve_profile(options.spec_version.as_deref(), options.strict_conformance)?;
    let mime = resolve_detached_mime(mime_type, profile)?;
    if profile.version == SpecVersion::V2_5 {
        let resolved = ResolvedOptions::resolve(options)?;
        return verify_detached_online_v25(asset, manifest_store, &mime, options, resolved);
    }
    let (mut report, needs, _) = detached_pass(
        asset,
        manifest_store,
        &mime,
        options,
        GraphInputs::default(),
    )?;
    let (network, evidence) = online::gather(options, &needs);
    if evidence.is_empty() {
        report.network = network;
        return Ok(report);
    }
    // The store the caller supplied is the one that binds this asset. Pass 2
    // re-reads it with the fetched evidence; it never swaps in another store.
    let next = online::apply_evidence(options, &evidence);
    let (mut report, _, _) =
        detached_pass(asset, manifest_store, &mime, &next, GraphInputs::default())?;
    report.network = network;
    Ok(report)
}

/// One offline verification of an asset against a separately held store, with
/// the network needs and capture it recorded.
fn detached_pass(
    asset: &[u8],
    manifest_store: &[u8],
    mime: &str,
    options: &VerifyOptions,
    graph_inputs: GraphInputs<'_>,
) -> Result<(VerificationReport, Vec<online::NetworkNeed>, PassCapture), Error> {
    let resolved = ResolvedOptions::resolve(options)?;
    detached_pass_resolved(
        asset,
        manifest_store,
        mime,
        options,
        &resolved,
        options.cawg_did_documents.as_ref(),
        graph_inputs,
    )
}

fn detached_pass_resolved(
    asset: &[u8],
    manifest_store: &[u8],
    mime: &str,
    options: &VerifyOptions,
    resolved: &ResolvedOptions,
    did_documents: Option<&HashMap<String, Value>>,
    graph_inputs: GraphInputs<'_>,
) -> Result<(VerificationReport, Vec<online::NetworkNeed>, PassCapture), Error> {
    if manifest_store.is_empty() {
        return Err(Error::Verification("manifest store is empty".into()));
    }
    if manifest_store.len() > MAX_MANIFEST_STORE_BYTES {
        return Err(Error::Verification(format!(
            "manifest store exceeds the {MAX_MANIFEST_STORE_BYTES} byte limit"
        )));
    }
    let input = resolved.input(asset, mime);
    let mut output = crate::c2pa_validate::verify_detached_safe(
        manifest_store,
        asset,
        mime,
        &input,
        resolved.cawg_trust(),
        resolved.cawg_allowed_certs(),
        resolved.cawg_document_signing_require_anchor,
        did_documents,
        options.cawg_ica_trusted_issuers.as_deref(),
        options.cawg_ica_trust_anchors.as_deref(),
        options.cawg_ica_status_lists.as_ref(),
        graph_inputs,
    )
    .map_err(map_validate_error)?;
    let needs = online::network_needs(&output);
    let capture = PassCapture::take(&mut output);
    Ok((
        report_from_output(output, mime.to_string(), resolved),
        needs,
        capture,
    ))
}

/// Validate a manifest store on its own, with no asset.
///
/// For a writer recording an ingredient or source it holds only as a store:
/// everything about the store is checked - claim structure, the selected
/// policy's assertion, action, ingredient and redaction rules, hashed-URI
/// bindings, the claim signature, time stamps, revocation, trust and CAWG
/// identity - and nothing about content. The report says so:
/// `hard_binding` is `not_evaluated` with the informational
/// `com.encypher.hardBinding.notEvaluated`, and `integrity` is `unbound`
/// rather than `valid` when no failure invalidates the claim.
///
/// Options are read as for [`verify_with_options`]. This entry point never
/// fetches (`online: Some(true)` is refused) and sends no telemetry.
pub fn verify_manifest_store_only(
    manifest_store: &[u8],
    options: &VerifyOptions,
) -> Result<StoreOnlyValidation, Error> {
    verify_manifest_store_only_with_graph_inputs(manifest_store, options, GraphInputs::default())
}

/// [`verify_manifest_store_only`] with caller-controlled external resource
/// resolution and lowered graph ceilings. Content remains deliberately
/// unevaluated, so a valid result stays unbound.
pub fn verify_manifest_store_only_with_graph_inputs(
    manifest_store: &[u8],
    options: &VerifyOptions,
    graph_inputs: GraphInputs<'_>,
) -> Result<StoreOnlyValidation, Error> {
    if options.online == Some(true) {
        return Err(Error::Verification(
            "online must not be Some(true): store-only validation never fetches".into(),
        ));
    }
    let resolved = ResolvedOptions::resolve(options)?;
    if manifest_store.is_empty() {
        return Err(Error::Verification("manifest store is empty".into()));
    }
    if manifest_store.len() > MAX_MANIFEST_STORE_BYTES {
        return Err(Error::Verification(format!(
            "manifest store exceeds the {MAX_MANIFEST_STORE_BYTES} byte limit"
        )));
    }
    let input = resolved.input(&[], "application/c2pa");
    let cawg_inputs = crate::c2pa_validate::CawgTrustInputs::new(
        resolved.cawg_trust(),
        resolved.cawg_allowed_certs(),
        resolved.cawg_document_signing_require_anchor,
        options.cawg_did_documents.as_ref(),
        options.cawg_ica_trusted_issuers.as_deref(),
        options.cawg_ica_trust_anchors.as_deref(),
        options.cawg_ica_status_lists.as_ref(),
        graph_inputs,
    );
    let output = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        crate::c2pa_validate::verify_store_binding(
            manifest_store,
            crate::c2pa_validate::StoreBinding::StoreOnly,
            &input,
            cawg_inputs,
        )
    }))
    .map_err(|_| Error::Verification("verification panicked".into()))?
    .map_err(map_validate_error)?;
    Ok(finish_store_only_validation(
        manifest_store,
        output,
        &resolved,
    ))
}

fn finish_store_only_validation(
    manifest_store: &[u8],
    output: crate::c2pa_validate::VerifyOutput,
    resolved: &ResolvedOptions,
) -> StoreOnlyValidation {
    let mut report = report_from_output(output, "application/c2pa".to_string(), resolved);
    report.hard_binding = "not_evaluated".to_string();
    if report.integrity == "valid" {
        report.integrity = "unbound".to_string();
        if let Some(verdict) = report
            .manifest_report
            .pointer_mut("/provenance_verdict")
            .and_then(Value::as_object_mut)
        {
            verdict.insert("integrity".to_string(), Value::from("unbound"));
        }
    }
    let (active_manifest_label, store_manifests) = manifest_identity(Some(manifest_store));
    StoreOnlyValidation {
        report,
        active_manifest_label,
        store_manifests,
    }
}

/// Verify with caller-controlled external resource resolution and lowered graph
/// ceilings. Policy selection, trust defaults and all verdict logic are the
/// same as [`verify_with_options`]; this function performs no network I/O.
pub fn verify_with_graph_inputs(
    data: &[u8],
    mime_type: &str,
    options: &VerifyOptions,
    graph_inputs: GraphInputs<'_>,
) -> Result<VerificationReport, Error> {
    let telemetry_enabled = telemetry_consent::resolve_telemetry_enabled(options.telemetry.enabled);
    let result = (|| {
        let resolved = ResolvedOptions::resolve(options)?;
        embedded_graph_pass(data, None, mime_type, options, &resolved, graph_inputs)
    })();
    enqueue_failure_telemetry(mime_type, &result, options, telemetry_enabled);
    result
}

/// Verify asset bytes against the bundled trust snapshots plus any static
/// trust material supplied by the caller. Failure telemetry follows the
/// explicit override or saved per-user preference.
pub fn verify_with_options(
    data: &[u8],
    mime_type: &str,
    options: &VerifyOptions,
) -> Result<VerificationReport, Error> {
    let resolved = ResolvedOptions::resolve(options)?;
    verify_with_resolved_options(data, None, mime_type, options, resolved)
}

/// Verify asset bytes exactly as [`verify_with_options`] does and return the
/// evidence a remote service needs to re-verify the same manifest store.
///
/// The report, the store bytes, and the hard-binding verdict all come from
/// one verification pass. A remote verifier that checks `manifest_store`
/// against `hard_binding` therefore evaluates the store the local verdict
/// was computed over. Failure telemetry follows the same rules as
/// [`verify_with_options`].
pub fn local_evidence_with_options(
    data: &[u8],
    mime_type: &str,
    options: &VerifyOptions,
) -> Result<LocalEvidence, Error> {
    let resolved = ResolvedOptions::resolve(options)?;
    let telemetry_enabled = telemetry_consent::resolve_telemetry_enabled(options.telemetry.enabled);
    let (result, capture) =
        match verify_with_options_inner(data, None, mime_type, options, resolved) {
            Ok((report, capture)) => (Ok(report), capture),
            Err(error) => (Err(error), PassCapture::default()),
        };
    enqueue_failure_telemetry(mime_type, &result, options, telemetry_enabled);
    let report = result?;
    let status = match report.hard_binding.as_str() {
        "match" => "match",
        "mismatch" => "mismatch",
        _ => "unknown",
    };
    let (active_manifest_label, store_manifests) =
        manifest_identity(capture.manifest_store.as_deref());
    Ok(LocalEvidence {
        manifest_store_sha256: capture
            .manifest_store
            .as_deref()
            .map(|store| hex::encode(Sha256::digest(store))),
        manifest_store: capture.manifest_store,
        asset_sha256: hex::encode(Sha256::digest(data)),
        hard_binding: LocalHardBinding {
            algorithm: capture.hard_binding_label,
            status: status.to_string(),
        },
        active_manifest_label,
        store_manifests,
        report,
    })
}

fn verify_with_resolved_options(
    data: &[u8],
    fragments: Option<&[&[u8]]>,
    mime_type: &str,
    options: &VerifyOptions,
    resolved: ResolvedOptions,
) -> Result<VerificationReport, Error> {
    let telemetry_enabled = telemetry_consent::resolve_telemetry_enabled(options.telemetry.enabled);
    let result = verify_with_options_inner(data, fragments, mime_type, options, resolved)
        .map(|(report, _)| report);
    enqueue_failure_telemetry(mime_type, &result, options, telemetry_enabled);
    result
}

fn enqueue_failure_telemetry(
    mime_type: &str,
    result: &Result<VerificationReport, Error>,
    options: &VerifyOptions,
    enabled: bool,
) {
    if let Some(event) = telemetry::validation_failure_telemetry_with_enabled(
        mime_type,
        result,
        &options.telemetry,
        enabled,
    ) {
        telemetry::enqueue(options.telemetry.endpoint(), event);
    }
}

/// Verify a fragmented ISO BMFF stream with explicit trust, validation-time,
/// CAWG, and telemetry options.
///
/// `init_segment` carries the C2PA manifest. `fragments` may be the complete
/// stream or any contiguous available subset; missing trailing fragments are
/// not a failure. Mark each intentional discontinuity by its zero-based index
/// in [`VerifyOptions::expected_seek_positions`].
pub fn verify_fragmented_with_options(
    init_segment: &[u8],
    fragments: &[&[u8]],
    mime_type: &str,
    options: &VerifyOptions,
) -> Result<VerificationReport, Error> {
    if options.stream_presentation_times.is_some() {
        return Err(Error::InvalidValidationTime(
            "stream_presentation_times: per-segment presentation times apply only to \
             session-key live streams verified with verify_stream_with_options; \
             Merkle-bound fragments are assessed at validation_time"
                .into(),
        ));
    }
    let resolved = ResolvedOptions::resolve(options)?;
    let telemetry_enabled = telemetry_consent::resolve_telemetry_enabled(options.telemetry.enabled);
    let mime = canonicalize_mime(mime_type);
    let result = if crate::c2pa_formats::AssetFormat::from_canonical_mime(&mime)
        == Some(crate::c2pa_formats::AssetFormat::Bmff)
    {
        verify_with_options_inner(init_segment, Some(fragments), &mime, options, resolved)
            .map(|(report, _)| report)
    } else {
        Err(Error::UnsupportedMime(mime))
    };
    enqueue_failure_telemetry(mime_type, &result, options, telemetry_enabled);
    result
}

/// [`verify_fragmented_with_options`] with caller-controlled external resource
/// resolution and lowered graph ceilings. The fragments, graph walk, and CAWG
/// identity checks run in one verification pass without network I/O.
pub fn verify_fragmented_with_graph_inputs(
    init_segment: &[u8],
    fragments: &[&[u8]],
    mime_type: &str,
    options: &VerifyOptions,
    graph_inputs: GraphInputs<'_>,
) -> Result<VerificationReport, Error> {
    if options.stream_presentation_times.is_some() {
        return Err(Error::InvalidValidationTime(
            "stream_presentation_times: per-segment presentation times apply only to \
             session-key live streams verified with verify_stream_with_options; \
             Merkle-bound fragments are assessed at validation_time"
                .into(),
        ));
    }
    let resolved = ResolvedOptions::resolve(options)?;
    let telemetry_enabled = telemetry_consent::resolve_telemetry_enabled(options.telemetry.enabled);
    let mime = canonicalize_mime(mime_type);
    let result = if crate::c2pa_formats::AssetFormat::from_canonical_mime(&mime)
        == Some(crate::c2pa_formats::AssetFormat::Bmff)
    {
        embedded_graph_pass(
            init_segment,
            Some(fragments),
            &mime,
            options,
            &resolved,
            graph_inputs,
        )
    } else {
        Err(Error::UnsupportedMime(mime))
    };
    enqueue_failure_telemetry(mime_type, &result, options, telemetry_enabled);
    result
}

/// Trust material, validation instant, and engine profile resolved once from
/// [`VerifyOptions`].
///
/// Every entry point - asset, fragmented, and stream - resolves its inputs
/// here, so a stream can never be verified against different trust material
/// than a single asset would be.
pub(crate) struct ResolvedOptions {
    claim_trust: Option<ResolvedTrust>,
    tsa_trust: Option<ResolvedTrust>,
    allowed_certs: Option<ResolvedTrust>,
    cawg_trust: Option<ResolvedTrust>,
    cawg_allowed_certs: Option<ResolvedTrust>,
    validation_time: OffsetDateTime,
    validation_time_text: String,
    trust_basis: &'static str,
    profile: EngineProfile,
    cawg_strict_encoding: bool,
    cawg_document_signing_require_anchor: bool,
    /// Caller-supplied online evidence, base64-decoded once.
    ocsp_responses: HashMap<String, Vec<u8>>,
    ocsp_unreachable: Vec<String>,
    external_data: HashMap<String, Vec<u8>>,
    external_data_media_types: HashMap<String, String>,
    external_data_unreachable: Vec<String>,
}

impl ResolvedOptions {
    pub(crate) fn resolve(options: &VerifyOptions) -> Result<Self, Error> {
        // The policy selector is resolved first, so an unknown value fails
        // before any trust material is parsed or asset read.
        let profile = resolve_profile(options.spec_version.as_deref(), options.strict_conformance)?;
        let use_defaults = !options.no_default_trust;
        let validation_time = parse_validation_time(options.validation_time.as_deref())?;
        let custom_claim_trust = options.trust_pem.is_some()
            || options
                .claim_trust_sources
                .as_ref()
                .is_some_and(|sources| !sources.is_empty())
            || options.allowed_list_pem.is_some();
        let bounds = (
            parse_optional_instant(
                options.trust_anchor_not_before.as_deref(),
                "trust_anchor_not_before",
            )?,
            parse_optional_instant(
                options.trust_anchor_not_after.as_deref(),
                "trust_anchor_not_after",
            )?,
        );
        let (cawg_anchors, cawg_direct) =
            resolve_cawg_configurations(options.cawg_trust_configurations.as_deref())?;
        Ok(Self {
            claim_trust: resolve_trust(
                options.trust_pem.as_deref(),
                options.claim_trust_sources.as_deref(),
                use_defaults.then(default_trust::claim_signing),
                AnchorPurpose::ClaimSigning,
                bounds,
            )?,
            tsa_trust: resolve_trust(
                options.tsa_trust_pem.as_deref(),
                options.tsa_trust_sources.as_deref(),
                use_defaults.then(default_trust::timestamp_authorities),
                AnchorPurpose::TimeStamping,
                bounds,
            )?,
            allowed_certs: resolve_trust(
                options.allowed_list_pem.as_deref(),
                None,
                use_defaults.then(default_trust::allowed_claim_signers),
                AnchorPurpose::ClaimSigning,
                bounds,
            )?,
            cawg_trust: extend_trust(
                resolve_trust(
                    options.cawg_trust_pem.as_deref(),
                    None,
                    use_defaults.then(default_trust::cawg_identity),
                    AnchorPurpose::CawgIdentity,
                    bounds,
                )?,
                cawg_anchors,
            ),
            cawg_allowed_certs: extend_trust(
                resolve_trust(
                    options.cawg_allowed_certs_pem.as_deref(),
                    None,
                    use_defaults.then(default_trust::cawg_allowed_identities),
                    AnchorPurpose::CawgIdentity,
                    bounds,
                )?,
                cawg_direct,
            ),
            validation_time,
            validation_time_text: validation_time
                .format(&Rfc3339)
                .map_err(|error| Error::InvalidValidationTime(error.to_string()))?,
            trust_basis: match (use_defaults, custom_claim_trust) {
                (true, true) => "bundled_and_caller_supplied_static_material",
                (true, false) => "bundled_static_material",
                (false, true) => "caller_supplied_static_material",
                (false, false) => "none",
            },
            profile,
            cawg_strict_encoding: options.cawg_strict_encoding,
            cawg_document_signing_require_anchor: options
                .cawg_document_signing_require_anchor
                .unwrap_or(true),
            ocsp_responses: decode_base64_map(
                options.ocsp_responses.as_ref(),
                "ocsp_responses",
                MAX_OCSP_EVIDENCE_BYTES,
            )?,
            ocsp_unreachable: options.ocsp_unreachable.clone().unwrap_or_default(),
            external_data: decode_base64_map(
                options.external_data.as_ref(),
                "external_data",
                MAX_EXTERNAL_DATA_EVIDENCE_BYTES,
            )?,
            external_data_media_types: options
                .external_data_media_types
                .clone()
                .unwrap_or_default(),
            external_data_unreachable: options
                .external_data_unreachable
                .clone()
                .unwrap_or_default(),
        })
    }

    fn take_external_data(&mut self) -> ValidatedExternalData {
        ValidatedExternalData {
            data: std::mem::take(&mut self.external_data),
            media_types: std::mem::take(&mut self.external_data_media_types),
            unreachable: std::mem::take(&mut self.external_data_unreachable),
        }
    }

    fn apply_ocsp_update(&mut self, update: native_online::OcspUpdate) {
        for (certificate, response) in update.responses {
            self.ocsp_responses.entry(certificate).or_insert(response);
        }
        for certificate in update.unreachable {
            if !self.ocsp_unreachable.contains(&certificate) {
                self.ocsp_unreachable.push(certificate);
            }
        }
    }

    pub(crate) fn input<'a>(&'a self, data: &'a [u8], mime: &'a str) -> VerifyInput<'a> {
        VerifyInput {
            data,
            mime,
            claim_signer_trust: self.claim_trust.as_ref().map(ResolvedTrust::get),
            tsa_trust: self.tsa_trust.as_ref().map(ResolvedTrust::get),
            allowed_certs: self.allowed_certs.as_ref().map(ResolvedTrust::get),
            validation_time: Some(self.validation_time),
            profile: self.profile,
            cawg_strict_encoding: self.cawg_strict_encoding,
            evidence: crate::c2pa_validate::OnlineEvidence {
                ocsp_responses: (!self.ocsp_responses.is_empty()).then_some(&self.ocsp_responses),
                ocsp_unreachable: (!self.ocsp_unreachable.is_empty())
                    .then_some(self.ocsp_unreachable.as_slice()),
                external_data: (!self.external_data.is_empty()).then_some(&self.external_data),
                external_data_media_types: (!self.external_data_media_types.is_empty())
                    .then_some(&self.external_data_media_types),
                external_data_unreachable: (!self.external_data_unreachable.is_empty())
                    .then_some(self.external_data_unreachable.as_slice()),
            },
        }
    }

    pub(crate) fn cawg_trust(&self) -> Option<&TrustList> {
        self.cawg_trust.as_ref().map(ResolvedTrust::get)
    }

    pub(crate) fn cawg_allowed_certs(&self) -> Option<&TrustList> {
        self.cawg_allowed_certs.as_ref().map(ResolvedTrust::get)
    }
}

/// The engine profile for the caller's policy selection.
///
/// `None` and `"2.4"` are the same policy and resolve to the same profile, so
/// the two produce byte-identical reports. `"2.2"` is an explicit older policy.
/// Strict 2.2 and 2.4 select their published program postures. Strict 2.5 is a
/// technical core-spec posture with strict diagnostics; it never claims a
/// certified or Conformance Program scope.
fn resolve_profile(spec_version: Option<&str>, strict: bool) -> Result<EngineProfile, Error> {
    let version = match spec_version {
        None => SpecVersion::V2_4,
        Some(value) => SpecVersion::public_policy_from_str(value).ok_or_else(|| {
            Error::UnsupportedSpecVersion(format!(
                "spec_version {value:?} is not one of {}",
                SpecVersion::PUBLIC_POLICIES
                    .iter()
                    .map(|version| format!("{:?}", version.version_str()))
                    .collect::<Vec<_>>()
                    .join(", ")
            ))
        })?,
    };
    match (version, strict) {
        (SpecVersion::V2_2, true) => Ok(EngineProfile::strict(SpecVersion::V2_2)),
        (SpecVersion::V2_2, false) => Ok(EngineProfile {
            version,
            ..EngineProfile::GENEROUS
        }),
        (SpecVersion::V2_4, true) => Ok(EngineProfile::strict(SpecVersion::V2_4)),
        (SpecVersion::V2_4, false) => Ok(EngineProfile::GENEROUS),
        (SpecVersion::V2_5, true) => Ok(EngineProfile::new(
            SpecVersion::V2_5,
            OperatingMode::Conformance,
        )
        .with_compliance(ComplianceLevel::CoreSpec)
        .with_debug(true)),
        (SpecVersion::V2_5, false) => Ok(EngineProfile {
            version,
            ..EngineProfile::GENEROUS
        }),
        _ => Err(Error::UnsupportedSpecVersion(format!(
            "spec_version {:?} is registered but has no public verification policy",
            version.version_str()
        ))),
    }
}

/// The report `profile` for an engine profile's validation policy.
fn report_profile(profile: EngineProfile) -> &'static str {
    match profile.version {
        SpecVersion::V2_5 => C2PA_PROFILE_2_5,
        SpecVersion::V2_2 => C2PA_PROFILE_2_2,
        _ => C2PA_PROFILE,
    }
}

/// Decode a map of standard-base64 evidence values, rejecting anything
/// malformed or over `max_bytes` rather than silently ignoring it.
///
/// A caller who hands the SDK evidence deserves to hear that it was unusable;
/// dropping it would show up much later as an unexplained `ocsp.skipped`.
fn decode_base64_map(
    values: Option<&HashMap<String, String>>,
    field: &str,
    max_bytes: usize,
) -> Result<HashMap<String, Vec<u8>>, Error> {
    let Some(values) = values else {
        return Ok(HashMap::new());
    };
    let mut decoded = HashMap::with_capacity(values.len());
    for (key, encoded) in values {
        let bytes = crate::c2pa_formats::util::base64_decode(encoded)
            .ok_or_else(|| Error::Verification(format!("{field}[{key}] is not standard base64")))?;
        if bytes.len() > max_bytes {
            return Err(Error::Verification(format!(
                "{field}[{key}] exceeds the {max_bytes} byte limit"
            )));
        }
        decoded.insert(key.clone(), bytes);
    }
    Ok(decoded)
}

/// Canonicalize `mime_type` and reject one the selected policy has no
/// embedded-manifest reader for. The 2.4 policy reads exactly the 2.4
/// registry; the 2.5 policy adds the carriers and text families 2.5 defines
/// ([`crate::c2pa_core::spec::reader_permits`]).
pub(crate) fn resolve_mime(mime_type: &str, profile: EngineProfile) -> Result<String, Error> {
    let mime = canonicalize_mime(mime_type);
    if !crate::c2pa_core::spec::reader_permits(&mime, profile.version)
        || crate::c2pa_formats::AssetFormat::from_canonical_mime(&mime).is_none()
    {
        return Err(Error::UnsupportedMime(mime));
    }
    Ok(mime)
}

/// Canonicalize the media type of an asset bound by a separately supplied
/// store.
///
/// Retained profiles admit ordinary readers and designated detached media.
/// C2PA 2.5 also admits syntactically valid unknown types as opaque bytes.
/// Byte checks happen in the shared detached validation pipeline.
fn resolve_detached_mime(mime_type: &str, profile: EngineProfile) -> Result<String, Error> {
    let mime = crate::c2pa_formats::canonicalize_detached_mime(mime_type);
    if !crate::c2pa_formats::detached_mime_permitted(&mime, profile.version) {
        return Err(Error::UnsupportedMime(mime));
    }
    Ok(mime)
}

/// Whether `mime` would be read with the generic XML comment armor: an
/// XML-derived type without a dedicated carrier.
fn is_xml_comment_carrier(mime: &str) -> bool {
    (matches!(mime, "application/xml" | "text/xml") || mime.ends_with("+xml"))
        && matches!(
            crate::c2pa_formats::AssetFormat::from_canonical_mime(mime),
            Some(crate::c2pa_formats::AssetFormat::TextStructured {
                comment_prefix: "<!--",
                ..
            })
        )
}

fn require_embedded_mime(mime: &str, profile: EngineProfile) -> Result<(), Error> {
    // The draft's generic XML comment armor contains "--", forbidden inside
    // XML comments (upstream issue 2590), so no well-formed XML document can
    // carry it. This covers every XML-derived type without a dedicated
    // carrier (XML, XHTML, RSS, Atom, MathML, ...). Dedicated SVG/TTML
    // carriers and separately supplied manifest stores are not this
    // embedding method and stay readable.
    if profile.version == SpecVersion::V2_5 && is_xml_comment_carrier(mime) {
        return Err(Error::UnsupportedMime(mime.to_owned()));
    }
    Ok(())
}

pub(crate) fn map_validate_error(error: crate::c2pa_validate::ValidateError) -> Error {
    match error {
        crate::c2pa_validate::ValidateError::UnsupportedMime(value) => {
            Error::UnsupportedMime(value)
        }
        other => Error::Verification(other.to_string()),
    }
}

/// Assemble the caller-facing report from one kernel verification.
pub(crate) fn report_from_output(
    output: crate::c2pa_validate::VerifyOutput,
    mime: String,
    resolved: &ResolvedOptions,
) -> VerificationReport {
    let present = output
        .report_json
        .pointer("/provenance_verdict/present")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    let integrity = output
        .report_json
        .pointer("/provenance_verdict/integrity")
        .and_then(Value::as_str)
        .unwrap_or(if present { "invalid" } else { "absent" })
        .to_string();
    let trust = trust_report(
        &output.results,
        present,
        resolved.trust_basis,
        resolved.validation_time_text.clone(),
    );
    VerificationReport {
        schema_version: REPORT_SCHEMA_VERSION.to_string(),
        profile: report_profile(resolved.profile).to_string(),
        mime_type: mime,
        present,
        integrity,
        signature: signature_status(&output.results),
        hard_binding: hard_binding_status(&output.results),
        trust,
        policy: None,
        managed_receipt: None,
        validation_state: output.validation_state.as_str().to_string(),
        validation_results: copy_results(&output.results),
        manifest_report: output.report_json,
        content_credentials: output.crjson,
        network: NetworkReport::default(),
    }
}

/// Verify with the online pass when evidence was gathered, returning the
/// capture of the pass whose report is returned.
fn verify_with_options_inner(
    data: &[u8],
    fragments: Option<&[&[u8]]>,
    mime_type: &str,
    options: &VerifyOptions,
    resolved: ResolvedOptions,
) -> Result<(VerificationReport, PassCapture), Error> {
    let mime = resolve_mime(mime_type, resolved.profile)?;
    require_embedded_mime(&mime, resolved.profile)?;
    if resolved.profile.version == SpecVersion::V2_5 {
        return verify_embedded_online_v25(data, fragments, &mime, options, resolved);
    }

    let (mut report, needs, capture) =
        embedded_pass_resolved(data, fragments, &mime, options, &resolved)?;
    let (mut network, evidence) = online::gather(options, &needs);
    if evidence.is_empty() {
        report.network = network;
        return Ok((report, capture));
    }
    let next = online::apply_evidence(options, &evidence);
    let second = match (evidence.manifest_store.as_deref(), fragments) {
        // The asset said where its manifest store lives and the store was
        // fetched. Pass 2 verifies the asset against it exactly as it would
        // against a sidecar handed in by the caller, hard binding and all.
        (Some(store), None) => detached_pass(data, store, &mime, &next, GraphInputs::default()),
        _ => embedded_pass(data, fragments, &mime, &next),
    };
    match second {
        Ok((mut second, _, second_capture)) => {
            second.network = network;
            Ok((second, second_capture))
        }
        // Legacy policies preserve their established fallback when a remote
        // body is not a usable store. Exact 2.5 never takes this route.
        Err(error) => {
            network.mark_unusable("remote_manifest", error.to_string());
            report.network = network;
            Ok((report, capture))
        }
    }
}

fn merged_did_documents(
    pinned: Option<&HashMap<String, Value>>,
    fetched: HashMap<String, Value>,
) -> Option<HashMap<String, Value>> {
    if fetched.is_empty() {
        return None;
    }
    let mut merged = pinned.cloned().unwrap_or_default();
    for (did, document) in fetched {
        merged.entry(did).or_insert(document);
    }
    Some(merged)
}

fn verify_embedded_online_v25(
    data: &[u8],
    fragments: Option<&[&[u8]]>,
    mime: &str,
    options: &VerifyOptions,
    mut resolved: ResolvedOptions,
) -> Result<(VerificationReport, PassCapture), Error> {
    let mut plan = locate_external_resources(data, mime, options, GraphLimits::default())?;
    let terminal_uri = (!plan.manifest_store_present)
        .then(|| {
            plan.resources
                .iter()
                .find(|request| request.kind == ExternalResourceKind::SegmentManifestStore)
                .map(|request| request.uri.clone())
        })
        .flatten();
    let mut online = native_online::NativeOnline::new(resolved.take_external_data(), options);

    while !plan.resources.is_empty() {
        let frontier = plan.resources.clone();
        for request in &frontier {
            online.ensure_graph_resource(
                options,
                request,
                terminal_uri.as_deref() == Some(request.uri.as_str()),
            );
        }
        plan.continue_with(online.resources())?;
    }
    online.mark_discovery_stop(plan.stop_reason.as_ref());

    let fetched_dids = online.resolve_did_documents(
        options,
        plan.did_documents(),
        options.cawg_did_documents.as_ref(),
    );
    let merged_dids = merged_did_documents(options.cawg_did_documents.as_ref(), fetched_dids);
    let did_documents = merged_dids.as_ref().or(options.cawg_did_documents.as_ref());
    let graph_inputs = GraphInputs {
        external: Some(online.resources()),
        limits: GraphLimits::default(),
    };
    let (mut report, mut needs, mut capture) = embedded_graph_pass_resolved(
        data,
        fragments,
        mime,
        options,
        &resolved,
        did_documents,
        graph_inputs,
    )?;

    let ocsp = online.fetch_ocsp(options, &needs);
    if ocsp.has_evidence() {
        resolved.apply_ocsp_update(ocsp);
        let graph_inputs = GraphInputs {
            external: Some(online.resources()),
            limits: GraphLimits::default(),
        };
        (report, needs, capture) = embedded_graph_pass_resolved(
            data,
            fragments,
            mime,
            options,
            &resolved,
            did_documents,
            graph_inputs,
        )?;
    }
    report.network = online.finish(&needs);
    Ok((report, capture))
}

fn verify_detached_online_v25(
    asset: &[u8],
    manifest_store: &[u8],
    mime: &str,
    options: &VerifyOptions,
    mut resolved: ResolvedOptions,
) -> Result<VerificationReport, Error> {
    let mut plan =
        c2pa_validate::external_discovery::locate_external_resources_with_canonical_manifest_store(
            asset,
            manifest_store,
            mime,
            resolved.profile,
            GraphLimits::default(),
        )?;
    let mut online = native_online::NativeOnline::new(resolved.take_external_data(), options);
    while !plan.resources.is_empty() {
        let frontier = plan.resources.clone();
        for request in &frontier {
            online.ensure_graph_resource(options, request, false);
        }
        plan.continue_with(online.resources())?;
    }
    online.mark_discovery_stop(plan.stop_reason.as_ref());

    let fetched_dids = online.resolve_did_documents(
        options,
        plan.did_documents(),
        options.cawg_did_documents.as_ref(),
    );
    let merged_dids = merged_did_documents(options.cawg_did_documents.as_ref(), fetched_dids);
    let did_documents = merged_dids.as_ref().or(options.cawg_did_documents.as_ref());
    let graph_inputs = GraphInputs {
        external: Some(online.resources()),
        limits: GraphLimits::default(),
    };
    let (mut report, mut needs, _) = detached_pass_resolved(
        asset,
        manifest_store,
        mime,
        options,
        &resolved,
        did_documents,
        graph_inputs,
    )?;

    let ocsp = online.fetch_ocsp(options, &needs);
    if ocsp.has_evidence() {
        resolved.apply_ocsp_update(ocsp);
        let graph_inputs = GraphInputs {
            external: Some(online.resources()),
            limits: GraphLimits::default(),
        };
        (report, needs, _) = detached_pass_resolved(
            asset,
            manifest_store,
            mime,
            options,
            &resolved,
            did_documents,
            graph_inputs,
        )?;
    }
    report.network = online.finish(&needs);
    Ok(report)
}

/// One offline verification of an asset's own bytes, with the network needs it
/// recorded.
fn embedded_pass(
    data: &[u8],
    fragments: Option<&[&[u8]]>,
    mime: &str,
    options: &VerifyOptions,
) -> Result<(VerificationReport, Vec<online::NetworkNeed>, PassCapture), Error> {
    let resolved = ResolvedOptions::resolve(options)?;
    embedded_pass_resolved(data, fragments, mime, options, &resolved)
}

fn embedded_pass_resolved(
    data: &[u8],
    fragments: Option<&[&[u8]]>,
    mime: &str,
    options: &VerifyOptions,
    resolved: &ResolvedOptions,
) -> Result<(VerificationReport, Vec<online::NetworkNeed>, PassCapture), Error> {
    let input = resolved.input(data, mime);
    let mut output = match fragments {
        Some(fragments) => verify_fragmented_safe(
            &input,
            fragments,
            &options.expected_seek_positions,
            resolved.cawg_trust(),
            resolved.cawg_allowed_certs(),
            resolved.cawg_document_signing_require_anchor,
            options.cawg_did_documents.as_ref(),
            options.cawg_ica_trusted_issuers.as_deref(),
            options.cawg_ica_trust_anchors.as_deref(),
            options.cawg_ica_status_lists.as_ref(),
            GraphInputs::default(),
        ),
        None => verify_safe(
            &input,
            resolved.cawg_trust(),
            resolved.cawg_allowed_certs(),
            resolved.cawg_document_signing_require_anchor,
            options.cawg_did_documents.as_ref(),
            options.cawg_ica_trusted_issuers.as_deref(),
            options.cawg_ica_trust_anchors.as_deref(),
            options.cawg_ica_status_lists.as_ref(),
        ),
    }
    .map_err(map_validate_error)?;
    let needs = online::network_needs(&output);
    let capture = PassCapture::take(&mut output);
    Ok((
        report_from_output(output, mime.to_string(), resolved),
        needs,
        capture,
    ))
}

fn embedded_graph_pass(
    data: &[u8],
    fragments: Option<&[&[u8]]>,
    mime_type: &str,
    options: &VerifyOptions,
    resolved: &ResolvedOptions,
    graph_inputs: GraphInputs<'_>,
) -> Result<VerificationReport, Error> {
    let mime = resolve_mime(mime_type, resolved.profile)?;
    require_embedded_mime(&mime, resolved.profile)?;
    embedded_graph_pass_resolved(
        data,
        fragments,
        &mime,
        options,
        resolved,
        options.cawg_did_documents.as_ref(),
        graph_inputs,
    )
    .map(|(report, _, _)| report)
}

#[allow(clippy::too_many_arguments)]
fn embedded_graph_pass_resolved(
    data: &[u8],
    fragments: Option<&[&[u8]]>,
    mime: &str,
    options: &VerifyOptions,
    resolved: &ResolvedOptions,
    did_documents: Option<&HashMap<String, Value>>,
    graph_inputs: GraphInputs<'_>,
) -> Result<(VerificationReport, Vec<online::NetworkNeed>, PassCapture), Error> {
    let input = resolved.input(data, mime);
    let mut output = match fragments {
        Some(fragments) => verify_fragmented_safe(
            &input,
            fragments,
            &options.expected_seek_positions,
            resolved.cawg_trust(),
            resolved.cawg_allowed_certs(),
            resolved.cawg_document_signing_require_anchor,
            did_documents,
            options.cawg_ica_trusted_issuers.as_deref(),
            options.cawg_ica_trust_anchors.as_deref(),
            options.cawg_ica_status_lists.as_ref(),
            graph_inputs,
        ),
        None => verify_graph_safe(
            &input,
            resolved.cawg_trust(),
            resolved.cawg_allowed_certs(),
            resolved.cawg_document_signing_require_anchor,
            did_documents,
            options.cawg_ica_trusted_issuers.as_deref(),
            options.cawg_ica_trust_anchors.as_deref(),
            options.cawg_ica_status_lists.as_ref(),
            graph_inputs,
        ),
    }
    .map_err(map_validate_error)?;
    let needs = online::network_needs(&output);
    let capture = PassCapture::take(&mut output);
    Ok((
        report_from_output(output, mime.to_string(), resolved),
        needs,
        capture,
    ))
}

/// Read and verify one local asset.
///
/// Path-based verification accepts regular files up to 128 MiB. Byte-slice
/// verification remains bounded only by caller memory.
pub fn verify_file(
    path: impl AsRef<Path>,
    mime_type: Option<&str>,
    options: &VerifyOptions,
) -> Result<VerificationReport, Error> {
    let resolved = ResolvedOptions::resolve(options)?;
    let path = path.as_ref();
    let mime = match mime_type {
        Some(value) => value.to_string(),
        None => mime_from_path(path)
            .ok_or_else(|| Error::UnsupportedMime(path.display().to_string()))?
            .to_string(),
    };
    let data = read_path_asset(path, MAX_PATH_ASSET_BYTES)?;
    verify_with_resolved_options(&data, None, &mime, options, resolved)
}

fn read_path_asset(path: &Path, limit: u64) -> io::Result<Vec<u8>> {
    let mut options = OpenOptions::new();
    options.read(true);
    #[cfg(unix)]
    options.custom_flags(libc::O_NONBLOCK | libc::O_CLOEXEC);

    // Open once, then validate that exact handle. On Unix O_NONBLOCK prevents
    // a FIFO substituted for the path from blocking before it can be rejected.
    let mut file = options.open(path)?;
    let opened_metadata = file.metadata()?;
    validate_path_asset(path, &opened_metadata, limit)?;
    read_bounded_file(&mut file, opened_metadata.len(), limit)
}

fn validate_path_asset(path: &Path, metadata: &fs::Metadata, limit: u64) -> io::Result<()> {
    if !metadata.is_file() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("asset path is not a regular file: {}", path.display()),
        ));
    }
    if metadata.len() > limit {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!("asset exceeds the 128 MiB path limit: {}", path.display()),
        ));
    }
    Ok(())
}

fn read_bounded_file<R: Read>(file: &mut R, expected_len: u64, limit: u64) -> io::Result<Vec<u8>> {
    if expected_len > limit {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "asset exceeds the path size limit",
        ));
    }
    let expected_len = usize::try_from(expected_len)
        .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "asset size is not addressable"))?;
    let mut data = vec![0_u8; expected_len + 1];
    let mut used = 0;
    while used < expected_len {
        let read = file.read(&mut data[used..expected_len])?;
        if read == 0 {
            break;
        }
        used += read;
    }
    if used == expected_len && file.read(&mut data[expected_len..expected_len + 1])? != 0 {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "asset grew while being read",
        ));
    }
    data.truncate(used);
    Ok(data)
}

/// Canonical MIME types covered by the C2PA 2.4 profile and readable by this build.
pub fn supported_mime_types() -> Vec<&'static str> {
    let mut mimes: Vec<_> = mimes_for_version(SpecVersion::V2_4)
        .into_iter()
        .filter(|mime| crate::c2pa_formats::AssetFormat::from_mime(mime).is_some())
        .collect();
    mimes.sort_unstable();
    mimes.dedup();
    mimes
}

/// Canonical MIME types the caller-selected policy reads with an embedded
/// manifest carrier. `None` is exactly `"2.4"`. The finite 2.2 and 2.4 lists
/// come from the shared format registry. `"2.5"` adds the standard ZIP package
/// and generic-container names used by generator products, plus WARC, MIDI,
/// TTML, ONNX, SafeTensors, Parquet, BlockFact, append-only JSON Lines, WebVTT
/// and textual comment-syntax types. It also reads the OpenDocument family,
/// other `text/*` types and `+xml` types by family, which no finite list can
/// enumerate. Generic XML-comment embedding stays unreadable under 2.5
/// (upstream issue 2590), so XML types without a dedicated carrier are omitted.
/// Any well-formed type can still be verified against a separately supplied
/// store with [`verify_with_manifest_store`].
pub fn supported_mime_types_for(spec_version: Option<&str>) -> Result<Vec<&'static str>, Error> {
    let profile = resolve_profile(spec_version, false)?;
    let registry_version = match profile.version {
        SpecVersion::V2_5 => SpecVersion::V2_4,
        version => version,
    };
    let mut mimes: Vec<_> = mimes_for_version(registry_version)
        .into_iter()
        .chain(
            (profile.version == SpecVersion::V2_5)
                .then_some(crate::c2pa_core::spec::V2_5_READER_MIMES)
                .into_iter()
                .flatten()
                .copied(),
        )
        .filter(|mime| crate::c2pa_formats::AssetFormat::from_mime(mime).is_some())
        .filter(|mime| require_embedded_mime(mime, profile).is_ok())
        .collect();
    mimes.sort_unstable();
    mimes.dedup();
    Ok(mimes)
}

/// Every filename extension the SDK maps to a MIME type, with its mapping.
///
/// This is the single source of truth for extension inference. It is public so
/// that callers can discover it and so that the non-mutation contract tests
/// iterate the real table rather than a hand-copied list: a reviewer hid a
/// writer in the `.dng` branch precisely because the test's own copy had
/// drifted and omitted it.
pub const SUPPORTED_EXTENSIONS: &[(&str, &str)] = &[
    ("jpg", "image/jpeg"),
    ("jpeg", "image/jpeg"),
    ("png", "image/png"),
    ("webp", "image/webp"),
    ("gif", "image/gif"),
    ("tif", "image/tiff"),
    ("tiff", "image/tiff"),
    ("dng", "image/x-adobe-dng"),
    ("heic", "image/heic"),
    ("heics", "image/heic-sequence"),
    ("heif", "image/heif"),
    ("heifs", "image/heif-sequence"),
    ("avif", "image/avif"),
    ("jxl", "image/jxl"),
    ("svg", "image/svg+xml"),
    ("mp4", "video/mp4"),
    ("m4v", "video/mp4"),
    ("mov", "video/quicktime"),
    ("avi", "video/x-msvideo"),
    ("wav", "audio/wav"),
    ("mp3", "audio/mpeg"),
    ("m4a", "audio/mp4"),
    ("aac", "audio/aac"),
    ("flac", "audio/flac"),
    ("ogg", "audio/ogg"),
    ("oga", "audio/ogg"),
    ("pdf", "application/pdf"),
    ("zip", "application/zip"),
    ("sketch", "application/zip"),
    ("epub", "application/epub+zip"),
    (
        "docx",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    ),
    (
        "xlsx",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    ),
    (
        "pptx",
        "application/vnd.openxmlformats-officedocument.presentationml.presentation",
    ),
    (
        "dotx",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
    ),
    ("docm", "application/vnd.ms-word.document.macroenabled.12"),
    ("dotm", "application/vnd.ms-word.template.macroenabled.12"),
    (
        "xltx",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
    ),
    ("xlsm", "application/vnd.ms-excel.sheet.macroenabled.12"),
    ("xltm", "application/vnd.ms-excel.template.macroenabled.12"),
    (
        "xlsb",
        "application/vnd.ms-excel.sheet.binary.macroenabled.12",
    ),
    (
        "ppsx",
        "application/vnd.openxmlformats-officedocument.presentationml.slideshow",
    ),
    (
        "potx",
        "application/vnd.openxmlformats-officedocument.presentationml.template",
    ),
    (
        "pptm",
        "application/vnd.ms-powerpoint.presentation.macroenabled.12",
    ),
    (
        "ppsm",
        "application/vnd.ms-powerpoint.slideshow.macroenabled.12",
    ),
    (
        "potm",
        "application/vnd.ms-powerpoint.template.macroenabled.12",
    ),
    ("vsdx", "application/vnd.ms-visio.drawing"),
    ("vsdm", "application/vnd.ms-visio.drawing.macroenabled.12"),
    ("vssx", "application/vnd.ms-visio.stencil"),
    ("vssm", "application/vnd.ms-visio.stencil.macroenabled.12"),
    ("vstx", "application/vnd.ms-visio.template"),
    ("vstm", "application/vnd.ms-visio.template.macroenabled.12"),
    ("oxps", "application/oxps"),
    ("xps", "application/vnd.ms-xpsdocument"),
    ("odt", "application/vnd.oasis.opendocument.text"),
    ("ods", "application/vnd.oasis.opendocument.spreadsheet"),
    ("odp", "application/vnd.oasis.opendocument.presentation"),
    ("odg", "application/vnd.oasis.opendocument.graphics"),
    ("ttf", "font/ttf"),
    ("otf", "font/otf"),
    ("sfnt", "font/sfnt"),
    ("txt", "text/plain"),
    ("tsv", "text/tab-separated-values"),
    ("csv", "text/csv"),
    ("md", "text/markdown"),
    ("markdown", "text/markdown"),
    ("html", "text/html"),
    ("htm", "text/html"),
    ("xhtml", "application/xhtml+xml"),
    ("xml", "application/xml"),
    ("css", "text/css"),
    ("js", "application/javascript"),
    ("mjs", "application/javascript"),
    ("json", "application/json"),
    ("yaml", "application/yaml"),
    ("yml", "application/yaml"),
    ("toml", "application/toml"),
    ("py", "text/x-python"),
    // Carriers C2PA 2.5 adds. Their media types are read only under the 2.5
    // policy; the default 2.4 policy reports them as unsupported.
    ("warc", "application/warc"),
    ("mid", "audio/midi"),
    ("midi", "audio/midi"),
    ("ttml", "application/ttml+xml"),
    ("onnx", "application/onnx"),
    ("safetensors", "application/safetensors"),
    ("parquet", "application/vnd.apache.parquet"),
    ("facti", "image/vnd.blockfact.facti"),
    ("facta", "audio/vnd.blockfact.facta"),
    ("factv", "video/vnd.blockfact.factv"),
    ("jsonl", "application/jsonl"),
    ("ndjson", "application/jsonl"),
    ("vtt", "text/vtt"),
];

/// Infer a MIME type from a filename extension, case-insensitively.
pub fn mime_from_path(path: &Path) -> Option<&'static str> {
    let extension = path.extension()?.to_str()?.to_ascii_lowercase();
    SUPPORTED_EXTENSIONS
        .iter()
        .find(|(candidate, _)| *candidate == extension)
        .map(|(_, mime)| *mime)
}

enum ResolvedTrust {
    Bundled(&'static TrustList),
    Owned(TrustList),
}

impl ResolvedTrust {
    fn get(&self) -> &TrustList {
        match self {
            Self::Bundled(trust) => trust,
            Self::Owned(trust) => trust,
        }
    }
}

/// Resolve one purpose's trust store: the bundled snapshot, the caller's PEM
/// bundle, or the snapshot extended by it.
///
/// Caller-supplied anchors take the configured `bounds`; bundled snapshots stay
/// unbounded, because their trust window is the snapshot itself.
///
/// CAWG identity material a caller supplies is an entry that caller configured
/// as the validator, so it is accepted under the CAWG Identity 1.3 base trust
/// model rather than under the interim S/MIME additions, which belong to the
/// two root stores that section names.
fn resolve_trust(
    custom_pem: Option<&str>,
    sources: Option<&[TrustListSource]>,
    bundled: Option<&'static TrustList>,
    purpose: AnchorPurpose,
    bounds: (Option<OffsetDateTime>, Option<OffsetDateTime>),
) -> Result<Option<ResolvedTrust>, Error> {
    let mut custom = custom_pem
        .map(|pem| TrustList::from_pem_for(purpose, pem))
        .transpose()
        .map_err(|error| Error::InvalidTrust(error.to_string()))?
        .map(|trust| trust.with_bounds(bounds.0, bounds.1))
        .map(|trust| match purpose {
            AnchorPurpose::CawgIdentity => trust.with_cawg_source(CawgTrustSource::CallerSupplied),
            _ => trust,
        });
    let mut windowed = TrustList::default();
    for (index, source) in sources.unwrap_or_default().iter().enumerate() {
        if source.uri.trim().is_empty() || url::Url::parse(&source.uri).is_err() {
            return Err(Error::InvalidTrust(format!(
                "trust source {index} has an invalid uri"
            )));
        }
        if source.source_type.trim().is_empty() {
            return Err(Error::InvalidTrust(format!(
                "trust source {index} has an empty type"
            )));
        }
        if source
            .identifier
            .as_ref()
            .is_some_and(|value| value.trim().is_empty())
        {
            return Err(Error::InvalidTrust(format!(
                "trust source {index} has an empty identifier"
            )));
        }
        let instant = |value: Option<&str>, field: &str| {
            value
                .map(|raw| {
                    OffsetDateTime::parse(raw, &Rfc3339).map_err(|error| {
                        Error::InvalidTrust(format!("trust source {index}.{field}: {error}"))
                    })
                })
                .transpose()
        };
        let not_before = instant(source.not_before.as_deref(), "not_before")?;
        let not_after = instant(source.not_after.as_deref(), "not_after")?;
        if let (Some(start), Some(end)) = (not_before, not_after) {
            if start > end {
                return Err(Error::InvalidTrust(format!(
                    "trust source {index}: not_before is later than not_after"
                )));
            }
        }
        // A source-specific window may narrow, but never relax, the caller's
        // bounds on all supplied anchors.
        let not_before = not_before.into_iter().chain(bounds.0).max();
        let not_after = not_after.into_iter().chain(bounds.1).min();
        let mut metadata =
            crate::c2pa_trust::TrustSource::new(source.uri.clone(), source.source_type.clone());
        if let Some(identifier) = &source.identifier {
            metadata = metadata.with_identifier(identifier.clone());
        }
        let sourced = TrustList::from_pem_for(purpose, &source.certificates_pem)
            .map_err(|error| Error::InvalidTrust(format!("trust source {index}: {error}")))?
            .with_bounds(not_before, not_after)
            .with_source(metadata);
        if source.not_before.is_some() || source.not_after.is_some() {
            for anchor in sourced.anchors {
                if let Some(existing) = windowed
                    .anchors
                    .iter_mut()
                    .find(|existing| existing.certificate == anchor.certificate)
                {
                    existing.not_before = existing
                        .not_before
                        .into_iter()
                        .chain(anchor.not_before)
                        .max();
                    existing.not_after =
                        existing.not_after.into_iter().chain(anchor.not_after).min();
                } else {
                    windowed.anchors.push(anchor);
                }
            }
        } else {
            match &mut custom {
                Some(custom) => custom.anchors.extend(sourced.anchors),
                None => custom = Some(sourced),
            }
        }
    }
    if !windowed.anchors.is_empty() {
        let mut merged = bundled.cloned().unwrap_or_default();
        if let Some(custom) = custom {
            merged.anchors.extend(custom.anchors);
        }
        // A window is a restriction on the certificate, not just on one
        // occurrence of it. Remove every unbounded duplicate, including a
        // bundled copy, before installing the intersected sourced entry.
        merged.anchors.retain(|anchor| {
            !windowed
                .anchors
                .iter()
                .any(|bounded| bounded.certificate == anchor.certificate)
        });
        merged.anchors.extend(windowed.anchors);
        return Ok(Some(ResolvedTrust::Owned(merged)));
    }
    match (bundled, custom) {
        (None, None) => Ok(None),
        (Some(trust), None) => Ok(Some(ResolvedTrust::Bundled(trust))),
        (None, Some(trust)) => Ok(Some(ResolvedTrust::Owned(trust))),
        (Some(bundled), Some(custom)) => {
            let mut merged = bundled.clone();
            merged.anchors.extend(custom.anchors);
            Ok(Some(ResolvedTrust::Owned(merged)))
        }
    }
}

/// Build the CAWG anchors and direct matches the caller's typed trust
/// configurations contribute, each certificate tagged with its entry's
/// profile and window and placed by what it is.
///
/// A malformed entry fails the call and names itself: silently dropping a
/// source or a bound would change which signatures the configuration
/// validates.
fn resolve_cawg_configurations(
    configurations: Option<&[CawgTrustConfiguration]>,
) -> Result<(TrustList, TrustList), Error> {
    let mut anchors = TrustList::default();
    let mut direct = TrustList::default();
    for (index, configuration) in configurations.unwrap_or_default().iter().enumerate() {
        let invalid = |field: &str, detail: &dyn std::fmt::Display| {
            Error::InvalidTrust(format!(
                "cawg_trust_configurations[{index}]{field}: {detail}"
            ))
        };
        let instant = |value: Option<&str>, field| {
            value
                .map(|raw| {
                    OffsetDateTime::parse(raw, &Rfc3339).map_err(|error| invalid(field, &error))
                })
                .transpose()
        };
        let not_before = instant(configuration.not_before.as_deref(), ".not_before")?;
        let not_after = instant(configuration.not_after.as_deref(), ".not_after")?;
        if let (Some(start), Some(end)) = (not_before, not_after) {
            if start > end {
                return Err(invalid("", &"not_before is later than not_after"));
            }
        }
        let source = match configuration.profile {
            CawgTrustProfile::Base => CawgTrustSource::CallerSupplied,
            CawgTrustProfile::SmimeInterim => CawgTrustSource::SmimeInterim,
        };
        let (entry_anchors, entry_direct) =
            TrustList::from_pem_for(AnchorPurpose::CawgIdentity, &configuration.certificates_pem)
                .map_err(|error| invalid(".certificates_pem", &error))?
                .with_bounds(not_before, not_after)
                .with_cawg_source(source)
                .split_certificate_authorities();
        anchors.anchors.extend(entry_anchors.anchors);
        direct.anchors.extend(entry_direct.anchors);
    }
    Ok((anchors, direct))
}

/// Append `extra` to one resolved trust store.
fn extend_trust(resolved: Option<ResolvedTrust>, extra: TrustList) -> Option<ResolvedTrust> {
    if extra.anchors.is_empty() {
        return resolved;
    }
    let mut merged = match resolved {
        None => return Some(ResolvedTrust::Owned(extra)),
        Some(ResolvedTrust::Bundled(bundled)) => bundled.clone(),
        Some(ResolvedTrust::Owned(owned)) => owned,
    };
    merged.anchors.extend(extra.anchors);
    Some(ResolvedTrust::Owned(merged))
}

fn parse_validation_time(value: Option<&str>) -> Result<OffsetDateTime, Error> {
    match value {
        Some(raw) => OffsetDateTime::parse(raw, &Rfc3339)
            .map_err(|error| Error::InvalidValidationTime(error.to_string())),
        None => Ok(OffsetDateTime::now_utc()),
    }
}

/// Parse an optional RFC 3339 trust-anchor bound, naming the field in the error
/// so a caller can tell which of the two bounds it mistyped.
fn parse_optional_instant(
    value: Option<&str>,
    field: &str,
) -> Result<Option<OffsetDateTime>, Error> {
    value
        .map(|raw| {
            OffsetDateTime::parse(raw, &Rfc3339)
                .map_err(|error| Error::InvalidValidationTime(format!("{field}: {error}")))
        })
        .transpose()
}

fn parse_stream_presentation_time(raw: &str, index: usize) -> Result<OffsetDateTime, Error> {
    OffsetDateTime::parse(raw, &Rfc3339).map_err(|error| {
        Error::InvalidValidationTime(format!("stream_presentation_times[{index}]: {error}"))
    })
}

/// Parse caller-supplied per-segment presentation instants, naming the first
/// malformed entry by index. `None` stays `None`: the stream is then assessed
/// at `validation_time`, never at a time read from the segments themselves.
pub(crate) fn parse_stream_presentation_times(
    values: Option<&[String]>,
) -> Result<Option<Vec<OffsetDateTime>>, Error> {
    values
        .map(|values| {
            values
                .iter()
                .enumerate()
                .map(|(index, raw)| parse_stream_presentation_time(raw, index))
                .collect()
        })
        .transpose()
}

fn copy_status(status: &CoreStatus) -> VerificationStatus {
    VerificationStatus {
        code: status.code.clone(),
        url: status.url.clone(),
        resource_url: status.resource_url.clone(),
        explanation: status.explanation.clone(),
        details: status.details.clone(),
    }
}

fn copy_results(results: &CoreResults) -> ValidationResults {
    ValidationResults {
        success: results.success.iter().map(copy_status).collect(),
        informational: results.informational.iter().map(copy_status).collect(),
        failure: results.failure.iter().map(copy_status).collect(),
        trust_list_sources: results.trust_list_sources.clone(),
    }
}

fn signature_status(results: &CoreResults) -> String {
    if results.has_success(CLAIM_SIGNATURE_VALIDATED) {
        "valid"
    } else if results.has_failure(CLAIM_SIGNATURE_MISMATCH) {
        "invalid"
    } else if results.has_failure(CLAIM_SIGNATURE_MISSING) {
        "missing"
    } else {
        "unknown"
    }
    .to_string()
}

fn hard_binding_status(results: &CoreResults) -> String {
    const MATCHES: &[&str] = &[
        ASSERTION_DATA_HASH_MATCH,
        ASSERTION_BMFF_HASH_MATCH,
        ASSERTION_BOXES_HASH_MATCH,
        ASSERTION_COLLECTION_HASH_MATCH,
        ASSERTION_MULTI_ASSET_HASH_MATCH,
        crate::c2pa_validate::ASSERTION_SEGMENT_HASH_MATCH,
    ];
    const FAILURES: &[&str] = &[
        ASSERTION_DATA_HASH_MISMATCH,
        ASSERTION_BMFF_HASH_MISMATCH,
        ASSERTION_BMFF_HASH_MALFORMED,
        ASSERTION_BOXES_HASH_MISMATCH,
        ASSERTION_BOXES_HASH_MALFORMED,
        ASSERTION_COLLECTION_HASH_MISMATCH,
        ASSERTION_COLLECTION_HASH_MALFORMED,
        ASSERTION_MULTI_ASSET_HASH_MISMATCH,
        ASSERTION_MULTI_ASSET_HASH_MALFORMED,
        crate::c2pa_validate::ASSERTION_SEGMENT_HASH_MISMATCH,
        crate::c2pa_validate::ASSERTION_SEGMENT_HASH_MALFORMED,
        crate::c2pa_validate::ASSERTION_SEGMENT_HASH_PARTIAL_COVERAGE,
        crate::c2pa_validate::ASSERTION_SEGMENT_HASH_PREDECESSOR_MISMATCH,
    ];
    // Checked before the match set, and it has to be: a manifest that binds
    // only its init segment DOES produce `assertion.bmffHash.match` over those
    // bytes, so a match-first read would answer "match" for a stream whose
    // media segments nothing covered. The axis answers "is every byte the
    // caller presented bound?", so an unbound or unauthenticated segment is a
    // mismatch no matter what else matched (PRD 1.1.1). The same holds for an
    // append-only file: the active checkpoint can match while an earlier
    // segment was rewritten, and a refused caller verdict binds nothing.
    const UNBOUND: &[&str] = &[
        crate::c2pa_validate::live_video::LIVEVIDEO_SEGMENT_INVALID,
        crate::c2pa_validate::ASSERTION_SEGMENT_HASH_MISMATCH,
        crate::c2pa_validate::ASSERTION_SEGMENT_HASH_MALFORMED,
        crate::c2pa_validate::ASSERTION_SEGMENT_HASH_PARTIAL_COVERAGE,
        crate::c2pa_validate::ASSERTION_SEGMENT_HASH_PREDECESSOR_MISMATCH,
        crate::c2pa_validate::HARD_BINDING_CALLER_EVIDENCE_MISMATCH,
    ];
    if UNBOUND.iter().any(|code| results.has_failure(code)) {
        "mismatch"
    } else if MATCHES.iter().any(|code| results.has_success(code)) {
        "match"
    } else if FAILURES.iter().any(|code| results.has_failure(code)) {
        "mismatch"
    } else if results.has_failure(CLAIM_HARD_BINDINGS_MISSING) {
        "missing"
    } else {
        "unknown"
    }
    .to_string()
}

fn trust_report(
    results: &CoreResults,
    present: bool,
    basis: &str,
    validation_time: String,
) -> TrustReport {
    let supplied = basis != "none";
    let trusted = results.has_success(SIGNING_CREDENTIAL_TRUSTED);
    let rejected = results.has_failure(SIGNING_CREDENTIAL_UNTRUSTED)
        || results.has_failure(SIGNING_CREDENTIAL_INVALID);
    let revoked = results.has_failure(SIGNING_CREDENTIAL_OCSP_REVOKED);
    let not_revoked = results.has_success(SIGNING_CREDENTIAL_OCSP_NOT_REVOKED);
    TrustReport {
        status: if trusted && !revoked {
            "valid_for_supplied_material"
        } else if present && supplied && (rejected || revoked) {
            "not_valid_for_supplied_material"
        } else {
            "not_evaluated"
        }
        .to_string(),
        basis: basis.to_string(),
        validation_time,
        revocation: RevocationReport {
            status: if revoked {
                "revoked"
            } else if not_revoked {
                "not_revoked"
            } else {
                "not_checked"
            }
            .to_string(),
            source: if !(revoked || not_revoked) {
                "none"
            } else if results
                .success
                .iter()
                .chain(&results.failure)
                .filter(|status| {
                    status.code == SIGNING_CREDENTIAL_OCSP_REVOKED
                        || status.code == SIGNING_CREDENTIAL_OCSP_NOT_REVOKED
                })
                .any(|status| {
                    status
                        .details
                        .as_ref()
                        .and_then(|details| details.get("source"))
                        .and_then(Value::as_str)
                        == Some("online_ocsp")
                })
            {
                "online_ocsp"
            } else {
                "embedded_ocsp"
            }
            .to_string(),
            responder_signature: if revoked || not_revoked {
                "valid"
            } else {
                "not_applicable"
            }
            .to_string(),
        },
        freshness: FreshnessReport {
            status: "unknown".to_string(),
            as_of: None,
        },
    }
}

#[cfg(test)]
mod tests {
    use super::{
        detached_manifest_evidence, mime_from_path, read_bounded_file, supported_mime_types,
        verify, verify_file, verify_fragmented, verify_fragmented_with_graph_inputs,
        verify_manifest_store_only_with_graph_inputs, verify_with_manifest_store_and_graph_inputs,
        verify_with_options, CawgTrustConfiguration, CawgTrustProfile, Error, GraphInputs,
        GraphLimits, VerificationReport, VerifyOptions,
    };
    use std::{io::Cursor, path::Path};

    #[test]
    fn windowed_claim_sources_override_pem_duplicates_and_intersect() {
        use crate::c2pa_crypto::extract_x5chain;
        use crate::c2pa_trust::{validate_chain_with, AnchorPurpose, CertificateProfile};
        use crate::c2pa_validate::signature_conformance_tests::Signer;
        use time::macros::datetime;

        let signer = Signer::conformant();
        let other = Signer::conformant();
        let pem = format!("{}{}", signer.root_pem(), other.root_pem());
        let chain = extract_x5chain(&signer.sign(b"claim")).unwrap();
        let other_chain = extract_x5chain(&other.sign(b"claim")).unwrap();
        let source = |uri: &str, start: Option<&str>, end: Option<&str>| {
            serde_json::from_value::<super::TrustListSource>(serde_json::json!({
                "uri": uri, "type": "c2pa.trustList", "certificates_pem": signer.root_pem(),
                "not_before": start, "not_after": end,
            }))
            .unwrap()
        };
        for reverse in [false, true] {
            let mut sources = vec![
                source("urn:fixture:start", Some("2026-06-01T00:00:00Z"), None),
                source("urn:fixture:end", None, Some("2026-06-30T00:00:00Z")),
                source("urn:fixture:unbounded", None, None),
            ];
            if reverse {
                sources.reverse();
            }
            let trust = super::resolve_trust(
                Some(&pem),
                Some(&sources),
                None,
                AnchorPurpose::ClaimSigning,
                (None, None),
            )
            .unwrap()
            .unwrap();
            assert_eq!(trust.get().anchors.len(), 2);
            let bounded = trust
                .get()
                .anchors
                .iter()
                .find(|anchor| anchor.certificate == *chain.last().unwrap())
                .unwrap();
            assert_eq!(bounded.not_before, Some(datetime!(2026-06-01 0:00 UTC)));
            assert_eq!(bounded.not_after, Some(datetime!(2026-06-30 0:00 UTC)));
            assert!(bounded.source.as_ref().unwrap().uri != "urn:fixture:unbounded");
            for profile in [
                CertificateProfile::V2_2,
                CertificateProfile::V2_4,
                CertificateProfile::V2_5,
            ] {
                for (at, expected) in [
                    (datetime!(2026-05-31 23:59:59 UTC), false),
                    (datetime!(2026-06-01 0:00 UTC), true),
                    (datetime!(2026-06-30 0:00 UTC), true),
                    (datetime!(2026-06-30 0:00:01 UTC), false),
                ] {
                    let result = validate_chain_with(
                        &chain[0],
                        &chain[1..],
                        trust.get(),
                        AnchorPurpose::ClaimSigning,
                        Some(at),
                        profile,
                    );
                    assert_eq!(result.trusted, expected, "{at} {profile:?}: {result:?}");
                    let unaffected = validate_chain_with(
                        &other_chain[0],
                        &other_chain[1..],
                        trust.get(),
                        AnchorPurpose::ClaimSigning,
                        Some(at),
                        profile,
                    );
                    assert!(
                        unaffected.trusted,
                        "PEM-only anchor must stay trusted: {unaffected:?}"
                    );
                }
            }
        }
    }

    #[test]
    fn source_windows_are_validated_before_asset_io() {
        for field in ["not_before", "not_after"] {
            for list in ["claim_trust_sources", "tsa_trust_sources"] {
                let mut source = serde_json::json!({
                    "uri": "urn:fixture:list",
                    "type": "c2pa.tsaTrustList",
                    "certificates_pem": include_str!("c2pa-trust/tests/fixtures/rfc3161_root.pem")
                });
                source[field] = serde_json::json!("not-an-rfc3339-instant");
                let mut value = serde_json::json!({"no_default_trust": true});
                value[list] = serde_json::json!([source]);
                let options: VerifyOptions = serde_json::from_value(value).unwrap();
                let error = options.validate().unwrap_err();
                assert_eq!(error.code(), "invalid_trust_material");
                assert!(error
                    .to_string()
                    .contains(&format!("trust source 0.{field}")));
            }
        }
    }

    #[test]
    fn source_windows_preserve_global_bounds_and_refuse_reversed_dates() {
        let source = |start: &str, end: &str| {
            serde_json::from_value::<super::TrustListSource>(serde_json::json!({
                "uri": "urn:fixture:list", "type": "c2pa.tsaTrustList",
                "certificates_pem": include_str!("c2pa-trust/tests/fixtures/rfc3161_root.pem"),
                "not_before": start, "not_after": end
            }))
            .unwrap()
        };
        let global_start = time::macros::datetime!(2026-01-01 0:00 UTC);
        let global_end = time::macros::datetime!(2027-01-01 0:00 UTC);
        let sources = [source("2025-01-01T00:00:00Z", "2028-01-01T00:00:00Z")];
        let trust = super::resolve_trust(
            None,
            Some(&sources),
            None,
            super::AnchorPurpose::TimeStamping,
            (Some(global_start), Some(global_end)),
        )
        .unwrap()
        .unwrap();
        assert_eq!(trust.get().anchors[0].not_before, Some(global_start));
        assert_eq!(trust.get().anchors[0].not_after, Some(global_end));
        let options = VerifyOptions {
            tsa_trust_sources: Some(vec![source("2028-01-01T00:00:00Z", "2025-01-01T00:00:00Z")]),
            ..Default::default()
        };
        assert!(options
            .validate()
            .unwrap_err()
            .to_string()
            .contains("not_before is later than not_after"));
    }

    #[test]
    fn known_filename_maps_to_mime() {
        assert_eq!(
            mime_from_path(Path::new("composition.MP4")),
            Some("video/mp4")
        );

        assert_eq!(
            mime_from_path(Path::new("drawing.odg")),
            Some("application/vnd.oasis.opendocument.graphics")
        );
        assert_eq!(
            mime_from_path(Path::new("data.tsv")),
            Some("text/tab-separated-values")
        );
        assert_eq!(
            mime_from_path(Path::new("archive.ZIP")),
            Some("application/zip")
        );
        assert_eq!(
            mime_from_path(Path::new("design.sketch")),
            Some("application/zip")
        );
    }

    /// A supported format with no extension can only be verified by passing
    /// its MIME type by hand, so a file named `report.oxps` failed on the
    /// command line as unsupported. Only alias names of a mapped type are exempt.
    #[test]
    fn every_supported_format_is_reachable_from_an_extension() {
        const ALIASES: &[&str] = &[
            "application/font-sfnt",
            "application/x-font-ttf",
            "application/mp4",
            "video/x-m4v",
            "text/xml",
            "application/x-zip-based",
        ];
        let unreachable: Vec<_> = supported_mime_types()
            .into_iter()
            .filter(|mime| !ALIASES.contains(mime))
            .filter(|mime| !super::SUPPORTED_EXTENSIONS.iter().any(|(_, m)| m == mime))
            .collect();
        assert!(
            unreachable.is_empty(),
            "no extension maps to {unreachable:?}"
        );
        assert_eq!(
            mime_from_path(Path::new("report.OXPS")),
            Some("application/oxps")
        );
    }

    /// The trust block names where a revocation answer came from, so a reader
    /// can tell a stapled response from one fetched with the user's consent.
    #[test]
    fn revocation_source_distinguishes_online_from_embedded_ocsp() {
        use crate::c2pa_validate::{StatusCode, ValidationResults};
        let status = |source: Option<&str>| StatusCode {
            code: crate::c2pa_validate::SIGNING_CREDENTIAL_OCSP_NOT_REVOKED.into(),
            url: "self#jumbf=/c2pa/urn:c2pa:x/c2pa.signature".into(),
            resource_url: None,
            explanation: "not revoked".into(),
            details: source.map(|source| serde_json::json!({ "source": source })),
        };
        let report = |source: Option<&str>| {
            let results = ValidationResults {
                success: vec![status(source)],
                ..ValidationResults::default()
            };
            super::trust_report(&results, true, "bundled_static_material", String::new())
                .revocation
                .source
        };
        assert_eq!(report(Some("online_ocsp")), "online_ocsp");
        assert_eq!(report(None), "embedded_ocsp");
    }

    #[test]
    fn format_list_is_sorted_and_contains_composition_formats() {
        let formats = supported_mime_types();
        assert_eq!(formats.len(), 73);
        assert!(formats.windows(2).all(|pair| pair[0] < pair[1]));
        assert!(formats.contains(&"video/mp4"));
        assert!(formats.contains(&"image/jpeg"));
        assert!(formats.contains(&"text/tab-separated-values"));
        assert!(formats.contains(&"application/vnd.oasis.opendocument.graphics"));
        assert!(formats.contains(&"application/zip"));
        assert!(formats.contains(&"application/x-zip-based"));
    }

    #[test]
    fn input_alias_is_reported_as_canonical_mime() {
        let asset = b"\x00\x00\x00\x10ftypisom\x00\x00\x00\x00";
        let report = verify(asset, "audio/aac; codecs=mp4a.40.2").unwrap();
        assert_eq!(report.mime_type, "audio/mp4");
        assert!(!report.present);
    }

    #[test]
    fn strict_conformance_option_selects_the_program_profile() {
        let asset = include_bytes!("../../../tests/fixtures/signed_test.jpg");
        let report = verify_with_options(
            asset,
            "image/jpeg",
            &VerifyOptions {
                strict_conformance: true,
                ..VerifyOptions::default()
            },
        )
        .unwrap();
        assert_eq!(
            report.manifest_report["engine_profile"]["operating_mode"],
            "conformance"
        );
        assert_eq!(
            report.manifest_report["engine_profile"]["compliance_level"],
            "conformance-program"
        );
    }

    #[test]
    fn fragmented_entry_point_rejects_non_bmff_mime() {
        let error = verify_fragmented(
            include_bytes!("../../../tests/fixtures/signed_test.jpg"),
            &[b"ignored fragment"],
            "image/jpeg",
        )
        .unwrap_err();
        assert!(matches!(error, Error::UnsupportedMime(mime) if mime == "image/jpeg"));
    }

    #[test]
    fn detached_fragmented_and_store_only_routes_honor_one_graph_budget() {
        let limited = || GraphInputs {
            external: None,
            limits: GraphLimits::lowered(32, 0, 16_384, 64 * 1024 * 1024),
        };
        let has_node_limit = |report: &VerificationReport| {
            report
                .validation_results
                .informational
                .iter()
                .any(|status| {
                    status.code == "com.encypher.resource.graphLimitExceeded"
                        && status
                            .details
                            .as_ref()
                            .and_then(|details| details.get("limit"))
                            .and_then(serde_json::Value::as_str)
                            == Some("nodes")
                })
        };

        let jpeg = include_bytes!("../../../tests/fixtures/signed_test.jpg");
        let store = detached_manifest_evidence(jpeg, "image/jpeg")
            .expect("extract detached evidence")
            .expect("signed JPEG manifest")
            .manifest_store;
        let detached = verify_with_manifest_store_and_graph_inputs(
            jpeg,
            &store,
            "image/jpeg",
            &VerifyOptions::default(),
            limited(),
        )
        .expect("detached graph verification");
        assert!(
            has_node_limit(&detached),
            "{:?}",
            detached.validation_results
        );

        let store_only = verify_manifest_store_only_with_graph_inputs(
            &store,
            &VerifyOptions::default(),
            limited(),
        )
        .expect("store-only graph verification");
        assert_eq!(store_only.report.hard_binding, "not_evaluated");
        assert!(has_node_limit(&store_only.report));

        let mp4 = include_bytes!("../../../tests/fixtures/signed_test.mp4");
        let fragmented = verify_fragmented_with_graph_inputs(
            mp4,
            &[],
            "video/mp4",
            &VerifyOptions::default(),
            limited(),
        )
        .expect("fragmented graph verification");
        assert!(
            has_node_limit(&fragmented),
            "{:?}",
            fragmented.validation_results
        );
    }

    #[test]
    fn unratified_hostless_store_is_not_in_public_profile() {
        let error = verify(b"jumb", "application/c2pa").unwrap_err();
        assert!(matches!(error, Error::UnsupportedMime(_)));
    }

    #[test]
    fn bounded_reader_accepts_exact_limit_without_large_allocation() {
        let mut input = Cursor::new(b"1234");
        assert_eq!(read_bounded_file(&mut input, 4, 4).unwrap(), b"1234");
    }

    #[test]
    fn bounded_reader_detects_growth_at_limit_plus_one() {
        let mut input = Cursor::new(b"12345");
        let error = read_bounded_file(&mut input, 4, 4).unwrap_err();
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
        assert!(error.to_string().contains("grew while being read"));
    }

    #[test]
    fn unsupported_mime_has_stable_error_code() {
        let error = verify(b"not an asset", "application/x-unknown").unwrap_err();
        assert!(matches!(error, Error::UnsupportedMime(_)));
        assert_eq!(error.code(), "unsupported_mime");
    }

    #[test]
    fn verify_file_resolves_options_before_opening_the_asset() {
        let path = std::env::temp_dir().join(format!(
            "encypher-c2pa-invalid-options-missing-{}.jpg",
            std::process::id()
        ));
        let options = VerifyOptions {
            no_default_trust: true,
            cawg_trust_configurations: Some(vec![CawgTrustConfiguration {
                profile: CawgTrustProfile::Base,
                certificates_pem: String::new(),
                not_before: None,
                not_after: None,
            }]),
            ..VerifyOptions::default()
        };

        let error = verify_file(path, Some("image/jpeg"), &options)
            .expect_err("invalid trust material must win over a missing asset");
        assert_eq!(error.code(), "invalid_trust_material");
        assert!(
            error
                .to_string()
                .contains("cawg_trust_configurations[0].certificates_pem"),
            "{error}"
        );
    }

    #[test]
    fn zip64_is_admitted_only_by_the_caller_selected_v2_5_policy() {
        let (archive, _) = crate::c2pa_formats::zip64_test_asset();
        for spec_version in [None, Some("2.4")] {
            let error = verify_with_options(
                &archive,
                "application/zip",
                &VerifyOptions {
                    spec_version: spec_version.map(str::to_string),
                    ..VerifyOptions::default()
                },
            )
            .expect_err("legacy policy must refuse ZIP64");
            assert!(
                matches!(error, Error::Verification(_)),
                "{spec_version:?} returned {error:?}"
            );
        }

        let error = verify_with_options(
            &archive,
            "application/zip",
            &VerifyOptions {
                spec_version: Some("2.2".into()),
                ..VerifyOptions::default()
            },
        )
        .expect_err("2.2 must refuse a ZIP MIME outside its format set");
        assert!(
            matches!(&error, Error::UnsupportedMime(mime) if mime == "application/zip"),
            "2.2 returned {error:?}"
        );

        let report = verify_with_options(
            &archive,
            "application/zip",
            &VerifyOptions {
                spec_version: Some("2.5".into()),
                ..VerifyOptions::default()
            },
        )
        .expect("2.5 ZIP64 verification returns a report");
        assert!(report.present, "2.5 did not reach the ZIP64 manifest");
    }

    /// CAWG-ID13-DELTA-009: a trust configuration's certificates and window
    /// are what the validator enforces, so a malformed one fails the call
    /// before any asset is read, naming the entry, rather than silently
    /// dropping a source or a bound. An unknown profile is a malformed option.
    #[test]
    fn a_malformed_cawg_trust_configuration_fails_the_call_naming_its_entry() {
        let root = include_str!("default_trust/encypher-identity-root.pem");
        let resolve = |entry: serde_json::Value| {
            let options: VerifyOptions = serde_json::from_value(serde_json::json!({
                "no_default_trust": true,
                "cawg_trust_configurations": [
                    { "profile": "base", "certificates_pem": root },
                    entry,
                ],
            }))
            .map_err(|error| error.to_string())?;
            super::ResolvedOptions::resolve(&options)
                .map(|_| ())
                .map_err(|error| format!("{}: {error}", error.code()))
        };

        for (entry, field) in [
            (
                serde_json::json!({ "profile": "smime_interim", "certificates_pem": "" }),
                "cawg_trust_configurations[1].certificates_pem",
            ),
            (
                serde_json::json!({ "profile": "smime_interim", "certificates_pem": root, "not_after": "next spring" }),
                "cawg_trust_configurations[1].not_after",
            ),
            (
                serde_json::json!({
                    "profile": "smime_interim",
                    "certificates_pem": root,
                    "not_before": "2027-01-02T00:00:00Z",
                    "not_after": "2027-01-01T00:00:00Z",
                }),
                "cawg_trust_configurations[1]",
            ),
        ] {
            let error = resolve(entry).expect_err("malformed configuration");
            assert!(error.starts_with("invalid_trust_material: "), "{error}");
            assert!(error.contains(field), "{error}");
        }

        let unknown =
            resolve(serde_json::json!({ "profile": "trusted", "certificates_pem": root }))
                .expect_err("unknown profile");
        assert!(unknown.contains("unknown variant `trusted`"), "{unknown}");
        assert_eq!(
            resolve(serde_json::json!({ "profile": "smime_interim", "certificates_pem": root })),
            Ok(())
        );
    }
}