Share error_response and default host allowlist; drop AppResult

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YShymaPrXmc3KYRUg2HMSs
This commit is contained in:
ariandClaude Sonnet 5.5 committed 2026-10-16 08:57:21 -04:00
1 parent 66eb91bf01
commit d022ebeae5
5 files changed
+38 -60

No files matched your search

+7 -12
View File
@@ -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`.
+15 -1
View File
@@ -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<String> {
let mut v: Vec<String> = ["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)]
+4 -19
View File
@@ -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<T> = Result<T, AppError>;
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"));
+4 -11
View File
@@ -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<String> {
let s = &state.config.server;
let mut v: Vec<String> = ["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<String> {
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"));
}
+8 -17
View File
@@ -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<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());
}
let mut v = c.server.default_hosts();
v.extend(
c.server
.allowed_hosts
@@ -94,14 +88,11 @@ async fn host_guard(State(allowed): State<Arc<Vec<String>>>, 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,
}
}