wsc 0.8.4

WebAssembly Signature Component - WASM signing and verification toolkit
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
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
use crate::error::WSError;
use crate::wasm_module::{CustomSection, Module, Section, SectionLike};
use base64::Engine;

// Re-export attestation types from the minimal attestation crate
pub use wsc_attestation::{
    // Section constants
    TRANSFORMATION_ATTESTATION_SECTION, TRANSFORMATION_AUDIT_TRAIL_SECTION,
    // Build provenance
    BuildProvenance, ProvenanceBuilder,
    // Transformation types
    TransformationType, ArtifactDescriptor, SignatureStatus,
    InputSignatureInfo, ToolInfo, AttestationSignature,
    InputArtifact, TransformationAttestation,
    RootComponent, TransformationAuditTrail,
    // Builder
    TransformationAttestationBuilder,
};
/// Component composition and provenance tracking
///
/// This module provides support for WebAssembly component composition with
/// full provenance tracking, enabling supply chain security and compliance
/// with SLSA, in-toto, and SBOM standards.
///
/// # Overview
///
/// When composing WASM components, it's critical to track:
/// - Where each component came from (source repository, commit)
/// - Who built it (builder identity, tool versions)
/// - How it was composed (composition tool, dependencies)
/// - Who verified/integrated it (integrator signatures)
///
/// This module provides the infrastructure to:
/// 1. Capture build provenance for individual components
/// 2. Track composition metadata during wac composition
/// 3. Generate SBOMs (Software Bill of Materials)
/// 4. Create in-toto attestations
/// 5. Verify full provenance chains
///
/// # Example: Basic Provenance Tracking
///
/// ```ignore
/// use wsc::composition::*;
///
/// // Capture build provenance for a component
/// let provenance = ProvenanceBuilder::new()
///     .component_name("my-component")
///     .version("1.0.0")
///     .source_repo("https://github.com/owner/my-component")
///     .commit_sha("abc123...")
///     .build_tool("cargo", "1.75.0")
///     .build();
///
/// // Embed in WASM as custom section
/// let with_provenance = embed_provenance(wasm_module, &provenance)?;
///
/// // Later: Extract and verify
/// let extracted = extract_provenance(&with_provenance)?;
/// assert_eq!(extracted.commit_sha, "abc123...");
/// ```
///
/// # Example: Composition Manifest
///
/// ```ignore
/// // Create composition manifest
/// let manifest = CompositionManifest {
///     version: "1.0".to_string(),
///     tool: "wac".to_string(),
///     tool_version: "0.5.0".to_string(),
///     components: vec![
///         ComponentRef {
///             id: "component-a".to_string(),
///             hash: compute_sha256(comp_a),
///             source: Some("https://github.com/owner/comp-a".to_string()),
///         },
///         ComponentRef {
///             id: "component-b".to_string(),
///             hash: compute_sha256(comp_b),
///             source: Some("https://github.com/owner/comp-b".to_string()),
///         },
///     ],
/// };
///
/// // Embed in composed WASM
/// let composed_with_manifest = embed_composition_manifest(composed, &manifest)?;
/// ```
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use x509_parser::prelude::FromDer;

// BuildProvenance and ProvenanceBuilder are re-exported from wsc_attestation

/// Reference to a component in a composition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComponentRef {
    /// Component identifier
    pub id: String,

    /// SHA-256 hash of the component
    pub hash: String,

    /// Source URL (repository, registry, etc.)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,

    /// Signature index (which signature in the WASM covers this component)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature_index: Option<usize>,
}

/// Composition manifest
///
/// Embedded in composed WASM as a custom section to track
/// how components were composed together.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompositionManifest {
    /// Manifest format version
    pub version: String,

    /// Composition tool name (e.g., "wac")
    pub tool: String,

    /// Composition tool version
    pub tool_version: String,

    /// Timestamp of composition (ISO 8601)
    pub timestamp: String,

    /// Components that were composed
    pub components: Vec<ComponentRef>,

    /// Integrator who signed the composed result
    #[serde(skip_serializing_if = "Option::is_none")]
    pub integrator: Option<IntegratorInfo>,

    /// Additional metadata
    #[serde(skip_serializing_if = "HashMap::is_empty", default)]
    pub metadata: HashMap<String, String>,
}

/// Information about the integrator
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IntegratorInfo {
    /// Integrator identity (certificate DN)
    pub identity: String,

    /// Signature index
    pub signature_index: usize,

    /// Verification timestamp
    pub verification_timestamp: String,
}

impl CompositionManifest {
    /// Create a new composition manifest
    pub fn new(tool: impl Into<String>, tool_version: impl Into<String>) -> Self {
        Self {
            version: "1.0".to_string(),
            tool: tool.into(),
            tool_version: tool_version.into(),
            timestamp: chrono::Utc::now().to_rfc3339(),
            components: Vec::new(),
            integrator: None,
            metadata: HashMap::new(),
        }
    }

    /// Add a component reference
    pub fn add_component(&mut self, id: impl Into<String>, hash: impl Into<String>) {
        self.components.push(ComponentRef {
            id: id.into(),
            hash: hash.into(),
            source: None,
            signature_index: None,
        });
    }

    /// Add component with source info
    pub fn add_component_with_source(
        &mut self,
        id: impl Into<String>,
        hash: impl Into<String>,
        source: impl Into<String>,
    ) {
        self.components.push(ComponentRef {
            id: id.into(),
            hash: hash.into(),
            source: Some(source.into()),
            signature_index: None,
        });
    }

    /// Set integrator information
    pub fn set_integrator(&mut self, identity: impl Into<String>, signature_index: usize) {
        self.integrator = Some(IntegratorInfo {
            identity: identity.into(),
            signature_index,
            verification_timestamp: chrono::Utc::now().to_rfc3339(),
        });
    }

    /// Serialize to JSON
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// Serialize to CBOR (compact binary format)
    #[cfg(feature = "cbor")]
    pub fn to_cbor(&self) -> Result<Vec<u8>, serde_cbor::Error> {
        serde_cbor::to_vec(self)
    }

    /// Deserialize from JSON
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }

    /// Deserialize from CBOR
    #[cfg(feature = "cbor")]
    pub fn from_cbor(bytes: &[u8]) -> Result<Self, serde_cbor::Error> {
        serde_cbor::from_slice(bytes)
    }
}

/// Custom section name for composition manifest
pub const COMPOSITION_MANIFEST_SECTION: &str = "wsc.composition.manifest";

/// Custom section name for build provenance
pub const BUILD_PROVENANCE_SECTION: &str = "wsc.build.provenance";

/// Custom section name for SBOM
pub const SBOM_SECTION: &str = "wsc.sbom";

/// Custom section name for in-toto attestation
pub const INTOTO_ATTESTATION_SECTION: &str = "wsc.intoto.attestation";

// All transformation attestation types (TransformationType, ArtifactDescriptor,
// SignatureStatus, InputSignatureInfo, ToolInfo, AttestationSignature, InputArtifact,
// TransformationAttestation, RootComponent, TransformationAuditTrail,
// TransformationAttestationBuilder) and section constants are re-exported from
// wsc_attestation crate at the top of this module.

// ============================================================================
// Dependency Graph and Validation
// ============================================================================

/// Dependency graph for component composition
///
/// Tracks dependencies between components to enable:
/// - Cycle detection
/// - Substitution detection
/// - Dependency validation
#[derive(Debug, Clone)]
pub struct DependencyGraph {
    /// Map from component ID to its dependencies
    dependencies: HashMap<String, Vec<String>>,

    /// Map from component ID to its expected hash
    expected_hashes: HashMap<String, String>,

    /// Map from component ID to actual hash (for validation)
    actual_hashes: HashMap<String, String>,
}

impl DependencyGraph {
    /// Create a new empty dependency graph
    pub fn new() -> Self {
        Self {
            dependencies: HashMap::new(),
            expected_hashes: HashMap::new(),
            actual_hashes: HashMap::new(),
        }
    }

    /// Add a component with its expected hash
    pub fn add_component(&mut self, id: impl Into<String>, expected_hash: impl Into<String>) {
        let id = id.into();
        self.expected_hashes
            .insert(id.clone(), expected_hash.into());
        self.dependencies.entry(id).or_default();
    }

    /// Add a dependency between two components
    pub fn add_dependency(&mut self, from: impl Into<String>, to: impl Into<String>) {
        let from = from.into();
        let to = to.into();
        self.dependencies
            .entry(from)
            .or_default()
            .push(to);
    }

    /// Set the actual hash for a component (for validation)
    pub fn set_actual_hash(&mut self, id: impl Into<String>, actual_hash: impl Into<String>) {
        self.actual_hashes.insert(id.into(), actual_hash.into());
    }

    /// Build a dependency graph from a composition manifest
    pub fn from_manifest(manifest: &CompositionManifest) -> Self {
        let mut graph = Self::new();

        for component in &manifest.components {
            graph.add_component(&component.id, &component.hash);
        }

        graph
    }

    /// Detect cycles in the dependency graph using depth-first search
    ///
    /// Returns the first cycle found, if any.
    pub fn detect_cycles(&self) -> Option<Vec<String>> {
        let mut visited = HashMap::new();
        let mut rec_stack = HashMap::new();

        for node in self.dependencies.keys() {
            if !visited.contains_key(node)
                && let Some(cycle) =
                    self.dfs_cycle_detection(node, &mut visited, &mut rec_stack, &mut Vec::new())
                {
                    return Some(cycle);
                }
        }

        None
    }

    /// DFS helper for cycle detection
    fn dfs_cycle_detection(
        &self,
        node: &str,
        visited: &mut HashMap<String, bool>,
        rec_stack: &mut HashMap<String, bool>,
        path: &mut Vec<String>,
    ) -> Option<Vec<String>> {
        visited.insert(node.to_string(), true);
        rec_stack.insert(node.to_string(), true);
        path.push(node.to_string());

        if let Some(neighbors) = self.dependencies.get(node) {
            for neighbor in neighbors {
                if !visited.contains_key(neighbor.as_str()) {
                    if let Some(cycle) =
                        self.dfs_cycle_detection(neighbor, visited, rec_stack, path)
                    {
                        return Some(cycle);
                    }
                } else if *rec_stack.get(neighbor.as_str()).unwrap_or(&false) {
                    // Found a cycle - extract it from the path
                    // The neighbor must be in the path since we only reach here when rec_stack[neighbor] == true,
                    // which means it was added to the path. However, for safety we handle the None case.
                    if let Some(cycle_start) = path.iter().position(|x| x == neighbor) {
                        let mut cycle = path[cycle_start..].to_vec();
                        cycle.push(neighbor.clone());
                        return Some(cycle);
                    }
                }
            }
        }

        rec_stack.insert(node.to_string(), false);
        path.pop();
        None
    }

    /// Detect component substitution by comparing expected vs actual hashes
    ///
    /// Returns a list of components that have been substituted.
    pub fn detect_substitutions(&self) -> Vec<ComponentSubstitution> {
        let mut substitutions = Vec::new();

        for (id, expected_hash) in &self.expected_hashes {
            if let Some(actual_hash) = self.actual_hashes.get(id)
                && expected_hash != actual_hash {
                    substitutions.push(ComponentSubstitution {
                        component_id: id.clone(),
                        expected_hash: expected_hash.clone(),
                        actual_hash: actual_hash.clone(),
                    });
                }
        }

        substitutions
    }

    /// Validate the dependency graph
    ///
    /// Returns an error if:
    /// - Cycles are detected
    /// - Component substitutions are detected
    /// - Components are missing
    pub fn validate(&self) -> Result<ValidationResult, ValidationError> {
        let mut warnings = Vec::new();
        let mut errors = Vec::new();

        // Check for cycles
        if let Some(cycle) = self.detect_cycles() {
            errors.push(format!("Cycle detected: {}", cycle.join(" -> ")));
        }

        // Check for substitutions
        let substitutions = self.detect_substitutions();
        if !substitutions.is_empty() {
            for sub in &substitutions {
                errors.push(format!(
                    "Component '{}' substituted: expected hash '{}', actual hash '{}'",
                    sub.component_id, sub.expected_hash, sub.actual_hash
                ));
            }
        }

        // Check for missing components
        for (id, deps) in &self.dependencies {
            for dep in deps {
                if !self.dependencies.contains_key(dep) {
                    warnings.push(format!(
                        "Component '{}' depends on missing component '{}'",
                        id, dep
                    ));
                }
            }
        }

        Ok(ValidationResult {
            valid: errors.is_empty(),
            errors,
            warnings,
        })
    }

    /// Get all components in topological order (dependencies first)
    ///
    /// Returns None if there are cycles.
    pub fn topological_sort(&self) -> Option<Vec<String>> {
        // Check for cycles first
        if self.detect_cycles().is_some() {
            return None;
        }

        let mut result = Vec::new();
        let mut visited = HashMap::new();
        let mut temp_mark = HashMap::new();

        for node in self.dependencies.keys() {
            if !visited.contains_key(node) {
                self.topological_visit(node, &mut visited, &mut temp_mark, &mut result);
            }
        }

        // Don't reverse - topological_visit already gives us dependencies-first order
        Some(result)
    }

    /// Helper for topological sort
    fn topological_visit(
        &self,
        node: &str,
        visited: &mut HashMap<String, bool>,
        temp_mark: &mut HashMap<String, bool>,
        result: &mut Vec<String>,
    ) {
        if temp_mark.contains_key(node) {
            return; // Cycle detected (shouldn't happen if we checked first)
        }

        if !visited.contains_key(node) {
            temp_mark.insert(node.to_string(), true);

            if let Some(neighbors) = self.dependencies.get(node) {
                for neighbor in neighbors {
                    self.topological_visit(neighbor, visited, temp_mark, result);
                }
            }

            visited.insert(node.to_string(), true);
            temp_mark.remove(node);
            result.push(node.to_string());
        }
    }
}

impl Default for DependencyGraph {
    fn default() -> Self {
        Self::new()
    }
}

/// Component substitution detected
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComponentSubstitution {
    pub component_id: String,
    pub expected_hash: String,
    pub actual_hash: String,
}

/// Validation result
#[derive(Debug, Clone)]
pub struct ValidationResult {
    pub valid: bool,
    pub errors: Vec<String>,
    pub warnings: Vec<String>,
}

/// Validation error
#[derive(Debug, Clone, thiserror::Error)]
pub enum ValidationError {
    #[error("Validation failed: {0}")]
    Failed(String),
}

// ============================================================================
// Phase 3: Advanced Validation
// ============================================================================

/// Version constraint for dependency validation
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VersionConstraint {
    /// Exact version required
    Exact(String),
    /// Minimum version (inclusive)
    Minimum(String),
    /// Maximum version (inclusive)
    Maximum(String),
    /// Range (min, max) both inclusive
    Range(String, String),
    /// Any version allowed
    Any,
}

impl VersionConstraint {
    /// Check if a version satisfies this constraint
    pub fn satisfies(&self, version: &str) -> bool {
        match self {
            VersionConstraint::Exact(required) => version == required,
            VersionConstraint::Minimum(min) => Self::compare_versions(version, min) >= 0,
            VersionConstraint::Maximum(max) => Self::compare_versions(version, max) <= 0,
            VersionConstraint::Range(min, max) => {
                Self::compare_versions(version, min) >= 0
                    && Self::compare_versions(version, max) <= 0
            }
            VersionConstraint::Any => true,
        }
    }

    /// Simple semantic version comparison (major.minor.patch)
    /// Returns: -1 if v1 < v2, 0 if v1 == v2, 1 if v1 > v2
    fn compare_versions(v1: &str, v2: &str) -> i32 {
        let parse_version =
            |v: &str| -> Vec<u32> { v.split('.').filter_map(|s| s.parse::<u32>().ok()).collect() };

        let v1_parts = parse_version(v1);
        let v2_parts = parse_version(v2);

        for i in 0..v1_parts.len().max(v2_parts.len()) {
            let p1 = v1_parts.get(i).copied().unwrap_or(0);
            let p2 = v2_parts.get(i).copied().unwrap_or(0);

            if p1 < p2 {
                return -1;
            } else if p1 > p2 {
                return 1;
            }
        }

        0
    }
}

/// Version policy for component validation
#[derive(Debug, Clone)]
pub struct VersionPolicy {
    /// Map from component ID to version constraint
    constraints: HashMap<String, VersionConstraint>,
}

impl VersionPolicy {
    /// Create a new empty version policy
    pub fn new() -> Self {
        Self {
            constraints: HashMap::new(),
        }
    }

    /// Require an exact version for a component
    pub fn require_exact(&mut self, component_id: impl Into<String>, version: impl Into<String>) {
        self.constraints.insert(
            component_id.into(),
            VersionConstraint::Exact(version.into()),
        );
    }

    /// Require a minimum version for a component
    pub fn require_minimum(&mut self, component_id: impl Into<String>, version: impl Into<String>) {
        self.constraints.insert(
            component_id.into(),
            VersionConstraint::Minimum(version.into()),
        );
    }

    /// Require a maximum version for a component
    pub fn require_maximum(&mut self, component_id: impl Into<String>, version: impl Into<String>) {
        self.constraints.insert(
            component_id.into(),
            VersionConstraint::Maximum(version.into()),
        );
    }

    /// Require a version range for a component
    pub fn require_range(
        &mut self,
        component_id: impl Into<String>,
        min_version: impl Into<String>,
        max_version: impl Into<String>,
    ) {
        self.constraints.insert(
            component_id.into(),
            VersionConstraint::Range(min_version.into(), max_version.into()),
        );
    }

    /// Validate a component version against policy
    pub fn validate_version(&self, component_id: &str, version: &str) -> Result<(), String> {
        if let Some(constraint) = self.constraints.get(component_id) {
            if constraint.satisfies(version) {
                Ok(())
            } else {
                Err(format!(
                    "Component '{}' version '{}' does not satisfy constraint {:?}",
                    component_id, version, constraint
                ))
            }
        } else {
            // No constraint for this component - allowed
            Ok(())
        }
    }
}

impl Default for VersionPolicy {
    fn default() -> Self {
        Self::new()
    }
}

/// Source allow-list for dependency validation
#[derive(Debug, Clone)]
pub struct SourceAllowList {
    /// Allowed source URL patterns (exact match or prefix)
    allowed_sources: Vec<String>,
    /// Whether to allow components with no source specified
    allow_no_source: bool,
}

impl SourceAllowList {
    /// Create a new empty allow-list
    pub fn new() -> Self {
        Self {
            allowed_sources: Vec::new(),
            allow_no_source: false,
        }
    }

    /// Add an allowed source URL or prefix
    pub fn add_source(&mut self, source: impl Into<String>) {
        self.allowed_sources.push(source.into());
    }

    /// Allow components with no source specified
    pub fn allow_no_source(&mut self, allow: bool) {
        self.allow_no_source = allow;
    }

