gunnar-ssh 2.0.0

gunnar's SSH server: a russh listener with publickey identity, a strict git exec dispatch, and the repository path sandbox.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
//! The russh server: authentication, the exec dispatch, and the channel
//! hand-off (the ACL model, the two-listener split).
//!
//! # The shape of a connection
//!
//! 0. **`auth_none`**, the anonymous read path, and the only place
//!    gunnar reads the SSH username. See below.
//! 1. **`auth_publickey`**: russh has already verified that the client owns the
//!    offered key. gunnar fingerprints it (SHA-256 over the wire blob, OpenSSH's
//!    printed form, [`crate::access::fingerprint_of_key`]) and asks
//!    `gunnar-core`'s identity table through [`Control`]. The SSH *username* is
//!    logged and otherwise ignored: identity comes from the key, so
//!    `git@host:ns/repo.git` works and `git` means nothing (the ACL model).
//! 2. **`channel_open_session`**. The channel is kept, because the exec request
//!    arrives as a separate message that only carries a [`ChannelId`], and the
//!    stream can only be taken from the `Channel` itself. A watchdog is armed
//!    here so a session that authenticates and then never execs cannot sit on
//!    the connection.
//! 3. **`env_request`**, answered against [`ENV_ALLOWLIST`], which holds
//!    exactly one name: `GIT_PROTOCOL`. Everything else is refused. See below.
//! 4. **`exec_request`**: [`Dispatch::authorise`] parses, resolves and checks
//!    the grant. Only then is the channel's stream handed to [`GitTransport`].
//! 5. **everything else**. `shell_request`, `subsystem_request`,
//!    `pty_request` and `x11_request` are answered with a channel failure.
//!    **No shell, ever.**
//!
//! # Why the transport is spawned and not awaited
//!
//! russh calls handler methods from the session's own read loop (see
//! `russh::server::Session::run`). Awaiting a whole clone inside `exec_request`
//! would stop the loop that has to deliver the client's bytes to the channel;
//! the transfer would deadlock on its first read. russh's own `sftp_server`
//! example awaits inline; gunnar does not.
//!
//! # The exit status, and why the channel is split rather than consumed
//!
//! `Channel::into_stream()` wraps the channel in russh's `ChannelCloseOnDrop`,
//! which spawns a task sending `ChannelMsg::Close` when the transport lets the
//! stream go. That `Close` raced the `exit-status` the server sent next, and
//! won often enough that a *successful* push reported failure. Measured
//! 2026-08-03: a complete 244-byte advertisement delivered with `ssh` exiting
//! **255**. See [`crate::channel`].
//!
//! The channel is therefore `split()` instead. The read half becomes an owned
//! [`ChannelReader`], the write half stays with the server, and `exit-status`
//! and `close` go out through **the same sender the data went through**, in
//! order, after the transport has finished with it. Nothing sleeps and nothing
//! races.
//!
//! # One span per connection, and what hangs off it
//!
//! ```text
//!   ssh.connection { conn, peer, principal, repo }     gunnar::ssh
//!     └── git.transfer { service, access }             gunnar::git
//!           ├── git.upload_pack | git.receive_pack     gunnar::git
//!           └── policy.gate { ref_name }               gunnar::policy
//! ```
//!
//! `principal` and `repo` are declared empty when the connection opens and
//! **recorded** when `auth_publickey` and `exec_request` learn them, so a line
//! emitted at any depth carries all four fields without any call site restating
//! them. That is the difference from what was here before: connection identity
//! was an ad-hoc `?self.peer` copy-pasted to fourteen call sites, there was no
//! id at all, and two lines from the same connection could not be tied
//! together.
//!
//! Two hand-offs would drop the span if they were not made explicit, and each
//! is a place where an operator would silently lose half a connection:
//!
//! * `tokio::spawn`: the exec watchdog and the transfer task both take
//!   `.instrument(span)`, because a spawned task does not inherit a
//!   thread-local span;
//! * `spawn_blocking`: `gunnar-cli`'s `WireTransport::serve` captures
//!   `Span::current()` and enters it on the blocking thread, which is where the
//!   whole git conversation actually happens.
//!
//! # How an anonymous session arrives, and why it is `auth_none` on one
//! # username
//!
//! SSH has no unauthenticated mode: a client must complete *some* userauth
//! method before it may open a channel. Three shapes were available.
//!
//! | | why not |
//! |---|---|
//! | accept `none` for **every** username | **This is the one that would break the server.** OpenSSH's client always sends a `none` request first, to learn the method list. A server that answers it with SUCCESS authenticates *every* stock client as anonymous before it ever offers its key, so every existing push would start failing, and every existing user would silently lose their identity. Measured against the russh dispatch: `server/encrypted.rs` calls `auth_none` on that first probe regardless of the advertised `methods`. |
//! | a **well-known published key** | The anonymous-FTP shape. It works, but a stranger has to obtain a key file before they can clone, which is worse than the problem it solves, and gunnar would then hold a key whose private half is public in the same table that authenticates real users. |
//! | **`none`, on one reserved username** | Taken. |
//!
//! `ssh://anonymous@host/ns/repo.git` gets the `none` method accepted and a
//! session whose principal is
//! [`Principal::anonymous`](gunnar_core::Principal::anonymous). Every other
//! username gets `none` refused, exactly as russh's default handler refused it
//! before this existed, and the client falls through to publickey unchanged.
//!
//! **Why it cannot become a bypass**, in the order the objections come:
//!
//! * *Does it weaken private repositories?* No. The username selects the
//!   authentication method; the **authorisation** answer still comes from
//!   `AuthTable::may` (the ACL model), where the anonymous principal is one rule, `Read` on
//!   `Public`, and is refused everything else including `may_namespace` and
//!   `may_server`. There is no second ACL (one implementation).
//! * *Can a caller claim to be someone by picking a username?* No. The
//!   anonymous principal is the **only** identity a username can select, it is
//!   never in the identity table, [`Principal::new`] and
//!   `AuthTable::add_principal` refuse its id, so no key and no grant can ever
//!   attach to it.
//! * *Can an authenticated user be silently downgraded?* No. `none` is refused
//!   for their username, so nothing changes for them; and a user who *does*
//!   type `anonymous@` asked for strictly less access, which is not an
//!   escalation.
//! * *Does the username now reach an authorisation decision, against the ACL model?* It
//!   reaches exactly one, in the direction of *removing* everything. The ACL model's
//!   rule exists so that a username cannot be used to become somebody; this
//!   uses it to become nobody.
//!
//! **`none` is not advertised** in [`RusshConfig::methods`], which stays
//! publickey-only. Advertising it would tell every client that `none` is
//! available when it is available only for one name (the failure list is
//! supposed to be true), and russh calls `auth_none` on the client's opening
//! probe either way, which is the only place it is ever needed.
//!
//! [`SshConfig::allow_anonymous`](crate::SshConfig::allow_anonymous) closes the
//! whole path at the listener for an appliance that wants it shut.
//!
//! # `GIT_PROTOCOL`, and why it is an allowlist of one
//!
//! A git client announces protocol v2 over SSH by sending
//! `GIT_PROTOCOL=version=2` as a channel environment request. Refusing every
//! `env_request`, which this server used to do, meant every session fell back
//! to v0. Stock `git` copes; `gix`'s blocking v0 client does not, because it
//! requires `multi_ack_detailed` and `gunnar_wire::caps` correctly declines to
//! advertise a capability it does not implement. The measured consequence was
//! that `gunnar clone` could not clone from `gunnar serve` at all.
//!
//! Accepting the variable is **not** the same as accepting an environment. An
//! SSH server that passes arbitrary client-supplied names through has handed
//! the client `LD_PRELOAD`, `PATH` and every other lever there is. [`ENV_ALLOWLIST`]
//! names the one variable gunnar reads; every other name is refused with a
//! channel failure, exactly as before. The accepted value is not an input to
//! any authorisation decision: it reaches [`ServiceRequest::git_protocol`] and
//! nothing else, and it only ever selects the *framing* the wire answers in.

use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

/// How long [`BoundServer::shutdown`] waits for sessions to answer the
/// disconnect before it aborts the listener. Longer than the gRPC grace (2 s):
/// a git transfer mid-pack deserves a moment to finish its write.
pub const SSH_SHUTDOWN_GRACE: Duration = Duration::from_secs(10);

use russh::keys::ssh_key::PublicKey;
use russh::server::{Auth, Config as RusshConfig, Handler, Msg, Server, Session};
use russh::{Channel, ChannelId, Disconnect, MethodKind, MethodSet};
use tokio::net::TcpListener;
use tokio::task::JoinHandle;
use tracing::Instrument;

use gunnar_core::observe::{RequestId, ServerMetrics, TARGET_GIT, TARGET_SSH};
use gunnar_core::RepoRef;

use crate::access::{fingerprint_of_key, Access, Fingerprint, Principal};
use crate::admission::{Admission, AdmissionStats};
use crate::channel::{serve_until_session_ends, session_ended_error, session_over, ChannelReader, SessionBound};
use crate::command::GitService;
use crate::command::{self, CommandError};
use crate::config::{SshConfig, ANONYMOUS_SSH_USER};
use crate::control::Control;
use crate::governor::OpClass;
use crate::seam::{Delivery, GitTransport, ServiceRequest};

// ───────────────────────────────────────────────────────────────────────────
// The authorisation decision, without any SSH in it
// ───────────────────────────────────────────────────────────────────────────

