7 — Т2302 — ебедев — на 5

This commit is contained in:
2026-11-22 23:26:17 +03:00
parent 20afc2c790
commit d15f2a3631
179 changed files with 21709 additions and 54 deletions
+198
View File
@@ -0,0 +1,198 @@
"""Общая обвязка собственных проверок студента (stdlib, Python 3.9+).
Переиспользует HTTP-клиент публичных тестов (tests/client.py), не изменяя его. Команды управления
стендом и доступа к SQL задаются переменными окружения; по умолчанию — Compose из этого репозитория.
"""
import base64
import hashlib
import json
import os
import shlex
import subprocess
import sys
import time
import traceback
import uuid
import zlib
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check # noqa: E402
DC = os.environ.get("COMPOSE", "docker compose --env-file .env")
# lab7: SQL — суперпользователь postgres только через unix-socket внутри контейнера (peer, без пароля).
PSQL = os.environ.get("PSQL", DC + " exec -T -u postgres postgres psql -d messenger")
# lab7: всё через HTTPS с проверкой сертификата по локальному CA (без отключения проверки).
os.environ.setdefault("CA_FILE", str(ROOT / "secrets" / "tls" / "trust" / "ca.crt"))
CA_FILE = os.environ["CA_FILE"]
COMMANDS = {
"stop_db": os.environ.get("STOP_DB", DC + " stop postgres"),
"start_db": os.environ.get("START_DB", DC + " start postgres"),
"stop_cache": os.environ.get("STOP_CACHE", DC + " stop redis"),
"start_cache": os.environ.get("START_CACHE", DC + " start redis"),
# lab5: worker и брокер (volumes не трогаются)
"stop_worker": os.environ.get("STOP_WORKER", DC + " stop worker"),
"start_worker": os.environ.get("START_WORKER", DC + " start worker"),
"restart_broker": os.environ.get("RESTART_BROKER", DC + " restart nats"),
"restart_api": os.environ.get("RESTART_API", DC + " restart api"),
}
BASE_URL = os.environ.get("BASE_URL", "https://127.0.0.1:8443")
TTL_BASE_URL = os.environ.get("TTL_BASE_URL", "https://127.0.0.1:8444")
TTL_SECONDS = float(os.environ.get("TTL_SECONDS", "2"))
def sh(name_or_cmd, timeout=90):
cmd = COMMANDS.get(name_or_cmd, name_or_cmd)
subprocess.run(shlex.split(cmd), cwd=ROOT, check=True, timeout=timeout,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def sql(query):
"""Одна SQL-команда через psql (-At); возвращает строки результата. Только синтетические данные."""
out = subprocess.run(shlex.split(PSQL) + ["-X", "-At", "-v", "ON_ERROR_STOP=1", "-c", query],
cwd=ROOT, check=True, capture_output=True, text=True, timeout=60)
return [line for line in out.stdout.splitlines() if line]
S3_ADMIN = os.environ.get("S3_ADMIN", DC + " --profile tools exec -T ops python -")
API_EXEC = os.environ.get("API_EXEC", DC + " exec -T api")
def s3_admin(op, key, data=None):
"""Операция с bucket admin-ключом В ОБХОД API (внедрение отказов на стороне S3)."""
args = [op, key] + ([base64.b64encode(data).decode()] if data is not None else [])
script = (ROOT / "student-tests" / "s3_admin.py").read_bytes()
out = subprocess.run(shlex.split(S3_ADMIN) + args, cwd=ROOT, input=script, capture_output=True,
check=True, timeout=120)
return out.stdout.decode().strip()
# Операторские команды — в контейнере ops (профиль tools; identity bootstrap/владелец схемы). В lab7 у API
# и worker нет прав на операторские действия (replay, purge, чтение журналов без своей роли).
JOBS_EXEC = os.environ.get("JOBS_EXEC", DC + " --profile tools exec -T ops")
def jobs_cli(*args, expect=(0,)):
"""python -m messenger jobs … внутри контейнера API; возвращает JSON-ответ (stdout)."""
out = subprocess.run(shlex.split(JOBS_EXEC) + ["python", "-m", "messenger", "jobs"] + [str(a) for a in args],
cwd=ROOT, capture_output=True, text=True, timeout=300)
if out.returncode not in expect:
raise Failure("jobs %s exit %d: %s" % (args[0], out.returncode, (out.stderr or out.stdout).strip()[-300:]))
return json.loads(out.stdout)
def events(attachment_id):
"""Журнал событий работ вложения: список (event, attempt, lease_token, worker, detail)."""
return jobs_cli("status", attachment_id)["events"]
def wait_status(c, actor, att_id, statuses, timeout=90, interval=0.3):
"""Ждать, пока GET метаданных вернёт один из statuses; возвращает Attachment."""
statuses = (statuses,) if isinstance(statuses, str) else tuple(statuses)
deadline = time.monotonic() + timeout
last = None
while time.monotonic() < deadline:
last = c.call("GET", "/api/v1/attachments/" + att_id, actor=actor, schema="Attachment")["json"]
if last["status"] in statuses:
return last
time.sleep(interval)
raise Failure("attachment %s: status %s, expected %s within %ss" % (att_id, last and last["status"], statuses, timeout))
def make_png(width=16, height=16, seed=None):
"""Валидный RGB PNG (stdlib), уникальный по seed — для разных SHA-256."""
seed = seed if seed is not None else uuid.uuid4().bytes
rnd = hashlib.sha256(seed).digest()
rows = b"".join(b"\x00" + bytes((rnd[(x + y) % 32] ^ x ^ y) & 0xFF for x in range(width * 3)) for y in range(height))
def chunk(t, d):
return len(d).to_bytes(4, "big") + t + d + zlib.crc32(t + d).to_bytes(4, "big")
ihdr = width.to_bytes(4, "big") + height.to_bytes(4, "big") + bytes([8, 2, 0, 0, 0])
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"")
def upload(c, actor, chat, data=None, content_type="image/png", filename="pic.png", expected=202, headers=None):
from urllib.parse import quote
data = make_png() if data is None else data
h = {"Content-Type": content_type}
h.update(headers or {})
r = c.call("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=" + quote(filename), expected,
actor=actor, raw=data, headers=h, schema="Attachment" if expected == 202 else None)
return (r["json"], data) if expected == 202 else r
def basic(username, password):
return "Basic " + base64.b64encode((username + ":" + password).encode("utf-8")).decode()
def new_user(c, label="s", password=None):
username = ("st_" + label + "_" + uuid.uuid4().hex[:10])[:32]
password = password or ("Pw-" + uuid.uuid4().hex)
user = c.call("POST", "/api/v1/users", 201, schema="User",
body={"username": username, "display_name": "Тест " + label, "password": password})["json"]
return {"id": user["id"], "user": user, "username": username, "password": password}
def login(c, actor, expected=201):
"""Вход. Ожидая 201, ведёт себя как вежливый клиент: на 429 (общий лимит входа с IP — все тесты идут с одного
адреса хоста) ждёт Retry-After (≤ 65 с) и повторяет, не более 2 раз."""
for attempt in range(3):
allowed = [201, 429] if expected == 201 and attempt < 2 else expected
r = c.call("POST", "/api/v1/auth/sessions", allowed,
headers={"Authorization": basic(actor["username"], actor["password"])},
schema="Session" if expected == 201 else None)
if r["status"] != 429 or expected == 429:
break
time.sleep(min(65, int(r["headers"].get("Retry-After") or 5)) + 0.5)
if expected == 201:
actor["token"] = r["json"]["token"]
actor["expires_at"] = r["json"]["expires_at"]
return r
def wait_until(probe, timeout=60, interval=0.5):
deadline = time.monotonic() + timeout
last = None
while time.monotonic() < deadline:
try:
if probe():
return time.monotonic()
except Failure as exc:
last = exc
time.sleep(interval)
raise Failure("condition not reached in %ss (%s)" % (timeout, last))
class Suite:
def __init__(self, name):
self.name, self.results = name, []
def case(self, title):
def decorator(fn):
self.results.append((title, fn))
return fn
return decorator
def run(self):
passed = failed = 0
print("## " + self.name)
for title, fn in self.results:
start = time.monotonic()
try:
note = fn()
passed += 1
print("PASS %-62s %6.2fs%s" % (title, time.monotonic() - start, (" " + note) if note else ""))
except Exception as exc: # noqa: BLE001
failed += 1
print("FAIL %-62s %s" % (title, exc))
if os.environ.get("DEBUG"):
traceback.print_exc()
print("summary: %d passed, %d failed" % (passed, failed))
raise SystemExit(1 if failed else 0)
__all__ = ["Client", "Failure", "check", "sh", "sql", "basic", "new_user", "login", "wait_until", "Suite",
"s3_admin", "jobs_cli", "events", "wait_status", "make_png", "upload",
"BASE_URL", "TTL_BASE_URL", "TTL_SECONDS", "json"]
+107
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env python3
"""Сценарий защиты lab5 (README, шаги 1–3) с протоколом действий: время, действие, HTTP-коды, статус,
ID вложения/работы и состояние контейнеров (StartedAt/PID). Токены и пароли не печатаются.
1. make test проходит отдельно (smoke).
2. worker остановлен → upload 202 → GET queued → content 409 → другие сообщения работают.
3. перезапуск API и брокера с сохранением volumes → запуск worker → та же запись ready, thumbnail доступен.
python3 student-tests/defense_demo.py # нужен docker compose в PATH и работающий стенд
"""
import datetime as dt
import hashlib
import shlex
import subprocess
import sys
import time
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from image_probe import jpeg_size # noqa: E402
from common import BASE_URL, DC, ROOT, Client, Failure, check, jobs_cli, login, make_png, new_user, sh, upload # noqa: E402
c = Client(BASE_URL, timeout=30)
def log(step, msg):
print("%s %-6s %s" % (dt.datetime.now(dt.timezone.utc).strftime("%H:%M:%S.%f")[:-3], step, msg), flush=True)
def containers(services=("api", "worker", "nats")):
out = []
for svc in services:
ids = subprocess.run(shlex.split(DC) + ["ps", "-a", "-q", svc], cwd=ROOT, capture_output=True, text=True).stdout.split()
for i in ids:
out.append(subprocess.run(["docker", "inspect", "-f", "{{.Name}} {{.State.Status}} started={{.State.StartedAt}}"
" pid={{.State.Pid}}", i], capture_output=True, text=True).stdout.strip().lstrip("/"))
return out
def wait(probe, timeout, interval=0.5):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
v = probe()
except Failure: # пока реплики перезапускаются, LB отвечает сам (503 без X-Instance-Id)
v = None
if v:
return v
time.sleep(interval)
raise SystemExit("timeout")
alice = new_user(c, "demo"); login(c, alice)
bob = new_user(c, "demob"); login(c, bob)
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "defense", "member_ids": [alice["id"], bob["id"]]})["json"]
log("0", "chat %s, users alice/bob (tokens not shown)" % chat["id"])
for line in containers():
log("0", " " + line)
log("2", "stop worker: " + DC + " stop worker")
sh("stop_worker", timeout=120)
for line in containers(("worker",)):
log("2", " " + line)
data = make_png(320, 200)
att, _ = upload(c, alice, chat, data, filename="defense.png")
log("2", "POST /chats/%s/attachments → 202, attachment_id=%s status=%s" % (chat["id"], att["id"], att["status"]))
job = jobs_cli("status", att["id"])["jobs"][0]
log("2", "job_id=%s pipeline_version=%s attempt=%s status=%s" % (job["job_id"], job["pipeline_version"], job["attempt"],
job["status"]))
r = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], 409, actor=bob)
log("2", "GET /attachments/%s/content → %d (%s)" % (att["id"], r["status"], r["json"]["error"]["code"]))
m = c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 201, actor=alice, schema="Message",
body={"text": "фото во вложении", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex})
log("2", "POST message with queued attachment → 201, message_id=%s" % m["json"]["id"])
m = c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 201, actor=bob, schema="Message",
body={"text": "обычное сообщение"}, headers={"Idempotency-Key": uuid.uuid4().hex})
log("2", "POST plain message (bob) → 201, message_id=%s; history works while worker is down" % m["json"]["id"])
ev = wait(lambda: [e for e in jobs_cli("status", att["id"])["events"] if e["event"] == "published"], 30)
log("2", "job published to JetStream: stream_seq=%s (outbox → relay → publish ack)" % ev[0]["detail"]["stream_seq"])
log("3", "restart broker (volume natsdata kept) and API replicas: restart nats; restart api")
sh("restart_broker", timeout=120)
sh("restart_api", timeout=180)
wait(lambda: c.call("GET", "/health/ready", [200, 502, 503])["status"] == 200, 90)
for line in containers(("api", "nats")):
log("3", " " + line)
meta = c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["json"]
log("3", "after restart: attachment %s status=%s (job survived in PostgreSQL + JetStream)" % (att["id"], meta["status"]))
log("3", "start worker: " + DC + " start worker")
sh("start_worker", timeout=120)
t = time.monotonic()
meta = wait(lambda: (lambda x: x if x["status"] in ("ready", "failed") else None)(
c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["json"]), 60)
check(meta["status"] == "ready", "not ready")
log("3", "attachment %s status=ready %.1fs after worker start; variants=%s" % (
att["id"], time.monotonic() - t, ["%s %dx%d" % (v["name"], v["width"], v["height"]) for v in meta["variants"]]))
orig = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)["bytes"]
thumb = c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], actor=bob)["bytes"]
check(orig == data, "original differs")
log("3", "original sha256=%s… (= uploaded), thumbnail JPEG %s" % (hashlib.sha256(orig).hexdigest()[:16], jpeg_size(thumb)))
for e in jobs_cli("status", att["id"])["events"]:
log("log", "%s %-24s attempt=%s token=%s %s" % (str(e["created_at"])[11:23], e["event"], e["attempt"],
e["lease_token"], e["detail"] or ""))
print("PASS: defense scenario (worker down → 202 → 409 → restart API+broker → worker → ready)")
Binary file not shown.

After

Width:  |  Height:  |  Size: 746 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 693 B