    /// Check if a source URL is allowed
    pub fn is_allowed(&self, source: Option<&str>) -> bool {
        match source {
            None => self.allow_no_source,
            Some(url) => self
                .allowed_sources
                .iter()
                .any(|allowed| url.starts_with(allowed) || url == allowed),
        }
    }

    /// Validate a component source against the allow-list
    pub fn validate_source(&self, component_id: &str, source: Option<&str>) -> Result<(), String> {
        if self.is_allowed(source) {
            Ok(())
        } else {
            Err(format!(
                "Component '{}' source '{}' is not in allow-list",
                component_id,
                source.unwrap_or("<no source>")
            ))
        }
    }
}

impl Default for SourceAllowList {
    fn default() -> Self {
        Self::new()
    }
}

/// Timestamp validation policy
///
/// Validates timestamps in provenance data to prevent:
/// - Time-based attacks (using old vulnerable versions)
/// - Timestamp manipulation to hide malicious activity
/// - Future-dated timestamps (clock skew attacks)
#[derive(Debug, Clone)]
pub struct TimestampPolicy {
    /// Maximum age for timestamps (in seconds from now)
    /// Signatures/compositions older than this are rejected
    max_age_seconds: Option<i64>,

    /// Maximum future tolerance (in seconds from now)
    /// Allows for clock skew between systems
    future_tolerance_seconds: i64,

    /// Require all timestamps to be present
    require_timestamps: bool,
}

impl TimestampPolicy {
    /// Create a new timestamp policy with default settings
    /// - No maximum age limit
    /// - 5 minutes future tolerance (for clock skew)
    /// - Timestamps required
    pub fn new() -> Self {
        Self {
            max_age_seconds: None,
            future_tolerance_seconds: 300, // 5 minutes
            require_timestamps: true,
        }
    }

    /// Set maximum age for timestamps
    /// Compositions/builds older than this are rejected
    pub fn with_max_age_seconds(mut self, seconds: i64) -> Self {
        self.max_age_seconds = Some(seconds);
        self
    }

    /// Set maximum age in days
    pub fn with_max_age_days(mut self, days: i64) -> Self {
        self.max_age_seconds = Some(days * 86400);
        self
    }

    /// Set future tolerance for clock skew
    pub fn with_future_tolerance_seconds(mut self, seconds: i64) -> Self {
        self.future_tolerance_seconds = seconds;
        self
    }

    /// Set whether timestamps are required
    pub fn require_timestamps(mut self, require: bool) -> Self {
        self.require_timestamps = require;
        self
    }

    /// Validate a timestamp string (ISO 8601 format)
    /// Returns Ok(()) if valid, Err(String) with reason if invalid
    pub fn validate_timestamp(&self, timestamp: &str, context: &str) -> Result<(), String> {
        // Parse the timestamp
        let parsed = chrono::DateTime::parse_from_rfc3339(timestamp)
            .map_err(|e| format!("Invalid timestamp format for {}: {}", context, e))?;

        let now = chrono::Utc::now();
        let timestamp_utc = parsed.with_timezone(&chrono::Utc);

        // Check if timestamp is too far in the future
        let future_limit = now + chrono::Duration::seconds(self.future_tolerance_seconds);
        if timestamp_utc > future_limit {
            return Err(format!(
                "{} timestamp is too far in the future (more than {} seconds ahead)",
                context, self.future_tolerance_seconds
            ));
        }

        // Check if timestamp is too old
        if let Some(max_age) = self.max_age_seconds {
            let age_limit = now - chrono::Duration::seconds(max_age);
            if timestamp_utc < age_limit {
                let age_days = max_age / 86400;
                return Err(format!(
                    "{} timestamp is too old (older than {} days)",
                    context, age_days
                ));
            }
        }

        Ok(())
    }

    /// Validate an optional timestamp
    pub fn validate_optional_timestamp(
        &self,
        timestamp: Option<&str>,
        context: &str,
    ) -> Result<(), String> {
        match timestamp {
            Some(ts) => self.validate_timestamp(ts, context),
            None => {
                if self.require_timestamps {
                    Err(format!("{} timestamp is required but missing", context))
                } else {
                    Ok(())
                }
            }
        }
    }
}

impl Default for TimestampPolicy {
    fn default() -> Self {
        Self::new()
    }
}

/// Validation mode configuration
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValidationMode {
    /// Lenient mode - warnings don't fail validation
    Lenient,
    /// Strict mode - warnings are treated as errors
    Strict,
}

/// Extended validation configuration
#[derive(Debug, Clone)]
pub struct ValidationConfig {
    /// Validation mode (lenient or strict)
    pub mode: ValidationMode,
    /// Version policy (optional)
    pub version_policy: Option<VersionPolicy>,
    /// Source allow-list (optional)
    pub source_allow_list: Option<SourceAllowList>,
    /// Timestamp validation policy (optional)
    pub timestamp_policy: Option<TimestampPolicy>,
    /// Enable transitive dependency validation
    pub validate_transitive: bool,
}

impl ValidationConfig {
    /// Create a new lenient validation config
    pub fn lenient() -> Self {
        Self {
            mode: ValidationMode::Lenient,
            version_policy: None,
            source_allow_list: None,
            timestamp_policy: None,
            validate_transitive: false,
        }
    }

    /// Create a new strict validation config
    pub fn strict() -> Self {
        Self {
            mode: ValidationMode::Strict,
            version_policy: None,
            source_allow_list: None,
            timestamp_policy: None,
            validate_transitive: false,
        }
    }

    /// Set version policy
    pub fn with_version_policy(mut self, policy: VersionPolicy) -> Self {
        self.version_policy = Some(policy);
        self
    }

    /// Set source allow-list
    pub fn with_source_allow_list(mut self, allow_list: SourceAllowList) -> Self {
        self.source_allow_list = Some(allow_list);
        self
    }

    /// Set timestamp validation policy
    pub fn with_timestamp_policy(mut self, policy: TimestampPolicy) -> Self {
        self.timestamp_policy = Some(policy);
        self
    }

    /// Enable transitive dependency validation
    pub fn with_transitive_validation(mut self, enable: bool) -> Self {
        self.validate_transitive = enable;
        self
    }
}

impl Default for ValidationConfig {
    fn default() -> Self {
        Self::lenient()
    }
}

// Extend DependencyGraph with advanced validation
impl DependencyGraph {
    /// Validate with configuration
    pub fn validate_with_config(
        &self,
        config: &ValidationConfig,
    ) -> Result<ValidationResult, ValidationError> {
        let mut warnings = Vec::new();
        let mut errors = Vec::new();

        // Standard validation (cycles, substitutions, missing)
        let basic_result = self.validate()?;
        errors.extend(basic_result.errors);
        warnings.extend(basic_result.warnings);

        // In strict mode, convert warnings to errors
        if config.mode == ValidationMode::Strict && !warnings.is_empty() {
            for warning in &warnings {
                errors.push(format!("STRICT MODE: {}", warning));
            }
            warnings.clear();
        }

        // Version policy validation
        if let Some(_policy) = &config.version_policy {
            for _component_id in self.expected_hashes.keys() {
                // Extract version from component metadata (would need to be stored)
                // For now, we'll add a placeholder for version validation
                // This would integrate with the ComponentRef which already has version info
            }
        }

        // Source allow-list validation
        if let Some(_allow_list) = &config.source_allow_list {
            // Would validate component sources against allow-list
            // This would integrate with ComponentRef.source field
        }

        Ok(ValidationResult {
            valid: errors.is_empty(),
            errors,
            warnings,
        })
    }
}

// ============================================================================
// SBOM Generation (CycloneDX Format)
// ============================================================================

/// CycloneDX SBOM (Software Bill of Materials)
///
/// Follows the CycloneDX 1.5 specification for SBOM.
/// See: https://cyclonedx.org/specification/overview/
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Sbom {
    /// BOM format (always "CycloneDX")
    #[serde(rename = "bomFormat")]
    pub bom_format: String,

    /// Spec version (e.g., "1.5")
    #[serde(rename = "specVersion")]
    pub spec_version: String,

    /// Serial number (UUID)
    #[serde(rename = "serialNumber")]
    pub serial_number: String,

    /// Version of this SBOM
    pub version: u32,

    /// Metadata about the SBOM
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<SbomMetadata>,

    /// Components in the SBOM
    pub components: Vec<SbomComponent>,

    /// Dependencies between components
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub dependencies: Vec<SbomDependency>,
}

/// SBOM metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SbomMetadata {
    /// Timestamp when SBOM was created
    pub timestamp: String,

    /// Tools used to create the SBOM
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub tools: Vec<SbomTool>,

    /// Component being described (the composed WASM)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub component: Option<SbomComponent>,
}

/// Tool that created the SBOM
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SbomTool {
    /// Vendor of the tool
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vendor: Option<String>,

    /// Tool name
    pub name: String,

    /// Tool version
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
}

/// Component in the SBOM
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SbomComponent {
    /// Component type (e.g., "application", "library")
    #[serde(rename = "type")]
    pub component_type: String,

    /// Component name
    pub name: String,

    /// Component version
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,

    /// Unique identifier (e.g., purl)
    #[serde(rename = "bom-ref")]
    pub bom_ref: String,

    /// Hashes of the component
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub hashes: Vec<SbomHash>,

    /// External references
    #[serde(
        rename = "externalReferences",
        skip_serializing_if = "Vec::is_empty",
        default
    )]
    pub external_references: Vec<SbomExternalReference>,
}

/// Hash of a component
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SbomHash {
    /// Hash algorithm (e.g., "SHA-256")
    pub alg: String,

    /// Hash value (hex encoded)
    pub content: String,
}

/// External reference to a component
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SbomExternalReference {
    /// Reference type (e.g., "vcs", "distribution")
    #[serde(rename = "type")]
    pub ref_type: String,

    /// URL
    pub url: String,
}

/// Dependency relationship
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SbomDependency {
    /// Component reference
    #[serde(rename = "ref")]
    pub component_ref: String,

    /// Dependencies of this component
    #[serde(rename = "dependsOn", skip_serializing_if = "Vec::is_empty", default)]
    pub depends_on: Vec<String>,
}

impl Sbom {
    /// Create a new SBOM for a composed WASM component
    pub fn new(component_name: impl Into<String>, component_version: impl Into<String>) -> Self {
        use uuid::Uuid;

        let name = component_name.into();
        let component = SbomComponent {
            component_type: "application".to_string(),
            name: name.clone(),
            version: Some(component_version.into()),
            bom_ref: format!("pkg:wasm/{}", name),
            hashes: Vec::new(),
            external_references: Vec::new(),
        };

        Self {
            bom_format: "CycloneDX".to_string(),
            spec_version: "1.5".to_string(),
            serial_number: format!("urn:uuid:{}", Uuid::new_v4()),
            version: 1,
            metadata: Some(SbomMetadata {
                timestamp: chrono::Utc::now().to_rfc3339(),
                tools: vec![SbomTool {
                    vendor: Some("wsc".to_string()),
                    name: "wsc".to_string(),
                    version: Some(env!("CARGO_PKG_VERSION").to_string()),
                }],
                component: Some(component),
            }),
            components: Vec::new(),
            dependencies: Vec::new(),
        }
    }

    /// Add a component to the SBOM
    pub fn add_component(
        &mut self,
        name: impl Into<String>,
        version: impl Into<String>,
        hash: impl Into<String>,
    ) {
        let name_str = name.into();
        let component = SbomComponent {
            component_type: "library".to_string(),
            name: name_str.clone(),
            version: Some(version.into()),
            bom_ref: format!("pkg:wasm/{}", name_str),
            hashes: vec![SbomHash {
                alg: "SHA-256".to_string(),
                content: hash.into(),
            }],
            external_references: Vec::new(),
        };
        self.components.push(component);
    }

    /// Add a component with source repository
    pub fn add_component_with_source(
        &mut self,
        name: impl Into<String>,
        version: impl Into<String>,
        hash: impl Into<String>,
        source_repo: impl Into<String>,
    ) {
        let name_str = name.into();
        let component = SbomComponent {
            component_type: "library".to_string(),
            name: name_str.clone(),
            version: Some(version.into()),
            bom_ref: format!("pkg:wasm/{}", name_str),
            hashes: vec![SbomHash {
                alg: "SHA-256".to_string(),
                content: hash.into(),
            }],
            external_references: vec![SbomExternalReference {
                ref_type: "vcs".to_string(),
                url: source_repo.into(),
            }],
        };
        self.components.push(component);
    }

    /// Serialize to JSON
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// Deserialize from JSON
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }
}

// ============================================================================
// in-toto Attestation
// ============================================================================

/// in-toto attestation
///
/// Follows the in-toto attestation framework specification.
/// See: https://github.com/in-toto/attestation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InTotoAttestation {
    /// Payload type (always "application/vnd.in-toto+json")
    #[serde(rename = "_type")]
    pub payload_type: String,

    /// Subject being attested
    pub subject: Vec<InTotoSubject>,

    /// Predicate type
    #[serde(rename = "predicateType")]
    pub predicate_type: String,

    /// Predicate (the actual attestation content)
    pub predicate: InTotoPredicate,
}

/// Subject of an in-toto attestation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InTotoSubject {
    /// Name/identifier of the subject
    pub name: String,

    /// Digest of the subject
    pub digest: HashMap<String, String>,
}

/// Predicate for composition attestation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InTotoPredicate {
    /// Builder information
    pub builder: InTotoBuilder,

    /// Build type
    #[serde(rename = "buildType")]
    pub build_type: String,

    /// Invocation details
    #[serde(skip_serializing_if = "Option::is_none")]
    pub invocation: Option<InTotoInvocation>,

    /// Materials (input components)
    pub materials: Vec<InTotoMaterial>,

    /// Metadata
    #[serde(skip_serializing_if = "HashMap::is_empty", default)]
    pub metadata: HashMap<String, serde_json::Value>,
}

/// Builder information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InTotoBuilder {
    /// Builder identity
    pub id: String,
}

/// Invocation details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InTotoInvocation {
    /// Configuration source
    #[serde(rename = "configSource")]
    pub config_source: InTotoConfigSource,

    /// Parameters
    #[serde(skip_serializing_if = "HashMap::is_empty", default)]
    pub parameters: HashMap<String, serde_json::Value>,

    /// Environment variables
    #[serde(skip_serializing_if = "HashMap::is_empty", default)]
    pub environment: HashMap<String, String>,
}

/// Configuration source
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InTotoConfigSource {
    /// URI of the config
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uri: Option<String>,

    /// Digest of the config
    #[serde(skip_serializing_if = "HashMap::is_empty", default)]
    pub digest: HashMap<String, String>,

    /// Entry point
    #[serde(rename = "entryPoint", skip_serializing_if = "Option::is_none")]
    pub entry_point: Option<String>,
}

/// Material (input) to the build
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InTotoMaterial {
    /// URI of the material
    pub uri: String,

    /// Digest of the material
    #[serde(skip_serializing_if = "HashMap::is_empty", default)]
    pub digest: HashMap<String, String>,
}

impl InTotoAttestation {
    /// Create a new composition attestation
    pub fn new_composition(
        composed_name: impl Into<String>,
        composed_hash: impl Into<String>,
        builder_id: impl Into<String>,
    ) -> Self {
        let mut digest = HashMap::new();
        digest.insert("sha256".to_string(), composed_hash.into());

        Self {
            payload_type: "application/vnd.in-toto+json".to_string(),
            subject: vec![InTotoSubject {
                name: composed_name.into(),
                digest,
            }],
            predicate_type: "https://wsc.dev/in-toto/composition/v1".to_string(),
            predicate: InTotoPredicate {
                builder: InTotoBuilder {
                    id: builder_id.into(),
                },
                build_type: "https://wsc.dev/composition@v1".to_string(),
                invocation: None,
                materials: Vec::new(),
                metadata: HashMap::new(),
            },
        }
    }

    /// Add a material (input component)
    pub fn add_material(&mut self, uri: impl Into<String>, hash: impl Into<String>) {
        let mut digest = HashMap::new();
        digest.insert("sha256".to_string(), hash.into());

        self.predicate.materials.push(InTotoMaterial {
            uri: uri.into(),
            digest,
        });
    }

    /// Serialize to JSON
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// Deserialize from JSON
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }
}

// ============================================================================
// WASM Module Embedding/Extraction
// ============================================================================

/// Embed a composition manifest in a WASM module as a custom section
pub fn embed_composition_manifest(
    mut module: Module,
    manifest: &CompositionManifest,
) -> Result<Module, WSError> {
    let json = manifest.to_json().map_err(|e| {
        WSError::InternalError(format!("Failed to serialize composition manifest: {}", e))
    })?;

    let custom_section = CustomSection::new(
        COMPOSITION_MANIFEST_SECTION.to_string(),
        json.as_bytes().to_vec(),
    );

    module.sections.push(Section::Custom(custom_section));
    Ok(module)
}

/// Extract a composition manifest from a WASM module
pub fn extract_composition_manifest(
    module: &Module,
) -> Result<Option<CompositionManifest>, WSError> {
    for section in &module.sections {
        if let Section::Custom(custom) = section
            && custom.name() == COMPOSITION_MANIFEST_SECTION {
                let json = std::str::from_utf8(custom.payload()).map_err(|e| {
                    WSError::InternalError(format!("Invalid UTF-8 in composition manifest: {}", e))
                })?;

                let manifest = CompositionManifest::from_json(json).map_err(|e| {
                    WSError::InternalError(format!(
                        "Failed to deserialize composition manifest: {}",
                        e
                    ))
                })?;

                return Ok(Some(manifest));
            }
    }
    Ok(None)
}

/// Embed a build provenance in a WASM module as a custom section
pub fn embed_build_provenance(
    mut module: Module,
    provenance: &BuildProvenance,
) -> Result<Module, WSError> {
    let json = serde_json::to_string_pretty(provenance).map_err(|e| {
        WSError::InternalError(format!("Failed to serialize build provenance: {}", e))
    })?;

    let custom_section = CustomSection::new(
        BUILD_PROVENANCE_SECTION.to_string(),
        json.as_bytes().to_vec(),
    );

    module.sections.push(Section::Custom(custom_section));
    Ok(module)
}

/// Extract build provenance from a WASM module
pub fn extract_build_provenance(module: &Module) -> Result<Option<BuildProvenance>, WSError> {
    for section in &module.sections {
        if let Section::Custom(custom) = section
            && custom.name() == BUILD_PROVENANCE_SECTION {
                let json = std::str::from_utf8(custom.payload()).map_err(|e| {
                    WSError::InternalError(format!("Invalid UTF-8 in build provenance: {}", e))
                })?;

                let provenance = serde_json::from_str(json).map_err(|e| {
                    WSError::InternalError(format!("Failed to deserialize build provenance: {}", e))
                })?;

                return Ok(Some(provenance));
            }
    }
    Ok(None)
}

