forked from mtusi2026/mtusi2026lab4
Реализовать lab4 на оценку 4: SeaweedFS, вложения и согласованность БД/S3.
Перенесён стенд lab3 (API, Redis-сессии, идемпотентность, HAProxy, реплики API). Добавлены приватный bucket SeaweedFS с отдельным ключом API, загрузка PNG/JPEG с лимитами и полной проверкой, компенсация и reconciler, плавная остановка API, тесты и evidence.
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
# Собственные проверки (lab4)
|
||||
|
||||
Нужен уже запущенный стенд (`scripts/up.cmd` / `scripts/up.sh`, ≥2 API за LB). Только stdlib Python.
|
||||
|
||||
```sh
|
||||
# из корня репозитория (Windows PowerShell: $env:PYTHONUTF8=1; $env:RUN_DOCKER_TESTS=1; ...)
|
||||
BASE_URL=http://127.0.0.1:8080 RUN_DOCKER_TESTS=1 RUN_DEPS_TEST=1 python student-tests/run_all.py
|
||||
# отдельный модуль:
|
||||
python student-tests/run_all.py test_attachments
|
||||
```
|
||||
|
||||
- `test_images_unit` — офлайн-проверка потокового валидатора PNG/JPEG (любое разбиение на куски, граница 40 млн пикселей, корпус повреждённых входов ревьюеров).
|
||||
- `test_attachments` — upload/download/ACL, лимиты 413 (ровно 10 485 760 байт → 201, +1 байт → 413, 8000×5001 → 413), повреждённые изображения и подмена MIME → 415, опасные filename и невалидный UTF-8/повтор `filename` в query → 400, чужое или неизвестное `attachment_id` → 404, порядок и идемпотентность `attachment_ids`.
|
||||
- `test_attachments_ops` (`RUN_DOCKER_TESTS=1`) — приватность bucket и права ключа API, отсутствие оригиналов на репликах, прерванные/зависшие загрузки, компенсация и reconciler, 16 параллельных загрузок 9.5 MiB без OOM у `s3`.
|
||||
- `test_shutdown` (`RUN_DOCKER_TESTS=1`, по очереди останавливает и возвращает одну API-реплику) — graceful shutdown: после SIGTERM `/health/ready` сразу 503, а обычные запросы обслуживаются всё окно drain (пробы изнутри реплики, процесс API — PID 1); `docker stop` реплики под нагрузкой через LB — 0 ошибок; загрузка, тело которой ещё идёт при закрытии listener, завершается 201.
|
||||
- `test_deps` (`RUN_DEPS_TEST=1`, останавливает зависимости!) — stop Redis, stop/pause PostgreSQL, stop S3: JSON 503 за ограниченное время и восстановление; хук `scripts/restart.*` действительно перезапускает API, PostgreSQL, Redis и S3.
|
||||
- `test_idempotency`, `test_sessions`, `test_concurrency`, `test_api` — перенесены из lab3 и дополнены (область ключа, формат ключа, текст с U+0000).
|
||||
|
||||
Для проверки истечения сессии поднимите API с `SESSION_TTL_SECONDS=2` и повторите `test_sessions`.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.8 KiB |
@@ -0,0 +1,17 @@
|
||||
"""Regenerate synthetic JPEG fixtures (needs Pillow; run once in a throwaway container):
|
||||
|
||||
docker run --rm -v "$PWD/student-tests/fixtures:/out" python:3.12.8-slim-bookworm \
|
||||
sh -c "pip install -q pillow==11.0.0 && python /out/make_jpeg_fixtures.py"
|
||||
"""
|
||||
|
||||
from PIL import Image
|
||||
|
||||
im = Image.new("RGB", (320, 200))
|
||||
px = im.load()
|
||||
for y in range(200):
|
||||
for x in range(320):
|
||||
px[x, y] = (x * 255 // 319, y * 255 // 199, (x + y) % 256)
|
||||
im.save("/out/sample.jpg", "JPEG", quality=85)
|
||||
im.save("/out/progressive.jpg", "JPEG", quality=80, progressive=True)
|
||||
im.convert("L").save("/out/gray.jpg", "JPEG", quality=80)
|
||||
print("ok")
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.4 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 5.3 KiB |
@@ -0,0 +1,94 @@
|
||||
"""Minimal HTTP helpers for student tests (stdlib only)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
|
||||
|
||||
|
||||
def call(method, path, expected=None, body=None, token=None, headers=None, raw=None):
|
||||
h = {"Accept": "application/json"}
|
||||
if token:
|
||||
h["Authorization"] = "Bearer " + token
|
||||
if body is not None:
|
||||
raw = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
h["Content-Type"] = "application/json"
|
||||
# Lab3+: POST messages require Idempotency-Key unless caller supplies headers.
|
||||
if (
|
||||
method == "POST"
|
||||
and path.rstrip("/").endswith("/messages")
|
||||
and (headers is None or "Idempotency-Key" not in headers)
|
||||
):
|
||||
h["Idempotency-Key"] = uuid.uuid4().hex
|
||||
h.update(headers or {})
|
||||
req = urllib.request.Request(BASE_URL + path, data=raw, headers=h, method=method)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=60)
|
||||
except urllib.error.HTTPError as err:
|
||||
resp = err
|
||||
data = resp.read()
|
||||
status = resp.code
|
||||
if expected is not None:
|
||||
assert status == expected, (
|
||||
f"{method} {path}: expected {expected}, got {status}: {data[:200]!r}"
|
||||
)
|
||||
payload = None
|
||||
ctype = resp.headers.get_content_type()
|
||||
if ctype == "application/json" and data:
|
||||
payload = json.loads(data.decode("utf-8"))
|
||||
assert resp.headers.get("X-Request-Id"), "missing X-Request-Id"
|
||||
assert resp.headers.get("X-Instance-Id"), "missing X-Instance-Id"
|
||||
return {"status": status, "headers": resp.headers, "json": payload, "bytes": data}
|
||||
|
||||
|
||||
def upload(token, chat_id, data, filename="photo.png", content_type="image/png", expected=None, headers=None):
|
||||
from urllib.parse import quote
|
||||
|
||||
h = {} if content_type is None else {"Content-Type": content_type}
|
||||
h.update(headers or {})
|
||||
query = "" if filename is None else "?filename=" + quote(filename, safe="")
|
||||
resp = call("POST", f"/api/v1/chats/{chat_id}/attachments{query}", expected, token=token, raw=data, headers=h)
|
||||
if expected is None or expected < 500:
|
||||
assert resp["status"] < 500, f"user error became {resp['status']}: {resp['json']}"
|
||||
return resp
|
||||
|
||||
|
||||
def chat_for(*actors, title="attachments"):
|
||||
return call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
token=actors[0]["token"],
|
||||
body={"title": title, "member_ids": [a["id"] for a in actors]},
|
||||
)["json"]
|
||||
|
||||
|
||||
def register(label: str):
|
||||
username = f"st_{label}_{uuid.uuid4().hex[:10]}"
|
||||
password = "T3st-" + uuid.uuid4().hex
|
||||
body = {
|
||||
"username": username,
|
||||
"display_name": f"Student {label}",
|
||||
"password": password,
|
||||
}
|
||||
user = call("POST", "/api/v1/users", 201, body=body)["json"]
|
||||
credential = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
session = call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
201,
|
||||
headers={"Authorization": "Basic " + credential},
|
||||
)["json"]
|
||||
return {
|
||||
"id": user["id"],
|
||||
"user": user,
|
||||
"token": session["token"],
|
||||
"registration": body,
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Synthetic PNG generation (stdlib only) for student tests and experiments."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import struct
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
FIXTURES = Path(__file__).resolve().parent / "fixtures"
|
||||
PUBLIC_PNG = Path(__file__).resolve().parents[1] / "tests" / "fixtures" / "sample.png"
|
||||
ADAM7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2))
|
||||
|
||||
|
||||
def chunk(kind: bytes, data: bytes) -> bytes:
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
||||
|
||||
|
||||
def png_from_raw(width: int, height: int, raw: bytes, *, depth: int = 8, color: int = 2,
|
||||
interlace: int = 0, level: int = 6, extra: bytes = b"", plte: bytes = b"") -> bytes:
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, depth, color, 0, 0, interlace)
|
||||
body = chunk(b"IHDR", ihdr) + extra
|
||||
if plte:
|
||||
body += chunk(b"PLTE", plte)
|
||||
return b"\x89PNG\r\n\x1a\n" + body + chunk(b"IDAT", zlib.compress(raw, level)) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def rgb_png(width: int, height: int, *, noise: bool = False, level: int = 6) -> bytes:
|
||||
if noise:
|
||||
rows = [b"\x00" + os.urandom(width * 3) for _ in range(height)]
|
||||
else:
|
||||
rows = [b"\x00" + bytes(((x + y) * 7) % 256 for x in range(width * 3)) for y in range(height)]
|
||||
return png_from_raw(width, height, b"".join(rows), level=level)
|
||||
|
||||
|
||||
def interlaced_rgb_png(width: int, height: int) -> bytes:
|
||||
def pixel(x: int, y: int) -> bytes:
|
||||
return bytes(((x * 31) % 256, (y * 17) % 256, ((x + y) * 5) % 256))
|
||||
|
||||
raw = bytearray()
|
||||
for x0, y0, dx, dy in ADAM7:
|
||||
xs = list(range(x0, width, dx))
|
||||
ys = list(range(y0, height, dy))
|
||||
if not xs or not ys:
|
||||
continue
|
||||
for y in ys:
|
||||
raw += b"\x00" + b"".join(pixel(x, y) for x in xs)
|
||||
return png_from_raw(width, height, bytes(raw), interlace=1)
|
||||
|
||||
|
||||
def gray1_png(width: int, height: int) -> bytes:
|
||||
"""1-bit grayscale: huge pixel counts in a tiny, perfectly valid file."""
|
||||
row = b"\x00" + b"\x55" * ((width + 7) // 8)
|
||||
return png_from_raw(width, height, row * height, depth=1, color=0, level=9)
|
||||
|
||||
|
||||
def palette_png(width: int, height: int) -> bytes:
|
||||
raw = b"".join(b"\x00" + bytes((x + y) % 4 for x in range(width)) for y in range(height))
|
||||
return png_from_raw(width, height, raw, depth=8, color=3, plte=bytes(range(12)))
|
||||
|
||||
|
||||
def png16_rgba(width: int, height: int) -> bytes:
|
||||
raw = b"".join(b"\x00" + bytes((x * 3 + y) % 256 for x in range(width * 8)) for y in range(height))
|
||||
return png_from_raw(width, height, raw, depth=16, color=6)
|
||||
|
||||
|
||||
def large_png(target_bytes: int) -> bytes:
|
||||
"""Incompressible RGB PNG of roughly target_bytes (stored with zlib level 0)."""
|
||||
width = 1024
|
||||
row = 1 + width * 3
|
||||
height = max(1, target_bytes // row)
|
||||
return rgb_png(width, height, noise=True, level=0)
|
||||
|
||||
|
||||
def exact_size_png(total_bytes: int) -> bytes:
|
||||
"""Valid PNG of exactly total_bytes: large_png padded with a tEXt chunk before IEND."""
|
||||
base = large_png(total_bytes - 64 * 1024)
|
||||
pad = total_bytes - len(base) - 12 - len(b"Comment\x00")
|
||||
assert pad >= 0
|
||||
text = chunk(b"tEXt", b"Comment\x00" + b"x" * pad)
|
||||
data = base[:-12] + text + base[-12:]
|
||||
assert len(data) == total_bytes
|
||||
return data
|
||||
|
||||
|
||||
def unknown_critical_chunk_png() -> bytes:
|
||||
return png_from_raw(2, 2, b"\x00" + b"\x10" * 6 + b"\x00" + b"\x20" * 6, extra=chunk(b"ABCD", b"x"))
|
||||
|
||||
|
||||
def fixture(name: str) -> bytes:
|
||||
return (FIXTURES / name).read_bytes()
|
||||
|
||||
|
||||
def all_filters_png(width: int, height: int, *, interlace: int = 0) -> bytes:
|
||||
"""Valid PNG whose scanlines cycle through filter types 0..4 (any bytes unfilter fine)."""
|
||||
passes = ADAM7 if interlace else ((0, 0, 1, 1),)
|
||||
raw = bytearray()
|
||||
row_no = 0
|
||||
for x0, y0, dx, dy in passes:
|
||||
pw = len(range(x0, width, dx))
|
||||
ph = len(range(y0, height, dy))
|
||||
if not pw or not ph:
|
||||
continue
|
||||
for _ in range(ph):
|
||||
raw.append(row_no % 5)
|
||||
raw += bytes((row_no * 13 + i) % 256 for i in range(pw * 3))
|
||||
row_no += 1
|
||||
return png_from_raw(width, height, bytes(raw), interlace=interlace)
|
||||
|
||||
|
||||
def _with_bad_idat(png: bytes) -> bytes:
|
||||
"""Same PNG, IDAT payload damaged in the middle, CRC recomputed (valid chunk framing)."""
|
||||
i = png.index(b"IDAT")
|
||||
length = struct.unpack(">I", png[i - 4:i])[0]
|
||||
data = bytearray(png[i + 4:i + 4 + length])
|
||||
data[len(data) // 2] ^= 0xFF
|
||||
data[len(data) // 2 + 1] ^= 0x55
|
||||
return png[:i - 4] + chunk(b"IDAT", bytes(data)) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def corrupted_pngs() -> dict:
|
||||
"""Inputs used by reviewers with an independent decoder: all must be 415."""
|
||||
public = PUBLIC_PNG.read_bytes()
|
||||
raw = bytearray()
|
||||
for x0, y0, dx, dy in ADAM7:
|
||||
pw, ph = len(range(x0, 9, dx)), len(range(y0, 9, dy))
|
||||
for _ in range(ph if pw else 0):
|
||||
raw += b"\x00" + bytes(pw * 3)
|
||||
raw[-(1 + 9 * 3)] = 7 # last scanline of the last Adam7 pass
|
||||
return {
|
||||
"first_33_bytes_of_sample_png": public[:33],
|
||||
"sample_png_truncated_half": public[: len(public) // 2],
|
||||
"broken_idat_stream_valid_crc": _with_bad_idat(rgb_png(64, 64)),
|
||||
"filter_byte_05": png_from_raw(1, 1, b"\x05\x00\x00\x00"),
|
||||
"filter_byte_ff": png_from_raw(1, 1, b"\xff\x00\x00\x00"),
|
||||
"interlaced_filter_byte_07": png_from_raw(9, 9, bytes(raw), interlace=1),
|
||||
"plte_257_entries": png_from_raw(1, 1, b"\x00\x00", color=3, plte=bytes(771)),
|
||||
"plte_not_multiple_of_3": png_from_raw(1, 1, b"\x00\x00", color=3, plte=bytes(4)),
|
||||
"plte_too_long_for_1bit": png_from_raw(1, 1, b"\x00\x00", depth=1, color=3, plte=bytes(9)),
|
||||
"plte_in_grayscale": png_from_raw(1, 1, b"\x00\x00", depth=8, color=0, plte=bytes(3)),
|
||||
"unknown_critical_chunk": unknown_critical_chunk_png(),
|
||||
}
|
||||
|
||||
|
||||
def corrupted_jpegs() -> dict:
|
||||
sample = fixture("sample.jpg")
|
||||
progressive = fixture("progressive.jpg")
|
||||
sos = sample.index(b"\xff\xda")
|
||||
sos_len = struct.unpack(">H", sample[sos + 2:sos + 4])[0]
|
||||
twelve_bit = bytearray(sample)
|
||||
twelve_bit[sample.index(b"\xff\xc0") + 4] = 12
|
||||
return {
|
||||
"jpeg_27_bytes_no_tables": bytes.fromhex("ffd8ffc0000b080001000101011100ffda0008010100003f00ffd9"),
|
||||
"jpeg_18_bytes": bytes.fromhex("ffd8ffc00008080001000101ffda0002ffd9"),
|
||||
"jpeg_no_data_after_sos": sample[: sos + 2 + sos_len] + b"\xff\xd9",
|
||||
"jpeg_half_plus_eoi": sample[: len(sample) // 2] + b"\xff\xd9",
|
||||
"progressive_half_plus_eoi": progressive[: len(progressive) // 2] + b"\xff\xd9",
|
||||
"jpeg_truncated_no_eoi": sample[:-200],
|
||||
"jpeg_12_bit": bytes(twelve_bit),
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run all student tests against a live API (BASE_URL)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
|
||||
MODULES = [
|
||||
"test_images_unit",
|
||||
"test_api",
|
||||
"test_concurrency",
|
||||
"test_sessions",
|
||||
"test_idempotency",
|
||||
"test_attachments",
|
||||
"test_attachments_ops",
|
||||
"test_shutdown",
|
||||
"test_deps",
|
||||
]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
failed = 0
|
||||
passed = 0
|
||||
only = set(sys.argv[1:])
|
||||
for name in MODULES:
|
||||
if only and name not in only:
|
||||
continue
|
||||
mod = importlib.import_module(name)
|
||||
tests = [getattr(mod, n) for n in dir(mod) if n.startswith("test_")]
|
||||
for fn in tests:
|
||||
label = f"{name}.{fn.__name__}"
|
||||
try:
|
||||
fn()
|
||||
print("OK", label)
|
||||
passed += 1
|
||||
except Exception as exc:
|
||||
failed += 1
|
||||
print("FAIL", label, ":", exc)
|
||||
traceback.print_exc()
|
||||
print(f"Summary: {passed} passed, {failed} failed")
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.path.insert(0, ".")
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,185 @@
|
||||
"""Grade 3/4 API checks: auth, conflict, X-User-Id ignored, logout."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from helpers import call, register
|
||||
|
||||
|
||||
def test_username_conflict():
|
||||
a = register("conflict")
|
||||
body = dict(a["registration"])
|
||||
call("POST", "/api/v1/users", 409, body=body)
|
||||
|
||||
|
||||
def test_wrong_password():
|
||||
a = register("wrongpw")
|
||||
bad = base64.b64encode(
|
||||
(a["registration"]["username"] + ":wrong-password-xx").encode()
|
||||
).decode()
|
||||
resp = call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
401,
|
||||
headers={"Authorization": "Basic " + bad},
|
||||
)
|
||||
assert resp["headers"].get("WWW-Authenticate", "").lower().startswith("basic")
|
||||
|
||||
|
||||
def test_x_user_id_ignored():
|
||||
a = register("xu")
|
||||
b = register("xv")
|
||||
me = call(
|
||||
"GET",
|
||||
"/api/v1/users/me",
|
||||
200,
|
||||
token=a["token"],
|
||||
headers={"X-User-Id": b["id"]},
|
||||
)["json"]
|
||||
assert me["id"] == a["id"]
|
||||
|
||||
|
||||
def test_basic_on_business_rejected():
|
||||
a = register("basicbiz")
|
||||
cred = base64.b64encode(
|
||||
(a["registration"]["username"] + ":" + a["registration"]["password"]).encode()
|
||||
).decode()
|
||||
call(
|
||||
"GET",
|
||||
"/api/v1/users/me",
|
||||
401,
|
||||
headers={"Authorization": "Basic " + cred},
|
||||
)
|
||||
|
||||
|
||||
def test_logout_revokes():
|
||||
a = register("logout")
|
||||
call("DELETE", "/api/v1/auth/sessions/current", 204, token=a["token"])
|
||||
call("GET", "/api/v1/users/me", 401, token=a["token"])
|
||||
|
||||
|
||||
def test_chat_requires_caller_member():
|
||||
a = register("owner")
|
||||
b = register("peer")
|
||||
call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
400,
|
||||
token=a["token"],
|
||||
body={"title": "no me", "member_ids": [b["id"]]},
|
||||
)
|
||||
|
||||
|
||||
def test_unknown_member_rolls_back():
|
||||
a = register("atom")
|
||||
fake = str(uuid.uuid4())
|
||||
call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
400,
|
||||
token=a["token"],
|
||||
body={"title": "bad", "member_ids": [a["id"], fake]},
|
||||
)
|
||||
|
||||
|
||||
def test_whitespace_only_password_rejected():
|
||||
# Maintainer remark: required strings must not be whitespace-only.
|
||||
body = {
|
||||
"username": "ws_" + uuid.uuid4().hex[:10],
|
||||
"display_name": "Spaces",
|
||||
"password": " " * 12,
|
||||
}
|
||||
call("POST", "/api/v1/users", 400, body=body)
|
||||
|
||||
|
||||
def test_username_trailing_newline_400():
|
||||
# The pattern must match the whole value: "name\n" is not a valid username.
|
||||
for username in ("review123\n", "review123\r\n", "\nreview123"):
|
||||
resp = call("POST", "/api/v1/users", 400,
|
||||
body={"username": username, "display_name": "x", "password": "T3st-" + uuid.uuid4().hex})
|
||||
assert resp["json"]["error"]["code"] == "invalid_request", repr(username)
|
||||
|
||||
|
||||
def test_malformed_cursor_400():
|
||||
a = register("cursor")
|
||||
chat = call("POST", "/api/v1/chats", 201, token=a["token"], body={"title": "c", "member_ids": [a["id"]]})["json"]
|
||||
|
||||
def b64(raw: str) -> str:
|
||||
return base64.urlsafe_b64encode(raw.encode()).decode()
|
||||
|
||||
bad = ["not-base64!!", b64("messages|not-a-date|" + str(uuid.uuid4())),
|
||||
b64("messages|2026-01-01T00:00:00Z|not-a-uuid"), b64("chats|2026-01-01T00:00:00Z|" + str(uuid.uuid4()))]
|
||||
for cursor in bad:
|
||||
call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor={cursor}", 400, token=a["token"])
|
||||
for cursor in bad[:3]:
|
||||
call("GET", f"/api/v1/chats?cursor={cursor}", 400, token=a["token"])
|
||||
|
||||
|
||||
def test_nul_in_text_roundtrip():
|
||||
# U+0000 is valid message text: exact in the response, history and idempotent replay.
|
||||
a = register("nul")
|
||||
peer = register("nulb")
|
||||
chat = call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
token=a["token"],
|
||||
body={"title": "nul-chat", "member_ids": [a["id"], peer["id"]]},
|
||||
)["json"]
|
||||
text = "abc\u0000def \\0 \\u0000"
|
||||
key = {"Idempotency-Key": "nul-" + uuid.uuid4().hex}
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
first = call("POST", path, 201, token=a["token"], body={"text": text}, headers=key)["json"]
|
||||
assert first["text"] == text
|
||||
again = call("POST", path, 201, token=a["token"], body={"text": text}, headers=key)["json"]
|
||||
assert again == first
|
||||
items = call("GET", path, 200, token=peer["token"])["json"]["items"]
|
||||
assert [m["text"] for m in items if m["id"] == first["id"]] == [text]
|
||||
|
||||
|
||||
def test_login_rejects_json_body():
|
||||
a = register("bodylogin")
|
||||
cred = base64.b64encode(
|
||||
(a["registration"]["username"] + ":" + a["registration"]["password"]).encode()
|
||||
).decode()
|
||||
call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
400,
|
||||
body={"unexpected": True},
|
||||
headers={"Authorization": "Basic " + cred},
|
||||
)
|
||||
|
||||
|
||||
def test_invalid_basic_encoding_is_401():
|
||||
# Maintainer remark: malformed Basic must be 401, not 500.
|
||||
call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
401,
|
||||
headers={"Authorization": "Basic " + base64.b64encode("é".encode()).decode()},
|
||||
)
|
||||
|
||||
|
||||
def test_unsupported_media_type():
|
||||
a = register("ctype")
|
||||
peer = register("ctypeb")
|
||||
chat = call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
token=a["token"],
|
||||
body={"title": "ctype", "member_ids": [a["id"], peer["id"]]},
|
||||
)["json"]
|
||||
raw = b'{"text":"x"}'
|
||||
call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
415,
|
||||
token=a["token"],
|
||||
raw=raw,
|
||||
headers={"Content-Type": "text/plain"},
|
||||
)
|
||||
@@ -0,0 +1,355 @@
|
||||
"""Lab4 grade 3/4: attachment upload/download, ACL, limits, MIME sniffing, filenames."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import http.client
|
||||
import socket
|
||||
import time
|
||||
import urllib.parse
|
||||
import uuid
|
||||
|
||||
import imagegen
|
||||
from helpers import BASE_URL, call, chat_for, register, upload
|
||||
|
||||
MIB = 1024 * 1024
|
||||
LIMIT = 10 * MIB
|
||||
|
||||
|
||||
def _trio():
|
||||
alice, bob, eve = register("att_a"), register("att_b"), register("att_e")
|
||||
return alice, bob, eve, chat_for(alice, bob)
|
||||
|
||||
|
||||
def _png(seed: int = 0) -> bytes:
|
||||
return imagegen.rgb_png(16 + seed % 7, 9 + seed % 5)
|
||||
|
||||
|
||||
def _download(token, att_id, expected=200, query=""):
|
||||
return call("GET", f"/api/v1/attachments/{att_id}/content{query}", expected, token=token)
|
||||
|
||||
|
||||
def _message(actor, chat, text, attachment_ids=None, expected=201, key=None):
|
||||
body = {"text": text}
|
||||
if attachment_ids is not None:
|
||||
body["attachment_ids"] = attachment_ids
|
||||
return call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
expected,
|
||||
token=actor["token"],
|
||||
body=body,
|
||||
headers={"Idempotency-Key": key or uuid.uuid4().hex},
|
||||
)
|
||||
|
||||
|
||||
def test_upload_roundtrip_png_and_jpeg_variants():
|
||||
alice, bob, _eve, chat = _trio()
|
||||
cases = [
|
||||
(imagegen.PUBLIC_PNG.read_bytes(), "image/png", "sample.png"),
|
||||
(imagegen.fixture("sample.jpg"), "image/jpeg", "sample.jpg"),
|
||||
(imagegen.fixture("progressive.jpg"), "image/jpeg", "progressive.jpg"),
|
||||
(imagegen.fixture("gray.jpg"), "image/jpeg", "gray.jpg"),
|
||||
(imagegen.interlaced_rgb_png(41, 29), "image/png", "adam7.png"),
|
||||
(imagegen.palette_png(12, 7), "image/png", "palette.png"),
|
||||
]
|
||||
for data, ctype, name in cases:
|
||||
resp = upload(alice["token"], chat["id"], data, name, ctype, 201)
|
||||
att = resp["json"]
|
||||
assert att["status"] == "ready" and att["variants"] == [] and att["error_code"] is None, att
|
||||
assert att["chat_id"] == chat["id"] and att["owner_id"] == alice["id"]
|
||||
assert att["content_type"] == ctype and att["filename"] == name
|
||||
assert att["size_bytes"] == len(data) and att["sha256"] == hashlib.sha256(data).hexdigest()
|
||||
assert set(att) == {"id", "chat_id", "owner_id", "filename", "content_type", "size_bytes",
|
||||
"sha256", "status", "variants", "error_code", "created_at", "updated_at"}
|
||||
assert resp["headers"].get("Location") == "/api/v1/attachments/" + att["id"]
|
||||
meta = call("GET", "/api/v1/attachments/" + att["id"], 200, token=bob["token"])["json"]
|
||||
assert meta == att
|
||||
dl = _download(bob["token"], att["id"])
|
||||
assert dl["bytes"] == data, name
|
||||
assert dl["headers"].get_content_type() == ctype
|
||||
assert dl["headers"].get("Content-Length") == str(len(data))
|
||||
assert dl["headers"].get("X-Content-Type-Options") == "nosniff"
|
||||
assert dl["headers"].get("ETag") == '"' + att["sha256"] + '"'
|
||||
|
||||
|
||||
def test_outsider_and_unknown_get_404():
|
||||
alice, _bob, eve, chat = _trio()
|
||||
att = upload(alice["token"], chat["id"], _png(), "secret.png", "image/png", 201)["json"]
|
||||
for suffix in ("", "/content", "/content?variant=original"):
|
||||
resp = call("GET", "/api/v1/attachments/" + att["id"] + suffix, 404, token=eve["token"])
|
||||
assert resp["json"]["error"]["code"] == "not_found"
|
||||
unknown = str(uuid.uuid4())
|
||||
call("GET", "/api/v1/attachments/" + unknown, 404, token=alice["token"])
|
||||
call("GET", "/api/v1/attachments/" + unknown + "/content", 404, token=alice["token"])
|
||||
call("GET", "/api/v1/attachments/not-a-uuid", 400, token=alice["token"])
|
||||
call("GET", "/api/v1/attachments/" + att["id"], 401)
|
||||
call("GET", "/api/v1/attachments/" + att["id"] + "/content", 401)
|
||||
# Outsider cannot upload into the chat either.
|
||||
upload(eve["token"], chat["id"], _png(), "x.png", "image/png", 404)
|
||||
|
||||
|
||||
def test_upload_auth_and_chat_checks():
|
||||
alice, _bob, _eve, chat = _trio()
|
||||
upload(None, chat["id"], _png(), "x.png", "image/png", 401)
|
||||
upload(alice["token"], str(uuid.uuid4()), _png(), "x.png", "image/png", 404)
|
||||
upload(alice["token"], "not-a-uuid", _png(), "x.png", "image/png", 400)
|
||||
|
||||
|
||||
def test_message_with_attachments_and_history():
|
||||
alice, bob, _eve, chat = _trio()
|
||||
a1 = upload(alice["token"], chat["id"], _png(1), "one.png", "image/png", 201)["json"]
|
||||
a2 = upload(bob["token"], chat["id"], _png(2), "two.png", "image/png", 201)["json"]
|
||||
key = uuid.uuid4().hex
|
||||
msg = _message(bob, chat, "", [a2["id"], a1["id"]], key=key)["json"]
|
||||
assert msg["attachment_ids"] == [a2["id"], a1["id"]] and msg["text"] == ""
|
||||
replay = _message(bob, chat, "", [a2["id"], a1["id"]], key=key)["json"]
|
||||
assert replay == msg
|
||||
_message(bob, chat, "", [a1["id"], a2["id"]], expected=409, key=key)
|
||||
plain_key = uuid.uuid4().hex
|
||||
plain = _message(alice, chat, "без вложений", key=plain_key)["json"]
|
||||
assert plain["attachment_ids"] == []
|
||||
# Absent attachment_ids ≡ []: same key replays the same message, another set conflicts.
|
||||
assert _message(alice, chat, "без вложений", [], key=plain_key)["json"] == plain
|
||||
_message(alice, chat, "без вложений", [a1["id"]], expected=409, key=plain_key)
|
||||
# Any member may reference any attachment of the chat, also repeatedly.
|
||||
again = _message(alice, chat, "ещё раз", [a2["id"]])["json"]
|
||||
assert again["attachment_ids"] == [a2["id"]]
|
||||
page = call("GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", 200, token=alice["token"])["json"]
|
||||
by_id = {m["id"]: m for m in page["items"]}
|
||||
assert by_id[msg["id"]]["attachment_ids"] == [a2["id"], a1["id"]]
|
||||
assert by_id[plain["id"]]["attachment_ids"] == []
|
||||
assert by_id[again["id"]]["attachment_ids"] == [a2["id"]]
|
||||
|
||||
|
||||
def test_foreign_and_unknown_attachment_ids_404():
|
||||
alice, bob, eve, chat = _trio()
|
||||
other = chat_for(alice, eve, title="other chat")
|
||||
foreign = upload(alice["token"], other["id"], _png(3), "other.png", "image/png", 201)["json"]
|
||||
own = upload(alice["token"], chat["id"], _png(4), "own.png", "image/png", 201)["json"]
|
||||
# File of another chat (even uploaded by the same user) cannot be attached.
|
||||
resp = _message(alice, chat, "чужой файл", [foreign["id"]], expected=404)
|
||||
assert resp["json"]["error"]["code"] == "not_found"
|
||||
_message(alice, chat, "смесь", [own["id"], foreign["id"]], expected=404)
|
||||
_message(bob, chat, "неизвестный", [str(uuid.uuid4())], expected=404)
|
||||
# Eve is in `other` only: cannot attach chat's file there.
|
||||
_message(eve, other, "украсть", [own["id"]], expected=404)
|
||||
# Failed attempts did not create messages.
|
||||
page = call("GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", 200, token=bob["token"])["json"]
|
||||
assert page["items"] == []
|
||||
|
||||
|
||||
def test_attachment_ids_validation_400():
|
||||
alice, _bob, _eve, chat = _trio()
|
||||
att = upload(alice["token"], chat["id"], _png(), "v.png", "image/png", 201)["json"]
|
||||
many = [str(uuid.uuid4()) for _ in range(11)]
|
||||
for bad in (many, [att["id"], att["id"]], ["not-a-uuid"], [123], "x", {"id": att["id"]}):
|
||||
_message(alice, chat, "x", bad, expected=400)
|
||||
call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
400,
|
||||
token=alice["token"],
|
||||
body={"text": "x", "attachment_ids": None},
|
||||
)
|
||||
_message(alice, chat, "", [], expected=400)
|
||||
_message(alice, chat, " ", None, expected=400)
|
||||
_message(alice, chat, " ", [att["id"]])
|
||||
|
||||
|
||||
def test_too_large_413():
|
||||
alice, _bob, _eve, chat = _trio()
|
||||
big = imagegen.large_png(LIMIT + 64 * 1024)
|
||||
assert len(big) > LIMIT
|
||||
resp = upload(alice["token"], chat["id"], big, "big.png", "image/png", 413)
|
||||
assert resp["json"]["error"]["code"] == "payload_too_large"
|
||||
# Same oversized body without Content-Length (chunked): detected while streaming.
|
||||
parsed = urllib.parse.urlparse(BASE_URL)
|
||||
conn = http.client.HTTPConnection(parsed.hostname, parsed.port or 80, timeout=60)
|
||||
|
||||
def body():
|
||||
for i in range(0, len(big), 256 * 1024):
|
||||
yield big[i:i + 256 * 1024]
|
||||
|
||||
conn.request(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=big.png",
|
||||
body=body(),
|
||||
headers={"Authorization": "Bearer " + alice["token"], "Content-Type": "image/png"},
|
||||
encode_chunked=True,
|
||||
)
|
||||
r = conn.getresponse()
|
||||
r.read()
|
||||
conn.close()
|
||||
assert r.status == 413, r.status
|
||||
|
||||
|
||||
def test_near_limit_real_png_accepted():
|
||||
alice, bob, _eve, chat = _trio()
|
||||
data = imagegen.large_png(LIMIT - 256 * 1024)
|
||||
assert len(data) <= LIMIT
|
||||
att = upload(alice["token"], chat["id"], data, "near-limit.png", "image/png", 201)["json"]
|
||||
dl = _download(bob["token"], att["id"])
|
||||
assert hashlib.sha256(dl["bytes"]).hexdigest() == att["sha256"] == hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def test_exact_limit_png_through_lb_accepted():
|
||||
# 10 485 760 bytes exactly passes the LB and the API; one more byte is JSON 413 from the API.
|
||||
alice, bob, _eve, chat = _trio()
|
||||
data = imagegen.exact_size_png(LIMIT)
|
||||
att = upload(alice["token"], chat["id"], data, "exact.png", "image/png", 201)["json"]
|
||||
assert att["size_bytes"] == LIMIT
|
||||
assert hashlib.sha256(_download(bob["token"], att["id"])["bytes"]).hexdigest() == hashlib.sha256(data).hexdigest()
|
||||
resp = upload(alice["token"], chat["id"], imagegen.exact_size_png(LIMIT + 1), "plus1.png", "image/png", 413)
|
||||
assert resp["json"]["error"]["code"] == "payload_too_large"
|
||||
|
||||
|
||||
def test_too_many_pixels_413():
|
||||
alice, _bob, _eve, chat = _trio()
|
||||
bomb = imagegen.gray1_png(8000, 5001) # 40 008 000 px in a few KiB
|
||||
assert len(bomb) < 64 * 1024
|
||||
resp = upload(alice["token"], chat["id"], bomb, "bomb.png", "image/png", 413)
|
||||
assert resp["json"]["error"]["code"] == "payload_too_large"
|
||||
upload(alice["token"], chat["id"], imagegen.gray1_png(8000, 5000), "limit.png", "image/png", 201)
|
||||
|
||||
|
||||
def test_corrupted_images_415():
|
||||
alice, _bob, _eve, chat = _trio()
|
||||
png = _png(5)
|
||||
flipped = bytearray(png)
|
||||
flipped[-20] ^= 0xFF
|
||||
jpeg = imagegen.fixture("sample.jpg")
|
||||
for data, ctype in (
|
||||
(png[: len(png) // 2], "image/png"),
|
||||
(bytes(flipped), "image/png"),
|
||||
(png + b"<script>", "image/png"),
|
||||
(jpeg[: len(jpeg) - 200], "image/jpeg"),
|
||||
(b"\xff\xd8\xff\xe0" + bytes(range(256)) * 8, "image/jpeg"),
|
||||
(b"\x89PNG\r\n\x1a\n" + b"\x00" * 64, "image/png"),
|
||||
):
|
||||
resp = upload(alice["token"], chat["id"], data, "broken", ctype, 415)
|
||||
assert resp["json"]["error"]["code"] == "unsupported_media_type"
|
||||
|
||||
|
||||
def test_reviewer_corrupted_images_415():
|
||||
# Same inputs reviewers verify with an independent decoder; valid edge cases stay 201.
|
||||
alice, bob, _eve, chat = _trio()
|
||||
for name, data in imagegen.corrupted_pngs().items():
|
||||
resp = upload(alice["token"], chat["id"], data, name + ".png", "image/png", 415)
|
||||
assert resp["json"]["error"]["code"] == "unsupported_media_type", name
|
||||
for name, data in imagegen.corrupted_jpegs().items():
|
||||
resp = upload(alice["token"], chat["id"], data, name + ".jpg", "image/jpeg", 415)
|
||||
assert resp["json"]["error"]["code"] == "unsupported_media_type", name
|
||||
for data, ctype in ((imagegen.all_filters_png(33, 20, interlace=1), "image/png"),
|
||||
(imagegen.fixture("progressive.jpg") + b"trailing", "image/jpeg")):
|
||||
att = upload(alice["token"], chat["id"], data, "edge", ctype, 201)["json"]
|
||||
assert _download(bob["token"], att["id"])["bytes"] == data
|
||||
page = call("GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", 200, token=bob["token"])["json"]
|
||||
assert page["items"] == []
|
||||
|
||||
|
||||
def test_mime_spoofing_415():
|
||||
alice, _bob, _eve, chat = _trio()
|
||||
png = _png(6)
|
||||
jpeg = imagegen.fixture("sample.jpg")
|
||||
cases = [
|
||||
(b"GIF89a\x01\x00\x01\x00\x00\x00\x00;", "image/png"),
|
||||
(b"%PDF-1.7\n%\xe2\xe3\xcf\xd3\n", "image/jpeg"),
|
||||
(b"<html><script>alert(1)</script></html>", "image/png"),
|
||||
(b"MZ\x90\x00\x03\x00\x00\x00", "image/jpeg"),
|
||||
(jpeg, "image/png"),
|
||||
(png, "image/jpeg"),
|
||||
(png, "text/plain"),
|
||||
(png, "image/gif"),
|
||||
(png, "multipart/form-data; boundary=x"),
|
||||
(png, "application/octet-stream"),
|
||||
]
|
||||
for data, ctype in cases:
|
||||
resp = upload(alice["token"], chat["id"], data, "spoof.png", ctype, 415)
|
||||
assert resp["json"]["error"]["code"] == "unsupported_media_type", ctype
|
||||
|
||||
|
||||
def test_dangerous_filenames_400_and_unicode_kept():
|
||||
alice, bob, _eve, chat = _trio()
|
||||
png = _png(7)
|
||||
for name in ("../etc/passwd", "../x.png", "a/b.png", "a\\b.png", "x\x00.png", "x\n.png", "x\r.png",
|
||||
"del\x7f.png", "c1\x85.png",
|
||||
"tab\t.png", "\u202egnp.exe", "zero\u200bwidth.png", "", " ", ".", "..", "a" * 256):
|
||||
resp = upload(alice["token"], chat["id"], png, name, "image/png", 400)
|
||||
assert resp["json"]["error"]["code"] == "invalid_request", repr(name)
|
||||
upload(alice["token"], chat["id"], png, None, "image/png", 400)
|
||||
for name in ("фото отпуска 😀.png", "b" * 255, "with space & ampersand;=.png"):
|
||||
att = upload(alice["token"], chat["id"], png, name, "image/png", 201)["json"]
|
||||
assert att["filename"] == name
|
||||
call("GET", "/api/v1/attachments/" + att["id"], 200, token=bob["token"])
|
||||
|
||||
|
||||
def test_filename_query_decoded_strictly_400():
|
||||
# Invalid UTF-8 must not be "sanitized" into U+FFFD; an ambiguous repeated filename is rejected too.
|
||||
alice, _bob, _eve, chat = _trio()
|
||||
png = _png(10)
|
||||
path = f"/api/v1/chats/{chat['id']}/attachments"
|
||||
for query in ("?filename=%FF%FE.png", "?filename=%C3.png", "?filename=%ED%A0%80.png",
|
||||
"?filename=ok.png&filename=a%2Fb", "?filename=a.png&filename=b.png"):
|
||||
resp = call("POST", path + query, 400, token=alice["token"], raw=png, headers={"Content-Type": "image/png"})
|
||||
assert resp["json"]["error"]["code"] == "invalid_request", query
|
||||
att = call("POST", path + "?filename=%D1%84%2B1+2.png", 201, token=alice["token"], raw=png,
|
||||
headers={"Content-Type": "image/png"})["json"]
|
||||
assert att["filename"] == "ф+1 2.png"
|
||||
|
||||
|
||||
def test_same_filename_distinct_objects():
|
||||
alice, bob, _eve, chat = _trio()
|
||||
first, second = _png(8), _png(9)
|
||||
a = upload(alice["token"], chat["id"], first, "same.png", "image/png", 201)["json"]
|
||||
b = upload(alice["token"], chat["id"], second, "same.png", "image/png", 201)["json"]
|
||||
assert a["id"] != b["id"]
|
||||
assert _download(bob["token"], a["id"])["bytes"] == first
|
||||
assert _download(bob["token"], b["id"])["bytes"] == second
|
||||
|
||||
|
||||
def test_empty_body_and_variants():
|
||||
alice, bob, _eve, chat = _trio()
|
||||
upload(alice["token"], chat["id"], b"", "empty.png", "image/png", 400)
|
||||
att = upload(alice["token"], chat["id"], _png(), "v.png", "image/png", 201)["json"]
|
||||
_download(bob["token"], att["id"], 200, "?variant=original")
|
||||
_download(bob["token"], att["id"], 404, "?variant=thumbnail")
|
||||
_download(bob["token"], att["id"], 400, "?variant=../../etc")
|
||||
|
||||
|
||||
def test_parallel_uploads_distinct():
|
||||
alice, bob, _eve, chat = _trio()
|
||||
blobs = [_png(i) + b"" for i in range(12)]
|
||||
|
||||
def send(i):
|
||||
return upload(alice["token"], chat["id"], blobs[i], f"p{i}.png", "image/png", 201)["json"]
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
|
||||
results = list(pool.map(send, range(12)))
|
||||
assert len({r["id"] for r in results}) == 12
|
||||
for i, att in enumerate(results):
|
||||
assert att["sha256"] == hashlib.sha256(blobs[i]).hexdigest()
|
||||
|
||||
|
||||
def _raw_partial_upload(token: str, chat_id: str, declared: int, payload: bytes, hold: float = 0.0) -> None:
|
||||
parsed = urllib.parse.urlparse(BASE_URL)
|
||||
sock = socket.create_connection((parsed.hostname, parsed.port or 80), timeout=30)
|
||||
head = (
|
||||
f"POST /api/v1/chats/{chat_id}/attachments?filename=cut.png HTTP/1.1\r\n"
|
||||
f"Host: {parsed.hostname}\r\nAuthorization: Bearer {token}\r\n"
|
||||
f"Content-Type: image/png\r\nContent-Length: {declared}\r\n\r\n"
|
||||
).encode()
|
||||
sock.sendall(head + payload)
|
||||
if hold:
|
||||
time.sleep(hold)
|
||||
sock.close()
|
||||
|
||||
|
||||
def test_interrupted_upload_does_not_break_service():
|
||||
alice, bob, _eve, chat = _trio()
|
||||
big = imagegen.large_png(2 * MIB)
|
||||
for _ in range(3):
|
||||
_raw_partial_upload(alice["token"], chat["id"], len(big), big[: 300 * 1024])
|
||||
att = upload(alice["token"], chat["id"], _png(), "after.png", "image/png", 201)["json"]
|
||||
_download(bob["token"], att["id"])
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Lab4 grade 4 operator checks that need the Docker CLI (RUN_DOCKER_TESTS=1).
|
||||
|
||||
Non-destructive: nothing is stopped; checks run inside the API containers.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
|
||||
import imagegen
|
||||
from helpers import call, chat_for, register, upload
|
||||
from test_attachments import _raw_partial_upload
|
||||
|
||||
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
|
||||
|
||||
|
||||
def _enabled(name: str) -> bool:
|
||||
if os.environ.get("RUN_DOCKER_TESTS") != "1":
|
||||
print(f"SKIP {name} (set RUN_DOCKER_TESTS=1)")
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _run(args, check=True):
|
||||
proc = subprocess.run(args, cwd=ROOT, capture_output=True, text=True, encoding="utf-8")
|
||||
if check and proc.returncode != 0:
|
||||
raise AssertionError(f"{' '.join(args[:6])} rc={proc.returncode}: {proc.stdout[-800:]}{proc.stderr[-400:]}")
|
||||
return proc
|
||||
|
||||
|
||||
def _api_containers():
|
||||
out = _run(["docker", "compose", "--env-file", ".env", "ps", "-q", "api"]).stdout.split()
|
||||
assert len(out) >= 2, out
|
||||
return out
|
||||
|
||||
|
||||
def _exec_json(container: str, *args):
|
||||
proc = _run(["docker", "exec", container, "python", "-m", *args])
|
||||
return json.loads(proc.stdout[proc.stdout.index("{"):])
|
||||
|
||||
|
||||
def _bucket_state(container: str) -> dict:
|
||||
return _exec_json(container, "messenger.reconcile", "--dry-run", "--grace-seconds", "0")
|
||||
|
||||
|
||||
def test_bucket_private_and_api_key_least_privilege():
|
||||
if not _enabled("test_bucket_private_and_api_key_least_privilege"):
|
||||
return
|
||||
report = _exec_json(_api_containers()[0], "messenger.selfcheck", "s3")
|
||||
failed = [r for r in report["results"] if not r["ok"]]
|
||||
assert report["passed"] and not failed, failed
|
||||
|
||||
|
||||
def test_s3_db_failure_compensation_and_reconcile():
|
||||
if not _enabled("test_s3_db_failure_compensation_and_reconcile"):
|
||||
return
|
||||
report = _exec_json(_api_containers()[0], "messenger.selfcheck", "consistency")
|
||||
failed = [r for r in report["results"] if not r["ok"]]
|
||||
assert report["passed"] and not failed, failed
|
||||
|
||||
|
||||
def test_interrupted_and_stalled_uploads_leave_nothing():
|
||||
if not _enabled("test_interrupted_and_stalled_uploads_leave_nothing"):
|
||||
return
|
||||
containers = _api_containers()
|
||||
alice, bob = register("cut_a"), register("cut_b")
|
||||
chat = chat_for(alice, bob)
|
||||
before = _bucket_state(containers[0])
|
||||
big = imagegen.large_png(3 * 1024 * 1024)
|
||||
for _ in range(4):
|
||||
_raw_partial_upload(alice["token"], chat["id"], len(big), big[: 512 * 1024])
|
||||
# Stalled client: headers + part of body, then silence past UPLOAD_IDLE_TIMEOUT_SECONDS (10 s).
|
||||
_raw_partial_upload(alice["token"], chat["id"], len(big), big[: 256 * 1024], hold=12)
|
||||
time.sleep(1)
|
||||
after = _bucket_state(containers[0])
|
||||
assert after["objects_scanned"] == before["objects_scanned"], (before, after)
|
||||
# Leftovers of earlier S3-outage runs (intents kept for the reconciler) are not ours.
|
||||
assert after["stale_intents"] == before["stale_intents"], (before, after)
|
||||
assert after["orphans_found"] == before["orphans_found"], (before, after)
|
||||
for container in containers:
|
||||
spool = _exec_json(container, "messenger.selfcheck", "spool")
|
||||
assert spool["passed"], (container, spool)
|
||||
att = upload(alice["token"], chat["id"], imagegen.rgb_png(8, 8), "ok.png", "image/png", 201)["json"]
|
||||
call("GET", "/api/v1/attachments/" + att["id"] + "/content", 200, token=bob["token"])
|
||||
|
||||
|
||||
def test_parallel_large_uploads_keep_s3_within_memory():
|
||||
# 2 replicas × 8 slots = 16 PUTs in flight; SeaweedFS holds ≈30–40 MiB per 10 MiB PUT.
|
||||
# With mem_limit 512m it ran at the limit and was OOM-killed (exit 137) under 40 uploads.
|
||||
if not _enabled("test_parallel_large_uploads_keep_s3_within_memory"):
|
||||
return
|
||||
s3 = _run(["docker", "compose", "--env-file", ".env", "ps", "-q", "s3"]).stdout.split()[0]
|
||||
limit = int(_run(["docker", "inspect", "-f", "{{.HostConfig.Memory}}", s3]).stdout.strip())
|
||||
alice = register("par_a")
|
||||
chat = chat_for(alice)
|
||||
payload = imagegen.large_png(int(9.5 * 1024 * 1024))
|
||||
peak = [0]
|
||||
stop = threading.Event()
|
||||
|
||||
def sample():
|
||||
while not stop.is_set():
|
||||
stat = _run(["docker", "exec", s3, "cat", "/sys/fs/cgroup/memory.stat"], check=False).stdout
|
||||
for line in stat.splitlines():
|
||||
if line.startswith("anon "):
|
||||
peak[0] = max(peak[0], int(line.split()[1]))
|
||||
time.sleep(0.1)
|
||||
|
||||
def send(i):
|
||||
return call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=par{i}.png", token=alice["token"],
|
||||
raw=payload, headers={"Content-Type": "image/png"})["status"]
|
||||
|
||||
sampler = threading.Thread(target=sample)
|
||||
sampler.start()
|
||||
try:
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as pool:
|
||||
statuses = list(pool.map(send, range(16)))
|
||||
finally:
|
||||
time.sleep(1)
|
||||
stop.set()
|
||||
sampler.join()
|
||||
state = _run(["docker", "inspect", "-f", "{{.State.Running}} {{.State.OOMKilled}}", s3]).stdout.split()
|
||||
assert state == ["true", "false"], state
|
||||
# 503 is the documented backpressure (slot wait > 5 s), never an S3 failure.
|
||||
assert set(statuses) <= {201, 503} and statuses.count(201) >= 10, statuses
|
||||
assert peak[0] < 0.8 * limit, (peak[0] // 2**20, limit // 2**20)
|
||||
call("GET", "/health/ready", 200)
|
||||
|
||||
|
||||
def test_s3_can_grow_volumes():
|
||||
# SeaweedFS grows a collection by 7 volumes at a time; when no slot is left every PUT
|
||||
# fails ("No writable volumes") while readiness stays 200. -volume.max=16 hit that at ≈4.7 GiB.
|
||||
if not _enabled("test_s3_can_grow_volumes"):
|
||||
return
|
||||
s3 = _run(["docker", "compose", "--env-file", ".env", "ps", "-q", "s3"]).stdout.split()[0]
|
||||
status = json.loads(_run(["docker", "exec", s3, "wget", "-q", "-O", "-", "http://127.0.0.1:9333/dir/status"]).stdout)
|
||||
topology = status["Topology"]
|
||||
assert topology["Free"] >= 8, {k: topology[k] for k in ("Max", "Free")}
|
||||
|
||||
|
||||
def test_no_original_kept_on_api_replicas():
|
||||
if not _enabled("test_no_original_kept_on_api_replicas"):
|
||||
return
|
||||
alice, bob = register("loc_a"), register("loc_b")
|
||||
chat = chat_for(alice, bob)
|
||||
for i in range(4):
|
||||
upload(alice["token"], chat["id"], imagegen.rgb_png(10 + i, 10), f"l{i}.png", "image/png", 201)
|
||||
for container in _api_containers():
|
||||
spool = _exec_json(container, "messenger.selfcheck", "spool")
|
||||
assert spool["passed"], (container, spool)
|
||||
# Any regular file created after the container started, anywhere on its writable layer
|
||||
# (/etc/hosts, /etc/resolv.conf, /etc/hostname are bind mounts written by Docker itself).
|
||||
started = _run(["docker", "inspect", "-f", "{{.State.StartedAt}}", container]).stdout.strip()
|
||||
found = _run(["docker", "exec", "-u", "0", container, "find", "/", "-xdev", "-type", "f",
|
||||
"-newermt", started, "-not", "-path", "/proc/*",
|
||||
"-not", "-path", "/etc/hosts", "-not", "-path", "/etc/resolv.conf",
|
||||
"-not", "-path", "/etc/hostname"]).stdout.split()
|
||||
assert not found, (container, found[:5])
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Concurrent registration race and parallel messages."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import uuid
|
||||
|
||||
from helpers import BASE_URL, call, register
|
||||
|
||||
|
||||
def test_parallel_messages_unique():
|
||||
a = register("par")
|
||||
b = register("parb")
|
||||
chat = call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
token=a["token"],
|
||||
body={"title": "parallel", "member_ids": [a["id"], b["id"]]},
|
||||
)["json"]
|
||||
|
||||
def send(i: int):
|
||||
return call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
201,
|
||||
token=a["token"],
|
||||
body={"text": f"msg-{i}"},
|
||||
)["json"]["id"]
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool:
|
||||
ids = list(pool.map(send, range(100)))
|
||||
assert len(ids) == len(set(ids)) == 100
|
||||
|
||||
|
||||
def test_username_race_one_winner():
|
||||
username = "race_" + uuid.uuid4().hex[:12]
|
||||
password = "T3st-" + uuid.uuid4().hex
|
||||
body = {
|
||||
"username": username,
|
||||
"display_name": "Race",
|
||||
"password": password,
|
||||
}
|
||||
|
||||
def attempt(_):
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
raw = json.dumps(body).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
BASE_URL + "/api/v1/users",
|
||||
data=raw,
|
||||
headers={"Content-Type": "application/json", "Accept": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=30)
|
||||
except urllib.error.HTTPError as err:
|
||||
resp = err
|
||||
return resp.code
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
codes = list(pool.map(attempt, range(8)))
|
||||
assert codes.count(201) == 1, codes
|
||||
assert codes.count(409) == 7, codes
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Dependency failure checks (Redis/Postgres/S3). Optional: RUN_DEPS_TEST=1."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import imagegen
|
||||
from helpers import call, chat_for, register, upload
|
||||
|
||||
|
||||
ROOT = os.path.join(os.path.dirname(__file__), "..")
|
||||
|
||||
|
||||
def _compose(*args: str) -> None:
|
||||
cmd = ["docker", "compose", "--env-file", ".env", *args]
|
||||
subprocess.check_call(cmd, cwd=ROOT)
|
||||
|
||||
|
||||
def _started_at(service: str) -> dict:
|
||||
ids = subprocess.check_output(["docker", "compose", "--env-file", ".env", "ps", "-q", service], cwd=ROOT, text=True).split()
|
||||
assert ids, service
|
||||
return {
|
||||
c: subprocess.check_output(["docker", "inspect", "-f", "{{.State.StartedAt}}", c], text=True).strip()
|
||||
for c in ids
|
||||
}
|
||||
|
||||
|
||||
def _wait_ready(timeout_s: int = 60, stable: int = 6) -> None:
|
||||
# Several consecutive 200s: HAProxy may still finish health checks that started
|
||||
# during the outage and briefly mark every replica DOWN after the first 200.
|
||||
deadline = time.time() + timeout_s
|
||||
streak = 0
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
streak = streak + 1 if call("GET", "/health/ready")["status"] == 200 else 0
|
||||
except Exception:
|
||||
streak = 0
|
||||
if streak >= stable:
|
||||
return
|
||||
time.sleep(1)
|
||||
raise AssertionError("stack did not become ready in time")
|
||||
|
||||
|
||||
def _unavailable(method: str, path: str, token: str | None = None, body=None) -> dict:
|
||||
# Every 503 — from a replica or from HAProxy itself — is the JSON error envelope
|
||||
# with X-Request-Id / X-Instance-Id (checked inside call()).
|
||||
resp = call(method, path, 503, token=token, body=body)
|
||||
assert resp["json"]["error"]["code"] == "unavailable", resp["json"]
|
||||
return resp
|
||||
|
||||
|
||||
def _skip(name: str) -> bool:
|
||||
if os.environ.get("RUN_DEPS_TEST") != "1":
|
||||
print(f"SKIP {name} (set RUN_DEPS_TEST=1)")
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def test_redis_stop_returns_503_or_unready():
|
||||
if _skip("test_redis_stop_returns_503_or_unready"):
|
||||
return
|
||||
actor = register("deps")
|
||||
_compose("stop", "redis")
|
||||
time.sleep(2)
|
||||
try:
|
||||
_unavailable("GET", "/health/ready")
|
||||
_unavailable("GET", "/api/v1/users/me", actor["token"])
|
||||
_unavailable("DELETE", "/api/v1/auth/sessions/current", actor["token"])
|
||||
finally:
|
||||
_compose("start", "redis")
|
||||
_wait_ready()
|
||||
call("GET", "/api/v1/users/me", 200, token=actor["token"])
|
||||
|
||||
|
||||
def test_s3_stop_degrades_only_attachments():
|
||||
# S3 is on the synchronous attachment path, so readiness reports 503; HAProxy then
|
||||
# falls back to the liveness-checked backend and text chat/metadata keep working.
|
||||
if _skip("test_s3_stop_degrades_only_attachments"):
|
||||
return
|
||||
alice, bob = register("s3down_a"), register("s3down_b")
|
||||
chat = chat_for(alice, bob)
|
||||
data = imagegen.rgb_png(24, 12)
|
||||
att = upload(alice["token"], chat["id"], data, "before.png", "image/png", 201)["json"]
|
||||
_compose("stop", "s3")
|
||||
try:
|
||||
time.sleep(3)
|
||||
_unavailable("GET", "/health/ready")
|
||||
started = time.monotonic()
|
||||
up = upload(alice["token"], chat["id"], data, "during.png", "image/png", 503)
|
||||
elapsed = time.monotonic() - started
|
||||
assert up["json"]["error"]["code"] == "unavailable", up["json"]
|
||||
assert elapsed < 15, elapsed
|
||||
_unavailable("GET", f"/api/v1/attachments/{att['id']}/content", bob["token"])
|
||||
meta = call("GET", f"/api/v1/attachments/{att['id']}", 200, token=bob["token"])["json"]
|
||||
assert meta["sha256"] == att["sha256"]
|
||||
msg = call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
201,
|
||||
token=bob["token"],
|
||||
body={"text": "S3 недоступен, но чат работает", "attachment_ids": [att["id"]]},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)["json"]
|
||||
assert msg["attachment_ids"] == [att["id"]]
|
||||
print(" s3 down: ready 503, upload 503 in %.2fs, download 503, metadata/messages OK" % elapsed)
|
||||
finally:
|
||||
_compose("start", "s3")
|
||||
_compose("restart", "s3-gw")
|
||||
_wait_ready()
|
||||
dl = call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"])
|
||||
assert hashlib.sha256(dl["bytes"]).hexdigest() == att["sha256"]
|
||||
upload(alice["token"], chat["id"], data, "after.png", "image/png", 201)
|
||||
|
||||
|
||||
def test_postgres_stop_returns_503():
|
||||
if _skip("test_postgres_stop_returns_503"):
|
||||
return
|
||||
actor = register("deps_pg")
|
||||
_compose("stop", "postgres")
|
||||
time.sleep(2)
|
||||
try:
|
||||
_unavailable("GET", "/health/ready")
|
||||
started = time.monotonic()
|
||||
_unavailable("GET", "/api/v1/users/me", actor["token"])
|
||||
_unavailable("GET", "/api/v1/chats", actor["token"])
|
||||
assert time.monotonic() - started < 15
|
||||
finally:
|
||||
_compose("start", "postgres")
|
||||
_wait_ready(90)
|
||||
call("GET", "/api/v1/users/me", 200, token=actor["token"])
|
||||
|
||||
|
||||
def test_restart_hook_restarts_api_and_stores():
|
||||
# tests/README: the persistence hook must restart the API and every store.
|
||||
if _skip("test_restart_hook_restarts_api_and_stores"):
|
||||
return
|
||||
actor = register("deps_hook")
|
||||
services = ("api", "postgres", "redis", "s3")
|
||||
before = {s: _started_at(s) for s in services}
|
||||
hook = ["cmd", "/c", r"scripts\restart.cmd"] if os.name == "nt" else ["sh", "scripts/restart.sh"]
|
||||
subprocess.check_call(hook, cwd=ROOT, stdout=subprocess.DEVNULL)
|
||||
_wait_ready(90)
|
||||
for s in services:
|
||||
after = _started_at(s)
|
||||
if s == "api":
|
||||
assert len(after) >= 2, after
|
||||
stale = [c for c, t in after.items() if before[s].get(c) == t]
|
||||
assert not stale, (s, stale)
|
||||
call("GET", "/api/v1/users/me", 200, token=actor["token"])
|
||||
|
||||
|
||||
def test_postgres_pause_fails_fast():
|
||||
# A paused (not stopped) database never answers: no RST, statement_timeout is never
|
||||
# evaluated. Requests must still end as JSON 503 within a bounded time.
|
||||
if _skip("test_postgres_pause_fails_fast"):
|
||||
return
|
||||
actor = register("deps_pause")
|
||||
_compose("pause", "postgres")
|
||||
try:
|
||||
timings = []
|
||||
for path in ("/api/v1/users/me", "/api/v1/chats", "/api/v1/users/me"):
|
||||
started = time.monotonic()
|
||||
_unavailable("GET", path, actor["token"])
|
||||
timings.append(time.monotonic() - started)
|
||||
assert max(timings) < 15, timings
|
||||
time.sleep(4)
|
||||
_unavailable("GET", "/health/ready")
|
||||
print(" postgres paused: 503 after " + ", ".join("%.2fs" % t for t in timings))
|
||||
finally:
|
||||
_compose("unpause", "postgres")
|
||||
_wait_ready(90)
|
||||
call("GET", "/api/v1/users/me", 200, token=actor["token"])
|
||||
@@ -0,0 +1,165 @@
|
||||
"""Lab3: shared Idempotency-Key and multi-replica visibility."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import uuid
|
||||
|
||||
from helpers import call, register
|
||||
|
||||
|
||||
def _chat_pair():
|
||||
a = register("idem_a")
|
||||
b = register("idem_b")
|
||||
chat = call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
token=a["token"],
|
||||
body={"title": "idem", "member_ids": [a["id"], b["id"]]},
|
||||
)["json"]
|
||||
return a, b, chat
|
||||
|
||||
|
||||
def test_missing_idempotency_key_400():
|
||||
a, _b, chat = _chat_pair()
|
||||
call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
400,
|
||||
token=a["token"],
|
||||
body={"text": "no-key"},
|
||||
headers={"Idempotency-Key": ""},
|
||||
)
|
||||
|
||||
|
||||
def test_replay_same_key_same_body():
|
||||
a, _b, chat = _chat_pair()
|
||||
key = uuid.uuid4().hex
|
||||
first = call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
201,
|
||||
token=a["token"],
|
||||
body={"text": "same"},
|
||||
headers={"Idempotency-Key": key},
|
||||
)["json"]
|
||||
second = call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
201,
|
||||
token=a["token"],
|
||||
body={"text": "same"},
|
||||
headers={"Idempotency-Key": key},
|
||||
)["json"]
|
||||
assert first == second
|
||||
|
||||
|
||||
def test_empty_attachment_ids_equals_absent():
|
||||
# Peer remark: attachment_ids: [] ≡ absent field; must not 400; same idempotency hash.
|
||||
a, _b, chat = _chat_pair()
|
||||
key = uuid.uuid4().hex
|
||||
first = call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
201,
|
||||
token=a["token"],
|
||||
body={"text": "with-empty-attachments", "attachment_ids": []},
|
||||
headers={"Idempotency-Key": key},
|
||||
)["json"]
|
||||
second = call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
201,
|
||||
token=a["token"],
|
||||
body={"text": "with-empty-attachments"},
|
||||
headers={"Idempotency-Key": key},
|
||||
)["json"]
|
||||
assert first == second
|
||||
|
||||
|
||||
def test_same_key_different_body_409():
|
||||
a, _b, chat = _chat_pair()
|
||||
key = uuid.uuid4().hex
|
||||
call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
201,
|
||||
token=a["token"],
|
||||
body={"text": "one"},
|
||||
headers={"Idempotency-Key": key},
|
||||
)
|
||||
call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
409,
|
||||
token=a["token"],
|
||||
body={"text": "two"},
|
||||
headers={"Idempotency-Key": key},
|
||||
)
|
||||
|
||||
|
||||
def test_key_scoped_to_user_and_chat():
|
||||
# Bob reusing Alice's key must get his own message, not her stored response.
|
||||
a, b, chat = _chat_pair()
|
||||
key = uuid.uuid4().hex
|
||||
first = call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, token=a["token"],
|
||||
body={"text": "same"}, headers={"Idempotency-Key": key})["json"]
|
||||
other = call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, token=b["token"],
|
||||
body={"text": "same"}, headers={"Idempotency-Key": key})["json"]
|
||||
assert other["id"] != first["id"] and other["sender_id"] == b["id"]
|
||||
second_chat = call("POST", "/api/v1/chats", 201, token=a["token"],
|
||||
body={"title": "idem2", "member_ids": [a["id"], b["id"]]})["json"]
|
||||
elsewhere = call("POST", f"/api/v1/chats/{second_chat['id']}/messages", 201, token=a["token"],
|
||||
body={"text": "same"}, headers={"Idempotency-Key": key})["json"]
|
||||
assert elsewhere["id"] != first["id"] and elsewhere["chat_id"] == second_chat["id"]
|
||||
|
||||
|
||||
def test_invalid_key_format_400():
|
||||
a, _b, chat = _chat_pair()
|
||||
for key in ("has space", "x" * 129, "a/b", "a,b", "ключ".encode().decode("latin-1")):
|
||||
resp = call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, token=a["token"],
|
||||
body={"text": "bad key"}, headers={"Idempotency-Key": key})
|
||||
assert resp["json"]["error"]["code"] == "invalid_request", key
|
||||
call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, token=a["token"],
|
||||
body={"text": "ok key"}, headers={"Idempotency-Key": "A-z0.9_:" + "x" * 120})
|
||||
|
||||
|
||||
def test_parallel_same_key_one_message():
|
||||
a, b, chat = _chat_pair()
|
||||
key = uuid.uuid4().hex
|
||||
text = "parallel-idem-" + key
|
||||
|
||||
def send(_):
|
||||
return call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
201,
|
||||
token=a["token"],
|
||||
body={"text": text},
|
||||
headers={"Idempotency-Key": key},
|
||||
)["json"]
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
results = list(pool.map(send, range(8)))
|
||||
ids = {m["id"] for m in results}
|
||||
assert len(ids) == 1, ids
|
||||
page = call(
|
||||
"GET",
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=100",
|
||||
200,
|
||||
token=b["token"],
|
||||
)["json"]
|
||||
assert sum(1 for m in page["items"] if m["text"] == text) == 1
|
||||
|
||||
|
||||
def test_multiple_instance_ids_observed():
|
||||
a = register("inst")
|
||||
seen = set()
|
||||
for _ in range(40):
|
||||
seen.add(
|
||||
call("GET", "/api/v1/users/me", 200, token=a["token"])["headers"].get(
|
||||
"X-Instance-Id"
|
||||
)
|
||||
)
|
||||
assert len(seen) >= 2, f"expected ≥2 replicas via LB, got {seen}"
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Offline checks of the streaming PNG/JPEG validators (no server needed)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
||||
|
||||
from messenger import images # noqa: E402
|
||||
|
||||
import imagegen # noqa: E402
|
||||
|
||||
LIMIT = 40_000_000
|
||||
|
||||
|
||||
def _validate(data: bytes, content_type: str, step: int = 0):
|
||||
v = images.validator_for(content_type, LIMIT)
|
||||
if step:
|
||||
for i in range(0, len(data), step):
|
||||
v.feed(data[i:i + step])
|
||||
else:
|
||||
v.feed(data)
|
||||
return v.finish()
|
||||
|
||||
|
||||
def _rejected(data: bytes, content_type: str, step: int = 0) -> int:
|
||||
try:
|
||||
_validate(data, content_type, step)
|
||||
except images.ImageRejected as exc:
|
||||
return exc.status
|
||||
raise AssertionError("image was accepted")
|
||||
|
||||
|
||||
def test_valid_pngs_any_chunking():
|
||||
cases = {
|
||||
"public": (imagegen.PUBLIC_PNG.read_bytes(), (320, 200)),
|
||||
"rgb": (imagegen.rgb_png(33, 17), (33, 17)),
|
||||
"interlaced": (imagegen.interlaced_rgb_png(37, 23), (37, 23)),
|
||||
"interlaced_tiny": (imagegen.interlaced_rgb_png(1, 1), (1, 1)),
|
||||
"gray1": (imagegen.gray1_png(13, 9), (13, 9)),
|
||||
"palette": (imagegen.palette_png(10, 6), (10, 6)),
|
||||
"rgba16": (imagegen.png16_rgba(5, 4), (5, 4)),
|
||||
}
|
||||
for name, (data, size) in cases.items():
|
||||
for step in (0, 1, 7, 4096):
|
||||
assert _validate(data, "image/png", step) == size, (name, step)
|
||||
|
||||
|
||||
def test_valid_jpegs_any_chunking():
|
||||
for name in ("sample.jpg", "progressive.jpg", "gray.jpg"):
|
||||
data = imagegen.fixture(name)
|
||||
for step in (0, 1, 5, 4096):
|
||||
assert _validate(data, "image/jpeg", step) == (320, 200), (name, step)
|
||||
|
||||
|
||||
def test_pixel_limit_detected_from_header_only():
|
||||
data = imagegen.gray1_png(8000, 5001)
|
||||
v = images.validator_for("image/png", LIMIT)
|
||||
try:
|
||||
v.feed(data[:33]) # signature + IHDR only
|
||||
except images.ImageRejected as exc:
|
||||
assert exc.status == 413
|
||||
else:
|
||||
raise AssertionError("pixel limit not enforced on IHDR")
|
||||
jpeg = bytearray(imagegen.fixture("sample.jpg"))
|
||||
sof = jpeg.find(b"\xff\xc0")
|
||||
struct.pack_into(">HH", jpeg, sof + 5, 6000, 8000)
|
||||
v = images.validator_for("image/jpeg", LIMIT)
|
||||
try:
|
||||
v.feed(bytes(jpeg[: sof + 32]))
|
||||
except images.ImageRejected as exc:
|
||||
assert exc.status == 413
|
||||
else:
|
||||
raise AssertionError("pixel limit not enforced on SOF")
|
||||
|
||||
|
||||
def test_exactly_at_pixel_limit_accepted():
|
||||
assert _validate(imagegen.gray1_png(8000, 5000), "image/png") == (8000, 5000)
|
||||
|
||||
|
||||
def test_corrupted_png_rejected():
|
||||
good = imagegen.rgb_png(20, 10)
|
||||
flipped = bytearray(good)
|
||||
flipped[-20] ^= 0xFF # inside IDAT → CRC mismatch
|
||||
assert _rejected(bytes(flipped), "image/png") == 415
|
||||
assert _rejected(good[: len(good) // 2], "image/png") == 415
|
||||
assert _rejected(good + b"trailing", "image/png") == 415
|
||||
ihdr = imagegen.chunk(b"IHDR", struct.pack(">IIBBBBB", 4, 4, 8, 2, 0, 0, 0))
|
||||
bad_zlib = b"\x89PNG\r\n\x1a\n" + ihdr + imagegen.chunk(b"IDAT", b"\x78\x9c" + b"\xff" * 40) + imagegen.chunk(b"IEND", b"")
|
||||
assert _rejected(bad_zlib, "image/png") == 415
|
||||
short = imagegen.png_from_raw(10, 10, b"\x00" * 10) # fewer rows than IHDR declares
|
||||
assert _rejected(short, "image/png") == 415
|
||||
long = imagegen.png_from_raw(2, 2, b"\x00" * 100) # decompression bomb style overflow
|
||||
assert _rejected(long, "image/png") == 415
|
||||
assert _rejected(imagegen.palette_png(4, 4).replace(b"PLTE", b"tEXt"), "image/png") == 415
|
||||
|
||||
|
||||
def test_corrupted_jpeg_rejected():
|
||||
good = imagegen.fixture("sample.jpg")
|
||||
assert _rejected(good[: len(good) // 2], "image/jpeg") == 415
|
||||
assert _rejected(b"\xff\xd8\xff\xe0" + bytes(range(256)) * 4, "image/jpeg") == 415
|
||||
no_sof = b"\xff\xd8\xff\xda\x00\x08\x01\x01\x00\x00\x3f\x00" + b"\x12" * 64 + b"\xff\xd9"
|
||||
assert _rejected(no_sof, "image/jpeg") == 415
|
||||
assert _rejected(b"\xff\xd8\xff\xd9", "image/jpeg") == 415
|
||||
arithmetic = bytearray(good)
|
||||
arithmetic[good.find(b"\xff\xc0") + 1] = 0xC9
|
||||
assert _rejected(bytes(arithmetic), "image/jpeg") == 415
|
||||
|
||||
|
||||
def test_reviewer_corrupted_pngs_rejected():
|
||||
for name, data in imagegen.corrupted_pngs().items():
|
||||
for step in (0, 1, 4096):
|
||||
assert _rejected(data, "image/png", step) == 415, (name, step)
|
||||
|
||||
|
||||
def test_all_filter_types_accepted():
|
||||
for interlace in (0, 1):
|
||||
for size in ((1, 1), (9, 7), (33, 20)):
|
||||
data = imagegen.all_filters_png(*size, interlace=interlace)
|
||||
for step in (0, 1, 7):
|
||||
assert _validate(data, "image/png", step) == size, (interlace, size, step)
|
||||
|
||||
|
||||
def test_reviewer_corrupted_jpegs_structural_part():
|
||||
# The rest (no tables, missing scan data, truncated + EOI) needs a real decoder:
|
||||
# covered over HTTP by test_attachments.test_reviewer_corrupted_images_415.
|
||||
corpus = imagegen.corrupted_jpegs()
|
||||
for name in ("jpeg_18_bytes", "jpeg_truncated_no_eoi", "jpeg_12_bit"):
|
||||
assert _rejected(corpus[name], "image/jpeg") == 415, name
|
||||
|
||||
|
||||
def test_foreign_formats_rejected():
|
||||
for blob in (b"GIF89a" + b"\x00" * 100, b"%PDF-1.7\n", b"<html></html>", b"MZ\x90\x00", b""):
|
||||
assert _rejected(blob, "image/png") == 415
|
||||
assert _rejected(blob, "image/jpeg") == 415
|
||||
assert images.sniff(imagegen.fixture("sample.jpg")[:8]) == "image/jpeg"
|
||||
assert images.sniff(imagegen.PUBLIC_PNG.read_bytes()[:8]) == "image/png"
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Session expiry (short TTL) — run against stack with SESSION_TTL_SECONDS=2."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import os
|
||||
import time
|
||||
|
||||
from helpers import call, register
|
||||
|
||||
|
||||
def test_session_expiry_if_short_ttl():
|
||||
ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
if ttl > 5:
|
||||
print("SKIP expiry: SESSION_TTL_SECONDS=%s (need <=5 for this test)" % ttl)
|
||||
return
|
||||
a = register("expire")
|
||||
time.sleep(ttl + 1.5)
|
||||
call("GET", "/api/v1/users/me", 401, token=a["token"])
|
||||
|
||||
|
||||
def test_login_after_register():
|
||||
a = register("relogin")
|
||||
cred = base64.b64encode(
|
||||
(a["registration"]["username"] + ":" + a["registration"]["password"]).encode()
|
||||
).decode()
|
||||
session = call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
201,
|
||||
headers={"Authorization": "Basic " + cred},
|
||||
)["json"]
|
||||
assert session["token_type"] == "Bearer"
|
||||
assert session["user"]["id"] == a["id"]
|
||||
@@ -0,0 +1,249 @@
|
||||
"""Graceful shutdown of an API replica (RUN_DOCKER_TESTS=1).
|
||||
|
||||
Each test stops ONE API replica and brings it back; dependencies are not touched.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
import imagegen
|
||||
from helpers import call, chat_for, register
|
||||
|
||||
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
|
||||
STOP_TIMEOUT_S = 15 # = stop_grace_period of the api service
|
||||
|
||||
# Runs inside the replica: SIGTERM to PID 1 (as `docker stop` does), then probes the
|
||||
# same process directly while HAProxy is still expected to route to it.
|
||||
PROBE = r"""
|
||||
import json, os, signal, time, urllib.error, urllib.request
|
||||
|
||||
def get(path, token=None):
|
||||
req = urllib.request.Request("http://127.0.0.1:8080" + path)
|
||||
if token:
|
||||
req.add_header("Authorization", "Bearer " + token)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=2) as resp:
|
||||
return resp.status
|
||||
except urllib.error.HTTPError as err:
|
||||
return err.code
|
||||
except Exception as exc:
|
||||
return type(exc).__name__
|
||||
|
||||
token = os.environ["DRAIN_TOKEN"]
|
||||
drain = float(os.environ.get("SHUTDOWN_DRAIN_SECONDS", "3"))
|
||||
with open("/proc/1/cmdline", "rb") as f:
|
||||
pid1 = f.read().replace(b"\0", b" ").decode().strip()
|
||||
before = [get("/health/ready"), get("/api/v1/users/me", token)]
|
||||
sent_at = time.time()
|
||||
t0 = time.monotonic()
|
||||
os.kill(1, signal.SIGTERM)
|
||||
samples = []
|
||||
while time.monotonic() - t0 < drain - 0.8:
|
||||
samples.append([round(time.monotonic() - t0, 2), get("/health/ready"), get("/api/v1/users/me", token)])
|
||||
time.sleep(0.1)
|
||||
print(json.dumps({"pid1": pid1, "drain": drain, "before": before, "sent_at": sent_at, "samples": samples}))
|
||||
"""
|
||||
|
||||
# Runs inside the replica: a slow upload (body from stdin) whose body is still being sent
|
||||
# when the drain window ends and the listener is closed.
|
||||
SLOW_UPLOAD = r"""
|
||||
import http.client, json, os, signal, sys, time
|
||||
|
||||
body = sys.stdin.buffer.read()
|
||||
drain = float(os.environ.get("SHUTDOWN_DRAIN_SECONDS", "3"))
|
||||
conn = http.client.HTTPConnection("127.0.0.1", 8080, timeout=30)
|
||||
conn.putrequest("POST", "/api/v1/chats/%s/attachments?filename=drain.png" % os.environ["DRAIN_CHAT"])
|
||||
conn.putheader("Authorization", "Bearer " + os.environ["DRAIN_TOKEN"])
|
||||
conn.putheader("Content-Type", "image/png")
|
||||
conn.putheader("Content-Length", str(len(body)))
|
||||
conn.endheaders()
|
||||
t0 = time.monotonic()
|
||||
step = len(body) // 40 + 1
|
||||
for i in range(0, len(body), step):
|
||||
conn.send(body[i:i + step])
|
||||
if i == 0:
|
||||
os.kill(1, signal.SIGTERM)
|
||||
time.sleep((drain + 2) / 40)
|
||||
resp = conn.getresponse()
|
||||
print(json.dumps({"status": resp.status, "body_sent_s": round(time.monotonic() - t0, 2),
|
||||
"json": json.loads(resp.read() or b"null")}))
|
||||
"""
|
||||
|
||||
|
||||
def _enabled(name: str) -> bool:
|
||||
if os.environ.get("RUN_DOCKER_TESTS") != "1":
|
||||
print(f"SKIP {name} (set RUN_DOCKER_TESTS=1)")
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _run(args, check=True):
|
||||
proc = subprocess.run(args, cwd=ROOT, capture_output=True, text=True, encoding="utf-8")
|
||||
if check and proc.returncode != 0:
|
||||
raise AssertionError(f"{' '.join(args[:6])} rc={proc.returncode}: {proc.stdout[-800:]}{proc.stderr[-400:]}")
|
||||
return proc
|
||||
|
||||
|
||||
def _api_containers():
|
||||
out = _run(["docker", "compose", "--env-file", ".env", "ps", "-q", "api"]).stdout.split()
|
||||
assert len(out) >= 2, out
|
||||
return out
|
||||
|
||||
|
||||
def _inspect(container: str, fmt: str) -> str:
|
||||
return _run(["docker", "inspect", "-f", fmt, container]).stdout.strip()
|
||||
|
||||
|
||||
def _docker_time(value: str) -> float:
|
||||
# 2026-11-06T15:37:12.123456789Z → POSIX seconds (nanoseconds cut to microseconds).
|
||||
head, _, frac = value.rstrip("Z").partition(".")
|
||||
stamp = datetime.fromisoformat(head + "+00:00").timestamp()
|
||||
return stamp + (float("0." + frac[:6]) if frac else 0.0)
|
||||
|
||||
|
||||
def _wait_in_rotation(host: str, timeout_s: int = 90) -> float:
|
||||
started = time.monotonic()
|
||||
while time.monotonic() - started < timeout_s:
|
||||
try:
|
||||
if call("GET", "/health/ready")["headers"].get("X-Instance-Id") == host:
|
||||
return time.monotonic() - started
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise AssertionError(f"replica {host} not back in LB rotation after {timeout_s}s")
|
||||
|
||||
|
||||
def _wait_restarted(container: str, restarts: int) -> None:
|
||||
# unless-stopped restarts the container after a SIGTERM sent from inside it.
|
||||
deadline = time.monotonic() + 60
|
||||
while int(_inspect(container, "{{.RestartCount}}")) == restarts:
|
||||
assert time.monotonic() < deadline, "replica did not exit after SIGTERM"
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def test_sigterm_drains_readiness_but_keeps_serving():
|
||||
# After SIGTERM the replica must report /health/ready 503 at once (HAProxy takes it
|
||||
# out after `inter 1s fall 2`) but keep answering normal requests until then.
|
||||
if not _enabled("test_sigterm_drains_readiness_but_keeps_serving"):
|
||||
return
|
||||
actor = register("drain")
|
||||
target = _api_containers()[0]
|
||||
host = _inspect(target, "{{.Config.Hostname}}")
|
||||
restarts = int(_inspect(target, "{{.RestartCount}}"))
|
||||
proc = subprocess.run(["docker", "exec", "-e", "DRAIN_TOKEN", target, "python", "-c", PROBE],
|
||||
cwd=ROOT, capture_output=True, text=True, encoding="utf-8",
|
||||
env=dict(os.environ, DRAIN_TOKEN=actor["token"]))
|
||||
if proc.returncode != 0:
|
||||
_wait_in_rotation(host)
|
||||
raise AssertionError(f"replica exited during the drain window (probe rc={proc.returncode}) {proc.stderr[-300:]}")
|
||||
probe = json.loads(proc.stdout[proc.stdout.index("{"):])
|
||||
samples = probe["samples"]
|
||||
assert probe["pid1"].startswith("python -m messenger"), probe["pid1"]
|
||||
assert probe["drain"] >= 2, f"drain window {probe['drain']}s < HAProxy inter 1s x fall 2"
|
||||
assert probe["before"] == [200, 200], probe["before"]
|
||||
assert len(samples) >= 5, samples
|
||||
not_served = [s for s in samples if s[2] != 200]
|
||||
assert not not_served, f"requests failed during the drain window: {not_served}"
|
||||
still_ready = [s for s in samples if s[0] >= 0.3 and s[1] != 503]
|
||||
assert not still_ready, f"/health/ready not 503 while draining: {still_ready}"
|
||||
|
||||
_wait_restarted(target, restarts)
|
||||
# FinishedAt is the exit of the drained process (same clock as the probe in the container).
|
||||
stop_s = _docker_time(_inspect(target, "{{.State.FinishedAt}}")) - probe["sent_at"]
|
||||
assert probe["drain"] - 0.2 <= stop_s < STOP_TIMEOUT_S, stop_s
|
||||
back_s = _wait_in_rotation(host)
|
||||
print(" drain: %d probes, ready 503 / users/me 200; exit %.2fs after SIGTERM; back in LB in %.1fs"
|
||||
% (len(samples), stop_s, back_s))
|
||||
|
||||
|
||||
def test_inflight_upload_finishes_after_listener_closed():
|
||||
# The body is still arriving when the drain window ends: the listener closes, but the
|
||||
# in-flight upload (spool → S3 PUT → DB commit) must complete before the process exits.
|
||||
if not _enabled("test_inflight_upload_finishes_after_listener_closed"):
|
||||
return
|
||||
alice, bob = register("drain_up_a"), register("drain_up_b")
|
||||
chat = chat_for(alice, bob, title="drain upload")
|
||||
data = imagegen.large_png(2 * 1024 * 1024)
|
||||
target = _api_containers()[0]
|
||||
host = _inspect(target, "{{.Config.Hostname}}")
|
||||
restarts = int(_inspect(target, "{{.RestartCount}}"))
|
||||
proc = subprocess.run(["docker", "exec", "-i", "-e", "DRAIN_TOKEN", "-e", "DRAIN_CHAT", target,
|
||||
"python", "-c", SLOW_UPLOAD],
|
||||
cwd=ROOT, input=data, capture_output=True,
|
||||
env=dict(os.environ, DRAIN_TOKEN=alice["token"], DRAIN_CHAT=chat["id"]))
|
||||
out = proc.stdout.decode("utf-8", "replace")
|
||||
_wait_restarted(target, restarts)
|
||||
back_s = _wait_in_rotation(host)
|
||||
assert proc.returncode == 0, f"upload probe rc={proc.returncode}: {proc.stderr[-300:]!r}"
|
||||
result = json.loads(out[out.index("{"):])
|
||||
assert result["status"] == 201, result
|
||||
att = result["json"]
|
||||
assert att["sha256"] == hashlib.sha256(data).hexdigest(), att
|
||||
dl = call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"])
|
||||
assert hashlib.sha256(dl["bytes"]).hexdigest() == att["sha256"]
|
||||
print(" in-flight upload: body sent over %.1fs across listener close -> 201, download via LB OK; back in LB in %.1fs"
|
||||
% (result["body_sent_s"], back_s))
|
||||
|
||||
|
||||
def test_replica_stop_under_load_has_no_errors():
|
||||
# Closed-loop POSTs through the LB while one replica gets `docker stop`: requests
|
||||
# that HAProxy still sends to it during the drain window must succeed.
|
||||
if not _enabled("test_replica_stop_under_load_has_no_errors"):
|
||||
return
|
||||
alice, bob = register("drain_load_a"), register("drain_load_b")
|
||||
chat = chat_for(alice, bob, title="drain")
|
||||
target = _api_containers()[0]
|
||||
host = _inspect(target, "{{.Config.Hostname}}")
|
||||
stats = {"ok": 0, "target_after_stop": 0, "errors": []}
|
||||
lock = threading.Lock()
|
||||
stop = threading.Event()
|
||||
stopping = threading.Event()
|
||||
|
||||
def worker():
|
||||
while not stop.is_set():
|
||||
key = uuid.uuid4().hex
|
||||
try:
|
||||
r = call("POST", f"/api/v1/chats/{chat['id']}/messages", token=alice["token"],
|
||||
body={"text": "drain-" + key}, headers={"Idempotency-Key": key})
|
||||
status, instance = r["status"], r["headers"].get("X-Instance-Id")
|
||||
except Exception as exc:
|
||||
status, instance = type(exc).__name__, None
|
||||
with lock:
|
||||
if status == 201:
|
||||
stats["ok"] += 1
|
||||
if stopping.is_set() and instance == host:
|
||||
stats["target_after_stop"] += 1
|
||||
else:
|
||||
stats["errors"].append(status)
|
||||
time.sleep(0.05)
|
||||
|
||||
threads = [threading.Thread(target=worker, daemon=True) for _ in range(4)]
|
||||
for th in threads:
|
||||
th.start()
|
||||
try:
|
||||
time.sleep(1.5)
|
||||
stopping.set()
|
||||
started = time.monotonic()
|
||||
_run(["docker", "stop", "-t", str(STOP_TIMEOUT_S), target])
|
||||
stop_s = time.monotonic() - started
|
||||
time.sleep(1.5)
|
||||
finally:
|
||||
stop.set()
|
||||
for th in threads:
|
||||
th.join(timeout=10)
|
||||
_run(["docker", "start", target])
|
||||
back_s = _wait_in_rotation(host)
|
||||
assert not stats["errors"], f"{len(stats['errors'])} errors during replica stop: {stats['errors'][:10]}"
|
||||
assert stats["ok"] >= 20, stats
|
||||
assert stats["target_after_stop"] >= 1, "stopped replica served nothing during its drain window"
|
||||
assert stop_s < STOP_TIMEOUT_S, stop_s
|
||||
print(" stop under load: %d x 201, 0 errors, %d served by stopping replica; docker stop %.2fs; back in LB in %.1fs"
|
||||
% (stats["ok"], stats["target_after_stop"], stop_s, back_s))
|
||||
Reference in New Issue
Block a user