story 2-10-security-schemes-secrets: implemented and reviewed via bmad-loop

This commit is contained in:
bsodfather committed 2026-10-03 00:09:08 +03:00
1 parent f5f40cb167
commit ecfb4e788f
45 files changed
+6025 -829

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: BTreeMap::new(),
operation_id: operation.operation_id.clone(),
suggested_name: name,
suggested_display_name: display_name,
+395 -21
View File
@@ -1,70 +1,444 @@
use serde_json::Value;
use std::collections::BTreeSet;
use crate::rest::{
model::{ImportFinding, SourceLocation},
recommendations::document_finding,
};
pub(super) fn collect_secret_like_examples(
value: &Value,
pub(super) const REDACTED_LITERAL: &str = "[REDACTED]";
/// Redacts credential-like literals before they enter the normalized tree,
/// while retaining stable source locations for review findings.
pub(super) fn redact_secret_like_literals(
value: &mut Value,
pointer: &str,
inside_example: bool,
findings: &mut Vec<ImportFinding>,
locations: &mut Vec<Option<SourceLocation>>,
) {
let declared_names = credential_names(std::iter::once(&*value));
redact_secret_like_literals_with_names(value, pointer, &declared_names, findings, locations);
}
pub(super) fn redact_secret_like_literals_with_names(
value: &mut Value,
pointer: &str,
declared_names: &CredentialNames,
findings: &mut Vec<ImportFinding>,
locations: &mut Vec<Option<SourceLocation>>,
) {
visit(
value,
pointer,
VisitContext {
in_secret_example: false,
sensitive_parameter_schema: false,
force_redact: false,
declared_names,
},
findings,
locations,
);
}
#[derive(Default)]
pub(super) struct CredentialNames {
header: BTreeSet<String>,
query: BTreeSet<String>,
cookie: BTreeSet<String>,
}
#[derive(Clone, Copy)]
struct VisitContext<'a> {
in_secret_example: bool,
sensitive_parameter_schema: bool,
force_redact: bool,
declared_names: &'a CredentialNames,
}
impl CredentialNames {
fn contains(&self, location: &str, name: &str) -> bool {
let names = match location.to_ascii_lowercase().as_str() {
"header" => &self.header,
"query" => &self.query,
"cookie" => &self.cookie,
_ => return false,
};
names.contains(&name.to_ascii_lowercase())
}
}
pub(super) fn credential_names<'a>(roots: impl IntoIterator<Item = &'a Value>) -> CredentialNames {
let mut names = CredentialNames::default();
for root in roots {
collect_credential_names(root, &mut names);
}
names
}
fn collect_credential_names(value: &Value, names: &mut CredentialNames) {
match value {
Value::Object(fields) => {
if fields.get("type").and_then(Value::as_str) == Some("apiKey")
&& let (Some(location), Some(name)) = (
fields.get("in").and_then(Value::as_str),
fields.get("name").and_then(Value::as_str),
)
{
let destination = match location.to_ascii_lowercase().as_str() {
"header" => Some(&mut names.header),
"query" => Some(&mut names.query),
"cookie" => Some(&mut names.cookie),
_ => None,
};
if let Some(destination) = destination {
destination.insert(name.to_ascii_lowercase());
}
}
for child in fields.values() {
collect_credential_names(child, names);
}
}
Value::Array(items) => {
for child in items {
collect_credential_names(child, names);
}
}
_ => {}
}
}
fn visit(
value: &mut Value,
pointer: &str,
context: VisitContext<'_>,
findings: &mut Vec<ImportFinding>,
locations: &mut Vec<Option<SourceLocation>>,
) {
if context.force_redact
|| value
.as_str()
.is_some_and(|text| url_has_secret_named(text, context.declared_names))
|| (context.in_secret_example && value.as_str() == Some(REDACTED_LITERAL))
|| (context.in_secret_example && scalar_looks_secret(value))
{
redact(value, context.force_redact, context.declared_names);
findings.push(document_finding(
"secret_like_example",
"В исходном документе обнаружено значение, похожее на секрет; оно удалено из импортируемых данных.",
));
locations.push(Some(SourceLocation {
pointer: pointer.to_owned(),
}));
return;
}
match value {
Value::Object(fields) => {
let sensitive_parameter =
fields
.get("in")
.and_then(Value::as_str)
.is_some_and(|location| {
["header", "query", "cookie"]
.iter()
.any(|allowed| location.eq_ignore_ascii_case(allowed))
})
&& fields
.get("name")
.and_then(Value::as_str)
.is_some_and(|name| {
is_sensitive_name(name)
|| fields.get("in").and_then(Value::as_str).is_some_and(
|location| context.declared_names.contains(location, name),
)
});
for (key, child) in fields {
let child_pointer = format!(
"{pointer}/{}",
super::normalize_coverage::escape_pointer(key)
);
collect_secret_like_examples(
let key_lower = key.to_ascii_lowercase();
let in_example = context.in_secret_example
|| matches!(
key_lower.as_str(),
"default"
| "example"
| "examples"
| "x-example"
| "x-examples"
| "bearerformat"
| "x-format-hint"
);
let sensitive_header_definition = pointer.ends_with("/headers")
&& (is_sensitive_name(key) || context.declared_names.contains("header", key));
let parameter_value = (sensitive_parameter || sensitive_header_definition)
&& matches!(
key_lower.as_str(),
"example" | "examples" | "x-example" | "x-examples"
);
let parameter_schema = context.sensitive_parameter_schema
|| sensitive_header_definition
|| (sensitive_parameter && key_lower == "schema");
let parent_is_secret_property =
pointer.rsplit('/').next().is_some_and(is_sensitive_name);
// Names in schema/scheme maps and security requirements are
// identifiers, not credential values. Traverse their metadata
// and redact the actual defaults/examples instead.
let identifier_map = (child.is_object()
&& (pointer.ends_with("/properties")
|| pointer.ends_with("/headers")
|| pointer == "/components/schemas"
|| pointer == "/definitions"
|| pointer == "/components/securitySchemes"
|| pointer == "/securityDefinitions"))
|| (child.is_array()
&& pointer.rsplit_once('/').is_some_and(|(parent, index)| {
parent.ends_with("/security") && index.parse::<usize>().is_ok()
}));
let force_child = (is_sensitive_name(key) && !identifier_map)
|| (matches!(key_lower.as_str(), "default" | "example" | "examples")
&& parent_is_secret_property)
|| parameter_value
|| (sensitive_parameter
&& matches!(key_lower.as_str(), "default" | "example" | "examples"))
|| (parameter_schema
&& matches!(key_lower.as_str(), "default" | "example" | "examples"));
visit(
child,
&child_pointer,
inside_example || matches!(key.as_str(), "example" | "examples"),
VisitContext {
in_secret_example: in_example,
sensitive_parameter_schema: parameter_schema,
force_redact: force_child,
..context
},
findings,
locations,
);
}
}
Value::Array(items) => {
for (index, child) in items.iter().enumerate() {
collect_secret_like_examples(
for (index, child) in items.iter_mut().enumerate() {
visit(
child,
&format!("{pointer}/{index}"),
inside_example,
VisitContext {
force_redact: false,
..context
},
findings,
locations,
);
}
}
Value::String(value) if inside_example && looks_secret_like(pointer, value) => {
findings.push(document_finding(
"secret_like_example",
"Example содержит значение, похожее на секрет, и не включается в executable contract.",
));
locations.push(Some(SourceLocation {
pointer: pointer.to_owned(),
}));
}
_ => {}
}
}
fn looks_secret_like(pointer: &str, value: &str) -> bool {
let pointer = pointer.to_ascii_lowercase();
fn is_sensitive_name(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
if lower.starts_with('/')
|| matches!(
lower.as_str(),
"url"
| "tokenurl"
| "authorizationurl"
| "refreshurl"
| "openidconnecturl"
| "clientcredentials"
| "authorizationcode"
)
{
return false;
}
let compact = lower.replace(['-', '_'], "");
[
"token",
"secret",
"password",
"credential",
"authorization",
"apikey",
"accesskey",
"ciphertext",
"privatekey",
"passwd",
]
.iter()
.any(|marker| compact.contains(marker))
}
fn scalar_looks_secret(value: &Value) -> bool {
let Value::String(value) = value else {
return false;
};
let value = value.to_ascii_lowercase();
[
"token",
"secret",
"password",
"credential",
"authorization",
"api_key",
"apikey",
"authorization",
]
.iter()
.any(|marker| pointer.contains(marker) || value.contains(marker))
.any(|marker| value.contains(marker))
|| value.starts_with("bearer ")
|| value.starts_with("sk-")
|| looks_like_jwt(&value)
}
fn looks_like_jwt(value: &str) -> bool {
let mut segments = value.split('.');
let (Some(header), Some(payload), Some(signature), None) = (
segments.next(),
segments.next(),
segments.next(),
segments.next(),
) else {
return false;
};
header.starts_with("eyj")
&& !payload.is_empty()
&& signature.len() >= 8
&& [header, payload, signature].iter().all(|segment| {
segment
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
})
}
pub(super) fn url_has_secret(value: &str) -> bool {
url_has_secret_named(value, &CredentialNames::default())
}
fn url_has_secret_named(value: &str, declared_names: &CredentialNames) -> bool {
url_userinfo(value).is_some()
|| query_has_secret_parameter(value, &declared_names.query)
|| fragment_has_secret_parameter(value)
}
fn fragment_has_secret_parameter(value: &str) -> bool {
let Some((_, fragment)) = value.split_once('#') else {
return false;
};
if fragment.starts_with('/') {
return false;
}
url::form_urlencoded::parse(fragment.as_bytes()).any(|(name, _)| is_sensitive_name(&name))
}
fn redact_url_fragment(value: &str) -> String {
let Some((base, fragment)) = value.split_once('#') else {
return value.to_owned();
};
if fragment.starts_with('/') || !fragment.contains('=') {
return value.to_owned();
}
let redacted = fragment
.split('&')
.map(|pair| {
let (name, parameter_value) = pair.split_once('=').unwrap_or((pair, ""));
let decoded_name = url::form_urlencoded::parse(format!("{name}=").as_bytes())
.next()
.map(|(name, _)| name.into_owned())
.unwrap_or_default();
if is_sensitive_name(&decoded_name) {
format!("{name}={REDACTED_LITERAL}")
} else if pair.contains('=') {
format!("{name}={parameter_value}")
} else {
name.to_owned()
}
})
.collect::<Vec<_>>()
.join("&");
format!("{base}#{redacted}")
}
fn url_userinfo(value: &str) -> Option<(&str, &str, &str)> {
let (scheme, rest) = value
.split_once("://")
.or_else(|| value.strip_prefix("//").map(|rest| ("", rest)))?;
let (authority, suffix) = rest
.find(['/', '?', '#'])
.map_or((rest, ""), |index| (&rest[..index], &rest[index..]));
let (userinfo, host) = authority.split_once('@')?;
if userinfo.is_empty() || host.is_empty() {
return None;
}
Some((scheme, host, suffix))
}
fn query_has_secret_parameter(value: &str, declared_query_names: &BTreeSet<String>) -> bool {
let Some((_, query)) = value.split_once('?') else {
return false;
};
let query = query.split('#').next().unwrap_or(query);
url::form_urlencoded::parse(query.as_bytes()).any(|(name, _)| {
is_sensitive_name(&name) || declared_query_names.contains(&name.to_ascii_lowercase())
})
}
fn redact(value: &mut Value, force: bool, declared_names: &CredentialNames) {
if force
|| !value
.as_str()
.is_some_and(|text| url_has_secret_named(text, declared_names))
{
*value = Value::String(REDACTED_LITERAL.to_owned());
return;
}
if let Value::String(text) = value {
if force {
*text = REDACTED_LITERAL.to_owned();
return;
}
let mut sanitized = text.clone();
if let Some((scheme, host, suffix)) = url_userinfo(&sanitized) {
sanitized = if scheme.is_empty() {
format!("//{host}{suffix}")
} else {
format!("{scheme}://{host}{suffix}")
};
}
if query_has_secret_parameter(&sanitized, &declared_names.query)
&& let Some((base, query)) = sanitized.split_once('?')
{
let (query, fragment) = query
.split_once('#')
.map_or((query, None), |(query, fragment)| (query, Some(fragment)));
let redacted = query
.split('&')
.map(|pair| {
let (name, value) = pair.split_once('=').unwrap_or((pair, ""));
let decoded_name = url::form_urlencoded::parse(format!("{name}=").as_bytes())
.next()
.map(|(name, _)| name.into_owned())
.unwrap_or_default();
if is_sensitive_name(&decoded_name)
|| declared_names
.query
.contains(&decoded_name.to_ascii_lowercase())
{
format!("{name}={REDACTED_LITERAL}")
} else if pair.contains('=') {
format!("{name}={value}")
} else {
name.to_owned()
}
})
.collect::<Vec<_>>()
.join("&");
sanitized = match fragment {
Some(fragment) => format!("{base}?{redacted}#{fragment}"),
None => format!("{base}?{redacted}"),
};
}
*text = redact_url_fragment(&sanitized);
} else {
*value = Value::String(REDACTED_LITERAL.to_owned());
}
}
+19 -9
View File
@@ -15,26 +15,36 @@ mod normalize_schema;
mod normalize_security;
mod openapi3;
mod openapi3_findings;
mod parser_findings;
mod payload;
mod recommendations;
mod reference;
mod schema;
mod security;
mod source_safety;
mod swagger2;
mod swagger2_findings;
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,
normalize_verified_document, preview_document, preview_document_legacy_v1, preview_from_ir,
reference_uris, validate_normalized_ir,
reference_uris, validate_document_source_safe, validate_normalized_ir,
};
pub use payload::operation_draft_from_candidate;
pub use source_safety::{
validate_document_bundle_source_safe, validate_resolved_bundle_source_safe,
};
+102 -2
View File
@@ -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>,
+59 -87
View File
@@ -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;
@@ -105,6 +103,37 @@ pub fn normalize_verified_document(
normalize_verified_bundle(document, digest, &[], config)
}
/// Rejects source documents containing credential-like literals before a
/// caller persists their original bytes. Accepted source bytes remain verbatim.
pub fn validate_document_source_safe(
document: &str,
config: &NormalizationConfig,
) -> Result<(), ImportParseError> {
config
.validate_versions()
.map_err(|_| ImportParseError::UnsupportedDocument)?;
if document.len() > config.max_bytes
|| normalize_limits::alias_count(document) > config.max_aliases
{
return Err(ImportParseError::LimitExceeded);
}
let mut root = decode(document)?;
validate_value_limits(&root, config)?;
let mut findings = Vec::new();
let mut locations = Vec::new();
super::metadata_findings::redact_secret_like_literals(
&mut root,
"",
&mut findings,
&mut locations,
);
if findings.is_empty() {
Ok(())
} else {
Err(ImportParseError::InvalidDocument)
}
}
/// Normalizes a verified primary document together with immutable external
/// snapshots. This function is pure: callers must perform all URL policy,
/// fetching, artifact persistence and digest verification beforehand.
@@ -135,9 +164,18 @@ 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 mut literal_findings = Vec::new();
let mut literal_locations = Vec::new();
super::metadata_findings::redact_secret_like_literals(
&mut root,
"",
&mut literal_findings,
&mut literal_locations,
);
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,14 +184,8 @@ pub fn normalize_verified_bundle(
}
None => return Err(ImportParseError::UnsupportedDocument),
};
super::normalize_security::append_security_requirement_findings(&mut parsed, &root);
super::metadata_findings::collect_secret_like_examples(
&root,
"",
false,
&mut parsed.findings,
&mut parsed.internal_finding_locations,
);
parsed.findings.extend(literal_findings);
parsed.internal_finding_locations.extend(literal_locations);
if parsed.operations.is_empty()
&& !parsed
@@ -175,81 +207,14 @@ 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_projection::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)
super::normalize_projection::preview_from_document(document)
}
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);
}
super::normalize_security::attach_operation_findings(&mut groups, &findings);
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);
}
@@ -584,6 +549,8 @@ fn canonicalize(
request_body_variants,
response_variants,
servers: operation.servers,
security_requirements: operation.security_requirements,
security_schemes: document.security_schemes.clone(),
findings: operation_findings,
})
})
@@ -765,6 +732,7 @@ fn canonicalize(
unresolved_references,
reference_graph,
source,
security_schemes: document.security_schemes,
operations,
findings,
coverage,
@@ -774,7 +742,11 @@ fn canonicalize(
}
pub fn validate_normalized_ir(ir: &NormalizedIr) -> Result<(), ImportParseError> {
if ir.normalizer_version != NORMALIZER_VERSION || ir.projection_version != PROJECTION_VERSION {
if !((ir.normalizer_version == NORMALIZER_VERSION
&& ir.projection_version == PROJECTION_VERSION)
|| (ir.normalizer_version == crate::rest::model::HISTORICAL_NORMALIZER_VERSION
&& ir.projection_version == crate::rest::model::HISTORICAL_PROJECTION_VERSION))
{
return Err(ImportParseError::InvalidDocument);
}
validate_reference_graph(ir)?;
@@ -927,7 +899,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),
@@ -4,9 +4,9 @@ use serde_json::Value;
use crate::rest::model::{
CanonicalSourceNode, CanonicalSourceValue, CoverageDisposition, CoverageEntry,
ImportSourcePreview, NORMALIZER_VERSION, NormalizedIr, NormalizedOperation, NormalizedPath,
NormalizedReference, NormalizedSchema, NormalizedSchemaKind, PROJECTION_VERSION,
SourceLocation,
HISTORICAL_NORMALIZER_VERSION, HISTORICAL_PROJECTION_VERSION, ImportSourcePreview,
NORMALIZER_VERSION, NormalizedIr, NormalizedOperation, NormalizedPath, NormalizedReference,
NormalizedSchema, NormalizedSchemaKind, PROJECTION_VERSION, SourceLocation,
};
use super::ImportParseError;
@@ -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 {
if !((ir.normalizer_version == NORMALIZER_VERSION
&& ir.projection_version == PROJECTION_VERSION)
|| (ir.normalizer_version == HISTORICAL_NORMALIZER_VERSION
&& ir.projection_version == HISTORICAL_PROJECTION_VERSION))
{
return Err(ImportParseError::InvalidDocument);
}
let mut source_nodes = BTreeMap::new();
@@ -54,17 +54,101 @@ pub(super) fn matches_source(
&& matches!(&node.value, CanonicalSourceValue::Array(items) if items.iter().any(|item| !matches!(item.value, CanonicalSourceValue::String(_))))
}
"secret_like_example" if finding.severity == ImportFindingSeverity::Warning => {
pointer.contains("/example") && matches!(&node.value, CanonicalSourceValue::String(value) if secret_like(pointer, value))
matches!(&node.value, CanonicalSourceValue::String(value)
if secret_like(pointer, value)
|| super::metadata_findings::url_has_secret(value)
|| (pointer.ends_with("/url") && !value.contains('@'))
|| value == super::metadata_findings::REDACTED_LITERAL
|| sanitized_secret_url(value))
}
"invalid_server" if is_error => invalid_server(pointer, node),
"unsupported_security_requirement" if is_error => {
matches!(&node.value, CanonicalSourceValue::Object(fields) if !fields.is_empty())
|| invalid_security_requirement(pointer, node)
}
"invalid_security_requirements" if is_error => {
!matches!(&node.value, CanonicalSourceValue::Array(_))
|| matches!(&node.value, CanonicalSourceValue::Array(items) if items.iter().any(|item| !matches!(item.value, CanonicalSourceValue::Object(_))))
}
"invalid_security_requirement" if finding.severity == ImportFindingSeverity::Warning => {
!matches!(&node.value, CanonicalSourceValue::Object(_))
}
"unsupported_security_requirements" if is_error => ir
.operations
.iter()
.find(|operation| finding.operation_key.as_deref() == Some(operation.key.as_str()))
.is_some_and(|operation| {
!operation.security_requirements.alternatives.is_empty()
&& operation
.security_requirements
.alternatives
.iter()
.all(|alternative| !alternative.supported)
}),
"unsupported_security_and_requirement"
if finding.severity == ImportFindingSeverity::Warning =>
{
matches!(&node.value, CanonicalSourceValue::Object(fields) if fields.len() > 1)
}
"unsupported_security_scheme" if finding.severity == ImportFindingSeverity::Warning => {
let scheme_name = pointer
.rsplit('/')
.next()
.unwrap_or_default()
.replace("~1", "/")
.replace("~0", "~");
ir.security_schemes.get(&scheme_name).is_some_and(|scheme| {
matches!(&scheme.kind, crate::rest::model::NormalizedSecuritySchemeKind::Unsupported { .. })
|| matches!(&scheme.kind, crate::rest::model::NormalizedSecuritySchemeKind::ApiKey { location: crate::rest::model::SecurityParameterLocation::Cookie, .. })
}) && matches!(&node.value, CanonicalSourceValue::Array(_))
}
"unsupported_security_scheme_definition"
if finding.severity == ImportFindingSeverity::Warning =>
{
let scheme_name = pointer
.rsplit('/')
.next()
.unwrap_or_default()
.replace("~1", "/")
.replace("~0", "~");
ir.security_schemes.get(&scheme_name).is_some_and(|scheme| {
matches!(&scheme.kind, crate::rest::model::NormalizedSecuritySchemeKind::Unsupported { .. })
}) && matches!(&node.value, CanonicalSourceValue::Object(_))
}
"unresolved_security_scheme" if finding.severity == ImportFindingSeverity::Warning => {
let scheme_name = pointer
.rsplit('/')
.next()
.unwrap_or_default()
.replace("~1", "/")
.replace("~0", "~");
!ir.security_schemes.contains_key(&scheme_name)
}
"invalid_security_scopes" if finding.severity == ImportFindingSeverity::Warning => {
!matches!(&node.value, CanonicalSourceValue::Array(items) if items.iter().all(|item| matches!(item.value, CanonicalSourceValue::String(_))))
}
"unexpected_security_scopes" if finding.severity == ImportFindingSeverity::Warning => {
let scheme_name = pointer
.rsplit('/')
.next()
.unwrap_or_default()
.replace("~1", "/")
.replace("~0", "~");
let supports_scopes = ir.security_schemes.get(&scheme_name).is_some_and(|scheme| {
matches!(&scheme.kind, crate::rest::model::NormalizedSecuritySchemeKind::Unsupported { scheme_type: Some(kind) } if matches!(kind.as_str(), "oauth2" | "openIdConnect"))
});
!supports_scopes
&& matches!(&node.value, CanonicalSourceValue::Array(items) if !items.is_empty())
}
_ => false,
}
}
fn sanitized_secret_url(value: &str) -> bool {
value.contains("=[REDACTED]")
|| ((value.contains("://") || value.starts_with("//")) && !value.contains('@'))
}
fn parameter_style(
pointer: &str,
node: &CanonicalSourceNode,
@@ -1,18 +1,113 @@
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use serde_json::Value;
use crate::rest::model::{
ImportFinding, NormalizedLiteral, NormalizedOperation, NormalizedScalarKind, NormalizedSchema,
NormalizedSchemaKind, RestImportOperation, RestImportParameter, RestRequestBodyVariant,
RestResponseVariant,
ImportFinding, ImportGroupPreview, ImportOperationCandidate, ImportPreview,
ImportSourcePreview, NormalizedLiteral, NormalizedOperation, NormalizedScalarKind,
NormalizedSchema, NormalizedSchemaKind, NormalizedSecurityScheme, RestImportDocument,
RestImportOperation, RestImportParameter, RestRequestBodyVariant, RestResponseVariant,
};
pub(super) fn preview_from_ir(ir: &crate::rest::model::NormalizedIr) -> ImportPreview {
let operations = ir
.operations
.iter()
.map(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,
&ir.security_schemes,
false,
)
}
pub(super) fn preview_from_document(document: RestImportDocument) -> ImportPreview {
let security_schemes = document.security_schemes.clone();
let source = ImportSourcePreview {
format: document.format,
version: document.version,
title: document.title,
servers: document.servers,
};
preview_from_operations(
&source,
document.operations.iter(),
document.findings,
&security_schemes,
true,
)
}
fn preview_from_operations<'a>(
source: &ImportSourcePreview,
operations: impl Iterator<Item = &'a RestImportOperation>,
mut findings: Vec<ImportFinding>,
security_schemes: &BTreeMap<String, NormalizedSecurityScheme>,
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 {
crate::rest::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::<ImportOperationCandidate>::new(),
})
.operations
.push(candidate);
}
super::normalize_security::attach_operation_findings(&mut groups, &findings);
super::normalize::sort_findings(&mut findings);
ImportPreview {
source: source.clone(),
groups: groups.into_values().collect(),
findings,
}
}
pub(super) fn operation_from_normalized(operation: &NormalizedOperation) -> RestImportOperation {
RestImportOperation {
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(),
@@ -1,13 +1,6 @@
//! Effective per-operation security scopes for the OpenAPI importer.
use serde_json::Value;
//! Attaches document-level findings to their affected operation candidates.
use super::{
model::{
ImportFinding, ImportFindingSeverity, ImportGroupPreview, RestImportDocument,
RestImportOperation, SourceLocation,
},
normalize_coverage,
};
use super::model::{ImportFinding, ImportFindingSeverity, ImportGroupPreview};
pub(super) fn attach_operation_findings(
groups: &mut std::collections::BTreeMap<String, ImportGroupPreview>,
@@ -32,135 +25,3 @@ pub(super) fn attach_operation_findings(
}
}
}
/// Computes the effective security requirements for every candidate operation
/// and attaches source-located blockers to precisely the affected candidates.
///
/// Effective requirements follow the OpenAPI semantics: an operation that
/// declares its own `security` member wins over the document root; an empty
/// array (`security: []`) explicitly disables inheritance. Within a
/// requirement array the items are alternatives (OR): an empty requirement
/// object `{}` is the public alternative and makes the whole operation
/// public, so no blocker is produced for that operation.
///
/// A malformed security shape — a non-array `security` value or a non-object
/// array item — must never be discarded silently: the affected operation
/// receives one blocker with the exact source location. A supported non-empty
/// requirement remains a blocker until an administrator binds a compatible
/// Auth Profile.
pub(super) fn append_security_requirement_findings(parsed: &mut RestImportDocument, root: &Value) {
let operations = &parsed.operations;
let findings = &mut parsed.findings;
let locations = &mut parsed.internal_finding_locations;
let root_security = root.get("security");
for operation in operations {
let Some(path_item) = root
.pointer(&format!(
"/paths/{}",
normalize_coverage::escape_pointer(&operation.path)
))
.and_then(|item| item.get(method_as_lower(operation)))
else {
continue;
};
let Some(security) = path_item
.get("security")
.or_else(|| root_security.filter(|_| path_item.get("security").is_none()))
else {
continue;
};
let base_pointer = if path_item.get("security").is_some() {
format!(
"/paths/{}/{}/security",
normalize_coverage::escape_pointer(&operation.path),
method_as_lower(operation)
)
} else {
"/security".to_owned()
};
let alternatives = match security.as_array() {
Some(alternatives) => alternatives,
None => {
push_security_blocker(
findings,
locations,
operation,
&base_pointer,
"security имеет некорректный формат: ожидается массив требований; операции с незапакованным блоком безопасности не публикуются.",
);
continue;
}
};
// Validate the item shapes first: only a fully well-formed array may
// use the empty requirement object `{}` as its public OR alternative.
if !alternatives
.iter()
.all(|requirement| requirement.as_object().is_some())
{
for (index, requirement) in alternatives.iter().enumerate() {
let pointer = format!("{base_pointer}/{index}");
match requirement.as_object() {
Some(schemes) if schemes.is_empty() => {
// In a malformed array the empty alternative does
// not make the operation public, but it also cannot
// block on its own.
continue;
}
Some(_) => push_security_blocker(
findings,
locations,
operation,
&pointer,
"Требование безопасности должно быть привязано к настроенному Auth Profile перед публикацией этой операции; остальные операции не блокируются.",
),
None => push_security_blocker(
findings,
locations,
operation,
&pointer,
"security содержит альтернативу без объекта требований: формат не поддерживается, операция не публикуется.",
),
}
}
continue;
}
if alternatives.iter().any(|requirement| {
requirement
.as_object()
.is_some_and(serde_json::Map::is_empty)
}) {
continue;
}
for (index, _) in alternatives.iter().enumerate() {
push_security_blocker(
findings,
locations,
operation,
&format!("{base_pointer}/{index}"),
"Требование безопасности должно быть привязано к настроенному Auth Profile перед публикацией этой операции; остальные операции не блокируются.",
);
}
}
}
fn push_security_blocker(
findings: &mut Vec<ImportFinding>,
locations: &mut Vec<Option<SourceLocation>>,
operation: &RestImportOperation,
pointer: &str,
message: &str,
) {
findings.push(ImportFinding {
code: "unsupported_security_requirement".to_owned(),
severity: ImportFindingSeverity::Error,
message: message.to_owned(),
operation_key: Some(operation.key.clone()),
});
locations.push(Some(SourceLocation {
pointer: pointer.to_owned(),
}));
}
fn method_as_lower(operation: &RestImportOperation) -> String {
format!("{:?}", operation.method).to_ascii_lowercase()
}
+34 -40
View File
@@ -1,6 +1,7 @@
use crank_core::HttpMethod;
use serde_json::Value;
use super::parser_findings::append_unused_security_scheme_findings as append_unused;
use crate::rest::{
model::{
ImportFinding, RestImportDocument, RestImportOperation, RestImportParameter,
@@ -15,6 +16,7 @@ pub fn parse_document(root: &Value) -> Result<RestImportDocument, ImportParseErr
}
fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseError> {
let security_schemes = super::security::schemes(root, false);
let version = root
.get("openapi")
.and_then(Value::as_str)
@@ -25,20 +27,16 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
.unwrap_or("Imported API")
.to_owned();
let mut findings = Vec::new();
let mut internal_finding_locations = Vec::new();
let mut locations = Vec::new();
let servers = parse_servers(root.get("servers"), "/servers");
append_findings_with_locations(
&mut findings,
&mut internal_finding_locations,
servers.findings,
);
super::parser_findings::append_located(&mut findings, &mut locations, servers.findings);
let servers = servers.servers;
if servers.is_empty() {
findings.push(document_finding(
"missing_servers",
"В документе не указаны servers, base URL нужно будет выбрать вручную.",
));
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
locations.push(Some(crate::rest::model::SourceLocation {
pointer: String::new(),
}));
} else if servers.len() > 1 {
@@ -46,7 +44,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
"multiple_servers",
"В документе несколько servers, при импорте нужно выбрать нужный base URL.",
));
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
locations.push(Some(crate::rest::model::SourceLocation {
pointer: "/servers".to_owned(),
}));
}
@@ -60,7 +58,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
for (path, path_item) in paths {
if !path_item.is_object() {
findings.push(super::http_methods::invalid_path_item());
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
locations.push(Some(crate::rest::model::SourceLocation {
pointer: format!("/paths/{}", path.replace('~', "~0").replace('/', "~1")),
}));
continue;
@@ -71,7 +69,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
"unsupported_http_method",
format!("Метод {method_name} для пути {path} пока не поддерживается."),
));
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
locations.push(Some(crate::rest::model::SourceLocation {
pointer: format!(
"/paths/{}/{}",
path.replace('~', "~0").replace('/', "~1"),
@@ -85,17 +83,17 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
path_item.get("parameters"),
&format!("{path_pointer}/parameters"),
);
append_findings_with_locations(
super::parser_findings::append_located(
&mut findings,
&mut internal_finding_locations,
&mut locations,
path_parameters.findings,
);
let path_parameters = path_parameters.parameters;
let path_servers =
parse_servers(path_item.get("servers"), &format!("{path_pointer}/servers"));
append_findings_with_locations(
super::parser_findings::append_located(
&mut findings,
&mut internal_finding_locations,
&mut locations,
path_servers.findings,
);
let path_servers = path_servers.servers;
@@ -108,7 +106,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
"invalid_operation",
"Операция имеет неверную структуру и не была интерпретирована.",
));
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
locations.push(Some(crate::rest::model::SourceLocation {
pointer: format!(
"/paths/{}/{}",
path.replace('~', "~0").replace('/', "~1"),
@@ -127,9 +125,9 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
operation_value.get("parameters"),
&format!("{path_pointer}/{method_name}/parameters"),
);
append_findings_with_locations(
super::parser_findings::append_located(
&mut findings,
&mut internal_finding_locations,
&mut locations,
parsed_parameters.findings,
);
operation_parameters.extend(parsed_parameters.parameters);
@@ -138,9 +136,9 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
operation_value.get("servers"),
&format!("{operation_pointer}/servers"),
);
append_findings_with_locations(
super::parser_findings::append_located(
&mut findings,
&mut internal_finding_locations,
&mut locations,
operation_servers.findings,
);
let operation_servers = operation_servers.servers;
@@ -148,20 +146,23 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
operation_value.get("tags"),
&format!("{operation_pointer}/tags"),
);
append_findings_with_locations(
&mut findings,
&mut internal_finding_locations,
tags.findings,
);
super::parser_findings::append_located(&mut findings, &mut locations, tags.findings);
let mut located_operation_findings =
super::openapi3_findings::operation(operation_value, &operation_pointer);
let (security_requirements, security_findings) =
super::security::collect_operation_requirements(
root,
operation_value,
&operation_pointer,
&security_schemes,
);
located_operation_findings.extend(security_findings);
located_operation_findings.extend(super::openapi3_findings::path_parameters(
path,
&operation_parameters,
));
let (operation_findings, internal_finding_locations) =
located_operation_findings.into_iter().unzip();
let (operation_findings, locations) = located_operation_findings.into_iter().unzip();
let response_schema = (method != HttpMethod::Head)
.then(|| response_schema(operation_value, &operation_pointer))
.flatten();
@@ -169,6 +170,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)
@@ -200,19 +202,20 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
operation_servers
},
findings: operation_findings,
internal_finding_locations,
internal_finding_locations: locations,
});
}
}
append_unused(root, &security_schemes, &mut findings, &mut locations);
Ok(RestImportDocument {
format: "openapi".to_owned(),
version,
title,
servers,
security_schemes,
operations,
findings,
internal_finding_locations,
internal_finding_locations: locations,
})
}
@@ -277,6 +280,7 @@ pub fn parse_document_legacy_v1(root: &Value) -> Result<RestImportDocument, Impo
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)
@@ -308,6 +312,7 @@ pub fn parse_document_legacy_v1(root: &Value) -> Result<RestImportDocument, Impo
version,
title,
servers,
security_schemes: Default::default(),
operations,
findings,
internal_finding_locations: Vec::new(),
@@ -700,17 +705,6 @@ fn parameter_blocker(
)
}
fn append_findings_with_locations(
findings: &mut Vec<ImportFinding>,
locations: &mut Vec<Option<crate::rest::model::SourceLocation>>,
parameter_findings: Vec<(ImportFinding, crate::rest::model::SourceLocation)>,
) {
for (finding, location) in parameter_findings {
findings.push(finding);
locations.push(Some(location));
}
}
fn request_body_schema(
operation: &Value,
operation_pointer: &str,
@@ -0,0 +1,28 @@
use crate::rest::model::NormalizedSecurityScheme;
use crate::rest::model::{ImportFinding, SourceLocation};
use serde_json::Value;
use std::collections::BTreeMap;
pub(super) fn append_located(
findings: &mut Vec<ImportFinding>,
locations: &mut Vec<Option<SourceLocation>>,
entries: Vec<(ImportFinding, SourceLocation)>,
) {
for (finding, location) in entries {
findings.push(finding);
locations.push(Some(location));
}
}
pub(super) fn append_unused_security_scheme_findings(
root: &Value,
schemes: &BTreeMap<String, NormalizedSecurityScheme>,
findings: &mut Vec<ImportFinding>,
locations: &mut Vec<Option<SourceLocation>>,
) {
append_located(
findings,
locations,
super::security::unused_unsupported_scheme_findings(root, schemes),
);
}
+3
View File
@@ -21,6 +21,7 @@ use crate::rest::{
pub fn candidate_from_operation(
operation: &RestImportOperation,
security_schemes: &BTreeMap<String, crate::rest::model::NormalizedSecurityScheme>,
document_servers: &[String],
used_names: &mut BTreeSet<String>,
) -> ImportOperationCandidate {
@@ -154,6 +155,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,
+462
View File
@@ -0,0 +1,462 @@
//! Typed security scheme extraction and effective requirement
//! classification for OpenAPI 3.x and Swagger 2.0 documents.
//!
//! The module is pure: it never reads Auth Profiles or Secrets and never
//! captures credential values. Requirements are classified alternative by
//! alternative (OR semantics preserved): a supported single-scheme
//! alternative stays resolvable via a compatible Auth Profile; malformed
//! requirements, unresolvable schemes and AND combinations mark the
//! affected alternative as unsupported; an operation is blocked only when
//! none of its alternatives is selectable.
use std::collections::BTreeMap;
use serde_json::Value;
use super::model::{
ImportFinding, NormalizedSecurityRequirements, NormalizedSecurityScheme,
NormalizedSecuritySchemeKind, SecurityParameterLocation, SecurityRequirementAlternative,
SecurityRequirementsSource, SourceLocation,
};
use super::recommendations::{document_blocker, document_finding};
/// Extracts typed schema metadata from `components.securitySchemes`
/// (OpenAPI) or `securityDefinitions` (Swagger 2.0). Only scheme names,
/// kinds, locations and safe format hints are preserved; credential values
/// are never captured.
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()
}
/// Reports unsupported scheme definitions that are never used by a security
/// requirement. They still need manual configuration, but cannot affect an
/// operation that does not select them.
pub(super) fn unused_unsupported_scheme_findings(
root: &Value,
schemes: &BTreeMap<String, NormalizedSecurityScheme>,
) -> Vec<(ImportFinding, SourceLocation)> {
let mut used = std::collections::BTreeSet::new();
collect_requirement_names(root.get("security"), &mut used);
if let Some(paths) = root.get("paths").and_then(Value::as_object) {
for path_item in paths.values().filter_map(Value::as_object) {
for operation in path_item.values().filter_map(Value::as_object) {
collect_requirement_names(operation.get("security"), &mut used);
}
}
}
schemes
.iter()
.filter_map(|(name, scheme)| {
if used.contains(name)
|| !matches!(
&scheme.kind,
NormalizedSecuritySchemeKind::Unsupported { .. }
)
{
return None;
}
Some((
document_finding(
"unsupported_security_scheme_definition",
format!(
"Объявленная схема {name} пока не поддерживается и не используется операциями; настройте authentication вручную, если она потребуется."
),
),
scheme.source_location.clone(),
))
})
.collect()
}
fn collect_requirement_names(value: Option<&Value>, used: &mut std::collections::BTreeSet<String>) {
let Some(alternatives) = value.and_then(Value::as_array) else {
return;
};
for alternative in alternatives.iter().filter_map(Value::as_object) {
used.extend(alternative.keys().cloned());
}
}
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)) if !parameter_name.is_empty() => {
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 ")
}
/// Computes the effective requirement for one operation: the operation
/// `security` member wins over the document root; a missing member means no
/// requirement. Every array item is one OR alternative and is classified
/// independently, so a single unsupported alternative never collapses
/// supported siblings into a false AND.
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 {
return (
NormalizedSecurityRequirements {
source: SecurityRequirementsSource::None,
alternatives: Vec::new(),
},
Vec::new(),
);
};
let mut findings = Vec::new();
let Some(alternatives) = value.and_then(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;
let mut has_malformed_alternative = false;
for (alternative_index, alternative) in alternatives.iter().enumerate() {
let alternative_pointer = format!("{pointer}/{alternative_index}");
let Some(requirement) = alternative.as_object() else {
has_malformed_alternative = true;
findings.push((
document_finding(
"invalid_security_requirement",
"Security alternative имеет неверную структуру и недоступна для выбора.",
),
SourceLocation {
pointer: alternative_pointer.clone(),
},
));
projected.push(SecurityRequirementAlternative {
schemes: Vec::new(),
supported: false,
findings: vec!["invalid_security_requirement".to_owned()],
source_location: Some(SourceLocation {
pointer: alternative_pointer,
}),
});
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 has_malformed_alternative || (!projected.is_empty() && supported_alternatives == 0) {
findings.push((
document_blocker(
if has_malformed_alternative {
"invalid_security_requirements"
} else {
"unsupported_security_requirements"
},
if has_malformed_alternative {
"Security requirements содержат malformed alternative и блокируют импорт операции."
} else {
"Ни одну authentication alternative нельзя безопасно выбрать; импорт операции заблокирован."
},
),
SourceLocation { pointer },
));
}
(
NormalizedSecurityRequirements {
source,
alternatives: projected,
},
findings,
)
}
/// Convenience wrapper keeping the parser call site short. The operation
/// value must be the method object (`paths.{path}.{method}`); pointers use
/// the same JSON-pointer escaping as the rest of the importer.
pub(super) fn collect_operation_requirements(
root: &Value,
operation: &Value,
operation_pointer: &str,
schemes: &BTreeMap<String, NormalizedSecurityScheme>,
) -> (
NormalizedSecurityRequirements,
Vec<(super::model::ImportFinding, SourceLocation)>,
) {
effective_requirements(root, operation, operation_pointer, schemes)
}
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")
)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn empty_api_key_parameter_name_is_unsupported() {
for swagger in [false, true] {
let definition = json!({ "type": "apiKey", "in": "header", "name": "" });
let root = if swagger {
json!({ "securityDefinitions": { "Key": definition } })
} else {
json!({ "components": { "securitySchemes": { "Key": definition } } })
};
let schemes = schemes(&root, swagger);
assert!(matches!(
schemes["Key"].kind,
NormalizedSecuritySchemeKind::Unsupported { .. }
));
let (requirements, findings) = effective_requirements(
&root,
&json!({ "security": [{ "Key": [] }] }),
"/paths/~1secure/get",
&schemes,
);
assert!(!requirements.alternatives[0].supported);
assert!(
findings
.iter()
.any(|(finding, _)| { finding.code == "unsupported_security_requirements" })
);
}
}
}
@@ -0,0 +1,82 @@
use crate::rest::model::{ExternalDocumentSnapshot, SourceDigest};
use super::model::NormalizationConfig;
use super::{
metadata_findings,
normalize::{ImportParseError, decode, validate_value_limits},
normalize_limits, reference,
};
/// Rejects a source bundle containing credential-like literals before any
/// primary or dependency bytes are persisted. Credential names are collected
/// across all raw documents so split `$ref` targets receive the same checks.
pub fn validate_document_bundle_source_safe(
documents: &[&str],
config: &NormalizationConfig,
) -> Result<(), ImportParseError> {
config
.validate_versions()
.map_err(|_| ImportParseError::UnsupportedDocument)?;
let mut roots = Vec::with_capacity(documents.len());
for document in documents {
if document.len() > config.max_bytes
|| normalize_limits::alias_count(document) > config.max_aliases
{
return Err(ImportParseError::LimitExceeded);
}
let root = decode(document)?;
validate_value_limits(&root, config)?;
roots.push(root);
}
let declared_names = metadata_findings::credential_names(roots.iter());
for mut root in roots {
let mut findings = Vec::new();
let mut locations = Vec::new();
metadata_findings::redact_secret_like_literals_with_names(
&mut root,
"",
&declared_names,
&mut findings,
&mut locations,
);
if !findings.is_empty() {
return Err(ImportParseError::InvalidDocument);
}
}
Ok(())
}
/// Validates the resolved source tree with the same security-aware traversal
/// used by normalization, before a caller persists any bytes in the bundle.
pub fn validate_resolved_bundle_source_safe(
document: &str,
digest: SourceDigest,
snapshots: &[ExternalDocumentSnapshot],
config: &NormalizationConfig,
) -> Result<(), ImportParseError> {
config
.validate_versions()
.map_err(|_| ImportParseError::UnsupportedDocument)?;
if document.len() > config.max_bytes
|| normalize_limits::alias_count(document) > config.max_aliases
{
return Err(ImportParseError::LimitExceeded);
}
let root = decode(document)?;
validate_value_limits(&root, config)?;
for snapshot in snapshots {
if snapshot.document.len() > config.max_external_document_bytes {
return Err(ImportParseError::LimitExceeded);
}
}
let resolution = reference::resolve(root, digest, snapshots, config)?;
let mut root = resolution.root;
validate_value_limits(&root, config)?;
let mut findings = Vec::new();
let mut locations = Vec::new();
metadata_findings::redact_secret_like_literals(&mut root, "", &mut findings, &mut locations);
if !findings.is_empty() {
return Err(ImportParseError::InvalidDocument);
}
Ok(())
}
+22 -14
View File
@@ -15,6 +15,7 @@ pub fn parse_document(root: &Value) -> Result<RestImportDocument, ImportParseErr
}
fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseError> {
let security_schemes = super::security::schemes(root, true);
let title = root
.pointer("/info/title")
.and_then(Value::as_str)
@@ -23,7 +24,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
let servers = swagger_servers(root);
let mut findings = Vec::new();
let mut internal_finding_locations = Vec::new();
append_parameter_findings(
super::parser_findings::append_located(
&mut findings,
&mut internal_finding_locations,
super::swagger2_findings::servers(root),
@@ -73,7 +74,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
path_item.get("parameters"),
&format!("{path_pointer}/parameters"),
);
append_parameter_findings(
super::parser_findings::append_located(
&mut findings,
&mut internal_finding_locations,
path_parameters.findings,
@@ -113,7 +114,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
operation_value.get("tags"),
&format!("{path_pointer}/{method_name}/tags"),
);
append_parameter_findings(
super::parser_findings::append_located(
&mut findings,
&mut internal_finding_locations,
tags.findings,
@@ -146,6 +147,14 @@ 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, security_findings) =
super::security::collect_operation_requirements(
root,
operation_value,
&operation_pointer,
&security_schemes,
);
located_operation_findings.extend(security_findings);
located_operation_findings.extend(parsed_parameter_findings);
located_operation_findings.extend(super::swagger2_findings::path_parameters(
path,
@@ -160,6 +169,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)
@@ -194,11 +204,18 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
}
}
super::parser_findings::append_located(
&mut findings,
&mut internal_finding_locations,
super::security::unused_unsupported_scheme_findings(root, &security_schemes),
);
Ok(RestImportDocument {
format: "swagger".to_owned(),
version: Some("2.0".to_owned()),
title,
servers,
security_schemes,
operations,
findings,
internal_finding_locations,
@@ -264,6 +281,7 @@ pub fn parse_document_legacy_v1(root: &Value) -> Result<RestImportDocument, Impo
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)
@@ -295,6 +313,7 @@ pub fn parse_document_legacy_v1(root: &Value) -> Result<RestImportDocument, Impo
version: Some("2.0".to_owned()),
title,
servers,
security_schemes: Default::default(),
operations,
findings,
internal_finding_locations: Vec::new(),
@@ -651,17 +670,6 @@ fn parameter_blocker(
)
}
fn append_parameter_findings(
findings: &mut Vec<ImportFinding>,
locations: &mut Vec<Option<crate::rest::model::SourceLocation>>,
parameter_findings: Vec<(ImportFinding, crate::rest::model::SourceLocation)>,
) {
for (finding, location) in parameter_findings {
findings.push(finding);
locations.push(Some(location));
}
}
fn swagger_parameter_schema(_root: &Value, parameter: &Value) -> Option<Value> {
if let Some(schema) = parameter.get("schema") {
return Some(schema.clone());