synaps 0.11.0

Terminal-native AI agent runtime — parallel orchestration, reactive subagents, MCP, autonomous supervision
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
//! `synaps auth-broker` — credential broker (epic #155, task #156).
//!
//! Holds ONE OAuth credential (this machine's `auth.json`), is the SINGLE
//! refresher (Anthropic rotates the refresh token on every refresh, so exactly
//! one party may refresh), and serves short-lived **access** tokens to authorized
//! client machines.
//!
//! ## Transport security (task #156 subtask 6)
//!
//! ```text
//! bind addr    | --tls-cert/key | --insecure-http | result
//! -------------|----------------|-----------------|-------------------------------------------
//! loopback     | absent         | any             | plain HTTP, no warning
//! loopback     | both set       | any             | HTTPS (redundant but allowed)
//! non-loopback | absent         | absent          | REFUSED — must TLS or explicit opt-in
//! non-loopback | absent         | present         | plain HTTP + WireGuard guidance warning
//! non-loopback | both set       | any             | HTTPS, clean startup
//! one of pair  | one set        | any             | REFUSED — must provide both cert+key
//! ```
//!
//! TLS is served via `axum-server` (tls-rustls feature, rustls 0.23).
//!
//! ## Machine auth (#147 C1)
//!
//! Every credential endpoint requires `Authorization: Bearer <machine token>`.
//! The token comes from `--machine-token-file` or `SYNAPS_BROKER_TOKEN`. A
//! loopback bind with neither generates one into `<base_dir>/auth-broker.token`
//! (0600, next to `auth.json`; reused on restart), and a local client whose
//! endpoint is a loopback URL reads that file when it has no
//! `auth.machine_token` / `SYNAPS_MACHINE_TOKEN`. A loopback broker also
//! refuses any `Host` other than `127.0.0.1:<port>`, `localhost:<port>` or
//! `[::1]:<port>` (DNS rebinding). Only a non-loopback bind with
//! `--insecure-no-auth` runs without a token.
//!
//! Clients run `synaps` with `auth.remote_endpoint` pointed here; they fetch a
//! token per request and never store the credential on their own disk.
//!
//! Endpoints:
//!   GET  /healthz                         -> { status }   (no secret; 503 until ANY OAuth slot exists)
//!   GET  /token?provider=X[&account=Y]    -> { access_token, expires, ttl_ms, account }
//!                                            (machine-auth, OAuth providers ONLY, never Muse
//!                                            (proxy-only, #216 I2); `account` is a
//!                                            label, `default`, or `auto`; unknown → 404, malformed
//!                                            → 400, no capacity → 503; never a fallback)
//!   POST /proxy                           -> typed broker proxy (machine-auth; OAuth providers may
//!                                            pin a slot as `provider@label`; keys never vended)
//!   GET  /usage                           -> legacy raw Anthropic usage JSON (machine-auth)
//!   GET  /usage/snapshot?provider&account -> normalized UsageSnapshot (machine-auth)
//!   POST /accounts/cooldown               -> { provider, account, until_ms?, reason } (machine-auth)
//!   GET  /capabilities                    -> provider status list incl. account rows (no secrets)

use std::net::SocketAddr;
use std::path::PathBuf;
use std::time::Duration;

use std::sync::Arc;

use axum::{
    extract::{ConnectInfo, Query, State},
    http::{HeaderMap, StatusCode},
    response::IntoResponse,
    routing::{get, post},
    Json, Router,
};
use futures::StreamExt;
use serde::Deserialize;
use serde_json::json;
use synaps_cli::auth;

/// OAuth providers whose descriptors permit access-token vending. Static-key
/// strategies are intentionally not served by this endpoint.
fn broker_provider(value: &str) -> Option<auth::OAuthProviderId> {
    let id: auth::OAuthProviderId = value.try_into().ok()?;
    let descriptor = auth::provider::registry().get(id).copied()?;
    (descriptor.broker_strategy == auth::BrokerCredentialStrategy::OAuthAccessToken).then_some(id)
}

/// Providers `/token` may vend an access token for: [`broker_provider`]
/// minus Meta Muse (#216 I2). Muse is routed `BrokerProxy` and its stored
/// `access` is a minted Model API key that is valid until it 401s, not a
/// short-lived OAuth access token, so it never leaves the broker. `/proxy`
/// (which does not consult this list) keeps serving Muse, and usage /
/// cooldown endpoints keep using `broker_provider`.
fn token_vending_provider(value: &str) -> Option<auth::OAuthProviderId> {
    broker_provider(value).filter(|id| *id != auth::OAuthProviderId::Muse)
}

// ── TLS config types ─────────────────────────────────────────────────────────

/// Validated, ready-to-use TLS material (PEM bytes confirmed parseable).
#[derive(Clone, Debug)]
pub struct TlsConfig {
    pub cert_pem: Vec<u8>,
    pub key_pem: Vec<u8>,
}

/// Outcome of [`check_bind_policy`] — what transport mode to use or why to abort.
#[derive(Debug, PartialEq, Eq)]
pub enum BindDecision {
    /// Plain HTTP is allowed (loopback or explicit opt-in on non-loopback).
    Http {
        /// Print the WireGuard guidance warning (non-loopback + --insecure-http).
        warn: bool,
    },
    /// Serve TLS.
    Tls,
    /// Refuse to start; contains the error message.
    Refuse(String),
}

// ── Bind-policy logic (pure — trivial to unit test) ──────────────────────────

/// Pure function — no I/O. Determines whether to serve HTTP, HTTPS, or refuse.
///
/// `is_loopback` — true if the bind address is 127.x or ::1  
/// `has_tls`     — both --tls-cert and --tls-key were provided  
/// `insecure_http` — --insecure-http flag was passed
pub fn check_bind_policy(is_loopback: bool, has_tls: bool, insecure_http: bool) -> BindDecision {
    if has_tls {
        return BindDecision::Tls;
    }
    if is_loopback {
        return BindDecision::Http { warn: false };
    }
    // non-loopback, no TLS
    if insecure_http {
        return BindDecision::Http { warn: true };
    }
    BindDecision::Refuse(
        "refusing to start: non-loopback bind without TLS. \
         Pass --tls-cert + --tls-key to enable HTTPS (recommended), \
         or --insecure-http to acknowledge you are running behind WireGuard \
         / a private network and accept plaintext."
            .to_string(),
    )
}

// ── PEM validation ────────────────────────────────────────────────────────────

/// Read and validate a cert+key PEM pair. Fails fast with a human-readable error
/// so the broker never starts with a broken TLS config.
pub fn load_and_validate_tls(cert_path: &PathBuf, key_path: &PathBuf) -> anyhow::Result<TlsConfig> {
    // Read files first — surface "file not found" before doing any parsing.
    let cert_pem = std::fs::read(cert_path)
        .map_err(|e| anyhow::anyhow!("--tls-cert '{}': {e}", cert_path.display()))?;
    let key_pem = std::fs::read(key_path)
        .map_err(|e| anyhow::anyhow!("--tls-key '{}': {e}", key_path.display()))?;

    // Parse to catch garbage PEM / wrong file type before binding.
    validate_pem_pair(&cert_pem, &key_pem)?;

    Ok(TlsConfig { cert_pem, key_pem })
}

/// Parse the PEM bytes — returns a readable error if either is malformed.
/// Uses `rustls-pki-types` (same parser axum-server uses internally).
/// Separated for unit-testability with in-memory bytes.
pub fn validate_pem_pair(cert_pem: &[u8], key_pem: &[u8]) -> anyhow::Result<()> {
    use rustls_pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer};

    // Validate cert chain — must have at least one cert.
    let certs: Vec<CertificateDer<'_>> = CertificateDer::pem_slice_iter(cert_pem)
        .collect::<Result<Vec<_>, _>>()
        .map_err(|e| anyhow::anyhow!("TLS cert PEM is malformed: {e}"))?;
    if certs.is_empty() {
        anyhow::bail!("TLS cert PEM contains no certificates (empty or wrong format)");
    }

    // Validate private key — must parse as one of the known key types.
    let keys: Vec<PrivateKeyDer<'_>> = PrivateKeyDer::pem_slice_iter(key_pem)
        .collect::<Result<Vec<_>, _>>()
        .map_err(|e| anyhow::anyhow!("TLS key PEM is malformed: {e}"))?;
    if keys.is_empty() {
        anyhow::bail!("TLS key PEM contains no private key (empty or wrong format)");
    }
    if keys.len() > 1 {
        anyhow::bail!("TLS key PEM contains multiple private keys; it must contain exactly one");
    }

    Ok(())
}

// ── Broker internal state ─────────────────────────────────────────────────────

#[derive(Clone)]
struct BrokerState {
    /// Token clients must present as `Authorization: Bearer <token>`. `None`
    /// disables auth: only a non-loopback bind with explicit
    /// `--insecure-no-auth`. A loopback broker always has one (#147 C1).
    machine_token: Option<String>,
    /// Loopback binds only: the hostnames a `Host` header may name
    /// (`localhost`, `127.0.0.1`, `[::1]` and the bound IP), any port.
    /// Anything else is refused before routing, so a DNS-rebinding page
    /// (`Host: attacker.example`) cannot talk to the broker through the
    /// victim's browser. The port is deliberately not checked: it adds no
    /// protection and would break `ssh -L <other-port>:127.0.0.1:<port>`.
    allowed_hosts: Option<Arc<[String]>>,
    /// Where the expected machine token comes from, for actionable denial
    /// logs (a path or an env var name; never the token).
    token_source: Arc<str>,
    /// The in-process broker that owns every credential (all providers and
    /// account slots), refreshes them, and executes proxied requests. Raw
    /// keys and refresh tokens never leave this boundary.
    local: Arc<auth::LocalBroker>,
}

/// Hostnames a loopback broker bound to `bind_ip` accepts in `Host`
/// (compared without the port).
fn loopback_allowed_hostnames(bind_ip: std::net::IpAddr) -> Vec<String> {
    let mut names: Vec<String> = ["localhost", "127.0.0.1", "[::1]"]
        .iter()
        .map(|n| n.to_string())
        .collect();
    let bound = match bind_ip {
        std::net::IpAddr::V4(ip) => ip.to_string(),
        std::net::IpAddr::V6(ip) => format!("[{ip}]"),
    };
    if !names.contains(&bound) {
        names.push(bound);
    }
    names
}

