use std::collections::HashSet;
use std::path::Path;
use reqwest::header::CONTENT_TYPE;
use reqwest::Method;
use serde_json::Value;
use url::Url;
use crate::checks::{cookies, headers, response_audit};
use crate::models::{
Category, CheckOutcome, Confidence, ExecutionStatus, Finding, Severity, Verdict,
};
use crate::transport::{AuthMode, HttpTransport, TransportError};
fn has_nonempty_security(val: Option<&Value>) -> Option<bool> {
let arr = val?.as_array()?;
if arr.is_empty() {
Some(false)
} else {
Some(
arr.iter()
.any(|obj| obj.as_object().map(|m| !m.is_empty()).unwrap_or(false)),
)
}
}
fn resolve_base_path(doc: &Value) -> String {
if let Some(bp) = doc.get("basePath").and_then(|v| v.as_str()) {
return bp.trim_end_matches('/').to_string();
}
if let Some(servers) = doc.get("servers").and_then(|v| v.as_array()) {
if let Some(first) = servers
.first()
.and_then(|s| s.get("url"))
.and_then(|u| u.as_str())
{
if let Ok(parsed) = Url::parse(first) {
return parsed.path().trim_end_matches('/').to_string();
}
if first.starts_with('/') {
return first.trim_end_matches('/').to_string();
}
}
}
String::new()
}
pub fn audit_openapi_document(
doc: &Value,
spec_source: &str,
) -> (Vec<Finding>, Vec<String>, Vec<(String, bool)>) {
let mut findings = Vec::new();
let mut unauthenticated_mutating = Vec::new();
let mut get_endpoints = Vec::new();
let base_path = resolve_base_path(doc);
if let Some(servers) = doc.get("servers").and_then(|v| v.as_array()) {
for srv in servers {
if let Some(u) = srv.get("url").and_then(|v| v.as_str()) {
let lower = u.to_ascii_lowercase();
if lower.starts_with("http://")
&& !lower.starts_with("http://localhost")
&& !lower.starts_with("http://127.0.0.1")
{
findings.push(Finding {
id: "API-OPENAPI-INSECURE-SERVER".into(),
category: Category::ApiSecurity,
severity: Severity::Medium,
title: "OpenAPI spec advertises an unencrypted http:// server URL".into(),
summary: "API clients generated from this specification may send credentials over plaintext HTTP.".into(),
evidence: Some(format!("{u} (in {spec_source})")),
remediation: "Use strictly `https://` URLs in OpenAPI `servers` entries.".into(),
standard_ref: Some("OWASP ASVS V9.1.1 / API8:2023".into()),
confidence: Confidence::High,
});
break;
}
}
}
}
let schemes = doc
.pointer("/components/securitySchemes")
.or_else(|| doc.get("securityDefinitions"))
.and_then(|v| v.as_object());
if let Some(map) = schemes {
for (name, scheme) in map {
if scheme.get("in").and_then(|v| v.as_str()) == Some("query") {
findings.push(Finding {
id: "API-OPENAPI-KEY-IN-QUERY".into(),
category: Category::ApiSecurity,
severity: Severity::Medium,
title: format!("API key security scheme `{name}` transmits credentials in query string"),
summary: "API keys passed in URL query parameters leak into proxy/access logs, browser history, and Referer headers.".into(),
evidence: Some(format!("securityScheme `{name}` uses `in: query` ({spec_source})")),
remediation: "Move API credentials to HTTP `Authorization` or custom request headers (`in: header`).".into(),
standard_ref: Some("OWASP ASVS V2.10 / WSTG-ATHN".into()),
confidence: Confidence::High,
});
}
}
}
let global_sec = has_nonempty_security(doc.get("security")).unwrap_or(false);
if let Some(paths) = doc.get("paths").and_then(|v| v.as_object()) {
for (raw_path, item) in paths {
let Some(methods) = item.as_object() else {
continue;
};
let full_path = if base_path.is_empty() || raw_path.starts_with(&base_path) {
raw_path.clone()
} else {
format!("{base_path}{raw_path}")
};
for method_name in ["get", "post", "put", "patch", "delete"] {
let Some(op) = methods.get(method_name) else {
continue;
};
let op_sec = has_nonempty_security(op.get("security")).unwrap_or(global_sec);
if method_name == "get" {
if !full_path.contains('{') {
get_endpoints.push((full_path.clone(), op_sec));
}
} else if !op_sec && unauthenticated_mutating.len() < 8 {
unauthenticated_mutating.push(format!(
"{} {}",
method_name.to_ascii_uppercase(),
full_path
));
}
}
}
}
if !unauthenticated_mutating.is_empty() {
findings.push(Finding {
id: "API-OPENAPI-UNPROTECTED-SPEC".into(),
category: Category::ApiSecurity,
severity: Severity::Medium,
title: "State-changing API endpoints have no security scheme in OpenAPI spec".into(),
summary: format!(
"Found {} mutating endpoint(s) without OpenAPI `security` requirements.",
unauthenticated_mutating.len()
),
evidence: Some(unauthenticated_mutating.join(", ")),
remediation: "Define global or per-operation `security` schemes for all mutating API operations in the OpenAPI document.".into(),
standard_ref: Some("OWASP API2:2023 / ASVS V4.1".into()),
confidence: Confidence::High,
});
}
let endpoint_paths: Vec<String> = get_endpoints.iter().map(|(p, _)| p.clone()).collect();
(findings, endpoint_paths, get_endpoints)
}
pub async fn run_openapi_audit(
spec_path_or_url: &str,
transport: &HttpTransport,
base_url: &Url,
auth_context: &str,
) -> (Vec<Finding>, Vec<CheckOutcome>) {
let mut findings = Vec::new();
let mut outcomes = Vec::new();
let trimmed = spec_path_or_url.trim();
let raw_spec = if trimmed.starts_with("http://")
|| trimmed.starts_with("https://")
|| trimmed.starts_with('/')
{
match transport.resolve_in_scope(base_url, trimmed) {
Ok(spec_url) => {
match transport
.send(Method::GET, &spec_url, AuthMode::TargetOrigin, &[], None)
.await
{
Ok(resp) if resp.status < 400 => {
String::from_utf8_lossy(&resp.body).to_string()
}
Ok(resp) => {
outcomes.push(CheckOutcome {
check_id: "openapi-security".into(),
category: Category::ApiSecurity,
location: transport.redactor.sanitize_url(&spec_url),
auth_context: auth_context.to_string(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some(format!("HTTP {} fetching OpenAPI spec", resp.status)),
});
return (findings, outcomes);
}
Err(e) => {
outcomes.push(CheckOutcome {
check_id: "openapi-security".into(),
category: Category::ApiSecurity,
location: trimmed.to_string(),
auth_context: auth_context.to_string(),
status: if matches!(e, TransportError::Cancelled) {
ExecutionStatus::Cancelled
} else {
ExecutionStatus::Error
},
verdict: Verdict::Inconclusive,
reason: Some(e.to_string()),
});
return (findings, outcomes);
}
}
}
Err(e) => {
outcomes.push(CheckOutcome {
check_id: "openapi-security".into(),
category: Category::ApiSecurity,
location: trimmed.to_string(),
auth_context: auth_context.to_string(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some(e.to_string()),
});
return (findings, outcomes);
}
}
} else {
match std::fs::read_to_string(Path::new(trimmed)) {
Ok(s) => s,
Err(e) => {
outcomes.push(CheckOutcome {
check_id: "openapi-security".into(),
category: Category::ApiSecurity,
location: trimmed.to_string(),
auth_context: auth_context.to_string(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some(format!("failed to read OpenAPI file: {e}")),
});
return (findings, outcomes);
}
}
};
let doc: Value = match serde_json::from_str(&raw_spec) {
Ok(v) => v,
Err(e) => {
outcomes.push(CheckOutcome {
check_id: "openapi-security".into(),
category: Category::ApiSecurity,
location: trimmed.to_string(),
auth_context: auth_context.to_string(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some(format!("invalid OpenAPI JSON: {e}")),
});
return (findings, outcomes);
}
};
let (spec_findings, _, get_endpoints) = audit_openapi_document(&doc, trimmed);
findings.extend(spec_findings);
let mut seen_ep = HashSet::new();
let mut probed = 0usize;
let mut any_auth_bypass = false;
for (ep_path, requires_sec) in get_endpoints.into_iter().take(20) {
if transport.is_cancelled() || !seen_ep.insert(ep_path.clone()) {
continue;
}
let Ok(ep_url) = transport.resolve_in_scope(base_url, &ep_path) else {
continue;
};
let ep_resp = match transport
.send(Method::GET, &ep_url, AuthMode::TargetOrigin, &[], None)
.await
{
Ok(r) => r,
Err(TransportError::Cancelled) | Err(TransportError::BudgetExhausted(_)) => break,
Err(_) => continue,
};
probed += 1;
let is_https = ep_resp.final_url.scheme() == "https";
findings.extend(headers::analyze_headers(&ep_resp.headers, is_https));
findings.extend(cookies::analyze_cookies(&ep_resp.headers, is_https));
if let Some(cf) =
headers::analyze_caching(&ep_resp.headers, true, ep_resp.final_url.as_str())
{
findings.push(cf);
}
if let Ok(text) = std::str::from_utf8(&ep_resp.body) {
findings.extend(response_audit::analyze_response_leaks(
&ep_resp.headers,
text,
&ep_resp.final_url,
));
}
if requires_sec && !transport.is_cancelled() {
if let Ok(anon_resp) = transport
.send(Method::GET, &ep_url, AuthMode::Anonymous, &[], None)
.await
{
let ct = anon_resp
.headers
.get(CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_ascii_lowercase();
if anon_resp.status == 200
&& !anon_resp.body.is_empty()
&& !ct.contains("text/html")
{
any_auth_bypass = true;
findings.push(Finding {
id: "AUTH-MISSING-ENFORCEMENT".into(),
category: Category::ApiSecurity,
severity: Severity::Critical,
title: format!("Protected OpenAPI endpoint responds HTTP 200 without credentials: {ep_path}"),
summary: "Endpoint specifies authentication in OpenAPI `security` metadata, but returned an unauthenticated 200 OK API payload.".into(),
evidence: Some(format!(
"GET {} (anonymous) -> HTTP 200 ({} bytes)",
transport.redactor.sanitize_url(&ep_url),
anon_resp.body.len()
)),
remediation: "Enforce authentication middleware on the route and verify server-side authorization before returning data.".into(),
standard_ref: Some("OWASP ASVS V4.1.1 / OWASP API2:2023".into()),
confidence: Confidence::High,
});
}
}
}
}
outcomes.push(CheckOutcome {
check_id: "openapi-security".into(),
category: Category::ApiSecurity,
location: trimmed.to_string(),
auth_context: auth_context.to_string(),
status: ExecutionStatus::Completed,
verdict: if any_auth_bypass || !findings.is_empty() {
Verdict::Fail
} else {
Verdict::Pass
},
reason: Some(format!("audited {probed} GET endpoint(s)")),
});
(findings, outcomes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn audits_openapi_spec_for_security_gaps() {
let spec: Value = serde_json::json!({
"openapi": "3.0.3",
"servers": [{ "url": "http://api.prod.example/v1" }],
"components": {
"securitySchemes": {
"ApiKeyAuth": { "type": "apiKey", "in": "query", "name": "api_key" },
"BearerAuth": { "type": "http", "scheme": "bearer" }
}
},
"paths": {
"/orders": {
"post": { "responses": { "201": { "description": "created" } } },
"get": {
"security": [{ "BearerAuth": [] }],
"responses": { "200": { "description": "ok" } }
}
}
}
});
let (findings, paths, gets) = audit_openapi_document(&spec, "openapi.json");
let ids: Vec<&str> = findings.iter().map(|f| f.id.as_str()).collect();
assert!(ids.contains(&"API-OPENAPI-INSECURE-SERVER"));
assert!(ids.contains(&"API-OPENAPI-KEY-IN-QUERY"));
assert!(ids.contains(&"API-OPENAPI-UNPROTECTED-SPEC"));
assert_eq!(paths, vec!["/v1/orders"]);
assert!(gets[0].1);
}
}