CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.
Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
resources/list admission fix for bound template publications.
Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
`just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
a real MCP Inspector 2.12.0 client smoke.
Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
runs only on main), story events run the changed packages, the full workspace suite
stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
release entry of the tag instead of dying with the runner workspace.
Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.
Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
744 lines
28 KiB
Rust
744 lines
28 KiB
Rust
//! 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(®istry, "sales-delete-lifecycle", vec![]).await;
|
|
let api_key = create_platform_api_key(
|
|
®istry,
|
|
"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(®istry, "sales-get-modern", vec![]).await;
|
|
let api_key = create_platform_api_key(
|
|
®istry,
|
|
"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(®istry, "sales-era-limit", vec![]).await;
|
|
let api_key = create_platform_api_key(
|
|
®istry,
|
|
"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(®istry, "sales-era-limit-delete", vec![]).await;
|
|
let api_key = create_platform_api_key(
|
|
®istry,
|
|
"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(®istry, "sales-old-session", vec![]).await;
|
|
let api_key = create_platform_api_key(
|
|
®istry,
|
|
"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(®istry, &operation, agent_slug).await;
|
|
let api_key = create_platform_api_key(
|
|
®istry,
|
|
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;
|
|
}
|