//! ATDD (RED) Story 3.10 / FR-16 — REST-backed Resource templates. //! //! Источник контракта: `_bmad-output/initiative-crank/epic-mcp-capabilities/ //! spec-resource-templates/spec.md` (wire, коды, пределы, AC→test map) + //! binding TL amendments t_2fb1508b comment 168. //! //! Состояние на момент написания: dynamic REST-backed Resource отсутствует. //! `metadata.source` сейчас игнорируется, а multipart требует часть `content`, //! поэтому каждый RED ниже — реальное поведенческое расхождение на HTTP-ответе //! (`400 validation_error` malformed multipart или `201` с проигнорированным //! source), а не ошибка компиляции/setup. Работоспособность харнесса //! (auth/session/PG/multipart/публикация операции) доказывает //! `story310_at00_static_control_create_publish_and_exact_published_source`. //! //! Фильтр запуска: `cargo test -p admin-api --test integration story310`. use super::super::common::{ TestServer, assert_success_json, authorized_client, build_test_app, operation_etag, spawn_admin_api, spawn_upstream_server, test_registry, test_storage_root, }; use super::helpers::{ DEFAULT_WORKSPACE_ID, OWNED_WORKSPACE_ID, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD, create_owned_workspace, draft_form, draft_metadata, draft_updated_at, error_signature, get_card, list_resources, login_client, post_draft_raw, read_preview, read_response, }; use crank_registry::PostgresRegistry; use reqwest::StatusCode; use reqwest::multipart::{Form, Part}; use serde_json::{Value, json}; // --------------------------------------------------------------------------- // Стенд и фикстуры // --------------------------------------------------------------------------- pub(super) async fn spawn_stand( name: &str, ) -> (PostgresRegistry, TestServer, reqwest::Client, String) { let registry = test_registry().await; let app = build_test_app(registry.clone(), test_storage_root(name)); let server = spawn_admin_api(app).await; let client = authorized_client(&server).await; let upstream = spawn_upstream_server().await; (registry, server, client, upstream) } fn metadata_part(metadata: &Value) -> Part { Part::bytes(serde_json::to_vec(metadata).expect("metadata must serialize")) .file_name("metadata.json".to_owned()) .mime_str("application/json") .expect("json part mime") } /// Multipart template Draft: только `metadata` (часть `content` обязана отсутствовать). pub(super) fn template_form(metadata: &Value) -> Form { Form::new().part("metadata", metadata_part(metadata)) } pub(super) async fn post_template_raw( client: &reqwest::Client, server: impl AsRef + Copy, metadata: &Value, ) -> (StatusCode, String, Value) { read_response( client .post(format!("{}/resources", server.as_ref())) .multipart(template_form(metadata)) .send() .await .expect("template create request must complete"), ) .await } pub(super) async fn create_template_draft( client: &reqwest::Client, server: impl AsRef + Copy, metadata: &Value, ) -> Value { let (status, text, body) = post_template_raw(client, server, metadata).await; assert_eq!( status, StatusCode::CREATED, "POST /resources with metadata.source must create a template Draft; observed {} body={text}", error_signature(status, &body) ); body } pub(super) async fn put_template_raw( client: &reqwest::Client, server: impl AsRef + Copy, resource_id: &str, metadata: &Value, ) -> (StatusCode, String, Value) { read_response( client .put(format!("{}/resources/{resource_id}", server.as_ref())) .multipart(template_form(metadata)) .send() .await .expect("template update request must complete"), ) .await } pub(super) async fn publish_raw( client: &reqwest::Client, server: impl AsRef + Copy, resource_id: &str, expected_updated_at: Option<&str>, ) -> (StatusCode, String, Value) { let body = match expected_updated_at { Some(value) => json!({ "expected_updated_at": value }), None => json!({}), }; read_response( client .post(format!( "{}/resources/{resource_id}/publish", server.as_ref() )) .json(&body) .send() .await .expect("publish request must complete"), ) .await } pub(super) async fn publish_with_card( client: &reqwest::Client, server: impl AsRef + Copy, resource_id: &str, ) -> (StatusCode, String, Value) { let card = get_card(client, server, resource_id).await; let updated_at = draft_updated_at(&card); publish_raw(client, server, resource_id, Some(&updated_at)).await } /// Коды findings из preview-ответа. pub(super) fn preview_codes(body: &Value) -> Vec { codes_of(&body["findings"]) } /// Коды findings из блокирующего 422 (`error.context.findings`). pub(super) fn blocked_codes(body: &Value) -> Vec { let context = &body["error"]["context"]["findings"]; if context.is_array() { codes_of(context) } else { codes_of(&body["findings"]) } } fn codes_of(items: &Value) -> Vec { items .as_array() .map(|array| { array .iter() .filter_map(|item| item["code"].as_str().map(str::to_owned)) .collect() }) .unwrap_or_default() } pub(super) fn assert_has_code(codes: &[String], expected: &str, context: &str) { assert!( codes.iter().any(|code| code == expected), "{context}: expected blocker finding `{expected}`, observed {codes:?}" ); } /// Draft создаётся, preview показывает искомый finding, publish блокируется им же. pub(super) async fn expect_blocked( client: &reqwest::Client, server: &TestServer, metadata: &Value, expected_code: &str, label: &str, ) -> Value { let created = create_template_draft(client, server, metadata).await; let resource_id = created["resource"]["resource_id"] .as_str() .expect("template Draft id") .to_owned(); let (status, text, preview) = read_preview(client, server, &resource_id).await; assert_eq!( status, StatusCode::OK, "preview must answer 200 ({label}): {text}" ); assert_has_code( &preview_codes(&preview), expected_code, &format!("preview finding ({label})"), ); let (status, text, published) = publish_with_card(client, server, &resource_id).await; assert_eq!( status, StatusCode::UNPROCESSABLE_ENTITY, "a blocker finding must stop publication ({label}); observed {} body={text}", error_signature(status, &published) ); assert_eq!(published["error"]["code"], json!("resource_source_blocked")); assert_has_code( &blocked_codes(&published), expected_code, &format!("publication blocker ({label})"), ); let card = get_card(client, server, &resource_id).await; assert_eq!( card["resource"]["latest_published_version"], Value::Null, "a blocked template must not be published ({label})" ); published } // --------------------------------------------------------------------------- // Operation fixtures (существующий accepted contract) // --------------------------------------------------------------------------- pub(super) fn object_schema(field: &str, schema: Value) -> Value { json!({ "type": "object", "required": true, "fields": { field: schema } }) } pub(super) fn string_field() -> Value { json!({ "type": "string", "required": true }) } pub(super) fn path_input_mapping(field: &str) -> Value { json!({ "rules": [ { "source": format!("$.mcp.{field}"), "target": format!("$.request.path.{field}"), "required": true } ] }) } pub(super) fn operation_payload( name: &str, upstream: &str, method: &str, path_template: &str, input_schema: Value, input_mapping: Value, execution_config: Value, ) -> Value { json!({ "name": name, "display_name": name, "category": "sales", "protocol": "rest", "security_level": "standard", "target": { "kind": "rest", "base_url": upstream, "method": method, "path_template": path_template }, "input_schema": input_schema, "output_schema": object_schema("id", string_field()), "input_mapping": input_mapping, "output_mapping": { "rules": [ { "source": "$.response.body.id", "target": "$.output.id", "required": true } ] }, "execution_config": execution_config, "tool_description": { "title": name, "description": "Story 3.10 fixture" } }) } /// GET-операция, читающая заказ по номеру: путь `/orders/{order_id}` и mapping в /// `request.path.order_id` — существующий accepted контракт Operation. pub(super) fn order_operation_payload( name: &str, upstream: &str, method: &str, safety: Value, approval: Value, headers: Value, ) -> Value { let mut execution = json!({ "timeout_ms": 1_000 }); if !safety.is_null() { execution["safety"] = safety; } if !approval.is_null() { execution["approval_policy"] = approval; } if !headers.is_null() { execution["headers"] = headers; } operation_payload( name, upstream, method, "/orders/{order_id}", object_schema( "order_id", json!({ "type": "string", "required": true, "format": "uuid" }), ), path_input_mapping("order_id"), execution, ) } pub(super) fn read_operation_payload( name: &str, upstream: &str, safety: Value, approval: Value, headers: Value, ) -> Value { order_operation_payload(name, upstream, "GET", safety, approval, headers) } pub(super) fn read_safety() -> Value { json!({ "class": "read" }) } pub(super) fn approval_required() -> Value { json!({ "required": true, "risk_level": "dangerous", "ttl_seconds": 30, "show_payload_preview": false, "payload_preview_mode": "summary" }) } pub(super) async fn create_operation( client: &reqwest::Client, server: impl AsRef + Copy, payload: &Value, ) -> String { let created = assert_success_json( client .post(format!("{}/operations", server.as_ref())) .json(payload) .send() .await .expect("operation create must complete"), ) .await; created["operation_id"] .as_str() .expect("operation create must return an id") .to_owned() } pub(super) async fn publish_operation( client: &reqwest::Client, server: impl AsRef + Copy, operation_id: &str, ) -> Value { let etag = operation_etag(client, server, operation_id).await; assert_success_json( client .post(format!( "{}/operations/{operation_id}/publish", server.as_ref() )) .header(reqwest::header::IF_MATCH, etag) .json(&json!({ "version": 1 })) .send() .await .expect("operation publish must complete"), ) .await } pub(super) async fn published_read_operation( client: &reqwest::Client, server: impl AsRef + Copy, upstream: &str, name: &str, ) -> String { let payload = read_operation_payload(name, upstream, read_safety(), Value::Null, Value::Null); let id = create_operation(client, server, &payload).await; publish_operation(client, server, &id).await; id } pub(super) fn template_source( operation_id: &str, operation_version: u32, uri_template: &str, parameters: Value, cache: Value, failure: Value, ) -> Value { json!({ "operation_id": operation_id, "operation_version": operation_version, "uri_template": uri_template, "parameters": parameters, "cache": cache, "failure": failure }) } pub(super) fn order_parameter(name: &str, input_path: &str, schema: Value) -> Value { json!({ "name": name, "input_path": input_path, "schema": schema }) } pub(super) fn cache_policy(ttl_ms: Value, vary: Value, max_bytes: Value) -> Value { json!({ "ttl_ms": ttl_ms, "vary": vary, "max_bytes": max_bytes }) } pub(super) fn error_outcome() -> Value { json!({ "outcome": "error" }) } /// Валидный source для published GET-операции `/orders/{order_id}`. pub(super) fn valid_source(operation_id: &str) -> Value { template_source( operation_id, 1, "crank://orders/{order_id}", json!([order_parameter( "order_id", "input.order_id", json!({ "type": "string", "required": true, "format": "uuid" }) )]), cache_policy(json!(60_000), json!(["order_id"]), json!(65_536)), error_outcome(), ) } pub(super) fn template_metadata(uri: &str, name: &str, source: Value) -> Value { let mut metadata = draft_metadata(uri, name, "text", "text/plain", "internal"); metadata["source"] = source; metadata } // --------------------------------------------------------------------------- // AT-3.10-00 — positive controls (должны быть GREEN и сейчас) // --------------------------------------------------------------------------- #[tokio::test(flavor = "multi_thread")] #[serial_test::serial] async fn story310_at00_static_control_create_publish_and_exact_published_source() { let (_registry, server, client, upstream) = spawn_stand("story310_control").await; // 1. Статический Draft по-прежнему создаётся и публикуется (auth/PG/multipart/publish). let static_metadata = draft_metadata( "crank://story310/static", "story310_static", "text", "text/plain", "internal", ); let (status, _traceable, text, body) = post_draft_raw( &client, &server, &static_metadata, b"story310 static body\n", "text/plain", ) .await; assert_eq!( status, StatusCode::CREATED, "static create is the harness positive control; observed {} body={text}", error_signature(status, &body) ); let static_id = body["resource"]["resource_id"] .as_str() .expect("created static draft id") .to_owned(); let (status, text, body) = publish_with_card(&client, &server, &static_id).await; assert_eq!( status, StatusCode::OK, "static publish is the harness positive control; observed {} body={text}", error_signature(status, &body) ); // 2. Точная Published версия GET-операции доступна через существующий контракт. let operation_id = published_read_operation(&client, &server, &upstream, "story310_control_read").await; let (status, text, version) = read_response( client .get(format!( "{}/operations/{operation_id}/versions/1", server.as_ref() )) .send() .await .expect("operation version request must complete"), ) .await; assert_eq!( status, StatusCode::OK, "the seeded exact Published Operation Version must be readable; observed {} body={text}", error_signature(status, &version) ); assert_eq!(version["snapshot"]["target"]["method"], json!("GET")); assert_eq!( version["snapshot"]["target"]["path_template"], json!("/orders/{order_id}") ); assert_eq!( version["snapshot"]["input_schema"]["fields"]["order_id"]["type"], json!("string") ); assert_eq!( version["snapshot"]["input_mapping"]["rules"][0]["target"], json!("$.request.path.order_id") ); assert_eq!(version["status"], json!("published")); } // --------------------------------------------------------------------------- // AC1 — только exact Published Operation Version того же workspace // --------------------------------------------------------------------------- #[tokio::test(flavor = "multi_thread")] #[serial_test::serial] async fn story310_at01_draft_accepts_only_exact_published_operation_version() { let (_registry, server, client, upstream) = spawn_stand("story310_at01_exact").await; let operation_id = published_read_operation(&client, &server, &upstream, "story310_at01_read").await; let metadata = template_metadata( "crank://story310/orders", "story310_orders", valid_source(&operation_id), ); let created = create_template_draft(&client, &server, &metadata).await; let resource_id = created["resource"]["resource_id"] .as_str() .expect("template Draft id") .to_owned(); let source = &created["source"]; assert_eq!(source["operation_id"], json!(operation_id)); assert_eq!(source["operation_version"], json!(1)); assert_eq!(source["uri_template"], json!("crank://orders/{order_id}")); assert_eq!( source["parameters"][0]["input_path"], json!("input.order_id"), "input_path addresses the pinned Operation input_schema, not request.path" ); assert_eq!(source["cache"]["scope"], json!("workspace_agent_auth")); assert_eq!(source["read_safety"]["method"], json!("GET")); assert_eq!(source["read_safety"]["read_safe"], json!(true)); assert_eq!(source["access"]["security_level"], json!("standard")); let (status, text, preview) = read_preview(&client, &server, &resource_id).await; assert_eq!(status, StatusCode::OK, "preview must succeed: {text}"); assert!( preview_codes(&preview).is_empty(), "a read-safe, fully mapped template Draft has no findings: {preview}" ); assert_eq!(preview["preview"]["text"], Value::Null); let (status, text, published) = publish_with_card(&client, &server, &resource_id).await; assert_eq!( status, StatusCode::OK, "the accepted template Draft must publish; observed {} body={text}", error_signature(status, &published) ); assert_eq!( published["published_version"]["source"]["operation_id"], json!(operation_id) ); assert_eq!( published["published_version"]["source"]["operation_version"], json!(1) ); // Negative: версия существует, но не Published → стабильный 422, публикации нет. let draft_payload = read_operation_payload( "story310_at01_draft_only", &upstream, read_safety(), Value::Null, Value::Null, ); let draft_operation_id = create_operation(&client, &server, &draft_payload).await; let mut draft_source = valid_source(&draft_operation_id); draft_source["operation_version"] = json!(1); let draft_metadata_value = template_metadata( "crank://story310/orders-draft-op", "story310_orders_draft_op", draft_source, ); let (status, text, body) = post_template_raw(&client, &server, &draft_metadata_value).await; assert_eq!( status, StatusCode::UNPROCESSABLE_ENTITY, "a Draft Operation Version must not become a source; observed {} body={text}", error_signature(status, &body) ); assert_eq!( body["error"]["code"], json!("resource_source_not_published") ); assert_eq!( body["error"]["context"]["field"], json!("source.operation_version") ); let (_, _, listed) = list_resources(&client, &server).await; assert_eq!( listed["items"].as_array().map(Vec::len), Some(1), "the rejected Draft must not create a second Resource: {listed}" ); // Positive control: тот же валидный source всё ещё создаётся (не «блокируется всё»). let accepted_metadata = template_metadata( "crank://story310/orders-accepted", "story310_orders_accepted", valid_source(&operation_id), ); create_template_draft(&client, &server, &accepted_metadata).await; } #[tokio::test(flavor = "multi_thread")] #[serial_test::serial] async fn story310_at01_source_rejects_arbitrary_url_and_inline_request_fields() { let (_registry, server, client, upstream) = spawn_stand("story310_at01_url").await; let operation_id = published_read_operation(&client, &server, &upstream, "story310_at01_url_read").await; // Positive control: валидный source-only request создаётся. let accepted = template_metadata( "crank://story310/url-accepted", "story310_url_accepted", valid_source(&operation_id), ); create_template_draft(&client, &server, &accepted).await; let (_, _, listed_before) = list_resources(&client, &server).await; let before = listed_before["items"].as_array().map(Vec::len).unwrap_or(0); // Каждое запрещённое поле — отдельное расширение исходного source. let forbidden = [ ("url", json!("https://evil.example/orders")), ("base_url", json!("https://evil.example")), ("host", json!("evil.example")), ("scheme", json!("https")), ("method", json!("POST")), ("path_template", json!("/orders/{order_id}")), ("headers", json!({ "authorization": "leak" })), ("body", json!({ "order_id": "{order_id}" })), ("request", json!({ "url": "https://evil.example" })), ]; for (index, (field, value)) in forbidden.iter().enumerate() { let mut source = valid_source(&operation_id); source[*field] = value.clone(); let metadata = template_metadata( &format!("crank://story310/url-field-{index}"), &format!("story310_url_field_{index}"), source, ); let (status, text, body) = post_template_raw(&client, &server, &metadata).await; assert_eq!( status, StatusCode::BAD_REQUEST, "source field `{field}` must be rejected; observed {} body={text}", error_signature(status, &body) ); assert_eq!( body["error"]["code"], json!("resource_source_invalid"), "source field `{field}` must use the stable source code: {body}" ); } let (_, _, listed_after) = list_resources(&client, &server).await; assert_eq!( listed_after["items"].as_array().map(Vec::len), Some(before), "rejected source fields must not create Resources: {listed_after}" ); } #[tokio::test(flavor = "multi_thread")] #[serial_test::serial] async fn story310_at01_source_and_content_are_mutually_exclusive() { let (_registry, server, client, upstream) = spawn_stand("story310_at01_exclusive").await; let operation_id = published_read_operation(&client, &server, &upstream, "story310_at01_exclusive_read").await; // Control: тот же metadata без source + content — прежний static Draft (201). let static_metadata = draft_metadata( "crank://story310/exclusive-static", "story310_exclusive_static", "text", "text/plain", "internal", ); let (status, _traceable, text, body) = post_draft_raw( &client, &server, &static_metadata, b"static body\n", "text/plain", ) .await; assert_eq!( status, StatusCode::CREATED, "the static control must stay 201; observed {} body={text}", error_signature(status, &body) ); // Source present ⇒ content part обязана отсутствовать. let metadata = template_metadata( "crank://story310/exclusive", "story310_exclusive", valid_source(&operation_id), ); let (status, text, body) = read_response( client .post(format!("{}/resources", server.as_ref())) .multipart(draft_form( &metadata, b"content must not travel\n", "draft.txt", "text/plain", )) .send() .await .expect("create request must complete"), ) .await; assert_eq!( status, StatusCode::BAD_REQUEST, "a template Draft must not carry a content part; observed {} body={text}", error_signature(status, &body) ); assert_eq!(body["error"]["code"], json!("resource_source_invalid")); assert_eq!(body["error"]["context"]["field"], json!("content")); } #[tokio::test(flavor = "multi_thread")] #[serial_test::serial] async fn story310_at01_foreign_and_missing_operation_are_not_disclosed() { let (registry, server, client, upstream) = spawn_stand("story310_at01_foreign").await; create_owned_workspace(®istry).await; // Права на новый workspace проверяются сессией после membership (как в 3.6 негативах). let owned_client = login_client(&server, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD).await; let owned_base = server .as_ref() .replace(DEFAULT_WORKSPACE_ID, OWNED_WORKSPACE_ID); let foreign_name = "story310_foreign_secret_tool"; let foreign_id = published_read_operation(&owned_client, &owned_base, &upstream, foreign_name).await; for (label, operation_id) in [ ("foreign", foreign_id.as_str()), ("missing", "op_story310_missing"), ] { let metadata = template_metadata( &format!("crank://story310/{label}-op"), &format!("story310_{label}_op"), valid_source(operation_id), ); let (status, text, body) = post_template_raw(&client, &server, &metadata).await; assert_eq!( status, StatusCode::NOT_FOUND, "an unusable source Operation must be a non-disclosing 404 ({label}); observed {} body={text}", error_signature(status, &body) ); assert_eq!(body["error"]["code"], json!("resource_source_not_found")); assert!( !text.contains(foreign_name) && !text.contains("crank://orders/"), "the rejection must not disclose the foreign operation ({label}): {text}" ); } } #[path = "template_boundaries.rs"] mod boundaries; #[path = "template_outbound.rs"] mod outbound; #[path = "template_parameters.rs"] mod parameters; #[path = "template_policy.rs"] mod policy; #[path = "template_safety.rs"] mod safety;