/// Embed an SBOM in a WASM module as a custom section
pub fn embed_sbom(mut module: Module, sbom: &Sbom) -> Result<Module, WSError> {
    let json = sbom
        .to_json()
        .map_err(|e| WSError::InternalError(format!("Failed to serialize SBOM: {}", e)))?;

    let custom_section = CustomSection::new(SBOM_SECTION.to_string(), json.as_bytes().to_vec());

    module.sections.push(Section::Custom(custom_section));
    Ok(module)
}

/// Extract an SBOM from a WASM module
pub fn extract_sbom(module: &Module) -> Result<Option<Sbom>, WSError> {
    for section in &module.sections {
        if let Section::Custom(custom) = section
            && custom.name() == SBOM_SECTION {
                let json = std::str::from_utf8(custom.payload())
                    .map_err(|e| WSError::InternalError(format!("Invalid UTF-8 in SBOM: {}", e)))?;

                let sbom = Sbom::from_json(json).map_err(|e| {
                    WSError::InternalError(format!("Failed to deserialize SBOM: {}", e))
                })?;

                return Ok(Some(sbom));
            }
    }
    Ok(None)
}

/// Embed an in-toto attestation in a WASM module as a custom section
pub fn embed_intoto_attestation(
    mut module: Module,
    attestation: &InTotoAttestation,
) -> Result<Module, WSError> {
    let json = attestation.to_json().map_err(|e| {
        WSError::InternalError(format!("Failed to serialize in-toto attestation: {}", e))
    })?;

    let custom_section = CustomSection::new(
        INTOTO_ATTESTATION_SECTION.to_string(),
        json.as_bytes().to_vec(),
    );

    module.sections.push(Section::Custom(custom_section));
    Ok(module)
}

/// Extract an in-toto attestation from a WASM module
pub fn extract_intoto_attestation(module: &Module) -> Result<Option<InTotoAttestation>, WSError> {
    for section in &module.sections {
        if let Section::Custom(custom) = section
            && custom.name() == INTOTO_ATTESTATION_SECTION {
                let json = std::str::from_utf8(custom.payload()).map_err(|e| {
                    WSError::InternalError(format!("Invalid UTF-8 in in-toto attestation: {}", e))
                })?;

                let attestation = InTotoAttestation::from_json(json).map_err(|e| {
                    WSError::InternalError(format!(
                        "Failed to deserialize in-toto attestation: {}",
                        e
                    ))
                })?;

                return Ok(Some(attestation));
            }
    }
    Ok(None)
}

/// Embed all provenance data in a WASM module
///
/// This is a convenience function that embeds all four types of provenance
/// data in a single operation.
pub fn embed_all_provenance(
    module: Module,
    manifest: &CompositionManifest,
    provenance: &BuildProvenance,
    sbom: &Sbom,
    attestation: &InTotoAttestation,
) -> Result<Module, WSError> {
    let module = embed_composition_manifest(module, manifest)?;
    let module = embed_build_provenance(module, provenance)?;
    let module = embed_sbom(module, sbom)?;
    let module = embed_intoto_attestation(module, attestation)?;
    Ok(module)
}

/// Type alias for the result of extracting all provenance data
pub type AllProvenanceData = (
    Option<CompositionManifest>,
    Option<BuildProvenance>,
    Option<Sbom>,
    Option<InTotoAttestation>,
);

/// Extract all provenance data from a WASM module
///
/// Returns a tuple of (manifest, provenance, sbom, attestation).
/// Any component that is not found will be None.
pub fn extract_all_provenance(module: &Module) -> Result<AllProvenanceData, WSError> {
    let manifest = extract_composition_manifest(module)?;
    let provenance = extract_build_provenance(module)?;
    let sbom = extract_sbom(module)?;
    let attestation = extract_intoto_attestation(module)?;
    Ok((manifest, provenance, sbom, attestation))
}

// ============================================================================
// Transformation Attestation Embedding/Extraction
// ============================================================================

/// Embed a transformation attestation in a WASM module as a custom section
///
/// This is used by transformation tools (like Loom, WAC) to record
/// their transformation of a module.
pub fn embed_transformation_attestation(
    mut module: Module,
    attestation: &TransformationAttestation,
) -> Result<Module, WSError> {
    let json = attestation.to_json().map_err(|e| {
        WSError::InternalError(format!("Failed to serialize transformation attestation: {}", e))
    })?;

    let custom_section = CustomSection::new(
        TRANSFORMATION_ATTESTATION_SECTION.to_string(),
        json.as_bytes().to_vec(),
    );

    module.sections.push(Section::Custom(custom_section));
    Ok(module)
}

/// Extract transformation attestation from a WASM module
///
/// Returns the most recent transformation attestation if present.
/// For multi-stage pipelines, the attestation contains nested chains.
pub fn extract_transformation_attestation(
    module: &Module,
) -> Result<Option<TransformationAttestation>, WSError> {
    for section in &module.sections {
        if let Section::Custom(custom) = section
            && custom.name() == TRANSFORMATION_ATTESTATION_SECTION
        {
            let json = std::str::from_utf8(custom.payload()).map_err(|e| {
                WSError::InternalError(format!(
                    "Invalid UTF-8 in transformation attestation: {}",
                    e
                ))
            })?;

            let attestation = TransformationAttestation::from_json(json).map_err(|e| {
                WSError::InternalError(format!(
                    "Failed to deserialize transformation attestation: {}",
                    e
                ))
            })?;

            return Ok(Some(attestation));
        }
    }
    Ok(None)
}

/// Extract all transformation attestations from a WASM module
///
/// Some modules may have multiple attestation sections (one per transformation stage).
/// This returns all of them in the order they appear in the module.
pub fn extract_all_transformation_attestations(
    module: &Module,
) -> Result<Vec<TransformationAttestation>, WSError> {
    let mut attestations = Vec::new();

    for section in &module.sections {
        if let Section::Custom(custom) = section
            && custom.name() == TRANSFORMATION_ATTESTATION_SECTION
        {
            let json = std::str::from_utf8(custom.payload()).map_err(|e| {
                WSError::InternalError(format!(
                    "Invalid UTF-8 in transformation attestation: {}",
                    e
                ))
            })?;

            let attestation = TransformationAttestation::from_json(json).map_err(|e| {
                WSError::InternalError(format!(
                    "Failed to deserialize transformation attestation: {}",
                    e
                ))
            })?;

            attestations.push(attestation);
        }
    }

    Ok(attestations)
}

/// Embed a full transformation audit trail in a WASM module
///
/// The audit trail contains the complete chain of transformations
/// from original signed components to the final artifact.
pub fn embed_transformation_audit_trail(
    mut module: Module,
    trail: &TransformationAuditTrail,
) -> Result<Module, WSError> {
    let json = trail.to_json().map_err(|e| {
        WSError::InternalError(format!("Failed to serialize transformation audit trail: {}", e))
    })?;

    let custom_section = CustomSection::new(
        TRANSFORMATION_AUDIT_TRAIL_SECTION.to_string(),
        json.as_bytes().to_vec(),
    );

    module.sections.push(Section::Custom(custom_section));
    Ok(module)
}

/// Extract transformation audit trail from a WASM module
pub fn extract_transformation_audit_trail(
    module: &Module,
) -> Result<Option<TransformationAuditTrail>, WSError> {
    for section in &module.sections {
        if let Section::Custom(custom) = section
            && custom.name() == TRANSFORMATION_AUDIT_TRAIL_SECTION
        {
            let json = std::str::from_utf8(custom.payload()).map_err(|e| {
                WSError::InternalError(format!(
                    "Invalid UTF-8 in transformation audit trail: {}",
                    e
                ))
            })?;

            let trail = TransformationAuditTrail::from_json(json).map_err(|e| {
                WSError::InternalError(format!(
                    "Failed to deserialize transformation audit trail: {}",
                    e
                ))
            })?;

            return Ok(Some(trail));
        }
    }
    Ok(None)
}

/// Remove transformation attestation sections from a module
///
/// Useful when re-transforming a module and replacing old attestations.
pub fn remove_transformation_attestations(mut module: Module) -> Module {
    module.sections.retain(|section| {
        if let Section::Custom(custom) = section {
            custom.name() != TRANSFORMATION_ATTESTATION_SECTION
                && custom.name() != TRANSFORMATION_AUDIT_TRAIL_SECTION
        } else {
            true
        }
    });
    module
}

// ============================================================================
// Chain Verification
// ============================================================================

/// Verification mode for transformation chains
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChainVerificationMode {
    /// All root inputs must have verified signatures
    AllInputsSigned,
    /// At least one root input must have a verified signature
    AnyInputSigned,
    /// Don't require root signatures (trust the chain alone)
    NoRootSignaturesRequired,
}

/// A trusted public key for attestation verification
#[derive(Debug, Clone)]
pub struct TrustedPublicKey {
    /// Algorithm (e.g., "ed25519", "ecdsa-p256")
    pub algorithm: String,
    /// Base64-encoded public key bytes
    pub key: String,
    /// Optional key identifier for matching against attestation key_id
    pub key_id: Option<String>,
}

impl TrustedPublicKey {
    /// Create a new Ed25519 trusted public key
    pub fn ed25519(key: impl Into<String>, key_id: Option<String>) -> Self {
        Self {
            algorithm: "ed25519".to_string(),
            key: key.into(),
            key_id,
        }
    }
}

/// Configuration for keyless (OIDC/Sigstore) attestation verification
#[derive(Debug, Clone, Default)]
pub struct KeylessVerificationConfig {
    /// Trusted OIDC issuers (e.g., "https://token.actions.githubusercontent.com")
    pub oidc_issuers: Vec<String>,
    /// Allowed subject patterns (glob patterns, e.g., "https://github.com/org/repo/*")
    pub allowed_subjects: Vec<String>,
}

/// Information about a trusted transformation tool
#[derive(Debug, Clone)]
pub struct TrustedToolInfo {
    /// Minimum required version (inclusive)
    pub min_version: Option<String>,
    /// Maximum allowed version (inclusive)
    pub max_version: Option<String>,
    /// Optional: Required tool hash for exact matching
    pub required_hash: Option<String>,
    /// Trusted public keys for this tool's attestation signatures
    pub public_keys: Vec<TrustedPublicKey>,
    /// Keyless verification config (for Sigstore/OIDC-based signing)
    pub keyless: Option<KeylessVerificationConfig>,
}

impl TrustedToolInfo {
    /// Create a new trusted tool info that accepts any version
    pub fn any_version() -> Self {
        Self {
            min_version: None,
            max_version: None,
            required_hash: None,
            public_keys: Vec::new(),
            keyless: None,
        }
    }

    /// Create a trusted tool info with a minimum version requirement
    pub fn min_version(version: impl Into<String>) -> Self {
        Self {
            min_version: Some(version.into()),
            max_version: None,
            required_hash: None,
            public_keys: Vec::new(),
            keyless: None,
        }
    }

    /// Add a trusted public key for attestation verification
    pub fn with_public_key(mut self, key: TrustedPublicKey) -> Self {
        self.public_keys.push(key);
        self
    }

    /// Add keyless verification config
    pub fn with_keyless(mut self, config: KeylessVerificationConfig) -> Self {
        self.keyless = Some(config);
        self
    }

    /// Check if a tool version satisfies this constraint
    pub fn satisfies(&self, version: &str, tool_hash: Option<&str>) -> bool {
        // Check hash first if required
        if let Some(required) = &self.required_hash {
            if tool_hash != Some(required.as_str()) {
                return false;
            }
        }

        // Simple version comparison (assumes semver-like ordering)
        if let Some(min) = &self.min_version {
            if version < min.as_str() {
                return false;
            }
        }

        if let Some(max) = &self.max_version {
            if version > max.as_str() {
                return false;
            }
        }

        true
    }
}

/// Policy for verifying transformation chains
#[derive(Debug, Clone)]
pub struct ChainVerificationPolicy {
    /// Whether root components must have valid signatures
    pub mode: ChainVerificationMode,

    /// Trusted root signers (key IDs or certificate subjects)
    pub trusted_root_signers: std::collections::HashSet<String>,

    /// Trusted transformation tools (tool name -> version constraints)
    pub trusted_tools: HashMap<String, TrustedToolInfo>,

    /// Trusted attestation signers (key IDs or certificate subjects for attestations)
    pub trusted_attestation_signers: std::collections::HashSet<String>,

    /// Maximum age for attestation timestamps (optional)
    pub max_attestation_age: Option<std::time::Duration>,

    /// Whether to verify attestation signatures (requires key material)
    pub verify_attestation_signatures: bool,
}

impl Default for ChainVerificationPolicy {
    fn default() -> Self {
        Self {
            mode: ChainVerificationMode::AllInputsSigned,
            trusted_root_signers: std::collections::HashSet::new(),
            trusted_tools: HashMap::new(),
            trusted_attestation_signers: std::collections::HashSet::new(),
            max_attestation_age: None,
            verify_attestation_signatures: false,
        }
    }
}

impl ChainVerificationPolicy {
    /// Create a lenient policy that doesn't require root signatures
    pub fn lenient() -> Self {
        Self {
            mode: ChainVerificationMode::NoRootSignaturesRequired,
            ..Default::default()
        }
    }

    /// Create a strict policy that requires all inputs to be signed
    pub fn strict() -> Self {
        Self {
            mode: ChainVerificationMode::AllInputsSigned,
            ..Default::default()
        }
    }

    /// Add a trusted root signer
    pub fn add_trusted_root_signer(mut self, signer: impl Into<String>) -> Self {
        self.trusted_root_signers.insert(signer.into());
        self
    }

    /// Add a trusted tool
    pub fn add_trusted_tool(mut self, name: impl Into<String>, info: TrustedToolInfo) -> Self {
        self.trusted_tools.insert(name.into(), info);
        self
    }

    /// Add a trusted attestation signer
    pub fn add_trusted_attestation_signer(mut self, signer: impl Into<String>) -> Self {
        self.trusted_attestation_signers.insert(signer.into());
        self
    }

    /// Set maximum attestation age
    pub fn with_max_attestation_age(mut self, age: std::time::Duration) -> Self {
        self.max_attestation_age = Some(age);
        self
    }
}

/// Result of chain verification
#[derive(Debug, Clone)]
pub struct ChainVerificationResult {
    /// Whether the chain is valid according to the policy
    pub valid: bool,

    /// Errors encountered during verification
    pub errors: Vec<String>,

    /// Warnings (non-fatal issues)
    pub warnings: Vec<String>,

    /// Tools found in the chain
    pub tools_used: Vec<String>,

    /// Number of transformation stages
    pub transformation_count: usize,

    /// Root components found
    pub root_components: Vec<String>,
}

impl ChainVerificationResult {
    fn new() -> Self {
        Self {
            valid: true,
            errors: Vec::new(),
            warnings: Vec::new(),
            tools_used: Vec::new(),
            transformation_count: 0,
            root_components: Vec::new(),
        }
    }

    fn add_error(&mut self, error: impl Into<String>) {
        self.valid = false;
        self.errors.push(error.into());
    }

    fn add_warning(&mut self, warning: impl Into<String>) {
        self.warnings.push(warning.into());
    }
}

/// Result of verifying an attestation signature
#[derive(Debug, Clone)]
pub enum AttestationSignatureResult {
    /// Signature verified successfully against a trusted key
    Verified {
        key_id: Option<String>,
        algorithm: String,
    },
    /// Attestation is unsigned (algorithm = "unsigned")
    Unsigned,
    /// Signature verification failed
    Invalid(String),
    /// No matching trusted key found
    NoMatchingKey,
}

/// Verify an attestation signature against trusted public keys
///
/// This function verifies that the attestation was signed by one of the
/// trusted public keys for the tool.
///
/// # Arguments
/// * `attestation` - The attestation to verify
/// * `trusted_keys` - List of trusted public keys for this tool
///
/// # Returns
/// * `AttestationSignatureResult` indicating the verification result
pub fn verify_attestation_signature(
    attestation: &TransformationAttestation,
    trusted_keys: &[TrustedPublicKey],
) -> AttestationSignatureResult {
    use ct_codecs::{Base64, Decoder};
    use ed25519_compact::{PublicKey, Signature};

    let sig = &attestation.attestation_signature;

    // Check if unsigned
    if sig.algorithm == "unsigned" || sig.signature.is_empty() {
        return AttestationSignatureResult::Unsigned;
    }

    // Currently only support Ed25519
    if sig.algorithm != "ed25519" {
        return AttestationSignatureResult::Invalid(format!(
            "Unsupported signature algorithm: {}",
            sig.algorithm
        ));
    }

    // Decode the signature
    let signature_bytes = match Base64::decode_to_vec(&sig.signature, None) {
        Ok(bytes) => bytes,
        Err(e) => {
            return AttestationSignatureResult::Invalid(format!(
                "Failed to decode signature: {}",
                e
            ));
        }
    };

    let signature = match Signature::from_slice(&signature_bytes) {
        Ok(sig) => sig,
        Err(e) => {
            return AttestationSignatureResult::Invalid(format!(
                "Invalid signature format: {}",
                e
            ));
        }
    };

    // Recreate the canonical message that was signed
    // (attestation with empty signature field)
    let mut attestation_for_signing = attestation.clone();
    attestation_for_signing.attestation_signature.signature = String::new();
    let canonical = match serde_json::to_string(&attestation_for_signing) {
        Ok(json) => json,
        Err(e) => {
            return AttestationSignatureResult::Invalid(format!(
                "Failed to serialize attestation: {}",
                e
            ));
        }
    };

    // Try to verify against each trusted key
    for trusted_key in trusted_keys {
        // Skip keys with wrong algorithm
        if trusted_key.algorithm != "ed25519" {
            continue;
        }

        // If key_id is specified, it must match
        if let Some(ref trusted_key_id) = trusted_key.key_id {
            if let Some(ref attestation_key_id) = sig.key_id {
                if trusted_key_id != attestation_key_id {
                    continue;
                }
            }
        }

        // Decode the trusted public key
        let pk_bytes = match Base64::decode_to_vec(&trusted_key.key, None) {
            Ok(bytes) => bytes,
            Err(_) => continue, // Skip malformed keys
        };

        let public_key = match PublicKey::from_slice(&pk_bytes) {
            Ok(pk) => pk,
            Err(_) => continue, // Skip malformed keys
        };

        // Verify the signature
        if public_key.verify(canonical.as_bytes(), &signature).is_ok() {
            return AttestationSignatureResult::Verified {
                key_id: sig.key_id.clone(),
                algorithm: sig.algorithm.clone(),
            };
        }
    }

    // Also try verification with the embedded public key if present
    // (useful for self-signed attestations where the verifier trusts the public key)
    if let Some(ref embedded_pk) = sig.public_key {
        let pk_bytes = match Base64::decode_to_vec(embedded_pk, None) {
            Ok(bytes) => bytes,
            Err(_) => return AttestationSignatureResult::NoMatchingKey,
        };

        let public_key = match PublicKey::from_slice(&pk_bytes) {
            Ok(pk) => pk,
            Err(_) => return AttestationSignatureResult::NoMatchingKey,
        };

        // Check if this public key is in the trusted list
        for trusted_key in trusted_keys {
            if trusted_key.key == *embedded_pk && trusted_key.algorithm == "ed25519" {
                if public_key.verify(canonical.as_bytes(), &signature).is_ok() {
                    return AttestationSignatureResult::Verified {
                        key_id: sig.key_id.clone(),
                        algorithm: sig.algorithm.clone(),
                    };
                }
            }
        }
    }

    AttestationSignatureResult::NoMatchingKey
}