/// Why an exec request was not served.
#[derive(Debug, thiserror::Error)]
pub enum DispatchError {
    /// The command did not parse. **The `bash` case, and every other one.**
    #[error("{0}")]
    Command(#[from] CommandError),
    /// The repository does not exist.
    #[error("no such repository: {0}")]
    NoSuchRepo(RepoRef),
    /// The principal does not hold enough access.
    #[error("{principal} holds {held} on {repo}, needs {needed}")]
    Denied {
        /// Who asked.
        principal: String,
        /// What they asked for.
        repo: RepoRef,
        /// What the command requires.
        needed: Access,
        /// What they actually hold, rendered as `none` when they hold nothing.
        held: String,
    },
    /// **This box is a read-only STANDBY** and the write is refused.
    ///
    /// A distinct arm, not a [`DispatchError::Denied`]: the writer holds the
    /// grant — on a primary this push would land — so "you do not have access"
    /// would be a lie that sends them to an administrator about permissions.
    /// The honest sentence is that this box does not take client writes; push
    /// to the primary. It is only ever reached by a principal who already
    /// passed the grant check, so it leaks no repository the writer could not
    /// already see.
    #[error("{principal}: this box is a standby; writes go to the primary ({repo})")]
    Standby {
        /// Who asked.
        principal: String,
        /// The repository they tried to write.
        repo: RepoRef,
        /// The box is a browse replica, so the
        /// refusal says so: a stranger who found a public repository here and
        /// tried to push to it should learn what this box is, not merely that
        /// it is frozen.
        browse: bool,
    },
    /// **This box is a TWIN and serves no git at all** — not a read, not a
    /// write, not to anybody (2026-09-21, lane T4).
    ///
    /// Its own arm and not a [`DispatchError::Standby`], because a standby is a
    /// box that serves reads and refuses writes, and a twin is a box that
    /// serves NEITHER: `serve.rs` says why in one line — *a read would grow the
    /// caches the twin must not hold* — and the twin's whole value is that its
    /// disk holds the primary's log and nothing derived.
    ///
    /// **Why this exists at the door rather than only at the bind.** The bind
    /// is chosen ONCE, in `serve::start`, from `stores.is_twin()` at that
    /// instant. A box becomes a twin over the wire, through
    /// `Bootstrap.BecomeTwin`, long after that — and the owner's one-medium
    /// ruling makes that the ONLY way it happens, because a twin is now
    /// installed from the same image as a main with no per-box parameter to
    /// say which it is. MEASURED under KVM by lane T3, 2026-09-21: a box
    /// conferred at runtime kept `0.0.0.0:2222` bound for the rest of its life,
    /// the `this box is a TWIN` warning never printed, and its volume ended up
    /// holding five `objects.exploded` cache files. A socket that cannot be
    /// moved without a restart is not a reason to serve git from it in the
    /// meantime.
    #[error("{principal}: this box is a TWIN; it serves no git to anyone — clone and push to the primary it follows ({repo})")]
    Twin {
        /// Who asked.
        principal: String,
        /// What they asked for.
        repo: RepoRef,
    },
    /// **Anonymous reads are not served here** (`--anonymous refuse`); the
    /// browse replica serves them, and `browse_host` names it when the
    /// operator did. Raised before the repository is even looked up, so a
    /// stranger learns nothing about what exists on the primary.
    #[error("anonymous reads are refused on this box ({repo}); browse host: {browse_host:?}")]
    AnonymousElsewhere {
        /// The repository the stranger asked for.
        repo: RepoRef,
        /// Where anonymous reads are served, when the operator named it.
        browse_host: Option<String>,
    },
    /// **The gate chain refuses this**: the disk is under its floor (every
    /// build), or (`metered`) a Suspended or Retention tenant's push or LFS
    /// upload, an anonymous read of a lapsed tenant's public repository, or a
    /// push at the pack quota.
    ///
    /// Its own arm for the same reason [`DispatchError::Standby`] is one: the
    /// caller holds the grant, so "you do not have access" would be a lie
    /// that sends a paying customer to an administrator about permissions.
    /// The honest sentence names the fact — free bytes and the floor, or the
    /// state, the date and where to renew — and it is only ever reached AFTER
    /// the grant check admitted the request, so it leaks nothing about a
    /// repository the caller could not already see.
    #[error("{namespace}: {line}")]
    Plan {
        /// The tenant.
        namespace: String,
        /// What the client is told, verbatim.
        line: String,
    },
    /// The identity table or the catalog could not be read.
    ///
    /// **Deliberately not folded into [`DispatchError::Denied`].** The tables
    /// live in storage (the Arrow-IPC ref log) and a read can fail; answering a storage
    /// fault with "you do not have access" would turn an outage into a silent,
    /// convincing permission denial that nobody would think to investigate.
    /// The ACL model is explicit that `may(...)` returns `Result<bool>` for this
    /// reason, and this variant is where that `Result` lands.
    #[error("the control plane could not answer: {0}")]
    Store(#[from] gunnar_core::Error),
}

impl DispatchError {
    /// What the client is told.
    ///
    /// `None` means "answer with a channel failure and say nothing": the
    /// request was not even a git command, so there is no git client on the
    /// other end that would understand a pkt-line.
    ///
    /// **"No such repository" and "no permission" produce the same string on
    /// purpose.** A client that could tell them apart could enumerate private
    /// repositories one guess at a time. The server log keeps the distinction;
    /// the wire does not.
    ///
    /// Those two arms are **one arm**, and were two identical `format!`s until
    /// 2026-08-05. That is the twinning one implementation forbids, and this is the case it
    /// forbids it for: the property is that the two strings are equal, so two
    /// copies of the string put the property one careless edit away from being
    /// false, in the direction where the wire starts leaking which private
    /// repositories exist.
    /// `a_missing_repository_and_a_forbidden_one_are_one_string_to_the_client`
    /// guards it from the far side of a real session; this makes the guard hard
    /// to need.
    pub fn client_message(&self) -> Option<String> {
        match self {
            // A verb gunnar knows and refuses BY NAME gets its sentence; the
            // rest of the parse failures are not git clients at all.
            DispatchError::Command(CommandError::NotServed { verb, why }) => {
                Some(format!("{verb}: {why}"))
            }
            DispatchError::Command(_) => None,
            DispatchError::NoSuchRepo(repo) | DispatchError::Denied { repo, .. } => Some(format!(
                "repository not found, or you do not have access: {repo}"
            )),
            // A standby refusal is told plainly — the writer is authorised, so
            // there is no repository to hide from them, and "push to the
            // primary" is the one thing they need to hear to succeed.
            // A twin refusal is told plainly for the same reason, and it is told
            // to EVERYONE including a stranger: it names no repository and
            // reveals nothing this box holds — "this is a twin" is a fact about
            // the box, not about its contents.
            DispatchError::Twin { .. } => Some(
                "this box is a TWIN: it holds a copy of the primary's transaction log and serves \
                 no git to anyone, read or write. Clone and push to the primary it follows"
                    .to_string(),
            ),
            DispatchError::Standby { browse: false, .. } => {
                Some("this box is a standby; push to the primary".to_string())
            }
            DispatchError::Standby { browse: true, .. } => Some(
                "this box is a browse replica: it serves public repositories read-only and \
                 takes no writes; push to the primary"
                    .to_string(),
            ),
            DispatchError::AnonymousElsewhere {
                browse_host: Some(host),
                repo,
            } => Some(format!(
                "anonymous reads are served by the browse replica, not here: clone \
                 {repo} from {host} (or authenticate with a registered key)"
            )),
            DispatchError::AnonymousElsewhere {
                browse_host: None, ..
            } => Some(
                "this server does not serve anonymous reads; authenticate with a registered \
                 key, or use the browse replica"
                    .to_string(),
            ),
            // The gate's refusal is told in full: the state, the date and the
            // URL are the three things a lapsed tenant needs to get going again,
            // and the free bytes and the floor are what a full box's operator
            // needs; hiding any of them would turn a fact into a support ticket.
            DispatchError::Plan { line, .. } => Some(line.clone()),
            // A fault, not a decision. The client is told the server broke,
            // because telling it "you do not have access" would be a lie that
            // sends the user to their administrator about permissions.
            DispatchError::Store(_) => {
                Some("the gunnar control plane is unavailable; try again".to_string())
            }
        }
    }
}

/// Parse → resolve → check, with no SSH anywhere in it.
///
/// Kept separate from the [`Handler`] so the security decision can be tested
/// directly, exhaustively and without a handshake, and so there is exactly one
/// place where it is made.
#[derive(Clone, Debug)]
pub struct Dispatch {
    control: Control,
}

impl Dispatch {
    /// Build a dispatch over the control plane.
    pub fn new(control: Control) -> Self {
        Dispatch { control }
    }

    /// The control plane this dispatch authenticates and authorises against.
    pub fn control(&self) -> &Control {
        &self.control
    }

    /// Decide whether `principal` may run `raw` on this server.
    ///
    /// Parse (which includes the sandbox), resolve, then check the grant. A
    /// storage failure at either lookup comes back as
    /// [`DispatchError::Store`] rather than as a denial. See
    /// [`crate::control`].
    ///
    /// **The client's environment is not a parameter here, and must not
    /// become one.** The returned [`ServiceRequest`] carries
    /// `git_protocol: None`; the handler attaches the allowlisted value with
    /// [`ServiceRequest::with_git_protocol`] *after* this decision has already
    /// been made, so there is no path by which anything the client typed into
    /// its environment can reach the grant check.
    pub fn authorise(
        &self,
        principal: &Principal,
        key_fingerprint: Option<&Fingerprint>,
        raw: &[u8],
    ) -> Result<ServiceRequest, DispatchError> {
        let parsed = command::parse(raw)?;
        self.authorise_service(principal, key_fingerprint, parsed.service, parsed.repo)
    }

    /// The same decision, entered from a **URL path** rather than an exec line.
    ///
    /// Smart HTTP does not send `git-upload-pack '<path>'`; it sends
    /// `POST /<path>/git-upload-pack`. The verb and the path arrive already
    /// separated, and the path has no shell quoting on it, so there is nothing
    /// for [`command::parse`] to do — but everything **after** the parse is
    /// identical and must stay identical: resolve, ask the ACL, and refuse in
    /// the one way that does not tell a caller whether a repository exists.
    ///
    /// So this is where that decision lives and [`Dispatch::authorise`] is now
    /// a parser in front of it. Two entry points, one answer (one implementation). A second
    /// copy of this in `gunnar-http` is precisely the thing that ends with SSH
    /// and HTTP disagreeing about who may push, and the disagreement being
    /// found by whoever pushes.
    ///
    /// `repo` is a [`RepoRef`], which is to say it has already been through
    /// [`gunnar_core::resolve_repo_path`]. The sandbox is not optional on this
    /// path either: the caller cannot construct a `RepoRef` without it.
    pub fn authorise_service(
        &self,
        principal: &Principal,
        key_fingerprint: Option<&Fingerprint>,
        service: GitService,
        path: RepoRef,
    ) -> Result<ServiceRequest, DispatchError> {
        let required = service.required_access();
        // **A TWIN serves no git**, before anything else is asked — before the
        // anonymous policy, before the catalog, before the grant. A read on a
        // twin grows exactly the caches the twin exists not to hold, and the
        // box's own `browse` flag (which `become_twin` sets) would otherwise
        // OVERRIDE `--anonymous refuse` and serve a stranger. This is a live
        // read of the same flag `ServerStores` flips, so the refusal begins the
        // instant `Bootstrap.BecomeTwin` returns and does not wait for a
        // restart to move the listener.
        if self.control.is_twin() {
            return Err(DispatchError::Twin { principal: principal.id.clone(), repo: path });
        }
        // **`--anonymous refuse`** (the browse replica), before the catalog is consulted:
        // a stranger on a primary that has a browse replica is sent there, and
        // learns nothing about what this box holds on the way.
        if principal.id == gunnar_core::ANONYMOUS_PRINCIPAL_ID && self.control.refuses_anonymous() {
            return Err(DispatchError::AnonymousElsewhere {
                repo: path,
                browse_host: self.control.browse_host().map(str::to_owned),
            });
        }
        let (repo, prospective) = match self.control.resolve(&path)? {
            Some(repo) => (repo, false),
            // The repository does not exist. For exactly one shape of request
            // — a PUSH, by a principal the control plane already permits to
            // create repositories here — absence is the first-repository door
            // rather than a refusal: the repository is created and the push
            // proceeds through the unchanged grant check below.
            //
            // # Why a door here, and not a fourth verb or the control plane
            //
            // The shipped appliance runs `--no-grpc` (gRPC v1 is
            // unauthenticated, loopback-only), has no shell by construction,
            // and its exec surface is three git verbs that all want a
            // repository — so after `--admin-key` enrolled the bootstrap
            // admin (a8ba0665), the admin could authenticate and then do
            // NOTHING, forever (measured under KVM, 2026-08-25). The
            // alternatives lost on the code, not on taste:
            //
            // * **a create verb** would be a wire surface no git client
            //   speaks, would need its own client incantation, and does not
            //   fit the dispatch's own shape: `SERVICES` carries per-service
            //   *repo grant levels* and this decision compares levels — a
            //   verb whose target does not exist has no repo to hold a level
            //   on, so it would be a special case beside the table, and a
            //   probe-discoverable one for every stranger;
            // * **turning gRPC on** is the door the unauthenticated v1 and
            //   `gunnar-grpc/tests/loopback_default.rs` exist to keep shut on
            //   a mailed medium: `Bootstrap.Enroll` with no credential is a
            //   race between the customer and whoever else finds the box.
            //
            // Push-to-create adds no verb, no parse production and no
            // vocabulary: `Control::create_for_push` asks the exact two
            // questions `Repos.CreateNamespace`/`Repos.Create` gate on, so
            // this door and the RPC door can never disagree (one implementation) — and it
            // sits HERE, where the two entry points (exec line, smart-HTTP
            // URL) have already fanned in, so SSH and HTTP answer a push to a
            // missing repository identically.
            //
            // Only a WRITE: ReceivePack, and (2026-09-28) an LFS upload.
            // Reading never creates: a `git clone` of a typo, or an LFS
            // download, stays an error.
            //
            // **Why the LFS upload too.** git-lfs's pre-push hook runs AFTER
            // git has taken receive-pack's advertisement and BEFORE it sends
            // a command, and it asks `git-lfs-transfer <repo> upload` first.
            // MEASURED 2026-09-28 (git-lfs 3.8.0, and on a real box): into a
            // repository that did not exist yet that exec was the fused
            // not-found, the hook died — `batch request: exec request failed
            // on channel 0: exit status 255` — and the push that would have
            // created the repository never sent its commands. The upload is
            // the same act as the push (it puts content in the repository),
            // by the same principal, and it is asked the same two questions
            // (`push_create_spec`), so it opens the same door and nobody else
            // learns anything new. Nothing is written here either: the
            // transport creates the repository when the first OBJECT arrives
            // (`gunnar-server` `ProspectiveLfs`), so a client that only
            // batches, or hangs up, leaves nothing.
            //
            // For everyone `create_for_push` answers `None` for, the refusal
            // below is bit-identical to what it always was — the one fused
            // "repository not found, or you do not have access" — so the
            // door's existence is not observable to a key it does not admit.
            //
            // **Nothing is written here.** The door answers with the
            // repository it WOULD create (`prospective`), the transport
            // advertises that, and the catalog row and the store are made
            // only once the client has sent commands that pass the hash
            // check — see `Control::push_create_spec` for the ghost
            // repository this order closes.
            None if service == GitService::ReceivePack
                || service == GitService::LfsTransfer(crate::command::Operation::Upload) =>
            {
                match self.control.push_create_spec(principal, &path)? {
                    Some(spec) => {
                        // The name filter (2026-10-05) — asked only of a
                        // pusher the door admits, so its sentence tells
                        // nobody else anything.
                        if let Some(line) = self.control.push_create_name_refusal(principal, &path) {
                            return Err(DispatchError::Plan {
                                namespace: path.namespace().to_owned(),
                                line,
                            });
                        }
                        (spec.prospect()?, true)
                    }
                    None => return Err(DispatchError::NoSuchRepo(path)),
                }
            }
            None => return Err(DispatchError::NoSuchRepo(path)),
        };
        let held = self.control.access_for(principal, &repo)?;
        match held {
            // **The standby freeze.** Checked here, INSIDE the authorised arm,
            // so it is only ever reached by a writer the grant check already
            // admitted — an unauthorised push still gets the fused not-found and
            // learns nothing new. A write-requiring service by a non-`Machine`
            // principal on a frozen box is refused: this box has abdicated or is
            // a configured standby, and a client write here would be a split
            // the primary never sees. The primary's own replication push is a
            // `Machine` identity and sails through — that is what a standby is
            // for.
            Some(level)
                if level.permits(required)
                    && required.permits(Access::Write)
                    && self.control.write_frozen_for(principal) =>
            {
                Err(DispatchError::Standby {
                    principal: principal.id.clone(),
                    repo: path,
                    browse: self.control.is_browse(),
                })
            }
            // **An encrypted repository takes no LFS upload** (wiring tracer B
            // 2026-10-08). git-lfs uploads in the pre-push hook, BEFORE the
            // pack the encrypted gate reads, and an LFS object is the
            // plaintext of a `filter=lfs` file that never went through
            // `filter=gunnar-crypt`: refused here, for SSH and smart HTTP
            // alike, before a byte is stored. Asked inside the authorised arm,
            // so a stranger still gets the fused not-found. A download is never
            // refused.
            Some(level)
                if level.permits(required)
                    && repo.encrypted
                    && service == GitService::LfsTransfer(crate::command::Operation::Upload) =>
            {
                Err(DispatchError::Plan {
                    namespace: path.namespace().to_owned(),
                    line: format!(
                        "{path} is encrypted, so it takes no LFS objects: LFS stores files as \
                         they are, outside your members' encryption. Track the file with \
                         `filter=gunnar-crypt` instead of `filter=lfs`"
                    ),
                })
            }
            Some(level) if level.permits(required) => {
                // **The gate chain**, asked LAST: after the grant (so a
                // refusal leaks nothing to a stranger) and after the standby
                // freeze (so a standby stays one whatever the gates say). A
                // write asks `Write`; an anonymous read asks `AnonymousRead`;
                // an authenticated read asks nothing at all, because the
                // owner's clone is allowed in every state — data is never held
                // hostage. See `crate::plan`.
                let PlanOutcome {
                    notice: plan_notice,
                    ceiling: pack_ceiling,
                    pack_mark,
                    allowance: lfs_allowance,
                } = self.ask_plan(principal, service, required, &repo)?;
                Ok(ServiceRequest {
                    service,
                    repo,
                    prospective,
                    principal: principal.clone(),
                    access: level,
                    // The key that authenticated this session, carried
                    // rather than guessed back out of the identity table. A
                    // parameter and not a builder, so it cannot be forgotten into
                    // `None`.
                    key_fingerprint: key_fingerprint.cloned(),
                    git_protocol: None,
                    delivery: Delivery::Session,
                    // Derived from `key_fingerprint` by the transport rather
                    // than spelled here: see `ServiceRequest::credential`.
                    credential: None,
                    plan_notice,
                    pack_ceiling,
                    pack_mark,
                    lfs_allowance,
                    cancel: crate::channel::Cancel::new(),
                })
            }
            other => Err(DispatchError::Denied {
                principal: principal.id.clone(),
                repo: path,
                needed: required,
                held: match other {
                    Some(level) => level.to_string(),
                    None => "none".to_string(),
                },
            }),
        }
    }

    /// **Ask the gate chain**, for a request the grant check already admitted.
    /// `Ok(Some(line))` is an allowed request that carries a warning (Grace);
    /// `Err(Plan)` is the refusal, with the line the client is told.
    ///
    /// The three shapes, and why each asks what it asks:
    ///
    /// * a **write** (`git-receive-pack`, LFS upload) asks
    ///   [`PlanAction::Write`](crate::plan::PlanAction::Write), and if that is
    ///   allowed asks [`PlanGate::pack_quota`](crate::plan::PlanGate::pack_quota)
    ///   — both before a single pack byte is read;
    /// * an **anonymous read** asks
    ///   [`PlanAction::AnonymousRead`](crate::plan::PlanAction::AnonymousRead):
    ///   a lapsed tenant's public surface is what costs the provider and earns
    ///   nothing;
    /// * an **authenticated read** asks nothing. The owner clones their own
    ///   repositories in every state, and so does anyone they granted. That is
    ///   rule 1 of `gunnar_core::entitlement`, and it is enforced here by the
    ///   absence of a question rather than by an answer.
    ///
    /// **The chain.** Gates are asked in the order `Control::with_plan_gate`
    /// added them — disk first — and the FIRST `Refuse` is the answer; a later
    /// gate is not consulted, so a full box is told it is full and not also
    /// that its plan lapsed. Each gate is asked BOTH its questions before the
    /// next gate is asked anything: its ladder (`verdict`), then, for a write
    /// that grows data, its quota (`pack_quota`). Within one gate that order is
    /// what tells a Suspended tenant they are suspended rather than also full;
    /// across gates it is what makes "disk first" mean disk first — the disk
    /// gate only ever refuses from `pack_quota`, and a chain that asked every
    /// ladder before any quota would let a plan's ladder outrank it whatever
    /// the order (`tests/disk_headroom.rs` caught exactly that, red first).
    /// Warnings from every allowing gate are joined.
    ///
    /// With no gate wired (`Control::with_plan_gate` never called) every
    /// namespace is Free and this is a no-op. A `Machine` principal —
    /// replication, the primary's copy arriving — is asked only of the gates
    /// that say they apply to it ([`PlanGate::applies_to_machine`]): the disk
    /// does, a plan does not, because refusing a lapsed tenant's replication
    /// would make their standby diverge from the primary.
    fn ask_plan(
        &self,
        principal: &Principal,
        service: GitService,
        required: Access,
        repo: &gunnar_core::Repo,
    ) -> Result<PlanOutcome, DispatchError> {
        use crate::plan::{PlanAction, PlanVerdict};
        let machine = principal.kind == gunnar_core::PrincipalKind::Machine;
        let gates: Vec<_> = self
            .control
            .plan_gates()
            .iter()
            .filter(|gate| !machine || gate.applies_to_machine())
            .collect();
        if gates.is_empty() {
            return Ok(PlanOutcome::default());
        }
        let anonymous = principal.id == gunnar_core::ANONYMOUS_PRINCIPAL_ID;
        let action = if required.permits(Access::Write) {
            PlanAction::Write
        } else if anonymous {
            PlanAction::AnonymousRead
        } else {
            return Ok(PlanOutcome::default());
        };
        let refused = |line: String| DispatchError::Plan {
            namespace: repo.namespace.clone(),
            line,
        };
        // `service` is named here so a future fourth write-shaped verb has to
        // decide whether it grows the tenant's data.
        let grows_data = matches!(
            service,
            GitService::ReceivePack | GitService::LfsTransfer(crate::command::Operation::Upload)
        );
        let mut notices: Vec<String> = Vec::new();
        let mut ceiling: Option<crate::plan::PackCeiling> = None;
        let mut allowance: Option<gunnar_lfs::Allowance> = None;
        // **Marked BEFORE any gate walks the disk, and that ordering is the
        // contract**, not an accident of where the line sits. A gate's
        // `lfs_allowance` measures the namespace's bytes off the disk; an upload
        // admitted DURING that walk may or may not have landed bytes for the
        // walk to see. Taking the mark first puts such an admission after the
        // mark, so it is charged — and charged twice if the walk saw it too,
        // which refuses a shade early. Taking the mark after the walk would put
        // it before the mark and possibly outside the walk, which admits too
        // much. Only one of those two roundings is a quota that leaks. See
        // `gunnar_lfs::ledger`.
        let mark = gunnar_lfs::AllowanceLedger::shared().mark(&repo.namespace);
        // …and the same standing in the PACK meter, taken in the same breath and
        // for the same reason: `pack_ceiling` below measures the namespace's
        // packfile bytes off the disk, and a push admitted during that walk has
        // to land after this mark to be counted.
        //
        // **Two marks and not one, because they are two meters.**
        // `caps["pack_bytes"]` and `caps["lfs_bytes"]` are capped separately on
        // the signed fact and reported separately by `Usage.Read`, and the two
        // numbers these marks are judged against are computed from different
        // caps. One shared counter would charge an LFS upload against a push's
        // ceiling — cutting a push mid-transfer over room its own cap never
        // lost — which is a quota that refuses wrongly, the same defect as one
        // that admits wrongly. They share a disk; they do not share a cap. See
        // `gunnar_lfs::AllowanceLedger::shared_pack`.
        let pack_mark = gunnar_lfs::AllowanceLedger::shared_pack().mark(&repo.namespace);
        for gate in &gates {
            match gate.verdict(&repo.namespace, action) {
                PlanVerdict::Allow => {}
                PlanVerdict::Warn(line) => notices.push(line),
                PlanVerdict::Refuse(line) => return Err(refused(line)),
            }
            // The quota, only for a write this gate's ladder allowed.
            if action == PlanAction::Write && grows_data {
                if let PlanVerdict::Refuse(line) = gate.pack_quota(&repo.namespace) {
                    return Err(refused(line));
                }
                // **The smallest ceiling in the chain wins**, which is the
                // byte-wise spelling of first-`Refuse`-wins one line above: a
                // push has to satisfy every gate, so it is held to the
                // tightest one, and the line the client reads is that gate's
                // own. Asked only where `pack_quota` is asked, so a read and a
                // deletion are never given a ceiling to trip over.
                if let Some(asked) = gate.pack_ceiling(&repo.namespace) {
                    let tighter = match &ceiling {
                        Some(held) => asked.bytes < held.bytes,
                        None => true,
                    };
                    if tighter {
                        ceiling = Some(asked);
                    }
                }
                // …and the same tightest-wins rule for the LFS wire, for the
                // same reason: a transfer has to satisfy every gate, so it is
                // held to the smallest room any of them will admit, and the
                // sentence the tenant reads is that gate's own.
                if let Some(asked) = gate.lfs_allowance(&repo.namespace) {
                    let tighter = match &allowance {
                        Some(held) => asked.bytes < held.bytes,
                        None => true,
                    };
                    if tighter {
                        allowance = Some(asked);
                    }
                }
            }
        }
        Ok(PlanOutcome {
            notice: (!notices.is_empty()).then(|| notices.join("; ")),
            // The tightest gate's number and the standing taken before any gate
            // looked, carried side by side rather than folded into one type:
            // see `ServiceRequest::pack_mark` for why the ceiling stays exactly
            // what `PlanGate::pack_ceiling` returned.
            pack_mark: ceiling.is_some().then_some(pack_mark),
            ceiling,
            // The tightest gate's number, bound to the standing taken above it.
            // `mark` is dropped unused when no gate asked for an allowance,
            // which costs one map read and holds nothing: there is no
            // reservation in a mark to leak.
            allowance: allowance
                .map(|allowance| gunnar_lfs::NamespaceAllowance::new(mark, allowance)),
        })
    }
}

/// What [`Dispatch::ask_plan`] learned: everything the gate chain wants carried
/// into the transfer, as opposed to the refusals, which are returned as errors
/// and never reach here.
///
/// A struct and not a tuple because both fields are `Option` and both are
/// about the plan: a `(Option<String>, Option<PackCeiling>)` at the call site
/// is two anonymous maybes that the next field added would make three.
#[derive(Default)]
struct PlanOutcome {
    /// See [`crate::ServiceRequest::plan_notice`].
    notice: Option<String>,
    /// See [`crate::ServiceRequest::pack_ceiling`].
    ceiling: Option<crate::plan::PackCeiling>,
    /// See [`crate::ServiceRequest::pack_mark`]. `Some` exactly when `ceiling`
    /// is: a mark with no number to be judged against is bookkeeping nobody
    /// reads, and a number with no mark is the bug this closed.
    pack_mark: Option<gunnar_lfs::Mark>,
    /// See [`crate::ServiceRequest::lfs_allowance`]. A third `Option` on this
    /// struct, and the reason the struct exists rather than a tuple.
    allowance: Option<gunnar_lfs::NamespaceAllowance>,
}

// ───────────────────────────────────────────────────────────────────────────
// The server
// ───────────────────────────────────────────────────────────────────────────

struct Shared {
    dispatch: Dispatch,
    transport: Arc<dyn GitTransport>,
    exec_grace: Option<Duration>,
    /// Whether `auth_none` on [`ANONYMOUS_SSH_USER`] is accepted.
    allow_anonymous: bool,
    admission: Arc<Admission>,
    metrics: Arc<ServerMetrics>,
    /// **Are the stores open?** See [`GunnarSsh::with_readiness`].
    ready: Arc<std::sync::atomic::AtomicBool>,
    /// [`SshConfig::max_auth_attempts`], carried here because the CONNECTION
    /// enforces it and russh 0.61.2 does not. See
    /// [`Connection::auth_attempts`].
    config_max_auth_attempts: usize,
    /// [`SshConfig::session_end_grace`] and
    /// [`SshConfig::session_end_grace_crowded`].
    session_end_grace: (Duration, Duration),
    /// The sealed box's tunnel-address door ([`TUNNEL_ADDRESS_VERB`]), or
    /// `None` on a build with no WireGuard tunnel.
    tunnel_door: Option<TunnelAddressDoor>,
    /// The repository-settings door ([`REPO_VERB`]), or `None` on a server
    /// with no control plane (`serve --no-grpc`).
    repo_door: Option<RepoDoor>,
}

/// **The one control verb on this listener** (2026-09-21, T17):
/// `gunnar-tunnel-address [a.b.c.d/prefix]`.
///
/// The sealed installer runs `serve --no-grpc`, so its SSH door is its only
/// door, and a box's WireGuard tunnel address is per box and not on the
/// medium. So it arrives here, held to **server-wide Admin** and answered by
/// the closure `gunnar-server` injects — the SAME function the gRPC doors call.
/// No argument is a read. Output is `key value` lines on stdout, exit 0; a
/// refusal is `error: <why>` on stdout, exit 1 (stdout and not stderr, so a
/// client reading only the data band still gets the sentence). Not a git
/// verb, so it never enters [`Dispatch::authorise`] or the transfer path.
pub const TUNNEL_ADDRESS_VERB: &str = "gunnar-tunnel-address";

/// **The operator's fire drill** (stinkies ssh-double-exec-error, 2026-09-30): ONE exec
/// verb, held to server-wide Admin like [`TUNNEL_ADDRESS_VERB`], that says exactly one
/// ERROR naming itself a drill and who asked — what the estate's watch raises on purpose
/// to prove its alert path end to end. Nothing is wrong when it is said; no other caller
/// can raise the server's ERROR at will.
pub const FIRE_DRILL_VERB: &str = "gunnar-fire-drill";

/// **A member's SSH public keys, for an encrypted repository's key ring**
/// (2026-10-06): `gunnar-recipient-keys '<namespace>/<repository>' '<member>'`.
///
/// What `gunnar crypt add-member NAME --from-server` asks when it is given no
/// control address — on an installed estate the forge's SSH door (tcp/2222
/// through the front) is the one door a member's key opens; the control plane
/// is bound to the WireGuard overlay. The SAME rule as `Repos.RecipientKeys`:
/// the caller reads the repository (otherwise it is told what a stranger is
/// told, the one "not found, or no access" sentence), and so must the person
/// named — gunnar hands out keys only for someone who could read it anyway,
/// never a directory of everybody's keys. Output is one OpenSSH public key
/// line per key on stdout, exit 0; a refusal is `error: <why>` on stdout,
/// exit [`EXIT_DENIED`] (stdout, like [`TUNNEL_ADDRESS_VERB`]'s). An anonymous
/// session is refused the channel. Not a git verb: it never enters
/// [`Dispatch::authorise`] or the transfer path, and it changes nothing.
pub const RECIPIENT_KEYS_VERB: &str = "gunnar-recipient-keys";

/// **Who this key is** (wiring tracer B 2026-10-08): `gunnar-whoami` answers the principal id
/// the session authenticated as, one line, exit 0 — what `gunnar crypt init` names its first
/// member by (the account name `add-member --from-server` looks members up by). Reveals nothing
/// the key's holder does not already know. An anonymous session is refused the channel. Not a
/// git verb.
pub const WHOAMI_VERB: &str = "gunnar-whoami";

/// **git-lfs's fallback verb**, answered with a sentence instead of a channel
/// failure. Gunnar serves Git LFS over pure SSH only (`git-lfs-transfer`,
/// git-lfs >= 3.0); git-lfs asks this verb only when a pure-SSH session failed
/// or was refused, and then prints what is on stderr after `batch request:`.
pub const LFS_AUTHENTICATE_VERB: &str = "git-lfs-authenticate";

/// What [`LFS_AUTHENTICATE_VERB`] answers, on stderr with exit 1. It must never
/// say `not found` / `no such file`: git-lfs reads those as "no such verb" and
/// goes on to a guessed HTTPS endpoint, which Gunnar does not serve.
pub const LFS_AUTHENTICATE_MESSAGE: &str = "Gunnar serves Git LFS over pure SSH only (git-lfs-transfer, \
git-lfs 3.0 or newer); there is no HTTPS LFS endpoint. The pure SSH transfer just failed or was \
refused (the server was busy or restarting): run the same command again.\n";

/// **A repository's settings, over the forge's door** (owner, 2026-10-14):
/// `gunnar-repo show '<namespace>/<repository>'`,
/// `gunnar-repo visibility '<namespace>/<repository>' public|private`,
/// `gunnar-repo default-branch '<namespace>/<repository>' '<refs/heads/…>'`.
///
/// What the client `gunnar repo show|visibility|default-branch` asks. On an
/// installed estate the forge's SSH door (tcp/2222 through the front) is the
/// one door a person's key opens; the control plane is bound to the WireGuard
/// overlay. The verb decides NOTHING itself: it hands the authenticated
/// principal and the ask to [`RepoDoor`], which `gunnar-server` answers with
/// the SAME `Repos.Get` / `Repos.SetVisibility` / `Repos.SetDefaultBranch`
/// handlers the control plane mounts — so the account-admin rule for
/// visibility, the repository-Admin rule for the default branch, the audit
/// event and the browse replica's notice are the gRPC door's, not a copy.
/// Output is `key value` lines on stdout, exit 0; a refusal is
/// `error: <why>` on stdout, exit [`EXIT_DENIED`]. An anonymous session is
/// refused the channel. Not a git verb: it never enters
/// [`Dispatch::authorise`] or the transfer path.
pub const REPO_VERB: &str = "gunnar-repo";

/// What a [`REPO_VERB`] line asks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RepoAction {
    /// `Repos.Get`.
    Show,
    /// `Repos.SetVisibility`: `true` is public.
    Visibility(bool),
    /// `Repos.SetDefaultBranch`, the branch exactly as sent (the server
    /// validates it; the client expands a short name).
    DefaultBranch(String),
    /// `Repos.Create` of an empty repository in this object format (`true`
    /// is sha256): what a client that knows its own format asks before its
    /// first push, since a push-made repository can only be sha1.
    Create {
        /// `true`: a sha256 repository; `false`: sha1.
        sha256: bool,
    },
}

/// One [`REPO_VERB`] ask, with who asked: the principal the session's key
/// authenticated as (re-read at the exec, never cached) and that key's
/// fingerprint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RepoAsk {
    /// The principal the session's key authenticated as.
    pub principal: String,
    /// That key's fingerprint.
    pub fingerprint: String,
    /// The repository the verb names.
    pub repo: RepoRef,
    /// The verb itself.
    pub action: RepoAction,
}

