axond 0.3.39

Axond — a stateless, single-binary, self-hosted AI gateway: one place for provider keys, model routing, usage, and telemetry.
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
//! The `/admin/v1` surface, end to end over the mounted route table.
//!
//! Distinct from [`super::tests`], which characterises the service and the
//! router's layers against hand-written test routes: these drive the *real*
//! route table, the real documents, and the real handlers over the in-memory
//! control plane, so the thing under test is what a deployment serves.
//!
//! The through-line is that a document is the only thing a caller supplies: no
//! test here can publish without an idempotency key, an expected revision, and a
//! complete candidate that validates, because the surface offers no other way.

use std::sync::Arc;
use std::time::SystemTime;

use gateway_core::CircuitState;

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

use super::auth::AdminAction;
use super::auth::INFERENCE_KEY_HEADER;
use super::fakes::{CountingStore, FakeAdminAuthenticator, FakeAdminAuthorizer};
use super::protocol::{
    ADMIN_PREFIX, DRY_RUN_HEADER, EXPECTED_REVISION_EMPTY, EXPECTED_REVISION_HEADER,
    IDEMPOTENCY_KEY_HEADER,
};
use super::router::{ADMIN_MAX_REQUEST_BYTES, AdminApi, refusing_router, router};
use super::service::AdminService;
use crate::availability::{
    AvailabilityIndex, AvailabilityKey, AvailabilityReader, AvailabilityRecord, CataloguePresence,
    DiscoveryCompleteness, DiscoveryObservation, DiscoveryResult, DiscoverySource, Enablement,
    Entitlement, PolicyDecision, RuntimeObservations, ScopeRef, TargetRef,
};
use crate::backends::control_plane::ControlPlaneStore;
use crate::backends::fakes::InMemorySecrets;
use crate::desired_state::oracle::InMemoryControlPlane;
use crate::desired_state::{DenialPage, ResourceScope, fixtures};

const TOKEN: &str = "human-admin-token";
const ISSUER: &str = "https://idp.example";
const SUBJECT: &str = "operator@example";

/// One administrative deployment under test: the surface, and the store behind
/// it.
struct Deployment {
    api: Arc<AdminApi>,
    store: Arc<InMemoryControlPlane>,
    secrets: Arc<InMemorySecrets>,
}

impl Deployment {
    fn new() -> Self {
        Self::with_authorizer(FakeAdminAuthorizer::permissive())
    }

    fn with_authorizer(authorizer: FakeAdminAuthorizer) -> Self {
        let store = Arc::new(InMemoryControlPlane::new());
        let secrets = Arc::new(InMemorySecrets::new());
        let api = Arc::new(AdminApi::new(
            Arc::new(AdminService::stateful(store.clone()).with_secrets(secrets.clone())),
            Arc::new(FakeAdminAuthenticator::new().with_human(TOKEN, ISSUER, SUBJECT)),
            Arc::new(authorizer),
        ));
        Self {
            api,
            store,
            secrets,
        }
    }

    /// A call that carries material: no idempotency key and no expected
    /// revision, because storing material publishes no revision.
    async fn post_material(&self, path: &str, body: &Value) -> (StatusCode, Value) {
        self.send(
            Request::post(format!("{ADMIN_PREFIX}{path}"))
                .header(axum::http::header::AUTHORIZATION, format!("Bearer {TOKEN}"))
                .body(Body::from(body.to_string()))
                .expect("a request"),
        )
        .await
    }

    /// Store material, asserting it was stored, and answer with the reference it
    /// was stored under.
    async fn stage(&self, tenant: &str, material: &str) -> String {
        let (status, body) = self
            .post_material(
                "/secrets",
                &json!({ "tenant": tenant, "material": material }),
            )
            .await;
        assert_eq!(status, StatusCode::OK, "staging refused: {body}");
        body["reference"]
            .as_str()
            .expect("a stored reference")
            .to_owned()
    }

    /// A deployment that derives availability: the index a snapshot would carry,
    /// and this replica's own circuits.
    fn deriving(
        authorizer: FakeAdminAuthorizer,
        index: AvailabilityIndex,
        runtime: RuntimeObservations,
    ) -> Self {
        let store = Arc::new(InMemoryControlPlane::new());
        let api = Arc::new(
            AdminApi::new(
                Arc::new(AdminService::stateful(store.clone())),
                Arc::new(FakeAdminAuthenticator::new().with_human(TOKEN, ISSUER, SUBJECT)),
                Arc::new(authorizer),
            )
            .with_availability(Arc::new(StaticAvailability {
                index: Some(Arc::new(index)),
                runtime,
            })),
        );
        Self {
            api,
            store,
            secrets: Arc::new(InMemorySecrets::new()),
        }
    }

    /// A deployment whose availability reader is attached and derives nothing:
    /// the shape every shipped binary currently has, since no compiler is wired
    /// to project a view.
    fn attached_but_underiving() -> Self {
        let store = Arc::new(InMemoryControlPlane::new());
        let api = Arc::new(
            AdminApi::new(
                Arc::new(AdminService::stateful(store.clone())),
                Arc::new(FakeAdminAuthenticator::new().with_human(TOKEN, ISSUER, SUBJECT)),
                Arc::new(FakeAdminAuthorizer::permissive()),
            )
            .with_availability(Arc::new(StaticAvailability {
                index: None,
                runtime: RuntimeObservations::none(),
            })),
        );
        Self {
            api,
            store,
            secrets: Arc::new(InMemorySecrets::new()),
        }
    }

    /// The same control plane, read through a narrower grant: what a tenant
    /// administrator sees of a deployment somebody with deployment authority
    /// built.
    fn narrowed(&self, scopes: &[ResourceScope]) -> Self {
        Self {
            api: Arc::new(AdminApi::new(
                Arc::new(AdminService::stateful(self.store.clone())),
                Arc::new(FakeAdminAuthenticator::new().with_human(TOKEN, ISSUER, SUBJECT)),
                Arc::new(FakeAdminAuthorizer::permissive().within(scopes)),
            )),
            store: self.store.clone(),
            secrets: self.secrets.clone(),
        }
    }

    async fn send(&self, request: Request<Body>) -> (StatusCode, Value) {
        let response = router(self.api.clone())
            .oneshot(request)
            .await
            .expect("a response");
        let status = response.status();
        let body = response
            .into_body()
            .collect()
            .await
            .expect("a body")
            .to_bytes();
        (status, serde_json::from_slice(&body).unwrap_or(Value::Null))
    }

    async fn get(&self, path: &str) -> (StatusCode, Value) {
        self.send(
            Request::get(format!("{ADMIN_PREFIX}{path}"))
                .header(axum::http::header::AUTHORIZATION, format!("Bearer {TOKEN}"))
                .body(Body::empty())
                .expect("a request"),
        )
        .await
    }

    /// A read, with its validator and the raw body: a `304` has no body to
    /// parse, so a conditional read cannot be characterised through
    /// [`Deployment::get`].
    async fn get_conditional(
        &self,
        path: &str,
        if_none_match: Option<&str>,
    ) -> (StatusCode, Option<String>, Vec<u8>) {
        let mut request = Request::get(format!("{ADMIN_PREFIX}{path}"))
            .header(axum::http::header::AUTHORIZATION, format!("Bearer {TOKEN}"));
        if let Some(validator) = if_none_match {
            request = request.header(axum::http::header::IF_NONE_MATCH, validator);
        }
        let response = router(self.api.clone())
            .oneshot(request.body(Body::empty()).expect("a request"))
            .await
            .expect("a response");
        let status = response.status();
        let etag = response
            .headers()
            .get(axum::http::header::ETAG)
            .map(|value| value.to_str().expect("a readable validator").to_owned());
        let body = response
            .into_body()
            .collect()
            .await
            .expect("a body")
            .to_bytes();
        (status, etag, body.to_vec())
    }

    /// A read, with the headers the conditional contract puts on it: the
    /// validator, and the directives that keep a per-caller projection out of a
    /// shared cache.
    async fn get_with_headers(
        &self,
        path: &str,
        if_none_match: Option<&str>,
    ) -> (StatusCode, axum::http::HeaderMap, Vec<u8>) {
        let mut request = Request::get(format!("{ADMIN_PREFIX}{path}"))
            .header(axum::http::header::AUTHORIZATION, format!("Bearer {TOKEN}"));
        if let Some(validator) = if_none_match {
            request = request.header(axum::http::header::IF_NONE_MATCH, validator);
        }
        let response = router(self.api.clone())
            .oneshot(request.body(Body::empty()).expect("a request"))
            .await
            .expect("a response");
        let status = response.status();
        let headers = response.headers().clone();
        let body = response
            .into_body()
            .collect()
            .await
            .expect("a body")
            .to_bytes();
        (status, headers, body.to_vec())
    }

    /// Publish a document, with the preconditions a mutation must carry.
    async fn post(
        &self,
        path: &str,
        key: &str,
        expected: &str,
        body: &Value,
    ) -> (StatusCode, Value) {
        self.post_with(path, key, expected, body, false).await
    }

    async fn dry_run(
        &self,
        path: &str,
        key: &str,
        expected: &str,
        body: &Value,
    ) -> (StatusCode, Value) {
        self.post_with(path, key, expected, body, true).await
    }

    async fn post_with(
        &self,
        path: &str,
        key: &str,
        expected: &str,
        body: &Value,
        dry_run: bool,
    ) -> (StatusCode, Value) {
        let mut request = Request::post(format!("{ADMIN_PREFIX}{path}"))
            .header(axum::http::header::AUTHORIZATION, format!("Bearer {TOKEN}"))
            .header(IDEMPOTENCY_KEY_HEADER, key)
            .header(EXPECTED_REVISION_HEADER, expected);
        if dry_run {
            request = request.header(DRY_RUN_HEADER, "true");
        }
        self.send(
            request
                .body(Body::from(body.to_string()))
                .expect("a request"),
        )
        .await
    }

    /// Publish a document that is expected to succeed, returning the revision it
    /// published — which is the expected revision of whatever comes next.
    async fn publish(&self, path: &str, key: &str, expected: &str, body: &Value) -> String {
        let (status, response) = self.post(path, key, expected, body).await;
        assert_eq!(status, StatusCode::OK, "{path} refused: {response}");
        assert_eq!(response["result"], "published", "{path}: {response}");
        response["revision"]
            .as_str()
            .expect("a published revision")
            .to_owned()
    }
}

// ---------------------------------------------------------------------------
// The documents, as a caller writes them
// ---------------------------------------------------------------------------

fn tenant_document() -> Value {
    json!({
        "summary": "onboard the acme tenant",
        "mutation": "create",
        "resource": {
            "tenant": fixtures::tenant_id(1).to_string(),
            "slug": "acme",
            "display_name": "Acme",
        }
    })
}

fn project_document() -> Value {
    json!({
        "summary": "add acme's production project",
        "mutation": "create",
        "resource": {
            "project": fixtures::project_id(2).to_string(),
            "tenant": fixtures::tenant_id(1).to_string(),
            "slug": "production",
            "display_name": "Production",
        }
    })
}

fn provider_document() -> Value {
    json!({
        "summary": "connect acme to openai",
        "mutation": "create",
        "resource": {
            "provider": fixtures::resource_id(10).to_string(),
            "tenant": fixtures::tenant_id(1).to_string(),
            "slug": "openai",
            "display_name": "OpenAI",
            "wire_family": "openai-chat",
            "endpoint": "https://api.openai.com",
        }
    })
}

fn credential_document() -> Value {
    json!({
        "summary": "stage acme's openai key",
        "mutation": "create",
        "resource": {
            "credential": fixtures::resource_id(11).to_string(),
            "tenant": fixtures::tenant_id(1).to_string(),
            "provider": fixtures::resource_id(10).to_string(),
            "slug": "openai-primary",
            "display_name": "OpenAI primary",
            "secret": fixtures::secret_id(12).to_string(),
        }
    })
}

fn catalog_document() -> Value {
    let blob = *fixtures::blob_backed_catalog(13)
        .body
        .blob()
        .expect("a blob body");
    json!({
        "summary": "import the openai catalogue",
        "mutation": "create",
        "resource": {
            "catalog": fixtures::resource_id(13).to_string(),
            "slug": "openai-models",
            "digest": blob.digest.to_string(),
            "size_bytes": blob.size_bytes,
        }
    })
}

