ЛР7: проверки экспозиции портов и hardening в сквозном тесте
- test_lab7 проверяет, что наружу опубликованы только 127.0.0.1/[::1] порты, и инспектирует api-реплики (non-root, read_only, cap_drop, no-new-privileges) - ожидание готовности после ротации ingress/api и worker - application_name пула БД берётся из роли сервиса Co-Authored-By: O3 Agent Claude <noreply@ozon.ru>
This commit is contained in:
@@ -30,7 +30,7 @@ def get_pool():
|
|||||||
reconnect_timeout=5,
|
reconnect_timeout=5,
|
||||||
check=ConnectionPool.check_connection,
|
check=ConnectionPool.check_connection,
|
||||||
kwargs={"row_factory": dict_row, "connect_timeout": 3, "options": options,
|
kwargs={"row_factory": dict_row, "connect_timeout": 3, "options": options,
|
||||||
"application_name": "messenger-api"},
|
"application_name": config.SERVICE},
|
||||||
open=False)
|
open=False)
|
||||||
pool.open(wait=False)
|
pool.open(wait=False)
|
||||||
_pool = pool
|
_pool = pool
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ def main():
|
|||||||
|
|
||||||
from . import health, relay # noqa: PLC0415
|
from . import health, relay # noqa: PLC0415
|
||||||
|
|
||||||
os.environ.setdefault("APP_SERVICE", "messenger-api")
|
|
||||||
relay.start()
|
relay.start()
|
||||||
health.start()
|
health.start()
|
||||||
|
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ def probe(*args, timeout=180):
|
|||||||
return json.loads(lines[-1])
|
return json.loads(lines[-1])
|
||||||
|
|
||||||
|
|
||||||
def http(method, path, body=None, headers=None, token=None, base=None, ca=None):
|
def http(method, path, body=None, headers=None, token=None, base=None, ca=None, timeout=20):
|
||||||
data = json.dumps(body).encode("utf-8") if body is not None else None
|
data = json.dumps(body).encode("utf-8") if body is not None else None
|
||||||
request = urllib.request.Request((base or BASE) + path, data=data, method=method)
|
request = urllib.request.Request((base or BASE) + path, data=data, method=method)
|
||||||
if body is not None:
|
if body is not None:
|
||||||
@@ -70,7 +70,7 @@ def http(method, path, body=None, headers=None, token=None, base=None, ca=None):
|
|||||||
request.add_header(key, value)
|
request.add_header(key, value)
|
||||||
context = ssl.create_default_context(cafile=ca or CA_PUBLIC)
|
context = ssl.create_default_context(cafile=ca or CA_PUBLIC)
|
||||||
try:
|
try:
|
||||||
with urllib.request.urlopen(request, timeout=20, context=context) as resp:
|
with urllib.request.urlopen(request, timeout=timeout, context=context) as resp:
|
||||||
raw = resp.read()
|
raw = resp.read()
|
||||||
return resp.status, dict(resp.headers), json.loads(raw) if raw else None
|
return resp.status, dict(resp.headers), json.loads(raw) if raw else None
|
||||||
except urllib.error.HTTPError as exc:
|
except urllib.error.HTTPError as exc:
|
||||||
@@ -124,6 +124,18 @@ def wait_attachment(token, attachment_id, seconds=90):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def wait_ready(seconds=180):
|
||||||
|
deadline = time.time() + seconds
|
||||||
|
while time.time() < deadline:
|
||||||
|
try:
|
||||||
|
if http("GET", "/health/ready", timeout=5)[0] == 200:
|
||||||
|
return True
|
||||||
|
except (urllib.error.URLError, OSError):
|
||||||
|
pass
|
||||||
|
time.sleep(2)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def hostname_probe():
|
def hostname_probe():
|
||||||
"""Внешний TLS к 127.0.0.1: сертификат выписан на localhost, hostname не совпадает."""
|
"""Внешний TLS к 127.0.0.1: сертификат выписан на localhost, hostname не совпадает."""
|
||||||
ctx = ssl.create_default_context(cafile=CA_PUBLIC)
|
ctx = ssl.create_default_context(cafile=CA_PUBLIC)
|
||||||
@@ -164,6 +176,32 @@ def main():
|
|||||||
check("external TLS: wrong hostname rejected by verification",
|
check("external TLS: wrong hostname rejected by verification",
|
||||||
wrong_name.startswith("cert_error"), wrong_name)
|
wrong_name.startswith("cert_error"), wrong_name)
|
||||||
|
|
||||||
|
# 1b. Наружу — только loopback-порты; app-контейнеры hardened.
|
||||||
|
ps_out = compose("ps", "--format", "{{.Service}}|{{.Ports}}").stdout
|
||||||
|
public = [line for line in ps_out.splitlines()
|
||||||
|
if "->" in line and "127.0.0.1:" not in line and "[::1]:" not in line]
|
||||||
|
check("exposure: no service published on all interfaces", not public,
|
||||||
|
"; ".join(public)[:240])
|
||||||
|
|
||||||
|
api_ids = compose("ps", "-q", "api").stdout.split()
|
||||||
|
hardening_ok = bool(api_ids)
|
||||||
|
details = []
|
||||||
|
if api_ids:
|
||||||
|
try:
|
||||||
|
for item in json.loads(run(["docker", "inspect", *api_ids]).stdout):
|
||||||
|
cfg, host = item["Config"], item["HostConfig"]
|
||||||
|
ok = (host.get("ReadonlyRootfs") is True
|
||||||
|
and "ALL" in (host.get("CapDrop") or [])
|
||||||
|
and any("no-new-privileges" in str(opt) for opt in (host.get("SecurityOpt") or []))
|
||||||
|
and bool(cfg.get("User")))
|
||||||
|
hardening_ok = hardening_ok and ok
|
||||||
|
details.append("%s user=%s ro=%s" % (item["Name"].lstrip("/"),
|
||||||
|
cfg.get("User"), host.get("ReadonlyRootfs")))
|
||||||
|
except (ValueError, KeyError):
|
||||||
|
hardening_ok = False
|
||||||
|
check("hardening: api replicas non-root, read-only, cap_drop, no-new-privileges",
|
||||||
|
hardening_ok, "; ".join(details)[:240])
|
||||||
|
|
||||||
# 2. Публичный smoke по HTTPS.
|
# 2. Публичный smoke по HTTPS.
|
||||||
r = run([PY, "tests/smoke.py", "--base-url", BASE, "--ca-file", CA_PUBLIC], timeout=600)
|
r = run([PY, "tests/smoke.py", "--base-url", BASE, "--ca-file", CA_PUBLIC], timeout=600)
|
||||||
check("public smoke over HTTPS", r.returncode == 0,
|
check("public smoke over HTTPS", r.returncode == 0,
|
||||||
@@ -347,6 +385,7 @@ def main():
|
|||||||
(ROOT / "pki/revoked/ingress-client.key").write_bytes(
|
(ROOT / "pki/revoked/ingress-client.key").write_bytes(
|
||||||
(ROOT / "pki/leaf/ingress-client.key").read_bytes())
|
(ROOT / "pki/leaf/ingress-client.key").read_bytes())
|
||||||
sh("scripts/revoke-identity.sh", "ingress-client")
|
sh("scripts/revoke-identity.sh", "ingress-client")
|
||||||
|
check("rotation: stack back to ready after recreating ingress/api", wait_ready())
|
||||||
revoked_probe = probe("api", "--cert", "/pki/revoked/ingress-client.crt",
|
revoked_probe = probe("api", "--cert", "/pki/revoked/ingress-client.crt",
|
||||||
"--key", "/pki/revoked/ingress-client.key",
|
"--key", "/pki/revoked/ingress-client.key",
|
||||||
"--ca", "/pki/trust/ca-clients-bundle.crt")
|
"--ca", "/pki/trust/ca-clients-bundle.crt")
|
||||||
@@ -362,6 +401,7 @@ def main():
|
|||||||
# 11. Ротация рабочего секрета (S3 worker) без пересборки.
|
# 11. Ротация рабочего секрета (S3 worker) без пересборки.
|
||||||
id_before = image_id()
|
id_before = image_id()
|
||||||
sh("scripts/rotate-secret.sh", timeout=600)
|
sh("scripts/rotate-secret.sh", timeout=600)
|
||||||
|
check("rotation: stack back to ready after recreating worker", wait_ready())
|
||||||
old_pair_file = ROOT / "secrets/.rotated-old-s3-worker"
|
old_pair_file = ROOT / "secrets/.rotated-old-s3-worker"
|
||||||
if old_pair_file.exists():
|
if old_pair_file.exists():
|
||||||
old_new_key, old_new_secret = old_pair_file.read_text().strip().splitlines()
|
old_new_key, old_new_secret = old_pair_file.read_text().strip().splitlines()
|
||||||
|
|||||||
Reference in New Issue
Block a user