Files
crank/crates/crank-import/src/rest/openapi3_findings.rs
T
bsodfather e93de7015a
CI / Rust Checks (pull_request) Failing after 1s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
feat(import): complete OpenAPI onboarding and verify delivery
2026-10-09 17:50:38 +03:00

530 lines
18 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 schema
.get("default")
.is_some_and(|value| value.is_object() || value.is_array())
{
push(
findings,
"unsupported_compound_default",
"Object и array schema defaults не поддерживаются executable import contract.",
&format!("{pointer}/default"),
);
}
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],
operation_pointer: &str,
) -> Vec<(ImportFinding, SourceLocation)> {
let mut findings = 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::<Vec<_>>();
for name in path_placeholders(path) {
if !parameters.iter().any(|parameter| {
parameter.location == RestParameterLocation::Path && parameter.name == name
}) {
findings.push((
document_blocker(
"path_parameter_not_declared",
format!("Path placeholder {name} не объявлен как path parameter."),
),
SourceLocation {
pointer: operation_pointer.to_owned(),
},
));
}
}
findings
}
fn path_placeholders(path: &str) -> Vec<String> {
let mut placeholders = Vec::new();
let mut remaining = path;
while let Some(open) = remaining.find('{') {
let after_open = &remaining[open + 1..];
let Some(close) = after_open.find('}') else {
break;
};
if close > 0 {
placeholders.push(after_open[..close].to_owned());
}
remaining = &after_open[close + 1..];
}
placeholders
}
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")
}