fn model_document() -> Value {
    json!({
        "summary": "enable gpt-4o for acme",
        "mutation": "create",
        "resource": {
            "enablement": fixtures::resource_id(14).to_string(),
            "tenant": fixtures::tenant_id(1).to_string(),
            "slug": "gpt-4o",
            "offering": fixtures::offering_id("gpt-4o").to_string(),
            "catalog": fixtures::resource_id(13).to_string(),
            "snapshot": fixtures::catalog_snapshot().to_string(),
            "wire_family": "openai-chat",
        }
    })
}

fn alias_document() -> Value {
    json!({
        "summary": "point acme's default alias at gpt-4o",
        "mutation": "create",
        "resource": {
            "alias": fixtures::resource_id(15).to_string(),
            "tenant": fixtures::tenant_id(1).to_string(),
            "project": fixtures::project_id(2).to_string(),
            "slug": "default",
            "wire_family": "openai-chat",
            "targets": [{ "enablement": fixtures::resource_id(14).to_string() }],
        }
    })
}

fn policy_document() -> Value {
    json!({
        "summary": "cap acme's spend and concurrency",
        "resource": {
            "tenant": fixtures::tenant_id(1).to_string(),
            "slug": "acme-limits",
            "epoch": 1,
            "subject_limit_microdollars": 50_000_000u64,
            "namespace_limit_microdollars": 500_000_000u64,
            "reservation_ttl_seconds": 300,
            "max_in_flight_per_subject": 8,
            "lease_ttl_seconds": 60,
        }
    })
}

/// The whole deployment, in the order an operator builds it: each document
/// published against the revision the previous one produced.
async fn build(deployment: &Deployment) -> String {
    let documents = [
        ("/tenants", tenant_document()),
        ("/projects", project_document()),
        ("/providers", provider_document()),
        ("/credentials", credential_document()),
        ("/catalogs", catalog_document()),
        ("/models", model_document()),
        ("/aliases", alias_document()),
        ("/policies", policy_document()),
    ];
    let mut expected = EXPECTED_REVISION_EMPTY.to_owned();
    for (index, (path, document)) in documents.iter().enumerate() {
        expected = deployment
            .publish(path, &format!("key-{index}"), &expected, document)
            .await;
    }
    expected
}

// ---------------------------------------------------------------------------
// Building a deployment
// ---------------------------------------------------------------------------

#[tokio::test]
async fn every_resource_family_publishes_and_is_readable_as_state() {
    let deployment = Deployment::new();
    let head = build(&deployment).await;
    assert_eq!(deployment.store.published_revisions(), 8);

    let (status, state) = deployment.get("/state").await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(state["revision"], head);
    let kinds: Vec<&str> = state["resources"]
        .as_array()
        .expect("resources")
        .iter()
        .map(|resource| resource["kind"].as_str().expect("a kind"))
        .collect();
    for kind in [
        "tenant",
        "project",
        "provider",
        "provider-credential",
        "catalog-model",
        "model-enablement",
        "alias",
        "policy",
    ] {
        assert!(kinds.contains(&kind), "{kind} is missing from {kinds:?}");
    }
    // A state read describes bodies, never renders them: no secret reference's
    // material, and no body payload, can appear in the projection.
    let rendered = state.to_string();
    assert!(!rendered.contains("secret_material"), "{rendered}");
}

/// Republishing a credential reauthors it: the document is the complete
/// credential, so a repointed secret takes effect — and takes the credential
/// back to `staged`, because material serves only after a candidate compiles
/// against it.
#[tokio::test]
async fn republishing_a_credential_repoints_it_at_the_material_the_document_names() {
    let deployment = Deployment::new();
    let mut head = deployment
        .publish(
            "/tenants",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &tenant_document(),
        )
        .await;
    head = deployment
        .publish("/providers", "key-2", &head, &provider_document())
        .await;
    head = deployment
        .publish("/credentials", "key-3", &head, &credential_document())
        .await;

    let mut repointed = credential_document();
    repointed["mutation"] = json!("update");
    repointed["resource"]["display_name"] = json!("OpenAI rotated");
    repointed["resource"]["secret"] = fixtures::secret_id(13).to_string().into();
    let head = deployment
        .publish("/credentials", "key-4", &head, &repointed)
        .await;

    let loaded = deployment
        .store
        .load_revision(crate::desired_state::RevisionId::parse(&head).expect("a revision"))
        .await
        .expect("the published revision hydrates");
    let credential = loaded
        .state()
        .version_of(
            crate::desired_state::ResourceKind::ProviderCredential,
            fixtures::resource_id(11),
        )
        .expect("the credential is desired");
    let body =
        crate::desired_state::ProviderCredentialBody::read(credential).expect("a credential body");
    assert_eq!(body.secret().secret, fixtures::secret_id(13));
    assert_eq!(body.display_name().as_str(), "OpenAI rotated");
    assert_eq!(
        body.lifecycle(),
        crate::desired_state::SecretLifecycle::Staged
    );
}

/// Rotation advances the version the credential is *in*, not the one the
/// document spells. The document names a credential, and `secret_version` is
/// optional, so rotating from a body already past its first version must not
/// fall back to the document's default and hand an operator an older secret
/// under the name of a rotation.
#[tokio::test]
async fn rotating_a_credential_advances_the_version_currently_in_force() {
    let deployment = Deployment::new();
    let mut head = deployment
        .publish(
            "/tenants",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &tenant_document(),
        )
        .await;
    head = deployment
        .publish("/providers", "key-2", &head, &provider_document())
        .await;
    head = deployment
        .publish("/credentials", "key-3", &head, &credential_document())
        .await;

    let mut rotate = credential_document();
    rotate["mutation"] = json!("update");
    rotate["resource"]["rotate"] = json!(true);
    for (key, expected) in [2_u64, 3, 4].into_iter().enumerate() {
        head = deployment
            .publish("/credentials", &format!("key-{}", key + 4), &head, &rotate)
            .await;
        assert_eq!(
            credential_secret(&deployment, &head).await.version.get(),
            expected,
            "each rotation advances from the version in force"
        );
    }

    // The material a rotation lands on is staged: rotation stores material, and
    // putting it in service stays a separate decision.
    let loaded = deployment
        .store
        .load_revision(crate::desired_state::RevisionId::parse(&head).expect("a revision"))
        .await
        .expect("the published revision hydrates");
    let credential = loaded
        .state()
        .version_of(
            crate::desired_state::ResourceKind::ProviderCredential,
            fixtures::resource_id(11),
        )
        .expect("the credential is desired");
    let body =
        crate::desired_state::ProviderCredentialBody::read(credential).expect("a credential body");
    assert_eq!(
        body.lifecycle(),
        crate::desired_state::SecretLifecycle::Staged
    );
    assert_eq!(body.secret().secret, fixtures::secret_id(12));
}

/// An edit that says nothing about material must not move any: `secret_version`
/// is unstated when omitted, not "version 1". A rename that republished a
/// rotated credential at v1 would re-stage it — taking the credential out of
/// service — and nothing in the document would have said so.
#[tokio::test]
async fn editing_a_credential_without_a_version_keeps_the_one_in_force() {
    let deployment = Deployment::new();
    let mut head = deployment
        .publish(
            "/tenants",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &tenant_document(),
        )
        .await;
    head = deployment
        .publish("/providers", "key-2", &head, &provider_document())
        .await;
    head = deployment
        .publish("/credentials", "key-3", &head, &credential_document())
        .await;

    let mut rotate = credential_document();
    rotate["mutation"] = json!("update");
    rotate["resource"]["rotate"] = json!(true);
    head = deployment
        .publish("/credentials", "key-4", &head, &rotate)
        .await;

    let mut activate = credential_document();
    activate["mutation"] = json!("update");
    activate["resource"]["lifecycle"] = json!("active");
    head = deployment
        .publish("/credentials", "key-5", &head, &activate)
        .await;

    let mut renamed = credential_document();
    renamed["mutation"] = json!("update");
    renamed["resource"]["display_name"] = json!("OpenAI primary (eu)");
    head = deployment
        .publish("/credentials", "key-6", &head, &renamed)
        .await;

    let body = credential_body(&deployment, &head).await;
    assert_eq!(
        body.secret().version.get(),
        2,
        "a rename says nothing about material, so the version in force stands"
    );
    assert_eq!(
        body.lifecycle(),
        crate::desired_state::SecretLifecycle::Active,
        "and the credential stays in service"
    );
    assert_eq!(body.display_name().as_str(), "OpenAI primary (eu)");
}

/// The credential fixture's body at `head`.
async fn credential_body(
    deployment: &Deployment,
    head: &str,
) -> crate::desired_state::ProviderCredentialBody {
    let loaded = deployment
        .store
        .load_revision(crate::desired_state::RevisionId::parse(head).expect("a revision"))
        .await
        .expect("the published revision hydrates");
    let credential = loaded
        .state()
        .version_of(
            crate::desired_state::ResourceKind::ProviderCredential,
            fixtures::resource_id(11),
        )
        .expect("the credential is desired");
    crate::desired_state::ProviderCredentialBody::read(credential).expect("a credential body")
}

/// The secret reference the credential fixture's resource holds at `head`.
async fn credential_secret(deployment: &Deployment, head: &str) -> crate::desired_state::SecretRef {
    let loaded = deployment
        .store
        .load_revision(crate::desired_state::RevisionId::parse(head).expect("a revision"))
        .await
        .expect("the published revision hydrates");
    let credential = loaded
        .state()
        .version_of(
            crate::desired_state::ResourceKind::ProviderCredential,
            fixtures::resource_id(11),
        )
        .expect("the credential is desired");
    crate::desired_state::ProviderCredentialBody::read(credential)
        .expect("a credential body")
        .secret()
}

/// A resource other resources pin can still be advanced. Dependency edges name
/// an exact version and one request publishes one resource, so the candidate
/// carries the dependents forward itself rather than leaving an operator with a
/// deployment that can never be changed again.
#[tokio::test]
async fn advancing_a_resource_other_resources_pin_carries_those_resources_forward() {
    let deployment = Deployment::new();
    let mut head = build(&deployment).await;

    let mut disabled = model_document();
    disabled["mutation"] = json!("update");
    disabled["resource"]["state"] = json!("disabled");
    let (status, outcome) = deployment
        .post("/models", "key-model-2", &head, &disabled)
        .await;
    assert_eq!(status, StatusCode::OK, "{outcome}");
    let retired_revision = outcome["revision"].as_str().expect("a revision").to_owned();
    let alias_delta = outcome["diff"]["resources"]
        .as_array()
        .expect("resource diff")
        .iter()
        .find(|delta| delta["kind"] == "alias")
        .expect("the implicitly retired alias is in the revision diff");
    assert_eq!(alias_delta["change"], "updated");
    let (status, audit) = deployment.get(&format!("/audit/{retired_revision}")).await;
    assert_eq!(status, StatusCode::OK, "{audit}");
    assert_eq!(audit["events"].as_array().expect("audit events").len(), 1);
    head = retired_revision;

    let mut reimported = catalog_document();
    reimported["mutation"] = json!("update");
    reimported["resource"]["size_bytes"] = json!(4_096);
    head = deployment
        .publish("/catalogs", "key-catalog-2", &head, &reimported)
        .await;

    let loaded = deployment
        .store
        .load_revision(crate::desired_state::RevisionId::parse(&head).expect("a revision"))
        .await
        .expect("the published revision hydrates");
    let state = loaded.state();
    let alias = state
        .version_of(
            crate::desired_state::ResourceKind::Alias,
            fixtures::resource_id(15),
        )
        .expect("the alias is desired");
    let alias_body = crate::desired_state::ModelAliasBody::read(alias).expect("an alias body");
    assert_eq!(
        (alias_body.is_enabled(), alias_body.targets().len()),
        (false, 0),
        "retiring the last target retires the alias in the same revision"
    );
    // A stale alias write cannot reactivate a name against the retired model.
    let (status, error) = deployment
        .post("/aliases", "key-alias-2", &head, &alias_document())
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "{error}");
    assert_eq!(error["error"]["type"], "validation_failed", "{error}");
}

