Skip to main content

ibridge_server/
http.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Streamable HTTP wiring shared by the local daemon and the hosted router.
4
5use std::net::SocketAddr;
6use std::sync::Arc;
7
8use axum::extract::{Request, State};
9use axum::http::{HeaderMap, StatusCode, Uri, header};
10use axum::middleware::{self, Next};
11use axum::response::{IntoResponse as _, Response};
12use rmcp::ServerHandler;
13use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
14use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
15use tokio::net::TcpListener;
16
17pub use axum::Router;
18
19/// Answers whether a presented bearer token is accepted.
20pub type Verifier = Arc<dyn Fn(&str) -> bool + Send + Sync>;
21
22/// Why the HTTP server could not start.
23#[derive(Debug, thiserror::Error)]
24#[non_exhaustive]
25pub enum HttpError {
26    /// The address is not on the loopback interface.
27    #[error("{0} is not a loopback address; the local daemon only listens on 127.0.0.1 or ::1")]
28    NotLoopback(SocketAddr),
29    /// The socket could not be opened or served.
30    #[error("could not use the HTTP socket: {0}")]
31    Io(#[from] std::io::Error),
32}
33
34/// Checks that `addr` is a loopback address.
35///
36/// # Errors
37///
38/// Returns [`HttpError::NotLoopback`] for any other address.
39pub fn check_loopback(addr: SocketAddr) -> Result<SocketAddr, HttpError> {
40    if addr.ip().is_loopback() {
41        Ok(addr)
42    } else {
43        Err(HttpError::NotLoopback(addr))
44    }
45}
46
47/// Binds `addr` after checking that it is a loopback address.
48///
49/// # Errors
50///
51/// Returns [`HttpError::NotLoopback`] for any other address, or the I/O error from binding.
52pub async fn bind_loopback(addr: SocketAddr) -> Result<TcpListener, HttpError> {
53    Ok(TcpListener::bind(check_loopback(addr)?).await?)
54}
55
56/// The Streamable HTTP settings both modes share: JSON responses, with
57/// sessions for clients that negotiate a protocol older than 2026-07-28.
58#[must_use]
59pub fn base_config() -> StreamableHttpServerConfig {
60    StreamableHttpServerConfig::default()
61        .with_legacy_session_mode(true)
62        .with_json_response(true)
63}
64
65/// Wraps `factory` in the Streamable HTTP service.
66pub fn mcp_service<S>(
67    factory: impl Fn() -> S + Send + Sync + 'static,
68    config: StreamableHttpServerConfig,
69) -> StreamableHttpService<S, LocalSessionManager>
70where
71    S: ServerHandler + Send + 'static,
72{
73    StreamableHttpService::new(move || Ok(factory()), Arc::default(), config)
74}
75
76/// The local daemon's router: `/mcp` behind the Origin check, then the bearer check.
77///
78/// A request with a foreign `Origin` gets 403 whatever its token. Every other
79/// request needs `Authorization: Bearer <token>` with a token `verify` accepts,
80/// and gets 401 without one.
81pub fn local_router<S>(
82    service: StreamableHttpService<S, LocalSessionManager>,
83    verify: Verifier,
84) -> Router
85where
86    S: ServerHandler + Send + 'static,
87{
88    Router::new()
89        .nest_service("/mcp", service)
90        .layer(middleware::from_fn_with_state(verify, require_bearer))
91        .layer(middleware::from_fn(require_loopback_origin))
92}
93
94/// Answers 403 to a request whose `Origin` is not a loopback page.
95///
96/// A client with no `Origin` header (a CLI, an SDK) passes: only browsers send one.
97async fn require_loopback_origin(request: Request, next: Next) -> Response {
98    match request.headers().get(header::ORIGIN) {
99        None => next.run(request).await,
100        Some(origin) if origin.to_str().is_ok_and(is_loopback_origin) => next.run(request).await,
101        Some(_) => (StatusCode::FORBIDDEN, "Forbidden: Origin is not allowed").into_response(),
102    }
103}
104
105fn is_loopback_origin(origin: &str) -> bool {
106    let Ok(uri) = origin.parse::<Uri>() else {
107        return false;
108    };
109    let web = matches!(uri.scheme_str(), Some("http" | "https"));
110    let bare = uri.path_and_query().is_none_or(|path| path.as_str() == "/");
111    let host = uri.authority().is_some_and(|authority| {
112        // `http::Uri` treats `user@host` as userinfo; an Origin never has any.
113        !authority.as_str().contains('@')
114            && matches!(authority.host(), "localhost" | "127.0.0.1" | "[::1]")
115    });
116    web && bare && host
117}
118
119/// Answers 401 unless the request carries a bearer token `verify` accepts.
120async fn require_bearer(State(verify): State<Verifier>, request: Request, next: Next) -> Response {
121    if bearer_token(request.headers()).is_some_and(|token| verify(token)) {
122        next.run(request).await
123    } else {
124        (
125            StatusCode::UNAUTHORIZED,
126            [(header::WWW_AUTHENTICATE, "Bearer")],
127            "Unauthorized",
128        )
129            .into_response()
130    }
131}
132
133fn bearer_token(headers: &HeaderMap) -> Option<&str> {
134    let value = headers.get(header::AUTHORIZATION)?.to_str().ok()?;
135    let (scheme, token) = value.split_once(' ')?;
136    scheme.eq_ignore_ascii_case("Bearer").then_some(token)
137}
138
139/// Serves `app` on `listener` until `shutdown` finishes.
140///
141/// # Errors
142///
143/// Returns the I/O error that stopped the server.
144pub async fn serve(
145    listener: TcpListener,
146    app: Router,
147    shutdown: impl Future<Output = ()> + Send + 'static,
148) -> Result<(), HttpError> {
149    axum::serve(listener, app)
150        .with_graceful_shutdown(shutdown)
151        .await?;
152    Ok(())
153}