//! Duplicate-carrier hygiene: conflicting/identical duplicate protocol-version headers, duplicate //! `Mcp-Name`/method carriers and duplicate session carriers, with the era-correct diagnostic. //! //! Tests moved verbatim from `revision_matrix.rs` (Story 3.6, kanban t_987bf309); only the module //! prefix changed. //! //! Split out of the accepted `carriers` group as the plan's documented alternative: the merged file //! measured 1018 body lines, above the enforced 1000-line health ceiling. 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, modern_post, modern_request_with_params, }; /// R12: two conflicting `MCP-Protocol-Version` header lines are an ambiguous identity and must be /// rejected before dispatch instead of silently using the first value. Our policy (recorded for the /// accepted matrix): conflicting duplicate identity carriers are rejected; identical duplicates carry /// no ambiguity and are served. #[tokio::test] async fn r12_conflicting_duplicate_protocol_version_headers_are_rejected_without_outbound() { use std::sync::atomic::Ordering; let fixture = counted_tool( None, &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let message = modern_request_with_params( Some(120), "tools/call", counted_call_params(COUNTED_TOOL_NAME), ); for order in [ [MODERN_REVISION, LEGACY_REVISION], [LEGACY_REVISION, MODERN_REVISION], ] { let response = 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), ) .headers(duplicated_header("mcp-protocol-version", order)) .header("Mcp-Method", "tools/call") .header("Mcp-Name", COUNTED_TOOL_NAME) .json(&message) .send() .await .unwrap(); assert_eq!( response.status().as_u16(), 400, "conflicting duplicate version headers ({order:?}) must be rejected, not resolved by order" ); } assert_eq!( fixture.calls.load(Ordering::SeqCst), 0, "an ambiguous identity must not reach the upstream" ); } #[tokio::test] async fn r12_identical_duplicate_protocol_version_headers_are_served() { use std::sync::atomic::Ordering; let fixture = counted_tool( None, &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let message = modern_request_with_params( Some(121), "tools/call", counted_call_params(COUNTED_TOOL_NAME), ); let response = 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), ) .headers(duplicated_header( "mcp-protocol-version", [MODERN_REVISION, MODERN_REVISION], )) .header("Mcp-Method", "tools/call") .header("Mcp-Name", COUNTED_TOOL_NAME) .json(&message) .send() .await .unwrap(); assert_eq!( response.status().as_u16(), 200, "identical duplicate version headers carry no ambiguity" ); assert_eq!(fixture.calls.load(Ordering::SeqCst), 1); } /// Assert the era-correct structured diagnostic for a single-fault version-carrier rejection. /// /// Every R28 probe sends a request whose **only** fault is the `MCP-Protocol-Version` carrier: the body /// carries the complete modern `_meta` identity, the JSON-RPC id and the `Mcp-Method`/`Mcp-Name` headers /// are valid, and the upstream counter is asserted by each probe. `protocol-era-matrix.md` row 17 requires /// the era-correct structured error for every malformed carrier (modern shape: `-32020`), and the modern /// rows 2/5/6 require the same JSON-RPC id plus the `error.data` correlation proven by R6. /// /// Defect this oracle pins: `resolve_request_identity` /// (`crates/crank-community-mcp/src/protocol/mod.rs` 511-519) turns both an unreadable/ambiguous header /// (`Err(status)` from `singleton_header`) and a blank header value into a **bare** `400` with an empty /// body, so the required JSON-RPC diagnostic is missing on both members of that branch. fn assert_carrier_rejection_is_structured( status: u16, raw: &str, id: i64, correlation: &str, case: &str, ) { assert_eq!( status, 400, "{case}: a malformed carrier must be a safe rejection" ); assert!( !raw.trim().is_empty(), "{case}: matrix row 17 requires the era-correct structured error for a malformed carrier, but \ the response body was empty" ); let body: Value = serde_json::from_str(raw).unwrap_or_else(|error| { panic!("{case}: the carrier diagnostic must be JSON-RPC, got {raw:?}: {error}") }); assert_eq!( body["jsonrpc"], "2.0", "{case}: the carrier diagnostic must be a complete JSON-RPC 2.0 envelope, got {body}" ); assert_eq!( body["id"], json!(id), "{case}: the carrier diagnostic must keep the JSON-RPC request id, got {body}" ); assert_eq!( body["error"]["code"], json!(-32020), "{case}: matrix row 17 requires the era-correct structured error (modern shape: -32020), got {body}" ); assert!( body["error"]["message"] .as_str() .is_some_and(|message| !message.trim().is_empty()), "{case}: the structured error must carry a non-empty message, got {body}" ); assert_eq!( body["error"]["data"]["request_id"], json!(correlation), "{case}: the carrier diagnostic must preserve the request correlation, got {body}" ); assert!( body.get("result").is_none(), "{case}: a rejected request must not carry a `result` key at all, got {body}" ); assert!( body["result"].is_null(), "{case}: a rejected request must not carry a result, got {body}" ); } /// R28 probe A: a `MCP-Protocol-Version` value the era resolver rejects on its own — empty, /// whitespace-only or unparsable. Single fault: the carrier value. async fn assert_modern_carrier_value_is_a_structured_mismatch(value: &str, correlation: &str) { use std::sync::atomic::Ordering; let fixture = counted_tool( None, &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let headers = vec![ ("MCP-Protocol-Version", value.to_owned()), ("Mcp-Method", "tools/call".to_owned()), ("Mcp-Name", COUNTED_TOOL_NAME.to_owned()), ]; let message = modern_request_with_params( Some(130), "tools/call", counted_call_params(COUNTED_TOOL_NAME), ); let response = modern_post(&fixture.endpoint, &headers, message, Some(correlation)).await; let status = response.status().as_u16(); let raw = response.text().await.unwrap(); assert_carrier_rejection_is_structured( status, &raw, 130, correlation, &format!("version carrier {value:?} ({correlation})"), ); assert_eq!( fixture.calls.load(Ordering::SeqCst), 0, "an identity diagnostic must not reach the upstream" ); } /// R28: an **empty** `MCP-Protocol-Version` value on an otherwise valid modern request. #[tokio::test] async fn r28_modern_empty_protocol_version_header_is_a_structured_mismatch() { assert_modern_carrier_value_is_a_structured_mismatch("", "r28-empty-carrier").await; } /// R28: a **whitespace-only** version value is the same single-fault class as the empty one. #[tokio::test] async fn r28_modern_whitespace_protocol_version_header_is_a_structured_mismatch() { assert_modern_carrier_value_is_a_structured_mismatch(" ", "r28-whitespace-carrier").await; } /// R28: an **unparsable** (non-blank) version value. Same row-17 obligation as the blank value, but this /// one is already resolved by the header/body mismatch branch (`protocol/mod.rs` 543-550), so it is /// expected **existing GREEN**: it separates the bare-`400` defect from the well-formed-value paths and /// pins that a malformed carrier must not be answered as `-32022` or as an unknown revision. #[tokio::test] async fn r28_modern_malformed_protocol_version_header_is_a_structured_mismatch() { assert_modern_carrier_value_is_a_structured_mismatch("not-a-version", "r28-malformed-carrier") .await; } /// R28 probe B: two **conflicting** `MCP-Protocol-Version` carriers in one request whose body carries a /// valid modern identity. The pair cannot be resolved to one era, so `protocol-era-matrix.md` row 17 /// (era-correct structured error) applies to the same `Err(status)` branch as the unreadable value. The /// duplicate policy itself ("identical duplicates are served") is the accepted R12 record; the matrix has /// no separate duplicate row and the existing R12 test asserts only the status, so the diagnostic shape is /// pinned here. Single fault: the ambiguity of the carrier, one order at a time. async fn assert_conflicting_duplicate_carriers_are_a_structured_mismatch( order: [&'static str; 2], correlation: &str, ) { use std::sync::atomic::Ordering; let fixture = counted_tool( None, &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let message = modern_request_with_params( Some(131), "tools/call", counted_call_params(COUNTED_TOOL_NAME), ); let response = 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) .headers(duplicated_header("mcp-protocol-version", order)) .header("Mcp-Method", "tools/call") .header("Mcp-Name", COUNTED_TOOL_NAME) .json(&message) .send() .await .unwrap(); let status = response.status().as_u16(); let raw = response.text().await.unwrap(); assert_carrier_rejection_is_structured( status, &raw, 131, correlation, &format!("conflicting carriers {order:?}"), ); assert_eq!( fixture.calls.load(Ordering::SeqCst), 0, "an ambiguous identity must not reach the upstream" ); } /// R28: the modern value first, the legacy value second. #[tokio::test] async fn r28_modern_conflicting_duplicate_protocol_headers_modern_first_are_a_structured_mismatch() { assert_conflicting_duplicate_carriers_are_a_structured_mismatch( [MODERN_REVISION, LEGACY_REVISION], "r28-duplicate-modern-first", ) .await; } /// R28: the same conflicting pair in the opposite order — the rejection must not depend on header order. #[tokio::test] async fn r28_modern_conflicting_duplicate_protocol_headers_legacy_first_are_a_structured_mismatch() { assert_conflicting_duplicate_carriers_are_a_structured_mismatch( [LEGACY_REVISION, MODERN_REVISION], "r28-duplicate-legacy-first", ) .await; } /// R28 probe C: an **unreadable** carrier value. HTTP/1.1 allows `obs-text` (bytes `0x80-0xFF`) in a field /// value, so a non-UTF-8 byte sequence is a real, transferable value that reaches the server and fails /// `HeaderValue::to_str()` inside `singleton_header` (`transport.rs` 185-190) — the second member of the /// `Err(status)` branch. Single fault: the carrier value only. #[tokio::test] async fn r28_modern_unreadable_protocol_version_header_is_a_structured_mismatch() { use std::sync::atomic::Ordering; let fixture = counted_tool( None, &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let message = modern_request_with_params( Some(132), "tools/call", counted_call_params(COUNTED_TOOL_NAME), ); let mut carrier = reqwest::header::HeaderMap::new(); carrier.append( reqwest::header::HeaderName::from_static("mcp-protocol-version"), reqwest::header::HeaderValue::from_bytes(&[b'2', 0x30, 0x32, 0x36, 0xf8, 0xfe]).unwrap(), ); let response = 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", "r28-unreadable-carrier") .headers(carrier) .header("Mcp-Method", "tools/call") .header("Mcp-Name", COUNTED_TOOL_NAME) .json(&message) .send() .await .unwrap(); let status = response.status().as_u16(); let raw = response.text().await.unwrap(); assert_carrier_rejection_is_structured( status, &raw, 132, "r28-unreadable-carrier", "unreadable version carrier", ); assert_eq!( fixture.calls.load(Ordering::SeqCst), 0, "an identity diagnostic must not reach the upstream" ); } /// R12 (session carrier half): two conflicting session identifiers are the same ambiguity class and /// must be rejected instead of resolving to the first value. #[tokio::test] async fn r12_conflicting_duplicate_session_headers_are_rejected() { let endpoint = endpoint().await; let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await; let message = json!({ "jsonrpc": "2.0", "id": 122, "method": "tools/list", "params": {} }); let response = endpoint .client .post(&endpoint.mcp_url) .header( reqwest::header::ACCEPT, "application/json, text/event-stream", ) .header( reqwest::header::AUTHORIZATION, format!("Bearer {}", endpoint.api_key), ) .headers(duplicated_header( "mcp-session-id", [session.as_str(), "session-that-never-existed"], )) .header("MCP-Protocol-Version", LEGACY_REVISION) .json(&message) .send() .await .unwrap(); assert_eq!( response.status().as_u16(), 400, "conflicting duplicate session identifiers must be rejected" ); } /// Review pass 6 (P3 / matrix rows 16-17): conflicting duplicate `MCP-Session-Id` carriers are /// rejected in `mcp_post_response` (`app.rs` 820-823) through `transport.rs::singleton_header` with /// a **bare** `400` and an empty body, before era resolution, envelope validation, rate limiting and /// any dispatch. /// /// Row 17 requires the era-correct structured diagnostic for an ambiguous carrier, and the era must /// be read from the rest of the request, never guessed from the ambiguous value. The duplicate /// *version*-carrier case already does exactly that /// (`protocol/mod.rs::malformed_carrier_response` 441-448); this oracle pins the same contract for /// the session carrier: modern shape → `400` + `-32020` with the request id and correlation, legacy /// shape → a numeric legacy error that is neither `-32020` nor `-32022`. `GET`/`DELETE` keep their /// separate lifecycle admission and are deliberately untouched. async fn assert_duplicate_session_carrier_rejection( session_values: [&str; 2], correlation: &str, id: i64, 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) .headers(duplicated_header("mcp-session-id", session_values)); let 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( Some(id as u64), "tools/call", counted_call_params(COUNTED_TOOL_NAME), ) } DuplicateSessionCarrierEra::Legacy => { request = request.header("MCP-Protocol-Version", LEGACY_REVISION); json!({ "jsonrpc": "2.0", "id": id, "method": "tools/call", "params": counted_call_params(COUNTED_TOOL_NAME) }) } }; let response = request.json(&message).send().await.unwrap(); let status = response.status().as_u16(); let raw = response.text().await.unwrap(); assert_eq!( status, 400, "an ambiguous session carrier must be a safe rejection ({correlation}), got {raw}" ); assert!( !raw.trim().is_empty(), "row 17 requires the era-correct structured diagnostic for an ambiguous session carrier \ ({correlation}), but the response body was empty" ); let body: Value = serde_json::from_str(&raw).unwrap_or_else(|error| { panic!( "the ambiguous-session diagnostic must be JSON-RPC ({correlation}), got {raw:?}: {error}" ) }); assert_eq!( body["jsonrpc"], "2.0", "the ambiguous-session diagnostic must be a JSON-RPC 2.0 envelope ({correlation}), got {body}" ); assert_eq!( body["id"], json!(id), "the ambiguous-session diagnostic must keep the request id ({correlation}), got {body}" ); match era { DuplicateSessionCarrierEra::Modern => assert_eq!( body["error"]["code"], json!(-32020), "a request whose dominant identity is modern answers the modern shape ({correlation}), \ got {body}" ), DuplicateSessionCarrierEra::Legacy => { assert!( body["error"]["code"].is_i64(), "the legacy shape must carry a numeric code ({correlation}), got {body}" ); assert_ne!( body["error"]["code"], json!(-32020), "the modern HeaderMismatch code must not be guessed for a legacy-shaped ambiguity \ ({correlation}), got {body}" ); assert_ne!( body["error"]["code"], json!(-32022), "the modern UnsupportedProtocolVersion code must not be guessed for a legacy-shaped \ ambiguity ({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 ambiguous identity must not reach the upstream ({correlation})" ); } /// Review pass 6 (P3): the modern request, first header value order. #[tokio::test] async fn review6_p3_modern_duplicate_session_carrier_first_order_is_structured() { assert_duplicate_session_carrier_rejection( ["review6-p3-session-a", "review6-p3-session-b"], "review6-p3-modern-a-first", 141, DuplicateSessionCarrierEra::Modern, ) .await; } /// Review pass 6 (P3): the modern request, reversed header value order — the outcome must not depend /// on which of the two conflicting values comes first. #[tokio::test] async fn review6_p3_modern_duplicate_session_carrier_second_order_is_structured() { assert_duplicate_session_carrier_rejection( ["review6-p3-session-b", "review6-p3-session-a"], "review6-p3-modern-b-first", 142, DuplicateSessionCarrierEra::Modern, ) .await; } /// Review pass 6 (P3): the legacy-shaped request, first header value order. #[tokio::test] async fn review6_p3_legacy_duplicate_session_carrier_first_order_is_legacy_shaped() { assert_duplicate_session_carrier_rejection( ["review6-p3-session-a", "review6-p3-session-b"], "review6-p3-legacy-a-first", 143, DuplicateSessionCarrierEra::Legacy, ) .await; } /// Review pass 6 (P3): the legacy-shaped request, reversed header value order. #[tokio::test] async fn review6_p3_legacy_duplicate_session_carrier_second_order_is_legacy_shaped() { assert_duplicate_session_carrier_rejection( ["review6-p3-session-b", "review6-p3-session-a"], "review6-p3-legacy-b-first", 144, DuplicateSessionCarrierEra::Legacy, ) .await; }