+912
View File
@@ -0,0 +1,912 @@
#!/usr/bin/env python3
"""Отрицательные (и контрольные положительные) проверки ВНУТРЕННЕЙ матрицы доверия lab7 — contracts/trust-matrix.md.
Запуск (оператор; контейнер probe профиля tests видит внутренние сети и тестовые identity):
docker compose --profile tests run --rm probe # всё
docker compose --profile tests run --rm probe student-tests/internal_security.py --only lb,nats
Для каждой связи: нет клиентского сертификата / сертификат ЧУЖОГО CA / сертификат НАШЕГО CA, но запрещённой
identity (rogue, другой сервис) / истёкший / отозванный → отказ; разрешённая identity → успех; затем права
(ACL/policy) разрешённой identity: разрешено только нужное. Отказ «по сертификату» отличается от «сервис
недоступен»: каждая проверка печатает конкретную причину (TLS alert, 403, NOPERM, permission denied).
Секреты (пароли из OpenBao, токены) используются только в памяти и не печатаются.
"""
import argparse
import asyncio
import http.client
import json
import os
import socket
import ssl
import sys
import time
import traceback
import urllib.error
import urllib.request
import uuid
sys.path.insert(0, "/app/src")
import logging # noqa: E402
logging.getLogger("asyncio").setLevel(logging.ERROR) # шум «eof_received()» при отказах TLS
import warnings # noqa: E402
warnings.filterwarnings("ignore", category=DeprecationWarning) # ssl.TLSVersion.TLSv1_1 — намеренно (проверка отказа)
TLS = os.environ.get("PROBE_TLS_DIR", "/secrets/tls")
TEST = os.environ.get("PROBE_TEST_DIR", "/secrets/test")
BAO = os.environ.get("PROBE_BAO_DIR", "/secrets/bao")
CA = TLS + "/trust/ca.crt"
FOREIGN_CA = TEST + "/foreign-ca.crt"
BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
ID = { # каталоги сертификатов
"lb": TLS + "/lb", "api": TLS + "/api", "worker": TLS + "/worker", "bootstrap": TLS + "/bootstrap",
"otel-collector": TLS + "/otel-collector", "grafana": TLS + "/grafana", "prometheus": TLS + "/prometheus",
"tempo": TLS + "/tempo", "migrate": TLS + "/migrate",
"rogue": TEST + "/rogue", "expired-lb": TEST + "/expired-lb", "revoked-lb": TEST + "/revoked-lb",
"foreign-lb": TEST + "/foreign-lb", "foreign-worker": TEST + "/foreign-worker", "foreign-api": TEST + "/foreign-api",
"foreign-otel-collector": TEST + "/foreign-otel-collector", "foreign-grafana": TEST + "/foreign-grafana",
"old-lb": TEST + "/old-lb", # копия сертификата LB ДО ротации (создаёт test_lifecycle.py)
}
RESULTS = []
class Fail(Exception):
pass
def check(cond, msg):
if not cond:
raise Fail(msg)
def case(group, title):
def deco(fn):
RESULTS.append([group, title, fn, None, None])
return fn
return deco
def ctx(identity=None, ca=CA, hostname_check=True):
c = ssl.create_default_context(cafile=ca)
c.check_hostname = hostname_check
if identity:
d = ID[identity]
c.load_cert_chain(d + "/tls.crt", d + "/tls.key")
return c
def https(host, port, path="/", identity=None, method="GET", body=None, headers=None, server_hostname=None,
ca=CA, timeout=5):
"""Результат: ('http', status, body) | ('tls', причина) | ('closed', причина) | ('net', причина)."""
c = ctx(identity, ca)
try:
raw = socket.create_connection((host, port), timeout=timeout)
except OSError as e:
return ("net", type(e).__name__)
try:
s = c.wrap_socket(raw, server_hostname=server_hostname or host)
except ssl.SSLCertVerificationError as e:
raw.close()
return ("tls", "server cert: " + (e.verify_message or str(e))[:80])
except (ssl.SSLError, OSError) as e:
raw.close()
return ("tls", getattr(e, "reason", None) or type(e).__name__)
# TLS 1.3: клиентское рукопожатие завершается раньше, чем сервер проверит НАШ сертификат, поэтому
# отказ по сертификату приходит алертом чуть позже — ждём его коротко, чтобы назвать причину точно.
try:
s.settimeout(0.3)
if s.recv(1) == b"":
s.close()
return ("closed", "EOF after handshake")
except ssl.SSLError as e:
s.close()
return ("tls", getattr(e, "reason", None) or str(e)[:80])
except (socket.timeout, TimeoutError):
pass
except (ConnectionResetError, BrokenPipeError) as e:
s.close()
return ("closed", type(e).__name__)
s.settimeout(timeout)
try:
conn = http.client.HTTPConnection(host, port, timeout=timeout)
conn.sock = s
conn.request(method, path, body=body, headers=dict({"Host": server_hostname or host}, **(headers or {})))
r = conn.getresponse()
data = r.read(4096)
return ("http", r.status, data)
except ssl.SSLError as e: # TLS 1.3: отказ сервера по сертификату приходит алертом после рукопожатия
return ("tls", getattr(e, "reason", None) or str(e)[:80])
except (http.client.RemoteDisconnected, ConnectionResetError, BrokenPipeError, http.client.BadStatusLine) as e:
return ("closed", type(e).__name__)
except OSError as e:
return ("net", type(e).__name__)
finally:
s.close()
def denied_tls(res, what):
check(res[0] in ("tls", "closed"), "%s: expected TLS/connection rejection, got %s" % (what, res[:2]))
return "%s: %s" % (res[0], res[1])
def status(res, want, what):
check(res[0] == "http" and res[1] == want, "%s: expected HTTP %s, got %s" % (what, want, res[:2]))
return "HTTP %s" % want
# ======================================================================================= OpenBao
def bao_call(method, path, body=None, token=None, ca=CA):
req = urllib.request.Request("https://openbao:8200/v1/" + path, method=method,
data=json.dumps(body).encode() if body is not None else None,
headers={"Content-Type": "application/json"})
if token:
req.add_header("X-Vault-Token", token)
try:
with urllib.request.urlopen(req, context=ctx(None, ca), timeout=5) as r:
return r.status, json.loads(r.read() or b"{}")
except urllib.error.HTTPError as e:
return e.code, json.loads(e.read() or b"{}")
_TOKENS = {}
def bao_login(svc):
if svc not in _TOKENS:
rid = open(BAO + "/%s/role_id" % svc).read().strip()
sid = open(BAO + "/%s/secret_id" % svc).read().strip()
st, body = bao_call("POST", "auth/approle/login", {"role_id": rid, "secret_id": sid})
check(st == 200, "AppRole login %s: HTTP %s" % (svc, st))
_TOKENS[svc] = body["auth"]
return _TOKENS[svc]
def kv(svc):
tok = bao_login(svc)["client_token"]
st, body = bao_call("GET", "secret/data/messenger/" + svc, token=tok)
check(st == 200, "read own KV %s: HTTP %s" % (svc, st))
return body["data"]["data"]
@case("openbao", "TLS: сервер проверяется по CA и имени; plaintext HTTP не обслуживается")
def _():
out = []
r = https("openbao", 8200, "/v1/sys/health", server_hostname="openbao")
check(r[0] == "http", "trusted TLS failed: %s" % (r,))
out.append("trusted=HTTP %s" % r[1])
r = https("openbao", 8200, "/v1/sys/health", ca=FOREIGN_CA)
out.append("foreign CA → " + denied_tls(r, "foreign trust store"))
try:
c = http.client.HTTPConnection("openbao", 8200, timeout=3)
c.request("GET", "/v1/sys/health")
resp = c.getresponse()
check(resp.status == 400, "plaintext got %s" % resp.status)
out.append("plaintext → HTTP 400 (TLS-only listener)")
except (ConnectionResetError, http.client.RemoteDisconnected, http.client.BadStatusLine) as e:
out.append("plaintext → " + type(e).__name__)
return "; ".join(out)
@case("openbao", "AppRole: токен api — только policy messenger-api, TTL ≤ 5 мин, без default policy")
def _():
a = bao_login("api")
check(a["policies"] == ["messenger-api"] and a["token_policies"] == ["messenger-api"], "policies %s" % a["policies"])
check(0 < a["lease_duration"] <= 300 and a["renewable"], "ttl %s renewable %s" % (a["lease_duration"], a["renewable"]))
st, body = bao_call("GET", "auth/token/lookup-self", token=a["client_token"])
check(st == 200 and body["data"].get("path") == "auth/approle/login", "lookup-self %s" % st)
check("root" not in body["data"]["policies"], "root policy!")
return "policies=%s ttl=%ss bound_cidrs=%s" % (a["policies"], a["lease_duration"], body["data"].get("bound_cidrs"))
@case("openbao", "policy api: свой путь — да; чужой путь, list, запись, sys/*, создание токенов — 403")
def _():
t = bao_login("api")["client_token"]
rows = []
for method, path, body, want in (
("GET", "secret/data/messenger/api", None, 200),
("GET", "secret/data/messenger/worker", None, 403),
("LIST", "secret/metadata/messenger", None, 403),
("GET", "secret/metadata/messenger/api", None, 403),
("POST", "secret/data/messenger/api", {"data": {"x": "1"}}, 403),
("PUT", "sys/policies/acl/evil", {"policy": 'path "*" {capabilities=["sudo"]}'}, 403),
("GET", "sys/mounts", None, 403),
("POST", "auth/token/create", {}, 403),
("GET", "auth/approle/role/messenger-worker/role-id", None, 403),
("POST", "auth/approle/role/messenger-api/secret-id", {}, 403)):
st, _ = bao_call(method, path, body, token=t)
check(st == want, "%s %s: expected %s got %s" % (method, path, want, st))
rows.append("%s %s→%s" % (method, path.replace("secret/data/messenger/", "kv:"), st))
return ", ".join(rows)
@case("openbao", "policy worker: только messenger/worker; секреты API (Redis, роль БД API) недоступны")
def _():
t = bao_login("worker")["client_token"]
st1, b1 = bao_call("GET", "secret/data/messenger/worker", token=t)
st2, _ = bao_call("GET", "secret/data/messenger/api", token=t)
check(st1 == 200 and st2 == 403, "worker own=%s api=%s" % (st1, st2))
keys = sorted(b1["data"]["data"])
check(not any(k.startswith("redis") for k in keys) and b1["data"]["data"]["db_user"].startswith("messenger_worker"),
"worker KV keys %s" % keys)
return "own=200 api=403; worker keys=%s (нет admin/owner/redis)" % keys
@case("openbao", "неверный/чужой SecretID и чужой role_id → вход отклонён")
def _():
rid = open(BAO + "/api/role_id").read().strip()
wsid = open(BAO + "/worker/secret_id").read().strip()
st1, _ = bao_call("POST", "auth/approle/login", {"role_id": rid, "secret_id": str(uuid.uuid4())})
st2, _ = bao_call("POST", "auth/approle/login", {"role_id": rid, "secret_id": wsid})
check(st1 in (400, 403) and st2 in (400, 403), "login with bad secret_id: %s/%s" % (st1, st2))
return "random SecretID → %s; SecretID worker с role_id api → %s" % (st1, st2)
# ======================================================================================= LB → API
API_HOSTS = None
def api_ips():
global API_HOSTS
if API_HOSTS is None:
API_HOSTS = sorted({a[4][0] for a in socket.getaddrinfo("api", 8443, proto=socket.IPPROTO_TCP)})
return API_HOSTS
def api_req(ip, identity, path="/health/ready", **kw):
return https(ip, 8443, path, identity=identity, server_hostname="api", **kw)
@case("lb", "каждая реплика API: identity lb → /health/ready 200; бизнес-API доступен (401 без Bearer)")
def _():
ips = api_ips()
check(len(ips) >= 2, "expected ≥2 API replicas, DNS gives %s" % ips)
for ip in ips:
status(api_req(ip, "lb"), 200, ip + " ready")
status(api_req(ip, "lb", "/api/v1/users/me"), 401, ip + " /users/me")
return "%d реплик: mTLS lb → 200/401" % len(ips)
@case("lb", "без клиентского сертификата → TLS-отказ (certificate required)")
def _():
return "; ".join(denied_tls(api_req(ip, None), ip) for ip in api_ips())
@case("lb", "сертификат ЧУЖОГО CA с identity lb → TLS-отказ (unknown CA)")
def _():
return "; ".join(denied_tls(api_req(ip, "foreign-lb"), ip) for ip in api_ips())
@case("lb", "НАШ CA, но identity не lb (worker, api, rogue) → соединение закрыто до HTTP")
def _():
out = []
for ident in ("worker", "api", "rogue", "otel-collector"):
for ip in api_ips():
r = api_req(ip, ident, "/api/v1/users/me")
check(r[0] in ("closed", "tls"), "%s via %s: got %s (identity must be rejected)" % (ident, ip, r[:2]))
out.append("%s→%s" % (ident, r[0]))
return ", ".join(out)
@case("lb", "истёкший сертификат lb (тот же CA) → TLS-отказ; отозванный (CRL) → закрыто")
def _():
out = []
for ip in api_ips():
out.append("expired " + denied_tls(api_req(ip, "expired-lb"), ip))
r = api_req(ip, "revoked-lb")
check(r[0] in ("closed", "tls"), "revoked lb accepted by %s: %s" % (ip, r[:2]))
out.append("revoked → %s" % r[0])
return "; ".join(out[-2:])
@case("lb", "после ротации leaf LB старый сертификат (отозван в CRL) → закрыто; новый — 200")
def _():
if not os.path.exists(ID["old-lb"] + "/tls.crt"):
return "SKIP: ротация ещё не выполнялась (нет secrets/test/old-lb)"
for ip in api_ips():
r = api_req(ip, "old-lb")
check(r[0] in ("closed", "tls"), "old (rotated) lb cert accepted by %s: %s" % (ip, r[:2]))
status(api_req(ip, "lb"), 200, ip + " new lb")
return "old lb → %s на всех репликах; new lb → 200" % r[0]
@case("lb", "сервер API проверяется клиентом: чужое имя (SAN ≠ evil) → ошибка проверки сертификата")
def _():
r = https(api_ips()[0], 8443, "/health/ready", identity="lb", server_hostname="evil.example")
check(r[0] == "tls" and "server cert" in r[1], "hostname mismatch not detected: %s" % (r,))
return r[1]
@case("lb", "обхода нет: plaintext на :8443 не обслуживается, health-listener :8081 снаружи недоступен")
def _():
ip = api_ips()[0]
out = []
try:
c = http.client.HTTPConnection(ip, 8443, timeout=3)
c.request("GET", "/api/v1/users/me")
r = c.getresponse()
raise Fail("plaintext HTTP answered %s" % r.status)
except (ConnectionResetError, http.client.RemoteDisconnected, http.client.BadStatusLine, OSError) as e:
out.append("plaintext :8443 → %s" % type(e).__name__)
try:
socket.create_connection((ip, 8081), timeout=2).close()
raise Fail("health listener reachable from network")
except OSError as e:
out.append(":8081 → %s" % type(e).__name__)
return "; ".join(out)
# ======================================================================================= NATS
def nats_handshake(identity, ca=CA):
"""Сырой протокол NATS: INFO (plaintext) → TLS с сертификатом identity → CONNECT+PING. None — сервер ответил,
иначе причина отказа. Нужен ДО nats-py: после закрытия соединения сервером (certificate not pinned) цикл
чтения nats-py может зациклиться и заблокировать event loop (wait_for не срабатывает)."""
try:
raw = socket.create_connection(("nats", 4222), timeout=3)
raw.settimeout(3)
raw.recv(4096) # INFO {...}
s = ctx(identity, ca).wrap_socket(raw, server_hostname="nats")
s.sendall(b'CONNECT {"verbose":false,"pedantic":false,"tls_required":true,"lang":"python","version":"probe",'
b'"protocol":1}\r\nPING\r\n')
data = b""
while b"\r\n" not in data:
chunk = s.recv(4096)
if not chunk:
return "connection closed by server (certificate not pinned / no user)"
data += chunk
s.close()
line = data.split(b"\r\n")[0].decode(errors="replace")
return None if line.startswith(("PONG", "INFO", "+OK")) else line[:80]
except ssl.SSLError as e:
return "TLS: " + (e.reason or str(e))[:60]
except OSError as e:
return type(e).__name__ + ": " + str(e)[:60]
async def nats_try(identity, ca=CA, inbox="_INBOX", actions=None, url="tls://nats:4222"):
import nats
errors = []
async def ecb(e):
errors.append(str(e)[:120])
kw = {}
if url.startswith("tls://"):
why = nats_handshake(identity, ca)
if why:
return {"connected": False, "error": "refused: " + why, "errors": errors}
kw = {"tls": ctx(identity, ca), "tls_hostname": "nats"}
try:
nc = await asyncio.wait_for(nats.connect(url, connect_timeout=2, allow_reconnect=False, max_reconnect_attempts=0,
error_cb=ecb, inbox_prefix=inbox.encode(), **kw), 5)
await nc.flush(timeout=2)
except BaseException as e: # noqa: BLE001
return {"connected": False, "error": type(e).__name__ + ": " + str(e)[:80], "errors": errors}
out = {"connected": True, "errors": errors, "results": {}}
for name, fn in (actions or {}).items():
try:
out["results"][name] = await fn(nc)
except BaseException as e: # noqa: BLE001
out["results"][name] = "ERR " + type(e).__name__
await asyncio.sleep(0.2)
try:
await nc.close()
except BaseException: # noqa: BLE001
pass
return out
async def js_req(nc, subject, body=b""):
try:
r = await nc.request(subject, body, timeout=1.5)
return "ok:" + r.data[:60].decode(errors="replace")
except BaseException as e: # noqa: BLE001
return "no-response(" + type(e).__name__ + ")"
async def sub_try(nc, subject):
await nc.subscribe(subject)
await nc.flush(timeout=1)
await asyncio.sleep(0.3)
return "subscribed"
def run(coro):
return asyncio.run(coro)
@case("nats", "без сертификата / чужой CA / plaintext → отказ подключения")
def _():
a = run(nats_try(None))
b = run(nats_try("foreign-worker", inbox="_INBOX_worker"))
c = run(nats_try(None, url="nats://nats:4222"))
for name, r in (("no cert", a), ("foreign CA", b), ("plaintext", c)):
check(not r["connected"], "%s connected!" % name)
return "no-cert: %s | foreign: %s | plaintext: %s" % (a["error"][:50], b["error"][:50], c["error"][:50])
@case("nats", "НАШ CA, но не клиент NATS (rogue, lb) → отказ (pinned_certs + нет пользователя)")
def _():
out = []
for ident in ("rogue", "lb"):
r = run(nats_try(ident, actions={"info": lambda nc: js_req(nc, "$JS.API.STREAM.INFO.ATTACHMENT_JOBS")}))
ok = (not r["connected"]) or (r["results"].get("info", "").startswith(("no-response", "ERR")))
check(ok, "%s got access: %s" % (ident, r))
out.append("%s → %s" % (ident, (r.get("error") or r["results"].get("info"))[:60]))
return "; ".join(out)
@case("nats", "identity api: публикация заданий — да; consumer/stream admin/чужой inbox — запрещено")
def _():
acts = {
"stream_info": lambda nc: js_req(nc, "$JS.API.STREAM.INFO.ATTACHMENT_JOBS"),
"fetch_as_consumer": lambda nc: js_req(nc, "$JS.API.CONSUMER.MSG.NEXT.ATTACHMENT_JOBS.attachment-workers",
b'{"batch":1,"no_wait":true}'),
"purge_stream": lambda nc: js_req(nc, "$JS.API.STREAM.PURGE.ATTACHMENT_JOBS"),
"delete_consumer": lambda nc: js_req(nc, "$JS.API.CONSUMER.DELETE.ATTACHMENT_JOBS.attachment-workers"),
"sub_worker_inbox": lambda nc: sub_try(nc, "_INBOX_worker.>"),
"sub_jobs": lambda nc: sub_try(nc, "attachments.>"),
}
r = run(nats_try("api", inbox="_INBOX_api", actions=acts))
check(r["connected"], "api cannot connect: %s" % r.get("error"))
res = r["results"]
check(res["stream_info"].startswith("ok:"), "stream info denied: %s" % res["stream_info"])
for k in ("fetch_as_consumer", "purge_stream", "delete_consumer"):
check(res[k].startswith(("no-response", "ERR")), "api %s allowed: %s" % (k, res[k]))
viol = [e for e in r["errors"] if "ermission" in e]
check(len(viol) >= 5, "expected permission violations, got %s" % r["errors"])
return "stream_info ok; denied: fetch, purge, delete consumer, sub _INBOX_worker.>, sub attachments.> (%d violations)" % len(viol)
@case("nats", "identity worker: свой consumer (info) — да; purge/delete/создание consumer/inbox api — запрещено")
def _():
acts = {
"consumer_info": lambda nc: js_req(nc, "$JS.API.CONSUMER.INFO.ATTACHMENT_JOBS.attachment-workers"),
"purge_stream": lambda nc: js_req(nc, "$JS.API.STREAM.PURGE.ATTACHMENT_JOBS"),
"delete_stream": lambda nc: js_req(nc, "$JS.API.STREAM.DELETE.ATTACHMENT_JOBS"),
"create_consumer": lambda nc: js_req(nc, "$JS.API.CONSUMER.CREATE.ATTACHMENT_JOBS.evil", b"{}"),
"sub_api_inbox": lambda nc: sub_try(nc, "_INBOX_api.>"),
}
r = run(nats_try("worker", inbox="_INBOX_worker", actions=acts))
check(r["connected"], "worker cannot connect: %s" % r.get("error"))
res = r["results"]
check(res["consumer_info"].startswith("ok:"), "consumer info denied: %s" % res["consumer_info"])
for k in ("purge_stream", "delete_stream", "create_consumer"):
check(res[k].startswith(("no-response", "ERR")), "worker %s allowed: %s" % (k, res[k]))
viol = [e for e in r["errors"] if "ermission" in e]
check(len(viol) >= 4, "expected permission violations, got %s" % r["errors"])
return "consumer_info ok; denied: purge, delete stream, create consumer, sub _INBOX_api.> (%d violations)" % len(viol)
# ======================================================================================= Collector
def otlp_logs(marker, service="messenger-api"):
now = str(time.time_ns())
return json.dumps({"resourceLogs": [{"resource": {"attributes": [
{"key": "service.name", "value": {"stringValue": service}}]},
"scopeLogs": [{"logRecords": [{"timeUnixNano": now, "observedTimeUnixNano": now, "severityNumber": 9,
"body": {"stringValue": marker}}]}]}]}).encode()
def collector(identity, path="/v1/logs", body=None, ca=CA, port=4318):
return https("otel-collector", port, path, identity=identity, method="POST" if body is not None else "GET",
body=body, headers={"Content-Type": "application/json"} if body is not None else None, ca=ca)
@case("collector", "без сертификата / чужой CA → TLS-отказ; rogue и lb (наш CA) → 403")
def _():
body = otlp_logs("probe")
out = ["no-cert " + denied_tls(collector(None, body=body), "no cert"),
"foreign " + denied_tls(collector("foreign-api", body=body), "foreign")]
for ident in ("rogue", "lb", "grafana"):
out.append("%s %s" % (ident, status(collector(ident, body=body), 403, ident)))
return "; ".join(out)
@case("collector", "api и worker → OTLP 200; self-метрики :8888 — только prometheus")
def _():
status(collector("api", body=otlp_logs("probe-ok")), 200, "api")
status(collector("worker", body=otlp_logs("probe-ok", "messenger-worker")), 200, "worker")
status(collector("api", "/metrics", port=8888), 403, "api → :8888")
status(collector("prometheus", "/metrics", port=8888), 200, "prometheus → :8888")
return "api 200, worker 200; :8888 api 403, prometheus 200"
def loki_query(identity, logql, since=300):
import urllib.parse
q = urllib.parse.urlencode({"query": logql, "start": str(int((time.time() - since) * 1e9)),
"end": str(int(time.time() * 1e9)), "limit": "20"})
return https("loki", 3100, "/loki/api/v1/query_range?" + q, identity=identity)
@case("collector", "подмена service.name: worker шлёт как messenger-api → сохранено как messenger-worker")
def _():
marker = "impersonation-probe-" + uuid.uuid4().hex
status(collector("worker", body=otlp_logs(marker, "messenger-api")), 200, "worker post")
deadline = time.time() + 40
while time.time() < deadline:
r = loki_query("grafana", '{service_name=~".+"} |= "%s"' % marker)
if r[0] == "http" and r[1] == 200:
streams = json.loads(r[2])["data"]["result"]
if streams:
labels = streams[0]["stream"]
check(labels.get("service_name") == "messenger-worker", "stored as %s" % labels.get("service_name"))
return "Loki: service_name=%s (identity из сертификата, не из данных клиента)" % labels["service_name"]
time.sleep(2)
raise Fail("marker not found in Loki in 40s")
# ======================================================================================= telemetry backends
@case("backends", "Collector только пишет: чтение Loki/Prometheus/Tempo — 403")
def _():
out = []
for host, port, path in (("loki", 3100, "/loki/api/v1/labels"), ("prometheus", 9090, "/api/v1/query?query=up"),
("tempo", 3200, "/api/search")):
out.append("%s %s" % (host, status(https(host, port, path, identity="otel-collector"), 403, host)))
return "; ".join(out)
@case("backends", "Grafana только читает: push Loki, remote write/OTLP/admin Prometheus, OTLP Tempo — 403; query — 200")
def _():
out = []
for host, port, method, path in (("loki", 3100, "POST", "/otlp/v1/logs"), ("loki", 3100, "POST", "/loki/api/v1/push"),
("prometheus", 9090, "POST", "/api/v1/write"),
("prometheus", 9090, "POST", "/api/v1/otlp/v1/metrics"),
("prometheus", 9090, "POST", "/api/v1/admin/tsdb/delete_series?match[]=up"),
("tempo", 4318, "POST", "/v1/traces")):
r = https(host, port, path, identity="grafana", method=method, body=b"{}")
out.append("%s %s %s" % (host, path, status(r, 403, host + path)))
status(https("prometheus", 9090, "/api/v1/query?query=up", identity="grafana"), 200, "grafana query")
status(loki_query("grafana", '{service_name="messenger-api"}', 60), 200, "grafana loki query")
status(https("tempo", 3200, "/api/echo", identity="grafana"), 200, "grafana tempo")
return "; ".join(out) + "; queries 200"
@case("backends", "rogue/foreign/no-cert к шлюзам → отказ; порты самих backend'ов из сети недоступны")
def _():
out = []
for host, port in (("loki", 3100), ("prometheus", 9090), ("tempo", 3200)):
check(https(host, port, "/", identity="rogue")[1] == 403, host + " rogue")
denied_tls(https(host, port, "/", identity="foreign-grafana"), host + " foreign")
denied_tls(https(host, port, "/", identity=None), host + " no cert")
out.append("rogue 403, foreign/no-cert TLS-отказ (loki, prometheus, tempo)")
for host, port in (("loki", 3101), ("prometheus", 9091), ("tempo", 3201), ("tempo", 4319), ("otel-collector", 14318)):
try:
socket.create_connection((host, port), timeout=2).close()
raise Fail("%s:%d reachable" % (host, port))
except OSError:
pass
out.append("loopback-порты 3101/9091/3201/4319/14318 из сети закрыты")
return "; ".join(out)
# ======================================================================================= PostgreSQL
def pg(user, password, identity="api", sslmode="verify-full", host="postgres", ca=CA, dbname="messenger"):
import psycopg
from messenger.tlsconf import private_key_copy
kw = {"host": host, "dbname": dbname, "user": user, "sslmode": sslmode, "connect_timeout": 3}
if password:
kw["password"] = password
if sslmode != "disable":
kw["sslrootcert"] = ca
if identity:
kw["sslcert"] = ID[identity] + "/tls.crt"
kw["sslkey"] = private_key_copy(ID[identity] + "/tls.key")
return psycopg.connect(**kw, autocommit=True)
def pg_fail(fn):
try:
conn = fn()
conn.close()
return None
except Exception as e: # noqa: BLE001
msg = " ".join(str(e).split()) or type(e).__name__
return msg.rsplit("failed: ", 1)[-1][:110]
@case("postgres", "plaintext, hostname≠SAN, без client cert, чужой CA, суперпользователь по сети → отказ")
def _():
w = kv("worker")
out = []
for name, fn in (
("plaintext", lambda: pg(w["db_user"], w["db_password"], None, sslmode="disable")),
("hostname mismatch", lambda: pg(w["db_user"], w["db_password"], "worker",
host=socket.gethostbyname("postgres"))),
("no client cert", lambda: pg(w["db_user"], w["db_password"], None)),
("foreign CA cert", lambda: pg(w["db_user"], w["db_password"], "foreign-worker")),
("wrong password", lambda: pg(w["db_user"], "wrong-" + uuid.uuid4().hex, "worker")),
("superuser postgres", lambda: pg("postgres", "x", "worker")),
("owner by worker cert", lambda: pg("messenger_owner", None, "worker"))):
err = pg_fail(fn)
check(err is not None, "%s: connection succeeded!" % name)
out.append("%s: %s" % (name, err[:70]))
return " | ".join(out)
def pg_try(conn, sql):
try:
with conn.transaction():
conn.execute(sql)
raise RuntimeError("rollback")
except RuntimeError:
return "allowed"
except Exception as e: # noqa: BLE001
return type(e).__name__
@case("postgres", "роль worker: только данные вложений/заданий; users/sessions/messages/DDL — permission denied")
def _():
w = kv("worker")
conn = pg(w["db_user"], w["db_password"], "worker")
rows = {}
for name, sql, want in (
("SELECT users.password_hash", "SELECT password_hash FROM users LIMIT 1", "InsufficientPrivilege"),
("SELECT sessions", "SELECT token_hash FROM sessions LIMIT 1", "InsufficientPrivilege"),
("SELECT messages", "SELECT text FROM messages LIMIT 1", "InsufficientPrivilege"),
("SELECT chat_members", "SELECT 1 FROM chat_members LIMIT 1", "InsufficientPrivilege"),
("UPDATE attachments.owner_id", "UPDATE attachments SET owner_id = owner_id", "InsufficientPrivilege"),
("DELETE attachments", "DELETE FROM attachments", "InsufficientPrivilege"),
("CREATE TABLE", "CREATE TABLE evil (x int)", "InsufficientPrivilege"),
("TRUNCATE job_events", "TRUNCATE job_events", "InsufficientPrivilege"),
("SELECT attachments", "SELECT id, status FROM attachments LIMIT 1", "allowed"),
("UPDATE attachments.status", "UPDATE attachments SET status = status WHERE false", "allowed"),
("SELECT attachment_jobs", "SELECT job_id FROM attachment_jobs LIMIT 1", "allowed")):
got = pg_try(conn, sql)
check(got == want, "%s: expected %s got %s" % (name, want, got))
rows[name] = got
conn.close()
return "; ".join("%s→%s" % (k, "ok" if v == "allowed" else "denied") for k, v in rows.items())
@case("postgres", "роль api: нет DDL/DELETE пользователей/смены username/статуса вложений; DML своего пути — да")
def _():
a = kv("api")
conn = pg(a["db_user"], a["db_password"], "api")
rows = {}
for name, sql, want in (
("DELETE users", "DELETE FROM users", "InsufficientPrivilege"),
("UPDATE users.username", "UPDATE users SET username = username", "InsufficientPrivilege"),
("UPDATE attachments.status", "UPDATE attachments SET status = status", "InsufficientPrivilege"),
("INSERT attachment_variants", "INSERT INTO attachment_variants SELECT * FROM attachment_variants LIMIT 0",
"InsufficientPrivilege"),
("DROP TABLE", "DROP TABLE messages", "InsufficientPrivilege"),
("SELECT users", "SELECT id FROM users LIMIT 1", "allowed"),
("UPDATE users.password_hash", "UPDATE users SET password_hash = password_hash WHERE false", "allowed")):
got = pg_try(conn, sql)
check(got == want, "%s: expected %s got %s" % (name, want, got))
rows[name] = got
who = conn.execute("SELECT current_user, ssl, version, client_dn FROM pg_stat_ssl JOIN pg_stat_activity USING (pid)"
" WHERE pid = pg_backend_pid()").fetchone()
conn.close()
return "; ".join("%s→%s" % (k, "ok" if v == "allowed" else "denied") for k, v in rows.items()) + \
"; session: user=%s ssl=%s %s client_dn=%s" % who
# ======================================================================================= Redis
def redis_client(user, password, identity="api", ca=CA):
import redis
kw = dict(host="redis", port=6379, ssl=True, ssl_ca_certs=ca, ssl_cert_reqs="required", ssl_check_hostname=True,
socket_timeout=3, socket_connect_timeout=3, username=user, password=password)
if identity:
kw.update(ssl_certfile=ID[identity] + "/tls.crt", ssl_keyfile=ID[identity] + "/tls.key")
return redis.Redis(**kw)
def rtry(fn):
try:
fn()
return "allowed"
except Exception as e: # noqa: BLE001
return type(e).__name__
@case("redis", "plaintext/без client cert/чужой CA → отказ; default-пользователь выключен")
def _():
import redis
a = kv("api")
out = {}
out["plaintext"] = rtry(lambda: redis.Redis(host="redis", port=6379, socket_timeout=2).ping())
out["no client cert"] = rtry(lambda: redis_client(a["redis_username"], a["redis_password"], None).ping())
out["foreign CA cert"] = rtry(lambda: redis_client(a["redis_username"], a["redis_password"], "foreign-api").ping())
out["default user"] = rtry(lambda: redis_client(None, None).ping())
out["wrong password"] = rtry(lambda: redis_client(a["redis_username"], "wrong").ping())
for k, v in out.items():
check(v != "allowed", "%s allowed" % k)
return "; ".join("%s→%s" % kv_ for kv_ in out.items())
@case("redis", "ACL messenger-api: ключи sess:/rl: — да; KEYS, CONFIG, FLUSHALL, чужие ключи — NOPERM")
def _():
a = kv("api")
r = redis_client(a["redis_username"], a["redis_password"])
k = "rl:v1:probe:" + uuid.uuid4().hex
out = {"INCR rl:*": rtry(lambda: r.execute_command("INCR", k)), "GET sess:*": rtry(lambda: r.get("sess:v1:" + uuid.uuid4().hex)),
"DEL own": rtry(lambda: r.delete(k)),
"SET other key": rtry(lambda: r.set("evil:" + uuid.uuid4().hex, "1")), "KEYS *": rtry(lambda: r.keys("*")),
"CONFIG GET": rtry(lambda: r.config_get("*")), "FLUSHALL": rtry(lambda: r.flushall()),
"ACL LIST": rtry(lambda: r.acl_list()), "PUBLISH": rtry(lambda: r.publish("chan", "x"))}
for name in ("INCR rl:*", "GET sess:*", "DEL own"):
check(out[name] == "allowed", "%s: %s" % (name, out[name]))
for name in ("SET other key", "KEYS *", "CONFIG GET", "FLUSHALL", "ACL LIST", "PUBLISH"):
check(out[name] in ("NoPermissionError", "ResponseError"), "%s: %s" % (name, out[name]))
return "; ".join("%s→%s" % (n, "ok" if v == "allowed" else v) for n, v in out.items())
# ======================================================================================= S3
def s3c(svc):
from messenger.s3 import S3Client
d = kv(svc)
return S3Client("https://s3:9000", "us-east-1", d["s3_access_key_id"], d["s3_secret_access_key"], timeout=5)
async def s3try(coro):
from messenger.s3 import S3Error
try:
r = await coro
if hasattr(r, "aclose"):
await r.aclose()
return "allowed"
except S3Error as e:
return e.code or str(e.status)
async def alist(gen):
return [o async for o in gen]
@case("s3", "TLS: plaintext не обслуживается; чужое имя/CA → ошибка проверки; аноним → 403")
def _():
out = []
try:
c = http.client.HTTPConnection("s3", 9000, timeout=3)
c.request("GET", "/" + BUCKET)
r = c.getresponse()
check(r.status == 400, "plaintext got %s" % r.status)
out.append("plaintext → HTTP 400 (TLS-only)")
except (ConnectionResetError, http.client.RemoteDisconnected, http.client.BadStatusLine) as e:
out.append("plaintext → " + type(e).__name__)
r = https(socket.gethostbyname("s3"), 9000, "/", server_hostname="evil.example")
check(r[0] == "tls", "hostname mismatch accepted %s" % (r,))
out.append("SAN≠имя → " + r[1][:40])
out.append("foreign CA → " + denied_tls(https("s3", 9000, "/", ca=FOREIGN_CA), "foreign"))
status(https("s3", 9000, "/" + BUCKET + "?list-type=2"), 403, "anonymous list")
out.append("anonymous list → 403")
return "; ".join(out)
@case("s3", "prefix-права: api не пишет originals/variants и не листит; worker не читает variants и не листит originals")
def _():
async def go():
api, wrk = s3c("api"), s3c("worker")
key = "probe-" + uuid.uuid4().hex
res = {
"api PUT originals/": await s3try(api.put_object(BUCKET, "originals/" + key, b"x")),
"api PUT variants/": await s3try(api.put_object(BUCKET, "variants/" + key, b"x")),
"api LIST": await s3try(alist(api.list_objects(BUCKET, "", page_size=1))),
"api PUT other bucket": await s3try(api.put_object("other-bucket", key, b"x")),
"worker GET variants/": await s3try(wrk.get_object_stream(BUCKET, "variants/" + key)),
"worker LIST originals/": await s3try(alist(wrk.list_objects(BUCKET, "originals/", page_size=1))),
"worker PUT staging→evil/": await s3try(wrk.put_object(BUCKET, "evil/" + key, b"x")),
"worker CreateBucket": await s3try(wrk.create_bucket("evil-" + key[:8])),
"api PUT staging/ (own)": await s3try(api.put_object(BUCKET, "staging/" + key, b"x")),
"worker LIST staging/ (own)": await s3try(alist(wrk.list_objects(BUCKET, "staging/", page_size=1))),
"worker DELETE staging/ (own)": await s3try(wrk.delete_object(BUCKET, "staging/" + key)),
}
await api.aclose()
await wrk.aclose()
return res
res = run(go())
for k, v in res.items():
if "(own)" in k:
check(v == "allowed", "%s: %s" % (k, v))
else:
check(v != "allowed", "%s allowed!" % k)
return "; ".join("%s→%s" % (k, "ok" if v == "allowed" else v) for k, v in res.items())
# ======================================================================================= TLS-аудит всей матрицы
AUDIT = [ # (endpoint, порт, identity для рукопожатия, требуется ли client cert)
("api", 8443, "lb", True), ("otel-collector", 4318, "api", True), ("otel-collector", 8888, "prometheus", True),
("prometheus", 9090, "grafana", True), ("loki", 3100, "grafana", True), ("tempo", 3200, "grafana", True),
("tempo", 4318, "otel-collector", True), ("redis", 6379, "api", True), ("s3", 9000, None, False),
("openbao", 8200, None, False), ("grafana", 3000, None, False)]
def tls_details(host, port, identity):
from cryptography import x509
raw = socket.create_connection((host, port), timeout=5)
s = ctx(identity).wrap_socket(raw, server_hostname=host)
der = s.getpeercert(binary_form=True)
ver, cipher = s.version(), s.cipher()[0]
s.close()
cert = x509.load_der_x509_certificate(der)
san = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
names = san.get_values_for_type(x509.DNSName)
days = (cert.not_valid_after_utc - __import__("datetime").datetime.now(__import__("datetime").timezone.utc)).days
return ver, cipher, names, days, cert.issuer.rfc4514_string()
@case("audit", "TLS-аудит: все TLS-endpoint'ы — TLS ≥ 1.2, наш CA, SAN = имя сервиса, срок > 0; где нужно — mTLS обязателен")
def _():
rows = []
for host, port, ident, need_cert in AUDIT:
ver, cipher, names, days, issuer = tls_details(host, port, ident)
check(ver in ("TLSv1.2", "TLSv1.3"), "%s:%d %s" % (host, port, ver))
check(host in names, "%s:%d SAN %s" % (host, port, names))
check(days > 0 and "MTUCI lab7 local CA" in issuer, "%s:%d days=%s issuer=%s" % (host, port, days, issuer))
mtls = "-"
if need_cert:
r = https(host, port, "/", identity=None)
check(r[0] in ("tls", "closed"), "%s:%d accepts clients without certificate: %s" % (host, port, r[:2]))
mtls = "required"
old = ssl.create_default_context(cafile=CA)
old.maximum_version = ssl.TLSVersion.TLSv1_1
try:
old.wrap_socket(socket.create_connection((host, port), timeout=3), server_hostname=host).close()
raise Fail("%s:%d accepts TLS 1.1" % (host, port))
except ssl.SSLError:
pass
rows.append("%s:%d %s %s mTLS=%s days=%d" % (host, port, ver, cipher, mtls, days))
# протоколы с собственным согласованием TLS: PostgreSQL (SSLRequest), NATS (INFO → TLS)
w = kv("worker")
conn = pg(w["db_user"], w["db_password"], "worker")
v = conn.execute("SELECT version, cipher, client_dn FROM pg_stat_ssl WHERE pid = pg_backend_pid()").fetchone()
conn.close()
rows.append("postgres:5432 %s %s client=%s (hostnossl → reject)" % v)
r = run(nats_try("worker", inbox="_INBOX_worker"))
check(r["connected"], "nats worker")
rows.append("nats:4222 TLS (verify_and_map + pinned_certs) mTLS=required")
return "; ".join(rows)
@case("audit", "служебные/кластерные порты из сети закрыты: raft OpenBao, SeaweedFS master/volume/filer/gRPC, "
"мониторинг и cluster/leafnode NATS, plaintext Redis, health API")
def _():
targets = [("openbao", 8201), ("s3", 9333), ("s3", 19333), ("s3", 8080), ("s3", 18080), ("s3", 8888),
("s3", 18888), ("nats", 8222), ("nats", 6222), ("nats", 7422), ("redis", 6380)]
targets += [(ip, 8081) for ip in api_ips()]
opened = []
for host, port in targets:
try:
socket.create_connection((host, port), timeout=2).close()
opened.append("%s:%d" % (host, port))
except OSError:
pass
check(not opened, "reachable: %s" % opened)
return "закрыты: " + ", ".join("%s:%d" % t for t in targets[:11]) + " и :8081 всех реплик API"
# ======================================================================================= main
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--only", default="", help="группы через запятую: openbao,lb,nats,collector,backends,postgres,redis,s3,audit")
ap.add_argument("--json", help="сохранить сводку (без секретов)")
a = ap.parse_args()
only = {x for x in a.only.split(",") if x}
print("## internal trust matrix (probe container, %s)" % time.strftime("%Y-%m-%d %H:%M:%S"))
passed = failed = 0
for row in RESULTS:
group, title, fn = row[0], row[1], row[2]
if only and group not in only:
continue
t0 = time.monotonic()
try:
detail = fn() or ""
row[3], row[4] = "PASS", detail
passed += 1
except Fail as e:
row[3], row[4] = "FAIL", str(e)
failed += 1
except Exception as e: # noqa: BLE001
row[3], row[4] = "FAIL", "%s: %s" % (type(e).__name__, str(e)[:200])
traceback.print_exc(limit=2)
failed += 1
print("%s [%s] %s (%.1fs)\n %s" % (row[3], group, title, time.monotonic() - t0, row[4]), flush=True)
print("summary: %d passed, %d failed" % (passed, failed))
if a.json:
with open(a.json, "w") as fh:
json.dump([{"group": r[0], "check": r[1], "result": r[3], "detail": r[4]} for r in RESULTS if r[3]], fh,
ensure_ascii=False, indent=1)
sys.exit(1 if failed else 0)
if __name__ == "__main__":
main()
+182
View File
@@ -0,0 +1,182 @@
"""Доступ к сохранённым наблюдениям через Grafana API (stdlib): Prometheus, Loki, Tempo — через
datasource proxy, т. е. ровно тем путём, которым смотрит человек в Grafana (заодно проверяется provisioning).
Пароль admin читается из secrets/grafana_admin_password (или GRAFANA_PASSWORD_FILE) и нигде не печатается.
"""
import base64
import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
GRAFANA_URL = os.environ.get("GRAFANA_URL", "https://127.0.0.1:3000").rstrip("/")
CA_FILE = os.environ.get("CA_FILE", str(ROOT / "secrets" / "tls" / "trust" / "ca.crt")) # lab7: Grafana — HTTPS
PASSWORD_FILE = os.environ.get("GRAFANA_PASSWORD_FILE", str(ROOT / "secrets" / "grafana_admin_password"))
class ObsError(Exception):
pass
class Grafana:
def __init__(self, url=GRAFANA_URL, user="admin", password_file=PASSWORD_FILE, timeout=20):
self.url = url
pw = Path(password_file).read_text(encoding="utf-8").strip()
self.auth = "Basic " + base64.b64encode(("%s:%s" % (user, pw)).encode()).decode()
handlers = [urllib.request.ProxyHandler({})]
if url.startswith("https://"):
import ssl
handlers.append(urllib.request.HTTPSHandler(context=ssl.create_default_context(cafile=CA_FILE)))
self.opener = urllib.request.build_opener(*handlers)
self.timeout = timeout
def request(self, method, path, params=None, body=None, raw=False):
url = self.url + path + ("?" + urllib.parse.urlencode(params, doseq=True) if params else "")
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, data=data, method=method, headers={
"Authorization": self.auth, "Accept": "application/json",
**({"Content-Type": "application/json"} if data else {})})
try:
with self.opener.open(req, timeout=self.timeout) as r:
payload = r.read()
except urllib.error.HTTPError as e:
payload = e.read()
if e.code == 404 and raw:
return None
raise ObsError("%s %s -> HTTP %d: %s" % (method, path.split("?")[0], e.code, payload[:300].decode(errors="replace"))) from None
except (urllib.error.URLError, OSError) as e:
raise ObsError("%s %s: %s" % (method, path, type(e).__name__)) from None
return json.loads(payload) if payload else None
def get(self, path, params=None, **kw):
return self.request("GET", path, params=params, **kw)
# ------------------------------------------------------------------ Prometheus
def prom(self, expr, at=None):
params = {"query": expr}
if at is not None:
params["time"] = "%.3f" % at
d = self.get("/api/datasources/proxy/uid/prometheus/api/v1/query", params)
if d.get("status") != "success":
raise ObsError("prometheus: %s" % d)
return d["data"]["result"]
def prom_value(self, expr, default=None, at=None):
res = self.prom(expr, at)
if not res:
return default
return float(res[0]["value"][1])
def prom_range(self, expr, start, end, step=5):
d = self.get("/api/datasources/proxy/uid/prometheus/api/v1/query_range",
{"query": expr, "start": "%.3f" % start, "end": "%.3f" % end, "step": step})
return d["data"]["result"]
def series(self, match, since=600):
now = time.time()
d = self.get("/api/datasources/proxy/uid/prometheus/api/v1/series",
{"match[]": match, "start": "%.0f" % (now - since), "end": "%.0f" % now})
return d["data"]
def alerts(self):
return self.get("/api/datasources/proxy/uid/prometheus/api/v1/alerts")["data"]["alerts"]
def rules(self):
return self.get("/api/datasources/proxy/uid/prometheus/api/v1/rules")["data"]["groups"]
# ------------------------------------------------------------------ Loki
def loki(self, query, since=900, limit=200, start=None, end=None):
"""Список записей: dict(stream labels + structured metadata) + 'line' + 'ts' (секунды)."""
end = end or time.time()
start = start or end - since
d = self.get("/api/datasources/proxy/uid/loki/loki/api/v1/query_range",
{"query": query, "limit": limit, "start": "%d" % (start * 1e9), "end": "%d" % (end * 1e9),
"direction": "backward"})
out = []
for stream in d["data"]["result"]:
for ts, line, *rest in stream["values"]:
rec = dict(stream["stream"])
if rest and isinstance(rest[0], dict):
rec.update(rest[0].get("structuredMetadata", {}))
rec["line"], rec["ts"] = line, int(ts) / 1e9
out.append(rec)
return sorted(out, key=lambda r: r["ts"])
def loki_metric(self, query, at=None):
d = self.get("/api/datasources/proxy/uid/loki/loki/api/v1/query",
{"query": query, **({"time": "%d" % (at * 1e9)} if at else {})})
return d["data"]["result"]
# ------------------------------------------------------------------ Tempo
def trace(self, trace_id):
"""Spans trace (плоский список) или None, если Tempo его не нашёл."""
d = self.get("/api/datasources/proxy/uid/tempo/api/traces/" + trace_id, raw=True)
if d is None:
return None
spans = []
for b in d.get("batches", d.get("resourceSpans", [])):
res = {a["key"]: _val(a["value"]) for a in b["resource"].get("attributes", [])}
for ss in b.get("scopeSpans", b.get("instrumentationLibrarySpans", [])):
for s in ss.get("spans", []):
spans.append({
"trace_id": _hex(s["traceId"]), "span_id": _hex(s["spanId"]),
"parent": _hex(s.get("parentSpanId", "")), "name": s["name"],
"kind": s.get("kind", "").replace("SPAN_KIND_", ""), "service": res.get("service.name"),
"instance": res.get("service.instance.id"),
"attrs": {a["key"]: _val(a["value"]) for a in s.get("attributes", [])},
"links": [_hex(l["spanId"]) for l in s.get("links", [])],
"status": s.get("status", {}).get("code", "").replace("STATUS_CODE_", ""),
"start": int(s["startTimeUnixNano"]) / 1e9, "end": int(s["endTimeUnixNano"]) / 1e9,
"raw": s})
return spans
def search(self, traceql, since=1800, limit=50):
now = time.time()
d = self.get("/api/datasources/proxy/uid/tempo/api/search",
{"q": traceql, "start": "%d" % (now - since), "end": "%d" % (now + 60), "limit": limit,
"spss": 50})
return d.get("traces", [])
def trace_raw_text(self, trace_id):
d = self.get("/api/datasources/proxy/uid/tempo/api/traces/" + trace_id, raw=True)
return json.dumps(d, ensure_ascii=False) if d else ""
# ------------------------------------------------------------------ Grafana
def ds_query(self, target, ds, since=900):
now = int(time.time() * 1000)
q = dict(target, refId=target.get("refId", "A"), datasource=ds, intervalMs=10000, maxDataPoints=200)
return self.request("POST", "/api/ds/query", body={"queries": [q], "from": str(now - since * 1000), "to": str(now)})
def _val(v):
for k in ("stringValue", "intValue", "doubleValue", "boolValue"):
if k in v:
return int(v[k]) if k == "intValue" else v[k]
return v
def _hex(b64_or_hex):
"""Tempo отдаёт ID в base64 (protobuf JSON) — приводим к hex, как в логах."""
if not b64_or_hex:
return ""
if all(c in "0123456789abcdef" for c in b64_or_hex) and len(b64_or_hex) in (16, 32):
return b64_or_hex
return base64.b64decode(b64_or_hex).hex()
def wait_for(probe, timeout=60, interval=1.0, what="condition"):
deadline = time.monotonic() + timeout
last_exc = None
while time.monotonic() < deadline:
try:
v = probe()
if v:
return v
except ObsError as e:
last_exc = e
time.sleep(interval)
raise ObsError("%s not observed in %ss%s" % (what, timeout, (" (%s)" % last_exc) if last_exc else ""))
+85
View File
@@ -0,0 +1,85 @@
"""Внедрение отказов на стороне S3 «в обход API» (только для тестов).
Выполняется ВНУТРИ контейнера s3-init (у него есть admin-ключи и сеть objects); тестам передаётся
через stdin: docker compose run --rm --no-deps -T --entrypoint python s3-init - <op> <key> [b64]
put <key> <base64> — записать объект; delete <key> — удалить; sha <key> — SHA-256 или "-"
ls <prefix> — ключи по префиксу; anon-get <key> — HTTP-статус анонимного GET.
seed <prefix> <n> <size> — n случайных объектов (параллельно), печать «key sha256 size»;
purge <prefix> — удалить все объекты с префиксом (уборка после эксперимента).
"""
import asyncio
import base64
import hashlib
import os
import sys
from messenger.config import _secret
from messenger.s3 import S3Client, S3Error
async def seed(s3, bucket, prefix, n, size):
import uuid
sem = asyncio.Semaphore(32)
async def one():
body = os.urandom(size)
key = prefix + uuid.uuid4().hex
async with sem:
await s3.put_object(bucket, key, body)
print(key, hashlib.sha256(body).hexdigest(), size)
for start in range(0, n, 500): # пачками: 20k корутин сразу не влезают в 128 МиБ контейнера
await asyncio.gather(*(one() for _ in range(min(500, n - start))))
async def purge(s3, bucket, prefix):
keys = [o.key async for o in s3.list_objects(bucket, prefix=prefix)]
sem = asyncio.Semaphore(32)
async def one(k):
async with sem:
await s3.delete_object(bucket, k)
for start in range(0, len(keys), 500):
await asyncio.gather(*(one(k) for k in keys[start:start + 500]))
print(len(keys))
async def main(op, key, data=None, extra=None):
bucket = os.environ.get("S3_BUCKET", "messenger-attachments")
endpoint = os.environ.get("S3_ENDPOINT", "https://s3:9000")
if op == "anon-get":
import httpx
from messenger import tlsconf
async with httpx.AsyncClient(verify=tlsconf.client_context(client_cert=False)) as c:
print((await c.get(f"{endpoint}/{bucket}/{key}")).status_code)
return
s3 = S3Client(endpoint, os.environ.get("S3_REGION", "us-east-1"),
_secret("S3_ACCESS_KEY_ID", True), _secret("S3_SECRET_ACCESS_KEY", True))
try:
if op == "put":
await s3.put_object(bucket, key, base64.b64decode(data), "application/octet-stream")
elif op == "delete":
await s3.delete_object(bucket, key)
elif op == "sha":
try:
resp = await s3.get_object_stream(bucket, key)
except S3Error as exc:
if exc.status == 404:
print("-")
return
raise
print(hashlib.sha256(await resp.aread()).hexdigest())
await resp.aclose()
elif op == "seed":
await seed(s3, bucket, key, int(data), int(extra))
elif op == "purge":
await purge(s3, bucket, key)
elif op == "ls":
async for o in s3.list_objects(bucket, prefix=key):
print(o.key, o.size)
else:
raise SystemExit("unknown op " + op)
finally:
await s3.aclose()
asyncio.run(main(*sys.argv[1:]))
+38
View File
@@ -0,0 +1,38 @@
"""Копирование файлов ВНУТРИ secrets/ для тестов (снимок «украденного» материала трека 1, копия старого сертификата LB).
Закрытые ключи сервисов принадлежат uid сервиса и имеют права 0400 (их выставляет одноразовый контейнер pki). На
Linux-хосте без root прочитать их нельзя — тогда копирование выполняет тот же контейнер pki (root + DAC_OVERRIDE,
network_mode: none, монтирует только ./secrets). На Windows/macOS (Docker Desktop) и под root копирует сам хост.
Значения не выводятся.
"""
import os
import shlex
import shutil
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SECRETS = ROOT / "secrets"
DC = shlex.split(os.environ.get("COMPOSE", "docker compose --env-file .env"))
def copy_secrets(pairs, mode=0o644):
"""pairs — [(src, dst)] относительно secrets/; каталоги назначения создаются на хосте заранее."""
for _, dst in pairs:
(SECRETS / dst).parent.mkdir(parents=True, exist_ok=True)
try:
for src, dst in pairs:
shutil.copyfile(SECRETS / src, SECRETS / dst)
os.chmod(SECRETS / dst, mode)
return "host"
except PermissionError:
pass
q = shlex.quote
script = "set -e; " + "; ".join(
"cp %s %s && chmod %o %s" % (q("/work/secrets/" + s), q("/work/secrets/" + d), mode, q("/work/secrets/" + d))
for s, d in pairs)
r = subprocess.run(DC + ["--profile", "tools", "run", "--rm", "--no-deps", "-T", "--entrypoint", "sh", "pki",
"-c", script], cwd=ROOT, capture_output=True, text=True, timeout=180)
if r.returncode != 0:
raise RuntimeError("copy via pki container failed: %s" % (r.stderr or r.stdout)[-300:])
return "pki container"
+238
View File
@@ -0,0 +1,238 @@
#!/usr/bin/env python3
"""Негативные и контрактные проверки уровня 3/4: аутентификация, KDF, валидация, ACL, пагинация,
атомарность/rollback создания чата, гонка регистрации, параметризация SQL."""
import hashlib
import threading
import uuid
from urllib.parse import quote
from common import BASE_URL, Client, Suite, basic, check, login, new_user, sql
c = Client(BASE_URL)
s = Suite("API, auth, validation, ACL, transactions (" + BASE_URL + ")")
alice = new_user(c, "alice"); login(c, alice)
bob = new_user(c, "bob"); login(c, bob)
eve = new_user(c, "eve"); login(c, eve)
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "student-tests", "member_ids": [alice["id"], bob["id"]]})["json"]
CHAT = "/api/v1/chats/" + chat["id"]
@s.case("password stored only as Argon2id hash (lab7; salt+params in PHC); User has no secret fields")
def _():
row = sql("SELECT password_hash FROM users WHERE id = '%s'" % alice["id"])[0]
check(row.startswith("$argon2id$v=19$m=") and ",t=" in row and ",p=" in row, "unexpected hash format")
check(alice["password"] not in row, "plaintext password in DB")
check(set(alice["user"]) == {"id", "username", "display_name", "created_at"}, "User leaks fields")
other = new_user(c, "same", password=alice["password"])
h2 = sql("SELECT password_hash FROM users WHERE id = '%s'" % other["id"])[0]
check(h2 != row, "same password produced same hash: salt missing")
@s.case("wrong password and unknown user: identical 401 + Basic challenge")
def _():
r1 = c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic(alice["username"], "wrong-password-123")})
r2 = c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic("no_such_user_x", "wrong-password-123")})
check(r1["json"]["error"]["message"] == r2["json"]["error"]["message"], "messages differ")
check(r1["headers"]["WWW-Authenticate"] == 'Basic realm="messenger", charset="UTF-8"', "challenge mismatch")
@s.case("malformed Basic / Bearer on /auth/sessions / body on login")
def _():
for value in ("Basic", "Basic !!!", "Basic " + "bm9jb2xvbg==", "Bearer " + "x" * 43):
c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": value})
c.call("POST", "/api/v1/auth/sessions", 401)
c.call("POST", "/api/v1/auth/sessions", 400, body={"username": alice["username"]},
headers={"Authorization": basic(alice["username"], alice["password"])})
@s.case("password with ':' and non-ASCII UTF-8 works (RFC 7617)")
def _():
u = new_user(c, "colon", password="пароль:с:двоеточием-😀")
login(c, u)
me = c.call("GET", "/api/v1/users/me", actor=u, schema="User")["json"]
check(me["id"] == u["id"], "wrong user")
@s.case("opaque 256-bit token, unique per login, DB stores only SHA-256")
def _():
a, b = dict(alice), dict(alice)
login(c, a); login(c, b)
check(a["token"] != b["token"] and len(a["token"]) == 43, "token not unique/opaque")
check(a["token"] not in (alice["id"], alice["username"]), "token derived from identity")
digest = hashlib.sha256(a["token"].encode()).hexdigest()
check(sql("SELECT count(*) FROM sessions WHERE token_hash = decode('%s','hex')" % digest) == ["1"], "hash not found")
check(sql("SELECT count(*) FROM information_schema.columns WHERE table_name = 'sessions'"
" AND data_type IN ('text', 'character varying')") == ["0"], "sessions has a text column for raw token")
@s.case("only Bearer accepted; Basic and X-User-Id never authenticate")
def _():
c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": basic(alice["username"], alice["password"])})
c.call("GET", "/api/v1/chats", 401, headers={"X-User-Id": alice["id"]})
c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Bearer " + "A" * 43})
c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Bearer short"})
me = c.call("GET", "/api/v1/users/me", actor=bob, headers={"X-User-Id": alice["id"]}, schema="User")["json"]
check(me["id"] == bob["id"], "X-User-Id overrode session")
@s.case("logout revokes only the current session; repeat -> 401")
def _():
u = new_user(c, "logout"); first = dict(u); second = dict(u)
login(c, first); login(c, second)
c.call("GET", "/api/v1/users/me", actor=first, schema="User") # прогреть кэш
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=first)
for path in ("/api/v1/users/me", "/api/v1/chats"):
c.call("GET", path, 401, actor=first)
c.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=first)
c.call("GET", "/api/v1/users/me", actor=second, schema="User")
check(sql("SELECT count(*) FROM sessions WHERE user_id='%s' AND revoked_at IS NOT NULL" % u["id"]) == ["1"],
"revocation not persisted")
@s.case("strict JSON validation -> 400")
def _():
base = {"username": "valid_" + uuid.uuid4().hex[:8], "display_name": "X", "password": "p" * 12}
bad = [dict(base, extra=1), dict(base, username="UPPER"), dict(base, username="ab"),
dict(base, display_name=" "), dict(base, display_name="x" * 101), dict(base, password="p" * 11),
dict(base, password="p" * 129), dict(base, display_name=5), {"username": base["username"]}]
for body in bad:
c.call("POST", "/api/v1/users", 400, body=body)
c.call("POST", "/api/v1/users", 400, raw=b'{"username": ', headers={"Content-Type": "application/json"})
c.call("POST", "/api/v1/users", 400, raw=b'[1,2]', headers={"Content-Type": "application/json"})
c.call("POST", "/api/v1/users", 400, raw=b'{"username":"a","username":"b"}', headers={"Content-Type": "application/json"})
c.call("POST", "/api/v1/users", 400, raw=b'username=x', headers={"Content-Type": "application/x-www-form-urlencoded"})
c.call("POST", "/api/v1/users", 413, raw=b'{"x":"' + b"a" * 70000 + b'"}', headers={"Content-Type": "application/json"})
@s.case("message text: 4000 code points OK, 4001 / whitespace / sender_id -> 400")
def _():
msg = c.message(alice, chat, "😀" * 4000)["json"]
check(len(msg["text"]) == 4000, "text truncated")
for body in ({"text": "a" * 4001}, {"text": " \n\t "}, {"text": "x", "sender_id": bob["id"]}, {"text": None}, {}):
c.call("POST", CHAT + "/messages", 400, actor=alice, body=body)
@s.case("SQL is parameterized: injection payloads stored verbatim")
def _():
payload = "'); DROP TABLE messages; -- \" \\ %s $1"
msg = c.message(alice, chat, payload)["json"]
check(msg["text"] == payload, "payload altered")
c.call("GET", CHAT + "/messages?limit=1", actor=alice, schema="MessagePage")
c.call("GET", "/api/v1/chats/" + quote("' OR 1=1 --", safe=""), 400, actor=alice)
@s.case("ACL: outsider gets 404 everywhere (even for invalid body)")
def _():
c.call("GET", CHAT, 404, actor=eve)
c.call("GET", CHAT + "/messages", 404, actor=eve)
c.call("POST", CHAT + "/messages", 404, actor=eve, body={"text": "x"})
c.call("POST", CHAT + "/messages", 404, actor=eve, body={"text": ""})
c.call("GET", "/api/v1/chats/" + str(uuid.uuid4()), 404, actor=alice)
c.call("GET", "/api/v1/chats/not-a-uuid", 400, actor=alice)
got = c.call("GET", CHAT, actor=bob, schema="Chat")["json"]
check(got["member_ids"] == [alice["id"], bob["id"]], "member order/content changed")
@s.case("create chat validation: duplicates, caller missing, unknown member")
def _():
c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": "d", "member_ids": [alice["id"], alice["id"]]})
c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": "d", "member_ids": [bob["id"]]})
c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": "d", "member_ids": []})
c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": " ", "member_ids": [alice["id"]]})
@s.case("compound create-chat rolls back on FK failure (no orphan chat)")
def _():
title = "rollback-" + uuid.uuid4().hex
before = sql("SELECT count(*) FROM chats")[0]
c.call("POST", "/api/v1/chats", 400, actor=alice,
body={"title": title, "member_ids": [alice["id"], bob["id"], str(uuid.uuid4())]})
check(sql("SELECT count(*) FROM chats WHERE title = '%s'" % title) == ["0"], "orphan chat committed")
check(sql("SELECT count(*) FROM chat_members m LEFT JOIN chats c ON c.id = m.chat_id WHERE c.id IS NULL") == ["0"],
"orphan membership")
return "chats before=%s, failed insert left 0 rows" % before
@s.case("registration race: 20 parallel same username -> exactly one 201")
def _():
username = "race_" + uuid.uuid4().hex[:12]
statuses, lock = [], threading.Lock()
barrier = threading.Barrier(20)
def worker():
local = Client(BASE_URL, timeout=30)
barrier.wait()
r = local.call("POST", "/api/v1/users", [201, 409],
body={"username": username, "display_name": "R", "password": "Race-password-123"})
with lock:
statuses.append(r["status"])
threads = [threading.Thread(target=worker) for _ in range(20)]
[t.start() for t in threads]; [t.join() for t in threads]
check(sorted(statuses) == [201] + [409] * 19, "statuses: %s" % sorted(statuses))
check(sql("SELECT count(*) FROM users WHERE username = '%s'" % username) == ["1"], "duplicate rows")
return "201x1, 409x19, rows=1"
@s.case("keyset pagination: 120 msgs, varying limit, no gaps/duplicates")
def _():
room = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "pages", "member_ids": [alice["id"], bob["id"]]})["json"]
path = "/api/v1/chats/" + room["id"] + "/messages"
sent = [c.message(alice if i % 2 else bob, room, "m%03d" % i)["json"] for i in range(120)]
got, cursor, limits, n = [], None, [7, 1, 50, 100, 3], 0
while True:
q = "?limit=%d" % limits[n % len(limits)] + ("&cursor=" + quote(cursor, safe="") if cursor else "")
page = c.call("GET", path + q, actor=bob, schema="MessagePage")["json"]
got.extend(page["items"]); cursor = page["next_cursor"]; n += 1
if cursor is None:
break
check([m["id"] for m in got] == [m["id"] for m in sent], "order/completeness mismatch")
first = c.call("GET", path + "?limit=2", actor=bob, schema="MessagePage")["json"]
c.call("GET", CHAT + "/messages?cursor=" + quote(first["next_cursor"], safe=""), 400, actor=alice)
for q in ("?limit=0", "?limit=101", "?limit=abc", "?limit=-1", "?limit=1&limit=2", "?cursor=garbage", "?cursor="):
c.call("GET", path + q, 400, actor=bob)
default = c.call("GET", path, actor=bob, schema="MessagePage")["json"]
check(len(default["items"]) == 50 and default["next_cursor"], "default limit must be 50")
return "%d pages" % n
@s.case("chat list: only own chats, ordered, cursor bound to user")
def _():
u = new_user(c, "lister"); login(c, u)
made = [c.call("POST", "/api/v1/chats", 201, actor=u, schema="Chat",
body={"title": "c%d" % i, "member_ids": [u["id"]]})["json"]["id"] for i in range(3)]
got, cursor = [], None
while True:
page = c.call("GET", "/api/v1/chats?limit=1" + ("&cursor=" + quote(cursor, safe="") if cursor else ""),
actor=u, schema="ChatPage")["json"]
got += [x["id"] for x in page["items"]]; cursor = page["next_cursor"]
if cursor is None:
break
foreign = cursor
check(got == made, "chat list mismatch")
c.call("GET", "/api/v1/chats?cursor=" + quote(foreign, safe=""), 400, actor=alice)
@s.case("read-after-write: confirmed message visible to next read")
def _():
m = c.message(bob, chat, "raw-" + uuid.uuid4().hex)["json"]
items, cursor = [], None
while True:
page = c.call("GET", CHAT + "/messages?limit=100" + ("&cursor=" + quote(cursor, safe="") if cursor else ""),
actor=alice, schema="MessagePage")["json"]
items += page["items"]; cursor = page["next_cursor"]
if not cursor:
break
check(items[-1] == m, "last message is not the just-written one")
@s.case("unknown route 404 / wrong method 405 in error format")
def _():
c.call("GET", "/api/v1/nope", 404)
r = c.call("PUT", "/api/v1/users", 405, body={})
check(r["json"]["error"]["code"] == "invalid_request", "405 code")
if __name__ == "__main__":
s.run()
+255
View File
@@ -0,0 +1,255 @@
#!/usr/bin/env python3
"""Вложения (lab4, адаптировано к lab5: upload → 202, готовность — по статусу): корректные файлы, лимиты, повреждения, подмена MIME, filename, ACL, чужие ID.
Каждая пользовательская ошибка обязана дать 4xx из контракта, а не 500 (Client проверяет код и формат
Error). Только синтетические данные; стенд и volumes не трогаются.
"""
import hashlib
import os
import socket
import time
import uuid
import zlib
from pathlib import Path
from urllib.parse import quote, urlsplit
from common import BASE_URL, Client, Suite, check, login, make_png, new_user
c = Client(BASE_URL, timeout=30)
s = Suite("attachments (" + BASE_URL + ")")
JPEG = (Path(__file__).parent / "fixtures" / "photo.jpg").read_bytes()
MAX = int(os.environ.get("MAX_UPLOAD_BYTES", str(10 * 1024 * 1024)))
alice = new_user(c, "aa"); login(c, alice)
bob = new_user(c, "ab"); login(c, bob)
eve = new_user(c, "ae"); login(c, eve)
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "files", "member_ids": [alice["id"], bob["id"]]})["json"]
other = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "other", "member_ids": [alice["id"]]})["json"]
UP = "/api/v1/chats/" + chat["id"] + "/attachments"
def chunk(t, d):
return len(d).to_bytes(4, "big") + t + d + zlib.crc32(t + d).to_bytes(4, "big")
def png_with(width, height, idat_raw, color_type=2, level=9):
ihdr = width.to_bytes(4, "big") + height.to_bytes(4, "big") + bytes([8, color_type, 0, 0, 0])
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(idat_raw, level))
+ chunk(b"IEND", b""))
def big_png(target):
"""Несжимаемый RGB PNG размером чуть меньше target байт."""
side = int(((target - 4096) / 3) ** 0.5)
rows = b"".join(b"\x00" + os.urandom(side * 3) for _ in range(side))
return png_with(side, side, rows, level=1)
def post(data, ctype="image/png", filename="f.png", expected=202, actor=None, chat_id=None):
path = "/api/v1/chats/" + (chat_id or chat["id"]) + "/attachments?filename=" + quote(filename, safe="")
return c.call("POST", path, expected, actor=actor or alice, raw=data, headers={"Content-Type": ctype},
schema="Attachment" if expected == 202 else None)
def ready(att):
"""lab5: content доступен только после ready (до этого — 409)."""
return c.wait_ready(alice, att)
def raw_http(head: bytes, body: bytes = b"", wait=5.0):
"""Сырые байты через сокет: запрос, который urllib не умеет отправить (обрыв, ложный Content-Length)."""
u = urlsplit(BASE_URL)
sock = socket.create_connection((u.hostname, u.port or (443 if u.scheme == "https" else 80)), timeout=wait)
if u.scheme == "https": # lab7: тот же сырой запрос, но внутри TLS с проверкой CA/имени
import ssl
from common import CA_FILE
sock = ssl.create_default_context(cafile=CA_FILE).wrap_socket(sock, server_hostname=u.hostname)
try:
sock.sendall(head + body)
t = time.monotonic()
data = b""
while b"\r\n" not in data:
part = sock.recv(4096)
if not part:
break
data += part
return data.split(b"\r\n", 1)[0].decode(errors="replace"), time.monotonic() - t
finally:
sock.close()
@s.case("valid PNG and JPEG: 202 queued → ready, byte-exact download by other member")
def _():
png = make_png(40, 30)
for data, ctype, name in ((png, "image/png", "фото отпуска.png"), (JPEG, "image/jpeg", "photo.jpg")):
att = post(data, ctype, name)["json"]
check(att["status"] in ("queued", "processing", "ready") and att["size_bytes"] == len(data), "bad metadata")
att = ready(att)
check(att["sha256"] == hashlib.sha256(data).hexdigest() and att["filename"] == name, "sha/filename mismatch")
r = c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=bob)
check(r["bytes"] == data, "download differs")
h = r["headers"]
check(h.get_content_type() == ctype and h.get("X-Content-Type-Options") == "nosniff", "unsafe headers")
check(int(h["Content-Length"]) == len(data), "Content-Length")
check("attachment" in h.get("Content-Disposition", "") or "inline" in h.get("Content-Disposition", ""),
"Content-Disposition missing")
msg = c.message(alice, chat, "", attachments=[att["id"]])["json"] # пустой текст + вложение
check(msg["attachment_ids"] == [att["id"]], "message lost attachment")
@s.case("exactly-near limit (~10 MiB) accepted, Content-Length > limit -> 413")
def _():
data = big_png(MAX)
check(len(data) <= MAX, "fixture too big")
att = post(data, filename="big.png")["json"]
check(att["size_bytes"] == len(data), "size")
over = data + b"\x00" * (MAX + 1 - len(data))
post(over, filename="over.png", expected=413)
return "%.2f MiB accepted" % (len(data) / 2**20)
@s.case("oversize rejected BEFORE body is read (early 413, socket)")
def _():
u = urlsplit(BASE_URL)
head = ("POST %s?filename=x.png HTTP/1.1\r\nHost: %s\r\nAuthorization: Bearer %s\r\nContent-Type: image/png\r\n"
"Content-Length: %d\r\nConnection: close\r\n\r\n" % (UP, u.netloc, alice["token"], 50 * 2**20)).encode()
status, took = raw_http(head, b"\x89PNG\r\n\x1a\n")
check(" 413 " in status + " ", "expected 413, got " + status)
check(took < 3, "413 took %.2fs (body awaited?)" % took)
return "%s in %.3fs, 50 MiB never sent" % (status, took)
@s.case("pixel limit: 8000x6000 header -> 413 without decoding")
def _():
# 48 млн пикселей > 40 млн: отклоняется по IHDR/SOF, IDAT даже не нужен корректный
ihdr = (8000).to_bytes(4, "big") + (6000).to_bytes(4, "big") + bytes([8, 2, 0, 0, 0])
bomb = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(b"\x00" * 1000)) + chunk(b"IEND", b"")
t = time.monotonic()
post(bomb, expected=413)
jpeg = bytearray(JPEG)
i = jpeg.find(b"\xff\xc0")
jpeg[i + 5:i + 9] = (7000).to_bytes(2, "big") + (7000).to_bytes(2, "big") # SOF: 49 Мп
post(bytes(jpeg), "image/jpeg", "big.jpg", expected=413)
return "%.3fs" % (time.monotonic() - t)
@s.case("decompression bomb: IDAT inflates beyond declared size -> 415")
def _():
bomb = png_with(100, 100, b"\x00" * (64 * 2**20)) # 64 МиБ нулей сжимаются в ~64 КиБ
check(len(bomb) < 200_000, "bomb not small")
t = time.monotonic()
post(bomb, expected=415)
return "%d-byte file claiming 64 MiB raw, rejected in %.3fs" % (len(bomb), time.monotonic() - t)
@s.case("corrupted images -> 415 (truncated, bad CRC, no EOI, garbage, empty)")
def _():
png = make_png(20, 20)
bad_crc = bytearray(png); bad_crc[30] ^= 0x01
cases = [(png[:-12], "image/png"), (bytes(bad_crc), "image/png"), (JPEG[:-2], "image/jpeg"),
(JPEG[:len(JPEG) // 2], "image/jpeg"), (os.urandom(4096), "image/png"),
(b"\x89PNG\r\n\x1a\n" + os.urandom(500), "image/png"), (b"\xff\xd8\xff" + os.urandom(500), "image/jpeg"),
(png + b"trailing-garbage", "image/png"), (b"", "image/png")]
for data, ctype in cases:
post(data, ctype, expected=415)
return "%d variants" % len(cases)
@s.case("MIME spoofing by Content-Type/filename -> 415")
def _():
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;"
cases = [(make_png(), "image/jpeg", "a.jpg"), (JPEG, "image/png", "a.png"),
(b"<html><script>alert(1)</script></html>", "image/png", "a.png"),
(gif, "image/png", "a.png"), (gif, "image/gif", "a.gif"), (make_png(), "application/octet-stream", "a.png"),
(make_png(), "text/html", "a.html"), (b"<svg xmlns='http://www.w3.org/2000/svg'/>", "image/svg+xml", "a.svg")]
for data, ctype, name in cases:
post(data, ctype, name, expected=415)
@s.case("dangerous/invalid filenames -> 400; filename never becomes a path")
def _():
png = make_png()
for name in ("", "../../etc/passwd", "a/b.png", "a\\b.png", "x\x00.png", "line\nbreak.png", "\t.png", ".", "..",
"x" * 256, "‮evil.png"):
post(png, filename=name, expected=400)
c.call("POST", UP, 400, actor=alice, raw=png, headers={"Content-Type": "image/png"}) # filename отсутствует
ok = post(png, filename="y" * 251 + ".png")["json"]
check(len(ok["filename"]) == 255, "255-char name must be accepted")
@s.case("missing/invalid Content-Length -> 400 (chunked upload is not accepted)")
def _():
u = urlsplit(BASE_URL)
head = ("POST %s?filename=x.png HTTP/1.1\r\nHost: %s\r\nAuthorization: Bearer %s\r\nContent-Type: image/png\r\n"
"Transfer-Encoding: chunked\r\nConnection: close\r\n\r\n" % (UP, u.netloc, alice["token"])).encode()
png = make_png()
status, _ = raw_http(head, b"%x\r\n" % len(png) + png + b"\r\n0\r\n\r\n")
check(" 400 " in status + " " or " 411 " in status + " ", "chunked upload: " + status)
return status
@s.case("ACL: outsider gets 404 for upload/metadata/content; anonymous 401")
def _():
att = post(make_png())["json"]
t = time.monotonic()
post(big_png(MAX), actor=eve, expected=404) # посторонний — 404 до чтения 10 МиБ
took = time.monotonic() - t
for path in ("", "/content", "/content?variant=original"):
c.call("GET", "/api/v1/attachments/" + att["id"] + path, 404, actor=eve)
c.call("GET", "/api/v1/attachments/" + att["id"] + path, 401)
c.call("GET", "/api/v1/attachments/" + str(uuid.uuid4()), 404, actor=alice)
c.call("GET", "/api/v1/attachments/not-a-uuid", [400, 404], actor=alice)
c.call("POST", UP + "?filename=a.png", 401, raw=make_png(), headers={"Content-Type": "image/png"})
c.call("POST", "/api/v1/chats/" + str(uuid.uuid4()) + "/attachments?filename=a.png", 404, actor=alice,
raw=make_png(), headers={"Content-Type": "image/png"})
return "outsider 10 MiB upload rejected in %.2fs" % took
@s.case("variants (lab5): original/thumbnail/crop/optimized OK after ready, unknown -> 400")
def _():
att = ready(post(make_png())["json"])
for v in ("original", "thumbnail", "crop", "optimized"):
c.call("GET", "/api/v1/attachments/" + att["id"] + "/content?variant=" + v, actor=bob)
c.call("GET", "/api/v1/attachments/" + att["id"] + "/content?variant=../../x", 400, actor=bob)
@s.case("message: foreign/unknown attachment_id -> 404, file of other chat -> 404, limits -> 400")
def _():
mine = post(make_png())["json"]
foreign = post(make_png(), chat_id=other["id"])["json"] # тот же владелец, ДРУГОЙ чат
path = "/api/v1/chats/" + chat["id"] + "/messages"
def send(body, expected, actor=alice):
return c.call("POST", path, expected, actor=actor, body=body, headers={"Idempotency-Key": uuid.uuid4().hex})
send({"text": "x", "attachment_ids": [foreign["id"]]}, 404)
send({"text": "x", "attachment_ids": [mine["id"], foreign["id"]]}, 404)
send({"text": "x", "attachment_ids": [str(uuid.uuid4())]}, 404)
send({"text": "x", "attachment_ids": ["nope"]}, 400)
send({"text": "x", "attachment_ids": [mine["id"], mine["id"]]}, 400)
send({"text": "x", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]}, 400)
send({"text": "", "attachment_ids": []}, 400)
send({"text": ""}, 400)
send({"text": "x" * 4001, "attachment_ids": [mine["id"]]}, 400)
# постороннему чат не виден вовсе
c.call("POST", path, 404, actor=eve, body={"text": "x", "attachment_ids": [mine["id"]]},
headers={"Idempotency-Key": uuid.uuid4().hex})
hist = c.call("GET", path + "?limit=50", actor=bob, schema="MessagePage")["json"]
check(all(foreign["id"] not in m.get("attachment_ids", []) for m in hist["items"]), "foreign file leaked")
@s.case("idempotency includes attachment_ids (replay same, conflict on change)")
def _():
a, b = post(make_png())["json"], post(make_png())["json"]
path = "/api/v1/chats/" + chat["id"] + "/messages"
key = uuid.uuid4().hex
first = c.call("POST", path, 201, actor=alice, body={"text": "k", "attachment_ids": [a["id"], b["id"]]},
headers={"Idempotency-Key": key}, schema="Message")["json"]
again = c.call("POST", path, [200, 201], actor=alice, body={"text": "k", "attachment_ids": [a["id"], b["id"]]},
headers={"Idempotency-Key": key}, schema="Message")["json"]
check(again["id"] == first["id"] and again["attachment_ids"] == [a["id"], b["id"]], "replay differs")
c.call("POST", path, 409, actor=alice, body={"text": "k", "attachment_ids": [b["id"], a["id"]]},
headers={"Idempotency-Key": key})
s.run()
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""In-process проверки политики кэша сессий против настоящего Redis/Valkey (нужен CACHE_URL[_FILE]).
Сценарий гонки: запрос A прочитал сессию из PostgreSQL ДО logout, а записать её в кэш пытается ПОСЛЕ
logout. Без защиты отозванный токен жил бы в кэше до SESSION_CACHE_TTL_SECONDS. Защита — «надгробие»
и атомарный Lua SET-if-not-revoked. Запуск в Compose: make test-cache-race.
"""
import asyncio
import os
import secrets
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
os.environ.setdefault("DATABASE_URL", "postgresql://unused") # БД этому тесту не нужна
from messenger import vault # noqa: E402
from messenger.config import load # noqa: E402
from messenger.sessions import KEY, TOMBSTONE, Principal, SessionCache # noqa: E402
async def main():
client = vault.init("api") # lab7: ACL-учётные данные Redis — из OpenBao (AppRole сервиса api)
settings = load(client.data if client else None)
if not settings.cache_enabled:
raise SystemExit("CACHE_URL or CACHE_URL_FILE is required")
cache = SessionCache(settings)
cache.degraded = False
user = {"id": "00000000-0000-4000-8000-000000000000", "username": "cache_test", "display_name": "t",
"created_at": "2026-01-01T00:00:00.000000Z"}
failures = 0
def report(ok, title, note=""):
nonlocal failures
failures += 0 if ok else 1
print(("PASS " if ok else "FAIL ") + title + ((" " + note) if note else ""))
th = secrets.token_bytes(32)
p = Principal(user=user, expires_at=time.time() + 3600, token_hash=th)
await cache.put(p)
report((await cache.get(th)) is not None, "read-through put makes entry readable")
ttl = await cache.client.pttl(KEY + th.hex())
report(0 < ttl <= settings.session_cache_ttl_seconds * 1000, "entry TTL capped by SESSION_CACHE_TTL_SECONDS",
"pttl=%dms" % ttl)
await cache.invalidate(th) # logout
report((await cache.get(th)) is None, "invalidate removes entry")
await cache.put(p) # «опоздавший» read-through после logout
report((await cache.client.exists(KEY + th.hex())) == 0, "late put after logout is refused by tombstone")
tomb = await cache.client.pttl(TOMBSTONE + th.hex())
report(tomb > settings.session_cache_ttl_seconds * 1000, "tombstone outlives any cache entry", "pttl=%dms" % tomb)
th2 = secrets.token_bytes(32)
await cache.put(Principal(user=user, expires_at=time.time() + 1.2, token_hash=th2))
ttl2 = await cache.client.pttl(KEY + th2.hex())
report(0 < ttl2 <= 1200, "entry never outlives session expiry", "pttl=%dms" % ttl2)
await asyncio.sleep(1.3)
report((await cache.get(th2)) is None, "expired session not served from cache")
th3 = secrets.token_bytes(32)
await cache.put(Principal(user=user, expires_at=time.time() + 3600, token_hash=th3))
cache._fail("test", ConnectionError("simulated"))
report((await cache.get(th3)) is None, "degraded mode: cache is not read until outbox drained")
await cache.client.delete(KEY + th.hex(), TOMBSTONE + th.hex(), KEY + th3.hex())
await cache.close()
print("summary: %s" % ("all passed" if not failures else "%d failed" % failures))
raise SystemExit(1 if failures else 0)
if __name__ == "__main__":
asyncio.run(main())
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Истечение сессии при коротком SESSION_TTL_SECONDS (экземпляр api-ttl, профиль compose `ttl`).
Проверяет и путь через кэш Redis (запись кэша прогрета сразу после входа), и путь через PostgreSQL:
TTL записи в кэше = min(SESSION_CACHE_TTL_SECONDS, остаток сессии), поэтому кэш не продлевает сессию.
"""
import datetime as dt
import time
from common import TTL_BASE_URL, TTL_SECONDS, Client, Suite, check, login, new_user, sql
c = Client(TTL_BASE_URL)
s = Suite("session expiry, SESSION_TTL_SECONDS=%g (%s)" % (TTL_SECONDS, TTL_BASE_URL))
@s.case("expires_at = now + SESSION_TTL_SECONDS")
def _():
u = new_user(c, "ttl"); login(c, u)
left = dt.datetime.fromisoformat(u["expires_at"][:-1] + "+00:00") - dt.datetime.now(dt.timezone.utc)
check(0 < left.total_seconds() <= TTL_SECONDS + 0.5, "unexpected TTL: %s" % left)
return "remaining %.2fs" % left.total_seconds()
@s.case("token valid before expiry, 401 Bearer after (cache warmed)")
def _():
u = new_user(c, "ttl2"); login(c, u)
c.call("GET", "/api/v1/users/me", actor=u, schema="User") # заполняет кэш
c.call("GET", "/api/v1/chats", actor=u, schema="ChatPage")
time.sleep(TTL_SECONDS + 1.0)
r = c.call("GET", "/api/v1/users/me", 401, actor=u)
check(r["headers"]["WWW-Authenticate"].startswith("Bearer"), "challenge")
c.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=u)
rows = sql("SELECT (expires_at < clock_timestamp())::text, (revoked_at IS NULL)::text FROM sessions s"
" JOIN users u ON u.id = s.user_id WHERE u.username = '%s'" % u["username"])
check(rows == ["true|true"], "expiry must come from expires_at, not deletion/revocation: %s" % rows)
@s.case("re-login after expiry issues a new valid session")
def _():
u = new_user(c, "ttl3"); login(c, u)
old = u["token"]
time.sleep(TTL_SECONDS + 1.0)
c.call("GET", "/api/v1/users/me", 401, actor=u)
login(c, u)
check(u["token"] != old, "token reused")
c.call("GET", "/api/v1/users/me", actor=u, schema="User")
if __name__ == "__main__":
s.run()
+96
View File
@@ -0,0 +1,96 @@
#!/usr/bin/env python3
"""Отказы зависимостей: Redis (кэш) и PostgreSQL (источник истины).
ВНИМАНИЕ: тест останавливает и снова запускает контейнеры redis и postgres (по умолчанию через
docker compose; команды переопределяются STOP_DB/START_DB/STOP_CACHE/START_CACHE). Volumes не трогает.
"""
import time
import uuid
from common import BASE_URL, Client, Failure, Suite, basic, check, login, new_user, sh, sql, wait_until
c = Client(BASE_URL, timeout=10)
s = Suite("dependency failures (" + BASE_URL + ")")
alice = new_user(c, "fa"); login(c, alice)
bob = new_user(c, "fb"); login(c, bob)
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "failures", "member_ids": [alice["id"], bob["id"]]})["json"]
PATH = "/api/v1/chats/" + chat["id"] + "/messages"
def timed(fn):
t = time.monotonic(); r = fn(); return r, time.monotonic() - t
@s.case("Redis down: API bypasses cache via PostgreSQL, no anonymous trust")
def _():
c.call("GET", "/api/v1/users/me", actor=alice, schema="User") # запись в кэше есть
victim = new_user(c, "fv"); login(c, victim)
c.call("GET", "/api/v1/users/me", actor=victim, schema="User")
sh("stop_cache")
try:
_, took = timed(lambda: c.call("GET", "/api/v1/users/me", actor=alice, schema="User"))
check(took < 2.0, "fallback too slow: %.2fs" % took)
c.call("GET", "/health/ready", schema="Health") # кэш не критичен
c.message(alice, chat, "while redis is down")
fresh = new_user(c, "fn"); login(c, fresh) # вход без Redis
c.call("GET", "/api/v1/users/me", actor=fresh, schema="User")
c.call("GET", "/api/v1/users/me", 401) # аноним — 401
c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Bearer " + "B" * 43})
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=victim) # logout при мёртвом Redis
c.call("GET", "/api/v1/users/me", 401, actor=victim)
pending = sql("SELECT count(*) FROM session_cache_invalidations")[0]
finally:
sh("start_cache")
# После возврата Redis старая запись кэша victim не должна «воскресить» отозванный токен.
wait_until(lambda: sql("SELECT count(*) FROM session_cache_invalidations") == ["0"], timeout=30)
for _ in range(10):
c.call("GET", "/api/v1/users/me", 401, actor=victim)
time.sleep(0.3)
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
return "fallback latency %.3fs; outbox rows during outage=%s, drained after recovery" % (took, pending)
@s.case("PostgreSQL down: bounded 503 in error format; anonymous still 401")
def _():
before = len(c.call("GET", PATH + "?limit=100", actor=bob, schema="MessagePage")["json"]["items"])
sh("stop_db")
observed = {}
try:
c.call("GET", "/health/live", schema="Health")
r, took = timed(lambda: c.call("GET", "/health/ready", 503))
observed["ready"] = round(took, 2)
for name, call in {
"post_message": lambda: c.call("POST", PATH, 503, actor=alice, body={"text": "db down"},
headers={"Idempotency-Key": uuid.uuid4().hex}),
"history": lambda: c.call("GET", PATH, 503, actor=bob),
"login": lambda: c.call("POST", "/api/v1/auth/sessions", 503,
headers={"Authorization": basic(alice["username"], alice["password"])}),
"register": lambda: c.call("POST", "/api/v1/users", 503,
body={"username": "x" + uuid.uuid4().hex[:10], "display_name": "x", "password": "p" * 12}),
}.items():
r, took = timed(call)
check(r["json"]["error"]["code"] == "unavailable", name + ": wrong code")
check(took < 5.0, name + ": not bounded (%.2fs)" % took)
check("psycopg" not in r["json"]["error"]["message"].lower(), "leaks internals")
observed[name] = round(took, 2)
c.call("GET", "/api/v1/users/me", 401) # без токена — 401
r = c.call("GET", "/api/v1/chats", [401, 503], headers={"Authorization": "Bearer " + "C" * 43})
check(r["status"] != 200, "unknown token accepted")
finally:
sh("start_db")
t0 = time.monotonic()
wait_until(lambda: c.call("GET", "/health/ready", [200, 503])["status"] == 200, timeout=90)
recovered = time.monotonic() - t0
after = c.call("GET", PATH + "?limit=100", actor=bob, schema="MessagePage")["json"]["items"]
check(len(after) == before, "data changed across DB outage")
c.message(alice, chat, "after db recovery")
return "latency(s)=%s; ready again in %.1fs" % (observed, recovered)
if __name__ == "__main__":
try:
s.run()
except Failure as exc:
print("FAIL", exc)
raise SystemExit(1)
+226
View File
@@ -0,0 +1,226 @@
#!/usr/bin/env python3
"""lab7: аудит запущенного стенда (с хоста, docker inspect) — привилегии контейнеров, опубликованные порты,
секреты вне env/образов/telemetry, отсутствие root token/unseal material у приложения.
python3 student-tests/test_hardening.py [--json evidence/hardening.json]
Значения секретов читаются из secrets/ и каталога оператора только для поиска совпадений и НЕ печатаются.
"""
import argparse
import json
import os
import shlex
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "student-tests"))
from common import DC, check # noqa: E402
PROJECT = "mtusi-lab7"
OPDIR = Path(os.environ.get("MTUSI_OPERATOR_DIR", str(Path.home() / ".mtusi-lab7-operator")))
# Сервисы, которым осознанно оставлены исключения (обоснование — REPORT.md, «Hardening»).
NO_READONLY_OK = set() # все долгоживущие сервисы — read_only
ALLOWED_PORTS = {"8443", "8444", "8445", "3000", "8200"}
APP = {"api", "api-ttl", "api-fault", "worker"}
results = []
def case(title):
def deco(fn):
results.append([title, fn, None, None])
return fn
return deco
def run(cmd, **kw):
return subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, **kw)
def containers():
ids = run(shlex.split(DC) + ["ps", "-q"]).stdout.split()
data = json.loads(run(["docker", "inspect"] + ids).stdout) if ids else []
return [(c["Config"]["Labels"].get("com.docker.compose.service"), c) for c in data]
def secret_values():
vals = {}
for p in (ROOT / "secrets").glob("*"):
if p.is_file() and p.suffix != ".json":
v = p.read_text(errors="ignore").strip()
if len(v) >= 16:
vals["secrets/" + p.name] = v
for svc in ("api", "worker"):
sid = ROOT / "secrets" / "bao" / svc / "secret_id"
if sid.exists():
vals["secret_id:" + svc] = sid.read_text().strip()
init = OPDIR / "openbao-init.json"
if init.exists():
d = json.loads(init.read_text())
vals["openbao root token"] = d["root_token"]
for i, k in enumerate(d["unseal_keys_b64"]):
vals["unseal share %d" % (i + 1)] = k
return vals
@case("контейнеры: нет privileged, host network/pid/ipc, docker.sock; заданы лимиты CPU/RAM/PIDs")
def _():
rows = []
for svc, c in containers():
hc = c["HostConfig"]
check(not hc.get("Privileged"), "%s privileged" % svc)
check(hc.get("NetworkMode") != "host" and hc.get("PidMode") != "host" and hc.get("IpcMode") != "host",
"%s host namespace" % svc)
for m in c.get("Mounts", []):
check("docker.sock" not in (m.get("Source") or ""), "%s mounts docker.sock" % svc)
check(hc.get("Memory", 0) > 0 and hc.get("NanoCpus", 0) > 0 and (hc.get("PidsLimit") or 0) > 0,
"%s without limits (mem=%s cpu=%s pids=%s)" % (svc, hc.get("Memory"), hc.get("NanoCpus"), hc.get("PidsLimit")))
rows.append(svc)
return "%d контейнеров проверено" % len(rows)
@case("контейнеры: не root, cap_drop ALL без cap_add, no-new-privileges, read-only rootfs")
def _():
bad, rows = [], {}
for svc, c in containers():
hc, cfg = c["HostConfig"], c["Config"]
user = cfg.get("User") or "root"
uid = user.split(":")[0]
if uid in ("", "0", "root"):
bad.append("%s runs as root" % svc)
if "ALL" not in (hc.get("CapDrop") or []) or hc.get("CapAdd"):
bad.append("%s caps drop=%s add=%s" % (svc, hc.get("CapDrop"), hc.get("CapAdd")))
if not any("no-new-privileges" in o for o in (hc.get("SecurityOpt") or [])):
bad.append("%s without no-new-privileges" % svc)
if not hc.get("ReadonlyRootfs") and svc not in NO_READONLY_OK:
bad.append("%s rootfs writable" % svc)
rows[svc] = user
check(not bad, "; ".join(bad))
return "users: " + ", ".join("%s=%s" % kv for kv in sorted(rows.items()))
@case("наружу опубликованы только 127.0.0.1: 8443/8444/8445 (LB), 3000 (Grafana), 8200 (OpenBao)")
def _():
pub = []
for svc, c in containers():
for port, binds in (c["NetworkSettings"].get("Ports") or {}).items():
for b in binds or []:
check(b["HostIp"] in ("127.0.0.1",), "%s publishes %s on %s" % (svc, port, b["HostIp"]))
check(b["HostPort"] in ALLOWED_PORTS, "%s publishes unexpected %s" % (svc, b["HostPort"]))
check(svc in ("lb", "grafana", "openbao"), "%s must not publish ports" % svc)
pub.append("%s:%s→%s" % (b["HostIp"], b["HostPort"], svc))
return ", ".join(sorted(set(pub)))
@case("секреты не в переменных окружения контейнеров и образов; нет BAO_TOKEN/VAULT_TOKEN")
def _():
vals = secret_values()
found = []
images = set()
for svc, c in containers():
env = "\n".join(c["Config"].get("Env") or [])
images.add(c["Config"]["Image"])
for name, v in vals.items():
if v in env:
found.append("%s env has %s" % (svc, name))
for bad in ("BAO_TOKEN=", "VAULT_TOKEN=", "AWS_SECRET_ACCESS_KEY=", "PGPASSWORD="):
if bad in env:
found.append("%s env has %s" % (svc, bad.rstrip("=")))
for img in images:
meta = run(["docker", "image", "inspect", img]).stdout
hist = run(["docker", "history", "--no-trunc", "--format", "{{.CreatedBy}}", img]).stdout
for name, v in vals.items():
if v in meta or v in hist:
found.append("image %s has %s" % (img, name))
check(not found, "; ".join(found))
return "%d секретных значений не найдено ни в env %d контейнеров, ни в metadata/history %d образов" % (
len(vals), len(containers()), len(images))
@case("образ приложения: нет закрытых ключей и secrets/ внутри; файлы приложения не записываемы")
def _():
img = "mtusi-lab7-app:local"
r = run(["docker", "run", "--rm", "--network", "none", "--entrypoint", "sh", img, "-c",
"grep -rIl 'PRIVATE KEY-----' /app 2>/dev/null; ls -d /app/secrets /run/secrets 2>/dev/null; "
"test -w /app/src && echo WRITABLE; id -u"])
lines = [x for x in r.stdout.split() if x]
check(lines and lines[-1] == "10001", "image user: %s" % lines)
check(len(lines) == 1, "found in image: %s" % lines[:-1])
return "uid 10001; в /app нет PRIVATE KEY, secrets/; /app/src не записываем"
@case("у приложения нет root token / unseal shares / чужих SecretID (файлы и память процесса недоступны снаружи)")
def _():
vals = {k: v for k, v in secret_values().items()
if k.startswith(("openbao root", "unseal", "secret_id:", "secrets/db_owner", "secrets/postgres",
"secrets/s3_admin", "secrets/redis_ops"))}
found = []
for svc, c in containers():
if svc not in APP:
continue
# всё, что процесс может прочитать на своей ФС: смонтированные каталоги и /tmp
r = run(["docker", "exec", c["Id"], "sh", "-c",
"cat /run/bao/* /run/tls/self/*.crt /tmp/* 2>/dev/null; env; ls /run/secrets 2>/dev/null"])
for name, v in vals.items():
own = name == "secret_id:" + ("worker" if svc == "worker" else "api")
if v in r.stdout and not own:
found.append("%s sees %s" % (svc, name))
mounts = [m["Destination"] for m in c.get("Mounts", [])]
if "/run/secrets" in " ".join(mounts):
found.append("%s has compose secrets mounted" % svc)
check(not found, "; ".join(found))
return "api/worker: только свой role_id+SecretID; нет root token, shares, owner/admin паролей, /run/secrets"
@case("telemetry без секретов: Loki (24 ч) и label'ы Prometheus не содержат значений secrets/SecretID/root token")
def _():
from obs import Grafana
g = Grafana()
vals = secret_values()
hits = []
for name, v in vals.items():
q = '{service_name=~".+"} |= `%s`' % v
try:
res = g.loki(q, since=86400)
except Exception as e: # noqa: BLE001
raise AssertionError("loki query failed: %s" % e)
if res:
hits.append("loki:" + name)
names = g.get("/api/datasources/proxy/uid/prometheus/api/v1/labels")["data"]
for lbl in names:
vs = g.get("/api/datasources/proxy/uid/prometheus/api/v1/label/%s/values" % lbl)["data"]
blob = "\n".join(vs)
for name, v in vals.items():
if v in blob:
hits.append("prometheus label %s: %s" % (lbl, name))
check(not hits, "; ".join(hits))
return "%d значений × Loki 24 ч + %d label'ов Prometheus — совпадений нет" % (len(vals), len(names))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--json")
a = ap.parse_args()
print("## lab7 hardening & secrets audit (%s)" % time.strftime("%Y-%m-%d %H:%M:%S"))
p = f = 0
for row in results:
t0 = time.monotonic()
try:
row[3] = row[1]() or ""
row[2] = "PASS"
p += 1
except Exception as e: # noqa: BLE001
row[2], row[3] = "FAIL", str(e)[:600]
f += 1
print("%s %s (%.1fs)\n %s" % (row[2], row[0], time.monotonic() - t0, row[3]), flush=True)
print("summary: %d passed, %d failed" % (p, f))
if a.json:
Path(a.json).write_text(json.dumps([{"check": r[0], "result": r[2], "detail": r[3]} for r in results],
ensure_ascii=False, indent=1))
sys.exit(1 if f else 0)
if __name__ == "__main__":
main()
+162
View File
@@ -0,0 +1,162 @@
#!/usr/bin/env python3
"""Общая идемпотентность POST /chats/{id}/messages через LB и несколько реплик.
Ключ — заголовок Idempotency-Key, область: пользователь + метод + путь чата + ключ, срок ≥ 24 ч.
Проверки: повтор и конкурентный повтор через разные реплики → ровно одно сообщение; другой body → 409;
области ключа; формат ключа; неуспешный запрос не «занимает» ключ; повтор снова проверяет сессию и доступ.
"""
import json
import threading
import uuid
from collections import Counter
from common import BASE_URL, Client, Suite, check, login, new_user, sql
c = Client(BASE_URL)
s = Suite("idempotency across replicas (" + BASE_URL + ")")
alice = new_user(c, "ia"); login(c, alice)
bob = new_user(c, "ib"); login(c, bob)
eve = new_user(c, "ie"); login(c, eve)
def chat_of(*actors):
return c.call("POST", "/api/v1/chats", 201, actor=actors[0], schema="Chat",
body={"title": "idem", "member_ids": [a["id"] for a in actors]})["json"]
chat = chat_of(alice, bob)
PATH = "/api/v1/chats/" + chat["id"] + "/messages"
def post(actor, key, body=None, raw=None, expected=201, client=None, path=PATH):
h = {"Idempotency-Key": key} if key is not None else {}
if raw is not None:
h["Content-Type"] = "application/json"
return (client or c).call("POST", path, expected, actor=actor, body=body, raw=raw, headers=h,
schema="Message" if expected == 201 else None)
def count_text(text):
return int(sql("SELECT count(*) FROM messages WHERE text = '%s'" % text.replace("'", "''"))[0])
@s.case("sequential replays: same 201 + same Message from different replicas")
def _():
key, text = uuid.uuid4().hex, "seq-" + uuid.uuid4().hex
first = post(alice, key, {"text": text})
instances = {first["headers"]["X-Instance-Id"]}
for _ in range(10):
r = post(alice, key, {"text": text})
check(r["json"] == first["json"], "replay differs")
check(r["headers"].get("Idempotent-Replayed") == "true", "replay not marked")
instances.add(r["headers"]["X-Instance-Id"])
check(len(instances) >= 2, "replays were not served by >=2 replicas: %s" % instances)
check(count_text(text) == 1, "duplicate message")
return "replicas=%d, rows=1" % len(instances)
@s.case("30 concurrent POSTs, same key + body, via LB -> exactly one message")
def _():
key, text = uuid.uuid4().hex, "conc-" + uuid.uuid4().hex
results, lock, barrier = [], threading.Lock(), threading.Barrier(30)
def worker():
local = Client(BASE_URL, timeout=15) # отдельное соединение → LB распределяет по репликам
barrier.wait()
r = post(alice, key, {"text": text}, client=local)
with lock:
results.append((r["status"], json.dumps(r["json"], sort_keys=True), r["headers"]["X-Instance-Id"]))
threads = [threading.Thread(target=worker) for _ in range(30)]
[t.start() for t in threads]; [t.join() for t in threads]
check(len(results) == 30 and all(st == 201 for st, _, _ in results), "not all 201")
check(len({b for _, b, _ in results}) == 1, "different Message bodies returned")
per_instance = Counter(i for _, _, i in results)
check(len(per_instance) >= 2, "concurrency did not span replicas: %s" % dict(per_instance))
check(count_text(text) == 1, "duplicates: %d" % count_text(text))
return "per-replica responses %s, rows=1" % dict(per_instance)
@s.case("concurrent same key, two different bodies -> one message, others 201-same or 409")
def _():
key, a, b = uuid.uuid4().hex, "race-a-" + uuid.uuid4().hex, "race-b-" + uuid.uuid4().hex
out, lock, barrier = [], threading.Lock(), threading.Barrier(20)
def worker(i):
local = Client(BASE_URL, timeout=15)
barrier.wait()
r = post(alice, key, {"text": a if i % 2 else b}, client=local, expected=[201, 409])
with lock:
out.append((i % 2, r["status"], r["json"]))
threads = [threading.Thread(target=worker, args=(i,)) for i in range(20)]
[t.start() for t in threads]; [t.join() for t in threads]
rows = count_text(a) + count_text(b)
check(rows == 1, "expected exactly one message, got %d" % rows)
winner = a if count_text(a) else b
for parity, status, body in out:
mine = a if parity else b
check(status == (201 if mine == winner else 409), "status %d for %s" % (status, "winner" if mine == winner else "loser"))
return "201x%d, 409x%d" % (sum(1 for o in out if o[1] == 201), sum(1 for o in out if o[1] == 409))
@s.case("after commit: different body -> 409; reordered/whitespace JSON -> replay")
def _():
key, text = uuid.uuid4().hex, "fmt-" + uuid.uuid4().hex
first = post(alice, key, {"text": text})
r = post(alice, key, {"text": text + "!"}, expected=409)
check(r["json"]["error"]["code"] == "conflict", "409 code")
raw = ('{ \n "text" : ' + json.dumps(text) + ' \n}').encode()
check(post(alice, key, raw=raw)["json"] == first["json"], "semantically equal JSON not replayed")
@s.case("scope: user + chat + key (same key elsewhere is independent)")
def _():
key = "shared-key:" + uuid.uuid4().hex[:8]
m1 = post(alice, key, {"text": "scope-1"})["json"]
m2 = post(bob, key, {"text": "scope-1"})["json"] # другой пользователь
other = chat_of(alice, bob)
m3 = post(alice, key, {"text": "scope-1"}, path="/api/v1/chats/" + other["id"] + "/messages")["json"]
check(len({m1["id"], m2["id"], m3["id"]}) == 3, "keys leaked across scope")
check(m2["sender_id"] == bob["id"], "sender")
@s.case("key format: missing/empty/129 chars/invalid -> 400; 128 chars ok")
def _():
for key in (None, "", "a" * 129, "bad key", "k%y", "a/b", "k\"q"):
post(alice, key, {"text": "x"}, expected=400)
post(alice, "A" * 120 + "._:-z019", {"text": "len-128"})
@s.case("failed attempt does not claim the key (400/404 not recorded)")
def _():
key = uuid.uuid4().hex
post(alice, key, {"text": " "}, expected=400)
m = post(alice, key, {"text": "after-400"})["json"]
check(m["text"] == "after-400", "key was claimed by failed request")
key2 = uuid.uuid4().hex
post(eve, key2, {"text": "intruder"}, expected=404) # посторонний
post(alice, key2, {"text": "after-404"})
@s.case("replay re-checks session and access")
def _():
u = dict(alice); login(c, u)
key, text = uuid.uuid4().hex, "relogin-" + uuid.uuid4().hex
post(u, key, {"text": text})
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=u)
post(u, key, {"text": text}, expected=401)
post(eve, key, {"text": text}, expected=404) # чужой ключ/чат не раскрывается
check(post(alice, key, {"text": text})["json"]["text"] == text, "new session must replay")
@s.case("key older than IDEMPOTENCY_TTL_SECONDS is reusable (24 h window)")
def _():
key, text = uuid.uuid4().hex, "ttl-" + uuid.uuid4().hex
first = post(alice, key, {"text": text})["json"]
sql("UPDATE idempotency_keys SET created_at = created_at - interval '25 hours' WHERE key = '%s'" % key)
second = post(alice, key, {"text": text})["json"]
check(second["id"] != first["id"], "expired key must create a new message")
check(count_text(text) == 2, "rows")
if __name__ == "__main__":
s.run()
+160
View File
@@ -0,0 +1,160 @@
#!/usr/bin/env python3
"""Обработка изображений worker (уровень 4): правила вариантов и лимиты — проверка декодированием.
Запускается ВНУТРИ образа приложения (нужен Pillow):
docker compose --env-file .env run --rm --no-deps -T -v "$PWD/student-tests:/app/student-tests:ro" \
--entrypoint python worker student-tests/test_imgproc.py
Проверяет: размеры (вписывание, округление вниз, без увеличения), EXIF orientation, alpha на белом,
отсутствие EXIF/ICC в вариантах, детерминированность (основа идемпотентности), отличие pipeline v2,
лимиты пикселей/памяти/времени и классификацию ошибок (постоянная vs временная).
"""
import asyncio
import io
import json
import os
import subprocess
import sys
import time
import types
from pathlib import Path
from PIL import Image, ImageCms, ImageDraw
sys.path.insert(0, "/app/src")
from messenger.worker import Permanent, Transient, Worker # noqa: E402
FIX = Path(__file__).parent / "fixtures"
results = []
def case(name):
def deco(fn):
t = time.monotonic()
try:
note = fn()
results.append(True)
print("PASS %-70s %.2fs %s" % (name, time.monotonic() - t, note or ""))
except Exception as exc: # noqa: BLE001
results.append(False)
print("FAIL %-70s %s: %s" % (name, type(exc).__name__, exc))
return fn
return deco
def run(data, version=1, mem=768, maxpx=40_000_000):
p = subprocess.run([sys.executable, "-m", "messenger.imgproc", str(maxpx), str(mem), "30", str(version)],
input=data, capture_output=True, env=dict(os.environ, PYTHONPATH="/app/src"))
head, _, rest = p.stdout.partition(b"\n")
info = json.loads(head)
if not info["ok"]:
return info
out, off = {}, 0
for v in info["variants"]:
body = rest[off:off + v["size_bytes"]]
off += v["size_bytes"]
im = Image.open(io.BytesIO(body))
im.load()
out[v["name"]] = (im, body, v)
return out
def enc(im, fmt, **kw):
b = io.BytesIO()
im.save(b, fmt, **kw)
return b.getvalue()
@case("fixture 320×200 → thumbnail 256×160, crop 128×128, optimized WebP 320×200")
def _():
o = run((FIX / "photo.jpg").read_bytes()) # 96×64 — меньше коробки: без увеличения
assert o["thumbnail"][0].size == (96, 64) and o["optimized"][0].size == (96, 64)
sample = Image.new("RGB", (320, 200), (10, 120, 200))
o = run(enc(sample, "PNG"))
assert o["thumbnail"][0].size == (256, 160) and o["crop"][0].size == (128, 128)
assert o["optimized"][0].format == "WEBP" and o["optimized"][0].size == (320, 200)
assert o["thumbnail"][0].format == "JPEG" and o["crop"][0].format == "JPEG"
@case("rounding down and minimum 1 px: 3000×10 → 256×1, 1280×4")
def _():
o = run(enc(Image.new("RGB", (3000, 10)), "PNG"))
assert o["thumbnail"][0].size == (256, 1) and o["optimized"][0].size == (1280, 4), \
(o["thumbnail"][0].size, o["optimized"][0].size)
@case("EXIF orientation 6 applied (400×200 stored → 128×256); orientation tag not copied")
def _():
o = run((FIX / "exif6.jpg").read_bytes())
t = o["thumbnail"][0]
assert t.size == (128, 256), t.size
# Левая жёлтая полоса исходника после поворота на 90° по часовой оказывается сверху.
top, bottom = t.getpixel((64, 10)), t.getpixel((64, 245))
assert top[0] > 200 and top[2] < 100 and bottom[2] > 120, (top, bottom)
assert not t.getexif(), "EXIF must be stripped"
@case("alpha composited on white for JPEG variants; WebP keeps alpha")
def _():
o = run((FIX / "alpha.png").read_bytes())
px = o["thumbnail"][0].getpixel((5, 5)) # прозрачная половина
assert all(v >= 250 for v in px), px
assert o["thumbnail"][0].getpixel((250, 80))[0] > 180 # непрозрачная красная половина
assert o["optimized"][0].mode == "RGBA" and o["optimized"][0].getpixel((5, 5))[3] == 0
@case("metadata removed: EXIF/XMP/ICC of the source are not in any variant")
def _():
im = Image.new("RGB", (500, 300), (200, 100, 50))
ex = Image.Exif()
ex[0x010F] = "SecretCameraMaker"
icc = ImageCms.ImageCmsProfile(ImageCms.createProfile("sRGB")).tobytes()
o = run(enc(im, "JPEG", exif=ex.tobytes(), icc_profile=icc))
for name, (img, body, _) in o.items():
assert b"SecretCameraMaker" not in body and not img.info.get("icc_profile") and not img.getexif(), name
@case("deterministic output (same bytes on re-run) — basis of idempotent effect; v2 differs")
def _():
data = enc(Image.new("RGB", (900, 600), (30, 200, 90)), "PNG")
a, b, v2 = run(data), run(data), run(data, version=2)
assert all(a[k][2]["sha256"] == b[k][2]["sha256"] for k in a)
assert a["thumbnail"][2]["sha256"] != v2["thumbnail"][2]["sha256"]
assert all(a[k][0].size == v2[k][0].size for k in a)
@case("limits: pixels by header (413-class), memory (RLIMIT_AS), undecodable → permanent")
def _():
big = enc(Image.new("L", (5000, 5000)), "PNG")
r = run(big, maxpx=10_000_000)
assert not isinstance(r, dict) or r.get("kind") == "too_large", r
r = run(enc(Image.new("RGB", (6000, 6000)), "PNG"), mem=200)
assert r.get("kind") == "resource_limit", r
r = run((FIX / "sof5.jpg").read_bytes())
assert r.get("kind") == "invalid_image", r
return "too_large / resource_limit / invalid_image"
@case("worker wall-clock timeout kills the subprocess → transient (retry), not a hang")
def _():
fake = types.SimpleNamespace(s=types.SimpleNamespace(max_image_pixels=40_000_000, worker_process_memory_mb=768,
job_timeout_seconds=0.05))
data = enc(Image.new("RGB", (4000, 3000)), "PNG")
t = time.monotonic()
try:
asyncio.run(Worker.run_pipeline(fake, data, 1))
raise AssertionError("no timeout")
except Transient as exc:
assert exc.code == "processing_timeout"
took = time.monotonic() - t
assert took < 2, took
fake.s.job_timeout_seconds = 30
try:
asyncio.run(Worker.run_pipeline(fake, (FIX / "sof5.jpg").read_bytes(), 1))
raise AssertionError("no error")
except Permanent as exc:
assert exc.code == "invalid_image"
return "killed after %.2fs; undecodable → Permanent(invalid_image)" % took
print("summary: %d passed, %d failed" % (sum(results), len(results) - sum(results)))
sys.exit(0 if all(results) else 1)
+345
View File
@@ -0,0 +1,345 @@
#!/usr/bin/env python3
"""Отказы pipeline (уровни 3–4): окна отказа из contracts/attachment-states.md и восстановление.
ВНИМАНИЕ: останавливает/запускает worker, брокер (nats) и реплики API, поднимает профиль fault
(api-fault, :8445), внедряет падения worker хуками по имени файла (нужен FAULT_HOOKS=lab у worker).
Volumes не удаляются. Сценарии:
1 защита: worker остановлен → 202 → 409 → сообщение создано → рестарт API и брокера → worker → ready
2 broker недоступен: upload всё равно 202 (задание в outbox PostgreSQL), после старта брокера — ready
3 разрыв COMMIT → publish (api-fault падает сразу после COMMIT): relay другой реплики публикует
4 разрыв publish ack → отметка outbox: повторная публикация, брокер отбрасывает дубль по Nats-Msg-Id
5 worker падает после claim до побочного эффекта / после записи S3 до COMMIT / после COMMIT до ack
6 зависший worker (event loop заблокирован) против долгой, но живой обработки (heartbeat)
7 временные ошибки: backoff с jitter; исчерпание попыток → failed retry_exhausted → replay → ready
8 processing с истёкшим lease и потерянным сообщением → reaper возвращает работу в очередь
9 ограниченная конкуренция: одновременно в обработке не больше replicas × WORKER_CONCURRENCY
10 staging удаляется после ready; у failed — после retention, после чего replay честно отказывает
"""
import os
import shlex
import subprocess
import time
import uuid
from common import (BASE_URL, DC, ROOT, Client, Failure, Suite, check, events, jobs_cli, login, make_png, new_user,
s3_admin, sh, sql, upload, wait_status, wait_until)
FAULT_URL = os.environ.get("FAULT_BASE_URL", "https://127.0.0.1:8445")
WORKERS = int(os.environ.get("WORKER_REPLICAS", "2"))
CONCURRENCY = int(os.environ.get("WORKER_CONCURRENCY", "2"))
LEASE = float(os.environ.get("JOB_LEASE_SECONDS", "20"))
c = Client(BASE_URL, timeout=30)
s = Suite("pipeline failures (" + BASE_URL + ")")
alice = new_user(c, "fa"); login(c, alice)
bob = new_user(c, "fb"); login(c, bob)
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "failures", "member_ids": [alice["id"], bob["id"]]})["json"]
def dc(*args, env=None, timeout=180):
subprocess.run(shlex.split(DC) + list(args), cwd=ROOT, check=True, timeout=timeout,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=dict(os.environ, **(env or {})))
def wait_healthy(service, timeout=120):
def ok():
ids = subprocess.run(shlex.split(DC) + ["ps", "-q", service], cwd=ROOT, capture_output=True, text=True).stdout.split()
return ids and all(subprocess.run(["docker", "inspect", "-f", "{{.State.Health.Status}}", i], capture_output=True,
text=True).stdout.strip() == "healthy" for i in ids)
wait_until(ok, timeout=timeout, interval=1)
def ev(att_id):
return [(e["event"], e["lease_token"], e["worker"], e["detail"]) for e in events(att_id)]
def names(att_id):
return [e[0] for e in ev(att_id)]
def message(text, att_ids=()):
return c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 201, actor=alice, schema="Message",
body={"text": text, "attachment_ids": list(att_ids)}, headers={"Idempotency-Key": uuid.uuid4().hex})
def broker_messages():
out = subprocess.run(shlex.split(DC) + ["exec", "-T", "api", "python", "-m", "messenger", "stats"], cwd=ROOT,
capture_output=True, text=True, timeout=30)
import json
return (json.loads(out.stdout).get("broker") or {}).get("stream_messages")
@s.case("defense: worker stopped → 202 → 409 → message ok → restart API+broker (volumes kept) → worker → ready")
def _():
sh("stop_worker", timeout=120)
try:
att, data = upload(c, alice, chat, make_png(120, 90), filename="defense.png")
meta = c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["json"]
check(meta["status"] == "queued", "expected queued, got " + meta["status"])
c.call("GET", "/api/v1/attachments/%s/content" % att["id"], 409, actor=bob)
message("со вложением", [att["id"]])
message("обычное сообщение работает без worker")
wait_until(lambda: "published" in names(att["id"]), timeout=30)
in_stream = broker_messages()
sh("restart_broker", timeout=120)
wait_healthy("nats")
sh("restart_api", timeout=180)
wait_healthy("api")
after = broker_messages()
check(after is not None and after >= 1, "job message lost on broker restart (stream has %s)" % after)
check(wait_status(c, bob, att["id"], ("queued",), timeout=10)["status"] == "queued", "not queued")
finally:
sh("start_worker", timeout=120)
t = time.monotonic()
ready = wait_status(c, bob, att["id"], ("ready", "failed"), timeout=60)
check(ready["status"] == "ready", "not ready")
check(c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)["bytes"] == data, "original")
c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], actor=bob)
return "attachment %s: stream held %s→%s msgs across restart; ready %.1fs after worker start" % (
att["id"][:8], in_stream, after, time.monotonic() - t)
@s.case("broker down: upload still 202 (job durable in outbox), ready after broker returns")
def _():
dc("stop", "nats")
try:
att, _ = upload(c, alice, chat, make_png(60, 60), filename="nobroker.png")
time.sleep(2)
check("published" not in names(att["id"]), "published without broker?!")
check(c.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")["json"]["status"]
== "queued", "not queued")
finally:
dc("start", "nats")
wait_healthy("nats")
ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=60)
check(ready["status"] == "ready", "not ready")
return "202 with broker stopped; events %s" % names(att["id"])[:3]
def fault_upload(mode, filename):
"""Загрузка через api-fault с заданной точкой отказа; процесс api-fault после неё умирает."""
dc("--profile", "fault", "up", "-d", "--no-deps", "--force-recreate", "api-fault", env={"API_FAULT_INJECT": mode})
fc = Client(FAULT_URL, timeout=15)
wait_until(lambda: fc.call("GET", "/health/ready", [200, 502, 503])["status"] == 200, timeout=90)
fault_instance = fc.call("GET", "/health/live")["headers"].get("X-Instance-Id")
marker = sql("SELECT clock_timestamp()")[0]
try:
upload(fc, alice, chat, make_png(70, 70), filename=filename)
except Failure:
pass # 202 могло не дойти: процесс умер — это и проверяем
rows = sql("SELECT id FROM attachments WHERE chat_id = '%s' AND filename = '%s' AND created_at >= '%s'"
% (chat["id"], filename, marker))
check(len(rows) == 1, "accepted attachment not found (%s)" % rows)
return rows[0], fault_instance
@s.case("crash between COMMIT and publish: relay of another process publishes, job reaches ready")
def _():
try:
aid, fault_instance = fault_upload("crash_after_commit_before_publish", "gap-commit-publish.png")
ready = wait_status(c, alice, aid, ("ready", "failed"), timeout=60)
check(ready["status"] == "ready", "not ready")
e = ev(aid)
seq = [x[0] for x in e]
pub = [x for x in e if x[0] == "published"]
# Порядок published/claimed в журнале — порядок COMMIT: worker может получить сообщение и
# зафиксировать claim раньше, чем relay зафиксирует отметку outbox (это и есть at-least-once).
check(seq[0] == "enqueued" and len(pub) == 1 and seq.count("committed") == 1, "events %s" % seq)
relay = pub[0][3].get("relay", "")
check(fault_instance and fault_instance not in relay, "published by the crashed process?! %s" % relay)
finally:
dc("--profile", "fault", "stop", "api-fault")
return "api-fault (%s) died after COMMIT; published by relay %s; events %s" % (fault_instance, relay, seq)
@s.case("crash between publish ack and outbox mark: duplicate publish dropped by Nats-Msg-Id")
def _():
seen = None
try:
for _ in range(3): # relay другой реплики может успеть первым — тогда повтор
aid, _ = fault_upload("crash_after_publish_before_mark", "gap-publish-mark.png")
wait_status(c, alice, aid, ("ready", "failed"), timeout=60)
pub = [x for x in ev(aid) if x[0] == "published"]
check(len(pub) == 1, "published events %s" % pub)
if pub[0][3].get("duplicate"):
seen = pub[0][3]
break
finally:
dc("--profile", "fault", "stop", "api-fault")
check(seen is not None, "crash window not hit in 3 tries (another relay always won)")
e = names(aid)
check(e.count("claimed") == 1 and e.count("committed") == 1, "processed more than once: %s" % e)
return "second publish: duplicate=true, stream_seq=%s; processed once" % seen["stream_seq"]
def crash_case(hook, expect_takeover):
att, _ = upload(c, alice, chat, make_png(90, 70), filename="fault-%s.png" % hook)
t = time.monotonic()
ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=LEASE * 3 + 30)
check(ready["status"] == "ready", "not ready")
e = ev(att["id"])
seq = [x[0] for x in e]
committed = [x for x in e if x[0] == "committed"]
check(len(committed) == 1, "committed %d times" % len(committed))
if expect_takeover:
check("lease_takeover" in seq, "no takeover: %s" % seq)
tok = [x[1] for x in e if x[0] in ("claimed", "lease_takeover")]
check(committed[0][1] == tok[-1] and tok[0] != tok[-1], "commit token %s, claims %s" % (committed[0][1], tok))
check(sql("SELECT count(*) FROM attachment_variants WHERE attachment_id = '%s'" % att["id"]) == ["3"], "variants")
wait_healthy("worker")
return att["id"], seq, time.monotonic() - t
@s.case("worker crash after claim, before any side effect → lease takeover → ready")
def _():
aid, seq, took = crash_case("crash-before-s3", True)
return "%s in %.1fs" % (seq, took)
@s.case("worker crash after S3 writes, before COMMIT → takeover rewrites the same keys, one result")
def _():
aid, seq, took = crash_case("crash-after-s3", True)
keys = sql("SELECT object_key FROM attachment_variants WHERE attachment_id = '%s' ORDER BY name" % aid)
check(len(keys) == 3 and all("/v1/" in k for k in keys), "keys %s" % keys)
return "%s in %.1fs; keys deterministic: %s" % (seq, took, [k.split("/")[-1] for k in keys])
@s.case("worker crash after COMMIT, before ack → redelivery is a no-op (duplicate_ignored)")
def _():
aid, seq, took = crash_case("crash-after-commit", False)
wait_until(lambda: "duplicate_ignored" in names(aid), timeout=LEASE * 3 + 20, interval=1)
seq = names(aid)
check(seq.count("committed") == 1 and seq.count("claimed") == 1, "unexpected: %s" % seq)
return "%s" % seq
@s.case("hung worker (event loop blocked 45 s) loses lease; takeover commits; zombie commit is fenced")
def _():
att, _ = upload(c, alice, chat, make_png(90, 90), filename="fault-hang-45.png")
ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=120)
check(ready["status"] == "ready", "not ready")
wait_until(lambda: "lease_lost" in names(att["id"]), timeout=60, interval=1)
e = ev(att["id"])
claims = [x for x in e if x[0] in ("claimed", "lease_takeover")]
commit = [x for x in e if x[0] == "committed"]
lost = [x for x in e if x[0] == "lease_lost"]
check(len(commit) == 1 and commit[0][1] == claims[-1][1] and lost[0][1] == claims[0][1],
"tokens: claims %s commit %s lost %s" % ([x[1] for x in claims], commit[0][1], lost[0][1]))
check(claims[0][2] != claims[-1][2], "takeover by the same worker?")
wait_healthy("worker", timeout=90)
return "claimed t%s → takeover t%s → committed t%s; zombie (t%s) → lease_lost" % (
claims[0][1], claims[-1][1], commit[0][1], lost[0][1])
@s.case("long but alive job (35 s > lease 20 s): heartbeat keeps the lease, no takeover, no duplicate")
def _():
att, _ = upload(c, alice, chat, make_png(60, 40), filename="fault-slow-35.png")
t = time.monotonic()
ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=120)
check(ready["status"] == "ready", "not ready")
seq = names(att["id"])
check(seq.count("claimed") == 1 and "lease_takeover" not in seq and seq.count("committed") == 1, "%s" % seq)
return "ready after %.1fs, %s" % (time.monotonic() - t, seq)
@s.case("transient errors: retry with backoff + jitter (2 failures), then ready")
def _():
att, _ = upload(c, alice, chat, make_png(50, 50), filename="fault-transient-2.png")
ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=60)
check(ready["status"] == "ready", "not ready")
e = events(att["id"])
retries = [x for x in e if x["event"] == "retry_scheduled"]
check(len(retries) == 2, "retries %d" % len(retries))
d1, d2 = retries[0]["detail"]["delay_seconds"], retries[1]["detail"]["delay_seconds"]
check(1.0 <= d1 <= 2.0 and 2.0 <= d2 <= 4.0, "backoff windows: %s, %s" % (d1, d2))
claims = [x for x in e if x["event"] == "claimed"]
gaps = []
for r, nxt in zip(retries, claims[1:]):
import datetime as dt
g = (dt.datetime.fromisoformat(nxt["created_at"]) - dt.datetime.fromisoformat(r["created_at"])).total_seconds()
gaps.append(round(g, 2))
check(g >= r["detail"]["delay_seconds"] - 0.05, "retried earlier than scheduled")
return "delays %.2fs, %.2fs (windows [1,2], [2,4]); actual gaps %s; attempts %s" % (
d1, d2, gaps, [x["attempt"] for x in claims])
@s.case("retries exhausted → failed retry_exhausted (in registry) → operator replay → ready")
def _():
att, _ = upload(c, alice, chat, make_png(40, 40), filename="fault-transient-5.png")
failed = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=90)
check(failed["status"] == "failed" and failed["error_code"] == "retry_exhausted", "got %s" % failed["status"])
seq = names(att["id"])
check(seq.count("claimed") == 5 and seq.count("retry_scheduled") == 4, "attempts: %s" % seq)
reg = jobs_cli("failed", "--limit", "500")["failed"]
check(any(r["attachment_id"] == att["id"] and r["replayable"] for r in reg), "not in registry")
r = jobs_cli("replay", "--attachment", att["id"], "--reason", "fixed dependency", "--operator", "student")
check(r["result"] == "replayed" and r["attempt"] == 6, "%s" % r)
ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=60)
check(ready["status"] == "ready" and ready["error_code"] is None, "replay did not finish")
return "5 attempts → retry_exhausted; replay (attempt 6) → ready"
@s.case("processing with expired lease and LOST message → reaper requeues → ready")
def _():
sh("stop_worker", timeout=120)
try:
att, _ = upload(c, alice, chat, make_png(55, 55), filename="reaper.png")
wait_until(lambda: "published" in names(att["id"]), timeout=30)
purged = jobs_cli("purge-stream")["purged"]
# имитация: worker захватил работу и умер, а его сообщение брокер уже не вернёт (потеряно)
sql("UPDATE attachment_jobs SET status = 'processing', claims = 1, lease_token = nextval('job_lease_token_seq'),"
" lease_owner = 'dead-worker', lease_until = clock_timestamp() - interval '2 minutes'"
" WHERE attachment_id = '%s'" % att["id"])
sql("UPDATE attachments SET status = 'processing' WHERE id = '%s'" % att["id"])
finally:
sh("start_worker", timeout=120)
ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=60)
check(ready["status"] == "ready", "not ready")
seq = names(att["id"])
check("requeued_expired_lease" in seq, "reaper did not act: %s" % seq)
return "purged %s stream msgs; %s" % (purged, seq[-4:])
@s.case("bounded concurrency: never more than replicas × WORKER_CONCURRENCY jobs in processing")
def _():
ids = [upload(c, alice, chat, make_png(30 + i, 30), filename="fault-slow-4-n%d.png" % i)[0]["id"] for i in range(8)]
import datetime as dt
for a in ids:
wait_status(c, alice, a, ("ready", "failed"), timeout=120)
spans = []
for a in ids:
e = events(a)
start = [x["created_at"] for x in e if x["event"] == "claimed"][0]
end = [x["created_at"] for x in e if x["event"] == "committed"][0]
spans.append((dt.datetime.fromisoformat(start), dt.datetime.fromisoformat(end)))
points = sorted([(s0, 1) for s0, _ in spans] + [(e0, -1) for _, e0 in spans])
cur = peak = 0
for _, d in points:
cur += d
peak = max(peak, cur)
limit = WORKERS * CONCURRENCY
check(peak <= limit, "peak %d > %d" % (peak, limit))
total = (max(e0 for _, e0 in spans) - min(s0 for s0, _ in spans)).total_seconds()
return "8 jobs × ~4 s: peak concurrency %d (limit %d), wall %.1fs" % (peak, limit, total)
@s.case("staging removed after ready; failed staging kept until retention, then replay refuses honestly")
def _():
att, _ = upload(c, alice, chat, make_png(33, 33), filename="staging.png")
wait_status(c, alice, att["id"], "ready")
hexid = att["id"].replace("-", "")
wait_until(lambda: s3_admin("ls", "staging/" + hexid) == "", timeout=30)
check(s3_admin("ls", "originals/" + hexid) != "", "original not published")
bad, _ = upload(c, alice, chat, open(os.path.join(os.path.dirname(__file__), "fixtures", "sof5.jpg"), "rb").read(),
"image/jpeg", "sof5-retention.jpg")
wait_status(c, alice, bad["id"], "failed")
bhex = bad["id"].replace("-", "")
check(s3_admin("ls", "staging/" + bhex) != "", "failed staging must be kept for replay")
sql("UPDATE attachments SET updated_at = clock_timestamp() - interval '2 days' WHERE id = '%s'" % bad["id"])
wait_until(lambda: s3_admin("ls", "staging/" + bhex) == "", timeout=30)
r = jobs_cli("replay", "--attachment", bad["id"], "--reason", "too late")
check(r["result"] == "refused", "replay after retention: %s" % r)
return "ready: staging gone, originals/ present; failed: staging kept, removed after retention; replay %s" % r["result"]
s.run()
+281
View File
@@ -0,0 +1,281 @@
#!/usr/bin/env python3
"""lab7 уровень 4: жизненный цикл secrets/сертификатов ПОД НАГРУЗКОЙ, без пересборки образов.
python3 student-tests/test_lifecycle.py [--only db,s3,cert,sealed,tokens,renewal] [--json evidence/lifecycle.json]
Каждый сценарий: фоновая нагрузка (загрузки + сообщения через HTTPS) → операторское действие → проверка, что
клиентских ошибок нет (или их число ограничено и объяснено), все загрузки дошли до ready, старый credential
отклоняется НОВЫМ подключением. ВНИМАНИЕ: тест меняет стенд (ротации, seal/unseal, масштабирование api).
"""
import argparse
import json
import os
import shlex
import shutil
import subprocess
import sys
import threading
import time
from pathlib import Path
from common import BASE_URL, DC, ROOT, Client, Failure, check, login, new_user, upload, wait_status
from secretcopy import copy_secrets
ENV = dict(os.environ, NO_PROXY="127.0.0.1,localhost", no_proxy="127.0.0.1,localhost")
RESULTS = []
def case(name):
def deco(fn):
RESULTS.append([name, fn, None, None])
return fn
return deco
def run(cmd, timeout=600, check_rc=True):
r = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, timeout=timeout, env=ENV)
if check_rc and r.returncode != 0:
raise Failure("%s → %d: %s" % (" ".join(cmd[:4]), r.returncode, (r.stderr or r.stdout)[-400:]))
return r
def py(script, *args, timeout=600):
out = run([sys.executable, str(ROOT / "scripts" / script)] + list(args), timeout=timeout).stdout
start = out.find("{")
return json.loads(out[start:]) if start >= 0 else out
def dc(*args, timeout=300, check_rc=True):
return run(shlex.split(DC) + list(args), timeout=timeout, check_rc=check_rc)
def logs(service, since):
return dc("logs", "--no-log-prefix", "--since", since, service, check_rc=False).stdout.splitlines()
def utc():
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
class Load:
"""Фоновая нагрузка: каждый цикл — сообщение + (каждый 2-й) загрузка картинки. Считает ошибки клиента."""
def __init__(self, period=0.4):
self.c = Client(BASE_URL, timeout=20)
self.u = new_user(self.c, "lc")
login(self.c, self.u)
self.chat = self.c.call("POST", "/api/v1/chats", 201, actor=self.u, schema="Chat",
body={"title": "lifecycle", "member_ids": [self.u["id"]]})["json"]
self.period, self.stop, self.atts = period, threading.Event(), []
self.ok = self.err = 0
self.errors = []
self.t = threading.Thread(target=self.loop, daemon=True)
def loop(self):
i = 0
while not self.stop.is_set():
i += 1
try:
self.c.call("POST", "/api/v1/chats/%s/messages" % self.chat["id"], 201, actor=self.u,
body={"text": "lc %d" % i}, headers={"Idempotency-Key": "lc-%d-%f" % (i, time.time())})
if i % 2 == 0:
att, _ = upload(self.c, self.u, self.chat)
self.atts.append(att["id"])
self.ok += 1
except Exception as e: # noqa: BLE001
self.err += 1
self.errors.append("%s %s" % (time.strftime("%H:%M:%S"), str(e)[:120]))
time.sleep(self.period)
def __enter__(self):
self.t.start()
return self
def __exit__(self, *exc):
self.stop.set()
self.t.join(30)
def settle(self, timeout=180):
ready = 0
for a in self.atts:
att = wait_status(self.c, self.u, a, ("ready", "failed"), timeout=timeout)
ready += att["status"] == "ready"
return ready
@case("db: ротация пароля роли БД worker (blue/green) под нагрузкой — без ошибок и потерь")
def _():
with Load() as ld:
time.sleep(3)
res = py("rotate_credentials.py", "db", "worker")
time.sleep(5)
ready = ld.settle()
check(res["old_credential_check"].startswith("REJECTED"), "old db password still works: %s" % res)
check(res["services_switched_after_s"] is not None, "workers did not switch: %s" % res)
check(ld.err == 0, "client errors: %s" % ld.errors[:3])
check(ready == len(ld.atts), "ready %d of %d" % (ready, len(ld.atts)))
return ("%s → %s, KV v%s, переход за %s с, закрыто %s сессий старой роли; старый пароль: %s; нагрузка: %d ok / %d err,"
" вложений ready %d/%d" % (res["old_role"], res["new_role"], res["kv_version"], res["services_switched_after_s"],
res["old_sessions_terminated"], res["old_credential_check"][:30], ld.ok, ld.err,
ready, len(ld.atts)))
@case("s3: ротация ключа S3 identity api (два ключа на время перехода) под нагрузкой")
def _():
with Load() as ld:
time.sleep(3)
res = py("rotate_credentials.py", "s3", "api")
time.sleep(3)
ready = ld.settle()
check(res["old_credential_check"].startswith("REJECTED"), "old key still works: %s" % res)
check(res["services_switched_after_s"] is not None, "replicas did not confirm switch: %s" % res)
check(ld.err == 0, "client errors: %s" % ld.errors[:3])
check(ready == len(ld.atts), "ready %d of %d" % (ready, len(ld.atts)))
return "KV v%s, %d реплик перешли за %s с; старый ключ: %s; нагрузка %d ok / %d err; ready %d/%d" % (
res["kv_version"], res["replicas"], res["services_switched_after_s"], res["old_credential_check"], ld.ok, ld.err,
ready, len(ld.atts))
@case("cert: ротация leaf LB + отзыв старого (CRL) под нагрузкой; старый сертификат отклонён новым подключением")
def _():
old = ROOT / "secrets" / "test" / "old-lb"
if old.exists():
shutil.rmtree(old)
old.mkdir(parents=True)
copy_secrets([("tls/lb/" + n, "test/old-lb/" + n) for n in ("tls.crt", "tls.key", "tls.pem")], mode=0o600)
since = utc()
with Load(period=0.2) as ld:
time.sleep(3)
res = py("rotate_cert.py", "lb")
time.sleep(6)
ready = ld.settle()
probe = dc("--profile", "tests", "run", "--rm", "-T", "probe", "student-tests/internal_security.py", "--only", "lb",
timeout=300, check_rc=False)
line = [x for x in probe.stdout.splitlines() if "после ротации" in x]
check(line and line[0].startswith("PASS"), "probe: %s" % probe.stdout[-600:])
revoked_closed = sum('"mtls_revoked_closed"' in x for x in logs("api", since))
check(ld.err <= 2, "client errors during reload: %s" % ld.errors)
return ("serial %s → %s, CRL+reload за %s с (%s); нагрузка %d ok / %d err; ready %d/%d; старый cert → отказ "
"(probe), живых соединений со старым cert закрыто API: %d" % (
res["pki"]["old_serial"][:10], res["pki"]["new_serial"][:10], res["total_s"], ",".join(res["reloaded"][:2]),
ld.ok, ld.err, ready, len(ld.atts), revoked_closed))
def api_containers():
return [x for x in dc("ps", "-q", "api").stdout.split() if x]
def health(cid):
return subprocess.run(["docker", "inspect", "-f", "{{.State.Status}}/{{if .State.Health}}{{.State.Health.Status}}{{end}}",
cid], capture_output=True, text=True).stdout.strip()
@case("sealed: OpenBao запечатан — работающие API обслуживают; новая реплика НЕ стартует; после unseal — стартует")
def _():
since = utc()
run([sys.executable, str(ROOT / "scripts" / "bao_admin.py"), "seal"])
try:
with Load() as ld:
time.sleep(20) # > BAO_REFRESH_SECONDS: реплики заметили sealed
before = set(api_containers())
dc("up", "-d", "--no-recreate", "--scale", "api=3", "api", timeout=120)
new = [c for c in api_containers() if c not in before]
check(len(new) == 1, "scale-up did not add a replica: %s" % new)
time.sleep(25)
st_sealed = health(new[0])
check(not st_sealed.endswith("healthy") or st_sealed.endswith("unhealthy"),
"new replica became healthy while sealed: %s" % st_sealed)
run([sys.executable, str(ROOT / "scripts" / "bao_admin.py"), "unseal"])
t0 = time.monotonic()
while time.monotonic() - t0 < 120 and not health(new[0]).endswith("/healthy"):
time.sleep(1)
st_after = health(new[0])
recover = round(time.monotonic() - t0, 1)
time.sleep(3)
finally:
s = run([sys.executable, str(ROOT / "scripts" / "bao_admin.py"), "status"], check_rc=False).stdout
if '"sealed": true' in s:
run([sys.executable, str(ROOT / "scripts" / "bao_admin.py"), "unseal"], check_rc=False)
dc("up", "-d", "--no-recreate", "--scale", "api=2", "api", timeout=120, check_rc=False)
# Удалённая реплика уходит из server-template LB по DNS (hold obsolete 5 с) — даём LB перестроиться, чтобы
# переходное окно scale-down не попало в нагрузку следующего сценария (см. REPORT, «Ограничения»).
time.sleep(8)
lines = logs("api", since)
unavailable = sum('"bao_unavailable"' in x for x in lines)
check(st_after.endswith("/healthy"), "new replica not healthy after unseal: %s" % st_after)
check(ld.err == 0, "client errors while sealed: %s" % ld.errors[:3])
check(unavailable > 0, "no bao_unavailable events logged")
return ("sealed 45 с: нагрузка %d ok / %d err (реплики на кэшированных секретах); новая реплика при sealed: %s; "
"после unseal healthy за %s с; событий bao_unavailable: %d" % (ld.ok, ld.err, st_sealed, recover, unavailable))
@case("tokens: отзыв токенов api → 403 → новый вход по SecretID; ротация SecretID без рестарта")
def _():
since = utc()
with Load() as ld:
r1 = py("bao_admin.py", "revoke-tokens", "api")
time.sleep(35) # 2 × BAO_REFRESH_SECONDS + backoff
r2 = py("bao_admin.py", "rotate-secret-id", "api")
py("bao_admin.py", "revoke-tokens", "api") # заставить войти с НОВЫМ SecretID
time.sleep(35)
lines = logs("api", since)
denied = sum('"bao_denied"' in x for x in lines)
logins = sum('"bao_login"' in x for x in lines)
check(ld.err == 0, "client errors: %s" % ld.errors[:3])
check(denied >= 2 and logins >= 4, "denied=%d logins=%d" % (denied, logins))
toks = py("bao_admin.py", "tokens", "api")["tokens"]
return ("отозвано %d токенов → bao_denied %d, повторных входов %d (в т.ч. с новым SecretID: старый уничтожен=%s); "
"нагрузка %d ok / %d err; действующих токенов api: %d (TTL ≤ %s с)" % (
r1["tokens_revoked"], denied, logins, r2["old_secret_id_destroyed"], ld.ok, ld.err, len(toks),
max(t["creation_ttl"] for t in toks) if toks else 0))
@case("renewal: токены продлеваются на 2/3 TTL (renew-self), у max TTL — новый вход; TTL рабочего токена 5 мин")
def _():
# Продление — на 2/3 TTL (≈ 200 с после входа). Если сервисы только что перезапущены/вошли заново (persistence,
# отзыв токенов выше), ждём первое продление, но не дольше 260 с.
deadline = time.monotonic() + 260
while True:
lines = dc("logs", "--no-log-prefix", "api", "worker", check_rc=False).stdout.splitlines()
renew = [json.loads(x) for x in lines if '"bao_token_renewed"' in x]
if renew or time.monotonic() > deadline:
break
time.sleep(10)
logins = [json.loads(x) for x in lines if '"bao_login"' in x]
toks = py("bao_admin.py", "tokens", "worker")["tokens"]
check(toks and all(t["creation_ttl"] <= 300 for t in toks), "worker token TTL: %s" % toks)
check(renew, "no renewals logged yet (стенд работает < 4 мин?)")
ttls = sorted({r.get("token_ttl_s") for r in renew})
return "продлений: %d (выданный TTL после продления, с: %s), входов: %d; токены worker: TTL %s, last_renewal есть у %d" % (
len(renew), ttls[:6], len(logins), [t["ttl"] for t in toks], sum(1 for t in toks if t.get("last_renewal")))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--only", default="")
ap.add_argument("--json")
a = ap.parse_args()
only = [x for x in a.only.split(",") if x]
print("## lab7 lifecycle under load (%s, %s)" % (BASE_URL, time.strftime("%Y-%m-%d %H:%M:%S")))
p = f = 0
for row in RESULTS:
if only and row[0].split(":")[0] not in only:
continue
t0 = time.monotonic()
try:
row[3] = row[1]() or ""
row[2] = "PASS"
p += 1
except Exception as e: # noqa: BLE001
row[2], row[3] = "FAIL", str(e)[:800]
f += 1
print("%s %s (%.0fs)\n %s" % (row[2], row[0], time.monotonic() - t0, row[3]), flush=True)
print("summary: %d passed, %d failed" % (p, f))
if a.json:
Path(a.json).write_text(json.dumps([{"check": r[0], "result": r[2], "detail": r[3]} for r in RESULTS if r[2]],
ensure_ascii=False, indent=1))
sys.exit(1 if f else 0)
if __name__ == "__main__":
main()
+280
View File
@@ -0,0 +1,280 @@
#!/usr/bin/env python3
"""Собственные проверки lab6 (уровни 3–4): telemetry своего приложения находится в сохранённых
наблюдениях — Prometheus/Loki/Tempo через Grafana (datasource proxy), без доступа к stdout контейнеров.
python3 student-tests/test_observability.py (стенд запущен, Grafana на 127.0.0.1:3000)
"""
import re
import time
import uuid
from common import BASE_URL, Client, Suite, check, new_user, login, upload, wait_status
from obs import Grafana, ObsError, wait_for
suite = Suite("lab6: наблюдаемость — provisioning, сигналы, корреляция, безопасность telemetry")
c = Client(BASE_URL)
g = Grafana()
ctx = {}
UUID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
FORBIDDEN_LABELS = {"user_id", "chat_id", "message_id", "attachment_id", "request_id", "url", "url_full", "url_path",
"http_target", "filename", "text", "job_id", "trace_id", "span_id"}
def setup_actors():
if "alice" not in ctx:
ctx["password"] = "Obs-Secret-" + uuid.uuid4().hex # ищем его потом в telemetry
alice = new_user(c, "obs", password=ctx["password"])
login(c, alice)
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "obs", "member_ids": [alice["id"]]})["json"]
ctx.update(alice=alice, chat=chat)
return ctx["alice"], ctx["chat"]
def log_by_request(rid, service="messenger-api"):
recs = g.loki('{service_name="%s"} | request_id="%s"' % (service, rid), since=600)
return [r for r in recs if r.get("event") == "http.request"]
def descendants_of(spans, root_id):
kids = {}
for s in spans:
kids.setdefault(s["parent"], []).append(s)
out, stack = [], [root_id]
while stack:
for s in kids.get(stack.pop(), []):
out.append(s)
stack.append(s["span_id"])
return out
def ancestors(spans, span):
by_id = {s["span_id"]: s for s in spans}
out, cur = [], by_id.get(span["parent"])
while cur is not None:
out.append(cur)
cur = by_id.get(cur["parent"])
return out
@suite.case("provisioning: Prometheus/Loki/Tempo из Git, health OK")
def provisioning_datasources():
ds = {d["uid"]: d for d in g.get("/api/datasources")}
check({"prometheus", "loki", "tempo"} <= set(ds), "datasources: %s" % sorted(ds))
check(all(ds[u]["readOnly"] for u in ("prometheus", "loki", "tempo")), "datasources must be provisioned (read-only)")
out = []
for uid in ("prometheus", "loki", "tempo"):
h = g.get("/api/datasources/uid/%s/health" % uid)
check(h.get("status") == "OK", "%s health: %s" % (uid, h))
out.append(uid)
return "health OK: " + ", ".join(out)
@suite.case("provisioning: dashboard импортирован, все запросы панелей выполняются")
def provisioning_dashboard():
d = g.get("/api/dashboards/uid/messenger-overview")
check(d["meta"].get("provisioned"), "dashboard is not provisioned from file")
panels = [p for p in d["dashboard"]["panels"] if p.get("type") != "row"]
queries = with_data = 0
errors = []
for p in panels:
for t in p.get("targets", []):
queries += 1
res = g.ds_query({k: v for k, v in t.items() if k != "datasource"}, t.get("datasource") or p["datasource"], since=1800)
r = res["results"][t.get("refId", "A")]
if r.get("error") or r.get("status", 200) >= 400:
errors.append("%s: %s" % (p["title"], (r.get("error") or "")[:120]))
elif any(f.get("data", {}).get("values") and any(len(v) for v in f["data"]["values"]) for f in r.get("frames", [])):
with_data += 1
check(not errors, "panel query errors: %s" % errors[:5])
return "%d панелей, %d запросов без ошибок, с данными %d" % (len(panels), queries, with_data)
@suite.case("HTTP: X-Request-Id → структурный лог → trace (server + DB spans)")
def request_log_trace():
alice, chat = setup_actors()
ctx["marker"] = "obs-marker-" + uuid.uuid4().hex # текст сообщения: не должен попасть в telemetry
r = c.message(alice, chat, "Тайное содержимое " + ctx["marker"])
rid = r["headers"]["X-Request-Id"]
recs = wait_for(lambda: log_by_request(rid), 60, what="log with request_id")
rec = recs[-1]
for f in ("trace_id", "span_id", "severity_text", "service_name", "event", "route", "status"):
check(rec.get(f), "log record lacks %s: %s" % (f, sorted(rec)))
check(rec["route"] == "/api/v1/chats/{chat_id}/messages" and rec["status"] == "201", "log route/status: %s" % rec)
spans = wait_for(lambda: g.trace(rec["trace_id"]), 60, what="trace " + rec["trace_id"])
server = [s for s in spans if s["kind"] == "SERVER"]
check(len(server) == 1, "expected one server span, got %s" % [s["name"] for s in spans])
sv = server[0]
check(sv["name"] == "POST /api/v1/chats/{chat_id}/messages", "server span name: %s" % sv["name"])
check(sv["attrs"].get("messenger.request_id") == rid and sv["attrs"].get("http.response.status_code") == 201,
"server span attrs: %s" % sv["attrs"])
check(sv["span_id"] == rec["span_id"], "log span_id %s != server span %s" % (rec["span_id"], sv["span_id"]))
db = [s for s in descendants_of(spans, sv["span_id"]) if s["attrs"].get("db.system.name") == "postgresql"]
check(any(s["name"] == "INSERT messages" for s in db), "no INSERT messages span: %s" % [s["name"] for s in db])
ctx["msg_trace"] = rec["trace_id"]
return "request_id → trace %s…, %d spans (%d DB)" % (rec["trace_id"][:12], len(spans), len(db))
@suite.case("безопасность: пароль, токен, тело сообщения не попадают в логи/трассы")
def no_secrets():
alice, chat = setup_actors()
if "marker" not in ctx:
request_log_trace()
r = login(c, alice) # Basic с паролем → токен в ответе
rid = r["headers"]["X-Request-Id"]
rec = wait_for(lambda: log_by_request(rid), 60, what="login log")[-1]
login_trace = wait_for(lambda: g.trace_raw_text(rec["trace_id"]), 60, what="login trace")
msg_trace = g.trace_raw_text(ctx["msg_trace"])
secrets = {"password": ctx["password"], "token": alice["token"], "message text": ctx["marker"], "Bearer": "Bearer "}
leaks = []
for name, value in secrets.items():
for where, text in (("login trace", login_trace), ("message trace", msg_trace)):
if value in text:
leaks.append("%s in %s" % (name, where))
if name != "Bearer" and g.loki('{service_name=~"messenger-api|messenger-worker"} |= "%s"' % value, since=900):
leaks.append(name + " in Loki")
check(not leaks, "telemetry leaks: %s" % leaks)
check("password.verify" in login_trace, "login trace has no password.verify span (KDF time not visible)")
return "проверено в Loki и 2 trace: пароль, токен, текст сообщения, Authorization"
@suite.case("upload → create → send → process → S3/DB: один trace; лог worker с тем же trace_id")
def upload_chain():
alice, chat = setup_actors()
att, _ = upload(c, alice, chat)
wait_status(c, alice, att["id"], "ready", timeout=60)
def find():
traces = g.search('{ span.messenger.attachment.id = "%s" }' % att["id"], since=600)
if not traces:
return None
spans = g.trace(traces[0]["traceID"])
procs = [s for s in spans or [] if s["kind"] == "CONSUMER" and s["attrs"].get("messenger.job.outcome")]
return spans if procs else None
spans = wait_for(find, 90, what="worker span in upload trace")
by = lambda n: [s for s in spans if s["name"] == n] # noqa: E731
server = by("POST /api/v1/chats/{chat_id}/attachments")
create, send = by("create attachments.process.v1"), by("send attachments.process.v1")
process = by("process attachments.process.v1")
check(len(server) == 1 and server[0]["kind"] == "SERVER" and server[0]["service"] == "messenger-api", "server span")
check(len(create) == 1 and create[0]["kind"] == "PRODUCER" and create[0]["parent"] == server[0]["span_id"],
"create span must be PRODUCER child of upload server span")
check(len(send) >= 1 and all(s["kind"] == "PRODUCER" and s["parent"] == create[0]["span_id"] for s in send),
"send span must be PRODUCER child of create")
check(len(process) == 1 and process[0]["kind"] == "CONSUMER" and process[0]["service"] == "messenger-worker"
and process[0]["parent"] == send[0]["span_id"], "process must be CONSUMER child of send (worker)")
p = process[0]
check(p["attrs"].get("messenger.job.outcome") == "ready" and p["attrs"].get("messaging.system") == "nats", "process attrs")
inner = descendants_of(spans, p["span_id"])
names = [s["name"] for s in inner]
check(names.count("S3.PutObject") >= 4, "original + 3 variants PUT expected: %s" % names)
check("imgproc.run" in names and "job.commit" in names and "UPDATE attachments" in names, "pipeline spans: %s" % names)
tid = p["trace_id"]
rec = wait_for(lambda: g.loki('{service_name="messenger-worker"} | event="job.finished" | attachment_id="%s"' % att["id"],
since=600), 60, what="worker log")[-1]
check(rec.get("trace_id") == tid and rec.get("span_id") == p["span_id"], "worker log not linked to process span")
ctx["upload_trace"] = tid
return "%d spans: SERVER→create→send→process(%s)→S3×%d; queue %.2f с" % (
len(spans), p["service"], names.count("S3.PutObject"), p["start"] - send[0]["end"])
@suite.case("retry: 2 временные ошибки + успех — три попытки в одном trace")
def retry_chain():
alice, chat = setup_actors()
att, _ = upload(c, alice, chat, filename="obs-fault-transient-2.png")
wait_status(c, alice, att["id"], "ready", timeout=90)
def find():
traces = g.search('{ span.messenger.attachment.id = "%s" }' % att["id"], since=600)
spans = g.trace(traces[0]["traceID"]) if traces else None
procs = [s for s in spans or [] if s["name"] == "process attachments.process.v1"]
return spans if len(procs) >= 3 and any(s["attrs"].get("messenger.job.outcome") == "ready" for s in procs) else None
spans = wait_for(find, 90, what="3 process spans")
procs = sorted([s for s in spans if s["name"] == "process attachments.process.v1"], key=lambda s: s["start"])
outcomes = [s["attrs"].get("messenger.job.outcome") for s in procs]
check(outcomes == ["retry", "retry", "ready"], "outcomes: %s" % outcomes)
check([s["attrs"].get("messenger.job.attempt") for s in procs] == [1, 2, 3], "attempts")
check(all(s["status"] == "ERROR" and s["attrs"].get("error.type") == "processing_failed" for s in procs[:2]),
"failed attempts must be marked as errors")
check(procs[0] in ancestors(spans, procs[1]) and procs[1] in ancestors(spans, procs[2]),
"next attempt must descend from previous attempt (retry → outbox → send → process)")
return "попытки 1→2→3: %s; паузы backoff %.1f с и %.1f с" % (
outcomes, procs[1]["start"] - procs[0]["end"], procs[2]["start"] - procs[1]["end"])
@suite.case("метрики контракта: имена, низкая кардинальность, шаблоны маршрутов")
def metric_contract():
required = ["http_server_request_duration_seconds_count", "http_server_active_requests",
"db_client_operation_duration_seconds_count", "db_client_connection_count",
"db_client_connection_pending_requests", "db_client_connection_max",
"messenger_jobs_processed_total", "messenger_job_duration_seconds_count",
"messenger_attachment_time_to_ready_seconds_count", "messenger_job_queue_wait_seconds_count",
"messenger_queue_depth", "messenger_queue_lag_seconds", "messenger_queue_oldest_age_seconds",
"messenger_broker_pending", "messenger_worker_busy", "messenger_worker_capacity",
"container_cpu_time_seconds_total", "container_memory_usage_bytes", "process_memory_usage_bytes",
"otel_sdk_processor_span_processed_total"]
missing = [m for m in required if not g.series(m, since=900)]
check(not missing, "metrics missing: %s" % missing)
series = g.series('{__name__=~"messenger_.*|http_server_.*|db_client_.*|container_.*"}', since=900)
labels = set().union(*(s.keys() for s in series))
bad = labels & FORBIDDEN_LABELS
check(not bad, "forbidden metric labels: %s" % bad)
routes = {s.get("http_route") for s in series if s.get("http_route")}
check(routes and not any(UUID_RE.search(r) for r in routes), "routes must be templates: %s" % routes)
check(all(s.get("service_name") in ("messenger-api", "messenger-worker") and s.get("deployment_environment_name") == "lab"
and s.get("service_instance_id") for s in series), "resource labels missing on some series")
n_http = len([s for s in series if s["__name__"] == "http_server_request_duration_seconds_count"])
check(n_http < 300, "too many http series: %d" % n_http)
return "%d метрик; серий %d (HTTP count — %d); маршрутов %d; запрещённых labels нет" % (
len(required), len(series), n_http, len(routes))
@suite.case("метрики отражают обработку: jobs, retry, time-to-ready, p95 из histogram")
def metric_values():
def ok():
ready = g.prom_value('sum(messenger_jobs_processed_total{outcome="ready"})', 0)
retry = g.prom_value('sum(messenger_jobs_processed_total{outcome="retry"})', 0)
ttr = g.prom_value("sum(messenger_attachment_time_to_ready_seconds_count)", 0)
return (ready, retry, ttr) if ready >= 2 and retry >= 2 and ttr >= 2 else None
ready, retry, ttr = wait_for(ok, 40, what="job metrics")
p95 = g.prom_value('histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket'
'{service_name="messenger-api",http_route!~"/health/.*"}[10m])))')
check(p95 is not None and p95 > 0, "p95 from histogram: %s" % p95)
t95 = g.prom_value("histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[30m])))")
return "ready=%d retry=%d time_to_ready count=%d; p95 HTTP %.0f мс, p95 ready %.2f с" % (ready, retry, ttr, p95 * 1000, t95 or 0)
@suite.case("алерты: правила загружены и вычисляются без ошибок")
def alert_rules():
groups = g.rules()
rules = [r for grp in groups for r in grp["rules"]]
names = {r["name"] for r in rules if r["type"] == "alerting"}
need = {"ApiHighErrorRate", "JobQueueLagGrowing", "WorkerHeartbeatMissing", "DbSlowQueries", "ApiLatencyHigh",
"TelemetryExportFailing"}
check(need <= names, "alerts missing: %s" % (need - names))
bad = [r["name"] for r in rules if r.get("health") != "ok" or r.get("lastError")]
check(not bad, "rules with evaluation errors: %s" % bad)
for r in rules:
if r["type"] == "alerting":
ann = r.get("annotations", {})
check(ann.get("summary") and ann.get("runbook_url"), "alert %s lacks summary/runbook" % r["name"])
firing = [a["labels"]["alertname"] for a in g.alerts() if a["state"] == "firing"]
return "%d правил (%d алертов), firing сейчас: %s" % (len(rules), len(names), firing or "нет")
@suite.case("SDK: spans/logs не отбрасываются при работающем Collector")
def sdk_no_drops():
total = g.prom_value("sum(otel_sdk_processor_span_processed_total)", 0)
dropped = g.prom_value('sum(otel_sdk_processor_span_processed_total{error_type!=""})', 0)
ldropped = g.prom_value('sum(otel_sdk_processor_log_processed_total{error_type!=""})', 0)
check(total > 0, "no SDK span counters")
check(dropped == 0 and ldropped == 0, "dropped spans=%s logs=%s" % (dropped, ldropped))
return "обработано spans %d, отброшено 0" % total
if __name__ == "__main__":
try:
g.get("/api/health")
except ObsError as e:
raise SystemExit("Grafana недоступна: %s" % e)
suite.run()
+187
View File
@@ -0,0 +1,187 @@
#!/usr/bin/env python3
"""Асинхронный pipeline вложений (уровни 3–4): 202/queued → ready, варианты по контракту, failed,
409 для неготовых, запрет прикреплять failed, идемпотентность повторной доставки, безопасный replay.
Размеры вариантов проверяются по РЕАЛЬНЫМ байтам (JPEG SOF и заголовок WebP), а не только по JSON.
Стенд должен работать с worker; volumes не трогаются. Для операторских шагов используется
`python -m messenger jobs …` в контейнере worker (нужен docker compose в PATH).
"""
import hashlib
import sys
import time
import zlib
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from image_probe import jpeg_size # noqa: E402
from common import (BASE_URL, Client, Suite, check, events, jobs_cli, login, make_png, new_user, upload, # noqa: E402
wait_status)
FIX = Path(__file__).parent / "fixtures"
c = Client(BASE_URL, timeout=30)
s = Suite("attachment pipeline (" + BASE_URL + ")")
alice = new_user(c, "pa"); login(c, alice)
bob = new_user(c, "pb"); login(c, bob)
eve = new_user(c, "pe"); login(c, eve)
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "pipeline", "member_ids": [alice["id"], bob["id"]]})["json"]
def webp_size(data):
check(data[:4] == b"RIFF" and data[8:12] == b"WEBP", "optimized is not WebP")
kind = data[12:16]
if kind == b"VP8 ":
return int.from_bytes(data[26:28], "little") & 0x3FFF, int.from_bytes(data[28:30], "little") & 0x3FFF
if kind == b"VP8L":
b = int.from_bytes(data[21:25], "little")
return (b & 0x3FFF) + 1, ((b >> 14) & 0x3FFF) + 1
if kind == b"VP8X":
return int.from_bytes(data[24:27], "little") + 1, int.from_bytes(data[27:30], "little") + 1
raise AssertionError("unknown WebP chunk %r" % kind)
def flat_png(w, h, rgb=(40, 160, 90)):
"""Однотонный RGB PNG любого размера (stdlib): хорошо сжимается, годится для проверки размеров."""
row = b"\x00" + bytes(rgb) * w
raw = zlib.compress(row * h, 6)
def chunk(t, d):
return len(d).to_bytes(4, "big") + t + d + zlib.crc32(t + d).to_bytes(4, "big")
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", w.to_bytes(4, "big") + h.to_bytes(4, "big") + bytes([8, 2, 0, 0, 0]))
+ chunk(b"IDAT", raw) + chunk(b"IEND", b""))
def fit(w, h, box):
m = max(w, h)
return (w, h) if m <= box else (max(1, w * box // m), max(1, h * box // m))
def check_variants(att, logical_w, logical_h):
"""Все три варианта: заявленные метаданные = реальные байты; размеры — по правилам контракта."""
got = {v["name"]: v for v in att["variants"]}
check(set(got) == {"thumbnail", "crop", "optimized"}, "variants %s" % sorted(got))
expect = {"thumbnail": ("image/jpeg", fit(logical_w, logical_h, 256)), "crop": ("image/jpeg", (128, 128)),
"optimized": ("image/webp", fit(logical_w, logical_h, 1280))}
for name, (ctype, dims) in expect.items():
v = got[name]
r = c.call("GET", "/api/v1/attachments/%s/content?variant=%s" % (att["id"], name), actor=bob)
body = r["bytes"]
check(r["headers"].get_content_type() == ctype == v["content_type"], name + " content type")
check(len(body) == v["size_bytes"] and hashlib.sha256(body).hexdigest() == v["sha256"], name + " checksum")
real = jpeg_size(body) if ctype == "image/jpeg" else webp_size(body)
check(real == dims == (v["width"], v["height"]), "%s: real %s, meta %s, expected %s"
% (name, real, (v["width"], v["height"]), dims))
return got
@s.case("upload → 202 queued snapshot, then ready; original byte-exact; three variants by contract")
def _():
data = (Path(__file__).resolve().parents[1] / "tests" / "fixtures" / "sample.png").read_bytes()
att, _ = upload(c, alice, chat, data, filename="sample.png")
check(att["status"] in ("queued", "processing", "ready") and att["error_code"] is None, "202 snapshot")
t = time.monotonic()
ready = wait_status(c, bob, att["id"], ("ready", "failed"))
check(ready["status"] == "ready", "not ready: %s" % ready)
took = time.monotonic() - t
orig = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)["bytes"]
check(orig == data and ready["sha256"] == hashlib.sha256(data).hexdigest(), "original changed")
check_variants(ready, 320, 200)
return "ready %.2fs after 202; thumbnail 256×160, crop 128×128, optimized 320×200 WebP" % took
@s.case("big image: optimized fits 1280 without upscale, thumbnail rounds down")
def _():
att, _ = upload(c, alice, chat, flat_png(3001, 1999), filename="big.png")
ready = wait_status(c, alice, att["id"], ("ready", "failed"))
check(ready["status"] == "ready", "not ready")
got = check_variants(ready, 3001, 1999)
return "thumbnail %sx%s, optimized %sx%s" % (got["thumbnail"]["width"], got["thumbnail"]["height"],
got["optimized"]["width"], got["optimized"]["height"])
@s.case("EXIF orientation applied (stored 400×200, orientation 6 → 200×400); tiny image not upscaled")
def _():
att, _ = upload(c, alice, chat, (FIX / "exif6.jpg").read_bytes(), "image/jpeg", "exif6.jpg")
ready = wait_status(c, alice, att["id"], ("ready", "failed"))
check_variants(ready, 200, 400)
tiny, _ = upload(c, alice, chat, make_png(40, 30), filename="tiny.png")
ready = wait_status(c, alice, tiny["id"], ("ready", "failed"))
got = check_variants(ready, 40, 30)
check((got["thumbnail"]["width"], got["thumbnail"]["height"]) == (40, 30), "tiny thumbnail upscaled")
att, _ = upload(c, alice, chat, (FIX / "alpha.png").read_bytes(), filename="alpha.png")
check_variants(wait_status(c, alice, att["id"], ("ready", "failed")), 300, 200)
@s.case("variant parameter: unknown → 400; default original; outsider → 404")
def _():
att, data = upload(c, alice, chat, make_png(64, 64))
wait_status(c, alice, att["id"], "ready")
c.call("GET", "/api/v1/attachments/%s/content?variant=../../x" % att["id"], 400, actor=bob)
c.call("GET", "/api/v1/attachments/%s/content?variant=preview" % att["id"], 400, actor=bob)
check(c.call("GET", "/api/v1/attachments/%s/content?variant=original" % att["id"], actor=bob)["bytes"] == data, "orig")
for v in ("", "?variant=thumbnail"):
c.call("GET", "/api/v1/attachments/%s/content%s" % (att["id"], v), 404, actor=eve)
c.call("GET", "/api/v1/attachments/%s" % att["id"], 404, actor=eve)
@s.case("undecodable image → failed with safe error_code, no retries; content 409; cannot attach (409)")
def _():
att, _ = upload(c, alice, chat, (FIX / "sof5.jpg").read_bytes(), "image/jpeg", "sof5.jpg")
failed = wait_status(c, alice, att["id"], ("ready", "failed"))
check(failed["status"] == "failed" and failed["error_code"] == "invalid_image", "got %s/%s"
% (failed["status"], failed["error_code"]))
check(failed["variants"] == [], "failed must have no variants")
for v in ("", "?variant=thumbnail"):
c.call("GET", "/api/v1/attachments/%s/content%s" % (att["id"], v), 409, actor=bob)
c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 409, actor=alice,
body={"text": "x", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": "failed-" + att["id"]})
ev = [e["event"] for e in events(att["id"])]
check(ev.count("claimed") == 1 and "retry_scheduled" not in ev and ev[-1] == "failed", "permanent: %s" % ev)
reg = jobs_cli("failed", "--limit", "500")["failed"]
check(any(r["attachment_id"] == att["id"] and r["error_code"] == "invalid_image" for r in reg), "not in registry")
return "events %s; listed in failed registry" % ev
@s.case("queued/processing attachment can be attached to a message right away")
def _():
att, _ = upload(c, alice, chat, make_png(50, 50))
m = c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 201, actor=bob, schema="Message",
body={"text": "", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": "q-" + att["id"]})["json"]
check(m["attachment_ids"] == [att["id"]], "message lost attachment")
wait_status(c, alice, att["id"], "ready")
@s.case("duplicate deliveries of a finished job are no-ops (5 raw duplicates)")
def _():
att, _ = upload(c, alice, chat, make_png(80, 60))
before = wait_status(c, alice, att["id"], "ready")
job = jobs_cli("status", att["id"])["jobs"][0]
jobs_cli("publish-raw", "--job", job["job_id"], "--count", "5")
time.sleep(3)
ev = [e["event"] for e in events(att["id"])]
after = c.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")["json"]
check(ev.count("committed") == 1 and ev.count("duplicate_ignored") == 5, "events %s" % ev)
check(after["variants"] == before["variants"] and after["updated_at"] == before["updated_at"], "result changed")
return "committed ×1, duplicate_ignored ×5, metadata unchanged"
@s.case("replay is safe: ready → noop; failed (permanent) → re-executed once, failed again")
def _():
att, _ = upload(c, alice, chat, make_png(30, 30))
wait_status(c, alice, att["id"], "ready")
r = jobs_cli("replay", "--attachment", att["id"], "--reason", "test ready")
check(r["result"] == "noop" and r["status"] == "ready", "replay of ready must be noop: %s" % r)
bad, _ = upload(c, alice, chat, (FIX / "sof5.jpg").read_bytes(), "image/jpeg", "sof5-replay.jpg")
wait_status(c, alice, bad["id"], "failed")
r = jobs_cli("replay", "--attachment", bad["id"], "--reason", "operator retry", "--operator", "student")
check(r["result"] == "replayed" and r["attempt"] == 2, "replay: %s" % r)
wait_status(c, alice, bad["id"], "failed")
ev = [e for e in events(bad["id"])]
rp = [e for e in ev if e["event"] == "replayed"]
check(len(rp) == 1 and rp[0]["detail"]["operator"] == "student", "audit record missing")
check([e["event"] for e in ev].count("failed") == 2, "expected second failure")
return "ready: %s; failed: replayed (audit by %s) → failed again (permanent error)" % (r and "noop", "student")
s.run()
+188
View File
@@ -0,0 +1,188 @@
#!/usr/bin/env python3
"""Трек 2: доказанная идемпотентность versioned pipeline — автоматическая инъекция отказов.
Каждый сценарий внедряет отказ, ждёт завершения и проверяет инварианты (python -m messenger jobs
invariants: I1 нет потерь, I2 один набор вариантов на ключ эффекта, I3 один COMMIT на работу,
I4 монотонный указатель версии, I5 ready не откатывается, I6 fencing, I7 нет осиротевших объектов).
D дубли: 8 копий сообщения одной работы одновременно (worker'ы стартуют на полной очереди)
R reorder: устаревшие попытки (attempt 1, 2) приходят после attempt 3; попытка «из будущего»
C crash до побочного эффекта / после записи S3 до COMMIT / после COMMIT до ack / зависание (fencing)
V1 устаревшая работа после новой версии: v2 опубликована, затем исполняется v1 → superseded без эффектов
V2 гонка версий: v1 медленно пишет результат, v2 фиксируется раньше → v1 не двигает указатель назад
V3 повторная доставка v1 после перехода на v2 и повтор reprocess — no-op
ВНИМАНИЕ: останавливает/пересоздаёт worker (в т. ч. с WORKER_PIPELINES=2), volumes не трогает.
"""
import os
import shlex
import subprocess
import time
import uuid
from common import (BASE_URL, DC, ROOT, Client, Suite, check, events, jobs_cli, login, make_png, new_user, s3_admin,
sh, sql, upload, wait_status, wait_until)
LEASE = float(os.environ.get("JOB_LEASE_SECONDS", "20"))
c = Client(BASE_URL, timeout=30)
s = Suite("track 2: pipeline idempotency (" + BASE_URL + ")")
alice = new_user(c, "ia"); login(c, alice)
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "idempotency", "member_ids": [alice["id"]]})["json"]
START = sql("SELECT to_char(clock_timestamp() AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"')")[0]
def workers(pipelines=None):
"""Пересоздать worker'ы с заданным WORKER_PIPELINES (None — по умолчанию 1,2) и дождаться healthy."""
env = dict(os.environ)
if pipelines:
env["WORKER_PIPELINES"] = pipelines
else:
env.pop("WORKER_PIPELINES", None)
subprocess.run(shlex.split(DC) + ["up", "-d", "--no-deps", "--force-recreate", "--wait", "worker"], cwd=ROOT,
check=True, timeout=180, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def names(aid):
return [e["event"] for e in events(aid)]
def jobs_of(aid):
return {j["pipeline_version"]: j for j in jobs_cli("status", aid)["jobs"]}
def invariants(scope_since=START):
r = jobs_cli("invariants", "--settled", "--verify-bytes", "--since", scope_since, expect=(0, 1))
check(r["ok"], "invariants violated: %s" % r["violations"])
return r["stats"]
def served(aid):
return {v["name"]: v["sha256"] for v in
c.call("GET", "/api/v1/attachments/" + aid, actor=alice, schema="Attachment")["json"]["variants"]}
def v_rows(aid):
return sql("SELECT pipeline_version || ':' || name || ':' || sha256 FROM attachment_variants"
" WHERE attachment_id = '%s' ORDER BY 1" % aid)
@s.case("D: 8 duplicate copies of one job delivered concurrently → one claim, one commit")
def _():
sh("stop_worker", timeout=120)
try:
att, _ = upload(c, alice, chat, make_png(70, 50), filename="dup.png")
wait_until(lambda: "published" in names(att["id"]), timeout=30)
job = jobs_of(att["id"])[1]
jobs_cli("publish-raw", "--job", job["job_id"], "--count", "8")
finally:
sh("start_worker", timeout=120)
wait_status(c, alice, att["id"], ("ready", "failed"), timeout=60)
wait_until(lambda: names(att["id"]).count("duplicate_ignored") == 8, timeout=LEASE * 3, interval=1)
seq = names(att["id"])
check(seq.count("claimed") == 1 and seq.count("committed") == 1 and "lease_takeover" not in seq, "%s" % seq)
check(len(v_rows(att["id"])) == 3, "variant rows")
return "9 deliveries: claimed 1, committed 1, duplicate_ignored 8"
@s.case("R: reorder — stale attempts (1, 2) and a future one arrive DURING attempt 3 → ignored")
def _():
# попытки 1–2 падают «временно», попытка 3 медленная (15 с) — в это окно приходят старые сообщения
att, _ = upload(c, alice, chat, make_png(44, 44), filename="fault-transient-2-fault-slow-15.png")
wait_until(lambda: names(att["id"]).count("claimed") == 3, timeout=60, interval=0.5)
job = jobs_of(att["id"])[1]
check(job["attempt"] == 3 and job["status"] == "processing", "job %s/%s" % (job["status"], job["attempt"]))
for a in (2, 1, 9):
jobs_cli("publish-raw", "--job", job["job_id"], "--attempt", a)
wait_until(lambda: names(att["id"]).count("stale_ignored") == 3, timeout=30, interval=1)
check(jobs_of(att["id"])[1]["status"] == "processing", "stale message interrupted the live attempt")
wait_status(c, alice, att["id"], "ready", timeout=60)
seq = names(att["id"])
check(seq.count("committed") == 1 and seq.count("claimed") == 3 and "lease_takeover" not in seq, "%s" % seq)
future = [e for e in events(att["id"]) if e["event"] == "stale_ignored" and (e["detail"] or {}).get("future")]
check(len(future) == 1 and len(v_rows(att["id"])) == 3, "future attempt / variants")
return "during attempt 3: attempts 2, 1 → stale_ignored; 9 → stale_ignored(future) + term; one commit"
@s.case("C: crash before/after side effect, after COMMIT, hung worker — all reach one result")
def _():
kinds = ["crash-before-s3", "crash-after-s3", "crash-after-commit", "hang-40"]
ids = {k: upload(c, alice, chat, make_png(60, 61), filename="fault-%s-m.png" % k)[0]["id"] for k in kinds}
for k, aid in ids.items():
check(wait_status(c, alice, aid, ("ready", "failed"), timeout=LEASE * 6)["status"] == "ready", k)
wait_until(lambda: "lease_lost" in names(ids["hang-40"]), timeout=60, interval=1)
out = {}
for k, aid in ids.items():
seq = names(aid)
check(seq.count("committed") == 1, "%s: %s" % (k, seq))
out[k] = "takeover" if "lease_takeover" in seq else ("dup_ignored" if "duplicate_ignored" in seq else "-")
return "%s" % out
@s.case("V1: stale v1 job after v2 is published → superseded, no v1 side effects")
def _():
sh("stop_worker", timeout=120)
att, data = upload(c, alice, chat, make_png(150, 100), filename="v1-after-v2.png")
r = jobs_cli("reprocess", "--attachment", att["id"], "--pipeline-version", 2)
check(r["result"] == "enqueued", "%s" % r)
wait_until(lambda: names(att["id"]).count("published") == 2, timeout=30)
workers("2") # только v2-worker'ы: v1 откладывается (nak), v2 исполняется
try:
wait_until(lambda: jobs_of(att["id"])[2]["status"] == "ready", timeout=60)
finally:
workers() # снова 1,2 — теперь доходит устаревшая v1
wait_until(lambda: jobs_of(att["id"])[1]["status"] == "superseded", timeout=LEASE * 2, interval=1)
rows = v_rows(att["id"])
check(all(r.startswith("2:") for r in rows) and len(rows) == 3, "v1 wrote variants: %s" % rows)
check(s3_admin("ls", "variants/%s/v1/" % att["id"].replace("-", "")) == "", "v1 objects exist")
meta = c.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")["json"]
check(meta["status"] == "ready", "status")
check(sql("SELECT published_version FROM attachments WHERE id = '%s'" % att["id"]) == ["2"], "pointer")
return "v2 ready first; v1 → superseded at claim; variants only v2, pointer 2"
@s.case("V2: version race — slow v1 commits after v2 → pointer stays on v2 (no overwrite by older)")
def _():
att, _ = upload(c, alice, chat, make_png(140, 90), filename="race-fault-slow-12-v1.png")
wait_until(lambda: "claimed" in names(att["id"]), timeout=30, interval=0.5)
jobs_cli("reprocess", "--attachment", att["id"], "--pipeline-version", 2)
wait_until(lambda: jobs_of(att["id"]).get(2, {}).get("status") == "ready", timeout=60)
check(sql("SELECT published_version FROM attachments WHERE id = '%s'" % att["id"]) == ["2"], "v2 not published")
v2_served = served(att["id"])
wait_until(lambda: jobs_of(att["id"])[1]["status"] in ("superseded", "ready"), timeout=60, interval=1)
j1 = jobs_of(att["id"])[1]
check(j1["status"] == "superseded", "v1 status %s" % j1["status"])
check(sql("SELECT published_version FROM attachments WHERE id = '%s'" % att["id"]) == ["2"], "pointer moved back")
check(served(att["id"]) == v2_served, "served variants changed")
ev = [e for e in events(att["id"]) if e["event"] == "published_version_changed"]
check([e["detail"]["to"] for e in ev] == [2], "pointer history %s" % [e["detail"] for e in ev])
return "v1 finished after v2 → superseded at commit; pointer history %s" % [(e["detail"]["from"], e["detail"]["to"]) for e in ev]
@s.case("V3: redelivered v1 after v2 rollout and repeated reprocess are no-ops")
def _():
att, _ = upload(c, alice, chat, make_png(64, 48), filename="rollout.png")
wait_status(c, alice, att["id"], "ready")
v1_served = served(att["id"])
jobs_cli("reprocess", "--attachment", att["id"], "--pipeline-version", 2)
wait_until(lambda: sql("SELECT published_version FROM attachments WHERE id = '%s'" % att["id"]) == ["2"], timeout=60)
v2_served = served(att["id"])
check(v2_served != v1_served and set(v2_served) == set(v1_served), "v2 variants not served")
j = jobs_of(att["id"])
jobs_cli("publish-raw", "--job", j[1]["job_id"], "--count", "3")
r1 = jobs_cli("reprocess", "--attachment", att["id"], "--pipeline-version", 2)
r2 = jobs_cli("reprocess", "--attachment", att["id"], "--pipeline-version", 1)
check(r1["result"] == r2["result"] == "noop", "%s %s" % (r1, r2))
wait_until(lambda: names(att["id"]).count("duplicate_ignored") >= 3, timeout=30, interval=1)
check(served(att["id"]) == v2_served, "v1 duplicate changed result")
check(sql("SELECT published_version FROM attachments WHERE id = '%s'" % att["id"]) == ["2"], "pointer")
return "v1 ready → v2 ready (pointer 1→2); 3 v1 duplicates ignored; reprocess v1/v2 again → noop"
@s.case("invariants I1–I7 hold for everything this suite produced (settled, bytes verified)")
def _():
wait_until(lambda: jobs_cli("invariants", "--settled", "--since", START, expect=(0, 1))["ok"], timeout=60, interval=2)
st = invariants()
return "attachments %s, jobs %s %s, variants %s, events %s" % (
st["attachments"], st["jobs"], st["job_status"], st["variants"], st["events"])
s.run()
+273
View File
@@ -0,0 +1,273 @@
#!/usr/bin/env python3
"""lab7: проверки ВНЕШНЕЙ границы через HTTPS (с хоста, как клиент): TLS/hostname, ACL постороннего,
подмена X-User-Id/X-Forwarded-For, logout/expiry, общий для реплик лимит входа (429 + Retry-After),
ограничения размера запроса, Argon2id и rehash legacy hash, отсутствие утечек в ошибках.
python3 student-tests/test_security.py # BASE_URL=https://127.0.0.1:8443, CA_FILE=secrets/tls/trust/ca.crt
Для части проверок нужен SQL суперпользователя внутри контейнера (PSQL из common.py; только синтетика).
"""
import base64
import hashlib
import http.client
import json
import os
import secrets
import socket
import ssl
import time
import urllib.error
import urllib.request
from urllib.parse import urlsplit
from common import (BASE_URL, CA_FILE, ROOT, TTL_BASE_URL, Client, Suite, basic, check, login, new_user, sql,
upload, wait_status)
c = Client(BASE_URL)
s = Suite("lab7 external security (%s)" % BASE_URL)
U = urlsplit(BASE_URL)
FOREIGN_CA = str(ROOT / "secrets" / "test" / "foreign-ca.crt")
def raw(method, path, headers=None, body=None):
"""Ответ без проверок публичного клиента (ответы самого LB не содержат X-Instance-Id)."""
ctxt = ssl.create_default_context(cafile=CA_FILE)
conn = http.client.HTTPSConnection(U.hostname, U.port, context=ctxt, timeout=10)
try:
conn.request(method, path, body=body, headers=headers or {})
r = conn.getresponse()
return r.status, dict(r.getheaders()), r.read()
finally:
conn.close()
def tls_connect(context, server_hostname=None, host=None, port=None):
raw = socket.create_connection((host or U.hostname, port or U.port), timeout=5)
try:
return context.wrap_socket(raw, server_hostname=server_hostname or U.hostname)
except BaseException:
raw.close()
raise
@s.case("TLS: доверенный CA + hostname → 200; пустой/чужой trust store и чужое имя → ошибка ПРОВЕРКИ сертификата")
def _():
c.call("GET", "/health/ready")
out = []
for name, ctxf, host in (
("empty trust store", lambda: ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT), None),
("foreign CA", lambda: ssl.create_default_context(cafile=FOREIGN_CA), None),
("system CAs only", lambda: ssl.create_default_context(), None),
("wrong hostname", lambda: ssl.create_default_context(cafile=CA_FILE), "evil.example")):
try:
tls_connect(ctxf(), host).close()
raise AssertionError(name + ": handshake succeeded")
except ssl.SSLCertVerificationError as e:
out.append("%s → %s" % (name, e.verify_message))
return "; ".join(out)
@s.case("TLS: версии < 1.2 отклоняются; согласуется TLS 1.3/1.2; HSTS; plaintext на :8443 не обслуживается")
def _():
old = ssl.create_default_context(cafile=CA_FILE)
old.minimum_version = ssl.TLSVersion.MINIMUM_SUPPORTED
import warnings
warnings.simplefilter("ignore", DeprecationWarning)
old.maximum_version = ssl.TLSVersion.TLSv1_1
try:
old.set_ciphers("ALL:@SECLEVEL=0")
tls_connect(old).close()
raise AssertionError("TLS 1.1 accepted")
except ssl.SSLError as e:
r11 = getattr(e, "reason", None) or type(e).__name__
t12 = ssl.create_default_context(cafile=CA_FILE)
t12.maximum_version = ssl.TLSVersion.TLSv1_2
v12 = tls_connect(t12)
v12_ver, v12_cipher = v12.version(), v12.cipher()[0]
v12.close()
v13 = tls_connect(ssl.create_default_context(cafile=CA_FILE))
ver = v13.version()
v13.close()
r = c.call("GET", "/health/live")
hsts = r["headers"].get("Strict-Transport-Security") or r["headers"].get("strict-transport-security")
check(hsts and "max-age=" in hsts, "no HSTS")
conn = http.client.HTTPConnection(U.hostname, U.port, timeout=5)
try:
conn.request("GET", "/health/live")
plain = conn.getresponse().status
check(plain == 400, "plaintext HTTP on TLS port answered %s" % plain)
except (http.client.RemoteDisconnected, ConnectionResetError) as e:
plain = "closed (%s)" % type(e).__name__
closed = []
for port in (8080, 8081, 9000, 5432, 6379, 4222, 4318):
try:
socket.create_connection(("127.0.0.1", port), timeout=1).close()
raise AssertionError("port %d is published on the host" % port)
except OSError:
closed.append(port)
return "TLS1.1→%s; TLS1.2 ok (%s); default %s; HSTS=%s; plaintext→%s; host ports closed: %s" % (
r11, v12_cipher, ver, hsts, plain, closed)
@s.case("ACL: посторонний не видит чат/сообщения/вложение (404); X-User-Id не меняет Bearer identity")
def _():
alice, bob, eve = new_user(c, "sa"), new_user(c, "sb"), new_user(c, "se")
for u in (alice, bob, eve):
login(c, u)
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "sec", "member_ids": [alice["id"], bob["id"]]})["json"]
c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 201, actor=alice, body={"text": "секрет"},
headers={"Idempotency-Key": secrets.token_hex(8)})
att, _ = upload(c, alice, chat)
wait_status(c, alice, att["id"], "ready")
for path in ("/api/v1/chats/" + chat["id"], "/api/v1/chats/%s/messages" % chat["id"],
"/api/v1/attachments/" + att["id"], "/api/v1/attachments/%s/content" % att["id"]):
c.call("GET", path, 404, actor=eve)
# eve прикрепляет чужой файл к сообщению в СВОЁМ чате → 404 (файл другого чата)
own = c.call("POST", "/api/v1/chats", 201, actor=eve, schema="Chat", body={"title": "eve", "member_ids": [eve["id"]]})["json"]
c.call("POST", "/api/v1/chats/%s/messages" % own["id"], 404, actor=eve, body={"text": "x", "attachment_ids": [att["id"]]},
headers={"Idempotency-Key": secrets.token_hex(8)})
me = c.call("GET", "/api/v1/users/me", 200, actor=eve, schema="User", headers={"X-User-Id": alice["id"]})["json"]
check(me["id"] == eve["id"], "X-User-Id changed identity")
c.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": alice["id"]})
c.call("GET", "/api/v1/chats/" + chat["id"], 200, actor=bob)
return "outsider 404 ×4, foreign attachment 404, X-User-Id ignored (me=eve), anonymous+X-User-Id 401"
@s.case("logout отзывает сессию; истечение TTL (api-ttl, профиль ttl) → 401")
def _():
u = new_user(c, "lo")
login(c, u)
c.call("GET", "/api/v1/users/me", 200, actor=u)
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=u)
c.call("GET", "/api/v1/users/me", 401, actor=u)
c.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=u)
try:
t = Client(TTL_BASE_URL)
t.call("GET", "/health/ready")
except Exception: # noqa: BLE001
return "logout ok; api-ttl не запущен (expiry — student-tests/test_expiry.py с профилем ttl)"
v = new_user(t, "ttl")
login(t, v)
t.call("GET", "/api/v1/users/me", 200, actor=v)
time.sleep(3.0)
t.call("GET", "/api/v1/users/me", 401, actor=v)
return "logout → 401; TTL 2 s → 401 после истечения"
def raw_login(username, password, extra_headers=None):
h = {"Authorization": basic(username, password)}
h.update(extra_headers or {})
r = c.call("POST", "/api/v1/auth/sessions", [201, 401, 429, 503], headers=h)
return r["status"], r["headers"]
@s.case("лимит входа ОБЩИЙ для реплик: 5 неудач (IP+username) → 429 + Retry-After, даже с верным паролем")
def _():
u = new_user(c, "rl")
seen, statuses = set(), []
for i in range(5):
st, h = raw_login(u["username"], "wrong-password-%d" % i)
statuses.append(st)
seen.add(h.get("X-Instance-Id"))
st, h = raw_login(u["username"], u["password"]) # верный пароль — уже поздно
check(statuses == [401] * 5 and st == 429, "statuses %s then %s" % (statuses, st))
ra = int(h.get("Retry-After", "0"))
check(1 <= ra <= 300, "Retry-After=%s" % h.get("Retry-After"))
# Подмена X-Forwarded-For не обходит лимит (LB перезаписывает заголовок)
st2, h2 = raw_login(u["username"], u["password"], {"X-Forwarded-For": "203.0.113.%d" % secrets.randbelow(250)})
check(st2 == 429, "XFF spoof bypassed the limit: %s" % st2)
# Другой пользователь с того же IP не заблокирован (лимит по паре IP+username, а не глобальный)
other = new_user(c, "rl2")
st3, _ = raw_login(other["username"], other["password"])
check(st3 == 201, "other user blocked: %s" % st3)
body = c.call("POST", "/api/v1/auth/sessions", 429, headers={"Authorization": basic(u["username"], u["password"])})
err = body["json"]["error"]
check(err["code"] == "rate_limited" and u["password"] not in json.dumps(body["json"]), "error body")
check(len(seen) >= 2, "401s came from one replica only (%s) — sharing not demonstrated" % seen)
return "401×5 от реплик %s → 429 Retry-After=%ss (shared via Redis); XFF spoof → 429; другой user → 201" % (
sorted(x for x in seen if x), ra)
@s.case("ограничения размера: JSON > 64 KiB → 413 (API), URI > 4 KiB → 414, > 64 заголовков → 400, заголовок > 16 KiB → 400 (LB)")
def _():
u = new_user(c, "sz")
login(c, u)
auth = {"Authorization": "Bearer " + u["token"]}
out = []
big = json.dumps({"title": "x" * 70000, "member_ids": [u["id"]]}).encode()
r = c.call("POST", "/api/v1/chats", 413, actor=u, raw=big, headers={"Content-Type": "application/json"})
out.append("json 70 KB→%s %s" % (r["status"], r["json"]["error"]["code"]))
st, h, b = raw("GET", "/api/v1/chats?cursor=" + "a" * 5000, auth)
check(st == 414, "long URI: %s" % st)
out.append("URI 5 KB→%s" % st)
st, h, b = raw("GET", "/api/v1/users/me", dict(auth, **{"X-H%d" % i: "v" for i in range(70)}))
check(st == 400, "70 headers: %s" % st)
out.append("70 headers→%s" % st)
try:
st, h, b = raw("GET", "/api/v1/users/me", dict(auth, **{"X-Big": "v" * 20000}))
check(st in (400, 431), "20 KB header: %s" % st)
out.append("20 KB header→%s" % st)
except (ConnectionError, http.client.HTTPException) as e:
out.append("20 KB header→closed (%s)" % type(e).__name__)
st, h, b = raw("POST", "/api/v1/chats/%s/attachments?filename=a.png" % u["id"],
dict(auth, **{"Content-Type": "image/png", "Content-Length": str(50 * 2 ** 20)}), b"")
check(st == 413, "50 MiB declared: %s" % st)
out.append("upload Content-Length 50 MiB→413 (LB, до чтения тела)")
return ", ".join(out)
def scrypt_hash(password):
salt = secrets.token_bytes(16)
d = hashlib.scrypt(password.encode(), salt=salt, n=2 ** 15, r=8, p=3, maxmem=128 * 8 * 2 ** 15 * 2 + 3 * 2 ** 20, dklen=32)
b = lambda x: base64.b64encode(x).decode().rstrip("=") # noqa: E731
return "$scrypt$ln=15,r=8,p=3$%s$%s" % (b(salt), b(d))
@s.case("Argon2id: соль+параметры в PHC; ≥ 19 MiB/t≥2/p=1; legacy scrypt и слабый Argon2id перехешируются при входе")
def _():
u = new_user(c, "ar")
h = sql("SELECT password_hash FROM users WHERE id = '%s'" % u["id"])[0]
check(h.startswith("$argon2id$v=19$"), "not argon2id: %s" % h[:20])
params = dict(x.split("=") for x in h.split("$")[3].split(","))
m, t, p = int(params["m"]), int(params["t"]), int(params["p"])
check(m >= 19456 and t >= 2 and p == 1, "weak params %s" % params)
# legacy: hash lab2–lab6 (scrypt) → вход → hash заменён текущим Argon2id
legacy = new_user(c, "lg")
sql("UPDATE users SET password_hash = '%s' WHERE id = '%s'" % (scrypt_hash(legacy["password"]), legacy["id"]))
login(c, legacy)
after = sql("SELECT password_hash FROM users WHERE id = '%s'" % legacy["id"])[0]
check(after.startswith("$argon2id$v=19$m=%d,t=%d,p=%d$" % (m, t, p)), "scrypt not rehashed: %s" % after[:30])
out = ["current m=%d t=%d p=%d" % (m, t, p), "scrypt → argon2id ✓"]
if t > 2: # слабее текущих (минимум OWASP t=2) → rehash до текущих
from_ = h.replace("t=%d," % t, "t=2,") # параметры в строке не совпадают с hash → вход не пройдёт…
weak = new_user(c, "wk")
# …поэтому слабый hash считаем честно (если на хосте есть cryptography) — иначе пропускаем.
try:
from cryptography.hazmat.primitives.kdf.argon2 import Argon2id
enc = Argon2id(salt=secrets.token_bytes(16), length=32, iterations=2, lanes=1,
memory_cost=19456).derive_phc_encoded(weak["password"].encode())
sql("UPDATE users SET password_hash = '%s' WHERE id = '%s'" % (enc, weak["id"]))
login(c, weak)
w2 = sql("SELECT password_hash FROM users WHERE id = '%s'" % weak["id"])[0]
check("t=%d" % t in w2, "weak argon2 not rehashed: %s" % w2[:40])
out.append("argon2id t=2 → t=%d ✓" % t)
except ImportError:
out.append("argon2id weak→strong: skipped (no cryptography on host)")
del from_
return "; ".join(out)
@s.case("ошибки не раскрывают credentials: 401 одинаков для неизвестного/неверного; нет Server/версий; пароль не эхо")
def _():
u = new_user(c, "er")
a = c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic(u["username"], "Wrong-pass-123")})
b = c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic("nouser_" + secrets.token_hex(4), "Wrong-pass-123")})
check(a["json"]["error"]["message"] == b["json"]["error"]["message"], "different 401 messages")
check("Wrong-pass-123" not in json.dumps(a["json"]) and u["username"] not in json.dumps(a["json"]), "echo")
srv = a["headers"].get("Server") or a["headers"].get("server")
check(not srv, "Server header: %s" % srv)
return "401 identical, no Server header, no credential echo"
if __name__ == "__main__":
s.run()
+147
View File
@@ -0,0 +1,147 @@
#!/usr/bin/env python3
"""Отказы объектного хранилища и согласованность S3 ↔ PostgreSQL (уровень 4).
ВНИМАНИЕ: тест останавливает/запускает контейнер s3 и поднимает профиль fault (api-fault, :8445).
Volumes не удаляются. Команды переопределяются STOP_S3/START_S3/FAULT_UP/FAULT_DOWN.
"""
import os
import socket
import subprocess
import shlex
import time
from urllib.parse import urlsplit
from common import (BASE_URL, DC, ROOT, Client, Failure, Suite, check, login, make_png, new_user, s3_admin, sh, sql,
upload, wait_until)
FAULT_URL = os.environ.get("FAULT_BASE_URL", "https://127.0.0.1:8445")
CMD = {"stop_s3": os.environ.get("STOP_S3", DC + " stop s3"),
"start_s3": os.environ.get("START_S3", DC + " start s3"),
"fault_up": os.environ.get("FAULT_UP", DC + " --profile fault up -d --no-deps --force-recreate api-fault"),
"fault_down": os.environ.get("FAULT_DOWN", DC + " --profile fault stop api-fault")}
c = Client(BASE_URL, timeout=15)
s = Suite("object storage failures (" + BASE_URL + ")")
alice = new_user(c, "sa"); login(c, alice)
bob = new_user(c, "sb"); login(c, bob)
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "storage", "member_ids": [alice["id"], bob["id"]]})["json"]
UP = "/api/v1/chats/" + chat["id"] + "/attachments"
def n_objects():
"""lab5: загрузка пишет в staging/ (оригинал публикует worker в originals/ после обработки)."""
return len(s3_admin("ls", "staging/").splitlines())
def n_intents():
return int(sql("SELECT count(*) FROM upload_intents")[0])
@s.case("bucket is private outside API: anonymous GET/LIST/PUT denied, API key limited")
def _():
att, _ = upload(c, alice, chat)
c.wait_ready(alice, att) # оригинал опубликован в originals/
key = sql("SELECT object_key FROM attachments WHERE id = '%s'" % att["id"])[0]
status = s3_admin("anon-get", key)
check(status in ("401", "403"), "anonymous GET of existing object returned " + status)
out = subprocess.run(shlex.split(DC + " exec -T api python -m messenger s3-check"), cwd=ROOT,
capture_output=True, text=True, timeout=60)
lines = [ln for ln in out.stdout.splitlines() if ln.startswith(("PASS", "FAIL"))]
check(out.returncode == 0 and lines and all(ln.startswith("PASS") for ln in lines), "s3-check failed: " + out.stdout[-400:])
return "anon GET %s; s3-check %d/%d PASS" % (status, len(lines), len(lines))
@s.case("S3 down: upload/download 503 fast, text messages and readiness keep working")
def _():
att, data = upload(c, alice, chat)
c.wait_ready(alice, att)
sh(CMD["stop_s3"])
try:
t = time.monotonic()
c.call("POST", UP + "?filename=a.png", 503, actor=alice, raw=make_png(), headers={"Content-Type": "image/png"})
took_up = time.monotonic() - t
t = time.monotonic()
c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", 503, actor=bob)
took_down = time.monotonic() - t
c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment") # метаданные — из БД
c.message(alice, chat, "S3 лежит, текст работает")
c.message(alice, chat, "", attachments=[att["id"]]) # ссылка на готовое вложение
c.call("GET", "/health/ready", schema="Health")
check(took_up < 5 and took_down < 5, "503 too slow: %.2f / %.2f s" % (took_up, took_down))
finally:
sh(CMD["start_s3"])
# После старта SeaweedFS чтение возвращается раньше записи (прогрев топологии ~15 с): ждём оба.
slow = Client(BASE_URL, timeout=60)
t0 = time.monotonic()
wait_until(lambda: slow.call("GET", "/api/v1/attachments/" + att["id"] + "/content", [200, 503], actor=bob)["status"] == 200,
timeout=90)
read_back = time.monotonic() - t0
wait_until(lambda: slow.call("POST", UP + "?filename=b.png", [202, 503], actor=alice, raw=make_png(),
headers={"Content-Type": "image/png"})["status"] == 202, timeout=90)
write_back = time.monotonic() - t0
check(c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=bob)["bytes"] == data, "data changed")
return "503 in %.2fs/%.2fs; after start: reads %.1fs, writes %.1fs" % (took_up, took_down, read_back, write_back)
@s.case("interrupted upload: no object and no intent left behind")
def _():
objects, intents = n_objects(), n_intents()
png = make_png(300, 300)
u = urlsplit(BASE_URL)
head = ("POST %s?filename=cut.png HTTP/1.1\r\nHost: %s\r\nAuthorization: Bearer %s\r\nContent-Type: image/png\r\n"
"Content-Length: %d\r\n\r\n" % (UP, u.netloc, alice["token"], len(png))).encode()
for cut in (len(png) // 3, len(png) - 1):
sock = socket.create_connection((u.hostname, u.port or 80), timeout=5)
sock.sendall(head + png[:cut])
time.sleep(0.3)
sock.close() # клиент пропал посреди тела
wait_until(lambda: n_intents() <= intents, timeout=30)
check(n_objects() == objects, "objects changed: %d -> %d" % (objects, n_objects()))
return "objects %d, intents %d — unchanged" % (objects, intents)
@s.case("uploads rejected at the very end (truncated PNG) leave no staging object (race regression)")
def _():
# Ошибка обнаруживается только в finish(), после последнего байта. Раньше S3 мог зафиксировать
# объект уже после компенсирующего DELETE (нашёл инвариант I7); теперь последний кусок
# придерживается до проверки, и PUT обрывается раньше Content-Length.
before = n_objects()
png = make_png(20, 20)
for i in range(30):
c.call("POST", UP + "?filename=trunc%d.png" % i, 415, actor=alice, raw=png[:-12], headers={"Content-Type": "image/png"})
time.sleep(3)
after = n_objects()
check(after == before, "staging objects %d -> %d" % (before, after))
return "30 × 415 at finish(); staging objects %d → %d" % (before, after)
@s.case("crash between staging PUT and DB COMMIT: intent recorded, janitor removes object after grace")
def _():
os.environ["API_FAULT_INJECT"] = "crash_after_s3_put" # точка отказа api-fault для этого сценария
sh(CMD["fault_up"], timeout=120)
try:
fc = Client(FAULT_URL, timeout=10)
wait_until(lambda: fc.call("GET", "/health/ready", [200, 503])["status"] == 200, timeout=90)
objects = n_objects()
try:
upload(fc, alice, chat, make_png(50, 50))
raise Failure("upload to crashing replica unexpectedly succeeded")
except Failure as exc:
if "unexpectedly" in str(exc):
raise
rows = sql("SELECT object_key FROM upload_intents WHERE created_at > clock_timestamp() - interval '1 minute'")
check(rows, "no intent recorded before S3 PUT")
key = rows[-1]
check(s3_admin("sha", key) != "-", "object must exist after PUT (crash happened after it)")
check(sql("SELECT count(*) FROM attachments WHERE staging_key = '%s'" % key) == ["0"], "metadata committed?!")
t = time.monotonic()
wait_until(lambda: s3_admin("sha", key) == "-" and
sql("SELECT count(*) FROM upload_intents WHERE object_key = '%s'" % key) == ["0"], timeout=90, interval=2)
check(n_objects() == objects, "untracked objects remain")
return "orphan %s… removed %.1fs after crash (grace 10 s)" % (key[:20], time.monotonic() - t)
finally:
sh(CMD["fault_down"], timeout=120)
os.environ.pop("API_FAULT_INJECT", None)
s.run()
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""lab6: история наблюдений переживает перезапуск хранилищ telemetry (volumes promdata/lokidata/tempodata/
grafanadata) и сбор продолжается после него.
Сценарий: контролируемый запрос (известный X-Request-Id) → его лог, trace и значение метрики в прошлом →
scripts/restart.sh (перезапуск ВСЕХ сервисов, включая Collector, Prometheus, Loki, Tempo, Grafana) →
тот же лог, тот же trace и то же историческое значение метрики находятся снова; dashboard по-прежнему
provisioned; новый запрос после рестарта тоже доходит до всех трёх хранилищ.
"""
import os
import subprocess
import sys
import time
from common import BASE_URL, ROOT, Client, Suite, check, login, new_user
from obs import Grafana, ObsError, wait_for
suite = Suite("lab6: сохранность истории telemetry после перезапуска")
c = Client(BASE_URL)
g = Grafana()
st = {}
HOOK = os.environ.get("RESTART_HOOK", "scripts/restart.ps1" if os.name == "nt" else "scripts/restart.sh")
def controlled_request():
a = new_user(c, "persist")
login(c, a)
chat = c.call("POST", "/api/v1/chats", 201, actor=a, schema="Chat", body={"title": "p", "member_ids": [a["id"]]})["json"]
r = c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 201, actor=a, body={"text": "persist"},
headers={"Idempotency-Key": "persist-%d" % time.time_ns()})
rid = r["headers"]["X-Request-Id"]
rec = wait_for(lambda: [x for x in g.loki('{service_name="messenger-api"} | request_id="%s"' % rid, since=600)
if x.get("event") == "http.request"], 60, what="log")[-1]
wait_for(lambda: g.trace(rec["trace_id"]), 60, what="trace")
return rid, rec["trace_id"]
@suite.case("до рестарта: лог, trace и метрика контрольного запроса сохранены")
def before():
rid, tid = controlled_request()
time.sleep(15) # метрика экспортирована и записана
st["t"] = time.time()
st["metric"] = g.prom_value('sum(http_server_request_duration_seconds_count{service_name="messenger-api",'
'http_route="/api/v1/chats/{chat_id}/messages"})', at=st["t"])
check(st["metric"], "no metric value")
st.update(rid=rid, tid=tid)
return "request_id → trace %s…, счётчик POST messages = %d" % (tid[:12], st["metric"])
@suite.case("перезапуск всех сервисов и хранилищ (volumes сохраняются)")
def restart():
cmd = (["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", HOOK] if HOOK.endswith(".ps1") else [HOOK])
t0 = time.time()
subprocess.run(cmd, cwd=ROOT, check=True, timeout=300, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def ready():
ok = c.call("GET", "/health/ready", [200, 503, 502])["status"] == 200
ok = ok and all(g.get("/api/datasources/uid/%s/health" % u).get("status") == "OK" for u in ("prometheus", "loki", "tempo"))
return ok
wait_for(ready, 180, interval=2, what="stack ready after restart")
return "hook %s + готовность за %.0f с" % (HOOK, time.time() - t0)
@suite.case("после рестарта: тот же лог, тот же trace, то же значение метрики в прошлом")
def after():
recs = wait_for(lambda: g.loki('{service_name="messenger-api"} | request_id="%s"' % st["rid"], since=1800), 60, what="old log")
check(any(r.get("trace_id") == st["tid"] for r in recs), "old log lost or unlinked")
spans = wait_for(lambda: g.trace(st["tid"]), 90, what="old trace")
check(any(s["kind"] == "SERVER" and s["attrs"].get("messenger.request_id") == st["rid"] for s in spans), "old trace content")
v = g.prom_value('sum(http_server_request_duration_seconds_count{service_name="messenger-api",'
'http_route="/api/v1/chats/{chat_id}/messages"})', at=st["t"])
check(v == st["metric"], "historical metric changed: %s != %s" % (v, st["metric"]))
d = g.get("/api/dashboards/uid/messenger-overview")
check(d["meta"].get("provisioned"), "dashboard lost")
return "лог, trace (%d spans), метрика (%d) и dashboard на месте" % (len(spans), v)
@suite.case("после рестарта: новые данные доходят во все три хранилища")
def new_data():
rid, tid = controlled_request()
v = wait_for(lambda: g.prom_value('sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api"}[1m]))'),
60, what="fresh metrics")
return "новый trace %s…, текущий RPS API %.2f" % (tid[:12], v)
if __name__ == "__main__":
try:
g.get("/api/health")
except ObsError as e:
sys.exit("Grafana недоступна: %s" % e)
suite.run()