gunnar-grpc 3.0.0

The tonic service implementations and the event bus behind gunnar's gRPC control plane.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
//! **The gate: the allow-all hole that shipped in v1, closed.**
//!
//! Measure, never assert is the whole shape of this file. A gate that refuses *everything*
//! passes a naive "unauthenticated calls are refused" suite exactly as well as
//! a correct one, and a handler hard-wired to `Ok` passes an "an admin may act"
//! suite exactly as well. So every claim here is asserted in both directions,
//! and the two constants that could hide a dead check are proved dead-or-alive
//! explicitly:
//!
//! - `may_stubbed_to_deny_turns_every_allow_red`: with
//!   [`MemoryControlPlane::force_may`]`(Some(false))`, calls that succeeded
//!   above now fail. So the success came *through* the grant decision, not past
//!   it.
//! - `may_stubbed_to_allow_turns_every_denial_green`: with `Some(true)`, calls
//!   that were `PERMISSION_DENIED` above now succeed. So the denial came from
//!   the grant decision, not from a gate that refuses everything.
//! - `every_rpc_refuses_an_unauthenticated_caller` drives every declared RPC
//!   **with no interceptor in the way**, so a handler that forgot its own check
//!   goes red.
//! - `a_valid_credential_is_not_refused` proves the `UNAUTHENTICATED` above is
//!   not a constant either.
//!
//! Nothing here is signed or verified by a stand-in: every credential is a real
//! `sshsig` over a real ed25519 key, minted in-process.

use std::collections::BTreeSet;
use std::sync::{Arc, Mutex};

use gunnar_grpc::auth::{audited_methods, AuthFailure, AuthGate, MAX_CLOCK_SKEW_MS};
use gunnar_grpc::{
    sign_credential, sign_credential_for, AccessService, AccountsService, AdminService, AuthMode,
    Caller, ControlPlane, EventBus, EventsService, ForgeService, MemoryControlPlane, MirrorService,
    PolicyService, PullsService, RefsService, ReposService, ServerConfig, ServiceContext,
    UsageService, WebhooksService, AUDIT_TARGET, CREDENTIAL_METADATA_KEY,
};
use gunnar_proto::access_server::Access as _;
use gunnar_proto::accounts_server::Accounts as _;
use gunnar_proto::admin_server::Admin as _;
use gunnar_proto::events_server::Events as _;
use gunnar_proto::sso_server::Sso as _;
// Clans (2026-10-05), kept apart from the other services' imports.
use gunnar_proto::clans_server::Clans as _;
use gunnar_proto::forge_server::Forge as _;
use gunnar_proto::mirror_server::Mirror as _;
use gunnar_proto::policy_server::Policy as _;
use gunnar_proto::pull_requests_server::PullRequests as _;
use gunnar_proto::refs_server::Refs as _;
use gunnar_proto::repos_server::Repos as _;
use gunnar_proto::usage_batch_server::UsageBatch as _;
use gunnar_proto::usage_server::Usage as _;
use gunnar_proto::*;
use tonic::{Code, Request};
use tracing::subscriber::with_default;
use tracing_subscriber::layer::SubscriberExt;

// ───────────────────────────────────────────────────────────────────────────
// Fixture
// ───────────────────────────────────────────────────────────────────────────

/// **Every RPC the protos declare, read out of the protos** (GUN-023).
///
/// This was `const DECLARED_RPCS: usize = 72 + …`, a number somebody wrote
/// down. The protos declared 84 non-metered RPCs, `auth::METHODS` listed 70,
/// and the two assertions below compared 70 against 72 and were green — so
/// twelve RPCs (`Access`'s four group verbs, `Forge.GetIssue`,
/// `Forge.ListIssues`, `Mirror.SetCredential`, `Mirror.ResyncReplication`,
/// `Usage.Activity` and all three `Webhooks`) were in no list, were never
/// driven by the sweep, and would have gone on being undriven if one of them
/// had lost its `require` call. The census that exists to prove nothing is
/// missed was itself missing things.
///
/// A count cannot fix that, because a count is what was wrong. The set is
/// derived from the `.proto` files — `include_str!`, so they are embedded at
/// compile time and this cannot read a different tree from the one that built
/// `gunnar-proto` — and compared as a SET. A new RPC now shows up by name.
fn declared_rpcs() -> BTreeSet<String> {
    const PROTOS: &[&str] = &[
        include_str!("../../gunnar-proto/proto/gunnar/v1/access.proto"),
        include_str!("../../gunnar-proto/proto/gunnar/v1/accounts.proto"),
        include_str!("../../gunnar-proto/proto/gunnar/v1/enterprise.proto"),
        include_str!("../../gunnar-proto/proto/gunnar/v1/admin.proto"),
        include_str!("../../gunnar-proto/proto/gunnar/v1/bootstrap.proto"),
        include_str!("../../gunnar-proto/proto/gunnar/v1/clans.proto"),
        include_str!("../../gunnar-proto/proto/gunnar/v1/events.proto"),
        include_str!("../../gunnar-proto/proto/gunnar/v1/forge.proto"),
        include_str!("../../gunnar-proto/proto/gunnar/v1/mirror.proto"),
        include_str!("../../gunnar-proto/proto/gunnar/v1/policy.proto"),
        include_str!("../../gunnar-proto/proto/gunnar/v1/pulls.proto"),
        include_str!("../../gunnar-proto/proto/gunnar/v1/refs.proto"),
        include_str!("../../gunnar-proto/proto/gunnar/v1/repos.proto"),
        include_str!("../../gunnar-proto/proto/gunnar/v1/sso.proto"),
        include_str!("../../gunnar-proto/proto/gunnar/v1/usage.proto"),
        include_str!("../../gunnar-proto/proto/gunnar/v1/usage_batch.proto"),
        include_str!("../../gunnar-proto/proto/gunnar/v1/webhooks.proto"),
        // `entitlement.proto` is compiled only with the feature, so the
        // community build must not be held to its four RPCs: absent code has
        // no refusal to check.
        #[cfg(feature = "metered")]
        include_str!("../../gunnar-proto/proto/gunnar/v1/entitlement.proto"),
        // `billing.proto` likewise (2026-09-17): the tenant's own renewal
        // path, which the community appliance does not carry at all.
        #[cfg(feature = "metered")]
        include_str!("../../gunnar-proto/proto/gunnar/v1/billing.proto"),
        // `sealed.proto` likewise (2026-10-09): the named sealed slot.
        #[cfg(feature = "metered")]
        include_str!("../../gunnar-proto/proto/gunnar/v1/sealed.proto"),
    ];
    let mut out = BTreeSet::new();
    for text in PROTOS {
        let mut service: Option<&str> = None;
        for line in text.lines() {
            let line = line.trim();
            if let Some(rest) = line.strip_prefix("service ") {
                service = rest.split_whitespace().next();
            } else if line == "}" {
                service = None;
            } else if let Some(rest) = line.strip_prefix("rpc ") {
                let (Some(service), Some(method)) = (service, rest.split('(').next()) else {
                    continue;
                };
                out.insert(format!("{service}.{}", method.trim()));
            }
        }
    }
    // The parser is the weak link, so it is measured rather than trusted: a
    // scanner that found nothing, or that found only one service, would make
    // every assertion below vacuous.
    assert!(
        out.len() > 60 && out.contains("Bootstrap.Enroll") && out.contains("Repos.Delete"),
        "the proto scanner did not read the service blocks: {out:?}"
    );
    out
}

const NS: &str = "nordisk";
const REPO: &str = "gunnar";

fn mint() -> ssh_key::PrivateKey {
    ssh_key::PrivateKey::random(
        &mut rand::rand_core::UnwrapErr(rand::rngs::SysRng),
        ssh_key::Algorithm::Ed25519,
    )
    .expect("mint an ed25519 key")
}

fn openssh_of(key: &ssh_key::PrivateKey) -> String {
    key.public_key()
        .to_openssh()
        .expect("render the public key")
}

struct Harness {
    plane: Arc<MemoryControlPlane>,
    ctx: ServiceContext,
}

impl Harness {
    /// A server with authentication ON, one namespace, one repo, and nothing
    /// else. Callers are added by the tests, so a test that forgets to grant
    /// anything gets a refusal rather than an accident.
    fn new() -> Harness {
        let plane = Arc::new(MemoryControlPlane::with_repo(NS, REPO));
        let control: Arc<dyn ControlPlane> = plane.clone();
        let ctx = ServiceContext::new(
            control,
            Arc::new(EventBus::new(64)),
            ServerConfig::default(),
        );
        assert_eq!(
            ctx.config.auth,
            AuthMode::Required,
            "the fixture must run the SHIPPED default; a test suite that quietly ran the \
             escape hatch would prove nothing"
        );
        Harness { plane, ctx }
    }

    /// Register a principal with a freshly minted key. Returns the key and the
    /// principal id; no grant is given.
    fn principal(&self, name: &str) -> (String, ssh_key::PrivateKey) {
        let key = mint();
        let principal = self
            .plane
            .add_principal(name, name, PrincipalKind::User)
            .expect("principal added");
        self.plane
            .add_key(&principal.id, &openssh_of(&key), name, None, "", None)
            .expect("key registered");
        (principal.id, key)
    }

    fn gate(&self) -> AuthGate {
        AuthGate::new(Arc::clone(&self.ctx.control), self.ctx.config.auth)
    }

    /// The caller the gate produces for this key, through the real gate and
    /// over a real signature, so no test invents an identity the server would
    /// not.
    fn caller_for(&self, key: &ssh_key::PrivateKey, nonce: &str) -> Caller {
        let credential = sign_credential_for(key, now_ms(), nonce, "Admin.Health").expect("sign");
        let mut request = Request::new(());
        request.metadata_mut().insert(
            CREDENTIAL_METADATA_KEY,
            credential.to_header_value().parse().expect("ascii"),
        );
        self.gate()
            .authenticate_bound(request.metadata(), now_ms(), Some("Admin.Health"))
            .expect("a freshly signed credential from a registered key must verify")
    }

    fn authed<T>(&self, caller: &Caller, message: T) -> Request<T> {
        let mut request = Request::new(message);
        request.extensions_mut().insert(caller.clone());
        request
    }

    fn repos(&self) -> ReposService {
        ReposService::new(self.ctx.clone())
    }
    fn accounts(&self) -> AccountsService {
        AccountsService::new(self.ctx.clone())
    }
    fn clans(&self) -> gunnar_grpc::ClansService {
        gunnar_grpc::ClansService::new(self.ctx.clone())
    }
    fn refs(&self) -> RefsService {
        RefsService::new(self.ctx.clone())
    }
    fn access(&self) -> AccessService {
        AccessService::new(self.ctx.clone())
    }
    fn enterprise(&self) -> gunnar_grpc::EnterpriseService {
        gunnar_grpc::EnterpriseService::new(self.ctx.clone())
    }
    fn sso(&self) -> gunnar_grpc::SsoService {
        gunnar_grpc::SsoService::new(self.ctx.clone())
    }
    fn policy(&self) -> PolicyService {
        PolicyService::new(self.ctx.clone())
    }
    fn events(&self) -> EventsService {
        EventsService::new(self.ctx.clone())
    }
    fn admin(&self) -> AdminService {
        AdminService::new(self.ctx.clone())
    }
    fn usage(&self) -> UsageService {
        UsageService::new(self.ctx.clone())
    }
    fn usage_batch(&self) -> gunnar_grpc::UsageBatchService {
        gunnar_grpc::UsageBatchService::new(self.ctx.clone())
    }
    fn mirror(&self) -> MirrorService {
        MirrorService::new(self.ctx.clone())
    }
    fn forge(&self) -> ForgeService {
        ForgeService::new(self.ctx.clone())
    }
    fn pulls(&self) -> PullsService {
        PullsService::new(self.ctx.clone())
    }
    fn webhooks(&self) -> WebhooksService {
        WebhooksService::new(self.ctx.clone())
    }
}

fn now_ms() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .expect("after 1970")
        .as_millis() as i64
}

fn path() -> Option<RepoPath> {
    Some(RepoPath::new(NS, REPO))
}

// ───────────────────────────────────────────────────────────────────────────
// Authentication: the credential itself
// ───────────────────────────────────────────────────────────────────────────

#[test]
fn a_registered_key_authenticates_and_an_unregistered_one_does_not() {
    let harness = Harness::new();
    let (principal_id, registered) = harness.principal("alice");
    let stranger = mint();
    let gate = harness.gate();

    let mut metadata = tonic::metadata::MetadataMap::new();
    let good = sign_credential_for(&registered, now_ms(), "nonce-registered-01", "Admin.Health")
        .expect("sign");
    metadata.insert(
        CREDENTIAL_METADATA_KEY,
        good.to_header_value().parse().unwrap(),
    );
    let caller = gate
        .authenticate_bound(&metadata, now_ms(), Some("Admin.Health"))
        .expect("a registered key must authenticate");
    assert_eq!(caller.principal_id, principal_id);
    assert!(caller.authenticated);
    assert_eq!(
        caller.fingerprint,
        registered
            .public_key()
            .fingerprint(ssh_key::HashAlg::Sha256)
            .to_string(),
        "the caller must carry the fingerprint that was actually presented"
    );

    // The same shape, a key nobody registered. If this passed, the whole
    // scheme would be decoration.
    let mut metadata = tonic::metadata::MetadataMap::new();
    let forged = sign_credential_for(&stranger, now_ms(), "nonce-stranger-01", "Admin.Health")
        .expect("sign");
    metadata.insert(
        CREDENTIAL_METADATA_KEY,
        forged.to_header_value().parse().unwrap(),
    );
    assert_eq!(
        gate.authenticate_bound(&metadata, now_ms(), Some("Admin.Health")),
        Err(AuthFailure::NotVerified),
        "an unregistered key authenticated"
    );
}

