mod support; use support::RuntimeExecutorTestExt; use std::{ collections::BTreeMap, sync::{Arc, Mutex}, }; use axum::{ Router, body::Bytes, extract::{OriginalUri, State}, http::{HeaderMap, StatusCode}, routing::post, }; use crank_adapter_rest::{OutboundHttpPolicy, RestAdapter}; use crank_core::{ExecutionConfig, OperationId, Protocol, Target}; use crank_import::rest::preview_document; use crank_runtime::{RuntimeExecutorBuilder, RuntimeOperation}; use serde_json::json; use tokio::net::TcpListener; type Requests = Arc>>; async fn capture( State(requests): State, OriginalUri(uri): OriginalUri, headers: HeaderMap, body: Bytes, ) -> StatusCode { requests .lock() .unwrap() .push((headers, uri.to_string(), body)); StatusCode::NO_CONTENT } #[tokio::test] async fn imported_variants_execute_on_wire_and_reject_invalid_inputs_before_dispatch() { let requests: Requests = Arc::new(Mutex::new(Vec::new())); let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let base_url = format!("http://{}", listener.local_addr().unwrap()); let app = Router::new() .route("/events", post(capture)) .with_state(Arc::clone(&requests)); let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap(); }); let source = r#" openapi: 3.0.3 info: {title: Wire contract} servers: [{url: 'http://wire.invalid'}] paths: /events: post: operationId: createEvent parameters: - {name: body, in: query, schema: {type: string}} - {name: content_type, in: cookie, schema: {type: string}} requestBody: required: false content: application/json: schema: {type: object, nullable: true, required: [name], properties: {name: {type: string}}} application/x-www-form-urlencoded: schema: {type: object, required: [title], properties: {title: {type: string}}} multipart/form-data: schema: {type: object, required: [file], properties: {file: {type: string, format: binary}}} encoding: {file: {contentType: 'image/png, image/jpeg'}} responses: {'204': {description: Empty}} "#.replace("http://wire.invalid", &base_url); let preview = preview_document(&source).unwrap(); assert_eq!(preview.groups[0].operations.len(), 1); assert!( !preview .findings .iter() .any(|finding| finding.severity == crank_import::rest::ImportFindingSeverity::Error) ); let draft = preview.groups[0].operations[0].draft.clone(); let operation = RuntimeOperation { operation_id: OperationId::new("op_http_wire"), operation_version: 1, tool_name: draft.name, protocol: Protocol::Rest, target: Target::Rest(draft.target), input_schema: draft.input_schema, output_schema: draft.output_schema, input_mapping: draft.input_mapping, output_mapping: draft.output_mapping, execution_config: ExecutionConfig { timeout_ms: 2000, retry_policy: None, response_cache: None, idempotency: None, safety: None, approval_policy: None, auth_profile_ref: None, headers: BTreeMap::new(), }, tool_description: draft.tool_description, }; let executor = RuntimeExecutorBuilder::new() .register_adapter(Arc::new(RestAdapter::with_policy( OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]), ))) .build(); for invalid in [ json!({"body": {"name": "Ada"}}), json!({"content_type": "application/json"}), json!({"content_type": "text/plain", "body": {"name": "Ada"}}), json!({"content_type": "application/json", "body": {"title": "wrong"}}), json!({"content_type": "multipart/form-data", "body": {}}), json!({"content_type": "multipart/form-data", "body": {"file": {"data_base64": "AA==", "filename": "bad\r\nname"}}}), json!({"content_type": "multipart/form-data", "body": {"file": {"data_base64": "AA==", "content_type": "text/plain"}}}), json!({"content_type": "multipart/form-data", "body": {"file": {"data_base64": "AA=="}}}), json!({"content_type": "application/x-www-form-urlencoded", "body": null}), ] { assert!( executor.execute(&operation, &invalid).await.is_err(), "accepted {invalid}" ); } for invalid_base64 in [ "AA==\n", "_w==", "data:application/octet-stream;base64,AA==", "AA", "%%%", ] { let invalid = json!({"content_type":"multipart/form-data", "body":{"file":{"data_base64":invalid_base64,"content_type":"image/png"}}}); assert!(executor.execute(&operation, &invalid).await.is_err()); } assert!(requests.lock().unwrap().is_empty()); for valid in [ json!({"query_body": "wire-query", "cookie_content_type": "wire-cookie", "content_type": "application/json", "body": {"name": "Ada"}}), json!({"content_type": "application/x-www-form-urlencoded", "body": {"title": "A B"}}), json!({"content_type": "multipart/form-data", "body": {"file": {"data_base64": "AAH/", "filename": "image.png", "content_type": "image/png"}}}), json!({"content_type": "application/json", "body": null}), json!({}), ] { executor.execute(&operation, &valid).await.unwrap(); } let captured = requests.lock().unwrap(); assert_eq!(captured.len(), 5); assert_eq!(captured[0].0["content-type"], "application/json"); assert_eq!(captured[0].0["cookie"], "content_type=wire-cookie"); assert_eq!(captured[0].1, "/events?body=wire-query"); assert_eq!( serde_json::from_slice::(&captured[0].2).unwrap(), json!({"name":"Ada"}) ); assert_eq!(&captured[1].2[..], b"title=A+B"); assert!( captured[2].0["content-type"] .to_str() .unwrap() .starts_with("multipart/form-data; boundary=") ); assert!( captured[2] .2 .windows(9) .any(|bytes| bytes == b"\r\n\r\n\0\x01\xff\r\n") ); assert_eq!(&captured[3].2[..], b"null"); assert!(captured[4].2.is_empty()); server.abort(); }