лр7: Docker-прогон, evidence, исправления

This commit is contained in:
kalibr456
2026-11-07 20:17:11 +03:00
parent 20afc2c790
commit cb38fd5231
249 changed files with 114500 additions and 82 deletions
+49
View File
@@ -0,0 +1,49 @@
"""lab7: замер Argon2id внутри контейнера api (тот же CPU-лимит, что у сервиса) и обоснование параметров.
python student-tests/argon2_bench.py
Для кандидатов (m, t, p) — время hash/verify (медиана из N), пиковая память процесса; бюджет реплики при
ARGON2_MAX_CONCURRENCY. Итог — evidence/argon2-bench.json и таблица для REPORT.md.
"""
import json
from common import EVIDENCE, app_python
BENCH = r'''
import json, resource, statistics, time
from argon2 import PasswordHasher
import settings
candidates = [(19456, 2, 1), (19456, 3, 1), (32768, 2, 1), (47104, 2, 1), (65536, 2, 1), (65536, 3, 1)]
rows = []
for m, t, p in candidates:
h = PasswordHasher(memory_cost=m, time_cost=t, parallelism=p)
stored = h.hash("Bench-password-123")
hashes, verifies = [], []
for _ in range(7):
s = time.perf_counter(); h.hash("Bench-password-123"); hashes.append(time.perf_counter() - s)
s = time.perf_counter(); h.verify(stored, "Bench-password-123"); verifies.append(time.perf_counter() - s)
rows.append({"m_kib": m, "t": t, "p": p, "hash_ms": round(statistics.median(hashes) * 1000, 1),
"verify_ms": round(statistics.median(verifies) * 1000, 1)})
print(json.dumps({"rows": rows, "maxrss_mib": round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024, 1),
"current": [settings.ARGON2_MEMORY_KIB, settings.ARGON2_ITERATIONS, settings.ARGON2_PARALLELISM],
"max_concurrency": settings.ARGON2_MAX_CONCURRENCY, "queue_s": settings.ARGON2_QUEUE_SECONDS}))
'''
def main():
data = json.loads(app_python(BENCH).splitlines()[-1])
print("m (KiB) t p hash ms verify ms logins/s per replica at concurrency "
f"{data['max_concurrency']} RAM for hashing")
for row in data["rows"]:
per_second = data["max_concurrency"] * 1000 / row["verify_ms"]
mark = " <- current" if [row["m_kib"], row["t"], row["p"]] == data["current"] else ""
print(f"{row['m_kib']:>7} {row['t']:>2} {row['p']:>2} {row['hash_ms']:>9} {row['verify_ms']:>10}"
f" {per_second:>14.1f} {data['max_concurrency'] * row['m_kib'] / 1024:>18.0f} MiB{mark}")
row["max_logins_per_s_per_replica"] = round(per_second, 1)
print(f"process max RSS during the bench: {data['maxrss_mib']} MiB")
(EVIDENCE / "argon2-bench.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
print("saved evidence/argon2-bench.json")
if __name__ == "__main__":
main()
+110
View File
@@ -0,0 +1,110 @@
"""Lab6/lab7: конфигурации наблюдаемости из Git проверены «родными» инструментами тех же версий + provisioning Grafana.
python student-tests/check_configs.py
В Docker-стенде (по умолчанию) инструменты запускаются в образах из compose.yaml:
otelcol-contrib validate, promtool check config/rules, promtool test rules (unit-тесты алертов),
loki -verify-config, tempo -config.verify; затем через HTTP API Grafana: источники данных созданы
provisioning-ом и отвечают (health), dashboard импортирован, его панели ссылаются на эти источники.
OBS_BIN_DIR=<каталог с бинарниками> — проверить конфиги локальными бинарниками без Docker (Grafana пропускается,
если GRAFANA_URL недоступен).
"""
import base64
import json
import os
import subprocess
import sys
import tempfile
import urllib.error
import urllib.request
from pathlib import Path
from common import ROOT, check
BIN = os.environ.get("OBS_BIN_DIR")
GRAFANA_URL = os.environ.get("GRAFANA_URL", "https://127.0.0.1:3000").rstrip("/") # lab7: HTTPS, CA стенда
def run(title, docker_args, local_args):
if BIN:
command = [str(Path(BIN) / local_args[0]), *local_args[1:]]
else:
command = ["docker", "compose", *docker_args]
result = subprocess.run(command, cwd=ROOT, capture_output=True, text=True)
output = (result.stdout + result.stderr).strip()
tail = "\n".join(output.splitlines()[-6:])
print(f"--- {title}: exit {result.returncode}\n{tail}")
check(result.returncode == 0, f"{title} failed")
def local_copy(path, replacements):
text = (ROOT / path).read_text(encoding="utf-8")
for old, new in replacements:
text = text.replace(old, new)
handle = tempfile.NamedTemporaryFile("w", suffix=Path(path).suffix, delete=False, encoding="utf-8")
handle.write(text)
handle.close()
return handle.name
def grafana(path):
password = (ROOT / "secrets/grafana_admin_password").read_text(encoding="utf-8").strip()
request = urllib.request.Request(GRAFANA_URL + path, headers={
"Authorization": "Basic " + base64.b64encode(f"admin:{password}".encode()).decode(), "Accept": "application/json"})
with urllib.request.urlopen(request, timeout=10) as reply:
return json.loads(reply.read().decode("utf-8"))
def main():
tmp = tempfile.mkdtemp()
run("otelcol-contrib validate (infra/otel/collector.yaml)",
["run", "--rm", "--no-deps", "otel-collector", "validate", "--config=/etc/otelcol-contrib/config.yaml"],
["otelcol-contrib", "validate", f"--config={ROOT / 'infra/otel/collector.yaml'}"])
run("promtool check config (infra/prometheus/prometheus.yml)",
["exec", "-T", "prometheus", "promtool", "check", "config", "/etc/prometheus/prometheus.yml"],
["promtool", "check", "config", local_copy("infra/prometheus/prometheus.yml", [
("/etc/prometheus/rules/", str(ROOT / "infra/prometheus/rules") + "/")])])
run("promtool check rules (recording + alerts)",
["exec", "-T", "prometheus", "sh", "-c", "promtool check rules /etc/prometheus/rules/*.yml"],
["promtool", "check", "rules", *map(str, sorted((ROOT / "infra/prometheus/rules").glob("*.yml")))])
run("promtool check web-config (lab7: TLS, client certs, allowed SANs)",
["exec", "-T", "prometheus", "promtool", "check", "web-config", "/etc/prometheus/web.yml"],
["promtool", "check", "web-config", str(ROOT / "infra/prometheus/web.yml")])
run("promtool test rules (unit tests of alert thresholds/windows/for)",
["exec", "-T", "prometheus", "promtool", "test", "rules", "/etc/prometheus/tests/alerts_test.yml"],
["promtool", "test", "rules", str(ROOT / "infra/prometheus/tests/alerts_test.yml")])
run("loki -verify-config (infra/loki/loki.yaml)",
["run", "--rm", "--no-deps", "loki", "-config.file=/etc/loki/loki.yaml", "-verify-config"],
["loki", f"-config.file={local_copy('infra/loki/loki.yaml', [('/loki', tmp + '/loki')])}", "-verify-config"])
run("tempo -config.verify (infra/tempo/tempo.yaml)",
["run", "--rm", "--no-deps", "tempo", "-config.file=/etc/tempo/tempo.yaml", "-config.verify=true"],
[os.environ.get("TEMPO_BIN", "tempo"),
f"-config.file={local_copy('infra/tempo/tempo.yaml', [('/var/tempo', tmp + '/tempo')])}", "-config.verify=true"])
try:
health = grafana("/api/health")
except (OSError, urllib.error.URLError) as exc:
check(BIN, f"Grafana is not reachable at {GRAFANA_URL}: {exc}")
print(f"--- Grafana: not reachable at {GRAFANA_URL}, skipped (local binaries mode)")
print("PASS: collector, prometheus (config, rules, unit tests), loki and tempo configs are valid")
return
print(f"--- Grafana {health.get('version')}: database {health.get('database')}")
sources = {d["uid"]: d for d in grafana("/api/datasources")}
for uid, kind in (("prometheus", "prometheus"), ("loki", "loki"), ("tempo", "tempo")):
check(uid in sources and sources[uid]["type"] == kind, f"datasource {uid} is not provisioned")
state = grafana(f"/api/datasources/uid/{uid}/health")
print(f"datasource {uid} ({kind}): {state.get('status')} {state.get('message', '')[:80]}")
check(state.get("status") == "OK", f"datasource {uid} is not healthy: {state}")
dashboard = grafana("/api/dashboards/uid/messenger-lab6")
panels = [p for p in dashboard["dashboard"]["panels"] if p["type"] != "row"]
used = {t.get("datasource", {}).get("uid") for p in panels for t in p.get("targets", [])}
print(f"dashboard '{dashboard['dashboard']['title']}' in folder '{dashboard['meta'].get('folderTitle')}': "
f"{len(panels)} panels, provisioned={dashboard['meta'].get('provisioned')}, datasources {sorted(used)}")
check(dashboard["meta"].get("provisioned"), "dashboard must come from provisioning, not the UI")
check(used <= set(sources), "panels reference a datasource that is not provisioned")
print("PASS: collector, prometheus (config, rules, unit tests), loki and tempo configs are valid; Grafana "
"provisioned 3 healthy datasources and the dashboard without manual steps")
if __name__ == "__main__":
sys.exit(main())
+119
View File
@@ -0,0 +1,119 @@
"""Lab6: каждый запрос dashboard и правил выполняется против живых хранилищ.
python student-tests/check_dashboard.py
Проверяет, что dashboard ссылается на реально существующие метрики/метки (контракт наблюдаемости):
- каждое PromQL-выражение панелей и recording/alert rules выполняется без ошибки;
- для ключевых сигналов (RED API, задания, очередь, пул, worker, CPU/RAM) результат НЕ пуст;
- LogQL логов и TraceQL трасс выполняются;
- в метках метрик приложения нет запрещённых (user_id, chat_id, message_id, attachment_id, request_id,
url, filename, text) и нет значений-UUID (кроме instance).
Перед запуском нужен трафик: make test (smoke) — он создаёт запросы, задание и логи.
"""
import json
import re
import sys
from pathlib import Path
import obs
from common import check
ROOT = Path(__file__).resolve().parents[1]
DASHBOARD = ROOT / "infra/grafana/dashboards/messenger.json"
RULES = ROOT / "infra/prometheus/rules"
FORBIDDEN_LABELS = {"user_id", "chat_id", "message_id", "attachment_id", "request_id", "url", "url_full",
"filename", "text", "job_id", "trace_id", "span_id", "authorization"}
UUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
# Метрики, которые обязаны иметь данные после smoke (имя -> зачем)
MUST_HAVE_DATA = {
'http_server_request_duration_seconds_count{job="messenger-api"}': "HTTP requests/duration (3)",
"messenger_job_duration_seconds_count": "jobs processed/failed + duration (3)",
"messenger_attachment_time_to_ready_seconds_count": "end-to-end time to ready (4)",
"messenger_queue_depth": "queue depth (4)",
"messenger_queue_oldest_age_seconds": "oldest job age (4)",
"db_client_connection_count": "DB pool used/idle (4)",
"db_client_connection_pending_requests": "DB pool waiting (4)",
"messenger_worker_busy": "worker busy (4)",
"messenger_worker_capacity": "worker capacity (4)",
"process_cpu_time_seconds_total": "process CPU (4)",
"process_memory_usage_bytes": "process RAM (4)",
"otelcol_exporter_queue_size": "collector queue (4)",
}
def substitute(expr):
return expr.replace("$__rate_interval", "1m").replace("$__interval", "1m").replace("$__range", "1h")
def main():
dashboard = json.loads(DASHBOARD.read_text(encoding="utf-8"))
prom_exprs, loki_exprs, tempo_exprs = [], [], []
for panel in dashboard["panels"]:
for target in panel.get("targets", []):
uid = target.get("datasource", {}).get("uid")
if uid == "prometheus":
prom_exprs.append((panel["title"], target["expr"]))
elif uid == "loki":
loki_exprs.append((panel["title"], target["expr"]))
elif uid == "tempo":
tempo_exprs.append((panel["title"], target["query"]))
try:
import yaml # noqa: F401 — если PyYAML есть, проверим и выражения правил
rules = []
for path in sorted(RULES.glob("*.yml")):
for group in yaml.safe_load(path.read_text(encoding="utf-8"))["groups"]:
for rule in group["rules"]:
rules.append((f"{path.name}: {rule.get('record') or rule.get('alert')}", rule["expr"]))
except ImportError:
rules = []
empty, errors = [], []
for title, expr in prom_exprs + rules:
try:
rows = obs.prom_query(substitute(expr))
except Exception as exc: # noqa: BLE001
errors.append(f"{title}: {exc}")
continue
if not rows:
empty.append(title)
print(f"PromQL: {len(prom_exprs)} dashboard expressions + {len(rules)} rule expressions executed, "
f"{len(errors)} errors, {len(empty)} empty now (no traffic of that kind / Docker-only / no incident)")
for title in sorted(set(empty)):
print(f" empty now: {title}")
check(not errors, "PromQL errors:\n" + "\n".join(errors))
for title, expr in loki_exprs:
obs.loki_query(expr, minutes=60, limit=5)
print(f"LogQL ok: {title}: {expr}")
for title, query in tempo_exprs:
found = obs.tempo_search(query, minutes=60, limit=5)
print(f"TraceQL ok: {title}: {query} -> {len(found)} trace(s)")
print()
for expr, why in MUST_HAVE_DATA.items():
rows = obs.prom_query(expr)
check(rows, f"no data for {expr} ({why})")
print(f"data: {expr:<70} {len(rows):>3} series <- {why}")
print()
bad = []
for job in ("messenger-api", "messenger-worker", "messenger-dispatcher", "messenger-janitor"):
for series in obs.prom_series(f'{{job="{job}"}}'):
for name, value in series.items():
if name in FORBIDDEN_LABELS:
bad.append(f"{series['__name__']}: forbidden label {name}")
if name != "instance" and UUID.search(value):
bad.append(f"{series['__name__']}: UUID value in label {name}")
labels = sorted({name for job in ("messenger-api", "messenger-worker", "messenger-dispatcher")
for series in obs.prom_series(f'{{job="{job}"}}') for name in series})
print(f"labels used by application metrics: {', '.join(labels)}")
check(not bad, "high-cardinality labels:\n" + "\n".join(sorted(set(bad))[:20]))
route_values = sorted({row[0].get("http_route") for row in obs.prom_query(
'count by (http_route) (http_server_request_duration_seconds_count{job="messenger-api"})')})
print(f"http_route values (templates, not URLs): {route_values}")
check(all(not UUID.search(value or "") for value in route_values), "raw URL in http_route")
print("PASS: every dashboard/rule query runs, key signals have data, no forbidden labels")
if __name__ == "__main__":
sys.exit(main())
+122
View File
@@ -0,0 +1,122 @@
"""lab7: проверка hardening контейнеров.
python student-tests/check_hardening.py # по docker compose config (стенд не нужен)
python student-tests/check_hardening.py --runtime # плюс docker inspect запущенных контейнеров
Для каждого сервиса: нет privileged / host network / Docker socket; cap_drop ALL и никаких cap_add
(кроме объяснённых исключений); no-new-privileges; корневая ФС только для чтения; не root; лимиты CPU, RAM, PID;
наружу (на 127.0.0.1) опубликованы только TLS-ingress и локальные админ-интерфейсы.
Исключения перечислены в EXCEPTIONS с причиной; результат — evidence/hardening.json.
"""
import json
import subprocess
import sys
from common import EVIDENCE, ROOT
# сервис -> {проверка: причина исключения}
EXCEPTIONS = {
"rabbitmq": {"read_only": "Erlang/RabbitMQ пишет cookie, схему и plugins-expand в /var/lib/rabbitmq и "
"служебные файлы в /etc/rabbitmq при старте; данные — в volume, корень оставлен "
"записываемым, но без capabilities, не root (user rabbitmq) и с no-new-privileges"},
"telemetry-init": {"cap_add": "одноразовый chown volumes Loki/Tempo для uid 10001: только CAP_CHOWN, "
"без сети (network_mode none), сразу завершается",
"non_root": "chown требует uid 0 (+CAP_CHOWN)"},
"otel-collector": {"network": "network_mode service:otel-gate — общий namespace с mTLS-шлюзом, Collector "
"слушает только 127.0.0.1"},
}
# Образы, где не-root задан в самом образе (USER), а не в compose
IMAGE_USER = {"api": "10001 (Dockerfile)", "worker": "10001 (Dockerfile)", "dispatcher": "10001 (Dockerfile)",
"janitor": "10001 (Dockerfile)", "migrate": "10001 (Dockerfile)", "s3-init": "10001 (Dockerfile)",
"probe": "10001 (Dockerfile)", "lb": "haproxy (образ)", "otel-gate": "haproxy (образ)",
"otel-collector": "10001 (образ)", "prometheus": "nobody (образ)", "loki": "10001 (образ)",
"tempo": "10001 (образ)", "grafana": "472 (образ)"}
ALLOWED_PORTS = {8443: "HTTPS ingress (lb)", 8404: "статистика HAProxy, mTLS оператора",
8200: "OpenBao (оператор: unseal/настройка)", 9090: "Prometheus (mTLS)", 3100: "Loki (mTLS)",
3200: "Tempo (mTLS)", 3000: "Grafana (HTTPS + пароль)"}
def compose_config():
result = subprocess.run(["docker", "compose", "--profile", "tools", "config", "--format", "json"], cwd=ROOT,
capture_output=True, check=True)
return json.loads(result.stdout)["services"]
def static_checks(services):
rows = []
def add(service, check, ok, detail=""):
reason = EXCEPTIONS.get(service, {}).get(check)
status = "PASS" if ok else ("EXCEPTION" if reason else "FAIL")
rows.append({"service": service, "check": check, "status": status, "detail": reason or detail})
for name, svc in sorted(services.items()):
add(name, "not_privileged", not svc.get("privileged"))
mode = svc.get("network_mode", "")
add(name, "network", mode != "host" and not mode.startswith("service:") or mode == "none", mode)
mounts = [v.get("source", "") for v in svc.get("volumes", []) if isinstance(v, dict)]
add(name, "no_docker_socket", not any("docker.sock" in m for m in mounts))
add(name, "cap_drop_all", "ALL" in (svc.get("cap_drop") or []))
add(name, "cap_add", not svc.get("cap_add"), ",".join(svc.get("cap_add") or []))
add(name, "no_new_privileges", any("no-new-privileges" in o for o in svc.get("security_opt") or []))
add(name, "read_only", bool(svc.get("read_only")))
user = str(svc.get("user", "") or "")
add(name, "non_root", (user not in ("", "0", "root", "0:0") or name in IMAGE_USER)
and not user.startswith("root") and not user.startswith("0:"), user or IMAGE_USER.get(name, "image default"))
limits = (svc.get("deploy") or {}).get("resources", {}).get("limits", {})
add(name, "limits_cpu_mem_pids", bool(limits.get("cpus") and limits.get("memory") and limits.get("pids")),
json.dumps(limits))
for port in svc.get("ports", []):
published = int(port.get("published", 0))
ok = port.get("host_ip") == "127.0.0.1" and published in ALLOWED_PORTS
add(name, f"port_{published}", ok, f"{port.get('host_ip')}:{published} — {ALLOWED_PORTS.get(published, '?')}")
return rows
def runtime_checks():
ids = subprocess.run(["docker", "compose", "ps", "-q"], cwd=ROOT, capture_output=True, text=True,
check=True).stdout.split()
rows = []
if not ids:
return rows
data = json.loads(subprocess.run(["docker", "inspect", *ids], capture_output=True, check=True).stdout)
for c in data:
name = c["Config"]["Labels"].get("com.docker.compose.service", c["Name"])
host = c["HostConfig"]
rows.append({"service": name, "container": c["Id"][:12], "user": c["Config"].get("User") or "image default",
"privileged": host.get("Privileged"), "readonly_rootfs": host.get("ReadonlyRootfs"),
"cap_drop": host.get("CapDrop"), "cap_add": host.get("CapAdd"),
"security_opt": host.get("SecurityOpt"), "network_mode": host.get("NetworkMode"),
"memory": host.get("Memory"), "nano_cpus": host.get("NanoCpus"),
"pids_limit": host.get("PidsLimit"),
"ports": {k: v for k, v in (c["NetworkSettings"].get("Ports") or {}).items() if v}})
return rows
def main():
rows = static_checks(compose_config())
bad = [r for r in rows if r["status"] == "FAIL"]
for r in rows:
if r["status"] != "PASS":
print(f"{r['status']:<9} {r['service']:<15} {r['check']:<20} {r['detail'][:150]}")
counts = {s: sum(1 for r in rows if r["status"] == s) for s in ("PASS", "EXCEPTION", "FAIL")}
print(f"static: {counts}")
out = {"static": rows}
if "--runtime" in sys.argv:
out["runtime"] = runtime_checks()
for r in out["runtime"]:
print(f"runtime {r['service']:<15} user={r['user']:<12} ro={r['readonly_rootfs']} priv={r['privileged']} "
f"capdrop={r['cap_drop']} capadd={r['cap_add']} nnp={'no-new-privileges:true' in (r['security_opt'] or [])} "
f"mem={r['memory']} pids={r['pids_limit']} ports={list(r['ports'])}")
if r["privileged"] or r["network_mode"] == "host":
bad.append(r)
(EVIDENCE / "hardening.json").write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8")
if bad:
print(f"FAIL: {len(bad)} hardening violation(s)")
raise SystemExit(1)
print("PASS: no privileged/host network/docker.sock; caps dropped; no-new-privileges; read-only roots; "
"non-root; CPU/RAM/PID limits; only 127.0.0.1 ports — exceptions are explained")
if __name__ == "__main__":
main()
+104
View File
@@ -0,0 +1,104 @@
"""lab7: раскладка стенда — реплики, сети по границам доверия, опубликованные порты, volumes, секреты, сертификаты.
python student-tests/check_stack.py
По docker compose config и docker inspect запущенных контейнеров. Значения секретов не читаются.
"""
import json
from common import BASE_URL, call, check, compose_output, docker, new_user, seen_instances
NETWORKS = { # сервис -> сети (границы доверия, contracts/trust-matrix.md)
"lb": ["frontend", "ingress"], "api": ["data", "frontend", "secrets", "telemetry"],
"worker": ["data", "secrets", "telemetry"], "dispatcher": ["data", "secrets", "telemetry"],
"janitor": ["data", "secrets", "telemetry"], "migrate": ["data", "secrets"], "s3-init": ["data", "secrets"],
"postgres": ["data"], "redis": ["data"], "s3": ["data"], "rabbitmq": ["data"],
"openbao": ["ops", "secrets"], "otel-gate": ["telemetry"], "prometheus": ["ops", "telemetry"],
"loki": ["ops", "telemetry"], "tempo": ["ops", "telemetry"], "grafana": ["ops", "telemetry"],
}
PORTS = {"lb": {8443, 8404}, "openbao": {8200}, "prometheus": {9090}, "loki": {3100}, "tempo": {3200},
"grafana": {3000}}
FILE_SECRETS = {"postgres": ["postgres_password"], "s3": ["s3_config"], "rabbitmq": ["rabbitmq_definitions"],
"grafana": ["grafana_admin_password"]}
IDENTITY = {"api": "api", "worker": "worker", "dispatcher": "dispatcher", "janitor": "janitor", "migrate": "migrate",
"s3-init": "s3-init", "postgres": "postgres", "redis": "redis", "s3": "s3", "rabbitmq": "rabbitmq",
"openbao": "openbao", "otel-gate": "otel-collector", "otel-collector": "otel-collector",
"prometheus": "prometheus", "loki": "loki", "tempo": "tempo", "grafana": "grafana"}
STATEFUL = {"postgres": "/var/lib/postgresql/data", "redis": "/data", "s3": "/data", "rabbitmq": "/var/lib/rabbitmq",
"openbao": "/openbao/file", "prometheus": "/prometheus", "loki": "/loki", "tempo": "/var/tempo",
"grafana": "/var/lib/grafana"}
def main():
config = json.loads(compose_output("config", "--format", "json"))
services = config["services"]
for one_shot in ("migrate", "s3-init", "telemetry-init"):
status = compose_output("ps", "-a", "--format", "{{.Status}}", one_shot).strip()
print(f"{one_shot}: {status}")
check(status.startswith("Exited (0)"), f"{one_shot} must finish with exit code 0")
ids = compose_output("ps", "-q").split()
rows = [json.loads(line) for line in docker("inspect", "--format", "{{json .}}", *ids).splitlines()]
print("\ncontainer image cpus memory pids host ports networks")
api_count, running = 0, set()
for row in sorted(rows, key=lambda r: r["Name"]):
service = row["Config"]["Labels"].get("com.docker.compose.service")
running.add(service)
host = row["HostConfig"]
cpus, memory = host.get("NanoCpus", 0) / 1e9, host.get("Memory", 0) / 2 ** 20
ports = sorted({f"{b['HostIp']}:{b['HostPort']}" for bindings in (row["NetworkSettings"]["Ports"] or {}).values()
for b in (bindings or [])})
networks = sorted(row["NetworkSettings"]["Networks"])
print(f"{row['Name'][1:]:<28} {row['Config']['Image'][:38]:<38} {cpus:>4} {memory:>6.0f}M {host.get('PidsLimit')!s:>5}"
f" {','.join(ports) or '-':<19} {','.join(n.split('_', 1)[-1] for n in networks)}")
check(cpus > 0 and memory > 0 and host.get("PidsLimit"), f"{service}: CPU/RAM/PID limit missing")
published = {int(p.rsplit(":", 1)[1]) for p in ports}
check(published == PORTS.get(service, set()), f"{service}: published ports {published}")
check(all(p.startswith("127.0.0.1:") for p in ports), f"{service}: ports must bind 127.0.0.1 only")
if service == "api":
api_count += 1
check(api_count >= 2, "need at least 2 api replicas")
for name, expected in NETWORKS.items():
got = sorted(services[name].get("networks", {}))
check(got == sorted(expected), f"{name}: networks {got}, expected {sorted(expected)}")
check(services["otel-collector"].get("network_mode") == "service:otel-gate", "collector must share gate netns")
for net in ("frontend", "data", "secrets", "telemetry"):
check(config["networks"][net].get("internal") is True, f"network {net} must be internal")
print("\nnetworks: ingress (lb only, 127.0.0.1:8443/8404) | frontend lb<->api | data | secrets | telemetry — "
"all internal except ingress/ops")
for name, path in STATEFUL.items():
check(any(v.get("target") == path and v.get("type") == "volume" for v in services[name].get("volumes", [])),
f"{name}: data must be in a named volume")
for name, svc in services.items():
image = svc.get("image") or ""
check(not image.endswith(":latest"), f"{name}: image version must be pinned")
secrets = sorted(s["source"] for s in svc.get("secrets", []))
check(secrets == FILE_SECRETS.get(name, []), f"{name}: file secrets {secrets}")
tls = [v for v in svc.get("volumes", []) if v.get("target") in ("/run/tls", "/run/tls-lb", "/run/tls-ingress")]
if name in IDENTITY:
check(tls and all(v.get("read_only") for v in tls), f"{name}: certificate must be mounted read-only")
check(any(v["source"].replace("\\", "/").endswith(f"secrets/pki/{IDENTITY[name]}") for v in tls),
f"{name}: must mount only its own identity {IDENTITY[name]}")
sources = [v.get("source", "").replace("\\", "/") for v in svc.get("volumes", [])]
check(not any(s.endswith("secrets/pki/ca") or s.endswith("secrets/operator") or s.endswith("secrets/pki")
for s in sources), f"{name}: CA key / operator files must never be mounted")
print("file secrets: only postgres (initdb), s3 (key config), rabbitmq (definitions), grafana (admin) — the "
"application gets credentials from OpenBao; every service mounts only its own certificate; CA key and "
"operator files are mounted nowhere")
user = new_user("stack")
served = seen_instances(user["token"], 20)
print(f"through {BASE_URL} one session is served by {len(served)} replicas: {sorted(served)}")
check(len(served) >= 2, "requests are not balanced")
call("GET", "/health/ready", 200)
print("PASS: stand layout matches the trust boundaries")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAIL: {exc}")
raise SystemExit(1)
+527
View File
@@ -0,0 +1,527 @@
import json
import os
import platform
import re
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / os.environ.get("EVIDENCE_DIR", "evidence") # по умолчанию evidence/
BASE_URL = os.environ.get("BASE_URL", "https://127.0.0.1:8443").rstrip("/")
CA_FILE = os.environ.get("CA_FILE", str(ROOT / "secrets" / "pki" / "public" / "ca.crt"))
PY = sys.executable
TLS = ["--base-url", BASE_URL, "--ca-file", CA_FILE]
STEPS = [
("check", "offline contract check (make check)", [PY, "scripts/check_contract.py"]),
("stack", "stand layout: replicas, ports, limits, networks, secrets, S3, telemetry services", [PY, "student-tests/check_stack.py"]),
("smoke", "public smoke over HTTPS (make test CA_FILE=...) with telemetry ON, with attachment", [PY, "tests/smoke.py", *TLS]),
# ---- lab7 ----
("security", "lab7 public: trusted HTTPS works, empty trust store fails verification (make test-security)",
[PY, "tests/security.py", *TLS]),
("hardening", "lab7: no privileged/host net/docker.sock, caps dropped, no-new-privileges, read-only, non-root, limits, ports",
[PY, "student-tests/check_hardening.py", "--runtime"]),
("tls-matrix", "lab7: every trust-matrix link from inside — allowed identity passes, no cert / foreign CA / wrong identity / expired fail",
[PY, "student-tests/test_tls_matrix.py"]),
("least-privilege", "lab7: each service identity vs PostgreSQL grants, S3 prefixes, OpenBao policies, Redis ACL",
[PY, "student-tests/test_least_privilege.py"]),
("lab7-security", "lab7: HTTPS only, headers, outsider ACL, logout, shared login rate limit, size limits, Argon2id, rehash, no credential leaks",
[PY, "student-tests/test_lab7_security.py"]),
("leak-check", "lab7: password/token/Authorization absent in container logs, Loki, Tempo traces, Prometheus labels",
[PY, "student-tests/leak_check.py"]),
("argon2-bench", "lab7: Argon2id cost inside the api container for candidate parameters", [PY, "student-tests/argon2_bench.py"]),
("lifecycle-rotate-secret", "lab7: Redis password of api rotated via OpenBao under load, old one revoked",
[PY, "student-tests/lifecycle.py", "rotate-secret"]),
("lifecycle-rotate-leaf", "lab7: LB leaf rotated (HAProxy reload), old leaf revoked via CRL, rejected by API",
[PY, "student-tests/lifecycle.py", "rotate-leaf"]),
("lifecycle-token-expiry", "lab7: OpenBao token TTL 20 s / max 40 s + revoke: services re-login with their cert",
[PY, "student-tests/lifecycle.py", "token-expiry"]),
("lifecycle-sealed", "lab7: sealed OpenBao: running replicas serve, restarted replica not ready until unseal",
[PY, "student-tests/lifecycle.py", "sealed"]),
# ---- lab6 ----
("configs", "lab6: collector/prometheus/loki/tempo configs by their own tools, alert unit tests, Grafana provisioning",
[PY, "student-tests/check_configs.py"]),
("telemetry", "lab6: request<->log<->trace, upload->publish->consume->S3/DB chain, retry, replay link, no secrets",
[PY, "student-tests/test_telemetry.py", "request", "upload-chain", "retry-chain", "replay-link"]),
("dashboard", "lab6: every dashboard/rule query runs on live data, key signals present, no forbidden labels",
[PY, "student-tests/check_dashboard.py"]),
("telemetry-history", "lab6: traces/logs/metrics survive restart of prometheus/loki/tempo (volumes)",
[PY, "student-tests/test_telemetry.py", "history"]),
("incident-worker", "lab6 incident 1: worker stopped -> queue lag + no consumers firing -> resolved",
[PY, "student-tests/incidents.py", "worker-stop"]),
("incident-db", "lab6 incident 2: slow PostgreSQL (table lock) -> high error rate firing, cause from traces -> resolved",
[PY, "student-tests/incidents.py", "db-slow"]),
("incident-telemetry", "lab6: Tempo+Loki down -> API unaffected, collector memory bounded, losses counted",
[PY, "student-tests/incidents.py", "telemetry-down"]),
("incident-collector", "lab6: Collector down -> API unaffected, SDK queue bounded, drops counted",
[PY, "student-tests/incidents.py", "collector-down"]),
("jobs-variants", "lab5: thumbnail/crop/optimized, EXIF orientation, alpha, no upscale, metadata stripped",
[PY, "student-tests/test_jobs.py", "variants"]),
("jobs-limits", "lab5: worker limits - bytes, pixels, memory (RLIMIT_AS), time (JOB_TIMEOUT_SECONDS)",
[PY, "student-tests/test_jobs.py", "limits"]),
("jobs-recovery", "lab5: worker down -> 202 -> restart api+broker -> ready; broker down -> outbox waits",
[PY, "student-tests/test_jobs.py", "worker-down", "broker-down"]),
("jobs-outbox", "lab5: dispatcher crash between COMMIT and publish / after confirm",
[PY, "student-tests/test_jobs.py", "outbox-crash"]),
("jobs-crash", "lab5: worker crash after S3 PUT / after COMMIT before ack, staging cleanup, frozen worker lease",
[PY, "student-tests/test_jobs.py", "crash-after-put", "crash-after-commit", "staging", "lease"]),
("jobs-retry", "lab5: backoff+jitter, retry_exhausted, replay, permanent errors, DLQ",
[PY, "student-tests/test_jobs.py", "retry", "exhausted-replay", "permanent", "dlq"]),
("jobs-janitor-replay", "lab5: janitor does not delete objects re-written by replay (review fix)",
[PY, "student-tests/test_janitor_replay.py"]),
("jobs-concurrency", "lab5: WORKER_CONCURRENCY consumers, prefetch 1, bounded processing",
[PY, "student-tests/test_jobs.py", "concurrency"]),
("attachments", "lab4: files, limits, damaged images, MIME, filenames, access, attachment_ids",
[PY, "student-tests/test_attachments.py"]),
("s3-security", "lab4: private bucket outside API, limited API key, no console/ports, idempotent bootstrap",
[PY, "student-tests/test_s3_security.py"]),
("consistency", "lab4: aborted upload, crash between S3 and DB, janitor, orphans, S3 outage",
[PY, "student-tests/test_consistency.py"]),
("upload-memory", "lab4: >=10 concurrent uploads, peak memory of api replicas",
[PY, "student-tests/upload_memory.py", "--output", "evidence/upload-memory.json"]),
("balancing", "balancing, shared sessions/data/files, X-Instance-Id", [PY, "student-tests/test_balancing.py"]),
("idempotency", "Idempotency-Key, parallel same key via replicas", [PY, "student-tests/test_idempotency.py"]),
("student-tests", "lab1/lab2 API tests via the balancer", [PY, "student-tests/test_api.py"]),
("race", "lab2 races via the balancer", [PY, "student-tests/test_race.py"]),
("db", "PostgreSQL: rollback, FK, Argon2id, unique keys, migrations", [PY, "student-tests/test_db.py"]),
("redis", "Redis as the session store", [PY, "student-tests/redis_info.py"]),
("explain", "EXPLAIN of the history page (full plans: explain-history.txt)", [PY, "student-tests/explain.py"]),
("failover", "public failover test for every replica, file downloaded via the other one (make test-failover)",
[PY, "student-tests/run_failover.py"]),
("load", "public load generator, 30 s, concurrency 4", [PY, "tests/load.py", *TLS,
"--duration", "30", "--concurrency", "4",
"--output", str(EVIDENCE / "load.json")]),
("failures", "Redis and PostgreSQL outages via the balancer", [PY, "student-tests/test_failures.py"]),
("persistence", "public persistence test incl. S3, OpenBao (+ operator unseal) + proof of real restarts (make test-persistence)",
[PY, "student-tests/run_persistence.py"]),
# последним: атака на вход исчерпывает общий лимит попыток с адреса клиента на окно (60 с)
("login-dos", "lab7: wrong-password login flood: Argon2id budget per replica, 503/429, latency of legit requests",
[PY, "student-tests/login_dos.py"]),
]
def git(*args):
try:
return subprocess.run(["git", *args], cwd=ROOT, capture_output=True, text=True, check=True).stdout.strip()
except (OSError, subprocess.CalledProcessError):
return ""
def commit():
head = git("rev-parse", "--short", "HEAD") or "unknown"
changed = [line for line in git("status", "--porcelain").splitlines()
if not line[3:].startswith(("evidence/", "REPORT.md"))]
return head + (" + uncommitted changes" if changed else "")
def run_step(name, description, command):
env = dict(os.environ, PYTHONUTF8="1", PYTHONIOENCODING="utf-8", BASE_URL=BASE_URL)
print(f"=== {name}: {description}", flush=True)
started = time.monotonic()
result = subprocess.run(command, cwd=ROOT, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
seconds = time.monotonic() - started
output = result.stdout.decode("utf-8", "replace").replace("\r\n", "\n")
shown = " ".join(Path(part).name if part == PY else part for part in command)
header = (f"# {name}: {description}\n# date: {time.strftime('%Y-%m-%d %H:%M:%S')}, commit: {commit()}\n"
f"# command: {shown}\n# exit code: {result.returncode}, {seconds:.1f} s\n\n")
(EVIDENCE / f"{name}.txt").write_text(header + output, encoding="utf-8")
tail = [line for line in output.splitlines() if line.strip()][-3:]
for line in tail:
print(" " + line)
print(f" -> {'PASS' if result.returncode == 0 else 'FAIL'} ({seconds:.0f} s), evidence/{name}.txt", flush=True)
return result.returncode == 0, seconds
def load_json(name):
path = EVIDENCE / name
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else None
def lab7_measurements():
"""Таблицы lab7 из evidence/*.json (если шаги выполнялись)."""
lines = []
matrix = load_json("tls-matrix.json")
if matrix:
by_link = {}
for row in matrix["checks"]:
ok, total = by_link.get(row["link"], (0, 0))
by_link[row["link"]] = (ok + row["pass"], total + 1)
lines += ["TLS/mTLS-аудит trust matrix изнутри сети (`student-tests/test_tls_matrix.py`, контейнер probe):", "",
"| Связь | Проверок | Пройдено |", "| --- | --- | --- |"]
lines += [f"| {link} | {total} | {ok} |" for link, (ok, total) in by_link.items()]
lines.append("")
rows = load_json("least-privilege.json")
if rows:
lines.append(f"Минимальные права (`test_least_privilege.py`): {len(rows)} проверок, "
f"{sum(1 for r in rows if r['pass'])} пройдено (разрешённое работает, запрещённое — отказ).")
lines.append("")
bench = load_json("argon2-bench.json")
if bench:
lines += ["Argon2id внутри контейнера api (`argon2_bench.py`, медиана из 7):", "",
"| m, KiB | t | p | hash, мс | verify, мс | входов/с на реплику при "
f"{bench['max_concurrency']} параллельных | RAM на хеширование, MiB |", "| --- | --- | --- | --- | --- | --- | --- |"]
for r in bench["rows"]:
mark = " (выбрано)" if [r["m_kib"], r["t"], r["p"]] == bench["current"] else ""
lines.append(f"| {r['m_kib']}{mark} | {r['t']} | {r['p']} | {r['hash_ms']} | {r['verify_ms']} | "
f"{r.get('max_logins_per_s_per_replica', '-')} | {bench['max_concurrency'] * r['m_kib'] // 1024} |")
lines.append("")
dos = load_json("login-dos.json")
if dos:
b, a = dos["baseline"]["legit"], dos["under_attack"]
lines.append(f"Login DoS (`login_dos.py`, {dos['attackers']} потоков неверных входов, {dos['seconds']} с): "
f"атака {a['attack']['rps']} попыток/с, коды {a['attack']['codes']}; легитимный клиент p95 "
f"{b['p95_ms']} -> {a['legit']['p95_ms']} мс, p99 {b['p99_ms']} -> {a['legit']['p99_ms']} мс, "
f"коды {a['legit']['codes']}.")
lines.append("")
for name, title in (("rotate-secret", "Ротация пароля Redis (api) через OpenBao"),
("rotate-leaf", "Ротация leaf LB + отзыв старого через CRL"),
("token-expiry", "Истечение/отзыв токенов OpenBao"),
("sealed", "OpenBao sealed")):
data = load_json(f"lifecycle-{name}.json")
if data:
load = data.pop("load", {})
lines.append(f"{title}: {json.dumps(data, ensure_ascii=False)}; нагрузка {load.get('seconds')} с, "
f"ответы {load.get('codes')}, ошибок 5xx/соединения {load.get('errors_5xx_or_conn')}.")
lines.append("")
return lines
def measurements():
"""Markdown-таблицы замеров из evidence/*.json и evidence/*.txt (для REPORT.md и summary.md)."""
lines = []
try:
info = json.loads(subprocess.run(["docker", "info", "--format", "{{json .}}"], capture_output=True,
text=True, check=True).stdout)
docker_vm = f"{info.get('NCPU')} CPU, {int(info.get('MemTotal', 0)) / 2**30:.1f} GiB RAM"
except (OSError, ValueError, subprocess.CalledProcessError):
docker_vm = "unknown"
lines.append(f"Машина: {platform.system()} {platform.release()}, {platform.processor() or platform.machine()}; "
f"Docker VM: {docker_vm}; клиент Python {platform.python_version()}; дата прогона "
f"{time.strftime('%Y-%m-%d')}, commit {commit()}. Лимиты контейнеров: api 1 CPU / 512 MiB "
f"каждая, postgres, s3 (SeaweedFS) и rabbitmq по 1 CPU / 512 MiB, redis и lb по 0,5 CPU / 128 MiB, "
f"janitor 0,25 CPU / 192 MiB, dispatcher 0,25 CPU / 128 MiB, worker 2 CPU / 1536 MiB; lab6: "
f"otel-collector 0,5 CPU / 384 MiB, prometheus, loki, tempo по 1 CPU / 512 MiB, grafana 0,5 CPU / 384 MiB; "
f"lab7: openbao 0,5 CPU / 256 MiB, otel-gate 0,25 CPU / 64 MiB; у всех — лимит PID.")
lines.append("")
lines += lab7_measurements()
lines += lab6_measurements()
failover = EVIDENCE / "failover.txt"
results = []
if failover.exists():
text = failover.read_text(encoding="utf-8")
stopped = re.findall(r"the hook stopped (\w+)", text)
results = [json.loads(m) for m in re.findall(r"^(\{\"observed_instances_before\".*\})$", text, re.M)]
if results:
lines.append("Публичный тест отказа (`make test-failover`, 15 с записи во время остановки реплики):")
lines.append("")
lines.append("| Прогон | Остановлена реплика | Реплик до отказа | Успешных записей | Неудачных попыток "
"(повторены с тем же ключом) | Первая запись после hook, с |")
lines.append("| --- | --- | --- | --- | --- | --- |")
for number, (result, container) in enumerate(zip(results, stopped), start=1):
lines.append(f"| {number} | {container} | {result['observed_instances_before']} | "
f"{result['successful_writes']} | {result['failed_attempts']} | "
f"{result['first_recovery_seconds']} |")
lines.append("")
memory = load_json("upload-memory.json")
if memory:
lines.append(f"Одновременные загрузки (`student-tests/upload_memory.py`, перед каждым сценарием реплики "
f"перезапускаются, лимит api {memory['api_limit_mib']} MiB / {memory['api_limit_cpus']:g} CPU). "
f"Пик RSS — VmHWM процесса API; cgroup — память контейнера, включая page cache временных файлов:")
lines.append("")
lines.append("| Сценарий | Одновременно | Объём, MiB | Время, с (p50 / max) | Реплика: загрузок | RSS до, MiB | "
"Пик RSS, MiB | Рост, MiB | Пик cgroup, MiB |")
lines.append("| --- | --- | --- | --- | --- | --- | --- | --- | --- |")
for run in memory["runs"]:
for n, r in enumerate(run["replicas"]):
head = (f"| {run['scenario']} | {run['concurrency']} | {run['total_mib']} | "
f"{run['latency_s']['p50']} / {run['latency_s']['max']} |") if n == 0 else "| | | | |"
cgroup = r["cgroup_peak_mib"] or r["cgroup_peak_sampled_mib"] or "-"
lines.append(f"{head} {r['replica']}: {r['uploads_served']} | {r['rss_before_mib']} | "
f"{r['rss_peak_mib']} | {r['rss_growth_mib']} | {cgroup} |")
naive = memory["single_file_extra_rss_mib"]
lines.append("")
lines.append(f"Один PNG 8000x5000 RGB внутри контейнера api, дополнительный пик RSS: наивно (тело целиком в "
f"памяти + полное декодирование Pillow) {naive['naive']} MiB, потоковая проверка "
f"{naive['streaming']} MiB. 10 таких наивных загрузок одновременно не поместились бы в "
f"{memory['api_limit_mib']} MiB.")
lines.append("")
metrics = load_json("failover-metrics.json")
if metrics:
lines.append("Остановка каждой реплики под нагрузкой (`student-tests/failover_metrics.py`: 4 потока записи "
"без пауз + 1 поток чтения, timeout клиента 2 с, 3 с до и 10 с после отказа):")
lines.append("")
lines.append("| Реплика | Как остановлена | Команда, с | HAProxy вывел из балансировки через, с | Ошибок "
"(коды) | Ошибки прекратились через, с | Записей/с до | Записей/с после | p95 после, мс | "
"Вернулась в балансировку после docker start, с |")
lines.append("| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |")
for r in metrics["runs"]:
how = "docker stop (SIGTERM)" if r["mode"] == "stop" else "docker kill (SIGKILL)"
codes = ", ".join(f"{k}: {v}" for k, v in r["error_codes"].items()) or "-"
lines.append(f"| {r['replica']} | {how} | {r['command_seconds']} | {r['lb_excluded_after_seconds']} | "
f"{r['errors']} ({codes}) | {r['errors_stopped_after_seconds']} | {r['before']['write_rps']} | "
f"{r['after']['write_rps']} | {r['after']['write_p95_ms']} | {r['rejoin_seconds']} |")
lines.append("")
lines.append("Во всех прогонах: потерянных подтверждённых сообщений 0, дублей 0, остановленная реплика "
"после остановки не ответила ни разу.")
lines.append("")
rolling = load_json("rolling-update.json")
if rolling:
during = rolling["during"]
codes = ", ".join(f"{k}: {v}" for k, v in during["error_codes"].items()) or "-"
lines.append(f"Rolling update (`student-tests/rolling_update.py`): версия {rolling['from_version']} -> "
f"{rolling['to_version']}, {rolling['replicas']} реплики заменены по одной за "
f"{rolling['update_seconds']} с под той же нагрузкой. Записей/с до: {rolling['before']['write_rps']}, "
f"во время замены: {during['write_rps']}; ошибок: {during['errors']} ({codes}); "
f"p95 {during['write_p95_ms']} мс, максимум {during['write_max_ms']} мс; подтверждено "
f"{rolling['integrity']['confirmed_writes']} сообщений, потерь и дублей нет.")
lines.append("")
load = load_json("load.json")
if load:
latency = load["successful_latency_ms"]
lines.append(f"Публичный генератор нагрузки (`tests/load.py`, closed loop, concurrency {load['concurrency']}, "
f"{load['requested_duration_seconds']:.0f} с, 2 реплики): {load['successful_rps']} успешных "
f"POST/с, ошибок {load['failed_requests']} (доля {load['error_ratio']}), задержка успешных "
f"p50 {latency['p50']} мс, p95 {latency['p95']} мс, p99 {latency['p99']} мс.")
lines.append("")
persistence = EVIDENCE / "persistence.txt"
restart_seconds = None
if persistence.exists():
found = re.search(r"took ([\d.]+) s", persistence.read_text(encoding="utf-8"))
restart_seconds = found.group(1) if found else None
impacts = []
if metrics:
for mode, what, expected in (
("stop", "`docker stop` реплики (SIGTERM) под нагрузкой",
"ошибок нет: реплика сначала уходит из балансировки (readiness 503), потом закрывает приём"),
("kill", "`docker kill` реплики (SIGKILL, авария) под нагрузкой",
"единицы 502 на запросы, начатые на убитой реплике; клиент повторяет их с тем же ключом")):
runs = [r for r in metrics["runs"] if r["mode"] == mode]
if runs:
impacts.append(
f"| {what} | {expected} | ошибок: {', '.join(str(r['errors']) for r in runs)} (по репликам); "
f"HAProxy вывел реплику через {', '.join(str(r['lb_excluded_after_seconds']) for r in runs)} с | "
f"ошибки прекратились через {max(r['errors_stopped_after_seconds'] for r in runs)} с; "
f"потерь 0, дублей 0; реплика вернулась через "
f"{max(r['rejoin_seconds'] for r in runs)} с после `docker start` |")
if failover.exists() and results:
impacts.append(
f"| публичный `make test-failover` для каждой реплики | запись продолжается не позже 10 с, "
f"подтверждённые сообщения на месте, дублей нет | PASS {len(results)} раз(а), неудачных попыток: "
f"{', '.join(str(r['failed_attempts']) for r in results)} | первая запись после hook через "
f"{', '.join(str(r['first_recovery_seconds']) for r in results)} с (hook ждёт остановки ~4 с); потерь нет |")
if rolling:
impacts.append(
f"| rolling update под нагрузкой | ошибок нет, реплик всё время не меньше {rolling['replicas']} | "
f"ошибок: {rolling['during']['errors']}, замена заняла {rolling['update_seconds']} с | потерь 0, дублей 0 |")
if restart_seconds:
impacts.append(
f"| перезапуск всего стенда (`restart` hook: postgres, redis, s3, api, janitor, lb) | данные, файл и "
f"прежний токен живы | "
f"PASS, те же контейнеры с новым временем старта | {restart_seconds} с до готовности; потерь нет |")
consistency = EVIDENCE / "consistency.txt"
if consistency.exists():
text = consistency.read_text(encoding="utf-8")
timings = re.findall(r"upload -> 503 unavailable in (\d+) ms", text)
if len(timings) >= 2:
impacts.append(f"| `docker compose stop s3` (SeaweedFS остановлен) | загрузка и скачивание -> 503, метаданные, "
f"сообщения и /health/ready работают | upload 503 за {timings[0]} мс, download 503, остальное 200/201 | "
f"после start файлы на месте; uploading-строку убрал janitor; потерь нет |")
impacts.append(f"| `docker compose pause s3` (SeaweedFS завис) | то же, но через таймауты S3-клиента | upload 503 за "
f"{timings[1]} мс (2 попытки x 5 с + откат 2 с) | после unpause файлы на месте; потерь нет |")
if "PASS: S3 written but DB not committed" in text:
impacts.append("| падение между PUT в S3 и COMMIT в БД (код API в контейнере, finish_upload падает) | "
"вложение не видно, janitor не трогает его до конца grace period, потом удаляет объект и строку | "
"GET/прикрепление -> 404; janitor: свежая строка сохранена, dry-run только отчёт, затем удалено | "
"мусора не осталось; повторный проход ничего не делает |")
if "PASS: an interrupted upload leaves no row" in text:
impacts.append("| обрыв загрузки клиентом (9 МБ заявлено, отправлено 0,2 и 3 МБ) | ничего не сохраняется | "
"строк и объектов не прибавилось, временных файлов 0 | мгновенно |")
impacts += lab5_impacts()
if impacts:
lines.append("| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |")
lines.append("| --- | --- | --- | --- |")
lines.extend(impacts)
lines.append("")
return "\n".join(lines).strip()
def lab6_measurements():
"""Таблицы lab6 из evidence/incident-*.json (их пишет student-tests/incidents.py)."""
lines = []
worker, db, tel, col = (load_json(f"incident-{n}.json") for n in ("worker-stop", "db-slow", "telemetry-down",
"collector-down"))
if worker or db or tel:
lines.append("Алерты на контролируемых инцидентах (`student-tests/incidents.py`, состояние из Prometheus /api/v1/alerts):")
lines.append("")
lines.append("| Инцидент | Воздействие | Алерт | firing через, с | resolved через, с после устранения |")
lines.append("| --- | --- | --- | --- | --- |")
if worker:
for name, seconds in worker["firing_after_stop_s"].items():
lines.append(f"| 1. worker | `docker compose stop worker` + 3 загрузки | {name} | {seconds} (от stop) | "
f"{worker['resolved_after_start_s'].get(name)} (от start) |")
if db:
lines.append(f"| 2. PostgreSQL | `LOCK TABLE messages IN ACCESS EXCLUSIVE MODE` на {db['lock_seconds']} с под "
f"нагрузкой 8 потоков | MessengerHighErrorRate | {db['firing_after_lock_s']} (от LOCK) | "
f"{db['resolved_after_unlock_s']} (от COMMIT блокировки) |")
if tel:
lines.append(f"| 3. телеметрия | `docker compose stop {' '.join(tel['stopped'])}` на {tel['outage_s']} с | "
f"TelemetryExportFailing | {tel.get('TelemetryExportFailing_firing_at_s')} (от stop) | "
f"{tel['resolved_after_start_s']} (от start) |")
lines.append("")
if worker:
d = worker["diagnosis"]
lines.append(f"Инцидент 1, наблюдения в момент firing: consumers очереди = {d['queue_consumers']}, сообщений в "
f"RabbitMQ = {d['broker_queue_depth']}, queued заданий = {d['jobs_backlog_queued']}, возраст "
f"старейшего = {d['oldest_job_age_s']} с, возраст outbox = {d['outbox_oldest_age_s']} с (публикация "
f"работает), метрики worker не обновлялись {d['worker_metrics_last_seen_s']} с, последний лог worker: "
f"event=`{(d.get('last_worker_log') or {}).get('event')}`; трасса загрузки содержит `publish attachments`, "
f"но не содержит `process attachments.process.v1`. После start: вложения ready через "
f"{max(worker['ready_after_start_s'])} с, backlog {worker.get('after_recovery', {}).get('jobs_backlog_queued')}.")
lines.append("")
if db:
d, e, c = db["diagnosis"], db["diagnosis"]["error_trace"], db["diagnosis"]["handler_cpu_contrast"]
lines.append(f"Инцидент 2, наблюдения: доля 5xx (1m) = {d['http_5xx_ratio_1m']}, коды POST /messages за 1m = "
f"{d['status_codes_1m']}, p95 POST /messages = {d['http_p95_messages_s']} с, чтения других таблиц "
f"(GET /users/me, /chats) во время блокировки {d.get('reads_during_lock_ms')} мс, занято соединений "
f"пула = {d['pool_used']}, p95 ожидания пула = "
f"{d['pool_wait_p95_s']} с, логи API event=db.unavailable по error_type: "
f"{d['api_log_db_unavailable_by_error_type']}. Error-трасса {e['trace_id']}: server-спан "
f"{e['server_ms']} мс, из них `{e['slowest_db_span']}` {e['slowest_db_ms']} мс (доля "
f"{e['db_share']}, статус {e['db_span_status']}). Контраст «медленный обработчик» (трасса "
f"{c['trace_id']}, POST /users): server {c['server_ms']} мс, `argon2id hash` {c['argon2id_ms']} мс, "
f"все спаны БД {c['db_ms_total']} мс. Нагрузка: до {db['baseline']['success_rps']} успешных записей/с, "
f"во время блокировки {db['during_lock']['codes']}, после {db['after']['success_rps']}/с без ошибок.")
lines.append("")
if tel or col:
lines.append("| Отказ телеметрии | API во время отказа | Память | Потери телеметрии |")
lines.append("| --- | --- | --- | --- |")
if tel:
probes = tel["probe_traces"]
lost = [p["sent_at_s"] for p in probes if not p["trace_in_tempo"]]
lines.append(f"| `stop {' '.join(tel['stopped'])}` на {tel['outage_s']} с (окно повторов Collector 120 с) | "
f"{tel['during']['requests']} запросов, коды {tel['during']['codes']}, доля успеха "
f"{tel['during']['success_ratio']} | heap Collector {tel['collector_heap_before_mib']} -> max "
f"{tel['collector_heap_max_mib']} MiB (limit 200), контейнер max {tel['collector_container_max_mib']} MiB | "
f"send/enqueue failed в Collector: {tel['lost_in_collector']}; пробные трассы дошли "
f"{len(probes) - len(lost)}/{len(probes)}, потеряны отправленные на {lost} с |")
if col:
lines.append(f"| `stop otel-collector` на {col['outage_s']} с | {col['during']['requests']} запросов, коды "
f"{col['during']['codes']}, доля успеха {col['during']['success_ratio']} | api {col['api_mib_before']} "
f"-> max {col['api_mib_max']} MiB (2 реплики) | SDK api потерял спанов: {col['sdk_lost_spans_api']} "
f"(queue_full — очередь 2048 полна, exporter_failed — Collector не принял пакет); после start "
f"экспорт возобновился ({col['sdk_exported_ok_after_restart']} спанов за минуту) |")
lines.append("")
return lines
def lab5_line(name, pattern):
"""Строка вывода test_jobs.py из evidence/<name>.txt, содержащая pattern (или None)."""
path = EVIDENCE / f"{name}.txt"
if not path.exists():
return None
for line in path.read_text(encoding="utf-8").splitlines():
if pattern in line and not line.startswith(("#", "---")):
return line.strip()
return None
def lab5_impacts():
"""Строки таблицы отказов lab5: наблюдение — дословно строка вывода теста (числа из прогона)."""
rows = [
("jobs-recovery", "worker started", "worker остановлен, upload, рестарт rabbitmq и api с volumes, start worker",
"202 queued, сообщение с вложением 201, content 409; после рестартов job в очереди; тот же job_id -> ready",
"потерь нет; staging удалён после COMMIT"),
("jobs-recovery", "rabbitmq started", "rabbitmq остановлен во время upload",
"202 и /health/ready 200 без брокера; строка outbox ждёт; после start публикуется", "потерь нет"),
("jobs-outbox", "killed between COMMIT and publish", "crash dispatcher между COMMIT задания и publish",
"строка outbox не отмечена -> публикуется после рестарта процесса", "без ручного действия"),
("jobs-outbox", "after publisher confirm", "crash dispatcher после confirm, до отметки outbox",
"дубль сообщения, worker распознаёт по состоянию job", "один набор вариантов"),
("jobs-crash", "killed after S3 PUT", "crash worker после PUT в S3, до COMMIT и ack",
"повтор после истечения аренды перезаписывает те же ключи", "один набор, 4 объекта"),
("jobs-crash", "after COMMIT, before ack", "crash worker после COMMIT, до ack",
"redelivery ready-задачи -> no-op ack", "очередь пуста, дублей нет"),
("jobs-crash", "frozen attempt", "worker завис (не продлевает аренду)",
"dispatcher возвращает job, другой поток завершает; поздний результат отклонён fencing", "ready не откатан"),
("jobs-limits", "imaging hang", "зависание обработки изображения",
"процесс убит по JOB_TIMEOUT_SECONDS, временная ошибка, аренда продлевалась", "повтор -> ready"),
("jobs-limits", "memory bomb", "нехватка памяти в процессе обработки (RLIMIT_AS)",
"failed/resource_limit, worker жив", "постоянная ошибка, без повторов"),
("jobs-retry", "storage_unavailable ->", "2 временные ошибки S3", "backoff с jitter, затем ready", "-"),
("jobs-retry", "retry_exhausted (public", "5 временных ошибок подряд",
"failed/retry_exhausted, реестр failed, content 409", "replay оператора"),
("jobs-retry", "ops replay", "replay failed и повторный replay ready", "тот же job_id -> ready; повтор отклонён",
"дубля нет"),
("jobs-retry", "-> reject -> DLQ", "невалидное сообщение и неизвестный job_id", "reject -> DLQ, dlq-replay не исполняет",
"сообщения сохранены"),
("jobs-concurrency", "peak processing", "8 заданий в очереди, старт worker",
"WORKER_CONCURRENCY=2, prefetch 1", "-"),
]
out = []
for name, pattern, what, expected, recovery in rows:
line = lab5_line(name, pattern)
if line:
out.append(f"| {what} | {expected} | {line.replace('|', '/')} | {recovery} |")
return out
def update_report(block):
report = ROOT / "REPORT.md"
text = report.read_text(encoding="utf-8")
begin, end = "<!-- measurements:begin -->", "<!-- measurements:end -->"
if begin not in text or end not in text:
print("REPORT.md has no measurement markers, only evidence/summary.md was written")
return
head, rest = text.split(begin, 1)
_, tail = rest.split(end, 1)
report.write_text(f"{head}{begin}\n{block}\n{end}{tail}", encoding="utf-8")
print("REPORT.md: measurement tables updated")
def main():
args = sys.argv[1:]
names = [name for name, _, _ in STEPS]
if args[:1] == ["--from"]:
if len(args) < 2 or args[1] not in names:
raise SystemExit("usage: --from <step>; steps: " + ", ".join(names))
selected = names[names.index(args[1]):]
else:
unknown = [a for a in args if a not in names]
if unknown:
raise SystemExit(f"unknown steps {unknown}; steps: " + ", ".join(names))
selected = args or names
EVIDENCE.mkdir(exist_ok=True)
results = []
for name, description, command in STEPS:
if name not in selected:
continue
ok, seconds = run_step(name, description, command)
results.append((name, description, ok, seconds))
if not ok and os.environ.get("CONTINUE_ON_FAIL") != "1":
print(f"\nSTOP: step '{name}' failed, see evidence/{name}.txt.")
print(f"After fixing: python student-tests/collect_evidence.py --from {name}")
break
block = measurements()
summary = ["# Сводка проверок", "", "| Шаг | Что проверяет | Результат | Время, с | Файл |",
"| --- | --- | --- | --- | --- |"]
summary += [f"| {n} | {d} | {'PASS' if ok else 'FAIL'} | {s:.0f} | evidence/{n}.txt |" for n, d, ok, s in results]
(EVIDENCE / "summary.md").write_text("\n".join(summary) + "\n\n# Замеры\n\n" + block + "\n", encoding="utf-8")
print("evidence/summary.md written")
passed = all(ok for _, _, ok, _ in results)
if passed and os.environ.get("REPORT_UPDATE", "1") == "1":
update_report(block) # таблицы строятся из всех файлов evidence/, в том числе от прошлых запусков
raise SystemExit(0 if passed else 1)
if __name__ == "__main__":
main()
+410
View File
@@ -0,0 +1,410 @@
import base64
import csv
import hashlib
import io
import json
import os
import ssl
import subprocess
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / os.environ.get("EVIDENCE_DIR", "evidence") # куда тесты lab7 пишут JSON (как collect_evidence.py)
EVIDENCE.mkdir(parents=True, exist_ok=True)
# По умолчанию 127.0.0.1, а не localhost: на Windows localhost сначала резолвится в ::1, порты же опубликованы
# только на 127.0.0.1, и каждое новое соединение ждёт ~2 с отказа по IPv6 (замер Docker-прогона). 127.0.0.1 есть
# в SAN сертификатов ingress/Prometheus/Loki/Tempo/Grafana/OpenBao — имя сервера проверяется как и раньше.
BASE_URL =os.environ.get("BASE_URL", "https://127.0.0.1:8443").rstrip("/")
LB_STATS_URL = os.environ.get("LB_STATS_URL", "https://127.0.0.1:8404/stats;csv")
PASSWORD = "Test-password-123"
# lab7: всё по HTTPS с проверкой учебного CA и имени сервера (ни одной ветки без проверки сертификата).
# Клиентский сертификат оператора нужен только для статистики HAProxy (:8404) и хранилищ телеметрии;
# внешний API клиентский сертификат не запрашивает.
PKI_DIR = Path(os.environ.get("PKI_DIR", ROOT / "secrets" / "pki"))
CA_FILE = os.environ.get("CA_FILE", str(PKI_DIR / "public" / "ca.crt"))
OPERATOR_DIR = PKI_DIR / "operator"
def tls_context(client_cert: bool = True) -> ssl.SSLContext:
context = ssl.create_default_context(cafile=CA_FILE)
context.minimum_version = ssl.TLSVersion.TLSv1_2
if client_cert and (OPERATOR_DIR / "tls.crt").exists():
context.load_cert_chain(str(OPERATOR_DIR / "tls.crt"), str(OPERATOR_DIR / "tls.key"))
return context
def https_connection(timeout=30):
"""http.client-соединение с API (lab7: HTTPS с проверкой CA и имени)."""
import http.client
url = urllib.parse.urlsplit(BASE_URL)
return http.client.HTTPSConnection(url.hostname, url.port or 443, timeout=timeout,
context=tls_context(client_cert=False))
def tls_socket(timeout=10):
"""«Сырой» сокет к API поверх TLS (для тестов обрыва/медленной отправки тела)."""
import socket
url = urllib.parse.urlsplit(BASE_URL)
raw = socket.create_connection((url.hostname, url.port or 443), timeout=timeout)
return tls_context(client_cert=False).wrap_socket(raw, server_hostname=url.hostname)
# Все urllib.request.urlopen тестов идут через этот opener: CA стенда, без системного прокси.
urllib.request.install_opener(urllib.request.build_opener(
urllib.request.ProxyHandler({}), urllib.request.HTTPSHandler(context=tls_context())))
class Response:
def __init__(self, status, headers, data):
self.status = status
self.headers = {name.lower(): value for name, value in headers.items()}
self.data = data
try:
self.json = json.loads(data.decode("utf-8")) if data else None
except ValueError:
self.json = None
@property
def instance(self):
"""X-Instance-Id: какая реплика API ответила (ID её контейнера)."""
return self.headers.get("x-instance-id")
def check(condition, message):
if not condition:
raise AssertionError(message)
def call(method, path, expected=200, *, body=None, raw=None, token=None, headers=None, timeout=30):
"""HTTP-запрос к API. expected — код или кортеж кодов, иначе AssertionError.
Заодно проверяет то, что контракт требует от любого ответа:
X-Request-Id, X-Instance-Id (с lab3), единый формат ошибки, WWW-Authenticate у 401.
"""
all_headers = dict(headers or {})
data = raw
if body is not None:
data = json.dumps(body).encode("utf-8")
if data is not None:
all_headers.setdefault("Content-Type", "application/json")
if token is not None:
all_headers["Authorization"] = "Bearer " + token
request = urllib.request.Request(BASE_URL + path, data=data, method=method, headers=all_headers)
try:
with urllib.request.urlopen(request, timeout=timeout) as reply:
response = Response(reply.status, reply.headers, reply.read())
except urllib.error.HTTPError as error:
response = Response(error.code, error.headers, error.read())
expected = expected if isinstance(expected, tuple) else (expected,)
check(response.status in expected,
f"{method} {path}: expected {expected}, got {response.status} {response.data[:200]!r}")
request_id = response.headers.get("x-request-id")
check(request_id, f"{method} {path}: no X-Request-Id header")
check(response.instance, f"{method} {path}: no X-Instance-Id header")
if response.status >= 400:
error = (response.json or {}).get("error") or {}
check(error.get("code") and error.get("message"), f"{method} {path}: wrong error format")
check(error.get("request_id") == request_id, f"{method} {path}: request_id differs from header")
if response.status == 401:
check(response.headers.get("www-authenticate"), f"{method} {path}: 401 without WWW-Authenticate")
return response
def try_call(method, path, *, body=None, token=None, headers=None, timeout=2):
"""Запрос без проверок и без исключений — для нагрузки во время отказа.
Возвращает Response или None, если соединение оборвалось / вышел timeout.
"""
all_headers = dict(headers or {})
data = None
if body is not None:
data = json.dumps(body).encode("utf-8")
all_headers["Content-Type"] = "application/json"
if token is not None:
all_headers["Authorization"] = "Bearer " + token
request = urllib.request.Request(BASE_URL + path, data=data, method=method, headers=all_headers)
try:
with urllib.request.urlopen(request, timeout=timeout) as reply:
return Response(reply.status, reply.headers, reply.read())
except urllib.error.HTTPError as error:
try:
return Response(error.code, error.headers, error.read())
except OSError:
return None
except (urllib.error.URLError, OSError):
return None
def basic(username, password):
"""Значение заголовка Authorization: Basic base64(username:password), пароль в UTF-8."""
return "Basic " + base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
def login(username, password, expected=201):
return call("POST", "/api/v1/auth/sessions", expected, headers={"Authorization": basic(username, password)})
def new_user(prefix="user", password=PASSWORD):
"""Регистрирует пользователя и входит. Возвращает dict: id, username, password, token."""
username = f"{prefix}_{uuid.uuid4().hex[:10]}"
user = call("POST", "/api/v1/users", 201,
body={"username": username, "display_name": prefix.title(), "password": password}).json
session = login(username, password).json
return {**user, "password": password, "token": session["token"]}
def new_chat(owner, *others, title="Test chat"):
member_ids = [owner["id"]] + [user["id"] for user in others]
return call("POST", "/api/v1/chats", 201, token=owner["token"],
body={"title": title, "member_ids": member_ids}).json
def new_key():
return uuid.uuid4().hex
def send(user, chat_id, text, expected=201, key=None):
"""POST сообщения. С lab3 Idempotency-Key обязателен: если не задан, берём новый случайный."""
return call("POST", f"/api/v1/chats/{chat_id}/messages", expected, token=user["token"],
body={"text": text}, headers={"Idempotency-Key": key or new_key()})
def post_message(user, chat_id, text="", attachment_ids=None, expected=201, key=None):
"""POST сообщения с вложениями (lab4). attachment_ids=None — поле не передаётся."""
body = {"text": text}
if attachment_ids is not None:
body["attachment_ids"] = attachment_ids
return call("POST", f"/api/v1/chats/{chat_id}/messages", expected, token=user["token"],
body=body, headers={"Idempotency-Key": key or new_key()})
def upload(user, chat_id, data, content_type="image/png", filename="photo.png", expected=202, timeout=60,
wait=True):
"""POST /chats/{id}/attachments сырыми байтами. filename=None — без параметра.
Lab5: успешный приём — 202 со снимком queued (переход 201 -> 202 из COURSE.md). При wait=True
ответ дополняется ожиданием готовности: .json — метаданные после GET в состоянии ready/failed,
.accepted — исходный снимок 202. Так проверки lab4 («файл скачивается побайтно») сохраняются.
"""
query = "" if filename is None else "?filename=" + urllib.parse.quote(filename, safe="")
headers = {"Content-Type": content_type} if content_type is not None else {}
reply = call("POST", f"/api/v1/chats/{chat_id}/attachments{query}", expected, raw=data,
token=user["token"] if user else None, headers=headers, timeout=timeout)
if reply.status == 202:
check(reply.json["status"] == "queued" and reply.json["variants"] == [], "202 must be a queued snapshot")
reply.accepted = reply.json
if wait:
reply.json = wait_attachment(user, reply.json["id"])
return reply
def wait_attachment(user, attachment_id, statuses=("ready", "failed"), seconds=60):
"""GET метаданных, пока вложение не перейдёт в одно из statuses (smoke ждёт ready до 60 с)."""
deadline = time.monotonic() + seconds
while True:
att = call("GET", f"/api/v1/attachments/{attachment_id}", 200, token=user["token"]).json
if att["status"] in statuses:
return att
check(time.monotonic() < deadline, f"attachment {attachment_id} is {att['status']} after {seconds} s")
time.sleep(0.2)
def read_history(user, chat_id, limit=100):
"""Вся история чата по страницам. Возвращает (сообщения, число_страниц)."""
items, pages, cursor = [], 0, None
while True:
query = f"?limit={limit}" + (f"&cursor={urllib.parse.quote(cursor, safe='')}" if cursor else "")
page = call("GET", f"/api/v1/chats/{chat_id}/messages{query}", 200, token=user["token"]).json
items += page["items"]
pages += 1
cursor = page["next_cursor"]
if cursor is None:
return items, pages
def wait_ready(seconds=90):
deadline = time.monotonic() + seconds
while True:
try:
with urllib.request.urlopen(BASE_URL + "/health/ready", timeout=3) as reply:
if reply.status == 200:
return
except (urllib.error.URLError, OSError):
pass
check(time.monotonic() < deadline, f"API is not ready after {seconds} s")
time.sleep(0.5)
def compose(*args, env=None):
"""docker compose <args> в корне репозитория. Вывод скрыт: в нём могут быть пути к секретам."""
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True, env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def compose_output(*args, env=None):
"""docker compose <args> и его вывод (для logs, ps)."""
result = subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, check=True, env=env)
return result.stdout.decode("utf-8", "replace") + result.stderr.decode("utf-8", "replace")
def docker(*args, check_exit=True):
"""docker <args>, возвращает stdout."""
result = subprocess.run(["docker", *args], cwd=ROOT, capture_output=True, check=check_exit)
return result.stdout.decode("utf-8", "replace").strip()
def api_containers(include_stopped=False):
"""Полные ID контейнеров сервиса api (по умолчанию только запущенные)."""
args = ["ps", "-q", "-a", "api"] if include_stopped else ["ps", "-q", "api"]
return sorted(compose_output(*args).split())
def instance_aliases(containers=None):
"""lab7: {контейнер api: его X-Instance-Id}. Alias случайный (не ID контейнера/hostname), реплика пишет его
в /tmp/instance-id (settings.INSTANCE_ID_FILE) — читаем изнутри каждого контейнера."""
aliases = {}
for container in containers if containers is not None else api_containers():
aliases[container] = docker("exec", container, "python", "-c",
"import settings; print(open(settings.INSTANCE_ID_FILE).read().strip())",
check_exit=False)
return aliases
def health(container):
"""Статус Docker healthcheck контейнера: starting / healthy / unhealthy / ''."""
return docker("inspect", "-f", "{{if .State.Health}}{{.State.Health.Status}}{{end}}", container,
check_exit=False)
def lb_servers():
"""Состояние слотов backend api в HAProxy (страница статистики, CSV): {имя: статус}."""
with urllib.request.urlopen(LB_STATS_URL, timeout=2) as reply:
rows = list(csv.reader(io.StringIO(reply.read().decode("utf-8", "replace"))))
header = [name.lstrip("# ") for name in rows[0]]
servers = {}
for row in rows[1:]:
item = dict(zip(header, row))
if item.get("pxname") == "api" and item.get("svname") not in ("FRONTEND", "BACKEND"):
servers[item["svname"]] = item.get("status", "")
return servers
def lb_up_count():
"""Сколько основных слотов (api1..api6, не аварийных) HAProxy считает готовыми (UP)."""
return sum(1 for name, status in lb_servers().items() if name.startswith("api") and status.startswith("UP"))
def seen_instances(token, requests=20):
"""Какие реплики отвечают через балансировщик: X-Instance-Id у серии GET /users/me."""
return {call("GET", "/api/v1/users/me", 200, token=token).instance for _ in range(requests)}
def wait_balanced(replicas, seconds=60):
"""Ждёт, пока все replicas контейнеров api healthy и HAProxy держит их в балансировке."""
deadline = time.monotonic() + seconds
while True:
running = api_containers()
healthy = [container for container in running if health(container) == "healthy"]
try:
up = lb_up_count()
except OSError:
up = 0
if len(healthy) >= replicas and up >= replicas:
return running
check(time.monotonic() < deadline,
f"after {seconds} s: {len(healthy)} healthy api containers, {up} UP in HAProxy, need {replicas}")
time.sleep(0.5)
def redis_cli(*args):
"""redis-cli внутри контейнера redis (lab7: TLS + ACL-пользователь admin оператора).
Пароль admin берётся из secrets/operator/redis_admin_password и передаётся через stdin
(не в аргументах команды и не в выводе).
"""
password = (ROOT / "secrets" / "operator" / "redis_admin_password").read_text(encoding="utf-8").strip()
command = ("read -r REDISCLI_AUTH; export REDISCLI_AUTH; exec redis-cli --tls --cacert /run/tls-ca/ca.crt "
"--cert /run/tls/tls.crt --key /run/tls/tls.key -h 127.0.0.1 --sni redis --user admin --no-auth-warning "
+ " ".join(args))
result = subprocess.run(["docker", "compose", "exec", "-T", "redis", "sh", "-c", command],
cwd=ROOT, input=(password + "\n").encode(), capture_output=True, check=True)
return result.stdout.decode("utf-8", "replace").strip()
def session_key(token):
"""Ключ сессии в Redis, как его считает auth.py: session:<SHA-256 токена>."""
return "session:" + hashlib.sha256(token.encode("utf-8")).hexdigest()
def psql(sql):
"""Выполняет SQL в контейнере postgres. Возвращает (код выхода, вывод, текст ошибки).
Значения в SQL тестов — только сгенерированные самим тестом (uuid), не ввод пользователя.
"""
result = subprocess.run(
["docker", "compose", "exec", "-T", "postgres",
"psql", "-U", "messenger", "-d", "messenger", "-X", "-A", "-t", "-v", "ON_ERROR_STOP=1", "-c", sql],
cwd=ROOT, capture_output=True, check=False,
)
output = result.stdout.decode("utf-8", "replace").strip()
error = result.stderr.decode("utf-8", "replace").strip()
return result.returncode, output, error
def app_python(code, *args, service="api", env=None):
"""Выполнить Python-скрипт внутри контейнера приложения (там есть модули API и S3-ключи API).
Скрипт передаётся через stdin, секреты остаются в контейнере. Возвращает stdout (последняя строка — JSON).
"""
command = ["docker", "compose", "exec", "-T"]
for name, value in (env or {}).items():
command += ["-e", f"{name}={value}"]
command += [service, "python", "-", *map(str, args)]
# lab7: учётные данные процесса — из OpenBao по сертификату этого сервиса (как у самого сервиса).
prelude = "import secretstore as _secrets\n_secrets.store.start()\n"
result = subprocess.run(command, cwd=ROOT, input=(prelude + code).encode("utf-8"), capture_output=True,
check=False)
output = result.stdout.decode("utf-8", "replace").strip()
check(result.returncode == 0, f"script in {service} failed: {result.stderr.decode('utf-8', 'replace')[-600:]}")
return output
def janitor(*args, env=None):
"""Один проход janitor.py в контейнере janitor. Возвращает его JSON-отчёт."""
command = ["docker", "compose", "exec", "-T"]
for name, value in (env or {}).items():
command += ["-e", f"{name}={value}"]
command += ["janitor", "python", "janitor.py", "--once", *map(str, args)]
result = subprocess.run(command, cwd=ROOT, capture_output=True, check=False)
output = result.stdout.decode("utf-8", "replace").strip()
check(result.returncode == 0, f"janitor failed: {result.stderr.decode('utf-8', 'replace')[-600:]}")
return json.loads(output.splitlines()[-1])
def sql_value(query):
"""Одно значение из PostgreSQL (psql -A -t)."""
code, output, error = psql(query)
check(code == 0, f"psql failed: {error[-300:]}")
return output
def run_tests(tests):
"""Запускает функции-тесты по очереди. Код выхода 1, если хоть один упал."""
failed = 0
for test in tests:
try:
test()
except Exception as exc: # noqa: BLE001 — нужно напечатать любую ошибку теста
failed += 1
print(f"FAIL: {test.__name__}: {exc}")
print(f"{len(tests) - failed} passed, {failed} failed")
raise SystemExit(1 if failed else 0)
+16
View File
@@ -0,0 +1,16 @@
from common import call, compose_output, new_user
def main():
user = new_user("demo")
print(f"logged in once as {user['username']}; 8 requests with the same Bearer token:")
for number in range(1, 9):
reply = call("GET", "/api/v1/users/me", 200, token=user["token"])
print(f" {number}. GET /api/v1/users/me -> {reply.status}, X-Instance-Id: {reply.instance}")
print()
print(compose_output("ps", "--format", "table {{.Service}}\t{{.ID}}\t{{.Status}}", "api").strip())
if __name__ == "__main__":
main()
+28
View File
@@ -0,0 +1,28 @@
import subprocess
from common import EVIDENCE, ROOT
OUTPUT = EVIDENCE / "explain-history.txt"
def main():
sql = (ROOT / "student-tests" / "explain.sql").read_bytes()
result = subprocess.run(
["docker", "compose", "exec", "-T", "postgres",
"psql", "-U", "messenger", "-d", "messenger", "-X", "-q", "-v", "ON_ERROR_STOP=1"],
cwd=ROOT, input=sql, capture_output=True, check=False,
)
OUTPUT.parent.mkdir(exist_ok=True)
OUTPUT.write_bytes(result.stdout + result.stderr)
if result.returncode != 0:
print(result.stderr.decode("utf-8", "replace"))
raise SystemExit("FAIL: psql returned an error, see output above")
for line in result.stdout.decode("utf-8", "replace").splitlines():
if line.startswith("===") or "Buffers" in line or "Execution Time" in line or " Scan " in line:
print(line)
print(f"PASS: full plans saved to {OUTPUT.relative_to(ROOT)}")
if __name__ == "__main__":
main()
+76
View File
@@ -0,0 +1,76 @@
\pset footer off
BEGIN;
CREATE TEMP TABLE seed_chats AS
SELECT gen_random_uuid() AS id, n, CASE WHEN n = 0 THEN 15000 ELSE 100 END AS size
FROM generate_series(0, 50) AS n;
CREATE TEMP TABLE seed_user AS SELECT gen_random_uuid() AS id;
INSERT INTO users (id, username, display_name, password_hash)
SELECT id, 'explain_' || substr(md5(random()::text), 1, 10), convert_to('Explain', 'UTF8'), 'not-a-real-hash'
FROM seed_user;
INSERT INTO chats (id, title) SELECT id, convert_to('explain ' || n, 'UTF8') FROM seed_chats;
INSERT INTO chat_members (chat_id, user_id) SELECT c.id, u.id FROM seed_chats c, seed_user u;
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), c.id, u.id, convert_to('message ' || g, 'UTF8'),
timestamptz '2026-09-01 00:00:00+00' + g * interval '1 second'
FROM seed_chats c, seed_user u, generate_series(1, c.size) AS g;
ANALYZE messages;
SELECT id AS big_chat FROM seed_chats WHERE n = 0 \gset
SELECT created_at AS cursor_time, id AS cursor_id FROM messages
WHERE chat_id = :'big_chat' ORDER BY created_at, id OFFSET 9999 LIMIT 1 \gset
\echo '=== Data volume'
SELECT count(*) AS messages_total,
count(*) FILTER (WHERE chat_id = :'big_chat') AS messages_in_big_chat
FROM messages;
\echo ''
\echo '=== History index'
SELECT indexdef FROM pg_indexes WHERE indexname = 'messages_history';
\echo ''
\echo '=== 1. First page: limit=50, the app asks for 51 rows to know if there is a next page'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat'
ORDER BY created_at, id LIMIT 51;
\echo ''
\echo '=== 2. Page after the 10000th message by keyset cursor (this is what the app does)'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat' AND (created_at, id) > (:'cursor_time'::timestamptz, :'cursor_id'::uuid)
ORDER BY created_at, id LIMIT 51;
\echo ''
\echo '=== 2b. The same page exactly as the app sends it since lab4: with attachment_ids of every message'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
ARRAY(SELECT a.attachment_id FROM message_attachments a
WHERE a.message_id = m.id ORDER BY a.position) AS attachment_ids
FROM messages m
WHERE m.chat_id = :'big_chat' AND (m.created_at, m.id) > (:'cursor_time'::timestamptz, :'cursor_id'::uuid)
ORDER BY m.created_at, m.id LIMIT 51;
\echo ''
\echo '=== 3. The same page with OFFSET 10000 (the app does NOT do this)'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat'
ORDER BY created_at, id OFFSET 10000 LIMIT 51;
\echo ''
\echo '=== 4. Query 2 without the index (index is dropped only inside this transaction)'
DROP INDEX messages_history;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat' AND (created_at, id) > (:'cursor_time'::timestamptz, :'cursor_id'::uuid)
ORDER BY created_at, id LIMIT 51;
ROLLBACK;
\echo ''
\echo '=== ROLLBACK: test data removed, index is back'
SELECT count(*) AS explain_users_left FROM users WHERE username LIKE 'explain\_%';
+133
View File
@@ -0,0 +1,133 @@
import json
import platform
import sys
import threading
import time
from common import ROOT, api_containers, check, docker, instance_aliases, lb_up_count, wait_balanced
ALIASES = {} # lab7: контейнер -> X-Instance-Id (случайный alias реплики)
from loadgen import Load, summary
WARMUP_SECONDS = 3
AFTER_SECONDS = 10
OUTPUT = ROOT / "evidence" / "failover-metrics.json"
class LbWatch:
"""Раз в 0,1 с спрашивает у HAProxy, сколько реплик в балансировке (UP)."""
def __init__(self):
self.points, self.stopping = [], threading.Event()
self.thread = threading.Thread(target=self._run, daemon=True)
def _run(self):
while not self.stopping.is_set():
try:
self.points.append((time.monotonic(), lb_up_count()))
except OSError:
pass
time.sleep(0.1)
def start(self):
self.thread.start()
def stop(self):
self.stopping.set()
self.thread.join(timeout=3)
def first_drop(self, after, replicas):
return next((t for t, up in self.points if t >= after and up < replicas), None)
def measure(container, mode, replicas):
wait_balanced(replicas)
load, watch = Load(), LbWatch()
watch.start()
load.start()
time.sleep(WARMUP_SECONDS)
t0 = time.monotonic()
if mode == "stop":
docker("stop", "--time", "8", container)
else:
docker("kill", container)
command_seconds = time.monotonic() - t0
time.sleep(max(0.0, AFTER_SECONDS - command_seconds))
end = t0 + AFTER_SECONDS
load.stop()
watch.stop()
errors = [e for e in load.window(t0 - WARMUP_SECONDS, end) if not e[2]]
errors_end = max((e[0] + e[5] for e in errors), default=None)
drop = watch.first_drop(t0, replicas)
served_after = [e[4] for e in load.window(t0 + command_seconds, end) if e[2]]
alias = ALIASES.get(container)
target_hits = sum(1 for instance in served_after if instance and instance == alias)
integrity = load.verify()
started = time.monotonic()
docker("start", container)
wait_balanced(replicas)
rejoin_seconds = time.monotonic() - started
return {
"replica": container[:12],
"mode": mode,
"command_seconds": round(command_seconds, 2),
"lb_excluded_after_seconds": round(drop - t0, 2) if drop else None,
"errors": len(errors),
"error_codes": summary(load, t0 - WARMUP_SECONDS, end)["error_codes"],
"errors_stopped_after_seconds": round(errors_end - t0, 2) if errors_end else 0.0,
"before": summary(load, t0 - WARMUP_SECONDS, t0),
"after": summary(load, t0, end),
"stopped_replica_answers_after_stop": target_hits,
"integrity": integrity,
"rejoin_seconds": round(rejoin_seconds, 2),
}
def main():
modes = sys.argv[1:] or ["stop", "kill"]
check(set(modes) <= {"stop", "kill"}, "usage: python student-tests/failover_metrics.py [stop] [kill]")
containers = api_containers()
ALIASES.update(instance_aliases(containers))
replicas = len(containers)
check(replicas >= 2, "need at least 2 running api replicas")
print(f"api replicas: {[c[:12] for c in containers]}; load: 4 writers without pauses + 1 reader, "
f"client timeout 2 s, retry with the same Idempotency-Key; {WARMUP_SECONDS} s before and "
f"{AFTER_SECONDS} s after the failure")
runs = []
for container in containers:
for mode in modes:
print(f"--- {mode} {container[:12]} ...")
run = measure(container, mode, replicas)
runs.append(run)
print(f" docker {mode}: {run['command_seconds']} s; HAProxy excluded it after "
f"{run['lb_excluded_after_seconds']} s; errors: {run['errors']} {run['error_codes']}, "
f"stopped after {run['errors_stopped_after_seconds']} s")
print(f" write RPS before {run['before']['write_rps']} -> after {run['after']['write_rps']}; "
f"p95 after {run['after']['write_p95_ms']} ms, max {run['after']['write_max_ms']} ms; "
f"answers from the stopped replica after stop: {run['stopped_replica_answers_after_stop']}")
print(f" confirmed {run['integrity']['confirmed_writes']}, in history "
f"{run['integrity']['messages_in_history']}, lost 0, duplicates 0; "
f"back in the balancer {run['rejoin_seconds']} s after docker start")
check(run["stopped_replica_answers_after_stop"] == 0, "the stopped replica still answered")
check(run["after"]["write_rps"] > 0, "no successful writes after the failure")
print()
print("replica mode cmd,s lb_out,s errors errors_end,s rps_before rps_after p95_after,ms rejoin,s")
for r in runs:
print(f"{r['replica']} {r['mode']:<4} {r['command_seconds']:>5} {str(r['lb_excluded_after_seconds']):>8} "
f"{r['errors']:>6} {r['errors_stopped_after_seconds']:>12} {r['before']['write_rps']:>10} "
f"{r['after']['write_rps']:>9} {str(r['after']['write_p95_ms']):>12} {r['rejoin_seconds']:>8}")
OUTPUT.parent.mkdir(exist_ok=True)
OUTPUT.write_text(json.dumps({
"profile": {"writers": 4, "readers": 1, "client_timeout_seconds": 2, "warmup_seconds": WARMUP_SECONDS,
"after_seconds": AFTER_SECONDS, "replicas": replicas, "client_python": platform.python_version()},
"runs": runs,
}, indent=2) + "\n", encoding="utf-8")
print(f"PASS: every replica was stopped ({', '.join(modes)}) and restored; no lost or duplicated messages; "
f"saved {OUTPUT.relative_to(ROOT)}")
if __name__ == "__main__":
main()
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

+93
View File
@@ -0,0 +1,93 @@
"""Синтетические изображения для тестов вложений: только стандартная библиотека.
PNG собирается вручную (сигнатура, IHDR, IDAT, IEND), поэтому можно получить любой размер
в пикселях и байтах, а также испортить конкретный байт. JPEG берётся из fixtures/.
"""
import os
import struct
import zlib
from pathlib import Path
FIXTURES = Path(__file__).resolve().parent / "fixtures"
ROOT = Path(__file__).resolve().parents[1]
MAX_UPLOAD_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
ADAM7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2))
def chunk(kind: bytes, data: bytes) -> bytes:
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
def png(width, height, *, gray=False, noise=False, interlace=0, pad_to=None, idat=None) -> bytes:
"""PNG width x height. noise=True — случайные пиксели (почти не сжимаются, файл большой).
pad_to — дополнить файл текстовым чанком tEXt после IDAT до точного размера в байтах.
idat — готовые сжатые данные (для «бомбы»: заголовок обещает одно, данных другое).
"""
channels = 1 if gray else 3
header = struct.pack(">IIBBBBB", width, height, 8, 0 if gray else 2, 0, 0, interlace)
if idat is None:
compressor = zlib.compressobj(6)
parts = []
# Adam7: 7 проходов, у каждого свои ширина и высота; без interlace — один проход.
passes = [(width, height)] if not interlace else [
((width - x + dx - 1) // dx, (height - y + dy - 1) // dy) for x, y, dx, dy in ADAM7]
for pass_width, pass_height in passes:
if pass_width <= 0 or pass_height <= 0:
continue
row = b"\x00" + bytes(pass_width * channels)
for _ in range(pass_height):
parts.append(compressor.compress(b"\x00" + os.urandom(pass_width * channels) if noise else row))
parts.append(compressor.flush())
idat = b"".join(parts)
body = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", idat)
if pad_to is not None:
need = pad_to - len(body) - 12 - 12 - 8 # заголовок чанка-заполнителя, IEND, ключ "Comment\0"
assert need >= 0, "image is already larger than pad_to"
body += chunk(b"tEXt", b"Comment\x00" + b"a" * need)
return body + chunk(b"IEND", b"")
def noise_png(target_bytes: int) -> bytes:
"""Почти несжимаемый PNG размером чуть меньше target_bytes (квадрат RGB со случайными пикселями)."""
side = int(((target_bytes - 4096) / 3) ** 0.5)
return png(side, side, noise=True)
def sample_png() -> bytes:
return (ROOT / "tests/fixtures/sample.png").read_bytes()
def sample_jpeg() -> bytes:
return (FIXTURES / "sample.jpg").read_bytes()
def progressive_jpeg() -> bytes:
return (FIXTURES / "progressive.jpg").read_bytes()
def flip_byte(data: bytes, position: int) -> bytes:
return data[:position] + bytes([data[position] ^ 0xFF]) + data[position + 1:]
GIF = b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;"
# --- сборка PNG из произвольных чанков (для проверок смысла чанков при верных CRC) ---
def ihdr(width, height, depth=8, color=2, interlace=0):
return b"IHDR", struct.pack(">IIBBBBB", width, height, depth, color, 0, 0, interlace)
def zero_idat(width, height, depth=8, channels=3):
"""Сжатые пиксели: каждая строка = байт фильтра 0 + нули (индекс палитры 0 / чёрный)."""
row_bytes = (width * depth * channels + 7) // 8
return b"IDAT", zlib.compress((b"\x00" + bytes(row_bytes)) * height)
def assemble(*chunks):
"""PNG из чанков (kind, data) с ВЕРНЫМИ CRC; IEND добавляется, если не передан."""
if not chunks or chunks[-1][0] != b"IEND":
chunks = chunks + ((b"IEND", b""),)
return b"\x89PNG\r\n\x1a\n" + b"".join(chunk(kind, data) for kind, data in chunks)
+499
View File
@@ -0,0 +1,499 @@
"""Lab6, уровень 4: контролируемые инциденты, алерты firing -> resolved и разбор причины по телеметрии.
python student-tests/incidents.py worker-stop # (1) остановлен worker: растёт возраст задач
python student-tests/incidents.py db-slow # (2) PostgreSQL медленный (блокировка таблицы)
python student-tests/incidents.py telemetry-down # (3) недоступны Tempo и Loki
python student-tests/incidents.py collector-down # (3') недоступен сам Collector
python student-tests/incidents.py # все по очереди (~20 минут)
Каждый сценарий: нагрузка/загрузки -> отказ -> ожидание firing в Prometheus -> «диагностика» только по
сохранённым наблюдениям (метрики, логи, трассы) -> восстановление -> ожидание resolved. Хронология
печатается, итог пишется в evidence/incident-<имя>.json (без токенов и текстов). Тест сам возвращает
стенд в рабочее состояние (start/unlock), даже если упал по проверке.
"""
import json
import os
import subprocess
import sys
import threading
import time
import uuid
import obs
from common import ROOT, call, check, compose, new_chat, new_user, try_call, wait_attachment
from images import png
EVIDENCE = ROOT / os.environ.get("EVIDENCE_DIR", "evidence")
FIRE_TIMEOUT = 300
RESOLVE_TIMEOUT = 300
T0 = time.monotonic()
def say(text):
print(f"[{time.monotonic() - T0:6.1f}s] {text}", flush=True)
def save(name, data):
EVIDENCE.mkdir(exist_ok=True)
path = EVIDENCE / f"incident-{name}.json"
path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
say(f"saved {path}")
def q(expr, default=None):
try:
value = obs.prom_value(expr, default)
except Exception: # noqa: BLE001 — Prometheus может быть недоступен в сценарии
return default
return default if value is None or value != value else value # NaN (нет данных) -> default
def rnd(value, digits=3):
return None if value is None else round(value, digits)
class Load:
"""Closed-loop POST сообщений в N потоков. Хранит (время, код или None, задержка) — без тела ответов."""
def __init__(self, threads=4, think=0.05, timeout=12):
self.user = new_user("incident")
self.chat = new_chat(self.user, title="Incident load")
self.threads, self.think, self.timeout = threads, think, timeout
self.samples = []
self.lock = threading.Lock()
self.stop_event = threading.Event()
self.workers = []
def _run(self):
while not self.stop_event.is_set():
started = time.monotonic()
reply = try_call("POST", f"/api/v1/chats/{self.chat['id']}/messages", body={"text": "load"},
token=self.user["token"], headers={"Idempotency-Key": uuid.uuid4().hex},
timeout=self.timeout)
with self.lock:
self.samples.append((started, reply.status if reply else None, time.monotonic() - started))
self.stop_event.wait(self.think)
def start(self):
for _ in range(self.threads):
thread = threading.Thread(target=self._run, daemon=True)
thread.start()
self.workers.append(thread)
return self
def stop(self):
self.stop_event.set()
for thread in self.workers:
thread.join(timeout=self.timeout + 2)
def window(self, since, until=None):
until = until or time.monotonic()
with self.lock:
rows = [s for s in self.samples if since <= s[0] < until]
codes = {}
for _, status, _ in rows:
key = str(status) if status else "timeout/conn"
codes[key] = codes.get(key, 0) + 1
ok = [lat for _, status, lat in rows if status and status < 500]
ok.sort()
p95 = ok[int(len(ok) * 0.95) - 1] if ok else None
seconds = max(until - since, 0.001)
return {"requests": len(rows), "codes": codes, "success_ratio": rnd(len(ok) / len(rows), 4) if rows else None,
"success_rps": rnd(len(ok) / seconds, 1), "p95_ms_successful": rnd(p95 * 1000 if p95 else None, 1)}
def container_mem_mib(service):
"""Память контейнера (docker stats) — работает и когда Prometheus/Collector недоступны."""
ids = subprocess.run(["docker", "compose", "ps", "-q", service], cwd=ROOT, capture_output=True,
text=True).stdout.split()
total = 0.0
for cid in ids:
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{json .}}", cid], cwd=ROOT,
capture_output=True, text=True).stdout.strip()
if not out:
continue
data = json.loads(out.splitlines()[0])
if "MemUsageBytes" in data:
total += data["MemUsageBytes"] / 2**20
continue
used = data.get("MemUsage", "0B").split("/")[0].strip()
for unit, factor in (("GiB", 1024), ("MiB", 1), ("KiB", 1 / 1024), ("kB", 1 / 1024), ("MB", 1), ("GB", 1024),
("B", 1 / 2**20)):
if used.endswith(unit):
total += float(used[:-len(unit)]) * factor
break
return round(total, 1)
def traced_upload(user, chat_id, size=(64, 48)):
trace_id, traceparent = obs.new_traceparent()
reply = call("POST", f"/api/v1/chats/{chat_id}/attachments?filename=incident.png", 202, raw=png(*size),
token=user["token"], headers={"Content-Type": "image/png", "traceparent": traceparent})
return reply.json["id"], trace_id
def probe(user, chat_id):
"""Запрос с известным trace_id: после восстановления проверим, дошла ли его трасса до Tempo."""
trace_id, traceparent = obs.new_traceparent()
reply = try_call("POST", f"/api/v1/chats/{chat_id}/messages", body={"text": "probe"}, token=user["token"],
headers={"Idempotency-Key": uuid.uuid4().hex, "traceparent": traceparent}, timeout=10)
return trace_id, reply.status if reply else None
def counter(expr):
return q(f"sum({expr})", 0.0) or 0.0
# ---------------------------------------------------------------------------------------------------
def worker_stop():
"""(1) Остановлен worker. Ожидаем: MessengerWorkerNoConsumers и MessengerQueueLagGrowing -> firing;
причина находится по метрикам очереди, логам и обрыву трасс; после start backlog -> 0, resolved."""
result = {"scenario": "worker-stop", "date": time.strftime("%Y-%m-%d %H:%M:%S")}
user = new_user("lag")
chat = new_chat(user, title="Lag chat")
check(obs.alerts().get("MessengerQueueLagGrowing") is None, "MessengerQueueLagGrowing is already active")
say("baseline: consumers=%s, oldest job age=%s s" % (
q('max(messenger_queue_consumers{messaging_destination_name="attachments.process.v1"})'),
q('max(messenger_queue_oldest_age_seconds{messaging_destination_name="attachments.process.v1"})')))
stopped = time.monotonic()
compose("stop", "worker")
say("docker compose stop worker")
try:
uploads = [traced_upload(user, chat["id"]) for _ in range(3)]
say(f"uploaded {len(uploads)} attachments: 202 queued (API accepts without worker)")
fired = {}
deadline = time.monotonic() + FIRE_TIMEOUT
while len(fired) < 2:
states = obs.alerts()
for name in ("MessengerWorkerNoConsumers", "MessengerQueueLagGrowing"):
if states.get(name) == "firing" and name not in fired:
fired[name] = round(time.monotonic() - stopped, 1)
say(f"ALERT {name} firing ({fired[name]} s after stop)")
if len(fired) < 2:
say(" consumers=%s backlog queued=%s oldest age=%s s, alerts: %s" % (
q('max(messenger_queue_consumers{messaging_destination_name="attachments.process.v1"})'),
q('max(messenger_jobs_backlog{status="queued"})'),
rnd(q('max(messenger_queue_oldest_age_seconds{messaging_destination_name="attachments.process.v1"})'), 1),
{k: v for k, v in states.items() if k.startswith("Messenger")}))
check(time.monotonic() < deadline, f"alerts not firing after {FIRE_TIMEOUT} s: {fired}")
time.sleep(5)
result["firing_after_stop_s"] = fired
# Диагностика только по сохранённым наблюдениям:
diag = {
"queue_consumers": q('max(messenger_queue_consumers{messaging_destination_name="attachments.process.v1"})'),
"broker_queue_depth": q('max(messenger_queue_depth{messaging_destination_name="attachments.process.v1"})'),
"jobs_backlog_queued": q('max(messenger_jobs_backlog{status="queued"})'),
"oldest_job_age_s": rnd(q('max(messenger_queue_oldest_age_seconds{messaging_destination_name="attachments.process.v1"})'), 1),
"outbox_oldest_age_s": rnd(q("max(messenger_outbox_oldest_age_seconds)"), 1),
"published_ok_last_5m": q('sum(increase(messenger_messages_published_total{outcome="ok"}[5m]))'),
"worker_metrics_last_seen_s": rnd(q('time() - max(timestamp(messenger_worker_capacity))'), 0),
}
last_worker_log = obs.loki_query('{service_name="messenger-worker"}', minutes=15, limit=1)
diag["last_worker_log"] = ({"event": last_worker_log[0][0].get("event"), "message": last_worker_log[0][1]}
if last_worker_log else None)
spans = obs.tempo_trace(uploads[0][1])
names = sorted({s["name"] for s in spans})
diag["upload_trace_span_names"] = names
diag["upload_trace_has_consumer_span"] = any(s["name"].startswith("process ") for s in spans)
result["diagnosis"] = diag
say("diagnosis: " + json.dumps(diag, ensure_ascii=False))
check(diag["queue_consumers"] == 0, "consumers must be 0 while worker is stopped")
check("publish attachments" in names and not diag["upload_trace_has_consumer_span"],
"trace must end at publish: message is in the broker, nobody consumes it")
finally:
started = time.monotonic()
compose("start", "worker")
say("docker compose start worker")
ready_at = []
for attachment_id, _ in uploads:
att = wait_attachment(user, attachment_id, seconds=120)
check(att["status"] == "ready", f"{attachment_id} is {att['status']}")
ready_at.append(round(time.monotonic() - started, 1))
result["ready_after_start_s"] = ready_at
say(f"all attachments ready {max(ready_at)} s after worker start; backlog now %s" %
q('max(messenger_jobs_backlog{status="queued"})'))
resolved = {}
for name in ("MessengerWorkerNoConsumers", "MessengerQueueLagGrowing"):
obs.wait_alert(name, "resolved", RESOLVE_TIMEOUT, log=say)
resolved[name] = round(time.monotonic() - started, 1)
result["resolved_after_start_s"] = resolved
result["after_recovery"] = {
"jobs_backlog_queued": q('max(messenger_jobs_backlog{status="queued"})'),
"oldest_job_age_s": rnd(q('max(messenger_queue_oldest_age_seconds{messaging_destination_name="attachments.process.v1"})'), 1),
"queue_consumers": q('max(messenger_queue_consumers{messaging_destination_name="attachments.process.v1"})')}
say(f"alerts resolved: {result['resolved_after_start_s']}; now {result['after_recovery']}")
result["time_to_ready_p95_5m_s"] = rnd(q('histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[5m])))'), 1)
save("worker-stop", result)
print("PASS: worker stop -> no consumers + growing queue lag -> firing; cause from metrics/logs/trace; "
"start -> backlog drained -> resolved")
# ---------------------------------------------------------------------------------------------------
LOCK_SECONDS = 210 # > окно rate (1m) + for (1m) + задержка экспорта метрик с запасом
def db_slow():
"""(2) PostgreSQL «медленный»: таблица messages заблокирована (ACCESS EXCLUSIVE) на LOCK_SECONDS.
Ожидаем MessengerHighErrorRate firing; трассы показывают, что время уходит в INSERT (PostgreSQL),
а не в обработчик; после снятия блокировки — resolved."""
result = {"scenario": "db-slow", "date": time.strftime("%Y-%m-%d %H:%M:%S"), "lock_seconds": LOCK_SECONDS}
load = Load(threads=8, think=0.05).start()
say("load: 8 threads POST /messages")
time.sleep(25)
base_from = time.monotonic() - 20
result["baseline"] = load.window(base_from)
result["baseline"]["server_p95_s"] = rnd(q('histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="messenger-api", http_route="/api/v1/chats/{chat_id}/messages"}[1m])))'), 4)
say(f"baseline: {result['baseline']}")
check(obs.alerts().get("MessengerHighErrorRate") is None, "MessengerHighErrorRate is already active")
lock_out = {}
def hold_lock():
command = ["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-X",
"-q", "-c", f"BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep({LOCK_SECONDS}); COMMIT;"]
lock_out["code"] = subprocess.run(command, cwd=ROOT, capture_output=True).returncode
lock_out["released"] = time.monotonic() # COMMIT выполнен: блокировка снята
locker = threading.Thread(target=hold_lock, daemon=True)
locked = time.monotonic()
locker.start()
say(f"LOCK TABLE messages IN ACCESS EXCLUSIVE MODE for {LOCK_SECONDS} s (PostgreSQL alive, writes wait)")
try:
fired_at = None
while fired_at is None:
if obs.alerts().get("MessengerHighErrorRate") == "firing":
fired_at = round(time.monotonic() - locked, 1)
break
say(" 5xx ratio=%s p95=%s s pool used=%s waiting=%s" % (
rnd(q("messenger:http_error_ratio:rate1m"), 3),
rnd(q('histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="messenger-api", http_route!~"/health/.*"}[1m])))'), 3),
q('sum(db_client_connection_count{db_client_connection_state="used"})'),
q("sum(db_client_connection_pending_requests)")))
check(time.monotonic() - locked < LOCK_SECONDS + 30, "MessengerHighErrorRate did not fire")
time.sleep(5)
say(f"ALERT MessengerHighErrorRate firing ({fired_at} s after lock)")
result["firing_after_lock_s"] = fired_at
# Диагностика: метрики
diag = {
"http_5xx_ratio_1m": rnd(q("messenger:http_error_ratio:rate1m"), 3),
"http_p95_messages_s": rnd(q('histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="messenger-api", http_route="/api/v1/chats/{chat_id}/messages"}[1m])))'), 3),
"pool_used": q('sum(db_client_connection_count{db_client_connection_state="used"})'),
"pool_wait_p95_s": rnd(q("histogram_quantile(0.95, sum by (le) (rate(db_client_connection_wait_time_seconds_bucket[1m])))"), 3),
"status_codes_1m": {row[0].get("http_response_status_code"): rnd(row[1], 2) for row in obs.prom_query(
'sum by (http_response_status_code) (rate(http_server_request_duration_seconds_count{job="messenger-api", http_route="/api/v1/chats/{chat_id}/messages"}[1m]))')},
}
# Чтения других таблиц во время блокировки messages: быстрые -> «медленно» не всё, а одна операция
reads = []
for _ in range(5):
began = time.monotonic()
call("GET", "/api/v1/users/me", 200, token=load.user["token"])
call("GET", "/api/v1/chats", 200, token=load.user["token"])
reads.append((time.monotonic() - began) * 1000 / 2)
diag["reads_during_lock_ms"] = {"GET /users/me + GET /chats, avg per request": rnd(sum(reads) / len(reads), 1),
"max": rnd(max(reads), 1)}
# Логи: какие ошибки БД видит API
logs = obs.loki_query('{service_name="messenger-api"} | event="db.unavailable"', minutes=5, limit=500)
by_type = {}
for labels, _ in logs:
by_type[labels.get("error_type", "?")] = by_type.get(labels.get("error_type", "?"), 0) + 1
diag["api_log_db_unavailable_by_error_type"] = by_type
# Трассы: медленный запрос с ошибкой — где время
found = obs.tempo_search('{ resource.service.name = "messenger-api" && name = "POST /api/v1/chats/{chat_id}/messages" && status = error }',
minutes=5, limit=5)
check(found, "no error traces of POST messages in Tempo")
spans = obs.wait_trace(found[0]["traceID"].rjust(32, "0"), seconds=30)
server = next(s for s in spans if s["kind"] == "SERVER")
db_spans = [s for s in spans if s["kind"] == "CLIENT" and s["name"] in ("INSERT", "SELECT", "UPDATE")]
slowest = max(db_spans, key=lambda s: s["duration_ms"])
diag["error_trace"] = {"trace_id": found[0]["traceID"], "server_ms": rnd(server["duration_ms"], 1),
"slowest_db_span": slowest["name"], "slowest_db_ms": rnd(slowest["duration_ms"], 1),
"db_span_status": slowest["status"], "db_share": rnd(slowest["duration_ms"] / server["duration_ms"], 3),
"tree": obs.span_tree(spans).splitlines()}
# Контраст: медленный ОБРАБОТЧИК (CPU Argon2id при регистрации) — время в своём спане, БД быстрая
trace_id, traceparent = obs.new_traceparent()
call("POST", "/api/v1/users", 201, body={"username": f"cpu_{uuid.uuid4().hex[:10]}", "display_name": "Cpu",
"password": "Test-password-123"}, headers={"traceparent": traceparent})
cpu = obs.wait_trace(trace_id, lambda s: any(x["name"] == "argon2id hash" for x in s), 30)
cpu_server = next(s for s in cpu if s["kind"] == "SERVER")
argon = next(s for s in cpu if s["name"] == "argon2id hash")
cpu_db = [s for s in cpu if s["kind"] == "CLIENT"]
diag["handler_cpu_contrast"] = {"trace_id": trace_id, "server_ms": rnd(cpu_server["duration_ms"], 1),
"argon2id_ms": rnd(argon["duration_ms"], 1),
"db_ms_total": rnd(sum(s["duration_ms"] for s in cpu_db), 1),
"tree": obs.span_tree(cpu).splitlines()}
result["diagnosis"] = diag
say("diagnosis: " + json.dumps({k: v for k, v in diag.items() if k not in ("error_trace", "handler_cpu_contrast")},
ensure_ascii=False))
say("error trace (DB): " + json.dumps({k: v for k, v in diag["error_trace"].items() if k != "tree"}))
print("\n".join(" " + line for line in diag["error_trace"]["tree"]))
say("contrast, slow handler (CPU): " + json.dumps({k: v for k, v in diag["handler_cpu_contrast"].items() if k != "tree"}))
print("\n".join(" " + line for line in diag["handler_cpu_contrast"]["tree"]))
check(diag["error_trace"]["db_share"] > 0.8, "in the DB incident most of the request time must be in a DB span")
check(diag["handler_cpu_contrast"]["argon2id_ms"] > diag["handler_cpu_contrast"]["db_ms_total"],
"in the CPU contrast the handler span must dominate the DB spans")
finally:
locker.join(timeout=LOCK_SECONDS + 30)
unlocked = lock_out.get("released", time.monotonic())
say(f"lock released (psql exit {lock_out.get('code')}), {round(unlocked - locked, 1)} s after LOCK")
result["during_lock"] = load.window(locked + 5, unlocked)
obs.wait_alert("MessengerHighErrorRate", "resolved", RESOLVE_TIMEOUT, log=say)
result["resolved_after_unlock_s"] = round(time.monotonic() - unlocked, 1)
say(f"ALERT MessengerHighErrorRate resolved {result['resolved_after_unlock_s']} s after unlock")
result["after"] = load.window(unlocked + 5)
load.stop()
say(f"load: during lock {result['during_lock']}; after {result['after']}")
check((result["after"]["success_ratio"] or 0) > 0.99, "writes must recover after the lock")
save("db-slow", result)
print("PASS: slow DB -> 503 -> MessengerHighErrorRate firing; traces show the time in the INSERT span "
"(not the handler); unlock -> resolved")
# ---------------------------------------------------------------------------------------------------
def telemetry_down(stores=("tempo", "loki"), outage=150):
"""(3) Хранилища трасс и логов недоступны дольше окна повторов Collector (120 с).
Ожидаем: API работает без ошибок, RSS Collector ограничен, TelemetryExportFailing firing,
потери считаются (send_failed) и видны на пробных трассах; после start — данные снова идут."""
result = {"scenario": "telemetry-down", "date": time.strftime("%Y-%m-%d %H:%M:%S"), "stopped": list(stores),
"outage_s": outage}
load = Load(threads=4, think=0.05).start()
time.sleep(20)
result["baseline"] = load.window(time.monotonic() - 15)
failed_before = {sig: counter(f"otelcol_exporter_send_failed_{sig}") + counter(f"otelcol_exporter_enqueue_failed_{sig}")
for sig in ("spans", "log_records")}
heap_before = q("max(otelcol_process_runtime_heap_alloc_bytes)")
mem_before = container_mem_mib("otel-collector")
result["collector_heap_before_mib"] = rnd((heap_before or 0) / 2**20, 1)
result["collector_container_before_mib"] = mem_before
say(f"baseline: {result['baseline']}, collector heap {result['collector_heap_before_mib']} MiB, "
f"container {mem_before} MiB")
compose("stop", *stores)
stopped = time.monotonic() # отсчёт после остановки (Loki при stop сбрасывает данные на диск ~десятки секунд)
say(f"docker compose stop {' '.join(stores)}: stopped")
samples, probes = [], []
try:
while time.monotonic() - stopped < outage:
probes.append((round(time.monotonic() - stopped, 1), *probe(load.user, load.chat["id"])))
# memory_limiter ограничивает heap Go-процесса (RSS ещё включает отображённый в память бинарник ~150 MiB)
sample = {"t": round(time.monotonic() - stopped, 1),
"collector_heap_mib": rnd((q("max(otelcol_process_runtime_heap_alloc_bytes)") or 0) / 2**20, 1),
"collector_rss_mib": rnd((q("max(otelcol_process_memory_rss)") or 0) / 2**20, 1),
"collector_container_mib": container_mem_mib("otel-collector"),
"queue": {r[0].get("exporter"): r[1] for r in obs.prom_query("otelcol_exporter_queue_size")},
"alert": obs.alerts().get("TelemetryExportFailing", "inactive")}
samples.append(sample)
say(f" {sample}")
time.sleep(10)
finally:
compose("start", *stores)
started = time.monotonic()
say(f"docker compose start {' '.join(stores)}")
result["during"] = load.window(stopped, started)
result["samples"] = samples
result["collector_heap_max_mib"] = max(s["collector_heap_mib"] or 0 for s in samples)
result["collector_rss_max_mib"] = max(s["collector_rss_mib"] or 0 for s in samples)
result["collector_container_max_mib"] = max(s["collector_container_mib"] or 0 for s in samples)
fired = [s["t"] for s in samples if s["alert"] == "firing"]
result["TelemetryExportFailing_firing_at_s"] = fired[0] if fired else None
# после восстановления: Collector досылает очередь; затем проверяем, какие пробные трассы дошли
obs.wait_metric("sum(otelcol_exporter_queue_size)", lambda v: v == 0, 180)
result["queue_drained_after_start_s"] = round(time.monotonic() - started, 1)
say(f"exporter queues drained {result['queue_drained_after_start_s']} s after start")
time.sleep(15) # Tempo/Loki индексируют принятые пакеты
found = []
for t, trace_id, status in probes:
spans = []
for _ in range(5):
spans = obs.tempo_trace(trace_id)
if spans:
break
time.sleep(2)
found.append({"sent_at_s": t, "http": status, "trace_in_tempo": bool(spans)})
result["probe_traces"] = found
failed_after = {sig: counter(f"otelcol_exporter_send_failed_{sig}") + counter(f"otelcol_exporter_enqueue_failed_{sig}")
for sig in ("spans", "log_records")}
result["lost_in_collector"] = {sig: round(failed_after[sig] - failed_before[sig]) for sig in failed_after}
obs.wait_alert("TelemetryExportFailing", "resolved", RESOLVE_TIMEOUT, log=say)
result["resolved_after_start_s"] = round(time.monotonic() - started, 1)
result["after"] = load.window(started + 5)
load.stop()
say(f"API during outage: {result['during']}")
say(f"probe traces: {sum(p['trace_in_tempo'] for p in found)}/{len(found)} reached Tempo "
f"(lost: sent at {[p['sent_at_s'] for p in found if not p['trace_in_tempo']]} s)")
say(f"lost in Collector (send_failed+enqueue_failed): {result['lost_in_collector']}; collector heap "
f"{result['collector_heap_before_mib']} -> max {result['collector_heap_max_mib']} MiB (memory_limiter 200 MiB), "
f"container max {result['collector_container_max_mib']} MiB")
check(result["during"]["success_ratio"] == 1.0, "API must keep working while telemetry stores are down")
check(result["collector_heap_max_mib"] < 200, "collector heap must stay below memory_limiter limit_mib")
save("telemetry-down", result)
print("PASS: Tempo+Loki down -> API unaffected, collector memory bounded, losses counted; recovery -> resolved")
def collector_down(outage=90):
"""(3') Сам Collector недоступен: SDK в процессах приложения ограничивает очередь и отбрасывает лишнее."""
result = {"scenario": "collector-down", "date": time.strftime("%Y-%m-%d %H:%M:%S"), "outage_s": outage}
load = Load(threads=4, think=0.05).start()
time.sleep(20)
result["baseline"] = load.window(time.monotonic() - 15)
# Потери SDK: отброшено процессором (очередь полна) + не принято exporter-ом (ошибка соединения).
sdk_lost = ('otel_sdk_processor_span_processed_total{job="messenger-api", error_type!=""}',
'otel_sdk_exporter_span_exported_total{job="messenger-api", error_type!=""}')
lost_before = [counter(expr) for expr in sdk_lost]
api_before = container_mem_mib("api")
say(f"baseline: {result['baseline']}, api containers {api_before} MiB")
stopped = time.monotonic()
compose("stop", "otel-collector")
say("docker compose stop otel-collector")
samples = []
try:
while time.monotonic() - stopped < outage:
samples.append({"t": round(time.monotonic() - stopped, 1), "api_mib": container_mem_mib("api")})
say(f" {samples[-1]}")
time.sleep(10)
finally:
compose("start", "otel-collector")
started = time.monotonic()
say("docker compose start otel-collector")
result["during"] = load.window(stopped, started)
result["api_mib_before"] = api_before
result["api_mib_max"] = max(s["api_mib"] for s in samples)
time.sleep(30) # SDK досылает cumulative-метрики, включая счётчик отброшенных спанов
lost_after = [counter(expr) for expr in sdk_lost]
result["sdk_lost_spans_api"] = {"processor_queue_full": round(lost_after[0] - lost_before[0]),
"exporter_failed": round(lost_after[1] - lost_before[1])}
result["sdk_exported_ok_after_restart"] = round(q(
'sum(increase(otel_sdk_exporter_span_exported_total{job="messenger-api", error_type=""}[1m]))', 0) or 0)
result["after"] = load.window(started + 5)
load.stop()
say(f"API during collector outage: {result['during']}; api memory {api_before} -> max {result['api_mib_max']} MiB; "
f"SDK lost spans (api): {result['sdk_lost_spans_api']}; exported OK in the last minute after restart: "
f"{result['sdk_exported_ok_after_restart']}")
check(sum(result["sdk_lost_spans_api"].values()) > 0, "losses during the outage must be counted by the SDK")
check(result["sdk_exported_ok_after_restart"] > 0, "spans must flow again after the Collector is back")
check(result["during"]["success_ratio"] == 1.0, "API must keep working without the Collector")
check(result["api_mib_max"] - api_before < 100, "API memory must not grow without bound")
save("collector-down", result)
print("PASS: Collector down -> API unaffected, SDK memory bounded, lost spans counted, export resumes after start")
SCENARIOS = {"worker-stop": worker_stop, "db-slow": db_slow, "telemetry-down": telemetry_down,
"collector-down": collector_down}
if __name__ == "__main__":
names = sys.argv[1:] or list(SCENARIOS)
unknown = [n for n in names if n not in SCENARIOS]
if unknown:
raise SystemExit(f"unknown scenarios {unknown}; available: {', '.join(SCENARIOS)}")
failed = 0
for name in names:
print(f"=== {name}", flush=True)
try:
SCENARIOS[name]()
except Exception as exc: # noqa: BLE001
failed += 1
print(f"FAIL: {name}: {exc}", flush=True)
for service in ("worker", "otel-collector", "tempo", "loki"):
compose("start", service)
print(f"{len(names) - failed} passed, {failed} failed")
raise SystemExit(1 if failed else 0)
+120
View File
@@ -0,0 +1,120 @@
"""lab7: секреты не попадают в логи и телеметрию.
python student-tests/leak_check.py
1. Создаёт пользователя с уникальным паролем-маркером, входит (получает токен-маркер), делает запросы с
этим токеном, неверный вход, загрузку файла — с явным traceparent, чтобы найти трассы.
2. Ищет маркеры (пароль, токен, base64 Basic, «Bearer <токен>») в:
- логах контейнеров (docker compose logs всех сервисов);
- Loki (полнотекстовый поиск по логам всех messenger-*);
- трассах этих запросов в Tempo (полный JSON всех спанов и атрибутов);
- метках Prometheus (значения label не содержат токен/UUID пользователя).
Также — что в логах нет секретов из OpenBao: ищется фрагмент «password=»/«secret_access_key» со значением.
Итог — evidence/leak-check.json. Ни один маркер не печатается целиком.
"""
import base64
import json
import os
import time
import uuid
from pathlib import Path
import images
from common import EVIDENCE, basic, call, check, compose_output, new_chat, upload
try:
import obs
except Exception: # noqa: BLE001
obs = None
def main():
marker_password = "LeakMarker-" + uuid.uuid4().hex
username = "leak_" + uuid.uuid4().hex[:10]
user = call("POST", "/api/v1/users", 201, body={"username": username, "display_name": "Leak",
"password": marker_password}).json
trace_ids = []
def traced():
trace_id = uuid.uuid4().hex
trace_ids.append(trace_id)
return {"traceparent": f"00-{trace_id}-{uuid.uuid4().hex[:16]}-01"}
token = call("POST", "/api/v1/auth/sessions", 201, headers={"Authorization": basic(username, marker_password),
**traced()}).json["token"]
call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic(username, marker_password + "x"),
**traced()})
me = {"id": user["id"], "token": token}
call("GET", "/api/v1/users/me", 200, token=token, headers=traced())
chat = new_chat({**user, "token": token})
upload({**user, "token": token}, chat["id"], images.sample_png())
call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Bearer " + token + "x", **traced()})
markers = {"password": marker_password, "token": token,
"basic_b64": base64.b64encode(f"{username}:{marker_password}".encode()).decode()[:24]}
time.sleep(20) # батчи SDK (2-5 с) + Collector (2 с) + индексация
found = {}
logs = compose_output("logs", "--no-log-prefix")
found["container_logs"] = {name: logs.count(value) for name, value in markers.items()}
found["container_logs_bearer_or_basic_header"] = logs.count("Authorization: Bearer") + logs.count(
"Authorization: Basic")
sources = ["container logs"]
if obs is not None:
try:
loki_hits = {}
for name, value in markers.items():
rows = obs.loki_query('{service_name=~"messenger-.+"} |= `' + value + '`', minutes=30, limit=50)
loki_hits[name] = len(rows)
found["loki"] = loki_hits
sources.append("Loki")
except Exception as exc: # noqa: BLE001
found["loki"] = f"unavailable: {type(exc).__name__}"
try:
tempo_hits, fetched = {name: 0 for name in markers}, 0
for trace_id in trace_ids:
try:
raw = json.dumps(obs.tempo_trace(trace_id))
except Exception: # noqa: BLE001
continue
fetched += 1
for name, value in markers.items():
tempo_hits[name] += raw.count(value)
tempo_hits.setdefault("authorization_attribute", 0)
tempo_hits["authorization_attribute"] += raw.lower().count("http.request.header.authorization")
found["tempo"] = {"traces_fetched": fetched, **tempo_hits}
sources.append("Tempo")
except Exception as exc: # noqa: BLE001
found["tempo"] = f"unavailable: {type(exc).__name__}"
try:
labels = obs.get_json(f"{obs.PROMETHEUS_URL}/api/v1/series?match[]="
+ "http_server_request_duration_seconds_count")
text = json.dumps(labels)
found["prometheus_labels"] = {"token": text.count(token), "user_id": text.count(me["id"])}
sources.append("Prometheus labels")
except Exception as exc: # noqa: BLE001
found["prometheus_labels"] = f"unavailable: {type(exc).__name__}"
dump_dir = os.environ.get("OTLP_DUMP_DIR") # нативная песочница: всё, что пришло в заглушку Collector
if dump_dir:
raw = b"".join(path.read_bytes() for path in Path(dump_dir).glob("*.bin"))
found["otlp_payloads"] = {name: raw.count(value.encode()) for name, value in markers.items()}
sources.append(f"raw OTLP payloads ({len(raw) // 1024} KiB)")
(EVIDENCE / "leak-check.json").write_text(json.dumps(found, indent=1), encoding="utf-8")
print(json.dumps(found))
leaks = []
for source, hits in found.items():
if isinstance(hits, dict):
leaks += [f"{source}.{k}" for k, v in hits.items() if k != "traces_fetched" and v]
elif isinstance(hits, int) and hits:
leaks.append(source)
check(not leaks, f"secrets found in: {leaks}")
print(f"searched: {', '.join(sources)}; traces fetched: "
f"{found.get('tempo', {}).get('traces_fetched') if isinstance(found.get('tempo'), dict) else 'n/a'}")
print("PASS: no password, session token or Authorization value in logs or telemetry")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAIL: {exc}")
raise SystemExit(1)
+323
View File
@@ -0,0 +1,323 @@
"""lab7, уровень 4: жизненный цикл секретов и сертификатов ПОД НАГРУЗКОЙ, без пересборки образов.
python student-tests/lifecycle.py rotate-secret | rotate-leaf | token-expiry | sealed | all
Нужны: запущенный стенд, Python с cryptography на хосте (requirements-ops.txt) и файлы оператора
(secrets/operator/*). Всё время сценария фоновая нагрузка (вход + чтение + отправка сообщений через LB)
считает ответы; итог — evidence/lifecycle-<сценарий>.json. Секреты не печатаются.
rotate-secret Пароль ACL-пользователя api в Redis (рабочий секрет API):
1) Redis: ACL SETUSER api >new — временно действуют оба пароля;
2) OpenBao: новая версия messenger/api.redis_password (bao.py kv-rotate, check-and-set);
3) ждём, пока КАЖДАЯ реплика API прочитала новую версию (лог secrets.rotated);
4) Redis: ACL SETUSER api resetpass >new — старый пароль больше не действует; CLIENT KILL USER api
рвёт старые соединения, пул API переподключается уже с новым паролем; ACL SAVE.
rotate-leaf Клиентский сертификат LB (identity CN=lb для mTLS LB -> API):
1) pki.py rotate lb (старый leaf — в lb/previous); 2) reload HAProxy (USR2, без обрыва);
3) pki.py revoke lb --previous + bao.py sync-crl; reload lb и otel-gate (их CRL);
4) API перечитывает CRL сам (CRL_RELOAD_SECONDS) и закрывает открытые соединения со старым leaf;
5) зонд: старый leaf -> отказ (revoked), новый -> 200.
token-expiry Короткий TTL токенов роли api (20 с / max 40 с) + отзыв всех токенов cert auth: сервисы
перелогиниваются сертификатом, renew/relogin видны в логах, запросы не падают. TTL возвращается.
sealed OpenBao запечатан: работающие реплики обслуживают запросы (секреты в памяти), перезапущенная
реплика НЕ становится готовой (fail closed, LB её не использует); после unseal — готова.
"""
import datetime as dt
import hashlib
import json
import os
import secrets
import subprocess
import sys
import tempfile
import threading
import time
from collections import Counter
from common import (EVIDENCE, ROOT, api_containers, check, compose, compose_output, docker, health, new_chat,
new_key, new_user, try_call, wait_balanced)
PY = sys.executable
RESULTS = {}
# ---------------- фоновая нагрузка ----------------
class Load:
"""2 потока: GET /users/me + POST message (Idempotency-Key) и периодический новый вход (новый Redis SET)."""
def __init__(self):
self.user = new_user("lifecycle")
self.chat = new_chat(self.user)
self.stop = threading.Event()
self.codes = Counter()
self.errors = []
self.threads = [threading.Thread(target=self.reader, daemon=True),
threading.Thread(target=self.login_loop, daemon=True)]
def note(self, what, reply):
code = reply.status if reply is not None else "conn_error"
self.codes[f"{what}:{code}"] += 1
if reply is None or reply.status >= 500:
self.errors.append({"t": time.time(), "what": what, "code": code})
def reader(self):
while not self.stop.is_set():
self.note("me", try_call("GET", "/api/v1/users/me", token=self.user["token"], timeout=5))
self.note("send", try_call("POST", f"/api/v1/chats/{self.chat['id']}/messages", token=self.user["token"],
body={"text": "load"}, headers={"Idempotency-Key": new_key()}, timeout=5))
time.sleep(0.05)
def login_loop(self):
users = [new_user("lifecycle_login") for _ in range(4)] # лимит 10 входов/мин на username
i = 0
while not self.stop.is_set():
u = users[i % len(users)]
i += 1
import base64
auth = "Basic " + base64.b64encode(f"{u['username']}:{u['password']}".encode()).decode()
self.note("login", try_call("POST", "/api/v1/auth/sessions", headers={"Authorization": auth}, timeout=5))
time.sleep(2)
def __enter__(self):
self.started = time.time()
for t in self.threads:
t.start()
return self
def __exit__(self, *exc):
self.stop.set()
for t in self.threads:
t.join(timeout=10)
self.seconds = round(time.time() - self.started, 1)
return False
def summary(self):
return {"seconds": self.seconds, "codes": dict(self.codes), "errors_5xx_or_conn": len(self.errors),
"errors": self.errors[:10]}
# ---------------- помощники оператора ----------------
def operator(*args):
result = subprocess.run([PY, *args], cwd=ROOT, capture_output=True, text=True, check=False)
check(result.returncode == 0, f"{' '.join(args[:3])}: {result.stderr.strip()[-300:]}")
return result.stdout.strip()
def redis_admin(commands):
"""Команды redis-cli от admin: пароль admin и сами команды идут через stdin (не в argv, не в выводе)."""
password = (ROOT / "secrets" / "operator" / "redis_admin_password").read_text(encoding="utf-8").strip()
script = ("read -r REDISCLI_AUTH; export REDISCLI_AUTH; exec redis-cli --tls --cacert /run/tls-ca/ca.crt "
"--cert /run/tls/tls.crt --key /run/tls/tls.key -h 127.0.0.1 --sni redis --user admin --no-auth-warning")
result = subprocess.run(["docker", "compose", "exec", "-T", "redis", "sh", "-c", script], cwd=ROOT,
input=(password + "\n" + "\n".join(commands) + "\n").encode(), capture_output=True,
check=False)
check(result.returncode == 0, f"redis-cli failed: {result.stderr.decode()[-200:]}")
return result.stdout.decode()
def events_since(service, since, names):
"""События из логов сервиса (JSON-строки) после момента since: {event: count}."""
counts = Counter()
for line in compose_output("logs", "--no-log-prefix", service).splitlines():
start = line.find("{")
if start < 0:
continue
try:
item = json.loads(line[start:])
except ValueError:
continue
ts = item.get("ts", "")
try:
moment = dt.datetime.fromisoformat(ts.replace("Z", "+00:00")).timestamp()
except ValueError:
continue
if moment >= since and item.get("event") in names:
counts[item["event"]] += 1
if item["event"] == "secrets.rotated":
counts[f"rotated:{item.get('message', '')[-20:]}"] += 1
return counts
def save(name, data):
RESULTS[name] = data
path = EVIDENCE / f"lifecycle-{name}.json"
path.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
print(f"saved {path}")
# ---------------- сценарии ----------------
def rotate_secret():
print("--- rotate-secret: пароль Redis ACL-пользователя api")
replicas = len(api_containers())
version_before = json.loads(operator("scripts/bao.py", "kv-version", "api"))["version"]
new_password = secrets.token_hex(24)
digest = hashlib.sha256(new_password.encode()).hexdigest()
started = time.time()
with Load() as load:
time.sleep(3)
redis_admin([f"ACL SETUSER api >{new_password}"])
both = sum(1 for line in redis_admin(["ACL GETUSER api"]).splitlines() if len(line.strip()) == 64)
with tempfile.NamedTemporaryFile("w", delete=False, dir=ROOT / "secrets" / "operator") as tmp:
tmp.write(new_password)
try:
os.chmod(tmp.name, 0o600)
operator("scripts/bao.py", "kv-rotate", "api", "redis_password", "--value-file", tmp.name)
finally:
os.unlink(tmp.name)
version_after = json.loads(operator("scripts/bao.py", "kv-version", "api"))["version"]
t_rotated = time.time()
deadline = time.time() + 90
while True:
seen = events_since("api", started, {"secrets.rotated"})
if seen.get("secrets.rotated", 0) >= replicas:
break
check(time.time() < deadline, f"replicas did not pick up the new version: {dict(seen)}")
time.sleep(1)
picked_up = round(time.time() - t_rotated, 1)
redis_admin([f"ACL SETUSER api resetpass >{new_password}", "CLIENT KILL USER api", "ACL SAVE"])
acl = redis_admin(["ACL GETUSER api"])
time.sleep(8) # новые соединения пула — уже с новым паролем
passwords = [line.strip() for line in acl.splitlines() if len(line.strip()) == 64
and all(c in "0123456789abcdef" for c in line.strip())]
check(passwords == [digest], "old password still active or new one missing")
data = {"kv_version": [version_before, version_after], "replicas": replicas,
"active_passwords_during_overlap": both,
"all_replicas_picked_up_after_s": picked_up, "active_password_hashes_after": len(passwords),
"new_password_hash_matches": digest in acl, "load": load.summary()}
check(len(passwords) == 1, f"expected exactly one active password, got {len(passwords)}")
check(load.summary()["errors_5xx_or_conn"] == 0, f"errors during rotation: {load.errors[:5]}")
print(json.dumps(data, ensure_ascii=False))
print("PASS: Redis password rotated via OpenBao without restarts; old password revoked; no errors")
save("rotate-secret", data)
def leaf_serial(path):
from cryptography import x509
return format(x509.load_pem_x509_certificate(path.read_bytes()).serial_number, "x")
def probe_lb():
result = subprocess.run(["docker", "compose", "--profile", "tools", "run", "--rm", "-T", "probe",
"python", "/probe/tls_probe.py", "lb-api"], cwd=ROOT, capture_output=True, check=False)
rows = [json.loads(line) for line in result.stdout.decode().splitlines() if line.startswith("{")]
return {r["case"]: r["observed"] for r in rows if "case" in r}, [r for r in rows if "case" in r and not r["pass"]]
def rotate_leaf():
print("--- rotate-leaf: клиентский сертификат LB (CN=lb)")
lb_dir = ROOT / "secrets" / "pki" / "lb"
old_serial = leaf_serial(lb_dir / "tls.crt")
with Load() as load:
time.sleep(3)
operator("scripts/pki.py", "rotate", "lb")
new_serial = leaf_serial(lb_dir / "tls.crt")
compose("kill", "-s", "USR2", "lb") # master-worker reload: новый leaf для новых соединений
time.sleep(5)
operator("scripts/pki.py", "revoke", "lb", "--previous")
operator("scripts/bao.py", "sync-crl")
compose("kill", "-s", "USR2", "lb") # HAProxy и otel-gate перечитывают CRL при reload
compose("kill", "-s", "USR2", "otel-gate")
t_revoked = time.time()
time.sleep(12) # > CRL_RELOAD_SECONDS: API перечитал CRL
observed, failed = probe_lb()
closed = events_since("api", t_revoked - 1, {"tls.crl_loaded", "tls.revoked_connections_closed",
"tls.client_rejected"})
data = {"old_serial": old_serial[:16], "new_serial": new_serial[:16],
"probe": {k: v for k, v in observed.items() if "LB" in k or "lb" in k},
"api_events_after_revoke": dict(closed), "load": load.summary()}
print(json.dumps(data, ensure_ascii=False))
check(observed.get("previous (rotated, revoked) LB leaf") in ("server_rejected_client_cert",
"connection_closed_after_handshake"),
"old leaf is still accepted")
check(observed.get("valid LB identity (CN=lb)") == "http_200", "new leaf is not accepted")
check(not failed, f"probe failures: {failed}")
check(load.summary()["errors_5xx_or_conn"] == 0, f"errors during rotation: {load.errors[:5]}")
print("PASS: LB leaf rotated without rebuild/restart; old leaf revoked by CRL and rejected; no errors")
save("rotate-leaf", data)
def token_expiry():
print("--- token-expiry: короткий TTL токенов OpenBao роли api")
started = time.time()
try:
with Load() as load:
operator("scripts/bao.py", "role-ttl", "api", "20s", "40s")
operator("scripts/bao.py", "revoke-service-tokens")
time.sleep(100)
finally:
operator("scripts/bao.py", "role-ttl", "api", "15m", "1h")
operator("scripts/bao.py", "revoke-service-tokens") # вернуть обычные токены
events = events_since("api", started, {"secrets.login", "secrets.renewed", "secrets.relogin",
"secrets.refresh_failed", "secrets.renew_failed"})
data = {"role_ttl": "20s / max 40s", "observed_seconds": 100, "api_events": dict(events),
"load": load.summary()}
print(json.dumps(data, ensure_ascii=False))
# Отзыв замечает то, что раньше обратится к OpenBao с отозванным токеном: чтение KV (refresh_failed)
# или продление (renew_failed -> сразу новый вход). Оба пути — реакция именно на revoke.
check(events.get("secrets.refresh_failed", 0) + events.get("secrets.renew_failed", 0) >= 1,
"revoked token was not noticed")
check(events.get("secrets.login", 0) + events.get("secrets.relogin", 0) + events.get("secrets.renew_failed", 0) >= 2,
"no re-login after expiry")
check(load.summary()["errors_5xx_or_conn"] == 0, f"errors: {load.errors[:5]}")
print("PASS: expired/revoked tokens -> services re-login with their certificate; requests unaffected")
save("token-expiry", data)
def sealed():
print("--- sealed: OpenBao запечатан")
containers = api_containers()
check(len(containers) >= 2, "need 2 api replicas")
victim = containers[0]
started = time.time()
with Load() as load:
time.sleep(3)
operator("scripts/bao.py", "seal")
t_sealed = time.time()
time.sleep(40) # > SECRETS_REFRESH_SECONDS: отказ обновления замечен
docker("stop", "--time", "15", victim)
docker("start", victim)
time.sleep(30)
victim_health = health(victim)
serving = len({try_call("GET", "/health/ready").instance for _ in range(6)} - {None})
operator("scripts/bao.py", "unseal")
t_unsealed = time.time()
deadline = time.time() + 120
while health(victim) != "healthy":
check(time.time() < deadline, "replica did not recover after unseal")
time.sleep(1)
recovered = round(time.time() - t_unsealed, 1)
time.sleep(3)
events = events_since("api", started, {"secrets.refresh_failed", "secrets.waiting", "secrets.unavailable",
"secrets.login"})
data = {"sealed_seconds": round(t_unsealed - t_sealed, 1), "restarted_replica_health_while_sealed": victim_health,
"replicas_answering_while_sealed": serving, "restarted_replica_ready_after_unseal_s": recovered,
"api_events": dict(events), "load": load.summary()}
print(json.dumps(data, ensure_ascii=False))
check(victim_health != "healthy", "a replica became ready without secrets")
check(events.get("secrets.refresh_failed", 0) >= 1, "sealed OpenBao was not noticed")
errors = [e for e in load.errors if e["code"] != 503]
check(not errors, f"unexpected errors while sealed: {errors[:5]}")
print("PASS: sealed OpenBao -> running replicas keep serving from memory, a restarted replica stays not ready "
"(fail closed) until unseal")
save("sealed", data)
wait_balanced(2, 60)
SCENARIOS = {"rotate-secret": rotate_secret, "rotate-leaf": rotate_leaf, "token-expiry": token_expiry,
"sealed": sealed}
if __name__ == "__main__":
names = sys.argv[1:] or ["all"]
if names == ["all"]:
names = list(SCENARIOS)
failed = 0
for name in names:
try:
SCENARIOS[name]()
except AssertionError as exc:
failed += 1
print(f"FAIL: {name}: {exc}")
raise SystemExit(1 if failed else 0)
+102
View File
@@ -0,0 +1,102 @@
import math
import threading
import time
from common import check, new_chat, new_key, new_user, read_history, try_call
class Load:
def __init__(self, writers=4, timeout=2):
self.alice, self.bob = new_user("load_a"), new_user("load_b")
self.chat = new_chat(self.alice, self.bob, title="load")
self.writers, self.timeout = writers, timeout
self.events = [] # (время, "write"/"read", ok, код или "conn", реплика, задержка в с)
self.confirmed = [] # сообщения, на которые пришёл 201
self.lock = threading.Lock()
self.stopping = threading.Event()
self.threads = []
def _record(self, kind, started, reply, ok):
code = reply.status if reply is not None else "conn"
instance = reply.instance if reply is not None else None
with self.lock:
self.events.append((started, kind, ok, code, instance, time.monotonic() - started))
def _writer(self, number):
path = f"/api/v1/chats/{self.chat['id']}/messages"
sent = 0
key, text = new_key(), f"load-{number}-{sent}"
while not self.stopping.is_set():
started = time.monotonic()
reply = try_call("POST", path, body={"text": text}, token=self.alice["token"],
headers={"Idempotency-Key": key}, timeout=self.timeout)
ok = reply is not None and reply.status == 201
self._record("write", started, reply, ok)
if ok:
with self.lock:
self.confirmed.append(reply.json)
sent += 1
key, text = new_key(), f"load-{number}-{sent}"
else:
time.sleep(0.05) # и повторить тот же text с тем же ключом
def _reader(self):
path = f"/api/v1/chats/{self.chat['id']}/messages?limit=20"
while not self.stopping.is_set():
started = time.monotonic()
reply = try_call("GET", path, token=self.bob["token"], timeout=self.timeout)
self._record("read", started, reply, reply is not None and reply.status == 200)
time.sleep(0.05)
def start(self):
self.threads = [threading.Thread(target=self._writer, args=(n,), daemon=True) for n in range(self.writers)]
self.threads.append(threading.Thread(target=self._reader, daemon=True))
for thread in self.threads:
thread.start()
def stop(self):
self.stopping.set()
for thread in self.threads:
thread.join(timeout=self.timeout + 5)
def window(self, start, end, kind=None):
with self.lock:
return [e for e in self.events if start <= e[0] < end and (kind is None or e[1] == kind)]
def verify(self):
"""Все подтверждённые сообщения есть в истории, id и тексты не повторяются."""
history, _ = read_history(self.bob, self.chat["id"])
ids = [message["id"] for message in history]
texts = [message["text"] for message in history]
by_id = {message["id"]: message for message in history}
check(len(ids) == len(set(ids)), "duplicated message ids in history")
check(len(texts) == len(set(texts)), "a retried request created a duplicate message")
lost = [m for m in self.confirmed if by_id.get(m["id"]) != m]
check(not lost, f"{len(lost)} confirmed messages are lost or changed")
return {"confirmed_writes": len(self.confirmed), "messages_in_history": len(history), "duplicates": 0, "lost": 0}
def summary(load, start, end):
"""Успешные RPS, ошибки и задержки на отрезке [start, end)."""
events = load.window(start, end)
writes = [e for e in events if e[1] == "write"]
ok_writes = sorted(e[5] for e in writes if e[2])
errors = [e for e in events if not e[2]]
seconds = max(end - start, 1e-6)
def percentile(p):
return round(1000 * ok_writes[max(0, math.ceil(p * len(ok_writes)) - 1)], 1) if ok_writes else None
codes = {}
for e in errors:
codes[str(e[3])] = codes.get(str(e[3]), 0) + 1
return {
"seconds": round(seconds, 2),
"write_rps": round(len(ok_writes) / seconds, 1),
"reads": len([e for e in events if e[1] == "read"]),
"errors": len(errors),
"error_codes": codes,
"write_p50_ms": percentile(0.50),
"write_p95_ms": percentile(0.95),
"write_max_ms": round(1000 * ok_writes[-1], 1) if ok_writes else None,
}
+149
View File
@@ -0,0 +1,149 @@
"""lab7: измеренный бюджет защиты от дорогостоящего login DoS.
python student-tests/login_dos.py [--seconds 20] [--attackers 16]
Фаза 1 (baseline): легитимный клиент — GET /users/me и POST message, p50/p95/p99.
Фаза 2 (атака): attackers потоков без пауз шлют вход с НЕВЕРНЫМ паролем по множеству разных существующих
username (обход лимита на username), с одного адреса — как ботнет за NAT; плюс тот же легитимный клиент.
Ожидаем: Argon2id не съедает реплику — одновременно не больше ARGON2_MAX_CONCURRENCY хешей на реплику,
лишние входы получают 503 + Retry-After сразу (нет очереди), затем общий лимит на IP даёт 429 до хеширования;
задержка легитимных запросов остаётся ограниченной. Итог — evidence/login-dos.json.
"""
import argparse
import json
import threading
import time
import uuid
from collections import Counter
from common import EVIDENCE, app_python, basic, new_chat, new_key, new_user, try_call
# Фаза 3: всплеск с МНОГИХ адресов (ботнет) — общий лимит по IP не помогает, держит бюджет реплики.
# Внутри одного контейнера api: N одновременных проверок пароля через auth.password_matches (тот же семафор,
# те же ARGON2_MAX_CONCURRENCY / ARGON2_QUEUE_SECONDS, что у запросов). Считаем, сколько получили 503 сразу,
# максимум одновременно идущих хешей и рост памяти процесса.
BURST = r'''
import json, resource, sys, threading, time
from concurrent.futures import ThreadPoolExecutor
import auth, settings
from errors import ApiError
n = int(sys.argv[1])
running = {"now": 0, "max": 0}
lock = threading.Lock()
class Counting: # обёртка над PasswordHasher: сколько verify идёт одновременно
def __init__(self, inner):
self.inner = inner
def verify(self, *a, **k):
with lock:
running["now"] += 1; running["max"] = max(running["max"], running["now"])
try:
return self.inner.verify(*a, **k)
finally:
with lock:
running["now"] -= 1
auth.hasher = Counting(auth.hasher)
rss_before = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
def one(_):
started = time.perf_counter()
try:
auth.password_matches(None, "Wrong-password-123")
return "hashed", time.perf_counter() - started
except ApiError as exc:
return f"rejected_{exc.status_code}", time.perf_counter() - started
t0 = time.perf_counter()
with ThreadPoolExecutor(max_workers=n) as pool:
results = list(pool.map(one, range(n)))
codes = {}
for code, _ in results:
codes[code] = codes.get(code, 0) + 1
slowest_rejection = max((t for c, t in results if c.startswith("rejected")), default=None)
print(json.dumps({"requests": n, "codes": codes, "max_parallel_hashes": running["max"],
"limit": settings.ARGON2_MAX_CONCURRENCY, "queue_s": settings.ARGON2_QUEUE_SECONDS,
"seconds": round(time.perf_counter() - t0, 2),
"slowest_rejection_s": round(slowest_rejection, 2) if slowest_rejection else None,
"maxrss_growth_mib": round((resource.getrusage(resource.RUSAGE_SELF).ru_maxrss - rss_before) / 1024, 1)}))
'''
def percentile(values, q):
if not values:
return None
values = sorted(values)
return round(values[min(len(values) - 1, int(q * len(values)))] * 1000, 1)
def legit(user, chat, stop, latencies, codes):
while not stop.is_set():
for method, path, body, headers in (
("GET", "/api/v1/users/me", None, None),
("POST", f"/api/v1/chats/{chat['id']}/messages", {"text": "hi"}, {"Idempotency-Key": new_key()})):
started = time.perf_counter()
reply = try_call(method, path, token=user["token"], body=body, headers=headers, timeout=10)
latencies.append(time.perf_counter() - started)
codes[reply.status if reply else "conn_error"] += 1
time.sleep(0.02)
def attacker(usernames, stop, codes, latencies, offset):
i = offset
while not stop.is_set():
name = usernames[i % len(usernames)]
i += 1
started = time.perf_counter()
reply = try_call("POST", "/api/v1/auth/sessions", headers={"Authorization": basic(name, "Wrong-" + uuid.uuid4().hex)},
timeout=10)
latencies.append(time.perf_counter() - started)
codes[reply.status if reply else "conn_error"] += 1
def phase(seconds, user, chat, usernames=None, attackers=0):
stop = threading.Event()
legit_lat, legit_codes, attack_lat, attack_codes = [], Counter(), [], Counter()
threads = [threading.Thread(target=legit, args=(user, chat, stop, legit_lat, legit_codes))]
threads += [threading.Thread(target=attacker, args=(usernames, stop, attack_codes, attack_lat, n * 7))
for n in range(attackers)]
for t in threads:
t.start()
time.sleep(seconds)
stop.set()
for t in threads:
t.join()
return {"legit": {"requests": len(legit_lat), "codes": dict(legit_codes), "p50_ms": percentile(legit_lat, .5),
"p95_ms": percentile(legit_lat, .95), "p99_ms": percentile(legit_lat, .99)},
"attack": {"requests": len(attack_lat), "codes": dict(attack_codes),
"rps": round(len(attack_lat) / seconds, 1), "p50_ms": percentile(attack_lat, .5),
"p95_ms": percentile(attack_lat, .95)} if attackers else None}
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--seconds", type=int, default=20)
parser.add_argument("--attackers", type=int, default=16)
args = parser.parse_args()
user = new_user("dos_legit")
chat = new_chat(user)
# жертвы: существующие username (неизвестный username тоже стоит один verify с DUMMY_HASH)
usernames = [new_user("dos_victim")["username"] for _ in range(40)]
print(f"baseline {args.seconds} s ...")
baseline = phase(args.seconds, user, chat)
print(json.dumps(baseline))
print(f"attack: {args.attackers} threads of wrong-password logins over {len(usernames)} usernames ...")
attack = phase(args.seconds, user, chat, usernames, args.attackers)
print(json.dumps(attack))
burst = json.loads(app_python(BURST, 200).splitlines()[-1])
print(f"burst of 200 simultaneous password checks in one api process: {json.dumps(burst)}")
data = {"baseline": baseline, "under_attack": attack, "seconds": args.seconds, "attackers": args.attackers,
"burst_one_replica": burst}
(EVIDENCE / "login-dos.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
codes = attack["attack"]["codes"]
hashed = codes.get(401, 0)
print(f"attack: {attack['attack']['rps']} login attempts/s; 401 (hash computed) {hashed}, "
f"503 busy (rejected before hashing) {codes.get(503, 0)}, 429 rate limited {codes.get(429, 0)}")
print(f"legit p95: {baseline['legit']['p95_ms']} ms -> {attack['legit']['p95_ms']} ms; "
f"legit errors: { {k: v for k, v in attack['legit']['codes'].items() if k not in (200, 201)} }")
print("saved evidence/login-dos.json")
if __name__ == "__main__":
main()
+226
View File
@@ -0,0 +1,226 @@
"""Запросы к хранилищам телеметрии для тестов lab6/lab7 (только стандартная библиотека).
Адреса — порты, опубликованные compose.yaml только на 127.0.0.1. lab7: HTTPS с проверкой учебного CA и
клиентским сертификатом оператора (CN=operator) — opener из common.py:
PROMETHEUS_URL (https://localhost:9090), LOKI_URL (https://localhost:3100), TEMPO_URL (https://localhost:3200).
"""
import base64
import binascii
import json
import os
import re
import secrets
import time
import urllib.error
import urllib.parse
import urllib.request
import common # noqa: F401,E402 — устанавливает HTTPS-opener (CA стенда + сертификат оператора)
PROMETHEUS_URL = os.environ.get("PROMETHEUS_URL", "https://127.0.0.1:9090").rstrip("/")
LOKI_URL = os.environ.get("LOKI_URL", "https://127.0.0.1:3100").rstrip("/")
TEMPO_URL = os.environ.get("TEMPO_URL", "https://127.0.0.1:3200").rstrip("/")
def get_json(url, timeout=10):
request = urllib.request.Request(url, headers={"Accept": "application/json"})
with urllib.request.urlopen(request, timeout=timeout) as reply:
return json.loads(reply.read().decode("utf-8"))
# ---------- Prometheus ----------
def prom_query(expr, at=None):
"""Мгновенный запрос. Возвращает список (labels, float). Ошибка запроса -> исключение."""
params = {"query": expr}
if at is not None:
params["time"] = str(at)
data = get_json(f"{PROMETHEUS_URL}/api/v1/query?" + urllib.parse.urlencode(params))
if data.get("status") != "success":
raise RuntimeError(f"PromQL error: {data}")
result = data["data"]["result"]
if data["data"]["resultType"] == "scalar":
return [({}, float(result[1]))]
return [(item["metric"], float(item["value"][1])) for item in result]
def prom_value(expr, default=None):
rows = prom_query(expr)
return rows[0][1] if rows else default
def prom_series(match):
data = get_json(f"{PROMETHEUS_URL}/api/v1/series?" + urllib.parse.urlencode({"match[]": match}))
return data["data"]
def alerts():
"""Активные алерты: {имя: состояние (pending/firing)}."""
data = get_json(f"{PROMETHEUS_URL}/api/v1/alerts")
out = {}
for alert in data["data"]["alerts"]:
name = alert["labels"]["alertname"]
if out.get(name) != "firing":
out[name] = alert["state"]
return out
def wait_alert(name, state, seconds, poll=5, log=print):
"""Ждёт, пока алерт name перейдёт в state ('firing' или 'resolved' = отсутствует). Возвращает секунды."""
started = time.monotonic()
while True:
current = alerts().get(name, "inactive")
done = current == "firing" if state == "firing" else current == "inactive"
if done:
return round(time.monotonic() - started, 1)
if time.monotonic() - started > seconds:
raise AssertionError(f"alert {name}: still {current} after {seconds} s (want {state})")
log(f" ... {name}: {current} ({time.monotonic() - started:.0f} s)")
time.sleep(poll)
def wait_metric(expr, predicate, seconds, poll=5):
"""Ждёт, пока значение выражения удовлетворит predicate. Возвращает значение."""
deadline = time.monotonic() + seconds
while True:
value = prom_value(expr)
if value is not None and predicate(value):
return value
if time.monotonic() > deadline:
raise AssertionError(f"{expr}: value {value} after {seconds} s")
time.sleep(poll)
# ---------- Loki ----------
def loki_query(logql, minutes=30, limit=200):
"""Записи за последние minutes минут: список (labels+structured metadata, строка)."""
now = time.time_ns()
params = {"query": logql, "start": str(now - minutes * 60 * 10**9), "end": str(now), "limit": str(limit),
"direction": "backward"}
data = get_json(f"{LOKI_URL}/loki/api/v1/query_range?" + urllib.parse.urlencode(params))
if data.get("status") != "success":
raise RuntimeError(f"LogQL error: {data}")
out = []
for stream in data["data"]["result"]:
for value in stream["values"]:
labels = dict(stream["stream"])
if len(value) > 2 and isinstance(value[2], dict):
for group in value[2].values():
if isinstance(group, dict):
labels.update(group)
out.append((labels, value[1]))
return out
def wait_logs(logql, minimum=1, seconds=60):
deadline = time.monotonic() + seconds
while True:
rows = loki_query(logql)
if len(rows) >= minimum:
return rows
if time.monotonic() > deadline:
raise AssertionError(f"Loki: {len(rows)} records for {logql} after {seconds} s")
time.sleep(2)
# ---------- Tempo ----------
def new_traceparent():
"""Свой trace_id для контролируемого запроса: по нему трасса находится без поиска."""
trace_id = secrets.token_hex(16)
return trace_id, f"00-{trace_id}-{secrets.token_hex(8)}-01"
def tempo_trace(trace_id):
"""Спаны трассы: список dict(service, name, kind, span_id, parent_id, duration_ms, status, attrs, links)."""
try:
data = get_json(f"{TEMPO_URL}/api/traces/{trace_id}")
except urllib.error.HTTPError as error:
if error.code == 404:
return []
raise
spans = []
for batch in data.get("batches", data.get("resourceSpans", [])):
resource = {a["key"]: _value(a["value"]) for a in batch["resource"].get("attributes", [])}
for scope in batch.get("scopeSpans", batch.get("instrumentationLibrarySpans", [])):
for span in scope.get("spans", []):
spans.append({
"service": resource.get("service.name"),
"instance": resource.get("service.instance.id"),
"name": span["name"],
"kind": span.get("kind", "").replace("SPAN_KIND_", ""),
"span_id": _hex_id(span["spanId"], 16),
"parent_id": _hex_id(span.get("parentSpanId", ""), 16),
"start": int(span["startTimeUnixNano"]),
"duration_ms": (int(span["endTimeUnixNano"]) - int(span["startTimeUnixNano"])) / 1e6,
"status": span.get("status", {}).get("code", "").replace("STATUS_CODE_", ""),
"attrs": {a["key"]: _value(a["value"]) for a in span.get("attributes", [])},
"links": [{"trace_id": _hex_id(link.get("traceId", ""), 32),
"span_id": _hex_id(link.get("spanId", ""), 16)} for link in span.get("links", [])],
})
return spans
def _hex_id(value, size):
"""ID спана/трассы из JSON Tempo: hex или base64 (OTLP JSON кодирует bytes в base64) -> hex."""
if not value:
return ""
if re.fullmatch(r"[0-9a-fA-F]+", value) and len(value) in (size, size // 2 * 2):
return value.lower().rjust(size, "0")
try:
return base64.b64decode(value).hex().rjust(size, "0")
except (binascii.Error, ValueError):
return value
def _value(value):
for key in ("stringValue", "intValue", "boolValue", "doubleValue"):
if key in value:
return int(value[key]) if key == "intValue" else value[key]
return json.dumps(value)
def wait_trace(trace_id, predicate=lambda spans: bool(spans), seconds=60):
deadline = time.monotonic() + seconds
while True:
spans = tempo_trace(trace_id)
if predicate(spans):
return spans
if time.monotonic() > deadline:
raise AssertionError(f"Tempo: trace {trace_id} incomplete after {seconds} s ({len(spans)} spans)")
time.sleep(2)
def tempo_search(traceql, minutes=30, limit=20):
now = int(time.time())
params = {"q": traceql, "start": str(now - minutes * 60), "end": str(now), "limit": str(limit)}
return get_json(f"{TEMPO_URL}/api/search?" + urllib.parse.urlencode(params)).get("traces", [])
def span_tree(spans):
"""Текстовое дерево трассы для отчёта (без атрибутов с данными пользователя)."""
by_id = {s["span_id"]: s for s in spans}
children = {}
for span in spans:
parent = span["parent_id"] if span["parent_id"] in by_id else ""
children.setdefault(parent, []).append(span)
lines = []
def walk(span, depth):
extra = []
for key in ("messenger.job.attempt", "messenger.job.outcome", "http.response.status_code", "error.type",
"aws.s3.key"):
if key in span["attrs"]:
extra.append(f"{key}={span['attrs'][key]}")
status = " ERROR" if span["status"] == "ERROR" else ""
links = f" links={len(span['links'])}" if span["links"] else ""
short = (span["service"] or "?").replace("messenger-", "")
lines.append(f"{' ' * depth}- [{short}] {span['name']} ({span['kind']}, {span['duration_ms']:.1f} ms)"
f"{status}{links} {' '.join(extra)}".rstrip())
for child in sorted(children.get(span["span_id"], []), key=lambda s: s["start"]):
walk(child, depth + 1)
for root in sorted(children.get("", []), key=lambda s: s["start"]):
walk(root, 0)
return "\n".join(lines)
+36
View File
@@ -0,0 +1,36 @@
import subprocess
from common import ROOT, login, new_user, redis_cli, session_key
def without_password():
"""lab7: по TLS с сертификатом, но без AUTH — сервер отвечает NOAUTH; без TLS — соединение не устанавливается."""
tls = ("redis-cli --tls --cacert /run/tls-ca/ca.crt --cert /run/tls/tls.crt --key /run/tls/tls.key "
"-h 127.0.0.1 --sni redis get anything")
plain = "redis-cli -h 127.0.0.1 -p 6379 get anything"
outputs = []
for command in (tls, plain):
result = subprocess.run(["docker", "compose", "exec", "-T", "redis", "sh", "-c", command + " 2>&1"],
cwd=ROOT, capture_output=True, check=False)
outputs.append((result.stdout + result.stderr).decode("utf-8", "replace").strip()[:80])
return f"TLS without AUTH -> {outputs[0]!r}; plaintext -> {outputs[1]!r}"
def main():
user = new_user("info")
token = login(user["username"], user["password"]).json["token"]
key = session_key(token)
print(f"session key: {key[:24]}...; value is the user id: {redis_cli('get', key) == user['id']}")
print(f"TTL of the key, seconds: {redis_cli('ttl', key)}")
keys = redis_cli("--scan", "--pattern", "'session:*'").splitlines()
print(f"sessions in Redis: {len(keys)}")
for name in ("appendonly", "appendfsync", "maxmemory-policy", "port", "tls-port", "tls-auth-clients"):
print("config", " = ".join(redis_cli("config", "get", name).split()))
for line in redis_cli("info", "persistence").splitlines():
if line.startswith(("aof_enabled", "aof_last_write_status")):
print(line)
print(f"without password: {without_password()}")
if __name__ == "__main__":
main()
+88
View File
@@ -0,0 +1,88 @@
import json
import os
import time
from common import ROOT, api_containers, check, compose, compose_output, docker, health, lb_up_count, wait_balanced
from loadgen import Load, summary
OUTPUT = ROOT / "evidence" / "rolling-update.json"
def env_of(container):
lines = docker("inspect", "-f", "{{range .Config.Env}}{{println .}}{{end}}", container).splitlines()
return dict(line.split("=", 1) for line in lines if "=" in line)
def wait_new_replica(container, up_needed, seconds=90):
deadline = time.monotonic() + seconds
while health(container) != "healthy" or lb_up_count() < up_needed:
check(time.monotonic() < deadline, f"new replica {container[:12]} is not in the balancer after {seconds} s")
time.sleep(0.2)
def main():
old = api_containers()
replicas = len(old)
check(replicas >= 2, "need at least 2 running api replicas")
wait_balanced(replicas)
old_version = env_of(old[0]).get("APP_VERSION")
version = time.strftime("rolling-%Y%m%d-%H%M%S")
env = dict(os.environ, APP_VERSION=version)
print(f"old replicas {[c[:12] for c in old]}, version {old_version}; building version {version}")
started = time.monotonic()
compose("build", "api", "migrate", env=env)
print(f"image built in {time.monotonic() - started:.1f} s")
migrate_log = compose_output("run", "--rm", "--no-deps", "-T", "migrate", env=env)
print("migrations: " + [line for line in migrate_log.splitlines() if "Migrations applied" in line][-1]
.split("messenger.db: ")[-1])
load = Load()
load.start()
time.sleep(3)
t0 = time.monotonic()
steps = []
for container in old:
step_start = time.monotonic()
before = set(api_containers())
compose("up", "-d", "--no-deps", "--no-recreate", "--scale", f"api={len(before) + 1}", "api", env=env)
new = sorted(set(api_containers()) - before)
check(len(new) == 1, f"expected one new container, got {len(new)}")
wait_new_replica(new[0], replicas + 1)
ready = time.monotonic() - step_start
docker("stop", "--time", "15", container)
docker("rm", container)
steps.append({"old": container[:12], "new": new[0][:12], "new_ready_seconds": round(ready, 2),
"step_seconds": round(time.monotonic() - step_start, 2)})
print(f"replaced {container[:12]} -> {new[0][:12]}: new replica ready and in HAProxy after {ready:.1f} s, "
f"step {steps[-1]['step_seconds']} s")
t1 = time.monotonic()
time.sleep(3)
load.stop()
final = api_containers()
versions = sorted({env_of(c).get("APP_VERSION") for c in final})
integrity = load.verify()
during = summary(load, t0, t1)
before_stats = summary(load, t0 - 3, t0)
print(f"now: replicas {[c[:12] for c in final]}, versions {versions}")
print(f"under load: write RPS before {before_stats['write_rps']}, during the update {during['write_rps']}; "
f"errors {during['errors']} {during['error_codes']}; p95 {during['write_p95_ms']} ms, "
f"max {during['write_max_ms']} ms; update took {t1 - t0:.1f} s")
print(f"confirmed {integrity['confirmed_writes']}, in history {integrity['messages_in_history']}, "
f"lost 0, duplicates 0")
check(len(final) == replicas and not set(final) & set(old), "old replicas are still running")
check(versions == [version], "not every replica runs the new version")
OUTPUT.parent.mkdir(exist_ok=True)
OUTPUT.write_text(json.dumps({
"from_version": old_version, "to_version": version, "replicas": replicas,
"profile": {"writers": 4, "readers": 1, "client_timeout_seconds": 2},
"steps": steps, "update_seconds": round(t1 - t0, 2),
"before": before_stats, "during": during, "integrity": integrity,
}, indent=2) + "\n", encoding="utf-8")
print(f"PASS: all {replicas} replicas replaced one by one under load, "
f"{during['errors']} errors, no lost or duplicated messages; saved {OUTPUT.relative_to(ROOT)}")
if __name__ == "__main__":
main()
+59
View File
@@ -0,0 +1,59 @@
import os
import subprocess
import sys
from common import (BASE_URL, CA_FILE, ROOT, api_containers, call, check, compose_output, docker, instance_aliases,
wait_balanced)
HOOK = ROOT / "scripts" / ("stop-one.cmd" if os.name == "nt" else "stop-one.sh")
def ps():
return compose_output("ps", "-a", "--format", "table {{.Service}}\t{{.ID}}\t{{.Status}}", "api").strip()
def aim(wanted):
"""Для 2 реплик: последним перед тестом должна ответить реплика из wanted.
lab7: X-Instance-Id — случайный alias, а не ID контейнера; сопоставляем через instance_aliases()."""
aliases = {alias for container, alias in instance_aliases().items() if container in wanted}
probe = call("GET", "/health/live", 200).instance
if probe not in aliases:
call("GET", "/health/live", 200) # теперь последней ответила другая реплика
def main():
containers = api_containers()
check(len(containers) >= 2, "need at least 2 running api replicas")
print(f"hook: {HOOK.relative_to(ROOT)}; api replicas: {[c[:12] for c in containers]}")
stopped_once = set()
for attempt in range(1, 7):
wait_balanced(len(containers))
if len(containers) == 2:
aim(set(containers) - stopped_once)
print(f"=== run {attempt}: api containers before")
print(ps())
env = dict(os.environ, PYTHONUTF8="1", PYTHONIOENCODING="utf-8")
result = subprocess.run([sys.executable, "tests/resilience.py", "--mode", "failover",
"--action-script", str(HOOK), "--base-url", BASE_URL, "--ca-file", CA_FILE],
cwd=ROOT, capture_output=True, env=env)
print((result.stdout + result.stderr).decode("utf-8", "replace").strip())
check(result.returncode == 0, "public failover test failed")
print("api containers after")
print(ps())
stopped = [container for container in containers if container not in api_containers()]
check(len(stopped) == 1, f"expected exactly one stopped api container, got {len(stopped)}")
print(f"the hook stopped {stopped[0][:12]} (the replica behind TARGET_INSTANCE_ID, mapped from its alias); "
f"other api containers kept running, postgres/redis/lb were not touched")
stopped_once.add(stopped[0])
docker("start", stopped[0])
wait_balanced(len(containers))
print(f"restored: docker start {stopped[0][:12]} -> healthy and back in HAProxy")
if stopped_once == set(containers):
break
check(stopped_once == set(containers), "not every replica was stopped by the public test")
print(f"PASS: public failover test passed {attempt} times; every api replica was stopped once and restored")
if __name__ == "__main__":
main()
+55
View File
@@ -0,0 +1,55 @@
import os
import re
import subprocess
import sys
import time
from common import BASE_URL, CA_FILE, ROOT, check, compose_output, docker
HOOK = ROOT / "scripts" / ("restart.cmd" if os.name == "nt" else "restart.sh")
def started():
containers = compose_output("ps", "-q").split()
lines = docker("inspect", "-f", "{{.Name}} {{.Id}} {{.State.StartedAt}}", *containers).splitlines()
return {name.lstrip("/"): (cid, at) for name, cid, at in (line.split() for line in lines)}
def main():
before = started()
print("before: container, ID, started at")
for name, (cid, at) in sorted(before.items()):
print(f" {name:<28} {cid[:12]} {at}")
env = dict(os.environ, PYTHONUTF8="1", PYTHONIOENCODING="utf-8")
begin = time.monotonic()
result = subprocess.run([sys.executable, "tests/resilience.py", "--mode", "persistence",
"--action-script", str(HOOK), "--base-url", BASE_URL, "--ca-file", CA_FILE],
cwd=ROOT, capture_output=True, env=env)
seconds = time.monotonic() - begin
print((result.stdout + result.stderr).decode("utf-8", "replace").strip())
check(result.returncode == 0, "public persistence test failed")
after = started()
print(f"after (hook + waiting for readiness took {seconds:.1f} s): container, ID, started at, restarted?")
restarted = []
for name, (cid, at) in sorted(after.items()):
same_id = before.get(name, ("", ""))[0] == cid
new_start = before.get(name, ("", ""))[1] != at
print(f" {name:<28} {cid[:12]} {at} same container: {same_id}, restarted: {new_start}")
check(same_id, f"{name}: container was recreated, volumes/IDs must stay")
if new_start:
match = re.match(r"^.+?-lab\d+-(.+)-\d+$", name) or re.match(r"^(.+?)(?:-\d+)?$", name)
restarted.append(match.group(1))
# lab7: + openbao (рестарт и unseal оператором в hook) и otel-gate
services = ("postgres", "redis", "s3", "rabbitmq", "openbao", "api", "janitor", "dispatcher", "worker", "lb",
"otel-gate", "otel-collector", "prometheus", "loki", "tempo", "grafana")
present = {re.sub(r"^.+?-lab\d+-(.+)-\d+$", r"\1", n) if re.match(r"^.+?-lab\d+-", n)
else re.sub(r"-\d+$", "", n) for n in after}
services = tuple(s for s in services if s in present) # песочница: без loki/tempo/grafana
for service in services:
check(service in restarted, f"{service} was not restarted by the hook")
print(f"PASS: the hook restarted {', '.join(services)} (all api replicas; same containers, new start time); "
f"data, the attachment bytes and the old token survived")
if __name__ == "__main__":
main()
+258
View File
@@ -0,0 +1,258 @@
import base64
import datetime as dt
import uuid
from common import PASSWORD, basic, call, check, login, new_chat, new_key, new_user, read_history, run_tests, send
def parse_time(value):
return dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
def test_duplicate_username():
body = {"username": "dup_" + uuid.uuid4().hex[:10], "display_name": "First user", "password": PASSWORD}
call("POST", "/api/v1/users", 201, body=body)
call("POST", "/api/v1/users", 409, body=dict(body, display_name="Second user"))
print("PASS: duplicate username returns 409")
def test_invalid_json():
alice = new_user("alice")
chat = new_chat(alice)
call("POST", "/api/v1/users", 400, raw=b'{"username":')
call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, token=alice["token"], raw=b"not json",
headers={"Idempotency-Key": new_key()})
print("PASS: invalid JSON returns 400")
def test_wrong_fields():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
call("POST", "/api/v1/users", 400, body={"username": "Bad Name!", "display_name": "x", "password": PASSWORD})
call("POST", "/api/v1/users", 400,
body={"username": "valid_" + uuid.uuid4().hex[:8], "display_name": "x", "password": PASSWORD, "is_admin": True})
# Отправителя нельзя подставить: он берётся из сессии.
call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, token=alice["token"],
body={"text": "hi", "sender_id": bob["id"]}, headers={"Idempotency-Key": new_key()})
print("PASS: wrong and extra fields return 400")
def test_foreign_chat():
alice, bob, eve = new_user("alice"), new_user("bob"), new_user("eve")
chat = new_chat(alice, bob)
call("GET", f"/api/v1/chats/{chat['id']}", 404, token=eve["token"])
call("GET", f"/api/v1/chats/{chat['id']}/messages", 404, token=eve["token"])
send(eve, chat["id"], "not my chat", expected=404)
# Несуществующий чат выглядит так же, как чужой.
call("GET", f"/api/v1/chats/{uuid.uuid4()}", 404, token=eve["token"])
print("PASS: foreign chat returns 404")
def test_empty_message():
alice = new_user("alice")
chat = new_chat(alice)
for text in ("", " ", "\n\t"):
send(alice, chat["id"], text, expected=400)
send(alice, chat["id"], "я" * 4001, expected=400)
send(alice, chat["id"], "я" * 4000)
print("PASS: empty and too long messages return 400, 4000 chars is ok")
def test_pagination():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
sent = [send(alice, chat["id"], f"Message {i}").json["id"] for i in range(7)]
history, pages = read_history(bob, chat["id"], limit=2)
check(pages == 4, f"expected 4 pages, got {pages}")
check([m["id"] for m in history] == sent, "pages overlap, lose or reorder messages")
other = new_chat(alice)
for i in range(3):
send(alice, other["id"], f"Other {i}")
first = call("GET", f"/api/v1/chats/{other['id']}/messages?limit=1", token=alice["token"]).json
call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor={first['next_cursor']}", 400, token=alice["token"])
call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor=broken", 400, token=alice["token"])
print("PASS: pagination works across multiple pages, foreign cursor returns 400")
def test_empty_cursor():
alice = new_user("alice")
chat = new_chat(alice)
send(alice, chat["id"], "one message")
for path in ("/api/v1/chats", f"/api/v1/chats/{chat['id']}/messages"):
for query in ("?cursor=", "?cursor", "?limit=10&cursor="):
call("GET", path + query, 400, token=alice["token"])
call("GET", path, 200, token=alice["token"])
print("PASS: empty cursor (?cursor= and ?cursor) returns 400, no cursor returns the first page")
def test_chat_list_pagination():
alice, bob = new_user("alice"), new_user("bob")
created = [new_chat(alice, bob, title=f"Chat {i}")["id"] for i in range(3)]
seen, cursor = [], None
while True:
query = "?limit=1" + (f"&cursor={cursor}" if cursor else "")
page = call("GET", "/api/v1/chats" + query, token=bob["token"]).json
seen += [chat["id"] for chat in page["items"]]
cursor = page["next_cursor"]
if cursor is None:
break
check(seen == created, "chat list pages are wrong")
print("PASS: chat list pagination")
def test_unicode():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob, title="Чат 👋")
text = "Привет 👋 你好"
check(send(alice, chat["id"], text).json["text"] == text, "text changed on write")
history, _ = read_history(bob, chat["id"])
check(history[-1]["text"] == text, "text changed on read")
print("PASS: unicode text is stored as is")
def test_nul_character_is_stored():
name, title, text = "A\u0000B", "Chat\u0000title", "hello\u0000world"
body = {"username": "nul_" + uuid.uuid4().hex[:10], "display_name": name, "password": "pass\u0000word-123"}
user = call("POST", "/api/v1/users", 201, body=body).json
check(user["display_name"] == name, "display_name with U+0000 changed")
token = login(body["username"], body["password"]).json["token"]
check(call("GET", "/api/v1/users/me", token=token).json["display_name"] == name, "display_name changed on read")
chat = call("POST", "/api/v1/chats", 201, token=token, body={"title": title, "member_ids": [user["id"]]}).json
check(chat["title"] == title, "title with U+0000 changed")
check(call("GET", f"/api/v1/chats/{chat['id']}", token=token).json["title"] == title, "title changed on read")
sent = call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, token=token, body={"text": text},
headers={"Idempotency-Key": new_key()}).json
history = call("GET", f"/api/v1/chats/{chat['id']}/messages", token=token).json["items"]
check(sent["text"] == text and history[-1]["text"] == text, "text with U+0000 changed")
login("nul\u0000user", PASSWORD, expected=401)
print("PASS: strings with U+0000 are stored and returned as is")
def test_user_has_no_password():
body = {"username": "np_" + uuid.uuid4().hex[:10], "display_name": "No password", "password": PASSWORD}
user = call("POST", "/api/v1/users", 201, body=body).json
check(set(user) == {"id", "username", "display_name", "created_at"}, f"unexpected fields: {set(user)}")
print("PASS: user response has no password or hash")
def test_password_rules():
def register(password, expected):
body = {"username": "pw_" + uuid.uuid4().hex[:10], "display_name": "Password", "password": password}
call("POST", "/api/v1/users", expected, body=body)
register("x" * 11, 400)
register("x" * 129, 400)
register(" " * 12, 400)
register("x" * 12, 201)
register("я" * 128, 201)
print("PASS: password length 12..128, blank password is rejected")
def test_login_gives_token():
username = "lg_" + uuid.uuid4().hex[:10]
user = call("POST", "/api/v1/users", 201,
body={"username": username, "display_name": "Login", "password": PASSWORD}).json
reply = login(username, PASSWORD)
session = reply.json
check(session["token_type"] == "Bearer", "token_type must be Bearer")
check(session["user"] == user, "session user differs from registered user")
check(len(session["token"]) >= 43, "token is too short")
check(username not in session["token"] and user["id"] not in session["token"], "token is not opaque")
check(reply.headers.get("cache-control") == "no-store", "response with token must not be cached")
left = (parse_time(session["expires_at"]) - dt.datetime.now(dt.timezone.utc)).total_seconds()
check(290 < left <= 3600 + 5, f"unexpected session lifetime: {left:.0f} s")
me = call("GET", "/api/v1/users/me", token=session["token"]).json
check(me == user, "/users/me returned another user")
print("PASS: Basic login returns opaque Bearer token with expiry")
def test_wrong_password():
user = new_user("wp")
wrong = login(user["username"], "Wrong-password-000", expected=401)
unknown = login("nobody_" + uuid.uuid4().hex[:8], PASSWORD, expected=401)
check(wrong.headers["www-authenticate"].lower().startswith("basic"), "login 401 must ask for Basic")
check(wrong.json["error"]["message"] == unknown.json["error"]["message"], "different answers leak usernames")
print("PASS: wrong password and unknown user both return the same 401")
def test_malformed_basic():
no_colon = base64.b64encode(b"just_username").decode()
for header in (None, "Basic", "Basic !!!", "Basic " + no_colon, "Bearer something"):
headers = {} if header is None else {"Authorization": header}
call("POST", "/api/v1/auth/sessions", 401, headers=headers)
print("PASS: malformed Basic header returns 401")
def test_password_with_colon_and_unicode():
password = "пароль:с:двоеточием 👋"
user = new_user("colon", password=password)
call("GET", "/api/v1/users/me", token=user["token"])
print("PASS: password with colon and unicode works")
def test_bearer_required():
user = new_user("br")
for headers in ({}, {"Authorization": basic(user["username"], user["password"])},
{"X-User-Id": user["id"]}, {"Authorization": "Bearer " + "A" * 43},
{"Authorization": "Bearer"}, {"Authorization": "Token " + user["token"]}):
reply = call("GET", "/api/v1/users/me", 401, headers=headers)
check(reply.headers["www-authenticate"].lower().startswith("bearer"), "401 must ask for Bearer")
call("GET", "/api/v1/users/me", 200, headers={"Authorization": "bearer " + user["token"]})
print("PASS: business endpoints need Bearer; Basic and X-User-Id give 401")
def test_x_user_id_ignored():
alice, bob = new_user("alice"), new_user("bob")
me = call("GET", "/api/v1/users/me", token=alice["token"], headers={"X-User-Id": bob["id"]}).json
check(me["id"] == alice["id"], "X-User-Id changed the current user")
print("PASS: X-User-Id does not change the current user")
def test_auth_before_body():
alice = new_user("alice")
chat = new_chat(alice)
call("POST", f"/api/v1/chats/{chat['id']}/messages", 401, raw=b"not json")
call("GET", f"/api/v1/chats/{uuid.uuid4()}", 401)
print("PASS: 401 comes before 400 and 404")
def test_logout():
user = new_user("lo")
second = login(user["username"], user["password"]).json["token"]
call("DELETE", "/api/v1/auth/sessions/current", 204, token=user["token"])
call("GET", "/api/v1/users/me", 401, token=user["token"])
call("DELETE", "/api/v1/auth/sessions/current", 401, token=user["token"])
call("GET", "/api/v1/users/me", 200, token=second) # другая сессия того же пользователя жива
again = login(user["username"], user["password"]).json["token"]
check(again != user["token"], "new login must give a new token")
call("GET", "/api/v1/users/me", 200, token=again)
print("PASS: logout revokes only the current session")
if __name__ == "__main__":
run_tests([
test_duplicate_username,
test_invalid_json,
test_wrong_fields,
test_foreign_chat,
test_empty_message,
test_pagination,
test_empty_cursor,
test_chat_list_pagination,
test_unicode,
test_nul_character_is_stored,
test_user_has_no_password,
test_password_rules,
test_login_gives_token,
test_wrong_password,
test_malformed_basic,
test_password_with_colon_and_unicode,
test_bearer_required,
test_x_user_id_ignored,
test_auth_before_body,
test_logout,
])
+338
View File
@@ -0,0 +1,338 @@
"""Вложения через балансировщик: корректные файлы, лимиты, битые файлы, подмена MIME, доступ.
Только HTTP, Docker не нужен. Каждый негативный случай проверяет точный код ответа:
пользовательская ошибка не должна становиться 500.
"""
import hashlib
import http.client
import socket
import struct
import urllib.parse
import uuid
import zlib
import images
from common import BASE_URL, https_connection, tls_socket, call, check, new_chat, new_key, new_user, post_message, read_history, run_tests, upload
URL = urllib.parse.urlsplit(BASE_URL)
def setup():
alice, bob, eve = new_user("alice"), new_user("bob"), new_user("eve")
return alice, bob, eve, new_chat(alice, bob)
def sha(data):
return hashlib.sha256(data).hexdigest()
def check_error(reply, code):
check(reply.json["error"]["code"] == code, f"expected error code {code}, got {reply.json['error']['code']}")
def test_png_and_jpeg_roundtrip():
alice, bob, _, chat = setup()
for data, ctype, name in ((images.sample_png(), "image/png", "sample.png"),
(images.sample_jpeg(), "image/jpeg", "sample.jpg"),
(images.progressive_jpeg(), "image/jpeg", "progressive.jpg"),
(images.png(33, 17, interlace=1), "image/png", "interlaced.png"),
(images.png(1, 1, gray=True), "image/png", "1x1.png")):
att = upload(alice, chat["id"], data, ctype, name).json
check(att["status"] == "ready" and att["error_code"] is None, "not ready")
check([v["name"] for v in att["variants"]] == ["thumbnail", "crop", "optimized"], "lab5 variants missing")
check(att["sha256"] == sha(data) and att["size_bytes"] == len(data), "checksum/size differ")
check(att["content_type"] == ctype and att["filename"] == name, "metadata differs")
meta = call("GET", f"/api/v1/attachments/{att['id']}", 200, token=bob["token"]).json
check(meta == att, "GET metadata differs from POST response")
got = call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"])
check(got.data == data, "downloaded bytes differ")
check(got.headers["content-type"] == ctype, "wrong Content-Type on download")
check(got.headers.get("content-length") == str(len(data)), "wrong Content-Length")
check(got.headers.get("x-content-type-options") == "nosniff", "nosniff is missing")
print(f"{name}: {len(data)} bytes, sha256 {att['sha256'][:12]}..., downloaded by the other member, same bytes")
print("PASS: PNG, JPEG, progressive JPEG, interlaced PNG and 1x1 PNG are stored and returned byte for byte")
def test_size_limit_exact_boundary():
alice, _, _, chat = setup()
exact = images.png(64, 64, pad_to=images.MAX_UPLOAD_BYTES)
check(len(exact) == images.MAX_UPLOAD_BYTES, "fixture must be exactly 10 MiB")
att = upload(alice, chat["id"], exact).json
check(att["size_bytes"] == images.MAX_UPLOAD_BYTES and att["sha256"] == sha(exact), "10 MiB file changed")
print(f"exactly {len(exact)} bytes (10 MiB) -> 202, then ready")
over = images.png(64, 64, pad_to=images.MAX_UPLOAD_BYTES + 1)
reply = upload(alice, chat["id"], over, expected=413)
check_error(reply, "payload_too_large")
print(f"{len(over)} bytes (10 MiB + 1) with Content-Length -> 413 before reading the body")
print("PASS: the 10 MiB limit is exact")
def chunked_upload(user, chat_id, total, piece=64 * 1024):
"""Тело без Content-Length (Transfer-Encoding: chunked): сервер узнаёт размер только при чтении."""
conn = https_connection(timeout=60)
def body():
sent = 0
head = images.sample_png()[:64]
yield head
sent += len(head)
while sent < total:
part = bytes(min(piece, total - sent))
sent += len(part)
yield part
try:
conn.request("POST", f"/api/v1/chats/{chat_id}/attachments?filename=big.png", body=body(),
headers={"Content-Type": "image/png", "Authorization": "Bearer " + user["token"]},
encode_chunked=True)
reply = conn.getresponse()
return reply.status, reply.read()
finally:
conn.close()
def test_size_limit_streaming():
alice, _, _, chat = setup()
status, data = chunked_upload(alice, chat["id"], 12 * 1024 * 1024)
check(status == 413 and b"payload_too_large" in data, f"chunked 12 MiB: expected 413, got {status}")
print("12 MiB without Content-Length (chunked) -> 413 as soon as the 10 MiB limit is passed")
call("GET", "/health/ready", 200)
print("PASS: oversized streamed body is cut off, the API keeps working")
def test_pixel_limit():
alice, _, _, chat = setup()
at_limit = images.png(8000, 5000, gray=True) # ровно 40 000 000 пикселей
att = upload(alice, chat["id"], at_limit, filename="40mpx.png").json
print(f"8000x5000 = 40 000 000 pixels ({len(at_limit)} bytes compressed) -> 202, ready {att['id'][:8]}")
over = images.png(8001, 5000, gray=True)
check_error(upload(alice, chat["id"], over, filename="over.png", expected=413), "payload_too_large")
print(f"8001x5000 = 40 005 000 pixels ({len(over)} bytes) -> 413")
bomb = images.png(100_000, 100_000, idat=b"x\x9c\x03\x00\x00\x00\x00\x01")
check_error(upload(alice, chat["id"], bomb, filename="bomb.png", expected=413), "payload_too_large")
print(f"header claims 100000x100000 in {len(bomb)} bytes -> 413 from the header, nothing is decoded")
print("PASS: pixel limit is checked before decompression")
def test_damaged_images():
alice, _, _, chat = setup()
png, jpeg = images.sample_png(), images.sample_jpeg()
cases = [
("PNG cut in half", png[:len(png) // 2], "image/png"),
("PNG without IEND", png[:-12], "image/png"),
("PNG with a flipped byte in IDAT (CRC mismatch)", images.flip_byte(png, len(png) // 2), "image/png"),
("PNG with garbage after IEND", png + b"garbage", "image/png"),
("PNG signature only", png[:8], "image/png"),
("PNG with less pixel data than the header says", images.png(10, 10, idat=zlib.compress(b"\x00" * 5)), "image/png"),
("JPEG cut in half", jpeg[:len(jpeg) // 2], "image/jpeg"),
("JPEG header only", jpeg[:20], "image/jpeg"),
("random bytes", uuid.uuid4().bytes * 100, "image/png"),
("plain text", "это не картинка".encode(), "image/jpeg"),
]
for name, data, ctype in cases:
reply = upload(alice, chat["id"], data, ctype, "broken.bin", expected=415)
check_error(reply, "unsupported_media_type")
print(f"{name} ({len(data)} bytes, {ctype}) -> 415")
check_error(upload(alice, chat["id"], b"", expected=400), "invalid_request")
print("empty body -> 400")
print("PASS: damaged and foreign files are rejected with 415, never 500")
def test_png_chunk_semantics():
"""CRC у всех чанков верные, но содержимое нарушает спецификацию PNG -> 415, а не 201.
Регрессия: PNG 1x1, глубина 8, палитровый, PLTE из 771 байта (257 записей) раньше получал 201 ready,
хотя Pillow его отклоняет (invalid palette size).
"""
alice, bob, _, chat = setup()
from images import assemble, ihdr, zero_idat
pal = lambda entries: (b"PLTE", bytes(3 * entries))
idat_p = zero_idat(1, 1, 8, 1)
bad = [
("PLTE 771 bytes = 257 entries (review case)",
assemble(ihdr(1, 1, 8, 3), (b"PLTE", bytes(771)), (b"IDAT", zlib.compress(b"\0\0")))),
("PLTE length not a multiple of 3", assemble(ihdr(1, 1, 8, 3), (b"PLTE", bytes(4)), idat_p)),
("empty PLTE", assemble(ihdr(1, 1, 8, 3), (b"PLTE", b""), idat_p)),
("palette larger than bit depth allows (depth 1, 3 entries)",
assemble(ihdr(1, 1, 1, 3), pal(3), zero_idat(1, 1, 1, 1))),
("palette image without PLTE", assemble(ihdr(1, 1, 8, 3), idat_p)),
("PLTE in a grayscale image", assemble(ihdr(1, 1, 8, 0), pal(2), zero_idat(1, 1, 8, 1))),
("PLTE after IDAT", assemble(ihdr(1, 1, 8, 3), idat_p, pal(2))),
("two PLTE chunks", assemble(ihdr(1, 1, 8, 3), pal(2), pal(2), idat_p)),
("tRNS longer than the palette", assemble(ihdr(1, 1, 8, 3), pal(2), (b"tRNS", bytes(3)), idat_p)),
("tRNS before PLTE", assemble(ihdr(1, 1, 8, 3), (b"tRNS", bytes(1)), pal(2), idat_p)),
("tRNS of wrong size for RGB (4 bytes instead of 6)",
assemble(ihdr(1, 1, 8, 2), (b"tRNS", bytes(4)), zero_idat(1, 1, 8, 3))),
("tRNS in an image with alpha channel",
assemble(ihdr(1, 1, 8, 6), (b"tRNS", bytes(2)), zero_idat(1, 1, 8, 4))),
("IEND with data", assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"IEND", b"x"))),
("unknown critical chunk", assemble(ihdr(1, 1, 8, 2), (b"ABCD", b""), zero_idat(1, 1, 8, 3))),
("IDAT chunks not consecutive",
assemble(ihdr(1, 2, 8, 2), (b"IDAT", zero_idat(1, 2, 8, 3)[1][:5]), (b"tEXt", b"k\0v"),
(b"IDAT", zero_idat(1, 2, 8, 3)[1][5:]))),
("gAMA after IDAT", assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"gAMA", bytes(4)))),
("gAMA of 2 bytes instead of 4", assemble(ihdr(1, 1, 8, 2), (b"gAMA", bytes(2)), zero_idat(1, 1, 8, 3))),
("3 MiB metadata chunk before IDAT", assemble(ihdr(1, 1, 8, 2), (b"prVt", bytes(3 * 1024 * 1024)),
zero_idat(1, 1, 8, 3))),
("private chunk after IDAT", assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"prVt", bytes(100)))),
("animated PNG frame (fdAT)", assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"fdAT", bytes(10)))),
("tIME of 2 bytes instead of 7", assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"tIME", bytes(2)))),
("tEXt without keyword separator", assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"tEXt", b"nokey"))),
("zTXt with broken zlib after IDAT",
assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"zTXt", b"k\0\0garbage"))),
("zTXt text bomb: 50 MB of text in ~50 KB after IDAT",
assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"zTXt", b"k\0\0" + zlib.compress(bytes(50_000_000))))),
]
for name, data in bad:
check_error(upload(alice, chat["id"], data, filename="bad.png", expected=415), "unsupported_media_type")
print(f"{name} ({len(data)} bytes, valid CRCs) -> 415")
good = [
("palette 256 entries + tRNS + tEXt and tIME after IDAT",
assemble(ihdr(2, 2, 8, 3), pal(256), (b"tRNS", bytes(256)), zero_idat(2, 2, 8, 1),
(b"tEXt", b"Comment\0ok"), (b"tIME", struct.pack(">HBBBBB", 2026, 10, 22, 12, 0, 0)))),
("palette depth 2 with 4 entries", assemble(ihdr(3, 1, 2, 3), pal(4), zero_idat(3, 1, 2, 1))),
("RGB with 6-byte tRNS and gAMA", assemble(ihdr(1, 1, 8, 2), (b"gAMA", struct.pack(">I", 45455)),
(b"tRNS", bytes(6)), zero_idat(1, 1, 8, 3))),
("compressed zTXt (100 KB of text) and iTXt after IDAT",
assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"zTXt", b"Comment\0\0" + zlib.compress(b"a" * 100_000)),
(b"iTXt", b"Title\0\1\0ru\0\0" + zlib.compress("Привет".encode())))),
]
for name, data in good:
att = upload(alice, chat["id"], data, filename="good.png").json
got = call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"])
check(got.data == data, "valid PNG changed")
print(f"{name} -> 201, downloaded byte for byte")
print("PASS: chunk contents are checked, not only CRCs; valid PNGs with metadata are still accepted")
def test_mime_substitution():
alice, _, _, chat = setup()
cases = [
("PNG bytes sent as image/jpeg", images.sample_png(), "image/jpeg"),
("JPEG bytes sent as image/png", images.sample_jpeg(), "image/png"),
("GIF bytes sent as image/png", images.GIF, "image/png"),
("PNG sent as image/gif", images.sample_png(), "image/gif"),
("PNG sent as text/html", images.sample_png(), "text/html"),
("PNG sent as application/octet-stream", images.sample_png(), "application/octet-stream"),
("PNG sent as multipart/form-data", images.sample_png(), "multipart/form-data; boundary=x"),
]
for name, data, ctype in cases:
check_error(upload(alice, chat["id"], data, ctype, expected=415), "unsupported_media_type")
print(f"{name} -> 415")
att = upload(alice, chat["id"], images.sample_png(), "IMAGE/PNG; charset=binary").json
check(att["content_type"] == "image/png", "content type must be normalised")
print("PNG sent as 'IMAGE/PNG; charset=binary' -> 201, stored as image/png")
print("PASS: the type is taken from the content; a declared type that does not match is refused")
def test_filenames():
alice, _, _, chat = setup()
bad = ["../../etc/passwd", "a/b.png", "a\\b.png", "a\x00b.png", "line\nbreak.png", "tab\t.png",
"bell\x07.png", "del\x7f.png", "", " ", ".", "..", "x" * 256]
for name in bad:
check_error(upload(alice, chat["id"], images.sample_png(), filename=name, expected=400), "invalid_request")
print(f"{len(bad)} dangerous or invalid names (path, slashes, NUL, control characters, empty, 256 chars) -> 400")
check_error(upload(alice, chat["id"], images.sample_png(), filename=None, expected=400), "invalid_request")
print("no filename -> 400")
for name in ("фото отпуска 😀.png", "x" * 255, "..hidden.png", "a b%20c?.png"):
att = upload(alice, chat["id"], images.sample_png(), filename=name).json
check(att["filename"] == name, "display name changed")
got = call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=alice["token"])
check("filename*=UTF-8''" in got.headers.get("content-disposition", ""), "Content-Disposition is not encoded")
print("Unicode, 255 chars, leading dots, %20 and ? are kept as display names only")
print("PASS: filename never becomes a path; dangerous names are refused")
def test_access_control():
alice, bob, eve, chat = setup()
att = upload(alice, chat["id"], images.sample_png()).json
for suffix in ("", "/content"):
reply = call("GET", f"/api/v1/attachments/{att['id']}{suffix}", 404, token=eve["token"])
check_error(reply, "not_found")
call("GET", f"/api/v1/attachments/{att['id']}{suffix}", 401)
call("GET", f"/api/v1/attachments/{uuid.uuid4()}{suffix}", 404, token=alice["token"])
call("GET", f"/api/v1/attachments/not-a-uuid{suffix}", 400, token=alice["token"])
print("outsider -> 404 for metadata and bytes (same as a non-existent id); no token -> 401; bad UUID -> 400")
check_error(upload(eve, chat["id"], images.sample_png(), expected=404), "not_found")
check_error(upload(alice, str(uuid.uuid4()), images.sample_png(), expected=404), "not_found")
upload(None, chat["id"], images.sample_png(), expected=401)
print("upload into someone else's / unknown chat -> 404, without token -> 401")
call("GET", f"/api/v1/attachments/{att['id']}/content?variant=preview", 400, token=bob["token"])
for variant in ("original", "thumbnail", "crop", "optimized"):
call("GET", f"/api/v1/attachments/{att['id']}/content?variant={variant}", 200, token=bob["token"])
print("variant=preview -> 400 (not in the contract); original/thumbnail/crop/optimized -> 200 (lab5)")
print("PASS: only chat members can see an attachment")
def test_message_attachments():
alice, bob, eve, chat = setup()
first = upload(alice, chat["id"], images.sample_png()).json
second = upload(bob, chat["id"], images.sample_jpeg(), "image/jpeg", "b.jpg").json
msg = post_message(alice, chat["id"], "", [second["id"], first["id"]]).json
check(msg["attachment_ids"] == [second["id"], first["id"]] and msg["text"] == "", "order or text changed")
print("text='' with 2 attachments -> 201, order kept; any member may attach a file uploaded by another member")
plain = post_message(bob, chat["id"], "без вложений").json
check(plain["attachment_ids"] == [], "default attachment_ids must be []")
reused = post_message(bob, chat["id"], "то же вложение ещё раз", [first["id"]]).json
history, _ = read_history(bob, chat["id"])
check(history == [msg, plain, reused], "history differs from the confirmed messages")
print("history returns attachment_ids for every message, [] for a message without files; reuse is allowed")
other_chat = new_chat(alice, eve)
foreign = upload(alice, other_chat["id"], images.sample_png()).json
for ids, what in (([foreign["id"]], "attachment of another chat (author is a member of both)"),
([first["id"], foreign["id"]], "own + foreign attachment"),
([str(uuid.uuid4())], "unknown attachment_id")):
check_error(post_message(alice, chat["id"], "x", ids, expected=404), "not_found")
print(f"{what} -> 404")
check_error(post_message(eve, chat["id"], "x", [first["id"]], expected=404), "not_found")
print("outsider referencing an attachment of the chat -> 404")
for ids, text, what in (([first["id"], first["id"]], "x", "duplicate ids"),
([str(uuid.uuid4()) for _ in range(11)], "x", "11 ids"),
(["not-a-uuid"], "x", "bad UUID"),
([], "", "empty text without attachments"),
([], " ", "whitespace text without attachments")):
check_error(post_message(alice, chat["id"], text, ids, expected=400), "invalid_request")
print(f"{what} -> 400")
history_after, _ = read_history(bob, chat["id"])
check(history_after == history, "a rejected message was stored")
print("PASS: only attachments of the same chat can be linked; rejected requests change nothing")
def test_idempotency_with_attachments():
alice, bob, _, chat = setup()
att = upload(alice, chat["id"], images.sample_png()).json
other = upload(alice, chat["id"], images.sample_jpeg(), "image/jpeg").json
key = new_key()
first = post_message(alice, chat["id"], "фото", [att["id"]], key=key).json
again = post_message(alice, chat["id"], "фото", [att["id"]], key=key).json
check(again == first, "replay returned a different message")
check_error(post_message(alice, chat["id"], "фото", [other["id"]], key=key, expected=409), "conflict")
check_error(post_message(alice, chat["id"], "фото", [att["id"], other["id"]], key=key, expected=409), "conflict")
key2 = new_key()
plain = post_message(alice, chat["id"], "текст", None, key=key2).json
check(post_message(alice, chat["id"], "текст", [], key=key2).json == plain, "[] must equal a missing field")
history, _ = read_history(bob, chat["id"])
check(len(history) == 2, "replays created extra messages")
print("same key + same attachments -> same 201; other attachments -> 409; missing field == []")
print("PASS: Idempotency-Key covers attachment_ids")
def test_aborted_upload():
alice, _, _, chat = setup()
sock = tls_socket(timeout=10)
head = (f"POST /api/v1/chats/{chat['id']}/attachments?filename=cut.png HTTP/1.1\r\nHost: {URL.hostname}\r\n"
f"Authorization: Bearer {alice['token']}\r\nContent-Type: image/png\r\nContent-Length: 5000000\r\n\r\n")
sock.sendall(head.encode() + images.sample_png() + bytes(1_000_000))
sock.close() # клиент пропал на середине тела
print("sent 1.1 MB of a declared 5 MB body and closed the connection")
att = upload(alice, chat["id"], images.sample_png()).json
call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=alice["token"])
print("the API keeps serving uploads; nothing of the aborted request is visible "
"(DB/S3 side is checked by test_consistency.py)")
print("PASS: an interrupted upload is dropped")
if __name__ == "__main__":
run_tests([test_png_and_jpeg_roundtrip, test_size_limit_exact_boundary, test_size_limit_streaming,
test_pixel_limit, test_damaged_images, test_png_chunk_semantics, test_mime_substitution, test_filenames, test_access_control,
test_message_attachments, test_idempotency_with_attachments, test_aborted_upload])
+107
View File
@@ -0,0 +1,107 @@
from collections import Counter
import images
from common import instance_aliases, api_containers, call, check, new_chat, new_key, new_user, run_tests, send, upload
def test_requests_spread_over_replicas():
alice = new_user("alice")
replies = [call("GET", "/api/v1/users/me", 200, token=alice["token"]) for _ in range(20)]
served = Counter(reply.instance for reply in replies)
print(f"20 x GET /users/me with one token -> replicas: {dict(served)}")
check(all(reply.json["id"] == alice["id"] for reply in replies), "another user returned")
check(len(served) >= 2, "all requests went to one replica: balancing does not work")
print("PASS: one session works on every replica, no second login (sessions are shared in Redis)")
def test_write_on_one_read_on_other():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
sent = send(alice, chat["id"], "written on one replica")
readers = set()
for _ in range(6):
reply = call("GET", f"/api/v1/chats/{chat['id']}/messages", 200, token=bob["token"])
check(sent.json in reply.json["items"], "confirmed message is not visible on another replica")
readers.add(reply.instance)
print(f"message written by {sent.instance}; read back by {sorted(readers)}")
check(readers - {sent.instance}, "no read went to another replica")
print("PASS: a message written via one replica is read right away via another (shared PostgreSQL)")
def test_logout_seen_by_all_replicas():
user = new_user("logout")
out = call("DELETE", "/api/v1/auth/sessions/current", 204, token=user["token"])
after = [call("GET", "/api/v1/users/me", 401, token=user["token"]).instance for _ in range(10)]
print(f"logout on {out.instance}; old token then rejected by {sorted(set(after))}")
check(len(set(after)) >= 2, "only one replica answered")
print("PASS: logout on one replica revokes the session on all of them")
def test_idempotent_retry_on_other_replica():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
key = new_key()
first = send(alice, chat["id"], "retry me", key=key)
for _ in range(10): # round robin: следующий запрос уйдёт на другую реплику
retry = send(alice, chat["id"], "retry me", key=key)
if retry.instance != first.instance:
break
print(f"first POST on {first.instance} -> 201 {first.json['id']}; "
f"same key on {retry.instance} -> {retry.status} {retry.json['id']}")
check(retry.instance != first.instance, "retry never reached another replica")
check(retry.json == first.json, "retry on another replica returned a different message")
items = call("GET", f"/api/v1/chats/{chat['id']}/messages", 200, token=bob["token"]).json["items"]
check([m["text"] for m in items].count("retry me") == 1, "retry created a duplicate")
print("PASS: Idempotency-Key is shared: a retry through another replica returns the same message")
def test_attachment_on_other_replica():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
data = images.sample_png()
sent = upload(alice, chat["id"], data)
readers = set()
for _ in range(6):
reply = call("GET", f"/api/v1/attachments/{sent.json['id']}/content", 200, token=bob["token"])
check(reply.data == data, "another replica returned different bytes")
readers.add(reply.instance)
print(f"file uploaded via {sent.instance}; downloaded byte for byte via {sorted(readers)}")
check(readers - {sent.instance}, "no download went to another replica")
print("PASS: a file uploaded through one replica is downloaded through another (shared S3, nothing local)")
def test_instance_header_everywhere():
containers = api_containers()
alice, eve = new_user("alice"), new_user("eve")
chat = new_chat(alice)
replies = [
call("GET", "/health/live", 200),
call("GET", "/health/ready", 200),
send(alice, chat["id"], "hello"),
call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, token=alice["token"], body={"text": "no key"}),
call("GET", "/api/v1/users/me", 401),
call("GET", f"/api/v1/chats/{chat['id']}", 404, token=eve["token"]),
call("POST", "/api/v1/users", 409,
body={"username": alice["username"], "display_name": "x", "password": alice["password"]}),
]
aliases = instance_aliases(containers) # lab7: X-Instance-Id — случайный alias, не ID контейнера
for reply in replies: # call() уже проверил, что заголовок есть; здесь — что это alias настоящей реплики
check(reply.instance in aliases.values(),
f"X-Instance-Id {reply.instance} is not the alias of a running api container")
check(not any(container.startswith(reply.instance) for container in containers),
"X-Instance-Id must not reveal the container ID")
print(f"statuses {[r.status for r in replies]}: every answer has X-Instance-Id of a running replica "
f"{sorted({r.instance for r in replies})}; api containers -> aliases: "
f"{ {c[:12]: a for c, a in aliases.items()} }")
print("PASS: X-Instance-Id is in every response and points to a real container")
if __name__ == "__main__":
run_tests([
test_requests_spread_over_replicas,
test_write_on_one_read_on_other,
test_logout_seen_by_all_replicas,
test_idempotent_retry_on_other_replica,
test_attachment_on_other_replica,
test_instance_header_everywhere,
])
+286
View File
@@ -0,0 +1,286 @@
"""Согласованность PostgreSQL и S3 при отказах; работа janitor (компенсация и очистка).
Нужен запущенный стенд из compose.yaml. Тест останавливает/замораживает S3 (`docker compose stop|pause s3`),
выполняет код приложения внутри контейнера api (имитация падения между S3 PUT и COMMIT) и запускает
janitor вручную. Данные синтетические, volumes не удаляются.
python student-tests/test_consistency.py [s3|crash|orphan|aborted|all]
"""
import json
import socket
import sys
import time
import urllib.parse
import images
from common import (BASE_URL, tls_socket, app_python, call, check, compose, compose_output, docker, janitor, new_chat,
new_user, post_message, run_tests, sql_value, upload, wait_ready)
URL = urllib.parse.urlsplit(BASE_URL)
# lab7: у каждого сервиса свой S3-ключ с правами по prefix — проверки выполняются в контейнере с нужным правом
# (запись staging — api, чтение staging — worker, листинг bucket — janitor).
# Выполняется внутри контейнера api: настоящие attachments.store / storage / db, но enqueue_upload
# (lab5: UPDATE ... state='queued' + задание + outbox, COMMIT) падает — как если бы реплика умерла
# сразу после PUT в staging, до фиксации задания.
CRASH_AFTER_PUT = r'''
import json, struct, sys, tempfile, zlib
from uuid import UUID
import attachments, db, storage, uploads
chat_id, owner_id = UUID(sys.argv[1]), UUID(sys.argv[2])
def chunk(k, d): return struct.pack(">I", len(d)) + k + d + struct.pack(">I", zlib.crc32(k + d))
data = (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 4, 4, 8, 0, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(b"\x00\x80\x80\x80\x80" * 4)) + chunk(b"IEND", b""))
f = tempfile.SpooledTemporaryFile(); f.write(data)
import hashlib
upload = uploads.Upload(f, len(data), hashlib.sha256(data).hexdigest())
image = uploads.inspect(upload, "image/png")
created = {}
real_intent = db.create_upload_intent
def remember(attachment_id, *args):
created["id"], created["key"] = str(attachment_id), args[-1]
return real_intent(attachment_id, *args)
def crash(attachment_id, *args):
raise RuntimeError("simulated crash between S3 PUT and DB COMMIT")
db.create_upload_intent = remember
db.enqueue_upload = crash
db.pool.open()
try:
attachments.store(chat_id, owner_id, "crash.png", upload, image)
outcome = "stored"
except RuntimeError as exc:
outcome = str(exc)
print(json.dumps({"outcome": outcome, "attachment_id": created["id"], "object_key": created["key"]}))
'''
OBJECT_EXISTS = r'''
import json, sys, storage
print(json.dumps({"exists": storage.exists(sys.argv[1])}))
'''
PUT_ORPHAN = r'''
import hashlib, io, json, uuid, storage
data = b"orphan object without a row in PostgreSQL"
key = storage.new_key(uuid.uuid4().hex)
storage.put(key, io.BytesIO(data), len(data), "image/png", hashlib.sha256(data).hexdigest())
print(json.dumps({"key": key}))
'''
DELETE_OBJECT = r'''
import json, sys, storage
storage.delete(sys.argv[1]); print(json.dumps({"deleted": sys.argv[1]}))
'''
COUNT_OBJECTS = r'''
import json, storage
print(json.dumps({"objects": sum(1 for prefix in storage.ALL_PREFIXES for _ in storage.list_objects(prefix))}))
'''
def last_json(output):
return json.loads(output.splitlines()[-1])
def object_exists(key):
# lab7: ключ api не читает staging/ (только пишет) — проверяем изнутри worker, которому чтение staging/ нужно
return last_json(app_python(OBJECT_EXISTS, key, service="worker"))["exists"]
def backdate(where):
sql_value(f"UPDATE attachments SET created_at = created_at - interval '2 hours' WHERE {where}")
def uploading_rows(chat_id):
return int(sql_value(f"SELECT count(*) FROM attachments WHERE chat_id = '{chat_id}' AND state = 'uploading'"))
def wait_download(user, att, seconds=60):
deadline = time.monotonic() + seconds
while True:
reply = call("GET", f"/api/v1/attachments/{att['id']}/content", (200, 503), token=user["token"])
if reply.status == 200:
return reply
check(time.monotonic() < deadline, "download did not recover after S3 start")
time.sleep(1)
def s3_outage(stop_action, start_action, label):
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
data = images.sample_png()
att = upload(alice, chat["id"], data).json
before = uploading_rows(chat["id"])
print(f"--- S3 {label}: docker compose {stop_action} s3")
compose(stop_action, "s3")
try:
started = time.monotonic()
reply = upload(alice, chat["id"], data, expected=503)
ms = (time.monotonic() - started) * 1000
check(reply.json["error"]["code"] == "unavailable", "expected code unavailable")
body = reply.data.decode().lower()
check(not any(word in body for word in ("seaweed", "bucket", "s3:8333", "originals/", "traceback")),
"error leaks storage details")
print(f"upload -> 503 unavailable in {ms:.0f} ms, no storage details in the body")
reply = call("GET", f"/api/v1/attachments/{att['id']}/content", 503, token=bob["token"])
print("download of an existing file -> 503")
meta = call("GET", f"/api/v1/attachments/{att['id']}", 200, token=bob["token"]).json
check(meta["sha256"] == att["sha256"], "metadata changed")
post_message(alice, chat["id"], "текст без файла")
post_message(alice, chat["id"], "", [att["id"]])
call("GET", "/health/ready", 200)
print("metadata, messages (also with an already stored attachment) and /health/ready keep working: "
"S3 is needed only for file bytes")
after = uploading_rows(chat["id"])
print(f"uploading rows of this chat: before {before}, after the failed upload {after} "
"(kept as a pointer for janitor if the rollback could not reach S3); not visible through the API")
finally:
print(f"docker compose {start_action} s3")
compose(start_action, "s3")
got = wait_download(bob, att)
check(got.data == data, "file changed after S3 recovery")
print("after S3 recovery the old file downloads byte for byte")
started = time.monotonic()
while True:
# SeaweedFS после рестарта отдаёт чтение раньше записи: мастер «прогревает» топологию
# (/dir/assign -> "master is warming up") ещё ~15 c после healthz. Ждём первую успешную запись.
reply = upload(alice, chat["id"], data, expected=(202, 503))
if reply.status == 202:
break
check(time.monotonic() - started < 90, "upload did not recover after S3 start")
time.sleep(1)
print(f"new upload -> 202 ({time.monotonic() - started:.1f} s after the old file became readable)")
leftover = uploading_rows(chat["id"])
if leftover:
backdate(f"chat_id = '{chat['id']}' AND state = 'uploading'")
report = janitor()
print(f"janitor after grace period: {json.dumps(report)}")
check(uploading_rows(chat["id"]) == 0, "abandoned upload rows remain")
print(f"PASS: S3 {label} -> 503 for file operations only, no visible half-uploads, everything cleaned up")
def test_s3_stopped():
s3_outage("stop", "start", "stopped (connection refused / name not resolved)")
def test_s3_frozen():
s3_outage("pause", "unpause", "frozen (no answer, timeouts)")
def test_crash_between_s3_and_db():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
ready = upload(alice, chat["id"], images.sample_png()).json
result = last_json(app_python(CRASH_AFTER_PUT, chat["id"], alice["id"]))
check(result["outcome"].startswith("simulated crash"), f"unexpected outcome {result['outcome']}")
att_id, key = result["attachment_id"], result["object_key"]
state = sql_value(f"SELECT state FROM attachments WHERE id = '{att_id}'")
check(state == "uploading" and object_exists(result["object_key"]), "expected an uploading row and an object in S3")
print(f"crash after S3 PUT: row {att_id[:8]} state={state}, object {key} exists in S3")
call("GET", f"/api/v1/attachments/{att_id}", 404, token=alice["token"])
call("GET", f"/api/v1/attachments/{att_id}/content", 404, token=alice["token"])
post_message(alice, chat["id"], "x", [att_id], expected=404)
print("the half-written attachment is invisible: GET -> 404, attach to a message -> 404")
report = janitor()
check(sql_value(f"SELECT count(*) FROM attachments WHERE id = '{att_id}'") == "1" and object_exists(key),
"fresh upload was deleted inside the grace period")
print(f"janitor with default grace ({report['grace_seconds']} s) right away: {json.dumps(report)} -> "
"fresh row and object are kept (the upload might still be running)")
backdate(f"id = '{att_id}'")
report = janitor("--dry-run")
check(report["stale_uploads"] >= 1 and report["stale_uploads_deleted"] == 0, "dry run must only report")
check(sql_value(f"SELECT count(*) FROM attachments WHERE id = '{att_id}'") == "1", "dry run deleted a row")
print(f"row made 2 h old; janitor --dry-run: {json.dumps(report)} -> nothing deleted")
report = janitor()
check(report["stale_uploads_deleted"] >= 1, "janitor did not reclaim the abandoned upload")
check(sql_value(f"SELECT count(*) FROM attachments WHERE id = '{att_id}'") == "0", "row still exists")
check(not object_exists(key), "object still exists")
print(f"janitor: {json.dumps(report)} -> row and object deleted")
report = janitor()
print(f"janitor again: {json.dumps(report)} -> idempotent")
got = call("GET", f"/api/v1/attachments/{ready['id']}/content", 200, token=bob["token"])
check(got.data == images.sample_png(), "ready attachment damaged by cleanup")
print("the ready attachment of the same chat is untouched")
print("PASS: S3 written but DB not committed -> invisible, reclaimed by janitor only after the grace period")
def test_orphan_objects():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
ready = upload(alice, chat["id"], images.sample_png()).json
key = last_json(app_python(PUT_ORPHAN))["key"]
print(f"object {key} put into the bucket without a row in PostgreSQL")
# Короткий grace только для теста: janitor требует grace >= 2 x UPLOAD_TIMEOUT_SECONDS, поэтому задаём 1 с.
short = {"UPLOAD_TIMEOUT_SECONDS": "1"}
report = janitor("--grace-seconds", "3", env=short)
check(object_exists(key), "fresh orphan deleted inside grace period")
print(f"janitor --grace-seconds 3 immediately: {json.dumps(report)} -> fresh object kept")
time.sleep(4)
report = janitor("--grace-seconds", "3", "--dry-run", env=short)
check(report["orphan_objects"] >= 1 and report["orphan_objects_deleted"] == 0 and object_exists(key),
"dry run must report and keep the orphan")
print(f"after 4 s, --dry-run: {json.dumps(report)} -> reported, kept")
report = janitor("--grace-seconds", "3", env=short)
check(report["orphan_objects_deleted"] >= 1 and not object_exists(key), "orphan not deleted")
print(f"janitor: {json.dumps(report)} -> orphan deleted")
got = call("GET", f"/api/v1/attachments/{ready['id']}/content", 200, token=bob["token"])
check(got.data == images.sample_png(), "ready attachment was deleted with orphans")
print("ready attachments older than the grace period are untouched (they have rows)")
victim = upload(alice, chat["id"], images.sample_png(), filename="victim.png").json
victim_key = sql_value(f"SELECT object_key FROM attachments WHERE id = '{victim['id']}'")
app_python(DELETE_OBJECT, victim_key, service="janitor") # lab7: удалять готовые объекты может только janitor
report = janitor("--grace-seconds", "3", env=short)
check(report["missing_objects"] >= 1, "missing object not reported")
check(sql_value(f"SELECT state FROM attachments WHERE id = '{victim['id']}'") == "ready", "row was deleted")
reply = call("GET", f"/api/v1/attachments/{victim['id']}/content", 503, token=bob["token"])
print(f"object of a ready attachment deleted behind the API's back: janitor reports missing_objects="
f"{report['missing_objects']} and keeps the row; download -> {reply.status} (not 500)")
print("PASS: orphans are found and deleted only after the grace period; missing objects are reported")
def api_tmp_files():
counts = {}
for container in compose_output("ps", "-q", "api").split():
counts[container[:12]] = int(docker("exec", container, "sh", "-c", "ls -A /tmp/uploads | wc -l") or 0)
return counts
def test_aborted_upload_leaves_nothing():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
objects = last_json(app_python(COUNT_OBJECTS, service="janitor"))["objects"]
rows = int(sql_value("SELECT count(*) FROM attachments"))
for sent in (100_000, 3_000_000):
sock = tls_socket(timeout=10)
head = (f"POST /api/v1/chats/{chat['id']}/attachments?filename=cut.png HTTP/1.1\r\nHost: x\r\n"
f"Authorization: Bearer {alice['token']}\r\nContent-Type: image/png\r\n"
f"Content-Length: 9000000\r\n\r\n")
sock.sendall(head.encode() + images.sample_png() + bytes(sent))
sock.close()
print(f"declared 9 000 000 bytes, sent {sent + len(images.sample_png())}, closed the connection")
time.sleep(2)
check(int(sql_value("SELECT count(*) FROM attachments")) == rows, "an aborted upload left a row")
check(last_json(app_python(COUNT_OBJECTS, service="janitor"))["objects"] == objects, "an aborted upload left an S3 object")
print(f"rows in attachments: {rows} -> {rows}; objects in bucket: {objects} -> {objects}")
tmp = api_tmp_files()
check(all(n == 0 for n in tmp.values()), f"temporary files left: {tmp}")
print(f"temporary upload files in api containers: {tmp} (removed when the request ends)")
for container in compose_output("ps", "-q", "api").split():
mounts = docker("inspect", "-f", "{{json .Mounts}}", container)
# файловые secrets и (lab7) сертификаты монтируются read-only в /run/... — это не хранилище данных
storage = [m for m in json.loads(mounts)
if not (m.get("Destination", "").startswith("/run/") and m.get("RW") is False)]
check(storage == [], f"api must not have volumes: originals live only in S3, got {storage}")
print("api containers have no volumes: the original is never stored locally")
print("PASS: an interrupted upload leaves no row, no object and no local file")
if __name__ == "__main__":
target = sys.argv[1] if len(sys.argv) > 1 else "all"
groups = {"s3": [test_s3_stopped, test_s3_frozen], "crash": [test_crash_between_s3_and_db],
"orphan": [test_orphan_objects], "aborted": [test_aborted_upload_leaves_nothing]}
groups["all"] = groups["aborted"] + groups["crash"] + groups["orphan"] + groups["s3"]
check(target in groups, "usage: python student-tests/test_consistency.py [s3|crash|orphan|aborted|all]")
wait_ready()
run_tests(groups[target])
+101
View File
@@ -0,0 +1,101 @@
import time
import uuid
from common import call, check, compose_output, new_user, psql, run_tests
def sql_value(sql):
code, output, error = psql(sql)
check(code == 0, f"psql failed: {error}")
return output
def test_create_chat_rolls_back():
alice = new_user("rollback")
title = "rollback-" + uuid.uuid4().hex[:8]
inserted_before = int(sql_value("SELECT n_tup_ins FROM pg_stat_user_tables WHERE relname = 'chats'"))
call("POST", "/api/v1/chats", 400, token=alice["token"],
body={"title": title, "member_ids": [alice["id"], str(uuid.uuid4())]})
left = sql_value(f"SELECT count(*) FROM chats WHERE title = '{title}'")
orphans = sql_value("SELECT count(*) FROM chats c WHERE NOT EXISTS "
"(SELECT 1 FROM chat_members m WHERE m.chat_id = c.id)")
inserted_after = inserted_before
deadline = time.monotonic() + 15
while inserted_after == inserted_before and time.monotonic() < deadline:
time.sleep(0.5)
inserted_after = int(sql_value("SELECT n_tup_ins FROM pg_stat_user_tables WHERE relname = 'chats'"))
print(f"chat with unknown member -> 400; rows with this title: {left}; chats without members: {orphans}; "
f"chats insert counter: {inserted_before} -> {inserted_after}")
check(left == "0" and orphans == "0", "chat row survived the failed transaction")
check(inserted_after > inserted_before, "the chat row was never inserted, rollback is not shown")
print("PASS: chat row was inserted and then rolled back together with members")
def test_message_needs_membership_in_db():
code, _, error = psql("INSERT INTO messages (id, chat_id, sender_id, text) "
f"VALUES ('{uuid.uuid4()}', '{uuid.uuid4()}', '{uuid.uuid4()}', convert_to('direct insert', 'UTF8'))")
print(f"direct INSERT of a message from a non-member -> exit code {code}: {error.splitlines()[0] if error else ''}")
check(code != 0 and "foreign key" in error, "database accepted a message from a non-member")
print("PASS: the database itself rejects a message from a non-member")
def test_password_is_argon2id():
user = new_user("hash")
stored = sql_value(f"SELECT password_hash FROM users WHERE username = '{user['username']}'")
print(f"stored password: {stored[:31]}... (length {len(stored)})")
check(stored.startswith("$argon2id$") and user["password"] not in stored, "password is not an Argon2id hash")
print("PASS: password is stored as Argon2id hash")
def test_unique_username_constraint():
constraint = sql_value("SELECT pg_get_constraintdef(oid) FROM pg_constraint "
"WHERE conrelid = 'users'::regclass AND contype = 'u'")
print(f"unique constraint on users: {constraint}")
check(constraint == "UNIQUE (username)", "no unique constraint on username")
print("PASS: username is unique in the database")
def test_migrations_are_not_repeated():
versions = sql_value("SELECT string_agg(version, ',' ORDER BY version) FROM schema_migrations")
print(f"applied migrations: {versions}; running the migrate service once more")
output = compose_output("run", "--rm", "--no-deps", "-T", "migrate")
again = sql_value("SELECT string_agg(version, ',' ORDER BY version) FROM schema_migrations")
last_log = [line for line in output.splitlines() if "Migrations applied" in line][-1]
print(f"after the second run: {again}; log: {last_log.split('messenger.db: ')[-1]}")
check(again == versions and "none" in last_log, "migrations were applied again")
print("PASS: migrations are applied once, a repeated run does nothing")
def test_replicas_do_not_migrate():
"""lab3: миграции применяет только сервис migrate, API-реплики лишь проверяют схему."""
logs = compose_output("logs", "api").splitlines()
checked = [line for line in logs if "Schema is up to date" in line]
migrated = [line for line in logs if "Migrations applied" in line]
migrate_exit = compose_output("ps", "-a", "--format", "{{.Status}}", "migrate").strip()
print(f"api replicas that checked the schema at start: {len(checked)}; api log lines 'Migrations applied': "
f"{len(migrated)}; migrate service: {migrate_exit}")
check(checked and not migrated, "api replicas must not apply migrations")
check(migrate_exit.startswith("Exited (0)"), "migrate service must finish with exit code 0")
print("PASS: only the migrate service applies migrations, replicas wait for the schema")
def test_idempotency_key_is_unique_in_db():
constraint = sql_value("SELECT pg_get_constraintdef(oid) FROM pg_constraint "
"WHERE conname = 'messages_idempotency_key'")
print(f"unique constraint for Idempotency-Key: {constraint}")
check(constraint == "UNIQUE (chat_id, sender_id, idempotency_key)", "no unique constraint for idempotency keys")
print("PASS: one message per (chat, sender, Idempotency-Key) is enforced by the database")
if __name__ == "__main__":
run_tests([
test_create_chat_rolls_back,
test_message_needs_membership_in_db,
test_password_is_argon2id,
test_unique_username_constraint,
test_migrations_are_not_repeated,
test_replicas_do_not_migrate,
test_idempotency_key_is_unique_in_db,
])
+57
View File
@@ -0,0 +1,57 @@
import datetime as dt
import os
import time
from common import call, check, compose, login, new_user, redis_cli, run_tests, session_key, wait_ready
SHORT_TTL = 2
def restart_api(ttl=None):
env = dict(os.environ)
if ttl is None:
env.pop("SESSION_TTL_SECONDS", None) # значение снова из .env
else:
env["SESSION_TTL_SECONDS"] = str(ttl)
compose("up", "-d", "--no-deps", "--wait", "api", env=env)
wait_ready()
def seconds_left(expires_at):
moment = dt.datetime.fromisoformat(expires_at.replace("Z", "+00:00"))
return (moment - dt.datetime.now(dt.timezone.utc)).total_seconds()
def test_session_expires():
print(f"recreating api with SESSION_TTL_SECONDS={SHORT_TTL}")
restart_api(SHORT_TTL)
try:
user = new_user("ttl")
session = login(user["username"], user["password"]).json
token = session["token"]
left = seconds_left(session["expires_at"])
print(f"session issued, expires in {left:.2f} s; Redis TTL of the key: "
f"{redis_cli('pttl', session_key(token))} ms")
check(0 < left <= SHORT_TTL + 0.5, "short TTL instance must issue ~2 second sessions")
call("GET", "/api/v1/users/me", 200, token=token)
print("before expiry: GET /users/me -> 200")
time.sleep(max(0.0, seconds_left(session["expires_at"])) + 1.0)
call("GET", "/api/v1/users/me", 401, token=token)
exists = redis_cli("exists", session_key(token))
print(f"after expiry: GET /users/me -> 401; key exists in Redis: {exists}")
check(exists == "0", "Redis must delete the expired session key")
finally:
print("recreating api with SESSION_TTL_SECONDS from .env")
restart_api()
user = new_user("ttl_back")
left = seconds_left(login(user["username"], user["password"]).json["expires_at"])
print(f"normal API again: new session expires in {left:.0f} s")
check(left > 300, "normal TTL was not restored")
print("PASS: session expires after SESSION_TTL_SECONDS and is rejected with 401")
if __name__ == "__main__":
run_tests([test_session_expires])
+110
View File
@@ -0,0 +1,110 @@
import sys
import time
import uuid
from common import PASSWORD, basic, call, check, compose, new_chat, new_key, new_user, read_history, run_tests, send, wait_ready
FAKE_TOKEN = "A" * 43
def timed(method, path, expected, **kwargs):
started = time.monotonic()
reply = call(method, path, expected, **kwargs)
return reply, (time.monotonic() - started) * 1000
def prepare():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
before = send(alice, chat["id"], "confirmed before outage").json
return alice, bob, chat, before
def recovered(alice, chat, before):
wait_ready()
history, _ = read_history(alice, chat["id"])
check(before in history, "message confirmed before the outage is lost or changed")
call("GET", "/api/v1/users/me", 200, token=alice["token"])
print("after start: the old token works, confirmed messages are in place")
def test_redis_down():
alice, bob, chat, before = prepare()
print("stopping redis")
compose("stop", "redis")
try:
call("GET", "/health/live", 200)
_, ms = timed("GET", "/health/ready", 503)
print(f"/health/live -> 200, /health/ready -> 503 ({ms:.0f} ms)")
reply, ms = timed("GET", "/api/v1/users/me", 503, token=alice["token"])
check(reply.json["error"]["code"] == "unavailable", "expected code unavailable")
print(f"valid token: GET /users/me -> 503 unavailable ({ms:.0f} ms), session cannot be checked")
call("GET", "/api/v1/chats", 503, token=FAKE_TOKEN)
print("unknown token -> 503, not 200: nobody is trusted without a check")
call("GET", "/api/v1/chats", 401)
print("no token -> 401")
call("POST", "/api/v1/auth/sessions", 503, headers={"Authorization": basic(alice["username"], PASSWORD)})
print("login -> 503: there is nowhere to store the session")
call("POST", "/api/v1/users", 201,
body={"username": "rd_" + uuid.uuid4().hex[:10], "display_name": "x", "password": PASSWORD})
print("registration -> 201: it needs only PostgreSQL")
finally:
print("starting redis")
compose("start", "redis")
recovered(alice, chat, before)
print("PASS: Redis outage gives 503 and does not let anyone in without a session check")
def test_redis_crash():
alice = new_user("crash")
print("killing redis with SIGKILL (docker compose kill redis): no graceful shutdown")
compose("kill", "redis")
try:
# Обычно 503; 200 возможен, если Docker уже успел поднять Redis по restart policy.
status = call("GET", "/api/v1/users/me", (503, 200), token=alice["token"]).status
print(f"right after the crash: GET /users/me -> {status}")
finally:
print("starting redis")
compose("start", "redis")
wait_ready()
call("GET", "/api/v1/users/me", 200, token=alice["token"])
print("after start: the session issued before the crash still works (AOF, appendfsync always)")
print("PASS: sessions survive a Redis crash, not only a clean restart")
def test_postgres_down():
alice, bob, chat, before = prepare()
print("stopping postgres")
compose("stop", "postgres")
try:
call("GET", "/health/live", 200)
_, ms = timed("GET", "/health/ready", 503)
print(f"/health/live -> 200, /health/ready -> 503 ({ms:.0f} ms)")
for method, path, body in (("GET", "/api/v1/users/me", None),
("GET", "/api/v1/chats", None),
("GET", f"/api/v1/chats/{chat['id']}/messages", None),
("POST", f"/api/v1/chats/{chat['id']}/messages", {"text": "will not be saved"})):
reply = call(method, path, 503, token=alice["token"], body=body, headers={"Idempotency-Key": new_key()})
check(reply.json["error"]["code"] == "unavailable", "expected code unavailable")
check("postgres" not in reply.data.decode().lower(), "error must not show database details")
print("valid token: users/me, chats, history, new message -> 503 unavailable, no details")
call("GET", "/api/v1/chats", 401)
call("GET", "/api/v1/chats", 401, token=FAKE_TOKEN)
print("no token -> 401, unknown token -> 401: anonymous users are not let in")
call("POST", "/api/v1/auth/sessions", 503, headers={"Authorization": basic(alice["username"], PASSWORD)})
call("POST", "/api/v1/users", 503,
body={"username": "pd_" + uuid.uuid4().hex[:10], "display_name": "x", "password": PASSWORD})
print("login -> 503, registration -> 503")
finally:
print("starting postgres")
compose("start", "postgres")
recovered(alice, chat, before)
print("PASS: PostgreSQL outage gives limited 503 errors and keeps anonymous users out")
if __name__ == "__main__":
target = sys.argv[1] if len(sys.argv) > 1 else "all"
tests = {"redis": [test_redis_down, test_redis_crash], "postgres": [test_postgres_down],
"all": [test_redis_down, test_redis_crash, test_postgres_down]}
check(target in tests, "usage: python student-tests/test_failures.py [redis|postgres]")
run_tests(tests[target])
+174
View File
@@ -0,0 +1,174 @@
import json
import socket
import threading
import time
import urllib.parse
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from common import BASE_URL, tls_socket, call, check, new_chat, new_key, new_user, read_history, run_tests, send
PARALLEL = 20
def post_raw(user, chat_id, raw, key):
"""POST с телом «как есть» (bytes) — чтобы проверить другой порядок ключей и пробелы."""
return call("POST", f"/api/v1/chats/{chat_id}/messages", (201, 409, 400), token=user["token"],
raw=raw, headers={"Idempotency-Key": key})
def texts_in(user, chat_id):
history, _ = read_history(user, chat_id)
return [message["text"] for message in history]
def test_replay_returns_same_message():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
key = new_key()
first = send(alice, chat["id"], "Привет 👋", key=key)
# То же JSON-значение, записанное иначе: пробелы и \u-экранирование.
same = post_raw(alice, chat["id"], b'{ "text" : "\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442 \\ud83d\\udc4b" }', key)
again = send(alice, chat["id"], "Привет 👋", key=key)
print(f"first -> {first.status}; same JSON written differently -> {same.status}; plain retry -> {again.status}")
check(same.status == 201 and same.json == first.json and again.json == first.json,
"retry must return the original 201 and the same message")
check(texts_in(bob, chat["id"]).count("Привет 👋") == 1, "retry created a duplicate")
print("PASS: a retry with the same key returns the original 201 and message, no duplicate")
def test_same_key_parallel_through_replicas():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
key = new_key()
barrier = threading.Barrier(PARALLEL)
def post(_):
barrier.wait() # все запросы стартуют одновременно
return send(alice, chat["id"], "one message for 20 requests", key=key)
with ThreadPoolExecutor(max_workers=PARALLEL) as pool:
replies = list(pool.map(post, range(PARALLEL)))
bodies = {json.dumps(reply.json, sort_keys=True) for reply in replies}
served = Counter(reply.instance for reply in replies)
count = texts_in(bob, chat["id"]).count("one message for 20 requests")
print(f"{PARALLEL} parallel POSTs with one key: statuses {dict(Counter(r.status for r in replies))}, "
f"replicas {dict(served)}, different bodies in answers: {len(bodies)}, messages in history: {count}")
check(len(served) >= 2, "requests did not go through different replicas")
check(len(bodies) == 1 and count == 1, "parallel retries created more than one message")
print("PASS: parallel requests with one key through different replicas create exactly one message")
def test_same_key_different_bodies_parallel():
alice = new_user("alice")
chat = new_chat(alice)
key = new_key()
barrier = threading.Barrier(PARALLEL)
def post(index):
text = "body A" if index % 2 == 0 else "body B"
barrier.wait()
reply = call("POST", f"/api/v1/chats/{chat['id']}/messages", (201, 409), token=alice["token"],
body={"text": text}, headers={"Idempotency-Key": key})
return text, reply
with ThreadPoolExecutor(max_workers=PARALLEL) as pool:
results = list(pool.map(post, range(PARALLEL)))
texts = texts_in(alice, chat["id"])
winner = [t for t in texts if t in ("body A", "body B")]
print(f"{PARALLEL} parallel POSTs, one key, two different bodies: "
f"{dict(Counter((t, r.status) for t, r in results))}; saved: {winner}")
check(len(winner) == 1, "exactly one message must be created")
for text, reply in results:
expected = 201 if text == winner[0] else 409
check(reply.status == expected, f"{text}: expected {expected}, got {reply.status}")
print("PASS: the first body wins, the same body gets 201, the other body gets 409")
def test_key_scope():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
other = new_chat(alice, bob)
key = new_key()
a1 = send(alice, chat["id"], "scope", key=key).json
b1 = send(bob, chat["id"], "scope", key=key).json
a2 = send(alice, other["id"], "scope", key=key).json
print(f"one key: alice in chat 1, bob in chat 1, alice in chat 2 -> {len({a1['id'], b1['id'], a2['id']})} messages")
check(len({a1["id"], b1["id"], a2["id"]}) == 3, "a key must be scoped to user + chat")
call("POST", f"/api/v1/chats/{chat['id']}/messages", 409, token=alice["token"],
body={"text": "other text"}, headers={"Idempotency-Key": key})
print("PASS: the key is scoped to the current user and chat; another body with a used key -> 409")
def test_key_validation():
alice = new_user("alice")
chat = new_chat(alice)
path = f"/api/v1/chats/{chat['id']}/messages"
call("POST", path, 400, token=alice["token"], body={"text": "no key"})
for bad in ("", "a" * 129, "has space", "slash/inside", "ключ", "quote\"", "a+b"):
call("POST", path, 400, token=alice["token"], body={"text": "bad key"},
headers={"Idempotency-Key": bad.encode("utf-8").decode("latin-1")}) # как есть, байтами UTF-8
longest = ("Az09._:-" * 16)[:128]
call("POST", path, 201, token=alice["token"], body={"text": "longest key"}, headers={"Idempotency-Key": longest})
print("missing, empty, 129 chars, space, '/', non-ASCII, '\"', '+' -> 400; 128 chars of A-Z a-z 0-9 . _ : - -> 201")
print("PASS: Idempotency-Key is required and checked: [A-Za-z0-9._:-]{1,128}")
def test_failed_request_does_not_burn_key():
alice, eve = new_user("alice"), new_user("eve")
chat = new_chat(alice)
key = new_key()
path = f"/api/v1/chats/{chat['id']}/messages"
call("POST", path, 400, token=alice["token"], body={"text": " "}, headers={"Idempotency-Key": key})
call("POST", path, 404, token=eve["token"], body={"text": "not my chat"}, headers={"Idempotency-Key": key})
created = call("POST", path, 201, token=alice["token"], body={"text": "valid now"}, headers={"Idempotency-Key": key})
print(f"key used by a 400 and by a 404 first, then valid request -> {created.status}")
print("PASS: rejected requests (400, 404) do not store a result for the key")
def test_replay_checks_session_and_access():
alice, eve = new_user("alice"), new_user("eve")
chat = new_chat(alice)
key = new_key()
send(alice, chat["id"], "private", key=key)
stolen = call("POST", f"/api/v1/chats/{chat['id']}/messages", 404, token=eve["token"],
body={"text": "private"}, headers={"Idempotency-Key": key})
call("DELETE", "/api/v1/auth/sessions/current", 204, token=alice["token"])
revoked = call("POST", f"/api/v1/chats/{chat['id']}/messages", 401, token=alice["token"],
body={"text": "private"}, headers={"Idempotency-Key": key})
print(f"same key and body by an outsider -> {stolen.status}; by alice after logout -> {revoked.status}")
print("PASS: a retry checks the session and chat access again, the saved answer is not leaked")
def test_lost_response_then_retry():
"""Клиент отправил POST и не дождался ответа (оборвал соединение). Повтор с тем же ключом безопасен."""
alice = new_user("alice")
chat = new_chat(alice)
key = new_key()
body = json.dumps({"text": "answer was lost"}).encode("utf-8")
url = urllib.parse.urlsplit(BASE_URL)
request = (f"POST /api/v1/chats/{chat['id']}/messages HTTP/1.1\r\nHost: {url.netloc}\r\n"
f"Authorization: Bearer {alice['token']}\r\nIdempotency-Key: {key}\r\n"
f"Content-Type: application/json\r\nContent-Length: {len(body)}\r\nConnection: close\r\n\r\n").encode()
with tls_socket(timeout=5) as connection:
connection.sendall(request + body) # и сразу закрываем, ответ не читаем
time.sleep(1)
retry = call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, token=alice["token"],
body={"text": "answer was lost"}, headers={"Idempotency-Key": key})
count = texts_in(alice, chat["id"]).count("answer was lost")
print(f"POST sent, connection closed without reading the answer; retry -> {retry.status}; messages: {count}")
check(count == 1, "the retry after a lost answer created a duplicate")
print("PASS: an unconfirmed POST can be safely retried with the same key")
if __name__ == "__main__":
run_tests([
test_replay_returns_same_message,
test_same_key_parallel_through_replicas,
test_same_key_different_bodies_parallel,
test_key_scope,
test_key_validation,
test_failed_request_does_not_burn_key,
test_replay_checks_session_and_access,
test_lost_response_then_retry,
])
+157
View File
@@ -0,0 +1,157 @@
"""Регрессия: janitor не должен удалять объекты, которые replay записывает заново.
Дефект (найден на ревью): у failed-вложения остаются объекты под attachments/<id>/v1/ (например, worker упал
после PUT, затем попытки исчерпаны). Janitor считал их сиротами, хотя failed ещё можно повторить (исходник
в staging хранится STAGING_RETENTION_SECONDS). Повторная проверка и DELETE не были синхронизированы с replay:
janitor, приостановленный после проверки, удалял crop.jpg, только что записанный успешным replay,
а метаданные оставались ready -> /content?variant=crop -> 503.
Сценарий воспроизводит ровно это чередование: janitor запускается в контейнере janitor с перехватом
storage.delete — перед удалением любого объекта этого вложения он печатает PAUSED и ждёт; в это время тест
делает штатный ops.py replay и ждёт ready, потом отпускает janitor. Ожидание после исправления: janitor
вообще не пытается удалить объекты failed-вложения, пока replay возможен; после replay все 4 файла — 200.
Вторая часть: когда исходник удалён по retention (replay больше невозможен — состояние конечное),
оставшиеся объекты failed-вложения удаляются, а replay отказывает.
python student-tests/test_janitor_replay.py
Длительность ~4 мин (объекты должны стать старше grace = 120 с, минимально допустимого).
"""
import json
import subprocess
import threading
import time
from common import ROOT, call, check, run_tests, wait_ready
from test_jobs import (clear_faults, content, fault, get, image, log, ops, probe, upload, user_and_chat,
wait_status, job)
GRACE = 120 # минимально допустимый grace: 2 x UPLOAD_TIMEOUT_SECONDS
HOOK = r'''
import json, pathlib, sys, time
import secretstore; secretstore.store.start() # lab7: секреты janitor из OpenBao
import janitor, storage
attachment_id, grace = sys.argv[1], int(sys.argv[2])
prefix = f"attachments/{attachment_id}/"
release = pathlib.Path("/tmp/janitor-release-" + attachment_id)
real_delete = storage.delete
deleted = []
def delete(key, *args, **kwargs):
if key.startswith(prefix):
print("PAUSED " + key, flush=True) # проверка уже пройдена, DELETE ещё не выполнен
deadline = time.time() + 120
while not release.exists() and time.time() < deadline:
time.sleep(0.2)
deleted.append(key)
return real_delete(key, *args, **kwargs)
storage.delete = delete
report = None
for _ in range(60): # фоновый janitor может держать advisory lock
report = janitor.run_once(grace, False)
if report is not None:
break
time.sleep(2)
print(json.dumps({"report": report, "deleted_ours": deleted}), flush=True)
'''
def exec_python(service, code, *args, env=None):
# lab7: учётные данные процесса — из OpenBao по сертификату этого сервиса
code = "import secretstore as _secrets\n_secrets.store.start()\n" + code
command = ["docker", "compose", "exec", "-T"]
for name, value in (env or {}).items():
command += ["-e", f"{name}={value}"]
command += [service, "python", "-", *map(str, args)]
result = subprocess.run(command, cwd=ROOT, input=code.encode(), capture_output=True, check=False)
check(result.returncode == 0, f"{service}: {result.stderr.decode('utf-8', 'replace')[-500:]}")
return result.stdout.decode("utf-8", "replace")
def failed_with_leftovers(name):
"""failed/retry_exhausted, у которого под attachments/<id>/v1/ остались объекты прерванной попытки."""
clear_faults()
fault("worker_crash_after_put") # попытка 1: объекты записаны, worker убит до COMMIT
att = upload(image("thumb320"), filename=f"{name}.png")
deadline = time.monotonic() + 30
while len(probe("inspect", att["id"])["final_keys"]) < 4:
check(time.monotonic() < deadline, "attempt 1 did not write its objects")
time.sleep(0.3)
written = time.monotonic()
fault("worker_s3_error", 4) # попытки 2-5: временная ошибка S3 -> retry_exhausted
failed = wait_status(att["id"], ("failed", "ready"), 120)
check(failed["status"] == "failed" and failed["error_code"] == "retry_exhausted", f"{name}: {failed}")
keys = probe("inspect", att["id"])["final_keys"]
check(len(keys) == 4, f"{name}: leftovers expected, got {keys}")
log(f"{name}: failed/retry_exhausted after a crash post-PUT; leftover objects {keys}")
return att, written
def test_janitor_does_not_delete_replayed_objects():
user_and_chat()
a, written_a = failed_with_leftovers("race-replayable")
b, written_b = failed_with_leftovers("race-terminal")
wait = max(written_a, written_b) + GRACE + 5 - time.monotonic() # объекты ОБОИХ старше grace
if wait > 0:
log(f"waiting {wait:.0f} s until the leftovers are older than grace ({GRACE} s)")
time.sleep(wait)
# 1. janitor проходит bucket; если решит удалить объект A — остановится перед DELETE
proc = subprocess.Popen(["docker", "compose", "exec", "-T", "janitor", "python", "-", a["id"], str(GRACE)],
cwd=ROOT, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
proc.stdin.write(HOOK.encode())
proc.stdin.close()
lines = []
reader = threading.Thread(target=lambda: lines.extend(l.decode().strip() for l in proc.stdout), daemon=True)
reader.start()
deadline = time.monotonic() + 60
while not any(l.startswith("PAUSED") for l in lines) and proc.poll() is None:
check(time.monotonic() < deadline, "janitor pass did not finish")
time.sleep(0.2)
paused = [l for l in lines if l.startswith("PAUSED")]
log(f"janitor pass over the bucket: {'paused before DELETE of ' + paused[0][7:] if paused else 'did not try to delete any object of the replayable failed attachment'}")
# 2. штатный replay, пока janitor стоит (или уже прошёл)
j = job(a["id"])
check("replayed" in ops("replay", j["job_id"], "--reason", "janitor race regression"), "replay refused")
wait_status(a["id"], "ready", 60)
log(f"ops replay -> job {j['job_id']} ready")
# 3. отпускаем janitor и ждём конца прохода
exec_python("janitor", "import pathlib, sys\npathlib.Path('/tmp/janitor-release-' + sys.argv[1]).touch()\n", a["id"])
proc.wait(timeout=120)
reader.join(timeout=5)
result = json.loads([l for l in lines if l.startswith("{")][-1])
check(result["report"] is not None, "janitor pass did not run")
# 4. результат replay цел
for variant in ("original", "thumbnail", "crop", "optimized"):
content(a["id"], variant, expected=200)
info = probe("inspect", a["id"])
check(info["final_keys"] == ["v1/crop.jpg", "v1/optimized.webp", "v1/original", "v1/thumbnail.jpg"],
f"objects after the janitor pass: {info['final_keys']}")
check(not result["deleted_ours"], f"janitor deleted objects of the replayed attachment: {result['deleted_ours']}")
log("after the janitor pass: original/thumbnail/crop/optimized -> 200, 4 objects in S3; "
f"janitor report: orphans {result['report']['orphan_objects']}, deleted {result['report']['orphan_objects_deleted']}")
# 5. B всё ещё можно повторить -> его остатки тоже не тронуты
check(len(probe("inspect", b["id"])["final_keys"]) == 4, "leftovers of a replayable failed attachment deleted")
# 6. retention истёк -> исходника нет, replay невозможен (конечное состояние) -> остатки удаляются
terminal = exec_python("janitor", "import janitor, json, sys, time\n"
"for _ in range(60):\n"
" r = janitor.run_once(int(sys.argv[1]), False)\n"
" if r is not None:\n break\n time.sleep(2)\n"
"print(json.dumps(r))\n", GRACE, env={"STAGING_RETENTION_SECONDS": "1"})
left = probe("inspect", b["id"])["final_keys"]
check(left == [], f"leftovers of a terminal failed attachment must be swept, got {left}; janitor: "
f"{terminal.strip().splitlines()[-1]}")
refused = ops("replay", job(b["id"])["job_id"])
check("refused" in refused and "staging" in refused["refused"], f"replay must be refused: {refused}")
check(get(b["id"])["status"] == "failed", "terminal attachment must stay failed")
log(f"retention expired (STAGING_RETENTION_SECONDS=1 for this pass): staging source removed, leftovers of "
f"the failed attachment swept; replay refused: \"{refused['refused']}\"")
if __name__ == "__main__":
wait_ready()
run_tests([test_janitor_does_not_delete_replayed_objects])
+569
View File
@@ -0,0 +1,569 @@
"""Lab5: асинхронная обработка вложений — варианты, сохранность, отказы, повторы, DLQ, replay.
Нужен запущенный стенд из compose.yaml с FAULT_INJECTION=1 (по умолчанию на учебном стенде).
Тест управляет только своими синтетическими данными и сервисами через `docker compose stop|start|restart`,
volumes не удаляет. Сбои внедряются файлами в volume faults (faults.py), SQL — только чтение.
python student-tests/test_jobs.py [сценарий ...] # без аргументов — все по порядку
Сценарии: variants limits worker-down broker-down outbox-crash crash-after-put crash-after-commit
lease retry exhausted-replay permanent concurrency dlq
"""
import base64
import json
import sys
import time
import urllib.parse
from pathlib import Path
from common import (call, check, compose, compose_output, new_chat, new_user, post_message, psql, run_tests,
send, sql_value, wait_ready)
HERE = Path(__file__).resolve().parent
PROBE = (HERE / "worker_probe.py").read_text(encoding="utf-8")
FINAL_KEYS = ["v1/crop.jpg", "v1/optimized.webp", "v1/original", "v1/thumbnail.jpg"]
LEASE = 15 # JOB_LEASE_SECONDS стенда
TIMEOUT = 60 # JOB_TIMEOUT_SECONDS стенда
MAX_ATTEMPTS = 5 # JOB_MAX_ATTEMPTS стенда
STATE = {}
# ---------- инфраструктура ----------
def in_container(service, code, *args):
"""python - <args> в контейнере service, код через stdin. Последняя строка stdout — JSON.
Если service остановлен (сценарии с выключенным worker) — в одноразовом контейнере того же сервиса."""
import subprocess
from common import ROOT
# lab7: учётные данные процесса — из OpenBao по сертификату этого сервиса
code = "import secretstore as _secrets\n_secrets.store.start()\n" + code
running = subprocess.run(["docker", "compose", "ps", "--status", "running", "-q", service], cwd=ROOT,
capture_output=True, check=False).stdout.strip()
launch = (["exec", "-T", service, "python"] if running
else ["run", "--rm", "--no-deps", "-T", "--entrypoint", "python", service])
result = subprocess.run(["docker", "compose", *launch, "-", *map(str, args)], cwd=ROOT,
input=code.encode("utf-8"), capture_output=True, check=False)
check(result.returncode == 0, f"{service}: {result.stderr.decode('utf-8', 'replace')[-500:]}")
return json.loads(result.stdout.decode("utf-8").strip().splitlines()[-1])
def probe(*args):
return in_container("worker", PROBE, *args)
def ops(*args):
import subprocess
from common import ROOT
result = subprocess.run(["docker", "compose", "exec", "-T", "dispatcher", "python", "ops.py", *map(str, args)],
cwd=ROOT, capture_output=True, check=False)
check(result.returncode == 0, f"ops {args[0]}: {result.stderr.decode('utf-8', 'replace')[-400:]}")
return json.loads(result.stdout.decode("utf-8"))
def fault(point, times=1):
"""Взвести точку сбоя: times файлов /faults/<point>.<n> (каждое срабатывание удаляет один файл)."""
code = ("import pathlib, sys, time\n"
"for n in range(int(sys.argv[2])):\n"
" pathlib.Path('/faults', f'{sys.argv[1]}.{time.time_ns()}_{n}').touch()\n"
"print('{}')\n")
in_container("worker", code, point, times)
def clear_faults():
code = "import pathlib\nfor p in pathlib.Path('/faults').glob('*'):\n p.unlink()\nprint('{}')\n"
in_container("worker", code)
def image(kind):
return base64.b64decode(probe("make", kind)["b64"])
def user_and_chat():
if "alice" not in STATE:
STATE["alice"] = new_user("alice")
STATE["bob"] = new_user("bob")
STATE["chat"] = new_chat(STATE["alice"], STATE["bob"], title="Lab5 jobs")
return STATE["alice"], STATE["bob"], STATE["chat"]
def upload(data, content_type="image/png", filename="probe.png", expected=202):
alice, _bob, chat = user_and_chat()
query = "?filename=" + urllib.parse.quote(filename, safe="")
att = call("POST", f"/api/v1/chats/{chat['id']}/attachments{query}", expected, raw=data, token=alice["token"],
headers={"Content-Type": content_type}, timeout=60).json
if expected == 202:
check(att["status"] == "queued" and att["variants"] == [] and att["error_code"] is None,
f"202 must be a queued snapshot, got {att['status']}")
return att
def get(att_id, user=None):
user = user or STATE["alice"]
return call("GET", f"/api/v1/attachments/{att_id}", 200, token=user["token"]).json
def wait_status(att_id, statuses, seconds=60):
statuses = (statuses,) if isinstance(statuses, str) else statuses
deadline = time.monotonic() + seconds
while True:
att = get(att_id)
if att["status"] in statuses:
return att
check(time.monotonic() < deadline, f"{att_id[:8]}: still {att['status']} after {seconds} s")
time.sleep(0.3)
def content(att_id, variant="original", expected=200):
return call("GET", f"/api/v1/attachments/{att_id}/content?variant={variant}", expected,
token=STATE["bob"]["token"])
def job(att_id):
rows = sql_value(f"SELECT job_id || '|' || status || '|' || attempt || '|' || coalesce(error_code, '-') "
f"FROM attachment_jobs WHERE attachment_id = '{att_id}'")
check(rows and "\n" not in rows, f"expected exactly one job for {att_id}")
job_id, status, attempt, error = rows.split("|")
return {"job_id": job_id, "status": status, "attempt": int(attempt), "error_code": error}
def events(job_id):
out = sql_value(f"SELECT attempt || ':' || event || ':' || coalesce(detail, '') FROM job_events "
f"WHERE job_id = '{job_id}' ORDER BY id")
return out.splitlines() if out else []
def names(evs):
return [e.split(":")[1] for e in evs]
def assert_one_result(att_id, label=""):
"""Инвариант идемпотентности: ровно один набор вариантов и ровно 4 объекта под конечным prefix."""
info = probe("inspect", att_id)
check(info["state"] == "ready", f"{label}: not ready in DB")
check(info["variant_rows"] == 3, f"{label}: {info['variant_rows']} variant rows, expected 3")
check(info["final_keys"] == FINAL_KEYS, f"{label}: final objects {info['final_keys']}")
check(info["original_sha_ok"] and info["original_size_ok"], f"{label}: original differs from upload")
check(all(v["sha_ok"] and v["meta_size_ok"] for v in info["variants"].values()), f"{label}: variant mismatch")
return info
def outbox_rows(job_id):
out = sql_value(f"SELECT attempt || ':' || (published_at IS NOT NULL) FROM outbox WHERE job_id = '{job_id}' "
f"ORDER BY id")
return out.splitlines() if out else []
def queue_depth():
out = compose_output("exec", "-T", "rabbitmq", "rabbitmqctl", "-q", "list_queues", "-p", "messenger",
"name", "messages", "messages_unacknowledged")
depth = {}
for line in out.splitlines():
parts = line.split()
if len(parts) == 3 and parts[1].isdigit():
depth[parts[0]] = (int(parts[1]), int(parts[2]))
return depth
def log(text):
print(text, flush=True)
# ---------- сценарии ----------
def test_variants():
"""thumbnail/crop/optimized по контракту, EXIF orientation, alpha -> белый, без увеличения, без метаданных."""
alice, bob, chat = user_and_chat()
cases = {
"thumb320": ("image/png", {"thumbnail": [256, 160], "crop": [128, 128], "optimized": [320, 200]}),
"exif6": ("image/jpeg", {"thumbnail": [192, 256], "crop": [128, 128], "optimized": [300, 400]}),
"alpha": ("image/png", {"thumbnail": [256, 170], "crop": [128, 128], "optimized": [300, 200]}),
"tiny": ("image/png", {"thumbnail": [40, 30], "crop": [128, 128], "optimized": [40, 30]}),
"large": ("image/jpeg", {"thumbnail": [256, 170], "crop": [128, 128], "optimized": [1280, 853]}),
"strip": ("image/png", {"thumbnail": [256, 1], "crop": [128, 128], "optimized": [1280, 1]}),
}
for kind, (ctype, sizes) in cases.items():
data = image(kind)
att = upload(data, ctype, f"{kind}.{'jpg' if ctype == 'image/jpeg' else 'png'}")
ready = wait_status(att["id"], "ready")
meta = {v["name"]: v for v in ready["variants"]}
check(set(meta) == {"thumbnail", "crop", "optimized"}, f"{kind}: variants {sorted(meta)}")
for name, size in sizes.items():
check([meta[name]["width"], meta[name]["height"]] == size,
f"{kind}/{name}: {meta[name]['width']}x{meta[name]['height']}, expected {size}")
check(meta["thumbnail"]["content_type"] == "image/jpeg" and meta["crop"]["content_type"] == "image/jpeg"
and meta["optimized"]["content_type"] == "image/webp", f"{kind}: wrong variant content types")
original = content(att["id"])
check(original.data == data, f"{kind}: original is not byte-identical")
for name in ("thumbnail", "crop", "optimized"):
reply = content(att["id"], name)
check(reply.headers["content-type"] == meta[name]["content_type"], f"{kind}/{name}: Content-Type")
info = assert_one_result(att["id"], kind)
for name, v in info["variants"].items():
check(v["exif_tags"] == 0 and not v["has_xmp"], f"{kind}/{name}: metadata not stripped")
if kind == "exif6":
top = info["variants"]["thumbnail"]["pixel_top_center"]
check(top[0] > 200 and top[1] < 60, f"exif6: orientation not applied, top pixel {top}")
if kind == "alpha":
left = info["variants"]["thumbnail"]["pixel_left_center"]
right = info["variants"]["thumbnail"]["pixel_right_center"]
check(left[:3] == [255, 255, 255] and right[2] > 200, f"alpha: not composited on white {left} {right}")
check(info["variants"]["optimized"]["mode"] == "RGBA", "alpha: optimized WebP lost transparency")
log(f"{kind}: " + ", ".join(f"{n} {s[0]}x{s[1]}" for n, s in sizes.items())
+ f"; original byte-identical; EXIF/XMP in variants: 0; S3 keys {info['final_keys']}")
# Отсутствующий вариант у ready -> 404 (нет такого имени в контракте -> 400), queued -> 409 проверяется ниже.
content(att["id"], "unknown", expected=400)
log("unknown variant name -> 400; variants carry their own size/sha256, original fields describe the upload")
def test_limits():
"""Лимиты: bytes и пиксели на API; память/пиксели/время процесса обработки на worker."""
alice, _bob, chat = user_and_chat()
big = b"\x89PNG\r\n\x1a\n" + b"\0" * (10 * 1024 * 1024)
call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=big.png", 413, raw=big, token=alice["token"],
headers={"Content-Type": "image/png"}, timeout=60)
log("10 MiB + 8 bytes -> 413 before any job is created")
report = probe("imaging-limits")
at, over = report["at_limit_40mpx"], report["over_limit_max_10mpx"]
check(at["exit_code"] == 0, f"40 Mpx PNG at the limit must be processed, exit {at['exit_code']}")
check(over["exit_code"] == 4, f"worker-side pixel limit must reject (exit 4), got {over['exit_code']}")
check(at["peak_rss_mib_max_children"] < report["memory_limit_mib"],
f"peak RSS {at['peak_rss_mib_max_children']} MiB exceeds RLIMIT_AS {report['memory_limit_mib']} MiB")
log(f"imaging.py on 8000x5000 PNG: exit 0, peak RSS {at['peak_rss_mib_max_children']} MiB "
f"(RLIMIT_AS {report['memory_limit_mib']} MiB); same file with MAX_IMAGE_PIXELS=10M -> exit 4 (image_too_large)")
# Память: процесс обработки упирается в RLIMIT_AS -> MemoryError -> постоянная ошибка resource_limit.
fault("imaging_oom")
att = upload(image("thumb320"), filename="oom.png")
failed = wait_status(att["id"], ("failed", "ready"), 60)
check(failed["status"] == "failed" and failed["error_code"] == "resource_limit",
f"oom: expected failed/resource_limit, got {failed['status']}/{failed['error_code']}")
j = job(att["id"])
check(j["attempt"] == 1, "resource_limit is permanent: no retries expected")
log(f"memory bomb in the imaging process -> failed/resource_limit after attempt 1; worker itself survived")
STATE["oom_job"] = j["job_id"]
# Время: зависший процесс обработки убивается по JOB_TIMEOUT_SECONDS -> временная ошибка -> retry -> ready.
fault("imaging_hang")
att = upload(image("thumb320"), filename="hang.png")
started = time.monotonic()
ready = wait_status(att["id"], "ready", TIMEOUT + 40)
j = job(att["id"])
evs = events(j["job_id"])
check("lease_expired" not in names(evs), f"a long-running (alive) attempt must keep its lease: {evs}")
check(any("processing_timeout" in e for e in evs) and j["attempt"] == 2, f"timeout not handled as retry: {evs}")
log(f"imaging hang -> killed after {TIMEOUT} s (processing_timeout, temporary), lease renewed meanwhile "
f"(no lease_expired), attempt 2 ready after {time.monotonic() - started:.0f} s")
def test_worker_down():
"""Защита п.2-3: worker остановлен -> 202 -> сообщение с вложением -> рестарт API+broker -> worker -> ready."""
alice, bob, chat = user_and_chat()
compose("stop", "worker")
log("worker stopped")
data = image("thumb320")
att = upload(data, filename="offline.png")
log(f"upload while worker is down -> 202 queued, attachment {att['id']}")
j = job(att["id"])
source_key = sql_value(f"SELECT source_key FROM attachments WHERE id = '{att['id']}'")
check(source_key.startswith("staging/"), "source must be in the durable staging prefix")
check(probe("exists", source_key)["exists"], "staging object must exist before 202")
msg = post_message(alice, chat["id"], "photo while worker is down", [att["id"]]).json
check(msg["attachment_ids"] == [att["id"]], "message must reference the queued attachment")
content(att["id"], expected=409)
content(att["id"], "thumbnail", expected=409)
send(bob, chat["id"], "other messages keep working")
deadline = time.monotonic() + 10
while outbox_rows(j["job_id"]) != ["1:true"]:
check(time.monotonic() < deadline, "dispatcher did not publish the job")
time.sleep(0.2)
deadline = time.monotonic() + 15 # счётчики quorum-очереди в rabbitmqctl обновляются раз в несколько секунд
while (queue_depth().get("attachments.process.v1") or (0, 0))[0] < 1:
check(time.monotonic() < deadline, "published message is not visible in the queue")
time.sleep(0.5)
depth = queue_depth().get("attachments.process.v1")
log(f"message with attachment 201, content 409, other messages 201; job {j['job_id']} published, "
f"queue messages/unacked = {depth}")
compose("restart", "rabbitmq")
compose("restart", "api")
wait_ready()
depth_after = queue_depth().get("attachments.process.v1")
check(depth_after and depth_after[0] >= 1, f"message lost after broker restart: {depth_after}")
check(get(att["id"])["status"] == "queued", "job must still be queued after restarts")
log(f"rabbitmq and api restarted with volumes; queue still holds {depth_after[0]} message(s); status queued")
compose("start", "worker")
ready = wait_status(att["id"], "ready", 60)
j2 = job(att["id"])
check(j2["job_id"] == j["job_id"] and j2["status"] == "ready", "same job_id must finish")
thumb = content(att["id"], "thumbnail")
check(len(thumb.data) == {v["name"]: v for v in ready["variants"]}["thumbnail"]["size_bytes"], "thumbnail size")
info = assert_one_result(att["id"], "worker-down")
check(not info["staging_present"] and not probe("exists", source_key)["exists"],
"staging must be cleaned after the safe commit")
log(f"worker started -> same job {j['job_id']} ready, thumbnail downloadable; staging object deleted")
def test_broker_down():
"""Брокер недоступен: API принимает (outbox), dispatcher копит и публикует после восстановления."""
compose("stop", "rabbitmq")
log("rabbitmq stopped")
att = upload(image("thumb320"), filename="no-broker.png")
call("GET", "/health/ready", 200)
j = job(att["id"])
time.sleep(3)
check(outbox_rows(j["job_id"]) == ["1:false"], "outbox row must wait while the broker is down")
log(f"upload -> 202 and /health/ready 200 without broker; outbox row pending for job {j['job_id']}")
compose("start", "rabbitmq")
wait_status(att["id"], "ready", 90)
check(outbox_rows(j["job_id"]) == ["1:true"], "outbox row must be published after recovery")
assert_one_result(att["id"], "broker-down")
log("rabbitmq started -> dispatcher published the pending row -> ready")
def test_outbox_crash():
"""Разрыв COMMIT/publish: dispatcher падает после COMMIT задания до publish и после confirm до отметки."""
fault("dispatcher_crash_before_publish")
att = upload(image("thumb320"), filename="crash-before-publish.png")
ready = wait_status(att["id"], "ready", 60)
j = job(att["id"])
logs = compose_output("logs", "--tail", "400", "dispatcher")
check("FAULT INJECTION: dispatcher_crash_before_publish" in logs, "fault did not fire")
check(outbox_rows(j["job_id"]) == ["1:true"] and j["attempt"] == 1, "outbox must publish exactly the same job")
assert_one_result(att["id"], "crash-before-publish")
log(f"dispatcher killed between COMMIT and publish; restarted by policy, outbox re-published -> job "
f"{j['job_id']} ready, attempt 1, no manual action")
fault("dispatcher_crash_after_confirm")
att = upload(image("thumb320"), filename="crash-after-confirm.png")
wait_status(att["id"], "ready", 60)
j = job(att["id"])
deadline = time.monotonic() + 20
while "duplicate_ignored" not in names(events(j["job_id"])):
check(time.monotonic() < deadline, f"duplicate delivery not observed: {events(j['job_id'])}")
time.sleep(0.3)
assert_one_result(att["id"], "crash-after-confirm")
log(f"dispatcher killed after publisher confirm, before marking outbox -> message published twice; "
f"worker: {names(events(j['job_id']))} -> one result set")
def test_crash_after_put():
"""Worker падает после записи объектов в S3, до COMMIT/ack: повтор завершает тот же результат."""
fault("worker_crash_after_put")
att = upload(image("thumb320"), filename="crash-after-put.png")
wait_status(att["id"], "ready", LEASE + 40)
j = job(att["id"])
evs = events(j["job_id"])
check(names(evs).count("claimed") == 2 and "lease_expired" in names(evs), f"unexpected history {evs}")
assert_one_result(att["id"], "crash-after-put")
log(f"worker killed after S3 PUT (before COMMIT and ack): redelivery saw a live lease (no-op), lease expired "
f"after {LEASE} s, attempt {j['attempt']} rewrote the same keys -> one set; events {names(evs)}")
def test_crash_after_commit():
"""Worker падает после COMMIT результата, до ack: повторная доставка ready-задачи — no-op с ack."""
fault("worker_crash_after_commit")
att = upload(image("thumb320"), filename="crash-after-commit.png")
wait_status(att["id"], "ready", 30)
j = job(att["id"])
deadline = time.monotonic() + 30
while "duplicate_ignored" not in names(events(j["job_id"])):
check(time.monotonic() < deadline, f"redelivery not observed: {events(j['job_id'])}")
time.sleep(0.3)
evs = events(j["job_id"])
check(names(evs).count("ready") == 1 and j["attempt"] == 1, f"ready must be recorded once: {evs}")
assert_one_result(att["id"], "crash-after-commit")
deadline = time.monotonic() + 20 # счётчики quorum-очереди обновляются с задержкой
while queue_depth().get("attachments.process.v1") != (0, 0):
check(time.monotonic() < deadline, f"message left in the queue: {queue_depth()}")
time.sleep(0.5)
log(f"worker killed after COMMIT, before ack: broker redelivered, worker acked as no-op ({evs[-1]}); "
f"queue empty (0 ready, 0 unacked)")
STATE["staging_check"] = att["id"]
def test_lease():
"""Зависший worker: аренда не продлевается -> dispatcher возвращает job -> другой поток завершает;
результат зависшего отклоняется fencing-токеном, ready не откатывается."""
fault("worker_freeze")
att = upload(image("thumb320"), filename="frozen.png")
started = time.monotonic()
wait_status(att["id"], "ready", LEASE + 40)
took = time.monotonic() - started
j = job(att["id"])
deadline = time.monotonic() + 3 * LEASE + 20
while "stale_result_rejected" not in names(events(j["job_id"])):
check(time.monotonic() < deadline, f"stale result of the frozen attempt not seen: {events(j['job_id'])}")
time.sleep(0.5)
evs = events(j["job_id"])
check(get(att["id"])["status"] == "ready", "late result must not roll ready back")
check(names(evs).count("ready") == 1, f"exactly one ready: {evs}")
assert_one_result(att["id"], "lease")
log(f"frozen attempt 1 stopped renewing; lease expired, recovered by dispatcher, attempt 2 ready after "
f"{took:.0f} s; frozen attempt woke up -> stale_result_rejected; events {names(evs)}")
def test_retry():
"""Временные ошибки S3: backoff с jitter, затем ready; задержки видны в журнале."""
fault("worker_s3_error", 2)
att = upload(image("thumb320"), filename="retry.png")
wait_status(att["id"], "ready", 60)
j = job(att["id"])
evs = [e for e in events(j["job_id"]) if ":retry_scheduled:" in e]
check(len(evs) == 2 and j["attempt"] == 3, f"expected 2 retries, got {evs}")
delays = [float(e.split("delay=")[1].rstrip("s")) for e in evs]
check(1.0 <= delays[0] <= 2.0 and 2.0 <= delays[1] <= 4.0, f"backoff out of range: {delays}")
assert_one_result(att["id"], "retry")
log(f"2 x storage_unavailable -> retries after {delays[0]:.2f} s and {delays[1]:.2f} s (equal jitter: "
f"1..2 s, 2..4 s), attempt 3 ready")
def test_exhausted_replay():
"""Исчерпание попыток -> failed/retry_exhausted, реестр failed, явный replay; replay ready — отказ."""
alice, _bob, chat = user_and_chat()
fault("worker_s3_error", MAX_ATTEMPTS)
att = upload(image("thumb320"), filename="exhausted.png")
failed = wait_status(att["id"], ("failed", "ready"), 120)
check(failed["status"] == "failed" and failed["error_code"] == "retry_exhausted",
f"expected failed/retry_exhausted, got {failed['status']}/{failed['error_code']}")
j = job(att["id"])
check(j["attempt"] == MAX_ATTEMPTS, f"attempts {j['attempt']}")
content(att["id"], expected=409)
post_message(alice, chat["id"], "", [att["id"]], expected=409)
registry = {row["job_id"]: row for row in ops("failed")}
check(registry.get(j["job_id"], {}).get("replayable") is True, "failed job must be in the registry")
log(f"{MAX_ATTEMPTS} temporary errors -> failed/retry_exhausted (public error_code), content 409, "
f"attach 409, listed by ops.py failed (replayable)")
replay = ops("replay", j["job_id"], "--reason", "s3 recovered")
check("replayed" in replay, f"replay refused: {replay}")
wait_status(att["id"], "ready", 60)
assert_one_result(att["id"], "replay")
j2 = job(att["id"])
refused = ops("replay", j["job_id"])
check("refused" in refused, "replay of a ready job must be refused")
again = job(att["id"])
check(again == j2, "refused replay must not change the job")
check(names(events(j["job_id"])).count("replayed") == 1, "audit must contain the replay once")
log(f"ops replay -> same job_id {j['job_id']} attempt {j2['attempt']} ready; second replay refused: "
f"\"{refused['refused']}\"")
def test_permanent():
"""Постоянная ошибка (битое изображение в worker) -> failed сразу, без повторов."""
fault("imaging_invalid")
att = upload(image("thumb320"), filename="invalid.png")
failed = wait_status(att["id"], ("failed", "ready"), 30)
check(failed["status"] == "failed" and failed["error_code"] == "invalid_image", f"got {failed}")
j = job(att["id"])
check(j["attempt"] == 1 and "retry_scheduled" not in names(events(j["job_id"])), "no retries for permanent")
log("invalid image in the worker -> failed/invalid_image at attempt 1, no retry (permanent error)")
def test_concurrency():
"""Ограниченная конкуренция: WORKER_CONCURRENCY потребителей с prefetch=1; одновременно processing <= 2."""
out = compose_output("exec", "-T", "rabbitmq", "rabbitmqctl", "-q", "list_consumers", "-p", "messenger",
"queue_name", "prefetch_count", "ack_required")
lines = [line.split() for line in out.splitlines() if line.strip()]
header = lines[0] if lines and lines[0][0] == "queue_name" else ["queue_name", "prefetch_count", "ack_required"]
consumers = [dict(zip(header, line)) for line in lines if line[0] == "attachments.process.v1"]
check(len(consumers) == 2 and all(c["prefetch_count"] == "1" and c["ack_required"] == "true"
for c in consumers), f"consumers {out}")
# Копим очередь при остановленном worker, затем запускаем: работы больше, чем потоков.
compose("stop", "worker")
data = image("large")
ids = [upload(data, "image/jpeg", f"burst{n}.jpg")["id"] for n in range(8)]
id_list = ", ".join(f"'{i}'" for i in ids)
compose("start", "worker")
started = time.monotonic()
peak, samples = 0, 0
while True:
busy, ready = map(int, sql_value(
f"SELECT count(*) FILTER (WHERE status = 'processing') || '|' || count(*) FILTER (WHERE status = 'ready') "
f"FROM attachment_jobs WHERE attachment_id IN ({id_list})").split("|"))
peak, samples = max(peak, busy), samples + 1
if ready == len(ids):
break
check(time.monotonic() - started < 120, "burst not processed in 120 s")
time.sleep(0.05)
took = time.monotonic() - started
check(peak == 2, f"peak {peak} jobs in processing, expected exactly WORKER_CONCURRENCY=2")
log(f"2 consumers, prefetch_count 1, manual ack; 8 queued 3000x2000 JPEG drained in {took:.1f} s after "
f"worker start, peak processing {peak} of 8 ({samples} samples)")
def test_dlq():
"""Невалидные сообщения и сообщения о неизвестной job -> DLQ; dlq-replay их не исполняет."""
publish = r'''
import json, sys, uuid
import broker, pipeline
p = broker.Publisher()
p.open().basic_publish(pipeline.EXCHANGE, pipeline.ROUTING_KEY, b'{"not":"a job"}', mandatory=True)
p.publish(pipeline.build_message(uuid.uuid4(), uuid.uuid4(), 1, 1, None))
p.close()
print("{}")
'''
before = queue_depth().get("attachments.process.v1.dlq", (0, 0))[0]
in_container("dispatcher", publish)
deadline = time.monotonic() + 15
while queue_depth().get("attachments.process.v1.dlq", (0, 0))[0] < before + 2:
check(time.monotonic() < deadline, "messages did not reach the DLQ")
time.sleep(0.3)
peek = ops("dlq", "--limit", "50")
reasons = {(m["invalid"] is not None, m["dead_letter_reason"]) for m in peek}
check((True, "rejected") in reasons, f"invalid message not in DLQ: {peek}")
replayed = ops("dlq-replay", "--limit", "50")
kept = [m for m in replayed if m["action"] == "keep"]
check(len(kept) >= 2, "invalid/unknown messages must be kept, not executed")
after = queue_depth().get("attachments.process.v1.dlq", (0, 0))[0]
check(after >= before + 2, "dlq-replay must not drop messages it cannot handle")
log(f"schema-invalid message and unknown job_id -> reject -> DLQ ({after} message(s)); "
f"dlq-replay kept them: {[m['note'] for m in kept][:2]}")
def test_staging_cleanup():
"""Janitor доделывает очистку staging, если worker упал до неё (после crash-after-commit)."""
att_id = STATE.get("staging_check")
if not att_id:
log("skip: run crash-after-commit first")
return
key = sql_value(f"SELECT coalesce(source_key, '') FROM attachments WHERE id = '{att_id}'")
if key:
log(f"staging source still present after the crash (worker died before cleanup); waiting 60 s window")
time.sleep(62)
from common import janitor
report = janitor()
# фоновый janitor (проход раз в JANITOR_INTERVAL_SECONDS) мог успеть первым в окне 62 с — проверяем результат
left = sql_value(f"SELECT coalesce(source_key, '') FROM attachments WHERE id = '{att_id}'")
check(not left, f"staging source still referenced: {report}")
check(not probe("exists", key)["exists"], "staging object must be gone")
by = "this pass" if report["staging_ready_deleted"] else "the background janitor pass"
log(f"janitor removed the staging source of the ready attachment ({by}); source_key NULL, object gone")
else:
log("staging already cleaned by the worker")
SCENARIOS = {
"variants": test_variants, "limits": test_limits, "worker-down": test_worker_down,
"broker-down": test_broker_down, "outbox-crash": test_outbox_crash, "crash-after-put": test_crash_after_put,
"crash-after-commit": test_crash_after_commit, "staging": test_staging_cleanup, "lease": test_lease,
"retry": test_retry, "exhausted-replay": test_exhausted_replay, "permanent": test_permanent,
"concurrency": test_concurrency, "dlq": test_dlq,
}
def main():
chosen = sys.argv[1:] or list(SCENARIOS)
wait_ready()
clear_faults()
tests = []
for name in chosen:
def run(name=name):
log(f"--- {name}: {SCENARIOS[name].__doc__.splitlines()[0]}")
try:
SCENARIOS[name]()
finally:
compose("start", "worker") # идемпотентно: стенд остаётся рабочим даже после FAIL
compose("start", "rabbitmq")
run.__name__ = name
tests.append(run)
run_tests(tests)
if __name__ == "__main__":
main()
+238
View File
@@ -0,0 +1,238 @@
"""lab7: защита на внешней границе и в API (через HTTPS-ingress, как обычный клиент).
python student-tests/test_lab7_security.py [имя_теста ...]
Каждый тест — отрицательная проверка конкретной угрозы из security/THREAT_MODEL.md. Пароли/токены тестов
синтетические и не печатаются.
"""
import base64
import hashlib
import json
import socket
import ssl
import sys
import urllib.parse
import uuid
import images
from common import (BASE_URL, CA_FILE, PASSWORD, app_python, basic, call, check, login, new_chat, new_key, new_user,
redis_cli, run_tests, sql_value, tls_socket, upload, PKI_DIR)
URL = urllib.parse.urlsplit(BASE_URL)
def raw_request(head: bytes, body: bytes = b"", read=4096) -> bytes:
with tls_socket(timeout=10) as sock:
sock.sendall(head + body)
data = b""
try:
while len(data) < read:
chunk = sock.recv(4096)
if not chunk:
break
data += chunk
if b"\r\n\r\n" in data and (b"Content-Length: 0" in data or data.count(b"}") > 0):
break
except (socket.timeout, ssl.SSLError, ConnectionResetError):
pass
return data
def test_https_only_and_certificate_checks():
# 1) HTTP на старом порту 8080: API там не отвечает (наружу опубликован только 8443)
try:
with socket.create_connection((URL.hostname, 8080), timeout=2) as sock:
sock.sendall(b"GET /health/live HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n")
data = sock.recv(400)
check(b"x-instance-id" not in data.lower(), "the API answers plain HTTP on 8080")
print("port 8080: something else answers locally, not the API")
except OSError:
print("port 8080: closed")
# 2) открытый HTTP на HTTPS-порт — ответа в открытом виде нет
with socket.create_connection((URL.hostname, URL.port), timeout=5) as sock:
sock.sendall(b"GET /health/live HTTP/1.1\r\nHost: x\r\n\r\n")
try:
data = sock.recv(200)
except OSError:
data = b""
check(b'"status"' not in data, f"plaintext HTTP got an application answer: {data[:80]!r}")
# 3) чужой CA и 4) неверное имя сервера — ошибка ПРОВЕРКИ сертификата, а не сети
for name, context, server_name in (
("empty trust store", ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT), URL.hostname),
("foreign CA", ssl.create_default_context(cafile=str(PKI_DIR / "test" / "rogue-ca" / "ca.crt")),
URL.hostname),
("wrong host name", ssl.create_default_context(cafile=CA_FILE), "evil.example")):
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIRED
try:
with socket.create_connection((URL.hostname, URL.port), timeout=5) as raw:
context.wrap_socket(raw, server_hostname=server_name).close()
check(False, f"{name}: handshake succeeded")
except ssl.SSLCertVerificationError as exc:
print(f"{name}: rejected by certificate verification ({exc.verify_message})")
print("PASS: only HTTPS on 8443; untrusted CA and wrong host name fail certificate verification")
def test_security_headers():
reply = call("GET", "/health/live", 200)
check("max-age" in reply.headers.get("strict-transport-security", ""), "no HSTS")
check(reply.headers.get("x-content-type-options") == "nosniff", "no nosniff")
check("server" not in reply.headers, f"Server header reveals {reply.headers.get('server')}")
check(len(reply.instance) == 12 and all(c in "0123456789abcdef" for c in reply.instance),
"X-Instance-Id is not a random alias")
print(f"HSTS, nosniff, no Server header; X-Instance-Id is an opaque alias ({reply.instance})")
print("PASS: security headers")
def test_outsider_cannot_reach_foreign_chat():
alice, bob, eve = new_user("alice"), new_user("bob"), new_user("eve")
chat = new_chat(alice, bob)
att = upload(alice, chat["id"], images.sample_png()).json
eve_chat = new_chat(eve)
spoof = {"X-User-Id": alice["id"]} # подделка идентичности заголовком — игнорируется
probes = [
("GET", f"/api/v1/chats/{chat['id']}", None),
("GET", f"/api/v1/chats/{chat['id']}/messages", None),
("POST", f"/api/v1/chats/{chat['id']}/messages", {"text": "intrusion"}),
("GET", f"/api/v1/attachments/{att['id']}", None),
("GET", f"/api/v1/attachments/{att['id']}/content", None),
("POST", f"/api/v1/chats/{eve_chat['id']}/messages", {"text": "", "attachment_ids": [att["id"]]}),
]
for method, path, body in probes:
headers = {**spoof, "Idempotency-Key": new_key()} if method == "POST" else spoof
reply = call(method, path, 404, token=eve["token"], body=body, headers=headers)
check(alice["id"] not in reply.data.decode(), "response mentions the victim")
me = call("GET", "/api/v1/users/me", 200, token=eve["token"], headers=spoof).json
check(me["id"] == eve["id"], "X-User-Id changed the identity")
print(f"outsider: {len(probes)} attempts on a foreign chat/attachment -> 404 (existence not revealed); "
"X-User-Id of the victim is ignored")
print("PASS: ACL — outsider reads/writes nothing, cannot attach a foreign file")
def test_logout_revokes_token():
user = new_user("logout")
call("DELETE", "/api/v1/auth/sessions/current", 204, token=user["token"])
reply = call("GET", "/api/v1/users/me", 401, token=user["token"])
check("Bearer" in reply.headers.get("www-authenticate", ""), "no Bearer challenge")
call("DELETE", "/api/v1/auth/sessions/current", 401, token=user["token"])
print("PASS: logout -> the same token is 401 on every replica (session deleted in shared Redis)")
def test_login_rate_limit_is_shared():
user = new_user("ratelimit")
seen, codes, retry_after = set(), [], None
for attempt in range(14):
reply = call("POST", "/api/v1/auth/sessions", (401, 429),
headers={"Authorization": basic(user["username"], "Wrong-password-" + str(attempt))})
codes.append(reply.status)
seen.add(reply.instance)
if reply.status == 429:
retry_after = reply.headers.get("retry-after")
check(reply.json["error"]["code"] == "rate_limited", "wrong error code")
# в new_user был 1 успешный вход: лимит 10 попыток на username за окно -> 401 x9, затем 429
check(codes[:9] == [401] * 9 and all(code == 429 for code in codes[9:]), f"unexpected codes {codes}")
check(retry_after and retry_after.isdigit() and 1 <= int(retry_after) <= 60, f"Retry-After {retry_after}")
check(len(seen) >= 2, f"all answers came from one replica {seen}: shared counter not shown")
# даже верный пароль до конца окна — 429 (подбор не продолжить, сменив попытку на правильную)
call("POST", "/api/v1/auth/sessions", 429, headers={"Authorization": basic(user["username"], PASSWORD)})
print(f"codes {codes}; answered by replicas {sorted(seen)}; Retry-After {retry_after} s")
print("PASS: login rate limit is shared by all replicas (Redis), 429 + Retry-After, before Argon2id")
def test_request_size_limits():
user = new_user("size")
chat = new_chat(user)
big = {"text": "x" * 70000} # > MAX_JSON_BYTES (64 KiB); text сам по себе тоже > 4000 символов
reply = call("POST", f"/api/v1/chats/{chat['id']}/messages", 413, token=user["token"], body=big,
headers={"Idempotency-Key": new_key()})
check(reply.json["error"]["code"] == "payload_too_large", "wrong code")
# chunked без Content-Length: лимит считается по фактически полученным байтам
body = json.dumps(big).encode()
chunked = b"".join(b"%x\r\n%s\r\n" % (len(body[i:i + 8192]), body[i:i + 8192])
for i in range(0, len(body), 8192)) + b"0\r\n\r\n"
head = (f"POST /api/v1/chats/{chat['id']}/messages HTTP/1.1\r\nHost: {URL.hostname}\r\n"
f"Authorization: Bearer {user['token']}\r\nContent-Type: application/json\r\n"
f"Idempotency-Key: {new_key()}\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n").encode()
data = raw_request(head, chunked)
check(data.startswith(b"HTTP/1.1 413"), f"chunked oversized JSON: {data[:60]!r}")
# ingress отвергает заявленное тело больше 11 MiB ещё до API
head = (f"POST /api/v1/chats/{chat['id']}/attachments?filename=a.png HTTP/1.1\r\nHost: {URL.hostname}\r\n"
f"Authorization: Bearer {user['token']}\r\nContent-Type: image/png\r\n"
f"Content-Length: 50000000\r\nConnection: close\r\n\r\n").encode()
data = raw_request(head, b"")
check(data.startswith(b"HTTP/1.1 413"), f"50 MB upload: {data[:60]!r}")
print("JSON > 64 KiB -> 413 (with Content-Length and chunked); upload Content-Length 50 MB -> 413 at the LB")
print("PASS: request size limits")
def argon2_params(user_id):
value = sql_value(f"SELECT password_hash FROM users WHERE id = '{user_id}'")
parts = value.split("$")
params = dict(item.split("=") for item in parts[3].split(","))
salt = base64.b64decode(parts[4] + "=" * (-len(parts[4]) % 4))
return parts[1], {k: int(v) for k, v in params.items()}, len(salt), value
def test_password_storage_argon2id():
a = new_user("hash_a")
b = new_user("hash_b") # тот же пароль
kind_a, params_a, salt_len, hash_a = argon2_params(a["id"])
kind_b, _params_b, _salt_b, hash_b = argon2_params(b["id"])
check(kind_a == kind_b == "argon2id", f"not argon2id: {kind_a}")
check(params_a["m"] >= 19456 and params_a["t"] >= 2 and params_a["p"] >= 1, f"weak params {params_a}")
check(salt_len >= 16, f"salt {salt_len} bytes")
check(hash_a != hash_b, "same password -> same hash (no salt)")
check(PASSWORD not in hash_a, "password in the hash string")
print(f"stored: $argon2id$v=19$m={params_a['m']},t={params_a['t']},p={params_a['p']}$<{salt_len}-byte salt>$<hash>;"
" two users with the same password have different hashes")
print("PASS: Argon2id with salt and parameters in the stored string")
LEGACY_HASH = r'''
import json, sys
from argon2 import PasswordHasher
# параметры lab2-6 этого решения: m=12 MiB, t=3, p=1 (ниже требования lab7 по памяти)
print(json.dumps({"hash": PasswordHasher(time_cost=3, memory_cost=12 * 1024, parallelism=1).hash(sys.argv[1])}))
'''
def test_rehash_on_login():
user = new_user("rehash")
legacy = json.loads(app_python(LEGACY_HASH, user["password"]).splitlines()[-1])["hash"]
sql_value(f"UPDATE users SET password_hash = '{legacy}' WHERE id = '{user['id']}' RETURNING 1")
_kind, before, _salt, _h = argon2_params(user["id"])
check(before["m"] == 12288 and before["t"] == 3, f"legacy hash not installed: {before}")
login(user["username"], user["password"])
_kind, after, _salt, stored = argon2_params(user["id"])
check(after["m"] >= 19456 and after != before, f"not rehashed: {after}")
login(user["username"], user["password"])
print(f"legacy hash m={before['m']},t={before['t']} -> after successful login m={after['m']},t={after['t']},"
f"p={after['p']}; the new hash still verifies")
print("PASS: old password hash is upgraded on successful login")
def test_errors_and_storage_do_not_reveal_credentials():
secret = "Leak-check-" + uuid.uuid4().hex
username = "leak_" + uuid.uuid4().hex[:10]
# неверное тело регистрации: ответ не повторяет пароль
reply = call("POST", "/api/v1/users", 400, body={"username": username, "display_name": "x",
"password": secret, "extra": 1})
check(secret not in reply.data.decode(), "400 echoes the password")
call("POST", "/api/v1/users", 201, body={"username": username, "display_name": "Leak", "password": secret})
reply = call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic(username, secret + "x")})
check(secret not in reply.data.decode() and username not in reply.data.decode(), "401 reveals input")
token = login(username, secret).json["token"]
keys = redis_cli("--scan", "--pattern", "'session:*'").split()
check(f"session:{hashlib.sha256(token.encode()).hexdigest()}" in keys, "session key is not SHA-256 of the token")
check(not any(token in key for key in keys), "plain token stored in Redis")
check(sql_value(f"SELECT count(*) FROM users WHERE password_hash LIKE '%{secret}%'") == "0", "password in DB")
print("errors do not echo credentials; Redis stores session:<SHA-256(token)> only; DB stores only the hash")
print("PASS: credentials and session tokens are not revealed")
if __name__ == "__main__":
tests = [test_https_only_and_certificate_checks, test_security_headers, test_outsider_cannot_reach_foreign_chat,
test_logout_revokes_token, test_login_rate_limit_is_shared, test_request_size_limits,
test_password_storage_argon2id, test_rehash_on_login, test_errors_and_storage_do_not_reveal_credentials]
selected = [t for t in tests if not sys.argv[1:] or t.__name__ in sys.argv[1:]]
run_tests(selected)
+192
View File
@@ -0,0 +1,192 @@
"""lab7: минимальные права identity сервисов — изнутри каждого сервиса, его же учётными данными.
python student-tests/test_least_privilege.py
В контейнерах api / worker / dispatcher / janitor выполняется скрипт, который берёт секреты так же, как сам
сервис (OpenBao по сертификату сервиса), и пробует разрешённые и запрещённые действия:
PostgreSQL — своя роль (GRANT из migrations/006_roles.sql), всё в транзакции с ROLLBACK;
S3 — свой ключ (права по prefix из s3_config), временные ключи probe-<uuid> удаляются;
OpenBao — свой токен (policy только на свой путь);
Redis — ACL-пользователь api (только session:* и ratelimit:*, только нужные команды).
Итог — таблица и evidence/least-privilege.json. Значения секретов не печатаются.
"""
import json
import subprocess
from common import EVIDENCE, ROOT, check
SCRIPT = r'''
import io, json, sys, uuid
import psycopg
import secretstore
from secretstore import store, Client, SecretsUnavailable
import settings
store.start()
role = settings.BAO_ROLE
results = []
def rec(area, action, expect, observed, detail=""):
results.append({"service": role, "area": area, "action": action, "expect": expect,
"observed": observed, "pass": observed == expect, "detail": str(detail)[:160]})
# ---------- PostgreSQL ----------
import dbconn
def sql(action, statement, expect):
try:
with dbconn.connect() as conn:
with conn.transaction():
conn.execute(statement)
raise _Rollback()
except _Rollback:
rec("postgres", action, expect, "allowed")
except psycopg.errors.InsufficientPrivilege as exc:
rec("postgres", action, expect, "denied", exc.diag.message_primary)
except psycopg.Error as exc:
rec("postgres", action, expect, "error", type(exc).__name__ + ": " + str(exc).splitlines()[0])
class _Rollback(Exception):
pass
PG = {
"api": [("SELECT users", "SELECT count(*) FROM users", "allowed"),
("INSERT outbox (enqueue)", "INSERT INTO outbox (job_id) SELECT NULL WHERE false", "allowed"),
("UPDATE users.username", "UPDATE users SET username = username WHERE false", "denied"),
("SELECT outbox", "SELECT count(*) FROM outbox", "denied"),
("DELETE messages", "DELETE FROM messages WHERE false", "denied"),
("DROP TABLE messages", "DROP TABLE messages", "denied"),
("CREATE TABLE", "CREATE TABLE probe_evil (x int)", "denied"),
("ALTER ROLE (escalate)", "ALTER ROLE messenger_api SUPERUSER", "denied")],
"worker": [("SELECT attachments", "SELECT count(*) FROM attachments", "allowed"),
("SELECT users (passwords)", "SELECT count(*) FROM users", "denied"),
("SELECT messages", "SELECT count(*) FROM messages", "denied"),
("DELETE attachments", "DELETE FROM attachments WHERE false", "denied"),
("UPDATE outbox", "UPDATE outbox SET published_at = published_at WHERE false", "denied")],
"dispatcher": [("SELECT outbox", "SELECT count(*) FROM outbox", "allowed"),
("SELECT users", "SELECT count(*) FROM users", "denied"),
("SELECT messages", "SELECT count(*) FROM messages", "denied"),
("DELETE attachments", "DELETE FROM attachments WHERE false", "denied")],
"janitor": [("SELECT attachments", "SELECT count(*) FROM attachments", "allowed"),
("SELECT users", "SELECT count(*) FROM users", "denied"),
("INSERT messages", "INSERT INTO messages (id) SELECT NULL WHERE false", "denied"),
("DELETE chats", "DELETE FROM chats WHERE false", "denied")],
}
for action, statement, expect in PG.get(role, []):
sql(action, statement, expect)
# ---------- S3 ----------
if role in ("api", "worker", "janitor"):
from botocore.exceptions import ClientError
import storage
client, bucket = storage._clients.get(), settings.S3_BUCKET
def s3(action, fn, expect):
try:
fn()
rec("s3", action, expect, "allowed")
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code", "?")
rec("s3", action, expect, "denied" if code in ("AccessDenied", "403", "Forbidden") else "error", code)
tag = "probe-" + uuid.uuid4().hex
put = lambda key: client.put_object(Bucket=bucket, Key=key, Body=b"probe")
get = lambda key: client.get_object(Bucket=bucket, Key=key)["Body"].read()
if role == "api":
s3("PUT staging/", lambda: put(f"staging/{tag}"), "allowed")
s3("DELETE staging/ (rollback)", lambda: client.delete_object(Bucket=bucket, Key=f"staging/{tag}"), "allowed")
s3("PUT attachments/ (worker's prefix)", lambda: put(f"attachments/{tag}"), "denied")
s3("GET staging/ (upload sources)", lambda: get("staging/none"), "denied")
s3("LIST bucket", lambda: client.list_objects_v2(Bucket=bucket, MaxKeys=1), "denied")
s3("DELETE attachments/", lambda: client.delete_object(Bucket=bucket, Key=f"attachments/{tag}"), "denied")
s3("CREATE bucket", lambda: client.create_bucket(Bucket="probe-" + uuid.uuid4().hex[:8]), "denied")
if role == "worker":
s3("PUT attachments/", lambda: put(f"attachments/{tag}"), "allowed")
s3("LIST attachments/", lambda: client.list_objects_v2(Bucket=bucket, Prefix="attachments/", MaxKeys=1),
"allowed")
s3("LIST bucket root", lambda: client.list_objects_v2(Bucket=bucket, MaxKeys=1), "denied")
s3("PUT outside known prefixes", lambda: put(f"evil/{tag}"), "denied")
s3("CREATE bucket", lambda: client.create_bucket(Bucket="probe-" + uuid.uuid4().hex[:8]), "denied")
try: # убрать за собой: у worker нет права удалить attachments/ — сделает janitor (сирота старше grace)
pass
finally:
pass
if role == "janitor":
s3("LIST bucket", lambda: client.list_objects_v2(Bucket=bucket, MaxKeys=1), "allowed")
s3("GET object content", lambda: get("staging/none"), "denied")
s3("CREATE bucket", lambda: client.create_bucket(Bucket="probe-" + uuid.uuid4().hex[:8]), "denied")
# ---------- OpenBao ----------
c = store._client
def bao(action, method, path, expect, body=None):
try:
c.request(method, path, body, token=c.token)
rec("openbao", action, expect, "allowed")
except SecretsUnavailable as exc:
rec("openbao", action, expect, "denied" if "HTTP 403" in str(exc) else "error", exc)
own = store._values.get(role, {})
rec("openbao", "own secret keys (no admin credentials)", "ok",
"ok" if not any(k.startswith(("db_owner", "s3_admin")) for k in own) else "has_admin_keys", sorted(own))
for other in ("api", "worker", "dispatcher", "janitor", "migrate", "s3-init"):
if other != role:
bao(f"read messenger/{other}", "GET", f"/v1/messenger/data/{other}", "denied")
bao("write own secret", "POST", f"/v1/messenger/data/{role}", "denied", {"data": {"x": "y"}})
bao("write ACL policy", "PUT", "/v1/sys/policies/acl/probe-evil", "denied", {"policy": 'path "*" {capabilities=["read"]}'})
bao("list auth methods", "GET", "/v1/sys/auth", "denied")
bao("create token", "POST", "/v1/auth/token/create", "denied", {"policies": ["api"]})
# ---------- Redis (только api) ----------
if role == "api":
import redis
import auth
r = auth._redis
def red(action, fn, expect):
try:
fn()
rec("redis", action, expect, "allowed")
except redis.exceptions.NoPermissionError as exc:
rec("redis", action, expect, "denied", exc)
except redis.RedisError as exc:
rec("redis", action, expect, "error", type(exc).__name__)
red("GET session:*", lambda: r.get("session:probe"), "allowed")
red("GET other key", lambda: r.get("probe:other"), "denied")
red("KEYS *", lambda: r.keys("*"), "denied")
red("FLUSHALL", lambda: r.flushall(), "denied")
red("CONFIG GET", lambda: r.config_get("*"), "denied")
red("ACL LIST", lambda: r.acl_list(), "denied")
red("SUBSCRIBE / PUBLISH", lambda: r.publish("probe", "x"), "denied")
print(json.dumps(results))
'''
def run_in(service):
result = subprocess.run(["docker", "compose", "exec", "-T", service, "python", "-"], cwd=ROOT,
input=SCRIPT.encode(), capture_output=True, check=False)
check(result.returncode == 0, f"{service}: {result.stderr.decode('utf-8', 'replace')[-600:]}")
return json.loads(result.stdout.decode("utf-8").strip().splitlines()[-1])
def main():
rows = []
for service in ("api", "worker", "dispatcher", "janitor"):
rows += run_in(service)
current = None
for row in rows:
if (row["service"], row["area"]) != current:
current = (row["service"], row["area"])
print(f"\n{row['service']} -> {row['area']}")
mark = "PASS" if row["pass"] else "FAIL"
print(f" {mark} {row['action']:<42} expect {row['expect']:<8} observed {row['observed']}"
+ ("" if row["pass"] else f" ({row['detail']})"))
(EVIDENCE / "least-privilege.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1),
encoding="utf-8")
failed = [r for r in rows if not r["pass"]]
print(f"\n{len(rows)} checks, {len(failed)} failed; saved to evidence/least-privilege.json")
check(not failed, "least privilege violated")
print("PASS: every service identity can do its job and nothing else that was probed")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAIL: {exc}")
raise SystemExit(1)
+57
View File
@@ -0,0 +1,57 @@
import threading
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from common import PASSWORD, call, check, new_chat, new_user, read_history, run_tests, send
CLIENTS = 10
MESSAGES_PER_CLIENT = 10
REGISTRATIONS = 20
def test_concurrent_messages():
users = [new_user(f"race{i}") for i in range(CLIENTS)]
chat = new_chat(*users, title="race")
barrier = threading.Barrier(CLIENTS) # все клиенты стартуют одновременно
def client(index):
barrier.wait()
for n in range(MESSAGES_PER_CLIENT):
send(users[index], chat["id"], f"client-{index}-message-{n}")
started = time.monotonic()
with ThreadPoolExecutor(max_workers=CLIENTS) as pool:
list(pool.map(client, range(CLIENTS))) # list() пробрасывает ошибки из потоков
elapsed = time.monotonic() - started
history, pages = read_history(users[0], chat["id"], limit=30)
ids = {message["id"] for message in history}
expected = {f"client-{i}-message-{n}" for i in range(CLIENTS) for n in range(MESSAGES_PER_CLIENT)}
print(f"sent {CLIENTS * MESSAGES_PER_CLIENT} messages from {CLIENTS} clients in {elapsed:.2f} s; "
f"read {len(history)} in {pages} pages, unique ids: {len(ids)}")
check(len(history) == CLIENTS * MESSAGES_PER_CLIENT, "wrong number of messages")
check(len(ids) == len(history), "duplicate message ids")
check({message["text"] for message in history} == expected, "lost or changed message texts")
print("PASS: 100 concurrent messages from 10 clients, no losses and no duplicates")
def test_concurrent_registration():
username = "race_" + uuid.uuid4().hex[:10]
barrier = threading.Barrier(REGISTRATIONS)
def register(index):
barrier.wait()
body = {"username": username, "display_name": f"Client {index}", "password": PASSWORD}
return call("POST", "/api/v1/users", (201, 409), body=body).status
with ThreadPoolExecutor(max_workers=REGISTRATIONS) as pool:
statuses = list(pool.map(register, range(REGISTRATIONS)))
created, conflicts = statuses.count(201), statuses.count(409)
print(f"{REGISTRATIONS} parallel registrations of one username: 201 x{created}, 409 x{conflicts}")
check(created == 1 and conflicts == REGISTRATIONS - 1, "exactly one registration must win")
print("PASS: concurrent registration created exactly one user")
if __name__ == "__main__":
run_tests([test_concurrent_messages, test_concurrent_registration])
+154
View File
@@ -0,0 +1,154 @@
"""S3 вне API: bucket приватный, ключ API ограничен, порты и веб-интерфейсы SeaweedFS не открыты, bootstrap идемпотентен.
lab7: S3 только по HTTPS (проверка учебного CA), у api/worker/janitor свои ключи с правами по prefix (из OpenBao);
admin-ключ — только у s3-init (тоже из OpenBao), в файлах контейнеров приложения его нет.
Нужен запущенный стенд из compose.yaml.
"""
import json
import socket
import images
from common import app_python, call, check, compose_output, new_chat, new_user, run_tests, sql_value, upload
# Анонимные запросы прямо в S3 (SeaweedFS) из сети data (из контейнера api), без подписи и без API.
ANONYMOUS = r'''
import json, sys, urllib.request, urllib.error
import settings, tlsutil
base = settings.S3_ENDPOINT.rstrip("/") + "/" + settings.S3_BUCKET
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}),
urllib.request.HTTPSHandler(context=tlsutil.client_context(cert=False)))
def status(method, url, data=None):
try:
with opener.open(urllib.request.Request(url, data=data, method=method), timeout=5) as r:
return r.status, r.read(300).decode("utf-8", "replace")
except urllib.error.HTTPError as e:
return e.code, e.read(300).decode("utf-8", "replace")
out = {}
for name, method, url, data in (("get_object", "GET", base + "/" + sys.argv[1], None),
("head_object", "HEAD", base + "/" + sys.argv[1], None),
("list_bucket", "GET", base + "?list-type=2", None),
("put_object", "PUT", base + "/originals/anonymous-test", b"x"),
("get_bucket_policy", "GET", base + "?policy", None)):
code, body = status(method, url, data)
out[name] = {"status": code, "s3_code": body.split("<Code>")[1].split("</Code>")[0] if "<Code>" in body else ""}
print(json.dumps(out))
'''
# Что разрешено и запрещено ключу API (политика infra/s3-api-policy.json).
API_KEY_RIGHTS = r'''
import io, json, sys, uuid
from botocore.exceptions import ClientError
import settings, storage
c, bucket = storage._clients.get(), settings.S3_BUCKET
def attempt(name, fn):
try:
fn(); return "allowed"
except ClientError as e:
return "denied: " + e.response.get("Error", {}).get("Code", "?")
public = json.dumps({"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Principal": {"AWS": ["*"]},
"Action": ["s3:GetObject"], "Resource": [f"arn:aws:s3:::{bucket}/*"]}]})
key = "staging/" + uuid.uuid4().hex # lab7: api пишет только в staging/
result = {
"get own object": attempt("get", lambda: c.get_object(Bucket=bucket, Key=sys.argv[1])["Body"].read()),
"put object": attempt("put", lambda: c.put_object(Bucket=bucket, Key=key, Body=b"x")),
"delete object": attempt("delete", lambda: c.delete_object(Bucket=bucket, Key=key)),
"put into attachments/ (worker's prefix)": attempt("put2", lambda: c.put_object(
Bucket=bucket, Key="attachments/" + uuid.uuid4().hex, Body=b"x")),
"list bucket": attempt("list", lambda: c.list_objects_v2(Bucket=bucket, MaxKeys=1)),
"create another bucket": attempt("create", lambda: c.create_bucket(Bucket="intruder-" + uuid.uuid4().hex[:8])),
"make bucket public (put policy)": attempt("policy", lambda: c.put_bucket_policy(Bucket=bucket, Policy=public)),
"read bucket policy": attempt("get_policy", lambda: c.get_bucket_policy(Bucket=bucket)),
"delete bucket": attempt("delete_bucket", lambda: c.delete_bucket(Bucket=bucket)),
"change versioning": attempt("versioning", lambda: c.put_bucket_versioning(
Bucket=bucket, VersioningConfiguration={"Status": "Enabled"})),
}
try: # хранилище может не отказать в ListBuckets, а показать только доступные ключу bucket
result["visible buckets"] = sorted(b["Name"] for b in c.list_buckets().get("Buckets", []))
except ClientError as e:
result["visible buckets"] = "denied: " + e.response.get("Error", {}).get("Code", "?")
print(json.dumps(result))
'''
def last_json(output):
return json.loads(output.splitlines()[-1])
def prepare():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
att = upload(alice, chat["id"], images.sample_png()).json
key = sql_value(f"SELECT object_key FROM attachments WHERE id = '{att['id']}'")
return alice, bob, att, key
def test_bucket_is_private():
alice, bob, att, key = prepare()
result = last_json(app_python(ANONYMOUS, key))
for name, reply in result.items():
print(f"anonymous {name} directly to S3 (from the data network) -> {reply['status']} {reply['s3_code']}")
check(reply["status"] in (401, 403), f"anonymous {name} must be refused, got {reply['status']}")
call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"])
print("the same file through the API for a chat member -> 200")
print("PASS: the bucket is private: no anonymous read, list, write or policy read")
def test_api_key_is_limited():
alice, bob, att, key = prepare()
result = last_json(app_python(API_KEY_RIGHTS, key))
allowed = {"get own object", "put object", "delete object"} # lab7: листинг — только у janitor
visible = result.pop("visible buckets")
print(f"API key: {'list buckets':<32} -> {visible}")
check(isinstance(visible, str) or len(visible) <= 1, "API key must not see other buckets")
for name, outcome in result.items():
print(f"API key: {name:<32} -> {outcome}")
if name in allowed:
check(outcome == "allowed", f"API key must be allowed to {name}")
else:
check(outcome.startswith("denied"), f"API key must NOT be allowed to {name}")
print("PASS: the API key can only read finished files and put/delete upload sources in staging/; "
"listing, other prefixes, bucket admin, policy and other buckets are denied")
def test_no_open_ports_or_console():
config = json.loads(compose_output("config", "--format", "json"))
s3 = config["services"]["s3"]
check(not s3.get("ports"), "s3 must not publish ports")
check(sorted(s3["networks"]) == ["data"], "s3 must be only in the internal data network")
check(config["networks"]["data"].get("internal") is True, "data network must be internal")
print("compose: s3 has no published ports, only the internal network 'data' (S3 8333, master UI 9333, "
"filer UI 8888 are reachable only inside the stand)")
for port in (8333, 18333): # lab7: master/volume/filer слушают только loopback контейнера
sock = socket.socket()
sock.settimeout(1)
refused = sock.connect_ex(("127.0.0.1", port)) != 0
sock.close()
check(refused, f"127.0.0.1:{port} is reachable from the host")
print(f"127.0.0.1:{port} from the host -> connection refused")
secrets = {name: sorted(s["source"] for s in svc.get("secrets", [])) for name, svc in config["services"].items()}
for name, items in sorted(secrets.items()):
if items:
print(f"file secrets of {name}: {items}")
for name in ("api", "janitor", "worker", "dispatcher"):
check(not secrets.get(name), f"{name} must not get file secrets (lab7: credentials come from OpenBao)")
check(secrets.get("s3") == ["s3_config"], "only s3 itself reads the key config")
print("PASS: S3 is reachable only inside the stand (HTTPS); the key config is only in s3; services get their "
"own limited keys from OpenBao, the admin key only s3-init")
def test_bootstrap_is_idempotent():
alice, bob, att, key = prepare()
output = compose_output("run", "--rm", "--no-deps", "s3-init")
print("\n".join("s3-init: " + line for line in output.strip().splitlines() if line.strip()))
check("bucket is private" in output, "bootstrap did not confirm a private bucket")
got = call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"])
check(got.data == images.sample_png(), "file changed after repeated bootstrap")
upload(alice, att["chat_id"], images.sample_png())
print("after the repeated bootstrap: old file downloads, new upload works")
print("PASS: bucket/user/policy bootstrap can be repeated safely")
if __name__ == "__main__":
run_tests([test_bucket_is_private, test_api_key_is_limited, test_no_open_ports_or_console,
test_bootstrap_is_idempotent])
+264
View File
@@ -0,0 +1,264 @@
"""Lab6: связь запроса, структурного лога и трассы; сквозная трасса upload -> worker, включая retry.
python student-tests/test_telemetry.py # все сценарии
python student-tests/test_telemetry.py upload-chain # один (список SCENARIOS ниже)
Нужен запущенный стенд (compose.yaml, FAULT_INJECTION=1 для retry/replay). Клиент сам задаёт W3C
traceparent запроса, поэтому трасса находится в Tempo по известному trace_id, без поиска «похожей».
Тест печатает дерево спанов (без данных пользователя) — это доказательство для отчёта.
Сценарии:
request уровень 3: POST сообщения -> server-спан API с дочерними спанами PostgreSQL/Redis,
запись лога event=http.request с тем же trace_id/span_id и request_id из X-Request-Id;
текст сообщения, пароль и токен не попали ни в логи (Loki), ни в атрибуты спанов.
upload-chain уровень 4: одна трасса API(server) -> create(producer, outbox) -> dispatcher publish
(producer) -> worker process (consumer) -> S3 PutObject x4 и COMMIT ready; логи worker
с тем же trace_id.
retry-chain уровень 4: временная ошибка S3 в worker (fault worker_s3_error) -> в той же трассе
попытка 1 (ERROR, outcome=retry) -> новая публикация -> попытка 2 (ready).
replay-link уровень 4: попытки исчерпаны -> failed -> ops.py replay создаёт НОВУЮ трассу со
ссылкой (link) на исходную загрузку, worker завершает её в ready.
history уровень 3: после restart prometheus/loki/tempo (volumes сохранены) прежние трасса,
логи и метрика по-прежнему находятся.
"""
import json
import subprocess
import sys
import time
import uuid
import obs
from common import ROOT, call, check, compose, new_chat, new_user, run_tests, wait_attachment
from images import png
LOKI_WAIT = 60
TRACE_WAIT = 60
def upload_traced(user, chat_id, data, traceparent, filename="trace.png"):
reply = call("POST", f"/api/v1/chats/{chat_id}/attachments?filename={filename}", 202, raw=data,
token=user["token"], headers={"Content-Type": "image/png", "traceparent": traceparent})
return reply
def by_name(spans, name, service=None):
return [s for s in spans if s["name"] == name and (service is None or s["service"] == service)]
def parent_of(spans, span):
return next((s for s in spans if s["span_id"] == span["parent_id"]), None)
def fault(point, count=1):
for n in range(count):
subprocess.run(["docker", "compose", "exec", "-T", "worker", "sh", "-c", f"touch /faults/{point}.{n + 1}"],
cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def ops(*args):
result = subprocess.run(["docker", "compose", "exec", "-T", "dispatcher", "python", "ops.py", *map(str, args)],
cwd=ROOT, capture_output=True, check=True)
return json.loads(result.stdout.decode("utf-8"))
# ---------- сценарии ----------
def test_request():
user = new_user("trace")
chat = new_chat(user, title="Trace chat")
marker = f"secret-text-{uuid.uuid4().hex}"
trace_id, traceparent = obs.new_traceparent()
reply = call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, token=user["token"], body={"text": marker},
headers={"Idempotency-Key": uuid.uuid4().hex, "traceparent": traceparent})
request_id = reply.headers["x-request-id"]
check(reply.headers.get("x-trace-id") == trace_id, "X-Trace-Id must continue the client's traceparent")
print(f"POST message: 201, X-Request-Id={request_id}, trace_id={trace_id} (client traceparent)")
spans = obs.wait_trace(trace_id, lambda s: by_name(s, "POST /api/v1/chats/{chat_id}/messages", "messenger-api")
and any(x["kind"] == "CLIENT" and x["name"] == "INSERT" for x in s), TRACE_WAIT)
server = by_name(spans, "POST /api/v1/chats/{chat_id}/messages", "messenger-api")[0]
check(server["kind"] == "SERVER" and server["attrs"].get("http.response.status_code") == 201, "server span")
check(server["attrs"].get("http.route") == "/api/v1/chats/{chat_id}/messages", "route template in span")
db = [s for s in spans if s["parent_id"] == server["span_id"] and "db.statement" in s["attrs"]
or "db.query.text" in s["attrs"]]
check(db, "PostgreSQL client spans under the server span")
check(by_name(spans, "redis GET", "messenger-api"), "Redis session lookup span")
print(obs.span_tree(spans))
rows = obs.wait_logs(f'{{service_name="messenger-api"}} | trace_id="{trace_id}" | event="http.request"',
1, LOKI_WAIT)
labels, line = rows[0]
check(labels.get("request_id") == request_id, "log request_id == X-Request-Id")
check(labels.get("span_id") == server["span_id"], "log span_id == server span id")
for field in ("service_name", "severity_text", "event", "trace_id", "span_id"):
check(labels.get(field), f"log field {field} is missing")
print(f"Loki: {line!r} event={labels['event']} severity={labels['severity_text']} "
f"service={labels['service_name']} trace_id={labels['trace_id']} span_id={labels['span_id']} "
f"request_id={labels['request_id']}")
# Ни текст сообщения, ни пароль, ни токен не попали в телеметрию.
for secret, what in ((marker, "message text"), (user["password"], "password"), (user["token"][:24], "token")):
found = obs.loki_query(f'{{service_name=~"messenger-.*"}} |= `{secret}`', minutes=10, limit=5)
check(not found, f"{what} found in Loki logs")
check(not any(secret in str(v) for s in spans for v in s["attrs"].values()), f"{what} found in span attributes")
check(not any(k.lower().startswith(("http.request.header.authorization", "enduser")) for s in spans
for k in s["attrs"]), "Authorization/enduser attributes in spans")
print("PASS: request -> server span with DB/Redis children -> structured log with the same trace_id/span_id "
"and request_id; no message text, password or token in logs/span attributes")
def test_upload_chain():
user = new_user("chain")
chat = new_chat(user, title="Chain chat")
trace_id, traceparent = obs.new_traceparent()
accepted = upload_traced(user, chat["id"], png(320, 200), traceparent).json
ready = wait_attachment(user, accepted["id"])
check(ready["status"] == "ready", f"attachment is {ready['status']}")
def complete(spans):
# Ждём span'ы всех трёх процессов: каждый выгружает свой batch (до OTEL_BSP_SCHEDULE_DELAY, 5 с)
# независимо, и в Docker batch worker нередко приходит в Tempo раньше batch API.
return (by_name(spans, "commit result", "messenger-worker") and by_name(spans, "cleanup staging")
and by_name(spans, "POST /api/v1/chats/{chat_id}/attachments", "messenger-api")
and by_name(spans, "create attachments", "messenger-api"))
spans = obs.wait_trace(trace_id, complete, TRACE_WAIT)
print(obs.span_tree(spans))
server = by_name(spans, "POST /api/v1/chats/{chat_id}/attachments", "messenger-api")[0]
create = by_name(spans, "create attachments", "messenger-api")[0]
publish = by_name(spans, "publish attachments", "messenger-dispatcher")[0]
consume = by_name(spans, "process attachments.process.v1", "messenger-worker")[0]
check(create["kind"] == "PRODUCER" and publish["kind"] == "PRODUCER" and consume["kind"] == "CONSUMER", "kinds")
check(parent_of(spans, create)["span_id"] == server["span_id"], "create is a child of the API request")
check(publish["parent_id"] == create["span_id"], "publish (dispatcher) is a child of create (API outbox)")
check(consume["parent_id"] == publish["span_id"], "consume (worker) is a child of publish (W3C via AMQP headers)")
check(consume["attrs"].get("messenger.job.outcome") == "ready", "consumer outcome ready")
puts = [s for s in by_name(spans, "S3 PutObject", "messenger-worker")
if s["attrs"].get("aws.s3.key", "").startswith(f"attachments/{accepted['id']}/v1/")]
check(len(puts) == 4, f"4 PUTs of the final objects, got {len(puts)}")
check({s["service"] for s in spans} >= {"messenger-api", "messenger-dispatcher", "messenger-worker"}, "services")
events = {labels["event"] for labels, _ in obs.wait_logs(
f'{{service_name="messenger-worker"}} | trace_id="{trace_id}"', 2, LOKI_WAIT)}
check({"job.claimed", "job.ready"} <= events, f"worker logs with this trace_id: {events}")
print(f"worker logs with trace_id {trace_id}: {sorted(events)}")
print(f"PASS: one trace {trace_id}: API 202 -> outbox create -> dispatcher publish -> worker consume -> "
f"4 S3 objects + COMMIT ready ({len(spans)} spans, services: "
f"{', '.join(sorted({s['service'] for s in spans}))})")
def test_retry_chain():
user = new_user("retry")
chat = new_chat(user, title="Retry chat")
before = obs.prom_value('sum(messenger_job_duration_seconds_count{outcome="retry"})', 0.0)
fault("worker_s3_error", 1)
trace_id, traceparent = obs.new_traceparent()
accepted = upload_traced(user, chat["id"], png(64, 48), traceparent).json
ready = wait_attachment(user, accepted["id"])
check(ready["status"] == "ready", f"attachment is {ready['status']}")
def complete(spans):
# + обе публикации dispatcher: его batch выгружается независимо от batch worker (см. test_upload_chain)
return (len(by_name(spans, "process attachments.process.v1")) >= 2 and by_name(spans, "commit result")
and len(by_name(spans, "publish attachments")) >= 2)
spans = obs.wait_trace(trace_id, complete, TRACE_WAIT)
print(obs.span_tree(spans))
attempts = sorted(by_name(spans, "process attachments.process.v1", "messenger-worker"), key=lambda s: s["start"])
first, second = attempts[0], attempts[-1]
check(first["status"] == "ERROR" and first["attrs"].get("messenger.job.outcome") == "retry", "attempt 1 = retry")
check(first["attrs"].get("error.type") == "storage_unavailable", "attempt 1 error.type")
check(second["attrs"].get("messenger.job.outcome") == "ready", "attempt 2 = ready")
retry_create = [s for s in by_name(spans, "create attachments") if s["parent_id"] == first["span_id"]]
check(retry_create, "retry message is created inside attempt 1 (outbox in the same transaction)")
second_publish = parent_of(spans, second)
check(second_publish["name"] == "publish attachments" and second_publish["parent_id"] == retry_create[0]["span_id"],
"attempt 2 consumes the retry publication")
check(len(by_name(spans, "publish attachments")) == 2, "two publications in one trace")
rows = obs.wait_logs(f'{{service_name="messenger-worker"}} | trace_id="{trace_id}" | event="job.retry"', 1, LOKI_WAIT)
print(f"worker log: {rows[0][1]!r} error_type={rows[0][0].get('error_type')}")
after = obs.wait_metric('sum(messenger_job_duration_seconds_count{outcome="retry"})', lambda v: v > before, 40)
print(f"messenger_job_duration_seconds_count{{outcome=\"retry\"}}: {before:g} -> {after:g}")
print(f"PASS: retry in one trace {trace_id}: attempt 1 ERROR storage_unavailable -> create -> publish -> "
f"attempt 2 ready; retry counted in metrics and logged")
def test_replay_link():
user = new_user("replay")
chat = new_chat(user, title="Replay chat")
fault("worker_s3_error", 5)
trace_id, traceparent = obs.new_traceparent()
accepted = upload_traced(user, chat["id"], png(32, 32), traceparent).json
failed = wait_attachment(user, accepted["id"], statuses=("failed",), seconds=120)
check(failed["error_code"] == "retry_exhausted", f"error_code {failed['error_code']}")
job = next(j for j in ops("failed", "--limit", "20") if j["attachment_id"] == accepted["id"])
result = ops("replay", job["job_id"], "--reason", "lab6 link test")
check("replayed" in result, f"replay refused: {result}")
ready = wait_attachment(user, accepted["id"])
check(ready["status"] == "ready", "ready after replay")
original = obs.wait_trace(trace_id, lambda s: len(by_name(s, "process attachments.process.v1")) >= 5, TRACE_WAIT)
print(f"original trace {trace_id}: {len(by_name(original, 'process attachments.process.v1'))} attempts, "
f"last outcome {sorted(by_name(original, 'process attachments.process.v1'), key=lambda s: s['start'])[-1]['attrs'].get('messenger.job.outcome')}")
found = None
deadline = time.monotonic() + TRACE_WAIT
while found is None and time.monotonic() < deadline:
for item in obs.tempo_search(f'{{ name = "create attachments" && span.messenger.job.id = "{job["job_id"]}" }}',
minutes=15, limit=20):
if item["traceID"].rjust(32, "0") != trace_id:
found = item["traceID"].rjust(32, "0")
if found is None:
time.sleep(2)
check(found, "replay trace not found")
spans = obs.wait_trace(found, lambda s: by_name(s, "commit result"), TRACE_WAIT)
print(obs.span_tree(spans))
create = by_name(spans, "create attachments")[0]
linked = {link["trace_id"] for link in create["links"]}
check(trace_id in linked, f"create span of the replay links to the original trace {trace_id}: {linked}")
print(f"replay trace {found}: create span links -> {sorted(linked)} (original upload trace {trace_id})")
check(by_name(spans, "ops replay"), "ops replay span is the root of the new trace")
check(by_name(spans, "process attachments.process.v1")[0]["attrs"].get("messenger.job.outcome") == "ready",
"replayed attempt ready")
print("PASS: replay = new trace (root 'ops replay') with a link to the original upload; worker finished it")
def test_history():
user = new_user("history")
chat = new_chat(user, title="History chat")
trace_id, traceparent = obs.new_traceparent()
call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, token=user["token"], body={"text": "history"},
headers={"Idempotency-Key": uuid.uuid4().hex, "traceparent": traceparent})
obs.wait_trace(trace_id, seconds=TRACE_WAIT)
obs.wait_logs(f'{{service_name="messenger-api"}} | trace_id="{trace_id}"', 1, LOKI_WAIT)
query = 'sum(http_server_request_duration_seconds_count{job="messenger-api"})'
stamp = round(time.time() - 30) # значение на момент t-30 с (параметр time запроса API Prometheus)
rows = obs.prom_query(query, at=stamp)
before = rows[0][1] if rows else None
check(before, "metric sample before restart")
print(f"before restart: trace {trace_id} found, its log found, {query} at t-30s = {before:g}")
compose("restart", "prometheus", "loki", "tempo")
deadline = time.monotonic() + 120
while True:
try:
spans = obs.tempo_trace(trace_id)
logs = obs.loki_query(f'{{service_name="messenger-api"}} | trace_id="{trace_id}"')
rows = obs.prom_query(query, at=stamp)
after = rows[0][1] if rows else None
if spans and logs and after == before:
break
except OSError:
pass
check(time.monotonic() < deadline, "history not available 120 s after restart")
time.sleep(3)
print(f"after restart of prometheus, loki, tempo: trace {trace_id} ({len(spans)} spans), "
f"{len(logs)} log record(s), metric at t-30s = {after:g} (same value)")
print("PASS: persistent volumes keep traces, logs and metrics across restarts of the stores")
SCENARIOS = {"request": test_request, "upload-chain": test_upload_chain, "retry-chain": test_retry_chain,
"replay-link": test_replay_link, "history": test_history}
if __name__ == "__main__":
names = sys.argv[1:] or list(SCENARIOS)
unknown = [n for n in names if n not in SCENARIOS]
if unknown:
raise SystemExit(f"unknown scenarios {unknown}; available: {', '.join(SCENARIOS)}")
run_tests([SCENARIOS[n] for n in names])
+51
View File
@@ -0,0 +1,51 @@
"""lab7: TLS/mTLS-аудит всей trust matrix (contracts/trust-matrix.md) изнутри внутренних сетей.
python student-tests/test_tls_matrix.py [группа ...] # группы: lb-api broker collector postgres redis s3
# openbao telemetry (по умолчанию все)
Запускает student-tests/tls_probe.py в одноразовом контейнере probe (compose profile tools): он во всех
внутренних сетях, но без ключа CA, паролей и токенов. Результат — таблица и evidence/tls-matrix.json.
"""
import json
import subprocess
import sys
from common import EVIDENCE, ROOT, check
def main():
groups = sys.argv[1:]
result = subprocess.run(["docker", "compose", "--profile", "tools", "run", "--rm", "-T", "probe",
"python", "/probe/tls_probe.py", "matrix", *groups],
cwd=ROOT, capture_output=True, check=False)
rows, summary = [], None
for line in result.stdout.decode("utf-8", "replace").splitlines():
try:
item = json.loads(line)
except ValueError:
continue
if item.get("summary"):
summary = item
else:
rows.append(item)
check(summary is not None, "probe did not finish: " + result.stderr.decode("utf-8", "replace")[-600:])
link = None
for row in rows:
if row["link"] != link:
link = row["link"]
print(f"\n{link}")
mark = "PASS" if row["pass"] else "FAIL"
print(f" {mark} {row['case']:<58} -> {row['observed']}"
+ ("" if row["pass"] else f" (expected {row['expect']}; {row['detail'][:120]})"))
out = EVIDENCE / "tls-matrix.json"
out.write_text(json.dumps({"summary": summary, "checks": rows}, ensure_ascii=False, indent=1), encoding="utf-8")
print(f"\n{summary['checks']} checks, {summary['failed']} failed; saved to {out}")
check(summary["failed"] == 0, "trust matrix has failed checks")
print("PASS: every link of the trust matrix accepts the allowed identity and rejects the rest")
if __name__ == "__main__":
try:
main()
except AssertionError as exc:
print(f"FAIL: {exc}")
raise SystemExit(1)
+396
View File
@@ -0,0 +1,396 @@
"""TLS/mTLS-аудит trust matrix изнутри внутренних сетей (lab7).
Запуск на стенде: python student-tests/test_tls_matrix.py (сам вызывает этот файл в контейнере probe)
Вручную: docker compose --profile tools run --rm probe python /probe/tls_probe.py matrix
Контейнер probe подключён ко всем внутренним сетям и получает только: CA, сертификаты test/* (чужой CA,
чужая identity нашего CA, истёкший) и клиентские сертификаты, которыми пробует войти «не туда»
(lb, api, worker, dispatcher, janitor, grafana, otel-collector, operator). Ключа CA, паролей и токенов
OpenBao у него нет. Для каждой связи: правильная identity проходит, остальные — отказ, причём отказ
именно проверки (сертификат/identity/права), а не «сервер недоступен».
Вывод — JSON-строка на проверку и итог; код выхода 1, если хоть одно ожидание не выполнено.
"""
import http.client
import json
import os
import socket
import ssl
import sys
import time
PKI = os.environ.get("PKI", "/pki")
CA = f"{PKI}/public/ca.crt"
ROGUE_CA = f"{PKI}/test/rogue-ca/ca.crt"
SANDBOX = os.environ.get("SANDBOX") == "1"
# Адреса: в Docker — имена сервисов; в нативной песочнице — loopback-адреса процессов (имя для SNI то же).
ADDR = {"api": ("127.0.1.11" if SANDBOX else "api"), "postgres": "postgres", "redis": "redis", "s3": "s3",
"rabbitmq": "rabbitmq", "openbao": "openbao", "otel-collector": "otel-collector",
"prometheus": "prometheus", "loki": "loki", "tempo": "tempo", "grafana": "grafana"}
RESULTS = []
def cert(name):
return (f"{PKI}/{name}/tls.crt", f"{PKI}/{name}/tls.key") if name else None
def ctx(client=None, ca=CA, check_hostname=True):
context = ssl.create_default_context(cafile=ca)
context.check_hostname = check_hostname
context.minimum_version = ssl.TLSVersion.TLSv1_2
if client:
context.load_cert_chain(*cert(client))
return context
def classify(exc):
"""Причина отказа: проверка сертификата/identity — засчитывается; сеть — нет."""
text = f"{type(exc).__name__}: {exc}"
lowered = text.lower()
if isinstance(exc, ssl.SSLCertVerificationError) or "certificate verify failed" in lowered:
return "client_rejected_server_cert", text
for marker in ("certificate required", "unknown ca", "bad certificate", "certificate expired",
"certificate revoked", "handshake failure", "access denied", "certificate unknown"):
if marker in lowered:
return "server_rejected_client_cert", text
if isinstance(exc, (ConnectionResetError, BrokenPipeError)) or "eof occurred" in lowered \
or "unexpected eof" in lowered or "connection reset" in lowered or isinstance(exc, ssl.SSLZeroReturnError):
return "connection_closed_after_handshake", text
if isinstance(exc, (ConnectionRefusedError, socket.gaierror)) or "timed out" in lowered:
return "unreachable", text
return "error", text
def record(link, case, expect, outcome, detail=""):
ok = outcome in expect if isinstance(expect, (list, tuple, set)) else outcome == expect
RESULTS.append({"link": link, "case": case, "expect": expect, "observed": outcome, "pass": ok,
"detail": detail[:220]})
print(json.dumps(RESULTS[-1], ensure_ascii=False), flush=True)
def https_get(host, port, path, client=None, ca=CA, timeout=5, method="GET", body=None, headers=None):
"""HTTPS-запрос: TCP к адресу сервиса, проверка сертификата по CA и ИМЕНИ сервиса (SNI = host)."""
conn = http.client.HTTPSConnection(host, port, timeout=timeout)
def connect():
raw = socket.create_connection((ADDR.get(host, host), port), timeout)
conn.sock = ctx(client, ca).wrap_socket(raw, server_hostname=host)
conn.connect = connect
try:
conn.request(method, path, body=body, headers=headers or {})
reply = conn.getresponse()
return reply.status, reply.read(300)
finally:
conn.close()
def http_case(link, case, host, port, path, client, expect, ca=CA, method="GET", body=None, headers=None):
try:
status, _ = https_get(host, port, path, client, ca, method=method, body=body, headers=headers)
record(link, case, expect, f"http_{status}")
except Exception as exc: # noqa: BLE001
outcome, text = classify(exc)
record(link, case, expect, outcome, text)
def plaintext_case(link, host, port, payload=b"GET / HTTP/1.0\r\n\r\n"):
"""Незашифрованный клиент на TLS-порт: ответа в открытом виде быть не должно."""
try:
with socket.create_connection((ADDR.get(host, host), port), timeout=5) as sock:
sock.sendall(payload)
data = sock.recv(200)
# HTTP-сервер Go отвечает 400 «client sent an HTTP request to an HTTPS server» — это не обход
if b"HTTP/1.0 400" in data or b"HTTP/1.1 400" in data or not data:
record(link, "plaintext client", ["no_plaintext_service"], "no_plaintext_service", repr(data[:60]))
elif data.startswith(b"\x15\x03"): # TLS alert
record(link, "plaintext client", ["no_plaintext_service"], "no_plaintext_service", "tls alert")
else:
record(link, "plaintext client", ["no_plaintext_service"], "plaintext_answer", repr(data[:80]))
except Exception as exc: # noqa: BLE001
outcome, text = classify(exc)
record(link, "plaintext client", ["no_plaintext_service"],
"no_plaintext_service" if outcome != "unreachable" else "unreachable", text)
# ---------------- связи ----------------
def lb_api():
link = "LB -> API (mTLS, allowlist CN=lb)"
rejected = ["server_rejected_client_cert", "connection_closed_after_handshake"]
http_case(link, "valid LB identity (CN=lb)", "api", 8443, "/health/ready", "lb", "http_200")
http_case(link, "no client certificate", "api", 8443, "/health/ready", None, rejected)
http_case(link, "foreign CA, CN=lb", "api", 8443, "/health/ready", "test/rogue-lb", rejected)
http_case(link, "our CA, expired, CN=lb", "api", 8443, "/health/ready", "test/expired-lb", rejected)
http_case(link, "our CA, CN=intruder", "api", 8443, "/health/ready", "test/intruder", rejected)
http_case(link, "our CA, CN=worker (other service)", "api", 8443, "/health/ready", "worker", rejected)
http_case(link, "our CA, CN=api (server's own identity)", "api", 8443, "/health/ready", "api", rejected)
http_case(link, "server identity: client trusts only foreign CA", "api", 8443, "/health/ready", "lb",
"client_rejected_server_cert", ca=ROGUE_CA)
if os.path.exists(f"{PKI}/lb/previous/tls.crt"):
http_case(link, "previous (rotated, revoked) LB leaf", "api", 8443, "/health/ready", "lb/previous", rejected)
plaintext_case(link, "api", 8443)
def broker():
import pika
link = "API/worker -> RabbitMQ (mTLS + EXTERNAL, CN = broker user)"
def connect(client, ca=CA):
params = pika.ConnectionParameters(host=ADDR["rabbitmq"], port=5671, virtual_host="messenger",
ssl_options=pika.SSLOptions(ctx(client, ca), server_hostname="rabbitmq"),
credentials=pika.credentials.ExternalCredentials(),
connection_attempts=1, socket_timeout=5, blocked_connection_timeout=5)
return pika.BlockingConnection(params)
def attempt(case, expect, client, action=None, ca=CA):
try:
connection = connect(client, ca)
try:
if action:
action(connection.channel())
record(link, case, expect, "allowed")
finally:
try:
connection.close()
except Exception: # noqa: BLE001
pass
except pika.exceptions.ProbableAuthenticationError as exc:
record(link, case, expect, "login_refused", str(exc))
except pika.exceptions.ChannelClosedByBroker as exc:
record(link, case, expect, f"access_refused_{exc.reply_code}", str(exc))
except Exception as exc: # noqa: BLE001
cause = exc
if isinstance(exc, pika.exceptions.AMQPConnectionError) and exc.args:
cause = exc.args[0] if isinstance(exc.args[0], Exception) else exc
outcome, text = classify(cause)
if outcome == "error" and "ssl" in str(exc).lower():
outcome = "server_rejected_client_cert"
record(link, case, expect, outcome, text)
rejected = ["server_rejected_client_cert", "connection_closed_after_handshake", "error"]
attempt("worker identity consumes its queue", "allowed", "worker",
lambda ch: ch.queue_declare("attachments.process.v1", passive=True))
attempt("dispatcher identity publishes to exchange", "allowed", "dispatcher",
lambda ch: (ch.confirm_delivery(), ch.exchange_declare("attachments", passive=True)))
attempt("CN=api (no broker user, API uses outbox)", "login_refused", "api")
attempt("our CA, CN=intruder", "login_refused", "test/intruder")
attempt("our CA, CN=lb", "login_refused", "lb")
attempt("foreign CA, CN=worker", rejected, "test/rogue-worker")
attempt("no client certificate", rejected, None)
attempt("worker publishes (not allowed)", "access_refused_403", "worker",
lambda ch: (ch.confirm_delivery(), ch.basic_publish("attachments", "attachment.process.v1", b"{}",
mandatory=True)))
attempt("dispatcher consumes main queue (not allowed)", "access_refused_403", "dispatcher",
lambda ch: ch.basic_get("attachments.process.v1"))
attempt("worker declares a queue (no configure)", "access_refused_403", "worker",
lambda ch: ch.queue_declare("probe-evil-queue"))
plaintext_case(link, "rabbitmq", 5671, b"AMQP\x00\x00\x09\x01")
def collector():
link = "API/worker -> OTel Collector (mTLS via otel-gate, allowlist app CNs)"
rejected = ["server_rejected_client_cert", "connection_closed_after_handshake"]
otlp = {"Content-Type": "application/x-protobuf"}
for identity in ("api", "worker", "dispatcher", "janitor"):
http_case(link, f"CN={identity} sends OTLP logs", "otel-collector", 4318, "/v1/logs", identity,
["http_200", "http_400"], method="POST", body=b"", headers=otlp)
for identity in ("lb", "grafana", "test/intruder", "operator"):
http_case(link, f"our CA, CN={identity.split('/')[-1]} (not an app) sends OTLP", "otel-collector", 4318,
"/v1/logs", identity, "http_403", method="POST", body=b"", headers=otlp)
http_case(link, "foreign CA, CN=worker", "otel-collector", 4318, "/v1/logs", "test/rogue-worker", rejected,
method="POST", body=b"", headers=otlp)
http_case(link, "no client certificate", "otel-collector", 4318, "/v1/logs", None, rejected,
method="POST", body=b"", headers=otlp)
# песочница: на 127.0.0.1:8888 вместо Collector отвечает filer SeaweedFS (общий loopback) — важно лишь «не 403»
http_case(link, "Collector self-metrics, CN=operator", "otel-collector", 8889, "/metrics", "operator",
["http_200", "http_404"] if SANDBOX else "http_200")
http_case(link, "Collector self-metrics, CN=api (not allowed)", "otel-collector", 8889, "/metrics", "api",
"http_403")
plaintext_case(link, "otel-collector", 4318)
def postgres():
import psycopg
link = "API/worker -> PostgreSQL (TLS verify-full, SCRAM, roles)"
def attempt(case, expect, **kwargs):
params = {"host": ADDR["postgres"], "port": 5432, "dbname": "messenger", "user": "messenger_api",
"password": "wrong-password-probe", "connect_timeout": 5, "sslcertmode": "disable"}
params.update(kwargs)
try:
psycopg.connect(**params).close()
record(link, case, expect, "connected")
except psycopg.OperationalError as exc:
text = str(exc)
lowered = text.lower()
if "password authentication failed" in lowered:
outcome = "tls_ok_auth_failed"
elif "no pg_hba.conf entry" in lowered or "no encryption" in lowered:
outcome = "rejected_no_tls"
elif "certificate verify failed" in lowered or "server certificate for" in lowered \
or "does not match host name" in lowered:
outcome = "client_rejected_server_cert"
else:
outcome = "error"
record(link, case, expect, outcome, text.replace("\n", " "))
attempt("TLS verify-full with our CA (wrong password on purpose)", "tls_ok_auth_failed",
sslmode="verify-full", sslrootcert=CA)
attempt("plaintext (sslmode=disable)", "rejected_no_tls", sslmode="disable")
attempt("trust foreign CA only", "client_rejected_server_cert", sslmode="verify-full", sslrootcert=ROGUE_CA)
if not SANDBOX:
import socket as _s
attempt("connect by IP: name does not match certificate", "client_rejected_server_cert",
host=_s.gethostbyname("postgres"), sslmode="verify-full", sslrootcert=CA)
def redis_link():
link = "API -> Redis (TLS + client cert of our CA + ACL user)"
def attempt(case, expect, client, ca=CA, command=b"*1\r\n$4\r\nPING\r\n"):
try:
with socket.create_connection((ADDR["redis"], 6379), timeout=5) as raw:
with ctx(client, ca).wrap_socket(raw, server_hostname="redis") as tls:
tls.sendall(command)
reply = tls.recv(200)
outcome = "noauth" if b"NOAUTH" in reply else ("wrongpass" if b"WRONGPASS" in reply else
("pong" if b"PONG" in reply else "reply"))
record(link, case, expect, outcome, reply[:80].decode("latin-1"))
except Exception as exc: # noqa: BLE001
outcome, text = classify(exc)
record(link, case, expect, outcome, text)
rejected = ["server_rejected_client_cert", "connection_closed_after_handshake"]
attempt("our CA client cert, no AUTH", "noauth", "test/intruder")
attempt("our CA, AUTH api with a wrong password", "wrongpass", "worker",
command=b"*3\r\n$4\r\nAUTH\r\n$3\r\napi\r\n$5\r\nwrong\r\n")
attempt("no client certificate", rejected, None)
attempt("foreign CA client certificate", rejected, "test/rogue-worker")
attempt("trust foreign CA only", "client_rejected_server_cert", "worker", ca=ROGUE_CA)
plaintext_case(link, "redis", 6379, b"*1\r\n$4\r\nPING\r\n")
def s3():
link = "API/worker -> S3 (HTTPS + per-service keys by prefix)"
http_case(link, "HTTPS anonymous list (no signature)", "s3", 8333, "/messenger-attachments?list-type=2", None,
"http_403")
http_case(link, "trust foreign CA only", "s3", 8333, "/", None, "client_rejected_server_cert", ca=ROGUE_CA)
plaintext_case(link, "s3", 8333)
# gRPC шлюза SeaweedFS: только mTLS c CN=s3 (security.toml)
for case, client, expect in (("S3 gRPC :18333, CN=intruder (our CA)", "test/intruder",
["server_rejected_client_cert", "connection_closed_after_handshake"]),
("S3 gRPC :18333, CN=api (our CA)", "api",
["server_rejected_client_cert", "connection_closed_after_handshake"]),
("S3 gRPC :18333, no client certificate", None,
["server_rejected_client_cert", "connection_closed_after_handshake"])):
try:
context = ctx(client)
context.set_alpn_protocols(["h2"])
with socket.create_connection((ADDR["s3"] if not SANDBOX else "127.0.1.20", 18333), timeout=5) as raw:
with context.wrap_socket(raw, server_hostname="s3") as tls:
tls.sendall(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" + b"\x00\x00\x00\x04\x00\x00\x00\x00\x00")
data = tls.recv(100)
data += tls.recv(100)
record(link, case, expect, "accepted" if data else "connection_closed_after_handshake")
except Exception as exc: # noqa: BLE001
outcome, text = classify(exc)
record(link, case, expect, outcome, text)
def openbao():
link = "Services -> OpenBao (TLS + cert auth by CN + policy)"
def login(case, expect, client, role):
try:
status, body = https_get("openbao", 8200, "/v1/auth/cert/login", client, method="POST",
body=json.dumps({"name": role}).encode(),
headers={"Content-Type": "application/json"})
record(link, case, expect, f"http_{status}")
except Exception as exc: # noqa: BLE001
outcome, text = classify(exc)
record(link, case, expect, outcome, text)
login("CN=worker logs in as role worker", "http_200", "worker", "worker")
login("CN=worker logs in as role api", "http_400", "worker", "api")
login("our CA, CN=intruder as role api", "http_400", "test/intruder", "api")
login("foreign CA, CN=worker as role worker", ["http_400", "server_rejected_client_cert"],
"test/rogue-worker", "worker")
login("no client certificate as role api", "http_400", None, "api")
http_case(link, "trust foreign CA only", "openbao", 8200, "/v1/sys/health", None, "client_rejected_server_cert",
ca=ROGUE_CA)
plaintext_case(link, "openbao", 8200)
def telemetry_backends():
rejected = ["server_rejected_client_cert", "connection_closed_after_handshake"]
link = "Collector/Grafana/operator -> Prometheus (mTLS + allowed SANs)"
http_case(link, "CN=operator", "prometheus", 9090, "/-/ready", "operator", "http_200")
http_case(link, "CN=grafana", "prometheus", 9090, "/-/ready", "grafana", "http_200")
http_case(link, "CN=otel-collector", "prometheus", 9090, "/-/ready", "otel-collector", "http_200")
http_case(link, "our CA, CN=api (SAN not allowed)", "prometheus", 9090, "/-/ready", "api", rejected)
http_case(link, "our CA, CN=intruder (SAN not allowed)", "prometheus", 9090, "/-/ready", "test/intruder", rejected)
http_case(link, "no client certificate", "prometheus", 9090, "/-/ready", None, rejected)
plaintext_case(link, "prometheus", 9090)
if SANDBOX:
record("Loki/Tempo/Grafana", "not available in the native sandbox", "skipped", "skipped")
return
for host, port, path in (("loki", 3100, "/ready"), ("tempo", 3200, "/ready")):
link = f"Collector/Grafana/operator -> {host.title()} (mTLS, CA)"
# 503 = mTLS пройден, но сервис ещё не готов (Loki после старта ~15 с отвечает «Ingester not ready»):
# ждём готовности до 30 с; любой отказ TLS не повторяется, ожидание остаётся http_200.
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
try:
if https_get(host, port, path, "operator")[0] != 503:
break
except Exception: # noqa: BLE001 — исход TLS запишет http_case ниже
break
time.sleep(2)
http_case(link, "CN=operator", host, port, path, "operator", "http_200")
http_case(link, "no client certificate", host, port, path, None, rejected)
http_case(link, "foreign CA client certificate", host, port, path, "test/rogue-worker", rejected)
plaintext_case(link, host, port)
link = "Collector -> Tempo OTLP gRPC :4317 (mTLS)"
for case, client, expect in (("no client certificate", None, rejected),
("foreign CA client certificate", "test/rogue-worker", rejected),
("CN=otel-collector", "otel-collector", "accepted")):
try:
context = ctx(client)
context.set_alpn_protocols(["h2"])
with socket.create_connection(("tempo", 4317), timeout=5) as raw:
with context.wrap_socket(raw, server_hostname="tempo") as tls:
tls.sendall(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" + b"\x00\x00\x00\x04\x00\x00\x00\x00\x00")
data = tls.recv(100)
record(link, case, expect, "accepted" if data else "connection_closed_after_handshake")
except Exception as exc: # noqa: BLE001
outcome, text = classify(exc)
record(link, case, expect, outcome, text)
link = "Operator -> Grafana (HTTPS)"
http_case(link, "HTTPS with our CA", "grafana", 3000, "/api/health", None, "http_200")
http_case(link, "trust foreign CA only", "grafana", 3000, "/api/health", None, "client_rejected_server_cert",
ca=ROGUE_CA)
plaintext_case(link, "grafana", 3000)
GROUPS = {"lb-api": lb_api, "broker": broker, "collector": collector, "postgres": postgres, "redis": redis_link,
"s3": s3, "openbao": openbao, "telemetry": telemetry_backends}
def main(argv):
names = argv[1:] if len(argv) > 1 and argv[0] == "matrix" else list(GROUPS)
if argv and argv[0] != "matrix":
names = argv
started = time.monotonic()
for name in names:
try:
GROUPS[name]()
except Exception as exc: # noqa: BLE001
record(name, "probe crashed", "no_crash", "crash", f"{type(exc).__name__}: {exc}")
failed = [r for r in RESULTS if not r["pass"]]
print(json.dumps({"summary": True, "checks": len(RESULTS), "failed": len(failed),
"seconds": round(time.monotonic() - started, 1)}))
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:] or ["matrix"]))
+224
View File
@@ -0,0 +1,224 @@
"""Эксперимент: >= 10 одновременных загрузок и пик памяти API-реплик.
Гипотеза: память реплики почти не растёт от числа и размера одновременных загрузок, потому что
тело пишется во временный файл (в RAM не больше 256 KiB на загрузку), PNG проверяется потоково
(куски по 64 KiB), JPEG декодируется в масштабе 1/8, а одновременно проверяется не больше
DECODE_CONCURRENCY файлов на реплику. Наивный вариант (тело целиком в память + полное декодирование)
при тех же 10 загрузках не помещается в лимит 512 MiB.
Методика: перед каждым сценарием `docker compose restart api` (сбросить пик), прогрев, затем N потоков
одновременно (barrier) загружают файл через балансировщик. Пик RSS процесса API — VmHWM из /proc/1/status
(high-water mark ядра, не пропускает короткие всплески); дополнительно память cgroup контейнера
(memory.peak, если ядро даёт; иначе максимум из опроса memory.current) и опрос VmRSS раз в ~0,1 с.
python student-tests/upload_memory.py [--concurrency 10] [--output evidence/upload-memory.json]
"""
import argparse
import hashlib
import json
import platform
import statistics
import threading
import time
import images
from common import (ROOT, app_python, call, check, compose, docker, new_chat, new_user, upload, wait_attachment,
wait_balanced, wait_ready)
def proc_status(container):
"""VmRSS и VmHWM (КиБ) процесса API (PID 1) и память cgroup контейнера (байты)."""
script = ("cat /proc/1/status | grep -E '^Vm(RSS|HWM)'; "
"for f in /sys/fs/cgroup/memory.peak /sys/fs/cgroup/memory.current "
"/sys/fs/cgroup/memory/memory.max_usage_in_bytes /sys/fs/cgroup/memory/memory.usage_in_bytes; "
"do [ -r $f ] && echo \"$f $(cat $f)\"; done; true")
out = docker("exec", container, "sh", "-c", script)
values = {}
for line in out.splitlines():
parts = line.replace(":", " ").split()
if parts[0] in ("VmRSS", "VmHWM"):
values[parts[0]] = int(parts[1])
elif parts[0].endswith(("memory.peak", "max_usage_in_bytes")):
values["cgroup_peak"] = int(parts[1])
elif parts[0].endswith(("memory.current", "usage_in_bytes")):
values["cgroup_current"] = int(parts[1])
return values
class Sampler(threading.Thread):
def __init__(self, containers):
super().__init__(daemon=True)
self.containers = containers
self.stop = threading.Event()
self.rss = {c: 0 for c in containers}
self.cgroup = {c: 0 for c in containers}
self.samples = 0
def run(self):
while not self.stop.is_set():
for c in self.containers:
try:
v = proc_status(c)
except Exception: # noqa: BLE001 — один пропущенный замер не важен
continue
self.rss[c] = max(self.rss[c], v.get("VmRSS", 0))
self.cgroup[c] = max(self.cgroup[c], v.get("cgroup_current", 0))
self.samples += 1
def api_containers():
from common import api_containers as running
return running()
def fresh_replicas():
compose("restart", "api")
containers = wait_balanced(2, seconds=90)
wait_ready()
return containers
def warm_up(user, chat):
"""По несколько загрузок на каждую реплику: в базовую линию входят импортированный Pillow, клиенты S3 и т.п."""
for data, ctype in ((images.sample_png(), "image/png"), (images.sample_jpeg(), "image/jpeg")) * 4:
upload(user, chat["id"], data, ctype)
def scenario(name, payloads, concurrency):
user = new_user("mem")
chat = new_chat(user)
containers = fresh_replicas()
warm_up(user, chat)
before = {c: proc_status(c) for c in containers}
sampler = Sampler(containers)
sampler.start()
barrier = threading.Barrier(concurrency)
results = [None] * concurrency
def worker(i):
data, ctype = payloads[i % len(payloads)]
barrier.wait()
started = time.monotonic()
try:
# lab5: замеряем только приём (202 queued); обработку worker'ом ждём ниже, вне замера
reply = upload(user, chat["id"], data, ctype, f"load-{i}.png", timeout=180, wait=False)
results[i] = (reply.status, time.monotonic() - started, reply.instance, reply.json, data)
except AssertionError as exc:
results[i] = (str(exc)[:120], time.monotonic() - started, None, None, data)
threads = [threading.Thread(target=worker, args=(i,)) for i in range(concurrency)]
wall = time.monotonic()
for t in threads:
t.start()
for t in threads:
t.join()
wall = time.monotonic() - wall
time.sleep(0.5)
sampler.stop.set()
sampler.join()
after = {c: proc_status(c) for c in containers}
ok = [r for r in results if r[0] == 202]
check(len(ok) == concurrency, f"{name}: not all uploads succeeded: {[r[0] for r in results if r[0] != 202]}")
for status, _, _, att, data in ok[:3]:
att = wait_attachment(user, att["id"], seconds=120)
check(att["status"] == "ready", f"{name}: attachment {att['id']} is {att['status']}, expected ready")
got = call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=user["token"])
check(got.data == data and att["sha256"] == hashlib.sha256(data).hexdigest(), "stored file differs")
latencies = sorted(r[1] for r in results)
from common import instance_aliases # lab7: X-Instance-Id — alias процесса, а не ID контейнера
aliases = instance_aliases(containers)
per_replica = []
for c in containers:
b, a = before[c], after[c]
per_replica.append({
"replica": c[:12],
"uploads_served": sum(1 for r in ok if r[2] and r[2] == aliases.get(c)),
"rss_before_mib": round(b["VmRSS"] / 1024, 1),
"rss_peak_mib": round(a["VmHWM"] / 1024, 1),
"rss_growth_mib": round((a["VmHWM"] - b["VmRSS"]) / 1024, 1),
"rss_peak_sampled_mib": round(sampler.rss[c] / 1024, 1),
"cgroup_peak_mib": round(a["cgroup_peak"] / 2**20, 1) if "cgroup_peak" in a else None,
"cgroup_peak_sampled_mib": round(sampler.cgroup[c] / 2**20, 1) if sampler.cgroup[c] else None,
})
sizes = sorted({len(d) for d, _ in payloads})
summary = {
"scenario": name,
"concurrency": concurrency,
"file_bytes": sizes,
"total_mib": round(sum(len(r[4]) for r in results) / 2**20, 1),
"all_202": True,
"wall_seconds": round(wall, 2),
"latency_s": {"p50": round(statistics.median(latencies), 2), "max": round(latencies[-1], 2)},
"sampler_rounds": sampler.samples,
"replicas": per_replica,
}
print(json.dumps(summary, ensure_ascii=False))
return summary
# Для сравнения: то же внутри контейнера api, но «наивно» — тело целиком в памяти и полное декодирование.
NAIVE_VS_STREAMING = r'''
import json, os, subprocess, sys
code = r"""
import io, os, resource, struct, sys, zlib
sys.path.insert(0, os.getcwd())
os.environ.setdefault("S3_ACCESS_KEY_ID", "x")
from PIL import Image
import uploads # импорт до замера: сравниваем только саму проверку файла
Image.MAX_IMAGE_PIXELS = None
def chunk(k, d): return struct.pack(">I", len(d)) + k + d + struct.pack(">I", zlib.crc32(k + d))
w, h = 8000, 5000
comp = zlib.compressobj(6); row = b"\x00" + bytes(w * 3)
idat = b"".join(comp.compress(row) for _ in range(h)) + comp.flush()
data = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + chunk(b"IDAT", idat) + chunk(b"IEND", b"")
del idat, comp, row
base = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
if sys.argv[1] == "naive":
body = bytes(data) + bytes(9 * 1024 * 1024) # тело запроса целиком в памяти (9 MiB)
im = Image.open(io.BytesIO(data)); im.load()
else:
f = io.BytesIO(data); uploads.check_png(f)
print((resource.getrusage(resource.RUSAGE_SELF).ru_maxrss - base) // 1024)
"""
out = {}
for mode in ("naive", "streaming"):
r = subprocess.run([sys.executable, "-c", code, mode], capture_output=True, text=True, cwd=os.getcwd())
out[mode] = int(r.stdout.strip().splitlines()[-1]) if r.returncode == 0 else r.stderr[-200:]
print(json.dumps(out))
'''
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--concurrency", type=int, default=10)
parser.add_argument("--output", default="evidence/upload-memory.json")
args = parser.parse_args()
check(args.concurrency >= 10, "the experiment needs at least 10 concurrent uploads")
print(f"client: Python {platform.python_version()} on {platform.system()} {platform.release()}")
print("preparing synthetic images (random-noise PNG ~9.5 MiB each, 40 Mpx PNG)...")
large = [(images.noise_png(int(9.5 * 2**20)), "image/png") for _ in range(4)]
pixels = [(images.png(8000, 5000), "image/png")]
jpeg = [(images.sample_jpeg(), "image/jpeg")]
print(f"large: {len(large[0][0])} bytes; 40 Mpx: {len(pixels[0][0])} bytes")
runs = [
scenario("10 x ~9.5 MiB PNG (noise)", large, args.concurrency),
scenario("10 x 40 Mpx PNG (8000x5000 RGB)", pixels, args.concurrency),
scenario(f"{2 * args.concurrency} mixed: large + 40 Mpx + JPEG", large + pixels + jpeg, 2 * args.concurrency),
]
naive = json.loads(app_python(NAIVE_VS_STREAMING).splitlines()[-1])
print(f"one 8000x5000 RGB PNG inside the api container, extra peak RSS: naive (body in RAM + full decode) "
f"{naive['naive']} MiB, streaming check {naive['streaming']} MiB")
limits = docker("inspect", "-f", "{{.HostConfig.Memory}} {{.HostConfig.NanoCpus}}", api_containers()[0]).split()
result = {"date": time.strftime("%Y-%m-%d %H:%M"), "api_limit_mib": int(limits[0]) // 2**20,
"api_limit_cpus": int(limits[1]) / 1e9, "runs": runs, "single_file_extra_rss_mib": naive}
(ROOT / args.output).write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
worst = max(r["rss_growth_mib"] for run in runs for r in run["replicas"])
print(f"PASS: all uploads succeeded; largest RSS growth of one replica: {worst} MiB "
f"(limit {result['api_limit_mib']} MiB); results in {args.output}")
if __name__ == "__main__":
main()
+153
View File
@@ -0,0 +1,153 @@
"""Пробник, который выполняется ВНУТРИ контейнера worker (там Pillow, модули приложения, доступ к БД и S3).
Тест передаёт этот файл через stdin: `docker compose exec -T worker python - <команда> [аргументы]`.
Секреты остаются в контейнере; наружу выходит одна строка JSON (без ключей доступа, только факты).
make <kind> — тестовое изображение, base64 (kind: thumb320, exif6, alpha, tiny, large, strip, big40)
inspect <attachment_id> — метаданные из БД + декодированные объекты из S3: размеры, формат, EXIF,
цвета контрольных точек, SHA-256, список ключей под attachments/<id>/
exists <key> — есть ли объект в bucket
imaging-limits — imaging.py на 40-Мп PNG: пик RSS дочернего процесса и отказ по лимиту пикселей
"""
import base64
import hashlib
import io
import json
import os
import resource
import subprocess
import sys
import tempfile
from uuid import UUID
from PIL import Image
import psycopg
from psycopg.rows import dict_row
import settings
import storage
import secretstore
secretstore.store.start() # lab7: учётные данные worker — из OpenBao по его сертификату
def make(kind: str) -> bytes:
out = io.BytesIO()
if kind == "thumb320": # 320x200 -> thumbnail 256x160 (контракт)
img = Image.new("RGB", (320, 200), (200, 30, 30))
img.paste((30, 30, 200), (0, 0, 160, 200))
img.save(out, "PNG")
elif kind == "exif6": # JPEG 400x300 с EXIF Orientation=6 и Make/Model/GPS
img = Image.new("RGB", (400, 300), (0, 160, 0))
img.paste((255, 0, 0), (0, 0, 100, 300)) # левая полоса красная: после поворота на 90° по часовой — сверху
exif = Image.Exif()
exif[0x0112] = 6
exif[0x010F] = "ProbeCamera"
exif[0x0110] = "Model-X"
exif[0x8825] = {1: "N", 2: (55.0, 45.0, 0.0)}
img.save(out, "JPEG", quality=95, exif=exif.tobytes())
elif kind == "alpha": # RGBA 300x200: левая половина прозрачная
img = Image.new("RGBA", (300, 200), (0, 0, 255, 255))
img.paste((0, 0, 0, 0), (0, 0, 150, 200))
img.save(out, "PNG")
elif kind == "tiny": # 40x30: без увеличения для thumbnail/optimized
Image.new("RGB", (40, 30), (10, 120, 220)).save(out, "PNG")
elif kind == "large": # 3000x2000 JPEG: optimized 1280x853, thumbnail 256x170
img = Image.radial_gradient("L").resize((3000, 2000)).convert("RGB")
img.save(out, "JPEG", quality=90)
elif kind == "strip": # 5000x2: thumbnail 256x1 (минимум 1 px)
Image.new("RGB", (5000, 2), (90, 90, 90)).save(out, "PNG")
elif kind == "big40": # 8000x5000 = 40 Мп ровно на лимите
Image.new("RGB", (8000, 5000), (120, 60, 30)).save(out, "PNG")
else:
raise SystemExit("unknown kind")
return out.getvalue()
def connect():
# lab7: роль messenger_worker по TLS, пароль из OpenBao (как у самого worker)
import dbconn
return dbconn.connect(autocommit=True, row_factory=dict_row)
def read(key: str) -> bytes:
stream = storage.open_read(key)
try:
return b"".join(storage.iter_chunks(stream))
finally:
stream.close()
def inspect(attachment_id: str) -> dict:
with connect() as conn:
a = conn.execute("SELECT state, object_key, source_key, pipeline_version, sha256, size_bytes "
"FROM attachments WHERE id = %s", (UUID(attachment_id),)).fetchone()
variants = conn.execute("SELECT name, content_type, width, height, sha256, size_bytes, object_key "
"FROM attachment_variants WHERE attachment_id = %s ORDER BY name",
(UUID(attachment_id),)).fetchall()
result = {"state": a["state"], "staging_present": a["source_key"] is not None and storage.exists(a["source_key"]),
"variant_rows": len(variants), "variants": {}}
if a["object_key"]:
original = read(a["object_key"])
result["original_sha_ok"] = hashlib.sha256(original).hexdigest() == a["sha256"]
result["original_size_ok"] = len(original) == a["size_bytes"]
for v in variants:
data = read(v["object_key"])
img = Image.open(io.BytesIO(data))
info = {"format": img.format, "size": list(img.size), "mode": img.mode,
"meta_size_ok": [v["width"], v["height"]] == list(img.size),
"sha_ok": hashlib.sha256(data).hexdigest() == v["sha256"] and len(data) == v["size_bytes"],
"exif_tags": len(img.getexif()), "has_xmp": "xmp" in img.info or b"http://ns.adobe.com/xap" in data,
"quality_hint": None}
rgb = img.convert("RGBA")
w, h = rgb.size
info["pixel_top_center"] = list(rgb.getpixel((w // 2, 0)))
info["pixel_left_center"] = list(rgb.getpixel((0, h // 2)))
info["pixel_right_center"] = list(rgb.getpixel((w - 1, h // 2)))
result["variants"][v["name"]] = info
prefix = f"attachments/{attachment_id}/"
result["final_keys"] = sorted(key[len(prefix):] for key, _m, _s in storage.list_objects(prefix))
return result
def imaging_limits() -> dict:
"""Пик памяти процесса обработки на худшем допустимом входе и отказ при превышении лимита пикселей."""
here = os.path.dirname(os.path.abspath(storage.__file__))
report = {}
with tempfile.TemporaryDirectory(dir=settings.WORKER_TMP_DIR) as tmp:
source = os.path.join(tmp, "big.png")
with open(source, "wb") as f:
f.write(make("big40"))
env = {"PATH": os.environ.get("PATH", ""), "IMAGING_MEMORY_MB": str(settings.WORKER_MEMORY_LIMIT_MB),
"IMAGING_CPU_SECONDS": str(settings.JOB_TIMEOUT_SECONDS)}
for label, max_pixels in (("at_limit_40mpx", 40_000_000), ("over_limit_max_10mpx", 10_000_000)):
out = os.path.join(tmp, label)
os.mkdir(out)
before = resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss
proc = subprocess.run([sys.executable, os.path.join(here, "imaging.py"), source, out, "image/png",
str(max_pixels)], env=env, capture_output=True, timeout=120)
peak = resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss
report[label] = {"exit_code": proc.returncode, "peak_rss_mib_max_children": round(peak / 1024, 1),
"rss_grew": peak > before}
report["memory_limit_mib"] = settings.WORKER_MEMORY_LIMIT_MB
report["timeout_s"] = settings.JOB_TIMEOUT_SECONDS
return report
def main():
command = sys.argv[1]
if command == "make":
print(json.dumps({"b64": base64.b64encode(make(sys.argv[2])).decode("ascii")}))
elif command == "inspect":
print(json.dumps(inspect(sys.argv[2])))
elif command == "exists":
print(json.dumps({"exists": storage.exists(sys.argv[2])}))
elif command == "imaging-limits":
print(json.dumps(imaging_limits()))
else:
raise SystemExit("unknown command")
if __name__ == "__main__":
main()