Files
mtusi2026lab7/student-tests/stand.py
T
alenchha 861e7722b5
Skeleton contracts / contracts (pull_request) Canceled after 0s
Application stand (lab7) / stand (pull_request) Canceled after 0s
ЛР 7 — БВТ2301 — Курлова — на 4
Перенесён минимум lab6 (API без изменений), добавлена защита на границах доверия:
- внешний HTTPS; обязательный mTLS LB -> API с allowlist identity и отзывом по serial;
- TLS на всех связях: PostgreSQL verify-full, MinIO HTTPS, RabbitMQ AMQPS mTLS (EXTERNAL),
  Valkey TLS + ACL, Collector и хранилища телеметрии через mTLS с отдельными CA;
- OpenBao в server mode: cert auth, токены 15 мин, политики только на свой путь;
- роли БД, S3-политики и права брокера по принципу минимальных прав;
- Argon2id с замером, rehash, общий лимит входа, бюджет защиты от login DoS;
- hardening всех контейнеров, scan образов с разбором, модель угроз, матрица доверия;
- отрицательные тесты: TLS-аудит (135 проверок), ACL, ротации, sealed OpenBao.
2026-11-16 10:49:13 +03:00

139 lines
5.6 KiB
Python
Executable File

"""Helpers for student resilience tests: the public HTTP client plus docker compose / psql / mc access.
Standard library only (Python 3.9+). Images that need Pillow are generated inside the API container.
Never prints tokens or secrets.
"""
import json
import os
import subprocess
import sys
import time
import uuid
from pathlib import Path
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
# lab7: every student test talks HTTPS to https://localhost:8443 and verifies it against the stand CA.
os.environ.setdefault("CA_FILE", str(ROOT / "secrets/pki/ca.crt"))
os.environ.setdefault("BASE_URL", "https://localhost:8443")
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run # noqa: E402,F401
SAMPLE = (ROOT / "tests/fixtures/sample.png").read_bytes()
def log(*parts):
print(time.strftime("%H:%M:%S"), *parts, flush=True)
def compose(*args, check_rc=True, capture=True, timeout=180):
done = subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=capture, text=True, timeout=timeout)
if check_rc and done.returncode != 0:
raise Failure("docker compose %s failed: %s" % (" ".join(args[:2]), (done.stderr or "")[-300:]))
return done.stdout if capture else ""
def started_at(*services):
"""Container name -> State.StartedAt, proof that a restart really happened."""
ids = compose("ps", "-q", *services).split()
out = subprocess.run(["docker", "inspect", "-f", "{{.Name}} {{.State.StartedAt}}", *ids],
capture_output=True, text=True).stdout
return "; ".join(line.strip("/")[:60] for line in out.splitlines())
def sql(query):
"""Run a read query in postgres; returns rows as lists of strings (tab separated)."""
out = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-F", "\t", "-c", query)
return [line.split("\t") for line in out.splitlines() if line]
def s3_keys(prefix):
"""Object keys starting with prefix, listed with the root credentials inside a throwaway minio-init container."""
wanted, prefix = prefix, prefix[:prefix.rfind("/") + 1]
script = ('mkdir -p /tmp/mc/certs/CAs && cp /run/secrets/ca.crt /tmp/mc/certs/CAs/ca.crt && '
'mc alias set l https://minio:9000 "$(cat /run/secrets/minio_root_user)" '
'"$(cat /run/secrets/minio_root_password)" >/dev/null && '
'mc ls --recursive --json l/messenger-attachments/%s || true' % prefix)
out = compose("run", "--rm", "--no-deps", "-T", "--entrypoint", "sh", "minio-init", "-c", script)
keys = []
for line in out.splitlines():
try:
item = json.loads(line)
except ValueError:
continue
if item.get("key"):
keys.append(prefix + item["key"])
return sorted(k for k in keys if k.startswith(wanted))
def queue_depth(queue="attachments.process"):
"""None while the broker node is still booting (right after a restart); callers poll (wait_queue)."""
out = compose("exec", "-T", "rabbitmq", "rabbitmqctl", "-q", "--vhost", "messenger", "list_queues",
"name", "messages", "messages_ready", "messages_unacknowledged", check_rc=False)
for line in out.splitlines():
parts = line.split()
if parts and parts[0] == queue and len(parts) == 4 and parts[1].isdigit():
return {"messages": int(parts[1]), "ready": int(parts[2]), "unacked": int(parts[3])}
return None
def wait_queue(min_ready=1, seconds=30):
"""Quorum queue counters are refreshed by the stats emitter (~5 s), so poll."""
deadline = time.monotonic() + seconds
depth = None
while time.monotonic() < deadline:
depth = queue_depth()
if depth and depth["ready"] >= min_ready:
return depth
time.sleep(1)
return depth
def jobs_cli(*args):
done = subprocess.run(["docker", "compose", "exec", "-T", "api-1", "python", "scripts/jobs.py", *args],
cwd=ROOT, capture_output=True, text=True, timeout=60)
return done.returncode, json.loads(done.stdout) if done.stdout.strip() else None
def wait_http_ready(c, seconds=120):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
try:
c.call("GET", "/health/ready", 200)
return
except Failure:
time.sleep(1)
raise Failure("API not ready after %ds" % seconds)
def upload(c, actor, chat, body=SAMPLE, filename="sample.png", ctype="image/png", expected=202):
path = "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], quote(filename, safe=""))
schema = "Attachment" if expected == 202 else None
return c.call("POST", path, expected, actor=actor, raw=body, headers={"Content-Type": ctype}, schema=schema)["json"]
def get(c, actor, att_id):
return c.call("GET", "/api/v1/attachments/" + att_id, actor=actor, schema="Attachment")["json"]
def wait_status(c, actor, att_id, statuses, seconds=120):
deadline = time.monotonic() + seconds
seen = []
while time.monotonic() < deadline:
att = get(c, actor, att_id)
if not seen or seen[-1] != att["status"]:
seen.append(att["status"])
if att["status"] in statuses:
return att, seen
time.sleep(0.5)
raise Failure("attachment %s did not reach %s in %ds (seen %s)" % (att_id, statuses, seconds, seen))
def objects_of(att_id):
return s3_keys("attachments/%s/" % att_id) + s3_keys("staging/%s" % att_id)
def unique_name(fault=None):
tag = uuid.uuid4().hex[:8]
return ("fault-%s-%s.png" % (fault, tag)) if fault else ("plain-%s.png" % tag)