#[tokio::test]
async fn republishing_an_already_disabled_enablement_preserves_a_disabled_alias_target() {
    let deployment = Deployment::new();
    let mut head = build(&deployment).await;

    let mut disable_model = model_document();
    disable_model["mutation"] = json!("update");
    disable_model["resource"]["state"] = json!("disabled");
    head = deployment
        .publish("/models", "key-model-disable", &head, &disable_model)
        .await;

    // An explicitly disabled alias may retain a historical target. This is the
    // legacy shape restack must preserve when the already-disabled enablement is
    // republished for metadata or catalogue carry-forward.
    let mut disabled_alias = alias_document();
    disabled_alias["mutation"] = json!("update");
    disabled_alias["resource"]["state"] = json!("disabled");
    disabled_alias["resource"]["targets"] =
        json!([{ "enablement": fixtures::resource_id(14).to_string(), "version": 2 }]);
    head = deployment
        .publish(
            "/aliases",
            "key-alias-legacy-target",
            &head,
            &disabled_alias,
        )
        .await;

    let mut republish_disabled = model_document();
    republish_disabled["mutation"] = json!("update");
    republish_disabled["resource"]["state"] = json!("disabled");
    republish_disabled["resource"]["observed_input_micros_per_million"] = json!(3_000);
    republish_disabled["resource"]["observed_output_micros_per_million"] = json!(2_000);
    let (status, outcome) = deployment
        .post(
            "/models",
            "key-model-republish-disabled",
            &head,
            &republish_disabled,
        )
        .await;
    assert_eq!(status, StatusCode::OK, "{outcome}");
    let next = outcome["revision"].as_str().expect("a revision").to_owned();

    let loaded = deployment
        .store
        .load_revision(crate::desired_state::RevisionId::parse(&next).expect("a revision"))
        .await
        .expect("the republished revision hydrates");
    let alias = loaded
        .state()
        .version_of(
            crate::desired_state::ResourceKind::Alias,
            fixtures::resource_id(15),
        )
        .expect("the alias is desired");
    let body = crate::desired_state::ModelAliasBody::read(alias).expect("an alias body");
    assert!(!body.is_enabled());
    assert_eq!(
        body.targets(),
        &[crate::desired_state::AliasTarget::new(
            fixtures::resource_id(14),
            crate::desired_state::ResourceVersionNumber::new(3).expect("version"),
        )],
        "republication is not an enabled -> disabled transition"
    );

    // The complete revision/diff is the resource-level audit plan: the alias
    // retirement is visible alongside the mutation-intent audit event.
    let alias_delta = outcome["diff"]["resources"]
        .as_array()
        .expect("resource diff")
        .iter()
        .find(|delta| delta["kind"] == "alias")
        .expect("the carried alias is recorded in the revision diff");
    assert_eq!(alias_delta["change"], "updated");
    let (status, audit) = deployment.get(&format!("/audit/{next}")).await;
    assert_eq!(status, StatusCode::OK, "{audit}");
    assert_eq!(
        audit["events"].as_array().expect("audit events").len(),
        1,
        "one mutation event owns the revision"
    );
}

#[tokio::test]
async fn disabling_an_enablement_preserves_targets_of_a_disabled_alias() {
    let deployment = Deployment::new();
    let mut head = build(&deployment).await;

    let mut disabled_alias = alias_document();
    disabled_alias["mutation"] = json!("update");
    disabled_alias["resource"]["state"] = json!("disabled");
    head = deployment
        .publish(
            "/aliases",
            "key-alias-disabled-history",
            &head,
            &disabled_alias,
        )
        .await;

    let mut disable_model = model_document();
    disable_model["mutation"] = json!("update");
    disable_model["resource"]["state"] = json!("disabled");
    head = deployment
        .publish(
            "/models",
            "key-model-disable-history",
            &head,
            &disable_model,
        )
        .await;

    let loaded = deployment
        .store
        .load_revision(crate::desired_state::RevisionId::parse(&head).expect("a revision"))
        .await
        .expect("the retirement revision hydrates");
    let alias = loaded
        .state()
        .version_of(
            crate::desired_state::ResourceKind::Alias,
            fixtures::resource_id(15),
        )
        .expect("the disabled alias is retained");
    let body = crate::desired_state::ModelAliasBody::read(alias).expect("an alias body");
    assert!(!body.is_enabled());
    assert_eq!(
        body.targets().len(),
        1,
        "disabled alias history is retained"
    );
    assert_eq!(body.targets()[0].version.get(), 2);
}

#[tokio::test]
async fn disabling_an_alias_can_clear_targets_in_one_revision() {
    let deployment = Deployment::new();
    let mut head = build(&deployment).await;
    let mut disabled = alias_document();
    disabled["mutation"] = json!("update");
    disabled["resource"]["state"] = json!("disabled");
    disabled["resource"]["targets"] = json!([]);

    head = deployment
        .publish("/aliases", "key-alias-disable", &head, &disabled)
        .await;

    let loaded = deployment
        .store
        .load_revision(crate::desired_state::RevisionId::parse(&head).expect("a revision"))
        .await
        .expect("the published revision hydrates");
    let alias = loaded
        .state()
        .version_of(
            crate::desired_state::ResourceKind::Alias,
            fixtures::resource_id(15),
        )
        .expect("the disabled alias is retained");
    let body = crate::desired_state::ModelAliasBody::read(alias).expect("an alias body");
    assert!(!body.is_enabled());
    assert!(body.targets().is_empty());
}

/// A refreshed catalogue is a new snapshot, and an enablement's snapshot is part
/// of what it is: re-importing different content under a row an enablement reads
/// from is refused by name, rather than published into a state whose pins no
/// longer resolve.
#[tokio::test]
async fn refreshing_a_catalogue_an_enablement_reads_from_is_refused_by_name() {
    let deployment = Deployment::new();
    let head = build(&deployment).await;

    let refreshed = *fixtures::second_blob_backed_catalog(23)
        .body
        .blob()
        .expect("a blob body");
    let mut reimported = catalog_document();
    reimported["mutation"] = json!("update");
    reimported["resource"]["digest"] = refreshed.digest.to_string().into();
    reimported["resource"]["size_bytes"] = json!(refreshed.size_bytes);

    let (status, error) = deployment
        .post("/catalogs", "key-catalog-refresh", &head, &reimported)
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "{error}");
    assert_eq!(error["error"]["type"], "validation_failed", "{error}");
    assert_eq!(
        error["error"]["rule"], "pinned_snapshot_withdrawn",
        "the refusal names why, not just that: {error}"
    );
    assert_eq!(
        deployment.store.published_revisions(),
        8,
        "a refused candidate publishes nothing"
    );
}

/// The way through the refusal above: the refreshed snapshot arrives as its own
/// catalogue resource, and offerings are enabled against it, leaving the
/// enablements that read the old snapshot to be retired on their own schedule.
#[tokio::test]
async fn a_refreshed_catalogue_is_imported_as_its_own_resource_and_enabled_against() {
    let deployment = Deployment::new();
    let mut head = build(&deployment).await;

    let refreshed = *fixtures::second_blob_backed_catalog(23)
        .body
        .blob()
        .expect("a blob body");
    let mut imported = catalog_document();
    imported["resource"]["catalog"] = fixtures::resource_id(23).to_string().into();
    imported["resource"]["slug"] = json!("openai-models-2026-08");
    imported["resource"]["digest"] = refreshed.digest.to_string().into();
    imported["resource"]["size_bytes"] = json!(refreshed.size_bytes);
    head = deployment
        .publish("/catalogs", "key-catalog-refresh", &head, &imported)
        .await;

    let mut disabled = model_document();
    disabled["mutation"] = json!("update");
    disabled["resource"]["state"] = json!("disabled");
    head = deployment
        .publish("/models", "key-model-retire", &head, &disabled)
        .await;

    let mut enabled = model_document();
    enabled["resource"]["enablement"] = fixtures::resource_id(24).to_string().into();
    enabled["resource"]["slug"] = json!("gpt-4o-2026-08");
    enabled["resource"]["catalog"] = fixtures::resource_id(23).to_string().into();
    enabled["resource"]["snapshot"] = refreshed.digest.to_string().into();
    head = deployment
        .publish("/models", "key-model-refresh", &head, &enabled)
        .await;

    let mut retargeted = alias_document();
    retargeted["mutation"] = json!("update");
    retargeted["resource"]["targets"] =
        json!([{ "enablement": fixtures::resource_id(24).to_string() }]);
    let head = deployment
        .publish("/aliases", "key-alias-refresh", &head, &retargeted)
        .await;

    let loaded = deployment
        .store
        .load_revision(crate::desired_state::RevisionId::parse(&head).expect("a revision"))
        .await
        .expect("the published revision hydrates");
    let state = loaded.state();
    let enablement = state
        .version_of(
            crate::desired_state::ResourceKind::ModelEnablement,
            fixtures::resource_id(24),
        )
        .expect("the refreshed enablement is desired");
    let body =
        crate::desired_state::ModelEnablementBody::read(enablement).expect("an enablement body");
    assert!(
        body.offering().is_pinned_to(refreshed.digest),
        "the new enablement reads the refreshed snapshot"
    );
    let alias = state
        .version_of(
            crate::desired_state::ResourceKind::Alias,
            fixtures::resource_id(15),
        )
        .expect("the alias is desired");
    let alias_body = crate::desired_state::ModelAliasBody::read(alias).expect("an alias body");
    assert_eq!(
        alias_body.primary().expect("a target").enablement,
        fixtures::resource_id(24),
        "the alias serves the refreshed enablement"
    );
}

#[tokio::test]
async fn a_second_publication_of_a_resource_supersedes_it_rather_than_duplicating_it() {
    let deployment = Deployment::new();
    let head = deployment
        .publish(
            "/tenants",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &tenant_document(),
        )
        .await;
    let mut renamed = tenant_document();
    renamed["resource"]["display_name"] = json!("Acme Corporation");
    renamed["mutation"] = json!("update");
    deployment
        .publish("/tenants", "key-2", &head, &renamed)
        .await;

    let (_, state) = deployment.get("/state").await;
    let tenants: Vec<&Value> = state["resources"]
        .as_array()
        .expect("resources")
        .iter()
        .filter(|resource| resource["kind"] == "tenant")
        .collect();
    assert_eq!(tenants.len(), 1, "the tenant was duplicated: {tenants:?}");
    assert_eq!(tenants[0]["version"], 2);
}

// ---------------------------------------------------------------------------
// Preconditions: conflict, replay, reuse
// ---------------------------------------------------------------------------

#[tokio::test]
async fn a_stale_expected_revision_is_a_conflict_that_names_the_head() {
    let deployment = Deployment::new();
    let head = deployment
        .publish(
            "/tenants",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &tenant_document(),
        )
        .await;

    // A second writer, still holding "the control plane is empty".
    let (status, body) = deployment
        .post(
            "/projects",
            "key-2",
            EXPECTED_REVISION_EMPTY,
            &project_document(),
        )
        .await;
    assert_eq!(status, StatusCode::CONFLICT, "{body}");
    assert_eq!(body["error"]["type"], "revision_conflict");
    assert_eq!(body["error"]["revision"], head);
    assert_eq!(deployment.store.published_revisions(), 1);

    // Re-read, retry: the same document lands against the head it conflicted on.
    deployment
        .publish("/projects", "key-3", &head, &project_document())
        .await;
}

#[tokio::test]
async fn a_lost_response_is_replayed_rather_than_published_twice() {
    let deployment = Deployment::new();
    let first = deployment
        .publish(
            "/tenants",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &tenant_document(),
        )
        .await;

    // The client never saw the response and retries byte-for-byte, including the
    // expected revision it was written against.
    let (status, body) = deployment
        .post(
            "/tenants",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &tenant_document(),
        )
        .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["result"], "replayed");
    assert_eq!(body["revision"], first);
    assert_eq!(
        deployment.store.published_revisions(),
        1,
        "a retry published a second revision"
    );
}

