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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dhalisoft
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ app_test
app_test/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ __all__ = ["__version__"]
2
+ __version__ = "0.1.0"
app_test/auth.py ADDED
@@ -0,0 +1,107 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+
5
+ import httpx
6
+
7
+
8
+ AUTH_TOKEN_BEARER_PREFIX = "bearer::"
9
+ AUTH_TOKEN_HEADER_PREFIX = "header::"
10
+
11
+
12
+ def serialize_bearer_token(token: str) -> str:
13
+ return f"{AUTH_TOKEN_BEARER_PREFIX}{token}"
14
+
15
+
16
+ def serialize_header_auth(header_name: str, header_value: str) -> str:
17
+ payload = {"name": header_name, "value": header_value}
18
+ return f"{AUTH_TOKEN_HEADER_PREFIX}{json.dumps(payload, separators=(',', ':'))}"
19
+
20
+
21
+ def auth_headers_from_token(token: str | None) -> dict[str, str]:
22
+ if not token:
23
+ return {}
24
+
25
+ if token.startswith(AUTH_TOKEN_BEARER_PREFIX):
26
+ raw_token = token[len(AUTH_TOKEN_BEARER_PREFIX) :]
27
+ if not raw_token:
28
+ return {}
29
+ return {"Authorization": f"Bearer {raw_token}"}
30
+
31
+ if token.startswith(AUTH_TOKEN_HEADER_PREFIX):
32
+ try:
33
+ payload = json.loads(token[len(AUTH_TOKEN_HEADER_PREFIX) :])
34
+ if not isinstance(payload, dict):
35
+ return {}
36
+ name = str(payload.get("name", "")).strip()
37
+ value = str(payload.get("value", "")).strip()
38
+ if not name or not value:
39
+ return {}
40
+ return {name: value}
41
+ except Exception:
42
+ return {}
43
+
44
+ # Backward compatibility: previously token was always raw bearer token.
45
+ return {"Authorization": f"Bearer {token}"}
46
+
47
+
48
+ def extract_bearer_token(token: str | None) -> str | None:
49
+ if not token:
50
+ return None
51
+
52
+ if token.startswith(AUTH_TOKEN_BEARER_PREFIX):
53
+ value = token[len(AUTH_TOKEN_BEARER_PREFIX) :].strip()
54
+ return value or None
55
+
56
+ if token.startswith(AUTH_TOKEN_HEADER_PREFIX):
57
+ try:
58
+ payload = json.loads(token[len(AUTH_TOKEN_HEADER_PREFIX) :])
59
+ if not isinstance(payload, dict):
60
+ return None
61
+ name = str(payload.get("name", "")).strip().lower()
62
+ value = str(payload.get("value", "")).strip()
63
+ if name == "authorization" and value.lower().startswith("bearer "):
64
+ bearer = value[7:].strip()
65
+ return bearer or None
66
+ return None
67
+ except Exception:
68
+ return None
69
+
70
+ # Backward compatibility: assume legacy token input is bearer.
71
+ return token
72
+
73
+
74
+ def login_and_get_token(
75
+ client: httpx.Client,
76
+ base_url: str,
77
+ username: str,
78
+ password: str,
79
+ ) -> str:
80
+ base = base_url.rstrip("/")
81
+ login_paths = [
82
+ "/api/data/auth/login",
83
+ "/auth/login",
84
+ ]
85
+ payloads = [
86
+ {"email": username, "password": password},
87
+ {"username": username, "password": password},
88
+ {"email": username, "username": username, "password": password},
89
+ ]
90
+
91
+ last_error: Exception | None = None
92
+ for login_path in login_paths:
93
+ login_url = f"{base}{login_path}"
94
+ for payload in payloads:
95
+ try:
96
+ response = client.post(login_url, json=payload)
97
+ response.raise_for_status()
98
+ data = response.json()
99
+ token = data.get("access_token") or data.get("token")
100
+ if token:
101
+ return token
102
+ except Exception as exc:
103
+ last_error = exc
104
+
105
+ if last_error:
106
+ raise last_error
107
+ raise ValueError("Login failed: no valid token response from known auth endpoints")
@@ -0,0 +1,24 @@
1
+ from app_test.categories import auth_robustness, authz, baseline, bola_matrix, contract_conformance, error_leakage_and_debug_surface, file_upload_security, jwt_security, mass_assignment, owasp, pen_test, privilege_escalation, rate_limit_and_resource_abuse, schema_contract_and_validation, security_misc, soak_profile, sql_injection, ssrf_and_redirects, token_security, workflow_chains
2
+
3
+ __all__ = [
4
+ "baseline",
5
+ "pen_test",
6
+ "sql_injection",
7
+ "owasp",
8
+ "security_misc",
9
+ "authz",
10
+ "auth_robustness",
11
+ "token_security",
12
+ "jwt_security",
13
+ "privilege_escalation",
14
+ "file_upload_security",
15
+ "ssrf_and_redirects",
16
+ "rate_limit_and_resource_abuse",
17
+ "error_leakage_and_debug_surface",
18
+ "mass_assignment",
19
+ "schema_contract_and_validation",
20
+ "contract_conformance",
21
+ "bola_matrix",
22
+ "workflow_chains",
23
+ "soak_profile",
24
+ ]
@@ -0,0 +1,186 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+
5
+ import httpx
6
+
7
+ from app_test.models import EndpointSpec, ExecutionResult
8
+
9
+
10
+ # Strong hints: these explicitly indicate a login/sign-in flow
11
+ AUTH_STRONG_HINTS = {"login", "signin", "token", "session"}
12
+ # Weak hint: 'auth' is a namespace prefix, not necessarily a login endpoint
13
+ AUTH_WEAK_HINTS = {"auth"}
14
+ # Explicit exclusions: these share path segments with auth but are not credential validation
15
+ AUTH_EXCLUDE_HINTS = {"signup", "register", "reset", "verify", "confirm", "invite", "refresh", "logout", "callback", "authorize", "oauth"}
16
+
17
+
18
+ def _looks_like_auth_endpoint(endpoint: EndpointSpec) -> bool:
19
+ if endpoint.method.upper() != "POST":
20
+ return False
21
+
22
+ path = endpoint.path.lower()
23
+ operation_id = (endpoint.operation_id or "").lower()
24
+
25
+ # Exclude known non-login paths first
26
+ if any(excl in path or excl in operation_id for excl in AUTH_EXCLUDE_HINTS):
27
+ return False
28
+
29
+ return any(hint in path or hint in operation_id for hint in AUTH_STRONG_HINTS | AUTH_WEAK_HINTS)
30
+
31
+
32
+ def _auth_endpoint_priority(endpoint: EndpointSpec) -> int:
33
+ """Lower number = higher priority. Strong hints beat weak (auth-namespace) hints."""
34
+ path = endpoint.path.lower()
35
+ operation_id = (endpoint.operation_id or "").lower()
36
+ if any(hint in path or hint in operation_id for hint in AUTH_STRONG_HINTS):
37
+ return 0
38
+ return 1
39
+
40
+
41
+ def _build_invalid_login_payload(endpoint: EndpointSpec) -> dict[str, str]:
42
+ properties = (
43
+ endpoint.request_body.get("content", {})
44
+ .get("application/json", {})
45
+ .get("schema", {})
46
+ .get("properties", {})
47
+ )
48
+
49
+ payload: dict[str, str] = {}
50
+ if isinstance(properties, dict) and properties:
51
+ for key in properties:
52
+ key_lower = key.lower()
53
+ if any(k in key_lower for k in {"email", "user", "login", "identifier"}):
54
+ payload[key] = "invalid-user@example.com"
55
+ elif any(k in key_lower for k in {"password", "pass", "passwd"}):
56
+ payload[key] = "DefinitelyWrongPassword123!"
57
+ else:
58
+ payload[key] = "invalid"
59
+
60
+ if not payload:
61
+ payload = {
62
+ "username": "invalid-user@example.com",
63
+ "password": "DefinitelyWrongPassword123!",
64
+ }
65
+ return payload
66
+
67
+
68
+ def _invalid_credentials_rejection_check(
69
+ client: httpx.Client,
70
+ base_url: str,
71
+ endpoint: EndpointSpec,
72
+ ) -> ExecutionResult:
73
+ url = f"{base_url.rstrip('/')}{endpoint.path}"
74
+ payload = _build_invalid_login_payload(endpoint)
75
+
76
+ try:
77
+ response = client.post(url, json=payload)
78
+ code = response.status_code
79
+ if code in {400, 401, 403, 422, 429}:
80
+ status = "pass"
81
+ message = f"Invalid credentials correctly rejected ({code})"
82
+ elif 200 <= code < 300:
83
+ status = "fail"
84
+ message = f"Invalid credentials returned success status ({code})"
85
+ else:
86
+ status = "error"
87
+ message = f"Unexpected auth response status ({code})"
88
+
89
+ return ExecutionResult(
90
+ category="auth_robustness",
91
+ test_name="invalid_credentials_rejection_check",
92
+ service=endpoint.service,
93
+ method="POST",
94
+ url=str(response.request.url),
95
+ status=status,
96
+ http_status=code,
97
+ message=message,
98
+ )
99
+ except Exception as exc:
100
+ return ExecutionResult(
101
+ category="auth_robustness",
102
+ test_name="invalid_credentials_rejection_check",
103
+ service=endpoint.service,
104
+ method="POST",
105
+ url=url,
106
+ status="error",
107
+ message=str(exc),
108
+ )
109
+
110
+
111
+ def _failed_login_throttle_signal_check(
112
+ client: httpx.Client,
113
+ base_url: str,
114
+ endpoint: EndpointSpec,
115
+ ) -> ExecutionResult:
116
+ url = f"{base_url.rstrip('/')}{endpoint.path}"
117
+ payload = _build_invalid_login_payload(endpoint)
118
+
119
+ statuses: list[int] = []
120
+ try:
121
+ for _ in range(5):
122
+ response = client.post(url, json=payload)
123
+ statuses.append(response.status_code)
124
+ time.sleep(0.05)
125
+
126
+ if any(code == 429 for code in statuses):
127
+ status = "pass"
128
+ message = f"Throttle signal detected during failed logins: statuses={statuses}"
129
+ else:
130
+ status = "skipped"
131
+ message = f"No explicit throttle signal in short failed-login burst: statuses={statuses}"
132
+
133
+ return ExecutionResult(
134
+ category="auth_robustness",
135
+ test_name="failed_login_throttle_signal_check",
136
+ service=endpoint.service,
137
+ method="POST",
138
+ url=url,
139
+ status=status,
140
+ http_status=statuses[-1] if statuses else None,
141
+ message=message,
142
+ )
143
+ except Exception as exc:
144
+ return ExecutionResult(
145
+ category="auth_robustness",
146
+ test_name="failed_login_throttle_signal_check",
147
+ service=endpoint.service,
148
+ method="POST",
149
+ url=url,
150
+ status="error",
151
+ message=str(exc),
152
+ )
153
+
154
+
155
+ def run(
156
+ client: httpx.Client,
157
+ base_url: str,
158
+ token: str,
159
+ endpoints: list[EndpointSpec],
160
+ include_unsafe: bool,
161
+ ) -> list[ExecutionResult]:
162
+ del token
163
+ del include_unsafe
164
+
165
+ auth_endpoints = sorted(
166
+ [endpoint for endpoint in endpoints if _looks_like_auth_endpoint(endpoint)],
167
+ key=_auth_endpoint_priority,
168
+ )
169
+ if not auth_endpoints:
170
+ return [
171
+ ExecutionResult(
172
+ category="auth_robustness",
173
+ test_name="auth_endpoint_discovery",
174
+ service="gateway",
175
+ method="POST",
176
+ url=base_url.rstrip("/"),
177
+ status="skipped",
178
+ message="No login-like auth endpoint discovered for authentication robustness checks",
179
+ )
180
+ ]
181
+
182
+ target = auth_endpoints[0]
183
+ return [
184
+ _invalid_credentials_rejection_check(client, base_url, target),
185
+ _failed_login_throttle_signal_check(client, base_url, target),
186
+ ]
@@ -0,0 +1,119 @@
1
+ from __future__ import annotations
2
+
3
+ import httpx
4
+
5
+ from app_test.auth import auth_headers_from_token
6
+ from app_test.executor import execute_endpoint
7
+ from app_test.models import EndpointSpec, ExecutionResult
8
+
9
+
10
+ ID_HINTS = {"id", "user", "account", "tenant", "org", "customer", "project"}
11
+
12
+
13
+ def _looks_like_id_path(endpoint: EndpointSpec) -> bool:
14
+ if "{" not in endpoint.path or "}" not in endpoint.path:
15
+ return False
16
+ path_lower = endpoint.path.lower()
17
+ return any(hint in path_lower for hint in ID_HINTS)
18
+
19
+
20
+ def _replace_path_params(endpoint: EndpointSpec, raw_path: str, replacement: str) -> str:
21
+ path = raw_path
22
+ for param in endpoint.parameters:
23
+ if param.where != "path":
24
+ continue
25
+ token = f"{{{param.name}}}"
26
+ path = path.replace(token, replacement)
27
+ return path
28
+
29
+
30
+ def _idor_probe(
31
+ client: httpx.Client,
32
+ base_url: str,
33
+ token: str,
34
+ endpoint: EndpointSpec,
35
+ include_unsafe: bool,
36
+ ) -> ExecutionResult:
37
+ method = endpoint.method.upper()
38
+ url = f"{base_url.rstrip('/')}{endpoint.path}"
39
+
40
+ if method in {"POST", "PUT", "PATCH", "DELETE"} and not include_unsafe:
41
+ return ExecutionResult(
42
+ category="authz",
43
+ test_name="idor_path_tamper_check",
44
+ service=endpoint.service,
45
+ method=method,
46
+ url=url,
47
+ status="skipped",
48
+ message="Unsafe HTTP method skipped (use --include-unsafe to run)",
49
+ )
50
+
51
+ tampered_path = _replace_path_params(endpoint, endpoint.path, "999999")
52
+ tampered_url = f"{base_url.rstrip('/')}{tampered_path}"
53
+ headers = auth_headers_from_token(token)
54
+
55
+ try:
56
+ response = client.request(method=method, url=tampered_url, headers=headers)
57
+ status_code = response.status_code
58
+
59
+ if status_code in {401, 403, 404}:
60
+ status = "pass"
61
+ message = "Tampered object access was blocked or hidden"
62
+ elif 200 <= status_code < 300:
63
+ status = "fail"
64
+ message = "Tampered object access returned success (possible IDOR risk)"
65
+ else:
66
+ status = "pass"
67
+ message = f"Tampered object access returned non-success status ({status_code})"
68
+
69
+ return ExecutionResult(
70
+ category="authz",
71
+ test_name="idor_path_tamper_check",
72
+ service=endpoint.service,
73
+ method=method,
74
+ url=str(response.request.url),
75
+ status=status,
76
+ http_status=status_code,
77
+ message=message,
78
+ )
79
+ except Exception as exc:
80
+ return ExecutionResult(
81
+ category="authz",
82
+ test_name="idor_path_tamper_check",
83
+ service=endpoint.service,
84
+ method=method,
85
+ url=tampered_url,
86
+ status="error",
87
+ message=str(exc),
88
+ )
89
+
90
+
91
+ def run(
92
+ client: httpx.Client,
93
+ base_url: str,
94
+ token: str,
95
+ endpoints: list[EndpointSpec],
96
+ include_unsafe: bool,
97
+ ) -> list[ExecutionResult]:
98
+ results: list[ExecutionResult] = []
99
+
100
+ auth_required = [endpoint for endpoint in endpoints if endpoint.requires_auth]
101
+ for endpoint in auth_required:
102
+ results.append(
103
+ execute_endpoint(
104
+ client=client,
105
+ endpoint=endpoint,
106
+ base_url=base_url,
107
+ token=token,
108
+ category="authz",
109
+ test_name="authz_unauthenticated_access_check",
110
+ include_unsafe=include_unsafe,
111
+ auth_mode="none",
112
+ )
113
+ )
114
+
115
+ id_endpoints = [endpoint for endpoint in auth_required if _looks_like_id_path(endpoint)]
116
+ for endpoint in id_endpoints[:20]:
117
+ results.append(_idor_probe(client, base_url, token, endpoint, include_unsafe))
118
+
119
+ return results
@@ -0,0 +1,29 @@
1
+ from __future__ import annotations
2
+
3
+ import httpx
4
+
5
+ from app_test.executor import execute_endpoint
6
+ from app_test.models import EndpointSpec, ExecutionResult
7
+
8
+
9
+ def run(
10
+ client: httpx.Client,
11
+ base_url: str,
12
+ token: str,
13
+ endpoints: list[EndpointSpec],
14
+ include_unsafe: bool,
15
+ ) -> list[ExecutionResult]:
16
+ results: list[ExecutionResult] = []
17
+ for endpoint in endpoints:
18
+ results.append(
19
+ execute_endpoint(
20
+ client=client,
21
+ endpoint=endpoint,
22
+ base_url=base_url,
23
+ token=token,
24
+ category="baseline",
25
+ test_name="baseline_request",
26
+ include_unsafe=include_unsafe,
27
+ )
28
+ )
29
+ return results