ЛР 5 — БВТ2302 — Лебедев — на 5

This commit is contained in:
2026-11-22 23:05:53 +03:00
parent 276dbdad8a
commit fbd04ce238
112 changed files with 9536 additions and 16 deletions
+185
View File
@@ -0,0 +1,185 @@
"""Общая обвязка собственных проверок студента (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")
PSQL = os.environ.get("PSQL", DC + " exec -T postgres psql -U messenger -d messenger")
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", "http://127.0.0.1:8080")
TTL_BASE_URL = os.environ.get("TTL_BASE_URL", "http://127.0.0.1:8081")
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 + " run --rm --no-deps -T --entrypoint python s3-init -")
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()
# Операторские команды выполняются в контейнере API (тот же образ; worker может быть остановлен).
JOBS_EXEC = os.environ.get("JOBS_EXEC", DC + " exec -T api")
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):
r = c.call("POST", "/api/v1/auth/sessions", expected, headers={"Authorization": basic(actor["username"], actor["password"])},
schema="Session" if expected == 201 else None)
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"]
+104
View File
@@ -0,0 +1,104 @@
#!/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, 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:
v = probe()
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

+84
View File
@@ -0,0 +1,84 @@
"""Внедрение отказов на стороне 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", "http://s3:9000")
if op == "anon-get":
import httpx
async with httpx.AsyncClient() 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_ADMIN_ACCESS_KEY_ID", True), _secret("S3_ADMIN_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:]))
+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 scrypt KDF hash; User has no secret fields")
def _():
row = sql("SELECT password_hash FROM users WHERE id = '%s'" % alice["id"])[0]
check(row.startswith("$scrypt$ln=15,r=8,p=3$"), "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()
+251
View File
@@ -0,0 +1,251 @@
#!/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 80), timeout=wait)
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()
+71
View File
@@ -0,0 +1,71 @@
#!/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.config import load # noqa: E402
from messenger.sessions import KEY, TOMBSTONE, Principal, SessionCache # noqa: E402
async def main():
settings = load()
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)
+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, :8082), внедряет падения 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", "http://127.0.0.1:8082")
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()
+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()
+147
View File
@@ -0,0 +1,147 @@
#!/usr/bin/env python3
"""Отказы объектного хранилища и согласованность S3 ↔ PostgreSQL (уровень 4).
ВНИМАНИЕ: тест останавливает/запускает контейнер s3 и поднимает профиль fault (api-fault, :8082).
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", "http://127.0.0.1:8082")
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()