vta-service 0.10.0

Service for Verifiable Trust Agents operating in Verifiable Trust Communities
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
//! Integration tests for the VTA REST API.
//!
//! Spins up the axum router with a temp fjall store and tests endpoints
//! with real HTTP requests. JWT tokens are created programmatically and
//! sessions are pre-inserted to bypass the DIDComm challenge-response flow.

use std::sync::Arc;

use axum::body::Body;
use axum::http::{Request, StatusCode};
use http_body_util::BodyExt;
use serde_json::{Value, json};
use tower::ServiceExt;

use vti_common::acl::Role;
use vti_common::auth::jwt::JwtKeys;
use vti_common::auth::session::{Session, SessionState, store_session};

use vta_service::store::KeyspaceHandle;
use vta_service::test_support::{TestAppContext, build_test_app};

// ── Test harness — thin wrapper over the workspace's `test_support`
// `build_test_app` helper. The substantial AppState wiring (every
// keyspace, the JWT keys, the DID resolver, the registry, the drain
// sweeper, etc.) was duplicated here pre-consolidation; it now lives
// in `vta_service::test_support` so any future integration test gets
// it for free with two lines of setup.

struct TestApp {
    router: axum::Router,
}

impl TestApp {
    async fn new() -> (Self, TestContext) {
        let (router, ctx) = build_test_app().await;
        (Self { router }, TestContext { inner: ctx })
    }

    async fn request(&self, req: Request<Body>) -> (StatusCode, Value) {
        let resp = self
            .router
            .clone()
            .oneshot(req)
            .await
            .expect("request failed");
        let status = resp.status();
        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let json: Value = serde_json::from_slice(&body)
            .unwrap_or_else(|_| json!({"raw": String::from_utf8_lossy(&body).to_string()}));
        (status, json)
    }
}

struct TestContext {
    inner: TestAppContext,
}

impl TestContext {
    fn jwt_keys(&self) -> &Arc<JwtKeys> {
        &self.inner.jwt_keys
    }

    fn sessions_ks(&self) -> &KeyspaceHandle {
        &self.inner.sessions_ks
    }

    #[allow(dead_code)]
    fn acl_ks(&self) -> &KeyspaceHandle {
        &self.inner.acl_ks
    }

    /// Turn on the AAL2 step-up policy for every operation. The shipping
    /// default is disabled (AAL1 everywhere); tests that assert the gate
    /// fires opt in here, mirroring an operator enabling step-up with a `*`
    /// floor. The config Arc is shared with the live router, so this takes
    /// effect for subsequent requests.
    async fn enable_step_up_all(&self) {
        use vti_common::auth::step_up::{StepUpFloor, StepUpMode};
        self.set_step_up_floors(vec![StepUpFloor {
            operation: "*".into(),
            mode: StepUpMode::SelfApprove,
            allow_aal1_if_non_escalating: false,
        }])
        .await;
    }

    /// Enable the step-up policy with an explicit set of floors. The config
    /// Arc is shared with the live router, so this takes effect immediately.
    async fn set_step_up_floors(&self, floors: Vec<vti_common::auth::step_up::StepUpFloor>) {
        use vti_common::auth::step_up::StepUpPolicy;
        self.inner.config.write().await.auth.step_up = StepUpPolicy {
            enabled: true,
            floors,
        };
    }
}

impl TestContext {
    /// Create an authenticated session and return a Bearer token.
    async fn auth_token(&self, did: &str, role: &str, contexts: Vec<String>) -> String {
        let session_id = format!("sess-{}", uuid::Uuid::new_v4());
        let session = Session {
            session_id: session_id.clone(),
            did: did.to_string(),
            challenge: String::new(),
            state: SessionState::Authenticated,
            created_at: now_epoch(),
            refresh_token: None,
            refresh_expires_at: None,
            tee_attested: false,
            amr: Vec::new(),
            acr: String::new(),
            token_id: None,
            session_pubkey_b58btc: None,
        };
        store_session(self.sessions_ks(), &session)
            .await
            .expect("store session");

        let claims = self.jwt_keys().new_claims(
            did.to_string(),
            session_id,
            role.to_string(),
            contexts,
            900,
            false,
        );
        self.jwt_keys().encode(&claims).expect("encode jwt")
    }

    /// Like [`auth_token`], but the session is **stepped-up (AAL2)** — the JWT
    /// carries `acr=aal2` and a second factor in `amr`. Required for endpoints
    /// gated by `RequireStepUp` (ACL mutations, context/key deletion). A plain
    /// `auth_token` is AAL1, which those endpoints reject with a step-up `403`.
    async fn auth_token_aal2(&self, did: &str, role: &str, contexts: Vec<String>) -> String {
        let session_id = format!("sess-{}", uuid::Uuid::new_v4());
        let session = Session {
            session_id: session_id.clone(),
            did: did.to_string(),
            challenge: String::new(),
            state: SessionState::Authenticated,
            created_at: now_epoch(),
            refresh_token: None,
            refresh_expires_at: None,
            tee_attested: false,
            amr: vec!["did".into(), "passkey".into()],
            acr: "aal2".into(),
            token_id: None,
            session_pubkey_b58btc: None,
        };
        store_session(self.sessions_ks(), &session)
            .await
            .expect("store session");

        let claims = self
            .jwt_keys()
            .new_claims(
                did.to_string(),
                session_id,
                role.to_string(),
                contexts,
                900,
                false,
            )
            .with_aal(vec!["did".into(), "passkey".into()], "aal2");
        self.jwt_keys().encode(&claims).expect("encode jwt")
    }

    /// Mint a token signed with a different audience. Used to verify
    /// audience-isolation rejection — a VTC-audience token must not
    /// authenticate against a VTA route. CLAUDE.md guards this as a
    /// load-bearing invariant; tested at the JWT layer in vti-common
    /// but here through the full route stack.
    #[allow(dead_code)]
    fn auth_token_with_audience(
        &self,
        did: &str,
        role: &str,
        contexts: Vec<String>,
        audience: &str,
    ) -> String {
        // Use a fresh JwtKeys with the specified audience — this is what
        // a VTC instance issuing tokens for its own audience would do.
        let foreign_keys = JwtKeys::from_ed25519_bytes(&[0x42u8; 32], audience).unwrap();
        let claims = foreign_keys.new_claims(
            did.to_string(),
            format!("sess-{}", uuid::Uuid::new_v4()),
            role.to_string(),
            contexts,
            900,
            false,
        );
        foreign_keys.encode(&claims).expect("encode foreign jwt")
    }

    /// Create an ACL entry for a DID.
    #[allow(dead_code)]
    async fn create_acl(&self, did: &str, role: Role, contexts: Vec<String>) {
        let entry = vti_common::acl::AclEntry::new(did, role, "test").with_contexts(contexts);
        self.acl_ks()
            .insert(format!("acl:{did}"), &entry)
            .await
            .expect("insert acl");
    }
}

fn now_epoch() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs()
}

fn get(uri: &str) -> Request<Body> {
    Request::builder()
        .method("GET")
        .uri(uri)
        .body(Body::empty())
        .unwrap()
}

fn get_auth(uri: &str, token: &str) -> Request<Body> {
    Request::builder()
        .method("GET")
        .uri(uri)
        .header("Authorization", format!("Bearer {token}"))
        .body(Body::empty())
        .unwrap()
}

fn post_auth(uri: &str, token: &str, body: Value) -> Request<Body> {
    Request::builder()
        .method("POST")
        .uri(uri)
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/json")
        .body(Body::from(serde_json::to_vec(&body).unwrap()))
        .unwrap()
}

fn patch_auth(uri: &str, token: &str, body: Value) -> Request<Body> {
    Request::builder()
        .method("PATCH")
        .uri(uri)
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/json")
        .body(Body::from(serde_json::to_vec(&body).unwrap()))
        .unwrap()
}

fn put_auth(uri: &str, token: &str, body: Value) -> Request<Body> {
    Request::builder()
        .method("PUT")
        .uri(uri)
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/json")
        .body(Body::from(serde_json::to_vec(&body).unwrap()))
        .unwrap()
}

fn delete_auth(uri: &str, token: &str) -> Request<Body> {
    Request::builder()
        .method("DELETE")
        .uri(uri)
        .header("Authorization", format!("Bearer {token}"))
        .body(Body::empty())
        .unwrap()
}

// ── Capabilities ──────────────────────────────────────────────────

#[tokio::test]
async fn capabilities_requires_auth() {
    let (app, _ctx) = TestApp::new().await;
    let (status, _) = app.request(get("/capabilities")).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn capabilities_returns_features() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx
        .auth_token("did:key:z6MkReader", "reader", vec!["any".into()])
        .await;
    let (status, body) = app.request(get_auth("/capabilities", &token)).await;
    assert_eq!(status, StatusCode::OK);
    assert!(body["version"].as_str().is_some());
    assert!(body["features"].is_object());
    assert!(body["services"].is_object());
    assert!(body["did_creation_modes"].is_array());
    // webvh feature is compiled in for tests
    assert_eq!(body["features"]["webvh"], true);
}

// ── Health ─────────────────────────────────────────────────────────

#[tokio::test]
async fn health_returns_ok_without_auth() {
    let (app, _ctx) = TestApp::new().await;
    let (status, body) = app.request(get("/health")).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["status"], "ok");
}

