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.
- api_gate_keeper-0.1.0.dist-info/METADATA +654 -0
- api_gate_keeper-0.1.0.dist-info/RECORD +35 -0
- api_gate_keeper-0.1.0.dist-info/WHEEL +5 -0
- api_gate_keeper-0.1.0.dist-info/entry_points.txt +2 -0
- api_gate_keeper-0.1.0.dist-info/licenses/LICENSE +21 -0
- api_gate_keeper-0.1.0.dist-info/top_level.txt +1 -0
- app_test/__init__.py +2 -0
- app_test/auth.py +107 -0
- app_test/categories/__init__.py +24 -0
- app_test/categories/auth_robustness.py +186 -0
- app_test/categories/authz.py +119 -0
- app_test/categories/baseline.py +29 -0
- app_test/categories/bola_matrix.py +340 -0
- app_test/categories/contract_conformance.py +249 -0
- app_test/categories/error_leakage_and_debug_surface.py +270 -0
- app_test/categories/file_upload_security.py +302 -0
- app_test/categories/jwt_security.py +261 -0
- app_test/categories/mass_assignment.py +200 -0
- app_test/categories/owasp.py +127 -0
- app_test/categories/pen_test.py +37 -0
- app_test/categories/privilege_escalation.py +180 -0
- app_test/categories/rate_limit_and_resource_abuse.py +240 -0
- app_test/categories/schema_contract_and_validation.py +297 -0
- app_test/categories/security_misc.py +99 -0
- app_test/categories/soak_profile.py +255 -0
- app_test/categories/sql_injection.py +36 -0
- app_test/categories/ssrf_and_redirects.py +280 -0
- app_test/categories/token_security.py +195 -0
- app_test/categories/workflow_chains.py +437 -0
- app_test/cli.py +1085 -0
- app_test/config.py +19 -0
- app_test/discovery.py +269 -0
- app_test/executor.py +184 -0
- app_test/models.py +54 -0
- app_test/report.py +628 -0
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import time
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from app_test.auth import auth_headers_from_token
|
|
10
|
+
from app_test.models import EndpointSpec, ExecutionResult
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
MAX_IDS_PER_SERVICE = 5
|
|
14
|
+
MAX_PROBE_ENDPOINTS = 20
|
|
15
|
+
|
|
16
|
+
# Regex matchers for ID shapes
|
|
17
|
+
_UUID_RE = re.compile(
|
|
18
|
+
r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
|
|
19
|
+
re.IGNORECASE,
|
|
20
|
+
)
|
|
21
|
+
_NUMERIC_RE = re.compile(r"^\d{1,20}$")
|
|
22
|
+
|
|
23
|
+
# Fields considered to carry object IDs in JSON responses
|
|
24
|
+
_ID_FIELD_NAMES = frozenset({"id", "uuid", "identifier", "object_id", "resource_id"})
|
|
25
|
+
|
|
26
|
+
# Path-segment keywords that suggest an endpoint accepts an object ID
|
|
27
|
+
_ID_PATH_HINTS = frozenset({
|
|
28
|
+
"id", "user", "account", "tenant", "org", "customer", "project",
|
|
29
|
+
"scan", "asset", "policy", "finding", "report", "rule",
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
# Common wrapper keys for paginated/list API responses
|
|
33
|
+
_LIST_WRAPPER_KEYS = ("items", "data", "results", "records", "assets", "scans", "objects", "findings")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# ---------------------------------------------------------------------------
|
|
37
|
+
# Phase 1: ID harvesting from collection endpoints
|
|
38
|
+
# ---------------------------------------------------------------------------
|
|
39
|
+
|
|
40
|
+
def _is_collection_endpoint(endpoint: EndpointSpec) -> bool:
|
|
41
|
+
"""GET endpoint with no path parameters — likely a list/collection."""
|
|
42
|
+
if endpoint.method.upper() != "GET":
|
|
43
|
+
return False
|
|
44
|
+
return not any(p.where == "path" for p in endpoint.parameters)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _looks_like_id_value(value: Any) -> bool:
|
|
48
|
+
if isinstance(value, int) and 1 <= value < 2**53:
|
|
49
|
+
return True
|
|
50
|
+
if isinstance(value, str) and value:
|
|
51
|
+
return bool(_UUID_RE.match(value) or _NUMERIC_RE.match(value))
|
|
52
|
+
return False
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _extract_ids_from_json(body: Any) -> list[str]:
|
|
56
|
+
"""Return up to MAX_IDS_PER_SERVICE ID-like strings from a parsed JSON body."""
|
|
57
|
+
items: list[Any] = []
|
|
58
|
+
|
|
59
|
+
if isinstance(body, list):
|
|
60
|
+
items = body[:10]
|
|
61
|
+
elif isinstance(body, dict):
|
|
62
|
+
for key in _LIST_WRAPPER_KEYS:
|
|
63
|
+
val = body.get(key)
|
|
64
|
+
if isinstance(val, list) and val:
|
|
65
|
+
items = val[:10]
|
|
66
|
+
break
|
|
67
|
+
if not items:
|
|
68
|
+
items = [body]
|
|
69
|
+
|
|
70
|
+
ids: list[str] = []
|
|
71
|
+
for item in items:
|
|
72
|
+
if not isinstance(item, dict):
|
|
73
|
+
continue
|
|
74
|
+
for field, value in item.items():
|
|
75
|
+
fl = field.lower()
|
|
76
|
+
if fl in _ID_FIELD_NAMES or fl.endswith("_id") or fl.endswith("id"):
|
|
77
|
+
if _looks_like_id_value(value):
|
|
78
|
+
ids.append(str(value))
|
|
79
|
+
if len(ids) >= MAX_IDS_PER_SERVICE:
|
|
80
|
+
break
|
|
81
|
+
|
|
82
|
+
return list(dict.fromkeys(ids))[:MAX_IDS_PER_SERVICE]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _harvest_ids(
|
|
86
|
+
client: httpx.Client,
|
|
87
|
+
base_url: str,
|
|
88
|
+
endpoints: list[EndpointSpec],
|
|
89
|
+
token: str | None,
|
|
90
|
+
) -> dict[str, list[str]]:
|
|
91
|
+
"""Return a mapping of service → list of real ID strings."""
|
|
92
|
+
headers = auth_headers_from_token(token) if token else {}
|
|
93
|
+
by_service: dict[str, list[str]] = {}
|
|
94
|
+
seen_services: set[str] = set()
|
|
95
|
+
|
|
96
|
+
for ep in endpoints:
|
|
97
|
+
if not _is_collection_endpoint(ep):
|
|
98
|
+
continue
|
|
99
|
+
if ep.service in seen_services:
|
|
100
|
+
continue
|
|
101
|
+
|
|
102
|
+
url = f"{base_url.rstrip('/')}{ep.path}"
|
|
103
|
+
try:
|
|
104
|
+
resp = client.get(url, headers=headers)
|
|
105
|
+
if resp.status_code == 200:
|
|
106
|
+
body = resp.json()
|
|
107
|
+
ids = _extract_ids_from_json(body)
|
|
108
|
+
if ids:
|
|
109
|
+
by_service[ep.service] = ids
|
|
110
|
+
seen_services.add(ep.service)
|
|
111
|
+
except Exception:
|
|
112
|
+
pass
|
|
113
|
+
|
|
114
|
+
return by_service
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
# ---------------------------------------------------------------------------
|
|
118
|
+
# Phase 2: endpoint selection
|
|
119
|
+
# ---------------------------------------------------------------------------
|
|
120
|
+
|
|
121
|
+
def _looks_like_id_path(endpoint: EndpointSpec) -> bool:
|
|
122
|
+
if "{" not in endpoint.path or "}" not in endpoint.path:
|
|
123
|
+
return False
|
|
124
|
+
path_lower = endpoint.path.lower()
|
|
125
|
+
return any(hint in path_lower for hint in _ID_PATH_HINTS)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _substitute_id(base_url: str, endpoint: EndpointSpec, id_value: str) -> str:
|
|
129
|
+
path = endpoint.path
|
|
130
|
+
for param in endpoint.parameters:
|
|
131
|
+
if param.where == "path":
|
|
132
|
+
path = path.replace(f"{{{param.name}}}", id_value)
|
|
133
|
+
return f"{base_url.rstrip('/')}{path}"
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
# ---------------------------------------------------------------------------
|
|
137
|
+
# Phase 3: ID mutation
|
|
138
|
+
# ---------------------------------------------------------------------------
|
|
139
|
+
|
|
140
|
+
def _neighbor_id(id_value: str) -> str | None:
|
|
141
|
+
"""Return a predictably adjacent ID: numeric+1, or UUID with last hex char rotated."""
|
|
142
|
+
if _NUMERIC_RE.match(id_value):
|
|
143
|
+
n = int(id_value)
|
|
144
|
+
return str(n + 1) if n < 2**31 - 1 else str(n - 1)
|
|
145
|
+
|
|
146
|
+
if _UUID_RE.match(id_value):
|
|
147
|
+
chars = list(id_value.lower())
|
|
148
|
+
for i in range(len(chars) - 1, -1, -1):
|
|
149
|
+
c = chars[i]
|
|
150
|
+
if c in "0123456789abcdef":
|
|
151
|
+
rotated = format((int(c, 16) + 1) % 16, "x")
|
|
152
|
+
if rotated != c:
|
|
153
|
+
chars[i] = rotated
|
|
154
|
+
return "".join(chars)
|
|
155
|
+
|
|
156
|
+
return None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
# ---------------------------------------------------------------------------
|
|
160
|
+
# Probe execution
|
|
161
|
+
# ---------------------------------------------------------------------------
|
|
162
|
+
|
|
163
|
+
def _make_result(
|
|
164
|
+
endpoint: EndpointSpec,
|
|
165
|
+
url: str,
|
|
166
|
+
test_name: str,
|
|
167
|
+
status: str,
|
|
168
|
+
http_status: int | None,
|
|
169
|
+
latency_ms: float | None,
|
|
170
|
+
message: str,
|
|
171
|
+
snippet: str = "",
|
|
172
|
+
) -> ExecutionResult:
|
|
173
|
+
return ExecutionResult(
|
|
174
|
+
category="bola_matrix",
|
|
175
|
+
test_name=test_name,
|
|
176
|
+
service=endpoint.service,
|
|
177
|
+
method="GET",
|
|
178
|
+
url=url,
|
|
179
|
+
status=status,
|
|
180
|
+
http_status=http_status,
|
|
181
|
+
latency_ms=latency_ms,
|
|
182
|
+
message=message,
|
|
183
|
+
response_snippet=snippet,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _get_probe(
|
|
188
|
+
client: httpx.Client,
|
|
189
|
+
base_url: str,
|
|
190
|
+
endpoint: EndpointSpec,
|
|
191
|
+
token: str | None,
|
|
192
|
+
id_value: str,
|
|
193
|
+
test_name: str,
|
|
194
|
+
fail_message: str,
|
|
195
|
+
pass_404_message: str,
|
|
196
|
+
) -> ExecutionResult:
|
|
197
|
+
url = _substitute_id(base_url, endpoint, id_value)
|
|
198
|
+
headers = auth_headers_from_token(token) if token else {}
|
|
199
|
+
|
|
200
|
+
t0 = time.monotonic()
|
|
201
|
+
try:
|
|
202
|
+
resp = client.get(url, headers=headers)
|
|
203
|
+
except Exception as exc:
|
|
204
|
+
return _make_result(endpoint, url, test_name, "error", None, None, str(exc))
|
|
205
|
+
|
|
206
|
+
latency_ms = (time.monotonic() - t0) * 1000
|
|
207
|
+
http_status = resp.status_code
|
|
208
|
+
snippet = " ".join(resp.text.split())[:400]
|
|
209
|
+
|
|
210
|
+
if http_status in {401, 403}:
|
|
211
|
+
msg = f"Access denied ({http_status}) — authorization check enforced"
|
|
212
|
+
return _make_result(endpoint, url, test_name, "pass", http_status, latency_ms, msg)
|
|
213
|
+
|
|
214
|
+
if http_status == 404:
|
|
215
|
+
return _make_result(endpoint, url, test_name, "pass", http_status, latency_ms, pass_404_message)
|
|
216
|
+
|
|
217
|
+
if 200 <= http_status < 300:
|
|
218
|
+
return _make_result(endpoint, url, test_name, "fail", http_status, latency_ms, fail_message, snippet)
|
|
219
|
+
|
|
220
|
+
msg = f"Non-success status {http_status}"
|
|
221
|
+
return _make_result(endpoint, url, test_name, "pass", http_status, latency_ms, msg)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
# ---------------------------------------------------------------------------
|
|
225
|
+
# Category entry point
|
|
226
|
+
# ---------------------------------------------------------------------------
|
|
227
|
+
|
|
228
|
+
def run(
|
|
229
|
+
client: httpx.Client,
|
|
230
|
+
base_url: str,
|
|
231
|
+
token: str | None,
|
|
232
|
+
endpoints: list[EndpointSpec],
|
|
233
|
+
include_unsafe: bool,
|
|
234
|
+
) -> list[ExecutionResult]:
|
|
235
|
+
del include_unsafe # bola_matrix is always read-only
|
|
236
|
+
|
|
237
|
+
# --- Phase 1: harvest real IDs from collection endpoints ---
|
|
238
|
+
id_pool = _harvest_ids(client, base_url, endpoints, token)
|
|
239
|
+
|
|
240
|
+
if not id_pool:
|
|
241
|
+
return [
|
|
242
|
+
ExecutionResult(
|
|
243
|
+
category="bola_matrix",
|
|
244
|
+
test_name="bola_matrix_id_harvest",
|
|
245
|
+
service="gateway",
|
|
246
|
+
method="GET",
|
|
247
|
+
url=base_url.rstrip("/"),
|
|
248
|
+
status="skipped",
|
|
249
|
+
message=(
|
|
250
|
+
"No real object IDs could be harvested from collection endpoints; "
|
|
251
|
+
"BOLA matrix checks skipped"
|
|
252
|
+
),
|
|
253
|
+
)
|
|
254
|
+
]
|
|
255
|
+
|
|
256
|
+
all_ids = [v for vals in id_pool.values() for v in vals]
|
|
257
|
+
|
|
258
|
+
# --- Phase 2: select probe endpoints ---
|
|
259
|
+
probe_endpoints = [
|
|
260
|
+
ep
|
|
261
|
+
for ep in endpoints
|
|
262
|
+
if ep.method.upper() == "GET"
|
|
263
|
+
and ep.requires_auth
|
|
264
|
+
and _looks_like_id_path(ep)
|
|
265
|
+
and any(p.where == "path" for p in ep.parameters)
|
|
266
|
+
][:MAX_PROBE_ENDPOINTS]
|
|
267
|
+
|
|
268
|
+
if not probe_endpoints:
|
|
269
|
+
return [
|
|
270
|
+
ExecutionResult(
|
|
271
|
+
category="bola_matrix",
|
|
272
|
+
test_name="bola_matrix_target_discovery",
|
|
273
|
+
service="gateway",
|
|
274
|
+
method="GET",
|
|
275
|
+
url=base_url.rstrip("/"),
|
|
276
|
+
status="skipped",
|
|
277
|
+
message=(
|
|
278
|
+
"No authenticated GET endpoints with path ID parameters found "
|
|
279
|
+
"for BOLA matrix probes"
|
|
280
|
+
),
|
|
281
|
+
)
|
|
282
|
+
]
|
|
283
|
+
|
|
284
|
+
results: list[ExecutionResult] = []
|
|
285
|
+
|
|
286
|
+
for endpoint in probe_endpoints:
|
|
287
|
+
# --- Probe 1: same-service neighbor ID enumeration ---
|
|
288
|
+
same_service_ids = id_pool.get(endpoint.service, [])
|
|
289
|
+
if same_service_ids:
|
|
290
|
+
real_id = same_service_ids[0]
|
|
291
|
+
neighbor = _neighbor_id(real_id)
|
|
292
|
+
if neighbor and neighbor != real_id:
|
|
293
|
+
results.append(
|
|
294
|
+
_get_probe(
|
|
295
|
+
client, base_url, endpoint, token, neighbor,
|
|
296
|
+
"bola_neighbor_id_enumeration",
|
|
297
|
+
(
|
|
298
|
+
f"Adjacent ID {neighbor!r} (neighbor of harvested {real_id!r}) "
|
|
299
|
+
f"returned success — object IDs appear predictable and enumerable "
|
|
300
|
+
f"(potential BOLA/IDOR)"
|
|
301
|
+
),
|
|
302
|
+
f"Adjacent ID {neighbor!r} not found — object IDs are not trivially enumerable",
|
|
303
|
+
)
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
# --- Probe 2: cross-service object reference ---
|
|
307
|
+
other_services = [svc for svc in id_pool if svc != endpoint.service]
|
|
308
|
+
if other_services:
|
|
309
|
+
other_svc = other_services[0]
|
|
310
|
+
other_id = id_pool[other_svc][0]
|
|
311
|
+
results.append(
|
|
312
|
+
_get_probe(
|
|
313
|
+
client, base_url, endpoint, token, other_id,
|
|
314
|
+
"bola_cross_service_id_probe",
|
|
315
|
+
(
|
|
316
|
+
f"Cross-service ID {other_id!r} from {other_svc!r} returned "
|
|
317
|
+
f"success on {endpoint.service!r} endpoint — potential cross-domain BOLA"
|
|
318
|
+
),
|
|
319
|
+
f"Cross-service ID {other_id!r} not accessible in {endpoint.service!r} (correctly isolated)",
|
|
320
|
+
)
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
# --- Probe 3: UUID variant probe ---
|
|
324
|
+
uuid_ids = [i for i in all_ids if _UUID_RE.match(i)]
|
|
325
|
+
if uuid_ids:
|
|
326
|
+
variant = _neighbor_id(uuid_ids[0])
|
|
327
|
+
if variant and variant != uuid_ids[0]:
|
|
328
|
+
results.append(
|
|
329
|
+
_get_probe(
|
|
330
|
+
client, base_url, endpoint, token, variant,
|
|
331
|
+
"bola_uuid_variant_probe",
|
|
332
|
+
(
|
|
333
|
+
f"UUID variant {variant!r} returned success — UUIDs may be "
|
|
334
|
+
f"guessable or reveal sequential allocation (potential BOLA)"
|
|
335
|
+
),
|
|
336
|
+
f"UUID variant {variant!r} was not accessible (correct)",
|
|
337
|
+
)
|
|
338
|
+
)
|
|
339
|
+
|
|
340
|
+
return results
|
|
@@ -0,0 +1,249 @@
|
|
|
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.executor import _materialize_url_and_params
|
|
10
|
+
from app_test.models import EndpointSpec, ExecutionResult
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
MAX_CONFORMANCE_TARGETS = 25
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# ---------------------------------------------------------------------------
|
|
17
|
+
# Helpers: endpoint filtering
|
|
18
|
+
# ---------------------------------------------------------------------------
|
|
19
|
+
|
|
20
|
+
def _safe_targets_with_schema(endpoints: list[EndpointSpec]) -> list[EndpointSpec]:
|
|
21
|
+
return [
|
|
22
|
+
ep
|
|
23
|
+
for ep in endpoints
|
|
24
|
+
if ep.method.upper() in {"GET", "HEAD", "OPTIONS"} and ep.response_schemas
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# ---------------------------------------------------------------------------
|
|
29
|
+
# Helpers: OpenAPI response schema extraction
|
|
30
|
+
# ---------------------------------------------------------------------------
|
|
31
|
+
|
|
32
|
+
def _declared_status_codes(response_schemas: dict[str, Any]) -> set[str]:
|
|
33
|
+
return set(response_schemas.keys())
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _matches_declared_status(actual: int, declared: set[str]) -> bool:
|
|
37
|
+
if str(actual) in declared:
|
|
38
|
+
return True
|
|
39
|
+
if str(actual)[0] + "XX" in declared:
|
|
40
|
+
return True
|
|
41
|
+
return "default" in declared
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _response_obj_for_status(response_schemas: dict[str, Any], actual_status: int) -> dict[str, Any] | None:
|
|
45
|
+
status_str = str(actual_status)
|
|
46
|
+
obj = response_schemas.get(status_str)
|
|
47
|
+
if obj is None:
|
|
48
|
+
obj = response_schemas.get(status_str[0] + "XX")
|
|
49
|
+
if obj is None:
|
|
50
|
+
obj = response_schemas.get("default")
|
|
51
|
+
return obj if isinstance(obj, dict) else None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _json_schema_from_response_obj(response_obj: dict[str, Any]) -> dict[str, Any]:
|
|
55
|
+
content = response_obj.get("content") or {}
|
|
56
|
+
json_content = content.get("application/json") or {}
|
|
57
|
+
schema = json_content.get("schema") or {}
|
|
58
|
+
return schema if isinstance(schema, dict) else {}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _properties(schema: dict[str, Any]) -> dict[str, Any] | None:
|
|
62
|
+
props = schema.get("properties")
|
|
63
|
+
return props if isinstance(props, dict) and props else None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _required_fields(schema: dict[str, Any]) -> list[str]:
|
|
67
|
+
req = schema.get("required")
|
|
68
|
+
return [f for f in req if isinstance(f, str)] if isinstance(req, list) else []
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# ---------------------------------------------------------------------------
|
|
72
|
+
# Result builder
|
|
73
|
+
# ---------------------------------------------------------------------------
|
|
74
|
+
|
|
75
|
+
def _result(
|
|
76
|
+
endpoint: EndpointSpec,
|
|
77
|
+
base_url: str,
|
|
78
|
+
test_name: str,
|
|
79
|
+
status: str,
|
|
80
|
+
http_status: int | None,
|
|
81
|
+
latency_ms: float | None,
|
|
82
|
+
message: str,
|
|
83
|
+
snippet: str = "",
|
|
84
|
+
) -> ExecutionResult:
|
|
85
|
+
return ExecutionResult(
|
|
86
|
+
category="contract_conformance",
|
|
87
|
+
test_name=test_name,
|
|
88
|
+
service=endpoint.service,
|
|
89
|
+
method=endpoint.method,
|
|
90
|
+
url=f"{base_url.rstrip('/')}{endpoint.path}",
|
|
91
|
+
status=status,
|
|
92
|
+
http_status=http_status,
|
|
93
|
+
latency_ms=latency_ms,
|
|
94
|
+
message=message,
|
|
95
|
+
response_snippet=snippet[:400],
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# ---------------------------------------------------------------------------
|
|
100
|
+
# Per-endpoint probe set
|
|
101
|
+
# ---------------------------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
def _probe(
|
|
104
|
+
client: httpx.Client,
|
|
105
|
+
endpoint: EndpointSpec,
|
|
106
|
+
base_url: str,
|
|
107
|
+
token: str | None,
|
|
108
|
+
) -> list[ExecutionResult]:
|
|
109
|
+
url, query_params = _materialize_url_and_params(base_url, endpoint)
|
|
110
|
+
headers: dict[str, str] = {}
|
|
111
|
+
if token:
|
|
112
|
+
headers.update(auth_headers_from_token(token))
|
|
113
|
+
|
|
114
|
+
t0 = time.monotonic()
|
|
115
|
+
try:
|
|
116
|
+
resp = client.get(url, params=query_params, headers=headers)
|
|
117
|
+
except Exception as exc:
|
|
118
|
+
return [
|
|
119
|
+
_result(endpoint, base_url, "contract_conformance_probe", "error", None, None, str(exc))
|
|
120
|
+
]
|
|
121
|
+
latency_ms = (time.monotonic() - t0) * 1000
|
|
122
|
+
actual_status = resp.status_code
|
|
123
|
+
snippet = " ".join(resp.text.split())[:400]
|
|
124
|
+
|
|
125
|
+
results: list[ExecutionResult] = []
|
|
126
|
+
declared = _declared_status_codes(endpoint.response_schemas)
|
|
127
|
+
|
|
128
|
+
# --- Probe 1: status code conformance ---
|
|
129
|
+
if _matches_declared_status(actual_status, declared):
|
|
130
|
+
results.append(_result(
|
|
131
|
+
endpoint, base_url, "response_status_code_conformance", "pass",
|
|
132
|
+
actual_status, latency_ms,
|
|
133
|
+
f"Status {actual_status} is declared in responses map",
|
|
134
|
+
))
|
|
135
|
+
else:
|
|
136
|
+
results.append(_result(
|
|
137
|
+
endpoint, base_url, "response_status_code_conformance", "fail",
|
|
138
|
+
actual_status, latency_ms,
|
|
139
|
+
f"Undocumented status code {actual_status}; declared: {sorted(declared)}",
|
|
140
|
+
snippet,
|
|
141
|
+
))
|
|
142
|
+
|
|
143
|
+
# --- Field-level probes only for 2xx JSON object responses ---
|
|
144
|
+
if not (200 <= actual_status < 300):
|
|
145
|
+
return results
|
|
146
|
+
|
|
147
|
+
try:
|
|
148
|
+
body = resp.json()
|
|
149
|
+
except Exception:
|
|
150
|
+
return results
|
|
151
|
+
|
|
152
|
+
if not isinstance(body, dict):
|
|
153
|
+
# Array or scalar response — skip field checks
|
|
154
|
+
return results
|
|
155
|
+
|
|
156
|
+
response_obj = _response_obj_for_status(endpoint.response_schemas, actual_status)
|
|
157
|
+
if response_obj is None:
|
|
158
|
+
return results
|
|
159
|
+
|
|
160
|
+
schema = _json_schema_from_response_obj(response_obj)
|
|
161
|
+
props = _properties(schema)
|
|
162
|
+
required = _required_fields(schema)
|
|
163
|
+
|
|
164
|
+
if props is not None:
|
|
165
|
+
# --- Probe 2: undocumented top-level fields ---
|
|
166
|
+
extra = sorted(set(body.keys()) - set(props.keys()))
|
|
167
|
+
if extra:
|
|
168
|
+
results.append(_result(
|
|
169
|
+
endpoint, base_url, "response_undocumented_fields", "fail",
|
|
170
|
+
actual_status, latency_ms,
|
|
171
|
+
f"{len(extra)} undocumented top-level field(s) in response: {extra[:10]}",
|
|
172
|
+
snippet,
|
|
173
|
+
))
|
|
174
|
+
else:
|
|
175
|
+
results.append(_result(
|
|
176
|
+
endpoint, base_url, "response_undocumented_fields", "pass",
|
|
177
|
+
actual_status, latency_ms,
|
|
178
|
+
f"All {len(body)} top-level response field(s) declared in schema",
|
|
179
|
+
))
|
|
180
|
+
|
|
181
|
+
# --- Probe 3: missing required fields ---
|
|
182
|
+
if required:
|
|
183
|
+
missing = sorted(set(required) - set(body.keys()))
|
|
184
|
+
if missing:
|
|
185
|
+
results.append(_result(
|
|
186
|
+
endpoint, base_url, "response_missing_required_fields", "fail",
|
|
187
|
+
actual_status, latency_ms,
|
|
188
|
+
f"{len(missing)} required field(s) absent from response: {missing[:10]}",
|
|
189
|
+
snippet,
|
|
190
|
+
))
|
|
191
|
+
else:
|
|
192
|
+
results.append(_result(
|
|
193
|
+
endpoint, base_url, "response_missing_required_fields", "pass",
|
|
194
|
+
actual_status, latency_ms,
|
|
195
|
+
f"All {len(required)} required field(s) present in response",
|
|
196
|
+
))
|
|
197
|
+
else:
|
|
198
|
+
results.append(_result(
|
|
199
|
+
endpoint, base_url, "response_missing_required_fields", "skipped",
|
|
200
|
+
actual_status, latency_ms,
|
|
201
|
+
"No required fields declared in response schema",
|
|
202
|
+
))
|
|
203
|
+
else:
|
|
204
|
+
# Schema exists but has no properties — field-level checks not possible
|
|
205
|
+
results.append(_result(
|
|
206
|
+
endpoint, base_url, "response_undocumented_fields", "skipped",
|
|
207
|
+
actual_status, latency_ms,
|
|
208
|
+
"Response schema has no properties defined; field-level check skipped",
|
|
209
|
+
))
|
|
210
|
+
results.append(_result(
|
|
211
|
+
endpoint, base_url, "response_missing_required_fields", "skipped",
|
|
212
|
+
actual_status, latency_ms,
|
|
213
|
+
"Response schema has no properties defined; required-fields check skipped",
|
|
214
|
+
))
|
|
215
|
+
|
|
216
|
+
return results
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
# ---------------------------------------------------------------------------
|
|
220
|
+
# Category entry point
|
|
221
|
+
# ---------------------------------------------------------------------------
|
|
222
|
+
|
|
223
|
+
def run(
|
|
224
|
+
client: httpx.Client,
|
|
225
|
+
base_url: str,
|
|
226
|
+
token: str | None,
|
|
227
|
+
endpoints: list[EndpointSpec],
|
|
228
|
+
include_unsafe: bool,
|
|
229
|
+
) -> list[ExecutionResult]:
|
|
230
|
+
del include_unsafe
|
|
231
|
+
|
|
232
|
+
targets = _safe_targets_with_schema(endpoints)[:MAX_CONFORMANCE_TARGETS]
|
|
233
|
+
if not targets:
|
|
234
|
+
return [
|
|
235
|
+
ExecutionResult(
|
|
236
|
+
category="contract_conformance",
|
|
237
|
+
test_name="contract_conformance_target_discovery",
|
|
238
|
+
service="gateway",
|
|
239
|
+
method="GET",
|
|
240
|
+
url=base_url.rstrip("/"),
|
|
241
|
+
status="skipped",
|
|
242
|
+
message="No GET endpoints with declared response schemas found for conformance checks",
|
|
243
|
+
)
|
|
244
|
+
]
|
|
245
|
+
|
|
246
|
+
results: list[ExecutionResult] = []
|
|
247
|
+
for endpoint in targets:
|
|
248
|
+
results.extend(_probe(client, endpoint, base_url, token))
|
|
249
|
+
return results
|