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

+1
View File
@@ -35,6 +35,7 @@ uuid.workspace = true
[dev-dependencies]
axum.workspace = true
crank-import = { path = "../crank-import" }
futures-util = "0.3"
metrics.workspace = true
metrics-util = "0.20.4"
+1
View File
@@ -85,6 +85,7 @@ fn infer_safety_class(operation: &RuntimeOperation) -> OperationSafetyClass {
match &operation.target {
Target::Rest(target) => match target.method {
HttpMethod::Get => OperationSafetyClass::Read,
HttpMethod::Head | HttpMethod::Options => OperationSafetyClass::Read,
HttpMethod::Delete => OperationSafetyClass::Destructive,
HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch => OperationSafetyClass::Write,
},
@@ -185,6 +185,7 @@ mod tests {
fn operation() -> RuntimeOperation {
let schema = Schema {
kind: SchemaKind::Object,
format: None,
description: None,
required: true,
nullable: false,
@@ -204,6 +205,9 @@ mod tests {
method: HttpMethod::Post,
path_template: "/".to_owned(),
static_headers: BTreeMap::new(),
request_contract: None,
response_contract: Vec::new(),
multipart_field_mime_types: BTreeMap::new(),
}),
input_schema: schema.clone(),
output_schema: schema,
+51 -5
View File
@@ -6,7 +6,7 @@ use std::time::{Duration, Instant};
use crank_core::{
AdapterRegistry, CoordinationStateStore, ExecutionMode, InvocationSource, InvocationStatus,
MeteringEvent, ResponseCacheStore, SharedMeteringSink, SharedProtocolAdapter,
MeteringEvent, ResponseCacheStore, SharedMeteringSink, SharedProtocolAdapter, Target,
};
use crank_metrics::{
CacheOutcome, ConfirmationOutcome, IdempotencyOutcome, InFlightGuard,
@@ -24,7 +24,7 @@ use crate::{
AdapterResponse, ExecutionAuthorization, PreparedRequest, RuntimeError,
RuntimeExecutionRequest, RuntimeLimits, RuntimeOperation, RuntimeRequestContext,
auth::apply_resolved_auth,
request_preparation::adapter_prepared_request,
request_preparation::{adapter_prepared_request, validate_selected_body_variant},
response_cache::{
adapter_response_from_cached, cached_response_from_adapter, response_cache_key,
response_cache_ttl,
@@ -284,6 +284,7 @@ impl RuntimeExecutor {
.input_schema
.validate_shape(input)
.map_err(RuntimeError::InputSchema)?;
validate_selected_body_variant(operation, input)?;
if operation.input_mapping.is_empty() {
return Ok(PreparedRequest::default());
@@ -293,7 +294,16 @@ impl RuntimeExecutor {
.input_mapping
.apply(&json!({ "mcp": input }))
.map_err(RuntimeError::InputMapping)?;
PreparedRequest::from_mapping_output(&mapped_input)
let mut prepared = PreparedRequest::from_mapping_output(&mapped_input, &operation.target)?;
let Target::Rest(target) = &operation.target;
if let Some(contract) = &target.request_contract
&& input.get(&contract.body_field).is_none()
{
// Mapping initializes an empty body object for legacy field mappings.
// A typed optional body is absent unless its public argument was supplied.
prepared.body = None;
}
Ok(prepared)
}
async fn execute_prepared(
@@ -838,8 +848,7 @@ fn transform_response(
let span = Stage::RuntimeResponseTransform.span();
let result = span.in_scope(|| {
let finalized_output = finalize_output(operation, response)?;
operation
.output_schema
output_schema_for_response(operation, response)?
.validate_shape(&finalized_output)
.map_err(RuntimeError::OutputSchema)?;
Ok(finalized_output)
@@ -854,6 +863,43 @@ fn transform_response(
result
}
fn output_schema_for_response<'a>(
operation: &'a RuntimeOperation,
response: &AdapterResponse,
) -> Result<&'a crank_schema::Schema, RuntimeError> {
let Target::Rest(target) = &operation.target;
if target.response_contract.is_empty() {
return Ok(&operation.output_schema);
}
let media_type = response
.headers
.get("content-type")
.and_then(|value| value.split(';').next())
.map(str::trim);
let descriptor = target
.response_contract
.iter()
.filter(|descriptor| descriptor.status_code == response.status_code)
.find(|descriptor| match (&descriptor.media_type, media_type) {
(Some(expected), Some(actual)) => expected.eq_ignore_ascii_case(actual),
(None, _) => response.body.is_null(),
_ => false,
})
.ok_or(RuntimeError::InvalidExecutionRequest)?;
if target.response_contract.len() > 1
&& operation.output_schema.kind == crank_schema::SchemaKind::Oneof
{
return operation
.output_schema
.variants
.get(descriptor.schema_variant)
.ok_or(RuntimeError::InvalidExecutionRequest);
}
(descriptor.schema_variant == 0)
.then_some(&operation.output_schema)
.ok_or(RuntimeError::InvalidExecutionRequest)
}
fn record_runtime_result<T>(span: &Span, result: &Result<T, RuntimeError>) {
match result {
Ok(_) => StageOutcome::Success.record(span),
+13 -2
View File
@@ -262,8 +262,14 @@ async fn resolve_existing(
}
pub fn policy(operation: &RuntimeOperation) -> Option<&IdempotencyPolicy> {
let is_mutating_rest =
matches!(&operation.target, Target::Rest(target) if target.method != HttpMethod::Get);
let is_mutating_rest = matches!(
&operation.target,
Target::Rest(target)
if matches!(
target.method,
HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch | HttpMethod::Delete
)
);
if !is_mutating_rest {
return None;
}
@@ -398,9 +404,13 @@ mod tests {
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: Schema {
kind: SchemaKind::Object,
format: None,
description: None,
required: true,
nullable: false,
@@ -412,6 +422,7 @@ mod tests {
},
output_schema: Schema {
kind: SchemaKind::Object,
format: None,
description: None,
required: true,
nullable: false,
+4
View File
@@ -51,6 +51,8 @@ pub struct PreparedRequest {
pub trusted_header_names: BTreeSet<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub body: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub body_content_type: Option<String>,
#[serde(default)]
pub timeout_ms: u64,
}
@@ -72,6 +74,7 @@ impl From<PreparedRequest> for crank_core::PreparedRequest {
headers: value.headers,
trusted_header_names: value.trusted_header_names,
body: value.body,
body_content_type: value.body_content_type,
timeout_ms: value.timeout_ms,
}
}
@@ -85,6 +88,7 @@ impl From<crank_core::PreparedRequest> for PreparedRequest {
headers: value.headers,
trusted_header_names: value.trusted_header_names,
body: value.body,
body_content_type: value.body_content_type,
timeout_ms: value.timeout_ms,
}
}
+169 -4
View File
@@ -1,12 +1,85 @@
use std::collections::BTreeMap;
use crank_core::Target;
use crank_schema::{SchemaError, SchemaKind};
use serde_json::Value;
use crate::{PreparedRequest, RuntimeError, RuntimeOperation};
/// Validates the imported `content_type`/`body` pair before mapping. The
/// public schema exposes the union of supported body shapes, while this check
/// binds the selected media type to its corresponding branch.
pub(crate) fn validate_selected_body_variant(
operation: &RuntimeOperation,
input: &Value,
) -> Result<(), RuntimeError> {
let Target::Rest(target) = &operation.target;
let Some(contract) = &target.request_contract else {
return Ok(());
};
let Some(input) = input.as_object() else {
return Ok(());
};
let body_field = contract.body_field.as_str();
let Some(selector_field) = contract.selector_field.as_deref() else {
if contract.body_required && !input.contains_key(body_field) {
return Err(RuntimeError::InputSchema(SchemaError::missing_field(
format!("$.{body_field}"),
)));
}
return Ok(());
};
match (input.get(selector_field), input.get(body_field)) {
(None, None) if !contract.body_required => Ok(()),
(_, None) => Err(RuntimeError::InputSchema(SchemaError::missing_field(
format!("$.{body_field}"),
))),
(None, Some(_)) => Err(RuntimeError::InputSchema(SchemaError::missing_field(
format!("$.{selector_field}"),
))),
(Some(selector), Some(_)) => {
let Some(selector) = selector.as_str() else {
return Err(RuntimeError::InputSchema(SchemaError::invalid_type(
format!("$.{selector_field}"),
"enum",
"non-string",
)));
};
let Some(descriptor) = contract
.variants
.iter()
.find(|variant| variant.media_type == selector)
else {
return Err(RuntimeError::InputSchema(SchemaError::invalid_enum_value(
format!("$.{selector_field}"),
contract
.variants
.iter()
.map(|variant| variant.media_type.clone())
.collect(),
selector,
)));
};
let selected_schema = if operation.input_schema.kind == SchemaKind::Oneof {
operation
.input_schema
.variants
.get(descriptor.schema_variant)
.ok_or(RuntimeError::InvalidExecutionRequest)?
} else if descriptor.schema_variant == 0 {
&operation.input_schema
} else {
return Err(RuntimeError::InvalidExecutionRequest);
};
selected_schema
.validate_shape(&Value::Object(input.clone()))
.map_err(RuntimeError::InputSchema)
}
}
}
impl PreparedRequest {
pub fn from_mapping_output(mapped: &Value) -> Result<Self, RuntimeError> {
pub fn from_mapping_output(mapped: &Value, target: &Target) -> Result<Self, RuntimeError> {
let request =
mapped
.get("request")
@@ -15,12 +88,40 @@ impl PreparedRequest {
reason: "mapped input must contain request root".to_owned(),
})?;
let mut headers = read_string_map(request.get("headers"), "request.headers")?;
for (index, (name, value)) in read_string_map(request.get("cookies"), "request.cookies")?
.into_iter()
.enumerate()
{
headers.insert(
format!("x-crank-internal-cookie-{index}"),
format!("{name}\t{value}"),
);
}
let typed_body_contract =
matches!(target, Target::Rest(target) if target.request_contract.is_some());
let body = if typed_body_contract {
request.get("body").cloned()
} else {
request.get("body").and_then(non_empty_legacy_body).cloned()
};
let body_content_type = match request.get("body_content_type") {
Some(Value::String(value)) => Some(value.clone()),
Some(_) => {
return Err(RuntimeError::InvalidPreparedRequest {
field: "request.body_content_type".to_owned(),
reason: "must be a string".to_owned(),
});
}
None => None,
};
Ok(Self {
path_params: read_string_map(request.get("path"), "request.path")?,
query_params: read_string_map(request.get("query"), "request.query")?,
headers: read_string_map(request.get("headers"), "request.headers")?,
headers,
trusted_header_names: Default::default(),
body: request.get("body").and_then(non_empty_body).cloned(),
body,
body_content_type,
timeout_ms: 0,
})
}
@@ -93,10 +194,74 @@ fn stringify_value(value: &Value) -> Result<String, String> {
}
}
fn non_empty_body(value: &Value) -> Option<&Value> {
fn non_empty_legacy_body(value: &Value) -> Option<&Value> {
match value {
Value::Null => None,
Value::Object(object) if object.is_empty() => None,
_ => Some(value),
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use crank_core::{
HttpMethod, RestRequestContract, RestRequestContractVersion, RestRequestDescriptor,
RestTarget, Target,
};
use serde_json::json;
use crate::PreparedRequest;
#[test]
fn legacy_empty_and_null_bodies_remain_absent() {
let target = legacy_target();
for body in [json!(null), json!({})] {
let mapped = json!({"request": {"body": body}});
assert_eq!(
PreparedRequest::from_mapping_output(&mapped, &target)
.unwrap()
.body,
None
);
}
}
#[test]
fn typed_contract_preserves_explicit_empty_and_null_bodies() {
let mut target = legacy_target();
let Target::Rest(rest) = &mut target;
rest.request_contract = Some(RestRequestContract {
version: RestRequestContractVersion::V1,
body_field: "body".to_owned(),
selector_field: None,
body_required: true,
variants: vec![RestRequestDescriptor {
media_type: "application/json".to_owned(),
schema_variant: 0,
}],
});
for body in [json!(null), json!({})] {
let mapped = json!({"request": {"body": body}});
assert_eq!(
PreparedRequest::from_mapping_output(&mapped, &target)
.unwrap()
.body,
Some(body)
);
}
}
fn legacy_target() -> Target {
Target::Rest(RestTarget {
base_url: "https://example.invalid".to_owned(),
method: HttpMethod::Post,
path_template: "/".to_owned(),
static_headers: BTreeMap::new(),
request_contract: None,
response_contract: Vec::new(),
multipart_field_mime_types: BTreeMap::new(),
})
}
}
+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()
}
}