/// What answers [`REPO_VERB`]: the ask in, the `key value` lines or the
/// refusal's sentence out.
pub type RepoDoor = Arc<
    dyn Fn(RepoAsk) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<String, String>> + Send>>
        + Send
        + Sync,
>;

/// Parse a [`REPO_VERB`] exec line. `None`: not this verb. `Some(Err)`: this
/// verb, malformed. Each argument may be single-quoted the way git quotes a
/// path; the path goes through the one sandbox
/// ([`gunnar_core::resolve_repo_path`]).
pub fn parse_repo_verb(raw: &[u8]) -> Option<Result<(RepoRef, RepoAction), String>> {
    let text = std::str::from_utf8(raw).ok()?;
    let mut tokens = text.split(' ').filter(|t| !t.is_empty());
    if tokens.next()? != REPO_VERB {
        return None;
    }
    let usage = || {
        format!(
            "the line is not `{REPO_VERB} show <namespace>/<repository>`, \
             `{REPO_VERB} visibility <namespace>/<repository> public|private` or \
             `{REPO_VERB} default-branch <namespace>/<repository> <branch>` or \
             `{REPO_VERB} create <namespace>/<repository> sha1|sha256`"
        )
    };
    if raw.len() > crate::command::MAX_EXEC_LEN || raw.iter().any(|b| *b < 0x20 || *b == 0x7f) {
        return Some(Err(usage()));
    }
    let mut args = Vec::new();
    for token in tokens {
        match crate::command::unquote(token) {
            Ok(arg) => args.push(arg),
            Err(_) => return Some(Err(usage())),
        }
    }
    let (sub, path, value) = match args.as_slice() {
        [sub, path] => (sub.as_str(), path.as_str(), None),
        [sub, path, value] => (sub.as_str(), path.as_str(), Some(value.as_str())),
        _ => return Some(Err(usage())),
    };
    let action = match (sub, value) {
        ("show", None) => RepoAction::Show,
        ("visibility", Some("public")) => RepoAction::Visibility(true),
        ("visibility", Some("private")) => RepoAction::Visibility(false),
        ("visibility", Some(other)) => {
            return Some(Err(format!("visibility is `public` or `private`, not `{}`", other.escape_default())))
        }
        ("default-branch", Some(branch)) if !branch.is_empty() => RepoAction::DefaultBranch(branch.to_string()),
        ("create", Some("sha256")) => RepoAction::Create { sha256: true },
        ("create", Some("sha1")) => RepoAction::Create { sha256: false },
        ("create", Some(other)) => {
            return Some(Err(format!("an object format is `sha1` or `sha256`, not `{}`", other.escape_default())))
        }
        _ => return Some(Err(usage())),
    };
    let repo = match gunnar_core::resolve_repo_path(path) {
        Ok(repo) => repo,
        Err(err) => return Some(Err(err.to_string())),
    };
    Some(Ok((repo, action)))
}

/// Parse a [`RECIPIENT_KEYS_VERB`] exec line. `None`: not this verb.
/// `Some(Err)`: this verb, malformed. The path and the member may each be
/// single-quoted the way git quotes a path; the path goes through the one
/// sandbox ([`gunnar_core::resolve_repo_path`]) and the member through the
/// principal id rule.
pub fn parse_recipient_keys_verb(raw: &[u8]) -> Option<Result<(RepoRef, String), String>> {
    let text = std::str::from_utf8(raw).ok()?;
    let (verb, rest) = text.split_once(' ').unwrap_or((text, ""));
    if verb != RECIPIENT_KEYS_VERB {
        return None;
    }
    let usage = || format!("the line is not `{RECIPIENT_KEYS_VERB} <namespace>/<repository> <member>`");
    if raw.len() > crate::command::MAX_EXEC_LEN || raw.iter().any(|b| *b < 0x20 || *b == 0x7f) {
        return Some(Err(usage()));
    }
    let Some((path, member)) = rest.trim().rsplit_once(' ') else {
        return Some(Err(usage()));
    };
    let (Ok(path), Ok(member)) = (crate::command::unquote(path.trim()), crate::command::unquote(member.trim())) else {
        return Some(Err(usage()));
    };
    let repo = match gunnar_core::resolve_repo_path(&path) {
        Ok(repo) => repo,
        Err(err) => return Some(Err(err.to_string())),
    };
    if gunnar_core::Principal::new(member.clone(), member.clone(), gunnar_core::PrincipalKind::User).is_err() {
        return Some(Err(format!("`{}` is not an account name", member.escape_default())));
    }
    Some(Ok((repo, member)))
}

/// **The answer to [`RECIPIENT_KEYS_VERB`]** for `caller`: `(exit status,
/// stdout)`. Reads the identity table and the catalog; changes nothing.
pub fn recipient_keys_answer(control: &Control, caller: &str, repo: &RepoRef, member: &str) -> (u32, String) {
    if control.is_twin() {
        let said = DispatchError::Twin { principal: caller.to_string(), repo: repo.clone() }.client_message().unwrap_or_default();
        return (EXIT_DENIED, format!("error: {said}\n"));
    }
    let hidden = || {
        let said = DispatchError::NoSuchRepo(repo.clone()).client_message().unwrap_or_default();
        (EXIT_DENIED, format!("error: {said}\n"))
    };
    // The member is told Gunnar could not answer; what broke is the operator's (the journal).
    let fault = |err: gunnar_core::Error| {
        tracing::error!(target: "gunnar::ssh", event = "ssh.recipient_keys.fault", %err, "gunnar-recipient-keys: the identity table or the catalog could not be read");
        (EXIT_DENIED, "error: Gunnar could not answer this just now; try again in a while\n".to_string())
    };
    let entry = match control.catalog().get(repo) {
        Ok(Some(entry)) => entry,
        Ok(None) => return hidden(),
        Err(err) => return fault(err),
    };
    match control.auth().may(caller, &entry, gunnar_core::Level::Read) {
        Ok(true) => {}
        Ok(false) => return hidden(),
        Err(err) => return fault(err),
    }
    match control.auth().may(member, &entry, gunnar_core::Level::Read) {
        Ok(true) => {}
        Ok(false) => {
            return (
                EXIT_DENIED,
                format!(
                    "error: {member} cannot read {}/{}: grant them access before adding them as a member of its key ring\n",
                    repo.namespace(),
                    repo.name()
                ),
            )
        }
        Err(err) => return fault(err),
    }
    // **The member's ONE encryption key** (CRYPT-YUBI 2026-10-26): a ring is wrapped to the
    // person's encryption public key, never to an SSH key.
    let Some(keys) = control.encryption_keys() else {
        return (EXIT_DENIED, "error: this Gunnar keeps no encryption keys\n".to_string());
    };
    match keys.public_of(member) {
        Ok(Some(public)) => (0, format!("{}\n", public.trim())),
        Ok(None) => (
            EXIT_DENIED,
            format!(
                "error: {member} has no encryption key yet: {member} makes one with `gunnar crypt key new` \
                 (or by adding a security key on their Account page), then the ring can be wrapped to it\n"
            ),
        ),
        Err(gunnar_core::encryption_key::KeyRefusal::Store(err)) => fault(err),
        Err(other) => (EXIT_DENIED, format!("error: {other}\n")),
    }
}

/// **The answer to [`gunnar_crypt::door::VERB`]** (`gunnar-user-key`, CRYPT-YUBI) for
/// `caller`, the session's own principal: `(exit status, stdout)`. Reads or changes the
/// caller's own encryption key only; there is no name to give.
pub fn user_key_answer(control: &Control, principal: &gunnar_core::Principal, request: gunnar_crypt::door::Request) -> (u32, String) {
    let caller = principal.id.as_str();
    use gunnar_core::encryption_key::{KeyRefusal, UnlockMethod};
    use gunnar_crypt::door::Request;
    if control.is_twin() {
        return (EXIT_DENIED, "error: this is a twin; ask the primary\n".to_string());
    }
    let Some(keys) = control.encryption_keys() else {
        return (EXIT_DENIED, "error: this Gunnar keeps no encryption keys\n".to_string());
    };
    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);
    let said = |r: Result<gunnar_core::encryption_key::EncryptionKey, KeyRefusal>| match r {
        Ok(key) => (0, key.to_answer().text()),
        Err(KeyRefusal::Store(err)) => {
            tracing::error!(target: "gunnar::ssh", event = "ssh.user_key.fault", %err, "gunnar-user-key: the store could not be read or written");
            (EXIT_DENIED, "error: Gunnar could not answer this just now; try again in a while\n".to_string())
        }
        Err(other) => (EXIT_DENIED, format!("error: {other}\n")),
    };
    match request {
        Request::Get => match keys.get(caller) {
            Ok(Some(key)) => (0, key.to_answer().text()),
            Ok(None) => (0, String::new()),
            Err(e) => said(Err(e)),
        },
        // The account's audit, the same kinds the gRPC door writes (RA4-3).
        Request::Create { public_key, method } => {
            let kind = method.kind.clone();
            let r = UnlockMethod::from_line(method).and_then(|m| keys.create(caller, &public_key, m, now));
            if r.is_ok() {
                control.encryption_key_event(principal, "encryption-key.created", &format!("first method {kind}"));
                tracing::info!(target: "gunnar::audit", event = "access.encryption_key_created", principal = %caller, method = %kind, "an encryption key was created");
            }
            said(r)
        }
        Request::Add(method) => {
            let kind = method.kind.clone();
            let r = UnlockMethod::from_line(method).and_then(|m| keys.add_method(caller, m, now));
            if r.is_ok() {
                control.encryption_key_event(principal, "encryption-key.method-added", &kind);
                tracing::info!(target: "gunnar::audit", event = "access.unlock_method_added", principal = %caller, method = %kind, "an unlock method was added");
            }
            said(r)
        }
        Request::Remove(id) => {
            let r = keys.remove_method(caller, &id);
            if r.is_ok() {
                control.encryption_key_event(principal, "encryption-key.method-removed", &id);
                tracing::info!(target: "gunnar::audit", event = "access.unlock_method_removed", principal = %caller, method_id = %id, "an unlock method was removed");
            }
            said(r)
        }
    }
}

/// What answers [`TUNNEL_ADDRESS_VERB`]: the address (empty = a read) in, the
/// answer's lines or the refusal out.
pub type TunnelAddressDoor = Arc<dyn Fn(&str) -> Result<String, String> + Send + Sync>;

/// Parse a [`TUNNEL_ADDRESS_VERB`] exec line. `None`: not this verb. `Some(Err)`:
/// this verb, malformed. Printable ASCII only, at most one argument, short.
pub fn parse_tunnel_address_verb(raw: &[u8]) -> Option<Result<String, String>> {
    let text = std::str::from_utf8(raw).ok()?;
    let mut tokens = text.split(' ').filter(|t| !t.is_empty());
    if tokens.next()? != TUNNEL_ADDRESS_VERB {
        return None;
    }
    if raw.len() > 64 || !raw.iter().all(|b| (0x20..0x7f).contains(b)) {
        return Some(Err("the line is not `gunnar-tunnel-address [a.b.c.d/prefix]`".to_string()));
    }
    let address = tokens.next().unwrap_or("").to_string();
    if tokens.next().is_some() {
        return Some(Err("one argument at most: `gunnar-tunnel-address [a.b.c.d/prefix]`".to_string()));
    }
    Some(Ok(address))
}

/// **The key exchanges gunnar's SSH door offers, post-quantum FIRST**
/// (2026-10-06, the PQ transport lane).
///
/// `mlkem768x25519-sha256` (draft-ietf-sshm-mlkem-hybrid-kex: ML-KEM-768 and
/// X25519, the session key from both) is what OpenSSH ≥ 9.9 offers first and
/// 10.0 makes its default — russh 0.63 runs it on RustCrypto's `ml-kem`. The
/// classical exchanges stay after it, so an older client still connects
/// (preferred, never required). `sntrup761x25519-sha512` is not here: russh
/// does not implement it.
///
/// **gunnar's own list, not russh's default**, though the two agree today:
/// a russh bump that reorders or drops its `Preferred::DEFAULT` must not
/// change what this door offers without a red test here. SSH lets the
/// CLIENT's order decide; the server's job is to offer the hybrid at all.
pub static KEX_ORDER: &[russh::kex::Name] = &[
    russh::kex::MLKEM768X25519_SHA256,
    russh::kex::CURVE25519,
    russh::kex::CURVE25519_PRE_RFC_8731,
    russh::kex::DH_GEX_SHA256,
    russh::kex::DH_G18_SHA512,
    russh::kex::DH_G17_SHA512,
    russh::kex::DH_G16_SHA512,
    russh::kex::DH_G15_SHA512,
    russh::kex::DH_G14_SHA256,
    russh::kex::EXTENSION_SUPPORT_AS_CLIENT,
    russh::kex::EXTENSION_SUPPORT_AS_SERVER,
    russh::kex::EXTENSION_OPENSSH_STRICT_KEX_AS_CLIENT,
    russh::kex::EXTENSION_OPENSSH_STRICT_KEX_AS_SERVER,
];

/// russh's algorithm preferences with gunnar's [`KEX_ORDER`]; ciphers, MACs
/// and host-key algorithms stay russh's.
pub fn preferred() -> russh::Preferred {
    russh::Preferred { kex: std::borrow::Cow::Borrowed(KEX_ORDER), ..russh::Preferred::DEFAULT }
}

/// gunnar's SSH listener.
pub struct GunnarSsh {
    config: SshConfig,
    shared: Arc<Shared>,
    /// **A connection that arrives at a refused LOCAL address is dropped**
    /// before a byte is spoken (`gunnar serve --wg-only`: the utility
    /// network's address — every box-to-box connection runs over the tunnel).
    refused_local: Option<RefusedLocal>,
}

/// Is a connection that arrived at this local address refused?
pub type RefusedLocal = Arc<dyn Fn(std::net::IpAddr) -> bool + Send + Sync>;

impl GunnarSsh {
    /// Build a server over the control plane and the wire seam.
    pub fn new(config: SshConfig, control: Control, transport: Arc<dyn GitTransport>) -> Self {
        let exec_grace = config.exec_grace;
        let allow_anonymous = config.allow_anonymous;
        let config_max_auth_attempts = config.max_auth_attempts;
        let session_end_grace = (config.session_end_grace, config.session_end_grace_crowded);
        // The memory budget travels with the two concurrency numbers: one
        // constructor, so a configuration cannot arrive with a governed
        // concurrency limit and an unmetered budget. `None` falls back to the
        // shipped constant rather than to "unlimited" — an operator who did not
        // set a budget wants the default, not the removal of a gate.
        let budget = config
            .memory_budget_bytes
            .unwrap_or(crate::governor::DEFAULT_MEMORY_BUDGET_BYTES);
        let wait = config
            .admission_wait
            .unwrap_or(crate::governor::DEFAULT_ADMISSION_WAIT);
        let admission = Arc::new(
            if config.per_principal_limit_is_hard {
                Admission::hard_capped(
                    config.max_concurrent_transfers,
                    config.max_transfers_per_principal,
                )
                .with_budget(budget)
            } else {
                Admission::with_memory_budget(
                    config.max_concurrent_transfers,
                    config.max_transfers_per_principal,
                    budget,
                )
            }
            // The anonymous door and its width are configured together, so
            // an appliance that opens the door cannot forget the ceiling.
            .with_anonymous_ceiling(config.max_anonymous_transfers)
            .with_wait(wait)
            .with_keyed_wait(config.keyed_admission_wait),
        );
        // The usage share (`admit-share`): the configured policy, unseeded
        // until `with_flow` hands it the durable ledger to seed from.
        #[cfg(feature = "admit-share")]
        let admission = Arc::new(
            Arc::try_unwrap(admission)
                .expect("the gate is not shared yet")
                .with_policy(config.admit.build()),
        );
        GunnarSsh {
            config,
            refused_local: None,
            shared: Arc::new(Shared {
                dispatch: Dispatch::new(control),
                transport,
                exec_grace,
                allow_anonymous,
                admission,
                metrics: Arc::new(ServerMetrics::new()),
                // Ready unless somebody hands us a flag to watch. A listener
                // built by a test has nothing to wait for, and a default of
                // "not ready" would make every such test hang on a sentence
                // about a boot that never happened.
                ready: Arc::new(std::sync::atomic::AtomicBool::new(true)),
                config_max_auth_attempts,
                session_end_grace,
                tunnel_door: None,
                repo_door: None,
            }),
        }
    }