#[tokio::test]
async fn health_details_requires_auth() {
    let (app, _ctx) = TestApp::new().await;
    let (status, _) = app.request(get("/health/details")).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn health_details_returns_version_with_auth() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkTest", "admin", vec![]).await;
    let (status, body) = app.request(get_auth("/health/details", &token)).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["status"], "ok");
    assert!(body["version"].is_string());
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn didcomm_status_requires_auth() {
    let (app, _ctx) = TestApp::new().await;
    let (status, _) = app.request(get("/services/didcomm")).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn didcomm_status_forbids_non_super_admin() {
    // Parity with `GET /services` (list_services): both are super-admin-gated
    // since they expose the same `mediator_did`. A reader-role caller is rejected.
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkTest", "reader", vec![]).await;
    let (status, _) = app.request(get_auth("/services/didcomm", &token)).await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn didcomm_status_returns_disabled_when_not_enabled() {
    let (app, ctx) = TestApp::new().await;
    ctx.inner.config.write().await.services.didcomm = false;
    // admin + empty contexts == super-admin
    let token = ctx.auth_token("did:key:z6MkTest", "admin", vec![]).await;
    let (status, body) = app.request(get_auth("/services/didcomm", &token)).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body, json!({ "enabled": false }));
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn didcomm_status_returns_mediator_and_websocket_state_when_enabled() {
    let (app, ctx) = TestApp::new().await;
    {
        let mut config = ctx.inner.config.write().await;
        config.services.didcomm = true;
        config.messaging = Some(vti_common::config::MessagingConfig {
            mediator_url: "wss://mediator.example.com".into(),
            mediator_did: "did:peer:2.med".into(),
            mediator_host: None,
        });
    }
    let token = ctx.auth_token("did:key:z6MkTest", "admin", vec![]).await;
    let (status, body) = app.request(get_auth("/services/didcomm", &token)).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["enabled"], true);
    assert_eq!(body["mediator_did"], "did:peer:2.med");
    assert_eq!(body["websocket_status"], "disconnected");
}

// ── Auth: missing/invalid token ────────────────────────────────────

#[tokio::test]
async fn missing_token_returns_401() {
    let (app, _ctx) = TestApp::new().await;
    let (status, _) = app.request(get("/config")).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn invalid_token_returns_401() {
    let (app, _ctx) = TestApp::new().await;
    let (status, _) = app.request(get_auth("/config", "not-a-jwt")).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn expired_session_returns_401() {
    let (app, ctx) = TestApp::new().await;
    // Create a token with a valid JWT but no session in the store
    let claims = ctx.jwt_keys().new_claims(
        "did:key:z6MkGhost".into(),
        "nonexistent-session".into(),
        "admin".into(),
        vec![],
        900,
        false,
    );
    let token = ctx.jwt_keys().encode(&claims).unwrap();
    let (status, _) = app.request(get_auth("/config", &token)).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

// ── Role enforcement ───────────────────────────────────────────────

#[tokio::test]
async fn application_role_cannot_access_admin_endpoints() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx
        .auth_token("did:key:z6MkApp", "application", vec!["ctx1".into()])
        .await;
    // POST /keys requires admin
    let (status, _) = app
        .request(post_auth(
            "/keys",
            &token,
            json!({"key_type": "ed25519", "context_id": "ctx1"}),
        ))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn initiator_cannot_access_super_admin_endpoints() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx
        .auth_token("did:key:z6MkInit", "initiator", vec![])
        .await;
    // PATCH /config requires super admin
    let (status, _) = app
        .request(patch_auth("/config", &token, json!({"vta_name": "hacked"})))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn admin_can_read_config() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;
    let (status, body) = app.request(get_auth("/config", &token)).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["vta_did"], "did:key:z6MkTestVTA");
}

#[tokio::test]
async fn super_admin_can_update_config() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;
    let (status, body) = app
        .request(patch_auth(
            "/config",
            &token,
            json!({"vta_name": "Updated Name"}),
        ))
        .await;
    assert!(status.is_success(), "update config: {status} {body}");
    assert_eq!(body["vta_name"], "Updated Name");
}

#[tokio::test]
async fn scoped_admin_cannot_update_config() {
    let (app, ctx) = TestApp::new().await;
    // Admin with allowed_contexts is NOT super admin
    let token = ctx
        .auth_token("did:key:z6MkScoped", "admin", vec!["ctx1".into()])
        .await;
    let (status, _) = app
        .request(patch_auth("/config", &token, json!({"vta_name": "nope"})))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

// ── ACL CRUD ───────────────────────────────────────────────────────

#[tokio::test]
async fn acl_create_and_list() {
    let (app, ctx) = TestApp::new().await;
    // ACL creation is an AAL2-gated mutation.
    let token = ctx
        .auth_token_aal2("did:key:z6MkAdmin", "admin", vec![])
        .await;

    // Create
    let (status, body) = app
        .request(post_auth(
            "/acl",
            &token,
            json!({
                "did": "did:key:z6MkNew",
                "role": "application",
                "label": "test app",
                "allowed_contexts": ["ctx1"]
            }),
        ))
        .await;
    assert!(status.is_success(), "create: {body}");

    // List
    let (status, body) = app.request(get_auth("/acl", &token)).await;
    assert_eq!(status, StatusCode::OK);
    let entries = body["entries"].as_array().expect("entries array");
    assert!(
        entries.iter().any(|e| e["did"] == "did:key:z6MkNew"),
        "new entry should be in list"
    );
}

/// An AAL1 admin hitting an AAL2-gated mutation is rejected with the step-up
/// `403` that *carries the approve-request* — not a bare 403. The caller has
/// the right role (so this isn't a permission failure); it just hasn't stepped
/// up. Mirrors the operator policy: all ACL changes require AAL2.
#[tokio::test]
async fn acl_mutation_requires_step_up() {
    let (app, ctx) = TestApp::new().await;
    // Opt into step-up enforcement (shipping default is disabled).
    ctx.enable_step_up_all().await;
    // A normal (AAL1) admin session: correct role, but not stepped up.
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    let (status, body) = app
        .request(post_auth(
            "/acl",
            &token,
            json!({
                "did": "did:key:z6MkNew",
                "role": "application",
                "label": "test app",
                "allowed_contexts": ["ctx1"]
            }),
        ))
        .await;

    assert_eq!(status, StatusCode::FORBIDDEN, "AAL1 must be gated: {body}");
    assert_eq!(body["error"], "step_up_required");
    assert_eq!(body["requiredAcr"], "aal2");
    // The 403 carries the approve-request the caller hands to its approver.
    let ar = &body["approveRequest"];
    assert_eq!(
        ar["type"],
        "https://trusttasks.org/spec/auth/step-up/approve-request/0.1"
    );
    assert_eq!(ar["recipient"], "did:key:z6MkAdmin");
    assert_eq!(ar["payload"]["targetAcr"], "aal2");
    assert!(
        ar["payload"]["challenge"]
            .as_str()
            .is_some_and(|c| c.len() >= 16),
        "approve-request must carry a ≥16-char challenge"
    );
}

#[tokio::test]
async fn step_up_floor_is_per_operation_class() {
    use vti_common::auth::step_up::{StepUpFloor, StepUpMode};
    let (app, ctx) = TestApp::new().await;
    // Gate ONLY `context/delete` — no floor for `acl/grant`, no `*` catch-all.
    ctx.set_step_up_floors(vec![StepUpFloor {
        operation: "context/delete".into(),
        mode: StepUpMode::SelfApprove,
        allow_aal1_if_non_escalating: false,
    }])
    .await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    let (status, body) = app
        .request(post_auth(
            "/acl",
            &token,
            json!({
                "did": "did:key:z6MkUngated",
                "role": "application",
                "label": "ungated app",
                "allowed_contexts": ["ctx1"]
            }),
        ))
        .await;

    // The `acl/grant` route must NOT be step-up-gated by a context/delete-only
    // policy — op-class resolution is specific, not all-or-nothing.
    assert_ne!(
        body["error"], "step_up_required",
        "acl/grant gated by a context/delete-only floor: {status} {body}"
    );
}

#[tokio::test]
async fn swap_key_carve_out_admits_aal1_when_configured() {
    use vti_common::auth::step_up::{StepUpFloor, StepUpMode};
    let (app, ctx) = TestApp::new().await;
    // Gate swap-key at AAL2 but allow the non-escalating self-service carve-out.
    ctx.set_step_up_floors(vec![StepUpFloor {
        operation: "acl/swap-key".into(),
        mode: StepUpMode::SelfApprove,
        allow_aal1_if_non_escalating: true,
    }])
    .await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    let (_status, body) = app
        .request(post_auth(
            "/acl/swap",
            &token,
            json!({ "presentation": "not-a-real-vp" }),
        ))
        .await;

    // The carve-out admits the swap at AAL1, so it is NOT step-up-gated; it
    // fails later on the (invalid) presentation rather than on step-up.
    assert_ne!(
        body["error"], "step_up_required",
        "swap-key carve-out should admit AAL1: {body}"
    );
}

#[tokio::test]
async fn swap_key_gated_without_carve_out() {
    use vti_common::auth::step_up::{StepUpFloor, StepUpMode};
    let (app, ctx) = TestApp::new().await;
    // Same AAL2 floor but WITHOUT the carve-out → swap-key is gated.
    ctx.set_step_up_floors(vec![StepUpFloor {
        operation: "acl/swap-key".into(),
        mode: StepUpMode::SelfApprove,
        allow_aal1_if_non_escalating: false,
    }])
    .await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    let (status, body) = app
        .request(post_auth(
            "/acl/swap",
            &token,
            json!({ "presentation": "not-a-real-vp" }),
        ))
        .await;

    assert_eq!(
        status,
        StatusCode::FORBIDDEN,
        "swap-key must be gated: {body}"
    );
    assert_eq!(body["error"], "step_up_required");
}

#[tokio::test]
async fn acl_update_sets_step_up_approver() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;
    // Grant with no approver…
    let (status, _) = app
        .request(post_auth(
            "/acl",
            &token,
            json!({ "did": "did:key:z6MkGrantee2", "role": "application", "allowed_contexts": ["ctx1"] }),
        ))
        .await;
    assert!(status.is_success());

    // …then add one via PATCH.
    let (status, body) = app
        .request(patch_auth(
            "/acl/did:key:z6MkGrantee2",
            &token,
            json!({ "step_up_approver": "did:key:z6MkApprover" }),
        ))
        .await;
    assert!(
        status.is_success(),
        "update should succeed: {status} {body}"
    );
    assert_eq!(
        body["step_up_approver"], "did:key:z6MkApprover",
        "update must set + reflect the step-up approver: {body}"
    );
}

#[tokio::test]
async fn acl_grant_persists_step_up_approver() {
    let (app, ctx) = TestApp::new().await;
    // Step-up ships disabled, so an AAL1 admin can grant without a gate.
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    let (status, body) = app
        .request(post_auth(
            "/acl",
            &token,
            json!({
                "did": "did:key:z6MkGrantee",
                "role": "application",
                "allowed_contexts": ["ctx1"],
                "step_up_approver": "did:key:z6MkApprover"
            }),
        ))
        .await;

    assert!(status.is_success(), "grant should succeed: {status} {body}");
    // The configured approver round-trips through the create result.
    assert_eq!(
        body["step_up_approver"], "did:key:z6MkApprover",
        "grant must persist + reflect the step-up approver: {body}"
    );
}

#[tokio::test]
async fn delegated_step_up_routes_to_configured_approver() {
    use vti_common::acl::{AclEntry, Role, store_acl_entry};
    use vti_common::auth::step_up::{StepUpFloor, StepUpMode};
    let (app, ctx) = TestApp::new().await;
    let caller = "did:key:z6MkAdmin";
    let approver = "did:key:z6MkApprover";
    // The caller's ACL entry names its delegated approver.
    store_acl_entry(
        ctx.acl_ks(),
        &AclEntry::new(caller, Role::Admin, "test")
            .with_step_up_approver(Some(approver.to_string())),
    )
    .await
    .unwrap();
    ctx.set_step_up_floors(vec![StepUpFloor {
        operation: "acl/grant".into(),
        mode: StepUpMode::Delegated,
        allow_aal1_if_non_escalating: false,
    }])
    .await;
    let token = ctx.auth_token(caller, "admin", vec![]).await;

    let (status, body) = app
        .request(post_auth(
            "/acl",
            &token,
            json!({ "did": "did:key:z6MkNew", "role": "application", "allowed_contexts": ["ctx1"] }),
        ))
        .await;

    assert_eq!(status, StatusCode::FORBIDDEN, "{body}");
    assert_eq!(body["error"], "step_up_required");
    // The approve-request is addressed to the configured approver, not the caller.
    assert_eq!(
        body["approveRequest"]["recipient"], approver,
        "delegated approve-request must be addressed to the configured approver: {body}"
    );
}

#[tokio::test]
async fn delegated_step_up_without_approver_fails_closed() {
    use vti_common::acl::{AclEntry, Role, store_acl_entry};
    use vti_common::auth::step_up::{StepUpFloor, StepUpMode};
    let (app, ctx) = TestApp::new().await;
    let caller = "did:key:z6MkNoApprover";
    // ACL entry with NO step-up approver under a delegated floor.
    store_acl_entry(ctx.acl_ks(), &AclEntry::new(caller, Role::Admin, "test"))
        .await
        .unwrap();
    ctx.set_step_up_floors(vec![StepUpFloor {
        operation: "acl/grant".into(),
        mode: StepUpMode::Delegated,
        allow_aal1_if_non_escalating: false,
    }])
    .await;
    let token = ctx.auth_token(caller, "admin", vec![]).await;

    let (status, body) = app
        .request(post_auth(
            "/acl",
            &token,
            json!({ "did": "did:key:z6MkNew2", "role": "application", "allowed_contexts": ["ctx1"] }),
        ))
        .await;

    // Fail-closed: 403 with no approve-request (nothing the caller can do until
    // an operator registers an approver — the subject can't self-approve a
    // delegated requirement).
    assert_eq!(status, StatusCode::FORBIDDEN, "{body}");
    assert_eq!(body["error"], "step_up_required");
    assert!(
        body.get("approveRequest").is_none(),
        "fail-closed must not carry an approve-request: {body}"
    );
}

#[tokio::test]
async fn acl_application_cannot_manage() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx
        .auth_token("did:key:z6MkApp", "application", vec!["ctx1".into()])
        .await;
    let (status, _) = app.request(get_auth("/acl", &token)).await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

// ── Context CRUD ───────────────────────────────────────────────────

#[tokio::test]
async fn context_create_requires_super_admin() {
    let (app, ctx) = TestApp::new().await;

    // Scoped admin → forbidden
    let token = ctx
        .auth_token("did:key:z6MkScoped", "admin", vec!["ctx1".into()])
        .await;
    let (status, _) = app
        .request(post_auth(
            "/contexts",
            &token,
            json!({"id": "new-ctx", "name": "New Context"}),
        ))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);

    // Super admin → OK
    let token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;
    let (status, body) = app
        .request(post_auth(
            "/contexts",
            &token,
            json!({"id": "new-ctx", "name": "New Context"}),
        ))
        .await;
    assert!(status.is_success(), "create: {body}");
}

// ── Key management ─────────────────────────────────────────────────

#[tokio::test]
async fn key_create_and_list() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    // Create a context first (needed for key creation)
    let (status, _) = app
        .request(post_auth(
            "/contexts",
            &token,
            json!({"id": "test", "name": "Test Context"}),
        ))
        .await;
    assert!(status.is_success());

    // Create key
    let (status, body) = app
        .request(post_auth(
            "/keys",
            &token,
            json!({"key_type": "ed25519", "context_id": "test"}),
        ))
        .await;
    assert!(status.is_success(), "create key: {body}");
    assert!(body["key_id"].is_string());
    assert_eq!(body["key_type"], "ed25519");

    // List keys
    let (status, body) = app.request(get_auth("/keys", &token)).await;
    assert_eq!(status, StatusCode::OK);
    let keys = body["keys"].as_array().expect("keys array");
    assert!(!keys.is_empty(), "should have at least one key");
}