#[tokio::test]
async fn an_idempotency_key_cannot_be_spent_on_a_different_candidate() {
    let deployment = Deployment::new();
    deployment
        .publish(
            "/tenants",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &tenant_document(),
        )
        .await;

    let mut different = tenant_document();
    different["resource"]["display_name"] = json!("Not Acme");
    let (status, body) = deployment
        .post("/tenants", "key-1", EXPECTED_REVISION_EMPTY, &different)
        .await;
    assert_eq!(status, StatusCode::CONFLICT);
    assert_eq!(body["error"]["type"], "idempotency_key_reused");
    assert_eq!(deployment.store.published_revisions(), 1);
}

// ---------------------------------------------------------------------------
// Dry run
// ---------------------------------------------------------------------------

#[tokio::test]
async fn a_dry_run_diffs_the_candidate_and_leaves_the_store_untouched() {
    let deployment = Deployment::new();
    let (status, body) = deployment
        .dry_run(
            "/tenants",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &tenant_document(),
        )
        .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["result"], "dry_run");
    assert_eq!(body["mode"], "dry-run");
    assert_eq!(body["diff"]["summary"]["added"], 1);
    assert!(body.get("revision").is_none());
    assert_eq!(deployment.store.published_revisions(), 0);

    // And the key it rehearsed with is still spendable: a rehearsal consumes
    // nothing.
    deployment
        .publish(
            "/tenants",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &tenant_document(),
        )
        .await;
}

#[tokio::test]
async fn a_dry_run_of_an_invalid_candidate_refuses_without_publishing() {
    let deployment = Deployment::new();
    let (status, body) = deployment
        .dry_run(
            "/models",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &model_document(),
        )
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_eq!(body["error"]["type"], "validation_failed");
    assert_eq!(deployment.store.published_revisions(), 0);
}

// ---------------------------------------------------------------------------
// Invalid graphs and malformed documents
// ---------------------------------------------------------------------------

#[tokio::test]
async fn an_enablement_pinning_a_catalogue_that_is_not_published_is_refused() {
    let deployment = Deployment::new();
    let head = deployment
        .publish(
            "/tenants",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &tenant_document(),
        )
        .await;
    // The catalogue row this enablement depends on was never imported.
    let (status, body) = deployment
        .post("/models", "key-2", &head, &model_document())
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_eq!(body["error"]["type"], "validation_failed");
    assert_eq!(deployment.store.published_revisions(), 1);
}

#[tokio::test]
async fn an_alias_whose_target_does_not_exist_is_refused() {
    let deployment = Deployment::new();
    let mut head = deployment
        .publish(
            "/tenants",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &tenant_document(),
        )
        .await;
    head = deployment
        .publish("/projects", "key-2", &head, &project_document())
        .await;
    let (status, body) = deployment
        .post("/aliases", "key-3", &head, &alias_document())
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_eq!(body["error"]["type"], "validation_failed");
    assert_eq!(deployment.store.published_revisions(), 2);
}

#[tokio::test]
async fn a_document_that_is_not_its_schema_is_refused_before_the_control_plane() {
    let store = Arc::new(InMemoryControlPlane::new());
    let counting = Arc::new(CountingStore::new(store.clone()));
    let api = Arc::new(AdminApi::new(
        Arc::new(AdminService::stateful(counting.clone())),
        Arc::new(FakeAdminAuthenticator::new().with_human(TOKEN, ISSUER, SUBJECT)),
        Arc::new(FakeAdminAuthorizer::permissive()),
    ));
    let deployment = Deployment {
        api,
        store,
        secrets: Arc::new(InMemorySecrets::new()),
    };

    let cases = [
        // An unknown field is a typo the caller must see, not an omission to
        // publish silently.
        (
            json!({
                "summary": "onboard acme",
                "resource": {
                    "tenant": fixtures::tenant_id(1).to_string(),
                    "slug": "acme",
                    "display_name": "Acme",
                    "lifecycle_state": "active",
                }
            }),
            "admin_request_invalid",
        ),
        // An id that is not one.
        (
            json!({
                "summary": "onboard acme",
                "resource": {
                    "tenant": "acme",
                    "slug": "acme",
                    "display_name": "Acme",
                }
            }),
            "admin_request_invalid",
        ),
        // A value a future build might know, and this one does not.
        (
            json!({
                "summary": "onboard acme",
                "resource": {
                    "tenant": fixtures::tenant_id(1).to_string(),
                    "slug": "acme",
                    "display_name": "Acme",
                    "lifecycle": "hibernating",
                }
            }),
            "admin_request_invalid",
        ),
        // A summary is required: an audit trail of empty strings is not one.
        (
            json!({
                "summary": "",
                "resource": {
                    "tenant": fixtures::tenant_id(1).to_string(),
                    "slug": "acme",
                    "display_name": "Acme",
                }
            }),
            "audit_summary_invalid",
        ),
    ];
    for (document, code) in cases {
        let (status, body) = deployment
            .post("/tenants", "key-1", EXPECTED_REVISION_EMPTY, &document)
            .await;
        assert_eq!(body["error"]["type"], code, "{status}: {body}");
    }
    assert_eq!(
        counting.calls(),
        0,
        "a document this build cannot read reached the control plane"
    );
}

/// The budget settings share one lower bound, and so do the concurrency ones,
/// so a refusal that named the last one checked would send an administrator to
/// edit a field that was right: the message names the setting they actually set
/// to zero.
#[tokio::test]
async fn a_zero_budget_cap_is_refused_against_the_setting_the_caller_wrote() {
    let deployment = Deployment::new();
    let cases = [
        ("subject_limit_microdollars", json!(0)),
        ("namespace_limit_microdollars", json!(0)),
        ("reservation_ttl_seconds", json!(0)),
        ("max_in_flight_per_subject", json!(0)),
        ("lease_ttl_seconds", json!(0)),
    ];
    for (field, value) in cases {
        let mut document = policy_document();
        document["resource"][field] = value;
        let (status, body) = deployment
            .post("/policies", "key-1", EXPECTED_REVISION_EMPTY, &document)
            .await;
        assert_eq!(status, StatusCode::BAD_REQUEST, "{field}: {body}");
        assert_eq!(body["error"]["type"], "admin_request_invalid", "{body}");
        let message = body["error"]["message"]
            .as_str()
            .unwrap_or_else(|| panic!("{field}: a message naming the field"));
        assert!(
            message.contains(&format!("`{field}`")),
            "{field} was set to zero, and the refusal says: {message}"
        );
    }
}

/// Nothing here removes a resource, so the audit trail may not say one was
/// removed: `delete` is accepted only for a document that retires the resource
/// through its own lifecycle, and refused for one that leaves it serving.
#[tokio::test]
async fn a_deletion_must_retire_the_resource_it_claims_to_delete() {
    let deployment = Deployment::new();
    let mut head = deployment
        .publish(
            "/tenants",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &tenant_document(),
        )
        .await;

    let mut renamed = tenant_document();
    renamed["mutation"] = json!("delete");
    renamed["resource"]["display_name"] = json!("Acme, retired");
    let (status, body) = deployment.post("/tenants", "key-2", &head, &renamed).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_eq!(body["error"]["type"], "admin_request_invalid");

    let mut deleted = tenant_document();
    deleted["mutation"] = json!("delete");
    deleted["resource"]["lifecycle"] = json!("deleted");
    head = deployment
        .publish("/tenants", "key-3", &head, &deleted)
        .await;

    let (status, audit) = deployment.get(&format!("/audit/{head}")).await;
    assert_eq!(status, StatusCode::OK, "{audit}");
    assert_eq!(audit["events"][0]["kind"], "delete", "{audit}");
}

/// A handler parses a document whole, so the surface declares how much it will
/// buffer — and refuses the excess in its own envelope, before anything is
/// parsed or the control plane is touched.
#[tokio::test]
async fn an_oversized_document_is_refused_in_the_administrative_envelope() {
    let store = Arc::new(InMemoryControlPlane::new());
    let counting = Arc::new(CountingStore::new(store.clone()));
    let api = Arc::new(AdminApi::new(
        Arc::new(AdminService::stateful(counting.clone())),
        Arc::new(FakeAdminAuthenticator::new().with_human(TOKEN, ISSUER, SUBJECT)),
        Arc::new(FakeAdminAuthorizer::permissive()),
    ));
    let deployment = Deployment {
        api,
        store,
        secrets: Arc::new(InMemorySecrets::new()),
    };
    let mut document = tenant_document();
    document["summary"] = json!("x".repeat(ADMIN_MAX_REQUEST_BYTES + 1));

    let (status, body) = deployment
        .post("/tenants", "key-1", EXPECTED_REVISION_EMPTY, &document)
        .await;

    assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
    assert_eq!(body["error"]["type"], "admin_request_too_large");
    assert_eq!(
        counting.calls(),
        0,
        "an oversized body reached the control plane"
    );
}

#[tokio::test]
async fn an_unknown_administrative_path_answers_in_the_administrative_envelope() {
    let deployment = Deployment::new();
    let (status, body) = deployment.get("/tenants").await;
    assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
    assert_eq!(body["error"]["type"], "admin_method_not_allowed");

    let (status, body) = deployment.get("/nonexistent").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert_eq!(body["error"]["type"], "admin_route_not_found");
}

// ---------------------------------------------------------------------------
// Authentication and authorization
// ---------------------------------------------------------------------------

#[tokio::test]
async fn no_route_answers_without_an_administrative_credential() {
    let deployment = Deployment::new();
    for spec in super::admin_route_specs() {
        let path = format!("{ADMIN_PREFIX}{}", super::router::concrete_path(&spec));
        let builder = if spec.action.writes() {
            Request::post(&path)
                .header(IDEMPOTENCY_KEY_HEADER, "key-1")
                .header(EXPECTED_REVISION_HEADER, EXPECTED_REVISION_EMPTY)
        } else {
            Request::get(&path)
        };
        let (status, body) = deployment
            .send(builder.body(Body::empty()).expect("a request"))
            .await;
        assert_eq!(status, StatusCode::UNAUTHORIZED, "{path} answered: {body}");
        assert_eq!(body["error"]["type"], "admin_unauthenticated");
    }
    assert_eq!(deployment.store.published_revisions(), 0);
}

#[tokio::test]
async fn an_inference_credential_carries_no_administrative_authority() {
    let deployment = Deployment::new();
    for (name, value) in [
        (
            axum::http::header::AUTHORIZATION.as_str(),
            "Bearer axt1.token.signature",
        ),
        (INFERENCE_KEY_HEADER, "gateway-inference-key"),
    ] {
        let (status, body) = deployment
            .send(
                Request::post(format!("{ADMIN_PREFIX}/tenants"))
                    .header(name, value)
                    .header(IDEMPOTENCY_KEY_HEADER, "key-1")
                    .header(EXPECTED_REVISION_HEADER, EXPECTED_REVISION_EMPTY)
                    .body(Body::from(tenant_document().to_string()))
                    .expect("a request"),
            )
            .await;
        assert_eq!(status, StatusCode::UNAUTHORIZED);
        assert_eq!(body["error"]["type"], "admin_unauthenticated");
    }
    assert_eq!(deployment.store.published_revisions(), 0);
}

#[tokio::test]
async fn a_tenant_scoped_administrator_cannot_publish_outside_its_tenant() {
    let tenant = ResourceScope::Tenant(fixtures::tenant_id(1));
    let deployment =
        Deployment::with_authorizer(FakeAdminAuthorizer::permissive().within(&[tenant]));

    // A tenant row is deployment-scoped: creating one is not a tenant
    // administrator's to authorize.
    let (status, body) = deployment
        .post(
            "/tenants",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &tenant_document(),
        )
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
    assert_eq!(body["error"]["type"], "admin_forbidden");

    // And another tenant's project is refused on the scope in the *document*,
    // not on the caller's word.
    let mut elsewhere = project_document();
    elsewhere["resource"]["tenant"] = json!(fixtures::tenant_id(7).to_string());
    let (status, body) = deployment
        .post("/projects", "key-2", EXPECTED_REVISION_EMPTY, &elsewhere)
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
    assert_eq!(body["error"]["type"], "admin_forbidden");
    assert_eq!(deployment.store.published_revisions(), 0);
}

// ---------------------------------------------------------------------------
// The management catalogue
// ---------------------------------------------------------------------------

