synaps 0.10.2

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
//! `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).
//!
//! 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, non-200 if cred missing)
//!   GET  /token?provider=X   -> { access_token, expires }  (machine-auth, OAuth providers ONLY)
//!   POST /proxy              -> typed broker proxy         (machine-auth, static-key providers;
//!                               the key is applied broker-side and never vended)
//!   GET  /usage              -> Anthropic usage JSON       (machine-auth, typed operation; the
//!                               OAuth token is resolved broker-side and never vended)
//!   GET  /capabilities       -> provider status list       (machine-auth, no secret values)

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)
}

// ── 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 safe on loopback or with explicit `--insecure-no-auth`).
    machine_token: Option<String>,
    /// HTTP client used for the (central, single) token refresh to the provider.
    client: reqwest::Client,
    /// The in-process broker that owns static keys and executes proxied
    /// requests. Raw keys never leave this boundary.
    local: Arc<auth::LocalBroker>,
}

/// 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>,
}

/// 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: refuse to start unauthenticated on a non-loopback bind unless the
    // operator explicitly opts in.
    if machine_token.is_none() && !addr.ip().is_loopback() && !insecure_no_auth {
        anyhow::bail!(
            "refusing to start: no machine token (set --machine-token-file / \
             SYNAPS_BROKER_TOKEN) while bound to non-loopback {addr}. That would serve credentials \
             unauthenticated to the network. Pass --insecure-no-auth to override, or bind 127.0.0.1."
        );
    }

    // D1: fail fast if the credential isn't present/readable.
    match auth::load_auth() {
        Ok(Some(_)) => {}
        Ok(None) => anyhow::bail!(
            "no credential at {}. Run `synaps login` 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(),
        client: client.clone(),
        local: Arc::new(auth::LocalBroker::new(client.clone())),
    };

    // Proactive refresh, SUPERVISED.
    {
        let refresh_client = client;
        let handle = tokio::spawn(async move {
            let mut tick = tokio::time::interval(Duration::from_secs(60));
            loop {
                tick.tick().await;
                if let Err(e) = auth::ensure_fresh_token(&refresh_client).await {
                    eprintln!("[auth-broker] proactive refresh failed: {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 — loopback/insecure only!"
                }
            );
            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 — loopback/insecure only!"
                }
            );
            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 client = reqwest::Client::new();
    let local = auth::LocalBroker::new(client.clone()).with_cloud_backend(backend);
    build_router(BrokerState {
        machine_token,
        client,
        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("/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))
        .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::load_auth() {
        Ok(Some(_)) => (StatusCode::OK, Json(json!({ "status": "ok" }))),
        Ok(None) => (
            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) {
        eprintln!("[auth-broker] DENIED from {} (bad machine auth)", peer.ip());
        return (
            StatusCode::UNAUTHORIZED,
            Json(json!({ "error": "bad machine auth" })),
        )
            .into_response();
    }

    // ── provider allowlist ──
    let provider = q.provider.unwrap_or_else(|| "anthropic".to_string());
    let Some(provider_id) = broker_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();
    };

    let creds = if provider_id == auth::OAuthProviderId::Anthropic {
        auth::ensure_fresh_token(&st.client).await
    } else {
        auth::ensure_fresh_provider_token(&st.client, provider_id).await
    };

    match creds {
        Ok(c) => {
            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 = c.expires.saturating_sub(now);
            eprintln!(
                "[auth-broker] issued {provider} token to {} (expires {})",
                peer.ip(),
                c.expires
            );
            (
                StatusCode::OK,
                Json(json!({ "access_token": c.access, "expires": c.expires, "ttl_ms": ttl_ms })),
            )
                .into_response()
        }
        Err(e) => {
            eprintln!(
                "[auth-broker] refresh failed for {provider} from {}: {}",
                peer.ip(),
                e
            );
            (
                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>,
    headers: HeaderMap,
    Json(request): Json<auth::ProxyRequest>,
) -> axum::response::Response {
    if !machine_auth_ok(&st, &headers) {
        return (
            StatusCode::UNAUTHORIZED,
            Json(json!({ "error": "bad machine auth" })),
        )
            .into_response();
    }
    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>, headers: HeaderMap) -> axum::response::Response {
    if !machine_auth_ok(&st, &headers) {
        return (
            StatusCode::UNAUTHORIZED,
            Json(json!({ "error": "bad machine auth" })),
        )
            .into_response();
    }
    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),
    }
}

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

async fn cloud_catalog(
    State(st): State<BrokerState>,
    headers: HeaderMap,
    Json(request): Json<CloudCatalogRequest>,
) -> axum::response::Response {
    if !machine_auth_ok(&st, &headers) {
        return (
            StatusCode::UNAUTHORIZED,
            Json(json!({"error":"bad machine auth"})),
        )
            .into_response();
    }
    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>,
    headers: HeaderMap,
    Json(request): Json<CloudInvokeRequest>,
) -> axum::response::Response {
    if !machine_auth_ok(&st, &headers) {
        return (
            StatusCode::UNAUTHORIZED,
            Json(json!({"error":"bad machine auth"})),
        )
            .into_response();
    }
    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>,
    headers: HeaderMap,
) -> axum::response::Response {
    if !machine_auth_ok(&st, &headers) {
        return (
            StatusCode::UNAUTHORIZED,
            Json(json!({ "error": "bad machine auth" })),
        )
            .into_response();
    }
    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::UnsupportedCapability { .. } => StatusCode::BAD_REQUEST,
        auth::BrokerError::NotConfigured(_) => StatusCode::FORBIDDEN,
        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 {
        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 state = BrokerState {
            machine_token,
            client,
            local: Arc::new(local),
        };
        let app = build_router(state);
        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();
        });
        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();
            let mut fields: Vec<&str> = obj.keys().map(String::as_str).collect();
            fields.sort_unstable();
            assert_eq!(
                fields,
                vec!["configured", "key", "kind", "name"],
                "capability rows carry status only — no credential fields"
            );
            assert!(obj["configured"].is_boolean());
        }
    }

    /// 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}"
            );
        }
    }

    #[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)
    }
}