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/cli.py ADDED
@@ -0,0 +1,1085 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ from concurrent.futures import ThreadPoolExecutor, as_completed
5
+ import os
6
+ from pathlib import Path
7
+ import re
8
+ import sys
9
+ from urllib.parse import urlparse
10
+
11
+ import httpx
12
+ from rich import print
13
+ import yaml
14
+
15
+ from app_test import __version__
16
+ from app_test.auth import login_and_get_token, serialize_bearer_token, serialize_header_auth
17
+ from app_test.categories import auth_robustness, authz, baseline, bola_matrix, contract_conformance, error_leakage_and_debug_surface, file_upload_security, jwt_security, mass_assignment, owasp, pen_test, privilege_escalation, rate_limit_and_resource_abuse, schema_contract_and_validation, security_misc, soak_profile, sql_injection, ssrf_and_redirects, token_security, workflow_chains
18
+ from app_test.config import AppConfig
19
+ from app_test.discovery import discover_endpoints
20
+ from app_test.models import EndpointSpec
21
+ from app_test.report import build_summary, write_junit_report, write_reports, write_sarif_report
22
+
23
+
24
+ ALL_CATEGORIES = {
25
+ "baseline",
26
+ "pen_test",
27
+ "sql_injection",
28
+ "owasp",
29
+ "security_misc",
30
+ "authz",
31
+ "auth_robustness",
32
+ "token_security",
33
+ "jwt_security",
34
+ "privilege_escalation",
35
+ "file_upload_security",
36
+ "ssrf_and_redirects",
37
+ "rate_limit_and_resource_abuse",
38
+ "error_leakage_and_debug_surface",
39
+ "mass_assignment",
40
+ "schema_contract_and_validation",
41
+ "contract_conformance",
42
+ "bola_matrix",
43
+ "workflow_chains",
44
+ "soak_profile",
45
+ }
46
+ PROFILE_CATEGORIES = {
47
+ "quick": {"baseline", "owasp", "security_misc", "authz", "auth_robustness", "token_security", "jwt_security", "privilege_escalation"},
48
+ "standard": set(ALL_CATEGORIES),
49
+ "strict": set(ALL_CATEGORIES),
50
+ }
51
+ PROFILE_INCLUDE_UNSAFE_DEFAULT = {
52
+ "quick": False,
53
+ "standard": False,
54
+ "strict": True,
55
+ }
56
+ DEFAULT_CONFIG_FILE = "apptest.yaml"
57
+ DEFAULT_CONFIG_TEMPLATE = """base_url: https://your-target.example
58
+ auth:
59
+ type: bearer
60
+ header: "Authorization: Bearer ${TARGET_TOKEN}"
61
+ profile: quick
62
+ timeout: 20
63
+ output_dir: reports
64
+ include_unsafe: false
65
+ unsafe_categories: all
66
+ categories: all
67
+ soak_samples: 12
68
+ soak_max_5xx_rate: 0.15
69
+ soak_max_exception_rate: 0.05
70
+ soak_max_p95_ms: 2500
71
+ """
72
+
73
+
74
+ def parse_args() -> argparse.Namespace:
75
+ parser = argparse.ArgumentParser(description="Web app API security test runner")
76
+ parser.add_argument(
77
+ "--config",
78
+ default=None,
79
+ help=(
80
+ f"Path to config YAML file (default auto-loads ./{DEFAULT_CONFIG_FILE} when present)"
81
+ ),
82
+ )
83
+ parser.add_argument(
84
+ "--base-url",
85
+ default=None,
86
+ help="Target app URL (or env APPTEST_BASE_URL)",
87
+ )
88
+ parser.add_argument(
89
+ "--targets",
90
+ default=None,
91
+ help="Comma-separated target app URLs. When set, runs all targets in parallel.",
92
+ )
93
+ parser.add_argument(
94
+ "--api-key",
95
+ default=None,
96
+ help="API key used as Bearer token (or env APPTEST_API_KEY); skips username/password login",
97
+ )
98
+ parser.add_argument(
99
+ "--username",
100
+ default=None,
101
+ help="Username/email (or env APPTEST_USERNAME; ignored when --api-key is set)",
102
+ )
103
+ parser.add_argument(
104
+ "--password",
105
+ default=None,
106
+ help="Password (or env APPTEST_PASSWORD; ignored when --api-key is set)",
107
+ )
108
+ parser.add_argument(
109
+ "--request-header",
110
+ action="append",
111
+ default=None,
112
+ help=(
113
+ "Additional request header in the form 'Header-Name: value'. "
114
+ "Can be passed multiple times. Useful for browser-copied auth/session headers."
115
+ ),
116
+ )
117
+ parser.add_argument(
118
+ "--cookie-header",
119
+ default=None,
120
+ help="Raw Cookie header value copied from the browser (without the 'Cookie:' prefix)",
121
+ )
122
+ parser.add_argument("--timeout", default=None, type=float, help="HTTP timeout in seconds")
123
+ parser.add_argument("--output-dir", default=None, help="Directory for reports")
124
+ parser.add_argument(
125
+ "--include-unsafe",
126
+ action=argparse.BooleanOptionalAction,
127
+ default=None,
128
+ help="Allow POST/PUT/PATCH/DELETE endpoint execution",
129
+ )
130
+ parser.add_argument(
131
+ "--insecure",
132
+ action=argparse.BooleanOptionalAction,
133
+ default=None,
134
+ help="Disable TLS certificate verification",
135
+ )
136
+ parser.add_argument(
137
+ "--unsafe-categories",
138
+ default=None,
139
+ help=(
140
+ "Comma-separated categories allowed to run unsafe methods when --include-unsafe is set. "
141
+ "Use 'all' or a subset of: baseline,pen_test,sql_injection,owasp,security_misc,authz,auth_robustness,token_security,jwt_security,privilege_escalation,file_upload_security,ssrf_and_redirects,rate_limit_and_resource_abuse,error_leakage_and_debug_surface,mass_assignment,schema_contract_and_validation,contract_conformance,bola_matrix,workflow_chains,soak_profile"
142
+ ),
143
+ )
144
+ parser.add_argument(
145
+ "--profile",
146
+ choices=["quick", "standard", "strict"],
147
+ default=None,
148
+ help=(
149
+ "Run profile presets. quick runs a reduced category set in safe mode; "
150
+ "standard runs all categories in safe mode; strict runs all categories with unsafe enabled"
151
+ ),
152
+ )
153
+ parser.add_argument(
154
+ "--fail-on-findings",
155
+ action="store_true",
156
+ help="Exit with non-zero status when failed or error findings are present",
157
+ )
158
+ parser.add_argument(
159
+ "--max-failed",
160
+ default=None,
161
+ type=int,
162
+ help="Maximum allowed failed findings before exiting non-zero",
163
+ )
164
+ parser.add_argument(
165
+ "--max-errors",
166
+ default=None,
167
+ type=int,
168
+ help="Maximum allowed error findings before exiting non-zero",
169
+ )
170
+ parser.add_argument(
171
+ "--junit-out",
172
+ default=None,
173
+ help="Optional output path for JUnit XML report",
174
+ )
175
+ parser.add_argument(
176
+ "--sarif-out",
177
+ default=None,
178
+ help="Optional output path for SARIF JSON report",
179
+ )
180
+ parser.add_argument(
181
+ "--categories",
182
+ default=None,
183
+ help=(
184
+ "Comma-separated categories to run. Use 'all' or a subset of: "
185
+ "baseline,pen_test,sql_injection,owasp,security_misc,authz,auth_robustness,token_security,jwt_security,privilege_escalation,file_upload_security,ssrf_and_redirects,rate_limit_and_resource_abuse,error_leakage_and_debug_surface,mass_assignment,schema_contract_and_validation,contract_conformance,bola_matrix,workflow_chains,soak_profile"
186
+ ),
187
+ )
188
+ parser.add_argument(
189
+ "--json-out",
190
+ default=None,
191
+ help="Optional output path for JSON report",
192
+ )
193
+ parser.add_argument(
194
+ "--md-summary-out",
195
+ default=None,
196
+ help="Optional output path for Markdown summary report",
197
+ )
198
+ parser.add_argument(
199
+ "--md-detail-out",
200
+ default=None,
201
+ help="Optional output path for Markdown detail report",
202
+ )
203
+ parser.add_argument(
204
+ "--md-failures-out",
205
+ default=None,
206
+ help="Optional output path for Markdown failures-only report",
207
+ )
208
+ parser.add_argument(
209
+ "--soak-samples",
210
+ default=None,
211
+ type=int,
212
+ help="Override soak_profile sample count per endpoint (default: 12)",
213
+ )
214
+ parser.add_argument(
215
+ "--soak-max-5xx-rate",
216
+ default=None,
217
+ type=float,
218
+ help="Override soak_profile maximum allowed 5xx rate (0.0-1.0, default: 0.15)",
219
+ )
220
+ parser.add_argument(
221
+ "--soak-max-exception-rate",
222
+ default=None,
223
+ type=float,
224
+ help="Override soak_profile maximum allowed exception rate (0.0-1.0, default: 0.05)",
225
+ )
226
+ parser.add_argument(
227
+ "--soak-max-p95-ms",
228
+ default=None,
229
+ type=float,
230
+ help="Override soak_profile maximum allowed p95 latency in ms (default: 2500)",
231
+ )
232
+ parser.add_argument(
233
+ "--openapi-url",
234
+ default=None,
235
+ help=(
236
+ "Explicit URL to an OpenAPI JSON/YAML spec. When set, endpoint discovery uses "
237
+ "only this URL (no probing). Useful for targets that expose their spec at a "
238
+ "non-standard path."
239
+ ),
240
+ )
241
+ parser.add_argument(
242
+ "--seed-endpoint",
243
+ action="append",
244
+ default=None,
245
+ help=(
246
+ "Manual endpoint seed in the form 'METHOD:/path'. Can be passed multiple times. "
247
+ "Useful when the target does not expose an OpenAPI spec. Example: "
248
+ "--seed-endpoint GET:/api/billday/v1/invoices.json"
249
+ ),
250
+ )
251
+ return parser.parse_args()
252
+
253
+
254
+ def _load_config_data(args: argparse.Namespace) -> tuple[dict[str, object], Path | None]:
255
+ candidate = Path(args.config) if args.config else Path(DEFAULT_CONFIG_FILE)
256
+ if not args.config and not candidate.exists():
257
+ return {}, None
258
+ if not candidate.exists():
259
+ raise SystemExit(f"Config file not found: {candidate}")
260
+
261
+ raw = yaml.safe_load(candidate.read_text(encoding="utf-8"))
262
+ if raw is None:
263
+ return {}, candidate
264
+ if not isinstance(raw, dict):
265
+ raise SystemExit(f"Config file must contain a top-level mapping/object: {candidate}")
266
+ return raw, candidate
267
+
268
+
269
+ def _resolve_value(cli_value: object, env_key: str, config_data: dict[str, object], config_key: str, default: object) -> object:
270
+ if cli_value is not None:
271
+ return cli_value
272
+ env_value = os.getenv(env_key)
273
+ if env_value is not None:
274
+ return env_value
275
+ if config_key in config_data and config_data[config_key] is not None:
276
+ return config_data[config_key]
277
+ return default
278
+
279
+
280
+ def _to_bool(value: object, *, label: str) -> bool:
281
+ if isinstance(value, bool):
282
+ return value
283
+ if isinstance(value, str):
284
+ lowered = value.strip().lower()
285
+ if lowered in {"1", "true", "yes", "y", "on"}:
286
+ return True
287
+ if lowered in {"0", "false", "no", "n", "off"}:
288
+ return False
289
+ raise SystemExit(f"Invalid boolean value for {label}: {value!r}")
290
+
291
+
292
+ def _expand_env_vars(value: object) -> object:
293
+ if isinstance(value, str):
294
+ return os.path.expandvars(value)
295
+ return value
296
+
297
+
298
+ def _parse_header_pair(value: object, *, label: str) -> tuple[str, str]:
299
+ if not isinstance(value, str):
300
+ raise SystemExit(f"Invalid {label}: expected string in the form 'Header-Name: value'")
301
+ expanded = str(_expand_env_vars(value)).strip()
302
+ if ":" not in expanded:
303
+ raise SystemExit(f"Invalid {label}: expected 'Header-Name: value'")
304
+ name, raw_header_value = expanded.split(":", 1)
305
+ header_name = name.strip()
306
+ header_value = raw_header_value.strip()
307
+ if not header_name or not header_value:
308
+ raise SystemExit(f"Invalid {label}: header name and value are required")
309
+ return header_name, header_value
310
+
311
+
312
+ def _parse_header_map(value: object, *, label: str) -> dict[str, str]:
313
+ if value is None:
314
+ return {}
315
+
316
+ if isinstance(value, str) and value == "":
317
+ return {}
318
+
319
+ if isinstance(value, dict):
320
+ result: dict[str, str] = {}
321
+ for key, raw_value in value.items():
322
+ header_name = str(_expand_env_vars(key)).strip()
323
+ header_value = str(_expand_env_vars(raw_value)).strip()
324
+ if not header_name or not header_value:
325
+ raise SystemExit(f"Invalid {label}: header name and value are required")
326
+ result[header_name] = header_value
327
+ return result
328
+
329
+ if isinstance(value, (list, tuple)):
330
+ result: dict[str, str] = {}
331
+ for index, item in enumerate(value):
332
+ header_name, header_value = _parse_header_pair(item, label=f"{label}[{index}]")
333
+ result[header_name] = header_value
334
+ return result
335
+
336
+ header_name, header_value = _parse_header_pair(value, label=label)
337
+ return {header_name: header_value}
338
+
339
+
340
+ def _build_config(args: argparse.Namespace, config_data: dict[str, object]) -> AppConfig:
341
+ base_url = _expand_env_vars(_resolve_value(args.base_url, "APPTEST_BASE_URL", config_data, "base_url", "https://your-target.example"))
342
+ api_key = _expand_env_vars(_resolve_value(args.api_key, "APPTEST_API_KEY", config_data, "api_key", None))
343
+ username = _expand_env_vars(_resolve_value(args.username, "APPTEST_USERNAME", config_data, "username", "your-user@example.com"))
344
+ password = _expand_env_vars(_resolve_value(args.password, "APPTEST_PASSWORD", config_data, "password", "your-password"))
345
+
346
+ auth_data_raw = config_data.get("auth")
347
+ if auth_data_raw is not None and not isinstance(auth_data_raw, dict):
348
+ raise SystemExit("Invalid config: 'auth' must be a mapping/object")
349
+ auth_data = auth_data_raw if isinstance(auth_data_raw, dict) else {}
350
+
351
+ auth_type_value = _resolve_value(None, "APPTEST_AUTH_TYPE", auth_data, "type", "auto")
352
+ auth_type = str(_expand_env_vars(auth_type_value)).strip().lower()
353
+ if auth_type == "":
354
+ auth_type = "auto"
355
+ allowed_auth_types = {"auto", "bearer", "api_key", "basic", "none"}
356
+ if auth_type not in allowed_auth_types:
357
+ raise SystemExit(
358
+ f"Invalid auth.type: {auth_type}. "
359
+ "Allowed values: auto, bearer, api_key, basic, none"
360
+ )
361
+
362
+ auth_header_name: str | None = None
363
+ auth_header_value: str | None = None
364
+ default_headers: dict[str, str] = {}
365
+ basic_username: str | None = None
366
+ basic_password: str | None = None
367
+
368
+ if auth_type in {"bearer", "api_key"}:
369
+ header_value = _resolve_value(None, "APPTEST_AUTH_HEADER", auth_data, "header", None)
370
+ if header_value in {None, ""}:
371
+ raise SystemExit("auth.header is required when auth.type is bearer or api_key")
372
+ auth_header_name, auth_header_value = _parse_header_pair(header_value, label="auth.header")
373
+ elif auth_type == "basic":
374
+ basic_username_value = _resolve_value(None, "APPTEST_AUTH_USERNAME", auth_data, "username", username)
375
+ basic_password_value = _resolve_value(None, "APPTEST_AUTH_PASSWORD", auth_data, "password", password)
376
+ basic_username = str(_expand_env_vars(basic_username_value)).strip()
377
+ basic_password = str(_expand_env_vars(basic_password_value)).strip()
378
+ if not basic_username or not basic_password:
379
+ raise SystemExit("auth.username and auth.password are required when auth.type is basic")
380
+
381
+ default_headers.update(
382
+ _parse_header_map(auth_data.get("extra_headers"), label="auth.extra_headers")
383
+ )
384
+ default_headers.update(
385
+ _parse_header_map(args.request_header, label="--request-header")
386
+ )
387
+
388
+ cookie_header = _resolve_value(
389
+ args.cookie_header,
390
+ "APPTEST_COOKIE_HEADER",
391
+ auth_data,
392
+ "cookie_header",
393
+ None,
394
+ )
395
+ if cookie_header not in {None, ""}:
396
+ default_headers["Cookie"] = str(_expand_env_vars(cookie_header)).strip()
397
+
398
+ timeout_seconds = float(_resolve_value(args.timeout, "APPTEST_TIMEOUT", config_data, "timeout", 20.0))
399
+ output_dir = str(_resolve_value(args.output_dir, "APPTEST_OUTPUT_DIR", config_data, "output_dir", "reports"))
400
+ include_unsafe = _to_bool(
401
+ _resolve_value(args.include_unsafe, "APPTEST_INCLUDE_UNSAFE", config_data, "include_unsafe", False),
402
+ label="include_unsafe",
403
+ )
404
+ insecure = _to_bool(
405
+ _resolve_value(args.insecure, "APPTEST_INSECURE", config_data, "insecure", False),
406
+ label="insecure",
407
+ )
408
+
409
+ return AppConfig(
410
+ base_url=str(base_url),
411
+ auth_type=auth_type,
412
+ auth_header_name=auth_header_name,
413
+ auth_header_value=auth_header_value,
414
+ default_headers=default_headers,
415
+ basic_username=basic_username,
416
+ basic_password=basic_password,
417
+ username=str(username),
418
+ password=str(password),
419
+ api_key=None if api_key in {None, ""} else str(api_key),
420
+ timeout_seconds=timeout_seconds,
421
+ include_unsafe=include_unsafe,
422
+ output_dir=output_dir,
423
+ verify_tls=not insecure,
424
+ )
425
+
426
+
427
+ def _validate_threshold_args(args: argparse.Namespace) -> None:
428
+ if args.max_failed is not None and args.max_failed < 0:
429
+ raise SystemExit("--max-failed must be >= 0")
430
+ if args.max_errors is not None and args.max_errors < 0:
431
+ raise SystemExit("--max-errors must be >= 0")
432
+
433
+
434
+ def _validate_soak_tuning(
435
+ *,
436
+ soak_samples: int | None,
437
+ soak_max_5xx_rate: float | None,
438
+ soak_max_exception_rate: float | None,
439
+ soak_max_p95_ms: float | None,
440
+ ) -> None:
441
+ if soak_samples is not None and soak_samples <= 0:
442
+ raise SystemExit("soak_samples must be > 0")
443
+ if soak_max_5xx_rate is not None and not (0.0 <= soak_max_5xx_rate <= 1.0):
444
+ raise SystemExit("soak_max_5xx_rate must be between 0.0 and 1.0")
445
+ if soak_max_exception_rate is not None and not (0.0 <= soak_max_exception_rate <= 1.0):
446
+ raise SystemExit("soak_max_exception_rate must be between 0.0 and 1.0")
447
+ if soak_max_p95_ms is not None and soak_max_p95_ms <= 0:
448
+ raise SystemExit("soak_max_p95_ms must be > 0")
449
+
450
+
451
+ def _resolve_optional_int(value: object, *, label: str) -> int | None:
452
+ if value in {None, ""}:
453
+ return None
454
+ try:
455
+ return int(value)
456
+ except Exception as exc:
457
+ raise SystemExit(f"Invalid integer value for {label}: {value!r}") from exc
458
+
459
+
460
+ def _resolve_optional_float(value: object, *, label: str) -> float | None:
461
+ if value in {None, ""}:
462
+ return None
463
+ try:
464
+ return float(value)
465
+ except Exception as exc:
466
+ raise SystemExit(f"Invalid float value for {label}: {value!r}") from exc
467
+
468
+
469
+ def _handle_init_command(argv: list[str]) -> int | None:
470
+ if len(argv) < 2 or argv[1] != "init":
471
+ return None
472
+
473
+ parser = argparse.ArgumentParser(description="Initialize apptest configuration")
474
+ parser.add_argument(
475
+ "--path",
476
+ default=DEFAULT_CONFIG_FILE,
477
+ help=f"Path for generated config file (default: {DEFAULT_CONFIG_FILE})",
478
+ )
479
+ parser.add_argument(
480
+ "--force",
481
+ action="store_true",
482
+ help="Overwrite config file if it already exists",
483
+ )
484
+ init_args = parser.parse_args(argv[2:])
485
+
486
+ output_path = Path(init_args.path)
487
+ if output_path.exists() and not init_args.force:
488
+ print(
489
+ f"[red]Config already exists:[/red] {output_path}. "
490
+ f"Use 'apptest init --force' to overwrite."
491
+ )
492
+ return 1
493
+
494
+ output_path.parent.mkdir(parents=True, exist_ok=True)
495
+ output_path.write_text(DEFAULT_CONFIG_TEMPLATE, encoding="utf-8")
496
+ print(f"[green]Created config:[/green] {output_path}")
497
+ return 0
498
+
499
+
500
+ def _parse_targets_arg(raw_targets: str | None) -> list[str]:
501
+ if raw_targets in {None, ""}:
502
+ return []
503
+ targets = [part.strip() for part in str(raw_targets).split(",") if part.strip()]
504
+ if not targets:
505
+ raise SystemExit("--targets provided but no valid URLs were found")
506
+ return targets
507
+
508
+
509
+ def _target_report_prefix(base_url: str) -> str:
510
+ parsed = urlparse(base_url)
511
+ candidate = parsed.netloc or parsed.path or base_url
512
+ candidate = candidate.strip().lower()
513
+ if not candidate:
514
+ candidate = "target"
515
+ return re.sub(r"[^a-z0-9._-]+", "-", candidate).strip("-") or "target"
516
+
517
+
518
+ def _parse_seed_endpoints(raw_values: object) -> list[EndpointSpec]:
519
+ if raw_values is None:
520
+ return []
521
+
522
+ values = raw_values if isinstance(raw_values, list) else [raw_values]
523
+ endpoints: list[EndpointSpec] = []
524
+ for index, raw_value in enumerate(values):
525
+ if not isinstance(raw_value, str) or not raw_value.strip():
526
+ raise SystemExit(f"Invalid --seed-endpoint[{index}]: expected 'METHOD:/path'")
527
+ value = raw_value.strip()
528
+ if ":" not in value:
529
+ raise SystemExit(
530
+ f"Invalid --seed-endpoint[{index}]: expected 'METHOD:/path', got {value!r}"
531
+ )
532
+ method, path = value.split(":", 1)
533
+ method = method.strip().upper()
534
+ path = path.strip()
535
+ if method.lower() not in {"get", "post", "put", "patch", "delete", "head", "options"}:
536
+ raise SystemExit(
537
+ f"Invalid --seed-endpoint[{index}]: unsupported method {method!r}"
538
+ )
539
+ if not path.startswith("/"):
540
+ raise SystemExit(
541
+ f"Invalid --seed-endpoint[{index}]: path must start with '/', got {path!r}"
542
+ )
543
+ endpoints.append(
544
+ EndpointSpec(
545
+ service="manual",
546
+ service_prefix="",
547
+ path=path,
548
+ method=method,
549
+ operation_id=f"manual_{method.lower()}_{path.strip('/').replace('/', '_').replace('.', '_') or 'root'}",
550
+ requires_auth=True,
551
+ )
552
+ )
553
+ return endpoints
554
+
555
+
556
+ def main() -> int:
557
+ init_exit_code = _handle_init_command(sys.argv)
558
+ if init_exit_code is not None:
559
+ return init_exit_code
560
+
561
+ args = parse_args()
562
+ _validate_threshold_args(args)
563
+ config_data, config_path = _load_config_data(args)
564
+
565
+ if args.targets and any([
566
+ args.json_out,
567
+ args.md_summary_out,
568
+ args.md_detail_out,
569
+ args.md_failures_out,
570
+ args.junit_out,
571
+ args.sarif_out,
572
+ ]):
573
+ raise SystemExit(
574
+ "Explicit output path flags (--json-out/--md-*/--junit-out/--sarif-out) are not supported with --targets"
575
+ )
576
+
577
+ profile_value = _resolve_value(args.profile, "APPTEST_PROFILE", config_data, "profile", None)
578
+ profile = None if profile_value in {None, ""} else str(profile_value).strip().lower()
579
+ if profile and profile not in PROFILE_CATEGORIES:
580
+ raise SystemExit(f"Invalid profile: {profile}. Allowed values: quick, standard, strict")
581
+
582
+ selected_categories = set(ALL_CATEGORIES)
583
+ default_include_unsafe_from_profile = None
584
+ if profile:
585
+ selected_categories = set(PROFILE_CATEGORIES[profile])
586
+ if args.include_unsafe is None:
587
+ default_include_unsafe_from_profile = PROFILE_INCLUDE_UNSAFE_DEFAULT[profile]
588
+
589
+ categories_raw = _resolve_value(
590
+ args.categories,
591
+ "APPTEST_CATEGORIES",
592
+ config_data,
593
+ "categories",
594
+ None,
595
+ )
596
+ categories_specified = categories_raw not in {None, ""}
597
+ if categories_specified:
598
+ categories_arg = str(categories_raw).strip().lower()
599
+ if categories_arg == "all":
600
+ selected_categories = set(ALL_CATEGORIES)
601
+ else:
602
+ selected_categories = {
603
+ part.strip()
604
+ for part in categories_arg.split(",")
605
+ if part.strip()
606
+ }
607
+ invalid = selected_categories - ALL_CATEGORIES
608
+ if invalid:
609
+ raise SystemExit(
610
+ f"Invalid values for --categories: {', '.join(sorted(invalid))}. "
611
+ f"Allowed values: {', '.join(sorted(ALL_CATEGORIES))}, all"
612
+ )
613
+
614
+ unsafe_categories_raw = _resolve_value(
615
+ args.unsafe_categories,
616
+ "APPTEST_UNSAFE_CATEGORIES",
617
+ config_data,
618
+ "unsafe_categories",
619
+ "all",
620
+ )
621
+ unsafe_categories_arg = str(unsafe_categories_raw).strip().lower()
622
+ if unsafe_categories_arg == "all":
623
+ unsafe_categories = set(ALL_CATEGORIES)
624
+ else:
625
+ unsafe_categories = {
626
+ part.strip()
627
+ for part in unsafe_categories_arg.split(",")
628
+ if part.strip()
629
+ }
630
+ invalid = unsafe_categories - ALL_CATEGORIES
631
+ if invalid:
632
+ raise SystemExit(
633
+ f"Invalid values for --unsafe-categories: {', '.join(sorted(invalid))}. "
634
+ f"Allowed values: {', '.join(sorted(ALL_CATEGORIES))}, all"
635
+ )
636
+
637
+ soak_samples = _resolve_optional_int(
638
+ _resolve_value(args.soak_samples, "APPTEST_SOAK_SAMPLES", config_data, "soak_samples", None),
639
+ label="soak_samples",
640
+ )
641
+ soak_max_5xx_rate = _resolve_optional_float(
642
+ _resolve_value(
643
+ args.soak_max_5xx_rate,
644
+ "APPTEST_SOAK_MAX_5XX_RATE",
645
+ config_data,
646
+ "soak_max_5xx_rate",
647
+ None,
648
+ ),
649
+ label="soak_max_5xx_rate",
650
+ )
651
+ soak_max_exception_rate = _resolve_optional_float(
652
+ _resolve_value(
653
+ args.soak_max_exception_rate,
654
+ "APPTEST_SOAK_MAX_EXCEPTION_RATE",
655
+ config_data,
656
+ "soak_max_exception_rate",
657
+ None,
658
+ ),
659
+ label="soak_max_exception_rate",
660
+ )
661
+ soak_max_p95_ms = _resolve_optional_float(
662
+ _resolve_value(
663
+ args.soak_max_p95_ms,
664
+ "APPTEST_SOAK_MAX_P95_MS",
665
+ config_data,
666
+ "soak_max_p95_ms",
667
+ None,
668
+ ),
669
+ label="soak_max_p95_ms",
670
+ )
671
+ _validate_soak_tuning(
672
+ soak_samples=soak_samples,
673
+ soak_max_5xx_rate=soak_max_5xx_rate,
674
+ soak_max_exception_rate=soak_max_exception_rate,
675
+ soak_max_p95_ms=soak_max_p95_ms,
676
+ )
677
+ seed_endpoints = _parse_seed_endpoints(getattr(args, "seed_endpoint", None))
678
+
679
+ def execute_for_base_url(base_url_override: str | None):
680
+ config = _build_config(args, config_data)
681
+ if default_include_unsafe_from_profile is not None:
682
+ config.include_unsafe = default_include_unsafe_from_profile
683
+ if base_url_override:
684
+ config.base_url = base_url_override
685
+
686
+ def allow_unsafe_for(category: str) -> bool:
687
+ return config.include_unsafe and category in unsafe_categories
688
+
689
+ client_auth: httpx.Auth | None = None
690
+ if config.auth_type == "basic" and not config.api_key:
691
+ if not config.basic_username or not config.basic_password:
692
+ raise SystemExit("basic auth selected but username/password are not configured")
693
+ client_auth = httpx.BasicAuth(config.basic_username, config.basic_password)
694
+
695
+ with httpx.Client(
696
+ timeout=config.timeout_seconds,
697
+ verify=config.verify_tls,
698
+ auth=client_auth,
699
+ headers=config.default_headers,
700
+ ) as client:
701
+ if config.api_key:
702
+ # --api-key always takes precedence over auth.type from config
703
+ token = serialize_bearer_token(config.api_key)
704
+ elif config.auth_type in {"bearer", "api_key"}:
705
+ if not config.auth_header_name or not config.auth_header_value:
706
+ raise SystemExit("auth.header is required when auth.type is bearer or api_key")
707
+ token = serialize_header_auth(config.auth_header_name, config.auth_header_value)
708
+ elif config.auth_type == "basic":
709
+ token = None
710
+ elif config.auth_type == "none":
711
+ token = None
712
+ else:
713
+ token = serialize_bearer_token(
714
+ login_and_get_token(
715
+ client=client,
716
+ base_url=config.base_url,
717
+ username=config.username,
718
+ password=config.password,
719
+ )
720
+ )
721
+
722
+ endpoints = discover_endpoints(
723
+ client=client,
724
+ base_url=config.base_url,
725
+ openapi_url=getattr(args, "openapi_url", None),
726
+ token=token,
727
+ )
728
+ if seed_endpoints:
729
+ deduped_seeded: dict[tuple[str, str], EndpointSpec] = {
730
+ (endpoint.method, endpoint.path): endpoint for endpoint in endpoints
731
+ }
732
+ for endpoint in seed_endpoints:
733
+ deduped_seeded[(endpoint.method, endpoint.path)] = endpoint
734
+ endpoints = list(deduped_seeded.values())
735
+
736
+ all_results = []
737
+ if "baseline" in selected_categories:
738
+ all_results.extend(
739
+ baseline.run(
740
+ client=client,
741
+ base_url=config.base_url,
742
+ token=token,
743
+ endpoints=endpoints,
744
+ include_unsafe=allow_unsafe_for("baseline"),
745
+ )
746
+ )
747
+ if "pen_test" in selected_categories:
748
+ all_results.extend(
749
+ pen_test.run(
750
+ client=client,
751
+ base_url=config.base_url,
752
+ token=token,
753
+ endpoints=endpoints,
754
+ include_unsafe=allow_unsafe_for("pen_test"),
755
+ )
756
+ )
757
+ if "sql_injection" in selected_categories:
758
+ all_results.extend(
759
+ sql_injection.run(
760
+ client=client,
761
+ base_url=config.base_url,
762
+ token=token,
763
+ endpoints=endpoints,
764
+ include_unsafe=allow_unsafe_for("sql_injection"),
765
+ )
766
+ )
767
+ if "owasp" in selected_categories:
768
+ all_results.extend(
769
+ owasp.run(
770
+ client=client,
771
+ base_url=config.base_url,
772
+ token=token,
773
+ endpoints=endpoints,
774
+ include_unsafe=allow_unsafe_for("owasp"),
775
+ )
776
+ )
777
+ if "security_misc" in selected_categories:
778
+ all_results.extend(
779
+ security_misc.run(
780
+ client=client,
781
+ base_url=config.base_url,
782
+ token=token,
783
+ endpoints=endpoints,
784
+ include_unsafe=allow_unsafe_for("security_misc"),
785
+ )
786
+ )
787
+ if "authz" in selected_categories:
788
+ all_results.extend(
789
+ authz.run(
790
+ client=client,
791
+ base_url=config.base_url,
792
+ token=token,
793
+ endpoints=endpoints,
794
+ include_unsafe=allow_unsafe_for("authz"),
795
+ )
796
+ )
797
+ if "auth_robustness" in selected_categories:
798
+ all_results.extend(
799
+ auth_robustness.run(
800
+ client=client,
801
+ base_url=config.base_url,
802
+ token=token,
803
+ endpoints=endpoints,
804
+ include_unsafe=allow_unsafe_for("auth_robustness"),
805
+ )
806
+ )
807
+ if "token_security" in selected_categories:
808
+ all_results.extend(
809
+ token_security.run(
810
+ client=client,
811
+ base_url=config.base_url,
812
+ token=token,
813
+ endpoints=endpoints,
814
+ include_unsafe=allow_unsafe_for("token_security"),
815
+ )
816
+ )
817
+ if "jwt_security" in selected_categories:
818
+ all_results.extend(
819
+ jwt_security.run(
820
+ client=client,
821
+ base_url=config.base_url,
822
+ token=token,
823
+ endpoints=endpoints,
824
+ include_unsafe=allow_unsafe_for("jwt_security"),
825
+ )
826
+ )
827
+ if "privilege_escalation" in selected_categories:
828
+ all_results.extend(
829
+ privilege_escalation.run(
830
+ client=client,
831
+ base_url=config.base_url,
832
+ token=token,
833
+ endpoints=endpoints,
834
+ include_unsafe=allow_unsafe_for("privilege_escalation"),
835
+ )
836
+ )
837
+ if "file_upload_security" in selected_categories:
838
+ all_results.extend(
839
+ file_upload_security.run(
840
+ client=client,
841
+ base_url=config.base_url,
842
+ token=token,
843
+ endpoints=endpoints,
844
+ include_unsafe=allow_unsafe_for("file_upload_security"),
845
+ )
846
+ )
847
+ if "ssrf_and_redirects" in selected_categories:
848
+ all_results.extend(
849
+ ssrf_and_redirects.run(
850
+ client=client,
851
+ base_url=config.base_url,
852
+ token=token,
853
+ endpoints=endpoints,
854
+ include_unsafe=allow_unsafe_for("ssrf_and_redirects"),
855
+ )
856
+ )
857
+ if "rate_limit_and_resource_abuse" in selected_categories:
858
+ all_results.extend(
859
+ rate_limit_and_resource_abuse.run(
860
+ client=client,
861
+ base_url=config.base_url,
862
+ token=token,
863
+ endpoints=endpoints,
864
+ include_unsafe=allow_unsafe_for("rate_limit_and_resource_abuse"),
865
+ )
866
+ )
867
+ if "error_leakage_and_debug_surface" in selected_categories:
868
+ all_results.extend(
869
+ error_leakage_and_debug_surface.run(
870
+ client=client,
871
+ base_url=config.base_url,
872
+ token=token,
873
+ endpoints=endpoints,
874
+ include_unsafe=allow_unsafe_for("error_leakage_and_debug_surface"),
875
+ )
876
+ )
877
+ if "mass_assignment" in selected_categories:
878
+ all_results.extend(
879
+ mass_assignment.run(
880
+ client=client,
881
+ base_url=config.base_url,
882
+ token=token,
883
+ endpoints=endpoints,
884
+ include_unsafe=allow_unsafe_for("mass_assignment"),
885
+ )
886
+ )
887
+ if "schema_contract_and_validation" in selected_categories:
888
+ all_results.extend(
889
+ schema_contract_and_validation.run(
890
+ client=client,
891
+ base_url=config.base_url,
892
+ token=token,
893
+ endpoints=endpoints,
894
+ include_unsafe=allow_unsafe_for("schema_contract_and_validation"),
895
+ )
896
+ )
897
+ if "contract_conformance" in selected_categories:
898
+ all_results.extend(
899
+ contract_conformance.run(
900
+ client=client,
901
+ base_url=config.base_url,
902
+ token=token,
903
+ endpoints=endpoints,
904
+ include_unsafe=allow_unsafe_for("contract_conformance"),
905
+ )
906
+ )
907
+ if "bola_matrix" in selected_categories:
908
+ all_results.extend(
909
+ bola_matrix.run(
910
+ client=client,
911
+ base_url=config.base_url,
912
+ token=token,
913
+ endpoints=endpoints,
914
+ include_unsafe=allow_unsafe_for("bola_matrix"),
915
+ )
916
+ )
917
+ if "workflow_chains" in selected_categories:
918
+ all_results.extend(
919
+ workflow_chains.run(
920
+ client=client,
921
+ base_url=config.base_url,
922
+ token=token,
923
+ endpoints=endpoints,
924
+ include_unsafe=allow_unsafe_for("workflow_chains"),
925
+ )
926
+ )
927
+ if "soak_profile" in selected_categories:
928
+ all_results.extend(
929
+ soak_profile.run(
930
+ client=client,
931
+ base_url=config.base_url,
932
+ token=token,
933
+ endpoints=endpoints,
934
+ include_unsafe=allow_unsafe_for("soak_profile"),
935
+ soak_samples=soak_samples,
936
+ soak_max_5xx_rate=soak_max_5xx_rate,
937
+ soak_max_exception_rate=soak_max_exception_rate,
938
+ soak_max_p95_ms=soak_max_p95_ms,
939
+ )
940
+ )
941
+ summary = build_summary(all_results, discovered_endpoints=len(endpoints))
942
+ return config, summary, all_results
943
+
944
+ print(f"[bold]Web App API Security Runner[/bold] v{__version__}")
945
+ if config_path:
946
+ print(f"Config: {config_path}")
947
+ if profile:
948
+ print(f"Profile: {profile} (categories: {', '.join(sorted(selected_categories))})")
949
+
950
+ targets = _parse_targets_arg(args.targets)
951
+ if not targets:
952
+ config, summary, all_results = execute_for_base_url(None)
953
+ print(f"Target: {config.base_url}")
954
+ if config.include_unsafe:
955
+ print(f"Unsafe execution enabled for categories: {', '.join(sorted(unsafe_categories))}")
956
+ else:
957
+ print("Unsafe execution disabled (POST/PUT/PATCH/DELETE will be skipped)")
958
+
959
+ json_report, summary_report, detail_report, failures_report = write_reports(
960
+ config.output_dir,
961
+ summary,
962
+ all_results,
963
+ json_out=args.json_out,
964
+ summary_md_out=args.md_summary_out,
965
+ detail_md_out=args.md_detail_out,
966
+ failures_md_out=args.md_failures_out,
967
+ filename_prefix=_target_report_prefix(config.base_url),
968
+ )
969
+
970
+ print("\n[bold]Run Summary[/bold]")
971
+ print(f"Passed: {summary.passed}")
972
+ print(f"Failed: {summary.failed}")
973
+ print(f"Skipped: {summary.skipped}")
974
+ print(f"Errors: {summary.errors}")
975
+ print(f"JSON report: {json_report}")
976
+ print(f"Summary report: {summary_report}")
977
+ print(f"Detail report: {detail_report}")
978
+ print(f"Failures report: {failures_report}")
979
+
980
+ if args.junit_out:
981
+ junit_path = write_junit_report(args.junit_out, summary, all_results)
982
+ print(f"JUnit report: {junit_path}")
983
+ if args.sarif_out:
984
+ sarif_path = write_sarif_report(args.sarif_out, summary, all_results)
985
+ print(f"SARIF report: {sarif_path}")
986
+
987
+ ci_gate_failed = False
988
+ ci_gate_reasons: list[str] = []
989
+ if args.fail_on_findings and (summary.failed > 0 or summary.errors > 0):
990
+ ci_gate_failed = True
991
+ ci_gate_reasons.append(
992
+ f"--fail-on-findings set and findings present (failed={summary.failed}, errors={summary.errors})"
993
+ )
994
+ if args.max_failed is not None and summary.failed > args.max_failed:
995
+ ci_gate_failed = True
996
+ ci_gate_reasons.append(
997
+ f"failed findings {summary.failed} exceeded --max-failed {args.max_failed}"
998
+ )
999
+ if args.max_errors is not None and summary.errors > args.max_errors:
1000
+ ci_gate_failed = True
1001
+ ci_gate_reasons.append(
1002
+ f"error findings {summary.errors} exceeded --max-errors {args.max_errors}"
1003
+ )
1004
+
1005
+ if ci_gate_failed:
1006
+ print("\n[bold red]CI gate failed[/bold red]")
1007
+ for reason in ci_gate_reasons:
1008
+ print(f"- {reason}")
1009
+ return 1
1010
+ return 0
1011
+
1012
+ print(f"Targets: {', '.join(targets)}")
1013
+ print("Running targets in parallel")
1014
+ target_failures: list[str] = []
1015
+ gate_failed = False
1016
+ target_summaries: dict[str, tuple[str, object, Path, Path, Path, Path]] = {}
1017
+
1018
+ with ThreadPoolExecutor(max_workers=min(8, max(1, len(targets)))) as executor:
1019
+ future_map = {
1020
+ executor.submit(execute_for_base_url, target): target
1021
+ for target in targets
1022
+ }
1023
+ for future in as_completed(future_map):
1024
+ target = future_map[future]
1025
+ try:
1026
+ config, summary, all_results = future.result()
1027
+ except BaseException as exc:
1028
+ gate_failed = True
1029
+ target_failures.append(f"{target}: execution error ({exc})")
1030
+ continue
1031
+
1032
+ prefix = _target_report_prefix(config.base_url)
1033
+ json_report, summary_report, detail_report, failures_report = write_reports(
1034
+ config.output_dir,
1035
+ summary,
1036
+ all_results,
1037
+ filename_prefix=prefix,
1038
+ )
1039
+ target_summaries[target] = (
1040
+ config.base_url,
1041
+ summary,
1042
+ json_report,
1043
+ summary_report,
1044
+ detail_report,
1045
+ failures_report,
1046
+ )
1047
+
1048
+ ci_gate_failed = False
1049
+ if args.fail_on_findings and (summary.failed > 0 or summary.errors > 0):
1050
+ ci_gate_failed = True
1051
+ if args.max_failed is not None and summary.failed > args.max_failed:
1052
+ ci_gate_failed = True
1053
+ if args.max_errors is not None and summary.errors > args.max_errors:
1054
+ ci_gate_failed = True
1055
+ if ci_gate_failed:
1056
+ gate_failed = True
1057
+ target_failures.append(
1058
+ f"{target}: gate failed (failed={summary.failed}, errors={summary.errors})"
1059
+ )
1060
+
1061
+ for target in targets:
1062
+ data = target_summaries.get(target)
1063
+ if data is None:
1064
+ continue
1065
+ base_url, summary, json_report, summary_report, detail_report, failures_report = data
1066
+ print(f"\n[bold]Target Summary[/bold] {base_url}")
1067
+ print(f"Passed: {summary.passed}")
1068
+ print(f"Failed: {summary.failed}")
1069
+ print(f"Skipped: {summary.skipped}")
1070
+ print(f"Errors: {summary.errors}")
1071
+ print(f"JSON report: {json_report}")
1072
+ print(f"Summary report: {summary_report}")
1073
+ print(f"Detail report: {detail_report}")
1074
+ print(f"Failures report: {failures_report}")
1075
+
1076
+ if target_failures:
1077
+ print("\n[bold red]Target failures[/bold red]")
1078
+ for failure in target_failures:
1079
+ print(f"- {failure}")
1080
+
1081
+ return 1 if gate_failed else 0
1082
+
1083
+
1084
+ if __name__ == "__main__":
1085
+ raise SystemExit(main())