#[test]
fn a_credential_signed_over_different_bytes_does_not_verify() {
    let harness = Harness::new();
    let (_, key) = harness.principal("alice");
    let gate = harness.gate();

    // Sign one challenge, present another: same key, same signature, a nonce
    // that was not the one signed. This is the check that proves the signature
    // is over the challenge, rather than simply being there.
    let mut credential =
        sign_credential_for(&key, now_ms(), "nonce-original-000", "Admin.Health").expect("sign");
    credential.nonce = "nonce-substituted".into();

    let mut metadata = tonic::metadata::MetadataMap::new();
    metadata.insert(
        CREDENTIAL_METADATA_KEY,
        credential.to_header_value().parse().unwrap(),
    );
    assert_eq!(
        gate.authenticate_bound(&metadata, now_ms(), Some("Admin.Health")),
        Err(AuthFailure::NotVerified),
        "a signature over other bytes was accepted"
    );
}

#[test]
fn a_credential_is_single_use_and_expires() {
    let harness = Harness::new();
    let (_, key) = harness.principal("alice");
    let gate = harness.gate();

    let credential =
        sign_credential_for(&key, now_ms(), "nonce-replay-0001", "Admin.Health").expect("sign");
    let mut metadata = tonic::metadata::MetadataMap::new();
    metadata.insert(
        CREDENTIAL_METADATA_KEY,
        credential.to_header_value().parse().unwrap(),
    );

    gate.authenticate_bound(&metadata, now_ms(), Some("Admin.Health"))
        .expect("first use must be accepted");
    assert_eq!(
        gate.authenticate_bound(&metadata, now_ms(), Some("Admin.Health")),
        Err(AuthFailure::Replayed),
        "the same credential was accepted twice; it is not single-use"
    );

    // …and one issued outside the window is refused before the signature is
    // even looked at.
    let stale = sign_credential_for(
        &key,
        now_ms() - MAX_CLOCK_SKEW_MS - 1_000,
        "nonce-stale-00001",
        "Admin.Health",
    )
    .expect("sign");
    let mut metadata = tonic::metadata::MetadataMap::new();
    metadata.insert(
        CREDENTIAL_METADATA_KEY,
        stale.to_header_value().parse().unwrap(),
    );
    assert!(
        matches!(
            gate.authenticate_bound(&metadata, now_ms(), Some("Admin.Health")),
            Err(AuthFailure::Stale { .. })
        ),
        "a credential older than the skew window was accepted"
    );
}

#[test]
fn a_missing_or_malformed_credential_is_refused() {
    let harness = Harness::new();
    let gate = harness.gate();

    assert_eq!(
        gate.authenticate_bound(
            &tonic::metadata::MetadataMap::new(),
            now_ms(),
            Some("Admin.Health")
        ),
        Err(AuthFailure::Missing)
    );

    for bad in [
        "",
        "Bearer hunter2",
        "gunnar-sshsig-v1",
        "gunnar-sshsig-v1 SHA256:x 1 nonce",
        "gunnar-sshsig-v1 not-a-fingerprint 1 abcdefghijklmnop sig",
        "gunnar-sshsig-v1 SHA256:x not-a-number abcdefghijklmnop sig",
        // A nonce too short to be single-use.
        "gunnar-sshsig-v1 SHA256:x 1 short sig",
    ] {
        let mut metadata = tonic::metadata::MetadataMap::new();
        metadata.insert(CREDENTIAL_METADATA_KEY, bad.parse().unwrap());
        assert!(
            matches!(
                gate.authenticate_bound(&metadata, now_ms(), Some("Admin.Health")),
                Err(AuthFailure::Malformed(_))
            ),
            "{bad:?} was not refused as malformed"
        );
    }
}

#[test]
fn a_revoked_key_stops_authenticating() {
    // The point of reusing the ACL key table: revoking a key for git revokes it
    // for the control plane in the same instant, because there is one table.
    let harness = Harness::new();
    let (_, key) = harness.principal("alice");
    let fingerprint = key
        .public_key()
        .fingerprint(ssh_key::HashAlg::Sha256)
        .to_string();
    let gate = harness.gate();

    let before =
        sign_credential_for(&key, now_ms(), "nonce-before-revoke", "Admin.Health").expect("sign");
    let mut metadata = tonic::metadata::MetadataMap::new();
    metadata.insert(
        CREDENTIAL_METADATA_KEY,
        before.to_header_value().parse().unwrap(),
    );
    gate.authenticate_bound(&metadata, now_ms(), Some("Admin.Health"))
        .expect("before revocation the key works");

    harness.plane.revoke_key(&fingerprint).expect("revoked");

    let after =
        sign_credential_for(&key, now_ms(), "nonce-after-revoke0", "Admin.Health").expect("sign");
    let mut metadata = tonic::metadata::MetadataMap::new();
    metadata.insert(
        CREDENTIAL_METADATA_KEY,
        after.to_header_value().parse().unwrap(),
    );
    assert_eq!(
        gate.authenticate_bound(&metadata, now_ms(), Some("Admin.Health")),
        Err(AuthFailure::NotVerified),
        "a revoked key still authenticated to the control plane"
    );
}

/// **The control plane has no anonymous caller, and never grows one.**
///
/// `Repo.visibility` now means a stranger with no key can *clone a public
/// repository over SSH*. That is a git-wire capability and it must not become a
/// control-plane one: an anonymous `Caller` reaching a handler would carry the
/// public-read rule of `AuthTable::may` into `Repos.Get`, `Refs.List` and
/// `Refs.ReadObject`, which is a control-plane read a stranger was never
/// supposed to have.
///
/// It is structurally impossible through `gunnar-core`: the reserved id cannot
/// be registered, so no key can be registered to it, so no credential can be
/// signed for it. **That is exactly why this test forges the answer**: a guard
/// against an unreachable state is worth nothing until it has been watched
/// refusing, and `AuthGate` takes `ControlPlane` as a trait, so any adapter can
/// return any principal id it likes.
#[test]
fn a_credential_that_resolves_to_the_anonymous_principal_is_refused() {
    let harness = Harness::new();
    let (_, key) = harness.principal("alice");
    let gate = harness.gate();

    let authenticate = |nonce: &str| {
        let credential = sign_credential_for(&key, now_ms(), nonce, "Admin.Health").expect("sign");
        let mut metadata = tonic::metadata::MetadataMap::new();
        metadata.insert(
            CREDENTIAL_METADATA_KEY,
            credential.to_header_value().parse().unwrap(),
        );
        gate.authenticate_bound(&metadata, now_ms(), Some("Admin.Health"))
    };

    // Green first, so the refusal below cannot be a gate that refuses
    // everything: the same key, the same signature scheme, an ordinary
    // principal id.
    let ordinary = authenticate("nonce-ordinary-caller")
        .expect("an ordinary principal's credential must verify");
    assert_ne!(ordinary.principal_id, gunnar_grpc::ANONYMOUS_PRINCIPAL_ID);
    assert!(ordinary.authenticated);

    // Red: the identical credential, with the control plane naming the
    // anonymous principal.
    harness
        .plane
        .forge_principal_id(Some(gunnar_grpc::ANONYMOUS_PRINCIPAL_ID));
    assert_eq!(
        authenticate("nonce-anonymous-caller"),
        Err(AuthFailure::Anonymous),
        "a credential resolving to the anonymous principal produced a CALLER. Anonymous is a \
         read-only git identity and must never reach the control plane."
    );

    // The caller is told nothing that distinguishes it. Saying "you are
    // anonymous" would confirm the id means something here, and it does not.
    let status = AuthFailure::Anonymous.status();
    assert_eq!(status.code(), Code::Unauthenticated);
    assert_eq!(
        status.message(),
        AuthFailure::NotVerified.status().message()
    );

    // And the audit reason is its own, so an operator can tell this apart from
    // an ordinary bad signature in the log even though the client cannot on the
    // wire.
    assert_ne!(
        AuthFailure::Anonymous.reason(),
        AuthFailure::NotVerified.reason()
    );

    // Restoring the plane restores the caller: the instrument is not sticky,
    // and the refusal above was about the forged id and nothing else.
    harness.plane.forge_principal_id(None);
    authenticate("nonce-restored-caller").expect("the ordinary answer is back");
}

/// Not one declared RPC is named with the anonymous id, and no method is
/// exempt from the gate. A "public read over gRPC" bolted on later would show
/// up here first.
#[test]
fn no_rpc_is_reachable_without_a_caller_and_none_is_anonymous_scoped() {
    assert!(
        !gunnar_grpc::ANONYMOUS_PRINCIPAL_ID.is_empty(),
        "the reserved id must be a real string; an empty one would match a Caller with no \
         principal and refuse honest traffic"
    );
    // Every audited method is in `METHODS`, and `every_rpc_refuses_an_\
    // unauthenticated_caller` (below) drives all of them with no caller at all.
    // This asserts the *count* has not silently shrunk to nothing, which would
    // make that test vacuous.
    // `DECLARED_RPCS` in the protos, minus the two `Bootstrap` RPCs served with
    // no credential on purpose. Written as the difference rather than as 60, so a
    // new RPC has to be driven above or declared open by name — it cannot be
    // absorbed by a constant somebody bumps.
    let accounted: BTreeSet<String> = audited_methods()
        .iter()
        .chain(gunnar_grpc::UNAUTHENTICATED_METHODS)
        .map(|m| (*m).to_owned())
        .collect();
    let declared = declared_rpcs();
    assert_eq!(
        declared.difference(&accounted).collect::<Vec<_>>(),
        Vec::<&String>::new(),
        "these RPCs are declared in the protos and are in neither `auth::METHODS` nor \
         `UNAUTHENTICATED_METHODS`, so nothing checks that they refuse"
    );
    assert_eq!(
        accounted.difference(&declared).collect::<Vec<_>>(),
        Vec::<&String>::new(),
        "these are named in gunnar-grpc's lists and are not RPCs the protos declare"
    );
}

// ───────────────────────────────────────────────────────────────────────────
// Authorisation: the three directions
// ───────────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn an_admin_may_mutate_and_a_reader_may_not() {
    let harness = Harness::new();
    let (admin_id, admin_key) = harness.principal("admin");
    harness.plane.grant_server(&admin_id, GrantLevel::Admin);
    let (reader_id, reader_key) = harness.principal("reader");
    harness
        .plane
        .grant(&reader_id, NS, REPO, GrantLevel::Read)
        .expect("granted read on the repo");

    let admin = harness.caller_for(&admin_key, "nonce-admin-000001");
    let reader = harness.caller_for(&reader_key, "nonce-reader-00001");

    // 1. Authenticated, with the grant → allowed.
    harness
        .access()
        .add_principal(harness.authed(
            &admin,
            AddPrincipalRequest {
                name: "ci".into(),
                kind: PrincipalKind::User as i32,
                id: String::new(),
            },
        ))
        .await
        .expect("a server-Admin principal may add a principal");

    // 2. Authenticated, WITHOUT the grant → refused, and refused as
    //    PERMISSION_DENIED rather than UNAUTHENTICATED: the server knows
    //    exactly who this is.
    let status = harness
        .access()
        .add_principal(harness.authed(
            &reader,
            AddPrincipalRequest {
                name: "smuggled".into(),
                kind: PrincipalKind::User as i32,
                id: String::new(),
            },
        ))
        .await
        .expect_err("a read-only principal must not write the key table");
    assert_eq!(status.code(), Code::PermissionDenied);
    assert!(
        status.message().contains(&reader_id),
        "the refusal must name the principal it refused: {}",
        status.message()
    );

    // 3. The same reader IS allowed what it was granted, so the refusal above
    //    is not "this principal can do nothing".
    harness
        .repos()
        .get(harness.authed(&reader, GetRepoRequest { path: path() }))
        .await
        .expect("a Read grant on the repo must allow Repos.Get");

    // 4. …and is refused a repo it has no grant on, so the allow above is not
    //    "any authenticated caller may read anything".
    harness
        .repos()
        .create_namespace(harness.authed(
            &admin,
            CreateNamespaceRequest {
                name: "other".into(),
                description: String::new(),
            },
        ))
        .await
        .expect("admin creates a second namespace");
    harness
        .repos()
        .create(harness.authed(
            &admin,
            CreateRepoRequest {
                path: Some(RepoPath::new("other", "secret")),
                ..Default::default()
            },
        ))
        .await
        .expect("admin creates a repo in it");
    let status = harness
        .repos()
        .get(harness.authed(
            &reader,
            GetRepoRequest {
                path: Some(RepoPath::new("other", "secret")),
            },
        ))
        .await
        .expect_err("a grant on one repo must not reach another");
    assert_eq!(status.code(), Code::PermissionDenied);
}

/// **Blame and search are Read-gated, like every other `Refs` read.**
///
/// The two directions the sweep above cannot show: a caller *with* Read passes
/// the gate (the memory plane then answers `Unimplemented`, which is the gate
/// having let it THROUGH — a `PermissionDenied` here would mean the verb was
/// gated too tight for the operator it exists for), and a caller with no grant
/// at all is refused `PermissionDenied`. Written against the red where the two
/// new RPCs forgot their `require` call and answered anyone, and the red where
/// they demanded more than Read.
#[tokio::test]
async fn blame_and_search_need_read_and_no_more() {
    let harness = Harness::new();
    let (reader_id, reader_key) = harness.principal("reader");
    harness
        .plane
        .grant(&reader_id, NS, REPO, GrantLevel::Read)
        .expect("granted read on the repo");
    let reader = harness.caller_for(&reader_key, "nonce-reader-blame1");

    let (stranger_id, stranger_key) = harness.principal("stranger");
    let stranger = harness.caller_for(&stranger_key, "nonce-stranger-001");

    // A Read grant passes the gate on both verbs — the memory plane then answers
    // Unimplemented, which is the gate having admitted the caller.
    let code = harness
        .refs()
        .blame(harness.authed(
            &reader,
            BlameRequest {
                repo: path(),
                path: "README.md".into(),
                ..Default::default()
            },
        ))
        .await
        .expect_err("the memory plane does not implement blame")
        .code();
    assert_eq!(
        code,
        Code::Unimplemented,
        "a Read grant must let a caller reach Refs.Blame; got {code:?}"
    );
    let code = harness
        .refs()
        .search(harness.authed(
            &reader,
            SearchRequest {
                repo: path(),
                pattern: "needle".into(),
                ..Default::default()
            },
        ))
        .await
        .expect_err("the memory plane does not implement search")
        .code();
    assert_eq!(
        code,
        Code::Unimplemented,
        "a Read grant must reach Refs.Search"
    );

    // No grant at all → refused, and refused as PermissionDenied (the server
    // knows who this is) rather than reaching the store.
    let status = harness
        .refs()
        .blame(harness.authed(
            &stranger,
            BlameRequest {
                repo: path(),
                path: "README.md".into(),
                ..Default::default()
            },
        ))
        .await
        .expect_err("a caller with no read on the repo must not blame it");
    assert_eq!(status.code(), Code::PermissionDenied);
    assert!(
        status.message().contains(&stranger_id),
        "the refusal must name the principal it refused: {}",
        status.message()
    );
    let status = harness
        .refs()
        .search(harness.authed(
            &stranger,
            SearchRequest {
                repo: path(),
                pattern: "needle".into(),
                ..Default::default()
            },
        ))
        .await
        .expect_err("a caller with no read on the repo must not search it");
    assert_eq!(status.code(), Code::PermissionDenied);
}

