api-gate-keeper 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. api_gate_keeper-0.1.0.dist-info/METADATA +654 -0
  2. api_gate_keeper-0.1.0.dist-info/RECORD +35 -0
  3. api_gate_keeper-0.1.0.dist-info/WHEEL +5 -0
  4. api_gate_keeper-0.1.0.dist-info/entry_points.txt +2 -0
  5. api_gate_keeper-0.1.0.dist-info/licenses/LICENSE +21 -0
  6. api_gate_keeper-0.1.0.dist-info/top_level.txt +1 -0
  7. app_test/__init__.py +2 -0
  8. app_test/auth.py +107 -0
  9. app_test/categories/__init__.py +24 -0
  10. app_test/categories/auth_robustness.py +186 -0
  11. app_test/categories/authz.py +119 -0
  12. app_test/categories/baseline.py +29 -0
  13. app_test/categories/bola_matrix.py +340 -0
  14. app_test/categories/contract_conformance.py +249 -0
  15. app_test/categories/error_leakage_and_debug_surface.py +270 -0
  16. app_test/categories/file_upload_security.py +302 -0
  17. app_test/categories/jwt_security.py +261 -0
  18. app_test/categories/mass_assignment.py +200 -0
  19. app_test/categories/owasp.py +127 -0
  20. app_test/categories/pen_test.py +37 -0
  21. app_test/categories/privilege_escalation.py +180 -0
  22. app_test/categories/rate_limit_and_resource_abuse.py +240 -0
  23. app_test/categories/schema_contract_and_validation.py +297 -0
  24. app_test/categories/security_misc.py +99 -0
  25. app_test/categories/soak_profile.py +255 -0
  26. app_test/categories/sql_injection.py +36 -0
  27. app_test/categories/ssrf_and_redirects.py +280 -0
  28. app_test/categories/token_security.py +195 -0
  29. app_test/categories/workflow_chains.py +437 -0
  30. app_test/cli.py +1085 -0
  31. app_test/config.py +19 -0
  32. app_test/discovery.py +269 -0
  33. app_test/executor.py +184 -0
  34. app_test/models.py +54 -0
  35. app_test/report.py +628 -0
