feat(import): preserve supported HTTP contracts
This commit is contained in:
1 parent
083974c27f
commit
f8ee7c9bfe
87 files changed
+7496
-534
No files matched your search
@@ -0,0 +1,25 @@
|
||||
use crank_core::HttpMethod;
|
||||
|
||||
use crate::rest::model::{ImportFinding, ImportFindingSeverity};
|
||||
|
||||
pub(super) fn from_lower(value: &str) -> Option<HttpMethod> {
|
||||
match value {
|
||||
"get" => Some(HttpMethod::Get),
|
||||
"post" => Some(HttpMethod::Post),
|
||||
"put" => Some(HttpMethod::Put),
|
||||
"patch" => Some(HttpMethod::Patch),
|
||||
"delete" => Some(HttpMethod::Delete),
|
||||
"head" => Some(HttpMethod::Head),
|
||||
"options" => Some(HttpMethod::Options),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn invalid_path_item() -> ImportFinding {
|
||||
ImportFinding {
|
||||
code: "invalid_path_item".to_owned(),
|
||||
severity: ImportFindingSeverity::Error,
|
||||
message: "Path Item имеет неверную структуру и не был интерпретирован.".to_owned(),
|
||||
operation_key: None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// Frozen pre-v4 projection for historical legacy-v1 jobs.
|
||||
use crank_mapping::{MappingRule, MappingSet};
|
||||
use crank_schema::{Schema, SchemaKind};
|
||||
|
||||
use crate::rest::model::{RestImportParameter, RestParameterLocation};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct BodyFieldMapping {
|
||||
pub input_name: String,
|
||||
pub body_path: String,
|
||||
pub required: bool,
|
||||
}
|
||||
|
||||
pub fn input_mapping(
|
||||
parameters: &[RestImportParameter],
|
||||
body_fields: &[BodyFieldMapping],
|
||||
) -> MappingSet {
|
||||
let mut rules = Vec::new();
|
||||
for parameter in parameters {
|
||||
let target_root = match parameter.location {
|
||||
RestParameterLocation::Path => "$.request.path",
|
||||
RestParameterLocation::Query => "$.request.query",
|
||||
RestParameterLocation::Header => "$.request.headers",
|
||||
RestParameterLocation::Cookie => "$.request.cookies",
|
||||
};
|
||||
rules.push(MappingRule {
|
||||
source: format!("$.mcp.{}", parameter.name),
|
||||
target: format!("{target_root}.{}", parameter.name),
|
||||
required: parameter.required,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
});
|
||||
}
|
||||
for field in body_fields {
|
||||
let target = if field.body_path.is_empty() {
|
||||
"$.request.body".to_owned()
|
||||
} else {
|
||||
format!("$.request.body.{}", field.body_path)
|
||||
};
|
||||
rules.push(MappingRule {
|
||||
source: format!("$.mcp.{}", field.input_name),
|
||||
target,
|
||||
required: field.required,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
});
|
||||
}
|
||||
MappingSet { rules }
|
||||
}
|
||||
|
||||
pub fn output_mapping(output_schema: &Schema) -> MappingSet {
|
||||
let mut rules = Vec::new();
|
||||
if output_schema.kind == SchemaKind::Object && !output_schema.fields.is_empty() {
|
||||
for (name, field) in &output_schema.fields {
|
||||
rules.push(MappingRule {
|
||||
source: format!("$.response.body.{name}"),
|
||||
target: format!("$.output.{name}"),
|
||||
required: field.required,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
rules.push(MappingRule {
|
||||
source: "$.response.body".to_owned(),
|
||||
target: "$.output".to_owned(),
|
||||
required: true,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
});
|
||||
}
|
||||
MappingSet { rules }
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
// Frozen pre-v4 projection for historical legacy-v1 jobs.
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use crank_core::{
|
||||
ExecutionConfig, HttpMethod, OperationSafetyClass, OperationSafetyPolicy, Protocol, RestTarget,
|
||||
ToolDescription, ToolExample, WizardState,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::rest::{
|
||||
legacy_mapping::{BodyFieldMapping, input_mapping, output_mapping},
|
||||
legacy_schema::{any_object, field_count, object_with_fields, schema_from_openapi},
|
||||
model::{
|
||||
ImportOperationCandidate, RestImportCandidate, RestImportOperation, RestParameterLocation,
|
||||
},
|
||||
naming::{fallback_operation_seed, title_from_name, unique_name},
|
||||
recommendations::{candidate_recommendations, operation_recommendations},
|
||||
};
|
||||
|
||||
pub fn candidate_from_operation(
|
||||
operation: &RestImportOperation,
|
||||
document_servers: &[String],
|
||||
used_names: &mut BTreeSet<String>,
|
||||
) -> ImportOperationCandidate {
|
||||
let method_name = method_as_str(operation.method);
|
||||
let seed = operation
|
||||
.operation_id
|
||||
.as_deref()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
.unwrap_or_else(|| fallback_operation_seed(method_name, &operation.path));
|
||||
let name = unique_name(&seed, used_names);
|
||||
let display_name = operation
|
||||
.summary
|
||||
.as_deref()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
.unwrap_or_else(|| title_from_name(&name));
|
||||
let description = operation
|
||||
.description
|
||||
.as_deref()
|
||||
.or(operation.summary.as_deref())
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
.unwrap_or_else(|| format!("Выполняет {method_name} {}", operation.path));
|
||||
let category = operation
|
||||
.tags
|
||||
.first()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "imported".to_owned());
|
||||
let server_urls = if operation.servers.is_empty() {
|
||||
document_servers.to_vec()
|
||||
} else {
|
||||
operation.servers.clone()
|
||||
};
|
||||
let base_url = server_urls.first().cloned().unwrap_or_default();
|
||||
let mut input_fields = BTreeMap::new();
|
||||
let mut used_input_field_names = BTreeSet::new();
|
||||
for parameter in &operation.parameters {
|
||||
used_input_field_names.insert(parameter.name.clone());
|
||||
input_fields.insert(
|
||||
parameter.name.clone(),
|
||||
schema_from_openapi(
|
||||
parameter.schema.as_ref(),
|
||||
parameter.required || parameter.location == RestParameterLocation::Path,
|
||||
parameter.description.clone(),
|
||||
),
|
||||
);
|
||||
}
|
||||
let body_fields = body_input_fields(
|
||||
operation.request_body_schema.as_ref(),
|
||||
&mut used_input_field_names,
|
||||
&mut input_fields,
|
||||
);
|
||||
let input_schema = object_with_fields(
|
||||
Some("Входные параметры MCP-инструмента".to_owned()),
|
||||
input_fields,
|
||||
);
|
||||
let output_schema = operation
|
||||
.response_schema
|
||||
.as_ref()
|
||||
.map(|schema| schema_from_openapi(Some(schema), true, Some("Ответ API".to_owned())))
|
||||
.unwrap_or_else(|| any_object(Some("Ответ API".to_owned())));
|
||||
let input_mapping = input_mapping(&operation.parameters, &body_fields);
|
||||
let output_mapping = output_mapping(&output_schema);
|
||||
let mut findings = operation_recommendations(operation);
|
||||
findings.extend(candidate_recommendations(
|
||||
operation,
|
||||
&name,
|
||||
&description,
|
||||
&input_schema,
|
||||
&output_schema,
|
||||
));
|
||||
|
||||
let draft = RestImportCandidate {
|
||||
name: name.clone(),
|
||||
display_name: display_name.clone(),
|
||||
category: category.clone(),
|
||||
target: RestTarget {
|
||||
base_url,
|
||||
method: operation.method,
|
||||
path_template: operation.path.clone(),
|
||||
static_headers: BTreeMap::new(),
|
||||
request_contract: None,
|
||||
response_contract: Vec::new(),
|
||||
multipart_field_mime_types: BTreeMap::new(),
|
||||
},
|
||||
input_schema: input_schema.clone(),
|
||||
output_schema: output_schema.clone(),
|
||||
input_mapping,
|
||||
output_mapping,
|
||||
tool_description: ToolDescription {
|
||||
title: display_name.clone(),
|
||||
description: description.clone(),
|
||||
tags: operation.tags.clone(),
|
||||
examples: vec![ToolExample { input: json!({}) }],
|
||||
},
|
||||
wizard_state: Some(WizardState {
|
||||
input_sample: None,
|
||||
output_sample: None,
|
||||
test_input: None,
|
||||
import_findings: Vec::new(),
|
||||
}),
|
||||
};
|
||||
|
||||
ImportOperationCandidate {
|
||||
key: operation.key.clone(),
|
||||
method: operation.method,
|
||||
path: operation.path.clone(),
|
||||
operation_id: operation.operation_id.clone(),
|
||||
suggested_name: name,
|
||||
suggested_display_name: display_name,
|
||||
description,
|
||||
category,
|
||||
input_fields: field_count(&input_schema),
|
||||
output_fields: field_count(&output_schema),
|
||||
server_urls,
|
||||
findings,
|
||||
draft,
|
||||
}
|
||||
}
|
||||
|
||||
fn body_input_fields(
|
||||
request_body_schema: Option<&serde_json::Value>,
|
||||
used_names: &mut BTreeSet<String>,
|
||||
input_fields: &mut BTreeMap<String, crank_schema::Schema>,
|
||||
) -> Vec<BodyFieldMapping> {
|
||||
let Some(request_body_schema) = request_body_schema else {
|
||||
return Vec::new();
|
||||
};
|
||||
let body_schema = schema_from_openapi(
|
||||
Some(request_body_schema),
|
||||
true,
|
||||
Some("Тело запроса".to_owned()),
|
||||
);
|
||||
if body_schema.kind != crank_schema::SchemaKind::Object || body_schema.fields.is_empty() {
|
||||
let input_name = unique_body_input_name("body", used_names);
|
||||
input_fields.insert(input_name.clone(), body_schema);
|
||||
return vec![BodyFieldMapping {
|
||||
input_name,
|
||||
body_path: String::new(),
|
||||
required: true,
|
||||
}];
|
||||
}
|
||||
|
||||
let mut mappings = Vec::new();
|
||||
for (field_name, field_schema) in body_schema.fields {
|
||||
let input_name = unique_body_input_name(&field_name, used_names);
|
||||
mappings.push(BodyFieldMapping {
|
||||
input_name: input_name.clone(),
|
||||
body_path: field_name,
|
||||
required: field_schema.required,
|
||||
});
|
||||
input_fields.insert(input_name, field_schema);
|
||||
}
|
||||
mappings
|
||||
}
|
||||
|
||||
fn unique_body_input_name(name: &str, used_names: &mut BTreeSet<String>) -> String {
|
||||
if used_names.insert(name.to_owned()) {
|
||||
return name.to_owned();
|
||||
}
|
||||
let prefixed = format!("body_{name}");
|
||||
if used_names.insert(prefixed.clone()) {
|
||||
return prefixed;
|
||||
}
|
||||
for index in 2.. {
|
||||
let candidate = format!("body_{name}_{index}");
|
||||
if used_names.insert(candidate.clone()) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
fn method_as_str(method: HttpMethod) -> &'static str {
|
||||
match method {
|
||||
HttpMethod::Get => "GET",
|
||||
HttpMethod::Head => "HEAD",
|
||||
HttpMethod::Options => "OPTIONS",
|
||||
HttpMethod::Post => "POST",
|
||||
HttpMethod::Put => "PUT",
|
||||
HttpMethod::Patch => "PATCH",
|
||||
HttpMethod::Delete => "DELETE",
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn safety_for_method(method: HttpMethod) -> OperationSafetyPolicy {
|
||||
let class = match method {
|
||||
HttpMethod::Get | HttpMethod::Head | HttpMethod::Options => OperationSafetyClass::Read,
|
||||
HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch => OperationSafetyClass::Write,
|
||||
HttpMethod::Delete => OperationSafetyClass::Destructive,
|
||||
};
|
||||
OperationSafetyPolicy {
|
||||
class,
|
||||
confirmation: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn default_execution_config() -> ExecutionConfig {
|
||||
ExecutionConfig {
|
||||
timeout_ms: 10_000,
|
||||
retry_policy: None,
|
||||
response_cache: None,
|
||||
idempotency: None,
|
||||
safety: None,
|
||||
approval_policy: None,
|
||||
auth_profile_ref: None,
|
||||
headers: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn _protocol() -> Protocol {
|
||||
Protocol::Rest
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
// Frozen pre-v4 projection for historical legacy-v1 jobs.
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crank_schema::{Schema, SchemaKind};
|
||||
use serde_json::Value;
|
||||
|
||||
pub fn any_object(description: Option<String>) -> Schema {
|
||||
Schema {
|
||||
format: None,
|
||||
kind: SchemaKind::Object,
|
||||
description,
|
||||
required: true,
|
||||
nullable: false,
|
||||
default_value: None,
|
||||
fields: BTreeMap::new(),
|
||||
items: None,
|
||||
enum_values: Vec::new(),
|
||||
variants: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn field_count(schema: &Schema) -> usize {
|
||||
match schema.kind {
|
||||
SchemaKind::Object => schema.fields.len(),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn schema_from_openapi(
|
||||
value: Option<&Value>,
|
||||
required: bool,
|
||||
description: Option<String>,
|
||||
) -> Schema {
|
||||
let Some(value) = value else {
|
||||
return primitive(SchemaKind::String, required, description);
|
||||
};
|
||||
// Only v3 NormalizedIR emits the private marker. Pending legacy-v1 jobs
|
||||
// retain their historical first-branch behavior, while modern oneOf/anyOf
|
||||
// is projected losslessly through crank-schema's existing Oneof shape.
|
||||
if value
|
||||
.get("x-crank-lossless-composition")
|
||||
.and_then(Value::as_bool)
|
||||
== Some(true)
|
||||
&& let Some(items) = value
|
||||
.get("oneOf")
|
||||
.or_else(|| value.get("anyOf"))
|
||||
.and_then(Value::as_array)
|
||||
{
|
||||
return Schema {
|
||||
format: None,
|
||||
kind: SchemaKind::Oneof,
|
||||
description: description.or_else(|| text(value, "description")),
|
||||
required,
|
||||
nullable: nullable(value),
|
||||
default_value: value.get("default").cloned(),
|
||||
fields: BTreeMap::new(),
|
||||
items: None,
|
||||
enum_values: Vec::new(),
|
||||
variants: items
|
||||
.iter()
|
||||
.map(|item| schema_from_openapi(Some(item), true, None))
|
||||
.collect(),
|
||||
};
|
||||
}
|
||||
let resolved = collapse_composition(value);
|
||||
|
||||
if let Some(values) = resolved.get("enum").and_then(Value::as_array) {
|
||||
let enum_values = values
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(ToOwned::to_owned)
|
||||
.collect::<Vec<_>>();
|
||||
if !enum_values.is_empty() {
|
||||
return Schema {
|
||||
format: None,
|
||||
kind: SchemaKind::Enum,
|
||||
description: description.or_else(|| text(&resolved, "description")),
|
||||
required,
|
||||
nullable: nullable(&resolved),
|
||||
default_value: resolved.get("default").cloned(),
|
||||
fields: BTreeMap::new(),
|
||||
items: None,
|
||||
enum_values,
|
||||
variants: Vec::new(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
match type_name(&resolved).unwrap_or("object") {
|
||||
"object" => object_schema(&resolved, required, description),
|
||||
"array" => Schema {
|
||||
format: None,
|
||||
kind: SchemaKind::Array,
|
||||
description: description.or_else(|| text(&resolved, "description")),
|
||||
required,
|
||||
nullable: nullable(&resolved),
|
||||
default_value: resolved.get("default").cloned(),
|
||||
fields: BTreeMap::new(),
|
||||
items: Some(Box::new(schema_from_openapi(
|
||||
resolved.get("items"),
|
||||
true,
|
||||
None,
|
||||
))),
|
||||
enum_values: Vec::new(),
|
||||
variants: Vec::new(),
|
||||
},
|
||||
"integer" => primitive(
|
||||
SchemaKind::Integer,
|
||||
required,
|
||||
description.or_else(|| text(&resolved, "description")),
|
||||
),
|
||||
"number" => primitive(
|
||||
SchemaKind::Number,
|
||||
required,
|
||||
description.or_else(|| text(&resolved, "description")),
|
||||
),
|
||||
"boolean" => primitive(
|
||||
SchemaKind::Boolean,
|
||||
required,
|
||||
description.or_else(|| text(&resolved, "description")),
|
||||
),
|
||||
"null" => primitive(
|
||||
SchemaKind::Null,
|
||||
required,
|
||||
description.or_else(|| text(&resolved, "description")),
|
||||
),
|
||||
_ => primitive(
|
||||
SchemaKind::String,
|
||||
required,
|
||||
description.or_else(|| text(&resolved, "description")),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn collapse_composition(value: &Value) -> Value {
|
||||
for key in ["allOf", "oneOf", "anyOf"] {
|
||||
if let Some(items) = value.get(key).and_then(Value::as_array)
|
||||
&& let Some(first) = items.first()
|
||||
{
|
||||
return first.clone();
|
||||
}
|
||||
}
|
||||
value.clone()
|
||||
}
|
||||
|
||||
pub fn object_with_fields(description: Option<String>, fields: BTreeMap<String, Schema>) -> Schema {
|
||||
Schema {
|
||||
format: None,
|
||||
kind: SchemaKind::Object,
|
||||
description,
|
||||
required: true,
|
||||
nullable: false,
|
||||
default_value: None,
|
||||
fields,
|
||||
items: None,
|
||||
enum_values: Vec::new(),
|
||||
variants: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn object_schema(value: &Value, required: bool, description: Option<String>) -> Schema {
|
||||
let required_fields = value
|
||||
.get("required")
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.collect::<std::collections::BTreeSet<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut fields = BTreeMap::new();
|
||||
|
||||
if let Some(properties) = value.get("properties").and_then(Value::as_object) {
|
||||
for (name, schema) in properties {
|
||||
fields.insert(
|
||||
name.clone(),
|
||||
schema_from_openapi(
|
||||
Some(schema),
|
||||
required_fields.contains(name.as_str()),
|
||||
text(schema, "description"),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Schema {
|
||||
format: None,
|
||||
kind: SchemaKind::Object,
|
||||
description: description.or_else(|| text(value, "description")),
|
||||
required,
|
||||
nullable: nullable(value),
|
||||
default_value: value.get("default").cloned(),
|
||||
fields,
|
||||
items: None,
|
||||
enum_values: Vec::new(),
|
||||
variants: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn primitive(kind: SchemaKind, required: bool, description: Option<String>) -> Schema {
|
||||
Schema {
|
||||
format: None,
|
||||
kind,
|
||||
description,
|
||||
required,
|
||||
nullable: false,
|
||||
default_value: None,
|
||||
fields: BTreeMap::new(),
|
||||
items: None,
|
||||
enum_values: Vec::new(),
|
||||
variants: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn type_name(value: &Value) -> Option<&str> {
|
||||
match value.get("type") {
|
||||
Some(Value::String(value)) => Some(value.as_str()),
|
||||
Some(Value::Array(values)) => values.iter().find_map(Value::as_str),
|
||||
_ if value.get("properties").is_some() => Some("object"),
|
||||
_ if value.get("items").is_some() => Some("array"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn nullable(value: &Value) -> bool {
|
||||
value
|
||||
.get("nullable")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn text(value: &Value, key: &str) -> Option<String> {
|
||||
value
|
||||
.get(key)
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use crank_mapping::{MappingRule, MappingSet};
|
||||
use crank_schema::{Schema, SchemaKind};
|
||||
|
||||
use crate::rest::model::{RestImportParameter, RestParameterLocation};
|
||||
use crate::rest::model::RestParameterLocation;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct BodyFieldMapping {
|
||||
@@ -10,8 +10,17 @@ pub struct BodyFieldMapping {
|
||||
pub required: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ParameterFieldMapping {
|
||||
pub input_name: String,
|
||||
pub wire_name: String,
|
||||
pub location: RestParameterLocation,
|
||||
pub required: bool,
|
||||
pub default_value: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
pub fn input_mapping(
|
||||
parameters: &[RestImportParameter],
|
||||
parameters: &[ParameterFieldMapping],
|
||||
body_fields: &[BodyFieldMapping],
|
||||
) -> MappingSet {
|
||||
let mut rules = Vec::new();
|
||||
@@ -20,19 +29,25 @@ pub fn input_mapping(
|
||||
RestParameterLocation::Path => "$.request.path",
|
||||
RestParameterLocation::Query => "$.request.query",
|
||||
RestParameterLocation::Header => "$.request.headers",
|
||||
// Cookies travel through a distinct mapping root. Runtime turns
|
||||
// this object into the single wire `Cookie` header at the adapter
|
||||
// boundary; source values cannot inject an arbitrary header.
|
||||
RestParameterLocation::Cookie => "$.request.cookies",
|
||||
};
|
||||
rules.push(MappingRule {
|
||||
source: format!("$.mcp.{}", parameter.name),
|
||||
target: format!("{target_root}.{}", parameter.name),
|
||||
source: format!("$.mcp.{}", parameter.input_name),
|
||||
target: format!("{target_root}.{}", parameter.wire_name),
|
||||
required: parameter.required,
|
||||
default_value: None,
|
||||
default_value: parameter.default_value.clone(),
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
});
|
||||
}
|
||||
for field in body_fields {
|
||||
let target = if field.body_path.is_empty() {
|
||||
let target = if field.body_path == "__content_type" {
|
||||
"$.request.body_content_type".to_owned()
|
||||
} else if field.body_path.is_empty() || field.body_path == "__body" {
|
||||
"$.request.body".to_owned()
|
||||
} else {
|
||||
format!("$.request.body.{}", field.body_path)
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::rest::{
|
||||
model::{ImportFinding, SourceLocation},
|
||||
recommendations::document_finding,
|
||||
};
|
||||
|
||||
pub(super) fn collect_secret_like_examples(
|
||||
value: &Value,
|
||||
pointer: &str,
|
||||
inside_example: bool,
|
||||
findings: &mut Vec<ImportFinding>,
|
||||
locations: &mut Vec<Option<SourceLocation>>,
|
||||
) {
|
||||
match value {
|
||||
Value::Object(fields) => {
|
||||
for (key, child) in fields {
|
||||
let child_pointer = format!(
|
||||
"{pointer}/{}",
|
||||
super::normalize_coverage::escape_pointer(key)
|
||||
);
|
||||
collect_secret_like_examples(
|
||||
child,
|
||||
&child_pointer,
|
||||
inside_example || matches!(key.as_str(), "example" | "examples"),
|
||||
findings,
|
||||
locations,
|
||||
);
|
||||
}
|
||||
}
|
||||
Value::Array(items) => {
|
||||
for (index, child) in items.iter().enumerate() {
|
||||
collect_secret_like_examples(
|
||||
child,
|
||||
&format!("{pointer}/{index}"),
|
||||
inside_example,
|
||||
findings,
|
||||
locations,
|
||||
);
|
||||
}
|
||||
}
|
||||
Value::String(value) if inside_example && looks_secret_like(pointer, value) => {
|
||||
findings.push(document_finding(
|
||||
"secret_like_example",
|
||||
"Example содержит значение, похожее на секрет, и не включается в executable contract.",
|
||||
));
|
||||
locations.push(Some(SourceLocation {
|
||||
pointer: pointer.to_owned(),
|
||||
}));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn looks_secret_like(pointer: &str, value: &str) -> bool {
|
||||
let pointer = pointer.to_ascii_lowercase();
|
||||
let value = value.to_ascii_lowercase();
|
||||
[
|
||||
"token",
|
||||
"secret",
|
||||
"password",
|
||||
"api_key",
|
||||
"apikey",
|
||||
"authorization",
|
||||
]
|
||||
.iter()
|
||||
.any(|marker| pointer.contains(marker) || value.contains(marker))
|
||||
|| value.starts_with("bearer ")
|
||||
|| value.starts_with("sk-")
|
||||
}
|
||||
@@ -1,25 +1,35 @@
|
||||
mod http_methods;
|
||||
mod legacy_mapping;
|
||||
mod legacy_payload;
|
||||
mod legacy_schema;
|
||||
mod mapping;
|
||||
mod metadata_findings;
|
||||
pub mod model;
|
||||
mod naming;
|
||||
mod normalize;
|
||||
mod normalize_coverage;
|
||||
mod normalize_finding_validation;
|
||||
mod normalize_limits;
|
||||
mod normalize_projection;
|
||||
mod normalize_schema;
|
||||
mod openapi3;
|
||||
mod openapi3_findings;
|
||||
mod payload;
|
||||
mod recommendations;
|
||||
mod reference;
|
||||
mod schema;
|
||||
mod swagger2;
|
||||
mod swagger2_findings;
|
||||
|
||||
pub use model::{
|
||||
ExternalDocumentSnapshot, ImportFinding, ImportFindingSeverity, ImportGroupPreview,
|
||||
ImportOperationCandidate, ImportPreview, ImportSourcePreview, NORMALIZER_VERSION,
|
||||
NormalizationConfig, NormalizedFinding, NormalizedIr, NormalizedOperation, NormalizedParameter,
|
||||
NormalizedReference, NormalizedSchema, NormalizedSchemaConstraints, NormalizedSchemaKind,
|
||||
PROJECTION_VERSION, ResolvedReferenceEdge, ResolvedReferenceGraph, ResolvedReferenceNode,
|
||||
RestImportCandidate, RestImportDocument, RestImportOperation, RestImportParameter,
|
||||
RestParameterLocation, SourceDigest, SourceIdentity, SourceLocation, UnresolvedReference,
|
||||
NormalizedReference, NormalizedRequestBodyVariant, NormalizedResponseVariant, NormalizedSchema,
|
||||
NormalizedSchemaConstraints, NormalizedSchemaKind, PROJECTION_VERSION, ResolvedReferenceEdge,
|
||||
ResolvedReferenceGraph, ResolvedReferenceNode, RestImportCandidate, RestImportDocument,
|
||||
RestImportOperation, RestImportParameter, RestParameterLocation, RestRequestBodyVariant,
|
||||
RestResponseVariant, SourceDigest, SourceIdentity, SourceLocation, UnresolvedReference,
|
||||
};
|
||||
pub use normalize::{
|
||||
ImportParseError, external_reference_uris, normalize_verified_bundle,
|
||||
|
||||
@@ -9,8 +9,8 @@ use serde_json::Value;
|
||||
/// The immutable contract used to normalize an OpenAPI source. These names
|
||||
/// deliberately travel with an import job: changing either contract must not
|
||||
/// silently reinterpret a pending preview.
|
||||
pub const NORMALIZER_VERSION: &str = "normalized-ir-v3";
|
||||
pub const PROJECTION_VERSION: &str = "preview-v3";
|
||||
pub const NORMALIZER_VERSION: &str = "normalized-ir-v4";
|
||||
pub const PROJECTION_VERSION: &str = "preview-v4";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
|
||||
pub struct SourceDigest(String);
|
||||
@@ -242,11 +242,35 @@ pub struct NormalizedOperation {
|
||||
pub request_body_schema: Option<NormalizedSchema>,
|
||||
pub response_schema: Option<NormalizedSchema>,
|
||||
#[serde(default)]
|
||||
pub request_body_variants: Vec<NormalizedRequestBodyVariant>,
|
||||
#[serde(default)]
|
||||
pub response_variants: Vec<NormalizedResponseVariant>,
|
||||
#[serde(default)]
|
||||
pub servers: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub findings: Vec<NormalizedFinding>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct NormalizedRequestBodyVariant {
|
||||
pub content_type: String,
|
||||
pub required: bool,
|
||||
pub schema: Option<NormalizedSchema>,
|
||||
/// MIME types allowed for individual multipart fields, keyed by source
|
||||
/// property name. Empty when the source does not constrain a field.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub multipart_field_mime_types: BTreeMap<String, Vec<String>>,
|
||||
pub source_location: SourceLocation,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct NormalizedResponseVariant {
|
||||
pub status_code: u16,
|
||||
pub content_type: Option<String>,
|
||||
pub schema: Option<NormalizedSchema>,
|
||||
pub source_location: SourceLocation,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct NormalizedParameter {
|
||||
pub name: String,
|
||||
@@ -306,9 +330,13 @@ pub enum NormalizedSchemaKind {
|
||||
Object {
|
||||
properties: BTreeMap<String, NormalizedSchema>,
|
||||
required: Vec<String>,
|
||||
nullable: bool,
|
||||
default_value: Option<NormalizedLiteral>,
|
||||
},
|
||||
Array {
|
||||
items: Option<Box<NormalizedSchema>>,
|
||||
nullable: bool,
|
||||
default_value: Option<NormalizedLiteral>,
|
||||
},
|
||||
Reference {
|
||||
reference: UnresolvedReference,
|
||||
@@ -468,11 +496,21 @@ pub struct RestImportOperation {
|
||||
pub request_body_schema: Option<Value>,
|
||||
#[serde(skip)]
|
||||
pub request_body_schema_location: Option<SourceLocation>,
|
||||
/// Every executable request variant. `request_body_schema` remains for
|
||||
/// legacy replay only; modern projection must use this complete list.
|
||||
#[serde(default)]
|
||||
pub request_body_variants: Vec<RestRequestBodyVariant>,
|
||||
pub response_schema: Option<Value>,
|
||||
#[serde(skip)]
|
||||
pub response_schema_location: Option<SourceLocation>,
|
||||
/// All successful response branches, including explicit no-content
|
||||
/// outcomes. The old singular field is retained for legacy-v1 jobs.
|
||||
#[serde(default)]
|
||||
pub response_variants: Vec<RestResponseVariant>,
|
||||
pub servers: Vec<String>,
|
||||
pub findings: Vec<ImportFinding>,
|
||||
#[serde(skip)]
|
||||
pub internal_finding_locations: Vec<SourceLocation>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -488,6 +526,37 @@ pub struct RestImportParameter {
|
||||
pub schema_source_location: Option<SourceLocation>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct RestRequestBodyVariant {
|
||||
pub content_type: String,
|
||||
pub required: bool,
|
||||
pub schema: Option<Value>,
|
||||
/// MIME types from OpenAPI's multipart `encoding.*.contentType`.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub multipart_field_mime_types: BTreeMap<String, Vec<String>>,
|
||||
#[serde(skip, default = "empty_source_location")]
|
||||
pub source_location: SourceLocation,
|
||||
#[serde(skip, default)]
|
||||
pub schema_source_location: Option<SourceLocation>,
|
||||
/// Swagger 2 formData schemas are assembled from independent parameters.
|
||||
/// This keeps each generated property tied to its original parameter.
|
||||
#[serde(skip, default)]
|
||||
pub schema_property_source_locations: BTreeMap<String, SourceLocation>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct RestResponseVariant {
|
||||
pub status_code: u16,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub content_type: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub schema: Option<Value>,
|
||||
#[serde(skip, default = "empty_source_location")]
|
||||
pub source_location: SourceLocation,
|
||||
#[serde(skip, default)]
|
||||
pub schema_source_location: Option<SourceLocation>,
|
||||
}
|
||||
|
||||
fn empty_source_location() -> SourceLocation {
|
||||
SourceLocation {
|
||||
pointer: String::new(),
|
||||
@@ -500,4 +569,5 @@ pub enum RestParameterLocation {
|
||||
Path,
|
||||
Query,
|
||||
Header,
|
||||
Cookie,
|
||||
}
|
||||
@@ -8,10 +8,9 @@ use crate::rest::{
|
||||
CoverageDisposition, CoverageEntry, ExternalDocumentSnapshot, ImportFinding,
|
||||
ImportFindingSeverity, ImportGroupPreview, ImportPreview, ImportSourcePreview,
|
||||
NORMALIZER_VERSION, NormalizationConfig, NormalizedApiMetadata, NormalizedFinding,
|
||||
NormalizedIr, NormalizedLiteral, NormalizedOperation, NormalizedParameter,
|
||||
NormalizedScalarKind, NormalizedSchema, NormalizedSchemaKind, PROJECTION_VERSION,
|
||||
RestImportDocument, RestImportOperation, RestImportParameter, SourceDigest, SourceIdentity,
|
||||
SourceLocation, SourceSyntax,
|
||||
NormalizedIr, NormalizedOperation, NormalizedParameter, NormalizedRequestBodyVariant,
|
||||
NormalizedResponseVariant, NormalizedSchema, NormalizedSchemaKind, PROJECTION_VERSION,
|
||||
RestImportDocument, SourceDigest, SourceIdentity, SourceLocation, SourceSyntax,
|
||||
},
|
||||
openapi3,
|
||||
payload::candidate_from_operation,
|
||||
@@ -139,7 +138,7 @@ pub fn normalize_verified_bundle(
|
||||
let root = resolution.root;
|
||||
validate_value_limits(&root, config)?;
|
||||
|
||||
let parsed = match root.get("openapi").and_then(Value::as_str) {
|
||||
let mut parsed = match root.get("openapi").and_then(Value::as_str) {
|
||||
Some(version) if supported_oas_version(version) => openapi3::parse_document(&root)?,
|
||||
Some(_) => return Err(ImportParseError::UnsupportedDocument),
|
||||
None if root.get("swagger").and_then(Value::as_str) == Some("2.0") => {
|
||||
@@ -147,8 +146,20 @@ pub fn normalize_verified_bundle(
|
||||
}
|
||||
None => return Err(ImportParseError::UnsupportedDocument),
|
||||
};
|
||||
super::metadata_findings::collect_secret_like_examples(
|
||||
&root,
|
||||
"",
|
||||
false,
|
||||
&mut parsed.findings,
|
||||
&mut parsed.internal_finding_locations,
|
||||
);
|
||||
|
||||
if parsed.operations.is_empty() {
|
||||
if parsed.operations.is_empty()
|
||||
&& !parsed
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.code == "unsupported_http_method")
|
||||
{
|
||||
return Err(ImportParseError::NoMethods);
|
||||
}
|
||||
canonicalize(
|
||||
@@ -166,7 +177,7 @@ pub fn preview_from_ir(ir: &NormalizedIr) -> ImportPreview {
|
||||
let operations = ir
|
||||
.operations
|
||||
.iter()
|
||||
.map(legacy_operation_from_normalized)
|
||||
.map(super::normalize_projection::operation_from_normalized)
|
||||
.collect::<Vec<_>>();
|
||||
let findings = ir
|
||||
.findings
|
||||
@@ -178,7 +189,7 @@ pub fn preview_from_ir(ir: &NormalizedIr) -> ImportPreview {
|
||||
operation_key: finding.operation_key.clone(),
|
||||
})
|
||||
.collect();
|
||||
preview_from_operations(&ir.source, operations.iter(), findings)
|
||||
preview_from_operations(&ir.source, operations.iter(), findings, false)
|
||||
}
|
||||
|
||||
fn preview_from_document(document: RestImportDocument) -> ImportPreview {
|
||||
@@ -188,19 +199,28 @@ fn preview_from_document(document: RestImportDocument) -> ImportPreview {
|
||||
title: document.title,
|
||||
servers: document.servers,
|
||||
};
|
||||
preview_from_operations(&source, document.operations.iter(), document.findings)
|
||||
preview_from_operations(&source, document.operations.iter(), document.findings, true)
|
||||
}
|
||||
|
||||
fn preview_from_operations<'a>(
|
||||
source: &ImportSourcePreview,
|
||||
operations: impl Iterator<Item = &'a crate::rest::model::RestImportOperation>,
|
||||
mut findings: Vec<ImportFinding>,
|
||||
legacy: bool,
|
||||
) -> ImportPreview {
|
||||
let mut groups: BTreeMap<String, ImportGroupPreview> = BTreeMap::new();
|
||||
let mut used_names = BTreeSet::new();
|
||||
|
||||
for operation in operations {
|
||||
let candidate = candidate_from_operation(operation, &source.servers, &mut used_names);
|
||||
let candidate = if legacy {
|
||||
super::legacy_payload::candidate_from_operation(
|
||||
operation,
|
||||
&source.servers,
|
||||
&mut used_names,
|
||||
)
|
||||
} else {
|
||||
candidate_from_operation(operation, &source.servers, &mut used_names)
|
||||
};
|
||||
let group_title = operation
|
||||
.tags
|
||||
.first()
|
||||
@@ -379,14 +399,27 @@ fn canonicalize(
|
||||
disposition: CoverageDisposition::Mapped,
|
||||
});
|
||||
}
|
||||
operation_findings.extend(operation.findings.iter().map(|finding| NormalizedFinding {
|
||||
code: finding.code.clone(),
|
||||
severity: finding.severity.clone(),
|
||||
message: finding.message.clone(),
|
||||
construct_id: stable_id.clone(),
|
||||
location: location.clone(),
|
||||
operation_key: Some(operation.key.clone()),
|
||||
}));
|
||||
operation_findings.extend(operation.findings.iter().enumerate().map(
|
||||
|(index, finding)| {
|
||||
let finding_location = operation
|
||||
.internal_finding_locations
|
||||
.get(index)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| location.clone());
|
||||
NormalizedFinding {
|
||||
code: finding.code.clone(),
|
||||
severity: finding.severity.clone(),
|
||||
message: finding.message.clone(),
|
||||
construct_id: if finding_location == location {
|
||||
stable_id.clone()
|
||||
} else {
|
||||
format!("{version}:{}", finding_location.pointer)
|
||||
},
|
||||
location: finding_location,
|
||||
operation_key: Some(operation.key.clone()),
|
||||
}
|
||||
},
|
||||
));
|
||||
let parameters = operation
|
||||
.parameters
|
||||
.into_iter()
|
||||
@@ -465,6 +498,52 @@ fn canonicalize(
|
||||
&mut coverage,
|
||||
)
|
||||
});
|
||||
let request_body_variants = operation
|
||||
.request_body_variants
|
||||
.iter()
|
||||
.map(|variant| NormalizedRequestBodyVariant {
|
||||
content_type: variant.content_type.clone(),
|
||||
required: variant.required,
|
||||
schema: variant.schema.as_ref().map(|schema| {
|
||||
let schema_location = variant
|
||||
.schema_source_location
|
||||
.as_ref()
|
||||
.unwrap_or(&variant.source_location);
|
||||
normalize_coverage::typed_schema_with_property_locations(
|
||||
schema,
|
||||
&schema_location.pointer,
|
||||
&variant.schema_property_source_locations,
|
||||
&mut coverage,
|
||||
)
|
||||
}),
|
||||
multipart_field_mime_types: variant.multipart_field_mime_types.clone(),
|
||||
source_location: variant.source_location.clone(),
|
||||
})
|
||||
.collect();
|
||||
let response_variants = operation
|
||||
.response_variants
|
||||
.iter()
|
||||
.map(|variant| NormalizedResponseVariant {
|
||||
status_code: variant.status_code,
|
||||
content_type: variant.content_type.clone(),
|
||||
schema: variant.schema.as_ref().map(|schema| {
|
||||
let schema_location = variant
|
||||
.schema_source_location
|
||||
.as_ref()
|
||||
.unwrap_or(&variant.source_location);
|
||||
normalize_coverage::typed_schema(
|
||||
schema,
|
||||
&schema_location.pointer,
|
||||
&format!(
|
||||
"{stable_id}:response_variant:{}",
|
||||
normalize_coverage::escape_pointer(&schema_location.pointer)
|
||||
),
|
||||
&mut coverage,
|
||||
)
|
||||
}),
|
||||
source_location: variant.source_location.clone(),
|
||||
})
|
||||
.collect();
|
||||
if normalize_coverage::has_reference_schema(request_body_schema.as_ref())
|
||||
|| normalize_coverage::has_reference_schema(response_schema.as_ref())
|
||||
|| parameters.iter().any(|parameter| {
|
||||
@@ -499,6 +578,8 @@ fn canonicalize(
|
||||
parameters,
|
||||
request_body_schema,
|
||||
response_schema,
|
||||
request_body_variants,
|
||||
response_variants,
|
||||
servers: operation.servers,
|
||||
findings: operation_findings,
|
||||
})
|
||||
@@ -599,6 +680,18 @@ fn canonicalize(
|
||||
.filter_map(|parameter| parameter.schema.as_ref())
|
||||
.chain(operation.request_body_schema.iter())
|
||||
.chain(operation.response_schema.iter())
|
||||
.chain(
|
||||
operation
|
||||
.request_body_variants
|
||||
.iter()
|
||||
.filter_map(|variant| variant.schema.as_ref()),
|
||||
)
|
||||
.chain(
|
||||
operation
|
||||
.response_variants
|
||||
.iter()
|
||||
.filter_map(|variant| variant.schema.as_ref()),
|
||||
)
|
||||
.any(|schema| schema_contains_reference(schema, &reference.location))
|
||||
})
|
||||
})
|
||||
@@ -738,115 +831,13 @@ fn coverage_disposition_rank(disposition: &CoverageDisposition) -> u8 {
|
||||
}
|
||||
}
|
||||
|
||||
fn legacy_operation_from_normalized(operation: &NormalizedOperation) -> RestImportOperation {
|
||||
RestImportOperation {
|
||||
key: operation.key.clone(),
|
||||
method: operation.method,
|
||||
path: operation.path.clone(),
|
||||
operation_id: operation.operation_id.clone(),
|
||||
summary: operation.summary.clone(),
|
||||
description: operation.description.clone(),
|
||||
tags: operation.tags.clone(),
|
||||
parameters: operation
|
||||
.parameters
|
||||
.iter()
|
||||
.map(|parameter| RestImportParameter {
|
||||
name: parameter.name.clone(),
|
||||
location: parameter.location,
|
||||
required: parameter.required,
|
||||
description: parameter.description.clone(),
|
||||
schema: parameter.schema.as_ref().map(legacy_schema_value),
|
||||
source_location: parameter.source_location.clone(),
|
||||
schema_source_location: None,
|
||||
})
|
||||
.collect(),
|
||||
request_body_schema: operation
|
||||
.request_body_schema
|
||||
.as_ref()
|
||||
.map(legacy_schema_value),
|
||||
request_body_schema_location: None,
|
||||
response_schema: operation.response_schema.as_ref().map(legacy_schema_value),
|
||||
response_schema_location: None,
|
||||
servers: operation.servers.clone(),
|
||||
findings: operation
|
||||
.findings
|
||||
.iter()
|
||||
.map(|finding| ImportFinding {
|
||||
code: finding.code.clone(),
|
||||
severity: finding.severity.clone(),
|
||||
message: finding.message.clone(),
|
||||
operation_key: finding.operation_key.clone(),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn legacy_schema_value(schema: &NormalizedSchema) -> Value {
|
||||
let mut value = match &schema.kind {
|
||||
NormalizedSchemaKind::Reference { reference } => serde_json::json!({"$ref": reference.uri}),
|
||||
NormalizedSchemaKind::Composition { operator, variants } => {
|
||||
serde_json::json!({
|
||||
operator: variants.iter().map(legacy_schema_value).collect::<Vec<_>>(),
|
||||
"x-crank-lossless-composition": true,
|
||||
})
|
||||
}
|
||||
NormalizedSchemaKind::Object {
|
||||
properties,
|
||||
required,
|
||||
} => {
|
||||
serde_json::json!({"type":"object", "properties": properties.iter().map(|(name, schema)| (name.clone(), legacy_schema_value(schema))).collect::<serde_json::Map<_, _>>(), "required": required})
|
||||
}
|
||||
NormalizedSchemaKind::Array { items } => {
|
||||
let mut value = serde_json::json!({"type":"array"});
|
||||
if let Some(items) = items {
|
||||
value["items"] = legacy_schema_value(items);
|
||||
}
|
||||
value
|
||||
}
|
||||
NormalizedSchemaKind::Scalar {
|
||||
scalar_type,
|
||||
format,
|
||||
nullable,
|
||||
default_value,
|
||||
enum_values,
|
||||
} => {
|
||||
let scalar_type = match scalar_type {
|
||||
NormalizedScalarKind::String => "string",
|
||||
NormalizedScalarKind::Integer => "integer",
|
||||
NormalizedScalarKind::Number => "number",
|
||||
NormalizedScalarKind::Boolean => "boolean",
|
||||
NormalizedScalarKind::Null => "null",
|
||||
};
|
||||
serde_json::json!({"type":scalar_type, "format":format, "nullable":nullable, "default":default_value.as_ref().map(legacy_literal_value), "enum":enum_values.iter().map(legacy_literal_value).collect::<Vec<_>>()})
|
||||
}
|
||||
NormalizedSchemaKind::Unknown => serde_json::json!({}),
|
||||
};
|
||||
if let Some(description) = &schema.description {
|
||||
value["description"] = Value::String(description.clone());
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
fn legacy_literal_value(value: &NormalizedLiteral) -> Value {
|
||||
match value {
|
||||
NormalizedLiteral::String(value) => Value::String(value.clone()),
|
||||
NormalizedLiteral::Integer(value) => Value::Number((*value).into()),
|
||||
NormalizedLiteral::Unsigned(value) => Value::Number((*value).into()),
|
||||
NormalizedLiteral::Number(value) => serde_json::Number::from_f64(*value)
|
||||
.map(Value::Number)
|
||||
.unwrap_or(Value::Null),
|
||||
NormalizedLiteral::Boolean(value) => Value::Bool(*value),
|
||||
NormalizedLiteral::Null => Value::Null,
|
||||
}
|
||||
}
|
||||
|
||||
fn schema_contains_reference(schema: &NormalizedSchema, location: &SourceLocation) -> bool {
|
||||
match &schema.kind {
|
||||
NormalizedSchemaKind::Reference { reference } => reference.location == *location,
|
||||
NormalizedSchemaKind::Object { properties, .. } => properties
|
||||
.values()
|
||||
.any(|schema| schema_contains_reference(schema, location)),
|
||||
NormalizedSchemaKind::Array { items } => items
|
||||
NormalizedSchemaKind::Array { items, .. } => items
|
||||
.as_deref()
|
||||
.is_some_and(|schema| schema_contains_reference(schema, location)),
|
||||
NormalizedSchemaKind::Composition { variants, .. } => variants
|
||||
@@ -908,6 +899,8 @@ fn method_name(method: crank_core::HttpMethod) -> &'static str {
|
||||
crank_core::HttpMethod::Put => "PUT",
|
||||
crank_core::HttpMethod::Patch => "PATCH",
|
||||
crank_core::HttpMethod::Delete => "DELETE",
|
||||
crank_core::HttpMethod::Head => "HEAD",
|
||||
crank_core::HttpMethod::Options => "OPTIONS",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -918,6 +911,8 @@ fn method_rank(method: crank_core::HttpMethod) -> u8 {
|
||||
crank_core::HttpMethod::Put => 2,
|
||||
crank_core::HttpMethod::Patch => 3,
|
||||
crank_core::HttpMethod::Delete => 4,
|
||||
crank_core::HttpMethod::Head => 5,
|
||||
crank_core::HttpMethod::Options => 6,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,9 @@ use crate::rest::model::{
|
||||
|
||||
use super::ImportParseError;
|
||||
|
||||
pub(super) use super::normalize_schema::{has_reference_schema, typed_schema};
|
||||
pub(super) use super::normalize_schema::{
|
||||
has_reference_schema, typed_schema, typed_schema_with_property_locations,
|
||||
};
|
||||
|
||||
pub(super) fn validate_coverage(ir: &NormalizedIr) -> Result<(), ImportParseError> {
|
||||
if ir.normalizer_version != NORMALIZER_VERSION || ir.projection_version != PROJECTION_VERSION {
|
||||
@@ -92,6 +94,19 @@ pub(super) fn validate_coverage(ir: &NormalizedIr) -> Result<(), ImportParseErro
|
||||
.flat_map(|operation| &operation.findings),
|
||||
)
|
||||
.collect::<Vec<_>>();
|
||||
for finding in &findings {
|
||||
if super::normalize_finding_validation::matches_source(finding, ir, &source_nodes)
|
||||
&& finding.construct_id == format!("{version}:{}", finding.location.pointer)
|
||||
{
|
||||
insert_real_expected(
|
||||
&mut expected,
|
||||
&source_nodes,
|
||||
finding.construct_id.clone(),
|
||||
finding.location.clone(),
|
||||
CoverageDisposition::Finding,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
for finding in &findings {
|
||||
let Some(target) = expected.get(&finding.construct_id) else {
|
||||
return Err(ImportParseError::InvalidDocument);
|
||||
@@ -342,6 +357,9 @@ fn openapi_servers(
|
||||
let CanonicalSourceValue::String(url) = &fields.get("url")?.value else {
|
||||
return None;
|
||||
};
|
||||
if !super::openapi3_findings::valid_http_server_url(url) {
|
||||
return None;
|
||||
}
|
||||
Some((url.trim_end_matches('/').to_owned(), item.location.clone()))
|
||||
})
|
||||
.unzip()
|
||||
@@ -413,6 +431,8 @@ fn method_rank(method: crank_core::HttpMethod) -> u8 {
|
||||
crank_core::HttpMethod::Put => 2,
|
||||
crank_core::HttpMethod::Patch => 3,
|
||||
crank_core::HttpMethod::Delete => 4,
|
||||
crank_core::HttpMethod::Head => 5,
|
||||
crank_core::HttpMethod::Options => 6,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -423,6 +443,8 @@ fn method_name(method: crank_core::HttpMethod) -> &'static str {
|
||||
crank_core::HttpMethod::Put => "put",
|
||||
crank_core::HttpMethod::Patch => "patch",
|
||||
crank_core::HttpMethod::Delete => "delete",
|
||||
crank_core::HttpMethod::Head => "head",
|
||||
crank_core::HttpMethod::Options => "options",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -518,6 +540,16 @@ fn collect_operation_expectations(
|
||||
if let Some(schema) = &operation.response_schema {
|
||||
collect_schema_expectations(schema, source_nodes, expected)?;
|
||||
}
|
||||
for variant in &operation.request_body_variants {
|
||||
if let Some(schema) = &variant.schema {
|
||||
collect_schema_expectations(schema, source_nodes, expected)?;
|
||||
}
|
||||
}
|
||||
for variant in &operation.response_variants {
|
||||
if let Some(schema) = &variant.schema {
|
||||
collect_schema_expectations(schema, source_nodes, expected)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -578,7 +610,9 @@ fn collect_schema_expectations(
|
||||
collect_schema_expectations(child, source_nodes, expected)?;
|
||||
}
|
||||
}
|
||||
NormalizedSchemaKind::Array { items: Some(child) } => {
|
||||
NormalizedSchemaKind::Array {
|
||||
items: Some(child), ..
|
||||
} => {
|
||||
collect_schema_expectations(child, source_nodes, expected)?;
|
||||
}
|
||||
NormalizedSchemaKind::Composition { variants, .. } => {
|
||||
@@ -639,12 +673,27 @@ fn collect_finding_only_expectations(
|
||||
expected,
|
||||
)?;
|
||||
}
|
||||
for method in ["head", "options", "trace", "connect"] {
|
||||
for method in methods.keys().filter(|method| {
|
||||
let non_method = if ir.source.format == "openapi" {
|
||||
matches!(
|
||||
method.as_str(),
|
||||
"$ref" | "summary" | "description" | "servers" | "parameters"
|
||||
)
|
||||
} else {
|
||||
matches!(method.as_str(), "$ref" | "parameters")
|
||||
};
|
||||
!method.starts_with("x-")
|
||||
&& !non_method
|
||||
&& !matches!(
|
||||
method.as_str(),
|
||||
"get" | "post" | "put" | "patch" | "delete" | "head" | "options"
|
||||
)
|
||||
}) {
|
||||
if let Some(node) = methods.get(method) {
|
||||
insert_finding_pointer(version, node, expected)?;
|
||||
}
|
||||
}
|
||||
for method in ["get", "post", "put", "patch", "delete"] {
|
||||
for method in ["get", "post", "put", "patch", "delete", "head", "options"] {
|
||||
if let Some(node) = methods.get(method) {
|
||||
match &node.value {
|
||||
CanonicalSourceValue::Object(operation) => {
|
||||
@@ -682,13 +731,16 @@ fn collect_invalid_openapi_server_findings(
|
||||
return Ok(());
|
||||
};
|
||||
for server in items {
|
||||
let valid = matches!(
|
||||
&server.value,
|
||||
CanonicalSourceValue::Object(fields)
|
||||
if matches!(fields.get("url").map(|node| &node.value), Some(CanonicalSourceValue::String(_)))
|
||||
);
|
||||
if !valid {
|
||||
insert_finding_pointer(version, server, expected)?;
|
||||
match &server.value {
|
||||
CanonicalSourceValue::Object(fields) => match fields.get("url") {
|
||||
Some(url) if matches!(&url.value, CanonicalSourceValue::String(value) if !super::openapi3_findings::valid_http_server_url(value)) =>
|
||||
{
|
||||
insert_finding_pointer(version, url, expected)?;
|
||||
}
|
||||
Some(url) if matches!(url.value, CanonicalSourceValue::String(_)) => {}
|
||||
_ => insert_finding_pointer(version, server, expected)?,
|
||||
},
|
||||
_ => insert_finding_pointer(version, server, expected)?,
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -746,8 +798,11 @@ fn collect_dropped_parameter_findings(
|
||||
return Err(ImportParseError::InvalidDocument);
|
||||
};
|
||||
let supported = match format {
|
||||
"openapi" => matches!(location.as_str(), "path" | "query" | "header"),
|
||||
"swagger" => matches!(location.as_str(), "path" | "query" | "header" | "body"),
|
||||
"openapi" => matches!(location.as_str(), "path" | "query" | "header" | "cookie"),
|
||||
"swagger" => matches!(
|
||||
location.as_str(),
|
||||
"path" | "query" | "header" | "body" | "formData"
|
||||
),
|
||||
_ => false,
|
||||
};
|
||||
if !supported {
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::rest::model::{
|
||||
CanonicalSourceNode, CanonicalSourceValue, ImportFindingSeverity, NormalizedFinding,
|
||||
NormalizedIr,
|
||||
};
|
||||
|
||||
pub(super) fn matches_source(
|
||||
finding: &NormalizedFinding,
|
||||
ir: &NormalizedIr,
|
||||
nodes: &BTreeMap<String, &CanonicalSourceNode>,
|
||||
) -> bool {
|
||||
let pointer = finding.location.pointer.as_str();
|
||||
let Some(node) = nodes.get(pointer).copied() else {
|
||||
return false;
|
||||
};
|
||||
let is_error = finding.severity == ImportFindingSeverity::Error;
|
||||
match finding.code.as_str() {
|
||||
"unsupported_parameter_style" if is_error => parameter_style(pointer, node, nodes),
|
||||
"unsupported_parameter_content" if is_error => pointer.ends_with("/content"),
|
||||
"missing_parameter_schema" if is_error => {
|
||||
matches!(&node.value, CanonicalSourceValue::Object(fields) if !fields.contains_key("schema") && !fields.contains_key("content"))
|
||||
}
|
||||
"unsupported_request_body" if is_error => pointer.ends_with("/requestBody"),
|
||||
"unsupported_request_media_type" | "unsupported_xml_request_media_type" if is_error => {
|
||||
media_from_pointer(pointer).is_some_and(|media| !supported_request_media(&media))
|
||||
}
|
||||
"unsupported_response_media_type" | "unsupported_xml_response_media_type" if is_error => {
|
||||
media_from_pointer(pointer).is_some_and(|media| !supported_response_media(&media))
|
||||
}
|
||||
"unsupported_multipart_encoding" | "unsupported_form_encoding" if is_error => {
|
||||
pointer.contains("/encoding")
|
||||
}
|
||||
"unsupported_form_schema" if is_error => form_schema_shape(pointer, node),
|
||||
"missing_request_media_schema" | "missing_response_media_schema" if is_error => {
|
||||
matches!(&node.value, CanonicalSourceValue::Object(fields) if !fields.contains_key("schema"))
|
||||
}
|
||||
"unsupported_consumes" if is_error => {
|
||||
matches!(&node.value, CanonicalSourceValue::String(media) if !supported_request_media(media))
|
||||
}
|
||||
"unsupported_produces" if is_error => {
|
||||
matches!(&node.value, CanonicalSourceValue::String(media) if !supported_response_media(media))
|
||||
}
|
||||
"path_parameter_not_required" if is_error => {
|
||||
matches!(&node.value, CanonicalSourceValue::Object(fields) if !matches!(fields.get("required").map(|node| &node.value), Some(CanonicalSourceValue::Boolean(true))))
|
||||
}
|
||||
"path_parameter_placeholder_missing" if is_error => ir.operations.iter().any(|operation| {
|
||||
finding.operation_key.as_deref() == Some(operation.key.as_str())
|
||||
&& matches!(&node.value, CanonicalSourceValue::Object(fields) if matches!(fields.get("name").map(|node| &node.value), Some(CanonicalSourceValue::String(name)) if !operation.path.contains(&format!("{{{name}}}"))))
|
||||
}),
|
||||
"unsupported_schema_keyword" if is_error => schema_keyword(pointer, node),
|
||||
"unsupported_schema_enum" if is_error => {
|
||||
pointer.ends_with("/enum")
|
||||
&& matches!(&node.value, CanonicalSourceValue::Array(items) if items.iter().any(|item| !matches!(item.value, CanonicalSourceValue::String(_))))
|
||||
}
|
||||
"secret_like_example" if finding.severity == ImportFindingSeverity::Warning => {
|
||||
pointer.contains("/example") && matches!(&node.value, CanonicalSourceValue::String(value) if secret_like(pointer, value))
|
||||
}
|
||||
"invalid_server" if is_error => invalid_server(pointer, node),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn parameter_style(
|
||||
pointer: &str,
|
||||
node: &CanonicalSourceNode,
|
||||
nodes: &BTreeMap<String, &CanonicalSourceNode>,
|
||||
) -> bool {
|
||||
if pointer.ends_with("/schema") {
|
||||
return compound_parameter(node);
|
||||
}
|
||||
if pointer.ends_with("/collectionFormat") {
|
||||
return true;
|
||||
}
|
||||
if compound_parameter(node) {
|
||||
return true;
|
||||
}
|
||||
let Some((parameter_pointer, field)) = pointer.rsplit_once('/') else {
|
||||
return false;
|
||||
};
|
||||
let location = nodes
|
||||
.get(&format!("{parameter_pointer}/in"))
|
||||
.and_then(|node| match &node.value {
|
||||
CanonicalSourceValue::String(value) => Some(value.as_str()),
|
||||
_ => None,
|
||||
});
|
||||
match (field, &node.value, location) {
|
||||
("style", CanonicalSourceValue::String(style), Some("path" | "header")) => {
|
||||
style != "simple"
|
||||
}
|
||||
("style", CanonicalSourceValue::String(style), Some("query" | "cookie")) => style != "form",
|
||||
("style", _, Some(_)) => true,
|
||||
("explode", CanonicalSourceValue::Boolean(value), Some("path" | "header")) => *value,
|
||||
("explode", CanonicalSourceValue::Boolean(value), Some("query" | "cookie")) => !*value,
|
||||
("explode", _, Some(_)) => true,
|
||||
("allowReserved", value, _) => !matches!(value, CanonicalSourceValue::Boolean(false)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn compound_parameter(node: &CanonicalSourceNode) -> bool {
|
||||
matches!(&node.value, CanonicalSourceValue::Object(fields) if matches!(fields.get("type").map(|node| &node.value), Some(CanonicalSourceValue::String(value)) if matches!(value.as_str(), "array" | "object")))
|
||||
}
|
||||
|
||||
fn schema_keyword(pointer: &str, node: &CanonicalSourceNode) -> bool {
|
||||
const UNSUPPORTED: &[&str] = &[
|
||||
"additionalProperties",
|
||||
"unevaluatedProperties",
|
||||
"prefixItems",
|
||||
"contains",
|
||||
"dependentSchemas",
|
||||
"if",
|
||||
"then",
|
||||
"else",
|
||||
"not",
|
||||
"propertyNames",
|
||||
"minimum",
|
||||
"maximum",
|
||||
"exclusiveMinimum",
|
||||
"exclusiveMaximum",
|
||||
"minLength",
|
||||
"maxLength",
|
||||
"pattern",
|
||||
"minItems",
|
||||
"maxItems",
|
||||
"uniqueItems",
|
||||
"const",
|
||||
"multipleOf",
|
||||
"minProperties",
|
||||
"maxProperties",
|
||||
"dependentRequired",
|
||||
];
|
||||
let field = pointer.rsplit('/').next().unwrap_or_default();
|
||||
if UNSUPPORTED.contains(&field) {
|
||||
return true;
|
||||
}
|
||||
field == "type"
|
||||
&& matches!(&node.value, CanonicalSourceValue::Array(items) if {
|
||||
let concrete = items.iter().filter(|item| matches!(&item.value, CanonicalSourceValue::String(value) if value != "null")).count();
|
||||
items.len() != 2 || concrete != 1 || !items.iter().any(|item| matches!(&item.value, CanonicalSourceValue::String(value) if value == "null"))
|
||||
})
|
||||
}
|
||||
|
||||
fn form_schema_shape(pointer: &str, node: &CanonicalSourceNode) -> bool {
|
||||
if !pointer.contains("/requestBody/content/application~1x-www-form-urlencoded/schema")
|
||||
&& !pointer.contains("/requestBody/content/multipart~1form-data/schema")
|
||||
&& !pointer.contains("/parameters/")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let object = matches!(
|
||||
&node.value,
|
||||
CanonicalSourceValue::Object(fields)
|
||||
if fields.contains_key("properties")
|
||||
|| matches!(fields.get("type").map(|field| &field.value), Some(CanonicalSourceValue::String(value)) if value == "object")
|
||||
);
|
||||
let nested_array = pointer.ends_with("/items")
|
||||
&& matches!(
|
||||
&node.value,
|
||||
CanonicalSourceValue::Object(fields)
|
||||
if matches!(fields.get("type").map(|field| &field.value), Some(CanonicalSourceValue::String(value)) if value == "array")
|
||||
);
|
||||
pointer.ends_with("/schema") || object || nested_array
|
||||
}
|
||||
|
||||
fn media_from_pointer(pointer: &str) -> Option<String> {
|
||||
Some(
|
||||
pointer
|
||||
.rsplit('/')
|
||||
.next()?
|
||||
.replace("~1", "/")
|
||||
.replace("~0", "~"),
|
||||
)
|
||||
}
|
||||
|
||||
fn supported_request_media(media: &str) -> bool {
|
||||
matches!(
|
||||
media,
|
||||
"application/json" | "application/x-www-form-urlencoded" | "multipart/form-data"
|
||||
) || media.ends_with("+json")
|
||||
}
|
||||
|
||||
fn supported_response_media(media: &str) -> bool {
|
||||
media == "application/json" || media.ends_with("+json")
|
||||
}
|
||||
|
||||
fn secret_like(pointer: &str, value: &str) -> bool {
|
||||
let pointer = pointer.to_ascii_lowercase();
|
||||
let value = value.to_ascii_lowercase();
|
||||
[
|
||||
"token",
|
||||
"secret",
|
||||
"password",
|
||||
"api_key",
|
||||
"apikey",
|
||||
"authorization",
|
||||
]
|
||||
.iter()
|
||||
.any(|marker| pointer.contains(marker) || value.contains(marker))
|
||||
|| value.starts_with("bearer ")
|
||||
|| value.starts_with("sk-")
|
||||
}
|
||||
|
||||
fn invalid_server(pointer: &str, node: &CanonicalSourceNode) -> bool {
|
||||
if pointer == "/host" {
|
||||
return !matches!(&node.value, CanonicalSourceValue::String(host) if !host.is_empty() && !host.contains('@') && !host.chars().any(char::is_whitespace));
|
||||
}
|
||||
if pointer == "/basePath" {
|
||||
return !matches!(&node.value, CanonicalSourceValue::String(path) if (path.is_empty() || path.starts_with('/')) && !path.chars().any(char::is_control));
|
||||
}
|
||||
if pointer.starts_with("/schemes/") {
|
||||
return !matches!(&node.value, CanonicalSourceValue::String(scheme) if matches!(scheme.as_str(), "http" | "https"));
|
||||
}
|
||||
if pointer.ends_with("/url") {
|
||||
return matches!(&node.value, CanonicalSourceValue::String(url) if !super::openapi3_findings::valid_http_server_url(url));
|
||||
}
|
||||
!matches!(&node.value, CanonicalSourceValue::Object(fields) if matches!(fields.get("url").map(|node| &node.value), Some(CanonicalSourceValue::String(_))))
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::rest::model::{
|
||||
ImportFinding, NormalizedLiteral, NormalizedOperation, NormalizedScalarKind, NormalizedSchema,
|
||||
NormalizedSchemaKind, RestImportOperation, RestImportParameter, RestRequestBodyVariant,
|
||||
RestResponseVariant,
|
||||
};
|
||||
|
||||
pub(super) fn operation_from_normalized(operation: &NormalizedOperation) -> RestImportOperation {
|
||||
RestImportOperation {
|
||||
key: operation.key.clone(),
|
||||
method: operation.method,
|
||||
path: operation.path.clone(),
|
||||
operation_id: operation.operation_id.clone(),
|
||||
summary: operation.summary.clone(),
|
||||
description: operation.description.clone(),
|
||||
tags: operation.tags.clone(),
|
||||
parameters: operation
|
||||
.parameters
|
||||
.iter()
|
||||
.map(|parameter| RestImportParameter {
|
||||
name: parameter.name.clone(),
|
||||
location: parameter.location,
|
||||
required: parameter.required,
|
||||
description: parameter.description.clone(),
|
||||
schema: parameter.schema.as_ref().map(schema_value),
|
||||
source_location: parameter.source_location.clone(),
|
||||
schema_source_location: None,
|
||||
})
|
||||
.collect(),
|
||||
request_body_schema: operation.request_body_schema.as_ref().map(schema_value),
|
||||
request_body_schema_location: None,
|
||||
request_body_variants: operation
|
||||
.request_body_variants
|
||||
.iter()
|
||||
.map(|variant| RestRequestBodyVariant {
|
||||
content_type: variant.content_type.clone(),
|
||||
required: variant.required,
|
||||
schema: variant.schema.as_ref().map(schema_value),
|
||||
multipart_field_mime_types: variant.multipart_field_mime_types.clone(),
|
||||
source_location: variant.source_location.clone(),
|
||||
schema_source_location: None,
|
||||
schema_property_source_locations: BTreeMap::new(),
|
||||
})
|
||||
.collect(),
|
||||
response_schema: operation.response_schema.as_ref().map(schema_value),
|
||||
response_schema_location: None,
|
||||
response_variants: operation
|
||||
.response_variants
|
||||
.iter()
|
||||
.map(|variant| RestResponseVariant {
|
||||
status_code: variant.status_code,
|
||||
content_type: variant.content_type.clone(),
|
||||
schema: variant.schema.as_ref().map(schema_value),
|
||||
source_location: variant.source_location.clone(),
|
||||
schema_source_location: None,
|
||||
})
|
||||
.collect(),
|
||||
servers: operation.servers.clone(),
|
||||
findings: operation
|
||||
.findings
|
||||
.iter()
|
||||
.map(|finding| ImportFinding {
|
||||
code: finding.code.clone(),
|
||||
severity: finding.severity.clone(),
|
||||
message: finding.message.clone(),
|
||||
operation_key: finding.operation_key.clone(),
|
||||
})
|
||||
.collect(),
|
||||
internal_finding_locations: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn schema_value(schema: &NormalizedSchema) -> Value {
|
||||
let mut value = match &schema.kind {
|
||||
NormalizedSchemaKind::Reference { reference } => serde_json::json!({"$ref": reference.uri}),
|
||||
NormalizedSchemaKind::Composition { operator, variants } => serde_json::json!({
|
||||
operator: variants.iter().map(schema_value).collect::<Vec<_>>(),
|
||||
"x-crank-lossless-composition": true,
|
||||
}),
|
||||
NormalizedSchemaKind::Object {
|
||||
properties,
|
||||
required,
|
||||
nullable,
|
||||
default_value,
|
||||
} => {
|
||||
let mut value = serde_json::json!({
|
||||
"type": "object",
|
||||
"properties": properties.iter().map(|(name, schema)| (name.clone(), schema_value(schema))).collect::<serde_json::Map<_, _>>(),
|
||||
"required": required,
|
||||
"nullable": nullable,
|
||||
});
|
||||
insert_default(&mut value, default_value.as_ref());
|
||||
value
|
||||
}
|
||||
NormalizedSchemaKind::Array {
|
||||
items,
|
||||
nullable,
|
||||
default_value,
|
||||
} => {
|
||||
let mut value = serde_json::json!({"type": "array", "nullable": nullable});
|
||||
if let Some(items) = items {
|
||||
value["items"] = schema_value(items);
|
||||
}
|
||||
insert_default(&mut value, default_value.as_ref());
|
||||
value
|
||||
}
|
||||
NormalizedSchemaKind::Scalar {
|
||||
scalar_type,
|
||||
format,
|
||||
nullable,
|
||||
default_value,
|
||||
enum_values,
|
||||
} => {
|
||||
let scalar_type = match scalar_type {
|
||||
NormalizedScalarKind::String => "string",
|
||||
NormalizedScalarKind::Integer => "integer",
|
||||
NormalizedScalarKind::Number => "number",
|
||||
NormalizedScalarKind::Boolean => "boolean",
|
||||
NormalizedScalarKind::Null => "null",
|
||||
};
|
||||
let mut value = serde_json::json!({"type": scalar_type, "nullable": nullable});
|
||||
if let Some(format) = format {
|
||||
value["format"] = Value::String(format.clone());
|
||||
}
|
||||
if !enum_values.is_empty() {
|
||||
value["enum"] = Value::Array(enum_values.iter().map(literal_value).collect());
|
||||
}
|
||||
insert_default(&mut value, default_value.as_ref());
|
||||
value
|
||||
}
|
||||
NormalizedSchemaKind::Unknown => serde_json::json!({}),
|
||||
};
|
||||
if let Some(description) = &schema.description {
|
||||
value["description"] = Value::String(description.clone());
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
fn insert_default(value: &mut Value, default: Option<&NormalizedLiteral>) {
|
||||
if let Some(default) = default {
|
||||
value["default"] = literal_value(default);
|
||||
}
|
||||
}
|
||||
|
||||
fn literal_value(value: &NormalizedLiteral) -> Value {
|
||||
match value {
|
||||
NormalizedLiteral::String(value) => Value::String(value.clone()),
|
||||
NormalizedLiteral::Integer(value) => Value::Number((*value).into()),
|
||||
NormalizedLiteral::Unsigned(value) => Value::Number((*value).into()),
|
||||
NormalizedLiteral::Number(value) => serde_json::Number::from_f64(*value)
|
||||
.map(Value::Number)
|
||||
.unwrap_or(Value::Null),
|
||||
NormalizedLiteral::Boolean(value) => Value::Bool(*value),
|
||||
NormalizedLiteral::Null => Value::Null,
|
||||
}
|
||||
}
|
||||
@@ -8,12 +8,71 @@ use crate::rest::model::{
|
||||
|
||||
use super::normalize_coverage::escape_pointer;
|
||||
|
||||
pub(super) fn typed_schema_with_property_locations(
|
||||
value: &Value,
|
||||
pointer: &str,
|
||||
property_locations: &std::collections::BTreeMap<String, SourceLocation>,
|
||||
coverage: &mut Vec<CoverageEntry>,
|
||||
) -> NormalizedSchema {
|
||||
if property_locations.is_empty() {
|
||||
return typed_schema(value, pointer, "", coverage);
|
||||
}
|
||||
let mut root_value = value.clone();
|
||||
if let Some(object) = root_value.as_object_mut() {
|
||||
object.remove("properties");
|
||||
}
|
||||
let mut normalized = typed_schema(&root_value, pointer, "", coverage);
|
||||
let Some(properties) = value.get("properties").and_then(Value::as_object) else {
|
||||
return normalized;
|
||||
};
|
||||
let NormalizedSchemaKind::Object {
|
||||
properties: normalized_properties,
|
||||
..
|
||||
} = &mut normalized.kind
|
||||
else {
|
||||
return normalized;
|
||||
};
|
||||
for (name, schema) in properties {
|
||||
let Some(location) = property_locations.get(name) else {
|
||||
continue;
|
||||
};
|
||||
normalized_properties.insert(
|
||||
name.clone(),
|
||||
typed_schema(schema, &location.pointer, "", coverage),
|
||||
);
|
||||
}
|
||||
normalized
|
||||
}
|
||||
|
||||
pub(super) fn typed_schema(
|
||||
value: &Value,
|
||||
pointer: &str,
|
||||
_id: &str,
|
||||
coverage: &mut Vec<CoverageEntry>,
|
||||
) -> NormalizedSchema {
|
||||
let normalized_type_value;
|
||||
let value = if let Some(types) = value.get("type").and_then(Value::as_array) {
|
||||
let concrete = types
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.filter(|value| *value != "null")
|
||||
.collect::<Vec<_>>();
|
||||
if types.iter().any(|value| value.as_str() == Some("null")) && concrete.len() == 1 {
|
||||
normalized_type_value = {
|
||||
let mut normalized = value.clone();
|
||||
if let Some(object) = normalized.as_object_mut() {
|
||||
object.insert("type".to_owned(), Value::String(concrete[0].to_owned()));
|
||||
object.insert("nullable".to_owned(), Value::Bool(true));
|
||||
}
|
||||
normalized
|
||||
};
|
||||
&normalized_type_value
|
||||
} else {
|
||||
value
|
||||
}
|
||||
} else {
|
||||
value
|
||||
};
|
||||
// IDs are derived from RFC 6901 locations rather than user-controlled
|
||||
// property names, so escaped keys cannot collide with one another.
|
||||
let id = format!("schema:{}", escape_pointer(pointer));
|
||||
@@ -105,6 +164,11 @@ pub(super) fn typed_schema(
|
||||
NormalizedSchemaKind::Object {
|
||||
properties,
|
||||
required,
|
||||
nullable: value
|
||||
.get("nullable")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false),
|
||||
default_value: value.get("default").and_then(normalized_literal),
|
||||
}
|
||||
} else if value.get("type").and_then(Value::as_str) == Some("array") {
|
||||
NormalizedSchemaKind::Array {
|
||||
@@ -116,6 +180,11 @@ pub(super) fn typed_schema(
|
||||
coverage,
|
||||
))
|
||||
}),
|
||||
nullable: value
|
||||
.get("nullable")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false),
|
||||
default_value: value.get("default").and_then(normalized_literal),
|
||||
}
|
||||
} else if let Some(raw_type) = value.get("type").and_then(Value::as_str) {
|
||||
NormalizedSchemaKind::Scalar {
|
||||
@@ -190,7 +259,7 @@ pub(super) fn has_reference_schema(schema: Option<&NormalizedSchema>) -> bool {
|
||||
Some(NormalizedSchemaKind::Object { properties, .. }) => properties
|
||||
.values()
|
||||
.any(|schema| has_reference_schema(Some(schema))),
|
||||
Some(NormalizedSchemaKind::Array { items }) => has_reference_schema(items.as_deref()),
|
||||
Some(NormalizedSchemaKind::Array { items, .. }) => has_reference_schema(items.as_deref()),
|
||||
Some(NormalizedSchemaKind::Composition { variants, .. }) => variants
|
||||
.iter()
|
||||
.any(|schema| has_reference_schema(Some(schema))),
|
||||
|
||||
@@ -3,8 +3,8 @@ use serde_json::Value;
|
||||
|
||||
use crate::rest::{
|
||||
model::{
|
||||
ImportFinding, ImportFindingSeverity, RestImportDocument, RestImportOperation,
|
||||
RestImportParameter, RestParameterLocation,
|
||||
ImportFinding, RestImportDocument, RestImportOperation, RestImportParameter,
|
||||
RestParameterLocation, RestRequestBodyVariant, RestResponseVariant,
|
||||
},
|
||||
normalize::ImportParseError,
|
||||
recommendations::{document_blocker, document_finding},
|
||||
@@ -59,13 +59,13 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
|
||||
for (path, path_item) in paths {
|
||||
if !path_item.is_object() {
|
||||
findings.push(path_item_blocker(path));
|
||||
findings.push(super::http_methods::invalid_path_item());
|
||||
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
|
||||
pointer: format!("/paths/{}", path.replace('~', "~0").replace('/', "~1")),
|
||||
}));
|
||||
continue;
|
||||
}
|
||||
for method_name in ["head", "options", "trace", "connect"] {
|
||||
for method_name in super::openapi3_findings::unsupported_methods(path_item) {
|
||||
if path_item.get(method_name).is_some() {
|
||||
findings.push(document_blocker(
|
||||
"unsupported_http_method",
|
||||
@@ -99,7 +99,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
path_servers.findings,
|
||||
);
|
||||
let path_servers = path_servers.servers;
|
||||
for method_name in ["get", "post", "put", "patch", "delete"] {
|
||||
for method_name in ["get", "post", "put", "patch", "delete", "head", "options"] {
|
||||
let Some(operation_value) = path_item.get(method_name) else {
|
||||
continue;
|
||||
};
|
||||
@@ -117,7 +117,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
}));
|
||||
continue;
|
||||
}
|
||||
let Some(method) = method_from_lower(method_name) else {
|
||||
let Some(method) = super::http_methods::from_lower(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||
@@ -154,6 +154,17 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
tags.findings,
|
||||
);
|
||||
|
||||
let mut located_operation_findings =
|
||||
super::openapi3_findings::operation(operation_value, &operation_pointer);
|
||||
located_operation_findings.extend(super::openapi3_findings::path_parameters(
|
||||
path,
|
||||
&operation_parameters,
|
||||
));
|
||||
let (operation_findings, internal_finding_locations) =
|
||||
located_operation_findings.into_iter().unzip();
|
||||
let response_schema = (method != HttpMethod::Head)
|
||||
.then(|| response_schema(operation_value, &operation_pointer))
|
||||
.flatten();
|
||||
operations.push(RestImportOperation {
|
||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||
method,
|
||||
@@ -179,16 +190,17 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
&operation_pointer,
|
||||
)
|
||||
.map(|(_, location)| location),
|
||||
response_schema: response_schema(operation_value, &operation_pointer)
|
||||
.map(|(schema, _)| schema),
|
||||
response_schema_location: response_schema(operation_value, &operation_pointer)
|
||||
.map(|(_, location)| location),
|
||||
request_body_variants: request_body_variants(operation_value, &operation_pointer),
|
||||
response_schema: response_schema.as_ref().map(|(schema, _)| schema.clone()),
|
||||
response_schema_location: response_schema.map(|(_, location)| location),
|
||||
response_variants: response_variants(operation_value, &operation_pointer, method),
|
||||
servers: if operation_servers.is_empty() {
|
||||
path_servers.clone()
|
||||
} else {
|
||||
operation_servers
|
||||
},
|
||||
findings: operation_findings(operation_value),
|
||||
findings: operation_findings,
|
||||
internal_finding_locations,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -251,7 +263,7 @@ pub fn parse_document_legacy_v1(root: &Value) -> Result<RestImportDocument, Impo
|
||||
let Some(operation) = path_item.get(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let Some(method) = method_from_lower(method_name) else {
|
||||
let Some(method) = super::http_methods::from_lower(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||
@@ -281,10 +293,13 @@ pub fn parse_document_legacy_v1(root: &Value) -> Result<RestImportDocument, Impo
|
||||
parameters,
|
||||
request_body_schema: legacy_request_body_schema(root, operation),
|
||||
request_body_schema_location: None,
|
||||
request_body_variants: Vec::new(),
|
||||
response_schema: legacy_response_schema(root, operation),
|
||||
response_schema_location: None,
|
||||
response_variants: Vec::new(),
|
||||
servers: legacy_servers(operation.get("servers")),
|
||||
findings: legacy_operation_findings(operation),
|
||||
internal_finding_locations: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -458,6 +473,10 @@ fn parse_servers(value: Option<&Value>, base_pointer: &str) -> ParsedServers {
|
||||
findings.push(server_blocker(&pointer));
|
||||
return None;
|
||||
};
|
||||
if !super::openapi3_findings::valid_http_server_url(url) {
|
||||
findings.push(server_blocker(&format!("{pointer}/url")));
|
||||
return None;
|
||||
}
|
||||
Some(url.trim_end_matches('/').to_owned())
|
||||
})
|
||||
.collect()
|
||||
@@ -559,14 +578,7 @@ fn parameters(value: Option<&Value>, base_pointer: &str) -> ParsedParameters {
|
||||
"path" => RestParameterLocation::Path,
|
||||
"query" => RestParameterLocation::Query,
|
||||
"header" => RestParameterLocation::Header,
|
||||
"cookie" => {
|
||||
findings.push(parameter_blocker(
|
||||
"unsupported_cookie_parameter",
|
||||
"Cookie parameter пока не поддерживается и не был импортирован.",
|
||||
&pointer,
|
||||
));
|
||||
return None;
|
||||
}
|
||||
"cookie" => RestParameterLocation::Cookie,
|
||||
_ => {
|
||||
findings.push(parameter_blocker(
|
||||
"unsupported_parameter_location",
|
||||
@@ -576,14 +588,81 @@ fn parameters(value: Option<&Value>, base_pointer: &str) -> ParsedParameters {
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let expected_style = match location {
|
||||
RestParameterLocation::Path | RestParameterLocation::Header => "simple",
|
||||
RestParameterLocation::Query | RestParameterLocation::Cookie => "form",
|
||||
};
|
||||
if item
|
||||
.get("style")
|
||||
.is_some_and(|style| style.as_str() != Some(expected_style))
|
||||
{
|
||||
findings.push(parameter_blocker(
|
||||
"unsupported_parameter_style",
|
||||
"Параметр использует style, который текущий REST mapping не сериализует без потерь.",
|
||||
&format!("{pointer}/style"),
|
||||
));
|
||||
}
|
||||
let default_explode = matches!(
|
||||
location,
|
||||
RestParameterLocation::Query | RestParameterLocation::Cookie
|
||||
);
|
||||
if item
|
||||
.get("explode")
|
||||
.is_some_and(|explode| explode.as_bool() != Some(default_explode))
|
||||
{
|
||||
findings.push(parameter_blocker(
|
||||
"unsupported_parameter_style",
|
||||
"Параметр использует explode, который текущий REST mapping не сериализует без потерь.",
|
||||
&format!("{pointer}/explode"),
|
||||
));
|
||||
}
|
||||
if item
|
||||
.get("allowReserved")
|
||||
.is_some_and(|value| value.as_bool() != Some(false))
|
||||
{
|
||||
findings.push(parameter_blocker(
|
||||
"unsupported_parameter_style",
|
||||
"allowReserved=true не поддерживается текущим REST mapping.",
|
||||
&format!("{pointer}/allowReserved"),
|
||||
));
|
||||
}
|
||||
if item.get("content").is_some() {
|
||||
findings.push(parameter_blocker(
|
||||
"unsupported_parameter_content",
|
||||
"Parameter content не поддерживается текущим REST mapping.",
|
||||
&format!("{pointer}/content"),
|
||||
));
|
||||
}
|
||||
if item.get("schema").is_none() && item.get("content").is_none() {
|
||||
findings.push(parameter_blocker(
|
||||
"missing_parameter_schema",
|
||||
"Параметр не содержит schema.",
|
||||
&pointer,
|
||||
));
|
||||
}
|
||||
if item.get("schema").is_some_and(|schema| {
|
||||
matches!(schema.get("type").and_then(Value::as_str), Some("array" | "object"))
|
||||
}) {
|
||||
findings.push(parameter_blocker(
|
||||
"unsupported_parameter_style",
|
||||
"Array/object parameter serialization не поддерживается текущим REST mapping.",
|
||||
&format!("{pointer}/schema"),
|
||||
));
|
||||
}
|
||||
if let Some(schema) = item.get("schema") {
|
||||
super::openapi3_findings::schema_findings(
|
||||
schema,
|
||||
&format!("{pointer}/schema"),
|
||||
&mut findings,
|
||||
);
|
||||
}
|
||||
Some(RestImportParameter {
|
||||
name: item.get("name").and_then(Value::as_str)?.to_owned(),
|
||||
location,
|
||||
required: item
|
||||
.get("required")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
|| location == RestParameterLocation::Path,
|
||||
.unwrap_or(false),
|
||||
description: item
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
@@ -672,6 +751,87 @@ fn request_body_schema(
|
||||
})
|
||||
}
|
||||
|
||||
fn request_body_variants(
|
||||
operation: &Value,
|
||||
operation_pointer: &str,
|
||||
) -> Vec<RestRequestBodyVariant> {
|
||||
let Some(body) = operation.get("requestBody") else {
|
||||
return Vec::new();
|
||||
};
|
||||
let required = body
|
||||
.get("required")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
let Some(content) = body.get("content").and_then(Value::as_object) else {
|
||||
return Vec::new();
|
||||
};
|
||||
content
|
||||
.iter()
|
||||
.filter(|(content_type, media)| {
|
||||
supported_request_content_type(content_type) && media.get("schema").is_some()
|
||||
})
|
||||
.map(|(content_type, media)| RestRequestBodyVariant {
|
||||
content_type: content_type.clone(),
|
||||
required,
|
||||
schema: media.get("schema").cloned(),
|
||||
multipart_field_mime_types: if content_type == "multipart/form-data" {
|
||||
multipart_field_mime_types(media)
|
||||
} else {
|
||||
Default::default()
|
||||
},
|
||||
source_location: crate::rest::model::SourceLocation {
|
||||
pointer: format!(
|
||||
"{operation_pointer}/requestBody/content/{}",
|
||||
content_type.replace('~', "~0").replace('/', "~1")
|
||||
),
|
||||
},
|
||||
schema_source_location: media.get("schema").map(|_| {
|
||||
crate::rest::model::SourceLocation {
|
||||
pointer: format!(
|
||||
"{operation_pointer}/requestBody/content/{}/schema",
|
||||
content_type.replace('~', "~0").replace('/', "~1")
|
||||
),
|
||||
}
|
||||
}),
|
||||
schema_property_source_locations: Default::default(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn multipart_field_mime_types(media: &Value) -> std::collections::BTreeMap<String, Vec<String>> {
|
||||
media
|
||||
.get("encoding")
|
||||
.and_then(Value::as_object)
|
||||
.map(|encoding| {
|
||||
encoding
|
||||
.iter()
|
||||
.filter_map(|(field, value)| {
|
||||
let mime_types = value
|
||||
.get("contentType")
|
||||
.and_then(Value::as_str)
|
||||
.map(|value| {
|
||||
value
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
(!mime_types.is_empty()).then(|| (field.clone(), mime_types))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn supported_request_content_type(content_type: &str) -> bool {
|
||||
content_type == "application/x-www-form-urlencoded"
|
||||
|| content_type == "multipart/form-data"
|
||||
|| content_type == "application/json"
|
||||
|| content_type.ends_with("+json")
|
||||
}
|
||||
|
||||
fn response_schema(
|
||||
operation: &Value,
|
||||
operation_pointer: &str,
|
||||
@@ -752,33 +912,85 @@ fn response_json_schema(
|
||||
})
|
||||
}
|
||||
|
||||
fn operation_findings(operation: &Value) -> Vec<ImportFinding> {
|
||||
let mut findings = Vec::new();
|
||||
if operation.get("requestBody").is_some() && request_body_schema(operation, "").is_none() {
|
||||
findings.push(document_finding(
|
||||
"unsupported_request_body",
|
||||
"У метода есть requestBody, но JSON schema не найдена.",
|
||||
));
|
||||
}
|
||||
findings
|
||||
}
|
||||
|
||||
fn method_from_lower(value: &str) -> Option<HttpMethod> {
|
||||
match value {
|
||||
"get" => Some(HttpMethod::Get),
|
||||
"post" => Some(HttpMethod::Post),
|
||||
"put" => Some(HttpMethod::Put),
|
||||
"patch" => Some(HttpMethod::Patch),
|
||||
"delete" => Some(HttpMethod::Delete),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn path_item_blocker(_path: &str) -> ImportFinding {
|
||||
ImportFinding {
|
||||
code: "invalid_path_item".to_owned(),
|
||||
severity: ImportFindingSeverity::Error,
|
||||
message: "Path Item имеет неверную структуру и не был интерпретирован.".to_owned(),
|
||||
operation_key: None,
|
||||
}
|
||||
fn response_variants(
|
||||
operation: &Value,
|
||||
operation_pointer: &str,
|
||||
method: HttpMethod,
|
||||
) -> Vec<RestResponseVariant> {
|
||||
let Some(responses) = operation.get("responses").and_then(Value::as_object) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut variants = responses
|
||||
.iter()
|
||||
.filter_map(|(code, response)| {
|
||||
let status_code = code
|
||||
.parse::<u16>()
|
||||
.ok()
|
||||
.filter(|code| (200..300).contains(code))?;
|
||||
let base = format!(
|
||||
"{operation_pointer}/responses/{}",
|
||||
code.replace('~', "~0").replace('/', "~1")
|
||||
);
|
||||
if method == HttpMethod::Head {
|
||||
return Some(vec![RestResponseVariant {
|
||||
status_code,
|
||||
content_type: None,
|
||||
schema: None,
|
||||
source_location: crate::rest::model::SourceLocation { pointer: base },
|
||||
schema_source_location: None,
|
||||
}]);
|
||||
}
|
||||
let content = response.get("content").and_then(Value::as_object);
|
||||
Some(match content {
|
||||
None => vec![RestResponseVariant {
|
||||
status_code,
|
||||
content_type: None,
|
||||
schema: None,
|
||||
source_location: crate::rest::model::SourceLocation { pointer: base },
|
||||
schema_source_location: None,
|
||||
}],
|
||||
Some(content) if content.is_empty() => vec![RestResponseVariant {
|
||||
status_code,
|
||||
content_type: None,
|
||||
schema: None,
|
||||
source_location: crate::rest::model::SourceLocation { pointer: base },
|
||||
schema_source_location: None,
|
||||
}],
|
||||
Some(content) => content
|
||||
.iter()
|
||||
.filter(|(content_type, _)| {
|
||||
*content_type == "application/json" || content_type.ends_with("+json")
|
||||
})
|
||||
.filter(|(_, media)| media.get("schema").is_some())
|
||||
.map(|(content_type, media)| RestResponseVariant {
|
||||
status_code,
|
||||
content_type: Some(content_type.clone()),
|
||||
schema: media.get("schema").cloned(),
|
||||
source_location: crate::rest::model::SourceLocation {
|
||||
pointer: format!(
|
||||
"{base}/content/{}",
|
||||
content_type.replace('~', "~0").replace('/', "~1")
|
||||
),
|
||||
},
|
||||
schema_source_location: media.get("schema").map(|_| {
|
||||
crate::rest::model::SourceLocation {
|
||||
pointer: format!(
|
||||
"{base}/content/{}/schema",
|
||||
content_type.replace('~', "~0").replace('/', "~1")
|
||||
),
|
||||
}
|
||||
}),
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
})
|
||||
.flatten()
|
||||
.collect::<Vec<_>>();
|
||||
variants.sort_by(|left, right| {
|
||||
(left.status_code, left.content_type.as_deref().unwrap_or("")).cmp(&(
|
||||
right.status_code,
|
||||
right.content_type.as_deref().unwrap_or(""),
|
||||
))
|
||||
});
|
||||
variants
|
||||
}
|
||||
@@ -0,0 +1,485 @@
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::rest::{
|
||||
model::{ImportFinding, RestImportParameter, RestParameterLocation, SourceLocation},
|
||||
recommendations::document_blocker,
|
||||
};
|
||||
|
||||
pub(super) fn operation(
|
||||
operation: &Value,
|
||||
operation_pointer: &str,
|
||||
) -> Vec<(ImportFinding, SourceLocation)> {
|
||||
let mut findings = Vec::new();
|
||||
if operation.get("requestBody").is_some() && supported_request_variants(operation) == 0 {
|
||||
push(
|
||||
&mut findings,
|
||||
"unsupported_request_body",
|
||||
"У requestBody нет поддерживаемой schema.",
|
||||
&format!("{operation_pointer}/requestBody"),
|
||||
);
|
||||
}
|
||||
if let Some(content) = operation
|
||||
.pointer("/requestBody/content")
|
||||
.and_then(Value::as_object)
|
||||
{
|
||||
for (content_type, media) in content {
|
||||
let media_pointer = format!(
|
||||
"{operation_pointer}/requestBody/content/{}",
|
||||
escape(content_type)
|
||||
);
|
||||
if !supported_request_media(content_type) {
|
||||
let code = if content_type.contains("xml") {
|
||||
"unsupported_xml_request_media_type"
|
||||
} else {
|
||||
"unsupported_request_media_type"
|
||||
};
|
||||
push(
|
||||
&mut findings,
|
||||
code,
|
||||
"Request media type не поддерживается без fallback.",
|
||||
&media_pointer,
|
||||
);
|
||||
}
|
||||
if supported_request_media(content_type) && media.get("schema").is_none() {
|
||||
push(
|
||||
&mut findings,
|
||||
"missing_request_media_schema",
|
||||
"Request media type не содержит schema.",
|
||||
&media_pointer,
|
||||
);
|
||||
}
|
||||
if let Some(schema) = media.get("schema") {
|
||||
schema_findings(schema, &format!("{media_pointer}/schema"), &mut findings);
|
||||
}
|
||||
if matches!(
|
||||
content_type.as_str(),
|
||||
"application/x-www-form-urlencoded" | "multipart/form-data"
|
||||
) && let Some(schema) = media.get("schema")
|
||||
{
|
||||
form_schema_findings(schema, &format!("{media_pointer}/schema"), &mut findings);
|
||||
}
|
||||
if content_type == "application/x-www-form-urlencoded" {
|
||||
form_encoding_findings(media, &media_pointer, &mut findings);
|
||||
}
|
||||
if content_type == "multipart/form-data" {
|
||||
multipart_encoding_findings(media, &media_pointer, &mut findings);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(responses) = operation.get("responses").and_then(Value::as_object) {
|
||||
for (status, response) in responses {
|
||||
let Some(content) = response.get("content").and_then(Value::as_object) else {
|
||||
continue;
|
||||
};
|
||||
for (content_type, media) in content {
|
||||
let media_pointer = format!(
|
||||
"{operation_pointer}/responses/{}/content/{}",
|
||||
escape(status),
|
||||
escape(content_type)
|
||||
);
|
||||
if !supported_response_media(content_type) {
|
||||
let code = if content_type.contains("xml") {
|
||||
"unsupported_xml_response_media_type"
|
||||
} else {
|
||||
"unsupported_response_media_type"
|
||||
};
|
||||
push(
|
||||
&mut findings,
|
||||
code,
|
||||
"Response media type не поддерживается без fallback.",
|
||||
&media_pointer,
|
||||
);
|
||||
} else if let Some(schema) = media.get("schema") {
|
||||
schema_findings(schema, &format!("{media_pointer}/schema"), &mut findings);
|
||||
} else {
|
||||
push(
|
||||
&mut findings,
|
||||
"missing_response_media_schema",
|
||||
"Response media type не содержит schema.",
|
||||
&media_pointer,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
findings
|
||||
}
|
||||
|
||||
fn form_encoding_findings(
|
||||
media: &Value,
|
||||
media_pointer: &str,
|
||||
findings: &mut Vec<(ImportFinding, SourceLocation)>,
|
||||
) {
|
||||
let Some(encoding_value) = media.get("encoding") else {
|
||||
return;
|
||||
};
|
||||
let Some(encoding) = encoding_value.as_object() else {
|
||||
push(
|
||||
findings,
|
||||
"unsupported_form_encoding",
|
||||
"Form encoding должен быть объектом.",
|
||||
&format!("{media_pointer}/encoding"),
|
||||
);
|
||||
return;
|
||||
};
|
||||
for (field, settings) in encoding {
|
||||
let field_pointer = format!("{media_pointer}/encoding/{}", escape(field));
|
||||
let Some(settings) = settings.as_object() else {
|
||||
push(
|
||||
findings,
|
||||
"unsupported_form_encoding",
|
||||
"Form encoding имеет неподдерживаемую структуру.",
|
||||
&field_pointer,
|
||||
);
|
||||
continue;
|
||||
};
|
||||
for (key, value) in settings {
|
||||
let supported = match key.as_str() {
|
||||
"style" => value.as_str() == Some("form"),
|
||||
"explode" => value.as_bool() == Some(true),
|
||||
_ => false,
|
||||
};
|
||||
if !supported {
|
||||
push(
|
||||
findings,
|
||||
"unsupported_form_encoding",
|
||||
"Form encoding metadata не поддерживается wire contract.",
|
||||
&format!("{field_pointer}/{}", escape(key)),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn form_schema_findings(
|
||||
schema: &Value,
|
||||
pointer: &str,
|
||||
findings: &mut Vec<(ImportFinding, SourceLocation)>,
|
||||
) {
|
||||
if !object_schema(schema) {
|
||||
push(
|
||||
findings,
|
||||
"unsupported_form_schema",
|
||||
"Form body должен быть object со scalar, file или array полями.",
|
||||
pointer,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if let Some(properties) = schema.get("properties").and_then(Value::as_object) {
|
||||
for (name, property) in properties {
|
||||
form_field_schema_findings(
|
||||
property,
|
||||
&format!("{pointer}/properties/{}", escape(name)),
|
||||
findings,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn form_field_schema_findings(
|
||||
schema: &Value,
|
||||
pointer: &str,
|
||||
findings: &mut Vec<(ImportFinding, SourceLocation)>,
|
||||
) {
|
||||
form_field_schema_findings_inner(schema, pointer, true, findings);
|
||||
}
|
||||
|
||||
fn form_field_schema_findings_inner(
|
||||
schema: &Value,
|
||||
pointer: &str,
|
||||
array_allowed: bool,
|
||||
findings: &mut Vec<(ImportFinding, SourceLocation)>,
|
||||
) {
|
||||
if object_schema(schema) {
|
||||
push(
|
||||
findings,
|
||||
"unsupported_form_schema",
|
||||
"Вложенный object field не поддерживается form wire contract.",
|
||||
pointer,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if schema.get("type").and_then(Value::as_str) == Some("array") {
|
||||
if !array_allowed {
|
||||
push(
|
||||
findings,
|
||||
"unsupported_form_schema",
|
||||
"Вложенные arrays не поддерживаются form wire contract.",
|
||||
pointer,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if let Some(items) = schema.get("items") {
|
||||
form_field_schema_findings_inner(items, &format!("{pointer}/items"), false, findings);
|
||||
}
|
||||
}
|
||||
for operator in ["allOf", "oneOf", "anyOf"] {
|
||||
if let Some(variants) = schema.get(operator).and_then(Value::as_array) {
|
||||
for (index, variant) in variants.iter().enumerate() {
|
||||
form_field_schema_findings_inner(
|
||||
variant,
|
||||
&format!("{pointer}/{operator}/{index}"),
|
||||
array_allowed,
|
||||
findings,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn object_schema(schema: &Value) -> bool {
|
||||
schema.get("properties").is_some()
|
||||
|| schema.get("type").and_then(Value::as_str) == Some("object")
|
||||
}
|
||||
|
||||
fn multipart_encoding_findings(
|
||||
media: &Value,
|
||||
media_pointer: &str,
|
||||
findings: &mut Vec<(ImportFinding, SourceLocation)>,
|
||||
) {
|
||||
let Some(encoding_value) = media.get("encoding") else {
|
||||
return;
|
||||
};
|
||||
let Some(encoding) = encoding_value.as_object() else {
|
||||
push(
|
||||
findings,
|
||||
"unsupported_multipart_encoding",
|
||||
"Multipart encoding должен быть объектом.",
|
||||
&format!("{media_pointer}/encoding"),
|
||||
);
|
||||
return;
|
||||
};
|
||||
for (field, settings) in encoding {
|
||||
let field_pointer = format!("{media_pointer}/encoding/{}", escape(field));
|
||||
let Some(settings) = settings.as_object() else {
|
||||
push(
|
||||
findings,
|
||||
"unsupported_multipart_encoding",
|
||||
"Multipart encoding имеет неподдерживаемую структуру.",
|
||||
&field_pointer,
|
||||
);
|
||||
continue;
|
||||
};
|
||||
for key in settings.keys().filter(|key| key.as_str() != "contentType") {
|
||||
push(
|
||||
findings,
|
||||
"unsupported_multipart_encoding",
|
||||
"Multipart encoding metadata не поддерживается wire contract.",
|
||||
&format!("{field_pointer}/{}", escape(key)),
|
||||
);
|
||||
}
|
||||
if let Some(content_type) = settings.get("contentType") {
|
||||
let source_field = media.pointer(&format!("/schema/properties/{}", escape(field)));
|
||||
let invalid_mime = content_type.as_str().is_none_or(|value| {
|
||||
value.split(',').map(str::trim).any(|mime| {
|
||||
mime.is_empty() || !mime.contains('/') || mime.chars().any(char::is_control)
|
||||
})
|
||||
});
|
||||
if invalid_mime || !source_field.is_some_and(binary_schema) {
|
||||
push(
|
||||
findings,
|
||||
"unsupported_multipart_encoding",
|
||||
"Multipart contentType поддерживается только для binary/file field с валидным MIME.",
|
||||
&format!("{field_pointer}/contentType"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn binary_schema(schema: &Value) -> bool {
|
||||
schema.get("type").and_then(Value::as_str) == Some("string")
|
||||
&& schema.get("format").and_then(Value::as_str) == Some("binary")
|
||||
|| schema.get("type").and_then(Value::as_str) == Some("array")
|
||||
&& schema.get("items").is_some_and(binary_schema)
|
||||
}
|
||||
|
||||
pub(super) fn schema_findings(
|
||||
schema: &Value,
|
||||
pointer: &str,
|
||||
findings: &mut Vec<(ImportFinding, SourceLocation)>,
|
||||
) {
|
||||
if let Some(types) = schema.get("type").and_then(Value::as_array) {
|
||||
let concrete = types
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.filter(|value| *value != "null")
|
||||
.count();
|
||||
let supported = types.len() == 2
|
||||
&& concrete == 1
|
||||
&& types.iter().any(|value| value.as_str() == Some("null"));
|
||||
if !supported {
|
||||
push(
|
||||
findings,
|
||||
"unsupported_schema_keyword",
|
||||
"Schema type array содержит неподдерживаемую комбинацию.",
|
||||
&format!("{pointer}/type"),
|
||||
);
|
||||
}
|
||||
}
|
||||
if schema
|
||||
.get("enum")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|values| values.iter().any(|value| !value.is_string()))
|
||||
{
|
||||
push(
|
||||
findings,
|
||||
"unsupported_schema_enum",
|
||||
"Non-string enum не поддерживается executable schema.",
|
||||
&format!("{pointer}/enum"),
|
||||
);
|
||||
}
|
||||
for keyword in [
|
||||
"additionalProperties",
|
||||
"unevaluatedProperties",
|
||||
"prefixItems",
|
||||
"contains",
|
||||
"dependentSchemas",
|
||||
"if",
|
||||
"then",
|
||||
"else",
|
||||
"not",
|
||||
"propertyNames",
|
||||
"minimum",
|
||||
"maximum",
|
||||
"exclusiveMinimum",
|
||||
"exclusiveMaximum",
|
||||
"minLength",
|
||||
"maxLength",
|
||||
"pattern",
|
||||
"minItems",
|
||||
"maxItems",
|
||||
"uniqueItems",
|
||||
"const",
|
||||
"multipleOf",
|
||||
"minProperties",
|
||||
"maxProperties",
|
||||
"dependentRequired",
|
||||
] {
|
||||
if schema.get(keyword).is_some() {
|
||||
push(
|
||||
findings,
|
||||
"unsupported_schema_keyword",
|
||||
"Schema keyword не поддерживается executable schema.",
|
||||
&format!("{pointer}/{keyword}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Some(properties) = schema.get("properties").and_then(Value::as_object) {
|
||||
for (name, child) in properties {
|
||||
schema_findings(
|
||||
child,
|
||||
&format!("{pointer}/properties/{}", escape(name)),
|
||||
findings,
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Some(items) = schema.get("items") {
|
||||
schema_findings(items, &format!("{pointer}/items"), findings);
|
||||
}
|
||||
for operator in ["allOf", "oneOf", "anyOf"] {
|
||||
if let Some(variants) = schema.get(operator).and_then(Value::as_array) {
|
||||
for (index, variant) in variants.iter().enumerate() {
|
||||
schema_findings(variant, &format!("{pointer}/{operator}/{index}"), findings);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn path_parameters(
|
||||
path: &str,
|
||||
parameters: &[RestImportParameter],
|
||||
) -> Vec<(ImportFinding, SourceLocation)> {
|
||||
parameters
|
||||
.iter()
|
||||
.filter(|parameter| parameter.location == RestParameterLocation::Path)
|
||||
.filter_map(|parameter| {
|
||||
let finding = if !parameter.required {
|
||||
Some((
|
||||
"path_parameter_not_required",
|
||||
format!("Path parameter {} должен быть required.", parameter.name),
|
||||
))
|
||||
} else if !path.contains(&format!("{{{}}}", parameter.name)) {
|
||||
Some((
|
||||
"path_parameter_placeholder_missing",
|
||||
format!(
|
||||
"Path parameter {} не имеет placeholder в пути.",
|
||||
parameter.name
|
||||
),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}?;
|
||||
Some((
|
||||
document_blocker(finding.0, finding.1),
|
||||
parameter.source_location.clone(),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn unsupported_methods(path_item: &Value) -> Vec<&str> {
|
||||
const NON_METHOD: &[&str] = &["$ref", "summary", "description", "servers", "parameters"];
|
||||
const SUPPORTED: &[&str] = &["get", "post", "put", "patch", "delete", "head", "options"];
|
||||
path_item
|
||||
.as_object()
|
||||
.into_iter()
|
||||
.flat_map(|item| item.keys())
|
||||
.map(String::as_str)
|
||||
.filter(|name| {
|
||||
!name.starts_with("x-") && !NON_METHOD.contains(name) && !SUPPORTED.contains(name)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn supported_request_variants(operation: &Value) -> usize {
|
||||
operation
|
||||
.pointer("/requestBody/content")
|
||||
.and_then(Value::as_object)
|
||||
.into_iter()
|
||||
.flat_map(|content| content.iter())
|
||||
.filter(|(media, value)| supported_request_media(media) && value.get("schema").is_some())
|
||||
.count()
|
||||
}
|
||||
|
||||
fn supported_request_media(media: &str) -> bool {
|
||||
matches!(
|
||||
media,
|
||||
"application/json" | "application/x-www-form-urlencoded" | "multipart/form-data"
|
||||
) || media.ends_with("+json")
|
||||
}
|
||||
|
||||
fn supported_response_media(media: &str) -> bool {
|
||||
media == "application/json" || media.ends_with("+json")
|
||||
}
|
||||
|
||||
pub(super) fn valid_http_server_url(url: &str) -> bool {
|
||||
if url.chars().any(char::is_control) {
|
||||
return false;
|
||||
}
|
||||
let Ok(parsed) = url::Url::parse(url) else {
|
||||
return false;
|
||||
};
|
||||
matches!(parsed.scheme(), "http" | "https")
|
||||
&& parsed.host().is_some()
|
||||
&& parsed.username().is_empty()
|
||||
&& parsed.password().is_none()
|
||||
}
|
||||
|
||||
fn push(
|
||||
findings: &mut Vec<(ImportFinding, SourceLocation)>,
|
||||
code: &str,
|
||||
message: impl Into<String>,
|
||||
pointer: &str,
|
||||
) {
|
||||
findings.push((
|
||||
document_blocker(code, message),
|
||||
SourceLocation {
|
||||
pointer: pointer.to_owned(),
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
fn escape(value: &str) -> String {
|
||||
value.replace('~', "~0").replace('/', "~1")
|
||||
}
|
||||
@@ -1,19 +1,22 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use crank_core::{
|
||||
ExecutionConfig, HttpMethod, OperationSafetyClass, OperationSafetyPolicy, Protocol, RestTarget,
|
||||
ToolDescription, ToolExample, WizardState,
|
||||
ExecutionConfig, HttpMethod, OperationSafetyClass, OperationSafetyPolicy, Protocol,
|
||||
RestRequestContract, RestRequestContractVersion, RestRequestDescriptor, RestResponseDescriptor,
|
||||
RestTarget, ToolDescription, ToolExample, WizardState,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::rest::{
|
||||
mapping::{BodyFieldMapping, input_mapping, output_mapping},
|
||||
mapping::{BodyFieldMapping, ParameterFieldMapping, input_mapping, output_mapping},
|
||||
model::{
|
||||
ImportOperationCandidate, RestImportCandidate, RestImportOperation, RestParameterLocation,
|
||||
},
|
||||
naming::{fallback_operation_seed, title_from_name, unique_name},
|
||||
recommendations::{candidate_recommendations, operation_recommendations},
|
||||
schema::{any_object, field_count, object_with_fields, schema_from_openapi},
|
||||
schema::{
|
||||
any_object, field_count, object_with_fields, schema_from_multipart, schema_from_openapi,
|
||||
},
|
||||
};
|
||||
|
||||
pub fn candidate_from_operation(
|
||||
@@ -55,32 +58,37 @@ pub fn candidate_from_operation(
|
||||
let base_url = server_urls.first().cloned().unwrap_or_default();
|
||||
let mut input_fields = BTreeMap::new();
|
||||
let mut used_input_field_names = BTreeSet::new();
|
||||
for parameter in &operation.parameters {
|
||||
used_input_field_names.insert(parameter.name.clone());
|
||||
input_fields.insert(
|
||||
parameter.name.clone(),
|
||||
schema_from_openapi(
|
||||
parameter.schema.as_ref(),
|
||||
parameter.required || parameter.location == RestParameterLocation::Path,
|
||||
parameter.description.clone(),
|
||||
),
|
||||
);
|
||||
}
|
||||
let body_fields = body_input_fields(
|
||||
operation.request_body_schema.as_ref(),
|
||||
&mut used_input_field_names,
|
||||
&mut input_fields,
|
||||
);
|
||||
let input_schema = object_with_fields(
|
||||
Some("Входные параметры MCP-инструмента".to_owned()),
|
||||
input_fields,
|
||||
);
|
||||
let output_schema = operation
|
||||
.response_schema
|
||||
.as_ref()
|
||||
.map(|schema| schema_from_openapi(Some(schema), true, Some("Ответ API".to_owned())))
|
||||
.unwrap_or_else(|| any_object(Some("Ответ API".to_owned())));
|
||||
let input_mapping = input_mapping(&operation.parameters, &body_fields);
|
||||
let parameter_mappings = operation
|
||||
.parameters
|
||||
.iter()
|
||||
.map(|parameter| {
|
||||
let input_name = unique_parameter_input_name(parameter, &mut used_input_field_names);
|
||||
let default_value = parameter
|
||||
.schema
|
||||
.as_ref()
|
||||
.and_then(|schema| schema.get("default"))
|
||||
.cloned();
|
||||
input_fields.insert(
|
||||
input_name.clone(),
|
||||
schema_from_openapi(
|
||||
parameter.schema.as_ref(),
|
||||
parameter.required || parameter.location == RestParameterLocation::Path,
|
||||
parameter.description.clone(),
|
||||
),
|
||||
);
|
||||
ParameterFieldMapping {
|
||||
input_name,
|
||||
wire_name: parameter.name.clone(),
|
||||
location: parameter.location,
|
||||
required: parameter.required || parameter.location == RestParameterLocation::Path,
|
||||
default_value,
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let body_fields = body_input_fields(operation, &mut used_input_field_names, &mut input_fields);
|
||||
let input_schema = input_schema_for_body_variants(operation, input_fields, &body_fields);
|
||||
let output_schema = output_schema_from_operation(operation);
|
||||
let input_mapping = input_mapping(¶meter_mappings, &body_fields);
|
||||
let output_mapping = output_mapping(&output_schema);
|
||||
let mut findings = operation_recommendations(operation);
|
||||
findings.extend(candidate_recommendations(
|
||||
@@ -100,6 +108,29 @@ pub fn candidate_from_operation(
|
||||
method: operation.method,
|
||||
path_template: operation.path.clone(),
|
||||
static_headers: BTreeMap::new(),
|
||||
request_contract: request_contract(operation, &body_fields),
|
||||
response_contract: operation
|
||||
.response_variants
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(schema_variant, variant)| RestResponseDescriptor {
|
||||
status_code: variant.status_code,
|
||||
media_type: variant.content_type.clone(),
|
||||
schema_variant,
|
||||
})
|
||||
.collect(),
|
||||
multipart_field_mime_types: operation
|
||||
.request_body_variants
|
||||
.iter()
|
||||
.filter(|variant| variant.content_type == "multipart/form-data")
|
||||
.filter(|variant| !variant.multipart_field_mime_types.is_empty())
|
||||
.map(|variant| {
|
||||
(
|
||||
variant.content_type.clone(),
|
||||
variant.multipart_field_mime_types.clone(),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
input_schema: input_schema.clone(),
|
||||
output_schema: output_schema.clone(),
|
||||
@@ -136,7 +167,274 @@ pub fn candidate_from_operation(
|
||||
}
|
||||
}
|
||||
|
||||
fn output_schema_from_operation(operation: &RestImportOperation) -> crank_schema::Schema {
|
||||
if operation.response_variants.is_empty() {
|
||||
return operation
|
||||
.response_schema
|
||||
.as_ref()
|
||||
.map(|schema| schema_from_openapi(Some(schema), true, Some("Ответ API".to_owned())))
|
||||
.unwrap_or_else(|| any_object(Some("Ответ API".to_owned())));
|
||||
}
|
||||
let mut variants = operation
|
||||
.response_variants
|
||||
.iter()
|
||||
.map(|variant| match &variant.schema {
|
||||
Some(schema) => schema_from_openapi(Some(schema), true, Some("Ответ API".to_owned())),
|
||||
None => crank_schema::Schema {
|
||||
kind: crank_schema::SchemaKind::Null,
|
||||
format: None,
|
||||
description: Some("Успешный ответ без тела".to_owned()),
|
||||
required: true,
|
||||
nullable: false,
|
||||
default_value: None,
|
||||
fields: BTreeMap::new(),
|
||||
items: None,
|
||||
enum_values: Vec::new(),
|
||||
variants: Vec::new(),
|
||||
},
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if variants.len() == 1 {
|
||||
return variants
|
||||
.pop()
|
||||
.unwrap_or_else(|| any_object(Some("Ответ API".to_owned())));
|
||||
}
|
||||
crank_schema::Schema {
|
||||
kind: crank_schema::SchemaKind::Oneof,
|
||||
format: None,
|
||||
description: Some("Варианты успешного ответа API".to_owned()),
|
||||
required: true,
|
||||
nullable: false,
|
||||
default_value: None,
|
||||
fields: BTreeMap::new(),
|
||||
items: None,
|
||||
enum_values: Vec::new(),
|
||||
variants,
|
||||
}
|
||||
}
|
||||
|
||||
fn body_input_fields(
|
||||
operation: &RestImportOperation,
|
||||
used_names: &mut BTreeSet<String>,
|
||||
input_fields: &mut BTreeMap<String, crank_schema::Schema>,
|
||||
) -> Vec<BodyFieldMapping> {
|
||||
let variants = &operation.request_body_variants;
|
||||
if variants.is_empty() {
|
||||
return legacy_body_input_fields(
|
||||
operation.request_body_schema.as_ref(),
|
||||
used_names,
|
||||
input_fields,
|
||||
);
|
||||
}
|
||||
let required = variants.iter().any(|variant| variant.required);
|
||||
let body_variants = variants
|
||||
.iter()
|
||||
.map(|variant| {
|
||||
let description = Some(format!("Тело запроса ({})", variant.content_type));
|
||||
if variant.content_type == "multipart/form-data" {
|
||||
schema_from_multipart(variant.schema.as_ref(), required, description)
|
||||
} else {
|
||||
schema_from_openapi(variant.schema.as_ref(), required, description)
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let body_schema = if body_variants.len() == 1 {
|
||||
body_variants
|
||||
.into_iter()
|
||||
.next()
|
||||
.expect("single body variant exists")
|
||||
} else {
|
||||
crank_schema::Schema {
|
||||
kind: crank_schema::SchemaKind::Oneof,
|
||||
format: None,
|
||||
description: Some("Тело запроса для выбранного формата".to_owned()),
|
||||
required,
|
||||
nullable: body_variants.iter().any(|variant| variant.nullable),
|
||||
default_value: None,
|
||||
fields: BTreeMap::new(),
|
||||
items: None,
|
||||
enum_values: Vec::new(),
|
||||
variants: body_variants,
|
||||
}
|
||||
};
|
||||
let body_name = unique_body_input_name("body", used_names);
|
||||
input_fields.insert(body_name.clone(), body_schema);
|
||||
if variants.len() > 1 {
|
||||
let selector = unique_body_input_name("content_type", used_names);
|
||||
input_fields.insert(
|
||||
selector.clone(),
|
||||
crank_schema::Schema {
|
||||
kind: crank_schema::SchemaKind::Enum,
|
||||
format: None,
|
||||
description: Some("Выбирает формат тела запроса".to_owned()),
|
||||
required,
|
||||
nullable: false,
|
||||
default_value: None,
|
||||
fields: BTreeMap::new(),
|
||||
items: None,
|
||||
enum_values: variants
|
||||
.iter()
|
||||
.map(|variant| variant.content_type.clone())
|
||||
.collect(),
|
||||
variants: Vec::new(),
|
||||
},
|
||||
);
|
||||
// The adapter obtains the selector from the mapped body envelope.
|
||||
return vec![
|
||||
BodyFieldMapping {
|
||||
input_name: body_name,
|
||||
// Keep selector and value in an internal envelope so that a
|
||||
// selected nullable body can remain JSON null on the wire.
|
||||
body_path: "__body".to_owned(),
|
||||
required,
|
||||
},
|
||||
BodyFieldMapping {
|
||||
input_name: selector,
|
||||
body_path: "__content_type".to_owned(),
|
||||
required,
|
||||
},
|
||||
];
|
||||
}
|
||||
vec![BodyFieldMapping {
|
||||
input_name: body_name,
|
||||
body_path: String::new(),
|
||||
required,
|
||||
}]
|
||||
}
|
||||
|
||||
fn input_schema_for_body_variants(
|
||||
operation: &RestImportOperation,
|
||||
input_fields: BTreeMap<String, crank_schema::Schema>,
|
||||
body_fields: &[BodyFieldMapping],
|
||||
) -> crank_schema::Schema {
|
||||
if operation.request_body_variants.len() <= 1 {
|
||||
return object_with_fields(
|
||||
Some("Входные параметры MCP-инструмента".to_owned()),
|
||||
input_fields,
|
||||
);
|
||||
}
|
||||
let Some(body_name) = body_fields
|
||||
.iter()
|
||||
.find(|field| field.body_path == "__body")
|
||||
.map(|field| field.input_name.as_str())
|
||||
else {
|
||||
return object_with_fields(
|
||||
Some("Входные параметры MCP-инструмента".to_owned()),
|
||||
input_fields,
|
||||
);
|
||||
};
|
||||
let Some(selector_name) = body_fields
|
||||
.iter()
|
||||
.find(|field| field.body_path == "__content_type")
|
||||
.map(|field| field.input_name.as_str())
|
||||
else {
|
||||
return object_with_fields(
|
||||
Some("Входные параметры MCP-инструмента".to_owned()),
|
||||
input_fields,
|
||||
);
|
||||
};
|
||||
let Some(body_schema) = input_fields.get(body_name) else {
|
||||
return object_with_fields(
|
||||
Some("Входные параметры MCP-инструмента".to_owned()),
|
||||
input_fields,
|
||||
);
|
||||
};
|
||||
let Some(selector_schema) = input_fields.get(selector_name) else {
|
||||
return object_with_fields(
|
||||
Some("Входные параметры MCP-инструмента".to_owned()),
|
||||
input_fields,
|
||||
);
|
||||
};
|
||||
let variants = operation
|
||||
.request_body_variants
|
||||
.iter()
|
||||
.zip(&body_schema.variants)
|
||||
.map(|(request_variant, body_schema)| {
|
||||
let mut fields = input_fields.clone();
|
||||
let mut body_schema = body_schema.clone();
|
||||
body_schema.required = true;
|
||||
fields.insert(body_name.to_owned(), body_schema);
|
||||
let mut selector = selector_schema.clone();
|
||||
selector.required = true;
|
||||
selector.enum_values = vec![request_variant.content_type.clone()];
|
||||
fields.insert(selector_name.to_owned(), selector);
|
||||
closed_object_with_fields(Some("Входные параметры MCP-инструмента".to_owned()), fields)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut variants = variants;
|
||||
if !operation
|
||||
.request_body_variants
|
||||
.iter()
|
||||
.any(|variant| variant.required)
|
||||
{
|
||||
let mut absent_fields = input_fields;
|
||||
absent_fields.remove(body_name);
|
||||
absent_fields.remove(selector_name);
|
||||
variants.push(closed_object_with_fields(
|
||||
Some("Входные параметры без HTTP body".to_owned()),
|
||||
absent_fields,
|
||||
));
|
||||
}
|
||||
crank_schema::Schema {
|
||||
kind: crank_schema::SchemaKind::Oneof,
|
||||
format: None,
|
||||
description: Some("Входные параметры для выбранного формата тела запроса".to_owned()),
|
||||
required: true,
|
||||
nullable: false,
|
||||
default_value: None,
|
||||
fields: BTreeMap::new(),
|
||||
items: None,
|
||||
enum_values: Vec::new(),
|
||||
variants,
|
||||
}
|
||||
}
|
||||
|
||||
fn closed_object_with_fields(
|
||||
description: Option<String>,
|
||||
fields: BTreeMap<String, crank_schema::Schema>,
|
||||
) -> crank_schema::Schema {
|
||||
let mut schema = object_with_fields(description, fields);
|
||||
schema.format = Some(crank_schema::CLOSED_OBJECT_SCHEMA_FORMAT.to_owned());
|
||||
schema
|
||||
}
|
||||
|
||||
fn request_contract(
|
||||
operation: &RestImportOperation,
|
||||
body_fields: &[BodyFieldMapping],
|
||||
) -> Option<RestRequestContract> {
|
||||
if operation.request_body_variants.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let body_field = body_fields
|
||||
.iter()
|
||||
.find(|field| field.body_path.is_empty() || field.body_path == "__body")?
|
||||
.input_name
|
||||
.clone();
|
||||
let selector_field = body_fields
|
||||
.iter()
|
||||
.find(|field| field.body_path == "__content_type")
|
||||
.map(|field| field.input_name.clone());
|
||||
Some(RestRequestContract {
|
||||
version: RestRequestContractVersion::V1,
|
||||
body_field,
|
||||
selector_field,
|
||||
body_required: operation
|
||||
.request_body_variants
|
||||
.iter()
|
||||
.any(|variant| variant.required),
|
||||
variants: operation
|
||||
.request_body_variants
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(schema_variant, variant)| RestRequestDescriptor {
|
||||
media_type: variant.content_type.clone(),
|
||||
schema_variant,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
|
||||
fn legacy_body_input_fields(
|
||||
request_body_schema: Option<&serde_json::Value>,
|
||||
used_names: &mut BTreeSet<String>,
|
||||
input_fields: &mut BTreeMap<String, crank_schema::Schema>,
|
||||
@@ -158,7 +456,6 @@ fn body_input_fields(
|
||||
required: true,
|
||||
}];
|
||||
}
|
||||
|
||||
let mut mappings = Vec::new();
|
||||
for (field_name, field_schema) in body_schema.fields {
|
||||
let input_name = unique_body_input_name(&field_name, used_names);
|
||||
@@ -172,6 +469,33 @@ fn body_input_fields(
|
||||
mappings
|
||||
}
|
||||
|
||||
fn unique_parameter_input_name(
|
||||
parameter: &crate::rest::model::RestImportParameter,
|
||||
used_names: &mut BTreeSet<String>,
|
||||
) -> String {
|
||||
let reserved = matches!(parameter.name.as_str(), "body" | "content_type");
|
||||
if !reserved && used_names.insert(parameter.name.clone()) {
|
||||
return parameter.name.clone();
|
||||
}
|
||||
unique_body_input_name(
|
||||
&format!(
|
||||
"{}_{}",
|
||||
parameter_location_name(parameter.location),
|
||||
parameter.name
|
||||
),
|
||||
used_names,
|
||||
)
|
||||
}
|
||||
|
||||
fn parameter_location_name(location: RestParameterLocation) -> &'static str {
|
||||
match location {
|
||||
RestParameterLocation::Path => "path",
|
||||
RestParameterLocation::Query => "query",
|
||||
RestParameterLocation::Header => "header",
|
||||
RestParameterLocation::Cookie => "cookie",
|
||||
}
|
||||
}
|
||||
|
||||
fn unique_body_input_name(name: &str, used_names: &mut BTreeSet<String>) -> String {
|
||||
if used_names.insert(name.to_owned()) {
|
||||
return name.to_owned();
|
||||
@@ -207,6 +531,8 @@ fn method_as_str(method: HttpMethod) -> &'static str {
|
||||
HttpMethod::Put => "PUT",
|
||||
HttpMethod::Patch => "PATCH",
|
||||
HttpMethod::Delete => "DELETE",
|
||||
HttpMethod::Head => "HEAD",
|
||||
HttpMethod::Options => "OPTIONS",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,6 +542,7 @@ fn safety_for_method(method: HttpMethod) -> OperationSafetyPolicy {
|
||||
HttpMethod::Get => OperationSafetyClass::Read,
|
||||
HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch => OperationSafetyClass::Write,
|
||||
HttpMethod::Delete => OperationSafetyClass::Destructive,
|
||||
HttpMethod::Head | HttpMethod::Options => OperationSafetyClass::Read,
|
||||
};
|
||||
OperationSafetyPolicy {
|
||||
class,
|
||||
|
||||
@@ -6,6 +6,7 @@ use serde_json::Value;
|
||||
pub fn any_object(description: Option<String>) -> Schema {
|
||||
Schema {
|
||||
kind: SchemaKind::Object,
|
||||
format: None,
|
||||
description,
|
||||
required: true,
|
||||
nullable: false,
|
||||
@@ -28,9 +29,26 @@ pub fn schema_from_openapi(
|
||||
value: Option<&Value>,
|
||||
required: bool,
|
||||
description: Option<String>,
|
||||
) -> Schema {
|
||||
schema_from_openapi_context(value, required, description, false)
|
||||
}
|
||||
|
||||
pub fn schema_from_multipart(
|
||||
value: Option<&Value>,
|
||||
required: bool,
|
||||
description: Option<String>,
|
||||
) -> Schema {
|
||||
schema_from_openapi_context(value, required, description, true)
|
||||
}
|
||||
|
||||
fn schema_from_openapi_context(
|
||||
value: Option<&Value>,
|
||||
required: bool,
|
||||
description: Option<String>,
|
||||
binary_envelopes: bool,
|
||||
) -> Schema {
|
||||
let Some(value) = value else {
|
||||
return primitive(SchemaKind::String, required, description);
|
||||
return primitive(SchemaKind::String, required, description, None);
|
||||
};
|
||||
// Only v3 NormalizedIR emits the private marker. Pending legacy-v1 jobs
|
||||
// retain their historical first-branch behavior, while modern oneOf/anyOf
|
||||
@@ -46,6 +64,7 @@ pub fn schema_from_openapi(
|
||||
{
|
||||
return Schema {
|
||||
kind: SchemaKind::Oneof,
|
||||
format: text(value, "format"),
|
||||
description: description.or_else(|| text(value, "description")),
|
||||
required,
|
||||
nullable: nullable(value),
|
||||
@@ -55,7 +74,7 @@ pub fn schema_from_openapi(
|
||||
enum_values: Vec::new(),
|
||||
variants: items
|
||||
.iter()
|
||||
.map(|item| schema_from_openapi(Some(item), true, None))
|
||||
.map(|item| schema_from_openapi_context(Some(item), true, None, binary_envelopes))
|
||||
.collect(),
|
||||
};
|
||||
}
|
||||
@@ -70,6 +89,7 @@ pub fn schema_from_openapi(
|
||||
if !enum_values.is_empty() {
|
||||
return Schema {
|
||||
kind: SchemaKind::Enum,
|
||||
format: text(&resolved, "format"),
|
||||
description: description.or_else(|| text(&resolved, "description")),
|
||||
required,
|
||||
nullable: nullable(&resolved),
|
||||
@@ -82,19 +102,31 @@ pub fn schema_from_openapi(
|
||||
}
|
||||
}
|
||||
|
||||
// OpenAPI binary/file fields use the frozen multipart envelope rather
|
||||
// than a path, URL, or base64 string. Arrays recurse through this branch
|
||||
// for each item and therefore expose the same object contract.
|
||||
if binary_envelopes && is_binary_file(&resolved) {
|
||||
return file_schema(
|
||||
required,
|
||||
description.or_else(|| text(&resolved, "description")),
|
||||
);
|
||||
}
|
||||
|
||||
match type_name(&resolved).unwrap_or("object") {
|
||||
"object" => object_schema(&resolved, required, description),
|
||||
"object" => object_schema(&resolved, required, description, binary_envelopes),
|
||||
"array" => Schema {
|
||||
kind: SchemaKind::Array,
|
||||
format: text(&resolved, "format"),
|
||||
description: description.or_else(|| text(&resolved, "description")),
|
||||
required,
|
||||
nullable: nullable(&resolved),
|
||||
default_value: resolved.get("default").cloned(),
|
||||
fields: BTreeMap::new(),
|
||||
items: Some(Box::new(schema_from_openapi(
|
||||
items: Some(Box::new(schema_from_openapi_context(
|
||||
resolved.get("items"),
|
||||
true,
|
||||
None,
|
||||
binary_envelopes,
|
||||
))),
|
||||
enum_values: Vec::new(),
|
||||
variants: Vec::new(),
|
||||
@@ -103,26 +135,31 @@ pub fn schema_from_openapi(
|
||||
SchemaKind::Integer,
|
||||
required,
|
||||
description.or_else(|| text(&resolved, "description")),
|
||||
Some(&resolved),
|
||||
),
|
||||
"number" => primitive(
|
||||
SchemaKind::Number,
|
||||
required,
|
||||
description.or_else(|| text(&resolved, "description")),
|
||||
Some(&resolved),
|
||||
),
|
||||
"boolean" => primitive(
|
||||
SchemaKind::Boolean,
|
||||
required,
|
||||
description.or_else(|| text(&resolved, "description")),
|
||||
Some(&resolved),
|
||||
),
|
||||
"null" => primitive(
|
||||
SchemaKind::Null,
|
||||
required,
|
||||
description.or_else(|| text(&resolved, "description")),
|
||||
Some(&resolved),
|
||||
),
|
||||
_ => primitive(
|
||||
SchemaKind::String,
|
||||
required,
|
||||
description.or_else(|| text(&resolved, "description")),
|
||||
Some(&resolved),
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -141,6 +178,7 @@ fn collapse_composition(value: &Value) -> Value {
|
||||
pub fn object_with_fields(description: Option<String>, fields: BTreeMap<String, Schema>) -> Schema {
|
||||
Schema {
|
||||
kind: SchemaKind::Object,
|
||||
format: None,
|
||||
description,
|
||||
required: true,
|
||||
nullable: false,
|
||||
@@ -152,7 +190,12 @@ pub fn object_with_fields(description: Option<String>, fields: BTreeMap<String,
|
||||
}
|
||||
}
|
||||
|
||||
fn object_schema(value: &Value, required: bool, description: Option<String>) -> Schema {
|
||||
fn object_schema(
|
||||
value: &Value,
|
||||
required: bool,
|
||||
description: Option<String>,
|
||||
binary_envelopes: bool,
|
||||
) -> Schema {
|
||||
let required_fields = value
|
||||
.get("required")
|
||||
.and_then(Value::as_array)
|
||||
@@ -169,10 +212,11 @@ fn object_schema(value: &Value, required: bool, description: Option<String>) ->
|
||||
for (name, schema) in properties {
|
||||
fields.insert(
|
||||
name.clone(),
|
||||
schema_from_openapi(
|
||||
schema_from_openapi_context(
|
||||
Some(schema),
|
||||
required_fields.contains(name.as_str()),
|
||||
text(schema, "description"),
|
||||
binary_envelopes,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -180,6 +224,7 @@ fn object_schema(value: &Value, required: bool, description: Option<String>) ->
|
||||
|
||||
Schema {
|
||||
kind: SchemaKind::Object,
|
||||
format: text(value, "format"),
|
||||
description: description.or_else(|| text(value, "description")),
|
||||
required,
|
||||
nullable: nullable(value),
|
||||
@@ -191,14 +236,54 @@ fn object_schema(value: &Value, required: bool, description: Option<String>) ->
|
||||
}
|
||||
}
|
||||
|
||||
fn primitive(kind: SchemaKind, required: bool, description: Option<String>) -> Schema {
|
||||
fn primitive(
|
||||
kind: SchemaKind,
|
||||
required: bool,
|
||||
description: Option<String>,
|
||||
value: Option<&Value>,
|
||||
) -> Schema {
|
||||
Schema {
|
||||
kind,
|
||||
format: value.and_then(|value| text(value, "format")),
|
||||
description,
|
||||
required,
|
||||
nullable: value.is_some_and(nullable),
|
||||
default_value: value.and_then(|value| value.get("default").cloned()),
|
||||
fields: BTreeMap::new(),
|
||||
items: None,
|
||||
enum_values: Vec::new(),
|
||||
variants: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_binary_file(value: &Value) -> bool {
|
||||
matches!(type_name(value), Some("file"))
|
||||
|| matches!(type_name(value), Some("string"))
|
||||
&& matches!(text(value, "format").as_deref(), Some("binary" | "file"))
|
||||
}
|
||||
|
||||
fn file_schema(required: bool, description: Option<String>) -> Schema {
|
||||
let mut fields = BTreeMap::new();
|
||||
fields.insert(
|
||||
"data_base64".to_owned(),
|
||||
primitive(SchemaKind::String, true, None, None),
|
||||
);
|
||||
fields.insert(
|
||||
"filename".to_owned(),
|
||||
primitive(SchemaKind::String, false, None, None),
|
||||
);
|
||||
fields.insert(
|
||||
"content_type".to_owned(),
|
||||
primitive(SchemaKind::String, false, None, None),
|
||||
);
|
||||
Schema {
|
||||
kind: SchemaKind::Object,
|
||||
format: Some("binary".to_owned()),
|
||||
description,
|
||||
required,
|
||||
nullable: false,
|
||||
default_value: None,
|
||||
fields: BTreeMap::new(),
|
||||
fields,
|
||||
items: None,
|
||||
enum_values: Vec::new(),
|
||||
variants: Vec::new(),
|
||||
|
||||
@@ -3,11 +3,11 @@ use serde_json::Value;
|
||||
|
||||
use crate::rest::{
|
||||
model::{
|
||||
ImportFinding, ImportFindingSeverity, RestImportDocument, RestImportOperation,
|
||||
RestImportParameter, RestParameterLocation,
|
||||
ImportFinding, RestImportDocument, RestImportOperation, RestImportParameter,
|
||||
RestParameterLocation, RestRequestBodyVariant, RestResponseVariant,
|
||||
},
|
||||
normalize::ImportParseError,
|
||||
recommendations::{document_blocker, document_finding, operation_finding},
|
||||
recommendations::{document_blocker, document_finding},
|
||||
};
|
||||
|
||||
pub fn parse_document(root: &Value) -> Result<RestImportDocument, ImportParseError> {
|
||||
@@ -23,6 +23,11 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
let servers = swagger_servers(root);
|
||||
let mut findings = Vec::new();
|
||||
let mut internal_finding_locations = Vec::new();
|
||||
append_parameter_findings(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
super::swagger2_findings::servers(root),
|
||||
);
|
||||
if servers.is_empty() {
|
||||
findings.push(document_finding(
|
||||
"missing_servers",
|
||||
@@ -41,13 +46,13 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
|
||||
for (path, path_item) in paths {
|
||||
if !path_item.is_object() {
|
||||
findings.push(path_item_blocker(path));
|
||||
findings.push(super::http_methods::invalid_path_item());
|
||||
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
|
||||
pointer: format!("/paths/{}", path.replace('~', "~0").replace('/', "~1")),
|
||||
}));
|
||||
continue;
|
||||
}
|
||||
for method_name in ["head", "options", "trace", "connect"] {
|
||||
for method_name in super::swagger2_findings::unsupported_methods(path_item) {
|
||||
if path_item.get(method_name).is_some() {
|
||||
findings.push(document_blocker(
|
||||
"unsupported_http_method",
|
||||
@@ -74,7 +79,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
path_parameters.findings,
|
||||
);
|
||||
let path_parameters = path_parameters.parameters;
|
||||
for method_name in ["get", "post", "put", "patch", "delete"] {
|
||||
for method_name in ["get", "post", "put", "patch", "delete", "head", "options"] {
|
||||
let Some(operation_value) = path_item.get(method_name) else {
|
||||
continue;
|
||||
};
|
||||
@@ -92,7 +97,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
}));
|
||||
continue;
|
||||
}
|
||||
let Some(method) = method_from_lower(method_name) else {
|
||||
let Some(method) = super::http_methods::from_lower(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let mut operation_parameters = path_parameters.clone();
|
||||
@@ -101,11 +106,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
operation_value.get("parameters"),
|
||||
&format!("{path_pointer}/{method_name}/parameters"),
|
||||
);
|
||||
append_parameter_findings(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
parsed_parameters.findings,
|
||||
);
|
||||
let parsed_parameter_findings = parsed_parameters.findings;
|
||||
operation_parameters.extend(parsed_parameters.parameters);
|
||||
deduplicate_parameters(&mut operation_parameters);
|
||||
let tags = tags(
|
||||
@@ -117,6 +118,13 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
&mut internal_finding_locations,
|
||||
tags.findings,
|
||||
);
|
||||
let request_body_variants = swagger_request_body_variants(
|
||||
root,
|
||||
path_item,
|
||||
operation_value,
|
||||
&path_pointer,
|
||||
&format!("{path_pointer}/{method_name}"),
|
||||
);
|
||||
let request_body_schema = operation_parameters
|
||||
.iter()
|
||||
.find(|parameter| parameter.name == "body")
|
||||
@@ -135,6 +143,19 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
.filter(|parameter| parameter.name != "body")
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||
let mut located_operation_findings =
|
||||
super::swagger2_findings::operation(root, operation_value, &operation_pointer);
|
||||
located_operation_findings.extend(parsed_parameter_findings);
|
||||
located_operation_findings.extend(super::swagger2_findings::path_parameters(
|
||||
path,
|
||||
&operation_parameters,
|
||||
));
|
||||
let (operation_findings, internal_finding_locations) =
|
||||
located_operation_findings.into_iter().unzip();
|
||||
let response_schema = (method != HttpMethod::Head)
|
||||
.then(|| response_schema(operation_value, &operation_pointer))
|
||||
.flatten();
|
||||
operations.push(RestImportOperation {
|
||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||
method,
|
||||
@@ -157,18 +178,18 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
.as_ref()
|
||||
.map(|(schema, _)| schema.clone()),
|
||||
request_body_schema_location: request_body_schema.map(|(_, location)| location),
|
||||
response_schema: response_schema(
|
||||
request_body_variants,
|
||||
response_schema: response_schema.as_ref().map(|(schema, _)| schema.clone()),
|
||||
response_schema_location: response_schema.map(|(_, location)| location),
|
||||
response_variants: swagger_response_variants(
|
||||
root,
|
||||
operation_value,
|
||||
&format!("{path_pointer}/{method_name}"),
|
||||
)
|
||||
.map(|(schema, _)| schema),
|
||||
response_schema_location: response_schema(
|
||||
operation_value,
|
||||
&format!("{path_pointer}/{method_name}"),
|
||||
)
|
||||
.map(|(_, location)| location),
|
||||
&operation_pointer,
|
||||
method,
|
||||
),
|
||||
servers: Vec::new(),
|
||||
findings: swagger_operation_findings(path, operation_value),
|
||||
findings: operation_findings,
|
||||
internal_finding_locations,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -221,7 +242,7 @@ pub fn parse_document_legacy_v1(root: &Value) -> Result<RestImportDocument, Impo
|
||||
let Some(operation) = path_item.get(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let Some(method) = method_from_lower(method_name) else {
|
||||
let Some(method) = super::http_methods::from_lower(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||
@@ -259,10 +280,13 @@ pub fn parse_document_legacy_v1(root: &Value) -> Result<RestImportDocument, Impo
|
||||
parameters,
|
||||
request_body_schema,
|
||||
request_body_schema_location: None,
|
||||
request_body_variants: Vec::new(),
|
||||
response_schema: legacy_response_schema(root, operation),
|
||||
response_schema_location: None,
|
||||
response_variants: Vec::new(),
|
||||
servers: Vec::new(),
|
||||
findings: swagger_operation_findings(path, operation),
|
||||
findings: super::swagger2_findings::legacy_operation(path, operation),
|
||||
internal_finding_locations: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -387,10 +411,24 @@ fn swagger_servers(root: &Value) -> Vec<String> {
|
||||
return Vec::new();
|
||||
};
|
||||
let base_path = root.get("basePath").and_then(Value::as_str).unwrap_or("");
|
||||
if host.is_empty()
|
||||
|| host.contains('@')
|
||||
|| host.chars().any(char::is_whitespace)
|
||||
|| (!base_path.is_empty() && !base_path.starts_with('/'))
|
||||
|| base_path.chars().any(char::is_control)
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
let schemes = root
|
||||
.get("schemes")
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.filter(|scheme| matches!(*scheme, "http" | "https"))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.filter(|items| !items.is_empty())
|
||||
.unwrap_or_else(|| vec!["https"]);
|
||||
|
||||
@@ -450,6 +488,14 @@ fn parameters(_root: &Value, value: Option<&Value>, base_pointer: &str) -> Parse
|
||||
}
|
||||
let item = item.clone();
|
||||
let raw_location = item.get("in").and_then(Value::as_str)?;
|
||||
let parameter_schema = swagger_parameter_schema(_root, &item);
|
||||
if parameter_schema.is_none() {
|
||||
findings.push(parameter_blocker(
|
||||
"missing_parameter_schema",
|
||||
"Swagger parameter не содержит schema/type.",
|
||||
&pointer,
|
||||
));
|
||||
}
|
||||
if raw_location == "body" {
|
||||
return Some(RestImportParameter {
|
||||
name: "body".to_owned(),
|
||||
@@ -473,6 +519,14 @@ fn parameters(_root: &Value, value: Option<&Value>, base_pointer: &str) -> Parse
|
||||
},
|
||||
});
|
||||
}
|
||||
if raw_location == "formData" {
|
||||
findings.extend(super::swagger2_findings::form_data_parameter(
|
||||
&item,
|
||||
parameter_schema.as_ref(),
|
||||
&pointer,
|
||||
));
|
||||
return None;
|
||||
}
|
||||
let location = match raw_location {
|
||||
"path" => RestParameterLocation::Path,
|
||||
"query" => RestParameterLocation::Query,
|
||||
@@ -494,14 +548,35 @@ fn parameters(_root: &Value, value: Option<&Value>, base_pointer: &str) -> Parse
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if parameter_schema.as_ref().is_some_and(|schema| {
|
||||
matches!(schema.get("type").and_then(Value::as_str), Some("array" | "object"))
|
||||
}) || item.get("collectionFormat").is_some()
|
||||
{
|
||||
let finding_pointer = if item.get("collectionFormat").is_some() {
|
||||
format!("{pointer}/collectionFormat")
|
||||
} else {
|
||||
pointer.clone()
|
||||
};
|
||||
findings.push(parameter_blocker(
|
||||
"unsupported_parameter_style",
|
||||
"Swagger array/object parameter serialization не поддерживается текущим REST mapping.",
|
||||
&finding_pointer,
|
||||
));
|
||||
}
|
||||
if let Some(schema) = swagger_parameter_schema(_root, &item) {
|
||||
super::openapi3_findings::schema_findings(
|
||||
&schema,
|
||||
&pointer,
|
||||
&mut findings,
|
||||
);
|
||||
}
|
||||
Some(RestImportParameter {
|
||||
name: item.get("name").and_then(Value::as_str)?.to_owned(),
|
||||
location,
|
||||
required: item
|
||||
.get("required")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
|| location == RestParameterLocation::Path,
|
||||
.unwrap_or(false),
|
||||
description: item
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
@@ -597,6 +672,10 @@ fn swagger_parameter_schema(_root: &Value, parameter: &Value) -> Option<Value> {
|
||||
schema.insert(key.to_owned(), value.clone());
|
||||
}
|
||||
}
|
||||
if schema.get("type").and_then(Value::as_str) == Some("file") {
|
||||
schema.insert("type".to_owned(), Value::String("string".to_owned()));
|
||||
schema.insert("format".to_owned(), Value::String("binary".to_owned()));
|
||||
}
|
||||
if schema.is_empty() {
|
||||
None
|
||||
} else {
|
||||
@@ -630,6 +709,266 @@ fn response_schema(
|
||||
.and_then(|response| response_schema_at(response, operation_pointer, "default"))
|
||||
}
|
||||
|
||||
fn swagger_request_body_variants(
|
||||
root: &Value,
|
||||
path_item: &Value,
|
||||
operation: &Value,
|
||||
path_pointer: &str,
|
||||
operation_pointer: &str,
|
||||
) -> Vec<RestRequestBodyVariant> {
|
||||
let parameters =
|
||||
effective_swagger_parameters(path_item, operation, path_pointer, operation_pointer);
|
||||
let body = parameters
|
||||
.iter()
|
||||
.find(|(parameter, _)| parameter.get("in").and_then(Value::as_str) == Some("body"));
|
||||
let form = swagger_form_data_schema(¶meters);
|
||||
let (schema, schema_source_location, schema_property_source_locations) =
|
||||
if let Some((body, pointer)) = body {
|
||||
let Some(schema) = body.get("schema").cloned() else {
|
||||
return Vec::new();
|
||||
};
|
||||
(
|
||||
schema,
|
||||
Some(crate::rest::model::SourceLocation {
|
||||
pointer: format!("{pointer}/schema"),
|
||||
}),
|
||||
Default::default(),
|
||||
)
|
||||
} else if let Some(form) = form {
|
||||
form
|
||||
} else {
|
||||
return Vec::new();
|
||||
};
|
||||
let required = body
|
||||
.and_then(|(parameter, _)| parameter.get("required").and_then(Value::as_bool))
|
||||
.unwrap_or_else(|| {
|
||||
parameters.iter().any(|(parameter, _)| {
|
||||
parameter.get("in").and_then(Value::as_str) == Some("formData")
|
||||
&& parameter
|
||||
.get("required")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
})
|
||||
});
|
||||
let content_types = effective_media_types(root, operation, "consumes", "application/json");
|
||||
content_types
|
||||
.into_iter()
|
||||
.filter(|content_type| supported_request_content_type(content_type))
|
||||
.map(|content_type| RestRequestBodyVariant {
|
||||
content_type,
|
||||
required,
|
||||
schema: Some(schema.clone()),
|
||||
multipart_field_mime_types: Default::default(),
|
||||
source_location: crate::rest::model::SourceLocation {
|
||||
pointer: schema_source_location
|
||||
.as_ref()
|
||||
.map(|location| location.pointer.trim_end_matches("/schema").to_owned())
|
||||
.unwrap_or_else(|| format!("{operation_pointer}/parameters")),
|
||||
},
|
||||
schema_source_location: schema_source_location.clone(),
|
||||
schema_property_source_locations: schema_property_source_locations.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn effective_swagger_parameters(
|
||||
path_item: &Value,
|
||||
operation: &Value,
|
||||
path_pointer: &str,
|
||||
operation_pointer: &str,
|
||||
) -> Vec<(Value, String)> {
|
||||
let mut parameters = Vec::new();
|
||||
for (owner, pointer) in [
|
||||
(path_item, format!("{path_pointer}/parameters")),
|
||||
(operation, format!("{operation_pointer}/parameters")),
|
||||
] {
|
||||
let Some(items) = owner.get("parameters").and_then(Value::as_array) else {
|
||||
continue;
|
||||
};
|
||||
for (index, parameter) in items.iter().enumerate() {
|
||||
let Some(name) = parameter.get("name").and_then(Value::as_str) else {
|
||||
continue;
|
||||
};
|
||||
let Some(location) = parameter.get("in").and_then(Value::as_str) else {
|
||||
continue;
|
||||
};
|
||||
parameters.retain(|(existing, _): &(Value, String)| {
|
||||
existing.get("name").and_then(Value::as_str) != Some(name)
|
||||
|| existing.get("in").and_then(Value::as_str) != Some(location)
|
||||
});
|
||||
parameters.push((parameter.clone(), format!("{pointer}/{index}")));
|
||||
}
|
||||
}
|
||||
parameters
|
||||
}
|
||||
|
||||
fn swagger_form_data_schema(
|
||||
parameters: &[(Value, String)],
|
||||
) -> Option<(
|
||||
Value,
|
||||
Option<crate::rest::model::SourceLocation>,
|
||||
std::collections::BTreeMap<String, crate::rest::model::SourceLocation>,
|
||||
)> {
|
||||
let form_parameters = parameters
|
||||
.iter()
|
||||
.filter(|(parameter, _)| parameter.get("in").and_then(Value::as_str) == Some("formData"));
|
||||
let mut properties = serde_json::Map::new();
|
||||
let mut required = Vec::new();
|
||||
let mut property_locations = std::collections::BTreeMap::new();
|
||||
let mut root_pointer = None;
|
||||
for (parameter, pointer) in form_parameters {
|
||||
let Some(name) = parameter.get("name").and_then(Value::as_str) else {
|
||||
continue;
|
||||
};
|
||||
root_pointer.get_or_insert_with(|| {
|
||||
pointer
|
||||
.rsplit_once('/')
|
||||
.map(|(parent, _)| parent.to_owned())
|
||||
.unwrap_or_else(|| pointer.clone())
|
||||
});
|
||||
property_locations.insert(
|
||||
name.to_owned(),
|
||||
crate::rest::model::SourceLocation {
|
||||
pointer: pointer.clone(),
|
||||
},
|
||||
);
|
||||
properties.insert(
|
||||
name.to_owned(),
|
||||
swagger_parameter_schema(&Value::Null, parameter)
|
||||
.unwrap_or_else(|| Value::Object(serde_json::Map::new())),
|
||||
);
|
||||
if parameter
|
||||
.get("required")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
required.push(Value::String(name.to_owned()));
|
||||
}
|
||||
}
|
||||
if properties.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut schema = serde_json::Map::new();
|
||||
schema.insert("type".to_owned(), Value::String("object".to_owned()));
|
||||
schema.insert("properties".to_owned(), Value::Object(properties));
|
||||
if !required.is_empty() {
|
||||
schema.insert("required".to_owned(), Value::Array(required));
|
||||
}
|
||||
Some((
|
||||
Value::Object(schema),
|
||||
root_pointer.map(|pointer| crate::rest::model::SourceLocation { pointer }),
|
||||
property_locations,
|
||||
))
|
||||
}
|
||||
|
||||
fn supported_request_content_type(content_type: &str) -> bool {
|
||||
content_type == "application/x-www-form-urlencoded"
|
||||
|| content_type == "multipart/form-data"
|
||||
|| content_type == "application/json"
|
||||
|| content_type.ends_with("+json")
|
||||
}
|
||||
|
||||
fn effective_media_types(
|
||||
root: &Value,
|
||||
operation: &Value,
|
||||
field: &str,
|
||||
default: &str,
|
||||
) -> Vec<String> {
|
||||
operation
|
||||
.get(field)
|
||||
.or_else(|| root.get(field))
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(ToOwned::to_owned)
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.filter(|items| !items.is_empty())
|
||||
.unwrap_or_else(|| vec![default.to_owned()])
|
||||
}
|
||||
|
||||
fn swagger_response_variants(
|
||||
root: &Value,
|
||||
operation: &Value,
|
||||
operation_pointer: &str,
|
||||
method: HttpMethod,
|
||||
) -> Vec<RestResponseVariant> {
|
||||
let Some(responses) = operation.get("responses").and_then(Value::as_object) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let produces = effective_media_types(root, operation, "produces", "application/json");
|
||||
let supported_produces = produces
|
||||
.iter()
|
||||
.filter(|content_type| supported_response_content_type(content_type))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let mut variants = responses
|
||||
.iter()
|
||||
.filter_map(|(code, response)| {
|
||||
let status_code = code
|
||||
.parse::<u16>()
|
||||
.ok()
|
||||
.filter(|code| (200..300).contains(code))?;
|
||||
let schema = response.get("schema").cloned();
|
||||
let pointer = format!(
|
||||
"{operation_pointer}/responses/{}",
|
||||
code.replace('~', "~0").replace('/', "~1")
|
||||
);
|
||||
if method == HttpMethod::Head {
|
||||
return Some(vec![RestResponseVariant {
|
||||
status_code,
|
||||
content_type: None,
|
||||
schema: None,
|
||||
source_location: crate::rest::model::SourceLocation { pointer },
|
||||
schema_source_location: None,
|
||||
}]);
|
||||
}
|
||||
if schema.is_none() {
|
||||
return Some(vec![RestResponseVariant {
|
||||
status_code,
|
||||
content_type: None,
|
||||
schema,
|
||||
source_location: crate::rest::model::SourceLocation { pointer },
|
||||
schema_source_location: None,
|
||||
}]);
|
||||
}
|
||||
if supported_produces.is_empty() {
|
||||
return Some(Vec::new());
|
||||
}
|
||||
Some(
|
||||
supported_produces
|
||||
.iter()
|
||||
.map(|content_type| RestResponseVariant {
|
||||
status_code,
|
||||
content_type: Some(content_type.clone()),
|
||||
schema: schema.clone(),
|
||||
source_location: crate::rest::model::SourceLocation {
|
||||
pointer: pointer.clone(),
|
||||
},
|
||||
schema_source_location: Some(crate::rest::model::SourceLocation {
|
||||
pointer: format!("{pointer}/schema"),
|
||||
}),
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
})
|
||||
.flatten()
|
||||
.collect::<Vec<_>>();
|
||||
variants.sort_by(|left, right| {
|
||||
(left.status_code, left.content_type.as_deref().unwrap_or("")).cmp(&(
|
||||
right.status_code,
|
||||
right.content_type.as_deref().unwrap_or(""),
|
||||
))
|
||||
});
|
||||
variants
|
||||
}
|
||||
|
||||
fn supported_response_content_type(content_type: &str) -> bool {
|
||||
content_type == "application/json" || content_type.ends_with("+json")
|
||||
}
|
||||
|
||||
fn response_schema_at(
|
||||
response: &Value,
|
||||
operation_pointer: &str,
|
||||
@@ -647,46 +986,3 @@ fn response_schema_at(
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn swagger_operation_findings(
|
||||
path: &str,
|
||||
operation: &Value,
|
||||
) -> Vec<crate::rest::model::ImportFinding> {
|
||||
let mut findings = Vec::new();
|
||||
if operation
|
||||
.get("consumes")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|items| {
|
||||
!items
|
||||
.iter()
|
||||
.any(|item| item.as_str().is_some_and(|value| value.contains("json")))
|
||||
})
|
||||
{
|
||||
findings.push(operation_finding(
|
||||
path,
|
||||
"unsupported_consumes",
|
||||
"Метод использует content type без JSON. Проверьте настройки тела запроса после импорта.",
|
||||
));
|
||||
}
|
||||
findings
|
||||
}
|
||||
|
||||
fn method_from_lower(value: &str) -> Option<HttpMethod> {
|
||||
match value {
|
||||
"get" => Some(HttpMethod::Get),
|
||||
"post" => Some(HttpMethod::Post),
|
||||
"put" => Some(HttpMethod::Put),
|
||||
"patch" => Some(HttpMethod::Patch),
|
||||
"delete" => Some(HttpMethod::Delete),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn path_item_blocker(_path: &str) -> ImportFinding {
|
||||
ImportFinding {
|
||||
code: "invalid_path_item".to_owned(),
|
||||
severity: ImportFindingSeverity::Error,
|
||||
message: "Path Item имеет неверную структуру и не был интерпретирован.".to_owned(),
|
||||
operation_key: None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::rest::{
|
||||
model::{ImportFinding, RestImportParameter, RestParameterLocation, SourceLocation},
|
||||
recommendations::{document_blocker, operation_finding},
|
||||
};
|
||||
|
||||
pub(super) fn servers(root: &Value) -> Vec<(ImportFinding, SourceLocation)> {
|
||||
let mut findings = Vec::new();
|
||||
if let Some(host) = root.get("host")
|
||||
&& (!host.is_string()
|
||||
|| host.as_str().is_some_and(|host| {
|
||||
host.is_empty() || host.contains('@') || host.chars().any(char::is_whitespace)
|
||||
}))
|
||||
{
|
||||
push(
|
||||
&mut findings,
|
||||
"invalid_server",
|
||||
"Swagger host неверен или содержит userinfo.",
|
||||
"/host",
|
||||
);
|
||||
}
|
||||
if let Some(base_path) = root.get("basePath")
|
||||
&& (!base_path.is_string()
|
||||
|| base_path.as_str().is_some_and(|path| {
|
||||
(!path.is_empty() && !path.starts_with('/')) || path.chars().any(char::is_control)
|
||||
}))
|
||||
{
|
||||
push(
|
||||
&mut findings,
|
||||
"invalid_server",
|
||||
"Swagger basePath имеет неверный формат.",
|
||||
"/basePath",
|
||||
);
|
||||
}
|
||||
if let Some(schemes) = root.get("schemes").and_then(Value::as_array) {
|
||||
for (index, scheme) in schemes.iter().enumerate() {
|
||||
if !scheme
|
||||
.as_str()
|
||||
.is_some_and(|scheme| matches!(scheme, "http" | "https"))
|
||||
{
|
||||
push(
|
||||
&mut findings,
|
||||
"invalid_server",
|
||||
"Swagger scheme должен быть http или https.",
|
||||
&format!("/schemes/{index}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
findings
|
||||
}
|
||||
|
||||
pub(super) fn operation(
|
||||
root: &Value,
|
||||
operation: &Value,
|
||||
operation_pointer: &str,
|
||||
) -> Vec<(ImportFinding, SourceLocation)> {
|
||||
let mut findings = Vec::new();
|
||||
for (media, location) in media_with_locations(root, operation, operation_pointer, "consumes") {
|
||||
if !supported_request_media(&media) {
|
||||
findings.push((
|
||||
document_blocker(
|
||||
"unsupported_consumes",
|
||||
format!("Content type запроса {media} не поддерживается."),
|
||||
),
|
||||
location,
|
||||
));
|
||||
}
|
||||
}
|
||||
for (media, location) in media_with_locations(root, operation, operation_pointer, "produces") {
|
||||
if !supported_response_media(&media) {
|
||||
findings.push((
|
||||
document_blocker(
|
||||
"unsupported_produces",
|
||||
format!("Content type ответа {media} не поддерживается."),
|
||||
),
|
||||
location,
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(responses) = operation.get("responses").and_then(Value::as_object) {
|
||||
for (status, response) in responses {
|
||||
if let Some(schema) = response.get("schema") {
|
||||
super::openapi3_findings::schema_findings(
|
||||
schema,
|
||||
&format!("{operation_pointer}/responses/{}/schema", escape(status)),
|
||||
&mut findings,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
findings
|
||||
}
|
||||
|
||||
pub(super) fn form_data_parameter(
|
||||
parameter: &Value,
|
||||
schema: Option<&Value>,
|
||||
pointer: &str,
|
||||
) -> Vec<(ImportFinding, SourceLocation)> {
|
||||
let Some(schema) = schema else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut findings = Vec::new();
|
||||
super::openapi3_findings::schema_findings(schema, pointer, &mut findings);
|
||||
super::openapi3_findings::form_field_schema_findings(schema, pointer, &mut findings);
|
||||
if schema.get("type").and_then(Value::as_str) == Some("array")
|
||||
&& parameter.get("collectionFormat").and_then(Value::as_str) != Some("multi")
|
||||
{
|
||||
let finding_pointer = parameter
|
||||
.get("collectionFormat")
|
||||
.map(|_| format!("{pointer}/collectionFormat"))
|
||||
.unwrap_or_else(|| pointer.to_owned());
|
||||
push(
|
||||
&mut findings,
|
||||
"unsupported_parameter_style",
|
||||
"Swagger formData array требует collectionFormat: multi; csv/default не соответствует repeat-key wire contract.",
|
||||
&finding_pointer,
|
||||
);
|
||||
}
|
||||
findings
|
||||
}
|
||||
|
||||
fn media_with_locations(
|
||||
root: &Value,
|
||||
operation: &Value,
|
||||
operation_pointer: &str,
|
||||
field: &str,
|
||||
) -> Vec<(String, SourceLocation)> {
|
||||
let (value, pointer) = if let Some(value) = operation.get(field) {
|
||||
(value, format!("{operation_pointer}/{field}"))
|
||||
} else if let Some(value) = root.get(field) {
|
||||
(value, format!("/{field}"))
|
||||
} else {
|
||||
return Vec::new();
|
||||
};
|
||||
value
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.enumerate()
|
||||
.filter_map(|(index, value)| {
|
||||
value.as_str().map(|value| {
|
||||
(
|
||||
value.to_owned(),
|
||||
SourceLocation {
|
||||
pointer: format!("{pointer}/{index}"),
|
||||
},
|
||||
)
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn legacy_operation(path: &str, operation: &Value) -> Vec<ImportFinding> {
|
||||
if operation
|
||||
.get("consumes")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|items| {
|
||||
!items
|
||||
.iter()
|
||||
.any(|item| item.as_str().is_some_and(|value| value.contains("json")))
|
||||
})
|
||||
{
|
||||
vec![operation_finding(
|
||||
path,
|
||||
"unsupported_consumes",
|
||||
"Метод использует content type без JSON. Проверьте настройки тела запроса после импорта.",
|
||||
)]
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn path_parameters(
|
||||
path: &str,
|
||||
parameters: &[RestImportParameter],
|
||||
) -> Vec<(ImportFinding, SourceLocation)> {
|
||||
parameters
|
||||
.iter()
|
||||
.filter(|parameter| parameter.location == RestParameterLocation::Path)
|
||||
.filter_map(|parameter| {
|
||||
let finding = if !parameter.required {
|
||||
Some((
|
||||
"path_parameter_not_required",
|
||||
format!("Path parameter {} должен быть required.", parameter.name),
|
||||
))
|
||||
} else if !path.contains(&format!("{{{}}}", parameter.name)) {
|
||||
Some((
|
||||
"path_parameter_placeholder_missing",
|
||||
format!(
|
||||
"Path parameter {} не имеет placeholder в пути.",
|
||||
parameter.name
|
||||
),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}?;
|
||||
Some((
|
||||
document_blocker(finding.0, finding.1),
|
||||
parameter.source_location.clone(),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn unsupported_methods(path_item: &Value) -> Vec<&str> {
|
||||
const NON_METHOD: &[&str] = &["$ref", "parameters"];
|
||||
const SUPPORTED: &[&str] = &["get", "post", "put", "patch", "delete", "head", "options"];
|
||||
path_item
|
||||
.as_object()
|
||||
.into_iter()
|
||||
.flat_map(|item| item.keys())
|
||||
.map(String::as_str)
|
||||
.filter(|name| {
|
||||
!name.starts_with("x-") && !NON_METHOD.contains(name) && !SUPPORTED.contains(name)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn supported_request_media(media: &str) -> bool {
|
||||
matches!(
|
||||
media,
|
||||
"application/json" | "application/x-www-form-urlencoded" | "multipart/form-data"
|
||||
) || media.ends_with("+json")
|
||||
}
|
||||
|
||||
fn supported_response_media(media: &str) -> bool {
|
||||
media == "application/json" || media.ends_with("+json")
|
||||
}
|
||||
|
||||
fn push(
|
||||
findings: &mut Vec<(ImportFinding, SourceLocation)>,
|
||||
code: &str,
|
||||
message: &str,
|
||||
pointer: &str,
|
||||
) {
|
||||
findings.push((
|
||||
document_blocker(code, message),
|
||||
SourceLocation {
|
||||
pointer: pointer.to_owned(),
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
fn escape(value: &str) -> String {
|
||||
value.replace('~', "~0").replace('/', "~1")
|
||||
}
|
||||
Reference in new issue
Block a user