993 lines
39 KiB
Rust
993 lines
39 KiB
Rust
use crank_core::HttpMethod;
|
|
use serde_json::Value;
|
|
|
|
use super::parser_findings::append_unused_security_scheme_findings as append_unused;
|
|
use crate::rest::{
|
|
model::{
|
|
ImportFinding, RestImportDocument, RestImportOperation, RestImportParameter,
|
|
RestParameterLocation, RestRequestBodyVariant, RestResponseVariant,
|
|
},
|
|
normalize::ImportParseError,
|
|
recommendations::{document_blocker, document_finding},
|
|
};
|
|
|
|
pub fn parse_document(root: &Value) -> Result<RestImportDocument, ImportParseError> {
|
|
parse_document_v2(root)
|
|
}
|
|
|
|
fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseError> {
|
|
let security_schemes = super::security::schemes(root, false);
|
|
let version = root
|
|
.get("openapi")
|
|
.and_then(Value::as_str)
|
|
.map(ToOwned::to_owned);
|
|
let title = root
|
|
.pointer("/info/title")
|
|
.and_then(Value::as_str)
|
|
.unwrap_or("Imported API")
|
|
.to_owned();
|
|
let mut findings = Vec::new();
|
|
let mut locations = Vec::new();
|
|
let servers = parse_servers(root.get("servers"), "/servers");
|
|
super::parser_findings::append_located(&mut findings, &mut locations, servers.findings);
|
|
let servers = servers.servers;
|
|
if servers.is_empty() {
|
|
findings.push(document_finding(
|
|
"missing_servers",
|
|
"В документе не указаны servers, base URL нужно будет выбрать вручную.",
|
|
));
|
|
locations.push(Some(crate::rest::model::SourceLocation {
|
|
pointer: String::new(),
|
|
}));
|
|
} else if servers.len() > 1 {
|
|
findings.push(document_finding(
|
|
"multiple_servers",
|
|
"В документе несколько servers, при импорте нужно выбрать нужный base URL.",
|
|
));
|
|
locations.push(Some(crate::rest::model::SourceLocation {
|
|
pointer: "/servers".to_owned(),
|
|
}));
|
|
}
|
|
|
|
let mut operations = Vec::new();
|
|
let paths = root
|
|
.get("paths")
|
|
.and_then(Value::as_object)
|
|
.ok_or(ImportParseError::UnsupportedDocument)?;
|
|
|
|
for (path, path_item) in paths {
|
|
if !path_item.is_object() {
|
|
findings.push(super::http_methods::invalid_path_item());
|
|
locations.push(Some(crate::rest::model::SourceLocation {
|
|
pointer: format!("/paths/{}", path.replace('~', "~0").replace('/', "~1")),
|
|
}));
|
|
continue;
|
|
}
|
|
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",
|
|
format!("Метод {method_name} для пути {path} пока не поддерживается."),
|
|
));
|
|
locations.push(Some(crate::rest::model::SourceLocation {
|
|
pointer: format!(
|
|
"/paths/{}/{}",
|
|
path.replace('~', "~0").replace('/', "~1"),
|
|
method_name
|
|
),
|
|
}));
|
|
}
|
|
}
|
|
let path_pointer = format!("/paths/{}", path.replace('~', "~0").replace('/', "~1"));
|
|
let path_parameters = parameters(
|
|
path_item.get("parameters"),
|
|
&format!("{path_pointer}/parameters"),
|
|
);
|
|
super::parser_findings::append_located(
|
|
&mut findings,
|
|
&mut locations,
|
|
path_parameters.findings,
|
|
);
|
|
let path_parameters = path_parameters.parameters;
|
|
let path_servers =
|
|
parse_servers(path_item.get("servers"), &format!("{path_pointer}/servers"));
|
|
super::parser_findings::append_located(
|
|
&mut findings,
|
|
&mut locations,
|
|
path_servers.findings,
|
|
);
|
|
let path_servers = path_servers.servers;
|
|
for method_name in ["get", "post", "put", "patch", "delete", "head", "options"] {
|
|
let Some(operation_value) = path_item.get(method_name) else {
|
|
continue;
|
|
};
|
|
if !operation_value.is_object() {
|
|
findings.push(document_blocker(
|
|
"invalid_operation",
|
|
"Операция имеет неверную структуру и не была интерпретирована.",
|
|
));
|
|
locations.push(Some(crate::rest::model::SourceLocation {
|
|
pointer: format!(
|
|
"/paths/{}/{}",
|
|
path.replace('~', "~0").replace('/', "~1"),
|
|
method_name
|
|
),
|
|
}));
|
|
continue;
|
|
}
|
|
let Some(method) = super::http_methods::from_lower(method_name) else {
|
|
continue;
|
|
};
|
|
let operation_pointer = format!("{path_pointer}/{method_name}");
|
|
|
|
let mut operation_parameters = path_parameters.clone();
|
|
let parsed_parameters = parameters(
|
|
operation_value.get("parameters"),
|
|
&format!("{path_pointer}/{method_name}/parameters"),
|
|
);
|
|
super::parser_findings::append_located(
|
|
&mut findings,
|
|
&mut locations,
|
|
parsed_parameters.findings,
|
|
);
|
|
operation_parameters.extend(parsed_parameters.parameters);
|
|
deduplicate_parameters(&mut operation_parameters);
|
|
let operation_servers = parse_servers(
|
|
operation_value.get("servers"),
|
|
&format!("{operation_pointer}/servers"),
|
|
);
|
|
super::parser_findings::append_located(
|
|
&mut findings,
|
|
&mut locations,
|
|
operation_servers.findings,
|
|
);
|
|
let operation_servers = operation_servers.servers;
|
|
let tags = tags(
|
|
operation_value.get("tags"),
|
|
&format!("{operation_pointer}/tags"),
|
|
);
|
|
super::parser_findings::append_located(&mut findings, &mut locations, tags.findings);
|
|
|
|
let mut located_operation_findings =
|
|
super::openapi3_findings::operation(operation_value, &operation_pointer);
|
|
let (security_requirements, security_findings) =
|
|
super::security::collect_operation_requirements(
|
|
root,
|
|
operation_value,
|
|
&operation_pointer,
|
|
&security_schemes,
|
|
);
|
|
located_operation_findings.extend(security_findings);
|
|
located_operation_findings.extend(super::openapi3_findings::path_parameters(
|
|
path,
|
|
&operation_parameters,
|
|
));
|
|
let (operation_findings, 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,
|
|
path: path.clone(),
|
|
source_location: None,
|
|
security_requirements,
|
|
operation_id: operation_value
|
|
.get("operationId")
|
|
.and_then(Value::as_str)
|
|
.map(ToOwned::to_owned),
|
|
summary: operation_value
|
|
.get("summary")
|
|
.and_then(Value::as_str)
|
|
.map(ToOwned::to_owned),
|
|
description: operation_value
|
|
.get("description")
|
|
.and_then(Value::as_str)
|
|
.map(ToOwned::to_owned),
|
|
tags: tags.tags,
|
|
parameters: operation_parameters,
|
|
request_body_schema: request_body_schema(operation_value, &operation_pointer)
|
|
.map(|(schema, _)| schema),
|
|
request_body_schema_location: request_body_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,
|
|
internal_finding_locations: locations,
|
|
});
|
|
}
|
|
}
|
|
append_unused(root, &security_schemes, &mut findings, &mut locations);
|
|
Ok(RestImportDocument {
|
|
format: "openapi".to_owned(),
|
|
version,
|
|
title,
|
|
servers,
|
|
security_schemes,
|
|
operations,
|
|
findings,
|
|
internal_finding_locations: locations,
|
|
})
|
|
}
|
|
|
|
fn deduplicate_parameters(parameters: &mut Vec<RestImportParameter>) {
|
|
let mut seen = std::collections::BTreeSet::new();
|
|
parameters.reverse();
|
|
parameters.retain(|parameter| seen.insert((parameter.name.clone(), parameter.location)));
|
|
parameters.reverse();
|
|
}
|
|
|
|
pub fn parse_document_legacy_v1(root: &Value) -> Result<RestImportDocument, ImportParseError> {
|
|
let version = root
|
|
.get("openapi")
|
|
.and_then(Value::as_str)
|
|
.map(ToOwned::to_owned);
|
|
let title = root
|
|
.pointer("/info/title")
|
|
.and_then(Value::as_str)
|
|
.unwrap_or("Imported API")
|
|
.to_owned();
|
|
let servers = legacy_servers(root.get("servers"));
|
|
let mut findings = Vec::new();
|
|
if servers.is_empty() {
|
|
findings.push(document_finding(
|
|
"missing_servers",
|
|
"В документе не указаны servers, base URL нужно будет выбрать вручную.",
|
|
));
|
|
} else if servers.len() > 1 {
|
|
findings.push(document_finding(
|
|
"multiple_servers",
|
|
"В документе несколько servers, при импорте нужно выбрать нужный base URL.",
|
|
));
|
|
}
|
|
|
|
let mut operations = Vec::new();
|
|
let paths = root
|
|
.get("paths")
|
|
.and_then(Value::as_object)
|
|
.ok_or(ImportParseError::UnsupportedDocument)?;
|
|
for (path, path_item) in paths {
|
|
let path_pointer = format!("/paths/{}", path.replace('~', "~0").replace('/', "~1"));
|
|
let path_parameters = legacy_parameters(
|
|
root,
|
|
path_item.get("parameters"),
|
|
&format!("{path_pointer}/parameters"),
|
|
);
|
|
for method_name in ["get", "post", "put", "patch", "delete"] {
|
|
let Some(operation) = path_item.get(method_name) else {
|
|
continue;
|
|
};
|
|
let Some(method) = super::http_methods::from_lower(method_name) else {
|
|
continue;
|
|
};
|
|
let operation_pointer = format!("{path_pointer}/{method_name}");
|
|
let mut parameters = path_parameters.clone();
|
|
parameters.extend(legacy_parameters(
|
|
root,
|
|
operation.get("parameters"),
|
|
&format!("{operation_pointer}/parameters"),
|
|
));
|
|
operations.push(RestImportOperation {
|
|
key: format!("{} {}", method_name.to_uppercase(), path),
|
|
method,
|
|
path: path.clone(),
|
|
source_location: None,
|
|
security_requirements: Default::default(),
|
|
operation_id: operation
|
|
.get("operationId")
|
|
.and_then(Value::as_str)
|
|
.map(ToOwned::to_owned),
|
|
summary: operation
|
|
.get("summary")
|
|
.and_then(Value::as_str)
|
|
.map(ToOwned::to_owned),
|
|
description: operation
|
|
.get("description")
|
|
.and_then(Value::as_str)
|
|
.map(ToOwned::to_owned),
|
|
tags: legacy_tags(operation.get("tags")),
|
|
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(),
|
|
});
|
|
}
|
|
}
|
|
Ok(RestImportDocument {
|
|
format: "openapi".to_owned(),
|
|
version,
|
|
title,
|
|
servers,
|
|
security_schemes: Default::default(),
|
|
operations,
|
|
findings,
|
|
internal_finding_locations: Vec::new(),
|
|
})
|
|
}
|
|
|
|
fn legacy_servers(value: Option<&Value>) -> Vec<String> {
|
|
value
|
|
.and_then(Value::as_array)
|
|
.map(|items| {
|
|
items
|
|
.iter()
|
|
.filter_map(|item| item.get("url").and_then(Value::as_str))
|
|
.map(|url| url.trim_end_matches('/').to_owned())
|
|
.collect()
|
|
})
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
fn legacy_tags(value: Option<&Value>) -> Vec<String> {
|
|
value
|
|
.and_then(Value::as_array)
|
|
.map(|items| {
|
|
items
|
|
.iter()
|
|
.filter_map(Value::as_str)
|
|
.map(ToOwned::to_owned)
|
|
.collect()
|
|
})
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
fn legacy_parameters(
|
|
root: &Value,
|
|
value: Option<&Value>,
|
|
base_pointer: &str,
|
|
) -> Vec<RestImportParameter> {
|
|
value
|
|
.and_then(Value::as_array)
|
|
.map(|items| {
|
|
items
|
|
.iter()
|
|
.enumerate()
|
|
.filter_map(|(index, item)| {
|
|
let item = crate::rest::normalize::resolve_local_ref(root, item, 0);
|
|
let location = match item.get("in").and_then(Value::as_str)? {
|
|
"path" => RestParameterLocation::Path,
|
|
"query" => RestParameterLocation::Query,
|
|
"header" => RestParameterLocation::Header,
|
|
_ => return None,
|
|
};
|
|
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,
|
|
description: item
|
|
.get("description")
|
|
.and_then(Value::as_str)
|
|
.map(ToOwned::to_owned),
|
|
schema: item.get("schema").map(|schema| {
|
|
crate::rest::normalize::resolve_local_ref(root, schema, 0)
|
|
}),
|
|
source_location: crate::rest::model::SourceLocation {
|
|
pointer: format!("{base_pointer}/{index}"),
|
|
},
|
|
schema_source_location: None,
|
|
})
|
|
})
|
|
.collect()
|
|
})
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
fn legacy_request_body_schema(root: &Value, operation: &Value) -> Option<Value> {
|
|
let body = crate::rest::normalize::resolve_local_ref(root, operation.get("requestBody")?, 0);
|
|
let content = body.get("content")?.as_object()?;
|
|
for content_type in ["application/json", "application/*+json"] {
|
|
if let Some(schema) = content
|
|
.get(content_type)
|
|
.and_then(|media| media.get("schema"))
|
|
{
|
|
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
|
}
|
|
}
|
|
content
|
|
.iter()
|
|
.find(|(content_type, _)| content_type.contains("json"))
|
|
.and_then(|(_, media)| media.get("schema"))
|
|
.map(|schema| crate::rest::normalize::resolve_local_ref(root, schema, 0))
|
|
}
|
|
|
|
fn legacy_response_schema(root: &Value, operation: &Value) -> Option<Value> {
|
|
let responses = operation.get("responses")?.as_object()?;
|
|
for code in ["200", "201", "202", "default"] {
|
|
let Some(response) = responses.get(code) else {
|
|
continue;
|
|
};
|
|
let response = crate::rest::normalize::resolve_local_ref(root, response, 0);
|
|
let Some(content) = response.get("content").and_then(Value::as_object) else {
|
|
continue;
|
|
};
|
|
for content_type in ["application/json", "application/*+json"] {
|
|
if let Some(schema) = content
|
|
.get(content_type)
|
|
.and_then(|media| media.get("schema"))
|
|
{
|
|
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
|
}
|
|
}
|
|
if let Some(schema) = content
|
|
.iter()
|
|
.find(|(content_type, _)| content_type.contains("json"))
|
|
.and_then(|(_, media)| media.get("schema"))
|
|
{
|
|
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
fn legacy_operation_findings(operation: &Value) -> Vec<ImportFinding> {
|
|
if operation.get("requestBody").is_some()
|
|
&& legacy_request_body_schema(&Value::Null, operation).is_none()
|
|
{
|
|
vec![document_finding(
|
|
"unsupported_request_body",
|
|
"У метода есть requestBody, но JSON schema не найдена.",
|
|
)]
|
|
} else {
|
|
Vec::new()
|
|
}
|
|
}
|
|
|
|
struct ParsedParameters {
|
|
parameters: Vec<RestImportParameter>,
|
|
findings: Vec<(ImportFinding, crate::rest::model::SourceLocation)>,
|
|
}
|
|
|
|
struct ParsedServers {
|
|
servers: Vec<String>,
|
|
findings: Vec<(ImportFinding, crate::rest::model::SourceLocation)>,
|
|
}
|
|
|
|
fn parse_servers(value: Option<&Value>, base_pointer: &str) -> ParsedServers {
|
|
let mut findings = Vec::new();
|
|
let servers = value
|
|
.and_then(Value::as_array)
|
|
.map(|items| {
|
|
items
|
|
.iter()
|
|
.enumerate()
|
|
.filter_map(|(index, item)| {
|
|
let pointer = format!("{base_pointer}/{index}");
|
|
let Some(object) = item.as_object() else {
|
|
findings.push(server_blocker(&pointer));
|
|
return None;
|
|
};
|
|
let Some(url) = object.get("url").and_then(Value::as_str) else {
|
|
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()
|
|
})
|
|
.unwrap_or_default();
|
|
ParsedServers { servers, findings }
|
|
}
|
|
|
|
struct ParsedTags {
|
|
tags: Vec<String>,
|
|
findings: Vec<(ImportFinding, crate::rest::model::SourceLocation)>,
|
|
}
|
|
|
|
fn tags(value: Option<&Value>, base_pointer: &str) -> ParsedTags {
|
|
let mut findings = Vec::new();
|
|
let tags = value
|
|
.and_then(Value::as_array)
|
|
.map(|items| {
|
|
items
|
|
.iter()
|
|
.enumerate()
|
|
.filter_map(|(index, item)| match item.as_str() {
|
|
Some(tag) => Some(tag.to_owned()),
|
|
None => {
|
|
findings.push((
|
|
document_finding(
|
|
"invalid_tag",
|
|
"Тег должен быть строкой и не был импортирован.",
|
|
),
|
|
crate::rest::model::SourceLocation {
|
|
pointer: format!("{base_pointer}/{index}"),
|
|
},
|
|
));
|
|
None
|
|
}
|
|
})
|
|
.collect()
|
|
})
|
|
.unwrap_or_default();
|
|
ParsedTags { tags, findings }
|
|
}
|
|
|
|
fn server_blocker(pointer: &str) -> (ImportFinding, crate::rest::model::SourceLocation) {
|
|
(
|
|
document_blocker(
|
|
"invalid_server",
|
|
"Server должен быть объектом со строковым url и не был импортирован.",
|
|
),
|
|
crate::rest::model::SourceLocation {
|
|
pointer: pointer.to_owned(),
|
|
},
|
|
)
|
|
}
|
|
|
|
fn parameters(value: Option<&Value>, base_pointer: &str) -> ParsedParameters {
|
|
let mut findings = Vec::new();
|
|
let parameters = value
|
|
.and_then(Value::as_array)
|
|
.map(|items| {
|
|
items
|
|
.iter()
|
|
.enumerate()
|
|
.filter_map(|(index, item)| {
|
|
let pointer = format!("{base_pointer}/{index}");
|
|
let Some(object) = item.as_object() else {
|
|
findings.push(parameter_blocker(
|
|
"invalid_parameter",
|
|
"Параметр должен быть объектом и не был интерпретирован.",
|
|
&pointer,
|
|
));
|
|
return None;
|
|
};
|
|
if object.contains_key("$ref") {
|
|
findings.push(parameter_blocker(
|
|
"unresolved_parameter_reference",
|
|
"Параметр по $ref требует разрешения перед импортом.",
|
|
&pointer,
|
|
));
|
|
return None;
|
|
}
|
|
if !object.get("name").is_some_and(Value::is_string) {
|
|
findings.push(parameter_blocker(
|
|
"missing_parameter_name",
|
|
"У параметра отсутствует строковое поле name.",
|
|
&pointer,
|
|
));
|
|
return None;
|
|
}
|
|
if !object.get("in").is_some_and(Value::is_string) {
|
|
findings.push(parameter_blocker(
|
|
"missing_parameter_location",
|
|
"У параметра отсутствует строковое поле in.",
|
|
&pointer,
|
|
));
|
|
return None;
|
|
}
|
|
let item = item.clone();
|
|
let location = match item.get("in").and_then(Value::as_str)? {
|
|
"path" => RestParameterLocation::Path,
|
|
"query" => RestParameterLocation::Query,
|
|
"header" => RestParameterLocation::Header,
|
|
"cookie" => RestParameterLocation::Cookie,
|
|
_ => {
|
|
findings.push(parameter_blocker(
|
|
"unsupported_parameter_location",
|
|
"Параметр использует неподдерживаемое значение in и не был импортирован.",
|
|
&pointer,
|
|
));
|
|
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),
|
|
description: item
|
|
.get("description")
|
|
.and_then(Value::as_str)
|
|
.map(ToOwned::to_owned),
|
|
schema: item.get("schema").cloned(),
|
|
schema_source_location: item.get("schema").map(|_| {
|
|
crate::rest::model::SourceLocation {
|
|
pointer: format!("{base_pointer}/{index}/schema"),
|
|
}
|
|
}),
|
|
source_location: crate::rest::model::SourceLocation {
|
|
pointer,
|
|
},
|
|
})
|
|
})
|
|
.collect()
|
|
})
|
|
.unwrap_or_default();
|
|
ParsedParameters {
|
|
parameters,
|
|
findings,
|
|
}
|
|
}
|
|
|
|
fn parameter_blocker(
|
|
code: &str,
|
|
message: &str,
|
|
pointer: &str,
|
|
) -> (ImportFinding, crate::rest::model::SourceLocation) {
|
|
(
|
|
document_blocker(code, message),
|
|
crate::rest::model::SourceLocation {
|
|
pointer: pointer.to_owned(),
|
|
},
|
|
)
|
|
}
|
|
|
|
fn request_body_schema(
|
|
operation: &Value,
|
|
operation_pointer: &str,
|
|
) -> Option<(Value, crate::rest::model::SourceLocation)> {
|
|
let body = operation.get("requestBody")?;
|
|
let content = body.get("content")?.as_object()?;
|
|
for content_type in ["application/json", "application/*+json"] {
|
|
if let Some(schema) = content
|
|
.get(content_type)
|
|
.and_then(|media| media.get("schema"))
|
|
{
|
|
return Some((
|
|
schema.clone(),
|
|
crate::rest::model::SourceLocation {
|
|
pointer: format!(
|
|
"{operation_pointer}/requestBody/content/{}/schema",
|
|
content_type.replace('~', "~0").replace('/', "~1")
|
|
),
|
|
},
|
|
));
|
|
}
|
|
}
|
|
content
|
|
.iter()
|
|
.find(|(content_type, _)| content_type.contains("json"))
|
|
.and_then(|(content_type, media)| {
|
|
media.get("schema").cloned().map(|schema| {
|
|
(
|
|
schema,
|
|
crate::rest::model::SourceLocation {
|
|
pointer: format!(
|
|
"{operation_pointer}/requestBody/content/{}/schema",
|
|
content_type.replace('~', "~0").replace('/', "~1")
|
|
),
|
|
},
|
|
)
|
|
})
|
|
})
|
|
}
|
|
|
|
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,
|
|
) -> Option<(Value, crate::rest::model::SourceLocation)> {
|
|
let responses = operation.get("responses")?.as_object()?;
|
|
let mut numeric = responses
|
|
.iter()
|
|
.filter_map(|(code, response)| {
|
|
(code.len() == 3)
|
|
.then(|| code.parse::<u16>().ok())
|
|
.flatten()
|
|
.filter(|status| (200..300).contains(status))
|
|
.map(|status| (status, code.as_str(), response))
|
|
})
|
|
.collect::<Vec<_>>();
|
|
numeric.sort_by(|left, right| (left.0, left.1).cmp(&(right.0, right.1)));
|
|
for (_, code, response) in numeric {
|
|
if let Some(schema) = response_json_schema(response, operation_pointer, code) {
|
|
return Some(schema);
|
|
}
|
|
}
|
|
|
|
let mut wildcard = responses
|
|
.iter()
|
|
.filter(|(code, _)| code.eq_ignore_ascii_case("2xx"))
|
|
.collect::<Vec<_>>();
|
|
wildcard.sort_by(|left, right| left.0.cmp(right.0));
|
|
for (code, response) in wildcard {
|
|
if let Some(schema) = response_json_schema(response, operation_pointer, code) {
|
|
return Some(schema);
|
|
}
|
|
}
|
|
|
|
responses
|
|
.get("default")
|
|
.and_then(|response| response_json_schema(response, operation_pointer, "default"))
|
|
}
|
|
|
|
fn response_json_schema(
|
|
response: &Value,
|
|
operation_pointer: &str,
|
|
code: &str,
|
|
) -> Option<(Value, crate::rest::model::SourceLocation)> {
|
|
let content = response.get("content")?.as_object()?;
|
|
for content_type in ["application/json", "application/*+json"] {
|
|
if let Some(schema) = content
|
|
.get(content_type)
|
|
.and_then(|media| media.get("schema"))
|
|
{
|
|
return Some((
|
|
schema.clone(),
|
|
crate::rest::model::SourceLocation {
|
|
pointer: format!(
|
|
"{operation_pointer}/responses/{}/content/{}/schema",
|
|
code.replace('~', "~0").replace('/', "~1"),
|
|
content_type.replace('~', "~0").replace('/', "~1")
|
|
),
|
|
},
|
|
));
|
|
}
|
|
}
|
|
content
|
|
.iter()
|
|
.find(|(content_type, _)| content_type.contains("json"))
|
|
.and_then(|(content_type, media)| {
|
|
media.get("schema").map(|schema| {
|
|
(
|
|
schema.clone(),
|
|
crate::rest::model::SourceLocation {
|
|
pointer: format!(
|
|
"{operation_pointer}/responses/{}/content/{}/schema",
|
|
code.replace('~', "~0").replace('/', "~1"),
|
|
content_type.replace('~', "~0").replace('/', "~1")
|
|
),
|
|
},
|
|
)
|
|
})
|
|
})
|
|
}
|
|
|
|
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
|
|
}
|