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());
@@ -0,0 +1,29 @@
{
"actionable_count": 50,
"content_digest": "a5c4d3c1da8ce9bcc820a97b3260bcef0fa2bd321493c35f03a4949541ec5462",
"content_digest_algorithm": "sha256",
"content_digest_definition": "SHA-256 of compact key-sorted JSON before the content_digest field is added.",
"corpus_version": "1.0.3",
"denominator": 50,
"evidence_identity": "089a330a8055dc50b96a4ac39ae8c364d08610171b952f1a2f2e942cfbb94c49",
"evidence_version": "1.0.0",
"exclusions": [],
"manifest_digest": "99ca69fb5ac10d637181a507d9e29d81888a9d4696a708ce6c3ac2b63eb61d57",
"matrix_contract": {
"construct_rows": 384,
"semantic_probes": "AC-1 runs a generated normalizer probe for every matrix row, including every 2xx status in all three formats."
},
"matrix_digest": "bf6419574fe27e2244ba6ace51bbc8f8be5936be9e0884fd25b253ad3c8cd9b8",
"matrix_version": "1.0.2",
"method": "real normalize_verified_document + preview_from_ir; every NormalizedIr passed validate_normalized_ir",
"raw_counts": {
"covered_source_constructs": 1837,
"documents": 63,
"findings": 0,
"representative_operations": 50,
"semantic_coverage_entries": 514,
"source_constructs": 1837
},
"silent_loss_count": 0,
"uncovered_source_constructs": []
}
+12 -43
View File
@@ -576,35 +576,13 @@ fn ac_2_manifest_covers_fifty_provenanced_specs_with_exact_expectations() {
"security-scope fixture must keep both candidates explicit: {:?}",
ir.operations.iter().map(|op| &op.key).collect::<Vec<_>>()
);
let requirements = ir
.findings
.iter()
.filter(|finding| finding.code == "unsupported_security_requirement")
.collect::<Vec<_>>();
assert_eq!(
requirements.len(),
1,
"exactly the inherited requirement must produce a blocker: {:?}",
ir.findings
);
let requirement = &requirements[0];
assert_eq!(
requirement.severity,
crank_import::rest::ImportFindingSeverity::Error,
"security requirement must block its candidate: {:?}",
requirement
);
assert_eq!(
requirement.operation_key.as_deref(),
Some("GET /secure"),
"blocker must belong only to the inherited secured candidate: {:?}",
requirement
);
assert_eq!(
requirement.location.pointer, "/security/0",
"inherited requirement must point at the document root requirement: {:?}",
requirement
);
let requirements = ir.findings.iter().filter(|finding| {
finding.code == "unsupported_security_requirements"
}).collect::<Vec<_>>();
assert!(requirements.is_empty(), "supported inherited basic requirement must remain selectable: {:?}", ir.findings);
let secured_operation = ir.operations.iter().find(|operation| operation.key == "GET /secure").unwrap();
assert!(secured_operation.security_requirements.alternatives[0].supported);
assert_eq!(secured_operation.security_requirements.alternatives[0].source_location.as_ref().unwrap().pointer, "/security/0");
let mut by_key = std::collections::BTreeMap::new();
for group in &preview.groups {
for candidate in &group.operations {
@@ -618,18 +596,9 @@ fn ac_2_manifest_covers_fifty_provenanced_specs_with_exact_expectations() {
"public operation with security: [] must stay actionable: {:?}",
public.findings
);
assert!(
by_key
.get("GET /secure")
.expect("secured candidate present")
.findings
.iter()
.any(|finding| finding.code == "unsupported_security_requirement"
&& finding.severity
== crank_import::rest::ImportFindingSeverity::Error),
"inherited requirement must block the secured candidate: {:?}",
by_key.get("GET /secure").unwrap().findings
);
assert!(by_key.get("GET /secure").expect("secured candidate present").findings.iter().all(|finding| {
finding.severity != crank_import::rest::ImportFindingSeverity::Error
}), "supported security must remain selectable before API binding: {:?}", by_key.get("GET /secure").unwrap().findings);
assert!(
preview
.findings
@@ -642,8 +611,8 @@ fn ac_2_manifest_covers_fifty_provenanced_specs_with_exact_expectations() {
ir.coverage
.iter()
.any(|entry| entry.location.pointer == "/security/0"
&& entry.disposition == CoverageDisposition::Finding),
"inherited requirement must stay in the source ledger bound to the finding: {:?}",
&& entry.disposition == CoverageDisposition::Mapped),
"inherited requirement must stay mapped in the source ledger: {:?}",
ir.coverage
);
let mut actual_operation_keys = preview
@@ -14405,16 +14405,9 @@
"GET /secure"
],
"warning_findings": [],
"blocker_findings": [
{
"code": "unsupported_security_requirement",
"severity": "Error",
"operation_key": "GET /secure",
"location": "/security/0"
}
]
"blocker_findings": []
}
}
],
"compatibility_impact": "Corpus 1.0.3 adds hostile-security-scope.json: an effective-security-scope fixture showing that a document-level requirement blocks only the inherited candidate (GET /secure, location /security/0) while the public candidate with an explicit security: [] stays actionable and no document-global blocker is produced; all 50 representative previews and the previous hostile oracles are unchanged."
"compatibility_impact": "Corpus 1.0.3 adds hostile-security-scope.json: an effective-security-scope fixture showing that a document-level basic requirement remains selectable on the inherited candidate (GET /secure, location /security/0) while the public candidate with an explicit security: [] stays public; malformed or unsupported requirements retain scoped blockers."
}
+66 -58
View File
@@ -172,53 +172,63 @@ fn ac_1_support_matrix_rows_have_exact_construct_contracts() {
"paths":{"/probe":{"get":{"security":[{"probe":[]}],"operationId":"securityProbe","responses":{"200":{"description":"ok"}}}}}
})
};
assert_eq!(
row["status"], "unsupported",
"security is not yet persisted as Auth Profile semantics"
);
let source = serde_json::to_string(&probe).unwrap();
let ir = normalize(&source).unwrap();
validate_normalized_ir(&ir).unwrap();
let expected_finding = row["expected_finding"].as_str().unwrap();
let requirement = ir
.findings
.iter()
.find(|finding| {
finding.code == expected_finding
&& finding.severity == crank_import::rest::ImportFindingSeverity::Error
})
.unwrap_or_else(|| {
panic!(
"{version} {construct} must be explicitly blocked: {:?}",
ir.findings
)
});
assert_eq!(
requirement.operation_key.as_deref(),
Some("GET /probe"),
"{version} {construct} blocker must belong to the affected candidate"
);
assert_eq!(
requirement.location.pointer, "/paths/~1probe/get/security/0",
"{version} {construct} blocker must point at the local requirement"
);
let preview = preview_from_ir(&ir);
let candidate = &preview.groups[0].operations[0];
assert!(
candidate
let requirement = &ir.operations[0].security_requirements.alternatives[0];
if expected_finding == "none" {
assert!(
requirement.supported,
"{version} {construct} is not selectable"
);
assert!(
candidate.findings.iter().all(|finding| {
finding.severity != crank_import::rest::ImportFindingSeverity::Error
}),
"{version} {construct} unexpectedly blocked: {:?}",
candidate.findings
);
assert!(ir.security_schemes.contains_key("probe"));
assert!(
ir.coverage.iter().any(|entry| {
entry.location.pointer == "/paths/~1probe/get/security/0"
&& entry.disposition == CoverageDisposition::Mapped
}),
"{version} {construct} requirement has no mapped source coverage"
);
} else {
let finding = ir
.findings
.iter()
.any(|finding| finding.code == expected_finding
&& finding.severity == crank_import::rest::ImportFindingSeverity::Error),
"{version} {construct} candidate must be blocked: {:?}",
candidate.findings
);
assert!(
ir.coverage.iter().any(|entry| entry.location.pointer
== "/paths/~1probe/get/security/0"
&& entry.disposition == CoverageDisposition::Finding),
"{version} {construct} has no finding coverage"
);
.chain(
ir.operations
.iter()
.flat_map(|operation| operation.findings.iter()),
)
.find(|finding| {
finding.code == expected_finding
&& finding.severity == crank_import::rest::ImportFindingSeverity::Error
})
.unwrap_or_else(|| {
panic!("{version} {construct} missing blocker: {:?}", ir.findings)
});
assert_eq!(finding.operation_key.as_deref(), Some("GET /probe"));
assert_eq!(finding.location.pointer, "/paths/~1probe/get/security");
assert!(
candidate
.findings
.iter()
.any(|finding| finding.code == expected_finding
&& finding.severity
== crank_import::rest::ImportFindingSeverity::Error)
);
assert!(ir.coverage.iter().any(|entry| entry.location.pointer
== "/paths/~1probe/get/security"
&& entry.disposition == CoverageDisposition::Finding));
}
probed(&construct);
}
{
@@ -301,23 +311,21 @@ fn ac_1_support_matrix_rows_have_exact_construct_contracts() {
.unwrap()["expected_finding"]
.as_str()
.unwrap();
let requirements = ir
.findings
assert_eq!(expected_finding, "none");
let secured_operation = ir
.operations
.iter()
.filter(|finding| finding.code == expected_finding)
.collect::<Vec<_>>();
.find(|operation| operation.key == "GET /secured")
.unwrap();
assert!(secured_operation.security_requirements.alternatives[0].supported);
assert_eq!(
requirements.len(),
1,
"exactly the inherited operation must be blocked: {:?}",
requirements
secured_operation.security_requirements.alternatives[0]
.source_location
.as_ref()
.unwrap()
.pointer,
"/security/0"
);
assert_eq!(
requirements[0].operation_key.as_deref(),
Some("GET /secured"),
"blocker must belong only to the affected candidate"
);
assert_eq!(requirements[0].location.pointer, "/security/0");
let preview = preview_from_ir(&ir);
let mut by_key = std::collections::BTreeMap::new();
for group in &preview.groups {
@@ -342,17 +350,17 @@ fn ac_1_support_matrix_rows_have_exact_construct_contracts() {
secured
.findings
.iter()
.any(|finding| finding.code == expected_finding
&& finding.severity == crank_import::rest::ImportFindingSeverity::Error),
"secured operation must be blocked: {:?}",
.all(|finding| finding.severity
!= crank_import::rest::ImportFindingSeverity::Error),
"supported secured operation must remain selectable before API binding: {:?}",
secured.findings
);
assert!(
ir.coverage
.iter()
.any(|entry| entry.location.pointer == "/security/0"
&& entry.disposition == CoverageDisposition::Finding),
"mixed probe has no finding coverage"
&& entry.disposition == CoverageDisposition::Mapped),
"mixed probe has no mapped security coverage"
);
probed(construct);
}
@@ -0,0 +1,799 @@
use crank_import::rest::{
ImportFindingSeverity, ImportOperationCandidate, NormalizationConfig,
NormalizedSecuritySchemeKind, SecurityParameterLocation, SecurityRequirementsSource,
SourceDigest, normalize_verified_document, preview_from_ir, validate_normalized_ir,
};
use serde_json::{Value, json};
fn normalize(document: &Value) -> crank_import::rest::NormalizedIr {
let text = serde_json::to_string(document).expect("fixture serializes");
normalize_verified_document(
&text,
SourceDigest::parse("b".repeat(64)).expect("digest is valid"),
&NormalizationConfig::default(),
)
.expect("security fixture normalizes")
}
fn candidate<'a>(
candidates: &'a [ImportOperationCandidate],
key: &str,
) -> &'a ImportOperationCandidate {
candidates
.iter()
.find(|candidate| candidate.key == key)
.unwrap_or_else(|| panic!("candidate {key} missing: {candidates:?}"))
}
fn candidates(ir: &crank_import::rest::NormalizedIr) -> Vec<ImportOperationCandidate> {
preview_from_ir(ir)
.groups
.into_iter()
.flat_map(|group| group.operations)
.collect()
}
fn operation<'a>(
ir: &'a crank_import::rest::NormalizedIr,
path: &str,
) -> &'a crank_import::rest::NormalizedOperation {
ir.operations
.iter()
.find(|operation| operation.path == path)
.unwrap_or_else(|| panic!("operation {path} missing: {ir:?}"))
}
#[test]
fn openapi_30_and_31_project_typed_schemes_and_safe_hints() {
for version in ["3.0.3", "3.1.0"] {
let document = json!({
"openapi": version,
"info": { "title": "Security metadata", "version": "1" },
"components": { "securitySchemes": {
"Bearer": { "type": "http", "scheme": "bearer", "bearerFormat": "JWT" },
"Basic": { "type": "http", "scheme": "basic" },
"HeaderKey": { "type": "apiKey", "in": "header", "name": "X-Api-Key" },
"QueryKey": { "type": "apiKey", "in": "query", "name": "access_token" },
"CookieKey": { "type": "apiKey", "in": "cookie", "name": "session" },
"UnsafeHint": { "type": "http", "scheme": "bearer", "bearerFormat": "sk-private-value" }
}},
"paths": { "/private": { "get": {
"security": [{ "Bearer": [] }],
"responses": { "200": { "description": "ok" } }
}}}
});
let ir = normalize(&document);
assert!(matches!(ir.security_schemes["Bearer"].kind,
NormalizedSecuritySchemeKind::Http { ref scheme, ref format_hint }
if scheme == "bearer" && format_hint.as_deref() == Some("JWT")));
assert!(matches!(ir.security_schemes["Basic"].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 == "access_token"));
assert!(matches!(ir.security_schemes["CookieKey"].kind,
NormalizedSecuritySchemeKind::ApiKey { location: SecurityParameterLocation::Cookie, ref parameter_name, .. }
if parameter_name == "session"));
assert!(matches!(
ir.security_schemes["UnsafeHint"].kind,
NormalizedSecuritySchemeKind::Http {
format_hint: None,
..
}
));
let requirement = &operation(&ir, "/private")
.security_requirements
.alternatives[0];
assert_eq!(requirement.schemes, ["Bearer"]);
assert!(requirement.supported);
}
}
#[test]
fn swagger2_projects_basic_and_api_key_header_and_query() {
let document = json!({
"swagger": "2.0",
"info": { "title": "Swagger security", "version": "1" },
"host": "security.example.test",
"schemes": ["https"],
"securityDefinitions": {
"BasicAuth": { "type": "basic" },
"HeaderKey": { "type": "apiKey", "in": "header", "name": "X-Api-Key" },
"QueryKey": { "type": "apiKey", "in": "query", "name": "api_key" },
"CookieKey": { "type": "apiKey", "in": "cookie", "name": "session" }
},
"security": [{ "BasicAuth": [] }, { "HeaderKey": [] }, { "QueryKey": [] }],
"paths": { "/private": { "get": {
"responses": { "200": { "description": "ok" } }
}}}
});
let ir = normalize(&document);
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,
..
}
));
assert!(matches!(
ir.security_schemes["QueryKey"].kind,
NormalizedSecuritySchemeKind::ApiKey {
location: SecurityParameterLocation::Query,
..
}
));
assert!(matches!(
ir.security_schemes["CookieKey"].kind,
NormalizedSecuritySchemeKind::Unsupported { .. }
));
assert_eq!(
operation(&ir, "/private")
.security_requirements
.alternatives
.len(),
3
);
}
#[test]
fn effective_requirements_inherit_override_and_allow_explicit_no_auth() {
let document = json!({
"openapi": "3.0.3",
"info": { "title": "Requirements", "version": "1" },
"components": { "securitySchemes": {
"Key": { "type": "apiKey", "in": "header", "name": "X-Key" },
"Bearer": { "type": "http", "scheme": "bearer" }
}},
"security": [{ "Key": [] }],
"paths": {
"/inherited": { "get": { "responses": { "200": { "description": "ok" } } } },
"/override": { "get": { "security": [{ "Bearer": [] }], "responses": { "200": { "description": "ok" } } } },
"/public": { "get": { "security": [], "responses": { "200": { "description": "ok" } } } },
"/unsecured": { "get": { "responses": { "200": { "description": "ok" } } } }
}
});
let ir = normalize(&document);
let inherited = &operation(&ir, "/inherited").security_requirements;
assert_eq!(inherited.source, SecurityRequirementsSource::Document);
assert_eq!(inherited.alternatives[0].schemes, ["Key"]);
let overridden = &operation(&ir, "/override").security_requirements;
assert_eq!(overridden.source, SecurityRequirementsSource::Operation);
assert_eq!(overridden.alternatives[0].schemes, ["Bearer"]);
let public = &operation(&ir, "/public").security_requirements;
assert_eq!(public.source, SecurityRequirementsSource::Operation);
assert!(public.alternatives.is_empty());
assert_eq!(
operation(&ir, "/unsecured").security_requirements.source,
SecurityRequirementsSource::Document
);
}
#[test]
fn or_alternatives_are_preserved_and_unsupported_and_is_scoped() {
let document = json!({
"openapi": "3.1.0",
"info": { "title": "Alternatives", "version": "1" },
"components": { "securitySchemes": {
"Bearer": { "type": "http", "scheme": "bearer" },
"One": { "type": "apiKey", "in": "header", "name": "X-One" },
"Two": { "type": "apiKey", "in": "query", "name": "two" }
}},
"paths": {
"/mixed": { "get": { "security": [
{ "One": [], "Two": [] }, { "Bearer": [] }
], "responses": { "200": { "description": "ok" } } } },
"/and-only": { "get": { "security": [
{ "One": [], "Two": [] }
], "responses": { "200": { "description": "ok" } } } },
"/or": { "get": { "security": [
{ "Bearer": [] }, { "One": [] }, { "Two": [] }
], "responses": { "200": { "description": "ok" } } } }
}
});
let ir = normalize(&document);
let preview = preview_from_ir(&ir);
let candidates = preview
.groups
.iter()
.flat_map(|group| &group.operations)
.cloned()
.collect::<Vec<_>>();
let mixed = candidate(&candidates, "GET /mixed");
assert_eq!(mixed.security_requirements.alternatives.len(), 2);
assert!(!mixed.security_requirements.alternatives[0].supported);
assert!(
mixed.security_requirements.alternatives[0]
.findings
.contains(&"unsupported_security_and_requirement".to_owned())
);
assert_eq!(
mixed.security_requirements.alternatives[0].schemes,
["One", "Two"]
);
assert!(mixed.security_requirements.alternatives[1].supported);
assert_eq!(
mixed.security_requirements.alternatives[1].schemes,
["Bearer"]
);
assert!(
mixed
.findings
.iter()
.all(|finding| finding.severity != ImportFindingSeverity::Error)
);
let and_only = candidate(&candidates, "GET /and-only");
assert!(and_only.findings.iter().any(|finding| {
finding.code == "unsupported_security_requirements"
&& finding.severity == ImportFindingSeverity::Error
}));
assert!(and_only.findings.iter().any(|finding| {
finding.code == "unsupported_security_and_requirement"
&& finding.severity == ImportFindingSeverity::Warning
&& finding.message.contains("One, Two")
}));
let or = candidate(&candidates, "GET /or");
assert_eq!(or.security_requirements.alternatives.len(), 3);
assert!(
or.security_requirements
.alternatives
.iter()
.all(|alternative| alternative.supported)
);
}
#[test]
fn unsupported_schemes_produce_manual_configuration_findings_without_typed_credentials() {
let document = json!({
"openapi": "3.0.3",
"info": { "title": "Unsupported", "version": "1" },
"components": { "securitySchemes": {
"OAuth": { "type": "oauth2", "flows": { "clientCredentials": {
"tokenUrl": "https://issuer.example/token?token=embedded",
"scopes": { "read": "read" },
"x-client-secret": "never-copy-this"
}}, "x-example-token": "also-never-copy" },
"Oidc": { "type": "openIdConnect", "openIdConnectUrl": "https://issuer.example" },
"Mutual": { "type": "mutualTLS" },
"Unknown": { "type": "vendorAuth", "x-api-key": "vendor-secret" }
}},
"paths": { "/private": { "get": {
"security": [{ "OAuth": ["read"] }, { "Oidc": [] }, { "Mutual": [] }, { "Unknown": [] }],
"responses": { "200": { "description": "ok" } }
}}}
});
let ir = normalize(&document);
let findings = &operation(&ir, "/private").findings;
assert!(
findings
.iter()
.any(|finding| finding.code == "unsupported_security_scheme")
);
assert!(
findings
.iter()
.any(|finding| finding.code == "unsupported_security_requirements")
);
assert!(
operation(&ir, "/private")
.security_requirements
.alternatives
.iter()
.all(|alternative| !alternative.supported)
);
let typed = serde_json::to_string(&ir.security_schemes).unwrap();
for secret_field in [
"flows",
"tokenUrl",
"x-client-secret",
"x-example-token",
"x-api-key",
] {
assert!(
!typed.contains(secret_field),
"typed metadata retained {secret_field}"
);
}
assert!(!typed.contains("never-copy-this"));
assert!(!typed.contains("vendor-secret"));
}
#[test]
fn normalized_ir_accepts_historical_v4_contract_without_security_fields() {
let document = json!({
"openapi": "3.0.3",
"info": { "title": "Historical", "version": "1" },
"paths": { "/health": { "get": {
"responses": { "200": { "description": "ok" } }
}}}
});
let mut ir = normalize(&document);
ir.normalizer_version = crank_import::rest::HISTORICAL_NORMALIZER_VERSION.to_owned();
ir.projection_version = crank_import::rest::HISTORICAL_PROJECTION_VERSION.to_owned();
ir.security_schemes.clear();
ir.operations[0].security_schemes.clear();
ir.operations[0].security_requirements = Default::default();
validate_normalized_ir(&ir).expect("historical v4 shape remains valid");
let serialized = serde_json::to_value(&ir).unwrap();
let operation = &serialized["operations"][0];
assert!(operation.get("security_requirements").is_none());
assert!(operation.get("security_schemes").is_none());
}
#[test]
fn non_array_security_is_rejected_as_an_import_error_surface() {
let document = json!({
"openapi": "3.0.3",
"info": { "title": "Malformed", "version": "1" },
"security": "Bearer",
"paths": { "/private": { "get": {
"responses": { "200": { "description": "ok" } }
}}}
});
let ir = normalize(&document);
assert!(operation(&ir, "/private").findings.iter().any(|finding| {
finding.code == "invalid_security_requirements"
&& finding.severity == ImportFindingSeverity::Error
&& finding.location.pointer == "/security"
}));
let candidates = candidates(&ir);
assert!(
candidate(&candidates, "GET /private")
.findings
.iter()
.any(|finding| {
finding.code == "invalid_security_requirements"
&& finding.severity == ImportFindingSeverity::Error
})
);
}
#[test]
fn secret_like_literals_are_redacted_from_ir_preview_and_source_snapshot() {
let document = json!({
"openapi": "3.0.3",
"info": { "title": "Redaction", "version": "1" },
"servers": [{ "url": "https://user:secret-canary@api.example.test" }],
"paths": { "/private": { "get": {
"parameters": [{
"name": "Authorization",
"in": "header",
"example": "Bearer header-canary"
}, {
"name": "X-Api-Key",
"in": "header",
"example": "opaque-canary-42",
"schema": { "type": "string" }
}, {
"name": "X-Trace",
"in": "header",
"example": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJjYW5hcnktNDIifQ.c2lnbmF0dXJlMTIzNDU2",
"schema": { "type": "string" }
}],
"requestBody": { "content": { "application/json": { "schema": {
"type": "object",
"properties": {
"password": { "type": "string", "default": "default-canary" },
"token": { "type": "integer", "default": 4242 },
"passwd": { "type": "boolean", "default": true },
"ordinaryDefault": { "type": "string", "default": "Bearer default-literal-canary" },
"ordinary": { "type": "string", "example": "token-example-canary" }
}
}}}},
"parameters": [{
"name": "X-Api-Key", "in": "header",
"schema": { "type": "string", "default": "opaque-header-default-canary" }
}, {
"name": "api_key", "in": "query",
"schema": { "type": "string", "default": "opaque-query-default-canary" }
}, {
"name": "session-token", "in": "cookie",
"schema": { "type": "string", "default": "opaque-cookie-default-canary" }
}],
"responses": { "200": { "description": "ok" } },
"x-api-key": "extension-canary",
"x-ciphertext": "opaque-ciphertext-canary",
"x-private-key": "private-key-canary"
}}}
});
let ir = normalize(&document);
let serialized_ir = serde_json::to_string(&ir).unwrap();
let serialized_preview = serde_json::to_string(&preview_from_ir(&ir)).unwrap();
for output in [&serialized_ir, &serialized_preview] {
for secret in [
"secret-canary",
"header-canary",
"opaque-canary-42",
"default-canary",
"default-literal-canary",
"opaque-header-default-canary",
"opaque-query-default-canary",
"opaque-cookie-default-canary",
"token-example-canary",
"extension-canary",
"opaque-ciphertext-canary",
"private-key-canary",
"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJjYW5hcnktNDIifQ.c2lnbmF0dXJlMTIzNDU2",
"4242",
] {
assert!(
!output.contains(secret),
"output retained {secret}: {output}"
);
}
}
assert!(!serialized_ir.contains("\"default\":true"));
assert!(serialized_ir.contains("[REDACTED]"));
assert!(
ir.findings
.iter()
.any(|finding| finding.code == "secret_like_example")
);
}
#[test]
fn encoded_sensitive_url_query_names_are_detected_and_sanitized() {
let document = json!({
"openapi": "3.0.3",
"info": { "title": "Encoded URL credentials", "version": "1" },
"servers": [{ "url": "https://api.example.test/?%61pi%5Fkey=encoded-query-canary&region=west" }],
"paths": { "/health": { "get": {
"responses": { "200": { "description": "ok" } }
}}}
});
let source = serde_json::to_string(&document).unwrap();
assert!(
crank_import::rest::validate_document_source_safe(&source, &NormalizationConfig::default())
.is_err()
);
let ir = normalize(&document);
let serialized = serde_json::to_string(&ir).unwrap();
assert!(!serialized.contains("encoded-query-canary"));
assert!(serialized.contains("%61pi%5Fkey=[REDACTED]"));
assert!(serialized.contains("region=west"));
}
#[test]
fn declared_api_key_names_seed_parameter_and_url_redaction_context() {
let document = json!({
"openapi": "3.0.3",
"info": { "title": "Declared API keys", "version": "1" },
"servers": [{ "url": "https://api.example.test/?key=query-canary&region=west" }],
"components": { "securitySchemes": {
"ClientKey": { "type": "apiKey", "in": "header", "name": "X-Client" },
"QueryKey": { "type": "apiKey", "in": "query", "name": "key" },
"CookieKey": { "type": "apiKey", "in": "cookie", "name": "session" }
}},
"paths": { "/public": {
"get": {
"parameters": [
{ "name": "X-Client", "in": "header", "schema": { "type": "string", "default": "header-canary" }, "example": "header-example-canary" },
{ "name": "session", "in": "cookie", "schema": { "type": "string", "default": "cookie-canary" } }
],
"responses": { "200": { "description": "ok" } }
}
}}
});
let source = serde_json::to_string(&document).unwrap();
assert!(
crank_import::rest::validate_document_source_safe(&source, &NormalizationConfig::default())
.is_err()
);
let ir = normalize(&document);
let serialized = serde_json::to_string(&ir).unwrap();
for canary in [
"query-canary",
"header-canary",
"header-example-canary",
"cookie-canary",
] {
assert!(!serialized.contains(canary), "{canary} leaked into IR");
}
assert!(serialized.contains("key=[REDACTED]"));
assert!(serialized.contains("region=west"));
let mixed_containers = json!({
"openapi": "3.0.3",
"info": { "title": "Legacy security map", "version": "1" },
"components": { "securitySchemes": {} },
"securityDefinitions": {
"QueryKey": { "type": "apiKey", "in": "query", "name": "key" }
},
"servers": [{ "url": "https://api.example.test/?key=legacy-container-canary" }],
"paths": { "/public": { "get": {
"responses": { "200": { "description": "ok" } }
}}}
});
let source = serde_json::to_string(&mixed_containers).unwrap();
assert!(
crank_import::rest::validate_document_source_safe(&source, &NormalizationConfig::default())
.is_err()
);
let ir = normalize(&mixed_containers);
let serialized = serde_json::to_string(&ir).unwrap();
assert!(!serialized.contains("legacy-container-canary"));
assert!(serialized.contains("key=[REDACTED]"));
}
#[test]
fn credential_like_security_format_hints_are_redacted_but_jwt_is_safe() {
let document = json!({
"openapi": "3.0.3",
"info": { "title": "Format hints", "version": "1" },
"components": { "securitySchemes": {
"Bearer": { "type": "http", "scheme": "bearer", "bearerFormat": "sk-private-value" },
"HeaderKey": { "type": "apiKey", "in": "header", "name": "X-Api-Key", "x-format-hint": "token-format-canary" },
"SafeBearer": { "type": "http", "scheme": "bearer", "bearerFormat": "JWT" }
}, "headers": {
"X-Api-Key": { "schema": { "type": "string", "default": "opaque-component-header-canary" } }
}},
"paths": { "/health": { "get": {
"responses": { "200": { "description": "ok" } }
}}}
});
let source = serde_json::to_string(&document).unwrap();
assert!(
crank_import::rest::validate_document_source_safe(&source, &NormalizationConfig::default())
.is_err()
);
let ir = normalize(&document);
let serialized = serde_json::to_string(&ir).unwrap();
assert!(!serialized.contains("sk-private-value"));
assert!(!serialized.contains("token-format-canary"));
assert!(!serialized.contains("opaque-component-header-canary"));
assert!(serialized.contains("X-Api-Key"));
let source_tree = serde_json::to_value(&ir.source_tree).unwrap();
let schema = &source_tree["value"]["value"]["components"]["value"]["value"]["headers"]["value"]
["value"]["X-Api-Key"]["value"]["value"]["schema"]["value"]["value"];
assert_eq!(schema["type"]["value"]["value"], "string");
assert_eq!(schema["default"]["value"]["value"], "[REDACTED]");
assert!(matches!(
ir.security_schemes["Bearer"].kind,
NormalizedSecuritySchemeKind::Http {
format_hint: None,
..
}
));
assert!(matches!(
ir.security_schemes["HeaderKey"].kind,
NormalizedSecuritySchemeKind::ApiKey {
format_hint: None,
..
}
));
assert!(matches!(ir.security_schemes["SafeBearer"].kind,
NormalizedSecuritySchemeKind::Http { ref format_hint, .. }
if format_hint.as_deref() == Some("JWT")));
}
#[test]
fn unused_unsupported_openapi_definitions_get_located_manual_warning_without_blocking_public() {
for version in ["3.0.3", "3.1.0"] {
let document = json!({
"openapi": version,
"info": { "title": "Unused OAuth definition", "version": "1" },
"components": { "securitySchemes": {
"OAuth": { "type": "oauth2", "flows": {} }
}},
"paths": { "/public": { "get": {
"responses": { "200": { "description": "ok" } }
}}}
});
let ir = normalize(&document);
let warning = ir
.findings
.iter()
.find(|finding| finding.code == "unsupported_security_scheme_definition")
.expect("unused unsupported definition needs a manual configuration warning");
assert_eq!(warning.severity, ImportFindingSeverity::Warning);
assert_eq!(
warning.location.pointer,
"/components/securitySchemes/OAuth"
);
assert!(warning.operation_key.is_none());
assert!(
candidate(&candidates(&ir), "GET /public")
.findings
.iter()
.all(|finding| finding.severity != ImportFindingSeverity::Error)
);
}
}
#[test]
fn unused_unsupported_swagger_definition_gets_located_manual_warning_without_blocking_public() {
let document = json!({
"swagger": "2.0",
"info": { "title": "Unused OAuth definition", "version": "1" },
"host": "security.example.test",
"schemes": ["https"],
"securityDefinitions": {
"OAuth": { "type": "oauth2", "flow": "application", "tokenUrl": "https://issuer.example/token", "scopes": {} }
},
"paths": { "/public": { "get": {
"responses": { "200": { "description": "ok" } }
}}}
});
let ir = normalize(&document);
let warning = ir
.findings
.iter()
.find(|finding| finding.code == "unsupported_security_scheme_definition")
.expect("unused unsupported definition needs a manual configuration warning");
assert_eq!(warning.severity, ImportFindingSeverity::Warning);
assert_eq!(warning.location.pointer, "/securityDefinitions/OAuth");
assert!(warning.operation_key.is_none());
assert!(
candidate(&candidates(&ir), "GET /public")
.findings
.iter()
.all(|finding| finding.severity != ImportFindingSeverity::Error)
);
}
#[test]
fn url_credentials_are_redacted_without_discarding_safe_oauth_endpoints() {
let document = json!({
"openapi": "3.0.3",
"info": { "title": "URL redaction", "version": "1" },
"components": { "securitySchemes": {
"OAuth": { "type": "oauth2", "flows": { "clientCredentials": {
"tokenUrl": "https://issuer.example/token",
"authorizationUrl": "https://issuer.example/authorize?client_id=public-client"
}} }
}},
"servers": [
{ "url": "https://bare-canary@api.example.test/v1?api_key=query-canary&region=west" },
{ "url": "//relative-userinfo-canary@api.example.test/v1" }
],
"paths": { "/health": { "get": {
"responses": { "200": { "description": "ok" } }
}}}
});
let source = serde_json::to_string(&document).unwrap();
assert!(
crank_import::rest::validate_document_source_safe(&source, &NormalizationConfig::default())
.is_err()
);
let ir = normalize(&document);
let serialized = serde_json::to_string(&ir).unwrap();
assert!(!serialized.contains("bare-canary"));
assert!(!serialized.contains("relative-userinfo-canary"));
assert!(!serialized.contains("query-canary"));
assert!(serialized.contains("api_key=[REDACTED]"));
assert!(serialized.contains("https://issuer.example/token"));
assert!(serialized.contains("https://issuer.example/authorize?client_id=public-client"));
}
#[test]
fn sanitized_userinfo_examples_and_declared_query_urls_validate_after_redaction() {
let document = json!({
"openapi": "3.0.3",
"info": {
"title": "Sanitized URL contexts",
"version": "1",
"description": "Docs: https://api.example.test/?key=description-query-canary"
},
"components": { "securitySchemes": {
"QueryKey": { "type": "apiKey", "in": "query", "name": "key" }
}},
"paths": { "/health": { "get": {
"requestBody": { "content": { "application/json": { "schema": {
"type": "string",
"example": "https://example-user:example-password@api.example.test/path"
}}}},
"responses": { "200": { "description": "ok" }
}}}}
});
let source = serde_json::to_string(&document).unwrap();
assert!(
crank_import::rest::validate_document_source_safe(&source, &NormalizationConfig::default())
.is_err()
);
let ir = normalize(&document);
let serialized = serde_json::to_string(&ir).unwrap();
assert!(!serialized.contains("description-query-canary"));
assert!(!serialized.contains("example-user"));
assert!(!serialized.contains("example-password"));
assert!(serialized.contains("key=[REDACTED]"));
assert!(serialized.contains("https://api.example.test/path"));
}
#[test]
fn credential_named_url_defaults_and_url_fragments_are_redacted() {
let document = json!({
"openapi": "3.0.3",
"info": { "title": "Credential URLs", "version": "1" },
"components": { "schemas": {
"Config": { "type": "object", "properties": {
"credentialUrl": { "type": "string", "default": "opaque-credential-url-canary" },
"x-credential-url": "opaque-extension-url-canary",
"callback": { "type": "string", "default": "https://issuer.example/callback#access_token=fragment-canary&state=safe" },
"reference": { "type": "string", "default": "https://issuer.example/#/components/securitySchemes/AccessToken" }
}}
}},
"paths": { "/health": { "get": {
"responses": { "200": { "description": "ok" } }
}}}
});
let source = serde_json::to_string(&document).unwrap();
assert!(
crank_import::rest::validate_document_source_safe(&source, &NormalizationConfig::default())
.is_err(),
"credentialUrl and URL fragment credentials must fail source preflight"
);
let serialized = serde_json::to_string(&normalize(&document)).unwrap();
assert!(!serialized.contains("opaque-credential-url-canary"));
assert!(!serialized.contains("opaque-extension-url-canary"));
assert!(!serialized.contains("fragment-canary"));
assert!(serialized.contains("[REDACTED]"));
assert!(serialized.contains("#access_token=[REDACTED]&state=safe"));
let safe_pointer = json!({
"openapi": "3.0.3",
"info": { "title": "JSON pointer", "version": "1" },
"paths": { "/health": { "get": {
"description": "#/components/securitySchemes/AccessToken",
"responses": { "200": { "description": "ok" } }
}}}
});
crank_import::rest::validate_document_source_safe(
&serde_json::to_string(&safe_pointer).unwrap(),
&NormalizationConfig::default(),
)
.expect("JSON-pointer fragments are references, not credential parameters");
}
#[test]
fn sensitive_identifiers_preserve_schemes_requirements_and_schema_metadata() {
let document = json!({
"openapi": "3.0.3",
"info": { "title": "Safe identifiers", "version": "1" },
"components": {
"securitySchemes": {
"AccessToken": { "type": "http", "scheme": "bearer" }
},
"schemas": { "Password": { "type": "string" } }
},
"security": [{ "AccessToken": [] }],
"paths": { "/login": { "post": {
"requestBody": { "content": { "application/json": { "schema": {
"type": "object", "properties": {
"password": { "type": "string", "description": "Password input" }
}
}}}},
"responses": { "200": { "description": "ok" } }
}}}
});
let source = serde_json::to_string(&document).unwrap();
crank_import::rest::validate_document_source_safe(&source, &NormalizationConfig::default())
.expect("names and schema declarations contain no literal credentials");
let ir = normalize(&document);
assert!(ir.security_schemes.contains_key("AccessToken"));
assert!(operation(&ir, "/login").security_requirements.alternatives[0].supported);
let schema = operation(&ir, "/login")
.request_body_schema
.as_ref()
.unwrap();
let crank_import::rest::NormalizedSchemaKind::Object { properties, .. } = &schema.kind else {
panic!("request object schema must survive redaction");
};
assert_eq!(
properties["password"].description.as_deref(),
Some("Password input")
);
assert!(matches!(
properties["password"].kind,
crank_import::rest::NormalizedSchemaKind::Scalar { .. }
));
}
+98 -87
View File
@@ -4,7 +4,7 @@
//! - an OR array with an empty requirement object `{}` exposes the public
//! alternative and must keep the affected operation actionable, without
//! touching other operations;
//! - a single non-empty requirement must remain a blocker (regression anchor);
//! - supported non-empty requirements remain resolvable for profile binding;
//! - malformed security shapes (non-array value, non-object array item) must
//! produce a source-located operation blocker instead of silently
//! disappearing.
@@ -50,19 +50,30 @@ fn candidate<'a>(
}
fn security_findings<'a>(
findings: &'a [NormalizedFinding],
ir: &'a crank_import::rest::NormalizedIr,
key: &str,
) -> Vec<&'a NormalizedFinding> {
findings
.iter()
all_findings(ir)
.into_iter()
.filter(|finding| {
finding.code == "unsupported_security_requirement"
finding.code == "invalid_security_requirements"
&& finding.severity == ImportFindingSeverity::Error
&& finding.operation_key.as_deref() == Some(key)
})
.collect()
}
fn all_findings(ir: &crank_import::rest::NormalizedIr) -> Vec<&NormalizedFinding> {
ir.findings
.iter()
.chain(
ir.operations
.iter()
.flat_map(|operation| &operation.findings),
)
.collect()
}
#[test]
fn empty_or_alternative_makes_the_operation_public() {
// Document-level OR array: [{"probe": []}, {}] offers an explicit public
@@ -91,7 +102,7 @@ fn empty_or_alternative_makes_the_operation_public() {
public.findings
);
assert!(
security_findings(&ir.findings, "GET /public").is_empty(),
security_findings(&ir, "GET /public").is_empty(),
"no security blocker may belong to the public operation: {:?}",
ir.findings
);
@@ -129,33 +140,28 @@ fn or_alternative_keeps_only_that_operation_public() {
);
let closed = candidate(&preview, "GET /closed");
assert!(
closed.findings.iter().any(|finding| {
finding.code == "unsupported_security_requirement"
&& finding.severity == ImportFindingSeverity::Error
}),
"non-empty requirement must still block the candidate: {:?}",
closed
.findings
.iter()
.all(|finding| finding.severity != ImportFindingSeverity::Error),
"well-formed supported requirement must remain resolvable: {:?}",
closed.findings
);
let ir_blocker = security_findings(&ir.findings, "GET /closed")[0];
assert!(security_findings(&ir, "GET /closed").is_empty());
assert!(closed.security_requirements.alternatives[0].supported);
assert_eq!(
ir_blocker.location.pointer, "/paths/~1closed/get/security/0",
"blocker must point at the local requirement: {:?}",
ir_blocker
closed.security_requirements.alternatives[0].schemes,
["probe"]
);
assert!(
security_findings(&ir.findings, "GET /closed").len() == 1,
"exactly one blocker for the closed operation: {:?}",
ir.findings
);
assert!(
security_findings(&ir.findings, "GET /open").is_empty(),
security_findings(&ir, "GET /open").is_empty(),
"the public alternative must not leak into the open operation: {:?}",
ir.findings
);
}
#[test]
fn nonempty_requirement_still_blocks_with_auth_profile_contract() {
fn well_formed_requirement_stays_resolvable_for_auth_profile_binding() {
let source = json!({
"openapi": "3.0.3",
"info": { "title": "Security scope regression", "version": "1" },
@@ -170,25 +176,18 @@ fn nonempty_requirement_still_blocks_with_auth_profile_contract() {
}
});
let (ir, preview) = run(&source);
let blocker = security_findings(&ir.findings, "GET /secured")
.into_iter()
.next()
.cloned()
.unwrap_or_else(|| panic!("non-empty requirement must block: {:?}", ir.findings));
assert_eq!(blocker.location.pointer, "/security/0");
assert_eq!(
blocker.message,
"Требование безопасности должно быть привязано к настроенному Auth Profile перед публикацией этой операции; остальные операции не блокируются.",
"Auth Profile contract message must be stable"
);
assert!(security_findings(&ir, "GET /secured").is_empty());
let secured = candidate(&preview, "GET /secured");
assert!(
secured.findings.iter().any(|finding| {
finding.code == "unsupported_security_requirement"
&& finding.severity == ImportFindingSeverity::Error
}),
"blocked candidate must expose the blocker: {:?}",
secured.findings
secured
.findings
.iter()
.all(|finding| finding.severity != ImportFindingSeverity::Error)
);
assert!(secured.security_requirements.alternatives[0].supported);
assert_eq!(
secured.security_requirements.source,
crank_import::rest::SecurityRequirementsSource::Document
);
}
@@ -209,7 +208,7 @@ fn malformed_security_shapes_block_the_affected_operation() {
});
let (ir, preview) = run(&source);
for key in ["GET /one", "GET /two"] {
let blocker = security_findings(&ir.findings, key)
let blocker = security_findings(&ir, key)
.into_iter()
.next()
.cloned()
@@ -221,14 +220,15 @@ fn malformed_security_shapes_block_the_affected_operation() {
);
assert!(
candidate(&preview, key).findings.iter().any(|finding| {
finding.code == "unsupported_security_requirement"
finding.code == "invalid_security_requirements"
&& finding.severity == ImportFindingSeverity::Error
}),
"{key} candidate must be blocked"
);
}
// Non-object array item: the item pointer must be preserved.
// Non-object array item: the array is fail-closed and the item has a
// source-located warning.
let source = json!({
"openapi": "3.0.3",
"info": { "title": "Security scope regression", "version": "1" },
@@ -240,16 +240,21 @@ fn malformed_security_shapes_block_the_affected_operation() {
}
});
let (ir, _) = run(&source);
let blocker = security_findings(&ir.findings, "GET /one")
let blocker = security_findings(&ir, "GET /one")
.into_iter()
.next()
.cloned()
.unwrap_or_else(|| panic!("non-object security item must block: {:?}", ir.findings));
assert_eq!(
blocker.location.pointer, "/security/0",
"blocker must point at the malformed item: {:?}",
blocker.location.pointer, "/security",
"blocker must point at the malformed array: {:?}",
blocker
);
assert!(all_findings(&ir).iter().any(|finding| {
finding.code == "invalid_security_requirement"
&& finding.severity == ImportFindingSeverity::Warning
&& finding.location.pointer == "/security/0"
}));
// Malformed operation-level security must not affect the neighbour.
let source = json!({
@@ -264,7 +269,7 @@ fn malformed_security_shapes_block_the_affected_operation() {
}
});
let (ir, preview) = run(&source);
let blocker = security_findings(&ir.findings, "GET /bad")
let blocker = security_findings(&ir, "GET /bad")
.into_iter()
.next()
.cloned()
@@ -275,7 +280,7 @@ fn malformed_security_shapes_block_the_affected_operation() {
blocker
);
assert!(
security_findings(&ir.findings, "GET /fine").is_empty(),
security_findings(&ir, "GET /fine").is_empty(),
"the neighbour operation must not inherit a local defect: {:?}",
ir.findings
);
@@ -307,25 +312,29 @@ fn empty_alternative_needs_a_well_formed_array() {
}
});
let (ir, preview) = run(&source);
let at_item = |pointer: &str| {
ir.findings
.iter()
let at_pointer = |pointer: &str, code: &str| {
all_findings(&ir)
.into_iter()
.find(|finding| {
finding.code == "unsupported_security_requirement"
finding.code == code
&& finding.operation_key.as_deref() == Some("GET /mixed")
&& finding.location.pointer == pointer
})
.unwrap_or_else(|| panic!("blocker at {pointer} missing: {:?}", ir.findings))
.unwrap_or_else(|| panic!("{code} finding at {pointer} missing: {:?}", ir.findings))
};
let secured = at_item("/security/0");
assert_eq!(
secured.message,
"Требование безопасности должно быть привязано к настроенному Auth Profile перед публикацией этой операции; остальные операции не блокируются."
at_pointer("/security", "invalid_security_requirements").severity,
ImportFindingSeverity::Error
);
let malformed = at_item("/security/2");
assert_eq!(
malformed.message,
"security содержит альтернативу без объекта требований: формат не поддерживается, операция не публикуется."
at_pointer("/security/2", "invalid_security_requirement").severity,
ImportFindingSeverity::Warning
);
assert!(
candidate(&preview, "GET /mixed")
.security_requirements
.alternatives[0]
.supported
);
assert!(
candidate(&preview, "GET /mixed")
@@ -365,10 +374,10 @@ fn object_instead_of_security_array_has_scoped_coverage() {
} else {
"/security"
};
let blocker = security_findings(&ir.findings, "GET /bad");
let blocker = security_findings(&ir, "GET /bad");
assert_eq!(blocker.len(), 1, "{version} {local}: {:?}", ir.findings);
assert_eq!(blocker[0].location.pointer, expected);
assert!(security_findings(&ir.findings, "GET /public").is_empty());
assert!(security_findings(&ir, "GET /public").is_empty());
assert!(
candidate(&preview, "GET /public")
.findings
@@ -435,7 +444,7 @@ fn openapi_31_non_array_root_security_blocks_inherited_operations() {
);
let (ir, preview) = run(&Value::Object(fixture));
for key in ["GET /one", "GET /two"] {
let blockers = security_findings(&ir.findings, key);
let blockers = security_findings(&ir, key);
assert_eq!(
blockers.len(),
1,
@@ -444,7 +453,7 @@ fn openapi_31_non_array_root_security_blocks_inherited_operations() {
);
let blocker = &blockers[0];
assert_eq!(
blocker.code, "unsupported_security_requirement",
blocker.code, "invalid_security_requirements",
"stable finding code: {blocker:?}"
);
assert_eq!(
@@ -458,7 +467,7 @@ fn openapi_31_non_array_root_security_blocks_inherited_operations() {
);
assert!(
candidate(&preview, key).findings.iter().any(|finding| {
finding.code == "unsupported_security_requirement"
finding.code == "invalid_security_requirements"
&& finding.severity == ImportFindingSeverity::Error
}),
"{key} candidate must be blocked"
@@ -481,10 +490,10 @@ fn openapi_31_malformed_local_security_affects_only_that_operation() {
}),
);
let (ir, preview) = run(&Value::Object(fixture));
let blockers = security_findings(&ir.findings, "GET /bad");
let blockers = security_findings(&ir, "GET /bad");
assert_eq!(blockers.len(), 1, "exactly one blocker: {:?}", ir.findings);
assert_eq!(
blockers[0].code, "unsupported_security_requirement",
blockers[0].code, "invalid_security_requirements",
"stable finding code"
);
assert_eq!(
@@ -498,7 +507,7 @@ fn openapi_31_malformed_local_security_affects_only_that_operation() {
blockers[0]
);
assert!(
security_findings(&ir.findings, "GET /public").is_empty(),
security_findings(&ir, "GET /public").is_empty(),
"the public neighbour must not inherit a local defect: {:?}",
ir.findings
);
@@ -520,7 +529,7 @@ fn openapi_31_public_alternative_with_malformed_sibling_does_not_go_public() {
json!({ "/mixed": get200("mixedOp31", None) }),
);
let (ir, preview) = run(&Value::Object(fixture));
let blockers = security_findings(&ir.findings, "GET /mixed");
let blockers = security_findings(&ir, "GET /mixed");
assert_eq!(
blockers.len(),
1,
@@ -528,14 +537,15 @@ fn openapi_31_public_alternative_with_malformed_sibling_does_not_go_public() {
ir.findings
);
assert_eq!(
blockers[0].location.pointer, "/security/1",
"blocker must point at the non-object item: {:?}",
blockers[0].location.pointer, "/security",
"fail-closed blocker must point at the malformed array: {:?}",
blockers[0]
);
assert_eq!(
blockers[0].message,
"security содержит альтернативу без объекта требований: формат не поддерживается, операция не публикуется."
);
assert!(all_findings(&ir).iter().any(|finding| {
finding.code == "invalid_security_requirement"
&& finding.severity == ImportFindingSeverity::Warning
&& finding.location.pointer == "/security/1"
}));
assert!(
candidate(&preview, "GET /mixed")
.findings
@@ -558,7 +568,7 @@ fn swagger2_non_array_root_security_blocks_inherited_operations() {
);
let (ir, preview) = run(&Value::Object(fixture));
for key in ["GET /one", "GET /two"] {
let blockers = security_findings(&ir.findings, key);
let blockers = security_findings(&ir, key);
assert_eq!(
blockers.len(),
1,
@@ -567,7 +577,7 @@ fn swagger2_non_array_root_security_blocks_inherited_operations() {
);
let blocker = &blockers[0];
assert_eq!(
blocker.code, "unsupported_security_requirement",
blocker.code, "invalid_security_requirements",
"stable finding code: {blocker:?}"
);
assert_eq!(
@@ -581,7 +591,7 @@ fn swagger2_non_array_root_security_blocks_inherited_operations() {
);
assert!(
candidate(&preview, key).findings.iter().any(|finding| {
finding.code == "unsupported_security_requirement"
finding.code == "invalid_security_requirements"
&& finding.severity == ImportFindingSeverity::Error
}),
"{key} candidate must be blocked"
@@ -604,9 +614,9 @@ fn swagger2_malformed_local_security_affects_only_that_operation() {
}),
);
let (ir, preview) = run(&Value::Object(fixture));
let blockers = security_findings(&ir.findings, "GET /bad");
let blockers = security_findings(&ir, "GET /bad");
assert_eq!(blockers.len(), 1, "exactly one blocker: {:?}", ir.findings);
assert_eq!(blockers[0].code, "unsupported_security_requirement");
assert_eq!(blockers[0].code, "invalid_security_requirements");
assert_eq!(blockers[0].severity, ImportFindingSeverity::Error);
assert_eq!(
blockers[0].location.pointer, "/paths/~1bad/get/security",
@@ -614,7 +624,7 @@ fn swagger2_malformed_local_security_affects_only_that_operation() {
blockers[0]
);
assert!(
security_findings(&ir.findings, "GET /public").is_empty(),
security_findings(&ir, "GET /public").is_empty(),
"the public neighbour must not inherit a local defect: {:?}",
ir.findings
);
@@ -636,7 +646,7 @@ fn swagger2_public_alternative_with_malformed_sibling_does_not_go_public() {
json!({ "/mixed": get200("mixedOpS2", None) }),
);
let (ir, preview) = run(&Value::Object(fixture));
let blockers = security_findings(&ir.findings, "GET /mixed");
let blockers = security_findings(&ir, "GET /mixed");
assert_eq!(
blockers.len(),
1,
@@ -644,14 +654,15 @@ fn swagger2_public_alternative_with_malformed_sibling_does_not_go_public() {
ir.findings
);
assert_eq!(
blockers[0].location.pointer, "/security/1",
"blocker must point at the non-object item: {:?}",
blockers[0].location.pointer, "/security",
"fail-closed blocker must point at the malformed array: {:?}",
blockers[0]
);
assert_eq!(
blockers[0].message,
"security содержит альтернативу без объекта требований: формат не поддерживается, операция не публикуется."
);
assert!(all_findings(&ir).iter().any(|finding| {
finding.code == "invalid_security_requirement"
&& finding.severity == ImportFindingSeverity::Warning
&& finding.location.pointer == "/security/1"
}));
assert!(
candidate(&preview, "GET /mixed")
.findings
@@ -675,7 +686,7 @@ fn empty_security_array_stays_public() {
});
let (ir, preview) = run(&source);
assert!(
security_findings(&ir.findings, "GET /public").is_empty(),
security_findings(&ir, "GET /public").is_empty(),
"explicit empty override must stay public: {:?}",
ir.findings
);
+35 -35
View File
@@ -598,19 +598,19 @@ constructs:
expected_finding: "none"
- specification_version: "OpenAPI 3.0"
construct_id: "security.bearer"
status: unsupported
preserved_semantics: "The source security requirement is retained as a blocker until an administrator selects a compatible Auth Profile; credentials are never copied into the import preview."
expected_finding: "unsupported_security_requirement"
status: supported
preserved_semantics: "Bearer scheme metadata and OR alternatives are retained without credentials; the import API resolves an Auth Profile binding."
expected_finding: "none"
- specification_version: "OpenAPI 3.0"
construct_id: "security.basic"
status: unsupported
preserved_semantics: "The source security requirement is retained as a blocker until an administrator selects a compatible Auth Profile; credentials are never copied into the import preview."
expected_finding: "unsupported_security_requirement"
status: supported
preserved_semantics: "Basic scheme metadata and OR alternatives are retained without credentials; the import API resolves an Auth Profile binding."
expected_finding: "none"
- specification_version: "OpenAPI 3.0"
construct_id: "security.api_key"
status: unsupported
preserved_semantics: "The source security requirement is retained as a blocker until an administrator selects a compatible Auth Profile; credentials are never copied into the import preview."
expected_finding: "unsupported_security_requirement"
status: supported
preserved_semantics: "API key location/name and OR alternatives are retained without credentials; the import API resolves an Auth Profile binding."
expected_finding: "none"
- specification_version: "OpenAPI 3.0"
construct_id: "security.override_empty"
status: supported
@@ -618,9 +618,9 @@ constructs:
expected_finding: "none"
- specification_version: "OpenAPI 3.0"
construct_id: "security.mixed_operations"
status: unsupported
preserved_semantics: "Only the operation carrying an effective security requirement receives the source-located blocker; operations overriding it with an empty security array remain actionable."
expected_finding: "unsupported_security_requirement"
status: supported
preserved_semantics: "Effective security metadata is retained on the inherited operation; explicit empty overrides remain public and actionable."
expected_finding: "none"
- specification_version: "OpenAPI 3.0"
construct_id: "media_type.application_xml.request"
status: unsupported
@@ -1238,19 +1238,19 @@ constructs:
expected_finding: "none"
- specification_version: "OpenAPI 3.1"
construct_id: "security.bearer"
status: unsupported
preserved_semantics: "The source security requirement is retained as a blocker until an administrator selects a compatible Auth Profile; credentials are never copied into the import preview."
expected_finding: "unsupported_security_requirement"
status: supported
preserved_semantics: "Bearer scheme metadata and OR alternatives are retained without credentials; the import API resolves an Auth Profile binding."
expected_finding: "none"
- specification_version: "OpenAPI 3.1"
construct_id: "security.basic"
status: unsupported
preserved_semantics: "The source security requirement is retained as a blocker until an administrator selects a compatible Auth Profile; credentials are never copied into the import preview."
expected_finding: "unsupported_security_requirement"
status: supported
preserved_semantics: "Basic scheme metadata and OR alternatives are retained without credentials; the import API resolves an Auth Profile binding."
expected_finding: "none"
- specification_version: "OpenAPI 3.1"
construct_id: "security.api_key"
status: unsupported
preserved_semantics: "The source security requirement is retained as a blocker until an administrator selects a compatible Auth Profile; credentials are never copied into the import preview."
expected_finding: "unsupported_security_requirement"
status: supported
preserved_semantics: "API key location/name and OR alternatives are retained without credentials; the import API resolves an Auth Profile binding."
expected_finding: "none"
- specification_version: "OpenAPI 3.1"
construct_id: "security.override_empty"
status: supported
@@ -1258,9 +1258,9 @@ constructs:
expected_finding: "none"
- specification_version: "OpenAPI 3.1"
construct_id: "security.mixed_operations"
status: unsupported
preserved_semantics: "Only the operation carrying an effective security requirement receives the source-located blocker; operations overriding it with an empty security array remain actionable."
expected_finding: "unsupported_security_requirement"
status: supported
preserved_semantics: "Effective security metadata is retained on the inherited operation; explicit empty overrides remain public and actionable."
expected_finding: "none"
- specification_version: "OpenAPI 3.1"
construct_id: "media_type.application_xml.request"
status: unsupported
@@ -1879,18 +1879,18 @@ constructs:
- specification_version: "Swagger 2.0"
construct_id: "security.bearer"
status: unsupported
preserved_semantics: "The source security requirement is retained as a blocker until an administrator selects a compatible Auth Profile; credentials are never copied into the import preview."
expected_finding: "unsupported_security_requirement"
preserved_semantics: "Swagger OAuth2 semantics require manual setup; OAuth credentials are never copied into the import preview."
expected_finding: "unsupported_security_requirements"
- specification_version: "Swagger 2.0"
construct_id: "security.basic"
status: unsupported
preserved_semantics: "The source security requirement is retained as a blocker until an administrator selects a compatible Auth Profile; credentials are never copied into the import preview."
expected_finding: "unsupported_security_requirement"
status: supported
preserved_semantics: "Basic scheme metadata and OR alternatives are retained without credentials; the import API resolves an Auth Profile binding."
expected_finding: "none"
- specification_version: "Swagger 2.0"
construct_id: "security.api_key"
status: unsupported
preserved_semantics: "The source security requirement is retained as a blocker until an administrator selects a compatible Auth Profile; credentials are never copied into the import preview."
expected_finding: "unsupported_security_requirement"
status: supported
preserved_semantics: "API key location/name and OR alternatives are retained without credentials; the import API resolves an Auth Profile binding."
expected_finding: "none"
- specification_version: "Swagger 2.0"
construct_id: "security.override_empty"
status: supported
@@ -1898,9 +1898,9 @@ constructs:
expected_finding: "none"
- specification_version: "Swagger 2.0"
construct_id: "security.mixed_operations"
status: unsupported
preserved_semantics: "Only the operation carrying an effective security requirement receives the source-located blocker; operations overriding it with an empty security array remain actionable."
expected_finding: "unsupported_security_requirement"
status: supported
preserved_semantics: "Effective basic security metadata is retained on the inherited operation; explicit empty overrides remain public and actionable."
expected_finding: "none"
- specification_version: "Swagger 2.0"
construct_id: "media_type.application_xml.request"
status: unsupported
@@ -1,9 +1,10 @@
mod legacy_auth;
mod plan_apply;
use super::*;
use crate::{
ArtifactSourceId, CreateImportPlanRequest, ImportJobKind, ImportJobSourceEnvelope, ImportPlan,
ImportPlanId,
ArtifactSourceId, CreateImportPlanRequest, ImportJobKind, ImportJobSourceEnvelope,
ImportOperationDraft, ImportPlan, ImportPlanId,
};
use crank_artifacts::ArtifactRef;
use sha2::{Digest, Sha256};
@@ -577,6 +578,8 @@ async fn apply_import_job_transaction(
}
}
legacy_auth::verify_legacy_import_auth(tx, request.workspace_id, request.operations).await?;
let mut result = ImportJobApplyResult {
application_key: request.application_key.to_owned(),
skipped: request.pre_skipped.to_vec(),
@@ -0,0 +1,144 @@
use super::*;
/// Legacy Apply has no plan-time auth snapshot, but it still must not create
/// operations from a stale or cross-workspace profile reference. Lock and
/// validate every referenced profile and its secret rows before inserting
/// any operation; ImportPlan Apply performs the stricter snapshot comparison.
pub(super) async fn verify_legacy_import_auth(
tx: &mut Transaction<'_, Postgres>,
workspace_id: &WorkspaceId,
operations: &[ImportOperationDraft],
) -> Result<(), RegistryError> {
let mut profiles = std::collections::BTreeMap::<String, Vec<String>>::new();
let mut profile_snapshots = std::collections::BTreeMap::<String, (String, Value)>::new();
for draft in operations {
if let Some(profile_id) = draft.operation.execution_config.auth_profile_ref.as_ref() {
profiles.entry(profile_id.as_str().to_owned()).or_default();
}
}
if profiles.is_empty() {
return Ok(());
}
let unavailable = |id: &str| RegistryError::ImportPlanAuthUnavailable {
auth_profile_id: id.to_owned(),
};
let profile_ids: Vec<String> = profiles.keys().cloned().collect();
for profile_id in &profile_ids {
let row = sqlx::query(
"select id, name, kind, config_json, created_at, updated_at
from auth_profiles
where workspace_id = $1 and id = $2",
)
.bind(workspace_id.as_str())
.bind(profile_id)
.fetch_optional(&mut **tx)
.await?
.ok_or_else(|| unavailable(profile_id))?;
let profile_id_value = row.try_get::<String, _>("id")?;
let profile_kind = row.try_get::<String, _>("kind")?;
let config_json = row.try_get::<Value, _>("config_json")?;
let profile = build_auth_profile(
profile_id_value,
workspace_id.as_str().to_owned(),
row.try_get::<String, _>("name")?,
profile_kind.clone(),
config_json.clone(),
row.try_get::<OffsetDateTime, _>("created_at")?,
row.try_get::<OffsetDateTime, _>("updated_at")?,
)
.map_err(|_| unavailable(profile_id))?;
if profile.kind != profile.config.kind() {
return Err(unavailable(profile_id));
}
let mut secret_ids = profile
.config
.secret_ids()
.into_iter()
.map(|secret| secret.as_str().to_owned())
.collect::<Vec<_>>();
secret_ids.sort();
secret_ids.dedup();
profiles.insert(profile_id.clone(), secret_ids);
profile_snapshots.insert(row.try_get::<String, _>("id")?, (profile_kind, config_json));
}
let secret_ids: std::collections::BTreeSet<String> =
profiles.values().flatten().cloned().collect();
for secret_id in secret_ids {
let owner = profiles
.iter()
.find_map(|(profile_id, ids)| ids.contains(&secret_id).then_some(profile_id.as_str()))
.unwrap_or_default();
let row = sqlx::query(
"select status, current_version
from secrets
where workspace_id = $1 and id = $2
for update",
)
.bind(workspace_id.as_str())
.bind(&secret_id)
.fetch_optional(&mut **tx)
.await?
.ok_or_else(|| unavailable(owner))?;
let status: String = row.try_get("status")?;
let version: i32 = row.try_get("current_version")?;
let version_present = sqlx::query_scalar::<_, bool>(
"select exists(select 1 from secret_versions where secret_id = $1 and version = $2)",
)
.bind(&secret_id)
.bind(version)
.fetch_one(&mut **tx)
.await?;
if status != "active" || !version_present {
return Err(unavailable(owner));
}
}
// Keep the established secret-then-profile lock order. The profile may
// have changed while secret rows were locked; compare its live config and
// secret set with the initial read before Apply mutates any operation.
for profile_id in profile_ids {
let row = sqlx::query(
"select id, name, kind, config_json, created_at, updated_at
from auth_profiles
where workspace_id = $1 and id = $2
for update",
)
.bind(workspace_id.as_str())
.bind(&profile_id)
.fetch_optional(&mut **tx)
.await?
.ok_or_else(|| unavailable(&profile_id))?;
let kind: String = row.try_get("kind")?;
let config: Value = row.try_get("config_json")?;
let Some((expected_kind, expected_config)) = profile_snapshots.get(&profile_id) else {
return Err(unavailable(&profile_id));
};
if &kind != expected_kind || &config != expected_config {
return Err(unavailable(&profile_id));
}
let profile = build_auth_profile(
row.try_get::<String, _>("id")?,
workspace_id.as_str().to_owned(),
row.try_get::<String, _>("name")?,
kind,
config,
row.try_get::<OffsetDateTime, _>("created_at")?,
row.try_get::<OffsetDateTime, _>("updated_at")?,
)
.map_err(|_| unavailable(&profile_id))?;
let mut live_secret_ids = profile
.config
.secret_ids()
.into_iter()
.map(|secret| secret.as_str().to_owned())
.collect::<Vec<_>>();
live_secret_ids.sort();
live_secret_ids.dedup();
if profiles.get(&profile_id) != Some(&live_secret_ids) {
return Err(unavailable(&profile_id));
}
}
Ok(())
}
@@ -60,6 +60,18 @@ pub(super) struct StoredPlanCandidate {
/// ids/status/versions.
#[serde(default)]
pub(crate) auth_snapshot: Option<StoredAuthSnapshot>,
/// Source-derived selected scheme requirement. Apply checks the live
/// profile against this independently of the captured profile snapshot,
/// closing a profile-change race between compatibility lookup and capture.
#[serde(default)]
pub(crate) auth_requirement: Option<StoredAuthRequirement>,
}
#[derive(Debug, Deserialize, PartialEq, Eq)]
pub(super) struct StoredAuthRequirement {
pub(crate) kind: String,
#[serde(default)]
pub(crate) parameter_name: Option<String>,
}
/// Plan-time snapshot of one auth profile's redacted metadata.
@@ -391,6 +403,24 @@ pub(super) fn read_and_validate_plan_material(
return Err(corrupt());
}
}
match (&candidate.auth_requirement, &auth_ref, actionable) {
(Some(requirement), Some(_), true)
if requirement.kind == "unconstrained"
&& requirement.parameter_name.is_none()
&& decision.action == "new_version" => {}
(Some(requirement), Some(_), true)
if matches!(requirement.kind.as_str(), "bearer" | "basic")
&& requirement.parameter_name.is_none()
|| matches!(
requirement.kind.as_str(),
"api_key_header" | "api_key_query"
) && requirement
.parameter_name
.as_deref()
.is_some_and(|name| !name.is_empty() && name.len() <= 256) => {}
(None, None, _) | (None, Some(_), false) => {}
_ => return Err(corrupt()),
}
match decision.action.as_str() {
"create" => {
if target.is_some()
@@ -68,7 +68,7 @@ pub(super) async fn lock_and_verify_auth(
workspace_id: &WorkspaceId,
candidates: &[StoredPlanCandidate],
) -> Result<(), RegistryError> {
use material::StoredAuthSnapshot;
use material::{StoredAuthRequirement, StoredAuthSnapshot};
let unavailable = |auth_profile_id: &str| RegistryError::ImportPlanAuthUnavailable {
auth_profile_id: auth_profile_id.to_owned(),
@@ -79,6 +79,7 @@ pub(super) async fn lock_and_verify_auth(
// snapshot; a disagreement means the profile drifted during CreatePlan
// and the whole apply must be re-previewed before any mutation.
let mut snapshots: BTreeMap<String, &StoredAuthSnapshot> = BTreeMap::new();
let mut requirements: BTreeMap<String, Vec<&StoredAuthRequirement>> = BTreeMap::new();
{
use std::collections::btree_map::Entry;
for candidate in candidates {
@@ -95,6 +96,14 @@ pub(super) async fn lock_and_verify_auth(
.auth_snapshot
.as_ref()
.ok_or_else(|| unavailable(ref_id.as_str()))?;
let requirement = candidate
.auth_requirement
.as_ref()
.ok_or_else(|| unavailable(ref_id.as_str()))?;
requirements
.entry(ref_id.as_str().to_owned())
.or_default()
.push(requirement);
match snapshots.entry(ref_id.as_str().to_owned()) {
Entry::Vacant(vacant) => {
vacant.insert(snapshot);
@@ -132,6 +141,13 @@ pub(super) async fn lock_and_verify_auth(
if profile.kind != profile.config.kind() {
return Err(unavailable(profile_id));
}
if requirements.get(profile_id).is_none_or(|expected| {
expected
.iter()
.any(|requirement| !auth_config_satisfies_requirement(&profile.config, requirement))
}) {
return Err(unavailable(profile_id));
}
// Drift since the plan was confirmed (config, name, kind or
// updated_at) means the re-preview contract: typed conflict, no
// mutation.
@@ -263,3 +279,57 @@ pub(super) async fn lock_and_verify_auth(
}
Ok(())
}
fn auth_config_satisfies_requirement(
config: &crank_core::AuthConfig,
requirement: &material::StoredAuthRequirement,
) -> bool {
use crank_core::AuthConfig;
match (config, requirement.kind.as_str()) {
(_, "unconstrained") => requirement.parameter_name.is_none(),
(AuthConfig::Bearer(_), "bearer") | (AuthConfig::Basic(_), "basic") => {
requirement.parameter_name.is_none()
}
(AuthConfig::ApiKeyHeader(config), "api_key_header") => requirement
.parameter_name
.as_deref()
.is_some_and(|name| config.header_name.eq_ignore_ascii_case(name)),
(AuthConfig::ApiKeyQuery(config), "api_key_query") => requirement
.parameter_name
.as_deref()
.is_some_and(|name| config.param_name == name),
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::auth_config_satisfies_requirement;
use crate::postgres::import_job::plan_apply::material::StoredAuthRequirement;
use crank_core::{ApiKeyHeaderAuthConfig, AuthConfig, SecretId};
#[test]
fn source_selected_header_name_is_rechecked_against_live_profile_config() {
let source_requirement = StoredAuthRequirement {
kind: "api_key_header".to_owned(),
parameter_name: Some("X-A".to_owned()),
};
let compatible = AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
header_name: "x-a".to_owned(),
secret_id: SecretId::new("secret_a"),
});
let changed_after_resolution = AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
header_name: "X-B".to_owned(),
secret_id: SecretId::new("secret_a"),
});
assert!(auth_config_satisfies_requirement(
&compatible,
&source_requirement
));
assert!(!auth_config_satisfies_requirement(
&changed_after_resolution,
&source_requirement
));
}
}
@@ -5,8 +5,8 @@
use super::*;
use crank_core::{
ApiKeyHeaderAuthConfig, AuthConfig, AuthKind, AuthProfile, Secret, SecretId, SecretKind,
SecretStatus,
ApiKeyHeaderAuthConfig, ApiKeyQueryAuthConfig, AuthConfig, AuthKind, AuthProfile,
BasicAuthConfig, Secret, SecretId, SecretKind, SecretStatus,
};
use crank_registry::MASTER_KEY_CIPHER_CONTRACT;
use crank_registry::{
@@ -110,6 +110,7 @@ fn auth_plan_payload(
"name": operation.name,
"state": "actionable",
"decision": { "action": "create" },
"auth_requirement": { "kind": "api_key_header", "parameter_name": "X-Apply-Key" },
"operation": operation
});
if let Some(snapshot) = snapshot {
@@ -133,6 +134,136 @@ fn auth_plan_payload(
})
}
fn typed_auth_plan_payload(
plan_id: &str,
job_id: &str,
fingerprint: &Value,
auth_profile_id: &str,
requirement_kind: &str,
parameter_name: Option<&str>,
snapshot: Value,
) -> Value {
let mut operation = plan_operation("op_typed_auth");
operation.execution_config.auth_profile_ref = Some(auth_profile_id.into());
let mut requirement = json!({ "kind": requirement_kind });
if let Some(parameter_name) = parameter_name {
requirement["parameter_name"] = json!(parameter_name);
}
json!({
"schema_version": "import-plan-v1",
"plan_reference": plan_id,
"job_id": job_id,
"fingerprint": fingerprint,
"source": { "source_id": SOURCE_ID, "digest": source_ref() },
"dependencies": [],
"selection": {
"mode": "full", "all": ["typed"], "selected": ["typed"], "excluded": []
},
"counts": { "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 },
"candidates": [{
"key": "typed",
"name": operation.name,
"state": "actionable",
"decision": { "action": "create" },
"auth_requirement": requirement,
"operation": operation,
"auth_snapshot": snapshot
}]
})
}
async fn typed_auth_base(
database: &TestDatabase,
workspace_tag: &str,
profile_id: &str,
config: AuthConfig,
) -> (
PostgresRegistry,
WorkspaceId,
ImportJobId,
Value,
AuthProfile,
Value,
) {
let registry = database.registry().await;
registry
.verify_or_register_master_key_identity(MasterKeyIdentityCandidate {
epoch: 1,
fingerprint: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
cipher_contract: MASTER_KEY_CIPHER_CONTRACT,
observed_at: &ts(),
})
.await
.unwrap();
let now = OffsetDateTime::now_utc();
let ws = create_workspace(&registry, workspace_tag).await;
let job = create_pending_openapi_job(
&registry,
&ws,
&format!("job_typed_auth_{workspace_tag}"),
now,
now + Duration::hours(1),
)
.await;
activate_source(&database.raw_pool().await, &ws, now).await;
let mut secrets = Vec::new();
for (index, secret_id) in config.secret_ids().into_iter().enumerate() {
let secret = Secret {
id: secret_id.clone(),
workspace_id: ws.clone(),
name: format!("Typed auth secret {index}"),
kind: SecretKind::Token,
status: SecretStatus::Active,
current_version: 1,
created_at: ts(),
updated_at: ts(),
last_used_at: None,
};
registry
.create_secret(CreateSecretRequest {
secret: &secret,
ciphertext: "ciphertext",
key_version: "v1",
master_key_epoch: 1,
created_by: None,
})
.await
.unwrap();
secrets.push(secret);
}
let profile = AuthProfile {
id: profile_id.into(),
workspace_id: ws.clone(),
name: "Typed auth profile".to_owned(),
kind: config.kind(),
config,
created_at: ts(),
updated_at: ts(),
};
registry
.save_auth_profile(SaveAuthProfileRequest {
workspace_id: &ws,
profile: &profile,
})
.await
.unwrap();
let snapshot = json!({
"profile_id": profile.id.as_str(),
"name": profile.name,
"kind": profile.kind,
"config": profile.config,
"updated_at": profile.updated_at.format(&Rfc3339).unwrap(),
"secrets": secrets.iter().map(|secret| json!({
"id": secret.id.as_str(),
"status": secret.status,
"current_version": secret.current_version,
"updated_at": secret.updated_at.format(&Rfc3339).unwrap()
})).collect::<Vec<_>>()
});
(registry, ws, job, fingerprint(), profile, snapshot)
}
async fn auth_base(
database: &TestDatabase,
workspace_tag: &str,
@@ -268,6 +399,67 @@ async fn apply_rejects_auth_profile_config_drift() {
database.cleanup().await;
}
#[tokio::test]
async fn apply_rechecks_live_profile_against_source_requirement_even_when_snapshot_matches() {
let database = TestDatabase::new().await;
let (registry, raw_pool, ws, job, fp, _snapshot_a) =
auth_base(&database, "a_source_requirement").await;
// Reproduce the race: source compatibility was resolved while the
// profile used X-Apply-Key, then the profile changed before the later
// snapshot capture, so the stored snapshot itself accurately says X-B.
sqlx::query(
"update auth_profiles
set config_json = jsonb_set(config_json, '{api_key_header,header_name}', '\"X-B\"'),
updated_at = now()
where workspace_id = $1 and id = $2",
)
.bind(ws.as_str())
.bind("auth_apply")
.execute(&raw_pool)
.await
.unwrap();
let profile = capture_profile_fixture(&registry, &ws).await;
let secret = registry
.get_secret(&ws, &SecretId::new("sec_apply"))
.await
.unwrap()
.unwrap()
.secret;
let snapshot_b = capture_snapshot(&profile, &secret);
assert_eq!(snapshot_b["config"]["api_key_header"]["header_name"], "X-B");
// The source-derived requirement remains X-Apply-Key even though the
// plan-time snapshot now matches the live X-B profile exactly.
let payload = auth_plan_payload("plan_auth_source_req", job.as_str(), &fp, Some(snapshot_b));
let (plan, digest) =
store_plan(&registry, &ws, &job, "plan_auth_source_req", &fp, payload).await;
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
let result = registry
.apply_import_plan(&ApplyImportPlanRequest {
workspace_id: &ws,
plan_id: &plan,
plan_digest: &digest,
idempotency_key: "idem_auth_source_req",
verified_fingerprint: &fp,
applied_at: &applied_at,
})
.await;
assert!(matches!(
result,
Err(RegistryError::ImportPlanAuthUnavailable { auth_profile_id })
if auth_profile_id == "auth_apply"
));
assert!(
registry
.get_operation_summary(&ws, &OperationId::new("op_apply_auth"))
.await
.unwrap()
.is_none()
);
database.cleanup().await;
}
async fn capture_profile_fixture(registry: &PostgresRegistry, ws: &WorkspaceId) -> AuthProfile {
registry
.get_auth_profile(ws, &crank_core::AuthProfileId::new("auth_apply"))
@@ -421,3 +613,149 @@ async fn apply_rejects_auth_candidates_missing_or_mismatched_snapshot() {
);
database.cleanup().await;
}
#[tokio::test]
async fn apply_accepts_basic_auth_with_matching_snapshot_and_source_requirement() {
let database = TestDatabase::new().await;
let profile_id = "auth_basic_apply";
let (registry, ws, job, fp, _profile, snapshot) = typed_auth_base(
&database,
"a_basic_ok",
profile_id,
AuthConfig::Basic(BasicAuthConfig {
username_secret_id: SecretId::new("sec_basic_user"),
password_secret_id: SecretId::new("sec_basic_password"),
}),
)
.await;
let payload = typed_auth_plan_payload(
"plan_basic_ok",
job.as_str(),
&fp,
profile_id,
"basic",
None,
snapshot,
);
let (plan, digest) = store_plan(&registry, &ws, &job, "plan_basic_ok", &fp, payload).await;
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
let result = registry
.apply_import_plan(&ApplyImportPlanRequest {
workspace_id: &ws,
plan_id: &plan,
plan_digest: &digest,
idempotency_key: "idem_basic_ok",
verified_fingerprint: &fp,
applied_at: &applied_at,
})
.await
.unwrap();
assert_eq!(result.report.status, ImportPlanApplyStatus::Applied);
assert_eq!(result.report.counts.created, 1);
let summary = registry
.get_operation_summary(&ws, &OperationId::new("op_typed_auth"))
.await
.unwrap()
.unwrap();
assert_eq!(summary.current_draft_version, 1);
database.cleanup().await;
}
#[tokio::test]
async fn apply_accepts_query_key_with_matching_snapshot_and_source_requirement() {
let database = TestDatabase::new().await;
let profile_id = "auth_query_apply";
let (registry, ws, job, fp, _profile, snapshot) = typed_auth_base(
&database,
"a_query_ok",
profile_id,
AuthConfig::ApiKeyQuery(ApiKeyQueryAuthConfig {
param_name: "access_token".to_owned(),
secret_id: SecretId::new("sec_query_key"),
}),
)
.await;
let payload = typed_auth_plan_payload(
"plan_query_ok",
job.as_str(),
&fp,
profile_id,
"api_key_query",
Some("access_token"),
snapshot,
);
let (plan, digest) = store_plan(&registry, &ws, &job, "plan_query_ok", &fp, payload).await;
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
let result = registry
.apply_import_plan(&ApplyImportPlanRequest {
workspace_id: &ws,
plan_id: &plan,
plan_digest: &digest,
idempotency_key: "idem_query_ok",
verified_fingerprint: &fp,
applied_at: &applied_at,
})
.await
.unwrap();
assert_eq!(result.report.status, ImportPlanApplyStatus::Applied);
assert_eq!(result.report.counts.created, 1);
let summary = registry
.get_operation_summary(&ws, &OperationId::new("op_typed_auth"))
.await
.unwrap()
.unwrap();
assert_eq!(summary.current_draft_version, 1);
database.cleanup().await;
}
#[tokio::test]
async fn apply_rejects_query_key_source_mismatch_with_matching_live_snapshot() {
let database = TestDatabase::new().await;
let profile_id = "auth_query_mismatch";
let (registry, ws, job, fp, _profile, snapshot) = typed_auth_base(
&database,
"a_query_mismatch",
profile_id,
AuthConfig::ApiKeyQuery(ApiKeyQueryAuthConfig {
param_name: "access_token".to_owned(),
secret_id: SecretId::new("sec_query_mismatch"),
}),
)
.await;
let payload = typed_auth_plan_payload(
"plan_query_mismatch",
job.as_str(),
&fp,
profile_id,
"api_key_query",
Some("other_token"),
snapshot,
);
let (plan, digest) =
store_plan(&registry, &ws, &job, "plan_query_mismatch", &fp, payload).await;
let applied_at = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
let result = registry
.apply_import_plan(&ApplyImportPlanRequest {
workspace_id: &ws,
plan_id: &plan,
plan_digest: &digest,
idempotency_key: "idem_query_mismatch",
verified_fingerprint: &fp,
applied_at: &applied_at,
})
.await;
assert!(matches!(
result,
Err(RegistryError::ImportPlanAuthUnavailable { auth_profile_id })
if auth_profile_id == profile_id
));
assert!(
registry
.get_operation_summary(&ws, &OperationId::new("op_typed_auth"))
.await
.unwrap()
.is_none(),
"query source mismatch must fail before creating an operation"
);
database.cleanup().await;
}