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:
1 parent
66eb91bf01
commit
d022ebeae5
5 files changed
+38
-60
No files matched your search
+7
-12
@@ -1,4 +1,4 @@
|
|||||||
//! REST layer (WS-E owns `src/api/`).
|
//! REST layer.
|
||||||
//!
|
//!
|
||||||
//! The router contains `/api/v1/*` handlers only (paths are relative; P3
|
//! The router contains `/api/v1/*` handlers only (paths are relative; P3
|
||||||
//! nests it). `healthz` is public and mounted outside auth by `main.rs`.
|
//! 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::rejection::QueryRejection;
|
||||||
use axum::extract::Query;
|
use axum::extract::Query;
|
||||||
|
use axum::http::StatusCode;
|
||||||
use axum::response::sse::{Event, KeepAlive, Sse};
|
use axum::response::sse::{Event, KeepAlive, Sse};
|
||||||
use axum::{Json, Router};
|
use axum::{Json, Router};
|
||||||
use futures::Stream;
|
use futures::Stream;
|
||||||
@@ -23,7 +24,7 @@ use serde::de::DeserializeOwned;
|
|||||||
use tokio::sync::mpsc;
|
use tokio::sync::mpsc;
|
||||||
use tokio_util::sync::CancellationToken;
|
use tokio_util::sync::CancellationToken;
|
||||||
|
|
||||||
use crate::error::AppError;
|
use crate::error::{error_response, AppError};
|
||||||
use crate::state::AppState;
|
use crate::state::AppState;
|
||||||
|
|
||||||
/// Routes under `/api/v1`, already bound to `state`.
|
/// Routes under `/api/v1`, already bound to `state`.
|
||||||
@@ -50,19 +51,13 @@ pub async fn not_found() -> AppError {
|
|||||||
AppError::NotFound("no such route".into())
|
AppError::NotFound("no such route".into())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 405 in the common error shape (`AppError` has no 405 variant, so this
|
/// 405 in the common error shape (`AppError` has no 405 variant).
|
||||||
/// renders the same JSON body with the right status).
|
|
||||||
pub async fn method_not_allowed() -> axum::response::Response {
|
pub async fn method_not_allowed() -> axum::response::Response {
|
||||||
use axum::http::StatusCode;
|
error_response(
|
||||||
use axum::response::IntoResponse;
|
|
||||||
(
|
|
||||||
StatusCode::METHOD_NOT_ALLOWED,
|
StatusCode::METHOD_NOT_ALLOWED,
|
||||||
Json(serde_json::json!({"error": {
|
"method_not_allowed",
|
||||||
"code": "method_not_allowed",
|
"method not allowed",
|
||||||
"message": "method not allowed",
|
|
||||||
}})),
|
|
||||||
)
|
)
|
||||||
.into_response()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Query extraction that reports failures as `AppError::BadRequest`.
|
/// Query extraction that reports failures as `AppError::BadRequest`.
|
||||||
|
|||||||
+15
-1
@@ -58,6 +58,20 @@ pub struct TlsConfig {
|
|||||||
pub key_file: PathBuf,
|
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 {
|
impl Default for ServerConfig {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
@@ -138,7 +152,7 @@ pub struct OtelLogsConfig {
|
|||||||
|
|
||||||
/// Glob allowlists for exported metrics.
|
/// 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.
|
/// means all containers.
|
||||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
|||||||
+4
-19
@@ -6,7 +6,6 @@
|
|||||||
use axum::http::{header, HeaderValue, StatusCode};
|
use axum::http::{header, HeaderValue, StatusCode};
|
||||||
use axum::response::{IntoResponse, Response};
|
use axum::response::{IntoResponse, Response};
|
||||||
use axum::Json;
|
use axum::Json;
|
||||||
use serde::Serialize;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, thiserror::Error)]
|
#[derive(Debug, Clone, thiserror::Error)]
|
||||||
pub enum AppError {
|
pub enum AppError {
|
||||||
@@ -27,8 +26,6 @@ pub enum AppError {
|
|||||||
Internal(String),
|
Internal(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
pub type AppResult<T> = Result<T, AppError>;
|
|
||||||
|
|
||||||
impl AppError {
|
impl AppError {
|
||||||
/// Stable machine-readable code used in REST bodies and MCP error data.
|
/// Stable machine-readable code used in REST bodies and MCP error data.
|
||||||
pub fn code(&self) -> &'static str {
|
pub fn code(&self) -> &'static str {
|
||||||
@@ -64,26 +61,14 @@ impl AppError {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// REST error body: `{"error": {"code": "...", "message": "..."}}`.
|
/// REST error body: `{"error": {"code": "...", "message": "..."}}`.
|
||||||
#[derive(Debug, Serialize)]
|
pub fn error_response(status: StatusCode, code: &str, message: &str) -> Response {
|
||||||
pub struct ErrorBody<'a> {
|
let body = serde_json::json!({"error": {"code": code, "message": message}});
|
||||||
pub error: ErrorDetail<'a>,
|
(status, Json(body)).into_response()
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
|
||||||
pub struct ErrorDetail<'a> {
|
|
||||||
pub code: &'a str,
|
|
||||||
pub message: &'a str,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IntoResponse for AppError {
|
impl IntoResponse for AppError {
|
||||||
fn into_response(self) -> Response {
|
fn into_response(self) -> Response {
|
||||||
let body = ErrorBody {
|
let mut resp = error_response(self.status(), self.code(), self.message());
|
||||||
error: ErrorDetail {
|
|
||||||
code: self.code(),
|
|
||||||
message: self.message(),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
let mut resp = (self.status(), Json(body)).into_response();
|
|
||||||
if matches!(self, AppError::Unauthorized(_)) {
|
if matches!(self, AppError::Unauthorized(_)) {
|
||||||
resp.headers_mut()
|
resp.headers_mut()
|
||||||
.insert(header::WWW_AUTHENTICATE, HeaderValue::from_static("Bearer"));
|
.insert(header::WWW_AUTHENTICATE, HeaderValue::from_static("Bearer"));
|
||||||
|
|||||||
+4
-11
@@ -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.
|
//! 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.
|
//! feeds it loopback names, `server.bind` and the configured extras.
|
||||||
|
|
||||||
pub mod prompts;
|
pub mod prompts;
|
||||||
@@ -400,13 +400,7 @@ fn authority(ip: IpAddr) -> String {
|
|||||||
/// Allowed `Host` values: loopback names, `server.bind`, plus configured extras.
|
/// Allowed `Host` values: loopback names, `server.bind`, plus configured extras.
|
||||||
fn allowed_hosts(state: &AppState) -> Vec<String> {
|
fn allowed_hosts(state: &AppState) -> Vec<String> {
|
||||||
let s = &state.config.server;
|
let s = &state.config.server;
|
||||||
let mut v: Vec<String> = ["localhost", "127.0.0.1", "::1"]
|
let mut v = s.default_hosts();
|
||||||
.into_iter()
|
|
||||||
.map(String::from)
|
|
||||||
.collect();
|
|
||||||
if !s.bind.is_unspecified() {
|
|
||||||
v.push(s.bind.to_string());
|
|
||||||
}
|
|
||||||
v.extend(s.allowed_hosts.iter().cloned());
|
v.extend(s.allowed_hosts.iter().cloned());
|
||||||
v
|
v
|
||||||
}
|
}
|
||||||
@@ -433,7 +427,7 @@ fn allowed_origins(state: &AppState) -> Vec<String> {
|
|||||||
v
|
v
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Streamable HTTP config with Host/Origin validation (DEC-8).
|
/// Streamable HTTP config with Host/Origin validation.
|
||||||
fn http_config(state: &AppState) -> StreamableHttpServerConfig {
|
fn http_config(state: &AppState) -> StreamableHttpServerConfig {
|
||||||
StreamableHttpServerConfig::default()
|
StreamableHttpServerConfig::default()
|
||||||
.with_allowed_hosts(allowed_hosts(state))
|
.with_allowed_hosts(allowed_hosts(state))
|
||||||
@@ -541,7 +535,6 @@ mod tests {
|
|||||||
assert!(info.capabilities.tools.is_some());
|
assert!(info.capabilities.tools.is_some());
|
||||||
assert!(info.capabilities.prompts.is_some());
|
assert!(info.capabilities.prompts.is_some());
|
||||||
let res = info.capabilities.resources.as_ref().unwrap();
|
let res = info.capabilities.resources.as_ref().unwrap();
|
||||||
// DEC-5: no subscriptions.
|
|
||||||
assert!(!res.subscribe.unwrap_or(false));
|
assert!(!res.subscribe.unwrap_or(false));
|
||||||
assert!(info.instructions.unwrap().contains("failed"));
|
assert!(info.instructions.unwrap().contains("failed"));
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-17
@@ -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.
|
//! `slinuxm serve` and the integration tests.
|
||||||
|
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
@@ -12,10 +12,10 @@ use std::sync::Arc;
|
|||||||
use axum::extract::{Request, State};
|
use axum::extract::{Request, State};
|
||||||
use axum::http::{header, StatusCode};
|
use axum::http::{header, StatusCode};
|
||||||
use axum::middleware::Next;
|
use axum::middleware::Next;
|
||||||
use axum::response::{IntoResponse, Response};
|
use axum::response::Response;
|
||||||
use axum::Json;
|
|
||||||
|
|
||||||
use crate::config::Config;
|
use crate::config::Config;
|
||||||
|
use crate::error::error_response;
|
||||||
use crate::state::AppState;
|
use crate::state::AppState;
|
||||||
use crate::{api, auth, mcp};
|
use crate::{api, auth, mcp};
|
||||||
|
|
||||||
@@ -57,13 +57,7 @@ pub async fn serve_listener(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn allowed_hosts(c: &Config) -> Arc<Vec<String>> {
|
fn allowed_hosts(c: &Config) -> Arc<Vec<String>> {
|
||||||
let mut v: Vec<String> = ["localhost", "127.0.0.1", "::1"]
|
let mut v = c.server.default_hosts();
|
||||||
.into_iter()
|
|
||||||
.map(String::from)
|
|
||||||
.collect();
|
|
||||||
if !c.server.bind.is_unspecified() {
|
|
||||||
v.push(c.server.bind.to_string());
|
|
||||||
}
|
|
||||||
v.extend(
|
v.extend(
|
||||||
c.server
|
c.server
|
||||||
.allowed_hosts
|
.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())
|
.and_then(|v| v.to_str().ok())
|
||||||
.map(host_only);
|
.map(host_only);
|
||||||
match host {
|
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,
|
StatusCode::FORBIDDEN,
|
||||||
Json(serde_json::json!({"error": {
|
"forbidden_host",
|
||||||
"code": "forbidden_host",
|
"Host header not allowed; add it to server.allowed_hosts",
|
||||||
"message": "Host header not allowed; add it to server.allowed_hosts",
|
),
|
||||||
}})),
|
|
||||||
)
|
|
||||||
.into_response(),
|
|
||||||
_ => next.run(req).await,
|
_ => next.run(req).await,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user