Files
crank/crates/crank-community-mcp/src/transport.rs
T
bsodfather a438c1df42
CI / UI Checks (pull_request) Successful in 11s
CI / Rust Checks (pull_request) Failing after 4m11s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Failing after 1s
CI / Deploy (pull_request) Skipped
feat(epic3): безопасное structured logging MCP (Story 3.18)
Story 3.18 (#25) surface: клиент получает только закрытые structured
`notifications/message` выбранного уровня, без запросов, секретов и
internal causes.

- `logging` capability advertising в обеих поддерживаемых revisions;
  `logging/setLevel` — legacy-only dispatch (modern — `_meta` per request);
- закрытый словарь LoggingLevel (RFC 5424), malformed → -32602 с одним
  safe detail; закрытый набор safe events, task-local request scope;
  bounded in-memory opt-in, без миграций;
- `notifications/message` идут перед ответом в SSE; JSON-режим их не несёт;
- ATDD в `scripts/ci-story-checks.sh`: mcp_logging (10), inventory projection (3),
  protocol::logging unit (12);
- проекция capability inventory/frozen oracle переведена на `logging`.

Story ATDD и affected проверки пройдены на этом дереве (fmt, clippy,
python oracle 56 OK, capability inventory valid). Полный `just verify` —
NOT_RUN на story по validation-policy, остаётся на собранной фиче.
2026-10-25 12:50:00 +00:00

451 lines
14 KiB
Rust

use std::{convert::Infallible, time::Duration};
use axum::{
Json,
http::{
HeaderMap, HeaderValue, StatusCode,
header::{self, ACCEPT, HeaderName},
},
response::{
IntoResponse, Response,
sse::{Event, KeepAlive, Sse},
},
};
use crank_metrics::McpOutcome;
use futures_util::stream;
use reqwest::Url;
use serde_json::Value;
use crate::jsonrpc::{LEGACY_PROTOCOL_VERSION, negotiated_protocol_version};
pub(super) const HEADER_MCP_SESSION_ID: &str = "MCP-Session-Id";
pub(super) const HEADER_MCP_PROTOCOL_VERSION: &str = "MCP-Protocol-Version";
pub(super) const HEADER_X_REQUEST_ID: HeaderName = HeaderName::from_static("x-request-id");
#[derive(Clone, Copy)]
pub(super) enum ResponseMode {
Json,
Sse,
}
#[derive(Clone)]
pub(super) struct AllowedOrigins {
public_origin: Option<String>,
}
impl AllowedOrigins {
pub(super) fn new(public_base_url: Option<String>) -> Self {
Self {
public_origin: public_base_url.and_then(|value| extract_origin(&value)),
}
}
pub(super) fn is_allowed(&self, origin: &str) -> bool {
let Some(origin) = parse_origin(origin, true) else {
return false;
};
if is_loopback_origin(&origin) {
return true;
}
match &self.public_origin {
Some(public_origin) => public_origin == &origin.origin().ascii_serialization(),
None => false,
}
}
}
fn is_loopback_origin(origin: &Url) -> bool {
matches!(origin.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"))
}
fn parse_origin(value: &str, origin_only: bool) -> Option<Url> {
let origin = Url::parse(value).ok()?;
if !matches!(origin.scheme(), "http" | "https")
|| origin.host_str().is_none()
|| !origin.username().is_empty()
|| origin.password().is_some()
{
return None;
}
if origin_only
&& (origin.path() != "/" || origin.query().is_some() || origin.fragment().is_some())
{
return None;
}
Some(origin)
}
pub(super) fn validate_origin(
allowed_origins: &AllowedOrigins,
headers: &HeaderMap,
) -> Result<(), StatusCode> {
let Some(origin) = headers.get(header::ORIGIN) else {
return Ok(());
};
let Ok(origin) = origin.to_str() else {
return Err(StatusCode::FORBIDDEN);
};
if allowed_origins.is_allowed(origin) {
return Ok(());
}
Err(StatusCode::FORBIDDEN)
}
/// The media types of the `Accept` header, in the client's preference order.
///
/// `None` means the header is absent or not text; both are the caller's own admission decision.
fn accepted_media_types(headers: &HeaderMap) -> Option<Vec<String>> {
let accept = headers.get(ACCEPT)?.to_str().ok()?;
Some(
accept
.split(',')
.map(|part| {
part.split(';')
.next()
.unwrap_or_default()
.trim()
.to_ascii_lowercase()
})
.collect(),
)
}
/// Whether this request offered `text/event-stream`.
///
/// Story 3.18: the SSE response stream is the only carrier of a server `notifications/message`, so
/// the logging projection asks this before it promises a notification. It is the same admission rule
/// the response-mode negotiation already applies, not a second interpretation of the header.
pub(super) fn accepts_event_stream(headers: &HeaderMap) -> bool {
accepted_media_types(headers).is_some_and(|media_types| {
media_types
.iter()
.any(|media_type| media_type == "text/event-stream")
})
}
pub(super) fn negotiate_post_response_mode(
headers: &HeaderMap,
) -> Result<ResponseMode, StatusCode> {
let Some(media_types) = accepted_media_types(headers) else {
return Err(StatusCode::BAD_REQUEST);
};
let mut saw_json = false;
let mut saw_sse = false;
let mut preferred = None;
for media_type in media_types {
match media_type.as_str() {
"application/json" => {
saw_json = true;
if preferred.is_none() {
preferred = Some(ResponseMode::Json);
}
}
"text/event-stream" => {
saw_sse = true;
if preferred.is_none() {
preferred = Some(ResponseMode::Sse);
}
}
_ => {}
}
}
if saw_json || saw_sse {
return preferred.ok_or(StatusCode::NOT_ACCEPTABLE);
}
Err(StatusCode::NOT_ACCEPTABLE)
}
pub(super) fn validate_get_accept_header(headers: &HeaderMap) -> Result<(), StatusCode> {
let Some(media_types) = accepted_media_types(headers) else {
return Err(StatusCode::BAD_REQUEST);
};
if media_types
.iter()
.any(|media_type| media_type == "text/event-stream")
{
return Ok(());
}
Err(StatusCode::NOT_ACCEPTABLE)
}
/// Read a singleton identity carrier.
///
/// Pinned HTTP semantics allow repeated header lines, so the ingress must decide what a repeated
/// carrier means instead of silently reading the first value. Identical duplicates carry no ambiguity
/// and collapse deterministically to one value; conflicting duplicates are an ambiguous identity and
/// are rejected. A non-text value is rejected as well.
pub(super) fn singleton_header<'a>(
headers: &'a HeaderMap,
name: &str,
) -> Result<Option<&'a str>, StatusCode> {
let mut values = headers.get_all(name).iter();
let Some(first) = values.next() else {
return Ok(None);
};
let first = first.to_str().map_err(|_| StatusCode::BAD_REQUEST)?;
for value in values {
let value = value.to_str().map_err(|_| StatusCode::BAD_REQUEST)?;
if value != first {
return Err(StatusCode::BAD_REQUEST);
}
}
Ok(Some(first))
}
/// Negotiated revision carried by the request header.
///
/// A missing header is reported as `None` rather than being replaced by an implicit default: the
/// withdrawn `2025-03-26` fallback is no longer served. Era resolution (header vs body identity,
/// mismatch and unsupported handling) happens in the request pipeline. Conflicting duplicate
/// carriers are rejected here, so no caller can resolve an ambiguous identity to the first value.
pub(super) fn protocol_version_from_headers(
headers: &HeaderMap,
) -> Result<Option<String>, StatusCode> {
Ok(singleton_header(headers, HEADER_MCP_PROTOCOL_VERSION)?.map(str::to_owned))
}
pub(super) fn validate_session_protocol_version(
headers: &HeaderMap,
negotiated_session_version: &str,
) -> Result<(), StatusCode> {
let Some(version) = singleton_header(headers, HEADER_MCP_PROTOCOL_VERSION)? else {
return Ok(());
};
if negotiated_protocol_version(version).is_none() {
return Err(StatusCode::BAD_REQUEST);
}
if version != negotiated_session_version {
return Err(StatusCode::BAD_REQUEST);
}
Ok(())
}
pub(super) fn session_id_from_headers(headers: &HeaderMap) -> Result<Option<String>, StatusCode> {
Ok(singleton_header(headers, HEADER_MCP_SESSION_ID)?.map(str::to_owned))
}
pub(super) fn json_response(
status: StatusCode,
payload: Value,
session_id: Option<&str>,
protocol_version: Option<&str>,
) -> Response {
let outcome = payload_outcome(&payload);
let mut response = (status, Json(payload)).into_response();
if let Some(outcome) = outcome {
response.extensions_mut().insert(outcome);
}
if let Some(session_id) = session_id {
response.headers_mut().insert(
HEADER_MCP_SESSION_ID,
HeaderValue::from_str(session_id)
.unwrap_or_else(|_| HeaderValue::from_static("invalid")),
);
}
if let Some(protocol_version) = protocol_version {
response.headers_mut().insert(
HEADER_MCP_PROTOCOL_VERSION,
HeaderValue::from_str(protocol_version)
.unwrap_or_else(|_| HeaderValue::from_static(LEGACY_PROTOCOL_VERSION)),
);
}
response
}
pub(super) fn transport_response(
status: StatusCode,
payload: Value,
response_mode: ResponseMode,
session_id: Option<&str>,
protocol_version: Option<&str>,
) -> Response {
let outcome = payload_outcome(&payload);
// Story 3.18: this is the single projection point of the adapter's own safe structured event.
// The severity is derived from the already-decided outcome of the payload, so no request payload,
// credential, error cause or user value is read here.
note_logging_outcome(&payload);
let notifications = crate::protocol::take_notifications();
// A pending `notifications/message` has no carrier in a JSON body. When the client offered both
// media types and opted in to logging, the negotiated mode is the SSE stream, so the notification
// precedes the response instead of being silently dropped.
let response_mode = if notifications.is_empty() {
response_mode
} else {
ResponseMode::Sse
};
if status == StatusCode::OK && matches!(response_mode, ResponseMode::Sse) {
let mut messages = Vec::with_capacity(notifications.len() + 1);
for notification in notifications {
messages.push(Ok(Event::default().data(notification.to_string())));
}
messages.push(Ok(Event::default().data(payload.to_string())));
let stream = stream::iter(messages);
let mut response = sse_response(status, stream, session_id, protocol_version);
if let Some(outcome) = outcome {
response.extensions_mut().insert(outcome);
}
return response;
}
json_response(status, payload, session_id, protocol_version)
}
/// Record the closed safe event of one response: served, rejected as invalid, failed, or a tool-level
/// error. Every label is a fixed string of the closed vocabulary; nothing from the payload or the
/// request is copied into it.
fn note_logging_outcome(payload: &Value) {
use crate::protocol::{EVENT_FAILED, EVENT_REJECTED, EVENT_SERVED, LogLevel, note};
if payload.get("error").is_some() {
match payload.pointer("/error/code").and_then(Value::as_i64) {
// The pinned client-error codes: a malformed request, a method that this era does not
// implement, and invalid params. The client can correct all three, so they are a
// rejection rather than a server failure; the closed label stays the one client-error
// label of the vocabulary instead of growing a new one.
Some(-32602..=-32600) => note(LogLevel::Warning, EVENT_REJECTED, "invalid_params"),
_ => note(LogLevel::Error, EVENT_FAILED, "internal"),
}
return;
}
if payload
.pointer("/result/isError")
.and_then(Value::as_bool)
.unwrap_or(false)
{
note(LogLevel::Warning, EVENT_REJECTED, "tool_error");
return;
}
note(LogLevel::Info, EVENT_SERVED, "ok");
}
fn payload_outcome(payload: &Value) -> Option<McpOutcome> {
if payload.get("error").is_some() {
return Some(McpOutcome::JsonRpcError);
}
if payload
.pointer("/result/isError")
.and_then(Value::as_bool)
.unwrap_or(false)
{
return Some(McpOutcome::ToolError);
}
None
}
pub(super) fn with_request_id_header(mut response: Response, request_id: &str) -> Response {
if let Ok(value) = HeaderValue::from_str(request_id) {
response.headers_mut().insert(HEADER_X_REQUEST_ID, value);
}
response
}
pub(super) fn sse_response<S>(
status: StatusCode,
stream: S,
session_id: Option<&str>,
protocol_version: Option<&str>,
) -> Response
where
S: futures_util::stream::Stream<Item = Result<Event, Infallible>> + Send + 'static,
{
let mut response = (
status,
Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(15))),
)
.into_response();
if let Some(session_id) = session_id {
response.headers_mut().insert(
HEADER_MCP_SESSION_ID,
HeaderValue::from_str(session_id)
.unwrap_or_else(|_| HeaderValue::from_static("invalid")),
);
}
if let Some(protocol_version) = protocol_version {
response.headers_mut().insert(
HEADER_MCP_PROTOCOL_VERSION,
HeaderValue::from_str(protocol_version)
.unwrap_or_else(|_| HeaderValue::from_static(LEGACY_PROTOCOL_VERSION)),
);
}
response
}
pub(super) fn extract_origin(url: &str) -> Option<String> {
Some(parse_origin(url, false)?.origin().ascii_serialization())
}
#[cfg(test)]
mod tests {
use super::AllowedOrigins;
#[test]
fn allows_loopback_origins_with_and_without_port() {
let origins = AllowedOrigins::new(None);
assert!(origins.is_allowed("http://localhost"));
assert!(origins.is_allowed("http://localhost:3000"));
assert!(origins.is_allowed("https://127.0.0.1:8443"));
assert!(origins.is_allowed("http://[::1]:3000"));
}
#[test]
fn rejects_hosts_that_only_prefix_match_loopback() {
let origins = AllowedOrigins::new(None);
assert!(!origins.is_allowed("http://localhost.attacker.com"));
assert!(!origins.is_allowed("http://127.0.0.1.attacker.com"));
assert!(!origins.is_allowed("http://localhost@attacker.com"));
assert!(!origins.is_allowed("http://attacker.com/http://localhost"));
assert!(!origins.is_allowed("http://[::1].attacker.com"));
assert!(!origins.is_allowed("http://attacker@[::1]"));
}
#[test]
fn matches_configured_public_origin_exactly() {
let origins = AllowedOrigins::new(Some("https://crank.example.com".to_owned()));
assert!(origins.is_allowed("https://crank.example.com"));
assert!(!origins.is_allowed("https://crank.example.com.attacker.com"));
assert!(!origins.is_allowed("https://evil.example.com"));
}
#[test]
fn rejects_non_http_schemes() {
let origins = AllowedOrigins::new(None);
assert!(!origins.is_allowed("file://localhost"));
assert!(!origins.is_allowed("javascript://localhost"));
}
#[test]
fn rejects_values_that_are_not_origins() {
let origins = AllowedOrigins::new(None);
assert!(!origins.is_allowed("http://localhost/path"));
assert!(!origins.is_allowed("http://localhost?query=value"));
assert!(!origins.is_allowed("http://localhost#fragment"));
}
}