    /// **Watch a readiness flag**, and answer git traffic with a *retryable*
    /// sentence until it is set.
    ///
    /// # The boot window — MEASURED 2026-08-30
    ///
    /// After a power cut the appliance answered ssh :2222 and grpc :50051
    /// **0.6–0.7 s before its stores had finished their post-crash open**, and
    /// a read in that window came back `the repository is unavailable; try
    /// again`. That sentence is `gunnar_wire::Error::Store`'s, it arrives with
    /// a *denial* exit status, and it is what a client is told when a
    /// repository is genuinely broken — so a harness could not tell "not yet"
    /// from "gone". The first power-cut door reported **64 acked pushes
    /// missing**; a boot one second later found every one of them, and the same
    /// window wedged a whole bench run's clone and fetch phases.
    ///
    /// The fix is not to bind later — PID 1 must answer quickly or an operator
    /// watching a console sees a dead box — but to answer **honestly**. While
    /// the flag is clear every git exec is refused in git's own protocol with
    /// [`EXIT_BUSY`] (75, EX_TEMPFAIL — the same status the admission gate
    /// uses, which is the status that means *retry*) and a sentence containing
    /// the word **starting**, which is the word a script may key on. Nothing is
    /// served, nothing is opened, and nothing looks like a missing repository.
    ///
    /// A flag and not a trait: `gunnar-ssh` may not read the operating system,
    /// and "have the stores finished opening" is `gunnar-server`'s fact to
    /// publish, not this crate's to discover.
    pub fn with_readiness(mut self, ready: Arc<std::sync::atomic::AtomicBool>) -> Self {
        // `Arc::get_mut` cannot be used: `bind` has not run, but `Shared` is
        // already behind an `Arc`. Rebuilding it is one allocation at start-up
        // and keeps every field in one place.
        let shared = Arc::try_unwrap(self.shared).unwrap_or_else(|shared| {
            panic!(
                "readiness must be set before the listener is shared: {} strong refs",
                Arc::strong_count(&shared)
            )
        });
        self.shared = Arc::new(Shared { ready, ..shared });
        self
    }

    /// **Refuse every connection that arrives at a local address `refused`
    /// names** — closed at accept, nothing said, logged once per peer at
    /// debug. `gunnar serve --wg-only` names the utility address: the public's
    /// git clients still reach SSH, a box over plain IP does not.
    pub fn with_refused_local(mut self, refused: RefusedLocal) -> Self {
        self.refused_local = Some(refused);
        self
    }

    /// **Answer [`TUNNEL_ADDRESS_VERB`]** with `door` — `gunnar-server` hands in
    /// its `appliance::tunnel_address_answer`, the function both gRPC doors
    /// call. Without one the verb is answered "no WireGuard tunnel".
    pub fn with_tunnel_address_door(mut self, door: TunnelAddressDoor) -> Self {
        let shared = Arc::try_unwrap(self.shared).unwrap_or_else(|shared| {
            panic!(
                "the tunnel door must be set before the listener is shared: {} strong refs",
                Arc::strong_count(&shared)
            )
        });
        self.shared = Arc::new(Shared { tunnel_door: Some(door), ..shared });
        self
    }

    /// **Answer [`REPO_VERB`]** with `door` — `gunnar-server` hands in the
    /// control plane's own `Repos` handlers. Without one the verb is answered
    /// "this server answers repository settings only on its control plane".
    pub fn with_repo_door(mut self, door: RepoDoor) -> Self {
        let shared = Arc::try_unwrap(self.shared).unwrap_or_else(|shared| {
            panic!(
                "the repository door must be set before the listener is shared: {} strong refs",
                Arc::strong_count(&shared)
            )
        });
        self.shared = Arc::new(Shared { repo_door: Some(door), ..shared });
        self
    }

    /// **Give the admission gate the per-namespace flow ledger.**
    ///
    /// The gate is what all three front doors — this exec line, smart HTTP and
    /// the gRPC transfer gate — ask before a transfer, so it is the one place a
    /// refusal can be charged to a tenant once rather than three times. The
    /// exec line's own `no-grant` denial reaches the same ledger back through
    /// `Admission::flow`.
    ///
    /// A listener built without one refuses exactly as it always did and counts
    /// the refusal only in its own `AdmissionStats`, which is what a test that
    /// drives `gunnar-ssh` alone wants — and what every build before the ledger
    /// existed did.
    ///
    /// The gate is rebuilt rather than mutated for the reason
    /// [`Self::with_readiness`] rebuilds `Shared`: `bind` has not run, but the
    /// `Arc` is already there.
    pub fn with_flow(mut self, flow: Arc<gunnar_core::FlowLedger>) -> Self {
        let shared =
            Arc::get_mut(&mut self.shared).expect("the shared state is not published until `bind`");
        let gate = Arc::try_unwrap(std::mem::replace(
            &mut shared.admission,
            Arc::new(Admission::unlimited()),
        ))
        .unwrap_or_else(|gate| {
            panic!(
                "the flow ledger must be set before the gate is shared: {} strong refs",
                Arc::strong_count(&gate)
            )
        });
        // admit-share: the policy is rebuilt SEEDED from this ledger — its
        // table is then a cache of the ledger, filled once per namespace.
        #[cfg(feature = "admit-share")]
        let gate = gate.with_policy(
            self.config
                .admit
                .build_seeded(Some(Admission::flow_seed(Arc::clone(&flow)))),
        );
        shared.admission = Arc::new(gate.with_flow(flow));
        self
    }

    /// Share the server-wide counters with the rest of the process.
    ///
    /// **Not a second set of counters.** `gunnar serve` mints one
    /// [`ServerMetrics`] and hands the same `Arc` to this listener and to the
    /// git transport, so "connections refused" and "pushes rejected by gate"
    /// are numbers about one server rather than two crates' private tallies.
    /// A listener built without this one still counts, into a set nobody else
    /// can read, which is what a test that only drives `gunnar-ssh` wants.
    pub fn with_metrics(mut self, metrics: Arc<ServerMetrics>) -> Self {
        let shared =
            Arc::get_mut(&mut self.shared).expect("the shared state is not published until `bind`");
        shared.metrics = metrics;
        self
    }

    /// The counters this listener writes to.
    pub fn metrics(&self) -> &Arc<ServerMetrics> {
        &self.shared.metrics
    }

    /// The russh configuration this server runs with.
    ///
    /// `methods` is publickey **only**, and stays that way even with the
    /// anonymous path open: `none` is available for exactly one username,
    /// so advertising it to everybody would make the failure list a lie and
    /// invite every client to try something that will not work. russh calls
    /// [`Handler::auth_none`] on the client's opening probe regardless of what
    /// is advertised, which is the only place it is needed.
    ///
    /// `password` is not offered and there is no handler for it, so the
    /// rejecting default is never the last line of defence.
    fn russh_config(&self, host_key: russh::keys::PrivateKey) -> RusshConfig {
        RusshConfig {
            server_id: russh::SshId::Standard(self.config.server_id.clone().into()),
            preferred: preferred(),
            methods: MethodSet::from(&[MethodKind::PublicKey][..]),
            auth_rejection_time: self.config.auth_rejection_time,
            auth_rejection_time_initial: Some(Duration::ZERO),
            keys: vec![host_key],
            max_auth_attempts: self.config.max_auth_attempts,
            inactivity_timeout: self.config.inactivity_timeout,
            keepalive_interval: self.config.keepalive_interval,
            nodelay: true,
            ..RusshConfig::default()
        }
    }

    /// Bind the listener and start accepting.
    ///
    /// Returns once the socket is bound, so a caller (or a test) knows the
    /// real address before the first client connects. That matters for
    /// [`SshConfig::ephemeral_loopback`], where the port is chosen by the
    /// kernel.
    pub async fn bind(self, host_key: russh::keys::PrivateKey) -> std::io::Result<BoundServer> {
        let listener = TcpListener::bind(self.config.bind).await?;
        let local_addr = listener.local_addr()?;
        let russh_config = Arc::new(self.russh_config(host_key));
        let shared = self.shared.clone();
        let admission = Arc::clone(&self.shared.admission);
        let metrics = Arc::clone(&self.shared.metrics);
        let (handle, _) = tokio::sync::broadcast::channel::<String>(1);

        let join = tokio::spawn(accept_loop(
            listener,
            russh_config,
            Factory { shared },
            handle.clone(),
            self.refused_local.clone(),
        ));

        tracing::info!(
            target: TARGET_SSH,
            %local_addr,
            max_concurrent_transfers = ?admission.max_concurrent(),
            max_transfers_per_principal = ?admission.max_per_principal(),
            per_principal_is_hard = admission.per_principal_is_hard(),
            "gunnar ssh listener bound"
        );
        Ok(BoundServer {
            local_addr,
            handle,
            join,
            admission,
            metrics,
        })
    }
}

/// How long the accept loop waits after the kernel refused it a descriptor,
/// before it asks again. A session ending in that window frees what the next
/// `accept` needs; nothing shorter gains anything, nothing longer is felt.
pub const ACCEPT_BACKOFF: Duration = Duration::from_millis(100);

/// Is this `accept` failure the kind the loop must outlive?
///
/// The resource ones — no descriptor left in the process (`EMFILE`) or in the
/// system (`ENFILE`), no buffer or memory for the socket — and the one the
/// client causes, `ECONNABORTED` (it hung up between SYN and `accept`).
/// Everything else (`EBADF`, `EINVAL`, a closed listener) is the listener
/// itself being gone, and the loop must return that.
pub fn accept_error_is_transient(err: &std::io::Error) -> bool {
    // Linux errno values, spelled here rather than through a `libc` crate this
    // crate does not otherwise carry: ENOMEM 12, ENFILE 23, EMFILE 24,
    // ECONNABORTED 103, ENOBUFS 105.
    matches!(err.raw_os_error(), Some(12 | 23 | 24 | 103 | 105))
        || matches!(
            err.kind(),
            std::io::ErrorKind::ConnectionAborted | std::io::ErrorKind::OutOfMemory
        )
}

/// **The accept loop, owned here so that it cannot die of `EMFILE`.**
///
/// russh's `run_on_socket` is the same loop with one difference that cost a
/// whole appliance: its `Err(e) => return Err(e)` on `accept`. MEASURED
/// 2026-08-29 on the rig: the 202nd repository touched since boot ran the
/// process out of descriptors, the next `accept` failed with `EMFILE`, the
/// loop returned, and every later client got `kex_exchange_identification:
/// read: Connection reset by peer` until reboot — the kernel kept completing
/// handshakes into a backlog nobody drained — while gRPC on its own listener
/// answered as if nothing were wrong. A server that has no descriptor for the
/// next client must say so and try again in a moment, not resign.
///
/// So on a transient failure ([`accept_error_is_transient`]) it logs a WARN
/// on `gunnar::ssh` — a row on the appliance dashboard — sleeps
/// [`ACCEPT_BACKOFF`] and continues. Everything else is what russh did: one
/// task per connection, `set_nodelay`, `run_stream`, the session raced against
/// the shutdown broadcast so `BoundServer::shutdown` still disconnects every
/// live session by application, and session errors go through
/// [`note_session_end`] exactly as `Server::handle_session_error` did.
async fn accept_loop(
    listener: TcpListener,
    config: Arc<RusshConfig>,
    mut factory: Factory,
    shutdown: tokio::sync::broadcast::Sender<String>,
    refused_local: Option<RefusedLocal>,
) -> std::io::Result<()> {
    let mut shutdown_rx = shutdown.subscribe();
    let mut refused_in_a_row: u32 = 0;
    loop {
        tokio::select! {
            _ = shutdown_rx.recv() => {
                tracing::debug!(target: TARGET_SSH, "ssh listener shutdown requested");
                return Ok(());
            }
            accepted = listener.accept() => {
                let (socket, peer) = match accepted {
                    Ok(pair) => pair,
                    Err(err) if accept_error_is_transient(&err) => {
                        refused_in_a_row += 1;
                        tracing::warn!(
                            target: TARGET_SSH,
                            event = "ssh.accept.refused",
                            error = %err,
                            refused_in_a_row,
                            "ssh accept failed: {err}; the listener stays up and retries in {} ms",
                            ACCEPT_BACKOFF.as_millis()
                        );
                        tokio::time::sleep(ACCEPT_BACKOFF).await;
                        continue;
                    }
                    Err(err) => {
                        tracing::error!(
                            target: TARGET_SSH,
                            event = "ssh.accept.failed",
                            error = %err,
                            "ssh accept failed with an error the listener cannot outlive"
                        );
                        return Err(err);
                    }
                };
                if let (Some(refused), Ok(local)) = (&refused_local, socket.local_addr()) {
                    if refused(local.ip()) {
                        tracing::debug!(target: TARGET_SSH, event = "ssh.accept.plain_ip_refused", %peer, %local, "a connection at the utility address is refused (--wg-only): boxes speak over the tunnel");
                        drop(socket);
                        continue;
                    }
                }
                if refused_in_a_row > 0 {
                    tracing::info!(
                        target: TARGET_SSH,
                        event = "ssh.accept.recovered",
                        refused_in_a_row,
                        "ssh accept works again"
                    );
                    refused_in_a_row = 0;
                }
                let handler = factory.new_client(Some(peer));
                let config = Arc::clone(&config);
                let mut session_shutdown = shutdown.subscribe();
                tokio::spawn(async move {
                    if config.nodelay {
                        if let Err(err) = socket.set_nodelay(true) {
                            tracing::debug!(target: TARGET_SSH, %err, "set_nodelay failed");
                        }
                    }
                    let session = match russh::server::run_stream(config, socket, handler).await {
                        Ok(session) => session,
                        Err(err) => {
                            note_session_end(&err);
                            return;
                        }
                    };
                    let handle = session.handle();
                    tokio::select! {
                        reason = session_shutdown.recv() => {
                            let reason = reason.unwrap_or_default();
                            let _ = handle
                                .disconnect(russh::Disconnect::ByApplication, reason, String::new())
                                .await;
                        }
                        ended = session => {
                            if let Err(err) = ended {
                                note_session_end(&err);
                            }
                        }
                    }
                });
            }
        }
    }
}

/// A bound, running listener.
pub struct BoundServer {
    local_addr: SocketAddr,
    /// The shutdown broadcast every live session and the accept loop listen on.
    handle: tokio::sync::broadcast::Sender<String>,
    join: JoinHandle<std::io::Result<()>>,
    admission: Arc<Admission>,
    metrics: Arc<ServerMetrics>,
}

impl BoundServer {
    /// The address actually bound, with the kernel's choice of port filled in.
    pub fn local_addr(&self) -> SocketAddr {
        self.local_addr
    }

    /// What the admission gate has done since this listener started.
    ///
    /// This is the visibility half of the fix. A limit whose saturation cannot
    /// be read is the same undiagnosable "git is slow" the accidental 512-thread
    /// ceiling produced; `admitted`, `refused_*` and `peak_in_flight` are what
    /// an operator, or a test, looks at instead.
    pub fn admission(&self) -> AdmissionStats {
        self.admission.stats()
    }

    /// The admission gate itself, so a **second transport can route through the
    /// SAME one** (one implementation).
    ///
    /// `gunnar-http` is a second front door onto the same server, and a git
    /// transfer over HTTP has to count against the same server-wide and
    /// per-principal ceilings — and the same memory budget — as one over SSH,
    /// or an appliance's real concurrency is silently twice the number written
    /// on the box. Handing out the `Arc` (rather than rebuilding a gate from
    /// the same numbers) is what makes it one gate with one set of counters,
    /// not two that happen to agree: on 2026-08-31 the HTTP front was found with no gate
    /// at all, and two gates would have been the next-worst answer.
    pub fn admission_gate(&self) -> Arc<Admission> {
        Arc::clone(&self.admission)
    }

    /// The server-wide counters.
    pub fn metrics(&self) -> gunnar_core::observe::MetricsSnapshot {
        self.metrics.snapshot()
    }

    /// The counter block itself, for a caller that wants to keep reading it
    /// after this listener is consumed by [`BoundServer::shutdown`].
    pub fn metrics_handle(&self) -> &Arc<ServerMetrics> {
        &self.metrics
    }

    /// Ask every session to disconnect, then wait for the accept loop to stop
    /// — for at most [`SSH_SHUTDOWN_GRACE`].
    ///
    /// **Bounded, the way the gRPC half already is** (`GRPC_SHUTDOWN_GRACE` in
    /// gunnar-server): the accept loop only ends when its sessions do, and a
    /// session whose peer never answers the disconnect — MEASURED 2026-09-28 on
    /// loki, a primary's replication session into a standby being stopped, 1 run
    /// in 17 under a parallel test binary — held `shutdown` for an hour. A
    /// shutdown that can hang forever is a restart, a drain or a growth that can
    /// hang forever. Past the grace the listener task is aborted and the reason
    /// is logged; the sessions go with the process.
    pub async fn shutdown(self, reason: &str) -> std::io::Result<()> {
        self.shutdown_within(reason, SSH_SHUTDOWN_GRACE).await
    }

    /// [`Self::shutdown`] with an explicit grace (tests use a short one).
    pub async fn shutdown_within(self, reason: &str, grace: Duration) -> std::io::Result<()> {
        let _ = self.handle.send(reason.to_string());
        let abort = self.join.abort_handle();
        match tokio::time::timeout(grace, self.join).await {
            Ok(Ok(result)) => result,
            Ok(Err(err)) if err.is_cancelled() => Ok(()),
            Ok(Err(err)) => Err(std::io::Error::other(err)),
            Err(_elapsed) => {
                tracing::warn!(
                    target: TARGET_SSH,
                    ?grace,
                    "the SSH listener did not stop within its grace: a session did not \
                     answer the disconnect. Aborting the listener so the shutdown completes."
                );
                abort.abort();
                Ok(())
            }
        }
    }
}

struct Factory {
    shared: Arc<Shared>,
}

impl Server for Factory {
    type Handler = Connection;

    fn new_client(&mut self, peer_addr: Option<SocketAddr>) -> Connection {
        // ── ONE span per connection, and one id ────────────────────────────
        //
        // `principal` and `repo` are declared `Empty` and filled in by
        // `auth_publickey` and `exec_request` as they become known, so every
        // line emitted under this connection carries all three WITHOUT the
        // call site repeating them. Before this, connection identity in the
        // SSH logs was an ad-hoc `?self.peer` copy-pasted to fourteen call
        // sites, and there was no way at all to tie two lines together.
        let conn = RequestId::next();
        let span = tracing::info_span!(
            target: TARGET_SSH,
            "ssh.connection",
            %conn,
            peer = tracing::field::Empty,
            principal = tracing::field::Empty,
            repo = tracing::field::Empty,
        );
        if let Some(peer) = peer_addr {
            span.record("peer", tracing::field::display(peer));
        }
        self.shared.metrics.add_connections_opened(1);
        span.in_scope(|| tracing::debug!(target: TARGET_SSH, "ssh connection accepted"));
        Connection {
            shared: self.shared.clone(),
            span,
            principal: None,
            key_fingerprint: None,
            channels: HashMap::new(),
            exec_seen: Arc::new(AtomicBool::new(false)),
            misuse_said: false,
            auth_attempts: 0,
            session_over: tokio::sync::watch::channel(false).0,
        }
    }

