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

+351 -7
View File
@@ -1,6 +1,9 @@
mod unit {
use crank_core::HttpMethod;
use crank_import::rest::{ImportParseError, preview_document, preview_document_legacy_v1};
use crank_import::rest::{
ImportParseError, NormalizationConfig, SourceDigest, normalize_verified_document,
preview_document, preview_document_legacy_v1,
};
use crank_schema::SchemaKind;
use serde_json::json;
@@ -174,7 +177,8 @@ paths:
assert_eq!(labels.kind, SchemaKind::Array);
assert_eq!(labels.items.as_ref().unwrap().kind, SchemaKind::String);
let payload = operation.draft.input_schema.field("payload").unwrap();
let body = operation.draft.input_schema.field("body").unwrap();
let payload = body.field("payload").unwrap();
assert_eq!(payload.description.as_deref(), Some("Request payload"));
assert_eq!(
payload.field("enabled").unwrap().description.as_deref(),
@@ -214,7 +218,7 @@ paths:
let v2 = preview_document(document).unwrap();
assert_eq!(
v2.groups[0].operations[0].draft.output_schema.kind,
SchemaKind::String
SchemaKind::Oneof
);
let legacy = preview_document_legacy_v1(document).unwrap();
@@ -555,10 +559,10 @@ paths:
.map(|rule| rule.target.as_str())
.collect::<Vec<_>>();
assert!(input_fields.contains_key("email"));
assert!(input_fields.contains_key("name"));
assert!(targets.contains(&"$.request.body.email"));
assert!(targets.contains(&"$.request.body.name"));
assert!(input_fields.contains_key("body"));
assert!(input_fields["body"].fields.contains_key("email"));
assert!(input_fields["body"].fields.contains_key("name"));
assert!(targets.contains(&"$.request.body"));
}
#[test]
@@ -612,4 +616,344 @@ paths:
assert!(codes.contains(&"weak_tool_name"));
assert!(codes.contains(&"too_many_output_fields"));
}
#[test]
fn previews_head_and_options_operations_and_rejects_trace_connect() {
let document = r#"
openapi: 3.0.3
info: { title: Method coverage }
paths:
/health:
head:
operationId: healthHead
responses: { '204': { description: Empty } }
options:
operationId: healthOptions
responses: { '204': { description: Empty } }
trace:
responses: { '200': { description: Unsupported } }
connect:
responses: { '200': { description: Unsupported } }
"#;
let preview = preview_document(document).unwrap();
let operations = preview
.groups
.iter()
.flat_map(|group| group.operations.iter())
.collect::<Vec<_>>();
assert_eq!(operations.len(), 2);
assert!(operations.iter().any(|operation| {
operation.key == "HEAD /health" && operation.method == HttpMethod::Head
}));
assert!(operations.iter().any(|operation| {
operation.key == "OPTIONS /health" && operation.method == HttpMethod::Options
}));
let unsupported = preview
.findings
.iter()
.filter(|finding| finding.code == "unsupported_http_method")
.count();
assert_eq!(unsupported, 2);
}
#[test]
fn preserves_cookie_location_and_does_not_collapse_same_name_parameters() {
let document = r#"
openapi: 3.0.3
info: { title: Cookie parameters }
paths:
/sessions:
get:
operationId: listSessions
parameters:
- name: token
in: query
schema: { type: string }
- name: token
in: cookie
required: true
schema: { type: string }
responses:
'200': { description: OK }
"#;
let preview = preview_document(document).unwrap();
let candidate = &preview.groups[0].operations[0];
let cookie_and_query_rules = candidate
.draft
.input_mapping
.rules
.iter()
.filter(|rule| {
rule.target == "$.request.query.token" || rule.target == "$.request.cookies.token"
})
.collect::<Vec<_>>();
assert_eq!(cookie_and_query_rules.len(), 2);
assert_ne!(
cookie_and_query_rules[0].source,
cookie_and_query_rules[1].source
);
let ir = normalize_verified_document(
document,
SourceDigest::parse("0".repeat(64)).unwrap(),
&NormalizationConfig::default(),
)
.unwrap();
let operation = &ir.operations[0];
assert_eq!(operation.parameters.len(), 2);
assert!(operation.parameters.iter().any(|parameter| {
parameter.name == "token"
&& parameter.location == crank_import::rest::RestParameterLocation::Query
}));
assert!(operation.parameters.iter().any(|parameter| {
parameter.name == "token"
&& parameter.location == crank_import::rest::RestParameterLocation::Cookie
&& parameter.required
}));
}
#[test]
fn preserves_all_supported_request_media_variants() {
let document = r#"
openapi: 3.0.3
info: { title: Request media variants }
paths:
/imports:
post:
operationId: importPayload
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [json_name]
properties: { json_name: { type: string } }
application/x-www-form-urlencoded:
schema:
type: object
required: [form_name]
properties: { form_name: { type: string } }
multipart/form-data:
schema:
type: object
required: [file]
properties: { file: { type: string, format: binary } }
encoding:
file: { contentType: "image/png, image/jpeg" }
responses:
'202': { description: Accepted }
"#;
let ir = normalize_verified_document(
document,
SourceDigest::parse("0".repeat(64)).unwrap(),
&NormalizationConfig::default(),
)
.unwrap();
let variants = &ir.operations[0].request_body_variants;
let content_types = variants
.iter()
.map(|variant| variant.content_type.as_str())
.collect::<Vec<_>>();
assert_eq!(
content_types,
vec![
"application/json",
"application/x-www-form-urlencoded",
"multipart/form-data"
]
);
assert!(variants.iter().all(|variant| variant.required));
assert!(variants.iter().all(|variant| variant.schema.is_some()));
assert_eq!(
variants[2].multipart_field_mime_types.get("file"),
Some(&vec!["image/png".to_owned(), "image/jpeg".to_owned()])
);
let preview = preview_document(document).unwrap();
let input_schema = &preview.groups[0].operations[0].draft.input_schema;
assert_eq!(input_schema.kind, SchemaKind::Oneof);
assert_eq!(input_schema.variants.len(), 3);
assert!(
input_schema
.validate_shape(&json!({
"content_type": "application/json",
"body": {"json_name": "Ada"}
}))
.is_ok()
);
assert!(
input_schema
.validate_shape(&json!({
"content_type": "application/json",
"body": {"form_name": "Ada"}
}))
.is_err()
);
assert!(
input_schema
.validate_shape(&json!({
"content_type": "multipart/form-data",
"body": {"file": {"data_base64": "SGVsbG8="}}
}))
.is_ok()
);
assert!(
input_schema
.validate_shape(&json!({
"content_type": "multipart/form-data",
"body": {"file": {"data_base64": "SGVsbG8=", "extra": true}}
}))
.is_err()
);
assert!(
input_schema
.validate_shape(&json!({
"content_type": "multipart/form-data",
"body": {}
}))
.is_err()
);
assert_eq!(
preview.groups[0].operations[0]
.draft
.target
.multipart_field_mime_types
.get("multipart/form-data")
.and_then(|fields| fields.get("file")),
Some(&vec!["image/png".to_owned(), "image/jpeg".to_owned()])
);
}
#[test]
fn optional_variant_pair_preserves_omission_and_nullable_null_in_mapping() {
let document = r#"
openapi: 3.0.3
info: { title: Optional variants }
paths:
/events:
post:
operationId: createEvent
requestBody:
required: false
content:
application/json:
schema: { type: object, nullable: true, properties: { name: { type: string } } }
application/x-www-form-urlencoded:
schema: { type: object, properties: { title: { type: string } } }
responses: { '204': { description: Empty } }
"#;
let preview = preview_document(document).unwrap();
let draft = &preview.groups[0].operations[0].draft;
assert!(draft.input_schema.validate_shape(&json!({})).is_ok());
assert!(
draft
.input_schema
.validate_shape(&json!({"content_type": "application/json", "body": null}))
.is_ok()
);
assert!(
draft
.input_schema
.validate_shape(
&json!({"content_type": "application/x-www-form-urlencoded", "body": null})
)
.is_err()
);
// Omission is represented by its own closed branch, so an incomplete
// selector/body pair is rejected by the portable schema as well.
assert!(
draft
.input_schema
.validate_shape(&json!({"content_type": "application/json"}))
.is_err()
);
let mapped = draft
.input_mapping
.apply(&json!({"mcp": {"content_type": "application/json", "body": null}}))
.unwrap();
assert_eq!(mapped["request"]["body"], json!(null));
assert_eq!(mapped["request"]["body_content_type"], "application/json");
}
#[test]
fn preserves_multiple_success_responses_and_explicit_no_content() {
let document = r#"
openapi: 3.0.3
info: { title: Response variants }
paths:
/items:
get:
operationId: getItems
responses:
'200':
description: JSON result
content:
application/json:
schema: { type: object, properties: { id: { type: string } } }
'204': { description: No content }
'206':
description: Partial result
content:
application/json:
schema: { type: array, items: { type: string } }
"#;
let preview = preview_document(document).unwrap();
let output_schema = &preview.groups[0].operations[0].draft.output_schema;
let response_contract = &preview.groups[0].operations[0]
.draft
.target
.response_contract;
assert_eq!(output_schema.kind, SchemaKind::Oneof);
assert_eq!(output_schema.variants.len(), 3);
assert_eq!(
response_contract
.iter()
.map(|descriptor| (descriptor.status_code, descriptor.media_type.as_deref()))
.collect::<Vec<_>>(),
vec![
(200, Some("application/json")),
(204, None),
(206, Some("application/json")),
]
);
assert!(
output_schema
.variants
.iter()
.any(|variant| variant.kind == SchemaKind::Null)
);
let ir = normalize_verified_document(
document,
SourceDigest::parse("0".repeat(64)).unwrap(),
&NormalizationConfig::default(),
)
.unwrap();
let variants = &ir.operations[0].response_variants;
assert_eq!(
variants
.iter()
.map(|variant| variant.status_code)
.collect::<Vec<_>>(),
vec![200, 204, 206]
);
assert_eq!(
variants[0].content_type.as_deref(),
Some("application/json")
);
assert!(variants[0].schema.is_some());
assert_eq!(variants[1].content_type, None);
assert!(variants[1].schema.is_none());
assert_eq!(
variants[2].content_type.as_deref(),
Some("application/json")
);
assert!(variants[2].schema.is_some());
}
}