feat(import): preserve supported HTTP contracts

This commit is contained in:
bsodfather committed 2026-09-13 03:30:31 +03:00
1 parent 083974c27f
commit f8ee7c9bfe
87 files changed
+7496 -534

No files matched your search

+355
View File
@@ -0,0 +1,355 @@
mod support;
use support::RuntimeExecutorTestExt;
use std::{
collections::BTreeMap,
sync::{
Arc, Mutex,
atomic::{AtomicUsize, Ordering},
},
};
use async_trait::async_trait;
use crank_core::{
AdapterResponse, ExecutionConfig, ExecutionMode, OperationId, Protocol, ProtocolAdapter,
ProtocolAdapterError, Target, ToolDescription,
};
use crank_import::rest::{RestImportCandidate, preview_document};
use crank_runtime::{RuntimeExecutorBuilder, RuntimeOperation};
use serde_json::{Value, json};
#[derive(Clone)]
struct CaptureAdapter {
calls: Arc<AtomicUsize>,
prepared: Arc<Mutex<Option<crank_core::PreparedRequest>>>,
response: AdapterResponse,
}
#[async_trait]
impl ProtocolAdapter for CaptureAdapter {
fn protocol(&self) -> Protocol {
Protocol::Rest
}
fn supports_mode(&self, mode: ExecutionMode) -> bool {
mode == ExecutionMode::Unary
}
async fn invoke_unary(
&self,
_target: &Target,
prepared: &crank_core::PreparedRequest,
_context: &crank_core::RuntimeRequestContext,
) -> Result<AdapterResponse, ProtocolAdapterError> {
self.calls.fetch_add(1, Ordering::SeqCst);
*self.prepared.lock().expect("prepared lock") = Some(prepared.clone());
Ok(self.response.clone())
}
}
#[tokio::test]
async fn imported_media_selector_is_validated_before_adapter_and_travels_out_of_band() {
let operation = imported_operation(
r#"
openapi: 3.0.3
info: { title: Media }
servers: [{ url: https://example.invalid }]
paths:
/events:
post:
requestBody:
required: true
content:
application/json:
schema: { type: object, required: [name], properties: { name: { type: string } } }
application/x-www-form-urlencoded:
schema: { type: object, required: [title], properties: { title: { type: string } } }
responses: { '204': { description: Empty } }
"#,
);
let calls = Arc::new(AtomicUsize::new(0));
let prepared = Arc::new(Mutex::new(None));
let executor = RuntimeExecutorBuilder::new()
.register_adapter(Arc::new(CaptureAdapter {
calls: Arc::clone(&calls),
prepared: Arc::clone(&prepared),
response: response(204, BTreeMap::new(), Value::Null),
}))
.build();
for invalid in [
json!({"body": {"name": "Ada"}}),
json!({"content_type": "text/plain", "body": {"name": "Ada"}}),
json!({"content_type": "application/json", "body": {"title": "wrong branch"}}),
] {
assert!(executor.execute(&operation, &invalid).await.is_err());
}
assert_eq!(calls.load(Ordering::SeqCst), 0);
assert!(
executor
.execute(
&operation,
&json!({"content_type": "application/json", "body": {"name": "Ada"}}),
)
.await
.is_ok()
);
let prepared = prepared.lock().expect("prepared lock").clone().unwrap();
assert_eq!(prepared.body, Some(json!({"name": "Ada"})));
assert_eq!(
prepared.body_content_type.as_deref(),
Some("application/json")
);
}
#[tokio::test]
async fn imported_single_body_preserves_empty_object_and_required_file_fails_before_adapter() {
let empty_operation = imported_operation(
r#"
openapi: 3.0.3
info: { title: Empty }
servers: [{ url: https://example.invalid }]
paths:
/empty:
post:
requestBody:
required: true
content:
application/json: { schema: { type: object } }
responses: { '204': { description: Empty } }
"#,
);
let calls = Arc::new(AtomicUsize::new(0));
let prepared = Arc::new(Mutex::new(None));
let executor = RuntimeExecutorBuilder::new()
.register_adapter(Arc::new(CaptureAdapter {
calls: Arc::clone(&calls),
prepared: Arc::clone(&prepared),
response: response(204, BTreeMap::new(), Value::Null),
}))
.build();
assert!(
executor
.execute(&empty_operation, &json!({"body": {}}))
.await
.is_ok()
);
assert_eq!(
prepared
.lock()
.expect("prepared lock")
.as_ref()
.unwrap()
.body,
Some(json!({}))
);
let file_operation = imported_operation(
r#"
openapi: 3.0.3
info: { title: Upload }
servers: [{ url: https://example.invalid }]
paths:
/upload:
post:
requestBody:
required: true
content:
multipart/form-data:
schema:
type: object
required: [file]
properties: { file: { type: string, format: binary } }
responses: { '204': { description: Empty } }
"#,
);
assert!(
executor
.execute(&file_operation, &json!({"body": {}}))
.await
.is_err()
);
assert_eq!(calls.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn response_status_selects_its_linked_output_schema_branch() {
let operation = imported_operation(
r#"
openapi: 3.0.3
info: { title: Responses }
servers: [{ url: https://example.invalid }]
paths:
/items:
get:
responses:
'200':
description: Full
content:
application/json:
schema: { type: object, required: [id], properties: { id: { type: string } } }
'206':
description: Partial
content:
application/json:
schema: { type: array, items: { type: string } }
"#,
);
let executor = RuntimeExecutorBuilder::new()
.register_adapter(Arc::new(CaptureAdapter {
calls: Arc::new(AtomicUsize::new(0)),
prepared: Arc::new(Mutex::new(None)),
response: response(
200,
BTreeMap::from([("content-type".to_owned(), "application/json".to_owned())]),
json!(["schema-for-206"]),
),
}))
.build();
assert!(executor.execute(&operation, &json!({})).await.is_err());
for (status, body) in [(200, json!({"id": "full"})), (206, json!(["partial"]))] {
let executor = RuntimeExecutorBuilder::new()
.register_adapter(Arc::new(CaptureAdapter {
calls: Arc::new(AtomicUsize::new(0)),
prepared: Arc::new(Mutex::new(None)),
response: response(
status,
BTreeMap::from([("content-type".to_owned(), "application/json".to_owned())]),
body.clone(),
),
}))
.build();
assert_eq!(
executor.execute(&operation, &json!({})).await.unwrap(),
body
);
}
}
#[tokio::test]
async fn single_response_preserves_all_source_composition_branches() {
let operation = imported_operation(
r#"
openapi: 3.0.3
info: {title: Response union}
servers: [{url: https://example.invalid}]
paths:
/items:
get:
responses:
'200':
description: Either
content:
application/json:
schema:
oneOf:
- {type: string}
- {type: integer}
"#,
);
let Target::Rest(target) = &operation.target;
assert_eq!(target.response_contract.len(), 1);
assert_eq!(operation.output_schema.variants.len(), 2);
for body in [json!("text"), json!(42)] {
let executor = RuntimeExecutorBuilder::new()
.register_adapter(Arc::new(CaptureAdapter {
calls: Arc::new(AtomicUsize::new(0)),
prepared: Arc::new(Mutex::new(None)),
response: response(
200,
BTreeMap::from([("content-type".to_owned(), "application/json".to_owned())]),
body.clone(),
),
}))
.build();
assert_eq!(
executor.execute(&operation, &json!({})).await.unwrap(),
body
);
}
}
#[tokio::test]
async fn optional_single_body_distinguishes_omission_empty_object_and_null() {
let operation = imported_operation(
r#"
openapi: 3.0.3
info: {title: Optional body}
servers: [{url: https://example.invalid}]
paths:
/items:
post:
requestBody:
required: false
content:
application/json:
schema: {type: object, nullable: true}
responses: {'204': {description: Empty}}
"#,
);
let prepared = Arc::new(Mutex::new(None));
let executor = RuntimeExecutorBuilder::new()
.register_adapter(Arc::new(CaptureAdapter {
calls: Arc::new(AtomicUsize::new(0)),
prepared: Arc::clone(&prepared),
response: response(204, BTreeMap::new(), Value::Null),
}))
.build();
for (input, expected) in [
(json!({}), None),
(json!({"body": {}}), Some(json!({}))),
(json!({"body": null}), Some(Value::Null)),
] {
executor.execute(&operation, &input).await.unwrap();
assert_eq!(prepared.lock().unwrap().as_ref().unwrap().body, expected);
}
}
fn imported_operation(document: &str) -> RuntimeOperation {
let preview = preview_document(document).expect("preview");
let draft = preview.groups[0].operations[0].draft.clone();
runtime_operation(draft)
}
fn runtime_operation(draft: RestImportCandidate) -> RuntimeOperation {
RuntimeOperation {
operation_id: OperationId::new("op_http_contract"),
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: 1_000,
retry_policy: None,
response_cache: None,
idempotency: None,
safety: None,
approval_policy: None,
auth_profile_ref: None,
headers: BTreeMap::new(),
},
tool_description: ToolDescription {
title: draft.tool_description.title,
description: draft.tool_description.description,
tags: draft.tool_description.tags,
examples: draft.tool_description.examples,
},
}
}
fn response(status_code: u16, headers: BTreeMap<String, String>, body: Value) -> AdapterResponse {
AdapterResponse {
status_code,
headers,
data: body.clone(),
body,
}
}
@@ -0,0 +1,170 @@
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<Mutex<Vec<(HeaderMap, String, Bytes)>>>;
async fn capture(
State(requests): State<Requests>,
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::<serde_json::Value>(&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();
}
@@ -296,6 +296,9 @@ fn destructive_delete_operation() -> Operation<Schema, MappingSet> {
method: HttpMethod::Delete,
path_template: "/orders/{order_id}".to_owned(),
static_headers: BTreeMap::new(),
request_contract: None,
response_contract: Vec::new(),
multipart_field_mime_types: BTreeMap::new(),
}),
input_schema: object_schema(BTreeMap::from([("order_id".to_owned(), string_schema())])),
output_schema: object_schema(BTreeMap::from([("deleted".to_owned(), bool_schema())])),
@@ -353,6 +356,7 @@ fn destructive_delete_operation() -> Operation<Schema, MappingSet> {
fn object_schema(fields: BTreeMap<String, Schema>) -> Schema {
Schema {
kind: SchemaKind::Object,
format: None,
description: None,
required: true,
nullable: false,
@@ -367,6 +371,7 @@ fn object_schema(fields: BTreeMap<String, Schema>) -> Schema {
fn string_schema() -> Schema {
Schema {
kind: SchemaKind::String,
format: None,
description: None,
required: true,
nullable: false,
@@ -381,6 +386,7 @@ fn string_schema() -> Schema {
fn bool_schema() -> Schema {
Schema {
kind: SchemaKind::Boolean,
format: None,
description: None,
required: true,
nullable: false,
@@ -310,6 +310,9 @@ fn idempotent_post_operation() -> Operation<Schema, MappingSet> {
method: HttpMethod::Post,
path_template: "/orders".to_owned(),
static_headers: BTreeMap::new(),
request_contract: None,
response_contract: Vec::new(),
multipart_field_mime_types: BTreeMap::new(),
}),
input_schema: object_schema(BTreeMap::from([("request_id".to_owned(), string_schema())])),
output_schema: object_schema(BTreeMap::from([("result".to_owned(), string_schema())])),
@@ -359,6 +362,7 @@ fn idempotent_post_operation() -> Operation<Schema, MappingSet> {
fn object_schema(fields: BTreeMap<String, Schema>) -> Schema {
Schema {
kind: SchemaKind::Object,
format: None,
description: None,
required: true,
nullable: false,
@@ -373,6 +377,7 @@ fn object_schema(fields: BTreeMap<String, Schema>) -> Schema {
fn string_schema() -> Schema {
Schema {
kind: SchemaKind::String,
format: None,
description: None,
required: true,
nullable: false,
@@ -72,9 +72,13 @@ fn no_input_get_operation() -> Operation<Schema, MappingSet> {
method: HttpMethod::Get,
path_template: "/health".to_owned(),
static_headers: BTreeMap::new(),
request_contract: None,
response_contract: Vec::new(),
multipart_field_mime_types: BTreeMap::new(),
}),
input_schema: Schema {
kind: SchemaKind::Object,
format: None,
description: None,
required: true,
nullable: false,
@@ -86,6 +90,7 @@ fn no_input_get_operation() -> Operation<Schema, MappingSet> {
},
output_schema: Schema {
kind: SchemaKind::Object,
format: None,
description: None,
required: true,
nullable: false,
@@ -322,6 +322,9 @@ fn operation(
method,
path_template: "/resource".to_owned(),
static_headers: BTreeMap::new(),
request_contract: None,
response_contract: Vec::new(),
multipart_field_mime_types: BTreeMap::new(),
}),
input_schema: object_schema("key"),
output_schema: object_schema("result"),
@@ -366,6 +369,7 @@ fn operation(
fn object_schema(field: &str) -> Schema {
Schema {
kind: SchemaKind::Object,
format: None,
description: None,
required: true,
nullable: false,
@@ -374,6 +378,7 @@ fn object_schema(field: &str) -> Schema {
field.to_owned(),
Schema {
kind: SchemaKind::String,
format: None,
description: None,
required: true,
nullable: false,
+6
View File
@@ -597,6 +597,9 @@ fn operation() -> Operation<Schema, MappingSet> {
method: HttpMethod::Post,
path_template: "/test".to_owned(),
static_headers: BTreeMap::new(),
request_contract: None,
response_contract: Vec::new(),
multipart_field_mime_types: BTreeMap::new(),
}),
input_schema: object_schema(BTreeMap::from([("name".to_owned(), string_schema())])),
output_schema: object_schema(BTreeMap::from([("accepted".to_owned(), bool_schema())])),
@@ -651,6 +654,7 @@ fn operation() -> Operation<Schema, MappingSet> {
fn object_schema(fields: BTreeMap<String, Schema>) -> Schema {
Schema {
kind: SchemaKind::Object,
format: None,
description: None,
required: true,
nullable: false,
@@ -665,6 +669,7 @@ fn object_schema(fields: BTreeMap<String, Schema>) -> Schema {
fn string_schema() -> Schema {
Schema {
kind: SchemaKind::String,
format: None,
description: None,
required: true,
nullable: false,
@@ -679,6 +684,7 @@ fn string_schema() -> Schema {
fn bool_schema() -> Schema {
Schema {
kind: SchemaKind::Boolean,
format: None,
..string_schema()
}
}