[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.
This commit is contained in:
Hermes DevOps committed 2026-10-25 10:00:22 +00:00
1 parent 1b6db09bd1
commit 75fe5a123c
357 files changed
+118831 -5113

No files matched your search

@@ -0,0 +1,483 @@
//! Legacy transport lifecycle and negotiation: initialized-notification gate, SSE GET/initialize,
//! expired and unknown sessions, the GET rate bucket, session-header requirement, DELETE and the
//! JSON-only response negotiation.
//!
//! Tests moved verbatim from `transport_protocol.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use axum::{
Json, Router,
http::header,
response::sse::{Event, KeepAlive, Sse},
routing::{get, post},
};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use crank_community_mcp::{
auth::{CommunityMachineCredentialVerifier, SharedMachineCredentialVerifier},
build_app,
catalog::PublishedToolCatalog,
session::{InMemorySessionStore, SharedSessionStore, TransportSessionStore},
};
use crank_core::{
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ExecutionConfig, HttpMethod,
Operation, OperationId, OperationStatus, PlatformApiKey, PlatformApiKeyId, PlatformApiKeyScope,
PlatformApiKeyStatus, Protocol, RestTarget, Target, ToolAccessMode, ToolDescription, ToolGroup,
ToolSearchSettings, ToolSelectionPolicy, WorkspaceId,
};
use crank_runtime::{
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, RuntimeExecutor,
SecretCrypto,
};
use futures_util::stream;
use serde_json::{Value, json};
use std::{
collections::BTreeMap,
io,
sync::{Arc, Mutex},
time::Duration,
};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use uuid::Version;
#[tokio::test]
async fn requires_initialized_notification_before_tool_methods() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-init", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-init",
"mcp-init",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-init");
let initialize_response = client
.post(&mcp_url)
.header(header::ACCEPT, "application/json, text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.json(&json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25"
}
}))
.send()
.await
.unwrap();
let session_id = initialize_response
.headers()
.get("MCP-Session-Id")
.unwrap()
.to_str()
.unwrap()
.to_owned();
let tools_list = client
.post(&mcp_url)
.header(header::ACCEPT, "application/json, text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", session_id)
.header("MCP-Protocol-Version", "2025-11-25")
.json(&json!({
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list",
"params": {}
}))
.send()
.await
.unwrap()
.json::<Value>()
.await
.unwrap();
assert_eq!(tools_list["error"]["code"], -32002);
}
#[tokio::test]
async fn initialize_can_return_sse_response_when_client_prefers_event_stream() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-sse-init", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-sse-init",
"mcp-sse-init",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let response = client
.post(agent_mcp_url(&base_url, "sales-sse-init"))
.header(header::ACCEPT, "text/event-stream, application/json")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.json(&json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25"
}
}))
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::OK);
assert_eq!(
response
.headers()
.get(header::CONTENT_TYPE)
.unwrap()
.to_str()
.unwrap(),
"text/event-stream"
);
assert!(response.headers().get("MCP-Session-Id").is_some());
let body = response.text().await.unwrap();
assert!(body.contains("\"jsonrpc\":\"2.0\""));
assert!(body.contains("\"protocolVersion\":\"2025-11-25\""));
}
#[tokio::test]
async fn get_opens_sse_stream_for_initialized_session() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-get-sse", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-get-sse",
"mcp-get-sse",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-get-sse");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let response = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &initialized_session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::OK);
assert_eq!(
response
.headers()
.get(header::CONTENT_TYPE)
.unwrap()
.to_str()
.unwrap(),
"text/event-stream"
);
assert_eq!(
response
.headers()
.get("MCP-Session-Id")
.unwrap()
.to_str()
.unwrap(),
initialized_session
);
}
#[tokio::test]
async fn get_returns_not_found_for_expired_transport_session() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-expired-session", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-expired-session",
"mcp-expired-session",
&[PlatformApiKeyScope::Read],
)
.await;
let session_store = Arc::new(InMemorySessionStore::default());
let session_id = session_store
.create(
"2025-11-25",
test_workspace_slug(),
"sales-expired-session",
false,
OffsetDateTime::parse("2026-05-01T10:00:00Z", &Rfc3339).unwrap(),
Some(OffsetDateTime::parse("2026-05-01T10:00:01Z", &Rfc3339).unwrap()),
)
.await
.unwrap();
session_store
.mark_initialized(
&session_id,
OffsetDateTime::parse("2026-05-01T10:00:01Z", &Rfc3339).unwrap(),
)
.await
.unwrap();
let base_url = spawn_mcp_server(build_test_app_with_store(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
RequestRateLimitConfig::new(10_000, 10_000).unwrap(),
session_store,
std::sync::Arc::new(CommunityMachineCredentialVerifier),
))
.await;
let client = reqwest::Client::new();
let response = client
.get(agent_mcp_url(&base_url, "sales-expired-session"))
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session_id)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn rejects_rapid_transport_get_requests_with_429() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-get-rate-limit", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-get-rate-limit",
"mcp-get-rate-limit",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app_with_rate_limit(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
RequestRateLimitConfig::new(1, 2).unwrap(),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-get-rate-limit");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let first_response = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &initialized_session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(first_response.status(), reqwest::StatusCode::OK);
let second_response = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &initialized_session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(
second_response.status(),
reqwest::StatusCode::TOO_MANY_REQUESTS
);
assert!(second_response.headers().get(header::RETRY_AFTER).is_some());
}
#[tokio::test]
async fn get_requires_session_header() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-get-sse-missing", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-get-sse-missing",
"mcp-get-sse-missing",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let response = client
.get(agent_mcp_url(&base_url, "sales-get-sse-missing"))
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("x-request-id", "req_early_mcp_error")
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::BAD_REQUEST);
assert_eq!(
response.headers()["x-request-id"].to_str().unwrap(),
"req_early_mcp_error"
);
let invalid_response = client
.get(agent_mcp_url(&base_url, "sales-get-sse-missing"))
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("x-request-id", "bad,value")
.send()
.await
.unwrap();
let generated = invalid_response.headers()["x-request-id"].to_str().unwrap();
assert_eq!(
uuid::Uuid::parse_str(generated).unwrap().get_version(),
Some(Version::SortRand)
);
}
#[tokio::test]
async fn delete_terminates_transport_session() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-delete-session", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-delete-session",
"mcp-delete-session",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-delete-session");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let delete_response = client
.delete(&mcp_url)
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &initialized_session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(delete_response.status(), reqwest::StatusCode::NO_CONTENT);
let after_delete = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &initialized_session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(after_delete.status(), reqwest::StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn initialize_accepts_json_only_response_negotiation() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-json-accept", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-json-accept",
"mcp-json-accept",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let response = client
.post(agent_mcp_url(&base_url, "sales-json-accept"))
.header(header::ACCEPT, "application/json")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.json(&json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25"
}
}))
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::OK);
assert_eq!(
response
.headers()
.get(header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.unwrap(),
"application/json"
);
}
#[tokio::test]
async fn rejects_get_with_protocol_version_mismatch() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-get-bad-version", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-get-bad-version",
"mcp-get-bad-version",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-get-bad-version");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let response = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &initialized_session)
.header("MCP-Protocol-Version", "2025-06-18")
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::BAD_REQUEST);
}
@@ -0,0 +1,468 @@
//! Request identity end to end: published tool call, preservation/generation of the request id and
//! the MCP ingress log projection, including this group's only-consumer log writer fixture.
//!
//! Tests moved verbatim from `transport_protocol.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use axum::{
Json, Router,
http::header,
response::sse::{Event, KeepAlive, Sse},
routing::{get, post},
};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use crank_core::{
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ExecutionConfig, HttpMethod,
Operation, OperationId, OperationStatus, PlatformApiKey, PlatformApiKeyId, PlatformApiKeyScope,
PlatformApiKeyStatus, Protocol, RestTarget, Target, ToolAccessMode, ToolDescription, ToolGroup,
ToolSearchSettings, ToolSelectionPolicy, WorkspaceId,
};
use crank_observability::{
ObservabilityConfig, RedactionLimits, ServiceIdentity, build_subscriber,
};
use crank_registry::{
CreateAgentRequest, CreatePlatformApiKeyRequest, ListInvocationLogsQuery, PostgresRegistry,
PublishAgentRequest, PublishRequest, SaveAgentBindingsRequest,
};
use serde_json::{Value, json};
use std::{
collections::BTreeMap,
io,
sync::{Arc, Mutex},
time::Duration,
};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use tracing_subscriber::fmt::MakeWriter;
use uuid::Version;
#[derive(Clone, Default)]
struct SharedLogWriter {
buffer: Arc<Mutex<Vec<u8>>>,
}
impl SharedLogWriter {
fn output(&self) -> String {
String::from_utf8(self.buffer.lock().unwrap().clone()).unwrap()
}
}
impl<'a> MakeWriter<'a> for SharedLogWriter {
type Writer = SharedLogGuard;
fn make_writer(&'a self) -> Self::Writer {
SharedLogGuard {
buffer: Arc::clone(&self.buffer),
}
}
}
struct SharedLogGuard {
buffer: Arc<Mutex<Vec<u8>>>,
}
impl io::Write for SharedLogGuard {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
self.buffer.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[tokio::test]
async fn initializes_lists_and_calls_published_tool_via_mcp() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let operation = test_operation(&upstream_base_url, "crm_create_lead");
registry
.create_operation(&test_workspace_id(), &operation, Some("alice"))
.await
.unwrap();
registry
.publish_operation(PublishRequest {
workspace_id: &test_workspace_id(),
operation_id: &operation.id,
version: 1,
published_at: &OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-rest").await;
let api_key = create_platform_api_key(
&registry,
"sales-rest",
"mcp-rest",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-rest");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let tools = post_jsonrpc(
&client,
&mcp_url,
&api_key,
Some(&initialized_session),
json!({
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list",
"params": {}
}),
)
.await;
let call_result = post_jsonrpc(
&client,
&mcp_url,
&api_key,
Some(&initialized_session),
json!({
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "crm_create_lead",
"arguments": {
"email": "user@example.com"
}
}
}),
)
.await;
assert_eq!(tools["result"]["tools"][0]["name"], "crm_create_lead");
assert_eq!(
call_result["result"]["structuredContent"],
json!({ "id": "lead_123" })
);
assert_eq!(call_result["result"]["isError"], false);
let logs = registry
.list_invocation_logs(ListInvocationLogsQuery {
workspace_id: &test_workspace_id(),
level: None,
status: None,
outcome_group: None,
search_text: None,
source: Some(crank_core::InvocationSource::AgentToolCall),
operation_id: Some(&operation.id),
agent_id: None,
created_after: None,
created_before: None,
cursor_created_at: None,
cursor_id: None,
limit: 10,
})
.await
.unwrap();
assert_eq!(logs.len(), 1);
assert_eq!(
logs[0].log.source,
crank_core::InvocationSource::AgentToolCall
);
assert_eq!(logs[0].log.status, crank_core::InvocationStatus::Ok);
assert_eq!(logs[0].log.tool_name, "crm_create_lead");
let keys = registry
.list_platform_api_keys(&test_workspace_id())
.await
.unwrap();
assert!(keys[0].api_key.last_used_at.is_some());
}
#[tokio::test]
async fn preserves_request_id_for_tool_call_invocations() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let operation = test_operation(&upstream_base_url, "crm_request_id");
registry
.create_operation(&test_workspace_id(), &operation, Some("alice"))
.await
.unwrap();
registry
.publish_operation(PublishRequest {
workspace_id: &test_workspace_id(),
operation_id: &operation.id,
version: 1,
published_at: &OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-request-id").await;
let api_key = create_platform_api_key(
&registry,
"sales-request-id",
"mcp-request-id",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-request-id");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let response = post_jsonrpc_response(
&client,
&mcp_url,
&api_key,
Some(&initialized_session),
Some("req_test_123"),
json!({
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "crm_request_id",
"arguments": {
"email": "user@example.com"
}
}
}),
)
.await;
assert_eq!(
response.headers()["x-request-id"].to_str().unwrap(),
"req_test_123"
);
let trace_id = response.headers()["x-trace-id"]
.to_str()
.unwrap()
.to_owned();
let call_result = response.json::<Value>().await.unwrap();
assert_eq!(call_result["result"]["isError"], false);
let logs = registry
.list_invocation_logs(ListInvocationLogsQuery {
workspace_id: &test_workspace_id(),
level: None,
status: None,
outcome_group: None,
search_text: None,
source: Some(crank_core::InvocationSource::AgentToolCall),
operation_id: Some(&operation.id),
agent_id: None,
created_after: None,
created_before: None,
cursor_created_at: None,
cursor_id: None,
limit: 10,
})
.await
.unwrap();
assert_eq!(logs.len(), 1);
assert_eq!(logs[0].log.request_id.as_deref(), Some("req_test_123"));
assert_eq!(logs[0].log.trace_id.as_deref(), Some(trace_id.as_str()));
}
#[tokio::test]
async fn generates_request_id_for_tool_call_responses_and_logs() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let operation = test_operation(&upstream_base_url, "crm_generated_request_id");
registry
.create_operation(&test_workspace_id(), &operation, Some("alice"))
.await
.unwrap();
registry
.publish_operation(PublishRequest {
workspace_id: &test_workspace_id(),
operation_id: &operation.id,
version: 1,
published_at: &OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-generated-request-id").await;
let api_key = create_platform_api_key(
&registry,
"sales-generated-request-id",
"mcp-generated-request-id",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-generated-request-id");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let response = post_jsonrpc_response(
&client,
&mcp_url,
&api_key,
Some(&initialized_session),
None,
json!({
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "crm_generated_request_id",
"arguments": {
"email": "user@example.com"
}
}
}),
)
.await;
let request_id = response
.headers()
.get("x-request-id")
.unwrap()
.to_str()
.unwrap()
.to_owned();
let trace_id = response
.headers()
.get("x-trace-id")
.unwrap()
.to_str()
.unwrap()
.to_owned();
assert_eq!(
uuid::Uuid::parse_str(&request_id).unwrap().get_version(),
Some(Version::SortRand)
);
let call_result = response.json::<Value>().await.unwrap();
assert_eq!(call_result["result"]["isError"], false);
let logs = registry
.list_invocation_logs(ListInvocationLogsQuery {
workspace_id: &test_workspace_id(),
level: None,
status: None,
outcome_group: None,
search_text: None,
source: Some(crank_core::InvocationSource::AgentToolCall),
operation_id: Some(&operation.id),
agent_id: None,
created_after: None,
created_before: None,
cursor_created_at: None,
cursor_id: None,
limit: 10,
})
.await
.unwrap();
assert_eq!(logs.len(), 1);
assert_eq!(logs[0].log.request_id.as_deref(), Some(request_id.as_str()));
assert_eq!(logs[0].log.trace_id.as_deref(), Some(trace_id.as_str()));
}
#[tokio::test(flavor = "current_thread")]
async fn emits_request_id_in_mcp_ingress_logs() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let operation = test_operation(&upstream_base_url, "crm_request_trace");
registry
.create_operation(&test_workspace_id(), &operation, Some("alice"))
.await
.unwrap();
registry
.publish_operation(PublishRequest {
workspace_id: &test_workspace_id(),
operation_id: &operation.id,
version: 1,
published_at: &OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-request-trace").await;
let api_key = create_platform_api_key(
&registry,
"sales-request-trace",
"mcp-request-trace",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let writer = SharedLogWriter::default();
let subscriber = build_subscriber(
ObservabilityConfig::new(
ServiceIdentity::try_new("mcp-server", "test", "test").unwrap(),
"info",
RedactionLimits::default(),
),
writer.clone(),
)
.unwrap();
let dispatch = tracing::Dispatch::new(subscriber);
let _guard = tracing::dispatcher::set_default(&dispatch);
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-request-trace");
let response = post_jsonrpc_response(
&client,
&mcp_url,
&api_key,
None,
Some("req_mcp_trace_123"),
json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25"
}
}),
)
.await;
assert_eq!(
response.headers()["x-request-id"].to_str().unwrap(),
"req_mcp_trace_123"
);
assert_eq!(response.status(), reqwest::StatusCode::OK);
let logs = writer.output();
let event = logs
.lines()
.filter_map(|line| serde_json::from_str::<Value>(line).ok())
.find(|event| event["event"] == "mcp.request.received")
.unwrap();
assert_eq!(event["service"], "mcp-server");
assert_eq!(event["request_id"], "req_mcp_trace_123");
assert_eq!(event["fields"]["agent_slug"], "sales-request-trace");
assert_eq!(event["fields"]["workspace_slug"], "default");
assert_eq!(event["fields"]["jsonrpc_method"], "initialize");
}
@@ -0,0 +1,743 @@
//! Modern identity and persisted-withdrawn-session restrictions on GET/DELETE/POST (r11/r17/r18/r29),
//! with the fixtures those scenarios own.
//!
//! Tests moved verbatim from `transport_protocol.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use axum::{
Json, Router,
http::header,
response::sse::{Event, KeepAlive, Sse},
routing::{get, post},
};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use crank_community_mcp::{
auth::{CommunityMachineCredentialVerifier, SharedMachineCredentialVerifier},
build_app,
catalog::PublishedToolCatalog,
session::{InMemorySessionStore, SharedSessionStore, TransportSessionStore},
};
use crank_core::{
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ExecutionConfig, HttpMethod,
Operation, OperationId, OperationStatus, PlatformApiKey, PlatformApiKeyId, PlatformApiKeyScope,
PlatformApiKeyStatus, Protocol, RestTarget, Target, ToolAccessMode, ToolDescription, ToolGroup,
ToolSearchSettings, ToolSelectionPolicy, WorkspaceId,
};
use crank_registry::{
CreateAgentRequest, CreatePlatformApiKeyRequest, ListInvocationLogsQuery, PostgresRegistry,
PublishAgentRequest, PublishRequest, SaveAgentBindingsRequest,
};
use crank_runtime::{
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, RuntimeExecutor,
SecretCrypto,
};
use futures_util::stream;
use serde_json::{Value, json};
use std::{
collections::BTreeMap,
io,
sync::{Arc, Mutex},
time::Duration,
};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use tokio::net::TcpListener;
use uuid::Version;
// ---------------------------------------------------------------------------------------------
// Review pass 2 regressions (R11): session lifecycle must not cross eras. Test-only stage.
// ---------------------------------------------------------------------------------------------
/// R11: an authenticated `DELETE` carrying the modern revision (the modern era has no session to
/// terminate, so the method is not available) or an unknown/withdrawn revision (a safe admission
/// error) must be rejected **and must not terminate the live legacy session**. A legitimate legacy
/// `DELETE` still terminates it, and the next one reports `404`.
#[tokio::test]
async fn r11_delete_without_legacy_revision_does_not_terminate_the_session() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-delete-lifecycle", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-delete-lifecycle",
"mcp-delete-lifecycle",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-delete-lifecycle");
let session = initialize_session(&client, &mcp_url, &api_key).await;
for (revision, expected_status) in [
("2026-07-28", reqwest::StatusCode::METHOD_NOT_ALLOWED),
("1999-01-01", reqwest::StatusCode::BAD_REQUEST),
("2025-03-26", reqwest::StatusCode::BAD_REQUEST),
] {
let rejected = client
.delete(&mcp_url)
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", revision)
.send()
.await
.unwrap();
assert_eq!(
rejected.status(),
expected_status,
"DELETE with revision {revision} must be rejected"
);
let list = client
.post(&mcp_url)
.header(header::ACCEPT, "application/json")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.json(&json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {} }))
.send()
.await
.unwrap();
assert_eq!(
list.status(),
reqwest::StatusCode::OK,
"the rejected DELETE ({revision}) must not terminate the live legacy session"
);
}
let terminated = client
.delete(&mcp_url)
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(
terminated.status(),
reqwest::StatusCode::NO_CONTENT,
"a legitimate legacy DELETE must still terminate the session"
);
let second_delete = client
.delete(&mcp_url)
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(
second_delete.status(),
reqwest::StatusCode::NOT_FOUND,
"a terminated session must report not found"
);
}
/// R11 (GET half): the modern revision has no standalone GET stream endpoint, so an explicit modern
/// identity must be answered with `405 Method Not Allowed` instead of carrying the legacy GET path.
/// The live session must stay untouched.
#[tokio::test]
async fn r11_get_with_modern_identity_is_method_not_allowed() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-get-modern", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-get-modern",
"mcp-get-modern",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-get-modern");
let session = initialize_session(&client, &mcp_url, &api_key).await;
let response = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2026-07-28")
.send()
.await
.unwrap();
assert_eq!(
response.status(),
reqwest::StatusCode::METHOD_NOT_ALLOWED,
"the modern revision removed the GET stream endpoint"
);
let list = client
.post(&mcp_url)
.header(header::ACCEPT, "application/json")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.json(&json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {} }))
.send()
.await
.unwrap();
assert_eq!(
list.status(),
reqwest::StatusCode::OK,
"a rejected modern GET must not disturb the legacy session"
);
}
// ---------------------------------------------------------------------------------------------
// Review pass 3 regressions (R17, R18). Test-only stage: production is read-only here.
// ---------------------------------------------------------------------------------------------
/// R17 (GET half): the legacy rate bucket must not shadow the modern era admission. The limiter is a
/// token bucket (`RequestRateLimitConfig::new(requests_per_second, burst)`) keyed per session once a
/// session carrier is present, so the handshake's `notifications/initialized` POST already consumes one
/// token from the same bucket the `GET` uses. With `burst = 3` exactly two tokens remain for the
/// sequence: a legitimate legacy GET consumes one, an explicit modern GET is rejected by the era
/// admission with `405` **without** consuming a token (proved by the next legacy GET still being
/// admitted), and the final legacy GET is limited once the bucket is empty — the legacy semantics are
/// unchanged. The `429` is asserted to come from the rate limiter (it carries `Retry-After`), not from
/// the concurrent-stream slot guard, which would make the oracle ambiguous.
#[tokio::test]
async fn r17_modern_get_is_not_shadowed_by_the_legacy_rate_bucket() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-era-limit", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-era-limit",
"mcp-era-limit",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app_with_rate_limit(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
RequestRateLimitConfig::new(1, 3).unwrap(),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-era-limit");
// The refill bound starts before the handshake: the session-scoped bucket is consumed by the
// handshake's `notifications/initialized` too, so the timing window must cover the whole
// token-consuming sequence (handshake + GETs), not only the part after `initialize_session` returned.
let sequence_started = std::time::Instant::now();
let session = initialize_session(&client, &mcp_url, &api_key).await;
let legacy_get = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(
legacy_get.status(),
reqwest::StatusCode::OK,
"the first legitimate legacy GET consumes the first bucket slot"
);
let modern_get = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2026-07-28")
.send()
.await
.unwrap();
assert_eq!(
modern_get.status(),
reqwest::StatusCode::METHOD_NOT_ALLOWED,
"the modern era admission must decide before the legacy rate bucket"
);
let second_legacy_get = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(
second_legacy_get.status(),
reqwest::StatusCode::OK,
"a rejected modern GET must not consume the legacy bucket"
);
let third_legacy_get = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(
third_legacy_get.status(),
reqwest::StatusCode::TOO_MANY_REQUESTS,
"the legacy bucket semantics themselves stay unchanged"
);
assert!(
third_legacy_get.headers().get("retry-after").is_some(),
"the 429 must come from the request rate limiter (it carries `Retry-After`), not from the \
concurrent-stream slot guard"
);
// Timing precondition: the local token bucket refills one token per second, so the assertions above
// only hold while the whole consuming sequence — handshake included — stays inside one refill window.
// A slower sequence makes this timing oracle inconclusive and is reported as such instead of staying
// silently GREEN. No production threshold was changed for this.
assert!(
sequence_started.elapsed() < Duration::from_secs(1),
"the GET sequence including the handshake took {:?}; with a 1 token/s bucket this timing oracle \
is inconclusive",
sequence_started.elapsed()
);
}
/// R17 (DELETE half): the same ordering rule for the terminating method. The session-scoped bucket is
/// shared with the handshake's `notifications/initialized`, so with `burst = 2` exactly one token is
/// left for the sequence: under the old ordering the modern DELETE occupied it and the following
/// legitimate legacy DELETE would be limited; once the admission decides first, the modern rejection
/// consumes nothing and the legacy DELETE still returns `204`.
#[tokio::test]
async fn r17_modern_delete_is_rejected_before_the_legacy_rate_bucket() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-era-limit-delete", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-era-limit-delete",
"mcp-era-limit-delete",
&[PlatformApiKeyScope::Read],
)
.await;
let base_url = spawn_mcp_server(build_test_app_with_rate_limit(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
RequestRateLimitConfig::new(1, 2).unwrap(),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-era-limit-delete");
// The refill bound starts before the handshake (see the GET regression).
let sequence_started = std::time::Instant::now();
let session = initialize_session(&client, &mcp_url, &api_key).await;
let modern_delete = client
.delete(&mcp_url)
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2026-07-28")
.send()
.await
.unwrap();
assert_eq!(
modern_delete.status(),
reqwest::StatusCode::METHOD_NOT_ALLOWED,
"the modern era admission must decide before the legacy rate bucket"
);
let legacy_delete = client
.delete(&mcp_url)
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", "2025-11-25")
.send()
.await
.unwrap();
assert_eq!(
legacy_delete.status(),
reqwest::StatusCode::NO_CONTENT,
"a rejected modern DELETE must not consume the legacy bucket"
);
// Timing precondition for the 1 token/s bucket: the bound covers the handshake and the DELETE
// sequence, so a refill inside the window is reported as an inconclusive oracle.
assert!(
sequence_started.elapsed() < Duration::from_secs(1),
"the DELETE sequence including the handshake took {:?}; with a 1 token/s bucket this timing \
oracle is inconclusive",
sequence_started.elapsed()
);
}
/// R18: a session persisted under a withdrawn revision must not be served as a live legacy session.
/// The session store is seeded directly (a withdrawn `initialize` is rejected, so an old session cannot
/// be created through the normal path) and the identity is taken from the session itself (no version
/// header).
///
/// Oracle provenance (corrected after TL review): `protocol-era-matrix.md` row 15 requires a **safe
/// structured error** for a withdrawn revision, while `405` is reserved for the modern identity
/// (row 20). A persisted `2025-03-26` session is therefore expected to be rejected with `400`, not
/// `405`; the earlier `405` expectation in this test was wrong and is preserved only as history in
/// `transport_protocol-attempt1-*.log`. The legitimate legacy path (`2025-11-25`, header absent) must
/// keep working.
#[tokio::test]
async fn r18_get_delete_reject_persisted_withdrawn_session_without_version_header() {
let registry = test_registry().await;
publish_agent_with_bindings(&registry, "sales-old-session", vec![]).await;
let api_key = create_platform_api_key(
&registry,
"sales-old-session",
"mcp-old-session",
&[PlatformApiKeyScope::Read],
)
.await;
let sessions = Arc::new(InMemorySessionStore::default());
let now = OffsetDateTime::now_utc();
let withdrawn = sessions
.create(
"2025-03-26",
test_workspace_slug(),
"sales-old-session",
false,
now,
None,
)
.await
.unwrap();
sessions.mark_initialized(&withdrawn, now).await.unwrap();
let legacy = sessions
.create(
"2025-11-25",
test_workspace_slug(),
"sales-old-session",
false,
now,
None,
)
.await
.unwrap();
sessions.mark_initialized(&legacy, now).await.unwrap();
let base_url = spawn_mcp_server(build_test_app_with_store(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
RequestRateLimitConfig::new(10_000, 10_000).unwrap(),
sessions.clone(),
Arc::new(CommunityMachineCredentialVerifier),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-old-session");
let get = client
.get(&mcp_url)
.header(header::ACCEPT, "text/event-stream")
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &withdrawn)
.send()
.await
.unwrap();
assert_eq!(
get.status(),
reqwest::StatusCode::BAD_REQUEST,
"a persisted withdrawn session must not open a legacy stream; matrix row 15 requires a safe error (405 belongs to the modern identity, row 20)"
);
let delete = client
.delete(&mcp_url)
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &withdrawn)
.send()
.await
.unwrap();
assert_eq!(
delete.status(),
reqwest::StatusCode::BAD_REQUEST,
"a persisted withdrawn session must not be terminated as a legacy session; matrix row 15 requires a safe error"
);
assert!(
sessions.get(&withdrawn).await.unwrap().is_some(),
"the withdrawn session state must be retained"
);
let legacy_delete = client
.delete(&mcp_url)
.header(header::AUTHORIZATION, format!("Bearer {api_key}"))
.header("MCP-Session-Id", &legacy)
.send()
.await
.unwrap();
assert_eq!(
legacy_delete.status(),
reqwest::StatusCode::NO_CONTENT,
"the legitimate legacy path without a version header must keep working"
);
assert!(sessions.get(&legacy).await.unwrap().is_none());
}
/// Test-only counted upstream (same shape as the revision-matrix fixture): every lead request
/// increments the counter, so a rejection can be proven to have performed **no** outbound request.
async fn spawn_counted_lead_upstream(calls: Arc<std::sync::atomic::AtomicUsize>) -> String {
let handler_calls = Arc::clone(&calls);
let app = Router::new().route(
"/crm/leads",
post(move |Json(payload): Json<Value>| {
let calls = Arc::clone(&handler_calls);
async move {
calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Json(json!({ "id": "lead_123", "email": payload["email"] }))
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
format!("http://{address}")
}
/// Shared R29 fixture: a counted upstream behind a published `crm_counted_lead` operation, a
/// transport session negotiated on a withdrawn revision (created in the shared store and marked
/// initialized, i.e. a session the server accepted while it was still inside the window), and the
/// credentials needed to POST against it.
struct WithdrawnSessionPostFixture {
client: reqwest::Client,
mcp_url: String,
api_key: String,
sessions: Arc<InMemorySessionStore>,
withdrawn: String,
calls: Arc<std::sync::atomic::AtomicUsize>,
}
async fn withdrawn_session_post_fixture(agent_slug: &str) -> WithdrawnSessionPostFixture {
let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let upstream_base_url = spawn_counted_lead_upstream(Arc::clone(&calls)).await;
let registry = test_registry().await;
let operation = test_operation(&upstream_base_url, "crm_counted_lead");
registry
.create_operation(&test_workspace_id(), &operation, Some("alice"))
.await
.unwrap();
registry
.publish_operation(PublishRequest {
workspace_id: &test_workspace_id(),
operation_id: &operation.id,
version: 1,
published_at: &OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, agent_slug).await;
let api_key = create_platform_api_key(
&registry,
agent_slug,
"mcp-withdrawn-post",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let sessions = Arc::new(InMemorySessionStore::default());
let now = OffsetDateTime::now_utc();
let withdrawn = sessions
.create(
"2025-03-26",
test_workspace_slug(),
agent_slug,
false,
now,
None,
)
.await
.unwrap();
sessions.mark_initialized(&withdrawn, now).await.unwrap();
let base_url = spawn_mcp_server(build_test_app_with_store(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
RequestRateLimitConfig::new(10_000, 10_000).unwrap(),
sessions.clone(),
Arc::new(CommunityMachineCredentialVerifier),
))
.await;
WithdrawnSessionPostFixture {
client: reqwest::Client::new(),
mcp_url: agent_mcp_url(&base_url, agent_slug),
api_key,
sessions,
withdrawn,
calls,
}
}
/// Shared R29 oracle (review pass 6, P7): a legacy POST whose persisted session is no longer
/// operational must be answered with the era-correct **legacy** structured error — a complete
/// JSON-RPC 2.0 envelope with the original id, a numeric code, a non-empty message, the preserved
/// request correlation and no `result` key at all — must leave the persisted session intact and must
/// not perform the outbound call.
///
/// The exact legacy code is deliberately **not** pinned: matrix row 14 records that the modern
/// `-32022` contract is not imposed on a legacy-shaped rejection, so only the modern diagnostics are
/// excluded here.
async fn assert_r29_structured_rejection(
fixture: &WithdrawnSessionPostFixture,
status: u16,
raw: &str,
correlation: &str,
) {
use std::sync::atomic::Ordering;
assert_eq!(
status, 400,
"a persisted withdrawn session must not be served (matrix row 15), got {raw}"
);
assert!(
!raw.trim().is_empty(),
"matrix row 15 requires a safe **structured** error, but the legacy POST rejection answered \
{status} with an empty body"
);
let body: Value = serde_json::from_str(raw).unwrap_or_else(|error| {
panic!("the row-15 rejection must be a JSON-RPC error envelope, got {raw:?}: {error}")
});
assert_eq!(body["jsonrpc"], "2.0", "got {body}");
assert_eq!(
body["id"],
json!(30),
"the legacy rejection must keep the JSON-RPC request id, got {body}"
);
assert!(
body["error"]["code"].is_i64(),
"the legacy rejection must carry a numeric JSON-RPC code, got {body}"
);
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"the legacy rejection must carry a non-empty message, got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(correlation),
"the legacy rejection must preserve the request correlation, got {body}"
);
assert_ne!(
body["error"]["code"],
json!(-32022),
"the modern UnsupportedProtocolVersionError must not be imposed on a legacy-sourced \
rejection (matrix row 14), got {body}"
);
assert_ne!(
body["error"]["code"],
json!(-32020),
"the modern HeaderMismatch code must not be imposed on a legacy-sourced rejection, got {body}"
);
assert!(
body.get("result").is_none(),
"a rejected request must not carry a `result` key at all, got {body}"
);
assert!(
body["result"].is_null(),
"a rejected request must not carry a result, got {body}"
);
let retained = fixture
.sessions
.get(&fixture.withdrawn)
.await
.unwrap()
.expect("the withdrawn session must be retained");
assert!(
retained.initialized,
"the rejected request must not mutate the persisted session state"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"a rejected request must not perform the outbound call"
);
}
/// R29 (header/session half): a legacy POST that names the served legacy revision in its
/// `MCP-Protocol-Version` header while the **persisted** session was negotiated on a withdrawn
/// revision. The first rejection here is the header/session-revision comparison (`app.rs` 873-875):
/// `2025-11-25` is a supported revision that contradicts the persisted `2025-03-26`.
///
/// Review pass 6 (P6) provenance correction: this is what the earlier `post_jsonrpc_response`-based
/// case actually exercised — that helper always adds the legacy version header
/// (`common.rs` 253-257), so the case never was a no-header case and the earlier "no version header"
/// claim was false. The no-header half is covered separately by
/// `r29_legacy_post_without_version_header_on_withdrawn_session_is_a_structured_error`.
#[tokio::test]
async fn r29_legacy_post_with_version_header_on_withdrawn_session_is_a_structured_error() {
let fixture = withdrawn_session_post_fixture("sales-withdrawn-post").await;
let response = post_jsonrpc_response(
&fixture.client,
&fixture.mcp_url,
&fixture.api_key,
Some(&fixture.withdrawn),
Some("r29-legacy-post"),
json!({
"jsonrpc": "2.0",
"id": 30,
"method": "tools/call",
"params": { "name": "crm_counted_lead", "arguments": { "email": "withdrawn@example.com" } }
}),
)
.await;
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_r29_structured_rejection(&fixture, status, &raw, "r29-legacy-post").await;
}
/// R29 (no-header half, matrix rows 10/15): a legacy POST that carries **no** version header at all —
/// the identity comes from the persisted session itself — while that persisted session was negotiated
/// on a withdrawn revision. `post_jsonrpc_with_headers` sends only the headers passed to it, so this
/// request really omits `MCP-Protocol-Version`; the session carrier, the JSON-RPC id and the request
/// correlation are the only inputs.
///
/// Review pass 6 (P6): this is the true no-header case the earlier R29 acceptance claim was missing.
/// Honest result note: on the frozen revision this path is already answered by the structured
/// rejection introduced in the review-5 BUILD (`app.rs` 873-887), i.e. expected existing GREEN — the
/// oracle is added because the coverage claim was false, not because a RED was manufactured.
#[tokio::test]
async fn r29_legacy_post_without_version_header_on_withdrawn_session_is_a_structured_error() {
let fixture = withdrawn_session_post_fixture("sales-withdrawn-no-header").await;
let response = post_jsonrpc_with_headers(
&fixture.client,
&fixture.mcp_url,
&fixture.api_key,
&[
("MCP-Session-Id", fixture.withdrawn.as_str()),
("x-request-id", "r29-no-header-post"),
],
json!({
"jsonrpc": "2.0",
"id": 30,
"method": "tools/call",
"params": { "name": "crm_counted_lead", "arguments": { "email": "withdrawn@example.com" } }
}),
)
.await;
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_r29_structured_rejection(&fixture, status, &raw, "r29-no-header-post").await;
}