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
@@ -0,0 +1,437 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ from typing import Any
5
+
6
+ import httpx
7
+
8
+ from app_test.auth import auth_headers_from_token
9
+ from app_test.models import EndpointSpec, ExecutionResult
10
+
11
+
12
+ MAX_CHAINS = 8
13
+
14
+ # ID field names to look for when extracting a created resource's ID
15
+ _ID_FIELD_PRIORITY = ("id", "uuid", "identifier", "object_id", "resource_id")
16
+ _LIST_WRAPPER_KEYS = ("items", "data", "results", "records", "assets", "objects")
17
+
18
+
19
+ # ---------------------------------------------------------------------------
20
+ # Resource group discovery
21
+ # ---------------------------------------------------------------------------
22
+
23
+ def _path_prefix(path: str) -> str:
24
+ """Return the static prefix before the first path parameter."""
25
+ if "{" not in path:
26
+ return path
27
+ return path[: path.index("{")].rstrip("/")
28
+
29
+
30
+ def _has_path_param(endpoint: EndpointSpec) -> bool:
31
+ return any(p.where == "path" for p in endpoint.parameters)
32
+
33
+
34
+ def _group_endpoints_by_resource(
35
+ endpoints: list[EndpointSpec],
36
+ ) -> dict[tuple[str, str], dict[str, EndpointSpec]]:
37
+ """
38
+ Group endpoints into resource chains keyed by (service, path_prefix).
39
+
40
+ A useful chain needs at least a POST (create) and one of GET/PUT/PATCH/DELETE.
41
+ """
42
+ by_prefix: dict[tuple[str, str], dict[str, EndpointSpec]] = {}
43
+
44
+ for ep in endpoints:
45
+ if not ep.requires_auth:
46
+ continue
47
+ method = ep.method.upper()
48
+ prefix = _path_prefix(ep.path)
49
+ key = (ep.service, prefix)
50
+ by_prefix.setdefault(key, {})[method] = ep
51
+
52
+ # Keep only groups that have a POST and at least one instance endpoint
53
+ chains: dict[tuple[str, str], dict[str, EndpointSpec]] = {}
54
+ for key, method_map in by_prefix.items():
55
+ if "POST" not in method_map:
56
+ continue
57
+ has_instance_ep = any(
58
+ m in method_map and _has_path_param(method_map[m])
59
+ for m in ("GET", "PUT", "PATCH", "DELETE")
60
+ )
61
+ if has_instance_ep:
62
+ chains[key] = method_map
63
+
64
+ return chains
65
+
66
+
67
+ # ---------------------------------------------------------------------------
68
+ # Helpers
69
+ # ---------------------------------------------------------------------------
70
+
71
+ def _sample_body(endpoint: EndpointSpec) -> dict[str, Any]:
72
+ content = (endpoint.request_body.get("content") or {}) or {}
73
+ json_body = content.get("application/json") or {}
74
+ schema = json_body.get("schema") or {}
75
+ properties = schema.get("properties") or {}
76
+
77
+ body: dict[str, Any] = {}
78
+ for key, prop in (properties.items() if isinstance(properties, dict) else {}.items()):
79
+ prop_type = str((prop or {}).get("type", "string"))
80
+ if prop_type == "integer":
81
+ body[key] = 1
82
+ elif prop_type == "number":
83
+ body[key] = 1.0
84
+ elif prop_type == "boolean":
85
+ body[key] = True
86
+ else:
87
+ body[key] = "workflow-chain-test"
88
+ return body
89
+
90
+
91
+ def _extract_created_id(body: Any) -> str | None:
92
+ """Extract an ID from a POST response body."""
93
+ if isinstance(body, dict):
94
+ for field in _ID_FIELD_PRIORITY:
95
+ val = body.get(field)
96
+ if val is not None:
97
+ return str(val)
98
+ # Try *_id suffixed fields
99
+ for key, val in body.items():
100
+ if key.lower().endswith("_id") and val is not None:
101
+ return str(val)
102
+ # Try wrapped responses
103
+ for wrapper in _LIST_WRAPPER_KEYS:
104
+ inner = body.get(wrapper)
105
+ if isinstance(inner, list) and inner:
106
+ return _extract_created_id(inner[0])
107
+ if isinstance(inner, dict):
108
+ return _extract_created_id(inner)
109
+ return None
110
+
111
+
112
+ def _inject_id(base_url: str, endpoint: EndpointSpec, resource_id: str) -> str:
113
+ path = endpoint.path
114
+ for param in endpoint.parameters:
115
+ if param.where == "path":
116
+ path = path.replace(f"{{{param.name}}}", resource_id)
117
+ return f"{base_url.rstrip('/')}{path}"
118
+
119
+
120
+ def _make_result(
121
+ service: str,
122
+ method: str,
123
+ url: str,
124
+ test_name: str,
125
+ status: str,
126
+ http_status: int | None,
127
+ latency_ms: float | None,
128
+ message: str,
129
+ snippet: str = "",
130
+ ) -> ExecutionResult:
131
+ return ExecutionResult(
132
+ category="workflow_chains",
133
+ test_name=test_name,
134
+ service=service,
135
+ method=method,
136
+ url=url,
137
+ status=status,
138
+ http_status=http_status,
139
+ latency_ms=latency_ms,
140
+ message=message,
141
+ response_snippet=snippet[:400],
142
+ )
143
+
144
+
145
+ def _timed_request(
146
+ client: httpx.Client,
147
+ method: str,
148
+ url: str,
149
+ headers: dict[str, str],
150
+ json: dict[str, Any] | None = None,
151
+ ) -> tuple[httpx.Response, float]:
152
+ t0 = time.monotonic()
153
+ resp = client.request(method=method, url=url, headers=headers, json=json)
154
+ return resp, (time.monotonic() - t0) * 1000
155
+
156
+
157
+ # ---------------------------------------------------------------------------
158
+ # Chain execution
159
+ # ---------------------------------------------------------------------------
160
+
161
+ def _run_chain(
162
+ client: httpx.Client,
163
+ base_url: str,
164
+ token: str | None,
165
+ service: str,
166
+ method_map: dict[str, EndpointSpec],
167
+ ) -> list[ExecutionResult]:
168
+ results: list[ExecutionResult] = []
169
+ headers = auth_headers_from_token(token) if token else {}
170
+ no_auth: dict[str, str] = {}
171
+
172
+ create_ep = method_map["POST"]
173
+ create_url = f"{base_url.rstrip('/')}{create_ep.path}"
174
+ body = _sample_body(create_ep)
175
+ snippet = ""
176
+
177
+ # --- Step 1: Create ---
178
+ try:
179
+ resp, latency = _timed_request(client, "POST", create_url, headers, json=body or None)
180
+ snippet = " ".join(resp.text.split())[:400]
181
+ except Exception as exc:
182
+ results.append(_make_result(service, "POST", create_url, "workflow_create", "error", None, None, str(exc)))
183
+ return results
184
+
185
+ if not (200 <= resp.status_code < 300):
186
+ results.append(_make_result(
187
+ service, "POST", create_url, "workflow_create",
188
+ "skipped", resp.status_code, latency,
189
+ f"Create returned {resp.status_code}; skipping remaining chain steps",
190
+ ))
191
+ return results
192
+
193
+ results.append(_make_result(
194
+ service, "POST", create_url, "workflow_create",
195
+ "pass", resp.status_code, latency, f"Resource created ({resp.status_code})",
196
+ ))
197
+
198
+ # Extract the created ID
199
+ try:
200
+ resource_id = _extract_created_id(resp.json())
201
+ except Exception:
202
+ resource_id = None
203
+
204
+ if not resource_id:
205
+ results.append(_make_result(
206
+ service, "POST", create_url, "workflow_id_extraction",
207
+ "skipped", resp.status_code, latency,
208
+ "Could not extract resource ID from create response; skipping read/update/delete steps",
209
+ snippet,
210
+ ))
211
+ return results
212
+
213
+ # --- Step 2: Read (GET by ID) ---
214
+ # Find a GET endpoint with a path parameter (instance endpoint)
215
+ read_ep = next(
216
+ (ep for m, ep in method_map.items() if m == "GET" and _has_path_param(ep)),
217
+ None,
218
+ )
219
+ if read_ep:
220
+ read_url = _inject_id(base_url, read_ep, resource_id)
221
+ try:
222
+ resp, latency = _timed_request(client, "GET", read_url, headers)
223
+ snippet = " ".join(resp.text.split())[:400]
224
+ except Exception as exc:
225
+ results.append(_make_result(service, "GET", read_url, "workflow_read", "error", None, None, str(exc)))
226
+ read_ep = None
227
+ else:
228
+ if 200 <= resp.status_code < 300:
229
+ results.append(_make_result(
230
+ service, "GET", read_url, "workflow_read",
231
+ "pass", resp.status_code, latency, f"Created resource is readable ({resp.status_code})",
232
+ ))
233
+ elif resp.status_code == 404:
234
+ results.append(_make_result(
235
+ service, "GET", read_url, "workflow_read",
236
+ "fail", resp.status_code, latency,
237
+ f"Newly created resource not found ({resp.status_code}) — possible ID mismatch or delayed visibility",
238
+ snippet,
239
+ ))
240
+ else:
241
+ results.append(_make_result(
242
+ service, "GET", read_url, "workflow_read",
243
+ "pass", resp.status_code, latency, f"Read returned {resp.status_code}",
244
+ ))
245
+
246
+ # Authz check: unauthenticated read should be denied
247
+ try:
248
+ resp_unauth, lat_unauth = _timed_request(client, "GET", read_url, no_auth)
249
+ except Exception as exc:
250
+ results.append(_make_result(service, "GET", read_url, "workflow_read_authz", "error", None, None, str(exc)))
251
+ else:
252
+ if resp_unauth.status_code in {401, 403}:
253
+ results.append(_make_result(
254
+ service, "GET", read_url, "workflow_read_authz",
255
+ "pass", resp_unauth.status_code, lat_unauth,
256
+ f"Unauthenticated read correctly denied ({resp_unauth.status_code})",
257
+ ))
258
+ elif 200 <= resp_unauth.status_code < 300:
259
+ results.append(_make_result(
260
+ service, "GET", read_url, "workflow_read_authz",
261
+ "fail", resp_unauth.status_code, lat_unauth,
262
+ f"Unauthenticated access to created resource returned success ({resp_unauth.status_code}) — missing auth enforcement",
263
+ " ".join(resp_unauth.text.split())[:400],
264
+ ))
265
+ else:
266
+ results.append(_make_result(
267
+ service, "GET", read_url, "workflow_read_authz",
268
+ "pass", resp_unauth.status_code, lat_unauth,
269
+ f"Unauthenticated read returned {resp_unauth.status_code}",
270
+ ))
271
+
272
+ # --- Step 3: Update (PATCH preferred over PUT) ---
273
+ update_method = "PATCH" if "PATCH" in method_map else ("PUT" if "PUT" in method_map else None)
274
+ update_ep = method_map.get(update_method) if update_method else None
275
+ if update_ep and _has_path_param(update_ep):
276
+ update_url = _inject_id(base_url, update_ep, resource_id)
277
+ update_body = _sample_body(update_ep)
278
+ try:
279
+ resp, latency = _timed_request(client, update_method, update_url, headers, json=update_body or None)
280
+ snippet = " ".join(resp.text.split())[:400]
281
+ except Exception as exc:
282
+ results.append(_make_result(service, update_method, update_url, "workflow_update", "error", None, None, str(exc)))
283
+ else:
284
+ if 200 <= resp.status_code < 300:
285
+ results.append(_make_result(
286
+ service, update_method, update_url, "workflow_update",
287
+ "pass", resp.status_code, latency, f"Resource updated ({resp.status_code})",
288
+ ))
289
+ elif resp.status_code in {400, 422}:
290
+ results.append(_make_result(
291
+ service, update_method, update_url, "workflow_update",
292
+ "skipped", resp.status_code, latency,
293
+ f"Update rejected ({resp.status_code}) — sample payload may be invalid for this resource",
294
+ ))
295
+ else:
296
+ results.append(_make_result(
297
+ service, update_method, update_url, "workflow_update",
298
+ "pass", resp.status_code, latency, f"Update returned {resp.status_code}",
299
+ ))
300
+
301
+ # Authz check: unauthenticated update should be denied
302
+ try:
303
+ resp_unauth, lat_unauth = _timed_request(client, update_method, update_url, no_auth, json=update_body or None)
304
+ except Exception as exc:
305
+ results.append(_make_result(service, update_method, update_url, "workflow_update_authz", "error", None, None, str(exc)))
306
+ else:
307
+ if resp_unauth.status_code in {401, 403}:
308
+ results.append(_make_result(
309
+ service, update_method, update_url, "workflow_update_authz",
310
+ "pass", resp_unauth.status_code, lat_unauth,
311
+ f"Unauthenticated update correctly denied ({resp_unauth.status_code})",
312
+ ))
313
+ elif 200 <= resp_unauth.status_code < 300:
314
+ results.append(_make_result(
315
+ service, update_method, update_url, "workflow_update_authz",
316
+ "fail", resp_unauth.status_code, lat_unauth,
317
+ f"Unauthenticated update returned success ({resp_unauth.status_code}) — missing auth enforcement on mutation",
318
+ " ".join(resp_unauth.text.split())[:400],
319
+ ))
320
+ else:
321
+ results.append(_make_result(
322
+ service, update_method, update_url, "workflow_update_authz",
323
+ "pass", resp_unauth.status_code, lat_unauth,
324
+ f"Unauthenticated update returned {resp_unauth.status_code}",
325
+ ))
326
+
327
+ # --- Step 4: Delete ---
328
+ delete_ep = method_map.get("DELETE")
329
+ if delete_ep and _has_path_param(delete_ep):
330
+ delete_url = _inject_id(base_url, delete_ep, resource_id)
331
+
332
+ # Authz check first (before actually deleting — use a wrong ID to stay safe)
333
+ authz_id = resource_id + "_nonexistent"
334
+ authz_delete_url = _inject_id(base_url, delete_ep, authz_id)
335
+ try:
336
+ resp_unauth, lat_unauth = _timed_request(client, "DELETE", authz_delete_url, no_auth)
337
+ except Exception as exc:
338
+ results.append(_make_result(service, "DELETE", authz_delete_url, "workflow_delete_authz", "error", None, None, str(exc)))
339
+ else:
340
+ if resp_unauth.status_code in {401, 403}:
341
+ results.append(_make_result(
342
+ service, "DELETE", authz_delete_url, "workflow_delete_authz",
343
+ "pass", resp_unauth.status_code, lat_unauth,
344
+ f"Unauthenticated delete correctly denied ({resp_unauth.status_code})",
345
+ ))
346
+ elif 200 <= resp_unauth.status_code < 300:
347
+ results.append(_make_result(
348
+ service, "DELETE", authz_delete_url, "workflow_delete_authz",
349
+ "fail", resp_unauth.status_code, lat_unauth,
350
+ f"Unauthenticated delete returned success ({resp_unauth.status_code}) — missing auth enforcement on deletion",
351
+ " ".join(resp_unauth.text.split())[:400],
352
+ ))
353
+ else:
354
+ results.append(_make_result(
355
+ service, "DELETE", authz_delete_url, "workflow_delete_authz",
356
+ "pass", resp_unauth.status_code, lat_unauth,
357
+ f"Unauthenticated delete returned {resp_unauth.status_code}",
358
+ ))
359
+
360
+ # Actual delete of the test resource (cleanup)
361
+ try:
362
+ resp, latency = _timed_request(client, "DELETE", delete_url, headers)
363
+ snippet = " ".join(resp.text.split())[:400]
364
+ except Exception as exc:
365
+ results.append(_make_result(service, "DELETE", delete_url, "workflow_delete", "error", None, None, str(exc)))
366
+ else:
367
+ if resp.status_code in {200, 202, 204}:
368
+ results.append(_make_result(
369
+ service, "DELETE", delete_url, "workflow_delete",
370
+ "pass", resp.status_code, latency, f"Resource deleted ({resp.status_code}) — test resource cleaned up",
371
+ ))
372
+ elif resp.status_code == 404:
373
+ results.append(_make_result(
374
+ service, "DELETE", delete_url, "workflow_delete",
375
+ "pass", resp.status_code, latency,
376
+ f"Resource already gone ({resp.status_code}) — possibly cleaned up by earlier step",
377
+ ))
378
+ else:
379
+ results.append(_make_result(
380
+ service, "DELETE", delete_url, "workflow_delete",
381
+ "skipped", resp.status_code, latency,
382
+ f"Delete returned {resp.status_code} — resource may remain; manual cleanup may be needed",
383
+ snippet,
384
+ ))
385
+
386
+ return results
387
+
388
+
389
+ # ---------------------------------------------------------------------------
390
+ # Category entry point
391
+ # ---------------------------------------------------------------------------
392
+
393
+ def run(
394
+ client: httpx.Client,
395
+ base_url: str,
396
+ token: str | None,
397
+ endpoints: list[EndpointSpec],
398
+ include_unsafe: bool,
399
+ ) -> list[ExecutionResult]:
400
+ if not include_unsafe:
401
+ return [
402
+ ExecutionResult(
403
+ category="workflow_chains",
404
+ test_name="workflow_chains_unsafe_gate",
405
+ service="gateway",
406
+ method="POST",
407
+ url=base_url.rstrip("/"),
408
+ status="skipped",
409
+ message=(
410
+ "workflow_chains requires --include-unsafe (uses POST/PATCH/PUT/DELETE "
411
+ "to create and delete test resources)"
412
+ ),
413
+ )
414
+ ]
415
+
416
+ groups = _group_endpoints_by_resource(endpoints)
417
+
418
+ if not groups:
419
+ return [
420
+ ExecutionResult(
421
+ category="workflow_chains",
422
+ test_name="workflow_chains_target_discovery",
423
+ service="gateway",
424
+ method="POST",
425
+ url=base_url.rstrip("/"),
426
+ status="skipped",
427
+ message=(
428
+ "No resource groups found with a POST endpoint plus at least one "
429
+ "authenticated instance endpoint (GET/PUT/PATCH/DELETE with path param)"
430
+ ),
431
+ )
432
+ ]
433
+
434
+ results: list[ExecutionResult] = []
435
+ for (service, prefix), method_map in list(groups.items())[:MAX_CHAINS]:
436
+ results.extend(_run_chain(client, base_url, token, service, method_map))
437
+ return results