feat(import): bind OpenAPI security schemes safely
This commit is contained in:
1 parent
c562d5368d
commit
41a0e46110
38 files changed
+4651
-590
No files matched your search
@@ -127,6 +127,8 @@ pub fn candidate_from_operation(
|
||||
key: operation.key.clone(),
|
||||
method: operation.method,
|
||||
path: operation.path.clone(),
|
||||
security_requirements: Default::default(),
|
||||
security_schemes: Default::default(),
|
||||
operation_id: operation.operation_id.clone(),
|
||||
suggested_name: name,
|
||||
suggested_display_name: display_name,
|
||||
|
||||
@@ -3,33 +3,41 @@ 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_preview;
|
||||
mod normalize_projection;
|
||||
mod normalize_schema;
|
||||
mod openapi3;
|
||||
mod openapi3_findings;
|
||||
mod openapi3_legacy;
|
||||
mod payload;
|
||||
mod recommendations;
|
||||
mod reference;
|
||||
mod schema;
|
||||
mod security;
|
||||
mod security_literals;
|
||||
mod swagger2;
|
||||
mod swagger2_findings;
|
||||
mod swagger2_legacy;
|
||||
|
||||
pub use model::{
|
||||
ExternalDocumentSnapshot, ImportFinding, ImportFindingSeverity, ImportGroupPreview,
|
||||
ImportOperationCandidate, ImportPreview, ImportSourcePreview, NORMALIZER_VERSION,
|
||||
NormalizationConfig, NormalizedFinding, NormalizedIr, NormalizedOperation, NormalizedParameter,
|
||||
NormalizedReference, NormalizedRequestBodyVariant, NormalizedResponseVariant, NormalizedSchema,
|
||||
NormalizedSchemaConstraints, NormalizedSchemaKind, PROJECTION_VERSION, ResolvedReferenceEdge,
|
||||
ResolvedReferenceGraph, ResolvedReferenceNode, RestImportCandidate, RestImportDocument,
|
||||
RestImportOperation, RestImportParameter, RestParameterLocation, RestRequestBodyVariant,
|
||||
RestResponseVariant, SourceDigest, SourceIdentity, SourceLocation, UnresolvedReference,
|
||||
ExternalDocumentSnapshot, HISTORICAL_NORMALIZER_VERSION, HISTORICAL_PROJECTION_VERSION,
|
||||
ImportFinding, ImportFindingSeverity, ImportGroupPreview, ImportOperationCandidate,
|
||||
ImportPreview, ImportSourcePreview, NORMALIZER_VERSION, NormalizationConfig, NormalizedFinding,
|
||||
NormalizedIr, NormalizedOperation, NormalizedParameter, NormalizedReference,
|
||||
NormalizedRequestBodyVariant, NormalizedResponseVariant, NormalizedSchema,
|
||||
NormalizedSchemaConstraints, NormalizedSchemaKind, NormalizedSecurityRequirements,
|
||||
NormalizedSecurityScheme, NormalizedSecuritySchemeKind, PROJECTION_VERSION,
|
||||
ResolvedReferenceEdge, ResolvedReferenceGraph, ResolvedReferenceNode, RestImportCandidate,
|
||||
RestImportDocument, RestImportOperation, RestImportParameter, RestParameterLocation,
|
||||
RestRequestBodyVariant, RestResponseVariant, SecurityParameterLocation,
|
||||
SecurityRequirementAlternative, SecurityRequirementsSource, SourceDigest, SourceIdentity,
|
||||
SourceLocation, UnresolvedReference,
|
||||
};
|
||||
pub use normalize::{
|
||||
ImportParseError, external_reference_uris, normalize_verified_bundle,
|
||||
@@ -37,3 +45,4 @@ pub use normalize::{
|
||||
reference_uris, validate_normalized_ir,
|
||||
};
|
||||
pub use payload::operation_draft_from_candidate;
|
||||
pub use security_literals::{SecretLiteralFinding, scan_secret_literals};
|
||||
@@ -9,8 +9,10 @@ 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-v4";
|
||||
pub const PROJECTION_VERSION: &str = "preview-v4";
|
||||
pub const NORMALIZER_VERSION: &str = "normalized-ir-v5";
|
||||
pub const PROJECTION_VERSION: &str = "preview-v5";
|
||||
pub const HISTORICAL_NORMALIZER_VERSION: &str = "normalized-ir-v4";
|
||||
pub const HISTORICAL_PROJECTION_VERSION: &str = "preview-v4";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
|
||||
pub struct SourceDigest(String);
|
||||
@@ -232,6 +234,13 @@ pub struct NormalizedOperation {
|
||||
pub key: String,
|
||||
pub method: HttpMethod,
|
||||
pub path: String,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "NormalizedSecurityRequirements::is_empty"
|
||||
)]
|
||||
pub security_requirements: NormalizedSecurityRequirements,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub security_schemes: BTreeMap<String, NormalizedSecurityScheme>,
|
||||
pub operation_id: Option<String>,
|
||||
pub summary: Option<String>,
|
||||
pub description: Option<String>,
|
||||
@@ -251,6 +260,81 @@ pub struct NormalizedOperation {
|
||||
pub findings: Vec<NormalizedFinding>,
|
||||
}
|
||||
|
||||
/// A supported OpenAPI/Swagger authentication scheme, without credential values.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct NormalizedSecurityScheme {
|
||||
pub name: String,
|
||||
pub kind: NormalizedSecuritySchemeKind,
|
||||
pub source_location: SourceLocation,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case", tag = "kind")]
|
||||
pub enum NormalizedSecuritySchemeKind {
|
||||
Http {
|
||||
scheme: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
format_hint: Option<String>,
|
||||
},
|
||||
ApiKey {
|
||||
location: SecurityParameterLocation,
|
||||
parameter_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
format_hint: Option<String>,
|
||||
},
|
||||
Unsupported {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
scheme_type: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum SecurityParameterLocation {
|
||||
Header,
|
||||
Query,
|
||||
Cookie,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub struct NormalizedSecurityRequirements {
|
||||
pub source: SecurityRequirementsSource,
|
||||
/// Each item is one OR alternative; names within an alternative are ANDed.
|
||||
#[serde(default)]
|
||||
pub alternatives: Vec<SecurityRequirementAlternative>,
|
||||
}
|
||||
|
||||
impl NormalizedSecurityRequirements {
|
||||
fn is_empty(&self) -> bool {
|
||||
self.source == SecurityRequirementsSource::None && self.alternatives.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum SecurityRequirementsSource {
|
||||
#[default]
|
||||
None,
|
||||
Document,
|
||||
Operation,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub struct SecurityRequirementAlternative {
|
||||
#[serde(default)]
|
||||
pub schemes: Vec<String>,
|
||||
#[serde(default = "default_supported_security_alternative")]
|
||||
pub supported: bool,
|
||||
#[serde(default)]
|
||||
pub findings: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub source_location: Option<SourceLocation>,
|
||||
}
|
||||
|
||||
fn default_supported_security_alternative() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct NormalizedRequestBodyVariant {
|
||||
pub content_type: String,
|
||||
@@ -387,6 +471,8 @@ pub struct NormalizedIr {
|
||||
#[serde(default)]
|
||||
pub reference_graph: ResolvedReferenceGraph,
|
||||
pub source: ImportSourcePreview,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub security_schemes: BTreeMap<String, NormalizedSecurityScheme>,
|
||||
#[serde(default)]
|
||||
pub operations: Vec<NormalizedOperation>,
|
||||
#[serde(default)]
|
||||
@@ -442,6 +528,13 @@ pub struct ImportOperationCandidate {
|
||||
pub key: String,
|
||||
pub method: HttpMethod,
|
||||
pub path: String,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "NormalizedSecurityRequirements::is_empty"
|
||||
)]
|
||||
pub security_requirements: NormalizedSecurityRequirements,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub security_schemes: BTreeMap<String, NormalizedSecurityScheme>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub operation_id: Option<String>,
|
||||
pub suggested_name: String,
|
||||
@@ -477,6 +570,8 @@ pub struct RestImportDocument {
|
||||
pub version: Option<String>,
|
||||
pub title: String,
|
||||
pub servers: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub security_schemes: BTreeMap<String, NormalizedSecurityScheme>,
|
||||
pub operations: Vec<RestImportOperation>,
|
||||
pub findings: Vec<ImportFinding>,
|
||||
#[serde(skip)]
|
||||
@@ -488,6 +583,11 @@ pub struct RestImportOperation {
|
||||
pub key: String,
|
||||
pub method: HttpMethod,
|
||||
pub path: String,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "NormalizedSecurityRequirements::is_empty"
|
||||
)]
|
||||
pub security_requirements: NormalizedSecurityRequirements,
|
||||
pub operation_id: Option<String>,
|
||||
pub summary: Option<String>,
|
||||
pub description: Option<String>,
|
||||
|
||||
@@ -6,15 +6,13 @@ use thiserror::Error;
|
||||
use crate::rest::{
|
||||
model::{
|
||||
CoverageDisposition, CoverageEntry, ExternalDocumentSnapshot, ImportFinding,
|
||||
ImportFindingSeverity, ImportGroupPreview, ImportPreview, ImportSourcePreview,
|
||||
NORMALIZER_VERSION, NormalizationConfig, NormalizedApiMetadata, NormalizedFinding,
|
||||
NormalizedIr, NormalizedOperation, NormalizedParameter, NormalizedRequestBodyVariant,
|
||||
ImportFindingSeverity, ImportPreview, ImportSourcePreview, NORMALIZER_VERSION,
|
||||
NormalizationConfig, NormalizedApiMetadata, NormalizedFinding, NormalizedIr,
|
||||
NormalizedOperation, NormalizedParameter, NormalizedRequestBodyVariant,
|
||||
NormalizedResponseVariant, NormalizedSchema, NormalizedSchemaKind, PROJECTION_VERSION,
|
||||
RestImportDocument, SourceDigest, SourceIdentity, SourceLocation, SourceSyntax,
|
||||
},
|
||||
openapi3,
|
||||
payload::candidate_from_operation,
|
||||
swagger2,
|
||||
openapi3, swagger2,
|
||||
};
|
||||
|
||||
use super::normalize_coverage;
|
||||
@@ -63,9 +61,9 @@ pub fn external_reference_uris(
|
||||
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)?,
|
||||
Some(_) => super::openapi3_legacy::parse_document_legacy_v1(&root)?,
|
||||
None if root.get("swagger").and_then(Value::as_str) == Some("2.0") => {
|
||||
swagger2::parse_document_legacy_v1(&root)?
|
||||
super::swagger2_legacy::parse_document_legacy_v1(&root)?
|
||||
}
|
||||
None => return Err(ImportParseError::UnsupportedDocument),
|
||||
};
|
||||
@@ -82,7 +80,7 @@ pub fn preview_document_legacy_v1(document: &str) -> Result<ImportPreview, Impor
|
||||
operation.response_schema = Some(resolve_local_ref(&root, &schema, 0));
|
||||
}
|
||||
}
|
||||
Ok(preview_from_document(parsed))
|
||||
Ok(super::normalize_preview::preview_from_document(parsed))
|
||||
}
|
||||
|
||||
fn decode_legacy_v1(document: &str) -> Result<Value, ImportParseError> {
|
||||
@@ -135,9 +133,11 @@ pub fn normalize_verified_bundle(
|
||||
}
|
||||
}
|
||||
let resolution = super::reference::resolve(root, digest.clone(), snapshots, config)?;
|
||||
let root = resolution.root;
|
||||
let mut root = resolution.root;
|
||||
validate_value_limits(&root, config)?;
|
||||
|
||||
let redacted_literals = super::security_literals::inspect_and_redact(&mut root);
|
||||
|
||||
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),
|
||||
@@ -146,13 +146,15 @@ 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,
|
||||
);
|
||||
for literal in redacted_literals {
|
||||
parsed.findings.push(super::recommendations::document_finding(
|
||||
"secret_literal_redacted",
|
||||
"Документ содержит literal credential; значение удалено из normalized representation.",
|
||||
));
|
||||
parsed
|
||||
.internal_finding_locations
|
||||
.push(Some(literal.location));
|
||||
}
|
||||
|
||||
if parsed.operations.is_empty()
|
||||
&& !parsed
|
||||
@@ -174,79 +176,10 @@ pub fn normalize_verified_bundle(
|
||||
}
|
||||
|
||||
pub fn preview_from_ir(ir: &NormalizedIr) -> ImportPreview {
|
||||
let operations = ir
|
||||
.operations
|
||||
.iter()
|
||||
.map(super::normalize_projection::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, false)
|
||||
super::normalize_preview::preview_from_ir(ir)
|
||||
}
|
||||
|
||||
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, 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 = 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()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "Без группы".to_owned());
|
||||
let group_key = crate::rest::naming::snake_name(&group_title);
|
||||
groups
|
||||
.entry(group_key.clone())
|
||||
.or_insert_with(|| ImportGroupPreview {
|
||||
key: group_key,
|
||||
title: group_title,
|
||||
operations: Vec::new(),
|
||||
})
|
||||
.operations
|
||||
.push(candidate);
|
||||
}
|
||||
|
||||
sort_findings(&mut findings);
|
||||
ImportPreview {
|
||||
source: source.clone(),
|
||||
groups: groups.into_values().collect(),
|
||||
findings,
|
||||
}
|
||||
}
|
||||
|
||||
fn decode(document: &str) -> Result<Value, ImportParseError> {
|
||||
pub(super) fn decode(document: &str) -> Result<Value, ImportParseError> {
|
||||
if let Ok(json) = serde_json::from_str(document) {
|
||||
return Ok(json);
|
||||
}
|
||||
@@ -272,6 +205,7 @@ fn canonicalize(
|
||||
reference_graph: crate::rest::model::ResolvedReferenceGraph,
|
||||
resolution_findings: Vec<NormalizedFinding>,
|
||||
) -> Result<NormalizedIr, ImportParseError> {
|
||||
let security_schemes = document.security_schemes.clone();
|
||||
let source = ImportSourcePreview {
|
||||
format: document.format,
|
||||
version: document.version,
|
||||
@@ -571,6 +505,8 @@ fn canonicalize(
|
||||
key: operation.key,
|
||||
method: operation.method,
|
||||
path: operation.path,
|
||||
security_requirements: operation.security_requirements,
|
||||
security_schemes: security_schemes.clone(),
|
||||
operation_id: operation.operation_id,
|
||||
summary: operation.summary,
|
||||
description: operation.description,
|
||||
@@ -762,6 +698,7 @@ fn canonicalize(
|
||||
unresolved_references,
|
||||
reference_graph,
|
||||
source,
|
||||
security_schemes: document.security_schemes,
|
||||
operations,
|
||||
findings,
|
||||
coverage,
|
||||
@@ -771,7 +708,11 @@ fn canonicalize(
|
||||
}
|
||||
|
||||
pub fn validate_normalized_ir(ir: &NormalizedIr) -> Result<(), ImportParseError> {
|
||||
if ir.normalizer_version != NORMALIZER_VERSION || ir.projection_version != PROJECTION_VERSION {
|
||||
let current =
|
||||
ir.normalizer_version == NORMALIZER_VERSION && ir.projection_version == PROJECTION_VERSION;
|
||||
let historical_v4 = ir.normalizer_version == super::model::HISTORICAL_NORMALIZER_VERSION
|
||||
&& ir.projection_version == super::model::HISTORICAL_PROJECTION_VERSION;
|
||||
if !current && !historical_v4 {
|
||||
return Err(ImportParseError::InvalidDocument);
|
||||
}
|
||||
validate_reference_graph(ir)?;
|
||||
@@ -924,7 +865,7 @@ fn severity_rank(severity: &ImportFindingSeverity) -> u8 {
|
||||
}
|
||||
}
|
||||
|
||||
fn sort_findings(findings: &mut [ImportFinding]) {
|
||||
pub(super) fn sort_findings(findings: &mut [ImportFinding]) {
|
||||
findings.sort_by(|left, right| {
|
||||
(
|
||||
severity_rank(&left.severity),
|
||||
|
||||
@@ -16,7 +16,11 @@ pub(super) use super::normalize_schema::{
|
||||
};
|
||||
|
||||
pub(super) fn validate_coverage(ir: &NormalizedIr) -> Result<(), ImportParseError> {
|
||||
if ir.normalizer_version != NORMALIZER_VERSION || ir.projection_version != PROJECTION_VERSION {
|
||||
let current =
|
||||
ir.normalizer_version == NORMALIZER_VERSION && ir.projection_version == PROJECTION_VERSION;
|
||||
let historical_v4 = ir.normalizer_version == super::model::HISTORICAL_NORMALIZER_VERSION
|
||||
&& ir.projection_version == super::model::HISTORICAL_PROJECTION_VERSION;
|
||||
if !current && !historical_v4 {
|
||||
return Err(ImportParseError::InvalidDocument);
|
||||
}
|
||||
let mut source_nodes = BTreeMap::new();
|
||||
@@ -94,6 +98,12 @@ pub(super) fn validate_coverage(ir: &NormalizedIr) -> Result<(), ImportParseErro
|
||||
.flat_map(|operation| &operation.findings),
|
||||
)
|
||||
.collect::<Vec<_>>();
|
||||
if findings.iter().any(|finding| {
|
||||
is_security_finding_code(&finding.code)
|
||||
&& !super::normalize_finding_validation::matches_source(finding, ir, &source_nodes)
|
||||
}) {
|
||||
return Err(ImportParseError::InvalidDocument);
|
||||
}
|
||||
for finding in &findings {
|
||||
if super::normalize_finding_validation::matches_source(finding, ir, &source_nodes)
|
||||
&& finding.construct_id == format!("{version}:{}", finding.location.pointer)
|
||||
@@ -145,6 +155,20 @@ pub(super) fn validate_coverage(ir: &NormalizedIr) -> Result<(), ImportParseErro
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_security_finding_code(code: &str) -> bool {
|
||||
matches!(
|
||||
code,
|
||||
"invalid_security_requirements"
|
||||
| "invalid_security_requirement"
|
||||
| "unresolved_security_scheme"
|
||||
| "unsupported_security_and_requirement"
|
||||
| "unsupported_security_scheme"
|
||||
| "unsupported_security_requirements"
|
||||
| "invalid_security_scopes"
|
||||
| "unexpected_security_scopes"
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct ExpectedCoverage {
|
||||
location: SourceLocation,
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::collections::BTreeMap;
|
||||
|
||||
use crate::rest::model::{
|
||||
CanonicalSourceNode, CanonicalSourceValue, ImportFindingSeverity, NormalizedFinding,
|
||||
NormalizedIr,
|
||||
NormalizedIr, NormalizedOperation, NormalizedSecuritySchemeKind, SecurityRequirementsSource,
|
||||
};
|
||||
|
||||
pub(super) fn matches_source(
|
||||
@@ -56,11 +56,158 @@ pub(super) fn matches_source(
|
||||
"secret_like_example" if finding.severity == ImportFindingSeverity::Warning => {
|
||||
pointer.contains("/example") && matches!(&node.value, CanonicalSourceValue::String(value) if secret_like(pointer, value))
|
||||
}
|
||||
"secret_literal_redacted" if finding.severity == ImportFindingSeverity::Warning => {
|
||||
matches!(&node.value, CanonicalSourceValue::String(value) if value == "[REDACTED]")
|
||||
}
|
||||
"invalid_security_requirements"
|
||||
| "invalid_security_requirement"
|
||||
| "unresolved_security_scheme"
|
||||
| "unsupported_security_and_requirement"
|
||||
| "unsupported_security_scheme"
|
||||
| "unsupported_security_requirements"
|
||||
| "invalid_security_scopes"
|
||||
| "unexpected_security_scopes" => security_finding(finding, ir, nodes),
|
||||
"invalid_server" if is_error => invalid_server(pointer, node),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn security_finding(
|
||||
finding: &NormalizedFinding,
|
||||
ir: &NormalizedIr,
|
||||
nodes: &BTreeMap<String, &CanonicalSourceNode>,
|
||||
) -> bool {
|
||||
let Some(operation) = ir
|
||||
.operations
|
||||
.iter()
|
||||
.find(|operation| finding.operation_key.as_deref() == Some(operation.key.as_str()))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Some(requirements_pointer) = requirements_pointer(operation) else {
|
||||
return false;
|
||||
};
|
||||
let pointer = finding.location.pointer.as_str();
|
||||
let node = nodes.get(pointer).copied();
|
||||
|
||||
match finding.code.as_str() {
|
||||
"invalid_security_requirements" => {
|
||||
finding.severity == ImportFindingSeverity::Error
|
||||
&& pointer == requirements_pointer
|
||||
&& node.is_some_and(|node| !matches!(&node.value, CanonicalSourceValue::Array(_)))
|
||||
}
|
||||
"invalid_security_requirement" => {
|
||||
finding.severity == ImportFindingSeverity::Warning
|
||||
&& alternative_at(operation, pointer).is_some_and(|_| {
|
||||
node.is_some_and(|node| !matches!(&node.value, CanonicalSourceValue::Object(_)))
|
||||
})
|
||||
}
|
||||
"unresolved_security_scheme" => {
|
||||
finding.severity == ImportFindingSeverity::Warning
|
||||
&& scheme_at(operation, pointer)
|
||||
.is_some_and(|name| node.is_some() && !ir.security_schemes.contains_key(name))
|
||||
}
|
||||
"unsupported_security_and_requirement" => {
|
||||
finding.severity == ImportFindingSeverity::Warning
|
||||
&& alternative_at(operation, pointer)
|
||||
.is_some_and(|alternative| alternative.schemes.len() > 1)
|
||||
&& node.is_some_and(|node| matches!(&node.value, CanonicalSourceValue::Object(_)))
|
||||
}
|
||||
"unsupported_security_scheme" => {
|
||||
finding.severity == ImportFindingSeverity::Warning
|
||||
&& scheme_at(operation, pointer).is_some_and(|name| {
|
||||
let Some(scheme) = ir.security_schemes.get(name) else {
|
||||
return false;
|
||||
};
|
||||
node.is_some()
|
||||
&& matches!(
|
||||
&scheme.kind,
|
||||
NormalizedSecuritySchemeKind::Unsupported { .. }
|
||||
| NormalizedSecuritySchemeKind::ApiKey {
|
||||
location: crate::rest::model::SecurityParameterLocation::Cookie,
|
||||
..
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
"unsupported_security_requirements" => {
|
||||
finding.severity == ImportFindingSeverity::Error
|
||||
&& pointer == requirements_pointer
|
||||
&& !operation.security_requirements.alternatives.is_empty()
|
||||
&& operation
|
||||
.security_requirements
|
||||
.alternatives
|
||||
.iter()
|
||||
.all(|alternative| !alternative.supported)
|
||||
&& node.is_some_and(|node| matches!(&node.value, CanonicalSourceValue::Array(_)))
|
||||
}
|
||||
"invalid_security_scopes" | "unexpected_security_scopes" => {
|
||||
if finding.severity != ImportFindingSeverity::Warning {
|
||||
return false;
|
||||
}
|
||||
let Some(name) = scheme_at(operation, pointer) else {
|
||||
return false;
|
||||
};
|
||||
let Some(node) = node else {
|
||||
return false;
|
||||
};
|
||||
let valid_scopes = matches!(&node.value, CanonicalSourceValue::Array(items) if items.iter().all(|item| matches!(item.value, CanonicalSourceValue::String(_))));
|
||||
if finding.code == "invalid_security_scopes" {
|
||||
!valid_scopes
|
||||
} else {
|
||||
let nonempty = matches!(&node.value, CanonicalSourceValue::Array(items) if !items.is_empty() && items.iter().all(|item| matches!(item.value, CanonicalSourceValue::String(_))));
|
||||
let oauth_scoped = ir.security_schemes.get(name).is_some_and(|scheme| {
|
||||
matches!(
|
||||
&scheme.kind,
|
||||
NormalizedSecuritySchemeKind::Unsupported {
|
||||
scheme_type: Some(scheme_type)
|
||||
} if matches!(scheme_type.as_str(), "oauth2" | "openIdConnect")
|
||||
)
|
||||
});
|
||||
nonempty && !oauth_scoped
|
||||
}
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn requirements_pointer(operation: &NormalizedOperation) -> Option<String> {
|
||||
match operation.security_requirements.source {
|
||||
SecurityRequirementsSource::Document => Some("/security".to_owned()),
|
||||
SecurityRequirementsSource::Operation => {
|
||||
Some(format!("{}/security", operation.location.pointer))
|
||||
}
|
||||
SecurityRequirementsSource::None => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn alternative_at<'a>(
|
||||
operation: &'a NormalizedOperation,
|
||||
pointer: &str,
|
||||
) -> Option<&'a crate::rest::model::SecurityRequirementAlternative> {
|
||||
operation
|
||||
.security_requirements
|
||||
.alternatives
|
||||
.iter()
|
||||
.find(|alternative| {
|
||||
alternative
|
||||
.source_location
|
||||
.as_ref()
|
||||
.is_some_and(|location| location.pointer == pointer)
|
||||
})
|
||||
}
|
||||
|
||||
fn scheme_at<'a>(operation: &'a NormalizedOperation, pointer: &str) -> Option<&'a str> {
|
||||
let (alternative_pointer, scheme) = pointer.rsplit_once('/')?;
|
||||
let alternative = alternative_at(operation, alternative_pointer)?;
|
||||
let name = scheme.replace("~1", "/").replace("~0", "~");
|
||||
alternative
|
||||
.schemes
|
||||
.iter()
|
||||
.find(|candidate| **candidate == name)
|
||||
.map(String::as_str)
|
||||
}
|
||||
|
||||
fn parameter_style(
|
||||
pointer: &str,
|
||||
node: &CanonicalSourceNode,
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use crate::rest::model::{
|
||||
ImportFinding, ImportGroupPreview, ImportPreview, ImportSourcePreview, NormalizedIr,
|
||||
NormalizedSecurityScheme, RestImportDocument,
|
||||
};
|
||||
|
||||
pub(super) fn preview_from_ir(ir: &NormalizedIr) -> ImportPreview {
|
||||
let operations = ir
|
||||
.operations
|
||||
.iter()
|
||||
.map(super::normalize_projection::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,
|
||||
&ir.security_schemes,
|
||||
operations.iter(),
|
||||
findings,
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) 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.security_schemes,
|
||||
document.operations.iter(),
|
||||
document.findings,
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
fn preview_from_operations<'a>(
|
||||
source: &ImportSourcePreview,
|
||||
security_schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||
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 = if legacy {
|
||||
super::legacy_payload::candidate_from_operation(
|
||||
operation,
|
||||
&source.servers,
|
||||
&mut used_names,
|
||||
)
|
||||
} else {
|
||||
super::payload::candidate_from_operation(
|
||||
operation,
|
||||
security_schemes,
|
||||
&source.servers,
|
||||
&mut used_names,
|
||||
)
|
||||
};
|
||||
let group_title = operation
|
||||
.tags
|
||||
.first()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "Без группы".to_owned());
|
||||
let group_key = crate::rest::naming::snake_name(&group_title);
|
||||
groups
|
||||
.entry(group_key.clone())
|
||||
.or_insert_with(|| ImportGroupPreview {
|
||||
key: group_key,
|
||||
title: group_title,
|
||||
operations: Vec::new(),
|
||||
})
|
||||
.operations
|
||||
.push(candidate);
|
||||
}
|
||||
|
||||
super::normalize::sort_findings(&mut findings);
|
||||
ImportPreview {
|
||||
source: source.clone(),
|
||||
groups: groups.into_values().collect(),
|
||||
findings,
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ pub(super) fn operation_from_normalized(operation: &NormalizedOperation) -> Rest
|
||||
key: operation.key.clone(),
|
||||
method: operation.method,
|
||||
path: operation.path.clone(),
|
||||
security_requirements: operation.security_requirements.clone(),
|
||||
operation_id: operation.operation_id.clone(),
|
||||
summary: operation.summary.clone(),
|
||||
description: operation.description.clone(),
|
||||
|
||||
@@ -27,6 +27,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
let mut findings = Vec::new();
|
||||
let mut internal_finding_locations = Vec::new();
|
||||
let servers = parse_servers(root.get("servers"), "/servers");
|
||||
let security_schemes = super::security::schemes(root, false);
|
||||
append_findings_with_locations(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
@@ -156,6 +157,13 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
|
||||
let mut located_operation_findings =
|
||||
super::openapi3_findings::operation(operation_value, &operation_pointer);
|
||||
let security_requirements = super::security::collect_operation_requirements(
|
||||
root,
|
||||
operation_value,
|
||||
&operation_pointer,
|
||||
&security_schemes,
|
||||
&mut located_operation_findings,
|
||||
);
|
||||
located_operation_findings.extend(super::openapi3_findings::path_parameters(
|
||||
path,
|
||||
&operation_parameters,
|
||||
@@ -169,6 +177,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||
method,
|
||||
path: path.clone(),
|
||||
security_requirements,
|
||||
operation_id: operation_value
|
||||
.get("operationId")
|
||||
.and_then(Value::as_str)
|
||||
@@ -210,6 +219,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
version,
|
||||
title,
|
||||
servers,
|
||||
security_schemes,
|
||||
operations,
|
||||
findings,
|
||||
internal_finding_locations,
|
||||
@@ -223,228 +233,6 @@ fn deduplicate_parameters(parameters: &mut Vec<RestImportParameter>) {
|
||||
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(),
|
||||
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,
|
||||
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)>,
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::rest::{
|
||||
model::{
|
||||
ImportFinding, RestImportDocument, RestImportOperation, RestImportParameter,
|
||||
RestParameterLocation,
|
||||
},
|
||||
normalize::ImportParseError,
|
||||
recommendations::document_finding,
|
||||
};
|
||||
|
||||
pub(super) 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(),
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,8 @@ use serde_json::json;
|
||||
use crate::rest::{
|
||||
mapping::{BodyFieldMapping, ParameterFieldMapping, input_mapping, output_mapping},
|
||||
model::{
|
||||
ImportOperationCandidate, RestImportCandidate, RestImportOperation, RestParameterLocation,
|
||||
ImportOperationCandidate, NormalizedSecurityScheme, RestImportCandidate,
|
||||
RestImportOperation, RestParameterLocation,
|
||||
},
|
||||
naming::{fallback_operation_seed, title_from_name, unique_name},
|
||||
recommendations::{candidate_recommendations, operation_recommendations},
|
||||
@@ -21,6 +22,7 @@ use crate::rest::{
|
||||
|
||||
pub fn candidate_from_operation(
|
||||
operation: &RestImportOperation,
|
||||
security_schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||
document_servers: &[String],
|
||||
used_names: &mut BTreeSet<String>,
|
||||
) -> ImportOperationCandidate {
|
||||
@@ -154,6 +156,8 @@ pub fn candidate_from_operation(
|
||||
key: operation.key.clone(),
|
||||
method: operation.method,
|
||||
path: operation.path.clone(),
|
||||
security_requirements: operation.security_requirements.clone(),
|
||||
security_schemes: security_schemes.clone(),
|
||||
operation_id: operation.operation_id.clone(),
|
||||
suggested_name: name,
|
||||
suggested_display_name: display_name,
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use super::model::{
|
||||
NormalizedSecurityRequirements, NormalizedSecurityScheme, NormalizedSecuritySchemeKind,
|
||||
SecurityParameterLocation, SecurityRequirementAlternative, SecurityRequirementsSource,
|
||||
SourceLocation,
|
||||
};
|
||||
use super::recommendations::{document_blocker, document_finding};
|
||||
|
||||
pub(super) fn schemes(root: &Value, swagger: bool) -> BTreeMap<String, NormalizedSecurityScheme> {
|
||||
let (container, prefix) = if swagger {
|
||||
(root.get("securityDefinitions"), "/securityDefinitions")
|
||||
} else {
|
||||
(
|
||||
root.pointer("/components/securitySchemes"),
|
||||
"/components/securitySchemes",
|
||||
)
|
||||
};
|
||||
let Some(definitions) = container.and_then(Value::as_object) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
definitions
|
||||
.iter()
|
||||
.map(|(name, definition)| {
|
||||
let location = SourceLocation {
|
||||
pointer: format!(
|
||||
"{prefix}/{}",
|
||||
super::normalize_coverage::escape_pointer(name)
|
||||
),
|
||||
};
|
||||
let kind = if swagger {
|
||||
match definition.get("type").and_then(Value::as_str) {
|
||||
Some("basic") => NormalizedSecuritySchemeKind::Http {
|
||||
scheme: "basic".to_owned(),
|
||||
format_hint: None,
|
||||
},
|
||||
Some("apiKey") => api_key(definition, false),
|
||||
other => NormalizedSecuritySchemeKind::Unsupported {
|
||||
scheme_type: other.map(ToOwned::to_owned),
|
||||
},
|
||||
}
|
||||
} else {
|
||||
match definition.get("type").and_then(Value::as_str) {
|
||||
Some("http") => {
|
||||
let scheme = definition
|
||||
.get("scheme")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
if matches!(scheme.to_ascii_lowercase().as_str(), "basic" | "bearer") {
|
||||
NormalizedSecuritySchemeKind::Http {
|
||||
scheme,
|
||||
format_hint: definition
|
||||
.get("bearerFormat")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| {
|
||||
safe_format_hint(value) && !looks_secret_hint(value)
|
||||
})
|
||||
.map(ToOwned::to_owned),
|
||||
}
|
||||
} else {
|
||||
NormalizedSecuritySchemeKind::Unsupported {
|
||||
scheme_type: Some(format!("http:{}", scheme)),
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("apiKey") => api_key(definition, true),
|
||||
other => NormalizedSecuritySchemeKind::Unsupported {
|
||||
scheme_type: other.map(ToOwned::to_owned),
|
||||
},
|
||||
}
|
||||
};
|
||||
(
|
||||
name.clone(),
|
||||
NormalizedSecurityScheme {
|
||||
name: name.clone(),
|
||||
kind,
|
||||
source_location: location,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn api_key(definition: &Value, allow_cookie: bool) -> NormalizedSecuritySchemeKind {
|
||||
let location = match definition.get("in").and_then(Value::as_str) {
|
||||
Some("header") => Some(SecurityParameterLocation::Header),
|
||||
Some("query") => Some(SecurityParameterLocation::Query),
|
||||
Some("cookie") if allow_cookie => Some(SecurityParameterLocation::Cookie),
|
||||
_ => None,
|
||||
};
|
||||
match (location, definition.get("name").and_then(Value::as_str)) {
|
||||
(Some(location), Some(parameter_name)) => NormalizedSecuritySchemeKind::ApiKey {
|
||||
location,
|
||||
parameter_name: parameter_name.to_owned(),
|
||||
format_hint: definition
|
||||
.get("x-format-hint")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| safe_format_hint(value) && !looks_secret_hint(value))
|
||||
.map(ToOwned::to_owned),
|
||||
},
|
||||
_ => NormalizedSecuritySchemeKind::Unsupported {
|
||||
scheme_type: Some("apiKey".to_owned()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn safe_format_hint(value: &str) -> bool {
|
||||
!value.is_empty()
|
||||
&& value.len() <= 64
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'+'))
|
||||
}
|
||||
|
||||
fn looks_secret_hint(value: &str) -> bool {
|
||||
let value = value.to_ascii_lowercase();
|
||||
["token", "secret", "password", "credential", "authorization"]
|
||||
.iter()
|
||||
.any(|marker| value.contains(marker))
|
||||
|| value.starts_with("sk-")
|
||||
|| value.starts_with("bearer ")
|
||||
}
|
||||
|
||||
pub(super) fn effective_requirements(
|
||||
root: &Value,
|
||||
operation: &Value,
|
||||
operation_pointer: &str,
|
||||
schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||
) -> (
|
||||
NormalizedSecurityRequirements,
|
||||
Vec<(super::model::ImportFinding, SourceLocation)>,
|
||||
) {
|
||||
let (value, source, pointer) = if let Some(value) = operation.get("security") {
|
||||
(
|
||||
Some(value),
|
||||
SecurityRequirementsSource::Operation,
|
||||
format!("{operation_pointer}/security"),
|
||||
)
|
||||
} else if let Some(value) = root.get("security") {
|
||||
(
|
||||
Some(value),
|
||||
SecurityRequirementsSource::Document,
|
||||
"/security".to_owned(),
|
||||
)
|
||||
} else {
|
||||
(None, SecurityRequirementsSource::None, String::new())
|
||||
};
|
||||
let mut findings = Vec::new();
|
||||
let Some(value) = value else {
|
||||
return (
|
||||
NormalizedSecurityRequirements {
|
||||
source,
|
||||
alternatives: Vec::new(),
|
||||
},
|
||||
findings,
|
||||
);
|
||||
};
|
||||
let Some(alternatives) = value.as_array() else {
|
||||
findings.push((
|
||||
document_blocker(
|
||||
"invalid_security_requirements",
|
||||
"Security requirements имеют неверную структуру и блокируют импорт операции.",
|
||||
),
|
||||
SourceLocation { pointer },
|
||||
));
|
||||
return (
|
||||
NormalizedSecurityRequirements {
|
||||
source,
|
||||
alternatives: Vec::new(),
|
||||
},
|
||||
findings,
|
||||
);
|
||||
};
|
||||
let mut projected = Vec::new();
|
||||
let mut supported_alternatives = 0usize;
|
||||
for (alternative_index, alternative) in alternatives.iter().enumerate() {
|
||||
let alternative_pointer = format!("{pointer}/{alternative_index}");
|
||||
let Some(requirement) = alternative.as_object() else {
|
||||
let source_location = SourceLocation {
|
||||
pointer: alternative_pointer,
|
||||
};
|
||||
findings.push((
|
||||
document_finding(
|
||||
"invalid_security_requirement",
|
||||
"Security alternative имеет неверную структуру и недоступна для выбора.",
|
||||
),
|
||||
source_location.clone(),
|
||||
));
|
||||
projected.push(SecurityRequirementAlternative {
|
||||
schemes: Vec::new(),
|
||||
supported: false,
|
||||
findings: vec!["invalid_security_requirement".to_owned()],
|
||||
source_location: Some(source_location),
|
||||
});
|
||||
continue;
|
||||
};
|
||||
let mut names = requirement.keys().cloned().collect::<Vec<_>>();
|
||||
names.sort();
|
||||
let mut alternative_findings = Vec::new();
|
||||
for name in &names {
|
||||
let scopes = requirement.get(name).and_then(Value::as_array);
|
||||
let valid_scope_array =
|
||||
scopes.is_some_and(|scopes| scopes.iter().all(Value::is_string));
|
||||
if !valid_scope_array {
|
||||
alternative_findings.push("invalid_security_scopes".to_owned());
|
||||
findings.push((
|
||||
document_finding(
|
||||
"invalid_security_scopes",
|
||||
"Security scopes должны быть массивом строк; эта альтернатива недоступна для выбора.",
|
||||
),
|
||||
SourceLocation {
|
||||
pointer: format!("{alternative_pointer}/{}", super::normalize_coverage::escape_pointer(name)),
|
||||
},
|
||||
));
|
||||
} else if scopes.is_some_and(|scopes| !scopes.is_empty())
|
||||
&& !schemes.get(name).is_some_and(supports_named_scopes)
|
||||
{
|
||||
alternative_findings.push("unexpected_security_scopes".to_owned());
|
||||
findings.push((
|
||||
document_finding(
|
||||
"unexpected_security_scopes",
|
||||
format!("Схема {name} не поддерживает OAuth scopes; непустой список блокирует эту alternative."),
|
||||
),
|
||||
SourceLocation {
|
||||
pointer: format!("{alternative_pointer}/{}", super::normalize_coverage::escape_pointer(name)),
|
||||
},
|
||||
));
|
||||
}
|
||||
if !schemes.contains_key(name) {
|
||||
alternative_findings.push("unresolved_security_scheme".to_owned());
|
||||
findings.push((
|
||||
document_finding(
|
||||
"unresolved_security_scheme",
|
||||
format!(
|
||||
"Альтернатива требует неизвестную схему {name} и недоступна для выбора."
|
||||
),
|
||||
),
|
||||
SourceLocation {
|
||||
pointer: format!(
|
||||
"{alternative_pointer}/{}",
|
||||
super::normalize_coverage::escape_pointer(name)
|
||||
),
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
if names.len() > 1 {
|
||||
alternative_findings.push("unsupported_security_and_requirement".to_owned());
|
||||
findings.push((
|
||||
document_finding(
|
||||
"unsupported_security_and_requirement",
|
||||
format!("Альтернатива требует AND-сочетание схем {}; текущий импорт поддерживает только одну Auth Profile и не сохраняет это сочетание.", names.join(", ")),
|
||||
),
|
||||
SourceLocation {
|
||||
pointer: alternative_pointer.clone(),
|
||||
},
|
||||
));
|
||||
}
|
||||
if let Some((_unsupported, message)) = names.iter().find_map(|name| {
|
||||
schemes.get(name).and_then(|scheme| match &scheme.kind {
|
||||
NormalizedSecuritySchemeKind::Unsupported { .. } => Some((
|
||||
name,
|
||||
format!("Альтернатива использует неподдерживаемую схему {name} и недоступна для выбора."),
|
||||
)),
|
||||
NormalizedSecuritySchemeKind::ApiKey {
|
||||
location: SecurityParameterLocation::Cookie,
|
||||
..
|
||||
} => Some((
|
||||
name,
|
||||
format!("Схема {name} передаёт ключ через cookie, чего текущий Auth Profile runtime не поддерживает; настройте authentication вручную."),
|
||||
)),
|
||||
_ => None,
|
||||
})
|
||||
}) {
|
||||
alternative_findings.push("unsupported_security_scheme".to_owned());
|
||||
findings.push((
|
||||
document_finding(
|
||||
"unsupported_security_scheme",
|
||||
message,
|
||||
),
|
||||
SourceLocation {
|
||||
pointer: format!("{alternative_pointer}/{}", super::normalize_coverage::escape_pointer(_unsupported)),
|
||||
},
|
||||
));
|
||||
}
|
||||
alternative_findings.sort();
|
||||
alternative_findings.dedup();
|
||||
let supported = alternative_findings.is_empty();
|
||||
supported_alternatives += usize::from(supported);
|
||||
projected.push(SecurityRequirementAlternative {
|
||||
schemes: names,
|
||||
supported,
|
||||
findings: alternative_findings,
|
||||
source_location: Some(SourceLocation {
|
||||
pointer: alternative_pointer,
|
||||
}),
|
||||
});
|
||||
}
|
||||
if !projected.is_empty() && supported_alternatives == 0 {
|
||||
findings.push((
|
||||
document_blocker(
|
||||
"unsupported_security_requirements",
|
||||
"Ни одну authentication alternative нельзя безопасно выбрать; импорт операции заблокирован.",
|
||||
),
|
||||
SourceLocation { pointer },
|
||||
));
|
||||
}
|
||||
(
|
||||
NormalizedSecurityRequirements {
|
||||
source,
|
||||
alternatives: projected,
|
||||
},
|
||||
findings,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn collect_operation_requirements(
|
||||
root: &Value,
|
||||
operation: &Value,
|
||||
pointer: &str,
|
||||
schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||
findings: &mut Vec<(super::model::ImportFinding, SourceLocation)>,
|
||||
) -> NormalizedSecurityRequirements {
|
||||
let (requirements, security_findings) =
|
||||
effective_requirements(root, operation, pointer, schemes);
|
||||
findings.extend(security_findings);
|
||||
requirements
|
||||
}
|
||||
|
||||
fn supports_named_scopes(scheme: &NormalizedSecurityScheme) -> bool {
|
||||
matches!(
|
||||
&scheme.kind,
|
||||
NormalizedSecuritySchemeKind::Unsupported {
|
||||
scheme_type: Some(scheme_type)
|
||||
} if matches!(scheme_type.as_str(), "oauth2" | "openIdConnect")
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
use serde_json::Value;
|
||||
|
||||
use super::model::SourceLocation;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct SecretLiteralFinding {
|
||||
pub location: SourceLocation,
|
||||
}
|
||||
|
||||
/// Scans UTF-8 JSON or YAML and returns source locations without literal values.
|
||||
pub fn scan_secret_literals(
|
||||
bytes: &[u8],
|
||||
) -> Result<Vec<SecretLiteralFinding>, super::normalize::ImportParseError> {
|
||||
let document = std::str::from_utf8(bytes)
|
||||
.map_err(|_| super::normalize::ImportParseError::InvalidDocument)?;
|
||||
let mut root = super::normalize::decode(document)?;
|
||||
Ok(inspect_and_redact(&mut root))
|
||||
}
|
||||
|
||||
pub(super) fn inspect_and_redact(root: &mut Value) -> Vec<SecretLiteralFinding> {
|
||||
let mut findings = Vec::new();
|
||||
walk(root, "", false, false, &mut findings, true, false);
|
||||
findings
|
||||
}
|
||||
|
||||
fn walk(
|
||||
value: &mut Value,
|
||||
pointer: &str,
|
||||
sensitive_context: bool,
|
||||
example_context: bool,
|
||||
findings: &mut Vec<SecretLiteralFinding>,
|
||||
redact: bool,
|
||||
cookie_context: bool,
|
||||
) {
|
||||
if example_context
|
||||
&& value
|
||||
.as_object()
|
||||
.is_some_and(|fields| fields.keys().any(|key| is_jwt(key)))
|
||||
{
|
||||
findings.push(SecretLiteralFinding {
|
||||
location: SourceLocation {
|
||||
pointer: pointer.to_owned(),
|
||||
},
|
||||
});
|
||||
if redact {
|
||||
*value = Value::String("[REDACTED]".to_owned());
|
||||
}
|
||||
return;
|
||||
}
|
||||
match value {
|
||||
Value::Object(fields) => {
|
||||
let header_parameter = fields
|
||||
.get("in")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|location| location.eq_ignore_ascii_case("header"));
|
||||
let parameter_name = fields.get("name").and_then(Value::as_str).unwrap_or("");
|
||||
let named_sensitive_parameter =
|
||||
sensitive_key(parameter_name) && fields.get("in").and_then(Value::as_str).is_some();
|
||||
let named_cookie_header = is_cookie_header(parameter_name);
|
||||
for (key, child) in fields {
|
||||
let child_pointer = format!(
|
||||
"{pointer}/{}",
|
||||
super::normalize_coverage::escape_pointer(key)
|
||||
);
|
||||
let property_definition = (pointer.contains("/properties/")
|
||||
|| pointer.ends_with("/properties"))
|
||||
&& !key.to_ascii_lowercase().starts_with("x-");
|
||||
let sensitive = sensitive_context
|
||||
|| (sensitive_key(key)
|
||||
&& !property_definition
|
||||
&& !is_oauth_flow_name(pointer, key));
|
||||
let example = example_context
|
||||
|| matches!(
|
||||
key.to_ascii_lowercase().as_str(),
|
||||
"example" | "examples" | "default"
|
||||
);
|
||||
let header_example = header_parameter
|
||||
&& matches!(
|
||||
key.to_ascii_lowercase().as_str(),
|
||||
"example" | "examples" | "default"
|
||||
);
|
||||
let named_header = is_cookie_header(key);
|
||||
let credential_example = matches!(
|
||||
key.to_ascii_lowercase().as_str(),
|
||||
"example" | "examples" | "default"
|
||||
) && (named_sensitive_parameter
|
||||
|| (cookie_context && !property_definition)
|
||||
|| (named_cookie_header && !property_definition));
|
||||
walk(
|
||||
child,
|
||||
&child_pointer,
|
||||
sensitive || header_example || credential_example,
|
||||
example,
|
||||
findings,
|
||||
redact,
|
||||
cookie_context || named_cookie_header || named_header,
|
||||
);
|
||||
}
|
||||
}
|
||||
Value::Array(items) => {
|
||||
for (index, child) in items.iter_mut().enumerate() {
|
||||
walk(
|
||||
child,
|
||||
&format!("{pointer}/{index}"),
|
||||
sensitive_context,
|
||||
example_context,
|
||||
findings,
|
||||
redact,
|
||||
cookie_context,
|
||||
);
|
||||
}
|
||||
}
|
||||
Value::String(string) => {
|
||||
let userinfo = url_userinfo_range(string);
|
||||
let query_secret = sensitive_query_value(string);
|
||||
let likely_example_secret = (example_context
|
||||
&& (looks_secret_like(pointer, string) || is_jwt(string)))
|
||||
|| looks_secret_value(string)
|
||||
|| ((pointer.ends_with("/bearerFormat") || pointer.ends_with("/x-format-hint"))
|
||||
&& looks_secret_like(pointer, string));
|
||||
if sensitive_context || likely_example_secret || userinfo.is_some() || query_secret {
|
||||
findings.push(SecretLiteralFinding {
|
||||
location: SourceLocation {
|
||||
pointer: pointer.to_owned(),
|
||||
},
|
||||
});
|
||||
if redact {
|
||||
if query_secret {
|
||||
*string = "[REDACTED]".to_owned();
|
||||
} else if let Some((start, end)) = userinfo {
|
||||
string.replace_range(start..end, "[REDACTED]");
|
||||
} else {
|
||||
*string = "[REDACTED]".to_owned();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Number(_) | Value::Bool(_) if sensitive_context => {
|
||||
findings.push(SecretLiteralFinding {
|
||||
location: SourceLocation {
|
||||
pointer: pointer.to_owned(),
|
||||
},
|
||||
});
|
||||
if redact {
|
||||
*value = Value::String("[REDACTED]".to_owned());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn sensitive_key(key: &str) -> bool {
|
||||
let mut normalized = String::new();
|
||||
let mut previous_lower = false;
|
||||
for ch in key.chars() {
|
||||
if ch.is_ascii_uppercase() && previous_lower {
|
||||
normalized.push('_');
|
||||
}
|
||||
if ch == '-' || ch == ' ' {
|
||||
normalized.push('_');
|
||||
} else {
|
||||
normalized.push(ch.to_ascii_lowercase());
|
||||
}
|
||||
previous_lower = ch.is_ascii_lowercase() || ch.is_ascii_digit();
|
||||
}
|
||||
let key = normalized;
|
||||
if matches!(key.as_str(), "authorization_url" | "token_url") {
|
||||
return false;
|
||||
}
|
||||
[
|
||||
"token",
|
||||
"secret",
|
||||
"secret_hash",
|
||||
"secrethash",
|
||||
"password",
|
||||
"password_hash",
|
||||
"passwordhash",
|
||||
"passwd",
|
||||
"api_key",
|
||||
"apikey",
|
||||
"authorization",
|
||||
"credential",
|
||||
"credentials",
|
||||
"access_key",
|
||||
"private_key",
|
||||
"privatekey",
|
||||
"ciphertext",
|
||||
]
|
||||
.iter()
|
||||
.any(|marker| {
|
||||
key == *marker
|
||||
|| key.ends_with(&format!("_{marker}"))
|
||||
|| key.starts_with(&format!("{marker}_"))
|
||||
})
|
||||
}
|
||||
|
||||
fn is_oauth_flow_name(parent_pointer: &str, key: &str) -> bool {
|
||||
if !parent_pointer.ends_with("/flows") {
|
||||
return false;
|
||||
}
|
||||
let compact_key: String = key
|
||||
.chars()
|
||||
.filter(|character| character.is_ascii_alphanumeric())
|
||||
.map(|character| character.to_ascii_lowercase())
|
||||
.collect();
|
||||
matches!(
|
||||
compact_key.as_str(),
|
||||
"implicit" | "password" | "clientcredentials" | "authorizationcode"
|
||||
)
|
||||
}
|
||||
|
||||
fn is_cookie_header(value: &str) -> bool {
|
||||
value.eq_ignore_ascii_case("cookie") || value.eq_ignore_ascii_case("set-cookie")
|
||||
}
|
||||
|
||||
fn is_jwt(value: &str) -> bool {
|
||||
let mut parts = value.split('.');
|
||||
let Some(header) = parts.next() else {
|
||||
return false;
|
||||
};
|
||||
let Some(payload) = parts.next() else {
|
||||
return false;
|
||||
};
|
||||
let Some(signature) = parts.next() else {
|
||||
return false;
|
||||
};
|
||||
parts.next().is_none()
|
||||
&& header.starts_with("eyJ")
|
||||
&& payload.starts_with("eyJ")
|
||||
&& header.len() >= 8
|
||||
&& payload.len() >= 16
|
||||
&& signature.len() >= 12
|
||||
&& [header, payload, signature].iter().all(|part| {
|
||||
!part.is_empty()
|
||||
&& part
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
|
||||
})
|
||||
}
|
||||
|
||||
fn sensitive_query_value(value: &str) -> bool {
|
||||
let Some(query_start) = value.find('?') else {
|
||||
return false;
|
||||
};
|
||||
value[query_start + 1..]
|
||||
.split('#')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.split(['&', ';'])
|
||||
.any(|pair| {
|
||||
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
|
||||
!value.is_empty() && sensitive_key(key)
|
||||
})
|
||||
}
|
||||
|
||||
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-")
|
||||
}
|
||||
|
||||
fn looks_secret_value(value: &str) -> bool {
|
||||
let value = value.to_ascii_lowercase();
|
||||
value.starts_with("bearer ") || value.starts_with("sk-")
|
||||
}
|
||||
|
||||
fn url_userinfo_range(value: &str) -> Option<(usize, usize)> {
|
||||
let scheme_end = value.find("://")? + 3;
|
||||
let authority_end = value[scheme_end..]
|
||||
.find('/')
|
||||
.map(|index| scheme_end + index)
|
||||
.unwrap_or(value.len());
|
||||
let authority = &value[scheme_end..authority_end];
|
||||
let at = authority.find('@')?;
|
||||
(at > 0).then_some((scheme_end, scheme_end + at))
|
||||
}
|
||||
@@ -21,6 +21,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
.unwrap_or("Imported API")
|
||||
.to_owned();
|
||||
let servers = swagger_servers(root);
|
||||
let security_schemes = super::security::schemes(root, true);
|
||||
let mut findings = Vec::new();
|
||||
let mut internal_finding_locations = Vec::new();
|
||||
append_parameter_findings(
|
||||
@@ -146,6 +147,13 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||
let mut located_operation_findings =
|
||||
super::swagger2_findings::operation(root, operation_value, &operation_pointer);
|
||||
let security_requirements = super::security::collect_operation_requirements(
|
||||
root,
|
||||
operation_value,
|
||||
&operation_pointer,
|
||||
&security_schemes,
|
||||
&mut located_operation_findings,
|
||||
);
|
||||
located_operation_findings.extend(parsed_parameter_findings);
|
||||
located_operation_findings.extend(super::swagger2_findings::path_parameters(
|
||||
path,
|
||||
@@ -160,6 +168,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||
method,
|
||||
path: path.clone(),
|
||||
security_requirements,
|
||||
operation_id: operation_value
|
||||
.get("operationId")
|
||||
.and_then(Value::as_str)
|
||||
@@ -199,6 +208,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
version: Some("2.0".to_owned()),
|
||||
title,
|
||||
servers,
|
||||
security_schemes,
|
||||
operations,
|
||||
findings,
|
||||
internal_finding_locations,
|
||||
@@ -212,201 +222,7 @@ fn deduplicate_parameters(parameters: &mut Vec<RestImportParameter>) {
|
||||
parameters.reverse();
|
||||
}
|
||||
|
||||
pub fn parse_document_legacy_v1(root: &Value) -> Result<RestImportDocument, ImportParseError> {
|
||||
let title = root
|
||||
.pointer("/info/title")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("Imported API")
|
||||
.to_owned();
|
||||
let servers = swagger_servers(root);
|
||||
let mut findings = Vec::new();
|
||||
if servers.is_empty() {
|
||||
findings.push(document_finding(
|
||||
"missing_servers",
|
||||
"В Swagger 2.0 документе не указаны host/schemes, 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"),
|
||||
));
|
||||
let request_body_schema = parameters
|
||||
.iter()
|
||||
.find(|parameter| parameter.name == "body")
|
||||
.and_then(|parameter| parameter.schema.clone());
|
||||
let parameters = parameters
|
||||
.into_iter()
|
||||
.filter(|parameter| parameter.name != "body")
|
||||
.collect();
|
||||
operations.push(RestImportOperation {
|
||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||
method,
|
||||
path: path.clone(),
|
||||
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,
|
||||
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: super::swagger2_findings::legacy_operation(path, operation),
|
||||
internal_finding_locations: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(RestImportDocument {
|
||||
format: "swagger".to_owned(),
|
||||
version: Some("2.0".to_owned()),
|
||||
title,
|
||||
servers,
|
||||
operations,
|
||||
findings,
|
||||
internal_finding_locations: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
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 raw_location = item.get("in").and_then(Value::as_str)?;
|
||||
let pointer = format!("{base_pointer}/{index}");
|
||||
if raw_location == "body" {
|
||||
return Some(RestImportParameter {
|
||||
name: "body".to_owned(),
|
||||
location: RestParameterLocation::Query,
|
||||
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").map(|schema| {
|
||||
crate::rest::normalize::resolve_local_ref(root, schema, 0)
|
||||
}),
|
||||
source_location: crate::rest::model::SourceLocation { pointer },
|
||||
schema_source_location: None,
|
||||
});
|
||||
}
|
||||
let location = match raw_location {
|
||||
"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: legacy_parameter_schema(root, &item),
|
||||
source_location: crate::rest::model::SourceLocation { pointer },
|
||||
schema_source_location: None,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_parameter_schema(root: &Value, parameter: &Value) -> Option<Value> {
|
||||
if let Some(schema) = parameter.get("schema") {
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
let mut schema = serde_json::Map::new();
|
||||
for key in ["type", "format", "items", "enum", "default", "description"] {
|
||||
if let Some(value) = parameter.get(key) {
|
||||
schema.insert(
|
||||
key.to_owned(),
|
||||
crate::rest::normalize::resolve_local_ref(root, value, 0),
|
||||
);
|
||||
}
|
||||
}
|
||||
(!schema.is_empty()).then_some(Value::Object(schema))
|
||||
}
|
||||
|
||||
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);
|
||||
if let Some(schema) = response.get("schema") {
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn swagger_servers(root: &Value) -> Vec<String> {
|
||||
pub(super) fn swagger_servers(root: &Value) -> Vec<String> {
|
||||
let Some(host) = root.get("host").and_then(Value::as_str) else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
use serde_json::Value;
|
||||
|
||||
use super::swagger2::swagger_servers;
|
||||
use crate::rest::{
|
||||
model::{RestImportDocument, RestImportOperation, RestImportParameter, RestParameterLocation},
|
||||
normalize::ImportParseError,
|
||||
recommendations::document_finding,
|
||||
};
|
||||
|
||||
pub(super) fn parse_document_legacy_v1(
|
||||
root: &Value,
|
||||
) -> Result<RestImportDocument, ImportParseError> {
|
||||
let title = root
|
||||
.pointer("/info/title")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("Imported API")
|
||||
.to_owned();
|
||||
let servers = swagger_servers(root);
|
||||
let mut findings = Vec::new();
|
||||
if servers.is_empty() {
|
||||
findings.push(document_finding(
|
||||
"missing_servers",
|
||||
"В Swagger 2.0 документе не указаны host/schemes, 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"),
|
||||
));
|
||||
let request_body_schema = parameters
|
||||
.iter()
|
||||
.find(|parameter| parameter.name == "body")
|
||||
.and_then(|parameter| parameter.schema.clone());
|
||||
let parameters = parameters
|
||||
.into_iter()
|
||||
.filter(|parameter| parameter.name != "body")
|
||||
.collect();
|
||||
operations.push(RestImportOperation {
|
||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||
method,
|
||||
path: path.clone(),
|
||||
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,
|
||||
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: super::swagger2_findings::legacy_operation(path, operation),
|
||||
internal_finding_locations: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(RestImportDocument {
|
||||
format: "swagger".to_owned(),
|
||||
version: Some("2.0".to_owned()),
|
||||
title,
|
||||
servers,
|
||||
security_schemes: Default::default(),
|
||||
operations,
|
||||
findings,
|
||||
internal_finding_locations: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
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 raw_location = item.get("in").and_then(Value::as_str)?;
|
||||
let pointer = format!("{base_pointer}/{index}");
|
||||
if raw_location == "body" {
|
||||
return Some(RestImportParameter {
|
||||
name: "body".to_owned(),
|
||||
location: RestParameterLocation::Query,
|
||||
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").map(|schema| {
|
||||
crate::rest::normalize::resolve_local_ref(root, schema, 0)
|
||||
}),
|
||||
source_location: crate::rest::model::SourceLocation { pointer },
|
||||
schema_source_location: None,
|
||||
});
|
||||
}
|
||||
let location = match raw_location {
|
||||
"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: legacy_parameter_schema(root, &item),
|
||||
source_location: crate::rest::model::SourceLocation { pointer },
|
||||
schema_source_location: None,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_parameter_schema(root: &Value, parameter: &Value) -> Option<Value> {
|
||||
if let Some(schema) = parameter.get("schema") {
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
let mut schema = serde_json::Map::new();
|
||||
for key in ["type", "format", "items", "enum", "default", "description"] {
|
||||
if let Some(value) = parameter.get(key) {
|
||||
schema.insert(
|
||||
key.to_owned(),
|
||||
crate::rest::normalize::resolve_local_ref(root, value, 0),
|
||||
);
|
||||
}
|
||||
}
|
||||
(!schema.is_empty()).then_some(Value::Object(schema))
|
||||
}
|
||||
|
||||
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);
|
||||
if let Some(schema) = response.get("schema") {
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,780 @@
|
||||
mod security_schemes {
|
||||
use crank_import::rest::{
|
||||
ImportFindingSeverity, ImportParseError, NormalizationConfig, NormalizedSecuritySchemeKind,
|
||||
SecurityParameterLocation, SecurityRequirementsSource, normalize_verified_document,
|
||||
preview_from_ir, scan_secret_literals, validate_normalized_ir,
|
||||
};
|
||||
|
||||
fn normalize_document(
|
||||
document: &str,
|
||||
config: &NormalizationConfig,
|
||||
) -> Result<crank_import::rest::NormalizedIr, ImportParseError> {
|
||||
normalize_verified_document(
|
||||
document,
|
||||
crank_import::rest::SourceDigest::parse("b".repeat(64)).unwrap(),
|
||||
config,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ac_1_projects_openapi_security_scheme_identity_onto_operation_metadata() {
|
||||
let document = r#"
|
||||
openapi: 3.1.0
|
||||
info: { title: Security metadata }
|
||||
components:
|
||||
securitySchemes:
|
||||
WorkspaceBearer:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: JWT
|
||||
paths:
|
||||
/private:
|
||||
get:
|
||||
operationId: private
|
||||
security: [{ WorkspaceBearer: [] }]
|
||||
responses: { '200': { description: ok } }
|
||||
"#;
|
||||
|
||||
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||
let operation = ir
|
||||
.operations
|
||||
.iter()
|
||||
.find(|operation| operation.path == "/private")
|
||||
.unwrap();
|
||||
let operation_contract = serde_json::to_string(operation).unwrap();
|
||||
|
||||
// This assertion deliberately inspects the operation projection, not the
|
||||
// canonical source tree, so copying the original document is insufficient.
|
||||
assert!(operation_contract.contains("WorkspaceBearer"));
|
||||
assert!(operation_contract.contains("bearer"));
|
||||
assert!(operation_contract.contains("JWT"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ac_6_never_copies_literal_secret_canaries_into_normalized_ir() {
|
||||
const CANARY: &str = "atdd-secret-canary-2-10";
|
||||
let document = format!(
|
||||
r#"
|
||||
openapi: 3.0.3
|
||||
info: {{ title: Secret canary }}
|
||||
components:
|
||||
securitySchemes:
|
||||
Bearer:
|
||||
type: http
|
||||
scheme: bearer
|
||||
x-example-token: {CANARY}
|
||||
x-credentials: {CANARY}
|
||||
x-ciphertext: {CANARY}
|
||||
paths:
|
||||
/private:
|
||||
get:
|
||||
security: [{{ Bearer: [] }}]
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content:
|
||||
application/json:
|
||||
example: {{ token: {CANARY} }}
|
||||
"#
|
||||
);
|
||||
|
||||
let ir = normalize_document(&document, &NormalizationConfig::default()).unwrap();
|
||||
let normalized = serde_json::to_string(&ir).unwrap();
|
||||
|
||||
assert!(
|
||||
!normalized.contains(CANARY),
|
||||
"normalized IR must not retain literal credential canaries"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn security_requirements_inherit_and_operation_empty_array_disables_auth() {
|
||||
let document = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Requirements }
|
||||
components:
|
||||
securitySchemes:
|
||||
Key: { type: apiKey, in: header, name: X-Workspace-Key }
|
||||
security: [{ Key: [] }]
|
||||
paths:
|
||||
/inherited:
|
||||
get: { responses: { '200': { description: ok } } }
|
||||
/public:
|
||||
get:
|
||||
security: []
|
||||
responses: { '200': { description: ok } }
|
||||
/and:
|
||||
get:
|
||||
security: [{ Key: [], Other: [] }]
|
||||
responses: { '200': { description: ok } }
|
||||
"#;
|
||||
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||
let inherited = ir
|
||||
.operations
|
||||
.iter()
|
||||
.find(|operation| operation.path == "/inherited")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
inherited.security_requirements.source,
|
||||
SecurityRequirementsSource::Document
|
||||
);
|
||||
assert_eq!(
|
||||
inherited.security_requirements.alternatives[0].schemes,
|
||||
["Key"]
|
||||
);
|
||||
let public = ir
|
||||
.operations
|
||||
.iter()
|
||||
.find(|operation| operation.path == "/public")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
public.security_requirements.source,
|
||||
SecurityRequirementsSource::Operation
|
||||
);
|
||||
assert!(public.security_requirements.alternatives.is_empty());
|
||||
let and = ir
|
||||
.operations
|
||||
.iter()
|
||||
.find(|operation| operation.path == "/and")
|
||||
.unwrap();
|
||||
assert!(
|
||||
and.findings
|
||||
.iter()
|
||||
.any(|finding| finding.code == "unsupported_security_and_requirement")
|
||||
);
|
||||
assert_eq!(
|
||||
and.security_requirements.alternatives[0].schemes,
|
||||
["Key", "Other"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn security_alternatives_preserve_or_and_and_preview_exposes_typed_schemes() {
|
||||
let document = r#"
|
||||
openapi: 3.1.0
|
||||
info: { title: Alternatives }
|
||||
components:
|
||||
securitySchemes:
|
||||
Bearer:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: JWT
|
||||
User:
|
||||
type: apiKey
|
||||
in: query
|
||||
name: access_token
|
||||
CookieKey:
|
||||
type: apiKey
|
||||
in: cookie
|
||||
name: session
|
||||
security:
|
||||
- Bearer: []
|
||||
- User: []
|
||||
- CookieKey: []
|
||||
paths:
|
||||
/private:
|
||||
get: { responses: { '200': { description: ok } } }
|
||||
"#;
|
||||
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||
let first = preview_from_ir(&ir);
|
||||
let second = preview_from_ir(&ir);
|
||||
assert_eq!(
|
||||
serde_json::to_vec(&first).unwrap(),
|
||||
serde_json::to_vec(&second).unwrap()
|
||||
);
|
||||
let candidate = &first.groups[0].operations[0];
|
||||
assert_eq!(candidate.security_requirements.alternatives.len(), 3);
|
||||
assert!(
|
||||
matches!(candidate.security_schemes["Bearer"].kind, NormalizedSecuritySchemeKind::Http { ref format_hint, .. } if format_hint.as_deref() == Some("JWT"))
|
||||
);
|
||||
assert!(
|
||||
matches!(candidate.security_schemes["User"].kind, NormalizedSecuritySchemeKind::ApiKey { location: SecurityParameterLocation::Query, ref parameter_name, .. } if parameter_name == "access_token")
|
||||
);
|
||||
assert!(
|
||||
matches!(candidate.security_schemes["CookieKey"].kind, NormalizedSecuritySchemeKind::ApiKey { location: SecurityParameterLocation::Cookie, ref parameter_name, .. } if parameter_name == "session")
|
||||
);
|
||||
assert!(!candidate.security_requirements.alternatives[2].supported);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swagger2_security_definitions_project_basic_and_api_key_header_and_query() {
|
||||
let document = r#"
|
||||
swagger: '2.0'
|
||||
info: { title: Swagger security }
|
||||
securityDefinitions:
|
||||
BasicAuth: { type: basic }
|
||||
HeaderKey: { type: apiKey, in: header, name: X-Api-Key }
|
||||
QueryKey: { type: apiKey, in: query, name: api_key }
|
||||
security: [{ BasicAuth: [] }, { HeaderKey: [] }]
|
||||
paths:
|
||||
/private:
|
||||
get: { responses: { '200': { description: ok } } }
|
||||
"#;
|
||||
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||
assert!(
|
||||
matches!(ir.security_schemes["BasicAuth"].kind, NormalizedSecuritySchemeKind::Http { ref scheme, .. } if scheme == "basic")
|
||||
);
|
||||
assert!(
|
||||
matches!(ir.security_schemes["HeaderKey"].kind, NormalizedSecuritySchemeKind::ApiKey { location: SecurityParameterLocation::Header, ref parameter_name, .. } if parameter_name == "X-Api-Key")
|
||||
);
|
||||
assert!(
|
||||
matches!(ir.security_schemes["QueryKey"].kind, NormalizedSecuritySchemeKind::ApiKey { location: SecurityParameterLocation::Query, ref parameter_name, .. } if parameter_name == "api_key")
|
||||
);
|
||||
assert_eq!(ir.operations[0].security_requirements.alternatives.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_security_schemes_create_blockers_without_copying_credentials() {
|
||||
let document = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Unsupported }
|
||||
components:
|
||||
securitySchemes:
|
||||
OAuth: { type: oauth2, flows: {} }
|
||||
Oidc: { type: openIdConnect, openIdConnectUrl: https://issuer.test }
|
||||
Mutual: { type: mutualTLS }
|
||||
paths:
|
||||
/private:
|
||||
get:
|
||||
security: [{ OAuth: [read] }, { Oidc: [] }, { Mutual: [] }, { Unknown: [] }]
|
||||
responses: { '200': { description: ok } }
|
||||
"#;
|
||||
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||
let codes = ir.operations[0]
|
||||
.findings
|
||||
.iter()
|
||||
.map(|finding| finding.code.as_str())
|
||||
.collect::<Vec<_>>();
|
||||
assert!(codes.contains(&"unsupported_security_scheme"));
|
||||
assert!(codes.contains(&"unresolved_security_scheme"));
|
||||
assert!(!codes.contains(&"invalid_security_scopes"));
|
||||
assert!(!codes.contains(&"unexpected_security_scopes"));
|
||||
assert!(ir.operations[0].findings.iter().any(|finding| {
|
||||
finding.code == "unsupported_security_requirements"
|
||||
&& finding.severity == ImportFindingSeverity::Error
|
||||
}));
|
||||
assert!(
|
||||
ir.operations[0]
|
||||
.security_requirements
|
||||
.alternatives
|
||||
.iter()
|
||||
.all(|alternative| !alternative.supported)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalized_ir_rejects_unrelated_security_findings_and_accepts_valid_security_ir() {
|
||||
let document = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Validation }
|
||||
components:
|
||||
securitySchemes:
|
||||
OAuth: { type: oauth2, flows: {} }
|
||||
paths:
|
||||
/private:
|
||||
get:
|
||||
security: [{ OAuth: [] }]
|
||||
responses: { '200': { description: ok } }
|
||||
"#;
|
||||
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||
validate_normalized_ir(&ir).unwrap();
|
||||
|
||||
let mut tampered = ir;
|
||||
let finding = tampered.operations[0]
|
||||
.findings
|
||||
.iter_mut()
|
||||
.find(|finding| finding.code == "unsupported_security_scheme")
|
||||
.unwrap();
|
||||
finding.location.pointer = "/info/title".to_owned();
|
||||
finding.construct_id = "3.0.3:/info/title".to_owned();
|
||||
assert_eq!(
|
||||
validate_normalized_ir(&tampered),
|
||||
Err(ImportParseError::InvalidDocument)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_or_alternative_does_not_block_a_supported_choice() {
|
||||
let document = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Mixed alternatives }
|
||||
components:
|
||||
securitySchemes:
|
||||
Bearer: { type: http, scheme: bearer }
|
||||
OAuth: { type: oauth2, flows: {} }
|
||||
security: [{ OAuth: [] }, { Bearer: [] }]
|
||||
paths:
|
||||
/private:
|
||||
get: { responses: { '200': { description: ok } } }
|
||||
"#;
|
||||
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||
let operation = &ir.operations[0];
|
||||
assert_eq!(operation.security_requirements.alternatives.len(), 2);
|
||||
assert!(!operation.security_requirements.alternatives[0].supported);
|
||||
assert!(operation.security_requirements.alternatives[1].supported);
|
||||
assert!(
|
||||
!operation
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.code == "unsupported_security_requirements")
|
||||
);
|
||||
assert!(operation.findings.iter().any(|finding| {
|
||||
finding.code == "unsupported_security_scheme"
|
||||
&& finding.severity == ImportFindingSeverity::Warning
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openapi_invalid_http_scopes_are_selection_aware_and_valid_or_sibling_survives() {
|
||||
let document = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Invalid HTTP scopes }
|
||||
components:
|
||||
securitySchemes:
|
||||
Bearer: { type: http, scheme: bearer }
|
||||
security:
|
||||
- Bearer: [read]
|
||||
- Bearer: "read"
|
||||
- Bearer: [1]
|
||||
- Bearer: []
|
||||
paths:
|
||||
/private:
|
||||
get: { responses: { '200': { description: ok } } }
|
||||
"#;
|
||||
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||
let operation = &ir.operations[0];
|
||||
let alternatives = &operation.security_requirements.alternatives;
|
||||
assert_eq!(alternatives.len(), 4);
|
||||
assert!(
|
||||
alternatives[..3]
|
||||
.iter()
|
||||
.all(|alternative| !alternative.supported)
|
||||
);
|
||||
assert!(alternatives[3].supported);
|
||||
assert!(operation.findings.iter().any(|finding| {
|
||||
finding.code == "unexpected_security_scopes"
|
||||
&& finding.severity == ImportFindingSeverity::Warning
|
||||
}));
|
||||
assert!(operation.findings.iter().any(|finding| {
|
||||
finding.code == "invalid_security_scopes"
|
||||
&& finding.severity == ImportFindingSeverity::Warning
|
||||
}));
|
||||
assert!(
|
||||
!operation
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| { finding.code == "unsupported_security_requirements" })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swagger_invalid_api_key_scopes_do_not_hide_valid_or_sibling() {
|
||||
let document = r#"
|
||||
swagger: '2.0'
|
||||
info: { title: Invalid Swagger scopes }
|
||||
securityDefinitions:
|
||||
HeaderKey: { type: apiKey, in: header, name: X-Api-Key }
|
||||
BasicAuth: { type: basic }
|
||||
security:
|
||||
- HeaderKey: [read]
|
||||
- BasicAuth: []
|
||||
paths:
|
||||
/private:
|
||||
get: { responses: { '200': { description: ok } } }
|
||||
"#;
|
||||
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||
let operation = &ir.operations[0];
|
||||
assert!(!operation.security_requirements.alternatives[0].supported);
|
||||
assert!(operation.security_requirements.alternatives[1].supported);
|
||||
assert!(operation.findings.iter().any(|finding| {
|
||||
finding.code == "unexpected_security_scopes"
|
||||
&& finding.severity == ImportFindingSeverity::Warning
|
||||
}));
|
||||
assert!(
|
||||
!operation
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| { finding.code == "unsupported_security_requirements" })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanner_finds_examples_defaults_extensions_and_url_userinfo_without_values() {
|
||||
const CANARIES: [&str; 5] = [
|
||||
"example-token-secret",
|
||||
"default-password-secret",
|
||||
"extension-api-key-secret",
|
||||
"url-userinfo-secret",
|
||||
"header-example-secret",
|
||||
];
|
||||
let document = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Redaction }
|
||||
servers: [{ url: 'https://operator:url-userinfo-secret@example.test' }]
|
||||
components:
|
||||
securitySchemes:
|
||||
Bearer: { type: http, scheme: bearer, x-example-token: extension-api-key-secret }
|
||||
paths:
|
||||
/private:
|
||||
get:
|
||||
parameters:
|
||||
- name: token
|
||||
in: header
|
||||
example: header-example-secret
|
||||
schema: { type: string, default: default-password-secret }
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content:
|
||||
application/json:
|
||||
example: { token: example-token-secret }
|
||||
"#;
|
||||
let findings = scan_secret_literals(document.as_bytes()).unwrap();
|
||||
assert!(findings.len() >= CANARIES.len());
|
||||
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||
let serialized = serde_json::to_string(&ir).unwrap();
|
||||
assert!(CANARIES.iter().all(|canary| !serialized.contains(canary)));
|
||||
let report = serde_json::to_string(&findings).unwrap();
|
||||
assert!(CANARIES.iter().all(|canary| !report.contains(canary)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanner_does_not_mistake_password_or_token_schema_properties_for_credentials() {
|
||||
let document = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Password fields }
|
||||
paths:
|
||||
/login:
|
||||
post:
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
password: { type: string, format: password }
|
||||
access_token: { type: string }
|
||||
responses: { '204': { description: ok } }
|
||||
"#;
|
||||
assert!(
|
||||
scan_secret_literals(document.as_bytes())
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanner_keeps_version_examples_and_null_credential_defaults() {
|
||||
let document = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Benign examples }
|
||||
components:
|
||||
securitySchemes:
|
||||
Bearer: { type: http, scheme: bearer, clientSecret: null }
|
||||
paths:
|
||||
/version:
|
||||
get:
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content:
|
||||
text/plain:
|
||||
example: 1.2.3
|
||||
"#;
|
||||
assert!(
|
||||
scan_secret_literals(document.as_bytes())
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanner_allows_oauth_endpoint_urls_but_redacts_secret_query_parameters() {
|
||||
let safe_document = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: OAuth URLs }
|
||||
components:
|
||||
securitySchemes:
|
||||
OAuth:
|
||||
type: oauth2
|
||||
flows:
|
||||
authorizationCode:
|
||||
authorizationUrl: https://auth.example.test/authorize
|
||||
tokenUrl: https://auth.example.test/token
|
||||
scopes: {}
|
||||
password:
|
||||
tokenUrl: https://auth.example.test/password-token
|
||||
scopes: {}
|
||||
clientCredentials:
|
||||
tokenUrl: https://auth.example.test/client-token
|
||||
scopes: {}
|
||||
"#;
|
||||
assert!(
|
||||
scan_secret_literals(safe_document.as_bytes())
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
let secret_document = safe_document
|
||||
.replace(
|
||||
"https://auth.example.test/token",
|
||||
"https://auth.example.test/token?access_token=oauth-url-canary",
|
||||
)
|
||||
.replace(
|
||||
"https://auth.example.test/password-token",
|
||||
"https://auth.example.test/password-token?access_token=password-flow-canary",
|
||||
)
|
||||
.replace(
|
||||
"https://auth.example.test/client-token",
|
||||
"https://auth.example.test/client-token?access_token=client-flow-canary",
|
||||
);
|
||||
let findings = scan_secret_literals(secret_document.as_bytes()).unwrap();
|
||||
assert!(findings.iter().any(|finding| {
|
||||
finding.location.pointer
|
||||
== "/components/securitySchemes/OAuth/flows/authorizationCode/tokenUrl"
|
||||
}));
|
||||
assert!(findings.iter().any(|finding| {
|
||||
finding.location.pointer == "/components/securitySchemes/OAuth/flows/password/tokenUrl"
|
||||
}));
|
||||
assert!(findings.iter().any(|finding| {
|
||||
finding.location.pointer
|
||||
== "/components/securitySchemes/OAuth/flows/clientCredentials/tokenUrl"
|
||||
}));
|
||||
let report = serde_json::to_string(&findings).unwrap();
|
||||
assert!(!report.contains("oauth-url-canary"));
|
||||
assert!(!report.contains("password-flow-canary"));
|
||||
assert!(!report.contains("client-flow-canary"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanner_redacts_contextual_credentials_non_strings_jwts_and_cookie_examples() {
|
||||
const CANARIES: [&str; 8] = [
|
||||
"982734651",
|
||||
"true",
|
||||
"opaque-query-canary",
|
||||
"cookie-session-canary",
|
||||
"set-cookie-canary",
|
||||
"query-param-canary",
|
||||
"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJl",
|
||||
"opaque-jwt-object-key-canary",
|
||||
];
|
||||
const JWT_KEY: &str = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJl";
|
||||
let document = format!(
|
||||
r#"
|
||||
openapi: 3.0.3
|
||||
info: {{ title: Contextual redaction }}
|
||||
servers: [{{ url: 'https://api.test/items?access_token=opaque-query-canary' }}]
|
||||
components:
|
||||
securitySchemes:
|
||||
Custom: {{ type: http, scheme: bearer, x-clientSecret: 982734651, x-accessToken: true }}
|
||||
paths:
|
||||
/login:
|
||||
post:
|
||||
parameters:
|
||||
- name: api_key
|
||||
in: query
|
||||
schema: {{ type: string }}
|
||||
example: query-param-canary
|
||||
- name: Cookie
|
||||
in: header
|
||||
schema: {{ type: string }}
|
||||
example: cookie-session-canary
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
headers:
|
||||
Set-Cookie:
|
||||
schema: {{ type: string }}
|
||||
example: set-cookie-canary
|
||||
content:
|
||||
application/json:
|
||||
example: {{{JWT_KEY}: opaque-jwt-object-key-canary}}
|
||||
examples:
|
||||
compact:
|
||||
value: {{{JWT_KEY}}}
|
||||
"#
|
||||
);
|
||||
let findings = scan_secret_literals(document.as_bytes()).unwrap();
|
||||
let location_pointers: Vec<_> = findings
|
||||
.iter()
|
||||
.map(|finding| finding.location.pointer.as_str())
|
||||
.collect();
|
||||
assert!(
|
||||
location_pointers
|
||||
.iter()
|
||||
.any(|pointer| pointer.ends_with("/x-clientSecret"))
|
||||
);
|
||||
assert!(
|
||||
location_pointers
|
||||
.iter()
|
||||
.any(|pointer| pointer.ends_with("/x-accessToken"))
|
||||
);
|
||||
assert!(
|
||||
location_pointers
|
||||
.iter()
|
||||
.any(|pointer| pointer.ends_with("/servers/0/url"))
|
||||
);
|
||||
assert!(
|
||||
location_pointers
|
||||
.iter()
|
||||
.any(|pointer| pointer.ends_with("/parameters/0/example"))
|
||||
);
|
||||
assert!(
|
||||
location_pointers
|
||||
.iter()
|
||||
.any(|pointer| pointer.ends_with("/parameters/1/example"))
|
||||
);
|
||||
assert!(
|
||||
location_pointers
|
||||
.iter()
|
||||
.any(|pointer| pointer.ends_with("/headers/Set-Cookie/example"))
|
||||
);
|
||||
assert!(
|
||||
location_pointers
|
||||
.iter()
|
||||
.any(|pointer| pointer.ends_with("/content/application~1json/example"))
|
||||
);
|
||||
assert!(
|
||||
location_pointers
|
||||
.iter()
|
||||
.any(|pointer| pointer
|
||||
.ends_with("/content/application~1json/examples/compact/value"))
|
||||
);
|
||||
|
||||
let ir = normalize_document(&document, &NormalizationConfig::default()).unwrap();
|
||||
let serialized = serde_json::to_string(&ir).unwrap();
|
||||
for canary in CANARIES {
|
||||
assert!(!serialized.contains(canary), "IR retained canary {canary}");
|
||||
}
|
||||
let redacted_locations: Vec<_> = ir
|
||||
.findings
|
||||
.iter()
|
||||
.filter(|finding| finding.code == "secret_literal_redacted")
|
||||
.map(|finding| finding.location.pointer.as_str())
|
||||
.collect();
|
||||
assert!(
|
||||
redacted_locations
|
||||
.iter()
|
||||
.any(|pointer| pointer.ends_with("/x-clientSecret"))
|
||||
);
|
||||
assert!(
|
||||
redacted_locations
|
||||
.iter()
|
||||
.any(|pointer| pointer.ends_with("/x-accessToken"))
|
||||
);
|
||||
assert!(
|
||||
redacted_locations
|
||||
.iter()
|
||||
.any(|pointer| pointer.ends_with("/servers/0/url"))
|
||||
);
|
||||
assert!(
|
||||
redacted_locations
|
||||
.iter()
|
||||
.any(|pointer| pointer.ends_with("/parameters/0/example"))
|
||||
);
|
||||
assert!(
|
||||
redacted_locations
|
||||
.iter()
|
||||
.any(|pointer| pointer.ends_with("/parameters/1/example"))
|
||||
);
|
||||
assert!(
|
||||
redacted_locations
|
||||
.iter()
|
||||
.any(|pointer| pointer.ends_with("/headers/Set-Cookie/example"))
|
||||
);
|
||||
assert!(
|
||||
redacted_locations
|
||||
.iter()
|
||||
.any(|pointer| pointer.ends_with("/content/application~1json/example"))
|
||||
);
|
||||
assert!(
|
||||
redacted_locations
|
||||
.iter()
|
||||
.any(|pointer| pointer
|
||||
.ends_with("/content/application~1json/examples/compact/value"))
|
||||
);
|
||||
let report = serde_json::to_string(&ir.findings).unwrap();
|
||||
assert!(report.contains("secret_literal_redacted"));
|
||||
for canary in CANARIES {
|
||||
assert!(
|
||||
!report.contains(canary),
|
||||
"finding report retained canary {canary}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsafe_bearer_format_canary_is_redacted_and_not_projected() {
|
||||
const CANARY: &str = "Bearer sk-format-canary";
|
||||
let document = format!(
|
||||
r#"
|
||||
openapi: 3.0.3
|
||||
info: {{ title: Format redaction }}
|
||||
components:
|
||||
securitySchemes:
|
||||
Bearer:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: "{CANARY}"
|
||||
paths:
|
||||
/private:
|
||||
get: {{ security: [{{ Bearer: [] }}], responses: {{ '200': {{ description: ok }} }} }}
|
||||
"#
|
||||
);
|
||||
let ir = normalize_document(&document, &NormalizationConfig::default()).unwrap();
|
||||
let serialized = serde_json::to_string(&ir).unwrap();
|
||||
assert!(!serialized.contains(CANARY));
|
||||
let scan_findings = scan_secret_literals(document.as_bytes()).unwrap();
|
||||
assert!(scan_findings.iter().any(|finding| {
|
||||
finding.location.pointer == "/components/securitySchemes/Bearer/bearerFormat"
|
||||
}));
|
||||
let redaction_findings: Vec<_> = ir
|
||||
.findings
|
||||
.iter()
|
||||
.filter(|finding| finding.code == "secret_literal_redacted")
|
||||
.collect();
|
||||
assert_eq!(redaction_findings.len(), 1);
|
||||
assert_eq!(
|
||||
redaction_findings[0].location.pointer,
|
||||
"/components/securitySchemes/Bearer/bearerFormat"
|
||||
);
|
||||
let report = serde_json::to_string(&ir.findings).unwrap();
|
||||
assert!(report.contains("secret_literal_redacted"));
|
||||
assert!(report.contains("/components/securitySchemes/Bearer/bearerFormat"));
|
||||
assert!(!report.contains(CANARY));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn historical_v4_ir_without_security_fields_remains_valid() {
|
||||
let document = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Replay }
|
||||
paths:
|
||||
/old:
|
||||
get: { responses: { '200': { description: ok } } }
|
||||
"#;
|
||||
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||
let mut value = serde_json::to_value(ir).unwrap();
|
||||
value["normalizer_version"] = serde_json::json!("normalized-ir-v4");
|
||||
value["projection_version"] = serde_json::json!("preview-v4");
|
||||
value.as_object_mut().unwrap().remove("security_schemes");
|
||||
for operation in value["operations"].as_array_mut().unwrap() {
|
||||
operation
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("security_schemes");
|
||||
operation
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("security_requirements");
|
||||
}
|
||||
let replay: crank_import::rest::NormalizedIr = serde_json::from_value(value).unwrap();
|
||||
validate_normalized_ir(&replay).unwrap();
|
||||
assert!(
|
||||
replay.operations[0]
|
||||
.security_requirements
|
||||
.alternatives
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user