    /// The session loop stopped. Usually because the client hung up, which is
    /// how every git client ends a transfer and is not news.
    ///
    /// A free function does the deciding, for the same reason
    /// [`note_teardown`] is one: the rule can then be asserted without standing
    /// up a russh session, and what is asserted is the line an operator reads.
    fn handle_session_error(&mut self, error: anyhow::Error) {
        note_session_end(&error);
    }
}

/// One open session channel, before its exec request arrives.
struct OpenChannel {
    /// The channel itself. The exec request carries only a [`ChannelId`], and
    /// the byte stream can only be taken from the `Channel`.
    channel: Channel<Msg>,
    /// The value of `GIT_PROTOCOL`, if the client sent it and
    /// [`ENV_ALLOWLIST`] accepted the name. Kept beside the channel it was sent
    /// on so that it cannot outlive it or be read for a different one.
    git_protocol: Option<String>,
}

/// One client connection.
struct Connection {
    shared: Arc<Shared>,
    /// The `ssh.connection` span every line from this connection is emitted
    /// under. Cloned (cheap: it is an id, not the data) rather than borrowed
    /// at each entry point, because entering it borrows `self` immutably while
    /// every handler needs `&mut self`.
    span: tracing::Span,
    /// Set by `auth_publickey`, and the only thing that authorises anything.
    principal: Option<Principal>,
    /// The key `auth_publickey` authenticated this session with.
    ///
    /// Beside `principal` rather than inside it, because a principal is a
    /// server-side identity that may hold several keys and this is the one that
    /// made *this* connection. Stays `None` for the anonymous path, which
    /// authenticated with no key at all.
    key_fingerprint: Option<Fingerprint>,
    channels: HashMap<ChannelId, OpenChannel>,
    exec_seen: Arc<AtomicBool>,
    /// A request for a channel this connection does not hold open (a client's second
    /// `exec` on one channel) was said already: WARN once per connection, then quiet —
    /// a client's protocol misuse is never the server's ERROR (stinkies ssh-double-exec-error).
    misuse_said: bool,
    /// **How many publickey offers this connection has had refused.**
    ///
    /// Counted here because russh does not count it. `SshConfig::    /// max_auth_attempts` is handed to russh 0.61.2's `Config`, which declares
    /// the field, defaults it to 10 and `Debug`-prints it — and never compares
    /// it to anything. VERIFIED by reading the whole of that crate's source:
    /// the only three occurrences are the declaration, the default and the
    /// `Debug` impl. (russh 0.63 does compare it, and carries tests named for
    /// exactly this; gunnar is pinned to 0.61.2 through an exact `ssh-key`
    /// dependency, and a limit that works is not worth an SSH-stack bump to
    /// obtain.)
    ///
    /// So until 2026-09-11 a connection could offer keys without bound: a
    /// dictionary of public keys against the identity table, at
    /// `auth_rejection_time` apiece, on one TCP connection that never had to be
    /// re-established.
    auth_attempts: usize,
    /// **Set when this session ends** — by `Drop`, because russh drops the
    /// handler on every way a session ends (hang-up, unanswered keepalives,
    /// inactivity, protocol error, shutdown). Every transfer's writer watches
    /// it ([`SessionBound`]): russh's own writer parks on the SSH window and
    /// nothing wakes it when the session dies, which left a fetch to a dead
    /// client holding its fan worker and admission slot forever (cov-13
    /// finding 4, 2026-10-06).
    session_over: tokio::sync::watch::Sender<bool>,
}

impl Drop for Connection {
    fn drop(&mut self) {
        self.session_over.send_replace(true);
    }
}

/// Why a session that authenticated may no longer act.
///
/// Two variants and not a `bool`, for [`Control::principal_for_key`]'s reason:
/// "nobody holds this key any more" and "the identity table could not be read"
/// call for entirely different operator action, and both refuse.
#[derive(Debug)]
enum Stale {
    /// The key that opened this session no longer resolves to anyone, or
    /// resolves to somebody else. Revoked, expired, or re-registered.
    Revoked,
    /// The identity table could not be read. Refused, because failing open is
    /// not on the table — the same answer `auth_publickey` gives.
    Unreadable(gunnar_core::Error),
}

impl Connection {
    /// **Who this session may act as right now — asked again, per exec.**
    ///
    /// `auth_publickey` caches the principal, and until 2026-09-11 every exec
    /// on the connection was authorised out of that cache. Revocation
    /// therefore took effect immediately for a NEW connection and never for an
    /// open one: `DocRef::read` caches nothing, so the identity table was
    /// current the whole time and nothing asked it. A long-lived session — and
    /// git over SSH holds one open for as long as a client wants to keep
    /// pushing — outlived the credential that opened it, for as long as it
    /// liked. An operator who revokes a leaked key and sees the revocation take
    /// effect on their own next connection has every reason to believe it took
    /// effect everywhere.
    ///
    /// Cheap enough to do per exec: it is the same single
    /// `principal_by_fingerprint` lookup the connection already pays once at
    /// auth, and an exec is about to fork a git process and move a pack.
    ///
    /// A key that now belongs to a DIFFERENT identity is refused rather than
    /// adopted. This session authenticated as somebody; if the key has since
    /// been registered to somebody else, this is not that session, and
    /// continuing as the new holder would make re-registration a way to inherit
    /// an open connection.
    ///
    /// The anonymous path has no fingerprint — it authenticated with no key at
    /// all — so there is nothing to re-read, and `Principal::anonymous()` is not
    /// in the identity table to be revoked from. It keeps the cached value, and
    /// what anonymity may DO is still `Dispatch::authorise`'s answer.
    fn live_principal(&self) -> Result<Principal, Stale> {
        let Some(cached) = self.principal.clone() else {
            return Err(Stale::Revoked);
        };
        let Some(fingerprint) = self.key_fingerprint.as_ref() else {
            return Ok(cached);
        };
        match self
            .shared
            .dispatch
            .control()
            .principal_for_key(fingerprint)
        {
            Ok(Some(now)) if now.id == cached.id => Ok(now),
            Ok(_) => Err(Stale::Revoked),
            Err(err) => Err(Stale::Unreadable(err)),
        }
    }

    /// **Count a refused publickey offer, and say whether this connection has
    /// had its last one.**
    ///
    /// One place, called from every refusing arm of `auth_publickey`, so a new
    /// refusal reason cannot arrive uncounted — which is how a limit stops
    /// applying to exactly the case somebody added last.
    ///
    /// `0` is no limit, which is russh's own reading of the same field and the
    /// reading an operator who writes `0` expects.
    ///
    /// The `none` probe is deliberately NOT counted. Every OpenSSH client opens
    /// with one to learn the method list, so counting it would spend one of the
    /// six on the ordinary first packet of an ordinary session — and it carries
    /// no key, so it cannot be the dictionary attempt the limit is for.
    fn refused_auth(&mut self) -> bool {
        self.auth_attempts += 1;
        let max = self.shared.config_max_auth_attempts;
        max > 0 && self.auth_attempts >= max
    }

    /// The error that ends a connection which has offered too many keys.
    ///
    /// An `Err` out of a handler, because russh 0.61.2's `auth_publickey` is
    /// handed no session and no handle, so there is nothing to call
    /// `disconnect` on — and the run loop treating a handler error as the end
    /// of the session is exactly the outcome wanted. It is a `warn!`, not a
    /// `debug!`: one of these is a client with a full agent, and a hundred is
    /// somebody reading the identity table one key at a time.
    fn too_many_auth_attempts(&self) -> anyhow::Error {
        tracing::warn!(
            target: TARGET_SSH,
            event = "ssh.auth.too_many",
            attempts = self.auth_attempts,
            max = self.shared.config_max_auth_attempts,
            "disconnecting: too many refused publickey offers on one connection"
        );
        self.shared.metrics.add_connections_refused(1);
        anyhow::anyhow!(
            "too many authentication failures ({} refused publickey offers)",
            self.auth_attempts
        )
    }
}

impl Handler for Connection {
    type Error = anyhow::Error;

    /// **The anonymous read path.** Accept the `none` method for exactly
    /// one username, and refuse it for every other.
    ///
    /// The refusing branch is byte-for-byte what russh's default handler did
    /// before this method existed: `Auth::reject()`, which makes russh drop
    /// `MethodKind::None` from the advertised set and let the client proceed to
    /// publickey. So a client that does not ask for anonymity is on exactly the
    /// path it was on yesterday.
    ///
    /// The accepting branch does **not** consult the catalog, the repository or
    /// the ACL: it establishes *who* is asking (nobody), and *what nobody may
    /// do* is `Dispatch::authorise`'s answer, through
    /// [`AuthTable::may`](gunnar_core::AuthTable::may), like everyone else.
    /// Deciding here would be a second ACL.
    async fn auth_none(&mut self, user: &str) -> Result<Auth, Self::Error> {
        let span = self.span.clone();
        let _entered = span.enter();
        if !self.shared.allow_anonymous || user != ANONYMOUS_SSH_USER {
            // Not a refusal worth a `warn!`: EVERY OpenSSH client opens with a
            // `none` probe to learn the method list, so this is the ordinary
            // first packet of an ordinary authenticated session.
            tracing::debug!(
                target: TARGET_SSH,
                event = "ssh.auth.none.refused",
                reason = if self.shared.allow_anonymous {
                    "not-the-anonymous-user"
                } else {
                    "anonymous-access-disabled"
                },
                decorative_ssh_user = %user,
                "the none method is refused; publickey is the only way in"
            );
            return Ok(Auth::reject());
        }

        let anonymous = Principal::anonymous();
        span.record("principal", tracing::field::display(&anonymous.id));
        self.shared.metrics.add_connections_anonymous(1);
        tracing::info!(
            target: TARGET_SSH,
            event = "ssh.auth.anonymous",
            // Named so nobody later reads this line as "a key was accepted".
            // It is on `gunnar::ssh` at `info` because "who is reading my
            // public repositories" must be answerable from a production log.
            authenticated = false,
            "anonymous session accepted: no key, public repositories only"
        );
        self.principal = Some(anonymous);
        Ok(Auth::Accept)
    }

    async fn auth_publickey(
        &mut self,
        user: &str,
        public_key: &PublicKey,
    ) -> Result<Auth, Self::Error> {
        let span = self.span.clone();
        let _entered = span.enter();
        // Over the key's WIRE BLOB, not over its type: russh's `ssh-key` is
        // 0.7.0-rc.10 and `gunnar-core`'s is 0.6.7, so this is the only value
        // that can reach the identity table. It is byte-for-byte the
        // string `ssh-keygen -lf` prints for the same key.
        //
        // `None` means the key would not re-encode. That used to be an
        // `expect()`, a panic in the auth handler, over client-supplied bytes.
        // It is a refusal now; `fingerprint_of_key` has already
        // logged why.
        let Some(fingerprint) = fingerprint_of_key(public_key) else {
            let refusal = refuse_unencodable_key(&self.shared.metrics, user);
            if self.refused_auth() {
                return Err(self.too_many_auth_attempts());
            }
            return Ok(refusal);
        };
        let started = std::time::Instant::now();
        // `peer` is a field of the enclosing span from here down, so it is not
        // repeated on any line below (one implementation, and the whole point of the span).
        match self
            .shared
            .dispatch
            .control()
            .principal_for_key(&fingerprint)
        {
            Ok(Some(principal)) => {
                span.record("principal", tracing::field::display(&principal.id));
                self.shared.metrics.add_connections_accepted(1);
                tracing::info!(
                    target: TARGET_SSH,
                    event = "ssh.auth.accepted",
                    %fingerprint,
                    // Logged so an operator can see what was sent, and named so
                    // nobody later mistakes it for an input to the decision.
                    decorative_ssh_user = %user,
                    elapsed_ms = started.elapsed().as_millis() as u64,
                    "publickey accepted"
                );
                self.principal = Some(principal);
                // Kept, not recomputed and not dropped. This is the
                // value the identity table was probed with one line above, so
                // it is the key that authenticated, by construction.
                self.key_fingerprint = Some(fingerprint);
                Ok(Auth::Accept)
            }
            Ok(None) => {
                self.shared.metrics.add_connections_refused(1);
                tracing::warn!(
                    target: TARGET_SSH,
                    event = "ssh.auth.refused",
                    reason = "unknown-key",
                    %fingerprint,
                    decorative_ssh_user = %user,
                    elapsed_ms = started.elapsed().as_millis() as u64,
                    "publickey refused: no principal holds this key"
                );
                if self.refused_auth() {
                    return Err(self.too_many_auth_attempts());
                }
                Ok(Auth::reject())
            }
            // The key is still refused, since failing open is not on the table, but
            // this is a FAULT, not "unknown key", and the log has to say so.
            // An identity table that has become unreadable looks exactly like
            // an empty one from the client's side (the ACL model).
            Err(err) => {
                self.shared.metrics.add_connections_refused(1);
                self.shared.metrics.add_auth_faults(1);
                tracing::error!(
                    target: TARGET_SSH,
                    event = "ssh.auth.refused",
                    reason = "identity-table-unreadable",
                    %fingerprint,
                    decorative_ssh_user = %user,
                    elapsed_ms = started.elapsed().as_millis() as u64,
                    %err,
                    "publickey refused: the identity table could not be read"
                );
                if self.refused_auth() {
                    return Err(self.too_many_auth_attempts());
                }
                Ok(Auth::reject())
            }
        }
    }

    async fn channel_open_session(
        &mut self,
        channel: Channel<Msg>,
        // russh 0.63 (2026-10-03): the open is answered through this handle, not
        // a returned bool; dropping it unanswered would refuse the channel.
        reply: russh::server::ChannelOpenHandle,
        session: &mut Session,
    ) -> Result<(), Self::Error> {
        // The exec request arrives later, carrying only a `ChannelId`, and the
        // byte stream can only be taken from the `Channel` itself, so it is
        // kept here. russh's own sftp example does the same.
        self.channels.insert(
            channel.id(),
            OpenChannel {
                channel,
                git_protocol: None,
            },
        );

        // A session that authenticates, opens a channel and then does nothing is
        // not idle, because it answers keepalives, so the inactivity timeout never
        // fires and the connection would be held indefinitely. Arm a watchdog.
        if let Some(grace) = self.shared.exec_grace {
            let handle = session.handle();
            let exec_seen = self.exec_seen.clone();
            // `.instrument`, not a captured `peer`: a spawned task does NOT
            // inherit the thread-local span, so the watchdog's line would
            // otherwise be the one line in the whole connection that could not
            // be tied back to it.
            let span = self.span.clone();
            tokio::spawn(
                async move {
                    tokio::time::sleep(grace).await;
                    if !exec_seen.load(Ordering::SeqCst) {
                        tracing::info!(
                            target: TARGET_SSH,
                            event = "ssh.watchdog.disconnect",
                            ?grace,
                            "disconnecting: authenticated but never asked for a git command"
                        );
                        note_teardown(
                            "watchdog-disconnect",
                            handle
                                .disconnect(
                                    Disconnect::ByApplication,
                                    "no git command requested".to_string(),
                                    String::new(),
                                )
                                .await,
                        );
                    }
                }
                .instrument(span),
            );
        }
        reply.accept().await;
        Ok(())
    }