/// The hostname part of a `Host` / `:authority` value, if well-formed.
fn host_header_hostname(value: &str) -> Option<String> {
    let authority: axum::http::uri::Authority = value.parse().ok()?;
    if authority.as_str().contains('@') {
        return None; // userinfo has no place in a Host header
    }
    Some(authority.host().to_string())
}

/// Refuse any request whose `Host` (or HTTP/2 `:authority`) is not on the
/// loopback allowlist. No-op for non-loopback binds.
async fn host_guard(
    State(st): State<BrokerState>,
    req: axum::extract::Request,
    next: axum::middleware::Next,
) -> axum::response::Response {
    if let Some(allowed) = st.allowed_hosts.as_deref() {
        let host = req
            .headers()
            .get(axum::http::header::HOST)
            .and_then(|v| v.to_str().ok())
            .or_else(|| req.uri().authority().map(|a| a.as_str()))
            .unwrap_or("");
        let hostname = host_header_hostname(host);
        if !hostname
            .as_deref()
            .is_some_and(|h| allowed.iter().any(|a| a.eq_ignore_ascii_case(h)))
        {
            eprintln!(
                "[auth-broker] DENIED request with non-loopback Host ({} chars)",
                host.len()
            );
            return (
                StatusCode::FORBIDDEN,
                Json(json!({ "error": "host not allowed" })),
            )
                .into_response();
        }
    }
    next.run(req).await
}

/// The machine token this broker will require. An explicit token (file or
/// env) wins. A loopback bind with none uses (creating on first start) the
/// 0600 token file at `token_path`, which local clients read automatically;
/// `--insecure-no-auth` does not turn auth off on loopback. A non-loopback
/// bind with none is refused unless `insecure_no_auth`.
fn resolve_machine_token(
    explicit: Option<String>,
    is_loopback: bool,
    insecure_no_auth: bool,
    token_path: &std::path::Path,
) -> anyhow::Result<Option<String>> {
    if explicit.is_some() {
        return Ok(explicit);
    }
    if is_loopback {
        if insecure_no_auth {
            eprintln!(
                "[auth-broker] WARNING: --insecure-no-auth is ignored on a loopback bind; \
                 a loopback broker always requires a machine token"
            );
        }
        let (token, origin) = auth::load_or_create_broker_token(token_path).map_err(|e| {
            anyhow::anyhow!("broker token file {}: {e}", token_path.display())
        })?;
        match origin {
            auth::BrokerTokenOrigin::Rotated => eprintln!(
                "[auth-broker] WARNING: {} was readable by other users, so its token may have \
                 leaked. Generated a NEW token (0600). Restart or reload every client that \
                 used the old one.",
                token_path.display()
            ),
            auth::BrokerTokenOrigin::Created | auth::BrokerTokenOrigin::Loaded => eprintln!(
                "[auth-broker] loopback machine token {} {} (0600; local clients read it automatically)",
                if origin == auth::BrokerTokenOrigin::Created {
                    "generated at"
                } else {
                    "loaded from"
                },
                token_path.display()
            ),
        }
        return Ok(Some(token));
    }
    if !insecure_no_auth {
        anyhow::bail!(
            "refusing to start: no machine token (set --machine-token-file / \
             SYNAPS_BROKER_TOKEN) while bound to a non-loopback address. That would serve \
             credentials unauthenticated to the network. Pass --insecure-no-auth to override, \
             or bind 127.0.0.1."
        );
    }
    Ok(None)
}

/// 401 for a request that failed machine auth, with an actionable log line
/// (prA I2): old clients can't explain a bare 401, so the broker does. The
/// token itself is never logged or echoed.
fn deny_machine_auth(
    st: &BrokerState,
    headers: &HeaderMap,
    route: &str,
    peer: Option<std::net::IpAddr>,
) -> axum::response::Response {
    let presented = headers.get("authorization").is_some();
    let peer_label = peer.map_or_else(|| "a client".to_string(), |ip| ip.to_string());
    // Rate-limited (prA R2-m6) per (reason, route, peer): a retrying old
    // client can't flood the log, and each route still names its peer.
    let key = denial_key(presented, route, peer);
    if let Some(suppressed) = denial_advisory_due(&DENIAL_LOG, &key, std::time::Instant::now(), DENIAL_LOG_EVERY) {
        let also = if suppressed > 0 {
            format!(" ({suppressed} similar denials suppressed in the last minute)")
        } else {
            String::new()
        };
        if presented {
            eprintln!(
                "[auth-broker] DENIED {route} from {peer_label} (wrong machine token){also}. The \
                 expected token is {}; if it was regenerated, restart or reload the client.",
                st.token_source
            );
        } else {
            eprintln!(
                "[auth-broker] DENIED {route} from {peer_label} (no machine token presented){also}. \
                 Clients must set auth.machine_token or SYNAPS_MACHINE_TOKEN to the token in {}. \
                 Clients older than this broker, or running as another user or base dir, do not \
                 pick it up automatically; restart or reload clients after it changes.",
                st.token_source
            );
        }
    }
    (
        StatusCode::UNAUTHORIZED,
        Json(json!({
            "error": "bad machine auth",
            "hint": "set auth.machine_token or SYNAPS_MACHINE_TOKEN to the broker's machine token \
                     (a loopback broker writes it to auth-broker.token in its base dir); restart \
                     or reload the client after it changes",
        })),
    )
        .into_response()
}

/// Rate-limit key for a 401 advisory: (missing|wrong token, route, peer).
fn denial_key(presented: bool, route: &str, peer: Option<std::net::IpAddr>) -> String {
    let reason = if presented { "wrong" } else { "missing" };
    let peer = peer.map_or_else(|| "-".to_string(), |ip| ip.to_string());
    format!("{reason}|{route}|{peer}")
}

/// One advisory per (reason, route, peer) per this interval.
const DENIAL_LOG_EVERY: std::time::Duration = std::time::Duration::from_secs(60);

type DenialLog = std::sync::Mutex<std::collections::HashMap<String, (std::time::Instant, u64)>>;

static DENIAL_LOG: std::sync::LazyLock<DenialLog> = std::sync::LazyLock::new(Default::default);

/// Whether the advisory for `key` should be logged now. `Some(n)`: log it,
/// `n` similar denials were suppressed since the last one; `None`: suppress.
fn denial_advisory_due(
    log: &DenialLog,
    key: &str,
    now: std::time::Instant,
    every: std::time::Duration,
) -> Option<u64> {
    let mut log = log.lock().unwrap_or_else(|e| e.into_inner());
    if log.len() > 1024 {
        log.retain(|_, (at, _)| now.duration_since(*at) < every);
    }
    match log.get_mut(key) {
        Some((at, suppressed)) if now.duration_since(*at) < every => {
            *suppressed += 1;
            None
        }
        Some((at, suppressed)) => {
            let n = *suppressed;
            *at = now;
            *suppressed = 0;
            Some(n)
        }
        None => {
            log.insert(key.to_string(), (now, 0));
            Some(0)
        }
    }
}

/// Constant-time machine-auth check shared by every credential endpoint.
fn machine_auth_ok(st: &BrokerState, headers: &HeaderMap) -> bool {
    let Some(ref expected) = st.machine_token else {
        return true; // auth disabled (loopback / explicit insecure opt-in)
    };
    let got = headers
        .get("authorization")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    let expected_header = format!("Bearer {expected}");
    ct_eq(got.as_bytes(), expected_header.as_bytes())
}

#[derive(Deserialize)]
struct TokenQuery {
    provider: Option<String>,
    /// `default`, a label, or `auto`. Absent → the broker host's policy.
    account: Option<String>,
    /// Model hint for capacity-aware `auto` selection.
    model: Option<String>,
}

#[derive(Deserialize)]
struct UsageSnapshotQuery {
    provider: Option<String>,
    account: Option<String>,
}

#[derive(Deserialize)]
struct CooldownReport {
    provider: String,
    account: String,
    #[serde(default)]
    until_ms: Option<u64>,
    #[serde(default)]
    reason: Option<String>,
}

/// Constant-time byte comparison — avoids a timing oracle on the machine token.
/// (#158 B1 / CWE-208.) Length mismatch short-circuits; token length is not the
/// secret. Equal-length inputs are compared in constant time.
fn ct_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut diff = 0u8;
    for (x, y) in a.iter().zip(b.iter()) {
        diff |= x ^ y;
    }
    diff == 0
}

// ── Entry point ───────────────────────────────────────────────────────────────