/// Verify a transformation chain against a policy
///
/// This walks through the attestation chain and verifies:
/// 1. Each transformation tool is trusted
/// 2. Attestation timestamps are within bounds
/// 3. Root inputs have valid signatures (according to policy)
/// 4. Hash chains are consistent (no gaps)
/// 5. Attestation signatures (if policy.verify_attestation_signatures is true)
pub fn verify_transformation_chain(
    attestation: &TransformationAttestation,
    policy: &ChainVerificationPolicy,
) -> ChainVerificationResult {
    let mut result = ChainVerificationResult::new();
    verify_attestation_recursive(attestation, policy, &mut result, 0);
    result
}

fn verify_attestation_recursive(
    attestation: &TransformationAttestation,
    policy: &ChainVerificationPolicy,
    result: &mut ChainVerificationResult,
    depth: usize,
) {
    const MAX_CHAIN_DEPTH: usize = 100;

    if depth > MAX_CHAIN_DEPTH {
        result.add_error(format!(
            "Chain depth exceeds maximum ({}) - possible cycle",
            MAX_CHAIN_DEPTH
        ));
        return;
    }

    result.transformation_count += 1;

    // Track the tool used
    let tool_name = &attestation.tool.name;
    if !result.tools_used.contains(tool_name) {
        result.tools_used.push(tool_name.clone());
    }

    // Verify tool is trusted
    let tool_info = policy.trusted_tools.get(tool_name);
    if let Some(info) = tool_info {
        if !info.satisfies(&attestation.tool.version, attestation.tool.tool_hash.as_deref()) {
            result.add_error(format!(
                "Tool '{}' version '{}' does not meet policy requirements",
                tool_name, attestation.tool.version
            ));
        }
    } else if !policy.trusted_tools.is_empty() {
        // If trusted_tools is specified, tool must be in the list
        result.add_error(format!("Tool '{}' is not in trusted tools list", tool_name));
    }

    // Verify attestation signature if policy requires it
    if policy.verify_attestation_signatures {
        // Get trusted keys for this tool
        let trusted_keys = tool_info
            .map(|info| info.public_keys.as_slice())
            .unwrap_or(&[]);

        if trusted_keys.is_empty() && tool_info.is_some() {
            // Tool is trusted but has no public keys configured - warn
            result.add_warning(format!(
                "Tool '{}' has no public keys configured for signature verification",
                tool_name
            ));
        }

        // Verify the signature
        match verify_attestation_signature(attestation, trusted_keys) {
            AttestationSignatureResult::Verified { key_id, algorithm } => {
                // Signature valid - this is the expected case
                log::debug!(
                    "Attestation signature verified for tool '{}' (algorithm: {}, key_id: {:?})",
                    tool_name,
                    algorithm,
                    key_id
                );
            }
            AttestationSignatureResult::Unsigned => {
                result.add_error(format!(
                    "Tool '{}' attestation is unsigned but signature verification is required",
                    tool_name
                ));
            }
            AttestationSignatureResult::Invalid(reason) => {
                result.add_error(format!(
                    "Tool '{}' attestation signature is invalid: {}",
                    tool_name, reason
                ));
            }
            AttestationSignatureResult::NoMatchingKey => {
                result.add_error(format!(
                    "Tool '{}' attestation signature does not match any trusted public key",
                    tool_name
                ));
            }
        }
    }

    // Verify attestation timestamp if policy has age limit
    if let Some(max_age) = policy.max_attestation_age {
        if let Ok(timestamp) = chrono::DateTime::parse_from_rfc3339(&attestation.timestamp) {
            let now = chrono::Utc::now();
            let age = now.signed_duration_since(timestamp);
            if age > chrono::Duration::from_std(max_age).unwrap_or(chrono::TimeDelta::MAX) {
                result.add_error(format!(
                    "Attestation timestamp {} is older than maximum allowed age",
                    attestation.timestamp
                ));
            }
        } else {
            result.add_warning(format!(
                "Could not parse attestation timestamp: {}",
                attestation.timestamp
            ));
        }
    }

    // Verify attestation signer if policy requires it
    if !policy.trusted_attestation_signers.is_empty() {
        let signer = attestation
            .attestation_signature
            .signer_identity
            .as_ref()
            .or(attestation.attestation_signature.key_id.as_ref());

        if let Some(signer_id) = signer {
            if !policy.trusted_attestation_signers.contains(signer_id) {
                result.add_error(format!(
                    "Attestation signer '{}' is not trusted",
                    signer_id
                ));
            }
        } else {
            result.add_error("Attestation has no signer identity or key ID");
        }
    }

    // Process inputs
    let mut signed_inputs = 0;
    let mut unsigned_inputs = 0;

    for input in &attestation.inputs {
        // Check for nested transformation chain
        if let Some(prior_attestation) = &input.transformation_chain {
            // Verify the hash chain is consistent
            if input.artifact.hash != prior_attestation.output.hash {
                result.add_error(format!(
                    "Hash mismatch in chain: input {} doesn't match prior output",
                    input.artifact.name
                ));
            }

            // Recursively verify the prior attestation
            verify_attestation_recursive(prior_attestation, policy, result, depth + 1);
        } else {
            // This is a root input (original component)
            result.root_components.push(input.artifact.name.clone());

            match input.signature_status {
                SignatureStatus::Verified => {
                    signed_inputs += 1;

                    // Verify signer is trusted if policy specifies trusted signers
                    if !policy.trusted_root_signers.is_empty() {
                        if let Some(sig_info) = &input.signature_info {
                            let signer = sig_info
                                .signer_identity
                                .as_ref()
                                .or(sig_info.key_id.as_ref());

                            if let Some(signer_id) = signer {
                                if !policy.trusted_root_signers.contains(signer_id) {
                                    result.add_warning(format!(
                                        "Root signer '{}' for '{}' is not in trusted list",
                                        signer_id, input.artifact.name
                                    ));
                                }
                            }
                        }
                    }
                }
                SignatureStatus::SignedUnverified => {
                    result.add_warning(format!(
                        "Root input '{}' has signature but was not verified",
                        input.artifact.name
                    ));
                }
                SignatureStatus::Unsigned => {
                    unsigned_inputs += 1;
                }
            }
        }
    }

    // Apply signature mode policy
    match policy.mode {
        ChainVerificationMode::AllInputsSigned => {
            if unsigned_inputs > 0 {
                result.add_error(format!(
                    "Policy requires all inputs signed, but {} inputs are unsigned",
                    unsigned_inputs
                ));
            }
        }
        ChainVerificationMode::AnyInputSigned => {
            if signed_inputs == 0 && !attestation.inputs.is_empty() {
                result.add_error("Policy requires at least one signed input, but none found");
            }
        }
        ChainVerificationMode::NoRootSignaturesRequired => {
            // No action needed
        }
    }
}

/// Verify a transformation audit trail against a policy
pub fn verify_audit_trail(
    trail: &TransformationAuditTrail,
    policy: &ChainVerificationPolicy,
) -> ChainVerificationResult {
    let mut result = ChainVerificationResult::new();

    // Verify each transformation in the trail
    for attestation in &trail.transformations {
        let sub_result = verify_transformation_chain(attestation, policy);
        result.errors.extend(sub_result.errors);
        result.warnings.extend(sub_result.warnings);
        result.tools_used.extend(sub_result.tools_used);
        result.transformation_count += sub_result.transformation_count;
        result.root_components.extend(sub_result.root_components);
    }

    // Deduplicate
    result.tools_used.sort();
    result.tools_used.dedup();
    result.root_components.sort();
    result.root_components.dedup();

    result.valid = result.errors.is_empty();
    result
}

// ============================================================================
// Timestamp Validation Functions
// ============================================================================

/// Validate timestamps in a composition manifest
pub fn validate_manifest_timestamps(
    manifest: &CompositionManifest,
    policy: &TimestampPolicy,
) -> Result<(), String> {
    // Validate composition timestamp
    policy.validate_timestamp(&manifest.timestamp, "Composition")?;

    // Validate integrator timestamp if present
    if let Some(integrator) = &manifest.integrator {
        policy.validate_timestamp(
            &integrator.verification_timestamp,
            "Integrator verification",
        )?;
    }

    Ok(())
}

/// Validate timestamps in build provenance
pub fn validate_provenance_timestamps(
    provenance: &BuildProvenance,
    policy: &TimestampPolicy,
) -> Result<(), String> {
    policy.validate_timestamp(&provenance.build_timestamp, "Build")?;
    Ok(())
}

/// Validate timestamps in an in-toto attestation
pub fn validate_attestation_timestamps(
    attestation: &InTotoAttestation,
    policy: &TimestampPolicy,
) -> Result<(), String> {
    // Validate metadata timestamps
    if let Some(finished_on_value) = attestation.predicate.metadata.get("finishedOn")
        && let Some(finished_on) = finished_on_value.as_str() {
            policy.validate_timestamp(finished_on, "Build completion")?;
        }

    Ok(())
}

/// Validate all timestamps in a WASM module's provenance data
pub fn validate_all_timestamps(
    module: &Module,
    policy: &TimestampPolicy,
) -> Result<ValidationResult, WSError> {
    let mut warnings = Vec::new();
    let mut errors = Vec::new();

    // Extract all provenance data
    let (manifest, provenance, _sbom, attestation) = extract_all_provenance(module)?;

    // Validate manifest timestamps
    if let Some(ref m) = manifest {
        if let Err(e) = validate_manifest_timestamps(m, policy) {
            errors.push(e);
        }
    } else if policy.require_timestamps {
        warnings.push("No composition manifest found for timestamp validation".to_string());
    }

    // Validate build provenance timestamps
    if let Some(ref p) = provenance
        && let Err(e) = validate_provenance_timestamps(p, policy) {
            errors.push(e);
        }

    // Validate attestation timestamps
    if let Some(ref a) = attestation
        && let Err(e) = validate_attestation_timestamps(a, policy) {
            errors.push(e);
        }

    Ok(ValidationResult {
        valid: errors.is_empty(),
        errors,
        warnings,
    })
}

/// Signature freshness validator
///
/// Validates that signatures were created within an acceptable time window
#[derive(Debug, Clone)]
pub struct SignatureFreshnessPolicy {
    /// Maximum age for signatures (in seconds)
    max_signature_age_seconds: Option<i64>,

    /// Minimum acceptable signature timestamp (absolute time)
    /// Useful for enforcing "no signatures before this date" policies
    minimum_timestamp: Option<chrono::DateTime<chrono::Utc>>,
}

impl SignatureFreshnessPolicy {
    /// Create a new signature freshness policy with no restrictions
    pub fn new() -> Self {
        Self {
            max_signature_age_seconds: None,
            minimum_timestamp: None,
        }
    }

    /// Set maximum signature age in seconds
    pub fn with_max_age_seconds(mut self, seconds: i64) -> Self {
        self.max_signature_age_seconds = Some(seconds);
        self
    }

    /// Set maximum signature age in days
    pub fn with_max_age_days(mut self, days: i64) -> Self {
        self.max_signature_age_seconds = Some(days * 86400);
        self
    }

    /// Set minimum acceptable timestamp
    /// Signatures created before this time are rejected
    pub fn with_minimum_timestamp(mut self, timestamp: chrono::DateTime<chrono::Utc>) -> Self {
        self.minimum_timestamp = Some(timestamp);
        self
    }

    /// Validate a signature timestamp
    pub fn validate(&self, timestamp: &str, context: &str) -> Result<(), String> {
        let parsed = chrono::DateTime::parse_from_rfc3339(timestamp)
            .map_err(|e| format!("Invalid timestamp format for {}: {}", context, e))?;

        let timestamp_utc = parsed.with_timezone(&chrono::Utc);
        let now = chrono::Utc::now();

        // Check maximum age
        if let Some(max_age) = self.max_signature_age_seconds {
            let age = now.signed_duration_since(timestamp_utc);
            if age.num_seconds() > max_age {
                let age_days = max_age / 86400;
                return Err(format!(
                    "{} signature is too old (created {} days ago, max age: {} days)",
                    context,
                    age.num_days(),
                    age_days
                ));
            }
        }

        // Check minimum timestamp
        if let Some(min_ts) = &self.minimum_timestamp
            && timestamp_utc < *min_ts {
                return Err(format!(
                    "{} signature was created before minimum acceptable time ({})",
                    context,
                    min_ts.to_rfc3339()
                ));
            }

        Ok(())
    }
}

impl Default for SignatureFreshnessPolicy {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Certificate Expiration Validation
// ============================================================================

/// Certificate validity policy
///
/// Validates X.509 certificates to ensure they are:
/// - Not expired
/// - Not used before their validity start date
/// - Have sufficient remaining validity
#[derive(Debug, Clone)]
pub struct CertificateValidityPolicy {
    /// Require minimum remaining validity (in seconds)
    /// Certificates expiring within this window are rejected
    min_remaining_validity_seconds: Option<i64>,

    /// Allow certificates not yet valid (for testing)
    allow_not_yet_valid: bool,
}

impl CertificateValidityPolicy {
    /// Create a new certificate validity policy with default settings
    /// - No minimum remaining validity requirement
    /// - Do not allow certificates not yet valid
    pub fn new() -> Self {
        Self {
            min_remaining_validity_seconds: None,
            allow_not_yet_valid: false,
        }
    }

    /// Set minimum remaining validity in seconds
    /// Certificates expiring within this time window are rejected
    pub fn with_min_remaining_validity_seconds(mut self, seconds: i64) -> Self {
        self.min_remaining_validity_seconds = Some(seconds);
        self
    }

    /// Set minimum remaining validity in days
    pub fn with_min_remaining_validity_days(mut self, days: i64) -> Self {
        self.min_remaining_validity_seconds = Some(days * 86400);
        self
    }

    /// Allow certificates that are not yet valid
    /// Useful for testing with future-dated certificates
    pub fn allow_not_yet_valid(mut self, allow: bool) -> Self {
        self.allow_not_yet_valid = allow;
        self
    }

    /// Validate certificate validity period using parsed not_before/not_after
    ///
    /// # Arguments
    /// * `not_before` - Certificate validity start time (ISO 8601)
    /// * `not_after` - Certificate validity end time (ISO 8601)
    /// * `context` - Description of the certificate for error messages
    pub fn validate_certificate_times(
        &self,
        not_before: &str,
        not_after: &str,
        context: &str,
    ) -> Result<(), String> {
        let now = chrono::Utc::now();

        // Parse timestamps
        let not_before_time = chrono::DateTime::parse_from_rfc3339(not_before)
            .map_err(|e| format!("Invalid not_before timestamp for {}: {}", context, e))?
            .with_timezone(&chrono::Utc);

        let not_after_time = chrono::DateTime::parse_from_rfc3339(not_after)
            .map_err(|e| format!("Invalid not_after timestamp for {}: {}", context, e))?
            .with_timezone(&chrono::Utc);

        // Check if certificate is not yet valid
        if now < not_before_time
            && !self.allow_not_yet_valid {
                return Err(format!(
                    "{} certificate is not yet valid (valid from: {})",
                    context,
                    not_before_time.to_rfc3339()
                ));
            }

        // Check if certificate is expired
        if now > not_after_time {
            return Err(format!(
                "{} certificate has expired (expired on: {})",
                context,
                not_after_time.to_rfc3339()
            ));
        }

        // Check minimum remaining validity
        if let Some(min_remaining) = self.min_remaining_validity_seconds {
            let remaining = not_after_time.signed_duration_since(now);
            if remaining.num_seconds() < min_remaining {
                let remaining_days = remaining.num_days();
                let min_days = min_remaining / 86400;
                return Err(format!(
                    "{} certificate expires too soon (remaining: {} days, minimum required: {} days)",
                    context, remaining_days, min_days
                ));
            }
        }

        Ok(())
    }

    /// Validate a certificate in DER format
    ///
    /// This function parses a DER-encoded X.509 certificate and validates
    /// its validity period.
    pub fn validate_certificate_der(&self, cert_der: &[u8], context: &str) -> Result<(), String> {
        // Parse the certificate using x509_parser
        let (_, cert) = x509_parser::certificate::X509Certificate::from_der(cert_der)
            .map_err(|e| format!("Failed to parse {} certificate: {:?}", context, e))?;

        // Get validity period
        let not_before = cert.validity().not_before;
        let not_after = cert.validity().not_after;

        // Convert to chrono DateTime for easier comparison
        let not_before_chrono =
            chrono::DateTime::<chrono::Utc>::from_timestamp(not_before.timestamp(), 0)
                .ok_or_else(|| format!("Invalid not_before timestamp for {}", context))?;

        let not_after_chrono =
            chrono::DateTime::<chrono::Utc>::from_timestamp(not_after.timestamp(), 0)
                .ok_or_else(|| format!("Invalid not_after timestamp for {}", context))?;

        // Validate using our policy
        self.validate_certificate_times(
            &not_before_chrono.to_rfc3339(),
            &not_after_chrono.to_rfc3339(),
            context,
        )
    }

    /// Validate a certificate in PEM format
    pub fn validate_certificate_pem(&self, cert_pem: &str, context: &str) -> Result<(), String> {
        // Parse PEM to get DER
        let pem = pem::parse(cert_pem)
            .map_err(|e| format!("Failed to parse {} PEM certificate: {}", context, e))?;

        self.validate_certificate_der(pem.contents(), context)
    }
}

impl Default for CertificateValidityPolicy {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Phase 5: Hardware Attestation & Device Identity
// ============================================================================

/// Device attestation for composition operations
///
/// Proves that a composition operation was performed on a specific device
/// with hardware-backed security.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviceAttestation {
    /// Device identifier (hardware serial number, device ID)
    pub device_id: String,

    /// Attestation type (TPM, SGX, SecureElement, etc.)
    pub attestation_type: String,

    /// Hardware security chip model (e.g., "ATECC608", "TPM2.0")
    pub hardware_model: String,

    /// Attestation data (platform-specific, base64-encoded)
    pub attestation_data: String,

    /// Signature over attestation (base64-encoded)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attestation_signature: Option<String>,

