stdio2http 0.3.0

MCP stdio -> Streamable HTTP proxy
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
//! Axum wiring: `/healthz`, the `/mcp` Streamable HTTP mount, graceful shutdown.

use std::sync::Arc;
use std::time::Duration;

use anyhow::{Context, Result};
use axum::Router;
use axum::routing::{MethodFilter, get};
use http::StatusCode;
use rmcp::transport::streamable_http_server::{
    StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
};
use tokio_util::sync::CancellationToken;
use tower::Service;

use crate::auth::AuthState;
use crate::config::Config;
use crate::proxy::ProxyHandler;
use crate::upstream::Upstream;

/// What `/healthz` answers with.
pub const HEALTH_BODY: &str = "ok";

/// Every method the Streamable HTTP transport answers.
const ALL_METHODS: MethodFilter = MethodFilter::GET
    .or(MethodFilter::POST)
    .or(MethodFilter::DELETE)
    .or(MethodFilter::OPTIONS)
    .or(MethodFilter::HEAD)
    .or(MethodFilter::PUT)
    .or(MethodFilter::PATCH)
    .or(MethodFilter::TRACE);

/// Bound on the post-signal drain: open streams and stalled bodies are
/// dropped once this elapses, so the process always exits promptly.
const SHUTDOWN_GRACE: Duration = Duration::from_secs(3);

/// Build the rmcp transport configuration from our own config.
///
/// Cancelling `token` ends the SSE streams the service holds open, which is
/// what lets an idle `GET /mcp` stream stop pinning the process after a signal.
fn server_config(cfg: &Config, token: CancellationToken) -> StreamableHttpServerConfig {
    let mut config = StreamableHttpServerConfig::default();
    config.cancellation_token = token;

    if cfg.disable_allowed_hosts {
        tracing::warn!(
            "Host header validation is off; only do this behind a proxy that already validates it"
        );
        config = config.disable_allowed_hosts();
    } else if !cfg.allowed_hosts.is_empty() {
        config = config.with_allowed_hosts(cfg.allowed_hosts.clone());
    }

    if !cfg.allowed_origins.is_empty() {
        config = config.with_allowed_origins(cfg.allowed_origins.clone());
    }

    config
}

/// CORS layer answering browser preflight for the configured origins.
///
/// Returns `None` when no `--allowed-origin` is set, leaving routing (and
/// auth) untouched. The layer is an exact-origin allowlist: no wildcards, no
/// credentials, and only the preflight itself bypasses auth — every actual
/// data request still passes through the auth layer below.
fn cors_layer(cfg: &Config) -> Option<tower_http::cors::CorsLayer> {
    if cfg.allowed_origins.is_empty() {
        return None;
    }
    // Invalid entries cannot reach here through `Config::validate`; skip
    // them so a hand-built config still fails closed instead of panicking.
    let origins: Vec<http::HeaderValue> = cfg
        .allowed_origins
        .iter()
        .filter_map(|origin| origin.parse().ok())
        .collect();
    Some(
        tower_http::cors::CorsLayer::new()
            .allow_origin(tower_http::cors::AllowOrigin::list(origins))
            .allow_methods([http::Method::GET, http::Method::POST, http::Method::DELETE])
            .allow_headers(tower_http::cors::AllowHeaders::list([
                http::header::AUTHORIZATION,
                http::header::CONTENT_TYPE,
                http::HeaderName::from_static("x-api-key"),
                http::HeaderName::from_static("mcp-session-id"),
                http::HeaderName::from_static("mcp-protocol-version"),
                http::HeaderName::from_static("last-event-id"),
            ]))
            .expose_headers([http::HeaderName::from_static("mcp-session-id")]),
    )
}