#[allow(clippy::too_many_arguments)]
pub async fn run(
    bind: String,
    machine_token: Option<String>,
    machine_token_file: Option<PathBuf>,
    insecure_no_auth: bool,
    tls_cert: Option<PathBuf>,
    tls_key: Option<PathBuf>,
    insecure_http: bool,
) -> anyhow::Result<()> {
    // ── TLS arg validation: must supply both or neither ──
    let tls = match (tls_cert, tls_key) {
        (Some(cert), Some(key)) => {
            let cfg = load_and_validate_tls(&cert, &key)?;
            Some(cfg)
        }
        (Some(_), None) => anyhow::bail!(
            "--tls-cert was given but --tls-key is missing. Provide both to enable TLS."
        ),
        (None, Some(_)) => anyhow::bail!(
            "--tls-key was given but --tls-cert is missing. Provide both to enable TLS."
        ),
        (None, None) => None,
    };

    // B3 (security): the raw `--machine-token` flag is REJECTED outright. A
    // secret passed in argv is world-readable through `ps aux` and
    // /proc/<pid>/cmdline for the whole life of the process, so any local user
    // can lift the broker credential — which fronts OAuth tokens for every
    // configured provider. The flag is still parsed so we can emit this
    // migration error instead of clap's opaque "unexpected argument".
    // Token sources are file > env only.
    if machine_token.is_some() {
        anyhow::bail!(
            "--machine-token is no longer accepted: a token in argv is visible to every local \
             user via `ps aux` and /proc/<pid>/cmdline, which leaks the broker credential.\n\
             \n\
             Use one of these instead:\n\
             \x20 --machine-token-file <path>   (file readable only by this user)\n\
             \x20 SYNAPS_BROKER_TOKEN=<token>   (environment variable)"
        );
    }

    let machine_token = match machine_token_file {
        Some(ref path) => Some(
            std::fs::read_to_string(path)
                .map_err(|e| {
                    anyhow::anyhow!(
                        "could not read --machine-token-file {}: {e}",
                        path.display()
                    )
                })?
                .trim()
                .to_string(),
        ),
        None => std::env::var("SYNAPS_BROKER_TOKEN").ok(),
    }
    .filter(|s| !s.trim().is_empty());

    let addr: SocketAddr = bind
        .parse()
        .map_err(|e| anyhow::anyhow!("invalid --bind '{}': {}", bind, e))?;

    // ── Bind policy ──────────────────────────────────────────────────────────
    let decision = check_bind_policy(addr.ip().is_loopback(), tls.is_some(), insecure_http);
    match &decision {
        BindDecision::Refuse(msg) => anyhow::bail!("{}", msg),
        BindDecision::Http { warn: true } => {
            eprintln!(
                "  ⚠  non-loopback plain-HTTP bind on {addr}.\n\
                 \n\
                 You have acknowledged this with --insecure-http. Ensure this broker is\n\
                 ONLY reachable via WireGuard or another encrypted private network layer.\n\
                 TLS in-process is available: pass --tls-cert <path> --tls-key <path>.\n"
            );
        }
        BindDecision::Http { warn: false } | BindDecision::Tls => {}
    }

    // B2 + #147 C1: a loopback broker always requires a machine token
    // (auto-generated next to auth.json when none is configured); a
    // non-loopback bind without one is refused unless explicitly opted in.
    let local_token_path = auth::local_broker_token_path();
    let token_source: Arc<str> = match (&machine_token_file, machine_token.is_some()) {
        (Some(path), _) => format!("the --machine-token-file {}", path.display()).into(),
        (None, true) => "SYNAPS_BROKER_TOKEN on the broker host".into(),
        (None, false) => format!("{} on the broker host", local_token_path.display()).into(),
    };
    let machine_token = resolve_machine_token(
        machine_token,
        addr.ip().is_loopback(),
        insecure_no_auth,
        &local_token_path,
    )?;

    // D1: fail fast if no OAuth credential of ANY provider/account is
    // present or the store is unreadable. Codex-only, Kimi-only, or
    // named-slot-only installations are valid broker hosts.
    match auth::any_oauth_credential_present() {
        Ok(true) => {}
        Ok(false) => anyhow::bail!(
            "no OAuth credential at {}. Run `synaps login --provider <id> [--account <label>]` on the broker host first.",
            auth::auth_file_path().display()
        ),
        Err(e) => anyhow::bail!("credential unreadable/corrupt: {e}"),
    }

    let client = reqwest::Client::builder()
        .tls_built_in_webpki_certs(true)
        .tls_built_in_native_certs(true)
        .connect_timeout(Duration::from_secs(10))
        .timeout(Duration::from_secs(60))
        .build()?;

    let state = BrokerState {
        machine_token: machine_token.clone(),
        allowed_hosts: addr
            .ip()
            .is_loopback()
            .then(|| Arc::from(loopback_allowed_hostnames(addr.ip()))),
        token_source,
        local: Arc::new(auth::LocalBroker::new(client.clone())),
    };

    // Proactive refresh of EVERY stored OAuth slot, SUPERVISED. Each slot
    // refreshes independently (own gate + cross-process lock); one failing
    // account never blocks the others. Log lines carry labels only.
    {
        let refresh_client = client;
        let handle = tokio::spawn(async move {
            let mut tick = tokio::time::interval(Duration::from_secs(60));
            loop {
                tick.tick().await;
                let accounts = match auth::list_all_accounts() {
                    Ok(list) => list,
                    Err(e) => {
                        eprintln!("[auth-broker] proactive refresh: cannot list accounts: {e}");
                        continue;
                    }
                };
                for summary in accounts {
                    let Some(cred) = summary.credential_ref() else {
                        continue;
                    };
                    if let Err(e) = auth::ensure_fresh_credential(&refresh_client, &cred).await {
                        eprintln!("[auth-broker] proactive refresh failed for {cred}: {e}");
                    }
                }
            }
        });
        tokio::spawn(async move {
            if let Err(e) = handle.await {
                eprintln!("[auth-broker] FATAL: proactive refresh task died: {e:?} — tokens will go stale; restart the broker.");
            }
        });
    }

    let app = build_router(state);

    match decision {
        BindDecision::Tls => {
            eprintln!(
                "synaps auth-broker listening on https://{addr}  (machine auth: {}, TLS: ON)",
                if machine_token.is_some() {
                    "ON"
                } else {
                    "OFF — --insecure-no-auth!"
                }
            );
            let tls_cfg = tls.expect("Tls decision requires tls config");
            // rustls 0.23 requires an explicit CryptoProvider when multiple backends
            // are compiled in; install ring as the default (idempotent — Err means already set).
            let _ = rustls::crypto::ring::default_provider().install_default();
            let rustls_config =
                axum_server::tls_rustls::RustlsConfig::from_pem(tls_cfg.cert_pem, tls_cfg.key_pem)
                    .await
                    .map_err(|e| anyhow::anyhow!("failed to build TLS config from PEM: {e}"))?;

            // Handle<SocketAddr> — matches addr type for bind_rustls.
            let handle = axum_server::Handle::<SocketAddr>::new();
            let h2 = handle.clone();
            tokio::spawn(async move {
                shutdown_signal().await;
                eprintln!("[auth-broker] shutting down (draining in-flight requests)…");
                h2.graceful_shutdown(Some(Duration::from_secs(30)));
            });

            axum_server::bind_rustls(addr, rustls_config)
                .handle(handle)
                .serve(app.into_make_service_with_connect_info::<SocketAddr>())
                .await
                .map_err(|e| anyhow::anyhow!("axum-server TLS serve error: {e}"))?;
        }
        BindDecision::Http { .. } => {
            eprintln!(
                "synaps auth-broker listening on http://{addr}  (machine auth: {})",
                if machine_token.is_some() {
                    "ON"
                } else {
                    "OFF — --insecure-no-auth!"
                }
            );
            let listener = tokio::net::TcpListener::bind(addr).await?;
            axum::serve(
                listener,
                app.into_make_service_with_connect_info::<SocketAddr>(),
            )
            .with_graceful_shutdown(shutdown_signal())
            .await?;
        }
        BindDecision::Refuse(_) => unreachable!("Refuse is handled above"),
    }

    Ok(())
}

/// Build the production auth-broker router with an injected typed cloud backend.
/// This is the supported construction seam for unattended production-router tests;
/// credentials and signing remain behind `CloudBackend`.
#[cfg(test)]
fn build_router_with_cloud_backend(
    machine_token: Option<String>,
    backend: Arc<dyn auth::broker::CloudBackend>,
) -> Router {
    let local = auth::LocalBroker::new(reqwest::Client::new()).with_cloud_backend(backend);
    build_router(BrokerState {
        machine_token,
        allowed_hosts: None,
        token_source: Arc::from("test"),
        local: Arc::new(local),
    })
}

/// Build the shared axum Router. Extracted so tests can reuse it.
fn build_router(state: BrokerState) -> Router {
    Router::new()
        .route("/healthz", get(healthz))
        .route("/token", get(token))
        .route("/proxy", post(proxy))
        .route("/usage", get(usage))
        .route("/usage/snapshot", get(usage_snapshot))
        .route("/accounts/cooldown", post(accounts_cooldown))
        .route("/cloud/catalog", post(cloud_catalog))
        .route("/cloud/invoke", post(cloud_invoke))
        .route("/capabilities", get(capabilities))
        // Bound inbound request bodies to the broker's typed proxy limit.
        .layer(axum::extract::DefaultBodyLimit::max(
            auth::MAX_PROXY_REQUEST_BYTES,
        ))
        // B7: cap concurrent in-flight requests.
        .layer(tower::limit::ConcurrencyLimitLayer::new(64))
        // #147 C1: loopback Host allowlist runs before every route.
        .layer(axum::middleware::from_fn_with_state(state.clone(), host_guard))
        .with_state(state)
}

/// Resolve on Ctrl-C or SIGTERM so the broker drains cleanly.
async fn shutdown_signal() {
    let ctrl_c = async {
        let _ = tokio::signal::ctrl_c().await;
    };
    #[cfg(unix)]
    let terminate = async {
        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
            Ok(mut sig) => {
                sig.recv().await;
            }
            Err(_) => std::future::pending::<()>().await,
        }
    };
    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();
    tokio::select! {
        _ = ctrl_c => {}
        _ = terminate => {}
    }
}

// ── Handlers ──────────────────────────────────────────────────────────────────

/// Liveness + credential readiness. Returns non-200 when the credential is
/// missing/corrupt so monitors actually catch it.
async fn healthz() -> impl IntoResponse {
    match auth::any_oauth_credential_present() {
        Ok(true) => (StatusCode::OK, Json(json!({ "status": "ok" }))),
        Ok(false) => (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({ "status": "no_credential" })),
        ),
        Err(_) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({ "status": "error" })),
        ),
    }
}

/// Issue a current access token for `provider` (default: anthropic, allowlisted).
async fn token(
    State(st): State<BrokerState>,
    ConnectInfo(peer): ConnectInfo<SocketAddr>,
    headers: HeaderMap,
    Query(q): Query<TokenQuery>,
) -> impl IntoResponse {
    // ── machine auth (constant-time) ──
    if !machine_auth_ok(&st, &headers) {
        return deny_machine_auth(&st, &headers, "/token", Some(peer.ip()));
    }

    // ── provider allowlist ──
    let provider = q.provider.unwrap_or_else(|| "anthropic".to_string());
    let Some(provider_id) = token_vending_provider(&provider) else {
        eprintln!(
            "[auth-broker] DENIED from {} (provider not allowed, {} chars)",
            peer.ip(),
            provider.len()
        );
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "unknown provider" })),
        )
            .into_response();
    };

    // ── account selection ──
    // Absent → this host's policy. `auto` → capacity selection here (the
    // client's own policy said auto). Anything else must be `default` or a
    // valid label; an unknown slot is 404 — never served from another slot.
    use synaps_cli::auth::CredentialBroker;
    let model = q.model.as_deref().filter(|m| !m.trim().is_empty());
    let pinned = match q.account.as_deref() {
        None => st.local.access_token_pinned_for(provider_id, model).await,
        Some(auth::AUTO_ACCOUNT_NAME) => st.local.access_token_auto(provider_id, model).await,
        Some(raw) => match auth::Account::parse(raw) {
            Ok(account) => {
                let cred = auth::CredentialRef::new(provider_id, account);
                st.local
                    .access_token_for(&cred)
                    .await
                    .map(|token| auth::PinnedToken {
                        credential: cred,
                        token,
                    })
            }
            Err(e) => Err(auth::BrokerError::InvalidAccount(e)),
        },
    };

    match pinned {
        Ok(p) => {
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_millis() as u64)
                .unwrap_or(0);
            let ttl_ms = p.token.expires.saturating_sub(now);
            eprintln!(
                "[auth-broker] issued {} token to {} (expires {})",
                p.credential,
                peer.ip(),
                p.token.expires
            );
            (
                StatusCode::OK,
                Json(json!({
                    "access_token": p.token.token,
                    "expires": p.token.expires,
                    "ttl_ms": ttl_ms,
                    "account": p.credential.account.label_str(),
                })),
            )
                .into_response()
        }
        Err(e) => {
            // BrokerError Display is secret-free by contract; the wire body
            // stays generic for credential failures.
            eprintln!(
                "[auth-broker] token request for {provider} from {} failed: {}",
                peer.ip(),
                e
            );
            match e {
                auth::BrokerError::InvalidAccount(_) | auth::BrokerError::UnsupportedAccount { .. } => (
                    StatusCode::BAD_REQUEST,
                    Json(json!({ "error": "invalid account" })),
                )
                    .into_response(),
                auth::BrokerError::UnknownAccount { .. } => (
                    StatusCode::NOT_FOUND,
                    Json(json!({ "error": "unknown account" })),
                )
                    .into_response(),
                auth::BrokerError::NoAccountAvailable { .. } => (
                    StatusCode::SERVICE_UNAVAILABLE,
                    Json(json!({ "error": "no account available" })),
                )
                    .into_response(),
                _ => (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(json!({ "error": "token refresh failed" })),
                )
                    .into_response(),
            }
        }
    }
}