/// **`Repos.Gc` needs `Write`, and `Write` is enough.**
///
/// Both directions, because either one alone is a guard that cannot fail. A
/// caller holding `Write` on the repository passes the gate — the memory plane
/// then answers `Unimplemented`, which is the gate having let it THROUGH, and a
/// `PermissionDenied` there is the bug this test exists for. A caller holding
/// only `Read` is refused, so "Write is enough" is not "anyone who is
/// authenticated is enough".
///
/// The upper direction is the one that matters. gc destroys nothing —
/// `storage.rs`: "every lazily-exploded object unlinked, the commit-and-tree
/// pool kept because that is the graph" — and gating it at `Admin` like its
/// destructive neighbours is what left 26 repositories on the estate never once
/// maintained. If someone later "tightens" this to `Admin` on the grounds that
/// every other reclaim verb is, this test goes red and says why.
#[tokio::test]
async fn gc_needs_write_and_no_more() {
    let harness = Harness::new();

    let (_writer_id, writer_key) = harness.principal("writer");
    harness
        .plane
        .grant(&_writer_id, NS, REPO, GrantLevel::Write)
        .expect("granted write on the repo");
    let writer = harness.caller_for(&writer_key, "nonce-writer-gc0001");

    let (reader_id, reader_key) = harness.principal("gc-reader");
    harness
        .plane
        .grant(&reader_id, NS, REPO, GrantLevel::Read)
        .expect("granted read on the repo");
    let reader = harness.caller_for(&reader_key, "nonce-gcreader-0001");

    // Write passes the gate. Unimplemented is the memory plane, not the gate.
    let code = harness
        .repos()
        .gc(harness.authed(&writer, GcRepoRequest { path: path() }))
        .await
        .expect_err("the memory plane does not implement gc")
        .code();
    assert_eq!(
        code,
        Code::Unimplemented,
        "a Write grant must let a caller reach Repos.Gc; got {code:?}. \
         PermissionDenied here means gc is gated above Write again."
    );

    // Read does not.
    let status = harness
        .repos()
        .gc(harness.authed(&reader, GcRepoRequest { path: path() }))
        .await
        .expect_err("a read-only principal must not gc the repository");
    assert_eq!(status.code(), Code::PermissionDenied);
    assert!(
        status.message().contains(&reader_id),
        "the refusal must name the principal it refused: {}",
        status.message()
    );

    // **But Read DOES reach `GcStatus`**, and that pairing is the design:
    // asking whether maintenance ran is not asking for it. A console that could
    // press the button but not watch it would be the worse half of the pair.
    let code = harness
        .repos()
        .gc_status(harness.authed(&reader, GcStatusRequest { path: path() }))
        .await
        .expect_err("the memory plane does not implement gc status")
        .code();
    assert_eq!(
        code,
        Code::Unimplemented,
        "a Read grant must let a caller reach Repos.GcStatus; got {code:?}"
    );

    // And a stranger reaches neither, so "Read is enough for GcStatus" is not
    // "no grant is needed".
    let (_stranger_id, stranger_key) = harness.principal("gc-stranger");
    let stranger = harness.caller_for(&stranger_key, "nonce-gcstranger-01");
    let status = harness
        .repos()
        .gc_status(harness.authed(&stranger, GcStatusRequest { path: path() }))
        .await
        .expect_err("a caller with no grant must not read the repository's gc");
    assert_eq!(status.code(), Code::PermissionDenied);
}

#[tokio::test]
async fn a_namespace_grant_does_not_reach_a_repo_in_another_namespace() {
    // the one-sandbox rule pins that grants do NOT inherit. The gRPC gate must not be the
    // place that quietly reintroduces inheritance.
    let harness = Harness::new();
    let (admin_id, admin_key) = harness.principal("admin");
    harness.plane.grant_server(&admin_id, GrantLevel::Admin);
    let admin = harness.caller_for(&admin_key, "nonce-admin-000002");

    let (tenant_id, tenant_key) = harness.principal("tenant");
    harness
        .plane
        .grant(&tenant_id, NS, "", GrantLevel::Admin)
        .expect("namespace-wide admin");
    let tenant = harness.caller_for(&tenant_key, "nonce-tenant-00001");

    // Inside the namespace: allowed.
    harness
        .repos()
        .create(harness.authed(
            &tenant,
            CreateRepoRequest {
                path: Some(RepoPath::new(NS, "second")),
                ..Default::default()
            },
        ))
        .await
        .expect("a namespace admin may create a repo in that namespace");

    // A different namespace: refused, even though the level is the same.
    harness
        .repos()
        .create_namespace(harness.authed(
            &admin,
            CreateNamespaceRequest {
                name: "elsewhere".into(),
                description: String::new(),
            },
        ))
        .await
        .expect("admin creates it");
    let status = harness
        .repos()
        .create(harness.authed(
            &tenant,
            CreateRepoRequest {
                path: Some(RepoPath::new("elsewhere", "sneaky")),
                ..Default::default()
            },
        ))
        .await
        .expect_err("a grant on one namespace must not reach another");
    assert_eq!(status.code(), Code::PermissionDenied);
}

// ───────────────────────────────────────────────────────────────────────────
// Measure, never assert: neither constant survives
// ───────────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn may_stubbed_to_deny_turns_every_allow_red() {
    // If `Repos.Get` had been hard-wired to succeed, this would still pass the
    // happy-path test above. Stub the grant decision to deny and it must fail:
    // that is the proof the success went THROUGH `Identity::may`.
    let harness = Harness::new();
    let (admin_id, admin_key) = harness.principal("admin");
    harness.plane.grant_server(&admin_id, GrantLevel::Admin);
    let admin = harness.caller_for(&admin_key, "nonce-admin-000003");

    harness
        .repos()
        .get(harness.authed(&admin, GetRepoRequest { path: path() }))
        .await
        .expect("the real answer allows this");

    harness.plane.force_may(Some(false));

    for (name, code) in [
        (
            "Repos.Get",
            harness
                .repos()
                .get(harness.authed(&admin, GetRepoRequest { path: path() }))
                .await
                .map(|_| ())
                .map_err(|e| e.code()),
        ),
        (
            "Access.AddPrincipal",
            harness
                .access()
                .add_principal(harness.authed(
                    &admin,
                    AddPrincipalRequest {
                        name: "nope".into(),
                        kind: PrincipalKind::User as i32,
                        id: String::new(),
                    },
                ))
                .await
                .map(|_| ())
                .map_err(|e| e.code()),
        ),
        (
            "Admin.Stats",
            harness
                .admin()
                .stats(harness.authed(&admin, StatsRequest {}))
                .await
                .map(|_| ())
                .map_err(|e| e.code()),
        ),
        // The PKI read consults the grant decision like everything else. The
        // certificate in the answer is public; the trusted-CA list and the
        // created/imported origin beside it are this box's state, and a
        // credential is not by itself a grant to read it.
        (
            "Admin.IssuerInfo",
            harness
                .admin()
                .issuer_info(harness.authed(&admin, gunnar_proto::IssuerInfoRequest {}))
                .await
                .map(|_| ())
                .map_err(|e| e.code()),
        ),
        // The estate's boxes (2026-10-04): addresses and principals of the
        // whole estate, a server-wide fact — a credential is not by itself a
        // grant to read it.
        (
            "Admin.Topology",
            harness
                .admin()
                .topology(harness.authed(&admin, gunnar_proto::TopologyRequest {}))
                .await
                .map(|_| ())
                .map_err(|e| e.code()),
        ),
        // The audit trail read (lane T11). Its answer is a count and a hash
        // and carries no entry — but who-audits-whom is this box's state, and
        // a credential is not by itself a grant to read it.
        (
            "Admin.AuditTrail",
            harness
                .admin()
                .audit_trail(harness.authed(&admin, gunnar_proto::AuditTrailRequest { at_seq: 0 }))
                .await
                .map(|_| ())
                .map_err(|e| e.code()),
        ),
        // The tunnel address decides what the hub routes to this box: held
        // to server Admin through `may`, like GrowStart.
        (
            "Admin.SetTunnelAddress",
            harness
                .admin()
                .set_tunnel_address(harness.authed(
                    &admin,
                    gunnar_proto::AssignTunnelAddressRequest {
                        address: "10.99.0.2/24".into(),
                    },
                ))
                .await
                .map(|_| ())
                .map_err(|e| e.code()),
        ),
        // Server ADMIN (lane T9): stubbed to deny, it must be refused before the
        // seam is asked to sign anything.
        (
            "Admin.IssueTwinCertificate",
            harness
                .admin()
                .issue_twin_certificate(harness.authed(
                    &admin,
                    gunnar_proto::IssueTwinCertificateRequest {
                        principal: "twin-box".into(),
                        csr_pem: String::new(),
                    },
                ))
                .await
                .map(|_| ())
                .map_err(|e| e.code()),
        ),
        // A capacity quote names the box's free space and its disk floor. An
        // authenticated caller is not by itself entitled to it: monetize is
        // told what a tenant may be sold, and a tenant is not.
        (
            "Admin.Capacity",
            harness
                .admin()
                .capacity(harness.authed(
                    &admin,
                    CapacityRequest {
                        requested_bytes: 1,
                        namespace: String::new(),
                        disks: false,
                    },
                ))
                .await
                .map(|_| ())
                .map_err(|e| e.code()),
        ),
    ] {
        assert_eq!(
            code,
            Err(Code::PermissionDenied),
            "{name} succeeded with the grant decision stubbed to deny, so it is not \
             consulting it"
        );
    }
}

#[tokio::test]
async fn may_stubbed_to_allow_turns_every_denial_green() {
    // The other half, and the one that catches a gate which simply refuses
    // everything: with the grant decision stubbed to allow, the calls that were
    // PERMISSION_DENIED must now go through.
    let harness = Harness::new();
    let (_, key) = harness.principal("nobody");
    let nobody = harness.caller_for(&key, "nonce-nobody-00001");

    let status = harness
        .access()
        .add_principal(harness.authed(
            &nobody,
            AddPrincipalRequest {
                name: "before".into(),
                kind: PrincipalKind::User as i32,
                id: String::new(),
            },
        ))
        .await
        .expect_err("a principal with no grants must be refused");
    assert_eq!(status.code(), Code::PermissionDenied);

    harness.plane.force_may(Some(true));

    harness
        .access()
        .add_principal(harness.authed(
            &nobody,
            AddPrincipalRequest {
                name: "after".into(),
                kind: PrincipalKind::User as i32,
                id: String::new(),
            },
        ))
        .await
        .expect(
            "with the grant decision stubbed to allow, the call must go through — otherwise \
             the refusal above came from a gate that refuses everything and proves nothing",
        );
    harness
        .repos()
        .get(harness.authed(&nobody, GetRepoRequest { path: path() }))
        .await
        .expect("and so must the read");
    // `Admin.Capacity` cannot SUCCEED here — the memory control plane has no
    // filesystem to measure and says `Unimplemented` — but it must no longer
    // be refused BY THE GATE, or the PERMISSION_DENIED asserted for it in
    // `may_stubbed_to_deny_turns_every_allow_red` would prove nothing but that
    // the handler refuses everyone.
    let status = harness
        .admin()
        .capacity(harness.authed(
            &nobody,
            CapacityRequest {
                requested_bytes: 1,
                namespace: String::new(),
                disks: false,
            },
        ))
        .await
        .expect_err("the test double holds no disk, so it cannot answer");
    assert_eq!(
        status.code(),
        Code::Unimplemented,
        "with the grant decision stubbed to allow, Admin.Capacity must get PAST the gate; it \
         answered {:?}",
        status.code()
    );
}

#[tokio::test]
async fn a_valid_credential_is_not_refused() {
    // The counterweight to `every_rpc_refuses_an_unauthenticated_caller`: the
    // UNAUTHENTICATED it asserts must not be a constant.
    let harness = Harness::new();
    let (admin_id, admin_key) = harness.principal("admin");
    harness.plane.grant_server(&admin_id, GrantLevel::Admin);
    let admin = harness.caller_for(&admin_key, "nonce-admin-000004");

    harness
        .admin()
        .health(harness.authed(&admin, HealthRequest {}))
        .await
        .expect("a verified admin must be served");
}