    /// Timestamp when attestation was created (ISO 8601)
    pub timestamp: String,

    /// Public key of the device signing key (base64-encoded)
    pub device_public_key: String,

    /// Additional metadata
    #[serde(skip_serializing_if = "HashMap::is_empty", default)]
    pub metadata: HashMap<String, String>,
}

impl DeviceAttestation {
    /// Create a new device attestation
    pub fn new(
        device_id: impl Into<String>,
        attestation_type: impl Into<String>,
        hardware_model: impl Into<String>,
    ) -> Self {
        Self {
            device_id: device_id.into(),
            attestation_type: attestation_type.into(),
            hardware_model: hardware_model.into(),
            attestation_data: String::new(),
            attestation_signature: None,
            timestamp: chrono::Utc::now().to_rfc3339(),
            device_public_key: String::new(),
            metadata: HashMap::new(),
        }
    }

    /// Set attestation data (will be base64-encoded)
    pub fn with_attestation_data(mut self, data: &[u8]) -> Self {
        self.attestation_data = base64::engine::general_purpose::STANDARD.encode(data);
        self
    }

    /// Set attestation signature (will be base64-encoded)
    pub fn with_signature(mut self, signature: &[u8]) -> Self {
        self.attestation_signature =
            Some(base64::engine::general_purpose::STANDARD.encode(signature));
        self
    }

    /// Set device public key (will be base64-encoded)
    pub fn with_public_key(mut self, public_key: &[u8]) -> Self {
        self.device_public_key = base64::engine::general_purpose::STANDARD.encode(public_key);
        self
    }

    /// Add metadata field
    pub fn add_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Serialize to JSON
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// Deserialize from JSON
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }
}

/// Hardware-backed composition manifest
///
/// Extends CompositionManifest with device attestation for SLSA Level 4
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HardwareCompositionManifest {
    /// Base composition manifest
    #[serde(flatten)]
    pub manifest: CompositionManifest,

    /// Device attestation (proves composition was done on specific hardware)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub device_attestation: Option<DeviceAttestation>,

    /// Hardware security level (0-4, where 4 is highest)
    pub security_level: u8,
}

impl HardwareCompositionManifest {
    /// Create from base manifest
    pub fn from_manifest(manifest: CompositionManifest) -> Self {
        Self {
            manifest,
            device_attestation: None,
            security_level: 0,
        }
    }

    /// Add device attestation
    pub fn with_device_attestation(mut self, attestation: DeviceAttestation) -> Self {
        self.device_attestation = Some(attestation);
        self
    }

    /// Set security level
    pub fn with_security_level(mut self, level: u8) -> Self {
        self.security_level = level.min(4); // Cap at level 4
        self
    }

    /// Serialize to JSON
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// Deserialize from JSON
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }
}

/// Transparency log entry
///
/// Records composition operations in an immutable transparency log (e.g., Rekor)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransparencyLogEntry {
    /// Log index (unique identifier in log)
    pub log_index: u64,

    /// Log entry UUID
    pub uuid: String,

    /// Log entry body (base64-encoded)
    pub body: String,

    /// Integrated timestamp from transparency log
    pub integrated_time: i64,

    /// Log ID (identifies which transparency log)
    pub log_id: String,

    /// Inclusion proof (for verification)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inclusion_proof: Option<InclusionProof>,
}

/// Inclusion proof for transparency log
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InclusionProof {
    /// Tree size when entry was added
    pub tree_size: u64,

    /// Root hash of the tree
    pub root_hash: String,

    /// Merkle proof hashes
    pub hashes: Vec<String>,

    /// Log index of this entry
    pub log_index: u64,
}

impl TransparencyLogEntry {
    /// Create a new transparency log entry
    pub fn new(log_index: u64, uuid: impl Into<String>) -> Self {
        Self {
            log_index,
            uuid: uuid.into(),
            body: String::new(),
            integrated_time: chrono::Utc::now().timestamp(),
            log_id: String::new(),
            inclusion_proof: None,
        }
    }

    /// Set body data (will be base64-encoded)
    pub fn with_body(mut self, body: &[u8]) -> Self {
        self.body = base64::engine::general_purpose::STANDARD.encode(body);
        self
    }

    /// Add inclusion proof
    pub fn with_inclusion_proof(mut self, proof: InclusionProof) -> Self {
        self.inclusion_proof = Some(proof);
        self
    }

    /// Serialize to JSON
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// Deserialize from JSON
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }
}

/// WASM custom section names for hardware attestation
const DEVICE_ATTESTATION_SECTION: &str = "wsc.device_attestation";
const TRANSPARENCY_LOG_SECTION: &str = "wsc.transparency_log";

/// Embed device attestation in a WASM module as a custom section
pub fn embed_device_attestation(
    mut module: Module,
    attestation: &DeviceAttestation,
) -> Result<Module, WSError> {
    let json = attestation.to_json().map_err(|e| {
        WSError::InternalError(format!("Failed to serialize device attestation: {}", e))
    })?;

    let custom_section = CustomSection::new(
        DEVICE_ATTESTATION_SECTION.to_string(),
        json.as_bytes().to_vec(),
    );

    module.sections.push(Section::Custom(custom_section));
    Ok(module)
}

/// Extract device attestation from a WASM module
pub fn extract_device_attestation(module: &Module) -> Result<Option<DeviceAttestation>, WSError> {
    for section in &module.sections {
        if let Section::Custom(custom) = section
            && custom.name() == DEVICE_ATTESTATION_SECTION {
                let json = std::str::from_utf8(custom.payload()).map_err(|e| {
                    WSError::InternalError(format!("Invalid UTF-8 in device attestation: {}", e))
                })?;

                let attestation = DeviceAttestation::from_json(json).map_err(|e| {
                    WSError::InternalError(format!(
                        "Failed to deserialize device attestation: {}",
                        e
                    ))
                })?;

                return Ok(Some(attestation));
            }
    }
    Ok(None)
}

/// Embed transparency log entry in a WASM module as a custom section
pub fn embed_transparency_log_entry(
    mut module: Module,
    entry: &TransparencyLogEntry,
) -> Result<Module, WSError> {
    let json = entry.to_json().map_err(|e| {
        WSError::InternalError(format!("Failed to serialize transparency log entry: {}", e))
    })?;

    let custom_section = CustomSection::new(
        TRANSPARENCY_LOG_SECTION.to_string(),
        json.as_bytes().to_vec(),
    );

    module.sections.push(Section::Custom(custom_section));
    Ok(module)
}

/// Extract transparency log entry from a WASM module
pub fn extract_transparency_log_entry(
    module: &Module,
) -> Result<Option<TransparencyLogEntry>, WSError> {
    for section in &module.sections {
        if let Section::Custom(custom) = section
            && custom.name() == TRANSPARENCY_LOG_SECTION {
                let json = std::str::from_utf8(custom.payload()).map_err(|e| {
                    WSError::InternalError(format!(
                        "Invalid UTF-8 in transparency log entry: {}",
                        e
                    ))
                })?;

                let entry = TransparencyLogEntry::from_json(json).map_err(|e| {
                    WSError::InternalError(format!(
                        "Failed to deserialize transparency log entry: {}",
                        e
                    ))
                })?;

                return Ok(Some(entry));
            }
    }
    Ok(None)
}

// =============================================================================
// DSSE-based attestation functions (standard format)
// =============================================================================

/// Section name for DSSE-wrapped attestations
pub const DSSE_ATTESTATION_SECTION: &str = "wsc.attestation";

/// Embed a SLSA provenance attestation in DSSE format
///
/// Creates a signed DSSE envelope containing an in-toto statement
/// with SLSA v1.0 provenance predicate.
///
/// # Arguments
///
/// * `module` - The WASM module to embed into
/// * `provenance` - SLSA v1.0 provenance data
/// * `signer` - DSSE signer for creating the signature
///
/// # Returns
///
/// The module with embedded DSSE attestation
pub fn embed_slsa_provenance(
    mut module: Module,
    provenance: &crate::slsa::Provenance,
    signer: &dyn crate::dsse::DsseSigner,
) -> Result<Module, WSError> {
    use crate::dsse::DsseEnvelope;
    use crate::intoto::{predicate_types, Statement, Subject};
    use sha2::{Digest, Sha256};

    // Compute module hash for subject
    let mut module_bytes = Vec::new();
    module
        .serialize(&mut module_bytes)
        .map_err(|e| WSError::InternalError(format!("Failed to serialize module: {}", e)))?;
    let module_hash = hex::encode(Sha256::digest(&module_bytes));

    // Create in-toto statement
    let statement = Statement::new(
        vec![Subject::new("module.wasm", &module_hash)],
        predicate_types::SLSA_PROVENANCE_V1,
        provenance.clone(),
    );

    // Wrap in DSSE envelope
    let payload = statement.to_json_bytes()?;
    let envelope = DsseEnvelope::sign(&payload, crate::dsse::payload_types::IN_TOTO, signer)?;

    // Serialize and embed
    let envelope_json = envelope.to_json()?;
    let custom_section =
        CustomSection::new(DSSE_ATTESTATION_SECTION.to_string(), envelope_json.into_bytes());
    module.sections.push(Section::Custom(custom_section));

    Ok(module)
}

/// Embed a transformation attestation in DSSE format
///
/// Creates a signed DSSE envelope for transformation tracking.
///
/// # Arguments
///
/// * `module` - The WASM module to embed into
/// * `attestation` - Transformation attestation from wsc-attestation
/// * `signer` - DSSE signer for creating the signature
pub fn embed_transformation_dsse(
    mut module: Module,
    attestation: &wsc_attestation::TransformationAttestation,
    signer: &dyn crate::dsse::DsseSigner,
) -> Result<Module, WSError> {
    use crate::dsse::DsseEnvelope;
    use crate::intoto::{predicate_types, Statement, Subject};
    use sha2::{Digest, Sha256};

    // Compute module hash for subject
    let mut module_bytes = Vec::new();
    module
        .serialize(&mut module_bytes)
        .map_err(|e| WSError::InternalError(format!("Failed to serialize module: {}", e)))?;
    let module_hash = hex::encode(Sha256::digest(&module_bytes));

    // Create in-toto statement with transformation predicate
    let statement = Statement::new(
        vec![Subject::new(&attestation.output.name, &module_hash)],
        predicate_types::WSC_TRANSFORMATION_V1,
        attestation.clone(),
    );

    // Wrap in DSSE envelope
    let payload = statement.to_json_bytes()?;
    let envelope = DsseEnvelope::sign(&payload, crate::dsse::payload_types::IN_TOTO, signer)?;

    // Serialize and embed
    let envelope_json = envelope.to_json()?;
    let custom_section =
        CustomSection::new(DSSE_ATTESTATION_SECTION.to_string(), envelope_json.into_bytes());
    module.sections.push(Section::Custom(custom_section));

    Ok(module)
}

/// Extract DSSE attestation envelope from a module
///
/// Returns the raw DSSE envelope which can be:
/// - Verified with any DSSE-compatible tool
/// - Saved as a standalone .sigstore bundle
/// - Parsed to extract the in-toto statement
pub fn extract_dsse_attestation(module: &Module) -> Result<Option<crate::dsse::DsseEnvelope>, WSError> {
    for section in &module.sections {
        if let Section::Custom(custom) = section {
            if custom.name() == DSSE_ATTESTATION_SECTION {
                let json = std::str::from_utf8(custom.payload()).map_err(|e| {
                    WSError::InternalError(format!("Invalid UTF-8 in DSSE attestation: {}", e))
                })?;

                let envelope = crate::dsse::DsseEnvelope::from_json(json)?;
                return Ok(Some(envelope));
            }
        }
    }
    Ok(None)
}

/// Extract and verify DSSE attestation
///
/// Extracts the DSSE envelope and verifies the signature.
///
/// # Returns
///
/// The verified payload bytes (in-toto statement JSON)
pub fn extract_and_verify_dsse(
    module: &Module,
    verifier: &dyn crate::dsse::DsseVerifier,
) -> Result<Option<Vec<u8>>, WSError> {
    if let Some(envelope) = extract_dsse_attestation(module)? {
        let payload = envelope.verify(verifier)?;
        Ok(Some(payload))
    } else {
        Ok(None)
    }
}

/// Extract SLSA provenance from DSSE attestation
///
/// Extracts and parses the SLSA v1.0 provenance predicate.
pub fn extract_slsa_provenance(
    module: &Module,
    verifier: &dyn crate::dsse::DsseVerifier,
) -> Result<Option<crate::slsa::Provenance>, WSError> {
    use crate::intoto::Statement;

    if let Some(payload) = extract_and_verify_dsse(module, verifier)? {
        let statement: Statement<crate::slsa::Provenance> = Statement::from_json_bytes(&payload)?;
        Ok(Some(statement.predicate))
    } else {
        Ok(None)
    }
}

/// Extract transformation attestation from DSSE envelope
pub fn extract_transformation_from_dsse(
    module: &Module,
    verifier: &dyn crate::dsse::DsseVerifier,
) -> Result<Option<wsc_attestation::TransformationAttestation>, WSError> {
    use crate::intoto::Statement;

    if let Some(payload) = extract_and_verify_dsse(module, verifier)? {
        let statement: Statement<wsc_attestation::TransformationAttestation> =
            Statement::from_json_bytes(&payload)?;
        Ok(Some(statement.predicate))
    } else {
        Ok(None)
    }
}

// =============================================================================
// Validation functions
// =============================================================================