// ── Restart requires super admin ───────────────────────────────────

#[tokio::test]
async fn restart_requires_super_admin() {
    let (app, ctx) = TestApp::new().await;

    // Regular admin with contexts → forbidden
    let token = ctx
        .auth_token("did:key:z6MkScoped", "admin", vec!["ctx1".into()])
        .await;
    let (status, _) = app
        .request(post_auth("/vta/restart", &token, json!({})))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);

    // Initiator → forbidden
    let token = ctx
        .auth_token("did:key:z6MkInit", "initiator", vec![])
        .await;
    let (status, _) = app
        .request(post_auth("/vta/restart", &token, json!({})))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

// ── Backup requires super admin ────────────────────────────────────

#[tokio::test]
async fn backup_export_requires_super_admin() {
    let (app, ctx) = TestApp::new().await;

    // Scoped admin → forbidden
    let token = ctx
        .auth_token("did:key:z6MkScoped", "admin", vec!["ctx1".into()])
        .await;
    let (status, _) = app
        .request(post_auth(
            "/backup/export",
            &token,
            json!({"password": "test-password-12!!", "include_audit": false}),
        ))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn backup_export_rejects_short_password() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;
    let (status, body) = app
        .request(post_auth(
            "/backup/export",
            &token,
            json!({"password": "short", "include_audit": false}),
        ))
        .await;
    assert_eq!(
        status,
        StatusCode::BAD_REQUEST,
        "should reject short password: {body}"
    );
}

#[tokio::test]
async fn backup_export_and_import_preview() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;

    // Export
    let (status, envelope) = app
        .request(post_auth(
            "/backup/export",
            &token,
            json!({"password": "test-password-12!!", "include_audit": false}),
        ))
        .await;
    assert_eq!(status, StatusCode::OK, "export: {envelope}");
    assert_eq!(envelope["format"], "vta-backup-v1");

    // Import preview (confirm=false)
    let (status, preview) = app
        .request(post_auth(
            "/backup/import",
            &token,
            json!({
                "backup": envelope,
                "password": "test-password-12!!",
                "confirm": false
            }),
        ))
        .await;
    assert_eq!(status, StatusCode::OK, "preview: {preview}");
    assert_eq!(preview["status"], "preview");
}

// ── Cache ──────────────────────────────────────────────────────────

#[tokio::test]
async fn cache_put_get_delete() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    // PUT
    let req = Request::builder()
        .method("PUT")
        .uri("/cache/test-key")
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/json")
        .body(Body::from(r#"{"value":"hello","ttl_secs":60}"#))
        .unwrap();
    let (status, _) = app.request(req).await;
    assert!(status.is_success(), "PUT cache: {status}");

    // GET
    let (status, body) = app.request(get_auth("/cache/test-key", &token)).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["value"], "hello");

    // DELETE
    let (status, _) = app.request(delete_auth("/cache/test-key", &token)).await;
    assert!(status.is_success(), "DELETE cache: {status}");

    // GET again → 404
    let (status, _) = app.request(get_auth("/cache/test-key", &token)).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

// ── Audit ──────────────────────────────────────────────────────────

#[tokio::test]
async fn audit_list_requires_admin() {
    let (app, ctx) = TestApp::new().await;

    // Application → forbidden
    let token = ctx
        .auth_token("did:key:z6MkApp", "application", vec!["ctx1".into()])
        .await;
    let (status, _) = app.request(get_auth("/audit/logs", &token)).await;
    assert_eq!(status, StatusCode::FORBIDDEN);

    // Admin → OK
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;
    let (status, body) = app.request(get_auth("/audit/logs", &token)).await;
    assert_eq!(status, StatusCode::OK);
    assert!(body["entries"].is_array());
}

// ── Context scoping ────────────────────────────────────────────────

#[tokio::test]
async fn scoped_admin_can_only_access_own_context_keys() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;

    // Create two contexts
    app.request(post_auth(
        "/contexts",
        &super_token,
        json!({"id": "ctx-a", "name": "A"}),
    ))
    .await;
    app.request(post_auth(
        "/contexts",
        &super_token,
        json!({"id": "ctx-b", "name": "B"}),
    ))
    .await;

    // Create a key in ctx-a
    let (status, key_body) = app
        .request(post_auth(
            "/keys",
            &super_token,
            json!({"key_type": "ed25519", "context_id": "ctx-a"}),
        ))
        .await;
    assert!(status.is_success());
    let key_id = key_body["key_id"].as_str().unwrap();

    // Scoped admin for ctx-b cannot get the key in ctx-a (returns 403 or 404 — both are valid)
    let encoded_id = urlencoding::encode(key_id);
    let scoped_b_token = ctx
        .auth_token("did:key:z6MkB", "admin", vec!["ctx-b".into()])
        .await;
    let (status, _) = app
        .request(get_auth(&format!("/keys/{encoded_id}"), &scoped_b_token))
        .await;
    assert!(
        status == StatusCode::FORBIDDEN || status == StatusCode::NOT_FOUND,
        "scoped admin should not access other context's key, got {status}"
    );

    // Scoped admin for ctx-a CAN get the key
    let scoped_a_token = ctx
        .auth_token("did:key:z6MkA", "admin", vec!["ctx-a".into()])
        .await;
    let (status, body) = app
        .request(get_auth(&format!("/keys/{encoded_id}"), &scoped_a_token))
        .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["key_id"], key_id);
}

// ── Key lifecycle ──────────────────────────────────────────────────

#[tokio::test]
async fn key_create_revoke_list_lifecycle() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    // Create context + key
    app.request(post_auth(
        "/contexts",
        &token,
        json!({"id": "lc", "name": "Lifecycle"}),
    ))
    .await;
    let (_, key_body) = app
        .request(post_auth(
            "/keys",
            &token,
            json!({"key_type": "ed25519", "context_id": "lc"}),
        ))
        .await;
    let key_id = key_body["key_id"].as_str().unwrap();
    assert_eq!(key_body["status"], "active");

    // Revoke the key (key_id may contain slashes from derivation path, URL-encode it)
    let encoded_id = urlencoding::encode(key_id);
    let (status, body) = app
        .request(delete_auth(&format!("/keys/{encoded_id}"), &token))
        .await;
    assert!(status.is_success(), "revoke: {status} {body}");

    // Get key — should show revoked status
    let (status, body) = app
        .request(get_auth(&format!("/keys/{encoded_id}"), &token))
        .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["status"], "revoked");
}

#[tokio::test]
async fn key_rename() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    app.request(post_auth(
        "/contexts",
        &token,
        json!({"id": "rn", "name": "Rename"}),
    ))
    .await;
    let (_, key_body) = app
        .request(post_auth(
            "/keys",
            &token,
            json!({"key_type": "ed25519", "context_id": "rn", "label": "original"}),
        ))
        .await;
    let key_id = key_body["key_id"].as_str().unwrap();

    // Rename the key (PATCH expects new key_id in body)
    let encoded_id = urlencoding::encode(key_id);
    let (status, body) = app
        .request(patch_auth(
            &format!("/keys/{encoded_id}"),
            &token,
            json!({"key_id": "renamed-key"}),
        ))
        .await;
    assert!(status.is_success(), "rename: {status} {body}");
    assert_eq!(body["key_id"], "renamed-key");
}

// ── Seed management ────────────────────────────────────────────────

#[tokio::test]
async fn seed_list_returns_seeds() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;
    let (status, body) = app.request(get_auth("/keys/seeds", &token)).await;
    assert_eq!(status, StatusCode::OK);
    assert!(body["seeds"].is_array());
}

// ── Audit entries created by operations ────────────────────────────

#[tokio::test]
async fn operations_create_audit_entries() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    // Perform some operations that create audit entries
    app.request(post_auth(
        "/contexts",
        &token,
        json!({"id": "aud", "name": "Audit Test"}),
    ))
    .await;
    app.request(post_auth(
        "/keys",
        &token,
        json!({"key_type": "ed25519", "context_id": "aud"}),
    ))
    .await;

    // Check audit logs contain entries
    let (status, body) = app.request(get_auth("/audit/logs", &token)).await;
    assert_eq!(status, StatusCode::OK);
    let entries = body["entries"].as_array().expect("entries");
    assert!(
        !entries.is_empty(),
        "should have at least 1 audit entry, got {}",
        entries.len()
    );

    // Verify audit entries have expected fields
    let entry = &entries[0];
    assert!(entry["id"].is_string());
    assert!(entry["timestamp"].is_number());
    assert!(entry["action"].is_string());
    assert!(entry["actor"].is_string());
}

// ── Audit retention ────────────────────────────────────────────────

#[tokio::test]
async fn audit_retention_get_and_update() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    // Get current retention
    let (status, body) = app.request(get_auth("/audit/retention", &token)).await;
    assert_eq!(status, StatusCode::OK);
    assert!(body["retention_days"].is_number());

    // Update retention
    let (status, body) = app
        .request(patch_auth(
            "/audit/retention",
            &token,
            json!({"retention_days": 90}),
        ))
        .await;
    assert!(status.is_success(), "update retention: {status} {body}");
}

// ── Backup wrong password ──────────────────────────────────────────

#[tokio::test]
async fn backup_import_wrong_password_returns_auth_error() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;

    // Export with one password
    let (status, envelope) = app
        .request(post_auth(
            "/backup/export",
            &token,
            json!({"password": "correct-password!!", "include_audit": false}),
        ))
        .await;
    assert_eq!(status, StatusCode::OK);

    // Import with wrong password
    let (status, body) = app
        .request(post_auth(
            "/backup/import",
            &token,
            json!({"backup": envelope, "password": "wrong-password!!!", "confirm": false}),
        ))
        .await;
    assert_eq!(
        status,
        StatusCode::UNAUTHORIZED,
        "wrong password should → 401: {body}"
    );
}

// ── ACL CRUD full lifecycle ────────────────────────────────────────

#[tokio::test]
async fn acl_get_update_delete_lifecycle() {
    let (app, ctx) = TestApp::new().await;
    // create/update/delete are AAL2-gated mutations.
    let token = ctx
        .auth_token_aal2("did:key:z6MkAdmin", "admin", vec![])
        .await;

    // Create
    app.request(post_auth(
        "/acl",
        &token,
        json!({
            "did": "did:key:z6MkTarget",
            "role": "application",
            "label": "test",
            "allowed_contexts": ["ctx1"]
        }),
    ))
    .await;

    // Get
    let (status, body) = app
        .request(get_auth("/acl/did:key:z6MkTarget", &token))
        .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["role"], "application");

    // Update
    let (status, body) = app
        .request(patch_auth(
            "/acl/did:key:z6MkTarget",
            &token,
            json!({"role": "initiator", "label": "updated"}),
        ))
        .await;
    assert!(status.is_success(), "update: {status} {body}");
    assert_eq!(body["role"], "initiator");

    // Delete
    let (status, _) = app
        .request(delete_auth("/acl/did:key:z6MkTarget", &token))
        .await;
    assert!(status.is_success());

    // Verify deleted
    let (status, _) = app
        .request(get_auth("/acl/did:key:z6MkTarget", &token))
        .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

// ── Context lifecycle ──────────────────────────────────────────────

#[tokio::test]
async fn context_create_get_update_delete() {
    let (app, ctx) = TestApp::new().await;
    // Context deletion (the final step) is AAL2-gated.
    let token = ctx
        .auth_token_aal2("did:key:z6MkSuper", "admin", vec![])
        .await;

    // Create
    let (status, _) = app
        .request(post_auth(
            "/contexts",
            &token,
            json!({"id": "lifecycle", "name": "Test", "description": "A test context"}),
        ))
        .await;
    assert!(status.is_success());

    // Get
    let (status, body) = app.request(get_auth("/contexts/lifecycle", &token)).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["name"], "Test");
    assert_eq!(body["description"], "A test context");

    // Update
    let (status, body) = app
        .request(patch_auth(
            "/contexts/lifecycle",
            &token,
            json!({"name": "Updated"}),
        ))
        .await;
    assert!(status.is_success(), "update: {status} {body}");
    assert_eq!(body["name"], "Updated");

    // List
    let (status, body) = app.request(get_auth("/contexts", &token)).await;
    assert_eq!(status, StatusCode::OK);
    let contexts = body["contexts"].as_array().expect("contexts");
    assert!(contexts.iter().any(|c| c["id"] == "lifecycle"));

    // Delete
    let (status, _) = app
        .request(delete_auth("/contexts/lifecycle", &token))
        .await;
    assert!(status.is_success());
}

