security-tests-m8 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.
- security_tests_m8/__init__.py +17 -0
- security_tests_m8/_client.py +75 -0
- security_tests_m8/_config.py +262 -0
- security_tests_m8/_detection.py +130 -0
- security_tests_m8/_preflight.py +137 -0
- security_tests_m8/_requests.py +60 -0
- security_tests_m8/cli.py +232 -0
- security_tests_m8/deployment.py +546 -0
- security_tests_m8/forge.py +189 -0
- security_tests_m8/full_security.py +131 -0
- security_tests_m8/plugin.py +470 -0
- security_tests_m8/suites/__init__.py +67 -0
- security_tests_m8/suites/algorithms.py +554 -0
- security_tests_m8/suites/deployment.py +36 -0
- security_tests_m8/suites/service.py +138 -0
- security_tests_m8/suites/token_modes.py +537 -0
- security_tests_m8/suites/universal.py +1253 -0
- security_tests_m8-0.1.0.dist-info/METADATA +644 -0
- security_tests_m8-0.1.0.dist-info/RECORD +22 -0
- security_tests_m8-0.1.0.dist-info/WHEEL +4 -0
- security_tests_m8-0.1.0.dist-info/entry_points.txt +5 -0
- security_tests_m8-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Reusable live security test suites for FastAPI M8 stacks."""
|
|
2
|
+
|
|
3
|
+
from security_tests_m8._config import (
|
|
4
|
+
LiveTestConfig,
|
|
5
|
+
configure,
|
|
6
|
+
configure_from_env,
|
|
7
|
+
get_config,
|
|
8
|
+
load_env_file,
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"LiveTestConfig",
|
|
13
|
+
"configure",
|
|
14
|
+
"configure_from_env",
|
|
15
|
+
"get_config",
|
|
16
|
+
"load_env_file",
|
|
17
|
+
]
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Synchronous HTTP helpers for live security tests."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import requests
|
|
6
|
+
|
|
7
|
+
from security_tests_m8._config import get_config
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ConfigUrl:
|
|
11
|
+
"""String-like URL proxy resolved from the active configuration."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, key: str) -> None:
|
|
14
|
+
self.key = key
|
|
15
|
+
|
|
16
|
+
def __str__(self) -> str:
|
|
17
|
+
config = get_config()
|
|
18
|
+
if self.key == "auth":
|
|
19
|
+
return config.auth_base_url
|
|
20
|
+
return config.resolve_service_base_url()
|
|
21
|
+
|
|
22
|
+
def __format__(self, spec: str) -> str:
|
|
23
|
+
return format(str(self), spec)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
AUTH_BASE = ConfigUrl("auth")
|
|
27
|
+
SVC_BASE = ConfigUrl("service")
|
|
28
|
+
TIMEOUT = get_config().timeout
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def timeout() -> int:
|
|
32
|
+
"""Return the configured request timeout."""
|
|
33
|
+
return get_config().timeout
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def auth_health_url() -> str:
|
|
37
|
+
"""Return the configured auth health/readiness URL."""
|
|
38
|
+
config = get_config()
|
|
39
|
+
return config.auth_health_url or f"{config.auth_base_url}/health"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def internal_headers() -> dict[str, str]:
|
|
43
|
+
"""Return private API headers when a private secret is configured."""
|
|
44
|
+
secret = get_config().private_api_secret
|
|
45
|
+
if not secret:
|
|
46
|
+
return {}
|
|
47
|
+
return {"X-Internal-Token": secret}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def auth_header(bearer: str) -> dict[str, str]:
|
|
51
|
+
"""Return an Authorization header dict for the given bearer token."""
|
|
52
|
+
return {"Authorization": f"Bearer {bearer}"}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def fresh_login(
|
|
56
|
+
email: str | None = None, password: str | None = None
|
|
57
|
+
) -> dict[str, object]:
|
|
58
|
+
"""Perform a fresh login and return token, cookies, and auth headers."""
|
|
59
|
+
config = get_config()
|
|
60
|
+
login_email = email or config.admin_email
|
|
61
|
+
login_password = password or config.admin_password
|
|
62
|
+
response = requests.post(
|
|
63
|
+
f"{config.auth_base_url}/login/access-token",
|
|
64
|
+
data={"username": login_email, "password": login_password},
|
|
65
|
+
timeout=config.timeout,
|
|
66
|
+
)
|
|
67
|
+
assert response.status_code == 200, (
|
|
68
|
+
f"Login failed for {login_email}: {response.text}"
|
|
69
|
+
)
|
|
70
|
+
token = str(response.json()["access_token"])
|
|
71
|
+
return {
|
|
72
|
+
"token": token,
|
|
73
|
+
"cookies": dict(response.cookies),
|
|
74
|
+
"headers": auth_header(token),
|
|
75
|
+
}
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
"""Runtime configuration for reusable live security tests."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from dataclasses import dataclass, field, replace
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from security_tests_m8._requests import install_live_tls_defaults
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _env_int(name: str, default: int) -> int:
|
|
16
|
+
raw = os.getenv(name)
|
|
17
|
+
if raw is None:
|
|
18
|
+
return default
|
|
19
|
+
return int(raw)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _env_bool(name: str, default: bool) -> bool:
|
|
23
|
+
raw = os.getenv(name)
|
|
24
|
+
if raw is None:
|
|
25
|
+
return default
|
|
26
|
+
return raw.lower() in {"1", "true", "yes", "on"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _env_tls_verify(name: str, default: bool | str) -> bool | str:
|
|
30
|
+
raw = os.getenv(name)
|
|
31
|
+
if raw is None:
|
|
32
|
+
return default
|
|
33
|
+
lowered = raw.lower()
|
|
34
|
+
if lowered in {"1", "true", "yes", "on"}:
|
|
35
|
+
return True
|
|
36
|
+
if lowered in {"0", "false", "no", "off"}:
|
|
37
|
+
return False
|
|
38
|
+
return raw
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _env_service_bases() -> dict[str, str]:
|
|
42
|
+
raw = os.getenv("LIVE_TEST_SVC_BASES")
|
|
43
|
+
if raw is None:
|
|
44
|
+
return {}
|
|
45
|
+
decoded = json.loads(raw)
|
|
46
|
+
if not isinstance(decoded, dict):
|
|
47
|
+
raise ValueError("LIVE_TEST_SVC_BASES must be a JSON object")
|
|
48
|
+
return {str(key): str(value).rstrip("/") for key, value in decoded.items()}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _env_endpoint_map(name: str) -> dict[str, list[str]]:
|
|
52
|
+
raw = os.getenv(name)
|
|
53
|
+
if raw is None:
|
|
54
|
+
return {}
|
|
55
|
+
decoded = json.loads(raw)
|
|
56
|
+
if not isinstance(decoded, dict):
|
|
57
|
+
raise ValueError(f"{name} must be a JSON object")
|
|
58
|
+
endpoints: dict[str, list[str]] = {}
|
|
59
|
+
for service, values in decoded.items():
|
|
60
|
+
if not isinstance(values, list):
|
|
61
|
+
raise ValueError(f"{name} values must be arrays")
|
|
62
|
+
endpoints[str(service)] = [str(value) for value in values]
|
|
63
|
+
return endpoints
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
DEFAULT_PLACEHOLDER_VALUE = "changethis"
|
|
67
|
+
|
|
68
|
+
_FIELD_ENV_NAMES = {
|
|
69
|
+
"auth_base_url": ("LIVE_TEST_AUTH_BASE",),
|
|
70
|
+
"auth_health_url": ("LIVE_TEST_AUTH_HEALTH_URL",),
|
|
71
|
+
"admin_email": ("LIVE_TEST_ADMIN_EMAIL",),
|
|
72
|
+
"admin_password": ("LIVE_TEST_ADMIN_PASSWORD",),
|
|
73
|
+
"service_base_url": ("LIVE_TEST_SVC_BASE",),
|
|
74
|
+
"service_base_urls": ("LIVE_TEST_SVC_BASES",),
|
|
75
|
+
"default_service": ("LIVE_TEST_DEFAULT_SVC",),
|
|
76
|
+
"timeout": ("LIVE_TEST_TIMEOUT",),
|
|
77
|
+
"repo_root": ("LIVE_TEST_REPO_ROOT",),
|
|
78
|
+
"deployment_root": ("LIVE_TEST_DEPLOYMENT_ROOT",),
|
|
79
|
+
"public_base_url": ("LIVE_TEST_PUBLIC_BASE",),
|
|
80
|
+
"public_tls_verify": ("LIVE_TEST_PUBLIC_TLS_VERIFY",),
|
|
81
|
+
"private_api_secret": ("LIVE_TEST_PRIVATE_API_SECRET",),
|
|
82
|
+
"refresh_secret_key": ("LIVE_TEST_REFRESH_SECRET_KEY",),
|
|
83
|
+
"fail_fast_preflight": ("LIVE_TEST_FAIL_FAST_PREFLIGHT",),
|
|
84
|
+
"forbid_bootstrap_superuser": ("LIVE_TEST_FORBID_BOOTSTRAP_SUPERUSER",),
|
|
85
|
+
"protected_endpoints": ("LIVE_TEST_PROTECTED_ENDPOINTS",),
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass(frozen=True)
|
|
90
|
+
class LiveTestConfig:
|
|
91
|
+
"""Configuration used by live security suites and pytest fixtures."""
|
|
92
|
+
|
|
93
|
+
auth_base_url: str = "http://localhost:9000/user"
|
|
94
|
+
auth_health_url: str | None = None
|
|
95
|
+
admin_email: str = "admin@example.com"
|
|
96
|
+
admin_password: str = DEFAULT_PLACEHOLDER_VALUE
|
|
97
|
+
service_base_url: str | None = None
|
|
98
|
+
service_base_urls: dict[str, str] = field(default_factory=dict)
|
|
99
|
+
default_service: str | None = None
|
|
100
|
+
timeout: int = 10
|
|
101
|
+
repo_root: Path | None = None
|
|
102
|
+
deployment_root: Path | None = None
|
|
103
|
+
public_base_url: str | None = "https://localhost:4430"
|
|
104
|
+
public_tls_verify: bool | str = True
|
|
105
|
+
private_api_secret: str | None = None
|
|
106
|
+
refresh_secret_key: str | None = None
|
|
107
|
+
fail_fast_preflight: bool = False
|
|
108
|
+
forbid_bootstrap_superuser: bool = True
|
|
109
|
+
protected_endpoints: dict[str, list[str]] = field(default_factory=dict)
|
|
110
|
+
|
|
111
|
+
@classmethod
|
|
112
|
+
def from_env(cls) -> LiveTestConfig:
|
|
113
|
+
"""Build a configuration object from environment variables."""
|
|
114
|
+
service_base_url = os.getenv("LIVE_TEST_SVC_BASE")
|
|
115
|
+
repo_root = os.getenv("LIVE_TEST_REPO_ROOT")
|
|
116
|
+
deployment_root = os.getenv("LIVE_TEST_DEPLOYMENT_ROOT")
|
|
117
|
+
return cls(
|
|
118
|
+
auth_base_url=os.getenv(
|
|
119
|
+
"LIVE_TEST_AUTH_BASE", "http://localhost:9000/user"
|
|
120
|
+
).rstrip("/"),
|
|
121
|
+
auth_health_url=(
|
|
122
|
+
os.getenv("LIVE_TEST_AUTH_HEALTH_URL", "").rstrip("/") or None
|
|
123
|
+
),
|
|
124
|
+
admin_email=os.getenv("LIVE_TEST_ADMIN_EMAIL", "admin@example.com"),
|
|
125
|
+
admin_password=os.getenv(
|
|
126
|
+
"LIVE_TEST_ADMIN_PASSWORD", DEFAULT_PLACEHOLDER_VALUE
|
|
127
|
+
),
|
|
128
|
+
service_base_url=service_base_url.rstrip("/") if service_base_url else None,
|
|
129
|
+
service_base_urls=_env_service_bases(),
|
|
130
|
+
default_service=os.getenv("LIVE_TEST_DEFAULT_SVC"),
|
|
131
|
+
timeout=_env_int("LIVE_TEST_TIMEOUT", 10),
|
|
132
|
+
repo_root=Path(repo_root).resolve() if repo_root else None,
|
|
133
|
+
deployment_root=Path(deployment_root).resolve()
|
|
134
|
+
if deployment_root
|
|
135
|
+
else None,
|
|
136
|
+
public_base_url=os.getenv(
|
|
137
|
+
"LIVE_TEST_PUBLIC_BASE", "https://localhost:4430"
|
|
138
|
+
).rstrip("/"),
|
|
139
|
+
public_tls_verify=_env_tls_verify("LIVE_TEST_PUBLIC_TLS_VERIFY", True),
|
|
140
|
+
private_api_secret=os.getenv("LIVE_TEST_PRIVATE_API_SECRET"),
|
|
141
|
+
refresh_secret_key=os.getenv("LIVE_TEST_REFRESH_SECRET_KEY"),
|
|
142
|
+
fail_fast_preflight=_env_bool("LIVE_TEST_FAIL_FAST_PREFLIGHT", False),
|
|
143
|
+
forbid_bootstrap_superuser=_env_bool(
|
|
144
|
+
"LIVE_TEST_FORBID_BOOTSTRAP_SUPERUSER", True
|
|
145
|
+
),
|
|
146
|
+
protected_endpoints=_env_endpoint_map("LIVE_TEST_PROTECTED_ENDPOINTS"),
|
|
147
|
+
).normalized()
|
|
148
|
+
|
|
149
|
+
def normalized(self) -> LiveTestConfig:
|
|
150
|
+
"""Return a copy with URL mappings normalized."""
|
|
151
|
+
urls = {key: value.rstrip("/") for key, value in self.service_base_urls.items()}
|
|
152
|
+
protected_endpoints = {
|
|
153
|
+
key: [endpoint for endpoint in endpoints]
|
|
154
|
+
for key, endpoints in self.protected_endpoints.items()
|
|
155
|
+
}
|
|
156
|
+
service_base_url = (
|
|
157
|
+
self.service_base_url.rstrip("/") if self.service_base_url else None
|
|
158
|
+
)
|
|
159
|
+
if service_base_url:
|
|
160
|
+
urls.setdefault("default", service_base_url)
|
|
161
|
+
default_service = self.default_service
|
|
162
|
+
if default_service is None and service_base_url:
|
|
163
|
+
default_service = "default"
|
|
164
|
+
return replace(
|
|
165
|
+
self,
|
|
166
|
+
auth_base_url=self.auth_base_url.rstrip("/"),
|
|
167
|
+
auth_health_url=self.auth_health_url.rstrip("/")
|
|
168
|
+
if self.auth_health_url
|
|
169
|
+
else None,
|
|
170
|
+
service_base_url=service_base_url,
|
|
171
|
+
service_base_urls=urls,
|
|
172
|
+
default_service=default_service,
|
|
173
|
+
public_base_url=self.public_base_url.rstrip("/")
|
|
174
|
+
if self.public_base_url
|
|
175
|
+
else None,
|
|
176
|
+
protected_endpoints=protected_endpoints,
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
def resolve_service_base_url(self, service: str | None = None) -> str:
|
|
180
|
+
"""Resolve a named service URL, falling back to the configured default."""
|
|
181
|
+
if service is not None:
|
|
182
|
+
try:
|
|
183
|
+
return self.service_base_urls[service]
|
|
184
|
+
except KeyError as exc:
|
|
185
|
+
names = ", ".join(sorted(self.service_base_urls)) or "<none>"
|
|
186
|
+
raise LookupError(
|
|
187
|
+
f"Service {service!r} is not configured. Known services: {names}"
|
|
188
|
+
) from exc
|
|
189
|
+
if self.default_service:
|
|
190
|
+
return self.resolve_service_base_url(self.default_service)
|
|
191
|
+
if self.service_base_url:
|
|
192
|
+
return self.service_base_url
|
|
193
|
+
raise LookupError(
|
|
194
|
+
"No service URL configured. Set LIVE_TEST_SVC_BASE or "
|
|
195
|
+
"LIVE_TEST_SVC_BASES, or call configure(service_base_url=...)."
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
_CONFIG = LiveTestConfig.from_env()
|
|
200
|
+
install_live_tls_defaults(_CONFIG)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def configure(**kwargs: object) -> LiveTestConfig:
|
|
204
|
+
"""Update the module-level live-test configuration."""
|
|
205
|
+
global _CONFIG
|
|
206
|
+
current = _CONFIG
|
|
207
|
+
data = current.__dict__ | kwargs
|
|
208
|
+
if isinstance(data.get("repo_root"), str):
|
|
209
|
+
data["repo_root"] = Path(str(data["repo_root"])).resolve()
|
|
210
|
+
if isinstance(data.get("deployment_root"), str):
|
|
211
|
+
data["deployment_root"] = Path(str(data["deployment_root"])).resolve()
|
|
212
|
+
if isinstance(data.get("service_base_urls"), Mapping):
|
|
213
|
+
data["service_base_urls"] = dict(data["service_base_urls"])
|
|
214
|
+
_CONFIG = LiveTestConfig(**data).normalized()
|
|
215
|
+
install_live_tls_defaults(_CONFIG)
|
|
216
|
+
return _CONFIG
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def load_env_file(path: str | Path, *, override: bool = False) -> dict[str, str]:
|
|
220
|
+
"""Load KEY=VALUE pairs from an env file into ``os.environ``."""
|
|
221
|
+
env_path = Path(path)
|
|
222
|
+
loaded: dict[str, str] = {}
|
|
223
|
+
if not env_path.exists():
|
|
224
|
+
return loaded
|
|
225
|
+
for line in env_path.read_text(encoding="utf-8").splitlines():
|
|
226
|
+
stripped = line.strip()
|
|
227
|
+
if not stripped or stripped.startswith("#") or "=" not in stripped:
|
|
228
|
+
continue
|
|
229
|
+
name, value = stripped.split("=", 1)
|
|
230
|
+
name = name.strip()
|
|
231
|
+
value = value.strip().strip("'\"")
|
|
232
|
+
if not name:
|
|
233
|
+
continue
|
|
234
|
+
loaded[name] = value
|
|
235
|
+
if override or name not in os.environ:
|
|
236
|
+
os.environ[name] = value
|
|
237
|
+
return loaded
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def configure_from_env(
|
|
241
|
+
env_file: str | Path | None = None,
|
|
242
|
+
*,
|
|
243
|
+
override_env_file: bool = False,
|
|
244
|
+
**defaults: Any,
|
|
245
|
+
) -> LiveTestConfig:
|
|
246
|
+
"""Load an optional env file and configure live tests from env plus defaults."""
|
|
247
|
+
env_path = Path.cwd() / ".env" if env_file is None else Path(env_file)
|
|
248
|
+
load_env_file(env_path, override=override_env_file)
|
|
249
|
+
|
|
250
|
+
config = LiveTestConfig.from_env()
|
|
251
|
+
data: dict[str, Any] = {}
|
|
252
|
+
for field_name, default in defaults.items():
|
|
253
|
+
env_names = _FIELD_ENV_NAMES.get(field_name, ())
|
|
254
|
+
if not any(name in os.environ for name in env_names):
|
|
255
|
+
data[field_name] = default
|
|
256
|
+
|
|
257
|
+
return configure(**(config.__dict__ | data))
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def get_config() -> LiveTestConfig:
|
|
261
|
+
"""Return the active live-test configuration."""
|
|
262
|
+
return _CONFIG
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Live stack detection helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import requests
|
|
10
|
+
|
|
11
|
+
from security_tests_m8._config import get_config
|
|
12
|
+
|
|
13
|
+
_DETECT_TIMEOUT = 5
|
|
14
|
+
DEFAULT_STATEFUL_MODE = "stateful"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _read_env_value(path: Path, name: str) -> str | None:
|
|
18
|
+
if not path.exists():
|
|
19
|
+
return None
|
|
20
|
+
prefix = f"{name}="
|
|
21
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
22
|
+
stripped = line.strip()
|
|
23
|
+
if stripped.startswith(prefix):
|
|
24
|
+
return stripped.split("=", 1)[1].strip().strip("'\"")
|
|
25
|
+
return None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _configured_token_mode() -> str | None:
|
|
29
|
+
env_value = os.getenv("LIVE_TEST_TOKEN_MODE")
|
|
30
|
+
if env_value:
|
|
31
|
+
return env_value.lower()
|
|
32
|
+
deployment_root = get_config().deployment_root
|
|
33
|
+
if deployment_root is None:
|
|
34
|
+
return None
|
|
35
|
+
token_mode = _read_env_value(deployment_root / "auth.env", "TOKEN_MODE")
|
|
36
|
+
return token_mode.lower() if token_mode else None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class StackInfo:
|
|
41
|
+
"""Detected live-stack security properties."""
|
|
42
|
+
|
|
43
|
+
reachable: bool = False
|
|
44
|
+
algorithm: str = "HS256"
|
|
45
|
+
token_mode: str = DEFAULT_STATEFUL_MODE
|
|
46
|
+
has_jwks: bool = False
|
|
47
|
+
redis_ok: bool = True
|
|
48
|
+
|
|
49
|
+
def get(self, key: str, default: object = None) -> object:
|
|
50
|
+
"""Dictionary-compatible accessor for ported pytest suites."""
|
|
51
|
+
return getattr(self, key, default)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _internal_headers() -> dict[str, str]:
|
|
55
|
+
secret = get_config().private_api_secret
|
|
56
|
+
if not secret:
|
|
57
|
+
return {}
|
|
58
|
+
return {"X-Internal-Token": secret}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _get_health_response() -> requests.Response | None:
|
|
62
|
+
config = get_config()
|
|
63
|
+
url = config.auth_health_url or f"{config.auth_base_url}/health"
|
|
64
|
+
try:
|
|
65
|
+
response = requests.get(
|
|
66
|
+
url, headers=_internal_headers(), timeout=_DETECT_TIMEOUT
|
|
67
|
+
)
|
|
68
|
+
except requests.RequestException:
|
|
69
|
+
return None
|
|
70
|
+
if response.status_code == 200:
|
|
71
|
+
return response
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _is_reachable_via_meta(auth_base_url: str) -> bool:
|
|
76
|
+
try:
|
|
77
|
+
response = requests.get(f"{auth_base_url}/meta", timeout=_DETECT_TIMEOUT)
|
|
78
|
+
except requests.RequestException:
|
|
79
|
+
return False
|
|
80
|
+
return response.status_code == 200
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _token_mode_from_health(
|
|
84
|
+
response: requests.Response | None,
|
|
85
|
+
) -> tuple[str, bool]:
|
|
86
|
+
token_mode = _configured_token_mode() or DEFAULT_STATEFUL_MODE
|
|
87
|
+
redis_ok = True
|
|
88
|
+
if response is None:
|
|
89
|
+
return token_mode, redis_ok
|
|
90
|
+
try:
|
|
91
|
+
body = response.json()
|
|
92
|
+
if "token_mode" in body:
|
|
93
|
+
token_mode = str(body["token_mode"])
|
|
94
|
+
if "redis" in body:
|
|
95
|
+
redis_ok = body["redis"] == "ok"
|
|
96
|
+
except (KeyError, ValueError, TypeError):
|
|
97
|
+
pass
|
|
98
|
+
return token_mode, redis_ok
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def detect_stack() -> StackInfo:
|
|
102
|
+
"""Probe health/meta/JWKS endpoints to detect the running stack."""
|
|
103
|
+
config = get_config()
|
|
104
|
+
health_response = _get_health_response()
|
|
105
|
+
if health_response is None and not _is_reachable_via_meta(config.auth_base_url):
|
|
106
|
+
return StackInfo()
|
|
107
|
+
|
|
108
|
+
token_mode, redis_ok = _token_mode_from_health(health_response)
|
|
109
|
+
algorithm = "HS256"
|
|
110
|
+
has_jwks = False
|
|
111
|
+
try:
|
|
112
|
+
jwks = requests.get(
|
|
113
|
+
f"{config.auth_base_url}/.well-known/jwks.json",
|
|
114
|
+
timeout=_DETECT_TIMEOUT,
|
|
115
|
+
)
|
|
116
|
+
if jwks.status_code == 200:
|
|
117
|
+
keys = jwks.json().get("keys", [])
|
|
118
|
+
if keys:
|
|
119
|
+
algorithm = str(keys[0].get("alg", "RS256"))
|
|
120
|
+
has_jwks = True
|
|
121
|
+
except (KeyError, ValueError, TypeError, requests.RequestException):
|
|
122
|
+
pass
|
|
123
|
+
|
|
124
|
+
return StackInfo(
|
|
125
|
+
reachable=True,
|
|
126
|
+
algorithm=algorithm,
|
|
127
|
+
token_mode=token_mode,
|
|
128
|
+
has_jwks=has_jwks,
|
|
129
|
+
redis_ok=redis_ok,
|
|
130
|
+
)
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Fail-fast checks for live security test sessions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import requests
|
|
8
|
+
|
|
9
|
+
from security_tests_m8._config import LiveTestConfig
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class PreflightError(RuntimeError):
|
|
13
|
+
"""Raised when a live stack is not safe or ready for the full suite."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _read_env_value(path: Path, name: str) -> str | None:
|
|
17
|
+
if not path.exists():
|
|
18
|
+
return None
|
|
19
|
+
prefix = f"{name}="
|
|
20
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
21
|
+
stripped = line.strip()
|
|
22
|
+
if stripped.startswith(prefix):
|
|
23
|
+
return stripped.split("=", 1)[1].strip().strip("'\"")
|
|
24
|
+
return None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _ensure_not_bootstrap_superuser(config: LiveTestConfig) -> None:
|
|
28
|
+
if not config.forbid_bootstrap_superuser or config.deployment_root is None:
|
|
29
|
+
return
|
|
30
|
+
|
|
31
|
+
bootstrap_email = _read_env_value(
|
|
32
|
+
config.deployment_root / "auth.env", "FIRST_SUPERUSER"
|
|
33
|
+
)
|
|
34
|
+
if bootstrap_email and config.admin_email.lower() == bootstrap_email.lower():
|
|
35
|
+
raise PreflightError(
|
|
36
|
+
"Refusing to run with the stack bootstrap superuser. Configure "
|
|
37
|
+
"LIVE_TEST_ADMIN_EMAIL/LIVE_TEST_ADMIN_PASSWORD with a dedicated "
|
|
38
|
+
"test-only superuser."
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _internal_headers(config: LiveTestConfig) -> dict[str, str]:
|
|
43
|
+
if not config.private_api_secret:
|
|
44
|
+
return {}
|
|
45
|
+
return {"X-Internal-Token": config.private_api_secret}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _check_auth_available(config: LiveTestConfig) -> None:
|
|
49
|
+
health_url = config.auth_health_url or f"{config.auth_base_url}/health"
|
|
50
|
+
probes: tuple[tuple[str, dict[str, str]], ...] = (
|
|
51
|
+
(health_url, _internal_headers(config)),
|
|
52
|
+
(f"{config.auth_base_url}/meta", {}),
|
|
53
|
+
)
|
|
54
|
+
failures: list[str] = []
|
|
55
|
+
for url, headers in probes:
|
|
56
|
+
try:
|
|
57
|
+
response = requests.get(url, headers=headers, timeout=config.timeout)
|
|
58
|
+
except requests.RequestException as exc:
|
|
59
|
+
failures.append(f"{url}: {exc}")
|
|
60
|
+
continue
|
|
61
|
+
if response.status_code in (200, 204):
|
|
62
|
+
return
|
|
63
|
+
if response.status_code >= 500:
|
|
64
|
+
raise PreflightError(
|
|
65
|
+
f"Auth API readiness probe {url} returned "
|
|
66
|
+
f"{response.status_code}: {response.text}"
|
|
67
|
+
)
|
|
68
|
+
failures.append(f"{url}: {response.status_code} {response.text}")
|
|
69
|
+
|
|
70
|
+
raise PreflightError(
|
|
71
|
+
"Auth API is not reachable on health or meta readiness probes: "
|
|
72
|
+
+ "; ".join(failures)
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _check_services_available(config: LiveTestConfig) -> None:
|
|
77
|
+
for name, base_url in config.service_base_urls.items():
|
|
78
|
+
try:
|
|
79
|
+
response = requests.get(base_url, timeout=config.timeout)
|
|
80
|
+
except requests.RequestException as exc:
|
|
81
|
+
raise PreflightError(
|
|
82
|
+
f"Service {name!r} is not reachable at {base_url}: {exc}"
|
|
83
|
+
) from exc
|
|
84
|
+
if response.status_code >= 500:
|
|
85
|
+
raise PreflightError(
|
|
86
|
+
f"Service {name!r} returned {response.status_code} at {base_url}: "
|
|
87
|
+
f"{response.text}"
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _check_admin_credentials(config: LiveTestConfig) -> None:
|
|
92
|
+
try:
|
|
93
|
+
response = requests.post(
|
|
94
|
+
f"{config.auth_base_url}/login/access-token",
|
|
95
|
+
data={"username": config.admin_email, "password": config.admin_password},
|
|
96
|
+
timeout=config.timeout,
|
|
97
|
+
)
|
|
98
|
+
except requests.RequestException as exc:
|
|
99
|
+
raise PreflightError(
|
|
100
|
+
f"Admin login preflight could not reach auth API: {exc}"
|
|
101
|
+
) from exc
|
|
102
|
+
|
|
103
|
+
if response.status_code == 200:
|
|
104
|
+
try:
|
|
105
|
+
token = response.json().get("access_token")
|
|
106
|
+
except ValueError as exc:
|
|
107
|
+
raise PreflightError(
|
|
108
|
+
"Admin login returned non-JSON success response"
|
|
109
|
+
) from exc
|
|
110
|
+
if not token:
|
|
111
|
+
raise PreflightError("Admin login response did not contain access_token")
|
|
112
|
+
return
|
|
113
|
+
|
|
114
|
+
if response.status_code == 429:
|
|
115
|
+
raise PreflightError(
|
|
116
|
+
"Admin login is rate-limited. Wait for the lockout window or clear only "
|
|
117
|
+
f"the live-test login limiter state. Response: {response.text}"
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
if response.status_code in (400, 401, 403, 404):
|
|
121
|
+
raise PreflightError(
|
|
122
|
+
"Configured live-test admin credentials are invalid or the dedicated "
|
|
123
|
+
f"test superuser does not exist. Status {response.status_code}: "
|
|
124
|
+
f"{response.text}"
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
raise PreflightError(
|
|
128
|
+
f"Admin login preflight failed with {response.status_code}: {response.text}"
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def run_live_preflight(config: LiveTestConfig) -> None:
|
|
133
|
+
"""Validate that the full live suite can run before pytest collection."""
|
|
134
|
+
_ensure_not_bootstrap_superuser(config)
|
|
135
|
+
_check_auth_available(config)
|
|
136
|
+
_check_services_available(config)
|
|
137
|
+
_check_admin_credentials(config)
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Request defaults for configured live-test target URLs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Any
|
|
6
|
+
|
|
7
|
+
import requests
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from security_tests_m8._config import LiveTestConfig
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
_ORIGINAL_REQUEST = requests.sessions.Session.request
|
|
14
|
+
_INSTALLED = False
|
|
15
|
+
_TLS_VERIFY: bool | str = True
|
|
16
|
+
_TLS_PREFIXES: tuple[str, ...] = ()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _url_matches_live_https_target(url: object) -> bool:
|
|
20
|
+
url_text = str(url)
|
|
21
|
+
if not url_text.lower().startswith("https://"):
|
|
22
|
+
return False
|
|
23
|
+
return any(
|
|
24
|
+
url_text == prefix or url_text.startswith(f"{prefix}/")
|
|
25
|
+
for prefix in _TLS_PREFIXES
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _request_with_live_tls_defaults(
|
|
30
|
+
self: requests.sessions.Session, method: str, url: str, **kwargs: Any
|
|
31
|
+
) -> requests.Response:
|
|
32
|
+
if "verify" not in kwargs and _TLS_VERIFY is not True:
|
|
33
|
+
if _url_matches_live_https_target(url):
|
|
34
|
+
kwargs["verify"] = _TLS_VERIFY
|
|
35
|
+
return _ORIGINAL_REQUEST(self, method, url, **kwargs)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def install_live_tls_defaults(config: LiveTestConfig) -> None:
|
|
39
|
+
"""Apply configured TLS verification defaults to live-test target requests."""
|
|
40
|
+
global _INSTALLED, _TLS_PREFIXES, _TLS_VERIFY
|
|
41
|
+
|
|
42
|
+
prefixes = {
|
|
43
|
+
config.auth_base_url,
|
|
44
|
+
config.auth_health_url,
|
|
45
|
+
config.service_base_url,
|
|
46
|
+
config.public_base_url,
|
|
47
|
+
*config.service_base_urls.values(),
|
|
48
|
+
}
|
|
49
|
+
_TLS_PREFIXES = tuple(
|
|
50
|
+
sorted(
|
|
51
|
+
(prefix.rstrip("/") for prefix in prefixes if prefix),
|
|
52
|
+
key=len,
|
|
53
|
+
reverse=True,
|
|
54
|
+
)
|
|
55
|
+
)
|
|
56
|
+
_TLS_VERIFY = config.public_tls_verify
|
|
57
|
+
|
|
58
|
+
if not _INSTALLED:
|
|
59
|
+
setattr(requests.sessions.Session, "request", _request_with_live_tls_defaults)
|
|
60
|
+
_INSTALLED = True
|