/// Validate device attestation
pub fn validate_device_attestation(
    attestation: &DeviceAttestation,
    _expected_device_id: Option<&str>,
) -> Result<(), String> {
    // Check required fields are present
    if attestation.device_id.is_empty() {
        return Err("Device ID is required".to_string());
    }

    if attestation.device_public_key.is_empty() {
        return Err("Device public key is required".to_string());
    }

    // Validate device ID matches expected (if provided)
    if let Some(expected) = _expected_device_id
        && attestation.device_id != expected {
            return Err(format!(
                "Device ID mismatch: expected '{}', got '{}'",
                expected, attestation.device_id
            ));
        }

    // Validate timestamp format
    if chrono::DateTime::parse_from_rfc3339(&attestation.timestamp).is_err() {
        return Err(format!(
            "Invalid timestamp format: {}",
            attestation.timestamp
        ));
    }

    Ok(())
}

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

    #[test]
    fn test_provenance_builder() {
        let prov = ProvenanceBuilder::new()
            .component_name("test-component")
            .version("1.0.0")
            .source_repo("https://github.com/test/comp")
            .commit_sha("abc123")
            .build_tool("cargo", "1.75.0")
            .builder_identity("CI/CD")
            .add_metadata("platform", "wasm32-wasi")
            .build();

        assert_eq!(prov.name, "test-component");
        assert_eq!(prov.version, "1.0.0");
        assert_eq!(
            prov.source_repo,
            Some("https://github.com/test/comp".to_string())
        );
        assert_eq!(prov.commit_sha, Some("abc123".to_string()));
        assert_eq!(prov.build_tool, "cargo");
        assert_eq!(
            prov.metadata.get("platform"),
            Some(&"wasm32-wasi".to_string())
        );
    }

    #[test]
    fn test_composition_manifest() {
        let mut manifest = CompositionManifest::new("wac", "0.5.0");

        manifest.add_component("comp-a", "sha256:abc123");
        manifest.add_component_with_source(
            "comp-b",
            "sha256:def456",
            "https://github.com/test/comp-b",
        );

        manifest.set_integrator("CN=Integrator, O=Test Corp", 2);

        assert_eq!(manifest.components.len(), 2);
        assert_eq!(manifest.components[0].id, "comp-a");
        assert_eq!(
            manifest.components[1].source,
            Some("https://github.com/test/comp-b".to_string())
        );
        assert!(manifest.integrator.is_some());
    }

    #[test]
    fn test_manifest_json_roundtrip() {
        let mut manifest = CompositionManifest::new("wac", "0.5.0");
        manifest.add_component("test", "sha256:123");

        let json = manifest.to_json().unwrap();
        let deserialized = CompositionManifest::from_json(&json).unwrap();

        assert_eq!(deserialized.tool, "wac");
        assert_eq!(deserialized.components.len(), 1);
        assert_eq!(deserialized.components[0].id, "test");
    }

    #[test]
    fn test_sbom_creation() {
        let sbom = Sbom::new("composed-app", "1.0.0");

        assert_eq!(sbom.bom_format, "CycloneDX");
        assert_eq!(sbom.spec_version, "1.5");
        assert!(sbom.serial_number.starts_with("urn:uuid:"));
        assert_eq!(sbom.version, 1);
        assert!(sbom.metadata.is_some());
    }

    #[test]
    fn test_sbom_add_components() {
        let mut sbom = Sbom::new("composed-app", "1.0.0");

        sbom.add_component("component-a", "1.0.0", "abc123");
        sbom.add_component_with_source(
            "component-b",
            "2.0.0",
            "def456",
            "https://github.com/test/component-b",
        );

        assert_eq!(sbom.components.len(), 2);
        assert_eq!(sbom.components[0].name, "component-a");
        assert_eq!(sbom.components[0].hashes[0].alg, "SHA-256");
        assert_eq!(sbom.components[0].hashes[0].content, "abc123");

        assert_eq!(sbom.components[1].name, "component-b");
        assert_eq!(sbom.components[1].external_references.len(), 1);
        assert_eq!(sbom.components[1].external_references[0].ref_type, "vcs");
    }

    #[test]
    fn test_sbom_json_serialization() {
        let mut sbom = Sbom::new("test-app", "1.0.0");
        sbom.add_component("comp-a", "1.0.0", "hash123");

        let json = sbom.to_json().unwrap();
        assert!(json.contains("CycloneDX"));
        assert!(json.contains("comp-a"));

        // Verify it's valid JSON and can be deserialized
        let deserialized = Sbom::from_json(&json).unwrap();
        assert_eq!(deserialized.components.len(), 1);
        assert_eq!(deserialized.components[0].name, "comp-a");
    }

    #[test]
    fn test_sbom_metadata() {
        let sbom = Sbom::new("test-app", "1.0.0");

        let metadata = sbom.metadata.as_ref().unwrap();
        assert!(!metadata.timestamp.is_empty());
        assert_eq!(metadata.tools.len(), 1);
        assert_eq!(metadata.tools[0].name, "wsc");
        assert!(metadata.tools[0].vendor.is_some());

        assert!(metadata.component.is_some());
        let component = metadata.component.as_ref().unwrap();
        assert_eq!(component.name, "test-app");
        assert_eq!(component.version.as_ref().unwrap(), "1.0.0");
    }

    #[test]
    fn test_intoto_attestation_creation() {
        let attestation =
            InTotoAttestation::new_composition("composed.wasm", "abc123def456", "wsc-builder");

        assert_eq!(attestation.payload_type, "application/vnd.in-toto+json");
        assert_eq!(attestation.subject.len(), 1);
        assert_eq!(attestation.subject[0].name, "composed.wasm");
        assert_eq!(
            attestation.subject[0].digest.get("sha256"),
            Some(&"abc123def456".to_string())
        );
        assert_eq!(attestation.predicate.builder.id, "wsc-builder");
    }

    #[test]
    fn test_intoto_add_materials() {
        let mut attestation =
            InTotoAttestation::new_composition("composed.wasm", "abc123", "builder");

        attestation.add_material("component-a.wasm", "hash-a");
        attestation.add_material("component-b.wasm", "hash-b");

        assert_eq!(attestation.predicate.materials.len(), 2);
        assert_eq!(attestation.predicate.materials[0].uri, "component-a.wasm");
        assert_eq!(
            attestation.predicate.materials[0].digest.get("sha256"),
            Some(&"hash-a".to_string())
        );
        assert_eq!(attestation.predicate.materials[1].uri, "component-b.wasm");
    }

    #[test]
    fn test_intoto_json_serialization() {
        let mut attestation =
            InTotoAttestation::new_composition("test.wasm", "hash123", "test-builder");
        attestation.add_material("input.wasm", "input-hash");

        let json = attestation.to_json().unwrap();
        assert!(json.contains("application/vnd.in-toto+json"));
        assert!(json.contains("test.wasm"));
        assert!(json.contains("test-builder"));

        // Verify deserialization
        let deserialized = InTotoAttestation::from_json(&json).unwrap();
        assert_eq!(deserialized.subject.len(), 1);
        assert_eq!(deserialized.predicate.materials.len(), 1);
    }

    #[test]
    fn test_full_composition_workflow() {
        // 1. Create composition manifest
        let mut manifest = CompositionManifest::new("wac", "0.5.0");
        manifest.add_component_with_source(
            "component-a",
            "sha256:abc123",
            "https://github.com/owner/component-a",
        );
        manifest.add_component_with_source(
            "component-b",
            "sha256:def456",
            "https://github.com/owner/component-b",
        );
        manifest.set_integrator("CN=Integrator, O=Test Corp", 2);

        // 2. Generate SBOM
        let mut sbom = Sbom::new("composed-app", "1.0.0");
        for component in &manifest.components {
            if let Some(source) = &component.source {
                sbom.add_component_with_source(&component.id, "1.0.0", &component.hash, source);
            } else {
                sbom.add_component(&component.id, "1.0.0", &component.hash);
            }
        }

        // 3. Create in-toto attestation
        let mut attestation = InTotoAttestation::new_composition(
            "composed-app.wasm",
            "composed-hash-xyz",
            "wsc-integrator",
        );
        for component in &manifest.components {
            attestation.add_material(format!("{}.wasm", component.id), &component.hash);
        }

        // Verify everything is consistent
        assert_eq!(manifest.components.len(), 2);
        assert_eq!(sbom.components.len(), 2);
        assert_eq!(attestation.predicate.materials.len(), 2);

        // Verify all can be serialized
        let _manifest_json = manifest.to_json().unwrap();
        let _sbom_json = sbom.to_json().unwrap();
        let _attestation_json = attestation.to_json().unwrap();
    }

    #[test]
    fn test_cyclonedx_spec_compliance() {
        let sbom = Sbom::new("test", "1.0.0");
        let json = sbom.to_json().unwrap();

        // Verify required CycloneDX 1.5 fields
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed["bomFormat"], "CycloneDX");
        assert_eq!(parsed["specVersion"], "1.5");
        assert!(
            parsed["serialNumber"]
                .as_str()
                .unwrap()
                .starts_with("urn:uuid:")
        );
        assert_eq!(parsed["version"], 1);
        assert!(parsed["metadata"].is_object());
    }

    #[test]
    fn test_intoto_predicate_type() {
        let attestation = InTotoAttestation::new_composition("test", "hash", "builder");

        // Verify custom predicate type for composition
        assert_eq!(
            attestation.predicate_type,
            "https://wsc.dev/in-toto/composition/v1"
        );
        assert_eq!(
            attestation.predicate.build_type,
            "https://wsc.dev/composition@v1"
        );
    }

    // Helper to create a minimal WASM module for testing
    fn create_test_module() -> Module {
        Module {
            header: [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00],
            sections: vec![],
        }
    }

    #[test]
    fn test_embed_extract_composition_manifest() {
        let mut manifest = CompositionManifest::new("wac", "0.5.0");
        manifest.add_component("comp-a", "hash-a");
        manifest.add_component("comp-b", "hash-b");

        let module = create_test_module();
        let module_with_manifest = embed_composition_manifest(module, &manifest).unwrap();

        // Verify custom section was added
        assert_eq!(module_with_manifest.sections.len(), 1);

        // Extract and verify
        let extracted = extract_composition_manifest(&module_with_manifest).unwrap();
        assert!(extracted.is_some());

        let extracted_manifest = extracted.unwrap();
        assert_eq!(extracted_manifest.tool, "wac");
        assert_eq!(extracted_manifest.components.len(), 2);
        assert_eq!(extracted_manifest.components[0].id, "comp-a");
    }

    #[test]
    fn test_embed_extract_build_provenance() {
        let provenance = ProvenanceBuilder::new()
            .component_name("test-comp")
            .version("1.0.0")
            .source_repo("https://github.com/test/repo")
            .commit_sha("abc123")
            .build_tool("cargo", "1.75.0")
            .build();

        let module = create_test_module();
        let module_with_prov = embed_build_provenance(module, &provenance).unwrap();

        // Extract and verify
        let extracted = extract_build_provenance(&module_with_prov).unwrap();
        assert!(extracted.is_some());

        let extracted_prov = extracted.unwrap();
        assert_eq!(extracted_prov.name, "test-comp");
        assert_eq!(extracted_prov.version, "1.0.0");
        assert_eq!(extracted_prov.commit_sha, Some("abc123".to_string()));
    }

    #[test]
    fn test_embed_extract_sbom() {
        let mut sbom = Sbom::new("app", "1.0.0");
        sbom.add_component("comp-a", "1.0.0", "hash-a");
        sbom.add_component_with_source("comp-b", "2.0.0", "hash-b", "https://github.com/test/b");

        let module = create_test_module();
        let module_with_sbom = embed_sbom(module, &sbom).unwrap();

        // Extract and verify
        let extracted = extract_sbom(&module_with_sbom).unwrap();
        assert!(extracted.is_some());

        let extracted_sbom = extracted.unwrap();
        assert_eq!(extracted_sbom.components.len(), 2);
        assert_eq!(extracted_sbom.components[0].name, "comp-a");
        assert_eq!(extracted_sbom.components[1].name, "comp-b");
    }

    #[test]
    fn test_embed_extract_intoto_attestation() {
        let mut attestation =
            InTotoAttestation::new_composition("app.wasm", "final-hash", "integrator");
        attestation.add_material("comp-a.wasm", "hash-a");
        attestation.add_material("comp-b.wasm", "hash-b");

        let module = create_test_module();
        let module_with_att = embed_intoto_attestation(module, &attestation).unwrap();

        // Extract and verify
        let extracted = extract_intoto_attestation(&module_with_att).unwrap();
        assert!(extracted.is_some());

        let extracted_att = extracted.unwrap();
        assert_eq!(extracted_att.subject.len(), 1);
        assert_eq!(extracted_att.subject[0].name, "app.wasm");
        assert_eq!(extracted_att.predicate.materials.len(), 2);
    }

    #[test]
    fn test_embed_all_provenance() {
        let manifest = CompositionManifest::new("wac", "0.5.0");
        let provenance = ProvenanceBuilder::new()
            .component_name("app")
            .version("1.0.0")
            .build();
        let sbom = Sbom::new("app", "1.0.0");
        let attestation = InTotoAttestation::new_composition("app.wasm", "hash", "builder");

        let module = create_test_module();
        let module_with_all =
            embed_all_provenance(module, &manifest, &provenance, &sbom, &attestation).unwrap();

        // Should have 4 custom sections
        assert_eq!(module_with_all.sections.len(), 4);

        // Extract all and verify
        let (m, p, s, a) = extract_all_provenance(&module_with_all).unwrap();
        assert!(m.is_some());
        assert!(p.is_some());
        assert!(s.is_some());
        assert!(a.is_some());
    }

    #[test]
    fn test_extract_from_module_without_provenance() {
        let module = create_test_module();

        // Extracting from empty module should return None for all
        let manifest = extract_composition_manifest(&module).unwrap();
        assert!(manifest.is_none());

        let provenance = extract_build_provenance(&module).unwrap();
        assert!(provenance.is_none());

        let sbom = extract_sbom(&module).unwrap();
        assert!(sbom.is_none());

        let attestation = extract_intoto_attestation(&module).unwrap();
        assert!(attestation.is_none());
    }

    #[test]
    fn test_roundtrip_serialization() {
        // Create full provenance
        let manifest = CompositionManifest::new("wac", "0.5.0");
        let provenance = ProvenanceBuilder::new()
            .component_name("app")
            .version("1.0.0")
            .build();
        let sbom = Sbom::new("app", "1.0.0");
        let attestation = InTotoAttestation::new_composition("app.wasm", "hash", "builder");

        // Embed in module
        let module = create_test_module();
        let module_with_all =
            embed_all_provenance(module, &manifest, &provenance, &sbom, &attestation).unwrap();

        // Serialize to bytes
        let mut buffer = Vec::new();
        module_with_all.serialize(&mut buffer).unwrap();

        // Deserialize back
        let mut reader = std::io::Cursor::new(buffer);
        let deserialized_module = Module::deserialize(&mut reader).unwrap();

        // Extract and verify
        let (m, p, s, a) = extract_all_provenance(&deserialized_module).unwrap();
        assert!(m.is_some());
        assert!(p.is_some());
        assert!(s.is_some());
        assert!(a.is_some());

        // Verify data integrity
        assert_eq!(m.unwrap().tool, "wac");
        assert_eq!(p.unwrap().name, "app");
        assert_eq!(s.unwrap().bom_format, "CycloneDX");
        assert_eq!(a.unwrap().predicate.builder.id, "builder");
    }

    #[test]
    fn test_multiple_sections_preserved() {
        // Start with a module that has existing custom sections
        let mut module = create_test_module();
        let existing_section = CustomSection::new("existing".to_string(), vec![1, 2, 3]);
        module.sections.push(Section::Custom(existing_section));

        // Add provenance
        let manifest = CompositionManifest::new("wac", "0.5.0");
        let module_with_prov = embed_composition_manifest(module, &manifest).unwrap();

        // Should have both sections
        assert_eq!(module_with_prov.sections.len(), 2);

        // Verify both sections exist
        let mut found_existing = false;
        let mut found_manifest = false;

        for section in &module_with_prov.sections {
            if let Section::Custom(custom) = section {
                if custom.name() == "existing" {
                    found_existing = true;
                }
                if custom.name() == COMPOSITION_MANIFEST_SECTION {
                    found_manifest = true;
                }
            }
        }

        assert!(found_existing, "Existing section was lost");
        assert!(found_manifest, "Manifest section was not added");
    }

    // ========================================================================
    // Dependency Graph Tests
    // ========================================================================

    #[test]
    fn test_dependency_graph_creation() {
        let mut graph = DependencyGraph::new();
        graph.add_component("comp-a", "hash-a");
        graph.add_component("comp-b", "hash-b");

        // Graph should have two components
        assert_eq!(graph.expected_hashes.len(), 2);
    }

    #[test]
    fn test_dependency_graph_from_manifest() {
        let mut manifest = CompositionManifest::new("wac", "0.5.0");
        manifest.add_component("comp-a", "hash-a");
        manifest.add_component("comp-b", "hash-b");
        manifest.add_component("comp-c", "hash-c");

        let graph = DependencyGraph::from_manifest(&manifest);

        assert_eq!(graph.expected_hashes.len(), 3);
        assert_eq!(
            graph.expected_hashes.get("comp-a"),
            Some(&"hash-a".to_string())
        );
    }

    #[test]
    fn test_cycle_detection_no_cycle() {
        let mut graph = DependencyGraph::new();
        graph.add_component("a", "hash-a");
        graph.add_component("b", "hash-b");
        graph.add_component("c", "hash-c");

        // a -> b -> c (no cycle)
        graph.add_dependency("a", "b");
        graph.add_dependency("b", "c");

        let cycle = graph.detect_cycles();
        assert!(cycle.is_none(), "No cycle should be detected");
    }

    #[test]
    fn test_cycle_detection_simple_cycle() {
        let mut graph = DependencyGraph::new();
        graph.add_component("a", "hash-a");
        graph.add_component("b", "hash-b");

        // a -> b -> a (simple cycle)
        graph.add_dependency("a", "b");
        graph.add_dependency("b", "a");

        let cycle = graph.detect_cycles();
        assert!(cycle.is_some(), "Cycle should be detected");

        let cycle = cycle.unwrap();
        assert!(cycle.len() >= 2, "Cycle should have at least 2 nodes");
        assert!(cycle.contains(&"a".to_string()));
        assert!(cycle.contains(&"b".to_string()));
    }

    #[test]
    fn test_cycle_detection_complex_cycle() {
        let mut graph = DependencyGraph::new();
        graph.add_component("a", "hash-a");
        graph.add_component("b", "hash-b");
        graph.add_component("c", "hash-c");
        graph.add_component("d", "hash-d");

        // a -> b -> c -> d -> b (cycle involving b, c, d)
        graph.add_dependency("a", "b");
        graph.add_dependency("b", "c");
        graph.add_dependency("c", "d");
        graph.add_dependency("d", "b");

        let cycle = graph.detect_cycles();
        assert!(cycle.is_some(), "Cycle should be detected");

        let cycle = cycle.unwrap();
        // The cycle should be b -> c -> d -> b
        assert!(cycle.contains(&"b".to_string()));
        assert!(cycle.contains(&"c".to_string()));
        assert!(cycle.contains(&"d".to_string()));
    }

    #[test]
    fn test_substitution_detection_no_substitution() {
        let mut graph = DependencyGraph::new();
        graph.add_component("comp-a", "hash-a");
        graph.add_component("comp-b", "hash-b");

        // Set actual hashes that match expected
        graph.set_actual_hash("comp-a", "hash-a");
        graph.set_actual_hash("comp-b", "hash-b");

        let substitutions = graph.detect_substitutions();
        assert!(
            substitutions.is_empty(),
            "No substitutions should be detected"
        );
    }

    #[test]
    fn test_substitution_detection_with_substitution() {
        let mut graph = DependencyGraph::new();
        graph.add_component("comp-a", "hash-a");
        graph.add_component("comp-b", "hash-b");

        // Set actual hash for comp-a that doesn't match expected
        graph.set_actual_hash("comp-a", "hash-a-modified");
        graph.set_actual_hash("comp-b", "hash-b");

        let substitutions = graph.detect_substitutions();
        assert_eq!(
            substitutions.len(),
            1,
            "One substitution should be detected"
        );

        let sub = &substitutions[0];
        assert_eq!(sub.component_id, "comp-a");
        assert_eq!(sub.expected_hash, "hash-a");
        assert_eq!(sub.actual_hash, "hash-a-modified");
    }

    #[test]
    fn test_substitution_detection_multiple() {
        let mut graph = DependencyGraph::new();
        graph.add_component("comp-a", "hash-a");
        graph.add_component("comp-b", "hash-b");
        graph.add_component("comp-c", "hash-c");

        // Two components have been substituted
        graph.set_actual_hash("comp-a", "hash-a-wrong");
        graph.set_actual_hash("comp-b", "hash-b");
        graph.set_actual_hash("comp-c", "hash-c-wrong");

        let substitutions = graph.detect_substitutions();
        assert_eq!(
            substitutions.len(),
            2,
            "Two substitutions should be detected"
        );
    }

    #[test]
    fn test_validation_success() {
        let mut graph = DependencyGraph::new();
        graph.add_component("comp-a", "hash-a");
        graph.add_component("comp-b", "hash-b");
        graph.add_dependency("comp-a", "comp-b");

        // Set matching actual hashes
        graph.set_actual_hash("comp-a", "hash-a");
        graph.set_actual_hash("comp-b", "hash-b");

        let result = graph.validate().unwrap();
        assert!(result.valid, "Validation should pass");
        assert!(result.errors.is_empty(), "No errors should be present");
    }

    #[test]
    fn test_validation_cycle_error() {
        let mut graph = DependencyGraph::new();
        graph.add_component("comp-a", "hash-a");
        graph.add_component("comp-b", "hash-b");

        // Create a cycle
        graph.add_dependency("comp-a", "comp-b");
        graph.add_dependency("comp-b", "comp-a");

        let result = graph.validate().unwrap();
        assert!(!result.valid, "Validation should fail due to cycle");
        assert!(!result.errors.is_empty(), "Errors should be present");
        assert!(result.errors[0].contains("Cycle detected"));
    }

    #[test]
    fn test_validation_substitution_error() {
        let mut graph = DependencyGraph::new();
        graph.add_component("comp-a", "hash-a");

        // Set wrong actual hash
        graph.set_actual_hash("comp-a", "hash-wrong");

        let result = graph.validate().unwrap();
        assert!(!result.valid, "Validation should fail due to substitution");
        assert!(!result.errors.is_empty(), "Errors should be present");
        assert!(result.errors[0].contains("substituted"));
    }

    #[test]
    fn test_validation_missing_dependency_warning() {
        let mut graph = DependencyGraph::new();
        graph.add_component("comp-a", "hash-a");
        graph.add_dependency("comp-a", "comp-b"); // comp-b doesn't exist

        let result = graph.validate().unwrap();
        assert!(result.valid, "Should still be valid (just a warning)");
        assert!(!result.warnings.is_empty(), "Warning should be present");
        assert!(result.warnings[0].contains("missing component"));
    }

    #[test]
    fn test_topological_sort_simple() {
        let mut graph = DependencyGraph::new();
        graph.add_component("a", "hash-a");
        graph.add_component("b", "hash-b");
        graph.add_component("c", "hash-c");

        // a -> b -> c
        graph.add_dependency("a", "b");
        graph.add_dependency("b", "c");

        let sorted = graph.topological_sort();
        assert!(sorted.is_some(), "Should be able to sort");

        let sorted = sorted.unwrap();
        assert_eq!(sorted.len(), 3);

        // In a DAG a -> b -> c, topological sort puts leaves first
        // So c (leaf) comes before b, and b comes before a (root)
        let c_pos = sorted.iter().position(|x| x == "c").unwrap();
        let b_pos = sorted.iter().position(|x| x == "b").unwrap();
        let a_pos = sorted.iter().position(|x| x == "a").unwrap();

        // Verify: c < b < a in sorted order (dependencies first)
        assert!(
            c_pos < b_pos,
            "c (no deps) should come before b (depends on c)"
        );
        assert!(
            b_pos < a_pos,
            "b (depends on c) should come before a (depends on b)"
        );
    }

    #[test]
    fn test_topological_sort_with_cycle() {
        let mut graph = DependencyGraph::new();
        graph.add_component("a", "hash-a");
        graph.add_component("b", "hash-b");

        // Create a cycle
        graph.add_dependency("a", "b");
        graph.add_dependency("b", "a");

        let sorted = graph.topological_sort();
        assert!(sorted.is_none(), "Should not be able to sort with cycle");
    }

    #[test]
    fn test_topological_sort_complex() {
        let mut graph = DependencyGraph::new();
        graph.add_component("a", "hash-a");
        graph.add_component("b", "hash-b");
        graph.add_component("c", "hash-c");
        graph.add_component("d", "hash-d");

        // Complex DAG:
        // a -> b
        // a -> c
        // b -> d
        // c -> d
        graph.add_dependency("a", "b");
        graph.add_dependency("a", "c");
        graph.add_dependency("b", "d");
        graph.add_dependency("c", "d");

        let sorted = graph.topological_sort();
        assert!(sorted.is_some(), "Should be able to sort");

        let sorted = sorted.unwrap();
        assert_eq!(sorted.len(), 4);

        // d should be first (no dependencies)
        // a should be last (depends on everything)
        let d_pos = sorted.iter().position(|x| x == "d").unwrap();
        let a_pos = sorted.iter().position(|x| x == "a").unwrap();

        assert!(d_pos < a_pos, "d should come before a");
    }

    #[test]
    fn test_dependency_graph_comprehensive() {
        // Create a realistic composition scenario
        let mut graph = DependencyGraph::new();

        // Add components
        graph.add_component("http-client", "sha256:abc123");
        graph.add_component("json-parser", "sha256:def456");
        graph.add_component("app-logic", "sha256:ghi789");
        graph.add_component("main-app", "sha256:jkl012");

        // Set up dependencies
        graph.add_dependency("main-app", "app-logic");
        graph.add_dependency("app-logic", "http-client");
        graph.add_dependency("app-logic", "json-parser");

        // Set actual hashes (all correct)
        graph.set_actual_hash("http-client", "sha256:abc123");
        graph.set_actual_hash("json-parser", "sha256:def456");
        graph.set_actual_hash("app-logic", "sha256:ghi789");
        graph.set_actual_hash("main-app", "sha256:jkl012");

        // Validate
        let result = graph.validate().unwrap();
        assert!(result.valid);
        assert!(result.errors.is_empty());

        // Check topological sort
        let sorted = graph.topological_sort();
        assert!(sorted.is_some());

        let sorted = sorted.unwrap();
        // main-app should be last
        assert_eq!(sorted.last(), Some(&"main-app".to_string()));
    }

    #[test]
    fn test_attack_scenario_substitution() {
        // Simulating an attack where a component has been substituted
        let mut graph = DependencyGraph::new();

        // Original manifest
        graph.add_component("crypto-lib", "sha256:trusted-hash");
        graph.add_component("app", "sha256:app-hash");
        graph.add_dependency("app", "crypto-lib");

        // Attacker substitutes crypto-lib with malicious version
        graph.set_actual_hash("crypto-lib", "sha256:malicious-hash");
        graph.set_actual_hash("app", "sha256:app-hash");

        // Validation should catch this
        let result = graph.validate().unwrap();
        assert!(!result.valid, "Attack should be detected");
        assert!(!result.errors.is_empty());
        assert!(result.errors[0].contains("crypto-lib"));
        assert!(result.errors[0].contains("malicious-hash"));
    }

    // ========================================================================
    // Phase 3: Advanced Validation Tests
    // ========================================================================

    #[test]
    fn test_version_constraint_exact() {
        let constraint = VersionConstraint::Exact("1.2.3".to_string());

        assert!(constraint.satisfies("1.2.3"));
        assert!(!constraint.satisfies("1.2.4"));
        assert!(!constraint.satisfies("1.2.2"));
    }

    #[test]
    fn test_version_constraint_minimum() {
        let constraint = VersionConstraint::Minimum("1.0.0".to_string());

        assert!(constraint.satisfies("1.0.0"));
        assert!(constraint.satisfies("1.0.1"));
        assert!(constraint.satisfies("2.0.0"));
        assert!(!constraint.satisfies("0.9.9"));
    }

    #[test]
    fn test_version_constraint_maximum() {
        let constraint = VersionConstraint::Maximum("2.0.0".to_string());

        assert!(constraint.satisfies("1.0.0"));
        assert!(constraint.satisfies("2.0.0"));
        assert!(!constraint.satisfies("2.0.1"));
        assert!(!constraint.satisfies("3.0.0"));
    }

    #[test]
    fn test_version_constraint_range() {
        let constraint = VersionConstraint::Range("1.0.0".to_string(), "2.0.0".to_string());

        assert!(!constraint.satisfies("0.9.9"));
        assert!(constraint.satisfies("1.0.0"));
        assert!(constraint.satisfies("1.5.0"));
        assert!(constraint.satisfies("2.0.0"));
        assert!(!constraint.satisfies("2.0.1"));
    }

    #[test]
    fn test_version_comparison() {
        assert_eq!(VersionConstraint::compare_versions("1.0.0", "1.0.0"), 0);
        assert_eq!(VersionConstraint::compare_versions("1.0.0", "1.0.1"), -1);
        assert_eq!(VersionConstraint::compare_versions("1.0.1", "1.0.0"), 1);
        assert_eq!(VersionConstraint::compare_versions("2.0.0", "1.9.9"), 1);
        assert_eq!(VersionConstraint::compare_versions("1.9.9", "2.0.0"), -1);
    }

    #[test]
    fn test_version_policy_exact() {
        let mut policy = VersionPolicy::new();
        policy.require_exact("crypto-lib", "1.2.3");

        assert!(policy.validate_version("crypto-lib", "1.2.3").is_ok());
        assert!(policy.validate_version("crypto-lib", "1.2.4").is_err());
        assert!(policy.validate_version("other-lib", "999.0.0").is_ok()); // No constraint
    }

    #[test]
    fn test_version_policy_minimum() {
        let mut policy = VersionPolicy::new();
        policy.require_minimum("crypto-lib", "2.0.0");

        assert!(policy.validate_version("crypto-lib", "1.9.9").is_err());
        assert!(policy.validate_version("crypto-lib", "2.0.0").is_ok());
        assert!(policy.validate_version("crypto-lib", "2.1.0").is_ok());
    }

    #[test]
    fn test_version_policy_range() {
        let mut policy = VersionPolicy::new();
        policy.require_range("lib-a", "1.0.0", "2.0.0");

        assert!(policy.validate_version("lib-a", "0.9.9").is_err());
        assert!(policy.validate_version("lib-a", "1.0.0").is_ok());
        assert!(policy.validate_version("lib-a", "1.5.0").is_ok());
        assert!(policy.validate_version("lib-a", "2.0.0").is_ok());
        assert!(policy.validate_version("lib-a", "2.0.1").is_err());
    }

    #[test]
    fn test_source_allow_list_basic() {
        let mut allow_list = SourceAllowList::new();
        allow_list.add_source("https://github.com/trusted-org");

        assert!(allow_list.is_allowed(Some("https://github.com/trusted-org/repo")));
        assert!(allow_list.is_allowed(Some("https://github.com/trusted-org")));
        assert!(!allow_list.is_allowed(Some("https://github.com/untrusted-org/repo")));
        assert!(!allow_list.is_allowed(None)); // No source not allowed by default
    }

    #[test]
    fn test_source_allow_list_with_no_source() {
        let mut allow_list = SourceAllowList::new();
        allow_list.add_source("https://github.com/trusted");
        allow_list.allow_no_source(true);

        assert!(allow_list.is_allowed(None));
        assert!(allow_list.is_allowed(Some("https://github.com/trusted/repo")));
    }

    #[test]
    fn test_source_allow_list_validation() {
        let mut allow_list = SourceAllowList::new();
        allow_list.add_source("https://internal.company.com");

        assert!(
            allow_list
                .validate_source("comp-a", Some("https://internal.company.com/repo"))
                .is_ok()
        );

        let result = allow_list.validate_source("comp-b", Some("https://external.com/repo"));
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("not in allow-list"));
    }

    #[test]
    fn test_validation_mode_lenient() {
        let config = ValidationConfig::lenient();
        assert_eq!(config.mode, ValidationMode::Lenient);
    }

    #[test]
    fn test_validation_mode_strict() {
        let config = ValidationConfig::strict();
        assert_eq!(config.mode, ValidationMode::Strict);
    }

    #[test]
    fn test_validation_config_builder() {
        let mut policy = VersionPolicy::new();
        policy.require_minimum("lib-a", "1.0.0");

        let mut allow_list = SourceAllowList::new();
        allow_list.add_source("https://github.com/trusted");

        let config = ValidationConfig::strict()
            .with_version_policy(policy)
            .with_source_allow_list(allow_list)
            .with_transitive_validation(true);

        assert_eq!(config.mode, ValidationMode::Strict);
        assert!(config.version_policy.is_some());
        assert!(config.source_allow_list.is_some());
        assert!(config.validate_transitive);
    }

    #[test]
    fn test_strict_mode_converts_warnings_to_errors() {
        let mut graph = DependencyGraph::new();
        graph.add_component("comp-a", "hash-a");
        graph.add_dependency("comp-a", "comp-b"); // comp-b doesn't exist - warning

        // Lenient mode
        let lenient_config = ValidationConfig::lenient();
        let lenient_result = graph.validate_with_config(&lenient_config).unwrap();
        assert!(lenient_result.valid); // Still valid with warnings
        assert!(!lenient_result.warnings.is_empty());
        assert!(lenient_result.errors.is_empty());

        // Strict mode
        let strict_config = ValidationConfig::strict();
        let strict_result = graph.validate_with_config(&strict_config).unwrap();
        assert!(!strict_result.valid); // Not valid - warnings became errors
        assert!(!strict_result.errors.is_empty());
        assert!(strict_result.errors[0].contains("STRICT MODE"));
        assert!(strict_result.warnings.is_empty());
    }

    #[test]
    fn test_version_rollback_attack_detection() {
        // Simulating THREAT-04: Version Rollback Attack
        let mut policy = VersionPolicy::new();
        policy.require_minimum("crypto-lib", "2.0.0"); // Security fix in 2.0.0

        // Attacker tries to use vulnerable old version
        let result = policy.validate_version("crypto-lib", "1.0.0");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("does not satisfy constraint"));
    }

    #[test]
    fn test_dependency_confusion_attack_detection() {
        // Simulating THREAT-02: Dependency Confusion Attack
        let mut allow_list = SourceAllowList::new();
        allow_list.add_source("https://internal.company.com");

        // Attacker publishes to public registry
        let result = allow_list.validate_source(
            "internal-lib",
            Some("https://public-registry.com/internal-lib"),
        );

        assert!(result.is_err());
        assert!(result.unwrap_err().contains("not in allow-list"));
    }

    #[test]
    fn test_comprehensive_validation_config() {
        // Complete validation scenario with all Phase 3 features
        let mut graph = DependencyGraph::new();
        graph.add_component("crypto-lib", "sha256:hash-crypto");
        graph.add_component("http-client", "sha256:hash-http");
        graph.add_component("app", "sha256:hash-app");

        graph.add_dependency("app", "crypto-lib");
        graph.add_dependency("app", "http-client");

        // Set actual hashes (all correct)
        graph.set_actual_hash("crypto-lib", "sha256:hash-crypto");
        graph.set_actual_hash("http-client", "sha256:hash-http");
        graph.set_actual_hash("app", "sha256:hash-app");

        // Create comprehensive validation config
        let mut policy = VersionPolicy::new();
        policy.require_minimum("crypto-lib", "2.0.0");

        let mut allow_list = SourceAllowList::new();
        allow_list.add_source("https://github.com/trusted-org");

        let config = ValidationConfig::strict()
            .with_version_policy(policy)
            .with_source_allow_list(allow_list)
            .with_transitive_validation(true);

        // Validate
        let result = graph.validate_with_config(&config).unwrap();
        assert!(result.valid); // Should pass basic validation
    }

    #[test]
    fn test_version_constraint_any() {
        let constraint = VersionConstraint::Any;

        assert!(constraint.satisfies("0.0.1"));
        assert!(constraint.satisfies("1.0.0"));
        assert!(constraint.satisfies("999.999.999"));
    }

    #[test]
    fn test_multiple_policies_combined() {
        let mut policy = VersionPolicy::new();
        policy.require_minimum("lib-a", "1.0.0");
        policy.require_exact("lib-b", "2.5.0");
        policy.require_range("lib-c", "1.0.0", "2.0.0");

        assert!(policy.validate_version("lib-a", "1.5.0").is_ok());
        assert!(policy.validate_version("lib-b", "2.5.0").is_ok());
        assert!(policy.validate_version("lib-c", "1.5.0").is_ok());

        assert!(policy.validate_version("lib-a", "0.9.0").is_err());
        assert!(policy.validate_version("lib-b", "2.5.1").is_err());
        assert!(policy.validate_version("lib-c", "2.1.0").is_err());
    }

    // ========================================================================
    // Phase 4: Timestamp Validation Tests
    // ========================================================================

    #[test]
    fn test_timestamp_policy_valid() {
        let policy = TimestampPolicy::new();
        let now = chrono::Utc::now().to_rfc3339();

        assert!(policy.validate_timestamp(&now, "Test").is_ok());
    }

    #[test]
    fn test_timestamp_policy_future_within_tolerance() {
        let policy = TimestampPolicy::new().with_future_tolerance_seconds(300); // 5 minutes

        // 2 minutes in the future (within tolerance)
        let future = (chrono::Utc::now() + chrono::Duration::seconds(120)).to_rfc3339();
        assert!(policy.validate_timestamp(&future, "Test").is_ok());
    }

    #[test]
    fn test_timestamp_policy_future_exceeds_tolerance() {
        let policy = TimestampPolicy::new().with_future_tolerance_seconds(300); // 5 minutes

        // 10 minutes in the future (exceeds tolerance)
        let future = (chrono::Utc::now() + chrono::Duration::seconds(600)).to_rfc3339();
        let result = policy.validate_timestamp(&future, "Test");

        assert!(result.is_err());
        assert!(result.unwrap_err().contains("too far in the future"));
    }

    #[test]
    fn test_timestamp_policy_max_age() {
        let policy = TimestampPolicy::new().with_max_age_days(30); // 30 days

        // 10 days ago (within limit)
        let recent = (chrono::Utc::now() - chrono::Duration::days(10)).to_rfc3339();
        assert!(policy.validate_timestamp(&recent, "Test").is_ok());

        // 40 days ago (exceeds limit)
        let old = (chrono::Utc::now() - chrono::Duration::days(40)).to_rfc3339();
        let result = policy.validate_timestamp(&old, "Test");

        assert!(result.is_err());
        assert!(result.unwrap_err().contains("too old"));
    }

    #[test]
    fn test_timestamp_policy_optional_missing_required() {
        let policy = TimestampPolicy::new().require_timestamps(true);

        let result = policy.validate_optional_timestamp(None, "Test");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("required but missing"));
    }

    #[test]
    fn test_timestamp_policy_optional_missing_allowed() {
        let policy = TimestampPolicy::new().require_timestamps(false);

        assert!(policy.validate_optional_timestamp(None, "Test").is_ok());
    }

    #[test]
    fn test_timestamp_policy_optional_present() {
        let policy = TimestampPolicy::new();
        let now = chrono::Utc::now().to_rfc3339();

        assert!(
            policy
                .validate_optional_timestamp(Some(&now), "Test")
                .is_ok()
        );
    }

    #[test]
    fn test_timestamp_policy_invalid_format() {
        let policy = TimestampPolicy::new();

        let result = policy.validate_timestamp("not-a-timestamp", "Test");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Invalid timestamp format"));
    }

    #[test]
    fn test_validate_manifest_timestamps() {
        let policy = TimestampPolicy::new();
        let now = chrono::Utc::now().to_rfc3339();

        let manifest = CompositionManifest {
            version: "1.0".to_string(),
            tool: "wac".to_string(),
            tool_version: "0.5.0".to_string(),
            timestamp: now.clone(),
            components: vec![],
            integrator: Some(IntegratorInfo {
                identity: "test@example.com".to_string(),
                signature_index: 0,
                verification_timestamp: now,
            }),
            metadata: HashMap::new(),
        };

        assert!(validate_manifest_timestamps(&manifest, &policy).is_ok());
    }

    #[test]
    fn test_validate_manifest_timestamps_old() {
        let policy = TimestampPolicy::new().with_max_age_days(1);

        let old_time = (chrono::Utc::now() - chrono::Duration::days(10)).to_rfc3339();

        let manifest = CompositionManifest {
            version: "1.0".to_string(),
            tool: "wac".to_string(),
            tool_version: "0.5.0".to_string(),
            timestamp: old_time,
            components: vec![],
            integrator: None,
            metadata: HashMap::new(),
        };

        let result = validate_manifest_timestamps(&manifest, &policy);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("too old"));
    }

    #[test]
    fn test_validate_provenance_timestamps() {
        let policy = TimestampPolicy::new();
        let now = chrono::Utc::now().to_rfc3339();

        let provenance = BuildProvenance {
            name: "test-component".to_string(),
            version: "1.0.0".to_string(),
            source_repo: None,
            commit_sha: None,
            build_tool: "cargo".to_string(),
            build_tool_version: "1.75.0".to_string(),
            builder: None,
            build_timestamp: now,
            metadata: HashMap::new(),
        };

        assert!(validate_provenance_timestamps(&provenance, &policy).is_ok());
    }

    // ========================================================================
    // Phase 4: Signature Freshness Tests
    // ========================================================================

    #[test]
    fn test_signature_freshness_no_restrictions() {
        let policy = SignatureFreshnessPolicy::new();
        let now = chrono::Utc::now().to_rfc3339();

        assert!(policy.validate(&now, "Signature").is_ok());
    }

    #[test]
    fn test_signature_freshness_max_age() {
        let policy = SignatureFreshnessPolicy::new().with_max_age_days(30);

        // 10 days old (OK)
        let recent = (chrono::Utc::now() - chrono::Duration::days(10)).to_rfc3339();
        assert!(policy.validate(&recent, "Signature").is_ok());

        // 40 days old (too old)
        let old = (chrono::Utc::now() - chrono::Duration::days(40)).to_rfc3339();
        let result = policy.validate(&old, "Signature");

        assert!(result.is_err());
        assert!(result.unwrap_err().contains("too old"));
    }

    #[test]
    fn test_signature_freshness_minimum_timestamp() {
        let cutoff = chrono::Utc::now() - chrono::Duration::days(7);
        let policy = SignatureFreshnessPolicy::new().with_minimum_timestamp(cutoff);

        // 3 days ago (after cutoff, OK)
        let recent = (chrono::Utc::now() - chrono::Duration::days(3)).to_rfc3339();
        assert!(policy.validate(&recent, "Signature").is_ok());

        // 10 days ago (before cutoff, fail)
        let old = (chrono::Utc::now() - chrono::Duration::days(10)).to_rfc3339();
        let result = policy.validate(&old, "Signature");

        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .contains("before minimum acceptable time")
        );
    }

    #[test]
    fn test_signature_freshness_combined_policies() {
        let cutoff = chrono::Utc::now() - chrono::Duration::days(60);
        let policy = SignatureFreshnessPolicy::new()
            .with_max_age_days(30)
            .with_minimum_timestamp(cutoff);

        // 15 days ago (within max age and after cutoff, OK)
        let valid = (chrono::Utc::now() - chrono::Duration::days(15)).to_rfc3339();
        assert!(policy.validate(&valid, "Signature").is_ok());

        // 45 days ago (exceeds max age but after cutoff, fail)
        let too_old = (chrono::Utc::now() - chrono::Duration::days(45)).to_rfc3339();
        assert!(policy.validate(&too_old, "Signature").is_err());

        // 90 days ago (before cutoff, fail)
        let before_cutoff = (chrono::Utc::now() - chrono::Duration::days(90)).to_rfc3339();
        assert!(policy.validate(&before_cutoff, "Signature").is_err());
    }

    // ========================================================================
    // Phase 4: Certificate Validity Tests
    // ========================================================================

    #[test]
    fn test_certificate_validity_policy_valid() {
        let policy = CertificateValidityPolicy::new();

        let not_before = (chrono::Utc::now() - chrono::Duration::days(30)).to_rfc3339();
        let not_after = (chrono::Utc::now() + chrono::Duration::days(30)).to_rfc3339();

        assert!(
            policy
                .validate_certificate_times(&not_before, &not_after, "Test")
                .is_ok()
        );
    }

    #[test]
    fn test_certificate_validity_policy_expired() {
        let policy = CertificateValidityPolicy::new();

        let not_before = (chrono::Utc::now() - chrono::Duration::days(60)).to_rfc3339();
        let not_after = (chrono::Utc::now() - chrono::Duration::days(1)).to_rfc3339();

        let result = policy.validate_certificate_times(&not_before, &not_after, "Test");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("expired"));
    }

    #[test]
    fn test_certificate_validity_policy_not_yet_valid() {
        let policy = CertificateValidityPolicy::new();

        let not_before = (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339();
        let not_after = (chrono::Utc::now() + chrono::Duration::days(30)).to_rfc3339();

        let result = policy.validate_certificate_times(&not_before, &not_after, "Test");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("not yet valid"));
    }

    #[test]
    fn test_certificate_validity_policy_not_yet_valid_allowed() {
        let policy = CertificateValidityPolicy::new().allow_not_yet_valid(true);

        let not_before = (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339();
        let not_after = (chrono::Utc::now() + chrono::Duration::days(30)).to_rfc3339();

        assert!(
            policy
                .validate_certificate_times(&not_before, &not_after, "Test")
                .is_ok()
        );
    }

    #[test]
    fn test_certificate_validity_policy_min_remaining() {
        let policy = CertificateValidityPolicy::new().with_min_remaining_validity_days(10);

        // 20 days remaining (OK)
        let not_before = (chrono::Utc::now() - chrono::Duration::days(10)).to_rfc3339();
        let not_after = (chrono::Utc::now() + chrono::Duration::days(20)).to_rfc3339();
        assert!(
            policy
                .validate_certificate_times(&not_before, &not_after, "Test")
                .is_ok()
        );

        // 5 days remaining (too soon)
        let not_before2 = (chrono::Utc::now() - chrono::Duration::days(10)).to_rfc3339();
        let not_after2 = (chrono::Utc::now() + chrono::Duration::days(5)).to_rfc3339();
        let result = policy.validate_certificate_times(&not_before2, &not_after2, "Test");

        assert!(result.is_err());
        assert!(result.unwrap_err().contains("expires too soon"));
    }

    #[test]
    fn test_timestamp_validation_config_integration() {
        let policy = TimestampPolicy::new().with_max_age_days(30);

        let config = ValidationConfig::lenient().with_timestamp_policy(policy);

        assert!(config.timestamp_policy.is_some());
    }

    #[test]
    fn test_timestamp_validation_strict_mode() {
        let policy = TimestampPolicy::new().with_max_age_days(7);

        let config = ValidationConfig::strict().with_timestamp_policy(policy);

        assert_eq!(config.mode, ValidationMode::Strict);
        assert!(config.timestamp_policy.is_some());
    }

    // ========================================================================
    // Phase 5: Hardware Attestation Tests
    // ========================================================================

    #[test]
    fn test_device_attestation_creation() {
        let attestation = DeviceAttestation::new("device-12345", "SecureElement", "ATECC608");

        assert_eq!(attestation.device_id, "device-12345");
        assert_eq!(attestation.attestation_type, "SecureElement");
        assert_eq!(attestation.hardware_model, "ATECC608");
        assert!(!attestation.timestamp.is_empty());
    }

    #[test]
    fn test_device_attestation_with_data() {
        let test_data = b"attestation_data_here";
        let attestation =
            DeviceAttestation::new("device-1", "TPM", "TPM2.0").with_attestation_data(test_data);

        let decoded = base64::engine::general_purpose::STANDARD
            .decode(&attestation.attestation_data)
            .unwrap();
        assert_eq!(decoded, test_data);
    }

    #[test]
    fn test_device_attestation_with_signature() {
        let signature = b"signature_bytes";
        let attestation =
            DeviceAttestation::new("device-1", "SGX", "SGX-Enabled").with_signature(signature);

        assert!(attestation.attestation_signature.is_some());
        let decoded = base64::engine::general_purpose::STANDARD
            .decode(attestation.attestation_signature.as_ref().unwrap())
            .unwrap();
        assert_eq!(decoded, signature);
    }

    #[test]
    fn test_device_attestation_with_public_key() {
        let pubkey = b"public_key_bytes_here_32_bytes!";
        let attestation =
            DeviceAttestation::new("device-1", "SecureElement", "ATECC608").with_public_key(pubkey);

        let decoded = base64::engine::general_purpose::STANDARD
            .decode(&attestation.device_public_key)
            .unwrap();
        assert_eq!(decoded, pubkey);
    }

    #[test]
    fn test_device_attestation_with_metadata() {
        let attestation = DeviceAttestation::new("device-1", "TrustZone", "ARMv8")
            .add_metadata("firmware_version", "1.2.3")
            .add_metadata("boot_time", "2025-11-15T10:00:00Z");

        assert_eq!(
            attestation.metadata.get("firmware_version"),
            Some(&"1.2.3".to_string())
        );
        assert_eq!(
            attestation.metadata.get("boot_time"),
            Some(&"2025-11-15T10:00:00Z".to_string())
        );
    }

    #[test]
    fn test_device_attestation_serialization() {
        let attestation = DeviceAttestation::new("device-1", "SecureElement", "ATECC608")
            .with_attestation_data(b"test_data")
            .with_public_key(b"public_key");

        let json = attestation.to_json().unwrap();
        let deserialized = DeviceAttestation::from_json(&json).unwrap();

        assert_eq!(deserialized.device_id, attestation.device_id);
        assert_eq!(deserialized.hardware_model, attestation.hardware_model);
        assert_eq!(deserialized.attestation_data, attestation.attestation_data);
    }

    #[test]
    fn test_hardware_composition_manifest() {
        let base_manifest = CompositionManifest::new("wac", "0.5.0");
        let hw_manifest =
            HardwareCompositionManifest::from_manifest(base_manifest).with_security_level(4);

        assert_eq!(hw_manifest.security_level, 4);
        assert!(hw_manifest.device_attestation.is_none());
    }

    #[test]
    fn test_hardware_composition_manifest_with_attestation() {
        let base_manifest = CompositionManifest::new("wac", "0.5.0");
        let attestation = DeviceAttestation::new("device-1", "ATECC608", "SecureElement");

        let hw_manifest = HardwareCompositionManifest::from_manifest(base_manifest)
            .with_device_attestation(attestation)
            .with_security_level(4);

        assert!(hw_manifest.device_attestation.is_some());
        assert_eq!(hw_manifest.security_level, 4);
    }

    #[test]
    fn test_hardware_composition_manifest_security_level_cap() {
        let base_manifest = CompositionManifest::new("wac", "0.5.0");
        let hw_manifest =
            HardwareCompositionManifest::from_manifest(base_manifest).with_security_level(10); // Try to set level 10

        assert_eq!(hw_manifest.security_level, 4); // Should cap at 4
    }

    #[test]
    fn test_transparency_log_entry_creation() {
        let entry = TransparencyLogEntry::new(12345, "uuid-abcd-1234");

        assert_eq!(entry.log_index, 12345);
        assert_eq!(entry.uuid, "uuid-abcd-1234");
        assert!(entry.body.is_empty());
        assert!(entry.inclusion_proof.is_none());
    }

    #[test]
    fn test_transparency_log_entry_with_body() {
        let body_data = b"log_entry_body_data";
        let entry = TransparencyLogEntry::new(100, "uuid-test").with_body(body_data);

        let decoded = base64::engine::general_purpose::STANDARD
            .decode(&entry.body)
            .unwrap();
        assert_eq!(decoded, body_data);
    }

    #[test]
    fn test_transparency_log_entry_with_proof() {
        let proof = InclusionProof {
            tree_size: 1000,
            root_hash: "abcd1234".to_string(),
            hashes: vec!["hash1".to_string(), "hash2".to_string()],
            log_index: 100,
        };

        let entry = TransparencyLogEntry::new(100, "uuid-test").with_inclusion_proof(proof.clone());

        assert!(entry.inclusion_proof.is_some());
        let included_proof = entry.inclusion_proof.unwrap();
        assert_eq!(included_proof.tree_size, 1000);
        assert_eq!(included_proof.log_index, 100);
        assert_eq!(included_proof.hashes.len(), 2);
    }

    #[test]
    fn test_transparency_log_entry_serialization() {
        let entry = TransparencyLogEntry::new(123, "uuid-456").with_body(b"test_body");

        let json = entry.to_json().unwrap();
        let deserialized = TransparencyLogEntry::from_json(&json).unwrap();

        assert_eq!(deserialized.log_index, entry.log_index);
        assert_eq!(deserialized.uuid, entry.uuid);
        assert_eq!(deserialized.body, entry.body);
    }

    #[test]
    fn test_embed_and_extract_device_attestation() {
        let module = Module::default();
        let attestation = DeviceAttestation::new("device-test", "ATECC608", "SecureElement")
            .with_attestation_data(b"test_data");

        let module_with_attestation = embed_device_attestation(module, &attestation).unwrap();
        let extracted = extract_device_attestation(&module_with_attestation).unwrap();

        assert!(extracted.is_some());
        let extracted_attestation = extracted.unwrap();
        assert_eq!(extracted_attestation.device_id, "device-test");
        assert_eq!(extracted_attestation.hardware_model, "SecureElement");
    }

    #[test]
    fn test_extract_device_attestation_none() {
        let module = Module::default();
        let extracted = extract_device_attestation(&module).unwrap();

        assert!(extracted.is_none());
    }

    #[test]
    fn test_embed_and_extract_transparency_log() {
        let module = Module::default();
        let entry = TransparencyLogEntry::new(999, "uuid-transparency").with_body(b"log_data");

        let module_with_log = embed_transparency_log_entry(module, &entry).unwrap();
        let extracted = extract_transparency_log_entry(&module_with_log).unwrap();

        assert!(extracted.is_some());
        let extracted_entry = extracted.unwrap();
        assert_eq!(extracted_entry.log_index, 999);
        assert_eq!(extracted_entry.uuid, "uuid-transparency");
    }

    #[test]
    fn test_extract_transparency_log_none() {
        let module = Module::default();
        let extracted = extract_transparency_log_entry(&module).unwrap();

        assert!(extracted.is_none());
    }

    #[test]
    fn test_validate_device_attestation_valid() {
        let attestation = DeviceAttestation::new("device-1", "ATECC608", "SecureElement")
            .with_public_key(b"pubkey");

        let result = validate_device_attestation(&attestation, None);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_device_attestation_missing_device_id() {
        let mut attestation = DeviceAttestation::new("device-1", "ATECC608", "SecureElement");
        attestation.device_id = String::new();
        attestation.device_public_key = "key".to_string();

        let result = validate_device_attestation(&attestation, None);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Device ID is required"));
    }

    #[test]
    fn test_validate_device_attestation_missing_public_key() {
        let attestation = DeviceAttestation::new("device-1", "ATECC608", "SecureElement");
        // device_public_key is empty by default until with_public_key is called

        let result = validate_device_attestation(&attestation, None);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("public key is required"));
    }

    #[test]
    fn test_validate_device_attestation_device_id_mismatch() {
        let attestation =
            DeviceAttestation::new("device-1", "ATECC608", "SecureElement").with_public_key(b"key");

        let result = validate_device_attestation(&attestation, Some("device-2"));
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Device ID mismatch"));
    }

    #[test]
    fn test_validate_device_attestation_device_id_match() {
        let attestation =
            DeviceAttestation::new("device-1", "ATECC608", "SecureElement").with_public_key(b"key");

        let result = validate_device_attestation(&attestation, Some("device-1"));
        assert!(result.is_ok());
    }

    #[test]
    fn test_multiple_provenance_types_embedded() {
        let module = Module::default();

        // Add composition manifest
        let manifest = CompositionManifest::new("wac", "0.5.0");
        let module = embed_composition_manifest(module, &manifest).unwrap();

        // Add device attestation
        let attestation =
            DeviceAttestation::new("device-1", "ATECC608", "SecureElement").with_public_key(b"key");
        let module = embed_device_attestation(module, &attestation).unwrap();

        // Add transparency log
        let log_entry = TransparencyLogEntry::new(100, "uuid-test");
        let module = embed_transparency_log_entry(module, &log_entry).unwrap();

        // Extract all
        let extracted_manifest = extract_composition_manifest(&module).unwrap();
        let extracted_attestation = extract_device_attestation(&module).unwrap();
        let extracted_log = extract_transparency_log_entry(&module).unwrap();

        assert!(extracted_manifest.is_some());
        assert!(extracted_attestation.is_some());
        assert!(extracted_log.is_some());
    }

    #[test]
    fn test_hardware_composition_manifest_serialization() {
        let base_manifest = CompositionManifest::new("wac", "0.5.0");
        let attestation = DeviceAttestation::new("device-1", "ATECC608", "SecureElement")
            .with_public_key(b"test_key");

        let hw_manifest = HardwareCompositionManifest::from_manifest(base_manifest)
            .with_device_attestation(attestation)
            .with_security_level(4);

        let json = hw_manifest.to_json().unwrap();
        let deserialized = HardwareCompositionManifest::from_json(&json).unwrap();

        assert_eq!(deserialized.security_level, 4);
        assert!(deserialized.device_attestation.is_some());
        assert_eq!(
            deserialized.device_attestation.as_ref().unwrap().device_id,
            "device-1"
        );
    }

    #[test]
    fn test_verify_attestation_signature_unsigned() {
        // Create an unsigned attestation
        let attestation = TransformationAttestationBuilder::new_optimization("loom", "0.1.0")
            .add_input_unsigned(b"test input", "input.wasm")
            .build(b"test output", "output.wasm");

        // Verify that unsigned attestation returns Unsigned
        let result = verify_attestation_signature(&attestation, &[]);
        assert!(matches!(result, AttestationSignatureResult::Unsigned));
    }

    #[test]
    fn test_trusted_public_key_creation() {
        let pk = TrustedPublicKey::ed25519("AAAA", Some("test-key".to_string()));
        assert_eq!(pk.algorithm, "ed25519");
        assert_eq!(pk.key, "AAAA");
        assert_eq!(pk.key_id, Some("test-key".to_string()));
    }

    #[test]
    fn test_trusted_tool_info_with_public_key() {
        let info = TrustedToolInfo::min_version("0.1.0")
            .with_public_key(TrustedPublicKey::ed25519("key1", Some("id1".to_string())))
            .with_public_key(TrustedPublicKey::ed25519("key2", None));

        assert_eq!(info.min_version, Some("0.1.0".to_string()));
        assert_eq!(info.public_keys.len(), 2);
        assert_eq!(info.public_keys[0].key, "key1");
        assert_eq!(info.public_keys[1].key, "key2");
    }

    #[test]
    fn test_chain_verification_with_attestation_signatures_unsigned() {
        // Create an unsigned attestation
        let attestation = TransformationAttestationBuilder::new_optimization("loom", "0.1.0")
            .add_input_unsigned(b"test input", "input.wasm")
            .build(b"test output", "output.wasm");

        // Create a policy requiring attestation signatures
        let mut policy = ChainVerificationPolicy::default();
        policy.mode = ChainVerificationMode::NoRootSignaturesRequired;
        policy.verify_attestation_signatures = true;
        policy.trusted_tools.insert(
            "loom".to_string(),
            TrustedToolInfo::min_version("0.1.0")
                .with_public_key(TrustedPublicKey::ed25519("dummy", None)),
        );

        // Verify should fail because attestation is unsigned
        let result = verify_transformation_chain(&attestation, &policy);
        assert!(!result.valid);
        assert!(result.errors.iter().any(|e| e.contains("unsigned")));
    }

    #[test]
    fn test_chain_verification_without_signature_requirement() {
        // Create an unsigned attestation
        let attestation = TransformationAttestationBuilder::new_optimization("loom", "0.1.0")
            .add_input_unsigned(b"test input", "input.wasm")
            .build(b"test output", "output.wasm");

        // Create a policy NOT requiring attestation signatures
        let mut policy = ChainVerificationPolicy::default();
        policy.mode = ChainVerificationMode::NoRootSignaturesRequired;
        policy.verify_attestation_signatures = false;
        policy.trusted_tools.insert(
            "loom".to_string(),
            TrustedToolInfo::min_version("0.1.0"),
        );

        // Verify should pass because signature verification is disabled
        let result = verify_transformation_chain(&attestation, &policy);
        assert!(result.valid);
    }

    #[test]
    fn test_keyless_verification_config() {
        let config = KeylessVerificationConfig {
            oidc_issuers: vec!["https://token.actions.githubusercontent.com".to_string()],
            allowed_subjects: vec!["https://github.com/org/repo/*".to_string()],
        };

        let info = TrustedToolInfo::min_version("0.1.0").with_keyless(config);
        assert!(info.keyless.is_some());
        let kl = info.keyless.unwrap();
        assert_eq!(kl.oidc_issuers.len(), 1);
        assert_eq!(kl.allowed_subjects.len(), 1);
    }
}