/// Mount a Streamable HTTP service behind the auth layer, leaving `/healthz` open.
///
/// Generic over the service so tests can substitute a stub for the real child.
/// `healthy` reports whether the upstream child is still reachable; an
/// unhealthy proxy answers `/healthz` with 503 so orchestrators restart it.
pub fn router_with<S, F>(cfg: &Config, mcp: S, healthy: F) -> Router
where
    S: Service<http::Request<axum::body::Body>, Error = std::convert::Infallible>
        + Clone
        + Send
        + Sync
        + 'static,
    S::Response: axum::response::IntoResponse + 'static,
    S::Future: Send + 'static,
    F: Fn() -> bool + Clone + Send + Sync + 'static,
{
    // Session binding sits inside auth: auth (outer) sets `Principal`, the
    // session layer (inner) checks it. Keep this order; swapping the two
    // would run the check before the principal exists.
    let mut guarded = axum::routing::MethodRouter::new()
        .on_service(ALL_METHODS, mcp)
        .layer(axum::middleware::from_fn_with_state(
            crate::session_owner::SessionOwners::default(),
            crate::session_owner::enforce,
        ))
        .layer(axum::middleware::from_fn_with_state(
            AuthState::new(cfg.auth_mode, &cfg.api_keys),
            crate::auth::require,
        ));

    // CORS wraps auth (outermost): it answers preflight for configured
    // origins before auth runs, while every other request still passes
    // through auth. Added last so the layer ordering above is unaffected.
    if let Some(cors) = cors_layer(cfg) {
        guarded = guarded.layer(cors);
    }

    Router::new().route(&cfg.mcp_path, guarded).route(
        "/healthz",
        get(move || {
            let healthy = healthy.clone();
            async move {
                if healthy() {
                    (StatusCode::OK, HEALTH_BODY)
                } else {
                    (StatusCode::SERVICE_UNAVAILABLE, "upstream unavailable")
                }
            }
        }),
    )
}

/// Build the router backed by the shared upstream child.
pub fn router(cfg: &Config, upstream: &Arc<Upstream>, token: CancellationToken) -> Router {
    let peer = Arc::clone(upstream.peer());
    let peer_for_health = Arc::clone(upstream.peer());
    let info = Arc::new(upstream.info().clone());
    let service = StreamableHttpService::new(
        move || Ok(ProxyHandler::new(Arc::clone(&peer), Arc::clone(&info))),
        Arc::new(LocalSessionManager::default()),
        server_config(cfg, token),
    );
    router_with(cfg, service, move || !peer_for_health.is_transport_closed())
}

/// Bind the listener. Port `0` selects an ephemeral port.
///
/// # Errors
///
/// Returns an error if the address cannot be bound.
pub async fn bind(cfg: &Config) -> Result<tokio::net::TcpListener> {
    let addr = cfg.socket_addr();
    tokio::net::TcpListener::bind(addr)
        .await
        .with_context(|| format!("failed to bind {addr}"))
}

/// Resolve once the process is asked to stop.
async fn shutdown_signal() {
    let interrupt = async {
        let _ = tokio::signal::ctrl_c().await;
    };

    #[cfg(unix)]
    let terminate = async {
        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
            Ok(mut stream) => {
                stream.recv().await;
            }
            Err(error) => {
                tracing::error!(%error, "failed to install SIGTERM handler");
                std::future::pending::<()>().await;
            }
        }
    };

    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    tokio::select! {
        () = interrupt => tracing::info!("received SIGINT, shutting down"),
        () = terminate => tracing::info!("received SIGTERM, shutting down"),
    }
}

/// Serve until a shutdown signal arrives, then return so the caller can reap the child.
///
/// If the upstream child exits first, the shutdown token is cancelled so the
/// listener drains, and this returns an error so the process exits non-zero
/// and the orchestrator restarts it.
///
/// A configured certificate (or ACME selection) switches the listener to
/// HTTPS-only TLS on the same `host:port`; plain HTTP on that port then fails
/// at the handshake instead of serving. mTLS, when configured, is enforced by
/// rustls for every connection — `/healthz` included — while `/mcp` auth
/// modes apply unchanged on top.
///
/// # Errors
///
/// Returns an error if the address cannot be bound, the TLS identity cannot
/// be loaded, the upstream child exits, or the server fails.
pub async fn serve(cfg: &Config, upstream: &Arc<Upstream>) -> Result<()> {
    // One token per serve call: the signal task cancels it, which ends rmcp
    // SSE streams (via the server config) and trips every graceful shutdown
    // below. Nothing awaits the token while holding it; it is only cloned.
    let token = CancellationToken::new();
    let signal = token.clone();
    tokio::spawn(async move {
        shutdown_signal().await;
        signal.cancel();
    });

    spawn_upstream_watcher(upstream, &token);

    let result = if cfg.tls_enabled() {
        serve_tls(cfg, upstream, token.clone()).await
    } else {
        serve_plain(cfg, upstream, token.clone()).await
    };

    if upstream.peer().is_transport_closed() {
        return Err(anyhow::anyhow!("upstream MCP server exited"));
    }
    result
}

