P3 review follow-ups: bounded shutdown, unit hardening, host guard, more tests
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YShymaPrXmc3KYRUg2HMSs
This commit is contained in:
1 parent
acedb9522e
commit
533659dfc1
8 files changed
+355
-14
No files matched your search
+84
-1
@@ -7,13 +7,33 @@ 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", api::router(state.clone()))
|
||||
.nest("/api/v1", rest)
|
||||
.nest_service("/mcp", mcp::service(state.clone()))
|
||||
.layer(auth::layer(state));
|
||||
Router::new()
|
||||
@@ -35,3 +55,66 @@ pub async fn serve_listener(
|
||||
.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");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user