feat(import): add deterministic OpenAPI normalized IR
This commit is contained in:
1 parent
bc03c33387
commit
6c2a3712d8
22 files changed
+6051
-352
No files matched your search
@@ -4,43 +4,156 @@ use serde_json::Value;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::rest::{
|
||||
model::{ImportGroupPreview, ImportPreview, RestImportDocument},
|
||||
model::{
|
||||
CoverageDisposition, CoverageEntry, 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,
|
||||
},
|
||||
openapi3,
|
||||
payload::candidate_from_operation,
|
||||
swagger2,
|
||||
};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
use super::normalize_coverage;
|
||||
use super::normalize_limits;
|
||||
|
||||
#[derive(Debug, Error, PartialEq, Eq)]
|
||||
pub enum ImportParseError {
|
||||
#[error("document is not valid YAML or JSON: {0}")]
|
||||
InvalidDocument(String),
|
||||
#[error("document is not valid YAML or JSON")]
|
||||
InvalidDocument,
|
||||
#[error("unsupported OpenAPI document")]
|
||||
UnsupportedDocument,
|
||||
#[error("OpenAPI document exceeds normalization limits")]
|
||||
LimitExceeded,
|
||||
#[error("OpenAPI document contains no supported operations")]
|
||||
NoMethods,
|
||||
}
|
||||
|
||||
pub fn preview_document(document: &str) -> Result<ImportPreview, ImportParseError> {
|
||||
let yaml: serde_yaml::Value = serde_yaml::from_str(document)
|
||||
.map_err(|error| ImportParseError::InvalidDocument(error.to_string()))?;
|
||||
let root = serde_json::to_value(yaml)
|
||||
.map_err(|error| ImportParseError::InvalidDocument(error.to_string()))?;
|
||||
let digest = SourceDigest::parse("0".repeat(64)).expect("fixed digest is valid");
|
||||
let ir = normalize_verified_document(document, digest, &NormalizationConfig::default())?;
|
||||
Ok(preview_from_ir(&ir))
|
||||
}
|
||||
|
||||
let normalized = if root.get("openapi").is_some() {
|
||||
openapi3::parse_document(&root)?
|
||||
} else if root.get("swagger").and_then(Value::as_str) == Some("2.0") {
|
||||
swagger2::parse_document(&root)?
|
||||
/// Compatibility projection for jobs created before `NormalizedIr`. It is
|
||||
/// deliberately isolated from the v2 pipeline and may be removed only after
|
||||
/// the import-job TTL has elapsed.
|
||||
pub fn preview_document_legacy_v1(document: &str) -> Result<ImportPreview, ImportParseError> {
|
||||
let root = decode_legacy_v1(document)?;
|
||||
let mut parsed = match root.get("openapi") {
|
||||
Some(_) => openapi3::parse_document_legacy_v1(&root)?,
|
||||
None if root.get("swagger").and_then(Value::as_str) == Some("2.0") => {
|
||||
swagger2::parse_document_legacy_v1(&root)?
|
||||
}
|
||||
None => return Err(ImportParseError::UnsupportedDocument),
|
||||
};
|
||||
for operation in &mut parsed.operations {
|
||||
for parameter in &mut operation.parameters {
|
||||
if let Some(schema) = parameter.schema.take() {
|
||||
parameter.schema = Some(resolve_local_ref(&root, &schema, 0));
|
||||
}
|
||||
}
|
||||
if let Some(schema) = operation.request_body_schema.take() {
|
||||
operation.request_body_schema = Some(resolve_local_ref(&root, &schema, 0));
|
||||
}
|
||||
if let Some(schema) = operation.response_schema.take() {
|
||||
operation.response_schema = Some(resolve_local_ref(&root, &schema, 0));
|
||||
}
|
||||
}
|
||||
Ok(preview_from_document(parsed))
|
||||
}
|
||||
|
||||
fn decode_legacy_v1(document: &str) -> Result<Value, ImportParseError> {
|
||||
let config = NormalizationConfig::default();
|
||||
if document.len() > config.max_bytes
|
||||
|| normalize_limits::alias_count(document) > config.max_aliases
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
let root = decode(document)?;
|
||||
validate_value_limits(&root, &config)?;
|
||||
Ok(root)
|
||||
}
|
||||
|
||||
pub fn normalize_verified_document(
|
||||
document: &str,
|
||||
digest: SourceDigest,
|
||||
config: &NormalizationConfig,
|
||||
) -> Result<NormalizedIr, ImportParseError> {
|
||||
config
|
||||
.validate_versions()
|
||||
.map_err(|_| ImportParseError::UnsupportedDocument)?;
|
||||
if document.len() > config.max_bytes
|
||||
|| normalize_limits::alias_count(document) > config.max_aliases
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
let source_syntax = if serde_json::from_str::<Value>(document).is_ok() {
|
||||
SourceSyntax::Json
|
||||
} else {
|
||||
return Err(ImportParseError::UnsupportedDocument);
|
||||
SourceSyntax::Yaml
|
||||
};
|
||||
let root = decode(document)?;
|
||||
validate_value_limits(&root, config)?;
|
||||
|
||||
let 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") => {
|
||||
swagger2::parse_document(&root)?
|
||||
}
|
||||
None => return Err(ImportParseError::UnsupportedDocument),
|
||||
};
|
||||
|
||||
Ok(preview_from_document(normalized))
|
||||
if parsed.operations.is_empty() {
|
||||
return Err(ImportParseError::NoMethods);
|
||||
}
|
||||
canonicalize(parsed, digest, config, root, source_syntax)
|
||||
}
|
||||
|
||||
pub fn preview_from_ir(ir: &NormalizedIr) -> ImportPreview {
|
||||
let operations = ir
|
||||
.operations
|
||||
.iter()
|
||||
.map(legacy_operation_from_normalized)
|
||||
.collect::<Vec<_>>();
|
||||
let findings = ir
|
||||
.findings
|
||||
.iter()
|
||||
.map(|finding| ImportFinding {
|
||||
code: finding.code.clone(),
|
||||
severity: finding.severity.clone(),
|
||||
message: finding.message.clone(),
|
||||
operation_key: finding.operation_key.clone(),
|
||||
})
|
||||
.collect();
|
||||
preview_from_operations(&ir.source, operations.iter(), findings)
|
||||
}
|
||||
|
||||
fn preview_from_document(document: RestImportDocument) -> ImportPreview {
|
||||
let source = ImportSourcePreview {
|
||||
format: document.format,
|
||||
version: document.version,
|
||||
title: document.title,
|
||||
servers: document.servers,
|
||||
};
|
||||
preview_from_operations(&source, document.operations.iter(), document.findings)
|
||||
}
|
||||
|
||||
fn preview_from_operations<'a>(
|
||||
source: &ImportSourcePreview,
|
||||
operations: impl Iterator<Item = &'a crate::rest::model::RestImportOperation>,
|
||||
mut findings: Vec<ImportFinding>,
|
||||
) -> ImportPreview {
|
||||
let mut groups: BTreeMap<String, ImportGroupPreview> = BTreeMap::new();
|
||||
let mut used_names = BTreeSet::new();
|
||||
|
||||
for operation in &document.operations {
|
||||
let candidate = candidate_from_operation(operation, &document.servers, &mut used_names);
|
||||
for operation in operations {
|
||||
let candidate = candidate_from_operation(operation, &source.servers, &mut used_names);
|
||||
let group_title = operation
|
||||
.tags
|
||||
.first()
|
||||
@@ -58,36 +171,674 @@ fn preview_from_document(document: RestImportDocument) -> ImportPreview {
|
||||
.push(candidate);
|
||||
}
|
||||
|
||||
sort_findings(&mut findings);
|
||||
ImportPreview {
|
||||
source: crate::rest::model::ImportSourcePreview {
|
||||
format: document.format,
|
||||
version: document.version,
|
||||
title: document.title,
|
||||
servers: document.servers,
|
||||
},
|
||||
source: source.clone(),
|
||||
groups: groups.into_values().collect(),
|
||||
findings: document.findings,
|
||||
findings,
|
||||
}
|
||||
}
|
||||
|
||||
fn decode(document: &str) -> Result<Value, ImportParseError> {
|
||||
if let Ok(json) = serde_json::from_str(document) {
|
||||
return Ok(json);
|
||||
}
|
||||
let yaml: serde_yaml::Value =
|
||||
serde_yaml::from_str(document).map_err(|_| ImportParseError::InvalidDocument)?;
|
||||
serde_json::to_value(yaml).map_err(|_| ImportParseError::InvalidDocument)
|
||||
}
|
||||
|
||||
fn supported_oas_version(version: &str) -> bool {
|
||||
["3.0.", "3.1."].into_iter().any(|prefix| {
|
||||
version.strip_prefix(prefix).is_some_and(|patch| {
|
||||
!patch.is_empty() && patch.bytes().all(|byte| byte.is_ascii_digit())
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn canonicalize(
|
||||
document: RestImportDocument,
|
||||
digest: SourceDigest,
|
||||
config: &NormalizationConfig,
|
||||
root: Value,
|
||||
source_syntax: SourceSyntax,
|
||||
) -> Result<NormalizedIr, ImportParseError> {
|
||||
let source = ImportSourcePreview {
|
||||
format: document.format,
|
||||
version: document.version,
|
||||
title: document.title,
|
||||
servers: document.servers,
|
||||
};
|
||||
let version = source.version.as_deref().unwrap_or("unknown");
|
||||
let mut coverage = Vec::new();
|
||||
let source_tree = normalize_coverage::canonical_source_tree(&root, "", &mut coverage);
|
||||
let unresolved_references = normalize_coverage::references_from_source_tree(&source_tree);
|
||||
coverage.extend(unresolved_references.iter().map(|reference| CoverageEntry {
|
||||
construct_id: reference.construct_id.clone(),
|
||||
location: reference.location.clone(),
|
||||
disposition: CoverageDisposition::Mapped,
|
||||
}));
|
||||
coverage.push(CoverageEntry {
|
||||
construct_id: "document".to_owned(),
|
||||
location: SourceLocation {
|
||||
pointer: String::new(),
|
||||
},
|
||||
disposition: CoverageDisposition::Mapped,
|
||||
});
|
||||
coverage.extend(normalize_coverage::server_coverage(
|
||||
&source,
|
||||
&source_tree,
|
||||
version,
|
||||
)?);
|
||||
let mut covered_paths = BTreeSet::new();
|
||||
let mut covered_parameters = BTreeSet::new();
|
||||
let internal_finding_locations = document.internal_finding_locations.clone();
|
||||
let mut findings = document
|
||||
.findings
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, finding)| {
|
||||
let location = internal_finding_locations.get(index).cloned().flatten();
|
||||
NormalizedFinding {
|
||||
code: finding.code.clone(),
|
||||
severity: finding.severity,
|
||||
message: finding.message,
|
||||
construct_id: location
|
||||
.as_ref()
|
||||
.map(|location| {
|
||||
if location.pointer.is_empty() {
|
||||
"document".to_owned()
|
||||
} else {
|
||||
format!("{version}:{}", location.pointer)
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| "document".to_owned()),
|
||||
location: location.unwrap_or(SourceLocation {
|
||||
pointer: String::new(),
|
||||
}),
|
||||
operation_key: finding.operation_key,
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut operations = document
|
||||
.operations
|
||||
.into_iter()
|
||||
.map(|operation| {
|
||||
let method = method_name(operation.method).to_ascii_lowercase();
|
||||
let pointer = format!(
|
||||
"/paths/{}/{}",
|
||||
normalize_coverage::escape_pointer(&operation.path),
|
||||
method
|
||||
);
|
||||
let stable_id = format!("{version}:{method}:{pointer}");
|
||||
let location = SourceLocation {
|
||||
pointer: pointer.clone(),
|
||||
};
|
||||
let mut operation_findings = Vec::new();
|
||||
if covered_paths.insert(operation.path.clone()) {
|
||||
coverage.push(CoverageEntry {
|
||||
construct_id: format!("{version}:path:{}", operation.path),
|
||||
location: SourceLocation {
|
||||
pointer: format!(
|
||||
"/paths/{}",
|
||||
normalize_coverage::escape_pointer(&operation.path)
|
||||
),
|
||||
},
|
||||
disposition: CoverageDisposition::Mapped,
|
||||
});
|
||||
}
|
||||
if operation
|
||||
.operation_id
|
||||
.as_deref()
|
||||
.is_some_and(|value| !value.trim().is_empty())
|
||||
{
|
||||
coverage.push(CoverageEntry {
|
||||
construct_id: format!("{stable_id}:operation_id"),
|
||||
location: SourceLocation {
|
||||
pointer: format!("{pointer}/operationId"),
|
||||
},
|
||||
disposition: CoverageDisposition::Mapped,
|
||||
});
|
||||
} else {
|
||||
operation_findings.push(NormalizedFinding {
|
||||
code: "missing_operation_id".to_owned(),
|
||||
severity: ImportFindingSeverity::Warning,
|
||||
message: "У метода нет operationId.".to_owned(),
|
||||
construct_id: format!("{stable_id}:operation_id"),
|
||||
location: SourceLocation {
|
||||
pointer: format!("{pointer}/operationId"),
|
||||
},
|
||||
operation_key: Some(operation.key.clone()),
|
||||
});
|
||||
coverage.push(CoverageEntry {
|
||||
construct_id: format!("{stable_id}:operation_id"),
|
||||
location: SourceLocation {
|
||||
pointer: format!("{pointer}/operationId"),
|
||||
},
|
||||
disposition: CoverageDisposition::Finding,
|
||||
});
|
||||
}
|
||||
for (index, location) in
|
||||
normalize_coverage::tag_locations(&root, &pointer, &operation.tags)?
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
coverage.push(CoverageEntry {
|
||||
construct_id: format!("{stable_id}:tag:{index}"),
|
||||
location,
|
||||
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()),
|
||||
}));
|
||||
let parameters = operation
|
||||
.parameters
|
||||
.into_iter()
|
||||
.map(|parameter| {
|
||||
let parameter_pointer = parameter.source_location.pointer;
|
||||
let parameter_id = format!(
|
||||
"parameter:{}",
|
||||
normalize_coverage::escape_pointer(¶meter_pointer)
|
||||
);
|
||||
if covered_parameters.insert(parameter_id.clone()) {
|
||||
coverage.push(CoverageEntry {
|
||||
construct_id: parameter_id.clone(),
|
||||
location: SourceLocation {
|
||||
pointer: parameter_pointer.clone(),
|
||||
},
|
||||
disposition: CoverageDisposition::Mapped,
|
||||
});
|
||||
}
|
||||
NormalizedParameter {
|
||||
name: parameter.name,
|
||||
location: parameter.location,
|
||||
required: parameter.required,
|
||||
description: parameter.description,
|
||||
schema: parameter.schema.as_ref().map(|schema| {
|
||||
normalize_coverage::typed_schema(
|
||||
schema,
|
||||
parameter
|
||||
.schema_source_location
|
||||
.as_ref()
|
||||
.map(|location| location.pointer.as_str())
|
||||
.unwrap_or(&format!("{parameter_pointer}/schema")),
|
||||
&format!("{parameter_id}:schema"),
|
||||
&mut coverage,
|
||||
)
|
||||
}),
|
||||
construct_id: parameter_id,
|
||||
source_location: SourceLocation {
|
||||
pointer: parameter_pointer,
|
||||
},
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let request_body_schema = operation.request_body_schema.as_ref().map(|schema| {
|
||||
let schema_location = operation
|
||||
.request_body_schema_location
|
||||
.as_ref()
|
||||
.cloned()
|
||||
.unwrap_or(SourceLocation {
|
||||
pointer: format!("{pointer}/requestBody"),
|
||||
});
|
||||
normalize_coverage::typed_schema(
|
||||
schema,
|
||||
&schema_location.pointer,
|
||||
&format!(
|
||||
"{stable_id}:request:{}",
|
||||
normalize_coverage::escape_pointer(&schema_location.pointer)
|
||||
),
|
||||
&mut coverage,
|
||||
)
|
||||
});
|
||||
let response_schema = operation.response_schema.as_ref().map(|schema| {
|
||||
let schema_location = operation
|
||||
.response_schema_location
|
||||
.as_ref()
|
||||
.cloned()
|
||||
.unwrap_or(SourceLocation {
|
||||
pointer: format!("{pointer}/responses"),
|
||||
});
|
||||
normalize_coverage::typed_schema(
|
||||
schema,
|
||||
&schema_location.pointer,
|
||||
&format!(
|
||||
"{stable_id}:response:{}",
|
||||
normalize_coverage::escape_pointer(&schema_location.pointer)
|
||||
),
|
||||
&mut coverage,
|
||||
)
|
||||
});
|
||||
if normalize_coverage::has_reference_schema(request_body_schema.as_ref())
|
||||
|| normalize_coverage::has_reference_schema(response_schema.as_ref())
|
||||
|| parameters.iter().any(|parameter| {
|
||||
normalize_coverage::has_reference_schema(parameter.schema.as_ref())
|
||||
})
|
||||
{
|
||||
operation_findings.push(NormalizedFinding {
|
||||
code: "unresolved_reference".to_owned(),
|
||||
severity: ImportFindingSeverity::Error,
|
||||
message: "Ссылка сохранена в NormalizedIR и будет разрешена отдельным этапом."
|
||||
.to_owned(),
|
||||
construct_id: stable_id.clone(),
|
||||
location: location.clone(),
|
||||
operation_key: Some(operation.key.clone()),
|
||||
});
|
||||
}
|
||||
coverage.push(CoverageEntry {
|
||||
construct_id: stable_id.clone(),
|
||||
location: location.clone(),
|
||||
disposition: CoverageDisposition::Mapped,
|
||||
});
|
||||
Ok::<_, ImportParseError>(NormalizedOperation {
|
||||
stable_id,
|
||||
location,
|
||||
key: operation.key,
|
||||
method: operation.method,
|
||||
path: operation.path,
|
||||
operation_id: operation.operation_id,
|
||||
summary: operation.summary,
|
||||
description: operation.description,
|
||||
tags: operation.tags,
|
||||
parameters,
|
||||
request_body_schema,
|
||||
response_schema,
|
||||
servers: operation.servers,
|
||||
findings: operation_findings,
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
operations.sort_by(|left, right| {
|
||||
(
|
||||
left.path.as_str(),
|
||||
method_rank(left.method),
|
||||
left.location.pointer.as_str(),
|
||||
)
|
||||
.cmp(&(
|
||||
right.path.as_str(),
|
||||
method_rank(right.method),
|
||||
right.location.pointer.as_str(),
|
||||
))
|
||||
});
|
||||
for operation in &mut operations {
|
||||
sort_normalized_findings(&mut operation.findings);
|
||||
}
|
||||
let mut operation_id_counts = BTreeMap::new();
|
||||
for operation in &operations {
|
||||
if let Some(operation_id) = operation
|
||||
.operation_id
|
||||
.as_deref()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
{
|
||||
*operation_id_counts
|
||||
.entry(operation_id.to_owned())
|
||||
.or_insert(0usize) += 1;
|
||||
}
|
||||
}
|
||||
for operation in &mut operations {
|
||||
if let Some(operation_id) = operation
|
||||
.operation_id
|
||||
.as_deref()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
&& operation_id_counts[operation_id] > 1
|
||||
{
|
||||
operation.findings.push(NormalizedFinding {
|
||||
code: "duplicate_operation_id".to_owned(),
|
||||
severity: ImportFindingSeverity::Warning,
|
||||
message: "operationId повторяется в документе.".to_owned(),
|
||||
construct_id: format!("{}:operation_id", operation.stable_id),
|
||||
location: SourceLocation {
|
||||
pointer: format!("{}/operationId", operation.location.pointer),
|
||||
},
|
||||
operation_key: Some(operation.key.clone()),
|
||||
});
|
||||
}
|
||||
sort_normalized_findings(&mut operation.findings);
|
||||
}
|
||||
// Resolution is deliberately deferred. References already represented by
|
||||
// an operation schema use that operation's blocker; all other references
|
||||
// need a document-level blocker so omitted object-level semantics can
|
||||
// never reach Apply silently.
|
||||
findings.extend(
|
||||
unresolved_references
|
||||
.iter()
|
||||
.filter(|reference| {
|
||||
!operations.iter().any(|operation| {
|
||||
operation
|
||||
.parameters
|
||||
.iter()
|
||||
.filter_map(|parameter| parameter.schema.as_ref())
|
||||
.chain(operation.request_body_schema.iter())
|
||||
.chain(operation.response_schema.iter())
|
||||
.any(|schema| schema_contains_reference(schema, &reference.location))
|
||||
})
|
||||
})
|
||||
.map(|reference| NormalizedFinding {
|
||||
code: "unresolved_reference".to_owned(),
|
||||
severity: ImportFindingSeverity::Error,
|
||||
message: "Ссылка требует разрешения перед применением импорта.".to_owned(),
|
||||
construct_id: reference.construct_id.clone(),
|
||||
location: reference.location.clone(),
|
||||
operation_key: None,
|
||||
}),
|
||||
);
|
||||
sort_normalized_findings(&mut findings);
|
||||
for finding in &findings {
|
||||
if !coverage.iter().any(|entry| {
|
||||
entry.construct_id == finding.construct_id
|
||||
&& entry.location == finding.location
|
||||
&& entry.disposition == CoverageDisposition::Mapped
|
||||
}) {
|
||||
coverage.push(CoverageEntry {
|
||||
construct_id: finding.construct_id.clone(),
|
||||
location: finding.location.clone(),
|
||||
disposition: CoverageDisposition::Finding,
|
||||
});
|
||||
}
|
||||
}
|
||||
coverage.sort_by(|left, right| {
|
||||
(
|
||||
left.construct_id.as_str(),
|
||||
left.location.pointer.as_str(),
|
||||
coverage_disposition_rank(&left.disposition),
|
||||
)
|
||||
.cmp(&(
|
||||
right.construct_id.as_str(),
|
||||
right.location.pointer.as_str(),
|
||||
coverage_disposition_rank(&right.disposition),
|
||||
))
|
||||
});
|
||||
coverage.dedup();
|
||||
|
||||
let ir = NormalizedIr {
|
||||
normalizer_version: config.normalizer_version.clone(),
|
||||
projection_version: config.projection_version.clone(),
|
||||
source_identity: SourceIdentity { digest },
|
||||
source_syntax,
|
||||
source_tree,
|
||||
metadata: NormalizedApiMetadata {
|
||||
title: source.title.clone(),
|
||||
version: root
|
||||
.pointer("/info/version")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
description: root
|
||||
.pointer("/info/description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
},
|
||||
base_path_candidates: root
|
||||
.get("basePath")
|
||||
.and_then(Value::as_str)
|
||||
.map(|value| vec![value.to_owned()])
|
||||
.unwrap_or_default(),
|
||||
paths: normalize_coverage::paths_from_operations(&operations, version),
|
||||
unresolved_references,
|
||||
source,
|
||||
operations,
|
||||
findings,
|
||||
coverage,
|
||||
};
|
||||
normalize_coverage::validate_coverage(&ir)?;
|
||||
Ok(ir)
|
||||
}
|
||||
|
||||
pub fn validate_normalized_ir(ir: &NormalizedIr) -> Result<(), ImportParseError> {
|
||||
if ir.normalizer_version != NORMALIZER_VERSION || ir.projection_version != PROJECTION_VERSION {
|
||||
return Err(ImportParseError::InvalidDocument);
|
||||
}
|
||||
normalize_coverage::validate_coverage(ir)
|
||||
}
|
||||
|
||||
fn coverage_disposition_rank(disposition: &CoverageDisposition) -> u8 {
|
||||
match disposition {
|
||||
CoverageDisposition::Mapped => 0,
|
||||
CoverageDisposition::Finding => 1,
|
||||
}
|
||||
}
|
||||
|
||||
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<_>>() })
|
||||
}
|
||||
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
|
||||
.as_deref()
|
||||
.is_some_and(|schema| schema_contains_reference(schema, location)),
|
||||
NormalizedSchemaKind::Composition { variants, .. } => variants
|
||||
.iter()
|
||||
.any(|schema| schema_contains_reference(schema, location)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_value_limits(
|
||||
value: &Value,
|
||||
config: &NormalizationConfig,
|
||||
) -> Result<(), ImportParseError> {
|
||||
fn visit(
|
||||
value: &Value,
|
||||
depth: usize,
|
||||
nodes: &mut usize,
|
||||
config: &NormalizationConfig,
|
||||
) -> Result<(), ImportParseError> {
|
||||
*nodes += 1;
|
||||
if depth > config.max_depth || *nodes > config.max_nodes {
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
match value {
|
||||
Value::String(text) if text.len() > config.max_scalar_bytes => {
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
}
|
||||
Value::Array(items) => {
|
||||
if items.len() > config.max_collection_items {
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
for item in items {
|
||||
visit(item, depth + 1, nodes, config)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Value::Object(object) => {
|
||||
if object.len() > config.max_collection_items {
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
for (key, item) in object {
|
||||
if key.len() > config.max_scalar_bytes {
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
visit(item, depth + 1, nodes, config)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
visit(value, 0, &mut 0, config)
|
||||
}
|
||||
|
||||
fn method_name(method: crank_core::HttpMethod) -> &'static str {
|
||||
match method {
|
||||
crank_core::HttpMethod::Get => "GET",
|
||||
crank_core::HttpMethod::Post => "POST",
|
||||
crank_core::HttpMethod::Put => "PUT",
|
||||
crank_core::HttpMethod::Patch => "PATCH",
|
||||
crank_core::HttpMethod::Delete => "DELETE",
|
||||
}
|
||||
}
|
||||
|
||||
fn method_rank(method: crank_core::HttpMethod) -> u8 {
|
||||
match method {
|
||||
crank_core::HttpMethod::Get => 0,
|
||||
crank_core::HttpMethod::Post => 1,
|
||||
crank_core::HttpMethod::Put => 2,
|
||||
crank_core::HttpMethod::Patch => 3,
|
||||
crank_core::HttpMethod::Delete => 4,
|
||||
}
|
||||
}
|
||||
|
||||
fn severity_rank(severity: &ImportFindingSeverity) -> u8 {
|
||||
match severity {
|
||||
ImportFindingSeverity::Error => 0,
|
||||
ImportFindingSeverity::Warning => 1,
|
||||
ImportFindingSeverity::Info => 2,
|
||||
}
|
||||
}
|
||||
|
||||
fn sort_findings(findings: &mut [ImportFinding]) {
|
||||
findings.sort_by(|left, right| {
|
||||
(
|
||||
severity_rank(&left.severity),
|
||||
left.operation_key.as_deref().unwrap_or(""),
|
||||
left.code.as_str(),
|
||||
)
|
||||
.cmp(&(
|
||||
severity_rank(&right.severity),
|
||||
right.operation_key.as_deref().unwrap_or(""),
|
||||
right.code.as_str(),
|
||||
))
|
||||
});
|
||||
}
|
||||
|
||||
fn sort_normalized_findings(findings: &mut [NormalizedFinding]) {
|
||||
findings.sort_by(|left, right| {
|
||||
(
|
||||
severity_rank(&left.severity),
|
||||
left.construct_id.as_str(),
|
||||
left.code.as_str(),
|
||||
)
|
||||
.cmp(&(
|
||||
severity_rank(&right.severity),
|
||||
right.construct_id.as_str(),
|
||||
right.code.as_str(),
|
||||
))
|
||||
});
|
||||
}
|
||||
|
||||
// Kept private for pending pre-v2 job replays. New normalization never calls
|
||||
// it: refs are represented above and are resolved only in Story 2.3.
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn resolve_local_ref(root: &Value, value: &Value, depth: usize) -> Value {
|
||||
if depth > 12 {
|
||||
return value.clone();
|
||||
}
|
||||
if let Some(reference) = value.get("$ref").and_then(Value::as_str) {
|
||||
if let Some(resolved) = pointer(root, reference) {
|
||||
return resolve_local_ref(root, resolved, depth + 1);
|
||||
}
|
||||
return value.clone();
|
||||
if let Some(reference) = value.get("$ref").and_then(Value::as_str)
|
||||
&& let Some(resolved) = pointer(root, reference)
|
||||
{
|
||||
return resolve_local_ref(root, resolved, depth + 1);
|
||||
}
|
||||
match value {
|
||||
Value::Object(map) => {
|
||||
let mut out = serde_json::Map::new();
|
||||
for (key, item) in map {
|
||||
out.insert(key.clone(), resolve_local_ref(root, item, depth + 1));
|
||||
}
|
||||
Value::Object(out)
|
||||
}
|
||||
Value::Object(map) => Value::Object(
|
||||
map.iter()
|
||||
.map(|(key, item)| (key.clone(), resolve_local_ref(root, item, depth + 1)))
|
||||
.collect(),
|
||||
),
|
||||
Value::Array(items) => Value::Array(
|
||||
items
|
||||
.iter()
|
||||
@@ -104,8 +855,7 @@ fn pointer<'a>(root: &'a Value, reference: &str) -> Option<&'a Value> {
|
||||
}
|
||||
let mut current = root;
|
||||
for part in reference.trim_start_matches("#/").split('/') {
|
||||
let part = part.replace("~1", "/").replace("~0", "~");
|
||||
current = current.get(&part)?;
|
||||
current = current.get(part.replace("~1", "/").replace("~0", "~"))?;
|
||||
}
|
||||
Some(current)
|
||||
}
|
||||
Reference in new issue
Block a user