// ───────────────────────────────────────────────────────────────────────────
// Deny by default: every declared RPC, with no interceptor in the way
// ───────────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn every_rpc_refuses_an_unauthenticated_caller() {
    // These call the handlers DIRECTLY. The interceptor is not in the path, so
    // this is not testing `AuthGate`. It is testing that no handler in the
    // crate reaches the storage seam on its own. A handler that forgot its
    // `authorize` would answer here, and go red.
    let harness = Harness::new();
    let mut covered: BTreeSet<&'static str> = BTreeSet::new();

    macro_rules! refuses {
        ($name:literal, $call:expr) => {{
            covered.insert($name);
            let status = $call
                .await
                .map(|_| ())
                .expect_err(concat!($name, " served an unauthenticated caller"));
            assert_eq!(
                status.code(),
                Code::Unauthenticated,
                "{} answered {:?}, not UNAUTHENTICATED",
                $name,
                status.code()
            );
        }};
    }

    let repos = harness.repos();
    refuses!(
        "Repos.CreateNamespace",
        repos.create_namespace(Request::new(CreateNamespaceRequest::default()))
    );
    refuses!(
        "Repos.ListNamespaces",
        repos.list_namespaces(Request::new(ListNamespacesRequest::default()))
    );
    refuses!(
        "Repos.DeleteNamespace",
        repos.delete_namespace(Request::new(DeleteNamespaceRequest {
            name: NS.into(),
            delete_repos: true,
        }))
    );
    refuses!(
        "Repos.ArchiveOut",
        repos.archive_out(Request::new(ArchiveOutRequest {
            path: path(),
            from_generation: 0,
        }))
    );
    refuses!(
        "Repos.Create",
        repos.create(Request::new(CreateRepoRequest {
            path: Some(RepoPath::new(NS, "new")),
            ..Default::default()
        }))
    );
    refuses!(
        "Repos.Delete",
        repos.delete(Request::new(DeleteRepoRequest {
            path: path(),
            ..Default::default()
        }))
    );
    refuses!(
        "Repos.Undelete",
        repos.undelete(Request::new(UndeleteRepoRequest { path: path() }))
    );
    refuses!(
        "Repos.Purge",
        repos.purge(Request::new(PurgeRepoRequest { path: path() }))
    );
    refuses!(
        "Repos.Gc",
        repos.gc(Request::new(GcRepoRequest { path: path() }))
    );
    refuses!(
        "Repos.GcStatus",
        repos.gc_status(Request::new(GcStatusRequest { path: path() }))
    );
    refuses!(
        "Repos.ListDeleted",
        repos.list_deleted(Request::new(ListDeletedRequest::default()))
    );
    refuses!(
        "Repos.ListOrphans",
        repos.list_orphans(Request::new(gunnar_proto::ListOrphansRequest::default()))
    );
    refuses!(
        "Repos.ReclaimOrphan",
        repos.reclaim_orphan(Request::new(gunnar_proto::ReclaimOrphanRequest {
            path: path()
        }))
    );
    refuses!(
        "Repos.List",
        repos.list(Request::new(ListReposRequest::default()))
    );

    // `Accounts`: the per-user gate and the hard purge. Driven with no caller
    // for the reason every other line here is — a handler that forgot its own
    // `authorize` would answer, and answering `Accounts.Purge` to a stranger is
    // the worst hole in the surface.
    let accounts = harness.accounts();
    refuses!(
        "Accounts.Gate",
        accounts.gate(Request::new(gunnar_proto::GateAccountRequest {
            account: NS.into(),
            note: "because".into(),
        }))
    );
    refuses!(
        "Accounts.Ungate",
        accounts.ungate(Request::new(gunnar_proto::UngateAccountRequest {
            account: NS.into(),
        }))
    );
    refuses!(
        "Accounts.ListAccountGates",
        accounts.list_account_gates(Request::new(gunnar_proto::ListAccountGatesRequest {}))
    );
    refuses!(
        "Accounts.Purge",
        accounts.purge(Request::new(gunnar_proto::PurgeAccountRequest {
            account: NS.into(),
            reason: "because".into(),
            remove_principal: false,
            expect_empty: false,
        }))
    );
    refuses!(
        "Accounts.PurgeStatus",
        accounts.purge_status(Request::new(gunnar_proto::PurgeAccountStatusRequest {
            account: NS.into(),
        }))
    );
    refuses!(
        "Accounts.EnrollEmployee",
        accounts.enroll_employee(Request::new(gunnar_proto::EnrollEmployeeRequest {
            account: NS.into(),
            id: "employee".into(),
            name: "employee".into(),
            ..Default::default()
        }))
    );
    refuses!(
        "Accounts.ListEmployees",
        accounts.list_employees(Request::new(gunnar_proto::ListEmployeesRequest {
            account: NS.into(),
        }))
    );
    refuses!(
        "Accounts.ClaimOperator",
        accounts.claim_operator(Request::new(gunnar_proto::ClaimOperatorRequest {
            name: "rickard".into(),
            ..Default::default()
        }))
    );
    // Clans (2026-10-05): the person's own verbs, and none without a person.
    let clans = harness.clans();
    let clan = || "fellows".to_owned();
    refuses!(
        "Clans.Create",
        clans.create(Request::new(CreateClanRequest {
            name: clan(),
            contribution_bytes: 0
        }))
    );
    refuses!(
        "Clans.Get",
        clans.get(Request::new(GetClanRequest { clan: clan() }))
    );
    refuses!("Clans.List", clans.list(Request::new(ListClansRequest {})));
    refuses!(
        "Clans.Invite",
        clans.invite(Request::new(InviteToClanRequest {
            clan: clan(),
            principal_id: "bob".into()
        }))
    );
    refuses!(
        "Clans.Accept",
        clans.accept(Request::new(AcceptClanInviteRequest {
            clan: clan(),
            contribution_bytes: 0
        }))
    );
    refuses!(
        "Clans.Decline",
        clans.decline(Request::new(DeclineClanInviteRequest {
            clan: clan(),
            principal_id: String::new()
        }))
    );
    refuses!(
        "Clans.SetContribution",
        clans.set_contribution(Request::new(SetClanContributionRequest {
            clan: clan(),
            contribution_bytes: 1
        }))
    );
    refuses!(
        "Clans.Leave",
        clans.leave(Request::new(LeaveClanRequest { clan: clan() }))
    );
    refuses!(
        "Clans.RemoveMember",
        clans.remove_member(Request::new(RemoveClanMemberRequest {
            clan: clan(),
            principal_id: "bob".into()
        }))
    );
    refuses!(
        "Clans.SetAdmin",
        clans.set_admin(Request::new(SetClanAdminRequest {
            clan: clan(),
            principal_id: "bob".into(),
            admin: true
        }))
    );
    refuses!(
        "Clans.Dissolve",
        clans.dissolve(Request::new(DissolveClanRequest { clan: clan() }))
    );
    refuses!(
        "Clans.OfferRepo",
        clans.offer_repo(Request::new(OfferRepoRequest {
            clan: clan(),
            repo: "app".into(),
            account: "bob".into()
        }))
    );
    refuses!(
        "Clans.AnswerRepoOffer",
        clans.answer_repo_offer(Request::new(AnswerRepoOfferRequest {
            clan: clan(),
            repo: "app".into(),
            accept: true
        }))
    );
    refuses!(
        "Repos.Get",
        repos.get(Request::new(GetRepoRequest { path: path() }))
    );
    refuses!(
        "Repos.SetDefaultBranch",
        repos.set_default_branch(Request::new(SetDefaultBranchRequest {
            path: path(),
            default_branch: "refs/heads/x".into(),
        }))
    );
    refuses!(
        "Repos.SetVisibility",
        repos.set_visibility(Request::new(SetVisibilityRequest {
            path: path(),
            visibility: Visibility::Public as i32,
        }))
    );
    refuses!(
        "Repos.RecipientKeys",
        repos.recipient_keys(Request::new(gunnar_proto::RecipientKeysRequest {
            path: path(),
            principal_id: "someone".into(),
        }))
    );
    refuses!(
        "Repos.SetEncrypted",
        repos.set_encrypted(Request::new(gunnar_proto::SetEncryptedRequest {
            path: path(),
            encrypted: true,
        }))
    );
    refuses!(
        "Repos.SetNamespaceSettings",
        repos.set_namespace_settings(Request::new(gunnar_proto::SetNamespaceSettingsRequest {
            name: NS.into(),
            public: Some(true),
            events_public: None,
        }))
    );

    let refs = harness.refs();
    refuses!(
        "Refs.List",
        refs.list(Request::new(ListRefsRequest {
            repo: path(),
            ..Default::default()
        }))
    );
    refuses!(
        "Refs.Get",
        refs.get(Request::new(GetRefRequest {
            repo: path(),
            ref_name: "refs/heads/main".into(),
            peel: false,
        }))
    );
    refuses!(
        "Refs.Log",
        refs.log(Request::new(LogRequest {
            repo: path(),
            ..Default::default()
        }))
    );
    refuses!(
        "Refs.ReadObject",
        refs.read_object(Request::new(ReadObjectRequest {
            repo: path(),
            oid: "deadbeef".into(),
            ..Default::default()
        }))
    );
    refuses!(
        "Refs.ReadLfsObject",
        refs.read_lfs_object(Request::new(ReadLfsObjectRequest {
            repo: path(),
            oid: "f0".repeat(32),
            ..Default::default()
        }))
    );
    refuses!(
        "Refs.Diff",
        refs.diff(Request::new(DiffRequest {
            repo: path(),
            ..Default::default()
        }))
    );
    refuses!(
        "Refs.Blame",
        refs.blame(Request::new(BlameRequest {
            repo: path(),
            path: "README.md".into(),
            ..Default::default()
        }))
    );
    refuses!(
        "Refs.Search",
        refs.search(Request::new(SearchRequest {
            repo: path(),
            pattern: "needle".into(),
            ..Default::default()
        }))
    );

    let access = harness.access();
    refuses!(
        "Access.AddPrincipal",
        access.add_principal(Request::new(AddPrincipalRequest {
            name: "x".into(),
            kind: PrincipalKind::User as i32,
            id: String::new(),
        }))
    );
    refuses!(
        "Access.ListPrincipals",
        access.list_principals(Request::new(ListPrincipalsRequest::default()))
    );
    refuses!(
        "Access.RemovePrincipal",
        access.remove_principal(Request::new(RemovePrincipalRequest {
            principal_id: "principal-00000001".into(),
        }))
    );
    refuses!(
        "Access.RenamePrincipal",
        access.rename_principal(Request::new(RenamePrincipalRequest {
            principal_id: "principal-00000001".into(),
            name: "somebody else".into(),
        }))
    );
    refuses!(
        "Access.AddKey",
        access.add_key(Request::new(AddKeyRequest {
            principal_id: "principal-00000001".into(),
            openssh_public_key: "ssh-ed25519 AAAA x".into(),
            ..Default::default()
        }))
    );
    refuses!(
        "Access.RevokeKey",
        access.revoke_key(Request::new(RevokeKeyRequest {
            fingerprint: "SHA256:whatever".into(),
        }))
    );
    // The four GROUP verbs. They were in no list at all until GUN-023, so
    // this sweep never drove them.
    refuses!(
        "Access.AddGroupMember",
        access.add_group_member(Request::new(AddGroupMemberRequest {
            group_id: "reviewers".into(),
            member_id: "someone".into(),
            signed: None,
        }))
    );
    refuses!(
        "Access.RemoveGroupMember",
        access.remove_group_member(Request::new(RemoveGroupMemberRequest {
            group_id: "reviewers".into(),
            member_id: "someone".into(),
            signed: None,
        }))
    );
    refuses!(
        "Access.ListGroupMembers",
        access.list_group_members(Request::new(ListGroupMembersRequest {
            group_id: "reviewers".into(),
        }))
    );
    refuses!(
        "Access.ListGroupMembershipEvents",
        access.list_group_membership_events(Request::new(ListGroupMembershipEventsRequest {
            group_id: "reviewers".into(),
        }))
    );
    refuses!(
        "Access.ListKeys",
        access.list_keys(Request::new(ListKeysRequest::default()))
    );
    // The caller's own standing (2026-10-04): no grant, but never a stranger.
    refuses!(
        "Access.WhoAmI",
        access.who_am_i(Request::new(WhoAmIRequest::default()))
    );
    refuses!(
        "Access.AddCredential",
        access.add_credential(Request::new(AddCredentialRequest::default()))
    );
    refuses!(
        "Access.ListCredentials",
        access.list_credentials(Request::new(ListCredentialsRequest::default()))
    );
    refuses!(
        "Access.RevokeCredential",
        access.revoke_credential(Request::new(RevokeCredentialRequest::default()))
    );
    refuses!(
        "Access.RenameCredential",
        access.rename_credential(Request::new(RenameCredentialRequest::default()))
    );
    refuses!(
        "Access.GetEncryptionKey",
        access.get_encryption_key(Request::new(GetEncryptionKeyRequest::default()))
    );
    refuses!(
        "Access.CreateEncryptionKey",
        access.create_encryption_key(Request::new(CreateEncryptionKeyRequest::default()))
    );
    refuses!(
        "Access.AddUnlockMethod",
        access.add_unlock_method(Request::new(AddUnlockMethodRequest::default()))
    );
    refuses!(
        "Access.RemoveUnlockMethod",
        access.remove_unlock_method(Request::new(RemoveUnlockMethodRequest::default()))
    );
    refuses!(
        "Access.EnrolmentLink",
        access.enrolment_link(Request::new(EnrolmentLinkRequest::default()))
    );
    refuses!(
        "Access.MachineChallenge",
        access.machine_challenge(Request::new(MachineChallengeRequest::default()))
    );
    refuses!(
        "Access.RequestMachineEnrolment",
        access.request_machine_enrolment(Request::new(RequestMachineEnrolmentRequest::default()))
    );
    refuses!(
        "Access.MachineEnrolmentStatus",
        access.machine_enrolment_status(Request::new(MachineEnrolmentStatusRequest::default()))
    );
    refuses!(
        "Access.ListMachineEnrolments",
        access.list_machine_enrolments(Request::new(ListMachineEnrolmentsRequest::default()))
    );
    refuses!(
        "Access.ApproveMachineEnrolment",
        access.approve_machine_enrolment(Request::new(ApproveMachineEnrolmentRequest::default()))
    );
    refuses!(
        "Access.RefuseMachineEnrolment",
        access.refuse_machine_enrolment(Request::new(RefuseMachineEnrolmentRequest::default()))
    );
    refuses!(
        "Access.Check",
        access.check(Request::new(CheckRequest {
            namespace: NS.into(),
            repo: String::new(),
            level: GrantLevel::Admin as i32,
        }))
    );
    refuses!(
        "Access.Grant",
        access.grant(Request::new(GrantRequest {
            principal_id: "principal-00000001".into(),
            namespace: NS.into(),
            repo: REPO.into(),
            level: GrantLevel::Admin as i32,
        }))
    );
    refuses!(
        "Access.Revoke",
        access.revoke(Request::new(RevokeRequest {
            principal_id: "principal-00000001".into(),
            namespace: NS.into(),
            repo: REPO.into(),
        }))
    );
    refuses!(
        "Access.ListGrants",
        access.list_grants(Request::new(ListGrantsRequest::default()))
    );

    let policy = harness.policy();
    refuses!(
        "Policy.GetProtection",
        policy.get_protection(Request::new(GetProtectionRequest {
            repo: path(),
            ..Default::default()
        }))
    );
    refuses!(
        "Policy.SetProtection",
        policy.set_protection(Request::new(SetProtectionRequest {
            repo: path(),
            protection: Some(BranchProtection {
                ref_pattern: "refs/heads/main".into(),
                ..Default::default()
            }),
        }))
    );
    refuses!(
        "Policy.DeleteProtection",
        policy.delete_protection(Request::new(DeleteProtectionRequest {
            repo: path(),
            ref_pattern: "refs/heads/main".into(),
        }))
    );
    refuses!(
        "Policy.GetRefNamePolicy",
        policy.get_ref_name_policy(Request::new(GetRefNamePolicyRequest { repo: path() }))
    );
    refuses!(
        "Policy.SetRefNamePolicy",
        policy.set_ref_name_policy(Request::new(SetRefNamePolicyRequest {
            repo: path(),
            policy: Some(RefNamePolicy::default()),
        }))
    );
    refuses!(
        "Policy.ListGates",
        policy.list_gates(Request::new(ListGatesRequest { repo: path() }))
    );

    refuses!(
        "Events.Watch",
        harness
            .events()
            .watch(Request::new(WatchRequest::default()))
    );

    let admin = harness.admin();
    refuses!("Admin.Health", admin.health(Request::new(HealthRequest {})));
    // `Admin.Capacity` answers "could you serve a cap of N bytes" — the box's
    // free space, its disk floor and what a named tenant holds. That is the
    // whole filesystem's business, so it is refused to a caller with no
    // credential like every other server-wide read.
    refuses!(
        "Admin.Capacity",
        admin.capacity(Request::new(CapacityRequest {
            requested_bytes: 1,
            namespace: String::new(),
            disks: false,
        }))
    );
    refuses!("Admin.Stats", admin.stats(Request::new(StatsRequest {})));
    // The runtime data-set growth: two mutators and the credentialled status.
    // (`Bootstrap.GrowStatus` is the credential-free twin, in
    // UNAUTHENTICATED_METHODS with its reason.)
    refuses!(
        "Admin.GrowStart",
        admin.grow_start(Request::new(GrowStartRequest {
            go_ahead: b"{}".to_vec(),
            ..Default::default()
        }))
    );
    refuses!(
        "Admin.GrowStatus",
        admin.grow_status(Request::new(GrowStatusRequest {}))
    );
    refuses!(
        "Admin.GrowResume",
        admin.grow_resume(Request::new(GrowResumeRequest { give_up: false }))
    );
    refuses!(
        "Admin.StorageInfo",
        admin.storage_info(Request::new(StorageInfoRequest { repo: None }))
    );
    // **The PKI read** (2026-09-17, lane PKI-READ). Driven the day it was
    // declared, not three lanes later: the certificate it returns is public,
    // but the trusted-CA list, the created/imported origin and the adoption
    // date are this box's PKI state, and a caller with no credential at all
    // gets none of it.
    refuses!(
        "Admin.IssuerInfo",
        admin.issuer_info(Request::new(gunnar_proto::IssuerInfoRequest {}))
    );
    // **The audit trail read is behind the gate too** (lane T11), declared
    // here at the door rather than three lanes later. It returns no entry —
    // but "how many decisions has this box made, and do they still verify" is
    // a fact about the box, and an unauthenticated caller gets none of it.
    refuses!(
        "Admin.AuditTrail",
        admin.audit_trail(Request::new(gunnar_proto::AuditTrailRequest { at_seq: 0 }))
    );
    // **The estate's boxes** (2026-10-04): which boxes exist and where, a
    // stranger gets none of it.
    refuses!(
        "Admin.Topology",
        admin.topology(Request::new(gunnar_proto::TopologyRequest {}))
    );
    // **The tunnel address of an enrolled box** (2026-09-21, T17): server
    // Admin, so a caller with no credential is refused before the plane.
    refuses!(
        "Admin.SetTunnelAddress",
        admin.set_tunnel_address(Request::new(gunnar_proto::AssignTunnelAddressRequest {
            address: "10.99.0.2/24".into(),
        }))
    );
    // A twin's replication certificate (lane T9): it mints a credential into
    // the stream that carries every sealed secret, so a caller with nothing
    // gets nothing — not even the seam's own refusals.
    refuses!(
        "Admin.IssueTwinCertificate",
        admin.issue_twin_certificate(Request::new(gunnar_proto::IssueTwinCertificateRequest {
            principal: "twin-box".into(),
            csr_pem: String::new(),
        }))
    );
    refuses!(
        "Admin.VerifyChain",
        admin.verify_chain(Request::new(VerifyChainRequest {
            repo: Some(RepoPath::new(NS, REPO)),
            ..Default::default()
        }))
    );
    // **The generic server settings** (owner 2026-10-26): server Admin, so a caller with
    // nothing reads and writes nothing.
    refuses!(
        "Admin.GetSetting",
        admin.get_setting(Request::new(gunnar_proto::GetSettingRequest {
            name: "console.a-switch".into()
        }))
    );
    refuses!(
        "Admin.SetSetting",
        admin.set_setting(Request::new(gunnar_proto::SetSettingRequest {
            name: "console.a-switch".into(),
            value: b"on".to_vec()
        }))
    );

    #[cfg(feature = "metered")]
    {
        use gunnar_proto::entitlement_server::Entitlement as _;
        let entitlement = gunnar_grpc::EntitlementService::new(harness.ctx.clone());
        refuses!(
            "Entitlement.Get",
            entitlement.get(Request::new(GetEntitlementRequest {
                namespace: NS.into(),
            }))
        );
        refuses!(
            "Entitlement.List",
            entitlement.list(Request::new(ListEntitlementsRequest {}))
        );
        refuses!(
            "Entitlement.Set",
            entitlement.set(Request::new(SetEntitlementRequest { fact: None }))
        );

        // **`Billing.*`** (2026-09-17). Driven here for the same reason
        // everything else is: an RPC absent from this sweep is an RPC nothing
        // checks the deny-by-default behaviour of. The scope check that makes
        // `MintActorTicket` safe is in `tests/billing.rs`; what this asserts is
        // the floor under it — with no verified caller at all, neither verb
        // answers, and in particular the one that SIGNS does not sign.
        use gunnar_proto::billing_server::Billing as _;
        let billing = gunnar_grpc::BillingService::new(harness.ctx.clone());
        refuses!(
            "Billing.MintActorTicket",
            billing.mint_actor_ticket(Request::new(gunnar_proto::MintActorTicketRequest {
                namespace: NS.into(),
                purpose: String::new(),
                // An empty purpose is a renewal, and a renewal names no caps.
                // The shape has to be a request the handler would otherwise
                // ACCEPT, or the refusal this sweep asserts could be about the
                // arguments rather than about the missing credential.
                caps: Default::default(),
            }))
        );
        refuses!(
            "Billing.ApplianceIdentity",
            billing.appliance_identity(Request::new(gunnar_proto::ApplianceIdentityRequest {}))
        );
        // **`Sealed.*`** (2026-10-09): a slot is its owner's alone; a caller
        // with nothing reads and writes nothing. The owner rule itself is in
        // `service::sealed`'s unit tests.
        use gunnar_proto::sealed_server::Sealed as _;
        let sealed = gunnar_grpc::SealedService::new(harness.ctx.clone());
        refuses!(
            "Sealed.Put",
            sealed.put(Request::new(gunnar_proto::SealedPutRequest {
                name: "slot".into(),
                value: b"x".to_vec(),
                owner: String::new()
            }))
        );
        refuses!(
            "Sealed.Get",
            sealed.get(Request::new(gunnar_proto::SealedGetRequest {
                name: "slot".into()
            }))
        );
    }

    let usage = harness.usage();
    refuses!(
        "Usage.Read",
        usage.read(Request::new(ReadUsageRequest {
            namespace: NS.into(),
        }))
    );
    refuses!(
        "Usage.ReadAll",
        usage.read_all(Request::new(ReadAllUsageRequest {}))
    );
    refuses!(
        "Usage.Activity",
        usage.activity(Request::new(ActivityRequest {
            namespace: NS.into(),
            since_unix_ms: 0,
            until_unix_ms: 0,
        }))
    );
    refuses!(
        "Usage.AdmitPlan",
        usage.admit_plan(Request::new(gunnar_proto::AdmitPlanRequest {
            namespace: NS.into(),
        }))
    );
    // Many namespaces' meters in one call (2026-10-06): `ReadAll`'s grant.
    let usage_batch = harness.usage_batch();
    refuses!(
        "UsageBatch.ReadMany",
        usage_batch.read_many(Request::new(gunnar_proto::ReadManyUsageRequest::default()))
    );

    let mirror = harness.mirror();
    refuses!(
        "Mirror.Add",
        mirror.add(Request::new(AddMirrorRequest {
            repo: path(),
            remote_url: "ssh://example/x.git".into(),
            ..Default::default()
        }))
    );
    refuses!(
        "Mirror.Sync",
        mirror.sync(Request::new(SyncMirrorRequest { repo: path() }))
    );
    refuses!(
        "Mirror.Status",
        mirror.status(Request::new(MirrorStatusRequest::default()))
    );
    // **The three replication RPCs, added with the soft-delete work and never driven here.**
    //
    // They were never a HOLE — `MirrorServer` is mounted `with_interceptor`,
    // and only `Bootstrap` sits outside the gate — but nothing verified that,
    // so the guarantee was unchecked for the RPCs that decide WHERE a copy of
    // every object gets shipped. The count assertion at the end of this test is
    // what caught it, which is that assertion earning its place: a bare number
    // nobody reconciles against the protos would have let five RPCs sit
    // undriven indefinitely.
    refuses!(
        "Mirror.SetReplication",
        mirror.set_replication(Request::new(SetReplicationRequest::default()))
    );
    refuses!(
        "Mirror.RemoveReplication",
        mirror.remove_replication(Request::new(RemoveReplicationRequest {
            name: "standby".into(),
        }))
    );
    refuses!(
        "Mirror.DemoteReplication",
        mirror.demote_replication(Request::new(DemoteReplicationRequest {}))
    );
    refuses!(
        "Mirror.SetRole",
        mirror.set_role(Request::new(SetRoleRequest {
            role: ReplicationRole::Standby as i32,
        }))
    );
    refuses!(
        "Mirror.AbdicateReplication",
        mirror.abdicate_replication(Request::new(AbdicateReplicationRequest {}))
    );
    refuses!(
        "Mirror.ReplicationStatus",
        mirror.replication_status(Request::new(ReplicationStatusRequest {
            include_refs: false
        }))
    );
    refuses!(
        "Mirror.Remove",
        mirror.remove(Request::new(RemoveMirrorRequest { repo: path() }))
    );
    refuses!(
        "Mirror.SetCredential",
        mirror.set_credential(Request::new(SetMirrorCredentialRequest {
            repo: path(),
            ..Default::default()
        }))
    );
    refuses!(
        "Mirror.ResyncReplication",
        mirror.resync_replication(Request::new(ResyncReplicationRequest {
            name: "standby".into(),
            ..Default::default()
        }))
    );
    refuses!(
        "Mirror.FlushReplication",
        mirror.flush_replication(Request::new(FlushReplicationRequest::default()))
    );
    refuses!(
        "Mirror.LogHead",
        mirror.log_head(Request::new(gunnar_proto::LogHeadRequest::default()))
    );
    refuses!(
        "Mirror.LogFetch",
        mirror.log_fetch(Request::new(gunnar_proto::LogFetchRequest {
            from: 1,
            ..Default::default()
        }))
    );

    let forge = harness.forge();
    let repo = || format!("{NS}/{REPO}");
    refuses!(
        "Forge.Append",
        forge.append(Request::new(AppendEventRequest {
            event: Some(SignedForgeEvent {
                event: Some(gunnar_proto::ForgeEvent {
                    repo: repo(),
                    pull: 1,
                    actor: "someone".into(),
                    at_unix_ms: 0,
                    kind: Some(gunnar_proto::forge_event::Kind::Commented(
                        gunnar_proto::Commented {
                            body: "hi".into(),
                            ..Default::default()
                        }
                    )),
                }),
                key_fingerprint: "SHA256:nope".into(),
                signature: String::new(),
                attested: None,
            }),
        }))
    );
    refuses!(
        "Forge.GetReview",
        forge.get_review(Request::new(GetReviewRequest {
            repo: repo(),
            pull: 1,
        }))
    );
    refuses!(
        "Forge.ListReviews",
        forge.list_reviews(Request::new(ListReviewsRequest { repo: repo() }))
    );
    refuses!(
        "Forge.GetIssue",
        forge.get_issue(Request::new(GetIssueRequest {
            repo: repo(),
            number: 1,
        }))
    );
    refuses!(
        "Forge.ListIssues",
        forge.list_issues(Request::new(ListIssuesRequest { repo: repo() }))
    );

    // The three `Webhooks.*` RPCs, and the service was not even built here
    // before GUN-023: an entire mounted service outside the sweep.
    let webhooks = harness.webhooks();
    refuses!(
        "Webhooks.AddWebhook",
        webhooks.add_webhook(Request::new(AddWebhookRequest {
            name: "ci".into(),
            url: "https://example.invalid/hook".into(),
            ..Default::default()
        }))
    );
    refuses!(
        "Webhooks.ListWebhooks",
        webhooks.list_webhooks(Request::new(ListWebhooksRequest {}))
    );
    refuses!(
        "Webhooks.RemoveWebhook",
        webhooks.remove_webhook(Request::new(RemoveWebhookRequest { name: "ci".into() }))
    );

    // The five `PullRequests.*` RPCs. They authorise in `service::pulls` and
    // were missing from `auth::METHODS` until the two designs were merged, so
    // this sweep never drove them — the exact hole the census exists to close.
    let pulls = harness.pulls();
    refuses!(
        "PullRequests.Create",
        pulls.create(Request::new(CreatePullRequestRequest {
            repo: path(),
            title: "t".into(),
            description: String::new(),
            source_ref: "refs/heads/topic".into(),
            target_ref: "refs/heads/main".into(),
        }))
    );
    refuses!(
        "PullRequests.List",
        pulls.list(Request::new(ListPullRequestsRequest {
            repo: path(),
            state: 0,
        }))
    );
    refuses!(
        "PullRequests.Get",
        pulls.get(Request::new(GetPullRequestRequest {
            repo: path(),
            number: 1,
        }))
    );
    refuses!(
        "PullRequests.Close",
        pulls.close(Request::new(ClosePullRequestRequest {
            repo: path(),
            number: 1,
        }))
    );
    refuses!(
        "PullRequests.Merge",
        pulls.merge(Request::new(MergePullRequestRequest {
            repo: path(),
            number: 1,
        }))
    );

    // **The twelve that were served and censused nowhere** (2026-09-11,
    // GUN-023/GUN-024). Each one authorises in its handler — every one was read
    // — so none of them was an open door. What was missing is this: an RPC
    // absent from `auth::METHODS` is an RPC this sweep has never once driven,
    // so nothing would notice if one stopped authorising. That is the same hole
    // the `PullRequests.*` note above records, five RPCs and one release
    // earlier, which is what makes the hand-kept census the defect rather than
    // the omissions. `tests/census.rs` derives the list from the protos now.
    use gunnar_proto::webhooks_server::Webhooks as _;
    refuses!(
        "Access.AddGroupMember",
        access.add_group_member(Request::new(AddGroupMemberRequest {
            group_id: "team".into(),
            member_id: "someone".into(),
            signed: None,
        }))
    );
    refuses!(
        "Access.RemoveGroupMember",
        access.remove_group_member(Request::new(RemoveGroupMemberRequest {
            group_id: "team".into(),
            member_id: "someone".into(),
            signed: None,
        }))
    );
    refuses!(
        "Access.ListGroupMembers",
        access.list_group_members(Request::new(ListGroupMembersRequest {
            group_id: "team".into(),
        }))
    );
    refuses!(
        "Access.ListGroupMembershipEvents",
        access.list_group_membership_events(Request::new(ListGroupMembershipEventsRequest {
            group_id: String::new(),
        }))
    );
    refuses!(
        "Forge.GetIssue",
        forge.get_issue(Request::new(GetIssueRequest {
            repo: repo(),
            number: 1,
        }))
    );
    refuses!(
        "Forge.ListIssues",
        forge.list_issues(Request::new(ListIssuesRequest { repo: repo() }))
    );
    refuses!(
        "Mirror.SetCredential",
        mirror.set_credential(Request::new(SetMirrorCredentialRequest {
            repo: path(),
            ..Default::default()
        }))
    );
    refuses!(
        "Mirror.ResyncReplication",
        mirror.resync_replication(Request::new(ResyncReplicationRequest {
            name: "standby".into(),
            ..Default::default()
        }))
    );
    refuses!(
        "Mirror.LogHead",
        mirror.log_head(Request::new(gunnar_proto::LogHeadRequest::default()))
    );
    refuses!(
        "Mirror.LogFetch",
        mirror.log_fetch(Request::new(gunnar_proto::LogFetchRequest {
            from: 1,
            ..Default::default()
        }))
    );
    // **The two the sweep had drifted away from** (2026-09-16, lane AUDIT-TWIN). The drift
    // assertion at the end of this test was RED on master for `Mirror.SnapshotFetch` — the verb
    // that streams every sealed secret and every object on the box — and
    // `no_rpc_is_reachable_without_a_caller_and_none_is_anonymous_scoped` was RED for
    // `Mirror.LogRetain`, which was in neither `auth::METHODS` nor `UNAUTHENTICATED_METHODS` at
    // all. Both authorise in their handlers and always did; neither had ever been DRIVEN
    // without a credential, which is the whole point of this sweep and the third time that
    // omission has been found here.
    refuses!(
        "Mirror.SnapshotFetch",
        mirror.snapshot_fetch(Request::new(gunnar_proto::SnapshotFetchRequest::default()))
    );
    refuses!(
        "Mirror.LogRetain",
        mirror.log_retain(Request::new(gunnar_proto::LogRetainRequest {
            from: 1,
            allow_past_twin: false
        }))
    );
    refuses!(
        "Usage.Activity",
        usage.activity(Request::new(ActivityRequest {
            namespace: NS.into(),
            ..Default::default()
        }))
    );
    refuses!(
        "Usage.AdmitPlan",
        usage.admit_plan(Request::new(gunnar_proto::AdmitPlanRequest {
            namespace: NS.into(),
        }))
    );
    let webhooks = harness.webhooks();
    refuses!(
        "Webhooks.AddWebhook",
        webhooks.add_webhook(Request::new(AddWebhookRequest {
            name: "hook".into(),
            url: "https://example/hook".into(),
            ..Default::default()
        }))
    );
    refuses!(
        "Webhooks.ListWebhooks",
        webhooks.list_webhooks(Request::new(ListWebhooksRequest {}))
    );
    refuses!(
        "Webhooks.RemoveWebhook",
        webhooks.remove_webhook(Request::new(RemoveWebhookRequest {
            name: "hook".into(),
        }))
    );

    // The owner's enterprise list (2026-10-05): the account admin's audit
    // log, the operator's aggregates and look, the name filter.
    {
        use gunnar_proto::enterprise_server::Enterprise as _;
        let e = harness.enterprise();
        refuses!(
            "Enterprise.AuditLog",
            e.audit_log(Request::new(AuditLogRequest {
                account: NS.into(),
                ..Default::default()
            }))
        );
        refuses!(
            "Enterprise.ExportAuditLog",
            e.export_audit_log(Request::new(ExportAuditLogRequest {
                account: NS.into(),
                ..Default::default()
            }))
        );
        refuses!(
            "Enterprise.Aggregates",
            e.aggregates(Request::new(AggregatesRequest {}))
        );
        refuses!(
            "Enterprise.RequestOperatorAccess",
            e.request_operator_access(Request::new(RequestOperatorAccessRequest {
                account: NS.into(),
                reason: "why".into(),
                minutes: 0
            }))
        );
        refuses!(
            "Enterprise.ListOperatorAccess",
            e.list_operator_access(Request::new(ListOperatorAccessRequest {
                account: NS.into()
            }))
        );
        refuses!(
            "Enterprise.ApproveOperatorAccess",
            e.approve_operator_access(Request::new(ApproveOperatorAccessRequest::default()))
        );
        refuses!(
            "Enterprise.RefuseOperatorAccess",
            e.refuse_operator_access(Request::new(RefuseOperatorAccessRequest::default()))
        );
        refuses!(
            "Enterprise.RevokeOperatorAccess",
            e.revoke_operator_access(Request::new(RevokeOperatorAccessRequest::default()))
        );
        refuses!(
            "Enterprise.CheckName",
            e.check_name(Request::new(CheckNameRequest {
                kind: "repo".into(),
                name: "x".into(),
                account: String::new()
            }))
        );
        refuses!(
            "Enterprise.GetNameLists",
            e.get_name_lists(Request::new(GetNameListsRequest {}))
        );
        refuses!(
            "Enterprise.SetNameLists",
            e.set_name_lists(Request::new(SetNameListsRequest::default()))
        );
        refuses!(
            "Enterprise.ListNameReviews",
            e.list_name_reviews(Request::new(ListNameReviewsRequest { account: NS.into() }))
        );
        refuses!(
            "Enterprise.DecideNameReview",
            e.decide_name_review(Request::new(DecideNameReviewRequest::default()))
        );
    }

    // Company SSO (2026-10-05): the account admin's verbs and the relay's.
    let sso = harness.sso();
    refuses!(
        "Sso.SetProvider",
        sso.set_provider(Request::new(SetProviderRequest::default()))
    );
    refuses!(
        "Sso.GetProvider",
        sso.get_provider(Request::new(GetProviderRequest {
            account: NS.into(),
            ..Default::default()
        }))
    );
    refuses!(
        "Sso.RemoveProvider",
        sso.remove_provider(Request::new(RemoveProviderRequest { account: NS.into() }))
    );
    refuses!(
        "Sso.CreateScimToken",
        sso.create_scim_token(Request::new(CreateScimTokenRequest {
            account: NS.into(),
            label: String::new(),
            ..Default::default()
        }))
    );
    refuses!(
        "Sso.ListScimTokens",
        sso.list_scim_tokens(Request::new(ListScimTokensRequest { account: NS.into() }))
    );
    refuses!(
        "Sso.RevokeScimToken",
        sso.revoke_scim_token(Request::new(RevokeScimTokenRequest::default()))
    );
    refuses!(
        "Sso.ListDirectory",
        sso.list_directory(Request::new(ListDirectoryRequest { account: NS.into() }))
    );
    refuses!(
        "Sso.SetUserActive",
        sso.set_user_active(Request::new(SetUserActiveRequest::default()))
    );
    refuses!(
        "Sso.ImportUsers",
        sso.import_users(Request::new(ImportUsersRequest::default()))
    );
    refuses!(
        "Sso.ImportStatus",
        sso.import_status(Request::new(ImportStatusRequest::default()))
    );
    refuses!(
        "Sso.Discover",
        sso.discover(Request::new(DiscoverRequest {
            hint: "bob@acme.example".into()
        }))
    );
    refuses!(
        "Sso.Begin",
        sso.begin(Request::new(BeginRequest::default()))
    );
    refuses!(
        "Sso.Finish",
        sso.finish(Request::new(FinishRequest::default()))
    );
    refuses!(
        "Sso.SecondFactor",
        sso.second_factor(Request::new(SecondFactorRequest::default()))
    );
    refuses!("Sso.Scim", sso.scim(Request::new(ScimRequest::default())));
    refuses!(
        "Sso.VerifyDomain",
        sso.verify_domain(Request::new(VerifyDomainRequest {
            account: NS.into(),
            domain: "acme.example".into()
        }))
    );
    refuses!(
        "Sso.RebindUsers",
        sso.rebind_users(Request::new(RebindUsersRequest {
            account: NS.into(),
            ..Default::default()
        }))
    );

    // The sweep and the crate's own list of audited methods must agree, so a
    // new RPC cannot be added without landing in both.
    assert_eq!(
        covered,
        audited_methods(),
        "the deny-by-default sweep and gunnar_grpc::auth::METHODS have drifted"
    );
    // **The arithmetic, not a bare number.** The protos declare `DECLARED_RPCS`; two of
    // them (`Bootstrap.Enroll`, `Bootstrap.Status`) are served with no
    // credential on purpose and are listed in `UNAUTHENTICATED_METHODS` with
    // the reason. Everything else must be swept here.
    //
    // Written as the SUM so the next RPC cannot land quietly: adding one moves
    // the declared count, and the only ways to keep this green are to drive it
    // above or to say out loud, in UNAUTHENTICATED_METHODS, that it needs no
    // credential. A hardcoded 56 would have been satisfied by driving 56 of
    // anything.
    let declared = declared_rpcs();
    let swept: BTreeSet<String> = covered
        .iter()
        .chain(gunnar_grpc::UNAUTHENTICATED_METHODS)
        .map(|m| (*m).to_owned())
        .collect();
    assert_eq!(
        declared.difference(&swept).collect::<Vec<_>>(),
        Vec::<&String>::new(),
        "these RPCs are declared in the protos and this sweep never drove them, so nothing \
         checks that they refuse an unauthenticated caller. Drive them here, or say out loud \
         in UNAUTHENTICATED_METHODS that they need no credential."
    );
}

