Перенос решения ЛР 6 без изменений (src, migrations, student-tests, bench, infra, scripts, compose, Dockerfile, docs)

This commit is contained in:
Alexey Bodanyuk
2026-11-27 16:01:21 +03:00
parent 20afc2c790
commit 6435b6a1c5
111 changed files with 19604 additions and 0 deletions
+439
View File
@@ -0,0 +1,439 @@
"""Shared helpers for the student tests.
* `unit/` — pure functions (validation, cursor, auth headers, Argon2id); no services.
* `test_*` in this folder — marker `stack`: black-box HTTP against the running compose
stand THROUGH THE LOAD BALANCER (BASE_URL, default http://127.0.0.1:8080) plus
`docker compose` for database checks (psql inside the postgres container), the HAProxy
runtime state (scripts/lbctl.py) and failure injection. Every failure test restores the
stopped/paused service or replica in `finally` and waits until HAProxy sees all replicas UP.
python -m pytest student-tests # everything (stand must be up)
python -m pytest student-tests -m "not stack" # unit only
"""
from __future__ import annotations
import base64
import contextlib
import json
import os
import subprocess
import sys
import time
import uuid
from pathlib import Path
from urllib.parse import quote
import httpx2 as httpx
import pytest
from jsonschema import Draft202012Validator
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
sys.path.insert(0, str(ROOT / "scripts"))
import lbctl # noqa: E402
SPEC = json.loads((ROOT / "contracts" / "openapi.json").read_text(encoding="utf-8"))
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
PASSWORD = "Test-password-Ω-12345" # synthetic; 12+ code points, non-ASCII on purpose
REPLICAS = int(os.environ.get("API_REPLICAS", "2")) # replicas the stand normally runs
def pytest_configure(config):
config.addinivalue_line("markers", "stack: needs the running compose stand (docker compose up -d --wait)")
def schema_errors(value, name: str) -> list[str]:
"""Validate against components/schemas/<name> of the course contract (JSON Schema 2020-12)."""
schema = {"$ref": f"#/components/schemas/{name}", "components": SPEC["components"]}
validator = Draft202012Validator(schema, format_checker=Draft202012Validator.FORMAT_CHECKER)
return [e.message for e in validator.iter_errors(value)]
def basic(username: str, password: str) -> str:
return "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()
# ------------------------------------------------------------------ docker / psql
def compose(*args: str, check: bool = True, timeout: float = 120, stdin: str | None = None) -> subprocess.CompletedProcess:
return subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, text=True,
encoding="utf-8", check=check, timeout=timeout, input=stdin)
def psql(sql: str) -> str:
"""Run SQL inside the postgres container (no DB port is published) and return unaligned output."""
result = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
"-At", "-v", "ON_ERROR_STOP=1", "-c", sql)
return result.stdout.strip()
def wait_ready(timeout: float = 90) -> None:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
if httpx.get(BASE_URL + "/health/ready", timeout=2).status_code == 200:
return
except httpx.HTTPError:
pass
time.sleep(0.3)
raise AssertionError("stand did not become ready")
def wait_healthy(*services: str, timeout: float = 120) -> None:
"""Poll Docker health until EVERY container of every service is healthy again. `compose up
--wait` is not used: it gives up at once on a container marked unhealthy while paused."""
deadline = time.monotonic() + timeout
pending = set(services)
while pending and time.monotonic() < deadline:
for service in list(pending):
ids = compose("ps", "-q", service, check=False).stdout.split()
if ids:
states = subprocess.run(["docker", "inspect", "-f", "{{.State.Health.Status}}", *ids],
capture_output=True, text=True).stdout.split()
if states and all(state == "healthy" for state in states):
pending.discard(service)
time.sleep(0.5)
assert not pending, f"not healthy: {pending}"
def wait_stand(replicas: int = REPLICAS) -> None:
"""Readiness through the LB AND every replica back in HAProxy rotation."""
wait_ready()
lbctl.wait_up(replicas, timeout=90)
def restart_services(*services: str) -> None:
compose("restart", *services)
wait_healthy(*services)
wait_stand()
@contextlib.contextmanager
def service_down(service: str, how: str = "stop"):
"""Stop or pause a compose service; ALWAYS bring it back and wait for readiness."""
assert how in {"stop", "pause"}
compose(how, service)
try:
yield
finally:
compose("unpause" if how == "pause" else "start", service)
wait_healthy(service)
wait_stand()
def recreate(service: str, env: dict, scale: int | None = None) -> None:
"""`docker compose up` of ONE service with the given environment (no dependency restarts)."""
cmd = ["docker", "compose", "up", "-d", "--no-deps", "--wait", service]
if scale is not None:
cmd[4:4] = ["--scale", f"{service}={scale}"]
subprocess.run(cmd, cwd=ROOT, env=env, capture_output=True, text=True, check=True, timeout=180)
@contextlib.contextmanager
def service_with_env(service: str, scale: int | None = None, **overrides: str):
"""Recreate a service (api, relay, worker) with environment overrides (e.g. FAULT_POINTS of the
worker = WORKER_FAULT_POINTS), then ALWAYS recreate it with the normal configuration."""
clean = {k: v for k, v in os.environ.items() if k not in overrides}
recreate(service, {**os.environ, **overrides}, scale)
if service == "api":
wait_stand()
try:
yield
finally:
recreate(service, clean, 1 if scale is not None and service != "api" else None)
wait_healthy(service)
if service == "api":
wait_stand()
def api_with_env(**overrides: str):
return service_with_env("api", **overrides)
def running_replicas() -> list[dict]:
return [r for r in lbctl.replicas() if r["state"] == "running"]
@contextlib.contextmanager
def replica_stopped(replica: dict, mode: str = "stop"):
"""Stop ONE api container (stop = SIGTERM + drain, kill = SIGKILL); ALWAYS start it again
and wait until HAProxy has every replica UP."""
assert mode in {"stop", "kill"}
subprocess.run(["docker", "stop", "--time", "15" if mode == "stop" else "0", replica["id"]],
capture_output=True, text=True, check=True, timeout=60)
try:
yield
finally:
subprocess.run(["docker", "start", replica["id"]], capture_output=True, text=True, check=True, timeout=60)
wait_healthy("api")
wait_stand()
def api_env(name: str) -> str:
"""Current value of an environment variable inside the running api container."""
return compose("exec", "-T", "api", "printenv", name).stdout.strip()
# ------------------------------------------------------------------ HTTP
class Api:
"""HTTP helper that checks the invariants every response must satisfy."""
def __init__(self, base_url: str = BASE_URL):
self.client = httpx.Client(base_url=base_url, timeout=15)
def call(self, method: str, path: str, expected: int | tuple[int, ...], *, token: str | None = None,
json_body=None, raw: bytes | None = None, headers: dict | None = None, schema: str | None = None,
lb_error_ok: bool = False):
"""lb_error_ok: a 502/503/504 generated by HAProxy itself (no API replica answered) is
accepted without X-Instance-Id; every response of an API replica must carry it."""
h = dict(headers or {})
if token is not None:
h["Authorization"] = "Bearer " + token
if json_body is not None:
raw = json.dumps(json_body, ensure_ascii=False).encode("utf-8")
h.setdefault("Content-Type", "application/json")
response = self.client.request(method, path, content=raw, headers=h)
allowed = (expected,) if isinstance(expected, int) else expected
assert response.status_code in allowed, (method, path, response.status_code, response.text[:300])
request_id = response.headers.get("x-request-id")
assert request_id, "every response must carry X-Request-Id"
if not response.headers.get("x-instance-id"):
assert lb_error_ok and response.status_code in (502, 503, 504), \
("missing X-Instance-Id", method, path, response.status_code)
if response.status_code >= 400:
body = response.json()
assert schema_errors(body, "Error") == [], response.text
assert body["error"]["request_id"] == request_id
assert "Traceback" not in response.text and "psycopg" not in response.text
if response.status_code == 401:
challenge = "basic" if path == "/api/v1/auth/sessions" else "bearer"
assert response.headers.get("www-authenticate", "").lower().startswith(challenge)
elif schema:
assert schema_errors(response.json(), schema) == [], response.text
return response
def register(self, label: str = "u", *, password: str = PASSWORD, display_name: str | None = None) -> dict:
username = f"{label}_{uuid.uuid4().hex[:12]}"[:32]
body = {"username": username, "display_name": display_name or f"Студент {label}", "password": password}
user = self.call("POST", "/api/v1/users", 201, json_body=body, schema="User").json()
return {"id": user["id"], "user": user, "username": username, "password": password}
def login(self, actor: dict) -> str:
session = self.call("POST", "/api/v1/auth/sessions", 201,
headers={"Authorization": basic(actor["username"], actor["password"])},
schema="Session").json()
assert session["user"] == actor["user"] and session["token_type"] == "Bearer"
return session["token"]
def user(self, label: str = "u", **kwargs) -> dict:
actor = self.register(label, **kwargs)
actor["token"] = self.login(actor)
return actor
def chat(self, owner: dict, *members: dict, title: str = "Тестовый чат") -> dict:
ids = [owner["id"], *(m["id"] for m in members)]
return self.call("POST", "/api/v1/chats", 201, token=owner["token"],
json_body={"title": title, "member_ids": ids}, schema="Chat").json()
def post_message(self, actor: dict, chat: dict, body, expected=201, *, key: str | None = None,
raw: bytes | None = None, headers: dict | None = None, **kwargs):
"""POST a message with an Idempotency-Key (a fresh one unless `key` is given)."""
h = {"Idempotency-Key": key or uuid.uuid4().hex, **(headers or {})}
if raw is not None:
h.setdefault("Content-Type", "application/json")
return self.call("POST", f"/api/v1/chats/{chat['id']}/messages", expected, token=actor["token"],
json_body=body if raw is None else None, raw=raw, headers=h,
schema="Message" if expected == 201 else None, **kwargs)
def send(self, actor: dict, chat: dict, text: str, key: str | None = None) -> dict:
return self.post_message(actor, chat, {"text": text}, key=key).json()
def upload(self, actor: dict, chat: dict, data, expected=202, *, content_type: str | None = "image/png",
filename: str | None = "photo.png", query: str | None = None, headers: dict | None = None):
"""POST raw bytes to /chats/{id}/attachments. `query` replaces the whole query string
(to send hand-made percent-encoding); `data` may be bytes or an iterator (chunked)."""
h = dict(headers or {})
if content_type is not None:
h["Content-Type"] = content_type
if query is None:
query = "" if filename is None else "filename=" + quote(filename, safe="")
path = f"/api/v1/chats/{chat['id']}/attachments" + (f"?{query}" if query else "")
if isinstance(data, (bytes, bytearray)):
return self.call("POST", path, expected, token=actor["token"], raw=bytes(data), headers=h,
schema="Attachment" if expected == 202 else None)
h["Authorization"] = "Bearer " + actor["token"]
response = self.client.post(path, content=data, headers=h)
assert response.status_code == expected, (response.status_code, response.text[:300])
return response
def attachment(self, actor: dict, attachment_id: str, expected=200) -> dict:
return self.call("GET", f"/api/v1/attachments/{attachment_id}", expected, token=actor["token"],
schema="Attachment" if expected == 200 else None).json()
def wait_status(self, actor: dict, attachment_id: str, *statuses: str, timeout: float = 60) -> dict:
"""Poll the metadata until the status is one of `statuses` (default: a final one)."""
wanted = statuses or ("ready", "failed")
deadline = time.monotonic() + timeout
while True:
att = self.attachment(actor, attachment_id)
if att["status"] in wanted:
return att
assert time.monotonic() < deadline, f"attachment stayed {att['status']}, wanted {wanted}"
time.sleep(0.3)
def content(self, actor: dict, attachment_id: str, variant: str | None = None, expected=200):
query = f"?variant={variant}" if variant else ""
return self.call("GET", f"/api/v1/attachments/{attachment_id}/content{query}", expected, token=actor["token"])
def history(self, actor: dict, chat: dict, limit: int) -> tuple[list[dict], int]:
"""Walk all pages; returns (items, number_of_pages)."""
items, pages, cursor = [], 0, None
while True:
query = f"?limit={limit}" + (f"&cursor={cursor}" if cursor else "")
page = self.call("GET", f"/api/v1/chats/{chat['id']}/messages{query}", 200,
token=actor["token"], schema="MessagePage").json()
pages += 1
items.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
return items, pages
assert len(page["items"]) == limit, "a non-final page must be full"
assert len(items) < 100_000, "cursor loop"
def _stand_is_up() -> bool:
try:
return httpx.get(BASE_URL + "/health/ready", timeout=3).status_code == 200
except httpx.HTTPError:
return False
def pytest_collection_modifyitems(config, items):
if any("stack" in item.keywords for item in items) and not _stand_is_up():
skip = pytest.mark.skip(reason=f"stand is not running at {BASE_URL}: docker compose up -d --wait")
for item in items:
if "stack" in item.keywords:
item.add_marker(skip)
@pytest.fixture(scope="session")
def api() -> Api:
return Api()
def run_hook(name: str, timeout: float = 180, **env: str) -> subprocess.CompletedProcess:
"""Run scripts/<name> (a POSIX sh hook); on Windows through Git Bash like the .cmd wrappers."""
script = str(ROOT / "scripts" / name)
if os.name == "nt":
command = [os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "Git", "bin", "bash.exe"), script]
else:
command = [script]
return subprocess.run(command, cwd=ROOT, capture_output=True, text=True, encoding="utf-8", check=True,
timeout=timeout, env={**os.environ, **env})
def s3_exec(body: str, bucket: str = "final", service: str = "worker", stdin: str | None = None) -> str:
"""Run `body` (async Python, `s` = messenger.storage.Storage of the final or the staging bucket)
INSIDE a container that holds S3 credentials: `worker` (Read+Write both buckets, no List) or
`auditor` (Read+List, no Write). The S3 port is not published on the host; this is how the
tests look into the buckets and inject faults."""
script = ("import asyncio, base64, json, sys\n"
"from messenger.config import Settings, s3_settings\n"
"from messenger.storage import Storage, ObjectMissing\n"
"async def main():\n"
" st = Settings(host='', port=0, env='lab', log_level='info', shutdown_timeout=0, max_body_bytes=1024, **s3_settings())\n"
f" s = Storage(st, bucket=st.s3_staging_bucket if {bucket == 'staging'} else None)\n"
" await s.open()\n"
" try:\n" + "".join(" " + line + "\n" for line in body.splitlines()) +
" finally:\n"
" await s.close()\n"
"asyncio.run(main())\n")
if service == "auditor":
cmd = ["run", "--rm", "--no-deps", "-T", "--entrypoint", "python", service, "-c", script]
else:
cmd = ["exec", "-T", service, "python", "-c", script]
return compose(*cmd, timeout=120, stdin=stdin).stdout.strip()
def s3_put(key: str, data: bytes, bucket: str = "final") -> None:
"""Write raw bytes under `key` (base64 over stdin: Windows limits command lines to 32 KiB)."""
s3_exec(f"await s.put({key!r}, base64.b64decode(sys.stdin.read()), 'image/png', {{}})", bucket,
stdin=base64.b64encode(data).decode())
def s3_delete(key: str, bucket: str = "final") -> None:
s3_exec(f"await s.delete({key!r})", bucket)
def s3_size(key: str, bucket: str = "final") -> int | None:
out = s3_exec(f"try:\n print((await s.head({key!r})).size)\nexcept ObjectMissing:\n print(-1)", bucket)
size = int(out.splitlines()[-1])
return None if size < 0 else size
def s3_keys(prefix: str, bucket: str = "final") -> set[str]:
"""Every object key under `prefix` (needs List: runs with the auditor's key pair)."""
out = s3_exec("keys, after = [], None\n"
"while True:\n"
f" page, more = await s.list_page({prefix!r}, after, 1000)\n"
" keys += [o.key for o in page]\n"
" if not more or not page:\n"
" break\n"
" after = page[-1].key\n"
"print(json.dumps(keys))", bucket, service="auditor")
return set(json.loads(out.splitlines()[-1]))
def jobctl(*args: str, expect_code: int = 0) -> dict:
"""Operator CLI (compose service jobctl, profile tools); returns its JSON output."""
result = compose("run", "--rm", "--no-deps", "-T", "jobctl", *args, check=False, timeout=120)
assert result.returncode == expect_code, (result.returncode, result.stdout[-1000:], result.stderr[-1000:])
return json.loads(result.stdout)
def audit(*args: str) -> dict:
"""Read-only invariant checker (compose service auditor); asserts that it found no violation."""
result = compose("run", "--rm", "--no-deps", "-T", "auditor", *args, check=False, timeout=300)
report = json.loads(result.stdout)
assert result.returncode == 0 and report["ok"], json.dumps(report.get("violations"), ensure_ascii=False)[:3000]
return report
def job_rows(attachment_id: str) -> list[dict]:
out = psql("SELECT coalesce(json_agg(json_build_object('id', id, 'state', state, 'attempt', attempt, 'kind', kind, "
"'pipeline_version', pipeline_version, 'error_code', error_code) ORDER BY created_at), '[]') "
"FROM jobs WHERE attachment_id = '%s'" % attachment_id)
return json.loads(out)
def events_of(attachment_id: str) -> list[dict]:
out = psql("SELECT coalesce(json_agg(json_build_object('event', e.event, 'attempt', e.attempt, 'actor', e.actor, "
"'error_code', e.error_code, 'detail', e.detail, 'at', e.at) ORDER BY e.id), '[]') "
"FROM job_events e JOIN jobs j ON j.id = e.job_id WHERE j.attachment_id = '%s'" % attachment_id)
return json.loads(out)
def queue_depth(queue: str = "messenger.attachment-jobs") -> int:
out = compose("exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "name", "messages").stdout
for line in out.splitlines():
name, _, count = line.partition("\t")
if name == queue:
return int(count)
raise AssertionError("queue not found: " + queue)
def attachment_row(attachment_id: str) -> dict | None:
out = psql("SELECT json_build_object('status', status, 'object_key', object_key, 'size', size_bytes, "
"'lost_reason', lost_reason, 'staging_key', staging_key, 'staging_state', staging_state, "
"'published_version', published_version, 'error_code', error_code) "
"FROM attachments WHERE id = '%s'" % attachment_id)
return json.loads(out) if out else None
def probe_inside(replica: dict, path: str) -> int:
"""HTTP status of `path` asked inside the replica container itself (bypassing the LB)."""
code = ("import urllib.request as u, urllib.error as e\n"
"try: print(u.urlopen('http://127.0.0.1:8080%s', timeout=3).status)\n"
"except e.HTTPError as x: print(x.code)") % path
out = subprocess.run(["docker", "exec", replica["id"], "python", "-c", code], capture_output=True, text=True,
timeout=30).stdout.strip()
return int(out or 0)
+117
View File
@@ -0,0 +1,117 @@
"""Synthetic images for the lab 4 tests: valid PNG/JPEG of any size, and the broken files the
reviewer used against other solutions (truncated, corrupted IDAT with a valid CRC, JPEG without
scan data, decompression-bomb headers, MIME spoofing). Nothing big is stored in Git: every file
is generated in memory."""
from __future__ import annotations
import io
import os
import struct
import zlib
from PIL import Image
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
def chunk(ctype: bytes, data: bytes) -> bytes:
return struct.pack(">I", len(data)) + ctype + data + struct.pack(">I", zlib.crc32(ctype + data))
def ihdr(width: int, height: int, depth: int = 8, color: int = 2, interlace: int = 0) -> bytes:
return chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, depth, color, 0, 0, interlace))
def png(width: int = 64, height: int = 48, mode: str = "RGB", noise: bool = False, **save) -> bytes:
if noise:
channels = len(mode)
image = Image.frombytes(mode, (width, height), os.urandom(width * height * channels))
else:
image = Image.new(mode, (width, height), (40, 120, 200) if mode == "RGB" else 128)
out = io.BytesIO()
image.save(out, "PNG", **save)
return out.getvalue()
def png_of_size(target: int) -> bytes:
"""A valid PNG of (about, at most) `target` bytes: random pixels do not compress."""
side = int((target / 3) ** 0.5)
data = png(side, side, noise=True, compress_level=1)
while len(data) > target:
side -= 8
data = png(side, side, noise=True, compress_level=1)
return data
def png_exactly(size: int) -> bytes:
"""A valid PNG of EXACTLY `size` bytes: noise image + an ancillary padding chunk."""
base = png_of_size(size - 64)
pad = size - len(base) - 12
assert pad >= 0
return base[:-12] + chunk(b"tEXt", b"pad\x00" + b"x" * (pad - 4)) + base[-12:]
def jpeg(width: int = 64, height: int = 48, progressive: bool = False, noise: bool = False, quality: int = 85) -> bytes:
if noise:
image = Image.frombytes("RGB", (width, height), os.urandom(width * height * 3))
else:
image = Image.new("RGB", (width, height), (200, 30, 30))
out = io.BytesIO()
image.save(out, "JPEG", progressive=progressive, quality=quality)
return out.getvalue()
# ------------------------------------------------------------------ broken files
def png_corrupt_idat() -> bytes:
"""Valid signature, IHDR and CRCs; the IDAT payload is 86 bytes of garbage (reviewer's case)."""
return PNG_SIGNATURE + ihdr(20, 20) + chunk(b"IDAT", bytes(range(86))) + chunk(b"IEND", b"")
def png_short_pixels() -> bytes:
"""A complete, CRC-correct PNG whose zlib stream holds fewer rows than the header promises."""
raw = b"".join(b"\x00" + bytes(60) for _ in range(19))
return PNG_SIGNATURE + ihdr(20, 20) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
def png_bomb_header(width: int = 20000, height: int = 10000) -> bytes:
"""Header of a huge picture: must be refused (413) from the first 33 bytes."""
raw_row = b"\x00" + bytes(width * 3)
body = zlib.compress(raw_row * 4, 9) # a few rows only: the decoder must never get that far
return PNG_SIGNATURE + ihdr(width, height) + chunk(b"IDAT", body) + chunk(b"IEND", b"")
def jpeg_without_scan_data() -> bytes:
data = jpeg(128, 96)
sos = data.index(b"\xff\xda")
length = struct.unpack(">H", data[sos + 2:sos + 4])[0]
return data[:sos + 2 + length] + b"\xff\xd9"
def jpeg_bomb_header() -> bytes:
"""SOF0 announcing 20000 x 20000 = 400 Mpx."""
return (b"\xff\xd8\xff\xc0\x00\x11\x08" + struct.pack(">HH", 20000, 20000)
+ b"\x03\x01\x22\x00\x02\x11\x01\x03\x11\x01" + b"\xff\xd9")
# ------------------------------------------------------------------ cases the reviewer used in lab 4/5 PRs
def png_bad_filter(filter_byte: int) -> bytes:
"""PNG 1x1 RGB, correct CRCs and zlib stream, but the row filter byte is not 0..4."""
raw = bytes([filter_byte]) + b"\x00\x00\x00"
return PNG_SIGNATURE + ihdr(1, 1) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
def png_idat_not_zlib() -> bytes:
"""Correct PNG structure, IDAT = b'not-a-zlib-stream' with a recomputed CRC."""
return PNG_SIGNATURE + ihdr(64, 64) + chunk(b"IDAT", b"not-a-zlib-stream") + chunk(b"IEND", b"")
# SOI, SOF0 1x1 grey, SOS, EOI: no tables, no scan data (27 bytes).
JPEG_27_BYTES = bytes.fromhex("ffd8ffc0000b080001000101011100ffda0008010100003f00ffd9")
def jpeg_sos_unknown_component() -> bytes:
"""A valid JPEG whose first SOS component id (byte sos+5) is 250, absent from SOF."""
data = bytearray(jpeg(64, 48))
sos = data.index(b"\xff\xda")
data[sos + 5] = 250
return bytes(data)
+344
View File
@@ -0,0 +1,344 @@
"""Contract behaviour over real HTTP (stand must be running). Lab 1 checks moved to Bearer + new lab 2 auth."""
from __future__ import annotations
import base64
import uuid
import pytest
from conftest import PASSWORD, basic
pytestmark = pytest.mark.stack
def key(item: dict) -> tuple[str, int]:
return item["created_at"], uuid.UUID(item["id"]).int
# ================================================================== registration & login
def test_register_never_returns_password_and_login_returns_bearer(api):
actor = api.register("alice", display_name="Алиса 👩‍💻")
assert set(actor["user"]) == {"id", "username", "display_name", "created_at"}
session = api.call("POST", "/api/v1/auth/sessions", 201,
headers={"Authorization": basic(actor["username"], PASSWORD)}, schema="Session").json()
assert session["token_type"] == "Bearer" and len(session["token"]) >= 43
assert actor["username"] not in session["token"] and actor["id"] not in session["token"]
assert api.call("GET", "/api/v1/users/me", 200, token=session["token"], schema="User").json() == actor["user"]
def test_duplicate_username_is_409(api):
actor = api.register("dup")
body = {"username": actor["username"], "display_name": "Другой", "password": PASSWORD}
assert api.call("POST", "/api/v1/users", 409, json_body=body).json()["error"]["code"] == "conflict"
@pytest.mark.parametrize("password", ["short-11ch", " " * 12, " \t \n " * 3, "я" * 129])
def test_bad_password_on_registration_is_400(api, password):
body = {"username": "pw_" + uuid.uuid4().hex[:10], "display_name": "x", "password": password}
api.call("POST", "/api/v1/users", 400, json_body=body)
@pytest.mark.parametrize("password", ["я" * 128, "with:colons:inside", "Twelve chars"])
def test_edge_passwords_register_and_login(api, password):
actor = api.user("edge", password=password)
api.call("GET", "/api/v1/users/me", 200, token=actor["token"])
def test_wrong_password_and_unknown_user_give_the_same_401(api):
actor = api.register("victim")
wrong = api.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic(actor["username"], "Wrong-password-1")})
unknown = api.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic("nobody_" + uuid.uuid4().hex[:8], PASSWORD)})
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
assert wrong.headers["www-authenticate"] == 'Basic realm="messenger", charset="UTF-8"'
@pytest.mark.parametrize("header", ["Basic é", "Basic !!!", "Basic " + base64.b64encode(b"no_colon").decode(),
"Basic " + base64.b64encode(b"\xff\xfe:x").decode(), "Bearer " + "a" * 43, ""])
def test_malformed_basic_is_401_not_500(api, header):
# Raw UTF-8 bytes, as curl would send them (httpx refuses non-ASCII str headers).
api.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": header.encode("utf-8")} if header else {})
def test_logout_revokes_only_this_token(api):
actor = api.user("logout")
second = api.login(actor)
api.call("DELETE", "/api/v1/auth/sessions/current", 204, token=actor["token"])
api.call("GET", "/api/v1/users/me", 401, token=actor["token"])
api.call("DELETE", "/api/v1/auth/sessions/current", 401, token=actor["token"])
api.call("GET", "/api/v1/users/me", 200, token=second) # other session of the same user survives
def test_x_user_id_basic_and_garbage_do_not_authenticate(api):
actor = api.user("hdr")
for headers in ({"X-User-Id": actor["id"]},
{"Authorization": basic(actor["username"], PASSWORD)},
{"Authorization": "Bearer " + "A" * 43},
{"Authorization": "Bearer"}):
api.call("GET", "/api/v1/users/me", 401, headers=headers)
me = api.call("GET", "/api/v1/users/me", 200, token=actor["token"], headers={"X-User-Id": str(uuid.uuid4())})
assert me.json()["id"] == actor["id"]
# ================================================================== validation / errors (from lab 1)
@pytest.mark.parametrize("raw", [b"{", b"", b"[]", b"null", b'{"username": "abc_def", "display_name": NaN, "password": "Twelve-chars"}',
b'{"username": "abc_def", "display_name": "x", "password": "Twelve-chars"}{"a": 1}',
b'{"username": "abc_def", "display_name": "\\ud800", "password": "Twelve-chars"}'])
def test_malformed_json_is_400(api, raw):
api.call("POST", "/api/v1/users", 400, raw=raw, headers={"Content-Type": "application/json"})
@pytest.mark.parametrize("body", [
{"username": "abc_def", "display_name": "x"}, # no password
{"username": "abc_def", "display_name": "x", "password": "Twelve-chars", "extra": 1},
{"username": "Abc_def", "display_name": "x", "password": "Twelve-chars"},
{"username": "abc_def", "display_name": " ", "password": "Twelve-chars"},
{"username": "abc_def", "display_name": "x" * 101, "password": "Twelve-chars"},
{"username": 5, "display_name": "x", "password": "Twelve-chars"},
])
def test_invalid_registration_fields_are_400(api, body):
api.call("POST", "/api/v1/users", 400, json_body=body)
def test_unicode_limits_are_code_points_and_nul_is_stored(api):
actor = api.user("uni", display_name="😀" * 100)
assert actor["user"]["display_name"] == "😀" * 100
nul = api.user("nul", display_name="A\u0000B")
assert api.call("GET", "/api/v1/users/me", 200, token=nul["token"]).json()["display_name"] == "A\u0000B"
chat = api.chat(actor, title="T\u0000itle")
assert chat["title"] == "T\u0000itle"
assert api.send(actor, chat, "hello\u0000world")["text"] == "hello\u0000world"
assert api.send(actor, chat, "🙂" * 4000)["text"] == "🙂" * 4000
api.post_message(actor, chat, {"text": "я" * 4001}, 400)
texts = [m["text"] for m in api.history(actor, chat, 100)[0]]
assert texts == ["hello\u0000world", "🙂" * 4000]
def test_oversized_body_and_wrong_content_type(api):
api.call("POST", "/api/v1/users", 413, json_body={"username": "big_body", "display_name": "x" * 70_000, "password": PASSWORD})
api.call("POST", "/api/v1/users", 400, raw=b'{"username":"abc_def"}', headers={"Content-Type": "text/plain"})
# ================================================================== chats & membership
def test_chat_validation(api):
alice, bob = api.user("alice"), api.user("bob")
for body in ({"title": "x", "member_ids": [alice["id"], bob["id"], bob["id"]]},
{"title": "x", "member_ids": [alice["id"], str(uuid.uuid4())]},
{"title": "x", "member_ids": [bob["id"]]},
{"title": " ", "member_ids": [alice["id"]]},
{"title": "x", "member_ids": [alice["id"], "bob"]}):
api.call("POST", "/api/v1/chats", 400, token=alice["token"], json_body=body)
def test_foreign_chat_is_indistinguishable_from_missing(api):
alice, bob, eve = api.user("alice"), api.user("bob"), api.user("eve")
chat = api.chat(alice, bob)
for chat_id in (chat["id"], str(uuid.uuid4())):
base = f"/api/v1/chats/{chat_id}"
errors = [api.call("GET", base, 404, token=eve["token"]).json(),
api.call("GET", base + "/messages", 404, token=eve["token"]).json(),
api.call("POST", base + "/messages", 404, token=eve["token"], json_body={"text": "чужое"}, headers={"Idempotency-Key": "k1"}).json(),
api.call("GET", base + "/messages?cursor=garbage", 404, token=eve["token"]).json()]
assert len({e["error"]["message"] for e in errors}) == 1
api.call("GET", "/api/v1/chats/not-a-uuid", 401)
api.call("GET", "/api/v1/chats/not-a-uuid", 400, token=alice["token"])
api.call("GET", "/api/v1/chats/NOT-A-UUID/messages", 400, token=alice["token"])
def test_chat_list_order_pagination_and_isolation(api):
alice, bob, eve = api.user("alice"), api.user("bob"), api.user("eve")
created = [api.chat(alice, bob, title=f"Чат {i}") for i in range(5)]
api.chat(eve, title="Чат Евы")
walked, cursor = [], None
while True:
query = "?limit=2" + (f"&cursor={cursor}" if cursor else "")
page = api.call("GET", "/api/v1/chats" + query, 200, token=bob["token"], schema="ChatPage").json()
walked += page["items"]
cursor = page["next_cursor"]
if not cursor:
break
assert walked == created
first = api.call("GET", "/api/v1/chats?limit=1", 200, token=alice["token"]).json()["next_cursor"]
api.call("GET", f"/api/v1/chats?limit=1&cursor={first}", 400, token=bob["token"]) # cursor of another user
api.call("GET", "/api/v1/chats?limit=0", 400, token=bob["token"])
# ================================================================== messages & keyset pagination
def test_history_pages_without_loss_or_duplicates(api):
alice, bob = api.user("alice"), api.user("bob")
chat = api.chat(alice, bob)
sent = [api.send(alice if i % 2 else bob, chat, f"сообщение {i}") for i in range(25)]
items, pages = api.history(bob, chat, 7)
assert pages == 4 and items == sent and items == sorted(items, key=key)
assert sent[0]["sender_id"] == bob["id"] and sent[1]["sender_id"] == alice["id"]
@pytest.mark.parametrize("query", ["limit=0", "limit=101", "limit=abc", "limit=1&limit=2", "cursor=", "cursor=garbage",
"cursor=djF8bXx4fDF8Mg", "cursor=" + base64.urlsafe_b64encode(b"v1|m|x|99999999999999999999|y").decode()])
def test_bad_limit_or_cursor_is_400(api, query):
alice = api.user("alice")
chat = api.chat(alice)
api.call("GET", f"/api/v1/chats/{chat['id']}/messages?{query}", 400, token=alice["token"])
def test_cursor_bound_to_chat(api):
alice = api.user("alice")
a, b = api.chat(alice, title="A"), api.chat(alice, title="B")
for chat in (a, b):
api.send(alice, chat, "1")
api.send(alice, chat, "2")
cursor = api.call("GET", f"/api/v1/chats/{a['id']}/messages?limit=1", 200, token=alice["token"]).json()["next_cursor"]
api.call("GET", f"/api/v1/chats/{b['id']}/messages?cursor={cursor}", 400, token=alice["token"])
empty = api.chat(alice, title="Empty")
api.call("GET", f"/api/v1/chats/{empty['id']}/messages?cursor=garbage", 400, token=alice["token"])
def test_read_after_write(api):
alice, bob = api.user("alice"), api.user("bob")
chat = api.chat(alice, bob)
for i in range(5):
message = api.send(alice, chat, f"m{i}")
last = api.call("GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", 200, token=bob["token"]).json()["items"][-1]
assert last == message
# ================================================================== lab 3: inputs found by the reviewer in other PRs
def b64(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
def bad_cursors(owner_id: str) -> list[str]:
"""Wrong types/values inside the cursor, empty and whitespace cursors, out-of-range time."""
good_uuid = str(uuid.uuid4())
return ["", " ", "%20", "garbage", b64(b"[]"), b64(b"{}"), b64(b"123"), b64(b"false"), b64(b"null"),
b64(b'{"created_at":1,"id":1}'), b64(b'{"created_at":null,"id":"x"}'),
b64(f"v1|m|{owner_id}|1|1".encode()), b64(f"v1|c|{owner_id}|1|1".encode()),
b64(f"v1|m|{owner_id}|abc|{good_uuid}".encode()), b64(f"v1|m|{owner_id}|-1|{good_uuid}".encode()),
b64(f"v1|m|{owner_id}|9223372036854775807|{good_uuid}".encode()),
b64(f"v1|c|{owner_id}|9223372036854775807|{good_uuid}".encode()),
b64(f"v1|m|{owner_id}|1|{good_uuid.upper()}".encode()), b64(f"v2|m|{owner_id}|1|{good_uuid}".encode())]
def test_malformed_cursor_values_are_400_on_both_lists(api):
alice = api.user("cur")
chat = api.chat(alice)
for cursor in bad_cursors(chat["id"]) + bad_cursors(alice["id"]):
quoted = cursor if cursor in ("", "%20") else cursor.replace(" ", "%20")
for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
error = api.call("GET", f"{path}?cursor={quoted}", 400, token=alice["token"]).json()
assert error["error"]["code"] == "invalid_request", (path, cursor)
@pytest.mark.parametrize("raw", [b"\xff", b'{"text":"first","TEXT":"second"}', b'{"text":"a","text":"b"}',
b'{"text":123}', b'{"text":"valid"}}', b'{"text":"valid"}]', b'{"text":"x"} {}',
b'{"text":"x","sender_id":"11111111-1111-4111-8111-111111111111"}',
b'{"text":"x","attachment_ids":null}', b'{"text":"x","attachment_ids":["nope"]}',
b'{"text":" \n\t "}'])
def test_bad_message_body_is_400_and_nothing_is_stored(api, raw):
alice = api.user("body")
chat = api.chat(alice)
error = api.post_message(alice, chat, None, 400, raw=raw).json()
assert error["error"]["code"] == "invalid_request"
assert api.history(alice, chat, 100)[0] == []
def test_ff_byte_body_on_registration_is_contract_error(api):
response = api.call("POST", "/api/v1/users", 400, raw=b"\xff", headers={"Content-Type": "application/json"})
assert response.json()["error"]["request_id"] == response.headers["x-request-id"]
def test_text_is_stored_verbatim_and_length_counts_raw_text(api):
alice = api.user("verbatim")
chat = api.chat(alice)
padded = " строка\nс пробелами "
assert api.send(alice, chat, padded)["text"] == padded
api.post_message(alice, chat, {"text": " " + "a" * 4000}, 400) # 4001 code points before any trimming
assert [m["text"] for m in api.history(alice, chat, 100)[0]] == [padded]
def test_unknown_attachment_ids_are_404(api):
alice = api.user("att")
chat = api.chat(alice)
api.post_message(alice, chat, {"text": "x", "attachment_ids": [str(uuid.uuid4())]}, 404)
api.post_message(alice, chat, {"text": "x", "attachment_ids": [str(uuid.uuid4())] * 2}, 400) # duplicates
assert api.history(alice, chat, 100)[0] == []
def test_member_ids_are_compared_as_uuids_not_strings(api):
alice, bob = api.user("case"), api.user("case")
api.call("POST", "/api/v1/chats", 400, token=alice["token"],
json_body={"title": "x", "member_ids": [alice["id"], alice["id"].upper()]})
api.call("POST", "/api/v1/chats", 400, token=alice["token"],
json_body={"title": "x", "member_ids": [alice["id"], bob["id"]], "id": str(uuid.uuid4())})
chat = api.call("POST", "/api/v1/chats", 201, token=alice["token"],
json_body={"title": "x", "member_ids": [alice["id"].upper(), bob["id"]]}, schema="Chat").json()
assert chat["member_ids"] == [alice["id"], bob["id"]]
@pytest.mark.parametrize("header", ["Bearer é", "Bearer .", "Bearer a b", "Bearer " + "é" * 43, "bearer\t" + "a" * 43])
def test_non_ascii_or_garbage_bearer_is_401_not_500(api, header):
api.call("GET", "/api/v1/users/me", 401, headers={"Authorization": header.encode("utf-8")})
def test_login_with_a_body_is_rejected(api):
actor = api.register("login_body")
auth = {"Authorization": basic(actor["username"], actor["password"])}
api.call("POST", "/api/v1/auth/sessions", 400, raw=b'{"extra":1}', headers={**auth, "Content-Type": "application/json"})
api.call("POST", "/api/v1/auth/sessions", 400, raw=b"x", headers=auth)
api.call("POST", "/api/v1/auth/sessions", 201, headers=auth, schema="Session")
def test_password_range_is_12_to_128_code_points(api):
api.call("POST", "/api/v1/users", 400, json_body={"username": "pw_" + uuid.uuid4().hex[:10], "display_name": "x", "password": "a"})
actor = api.user("pw128", password="я:" * 64)
api.call("GET", "/api/v1/users/me", 200, token=actor["token"])
def test_every_api_response_carries_instance_and_request_id(api):
"""X-Instance-Id also on 404 of unknown routes, 405, 401, 400 and health (Api.call asserts it)."""
api.call("GET", "/health/live", 200)
api.call("GET", "/health/ready", 200)
api.call("GET", "/no/such/route", 404)
api.call("PUT", "/api/v1/users", 405)
api.call("GET", "/api/v1/users/me", 401)
response = api.call("GET", "/api/v1/users/me", 401, headers={"X-Request-Id": "client-supplied.id-1"})
assert response.headers["x-request-id"] == "client-supplied.id-1" # one id from LB log to API log
@pytest.mark.parametrize("blank", [" ", "  ", "  \t "])
def test_unicode_whitespace_only_strings_are_400(api, blank):
alice = api.user("blank")
chat = api.chat(alice)
api.call("POST", "/api/v1/users", 400, json_body={"username": "bl_" + uuid.uuid4().hex[:10], "display_name": blank,
"password": PASSWORD})
api.call("POST", "/api/v1/chats", 400, token=alice["token"], json_body={"title": blank, "member_ids": [alice["id"]]})
api.post_message(alice, chat, {"text": blank}, 400)
assert api.history(alice, chat, 100)[0] == []
@pytest.mark.parametrize("raw", [b'{"username":"num_probe","display_name":"x","password":1e1000}',
'{"username":"ff_probe","display_name":"x","password":"12345678901'.encode() + b'\xff"}',
b'{"username":"num_probe","display_name":1,"password":"Twelve-chars-ok"}'])
def test_odd_registration_bodies_are_400_and_the_api_survives(api, raw):
api.call("POST", "/api/v1/users", 400, raw=raw, headers={"Content-Type": "application/json"})
api.call("GET", "/health/ready", 200)
def test_more_than_100_members_is_400(api):
owner = api.user("big")
others = [api.register(f"m{i}")["id"] for i in range(100)]
api.call("POST", "/api/v1/chats", 400, token=owner["token"], json_body={"title": "x", "member_ids": [owner["id"], *others]})
chat = api.call("POST", "/api/v1/chats", 201, token=owner["token"],
json_body={"title": "x", "member_ids": [owner["id"], *others[:99]]}, schema="Chat").json()
assert len(chat["member_ids"]) == 100
def test_cursor_of_one_list_is_rejected_by_the_other(api):
alice = api.user("cross")
chats = [api.chat(alice, title=f"c{i}") for i in range(2)]
for _ in range(2):
api.send(alice, chats[0], "m")
message_cursor = api.call("GET", f"/api/v1/chats/{chats[0]['id']}/messages?limit=1", 200,
token=alice["token"]).json()["next_cursor"]
chat_cursor = api.call("GET", "/api/v1/chats?limit=1", 200, token=alice["token"]).json()["next_cursor"]
api.call("GET", f"/api/v1/chats?cursor={message_cursor}", 400, token=alice["token"])
api.call("GET", f"/api/v1/chats/{chats[0]['id']}/messages?cursor={chat_cursor}", 400, token=alice["token"])
+291
View File
@@ -0,0 +1,291 @@
"""Attachments through the load balancer (lab 4, levels 3 and 4; lab 5: upload is 202 queued and
the worker publishes the original + variants): upload/download, ACL, limits, content checks,
filename rules and messages with attachment_ids.
Negative inputs include every case the reviewer used against other lab 4 solutions: corrupted
IDAT with valid CRCs, the first 33 bytes of the fixture, JPEG without scan data, a 20000x10000
header (DecompressionBomb), exactly 10 MiB through the LB, C1 control U+0085 and a whitespace
filename, text=null / missing text / attachment_ids=null in a message; and the lab 4/5 review
cases: PNG row filter 5 and 0xff, IDAT that is not a zlib stream, the 27-byte JPEG without tables
and scan data, a JPEG whose SOS names a component missing from SOF - all 415 AT UPLOAD, never
202 followed by failed/invalid_image."""
from __future__ import annotations
import hashlib
import subprocess
import time
import uuid
from pathlib import Path
import pytest
import imagegen
from conftest import attachment_row, compose, s3_size
pytestmark = pytest.mark.stack
ROOT = Path(__file__).resolve().parents[1]
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
MiB = 1024 * 1024
@pytest.fixture()
def trio(api):
"""alice + bob share a chat; eve is an outsider with her own chat."""
alice, bob, eve = api.user("alice"), api.user("bob"), api.user("eve")
return alice, bob, eve, api.chat(alice, bob), api.chat(eve)
def content(api, actor, attachment_id, expected=200, query=""):
return api.call("GET", f"/api/v1/attachments/{attachment_id}/content{query}", expected, token=actor["token"])
# ------------------------------------------------------------------ positive path
def test_png_and_jpeg_roundtrip_byte_for_byte(api, trio):
alice, bob, _, chat, _ = trio
jpg = imagegen.jpeg(321, 123, noise=True)
for data, ctype in ((SAMPLE, "image/png"), (jpg, "image/jpeg")):
att = api.upload(alice, chat, data, content_type=ctype, filename="кот 😺.bin").json()
assert att["status"] == "queued" and att["variants"] == [] and att["error_code"] is None
assert att["chat_id"] == chat["id"] and att["owner_id"] == alice["id"]
assert att["size_bytes"] == len(data) and att["sha256"] == hashlib.sha256(data).hexdigest()
assert att["content_type"] == ctype and att["filename"] == "кот 😺.bin"
meta = api.wait_status(bob, att["id"], "ready")
assert {k: v for k, v in meta.items() if k not in ("status", "variants", "updated_at")} == \
{k: v for k, v in att.items() if k not in ("status", "variants", "updated_at")}
assert [v["name"] for v in meta["variants"]] == ["thumbnail", "crop", "optimized"]
got = content(api, bob, att["id"])
assert got.content == data and got.headers["content-type"] == ctype
assert got.headers["content-length"] == str(len(data))
assert got.headers["x-content-type-options"] == "nosniff"
assert got.headers["content-disposition"].startswith("attachment;")
assert "location" not in got.headers # bytes through the API, never a redirect to S3
def test_metadata_reveals_no_storage_details(api, trio):
alice, _, _, chat, _ = trio
att = api.upload(alice, chat, SAMPLE).json()
api.wait_status(alice, att["id"], "ready")
row = attachment_row(att["id"])
assert row["status"] == "ready" and row["object_key"].startswith(f"a/{att['id']}/")
assert row["staging_key"].startswith("s/")
text = api.call("GET", f"/api/v1/attachments/{att['id']}", 200, token=alice["token"]).text
for secret in (row["object_key"], row["staging_key"], "messenger-attachments", "messenger-staging", "a/", "s3"):
assert secret not in text.lower(), secret
# The staging key is random: neither the id nor the filename is part of it.
assert att["id"].replace("-", "") not in row["staging_key"] and "photo" not in row["staging_key"]
assert s3_size(row["object_key"]) == len(SAMPLE) # the published original IS in the final bucket
def test_original_is_not_stored_on_api_containers(api, trio):
"""The API keeps no file of the original: no recently written file of that size anywhere in
the replica's filesystem (the bytes live only in the bucket)."""
alice, _, _, chat, _ = trio
data = imagegen.png_of_size(300_000)
api.upload(alice, chat, data)
size = len(data)
for cid in compose("ps", "-q", "api").stdout.split():
out = subprocess.run(
["docker", "exec", cid, "sh", "-c", f"find / -xdev -type f -size {size}c -mmin -10 2>/dev/null | head"],
capture_output=True, text=True, timeout=60).stdout.strip()
assert out == "", out
# ------------------------------------------------------------------ access control
def test_outsider_and_unknown_get_404(api, trio):
alice, _, eve, chat, _ = trio
att = api.upload(alice, chat, SAMPLE).json()
for suffix in ("", "/content"):
api.call("GET", f"/api/v1/attachments/{att['id']}{suffix}", 404, token=eve["token"])
api.call("GET", f"/api/v1/attachments/{uuid.uuid4()}{suffix}", 404, token=alice["token"])
api.call("GET", f"/api/v1/attachments/not-a-uuid{suffix}", 400, token=alice["token"])
api.call("GET", f"/api/v1/attachments/{att['id']}{suffix}", 401)
# Upload into a foreign chat: 404 before anything about the body is looked at.
api.upload(eve, chat, SAMPLE, 404)
api.upload(eve, chat, b"garbage", 404, content_type="text/plain")
def test_attachment_ids_are_checked_per_chat(api, trio):
alice, bob, eve, chat, eve_chat = trio
other = api.chat(alice) # alice's second chat
att_other = api.upload(alice, other, SAMPLE).json()
att_eve = api.upload(eve, eve_chat, SAMPLE).json()
# Alice is a member of both chats, but a file is bound to its chat.
api.post_message(alice, chat, {"text": "x", "attachment_ids": [att_other["id"]]}, 404)
api.post_message(alice, chat, {"text": "x", "attachment_ids": [att_eve["id"]]}, 404)
api.post_message(alice, chat, {"text": "x", "attachment_ids": [str(uuid.uuid4())]}, 404)
# Eve cannot post into alice's chat even with her own file: membership first.
api.post_message(eve, chat, {"text": "x", "attachment_ids": [att_eve["id"]]}, 404)
# Any member may reference an attachment of the chat.
att = api.upload(alice, chat, SAMPLE).json()
msg = api.post_message(bob, chat, {"text": "", "attachment_ids": [att["id"]]}).json()
assert msg["attachment_ids"] == [att["id"]] and msg["sender_id"] == bob["id"]
# ------------------------------------------------------------------ messages with attachments
def test_message_with_attachments_and_history(api, trio):
alice, bob, _, chat, _ = trio
a1, a2 = (api.upload(alice, chat, SAMPLE).json()["id"] for _ in range(2))
m1 = api.post_message(alice, chat, {"text": "", "attachment_ids": [a2, a1]}).json()
m2 = api.post_message(alice, chat, {"text": " ", "attachment_ids": [a1]}).json() # blank text + file: ok
m3 = api.post_message(alice, chat, {"text": "без файлов"}).json()
assert m1["attachment_ids"] == [a2, a1] and m1["text"] == ""
assert m2["text"] == " " and m3["attachment_ids"] == []
items, _ = api.history(bob, chat, 2)
assert [m["attachment_ids"] for m in items] == [[a2, a1], [a1], []]
def test_idempotent_replay_with_attachments(api, trio):
alice, _, _, chat, _ = trio
a1, a2 = (api.upload(alice, chat, SAMPLE).json()["id"] for _ in range(2))
key = uuid.uuid4().hex
first = api.post_message(alice, chat, {"text": "файлы", "attachment_ids": [a1, a2]}, key=key).json()
raw = ('{"attachment_ids":["%s","%s"],"text":"файлы"}' % (a1, a2)).encode()
assert api.post_message(alice, chat, None, raw=raw, key=key).json() == first # key order irrelevant
api.post_message(alice, chat, {"text": "файлы", "attachment_ids": [a2, a1]}, 409, key=key) # other body
api.post_message(alice, chat, {"text": "файлы"}, 409, key=key)
# A failed attachment check does not burn the key: the same key works with a valid body later.
key2 = uuid.uuid4().hex
api.post_message(alice, chat, {"text": "x", "attachment_ids": [str(uuid.uuid4())]}, 404, key=key2)
api.post_message(alice, chat, {"text": "x", "attachment_ids": [a1]}, key=key2)
@pytest.mark.parametrize("raw", [
b'{"attachment_ids":["%(a)s"]}', # text missing
b'{"text":null,"attachment_ids":["%(a)s"]}', # text null
b'{"text":1,"attachment_ids":["%(a)s"]}',
b'{"text":"x","attachment_ids":null}', # attachment_ids null
b'{"text":"x","attachment_ids":"%(a)s"}',
b'{"text":"x","attachment_ids":{}}',
b'{"text":"x","attachment_ids":["%(a)s","%(a)s"]}', # duplicates
b'{"text":"x","attachment_ids":["%(a)s",1]}',
b'{"text":"x","attachment_ids":["not-a-uuid"]}',
b'{"text":"","attachment_ids":[]}', # neither text nor files
b'{"text":" "}',
b'{"text":"x","attachment_ids":[],"sender_id":"%(a)s"}',
], ids=lambda raw: raw.decode()[:40])
def test_message_body_validation(api, trio, raw):
alice, _, _, chat, _ = trio
a = api.upload(alice, chat, SAMPLE).json()["id"]
api.post_message(alice, chat, None, 400, raw=raw % {b"a": a.encode()})
def test_at_most_ten_attachments(api, trio):
alice, _, _, chat, _ = trio
ids = [api.upload(alice, chat, imagegen.png(4, 4)).json()["id"] for _ in range(11)]
assert len(api.post_message(alice, chat, {"text": "", "attachment_ids": ids[:10]}).json()["attachment_ids"]) == 10
api.post_message(alice, chat, {"text": "", "attachment_ids": ids}, 400)
# ------------------------------------------------------------------ limits
def test_size_limit_through_the_load_balancer(api, trio):
alice, bob, _, chat, _ = trio
exact = imagegen.png_exactly(10 * MiB)
assert len(exact) == 10 * MiB
att = api.upload(alice, chat, exact).json() # exactly the limit: accepted via LB
api.wait_status(bob, att["id"], "ready")
assert content(api, bob, att["id"]).content == exact
started = time.monotonic()
api.upload(alice, chat, exact + b"\x00", 413) # Content-Length over the limit
assert time.monotonic() - started < 5
over = exact + bytes(1024)
def chunks(): # no Content-Length: chunked body
for i in range(0, len(over), 256 * 1024):
yield over[i:i + 256 * 1024]
error = api.upload(alice, chat, chunks(), 413).json()
assert error["error"]["code"] == "payload_too_large"
def test_pixel_limit_before_decoding(api, trio):
alice, _, _, chat, _ = trio
for data, ctype in ((imagegen.png_bomb_header(), "image/png"), (imagegen.jpeg_bomb_header(), "image/jpeg"),
(imagegen.PNG_SIGNATURE + imagegen.ihdr(8001, 5000), "image/png")):
started = time.monotonic()
assert api.upload(alice, chat, data, 413, content_type=ctype).json()["error"]["code"] == "payload_too_large"
assert time.monotonic() - started < 2 # refused from the header, nothing decoded
def test_exactly_40_megapixels_is_accepted(api, trio):
alice, _, _, chat, _ = trio
data = imagegen.png(8000, 5000, compress_level=9) # 40 000 000 px, ~120 KB file
att = api.upload(alice, chat, data).json()
assert att["size_bytes"] == len(data)
# Lab 5: the worker processes the biggest allowed picture within its memory limit.
ready = api.wait_status(alice, att["id"], "ready", timeout=120)
assert {v["name"]: (v["width"], v["height"]) for v in ready["variants"]} == \
{"thumbnail": (256, 160), "crop": (128, 128), "optimized": (1280, 800)}
# ------------------------------------------------------------------ content checks
BROKEN = {
"png: first 33 bytes of the fixture": (SAMPLE[:33], "image/png"),
"png: truncated": (SAMPLE[:-20], "image/png"),
"png: corrupt IDAT, valid CRC": (imagegen.png_corrupt_idat(), "image/png"),
"png: fewer rows than IHDR": (imagegen.png_short_pixels(), "image/png"),
"png: flipped byte": (SAMPLE[:700] + bytes([SAMPLE[700] ^ 0x5A]) + SAMPLE[701:], "image/png"),
"png: bytes after IEND": (SAMPLE + b"<?php echo 1; ?>", "image/png"),
"jpeg: no scan data after SOS": (imagegen.jpeg_without_scan_data(), "image/jpeg"),
"jpeg: truncated": (imagegen.jpeg(400, 300, noise=True)[:5000], "image/jpeg"),
"review: png row filter 5": (imagegen.png_bad_filter(5), "image/png"),
"review: png row filter 0xff": (imagegen.png_bad_filter(0xFF), "image/png"),
"review: png IDAT not-a-zlib-stream": (imagegen.png_idat_not_zlib(), "image/png"),
"review: jpeg 27 bytes, no tables/scan": (imagegen.JPEG_27_BYTES, "image/jpeg"),
"review: jpeg SOS component not in SOF": (imagegen.jpeg_sos_unknown_component(), "image/jpeg"),
"mime: png bytes declared jpeg": (SAMPLE, "image/jpeg"),
"mime: jpeg bytes declared png": (imagegen.jpeg(), "image/png"),
"mime: gif declared png": (b"GIF89a" + bytes(100), "image/png"),
"mime: html declared png": (b"<html><script>alert(1)</script></html>", "image/png"),
"type: text/plain": (SAMPLE, "text/plain"),
"type: octet-stream": (SAMPLE, "application/octet-stream"),
"type: multipart": (SAMPLE, "multipart/form-data; boundary=x"),
"type: missing": (SAMPLE, None),
}
@pytest.mark.parametrize("name", list(BROKEN))
def test_bad_content_is_415(api, trio, name):
alice, _, _, chat, _ = trio
data, ctype = BROKEN[name]
error = api.upload(alice, chat, data, 415, content_type=ctype).json()
assert error["error"]["code"] == "unsupported_media_type"
def test_empty_body_is_400(api, trio):
alice, _, _, chat, _ = trio
api.upload(alice, chat, b"", 400)
# ------------------------------------------------------------------ filename
@pytest.mark.parametrize("query", [
"", "filename=", "filename=%20%20%20", "filename=.", "filename=..", "filename=a%2Fb.png", "filename=a%5Cb.png",
"filename=a%00b.png", "filename=c1%C2%85.png", "filename=tab%09.png", "filename=photo%E2%80%AEgnp.exe",
"filename=%FF%FE.png", "filename=a.png&filename=b.png", "filename=" + "a" * 256,
], ids=lambda q: q[:40] or "missing")
def test_bad_filename_is_400(api, trio, query):
alice, _, _, chat, _ = trio
api.upload(alice, chat, SAMPLE, 400, query=query)
def test_unicode_filename_is_kept_and_safely_exposed(api, trio):
alice, _, _, chat, _ = trio
name = 'отчёт "Q3"; ok.png'
att = api.upload(alice, chat, SAMPLE, filename=name).json()
assert att["filename"] == name
api.wait_status(alice, att["id"], "ready")
disposition = content(api, alice, att["id"]).headers["content-disposition"]
assert '"' not in disposition.split('filename="')[1].split('";')[0] # quotes neutralised in the fallback
assert "filename*=UTF-8''" in disposition
# ------------------------------------------------------------------ variants
def test_variant_parameter(api, trio):
alice, _, eve, chat, _ = trio
att = api.upload(alice, chat, SAMPLE).json()
api.wait_status(alice, att["id"], "ready")
assert content(api, alice, att["id"], query="?variant=original").content == SAMPLE
assert content(api, alice, att["id"], query="?variant=thumbnail").headers["content-type"] == "image/jpeg"
content(api, alice, att["id"], 400, query="?variant=huge")
content(api, alice, att["id"], 400, query="?variant=thumbnail&variant=crop")
content(api, eve, att["id"], 404, query="?variant=thumbnail") # outsider: 404, nothing revealed
content(api, eve, att["id"], 404, query="?variant=huge") # outsider first, then the value
+354
View File
@@ -0,0 +1,354 @@
"""Load balancer, replicas and graceful shutdown (lab 3, levels 3 and 4).
Each test that stops, kills, rescales or isolates a replica restores the stand in `finally`
and waits until HAProxy reports every replica UP again (conftest.wait_stand).
"""
from __future__ import annotations
import contextlib
import json
import subprocess
import threading
import time
import uuid
import httpx2 as httpx
import pytest
from conftest import BASE_URL, REPLICAS, Api, compose, lbctl, probe_inside, psql, replica_stopped, run_hook, \
running_replicas, wait_healthy, wait_stand
pytestmark = pytest.mark.stack
def instances_seen(api: Api, token: str, requests: int = 40) -> list[str]:
return [api.call("GET", "/api/v1/users/me", 200, token=token).headers["x-instance-id"] for _ in range(requests)]
# ------------------------------------------------------------------ level 3: replicas, no affinity
def test_one_session_is_served_by_every_real_replica(api):
actor = api.user("rr")
seen = instances_seen(api, actor["token"])
running = {r["hostname"] for r in running_replicas()}
assert len(running) == REPLICAS >= 2
assert set(seen) == running, "X-Instance-Id values must be exactly the hostnames of the running containers"
# Round robin on ONE keep-alive client connection: consecutive requests switch replicas,
# so there is no sticky session hiding split state.
switches = sum(1 for a, b in zip(seen, seen[1:]) if a != b)
assert switches >= len(seen) // 2, seen
assert {s["instance_id"] for s in lbctl.lb_servers() if s["state"] == "UP"} == running
def test_write_on_one_replica_is_read_on_the_other(api):
alice, bob = api.user("rw"), api.user("rw")
chat = api.chat(alice, bob)
for i in range(10):
sent = api.post_message(alice, chat, {"text": f"m{i}"})
read = api.call("GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", 200, token=bob["token"])
assert read.json()["items"][-1] == sent.json()
logout = api.call("DELETE", "/api/v1/auth/sessions/current", 204, token=alice["token"])
for _ in range(6): # the revocation is visible on every replica at once (shared Valkey)
r = api.call("GET", "/api/v1/users/me", 401, token=alice["token"])
assert r.headers["x-instance-id"]
assert logout.headers["x-instance-id"]
# ------------------------------------------------------------------ readiness drives the LB
def hba_file() -> str:
return psql("SHOW hba_file")
@contextlib.contextmanager
def isolated_from_postgres(replica: dict):
"""Make ONE replica unable to reach PostgreSQL (pg_hba reject for its IP + terminate its
connections), while it keeps running and answering /health/live. Always undone."""
ip = replica["networks"]["data"] # PostgreSQL sees the replica's address on the data network
path = hba_file()
marker = "lab3-test-isolate"
compose("exec", "-T", "postgres", "sh", "-c", f"sed -i '1i host all all {ip}/32 reject # {marker}' {path}")
try:
psql("SELECT pg_reload_conf()")
psql(f"SELECT count(pg_terminate_backend(pid)) FROM pg_stat_activity WHERE client_addr = '{ip}'")
yield replica
finally:
compose("exec", "-T", "postgres", "sh", "-c", f"sed -i '/{marker}/d' {path}")
psql("SELECT pg_reload_conf()")
lbctl.wait_up(REPLICAS, timeout=15) # self-heals: no restart of the replica needed
wait_stand()
@contextlib.contextmanager
def disconnected_from_data_network(replica: dict):
"""`docker network disconnect <project>_data <api>`: the replica keeps its edge link to the
LB but loses PostgreSQL AND Valkey. Always reconnected."""
network = next(n for n in json.loads(subprocess.run(
["docker", "inspect", "-f", "{{json .NetworkSettings.Networks}}", replica["id"]],
capture_output=True, text=True, check=True).stdout) if n.endswith("_data"))
subprocess.run(["docker", "network", "disconnect", network, replica["id"]], check=True, capture_output=True)
try:
yield
finally:
subprocess.run(["docker", "network", "connect", network, replica["id"]], check=True, capture_output=True)
lbctl.wait_up(REPLICAS, timeout=15) # self-heals: dead sockets are dropped (tcp_user_timeout)
wait_stand()
@pytest.mark.parametrize("how", ["pg_hba", "network"])
@pytest.mark.parametrize("position", range(REPLICAS))
def test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready(api, position, how):
"""The reviewers' scenarios: one API loses PostgreSQL (pg_hba reject) or its whole data
network (docker network disconnect) but keeps running. /health/live 200, /health/ready
503 -> HAProxy must take it out; no business request may reach it."""
replica = sorted(running_replicas(), key=lambda r: r["name"])[position]
actor = api.user("ready")
isolate = isolated_from_postgres if how == "pg_hba" else disconnected_from_data_network
with isolate(replica):
started = time.monotonic()
while replica["hostname"] in lbctl.up_instances():
assert time.monotonic() - started < 5, "HAProxy did not mark the unready replica DOWN within 5 s"
time.sleep(0.1)
detected = time.monotonic() - started
for _ in range(3): # the process stays responsive (event loop never blocked) ...
started_probe = time.monotonic()
assert probe_inside(replica, "/health/live") == 200
assert probe_inside(replica, "/health/ready") == 503 # ... but not ready
assert time.monotonic() - started_probe < 4.5, "replica froze while its dependencies were unreachable"
seen = instances_seen(api, actor["token"], 40)
assert replica["hostname"] not in seen and len(seen) == 40
for i in range(20): # writes keep working, only through the ready replicas
assert api.register(f"r{i}")["id"]
print(f"{replica['name']} ({how}): unready replica out of rotation after {detected:.2f} s")
# ------------------------------------------------------------------ stopping replicas under traffic
class Traffic:
"""Background writers/readers through the LB; uncertain POSTs are retried with the SAME key."""
def __init__(self, api: Api, workers: int = 4):
self.alice, self.bob = api.user("load"), api.user("load")
self.chat = api.chat(self.alice, self.bob)
self.workers = workers
self.stop = threading.Event()
self.lock = threading.Lock()
self.events: list[tuple[float, str, int, str | None]] = [] # (time, kind, status, instance)
self.confirmed: list[dict] = []
self.threads = [threading.Thread(target=self.run, args=(i,), daemon=True) for i in range(workers)]
def record(self, kind: str, status: int, instance: str | None) -> None:
with self.lock:
self.events.append((time.monotonic(), kind, status, instance))
def run(self, index: int) -> None:
client = httpx.Client(base_url=BASE_URL, timeout=3)
auth = {"Authorization": "Bearer " + self.alice["token"]}
n = 0
key, text = uuid.uuid4().hex, f"w{index}-0"
while not self.stop.is_set():
try:
r = client.post(f"/api/v1/chats/{self.chat['id']}/messages", json={"text": text},
headers={**auth, "Idempotency-Key": key})
self.record("POST", r.status_code, r.headers.get("x-instance-id"))
if r.status_code == 201:
with self.lock:
self.confirmed.append(r.json())
n += 1
key, text = uuid.uuid4().hex, f"w{index}-{n}"
# any other outcome: keep key and text, retry the same request
except httpx.HTTPError:
self.record("POST", 0, None)
try:
r = client.get(f"/api/v1/chats/{self.chat['id']}/messages?limit=5", headers=auth)
self.record("GET", r.status_code, r.headers.get("x-instance-id"))
except httpx.HTTPError:
self.record("GET", 0, None)
time.sleep(0.02)
client.close()
def __enter__(self) -> "Traffic":
for t in self.threads:
t.start()
time.sleep(1.0)
return self
def __exit__(self, *exc) -> None:
self.stop.set()
for t in self.threads:
t.join(timeout=10)
def failures(self, since: float = 0.0) -> list[tuple]:
return [e for e in self.events if e[0] >= since and e[2] not in (200, 201)]
def check_history(self, api: Api) -> None:
history = api.history(self.bob, self.chat, 100)[0]
ids, texts = [m["id"] for m in history], [m["text"] for m in history]
assert len(ids) == len(set(ids)) and len(texts) == len(set(texts)), "duplicate after retry"
assert {m["id"] for m in self.confirmed} <= set(ids), "a confirmed message was lost"
@pytest.mark.parametrize("position", range(REPLICAS))
def test_graceful_stop_of_each_replica_loses_no_request(api, position):
"""SIGTERM -> readiness 503 -> HAProxy DOWN -> drain -> exit 0: not one failed request."""
replica = sorted(running_replicas(), key=lambda r: r["name"])[position]
with Traffic(api) as traffic:
started = time.monotonic()
with replica_stopped(replica, "stop"):
stopped_after = time.monotonic() - started
time.sleep(3)
after = [e for e in traffic.events if e[0] > time.monotonic() - 2]
assert after and replica["hostname"] not in {e[3] for e in after}
time.sleep(1)
state = json.loads(subprocess.run(["docker", "inspect", replica["id"]], capture_output=True, text=True,
check=True).stdout)[0]["State"]
assert traffic.failures() == [], traffic.failures()[:10]
assert stopped_after < 15, "graceful stop must finish before stop_grace_period (no SIGKILL)"
assert state["Status"] == "running" # restored by replica_stopped
traffic.check_history(api)
print(f"{replica['name']}: stop took {stopped_after:.1f} s, {len(traffic.events)} requests, 0 failed")
@pytest.mark.parametrize("position", range(REPLICAS))
def test_killed_replica_bounded_errors_recovery_and_no_duplicates(api, position):
"""SIGKILL: requests in flight on that replica may fail (counted), new ones succeed within
10 s, the killed replica gets nothing after detection, retries do not duplicate."""
replica = sorted(running_replicas(), key=lambda r: r["name"])[position]
with Traffic(api) as traffic:
killed_at = time.monotonic()
with replica_stopped(replica, "kill"):
time.sleep(4)
failures = traffic.failures(killed_at)
last_failure = max((e[0] for e in failures), default=killed_at) - killed_at
post_ok = [e for e in traffic.events if e[0] > killed_at and e[1] == "POST" and e[2] == 201]
assert post_ok and post_ok[0][0] - killed_at <= 10, "writes did not recover within 10 s"
late = [e for e in traffic.events if e[0] > killed_at + 3.5]
assert late and replica["hostname"] not in {e[3] for e in late}
assert last_failure <= 10
traffic.check_history(api)
print(f"{replica['name']}: killed; {len(failures)} failed of {len(traffic.events)}, last failure +{last_failure:.2f} s")
def test_graceful_shutdown_order_in_logs(api):
"""Logs prove the order: drain_started -> (HAProxy marks DOWN) -> shutdown_requested -> exit 0."""
replica = sorted(running_replicas(), key=lambda r: r["name"])[-1]
since = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - 1))
with replica_stopped(replica, "stop"):
logs = subprocess.run(["docker", "logs", "--since", since, replica["id"]], capture_output=True,
text=True, encoding="utf-8").stdout
lb_logs = compose("logs", "--no-log-prefix", "--since", since, "lb").stdout
state = json.loads(subprocess.run(["docker", "inspect", replica["id"]], capture_output=True, text=True,
check=True).stdout)[0]["State"]
events = [json.loads(line) for line in logs.splitlines() if line.startswith("{")]
names = [e["event"] for e in events]
assert names.index("drain_started") < names.index("shutdown_requested") < names.index("stopped")
t = {e["event"]: e["ts"] for e in events}
assert t["drain_started"] < t["shutdown_requested"]
assert state["ExitCode"] == 0 and not state["OOMKilled"]
assert "is DOWN" in lb_logs and ("503" in lb_logs or "Connection refused" in lb_logs)
# ------------------------------------------------------------------ discovery: restart and scaling
def test_full_restart_lb_rediscovers_all_replicas(api):
actor = api.user("restart")
before = {r["hostname"]: r["started_at"] for r in running_replicas()}
run_hook("restart.sh")
wait_healthy("postgres", "valkey", "api")
wait_stand()
after = {r["hostname"]: r["started_at"] for r in running_replicas()}
assert set(after) == set(before) and all(after[h] != before[h] for h in after), "every replica restarted"
assert set(instances_seen(api, actor["token"])) == set(after) # same token, both replicas, no LB restart needed
def test_scale_up_and_down_is_picked_up_without_errors(api):
with Traffic(api, workers=2) as traffic:
try:
compose("up", "-d", "--no-deps", "--no-recreate", "--wait", "--scale", f"api={REPLICAS + 1}", "api",
timeout=180)
lbctl.wait_up(REPLICAS + 1, timeout=30)
actor = api.user("scale")
assert len(set(instances_seen(api, actor["token"], 30))) == REPLICAS + 1
finally:
compose("up", "-d", "--no-deps", "--no-recreate", "--wait", "--scale", f"api={REPLICAS}", "api",
timeout=180)
wait_stand()
time.sleep(1)
assert traffic.failures() == [], traffic.failures()[:10]
traffic.check_history(api)
# ------------------------------------------------------------------ level 4: deployment policy
def test_compose_policy_limits_ports_secrets_images():
config = json.loads(compose("config", "--format", "json").stdout)
services = config["services"]
# auditor and jobctl (profile "tools") are started on demand and not part of the running stand.
assert set(services) == {"postgres", "valkey", "s3", "broker", "migrate", "s3-init", "api", "lb", "relay", "worker",
# lab 6: observability
"otel-collector", "prometheus", "loki", "tempo", "grafana"}
for name, svc in services.items():
limits = svc.get("deploy", {}).get("resources", {}).get("limits", {})
assert limits.get("cpus") and limits.get("memory"), f"{name}: CPU/RAM limits"
assert "container_name" not in svc, f"{name}: container_name prevents scaling"
if name in ("api", "migrate"):
assert "build" in svc # built from this repository's source
elif name in ("s3-init", "relay", "worker"):
assert svc["image"] == services["api"]["image"] # the same locally built image
else:
assert "@sha256:" in svc["image"], f"{name}: image must be pinned by digest"
assert services["api"]["deploy"]["replicas"] >= 2 and not services["api"].get("ports")
published = {name: svc.get("ports", []) for name, svc in services.items() if svc.get("ports")}
# Published: the LB and (lab 6) the Grafana UI - both on loopback only. No OTLP/store/admin port.
assert set(published) == {"lb", "grafana"}
assert all(p["host_ip"] in ("127.0.0.1", "::1") for ports in published.values() for p in ports)
assert [p["target"] for p in published["grafana"]] == [3000, 3000]
secrets = {name: sorted(s["source"] for s in svc.get("secrets", [])) for name, svc in services.items()}
s3_keys = sorted(f"s3_{who}_{part}" for who in ("admin", "api", "worker", "auditor")
for part in ("access_key_id", "secret_access_key"))
assert secrets == {"postgres": ["postgres_password"], "valkey": ["valkey_password"], "s3": s3_keys,
"migrate": ["database_url"], "s3-init": s3_keys, "lb": [],
"broker": ["rabbitmq_users"],
# the API: its own S3 key pair only (no admin/worker keys, no broker credentials)
"api": ["cache_url", "database_url", "s3_api_access_key_id", "s3_api_secret_access_key"],
# relay: database + its broker user only; worker: + its own S3 key pair
"relay": ["broker_url_relay", "database_url"],
"worker": ["broker_url_worker", "database_url", "s3_worker_access_key_id",
"s3_worker_secret_access_key"],
# lab 6: the telemetry services get no application secret at all
"otel-collector": [], "prometheus": [], "loki": [], "tempo": [],
"grafana": ["grafana_admin_password"]}
volumes = {name: [v["source"] for v in svc.get("volumes", []) if v["type"] == "volume"]
for name, svc in services.items()}
assert volumes == {"postgres": ["pgdata"], "valkey": ["valkeydata"], "s3": ["s3data"], "migrate": [],
"s3-init": [], "api": [], "lb": [], "broker": ["rabbitmqdata"], "relay": [], "worker": [],
"otel-collector": [], "prometheus": ["promdata"], "loki": ["lokidata"], "tempo": ["tempodata"],
"grafana": ["grafanadata"]}
networks = {name: sorted(svc.get("networks", {})) for name, svc in services.items()}
assert networks == {"postgres": ["data"], "valkey": ["data"], "s3": ["storage"], "migrate": ["data"],
"s3-init": ["storage"], "api": ["data", "edge", "storage", "telemetry"], "broker": ["queue"],
"relay": ["data", "queue", "telemetry"], "worker": ["data", "queue", "storage", "telemetry"],
"lb": ["edge"], "otel-collector": ["telemetry"], "prometheus": ["telemetry"],
"loki": ["telemetry"], "tempo": ["telemetry"], "grafana": ["telemetry", "ui"]}, networks
# the LB cannot reach the stores; the API not the broker; telemetry stores cannot reach the app stores
for network in ("data", "storage", "queue", "telemetry"):
assert config["networks"][network].get("internal") is True, network
def test_running_containers_have_limits_and_no_bypass_ports():
ids = compose("ps", "-q").stdout.split()
for item in json.loads(subprocess.run(["docker", "inspect", *ids], capture_output=True, text=True,
check=True).stdout):
name = item["Name"]
assert item["HostConfig"]["NanoCpus"] > 0 and item["HostConfig"]["Memory"] > 0, name
bindings = item["HostConfig"]["PortBindings"] or {}
if "-lb-" in name or "-grafana-" in name:
assert all(b["HostIp"] in ("127.0.0.1", "::1") for v in bindings.values() for b in v) # loopback only
else:
assert not bindings, f"{name} publishes ports in bypass of the LB"
def test_migrations_ran_once_by_the_migrate_service():
applied = psql("SELECT version FROM schema_migrations ORDER BY version").split()
assert applied == ["0001_init", "0002_idempotency_keys", "0003_post_message_function", "0004_attachments",
"0005_pipeline", "0006_observability"]
migrate = compose("ps", "-a", "--format", "json", "migrate").stdout
rows = [json.loads(line) for line in migrate.splitlines() if line.strip()]
assert rows and all(r["State"] == "exited" and r["ExitCode"] == 0 for r in rows)
api_logs = compose("logs", "--no-log-prefix", "api").stdout
assert "migrate:" not in api_logs and "schema_migrations" not in api_logs # replicas never migrate
+125
View File
@@ -0,0 +1,125 @@
"""Consistency of PostgreSQL and S3 around one upload (lab 4 level 4, lab 5 failure windows of the API).
Lab 5 upload: intent row 'pending' -> staging PUT -> ONE transaction 'queued' + job + outbox -> 202.
Failures between the steps are injected with FAULT_POINTS of the api service (compose variable
API_FAULT_POINTS, empty in normal runs; the API raises 503 at that exact point, as if the process
or the network failed there):
* after_s3_put "after staging, before the job is written": staging object exists, row
still pending, NO job and NO outbox row; the client got 503 -> invisible,
the janitor removes the staging object and the row after PENDING_GRACE_SECONDS;
* after_enqueue_commit job committed, the answer is lost (client got 503) -> nothing may be
deleted: the worker processes the job and the attachment becomes ready.
Plus: an upload interrupted by the client and a stalled body leave nothing behind."""
from __future__ import annotations
import socket
import time
from pathlib import Path
import pytest
import imagegen
from conftest import api_with_env, attachment_row, psql, s3_size
pytestmark = pytest.mark.stack
ROOT = Path(__file__).resolve().parents[1]
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
def rows_of_chat(chat_id: str) -> list[tuple[str, str, str]]:
out = psql(f"SELECT id || ' ' || status || ' ' || staging_key FROM attachments WHERE chat_id = '{chat_id}'")
return [tuple(line.split()) for line in out.splitlines() if line]
def jobs_of(attachment_id: str) -> tuple[int, int]:
"""(jobs rows, outbox rows) of an attachment."""
out = psql(f"SELECT (SELECT count(*) FROM jobs WHERE attachment_id = '{attachment_id}') || ' ' || "
f"(SELECT count(*) FROM outbox o JOIN jobs j ON j.id = o.job_id WHERE j.attachment_id = '{attachment_id}')")
jobs, outbox = out.split()
return int(jobs), int(outbox)
def wait_for(condition, timeout: float, what: str) -> None:
deadline = time.monotonic() + timeout
while not condition():
assert time.monotonic() < deadline, what
time.sleep(0.5)
def raw_upload(token: str, chat_id: str, declared: int, body: bytes, *, wait_answer: float | None) -> bytes:
"""Hand-made HTTP request: announce `declared` bytes, send only `body`, then either close the
socket (client gone) or keep it open and read the answer after `wait_answer` seconds."""
sock = socket.create_connection(("127.0.0.1", 8080), timeout=30)
head = (f"POST /api/v1/chats/{chat_id}/attachments?filename=x.png HTTP/1.1\r\nHost: localhost\r\n"
f"Authorization: Bearer {token}\r\nContent-Type: image/png\r\nContent-Length: {declared}\r\n\r\n")
sock.sendall(head.encode() + body)
if wait_answer is None:
sock.close()
return b""
time.sleep(wait_answer)
answer = sock.recv(65536)
sock.close()
return answer
def test_interrupted_and_stalled_uploads_leave_nothing(api):
alice = api.user("alice")
chat = api.chat(alice)
data = imagegen.png_of_size(2_000_000)
raw_upload(alice["token"], chat["id"], len(data), data[:300_000], wait_answer=None) # client disconnects
with api_with_env(UPLOAD_READ_TIMEOUT_SECONDS="2"):
answer = raw_upload(alice["token"], chat["id"], len(data), data[:300_000], wait_answer=5) # client stalls
assert answer.startswith(b"HTTP/1.1 400") and b"invalid_request" in answer, answer[:200]
assert b"x-instance-id" in answer.lower()
time.sleep(1)
assert rows_of_chat(chat["id"]) == [] # nothing was written: the body is checked before any write
def test_crash_after_staging_before_job_is_cleaned_by_janitor(api):
"""Failure window 1 of contracts/attachment-states.md: the original is in staging, the job is
not written. No 202 was sent, so nothing was promised: the janitor removes the staging copy
(object first) and then the intent row; no job, no message ever existed."""
alice = api.user("alice")
chat = api.chat(alice)
with api_with_env(API_FAULT_POINTS="after_s3_put", PENDING_GRACE_SECONDS="3", JANITOR_INTERVAL_SECONDS="1"):
assert api.upload(alice, chat, SAMPLE, 503).json()["error"]["code"] == "unavailable"
[(attachment_id, status, key)] = rows_of_chat(chat["id"])
assert status == "pending" and s3_size(key, "staging") == len(SAMPLE) # the orphan-to-be exists
assert jobs_of(attachment_id) == (0, 0) # no job, no outbox row
api.call("GET", f"/api/v1/attachments/{attachment_id}", 404, token=alice["token"]) # invisible
api.post_message(alice, chat, {"text": "", "attachment_ids": [attachment_id]}, 404) # not attachable
wait_for(lambda: rows_of_chat(chat["id"]) == [], 30, "janitor did not remove the stale intent")
assert s3_size(key, "staging") is None # object removed first
# Normal configuration again: an upload in the same chat works and is not touched.
att = api.upload(alice, chat, SAMPLE).json()
assert api.wait_status(alice, att["id"], "ready")["status"] == "ready"
def test_lost_answer_after_job_commit_still_becomes_ready(api):
"""The job COMMIT succeeded, the answer was lost (503). Nothing compensates in the request path
(the janitor only touches 'pending' rows); the worker processes the job as usual."""
alice, bob = api.user("alice"), api.user("bob")
chat = api.chat(alice, bob)
with api_with_env(API_FAULT_POINTS="after_enqueue_commit", PENDING_GRACE_SECONDS="3", JANITOR_INTERVAL_SECONDS="1"):
api.upload(alice, chat, SAMPLE, 503)
[(attachment_id, status, key)] = rows_of_chat(chat["id"])
assert status in ("queued", "processing", "ready") and jobs_of(attachment_id)[0] == 1
att = api.wait_status(bob, attachment_id, "ready")
time.sleep(4) # several janitor rounds
assert attachment_row(attachment_id)["status"] == "ready"
got = api.call("GET", f"/api/v1/attachments/{attachment_id}/content", 200, token=bob["token"])
assert got.content == SAMPLE and att["sha256"] == __import__("hashlib").sha256(SAMPLE).hexdigest()
def test_fresh_pending_upload_is_not_touched_by_janitor(api):
"""An intent younger than PENDING_GRACE_SECONDS is an upload in progress: never removed."""
alice = api.user("alice")
chat = api.chat(alice)
with api_with_env(API_FAULT_POINTS="after_s3_put", PENDING_GRACE_SECONDS="600", JANITOR_INTERVAL_SECONDS="1"):
api.upload(alice, chat, SAMPLE, 503)
time.sleep(4)
[(_, status, key)] = rows_of_chat(chat["id"])
assert status == "pending" and s3_size(key, "staging") == len(SAMPLE)
+119
View File
@@ -0,0 +1,119 @@
"""Database-level guarantees, checked over HTTP and verified directly in PostgreSQL / Valkey."""
from __future__ import annotations
import threading
import time
import uuid
import pytest
from conftest import PASSWORD, Api, compose, psql
pytestmark = pytest.mark.stack
def run_concurrently(workers: int, target) -> list:
barrier = threading.Barrier(workers)
results: list = [None] * workers
def body(index: int) -> None:
local = Api() # one HTTP client (connection) per worker
barrier.wait() # all workers fire at the same moment
try:
results[index] = target(local, index)
except BaseException as exc: # noqa: BLE001 - reported by the test
results[index] = exc
threads = [threading.Thread(target=body, args=(i,)) for i in range(workers)]
for t in threads:
t.start()
for t in threads:
t.join()
return results
def test_registration_race_exactly_one_201_and_seven_409():
username = "race_" + uuid.uuid4().hex[:10]
def register(client: Api, _index: int) -> int:
body = {"username": username, "display_name": "Гонка", "password": PASSWORD}
response = client.client.post("/api/v1/users", json=body)
return response.status_code
statuses = run_concurrently(8, register)
# Real HTTP codes are compared: a timeout, 500 or exception fails the test instead of counting as 409.
assert sorted(statuses, key=str) == [201] + [409] * 7, statuses
assert psql(f"SELECT count(*) FROM users WHERE username = '{username}'") == "1"
def _ins_counter() -> int:
return int(psql("SELECT n_tup_ins FROM pg_stat_user_tables WHERE relname = 'chats'"))
def test_create_chat_rolls_back_after_the_chat_row_was_inserted(api):
"""The chat INSERT runs first; the unknown member then breaks the membership INSERT (FK).
Proof that the first INSERT really happened and was rolled back: PostgreSQL counts
attempted inserts in pg_stat_user_tables.n_tup_ins even for aborted transactions,
while the table contains no such chat and no new membership rows.
"""
alice = api.user("rollback")
title = "rollback-" + uuid.uuid4().hex
members_before = int(psql("SELECT count(*) FROM chat_members"))
attempts_before = _ins_counter()
error = api.call("POST", "/api/v1/chats", 400, token=alice["token"],
json_body={"title": title, "member_ids": [alice["id"], str(uuid.uuid4())]}).json()
assert "несуществующих" in error["error"]["message"]
deadline = time.monotonic() + 20 # statistics are flushed by the API backend asynchronously
while _ins_counter() == attempts_before and time.monotonic() < deadline:
time.sleep(0.5)
assert _ins_counter() > attempts_before, "the chat INSERT was never attempted"
assert psql(f"SELECT count(*) FROM chats WHERE title = convert_to('{title}', 'UTF8')") == "0"
assert int(psql("SELECT count(*) FROM chat_members")) == members_before
def test_migrations_rerun_is_a_noop():
users_before = psql("SELECT count(*) FROM users")
result = compose("run", "--rm", "--no-deps", "migrate")
assert "0001_init: already applied, skipped" in result.stdout
assert "0002_idempotency_keys: already applied, skipped" in result.stdout
assert "0003_post_message_function: already applied, skipped" in result.stdout
assert "0004_attachments: already applied, skipped" in result.stdout
assert "0005_pipeline: already applied, skipped" in result.stdout
assert "0006_observability: already applied, skipped" in result.stdout
assert psql("SELECT count(*) FROM schema_migrations") == "6"
assert psql("SELECT count(*) FROM users") == users_before
def test_100_messages_from_10_clients_keep_order_and_cursor_walk(api):
clients = [api.user(f"w{i}") for i in range(10)]
chat = api.chat(clients[0], *clients[1:])
def writer(client: Api, index: int) -> list[dict]:
return [client.send(clients[index], chat, f"c{index}-m{j}") for j in range(10)]
results = run_concurrently(10, writer)
assert all(isinstance(r, list) for r in results), results
confirmed = [m for batch in results for m in batch]
history, pages = api.history(clients[5], chat, 7)
ids = [m["id"] for m in history]
assert len(confirmed) == 100 and len(history) == 100 and len(set(ids)) == 100 and pages == 15
assert set(ids) == {m["id"] for m in confirmed}
keys = [(m["created_at"], uuid.UUID(m["id"]).int) for m in history]
assert all(a < b for a, b in zip(keys, keys[1:])), "history is not strictly ordered"
stamps = [m["created_at"] for m in history]
assert len(set(stamps)) == 100, "per-chat clock must give unique timestamps"
for i, client in enumerate(clients):
own = [m["text"] for m in history if m["sender_id"] == client["id"]]
assert own == [f"c{i}-m{j}" for j in range(10)]
def test_secrets_are_not_stored_in_plain_text(api):
actor = api.user("store")
stored = psql(f"SELECT password_hash FROM users WHERE id = '{actor['id']}'")
assert stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$") and PASSWORD not in stored
token_hex = actor["token"].encode().hex()
keys = compose("exec", "-T", "valkey", "sh", "-c",
'REDISCLI_AUTH="$(cat /run/secrets/valkey_password)" valkey-cli --scan --pattern "session:*"').stdout.split()
assert keys and all(len(k) == len("session:") + 64 for k in keys)
assert not any(actor["token"] in k or token_hex in k for k in keys)
+35
View File
@@ -0,0 +1,35 @@
"""The history index really bounds the work of a late page (>= 10 000 messages, generic plan)."""
from __future__ import annotations
import re
import sys
import pytest
from conftest import ROOT
pytestmark = pytest.mark.stack
sys.path.insert(0, str(ROOT / "scripts"))
import explain_history # noqa: E402
def section(text: str, number: int) -> str:
parts = re.split(r"^=== ", text, flags=re.M)
return next(p for p in parts if p.startswith(f"{number}."))
def buffers(plan: str) -> int:
return int(re.search(r"Buffers: shared hit=(\d+)", plan).group(1))
def test_late_page_uses_index_range_not_filter():
text = explain_history.run()
assert "20000" in text # the target chat holds 20 000 messages
app_late = section(text, 2)
assert "Index Cond: ((chat_id = $1) AND (ROW(created_at, id) > ROW($2, $3)))" in app_late
assert "Rows Removed by Filter" not in app_late and "Sort" not in app_late
rejected = section(text, 3)
assert "Rows Removed by Filter: 19950" in rejected
# The app query touches a handful of pages; the rejected variants touch the whole prefix.
assert buffers(app_late) <= 10 < buffers(rejected) and buffers(app_late) <= 10 < buffers(section(text, 4))
+111
View File
@@ -0,0 +1,111 @@
"""Dependency failures with a VALID session: bounded 503, never anonymous access, recovery afterwards.
Every test stops/pauses a real container and restores it in `finally` (service_down).
Timing bounds: DB_TIMEOUT_SECONDS=3 (client deadline), CACHE_TIMEOUT_SECONDS=0.5.
Lab 3: requests go through HAProxy. While the outage is being detected the replicas answer
503 themselves; once every replica fails /health/ready, HAProxy answers 503 in the same
contract format (without X-Instance-Id). Both are "unavailable"; never 200 and never 401
for a valid token. Liveness/readiness of the processes are checked inside each container.
"""
from __future__ import annotations
import subprocess
import time
import pytest
from conftest import ROOT, probe_inside, restart_services, running_replicas, service_down
pytestmark = pytest.mark.stack
DB_BOUND = 3.6 # DB_TIMEOUT_SECONDS + network/HTTP overhead
CACHE_BOUND = 1.6 # 2 x CACHE_TIMEOUT_SECONDS + overhead
def timed(api, *args, **kwargs):
started = time.monotonic()
response = api.call(*args, lb_error_ok=True, **kwargs)
return response, time.monotonic() - started
def processes_alive_but_not_ready() -> None:
for replica in running_replicas():
assert probe_inside(replica, "/health/live") == 200
assert probe_inside(replica, "/health/ready") == 503
@pytest.fixture
def prepared(api):
alice, bob = api.user("alice"), api.user("bob")
chat = api.chat(alice, bob)
message = api.send(alice, chat, "до отказа")
return alice, bob, chat, message
def check_intact(api, alice, bob, chat, message):
"""After recovery the SAME tokens work and confirmed data is unchanged."""
assert api.call("GET", "/api/v1/users/me", 200, token=alice["token"]).json() == alice["user"]
items = api.call("GET", f"/api/v1/chats/{chat['id']}/messages", 200, token=bob["token"]).json()["items"]
assert items == [message]
@pytest.mark.parametrize("how", ["stop", "pause"])
def test_valkey_failure(api, prepared, how):
alice, bob, chat, message = prepared
with service_down("valkey", how):
response, took = timed(api, "GET", "/api/v1/users/me", 503, token=alice["token"])
assert response.json()["error"]["code"] == "unavailable" and took < CACHE_BOUND, took
api.call("GET", f"/api/v1/chats/{chat['id']}/messages", 503, token=bob["token"])
api.call("GET", "/api/v1/users/me", (401, 503), lb_error_ok=True) # anonymous never gets access
api.call("GET", "/health/ready", 503, lb_error_ok=True)
processes_alive_but_not_ready()
check_intact(api, alice, bob, chat, message)
@pytest.mark.parametrize("how", ["stop", "pause"])
def test_postgres_failure(api, prepared, how):
alice, bob, chat, message = prepared
with service_down("postgres", how):
for path in ("/api/v1/users/me", f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
response, took = timed(api, "GET", path, 503, token=alice["token"])
assert response.json()["error"]["code"] == "unavailable", path
assert took < DB_BOUND, (path, took) # bounded even when PostgreSQL is frozen (pause)
api.call("GET", "/api/v1/users/me", (401, 503), lb_error_ok=True) # anonymous never gets access
api.call("GET", "/health/ready", 503, lb_error_ok=True)
processes_alive_but_not_ready()
check_intact(api, alice, bob, chat, message)
def test_locked_table_gives_bounded_503(api, prepared):
"""A statement stuck behind a lock is stopped by lock_timeout, not after minutes."""
alice, bob, chat, message = prepared
locker = subprocess.Popen(
["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-c",
"BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(6); COMMIT;"],
cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
time.sleep(1.5) # let the lock be taken
response, took = timed(api, "GET", f"/api/v1/chats/{chat['id']}/messages", 503, token=bob["token"])
assert response.json()["error"]["code"] == "unavailable" and took < DB_BOUND, took
assert response.headers.get("x-instance-id"), "a lock is the API's own 503, the replicas stay ready"
finally:
locker.wait(timeout=30)
check_intact(api, alice, bob, chat, message)
def test_logout_during_valkey_outage_is_never_lost(api, prepared):
"""Valkey is the single source of truth for sessions, so a logout cannot be 'forgotten':
during the outage logout answers 503 (nothing revoked, the client knows it failed);
after recovery logout works, and the revocation survives a Valkey and API restart (AOF)."""
alice, bob, chat, message = prepared
with service_down("valkey", "stop"):
api.call("DELETE", "/api/v1/auth/sessions/current", 503, token=alice["token"], lb_error_ok=True)
api.call("GET", "/api/v1/users/me", 200, token=alice["token"]) # logout did not happen
api.call("DELETE", "/api/v1/auth/sessions/current", 204, token=alice["token"])
api.call("GET", "/api/v1/users/me", 401, token=alice["token"])
restart_services("valkey", "api")
for _ in range(10): # repeated checks: the revoked token must never come back
api.call("GET", "/api/v1/users/me", 401, token=alice["token"])
api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 401, token=alice["token"], json_body={"text": "x"})
api.call("GET", "/api/v1/users/me", 200, token=bob["token"]) # other sessions survived the restart
+281
View File
@@ -0,0 +1,281 @@
"""Shared idempotency of POST /chats/{id}/messages (lab 3), through the load balancer.
Strict assertions: exact HTTP codes for every request, identical bodies for replays,
the number of rows in PostgreSQL (messages AND idempotency_keys), and which replica
answered (X-Instance-Id). Fault injection (trigger, row lock, stopped replica) is always
undone in `finally`.
"""
from __future__ import annotations
import subprocess
import threading
import time
import uuid
import httpx2 as httpx
import pytest
from conftest import BASE_URL, ROOT, Api, psql, replica_stopped, running_replicas
pytestmark = pytest.mark.stack
def messages_in_db(chat: dict) -> int:
return int(psql(f"SELECT count(*) FROM messages WHERE chat_id = '{chat['id']}'"))
def key_rows(actor: dict, key: str) -> int:
return int(psql(f"SELECT count(*) FROM idempotency_keys WHERE user_id = '{actor['id']}' AND key = '{key}'"))
@pytest.fixture
def pair(api):
alice, bob = api.user("alice"), api.user("bob")
return alice, bob, api.chat(alice, bob)
def test_replay_returns_the_same_201_and_message_from_every_replica(api, pair):
alice, bob, chat = pair
key = "replay-" + uuid.uuid4().hex
first = api.post_message(alice, chat, {"text": "один раз"}, key=key)
served = {first.headers["x-instance-id"]}
for _ in range(20):
again = api.post_message(alice, chat, {"text": "один раз"}, key=key)
assert again.status_code == 201 and again.json() == first.json()
served.add(again.headers["x-instance-id"])
assert len(served) >= 2, "replays must be answered by different replicas, not a local cache"
assert api.history(bob, chat, 100)[0] == [first.json()]
assert messages_in_db(chat) == 1 and key_rows(alice, key) == 1
def test_other_body_with_the_same_key_is_409_and_keeps_the_original(api, pair):
alice, bob, chat = pair
key = uuid.uuid4().hex
original = api.send(alice, chat, "оригинал", key=key)
for body in ({"text": "другой текст"}, {"text": "оригинал "}, {"text": "Оригинал"}):
assert api.post_message(alice, chat, body, 409, key=key).json()["error"]["code"] == "conflict"
assert api.send(alice, chat, "оригинал", key=key) == original
assert api.history(bob, chat, 100)[0] == [original] and key_rows(alice, key) == 1
def test_key_order_and_missing_attachment_ids_are_the_same_body(api, pair):
alice, _, chat = pair
key = uuid.uuid4().hex
first = api.post_message(alice, chat, None, raw='{"text":"порядок"}'.encode(), key=key).json()
for raw in ('{"attachment_ids":[],"text":"порядок"}', '{"text":"порядок","attachment_ids":[]}',
'{ "text" : "\\u043f\\u043e\\u0440\\u044f\\u0434\\u043e\\u043a" }'):
assert api.post_message(alice, chat, None, raw=raw.encode(), key=key).json() == first
assert messages_in_db(chat) == 1
@pytest.mark.parametrize("value", ["", "a" * 129, "ключ", "a b", "a/b", "a,b", "a\tb", "*"])
def test_missing_or_invalid_key_is_400(api, pair, value):
alice, _, chat = pair
raw_value = value.encode("utf-8")
error = api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, token=alice["token"],
json_body={"text": "x"}, headers={"Idempotency-Key": raw_value} if value else {}).json()
assert error["error"]["code"] == "invalid_request"
assert messages_in_db(chat) == 0
def test_repeated_key_header_is_400(pair):
alice, _, chat = pair
response = httpx.post(BASE_URL + f"/api/v1/chats/{chat['id']}/messages", json={"text": "x"}, timeout=10,
headers=[("Authorization", "Bearer " + alice["token"]),
("Idempotency-Key", "one"), ("Idempotency-Key", "two")])
assert response.status_code == 400 and response.headers["x-instance-id"]
assert messages_in_db(chat) == 0
def test_longest_key_and_every_allowed_character(api, pair):
alice, _, chat = pair
for key in ("k" * 128, "A-Za-z0-9._:-" + uuid.uuid4().hex):
first = api.send(alice, chat, key[:20], key=key)
assert api.send(alice, chat, key[:20], key=key) == first
assert messages_in_db(chat) == 2
def test_scope_is_user_plus_chat_plus_key(api, pair):
alice, bob, chat = pair
other = api.chat(alice, bob, title="второй")
key = "shared-key"
a1 = api.send(alice, chat, "текст", key=key)
b1 = api.send(bob, chat, "текст", key=key) # another user: independent
a2 = api.send(alice, other, "текст", key=key) # another chat: independent
assert len({a1["id"], b1["id"], a2["id"]}) == 3
assert messages_in_db(chat) == 2 and messages_in_db(other) == 1
def test_outsider_and_revoked_session_never_see_the_stored_result(api, pair):
alice, bob, chat = pair
eve = api.user("eve")
key = uuid.uuid4().hex
api.send(alice, chat, "секрет", key=key)
for _ in range(3): # a replay checks access again: always 404, never 409 or the stored message
assert api.post_message(eve, chat, {"text": "секрет"}, 404, key=key).json()["error"]["code"] == "not_found"
api.post_message(eve, chat, {"text": "другое"}, 404, key=key)
api.call("DELETE", "/api/v1/auth/sessions/current", 204, token=alice["token"])
api.post_message(alice, chat, {"text": "секрет"}, 401, key=key) # session checked again
assert messages_in_db(chat) == 1
def fire_together(workers: int, request) -> list:
barrier = threading.Barrier(workers)
results: list = [None] * workers
def body(index: int) -> None:
client = httpx.Client(base_url=BASE_URL, timeout=15) # own connection -> LB spreads them
barrier.wait()
try:
results[index] = request(client, index)
except BaseException as exc: # noqa: BLE001 - asserted by the test
results[index] = exc
finally:
client.close()
threads = [threading.Thread(target=body, args=(i,)) for i in range(workers)]
for t in threads:
t.start()
for t in threads:
t.join()
return results
def test_concurrent_same_key_through_different_replicas_creates_exactly_one(pair):
alice, bob, chat = pair
key = "race-" + uuid.uuid4().hex
def post(client: httpx.Client, _index: int):
r = client.post(f"/api/v1/chats/{chat['id']}/messages", json={"text": "гонка"},
headers={"Authorization": "Bearer " + alice["token"], "Idempotency-Key": key})
return r.status_code, r.headers.get("x-instance-id"), r.json()
for _ in range(3): # three rounds: the first creates, later rounds replay concurrently
results = fire_together(24, post)
assert all(isinstance(r, tuple) for r in results), results
assert [r[0] for r in results] == [201] * 24, [r[0] for r in results]
assert len({str(r[2]) for r in results}) == 1, "every concurrent replay must return the same Message"
assert len({r[1] for r in results}) >= 2, "requests did not reach two replicas"
assert messages_in_db(chat) == 1 and key_rows(alice, key) == 1
def test_concurrent_same_key_different_bodies_one_wins(pair):
alice, _, chat = pair
key = "conflict-" + uuid.uuid4().hex
def post(client: httpx.Client, index: int):
r = client.post(f"/api/v1/chats/{chat['id']}/messages", json={"text": f"вариант {index % 2}"},
headers={"Authorization": "Bearer " + alice["token"], "Idempotency-Key": key})
return r.status_code, r.json()
results = fire_together(20, post)
winners = [body for status, body in results if status == 201]
losers = [body for status, body in results if status == 409]
assert len(winners) + len(losers) == 20, results
assert winners and len({str(b) for b in winners}) == 1
assert all(b["error"]["code"] == "conflict" for b in losers)
assert {b["text"] for b in winners} <= {"вариант 0", "вариант 1"}
assert len(losers) == sum(1 for i in range(20) if f"вариант {i % 2}" != winners[0]["text"])
assert messages_in_db(chat) == 1
def inserts_into_keys() -> int:
return int(psql("SELECT n_tup_ins FROM pg_stat_user_tables WHERE relname = 'idempotency_keys'"))
def test_failure_after_the_key_insert_rolls_everything_back(api, pair):
"""A trigger makes the MESSAGE insert fail AFTER the key row was inserted in the same
transaction. Expected: 500 for the client, no key row and no message left behind
(n_tup_ins proves the key INSERT really ran), and a retry with the same key succeeds."""
alice, bob, chat = pair
marker = "boom-" + uuid.uuid4().hex
key = uuid.uuid4().hex
psql("CREATE OR REPLACE FUNCTION lab3_test_fail() RETURNS trigger LANGUAGE plpgsql AS $$ "
f"BEGIN IF NEW.text = convert_to('{marker}', 'UTF8') THEN RAISE EXCEPTION 'injected failure'; END IF; "
"RETURN NEW; END $$; "
"CREATE TRIGGER lab3_test_fail BEFORE INSERT ON messages FOR EACH ROW EXECUTE FUNCTION lab3_test_fail()")
try:
before = inserts_into_keys()
error = api.post_message(alice, chat, {"text": marker}, 500, key=key)
assert error.json()["error"]["code"] == "internal_error" and "injected" not in error.text
assert key_rows(alice, key) == 0 and messages_in_db(chat) == 0
deadline = time.monotonic() + 20 # table statistics are flushed asynchronously
while inserts_into_keys() == before and time.monotonic() < deadline:
time.sleep(0.5)
assert inserts_into_keys() > before, "the key INSERT never ran before the failure"
finally:
psql("DROP TRIGGER IF EXISTS lab3_test_fail ON messages; DROP FUNCTION IF EXISTS lab3_test_fail()")
retried = api.send(alice, chat, marker, key=key) # transient failure was not recorded
assert api.send(alice, chat, marker, key=key) == retried
assert api.history(bob, chat, 100)[0] == [retried] and key_rows(alice, key) == 1
def lock_chat_row(chat: dict, seconds: float) -> subprocess.Popen:
sql = (f"BEGIN; SELECT 1 FROM chats WHERE id = '{chat['id']}' FOR UPDATE; "
f"SELECT pg_sleep({seconds}); COMMIT;")
return subprocess.Popen(["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d",
"messenger", "-c", sql], cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def wait_lock_taken(chat: dict) -> None:
deadline = time.monotonic() + 15
while time.monotonic() < deadline:
if psql("SELECT count(*) FROM pg_stat_activity WHERE query LIKE '%pg_sleep%' AND state = 'active' "
"AND pid <> pg_backend_pid()") != "0":
return
time.sleep(0.2)
raise AssertionError("the row lock was not taken")
def test_client_timeout_then_retry_with_the_same_key_gives_the_committed_message(api, pair):
"""Uncertain outcome: the client gives up after 0.4 s, the server commits later (the row
lock is held 1 s < lock_timeout). The retry must return THAT message, not a second one."""
alice, bob, chat = pair
key = uuid.uuid4().hex
locker = lock_chat_row(chat, 1.0)
try:
wait_lock_taken(chat)
with pytest.raises(httpx.TimeoutException):
httpx.post(BASE_URL + f"/api/v1/chats/{chat['id']}/messages", json={"text": "неопределённо"}, timeout=0.4,
headers={"Authorization": "Bearer " + alice["token"], "Idempotency-Key": key})
finally:
locker.wait(timeout=30)
deadline = time.monotonic() + 10
while messages_in_db(chat) == 0 and time.monotonic() < deadline:
time.sleep(0.2)
stored = psql(f"SELECT id FROM messages WHERE chat_id = '{chat['id']}'")
assert stored, "the server-side transaction was expected to commit after the lock was released"
retried = api.send(alice, chat, "неопределённо", key=key)
assert retried["id"] == stored and messages_in_db(chat) == 1 and key_rows(alice, key) == 1
def test_lock_timeout_is_a_transient_503_that_is_not_recorded(api, pair):
"""The row lock outlives lock_timeout: the API answers 503 within its deadline and stores
nothing; after the lock is gone the same key creates the message exactly once."""
alice, bob, chat = pair
key = uuid.uuid4().hex
locker = lock_chat_row(chat, 4.0)
try:
wait_lock_taken(chat)
started = time.monotonic()
api.post_message(alice, chat, {"text": "после блокировки"}, 503, key=key)
assert time.monotonic() - started < 3.6
assert key_rows(alice, key) == 0 and messages_in_db(chat) == 0
finally:
locker.wait(timeout=30)
created = api.send(alice, chat, "после блокировки", key=key)
assert api.send(alice, chat, "после блокировки", key=key) == created
assert api.history(bob, chat, 100)[0] == [created] and key_rows(alice, key) == 1
def test_replay_after_the_serving_replica_is_stopped(api, pair):
alice, bob, chat = pair
key = uuid.uuid4().hex
first = api.post_message(alice, chat, {"text": "до остановки"}, key=key)
served_by = first.headers["x-instance-id"]
replica = next(r for r in running_replicas() if r["hostname"] == served_by)
with replica_stopped(replica):
for _ in range(5):
again = Api().post_message(alice, chat, {"text": "до остановки"}, key=key)
assert again.json() == first.json() and again.headers["x-instance-id"] != served_by
assert messages_in_db(chat) == 1
+184
View File
@@ -0,0 +1,184 @@
"""Lab 6, against the running stand: what the stored observations really contain.
* one upload with a client-chosen traceparent = ONE trace: API SERVER (continues it) -> relay
PRODUCER -> worker CONSUMER -> s3/db spans; with WORKER_FAULT_POINTS=transient_error=1 the
failed attempt AND the retry are in the same trace (two publishes, two consumer spans);
* log records of api and worker carry the trace_id and the X-Request-Id;
* metrics: exact counters (jobs processed by outcome, time to ready) moved for our work, and
no metric series has an id/raw path as a label value;
* nothing secret in Loki/Tempo: no password, token, message text of our requests.
Stores are read through Grafana's datasource proxy (scripts/obs.py).
"""
from __future__ import annotations
import re
import secrets
import time
import pytest
import obs
from conftest import ROOT, service_with_env
pytestmark = pytest.mark.stack
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
UUID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
def traced_upload(api, actor, chat):
trace_id, parent = secrets.token_hex(16), secrets.token_hex(8)
response = api.upload(actor, chat, SAMPLE, headers={"traceparent": f"00-{trace_id}-{parent}-01",
"X-Request-Id": "obs-" + secrets.token_hex(6)})
assert response.headers["x-trace-id"] == trace_id
return trace_id, parent, response
def jobs_counter(outcome: str) -> float:
return obs.scalar(f'sum(messenger_jobs_processed_total{{outcome="{outcome}"}})', 0.0)
def test_upload_is_one_trace_api_relay_worker_s3_db(api):
owner = api.user("obs")
chat = api.chat(owner)
trace_id, parent, response = traced_upload(api, owner, chat)
att = api.wait_status(owner, response.json()["id"], "ready")
spans = obs.wait_trace(trace_id, lambda s: any(x["name"] == "db jobs.complete" for x in s), timeout=90)
ids = {s["span_id"]: s for s in spans}
server = [s for s in spans if s["kind"] == "SERVER"]
assert len(server) == 1 and server[0]["service"] == "messenger-api"
assert server[0]["parent_id"] == parent # continued, not replaced
assert server[0]["name"] == "POST /api/v1/chats/{chat_id}/attachments"
producer = [s for s in spans if s["kind"] == "PRODUCER"]
consumer = [s for s in spans if s["kind"] == "CONSUMER"]
assert len(producer) == 1 and producer[0]["service"] == "messenger-relay"
assert len(consumer) == 1 and consumer[0]["service"] == "messenger-worker"
assert consumer[0]["parent_id"] == producer[0]["span_id"]
assert producer[0]["parent_id"] == server[0]["span_id"] # context stored with the job = the upload request
assert any(s["name"] == "db enqueue" and s["parent_id"] == server[0]["span_id"] for s in spans)
assert consumer[0]["attrs"]["messenger.job.outcome"] == "succeeded"
assert consumer[0]["attrs"]["messenger.attachment.id"] == att["id"]
worker_children = {s["name"] for s in spans if s["parent_id"] == consumer[0]["span_id"]}
assert {"db jobs.claim", "s3 download", "image render", "s3 put", "db jobs.complete"} <= worker_children
puts = [s for s in spans if s["name"] == "s3 put" and s["parent_id"] == consumer[0]["span_id"]]
assert len(puts) == 4 # original + thumbnail + crop + optimized
for s in spans: # no object keys / urls in span attributes
assert not any(k in s["attrs"] for k in ("aws.s3.key", "url.full", "http.url", "db.query.text"))
def test_retry_is_visible_in_the_same_trace():
"""WORKER_FAULT_POINTS=transient_error=1: attempt 1 fails (transient), the job is retried via
the outbox; both publishes and both worker attempts belong to the upload's trace."""
from conftest import Api
api = Api()
before_retry, before_ok = jobs_counter("retry"), jobs_counter("succeeded")
with service_with_env("worker", WORKER_FAULT_POINTS="transient_error=1", JOB_RETRY_BASE_SECONDS="1"):
owner = api.user("obsretry")
chat = api.chat(owner)
trace_id, _, response = traced_upload(api, owner, chat)
api.wait_status(owner, response.json()["id"], "ready", timeout=90)
spans = obs.wait_trace(trace_id, lambda s: sum(x["kind"] == "CONSUMER" for x in s) >= 2
and any(x["name"] == "db jobs.complete" for x in s), timeout=90)
consumers = sorted((s for s in spans if s["kind"] == "CONSUMER"), key=lambda s: s["start"])
producers = sorted((s for s in spans if s["kind"] == "PRODUCER"), key=lambda s: s["start"])
assert len(producers) == 2 and len(consumers) == 2
assert [p["attrs"]["messenger.job.attempt"] for p in producers] == [1, 2] or \
[str(p["attrs"]["messenger.job.attempt"]) for p in producers] == ["1", "2"]
first, second = consumers
assert first["attrs"]["messenger.job.outcome"] == "retry" and first["status"] == "ERROR"
assert first["attrs"]["messenger.job.error_code"] == "injected_transient"
assert second["attrs"]["messenger.job.outcome"] == "succeeded"
assert {c["parent_id"] for c in consumers} == {p["span_id"] for p in producers}
time.sleep(12) # metric export 5 s + batch + push
assert jobs_counter("retry") >= before_retry + 1
assert jobs_counter("succeeded") >= before_ok + 1
def test_logs_of_api_and_worker_are_joined_by_trace_id(api):
owner = api.user("obslog")
chat = api.chat(owner)
trace_id, _, response = traced_upload(api, owner, chat)
request_id = response.headers["x-request-id"]
api.wait_status(owner, response.json()["id"], "ready")
deadline = time.monotonic() + 60
records = []
while time.monotonic() < deadline:
records = obs.trace_logs(trace_id, minutes=10)
if {"messenger-api", "messenger-worker"} <= {r["service"] for r in records} and \
any(r["line"] == "job_done" for r in records):
break
time.sleep(2)
access = [r for r in records if r["service"] == "messenger-api" and r["line"] == "request"]
assert access and access[0]["metadata"]["request_id"] == request_id
assert access[0]["metadata"]["route"] == "/api/v1/chats/{chat_id}/attachments"
assert access[0]["metadata"]["severity_text"] == "INFO"
done = [r for r in records if r["service"] == "messenger-worker" and r["line"] == "job_done"]
assert done and done[0]["metadata"]["outcome"] == "succeeded"
for r in records:
assert len(r["metadata"]["span_id"]) == 16 and r["metadata"].get("trace_id") in (None, trace_id)
def test_no_ids_or_raw_paths_in_metric_labels():
"""Cardinality guard: no label VALUE of an application series looks like a UUID/hex id, and the
route label only holds templates."""
series = obs.promql('count by (__name__) ({job=~"messenger-.+"})')
assert series, "no application metrics in Prometheus"
names = [s["metric"]["__name__"] for s in series]
for name in names:
for s in obs.promql(f'{name}{{job=~"messenger-.+"}}'):
for label, value in s["metric"].items():
if label in ("instance",): # container hostname (one per replica)
continue
assert not UUID_RE.search(value), (name, label, value)
assert label not in ("user_id", "chat_id", "message_id", "attachment_id", "request_id", "url_path")
routes = {s["metric"]["http_route"] for s in obs.promql("count by (http_route) (http_server_request_duration_seconds_count)")}
assert routes and all(r == "UNMATCHED" or r.startswith("/") and not UUID_RE.search(r) for r in routes)
assert "/api/v1/chats/{chat_id}/messages" in routes
def test_no_secrets_or_message_text_in_logs_and_traces(api):
owner = api.user("obssecret")
chat = api.chat(owner)
text = "секретный-текст-" + secrets.token_hex(8)
response = api.post_message(owner, chat, {"text": text})
trace_id = response.headers["x-trace-id"]
spans = obs.wait_trace(trace_id, lambda s: any(x["kind"] == "SERVER" for x in s), timeout=60)
time.sleep(3)
blobs = [str(spans), str(obs.trace_logs(trace_id, minutes=10)),
str(obs.logs(f'{{service_name="messenger-api"}} |= "{owner["username"]}"', minutes=10))]
for blob in blobs:
assert text not in blob
assert owner["token"] not in blob
assert owner["password"] not in blob
assert "Bearer " not in blob and "Basic " not in blob
def test_history_survives_restart_of_the_stores(api):
"""Persistent volumes keep the history: a trace, its logs and a metric value recorded BEFORE a
restart of Tempo, Loki and Prometheus are still found after it."""
from conftest import compose
owner = api.user("obshist")
chat = api.chat(owner)
trace_id, _, response = traced_upload(api, owner, chat)
api.wait_status(owner, response.json()["id"], "ready")
obs.wait_trace(trace_id, lambda s: any(x["kind"] == "CONSUMER" for x in s), timeout=90)
time.sleep(15) # metric pushes (5 s) and log batches are in
before = time.time()
value_before = obs.scalar('sum(messenger_jobs_processed_total{outcome="succeeded"})')
assert value_before and value_before >= 1
compose("restart", "tempo", "loki", "prometheus", timeout=180)
deadline = time.monotonic() + 180
while True:
try:
spans = obs.trace_spans(trace_id)
records = obs.trace_logs(trace_id, minutes=15)
old = obs.promql('sum(messenger_jobs_processed_total{outcome="succeeded"})', at=before)
if spans and records and old:
break
except Exception: # noqa: BLE001 - stores still starting
pass
assert time.monotonic() < deadline, "history not available after the restart"
time.sleep(3)
assert any(s["kind"] == "SERVER" for s in spans) and any(s["kind"] == "CONSUMER" for s in spans)
assert any(r["line"] == "job_done" for r in records)
assert float(old[0]["value"][1]) == value_before
+504
View File
@@ -0,0 +1,504 @@
"""Lab 5 pipeline against the running stand: 202 -> queued -> ready, variants by the contract,
the failure windows of contracts/attachment-states.md, retries, the failed registry and replay,
lease expiry of a hung worker, cleanup that never deletes accepted work.
Failures are injected with the real mechanisms - docker stop/pause/restart of a service, and
FAULT_POINTS of ONE service recreated with an override (conftest.service_with_env) - and every
test restores the normal stand in `finally`. Each test checks exact HTTP codes AND the rows in
PostgreSQL AND the objects in S3, then the read-only invariant audit (I1-I7) of the whole stand."""
from __future__ import annotations
import hashlib
import io
import json
import subprocess
import time
import uuid
from pathlib import Path
import pytest
from PIL import Image
import imagegen
from conftest import (attachment_row, audit, compose, events_of, job_rows, jobctl, psql, queue_depth, s3_keys,
s3_size, service_down, service_with_env, wait_healthy, wait_stand)
pytestmark = pytest.mark.stack
ROOT = Path(__file__).resolve().parents[1]
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
FAST_LEASE = {"JOB_LEASE_SECONDS": "6"} # the reaper notices a dead attempt within ~11 s
@pytest.fixture()
def pair(api):
alice, bob = api.user("alice"), api.user("bob")
return alice, bob, api.chat(alice, bob)
def wait_for(condition, timeout: float, what: str):
deadline = time.monotonic() + timeout
while True:
value = condition()
if value:
return value
assert time.monotonic() < deadline, what
time.sleep(0.5)
def check_variants(api, actor, att: dict, source: bytes) -> dict[str, bytes]:
"""Download every variant: real format and size decoded with Pillow, size/sha256 = metadata."""
expected = {"thumbnail": ("image/jpeg", "JPEG"), "crop": ("image/jpeg", "JPEG"), "optimized": ("image/webp", "WEBP")}
assert [v["name"] for v in att["variants"]] == list(expected)
src = Image.open(io.BytesIO(source))
w, h = src.size
out = {}
for v in att["variants"]:
got = api.content(actor, att["id"], v["name"])
assert got.headers["content-type"] == expected[v["name"]][0] == v["content_type"]
assert len(got.content) == v["size_bytes"] and hashlib.sha256(got.content).hexdigest() == v["sha256"]
img = Image.open(io.BytesIO(got.content))
assert img.format == expected[v["name"]][1] and img.size == (v["width"], v["height"])
out[v["name"]] = got.content
def fit(box):
if w <= box and h <= box:
return w, h
return (box, max(1, h * box // w)) if w >= h else (max(1, w * box // h), box)
sizes = {v["name"]: (v["width"], v["height"]) for v in att["variants"]}
assert sizes == {"thumbnail": fit(256), "crop": (128, 128), "optimized": fit(1280)}
original = api.content(actor, att["id"])
assert original.content == source # the original is published byte for byte
return out
def published_keys(attachment_id: str) -> list[str]:
return psql(f"SELECT object_key FROM attachment_variants WHERE attachment_id = '{attachment_id}' "
f"UNION ALL SELECT object_key FROM attachments WHERE id = '{attachment_id}' ORDER BY 1").split()
def attempts(attachment_id: str) -> list[dict]:
out = psql("SELECT coalesce(json_agg(json_build_object('attempt', a.attempt, 'outcome', a.outcome, "
"'error_code', a.error_code, 'token', a.token, 'cleaned', a.objects_cleaned_at IS NOT NULL, "
"'keys', a.planned_keys) ORDER BY a.started_at), '[]') FROM job_attempts a JOIN jobs j ON j.id = a.job_id "
f"WHERE j.attachment_id = '{attachment_id}'")
return json.loads(out)
def outbox_of(attachment_id: str) -> list[dict]:
out = psql("SELECT coalesce(json_agg(json_build_object('attempt', o.attempt, 'published', o.published_at IS NOT NULL) "
f"ORDER BY o.id), '[]') FROM outbox o JOIN jobs j ON j.id = o.job_id WHERE j.attachment_id = '{attachment_id}'")
return json.loads(out)
def names(events: list[dict]) -> list[str]:
return [e["event"] for e in events]
# ------------------------------------------------------------------ level 3: the happy path
def test_upload_is_202_queued_then_ready_with_contract_variants(api, pair):
alice, bob, chat = pair
data = imagegen.png(900, 600, noise=True)
response = api.upload(alice, chat, data)
assert response.status_code == 202
att = response.json()
assert att["status"] == "queued" and att["variants"] == [] and att["error_code"] is None
ready = api.wait_status(bob, att["id"], "ready")
assert ready["error_code"] is None and ready["sha256"] == hashlib.sha256(data).hexdigest()
check_variants(api, bob, ready, data)
row = attachment_row(att["id"])
assert row["published_version"] == 1 and row["staging_state"] == "deleted" # staging cleaned after ready
assert s3_size(row["staging_key"], "staging") is None
[job] = job_rows(att["id"])
assert job["state"] == "succeeded" and job["attempt"] == 1 and job["kind"] == "upload"
assert names(events_of(att["id"])) == ["created", "claimed", "succeeded"]
def test_queued_attachment_is_attachable_failed_is_not(api, pair):
alice, bob, chat = pair
with service_down("worker"): # stays queued
att = api.upload(alice, chat, SAMPLE).json()
msg = api.post_message(alice, chat, {"text": "", "attachment_ids": [att["id"]]}).json()
assert msg["attachment_ids"] == [att["id"]]
api.wait_status(alice, att["id"], "ready")
with service_with_env("worker", WORKER_FAULT_POINTS="permanent_error"):
bad = api.upload(alice, chat, SAMPLE).json()
failed = api.wait_status(bob, bad["id"], "failed")
assert failed["error_code"] == "invalid_image" and failed["variants"] == []
api.post_message(alice, chat, {"text": "", "attachment_ids": [bad["id"]]}, 409)
api.content(bob, bad["id"], expected=409)
api.content(bob, bad["id"], "thumbnail", expected=409)
def test_worker_stopped_upload_202_content_409_restart_api_and_broker_then_ready(api, pair):
"""The defence scenario: worker stopped -> upload 202 -> content 409, other messages keep working
-> the message with the attachment is created -> API and broker restarted WITH volumes ->
the job is still in the queue -> worker started -> ready, thumbnail downloadable."""
alice, bob, chat = pair
compose("stop", "worker")
try:
response = api.upload(alice, chat, SAMPLE)
att = response.json()
assert response.status_code == 202 and att["status"] == "queued"
for variant in (None, "thumbnail"):
assert api.content(bob, att["id"], variant, expected=409).json()["error"]["code"] == "conflict"
api.send(bob, chat, "текст работает без worker")
msg = api.post_message(alice, chat, {"text": "фото", "attachment_ids": [att["id"]]}).json()
wait_for(lambda: all(o["published"] for o in outbox_of(att["id"])), 15, "relay did not publish the job")
# rabbitmqctl counters are refreshed every ~5 s (statistics interval): wait, do not sample once.
wait_for(lambda: queue_depth() >= 1, 20, "no message in the queue") # durable message waits in the queue
compose("restart", "api", "broker") # volumes preserved
wait_healthy("api", "broker", "relay")
wait_stand()
wait_for(lambda: queue_depth() >= 1, 20, "the accepted job was lost by the broker restart")
assert api.attachment(bob, att["id"])["status"] == "queued"
finally:
compose("start", "worker")
wait_healthy("worker")
ready = api.wait_status(bob, att["id"], "ready")
check_variants(api, bob, ready, SAMPLE)
items, _ = api.history(bob, chat, 50)
assert any(m["id"] == msg["id"] and m["attachment_ids"] == [att["id"]] for m in items)
[job] = job_rows(att["id"])
assert job["attempt"] == 1 # no duplicate work
# ------------------------------------------------------------------ failure windows
def test_broker_down_commit_to_publish_gap_is_closed_by_the_outbox(api, pair):
"""Window "after COMMIT, before publish": the broker is down, the API still answers 202 (it never
talks to the broker), the outbox row stays unpublished. No manual action: when the broker is
back the relay publishes it and the worker finishes the job."""
alice, bob, chat = pair
with service_down("broker"):
att = api.upload(alice, chat, SAMPLE).json()
assert att["status"] == "queued"
time.sleep(3)
assert outbox_of(att["id"]) == [{"attempt": 1, "published": False}]
api.send(alice, chat, "сообщения работают без брокера")
api.wait_status(bob, att["id"], "ready", timeout=90)
assert outbox_of(att["id"]) == [{"attempt": 1, "published": True}]
assert [j["attempt"] for j in job_rows(att["id"])] == [1]
def test_relay_down_job_waits_in_outbox_not_lost(api, pair):
alice, bob, chat = pair
with service_down("relay"):
att = api.upload(alice, chat, SAMPLE).json()
time.sleep(3)
assert outbox_of(att["id"]) == [{"attempt": 1, "published": False}]
assert api.attachment(bob, att["id"])["status"] == "queued"
api.wait_status(bob, att["id"], "ready")
def test_crash_after_publish_before_confirm_is_recorded_gives_a_harmless_duplicate(api, pair):
"""Window "after publish, before confirm": the relay dies after the broker confirmed the message
but before outbox.published_at is committed. The restarted relay publishes it AGAIN; the
duplicate is a no-op (one claim, one set of variants)."""
alice, bob, chat = pair
with service_with_env("relay", RELAY_FAULT_POINTS="crash_after_publish"):
att = api.upload(alice, chat, SAMPLE).json()
api.wait_status(bob, att["id"], "ready", timeout=90)
wait_for(lambda: all(o["published"] for o in outbox_of(att["id"])), 30, "outbox not marked after restart")
events = events_of(att["id"])
assert names(events).count("fault_injected") == 1 and names(events).count("claimed") == 1
assert [j["attempt"] for j in job_rows(att["id"])] == [1]
assert len(published_keys(att["id"])) == 4 # original + 3 variants, once
def test_duplicate_and_reordered_deliveries_are_noops(api, pair):
alice, bob, chat = pair
with service_with_env("relay", RELAY_FAULT_POINTS="duplicate_publish,reverse_order"):
atts = [api.upload(alice, chat, imagegen.png(50 + i, 40)).json() for i in range(4)]
for att in atts:
api.wait_status(bob, att["id"], "ready")
time.sleep(2) # let the duplicates be consumed
for att in atts:
assert names(events_of(att["id"])) == ["created", "claimed", "succeeded"]
assert len(published_keys(att["id"])) == 4
logs = compose("logs", "--no-log-prefix", "worker").stdout
assert '"noop_finished"' in logs or '"noop_leased"' in logs # duplicates were seen and acked
def test_worker_crash_before_side_effect_lease_expires_and_job_completes(api, pair):
"""The worker dies right after the claim. The redelivered message finds a valid lease (no-op);
the reaper returns the job to queued when the lease expires; attempt 2 publishes."""
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="crash_after_claim", **FAST_LEASE):
att = api.upload(alice, chat, SAMPLE).json()
api.wait_status(bob, att["id"], "ready", timeout=90)
ev = names(events_of(att["id"]))
assert ev.count("fault_injected") == 1 and "lease_expired" in ev and ev[-1] == "succeeded"
tries = attempts(att["id"])
assert [(a["attempt"], a["outcome"]) for a in tries] == [(1, "abandoned"), (2, "succeeded")]
assert tries[0]["keys"] and all(s3_size(k) is None for k in tries[0]["keys"]) # nothing written
def test_worker_crash_after_s3_write_before_commit_republishes_without_duplicates(api, pair):
"""Window "after the S3 write, before the result COMMIT": objects of attempt 1 exist under ITS keys
but are never published; attempt 2 publishes its own; the cleanup deletes attempt 1's objects
after ORPHAN_GRACE_SECONDS (they can never become published: the token is fenced)."""
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="crash_after_s3_write", ORPHAN_GRACE_SECONDS="2",
CLEANUP_INTERVAL_SECONDS="1", **FAST_LEASE):
att = api.upload(alice, chat, SAMPLE).json()
ready = api.wait_status(bob, att["id"], "ready", timeout=90)
first, second = attempts(att["id"])
assert (first["outcome"], second["outcome"]) == ("abandoned", "succeeded")
assert set(published_keys(att["id"])) == set(second["keys"])
wait_for(lambda: attempts(att["id"])[0]["cleaned"], 30, "orphans of attempt 1 not cleaned")
assert all(s3_size(k) is None for k in first["keys"])
assert all(s3_size(k) is not None for k in second["keys"])
assert s3_keys(f"a/{att['id']}/") == set(second["keys"]) # exactly one set of objects
check_variants(api, bob, ready, SAMPLE)
def test_worker_crash_after_commit_before_ack_redelivery_is_noop(api, pair):
"""Window "after the result COMMIT, before the ack": the message comes back; the job is
succeeded -> ack without any work; the same result stays published."""
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="crash_after_commit"):
att = api.upload(alice, chat, SAMPLE).json()
ready = api.wait_status(bob, att["id"], "ready", timeout=60)
before = published_keys(att["id"])
wait_healthy("worker")
wait_for(lambda: '"noop_finished"' in compose("logs", "--no-log-prefix", "worker").stdout, 30,
"the redelivered message was not acknowledged as a no-op")
ev = names(events_of(att["id"]))
assert ev == ["created", "claimed", "fault_injected", "succeeded"] or ev == ["created", "claimed", "succeeded", "fault_injected"]
assert published_keys(att["id"]) == before and [a["outcome"] for a in attempts(att["id"])] == ["succeeded"]
assert api.attachment(bob, att["id"]) == ready
# ------------------------------------------------------------------ retries and failures
def test_transient_errors_are_retried_with_jittered_backoff(api, pair):
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="transient_error=2", JOB_RETRY_BASE_SECONDS="1",
JOB_RETRY_MAX_SECONDS="8"):
att = api.upload(alice, chat, SAMPLE).json()
api.wait_status(bob, att["id"], "ready", timeout=60)
events = events_of(att["id"])
retries = [e for e in events if e["event"] == "retry_scheduled"]
assert [(e["attempt"], e["error_code"]) for e in retries] == [(1, "injected_transient"), (2, "injected_transient")]
for e in retries:
assert 0 <= e["detail"]["delay_s"] <= 1 * 2 ** (e["attempt"] - 1) # full jitter window
assert [(a["attempt"], a["outcome"]) for a in attempts(att["id"])] == [(1, "retry"), (2, "retry"), (3, "succeeded")]
assert [o["attempt"] for o in outbox_of(att["id"])] == [1, 2, 3] # every retry went through the outbox
def test_retry_exhausted_failed_registry_then_replay(api, pair):
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="transient_error", JOB_RETRY_BASE_SECONDS="0.2",
JOB_RETRY_MAX_SECONDS="0.5"):
att = api.upload(alice, chat, SAMPLE).json()
failed = api.wait_status(bob, att["id"], "failed", timeout=60)
assert failed["error_code"] == "retry_exhausted" and failed["variants"] == []
[job] = job_rows(att["id"])
assert (job["state"], job["attempt"], job["error_code"]) == ("failed", 5, "retry_exhausted") # JOB_MAX_ATTEMPTS
registry = jobctl("list-failed", "--limit", "200")["failed"]
assert any(r["attachment_id"] == att["id"] and r["error_code"] == "retry_exhausted" for r in registry)
assert attachment_row(att["id"])["staging_state"] == "present" # kept for the replay
# Operator replay: a NEW job (replay_of = the failed one), audit with operator and reason.
result = jobctl("replay", att["id"], "--operator", "alice", "--reason", "fault removed")
assert result["result"] == "queued" and result["replay_of"] == job["id"]
ready = api.wait_status(bob, att["id"], "ready", timeout=60)
check_variants(api, bob, ready, SAMPLE)
jobs = job_rows(att["id"])
assert [(j["kind"], j["state"]) for j in jobs] == [("upload", "failed"), ("replay", "succeeded")]
ev = events_of(att["id"])
req = next(e for e in ev if e["event"] == "replay_requested")
assert req["actor"] == "jobctl:alice" and req["detail"]["reason"] == "fault removed"
# "Repeat" never re-runs a finished job: a replay of a ready attachment is refused, nothing created.
refused = jobctl("replay", att["id"], "--operator", "alice", "--reason", "again", expect_code=3)
assert refused == {"result": "refused", "reason": "already_ready"}
assert len(job_rows(att["id"])) == 2
def test_permanent_error_fails_at_once_without_retries(api, pair):
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="permanent_error"):
att = api.upload(alice, chat, SAMPLE).json()
failed = api.wait_status(bob, att["id"], "failed")
assert failed["error_code"] == "invalid_image"
assert [(a["attempt"], a["outcome"]) for a in attempts(att["id"])] == [(1, "failed")]
def test_memory_and_time_limits_of_the_worker(api, pair):
"""40 Mpx PNG (valid, accepted by the API) with IMAGE_MAX_MEMORY_MB=200: the child process cannot
allocate the raster -> image_too_large (permanent); the worker itself keeps running.
JOB_TIMEOUT_SECONDS=3 with a 10 s stall -> processing_timeout (transient, retried)."""
alice, bob, chat = pair
with service_with_env("worker", IMAGE_MAX_MEMORY_MB="200"):
att = api.upload(alice, chat, imagegen.png(8000, 5000, compress_level=9)).json()
failed = api.wait_status(bob, att["id"], "failed", timeout=90)
assert failed["error_code"] == "image_too_large"
ok = api.upload(alice, chat, SAMPLE).json() # the same worker still works
api.wait_status(bob, ok["id"], "ready")
with service_with_env("worker", WORKER_FAULT_POINTS="slow=10", JOB_TIMEOUT_SECONDS="3"):
slow = api.upload(alice, chat, SAMPLE).json()
wait_for(lambda: any(a["error_code"] == "processing_timeout" for a in attempts(slow["id"])), 60,
"no processing_timeout")
api.wait_status(bob, slow["id"], "ready", timeout=120) # normal worker finishes it
def test_bad_message_is_dead_lettered_not_processed(api, pair):
"""A message that does not match jobs.schema.json (published here with the relay's own broker
user) is rejected by the worker into the DLQ; nothing is processed."""
before = queue_depth("messenger.attachment-jobs.dlq")
script = ("import asyncio, aio_pika\n"
"async def m():\n"
" url = open('/run/secrets/broker_url').read().strip()\n"
" c = await aio_pika.connect(url)\n"
" ch = await c.channel(publisher_confirms=True)\n"
" ex = await ch.get_exchange('messenger.jobs', ensure=False)\n"
" await ex.publish(aio_pika.Message(b'{\"url\":\"http://evil/x.png\"}'), routing_key='attachment.process.v1')\n"
" await c.close()\n"
"asyncio.run(m())\n")
compose("exec", "-T", "relay", "python", "-c", script)
wait_for(lambda: queue_depth("messenger.attachment-jobs.dlq") == before + 1, 20, "not dead-lettered")
assert '"bad_message"' in compose("logs", "--no-log-prefix", "worker").stdout
# ------------------------------------------------------------------ lease, hung worker, shutdown, concurrency
def worker_containers() -> dict[str, str]:
"""hostname (= lease_owner) -> container id of every running worker."""
ids = compose("ps", "-q", "worker").stdout.split()
out = subprocess.run(["docker", "inspect", "-f", "{{.Config.Hostname}} {{.Id}}", *ids], capture_output=True,
text=True, check=True).stdout
return dict(line.split() for line in out.splitlines())
def test_hung_worker_loses_its_lease_and_cannot_publish(api, pair):
"""Two workers. The one processing the job is frozen (docker pause: no heartbeat). Its lease
expires, the reaper re-queues the job, the other worker publishes it. When the frozen worker
resumes, its result is fenced by the token: the published result does not change."""
alice, bob, chat = pair
with service_with_env("worker", scale=2, WORKER_FAULT_POINTS="slow=8", **FAST_LEASE):
att = api.upload(alice, chat, SAMPLE).json()
owner = wait_for(lambda: psql(f"SELECT lease_owner FROM jobs WHERE attachment_id = '{att['id']}' "
"AND state = 'processing'"), 30, "job never claimed")
frozen = worker_containers()[owner]
subprocess.run(["docker", "pause", frozen], check=True, capture_output=True)
try:
ready = api.wait_status(bob, att["id"], "ready", timeout=120)
published = published_keys(att["id"])
finally:
subprocess.run(["docker", "unpause", frozen], check=True, capture_output=True)
time.sleep(12) # the resumed attempt finishes its sleep and tries to publish
assert published_keys(att["id"]) == published and api.attachment(bob, att["id"]) == ready
tries = attempts(att["id"])
assert [(a["attempt"], a["outcome"]) for a in tries] == [(1, "abandoned"), (2, "succeeded")]
assert "lease_expired" in names(events_of(att["id"]))
check_variants(api, bob, ready, SAMPLE)
def test_graceful_worker_stop_finishes_the_running_attempt(api, pair):
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="slow=5"):
att = api.upload(alice, chat, SAMPLE).json()
wait_for(lambda: api.attachment(bob, att["id"])["status"] == "processing", 30, "never processing")
started = time.monotonic()
compose("stop", "worker") # SIGTERM: drain, not kill
assert time.monotonic() - started < 30
assert attachment_row(att["id"])["status"] == "ready" # committed before the exit
compose("start", "worker")
wait_healthy("worker")
assert [a["outcome"] for a in attempts(att["id"])] == ["succeeded"]
def test_concurrency_is_bounded_by_prefetch(api, pair):
"""WORKER_CONCURRENCY=2: never more than 2 jobs processing and 2 unacked messages at once."""
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="slow=3"):
atts = [api.upload(alice, chat, imagegen.png(30 + i, 30)).json() for i in range(6)]
peak = 0
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
states = [api.attachment(bob, a["id"])["status"] for a in atts]
peak = max(peak, states.count("processing"))
unacked = compose("exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "name",
"messages_unacknowledged").stdout
for line in unacked.splitlines():
if line.startswith("messenger.attachment-jobs\t"):
assert int(line.split("\t")[1]) <= 2, line
if all(s == "ready" for s in states):
break
time.sleep(0.3)
assert all(api.attachment(bob, a["id"])["status"] == "ready" for a in atts)
assert peak == 2
# ------------------------------------------------------------------ cleanup never deletes accepted work
def test_queued_staging_is_never_deleted_even_after_retention(api, pair):
"""Reviewer's case in another PR: the worker was down longer than the retention and the cleanup
deleted the original of a job that was still queued. Here: the job waits queued (relay down)
while the cleanup runs every second with retention 0 - the staging copy stays, and the
database itself refuses marking it (CHECK attachments_active_has_source)."""
alice, bob, chat = pair
with service_with_env("worker", STAGING_RETENTION_SECONDS="0", CLEANUP_INTERVAL_SECONDS="1"):
with service_down("relay"):
att = api.upload(alice, chat, SAMPLE).json()
time.sleep(5) # several cleanup passes
row = attachment_row(att["id"])
assert row["status"] == "queued" and row["staging_state"] == "present"
assert s3_size(row["staging_key"], "staging") == len(SAMPLE)
refused = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-c",
f"UPDATE attachments SET staging_state = 'deleting' WHERE id = '{att['id']}'",
check=False)
assert refused.returncode != 0 and "attachments_active_has_source" in refused.stderr
ready = api.wait_status(bob, att["id"], "ready", timeout=60)
check_variants(api, bob, ready, SAMPLE)
def test_retention_deletes_failed_staging_then_replay_is_refused(api, pair):
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="permanent_error", STAGING_RETENTION_SECONDS="1",
CLEANUP_INTERVAL_SECONDS="1"):
att = api.upload(alice, chat, SAMPLE).json()
api.wait_status(bob, att["id"], "failed")
wait_for(lambda: attachment_row(att["id"])["staging_state"] == "deleted", 30, "staging not cleaned")
assert s3_size(attachment_row(att["id"])["staging_key"], "staging") is None
refused = jobctl("replay", att["id"], "--operator", "alice", "--reason", "too late", expect_code=3)
assert refused == {"result": "refused", "reason": "source_missing"}
assert api.attachment(bob, att["id"])["status"] == "failed" and len(job_rows(att["id"])) == 1
def test_cleanup_racing_a_replay_never_deletes_the_replayed_source(api, pair):
"""Reviewer's interleaving in another PR: the cleanup READ its candidates (an expired failed
attachment), a replay committed queued, the cleanup went on and deleted the staging copy.
Here the cleanup pauses exactly there (pause_cleanup); the replay commits during the pause;
the cleanup then re-checks under the row lock and skips the row. The replay finishes ready."""
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="permanent_error"):
att = api.upload(alice, chat, SAMPLE).json()
api.wait_status(bob, att["id"], "failed")
# The pause must outlast `docker compose run jobctl` (container start: 3-15 s on a loaded Windows
# stand). With 8 s the replay once came too late: the cleanup went on, deleted the expired staging
# copy and the replay was - correctly - refused with source_missing. 20 s keeps the race window.
with service_with_env("worker", WORKER_FAULT_POINTS="pause_cleanup=20", STAGING_RETENTION_SECONDS="1",
CLEANUP_INTERVAL_SECONDS="1"):
wait_for(lambda: '"cleanup_paused"' in compose("logs", "--no-log-prefix", "--since", "60s", "worker").stdout
and att["id"] in compose("logs", "--no-log-prefix", "--since", "60s", "worker").stdout,
30, "cleanup did not pick the failed attachment")
result = jobctl("replay", att["id"], "--operator", "alice", "--reason", "race test")
assert result["result"] == "queued"
ready = api.wait_status(bob, att["id"], "ready", timeout=90)
check_variants(api, bob, ready, SAMPLE)
assert attachment_row(att["id"])["staging_state"] == "deleted" # deleted only AFTER ready
def test_reprocess_of_a_not_ready_upload_is_refused(api, pair):
"""Reviewer's case in another PR: worker stopped -> upload 202 -> reprocess with pipeline 2 ->
the attachment stayed queued forever. Here the command is refused and v1 completes."""
alice, bob, chat = pair
with service_down("worker"):
att = api.upload(alice, chat, SAMPLE).json()
refused = jobctl("reprocess", att["id"], "--pipeline", "2", "--operator", "alice", "--reason", "x",
expect_code=3)
assert refused == {"result": "refused", "reason": "not_ready:queued"}
assert len(job_rows(att["id"])) == 1
api.wait_status(bob, att["id"], "ready")
assert attachment_row(att["id"])["published_version"] == 1
def test_zz_invariants_hold_after_all_scenarios():
report = audit("--verify-checksums")
assert report["objects"]["published"] > 0
+66
View File
@@ -0,0 +1,66 @@
"""Session lifetime: expiry with a short SESSION_TTL_SECONDS, no extension by restarts,
and the alternative SESSION_STORE=postgres. The api container is recreated with the
override and ALWAYS recreated back with the normal configuration (api_with_env)."""
from __future__ import annotations
import datetime as dt
import time
import pytest
from conftest import api_env, api_with_env, restart_services, service_down
pytestmark = pytest.mark.stack
def seconds_left(expires_at: str) -> float:
moment = dt.datetime.fromisoformat(expires_at.replace("Z", "+00:00"))
return (moment - dt.datetime.now(dt.timezone.utc)).total_seconds()
def login_session(api, actor) -> dict:
from conftest import basic
return api.call("POST", "/api/v1/auth/sessions", 201,
headers={"Authorization": basic(actor["username"], actor["password"])}, schema="Session").json()
@pytest.mark.parametrize("store", ["valkey", "postgres"])
def test_short_ttl_expires(api, store):
with api_with_env(SESSION_TTL_SECONDS="2", SESSION_STORE=store):
assert api_env("SESSION_TTL_SECONDS") == "2" # the contract variable reaches the container
actor = api.register("ttl")
session = login_session(api, actor)
assert 1.0 < seconds_left(session["expires_at"]) <= 2.1
api.call("GET", "/api/v1/users/me", 200, token=session["token"])
time.sleep(max(0.0, seconds_left(session["expires_at"])) + 0.3)
api.call("GET", "/api/v1/users/me", 401, token=session["token"])
api.call("DELETE", "/api/v1/auth/sessions/current", 401, token=session["token"])
def test_restart_does_not_extend_ttl(api):
# 30 s: a restart of Valkey + both API replicas (readiness now also waits for S3) takes ~12-15 s.
with api_with_env(SESSION_TTL_SECONDS="30"):
actor = api.register("ttlrestart")
session = login_session(api, actor)
restart_services("valkey", "api")
assert seconds_left(session["expires_at"]) > 0, "restart took longer than the TTL; increase it"
api.call("GET", "/api/v1/users/me", 200, token=session["token"])
time.sleep(max(0.0, seconds_left(session["expires_at"])) + 0.3)
api.call("GET", "/api/v1/users/me", 401, token=session["token"])
def test_postgres_session_store(api):
"""SESSION_STORE=postgres: sessions survive an API restart, logout revokes, and a DB outage
is 503 for a valid token (not 401 and not anonymous access)."""
with api_with_env(SESSION_STORE="postgres"):
assert api_env("SESSION_STORE") == "postgres"
actor = api.user("pgstore")
restart_services("api")
api.call("GET", "/api/v1/users/me", 200, token=actor["token"])
with service_down("postgres", "stop"):
assert api.call("GET", "/api/v1/users/me", 503, token=actor["token"],
lb_error_ok=True).json()["error"]["code"] == "unavailable"
api.call("GET", "/api/v1/users/me", (401, 503), lb_error_ok=True)
api.call("GET", "/api/v1/users/me", 200, token=actor["token"])
api.call("DELETE", "/api/v1/auth/sessions/current", 204, token=actor["token"])
api.call("GET", "/api/v1/users/me", 401, token=actor["token"])
+112
View File
@@ -0,0 +1,112 @@
"""S3 outages, private buckets and failover of attachments (lab 4, levels 3 and 4; lab 5: two
buckets, upload 202 + worker).
Every injected failure is undone in `finally` (conftest.service_down / replica_stopped), and the
stand is waited for until HAProxy sees all replicas UP again."""
from __future__ import annotations
import time
from pathlib import Path
import pytest
import imagegen
from conftest import attachment_row, compose, probe_inside, replica_stopped, running_replicas, service_down
pytestmark = pytest.mark.stack
ROOT = Path(__file__).resolve().parents[1]
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
@pytest.fixture()
def pair(api):
alice, bob = api.user("alice"), api.user("bob")
return alice, bob, api.chat(alice, bob)
@pytest.mark.parametrize("how", ["stop", "pause"])
def test_s3_outage_is_503_and_text_keeps_working(api, pair, how):
"""S3 down (stopped: connection refused; paused: no answer at all):
* readiness is 503 on every replica (and through the LB), quickly;
* uploads/downloads are 503 `unavailable` within the S3 deadline, never 500;
* the LB's degraded mode keeps chats/text messages working (HAProxy backend api_core);
* after recovery the earlier file is intact."""
alice, bob, chat = pair
att = api.upload(alice, chat, SAMPLE).json()
api.wait_status(alice, att["id"], "ready")
with service_down("s3", how):
deadline = time.monotonic() + 15
while api.client.get("/health/ready").status_code != 503:
assert time.monotonic() < deadline, "readiness did not turn 503"
time.sleep(0.5)
for replica in running_replicas():
assert probe_inside(replica, "/health/ready") == 503
assert probe_inside(replica, "/health/ready/core") == 200
started = time.monotonic()
error = api.upload(alice, chat, SAMPLE, 503).json()
assert error["error"]["code"] == "unavailable"
assert time.monotonic() - started < 8
started = time.monotonic()
api.call("GET", f"/api/v1/attachments/{att['id']}/content", 503, token=bob["token"])
assert time.monotonic() - started < 8
api.call("GET", f"/api/v1/attachments/{att['id']}", 200, token=bob["token"]) # metadata: PostgreSQL only
api.send(alice, chat, "текст работает без S3") # degraded mode
got = api.call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"])
assert got.content == SAMPLE
api.upload(alice, chat, SAMPLE)
def test_upload_survives_failover_of_the_serving_replica(api, pair):
"""Upload -> stop the replica that served it -> another replica downloads the same bytes
(nothing of the file lives in the replica)."""
alice, bob, chat = pair
data = imagegen.png_of_size(500_000)
response = api.upload(alice, chat, data)
att, served_by = response.json(), response.headers["x-instance-id"]
replica = next(r for r in running_replicas() if r["hostname"] == served_by)
api.wait_status(bob, att["id"], "ready")
with replica_stopped(replica, "kill"):
for _ in range(5):
got = api.call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"])
assert got.headers["x-instance-id"] != served_by and got.content == data
def test_bucket_is_private_outside_the_api(api, pair):
"""Inside the storage network (where the API is): an UNSIGNED GET of a real object and an
unsigned LIST are refused; the same GET signed with the API key pair works (control).
SeaweedFS admin endpoints (master 9333, filer 8888, volume 8080) are not reachable."""
alice, _, chat = pair
att = api.upload(alice, chat, SAMPLE).json()
api.wait_status(alice, att["id"], "ready")
key = attachment_row(att["id"])["object_key"]
probe = (
"import urllib.request as u, urllib.error as e, socket\n"
"def st(url):\n"
" try: return u.urlopen(url, timeout=3).status\n"
" except e.HTTPError as x: return x.code\n"
f"print(st('http://s3:8333/messenger-attachments/{key}'), st('http://s3:8333/messenger-attachments?list-type=2'))\n"
"for port in (9333, 8888, 8080):\n"
" s = socket.socket(); s.settimeout(2)\n"
" print(port, s.connect_ex(('s3', port)))\n")
out = compose("exec", "-T", "api", "python", "-c", probe).stdout.split("\n")
get_status, list_status = out[0].split()
assert get_status in ("401", "403") and list_status in ("401", "403"), out[0]
for line in out[1:4]:
port, code = line.split()
assert code != "0", f"admin port {port} reachable"
signed = compose("exec", "-T", "api", "python", "-c",
"import asyncio\nfrom messenger.config import Settings\nfrom messenger.storage import Storage\n"
"async def m():\n s=Storage(Settings.from_env()); await s.open()\n"
f" print((await s.head('{key}')).size); await s.close()\nasyncio.run(m())").stdout.strip()
assert signed == str(len(SAMPLE))
def test_s3_restart_keeps_objects(api, pair):
alice, bob, chat = pair
data = imagegen.png_of_size(200_000)
att = api.upload(alice, chat, data).json()
api.wait_status(bob, att["id"], "ready")
with service_down("s3", "stop"):
pass
assert api.call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"]).content == data
+148
View File
@@ -0,0 +1,148 @@
"""Unit tests of the image checks (src/messenger/images.py) and the filename rules. No services.
The JPEG decoder (djpeg) exists in the API image; locally these tests are skipped without it
(the same cases run against the stand in test_attachments.py)."""
from __future__ import annotations
import asyncio
import shutil
import sys
import time
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "src"))
sys.path.insert(0, str(ROOT / "student-tests"))
import imagegen # noqa: E402
from messenger import images, validation # noqa: E402
from messenger.errors import InvalidRequest # noqa: E402
LIMIT = 40_000_000
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
has_djpeg = pytest.mark.skipif(shutil.which("djpeg") is None, reason="djpeg (libjpeg-turbo-progs) not installed")
def status(data: bytes) -> int:
"""201 if accepted, else the HTTP status of the ImageError (413/415)."""
try:
info = images.sniff(data, LIMIT)
if info is None:
return 415 # header never completed
asyncio.run(images.verify(data, info))
return 201
except images.ImageError as exc:
return exc.status
def test_public_fixture_is_accepted():
assert images.sniff(SAMPLE, LIMIT) == images.ImageInfo("image/png", 320, 200)
assert status(SAMPLE) == 201
@pytest.mark.parametrize("data", [
imagegen.png(37, 23, "RGBA"), imagegen.png(33, 17, "P"), imagegen.png(33, 17, "1"),
imagegen.png(33, 17, "L"), imagegen.png(81, 57, "RGB", noise=True), imagegen.png(1, 1),
], ids=["rgba", "palette", "1bit", "gray", "noise", "1x1"])
def test_valid_png_kinds(data):
assert status(data) == 201
def test_interlaced_png_is_accepted():
# Pillow cannot write Adam7; build one by hand: 9 x 9 grey, every pass with filter 0.
from messenger.images import _png_segments
raw = b"".join(b"\x00" + bytes(stride - 1) for size, stride in _png_segments(9, 9, 8, 0, 1)
for _ in range(size // stride))
data = imagegen.PNG_SIGNATURE + imagegen.ihdr(9, 9, 8, 0, 1) + imagegen.chunk(b"IDAT", __import__("zlib").compress(raw)) \
+ imagegen.chunk(b"IEND", b"")
assert status(data) == 201
BROKEN_PNG = {
"first 33 bytes of the fixture": SAMPLE[:33],
"truncated (no IEND)": SAMPLE[:-12],
"truncated in IDAT": SAMPLE[:len(SAMPLE) // 2],
"flipped byte -> CRC error": SAMPLE[:500] + bytes([SAMPLE[500] ^ 0xFF]) + SAMPLE[501:],
"garbage IDAT with valid CRC": imagegen.png_corrupt_idat(),
"fewer rows than IHDR": imagegen.png_short_pixels(),
"bytes after IEND (polyglot)": SAMPLE + b"PK\x03\x04zip",
"text": b"just text, definitely not an image",
"gif": b"GIF89a" + bytes(64),
"two bytes of a signature": b"\x89P",
}
@pytest.mark.parametrize("name", list(BROKEN_PNG))
def test_broken_png_is_415(name):
assert status(BROKEN_PNG[name]) == 415, name
def test_pixel_limit_is_checked_from_the_header():
with pytest.raises(images.ImageError) as exc:
images.sniff(imagegen.png_bomb_header()[:33], LIMIT) # 33 bytes are enough
assert exc.value.status == 413
exact = imagegen.PNG_SIGNATURE + imagegen.ihdr(8000, 5000) # exactly 40 000 000: allowed
assert images.sniff(exact, LIMIT).width == 8000
with pytest.raises(images.ImageError) as exc:
images.sniff(imagegen.PNG_SIGNATURE + imagegen.ihdr(8001, 5000), LIMIT)
assert exc.value.status == 413
with pytest.raises(images.ImageError) as exc:
images.sniff(imagegen.jpeg_bomb_header(), LIMIT)
assert exc.value.status == 413
def test_png_verification_is_streaming_and_fast():
"""40 Mpx RGB = 120 MB of raw pixels: inflated in 1 MiB steps and discarded."""
big = imagegen.png(8000, 5000, compress_level=9)
started = time.perf_counter()
assert status(big) == 201
assert time.perf_counter() - started < 5
def test_jpeg_header_is_parsed_incrementally():
data = imagegen.jpeg(320, 200)
assert images.sniff(data[:4], LIMIT) is None # SOF not arrived yet
assert images.sniff(data, LIMIT) == images.ImageInfo("image/jpeg", 320, 200)
@has_djpeg
@pytest.mark.parametrize("data", [imagegen.jpeg(), imagegen.jpeg(640, 480, progressive=True)], ids=["base", "prog"])
def test_valid_jpeg(data):
assert status(data) == 201
@has_djpeg
@pytest.mark.parametrize("name,data", [
("no scan data after SOS", imagegen.jpeg_without_scan_data()),
("truncated", imagegen.jpeg(320, 240, noise=True)[:3000]),
], ids=lambda v: v if isinstance(v, str) else "")
def test_broken_jpeg_is_415(name, data):
assert status(data) == 415, name
# ------------------------------------------------------------------ filename
@pytest.mark.parametrize("name", ["photo.png", "фото отпуска.jpg", "a" * 255, "emoji 👨‍👩‍👧.png", " x ", "..."[:2] + "x"])
def test_good_filenames(name):
assert validation.filename_param([("filename", name)]) == name
@pytest.mark.parametrize("name", ["", " ", " ", ".", "..", "a/b.png", "a\\b.png", "a\x00b", "c1\x85.png",
"tab\t.png", "del\x7f.png", "x
y", "photo‮gnp.exe", "a" * 256])
def test_bad_filenames(name):
with pytest.raises(InvalidRequest):
validation.filename_param([("filename", name)])
def test_filename_must_be_single_and_present():
with pytest.raises(InvalidRequest):
validation.filename_param([])
with pytest.raises(InvalidRequest):
validation.filename_param([("filename", "a.png"), ("filename", "b.png")])
def test_query_must_be_valid_utf8():
assert validation.query_items(b"filename=%D1%84.png") == [("filename", "ф.png")]
with pytest.raises(InvalidRequest):
validation.query_items(b"filename=%FF%FE.png")
+224
View File
@@ -0,0 +1,224 @@
"""Unit tests of lab 5 without services: variant geometry and encoding (imaging.build, the same
code the worker runs in its child process), the job message schema, backoff with jitter and the
pipeline configuration."""
from __future__ import annotations
import io
import json
import sys
import uuid
from pathlib import Path
import pytest
from jsonschema import Draft202012Validator
from PIL import Image
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "src"))
sys.path.insert(0, str(ROOT / "student-tests"))
import imagegen # noqa: E402
from messenger import broker, imaging, jobs # noqa: E402
from messenger.config import ConfigError, Settings # noqa: E402
from messenger.pipeline import PIPELINES, center_square, fit # noqa: E402
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
SCHEMA = json.loads((ROOT / "contracts" / "jobs.schema.json").read_text(encoding="utf-8"))
LIMIT = 40_000_000
def variants(data: bytes, content_type: str = "image/png", version: int = 1) -> dict[str, imaging.Rendered]:
return {v.name: v for v in imaging.build(data, content_type, version, LIMIT)}
def decoded(v: imaging.Rendered) -> Image.Image:
img = Image.open(io.BytesIO(v.data))
img.load()
return img
# ------------------------------------------------------------------ geometry (contract rules)
@pytest.mark.parametrize("size, box, expected", [
((320, 200), 256, (256, 160)), # public fixture
((200, 320), 256, (160, 256)),
((100, 50), 256, (100, 50)), # never upscale
((256, 256), 256, (256, 256)),
((1000, 1), 256, (256, 1)), # 0.256 px -> minimum 1 px
((1, 1000), 256, (1, 256)),
((257, 255), 256, (256, 254)), # 255 * 256 / 257 = 254.0 (floor)
((3000, 2000), 1280, (1280, 853)), # 853.33 -> 853
])
def test_fit_rounds_down_without_upscaling(size, box, expected):
assert fit(*size, box) == expected
def test_center_square():
assert center_square(320, 200) == (60, 0, 260, 200)
assert center_square(7, 10) == (0, 1, 7, 8)
def test_public_fixture_variants_match_the_contract():
out = variants(SAMPLE)
assert list(out) == ["thumbnail", "crop", "optimized"]
assert (out["thumbnail"].content_type, decoded(out["thumbnail"]).format, decoded(out["thumbnail"]).size) == \
("image/jpeg", "JPEG", (256, 160))
assert (out["crop"].content_type, decoded(out["crop"]).size) == ("image/jpeg", (128, 128))
assert (out["optimized"].content_type, decoded(out["optimized"]).format, decoded(out["optimized"]).size) == \
("image/webp", "WEBP", (320, 200)) # fits 1280 already: no upscale
for v in out.values():
assert (v.width, v.height) == decoded(v).size
def test_small_image_is_not_upscaled_but_crop_is():
out = variants(imagegen.png(40, 30))
assert decoded(out["thumbnail"]).size == (40, 30)
assert decoded(out["optimized"]).size == (40, 30)
assert decoded(out["crop"]).size == (128, 128)
def test_big_image_is_bounded_by_1280():
out = variants(imagegen.png(3000, 2000))
assert decoded(out["optimized"]).size == (1280, 853)
assert decoded(out["thumbnail"]).size == (256, 170)
def test_exif_orientation_is_applied_and_dropped():
# 60x20 stored landscape with Orientation=6 (rotate 90 CW): displayed portrait 20x60.
img = Image.new("RGB", (60, 20), (200, 30, 30))
exif = Image.Exif()
exif[0x0112] = 6
buf = io.BytesIO()
img.save(buf, "JPEG", exif=exif.tobytes(), quality=95)
out = variants(buf.getvalue(), "image/jpeg")
assert decoded(out["thumbnail"]).size == (20, 60)
assert decoded(out["optimized"]).size == (20, 60)
for v in out.values():
assert not decoded(v).getexif(), v.name
def test_alpha_is_composited_on_white_for_jpeg_and_kept_for_webp():
img = Image.new("RGBA", (64, 64), (255, 0, 0, 0)) # fully transparent red
buf = io.BytesIO()
img.save(buf, "PNG")
out = variants(buf.getvalue())
thumb = decoded(out["thumbnail"]).convert("RGB")
assert min(thumb.getpixel((32, 32))) >= 250, "transparent pixels must become white, not red/black"
webp = decoded(out["optimized"])
assert webp.mode == "RGBA" and webp.getpixel((10, 10))[3] == 0
def test_metadata_is_not_copied():
img = Image.new("RGB", (300, 300), (10, 200, 10))
exif = Image.Exif()
exif[0x010F] = "SecretCamera" # Make
buf = io.BytesIO()
img.save(buf, "JPEG", exif=exif.tobytes(), icc_profile=b"\0" * 128, comment=b"private")
out = variants(buf.getvalue(), "image/jpeg")
for name in ("thumbnail", "crop"):
data = out[name].data
assert b"Exif" not in data and b"ICC_PROFILE" not in data and b"SecretCamera" not in data, name
assert b"EXIF" not in out["optimized"].data and b"ICCP" not in out["optimized"].data
@pytest.mark.parametrize("mode", ["RGBA", "P", "1", "L", "LA", "RGB"])
def test_png_modes_are_processed(mode):
out = variants(imagegen.png(33, 17, mode))
assert decoded(out["thumbnail"]).size == (33, 17)
def test_16_bit_grey_is_scaled_not_clipped():
img = Image.new("I;16", (8, 8), 32768) # 50 % grey in 16 bits
buf = io.BytesIO()
img.save(buf, "PNG")
out = variants(buf.getvalue())
value = decoded(out["thumbnail"]).convert("L").getpixel((4, 4))
assert 120 <= value <= 135
def test_pipeline_versions_differ_in_bytes_not_in_geometry():
v1, v2 = variants(SAMPLE, version=1), variants(SAMPLE, version=2)
for name in v1:
assert (v1[name].width, v1[name].height) == (v2[name].width, v2[name].height)
assert v1[name].sha256 != v2[name].sha256
assert variants(SAMPLE, version=1)["thumbnail"].sha256 == v1["thumbnail"].sha256 # deterministic
def test_pixel_limit_is_checked_before_decoding():
# 8001 x 5000 = 40.005 Mpx with only a few rows of data: refused from the header (TooLarge);
# 20000 x 10000 is refused even earlier by Pillow's own bomb check (> 2 x MAX_IMAGE_PIXELS).
with pytest.raises(imaging.TooLarge):
imaging.build(imagegen.png_bomb_header(8001, 5000), "image/png", 1, LIMIT)
with pytest.raises((imaging.TooLarge, Image.DecompressionBombError)):
imaging.build(imagegen.png_bomb_header(), "image/png", 1, LIMIT)
def test_child_process_protocol_round_trip():
out = list(variants(SAMPLE).values())
raw = json.dumps({"variants": [{"name": v.name, "content_type": v.content_type, "width": v.width,
"height": v.height, "size": len(v.data)} for v in out]}).encode() + b"\n"
raw += b"".join(v.data for v in out)
parsed = imaging.parse_output(raw)
assert [(p.name, p.sha256) for p in parsed] == [(v.name, v.sha256) for v in out]
with pytest.raises(imaging.ProcessingError):
imaging.parse_output(raw[:-1])
# ------------------------------------------------------------------ message format
def test_encoded_message_matches_jobs_schema_and_carries_ids_only():
import datetime as dt
raw = broker.encode(str(uuid.uuid4()), str(uuid.uuid4()), 1, 2, dt.datetime.now(dt.timezone.utc))
body = json.loads(raw)
assert not list(Draft202012Validator(SCHEMA, format_checker=Draft202012Validator.FORMAT_CHECKER).iter_errors(body))
assert set(body) == {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"}
assert broker.decode(raw) == body
@pytest.mark.parametrize("change", [
{"schema_version": 2}, {"type": "other"}, {"job_id": "not-a-uuid"}, {"attempt": 0}, {"attempt": True},
{"pipeline_version": "1"}, {"created_at": "yesterday"}, {"url": "http://evil"}, {"object_key": "a/b"},
{"traceparent": "bad"},
])
def test_invalid_messages_are_rejected(change):
body = json.loads(broker.encode(str(uuid.uuid4()), str(uuid.uuid4()), 1, 1,
__import__("datetime").datetime(2026, 1, 1, tzinfo=__import__("datetime").timezone.utc)))
body.update(change)
with pytest.raises(broker.BadMessage):
broker.decode(json.dumps(body).encode())
# The contract schema refuses the same messages (date-time needs an optional jsonschema extra).
checker = Draft202012Validator.FORMAT_CHECKER
assert list(Draft202012Validator(SCHEMA, format_checker=checker).iter_errors(body)) or "created_at" in change
def test_garbage_is_rejected():
for raw in (b"", b"[]", b"{", b"\xff", b"x" * 5000):
with pytest.raises(broker.BadMessage):
broker.decode(raw)
# ------------------------------------------------------------------ backoff and configuration
def test_backoff_is_full_jitter_and_capped():
assert jobs.backoff_delay(1, 2, 60, rnd=lambda: 1.0) == 2
assert jobs.backoff_delay(3, 2, 60, rnd=lambda: 1.0) == 8
assert jobs.backoff_delay(10, 2, 60, rnd=lambda: 1.0) == 60
assert jobs.backoff_delay(4, 2, 60, rnd=lambda: 0.0) == 0
samples = [jobs.backoff_delay(3, 2, 60) for _ in range(500)]
assert 0 <= min(samples) < 2 and 6 < max(samples) <= 8 # spread over the whole window
def test_pipeline_settings(monkeypatch):
monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z")
monkeypatch.setenv("S3_ACCESS_KEY_ID", "AKTEST")
monkeypatch.setenv("S3_SECRET_ACCESS_KEY", "secret-for-unit-tests")
s = Settings.from_env()
assert (s.job_max_attempts, s.job_timeout_seconds, s.worker_concurrency, s.staging_retention_seconds) == (5, 60, 2, 86400)
assert s.s3_staging_bucket == "messenger-staging" and s.pipeline_version == 1
monkeypatch.setenv("FAULT_POINTS", "transient_error=3,slow")
s = Settings.from_env()
assert s.fault_points == {"transient_error", "slow"} and s.fault_value("transient_error") == 3
for name, value in (("PIPELINE_VERSION", "9"), ("JOB_MAX_ATTEMPTS", "0"), ("FAULT_POINTS", "slow=x"),
("S3_STAGING_BUCKET", "messenger-attachments"), ("JOB_RETRY_BASE_SECONDS", "100")):
monkeypatch.setenv(name, value)
with pytest.raises(ConfigError):
Settings.from_env()
monkeypatch.delenv(name)
assert set(PIPELINES) == {1, 2, 3}
+196
View File
@@ -0,0 +1,196 @@
"""Lab 6 unit tests of the instrumentation (no stand): in-memory span/log/metric exporters.
What must hold (README level 3/4, reviewer remarks to other students):
* the HTTP SERVER span CONTINUES an incoming W3C traceparent (same trace id, parent = caller span),
it is SERVER (not INTERNAL), named by the route TEMPLATE; 5xx = error, 4xx = not an error;
* metric attributes are low-cardinality only (no ids, no raw path); buckets fit seconds;
* the job message carries traceparent in the schema field (contracts/jobs.schema.json);
* log records carry trace_id/span_id of the active span; successful probes are not exported.
"""
from __future__ import annotations
import json
import logging
from pathlib import Path
import pytest
from jsonschema import Draft202012Validator
from opentelemetry import metrics, trace
from opentelemetry._logs import set_logger_provider
from opentelemetry.sdk._logs import LoggerProvider
from opentelemetry.sdk._logs.export import InMemoryLogRecordExporter, SimpleLogRecordProcessor
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.trace import SpanKind, StatusCode
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette.testclient import TestClient
from messenger import broker, telemetry
from messenger.app import RequestContextMiddleware, route_template
ROOT = Path(__file__).resolve().parents[2]
SPANS = InMemorySpanExporter()
LOGS = InMemoryLogRecordExporter()
METRICS = InMemoryMetricReader()
@pytest.fixture(scope="module", autouse=True)
def providers():
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(SPANS))
trace.set_tracer_provider(provider)
metrics.set_meter_provider(MeterProvider(metric_readers=[METRICS]))
log_provider = LoggerProvider()
log_provider.add_log_record_processor(SimpleLogRecordProcessor(LOGS))
set_logger_provider(log_provider)
handler = telemetry.OtlpLogHandler(log_provider)
logger = logging.getLogger("messenger")
level = logger.level
logger.addHandler(handler)
logger.setLevel(logging.INFO)
yield
logger.removeHandler(handler)
logger.setLevel(level)
async def item(request):
status = int(request.query_params.get("status", "200"))
logging.getLogger("messenger.test").info("item_served", extra={"fields": {"item": "x", "n": 1}})
return JSONResponse({"ok": True}, status_code=status)
async def health(request):
return JSONResponse({"status": "ok"})
def client() -> TestClient:
app = Starlette(routes=[Route("/api/v1/items/{item_id}", item, methods=["GET"]),
Route("/health/live", health, methods=["GET"])])
app.add_middleware(RequestContextMiddleware, instance_id="unit-1")
return TestClient(app)
def server_spans():
return [s for s in SPANS.get_finished_spans() if s.kind == SpanKind.SERVER]
def test_server_span_continues_incoming_traceparent():
SPANS.clear()
trace_id, parent = "4bf92f3577b34da6a3ce929d0e0e4736", "00f067aa0ba902b7"
response = client().get("/api/v1/items/123e4567-e89b-12d3-a456-426614174000",
headers={"traceparent": f"00-{trace_id}-{parent}-01"})
assert response.status_code == 200
assert response.headers["x-trace-id"] == trace_id
(span,) = server_spans()
assert format(span.context.trace_id, "032x") == trace_id
assert format(span.parent.span_id, "016x") == parent and span.parent.is_remote
assert span.name == "GET /api/v1/items/{item_id}" # template, not the UUID
assert span.attributes["http.route"] == "/api/v1/items/{item_id}"
assert span.attributes["http.response.status_code"] == 200
assert span.status.status_code == StatusCode.UNSET
assert "123e4567" not in json.dumps(dict(span.attributes)) # no raw path / ids in attributes
def test_without_traceparent_a_new_root_trace_is_started():
SPANS.clear()
response = client().get("/api/v1/items/1")
(span,) = server_spans()
assert span.parent is None
assert response.headers["x-trace-id"] == format(span.context.trace_id, "032x")
def test_5xx_is_an_error_4xx_is_not():
SPANS.clear()
client().get("/api/v1/items/1?status=503")
client().get("/api/v1/items/1?status=404")
by_code = {s.attributes["http.response.status_code"]: s for s in server_spans()}
assert by_code[503].status.status_code == StatusCode.ERROR
assert by_code[404].status.status_code == StatusCode.UNSET
def test_health_probes_get_no_span_and_unknown_paths_one_label():
SPANS.clear()
c = client()
assert c.get("/health/live").status_code == 200
assert c.get("/scanner/random/path/12345").status_code == 404
assert [s.name for s in server_spans()] == ["GET UNMATCHED"]
assert route_template({}) == "UNMATCHED"
def test_http_metric_attributes_are_low_cardinality_and_buckets_fit_seconds():
client().get("/api/v1/items/42?status=200")
data = METRICS.get_metrics_data()
points = [p for rm in data.resource_metrics for sm in rm.scope_metrics for m in sm.metrics
if m.name == "http.server.request.duration" for p in m.data.data_points]
assert points
for point in points:
assert set(point.attributes) == {"http.request.method", "http.route", "http.response.status_code",
"http.response.status_class"}
assert "42" not in str(point.attributes["http.route"])
assert list(points[0].explicit_bounds) == list(telemetry.HTTP_BUCKETS)
assert points[0].explicit_bounds[0] <= 0.001 # millisecond resolution, not 0/5/10 s
def test_job_message_carries_traceparent_in_the_schema_field():
schema = json.loads((ROOT / "contracts" / "jobs.schema.json").read_text(encoding="utf-8"))
tracer = trace.get_tracer("test")
with tracer.start_as_current_span("producer", kind=SpanKind.PRODUCER) as span:
carrier = telemetry.inject()
import datetime as dt
raw = broker.encode("11111111-1111-4111-8111-111111111111", "22222222-2222-4222-8222-222222222222", 1, 1,
dt.datetime(2026, 11, 16, tzinfo=dt.timezone.utc), carrier)
body = json.loads(raw)
assert list(Draft202012Validator(schema).iter_errors(body)) == []
# flags: 01 = sampled (+ 02 = "random trace id", W3C Trace Context level 2, newer SDKs)
ctx = span.get_span_context()
assert body["traceparent"][:52] == f"00-{format(ctx.trace_id, '032x')}-{format(ctx.span_id, '016x')}"
assert int(body["traceparent"][-2:], 16) & 1 == 1
assert broker.decode(raw)["traceparent"] == body["traceparent"]
# the consumer side: the extracted context makes the CONSUMER span a child of the producer
ctx = telemetry.extract(body["traceparent"], body.get("tracestate"))
with tracer.start_as_current_span("consumer", context=ctx, kind=SpanKind.CONSUMER) as consumer:
assert consumer.parent.span_id == span.get_span_context().span_id
def test_log_records_carry_trace_context_and_fields():
LOGS.clear()
SPANS.clear()
client().get("/api/v1/items/7", headers={"X-Request-Id": "unit-req-1"})
records = [r.log_record for r in LOGS.get_finished_logs()]
served = next(r for r in records if r.body == "item_served")
(span,) = server_spans()
assert served.trace_id == span.context.trace_id and served.span_id == span.context.span_id
assert served.attributes["item"] == "x" and served.attributes["n"] == 1
access = next(r for r in records if r.body == "request")
assert access.attributes["request_id"] == "unit-req-1"
assert access.attributes["route"] == "/api/v1/items/{item_id}"
assert access.trace_id == span.context.trace_id
def test_successful_probe_lines_are_not_exported_failed_ones_are():
LOGS.clear()
log = logging.getLogger("messenger.access")
log.info("request", extra={"fields": {"route": "/health/ready", "status": 200}})
log.info("request", extra={"fields": {"route": "/health/ready", "status": 503}})
log.info("request", extra={"fields": {"route": "/api/v1/chats", "status": 200}})
exported = [(r.log_record.attributes["route"], r.log_record.attributes["status"]) for r in LOGS.get_finished_logs()]
assert exported == [("/health/ready", 503), ("/api/v1/chats", 200)]
def test_child_span_only_inside_a_traced_operation():
SPANS.clear()
with telemetry.child_span("orphan") as span:
assert span is None # no root spans from background loops
tracer = trace.get_tracer("test")
with tracer.start_as_current_span("job"):
with pytest.raises(ValueError):
with telemetry.child_span("step") as span:
assert span is not None
raise ValueError("boom")
step = next(s for s in SPANS.get_finished_spans() if s.name == "step")
assert step.status.status_code == StatusCode.ERROR and step.attributes["error.type"] == "ValueError"
+225
View File
@@ -0,0 +1,225 @@
"""Pure functions, no services: validation, cursor, Authorization parsing, Argon2id, config."""
from __future__ import annotations
import asyncio
import base64
import datetime as dt
import pytest
from messenger import authhdr, cursor, passwords, validation
from messenger.config import ConfigError, Settings
from messenger.errors import InvalidRequest, Unauthorized
from messenger.timefmt import UTC, from_us, rfc3339, to_us
def b64(raw: bytes) -> str:
return base64.b64encode(raw).decode()
# ------------------------------------------------------------------ password rules
@pytest.mark.parametrize("password", ["Twelve-chars", "я" * 128, "пароль:с:двоеточиями", "😀" * 12, "a b c d e f g"])
def test_valid_passwords(password):
assert validation.password_field({"password": password}) == password
@pytest.mark.parametrize("password", ["short-11ch", "я" * 129, " " * 12, "\t\n " * 5, "\ud800" * 12, None, 123456789012])
def test_invalid_passwords(password):
with pytest.raises(InvalidRequest):
validation.password_field({"password": password})
def test_text_may_contain_nul_but_not_lone_surrogates():
assert validation.text_field({"t": "a\u0000b"}, "t", 10) == "a\u0000b"
with pytest.raises(InvalidRequest):
validation.text_field({"t": "a\ud800"}, "t", 10)
# ------------------------------------------------------------------ cursor
CHAT = "3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11"
def test_cursor_roundtrip_and_binding():
key = (to_us(dt.datetime(2026, 10, 12, 12, 0, 0, 123456, tzinfo=UTC)), "11111111-1111-4111-8111-111111111111")
token = cursor.encode(cursor.MESSAGES, CHAT, key)
assert cursor.decode(token, cursor.MESSAGES, CHAT) == key
with pytest.raises(InvalidRequest):
cursor.decode(token, cursor.MESSAGES, "00000000-0000-4000-8000-000000000000") # other chat
with pytest.raises(InvalidRequest):
cursor.decode(token, cursor.CHATS, CHAT) # other resource
@pytest.mark.parametrize("payload", [
b"v1|m|" + CHAT.encode() + b"|253402300800000000|11111111-1111-4111-8111-111111111111", # 1 us after 9999-12-31
b"v1|m|" + CHAT.encode() + b"|9999999999999999999|11111111-1111-4111-8111-111111111111", # int64 edge
b"v1|m|" + CHAT.encode() + b"|-1|11111111-1111-4111-8111-111111111111",
b"v1|m|" + CHAT.encode() + b"|1|not-a-uuid",
b"v1|m|" + CHAT.encode() + b"|1|11111111-1111-4111-8111-11111111111G",
b"v2|m|" + CHAT.encode() + b"|1|11111111-1111-4111-8111-111111111111",
])
def test_broken_cursors_are_400_not_500(payload):
token = base64.urlsafe_b64encode(payload).rstrip(b"=").decode()
with pytest.raises(InvalidRequest):
cursor.decode(token, cursor.MESSAGES, CHAT)
def test_time_helpers_are_exact():
moment = dt.datetime(2026, 2, 28, 23, 59, 59, 999999, tzinfo=UTC)
assert from_us(to_us(moment)) == moment
assert rfc3339(moment) == "2026-02-28T23:59:59.999999Z"
assert from_us(cursor.MAX_TS_US).year == 9999
# ------------------------------------------------------------------ Authorization header
def test_basic_is_parsed_and_password_may_contain_colons():
assert authhdr.parse_basic("Basic " + b64("alice:pa:ss:wörd".encode())) == ("alice", "pa:ss:wörd")
assert authhdr.parse_basic("basic " + b64(b"bob_1:x" * 1)) == ("bob_1", "x")
@pytest.mark.parametrize("header", [
None, "", "Basic", "Basic é", "Basic !!!!", "Basic " + b64(b"no-colon"), "Basic " + b64(b"\xff\xfe:pw"),
"Basic " + b64(b":password"), "Basic " + b64(b"alice:"), "Basic " + b64("Алиса:pw".encode()),
"Bearer " + "a" * 43, "Basic " + "A" * 2000,
])
def test_bad_basic_is_401_with_basic_challenge(header):
with pytest.raises(Unauthorized) as info:
authhdr.parse_basic(header)
assert info.value.headers["WWW-Authenticate"].startswith("Basic realm=\"messenger\"")
@pytest.mark.parametrize("header", [None, "", "Bearer", "Bearer short", "Bearer " + "a" * 43 + "!",
"Basic " + b64(b"alice:password-123"), "Token " + "a" * 43, "Bearer " + "é" * 43])
def test_bad_bearer_is_401_with_bearer_challenge(header):
with pytest.raises(Unauthorized) as info:
authhdr.parse_bearer(header)
assert info.value.headers["WWW-Authenticate"] == 'Bearer realm="messenger"'
def test_bearer_ok():
token = "A_b-" + "x" * 39
assert authhdr.parse_bearer("Bearer " + token) == token
# ------------------------------------------------------------------ Argon2id
def test_argon2id_hash_and_verify():
async def scenario():
stored = await passwords.hash_password("я" * 128)
assert stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$")
assert await passwords.verify_password(stored, "я" * 128)
assert not await passwords.verify_password(stored, "я" * 127)
assert not await passwords.verify_password(None, "anything") # unknown user, dummy hash
assert not await passwords.verify_password("not-a-hash", "anything")
assert await passwords.hash_password("same password!") != await passwords.hash_password("same password!") # salt
asyncio.run(scenario())
# ------------------------------------------------------------------ config
@pytest.fixture(autouse=True)
def s3_credentials(monkeypatch):
"""Lab 4: Settings require the API's S3 key pair; synthetic values for the unit tests."""
monkeypatch.setenv("S3_ACCESS_KEY_ID", "AKTEST")
monkeypatch.setenv("S3_SECRET_ACCESS_KEY", "secret-for-unit-tests")
def test_s3_settings_are_validated_and_contract_limits_cannot_be_raised(monkeypatch):
monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z")
settings = Settings.from_env()
assert (settings.max_upload_bytes, settings.max_image_pixels) == (10 * 1024 * 1024, 40_000_000)
assert settings.fault_points == frozenset() and settings.upload_concurrency == 4
for name, value in (("MAX_UPLOAD_BYTES", "10485761"), ("MAX_IMAGE_PIXELS", "40000001"),
("FAULT_POINTS", "drop_database"), ("S3_ENDPOINT", "ftp://s3"), ("S3_BUCKET", "Bad_Bucket")):
monkeypatch.setenv(name, value)
with pytest.raises(ConfigError):
Settings.from_env()
monkeypatch.delenv(name)
monkeypatch.delenv("S3_SECRET_ACCESS_KEY")
with pytest.raises(ConfigError):
Settings.from_env()
def test_settings_read_secret_files_and_contract_names(tmp_path, monkeypatch):
url_file = tmp_path / "database_url"
url_file.write_text("postgresql://u:p@db/x\n", encoding="utf-8")
monkeypatch.setenv("DATABASE_URL_FILE", str(url_file))
monkeypatch.setenv("SESSION_STORE", "redis")
monkeypatch.setenv("CACHE_URL", "redis://:p@valkey:6379/0")
monkeypatch.setenv("SESSION_TTL_SECONDS", "2")
settings = Settings.from_env()
assert settings.database_url == "postgresql://u:p@db/x"
assert settings.session_store == "valkey" and settings.session_ttl_seconds == 2
monkeypatch.setenv("SESSION_TTL_SECONDS", "0")
with pytest.raises(ConfigError):
Settings.from_env()
monkeypatch.setenv("SESSION_TTL_SECONDS", "2")
monkeypatch.setenv("DATABASE_URL_FILE", str(tmp_path / "missing"))
with pytest.raises(ConfigError) as info:
Settings.from_env()
assert "u:p" not in str(info.value)
# ------------------------------------------------------------------ lab 3: idempotency, JSON, instance id
@pytest.mark.parametrize("key", ["a", "k" * 128, "A-Za-z0-9._:-", "2026-10-16T10:00:00.1"])
def test_valid_idempotency_keys(key):
assert validation.idempotency_key(key) == key
@pytest.mark.parametrize("key", [None, "", "k" * 129, "ключ", "a b", "a/b", "a,b", "a\tb", "a\x00b", "*", "é"])
def test_invalid_idempotency_keys(key):
with pytest.raises(InvalidRequest):
validation.idempotency_key(key)
@pytest.mark.parametrize("raw", [b'{"text":"a","text":"b"}', b'{"a":{"x":1,"x":2}}', b'\xff', b'{"text":"x"} {}'])
def test_duplicate_keys_and_garbage_json_are_rejected(raw):
with pytest.raises(InvalidRequest):
validation.parse_json_object(raw)
def test_attachment_ids_absent_equals_empty_and_is_validated():
assert validation.attachment_ids_field({"text": "x"}) == []
assert validation.attachment_ids_field({"attachment_ids": []}) == []
one = "11111111-1111-4111-8111-111111111111"
assert validation.attachment_ids_field({"attachment_ids": [one.upper()]}) == [one]
for bad in (None, "x", [1], ["nope"], [one, one.upper()], [one] * 11):
with pytest.raises(InvalidRequest):
validation.attachment_ids_field({"attachment_ids": bad})
def test_request_fingerprint_ignores_key_order_and_default_attachments():
from messenger.app import request_fingerprint
assert request_fingerprint("привет", []) == request_fingerprint("привет", [])
assert request_fingerprint("привет", []) != request_fingerprint("привет ", [])
assert request_fingerprint("a\u0000b", []) != request_fingerprint("ab", [])
one = "11111111-1111-4111-8111-111111111111"
assert request_fingerprint("x", [one]) != request_fingerprint("x", [])
def test_instance_id_defaults_to_hostname_and_is_validated(monkeypatch):
import socket
monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z")
monkeypatch.delenv("INSTANCE_ID", raising=False)
assert Settings.from_env().instance_id == socket.gethostname()
monkeypatch.setenv("INSTANCE_ID", "replica-a")
assert Settings.from_env().instance_id == "replica-a"
for bad in ("with space", "x" * 65, "ip/1"):
monkeypatch.setenv("INSTANCE_ID", bad)
with pytest.raises(ConfigError):
Settings.from_env()
def test_idempotency_ttl_cannot_be_below_24_hours(monkeypatch):
monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z")
monkeypatch.setenv("IDEMPOTENCY_TTL_SECONDS", "3600")
with pytest.raises(ConfigError):
Settings.from_env()
def test_message_write_path_setting(monkeypatch):
monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z")
monkeypatch.delenv("MESSAGE_WRITE_PATH", raising=False)
assert Settings.from_env().message_write_path == "function"
monkeypatch.setenv("MESSAGE_WRITE_PATH", "multi")
assert Settings.from_env().message_write_path == "multi"
monkeypatch.setenv("MESSAGE_WRITE_PATH", "fast")
with pytest.raises(ConfigError):
Settings.from_env()