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,180 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import json
5
+
6
+ import httpx
7
+
8
+ from app_test.auth import auth_headers_from_token, extract_bearer_token
9
+ from app_test.models import EndpointSpec, ExecutionResult
10
+
11
+
12
+ ADMIN_HINTS = {
13
+ "admin",
14
+ "role",
15
+ "permission",
16
+ "rbac",
17
+ "tenant-admin",
18
+ "superuser",
19
+ }
20
+ ADMIN_ROLE_HINTS = {
21
+ "admin",
22
+ "superadmin",
23
+ "super_admin",
24
+ "tenant_admin",
25
+ "owner",
26
+ "root",
27
+ }
28
+ SAFE_METHODS = {"GET", "HEAD", "OPTIONS"}
29
+ MAX_TARGETS = 20
30
+
31
+
32
+ def _sample_value(schema_type: str) -> str | int | float | bool:
33
+ if schema_type == "integer":
34
+ return 1
35
+ if schema_type == "number":
36
+ return 1.0
37
+ if schema_type == "boolean":
38
+ return True
39
+ return "sample"
40
+
41
+
42
+ def _materialize_url(base_url: str, endpoint: EndpointSpec) -> tuple[str, dict[str, str | int | float | bool]]:
43
+ url = f"{base_url.rstrip('/')}{endpoint.path}"
44
+ query_params: dict[str, str | int | float | bool] = {}
45
+
46
+ for param in endpoint.parameters:
47
+ sample = _sample_value(param.schema_type)
48
+ if param.where == "path":
49
+ url = url.replace(f"{{{param.name}}}", str(sample))
50
+ elif param.where == "query":
51
+ query_params[param.name] = sample
52
+
53
+ return url, query_params
54
+
55
+
56
+ def _looks_like_admin_endpoint(endpoint: EndpointSpec) -> bool:
57
+ if endpoint.method.upper() not in SAFE_METHODS or not endpoint.requires_auth:
58
+ return False
59
+
60
+ path = endpoint.path.lower()
61
+ operation_id = (endpoint.operation_id or "").lower()
62
+ return any(hint in path or hint in operation_id for hint in ADMIN_HINTS)
63
+
64
+
65
+ def _decode_token_claims(token: str) -> dict[str, object]:
66
+ if token.count(".") != 2:
67
+ return {}
68
+
69
+ payload = token.split(".")[1]
70
+ padding = "=" * (-len(payload) % 4)
71
+ try:
72
+ decoded = base64.urlsafe_b64decode(f"{payload}{padding}")
73
+ claims = json.loads(decoded.decode("utf-8"))
74
+ return claims if isinstance(claims, dict) else {}
75
+ except Exception:
76
+ return {}
77
+
78
+
79
+ def _extract_roles_from_claims(claims: dict[str, object]) -> set[str]:
80
+ roles: set[str] = set()
81
+ for key in ("role", "roles", "permissions", "groups", "scope", "scp"):
82
+ value = claims.get(key)
83
+ if isinstance(value, str):
84
+ roles.update(part.strip().lower() for part in value.replace(",", " ").split() if part.strip())
85
+ elif isinstance(value, list):
86
+ for item in value:
87
+ if isinstance(item, str) and item.strip():
88
+ roles.add(item.strip().lower())
89
+ return roles
90
+
91
+
92
+ def _principal_appears_admin(token: str) -> bool:
93
+ bearer_token = extract_bearer_token(token)
94
+ if not bearer_token:
95
+ return False
96
+ claims = _decode_token_claims(bearer_token)
97
+ roles = _extract_roles_from_claims(claims)
98
+ return any(role in ADMIN_ROLE_HINTS for role in roles)
99
+
100
+
101
+ def _skip_result(base_url: str, message: str) -> list[ExecutionResult]:
102
+ return [
103
+ ExecutionResult(
104
+ category="privilege_escalation",
105
+ test_name="privileged_endpoint_access_check",
106
+ service="gateway",
107
+ method="GET",
108
+ url=base_url.rstrip("/"),
109
+ status="skipped",
110
+ message=message,
111
+ )
112
+ ]
113
+
114
+
115
+ def _probe_admin_endpoint(
116
+ client: httpx.Client,
117
+ base_url: str,
118
+ token: str,
119
+ endpoint: EndpointSpec,
120
+ ) -> ExecutionResult:
121
+ url, query_params = _materialize_url(base_url, endpoint)
122
+ headers = auth_headers_from_token(token)
123
+ try:
124
+ response = client.request(
125
+ method=endpoint.method.upper(),
126
+ url=url,
127
+ params=query_params,
128
+ headers=headers,
129
+ )
130
+ status_code = response.status_code
131
+
132
+ if status_code in {401, 403, 404}:
133
+ status = "pass"
134
+ message = "Likely privileged endpoint was not accessible to the current token"
135
+ elif 200 <= status_code < 300:
136
+ status = "fail"
137
+ message = "Likely privileged endpoint returned success for the current token"
138
+ else:
139
+ status = "pass"
140
+ message = f"Likely privileged endpoint returned non-success status ({status_code})"
141
+
142
+ return ExecutionResult(
143
+ category="privilege_escalation",
144
+ test_name="privileged_endpoint_access_check",
145
+ service=endpoint.service,
146
+ method=endpoint.method.upper(),
147
+ url=str(response.request.url),
148
+ status=status,
149
+ http_status=status_code,
150
+ message=message,
151
+ )
152
+ except Exception as exc:
153
+ return ExecutionResult(
154
+ category="privilege_escalation",
155
+ test_name="privileged_endpoint_access_check",
156
+ service=endpoint.service,
157
+ method=endpoint.method.upper(),
158
+ url=url,
159
+ status="error",
160
+ message=str(exc),
161
+ )
162
+
163
+
164
+ def run(
165
+ client: httpx.Client,
166
+ base_url: str,
167
+ token: str,
168
+ endpoints: list[EndpointSpec],
169
+ include_unsafe: bool,
170
+ ) -> list[ExecutionResult]:
171
+ del include_unsafe
172
+
173
+ targets = [endpoint for endpoint in endpoints if _looks_like_admin_endpoint(endpoint)][:MAX_TARGETS]
174
+ if not targets:
175
+ return _skip_result(base_url, "No likely privileged safe endpoints discovered for privilege escalation checks")
176
+
177
+ if _principal_appears_admin(token):
178
+ return _skip_result(base_url, "Current access token appears admin-privileged; skipping privilege escalation checks to avoid false positives")
179
+
180
+ return [_probe_admin_endpoint(client, base_url, token, endpoint) for endpoint in targets]
@@ -0,0 +1,240 @@
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, ExecutionResult, ParameterSpec
9
+
10
+
11
+ BURST_REQUEST_COUNT = 12
12
+ MAX_BURST_TARGETS = 6
13
+ MAX_WINDOW_TARGETS = 6
14
+ RATE_LIMIT_HINTS = {
15
+ "dashboard",
16
+ "report",
17
+ "reports",
18
+ "scan",
19
+ "scans",
20
+ "risk",
21
+ "heatmap",
22
+ "audit",
23
+ "application",
24
+ "applications",
25
+ "export",
26
+ "tests",
27
+ "nodes",
28
+ "files",
29
+ "models",
30
+ "prompts",
31
+ "datastores",
32
+ }
33
+ WINDOW_PARAM_HINTS = {"page_size", "limit", "offset", "days"}
34
+ SAFE_REQUIRED_QUERY_PARAMS = {"page", "page_size", "limit", "offset", "days", "time_range"}
35
+
36
+
37
+ def _sample_value(param: ParameterSpec, override: dict[str, Any] | None = None) -> Any:
38
+ if override and param.name in override:
39
+ return override[param.name]
40
+ if param.name == "page":
41
+ return 1
42
+ if param.name == "page_size":
43
+ return 10
44
+ if param.name == "limit":
45
+ return 20
46
+ if param.name == "offset":
47
+ return 0
48
+ if param.name == "days":
49
+ return 30
50
+ if param.name == "time_range":
51
+ return "30d"
52
+ if param.schema_type == "integer":
53
+ return 1
54
+ if param.schema_type == "number":
55
+ return 1.0
56
+ if param.schema_type == "boolean":
57
+ return True
58
+ if param.name.endswith("_id"):
59
+ return "sample"
60
+ return "sample"
61
+
62
+
63
+ def _materialize_url_and_params(
64
+ base_url: str,
65
+ endpoint: EndpointSpec,
66
+ override: dict[str, Any] | None = None,
67
+ ) -> tuple[str, dict[str, Any]]:
68
+ url = f"{base_url.rstrip('/')}{endpoint.path}"
69
+ query_params: dict[str, Any] = {}
70
+ for param in endpoint.parameters:
71
+ sample = _sample_value(param, override)
72
+ if param.where == "path":
73
+ url = url.replace(f"{{{param.name}}}", str(sample))
74
+ elif param.where == "query":
75
+ query_params[param.name] = sample
76
+ return url, query_params
77
+
78
+
79
+ def _is_rate_probe_candidate(endpoint: EndpointSpec) -> bool:
80
+ if endpoint.method.upper() != "GET":
81
+ return False
82
+ if not endpoint.requires_auth:
83
+ return False
84
+ if any(param.where == "path" for param in endpoint.parameters):
85
+ return False
86
+ if any(
87
+ param.where == "query" and param.required and param.name not in SAFE_REQUIRED_QUERY_PARAMS
88
+ for param in endpoint.parameters
89
+ ):
90
+ return False
91
+ lowered = f"{endpoint.path} {(endpoint.operation_id or '')}".lower()
92
+ if any(hint in lowered for hint in RATE_LIMIT_HINTS):
93
+ return True
94
+ return any(param.name in WINDOW_PARAM_HINTS for param in endpoint.parameters if param.where == "query")
95
+
96
+
97
+ def _burst_candidates(endpoints: list[EndpointSpec]) -> list[EndpointSpec]:
98
+ return [endpoint for endpoint in endpoints if _is_rate_probe_candidate(endpoint)][:MAX_BURST_TARGETS]
99
+
100
+
101
+ def _window_candidates(endpoints: list[EndpointSpec]) -> list[EndpointSpec]:
102
+ return [
103
+ endpoint
104
+ for endpoint in endpoints
105
+ if _is_rate_probe_candidate(endpoint)
106
+ and any(param.name in WINDOW_PARAM_HINTS for param in endpoint.parameters if param.where == "query")
107
+ ][:MAX_WINDOW_TARGETS]
108
+
109
+
110
+ def _burst_probe(client: httpx.Client, base_url: str, token: str, endpoint: EndpointSpec) -> ExecutionResult:
111
+ url, query_params = _materialize_url_and_params(base_url, endpoint)
112
+ headers = auth_headers_from_token(token)
113
+ statuses: list[int] = []
114
+ retry_after_seen = False
115
+ try:
116
+ for _ in range(BURST_REQUEST_COUNT):
117
+ response = client.get(url, params=query_params, headers=headers)
118
+ statuses.append(response.status_code)
119
+ if response.headers.get("Retry-After"):
120
+ retry_after_seen = True
121
+
122
+ if any(status == 429 for status in statuses) or retry_after_seen:
123
+ status = "pass"
124
+ message = f"Observed throttling signal during burst probe: statuses={statuses}"
125
+ elif any(status >= 500 for status in statuses):
126
+ status = "fail"
127
+ message = f"Burst probe triggered server instability: statuses={statuses}"
128
+ else:
129
+ status = "skipped"
130
+ message = f"Burst probe completed without throttle signal or server failure: statuses={statuses}"
131
+
132
+ return ExecutionResult(
133
+ category="rate_limit_and_resource_abuse",
134
+ test_name="burst_rate_limit_signal_check",
135
+ service=endpoint.service,
136
+ method="GET",
137
+ url=str(response.request.url),
138
+ status=status,
139
+ http_status=statuses[-1] if statuses else None,
140
+ message=message,
141
+ )
142
+ except Exception as exc:
143
+ return ExecutionResult(
144
+ category="rate_limit_and_resource_abuse",
145
+ test_name="burst_rate_limit_signal_check",
146
+ service=endpoint.service,
147
+ method="GET",
148
+ url=url,
149
+ status="error",
150
+ message=str(exc),
151
+ )
152
+
153
+
154
+ def _window_override(endpoint: EndpointSpec) -> dict[str, Any]:
155
+ override: dict[str, Any] = {}
156
+ for param in endpoint.parameters:
157
+ if param.where != "query":
158
+ continue
159
+ if param.name == "page_size":
160
+ override[param.name] = 1000000
161
+ elif param.name == "limit":
162
+ override[param.name] = 1000000
163
+ elif param.name == "offset":
164
+ override[param.name] = 1000000
165
+ elif param.name == "days":
166
+ override[param.name] = 5000
167
+ return override
168
+
169
+
170
+ def _oversized_window_probe(client: httpx.Client, base_url: str, token: str, endpoint: EndpointSpec) -> ExecutionResult:
171
+ override = _window_override(endpoint)
172
+ url, query_params = _materialize_url_and_params(base_url, endpoint, override)
173
+ headers = auth_headers_from_token(token)
174
+ try:
175
+ response = client.get(url, params=query_params, headers=headers)
176
+ if response.status_code in {400, 413, 414, 422}:
177
+ status = "pass"
178
+ message = f"Oversized pagination or range request was rejected ({response.status_code})"
179
+ elif response.status_code >= 500:
180
+ status = "fail"
181
+ message = f"Oversized pagination or range request triggered server-side failure ({response.status_code})"
182
+ elif 200 <= response.status_code < 300:
183
+ status = "skipped"
184
+ message = "Oversized pagination or range request succeeded without explicit rejection or degradation"
185
+ else:
186
+ status = "pass"
187
+ message = f"Oversized pagination or range request returned non-success status ({response.status_code})"
188
+
189
+ return ExecutionResult(
190
+ category="rate_limit_and_resource_abuse",
191
+ test_name="oversized_pagination_window_check",
192
+ service=endpoint.service,
193
+ method="GET",
194
+ url=str(response.request.url),
195
+ status=status,
196
+ http_status=response.status_code,
197
+ message=message,
198
+ )
199
+ except Exception as exc:
200
+ return ExecutionResult(
201
+ category="rate_limit_and_resource_abuse",
202
+ test_name="oversized_pagination_window_check",
203
+ service=endpoint.service,
204
+ method="GET",
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
+ burst_targets = _burst_candidates(endpoints)
221
+ window_targets = _window_candidates(endpoints)
222
+ if not burst_targets and not window_targets:
223
+ return [
224
+ ExecutionResult(
225
+ category="rate_limit_and_resource_abuse",
226
+ test_name="rate_limit_target_discovery",
227
+ service="gateway",
228
+ method="GET",
229
+ url=base_url.rstrip("/"),
230
+ status="skipped",
231
+ message="No authenticated list, dashboard, report, or status endpoints were discovered for rate-limit and resource-abuse checks",
232
+ )
233
+ ]
234
+
235
+ results: list[ExecutionResult] = []
236
+ for endpoint in burst_targets:
237
+ results.append(_burst_probe(client, base_url, token, endpoint))
238
+ for endpoint in window_targets:
239
+ results.append(_oversized_window_probe(client, base_url, token, endpoint))
240
+ return results