Files
crank/apps/mcp-server/tests/integration/revision_matrix/review8_identity.rs
T
Hermes DevOps 301dce301a [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 08:05:37 +00:00

383 lines
16 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Review pass 8 identity regressions — `review8_identity` child module of `revision_matrix`.
//!
//! Bounded test-only maintenance (kanban t_f6b289ab, Story 3.1 / Gitea #8; TL triage
//! `build/review9-triage/TL-TRIAGE.md`): the three review-8 F1/F2 regressions moved verbatim
//! out of the parent module file, and their business parameters now come from the shared
//! `counted_call_params` factory. No assertion, input, header or wire expectation changed; the
//! shared parent helpers are reached through `super`.
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, counted_call_params, counted_tool, duplicated_header, modern_post,
};
// ---------------------------------------------------------------------------------------------
// Review pass 8 — test-only regression for two residual protocol-root defects (F1/F2).
//
// Both oracles pin the **expected** era-correct behaviour of the current binding contract
// (`protocol-era-matrix.md`, CURRENT binding section). This stage changes no production code: it
// demonstrates the behaviour of the accepted freeze on the real endpoint and hands the complete
// oracle to TL review. F1 and F2 are two distinct observed product paths, not the full set of
// reviewer candidates, and neither is a Story/Epic/release qualification.
// ---------------------------------------------------------------------------------------------
/// A modern-specific request `_meta` with **no** version field.
///
/// `clientInfo` is a valid *optional* carrier in the pinned `RequestMetaObject`, so the
/// client-info-less variant is deliberately part of the F1 oracle instead of being treated as a
/// second defect: the rejection is required for the modern-specific identity as such, not for the
/// optional field.
fn review8_modern_meta_without_version(with_client_info: bool) -> Value {
let mut meta = json!({ META_CLIENT_CAPABILITIES: {} });
if with_client_info {
meta[META_CLIENT_INFO] = json!({ "name": "crank-review8-client", "version": "0.1.0" });
}
meta
}
/// Review pass 8 (F1 / matrix rows 4 and 16): an explicit **legacy** `MCP-Protocol-Version` header
/// must not turn a modern-specific request into a legacy admission.
///
/// Static trace of the accepted freeze (`crates/crank-community-mcp/src/protocol/mod.rs`):
/// `:623-643` reads `_meta` and finds no version field → `meta_version = None`; `:671` makes the
/// *effective* identity the legacy header value, so the missing-modern-version guard `:673-706`
/// (including its `declares_modern_metadata` check at `:678`) is skipped entirely; `:726-729`
/// selects `RequestEra::Legacy`. `app.rs` then accepts that header against the live legacy session
/// (`:866-895`), authorizes the valid write credential (`:902-905`) and reaches the real catalog
/// dispatch (`:1000-1041`), which performs the outbound call.
///
/// Binding row 4 ("modern `_meta` present without a version field → reject as header validation
/// failure") and row 16 (mixed carriers are rejected for the era identified by the dominant
/// carrier, with no hidden session and no partial state) require the opposite: a `400` + `-32020`
/// `HeaderMismatch` **before** any adapter or session admission — no business dispatch, no session
/// minting, no approval conversion.
///
/// The probe is bounded to the two metadata variants (client capabilities only, and client
/// capabilities plus a valid optional `clientInfo`) and is preceded by two positive controls on the
/// same live session (a plain legacy call and a legacy call with an ordinary non-modern `_meta`
/// key). The controls prove that the fixture, the session and the write credential are valid, so
/// the rejection cannot be explained by a malformed probe, and they pin that an ordinary `_meta`
/// stays permitted for the legacy era.
#[tokio::test]
async fn review8_f1_legacy_version_header_does_not_bypass_missing_modern_version_rejection() {
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;
// Positive control 1: a plain valid legacy `tools/call` on the same live session. This is the
// accepted legacy behaviour and must stay GREEN before and after any F1 repair.
//
// The business parameters come from the shared `counted_call_params` factory and only the
// stage-specific email is overridden, so the request body keeps exactly the previous shape (M2).
let mut plain_params = counted_call_params(COUNTED_TOOL_NAME);
plain_params["arguments"]["email"] = json!("review8-f1-control-plain@example.com");
let plain = post_jsonrpc(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0",
"id": 811,
"method": "tools/call",
"params": plain_params
}),
)
.await;
assert!(
plain["error"].is_null(),
"the plain legacy positive control must be served, got {plain}"
);
assert_eq!(
plain["result"]["structuredContent"],
json!({ "id": "lead_123" }),
"the plain legacy positive control must return the published business payload, got {plain}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
1,
"the plain legacy positive control must perform exactly one outbound call"
);
// Positive control 2: the same valid legacy call with an ordinary (non-modern) `_meta` key. The
// legacy era requires no client metadata, and a fix for F1 must not ban every `_meta` object.
// Same shared factory, same fixed email override and the same explicit ordinary `_meta` probe.
let mut ordinary_params = counted_call_params(COUNTED_TOOL_NAME);
ordinary_params["arguments"]["email"] = json!("review8-f1-control-ordinary-meta@example.com");
ordinary_params["_meta"] = json!({ "crank.probe": "ordinary" });
let ordinary_meta = post_jsonrpc(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0",
"id": 812,
"method": "tools/call",
"params": ordinary_params
}),
)
.await;
assert!(
ordinary_meta["error"].is_null(),
"an ordinary non-modern `_meta` must not break a valid legacy call, got {ordinary_meta}"
);
assert_eq!(
ordinary_meta["result"]["structuredContent"],
json!({ "id": "lead_123" }),
"the ordinary-`_meta` positive control must return the published business payload, got \
{ordinary_meta}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
2,
"the second positive control must perform exactly one additional outbound call"
);
let calls_before_probe = fixture.calls.load(Ordering::SeqCst);
// The probe: an otherwise valid legacy-shaped `tools/call` whose `_meta` carries the
// modern-specific client identity without any version field, plus the explicit legacy version
// header on the same initialized session.
for (variant, with_client_info, id, correlation) in [
(
"clientCapabilities only",
false,
813_i64,
"review8-f1-capabilities-only",
),
(
"clientCapabilities plus clientInfo",
true,
814_i64,
"review8-f1-client-info",
),
] {
let headers = vec![
("MCP-Session-Id", session.clone()),
("MCP-Protocol-Version", LEGACY_REVISION.to_owned()),
];
let mut probe_params = counted_call_params(COUNTED_TOOL_NAME);
probe_params["arguments"]["email"] = json!("review8-f1@example.com");
// The adversarial modern-specific `_meta` stays exactly what it was: the same builder, still
// without any version carrier, so the probe only adds it to the shared business shape.
probe_params["_meta"] = review8_modern_meta_without_version(with_client_info);
let probe = json!({
"jsonrpc": "2.0",
"id": id,
"method": "tools/call",
"params": probe_params
});
let response = modern_post(&fixture.endpoint, &headers, probe, Some(correlation)).await;
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"{variant}: a rejected request must not mint a session"
);
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_eq!(
status, 400,
"{variant}: modern `_meta` without a version carrier must be rejected even when a \
legacy version header is present (matrix rows 4/16), got {raw}"
);
assert!(
!raw.trim().is_empty(),
"{variant}: the row-4 rejection must be a structured diagnostic, but the body was empty"
);
let body: Value = serde_json::from_str(&raw).unwrap_or_else(|error| {
panic!(
"{variant}: the row-4 rejection must be a JSON-RPC envelope, got {raw:?}: {error}"
)
});
assert_eq!(
body["jsonrpc"], "2.0",
"{variant}: the rejection must be a JSON-RPC 2.0 envelope, got {body}"
);
assert_eq!(
body["id"],
json!(id),
"{variant}: the rejection must keep the request id, got {body}"
);
assert_eq!(
body["error"]["code"],
json!(-32020),
"{variant}: a modern-specific 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()),
"{variant}: the rejection must carry a non-empty message, got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(correlation),
"{variant}: the rejection must preserve the request correlation, got {body}"
);
assert!(
body.get("result").is_none(),
"{variant}: a rejected request must not carry a result, got {body}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
calls_before_probe,
"{variant}: modern-specific metadata without a version carrier must not be executed as a \
legacy request"
);
}
}
/// Review pass 8 (F2 / matrix rows 3, 16 and 17): the era of an ambiguous `MCP-Session-Id` carrier
/// is read from the unambiguous part of the request, and a valid modern `MCP-Protocol-Version`
/// header is such a marker.
///
/// Static trace of the accepted freeze: `app.rs` `:827-830` projects
/// `protocol::ambiguous_session_carrier_response` (`protocol/mod.rs` `:480-488`) **before** era
/// resolution, and that projection asks `declares_modern_identity` (`:495-508`), which inspects only
/// the `Mcp-Method` header and the request `_meta`. A request that carries
/// `MCP-Protocol-Version: 2026-07-28` but no `Mcp-Method` and no `_meta` is therefore diagnosed in
/// the **legacy** shape (`:486` → `error_response` `:312-318`, `400` + `-32602`). Row 3 forbids
/// exactly that: "a modern header never routes the request into the legacy branch", and row 17
/// requires the era-correct structured diagnostic for an ambiguous carrier.
///
/// This is a compound *diagnostic* failure, not a successful modern admission: the request is
/// intentionally missing its required modern metadata and `Mcp-Method` header, so the expected
/// outcome stays a rejection — but the modern one (row 3/17: `400` + `-32020`) instead of a legacy
/// `-32602`. No result, no session minting and no outbound request in either shape.
async fn assert_modern_version_header_selects_the_modern_carrier_diagnostic(
session_values: [&'static str; 2],
correlation: &str,
id: Value,
) {
use std::sync::atomic::Ordering;
let fixture = counted_tool(None, &[PlatformApiKeyScope::Read]).await;
let message = json!({
"jsonrpc": "2.0",
"id": id.clone(),
"method": "tools/list",
"params": {}
});
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-session-id", session_values))
.header("MCP-Protocol-Version", MODERN_REVISION)
.json(&message)
.send()
.await
.unwrap();
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"an ambiguous session carrier must not mint a session ({correlation})"
);
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_eq!(
status, 400,
"an ambiguous session carrier is 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"], id,
"the ambiguous-session diagnostic must keep the request id ({correlation}), got {body}"
);
assert_eq!(
body["error"]["code"],
json!(-32020),
"matrix row 3: a request carrying a valid unambiguous modern version header must not be \
diagnosed in the legacy shape ({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 8 (F2): the numeric request id, first conflicting-value order.
#[tokio::test]
async fn review8_f2_modern_version_header_selects_the_modern_carrier_diagnostic() {
assert_modern_version_header_selects_the_modern_carrier_diagnostic(
["review8-f2-session-a", "review8-f2-session-b"],
"review8-f2-numeric-id",
json!(1),
)
.await;
}
/// Review pass 8 (F2, bounded sibling): the same compound diagnostic with a valid `string` request id
/// and the opposite conflicting-value order. The pinned `RequestId` is `string | number`, so the
/// diagnostic must keep the modern era shape and preserve the valid string id as well — this is one
/// bounded projection, not a cross-product of era × id × order.
#[tokio::test]
async fn review8_f2_string_request_id_keeps_the_modern_carrier_diagnostic() {
assert_modern_version_header_selects_the_modern_carrier_diagnostic(
["review8-f2-session-b", "review8-f2-session-a"],
"review8-f2-string-id",
json!("review8-f2-string"),
)
.await;
}