/// Typed broker proxy: execute a static-key provider request broker-side.
///
/// OAuth providers are structurally excluded (`ProxyRequest::validate`), so
/// this endpoint can never become a second token-vending path, and no raw
/// static key ever appears in a response — the broker attaches it upstream.
async fn proxy(
    State(st): State<BrokerState>,
    ConnectInfo(peer): ConnectInfo<SocketAddr>,
    headers: HeaderMap,
    Json(request): Json<auth::ProxyRequest>,
) -> axum::response::Response {
    if !machine_auth_ok(&st, &headers) {
        return deny_machine_auth(&st, &headers, "/proxy", Some(peer.ip()));
    }
    if let Err(e) = request.validate() {
        // BrokerError Display is secret-free by contract.
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": e.to_string() })),
        )
            .into_response();
    }
    use synaps_cli::auth::CredentialBroker;
    if request.stream {
        match st.local.proxy_stream(request).await {
            Ok(stream) => {
                let body = axum::body::Body::from_stream(
                    stream.map(|chunk| chunk.map_err(|e| std::io::Error::other(e.to_string()))),
                );
                (
                    StatusCode::OK,
                    [("content-type", "text/event-stream")],
                    body,
                )
                    .into_response()
            }
            Err(e) => broker_error_response(e),
        }
    } else {
        match st.local.proxy(request).await {
            Ok(resp) => (StatusCode::OK, Json(resp)).into_response(),
            Err(e) => broker_error_response(e),
        }
    }
}

/// Typed usage operation: the local broker resolves the Anthropic OAuth token
/// behind the boundary and calls the pinned usage URL; clients receive usage
/// JSON only. No token, refresh token, or URL choice ever crosses this
/// endpoint — it is deliberately not a general OAuth proxy.
async fn usage(
    State(st): State<BrokerState>,
    ConnectInfo(peer): ConnectInfo<SocketAddr>,
    headers: HeaderMap,
) -> axum::response::Response {
    if !machine_auth_ok(&st, &headers) {
        return deny_machine_auth(&st, &headers, "/usage", Some(peer.ip()));
    }
    use synaps_cli::auth::CredentialBroker;
    match st.local.anthropic_usage().await {
        Ok(value) => (StatusCode::OK, Json(value)).into_response(),
        Err(e) => broker_error_response(e),
    }
}

/// Normalized, secret-free usage snapshot for one `(provider, account)`.
/// The token is resolved broker-side. `account` absent → this host's
/// explicit policy selection (an `auto` policy is not a snapshot target).
async fn usage_snapshot(
    State(st): State<BrokerState>,
    ConnectInfo(peer): ConnectInfo<SocketAddr>,
    headers: HeaderMap,
    Query(q): Query<UsageSnapshotQuery>,
) -> axum::response::Response {
    if !machine_auth_ok(&st, &headers) {
        return deny_machine_auth(&st, &headers, "/usage/snapshot", Some(peer.ip()));
    }
    use synaps_cli::auth::CredentialBroker;
    let provider = q.provider.unwrap_or_else(|| "anthropic".to_string());
    let Some(provider_id) = broker_provider(&provider) else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "unknown provider" })),
        )
            .into_response();
    };
    let account = match q.account.as_deref() {
        Some(raw) => match auth::Account::parse(raw) {
            Ok(account) => account,
            Err(_) => {
                return (
                    StatusCode::BAD_REQUEST,
                    Json(json!({ "error": "invalid account" })),
                )
                    .into_response()
            }
        },
        None => match st.local.account_selector(provider_id) {
            auth::AccountSelector::Account(account) => account,
            _ => {
                return (
                    StatusCode::BAD_REQUEST,
                    Json(json!({ "error": "account required" })),
                )
                    .into_response()
            }
        },
    };
    let cred = auth::CredentialRef::new(provider_id, account);
    match st.local.usage(&cred).await {
        Ok(snapshot) => (StatusCode::OK, Json(snapshot)).into_response(),
        Err(e) => broker_error_response(e),
    }
}

/// A client reports a provider limit for one account so `auto` selection on
/// this host stops advertising it. Machine-auth; labels only.
async fn accounts_cooldown(
    State(st): State<BrokerState>,
    ConnectInfo(peer): ConnectInfo<SocketAddr>,
    headers: HeaderMap,
    Json(report): Json<CooldownReport>,
) -> axum::response::Response {
    if !machine_auth_ok(&st, &headers) {
        return deny_machine_auth(&st, &headers, "/accounts/cooldown", Some(peer.ip()));
    }
    use synaps_cli::auth::CredentialBroker;
    let Some(provider_id) = broker_provider(&report.provider) else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "unknown provider" })),
        )
            .into_response();
    };
    let account = match auth::Account::parse(&report.account) {
        Ok(account) => account,
        Err(_) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({ "error": "invalid account" })),
            )
                .into_response()
        }
    };
    let cred = auth::CredentialRef::new(provider_id, account);
    let reason = report.reason.as_deref().unwrap_or("client_report");
    match st.local.report_cooldown(&cred, report.until_ms, reason).await {
        Ok(()) => (StatusCode::OK, Json(json!({ "status": "ok" }))).into_response(),
        Err(e) => broker_error_response(e),
    }
}

#[derive(Deserialize)]
struct CloudCatalogRequest {
    provider: auth::CloudProviderId,
    context_ref: String,
    #[serde(default)]
    allow_stale: bool,
}

async fn cloud_catalog(
    State(st): State<BrokerState>,
    ConnectInfo(peer): ConnectInfo<SocketAddr>,
    headers: HeaderMap,
    Json(request): Json<CloudCatalogRequest>,
) -> axum::response::Response {
    if !machine_auth_ok(&st, &headers) {
        return deny_machine_auth(&st, &headers, "/cloud/catalog", Some(peer.ip()));
    }
    use synaps_cli::auth::CredentialBroker;
    match st
        .local
        .cloud_catalog(request.provider, &request.context_ref, request.allow_stale)
        .await
    {
        Ok(entries) => (StatusCode::OK, Json(entries)).into_response(),
        Err(error) => broker_error_response(error),
    }
}

#[derive(Deserialize)]
struct CloudInvokeRequest {
    provider: auth::CloudProviderId,
    context_ref: String,
    model_id: String,
    request: auth::InvokeRequest,
}

async fn cloud_invoke(
    State(st): State<BrokerState>,
    ConnectInfo(peer): ConnectInfo<SocketAddr>,
    headers: HeaderMap,
    Json(request): Json<CloudInvokeRequest>,
) -> axum::response::Response {
    if !machine_auth_ok(&st, &headers) {
        return deny_machine_auth(&st, &headers, "/cloud/invoke", Some(peer.ip()));
    }
    use synaps_cli::auth::CredentialBroker;
    match st
        .local
        .cloud_invoke(
            request.provider,
            &request.context_ref,
            &request.model_id,
            request.request,
        )
        .await
    {
        Ok(stream) => {
            // NDJSON framing survives arbitrary HTTP chunk boundaries.
            let body = axum::body::Body::from_stream(stream.map(|event| {
                event
                    .and_then(|event| {
                        serde_json::to_vec(&event)
                            .map(|mut bytes| {
                                bytes.push(b'\n');
                                bytes::Bytes::from(bytes)
                            })
                            .map_err(|e| auth::BrokerError::Transport(e.to_string()))
                    })
                    .map_err(|e| std::io::Error::other(e.to_string()))
            }));
            (
                StatusCode::OK,
                [("content-type", "application/x-ndjson")],
                body,
            )
                .into_response()
        }
        Err(error) => broker_error_response(error),
    }
}

/// Non-secret provider capability/status list.
async fn capabilities(
    State(st): State<BrokerState>,
    ConnectInfo(peer): ConnectInfo<SocketAddr>,
    headers: HeaderMap,
) -> axum::response::Response {
    if !machine_auth_ok(&st, &headers) {
        return deny_machine_auth(&st, &headers, "/capabilities", Some(peer.ip()));
    }
    use synaps_cli::auth::CredentialBroker;
    match st.local.capabilities().await {
        Ok(caps) => (StatusCode::OK, Json(caps)).into_response(),
        Err(e) => broker_error_response(e),
    }
}