// ── Multiple key types ─────────────────────────────────────────────

#[tokio::test]
async fn create_p256_key() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    app.request(post_auth(
        "/contexts",
        &token,
        json!({"id": "p256", "name": "P256 Test"}),
    ))
    .await;

    let (status, body) = app
        .request(post_auth(
            "/keys",
            &token,
            json!({"key_type": "p256", "context_id": "p256"}),
        ))
        .await;
    assert!(status.is_success(), "create p256: {status} {body}");
    assert_eq!(body["key_type"], "p256");
    assert!(body["public_key"].is_string());
}

// ── Context DID update (context admin) ────────────────────────────

#[tokio::test]
async fn context_admin_can_update_own_context_did() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    // Create a context as super admin
    let (status, _) = app
        .request(post_auth(
            "/contexts",
            &super_token,
            json!({"id": "myctx", "name": "My Context"}),
        ))
        .await;
    assert!(status.is_success());

    // Context-scoped admin can update DID on their own context
    let scoped_token = ctx
        .auth_token("did:key:z6MkScoped", "admin", vec!["myctx".into()])
        .await;
    let (status, body) = app
        .request(put_auth(
            "/contexts/myctx/did",
            &scoped_token,
            json!({"did": "did:webvh:abc:example.com"}),
        ))
        .await;
    assert!(status.is_success(), "update did: {status} {body}");
    assert_eq!(body["did"], "did:webvh:abc:example.com");
}

#[tokio::test]
async fn context_admin_cannot_update_other_context_did() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    // Create two contexts
    app.request(post_auth(
        "/contexts",
        &super_token,
        json!({"id": "ctx-a", "name": "A"}),
    ))
    .await;
    app.request(post_auth(
        "/contexts",
        &super_token,
        json!({"id": "ctx-b", "name": "B"}),
    ))
    .await;

    // Admin scoped to ctx-a cannot update ctx-b's DID
    let scoped_token = ctx
        .auth_token("did:key:z6MkScopedA", "admin", vec!["ctx-a".into()])
        .await;
    let (status, _) = app
        .request(put_auth(
            "/contexts/ctx-b/did",
            &scoped_token,
            json!({"did": "did:webvh:nope:example.com"}),
        ))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn super_admin_can_update_any_context_did() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    app.request(post_auth(
        "/contexts",
        &token,
        json!({"id": "anyctx", "name": "Any"}),
    ))
    .await;

    let (status, body) = app
        .request(put_auth(
            "/contexts/anyctx/did",
            &token,
            json!({"did": "did:webvh:xyz:example.com"}),
        ))
        .await;
    assert!(
        status.is_success(),
        "super admin update did: {status} {body}"
    );
    assert_eq!(body["did"], "did:webvh:xyz:example.com");
}

#[tokio::test]
async fn non_admin_cannot_update_context_did() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;

    app.request(post_auth(
        "/contexts",
        &super_token,
        json!({"id": "restricted", "name": "R"}),
    ))
    .await;

    // Application role cannot update DID
    let app_token = ctx
        .auth_token("did:key:z6MkApp", "application", vec!["restricted".into()])
        .await;
    let (status, _) = app
        .request(put_auth(
            "/contexts/restricted/did",
            &app_token,
            json!({"did": "did:webvh:bad:example.com"}),
        ))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

// ── Reader role tests ──────────────────────────────────────────────

#[tokio::test]
async fn reader_can_list_keys() {
    let (app, ctx) = TestApp::new().await;
    let reader_token = ctx
        .auth_token("did:key:z6MkReader", "reader", vec!["test-ctx".into()])
        .await;

    let (status, _) = app
        .request(get_auth("/keys?context_id=test-ctx", &reader_token))
        .await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn reader_cannot_sign() {
    let (app, ctx) = TestApp::new().await;
    let reader_token = ctx
        .auth_token("did:key:z6MkReader", "reader", vec!["test-ctx".into()])
        .await;

    let (status, _) = app
        .request(post_auth(
            "/keys/test-key/sign",
            &reader_token,
            json!({"payload": "aGVsbG8", "algorithm": "EdDSA"}),
        ))
        .await;
    assert!(
        status == StatusCode::FORBIDDEN || status == StatusCode::UNPROCESSABLE_ENTITY,
        "expected 403 or 422, got {status}"
    );
}

#[tokio::test]
async fn reader_cannot_create_key() {
    let (app, ctx) = TestApp::new().await;
    let reader_token = ctx
        .auth_token("did:key:z6MkReader", "reader", vec!["test-ctx".into()])
        .await;

    let (status, _) = app
        .request(post_auth(
            "/keys",
            &reader_token,
            json!({"key_type": "ed25519", "context_id": "test-ctx"}),
        ))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

// ── WebVH DID creation mode tests ─────────────────────────────────

/// Helper: create a context via the API and return admin token.
async fn setup_webvh_context(app: &TestApp, ctx: &TestContext, context_id: &str) -> String {
    let super_token = ctx.auth_token("did:key:z6MkAdmin", "admin", vec![]).await;
    let (status, _) = app
        .request(post_auth(
            "/contexts",
            &super_token,
            json!({"id": context_id, "name": context_id}),
        ))
        .await;
    assert!(status.is_success(), "create context: {status}");
    super_token
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_rejects_both_document_and_log() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "test-reject").await;

    let (status, body) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": "test-reject",
                "url": "https://example.com/.well-known/did/did.jsonl",
                "did_document": {"id": "{DID}"},
                "did_log": "{\"some\": \"log\"}"
            }),
        ))
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "expected 400: {body}");
}

/// The new `path_mode` wire field deserializes and threads through
/// `CreateDidWebvhBody` → `CreateDidWebvhParams` without breaking the
/// serverless create path. (Serverless ignores the mode — `server_id`
/// selects `.well-known` self-hosting — but the field must still be
/// accepted so server-managed callers can set it.) Pins back-compat for
/// the `WebvhPathMode` addition.
#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_accepts_path_mode_field() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "test-path-mode").await;

    let (status, body) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": "test-path-mode",
                "url": "https://example.com/.well-known/did/did.jsonl",
                "path_mode": { "mode": "auto_assign" },
                "set_primary": false,
            }),
        ))
        .await;
    assert_eq!(
        status,
        StatusCode::CREATED,
        "create with explicit path_mode: {status} {body}"
    );
    assert!(body["did"].as_str().is_some(), "response has did");
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_template_mode() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "test-template").await;

    // Client-provided DID document template with {DID} placeholders
    let template = json!({
        "@context": [
            "https://www.w3.org/ns/did/v1",
            "https://www.w3.org/ns/cid/v1"
        ],
        "id": "{DID}",
        "verificationMethod": [{
            "id": "{DID}#custom-key",
            "type": "Multikey",
            "controller": "{DID}",
            "publicKeyMultibase": "z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK"
        }],
        "authentication": ["{DID}#custom-key"],
        "assertionMethod": ["{DID}#custom-key"]
    });

    let (status, body) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": "test-template",
                "url": "https://example.com/.well-known/did/did.jsonl",
                "did_document": template,
            }),
        ))
        .await;
    assert_eq!(
        status,
        StatusCode::CREATED,
        "template create: {status} {body}"
    );
    assert!(body["did"].as_str().is_some(), "response has did");
    assert!(
        body["did_document"].is_object(),
        "response has did_document"
    );
    assert!(
        body["log_entry"].as_str().is_some(),
        "response has log_entry"
    );
    // Verify the template was used (custom key ID present in returned document)
    let doc = &body["did_document"];
    let vm = doc["verificationMethod"]
        .as_array()
        .expect("verificationMethod array");
    assert!(
        vm.iter().any(|v| {
            v["id"]
                .as_str()
                .is_some_and(|id| id.ends_with("#custom-key"))
        }),
        "template's custom key should be in the returned document"
    );
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_final_mode_stores_record() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "test-final").await;

    // First, create a DID via VTA-built mode to get a valid log entry
    let (status, created) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": "test-final",
                "url": "https://example.com/.well-known/did/did.jsonl",
                "set_primary": false,
            }),
        ))
        .await;
    assert_eq!(
        status,
        StatusCode::CREATED,
        "bootstrap create: {status} {created}"
    );
    let log_entry = created["log_entry"].as_str().expect("log_entry string");

    // Now create another DID using the log entry in final mode, under a new context
    let token2 = setup_webvh_context(&app, &ctx, "test-final-2").await;
    let (status, body) = app
        .request(post_auth(
            "/webvh/dids",
            &token2,
            json!({
                "context_id": "test-final-2",
                "url": "https://example.com/.well-known/did/did.jsonl",
                "did_log": log_entry,
            }),
        ))
        .await;
    assert_eq!(
        status,
        StatusCode::CREATED,
        "final mode create: {status} {body}"
    );
    let final_did = body["did"].as_str().expect("did in response");
    assert!(!final_did.is_empty());
    // signing_key_id and ka_key_id are empty in final mode (VTA didn't derive keys)
    assert_eq!(body["signing_key_id"].as_str().unwrap(), "");
    assert_eq!(body["ka_key_id"].as_str().unwrap(), "");
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_set_primary_false() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "test-no-primary").await;

    let (status, _) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": "test-no-primary",
                "url": "https://example.com/.well-known/did/did.jsonl",
                "set_primary": false,
            }),
        ))
        .await;
    assert_eq!(status, StatusCode::CREATED);

    // Context's primary DID should still be null
    let (status, body) = app
        .request(get_auth("/contexts/test-no-primary", &token))
        .await;
    assert!(status.is_success(), "get context: {status}");
    assert!(
        body["did"].is_null(),
        "context did should be null when set_primary=false"
    );
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_set_primary_true() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "test-primary").await;

    let (status, created) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": "test-primary",
                "url": "https://example.com/.well-known/did/did.jsonl",
                "set_primary": true,
            }),
        ))
        .await;
    assert_eq!(status, StatusCode::CREATED);
    let created_did = created["did"].as_str().expect("did");

    // Context's primary DID should be set
    let (status, body) = app
        .request(get_auth("/contexts/test-primary", &token))
        .await;
    assert!(status.is_success(), "get context: {status}");
    assert_eq!(
        body["did"].as_str().unwrap(),
        created_did,
        "context did should match created DID"
    );
}

// ── User-specified key tests ──────────────────────────────────────

/// Regression test for the security-review patch #9 hardening: the
/// REST `POST /keys/import` handler must refuse the legacy
/// `private_key_multibase` field (raw private key over a TLS-only
/// channel). `#[serde(deny_unknown_fields)]` is the load-bearing
/// mechanism — operators get a specific "unknown field" error
/// pointing them at the sealed-transfer migration path.
#[tokio::test]
async fn keys_import_rejects_private_key_multibase_over_rest() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx
        .auth_token("did:key:z6MkSuperAdmin", "admin", vec![])
        .await;

    let (status, body) = app
        .request(post_auth(
            "/keys/import",
            &token,
            json!({
                "key_type": "ed25519",
                "private_key_multibase": "z6MkDeadbeefDeadbeefDeadbeef",
                "label": "should-be-refused",
            }),
        ))
        .await;
    assert_eq!(
        status,
        StatusCode::UNPROCESSABLE_ENTITY,
        "expected 422 for unknown field, got {status} {body}"
    );
    let rendered = body.to_string();
    assert!(
        rendered.contains("private_key_multibase"),
        "rejection must name the offending field so operators can find the migration path: {rendered}"
    );
}

