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,270 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ import httpx
6
+
7
+ from app_test.executor import execute_endpoint
8
+ from app_test.models import EndpointSpec, ExecutionResult
9
+
10
+
11
+ SAFE_METHODS = {"GET", "HEAD", "OPTIONS"}
12
+ MAX_TARGETS = 24
13
+ PROBE_PAYLOAD = "__apptest_error_probe__'\"<script>alert(1)</script>"
14
+ HIGH_LEAK_MARKERS = {
15
+ "traceback (most recent call last)",
16
+ "stack trace",
17
+ "sqlalchemy.exc",
18
+ "psycopg2.",
19
+ "sqlite3.",
20
+ "java.lang.",
21
+ "nullpointerexception",
22
+ "module not found",
23
+ "permission denied:",
24
+ "file \"/",
25
+ }
26
+ MEDIUM_LEAK_MARKERS = {
27
+ "exception",
28
+ "error while processing",
29
+ "internal server error",
30
+ "debug",
31
+ }
32
+
33
+
34
+ def _sample_value(schema_type: str) -> str | int | float | bool:
35
+ if schema_type == "integer":
36
+ return 1
37
+ if schema_type == "number":
38
+ return 1.0
39
+ if schema_type == "boolean":
40
+ return True
41
+ return "sample"
42
+
43
+
44
+ def _materialize_url_and_params(base_url: str, endpoint: EndpointSpec) -> tuple[str, dict[str, str | int | float | bool]]:
45
+ url = f"{base_url.rstrip('/')}{endpoint.path}"
46
+ query_params: dict[str, str | int | float | bool] = {}
47
+ for param in endpoint.parameters:
48
+ sample = _sample_value(param.schema_type)
49
+ if param.where == "path":
50
+ url = url.replace(f"{{{param.name}}}", str(sample))
51
+ elif param.where == "query":
52
+ query_params[param.name] = sample
53
+ return url, query_params
54
+
55
+
56
+ def _target_candidates(endpoints: list[EndpointSpec]) -> list[EndpointSpec]:
57
+ filtered = [
58
+ endpoint
59
+ for endpoint in endpoints
60
+ if endpoint.method.upper() in SAFE_METHODS
61
+ and "health" not in endpoint.path.lower()
62
+ and "ready" not in endpoint.path.lower()
63
+ ]
64
+ scored = sorted(
65
+ filtered,
66
+ key=lambda endpoint: (
67
+ len(endpoint.parameters),
68
+ endpoint.requires_auth,
69
+ endpoint.service == "data",
70
+ ),
71
+ reverse=True,
72
+ )
73
+ return scored[:MAX_TARGETS]
74
+
75
+
76
+ def _normalize_error_leakage_result(result: ExecutionResult) -> ExecutionResult:
77
+ if result.status in {"error", "skipped"}:
78
+ return ExecutionResult(
79
+ category="error_leakage_and_debug_surface",
80
+ test_name="error_response_information_leak_check",
81
+ service=result.service,
82
+ method=result.method,
83
+ url=result.url,
84
+ status=result.status,
85
+ http_status=result.http_status,
86
+ latency_ms=result.latency_ms,
87
+ message=result.message,
88
+ retries=result.retries,
89
+ diagnostics=result.diagnostics,
90
+ response_snippet=result.response_snippet,
91
+ )
92
+
93
+ snippet = (result.response_snippet or "").lower()
94
+ high_hits = sorted(marker for marker in HIGH_LEAK_MARKERS if marker in snippet)
95
+ medium_hits = sorted(marker for marker in MEDIUM_LEAK_MARKERS if marker in snippet)
96
+ if high_hits:
97
+ status = "fail"
98
+ message = f"[high] Error response appears to leak internal debug information: {', '.join(high_hits[:3])}"
99
+ elif medium_hits:
100
+ status = "skipped"
101
+ message = f"[medium] Error response contains generic diagnostic terms without high-confidence internal leakage: {', '.join(medium_hits[:3])}"
102
+ elif result.http_status is not None and result.http_status >= 500:
103
+ status = "pass"
104
+ message = "Server error did not expose known internal debug markers"
105
+ elif result.http_status is not None and 400 <= result.http_status < 500:
106
+ status = "pass"
107
+ message = "Client error response did not expose known internal debug markers"
108
+ else:
109
+ status = "skipped"
110
+ message = "Probe returned non-error response without leakage markers"
111
+
112
+ return ExecutionResult(
113
+ category="error_leakage_and_debug_surface",
114
+ test_name="error_response_information_leak_check",
115
+ service=result.service,
116
+ method=result.method,
117
+ url=result.url,
118
+ status=status,
119
+ http_status=result.http_status,
120
+ latency_ms=result.latency_ms,
121
+ message=message,
122
+ retries=result.retries,
123
+ diagnostics=result.diagnostics,
124
+ response_snippet=result.response_snippet,
125
+ )
126
+
127
+
128
+ def _debug_candidates(endpoints: list[EndpointSpec]) -> list[EndpointSpec]:
129
+ return [
130
+ endpoint
131
+ for endpoint in endpoints
132
+ if "debug" in endpoint.path.lower() or "debug" in (endpoint.operation_id or "").lower()
133
+ ]
134
+
135
+
136
+ def _debug_route_exposure(endpoints: list[EndpointSpec], base_url: str) -> ExecutionResult:
137
+ debug_endpoints = _debug_candidates(endpoints)
138
+ if not debug_endpoints:
139
+ return ExecutionResult(
140
+ category="error_leakage_and_debug_surface",
141
+ test_name="debug_route_public_exposure_check",
142
+ service="gateway",
143
+ method="GET",
144
+ url=base_url.rstrip("/"),
145
+ status="skipped",
146
+ message="No debug-style routes discovered in OpenAPI surface",
147
+ )
148
+
149
+ public_debug = [endpoint for endpoint in debug_endpoints if not endpoint.requires_auth]
150
+ if public_debug:
151
+ endpoint = public_debug[0]
152
+ return ExecutionResult(
153
+ category="error_leakage_and_debug_surface",
154
+ test_name="debug_route_public_exposure_check",
155
+ service=endpoint.service,
156
+ method=endpoint.method.upper(),
157
+ url=f"{base_url.rstrip('/')}{endpoint.path}",
158
+ status="fail",
159
+ message="Public debug route discovered in API schema",
160
+ )
161
+
162
+ endpoint = debug_endpoints[0]
163
+ return ExecutionResult(
164
+ category="error_leakage_and_debug_surface",
165
+ test_name="debug_route_public_exposure_check",
166
+ service=endpoint.service,
167
+ method=endpoint.method.upper(),
168
+ url=f"{base_url.rstrip('/')}{endpoint.path}",
169
+ status="pass",
170
+ message=f"Discovered {len(debug_endpoints)} debug route(s), all require authentication",
171
+ )
172
+
173
+
174
+ def _debug_unauthenticated_probe(client: httpx.Client, base_url: str, endpoint: EndpointSpec) -> ExecutionResult:
175
+ url, query_params = _materialize_url_and_params(base_url, endpoint)
176
+ try:
177
+ response = client.request(endpoint.method.upper(), url, params=query_params)
178
+ if response.status_code in {401, 403, 404}:
179
+ status = "pass"
180
+ message = f"Debug route denied unauthenticated access ({response.status_code})"
181
+ elif 200 <= response.status_code < 300:
182
+ status = "fail"
183
+ message = f"Debug route returned success for unauthenticated request ({response.status_code})"
184
+ else:
185
+ status = "pass"
186
+ message = f"Debug route returned non-success status for unauthenticated request ({response.status_code})"
187
+
188
+ return ExecutionResult(
189
+ category="error_leakage_and_debug_surface",
190
+ test_name="debug_route_unauthenticated_access_check",
191
+ service=endpoint.service,
192
+ method=endpoint.method.upper(),
193
+ url=str(response.request.url),
194
+ status=status,
195
+ http_status=response.status_code,
196
+ message=message,
197
+ response_snippet=(" ".join((response.text or "").split()))[:400],
198
+ )
199
+ except Exception as exc:
200
+ return ExecutionResult(
201
+ category="error_leakage_and_debug_surface",
202
+ test_name="debug_route_unauthenticated_access_check",
203
+ service=endpoint.service,
204
+ method=endpoint.method.upper(),
205
+ url=url,
206
+ status="error",
207
+ message=str(exc),
208
+ )
209
+
210
+
211
+ def run(
212
+ client: httpx.Client,
213
+ base_url: str,
214
+ token: str,
215
+ endpoints: list[EndpointSpec],
216
+ include_unsafe: bool,
217
+ ) -> list[ExecutionResult]:
218
+ del include_unsafe
219
+
220
+ results = [_debug_route_exposure(endpoints, base_url)]
221
+
222
+ auth_debug_targets = [
223
+ endpoint
224
+ for endpoint in _debug_candidates(endpoints)
225
+ if endpoint.requires_auth and endpoint.method.upper() in SAFE_METHODS
226
+ ]
227
+ if auth_debug_targets:
228
+ results.append(_debug_unauthenticated_probe(client, base_url, auth_debug_targets[0]))
229
+ else:
230
+ results.append(
231
+ ExecutionResult(
232
+ category="error_leakage_and_debug_surface",
233
+ test_name="debug_route_unauthenticated_access_check",
234
+ service="gateway",
235
+ method="GET",
236
+ url=base_url.rstrip("/"),
237
+ status="skipped",
238
+ message="No authenticated debug route with safe method was available for unauthenticated access probe",
239
+ )
240
+ )
241
+
242
+ targets = _target_candidates(endpoints)
243
+ if not targets:
244
+ results.append(
245
+ ExecutionResult(
246
+ category="error_leakage_and_debug_surface",
247
+ test_name="error_leakage_target_discovery",
248
+ service="gateway",
249
+ method="GET",
250
+ url=base_url.rstrip("/"),
251
+ status="skipped",
252
+ message="No safe endpoints discovered for error leakage probing",
253
+ )
254
+ )
255
+ return results
256
+
257
+ for endpoint in targets:
258
+ base_result = execute_endpoint(
259
+ client=client,
260
+ endpoint=endpoint,
261
+ base_url=base_url,
262
+ token=token,
263
+ category="error_leakage_and_debug_surface",
264
+ test_name="error_response_information_leak_check",
265
+ include_unsafe=False,
266
+ attack_payload=PROBE_PAYLOAD,
267
+ )
268
+ results.append(_normalize_error_leakage_result(base_result))
269
+
270
+ return results
@@ -0,0 +1,302 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ import httpx
6
+
7
+ from app_test.auth import auth_headers_from_token
8
+ from app_test.executor import execute_endpoint
9
+ from app_test.models import EndpointSpec, ExecutionResult
10
+
11
+
12
+ MAX_TARGETS = 10
13
+ PATH_TRAVERSAL_FILENAME = "../../../../tmp/__apptest_upload_traversal__.py"
14
+ ABSOLUTE_PATH_FILENAME = "/etc/__apptest_upload_absolute__.py"
15
+ UPLOAD_FILE_CONTENT = b"print('apptest upload probe')\n"
16
+ UPLOAD_CONTENT_TYPE = "application/octet-stream"
17
+ SUCCESS_REJECTION_CODES = {400, 401, 403, 404, 409, 413, 415, 422}
18
+
19
+
20
+ def _multipart_schema(endpoint: EndpointSpec) -> dict[str, Any]:
21
+ return (
22
+ endpoint.request_body.get("content", {})
23
+ .get("multipart/form-data", {})
24
+ .get("schema", {})
25
+ )
26
+
27
+
28
+ def _multipart_properties(endpoint: EndpointSpec) -> dict[str, dict[str, Any]]:
29
+ properties = _multipart_schema(endpoint).get("properties", {})
30
+ return properties if isinstance(properties, dict) else {}
31
+
32
+
33
+ def _is_file_property(name: str, prop: dict[str, Any]) -> bool:
34
+ if not isinstance(prop, dict):
35
+ return False
36
+
37
+ if prop.get("contentMediaType"):
38
+ return True
39
+
40
+ items = prop.get("items")
41
+ if isinstance(items, dict) and items.get("contentMediaType"):
42
+ return True
43
+
44
+ lowered_name = name.lower()
45
+ return any(token in lowered_name for token in {"file", "files", "upload", "attachment"})
46
+
47
+
48
+ def _file_field_name(endpoint: EndpointSpec) -> str | None:
49
+ for name, prop in _multipart_properties(endpoint).items():
50
+ if _is_file_property(name, prop):
51
+ return name
52
+ return None
53
+
54
+
55
+ def _candidate_targets(endpoints: list[EndpointSpec]) -> list[EndpointSpec]:
56
+ targets: list[EndpointSpec] = []
57
+ for endpoint in endpoints:
58
+ if endpoint.method.upper() not in {"POST", "PUT", "PATCH"}:
59
+ continue
60
+ if not endpoint.requires_auth:
61
+ continue
62
+ if not _file_field_name(endpoint):
63
+ continue
64
+ targets.append(endpoint)
65
+ return targets[:MAX_TARGETS]
66
+
67
+
68
+ def _sample_form_value(name: str, schema_type: str, application_id: str) -> str:
69
+ lowered_name = name.lower()
70
+ if lowered_name == "application_id":
71
+ return application_id
72
+ if schema_type == "integer":
73
+ return "1"
74
+ if schema_type == "number":
75
+ return "1"
76
+ if schema_type == "boolean":
77
+ return "true"
78
+ if lowered_name == "folder_name":
79
+ return "apptest-upload-probe"
80
+ return "sample"
81
+
82
+
83
+ def _build_form_data(endpoint: EndpointSpec, application_id: str) -> dict[str, str]:
84
+ form: dict[str, str] = {}
85
+ for name, prop in _multipart_properties(endpoint).items():
86
+ if _is_file_property(name, prop):
87
+ continue
88
+ schema_type = "string"
89
+ if isinstance(prop, dict):
90
+ schema_type = str(prop.get("type", "string"))
91
+ form[name] = _sample_form_value(name, schema_type, application_id)
92
+ return form
93
+
94
+
95
+ def _discover_application_id(client: httpx.Client, base_url: str, token: str) -> str | None:
96
+ url = f"{base_url.rstrip('/')}/api/assets/applications"
97
+ headers = auth_headers_from_token(token)
98
+ try:
99
+ response = client.get(url, headers=headers)
100
+ if response.status_code != 200:
101
+ return None
102
+ payload = response.json()
103
+ except Exception:
104
+ return None
105
+
106
+ items: list[dict[str, Any]] = []
107
+ if isinstance(payload, list):
108
+ items = [item for item in payload if isinstance(item, dict)]
109
+ elif isinstance(payload, dict):
110
+ raw_items = payload.get("items")
111
+ if isinstance(raw_items, list):
112
+ items = [item for item in raw_items if isinstance(item, dict)]
113
+
114
+ for item in items:
115
+ application_id = item.get("id")
116
+ if isinstance(application_id, str) and application_id:
117
+ return application_id
118
+ return None
119
+
120
+
121
+ def _normalize_upload_result(
122
+ result: ExecutionResult,
123
+ *,
124
+ test_name: str,
125
+ unsafe_marker: str,
126
+ ) -> ExecutionResult:
127
+ if result.status == "skipped":
128
+ return ExecutionResult(
129
+ category="file_upload_security",
130
+ test_name=test_name,
131
+ service=result.service,
132
+ method=result.method,
133
+ url=result.url,
134
+ status="skipped",
135
+ message=result.message,
136
+ )
137
+
138
+ if result.status == "error":
139
+ return ExecutionResult(
140
+ category="file_upload_security",
141
+ test_name=test_name,
142
+ service=result.service,
143
+ method=result.method,
144
+ url=result.url,
145
+ status="error",
146
+ http_status=result.http_status,
147
+ latency_ms=result.latency_ms,
148
+ message=result.message,
149
+ retries=result.retries,
150
+ diagnostics=result.diagnostics,
151
+ response_snippet=result.response_snippet,
152
+ )
153
+
154
+ if result.status == "fail":
155
+ return ExecutionResult(
156
+ category="file_upload_security",
157
+ test_name=test_name,
158
+ service=result.service,
159
+ method=result.method,
160
+ url=result.url,
161
+ status="fail",
162
+ http_status=result.http_status,
163
+ latency_ms=result.latency_ms,
164
+ message="Upload probe triggered server-side failure",
165
+ retries=result.retries,
166
+ diagnostics=result.diagnostics,
167
+ response_snippet=result.response_snippet,
168
+ )
169
+
170
+ status_code = result.http_status
171
+ snippet = result.response_snippet.lower()
172
+ if status_code in SUCCESS_REJECTION_CODES:
173
+ status = "pass"
174
+ message = f"Unsafe upload filename was rejected ({status_code})"
175
+ elif status_code is not None and 200 <= status_code < 300:
176
+ if unsafe_marker.lower() in snippet:
177
+ status = "fail"
178
+ message = "Unsafe upload filename appears reflected in the response"
179
+ else:
180
+ status = "skipped"
181
+ message = "Upload request succeeded without clear evidence that the unsafe filename was persisted or rejected"
182
+ else:
183
+ status = "pass"
184
+ message = f"Upload probe returned non-success status ({status_code})"
185
+
186
+ return ExecutionResult(
187
+ category="file_upload_security",
188
+ test_name=test_name,
189
+ service=result.service,
190
+ method=result.method,
191
+ url=result.url,
192
+ status=status,
193
+ http_status=result.http_status,
194
+ latency_ms=result.latency_ms,
195
+ message=message,
196
+ retries=result.retries,
197
+ diagnostics=result.diagnostics,
198
+ response_snippet=result.response_snippet,
199
+ )
200
+
201
+
202
+ def _run_upload_probe(
203
+ client: httpx.Client,
204
+ base_url: str,
205
+ token: str,
206
+ endpoint: EndpointSpec,
207
+ include_unsafe: bool,
208
+ *,
209
+ test_name: str,
210
+ application_id: str,
211
+ filename: str,
212
+ ) -> ExecutionResult:
213
+ file_field = _file_field_name(endpoint)
214
+ if file_field is None:
215
+ return ExecutionResult(
216
+ category="file_upload_security",
217
+ test_name=test_name,
218
+ service=endpoint.service,
219
+ method=endpoint.method.upper(),
220
+ url=f"{base_url.rstrip('/')}{endpoint.path}",
221
+ status="skipped",
222
+ message="No multipart file field discovered for this endpoint",
223
+ )
224
+
225
+ base_result = execute_endpoint(
226
+ client=client,
227
+ endpoint=endpoint,
228
+ base_url=base_url,
229
+ token=token,
230
+ category="file_upload_security",
231
+ test_name=test_name,
232
+ include_unsafe=include_unsafe,
233
+ form_override=_build_form_data(endpoint, application_id),
234
+ files_override=[
235
+ (file_field, (filename, UPLOAD_FILE_CONTENT, UPLOAD_CONTENT_TYPE)),
236
+ ],
237
+ )
238
+ return _normalize_upload_result(base_result, test_name=test_name, unsafe_marker=filename)
239
+
240
+
241
+ def run(
242
+ client: httpx.Client,
243
+ base_url: str,
244
+ token: str,
245
+ endpoints: list[EndpointSpec],
246
+ include_unsafe: bool,
247
+ ) -> list[ExecutionResult]:
248
+ targets = _candidate_targets(endpoints)
249
+ if not targets:
250
+ return [
251
+ ExecutionResult(
252
+ category="file_upload_security",
253
+ test_name="file_upload_target_discovery",
254
+ service="gateway",
255
+ method="POST",
256
+ url=base_url.rstrip("/"),
257
+ status="skipped",
258
+ message="No authenticated multipart upload endpoints discovered for file upload security checks",
259
+ )
260
+ ]
261
+
262
+ application_id = _discover_application_id(client, base_url, token)
263
+ if not application_id:
264
+ return [
265
+ ExecutionResult(
266
+ category="file_upload_security",
267
+ test_name="file_upload_application_context_discovery",
268
+ service=targets[0].service,
269
+ method=targets[0].method.upper(),
270
+ url=f"{base_url.rstrip('/')}{targets[0].path}",
271
+ status="skipped",
272
+ message="No application ID could be discovered for the authenticated tenant; upload checks were not executed",
273
+ )
274
+ ]
275
+
276
+ results: list[ExecutionResult] = []
277
+ for endpoint in targets:
278
+ results.append(
279
+ _run_upload_probe(
280
+ client,
281
+ base_url,
282
+ token,
283
+ endpoint,
284
+ include_unsafe,
285
+ test_name="upload_path_traversal_filename_check",
286
+ application_id=application_id,
287
+ filename=PATH_TRAVERSAL_FILENAME,
288
+ )
289
+ )
290
+ results.append(
291
+ _run_upload_probe(
292
+ client,
293
+ base_url,
294
+ token,
295
+ endpoint,
296
+ include_unsafe,
297
+ test_name="upload_absolute_path_filename_check",
298
+ application_id=application_id,
299
+ filename=ABSOLUTE_PATH_FILENAME,
300
+ )
301
+ )
302
+ return results