Files
skyg-linux-tracker/src/server.rs
T

121 lines
3.5 KiB
Rust

//! Router assembly and the serve loop (P3). `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 axum::extract::{Request, State};
use axum::http::{header, StatusCode};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use axum::Json;
use crate::config::Config;
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())
}
/// Serve `app` on `listener` until `shutdown` is cancelled.
pub async fn serve_listener(
listener: tokio::net::TcpListener,
app: Router,
shutdown: CancellationToken,
) -> Result<()> {
let addr = listener.local_addr().context("local_addr")?;
tracing::info!(%addr, "listening");
axum::serve(listener, app)
.with_graceful_shutdown(async move { shutdown.cancelled().await })
.await
.context("server error")
}
fn allowed_hosts(c: &Config) -> Arc<Vec<String>> {
let mut v: Vec<String> = ["localhost", "127.0.0.1", "::1"]
.into_iter()
.map(String::from)
.collect();
if !c.server.bind.is_unspecified() {
v.push(c.server.bind.to_string());
}
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]:9109` -> `::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<Arc<Vec<String>>>, 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)) => (
StatusCode::FORBIDDEN,
Json(serde_json::json!({"error": {
"code": "forbidden_host",
"message": "Host header not allowed; add it to server.allowed_hosts",
}})),
)
.into_response(),
_ => next.run(req).await,
}
}
#[cfg(test)]
mod tests {
use super::host_only;
#[test]
fn host_parsing() {
assert_eq!(host_only("localhost:9109"), "localhost");
assert_eq!(host_only("[::1]:9109"), "::1");
assert_eq!(host_only("::1"), "::1");
assert_eq!(host_only("10.0.0.5"), "10.0.0.5");
}
}