1use std::collections::HashSet;
2use std::path::Path;
3
4use reqwest::header::CONTENT_TYPE;
5use reqwest::Method;
6use serde_json::Value;
7use url::Url;
8
9use crate::checks::{cookies, headers, response_audit};
10use crate::models::{
11 Category, CheckOutcome, Confidence, ExecutionStatus, Finding, Severity, Verdict,
12};
13use crate::transport::{AuthMode, HttpTransport, TransportError};
14
15fn has_nonempty_security(val: Option<&Value>) -> Option<bool> {
16 let arr = val?.as_array()?;
17 if arr.is_empty() {
18 Some(false)
19 } else {
20 Some(
21 arr.iter()
22 .any(|obj| obj.as_object().map(|m| !m.is_empty()).unwrap_or(false)),
23 )
24 }
25}
26
27fn resolve_base_path(doc: &Value) -> String {
28 if let Some(bp) = doc.get("basePath").and_then(|v| v.as_str()) {
29 return bp.trim_end_matches('/').to_string();
30 }
31 if let Some(servers) = doc.get("servers").and_then(|v| v.as_array()) {
32 if let Some(first) = servers
33 .first()
34 .and_then(|s| s.get("url"))
35 .and_then(|u| u.as_str())
36 {
37 if let Ok(parsed) = Url::parse(first) {
38 return parsed.path().trim_end_matches('/').to_string();
39 }
40 if first.starts_with('/') {
41 return first.trim_end_matches('/').to_string();
42 }
43 }
44 }
45 String::new()
46}
47
48pub fn audit_openapi_document(
49 doc: &Value,
50 spec_source: &str,
51) -> (Vec<Finding>, Vec<String>, Vec<(String, bool)>) {
52 let mut findings = Vec::new();
53 let mut unauthenticated_mutating = Vec::new();
54 let mut get_endpoints = Vec::new();
55 let base_path = resolve_base_path(doc);
56
57 if let Some(servers) = doc.get("servers").and_then(|v| v.as_array()) {
59 for srv in servers {
60 if let Some(u) = srv.get("url").and_then(|v| v.as_str()) {
61 let lower = u.to_ascii_lowercase();
62 if lower.starts_with("http://")
63 && !lower.starts_with("http://localhost")
64 && !lower.starts_with("http://127.0.0.1")
65 {
66 findings.push(Finding {
67 id: "API-OPENAPI-INSECURE-SERVER".into(),
68 category: Category::ApiSecurity,
69 severity: Severity::Medium,
70 title: "OpenAPI spec advertises an unencrypted http:// server URL".into(),
71 summary: "API clients generated from this specification may send credentials over plaintext HTTP.".into(),
72 evidence: Some(format!("{u} (in {spec_source})")),
73 remediation: "Use strictly `https://` URLs in OpenAPI `servers` entries.".into(),
74 standard_ref: Some("OWASP ASVS V9.1.1 / API8:2023".into()),
75 confidence: Confidence::High,
76 });
77 break;
78 }
79 }
80 }
81 }
82
83 let schemes = doc
85 .pointer("/components/securitySchemes")
86 .or_else(|| doc.get("securityDefinitions"))
87 .and_then(|v| v.as_object());
88 if let Some(map) = schemes {
89 for (name, scheme) in map {
90 if scheme.get("in").and_then(|v| v.as_str()) == Some("query") {
91 findings.push(Finding {
92 id: "API-OPENAPI-KEY-IN-QUERY".into(),
93 category: Category::ApiSecurity,
94 severity: Severity::Medium,
95 title: format!("API key security scheme `{name}` transmits credentials in query string"),
96 summary: "API keys passed in URL query parameters leak into proxy/access logs, browser history, and Referer headers.".into(),
97 evidence: Some(format!("securityScheme `{name}` uses `in: query` ({spec_source})")),
98 remediation: "Move API credentials to HTTP `Authorization` or custom request headers (`in: header`).".into(),
99 standard_ref: Some("OWASP ASVS V2.10 / WSTG-ATHN".into()),
100 confidence: Confidence::High,
101 });
102 }
103 }
104 }
105
106 let global_sec = has_nonempty_security(doc.get("security")).unwrap_or(false);
107
108 if let Some(paths) = doc.get("paths").and_then(|v| v.as_object()) {
109 for (raw_path, item) in paths {
110 let Some(methods) = item.as_object() else {
111 continue;
112 };
113 let full_path = if base_path.is_empty() || raw_path.starts_with(&base_path) {
114 raw_path.clone()
115 } else {
116 format!("{base_path}{raw_path}")
117 };
118
119 for method_name in ["get", "post", "put", "patch", "delete"] {
120 let Some(op) = methods.get(method_name) else {
121 continue;
122 };
123 let op_sec = has_nonempty_security(op.get("security")).unwrap_or(global_sec);
124
125 if method_name == "get" {
126 if !full_path.contains('{') {
127 get_endpoints.push((full_path.clone(), op_sec));
128 }
129 } else if !op_sec && unauthenticated_mutating.len() < 8 {
130 unauthenticated_mutating.push(format!(
131 "{} {}",
132 method_name.to_ascii_uppercase(),
133 full_path
134 ));
135 }
136 }
137 }
138 }
139
140 if !unauthenticated_mutating.is_empty() {
141 findings.push(Finding {
142 id: "API-OPENAPI-UNPROTECTED-SPEC".into(),
143 category: Category::ApiSecurity,
144 severity: Severity::Medium,
145 title: "State-changing API endpoints have no security scheme in OpenAPI spec".into(),
146 summary: format!(
147 "Found {} mutating endpoint(s) without OpenAPI `security` requirements.",
148 unauthenticated_mutating.len()
149 ),
150 evidence: Some(unauthenticated_mutating.join(", ")),
151 remediation: "Define global or per-operation `security` schemes for all mutating API operations in the OpenAPI document.".into(),
152 standard_ref: Some("OWASP API2:2023 / ASVS V4.1".into()),
153 confidence: Confidence::High,
154 });
155 }
156
157 let endpoint_paths: Vec<String> = get_endpoints.iter().map(|(p, _)| p.clone()).collect();
158 (findings, endpoint_paths, get_endpoints)
159}
160
161pub async fn run_openapi_audit(
162 spec_path_or_url: &str,
163 transport: &HttpTransport,
164 base_url: &Url,
165 auth_context: &str,
166) -> (Vec<Finding>, Vec<CheckOutcome>) {
167 let mut findings = Vec::new();
168 let mut outcomes = Vec::new();
169 let trimmed = spec_path_or_url.trim();
170
171 let raw_spec = if trimmed.starts_with("http://")
172 || trimmed.starts_with("https://")
173 || trimmed.starts_with('/')
174 {
175 match transport.resolve_in_scope(base_url, trimmed) {
176 Ok(spec_url) => {
177 match transport
178 .send(Method::GET, &spec_url, AuthMode::TargetOrigin, &[], None)
179 .await
180 {
181 Ok(resp) if resp.status < 400 => {
182 String::from_utf8_lossy(&resp.body).to_string()
183 }
184 Ok(resp) => {
185 outcomes.push(CheckOutcome {
186 check_id: "openapi-security".into(),
187 category: Category::ApiSecurity,
188 location: transport.redactor.sanitize_url(&spec_url),
189 auth_context: auth_context.to_string(),
190 status: ExecutionStatus::Error,
191 verdict: Verdict::Inconclusive,
192 reason: Some(format!("HTTP {} fetching OpenAPI spec", resp.status)),
193 });
194 return (findings, outcomes);
195 }
196 Err(e) => {
197 outcomes.push(CheckOutcome {
198 check_id: "openapi-security".into(),
199 category: Category::ApiSecurity,
200 location: trimmed.to_string(),
201 auth_context: auth_context.to_string(),
202 status: if matches!(e, TransportError::Cancelled) {
203 ExecutionStatus::Cancelled
204 } else {
205 ExecutionStatus::Error
206 },
207 verdict: Verdict::Inconclusive,
208 reason: Some(e.to_string()),
209 });
210 return (findings, outcomes);
211 }
212 }
213 }
214 Err(e) => {
215 outcomes.push(CheckOutcome {
216 check_id: "openapi-security".into(),
217 category: Category::ApiSecurity,
218 location: trimmed.to_string(),
219 auth_context: auth_context.to_string(),
220 status: ExecutionStatus::Error,
221 verdict: Verdict::Inconclusive,
222 reason: Some(e.to_string()),
223 });
224 return (findings, outcomes);
225 }
226 }
227 } else {
228 match std::fs::read_to_string(Path::new(trimmed)) {
229 Ok(s) => s,
230 Err(e) => {
231 outcomes.push(CheckOutcome {
232 check_id: "openapi-security".into(),
233 category: Category::ApiSecurity,
234 location: trimmed.to_string(),
235 auth_context: auth_context.to_string(),
236 status: ExecutionStatus::Error,
237 verdict: Verdict::Inconclusive,
238 reason: Some(format!("failed to read OpenAPI file: {e}")),
239 });
240 return (findings, outcomes);
241 }
242 }
243 };
244
245 let doc: Value = match serde_json::from_str(&raw_spec) {
246 Ok(v) => v,
247 Err(e) => {
248 outcomes.push(CheckOutcome {
249 check_id: "openapi-security".into(),
250 category: Category::ApiSecurity,
251 location: trimmed.to_string(),
252 auth_context: auth_context.to_string(),
253 status: ExecutionStatus::Error,
254 verdict: Verdict::Inconclusive,
255 reason: Some(format!("invalid OpenAPI JSON: {e}")),
256 });
257 return (findings, outcomes);
258 }
259 };
260
261 let (spec_findings, _, get_endpoints) = audit_openapi_document(&doc, trimmed);
262 findings.extend(spec_findings);
263
264 let mut seen_ep = HashSet::new();
265 let mut probed = 0usize;
266 let mut any_auth_bypass = false;
267
268 for (ep_path, requires_sec) in get_endpoints.into_iter().take(20) {
269 if transport.is_cancelled() || !seen_ep.insert(ep_path.clone()) {
270 continue;
271 }
272 let Ok(ep_url) = transport.resolve_in_scope(base_url, &ep_path) else {
273 continue;
274 };
275
276 let ep_resp = match transport
277 .send(Method::GET, &ep_url, AuthMode::TargetOrigin, &[], None)
278 .await
279 {
280 Ok(r) => r,
281 Err(TransportError::Cancelled) | Err(TransportError::BudgetExhausted(_)) => break,
282 Err(_) => continue,
283 };
284 probed += 1;
285
286 let is_https = ep_resp.final_url.scheme() == "https";
287 findings.extend(headers::analyze_headers(&ep_resp.headers, is_https));
288 findings.extend(cookies::analyze_cookies(&ep_resp.headers, is_https));
289 if let Some(cf) =
290 headers::analyze_caching(&ep_resp.headers, true, ep_resp.final_url.as_str())
291 {
292 findings.push(cf);
293 }
294 if let Ok(text) = std::str::from_utf8(&ep_resp.body) {
295 findings.extend(response_audit::analyze_response_leaks(
296 &ep_resp.headers,
297 text,
298 &ep_resp.final_url,
299 ));
300 }
301
302 if requires_sec && !transport.is_cancelled() {
304 if let Ok(anon_resp) = transport
305 .send(Method::GET, &ep_url, AuthMode::Anonymous, &[], None)
306 .await
307 {
308 let ct = anon_resp
309 .headers
310 .get(CONTENT_TYPE)
311 .and_then(|v| v.to_str().ok())
312 .unwrap_or("")
313 .to_ascii_lowercase();
314 if anon_resp.status == 200
315 && !anon_resp.body.is_empty()
316 && !ct.contains("text/html")
317 {
318 any_auth_bypass = true;
319 findings.push(Finding {
320 id: "AUTH-MISSING-ENFORCEMENT".into(),
321 category: Category::ApiSecurity,
322 severity: Severity::Critical,
323 title: format!("Protected OpenAPI endpoint responds HTTP 200 without credentials: {ep_path}"),
324 summary: "Endpoint specifies authentication in OpenAPI `security` metadata, but returned an unauthenticated 200 OK API payload.".into(),
325 evidence: Some(format!(
326 "GET {} (anonymous) -> HTTP 200 ({} bytes)",
327 transport.redactor.sanitize_url(&ep_url),
328 anon_resp.body.len()
329 )),
330 remediation: "Enforce authentication middleware on the route and verify server-side authorization before returning data.".into(),
331 standard_ref: Some("OWASP ASVS V4.1.1 / OWASP API2:2023".into()),
332 confidence: Confidence::High,
333 });
334 }
335 }
336 }
337 }
338
339 outcomes.push(CheckOutcome {
340 check_id: "openapi-security".into(),
341 category: Category::ApiSecurity,
342 location: trimmed.to_string(),
343 auth_context: auth_context.to_string(),
344 status: ExecutionStatus::Completed,
345 verdict: if any_auth_bypass || !findings.is_empty() {
346 Verdict::Fail
347 } else {
348 Verdict::Pass
349 },
350 reason: Some(format!("audited {probed} GET endpoint(s)")),
351 });
352
353 (findings, outcomes)
354}
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359
360 #[test]
361 fn audits_openapi_spec_for_security_gaps() {
362 let spec: Value = serde_json::json!({
363 "openapi": "3.0.3",
364 "servers": [{ "url": "http://api.prod.example/v1" }],
365 "components": {
366 "securitySchemes": {
367 "ApiKeyAuth": { "type": "apiKey", "in": "query", "name": "api_key" },
368 "BearerAuth": { "type": "http", "scheme": "bearer" }
369 }
370 },
371 "paths": {
372 "/orders": {
373 "post": { "responses": { "201": { "description": "created" } } },
374 "get": {
375 "security": [{ "BearerAuth": [] }],
376 "responses": { "200": { "description": "ok" } }
377 }
378 }
379 }
380 });
381
382 let (findings, paths, gets) = audit_openapi_document(&spec, "openapi.json");
383 let ids: Vec<&str> = findings.iter().map(|f| f.id.as_str()).collect();
384 assert!(ids.contains(&"API-OPENAPI-INSECURE-SERVER"));
385 assert!(ids.contains(&"API-OPENAPI-KEY-IN-QUERY"));
386 assert!(ids.contains(&"API-OPENAPI-UNPROTECTED-SPEC"));
387 assert_eq!(paths, vec!["/v1/orders"]);
388 assert!(gets[0].1);
389 }
390}