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/config.py ADDED
@@ -0,0 +1,19 @@
1
+ from dataclasses import dataclass, field
2
+
3
+
4
+ @dataclass(slots=True)
5
+ class AppConfig:
6
+ base_url: str = "https://your-target.example"
7
+ auth_type: str = "auto"
8
+ auth_header_name: str | None = None
9
+ auth_header_value: str | None = None
10
+ default_headers: dict[str, str] = field(default_factory=dict)
11
+ basic_username: str | None = None
12
+ basic_password: str | None = None
13
+ username: str = "your-user@example.com"
14
+ password: str = "your-password"
15
+ api_key: str | None = None
16
+ timeout_seconds: float = 20.0
17
+ include_unsafe: bool = False
18
+ output_dir: str = "reports"
19
+ verify_tls: bool = True
app_test/discovery.py ADDED
@@ -0,0 +1,269 @@
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.models import EndpointSpec, HTTP_METHODS, ParameterSpec
9
+
10
+ # Common OpenAPI spec paths probed for arbitrary targets
11
+ COMMON_OPENAPI_PATHS: list[str] = [
12
+ "/openapi.json",
13
+ "/openapi.yaml",
14
+ "/api-docs/openapi.json",
15
+ "/api/openapi.json",
16
+ "/api/v1/openapi.json",
17
+ "/api/v2/openapi.json",
18
+ "/v1/openapi.json",
19
+ "/v2/openapi.json",
20
+ "/swagger.json",
21
+ "/swagger/v1/swagger.json",
22
+ "/swagger/v2/swagger.json",
23
+ "/docs/openapi.json",
24
+ "/api-docs",
25
+ "/api/docs/openapi.json",
26
+ ]
27
+
28
+
29
+ def _build_full_path(service_prefix: str, endpoint_path: str) -> str:
30
+ if endpoint_path.startswith("/api/"):
31
+ return endpoint_path
32
+ if endpoint_path.startswith("/"):
33
+ return f"{service_prefix}{endpoint_path}"
34
+ return f"{service_prefix}/{endpoint_path}"
35
+
36
+
37
+ def _parameter_specs(raw_parameters: list[dict[str, Any]]) -> list[ParameterSpec]:
38
+ params: list[ParameterSpec] = []
39
+ for param in raw_parameters:
40
+ schema = param.get("schema", {}) or {}
41
+ params.append(
42
+ ParameterSpec(
43
+ name=param.get("name", "unknown"),
44
+ where=param.get("in", "query"),
45
+ required=bool(param.get("required", False)),
46
+ schema_type=schema.get("type", "string"),
47
+ )
48
+ )
49
+ return params
50
+
51
+
52
+ def _resolve_ref(document: dict[str, Any], ref: str) -> dict[str, Any]:
53
+ if not ref.startswith("#/"):
54
+ return {}
55
+
56
+ current: Any = document
57
+ for part in ref[2:].split("/"):
58
+ if not isinstance(current, dict):
59
+ return {}
60
+ current = current.get(part)
61
+ if current is None:
62
+ return {}
63
+
64
+ return current if isinstance(current, dict) else {}
65
+
66
+
67
+ def _merge_schema_parts(parts: list[dict[str, Any]]) -> dict[str, Any]:
68
+ merged: dict[str, Any] = {"properties": {}}
69
+ required: list[str] = []
70
+ for part in parts:
71
+ if not isinstance(part, dict):
72
+ continue
73
+ properties = part.get("properties") or {}
74
+ if isinstance(properties, dict):
75
+ merged.setdefault("properties", {}).update(properties)
76
+ for field in part.get("required") or []:
77
+ if field not in required:
78
+ required.append(field)
79
+ for key, value in part.items():
80
+ if key in {"properties", "required"}:
81
+ continue
82
+ merged.setdefault(key, value)
83
+ if required:
84
+ merged["required"] = required
85
+ return merged
86
+
87
+
88
+ def _resolve_schema(document: dict[str, Any], schema: dict[str, Any]) -> dict[str, Any]:
89
+ if not isinstance(schema, dict):
90
+ return {}
91
+
92
+ if "$ref" in schema:
93
+ resolved = _resolve_ref(document, str(schema["$ref"]))
94
+ merged = {k: v for k, v in schema.items() if k != "$ref"}
95
+ merged.update(_resolve_schema(document, resolved))
96
+ return merged
97
+
98
+ for key in ("allOf", "oneOf", "anyOf"):
99
+ if key in schema and isinstance(schema[key], list):
100
+ resolved_parts = [_resolve_schema(document, part) for part in schema[key]]
101
+ merged = _merge_schema_parts(resolved_parts)
102
+ for extra_key, extra_value in schema.items():
103
+ if extra_key != key:
104
+ merged.setdefault(extra_key, extra_value)
105
+ return merged
106
+
107
+ resolved = dict(schema)
108
+ properties = resolved.get("properties") or {}
109
+ if isinstance(properties, dict):
110
+ resolved["properties"] = {
111
+ key: _resolve_schema(document, value if isinstance(value, dict) else {})
112
+ for key, value in properties.items()
113
+ }
114
+ return resolved
115
+
116
+
117
+ def _resolve_responses(document: dict[str, Any], responses: dict[str, Any]) -> dict[str, Any]:
118
+ if not isinstance(responses, dict):
119
+ return {}
120
+
121
+ resolved: dict[str, Any] = {}
122
+ for status_code, response_obj in responses.items():
123
+ if not isinstance(response_obj, dict):
124
+ resolved[status_code] = response_obj
125
+ continue
126
+
127
+ if "$ref" in response_obj:
128
+ response_obj = _resolve_ref(document, str(response_obj["$ref"]))
129
+
130
+ resp = dict(response_obj)
131
+ content = resp.get("content") or {}
132
+ if isinstance(content, dict):
133
+ resolved_content: dict[str, Any] = {}
134
+ for media_type, media_config in content.items():
135
+ if not isinstance(media_config, dict):
136
+ resolved_content[media_type] = media_config
137
+ continue
138
+ resolved_media = dict(media_config)
139
+ schema = resolved_media.get("schema") or {}
140
+ if isinstance(schema, dict):
141
+ resolved_media["schema"] = _resolve_schema(document, schema)
142
+ resolved_content[media_type] = resolved_media
143
+ resp["content"] = resolved_content
144
+ resolved[status_code] = resp
145
+
146
+ return resolved
147
+
148
+
149
+ def _resolve_request_body(document: dict[str, Any], request_body: dict[str, Any]) -> dict[str, Any]:
150
+ if not isinstance(request_body, dict):
151
+ return {}
152
+
153
+ if "$ref" in request_body:
154
+ resolved_request_body = _resolve_ref(document, str(request_body["$ref"]))
155
+ merged_request_body = dict(resolved_request_body)
156
+ merged_request_body.update({k: v for k, v in request_body.items() if k != "$ref"})
157
+ request_body = merged_request_body
158
+
159
+ resolved_body = dict(request_body)
160
+ content = resolved_body.get("content") or {}
161
+ if not isinstance(content, dict):
162
+ return resolved_body
163
+
164
+ resolved_content: dict[str, Any] = {}
165
+ for media_type, media_config in content.items():
166
+ if not isinstance(media_config, dict):
167
+ resolved_content[media_type] = media_config
168
+ continue
169
+ resolved_media_config = dict(media_config)
170
+ schema = resolved_media_config.get("schema") or {}
171
+ if isinstance(schema, dict):
172
+ resolved_media_config["schema"] = _resolve_schema(document, schema)
173
+ resolved_content[media_type] = resolved_media_config
174
+
175
+ resolved_body["content"] = resolved_content
176
+ return resolved_body
177
+
178
+
179
+ def _fetch_openapi_schema(
180
+ client: httpx.Client, url: str, headers: dict[str, str] | None = None
181
+ ) -> dict[str, Any] | None:
182
+ """Fetch and parse an OpenAPI JSON/YAML document. Returns None on any failure."""
183
+ try:
184
+ response = client.get(url, headers=headers or {})
185
+ response.raise_for_status()
186
+ content_type = response.headers.get("content-type", "")
187
+ # Accept JSON or YAML content types; also try JSON parse for .yaml paths
188
+ if "yaml" in content_type or url.endswith(".yaml"):
189
+ try:
190
+ import yaml # type: ignore[import-untyped] # optional dep
191
+ return yaml.safe_load(response.text) # type: ignore[no-any-return]
192
+ except Exception:
193
+ pass
194
+ schema = response.json()
195
+ if not isinstance(schema, dict) or "paths" not in schema:
196
+ return None
197
+ return schema # type: ignore[return-value]
198
+ except Exception:
199
+ return None
200
+
201
+
202
+ def _endpoints_from_schema(
203
+ schema: dict[str, Any], service_name: str, service_prefix: str
204
+ ) -> list[EndpointSpec]:
205
+ endpoints: list[EndpointSpec] = []
206
+ global_security = schema.get("security", [])
207
+ for route_path, route_config in (schema.get("paths") or {}).items():
208
+ if not isinstance(route_config, dict):
209
+ continue
210
+ for method, operation in route_config.items():
211
+ if method.lower() not in HTTP_METHODS:
212
+ continue
213
+ operation = operation or {}
214
+ operation_security = operation.get("security")
215
+ requires_auth = bool(operation_security or global_security)
216
+ parameters = _parameter_specs(operation.get("parameters", []) or [])
217
+ request_body = _resolve_request_body(schema, operation.get("requestBody", {}) or {})
218
+ response_schemas = _resolve_responses(schema, operation.get("responses", {}) or {})
219
+ endpoints.append(
220
+ EndpointSpec(
221
+ service=service_name,
222
+ service_prefix=service_prefix,
223
+ path=_build_full_path(service_prefix, route_path),
224
+ method=method.upper(),
225
+ operation_id=operation.get("operationId", f"{method}_{route_path}"),
226
+ requires_auth=requires_auth,
227
+ parameters=parameters,
228
+ request_body=request_body,
229
+ response_schemas=response_schemas,
230
+ )
231
+ )
232
+ return endpoints
233
+
234
+
235
+ def discover_endpoints(
236
+ client: httpx.Client,
237
+ base_url: str,
238
+ openapi_url: str | None = None,
239
+ token: str | None = None,
240
+ ) -> list[EndpointSpec]:
241
+ """Discover API endpoints from OpenAPI specs.
242
+
243
+ Resolution order:
244
+ 1. ``openapi_url`` — explicit full URL supplied by the caller (``--openapi-url``).
245
+ 2. Common OpenAPI probe paths (``COMMON_OPENAPI_PATHS``) — fallback for arbitrary
246
+ targets that expose a standard spec location.
247
+ """
248
+ base = base_url.rstrip("/")
249
+ endpoints: list[EndpointSpec] = []
250
+ auth_hdrs = auth_headers_from_token(token)
251
+
252
+ # --- 1. Explicit openapi_url override ---
253
+ if openapi_url:
254
+ schema = _fetch_openapi_schema(client, openapi_url, headers=auth_hdrs)
255
+ if schema:
256
+ endpoints.extend(_endpoints_from_schema(schema, "api", ""))
257
+
258
+ # --- 2. Common OpenAPI path fallback ---
259
+ if not endpoints:
260
+ for openapi_path in COMMON_OPENAPI_PATHS:
261
+ schema = _fetch_openapi_schema(client, f"{base}{openapi_path}", headers=auth_hdrs)
262
+ if schema:
263
+ endpoints.extend(_endpoints_from_schema(schema, "api", ""))
264
+ break # stop at the first successfully parsed spec
265
+
266
+ deduped: dict[tuple[str, str], EndpointSpec] = {}
267
+ for endpoint in endpoints:
268
+ deduped[(endpoint.method, endpoint.path)] = endpoint
269
+ return list(deduped.values())
app_test/executor.py ADDED
@@ -0,0 +1,184 @@
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_5XX_RETRIES = 2
13
+ RETRY_BACKOFF_SECONDS = 0.35
14
+ DIAGNOSTIC_HEADER_KEYS = [
15
+ "x-correlation-id",
16
+ "x-request-id",
17
+ "x-ms-request-id",
18
+ "traceparent",
19
+ "x-amzn-trace-id",
20
+ ]
21
+
22
+
23
+ def _sample_value(schema_type: str, attack_payload: str | None = None) -> Any:
24
+ if attack_payload is not None:
25
+ return attack_payload
26
+ if schema_type == "integer":
27
+ return 1
28
+ if schema_type == "number":
29
+ return 1.0
30
+ if schema_type == "boolean":
31
+ return True
32
+ return "sample"
33
+
34
+
35
+ def _materialize_url_and_params(
36
+ base_url: str,
37
+ endpoint: EndpointSpec,
38
+ attack_payload: str | None = None,
39
+ ) -> tuple[str, dict[str, Any]]:
40
+ url = f"{base_url.rstrip('/')}{endpoint.path}"
41
+ query_params: dict[str, Any] = {}
42
+
43
+ for param in endpoint.parameters:
44
+ if param.where == "path":
45
+ token = f"{{{param.name}}}"
46
+ url = url.replace(token, str(_sample_value(param.schema_type, attack_payload)))
47
+ elif param.where == "query":
48
+ query_params[param.name] = _sample_value(param.schema_type, attack_payload)
49
+
50
+ return url, query_params
51
+
52
+
53
+ def _default_body(endpoint: EndpointSpec, attack_payload: str | None = None) -> dict[str, Any] | None:
54
+ if not endpoint.request_body:
55
+ return None
56
+
57
+ content = endpoint.request_body.get("content", {}) or {}
58
+ json_body = content.get("application/json", {}) or {}
59
+ schema = json_body.get("schema", {}) or {}
60
+ properties = schema.get("properties", {}) or {}
61
+
62
+ if not properties:
63
+ return {} if attack_payload is None else {"input": attack_payload}
64
+
65
+ body: dict[str, Any] = {}
66
+ for key, prop in properties.items():
67
+ prop_type = (prop or {}).get("type", "string")
68
+ body[key] = _sample_value(prop_type, attack_payload)
69
+ return body
70
+
71
+
72
+ def _extract_diagnostics(response: httpx.Response) -> tuple[dict[str, str], str]:
73
+ diagnostics: dict[str, str] = {}
74
+ for key in DIAGNOSTIC_HEADER_KEYS:
75
+ value = response.headers.get(key)
76
+ if value:
77
+ diagnostics[key] = value
78
+
79
+ body_text = response.text or ""
80
+ snippet = " ".join(body_text.split())
81
+ return diagnostics, snippet[:400]
82
+
83
+
84
+ def execute_endpoint(
85
+ client: httpx.Client,
86
+ endpoint: EndpointSpec,
87
+ base_url: str,
88
+ token: str | None,
89
+ category: str,
90
+ test_name: str,
91
+ include_unsafe: bool,
92
+ attack_payload: str | None = None,
93
+ auth_mode: str = "default",
94
+ auth_header_override: str | None = None,
95
+ body_override: dict[str, Any] | None = None,
96
+ form_override: dict[str, Any] | None = None,
97
+ files_override: list[tuple[str, tuple[str, bytes, str]]] | None = None,
98
+ ) -> ExecutionResult:
99
+ method = endpoint.method.upper()
100
+ if method in {"POST", "PUT", "PATCH", "DELETE"} and not include_unsafe:
101
+ return ExecutionResult(
102
+ category=category,
103
+ test_name=test_name,
104
+ service=endpoint.service,
105
+ method=method,
106
+ url=f"{base_url.rstrip('/')}{endpoint.path}",
107
+ status="skipped",
108
+ message="Unsafe HTTP method skipped (use --include-unsafe to run)",
109
+ )
110
+
111
+ url, query_params = _materialize_url_and_params(base_url, endpoint, attack_payload)
112
+ body = body_override if body_override is not None else _default_body(endpoint, attack_payload)
113
+
114
+ headers: dict[str, str] = {}
115
+ if auth_header_override is not None:
116
+ headers["Authorization"] = auth_header_override
117
+ elif auth_mode == "default" and endpoint.requires_auth and token:
118
+ headers.update(auth_headers_from_token(token))
119
+
120
+ try:
121
+ response: httpx.Response | None = None
122
+ diagnostics: dict[str, str] = {}
123
+ response_snippet = ""
124
+ retries_used = 0
125
+ elapsed_ms = 0.0
126
+
127
+ for attempt in range(MAX_5XX_RETRIES + 1):
128
+ start = time.perf_counter()
129
+ request_kwargs: dict[str, Any] = {
130
+ "method": method,
131
+ "url": url,
132
+ "params": query_params,
133
+ "headers": headers,
134
+ }
135
+ if files_override is not None:
136
+ request_kwargs["data"] = form_override or {}
137
+ request_kwargs["files"] = files_override
138
+ else:
139
+ request_kwargs["json"] = body
140
+
141
+ response = client.request(**request_kwargs)
142
+ elapsed_ms = (time.perf_counter() - start) * 1000
143
+
144
+ diagnostics, response_snippet = _extract_diagnostics(response)
145
+ if response.status_code < 500:
146
+ retries_used = attempt
147
+ break
148
+
149
+ retries_used = attempt
150
+ if attempt < MAX_5XX_RETRIES:
151
+ time.sleep(RETRY_BACKOFF_SECONDS * (attempt + 1))
152
+
153
+ if response is None:
154
+ raise RuntimeError("No response returned")
155
+
156
+ status = "pass" if response.status_code < 500 else "fail"
157
+ message = ""
158
+ if status == "fail":
159
+ message = f"HTTP {response.status_code} after {retries_used + 1} attempts"
160
+
161
+ return ExecutionResult(
162
+ category=category,
163
+ test_name=test_name,
164
+ service=endpoint.service,
165
+ method=method,
166
+ url=str(response.request.url),
167
+ status=status,
168
+ http_status=response.status_code,
169
+ latency_ms=round(elapsed_ms, 2),
170
+ message=message,
171
+ retries=retries_used,
172
+ diagnostics=diagnostics,
173
+ response_snippet=response_snippet,
174
+ )
175
+ except Exception as exc:
176
+ return ExecutionResult(
177
+ category=category,
178
+ test_name=test_name,
179
+ service=endpoint.service,
180
+ method=method,
181
+ url=url,
182
+ status="error",
183
+ message=str(exc),
184
+ )
app_test/models.py ADDED
@@ -0,0 +1,54 @@
1
+ from dataclasses import dataclass, field
2
+ from typing import Any
3
+
4
+
5
+ HTTP_METHODS = {"get", "post", "put", "patch", "delete", "head", "options"}
6
+ SAFE_HTTP_METHODS = {"get", "head", "options"}
7
+
8
+
9
+ @dataclass(slots=True)
10
+ class ParameterSpec:
11
+ name: str
12
+ where: str
13
+ required: bool
14
+ schema_type: str = "string"
15
+
16
+
17
+ @dataclass(slots=True)
18
+ class EndpointSpec:
19
+ service: str
20
+ service_prefix: str
21
+ path: str
22
+ method: str
23
+ operation_id: str
24
+ requires_auth: bool
25
+ parameters: list[ParameterSpec] = field(default_factory=list)
26
+ request_body: dict[str, Any] = field(default_factory=dict)
27
+ response_schemas: dict[str, Any] = field(default_factory=dict)
28
+
29
+
30
+ @dataclass(slots=True)
31
+ class ExecutionResult:
32
+ category: str
33
+ test_name: str
34
+ service: str
35
+ method: str
36
+ url: str
37
+ status: str
38
+ http_status: int | None = None
39
+ latency_ms: float | None = None
40
+ message: str = ""
41
+ retries: int = 0
42
+ diagnostics: dict[str, str] = field(default_factory=dict)
43
+ response_snippet: str = ""
44
+
45
+
46
+ @dataclass(slots=True)
47
+ class RunSummary:
48
+ discovered_endpoints: int
49
+ executed_tests: int
50
+ passed: int
51
+ failed: int
52
+ skipped: int
53
+ errors: int
54
+ by_category: dict[str, dict[str, int]]