/// Helper: drive the full sealed-transfer wrapping flow against
/// `POST /keys/import`, returning the new `key_id`.
///
/// Mirrors what a real consumer does:
/// 1. `GET /keys/import/wrapping-key` to fetch an ephemeral X25519
///    pubkey + kid.
/// 2. Build a [`SealedPayloadV1::RawPrivateKey`] around the test
///    key bytes.
/// 3. `seal_payload` against the wrapping pubkey, ASCII-armor.
/// 4. `POST /keys/import` with `private_key_sealed`.
///
/// The plaintext `private_key_multibase` REST path was removed —
/// see the `ImportKeyRestRequest` doc comment in
/// `vta-service/src/routes/keys.rs`.
#[cfg(feature = "webvh")]
async fn import_key_via_sealed_transfer(
    app: &TestApp,
    token: &str,
    key_type_str: &str,
    key_bytes: &[u8],
    label: &str,
    context_id: &str,
) -> String {
    use base64::Engine;
    use base64::engine::general_purpose::URL_SAFE_NO_PAD as BASE64;
    use vta_sdk::sealed_transfer::{
        AssertionProof, InMemoryNonceStore, ProducerAssertion, RawPrivateKey, SealedPayloadV1,
        armor, generate_ed25519_keypair, seal_payload,
    };

    // 1. Fetch the wrapping key.
    let (status, body) = app
        .request(get_auth("/keys/import/wrapping-key", token))
        .await;
    assert!(status.is_success(), "GET wrapping-key: {status} {body}");
    let pub_b64 = body["x"]
        .as_str()
        .expect("wrapping-key response missing `x`")
        .to_string();
    let pub_bytes: [u8; 32] = BASE64
        .decode(&pub_b64)
        .expect("decode wrapping pubkey")
        .try_into()
        .expect("wrapping pubkey must be 32 bytes");

    // 2. Build the sealed payload.
    let payload = SealedPayloadV1::RawPrivateKey(RawPrivateKey {
        key_type: key_type_str.into(),
        key_bytes_b64: BASE64.encode(key_bytes),
    });

    // 3. Seal + armor. Producer assertion is `PinnedOnly` — the
    // wrapping-key endpoint already pins the producer↔consumer
    // pairing via the single-use ephemeral key, so no separate
    // signed assertion is required here.
    let (_seed, prod_ed_pub) = generate_ed25519_keypair();
    let producer = ProducerAssertion {
        producer_did: affinidi_crypto::did_key::ed25519_pub_to_did_key(&prod_ed_pub),
        proof: AssertionProof::PinnedOnly,
    };
    let store = InMemoryNonceStore::new();
    let bundle = seal_payload(&pub_bytes, [0u8; 16], producer, &payload, &store)
        .await
        .expect("seal_payload");
    let armored = armor::encode(&bundle);

    // 4. POST the armored bundle as the import request.
    let (status, body) = app
        .request(post_auth(
            "/keys/import",
            token,
            json!({
                "key_type": key_type_str,
                "private_key_sealed": armored,
                "label": label,
                "context_id": context_id,
            }),
        ))
        .await;
    assert!(
        status.is_success(),
        "import {key_type_str} via sealed-transfer: {status} {body}",
    );
    body["key_id"].as_str().unwrap().to_string()
}

/// Helper: import an Ed25519 key via the sealed-transfer wrapping
/// flow and return the key_id.
#[cfg(feature = "webvh")]
async fn import_ed25519_key(app: &TestApp, token: &str, label: &str, context_id: &str) -> String {
    // 32 deterministic bytes for the Ed25519 seed (test only).
    let seed_bytes = [0x42u8; 32];
    import_key_via_sealed_transfer(app, token, "ed25519", &seed_bytes, label, context_id).await
}

/// Helper: import an X25519 key via the sealed-transfer wrapping
/// flow and return the key_id.
#[cfg(feature = "webvh")]
async fn import_x25519_key(app: &TestApp, token: &str, label: &str, context_id: &str) -> String {
    // 32 deterministic bytes for the X25519 private key (test only).
    let key_bytes = [0x99u8; 32];
    import_key_via_sealed_transfer(app, token, "x25519", &key_bytes, label, context_id).await
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_with_user_signing_key() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "test-user-sign").await;
    let signing_key = import_ed25519_key(&app, &token, "my-sign", "test-user-sign").await;

    let (status, body) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": "test-user-sign",
                "url": "https://example.com/.well-known/did/did.jsonl",
                "signing_key_id": signing_key,
            }),
        ))
        .await;
    assert_eq!(
        status,
        StatusCode::CREATED,
        "signing-only create: {status} {body}"
    );
    assert!(body["did"].as_str().is_some());
    // Document should have signing key but no keyAgreement
    let doc = &body["did_document"];
    assert!(doc["authentication"].is_array());
    assert!(doc.get("keyAgreement").is_none() || doc["keyAgreement"].is_null());
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_with_user_signing_and_ka_keys() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "test-user-both").await;
    let signing_key = import_ed25519_key(&app, &token, "my-sign", "test-user-both").await;
    let ka_key = import_x25519_key(&app, &token, "my-ka", "test-user-both").await;

    let (status, body) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": "test-user-both",
                "url": "https://example.com/.well-known/did/did.jsonl",
                "signing_key_id": signing_key,
                "ka_key_id": ka_key,
            }),
        ))
        .await;
    assert_eq!(
        status,
        StatusCode::CREATED,
        "both keys create: {status} {body}"
    );
    let doc = &body["did_document"];
    assert!(doc["keyAgreement"].is_array(), "should have keyAgreement");
    let vm = doc["verificationMethod"].as_array().unwrap();
    assert_eq!(vm.len(), 2, "should have 2 verification methods");
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_ka_without_signing_rejected() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "test-ka-only").await;
    let ka_key = import_x25519_key(&app, &token, "my-ka", "test-ka-only").await;

    let (status, _) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": "test-ka-only",
                "url": "https://example.com/.well-known/did/did.jsonl",
                "ka_key_id": ka_key,
            }),
        ))
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_didcomm_requires_ka_key() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "test-didcomm-ka").await;
    let signing_key = import_ed25519_key(&app, &token, "my-sign", "test-didcomm-ka").await;

    // Signing key only + mediator service → should fail
    let (status, body) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": "test-didcomm-ka",
                "url": "https://example.com/.well-known/did/did.jsonl",
                "signing_key_id": signing_key,
                "add_mediator_service": true,
            }),
        ))
        .await;
    assert_eq!(
        status,
        StatusCode::BAD_REQUEST,
        "didcomm without ka: {status} {body}"
    );
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_wrong_key_type_rejected() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "test-wrong-type").await;
    let ka_key = import_x25519_key(&app, &token, "my-ka", "test-wrong-type").await;

    // Use X25519 key as signing key → should fail
    let (status, _) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": "test-wrong-type",
                "url": "https://example.com/.well-known/did/did.jsonl",
                "signing_key_id": ka_key,
            }),
        ))
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
}

// ── Server-managed DID creation tests ─────────────────────────────

#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_unknown_server_returns_404() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "test-no-server").await;

    let (status, body) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": "test-no-server",
                "server_id": "nonexistent-server",
            }),
        ))
        .await;
    assert_eq!(
        status,
        StatusCode::NOT_FOUND,
        "unknown server_id: {status} {body}"
    );
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_server_and_url_mutually_exclusive() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "test-exclusive").await;

    let (status, _) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": "test-exclusive",
                "server_id": "some-server",
                "url": "https://example.com/.well-known/did/did.jsonl",
            }),
        ))
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_neither_server_nor_url_rejected() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "test-neither").await;

    let (status, _) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": "test-neither",
            }),
        ))
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
}

// ── DID templates (Phase 2, global scope) ──────────────────────────

/// Minimum valid template body for create/update tests.
fn sample_template(name: &str) -> Value {
    json!({
        "schemaVersion": 1,
        "name": name,
        "kind": "custom",
        "description": "integration-test template",
        "methods": ["webvh"],
        "requiredVars": ["URL"],
        "optionalVars": { "ACCEPT": ["didcomm/v2"] },
        "defaults": {},
        "document": {
            "@context": ["https://www.w3.org/ns/did/v1"],
            "id": "{DID}",
            "verificationMethod": [{
                "id": "{DID}#key-1",
                "type": "Multikey",
                "controller": "{DID}",
                "publicKeyMultibase": "{SIGNING_KEY_MB}"
            }],
            "service": [{
                "id": "{DID}#svc",
                "type": "Custom",
                "serviceEndpoint": { "uri": "{URL}", "accept": "{ACCEPT}" }
            }]
        }
    })
}

#[tokio::test]
async fn did_templates_list_empty_for_fresh_vta() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx
        .auth_token("did:key:z6MkReader", "reader", vec!["any".into()])
        .await;
    let (status, body) = app.request(get_auth("/did-templates", &token)).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["templates"].as_array().map(|a| a.len()), Some(0));
}

#[tokio::test]
async fn did_templates_create_requires_super_admin() {
    let (app, ctx) = TestApp::new().await;
    // An admin with allowed_contexts is NOT a super admin.
    let token = ctx
        .auth_token("did:key:z6MkAdmin", "admin", vec!["some-ctx".into()])
        .await;

    let (status, _) = app
        .request(post_auth(
            "/did-templates",
            &token,
            sample_template("forbidden"),
        ))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn did_templates_create_get_delete_roundtrip() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;

    // Create
    let (status, body) = app
        .request(post_auth(
            "/did-templates",
            &super_token,
            sample_template("rt"),
        ))
        .await;
    assert_eq!(status, StatusCode::CREATED, "body: {body}");
    assert_eq!(body["name"], "rt");
    assert_eq!(body["scope"]["type"], "global");
    assert_eq!(body["createdBy"], "did:key:z6MkSuper");

    // Duplicate rejected
    let (status, _) = app
        .request(post_auth(
            "/did-templates",
            &super_token,
            sample_template("rt"),
        ))
        .await;
    assert_eq!(status, StatusCode::CONFLICT);

    // Get
    let (status, body) = app
        .request(get_auth("/did-templates/rt", &super_token))
        .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["name"], "rt");

    // List shows one
    let (status, body) = app.request(get_auth("/did-templates", &super_token)).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["templates"].as_array().map(|a| a.len()), Some(1));

    // Delete
    let (status, _) = app
        .request(delete_auth("/did-templates/rt", &super_token))
        .await;
    assert_eq!(status, StatusCode::NO_CONTENT);

    // Gone
    let (status, _) = app
        .request(get_auth("/did-templates/rt", &super_token))
        .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn did_templates_update_replaces_body_preserves_created_at() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;

    let (status, original) = app
        .request(post_auth(
            "/did-templates",
            &super_token,
            sample_template("evolving"),
        ))
        .await;
    assert_eq!(status, StatusCode::CREATED);
    let created_at_original = original["createdAt"].clone();

    // Update with a tweaked description.
    let mut updated = sample_template("evolving");
    updated["description"] = json!("new description");
    let (status, body) = app
        .request(put_auth("/did-templates/evolving", &super_token, updated))
        .await;
    assert_eq!(status, StatusCode::OK, "body: {body}");
    assert_eq!(body["description"], "new description");
    // createdAt preserved, updatedAt advances (can't assert >, but must exist).
    assert_eq!(body["createdAt"], created_at_original);
    assert!(body["updatedAt"].is_u64());
}

#[tokio::test]
async fn did_templates_update_name_mismatch_rejected() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;

    let _ = app
        .request(post_auth(
            "/did-templates",
            &super_token,
            sample_template("fixed-name"),
        ))
        .await;

    // Body names "other" but path is "fixed-name".
    let (status, _) = app
        .request(put_auth(
            "/did-templates/fixed-name",
            &super_token,
            sample_template("other"),
        ))
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn did_templates_render_injects_ambient_and_merges_caller_vars() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;

    let _ = app
        .request(post_auth(
            "/did-templates",
            &super_token,
            sample_template("renderable"),
        ))
        .await;

    let reader = ctx
        .auth_token("did:key:z6MkReader", "reader", vec!["any".into()])
        .await;
    // DID/SIGNING_KEY_MB are reserved ambient but Phase 2 doesn't mint them —
    // callers must supply for a preview render.
    let (status, body) = app
        .request(post_auth(
            "/did-templates/renderable/render",
            &reader,
            json!({
                "vars": {
                    "DID": "did:webvh:example.com:test",
                    "SIGNING_KEY_MB": "z6MkSigning",
                    "URL": "https://example.com"
                }
            }),
        ))
        .await;
    assert_eq!(status, StatusCode::OK, "body: {body}");
    assert_eq!(body["document"]["id"], "did:webvh:example.com:test");
    assert_eq!(
        body["document"]["service"][0]["serviceEndpoint"]["uri"],
        "https://example.com"
    );
    // ACCEPT defaulted from optionalVars, survived as array.
    assert_eq!(
        body["document"]["service"][0]["serviceEndpoint"]["accept"],
        json!(["didcomm/v2"])
    );
}

#[tokio::test]
async fn did_templates_render_missing_required_var_errors() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;

    let _ = app
        .request(post_auth(
            "/did-templates",
            &super_token,
            sample_template("needs-url"),
        ))
        .await;

    // Omit URL — server should 400 with a clear message.
    let (status, _) = app
        .request(post_auth(
            "/did-templates/needs-url/render",
            &super_token,
            json!({ "vars": { "DID": "did:x", "SIGNING_KEY_MB": "z6MkX" } }),
        ))
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn did_templates_invalid_body_rejected_at_create() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;

    let mut bad = sample_template("bad-name-has-space");
    bad["name"] = json!("Has Space");
    let (status, _) = app
        .request(post_auth("/did-templates", &super_token, bad))
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
}