#[tokio::test]
async fn the_escape_hatch_serves_what_the_default_refuses() {
    // The escape hatch must actually be an escape hatch; otherwise the
    // sweep above would pass against a server that is simply broken.
    let plane = Arc::new(MemoryControlPlane::with_repo(NS, REPO));
    let control: Arc<dyn ControlPlane> = plane.clone();
    let ctx = ServiceContext::new(
        control,
        Arc::new(EventBus::new(64)),
        ServerConfig::default().insecure_allow_all_for_local_development(),
    );
    let served = AdminService::new(ctx)
        .health(Request::new(HealthRequest {}))
        .await
        .expect("the escape hatch serves an unauthenticated caller")
        .into_inner();
    assert!(
        !served.grpc_authentication_enabled,
        "and says so on the wire"
    );
}

// ───────────────────────────────────────────────────────────────────────────
// The audit trail
// ───────────────────────────────────────────────────────────────────────────

/// Captures `tracing` events emitted on [`AUDIT_TARGET`], with their fields.
#[derive(Clone, Default)]
struct AuditLog(Arc<Mutex<Vec<String>>>);

impl AuditLog {
    fn lines(&self) -> Vec<String> {
        self.0.lock().unwrap().clone()
    }
}

struct AuditLayer(AuditLog);

impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for AuditLayer {
    fn on_event(
        &self,
        event: &tracing::Event<'_>,
        _ctx: tracing_subscriber::layer::Context<'_, S>,
    ) {
        if event.metadata().target() != AUDIT_TARGET {
            return;
        }
        struct Visit(String);
        impl tracing::field::Visit for Visit {
            fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
                self.0.push_str(&format!("{}={:?} ", field.name(), value));
            }
        }
        let mut visit = Visit(String::new());
        event.record(&mut visit);
        self.0 .0.lock().unwrap().push(visit.0);
    }
}

fn capture_audit() -> (AuditLog, impl tracing::Subscriber + Send + Sync) {
    let log = AuditLog::default();
    let subscriber = tracing_subscriber::registry().with(AuditLayer(log.clone()));
    (log, subscriber)
}

#[test]
fn a_mutation_emits_an_audit_record_naming_the_caller() {
    // Every gRPC service file used to have zero log lines, so the one
    // surface that most needed an audit trail had none at all.
    let (log, subscriber) = capture_audit();
    let runtime = tokio::runtime::Builder::new_current_thread()
        .build()
        .expect("runtime");

    with_default(subscriber, || {
        let harness = Harness::new();
        let (admin_id, admin_key) = harness.principal("admin");
        harness.plane.grant_server(&admin_id, GrantLevel::Admin);
        let admin = harness.caller_for(&admin_key, "nonce-admin-000005");
        log.0.lock().unwrap().clear();

        runtime.block_on(async {
            harness
                .repos()
                .create(harness.authed(
                    &admin,
                    CreateRepoRequest {
                        path: Some(RepoPath::new(NS, "audited")),
                        ..Default::default()
                    },
                ))
                .await
                .expect("created");
        });

        let lines = log.lines();
        let record = lines
            .iter()
            .find(|line| line.contains("Repos.Create"))
            .unwrap_or_else(|| panic!("no audit record for the mutation; captured {lines:#?}"));
        assert!(
            record.contains(&format!("principal={admin_id} ")),
            "the record does not name the caller: {record}"
        );
        assert!(
            record.contains("decision=\"allow\""),
            "the record does not carry the decision: {record}"
        );
        assert!(
            record.contains(&format!("scope=namespace:{NS} ")),
            "the record does not carry the scope: {record}"
        );
        assert!(
            record.contains("auth_mode=\"required\""),
            "the record does not say which mode served it: {record}"
        );
    });
}

