//! Story 3.8 / AT-3.8-04/05: the deny is PostgreSQL state, not process memory, and pagination //! keeps addressing the original immutable bindings array on both supported revisions. //! //! - a brand-new MCP service instance (new registry pool and new catalog cache) over the same //! PostgreSQL schema still denies, and a repeated revoke stays 204 with the first audit event; //! - a cursor issued before the revoke never bypasses it, revoked entries before and inside the //! range are skipped without duplicates or offset shift, an empty page still carries a //! continuation, and the era-specific list envelope is preserved. use std::time::Duration; use crank_registry::PostgresRegistry; use reqwest::StatusCode; use serde_json::{Value, json}; use super::revocation::{ KEPT_URI, LEGACY_REVISION, MODERN_REVISION, NOT_AVAILABLE_CODE, NOT_AVAILABLE_MESSAGE, REVOKED_URI, WORKSPACE_SLUG, build_mcp_app, create_mcp_key, create_published_resource, create_published_resource_only_agent, legacy_session, listed_uris, mcp_list, mcp_read, spawn_mcp_server, spawn_revocation_stand, supported_revisions, }; use super::revocation_security::revoke; /// A fresh registry pool over the same PostgreSQL schema (new cache, same durable state). async fn fresh_registry(stand: &super::revocation::RevocationStand) -> PostgresRegistry { let schema: String = sqlx::query_scalar("select current_schema()") .fetch_one(stand.registry.pool()) .await .expect("the test schema must be resolvable"); let base_url = crank_test_support::postgres_database_url().await; let url = format!("{base_url}?options=-csearch_path%3D{schema}"); PostgresRegistry::connect(&url) .await .expect("a fresh registry must connect to the same test schema") } /// A new MCP service instance over the same schema and artifact root: its URLs differ only in the /// listener, so the request path (workspace/Agent) is identical. async fn spawn_fresh_mcp_instance(stand: &super::revocation::RevocationStand) -> (String, String) { let registry = fresh_registry(stand).await; let app = build_mcp_app(registry, &stand.storage_root, Duration::from_secs(0)); let base = spawn_mcp_server(app).await; ( stand.mcp_url.replace(&stand.mcp_base, &base), stand.mcp_url_second.replace(&stand.mcp_base, &base), ) } #[tokio::test] async fn story38_a_new_service_instance_keeps_the_deny_and_the_first_audit_event() { let stand = spawn_revocation_stand("new_instance").await; let pool = stand.registry.pool(); assert_eq!( revoke(&stand.admin, &stand.server, &stand.revoked_id) .await .status(), StatusCode::NO_CONTENT ); let (revoked_at, actor, request_id): (time::OffsetDateTime, String, String) = sqlx::query_as( "select revoked_at, actor_user_id, request_id from resource_security_revocations", ) .fetch_one(pool) .await .expect("the audit event must be readable"); let (fresh_url, fresh_url_second) = spawn_fresh_mcp_instance(&stand).await; for revision in supported_revisions() { for (agent, url, key) in [ ("first", &fresh_url, &stand.mcp_key), ("second", &fresh_url_second, &stand.mcp_key_second), ] { let denied = mcp_read(&stand.mcp, url, key, &revision, REVOKED_URI).await; assert!( denied.get("result").is_none(), "{agent}/{revision}: a new instance must not serve the revoked Resource: {denied}" ); assert_eq!( denied["error"]["code"].as_i64(), Some(NOT_AVAILABLE_CODE), "{agent}/{revision}: {denied}" ); assert_eq!( denied["error"]["message"].as_str(), Some(NOT_AVAILABLE_MESSAGE) ); let uris = listed_uris(&mcp_list(&stand.mcp, url, key, &revision).await); assert!( !uris.contains(&REVOKED_URI.to_owned()) && uris.contains(&KEPT_URI.to_owned()), "{agent}/{revision}: a new instance must keep the same page: {uris:?}" ); } } // The original instance still denies too, and the repeat is idempotent. let original = mcp_read( &stand.mcp, &stand.mcp_url, &stand.mcp_key, LEGACY_REVISION, REVOKED_URI, ) .await; assert!(original.get("result").is_none()); assert_eq!( revoke(&stand.admin, &stand.server, &stand.revoked_id) .await .status(), StatusCode::NO_CONTENT ); let (after_at, after_actor, after_request, rows): (time::OffsetDateTime, String, String, i64) = sqlx::query_as( "select revoked_at, actor_user_id, request_id, (select count(*) from resource_security_revocations) from resource_security_revocations", ) .fetch_one(pool) .await .expect("the audit event must stay readable"); assert_eq!(rows, 1, "a repeat must not create a second event"); assert_eq!( (after_at, after_actor, after_request), (revoked_at, actor, request_id), "the first actor/time/correlation must be preserved" ); } /// A page request over both revisions: legacy is session-based, modern carries `_meta`. async fn list_page( client: &reqwest::Client, mcp_url: &str, api_key: &str, revision: &str, cursor: Option<&str>, limit: usize, ) -> Value { let params = match cursor { Some(cursor) => json!({ "cursor": cursor, "limit": limit }), None => json!({ "limit": limit }), }; let response = if revision == LEGACY_REVISION { let session = legacy_session(client, mcp_url, api_key).await; let mut params = params; params .as_object_mut() .expect("list params are an object") .remove("_meta"); 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": 41, "method": "resources/list", "params": params })) .send() .await .expect("the legacy page request must reach the MCP server") } else { let mut params = params; params["_meta"] = json!({ "io.modelcontextprotocol/protocolVersion": revision, "io.modelcontextprotocol/clientCapabilities": {}, "io.modelcontextprotocol/clientInfo": { "name": "crank-story38-pages", "version": "0.1.0" } }); 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": 41, "method": "resources/list", "params": params })) .send() .await .expect("the modern page request must reach the MCP server") }; let status = response.status(); let body = response.text().await.unwrap_or_default(); serde_json::from_str(&body) .unwrap_or_else(|error| panic!("expected JSON-RPC, got {status} {body:?}: {error}")) } #[tokio::test] async fn story38_pagination_continuation_stays_era_correct_on_both_revisions() { let stand = spawn_revocation_stand("pagination_eras").await; // A revoke is permanent, so each revision gets its own four freshly published Resources and // its own Agent: the second era must observe the same behaviour from a clean catalog. for revision in supported_revisions() { let tag = revision.replace(['.', '-'], "_"); let mut created: Vec<(String, String)> = Vec::new(); for index in 1..=4 { let uri = format!("crank://resources/story38-page-{tag}-{index}"); let name = format!("story38_page_{tag}_{index}"); let resource_id = create_published_resource( &stand.admin, &stand.server, &uri, &name, &format!("page {index} for {revision}\n"), ) .await; created.push((resource_id, uri)); } let slug = format!("story38-pages-{tag}"); let bindings: Vec<(&str, u32)> = created .iter() .map(|(resource_id, _)| (resource_id.as_str(), 1)) .collect(); let agent_id = create_published_resource_only_agent(&stand.admin, &stand.server, &slug, &bindings) .await; let key = create_mcp_key(&stand.admin, &stand.server, &agent_id).await; let url = format!("{}/v1/{WORKSPACE_SLUG}/{slug}", stand.mcp_base); let full = listed_uris(&list_page(&stand.mcp, &url, &key, &revision, None, 100).await); assert_eq!(full.len(), 4, "{revision}: four bound Resources: {full:?}"); // The first page is issued before any revoke; its cursor must keep its meaning. let first_page = list_page(&stand.mcp, &url, &key, &revision, None, 1).await; if revision == MODERN_REVISION { assert!( first_page["result"]["ttlMs"].is_number() && first_page["result"]["cacheScope"].is_string(), "the modern list envelope must stay era-correct: {first_page}" ); } else { assert!( first_page["result"].get("ttlMs").is_none(), "the legacy list envelope must not carry modern cache fields: {first_page}" ); } let first = listed_uris(&first_page); assert_eq!(first.len(), 1, "{revision}: a short page: {first_page}"); let cursor = first_page["result"]["nextCursor"] .as_str() .unwrap_or_else(|| panic!("{revision}: a non-final page must carry nextCursor")) .to_owned(); let behind = full[0].clone(); let inside = full[2].clone(); assert_eq!( first[0], behind, "{revision}: the first page is the first element" ); for uri in [&behind, &inside] { let resource_id = created .iter() .find(|(_, created_uri)| created_uri == uri) .map(|(resource_id, _)| resource_id.clone()) .unwrap_or_else(|| panic!("{revision}: {uri} must belong to this fixture")); assert_eq!( revoke(&stand.admin, &stand.server, &resource_id) .await .status(), StatusCode::NO_CONTENT, "{revision}: revoking {uri} must succeed" ); } let mut page = list_page(&stand.mcp, &url, &key, &revision, Some(&cursor), 1).await; let mut seen: Vec = Vec::new(); let mut empty_pages_with_continuation = 0; let mut guard = 0; loop { guard += 1; assert!(guard < 10, "{revision}: pagination must terminate: {page}"); let uris = listed_uris(&page); if uris.is_empty() && page["result"]["nextCursor"].is_string() { empty_pages_with_continuation += 1; } for uri in &uris { assert!( !seen.contains(uri), "{revision}: a continuation must not repeat {uri}: {seen:?}" ); assert_ne!( uri, &behind, "{revision}: an element revoked behind the cursor must never reappear" ); assert_ne!( uri, &inside, "{revision}: an element revoked inside the range must be skipped" ); seen.push(uri.clone()); } match page["result"]["nextCursor"].as_str() { Some(next) => { let next = next.to_owned(); page = list_page(&stand.mcp, &url, &key, &revision, Some(&next), 1).await; } None => break, } } let mut expected: Vec = full .iter() .filter(|uri| **uri != behind && **uri != inside) .cloned() .collect(); expected.sort(); let mut observed = seen.clone(); observed.sort(); assert_eq!( observed, expected, "{revision}: the continuation must yield exactly the unrevoked elements once" ); assert!( empty_pages_with_continuation >= 1, "{revision}: the revoked element inside the range must produce an empty page with a continuation, seen {seen:?}" ); assert!( seen.len() < full.len(), "{revision}: the revoked elements must be gone from the continuation" ); } }