/// The read a tenant administrator makes after publishing: the enablement it
/// created, the alias that names it, and the one thing still standing between
/// them and a routable model.
#[tokio::test]
async fn the_management_catalogue_reports_what_a_tenant_published() {
    let deployment = Deployment::new();
    let head = build(&deployment).await;

    let (status, view) = deployment
        .get(&format!("/catalogue?tenant={}", fixtures::tenant_id(1)))
        .await;
    assert_eq!(status, StatusCode::OK, "{view}");
    assert_eq!(view["revision"], head);
    assert_eq!(view["scope"]["kind"], "tenant");

    let entries = view["entries"].as_array().expect("entries");
    assert_eq!(entries.len(), 1, "{view}");
    let entry = &entries[0];
    assert_eq!(entry["slug"], "gpt-4o");
    assert_eq!(
        entry["offering"],
        fixtures::offering_id("gpt-4o").to_string()
    );
    assert_eq!(
        entry["catalog_snapshot"],
        fixtures::catalog_snapshot().to_string()
    );
    assert_eq!(entry["state"], "enabled");
    assert_eq!(entry["aliases"], json!(["default"]));
    let aliases = view["aliases"].as_array().expect("aliases");
    assert_eq!(aliases.len(), 1, "{view}");
    assert_eq!(aliases[0]["slug"], "default");
    assert_eq!(aliases[0]["scope"]["kind"], "project");
    assert_eq!(aliases[0]["targets"].as_array().unwrap().len(), 1);
    // Enabled and named, and still not routable: nobody approved a price. The
    // read says which of the two acts is missing rather than reporting a bare
    // "unavailable".
    assert_eq!(entry["billable"], json!(false));
    assert_eq!(entry["routable"], json!(false));
    assert_eq!(entry["unavailable"], json!(["unpriced"]));
    // And it says what this build could not consult, so an operator does not read
    // silence as an all-clear.
    assert_eq!(
        view["pending"],
        json!(["offering-metadata", "availability"])
    );

    let (status, filtered) = deployment
        .get(&format!(
            "/catalogue?tenant={}&state=enabled&wire_family=openai-chat&offering={}&billable=false",
            fixtures::tenant_id(1),
            fixtures::offering_id("gpt-4o")
        ))
        .await;
    assert_eq!(status, StatusCode::OK, "{filtered}");
    assert_eq!(filtered["entries"].as_array().expect("entries").len(), 1);
    assert_eq!(filtered["entries"][0]["slug"], "gpt-4o");
}

/// The scope is a request parameter, so it is checked against the grant like any
/// other: a tenant administrator cannot read another tenant's catalogue, and the
/// refusal does not tell it whether that tenant has anything enabled.
#[tokio::test]
async fn a_catalogue_read_outside_the_grant_is_forbidden() {
    let built = Deployment::new();
    build(&built).await;
    let deployment = built.narrowed(&[
        ResourceScope::Tenant(fixtures::tenant_id(1)),
        ResourceScope::Project {
            tenant: fixtures::tenant_id(1),
            project: fixtures::project_id(2),
        },
    ]);

    let (status, body) = deployment
        .get(&format!("/catalogue?tenant={}", fixtures::tenant_id(7)))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN, "{body}");
    assert_eq!(body["error"]["type"], "admin_forbidden");

    // The scope a project read is checked against is the pair, so a grant that
    // covers the pair reads it and one that names another tenant does not.
    let (status, view) = deployment
        .get(&format!(
            "/catalogue?tenant={}&project={}",
            fixtures::tenant_id(1),
            fixtures::project_id(2)
        ))
        .await;
    assert_eq!(status, StatusCode::OK, "{view}");
    assert_eq!(view["scope"]["kind"], "project");
    assert_eq!(view["entries"].as_array().expect("entries").len(), 1);
}

/// A malformed filter is a typed refusal rather than a silently ignored
/// parameter: a caller that filtered on a spelling this build does not know must
/// not be handed an unfiltered catalogue and believe it was filtered.
#[tokio::test]
async fn a_catalogue_filter_this_build_cannot_read_is_refused() {
    let deployment = Deployment::new();
    build(&deployment).await;

    for query in [
        "tenant=not-a-uuid".to_owned(),
        format!("tenant={}&state=retired", fixtures::tenant_id(1)),
        format!("tenant={}&wire_family=telepathy", fixtures::tenant_id(1)),
        format!("tenant={}&offering=nonsense", fixtures::tenant_id(1)),
        format!("tenant={}&unknown=1", fixtures::tenant_id(1)),
        format!(
            "tenant={}&state=enabled&state=disabled",
            fixtures::tenant_id(1)
        ),
        "project=nothing".to_owned(),
    ] {
        let (status, body) = deployment.get(&format!("/catalogue?{query}")).await;
        assert_eq!(status, StatusCode::BAD_REQUEST, "{query}: {body}");
        assert_eq!(body["error"]["type"], "admin_request_invalid", "{query}");
    }

    let oversized = format!(
        "tenant={}&offering={}",
        fixtures::tenant_id(1),
        "x".repeat(super::handlers::CATALOGUE_MAX_QUERY_BYTES)
    );
    let (status, body) = deployment.get(&format!("/catalogue?{oversized}")).await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
    assert_eq!(body["error"]["type"], "admin_request_invalid");
    assert!(!body.to_string().contains(&"x".repeat(64)));
}

// ---------------------------------------------------------------------------
// History, audit, rollback
// ---------------------------------------------------------------------------

#[tokio::test]
async fn history_is_bounded_newest_first_and_audit_names_the_actor() {
    let deployment = Deployment::new();
    let head = build(&deployment).await;

    let (status, page) = deployment.get("/history?limit=3").await;
    assert_eq!(status, StatusCode::OK);
    let revisions = page["revisions"].as_array().expect("revisions");
    assert_eq!(revisions.len(), 3);
    assert_eq!(revisions[0]["revision"], head);

    let (status, body) = deployment.get("/history?limit=0").await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_eq!(body["error"]["type"], "history_limit_invalid");

    // A query string the extractor cannot read is still an administrative
    // refusal: a client branching on `AdminError::CODES` never meets a body it
    // cannot parse.
    for query in ["/history?limit=abc", "/history?page=2"] {
        let (status, body) = deployment.get(query).await;
        assert_eq!(status, StatusCode::BAD_REQUEST, "{query}");
        assert_eq!(body["error"]["type"], "admin_request_invalid", "{query}");
    }

    let (status, audit) = deployment.get(&format!("/audit/{head}")).await;
    assert_eq!(status, StatusCode::OK);
    let events = audit["events"].as_array().expect("events");
    assert!(!events.is_empty());
    assert_eq!(events[0]["actor"]["kind"], "human");
    assert_eq!(events[0]["actor"]["subject"], SUBJECT);
    assert_eq!(events[0]["summary"], "cap acme's spend and concurrency");
}

// ---------------------------------------------------------------------------
// Conditional reads
// ---------------------------------------------------------------------------

#[tokio::test]
async fn a_read_a_caller_already_holds_answers_not_modified_without_a_body() {
    let deployment = Deployment::new();
    build(&deployment).await;

    for path in ["/state", "/history", "/convergence"] {
        let (status, etag, body) = deployment.get_conditional(path, None).await;
        assert_eq!(status, StatusCode::OK, "{path}");
        let validator = etag.expect("every administrative read carries a validator");
        // `/convergence` answers a weak validator, because its reported lag moves
        // while nothing about the replica's convergence state does.
        let expected = if path == "/convergence" { "W/\"" } else { "\"" };
        assert!(validator.starts_with(expected), "{path}: {validator}");

        let (status, repeat, body_again) = deployment.get_conditional(path, Some(&validator)).await;
        assert_eq!(status, StatusCode::NOT_MODIFIED, "{path}");
        // The validator is echoed on the `304`, so a poller keeps conditioning on
        // the one it holds rather than falling back to full reads.
        assert_eq!(repeat.as_deref(), Some(validator.as_str()), "{path}");
        assert!(body_again.is_empty(), "{path}: a 304 carries no body");
        assert!(!body.is_empty(), "{path}");

        // `*` matches any current representation, and a read that answers has one.
        let (status, _, _) = deployment.get_conditional(path, Some("*")).await;
        assert_eq!(status, StatusCode::NOT_MODIFIED, "{path}");
    }
}

#[tokio::test]
async fn a_validator_stops_matching_once_the_state_it_described_changes() {
    let deployment = Deployment::new();
    let head = deployment
        .publish(
            "/tenants",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &tenant_document(),
        )
        .await;
    let (_, before, _) = deployment.get_conditional("/state", None).await;
    let before = before.expect("a validator");

    deployment
        .publish("/projects", "key-2", &head, &project_document())
        .await;

    let (status, after, body) = deployment.get_conditional("/state", Some(&before)).await;
    assert_eq!(status, StatusCode::OK);
    let after = after.expect("a validator");
    assert_ne!(after, before);
    // The validator describes the bytes, not the revision: the projection a
    // caller receives is the one its new validator was taken over.
    let state: Value = serde_json::from_slice(&body).expect("a state view");
    assert!(
        state["resources"]
            .as_array()
            .expect("resources")
            .iter()
            .any(|resource| resource["kind"] == "project"),
        "{state}",
    );
    let (status, _, _) = deployment.get_conditional("/state", Some(&after)).await;
    assert_eq!(status, StatusCode::NOT_MODIFIED);
}

#[tokio::test]
async fn a_conditional_the_surface_cannot_use_is_answered_in_full() {
    let deployment = Deployment::new();
    build(&deployment).await;
    let (_, validator, _) = deployment.get_conditional("/state", None).await;
    let validator = validator.expect("a validator");

    // A validator for another representation, a mangled one, and one this
    // surface never issued: none may be read as a match, because a wrong `304`
    // hands an operator a stale answer during an incident.
    let (_, history, _) = deployment.get_conditional("/history", None).await;
    let history = history.expect("a validator");
    for conditional in [
        history.clone(),
        "\"not-a-checksum\"".to_owned(),
        "garbage".to_owned(),
        "W/\"not-a-checksum\"".to_owned(),
        // Not an entity-tag: a doubled prefix names no representation, however
        // closely the rest of it resembles the current one.
        format!("W/W/{validator}"),
    ] {
        let (status, echoed, body) = deployment
            .get_conditional("/state", Some(&conditional))
            .await;
        assert_eq!(status, StatusCode::OK, "{conditional}");
        assert_eq!(echoed.as_deref(), Some(validator.as_str()), "{conditional}");
        assert!(!body.is_empty(), "{conditional}");
    }

    // A weak validator over the *current* representation can only be an
    // intermediary weakening one that came from here, and still matches.
    let (status, _, _) = deployment
        .get_conditional("/state", Some(&format!("W/{validator}")))
        .await;
    assert_eq!(status, StatusCode::NOT_MODIFIED);
}

#[tokio::test]
async fn a_conditional_read_is_still_authenticated_and_authorized() {
    let deployment = Deployment::with_authorizer(FakeAdminAuthorizer::permissive());
    build(&deployment).await;
    let (_, validator, _) = deployment.get_conditional("/state", None).await;
    let validator = validator.expect("a validator");

    // A validator is not a credential: presenting one without an administrative
    // credential is an unauthenticated read, not a free `304`.
    let response = router(deployment.api.clone())
        .oneshot(
            Request::get(format!("{ADMIN_PREFIX}/state"))
                .header(axum::http::header::IF_NONE_MATCH, &validator)
                .body(Body::empty())
                .expect("a request"),
        )
        .await
        .expect("a response");
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    assert!(response.headers().get(axum::http::header::ETAG).is_none());

    // Nor does it bypass authorization: a caller without deployment authority
    // is refused whether or not it names the representation.
    let scoped = Deployment::with_authorizer(
        FakeAdminAuthorizer::permissive().within(&[ResourceScope::Tenant(fixtures::tenant_id(1))]),
    );
    let (status, etag, _) = scoped.get_conditional("/state", Some(&validator)).await;
    assert_eq!(status, StatusCode::FORBIDDEN);
    assert!(etag.is_none());
}

