#!/usr/bin/env python3 """lab7: сквозные положительные и отрицательные проверки доверия. Запуск (Git Bash/WSL, стенд поднят, секреты созданы): python student-tests/test_lab7.py Проверяет то, что не покрывают публичные тесты: mTLS LB→API, mTLS к broker и OTLP-ingress, ACL и scoped policies OpenBao, rate limit, rehash Argon2id, ротацию/отзыв identity, sealed OpenBao и отсутствие утечек в telemetry. """ import base64 import json import os import pathlib import re import ssl import subprocess import sys import time import urllib.error import urllib.request import uuid ROOT = pathlib.Path(__file__).resolve().parents[1] BASE = os.environ.get("BASE_URL", "https://localhost:8443").rstrip("/") CA_PUBLIC = str(ROOT / "pki/trust/public-ca.crt") CA_SERVERS = str(ROOT / "pki/trust/ca-servers-bundle.crt") PY = os.environ.get("PYTHON", sys.executable) COMPOSE = ["docker", "compose", "--env-file", ".env"] RESULTS = [] def check(name, ok, detail=""): RESULTS.append((name, bool(ok), detail)) print(("PASS " if ok else "FAIL ") + name + (" — " + detail if detail else "")) return ok def run(cmd, timeout=240, input_text=None): return subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, timeout=timeout, input=input_text) def compose(*args, timeout=240): return run(COMPOSE + list(args), timeout=timeout) def sh(script, *args, timeout=300): return run(["sh", script, *args], timeout=timeout) def probe(*args, timeout=180): result = compose("--profile", "tools", "run", "--rm", "-T", "mtls-probe", *args, timeout=timeout) lines = [line for line in result.stdout.splitlines() if line.startswith("{")] if not lines: return {"result": "no_output", "stderr": result.stderr[-400:]} return json.loads(lines[-1]) 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: request.add_header("Content-Type", "application/json") if token: request.add_header("Authorization", "Bearer " + token) for key, value in (headers or {}).items(): request.add_header(key, value) context = ssl.create_default_context(cafile=ca or CA_PUBLIC) try: 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: raw = exc.read() try: parsed = json.loads(raw) if raw else None except ValueError: parsed = None return exc.code, dict(exc.headers), parsed def new_user(prefix="probe"): username = (prefix + uuid.uuid4().hex)[:24] password = "Pw-" + uuid.uuid4().hex status, _, body = http("POST", "/api/v1/users", { "username": username, "display_name": "Probe " + username[-4:], "password": password}) if status != 201: raise RuntimeError("create_user failed: %s %s" % (status, body)) return username, password, body def login(username, password): creds = base64.b64encode(("%s:%s" % (username, password)).encode("utf-8")).decode("ascii") return http("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + creds}) def create_chat(token, member_ids, title="probe"): return http("POST", "/api/v1/chats", {"title": title, "member_ids": member_ids}, token=token) def upload(token, chat_id, filename="probe.png"): payload = (ROOT / "tests/fixtures/sample.png").read_bytes() request = urllib.request.Request( "%s/api/v1/chats/%s/attachments?filename=%s" % (BASE, chat_id, filename), data=payload, method="POST") request.add_header("Authorization", "Bearer " + token) request.add_header("Content-Type", "image/png") with urllib.request.urlopen(request, timeout=30, context=ssl.create_default_context(cafile=CA_PUBLIC)) as resp: return json.loads(resp.read()) def wait_attachment(token, attachment_id, seconds=90): deadline = time.time() + seconds while time.time() < deadline: status, _, body = http("GET", "/api/v1/attachments/" + attachment_id, token=token) if status == 200 and body.get("status") in ("ready", "failed"): return body time.sleep(2) 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) try: urllib.request.urlopen("https://127.0.0.1:8443/health/ready", context=ctx, timeout=10) return "ok" except ssl.SSLCertVerificationError as exc: return "cert_error:" + (exc.verify_message or type(exc).__name__) except urllib.error.URLError as exc: return "url_error:" + type(exc.reason).__name__ def image_id(): result = run(["docker", "image", "inspect", "messenger-lab7-app:1.7.0", "--format", "{{.Id}}"]) return result.stdout.strip() def psql(sql): return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-tAc", sql) def main(): failures = 0 # 0. Контракт и PKI-материал для отрицательных тестов. check("make check (offline contract)", run([PY, "scripts/check_contract.py"]).returncode == 0) sh("scripts/pki.sh", "rogue") check("rogue PKI material present", (ROOT / "pki/rogue/rogue-same-ca.crt").exists()) # 1. Внешний TLS: доверенный CA/hostname проходит, пустой trust store — нет. r = run([PY, "tests/security.py", "--base-url", BASE, "--ca-file", CA_PUBLIC]) check("external TLS trust (public test-security)", r.returncode == 0, r.stdout.strip().splitlines()[-1] if r.stdout else r.stderr[-200:]) wrong_name = hostname_probe() 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, r.stdout.strip().splitlines()[-1] if r.stdout else r.stderr[-300:]) if r.returncode != 0: print(r.stdout[-2000:]) print(r.stderr[-2000:]) # 3. LB -> API mTLS: матрица identity. allowed = probe("api", "--ca", "/pki/trust/ca-clients-bundle.crt", "--cert", "/pki/leaf/ingress-client.crt", "--key", "/pki/leaf/ingress-client.key") check("mTLS LB->API: allowed identity lb", allowed.get("result") == "ok", str(allowed)) no_cert = probe("api", "--ca", "/pki/trust/ca-clients-bundle.crt") check("mTLS LB->API: no client certificate rejected", no_cert.get("result") == "tls_error", str(no_cert)) rogue = probe("api", "--ca", "/pki/trust/ca-clients-bundle.crt", "--cert", "/pki/rogue/rogue-same-ca.crt", "--key", "/pki/rogue/rogue.key") check("mTLS LB->API: same-CA foreign identity rejected", rogue.get("result") == "http" and rogue.get("status") == 403, str(rogue)) foreign = probe("api", "--ca", "/pki/trust/ca-clients-bundle.crt", "--cert", "/pki/rogue/foreign.crt", "--key", "/pki/rogue/foreign.key") check("mTLS LB->API: certificate from foreign CA rejected", foreign.get("result") == "tls_error", str(foreign)) scoped = probe("api", "--path", "/api/v1/users/me", "--ca", "/pki/trust/ca-clients-bundle.crt", "--cert", "/pki/leaf/health-client.crt", "--key", "/pki/leaf/health-client.key") check("mTLS LB->API: health identity cannot call business API", scoped.get("result") == "http" and scoped.get("status") == 403, str(scoped)) # 4. Broker: mTLS + EXTERNAL auth + ACL. api_broker = probe("broker", "--cert", "/pki/leaf/api-client.crt", "--key", "/pki/leaf/api-client.key") check("broker mTLS: messenger-api identity accepted", api_broker.get("result") == "ok", str(api_broker)) worker_broker = probe("broker", "--cert", "/pki/leaf/worker-client.crt", "--key", "/pki/leaf/worker-client.key") check("broker mTLS: messenger-worker identity accepted", worker_broker.get("result") == "ok", str(worker_broker)) rogue_broker = probe("broker", "--cert", "/pki/rogue/rogue-same-ca.crt", "--key", "/pki/rogue/rogue.key") check("broker mTLS: same-CA foreign identity rejected", rogue_broker.get("result") in ("connect_error", "access_denied"), str(rogue_broker)) acl_broker = probe("broker", "--cert", "/pki/leaf/worker-client.crt", "--key", "/pki/leaf/worker-client.key", "--foreign-queue") check("broker ACL: worker cannot declare a foreign queue", acl_broker.get("result") in ("access_denied", "connect_error"), str(acl_broker)) # 5. OTLP ingress: mTLS + identity allowlist. otlp_ok = probe("otlp", "--cert", "/pki/leaf/api-client.crt", "--key", "/pki/leaf/api-client.key") check("OTLP ingress: api identity accepted", otlp_ok.get("result") == "http", str(otlp_ok)) otlp_rogue = probe("otlp", "--cert", "/pki/rogue/rogue-same-ca.crt", "--key", "/pki/rogue/rogue.key") check("OTLP ingress: same-CA foreign identity rejected", otlp_rogue.get("result") == "http" and otlp_rogue.get("status") == 403, str(otlp_rogue)) otlp_none = probe("otlp") check("OTLP ingress: no client certificate rejected", otlp_none.get("result") == "tls_error", str(otlp_none)) # 6. S3: TLS + раздельные scoped credentials. api_key = (ROOT / "secrets/s3_api_access_key").read_text().strip() api_secret = (ROOT / "secrets/s3_api_secret").read_text().strip() worker_key = (ROOT / "secrets/s3_worker_access_key").read_text().strip() worker_secret = (ROOT / "secrets/s3_worker_secret").read_text().strip() s3_api_staging = probe("s3", "--access-key", api_key, "--secret", api_secret, "--key-prefix", "staging") check("S3: api may write staging/", s3_api_staging.get("result") == "ok", str(s3_api_staging)) s3_api_originals = probe("s3", "--access-key", api_key, "--secret", api_secret, "--key-prefix", "originals") check("S3: api cannot write originals/", s3_api_originals.get("result") == "denied", str(s3_api_originals)) s3_worker_staging = probe("s3", "--access-key", worker_key, "--secret", worker_secret, "--key-prefix", "staging") check("S3: worker cannot write staging/", s3_worker_staging.get("result") == "denied", str(s3_worker_staging)) s3_worker_originals = probe("s3", "--access-key", worker_key, "--secret", worker_secret, "--key-prefix", "originals") check("S3: worker may write originals/", s3_worker_originals.get("result") == "ok", str(s3_worker_originals)) # 7. ACL и идентичность. alice_name, alice_pw, alice = new_user("alice") bob_name, bob_pw, bob = new_user("bob") eve_name, eve_pw, eve = new_user("eve") _, _, alice_session = login(alice_name, alice_pw) _, _, bob_session = login(bob_name, bob_pw) _, _, eve_session = login(eve_name, eve_pw) alice_token = alice_session["token"] bob_token = bob_session["token"] eve_token = eve_session["token"] status, _, chat = create_chat(alice_token, [alice["id"], bob["id"]]) chat_id = chat["id"] status, _, _ = create_chat(alice_token, [alice["id"]], title="secret") check("ACL: outsider cannot read chat", http("GET", "/api/v1/chats/" + chat_id, token=eve_token)[0] == 404) attachment = upload(alice_token, chat_id) check("ACL: outsider cannot read attachment metadata", http("GET", "/api/v1/attachments/" + attachment["id"], token=eve_token)[0] == 404) check("ACL: forged X-User-Id does not change identity", http("GET", "/api/v1/users/me", token=eve_token, headers={"X-User-Id": alice["id"]})[2]["id"] == eve["id"]) http("DELETE", "/api/v1/auth/sessions/current", token=eve_token) check("ACL: token invalid after logout", http("GET", "/api/v1/users/me", token=eve_token)[0] == 401) # Ошибка входа не должна различать «неверный пароль» и «нет пользователя». wrong_existing = login(alice_name, "definitely-wrong-" + uuid.uuid4().hex) wrong_missing = login("nosuch" + uuid.uuid4().hex[:12], "definitely-wrong-" + uuid.uuid4().hex) code_existing = (wrong_existing[2] or {}).get("error", {}).get("code") code_missing = (wrong_missing[2] or {}).get("error", {}).get("code") check("auth: identical error for wrong password and unknown user", wrong_existing[0] == wrong_missing[0] == 401 and code_existing == code_missing, "statuses=%s/%s codes=%s/%s" % (wrong_existing[0], wrong_missing[0], code_existing, code_missing)) ready = wait_attachment(alice_token, attachment["id"], seconds=90) check("worker pipeline ready over TLS", ready is not None and ready.get("status") == "ready", str(ready and ready.get("status"))) # 8. OpenBao: scoped policy, запрет чужих путей и записи. bao_code = "\n".join([ "from app import secrets", "tok, _ = secrets.login()", "own = secrets.read_kv(tok, 'api')", "assert own.get('database_url')", "denied = []", "for path in ('/v1/secret/data/messenger/worker', '/v1/sys/policies/acl/messenger-api'):", " try:", " secrets._request('GET', path, token=tok)", " denied.append(path)", " except secrets.OpenBaoError:", " pass", "try:", " secrets._request('POST', '/v1/secret/data/messenger/api', {'data': {'x': '1'}}, token=tok)", " denied.append('write')", "except secrets.OpenBaoError:", " pass", "import os", "assert not os.environ.get('BAO_TOKEN')", "print('DENIED=' + ','.join(denied))", ]) r = compose("exec", "-T", "api", "python", "-c", bao_code) output = (r.stdout + r.stderr).strip() check("OpenBao: api reads own secret, denied elsewhere", r.returncode == 0 and output.endswith("DENIED="), output[-200:]) # 9. Sealed OpenBao: API продолжает работать на загруженных секретах, # новый процесс не стартует, после unseal всё восстанавливается. init = json.loads((ROOT / "secrets/openbao-init.json").read_text()) seal_status, _, _ = http("POST", "/v1/sys/seal", {}, token=init["root_token"], base="https://127.0.0.1:8200", ca=CA_SERVERS) check("OpenBao: sealed by operator", seal_status in (200, 204), str(seal_status)) check("sealed OpenBao: running API stays ready", http("GET", "/health/ready")[0] == 200) name_sealed, pw_sealed, _ = new_user("sealed") check("sealed OpenBao: running API still serves business requests", login(name_sealed, pw_sealed)[0] == 201) r = compose("exec", "-T", "-e", "OPENBAO_WAIT_SECONDS=5", "api", "python", "-c", "from app import secrets; secrets.load('api')") check("sealed OpenBao: new process fails instead of using cached/file secrets", r.returncode != 0) sh("scripts/openbao-unseal.sh") check("OpenBao: unsealed again", http("GET", "/v1/sys/health", base="https://127.0.0.1:8200", ca=CA_SERVERS)[0] == 200) # 10. Ротация и отзыв leaf-certificate без пересборки образа. id_before = image_id() (ROOT / "pki/revoked").mkdir(exist_ok=True) (ROOT / "pki/revoked/ingress-client.crt").write_bytes( (ROOT / "pki/leaf/ingress-client.crt").read_bytes()) (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") check("rotation: old lb identity rejected on new connections", revoked_probe.get("result") == "http" and revoked_probe.get("status") == 403, str(revoked_probe)) new_probe = probe("api", "--cert", "/pki/leaf/ingress-client.crt", "--key", "/pki/leaf/ingress-client.key", "--ca", "/pki/trust/ca-clients-bundle.crt") check("rotation: new lb identity works", new_probe.get("result") == "ok", str(new_probe)) check("rotation: image not rebuilt", image_id() == id_before) # 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() old_probe = probe("s3", "--access-key", old_new_key, "--secret", old_new_secret, "--key-prefix", "originals") check("rotation: disabled S3 identity denied", old_probe.get("result") == "denied", str(old_probe)) old_pair_file.unlink() else: check("rotation: old S3 pair recorded for proof", False, "missing file") rotated_attachment = upload(alice_token, chat_id) rotated_ready = wait_attachment(alice_token, rotated_attachment["id"], seconds=90) check("rotation: worker works with rotated secret", rotated_ready is not None and rotated_ready.get("status") == "ready") check("rotation: image not rebuilt (secret)", image_id() == id_before) # 12. Telemetry не содержит секретов и высококардинальных labels. leak = probe("leak") check("telemetry: no secrets or user identifiers in logs/metric labels", leak.get("result") == "ok", str(leak)) # 13. Rehash Argon2id: старый hash обновляется при успешном входе. legacy_name = ("legacy" + uuid.uuid4().hex)[:24] legacy_pw = "LegacyPw-" + uuid.uuid4().hex r = compose("exec", "-T", "api", "python", "-c", "from argon2 import PasswordHasher, Type;" "print(PasswordHasher(memory_cost=8192, time_cost=2, parallelism=1," " type=Type.ID).hash('%s'))" % legacy_pw) legacy_hash = (r.stdout or "").strip().splitlines()[-1] psql("INSERT INTO users (id, username, display_name, password_hash) " "VALUES (gen_random_uuid(), '%s', 'Legacy', '%s')" % (legacy_name, legacy_hash)) status, _, _ = login(legacy_name, legacy_pw) new_hash = psql("SELECT password_hash FROM users WHERE username='%s'" % legacy_name).stdout.strip() check("rehash: legacy hash replaced on successful login", status == 201 and new_hash.startswith("$argon2id$v=19$m=19456,t=2,p=1"), "status=%s prefix=%s" % (status, new_hash[:32])) # 14. Rate limit входа: 429 + Retry-After, общий для реплик. # Идёт последним: после него входы с этого IP на минуту ограничены. lim_name = ("rl" + uuid.uuid4().hex)[:24] statuses, instances, retry_after = [], set(), None for _ in range(40): status, headers, _ = login(lim_name, "wrong-password-" + uuid.uuid4().hex) statuses.append(status) if headers.get("X-Instance-Id"): instances.add(headers["X-Instance-Id"]) if status == 429: retry_after = headers.get("Retry-After") break check("rate limit: 429 returned", 429 in statuses, "statuses=" + ",".join(map(str, statuses[-5:]))) check("rate limit: Retry-After present", bool(retry_after), str(retry_after)) check("rate limit: shared across replicas (both instances observed before 429)", len(instances) >= 2, "instances=" + ",".join(sorted(instances))[:160]) print() failed = [name for name, ok, _ in RESULTS if not ok] failures = len(failed) print("SUMMARY: %d passed, %d failed" % (len(RESULTS) - failures, failures)) for name in failed: print(" FAILED: " + name) return 1 if failures else 0 if __name__ == "__main__": sys.exit(main())