// ── Context-scoped DID templates (Phase 3) ─────────────────────────

async fn create_test_context(app: &TestApp, super_token: &str, id: &str) {
    let (status, _) = app
        .request(post_auth(
            "/contexts",
            super_token,
            json!({ "id": id, "name": id }),
        ))
        .await;
    assert_eq!(
        status,
        StatusCode::CREATED,
        "failed to create context '{id}'"
    );
}

#[tokio::test]
async fn ctx_did_templates_create_requires_context_admin_or_super() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;
    create_test_context(&app, &super_token, "tpl-ctx").await;

    // Reader with context access — may list/read, must not write.
    let reader = ctx
        .auth_token("did:key:z6MkReader", "reader", vec!["tpl-ctx".into()])
        .await;
    let (status, _) = app
        .request(post_auth(
            "/contexts/tpl-ctx/did-templates",
            &reader,
            sample_template("rejected"),
        ))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);

    // Admin scoped to a different context — no access to tpl-ctx at all.
    let other_admin = ctx
        .auth_token("did:key:z6MkOther", "admin", vec!["somewhere-else".into()])
        .await;
    let (status, _) = app
        .request(post_auth(
            "/contexts/tpl-ctx/did-templates",
            &other_admin,
            sample_template("rejected"),
        ))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn ctx_did_templates_context_admin_can_crud() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;
    create_test_context(&app, &super_token, "cx-admin-test").await;

    let ctx_admin = ctx
        .auth_token(
            "did:key:z6MkCtxAdmin",
            "admin",
            vec!["cx-admin-test".into()],
        )
        .await;

    // Create
    let (status, body) = app
        .request(post_auth(
            "/contexts/cx-admin-test/did-templates",
            &ctx_admin,
            sample_template("scoped-tpl"),
        ))
        .await;
    assert_eq!(status, StatusCode::CREATED, "body: {body}");
    assert_eq!(body["scope"]["type"], "context");
    assert_eq!(body["scope"]["contextId"], "cx-admin-test");
    assert_eq!(body["name"], "scoped-tpl");

    // Get + list
    let (status, body) = app
        .request(get_auth(
            "/contexts/cx-admin-test/did-templates/scoped-tpl",
            &ctx_admin,
        ))
        .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["name"], "scoped-tpl");

    let (status, body) = app
        .request(get_auth(
            "/contexts/cx-admin-test/did-templates",
            &ctx_admin,
        ))
        .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["templates"].as_array().map(|a| a.len()), Some(1));

    // Update
    let mut updated = sample_template("scoped-tpl");
    updated["description"] = json!("changed");
    let (status, body) = app
        .request(put_auth(
            "/contexts/cx-admin-test/did-templates/scoped-tpl",
            &ctx_admin,
            updated,
        ))
        .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["description"], "changed");

    // Delete
    let (status, _) = app
        .request(delete_auth(
            "/contexts/cx-admin-test/did-templates/scoped-tpl",
            &ctx_admin,
        ))
        .await;
    assert_eq!(status, StatusCode::NO_CONTENT);

    let (status, _) = app
        .request(get_auth(
            "/contexts/cx-admin-test/did-templates/scoped-tpl",
            &ctx_admin,
        ))
        .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn ctx_did_templates_rejects_missing_context() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;

    let (status, _) = app
        .request(post_auth(
            "/contexts/does-not-exist/did-templates",
            &super_token,
            sample_template("orphan"),
        ))
        .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn ctx_did_templates_shadow_global_without_conflict() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;
    create_test_context(&app, &super_token, "shadow-ctx").await;

    // Create a global "mediator" template.
    let (status, _) = app
        .request(post_auth(
            "/did-templates",
            &super_token,
            sample_template("mediator"),
        ))
        .await;
    assert_eq!(status, StatusCode::CREATED);

    // Same name in a context — must coexist without conflict.
    let (status, body) = app
        .request(post_auth(
            "/contexts/shadow-ctx/did-templates",
            &super_token,
            sample_template("mediator"),
        ))
        .await;
    assert_eq!(status, StatusCode::CREATED, "body: {body}");
    assert_eq!(body["scope"]["type"], "context");

    let (_, global) = app
        .request(get_auth("/did-templates/mediator", &super_token))
        .await;
    let (_, context_local) = app
        .request(get_auth(
            "/contexts/shadow-ctx/did-templates/mediator",
            &super_token,
        ))
        .await;
    assert_eq!(global["scope"]["type"], "global");
    assert_eq!(context_local["scope"]["type"], "context");
}

#[tokio::test]
async fn ctx_did_templates_render_injects_context_vars() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;
    create_test_context(&app, &super_token, "render-ctx").await;

    // Template references CONTEXT_ID in its document.
    let mut tpl = sample_template("ctxtpl");
    tpl["document"]["service"][0]["serviceEndpoint"]["contextId"] = json!("{CONTEXT_ID}");
    let (status, _) = app
        .request(post_auth(
            "/contexts/render-ctx/did-templates",
            &super_token,
            tpl,
        ))
        .await;
    assert_eq!(status, StatusCode::CREATED);

    let (status, body) = app
        .request(post_auth(
            "/contexts/render-ctx/did-templates/ctxtpl/render",
            &super_token,
            json!({
                "vars": {
                    "DID": "did:x",
                    "SIGNING_KEY_MB": "z6Mk",
                    "URL": "https://example.com"
                }
            }),
        ))
        .await;
    assert_eq!(status, StatusCode::OK, "body: {body}");
    assert_eq!(
        body["document"]["service"][0]["serviceEndpoint"]["contextId"],
        "render-ctx"
    );
}

#[tokio::test]
async fn ctx_did_templates_deleted_when_parent_context_deleted() {
    let (app, ctx) = TestApp::new().await;
    // This test deletes a context (an AAL2-gated mutation), so it needs a
    // stepped-up session.
    let super_token = ctx
        .auth_token_aal2("did:key:z6MkSuper", "admin", vec![])
        .await;
    create_test_context(&app, &super_token, "cascade-ctx").await;

    // Add a template to the context.
    let _ = app
        .request(post_auth(
            "/contexts/cascade-ctx/did-templates",
            &super_token,
            sample_template("will-be-deleted"),
        ))
        .await;

    // Preview must list the template among resources to be removed.
    let (status, preview) = app
        .request(get_auth(
            "/contexts/cascade-ctx/delete-preview",
            &super_token,
        ))
        .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(
        preview["did_templates"].as_array().map(|a| a.len()),
        Some(1)
    );
    assert_eq!(preview["did_templates"][0], "will-be-deleted");

    // Force-delete the context.
    let (status, _) = app
        .request(delete_auth(
            "/contexts/cascade-ctx?force=true",
            &super_token,
        ))
        .await;
    assert_eq!(status, StatusCode::NO_CONTENT);

    // Template is gone; context itself is gone too so the lookup fails.
    let (status, _) = app
        .request(get_auth(
            "/contexts/cascade-ctx/did-templates/will-be-deleted",
            &super_token,
        ))
        .await;
    assert!(
        matches!(status, StatusCode::FORBIDDEN | StatusCode::NOT_FOUND),
        "expected 403/404 after context delete, got {status}"
    );
}

// ── Template-driven DID creation (Phase 4) ─────────────────────────

#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_via_builtin_mediator_template() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "tpl-mediator").await;

    // Use the built-in `didcomm-mediator` template. No `did_document` in
    // the request — the server renders the template with the keys it mints
    // and uses the result as the DID document.
    let (status, body) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": "tpl-mediator",
                "url": "https://mediator.example.com/.well-known/did/did.jsonl",
                "template": "didcomm-mediator",
                "template_vars": {
                    "URL": "https://mediator.example.com",
                    "WS_URL": "wss://mediator.example.com/ws"
                }
            }),
        ))
        .await;
    assert!(
        status.is_success(),
        "template-driven create failed: {status} {body}"
    );

    // The rendered document should carry a DIDCommMessaging service whose
    // serviceEndpoint is an array of two endpoints — HTTP first, WSS
    // second. The mediator template advertises both transports under one
    // `#service` entry; clients pick whichever transport they support.
    let doc = &body["did_document"];
    assert!(doc.is_object(), "result must include did_document");
    let services = doc["service"].as_array().unwrap();
    let didcomm = services
        .iter()
        .find(|s| s["type"] == json!(["DIDCommMessaging"]))
        .expect("mediator template must produce a DIDCommMessaging service");
    let endpoints = didcomm["serviceEndpoint"].as_array().unwrap();
    assert_eq!(endpoints.len(), 2);
    assert_eq!(endpoints[0]["uri"], "https://mediator.example.com");
    assert_eq!(endpoints[0]["accept"], json!(["didcomm/v2"]));
    assert_eq!(endpoints[1]["uri"], "wss://mediator.example.com/ws");
    assert_eq!(endpoints[1]["accept"], json!(["didcomm/v2"]));
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_template_mutually_exclusive_with_did_document() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "tpl-excl").await;

    let (status, _) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": "tpl-excl",
                "url": "https://example.com/.well-known/did/did.jsonl",
                "template": "didcomm-mediator",
                "template_vars": { "URL": "https://example.com" },
                "did_document": { "id": "{DID}" }
            }),
        ))
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_template_missing_required_var_errors() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "tpl-missing").await;

    // `didcomm-mediator` requires URL — omit it.
    let (status, _) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": "tpl-missing",
                "url": "https://example.com/.well-known/did/did.jsonl",
                "template": "didcomm-mediator"
            }),
        ))
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_template_unknown_name_errors() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "tpl-unk").await;

    let (status, _) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": "tpl-unk",
                "url": "https://example.com/.well-known/did/did.jsonl",
                "template": "no-such-template"
            }),
        ))
        .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

// Export round-trips: `GET /did-templates/{name}` body, with server-only
// fields stripped, must parse back through the SDK loader. This is the
// contract `pnm did-templates export | create --file -` depends on.
#[tokio::test]
async fn did_templates_export_round_trips_through_sdk_loader() {
    use vta_sdk::did_templates::DidTemplate;

    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;

    let original = sample_template("round-trip");
    let _ = app
        .request(post_auth("/did-templates", &super_token, original))
        .await;

    let (status, mut body) = app
        .request(get_auth("/did-templates/round-trip", &super_token))
        .await;
    assert_eq!(status, StatusCode::OK);

    // Strip server metadata (what the CLI `export` command does).
    let obj = body.as_object_mut().unwrap();
    obj.remove("scope");
    obj.remove("created_at");
    obj.remove("updated_at");
    obj.remove("created_by");

    let tpl = DidTemplate::from_json(body).expect("export must round-trip");
    assert_eq!(tpl.name, "round-trip");
    assert_eq!(tpl.kind, "custom");
}

// ── Provision-integration REST surface ────────────────────────────
//
// Item 18: exercise the HTTP-specific concerns — auth gate, payload
// deserialization, and VP validation — in isolation from the happy-
// path library flow that the `operations::provision_integration`
// unit tests already cover end-to-end.