#[tokio::test]
async fn a_rollback_republishes_an_earlier_state_as_a_new_revision() {
    let deployment = Deployment::new();
    let first = deployment
        .publish(
            "/tenants",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &tenant_document(),
        )
        .await;
    let second = deployment
        .publish("/projects", "key-2", &first, &project_document())
        .await;

    let rollback = json!({
        "summary": "the project was created against the wrong tenant",
        "revision": first,
    });
    let (status, body) = deployment
        .post("/rollback", "key-3", &second, &rollback)
        .await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["result"], "published");
    let restored = body["revision"].as_str().expect("a revision");
    assert_ne!(restored, first, "a rollback moves forward, not backwards");
    assert_eq!(body["diff"]["summary"]["removed"], 1);

    let (_, state) = deployment.get("/state").await;
    assert_eq!(state["revision"], restored);
    let kinds: Vec<&str> = state["resources"]
        .as_array()
        .expect("resources")
        .iter()
        .map(|resource| resource["kind"].as_str().expect("a kind"))
        .collect();
    assert_eq!(kinds, vec!["tenant"]);
    // The rolled-back-from revision is still readable: history is append-only.
    assert_eq!(
        deployment.get(&format!("/audit/{second}")).await.0,
        StatusCode::OK
    );
}

#[tokio::test]
async fn a_rollback_to_a_revision_that_does_not_exist_is_refused() {
    let deployment = Deployment::new();
    let head = deployment
        .publish(
            "/tenants",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &tenant_document(),
        )
        .await;
    let rollback = json!({
        "summary": "restore a revision nobody published",
        "revision": fixtures::revision_id(99).to_string(),
    });
    let (status, body) = deployment
        .post("/rollback", "key-2", &head, &rollback)
        .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert_eq!(body["error"]["type"], "revision_not_found");
    assert_eq!(deployment.store.published_revisions(), 1);
}

// ---------------------------------------------------------------------------
// Stateless mode
// ---------------------------------------------------------------------------

#[tokio::test]
async fn a_stateless_deployment_refuses_every_administrative_route_by_mode() {
    for spec in super::admin_route_specs() {
        let path = format!("{ADMIN_PREFIX}{}", super::router::concrete_path(&spec));
        let builder = if spec.action.writes() {
            Request::post(&path)
        } else {
            Request::get(&path)
        };
        let response = refusing_router()
            .oneshot(builder.body(Body::empty()).expect("a request"))
            .await
            .expect("a response");
        let status = response.status();
        let body = response
            .into_body()
            .collect()
            .await
            .expect("a body")
            .to_bytes();
        let body: Value = serde_json::from_slice(&body).expect("an administrative envelope");
        assert_eq!(status, StatusCode::NOT_IMPLEMENTED, "{path}: {body}");
        assert_eq!(body["error"]["type"], "stateful_mode_required");
        // Unauthenticated, and still the *mode* answer: the refusal cannot depend
        // on a credential a stateless deployment has no way to issue.
        assert_eq!(body["error"]["retryable"], false);
    }
}

/// A replica's derived availability, as a snapshot would carry it.
struct StaticAvailability {
    index: Option<Arc<AvailabilityIndex>>,
    runtime: RuntimeObservations,
}

impl AvailabilityReader for StaticAvailability {
    fn read(&self) -> Option<(Arc<AvailabilityIndex>, RuntimeObservations)> {
        Some((self.index.clone()?, self.runtime.clone()))
    }
}

/// A record every authority permits, resting on the evidence it is handed.
fn entitled(evidence: DiscoveryObservation) -> AvailabilityRecord {
    AvailabilityRecord {
        presence: CataloguePresence::Present,
        enablement: Enablement::Enabled,
        entitlement: Entitlement::Granted,
        policy: PolicyDecision::Permitted,
        discovery: Some(evidence),
        ..AvailabilityRecord::default()
    }
}

/// Two tenants' derived availability in one index, which is what a replica
/// actually holds: the read must never widen past the scope it was asked about.
fn two_tenant_index() -> (AvailabilityIndex, ScopeRef, ScopeRef) {
    let mine = ScopeRef::tenant(fixtures::tenant_id(1));
    let theirs = ScopeRef::tenant(fixtures::tenant_id(11));
    let target = TargetRef::parse("openai", "gpt-4o").expect("a well-formed target");
    let observation = |scope: ScopeRef| {
        DiscoveryObservation::new(
            scope,
            target.clone(),
            DiscoveryResult::Present,
            DiscoveryCompleteness::Complete,
            DiscoverySource::ProviderListing,
            SystemTime::now(),
        )
        .detailed("listed by https://api.example.test/v1/models?key=sk-live-never-served")
    };
    let index = AvailabilityIndex::builder()
        .record(
            AvailabilityKey::new(mine, target.clone()),
            entitled(observation(mine)),
        )
        .record(
            AvailabilityKey::new(theirs, target.clone()),
            entitled(observation(theirs)),
        )
        .build();
    (index, mine, theirs)
}

/// A replica that derives no view says so, rather than answering "no models" —
/// which reads identically to an entitlement a caller has just lost.
#[tokio::test]
async fn an_availability_read_distinguishes_deriving_nothing_from_finding_nothing() {
    let deployment = Deployment::new();

    let (status, body) = deployment
        .get(&format!("/availability?tenant={}", fixtures::tenant_id(1)))
        .await;

    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["deriving"], json!(false));
    assert_eq!(body["targets"], json!([]));

    // Attached and deriving nothing is the same answer: what the flag reports is
    // whether a view exists, not whether a reader was wired up.
    let attached = Deployment::attached_but_underiving();
    let (status, body) = attached
        .get(&format!("/availability?tenant={}", fixtures::tenant_id(1)))
        .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["deriving"], json!(false));
    assert_eq!(body["targets"], json!([]));

    let (index, mine, _) = two_tenant_index();
    let deriving = Deployment::deriving(
        FakeAdminAuthorizer::permissive(),
        index,
        RuntimeObservations::none(),
    );
    let (status, body) = deriving
        .get(&format!("/availability?tenant={}", mine.tenant))
        .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["deriving"], json!(true));
    assert_eq!(body["targets"].as_array().expect("targets").len(), 1);
    assert_eq!(body["targets"][0]["state"], json!("available"));
    assert_eq!(body["targets"][0]["provider"], json!("openai"));
}

/// The read is answered from the replica's own memory: an availability question
/// asked *because* the control plane is unreachable must not need it.
#[tokio::test]
async fn an_availability_read_reaches_no_control_plane() {
    let (index, mine, _) = two_tenant_index();
    let store = Arc::new(InMemoryControlPlane::new());
    let counting = Arc::new(CountingStore::new(store.clone()));
    let api = Arc::new(
        AdminApi::new(
            Arc::new(AdminService::stateful(counting.clone())),
            Arc::new(FakeAdminAuthenticator::new().with_human(TOKEN, ISSUER, SUBJECT)),
            Arc::new(FakeAdminAuthorizer::permissive()),
        )
        .with_availability(Arc::new(StaticAvailability {
            index: Some(Arc::new(index)),
            runtime: RuntimeObservations::none(),
        })),
    );
    let deployment = Deployment {
        api,
        store,
        secrets: Arc::new(InMemorySecrets::new()),
    };

    let (status, body) = deployment
        .get(&format!("/availability?tenant={}", mine.tenant))
        .await;

    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["deriving"], json!(true));
    assert_eq!(
        counting.calls(),
        0,
        "an availability read consulted the control plane"
    );
}

/// One tenant's derived entitlements are not another's, and a grant that does
/// not enclose the scope is refused rather than narrowed.
#[tokio::test]
async fn an_availability_read_is_confined_to_the_scope_the_grant_encloses() {
    let (index, mine, theirs) = two_tenant_index();
    let deployment = Deployment::deriving(
        FakeAdminAuthorizer::permissive().within(&[ResourceScope::Tenant(mine.tenant)]),
        index,
        RuntimeObservations::none(),
    );

    let (status, body) = deployment
        .get(&format!("/availability?tenant={}", mine.tenant))
        .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["targets"].as_array().expect("targets").len(), 1);
    // A tenant's own answer carries no discovery machinery: which listing the
    // deployment took, and what a probe's error body said, are the operator's.
    assert_eq!(body["targets"][0].get("source"), None);
    let serialized = body.to_string();
    assert!(!serialized.contains("sk-live"), "{serialized}");
    assert!(!serialized.contains("api.example.test"), "{serialized}");

    let (status, _) = deployment
        .get(&format!("/availability?tenant={}", theirs.tenant))
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

/// Availability is a question about a tenant's models. A deployment-wide answer
/// would be every tenant's entitlements in one document, so it is refused rather
/// than served to the one caller who could read it.
#[tokio::test]
async fn an_availability_read_must_name_the_tenant_it_asks_about() {
    let (index, _, _) = two_tenant_index();
    let deployment = Deployment::deriving(
        FakeAdminAuthorizer::permissive(),
        index,
        RuntimeObservations::none(),
    );

    let (status, body) = deployment.get("/availability").await;

    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_eq!(body["error"]["type"], "admin_request_invalid");

    // And the same answer for a caller who could never have asked deployment-wide:
    // the request shape is refused before any authority is consulted, so a tenant
    // administrator's typo is not answered with a forbidden — nor recorded as one
    // in the denial trail.
    let (index, mine, _) = two_tenant_index();
    let scoped = Deployment::deriving(
        FakeAdminAuthorizer::permissive().within(&[ResourceScope::Tenant(mine.tenant)]),
        index,
        RuntimeObservations::none(),
    );

    let (status, body) = scoped.get("/availability").await;

    assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
    assert_eq!(body["error"]["type"], "admin_request_invalid");
    let denials = ControlPlaneStore::denials(
        scoped.store.as_ref(),
        &DenialPage::for_scope(Some(mine.tenant)),
        10,
    )
    .await
    .expect("the denial trail");
    assert!(
        denials.is_empty(),
        "a malformed query is not an access denial: {denials:?}"
    );
}

/// A project's enablements are *overrides* of its tenant's, so a project that
/// has overridden nothing may still call everything its tenant enabled — and the
/// read says so rather than reporting a project with no models.
#[tokio::test]
async fn an_availability_read_of_a_project_carries_what_the_project_inherits() {
    let tenant = fixtures::tenant_id(1);
    let project = fixtures::project_id(2);
    let scope = ScopeRef::tenant(tenant);
    let inherited = TargetRef::parse("openai", "gpt-4o").expect("a well-formed target");
    let overridden = TargetRef::parse("openai", "o3").expect("a well-formed target");
    let index = AvailabilityIndex::builder()
        .record(
            AvailabilityKey::new(scope, inherited.clone()),
            entitled(DiscoveryObservation::new(
                scope,
                inherited,
                DiscoveryResult::Present,
                DiscoveryCompleteness::Complete,
                DiscoverySource::ProviderListing,
                SystemTime::now(),
            )),
        )
        .record(
            AvailabilityKey::new(
                ScopeRef {
                    tenant,
                    project: Some(project),
                },
                overridden,
            ),
            AvailabilityRecord {
                enablement: Enablement::NotEnabled,
                ..AvailabilityRecord::enabled()
            },
        )
        .build();
    let deployment = Deployment::deriving(
        FakeAdminAuthorizer::permissive(),
        index,
        RuntimeObservations::none(),
    );

    let (status, body) = deployment
        .get(&format!("/availability?tenant={tenant}&project={project}"))
        .await;

    assert_eq!(status, StatusCode::OK);
    let targets = body["targets"].as_array().expect("targets");
    assert_eq!(targets.len(), 2, "{body}");
    assert_eq!(targets[0]["model"], json!("gpt-4o"));
    assert_eq!(targets[0]["state"], json!("available"));
    // The project's own record still replaces what it overrides, including when
    // the override is a refusal.
    assert_eq!(targets[1]["model"], json!("o3"));
    assert_eq!(targets[1]["state"], json!("denied"));
}

/// This replica's own circuits are overlaid at the instant of the question, so
/// two replicas answer honestly rather than one answering for the fleet.
#[tokio::test]
async fn an_availability_read_overlays_this_replicas_own_health() {
    let (index, mine, _) = two_tenant_index();
    let deployment = Deployment::deriving(
        FakeAdminAuthorizer::permissive(),
        index,
        RuntimeObservations::of_circuits([("openai/gpt-4o".to_owned(), CircuitState::Open)]),
    );

    let (status, body) = deployment
        .get(&format!("/availability?tenant={}", mine.tenant))
        .await;

    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["targets"][0]["state"], json!("unavailable"));
    // An operator trusted with the whole deployment is told which authority
    // refused, because "why can this tenant not reach this model" is the
    // question the read exists to answer.
    assert_eq!(body["targets"][0]["decided_by"], json!("runtime"));
}