/// Cancel the shutdown token once the child is gone so an idle proxy does not
/// keep serving a dead upstream. The `serve` result is mapped to an error
/// separately so the process exits non-zero.
fn spawn_upstream_watcher(upstream: &Arc<Upstream>, token: &CancellationToken) {
    let peer = Arc::clone(upstream.peer());
    let token = token.clone();
    tokio::spawn(async move {
        loop {
            tokio::select! {
                () = token.cancelled() => break,
                () = tokio::time::sleep(Duration::from_secs(1)) => {}
            }
            if peer.is_transport_closed() {
                tracing::error!("upstream MCP server exited; shutting down");
                token.cancel();
                break;
            }
        }
    });
}

async fn serve_plain(
    cfg: &Config,
    upstream: &Arc<Upstream>,
    token: CancellationToken,
) -> Result<()> {
    let listener = bind(cfg).await?;
    let local = listener
        .local_addr()
        .context("listener has no local address")?;
    tracing::info!(%local, path = %cfg.mcp_path, "stdio2http listening");

    let server = axum::serve(listener, router(cfg, upstream, token.clone()))
        .with_graceful_shutdown(token.clone().cancelled_owned());
    // Axum's graceful drain waits out idle keep-alive and SSE streams, so an
    // open stream would pin the process indefinitely. Bound it: after the
    // signal plus `SHUTDOWN_GRACE`, return and drop the server, which closes
    // the remaining connections.
    tokio::select! {
        result = server => result.context("HTTP server failed"),
        () = async {
            token.cancelled().await;
            tokio::time::sleep(SHUTDOWN_GRACE).await;
        } => {
            tracing::warn!("shutdown grace expired; dropping open connections");
            Ok(())
        }
    }
}

async fn serve_tls(cfg: &Config, upstream: &Arc<Upstream>, token: CancellationToken) -> Result<()> {
    if cfg.has_manual_cert() {
        serve_manual_tls(cfg, upstream, token).await
    } else if cfg.uses_acme() {
        serve_acme(cfg, upstream, token).await
    } else {
        // mTLS-alone: `Config::validate` rejects this; fail closed here too so
        // a caller that skipped validation still gets the same message.
        anyhow::bail!(
            "--tls-client-ca* requires a server certificate (--tls-cert/--tls-key) or ACME (--acme-domain)"
        )
    }
}

async fn serve_manual_tls(
    cfg: &Config,
    upstream: &Arc<Upstream>,
    token: CancellationToken,
) -> Result<()> {
    let addr = cfg.socket_addr();
    let material = crate::tls::load(cfg).context("TLS setup failed")?;
    let info = &material.info;
    tracing::info!(
        %addr,
        path = %cfg.mcp_path,
        subject = %info.subject,
        expiry = %info.expiry,
        fingerprint = %info.fingerprint,
        mtls = info.mtls,
        acme = cfg.uses_acme(),
        "stdio2http listening (https)"
    );

    let tls = axum_server::tls_rustls::RustlsConfig::from_config(Arc::new(material.server_config));
    let handle = axum_server::Handle::new();
    let shutdown = handle.clone();
    let signal = token.clone();
    tokio::spawn(async move {
        signal.cancelled().await;
        shutdown.graceful_shutdown(Some(SHUTDOWN_GRACE));
    });

    axum_server::tls_rustls::bind_rustls(addr, tls)
        .handle(handle)
        .serve(router(cfg, upstream, token).into_make_service())
        .await
        .context("HTTPS server failed")
}