#[cfg(feature = "webvh")]
async fn sign_sample_bootstrap_request() -> vta_sdk::provision_integration::BootstrapRequest {
    use std::collections::BTreeMap;
    use vta_sdk::provision_integration::{BootstrapAsk, DidTemplateRef, TemplateBootstrapAsk};

    let (seed_box, pub_bytes) = vta_sdk::sealed_transfer::generate_ed25519_keypair();
    let client_did = affinidi_crypto::did_key::ed25519_pub_to_did_key(&pub_bytes);

    let ask = BootstrapAsk::TemplateBootstrap(TemplateBootstrapAsk {
        context_hint: Some("prod-mediator".into()),
        template: DidTemplateRef {
            name: "didcomm-mediator".into(),
            vars: BTreeMap::from([(
                "URL".into(),
                Value::String("https://mediator.example.com".into()),
            )]),
        },
        admin_template: None,
        note: None,
    });

    vta_sdk::provision_integration::BootstrapRequest::sign(
        &seed_box,
        &client_did,
        [0xAAu8; 16],
        chrono::Duration::hours(1),
        Some("item-18-rest-test".into()),
        ask,
    )
    .await
    .expect("sign sample VP")
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn provision_integration_requires_auth() {
    // No Bearer token → the AdminAuth extractor rejects before any
    // validation runs.
    let (app, _ctx) = TestApp::new().await;
    let vp = sign_sample_bootstrap_request().await;
    let body = json!({
        "request": vp,
        "context": "prod-mediator",
    });
    let req = Request::builder()
        .method("POST")
        .uri("/bootstrap/provision-integration")
        .header("Content-Type", "application/json")
        .body(Body::from(serde_json::to_vec(&body).unwrap()))
        .unwrap();
    let (status, _) = app.request(req).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn provision_integration_rejects_non_admin_token() {
    // Caller authenticates as role "reader" — AdminAuth must reject.
    let (app, ctx) = TestApp::new().await;
    let token = ctx
        .auth_token("did:key:z6MkReader", "reader", vec!["prod-mediator".into()])
        .await;
    let vp = sign_sample_bootstrap_request().await;
    let body = json!({
        "request": vp,
        "context": "prod-mediator",
    });
    let (status, _) = app
        .request(post_auth("/bootstrap/provision-integration", &token, body))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn provision_integration_rejects_tampered_vp() {
    // Admin token + structurally valid body, but the VP's nonce has
    // been mutated after signing — the handler calls `.verify()` on
    // the request and returns 400.
    let (app, ctx) = TestApp::new().await;
    let token = ctx
        .auth_token("did:key:z6MkAdmin", "admin", vec!["prod-mediator".into()])
        .await;
    let mut vp = sign_sample_bootstrap_request().await;
    // Swap the nonce — same length, different bytes → signature
    // over the mutated body is now invalid.
    vp.nonce = "BBBBBBBBBBBBBBBBBBBBBB".to_string();
    let body = json!({
        "request": vp,
        "context": "prod-mediator",
    });
    let (status, _) = app
        .request(post_auth("/bootstrap/provision-integration", &token, body))
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn provision_integration_rejects_unknown_field_in_body() {
    // `deny_unknown_fields` on BootstrapRequest (item 22 hardening)
    // kicks in at deserialize time for any field the verifier doesn't
    // know about. The handler surfaces this as a Deserialize error
    // → 400 via axum's default JSON extractor rejection.
    let (app, ctx) = TestApp::new().await;
    let token = ctx
        .auth_token("did:key:z6MkAdmin", "admin", vec!["prod-mediator".into()])
        .await;
    let mut vp_value =
        serde_json::to_value(sign_sample_bootstrap_request().await).expect("serialize VP");
    // Inject an attacker-chosen field — item-22 guard must reject.
    vp_value["smugglerField"] = json!("malicious");
    let body = json!({
        "request": vp_value,
        "context": "prod-mediator",
    });
    let (status, _) = app
        .request(post_auth("/bootstrap/provision-integration", &token, body))
        .await;
    assert!(
        status == StatusCode::BAD_REQUEST || status == StatusCode::UNPROCESSABLE_ENTITY,
        "expected 4xx rejection for unknown field, got {status}"
    );
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn create_did_webvh_context_scoped_template_shadows_global() {
    let (app, ctx) = TestApp::new().await;
    let super_token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;
    create_test_context(&app, &super_token, "shadow-didcreate").await;

    // Global template with one description.
    let mut global = sample_template("my-custom");
    global["description"] = json!("GLOBAL");
    let _ = app
        .request(post_auth("/did-templates", &super_token, global))
        .await;

    // Context-scoped override with a different description.
    let mut local = sample_template("my-custom");
    local["description"] = json!("CONTEXT");
    let _ = app
        .request(post_auth(
            "/contexts/shadow-didcreate/did-templates",
            &super_token,
            local,
        ))
        .await;

    // Create a DID using the template — with template_context set to the
    // context, resolution should pick up the context-scoped override first.
    let (status, body) = app
        .request(post_auth(
            "/webvh/dids",
            &super_token,
            json!({
                "context_id": "shadow-didcreate",
                "url": "https://example.com/.well-known/did/did.jsonl",
                "template": "my-custom",
                "template_context": "shadow-didcreate",
                "template_vars": { "URL": "https://example.com" }
            }),
        ))
        .await;
    assert!(status.is_success(), "{status} {body}");
    // The fact that it succeeded (and the service shape from `sample_template`
    // is present — a `Custom` service type we used in the sample) confirms
    // the rendered doc came from a template, not the VTA's auto-builder.
    let doc = &body["did_document"];
    assert_eq!(doc["service"][0]["type"], "Custom");
}

// ── webvh DID update + rotate-keys tests ─────────────────────────

/// Helper: create a context + a serverless webvh DID, return
/// `(token, scid, did)` for follow-up update/rotate calls.
#[cfg(feature = "webvh")]
async fn create_test_webvh_did(
    app: &TestApp,
    ctx: &TestContext,
    context_id: &str,
) -> (String, String, String) {
    let token = setup_webvh_context(app, ctx, context_id).await;
    let (status, created) = app
        .request(post_auth(
            "/webvh/dids",
            &token,
            json!({
                "context_id": context_id,
                "url": "https://example.com/.well-known/did/did.jsonl",
                "set_primary": false,
            }),
        ))
        .await;
    assert_eq!(
        status,
        StatusCode::CREATED,
        "create did: {status} {created}"
    );
    let scid = created["scid"]
        .as_str()
        .expect("scid in response")
        .to_string();
    let did = created["did"]
        .as_str()
        .expect("did in response")
        .to_string();
    (token, scid, did)
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn update_did_webvh_metadata_only_succeeds() {
    let (app, ctx) = TestApp::new().await;
    let (token, scid, did) = create_test_webvh_did(&app, &ctx, "update-meta").await;

    // Toggle pre-rotation off — metadata-only change.
    let (status, body) = app
        .request(post_auth(
            &format!("/contexts/update-meta/dids/{scid}/update"),
            &token,
            json!({ "pre_rotation_count": 0 }),
        ))
        .await;
    assert_eq!(status, StatusCode::OK, "update: {status} {body}");
    assert_eq!(body["did"], did);
    assert_eq!(body["pre_rotation_key_count"], 0);
    assert!(body["new_version_id"].as_str().unwrap().starts_with("2-"));
    assert!(!body["new_log_entry"].as_str().unwrap().is_empty());
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn update_did_webvh_with_new_document_rotates_keys() {
    let (app, ctx) = TestApp::new().await;
    let (token, scid, did) = create_test_webvh_did(&app, &ctx, "update-doc").await;

    // Fetch current doc so we can hand back a valid (id-matching) one.
    let (status, get_body) = app
        .request(post_auth(
            &format!("/webvh/dids/{}/log", urlencoding::encode(&did)),
            &token,
            json!({}),
        ))
        .await;
    // Fall back: get the current entry by parsing it from the create
    // response's `log_entry`. Simpler than fetching.
    let _ = (status, get_body);

    let new_doc = json!({
        "@context": ["https://www.w3.org/ns/did/v1"],
        "id": did,
        "verificationMethod": [{
            "id": format!("{did}#key-99"),
            "type": "Multikey",
            "controller": did.clone(),
            "publicKeyMultibase": "z6MkExternalPubForTest"
        }]
    });
    let (status, body) = app
        .request(post_auth(
            &format!("/contexts/update-doc/dids/{scid}/update"),
            &token,
            json!({ "document": new_doc }),
        ))
        .await;
    assert_eq!(status, StatusCode::OK, "update with doc: {status} {body}");
    assert_eq!(
        body["update_keys_count"], 1,
        "auth keys rotated to 1 fresh key"
    );
    assert!(body["new_version_id"].as_str().unwrap().starts_with("2-"));
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn rotate_did_webvh_keys_advances_fragment_ids() {
    let (app, ctx) = TestApp::new().await;
    let (token, scid, _did) = create_test_webvh_did(&app, &ctx, "rotate-frags").await;

    let (status, body) = app
        .request(post_auth(
            &format!("/contexts/rotate-frags/dids/{scid}/rotate-keys"),
            &token,
            json!({ "label": "test rotation" }),
        ))
        .await;
    assert_eq!(status, StatusCode::OK, "rotate-keys: {status} {body}");
    assert!(body["new_version_id"].as_str().unwrap().starts_with("2-"));
    assert_eq!(body["update_keys_count"], 1);
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn update_did_webvh_unknown_scid_returns_404() {
    let (app, ctx) = TestApp::new().await;
    let token = setup_webvh_context(&app, &ctx, "not-here").await;

    let (status, _body) = app
        .request(post_auth(
            "/contexts/not-here/dids/Qnonexistent/update",
            &token,
            json!({ "pre_rotation_count": 0 }),
        ))
        .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn update_did_webvh_invalid_document_returns_400() {
    let (app, ctx) = TestApp::new().await;
    let (token, scid, _did) = create_test_webvh_did(&app, &ctx, "bad-doc").await;

    // id mismatch — caller can't rename a DID via update
    let bad_doc = json!({
        "@context": ["https://www.w3.org/ns/did/v1"],
        "id": "did:webvh:totally-different",
        "verificationMethod": []
    });
    let (status, _body) = app
        .request(post_auth(
            &format!("/contexts/bad-doc/dids/{scid}/update"),
            &token,
            json!({ "document": bad_doc }),
        ))
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
}

// ── DIDComm protocol management (Phase 3 vertical) ────────────────
// Spec: docs/05-design-notes/didcomm-protocol-management.md, criterion #1.
//
// These tests exercise the route → operation path end-to-end through
// the full HTTP stack. The "happy path" (live LogEntry publish with a
// real mediator) requires either a synthetic did:peer:2 mediator with
// an embedded DIDCommMessaging service or an in-process mock mediator —
// that piece lives with the migrate vertical (P4.2) where the same
// machinery serves several tests at once.

#[cfg(feature = "webvh")]
#[tokio::test]
async fn enable_didcomm_unauthenticated_returns_401() {
    let (app, _ctx) = TestApp::new().await;
    let req = Request::builder()
        .method("POST")
        .uri("/services/didcomm/enable")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({ "mediator_did": "did:key:z6MkM" }).to_string(),
        ))
        .unwrap();
    let (status, _body) = app.request(req).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn enable_didcomm_non_super_admin_returns_403() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx
        .auth_token("did:key:z6MkAdmin", "admin", vec!["any".into()])
        .await;
    let (status, _body) = app
        .request(post_auth(
            "/services/didcomm/enable",
            &token,
            json!({ "mediator_did": "did:key:z6MkM" }),
        ))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn enable_didcomm_already_enabled_returns_409_with_suggested_fix() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;
    {
        let mut config = ctx.inner.config.write().await;
        config.services.didcomm = true;
        config.messaging = Some(vti_common::config::MessagingConfig {
            mediator_url: "wss://mediator.example.com".into(),
            mediator_did: "did:peer:2.med".into(),
            mediator_host: None,
        });
    }
    let (status, body) = app
        .request(post_auth(
            "/services/didcomm/enable",
            &token,
            json!({ "mediator_did": "did:key:z6MkBogus" }),
        ))
        .await;
    assert_eq!(status, StatusCode::CONFLICT, "unexpected body: {body}");
    assert_eq!(body["error"], "didcomm_already_enabled");
    assert_eq!(body["mediator_did"], "did:peer:2.med");
    assert!(
        body.get("suggested_fix").and_then(|v| v.as_str()).is_some(),
        "operator-friendly suggested_fix string is required, body: {body}"
    );
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn disable_didcomm_unauthenticated_returns_401() {
    let (app, _ctx) = TestApp::new().await;
    let req = Request::builder()
        .method("POST")
        .uri("/services/didcomm/disable")
        .header("content-type", "application/json")
        .body(Body::from(json!({ "drain_ttl_secs": 0 }).to_string()))
        .unwrap();
    let (status, _body) = app.request(req).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn disable_didcomm_returns_typed_error_body() {
    // The default fixture's vta_did is `did:key:...` which has no
    // webvh record. The operation passes the didcomm-enabled and
    // REST-enabled gates (both true by default) and reaches the
    // VtaDidRecordMissing path → 500 with a typed error body. The
    // contract this test enforces: every failure mode produces a
    // typed error code + human message (no opaque 500s).
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;
    let (_status, body) = app
        .request(post_auth(
            "/services/didcomm/disable",
            &token,
            json!({ "drain_ttl_secs": 0 }),
        ))
        .await;
    assert!(
        body.get("error").and_then(|v| v.as_str()).is_some(),
        "error code in body: {body}"
    );
    assert!(
        body.get("message").and_then(|v| v.as_str()).is_some(),
        "message in body: {body}"
    );
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn drain_cancel_unauthenticated_returns_401() {
    let (app, _ctx) = TestApp::new().await;
    let req = Request::builder()
        .method("POST")
        .uri("/mediators/drain/cancel")
        .header("content-type", "application/json")
        .body(Body::from(json!({ "mediator_did": "did:m:A" }).to_string()))
        .unwrap();
    let (status, _body) = app.request(req).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn drain_cancel_unknown_mediator_returns_typed_error() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;
    let (status, body) = app
        .request(post_auth(
            "/mediators/drain/cancel",
            &token,
            json!({ "mediator_did": "did:m:never-registered" }),
        ))
        .await;
    assert_eq!(status, StatusCode::CONFLICT);
    assert_eq!(
        body.get("error").and_then(|v| v.as_str()),
        Some("not_registered")
    );
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn mediator_report_unauthenticated_returns_401() {
    let (app, _ctx) = TestApp::new().await;
    let req = Request::builder()
        .method("GET")
        .uri("/mediators/report")
        .body(Body::empty())
        .unwrap();
    let (status, _body) = app.request(req).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn mediator_report_returns_empty_report_when_no_traffic() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;
    let req = Request::builder()
        .method("GET")
        .uri("/mediators/report")
        .header("authorization", format!("Bearer {token}"))
        .body(Body::empty())
        .unwrap();
    let (status, body) = app.request(req).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(
        body.get("mediators")
            .and_then(|v| v.as_array())
            .map(Vec::len),
        Some(0)
    );
    assert_eq!(
        body.get("senders").and_then(|v| v.as_array()).map(Vec::len),
        Some(0)
    );
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn update_didcomm_unauthenticated_returns_401() {
    let (app, _ctx) = TestApp::new().await;
    let req = Request::builder()
        .method("POST")
        .uri("/services/didcomm/update")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "new_mediator_did": "did:key:z6MkM",
                "drain_ttl_secs": 3600
            })
            .to_string(),
        ))
        .unwrap();
    let (status, _body) = app.request(req).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn update_didcomm_returns_typed_error_body() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;
    let (_status, body) = app
        .request(post_auth(
            "/services/didcomm/update",
            &token,
            json!({
                "new_mediator_did": "did:key:z6MkBogus",
                "drain_ttl_secs": 3600,
            }),
        ))
        .await;
    assert!(
        body.get("error").and_then(|v| v.as_str()).is_some(),
        "error code in body: {body}"
    );
    assert!(
        body.get("message").and_then(|v| v.as_str()).is_some(),
        "message in body: {body}"
    );
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn rollback_routes_via_migrate_with_rollback_flag() {
    // The rollback CLI alias hits the same endpoint with
    // `rollback: true`. Body shape contract identical to forward
    // migrate.
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;
    let (_status, body) = app
        .request(post_auth(
            "/services/didcomm/update",
            &token,
            json!({
                "new_mediator_did": "did:key:z6MkBogus",
                "drain_ttl_secs": 3600,
                "rollback": true,
            }),
        ))
        .await;
    assert!(
        body.get("error").and_then(|v| v.as_str()).is_some(),
        "error code in body: {body}"
    );
}

#[cfg(feature = "webvh")]
#[tokio::test]
async fn enable_didcomm_propagates_resolve_failure_with_stage() {
    // With a webvh-shaped vta_did + record, the operation reaches
    // the handshake stage. A bogus mediator DID fails resolve and
    // the route maps that to 502 with stage="resolve" so operators
    // can target their fix.
    //
    // Setting up a real webvh vta_did in the fixture is heavyweight
    // (requires create_did_webvh end-to-end). Instead we assert the
    // weaker invariant exercisable here: any failure inside
    // enable_didcomm produces a JSON body with a stable error code,
    // a human-readable message, and (when applicable) a stage
    // field. Stronger handshake-stage assertions live with the
    // P4.2 migrate vertical, which can stand up a synthetic
    // mediator DID alongside its other test machinery.
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:z6MkSuper", "admin", vec![]).await;
    let (_status, body) = app
        .request(post_auth(
            "/services/didcomm/enable",
            &token,
            json!({
                "mediator_did": "did:key:z6MkBogus",
                "force": false,
            }),
        ))
        .await;
    // Body shape contract: typed error code + human-readable message.
    assert!(
        body.get("error").and_then(|v| v.as_str()).is_some(),
        "error code in body: {body}"
    );
    assert!(
        body.get("message").and_then(|v| v.as_str()).is_some(),
        "message in body: {body}"
    );
}

// ── JWT audience isolation ────────────────────────────────────────────
//
// CLAUDE.md identifies cross-audience token rejection as a load-bearing
// invariant: a JWT minted by the VTC service (audience = "VTC") MUST
// NOT authenticate against a VTA route, and vice versa. Tested at the
// JWT-encode/decode layer in `vti-common/src/auth/jwt.rs`; these tests
// run the assertion through the full route stack to catch any
// integration-layer drift (a future refactor that, say, normalises
// audience strings before validation).

#[tokio::test]
async fn vtc_audience_token_rejected_by_vta_route() {
    let (app, ctx) = TestApp::new().await;
    // Mint a token whose `aud` claim is "VTC". The JwtKeys validation
    // path on the VTA side configures `audience = "VTA"` and uses
    // `Validation::set_audience(&["VTA"])`, so the foreign-audience
    // token must be rejected at decode time.
    let foreign_token = ctx.auth_token_with_audience("did:key:z6MkAdmin", "admin", vec![], "VTC");
    let (status, _body) = app.request(get_auth("/contexts", &foreign_token)).await;
    assert_eq!(
        status,
        StatusCode::UNAUTHORIZED,
        "VTC-audience JWT must be rejected by VTA routes"
    );
}

#[tokio::test]
async fn unknown_audience_token_rejected_by_vta_route() {
    // Defence-in-depth: any audience that isn't "VTA" must be rejected,
    // not just the well-known "VTC" string. A future "VTM" service or
    // an attacker-supplied token with a custom audience must never
    // authenticate.
    let (app, ctx) = TestApp::new().await;
    let foreign_token =
        ctx.auth_token_with_audience("did:key:z6MkAdmin", "admin", vec![], "EVIL-SERVICE-V99");
    let (status, _body) = app.request(get_auth("/contexts", &foreign_token)).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

// ── Runtime guards (rate limit + body cap) ─────────────────────────────
//
// Both flagged in CLAUDE.md as load-bearing protections we must never
// silently regress on. One test per bound — burst-then-throttled for the
// per-IP rate limiter, then >1 MB body returns 413 for the global cap.

/// `tower_governor` is wired at 5 req/sec with a 10-burst per source IP
/// across every unauthenticated endpoint. Send 12 requests in a tight
/// loop and assert at least one comes back as 429 — confirming the
/// layer is wired into the router. Without this test, a future router
/// refactor that drops the `GovernorLayer` would silently land.
#[tokio::test]
async fn unauth_endpoint_rate_limit_returns_429_after_burst() {
    let (app, _ctx) = TestApp::new().await;

    // `/auth/challenge` is the canonical unauth route the limiter
    // protects (CLAUDE.md flags this as a load-bearing surface). Send
    // requests serially — the limiter is per-IP, so even concurrent
    // calls would all hash to the same bucket; serial is simpler.
    // `tower::oneshot` doesn't carry a real peer IP; the `SmartIpKey`
    // extractor reads `X-Forwarded-For` / `X-Real-IP` first, then
    // falls back to the connection. Stamp a stable client IP via
    // `X-Forwarded-For` so every request hashes to the same bucket.
    let mut saw_429 = false;
    for _ in 0..20 {
        let req = Request::builder()
            .method("POST")
            .uri("/auth/challenge")
            .header("content-type", "application/json")
            .header("x-forwarded-for", "192.0.2.1")
            .body(Body::from(
                json!({"client_did": "did:key:zTest"}).to_string(),
            ))
            .unwrap();
        let (status, _) = app.request(req).await;
        if status == StatusCode::TOO_MANY_REQUESTS {
            saw_429 = true;
            break;
        }
    }
    assert!(
        saw_429,
        "expected at least one 429 within 20 sequential POST /auth/challenge calls; \
         the GovernorLayer (5 rps + 10 burst) appears to be missing"
    );
}

/// P0.10: the token-gated backup-blob branch must also be rate-limited.
/// Without a token the handler rejects the request, but the governor sits
/// *outside* the handler, so a flood trips 429 before the handler ever
/// runs — proving the branch carries the limiter (it previously did not).
#[tokio::test]
async fn backup_blob_branch_is_rate_limited() {
    let (app, _ctx) = TestApp::new().await;
    let mut saw_429 = false;
    for _ in 0..20 {
        let req = Request::builder()
            .method("GET")
            .uri("/backup/blob/some-bundle-id")
            .header("x-forwarded-for", "192.0.2.7")
            .body(Body::empty())
            .unwrap();
        let (status, _) = app.request(req).await;
        if status == StatusCode::TOO_MANY_REQUESTS {
            saw_429 = true;
            break;
        }
    }
    assert!(
        saw_429,
        "expected a 429 within 20 GET /backup/blob calls; the backup-blob \
         branch is missing its GovernorLayer"
    );
}

/// P0.10: the unauthenticated TEE attestation endpoints (`status`,
/// `report`, `did-log`) were on the main router, bypassing the rate
/// limiter. They now live on the governed `unauth` branch. Flooding
/// `GET /attestation/status` must trip 429 — the governor runs before the
/// handler, so this holds even though the test app has no real TEE state
/// (the handler would otherwise error). Only the super-admin
/// `/attestation/mnemonic` routes stay off the limiter (JWT-gated).
#[cfg(feature = "tee")]
#[tokio::test]
async fn unauth_attestation_status_is_rate_limited() {
    let (app, _ctx) = TestApp::new().await;
    let mut saw_429 = false;
    for _ in 0..20 {
        let req = Request::builder()
            .method("GET")
            .uri("/attestation/status")
            .header("x-forwarded-for", "192.0.2.9")
            .body(Body::empty())
            .unwrap();
        let (status, _) = app.request(req).await;
        if status == StatusCode::TOO_MANY_REQUESTS {
            saw_429 = true;
            break;
        }
    }
    assert!(
        saw_429,
        "expected a 429 within 20 GET /attestation/status calls; the unauth \
         attestation routes are not on the governed branch"
    );
}

/// P0.10: a handler that stalls must not hold its connection forever. The
/// production router wraps every route in a `TimeoutLayer` at
/// `REQUEST_TIMEOUT`; this drives the same layer (at a short, deterministic
/// duration) over a deliberately-slow handler and asserts it returns
/// `408 Request Timeout` rather than hanging.
#[tokio::test]
async fn request_timeout_layer_returns_408_for_slow_handler() {
    use std::time::Duration;
    use tower::ServiceExt;
    use tower_http::timeout::TimeoutLayer;

    let app: axum::Router = axum::Router::new()
        .route(
            "/slow",
            axum::routing::get(|| async {
                tokio::time::sleep(Duration::from_millis(500)).await;
                "should never arrive"
            }),
        )
        .layer(TimeoutLayer::with_status_code(
            StatusCode::REQUEST_TIMEOUT,
            Duration::from_millis(50),
        ));

    let resp = app
        .oneshot(Request::builder().uri("/slow").body(Body::empty()).unwrap())
        .await
        .expect("layer must produce a response, not hang");
    assert_eq!(
        resp.status(),
        StatusCode::REQUEST_TIMEOUT,
        "a handler slower than the timeout must yield 408, not block the connection"
    );
}

/// `MAX_BODY_SIZE` (1 MB) is enforced via axum's `DefaultBodyLimit::max`
/// across every authenticated mutation endpoint. A 1.5 MB body must
/// be rejected with 413 — this is the protection against memory
/// exhaustion CLAUDE.md flags as critical for TEE deployments.
#[tokio::test]
async fn body_cap_returns_413_for_oversized_payload() {
    let (app, ctx) = TestApp::new().await;
    let token = ctx.auth_token("did:key:zAdmin", "admin", vec![]).await;

    // 1.5 MB of 'A' bytes wrapped in a JSON-string envelope so the
    // axum body extractor accepts it as a candidate (rejection happens
    // at the body-limit layer, not at the parser). The total wire
    // body is ~1.5 MB + a few bytes of JSON framing.
    let huge_payload = json!({"data": "A".repeat(1_500_000)});
    let req = Request::builder()
        .method("POST")
        .uri("/contexts")
        .header("Authorization", format!("Bearer {token}"))
        .header("content-type", "application/json")
        .body(Body::from(huge_payload.to_string()))
        .unwrap();
    let (status, _) = app.request(req).await;
    assert_eq!(
        status,
        StatusCode::PAYLOAD_TOO_LARGE,
        "expected 413 Payload Too Large for a 1.5 MB body; the \
         DefaultBodyLimit::max(1 MB) layer appears to be missing"
    );
}