From d022ebeae5735458e67923ce7be8589454b653d9 Mon Sep 17 00:00:00 2001 From: Ari Sosnovsky Date: Fri, 16 Oct 2026 08:57:21 -0400 Subject: [PATCH] Share error_response and default host allowlist; drop AppResult Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01YShymaPrXmc3KYRUg2HMSs --- src/api/mod.rs | 19 +++++++------------ src/config.rs | 16 +++++++++++++++- src/error.rs | 23 ++++------------------- src/mcp/mod.rs | 15 ++++----------- src/server.rs | 25 ++++++++----------------- 5 files changed, 38 insertions(+), 60 deletions(-) diff --git a/src/api/mod.rs b/src/api/mod.rs index 3fe2c0e..d2c87a1 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -1,4 +1,4 @@ -//! REST layer (WS-E owns `src/api/`). +//! REST layer. //! //! The router contains `/api/v1/*` handlers only (paths are relative; P3 //! nests it). `healthz` is public and mounted outside auth by `main.rs`. @@ -16,6 +16,7 @@ use std::time::Duration; use axum::extract::rejection::QueryRejection; use axum::extract::Query; +use axum::http::StatusCode; use axum::response::sse::{Event, KeepAlive, Sse}; use axum::{Json, Router}; use futures::Stream; @@ -23,7 +24,7 @@ use serde::de::DeserializeOwned; use tokio::sync::mpsc; use tokio_util::sync::CancellationToken; -use crate::error::AppError; +use crate::error::{error_response, AppError}; use crate::state::AppState; /// Routes under `/api/v1`, already bound to `state`. @@ -50,19 +51,13 @@ pub async fn not_found() -> AppError { AppError::NotFound("no such route".into()) } -/// 405 in the common error shape (`AppError` has no 405 variant, so this -/// renders the same JSON body with the right status). +/// 405 in the common error shape (`AppError` has no 405 variant). pub async fn method_not_allowed() -> axum::response::Response { - use axum::http::StatusCode; - use axum::response::IntoResponse; - ( + error_response( StatusCode::METHOD_NOT_ALLOWED, - Json(serde_json::json!({"error": { - "code": "method_not_allowed", - "message": "method not allowed", - }})), + "method_not_allowed", + "method not allowed", ) - .into_response() } /// Query extraction that reports failures as `AppError::BadRequest`. diff --git a/src/config.rs b/src/config.rs index 60dbbbe..6b599b2 100644 --- a/src/config.rs +++ b/src/config.rs @@ -58,6 +58,20 @@ pub struct TlsConfig { pub key_file: PathBuf, } +impl ServerConfig { + /// Host names always accepted: loopback plus `bind` (unless unspecified). + pub fn default_hosts(&self) -> Vec { + let mut v: Vec = ["localhost", "127.0.0.1", "::1"] + .into_iter() + .map(String::from) + .collect(); + if !self.bind.is_unspecified() { + v.push(self.bind.to_string()); + } + v + } +} + impl Default for ServerConfig { fn default() -> Self { Self { @@ -138,7 +152,7 @@ pub struct OtelLogsConfig { /// Glob allowlists for exported metrics. /// -/// Empty `units` means `*.service` and `*.timer` (DEC-7). Empty `containers` +/// Empty `units` means `*.service` and `*.timer`. Empty `containers` /// means all containers. #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] #[serde(default)] diff --git a/src/error.rs b/src/error.rs index f47a762..5edd76d 100644 --- a/src/error.rs +++ b/src/error.rs @@ -6,7 +6,6 @@ use axum::http::{header, HeaderValue, StatusCode}; use axum::response::{IntoResponse, Response}; use axum::Json; -use serde::Serialize; #[derive(Debug, Clone, thiserror::Error)] pub enum AppError { @@ -27,8 +26,6 @@ pub enum AppError { Internal(String), } -pub type AppResult = Result; - impl AppError { /// Stable machine-readable code used in REST bodies and MCP error data. pub fn code(&self) -> &'static str { @@ -64,26 +61,14 @@ impl AppError { } /// REST error body: `{"error": {"code": "...", "message": "..."}}`. -#[derive(Debug, Serialize)] -pub struct ErrorBody<'a> { - pub error: ErrorDetail<'a>, -} - -#[derive(Debug, Serialize)] -pub struct ErrorDetail<'a> { - pub code: &'a str, - pub message: &'a str, +pub fn error_response(status: StatusCode, code: &str, message: &str) -> Response { + let body = serde_json::json!({"error": {"code": code, "message": message}}); + (status, Json(body)).into_response() } impl IntoResponse for AppError { fn into_response(self) -> Response { - let body = ErrorBody { - error: ErrorDetail { - code: self.code(), - message: self.message(), - }, - }; - let mut resp = (self.status(), Json(body)).into_response(); + let mut resp = error_response(self.status(), self.code(), self.message()); if matches!(self, AppError::Unauthorized(_)) { resp.headers_mut() .insert(header::WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")); diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs index 388890b..f108515 100644 --- a/src/mcp/mod.rs +++ b/src/mcp/mod.rs @@ -1,7 +1,7 @@ -//! MCP server (WS-F). Tools, prompts and resources are thin projections over +//! MCP server. Tools, prompts and resources are thin projections over //! the `sources` traits; nothing here talks to D-Bus, journald or Docker. //! -//! Pinned `rmcp` 3.5.1 validates `Host` and `Origin` itself (DEC-8); `service` +//! Pinned `rmcp` 3.5.1 validates `Host` and `Origin` itself; `service` //! feeds it loopback names, `server.bind` and the configured extras. pub mod prompts; @@ -400,13 +400,7 @@ fn authority(ip: IpAddr) -> String { /// Allowed `Host` values: loopback names, `server.bind`, plus configured extras. fn allowed_hosts(state: &AppState) -> Vec { let s = &state.config.server; - let mut v: Vec = ["localhost", "127.0.0.1", "::1"] - .into_iter() - .map(String::from) - .collect(); - if !s.bind.is_unspecified() { - v.push(s.bind.to_string()); - } + let mut v = s.default_hosts(); v.extend(s.allowed_hosts.iter().cloned()); v } @@ -433,7 +427,7 @@ fn allowed_origins(state: &AppState) -> Vec { v } -/// Streamable HTTP config with Host/Origin validation (DEC-8). +/// Streamable HTTP config with Host/Origin validation. fn http_config(state: &AppState) -> StreamableHttpServerConfig { StreamableHttpServerConfig::default() .with_allowed_hosts(allowed_hosts(state)) @@ -541,7 +535,6 @@ mod tests { assert!(info.capabilities.tools.is_some()); assert!(info.capabilities.prompts.is_some()); let res = info.capabilities.resources.as_ref().unwrap(); - // DEC-5: no subscriptions. assert!(!res.subscribe.unwrap_or(false)); assert!(info.instructions.unwrap().contains("failed")); } diff --git a/src/server.rs b/src/server.rs index 7948250..99048ae 100644 --- a/src/server.rs +++ b/src/server.rs @@ -1,4 +1,4 @@ -//! Router assembly and the serve loop (P3). `build_router` is used by both +//! Router assembly and the serve loop. `build_router` is used by both //! `slinuxm serve` and the integration tests. use anyhow::{Context, Result}; @@ -12,10 +12,10 @@ 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 axum::response::Response; use crate::config::Config; +use crate::error::error_response; use crate::state::AppState; use crate::{api, auth, mcp}; @@ -57,13 +57,7 @@ pub async fn serve_listener( } fn allowed_hosts(c: &Config) -> Arc> { - let mut v: Vec = ["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()); - } + let mut v = c.server.default_hosts(); v.extend( c.server .allowed_hosts @@ -94,14 +88,11 @@ async fn host_guard(State(allowed): State>>, req: Request, next: .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)) => ( + Some(h) if !allowed.iter().any(|a| a.eq_ignore_ascii_case(h)) => error_response( StatusCode::FORBIDDEN, - Json(serde_json::json!({"error": { - "code": "forbidden_host", - "message": "Host header not allowed; add it to server.allowed_hosts", - }})), - ) - .into_response(), + "forbidden_host", + "Host header not allowed; add it to server.allowed_hosts", + ), _ => next.run(req).await, } }