#[test]
fn a_call_refused_before_the_handler_leaves_no_call_record() {
    // The other half of the audit claim: a request the gate turned away must
    // not produce a `grpc.call` record, because nothing was called. If it did,
    // the trail would show admin activity that never happened.
    let (log, subscriber) = capture_audit();
    let runtime = tokio::runtime::Builder::new_current_thread()
        .build()
        .expect("runtime");

    with_default(subscriber, || {
        let harness = Harness::new();
        log.0.lock().unwrap().clear();

        // (a) refused by the interceptor, before any handler exists.
        let mut gate = harness.gate();
        let refused = <AuthGate as tonic::service::Interceptor>::call(&mut gate, Request::new(()));
        assert_eq!(refused.err().map(|s| s.code()), Some(Code::Unauthenticated));

        // (b) and the handler, driven directly, also refuses.
        runtime.block_on(async {
            harness
                .repos()
                .create(Request::new(CreateRepoRequest {
                    path: Some(RepoPath::new(NS, "never")),
                    ..Default::default()
                }))
                .await
                .expect_err("refused");
        });

        let lines = log.lines();
        assert!(
            lines.iter().any(|l| l.contains("grpc.auth.refused")),
            "the refusal itself must be recorded; captured {lines:#?}"
        );
        assert!(
            !lines.iter().any(|l| l.contains("grpc.call")),
            "a refused call produced a control-plane call record: {lines:#?}"
        );
        assert!(
            !lines.iter().any(|l| l.contains("Repos.Create")),
            "a refused call named a method it never reached: {lines:#?}"
        );
    });

    // …and the capture itself is not broken: an allowed call DOES produce one.
    // Without this, the two assertions above would pass against a subscriber
    // that captured nothing at all (measured, not asserted).
    let (log, subscriber) = capture_audit();
    with_default(subscriber, || {
        let harness = Harness::new();
        let (admin_id, admin_key) = harness.principal("admin");
        harness.plane.grant_server(&admin_id, GrantLevel::Admin);
        let admin = harness.caller_for(&admin_key, "nonce-admin-000006");
        runtime.block_on(async {
            harness
                .admin()
                .stats(harness.authed(&admin, StatsRequest {}))
                .await
                .expect("stats");
        });
        assert!(
            log.lines().iter().any(|l| l.contains("grpc.call")),
            "the audit capture never sees anything, so the absence assertions above are \
             vacuous"
        );
    });
}

// ───────────────────────────────────────────────────────────────────────────
// The wiring: the gate is actually mounted
// ───────────────────────────────────────────────────────────────────────────

#[test]
fn the_gate_attaches_a_caller_to_the_request_it_lets_through() {
    // `router()` mounts this interceptor in front of all seven services. If it
    // did not attach a `Caller`, every handler would refuse a perfectly good
    // credential, and if it attached one without verifying, everything above
    // would be theatre. Both halves, on the real type.
    let harness = Harness::new();
    let (principal_id, key) = harness.principal("alice");
    let mut gate = harness.gate();

    let credential =
        gunnar_grpc::sign_credential_for(&key, now_ms(), "nonce-wiring-00001", "Admin.Health")
            .expect("sign");
    let mut request = Request::new(());
    request.metadata_mut().insert(
        CREDENTIAL_METADATA_KEY,
        credential.to_header_value().parse().unwrap(),
    );
    // What `RequestSpanLayer` puts there from the router's path.
    request
        .extensions_mut()
        .insert(gunnar_grpc::auth::CalledMethod("Admin.Health".to_owned()));
    let passed = <AuthGate as tonic::service::Interceptor>::call(&mut gate, request)
        .expect("a valid credential must pass the gate");
    let caller = passed
        .extensions()
        .get::<Caller>()
        .expect("the gate must attach the caller it verified");
    assert_eq!(caller.principal_id, principal_id);

    assert_eq!(
        <AuthGate as tonic::service::Interceptor>::call(&mut gate, Request::new(()))
            .err()
            .map(|s| s.code()),
        Some(Code::Unauthenticated),
        "the gate let a request with no credential through"
    );
}

// ───────────────────────────────────────────────────────────────────────────
// The method binding (GUN-001)
// ───────────────────────────────────────────────────────────────────────────
//
// The finding: the signed bytes were `fingerprint‖timestamp‖nonce`, so a
// credential lifted off a plaintext control plane could be re-sent at any other
// method — `Admin.Health` in, `Access.AddKey` out, permanent admin, and the
// audit line names the victim. Three things have to hold for that to be closed
// and each is asserted in both directions here:
//
//   1. a bound credential presented at another method is refused;
//   2. the method the gate checks against comes from the ROUTER's path, which
//      means `RequestSpanLayer` has to put it somewhere the interceptor can
//      read — the one mechanism the old comment said did not exist;
//   3. the method-blind v1 credential is refused at every method (5.3.3,
//      OWNER 2026-10-10; it used to be served until an opt-in flag).

/// The relay, on the real gate: sign for `Admin.Health`, present at
/// `Access.AddKey`.
///
/// Mutation-proven 2026-09-11: with the `signed != called` arm of
/// `authenticate_bound` deleted, this test goes green on the `Ok(_)` it is
/// asserting against — the credential verifies perfectly well, it is simply
/// being spent somewhere it was not issued for, which is the whole finding.
#[test]
fn a_credential_signed_for_one_method_is_refused_at_another() {
    let harness = Harness::new();
    let (principal_id, key) = harness.principal("alice");
    let gate = harness.gate();

    let credential =
        gunnar_grpc::sign_credential_for(&key, now_ms(), "nonce-bound-000001", "Admin.Health")
            .expect("sign");
    let mut metadata = tonic::metadata::MetadataMap::new();
    metadata.insert(
        CREDENTIAL_METADATA_KEY,
        credential.to_header_value().parse().unwrap(),
    );

    assert_eq!(
        gate.authenticate_bound(&metadata, now_ms(), Some("Access.AddKey")),
        Err(AuthFailure::MethodMismatch {
            signed: "Admin.Health".to_owned(),
            called: "Access.AddKey".to_owned(),
        }),
        "a credential issued for Admin.Health was accepted at Access.AddKey"
    );

    // The other direction, and it matters: a gate that refused everything
    // would pass the assertion above without binding anything. The SAME
    // credential, at the method it names, authenticates — and names the right
    // principal.
    let caller = gate
        .authenticate_bound(&metadata, now_ms(), Some("Admin.Health"))
        .expect("the credential must be accepted at the method it was signed for");
    assert_eq!(caller.principal_id, principal_id);

    // …and the refusal was not free: a mismatch must NOT spend the nonce, or
    // an attacker who cannot use a captured credential could still burn it and
    // make the honest caller's own call fail.
    let replayed =
        gunnar_grpc::sign_credential_for(&key, now_ms(), "nonce-bound-000002", "Admin.Health")
            .expect("sign");
    let mut metadata = tonic::metadata::MetadataMap::new();
    metadata.insert(
        CREDENTIAL_METADATA_KEY,
        replayed.to_header_value().parse().unwrap(),
    );
    assert!(
        gate.authenticate_bound(&metadata, now_ms(), Some("Access.AddKey"))
            .is_err(),
        "the relay must be refused"
    );
    assert!(
        gate.authenticate_bound(&metadata, now_ms(), Some("Admin.Health"))
            .is_ok(),
        "a refused relay spent the honest caller's nonce"
    );
}

/// The method is signed, not merely carried: rewriting the header's method
/// field breaks the signature rather than moving the credential.
#[test]
fn the_method_cannot_be_edited_out_of_a_bound_credential() {
    let harness = Harness::new();
    let (_, key) = harness.principal("alice");
    let gate = harness.gate();

    let mut credential =
        gunnar_grpc::sign_credential_for(&key, now_ms(), "nonce-rewrite-0001", "Admin.Health")
            .expect("sign");
    credential.method = Some("Access.AddKey".to_owned());
    let mut metadata = tonic::metadata::MetadataMap::new();
    metadata.insert(
        CREDENTIAL_METADATA_KEY,
        credential.to_header_value().parse().unwrap(),
    );
    assert_eq!(
        gate.authenticate_bound(&metadata, now_ms(), Some("Access.AddKey")),
        Err(AuthFailure::NotVerified),
        "the method was rewritten and the signature still verified"
    );

    // And dropping the method altogether — presenting the v2 signature under
    // the v1 scheme — does not downgrade into the unbound path either: that
    // path refuses everything, before the signature is even read.
    let mut credential =
        gunnar_grpc::sign_credential_for(&key, now_ms(), "nonce-rewrite-0002", "Admin.Health")
            .expect("sign");
    credential.method = None;
    let mut metadata = tonic::metadata::MetadataMap::new();
    metadata.insert(
        CREDENTIAL_METADATA_KEY,
        credential.to_header_value().parse().unwrap(),
    );
    assert_eq!(
        gate.authenticate_bound(&metadata, now_ms(), Some("Access.AddKey")),
        Err(AuthFailure::Unbound),
        "a v2 signature presented as v1 was accepted, which is a downgrade"
    );
}

/// A bound credential with no method in scope is refused rather than served.
///
/// This is the fail-closed half. `authenticate` — the entry point with no
/// request behind it — cannot check the binding, and "cannot check" must never
/// read as "passes".
#[test]
fn a_bound_credential_is_refused_when_the_method_is_not_in_scope() {
    let harness = Harness::new();
    let (_, key) = harness.principal("alice");
    let gate = harness.gate();

    let credential =
        gunnar_grpc::sign_credential_for(&key, now_ms(), "nonce-noscope-001", "Admin.Health")
            .expect("sign");
    let mut metadata = tonic::metadata::MetadataMap::new();
    metadata.insert(
        CREDENTIAL_METADATA_KEY,
        credential.to_header_value().parse().unwrap(),
    );
    assert!(
        matches!(
            gate.authenticate(&metadata, now_ms()),
            Err(AuthFailure::MethodMismatch { .. })
        ),
        "a bound credential was served by the path that cannot check the binding"
    );
}

/// **The shipped gate refuses the method-blind v1 credential at every method**
/// (OWNER 2026-10-10: require_bound ON in 5.3.3; stinky row 2, GUN-001).
///
/// The default gate — no builder call, no flag — handed a valid, fresh,
/// correctly signed `gunnar-sshsig-v1` header from a registered key, at every
/// method the control plane serves, plus the interceptor path with the router's
/// `CalledMethod` and the no-method-in-scope path. Every one is `Unbound`, and
/// each refusal is counted against the caller and method it was presented at,
/// none as served.
#[test]
fn the_shipped_gate_refuses_a_method_blind_credential_at_every_method() {
    let harness = Harness::new();
    let (_, key) = harness.principal("alice");
    let gate = harness.gate();
    let v1 = |nonce: &str| {
        let credential = sign_credential(&key, now_ms(), nonce).expect("sign");
        let mut metadata = tonic::metadata::MetadataMap::new();
        metadata.insert(
            CREDENTIAL_METADATA_KEY,
            credential.to_header_value().parse().unwrap(),
        );
        metadata
    };

    let mut served = Vec::new();
    for (i, method) in gunnar_grpc::auth::METHODS.iter().enumerate() {
        let answer = gate.authenticate_bound(
            &v1(&format!("nonce-v1-every-{i:06}")),
            now_ms(),
            Some(method),
        );
        if answer != Err(AuthFailure::Unbound) {
            served.push(format!("{method}: {answer:?}"));
        }
    }
    assert!(
        served.is_empty(),
        "the shipped gate did not refuse a method-blind credential at these methods: {served:#?}"
    );
    assert_eq!(
        gate.authenticate(&v1("nonce-v1-no-method-01"), now_ms()),
        Err(AuthFailure::Unbound),
        "with no method in scope a v1 credential must still be refused"
    );

    // The interceptor, with the method the router is about to dispatch to.
    let mut request = Request::new(());
    *request.metadata_mut() = v1("nonce-v1-intercept-1");
    request
        .extensions_mut()
        .insert(gunnar_grpc::auth::CalledMethod("Access.AddKey".to_owned()));
    let mut intercepting = gate.clone();
    let status = <AuthGate as tonic::service::Interceptor>::call(&mut intercepting, request)
        .expect_err("the interceptor let a method-blind credential through to Access.AddKey");
    assert_eq!(status.code(), Code::Unauthenticated);
    assert!(
        status.message().contains(gunnar_grpc::CREDENTIAL_SCHEME),
        "{}",
        status.message()
    );

    let report = gate.unbound_log().report();
    assert_eq!(
        report.accepted, 0,
        "nothing method-blind may be counted as served"
    );
    assert_eq!(
        report.refused as usize,
        gunnar_grpc::auth::METHODS.len() + 2,
        "every refusal must be counted"
    );
}

