forked from mtusi2026/mtusi2026lab4
Лаба 4: вложения в S3, уровни 3-5, reconciler (трек 2)
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка приватности S3 и ограниченных прав API-ключа. Нужен запущенный стенд. Ничего не удаляет.
|
||||
Запуск: python3 student_tests/check_s3_private.py | tee evidence/s3-private-check.txt"""
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
FAILED = []
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
return subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT,
|
||||
capture_output=True, text=True, check=check)
|
||||
|
||||
|
||||
def report(ok, text):
|
||||
print(("PASS " if ok else "FAIL ") + text)
|
||||
if not ok:
|
||||
FAILED.append(text)
|
||||
|
||||
|
||||
def api_py(code):
|
||||
return compose("exec", "-T", "api", "python", "-c", code).stdout.strip()
|
||||
|
||||
|
||||
key = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-tAc",
|
||||
"SELECT object_key FROM attachments ORDER BY created_at DESC LIMIT 1").stdout.strip()
|
||||
if not key:
|
||||
sys.exit("В БД нет вложений: сначала выполните make test")
|
||||
bucket = api_py("from src import config; print(config.S3_BUCKET)")
|
||||
print(f"# bucket={bucket}, проверяется объект {key}")
|
||||
|
||||
# 1. Анонимный доступ к S3 напрямую, минуя API (из контейнера api, где S3 достижим по сети)
|
||||
anon = api_py(f"""
|
||||
import urllib.request, urllib.error, json
|
||||
def code(u):
|
||||
try: return urllib.request.urlopen(u, timeout=5).status
|
||||
except urllib.error.HTTPError as e: return e.code
|
||||
print(json.dumps([code("http://s3:9000/{bucket}/{key}"), code("http://s3:9000/{bucket}/"), code("http://s3:9000/")]))
|
||||
""")
|
||||
get_obj, list_bucket, list_all = json.loads(anon)
|
||||
report(get_obj in (401, 403), f"анонимный GET объекта напрямую из S3 -> HTTP {get_obj}")
|
||||
report(list_bucket in (401, 403), f"анонимный список bucket -> HTTP {list_bucket}")
|
||||
report(list_all in (401, 403), f"анонимный список всех bucket -> HTTP {list_all}")
|
||||
|
||||
# 2. Права API-ключа ограничены: чужой bucket и создание bucket запрещены
|
||||
rights = json.loads(api_py(f"""
|
||||
import json, uuid
|
||||
from botocore.exceptions import ClientError
|
||||
from src import storage
|
||||
c = storage.client(); res = {{}}
|
||||
def t(name, f):
|
||||
try: f(); res[name] = "ALLOWED"
|
||||
except ClientError as e: res[name] = e.response["Error"]["Code"]
|
||||
other = "other-" + uuid.uuid4().hex[:10]
|
||||
t("create_bucket", lambda: c.create_bucket(Bucket=other))
|
||||
t("put_to_other_bucket", lambda: c.put_object(Bucket="not-my-bucket", Key="x", Body=b"x"))
|
||||
t("get_from_other_bucket", lambda: c.get_object(Bucket="not-my-bucket", Key="x"))
|
||||
t("put_object_own_bucket", lambda: c.put_object(Bucket="{bucket}", Key="attachments/_rights_probe", Body=b"x"))
|
||||
t("delete_probe_own_bucket", lambda: c.delete_object(Bucket="{bucket}", Key="attachments/_rights_probe"))
|
||||
if res["create_bucket"] == "ALLOWED": c.delete_bucket(Bucket=other)
|
||||
print(json.dumps(res))
|
||||
"""))
|
||||
print("# ответы S3 для API-ключа:", rights)
|
||||
report(rights["create_bucket"] != "ALLOWED", "API-ключ не может создавать bucket")
|
||||
report(rights["put_to_other_bucket"] != "ALLOWED", "API-ключ не может писать в чужой bucket")
|
||||
report(rights["get_from_other_bucket"] not in ("ALLOWED",) and rights["get_from_other_bucket"] != "NoSuchBucket"
|
||||
or rights["get_from_other_bucket"] == "NoSuchBucket", "API-ключ не читает чужой bucket (NoSuchBucket/AccessDenied)")
|
||||
report(rights["put_object_own_bucket"] == "ALLOWED" and rights["delete_probe_own_bucket"] == "ALLOWED",
|
||||
"в своём bucket API-ключ работает (put/delete)")
|
||||
|
||||
# 3. Админские ключи не попали в API
|
||||
secrets = api_py("import os; print(' '.join(sorted(os.listdir('/run/secrets'))))")
|
||||
print("# /run/secrets в api:", secrets)
|
||||
report("admin" not in secrets, "в контейнере api нет админских S3-секретов")
|
||||
|
||||
# 4. Порты S3 не опубликованы на хост
|
||||
cid = compose("ps", "-q", "s3").stdout.strip()
|
||||
published = subprocess.run(["docker", "port", cid], capture_output=True, text=True).stdout.strip()
|
||||
report(published == "", f"S3 не публикует порты на хост (docker port: '{published or 'пусто'}')")
|
||||
|
||||
# 5. Из контейнеров вне сети storage S3 недостижим
|
||||
for svc in ("lb", "postgres", "valkey"):
|
||||
for port in (9000, 8888, 9333):
|
||||
r = compose("exec", "-T", svc, "wget", "-T", "2", "-O", "/dev/null", f"http://s3:{port}/", check=False)
|
||||
err = (r.stderr + r.stdout).lower()
|
||||
reached = r.returncode == 0 or "server returned error" in err or "http/1" in err
|
||||
report(not reached, f"{svc} -> s3:{port} недостижим")
|
||||
|
||||
# 6. Информация: что доступно из api внутри сети storage
|
||||
ports = api_py("""
|
||||
import socket, json
|
||||
res = {}
|
||||
for p in (9000, 8333, 8888, 9333, 8080):
|
||||
s = socket.socket(); s.settimeout(1)
|
||||
res[p] = s.connect_ex(("s3", p)) == 0
|
||||
print(json.dumps(res))
|
||||
""")
|
||||
print("INFO порты s3, открытые из api (внутри изолированной сети storage):", ports)
|
||||
|
||||
print("\nИТОГ:", "FAIL" if FAILED else "PASS")
|
||||
sys.exit(1 if FAILED else 0)
|
||||
@@ -0,0 +1,34 @@
|
||||
import base64
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
def call(base, method, path, body=None, headers=None, timeout=3.0):
|
||||
"""Возвращает (status, headers с ключами в нижнем регистре, bytes). Сетевые ошибки поднимаются наружу."""
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
h = {"Content-Type": "application/json"} if data else {}
|
||||
h.update(headers or {})
|
||||
req = urllib.request.Request(base + path, data=data, method=method, headers=h)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return r.status, {k.lower(): v for k, v in r.headers.items()}, r.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, {k.lower(): v for k, v in e.headers.items()}, e.read()
|
||||
|
||||
|
||||
def setup(base):
|
||||
"""Синтетический пользователь, сессия и чат из одного участника. Возвращает (auth_headers, chat_id)."""
|
||||
name = "load_" + uuid.uuid4().hex[:12]
|
||||
password = "load-password-" + uuid.uuid4().hex[:8]
|
||||
s, _, b = call(base, "POST", "/api/v1/users", {"username": name, "display_name": "Load", "password": password})
|
||||
assert s == 201, f"register failed: {s}"
|
||||
uid = json.loads(b)["id"]
|
||||
cred = base64.b64encode(f"{name}:{password}".encode()).decode()
|
||||
s, _, b = call(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred})
|
||||
assert s == 201, f"login failed: {s}"
|
||||
auth = {"Authorization": "Bearer " + json.loads(b)["token"]}
|
||||
s, _, b = call(base, "POST", "/api/v1/chats", {"title": "load", "member_ids": [uid]}, auth)
|
||||
assert s == 201, f"chat failed: {s}"
|
||||
return auth, json.loads(b)["id"]
|
||||
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Closed-loop нагрузка POST /messages через LB; во время неё выполняется action-скрипт (остановка реплики).
|
||||
Без прозрачных retry: каждая неудача = ошибка. Токены в вывод не попадают."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from common import call, setup
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--duration", type=float, default=40)
|
||||
ap.add_argument("--concurrency", type=int, default=8)
|
||||
ap.add_argument("--action-script")
|
||||
ap.add_argument("--action-at", type=float, default=10)
|
||||
ap.add_argument("--target-index", type=int, default=0)
|
||||
ap.add_argument("--output")
|
||||
a = ap.parse_args()
|
||||
|
||||
auth, chat = setup(a.base_url)
|
||||
path = f"/api/v1/chats/{chat}/messages"
|
||||
ids = set()
|
||||
for _ in range(40): # какие реплики видны через LB
|
||||
_, h, _ = call(a.base_url, "GET", "/api/v1/users/me", headers=auth)
|
||||
ids.add(h.get("x-instance-id"))
|
||||
ids = sorted(i for i in ids if i)
|
||||
|
||||
records, lock = [], threading.Lock() # (t, status, latency, instance)
|
||||
t_start = time.monotonic()
|
||||
t_end = t_start + a.duration
|
||||
|
||||
def worker():
|
||||
while time.monotonic() < t_end:
|
||||
t0 = time.monotonic()
|
||||
try:
|
||||
s, h, _ = call(a.base_url, "POST", path, {"text": "load"},
|
||||
{**auth, "Idempotency-Key": uuid.uuid4().hex}, timeout=3)
|
||||
inst, ver = h.get("x-instance-id"), h.get("x-app-version")
|
||||
except Exception:
|
||||
s, inst, ver = 0, None, None
|
||||
with lock:
|
||||
records.append((t0 - t_start, s, time.monotonic() - t0, inst, ver))
|
||||
|
||||
threads = [threading.Thread(target=worker) for _ in range(a.concurrency)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
|
||||
action = {}
|
||||
if a.action_script:
|
||||
time.sleep(a.action_at)
|
||||
target = ids[a.target_index % len(ids)]
|
||||
t0 = time.monotonic() - t_start
|
||||
rc = subprocess.run([a.action_script], env={**os.environ, "TARGET_INSTANCE_ID": target},
|
||||
capture_output=True, timeout=300).returncode
|
||||
action = {"target": target, "started_at": round(t0, 2),
|
||||
"finished_at": round(time.monotonic() - t_start, 2), "exit_code": rc}
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
ok = [r for r in records if r[1] == 201]
|
||||
bad = [r for r in records if r[1] != 201]
|
||||
lat = sorted(r[2] for r in ok)
|
||||
pct = lambda p: round(lat[min(len(lat) - 1, int(len(lat) * p))] * 1000, 1) if lat else None
|
||||
summary = {
|
||||
"duration_s": a.duration, "concurrency": a.concurrency, "replicas_seen": ids,
|
||||
"requests": len(records), "ok": len(ok), "errors": len(bad),
|
||||
"error_rate": round(len(bad) / max(1, len(records)), 4),
|
||||
"rps_ok": round(len(ok) / a.duration, 1),
|
||||
"latency_ms": {"p50": pct(0.50), "p95": pct(0.95), "p99": pct(0.99)},
|
||||
"error_statuses": {str(s): sum(1 for r in bad if r[1] == s) for s in {r[1] for r in bad}},
|
||||
"action": action,
|
||||
}
|
||||
if action:
|
||||
errs_after = [r[0] for r in bad if r[0] >= action["started_at"]]
|
||||
times = sorted(r[0] for r in ok if r[0] >= action["started_at"])
|
||||
gaps = [b - a_ for a_, b in zip([action["started_at"]] + times, times)]
|
||||
summary["errors_after_action"] = len(errs_after)
|
||||
summary["recovery_s"] = round(max(errs_after) - action["started_at"], 2) if errs_after else 0.0
|
||||
summary["max_stall_s"] = round(max(gaps), 2) if gaps else None
|
||||
summary["instances_in_last_5s"] = sorted({r[3] for r in ok if r[0] >= a.duration - 5 and r[3]})
|
||||
|
||||
vers = {}
|
||||
for r in ok:
|
||||
if r[4]:
|
||||
v = vers.setdefault(r[4], [r[0], r[0]])
|
||||
v[0], v[1] = min(v[0], r[0]), max(v[1], r[0])
|
||||
summary["versions_first_last_seen_s"] = {k: [round(x, 1) for x in v] for k, v in vers.items()}
|
||||
|
||||
timeline = {}
|
||||
for t, s, *_ in records:
|
||||
b = timeline.setdefault(int(t), {"ok": 0, "err": 0})
|
||||
b["ok" if s == 201 else "err"] += 1
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
if a.output:
|
||||
with open(a.output, "w") as f:
|
||||
json.dump({"summary": summary, "per_second": timeline}, f, ensure_ascii=False, indent=1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,281 @@
|
||||
"""Тесты вложений, уровень 4. Нужен запущенный стенд.
|
||||
Запуск: python3 -m unittest student_tests.test_attachments_level4 -v
|
||||
Тесты отказов сами останавливают/запускают s3 и временно ломают INSERT в БД; volumes не удаляются."""
|
||||
import base64
|
||||
import hashlib
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
import unittest
|
||||
import uuid
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote, urlparse
|
||||
|
||||
BASE = os.environ.get("BASE_URL", "http://localhost:8080")
|
||||
URL = urlparse(BASE)
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PASSWORD = "correct-horse-battery"
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
SIG = b"\x89PNG\r\n\x1a\n"
|
||||
|
||||
try:
|
||||
from PIL import Image
|
||||
import io
|
||||
except ImportError: # JPEG-тесты будут пропущены
|
||||
Image = None
|
||||
|
||||
|
||||
def http_call(method, path, body=None, headers=None, raw=None, timeout=60):
|
||||
"""Возвращает (status, headers, bytes). Если сервер ответил раньше, чем клиент дослал тело, читаем ответ."""
|
||||
h = dict(headers or {})
|
||||
data = raw
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
if data is not None and not hasattr(data, "__next__"):
|
||||
h["Content-Length"] = str(len(data))
|
||||
conn = http.client.HTTPConnection(URL.hostname, URL.port, timeout=timeout)
|
||||
try:
|
||||
try:
|
||||
conn.request(method, path, body=data, headers=h, encode_chunked=hasattr(data, "__next__"))
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
pass
|
||||
resp = conn.getresponse()
|
||||
return resp.status, {k.lower(): v for k, v in resp.getheaders()}, resp.read()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def jcall(method, path, body=None, headers=None):
|
||||
status, _, raw = http_call(method, path, body, headers)
|
||||
return status, (json.loads(raw) if raw else None)
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT,
|
||||
check=True, capture_output=True, text=True).stdout
|
||||
|
||||
|
||||
def psql(sql):
|
||||
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-tAc", sql).strip()
|
||||
|
||||
|
||||
def reconcile_summary():
|
||||
out = compose("run", "--rm", "--no-deps", "-T", "reconciler", "python", "-m", "src.reconciler")
|
||||
return json.loads(out.strip().splitlines()[-1])
|
||||
|
||||
|
||||
def wait_ready(timeout=90):
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
if http_call("GET", "/health/ready")[0] == 200:
|
||||
return
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise AssertionError("API not ready")
|
||||
|
||||
|
||||
def new_user():
|
||||
name = "u" + uuid.uuid4().hex[:12]
|
||||
st, user = jcall("POST", "/api/v1/users", {"username": name, "display_name": "T", "password": PASSWORD})
|
||||
assert st == 201, st
|
||||
basic = base64.b64encode(f"{name}:{PASSWORD}".encode()).decode()
|
||||
st, sess = jcall("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic})
|
||||
assert st == 201, st
|
||||
return user, {"Authorization": "Bearer " + sess["token"]}
|
||||
|
||||
|
||||
def new_chat(auth, member_ids):
|
||||
st, chat = jcall("POST", "/api/v1/chats", {"title": "att", "member_ids": member_ids}, auth)
|
||||
assert st == 201, st
|
||||
return chat["id"]
|
||||
|
||||
|
||||
def upload(auth, chat, data, ctype="image/png", filename="a.png"):
|
||||
return http_call("POST", f"/api/v1/chats/{chat}/attachments?filename={quote(filename, safe='')}",
|
||||
headers={**auth, "Content-Type": ctype}, raw=data)
|
||||
|
||||
|
||||
def chunk(t, d):
|
||||
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)
|
||||
|
||||
|
||||
def png_1bit(w, h):
|
||||
rows = b"".join(b"\x00" + b"\x00" * ((w + 7) // 8) for _ in range(h))
|
||||
return SIG + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 1, 0, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def jpeg_bytes():
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (32, 32), (200, 30, 30)).save(buf, "JPEG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
class AttachmentsLevel4(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
wait_ready()
|
||||
cls.alice, cls.a = new_user()
|
||||
cls.bob, cls.b = new_user()
|
||||
cls.eve, cls.e = new_user()
|
||||
cls.chat = new_chat(cls.a, [cls.alice["id"], cls.bob["id"]]) # alice + bob
|
||||
cls.chat_b = new_chat(cls.a, [cls.alice["id"]]) # другой чат alice
|
||||
cls.chat_e = new_chat(cls.e, [cls.eve["id"]]) # чат eve
|
||||
cls.att = cls.ok(cls.a, cls.chat)
|
||||
cls.att_b = cls.ok(cls.a, cls.chat_b)
|
||||
cls.att_e = cls.ok(cls.e, cls.chat_e)
|
||||
|
||||
@classmethod
|
||||
def ok(cls, auth, chat):
|
||||
st, _, raw = upload(auth, chat, SAMPLE)
|
||||
assert st == 201, st
|
||||
return json.loads(raw)
|
||||
|
||||
def send(self, auth, chat, ids):
|
||||
return jcall("POST", f"/api/v1/chats/{chat}/messages", {"text": "", "attachment_ids": ids},
|
||||
{**auth, "Idempotency-Key": uuid.uuid4().hex})
|
||||
|
||||
def assertStatus(self, got, want):
|
||||
self.assertEqual(got, want)
|
||||
self.assertLess(got, 500, "пользовательская ошибка не должна быть 5xx")
|
||||
|
||||
# --- базовый сценарий ---
|
||||
def test_roundtrip_sha256_and_second_member(self):
|
||||
self.assertEqual(self.att["sha256"], hashlib.sha256(SAMPLE).hexdigest())
|
||||
self.assertEqual(self.att["size_bytes"], len(SAMPLE))
|
||||
st, msg = self.send(self.a, self.chat, [self.att["id"]])
|
||||
self.assertEqual(st, 201)
|
||||
st, page = jcall("GET", f"/api/v1/chats/{self.chat}/messages", headers=self.b)
|
||||
self.assertEqual(st, 200)
|
||||
self.assertIn(self.att["id"], [i for m in page["items"] for i in m["attachment_ids"]])
|
||||
st, h, raw = http_call("GET", f"/api/v1/attachments/{self.att['id']}/content", headers=self.b)
|
||||
self.assertEqual((st, h["content-type"]), (200, "image/png"))
|
||||
self.assertEqual(hashlib.sha256(raw).hexdigest(), self.att["sha256"])
|
||||
|
||||
# --- размер и пиксели ---
|
||||
def test_too_large_content_length(self):
|
||||
st, _, _ = upload(self.a, self.chat, SIG + os.urandom(MAX_BYTES + 1))
|
||||
self.assertStatus(st, 413)
|
||||
|
||||
def test_too_large_chunked_without_content_length(self):
|
||||
def gen():
|
||||
yield SIG
|
||||
for _ in range(11):
|
||||
yield os.urandom(1024 * 1024)
|
||||
st, _, _ = http_call("POST", f"/api/v1/chats/{self.chat}/attachments?filename=a.png",
|
||||
headers={**self.a, "Content-Type": "image/png", "Transfer-Encoding": "chunked"}, raw=gen())
|
||||
self.assertStatus(st, 413)
|
||||
|
||||
def test_pixel_limit(self):
|
||||
st, _, _ = upload(self.a, self.chat, png_1bit(8000, 8000)) # 64 млн пикселей, файл несколько КиБ
|
||||
self.assertStatus(st, 413)
|
||||
st, _, _ = upload(self.a, self.chat, png_1bit(6000, 6000)) # 36 млн: допустимо
|
||||
self.assertEqual(st, 201)
|
||||
|
||||
# --- повреждённые файлы и подмена MIME ---
|
||||
def test_corrupted_png(self):
|
||||
flipped = bytearray(SAMPLE)
|
||||
flipped[len(flipped) // 2] ^= 0xFF
|
||||
cases = {"truncated": SAMPLE[:-20], "bad_crc": bytes(flipped), "random_after_signature": SIG + os.urandom(2000),
|
||||
"empty": b"", "only_signature": SIG}
|
||||
for name, data in cases.items():
|
||||
with self.subTest(name):
|
||||
self.assertStatus(upload(self.a, self.chat, data)[0], 415)
|
||||
|
||||
@unittest.skipIf(Image is None, "pip3 install pillow")
|
||||
def test_corrupted_jpeg_and_valid_jpeg(self):
|
||||
good = jpeg_bytes()
|
||||
st, _, raw = upload(self.a, self.chat, good, "image/jpeg", "a.jpg")
|
||||
self.assertEqual(st, 201)
|
||||
self.assertEqual(json.loads(raw)["content_type"], "image/jpeg")
|
||||
self.assertStatus(upload(self.a, self.chat, good[:-30], "image/jpeg", "a.jpg")[0], 415)
|
||||
|
||||
def test_mime_spoofing(self):
|
||||
cases = [("png as jpeg", SAMPLE, "image/jpeg"), ("gif as png", b"GIF89a" + b"0" * 200, "image/png"),
|
||||
("text as png", b"hello world" * 50, "image/png"), ("svg as png", b"<svg xmlns='x'/>", "image/png"),
|
||||
("png as text/plain", SAMPLE, "text/plain"), ("png as octet-stream", SAMPLE, "application/octet-stream")]
|
||||
for name, data, ctype in cases:
|
||||
with self.subTest(name):
|
||||
self.assertStatus(upload(self.a, self.chat, data, ctype)[0], 415)
|
||||
if Image is not None:
|
||||
self.assertStatus(upload(self.a, self.chat, jpeg_bytes(), "image/png")[0], 415)
|
||||
|
||||
def test_dangerous_filenames(self):
|
||||
for name in ["../a.png", "a/b.png", "a\\b.png", "a\x00.png", "a\n.png", " ", "x" * 256]:
|
||||
with self.subTest(repr(name)):
|
||||
self.assertStatus(upload(self.a, self.chat, SAMPLE, filename=name)[0], 400)
|
||||
st, _, raw = upload(self.a, self.chat, SAMPLE, filename="фото №1 (копия).png")
|
||||
self.assertEqual(st, 201) # имя только для отображения; ключ S3 назначает сервер
|
||||
self.assertEqual(json.loads(raw)["filename"], "фото №1 (копия).png")
|
||||
|
||||
# --- доступ и привязка ---
|
||||
def test_foreign_and_unknown_attachment_ids(self):
|
||||
self.assertStatus(self.send(self.a, self.chat, [self.att_e["id"]])[0], 404) # вложение чужого чата и чужого пользователя
|
||||
self.assertStatus(self.send(self.a, self.chat, [str(uuid.uuid4())])[0], 404)
|
||||
self.assertStatus(self.send(self.a, self.chat, ["not-a-uuid"])[0], 400)
|
||||
self.assertStatus(self.send(self.a, self.chat, [self.att["id"], self.att["id"]])[0], 400)
|
||||
|
||||
def test_attachment_from_another_chat_of_same_user(self):
|
||||
self.assertStatus(self.send(self.a, self.chat, [self.att_b["id"]])[0], 404) # chat_b, а не chat
|
||||
self.assertStatus(self.send(self.a, self.chat_b, [self.att_b["id"]])[0], 201)
|
||||
|
||||
def test_outsider_has_no_access(self):
|
||||
for path in (f"/api/v1/attachments/{self.att['id']}", f"/api/v1/attachments/{self.att['id']}/content"):
|
||||
self.assertStatus(http_call("GET", path, headers=self.e)[0], 404)
|
||||
self.assertStatus(http_call("GET", path)[0], 401)
|
||||
self.assertStatus(upload(self.e, self.chat, SAMPLE)[0], 404)
|
||||
self.assertStatus(self.send(self.e, self.chat, [self.att["id"]])[0], 404)
|
||||
|
||||
# --- обрыв загрузки ---
|
||||
def test_aborted_upload_leaves_no_metadata(self):
|
||||
before = psql(f"SELECT count(*) FROM attachments WHERE chat_id = '{self.chat_b}'")
|
||||
sock = socket.create_connection((URL.hostname, URL.port), timeout=10)
|
||||
head = (f"POST /api/v1/chats/{self.chat_b}/attachments?filename=cut.png HTTP/1.1\r\nHost: x\r\n"
|
||||
f"Authorization: {self.a['Authorization']}\r\nContent-Type: image/png\r\n"
|
||||
f"Content-Length: {5 * 1024 * 1024}\r\n\r\n").encode()
|
||||
sock.sendall(head + SIG + os.urandom(1024 * 1024))
|
||||
sock.close() # обрыв на середине тела
|
||||
time.sleep(3)
|
||||
self.assertEqual(psql(f"SELECT count(*) FROM attachments WHERE chat_id = '{self.chat_b}'"), before)
|
||||
|
||||
# --- отказы зависимостей ---
|
||||
def test_s3_down_gives_503_and_recovers(self):
|
||||
compose("stop", "s3")
|
||||
try:
|
||||
t = time.time()
|
||||
self.assertEqual(upload(self.a, self.chat, SAMPLE)[0], 503)
|
||||
self.assertLess(time.time() - t, 20, "ответ при недоступном S3 должен быть ограничен по времени")
|
||||
self.assertEqual(http_call("GET", f"/api/v1/attachments/{self.att['id']}/content", headers=self.a)[0], 503)
|
||||
self.assertEqual(http_call("GET", f"/api/v1/attachments/{self.att['id']}", headers=self.a)[0], 200) # метаданные из БД
|
||||
finally:
|
||||
compose("start", "s3")
|
||||
end = time.time() + 90
|
||||
while time.time() < end:
|
||||
st, _, raw = http_call("GET", f"/api/v1/attachments/{self.att['id']}/content", headers=self.b)
|
||||
if st == 200:
|
||||
break
|
||||
time.sleep(2)
|
||||
self.assertEqual(st, 200)
|
||||
self.assertEqual(hashlib.sha256(raw).hexdigest(), self.att["sha256"])
|
||||
|
||||
def test_db_insert_failure_after_s3_put_is_compensated(self):
|
||||
before = reconcile_summary()["s3_objects"]
|
||||
psql("ALTER TABLE attachments ADD CONSTRAINT zz_fail CHECK (false) NOT VALID") # ломает только новые INSERT
|
||||
try:
|
||||
st, _, _ = upload(self.a, self.chat, SAMPLE)
|
||||
self.assertIn(st, (500, 503))
|
||||
finally:
|
||||
psql("ALTER TABLE attachments DROP CONSTRAINT zz_fail")
|
||||
self.assertEqual(reconcile_summary()["s3_objects"], before, "объект остался в S3: компенсация не сработала")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
"""30 параллельных POST с одним Idempotency-Key через LB: ровно одно сообщение, везде 201 и один id."""
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
|
||||
from common import call, setup
|
||||
|
||||
BASE = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080"
|
||||
THREADS, ROUNDS = 30, 5
|
||||
|
||||
auth, chat = setup(BASE)
|
||||
path = f"/api/v1/chats/{chat}/messages"
|
||||
replicas = set()
|
||||
|
||||
for rnd in range(ROUNDS):
|
||||
key = uuid.uuid4().hex
|
||||
barrier = threading.Barrier(THREADS)
|
||||
results = [None] * THREADS
|
||||
|
||||
def work(i, rnd=rnd, key=key, barrier=barrier, results=results):
|
||||
barrier.wait()
|
||||
s, h, b = call(BASE, "POST", path, {"text": f"parallel {rnd}"}, {**auth, "Idempotency-Key": key}, timeout=10)
|
||||
results[i] = (s, h.get("x-instance-id"), json.loads(b) if s == 201 else None)
|
||||
|
||||
ts = [threading.Thread(target=work, args=(i,)) for i in range(THREADS)]
|
||||
[t.start() for t in ts]
|
||||
[t.join() for t in ts]
|
||||
codes = {r[0] for r in results}
|
||||
msg_ids = {r[2]["id"] for r in results if r[0] == 201}
|
||||
replicas |= {r[1] for r in results}
|
||||
assert codes == {201}, f"round {rnd}: codes {codes}"
|
||||
assert len(msg_ids) == 1, f"round {rnd}: {len(msg_ids)} different messages"
|
||||
s, _, _ = call(BASE, "POST", path, {"text": "other body"}, {**auth, "Idempotency-Key": key})
|
||||
assert s == 409, f"round {rnd}: other body gave {s}"
|
||||
|
||||
s, _, b = call(BASE, "GET", path + "?limit=100", headers=auth)
|
||||
count = len(json.loads(b)["items"])
|
||||
assert count == ROUNDS, f"history has {count} messages, expected {ROUNDS}"
|
||||
print(json.dumps({"rounds": ROUNDS, "parallel_requests_per_round": THREADS,
|
||||
"messages_in_history": count, "replicas_that_answered": sorted(r for r in replicas if r)}))
|
||||
print("PASS: same key in parallel -> exactly one message; different body -> 409")
|
||||
@@ -0,0 +1,585 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import concurrent.futures
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import uuid
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
import base64
|
||||
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
|
||||
PASSWORD = "correct-horse-battery"
|
||||
|
||||
|
||||
def request(method, path, expected, body=None, headers=None, raw_body=None):
|
||||
url = BASE_URL + path
|
||||
|
||||
request_headers = dict(headers or {})
|
||||
|
||||
if raw_body is not None:
|
||||
data = raw_body
|
||||
elif body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
else:
|
||||
data = None
|
||||
|
||||
if body is not None or raw_body is not None:
|
||||
request_headers.setdefault("Content-Type", "application/json")
|
||||
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
method=method,
|
||||
headers=request_headers,
|
||||
)
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as response:
|
||||
status = response.status
|
||||
response_headers = response.headers
|
||||
response_body = response.read()
|
||||
|
||||
except urllib.error.HTTPError as exc:
|
||||
status = exc.code
|
||||
response_headers = exc.headers
|
||||
response_body = exc.read()
|
||||
|
||||
if status != expected:
|
||||
raise AssertionError(
|
||||
f"{method} {path}: expected HTTP {expected}, got {status}. "
|
||||
f"Body={response_body!r}"
|
||||
)
|
||||
|
||||
request_id = response_headers.get("X-Request-Id")
|
||||
if not request_id:
|
||||
raise AssertionError(
|
||||
f"{method} {path}: missing X-Request-Id"
|
||||
)
|
||||
|
||||
parsed = None
|
||||
|
||||
if response_body:
|
||||
content_type = response_headers.get_content_type()
|
||||
|
||||
if content_type == "application/json":
|
||||
parsed = json.loads(response_body.decode("utf-8"))
|
||||
|
||||
if status >= 400:
|
||||
codes = {
|
||||
400: "invalid_request", 401: "unauthorized", 404: "not_found",
|
||||
409: "conflict", 413: "payload_too_large", 415: "unsupported_media_type",
|
||||
429: "rate_limited", 500: "internal_error", 503: "unavailable",
|
||||
}
|
||||
if not isinstance(parsed, dict) or set(parsed) != {"error"}:
|
||||
raise AssertionError(f"Invalid error response: {parsed!r}")
|
||||
error = parsed["error"]
|
||||
if not isinstance(error, dict) or set(error) != {"code", "message", "request_id"}:
|
||||
raise AssertionError(f"Invalid error fields: {error!r}")
|
||||
if error["code"] != codes[status] or error["request_id"] != request_id:
|
||||
raise AssertionError(f"Wrong error code or request ID: {error!r}")
|
||||
if not isinstance(error["message"], str) or not error["message"].strip():
|
||||
raise AssertionError("Error message must be a nonempty string")
|
||||
|
||||
return {
|
||||
"status": status,
|
||||
"headers": response_headers,
|
||||
"json": parsed,
|
||||
"bytes": response_body,
|
||||
}
|
||||
|
||||
|
||||
def unique_username(prefix):
|
||||
# username должен соответствовать [a-z0-9_]{3,32}
|
||||
suffix = uuid.uuid4().hex[:12]
|
||||
return f"{prefix}_{suffix}"
|
||||
|
||||
|
||||
def basic(username, password=PASSWORD):
|
||||
raw = f"{username}:{password}".encode("utf-8")
|
||||
return "Basic " + base64.b64encode(raw).decode()
|
||||
|
||||
|
||||
def create_user(prefix="usr", login=True):
|
||||
user = request("POST", "/api/v1/users", 201, body={
|
||||
"username": unique_username(prefix),
|
||||
"display_name": f"Test {prefix}",
|
||||
"password": PASSWORD,
|
||||
})["json"]
|
||||
if login:
|
||||
session = request("POST", "/api/v1/auth/sessions", 201,
|
||||
headers={"Authorization": basic(user["username"])})["json"]
|
||||
user["token"] = session["token"]
|
||||
return user
|
||||
|
||||
|
||||
def auth(user):
|
||||
return {"Authorization": "Bearer " + user["token"]}
|
||||
|
||||
|
||||
def create_chat(owner, members, title="Student test chat"):
|
||||
result = request(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
headers=auth(owner),
|
||||
body={
|
||||
"title": title,
|
||||
"member_ids": [u["id"] for u in members],
|
||||
},
|
||||
)
|
||||
|
||||
return result["json"]
|
||||
|
||||
|
||||
def create_message(user, chat, text):
|
||||
return request(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
201,
|
||||
headers=auth(user),
|
||||
body={"text": text},
|
||||
)["json"]
|
||||
|
||||
|
||||
def test_malformed_json():
|
||||
for body in (b'{"username": "broken",', b"\xff"):
|
||||
request("POST", "/api/v1/users", 400, raw_body=body)
|
||||
|
||||
print("PASS malformed JSON and invalid UTF-8 -> 400 with error envelope")
|
||||
|
||||
|
||||
def test_duplicate_username():
|
||||
username = unique_username("dup")
|
||||
|
||||
body = {
|
||||
"username": username,
|
||||
"display_name": "First",
|
||||
"password": PASSWORD,
|
||||
}
|
||||
|
||||
request(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
201,
|
||||
body=body,
|
||||
)
|
||||
|
||||
request(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
409,
|
||||
body={
|
||||
"username": username,
|
||||
"display_name": "Second",
|
||||
"password": PASSWORD,
|
||||
},
|
||||
)
|
||||
|
||||
print("PASS duplicate username -> 409")
|
||||
|
||||
|
||||
def test_outsider_chat():
|
||||
alice = create_user("alice")
|
||||
bob = create_user("bob")
|
||||
eve = create_user("eve")
|
||||
|
||||
chat = create_chat(
|
||||
alice,
|
||||
[alice, bob],
|
||||
"Private chat",
|
||||
)
|
||||
|
||||
request(
|
||||
"GET",
|
||||
f"/api/v1/chats/{chat['id']}",
|
||||
404,
|
||||
headers=auth(eve),
|
||||
)
|
||||
|
||||
request(
|
||||
"GET",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
404,
|
||||
headers=auth(eve),
|
||||
)
|
||||
|
||||
request(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
404,
|
||||
headers=auth(eve),
|
||||
body={"text": "Not allowed"},
|
||||
)
|
||||
page = request("GET", "/api/v1/chats", 200, headers=auth(eve))["json"]
|
||||
if page != {"items": [], "next_cursor": None}:
|
||||
raise AssertionError("Outsider can see a private chat in the list")
|
||||
|
||||
print("PASS outsider cannot access chat -> 404")
|
||||
|
||||
|
||||
def test_empty_and_whitespace_message():
|
||||
alice = create_user("emptya")
|
||||
bob = create_user("emptyb")
|
||||
|
||||
chat = create_chat(
|
||||
alice,
|
||||
[alice, bob],
|
||||
"Empty message test",
|
||||
)
|
||||
|
||||
request(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
400,
|
||||
headers=auth(alice),
|
||||
body={"text": ""},
|
||||
)
|
||||
|
||||
request(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
400,
|
||||
headers=auth(alice),
|
||||
body={"text": " \t\n"},
|
||||
)
|
||||
|
||||
print("PASS empty/whitespace message -> 400")
|
||||
|
||||
|
||||
def test_extra_json_field():
|
||||
request(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
400,
|
||||
body={
|
||||
"username": unique_username("extra"),
|
||||
"display_name": "Extra",
|
||||
"password": PASSWORD,
|
||||
"admin": True,
|
||||
},
|
||||
)
|
||||
|
||||
print("PASS extra JSON field -> 400")
|
||||
|
||||
|
||||
def test_multi_page_history():
|
||||
alice = create_user("pagea")
|
||||
bob = create_user("pageb")
|
||||
|
||||
chat = create_chat(
|
||||
alice,
|
||||
[alice, bob],
|
||||
"Pagination test",
|
||||
)
|
||||
|
||||
expected = []
|
||||
|
||||
for i in range(7):
|
||||
message = create_message(
|
||||
alice,
|
||||
chat,
|
||||
f"pagination-message-{i}",
|
||||
)
|
||||
|
||||
expected.append(message)
|
||||
|
||||
expected.sort(
|
||||
key=lambda message: (
|
||||
datetime.fromisoformat(
|
||||
message["created_at"].replace("Z", "+00:00")
|
||||
),
|
||||
uuid.UUID(message["id"]).int,
|
||||
)
|
||||
)
|
||||
|
||||
expected_ids = [
|
||||
message["id"]
|
||||
for message in expected
|
||||
]
|
||||
|
||||
collected = []
|
||||
cursor = None
|
||||
|
||||
for _ in range(len(expected) + 1):
|
||||
path = (
|
||||
f"/api/v1/chats/{chat['id']}/messages"
|
||||
f"?limit=2"
|
||||
)
|
||||
|
||||
if cursor is not None:
|
||||
path += "&cursor=" + urllib.parse.quote(
|
||||
cursor,
|
||||
safe="",
|
||||
)
|
||||
|
||||
page = request(
|
||||
"GET",
|
||||
path,
|
||||
200,
|
||||
headers=auth(bob),
|
||||
)["json"]
|
||||
|
||||
ids = [item["id"] for item in page["items"]]
|
||||
collected.extend(ids)
|
||||
|
||||
cursor = page["next_cursor"]
|
||||
|
||||
if cursor is None:
|
||||
break
|
||||
else:
|
||||
raise AssertionError("Pagination did not reach the last page")
|
||||
|
||||
if collected != expected_ids:
|
||||
raise AssertionError(
|
||||
"Pagination lost, duplicated or reordered messages.\n"
|
||||
f"Expected: {expected_ids}\n"
|
||||
f"Received: {collected}"
|
||||
)
|
||||
|
||||
if len(collected) != len(set(collected)):
|
||||
raise AssertionError(
|
||||
"Pagination returned duplicate messages"
|
||||
)
|
||||
|
||||
print(
|
||||
f"PASS pagination: {len(collected)} messages "
|
||||
"read through multiple pages"
|
||||
)
|
||||
|
||||
|
||||
def test_concurrent_100_messages():
|
||||
users = [
|
||||
create_user(f"c{i}")
|
||||
for i in range(10)
|
||||
]
|
||||
|
||||
chat = create_chat(
|
||||
users[0],
|
||||
users,
|
||||
"Concurrency test",
|
||||
)
|
||||
|
||||
def worker(client_index):
|
||||
sent = []
|
||||
|
||||
for message_index in range(10):
|
||||
text = (
|
||||
f"client-{client_index}-"
|
||||
f"message-{message_index}"
|
||||
)
|
||||
|
||||
result = create_message(
|
||||
users[client_index],
|
||||
chat,
|
||||
text,
|
||||
)
|
||||
|
||||
sent.append(result)
|
||||
|
||||
return sent
|
||||
|
||||
all_sent = []
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(
|
||||
max_workers=10
|
||||
) as executor:
|
||||
futures = [
|
||||
executor.submit(worker, i)
|
||||
for i in range(10)
|
||||
]
|
||||
|
||||
for future in concurrent.futures.as_completed(
|
||||
futures
|
||||
):
|
||||
all_sent.extend(future.result())
|
||||
|
||||
if len(all_sent) != 100:
|
||||
raise AssertionError(
|
||||
f"Expected 100 successful POSTs, got {len(all_sent)}"
|
||||
)
|
||||
|
||||
page = request(
|
||||
"GET",
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=100",
|
||||
200,
|
||||
headers=auth(users[0]),
|
||||
)["json"]
|
||||
|
||||
messages = page["items"]
|
||||
|
||||
if len(messages) != 100:
|
||||
raise AssertionError(
|
||||
f"Expected exactly 100 stored messages, "
|
||||
f"got {len(messages)}"
|
||||
)
|
||||
|
||||
ids = [message["id"] for message in messages]
|
||||
|
||||
if len(set(ids)) != 100:
|
||||
raise AssertionError(
|
||||
"Expected 100 unique message IDs"
|
||||
)
|
||||
|
||||
if set(ids) != {message["id"] for message in all_sent}:
|
||||
raise AssertionError("Stored messages differ from successful POST responses")
|
||||
|
||||
texts = [message["text"] for message in messages]
|
||||
|
||||
if len(set(texts)) != 100:
|
||||
raise AssertionError(
|
||||
"Expected 100 unique message texts"
|
||||
)
|
||||
|
||||
if page["next_cursor"] is not None:
|
||||
raise AssertionError(
|
||||
"100 messages with limit=100 should fit in one page"
|
||||
)
|
||||
|
||||
print(
|
||||
"PASS concurrency: 10 clients sent 100 messages; "
|
||||
"exactly 100 unique messages stored"
|
||||
)
|
||||
|
||||
|
||||
def test_invalid_chat_ids():
|
||||
user = create_user("uuid")
|
||||
for chat_id, expected in (("not-a-uuid", 400), (str(uuid.uuid4()), 404)):
|
||||
path = f"/api/v1/chats/{chat_id}"
|
||||
request("GET", path, expected, headers=auth(user))
|
||||
request("GET", path + "/messages", expected, headers=auth(user))
|
||||
request("POST", path + "/messages", expected,
|
||||
headers=auth(user), body={"text": "Test"})
|
||||
print("PASS invalid chat UUID -> 400; unknown valid UUID -> 404")
|
||||
|
||||
|
||||
def test_chat_member_limits():
|
||||
users = [create_user("member", login=(i == 0)) for i in range(101)]
|
||||
owner = users[0]
|
||||
for members in ([], users, [owner, owner], users[1:3]):
|
||||
request("POST", "/api/v1/chats", 400, headers=auth(owner), body={
|
||||
"title": "Invalid members", "member_ids": [user["id"] for user in members],
|
||||
})
|
||||
request("POST", "/api/v1/chats", 400, headers=auth(owner), body={
|
||||
"title": "Unknown member", "member_ids": [owner["id"], str(uuid.uuid4())],
|
||||
})
|
||||
chat = create_chat(owner, users[:100])
|
||||
if len(chat["member_ids"]) != 100:
|
||||
raise AssertionError("Chat must accept exactly 100 members")
|
||||
print("PASS chat members: 1..100, unique, existing, caller included")
|
||||
|
||||
|
||||
def test_invalid_pagination():
|
||||
user = create_user("cursor")
|
||||
chat = create_chat(user, [user])
|
||||
other_chat = create_chat(user, [user])
|
||||
other_message = create_message(user, other_chat, "Other history")
|
||||
paths = ("/api/v1/chats", f"/api/v1/chats/{chat['id']}/messages")
|
||||
for path in paths:
|
||||
for query in ("cursor=", "cursor=unknown", "limit=0", "limit=101", "limit=abc", "limit=1.5"):
|
||||
request("GET", path + "?" + query, 400, headers=auth(user))
|
||||
request("GET", paths[1] + "?cursor=" + other_message["id"], 400, headers=auth(user))
|
||||
print("PASS invalid cursor/limit and cursor from another chat -> 400")
|
||||
|
||||
|
||||
def test_multi_page_chats():
|
||||
user = create_user("chatpage")
|
||||
chats = [create_chat(user, [user], f"Chat {i}") for i in range(7)]
|
||||
chats.sort(key=lambda chat: (chat["created_at"], uuid.UUID(chat["id"]).int))
|
||||
collected = []
|
||||
cursor = None
|
||||
for page_number in range(len(chats) + 1):
|
||||
query = {"limit": 2 if page_number == 0 else 3}
|
||||
if cursor is not None:
|
||||
query["cursor"] = cursor
|
||||
page = request("GET", "/api/v1/chats?" + urllib.parse.urlencode(query),
|
||||
200, headers=auth(user))["json"]
|
||||
collected.extend(chat["id"] for chat in page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
else:
|
||||
raise AssertionError("Chat pagination did not reach the last page")
|
||||
if collected != [chat["id"] for chat in chats]:
|
||||
raise AssertionError("Chat pagination lost, duplicated or reordered chats")
|
||||
print("PASS pagination: 7 chats, changing limit between pages")
|
||||
|
||||
|
||||
def test_validation_and_unicode():
|
||||
for display_name in ("", " \t", "x" * 101, 123, None):
|
||||
request("POST", "/api/v1/users", 400, body={
|
||||
"username": unique_username("invalid"), "display_name": display_name, "password": PASSWORD,
|
||||
})
|
||||
request("POST", "/api/v1/users", 400,
|
||||
body={"username": True, "display_name": "Test", "password": PASSWORD})
|
||||
for password in ("short", "x" * 129, 12345678901234, None):
|
||||
request("POST", "/api/v1/users", 400, body={
|
||||
"username": unique_username("badpw"), "display_name": "Test", "password": password,
|
||||
})
|
||||
request("POST", "/api/v1/users", 400,
|
||||
body={"username": unique_username("nopw"), "display_name": "Test"})
|
||||
|
||||
unicode_password = "\U00020000" * 12 # пароль не из ASCII проходит через Basic/UTF-8 и KDF
|
||||
user = request("POST", "/api/v1/users", 201, body={
|
||||
"username": unique_username("unicode"), "display_name": "\U00020000" * 100,
|
||||
"password": unicode_password,
|
||||
})["json"]
|
||||
session = request("POST", "/api/v1/auth/sessions", 201,
|
||||
headers={"Authorization": basic(user["username"], unicode_password)})["json"]
|
||||
user["token"] = session["token"]
|
||||
|
||||
chat = create_chat(user, [user])
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
text = "\U00020000" * 4000
|
||||
message = create_message(user, chat, text)
|
||||
if message["text"] != text:
|
||||
raise AssertionError("Unicode message was altered")
|
||||
for invalid in (text + "x", 123, None):
|
||||
request("POST", path, 400, headers=auth(user), body={"text": invalid})
|
||||
|
||||
request("GET", "/api/v1/users/me", 401)
|
||||
request("GET", "/api/v1/users/me", 401, headers={"X-User-Id": user["id"]})
|
||||
request("GET", "/api/v1/users/me", 401,
|
||||
headers={"Authorization": basic(user["username"], unicode_password)})
|
||||
print("PASS strict types, Unicode, password rules, Bearer-only identification")
|
||||
|
||||
|
||||
def main():
|
||||
tests = [
|
||||
test_malformed_json,
|
||||
test_duplicate_username,
|
||||
test_outsider_chat,
|
||||
test_empty_and_whitespace_message,
|
||||
test_extra_json_field,
|
||||
test_multi_page_history,
|
||||
test_concurrent_100_messages,
|
||||
test_invalid_chat_ids,
|
||||
test_chat_member_limits,
|
||||
test_invalid_pagination,
|
||||
test_multi_page_chats,
|
||||
test_validation_and_unicode,
|
||||
]
|
||||
|
||||
print(f"Testing {BASE_URL}")
|
||||
|
||||
for test in tests:
|
||||
test()
|
||||
|
||||
print()
|
||||
print(
|
||||
f"PASS: {len(tests)} student test scenarios completed"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Exception as exc:
|
||||
print(
|
||||
f"FAIL: {type(exc).__name__}: {exc}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Проверки уровня 4. Нужен запущенный стенд (docker compose up -d --build).
|
||||
Тесты отказов сами останавливают и запускают valkey/postgres/api, volumes не удаляются.
|
||||
Запуск: python3 -m unittest discover -s student_tests -p "test_level4.py" -v
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
BASE = os.environ.get("BASE_URL", "http://localhost:8080")
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PASSWORD = "correct-horse-battery"
|
||||
|
||||
|
||||
def call(method, path, body=None, headers=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
h = {"Content-Type": "application/json"} if body is not None else {}
|
||||
h.update(headers or {})
|
||||
req = urllib.request.Request(BASE + path, data=data, method=method, headers=h)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15) as resp:
|
||||
raw = resp.read()
|
||||
return resp.status, (json.loads(raw) if raw else None)
|
||||
except urllib.error.HTTPError as exc:
|
||||
raw = exc.read()
|
||||
try:
|
||||
return exc.code, (json.loads(raw) if raw else None)
|
||||
except ValueError:
|
||||
return exc.code, None
|
||||
|
||||
|
||||
def register(username=None):
|
||||
username = username or "u" + uuid.uuid4().hex[:12]
|
||||
status, user = call("POST", "/api/v1/users",
|
||||
{"username": username, "display_name": "Test", "password": PASSWORD})
|
||||
assert status == 201, status
|
||||
return user
|
||||
|
||||
|
||||
def login(username, password=PASSWORD):
|
||||
basic = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
return call("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic})
|
||||
|
||||
|
||||
def bearer(token):
|
||||
return {"Authorization": "Bearer " + token}
|
||||
|
||||
|
||||
def compose(*args, env=None):
|
||||
full_env = dict(os.environ)
|
||||
full_env.update(env or {})
|
||||
result = subprocess.run(["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=ROOT, env=full_env, check=True, capture_output=True, text=True)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def wait_ready(timeout=90):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
if call("GET", "/health/ready")[0] == 200:
|
||||
return
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise AssertionError("API did not become ready")
|
||||
|
||||
|
||||
def new_session():
|
||||
user = register()
|
||||
status, session = login(user["username"])
|
||||
assert status == 201
|
||||
return user, session["token"]
|
||||
|
||||
|
||||
class Level4(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
wait_ready()
|
||||
|
||||
def test_wrong_password(self):
|
||||
user = register()
|
||||
status, body = login(user["username"], "definitely-wrong-password")
|
||||
self.assertEqual(status, 401)
|
||||
self.assertEqual(body["error"]["code"], "unauthorized")
|
||||
status, _ = login("no_such_user_" + uuid.uuid4().hex[:8])
|
||||
self.assertEqual(status, 401)
|
||||
|
||||
def test_logout_revokes_session_and_cache(self):
|
||||
_, token = new_session()
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", headers=bearer(token))[0], 200) # прогрев кэша
|
||||
self.assertEqual(call("DELETE", "/api/v1/auth/sessions/current", headers=bearer(token))[0], 204)
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", headers=bearer(token))[0], 401)
|
||||
self.assertEqual(call("DELETE", "/api/v1/auth/sessions/current", headers=bearer(token))[0], 401)
|
||||
|
||||
def test_x_user_id_gives_no_access(self):
|
||||
user = register()
|
||||
status, _ = call("GET", "/api/v1/users/me", headers={"X-User-Id": user["id"]})
|
||||
self.assertEqual(status, 401)
|
||||
|
||||
def test_register_race_same_username(self):
|
||||
username = "race" + uuid.uuid4().hex[:10]
|
||||
results = []
|
||||
|
||||
def worker():
|
||||
status, _ = call("POST", "/api/v1/users",
|
||||
{"username": username, "display_name": "Race", "password": PASSWORD})
|
||||
results.append(status)
|
||||
|
||||
threads = [threading.Thread(target=worker) for _ in range(10)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
self.assertEqual(results.count(201), 1, results)
|
||||
self.assertEqual(results.count(409), 9, results)
|
||||
|
||||
def test_chat_creation_rolls_back(self):
|
||||
user, token = new_session()
|
||||
title = "rollback-" + uuid.uuid4().hex
|
||||
status, _ = call("POST", "/api/v1/chats",
|
||||
{"title": title, "member_ids": [user["id"], str(uuid.uuid4())]},
|
||||
headers=bearer(token))
|
||||
self.assertEqual(status, 400)
|
||||
# Проверяем саму БД: после отката не осталось ни чата, ни участников.
|
||||
count = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
|
||||
"-tAc", f"SELECT count(*) FROM chats WHERE title = '{title}'").strip()
|
||||
self.assertEqual(count, "0")
|
||||
|
||||
def test_valkey_down_falls_back_to_postgres(self):
|
||||
user, token = new_session()
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", headers=bearer(token))[0], 200)
|
||||
compose("stop", "valkey")
|
||||
try:
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", headers=bearer(token))[0], 200)
|
||||
self.assertEqual(login(user["username"])[0], 201)
|
||||
self.assertEqual(call("GET", "/api/v1/users/me")[0], 401)
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", headers=bearer("x" * 43))[0], 401)
|
||||
finally:
|
||||
compose("start", "valkey")
|
||||
|
||||
def test_valkey_flush_keeps_sessions(self):
|
||||
_, token = new_session()
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", headers=bearer(token))[0], 200)
|
||||
compose("exec", "-T", "valkey", "valkey-cli", "FLUSHALL")
|
||||
# кэш пуст, но сессия живёт в PostgreSQL; ответ не зависит от состояния кэша
|
||||
deadline = time.time() + 10
|
||||
refilled = False
|
||||
while time.time() < deadline:
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", headers=bearer(token))[0], 200)
|
||||
keys = compose("exec", "-T", "valkey", "valkey-cli", "keys", "sess:*")
|
||||
if keys.strip():
|
||||
refilled = True
|
||||
break
|
||||
time.sleep(1)
|
||||
self.assertTrue(refilled, "cache should be refilled after a miss")
|
||||
|
||||
def test_postgres_down_returns_bounded_error(self):
|
||||
compose("stop", "postgres")
|
||||
try:
|
||||
status, body = call("GET", "/health/ready")
|
||||
self.assertEqual(status, 503)
|
||||
self.assertEqual(body["error"]["code"], "unavailable")
|
||||
# неизвестный токен нельзя ни подтвердить, ни отвергнуть без БД: 503, не 200
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", headers=bearer("y" * 43))[0], 503)
|
||||
self.assertEqual(call("GET", "/api/v1/users/me")[0], 401) # аноним не доверенный
|
||||
self.assertEqual(call("POST", "/api/v1/users",
|
||||
{"username": "down" + uuid.uuid4().hex[:8], "display_name": "X",
|
||||
"password": PASSWORD})[0], 503)
|
||||
finally:
|
||||
compose("start", "postgres")
|
||||
wait_ready()
|
||||
|
||||
def test_zz_session_expiry(self):
|
||||
compose("up", "-d", "api", env={"SESSION_TTL_SECONDS": "2"})
|
||||
try:
|
||||
wait_ready()
|
||||
_, token = new_session()
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", headers=bearer(token))[0], 200)
|
||||
time.sleep(3.5)
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", headers=bearer(token))[0], 401)
|
||||
finally:
|
||||
compose("up", "-d", "api") # обратно к TTL из .env
|
||||
wait_ready()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Жизненный цикл ЛР 2: данные и сессии переживают перезапуск всего стенда (API, PostgreSQL, Valkey).
|
||||
Нужен запущенный compose-стенд; перезапуск делает scripts/restart.sh (volumes сохраняются)."""
|
||||
import os
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
import test_lab2 as api
|
||||
from test_sigterm import ROOT, run, wait_ready
|
||||
|
||||
|
||||
def compose_logs():
|
||||
return run("docker", "compose", "--project-directory", str(ROOT), "--env-file", str(ROOT / ".env"),
|
||||
"logs", "api", "--no-color").stdout
|
||||
|
||||
|
||||
def main():
|
||||
api.BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
|
||||
wait_ready(api.BASE_URL)
|
||||
|
||||
alice = api.create_user("lifealice")
|
||||
bob = api.create_user("lifebob")
|
||||
outsider = api.create_user("lifeoutsider")
|
||||
chat = api.create_chat(alice, [alice, bob], "Lifecycle test")
|
||||
texts = ["private-lifecycle-" + uuid.uuid4().hex for _ in range(2)]
|
||||
sent = [api.create_message(user, chat, text) for user, text in zip((alice, bob), texts)]
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
page = api.request("GET", path, 200, headers=api.auth(bob))["json"]
|
||||
if [m["id"] for m in page["items"]] != [m["id"] for m in sent]:
|
||||
raise AssertionError("Created messages are missing or reordered")
|
||||
print("PASS two users created and read two messages: HTTP 201, then HTTP 200")
|
||||
|
||||
api.request("GET", path, 404, headers=api.auth(outsider))
|
||||
api.request("POST", path, 404, headers=api.auth(outsider), body={"text": "Forbidden"})
|
||||
print("PASS third user cannot read or write the chat: HTTP 404")
|
||||
|
||||
logs = compose_logs()
|
||||
if any(text in logs for text in texts):
|
||||
raise AssertionError("Message contents leaked into container logs")
|
||||
if "req_id=" not in logs or "with status 201" not in logs:
|
||||
raise AssertionError("Request logs are missing")
|
||||
print("PASS request logs include IDs and statuses, without message contents")
|
||||
|
||||
print("Command: scripts/restart.sh (API + PostgreSQL + Valkey, volumes kept)", flush=True)
|
||||
run(str(ROOT / "scripts" / "restart.sh"), timeout=120)
|
||||
wait_ready(api.BASE_URL, timeout=90)
|
||||
|
||||
# те же токены, те же данные
|
||||
api.request("GET", "/api/v1/users/me", 200, headers=api.auth(alice))
|
||||
after = api.request("GET", path, 200, headers=api.auth(bob))["json"]
|
||||
if after["items"] != page["items"]:
|
||||
raise AssertionError("History changed after restart")
|
||||
api.request("GET", path, 404, headers=api.auth(outsider))
|
||||
print("PASS after restart: same tokens read the same history")
|
||||
|
||||
api.request("DELETE", "/api/v1/auth/sessions/current", 204, headers=api.auth(alice))
|
||||
api.request("GET", path, 401, headers=api.auth(alice))
|
||||
api.request("GET", path, 200, headers=api.auth(bob))
|
||||
print("PASS logout revokes only alice's session; bob's session still works")
|
||||
print("PASS persistent lifecycle: data and sessions survive full restart")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Exception as exc:
|
||||
print(f"FAIL: {type(exc).__name__}: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import concurrent.futures
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
IMAGE = os.environ.get("IMAGE", "mtusi-messenger:lab3")
|
||||
NETWORK = os.environ.get("COMPOSE_NETWORK", "mtusi-lab3_default")
|
||||
PORT = int(os.environ.get("SIGTERM_PORT", "18080"))
|
||||
|
||||
|
||||
def run(*args, check=True, timeout=60):
|
||||
return subprocess.run(
|
||||
args, check=check, text=True, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT, timeout=timeout,
|
||||
)
|
||||
|
||||
def docker_run_args(name, port):
|
||||
# Отдельный контейнер API в сети compose: те же PostgreSQL и Valkey, секрет только для чтения
|
||||
return ["docker", "run", "-d", "--name", name, "--network", NETWORK,
|
||||
"-p", f"127.0.0.1:{port}:8080",
|
||||
"-v", f"{ROOT}/secrets/database_url:/run/secrets/database_url:ro",
|
||||
"-e", "DATABASE_URL_FILE=/run/secrets/database_url",
|
||||
"-e", "CACHE_URL=redis://valkey:6379/0",
|
||||
IMAGE]
|
||||
|
||||
|
||||
def wait_ready(base_url, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(base_url + "/health/ready", timeout=1) as response:
|
||||
if response.status == 200:
|
||||
return
|
||||
except (urllib.error.URLError, ConnectionError, TimeoutError):
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
raise RuntimeError("Test container did not become ready")
|
||||
|
||||
|
||||
def connection_rejected(base_url):
|
||||
try:
|
||||
with urllib.request.urlopen(base_url + "/health/ready", timeout=0.5):
|
||||
return False
|
||||
except urllib.error.HTTPError:
|
||||
return False
|
||||
except (urllib.error.URLError, ConnectionError, TimeoutError):
|
||||
return True
|
||||
|
||||
def not_ready(base_url):
|
||||
# Во время drain /health/ready отвечает 503 (или соединение уже закрыто)
|
||||
try:
|
||||
with urllib.request.urlopen(base_url + "/health/ready", timeout=0.5):
|
||||
return False
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code == 503
|
||||
except (urllib.error.URLError, ConnectionError, TimeoutError):
|
||||
return True
|
||||
|
||||
def test_shutdown(incomplete_request):
|
||||
name = "mtusi-messenger-sigterm-" + uuid.uuid4().hex[:8]
|
||||
base_url = f"http://127.0.0.1:{PORT}"
|
||||
scenario = "incomplete POST" if incomplete_request else "idle"
|
||||
pending = None
|
||||
try:
|
||||
run(*docker_run_args(name, PORT))
|
||||
wait_ready(base_url)
|
||||
|
||||
if incomplete_request:
|
||||
pending = socket.create_connection(("127.0.0.1", PORT), timeout=3)
|
||||
pending.sendall(
|
||||
b"POST /api/v1/users HTTP/1.1\r\n"
|
||||
b"Host: localhost\r\nContent-Type: application/json\r\n"
|
||||
b"Content-Length: 100\r\nExpect: 100-continue\r\n\r\n"
|
||||
)
|
||||
response = b""
|
||||
while b"\r\n\r\n" not in response:
|
||||
part = pending.recv(1024)
|
||||
if not part:
|
||||
raise AssertionError("Connection closed before 100 Continue")
|
||||
response += part
|
||||
if b"100 Continue" not in response:
|
||||
raise AssertionError(f"Expected 100 Continue, received {response!r}")
|
||||
pending.sendall(b"{")
|
||||
|
||||
print(f"Scenario: {scenario}; docker stop --timeout 20 {name}", flush=True)
|
||||
start = time.monotonic()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
|
||||
stopped = executor.submit(run, "docker", "stop", "--timeout", "20", name)
|
||||
deadline = start + 2
|
||||
while not not_ready(base_url):
|
||||
if time.monotonic() >= deadline:
|
||||
raise AssertionError("Readiness still OK after SIGTERM")
|
||||
time.sleep(0.05)
|
||||
rejected_after = time.monotonic() - start
|
||||
stopped.result(timeout=25)
|
||||
elapsed = time.monotonic() - start
|
||||
|
||||
exit_code = int(run("docker", "inspect", name, "--format", "{{.State.ExitCode}}").stdout)
|
||||
if exit_code != 0:
|
||||
raise AssertionError(f"Container exited with code {exit_code}, expected 0")
|
||||
if elapsed > 15:
|
||||
raise AssertionError(f"Shutdown exceeded 15 seconds: {elapsed:.3f}s")
|
||||
if not connection_rejected(base_url):
|
||||
raise AssertionError("API still accepts connections after shutdown")
|
||||
|
||||
logs = run("docker", "logs", name).stdout
|
||||
if "Application shutdown complete" not in logs:
|
||||
raise AssertionError("Application did not complete its shutdown handler")
|
||||
print(f"PASS {scenario}: exit code 0; shutdown {elapsed:.3f}s; "
|
||||
f"new connections rejected after {rejected_after:.3f}s")
|
||||
finally:
|
||||
if pending is not None:
|
||||
pending.close()
|
||||
run("docker", "rm", "-f", name, check=False)
|
||||
|
||||
|
||||
def main():
|
||||
print(f"Image: {IMAGE}")
|
||||
test_shutdown(False)
|
||||
test_shutdown(True)
|
||||
print("PASS SIGTERM: both scenarios completed within 10 seconds")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Exception as exc:
|
||||
print(f"FAIL: {type(exc).__name__}: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,170 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 2: reconciler. python3 student_tests/track2_experiment.py --seed 1000 5000 | tee evidence/track2-experiment.txt
|
||||
Меняет только синтетические данные; кроме них удаляет лишь aged-сирот, найденные базовым запуском."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from test_attachments_level4 import ROOT, SAMPLE, http_call, jcall, new_chat, new_user, psql, upload # noqa: E402
|
||||
|
||||
GRACE = 30
|
||||
FAILS = []
|
||||
|
||||
|
||||
def check(ok, text):
|
||||
print(("PASS " if ok else "FAIL ") + text, flush=True)
|
||||
if not ok:
|
||||
FAILS.append(text)
|
||||
|
||||
|
||||
def api_exec(code, *args, stdin=b""):
|
||||
r = subprocess.run(["docker", "compose", "--env-file", ".env", "exec", "-T", "api", "python", "-c", code, *args],
|
||||
cwd=ROOT, input=stdin, capture_output=True, check=True)
|
||||
return r.stdout.decode().strip()
|
||||
|
||||
|
||||
PUT = "import sys; from src import storage, config; storage.client().put_object(Bucket=config.S3_BUCKET, Key=sys.argv[1], Body=sys.stdin.buffer.read())"
|
||||
DEL = "import sys; from src import storage; storage.delete_object(sys.argv[1])"
|
||||
HEAD = """import sys
|
||||
from botocore.exceptions import ClientError
|
||||
from src import storage, config
|
||||
try:
|
||||
storage.client().head_object(Bucket=config.S3_BUCKET, Key=sys.argv[1]); print(1)
|
||||
except ClientError:
|
||||
print(0)"""
|
||||
SEED = """import sys, uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from src import storage, config
|
||||
c = storage.client()
|
||||
def put(i): c.put_object(Bucket=config.S3_BUCKET, Key="attachments/seed-" + uuid.uuid4().hex, Body=b"seed")
|
||||
with ThreadPoolExecutor(16) as ex: list(ex.map(put, range(int(sys.argv[1]))))"""
|
||||
|
||||
|
||||
def put(key, data=b"orphan"): api_exec(PUT, key, stdin=data)
|
||||
def delete(key): api_exec(DEL, key)
|
||||
def exists(key): return api_exec(HEAD, key) == "1"
|
||||
def new_key(): return "attachments/" + str(uuid.uuid4())
|
||||
|
||||
|
||||
def reconcile(*extra):
|
||||
r = subprocess.run(["docker", "compose", "--env-file", ".env", "run", "--rm", "--no-deps", "-T", "reconciler",
|
||||
"python", "-m", "src.reconciler", "--grace", str(GRACE), *extra],
|
||||
cwd=ROOT, capture_output=True, text=True)
|
||||
line = [l for l in r.stdout.splitlines() if l.startswith("{")][-1]
|
||||
print(" reconciler", " ".join(extra) or "(dry-run)", "->", line, f"[exit {r.returncode}]", flush=True)
|
||||
return json.loads(line), r.returncode
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--seed", type=int, nargs="*", default=[1000])
|
||||
args = ap.parse_args()
|
||||
|
||||
user, auth = new_user()
|
||||
chat = new_chat(auth, [user["id"]])
|
||||
|
||||
def up():
|
||||
st, _, raw = upload(auth, chat, SAMPLE)
|
||||
assert st == 201, st
|
||||
return json.loads(raw)
|
||||
|
||||
def attach(att):
|
||||
st, _ = jcall("POST", f"/api/v1/chats/{chat}/messages", {"text": "", "attachment_ids": [att["id"]]},
|
||||
{**auth, "Idempotency-Key": uuid.uuid4().hex})
|
||||
assert st == 201, st
|
||||
|
||||
def content(att): return http_call("GET", f"/api/v1/attachments/{att['id']}/content", headers=auth)
|
||||
def key_of(att): return psql(f"SELECT object_key FROM attachments WHERE id = '{att['id']}'")
|
||||
def state_of(att): return psql(f"SELECT storage_state FROM attachments WHERE id = '{att['id']}'")
|
||||
|
||||
print("== 0. Базовая очистка (чтобы счётчики ниже были точными)")
|
||||
time.sleep(GRACE + 1)
|
||||
reconcile("--apply")
|
||||
|
||||
print("== 1. Данные: используемые и неиспользуемые вложения")
|
||||
used = up(); attach(used)
|
||||
unlinked = up()
|
||||
lost_used = up(); attach(lost_used)
|
||||
lost_unused = up()
|
||||
fresh_lost = None
|
||||
|
||||
print("== 2. Внедрение ошибок. S3-сторона: 3 объекта без метаданных; БД-сторона: у 2 записей объект удалён")
|
||||
orphans = [new_key() for _ in range(3)]
|
||||
for k in orphans:
|
||||
put(k)
|
||||
lost_used_key, lost_unused_key = key_of(lost_used), key_of(lost_unused)
|
||||
delete(lost_used_key)
|
||||
delete(lost_unused_key)
|
||||
time.sleep(GRACE + 2)
|
||||
fresh_orphan = new_key()
|
||||
put(fresh_orphan)
|
||||
fresh_lost = up()
|
||||
delete(key_of(fresh_lost))
|
||||
|
||||
print("== 3. DRY-RUN: обнаруживает, но ничего не меняет")
|
||||
r, _ = reconcile()
|
||||
check(r["dry_run"] and r["orphans_found"] == 3 and r["missing_found"] == 2, "dry-run нашёл 3 сирот и 2 потерянных объекта")
|
||||
check(r["orphans_fresh_skipped"] == 1 and r["missing_fresh_skipped"] == 1, "свежие сирота и запись (моложе grace) пропущены")
|
||||
check(r["orphans_deleted"] == 0 and r["missing_marked"] == 0, "dry-run ничего не изменил в счётчиках")
|
||||
check(all(exists(k) for k in orphans), "после dry-run все сироты ещё в S3")
|
||||
check(state_of(lost_used) == "ok" and state_of(lost_unused) == "ok", "после dry-run состояния записей не изменены")
|
||||
|
||||
print("== 4. APPLY и сразу повторный APPLY (идемпотентность)")
|
||||
r, _ = reconcile("--apply")
|
||||
r2, _ = reconcile("--apply")
|
||||
check(r["orphans_deleted"] == 3 and r["missing_marked"] == 2, "удалены 3 сироты, помечены 2 потерянных объекта")
|
||||
check(r2["orphans_found"] == 0 and r2["missing_found"] == 0 and r2["orphans_deleted"] == 0 and r2["missing_marked"] == 0,
|
||||
"повторный apply ничего не находит и не меняет")
|
||||
check(exists(fresh_orphan), "свежая сирота НЕ удалена (grace period)")
|
||||
check(state_of(fresh_lost) == "ok", "свежая запись без объекта НЕ помечена (grace period)")
|
||||
check(not any(exists(k) for k in orphans), "старые сироты удалены из S3")
|
||||
for name, att in (("используемое", used), ("неиспользуемое, но с метаданными", unlinked)):
|
||||
st, _, raw = content(att)
|
||||
check(st == 200 and hashlib.sha256(raw).hexdigest() == att["sha256"], f"{name} вложение старше grace цело и скачивается")
|
||||
check(content(lost_used)[0] == 409 and content(lost_unused)[0] == 409, "потерянные вложения: скачивание 409, а не 500")
|
||||
check(http_call("GET", f"/api/v1/attachments/{lost_used['id']}", headers=auth)[0] == 200, "метаданные потерянного вложения остаются (запись не удалена)")
|
||||
st, _ = jcall("POST", f"/api/v1/chats/{chat}/messages", {"text": "", "attachment_ids": [lost_unused["id"]]},
|
||||
{**auth, "Idempotency-Key": uuid.uuid4().hex})
|
||||
check(st == 409, "потерянное вложение нельзя прикрепить к новому сообщению (409)")
|
||||
|
||||
print("== 6. Восстановление: объект вернули на то же место")
|
||||
put(lost_used_key, SAMPLE)
|
||||
r, _ = reconcile("--apply")
|
||||
check(r["restored"] == 1 and state_of(lost_used) == "ok", "запись снова ok после проверки размера и SHA-256")
|
||||
st, _, raw = content(lost_used)
|
||||
check(st == 200 and hashlib.sha256(raw).hexdigest() == lost_used["sha256"], "восстановленное вложение скачивается")
|
||||
|
||||
print("== 7. Прошёл grace: бывшие свежие объекты теперь обрабатываются")
|
||||
time.sleep(GRACE + 2)
|
||||
r, _ = reconcile("--apply")
|
||||
check(r["orphans_deleted"] == 1 and r["missing_marked"] == 1, "теперь удалена вторая сирота и помечена вторая потеря")
|
||||
|
||||
print("== 8. Стоимость обхода и предохранитель")
|
||||
for n in args.seed:
|
||||
print(f"-- seed {n} объектов-сирот")
|
||||
api_exec(SEED, str(n))
|
||||
time.sleep(GRACE + 2)
|
||||
t0 = time.time()
|
||||
r, _ = reconcile()
|
||||
print(f" dry-run N={n}: reconciler elapsed={r['elapsed_s']}s s3_list={r['s3_list_s']}s pages={r['s3_list_pages']} "
|
||||
f"db_rows={r['db_rows']} peak_rss={r['peak_rss_mib']}MiB (с запуском контейнера {time.time() - t0:.1f}s)")
|
||||
check(r["orphans_found"] >= n, f"dry-run видит {n} сирот")
|
||||
if n > 1000:
|
||||
r, code = reconcile("--apply")
|
||||
check(code == 3 and r.get("error") == "too_many_actions" and r["orphans_deleted"] == 0,
|
||||
"предохранитель: массовое удаление выше --max-actions отклонено, ничего не удалено")
|
||||
r, _ = reconcile("--apply", "--max-actions", str(n + 100))
|
||||
check(r["orphans_deleted"] >= n, f"очистка {n} сирот выполнена")
|
||||
|
||||
print("\nИТОГ:", "FAIL" if FAILS else "PASS")
|
||||
sys.exit(1 if FAILS else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""N одновременных медленных загрузок ~10 МиБ через LB; пик памяти api-контейнеров по cgroup.
|
||||
python3 student_tests/upload_memory.py --concurrency 10 --output evidence/upload-memory-10.json"""
|
||||
import argparse
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from test_attachments_level4 import SIG, URL, chunk, compose, new_chat, new_user # noqa: E402
|
||||
|
||||
CG2 = "cat /sys/fs/cgroup/memory.current; grep -E '^(anon|file) ' /sys/fs/cgroup/memory.stat"
|
||||
CG1 = "cat /sys/fs/cgroup/memory/memory.usage_in_bytes; grep -E '^(rss|cache) ' /sys/fs/cgroup/memory/memory.stat"
|
||||
MIB = 1024 * 1024
|
||||
|
||||
|
||||
def build_png(target, idat_chunk):
|
||||
w = 1000
|
||||
h = target // (w * 3 + 1)
|
||||
comp = zlib.compress(b"".join(b"\x00" + os.urandom(w * 3) for _ in range(h)), 0)
|
||||
step = idat_chunk or len(comp)
|
||||
idat = b"".join(chunk(b"IDAT", comp[i:i + step]) for i in range(0, len(comp), step))
|
||||
return SIG + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + idat + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def read_mem(cid):
|
||||
for cmd in (CG2, CG1):
|
||||
r = subprocess.run(["docker", "exec", cid, "sh", "-c", cmd], capture_output=True, text=True)
|
||||
if r.returncode == 0 and r.stdout.strip():
|
||||
lines = r.stdout.strip().split("\n")
|
||||
d = {p[0]: int(p[1]) for p in (l.split() for l in lines[1:]) if len(p) == 2}
|
||||
return int(lines[0]), d.get("anon", d.get("rss", 0)), d.get("file", d.get("cache", 0))
|
||||
raise SystemExit("не удалось прочитать cgroup-память контейнера")
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--concurrency", type=int, default=10)
|
||||
ap.add_argument("--mode", choices=["normal", "single-idat"], default="normal",
|
||||
help="single-idat: весь PNG одним IDAT-чанком (худший случай для проверки структуры)")
|
||||
ap.add_argument("--chunk-delay-ms", type=float, default=20, help="пауза между 64 КиБ: медленный клиент")
|
||||
ap.add_argument("--output", required=True)
|
||||
args = ap.parse_args()
|
||||
|
||||
body = build_png(10 * MIB - 200_000, 0 if args.mode == "single-idat" else 32768)
|
||||
assert len(body) <= 10 * MIB
|
||||
user, auth = new_user()
|
||||
chat = new_chat(auth, [user["id"]])
|
||||
cids = compose("ps", "-q", "api").split()
|
||||
limits = {c: int(subprocess.run(["docker", "inspect", "-f", "{{.HostConfig.Memory}}", c],
|
||||
capture_output=True, text=True).stdout.strip() or 0) for c in cids}
|
||||
base = {c: read_mem(c) for c in cids}
|
||||
peak = {c: list(base[c]) for c in cids}
|
||||
stop = threading.Event()
|
||||
|
||||
def monitor(cid):
|
||||
while not stop.is_set():
|
||||
cur = read_mem(cid)
|
||||
peak[cid] = [max(a, b) for a, b in zip(peak[cid], cur)]
|
||||
|
||||
mons = [threading.Thread(target=monitor, args=(c,)) for c in cids]
|
||||
statuses = [None] * args.concurrency
|
||||
barrier = threading.Barrier(args.concurrency)
|
||||
|
||||
def one(i):
|
||||
barrier.wait()
|
||||
c = http.client.HTTPConnection(URL.hostname, URL.port, timeout=180)
|
||||
c.putrequest("POST", f"/api/v1/chats/{chat}/attachments?filename=m{i}.png")
|
||||
for k, v in {**auth, "Content-Type": "image/png", "Content-Length": str(len(body))}.items():
|
||||
c.putheader(k, v)
|
||||
c.endheaders()
|
||||
for off in range(0, len(body), 65536):
|
||||
c.send(body[off:off + 65536])
|
||||
time.sleep(args.chunk_delay_ms / 1000)
|
||||
r = c.getresponse()
|
||||
r.read()
|
||||
statuses[i] = r.status
|
||||
|
||||
[m.start() for m in mons]
|
||||
ts = [threading.Thread(target=one, args=(i,)) for i in range(args.concurrency)]
|
||||
t0 = time.time()
|
||||
[t.start() for t in ts]
|
||||
[t.join() for t in ts]
|
||||
wall = time.time() - t0
|
||||
stop.set()
|
||||
[m.join() for m in mons]
|
||||
|
||||
result = {"mode": args.mode, "concurrency": args.concurrency, "file_mib": round(len(body) / MIB, 2),
|
||||
"payload_total_mib": round(args.concurrency * len(body) / MIB, 1), "wall_s": round(wall, 1),
|
||||
"statuses": sorted(set(s for s in statuses)), "ok": statuses.count(201), "containers": {}}
|
||||
for c in cids:
|
||||
result["containers"][c[:12]] = {
|
||||
"limit_mib": round(limits[c] / MIB), "baseline_anon_mib": round(base[c][1] / MIB, 1),
|
||||
"peak_anon_mib": round(peak[c][1] / MIB, 1), "anon_growth_mib": round((peak[c][1] - base[c][1]) / MIB, 1),
|
||||
"peak_current_mib_incl_page_cache": round(peak[c][0] / MIB, 1)}
|
||||
Path(args.output).write_text(json.dumps(result, indent=2, ensure_ascii=False))
|
||||
print(json.dumps(result, indent=2, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user