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
@@ -249,6 +249,11 @@ impl Config {
|
||||
|
||||
/// Cross-field validation.
|
||||
pub fn validate(&self) -> Result<(), ConfigError> {
|
||||
if self.server.port == 0 {
|
||||
return Err(ConfigError::Invalid(
|
||||
"server.port must be greater than zero".into(),
|
||||
));
|
||||
}
|
||||
if !self.auth.enabled && !self.server.bind.is_loopback() {
|
||||
return Err(ConfigError::Invalid(format!(
|
||||
"auth.enabled = false is only allowed on a loopback bind address (server.bind = {})",
|
||||
@@ -291,6 +296,18 @@ mod tests {
|
||||
Config::load(file.map(Path::new), cli)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn port_zero_rejected() {
|
||||
Jail::expect_with(|_| {
|
||||
let cli = CliOverrides {
|
||||
port: Some(0),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(load(None, &cli).is_err());
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_only() {
|
||||
Jail::expect_with(|_| {
|
||||
|
||||
+32
-3
@@ -99,6 +99,11 @@ async fn main() -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Upper bounds for shutdown phases (the OTel flush adds up to 5s per
|
||||
/// provider, so the unit uses TimeoutStopSec=30).
|
||||
const DRAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
const EXPORTER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
|
||||
async fn serve(config: Config) -> Result<()> {
|
||||
let guard = telemetry::init(&config).context("initialising telemetry")?;
|
||||
let db = if config.auth.enabled {
|
||||
@@ -125,11 +130,35 @@ async fn serve(config: Config) -> Result<()> {
|
||||
signal_token.cancel();
|
||||
});
|
||||
|
||||
let result = server::serve_listener(listener, app, shutdown.clone()).await;
|
||||
// `serve_listener` returns once the shutdown token fires and connections
|
||||
// drain. If the token has not fired it is a server error, so return
|
||||
// immediately. Bound the drain so a stuck client cannot hang SIGTERM.
|
||||
let serving = server::serve_listener(listener, app, shutdown.clone());
|
||||
tokio::pin!(serving);
|
||||
let result = tokio::select! {
|
||||
r = &mut serving => r,
|
||||
_ = shutdown.cancelled() => {
|
||||
match tokio::time::timeout(DRAIN_TIMEOUT, &mut serving).await {
|
||||
Ok(r) => r,
|
||||
Err(_) => {
|
||||
tracing::warn!("graceful drain timed out; closing remaining connections");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
// Reached on signal or server error: stop everything, then flush OTel.
|
||||
shutdown.cancel();
|
||||
for h in exporters {
|
||||
let _ = h.await;
|
||||
let join_all = async {
|
||||
for h in exporters {
|
||||
let _ = h.await;
|
||||
}
|
||||
};
|
||||
if tokio::time::timeout(EXPORTER_TIMEOUT, join_all)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!("exporter tasks did not stop in time");
|
||||
}
|
||||
guard.shutdown().await;
|
||||
if let Some(pool) = pool {
|
||||
|
||||
+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