//! Story 3.8 / AT-3.8-04, AT-3.8-05 — missing capability RED: a Resource-wide security revoke. //! //! Owner decision A (`t_6f76be08`): revoking a Resource denies every version of it in every Agent, //! including already published snapshots, disallows new publications/bindings, keeps archive, //! immutable bytes and the protected administrative read. This file is the pre-build checkpoint: //! it proves the capability is absent, not that the implementation is correct. //! //! Everything below runs on the real stack reused from the accepted Story 3.6/3.7 suites: //! Resources are created and published through the real Admin HTTP API (multipart Draft + publish), //! the Agent is bound and published through the real Admin router with an Owner session and CSRF, //! the MCP key comes from the real `platform-api-keys` endpoint, and `resources/list` / //! `resources/read` go through the real MCP HTTP dispatch for both supported revisions //! (`tests/fixtures/mcp-revisions/supported-revisions.json`). No route stub, no fake service. //! //! Expected today: `POST .../resources/{id}/revoke` does not exist (fallback 404 instead of 204), //! so `resources/list` still advertises the Resource and `resources/read` still returns its bytes. //! After the build the same test must see 204, the Resource gone from `list`, and the existing //! safe `-32602 "the requested resource is not available"` outcome before any artifact byte. //! //! The archive positive control is not duplicated or weakened here: it stays //! `archive_keeps_the_exact_published_snapshot_readable_for_the_bound_agent` in //! `apps/mcp-server/tests/integration/static_resources/lifecycle.rs`. //! //! Run: `SQLX_OFFLINE=true CARGO_BUILD_JOBS=2 CARGO_INCREMENTAL=0 \ //! cargo test -p admin-api --test integration story38_revoke -- --test-threads=1` use std::{ fs, path::{Path, PathBuf}, time::Duration, }; use crank_artifacts::ArtifactStore; use crank_community_mcp::{ auth::CommunityMachineCredentialVerifier, build_app_with_artifacts, session::InMemorySessionStore, }; use crank_core::PlatformApiKeyKind; use crank_registry::PostgresRegistry; use crank_runtime::{InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter}; use reqwest::StatusCode; use serde_json::{Value, json}; use tokio::net::TcpListener; use super::super::common::{ agent_etag, assert_success_json, authorized_client, build_test_app, test_registry, test_secret_crypto, test_storage_root, }; use super::helpers::{ create_draft, created_resource_id, draft_metadata, draft_updated_at, get_card, read_response, sha256_hex, }; pub(super) const MODERN_REVISION: &str = "2026-07-28"; pub(super) const LEGACY_REVISION: &str = "2025-11-25"; pub(super) const WORKSPACE_SLUG: &str = "default"; pub(super) const REVOKED_URI: &str = "crank://resources/story38-revoke-target"; pub(super) const REVOKED_NAME: &str = "story38_revoke_target"; pub(super) const REVOKED_CANARY: &str = "story38 revocation target v1\n"; pub(super) const KEPT_URI: &str = "crank://resources/story38-revoke-control"; pub(super) const KEPT_NAME: &str = "story38_revoke_control"; pub(super) const KEPT_CANARY: &str = "story38 revocation control v1\n"; /// Вторая версия того же Resource (owner decision A: отзыв закрывает все версии). pub(super) const REVOKED_CANARY_V2: &str = "story38 revocation target v2\n"; /// The pinned safe outcome every denied Resource read must reuse (ARC §3, `dispatch.rs`). pub(super) const NOT_AVAILABLE_CODE: i64 = -32602; pub(super) const NOT_AVAILABLE_MESSAGE: &str = "the requested resource is not available"; // --------------------------------------------------------------------------- // Fixture: Admin HTTP stack + in-process MCP dispatch over the same registry/root // --------------------------------------------------------------------------- pub(super) struct RevocationStand { /// Workspace-scoped Admin API base URL (`.../api/admin/workspaces/ws_default`). pub(super) server: String, pub(super) admin: reqwest::Client, pub(super) mcp: reqwest::Client, pub(super) mcp_url: String, pub(super) mcp_key: String, /// Second published Agent with a warmed cache, bound to version 2 of the target. pub(super) mcp_url_second: String, pub(super) mcp_key_second: String, pub(super) registry: PostgresRegistry, /// Resource that the scenario revokes. pub(super) revoked_id: String, /// Unrevoked control Resource bound to both Agents. pub(super) kept_id: String, /// MCP listener base (`http://host:port`) of the first service instance. pub(super) mcp_base: String, pub(super) storage_root: PathBuf, } pub(super) async fn spawn_revocation_stand(name: &str) -> RevocationStand { spawn_revocation_stand_with_refresh(name, Duration::from_millis(0)).await } /// Same stand, but with a non-zero catalog refresh interval, so a warmed catalog cache can be /// proven not to serve a Resource after the live PostgreSQL gate fails. pub(super) async fn spawn_revocation_stand_with_refresh( name: &str, refresh_interval: Duration, ) -> RevocationStand { let registry = test_registry().await; let storage_root = test_storage_root(name); let server = spawn_admin_router(build_test_app(registry.clone(), storage_root.clone())).await; let admin = authorized_client(&server).await; let revoked_id = create_published_resource(&admin, &server, REVOKED_URI, REVOKED_NAME, REVOKED_CANARY).await; let kept_id = create_published_resource(&admin, &server, KEPT_URI, KEPT_NAME, KEPT_CANARY).await; // Owner decision A covers every version of the Resource; the second published // version gives the build a real multi-version target. publish_resource_version( &admin, &server, &revoked_id, REVOKED_URI, REVOKED_NAME, REVOKED_CANARY_V2, ) .await; let agent_slug = format!("story38-revoke-{name}"); let agent_id = create_published_resource_only_agent( &admin, &server, &agent_slug, &[(&revoked_id, 1), (&kept_id, 1)], ) .await; let mcp_key = create_mcp_key(&admin, &server, &agent_id).await; let second_slug = format!("story38-revoke-{name}-v2"); let second_agent_id = create_published_resource_only_agent( &admin, &server, &second_slug, &[(&revoked_id, 2), (&kept_id, 1)], ) .await; let mcp_key_second = create_mcp_key(&admin, &server, &second_agent_id).await; let mcp_app = build_mcp_app(registry.clone(), &storage_root, refresh_interval); let mcp_base = spawn_mcp_server(mcp_app).await; let mcp_url = format!("{mcp_base}/v1/{WORKSPACE_SLUG}/{agent_slug}"); let mcp_url_second = format!("{mcp_base}/v1/{WORKSPACE_SLUG}/{second_slug}"); RevocationStand { server, admin, mcp: reqwest::Client::new(), mcp_url, mcp_key, mcp_url_second, mcp_key_second, registry, revoked_id, kept_id, mcp_base, storage_root, } } /// Spawn the real Admin router without the graceful-shutdown `Drop` guard: an expected RED panic /// must not turn into a process abort while the fixture is being torn down. async fn spawn_admin_router(app: axum::Router) -> String { let listener = TcpListener::bind("127.0.0.1:0") .await .expect("Admin test listener must bind"); let address = listener.local_addr().expect("Admin test listener address"); tokio::spawn(async move { axum::serve(listener, app) .await .expect("Admin test server must serve"); }); format!("http://{address}/api/admin/workspaces/ws_default") } pub(super) async fn create_published_resource( client: &reqwest::Client, server: impl AsRef, uri: &str, name: &str, body: &str, ) -> String { let server = server.as_ref(); let metadata = draft_metadata(uri, name, "text", "text/plain", "internal"); let created = create_draft( client, server, &metadata, body.as_bytes(), "story38-revocation.txt", "text/plain", ) .await; let resource_id = created_resource_id(&created); let card = get_card(client, server, &resource_id).await; let updated_at = draft_updated_at(&card); let (status, text, published) = read_response( client .post(format!("{server}/resources/{resource_id}/publish")) .json(&json!({ "expected_updated_at": updated_at })) .send() .await .expect("publish request must complete"), ) .await; assert_eq!( status, StatusCode::OK, "positive control: the published Resource {uri} must be created through the real Admin API; \ observed {status} body={text}" ); assert_eq!( published["published_version"]["version"], json!(1), "positive control: the first publication must be exact version 1: {published}" ); resource_id } /// Публикует следующую версию существующего Resource из нового содержимого. pub(super) async fn publish_resource_version( client: &reqwest::Client, server: impl AsRef, resource_id: &str, uri: &str, name: &str, body: &str, ) { let server = server.as_ref(); let card = get_card(client, server, resource_id).await; let updated_at = draft_updated_at(&card); let metadata = super::update_metadata("", "text/plain", "internal", &updated_at); let (status, text, _) = super::put_draft_raw( client, server, resource_id, &metadata, body.as_bytes(), "text/plain", ) .await; assert_eq!( status, StatusCode::OK, "fixture: draft update of {uri}/{name} must succeed; observed {status} body={text}" ); let card = get_card(client, server, resource_id).await; let updated_at = draft_updated_at(&card); let (status, text, _) = read_response( client .post(format!("{server}/resources/{resource_id}/publish")) .json(&json!({ "expected_updated_at": updated_at })) .send() .await .expect("publish request must complete"), ) .await; assert_eq!( status, StatusCode::OK, "fixture: the next version of {uri} must publish; observed {status} body={text}" ); } /// A published Agent whose only catalog is exact published Resource Versions (valid for a /// Resource-only Agent, see `AdminService::publish_agent`). pub(super) async fn create_published_resource_only_agent( client: &reqwest::Client, server: impl AsRef, slug: &str, bindings: &[(&str, u32)], ) -> String { let server = server.as_ref(); let agent = assert_success_json( client .post(format!("{server}/agents")) .json(&json!({ "slug": slug, "display_name": slug, "description": "Story 3.8 Resource revocation fixture", "instructions": {}, "tool_selection_policy": {} })) .send() .await .expect("Agent creation request must complete"), ) .await; let agent_id = agent["agent_id"] .as_str() .expect("Agent creation must return the Agent identifier") .to_owned(); let resource_bindings: Vec = bindings .iter() .map(|(resource_id, version)| { json!({ "resource_id": resource_id, "resource_version": version }) }) .collect(); let etag = agent_etag(client, server, &agent_id).await; let (status, text, _) = read_response( client .post(format!("{server}/agents/{agent_id}/bindings")) .header(reqwest::header::IF_MATCH, etag) .json(&json!({ "bindings": [], "tool_selection_policy": {}, "resource_bindings": resource_bindings, })) .send() .await .expect("Agent bindings request must complete"), ) .await; assert_eq!( status, StatusCode::OK, "positive control: exact Resource bindings must save on the draft Agent; observed {status} body={text}" ); let etag = agent_etag(client, server, &agent_id).await; let (status, text, _) = read_response( client .post(format!("{server}/agents/{agent_id}/publish")) .header(reqwest::header::IF_MATCH, etag) .json(&json!({ "version": 1 })) .send() .await .expect("Agent publish request must complete"), ) .await; assert_eq!( status, StatusCode::OK, "positive control: a Resource-only Agent must publish; observed {status} body={text}" ); agent_id } pub(super) async fn create_mcp_key( client: &reqwest::Client, server: impl AsRef, agent_id: &str, ) -> String { let server = server.as_ref(); let created = assert_success_json( client .post(format!("{server}/agents/{agent_id}/platform-api-keys")) .json(&json!({ "name": format!("story38-revocation-mcp-{agent_id}"), "key_kind": PlatformApiKeyKind::McpClient, "scopes": ["read"] })) .send() .await .expect("platform API key request must complete"), ) .await; created["secret"] .as_str() .expect("the created MCP key must disclose its raw value once") .to_owned() } pub(super) fn build_mcp_app( registry: PostgresRegistry, storage_root: &Path, refresh_interval: Duration, ) -> axum::Router { build_app_with_artifacts( registry, refresh_interval, None, test_secret_crypto(), crank_runtime::community_with_outbound_policy( crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]), ) .build(), RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()), std::sync::Arc::new(InMemoryCoordinationStateStore::default()), std::sync::Arc::new(InMemorySessionStore::default()), std::sync::Arc::new(CommunityMachineCredentialVerifier), 16, ArtifactStore::open(storage_root) .expect("the MCP app must open the artifact root the Admin API publishes into"), ) } pub(super) async fn spawn_mcp_server(app: axum::Router) -> String { let listener = TcpListener::bind("127.0.0.1:0") .await .expect("MCP test listener must bind"); let address = listener.local_addr().expect("MCP test listener address"); tokio::spawn(async move { axum::serve(listener, app) .await .expect("MCP test server must serve"); }); format!("http://{address}") } // --------------------------------------------------------------------------- // MCP transport helpers (same wire contract the accepted suites use) // --------------------------------------------------------------------------- /// Revisions come from the checked-in oracle, never from memory. pub(super) fn supported_revisions() -> Vec { let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("../../tests/fixtures/mcp-revisions/supported-revisions.json"); let raw = fs::read_to_string(&path).unwrap_or_else(|error| { panic!( "revision oracle must be readable at {}: {error}", path.display() ) }); serde_json::from_str::(&raw).expect("revision oracle must be JSON")["revisions"] .as_array() .expect("revision oracle must list revisions") .iter() .map(|entry| { entry["revision"] .as_str() .expect("revision string") .to_owned() }) .collect() } fn modern_meta(revision: &str) -> Value { json!({ "io.modelcontextprotocol/protocolVersion": revision, "io.modelcontextprotocol/clientCapabilities": {}, "io.modelcontextprotocol/clientInfo": { "name": "crank-story38-revocation", "version": "0.1.0" } }) } pub(super) async fn legacy_session( client: &reqwest::Client, mcp_url: &str, api_key: &str, ) -> String { let initialize = client .post(mcp_url) .header( reqwest::header::ACCEPT, "application/json, text/event-stream", ) .header(reqwest::header::AUTHORIZATION, format!("Bearer {api_key}")) .json(&json!({ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": LEGACY_REVISION, "capabilities": {} } })) .send() .await .expect("legacy initialize must reach the MCP server"); assert_eq!( initialize.status(), StatusCode::OK, "legacy initialize must succeed on the real MCP dispatch" ); let session_id = initialize .headers() .get("MCP-Session-Id") .expect("legacy initialize must return a session") .to_str() .expect("session id must be a header string") .to_owned(); let initialized = client .post(mcp_url) .header( reqwest::header::ACCEPT, "application/json, text/event-stream", ) .header(reqwest::header::AUTHORIZATION, format!("Bearer {api_key}")) .header("MCP-Session-Id", &session_id) .header("MCP-Protocol-Version", LEGACY_REVISION) .json(&json!({ "jsonrpc": "2.0", "method": "notifications/initialized", "params": {} })) .send() .await .expect("legacy initialized notification must reach the MCP server"); assert_eq!( initialized.status(), StatusCode::ACCEPTED, "legacy initialized notification must be accepted" ); session_id } pub(super) async fn mcp_list( client: &reqwest::Client, mcp_url: &str, api_key: &str, revision: &str, ) -> Value { if revision == LEGACY_REVISION { let session = legacy_session(client, mcp_url, api_key).await; let response = client .post(mcp_url) .header( reqwest::header::ACCEPT, "application/json, text/event-stream", ) .header(reqwest::header::AUTHORIZATION, format!("Bearer {api_key}")) .header("MCP-Protocol-Version", LEGACY_REVISION) .header("MCP-Session-Id", session) .json(&json!({ "jsonrpc": "2.0", "id": 11, "method": "resources/list", "params": {} })) .send() .await .expect("legacy resources/list must reach the MCP server"); return json_body(response).await; } let response = client .post(mcp_url) .header( reqwest::header::ACCEPT, "application/json, text/event-stream", ) .header(reqwest::header::AUTHORIZATION, format!("Bearer {api_key}")) .header("MCP-Protocol-Version", revision) .header("Mcp-Method", "resources/list") .json(&json!({ "jsonrpc": "2.0", "id": 11, "method": "resources/list", "params": { "_meta": modern_meta(revision) } })) .send() .await .expect("modern resources/list must reach the MCP server"); json_body(response).await } pub(super) async fn mcp_read( client: &reqwest::Client, mcp_url: &str, api_key: &str, revision: &str, uri: &str, ) -> Value { if revision == LEGACY_REVISION { let session = legacy_session(client, mcp_url, api_key).await; let response = client .post(mcp_url) .header( reqwest::header::ACCEPT, "application/json, text/event-stream", ) .header(reqwest::header::AUTHORIZATION, format!("Bearer {api_key}")) .header("MCP-Protocol-Version", LEGACY_REVISION) .header("MCP-Session-Id", session) .json(&json!({ "jsonrpc": "2.0", "id": 21, "method": "resources/read", "params": { "uri": uri } })) .send() .await .expect("legacy resources/read must reach the MCP server"); return json_body(response).await; } let response = client .post(mcp_url) .header( reqwest::header::ACCEPT, "application/json, text/event-stream", ) .header(reqwest::header::AUTHORIZATION, format!("Bearer {api_key}")) .header("MCP-Protocol-Version", revision) .header("Mcp-Method", "resources/read") .header("Mcp-Name", uri) .json(&json!({ "jsonrpc": "2.0", "id": 21, "method": "resources/read", "params": { "uri": uri, "_meta": modern_meta(revision) } })) .send() .await .expect("modern resources/read must reach the MCP server"); json_body(response).await } async fn json_body(response: reqwest::Response) -> Value { let status = response.status(); let body = response.text().await.unwrap_or_default(); serde_json::from_str(&body).unwrap_or_else(|error| { panic!("expected a JSON-RPC body, got status {status} body {body:?}: {error}") }) } pub(super) fn listed_uris(body: &Value) -> Vec { body["result"]["resources"] .as_array() .unwrap_or_else(|| panic!("resources/list must return a resources array: {body}")) .iter() .map(|resource| { resource["uri"] .as_str() .unwrap_or_else(|| panic!("listed Resource must carry a uri: {resource}")) .to_owned() }) .collect() } pub(super) fn read_text(body: &Value) -> Option { body["result"]["contents"] .as_array() .and_then(|contents| contents.first()) .and_then(|content| content["text"].as_str()) .map(str::to_owned) } // --------------------------------------------------------------------------- // GREEN control: the stand itself lists and reads the published Resource // --------------------------------------------------------------------------- #[tokio::test] async fn story38_revoke_control_published_resources_are_listed_and_readable_on_both_revisions() { let stand = spawn_revocation_stand("control").await; let revisions = supported_revisions(); assert!( revisions.iter().any(|revision| revision == MODERN_REVISION) && revisions.iter().any(|revision| revision == LEGACY_REVISION), "the revision oracle must still cover both supported eras: {revisions:?}" ); for revision in &revisions { let listed = listed_uris(&mcp_list(&stand.mcp, &stand.mcp_url, &stand.mcp_key, revision).await); for uri in [REVOKED_URI, KEPT_URI] { assert!( listed.iter().any(|listed| listed == uri), "positive control: {uri} must be discoverable through the real MCP dispatch on {revision}: {listed:?}" ); } let revoked = mcp_read( &stand.mcp, &stand.mcp_url, &stand.mcp_key, revision, REVOKED_URI, ) .await; assert_eq!( read_text(&revoked).as_deref(), Some(REVOKED_CANARY), "positive control: the published bytes must be readable before any revoke on {revision}: {revoked}" ); let kept = mcp_read( &stand.mcp, &stand.mcp_url, &stand.mcp_key, revision, KEPT_URI, ) .await; assert_eq!( read_text(&kept).as_deref(), Some(KEPT_CANARY), "positive control: the control Resource must be readable before any revoke on {revision}: {kept}" ); } // The administrative read of the exact published version stays available (owner decision A). let (status, text, _) = read_response( stand .admin .get(format!( "{}/resources/{}/versions/1", stand.server, stand.revoked_id )) .send() .await .expect("administrative version read must complete"), ) .await; assert_eq!( status, StatusCode::OK, "positive control: the protected administrative read must work before any revoke: {text}" ); } // --------------------------------------------------------------------------- // RED: POST .../resources/{resource_id}/revoke does not exist yet // --------------------------------------------------------------------------- #[tokio::test] async fn story38_revoke_denies_mcp_discovery_and_read_of_the_whole_resource() { let stand = spawn_revocation_stand("revoke").await; let revisions = supported_revisions(); // Hard positive controls first: if these fail the stand is broken, not the product. for revision in &revisions { let body = mcp_read( &stand.mcp, &stand.mcp_url, &stand.mcp_key, revision, REVOKED_URI, ) .await; assert_eq!( read_text(&body).as_deref(), Some(REVOKED_CANARY), "fixture must start with the target Resource readable on {revision}: {body}" ); } // Everything below is collected so one RED run reports the whole missing capability instead of // stopping before the post-attempt read is actually observed. let mut failures: Vec = Vec::new(); let response = stand .admin .post(format!( "{}/resources/{}/revoke", stand.server, stand.revoked_id )) .send() .await .expect("resource revoke request must reach the real Admin router"); let revoke_status = response.status(); let revoke_body = response.text().await.unwrap_or_default(); if revoke_status != StatusCode::NO_CONTENT { failures.push(format!( "POST /resources/{{resource_id}}/revoke must perform the audited Resource-wide revoke and \ answer 204; observed {revoke_status} body={revoke_body}" )); } for revision in &revisions { let listed = mcp_list(&stand.mcp, &stand.mcp_url, &stand.mcp_key, revision).await; if listed.get("result").is_none() { failures.push(format!( "{revision}: resources/list must still serve the page of unrevoked Resources, got {listed}" )); } else { let uris = listed_uris(&listed); if uris.iter().any(|uri| uri == REVOKED_URI) { failures.push(format!( "{revision}: resources/list still advertises the revoked Resource {REVOKED_URI}: {uris:?}" )); } if !uris.iter().any(|uri| uri == KEPT_URI) { failures.push(format!( "{revision}: resources/list must keep the unrevoked Resource {KEPT_URI}: {uris:?}" )); } let listed_text = listed.to_string(); for leak in [REVOKED_NAME, REVOKED_CANARY.trim()] { if listed_text.contains(leak) { failures.push(format!( "{revision}: resources/list must not expose revoked metadata or bytes ({leak}): {listed}" )); } } } let read = mcp_read( &stand.mcp, &stand.mcp_url, &stand.mcp_key, revision, REVOKED_URI, ) .await; if read.get("result").is_some() { failures.push(format!( "{revision}: after the revoke attempt resources/read still returned the revoked Resource \ (observed text {:?}): {read}", read_text(&read) )); } else { let code = read["error"]["code"].as_i64().unwrap_or_default(); let message = read["error"]["message"].as_str().unwrap_or_default(); if code != NOT_AVAILABLE_CODE || message != NOT_AVAILABLE_MESSAGE { failures.push(format!( "{revision}: a revoked Resource read must reuse the existing safe NotAvailable \ ({NOT_AVAILABLE_CODE} {NOT_AVAILABLE_MESSAGE:?}), got {read}" )); } let read_text = read.to_string(); for leak in [ REVOKED_CANARY.trim(), REVOKED_NAME, REVOKED_URI, "text/plain", sha256_hex(REVOKED_CANARY.as_bytes()).as_str(), ] { if read_text.contains(leak) { failures.push(format!( "{revision}: the revoked read failure must not disclose Resource data ({leak}): {read}" )); } } } let kept = mcp_read( &stand.mcp, &stand.mcp_url, &stand.mcp_key, revision, KEPT_URI, ) .await; if read_text(&kept).as_deref() != Some(KEPT_CANARY) { failures.push(format!( "{revision}: revoking one Resource must not affect another bound Resource {KEPT_URI}: {kept}" )); } } assert!( failures.is_empty(), "Story 3.8 AT-3.8-04/05 Resource revoke is not implemented yet:\n---\n{}", failures.join("\n---\n") ); }