Files
mtusi2026lab4/student_tests/test_attachments_level4.py

281 lines
13 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Тесты вложений, уровень 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()