/// The same answer to a tenant's own administrator says only what it is, not
/// which of the deployment's authorities decided it.
///
/// Disclosure follows the caller's authority rather than the scope the query
/// names — an availability read always names a tenant, so the scope cannot tell
/// a root operator apart from a tenant administrator asking about themselves.
#[tokio::test]
async fn an_availability_read_by_a_tenants_own_administrator_names_no_authority() {
    let (index, mine, _) = two_tenant_index();
    let scoped = Deployment::deriving(
        FakeAdminAuthorizer::permissive().within(&[ResourceScope::Tenant(mine.tenant)]),
        index,
        RuntimeObservations::of_circuits([("openai/gpt-4o".to_owned(), CircuitState::Open)]),
    );

    let (status, body) = scoped
        .get(&format!("/availability?tenant={}", mine.tenant))
        .await;

    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["targets"][0]["state"], json!("unavailable"));
    // A tenant learns that the target is not being attempted, not that this
    // replica's breaker is open.
    assert_eq!(body["targets"][0]["decided_by"], json!("undisclosed"));
}

/// An availability read is a read like the others: an operator watching a target
/// through an incident conditions on the answer it already holds, and pays for a
/// body only when the answer moved.
#[tokio::test]
async fn an_availability_read_a_caller_already_holds_answers_not_modified() {
    let (index, mine, _) = two_tenant_index();
    let deployment = Deployment::deriving(
        FakeAdminAuthorizer::permissive(),
        index,
        RuntimeObservations::none(),
    );
    let path = format!("/availability?tenant={}", mine.tenant);

    let (status, etag, body) = deployment.get_conditional(&path, None).await;
    assert_eq!(status, StatusCode::OK);
    let validator = etag.expect("every administrative read carries a validator");
    assert!(validator.starts_with('"'), "{validator}");
    assert!(!body.is_empty());

    let (status, repeat, body_again) = deployment.get_conditional(&path, Some(&validator)).await;
    assert_eq!(status, StatusCode::NOT_MODIFIED);
    assert_eq!(repeat.as_deref(), Some(validator.as_str()));
    assert!(body_again.is_empty(), "a 304 carries no body");
}

// ---------------------------------------------------------------------------
// The credential lifecycle: `/admin/v1/secrets`
// ---------------------------------------------------------------------------

const MATERIAL: &str = "sk-live-do-not-log-this";
const ROTATED: &str = "sk-live-the-replacement";

/// The tenant every material case below owns its secrets as.
fn owning_tenant() -> String {
    fixtures::tenant_id(1).to_string()
}

/// Nothing a material call answers with may carry what was presented — not the
/// stored value, not a prefix of it, not a fingerprint derived from it.
fn carries_no_material(body: &Value) {
    let rendered = body.to_string();
    for material in [MATERIAL, ROTATED] {
        assert!(
            !rendered.contains(material),
            "material reached a caller: {rendered}"
        );
        // A prefix long enough to identify a key is a leak too.
        assert!(
            !rendered.contains(&material[..12]),
            "a prefix of material reached a caller: {rendered}"
        );
    }
}

#[tokio::test]
async fn material_is_stored_under_a_reference_and_never_answered_back() {
    let deployment = Deployment::new();
    let tenant = owning_tenant();
    let (status, staged) = deployment
        .post_material(
            "/secrets",
            &json!({ "tenant": tenant, "material": MATERIAL }),
        )
        .await;
    assert_eq!(status, StatusCode::OK, "{staged}");
    carries_no_material(&staged);
    // Staged, not active: storing material makes nothing servable.
    assert_eq!(staged["lifecycle"], "staged");
    assert_eq!(staged["version"], 1);
    assert_eq!(staged["owner"], tenant);
    let reference = staged["reference"]
        .as_str()
        .expect("a reference")
        .to_owned();
    assert!(reference.ends_with("@v1"), "{reference}");

    // And there is no route that gives it back: the versions read is the widest
    // thing a caller may ask for.
    let secret = staged["secret"].as_str().expect("a secret id");
    let (status, versions) = deployment
        .get(&format!("/secrets/{secret}?tenant={tenant}"))
        .await;
    assert_eq!(status, StatusCode::OK, "{versions}");
    carries_no_material(&versions);
    assert_eq!(versions["versions"].as_array().expect("versions").len(), 1);
    assert_eq!(versions["versions"][0]["reference"], reference);
    assert_eq!(deployment.store.published_revisions(), 0);
}

#[tokio::test]
async fn a_rotation_stages_the_next_version_beside_the_one_in_service() {
    let deployment = Deployment::new();
    let tenant = owning_tenant();
    let first = deployment.stage(&tenant, MATERIAL).await;
    let (status, activated) = deployment
        .post_material(
            "/secrets/lifecycle",
            &json!({ "tenant": tenant, "reference": first, "lifecycle": "active" }),
        )
        .await;
    assert_eq!(status, StatusCode::OK, "{activated}");
    assert_eq!(activated["changed"], true);

    let (status, rotated) = deployment
        .post_material(
            "/secrets/rotate",
            &json!({ "tenant": tenant, "reference": first, "material": ROTATED }),
        )
        .await;
    assert_eq!(status, StatusCode::OK, "{rotated}");
    carries_no_material(&rotated);
    assert_eq!(rotated["version"], 2);
    assert_eq!(rotated["lifecycle"], "staged");

    // Both versions exist at once, which is what makes a cutover reversible: the
    // old one is still resolvable while the new one is provable.
    let secret = rotated["secret"].as_str().expect("a secret id");
    let (_, versions) = deployment
        .get(&format!("/secrets/{secret}?tenant={tenant}"))
        .await;
    let versions = versions["versions"].as_array().expect("versions").clone();
    assert_eq!(versions.len(), 2, "{versions:?}");
    assert_eq!(versions[0]["lifecycle"], "active");
    assert_eq!(versions[0]["resolvable"], true);
    assert_eq!(versions[1]["lifecycle"], "staged");
    assert_eq!(versions[1]["resolvable"], true);

    // Withdrawing the superseded version is the end of the rotation, and it is
    // visible as rotation status rather than inferred.
    let (status, disabled) = deployment
        .post_material(
            "/secrets/lifecycle",
            &json!({ "tenant": tenant, "reference": first, "lifecycle": "disabled" }),
        )
        .await;
    assert_eq!(status, StatusCode::OK, "{disabled}");
    let (_, versions) = deployment
        .get(&format!("/secrets/{secret}?tenant={tenant}"))
        .await;
    assert_eq!(versions["versions"][0]["lifecycle"], "disabled");
    assert_eq!(versions["versions"][0]["resolvable"], false);
    assert_eq!(
        deployment.store.published_revisions(),
        0,
        "secret material lifecycle calls do not publish a revision or AuditEvent"
    );
}

/// The rotation an operator repeats — a retried request, or a second
/// administrator doing what the first already did — must not be reported as a
/// bad key: the material was never examined, and an operator told their key was
/// refused re-issues a credential that was never at fault.
#[tokio::test]
async fn a_repeated_rotation_is_a_conflict_rather_than_a_refusal_of_the_material() {
    let deployment = Deployment::new();
    let tenant = owning_tenant();
    let first = deployment.stage(&tenant, MATERIAL).await;
    let body = json!({ "tenant": tenant, "reference": first, "material": ROTATED });
    let (status, rotated) = deployment.post_material("/secrets/rotate", &body).await;
    assert_eq!(status, StatusCode::OK, "{rotated}");
    let next = rotated["reference"]
        .as_str()
        .expect("a reference")
        .to_owned();

    let (status, again) = deployment.post_material("/secrets/rotate", &body).await;
    assert_eq!(status, StatusCode::CONFLICT, "{again}");
    assert_eq!(again["error"]["type"], "secret_version_exists");
    assert_ne!(
        again["error"]["type"], "secret_material_refused",
        "the presented material was never examined, so it cannot be what was refused"
    );
    // Not retryable: the version this would mint exists, and replaying cannot
    // change that — the caller re-reads the versions and rotates from the current
    // one.
    assert_eq!(again["error"]["retryable"], false);
    // The refusal names the version that already exists, which is what tells the
    // caller the rotation it wanted has happened.
    assert_eq!(again["error"]["resource"], next);
    carries_no_material(&again);

    // And the stored version is the first rotation's, untouched: a version is
    // immutable, so the second call could not have overwritten what a credential
    // pinning it already resolves to.
    let secret = rotated["secret"].as_str().expect("a secret id");
    let (_, versions) = deployment
        .get(&format!("/secrets/{secret}?tenant={tenant}"))
        .await;
    let listed = versions["versions"].as_array().expect("versions").clone();
    assert_eq!(listed.len(), 2, "{listed:?}");
    assert_eq!(listed[1]["reference"], next);
    assert_eq!(listed[1]["lifecycle"], "staged");
}

/// The versions read is polled — by an operator watching a staged version reach
/// `active` — so it answers the same conditional contract as every other
/// administrative projection, rather than a bare body.
#[tokio::test]
async fn the_versions_read_answers_the_conditional_contract() {
    let deployment = Deployment::new();
    let tenant = owning_tenant();
    let reference = deployment.stage(&tenant, MATERIAL).await;
    let secret = reference.split('@').next().expect("a secret id").to_owned();
    let path = format!("/secrets/{secret}?tenant={tenant}");

    let (status, headers, body) = deployment.get_with_headers(&path, None).await;
    assert_eq!(status, StatusCode::OK);
    let validator = headers
        .get(axum::http::header::ETAG)
        .expect("a validator")
        .to_str()
        .expect("a readable validator")
        .to_owned();
    // Strong: this projection is validated by the bytes it answers with.
    assert!(validator.starts_with('"'), "{validator}");
    // Per-caller — a project-scoped grant reads a narrower projection of the same
    // secret — so no shared cache may reuse it for another administrator.
    assert_eq!(
        headers
            .get(axum::http::header::CACHE_CONTROL)
            .and_then(|value| value.to_str().ok()),
        Some("private, no-cache"),
    );
    assert_eq!(
        headers
            .get(axum::http::header::VARY)
            .and_then(|value| value.to_str().ok()),
        Some("authorization"),
    );
    assert!(!body.is_empty());

    let (status, headers, body) = deployment.get_with_headers(&path, Some(&validator)).await;
    assert_eq!(status, StatusCode::NOT_MODIFIED);
    assert_eq!(
        headers
            .get(axum::http::header::ETAG)
            .and_then(|value| value.to_str().ok()),
        Some(validator.as_str()),
    );
    assert!(body.is_empty(), "a 304 carries no body");

    // A lifecycle move is a new representation, so the validator the caller holds
    // stops matching and the next poll is answered in full.
    let (status, moved) = deployment
        .post_material(
            "/secrets/lifecycle",
            &json!({ "tenant": tenant, "reference": reference, "lifecycle": "active" }),
        )
        .await;
    assert_eq!(status, StatusCode::OK, "{moved}");
    let (status, headers, body) = deployment.get_with_headers(&path, Some(&validator)).await;
    assert_eq!(status, StatusCode::OK);
    assert_ne!(
        headers
            .get(axum::http::header::ETAG)
            .and_then(|value| value.to_str().ok()),
        Some(validator.as_str()),
    );
    let versions: Value = serde_json::from_slice(&body).expect("a projection");
    assert_eq!(versions["versions"][0]["lifecycle"], "active");
    carries_no_material(&versions);
}

