//! JSON-RPC envelope validity: notifications versus requests, invalid/missing envelope fields, //! request-id correlation of errors and duplicate `mcp method`/`mcp name` carriers. //! //! 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, LEGACY_REVISION, META_CLIENT_CAPABILITIES, META_CLIENT_INFO, MODERN_REVISION, UNKNOWN_REVISION, approved_revisions, counted_call_params, counted_tool, duplicated_header, endpoint, json_body, modern_call_headers, modern_headers, modern_meta, modern_post, modern_request_with_params, pending_approvals, }; /// Review pass 6 (P1 / matrix row 4): modern-specific request metadata without **any** version /// carrier must be rejected as a header-validation failure instead of being admitted as legacy. /// /// Defect this oracle pins: `resolve_request_identity` (`protocol/mod.rs` 568-642) reads only the /// `_meta` version field and the `MCP-Protocol-Version` header. A request whose `_meta` carries the /// modern-specific `clientCapabilities`/`clientInfo` keys but no version at all yields an effective /// identity of `None`, so it is admitted as `Legacy` (`638-641`) and a **live initialized legacy /// session** executes it as a legacy `tools/call`. Row 4 requires a rejection before any adapter /// admission; the modern era defines a header-validation failure as `400` + `-32020` /// `HeaderMismatch`, the same shape this resolver already emits for a modern identity with a missing /// version header (`648-653`) and for a missing `_meta` version (`492-497`). /// /// The probe is repeated once so row 21 (a repeated request has the same outcome and leaves no /// residual state) is asserted observably, and the counted upstream proves that no legacy outbound /// call happened. #[tokio::test] async fn review6_p1_modern_metadata_without_version_carrier_is_rejected_before_legacy_admission() { use std::sync::atomic::Ordering; let fixture = counted_tool( None, &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let session = initialize_session( &fixture.endpoint.client, &fixture.endpoint.mcp_url, &fixture.endpoint.api_key, ) .await; let headers = vec![("MCP-Session-Id", session.clone())]; let message = modern_request_with_params( Some(140), "tools/call", json!({ "name": COUNTED_TOOL_NAME, "arguments": { "email": "review6-p1@example.com" }, "_meta": { META_CLIENT_CAPABILITIES: {}, META_CLIENT_INFO: { "name": "crank-atdd-client", "version": "0.1.0" } } }), ); for attempt in 1..=2 { let response = modern_post( &fixture.endpoint, &headers, message.clone(), Some("review6-p1"), ) .await; let status = response.status().as_u16(); assert!( response.headers().get("MCP-Session-Id").is_none(), "attempt {attempt}: a rejected request must not mint a session" ); let raw = response.text().await.unwrap(); assert_eq!( status, 400, "attempt {attempt}: modern `_meta` without a version carrier must be rejected before \ legacy admission (matrix row 4), got {raw}" ); assert!( !raw.trim().is_empty(), "attempt {attempt}: row 4 requires a structured rejection, but the response body was empty" ); let body: Value = serde_json::from_str(&raw).unwrap_or_else(|error| { panic!( "attempt {attempt}: the row-4 rejection must be a JSON-RPC envelope, got {raw:?}: {error}" ) }); assert_eq!( body["jsonrpc"], "2.0", "attempt {attempt}: the rejection must be a JSON-RPC 2.0 envelope, got {body}" ); assert_eq!( body["id"], json!(140), "attempt {attempt}: the rejection must keep the request id, got {body}" ); assert_eq!( body["error"]["code"], json!(-32020), "attempt {attempt}: a modern identity without its required version carrier is a \ header-validation failure (matrix row 4), got {body}" ); assert!( body["error"]["message"] .as_str() .is_some_and(|message| !message.trim().is_empty()), "attempt {attempt}: the rejection must carry a non-empty message, got {body}" ); assert_eq!( body["error"]["data"]["request_id"], json!("review6-p1"), "attempt {attempt}: the rejection must preserve the request correlation, got {body}" ); assert!( body.get("result").is_none(), "attempt {attempt}: a rejected request must not carry a result, got {body}" ); } assert_eq!( fixture.calls.load(Ordering::SeqCst), 0, "modern-specific metadata without a version carrier must not be executed as a legacy request" ); // Review pass 7 (G3, matrix row 21 valid follow-up): after the repeated rejection the same live // initialized legacy session must still serve a valid legacy request. This is the narrow // valid-follow-up half of row 21 — it is not a session-store dump or a full persisted-state // equality oracle, and it claims no more than "the rejected requests left the session usable". let follow_up = post_jsonrpc( &fixture.endpoint.client, &fixture.endpoint.mcp_url, &fixture.endpoint.api_key, Some(&session), json!({ "jsonrpc": "2.0", "id": 141, "method": "tools/call", "params": { "name": COUNTED_TOOL_NAME, "arguments": { "email": "review7-p1-follow-up@example.com" } } }), ) .await; assert!( follow_up["error"].is_null(), "a valid legacy follow-up on the same live session must be served, got {follow_up}" ); assert_eq!( follow_up["result"]["structuredContent"], json!({ "id": "lead_123" }), "the valid follow-up must return the published business payload, got {follow_up}" ); assert_eq!( fixture.calls.load(Ordering::SeqCst), 1, "the valid follow-up must perform exactly one additional outbound call" ); } /// R5/R15: a valid modern notification (no `id`) must be acknowledged with exactly `202` and an empty /// body — not a JSON-RPC result and not an error envelope. Invalid envelopes (e.g. a foreign `id`) are /// R10's business and are covered separately. #[tokio::test] async fn r5_modern_notification_is_not_executed_as_request() { let endpoint = endpoint().await; let headers = modern_headers(MODERN_REVISION, "tools/list"); let message = modern_request_with_params(None, "tools/list", json!({})); let response = modern_post(&endpoint, &headers, message, None).await; assert_eq!( response.status().as_u16(), 202, "a valid notification is acknowledged with 202" ); let body = response.text().await.unwrap(); assert!( body.is_empty(), "a notification acknowledgement must have an empty body, got {body:?}" ); } /// R6: era errors must keep the existing request correlation data. /// /// Single fault: the unknown revision is carried identically in the header and in the body `_meta`, /// while the remaining metadata (`clientCapabilities`, `clientInfo`) and `Mcp-Method` stay valid, so the /// only defect in play is the unsupported revision itself (`-32022`, not a mismatch). #[tokio::test] async fn r6_error_data_preserves_request_correlation() { let endpoint = endpoint().await; let headers = modern_headers(UNKNOWN_REVISION, "tools/list"); let message = modern_request_with_params( Some(70), "tools/list", json!({ "_meta": modern_meta(UNKNOWN_REVISION) }), ); let response = modern_post(&endpoint, &headers, message, Some("r6-correlation-check")).await; assert_eq!(response.status().as_u16(), 400); let body = json_body(response).await; assert_eq!( body["error"]["code"], json!(-32022), "an identically unknown header/body revision is an unsupported-version error, got {body}" ); let data = &body["error"]["data"]; assert_eq!( data["requested"], json!(UNKNOWN_REVISION), "the requested revision must be reported, got {body}" ); let mut supported: Vec = data["supported"] .as_array() .cloned() .unwrap_or_default() .iter() .filter_map(Value::as_str) .map(str::to_owned) .collect(); supported.sort(); let mut approved = approved_revisions(); approved.sort(); assert_eq!( supported, approved, "the supported list must survive alongside the correlation, got {body}" ); assert_eq!( data["request_id"], json!("r6-correlation-check"), "the unsupported-version error must keep the request correlation, got {body}" ); } #[tokio::test] async fn r6_mismatch_error_data_preserves_request_correlation() { let endpoint = endpoint().await; let headers = modern_headers(MODERN_REVISION, "tools/list"); let message = modern_request_with_params( Some(71), "tools/list", json!({ "_meta": modern_meta(LEGACY_REVISION) }), ); let response = modern_post(&endpoint, &headers, message, Some("r6-mismatch-check")).await; assert_eq!(response.status().as_u16(), 400); let body = json_body(response).await; let data = &body["error"]["data"]; assert_eq!( data["request_id"], json!("r6-mismatch-check"), "the mismatch error must keep the request correlation, got {body}" ); assert!( data["details"].is_string(), "the mismatch detail must survive alongside the correlation, got {body}" ); } /// R5/R15: a mutating notification (no `id`) must be acknowledged with exactly `202` and an empty body, /// must not be dispatched and must not reach the upstream. #[tokio::test] async fn r5_modern_mutating_notification_is_not_dispatched_without_outbound() { use std::sync::atomic::Ordering; let fixture = counted_tool( None, &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME); let message = modern_request_with_params(None, "tools/call", counted_call_params(COUNTED_TOOL_NAME)); let response = modern_post(&fixture.endpoint, &headers, message, None).await; assert_eq!( response.status().as_u16(), 202, "a mutating notification is acknowledged with 202" ); let body = response.text().await.unwrap(); assert!( body.is_empty(), "a notification acknowledgement must have an empty body, got {body:?}" ); assert_eq!( fixture.calls.load(Ordering::SeqCst), 0, "a mutating notification must not perform the outbound request" ); } /// R10: a modern request must be a well-formed JSON-RPC request before any tool dispatch. The pinned /// modern schema types the request `id` as `string | number` (`RequestId`), so a missing or foreign /// `jsonrpc` field and an object/boolean `id` are invalid requests — the JSON syntax being extractable /// says nothing about the envelope. #[tokio::test] async fn r10_modern_missing_jsonrpc_field_is_rejected_without_outbound() { use std::sync::atomic::Ordering; let fixture = counted_tool( None, &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME); let mut message = modern_request_with_params( Some(110), "tools/call", counted_call_params(COUNTED_TOOL_NAME), ); message.as_object_mut().unwrap().remove("jsonrpc"); let response = modern_post(&fixture.endpoint, &headers, message, None).await; assert_eq!( response.status().as_u16(), 400, "a message without the `jsonrpc` field is not a valid JSON-RPC request" ); let body = json_body(response).await; assert_eq!(body["error"]["code"], json!(-32600), "got {body}"); assert!( body["id"].is_null(), "an undeterminable request id must be reported as null, got {body}" ); assert_eq!( fixture.calls.load(Ordering::SeqCst), 0, "an invalid envelope must not reach the upstream" ); } #[tokio::test] async fn r10_modern_wrong_jsonrpc_version_is_rejected_without_outbound() { use std::sync::atomic::Ordering; let fixture = counted_tool( None, &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME); let mut message = modern_request_with_params( Some(111), "tools/call", counted_call_params(COUNTED_TOOL_NAME), ); message["jsonrpc"] = json!("1.0"); let response = modern_post(&fixture.endpoint, &headers, message, None).await; assert_eq!(response.status().as_u16(), 400); let body = json_body(response).await; assert_eq!(body["error"]["code"], json!(-32600), "got {body}"); assert_eq!(fixture.calls.load(Ordering::SeqCst), 0, "got {body}"); } #[tokio::test] async fn r10_modern_non_scalar_request_id_is_rejected_without_outbound() { use std::sync::atomic::Ordering; let fixture = counted_tool( None, &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME); for foreign_id in [json!({}), json!(true), json!([1, 2])] { let mut message = modern_request_with_params( Some(112), "tools/call", counted_call_params(COUNTED_TOOL_NAME), ); message["id"] = foreign_id.clone(); let response = modern_post(&fixture.endpoint, &headers, message, None).await; assert_eq!( response.status().as_u16(), 400, "the pinned request id is `string | number`, so {foreign_id} is invalid" ); let body = json_body(response).await; assert_eq!(body["error"]["code"], json!(-32600), "got {body}"); assert!( !body["id"].is_object() && !body["id"].is_boolean() && !body["id"].is_array(), "the response must not echo an arbitrary id value, got {body}" ); } assert_eq!(fixture.calls.load(Ordering::SeqCst), 0); } /// R10 (approval half): an invalid envelope on an approval-gated operation must neither call the /// upstream nor create a pending approval request. #[tokio::test] async fn r10_modern_invalid_envelope_creates_no_pending_approval() { use crank_core::{ OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy, OperationApprovalRiskLevel, }; use std::sync::atomic::Ordering; let policy = OperationApprovalPolicy { required: true, mode: OperationApprovalMode::Custom, risk_level: OperationApprovalRiskLevel::Dangerous, ttl_seconds: 300, show_payload_preview: true, payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson, elicitation_message: None, }; let fixture = counted_tool( Some(policy), &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME); let mut message = modern_request_with_params( Some(113), "tools/call", counted_call_params(COUNTED_TOOL_NAME), ); message["jsonrpc"] = json!("1.0"); // R21: the persisted registry state is the proof, not the absence of an id in the response body. let before = pending_approvals(&fixture.endpoint.registry, "sales-gated").await; let response = modern_post(&fixture.endpoint, &headers, message, None).await; assert_eq!(response.status().as_u16(), 400); let body = json_body(response).await; assert_eq!(body["error"]["code"], json!(-32600), "got {body}"); assert!( !body.to_string().contains("approval_"), "an invalid envelope must not produce a pending approval, got {body}" ); let after = pending_approvals(&fixture.endpoint.registry, "sales-gated").await; assert_eq!( after, before, "an invalid envelope must not persist a pending approval request" ); assert_eq!( fixture.calls.load(Ordering::SeqCst), 0, "an invalid envelope must not perform the outbound request" ); } /// R10 (correlation): an invalid envelope must still answer with the request correlation the ingress /// already established, and the safe response id must stay null. #[tokio::test] async fn r10_invalid_envelope_keeps_request_correlation() { use std::sync::atomic::Ordering; let fixture = counted_tool( None, &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME); let mut message = modern_request_with_params( Some(115), "tools/call", counted_call_params(COUNTED_TOOL_NAME), ); message.as_object_mut().unwrap().remove("jsonrpc"); let response = modern_post( &fixture.endpoint, &headers, message, Some("r10-envelope-correlation"), ) .await; assert_eq!(response.status().as_u16(), 400); let body = json_body(response).await; assert_eq!(body["error"]["code"], json!(-32600), "got {body}"); assert_eq!( body["error"]["data"]["request_id"], json!("r10-envelope-correlation"), "an invalid envelope must keep the ingress correlation, got {body}" ); assert!(body["id"].is_null(), "got {body}"); assert_eq!(fixture.calls.load(Ordering::SeqCst), 0); } /// R10 (id null): a present but null id is not a valid request id under the pinned `string | number` /// contract and must never be acknowledged as a notification — no `202`, no dispatch, no outbound. #[tokio::test] async fn r10_null_request_id_is_not_a_notification() { use std::sync::atomic::Ordering; let fixture = counted_tool( None, &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME); let mut message = modern_request_with_params( Some(116), "tools/call", counted_call_params(COUNTED_TOOL_NAME), ); message["id"] = Value::Null; let response = modern_post(&fixture.endpoint, &headers, message, None).await; assert_eq!( response.status().as_u16(), 400, "a null id must be an invalid request, not a notification acknowledgement" ); let body = json_body(response).await; assert_eq!(body["error"]["code"], json!(-32600), "got {body}"); assert_eq!( fixture.calls.load(Ordering::SeqCst), 0, "an invalid envelope must not reach the upstream" ); } /// R13: a message without `method` and without `Mcp-Method` currently matches `None == None` and is /// routed to unknown-method dispatch. It is an invalid request and must be rejected as such, not /// answered as an unknown method with a `-32601` result. #[tokio::test] async fn r13_absent_method_with_valid_modern_identity_is_an_invalid_request() { use std::sync::atomic::Ordering; let fixture = counted_tool( None, &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let headers = vec![("MCP-Protocol-Version", MODERN_REVISION.to_owned())]; let message = json!({ "jsonrpc": "2.0", "id": 130, "params": { "_meta": modern_meta(MODERN_REVISION) } }); let response = modern_post(&fixture.endpoint, &headers, message, None).await; assert_eq!( response.status().as_u16(), 400, "a message without a method is an invalid request, not an unknown method" ); let body = json_body(response).await; assert_eq!(body["error"]["code"], json!(-32600), "got {body}"); assert!( body["result"].is_null(), "an invalid request must not be answered with a result, got {body}" ); assert_eq!(fixture.calls.load(Ordering::SeqCst), 0); } #[tokio::test] async fn r13_non_string_method_is_an_invalid_request() { use std::sync::atomic::Ordering; let fixture = counted_tool( None, &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let headers = vec![("MCP-Protocol-Version", MODERN_REVISION.to_owned())]; let message = json!({ "jsonrpc": "2.0", "id": 131, "method": 42, "params": { "_meta": modern_meta(MODERN_REVISION) } }); let response = modern_post(&fixture.endpoint, &headers, message, None).await; assert_eq!(response.status().as_u16(), 400); let body = json_body(response).await; assert_eq!(body["error"]["code"], json!(-32600), "got {body}"); assert_eq!(fixture.calls.load(Ordering::SeqCst), 0); } /// R19: matrix row 18 — notifications do not inherit the mandatory request headers. A valid modern /// notification (no id, valid `_meta`, valid protocol identity) without `Mcp-Method` must be /// acknowledged with `202` and an empty body, and must not reach the upstream. The request case with a /// missing method header stays rejected (`r7_modern_missing_mcp_method_is_rejected`). #[tokio::test] async fn r19_modern_notification_without_mcp_method_is_acknowledged() { use std::sync::atomic::Ordering; let fixture = counted_tool( None, &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let headers = vec![("MCP-Protocol-Version", MODERN_REVISION.to_owned())]; let message = modern_request_with_params(None, "tools/call", counted_call_params(COUNTED_TOOL_NAME)); let response = modern_post(&fixture.endpoint, &headers, message, None).await; assert_eq!( response.status().as_u16(), 202, "a notification does not carry the mandatory request headers" ); let body = response.text().await.unwrap(); assert!( body.is_empty(), "a notification acknowledgement must have an empty body, got {body:?}" ); assert_eq!( fixture.calls.load(Ordering::SeqCst), 0, "a notification must not perform the outbound request" ); } /// R22: a conflicting duplicate `Mcp-Method` is an ambiguous method declaration and must be rejected /// with `400 -32020`, the preserved correlation and no outbound request. #[tokio::test] async fn r22_conflicting_duplicate_mcp_method_is_rejected() { use std::sync::atomic::Ordering; let fixture = counted_tool( None, &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let message = modern_request_with_params( Some(160), "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("MCP-Protocol-Version", MODERN_REVISION) .headers(duplicated_header( "mcp-method", ["tools/call", "tools/list"], )) .header("Mcp-Name", COUNTED_TOOL_NAME) .header("x-request-id", "r22-duplicate-mcp-method") .json(&message) .send() .await .unwrap(); assert_eq!(response.status().as_u16(), 400); let body = json_body(response).await; assert_eq!(body["error"]["code"], json!(-32020), "got {body}"); assert_eq!( body["error"]["data"]["request_id"], json!("r22-duplicate-mcp-method"), "got {body}" ); assert_eq!(fixture.calls.load(Ordering::SeqCst), 0); } /// R22: a conflicting duplicate `Mcp-Name` is rejected the same way. #[tokio::test] async fn r22_conflicting_duplicate_mcp_name_is_rejected() { use std::sync::atomic::Ordering; let fixture = counted_tool( None, &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let message = modern_request_with_params( Some(161), "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("MCP-Protocol-Version", MODERN_REVISION) .header("Mcp-Method", "tools/call") .headers(duplicated_header( "mcp-name", [COUNTED_TOOL_NAME, "some_other_tool"], )) .json(&message) .send() .await .unwrap(); assert_eq!(response.status().as_u16(), 400); let body = json_body(response).await; assert_eq!(body["error"]["code"], json!(-32020), "got {body}"); assert_eq!(fixture.calls.load(Ordering::SeqCst), 0); } /// R22: identical duplicates carry no ambiguity and keep working (accepted current semantics). #[tokio::test] async fn r22_identical_duplicate_mcp_method_is_served() { use std::sync::atomic::Ordering; let fixture = counted_tool( None, &[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write], ) .await; let message = modern_request_with_params( Some(162), "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("MCP-Protocol-Version", MODERN_REVISION) .headers(duplicated_header( "mcp-method", ["tools/call", "tools/call"], )) .header("Mcp-Name", COUNTED_TOOL_NAME) .json(&message) .send() .await .unwrap(); assert_eq!(response.status().as_u16(), 200); assert_eq!(fixture.calls.load(Ordering::SeqCst), 1); }