    async fn exec_request(
        &mut self,
        channel: ChannelId,
        data: &[u8],
        session: &mut Session,
    ) -> Result<(), Self::Error> {
        self.exec_seen.store(true, Ordering::SeqCst);
        let span = self.span.clone();
        let _entered = span.enter();

        // **The credential is re-read here, not remembered.** See
        // [`Connection::live_principal`]: russh will not dispatch an exec
        // before authentication succeeds, so an unauthenticated session is
        // unreachable rather than checked — but a session whose key was
        // REVOKED while it was open is entirely reachable, and until
        // 2026-09-11 it was authorised out of a cache filled at auth time.
        let principal = match self.live_principal() {
            Ok(principal) => principal,
            Err(stale) => {
                self.shared.metrics.add_exec_refused(1);
                let (reason, detail) = match &stale {
                    Stale::Revoked => ("key-revoked", String::new()),
                    Stale::Unreadable(err) => ("identity-table-unreadable", format!("{err}")),
                };
                tracing::warn!(
                    target: TARGET_SSH,
                    event = "ssh.exec.denied",
                    reason,
                    fingerprint = self.key_fingerprint.as_ref().map(tracing::field::display),
                    detail = %detail,
                    "exec denied: the key that opened this session no longer authorises it"
                );
                // Answered in git's own protocol, like every other denial on
                // this path: an `ERR ` pkt-line is what `git` prints verbatim
                // after `remote: `. A bare `channel_failure` here would put the
                // client back on "Could not read from remote repository", which
                // is the failure `report_error` was found unused for.
                session.channel_success(channel)?;
                session.data(channel, err_packet(REVOKED_MESSAGE)?)?;
                session.exit_status_request(channel, EXIT_DENIED)?;
                session.close(channel)?;
                // And the session goes with it. Refusing the one exec would
                // leave the connection open for the next one, which is the
                // finding restated a request later: a revoked key must not keep
                // a channel it can keep asking on.
                note_teardown(
                    "revoked-key-disconnect",
                    session
                        .handle()
                        .disconnect(
                            Disconnect::ByApplication,
                            "the key that opened this session no longer authorises it".to_string(),
                            String::new(),
                        )
                        .await,
                );
                return Ok(());
            }
        };

        // ── the operator's fire drill: ONE ERROR on purpose ─────────────
        //
        // What the estate's watch raises to prove its alert path end to end (estate-box
        // 8A). Held to server-wide Admin before it says anything; an anonymous session
        // is refused the channel like the tunnel verb below.
        if std::str::from_utf8(data).map(str::trim) == Ok(FIRE_DRILL_VERB) {
            if self.key_fingerprint.is_none() {
                tracing::warn!(target: TARGET_SSH, event = "ssh.exec.refused", reason = "anonymous-control-verb", "exec refused: {FIRE_DRILL_VERB} needs a key");
                session.channel_failure(channel)?;
                return Ok(());
            }
            let (exit, out) = match self.shared.dispatch.control().auth().may_server(&principal.id, gunnar_core::Level::Admin) {
                Ok(true) => {
                    tracing::error!(
                        target: TARGET_SSH,
                        event = "ssh.fire_drill",
                        principal = %principal.id,
                        "fire drill: {} asked for this ERROR to prove the alert path end to end — nothing is wrong",
                        principal.id
                    );
                    (0, "fire drill: one ERROR said on this server's log (nothing is wrong)\n".to_string())
                }
                Ok(false) => {
                    tracing::warn!(target: TARGET_SSH, event = "ssh.exec.denied", reason = "not-server-admin", principal = %principal.id, "{FIRE_DRILL_VERB} refused");
                    (EXIT_DENIED, format!("error: {FIRE_DRILL_VERB} needs server-wide Admin, which {} does not hold\n", principal.id))
                }
                Err(err) => (EXIT_DENIED, format!("error: the identity table could not be read: {err}\n")),
            };
            session.channel_success(channel)?;
            session.data(channel, out.into_bytes())?;
            session.exit_status_request(channel, exit)?;
            session.close(channel)?;
            return Ok(());
        }

        // ── git-lfs's fallback: answered, never a channel failure (2026-10-25) ──
        if std::str::from_utf8(data).ok().and_then(|l| l.split_whitespace().next()) == Some(LFS_AUTHENTICATE_VERB) {
            tracing::info!(
                target: TARGET_SSH,
                event = "ssh.lfs_authenticate.answered",
                principal = %principal.id,
                command = %String::from_utf8_lossy(data),
                "git-lfs asked for its HTTPS fallback: its pure-SSH transfer failed or was refused just before"
            );
            session.channel_success(channel)?;
            session.extended_data(channel, 1, LFS_AUTHENTICATE_MESSAGE.as_bytes().to_vec())?;
            session.exit_status_request(channel, 1)?;
            session.close(channel)?;
            return Ok(());
        }

        // ── who this key is (wiring tracer B 2026-10-08) ──
        if std::str::from_utf8(data).map(str::trim) == Ok(WHOAMI_VERB) {
            if self.key_fingerprint.is_none() {
                tracing::warn!(target: TARGET_SSH, event = "ssh.exec.refused", reason = "anonymous-control-verb", "exec refused: {WHOAMI_VERB} needs a key");
                session.channel_failure(channel)?;
                return Ok(());
            }
            session.channel_success(channel)?;
            session.data(channel, format!("{}\n", principal.id).into_bytes())?;
            session.exit_status_request(channel, 0)?;
            session.close(channel)?;
            return Ok(());
        }

        // ── a repository's settings (owner, 2026-10-14) ──
        //
        // Decided by the control plane's own `Repos` handlers through
        // [`RepoDoor`]: this listener only proves who asks (the key, re-read
        // above) and carries the answer. An anonymous session is refused the
        // channel, before the pause and the plan gates (not a transfer).
        if let Some(parsed) = parse_repo_verb(data) {
            let Some(fingerprint) = self.key_fingerprint.as_ref().map(|f| f.to_string()) else {
                tracing::warn!(target: TARGET_SSH, event = "ssh.exec.refused", reason = "anonymous-control-verb", "exec refused: {REPO_VERB} needs a key");
                session.channel_failure(channel)?;
                return Ok(());
            };
            let (exit, out) = match parsed {
                Err(why) => (1, format!("error: {why}\n")),
                Ok((repo, action)) => match self.shared.repo_door.clone() {
                    None => (
                        1,
                        "error: this server answers repository settings only on its control plane\n".to_string(),
                    ),
                    Some(door) => {
                        let ask = RepoAsk { principal: principal.id.clone(), fingerprint, repo: repo.clone(), action: action.clone() };
                        let answer = door(ask).await;
                        tracing::info!(
                            target: TARGET_SSH,
                            event = "ssh.control",
                            verb = REPO_VERB,
                            principal = %principal.id,
                            repo = %repo,
                            action = ?action,
                            decision = if answer.is_ok() { "allow" } else { "deny" },
                            "repository settings asked over the forge's door"
                        );
                        match answer {
                            Ok(said) => (0, if said.ends_with('\n') { said } else { format!("{said}\n") }),
                            Err(why) => (EXIT_DENIED, format!("error: {why}\n")),
                        }
                    }
                },
            };
            session.channel_success(channel)?;
            session.data(channel, out.into_bytes())?;
            session.exit_status_request(channel, exit)?;
            session.close(channel)?;
            return Ok(());
        }

        // ── a member's keys for an encrypted repository's ring (2026-10-06) ──
        //
        // A read of the identity table, held to the same rule as
        // `Repos.RecipientKeys` (see [`recipient_keys_answer`]). Before the
        // pause and the plan gates for the tunnel verb's reason: not a
        // transfer. An anonymous session is refused the channel.
        if let Some(parsed) = parse_recipient_keys_verb(data) {
            if self.key_fingerprint.is_none() {
                tracing::warn!(target: TARGET_SSH, event = "ssh.exec.refused", reason = "anonymous-control-verb", "exec refused: {RECIPIENT_KEYS_VERB} needs a key");
                session.channel_failure(channel)?;
                return Ok(());
            }
            let (exit, out) = match parsed {
                Err(why) => (1, format!("error: {why}\n")),
                Ok((repo, member)) => {
                    let (exit, out) = recipient_keys_answer(self.shared.dispatch.control(), &principal.id, &repo, &member);
                    tracing::info!(
                        target: TARGET_SSH,
                        event = "ssh.control",
                        verb = RECIPIENT_KEYS_VERB,
                        principal = %principal.id,
                        repo = %repo,
                        member = %member,
                        decision = if exit == 0 { "allow" } else { "deny" },
                        "recipient keys asked over the forge's door"
                    );
                    (exit, out)
                }
            };
            session.channel_success(channel)?;
            session.data(channel, out.into_bytes())?;
            session.exit_status_request(channel, exit)?;
            session.close(channel)?;
            return Ok(());
        }

        // ── the caller's own encryption key (CRYPT-YUBI 2026-10-26) ──────
        //
        // The session's principal reads or changes ITS OWN key and methods: the
        // public half, and wraps that are ciphertext to this server. Not a
        // transfer; an anonymous session is refused the channel.
        if let Some(parsed) = gunnar_crypt::door::parse_request(data) {
            if self.key_fingerprint.is_none() {
                tracing::warn!(target: TARGET_SSH, event = "ssh.exec.refused", reason = "anonymous-control-verb", "exec refused: {} needs a key", gunnar_crypt::door::VERB);
                session.channel_failure(channel)?;
                return Ok(());
            }
            let (exit, out) = match parsed {
                Err(why) => (1, format!("error: {why}\n")),
                Ok(request) => {
                    let verb = match &request {
                        gunnar_crypt::door::Request::Get => "get",
                        gunnar_crypt::door::Request::Create { .. } => "create",
                        gunnar_crypt::door::Request::Add(_) => "add",
                        gunnar_crypt::door::Request::Remove(_) => "remove",
                    };
                    let (exit, out) = user_key_answer(self.shared.dispatch.control(), &principal, request);
                    tracing::info!(
                        target: TARGET_SSH,
                        event = "ssh.control",
                        verb = gunnar_crypt::door::VERB,
                        action = verb,
                        principal = %principal.id,
                        decision = if exit == 0 { "allow" } else { "deny" },
                        "own encryption key over the forge's door"
                    );
                    (exit, out)
                }
            };
            session.channel_success(channel)?;
            session.data(channel, out.into_bytes())?;
            session.exit_status_request(channel, exit)?;
            session.close(channel)?;
            return Ok(());
        }

        // ── the ONE control verb: the tunnel address (T17) ─────────────
        //
        // Before the pause and the plan gates: those are about transfers, and
        // this is not one. Never through `Dispatch::authorise`, which knows
        // only git verbs. An anonymous session gets the channel refused like a
        // shell would; everyone else is held to server-wide Admin BEFORE the
        // door runs.
        if let Some(parsed) = parse_tunnel_address_verb(data) {
            if self.key_fingerprint.is_none() {
                tracing::warn!(target: TARGET_SSH, event = "ssh.exec.refused", reason = "anonymous-control-verb", "exec refused: {TUNNEL_ADDRESS_VERB} needs a key");
                session.channel_failure(channel)?;
                return Ok(());
            }
            let (exit, out) = match self
                .shared
                .dispatch
                .control()
                .auth()
                .may_server(&principal.id, gunnar_core::Level::Admin)
            {
                Ok(false) => {
                    tracing::warn!(target: TARGET_SSH, event = "ssh.exec.denied", reason = "not-server-admin", principal = %principal.id, "{TUNNEL_ADDRESS_VERB} refused");
                    (EXIT_DENIED, format!("error: {TUNNEL_ADDRESS_VERB} needs server-wide Admin, which {} does not hold\n", principal.id))
                }
                Err(err) => (EXIT_DENIED, format!("error: the identity table could not be read: {err}\n")),
                Ok(true) => match parsed {
                    Err(why) => (1, format!("error: {why}\n")),
                    Ok(address) => match &self.shared.tunnel_door {
                        None => (1, "error: this box has no WireGuard tunnel (built without wg-client)\n".to_string()),
                        Some(door) => match door(&address) {
                            Ok(answer) => {
                                tracing::warn!(target: TARGET_SSH, event = "ssh.control", verb = TUNNEL_ADDRESS_VERB, principal = %principal.id, address = %address, decision = "allow", "tunnel address door answered");
                                (0, if answer.ends_with('\n') { answer } else { format!("{answer}\n") })
                            }
                            Err(why) => {
                                tracing::warn!(target: TARGET_SSH, event = "ssh.control", verb = TUNNEL_ADDRESS_VERB, principal = %principal.id, address = %address, decision = "deny", reason = %why, "tunnel address door refused");
                                (1, format!("error: {why}\n"))
                            }
                        },
                    },
                },
            };
            session.channel_success(channel)?;
            session.data(channel, out.into_bytes())?;
            session.exit_status_request(channel, exit)?;
            session.close(channel)?;
            return Ok(());
        }

        // ── the PAUSED door, before the plan gates ──────────────────────
        //
        // MEASURED under KVM (bench R1, 2026-09-15): with the gate paused for
        // a growth and `/data` already unmounted, a push knocked, the plan
        // gates ran FIRST, and the disk-floor check statvfs'd the read-only
        // guard tmpfs under the mountpoint — the client was told "/data has
        // 64.0 KiB free … no push until space is reclaimed (`gunnar control
        // repo delete --purge`)". The wrong sentence, with advice to delete
        // repositories, on a box that is growing. The pause is the box's own
        // state and says nothing about any repository, so it is answered
        // before the command is even resolved: the same words and the same
        // EX_TEMPFAIL for every principal and every path.
        if let Some(pause) = self.shared.admission.paused() {
            self.shared.admission.note_refused_paused();
            tracing::info!(
                target: TARGET_GIT,
                event = "git.transfer.refused",
                reason = pause.reason(),
                command = %String::from_utf8_lossy(data),
                "transfer REFUSED: the admission gate is paused"
            );
            session.channel_success(channel)?;
            session.data(channel, err_packet(pause.words())?)?;
            session.exit_status_request(channel, EXIT_BUSY)?;
            session.close(channel)?;
            return Ok(());
        }

        let request =
            match self
                .shared
                .dispatch
                .authorise(&principal, self.key_fingerprint.as_ref(), data)
            {
                Ok(request) => request,
                Err(err) => {
                    self.shared.metrics.add_exec_refused(1);
                    // **THE counting point for a tenant's `auth_failures`**: a
                    // principal that authenticated and then held no grant on
                    // the repository it named.
                    //
                    // Only `Denied`, and deliberately only `Denied`. The other
                    // arms are a different sentence: `NoSuchRepo` hides a
                    // typo behind the same wire message on purpose and would
                    // charge a namespace that may not exist; `Standby` and
                    // `Plan` are the box and the plan refusing, not the
                    // credential; `Command` never named a repository at all.
                    // And the OTHER half of "authentication failed" — a key
                    // that resolves to nobody — happens before any exec line
                    // and belongs to no namespace, so it stays where it is, on
                    // the box's own `connections_refused`.
                    if let (DispatchError::Denied { repo, .. }, Some(flow)) =
                        (&err, self.shared.admission.flow())
                    {
                        flow.auth_failure(repo.namespace(), gunnar_core::now_ms());
                    }
                    let raw = String::from_utf8_lossy(data);
                    match err.client_message() {
                        // Not a git command at all: `bash`, `scp`, an empty
                        // string. Refuse the channel request itself; the client is
                        // not speaking a protocol that could read a reply.
                        // git-lfs asks SSH for its credentials (`git-lfs-authenticate`,
                        // `git-lfs-transfer`) before every transfer and goes to its
                        // https endpoint when refused: a client's known first step,
                        // said at INFO (RUN A 2026-10-08: seven a minute during one LFS
                        // push failed the log gate as WARN spam). Anything else stays WARN.
                        None if is_lfs_over_ssh(&raw) => {
                            tracing::info!(
                                target: TARGET_SSH,
                                event = "ssh.exec.refused",
                                reason = "lfs-over-ssh",
                                command = %raw,
                                "exec refused: git-lfs asks SSH first and uses its https endpoint"
                            );
                            session.channel_failure(channel)?;
                        }
                        None => {
                            tracing::warn!(
                                target: TARGET_SSH,
                                event = "ssh.exec.refused",
                                reason = "not-a-git-command",
                                command = %raw,
                                %err,
                                "exec refused"
                            );
                            session.channel_failure(channel)?;
                        }
                        // A git client asked for something it may not have. Accept
                        // the channel and answer in its own protocol, so it prints
                        // the reason instead of "Could not read from remote
                        // repository".
                        Some(message) => {
                            tracing::warn!(
                                target: TARGET_SSH,
                                event = "ssh.exec.denied",
                                // The distinction the *wire* deliberately hides:
                                // "no such repository" and "no permission" are one
                                // string to the client so a caller cannot enumerate
                                // private repositories. The log keeps it.
                                reason = match &err {
                                    DispatchError::NoSuchRepo(_) => "no-such-repository",
                                    DispatchError::Denied { .. } => "no-grant",
                                    DispatchError::Standby { .. } => "standby-read-only",
                                    DispatchError::Twin { .. } => "twin-serves-no-git",
                                    DispatchError::AnonymousElsewhere { .. } => {
                                        "anonymous-elsewhere"
                                    }
                                    DispatchError::Plan { .. } => "gate-refused",
                                    DispatchError::Store(_) => "control-plane-unavailable",
                                    DispatchError::Command(_) => "not-a-git-command",
                                },
                                command = %raw,
                                %err,
                                "exec denied"
                            );
                            session.channel_success(channel)?;
                            session.data(channel, err_packet(&message)?)?;
                            session.exit_status_request(channel, EXIT_DENIED)?;
                            session.close(channel)?;
                        }
                    }
                    return Ok(());
                }
            };

        let Some(open) = self.channels.remove(&channel) else {
            // The CLIENT's misuse (a second exec on one channel, or a channel never
            // opened): refused, said at WARN once per connection — any caller that may
            // run one git command could otherwise raise the server's ERROR at will.
            if std::mem::replace(&mut self.misuse_said, true) {
                tracing::debug!(target: TARGET_SSH, ?channel, "exec request for a channel that is not open (said already on this connection)");
            } else {
                tracing::warn!(
                    target: TARGET_SSH,
                    event = "ssh.exec.misuse",
                    ?channel,
                    "exec request for a channel that is not open (a second exec on one channel, or one never opened) — refused; said once per connection"
                );
            }
            session.channel_failure(channel)?;
            return Ok(());
        };

        // The repository is known from here on, so it goes on the CONNECTION
        // span: every line the transfer emits underneath inherits it, and the
        // "which repository was that connection touching" question is answered
        // even for a line that has nothing to do with git.
        span.record("repo", tracing::field::display(&request.repo));

        // Attached *after* the decision above, never before it: an environment
        // variable selects the framing of the answer and nothing else.
        let request = request.with_git_protocol(open.git_protocol);

        // ── the explicit ceiling ───────────────────────────────────────────
        //
        // After authorisation, deliberately. "The server is busy" is a fact
        // about the server, and telling it to a client that may not touch this
        // repository at all would leak that the repository exists. The order
        // also means the gate meters *transfers gunnar was going to serve*,
        // which is what the counter is supposed to mean.
        //
        // It refuses rather than queues; `crate::admission` sets out why at
        // length. In one line: a git client retries, and a fast refusal with a
        // sentence in it beats a socket that goes quiet while still holding the
        // session, the channel and a slot.
        // The class the governor meters this operation as. `git-upload-pack` is
        // clone, fetch AND ls-remote on the wire and cannot be told apart before
        // the stream is open, which is *after* this decision by design; see
        // `OpClass::for_ssh_service` for what that costs and why the middle
        // class is the right guess.
        // ── the BOOT WINDOW door, before admission ─────────────────────────
        //
        // After the repository is known and authorised, so a stranger cannot
        // learn from this whether a repository exists, and before a slot is
        // taken, so a boot does not spend its gate on requests it cannot serve.
        // See `GunnarSsh::with_readiness` for what was measured.
        // A KEYED caller is queued for the stores to open, up to its keyed
        // wait: a restart (a release, an upgrade) lasts seconds, and git-lfs's
        // pure-SSH transfer cannot retry a refusal — it falls back to
        // `git-lfs-authenticate` and fails the push (gunnar.rs 2026-10-25). A
        // stranger is still answered at once.
        if !self.shared.ready.load(std::sync::atomic::Ordering::Relaxed)
            && request.principal.id != gunnar_core::ANONYMOUS_PRINCIPAL_ID
        {
            let until = std::time::Instant::now() + self.shared.admission.wait_for(&request.principal.id);
            while !self.shared.ready.load(std::sync::atomic::Ordering::Relaxed) && std::time::Instant::now() < until {
                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            }
        }
        if !self.shared.ready.load(std::sync::atomic::Ordering::Relaxed) {
            tracing::info!(
                target: TARGET_GIT,
                event = "git.transfer.refused",
                reason = "starting",
                service = %request.service,
                "transfer REFUSED: the stores are still opening after a restart"
            );
            session.channel_success(channel)?;
            session.data(channel, err_packet(STARTING_MESSAGE)?)?;
            session.exit_status_request(channel, EXIT_BUSY)?;
            session.close(channel)?;
            return Ok(());
        }

        let class = OpClass::for_ssh_service(request.service);
        // `admit_within`, not `try_admit`: over the limit the transfer parks for
        // a bounded moment instead of being refused on the spot. A refused
        // client reconnects, and a reconnect is a whole SSH handshake — more
        // than the wait costs. `crate::governor::DEFAULT_ADMISSION_WAIT` has the
        // measurement; `--admission-wait-ms 0` is the old behaviour exactly.
        let admitted = match self
            .shared
            .admission
            .admit_within(&request.principal.id, &request.repo.namespace, class)
            .await
        {
            Ok((guard, waited)) => {
                // AGGREGATE, at most once a second. A row per waiting client is
                // the appliance's whole twenty-row console under load (the
                // measured 5411 in one 256-client run); a row per second
                // carrying the totals is the same fact, readable.
                if !waited.is_zero() && self.shared.admission.wait_row_due() {
                    let stats = self.shared.admission.stats();
                    tracing::info!(
                        target: TARGET_GIT,
                        event = "git.transfer.waited",
                        class = class.name(),
                        waited_ms = waited.as_millis() as u64,
                        waited_total = stats.admitted_after_wait,
                        mean_wait_ms = stats.mean_wait_ms(),
                        peak_wait_ms = stats.peak_wait_ms,
                        in_flight = stats.in_flight,
                        limit = stats.limit,
                        "transfers are WAITING for a slot and are then served: {} so far, mean \
                         {} ms, worst {} ms against a bound of {} ms",
                        stats.admitted_after_wait,
                        stats.mean_wait_ms(),
                        stats.peak_wait_ms,
                        self.shared.admission.wait().as_millis() as u64
                    );
                }
                guard
            }
            Err(refusal) => {
                let stats = self.shared.admission.stats();
                tracing::warn!(
                    target: TARGET_GIT,
                    event = "git.transfer.refused",
                    // Which gate, not just "a gate": the anonymous ceiling
                    // fires with the box nearly empty, and a line that
                    // still said `admission-gate-full` there would send an
                    // operator to raise a limit that was never reached.
                    reason = refusal.reason(),
                    service = %request.service,
                    class = class.name(),
                    %refusal,
                    in_flight = stats.in_flight,
                    peak_in_flight = stats.peak_in_flight,
                    // The governed limit, so a log line says what was actually
                    // in force rather than what was configured. Without it the
                    // shed is invisible again.
                    limit = stats.limit,
                    reserved_bytes = stats.reserved_bytes,
                    refused_total = stats.refused(),
                    // The bound the transfer waited out before this. Without it
                    // a reader cannot tell an instant refusal from one the
                    // server spent two seconds trying to avoid.
                    waited_ms = self.shared.admission.wait().as_millis() as u64,
                    peak_wait_ms = stats.peak_wait_ms,
                    "transfer REFUSED by the admission gate"
                );
                // Answered in the client's own protocol, like a denial, so git
                // prints the reason instead of "Could not read from remote
                // repository". Saturation the operator can see and the user
                // cannot is only half a fix.
                session.channel_success(channel)?;
                session.data(channel, err_packet(&refusal.client_message())?)?;
                session.exit_status_request(channel, EXIT_BUSY)?;
                session.close(channel)?;
                return Ok(());
            }
        };

        // ── the span the whole transfer runs under ─────────────────────────
        //
        // A CHILD of `ssh.connection`, so it inherits `conn`, `peer`,
        // `principal` and `repo` and states none of them again. `service` is
        // the one thing that is new. Everything `gunnar-cli`'s transport and
        // `gunnar-policy`'s gate emit lands underneath it, in the same
        // process, without either of them being handed an id to repeat.
        let transfer = tracing::info_span!(
            target: TARGET_GIT,
            "git.transfer",
            service = %request.service,
            access = %request.access,
        );
        transfer.in_scope(|| {
            tracing::info!(
                target: TARGET_GIT,
                event = "git.transfer.started",
                git_protocol = ?request.git_protocol,
                "serving"
            )
        });
        let in_flight = self.shared.metrics.transfer_started();
        let metrics = Arc::clone(&self.shared.metrics);
        let started = std::time::Instant::now();

        session.channel_success(channel)?;

        let transport = self.shared.transport.clone();
        // Split, NOT `into_stream()`. `into_stream` wraps the channel in
        // russh's `ChannelCloseOnDrop`, which spawns a `Close` the instant the
        // transport lets the stream go, and that `Close` raced (and beat) the
        // `exit-status` sent next, which is how a successful push came to
        // report failure. Neither half closes the channel on drop, so the two
        // messages below are ordered by the sender's own queue.
        let (read_half, write_half) = open.channel.split();
        // METERED, so the memory ledger learns this transfer's real size as it
        // happens rather than being charged a flat per-class constant at
        // admission. `crate::admission::Metered` is the only place a byte count
        // reaches the governor, and it wraps the duplex the transport was
        // already going to be handed — no second copy, no second truth.
        let admitted = Arc::new(admitted);
        let stream = crate::admission::Metered::new(
            tokio::io::join(
                ChannelReader::new(read_half),
                // Bound to the session: a write parked on the SSH window ends
                // with an error when the session does (see `SessionBound`).
                SessionBound::new(write_half.make_writer(), self.session_over.subscribe()),
            ),
            Arc::clone(&admitted),
        );
        // Spawned, not awaited: see the module docs. Awaiting here would stop
        // the session loop that has to feed this very stream.
        // ── THE STANDING FAN, not a fresh thread ────────────────────────
        //
        // This used to be `tokio::spawn` alone, and the task itself was never
        // the cost — tasks are cheap. The cost is behind it: `SyncIoBridge`
        // hands the transfer to tokio's BLOCKING pool, which spawns an OS
        // thread on demand, per operation, up to 512 of them. That is
        // per-request initialisation, and it is what the fans replace.
        //
        // The future is driven by `Handle::block_on` on a worker that was
        // already alive and parked before this client connected. A full queue
        // refuses here, which is the only place a refusal is free.
        let handle = tokio::runtime::Handle::current();
        let pipelines = crate::pipeline::fans();
        let over = self.session_over.subscribe();
        let (calm_grace, crowded_grace) = self.shared.session_end_grace;
        let body = async move {
            // ── the CoDel dequeue ──────────────────────────────────────
            //
            // The FIRST line of the task, deliberately. Everything between
            // `try_admit` above and this point is the transfer WAITING:
            // tokio's ready queue, and behind it the blocking-pool handoff
            // that `SyncIoBridge` needs before a single byte moves. That
            // wait is the queue the record called invisible, and this call is
            // what makes the governor able to see it. Measured here rather
            // than at the end because sojourn is wait time; service time
            // filed as sojourn would make every large clone look like a
            // standing queue.
            admitted.entered_service();
            // ★ The WHOLE transfer is bound to the session, not only its writes
            // (`SessionBound`): a client that goes silent while main is still
            // building the pack has no write parked on the window to wake, and
            // the build can take minutes (the UpCloud mockup's LD1/LD2,
            // 2026-10-09: 2 min 10 s on TCG). When the session ends — the
            // keepalives unanswered, a hang-up — the transfer ends with it and
            // gives back its fan worker, admission slot and store handle.
            let cancel = request.cancel.clone();
            let served = serve_until_session_ends(transport.serve(request, Box::new(stream)), over.clone(), &cancel, || {
                // Stinky row 19 (2026-10-10): a hung-up client's worker is one
                // a queued client waits for, so the grace is short when any do.
                crate::channel::grace_for(calm_grace, crowded_grace, pipelines.queued(class))
            }, || {
                crate::seam::TransportError::Io(session_ended_error())
            })
            .await;
            let status = match served {
                Ok(()) => 0,
                Err(err) => {
                    metrics.add_transfers_failed(1);
                    // ── the refusal the client used to never hear ───────
                    //
                    // Until 2026-08-05 this arm logged the whole reason and
                    // sent the client an exit status and nothing else, so
                    // every post-authorisation refusal — the repository's
                    // store lock held by a `gunnar gc`, a storage fault on
                    // open, an unwired service — reached the user as
                    // `fatal: the remote end hung up unexpectedly`. The two
                    // gates ABOVE this one, in this same function, both
                    // answer in the client's own protocol; this one did not,
                    // and the asymmetry is what made it invisible.
                    //
                    // `client_message()` is `None` whenever bytes may
                    // already have gone out, so this cannot append a
                    // pkt-line to a half-written pack — see
                    // `TransportError::client_message`.
                    let told = err.client_message();
                    tracing::warn!(
                        target: TARGET_GIT,
                        event = "git.transfer.failed",
                        %err,
                        // Whether the user was given a reason, said in the
                        // log, because "the client was told" and "the client
                        // saw a dead socket" must not be the same line.
                        client_told = told.is_some(),
                        "transport ended with an error"
                    );
                    if let Some(message) = told {
                        match err_packet(&message) {
                            Ok(packet) => {
                                // Raced against the session's end: `data_bytes`
                                // waits for SSH window like the stream does.
                                let sent = tokio::select! {
                                    sent = write_half.data_bytes(packet) => sent,
                                    () = session_over(over.clone()) => Err(russh::Error::IO(session_ended_error())),
                                };
                                note_teardown("refusal-packet", sent)
                            }
                            Err(err) => tracing::error!(
                                target: TARGET_GIT,
                                %err,
                                "the refusal could not be encoded, so the client is \
                                 getting only an exit status"
                            ),
                        }
                    }
                    EXIT_TRANSPORT_FAILED
                }
            };
            // The channel is still open here, nothing has been dropped that
            // could have closed it, so the status arrives before the close,
            // through the same sender the data went through.
            if write_half.exit_status(status).await.is_err() {
                // WARN only when the client missed a verdict it needed. A
                // client that took everything it asked for and hung up
                // before the `exit-status` has lost nothing — it is how
                // `ls-remote` and `fetch` end — and warning about it made
                // `grep -i error` useless on a completely healthy server:
                // MEASURED 2026-08-06, 9 successful transfers, 9 of these.
                // A client that missed a NON-ZERO status did lose
                // something: it believes the transfer worked.
                if status == 0 {
                    tracing::debug!(
                        target: TARGET_GIT,
                        event = "git.exit_status.undelivered",
                        ?channel,
                        status,
                        "the client hung up before the exit status; it had already \
                         been served"
                    );
                } else {
                    tracing::warn!(
                        target: TARGET_GIT,
                        event = "git.exit_status.undelivered",
                        ?channel,
                        status,
                        "the client was gone before a NON-ZERO exit status, so it \
                         does not know this transfer failed"
                    );
                }
            }
            note_teardown("channel-close", write_half.close().await);
            // The duration an operator asked "why was that clone slow"
            // about: the WHOLE transfer, from admission to the last byte
            // acknowledged, not the state machine's own view of itself.
            tracing::info!(
                target: TARGET_GIT,
                event = "git.transfer.finished",
                status,
                elapsed_ms = started.elapsed().as_millis() as u64,
                "transfer finished"
            );
            // Moved into this task and dropped here, so the slot is held for the
            // whole transfer and released by `Drop` rather than by a call that
            // an early return could skip. The in-flight gauge is released the
            // same way, and for the same reason.
            drop(admitted);
            drop(in_flight);
        }
        .instrument(transfer);

        // ── WHAT THE FAN IS ACTUALLY CARRYING ───────────────────────────────
        //
        // `Pipelines` has counted `served`, `queued` and `workers` since it was
        // written and NOTHING reported them, so the only evidence the fans were
        // doing anything was the absence of refusals — which is not evidence,
        // it is silence. Asked "is the queue filling", the honest answer was an
        // inference from the workload's shape.
        //
        // `submit` already returns the queue depth after the push, so this
        // costs one integer. Emitted only when an operation ACTUALLY QUEUED
        // (depth > 1, i.e. it did not go straight to a free worker), because a
        // line per transfer on a 102-client arm is noise that hides the signal.
        // `served` and `workers` ride along so one line answers "how deep, out
        // of how many, having done how much".
        match pipelines.submit(
            class,
            Box::new(move || {
                handle.block_on(body);
            }),
        ) {
            Ok(depth) if depth > 1 => tracing::info!(
                target: TARGET_GIT,
                event = "git.pipeline.queued",
                class = ?class,
                depth,
                workers = pipelines.workers(class),
                served = pipelines.served(class),
                "an operation waited for a worker"
            ),
            Ok(_) => {}
            Err(refused) => {
                // The fan is saturated. Say so in the client's own protocol
                // rather than dropping the channel — a dead socket is how a
                // refusal becomes "the remote end hung up unexpectedly".
                tracing::warn!(
                    target: TARGET_GIT,
                    event = "git.transfer.refused",
                    class = ?class,
                    depth = pipelines.queued(class),
                    workers = pipelines.workers(class),
                    served = pipelines.served(class),
                    %refused,
                    "the standing fan for this class refused the operation"
                );
                return Err(anyhow::anyhow!("{refused}"));
            }
        }
        Ok(())
    }

