Files
crank/apps/mcp-server/tests/integration/revision_matrix/session_guards.rs
T
Hermes DevOps 75fe5a123c [skip ci] wip: preserve Hermes crank development checkpoint
Owner-authorized recovery of accumulated source changes.
Includes accepted work and in-progress changes; NOT a release or acceptance.
Parent baseline 1b6db09bd1. Runtime data, build caches and local credentials excluded.
2026-10-25 10:00:22 +00:00

425 lines
16 KiB
Rust

//! Session-carrier guards: an ambiguous or unusable `MCP-Session-Id` is rejected by the same
//! structured diagnostic per era, and never echoes the invalid value.
//!
//! Tests moved verbatim from `revision_matrix.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use axum::http::header;
use crank_core::PlatformApiKeyScope;
use serde_json::{Value, json};
use super::harness::{
COUNTED_TOOL_NAME, DuplicateSessionCarrierEra, LEGACY_REVISION, MODERN_REVISION,
counted_call_params, counted_tool, duplicated_header, endpoint, json_body, modern_headers,
modern_post, modern_request_with_params, oracle_status, tools_list_request,
};
/// AT-3.1-11 (wm-07): without a version header a live legacy session establishes the revision.
#[tokio::test]
async fn at_3_1_11_subsequent_request_without_version_header_keeps_session_revision() {
let endpoint = endpoint().await;
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[("MCP-Session-Id", session.as_str())],
tools_list_request(10),
)
.await;
assert_eq!(
response.status().as_u16(),
oracle_status("wm-07"),
"a live legacy session with no version header must still be served"
);
let echoed = response
.headers()
.get("MCP-Protocol-Version")
.map(|value| value.to_str().unwrap().to_owned());
assert_eq!(
echoed.as_deref(),
Some(LEGACY_REVISION),
"the negotiated session revision must identify the era"
);
}
/// AT-3.1-11 (wm-08): a session-requiring era rejects a request without the session header.
#[tokio::test]
async fn at_3_1_11_subsequent_request_without_session_header_is_rejected() {
let endpoint = endpoint().await;
let _session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[("MCP-Protocol-Version", LEGACY_REVISION)],
tools_list_request(11),
)
.await;
assert_eq!(
response.status().as_u16(),
oracle_status("wm-08"),
"a request without the required session header must be rejected"
);
}
/// AT-3.1-11 (wm-09 / wm-14): a terminated session is answered with `404`, never resurrected.
#[tokio::test]
async fn at_3_1_11_terminated_session_is_rejected_with_not_found() {
let endpoint = endpoint().await;
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let deleted = endpoint
.client
.delete(&endpoint.mcp_url)
.header(
header::AUTHORIZATION,
format!("Bearer {}", endpoint.api_key),
)
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", LEGACY_REVISION)
.header(header::ORIGIN, "https://crank.example.com")
.send()
.await
.unwrap();
assert!(
deleted.status().is_success() || deleted.status().as_u16() == 405,
"session termination must be accepted or explicitly unsupported, got {}",
deleted.status()
);
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[
("MCP-Session-Id", session.as_str()),
("MCP-Protocol-Version", LEGACY_REVISION),
],
tools_list_request(12),
)
.await;
assert_eq!(
response.status().as_u16(),
oracle_status("wm-09"),
"a terminated session must be answered with 404 and never restored"
);
}
/// R4: conflicting/modern identity with a session carrier must be rejected before dispatch.
#[tokio::test]
async fn r4_modern_identity_with_unknown_session_header_is_rejected() {
let endpoint = endpoint().await;
let mut headers = modern_headers(MODERN_REVISION, "tools/list");
headers.push(("MCP-Session-Id", "session-that-never-existed".to_owned()));
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(60), "tools/list", json!({})),
None,
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"an unknown session carrier must not be ignored by the modern path"
);
let body = json_body(response).await;
assert!(body["result"].is_null(), "got {body}");
}
#[tokio::test]
async fn r4_modern_identity_with_live_legacy_session_header_is_rejected() {
let endpoint = endpoint().await;
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let mut headers = modern_headers(MODERN_REVISION, "tools/list");
headers.push(("MCP-Session-Id", session.clone()));
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(61), "tools/list", json!({})),
None,
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"mixed modern identity plus a legacy session carrier must be rejected"
);
}
/// R4 (observable half only): a modern request carrying an unknown session id must be rejected for the
/// carrier conflict. The quota question itself stays **NOT PROVEN** — it needs an observable counter over
/// the session-keyed limiter, which this harness does not expose.
#[tokio::test]
async fn r4_mixed_carrier_rejection_is_observable_quota_is_not_proven() {
let endpoint = endpoint().await;
let mut headers = modern_headers(MODERN_REVISION, "tools/list");
headers.push(("MCP-Session-Id", "quota-probe-session".to_owned()));
let first = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(62), "tools/list", json!({})),
None,
)
.await;
assert_eq!(
first.status().as_u16(),
400,
"a modern request with an unknown session carrier must be rejected"
);
}
/// The two ways `session_id_from_headers` (`transport.rs` 227-229 → `singleton_header` 177-194)
/// reports an unusable `MCP-Session-Id`. Both surface as the same `Err(_status)` projection branch in
/// `mcp_post_response` (`app.rs` 827-830), so they are one root class for the diagnostic.
enum UnusableSessionCarrier {
/// Two conflicting session values: the carrier cannot identify the era or the session.
Conflicting([&'static str; 2]),
/// A non-text value. HTTP/1.1 allows `obs-text` (bytes `0x80-0xFF`) in a field value, so this is a
/// real transferable value that fails `HeaderValue::to_str()` inside `singleton_header`.
Unreadable,
}
/// Review pass 7 (G1): an otherwise-valid request whose `id` is **not** a valid request id must never
/// have that value echoed back.
///
/// `mcp_post_response` projects the ambiguous/unusable-session diagnostic (`app.rs` 827-830 →
/// `protocol::ambiguous_session_carrier_response` 461-468) **before** the single JSON-RPC envelope
/// guard (`app.rs` 832-837), and that projection reads the raw body id through `jsonrpc::request_id`
/// (`jsonrpc.rs` 32-33). The pinned `RequestId` is `string | number`, and the established
/// invalid-request convention answers with a `null` id precisely because an unvalidated value must
/// never be echoed (`protocol/mod.rs` 164-170).
///
/// This oracle pins that safety property only: the era-correct diagnostic keeps one of the existing
/// structured codes (modern `-32020` or the invalid-request `-32600`; legacy numeric and never
/// `-32020`/`-32022`) and the id is `null` instead of `{}`/`true`/`[]`. It deliberately invents no new
/// compound-case code and does not require the envelope guard to move; the valid-id shapes stay the
/// accepted P3 contract.
async fn assert_unusable_session_carrier_never_echoes_an_invalid_id(
carrier: UnusableSessionCarrier,
correlation: &str,
invalid_id: Value,
era: DuplicateSessionCarrierEra,
) {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let mut request = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.header("x-request-id", correlation);
request = match carrier {
UnusableSessionCarrier::Conflicting(values) => {
request.headers(duplicated_header("mcp-session-id", values))
}
UnusableSessionCarrier::Unreadable => {
let mut headers = reqwest::header::HeaderMap::new();
headers.append(
reqwest::header::HeaderName::from_static("mcp-session-id"),
reqwest::header::HeaderValue::from_bytes(&[b'x', 0xf8, 0xfe]).unwrap(),
);
request.headers(headers)
}
};
// The request is otherwise valid for its era: only the session carrier and the id are faulty.
let mut message = match era {
DuplicateSessionCarrierEra::Modern => {
request = request
.header("MCP-Protocol-Version", MODERN_REVISION)
.header("Mcp-Method", "tools/call")
.header("Mcp-Name", COUNTED_TOOL_NAME);
modern_request_with_params(None, "tools/call", counted_call_params(COUNTED_TOOL_NAME))
}
DuplicateSessionCarrierEra::Legacy => {
request = request.header("MCP-Protocol-Version", LEGACY_REVISION);
json!({
"jsonrpc": "2.0",
"method": "tools/call",
"params": counted_call_params(COUNTED_TOOL_NAME)
})
}
};
message["id"] = invalid_id.clone();
let response = request.json(&message).send().await.unwrap();
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"a rejected request must not mint a session ({correlation})"
);
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_eq!(
status, 400,
"an unusable session carrier must be a safe rejection ({correlation}), got {raw}"
);
let body: Value = serde_json::from_str(&raw).unwrap_or_else(|error| {
panic!(
"the unusable-session diagnostic must be JSON-RPC ({correlation}), got {raw:?}: {error}"
)
});
assert_eq!(
body["jsonrpc"], "2.0",
"the diagnostic must be a complete JSON-RPC 2.0 envelope ({correlation}), got {body}"
);
assert_eq!(
body["id"],
Value::Null,
"an invalid request id must never be echoed; the established invalid-request convention \
answers with a null id ({correlation}), got {body}"
);
assert!(
!body["id"].is_object() && !body["id"].is_boolean() && !body["id"].is_array(),
"the response id must never be the unvalidated value ({correlation}), got {body}"
);
let code = body["error"]["code"].clone();
assert!(
code.is_i64(),
"the diagnostic must carry a numeric JSON-RPC error code ({correlation}), got {body}"
);
assert_ne!(
code,
json!(-32022),
"the UnsupportedProtocolVersion code is reserved for a well-formed unknown identity \
({correlation}), got {body}"
);
match era {
DuplicateSessionCarrierEra::Modern => assert!(
code == json!(-32020) || code == json!(-32600),
"the modern shape keeps an existing structured code (header mismatch or invalid \
request) ({correlation}), got {body}"
),
DuplicateSessionCarrierEra::Legacy => assert_ne!(
code,
json!(-32020),
"the modern HeaderMismatch code must not be imposed on a legacy-sourced rejection \
({correlation}), got {body}"
),
}
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"the diagnostic must carry a non-empty message ({correlation}), got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(correlation),
"the diagnostic must preserve the request correlation ({correlation}), got {body}"
);
assert!(
body.get("result").is_none(),
"a rejected request must not carry a result ({correlation}), got {body}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an unusable identity must not reach the upstream ({correlation})"
);
}
/// Review pass 7 (G1): modern identity, conflicting session carriers (a first), invalid object id.
#[tokio::test]
async fn review7_g1_modern_ambiguous_session_carrier_with_object_id_is_safe() {
assert_unusable_session_carrier_never_echoes_an_invalid_id(
UnusableSessionCarrier::Conflicting(["review7-g1-session-a", "review7-g1-session-b"]),
"review7-g1-modern-object-id",
json!({}),
DuplicateSessionCarrierEra::Modern,
)
.await;
}
/// Review pass 7 (G1): the same modern case with the conflicting values in the opposite order and a
/// boolean id — the outcome must not depend on the header order or on the id's invalid kind.
#[tokio::test]
async fn review7_g1_modern_ambiguous_session_carrier_with_boolean_id_is_safe() {
assert_unusable_session_carrier_never_echoes_an_invalid_id(
UnusableSessionCarrier::Conflicting(["review7-g1-session-b", "review7-g1-session-a"]),
"review7-g1-modern-boolean-id",
json!(true),
DuplicateSessionCarrierEra::Modern,
)
.await;
}
/// Review pass 7 (G1): the third invalid id kind (an array) on the modern identity.
#[tokio::test]
async fn review7_g1_modern_ambiguous_session_carrier_with_array_id_is_safe() {
assert_unusable_session_carrier_never_echoes_an_invalid_id(
UnusableSessionCarrier::Conflicting(["review7-g1-session-a", "review7-g1-session-b"]),
"review7-g1-modern-array-id",
json!([]),
DuplicateSessionCarrierEra::Modern,
)
.await;
}
/// Review pass 7 (G1): legacy identity, conflicting session carriers, invalid object id. The legacy
/// diagnostic stays legacy-shaped and must still never echo the invalid id.
#[tokio::test]
async fn review7_g1_legacy_ambiguous_session_carrier_with_object_id_is_safe() {
assert_unusable_session_carrier_never_echoes_an_invalid_id(
UnusableSessionCarrier::Conflicting(["review7-g1-session-a", "review7-g1-session-b"]),
"review7-g1-legacy-object-id",
json!({}),
DuplicateSessionCarrierEra::Legacy,
)
.await;
}
/// Review pass 7 (G1): the legacy case, reversed order, array id.
#[tokio::test]
async fn review7_g1_legacy_ambiguous_session_carrier_with_array_id_is_safe() {
assert_unusable_session_carrier_never_echoes_an_invalid_id(
UnusableSessionCarrier::Conflicting(["review7-g1-session-b", "review7-g1-session-a"]),
"review7-g1-legacy-array-id",
json!([]),
DuplicateSessionCarrierEra::Legacy,
)
.await;
}
/// Review pass 7 (G1): an **unreadable** (non-text) session carrier reaches the same projection branch,
/// so the same no-echo guarantee is pinned for it.
#[tokio::test]
async fn review7_g1_modern_unreadable_session_carrier_with_object_id_is_safe() {
assert_unusable_session_carrier_never_echoes_an_invalid_id(
UnusableSessionCarrier::Unreadable,
"review7-g1-modern-unreadable-carrier",
json!({}),
DuplicateSessionCarrierEra::Modern,
)
.await;
}