From 43d167f66baed9d52b7d4220395ed5b841bb4772 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B8=D0=BA=D0=B8=D1=84=D0=BE=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0=20=D0=95=D0=BA=D0=B0=D1=82=D0=B5=D1=80=D0=B8=D0=BD=D0=B0?= Date: Fri, 27 Nov 2026 19:59:28 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=A07:=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=D0=BA=D0=B8=20=D1=8D=D0=BA=D1=81=D0=BF=D0=BE=D0=B7=D0=B8?= =?UTF-8?q?=D1=86=D0=B8=D0=B8=20=D0=BF=D0=BE=D1=80=D1=82=D0=BE=D0=B2=20?= =?UTF-8?q?=D0=B8=20hardening=20=D0=B2=20=D1=81=D0=BA=D0=B2=D0=BE=D0=B7?= =?UTF-8?q?=D0=BD=D0=BE=D0=BC=20=D1=82=D0=B5=D1=81=D1=82=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- app/db.py | 2 +- app/server.py | 1 - student-tests/test_lab7.py | 44 ++++++++++++++++++++++++++++++++++++-- 3 files changed, 43 insertions(+), 4 deletions(-) diff --git a/app/db.py b/app/db.py index b3349cd..e5815dd 100644 --- a/app/db.py +++ b/app/db.py @@ -30,7 +30,7 @@ def get_pool(): reconnect_timeout=5, check=ConnectionPool.check_connection, kwargs={"row_factory": dict_row, "connect_timeout": 3, "options": options, - "application_name": "messenger-api"}, + "application_name": config.SERVICE}, open=False) pool.open(wait=False) _pool = pool diff --git a/app/server.py b/app/server.py index 33cfef1..57d9208 100644 --- a/app/server.py +++ b/app/server.py @@ -17,7 +17,6 @@ def main(): from . import health, relay # noqa: PLC0415 - os.environ.setdefault("APP_SERVICE", "messenger-api") relay.start() health.start() diff --git a/student-tests/test_lab7.py b/student-tests/test_lab7.py index a7b04d7..69c444f 100644 --- a/student-tests/test_lab7.py +++ b/student-tests/test_lab7.py @@ -59,7 +59,7 @@ def probe(*args, timeout=180): 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 request = urllib.request.Request((base or BASE) + path, data=data, method=method) 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) context = ssl.create_default_context(cafile=ca or CA_PUBLIC) 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() return resp.status, dict(resp.headers), json.loads(raw) if raw else None except urllib.error.HTTPError as exc: @@ -124,6 +124,18 @@ def wait_attachment(token, attachment_id, seconds=90): 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(): """Внешний TLS к 127.0.0.1: сертификат выписан на localhost, hostname не совпадает.""" ctx = ssl.create_default_context(cafile=CA_PUBLIC) @@ -164,6 +176,32 @@ def main(): check("external TLS: wrong hostname rejected by verification", 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. r = run([PY, "tests/smoke.py", "--base-url", BASE, "--ca-file", CA_PUBLIC], timeout=600) check("public smoke over HTTPS", r.returncode == 0, @@ -347,6 +385,7 @@ def main(): (ROOT / "pki/revoked/ingress-client.key").write_bytes( (ROOT / "pki/leaf/ingress-client.key").read_bytes()) 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", "--key", "/pki/revoked/ingress-client.key", "--ca", "/pki/trust/ca-clients-bundle.crt") @@ -362,6 +401,7 @@ def main(): # 11. Ротация рабочего секрета (S3 worker) без пересборки. id_before = image_id() 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" if old_pair_file.exists(): old_new_key, old_new_secret = old_pair_file.read_text().strip().splitlines()