app_test/report.py ADDED
@@ -0,0 +1,628 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from collections import defaultdict
5
+ from dataclasses import asdict
6
+ from datetime import UTC, datetime
7
+ from pathlib import Path
8
+ import xml.etree.ElementTree as ET
9
+
10
+ from app_test.models import ExecutionResult, RunSummary
11
+
12
+
13
+ def build_summary(results: list[ExecutionResult], discovered_endpoints: int) -> RunSummary:
14
+ by_category: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int))
15
+ counters = {"pass": 0, "fail": 0, "skipped": 0, "error": 0}
16
+
17
+ for result in results:
18
+ counters[result.status] = counters.get(result.status, 0) + 1
19
+ by_category[result.category][result.status] += 1
20
+
21
+ return RunSummary(
22
+ discovered_endpoints=discovered_endpoints,
23
+ executed_tests=len(results),
24
+ passed=counters.get("pass", 0),
25
+ failed=counters.get("fail", 0),
26
+ skipped=counters.get("skipped", 0),
27
+ errors=counters.get("error", 0),
28
+ by_category={k: dict(v) for k, v in by_category.items()},
29
+ )
30
+
31
+
32
+ def _test_description(item: ExecutionResult) -> str:
33
+ if item.test_name == "baseline_request":
34
+ return f"Baseline API execution for {item.method} {item.url}"
35
+ if item.test_name.startswith("sqli_payload:"):
36
+ payload = item.test_name.split(":", 1)[1]
37
+ return f"SQL injection probe with payload '{payload}' on {item.method} {item.url}"
38
+ if item.test_name.startswith("pentest_payload:"):
39
+ payload = item.test_name.split(":", 1)[1]
40
+ return f"Penetration payload probe with '{payload}' on {item.method} {item.url}"
41
+ if item.test_name == "security_headers_check":
42
+ return f"Security header validation for endpoint {item.url}"
43
+ if item.test_name == "auth_required_check":
44
+ return f"Authorization enforcement check without bearer token for {item.method} {item.url}"
45
+ if item.test_name == "authz_unauthenticated_access_check":
46
+ return f"Authorization check without bearer token for {item.method} {item.url}"
47
+ if item.test_name == "idor_path_tamper_check":
48
+ return f"IDOR probe with tampered path identifier on {item.method} {item.url}"
49
+ if item.test_name == "invalid_credentials_rejection_check":
50
+ return f"Invalid credential rejection check on {item.method} {item.url}"
51
+ if item.test_name == "failed_login_throttle_signal_check":
52
+ return f"Failed-login throttle signal check on {item.method} {item.url}"
53
+ if item.test_name == "auth_endpoint_discovery":
54
+ return "Authentication endpoint discovery for auth robustness checks"
55
+ if item.test_name == "malformed_bearer_token_check":
56
+ return f"Malformed bearer token rejection check on {item.method} {item.url}"
57
+ if item.test_name == "tampered_bearer_token_check":
58
+ return f"Tampered bearer token rejection check on {item.method} {item.url}"
59
+ if item.test_name == "missing_bearer_prefix_check":
60
+ return f"Authorization header format enforcement check on {item.method} {item.url}"
61
+ if item.test_name == "token_security_target_discovery":
62
+ return "Authenticated endpoint discovery for token security checks"
63
+ if item.test_name == "jwt_format_detection":
64
+ return "JWT token format detection for token security checks"
65
+ if item.test_name == "privileged_endpoint_access_check":
66
+ return f"Privileged endpoint access check on {item.method} {item.url}"
67
+ if item.test_name == "upload_path_traversal_filename_check":
68
+ return f"Multipart upload path traversal filename check on {item.method} {item.url}"
69
+ if item.test_name == "upload_absolute_path_filename_check":
70
+ return f"Multipart upload absolute-path filename check on {item.method} {item.url}"
71
+ if item.test_name == "file_upload_target_discovery":
72
+ return "Multipart upload endpoint discovery for file upload security checks"
73
+ if item.test_name == "file_upload_application_context_discovery":
74
+ return "Application context discovery required to execute authenticated upload checks"
75
+ if item.test_name == "ssrf_private_address_rejection_check":
76
+ return f"SSRF probe using a localhost/private-address URL on {item.method} {item.url}"
77
+ if item.test_name == "ssrf_metadata_address_rejection_check":
78
+ return f"SSRF probe using a cloud metadata URL on {item.method} {item.url}"
79
+ if item.test_name == "ssrf_target_discovery":
80
+ return "Supported SSRF-style URL mutation endpoint discovery"
81
+ if item.test_name == "ssrf_instance_url_context_discovery":
82
+ return "Existing ServiceNow integration context discovery required to safely execute SSRF checks"
83
+ if item.test_name == "redirect_target_discovery":
84
+ return "Redirect-style parameter discovery for open redirect coverage expansion"
85
+ if item.test_name == "burst_rate_limit_signal_check":
86
+ return f"Rapid burst request probe for endpoint {item.url}"
87
+ if item.test_name == "oversized_pagination_window_check":
88
+ return f"Oversized pagination or range-window probe for endpoint {item.url}"
89
+ if item.test_name == "rate_limit_target_discovery":
90
+ return "Authenticated high-value read endpoint discovery for rate-limit and resource-abuse checks"
91
+ if item.test_name == "debug_route_public_exposure_check":
92
+ return "Debug route public exposure discovery check"
93
+ if item.test_name == "debug_route_unauthenticated_access_check":
94
+ return f"Unauthenticated access check for debug route {item.url}"
95
+ if item.test_name == "error_response_information_leak_check":
96
+ return f"Error response information leakage probe for {item.method} {item.url}"
97
+ if item.test_name == "error_leakage_target_discovery":
98
+ return "Safe endpoint discovery for error response leakage checks"
99
+ if item.test_name == "mass_assignment_sensitive_field_probe":
100
+ return f"Sensitive field mass assignment probe on {item.method} {item.url}"
101
+ if item.test_name == "mass_assignment_target_discovery":
102
+ return "Authenticated JSON mutation endpoint discovery for mass assignment checks"
103
+ if item.test_name == "required_field_validation_check":
104
+ return f"Required field validation check on {item.method} {item.url}"
105
+ if item.test_name == "wrong_type_validation_check":
106
+ return f"Wrong-type validation check on {item.method} {item.url}"
107
+ if item.test_name == "unknown_field_handling_check":
108
+ return f"Unknown field handling check on {item.method} {item.url}"
109
+ if item.test_name == "schema_validation_target_discovery":
110
+ return "Authenticated JSON mutation endpoint discovery for schema contract validation checks"
111
+ if item.test_name == "cors_wildcard_check":
112
+ return "CORS policy check for wildcard allow-origin"
113
+ if item.test_name == "basic_rate_probe":
114
+ return f"Basic rapid-request probe for endpoint {item.url}"
115
+ return f"{item.test_name} on {item.method} {item.url}"
116
+
117
+
118
+ def _expected_behavior(item: ExecutionResult) -> str:
119
+ if item.test_name == "security_headers_check":
120
+ return "Response should include key security headers such as HSTS and CSP"
121
+ if item.test_name == "auth_required_check":
122
+ return "Endpoint should reject unauthenticated access"
123
+ if item.test_name == "authz_unauthenticated_access_check":
124
+ return "Endpoint should reject unauthenticated access"
125
+ if item.test_name == "idor_path_tamper_check":
126
+ return "Endpoint should reject or hide unauthorized object access attempts"
127
+ if item.test_name == "invalid_credentials_rejection_check":
128
+ return "Login endpoint should reject invalid credentials"
129
+ if item.test_name == "failed_login_throttle_signal_check":
130
+ return "Login endpoint should show basic failed-attempt throttling or lockout signal"
131
+ if item.test_name == "auth_endpoint_discovery":
132
+ return "Scanner should discover a login-like endpoint to execute authentication robustness checks"
133
+ if item.test_name == "malformed_bearer_token_check":
134
+ return "API should reject malformed bearer tokens"
135
+ if item.test_name == "tampered_bearer_token_check":
136
+ return "API should reject tampered or signature-invalid bearer tokens"
137
+ if item.test_name == "missing_bearer_prefix_check":
138
+ return "API should require a properly formatted Authorization: Bearer header"
139
+ if item.test_name == "token_security_target_discovery":
140
+ return "Scanner should discover authenticated endpoints suitable for token validation checks"
141
+ if item.test_name == "jwt_format_detection":
142
+ return "Scanner should identify whether JWT-specific token structure checks are applicable"
143
+ if item.test_name == "privileged_endpoint_access_check":
144
+ return "Non-admin tokens should not access privileged or admin-oriented endpoints"
145
+ if item.test_name in {"upload_path_traversal_filename_check", "upload_absolute_path_filename_check"}:
146
+ return "Upload handlers should reject or safely sanitize unsafe filenames such as ../ traversal or absolute paths"
147
+ if item.test_name == "file_upload_target_discovery":
148
+ return "Scanner should discover multipart/form-data upload endpoints suitable for file upload security checks"
149
+ if item.test_name == "file_upload_application_context_discovery":
150
+ return "Scanner should discover an application context so authenticated upload endpoints can be exercised meaningfully"
151
+ if item.test_name in {"ssrf_private_address_rejection_check", "ssrf_metadata_address_rejection_check"}:
152
+ return "Endpoints that configure or trigger outbound network access should reject localhost, link-local, metadata, and other dangerous internal targets"
153
+ if item.test_name == "ssrf_target_discovery":
154
+ return "Scanner should discover supported URL-bearing mutation endpoints suitable for SSRF coverage"
155
+ if item.test_name == "ssrf_instance_url_context_discovery":
156
+ return "Scanner should discover existing outbound integration context so SSRF probes can be executed and safely restored"
157
+ if item.test_name == "redirect_target_discovery":
158
+ return "Scanner should identify redirect-style parameters or endpoints suitable for open redirect checks"
159
+ if item.test_name == "burst_rate_limit_signal_check":
160
+ return "Sensitive list, status, and dashboard endpoints should throttle abusive bursts or at least avoid degradation under short spikes"
161
+ if item.test_name == "oversized_pagination_window_check":
162
+ return "Endpoints should reject or strictly bound abusive pagination and range-window requests"
163
+ if item.test_name == "rate_limit_target_discovery":
164
+ return "Scanner should discover authenticated high-value read endpoints suitable for rate-limit and resource-abuse checks"
165
+ if item.test_name == "debug_route_public_exposure_check":
166
+ return "Debug routes should not be publicly exposed in production API surfaces"
167
+ if item.test_name == "debug_route_unauthenticated_access_check":
168
+ return "Debug routes should reject unauthenticated access"
169
+ if item.test_name == "error_response_information_leak_check":
170
+ return "Error responses should avoid leaking stack traces, internal paths, framework internals, or backend exception details"
171
+ if item.test_name == "error_leakage_target_discovery":
172
+ return "Scanner should discover safe endpoints suitable for error-leakage probing"
173
+ if item.test_name == "mass_assignment_sensitive_field_probe":
174
+ return "API should reject or ignore client-supplied sensitive fields such as role, tenant_id, or is_admin"
175
+ if item.test_name == "mass_assignment_target_discovery":
176
+ return "Scanner should discover authenticated JSON mutation endpoints suitable for mass assignment checks"
177
+ if item.test_name == "required_field_validation_check":
178
+ return "API should reject payloads that omit required fields"
179
+ if item.test_name == "wrong_type_validation_check":
180
+ return "API should reject payloads with values that do not match declared field types"
181
+ if item.test_name == "unknown_field_handling_check":
182
+ return "API should reject or safely ignore undeclared fields outside the schema contract"
183
+ if item.test_name == "schema_validation_target_discovery":
184
+ return "Scanner should discover authenticated JSON mutation endpoints suitable for schema validation checks"
185
+ if item.test_name == "cors_wildcard_check":
186
+ return "CORS should not allow wildcard origin for sensitive APIs"
187
+ if item.status == "skipped":
188
+ return "Unsafe mutation endpoints are skipped unless explicitly enabled"
189
+ return "Endpoint should respond without server-side failure (5xx)"
190
+
191
+
192
+ def _actual_behavior(item: ExecutionResult) -> str:
193
+ base = f"status={item.status}"
194
+ if item.http_status is not None:
195
+ base += f", http_status={item.http_status}"
196
+ if item.retries:
197
+ base += f", retries={item.retries}"
198
+ if item.message:
199
+ base += f", message={item.message}"
200
+ if item.response_snippet:
201
+ base += f", response_snippet={item.response_snippet}"
202
+ return base
203
+
204
+
205
+ def _remediation(item: ExecutionResult) -> str:
206
+ if item.status in {"pass", "skipped"}:
207
+ return "No remediation required"
208
+ if item.test_name == "security_headers_check":
209
+ return "Configure API gateway/reverse proxy to inject missing security headers (at least HSTS and CSP)"
210
+ if item.test_name == "auth_required_check":
211
+ return "Enforce authentication/authorization middleware on this endpoint and verify role checks"
212
+ if item.test_name == "authz_unauthenticated_access_check":
213
+ return "Require valid bearer authentication for this endpoint and verify role checks"
214
+ if item.test_name == "idor_path_tamper_check":
215
+ return "Enforce object-level authorization, tenant scoping, and non-enumerable access checks"
216
+ if item.test_name == "invalid_credentials_rejection_check":
217
+ return "Ensure auth endpoint returns non-success for invalid credentials and avoids credential oracle leaks"
218
+ if item.test_name == "failed_login_throttle_signal_check":
219
+ return "Add per-account/IP failed-login throttling and lockout controls with safe recovery paths"
220
+ if item.test_name == "auth_endpoint_discovery":
221
+ return "Document or expose auth endpoint in API schema so automated robustness checks can run"
222
+ if item.test_name in {"malformed_bearer_token_check", "tampered_bearer_token_check", "missing_bearer_prefix_check"}:
223
+ return "Validate token signature, structure, and bearer header format before request authorization"
224
+ if item.test_name == "token_security_target_discovery":
225
+ return "Document authenticated endpoints in the API schema so token validation checks can run"
226
+ if item.test_name == "jwt_format_detection":
227
+ return "If JWT is expected, expose a standard JWT access token format or adjust scanner rules for opaque tokens"
228
+ if item.test_name == "privileged_endpoint_access_check":
229
+ return "Enforce role-based authorization and tenant scoping for privileged endpoints before returning protected data"
230
+ if item.test_name in {"upload_path_traversal_filename_check", "upload_absolute_path_filename_check"}:
231
+ return "Reject or normalize unsafe upload filenames before any filesystem, extraction, or downstream processing step"
232
+ if item.test_name == "file_upload_target_discovery":
233
+ return "Document multipart upload endpoints in the API schema so automated upload security checks can run"
234
+ if item.test_name == "file_upload_application_context_discovery":
235
+ return "Ensure an application exists for the authenticated tenant or expose an upload flow that can be exercised without prior application bootstrap"
236
+ if item.test_name in {"ssrf_private_address_rejection_check", "ssrf_metadata_address_rejection_check"}:
237
+ return "Validate and block internal, link-local, metadata, file-scheme, and other non-allowlisted outbound targets before persisting or using them"
238
+ if item.test_name == "ssrf_target_discovery":
239
+ return "Document URL-bearing mutation endpoints in the API schema so automated SSRF checks can run"
240
+ if item.test_name == "ssrf_instance_url_context_discovery":
241
+ return "Ensure a restorable outbound integration configuration exists in the test tenant before running mutation-based SSRF checks"
242
+ if item.test_name == "redirect_target_discovery":
243
+ return "Document redirect-style parameters in the API schema or add dedicated open redirect checks where user-controlled redirect targets exist"
244
+ if item.test_name == "burst_rate_limit_signal_check":
245
+ return "Add per-user, per-token, or per-IP throttling and protect expensive read endpoints with caching, quotas, or concurrency guards"
246
+ if item.test_name == "oversized_pagination_window_check":
247
+ return "Enforce strict maximums for page size, offsets, and time windows and reject abusive query shapes before expensive execution"
248
+ if item.test_name == "rate_limit_target_discovery":
249
+ return "Document high-value read endpoints in the API schema so automated abuse checks can run"
250
+ if item.test_name == "debug_route_public_exposure_check":
251
+ return "Remove or disable debug routes in production, or strictly gate them behind privileged auth and network controls"
252
+ if item.test_name == "debug_route_unauthenticated_access_check":
253
+ return "Require authentication and role-based authorization for all debug routes"
254
+ if item.test_name == "error_response_information_leak_check":
255
+ return "Return sanitized error payloads, disable verbose debug handlers, and keep stack traces and internal exception details server-side only"
256
+ if item.test_name == "error_leakage_target_discovery":
257
+ return "Document safe probe targets in API schema so automated error-leakage checks can run"
258
+ if item.test_name == "mass_assignment_sensitive_field_probe":
259
+ return "Use allowlisted writable fields on the server and ignore or reject sensitive ownership, role, and status properties from clients"
260
+ if item.test_name == "mass_assignment_target_discovery":
261
+ return "Document authenticated mutation endpoints in the API schema so automated mass assignment checks can run"
262
+ if item.test_name in {"required_field_validation_check", "wrong_type_validation_check", "unknown_field_handling_check"}:
263
+ return "Enforce request schema validation server-side and reject payloads that violate required fields, field types, or declared object structure"
264
+ if item.test_name == "schema_validation_target_discovery":
265
+ return "Document authenticated mutation endpoints in the API schema so automated schema validation checks can run"
266
+ if item.test_name == "cors_wildcard_check":
267
+ return "Replace wildcard CORS with strict allowlist of trusted origins"
268
+ if item.test_name.startswith("sqli_payload:"):
269
+ return "Use parameterized queries/ORM protections and server-side input validation"
270
+ if item.test_name.startswith("pentest_payload:"):
271
+ return "Validate and sanitize input, enforce output encoding, and harden command/path handling"
272
+ if item.http_status and item.http_status >= 500:
273
+ return "Review server logs using request/correlation IDs, add defensive validation, and fix exception handling"
274
+ if item.status == "error":
275
+ return "Investigate client/server connectivity, timeout, or protocol errors and stabilize request handling"
276
+ return "Investigate endpoint behavior and align with expected security controls"
277
+
278
+
279
+ CATEGORY_PRIORITY: dict[str, str] = {
280
+ "authz": "High",
281
+ "auth_robustness": "High",
282
+ "token_security": "High",
283
+ "jwt_security": "High",
284
+ "privilege_escalation": "High",
285
+ "sql_injection": "High",
286
+ "ssrf_and_redirects": "High",
287
+ "mass_assignment": "High",
288
+ "bola_matrix": "High",
289
+ "workflow_chains": "High",
290
+ "owasp": "Medium",
291
+ "pen_test": "Medium",
292
+ "contract_conformance": "Medium",
293
+ "schema_contract_and_validation": "Medium",
294
+ "file_upload_security": "Medium",
295
+ "error_leakage_and_debug_surface": "Medium",
296
+ "rate_limit_and_resource_abuse": "Medium",
297
+ "baseline": "Low",
298
+ "security_misc": "Low",
299
+ "soak_profile": "Low",
300
+ }
301
+
302
+ _PRIORITY_RANK = {"High": 0, "Medium": 1, "Low": 2}
303
+
304
+
305
+ def _category_priority(category: str) -> str:
306
+ return CATEGORY_PRIORITY.get(category, "Medium")
307
+
308
+
309
+ def _build_remediation_plan(failed_results: list[ExecutionResult]) -> list[str]:
310
+ by_category: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int))
311
+ for item in failed_results:
312
+ by_category[item.category][_remediation(item)] += 1
313
+
314
+ ordered_categories = sorted(
315
+ by_category.keys(),
316
+ key=lambda c: (_PRIORITY_RANK.get(_category_priority(c), 1), c),
317
+ )
318
+
319
+ lines: list[str] = ["## Remediation Plan", ""]
320
+ lines.append("| Priority | Category | Affected Tests | Recommended Fix |")
321
+ lines.append("|---|---|---|---|")
322
+ for category in ordered_categories:
323
+ priority = _category_priority(category)
324
+ for remediation, count in sorted(
325
+ by_category[category].items(), key=lambda kv: kv[1], reverse=True
326
+ ):
327
+ lines.append(
328
+ "| "
329
+ f"{priority} | "
330
+ f"{category} | "
331
+ f"{count} | "
332
+ f"{_escape_table_text(remediation)} |"
333
+ )
334
+ lines.append("")
335
+ return lines
336
+
337
+
338
+ def _escape_table_text(value: str) -> str:
339
+ return value.replace("|", "\\|").replace("\n", "<br>")
340
+
341
+
342
+ def _result_badge(status: str) -> str:
343
+ status_upper = status.upper()
344
+ if status_upper == "PASS":
345
+ return '<span style="color: green; font-weight: 600;">PASS</span>'
346
+ if status_upper == "FAIL":
347
+ return '<span style="color: red; font-weight: 600;">FAIL</span>'
348
+ if status_upper == "ERROR":
349
+ return '<span style="color: red; font-weight: 600;">ERROR</span>'
350
+ return status_upper
351
+
352
+
353
+ def write_reports(
354
+ output_dir: str,
355
+ summary: RunSummary,
356
+ results: list[ExecutionResult],
357
+ *,
358
+ json_out: str | None = None,
359
+ summary_md_out: str | None = None,
360
+ detail_md_out: str | None = None,
361
+ failures_md_out: str | None = None,
362
+ filename_prefix: str | None = None,
363
+ ) -> tuple[Path, Path, Path, Path]:
364
+ out = Path(output_dir)
365
+ out.mkdir(parents=True, exist_ok=True)
366
+
367
+ timestamp = datetime.now(UTC).strftime("%Y%m%d-%H%M%S")
368
+ prefix = ""
369
+ if filename_prefix:
370
+ safe_prefix = filename_prefix.strip()
371
+ if safe_prefix:
372
+ prefix = f"{safe_prefix}-"
373
+
374
+ json_path = Path(json_out) if json_out else out / f"{prefix}{timestamp}-api-security-report.json"
375
+ summary_md_path = (
376
+ Path(summary_md_out)
377
+ if summary_md_out
378
+ else out / f"{prefix}{timestamp}-api-security-summary.md"
379
+ )
380
+ detail_md_path = (
381
+ Path(detail_md_out)
382
+ if detail_md_out
383
+ else out / f"{prefix}{timestamp}-api-security-detail.md"
384
+ )
385
+ failures_md_path = (
386
+ Path(failures_md_out)
387
+ if failures_md_out
388
+ else out / f"{prefix}{timestamp}-api-security-failures.md"
389
+ )
390
+ json_path.parent.mkdir(parents=True, exist_ok=True)
391
+ summary_md_path.parent.mkdir(parents=True, exist_ok=True)
392
+ detail_md_path.parent.mkdir(parents=True, exist_ok=True)
393
+ failures_md_path.parent.mkdir(parents=True, exist_ok=True)
394
+
395
+ json_payload = {
396
+ "summary": asdict(summary),
397
+ "results": [asdict(item) for item in results],
398
+ }
399
+ json_path.write_text(json.dumps(json_payload, indent=2), encoding="utf-8")
400
+
401
+ summary_lines: list[str] = []
402
+ summary_lines.append("# Web App API Security Summary Report")
403
+ summary_lines.append("")
404
+ summary_lines.append(f"- Discovered endpoints: {summary.discovered_endpoints}")
405
+ summary_lines.append(f"- Executed tests: {summary.executed_tests}")
406
+ summary_lines.append(f"- Passed: {summary.passed}")
407
+ summary_lines.append(f"- Failed: {summary.failed}")
408
+ summary_lines.append(f"- Skipped: {summary.skipped}")
409
+ summary_lines.append(f"- Errors: {summary.errors}")
410
+ summary_lines.append("")
411
+ summary_lines.append("## By Category")
412
+ summary_lines.append("")
413
+
414
+ categories = sorted({r.category for r in results})
415
+ for category, counts in sorted(summary.by_category.items()):
416
+ total = (
417
+ counts.get("pass", 0)
418
+ + counts.get("fail", 0)
419
+ + counts.get("skipped", 0)
420
+ + counts.get("error", 0)
421
+ )
422
+ summary_lines.append(f"### {category}")
423
+ summary_lines.append(
424
+ f"- Total tests: {total}"
425
+ )
426
+ summary_lines.append(
427
+ f"- Tests passed: {counts.get('pass', 0)}"
428
+ )
429
+ summary_lines.append(
430
+ f"- Tests failed: {counts.get('fail', 0) + counts.get('error', 0)}"
431
+ )
432
+ summary_lines.append(
433
+ f"- {category}: pass={counts.get('pass', 0)}, fail={counts.get('fail', 0)}, "
434
+ f"skipped={counts.get('skipped', 0)}, error={counts.get('error', 0)}"
435
+ )
436
+ summary_lines.append("")
437
+
438
+ summary_md_path.write_text("\n".join(summary_lines), encoding="utf-8")
439
+
440
+ detail_lines: list[str] = []
441
+ detail_lines.append("# Web App API Security Detail Report")
442
+ detail_lines.append("")
443
+
444
+ for category in categories:
445
+ detail_lines.append(f"## Test: {category}")
446
+ detail_lines.append("")
447
+ detail_lines.append("| Test Description | Expected Behavior | Actual Behavior | Result | Remediation |")
448
+ detail_lines.append("|---|---|---|---|---|")
449
+ category_results = [r for r in results if r.category == category]
450
+ for item in category_results:
451
+ detail_lines.append(
452
+ "| "
453
+ f"{_escape_table_text(_test_description(item))} | "
454
+ f"{_escape_table_text(_expected_behavior(item))} | "
455
+ f"{_escape_table_text(_actual_behavior(item))} | "
456
+ f"{_result_badge(item.status)} | "
457
+ f"{_escape_table_text(_remediation(item))} |"
458
+ )
459
+ detail_lines.append("")
460
+
461
+ detail_md_path.write_text("\n".join(detail_lines), encoding="utf-8")
462
+
463
+ # Failures-only report — same table format as the detail report
464
+ failed_results = [r for r in results if r.status in {"fail", "error"}]
465
+ failed_categories = sorted({r.category for r in failed_results})
466
+ failures_lines: list[str] = []
467
+ failures_lines.append("# Web App API Security — Failures Report")
468
+ failures_lines.append("")
469
+ failures_lines.append(f"- Total failures: {len(failed_results)}")
470
+ failures_lines.append(f"- Affected categories: {len(failed_categories)}")
471
+ failures_lines.append("")
472
+ if not failed_results:
473
+ failures_lines.append("_No failures recorded in this run._")
474
+ failures_lines.append("")
475
+ else:
476
+ failures_lines.extend(_build_remediation_plan(failed_results))
477
+ for category in failed_categories:
478
+ failures_lines.append(f"## Test: {category}")
479
+ failures_lines.append("")
480
+ failures_lines.append("| Test Description | Expected Behavior | Actual Behavior | Result | Remediation |")
481
+ failures_lines.append("|---|---|---|---|---|")
482
+ for item in [r for r in failed_results if r.category == category]:
483
+ failures_lines.append(
484
+ "| "
485
+ f"{_escape_table_text(_test_description(item))} | "
486
+ f"{_escape_table_text(_expected_behavior(item))} | "
487
+ f"{_escape_table_text(_actual_behavior(item))} | "
488
+ f"{_result_badge(item.status)} | "
489
+ f"{_escape_table_text(_remediation(item))} |"
490
+ )
491
+ failures_lines.append("")
492
+ failures_md_path.write_text("\n".join(failures_lines), encoding="utf-8")
493
+
494
+ return json_path, summary_md_path, detail_md_path, failures_md_path
495
+
496
+
497
+ def write_junit_report(output_path: str, summary: RunSummary, results: list[ExecutionResult]) -> Path:
498
+ out_path = Path(output_path)
499
+ out_path.parent.mkdir(parents=True, exist_ok=True)
500
+
501
+ suite = ET.Element(
502
+ "testsuite",
503
+ {
504
+ "name": "apptest",
505
+ "tests": str(summary.executed_tests),
506
+ "failures": str(summary.failed),
507
+ "errors": str(summary.errors),
508
+ "skipped": str(summary.skipped),
509
+ },
510
+ )
511
+
512
+ for item in results:
513
+ test_name = f"{item.category}:{item.test_name}"
514
+ attrs = {
515
+ "classname": item.category,
516
+ "name": test_name,
517
+ "time": str((item.latency_ms or 0.0) / 1000.0),
518
+ }
519
+ case = ET.SubElement(suite, "testcase", attrs)
520
+
521
+ message = item.message or f"{item.method} {item.url}"
522
+ details = [f"status={item.status}"]
523
+ if item.http_status is not None:
524
+ details.append(f"http_status={item.http_status}")
525
+ if item.retries:
526
+ details.append(f"retries={item.retries}")
527
+ if item.response_snippet:
528
+ details.append(f"response_snippet={item.response_snippet}")
529
+
530
+ if item.status == "skipped":
531
+ ET.SubElement(case, "skipped", {"message": message}).text = "; ".join(details)
532
+ elif item.status == "fail":
533
+ ET.SubElement(case, "failure", {"message": message}).text = "; ".join(details)
534
+ elif item.status == "error":
535
+ ET.SubElement(case, "error", {"message": message}).text = "; ".join(details)
536
+
537
+ tree = ET.ElementTree(suite)
538
+ tree.write(out_path, encoding="utf-8", xml_declaration=True)
539
+ return out_path
540
+
541
+
542
+ def write_sarif_report(output_path: str, summary: RunSummary, results: list[ExecutionResult]) -> Path:
543
+ out_path = Path(output_path)
544
+ out_path.parent.mkdir(parents=True, exist_ok=True)
545
+
546
+ rules: dict[str, dict[str, object]] = {}
547
+ sarif_results: list[dict[str, object]] = []
548
+
549
+ for item in results:
550
+ if item.status not in {"fail", "error"}:
551
+ continue
552
+
553
+ rule_id = f"{item.category}:{item.test_name}"
554
+ if rule_id not in rules:
555
+ rules[rule_id] = {
556
+ "id": rule_id,
557
+ "name": item.test_name,
558
+ "shortDescription": {
559
+ "text": f"{item.category} - {item.test_name}",
560
+ },
561
+ "help": {
562
+ "text": "Investigate the endpoint behavior and apply recommended security controls.",
563
+ },
564
+ "properties": {
565
+ "category": item.category,
566
+ },
567
+ }
568
+
569
+ level = "error" if item.status == "error" else "warning"
570
+ message_bits = [f"{item.method} {item.url}"]
571
+ if item.http_status is not None:
572
+ message_bits.append(f"http_status={item.http_status}")
573
+ if item.message:
574
+ message_bits.append(item.message)
575
+ if item.response_snippet:
576
+ message_bits.append(f"response_snippet={item.response_snippet}")
577
+
578
+ sarif_results.append(
579
+ {
580
+ "ruleId": rule_id,
581
+ "level": level,
582
+ "message": {
583
+ "text": " | ".join(message_bits),
584
+ },
585
+ "properties": {
586
+ "category": item.category,
587
+ "status": item.status,
588
+ "service": item.service,
589
+ "method": item.method,
590
+ "url": item.url,
591
+ },
592
+ }
593
+ )
594
+
595
+ payload = {
596
+ "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
597
+ "version": "2.1.0",
598
+ "runs": [
599
+ {
600
+ "tool": {
601
+ "driver": {
602
+ "name": "apptest",
603
+ "version": "0.1.0",
604
+ "informationUri": "https://example.com/apptest",
605
+ "rules": list(rules.values()),
606
+ }
607
+ },
608
+ "results": sarif_results,
609
+ "invocations": [
610
+ {
611
+ "executionSuccessful": True,
612
+ "properties": {
613
+ "summary": {
614
+ "executed_tests": summary.executed_tests,
615
+ "passed": summary.passed,
616
+ "failed": summary.failed,
617
+ "skipped": summary.skipped,
618
+ "errors": summary.errors,
619
+ }
620
+ },
621
+ }
622
+ ],
623
+ }
624
+ ],
625
+ }
626
+
627
+ out_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
628
+ return out_path