845 lines
33 KiB
Rust
845 lines
33 KiB
Rust
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 swagger2_cookie_api_key_is_explicitly_unsupported_at_operation_and_preview() {
|
|
let document = json!({
|
|
"swagger": "2.0",
|
|
"info": { "title": "Unsupported Swagger cookie", "version": "1" },
|
|
"host": "security.example.test",
|
|
"schemes": ["https"],
|
|
"securityDefinitions": {
|
|
"CookieKey": { "type": "apiKey", "in": "cookie", "name": "session" }
|
|
},
|
|
"security": [{ "CookieKey": [] }],
|
|
"paths": { "/private": { "get": {
|
|
"responses": { "200": { "description": "ok" } }
|
|
}}}
|
|
});
|
|
let ir = normalize(&document);
|
|
let operation = operation(&ir, "/private");
|
|
assert!(matches!(
|
|
ir.security_schemes["CookieKey"].kind,
|
|
NormalizedSecuritySchemeKind::Unsupported { .. }
|
|
));
|
|
assert!(!operation.security_requirements.alternatives[0].supported);
|
|
assert!(
|
|
operation
|
|
.findings
|
|
.iter()
|
|
.any(|finding| finding.code == "unsupported_security_scheme")
|
|
);
|
|
assert!(
|
|
operation
|
|
.findings
|
|
.iter()
|
|
.any(|finding| finding.code == "unsupported_security_requirements")
|
|
);
|
|
let preview = candidates(&ir);
|
|
let candidate = candidate(&preview, "GET /private");
|
|
assert!(
|
|
candidate
|
|
.findings
|
|
.iter()
|
|
.any(|finding| finding.code == "unsupported_security_requirements")
|
|
);
|
|
assert!(candidate.draft.input_mapping.rules.is_empty());
|
|
}
|
|
|
|
#[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®ion=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®ion=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®ion=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 { .. }
|
|
));
|
|
}
|