Files
crank/crates/crank-import/tests/security_scope.rs
T

690 lines
25 KiB
Rust

//! Focused regressions for the effective security scope
//! (story 2.14 review findings):
//!
//! - 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);
//! - malformed security shapes (non-array value, non-object array item) must
//! produce a source-located operation blocker instead of silently
//! disappearing.
use crank_import::rest::{
ImportFindingSeverity, ImportOperationCandidate, NormalizationConfig, NormalizedFinding,
SourceDigest, normalize_verified_document, preview_from_ir,
};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
fn hex(bytes: impl AsRef<[u8]>) -> String {
Sha256::digest(bytes)
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
fn run(
source: &Value,
) -> (
crank_import::rest::NormalizedIr,
crank_import::rest::ImportPreview,
) {
let text = serde_json::to_string(source).unwrap();
let source_digest = SourceDigest::parse(hex(text.as_bytes())).expect("sha256 is valid");
let ir = normalize_verified_document(&text, source_digest, &NormalizationConfig::default())
.expect("security-scope fixture parses");
let preview = preview_from_ir(&ir);
(ir, preview)
}
fn candidate<'a>(
preview: &'a crank_import::rest::ImportPreview,
key: &str,
) -> &'a ImportOperationCandidate {
preview
.groups
.iter()
.flat_map(|group| &group.operations)
.find(|candidate| candidate.key == key)
.unwrap_or_else(|| panic!("{key} candidate missing in {preview:?}"))
}
fn security_findings<'a>(
findings: &'a [NormalizedFinding],
key: &str,
) -> Vec<&'a NormalizedFinding> {
findings
.iter()
.filter(|finding| {
finding.code == "unsupported_security_requirement"
&& finding.severity == ImportFindingSeverity::Error
&& finding.operation_key.as_deref() == Some(key)
})
.collect()
}
#[test]
fn empty_or_alternative_makes_the_operation_public() {
// Document-level OR array: [{"probe": []}, {}] offers an explicit public
// alternative, so the inherited operation must stay actionable.
let source = json!({
"openapi": "3.0.3",
"info": { "title": "Security scope regression", "version": "1" },
"servers": [{ "url": "https://security-scope.example.test" }],
"components": {
"securitySchemes": { "probe": { "type": "http", "scheme": "basic" } }
},
"security": [{ "probe": [] }, {}],
"paths": {
"/public": { "get": { "operationId": "publicInherit",
"responses": { "200": { "description": "ok" } } } }
}
});
let (ir, preview) = run(&source);
let public = candidate(&preview, "GET /public");
assert!(
public
.findings
.iter()
.all(|finding| finding.severity != ImportFindingSeverity::Error),
"empty OR alternative must keep the inherited operation public: {:?}",
public.findings
);
assert!(
security_findings(&ir.findings, "GET /public").is_empty(),
"no security blocker may belong to the public operation: {:?}",
ir.findings
);
assert!(
preview.findings.iter().all(|finding| {
!(finding.severity == ImportFindingSeverity::Error && finding.operation_key.is_none())
}),
"no document-global blocker may be produced: {preview:?}"
);
}
#[test]
fn or_alternative_keeps_only_that_operation_public() {
let source = json!({
"openapi": "3.0.3",
"info": { "title": "Security scope regression", "version": "1" },
"servers": [{ "url": "https://security-scope.example.test" }],
"components": {
"securitySchemes": { "probe": { "type": "http", "scheme": "basic" } }
},
"paths": {
"/open": { "get": { "security": [{ "probe": [] }, {}], "operationId": "openOp",
"responses": { "200": { "description": "ok" } } } },
"/closed": { "get": { "security": [{ "probe": [] }], "operationId": "closedOp",
"responses": { "200": { "description": "ok" } } } }
}
});
let (ir, preview) = run(&source);
let open = candidate(&preview, "GET /open");
assert!(
open.findings
.iter()
.all(|finding| { finding.severity != ImportFindingSeverity::Error }),
"operation with a public OR alternative must stay actionable: {:?}",
open.findings
);
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
);
let ir_blocker = security_findings(&ir.findings, "GET /closed")[0];
assert_eq!(
ir_blocker.location.pointer, "/paths/~1closed/get/security/0",
"blocker must point at the local requirement: {:?}",
ir_blocker
);
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(),
"the public alternative must not leak into the open operation: {:?}",
ir.findings
);
}
#[test]
fn nonempty_requirement_still_blocks_with_auth_profile_contract() {
let source = json!({
"openapi": "3.0.3",
"info": { "title": "Security scope regression", "version": "1" },
"servers": [{ "url": "https://security-scope.example.test" }],
"components": {
"securitySchemes": { "probe": { "type": "http", "scheme": "basic" } }
},
"security": [{ "probe": [] }],
"paths": {
"/secured": { "get": { "operationId": "securedOp",
"responses": { "200": { "description": "ok" } } } }
}
});
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"
);
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
);
}
#[test]
fn malformed_security_shapes_block_the_affected_operation() {
// Non-array security value: both inherited operations are affected.
let source = json!({
"openapi": "3.0.3",
"info": { "title": "Security scope regression", "version": "1" },
"servers": [{ "url": "https://security-scope.example.test" }],
"security": "basic",
"paths": {
"/one": { "get": { "operationId": "oneOp",
"responses": { "200": { "description": "ok" } } } },
"/two": { "get": { "operationId": "twoOp",
"responses": { "200": { "description": "ok" } } } }
}
});
let (ir, preview) = run(&source);
for key in ["GET /one", "GET /two"] {
let blocker = security_findings(&ir.findings, key)
.into_iter()
.next()
.cloned()
.unwrap_or_else(|| panic!("non-array security must block {key}: {:?}", ir.findings));
assert_eq!(
blocker.location.pointer, "/security",
"blocker must point at the malformed root security: {:?}",
blocker
);
assert!(
candidate(&preview, key).findings.iter().any(|finding| {
finding.code == "unsupported_security_requirement"
&& finding.severity == ImportFindingSeverity::Error
}),
"{key} candidate must be blocked"
);
}
// Non-object array item: the item pointer must be preserved.
let source = json!({
"openapi": "3.0.3",
"info": { "title": "Security scope regression", "version": "1" },
"servers": [{ "url": "https://security-scope.example.test" }],
"security": ["basic"],
"paths": {
"/one": { "get": { "operationId": "oneOp",
"responses": { "200": { "description": "ok" } } } }
}
});
let (ir, _) = run(&source);
let blocker = security_findings(&ir.findings, "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
);
// Malformed operation-level security must not affect the neighbour.
let source = json!({
"openapi": "3.0.3",
"info": { "title": "Security scope regression", "version": "1" },
"servers": [{ "url": "https://security-scope.example.test" }],
"paths": {
"/bad": { "get": { "security": "basic", "operationId": "badOp",
"responses": { "200": { "description": "ok" } } } },
"/fine": { "get": { "operationId": "fineOp",
"responses": { "200": { "description": "ok" } } } }
}
});
let (ir, preview) = run(&source);
let blocker = security_findings(&ir.findings, "GET /bad")
.into_iter()
.next()
.cloned()
.unwrap_or_else(|| panic!("malformed local security must block: {:?}", ir.findings));
assert_eq!(
blocker.location.pointer, "/paths/~1bad/get/security",
"blocker must point at the malformed local security: {:?}",
blocker
);
assert!(
security_findings(&ir.findings, "GET /fine").is_empty(),
"the neighbour operation must not inherit a local defect: {:?}",
ir.findings
);
assert!(
candidate(&preview, "GET /fine")
.findings
.iter()
.all(|finding| finding.severity != ImportFindingSeverity::Error),
"neighbour operation must stay actionable"
);
}
#[test]
fn empty_alternative_needs_a_well_formed_array() {
// A malformed item in the same array invalidates the public
// alternative: every alternative is reported, and the operation
// stays blocked instead of silently becoming public.
let source = json!({
"openapi": "3.0.3",
"info": { "title": "Security scope regression", "version": "1" },
"servers": [{ "url": "https://security-scope.example.test" }],
"components": {
"securitySchemes": { "probe": { "type": "http", "scheme": "basic" } }
},
"security": [{ "probe": [] }, {}, "basic"],
"paths": {
"/mixed": { "get": { "operationId": "mixedOp",
"responses": { "200": { "description": "ok" } } } }
}
});
let (ir, preview) = run(&source);
let at_item = |pointer: &str| {
ir.findings
.iter()
.find(|finding| {
finding.code == "unsupported_security_requirement"
&& finding.operation_key.as_deref() == Some("GET /mixed")
&& finding.location.pointer == pointer
})
.unwrap_or_else(|| panic!("blocker at {pointer} missing: {:?}", ir.findings))
};
let secured = at_item("/security/0");
assert_eq!(
secured.message,
"Требование безопасности должно быть привязано к настроенному Auth Profile перед публикацией этой операции; остальные операции не блокируются."
);
let malformed = at_item("/security/2");
assert_eq!(
malformed.message,
"security содержит альтернативу без объекта требований: формат не поддерживается, операция не публикуется."
);
assert!(
candidate(&preview, "GET /mixed")
.findings
.iter()
.any(|finding| finding.severity == ImportFindingSeverity::Error),
"the operation must not become public because of a malformed sibling: {preview:?}"
);
}
fn security_fixture_31() -> serde_json::Map<String, Value> {
security_fixture_openapi("3.1.0")
}
#[test]
fn object_instead_of_security_array_has_scoped_coverage() {
for version in ["3.0.3", "3.1.0", "2.0"] {
for local in [false, true] {
let mut fixture = if version == "2.0" {
security_fixture_swagger2()
} else {
security_fixture_openapi(version)
};
if !local {
fixture.insert("security".to_owned(), json!({}));
}
fixture.insert(
"paths".to_owned(),
json!({
"/bad": get200("badObject", local.then(|| json!({}))),
"/public": get200("publicObject", Some(json!([])))
}),
);
let (ir, preview) = run(&Value::Object(fixture));
let expected = if local {
"/paths/~1bad/get/security"
} else {
"/security"
};
let blocker = security_findings(&ir.findings, "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!(
candidate(&preview, "GET /public")
.findings
.iter()
.all(|finding| finding.severity != ImportFindingSeverity::Error)
);
crank_import::rest::validate_normalized_ir(&ir).unwrap();
}
}
}
fn security_fixture_openapi(version: &str) -> serde_json::Map<String, Value> {
let mut fixture = serde_json::Map::new();
fixture.insert("openapi".to_owned(), json!(version));
fixture.insert(
"info".to_owned(),
json!({ "title": "Security scope regression", "version": "1" }),
);
fixture.insert(
"servers".to_owned(),
json!([{ "url": "https://security-scope.example.test" }]),
);
fixture
}
fn security_fixture_swagger2() -> serde_json::Map<String, Value> {
let mut fixture = serde_json::Map::new();
fixture.insert("swagger".to_owned(), json!("2.0"));
fixture.insert(
"info".to_owned(),
json!({ "title": "Security scope regression" }),
);
fixture.insert("host".to_owned(), json!("security-scope.example.test"));
fixture.insert("schemes".to_owned(), json!(["https"]));
fixture
}
fn get200(operation_id: &str, security: Option<Value>) -> Value {
let mut get = serde_json::Map::from_iter([
("operationId".to_owned(), json!(operation_id)),
(
"responses".to_owned(),
json!({ "200": { "description": "ok" } }),
),
]);
if let Some(security) = security {
get.insert("security".to_owned(), security);
}
let mut path_item = serde_json::Map::new();
path_item.insert("get".to_owned(), Value::Object(get));
Value::Object(path_item)
}
#[test]
fn openapi_31_non_array_root_security_blocks_inherited_operations() {
let mut fixture = security_fixture_31();
fixture.insert("security".to_owned(), json!("basic"));
fixture.insert(
"paths".to_owned(),
json!({
"/one": get200("oneOp31", None),
"/two": get200("twoOp31", None)
}),
);
let (ir, preview) = run(&Value::Object(fixture));
for key in ["GET /one", "GET /two"] {
let blockers = security_findings(&ir.findings, key);
assert_eq!(
blockers.len(),
1,
"exactly one blocker for {key}: {:?}",
ir.findings
);
let blocker = &blockers[0];
assert_eq!(
blocker.code, "unsupported_security_requirement",
"stable finding code: {blocker:?}"
);
assert_eq!(
blocker.severity,
ImportFindingSeverity::Error,
"stable finding severity: {blocker:?}"
);
assert_eq!(
blocker.location.pointer, "/security",
"blocker must point at the malformed root security: {blocker:?}"
);
assert!(
candidate(&preview, key).findings.iter().any(|finding| {
finding.code == "unsupported_security_requirement"
&& finding.severity == ImportFindingSeverity::Error
}),
"{key} candidate must be blocked"
);
}
}
#[test]
fn openapi_31_malformed_local_security_affects_only_that_operation() {
let mut fixture = security_fixture_31();
// A well-formed root requirement proves priority: the malformed local
// security wins for /bad (no root blocker may be added), while /public
// relies on an explicit empty override to stay public.
fixture.insert("security".to_owned(), json!([{ "probe": [] }]));
fixture.insert(
"paths".to_owned(),
json!({
"/bad": get200("badOp31", Some(json!("basic"))),
"/public": get200("publicOp31", Some(json!([])))
}),
);
let (ir, preview) = run(&Value::Object(fixture));
let blockers = security_findings(&ir.findings, "GET /bad");
assert_eq!(blockers.len(), 1, "exactly one blocker: {:?}", ir.findings);
assert_eq!(
blockers[0].code, "unsupported_security_requirement",
"stable finding code"
);
assert_eq!(
blockers[0].severity,
ImportFindingSeverity::Error,
"stable finding severity"
);
assert_eq!(
blockers[0].location.pointer, "/paths/~1bad/get/security",
"blocker must point at the malformed local security: {:?}",
blockers[0]
);
assert!(
security_findings(&ir.findings, "GET /public").is_empty(),
"the public neighbour must not inherit a local defect: {:?}",
ir.findings
);
assert!(
candidate(&preview, "GET /public")
.findings
.iter()
.all(|finding| finding.severity != ImportFindingSeverity::Error),
"public neighbour must stay actionable: {preview:?}"
);
}
#[test]
fn openapi_31_public_alternative_with_malformed_sibling_does_not_go_public() {
let mut fixture = security_fixture_31();
fixture.insert("security".to_owned(), json!([{}, "basic"]));
fixture.insert(
"paths".to_owned(),
json!({ "/mixed": get200("mixedOp31", None) }),
);
let (ir, preview) = run(&Value::Object(fixture));
let blockers = security_findings(&ir.findings, "GET /mixed");
assert_eq!(
blockers.len(),
1,
"only the malformed sibling blocks: {:?}",
ir.findings
);
assert_eq!(
blockers[0].location.pointer, "/security/1",
"blocker must point at the non-object item: {:?}",
blockers[0]
);
assert_eq!(
blockers[0].message,
"security содержит альтернативу без объекта требований: формат не поддерживается, операция не публикуется."
);
assert!(
candidate(&preview, "GET /mixed")
.findings
.iter()
.any(|finding| finding.severity == ImportFindingSeverity::Error),
"the operation must not become public because of a malformed sibling: {preview:?}"
);
}
#[test]
fn swagger2_non_array_root_security_blocks_inherited_operations() {
let mut fixture = security_fixture_swagger2();
fixture.insert("security".to_owned(), json!("apikey"));
fixture.insert(
"paths".to_owned(),
json!({
"/one": get200("oneOpS2", None),
"/two": get200("twoOpS2", None)
}),
);
let (ir, preview) = run(&Value::Object(fixture));
for key in ["GET /one", "GET /two"] {
let blockers = security_findings(&ir.findings, key);
assert_eq!(
blockers.len(),
1,
"exactly one blocker for {key}: {:?}",
ir.findings
);
let blocker = &blockers[0];
assert_eq!(
blocker.code, "unsupported_security_requirement",
"stable finding code: {blocker:?}"
);
assert_eq!(
blocker.severity,
ImportFindingSeverity::Error,
"stable finding severity: {blocker:?}"
);
assert_eq!(
blocker.location.pointer, "/security",
"blocker must point at the malformed root security: {blocker:?}"
);
assert!(
candidate(&preview, key).findings.iter().any(|finding| {
finding.code == "unsupported_security_requirement"
&& finding.severity == ImportFindingSeverity::Error
}),
"{key} candidate must be blocked"
);
}
}
#[test]
fn swagger2_malformed_local_security_affects_only_that_operation() {
let mut fixture = security_fixture_swagger2();
// A well-formed root requirement proves priority: the malformed local
// security wins for /bad (no root blocker may be added), while /public
// relies on an explicit empty override to stay public.
fixture.insert("security".to_owned(), json!([{ "apiKey": [] }]));
fixture.insert(
"paths".to_owned(),
json!({
"/bad": get200("badOpS2", Some(json!("apikey"))),
"/public": get200("publicOpS2", Some(json!([])))
}),
);
let (ir, preview) = run(&Value::Object(fixture));
let blockers = security_findings(&ir.findings, "GET /bad");
assert_eq!(blockers.len(), 1, "exactly one blocker: {:?}", ir.findings);
assert_eq!(blockers[0].code, "unsupported_security_requirement");
assert_eq!(blockers[0].severity, ImportFindingSeverity::Error);
assert_eq!(
blockers[0].location.pointer, "/paths/~1bad/get/security",
"blocker must point at the malformed local security: {:?}",
blockers[0]
);
assert!(
security_findings(&ir.findings, "GET /public").is_empty(),
"the public neighbour must not inherit a local defect: {:?}",
ir.findings
);
assert!(
candidate(&preview, "GET /public")
.findings
.iter()
.all(|finding| finding.severity != ImportFindingSeverity::Error),
"public neighbour must stay actionable: {preview:?}"
);
}
#[test]
fn swagger2_public_alternative_with_malformed_sibling_does_not_go_public() {
let mut fixture = security_fixture_swagger2();
fixture.insert("security".to_owned(), json!([{}, "apikey"]));
fixture.insert(
"paths".to_owned(),
json!({ "/mixed": get200("mixedOpS2", None) }),
);
let (ir, preview) = run(&Value::Object(fixture));
let blockers = security_findings(&ir.findings, "GET /mixed");
assert_eq!(
blockers.len(),
1,
"only the malformed sibling blocks: {:?}",
ir.findings
);
assert_eq!(
blockers[0].location.pointer, "/security/1",
"blocker must point at the non-object item: {:?}",
blockers[0]
);
assert_eq!(
blockers[0].message,
"security содержит альтернативу без объекта требований: формат не поддерживается, операция не публикуется."
);
assert!(
candidate(&preview, "GET /mixed")
.findings
.iter()
.any(|finding| finding.severity == ImportFindingSeverity::Error),
"the operation must not become public because of a malformed sibling: {preview:?}"
);
}
#[test]
fn empty_security_array_stays_public() {
let source = json!({
"openapi": "3.0.3",
"info": { "title": "Security scope regression", "version": "1" },
"servers": [{ "url": "https://security-scope.example.test" }],
"security": [{ "probe": [] }],
"paths": {
"/public": { "get": { "security": [], "operationId": "publicOp",
"responses": { "200": { "description": "ok" } } } }
}
});
let (ir, preview) = run(&source);
assert!(
security_findings(&ir.findings, "GET /public").is_empty(),
"explicit empty override must stay public: {:?}",
ir.findings
);
assert!(
candidate(&preview, "GET /public")
.findings
.iter()
.all(|finding| finding.severity != ImportFindingSeverity::Error),
"overridden operation must remain actionable"
);
}