//! Story 3.8 AC01 / AT-3.8-01: authorized discovery returns only the Published Resources bound to the //! exact published Agent snapshot, with an opaque continuation. Draft, foreign and unbound Resources //! never appear. use std::{ collections::BTreeSet, sync::atomic::{AtomicUsize, Ordering}, }; use axum::{ Json as AxumJson, body::Body, extract::{Path, State}, response::Response, routing::{get, head}, }; use crank_core::resource::template::TemplateSource; use crank_core::{ AgentStatus, HttpMethod, OperationId, OperationSafetyClass, OperationSafetyPolicy, RestResponseDescriptor, RestTarget, Target, ids::ResourceId, }; use crank_mapping::{MappingRule, MappingSet}; use crank_registry::model::CreateAgentDraftVersionRequest; use crank_registry::model::resource::{ CreateResourceTemplateDraftRequest, PublishResourceTemplateVersionRequest, }; use crank_registry::{ AgentResourceBinding, PostgresRegistry, PublishAgentRequest, PublishRequest, SaveAgentCatalogConfigRequest, }; use crank_schema::SchemaKind; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; use time::OffsetDateTime; use super::super::common::{ object_schema, post_jsonrpc_response, post_jsonrpc_with_headers, test_operation, test_workspace_id, }; use super::fixtures::*; #[path = "list/template_discovery.rs"] mod template_discovery; #[tokio::test] async fn list_serves_every_supported_revision_with_only_bound_published_resources() { let endpoint = standard_endpoint("list_matrix").await; let expected: BTreeSet = endpoint.bound_uris().into_iter().collect(); let revisions = supported_revisions(); assert!( revisions.contains(&MODERN_REVISION.to_owned()) && revisions.contains(&LEGACY_REVISION.to_owned()), "the protocol matrix must be driven by the checked-in revision oracle: {revisions:?}" ); let mut checks = RevisionChecks::default(); for revision in revisions { let body = json_body(list_resources(&endpoint, &revision, json!({})).await).await; let Some(result) = checks.result(&body, &revision, "resources/list") else { continue; }; if revision != LEGACY_REVISION { checks.require(result["resultType"].as_str() == Some("complete"), || { format!( "a modern resources/list result must carry Result.resultType=\"complete\" on {revision}: {body}" ) }); } let Some(listed_array) = result["resources"].as_array() else { checks.require(false, || { format!("resources/list must carry a resources array on {revision}: {body}") }); continue; }; let listed: BTreeSet = listed_array .iter() .filter_map(|resource| resource["uri"].as_str().map(str::to_owned)) .collect(); checks.require(listed == expected, || { format!( "revision {revision} must list exactly the bound Published Resources, got {body}" ) }); for excluded in [ &endpoint.draft_uri, &endpoint.unbound_uri, &endpoint.foreign_uri, ] { checks.require(!listed.contains(excluded), || { format!( "a Draft, foreign or unbound Resource ({excluded}) must not be discoverable on {revision}: {body}" ) }); } for resource in listed_array { let uri = resource["uri"].as_str().unwrap_or_default(); match [&endpoint.text, &endpoint.json, &endpoint.binary] .into_iter() .find(|bound| bound.uri == uri) { None => checks.require(false, || { format!("unexpected listed Resource {uri} on {revision}: {body}") }), Some(bound) => { checks.require( resource["name"].as_str() == Some(bound.name.as_str()), || { format!( "the listed Resource must expose the published name for {uri} on {revision}: {resource}" ) }, ); checks.require(resource["mimeType"].as_str().is_some(), || { format!( "the listed Resource must expose the published MIME type for {uri} on {revision}: {resource}" ) }); } } } } checks.finish(); } /// The pinned 2026-07-28 `ListResourcesResult extends PaginatedResult, CacheableResult`: every modern /// list result — an empty page, a populated page and a continued page — must carry `resultType`, /// `ttlMs` and `cacheScope`. The legacy revision keeps its earlier shape without those members. #[tokio::test] async fn list_modern_results_carry_the_required_cacheable_result_fields() { let populated = standard_endpoint("list_cacheable_populated").await; let empty = empty_resource_endpoint("list_cacheable_empty").await; let bound = populated.bound_uris().len(); assert!( bound > 1, "the fixture must paginate more than one Resource" ); let mut checks = RevisionChecks::default(); for revision in supported_revisions() { let first = json_body(list_resources(&populated, &revision, json!({ "limit": 1 })).await).await; let cursor = result_of(&first, "bounded resources/list")["nextCursor"] .as_str() .unwrap_or_else(|| { panic!("a bounded page must advertise a cursor on {revision}: {first}") }) .to_owned(); let second = json_body( list_resources( &populated, &revision, json!({ "limit": 1, "cursor": cursor }), ) .await, ) .await; let empty_page = json_body( list_resources_at( &empty.client, &empty.mcp_url, &empty.api_key, &revision, json!({}), ) .await, ) .await; for (what, body, expected) in [ ("populated resources/list", &first, 1usize), ("continued resources/list", &second, 1usize), ("empty resources/list", &empty_page, 0usize), ] { require_list_result_shape(&mut checks, body, &revision, what); let Some(result) = body.get("result") else { continue; }; let listed = listed_uris(result); checks.require(listed.len() == expected, || { format!("{what} must carry {expected} Resource(s) on {revision}: {body}") }); } } checks.finish(); } /// Story 3.8 correction (Cherry Studio 2.1.7): the client requests `resources/templates/list` /// together with `resources/list` and drops the whole resource browser when that call fails, even /// though the second call succeeds. This server has no dynamic Resource template, so both supported /// revisions must answer the authenticated request with an empty `resourceTemplates` array in their /// own result envelope instead of an era-correct "method not found". #[tokio::test] async fn list_resource_templates_answers_an_empty_page_on_every_revision() { let endpoint = standard_endpoint("list_templates").await; let mut checks = RevisionChecks::default(); for revision in supported_revisions() { let response = list_resource_templates(&endpoint, &revision).await; let status = response.status(); let body = json_body(response).await; checks.require(status == reqwest::StatusCode::OK, || { format!( "resources/templates/list must be served on {revision}, got HTTP {status}: {body}" ) }); let Some(result) = checks.result(&body, &revision, "resources/templates/list") else { continue; }; checks.require(body["id"].as_i64() == Some(31), || { format!("resources/templates/list must preserve the request id on {revision}: {body}") }); checks.require( result .get("resourceTemplates") .and_then(Value::as_array) .is_some_and(Vec::is_empty), || { format!( "resources/templates/list must answer exactly an empty resourceTemplates array on {revision}: {body}" ) }, ); checks.require(result.get("nextCursor").is_none(), || { format!("an empty template page must not advertise nextCursor on {revision}: {body}") }); if revision == LEGACY_REVISION { for field in ["resultType", "ttlMs", "cacheScope"] { checks.require(result.get(field).is_none(), || { format!( "the legacy resources/templates/list must keep its earlier shape without {field} on {revision}: {body}" ) }); } continue; } checks.require(result["resultType"].as_str() == Some("complete"), || { format!( "a modern resources/templates/list must carry Result.resultType=\"complete\" on {revision}: {body}" ) }); checks.require( result.get("ttlMs").and_then(Value::as_u64).is_some(), || { format!( "a modern resources/templates/list must carry CacheableResult.ttlMs on {revision}: {body}" ) }, ); checks.require( matches!( result.get("cacheScope").and_then(Value::as_str), Some("public" | "private") ), || { format!( "a modern resources/templates/list must carry CacheableResult.cacheScope on {revision}: {body}" ) }, ); } checks.finish(); } /// The new method is not an escape hatch: the shared modern header rule, the transport /// authorization and the legacy initialized-session guard still decide before its handler runs. #[tokio::test] async fn list_resource_templates_keeps_the_existing_guards() { let endpoint = standard_endpoint("list_templates_guards").await; let payload = json!({ "jsonrpc": "2.0", "id": 41, "method": "resources/templates/list", "params": { "_meta": modern_meta(MODERN_REVISION) } }); for headers in [ vec![("MCP-Protocol-Version", MODERN_REVISION)], vec![ ("MCP-Protocol-Version", MODERN_REVISION), ("Mcp-Method", "resources/list"), ], ] { let body = json_body( post_jsonrpc_with_headers( &endpoint.client, &endpoint.mcp_url, &endpoint.api_key, &headers, payload.clone(), ) .await, ) .await; assert!( body.get("result").is_none(), "a modern resources/templates/list without its own Mcp-Method must not reach the handler ({headers:?}): {body}" ); assert_eq!( error_code(&body), -32020, "a missing or mismatched Mcp-Method stays a header mismatch ({headers:?}): {body}" ); } // No credential: the transport authorization still answers first. let unauthenticated = endpoint .client .post(&endpoint.mcp_url) .header( reqwest::header::ACCEPT, "application/json, text/event-stream", ) .header("MCP-Protocol-Version", MODERN_REVISION) .header("Mcp-Method", "resources/templates/list") .json(&payload) .send() .await .expect("unauthenticated request must reach the server"); assert_eq!( unauthenticated.status().as_u16(), 401, "an unauthenticated resources/templates/list must be rejected before dispatch" ); // A legacy session that never completed `notifications/initialized` is still refused. let initialized = endpoint .client .post(&endpoint.mcp_url) .header( reqwest::header::ACCEPT, "application/json, text/event-stream", ) .header("Authorization", format!("Bearer {}", endpoint.api_key)) .json(&json!({ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": LEGACY_REVISION, "capabilities": {} } })) .send() .await .expect("the legacy initialize must reach the server"); let session_id = initialized .headers() .get("MCP-Session-Id") .expect("initialize must mint a session") .to_str() .expect("session id is ASCII") .to_owned(); let body = json_body( post_jsonrpc_response( &endpoint.client, &endpoint.mcp_url, &endpoint.api_key, Some(&session_id), None, json!({ "jsonrpc": "2.0", "id": 42, "method": "resources/templates/list", "params": {} }), ) .await, ) .await; assert!( body.get("result").is_none(), "a legacy resources/templates/list on an uninitialized session must not be served: {body}" ); assert_eq!( error_code(&body), -32002, "the legacy initialized-session guard keeps its answer: {body}" ); } fn require_list_result_shape( checks: &mut RevisionChecks, body: &Value, revision: &str, what: &str, ) { let Some(result) = checks.result(body, revision, what) else { return; }; if revision == LEGACY_REVISION { for field in ["resultType", "ttlMs", "cacheScope"] { checks.require(result.get(field).is_none(), || { format!( "the legacy {what} must keep its earlier shape without {field} on {revision}: {body}" ) }); } return; } checks.require(result["resultType"].as_str() == Some("complete"), || { format!("a modern {what} must carry Result.resultType=\"complete\" on {revision}: {body}") }); checks.require( result.get("ttlMs").and_then(Value::as_u64).is_some(), || format!("a modern {what} must carry CacheableResult.ttlMs on {revision}: {body}"), ); checks.require( matches!( result.get("cacheScope").and_then(Value::as_str), Some("public" | "private") ), || format!("a modern {what} must carry CacheableResult.cacheScope on {revision}: {body}"), ); } /// Opacity is not enough: a continuation is bound to this workspace+Agent+catalog revision+MCP /// revision, so a malformed, cross-revision or cross-agent cursor is a safe invalid-params answer and /// never mixes two pages. #[tokio::test] async fn list_rejects_malformed_cross_revision_and_cross_agent_cursors() { let endpoint = standard_endpoint("list_cursor_scope").await; let other = standard_endpoint("list_cursor_other_agent").await; for revision in supported_revisions() { let first = json_body(list_resources(&endpoint, &revision, json!({ "limit": 1 })).await).await; let cursor = result_of(&first, "bounded resources/list")["nextCursor"] .as_str() .unwrap_or_else(|| panic!("a bounded page must advertise a cursor: {first}")) .to_owned(); let rejected = [ ("malformed", "not-a-cursor".to_owned(), &revision), ("not base64", "%%%".to_owned(), &revision), ( "forged scope", forge_cursor_for_other_scope(&endpoint, &revision), &revision, ), ]; for (what, cursor_value, requested_revision) in rejected { let body = json_body( list_resources( &endpoint, requested_revision, json!({ "limit": 1, "cursor": cursor_value }), ) .await, ) .await; assert!( body.get("result").is_none(), "a {what} cursor must not be served a page on {revision}: {body}" ); assert_eq!( error_code(&body), -32602, "a {what} cursor must be safe invalid params on {revision}: {body}" ); } // A cursor minted for another MCP revision is a different scope. let cross_revision = if revision == LEGACY_REVISION { MODERN_REVISION } else { LEGACY_REVISION }; let body = json_body( list_resources( &endpoint, cross_revision, json!({ "limit": 1, "cursor": cursor.clone() }), ) .await, ) .await; assert!( body.get("result").is_none(), "a cursor minted for {revision} must not page the {cross_revision} revision: {body}" ); assert_eq!( error_code(&body), -32602, "a cross-revision cursor must be safe invalid params: {body}" ); } // A cursor of another Agent is a different scope as well. let foreign_cursor = { let first = json_body(list_resources(&other, MODERN_REVISION, json!({ "limit": 1 })).await).await; result_of(&first, "other Agent bounded resources/list")["nextCursor"] .as_str() .unwrap_or_else(|| panic!("the other Agent must advertise a cursor: {first}")) .to_owned() }; let body = json_body( list_resources( &endpoint, MODERN_REVISION, json!({ "limit": 1, "cursor": foreign_cursor }), ) .await, ) .await; assert!( body.get("result").is_none(), "a cursor of another Agent must never page this Agent's snapshot: {body}" ); assert_eq!( error_code(&body), -32602, "a cross-agent cursor must be safe invalid params: {body}" ); } /// A cursor whose scope fields are well-formed but name another catalog revision: the minimal opaque /// continuation contract binds the catalog identity, so this is a stale continuation, not a page. fn forge_cursor_for_other_scope(endpoint: &ResourceEndpoint, revision: &str) -> String { use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; let payload = json!({ "v": 1u8, "w": "default", "a": endpoint.agent_id.as_str(), "c": "agent-version-1-catalog-revision-0", "r": revision, "o": 1usize, }); URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).expect("cursor payload is serializable")) } /// Opacity + no duplicates + one catalog revision: the cursor is an opaque continuation, not a /// Resource URI/id, and a bounded page never mixes or repeats entries. #[tokio::test] async fn list_pagination_is_an_opaque_continuation_over_the_same_catalog_revision() { let endpoint = standard_endpoint("list_pagination").await; let expected: BTreeSet = endpoint.bound_uris().into_iter().collect(); for revision in supported_revisions() { let first = json_body(list_resources(&endpoint, &revision, json!({ "limit": 2 })).await).await; let first_result = result_of(&first, &format!("bounded resources/list on {revision}")); let first_uris = listed_uris(first_result); assert_eq!( first_uris.len(), 2, "resources/list limit=2 must bound the page on {revision}, got {first}" ); let cursor = first_result["nextCursor"] .as_str() .unwrap_or_else(|| { panic!("a page with more bounded Resources must advertise nextCursor on {revision}: {first}") }) .to_owned(); for opaque in expected.iter().map(String::as_str).chain([ endpoint.text.id.as_str(), endpoint.json.id.as_str(), endpoint.binary.id.as_str(), ]) { assert!( !cursor.contains(opaque), "the pagination cursor must be opaque, not a Resource URI/id ({opaque}): {cursor}" ); } let second = json_body( list_resources( &endpoint, &revision, json!({ "limit": 2, "cursor": cursor }), ) .await, ) .await; let second_result = result_of(&second, &format!("continued resources/list on {revision}")); let mut all = first_uris; all.extend(listed_uris(second_result)); assert_eq!( all.len(), expected.len(), "the continuation must not repeat or skip Resources on {revision}: {all:?}" ); assert_eq!( all.into_iter().collect::>(), expected, "the union of both pages must be the bound snapshot on {revision}: {second}" ); assert!( second_result.get("nextCursor").is_none(), "the last page must not advertise another cursor on {revision}: {second}" ); } } /// Regression for the defect the Story 3.17 real-client smoke reproduced: with a *valid* published /// Resource template bound to the exact published Agent snapshot, `resources/list` answered /// `-32603`/HTTP 500 for the whole page, so no client could open the template parameter form. /// /// A template is not an artifact-backed concrete Resource — its publication has no blob and its /// concrete URIs are the expanded ones. So the page keeps answering exactly the earlier entries, /// while the template stays discoverable through `resources/templates/list` with its typed /// parameters, and it is never advertised as a downloadable Resource. #[tokio::test] async fn list_stays_available_when_a_published_template_is_bound() { let endpoint = standard_endpoint("list_bound_template").await; let registry = &endpoint.registry; let published = registry .get_agent_version(&test_workspace_id(), &endpoint.agent_id, 1) .await .expect("published Agent snapshot must be readable") .expect("published Agent version 1 must exist"); // A published Resource template (Story 3.10) pointing at the already published test Operation. let template_id = ResourceId::new("res_list_bound_template"); let template_uri = "crank://templates/regions"; let template_source = TemplateSource::parse(&json!({ "operation_id": "op_crm_resources_probe", "operation_version": 1, "uri_template": "crank://regions/{region}", "parameters": [{ "name": "region", "input_path": "input.region", "schema": { "type": "string", "required": true } }], "cache": { "ttl_ms": 60000, "vary": ["region"], "max_bytes": 65536 }, "failure": { "outcome": "error" } })) .expect("template fixture must satisfy the Story 3.10 source contract"); let definition = serde_json::to_string(&template_source).expect("normalized definition must serialize"); let digest = format!("{:x}", Sha256::digest(definition.as_bytes())); let draft = registry .create_resource_template_draft(CreateResourceTemplateDraftRequest { workspace_id: test_workspace_id(), resource_id: template_id.clone(), uri: template_uri.to_owned(), name: "regions".to_owned(), description: "Published regions template".to_owned(), kind: "text".to_owned(), mime_type: "application/json".to_owned(), sensitivity: "internal".to_owned(), definition_json: definition, definition_digest: digest.clone(), created_at: OffsetDateTime::now_utc(), }) .await .expect("template Draft must be created through the registry API"); registry .publish_resource_template_version(PublishResourceTemplateVersionRequest { workspace_id: test_workspace_id(), resource_id: template_id.clone(), expected_updated_at: draft.snapshot.resource.updated_at, expected_version: draft.snapshot.version.version, expected_digest: digest, published_at: OffsetDateTime::now_utc(), }) .await .expect("template exact version must publish"); // Mixed Agent snapshot: the three artifact-backed Resources plus the one template binding. let now = OffsetDateTime::now_utc(); let mut agent_draft = published.snapshot.clone(); agent_draft.version = 2; agent_draft.status = AgentStatus::Draft; agent_draft.created_at = now; registry .create_agent_draft_version(CreateAgentDraftVersionRequest { workspace_id: &test_workspace_id(), agent_id: &endpoint.agent_id, version: &agent_draft, bindings: &published.bindings, updated_at: &now, }) .await .expect("a new Agent Draft must be created for the mixed Resource bindings"); registry .save_agent_catalog_config(SaveAgentCatalogConfigRequest { workspace_id: &test_workspace_id(), agent_id: &endpoint.agent_id, agent_version: 2, bindings: &published.bindings, tool_selection_policy: &published.snapshot.tool_selection_policy, resource_bindings: &[ AgentResourceBinding { resource_id: endpoint.text.id.clone(), resource_version: 1, }, AgentResourceBinding { resource_id: endpoint.json.id.clone(), resource_version: 1, }, AgentResourceBinding { resource_id: endpoint.binary.id.clone(), resource_version: 1, }, AgentResourceBinding { resource_id: template_id.clone(), resource_version: 1, }, ], expected_state: None, }) .await .expect("the template binding must be saved next to the artifact-backed Resources"); registry .publish_agent(PublishAgentRequest { workspace_id: &test_workspace_id(), agent_id: &endpoint.agent_id, version: 2, published_at: &OffsetDateTime::now_utc(), published_by: Some("alice"), expected_state: None, }) .await .expect("the mixed Agent snapshot must publish"); let expected: BTreeSet = endpoint.bound_uris().into_iter().collect(); let mut checks = RevisionChecks::default(); for revision in supported_revisions() { let body = json_body(list_resources(&endpoint, &revision, json!({})).await).await; if let Some(result) = checks.result(&body, &revision, "resources/list") { let listed: BTreeSet = listed_uris(result).into_iter().collect(); checks.require(listed == expected, || { format!( "a bound published template must not break or change resources/list on {revision}: {body}" ) }); checks.require(!listed.contains(template_uri), || { format!( "a template must not be advertised as a concrete Resource on {revision}: {body}" ) }); } let templates = json_body(list_resource_templates(&endpoint, &revision).await).await; if let Some(result) = checks.result(&templates, &revision, "resources/templates/list") { let advertised = result["resourceTemplates"] .as_array() .map(|items| { items .iter() .find(|item| { item["uriTemplate"].as_str() == Some("crank://regions/{region}") }) .cloned() }) .unwrap_or(None); match advertised { Some(template) => checks.require( template["parameters"][0]["name"].as_str() == Some("region") && template["mimeType"].as_str() == Some("application/json"), || { format!( "template discovery must keep its typed parameters on {revision}: {template}" ) }, ), None => checks.require(false, || { format!( "the bound template must stay discoverable on {revision}: {templates}" ) }), } } // Mixed pagination: the template binding must neither fail a page nor duplicate/skip entries. let first = json_body(list_resources(&endpoint, &revision, json!({ "limit": 2 })).await).await; let Some(first_result) = checks.result(&first, &revision, "bounded resources/list") else { continue; }; let mut union: Vec = listed_uris(first_result); let mut next = first_result["nextCursor"].as_str().map(str::to_owned); while let Some(cursor) = next { let page = json_body( list_resources( &endpoint, &revision, json!({ "limit": 2, "cursor": cursor }), ) .await, ) .await; let Some(page_result) = checks.result(&page, &revision, "continued resources/list") else { break; }; union.extend(listed_uris(page_result)); next = page_result["nextCursor"].as_str().map(str::to_owned); } checks.require( union.iter().cloned().collect::>() == expected && union.len() == expected.len(), || { format!( "mixed pagination must neither skip nor repeat Resources on {revision}: {union:?}" ) }, ); } checks.finish(); // Integrity is still enforced for a template admission: a publication whose digest no longer // matches its own definition must fail the page instead of silently dropping the entry. sqlx::query( "update resource_publications set digest = $4 where workspace_id = $1 and resource_id = $2 and version = $3", ) .bind(test_workspace_id().as_str()) .bind(template_id.as_str()) .bind(1_i32) .bind("0".repeat(64)) .execute(registry.pool()) .await .expect("test-owned template publication metadata must be corruptible"); let corrupted = json_body(list_resources(&endpoint, MODERN_REVISION, json!({})).await).await; assert!( corrupted.get("result").is_none(), "a corrupt template publication must fail the page, not answer a partial success: {corrupted}" ); assert_eq!( error_code(&corrupted), -32603, "a corrupt template publication must stay an internal error: {corrupted}" ); }