    // ── everything below is the "no shell, ever" half ──────────────────────
    //
    // russh's defaults for these return `Ok(())` **without** answering the
    // channel request, which leaves a client waiting rather than failing. Each
    // one is answered explicitly.

    async fn shell_request(
        &mut self,
        channel: ChannelId,
        session: &mut Session,
    ) -> Result<(), Self::Error> {
        self.refuse(channel, session, "shell").await
    }

    async fn subsystem_request(
        &mut self,
        channel: ChannelId,
        name: &str,
        session: &mut Session,
    ) -> Result<(), Self::Error> {
        // Includes `sftp`. gunnar serves git and nothing else.
        self.span.in_scope(|| {
            tracing::warn!(
                target: TARGET_SSH,
                event = "ssh.request.refused",
                subsystem = %name,
                "subsystem refused"
            )
        });
        self.refuse(channel, session, "subsystem").await
    }

    async fn pty_request(
        &mut self,
        channel: ChannelId,
        _term: &str,
        _col_width: u32,
        _row_height: u32,
        _pix_width: u32,
        _pix_height: u32,
        _modes: &[(russh::Pty, u32)],
        session: &mut Session,
    ) -> Result<(), Self::Error> {
        self.refuse(channel, session, "pty").await
    }

    async fn x11_request(
        &mut self,
        channel: ChannelId,
        _single_connection: bool,
        _x11_auth_protocol: &str,
        _x11_auth_cookie: &str,
        _x11_screen_number: u32,
        session: &mut Session,
    ) -> Result<(), Self::Error> {
        self.refuse(channel, session, "x11").await
    }

    async fn env_request(
        &mut self,
        channel: ChannelId,
        variable_name: &str,
        variable_value: &str,
        session: &mut Session,
    ) -> Result<(), Self::Error> {
        // An ALLOWLIST, not a filter: everything that is not named here is
        // refused, so adding a variable is a deliberate edit to one array and
        // the default for anything new is "no". See the module docs for why an
        // SSH server that passes an environment through is an attack surface.
        let span = self.span.clone();
        let _entered = span.enter();
        if !ENV_ALLOWLIST.contains(&variable_name) {
            // Same refusal, same event, same fields — two levels. See
            // [`ENV_ROUTINE`] for the 406-of-406 measurement that split them.
            if env_refusal_is_routine(variable_name) {
                tracing::debug!(
                    target: TARGET_SSH,
                    event = "ssh.env.refused",
                    reason = "not-allowlisted",
                    routine = true,
                    variable = %variable_name,
                    "env refused: gunnar reads exactly one environment variable"
                );
            } else {
                tracing::warn!(
                    target: TARGET_SSH,
                    event = "ssh.env.refused",
                    reason = "not-allowlisted",
                    routine = false,
                    variable = %variable_name,
                    "env refused: gunnar reads exactly one environment variable"
                );
            }
            session.channel_failure(channel)?;
            return Ok(());
        }

        // A value gunnar will not read is not worth holding. `version=2` is
        // nine bytes; the cap is generous and exists so a client cannot make
        // the server keep an unbounded string per channel.
        if variable_value.len() > MAX_ENV_VALUE {
            tracing::warn!(
                target: TARGET_SSH,
                event = "ssh.env.refused",
                reason = "value-too-long",
                variable = %variable_name,
                length = variable_value.len(),
                "env refused: the value is implausibly long"
            );
            session.channel_failure(channel)?;
            return Ok(());
        }

        let Some(open) = self.channels.get_mut(&channel) else {
            tracing::warn!(
                target: TARGET_SSH,
                ?channel,
                "env request for a channel that was never opened"
            );
            session.channel_failure(channel)?;
            return Ok(());
        };
        if variable_name != ENV_GIT_PROTOCOL {
            // `ENV_ALLOWLIST` grew a name and nothing here was taught to carry
            // it. Fail closed and say so, rather than quietly filing an unknown
            // variable in the `GIT_PROTOCOL` slot.
            tracing::error!(
                target: TARGET_SSH,
                variable = %variable_name,
                "env allowlisted but not carried anywhere; refusing"
            );
            session.channel_failure(channel)?;
            return Ok(());
        }
        tracing::debug!(
            target: TARGET_SSH,
            variable = %variable_name,
            value = %variable_value,
            "env accepted"
        );
        open.git_protocol = Some(variable_value.to_string());
        session.channel_success(channel)?;
        Ok(())
    }

    async fn channel_close(
        &mut self,
        channel: ChannelId,
        _session: &mut Session,
    ) -> Result<(), Self::Error> {
        self.channels.remove(&channel);
        Ok(())
    }
}

impl Connection {
    async fn refuse(
        &mut self,
        channel: ChannelId,
        session: &mut Session,
        what: &'static str,
    ) -> Result<(), anyhow::Error> {
        self.span.in_scope(|| {
            tracing::warn!(
                target: TARGET_SSH,
                event = "ssh.request.refused",
                request = what,
                "refused: gunnar has no shell"
            )
        });
        session.channel_failure(channel)?;
        Ok(())
    }
}

/// The session loop ended: say so in words an operator's `grep -i error` will
/// not find, unless it really was an error.
///
/// See [`peer_hung_up`]. `error=early eof` fired on **every healthy fetch**
/// before this existed.
fn note_session_end(error: &anyhow::Error) {
    if peer_hung_up(error.as_ref()) {
        tracing::debug!(
            target: TARGET_SSH,
            event = "ssh.session.closed",
            reason = "peer-hung-up",
            "the client closed the connection"
        );
        return;
    }
    tracing::debug!(target: TARGET_SSH, %error, "ssh session ended with an error");
}

/// Note that a best-effort teardown step did not work.
///
/// # Best-effort stays best-effort. What changes is that it stops being silent
///
/// Closing a channel and disconnecting a watchdogged session are both allowed
/// to fail: the peer may already be gone, which is the ordinary case and not
/// worth an operator's attention. Neither ever became an error, and neither
/// should. But a **systemic** failure to tear sessions down, from descriptor
/// exhaustion, the failure mode the unbounded handle cache used to
/// produce, was previously indistinguishable from a quiet server, because
/// `let _ =` leaves nothing behind at any level.
///
/// `debug!` rather than `warn!`: one of these is normal and a thousand is not,
/// and the thing that tells them apart is a count in a journal, not a severity
/// on a line that fires every time a client hangs up first.
/// The one encoder for a client-visible refusal: `ERR <message>` as a pkt-line.
///
/// Three call sites now answer a refusal in the client's own protocol — the
/// dispatch denial, the admission gate and a transfer refused before its first
/// byte — and a fourth is a matter of time. One implementation: the framing is written once,
/// so a refusal cannot acquire a subtly different shape depending on which gate
/// produced it. `ERR` is git's own out-of-band error line, which every git
/// version since 1.6 prints verbatim instead of "Could not read from remote
/// repository".
fn err_packet(message: &str) -> anyhow::Result<Vec<u8>> {
    let mut packet = Vec::new();
    gunnar_pktline::write_text(&mut packet, format!("ERR {message}").as_bytes())
        .map_err(|e| anyhow::anyhow!("encoding ERR packet: {e}"))?;
    Ok(packet)
}

///
/// # …and "the peer is already gone" is not a failure at all
///
/// Closing a channel whose peer has already hung up returns
/// `russh::Error::SendError`, and until 2026-08-06 that was logged as
/// `ssh.teardown.failed err=Channel send error` on **every healthy transfer**
/// (MEASURED that day: 9 successful transfers, 6 of these). It is the same
/// fact `handle_session_error` and the undelivered exit status already report,
/// counted a third time in the third set of words with "err" in it. It is
/// separated here by [`peer_hung_up`] so the systemic case this function exists
/// for — descriptor exhaustion, a wedged sender — is still the only thing that
/// says `failed`.
fn note_teardown<E: std::error::Error + 'static>(step: &'static str, result: Result<(), E>) {
    if let Err(err) = result {
        if peer_hung_up(&err) {
            tracing::debug!(
                target: TARGET_SSH,
                event = "ssh.teardown.peer_gone",
                step,
                "the peer had already gone, so this teardown step had nothing to say \
                 it to"
            );
            return;
        }
        tracing::debug!(
            target: TARGET_SSH,
            event = "ssh.teardown.failed",
            step,
            %err,
            "a session teardown step did not complete"
        );
    }
}

