//! Router assembly and the serve loop. `build_router` is used by both //! `slinuxm serve` and the integration tests. use anyhow::{Context, Result}; use axum::routing::get; use axum::Router; use tokio_util::sync::CancellationToken; use tower_http::trace::TraceLayer; use std::sync::Arc; use std::time::Duration; use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer}; use hyper_util::server::conn::auto::Builder; use hyper_util::service::TowerToHyperService; use tokio::sync::Semaphore; use tokio::task::JoinSet; use tokio::time::Instant; use tokio_rustls::TlsAcceptor; use axum::extract::{Request, State}; use axum::http::{header, StatusCode}; use axum::middleware::Next; use axum::response::Response; use crate::config::Config; use crate::error::error_response; use crate::state::AppState; use crate::{api, auth, mcp}; /// `/healthz` public; `/api/v1/*` and `/mcp` behind the auth layer. pub fn build_router(state: AppState) -> Router { // With auth off there is no bearer gate, so guard REST against DNS // rebinding with a Host allowlist (MCP has its own check). let rest = api::router(state.clone()); let rest = if state.config.auth.enabled { rest } else { rest.layer(axum::middleware::from_fn_with_state( allowed_hosts(&state.config), host_guard, )) }; let protected = Router::new() .nest("/api/v1", rest) .nest_service("/mcp", mcp::service(state.clone())) .layer(auth::layer(state)); Router::new() .route("/healthz", get(api::healthz)) .merge(protected) .layer(TraceLayer::new_for_http()) } /// Connection limits shared by the plain and TLS listeners. #[derive(Debug, Clone, Copy)] pub struct Limits { /// Maximum concurrent connections (handshaking or established). At the /// cap, accepting pauses until a connection closes. pub max_conns: usize, /// Time allowed to receive a request header (also covers idle /// keep-alive and post-handshake silence). pub header_timeout: Duration, } impl Default for Limits { fn default() -> Self { Self { max_conns: 1024, header_timeout: Duration::from_secs(30), } } } const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10); /// Serve `app` on `listener` (over TLS when `acceptor` is set) until /// `shutdown` is cancelled, then drain: stop accepting, ask each connection /// to finish gracefully, and wait. The caller bounds the drain by dropping /// this future (which aborts the connections). pub async fn serve_listener( listener: tokio::net::TcpListener, acceptor: Option, app: Router, shutdown: CancellationToken, limits: Limits, ) -> Result<()> { let addr = listener.local_addr().context("local_addr")?; tracing::info!(%addr, tls = acceptor.is_some(), "listening"); let mut conns: JoinSet<()> = JoinSet::new(); let slots = Arc::new(Semaphore::new(limits.max_conns)); let mut last_accept_warn: Option = None; loop { // Wait for a free slot first, so at the cap we stop accepting. let permit = tokio::select! { _ = shutdown.cancelled() => break, Some(_) = conns.join_next(), if !conns.is_empty() => continue, p = slots.clone().acquire_owned() => match p { Ok(p) => p, Err(_) => break, }, }; tokio::select! { _ = shutdown.cancelled() => break, Some(_) = conns.join_next(), if !conns.is_empty() => {} r = listener.accept() => { let (tcp, peer) = match r { Ok(x) => x, Err(e) => { if last_accept_warn.is_none_or(|t| t.elapsed() > Duration::from_secs(10)) { tracing::warn!(error = %e, "accept failed (further failures suppressed for 10s)"); last_accept_warn = Some(Instant::now()); } tokio::time::sleep(Duration::from_millis(100)).await; continue; } }; let acceptor = acceptor.clone(); let svc = TowerToHyperService::new(app.clone()); let stop = shutdown.clone(); conns.spawn(async move { let _permit = permit; match acceptor { None => serve_conn(tcp, peer, svc, stop, limits).await, Some(acceptor) => { match tokio::time::timeout(HANDSHAKE_TIMEOUT, acceptor.accept(tcp)).await { Ok(Ok(tls)) => serve_conn(tls, peer, svc, stop, limits).await, Ok(Err(e)) => tracing::debug!(%peer, error = %e, "TLS handshake failed"), Err(_) => tracing::debug!(%peer, "TLS handshake timed out"), } } } }); } } } drop(listener); while conns.join_next().await.is_some() {} Ok(()) } async fn serve_conn( io: I, peer: std::net::SocketAddr, svc: TowerToHyperService, stop: CancellationToken, limits: Limits, ) where I: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static, { let mut builder = Builder::new(TokioExecutor::new()).http1_only(); builder .http1() .timer(TokioTimer::new()) .header_read_timeout(limits.header_timeout); // Plain serve_connection: the auto builder's _with_upgrades variant // sniffs the protocol first, which would defeat the header timeout for // silent clients. let conn = builder.serve_connection(TokioIo::new(io), svc); tokio::pin!(conn); tokio::select! { r = conn.as_mut() => { if let Err(e) = r { tracing::debug!(%peer, error = %e, "connection error"); } } _ = stop.cancelled() => { conn.as_mut().graceful_shutdown(); if let Err(e) = conn.as_mut().await { tracing::debug!(%peer, error = %e, "connection error"); } } } } fn allowed_hosts(c: &Config) -> Arc> { let mut v = c.server.default_hosts(); v.extend( c.server .allowed_hosts .iter() .map(|h| host_only(h).to_owned()), ); Arc::new(v) } /// Strip an optional port and IPv6 brackets: `[::1]:1984` -> `::1`. fn host_only(h: &str) -> &str { let h = h.trim(); if let Some(rest) = h.strip_prefix('[') { return rest.split(']').next().unwrap_or(rest); } match h.rsplit_once(':') { Some((host, port)) if !host.contains(':') && port.chars().all(|c| c.is_ascii_digit()) => { host } _ => h, } } async fn host_guard(State(allowed): State>>, req: Request, next: Next) -> Response { let host = req .headers() .get(header::HOST) .and_then(|v| v.to_str().ok()) .map(host_only); match host { Some(h) if !allowed.iter().any(|a| a.eq_ignore_ascii_case(h)) => error_response( StatusCode::FORBIDDEN, "forbidden_host", "Host header not allowed; add it to server.allowed_hosts", ), _ => next.run(req).await, } } #[cfg(test)] mod tests { use super::host_only; #[test] fn host_parsing() { assert_eq!(host_only("localhost:1984"), "localhost"); assert_eq!(host_only("[::1]:1984"), "::1"); assert_eq!(host_only("::1"), "::1"); assert_eq!(host_only("10.0.0.5"), "10.0.0.5"); } }