/// Map a broker error to an HTTP response. Messages are secret-free.
fn broker_error_response(e: auth::BrokerError) -> axum::response::Response {
    let status = match e {
        auth::BrokerError::UnknownProvider(_)
        | auth::BrokerError::Denied(_)
        | auth::BrokerError::InvalidAccount(_)
        | auth::BrokerError::UnsupportedAccount { .. }
        | auth::BrokerError::UnsupportedCapability { .. } => StatusCode::BAD_REQUEST,
        auth::BrokerError::NotConfigured(_) => StatusCode::FORBIDDEN,
        auth::BrokerError::UnknownAccount { .. } => StatusCode::NOT_FOUND,
        auth::BrokerError::NoAccountAvailable { .. } => StatusCode::SERVICE_UNAVAILABLE,
        auth::BrokerError::Unauthorized => StatusCode::UNAUTHORIZED,
        _ => StatusCode::BAD_GATEWAY,
    };
    (status, Json(json!({ "error": e.to_string() }))).into_response()
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use futures::stream;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::Duration;

    // ── ct_eq (preserved) ────────────────────────────────────────────────────

    #[test]
    fn ct_eq_matches_only_identical() {
        assert!(ct_eq(b"Bearer secret", b"Bearer secret"));
        assert!(!ct_eq(b"Bearer secret", b"Bearer secreT"));
        assert!(!ct_eq(b"Bearer secret", b"Bearer wrong"));
        assert!(!ct_eq(b"short", b"longer-value"));
        assert!(!ct_eq(b"", b"x"));
        assert!(ct_eq(b"", b""));
    }

    // ── Bind-policy matrix (pure fn, no I/O) ─────────────────────────────────

    #[test]
    fn policy_loopback_no_tls_is_plain_http() {
        assert_eq!(
            check_bind_policy(true, false, false),
            BindDecision::Http { warn: false }
        );
    }

    #[test]
    fn policy_loopback_insecure_flag_is_still_plain_http_no_warn() {
        // loopback + insecure flag → still HTTP, no warning (flag is irrelevant on loopback)
        assert_eq!(
            check_bind_policy(true, false, true),
            BindDecision::Http { warn: false }
        );
    }

    #[test]
    fn policy_loopback_with_tls_is_https() {
        assert_eq!(check_bind_policy(true, true, false), BindDecision::Tls);
    }

    #[test]
    fn policy_nonloopback_no_tls_no_flag_refuses() {
        let d = check_bind_policy(false, false, false);
        assert!(matches!(d, BindDecision::Refuse(_)));
        if let BindDecision::Refuse(msg) = d {
            assert!(
                msg.contains("non-loopback"),
                "message should mention non-loopback: {msg}"
            );
            assert!(
                msg.contains("--tls-cert"),
                "message should mention --tls-cert: {msg}"
            );
            assert!(
                msg.contains("--insecure-http"),
                "message should mention --insecure-http: {msg}"
            );
        }
    }

    #[test]
    fn policy_nonloopback_no_tls_insecure_flag_warns() {
        assert_eq!(
            check_bind_policy(false, false, true),
            BindDecision::Http { warn: true }
        );
    }

    #[test]
    fn policy_nonloopback_with_tls_is_https() {
        assert_eq!(check_bind_policy(false, true, false), BindDecision::Tls);
    }

    #[test]
    fn policy_nonloopback_tls_and_insecure_flag_still_tls() {
        // TLS wins — insecure-http is irrelevant when TLS is configured.
        assert_eq!(check_bind_policy(false, true, true), BindDecision::Tls);
    }

    // ── PEM validation unit tests ─────────────────────────────────────────────

    #[test]
    fn validate_garbage_pem_cert_returns_error() {
        let garbage = b"this is not a pem file at all";
        let valid_key = generate_test_cert_key().1;
        let err = validate_pem_pair(garbage, &valid_key);
        assert!(err.is_err(), "garbage cert PEM should fail validation");
        let msg = err.unwrap_err().to_string();
        assert!(
            msg.contains("cert") || msg.contains("no certificates"),
            "error should mention cert issue: {msg}"
        );
    }

    #[test]
    fn validate_garbage_pem_key_returns_error() {
        let (valid_cert, _) = generate_test_cert_key();
        let garbage_key = b"this is definitely not a private key";
        let err = validate_pem_pair(&valid_cert, garbage_key);
        assert!(err.is_err(), "garbage key PEM should fail validation");
        let msg = err.unwrap_err().to_string();
        assert!(
            msg.contains("key") || msg.contains("no private key"),
            "error should mention key issue: {msg}"
        );
    }

    #[test]
    fn validate_valid_self_signed_pair_succeeds() {
        let (cert_pem, key_pem) = generate_test_cert_key();
        validate_pem_pair(&cert_pem, &key_pem).expect("self-signed pair should validate");
    }

    #[test]
    fn validate_cert_pem_used_as_key_returns_error() {
        // Providing cert PEM where key is expected → should fail.
        let (cert_pem, _) = generate_test_cert_key();
        let err = validate_pem_pair(&cert_pem, &cert_pem);
        assert!(err.is_err(), "cert-as-key should fail validation");
    }

    // ── load_and_validate_tls file-path tests ─────────────────────────────────

    #[test]
    fn load_tls_missing_cert_file_returns_error() {
        let dir = tempfile::tempdir().unwrap();
        let cert_path = dir.path().join("nonexistent-cert.pem");
        let key_path = dir.path().join("nonexistent-key.pem");
        // Key exists but cert doesn't
        let (_, key_pem) = generate_test_cert_key();
        std::fs::write(&key_path, &key_pem).unwrap();
        let err = load_and_validate_tls(&cert_path, &key_path);
        assert!(err.is_err());
        let msg = err.unwrap_err().to_string();
        assert!(
            msg.contains("--tls-cert"),
            "error should mention --tls-cert flag: {msg}"
        );
    }

    #[test]
    fn load_tls_missing_key_file_returns_error() {
        let dir = tempfile::tempdir().unwrap();
        let cert_path = dir.path().join("cert.pem");
        let key_path = dir.path().join("nonexistent-key.pem");
        let (cert_pem, _) = generate_test_cert_key();
        std::fs::write(&cert_path, &cert_pem).unwrap();
        let err = load_and_validate_tls(&cert_path, &key_path);
        assert!(err.is_err());
        let msg = err.unwrap_err().to_string();
        assert!(
            msg.contains("--tls-key"),
            "error should mention --tls-key flag: {msg}"
        );
    }

    #[test]
    fn load_tls_garbage_files_returns_error() {
        let dir = tempfile::tempdir().unwrap();
        let cert_path = dir.path().join("cert.pem");
        let key_path = dir.path().join("key.pem");
        std::fs::write(&cert_path, b"not a cert").unwrap();
        std::fs::write(&key_path, b"not a key").unwrap();
        let err = load_and_validate_tls(&cert_path, &key_path);
        assert!(err.is_err(), "garbage files should fail validation");
    }

    #[test]
    fn load_tls_valid_pair_from_tempdir() {
        let dir = tempfile::tempdir().unwrap();
        let cert_path = dir.path().join("cert.pem");
        let key_path = dir.path().join("key.pem");
        let (cert_pem, key_pem) = generate_test_cert_key();
        std::fs::write(&cert_path, &cert_pem).unwrap();
        std::fs::write(&key_path, &key_pem).unwrap();
        load_and_validate_tls(&cert_path, &key_path).expect("valid pair from files should succeed");
    }

    // ── TLS integration tests (axum-server + reqwest over real TLS) ───────────
    //
    // Spin up a real HTTPS listener on 127.0.0.1:<ephemeral>, hit it with
    // reqwest (danger_accept_invalid_certs for the self-signed test CA),
    // then gracefully shut down.

    /// Build a minimal HTTPS router for integration tests (no auth::load_auth dependency).
    fn build_test_router(machine_token: Option<String>) -> Router {
        let tok = machine_token.clone();
        Router::new()
            .route(
                "/healthz",
                get(|| async { Json(json!({ "status": "ok" })) }),
            )
            .route(
                "/token",
                get(move |headers: HeaderMap| {
                    let tok = tok.clone();
                    async move {
                        if let Some(ref expected) = tok {
                            let got = headers
                                .get("authorization")
                                .and_then(|v| v.to_str().ok())
                                .unwrap_or("");
                            let want = format!("Bearer {expected}");
                            if !ct_eq(got.as_bytes(), want.as_bytes()) {
                                return (
                                    StatusCode::UNAUTHORIZED,
                                    Json(json!({ "error": "bad machine auth" })),
                                );
                            }
                        }
                        (
                            StatusCode::OK,
                            Json(json!({
                                "access_token": "test-tok",
                                "expires": 9_999_999_999u64,
                                "ttl_ms": 999_999u64
                            })),
                        )
                    }
                }),
            )
    }

    /// Spin up a real TLS listener on a random loopback port; return addr + handle.
    async fn spawn_tls_server(
        machine_token: Option<String>,
    ) -> (SocketAddr, axum_server::Handle<SocketAddr>) {
        // rustls 0.23 requires an explicit CryptoProvider when multiple backends
        // are compiled in (both aws-lc-rs and ring are in the dep tree here).
        // install_default() is idempotent — the Err case just means it was already set.
        let _ = rustls::crypto::ring::default_provider().install_default();

        let (cert_pem, key_pem) = generate_test_cert_key();
        let rustls_config = axum_server::tls_rustls::RustlsConfig::from_pem(cert_pem, key_pem)
            .await
            .expect("test TLS config should build");

        let app = build_test_router(machine_token);

        // Port 0 → let the OS assign an ephemeral port. Keep the listener alive
        // and pass it directly to from_tcp_rustls so there's no TOCTOU window
        // between get-addr and re-bind.
        let std_listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        std_listener.set_nonblocking(true).unwrap();
        let addr = std_listener.local_addr().unwrap();

        let handle = axum_server::Handle::<SocketAddr>::new();
        let h2 = handle.clone();
        tokio::spawn(async move {
            axum_server::tls_rustls::from_tcp_rustls(std_listener, rustls_config)
                .expect("from_tcp_rustls should succeed")
                .handle(h2)
                .serve(app.into_make_service())
                .await
                .ok();
        });
        // Give it a tick to bind and start accepting.
        tokio::time::sleep(Duration::from_millis(80)).await;
        (addr, handle)
    }

    /// reqwest client that accepts self-signed certs (test-only, never ship to prod).
    fn insecure_client() -> reqwest::Client {
        reqwest::Client::builder()
            .danger_accept_invalid_certs(true)
            .build()
            .expect("insecure reqwest client should build")
    }

    #[tokio::test]
    async fn tls_healthz_returns_200() {
        let (addr, handle) = spawn_tls_server(None).await;
        let url = format!("https://{addr}/healthz");
        let resp = insecure_client()
            .get(&url)
            .send()
            .await
            .expect("GET /healthz over TLS");
        assert_eq!(resp.status(), 200, "/healthz should return 200 over TLS");
        let body: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(body["status"], "ok");
        handle.graceful_shutdown(Some(Duration::from_millis(200)));
    }

    #[tokio::test]
    async fn tls_token_no_auth_returns_401() {
        let (addr, handle) = spawn_tls_server(Some("secret123".to_string())).await;
        let url = format!("https://{addr}/token");
        let resp = insecure_client()
            .get(&url)
            .send()
            .await
            .expect("GET /token no auth");
        assert_eq!(
            resp.status(),
            401,
            "/token without bearer should 401 over TLS"
        );
        handle.graceful_shutdown(Some(Duration::from_millis(200)));
    }

    #[tokio::test]
    async fn tls_token_with_correct_auth_returns_200() {
        let (addr, handle) = spawn_tls_server(Some("my-machine-token".to_string())).await;
        let url = format!("https://{addr}/token");
        let resp = insecure_client()
            .get(&url)
            .header("Authorization", "Bearer my-machine-token")
            .send()
            .await
            .expect("GET /token with correct auth");
        assert_eq!(
            resp.status(),
            200,
            "/token with correct bearer should 200 over TLS"
        );
        let body: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(body["access_token"], "test-tok");
        handle.graceful_shutdown(Some(Duration::from_millis(200)));
    }

    #[tokio::test]
    async fn tls_token_wrong_auth_returns_401() {
        let (addr, handle) = spawn_tls_server(Some("my-machine-token".to_string())).await;
        let url = format!("https://{addr}/token");
        let resp = insecure_client()
            .get(&url)
            .header("Authorization", "Bearer wrong-token")
            .send()
            .await
            .expect("GET /token with wrong auth");
        assert_eq!(
            resp.status(),
            401,
            "/token with wrong bearer should 401 over TLS"
        );
        handle.graceful_shutdown(Some(Duration::from_millis(200)));
    }

    // ── Broker service: /proxy, /capabilities, /token isolation ─────────────

    // ── Genuine authenticated cloud production-router E2E ────────────────────

    struct TypedCloudFixture {
        invokes: AtomicUsize,
    }

    #[async_trait]
    impl auth::broker::CloudBackend for TypedCloudFixture {
        async fn catalog(
            &self,
            provider: auth::CloudProviderId,
            context: &str,
            _: bool,
        ) -> Result<Vec<auth::broker::CloudCatalogEntry>, auth::BrokerError> {
            assert_eq!(context, "ctx-opaque-route");
            Ok(vec![auth::broker::CloudCatalogEntry {
                provider,
                id: "model-x".into(),
                display_name: "Model X".into(),
                context_ref: context.into(),
                context_label: "sandbox".into(),
                stale: false,
                fetched_at: 7,
            }])
        }
        async fn invoke(
            &self,
            _: auth::CloudProviderId,
            context: &str,
            model: &str,
            _: auth::InvokeRequest,
        ) -> Result<auth::broker::CloudEventStream, auth::BrokerError> {
            assert_eq!((context, model), ("ctx-opaque-route", "model-x"));
            self.invokes.fetch_add(1, Ordering::SeqCst);
            Ok(Box::pin(stream::iter(vec![
                Ok(auth::broker::CloudEvent::TextDelta {
                    delta: "frag".into(),
                }),
                Ok(auth::broker::CloudEvent::TextDelta {
                    delta: "mented".into(),
                }),
                Ok(auth::broker::CloudEvent::Done),
            ])))
        }
    }

    #[tokio::test]
    async fn remote_broker_catalog_then_fragmented_invoke_uses_real_auth_router() {
        use auth::CredentialBroker;
        let backend = Arc::new(TypedCloudFixture {
            invokes: AtomicUsize::new(0),
        });
        let app = build_router_with_cloud_backend(Some("machine-only".into()), backend.clone());
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            axum::serve(
                listener,
                app.into_make_service_with_connect_info::<SocketAddr>(),
            )
            .await
            .unwrap()
        });
        let endpoint = format!("http://{addr}");
        let remote = auth::RemoteBroker::new(
            &endpoint,
            "machine-only",
            reqwest::Client::new(),
            auth::TokenCache::new(),
        );
        let provider = auth::CloudProviderId::AwsBedrock;
        let catalog = remote
            .cloud_catalog(provider, "ctx-opaque-route", false)
            .await
            .unwrap();
        assert_eq!(catalog[0].context_ref, "ctx-opaque-route");
        let request: auth::InvokeRequest =
            serde_json::from_value(json!({"messages":[],"tools":[],"stream":true,"options":{}}))
                .unwrap();
        let mut events = remote
            .cloud_invoke(
                provider,
                &catalog[0].context_ref,
                &catalog[0].id,
                request.clone(),
            )
            .await
            .unwrap();
        let mut seen = Vec::new();
        while let Some(event) = events.next().await {
            seen.push(event.unwrap());
        }
        assert_eq!(
            seen,
            vec![
                auth::broker::CloudEvent::TextDelta {
                    delta: "frag".into()
                },
                auth::broker::CloudEvent::TextDelta {
                    delta: "mented".into()
                },
                auth::broker::CloudEvent::Done
            ]
        );
        assert_eq!(backend.invokes.load(Ordering::SeqCst), 1);

        for token in [None, Some("invalid")] {
            let client = reqwest::Client::new();
            let mut call = client.post(format!("{endpoint}/cloud/invoke")).json(&json!({"provider":"aws-bedrock","context_ref":"ctx-opaque-route","model_id":"model-x","request":request}));
            if let Some(token) = token {
                call = call.bearer_auth(token);
            }
            let response = call.send().await.unwrap();
            assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
            let wire = response.text().await.unwrap();
            assert!(!wire.contains("machine-only") && !wire.contains("ctx-opaque-route"));
        }
        assert_eq!(backend.invokes.load(Ordering::SeqCst), 1);
    }

    /// Spawn the REAL router (real handlers/state) on an ephemeral loopback
    /// port. `local_upstream` pins the `local` provider at a fake endpoint so
    /// no real provider or credential file is touched.
    async fn spawn_broker_service(
        machine_token: Option<String>,
        local_upstream: Option<String>,
    ) -> String {
        spawn_broker_service_with(machine_token, local_upstream, true).await
    }

    /// `loopback_host_check`: run the production loopback Host allowlist
    /// for the bound port (what `run` installs for a loopback bind).
    async fn spawn_broker_service_with(
        machine_token: Option<String>,
        local_upstream: Option<String>,
        loopback_host_check: bool,
    ) -> String {
        let client = reqwest::Client::new();
        let local = match local_upstream {
            Some(url) => auth::LocalBroker::with_local_base_url(client.clone(), url),
            None => auth::LocalBroker::new(client.clone()),
        };
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let state = BrokerState {
            machine_token,
            allowed_hosts: loopback_host_check
                .then(|| Arc::from(loopback_allowed_hostnames(addr.ip()))),
            token_source: Arc::from("test"),
            local: Arc::new(local),
        };
        let app = build_router(state);
        tokio::spawn(async move {
            axum::serve(
                listener,
                app.into_make_service_with_connect_info::<SocketAddr>(),
            )
            .await
            .unwrap();
        });
        format!("http://{addr}")
    }

    /// Fake OpenAI-compatible upstream that records the Authorization header
    /// it receives and serves an SSE body.
    async fn spawn_sse_upstream(seen_auth: Arc<std::sync::Mutex<String>>) -> String {
        use axum::routing::post as axum_post;
        let app = Router::new().route(
            "/chat/completions",
            axum_post(move |headers: HeaderMap| {
                let seen = seen_auth.clone();
                async move {
                    *seen.lock().unwrap() = headers
                        .get("authorization")
                        .and_then(|v| v.to_str().ok())
                        .unwrap_or("")
                        .to_string();
                    (
                        [("content-type", "text/event-stream")],
                        "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\ndata: [DONE]\n\n",
                    )
                }
            }),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });
        format!("http://{addr}")
    }

    fn proxy_body(stream: bool) -> serde_json::Value {
        json!({
            "provider": "local",
            "method": "post",
            "path": "/chat/completions",
            "body": {"model": "m", "messages": []},
            "stream": stream,
        })
    }

    /// Proxy authorization: no bearer and a wrong bearer are both 401, and the
    /// denial body contains no credential material.
    #[tokio::test]
    async fn proxy_requires_machine_auth() {
        let base = spawn_broker_service(Some("machine-secret".into()), None).await;
        let client = reqwest::Client::new();

        let resp = client
            .post(format!("{base}/proxy"))
            .json(&proxy_body(false))
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 401, "missing bearer must be denied");

        let resp = client
            .post(format!("{base}/proxy"))
            .bearer_auth("wrong-token")
            .json(&proxy_body(false))
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 401, "wrong bearer must be denied");
        let body = resp.text().await.unwrap();
        assert!(
            !body.contains("machine-secret"),
            "denial must not echo the expected token"
        );
    }

    /// The typed /usage operation is a credential endpoint: it requires
    /// machine auth, and denials carry no token material.
    #[tokio::test]
    async fn usage_requires_machine_auth_and_denials_are_secret_free() {
        let base = spawn_broker_service(Some("machine-secret".into()), None).await;
        let client = reqwest::Client::new();

        let resp = client.get(format!("{base}/usage")).send().await.unwrap();
        assert_eq!(resp.status(), 401, "missing bearer must be denied");

        let resp = client
            .get(format!("{base}/usage"))
            .bearer_auth("wrong-token")
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 401, "wrong bearer must be denied");
        let body = resp.text().await.unwrap();
        assert!(
            !body.contains("machine-secret") && !body.contains("access"),
            "denial must not echo credentials: {body}"
        );
    }

    /// Capabilities also require machine auth (they reveal configured-ness).
    #[tokio::test]
    async fn capabilities_require_machine_auth_and_expose_no_secrets() {
        let base = spawn_broker_service(Some("machine-secret".into()), None).await;
        let client = reqwest::Client::new();

        let resp = client
            .get(format!("{base}/capabilities"))
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 401);

        let resp = client
            .get(format!("{base}/capabilities"))
            .bearer_auth("machine-secret")
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 200);
        let caps: serde_json::Value = resp.json().await.unwrap();
        for row in caps.as_array().expect("array") {
            let obj = row.as_object().unwrap();
            for field in obj.keys() {
                assert!(
                    matches!(
                        field.as_str(),
                        "configured" | "key" | "kind" | "name" | "accounts"
                    ),
                    "capability rows carry status only — unexpected field {field}"
                );
            }
            assert!(obj["configured"].is_boolean());
            // Account rows (OAuth providers only) are non-secret listing rows.
            if let Some(accounts) = obj.get("accounts").and_then(|a| a.as_array()) {
                for account in accounts {
                    for field in account.as_object().unwrap().keys() {
                        assert!(
                            matches!(
                                field.as_str(),
                                "provider"
                                    | "label"
                                    | "identity"
                                    | "account_id_prefix"
                                    // Opaque SHA-256 over the provider account id
                                    // (never token material); lets a client pin
                                    // spending to exactly one listed seat.
                                    | "seat_fingerprint"
                                    | "expires"
                                    | "added_at"
                                    | "selected"
                                    | "cooldown_until"
                            ),
                            "account rows must never carry credential fields: {field}"
                        );
                    }
                    let prefix = account
                        .get("account_id_prefix")
                        .and_then(|v| v.as_str())
                        .unwrap_or("");
                    assert!(prefix.len() <= 8, "account id must be a short prefix");
                }
            }
        }
    }

    /// Remote non-disclosure / cross-provider isolation: the /token endpoint
    /// refuses to vend anything for a static-key provider — static keys are
    /// proxy-only and never leave the broker.
    #[tokio::test]
    async fn token_endpoint_denies_static_key_providers() {
        let base = spawn_broker_service(Some("machine-secret".into()), None).await;
        let client = reqwest::Client::new();
        for provider in ["groq", "openrouter", "local", "definitely-unknown"] {
            let resp = client
                .get(format!("{base}/token"))
                .query(&[("provider", provider)])
                .bearer_auth("machine-secret")
                .send()
                .await
                .unwrap();
            assert_eq!(
                resp.status(),
                400,
                "static/unknown provider '{provider}' must never be vended a token"
            );
            let body = resp.text().await.unwrap();
            assert!(
                !body.contains("access_token"),
                "no token material for {provider}"
            );
        }
    }

    // ── Loopback Host allowlist (DNS rebinding, #147 C1) ─────────────────────

    async fn capabilities_with_host(base: &str, host: &str) -> u16 {
        reqwest::Client::new()
            .get(format!("{base}/capabilities"))
            .header(reqwest::header::HOST, host)
            .bearer_auth("machine-secret")
            .send()
            .await
            .unwrap()
            .status()
            .as_u16()
    }

    /// prA I4: the hostname is checked, the port is not (DNS rebinding sends
    /// a foreign hostname; an `ssh -L 9000:127.0.0.1:<port>` forward sends
    /// `Host: 127.0.0.1:9000` and must work).
    #[tokio::test]
    async fn loopback_broker_rejects_foreign_hostnames_but_not_other_ports() {
        let base = spawn_broker_service(Some("machine-secret".into()), None).await;
        let port = base.rsplit(':').next().unwrap().to_string();
        for host in [
            format!("127.0.0.1:{port}"),
            format!("localhost:{port}"),
            format!("LOCALHOST:{port}"),
            format!("[::1]:{port}"),
            "127.0.0.1:9000".to_string(),
            "localhost:1".to_string(),
            "localhost".to_string(),
            "[::1]".to_string(),
        ] {
            assert_eq!(capabilities_with_host(&base, &host).await, 200, "{host}");
        }
        for host in [
            format!("evil.example:{port}"),
            "evil.example".to_string(),
            format!("localhost.evil.example:{port}"),
            format!("127.0.0.1.evil.example:{port}"),
            format!("user@127.0.0.1:{port}"),
            "127.0.0.2".to_string(),
            String::new(),
        ] {
            assert_eq!(
                capabilities_with_host(&base, &host).await,
                403,
                "rebinding Host {host:?} must be refused even with a valid token"
            );
        }
        // Every route is covered, including the unauthenticated /healthz.
        let resp = reqwest::Client::new()
            .get(format!("{base}/healthz"))
            .header(reqwest::header::HOST, "evil.example")
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 403);
        let body = resp.text().await.unwrap();
        assert!(!body.contains("machine-secret"));
    }

    /// An HTTP/1.0 request with no Host header at all is refused.
    #[tokio::test]
    async fn loopback_broker_refuses_a_missing_host_header() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let base = spawn_broker_service(Some("machine-secret".into()), None).await;
        let addr = base.trim_start_matches("http://");
        let mut conn = tokio::net::TcpStream::connect(addr).await.unwrap();
        conn.write_all(b"GET /healthz HTTP/1.0\r\n\r\n").await.unwrap();
        let mut reply = String::new();
        conn.read_to_string(&mut reply).await.unwrap();
        assert!(
            reply.starts_with("HTTP/1.0 403") || reply.starts_with("HTTP/1.1 403"),
            "{reply}"
        );
    }

    /// prA m6: a broker bound to another 127.x address accepts its own IP.
    #[tokio::test]
    async fn loopback_broker_on_another_127_address_accepts_its_bind_ip() {
        let listener = match tokio::net::TcpListener::bind("127.0.0.2:0").await {
            Ok(l) => l,
            Err(_) => return, // platform without 127/8 aliasing (macOS)
        };
        let addr = listener.local_addr().unwrap();
        let state = BrokerState {
            machine_token: Some("machine-secret".into()),
            allowed_hosts: Some(Arc::from(loopback_allowed_hostnames(addr.ip()))),
            token_source: Arc::from("test"),
            local: Arc::new(auth::LocalBroker::new(reqwest::Client::new())),
        };
        let app = build_router(state);
        tokio::spawn(async move {
            axum::serve(
                listener,
                app.into_make_service_with_connect_info::<SocketAddr>(),
            )
            .await
            .unwrap();
        });
        let base = format!("http://{addr}");
        assert_eq!(capabilities_with_host(&base, &addr.to_string()).await, 200);
        assert_eq!(capabilities_with_host(&base, "127.0.0.3:1").await, 403);
    }

    #[tokio::test]
    async fn host_allowlist_is_only_applied_to_loopback_binds() {
        let base = spawn_broker_service_with(Some("machine-secret".into()), None, false).await;
        assert_eq!(capabilities_with_host(&base, "broker.example:8181").await, 200);
    }

    #[test]
    fn loopback_allowed_hostnames_cover_the_loopback_names_and_bind_ip() {
        let v4: std::net::IpAddr = "127.0.0.1".parse().unwrap();
        assert_eq!(
            loopback_allowed_hostnames(v4),
            vec!["localhost", "127.0.0.1", "[::1]"]
        );
        let other: std::net::IpAddr = "127.0.0.2".parse().unwrap();
        assert!(loopback_allowed_hostnames(other).contains(&"127.0.0.2".to_string()));
        assert_eq!(host_header_hostname("[::1]:8181").as_deref(), Some("[::1]"));
        assert_eq!(host_header_hostname("LOCALHOST").as_deref(), Some("LOCALHOST"));
        assert_eq!(host_header_hostname(""), None);
    }

    #[test]
    fn denial_key_is_per_reason_route_and_peer() {
        let a: std::net::IpAddr = "127.0.0.1".parse().unwrap();
        let b: std::net::IpAddr = "10.0.0.2".parse().unwrap();
        let k = denial_key(false, "/usage", Some(a));
        assert_eq!(k, "missing|/usage|127.0.0.1");
        assert_ne!(k, denial_key(false, "/capabilities", Some(a)), "per route");
        assert_ne!(k, denial_key(false, "/usage", Some(b)), "per peer");
        assert_ne!(k, denial_key(true, "/usage", Some(a)), "per reason");
    }

    #[test]
    fn denial_advisory_is_rate_limited_per_reason_and_peer() {
        let log = DenialLog::default();
        let t0 = std::time::Instant::now();
        let every = Duration::from_secs(60);
        assert_eq!(denial_advisory_due(&log, "missing|127.0.0.1", t0, every), Some(0));
        for i in 1..=50 {
            let t = t0 + Duration::from_millis(i * 100);
            assert_eq!(denial_advisory_due(&log, "missing|127.0.0.1", t, every), None);
        }
        // A different reason or peer is its own stream.
        assert_eq!(denial_advisory_due(&log, "wrong|127.0.0.1", t0, every), Some(0));
        assert_eq!(denial_advisory_due(&log, "missing|10.0.0.2", t0, every), Some(0));
        // After the interval: logged again, with the suppressed count.
        let later = t0 + Duration::from_secs(61);
        assert_eq!(denial_advisory_due(&log, "missing|127.0.0.1", later, every), Some(50));
        assert_eq!(denial_advisory_due(&log, "missing|127.0.0.1", later, every), None);
    }

    /// prA I2: a denied request gets an actionable hint and never the token.
    #[tokio::test]
    async fn machine_auth_denial_carries_a_hint_and_no_token() {
        let base = spawn_broker_service(Some("machine-secret".into()), None).await;
        let resp = reqwest::Client::new()
            .get(format!("{base}/capabilities"))
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 401);
        let body: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(body["error"], "bad machine auth");
        let hint = body["hint"].as_str().unwrap();
        assert!(
            hint.contains("auth.machine_token") && hint.contains("SYNAPS_MACHINE_TOKEN"),
            "{hint}"
        );
        assert!(hint.contains("auth-broker.token") && hint.contains("restart"), "{hint}");
        assert!(!body.to_string().contains("machine-secret"));
    }

    // ── Loopback machine-token bootstrap (#147 C1) ───────────────────────────

    #[test]
    fn loopback_without_token_generates_one_and_remote_needs_explicit_opt_out() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("auth-broker.token");
        let tok = resolve_machine_token(None, true, false, &path).unwrap();
        let tok = tok.expect("loopback always has a machine token");
        assert_eq!(std::fs::read_to_string(&path).unwrap().trim(), tok);
        assert_eq!(
            resolve_machine_token(None, true, false, &path).unwrap().as_deref(),
            Some(tok.as_str()),
            "restart reuses the token clients already read"
        );
        // --insecure-no-auth never turns auth off on loopback.
        assert_eq!(
            resolve_machine_token(None, true, true, &path).unwrap().as_deref(),
            Some(tok.as_str())
        );
        // An explicit token wins and no file is consulted.
        let other = dir.path().join("unused.token");
        assert_eq!(
            resolve_machine_token(Some("explicit".into()), true, false, &other)
                .unwrap()
                .as_deref(),
            Some("explicit")
        );
        assert!(!other.exists());
        // Non-loopback: unchanged — no token is refused unless opted out.
        assert!(resolve_machine_token(None, false, false, &other).is_err());
        assert_eq!(resolve_machine_token(None, false, true, &other).unwrap(), None);
        assert!(!other.exists(), "never auto-generated for a network bind");
    }

    // ── /usage/snapshot and /accounts/cooldown machine auth (#147 I5) ───────
    //
    // With the right bearer the request reaches the handler's own validation
    // (400 for a bad provider / account), which needs no credential store;
    // without it, or with a wrong one, it is 401 before anything else runs.

    async fn snapshot_status(base: &str, bearer: Option<&str>, query: &[(&str, &str)]) -> (u16, String) {
        let mut req = reqwest::Client::new()
            .get(format!("{base}/usage/snapshot"))
            .query(query);
        if let Some(b) = bearer {
            req = req.bearer_auth(b);
        }
        let resp = req.send().await.unwrap();
        (resp.status().as_u16(), resp.text().await.unwrap())
    }

    async fn cooldown_status(base: &str, bearer: Option<&str>, body: serde_json::Value) -> (u16, String) {
        let mut req = reqwest::Client::new()
            .post(format!("{base}/accounts/cooldown"))
            .json(&body);
        if let Some(b) = bearer {
            req = req.bearer_auth(b);
        }
        let resp = req.send().await.unwrap();
        (resp.status().as_u16(), resp.text().await.unwrap())
    }

    #[tokio::test]
    async fn usage_snapshot_requires_machine_auth() {
        let base = spawn_broker_service(Some("machine-secret".into()), None).await;
        let q = [("provider", "anthropic"), ("account", "../bad")];
        for bearer in [None, Some("wrong-token"), Some("machine-secret-but-longer")] {
            let (status, body) = snapshot_status(&base, bearer, &q).await;
            assert_eq!(status, 401, "{bearer:?}");
            assert!(!body.contains("machine-secret"), "{body}");
        }
        let (status, body) = snapshot_status(&base, Some("machine-secret"), &q).await;
        assert_eq!(status, 400, "authorized request reaches validation: {body}");
        assert!(body.contains("invalid account"), "{body}");
        let (status, _) = snapshot_status(
            &base,
            Some("machine-secret"),
            &[("provider", "groq"), ("account", "default")],
        )
        .await;
        assert_eq!(status, 400, "static-key provider is not a snapshot target");
    }

    #[tokio::test]
    async fn accounts_cooldown_requires_machine_auth() {
        let base = spawn_broker_service(Some("machine-secret".into()), None).await;
        let body = json!({"provider": "anthropic", "account": "../bad", "reason": "t"});
        for bearer in [None, Some("wrong-token")] {
            let (status, text) = cooldown_status(&base, bearer, body.clone()).await;
            assert_eq!(status, 401, "{bearer:?}");
            assert!(!text.contains("machine-secret"), "{text}");
        }
        let (status, text) = cooldown_status(&base, Some("machine-secret"), body).await;
        assert_eq!(status, 400, "authorized request reaches validation: {text}");
        assert!(text.contains("invalid account"), "{text}");
        let (status, text) = cooldown_status(
            &base,
            Some("machine-secret"),
            json!({"provider": "groq", "account": "default"}),
        )
        .await;
        assert_eq!(status, 400, "{text}");
        assert!(text.contains("unknown provider"), "{text}");
    }

    /// Malformed `account` on `/token` is 400 from the real handler before
    /// any credential lookup (unknown → 404 and auto → 503 need a store;
    /// see tests/multi_account_cli.rs, which runs the production binary).
    #[tokio::test]
    async fn token_malformed_account_is_400() {
        let base = spawn_broker_service(Some("machine-secret".into()), None).await;
        for account in ["../bad", "Bad Label", "", "a/b"] {
            let resp = reqwest::Client::new()
                .get(format!("{base}/token"))
                .query(&[("provider", "anthropic"), ("account", account)])
                .bearer_auth("machine-secret")
                .send()
                .await
                .unwrap();
            assert_eq!(resp.status(), 400, "{account:?}");
            let body = resp.text().await.unwrap();
            assert!(body.contains("invalid account") && !body.contains("access_token"), "{body}");
        }
    }

    // ── Muse is proxy-only (#216 I2) ────────────────────────────────────────

    /// The minted Muse Model API key never expires on its own and Muse is
    /// routed BrokerProxy, so `/token` must never vend it — for any slot.
    #[tokio::test]
    async fn token_endpoint_never_vends_muse() {
        let base = spawn_broker_service(Some("machine-secret".into()), None).await;
        let client = reqwest::Client::new();
        for query in [
            vec![("provider", "muse")],
            vec![("provider", "muse"), ("account", "default")],
            vec![("provider", "muse"), ("account", "work")],
            vec![("provider", "muse"), ("account", "auto")],
        ] {
            let resp = client
                .get(format!("{base}/token"))
                .query(&query)
                .bearer_auth("machine-secret")
                .send()
                .await
                .unwrap();
            assert_eq!(resp.status(), 400, "{query:?}");
            let body = resp.text().await.unwrap();
            assert!(!body.contains("access_token"), "{query:?}: {body}");
        }
    }

    /// `/proxy` is unaffected: a Muse proxy request still reaches the Muse
    /// endpoint policy (here: its allowlist refusing the key-mint path,
    /// checked before any credential or network access).
    #[tokio::test]
    async fn proxy_still_routes_muse_requests() {
        let base = spawn_broker_service(Some("machine-secret".into()), None).await;
        let resp = reqwest::Client::new()
            .post(format!("{base}/proxy"))
            .bearer_auth("machine-secret")
            .json(&json!({
                "provider": "muse",
                "method": "post",
                "path": "/muse-code/key",
                "body": {},
                "stream": false,
            }))
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 400);
        let body = resp.text().await.unwrap();
        assert!(
            !body.contains("unknown provider"),
            "muse is still a proxy provider: {body}"
        );
        assert!(body.contains("allow"), "the Muse path allowlist answered: {body}");
    }

    #[test]
    fn muse_is_excluded_from_token_vending_only() {
        assert_eq!(token_vending_provider("muse"), None);
        // Usage snapshots / cooldown reports keep their provider check.
        assert_eq!(broker_provider("muse"), Some(auth::OAuthProviderId::Muse));
        assert_eq!(
            token_vending_provider("anthropic"),
            Some(auth::OAuthProviderId::Anthropic)
        );
    }

    #[test]
    fn github_copilot_is_oauth_token_vending_allowlisted() {
        // Descriptor strategy permits /token for github-copilot (session token only).
        let id = broker_provider("github-copilot").expect("github-copilot must be allowlisted");
        assert_eq!(id, auth::OAuthProviderId::GitHubCopilot);
        assert_eq!(id.as_str(), "github-copilot");
        // Aliases are not canonical broker ids
        assert!(broker_provider("copilot").is_none());
        assert!(broker_provider("gh-copilot").is_none());
    }

    /// Proxy validation fails closed: OAuth providers and absolute/escaping
    /// paths are rejected before any upstream contact.
    #[tokio::test]
    async fn proxy_rejects_oauth_providers_and_bad_paths() {
        let base = spawn_broker_service(Some("machine-secret".into()), None).await;
        let client = reqwest::Client::new();

        for (provider, path) in [
            ("anthropic", "/v1/messages"),
            ("openai-codex", "/responses"),
            // `/v1/messages` is advertised by Anthropic-vendor Copilot rows but
            // the broker does not currently route it — must fail closed.
            ("github-copilot", "/v1/messages"),
            ("github-copilot", "/models/gpt-5.4/policy"),
            ("local", "https://evil.example/steal"),
            ("local", "/../../etc/passwd"),
        ] {
            let resp = client
                .post(format!("{base}/proxy"))
                .bearer_auth("machine-secret")
                .json(&json!({
                    "provider": provider,
                    "method": "post",
                    "path": path,
                    "stream": false,
                }))
                .send()
                .await
                .unwrap();
            assert_eq!(resp.status(), 400, "{provider} {path} must be rejected");
        }
    }

    /// Streaming forwarding: an authenticated /proxy stream call reaches the
    /// upstream with the BROKER-applied credential and the SSE bytes flow back
    /// to the client unmodified. The client never supplied a provider key.
    #[tokio::test]
    async fn proxy_streams_sse_and_applies_key_broker_side() {
        let seen_auth = Arc::new(std::sync::Mutex::new(String::new()));
        let upstream = spawn_sse_upstream(seen_auth.clone()).await;
        let base = spawn_broker_service(Some("machine-secret".into()), Some(upstream)).await;
        let client = reqwest::Client::new();

        let resp = client
            .post(format!("{base}/proxy"))
            .bearer_auth("machine-secret")
            .json(&proxy_body(true))
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 200);
        assert_eq!(
            resp.headers()
                .get("content-type")
                .and_then(|v| v.to_str().ok()),
            Some("text/event-stream")
        );
        let body = resp.text().await.unwrap();
        assert!(
            body.contains("data: {\"choices\""),
            "SSE payload forwarded: {body}"
        );
        assert!(body.contains("[DONE]"));
        // The upstream saw the broker-owned credential, not the machine token.
        assert_eq!(&*seen_auth.lock().unwrap(), "Bearer local");
    }

    /// Non-streaming proxy returns the JSON envelope RemoteBroker expects.
    #[tokio::test]
    async fn proxy_non_streaming_returns_status_envelope() {
        let seen_auth = Arc::new(std::sync::Mutex::new(String::new()));
        let upstream = spawn_sse_upstream(seen_auth.clone()).await;
        let base = spawn_broker_service(None, Some(upstream)).await;
        let client = reqwest::Client::new();
        let resp = client
            .post(format!("{base}/proxy"))
            .json(&proxy_body(false))
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 200);
        let envelope: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(envelope["status"], 200);
        assert!(envelope["body"].as_str().unwrap().contains("[DONE]"));
    }

    // ── Helper: rcgen self-signed cert ────────────────────────────────────────

    /// Mint a self-signed cert + PKCS#8 key pair for localhost.
    /// Returns (cert_pem_bytes, key_pem_bytes).
    pub(super) fn generate_test_cert_key() -> (Vec<u8>, Vec<u8>) {
        use rcgen::generate_simple_self_signed;
        let san = vec!["localhost".to_string(), "127.0.0.1".to_string()];
        let cert = generate_simple_self_signed(san).expect("rcgen cert generation should succeed");
        let cert_pem = cert.cert.pem().into_bytes();
        let key_pem = cert.signing_key.serialize_pem().into_bytes();
        (cert_pem, key_pem)
    }
}