/// **Is this failure just "the peer hung up first"?**
///
/// The one classifier for that question (one implementation). Three places used to answer it
/// independently, and all three answered *"no"*, which is why a completely
/// healthy `gunnar ls-remote` left this in the journal:
///
/// ```text
///   DEBUG ssh session ended with an error   error=early eof
///   WARN  the client was gone before the exit status  channel=ChannelId(2) status=0
///   DEBUG ssh.teardown.failed  step="channel-close"  err=Channel send error
///   INFO  transfer finished  status=0  elapsed_ms=106
/// ```
///
/// MEASURED on the reference desktop 2026-08-06 from the live server's own journal, at
/// `10:55:10`, for a transfer that succeeded. Nothing was damaged — `status=0`,
/// `transfer finished` — but three lines carrying `error`, `err` and `failed`
/// per healthy call means `grep -i error` finds only noise, and that is the
/// first command an operator runs.
///
/// # Classified on the cause, never on the message text
///
/// A `contains("early eof")` would be a guard that silently stops matching the
/// day tokio rewords its `read_exact`, and the failure would be invisible
/// because it fails in the *quiet* direction — back to noise, not to a crash.
/// So this walks the source chain and matches concrete things:
/// `io::ErrorKind`, and russh's own named variants. `early eof` is
/// `ErrorKind::UnexpectedEof` (tokio's `read_exact`) and `Channel send error`
/// is `russh::Error::SendError`; neither string appears below.
///
/// # What it deliberately does NOT swallow
///
/// Only the socket going away. A key exchange failure, a MAC failure, a
/// protocol desync, a decryption failure — every one of those is still an error
/// and still logged as one. `tests/teardown_noise.rs` asserts both directions,
/// because a classifier that answered `true` for everything would produce a
/// beautifully quiet journal for a server that was on fire.
fn peer_hung_up(err: &(dyn std::error::Error + 'static)) -> bool {
    use std::io::ErrorKind;

    let mut cause: Option<&(dyn std::error::Error + 'static)> = Some(err);
    while let Some(e) = cause {
        if let Some(io) = e.downcast_ref::<std::io::Error>() {
            if matches!(
                io.kind(),
                ErrorKind::UnexpectedEof
                    | ErrorKind::BrokenPipe
                    | ErrorKind::ConnectionReset
                    | ErrorKind::ConnectionAborted
                    | ErrorKind::NotConnected
            ) {
                return true;
            }
        }
        if let Some(r) = e.downcast_ref::<russh::Error>() {
            if matches!(
                r,
                // The channel's sender is gone: nothing left to send to.
                russh::Error::SendError
                    // russh's own names for a hung-up peer.
                    | russh::Error::HUP
                    | russh::Error::Disconnect
            ) {
                return true;
            }
        }
        cause = e.source();
    }
    false
}

/// Refuse a key that would not re-encode.
///
/// A free function taking only the counters, so the decision this makes (a
/// **rejection**, and a counted one) can be asserted without standing up a
/// russh session. The alternative, an `expect()`, aborted the auth handler.
///
/// `auth_faults` is deliberately **not** moved: that counter means "the
/// identity table could not be read", and this key never reached it. The `warn`
/// [`crate::access::fingerprint_of_key`] emits carries
/// `reason = "key-does-not-re-encode"`, which is what tells the two apart.
fn refuse_unencodable_key(metrics: &gunnar_core::observe::ServerMetrics, user: &str) -> Auth {
    metrics.add_connections_refused(1);
    tracing::warn!(
        target: TARGET_SSH,
        event = "ssh.auth.refused",
        reason = "key-does-not-re-encode",
        decorative_ssh_user = %user,
        "publickey refused: the offered key did not re-encode"
    );
    Auth::reject()
}

/// The one environment variable a git client may send: how it asks for
/// protocol v2 over SSH.
pub const ENV_GIT_PROTOCOL: &str = "GIT_PROTOCOL";

/// **Every** environment variable this server accepts from a client.
///
/// An allowlist, checked by `env_request`. `LD_PRELOAD`, `PATH`, `GIT_DIR` and
/// everything else a client might try is refused with a channel failure, the
/// same answer this server gave to *all* environment requests before
/// [`ENV_GIT_PROTOCOL`] was needed. Nothing here is ever executed, exported to
/// a process or consulted by the grant check; gunnar has no shell and spawns
/// nothing, so the only reason an accepted name exists is that the *wire* reads
/// it.
pub const ENV_ALLOWLIST: [&str; 1] = [ENV_GIT_PROTOCOL];

/// The refused names that mean **nothing at all**, because OpenSSH sends them
/// on its own without being asked.
///
/// Still refused — [`ENV_ALLOWLIST`] is unchanged and this list grants nothing.
/// What it changes is the *level* the refusal is reported at, and the reason it
/// has to exist is a measurement.
///
/// MEASURED on the reference desktop 2026-08-05, an 18-repository ingest over real SSH with stock
/// git 2.53.0 as the client, 203 connections, `RUST_LOG=info`:
///
/// | WARN lines | of which `ssh.env.refused` for `LANG`/`COLORTERM` |
/// |---|---|
/// | 406 | **406 (100%)** |
///
/// Zero warnings of any other kind were emitted in the whole run. OpenSSH's
/// shipped `ssh_config` carries `SendEnv LANG LC_*`, and desktop terminals add
/// `COLORTERM`, so every `git` over `ssh` produces two of these before it has
/// asked for anything. An operator who greps for `WARN` on a live gunnar
/// therefore reads noise at a 100% false-positive rate and will not see the
/// first real one — which is the same disease as a check that cannot go red,
/// wearing the other colour.
///
/// A client naming something NOT on this list is a different event and keeps
/// its `warn`: `LD_PRELOAD`, `PATH`, `GIT_DIR`, `GIT_ALTERNATE_OBJECT_DIRECTORIES`
/// are what an attacker tries, and nothing sends them by accident.
pub const ENV_ROUTINE: [&str; 4] = ["LANG", "LANGUAGE", "COLORTERM", "TERM"];

/// Whether `name` is a routine refusal ([`ENV_ROUTINE`], or any `LC_*`, which
/// OpenSSH sends as a glob).
pub fn env_refusal_is_routine(name: &str) -> bool {
    ENV_ROUTINE.contains(&name) || name.starts_with("LC_")
}

/// The longest environment value the server will hold.
///
/// `version=2` is nine bytes. This is a bound on what one channel can make the
/// server remember, not a syntax check; the grammar is `gunnar-wire`'s.
pub const MAX_ENV_VALUE: usize = 256;

/// Exit status reported when access was refused. Matches what `git` itself
/// reports for a failed remote helper.
pub const EXIT_DENIED: u32 = 128;

/// **What a client is told when the key that opened its session stopped
/// authorising it.**
///
/// One string, named here rather than spelled at the refusal site, so the test
/// that asserts what reaches the client reads the same constant the server
/// sends. It says what happened and what to do, because "denied" on a
/// connection that worked a second ago is otherwise indistinguishable from the
/// server having broken.
///
/// It does NOT distinguish a revoked key from an unreadable identity table, for
/// the reason the whole of this surface merges "no such repository" with "no
/// permission": the difference is operator information, and the log keeps it.
pub const REVOKED_MESSAGE: &str =
    "the key that opened this session no longer authorises it; reconnect";

/// Exit status reported when the wire failed mid-transfer.
pub const EXIT_TRANSPORT_FAILED: u32 = 1;

/// Exit status reported when the admission gate refused a transfer.
///
/// `EX_TEMPFAIL` from `sysexits.h`, and deliberately **not** [`EXIT_DENIED`]:
/// "try again" and "you may not" are different answers, and a retry script that
/// cannot tell them apart either hammers a permission error forever or gives up
/// on a transient one.
pub const EXIT_BUSY: u32 = 75;

/// What a client is told while the server's stores are still opening.
///
/// **The word `starting` is load-bearing** and is asserted by
/// `tests/readiness.rs`: it is what separates this from
/// `gunnar_wire::Error::Store`'s `the repository is unavailable; try again`,
/// which is what a client hears when a repository is genuinely broken. The
/// power-cut door read the second sentence during the first condition and
/// reported 64 acked pushes missing that were all present a second later. A
/// harness, a CI script and a person all have to be able to tell "not yet" from
/// "gone", and the only place that distinction can be made is here, in the
/// words.
///
/// It carries [`EXIT_BUSY`], not [`EXIT_DENIED`], for the same reason: 75 means
/// retry.
pub const STARTING_MESSAGE: &str =
    "the server is starting: its stores are still opening after a restart, and it will serve \
     this in a moment; retry";

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

    /// `gunnar-recipient-keys`: the path through the one sandbox (git's
    /// quoting taken off), the member through the principal id rule, and
    /// nothing else on the line; another verb is not this one.
    #[test]
    fn the_recipient_keys_line_takes_a_sandboxed_path_and_an_account_name() {
        let ok = |line: &str| parse_recipient_keys_verb(line.as_bytes()).expect("this verb").expect("well formed");
        let (repo, member) = ok("gunnar-recipient-keys 'team/vault.git' 'bob'");
        assert_eq!((repo.namespace(), repo.name(), member.as_str()), ("team", "vault", "bob"));
        let (repo, member) = ok("gunnar-recipient-keys team/vault bob");
        assert_eq!((repo.namespace(), repo.name(), member.as_str()), ("team", "vault", "bob"));
        let (repo, _) = ok("gunnar-recipient-keys '/team/vault.git' bob");
        assert_eq!(repo.name(), "vault");
        assert!(parse_recipient_keys_verb(b"git-upload-pack 'team/vault.git'").is_none());
        assert!(parse_recipient_keys_verb(b"gunnar-recipient-keysx a/b c").is_none());
        for bad in [
            "gunnar-recipient-keys",
            "gunnar-recipient-keys 'team/vault.git'",
            "gunnar-recipient-keys '../etc/passwd' bob",
            "gunnar-recipient-keys team/vault 'bo b'",
            "gunnar-recipient-keys team/vault anonymous",
            "gunnar-recipient-keys team/vault 'bob",
            "gunnar-recipient-keys team/vault bob\u{1}",
        ] {
            assert!(
                matches!(parse_recipient_keys_verb(bad.as_bytes()), Some(Err(_))),
                "{bad:?} is refused"
            );
        }
        let long = format!("gunnar-recipient-keys team/vault {}", "b".repeat(600));
        assert!(matches!(parse_recipient_keys_verb(long.as_bytes()), Some(Err(_))));
    }

    /// **The door offers the post-quantum hybrid first**, from gunnar's own
    /// list: `mlkem768x25519-sha256`, then the classical fallbacks, and the
    /// strict-kex markers (Terrapin) kept.
    #[test]
    fn the_door_offers_mlkem768x25519_first_from_gunnars_own_list() {
        let p = preferred();
        assert!(std::ptr::eq(p.kex.as_ref().as_ptr(), KEX_ORDER.as_ptr()), "the server's list is gunnar's KEX_ORDER, not whatever russh defaults to");
        let names: Vec<&str> = p.kex.iter().map(|n| n.as_ref()).collect();
        assert_eq!(names[..3], ["mlkem768x25519-sha256", "curve25519-sha256", "curve25519-sha256@libssh.org"], "{names:?}");
        assert!(names.contains(&"kex-strict-s-v00@openssh.com"), "strict kex stays: {names:?}");
        assert_eq!(p.cipher, russh::Preferred::DEFAULT.cipher, "only the key exchange is gunnar's own");
    }

    /// The accept loop outlives a descriptor shortage and a client that hung
    /// up mid-handshake; it returns on a listener that is gone.
    #[test]
    fn transient_accept_errors_are_named() {
        for errno in [24, 23, 105, 12, 103] {
            assert!(
                accept_error_is_transient(&std::io::Error::from_raw_os_error(errno)),
                "errno {errno}"
            );
        }
        for errno in [9, 22, 88] {
            assert!(
                !accept_error_is_transient(&std::io::Error::from_raw_os_error(errno)),
                "errno {errno}"
            );
        }
        assert!(!accept_error_is_transient(&std::io::Error::other("closed")));
    }

    /// A teardown that fails is **reported**, and one that works is
    /// silent.
    ///
    /// Driven through the helper rather than through a live channel: making
    /// `Channel::close()` fail on demand means a peer that has vanished at an
    /// exact moment, which is a race to arrange and a race to assert on. What
    /// the helper decides is the whole of what changed, `let _ =` against a
    /// line in the journal, and both directions are asserted, because a
    /// `note_teardown` that logged unconditionally would put a line in an
    /// operator's journal on every clean disconnect and make the signal
    /// useless.
    /// Capture every `tracing` line `emit` produces, rendered as
    /// `<target> <field>=<value> …`.
    ///
    /// One capture for every test in this module that reads the journal (one
    /// implementation): there were two copies of this layer forty lines apart, and a second
    /// copy of a capture is a second chance to filter out the line under test.
    fn captured_lines(emit: impl FnOnce()) -> Vec<String> {
        use std::sync::{Arc, Mutex};
        use tracing_subscriber::layer::SubscriberExt;
        use tracing_subscriber::Layer as _;

        #[derive(Clone, Default)]
        struct Capture(Arc<Mutex<Vec<String>>>);
        struct CaptureLayer(Capture);
        impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for CaptureLayer {
            fn on_event(
                &self,
                event: &tracing::Event<'_>,
                _: tracing_subscriber::layer::Context<'_, S>,
            ) {
                struct Render(String);
                impl tracing::field::Visit for Render {
                    fn record_debug(
                        &mut self,
                        field: &tracing::field::Field,
                        value: &dyn std::fmt::Debug,
                    ) {
                        self.0.push_str(&format!("{}={value:?} ", field.name()));
                    }
                }
                let mut render = Render(String::new());
                event.record(&mut render);
                self.0 .0.lock().expect("capture").push(format!(
                    "{} {}",
                    event.metadata().target(),
                    render.0
                ));
            }
        }

        let capture = Capture::default();
        let subscriber = tracing_subscriber::registry().with(
            CaptureLayer(capture.clone())
                .with_filter(tracing_subscriber::filter::LevelFilter::TRACE),
        );
        tracing::subscriber::with_default(subscriber, emit);
        let lines = capture.0.lock().expect("capture").clone();
        lines
    }

    #[test]
    fn a_failed_teardown_step_is_reported_and_a_clean_one_is_not() {
        let lines = captured_lines(|| {
            note_teardown::<std::io::Error>("channel-close", Ok(()));
            note_teardown(
                "watchdog-disconnect",
                Err(std::io::Error::other("the peer was already gone")),
            );
        });

        assert_eq!(
            lines.len(),
            1,
            "expected exactly one line — the failure — got {lines:?}"
        );
        assert!(
            lines[0].starts_with(gunnar_core::observe::TARGET_SSH),
            "the line is not on the ssh target: {}",
            lines[0]
        );
        assert!(
            lines[0].contains("watchdog-disconnect") && lines[0].contains("already gone"),
            "the line names neither the step nor the error: {}",
            lines[0]
        );
    }

    /// **RED-WHEN-BROKEN: a real failure is still reported as one.**
    ///
    /// The dangerous direction of [`peer_hung_up`] is not missing a hung-up
    /// peer — that only restores the noise. It is answering `true` for
    /// everything, which gives a beautifully quiet journal for a server that is
    /// on fire, and does it in a way no other test would notice.
    ///
    /// So every case is asserted in both directions, against **rendered log
    /// output** rather than against the predicate, because the predicate is
    /// private and the log line is what an operator has.
    #[test]
    fn a_real_failure_is_still_reported_as_one() {
        // Benign: the peer went away. Each of these is a shape MEASURED in the
        // live journal on 2026-08-06 for a transfer that succeeded.
        let benign: Vec<(&str, Box<dyn std::error::Error + 'static>)> = vec![
            // `err=Channel send error` — the channel's sender is gone.
            ("russh SendError", Box::new(russh::Error::SendError)),
            ("russh HUP", Box::new(russh::Error::HUP)),
            ("russh Disconnect", Box::new(russh::Error::Disconnect)),
            // `error=early eof` — tokio's `read_exact` on a closed socket.
            (
                "early eof",
                Box::new(std::io::Error::new(
                    std::io::ErrorKind::UnexpectedEof,
                    "early eof",
                )),
            ),
            (
                "broken pipe",
                Box::new(std::io::Error::from(std::io::ErrorKind::BrokenPipe)),
            ),
            (
                "connection reset",
                Box::new(std::io::Error::from(std::io::ErrorKind::ConnectionReset)),
            ),
        ];
        for (what, err) in benign {
            let lines = captured_lines(|| note_teardown("channel-close", Err(BoxedError(err))));
            assert_eq!(lines.len(), 1, "{what}: expected one line, got {lines:?}");
            let line = lines[0].to_ascii_lowercase();
            assert!(
                line.contains("peer_gone"),
                "{what} was not classified as a hung-up peer: {}",
                lines[0]
            );
            assert!(
                !line.contains("error") && !line.contains("err=") && !line.contains("fail"),
                "{what} is benign but its line is still found by `grep -i error`: {}",
                lines[0]
            );
        }

        // NOT benign: the protocol itself went wrong. These must keep saying so
        // — this is the half that stops the classifier becoming a blanket yes.
        let real: Vec<(&str, Box<dyn std::error::Error + 'static>)> = vec![
            ("key exchange", Box::new(russh::Error::Kex)),
            ("packet auth", Box::new(russh::Error::PacketAuth)),
            ("decryption", Box::new(russh::Error::DecryptionError)),
            ("inconsistent state", Box::new(russh::Error::Inconsistent)),
            ("no common algo", Box::new(russh::Error::WrongChannel)),
            (
                "permission denied on disk",
                Box::new(std::io::Error::from(std::io::ErrorKind::PermissionDenied)),
            ),
            (
                "out of descriptors",
                Box::new(std::io::Error::from(std::io::ErrorKind::Other)),
            ),
        ];
        for (what, err) in real {
            let lines = captured_lines(|| note_teardown("channel-close", Err(BoxedError(err))));
            assert_eq!(lines.len(), 1, "{what}: expected one line, got {lines:?}");
            assert!(
                lines[0].contains("ssh.teardown.failed"),
                "{what} was swallowed as benign, so the classifier is a blanket yes: {}",
                lines[0]
            );
            assert!(
                lines[0].contains("err="),
                "{what} lost the error itself, so the line names no cause: {}",
                lines[0]
            );
        }
    }

    /// A boxed error that is still `std::error::Error`, so the table above can
    /// hold two concrete types in one `Vec` and still reach the classifier's
    /// `downcast_ref` through `source()`.
    #[derive(Debug)]
    struct BoxedError(Box<dyn std::error::Error + 'static>);

    impl std::fmt::Display for BoxedError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            self.0.fmt(f)
        }
    }

    impl std::error::Error for BoxedError {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            Some(self.0.as_ref())
        }
    }

    /// The session-level half of the same rule: an ended session says nothing
    /// an operator greps for when the client simply hung up, and still says
    /// `error` when it did not.
    ///
    /// Asserted through the real `Handler` method rather than the predicate,
    /// because the method is what russh calls.
    #[test]
    fn a_hung_up_session_is_not_logged_as_an_error() {
        let quiet = captured_lines(|| {
            note_session_end(&anyhow::Error::new(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                "early eof",
            )));
        });
        assert_eq!(quiet.len(), 1, "expected one line, got {quiet:?}");
        let line = quiet[0].to_ascii_lowercase();
        assert!(
            line.contains("peer-hung-up") && !line.contains("error"),
            "a client hanging up is still logged as an error: {}",
            quiet[0]
        );

        let loud = captured_lines(|| {
            note_session_end(&anyhow::Error::new(russh::Error::Kex));
        });
        assert_eq!(loud.len(), 1, "expected one line, got {loud:?}");
        assert!(
            loud[0].to_ascii_lowercase().contains("error"),
            "a key-exchange failure was swallowed as a hung-up peer: {}",
            loud[0]
        );
    }

    /// An unencodable key is **refused and counted**, never accepted.
    ///
    /// The assertion is on the applied output, the `Auth` value that goes back
    /// to russh and the counter an operator reads, not on "it did not panic".
    /// A body that returned `Auth::Accept` would let a key nobody could
    /// fingerprint onto the server, which is the one outcome worse than the
    /// panic this replaced.
    #[test]
    fn a_key_that_does_not_re_encode_is_rejected_and_counted() {
        let metrics = gunnar_core::observe::ServerMetrics::default();
        let auth = refuse_unencodable_key(&metrics, "decorative");

        assert!(
            matches!(auth, Auth::Reject { .. }),
            "an unencodable key must be rejected, got {auth:?}"
        );
        let snapshot = metrics.snapshot();
        assert_eq!(
            snapshot.connections_refused, 1,
            "the refusal must be visible to an operator"
        );
        // Not an identity-table fault, and the counters must not blur the two.
        assert_eq!(snapshot.auth_faults, 0);
        assert_eq!(snapshot.connections_accepted, 0);
    }
}

/// Pure: whether an exec line is git-lfs asking SSH (`git-lfs-authenticate …`,
/// `git-lfs-transfer …`) — refused, and said at INFO.
pub fn is_lfs_over_ssh(command: &str) -> bool {
    let first = command.split_whitespace().next().unwrap_or("");
    // The transfer verb is named through the dispatch table's own LFS row, never spelled here
    // (`command_parsing::the_dispatch_table_is_the_only_place_a_verb_is_named`).
    // `git-lfs-authenticate` is no verb gunnar dispatches: it is git-lfs's own probe.
    first == "git-lfs-authenticate"
        || crate::command::SERVICES
            .iter()
            .any(|spec| spec.verb == first && matches!(spec.service, crate::command::GitService::LfsTransfer(_)))
}

#[cfg(test)]
mod lfs_over_ssh_tests {
    /// ★ git-lfs's SSH probe is a client's known step, not a defect (RUN A 2026-10-08).
    #[test]
    fn git_lfs_asking_ssh_is_known_and_anything_else_is_not() {
        assert!(super::is_lfs_over_ssh("git-lfs-authenticate /cbc/vault upload"));
        assert!(super::is_lfs_over_ssh("git-lfs-transfer 'acme/site' download"));
        for other in ["bash", "scp -t /etc", "", "git-lfs-authenticatex /a upload", "echo git-lfs-authenticate"] {
            assert!(!super::is_lfs_over_ssh(other), "{other:?}");
        }
    }
}