/// Serve HTTPS with an ACME-issued certificate, renewing in the background.
///
/// Bind order matters: the HTTP-01 challenge listener goes up first and stays
/// for the process lifetime (renewals need it), then `ensure_cert_with`
/// issues into the same shared token map the listener serves.
async fn serve_acme(
    cfg: &Config,
    upstream: &Arc<Upstream>,
    token: CancellationToken,
) -> Result<()> {
    use crate::acme::{AcmeConfig, AcmeManager, ChallengeTokens, serve_challenges};

    let acme_cfg = AcmeConfig::from_config(cfg).map_err(anyhow::Error::msg)?;
    let manager = AcmeManager::load_or_create(acme_cfg.clone()).await?;

    // The CA dials this port from outside, so it binds all interfaces rather
    // than `cfg.host`.
    let challenge_addr = std::net::SocketAddr::from(([0, 0, 0, 0], acme_cfg.http_port));
    let challenge_listener = tokio::net::TcpListener::bind(challenge_addr)
        .await
        .with_context(|| format!("failed to bind ACME challenge listener on {challenge_addr}"))?;
    let tokens = ChallengeTokens::new();
    {
        let tokens = tokens.clone();
        tokio::spawn(async move {
            if let Err(error) =
                serve_challenges(challenge_listener, tokens, shutdown_signal()).await
            {
                tracing::error!(error = format!("{error:#}"), "ACME challenge server failed");
            }
        });
    }

    // Without the `acme` feature this bails with the rebuild hint; with it,
    // this issues (or skips when the cache is fresh) into the shared map.
    manager.ensure_cert_with(&tokens).await?;

    let snapshot = manager
        .cert_handle()
        .current()
        .context("ACME issuance produced no certificate")?;
    // mTLS-with-ACME: the client CA still comes from `Config`.
    let ca_pem = crate::tls::client_ca_pem(cfg).context("TLS setup failed")?;
    let material = crate::tls::build(
        snapshot.cert_pem.as_bytes(),
        snapshot.key_pem.as_bytes(),
        ca_pem.as_deref(),
    )
    .context("TLS setup failed")?;
    let info = &material.info;
    let addr = cfg.socket_addr();
    tracing::info!(
        %addr,
        path = %cfg.mcp_path,
        subject = %info.subject,
        expiry = %info.expiry,
        fingerprint = %info.fingerprint,
        mtls = info.mtls,
        acme = true,
        "stdio2http listening (https)"
    );

    let tls = axum_server::tls_rustls::RustlsConfig::from_config(Arc::new(material.server_config));
    let handle = axum_server::Handle::new();
    let shutdown = handle.clone();
    let signal = token.clone();
    tokio::spawn(async move {
        signal.cancelled().await;
        shutdown.graceful_shutdown(Some(SHUTDOWN_GRACE));
    });

    // Renewals publish into the same shared map the challenge listener serves.
    // Dropping the handle detaches the task; it runs for the process lifetime.
    #[cfg(feature = "acme")]
    let _renewal_task = AcmeManager::spawn_renewal_task(&manager, tokens.clone());

    // Rotation watcher: renewals install into the shared handle; poll the
    // generation counter and reload the acceptor without dropping connections.
    {
        let cert = manager.cert_handle();
        let tls = tls.clone();
        let seen = snapshot.generation;
        tokio::spawn(async move {
            rotation_watcher(cert, tls, ca_pem, seen).await;
        });
    }

    axum_server::tls_rustls::bind_rustls(addr, tls)
        .handle(handle)
        .serve(router(cfg, upstream, token).into_make_service())
        .await
        .context("HTTPS server failed")
}