/// Version listing is an operational rotation projection, not a control-plane
/// or provider calibration endpoint: it returns only store metadata for the
/// tenant the caller named and does not load desired state or unwrap material.
#[tokio::test]
async fn the_versions_read_is_tenant_scoped_metadata_only() {
    let control_plane = Arc::new(InMemoryControlPlane::new());
    let counting = Arc::new(CountingStore::new(control_plane));
    let secrets = Arc::new(InMemorySecrets::new());
    let tenant = fixtures::tenant_id(1);
    let reference = fixtures::secret_ref(1);
    secrets.seed(
        crate::desired_state::secrets::SecretOwner::tenant(tenant),
        reference,
        MATERIAL,
        crate::desired_state::SecretLifecycle::Active,
    );
    let api = Arc::new(AdminApi::new(
        Arc::new(AdminService::stateful(counting.clone()).with_secrets(secrets)),
        Arc::new(FakeAdminAuthenticator::new().with_human(TOKEN, ISSUER, SUBJECT)),
        Arc::new(FakeAdminAuthorizer::permissive()),
    ));

    let response = router(api)
        .oneshot(
            Request::get(format!(
                "{ADMIN_PREFIX}/secrets/{}?tenant={tenant}",
                reference.secret
            ))
            .header(axum::http::header::AUTHORIZATION, format!("Bearer {TOKEN}"))
            .body(Body::empty())
            .expect("a request"),
        )
        .await
        .expect("a response");
    assert_eq!(response.status(), StatusCode::OK);
    let body = response
        .into_body()
        .collect()
        .await
        .expect("a body")
        .to_bytes();
    let body: Value = serde_json::from_slice(&body).expect("a projection");

    assert_eq!(body["secret"], reference.secret.to_string());
    assert_eq!(body["owner"], tenant.to_string());
    assert_eq!(body["versions"][0]["reference"], reference.to_string());
    assert_eq!(body["versions"][0]["lifecycle"], "active");
    assert_eq!(body["versions"][0]["resolvable"], true);
    carries_no_material(&body);
    assert_eq!(
        counting.calls(),
        0,
        "version listing consulted the control plane"
    );
}

#[tokio::test]
async fn moving_a_version_to_the_state_it_already_holds_is_not_a_second_change() {
    let deployment = Deployment::new();
    let tenant = owning_tenant();
    let reference = deployment.stage(&tenant, MATERIAL).await;
    let body = json!({ "tenant": tenant, "reference": reference, "lifecycle": "revoked" });
    let (status, first) = deployment.post_material("/secrets/lifecycle", &body).await;
    assert_eq!(status, StatusCode::OK, "{first}");
    assert_eq!(first["changed"], true);
    // The retry a client makes after a lost response: same state, no second
    // change, which is what stands in for an idempotency key here.
    let (status, again) = deployment.post_material("/secrets/lifecycle", &body).await;
    assert_eq!(status, StatusCode::OK, "{again}");
    assert_eq!(again["changed"], false);
    assert_eq!(again["lifecycle"], "revoked");
}

#[tokio::test]
async fn destroying_material_the_desired_state_still_pins_is_refused() {
    let deployment = Deployment::new();
    let tenant = owning_tenant();
    let reference = deployment.stage(&tenant, MATERIAL).await;
    let secret = reference.split('@').next().expect("a secret id").to_owned();

    // A credential that pins exactly this version, published the ordinary way.
    let head = deployment
        .publish(
            "/tenants",
            "key-1",
            EXPECTED_REVISION_EMPTY,
            &tenant_document(),
        )
        .await;
    let head = deployment
        .publish("/providers", "key-2", &head, &provider_document())
        .await;
    let mut credential = credential_document();
    credential["resource"]["secret"] = json!(secret);
    credential["resource"]["secret_version"] = json!(1);
    let head = deployment
        .publish("/credentials", "key-3", &head, &credential)
        .await;

    let tombstone = json!({ "tenant": tenant, "reference": reference, "lifecycle": "tombstoned" });
    let (status, refusal) = deployment
        .post_material("/secrets/lifecycle", &tombstone)
        .await;
    assert_eq!(status, StatusCode::CONFLICT, "{refusal}");
    assert_eq!(refusal["error"]["type"], "secret_in_use");

    // Revocation is not gated the same way: a leaked key is withdrawable at
    // once, and withdrawing it is what fails the *next* candidate rather than
    // the snapshot serving now.
    let (status, revoked) = deployment
        .post_material(
            "/secrets/lifecycle",
            &json!({ "tenant": tenant, "reference": reference, "lifecycle": "revoked" }),
        )
        .await;
    assert_eq!(status, StatusCode::OK, "{revoked}");

    // Unpinned, and then destroyable: the credential is retired first, which is
    // what stops a candidate revision from resolving the version at all.
    let mut retire = credential_document();
    retire["mutation"] = json!("update");
    retire["resource"]["secret"] = json!(secret);
    retire["resource"]["secret_version"] = json!(1);
    retire["resource"]["lifecycle"] = json!("revoked");
    deployment
        .publish("/credentials", "key-4", &head, &retire)
        .await;
    let (status, destroyed) = deployment
        .post_material("/secrets/lifecycle", &tombstone)
        .await;
    assert_eq!(status, StatusCode::OK, "{destroyed}");
    assert_eq!(destroyed["lifecycle"], "tombstoned");
}

#[tokio::test]
async fn one_tenants_administrator_cannot_reach_another_tenants_material() {
    let deployment = Deployment::with_authorizer(
        FakeAdminAuthorizer::permissive().within(&[ResourceScope::Tenant(fixtures::tenant_id(1))]),
    );
    let ours = owning_tenant();
    let theirs = fixtures::tenant_id(2).to_string();
    let reference = deployment.stage(&ours, MATERIAL).await;
    let secret = reference.split('@').next().expect("a secret id").to_owned();

    let (status, refusal) = deployment
        .post_material(
            "/secrets",
            &json!({ "tenant": theirs, "material": MATERIAL }),
        )
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN, "{refusal}");
    carries_no_material(&refusal);

    // A grant that *is* held, aimed at material another tenant owns: the store
    // answers as it does for a reference that was never stored, so this route is
    // not a way to learn that one exists.
    let deployment = Deployment::new();
    deployment.secrets.seed(
        crate::desired_state::secrets::SecretOwner::tenant(fixtures::tenant_id(2)),
        crate::desired_state::secrets::SecretRef::parse(&reference).expect("a reference"),
        MATERIAL,
        crate::desired_state::secrets::SecretLifecycle::Active,
    );
    let (status, versions) = deployment
        .get(&format!("/secrets/{secret}?tenant={ours}"))
        .await;
    assert_eq!(status, StatusCode::OK, "{versions}");
    assert_eq!(
        versions,
        json!({
            "secret": secret,
            "owner": ours,
            "versions": [],
        })
    );
    let (status, refusal) = deployment
        .post_material(
            "/secrets/lifecycle",
            &json!({ "tenant": ours, "reference": reference, "lifecycle": "revoked" }),
        )
        .await;
    assert_eq!(status, StatusCode::NOT_FOUND, "{refusal}");
    assert_eq!(refusal["error"]["type"], "secret_not_found");
}

#[tokio::test]
async fn tombstoning_a_foreign_pinned_version_is_not_an_existence_probe() {
    let deployment = Deployment::new();
    let ours = fixtures::tenant_id(1).to_string();
    let theirs = fixtures::tenant_id(2).to_string();
    let foreign_owner = crate::desired_state::secrets::SecretOwner::tenant(fixtures::tenant_id(2));
    let foreign_reference = fixtures::secret_ref(12);

    deployment.secrets.seed(
        foreign_owner,
        foreign_reference,
        MATERIAL,
        crate::desired_state::SecretLifecycle::Active,
    );

    // The desired state pins the foreign version as resolvable. A caller that
    // owns tenant 1 must still receive the same not-found answer as for an
    // unreferenced foreign version: ownership is established before this
    // deployment-wide reference-use check.
    let mut tenant = tenant_document();
    tenant["resource"]["tenant"] = json!(theirs);
    tenant["resource"]["slug"] = json!("globex");
    let mut provider = provider_document();
    provider["resource"]["tenant"] = json!(theirs);
    let mut credential = credential_document();
    credential["resource"]["tenant"] = json!(theirs);
    credential["resource"]["secret"] = json!(foreign_reference.secret.to_string());

    let mut head = deployment
        .publish(
            "/tenants",
            "key-foreign-1",
            EXPECTED_REVISION_EMPTY,
            &tenant,
        )
        .await;
    head = deployment
        .publish("/providers", "key-foreign-2", &head, &provider)
        .await;
    deployment
        .publish("/credentials", "key-foreign-3", &head, &credential)
        .await;

    let (status, pinned_refusal) = deployment
        .post_material(
            "/secrets/lifecycle",
            &json!({
                "tenant": ours,
                "reference": foreign_reference.to_string(),
                "lifecycle": "tombstoned",
            }),
        )
        .await;
    assert_eq!(status, StatusCode::NOT_FOUND, "{pinned_refusal}");
    assert_eq!(pinned_refusal["error"]["type"], "secret_not_found");

    let (status, absent_refusal) = deployment
        .post_material(
            "/secrets/lifecycle",
            &json!({
                "tenant": ours,
                "reference": fixtures::secret_ref(99).to_string(),
                "lifecycle": "tombstoned",
            }),
        )
        .await;
    assert_eq!(status, StatusCode::NOT_FOUND, "{absent_refusal}");
    assert_eq!(absent_refusal["error"]["type"], "secret_not_found");
}

#[tokio::test]
async fn a_body_that_carries_material_is_refused_without_echoing_it() {
    let deployment = Deployment::new();
    let tenant = owning_tenant();
    // Valid JSON, wrong shape: serde renders the offending input into some of
    // its messages, and the offending input here is a provider key.
    let (status, refusal) = deployment
        .post_material(
            "/secrets",
            &json!({ "tenant": tenant, "material": { "value": MATERIAL } }),
        )
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "{refusal}");
    assert_eq!(refusal["error"]["type"], "admin_request_invalid");
    carries_no_material(&refusal);

    // Empty material is refused before it is stored, rather than becoming a
    // version that can never authenticate anything.
    let (status, refusal) = deployment
        .post_material("/secrets", &json!({ "tenant": tenant, "material": "" }))
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "{refusal}");
    assert_eq!(refusal["error"]["type"], "secret_material_refused");

    // A lifecycle value is not material by type, but it is still caller input
    // and must not be copied into either the response or operator detail.
    let lifecycle_value = "sk-lifecycle-value-must-not-echo";
    let (status, refusal) = deployment
        .post_material(
            "/secrets/lifecycle",
            &json!({
                "tenant": tenant,
                "reference": fixtures::secret_ref(12).to_string(),
                "lifecycle": lifecycle_value,
            }),
        )
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "{refusal}");
    assert_eq!(refusal["error"]["type"], "admin_request_invalid");
    assert!(
        !refusal.to_string().contains(lifecycle_value),
        "caller input reached the response: {refusal}"
    );

    // A reference that names no version is refused: every operation here is
    // aimed at an exact version.
    let (status, refusal) = deployment
        .post_material(
            "/secrets/rotate",
            &json!({
                "tenant": tenant,
                "reference": fixtures::secret_id(7).to_string(),
                "material": ROTATED,
            }),
        )
        .await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "{refusal}");
    carries_no_material(&refusal);
}

#[tokio::test]
async fn a_secret_store_outage_refuses_the_call_and_names_no_backend_detail() {
    let deployment = Deployment::new();
    let tenant = owning_tenant();
    deployment.secrets.set_unavailable(true);
    let (status, refusal) = deployment
        .post_material(
            "/secrets",
            &json!({ "tenant": tenant, "material": MATERIAL }),
        )
        .await;
    assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "{refusal}");
    assert_eq!(refusal["error"]["type"], "secret_store_unavailable");
    assert_eq!(refusal["error"]["retryable"], true);
    carries_no_material(&refusal);
}

#[tokio::test]
async fn material_calls_need_the_material_authority_and_not_the_publishing_one() {
    let deployment =
        Deployment::with_authorizer(FakeAdminAuthorizer::permitting(&[AdminAction::Publish]));
    let tenant = owning_tenant();
    let (status, refusal) = deployment
        .post_material(
            "/secrets",
            &json!({ "tenant": tenant, "material": MATERIAL }),
        )
        .await;
    assert_eq!(status, StatusCode::FORBIDDEN, "{refusal}");
    assert_eq!(refusal["error"]["type"], "admin_forbidden");
    carries_no_material(&refusal);
}