/// `/gunnar.v1.Access/AddKey` is `Access.AddKey`, and nothing else is anything.
#[test]
fn a_path_names_the_method_the_credential_names() {
    use gunnar_grpc::method_name_from_path;

    assert_eq!(
        method_name_from_path("/gunnar.v1.Access/AddKey").as_deref(),
        Some("Access.AddKey")
    );
    // Every audited method must be derivable from the path its service is
    // mounted at, or a credential could never match one of them.
    for method in audited_methods() {
        let (service, verb) = method.split_once('.').expect("Service.Method");
        assert_eq!(
            method_name_from_path(&format!("/gunnar.v1.{service}/{verb}")).as_deref(),
            Some(method),
            "the path for {method} does not round-trip to its own name"
        );
    }
    // …and the shapes that are not a gRPC method are None, so a credential
    // claiming one can never be "matched" against a route that does not exist.
    for junk in [
        "/",
        "",
        "/gunnar.v1.Access",
        "/gunnar.v1.Access/AddKey/extra",
        "/gunnar.v1.Access/",
    ] {
        assert_eq!(
            method_name_from_path(junk),
            None,
            "{junk:?} was read as a method name"
        );
    }
}

// ───────────────────────────────────────────────────────────────────────────
// The replay guard does not forget (GUN-009)
// ───────────────────────────────────────────────────────────────────────────

/// **The finding.** A credential inside the freshness window is never pushed
/// out of the guard to make room for a newer one.
///
/// The guard used to run `while order.len() >= capacity { pop_front() }`, and
/// the oldest entry inside a five-minute window is still perfectly
/// presentable. An enrolled principal — a key and nothing else — could mint
/// their own credentials at ~27/s for five minutes, evict a captured one, and
/// replay it. That guard was the whole compensation for a credential that
/// bound no method, so GUN-001 and this were one hole.
///
/// Mutation-proven 2026-09-11: restore the eviction loop and the first
/// credential below is accepted a SECOND time, which is the replay.
#[test]
fn a_fresh_credential_is_never_evicted_to_make_room() {
    let harness = Harness::new();
    let (_, key) = harness.principal("alice");
    // Four is the whole guard, so "the attacker fills it" is four calls
    // rather than 8192.
    let guard = gunnar_grpc::ReplayGuard::new(4);
    let now = now_ms();

    let captured = sign_credential(&key, now, "nonce-captured-0001").expect("sign");
    assert_eq!(
        guard.accept(&captured, now),
        gunnar_grpc::Accepted::Fresh,
        "the first use of a credential must be accepted"
    );

    // The attacker's own, valid, freshly signed, one after another. Nothing
    // here is forged: this is what any enrolled principal can do.
    for seq in 0..3 {
        let mine = sign_credential(&key, now, &format!("nonce-filler-{seq:07}")).expect("sign");
        assert_eq!(guard.accept(&mine, now), gunnar_grpc::Accepted::Fresh);
    }

    // The guard is now full of entries that are all still inside the window.
    // One more must be REFUSED rather than make room.
    let overflow = sign_credential(&key, now, "nonce-overflow-001").expect("sign");
    assert_eq!(
        guard.accept(&overflow, now),
        gunnar_grpc::Accepted::Full,
        "a full guard must refuse rather than forget something still presentable"
    );

    // …and the captured credential is still remembered, which is the whole
    // point. Before the fix this line read `Fresh`.
    assert_eq!(
        guard.accept(&captured, now),
        gunnar_grpc::Accepted::Replayed,
        "a captured credential was forgotten and could be replayed"
    );
}

/// The guard still forgets what it is allowed to forget, so a full one is a
/// transient state and not a permanently closed door.
///
/// Without this the fix above would be satisfied by a guard that refuses
/// everything after `capacity` credentials for the life of the process.
#[test]
fn the_guard_forgets_exactly_what_can_no_longer_be_presented() {
    let harness = Harness::new();
    let (_, key) = harness.principal("alice");
    let guard = gunnar_grpc::ReplayGuard::new(2);
    let now = now_ms();

    for seq in 0..2 {
        let filler = sign_credential(&key, now, &format!("nonce-window-{seq:07}")).expect("sign");
        assert_eq!(guard.accept(&filler, now), gunnar_grpc::Accepted::Fresh);
    }
    let blocked = sign_credential(&key, now, "nonce-blocked-0001").expect("sign");
    assert_eq!(guard.accept(&blocked, now), gunnar_grpc::Accepted::Full);

    // One window later, the two entries can no longer be presented at all —
    // `authenticate_bound` refuses them as stale before the guard is reached —
    // so forgetting them costs nothing, and the guard has room again.
    let later = now + MAX_CLOCK_SKEW_MS + 1;
    assert_eq!(guard.accept(&blocked, later), gunnar_grpc::Accepted::Fresh);
    assert_eq!(guard.len(), 1, "the expired pair must have been dropped");
}

/// A full guard is `RESOURCE_EXHAUSTED` and not `UNAUTHENTICATED`.
///
/// Nothing is wrong with the credential, and a client told "not authenticated"
/// rotates a key for no reason. The two answers are different facts about
/// different things and the status says which.
#[test]
fn a_full_guard_reports_the_server_and_not_the_caller() {
    let harness = Harness::new();
    let (_, key) = harness.principal("alice");
    let gate = harness
        .gate()
        .with_replay_guard(std::sync::Arc::new(gunnar_grpc::ReplayGuard::new(1)));
    let now = now_ms();

    for (seq, expected) in [(0, None), (1, Some(Code::ResourceExhausted))] {
        let credential = gunnar_grpc::sign_credential_for(
            &key,
            now,
            &format!("nonce-status-{seq:07}"),
            "Admin.Health",
        )
        .expect("sign");
        let mut metadata = tonic::metadata::MetadataMap::new();
        metadata.insert(
            CREDENTIAL_METADATA_KEY,
            credential.to_header_value().parse().unwrap(),
        );
        let answer = gate.authenticate_bound(&metadata, now, Some("Admin.Health"));
        assert_eq!(
            answer.as_ref().err().map(|failure| failure.status().code()),
            expected,
            "credential {seq}"
        );
    }
}

// ───────────────────────────────────────────────────────────────────────────
// Who still signs v1: the unbound-credential log
//
// Until 5.3.3 this log was the evidence for flipping an opt-in flag; with v1
// refused everywhere it is what names the client that just stopped working.
// Mutations, recorded because a green that has never been red is a comment
// (2026-09; the served-side rows went with the served path in 5.3.3):
//
// | mutation in `auth.rs` | what went red |
// |---|---|
// | the refused-side `note_unbound` removed | the refusal tests below (`refused` read 0) |
// | the roster's capacity check removed (unbounded) | `the_unbound_roster_is_bounded_…` (`distinct_dropped` stayed 0) |
// | the counters bounded along with the roster | the same test (`accepted` read 3 instead of 4) |
// ───────────────────────────────────────────────────────────────────────────

/// **A bound credential is served and leaves the log empty; a method-blind
/// one is refused, counted as refused, and named.**
///
/// Both directions, on ONE gate: a log that counted every credential would
/// name a fleet on v2 as still needing an update, and one that counted none
/// would leave the client that just broke unnamed. Presented at
/// `Access.AddKey`, the relay GUN-001 is about.
#[test]
fn a_bound_credential_is_not_logged_and_a_method_blind_one_is_refused_and_named() {
    let harness = Harness::new();
    let (_, key) = harness.principal("alice");
    let fingerprint = key
        .public_key()
        .fingerprint(ssh_key::HashAlg::Sha256)
        .to_string();
    let gate = harness.gate();

    // ── the bound credential: served, nothing to report ─────────────────
    let bound = sign_credential_for(&key, now_ms(), "nonce-bound-000001", "Admin.Health")
        .expect("sign a bound credential");
    let mut metadata = tonic::metadata::MetadataMap::new();
    metadata.insert(
        CREDENTIAL_METADATA_KEY,
        bound.to_header_value().parse().unwrap(),
    );
    gate.authenticate_bound(&metadata, now_ms(), Some("Admin.Health"))
        .expect("a bound credential must be served");
    let report = gate.unbound_log().report();
    assert_eq!(
        report,
        gunnar_grpc::UnboundCredentialReport::default(),
        "a method-bound credential put something in the unbound log"
    );
    assert!(report.nothing_unbound_has_been_served());

    // ── the method-blind one: refused, counted, named ───────────────────
    let blind = sign_credential(&key, 1_700_000_000_000, "nonce-blind-000001").expect("sign");
    let mut metadata = tonic::metadata::MetadataMap::new();
    metadata.insert(
        CREDENTIAL_METADATA_KEY,
        blind.to_header_value().parse().unwrap(),
    );
    assert_eq!(
        gate.authenticate_bound(&metadata, 1_700_000_000_000, Some("Access.AddKey")),
        Err(AuthFailure::Unbound)
    );

    let report = gate.unbound_log().report();
    assert_eq!(
        report.accepted, 0,
        "a refused credential was counted as served"
    );
    assert_eq!(report.refused, 1, "the refusal was not counted");
    assert!(
        report.nothing_unbound_has_been_served(),
        "the verdict must follow the count, or the two readers disagree"
    );
    assert_eq!(report.last_seen_unix_ms, 1_700_000_000_000);
    assert_eq!(report.callers.len(), 1, "one caller, one method, one row");
    let row = &report.callers[0];
    assert!(row.refused);
    assert_eq!(row.fingerprint, fingerprint);
    assert_eq!(row.method, "Access.AddKey");
    assert_eq!(row.count, 1);
    assert!(
        row.principal_id.is_empty(),
        "the refusal happens before the key lookup, so no principal is known here — a row \
         that claimed one would be claiming the header's word for it"
    );
}

/// **The refusal comes before the key lookup, and after the clock.**
///
/// A forged method-blind credential (a key nobody registered) is refused as
/// `Unbound` — the server never looks the key up for a shape it serves to no
/// one — and is counted as refused: the counter answers "who is hitting the
/// closed door", junk included. A stale one is refused as `Stale` before the
/// binding is read, and is not counted at all. Neither is ever `accepted`.
#[test]
fn a_forged_method_blind_credential_is_refused_unread_and_a_stale_one_as_stale() {
    let harness = Harness::new();
    let (_, registered) = harness.principal("alice");
    let stranger = mint();
    let gate = harness.gate();

    let forged = sign_credential(&stranger, now_ms(), "nonce-forged-00001").expect("sign");
    let mut metadata = tonic::metadata::MetadataMap::new();
    metadata.insert(
        CREDENTIAL_METADATA_KEY,
        forged.to_header_value().parse().unwrap(),
    );
    assert_eq!(
        gate.authenticate_bound(&metadata, now_ms(), Some("Admin.Health")),
        Err(AuthFailure::Unbound)
    );

    let stale =
        sign_credential(&registered, now_ms() - 3_600_000, "nonce-stale-000001").expect("sign");
    let mut metadata = tonic::metadata::MetadataMap::new();
    metadata.insert(
        CREDENTIAL_METADATA_KEY,
        stale.to_header_value().parse().unwrap(),
    );
    assert!(matches!(
        gate.authenticate_bound(&metadata, now_ms(), Some("Admin.Health")),
        Err(AuthFailure::Stale { .. })
    ));

    let report = gate.unbound_log().report();
    assert_eq!(report.accepted, 0, "nothing method-blind is ever served");
    assert_eq!(
        report.refused, 1,
        "the forged one is counted; the stale one never reached the binding"
    );
    assert_eq!(report.callers.len(), 1);
    assert!(report.callers[0].refused);
}

/// **A full roster never turns a non-zero count into an empty list.**
///
/// The roster is bounded and the counters are not, and that asymmetry is the
/// whole reason the flag decision can rest on `accepted == 0`: an unbounded
/// roster is a memory hole anyone with a key can fill, and a bounded *counter*
/// would read "nobody sends v1" on the one busy server where it is wrong.
///
/// Driven at capacity 2 rather than at the shipped 64 so the arithmetic is
/// visible: three distinct pairs, two listed, one dropped, three counted.
#[test]
fn the_unbound_roster_is_bounded_and_the_counter_is_not() {
    let log = gunnar_grpc::UnboundCredentialLog::new(2);
    assert!(log.record("SHA256:a", "alice", "Admin.Health", false, 10));
    assert!(log.record("SHA256:b", "bob", "Admin.Health", false, 20));
    // The same pair again: counted, not new, and not a second row.
    assert!(!log.record("SHA256:a", "alice", "Admin.Health", false, 30));
    // A third distinct pair, past the bound.
    assert!(log.record("SHA256:c", "carol", "Admin.Health", false, 40));

    let report = log.report();
    assert_eq!(
        report.accepted, 4,
        "every presentation must be counted, whether or not the roster could hold it"
    );
    assert_eq!(report.last_seen_unix_ms, 40);
    assert_eq!(report.callers.len(), 2, "the roster is bounded at 2");
    assert_eq!(
        report.distinct_dropped, 1,
        "and it must SAY that it dropped one, or the short list reads as the whole truth"
    );
    assert_eq!(
        report.callers[0].count, 2,
        "the repeat landed on alice's row"
    );
    assert_eq!(report.callers[1].count, 1);
    assert!(
        !report.nothing_unbound_has_been_served(),
        "a full roster must never make the verdict say the fleet is ready"
    );
}