/// Poll the shared cert handle; on generation change, rebuild via
/// `tls::build` and swap with `reload_from_config`.
///
/// A full rebuild (rather than `reload_from_pem`) preserves the mTLS verifier:
/// axum-server's PEM reload helper installs `with_no_client_auth`, which would
/// silently drop client-certificate enforcement after the first rotation.
/// Never logs key material, only the new fingerprint and expiry.
async fn rotation_watcher(
    cert: crate::acme::SharedCert,
    tls: axum_server::tls_rustls::RustlsConfig,
    ca_pem: Option<Vec<u8>>,
    mut seen: u64,
) {
    loop {
        tokio::time::sleep(Duration::from_secs(60)).await;
        let Some(snapshot) = cert.current() else {
            continue;
        };
        if snapshot.generation == seen {
            continue;
        }
        seen = snapshot.generation;
        match crate::tls::build(
            snapshot.cert_pem.as_bytes(),
            snapshot.key_pem.as_bytes(),
            ca_pem.as_deref(),
        ) {
            Ok(material) => {
                tls.reload_from_config(Arc::new(material.server_config));
                tracing::info!(
                    generation = snapshot.generation,
                    expiry = ?snapshot.expiry,
                    fingerprint = %material.info.fingerprint,
                    "ACME certificate rotated"
                );
            }
            Err(error) => tracing::warn!(
                error = format!("{error:#}"),
                "ACME rotated chain failed to load; keeping the previous certificate"
            ),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;
    use http::StatusCode;
    use http_body_util::BodyExt as _;
    use std::convert::Infallible;
    use tower::ServiceExt as _;

    fn config(argv: &[&str]) -> Config {
        let mut full = vec!["stdio2http"];
        full.extend_from_slice(argv);
        Config::parse_from(full)
    }

    /// A stand-in for the rmcp service so router tests need no child process.
    ///
    /// Hand-written rather than `tower::service_fn` because `router_with`
    /// requires a `Send` future, which `service_fn` does not promise for an
    /// unboxed async block.
    #[derive(Clone, Copy)]
    struct StubService;

    impl Service<http::Request<axum::body::Body>> for StubService {
        type Response = axum::response::Response;
        type Error = Infallible;
        type Future = std::pin::Pin<
            Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>,
        >;

        fn poll_ready(
            &mut self,
            _cx: &mut std::task::Context<'_>,
        ) -> std::task::Poll<Result<(), Self::Error>> {
            std::task::Poll::Ready(Ok(()))
        }

        fn call(&mut self, _req: http::Request<axum::body::Body>) -> Self::Future {
            Box::pin(async {
                Ok(axum::response::Response::new(axum::body::Body::from(
                    "mcp-ok",
                )))
            })
        }
    }

    fn stub_service() -> StubService {
        StubService
    }

    /// Drive the router without binding a socket.
    async fn call(app: Router, uri: &str) -> (StatusCode, Vec<u8>) {
        let response = app
            .oneshot(
                http::Request::builder()
                    .uri(uri)
                    .body(axum::body::Body::empty())
                    .expect("request builds"),
            )
            .await
            .expect("router always responds");
        let status = response.status();
        let body = response
            .into_body()
            .collect()
            .await
            .expect("body collects")
            .to_bytes();
        (status, body.to_vec())
    }

    #[test]
    fn default_config_keeps_loopback_only_host_validation() {
        let server = server_config(&config(&["--command", "s"]), CancellationToken::new());
        assert_eq!(server.allowed_hosts, ["localhost", "127.0.0.1", "::1"]);
    }

    #[test]
    fn allowed_hosts_replace_the_default_list() {
        let cfg = config(&[
            "--command",
            "s",
            "--allowed-host",
            "proxy.internal",
            "--allowed-host",
            "proxy.internal:8080",
        ]);
        assert_eq!(
            server_config(&cfg, CancellationToken::new()).allowed_hosts,
            ["proxy.internal", "proxy.internal:8080"]
        );
    }

    #[test]
    fn disabling_allowed_hosts_empties_the_list() {
        let cfg = config(&["--command", "s", "--disable-allowed-hosts"]);
        assert_eq!(
            server_config(&cfg, CancellationToken::new()).allowed_hosts,
            Vec::<String>::new()
        );
    }

    #[test]
    fn allowed_origins_are_forwarded() {
        let cfg = config(&[
            "--command",
            "s",
            "--allowed-origin",
            "https://app.example.com",
        ]);
        assert_eq!(
            server_config(&cfg, CancellationToken::new()).allowed_origins,
            ["https://app.example.com"]
        );
    }

    #[test]
    fn server_config_carries_the_shutdown_token() {
        let token = CancellationToken::new();
        let server = server_config(&config(&["--command", "s"]), token.clone());
        assert!(!server.cancellation_token.is_cancelled());
        token.cancel();
        assert!(server.cancellation_token.is_cancelled());
    }

    #[tokio::test]
    async fn health_endpoint_is_not_behind_auth() {
        let cfg = config(&["--command", "s", "--auth-mode", "bearer", "--api-key", "k"]);

        let (status, body) = call(router_with(&cfg, stub_service(), || true), "/healthz").await;

        assert_eq!(status, StatusCode::OK);
        assert_eq!(body, HEALTH_BODY.as_bytes());
    }

    #[tokio::test]
    async fn unhealthy_reports_service_unavailable() {
        let cfg = config(&["--command", "s"]);

        let (status, body) = call(router_with(&cfg, stub_service(), || false), "/healthz").await;

        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
        assert_eq!(body, b"upstream unavailable");
    }

    #[tokio::test]
    async fn mcp_route_is_mounted_at_the_configured_path() {
        let cfg = config(&["--command", "s", "--mcp-path", "/rpc"]);

        let (status, body) = call(router_with(&cfg, stub_service(), || true), "/rpc").await;

        assert_eq!(status, StatusCode::OK);
        assert_eq!(body, b"mcp-ok");
    }

    #[tokio::test]
    async fn unknown_paths_are_not_routed_to_the_child() {
        let cfg = config(&["--command", "s"]);

        let (status, _) = call(router_with(&cfg, stub_service(), || true), "/nope").await;

        assert_eq!(status, StatusCode::NOT_FOUND);
    }

    /// A stub that mints a session id when the request carries none, mimicking
    /// rmcp's `initialize` without a child process.
    #[derive(Clone, Copy)]
    struct SessionIssuingStub;

    impl Service<http::Request<axum::body::Body>> for SessionIssuingStub {
        type Response = axum::response::Response;
        type Error = Infallible;
        type Future = std::pin::Pin<
            Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>,
        >;

        fn poll_ready(
            &mut self,
            _cx: &mut std::task::Context<'_>,
        ) -> std::task::Poll<Result<(), Self::Error>> {
            std::task::Poll::Ready(Ok(()))
        }

        fn call(&mut self, req: http::Request<axum::body::Body>) -> Self::Future {
            Box::pin(async move {
                if req.headers().contains_key("mcp-session-id") {
                    Ok(axum::response::Response::new(axum::body::Body::from(
                        "mcp-ok",
                    )))
                } else {
                    Ok(axum::response::Response::builder()
                        .header("mcp-session-id", "sess-order")
                        .body(axum::body::Body::from("created"))
                        .expect("response builds"))
                }
            })
        }
    }

    /// Drive the router with a key and an optional session id.
    async fn call_authed(
        app: Router,
        key: &str,
        session: Option<&str>,
    ) -> (StatusCode, Vec<u8>, Option<String>) {
        let mut builder = http::Request::builder()
            .uri("/mcp")
            .method(http::Method::POST)
            .header(http::header::AUTHORIZATION, format!("Bearer {key}"));
        if let Some(id) = session {
            builder = builder.header("mcp-session-id", id);
        }
        let response = app
            .oneshot(
                builder
                    .body(axum::body::Body::empty())
                    .expect("request builds"),
            )
            .await
            .expect("router always responds");
        let status = response.status();
        let new_session = response
            .headers()
            .get("mcp-session-id")
            .and_then(|value| value.to_str().ok())
            .map(str::to_owned);
        let body = response
            .into_body()
            .collect()
            .await
            .expect("body collects")
            .to_bytes()
            .to_vec();
        (status, body, new_session)
    }

    #[tokio::test]
    async fn session_layer_sits_inside_auth() {
        let cfg = config(&[
            "--command",
            "s",
            "--auth-mode",
            "bearer",
            "--api-key",
            "k1",
            "--api-key",
            "k2",
        ]);
        let app = router_with(&cfg, SessionIssuingStub, || true);

        let (status, _, issued) = call_authed(app.clone(), "k1", None).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(issued.as_deref(), Some("sess-order"));

        // Another key reusing the session is denied: enforce saw Principal(1)
        // set by the outer auth layer. With the layers swapped, enforce would
        // run before auth, see no principal, and let this through with 200.
        let (status, body, _) = call_authed(app.clone(), "k2", Some("sess-order")).await;
        assert_eq!(status, StatusCode::NOT_FOUND);
        assert_eq!(body, b"Not Found: Session not found");

        // The owning key still passes.
        let (status, body, _) = call_authed(app, "k1", Some("sess-order")).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body, b"mcp-ok");
    }

    /// A browser preflight: OPTIONS with Origin and Access-Control-Request-Method.
    fn preflight(origin: &str) -> http::Request<axum::body::Body> {
        http::Request::builder()
            .uri("/mcp")
            .method(http::Method::OPTIONS)
            .header(http::header::ORIGIN, origin)
            .header(http::header::ACCESS_CONTROL_REQUEST_METHOD, "POST")
            .body(axum::body::Body::empty())
            .expect("request builds")
    }

    /// Drive the router with a fully built request.
    async fn call_request(
        app: Router,
        req: http::Request<axum::body::Body>,
    ) -> http::Response<axum::body::Body> {
        app.oneshot(req).await.expect("router always responds")
    }

    #[tokio::test]
    async fn preflight_from_allowed_origin_succeeds_without_key() {
        let cfg = config(&[
            "--command",
            "s",
            "--auth-mode",
            "bearer",
            "--api-key",
            "k",
            "--allowed-origin",
            "https://app.example.com",
        ]);

        let response = call_request(
            router_with(&cfg, stub_service(), || true),
            preflight("https://app.example.com"),
        )
        .await;

        assert!(
            response.status().is_success(),
            "preflight from a configured origin must succeed, got {}",
            response.status()
        );
        assert_eq!(
            response
                .headers()
                .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN),
            Some(&http::HeaderValue::from_static("https://app.example.com")),
            "preflight must echo the allowed origin",
        );
    }

    #[tokio::test]
    async fn preflight_from_unknown_origin_gets_no_allow_origin() {
        let cfg = config(&[
            "--command",
            "s",
            "--auth-mode",
            "bearer",
            "--api-key",
            "k",
            "--allowed-origin",
            "https://app.example.com",
        ]);

        let response = call_request(
            router_with(&cfg, stub_service(), || true),
            preflight("https://evil.example.com"),
        )
        .await;

        assert!(
            !response
                .headers()
                .contains_key(http::header::ACCESS_CONTROL_ALLOW_ORIGIN),
            "unlisted origins must get no access-control-allow-origin header, got {:?}",
            response.headers(),
        );
    }

    #[tokio::test]
    async fn options_without_configured_origins_still_needs_a_key() {
        let cfg = config(&["--command", "s", "--auth-mode", "bearer", "--api-key", "k"]);

        let response = call_request(
            router_with(&cfg, stub_service(), || true),
            preflight("https://app.example.com"),
        )
        .await;

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn non_options_requests_still_need_a_key_with_origins_configured() {
        let cfg = config(&[
            "--command",
            "s",
            "--auth-mode",
            "bearer",
            "--api-key",
            "k",
            "--allowed-origin",
            "https://app.example.com",
        ]);

        let response = call_request(
            router_with(&cfg, stub_service(), || true),
            http::Request::builder()
                .uri("/mcp")
                .method(http::Method::POST)
                .header(http::header::ORIGIN, "https://app.example.com")
                .body(axum::body::Body::empty())
                .expect("request builds"),
        )
        .await;

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }
}