Files
mtusi2026lab4/student-tests/test_attachments.py
T
alenchha 078a8341b5 ЛР 4: вложения в S3 (MinIO), reconciler БД<->S3, отчёт и evidence
Перенесён минимум lab3. Добавлены загрузка/скачивание PNG/JPEG через API
с потоковой проверкой целостности, метаданные в PostgreSQL и байты в
приватном bucket, отдельный S3-пользователь с ограниченными правами,
идемпотентный bootstrap bucket, компенсация и reconciler (трек 2),
тесты отказов, эксперименты по памяти и согласованности.
2026-11-02 16:59:17 +03:00

116 lines
6.0 KiB
Python

#!/usr/bin/env python3
"""Negative and boundary scenarios for attachments (grade 4). Needs the stack from README on BASE_URL."""
import hashlib
import os
import socket
import struct
import sys
import uuid
import zlib
from pathlib import Path
from urllib.parse import quote, urlparse
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, check, run # noqa: E402
SAMPLE = (ROOT / "tests/fixtures/sample.png").read_bytes()
def chunk(kind, body):
return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body) & 0xFFFFFFFF)
def header_only_png(width, height):
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IEND", b"")
def upload(c, actor, chat, body, ctype, expected, filename="a.png"):
path = "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], quote(filename, safe=""))
return c.call("POST", path, expected, actor=actor, raw=body, headers={"Content-Type": ctype},
schema="Attachment" if expected == 201 else None)
def main():
c = Client()
alice, bob, eve, chat = c.bootstrap()
other = c.call("POST", "/api/v1/chats", 201, actor=alice,
body={"title": "Второй", "member_ids": [alice["id"]]}, schema="Chat")["json"]
eve_chat = c.call("POST", "/api/v1/chats", 201, actor=eve,
body={"title": "Чат Евы", "member_ids": [eve["id"]]}, schema="Chat")["json"]
ok = upload(c, alice, chat, SAMPLE, "image/png", 201)["json"]
check(ok["status"] == "ready" and ok["variants"] == [] and ok["error_code"] is None, "ready upload shape")
got = c.call("GET", "/api/v1/attachments/" + ok["id"] + "/content", actor=bob)
check(hashlib.sha256(got["bytes"]).hexdigest() == ok["sha256"], "bob downloads identical bytes")
check(int(got["headers"]["Content-Length"]) == len(SAMPLE), "download Content-Length")
c.call("GET", "/api/v1/attachments/" + ok["id"] + "/content?variant=thumbnail", 404, actor=bob)
upload(c, None, chat, SAMPLE, "image/png", 401)
upload(c, eve, chat, SAMPLE, "image/png", 404)
print("ok auth and membership on upload")
big = header_only_png(10, 10) + b"\0" * (10 * 1024 * 1024)
upload(c, alice, chat, big, "image/png", 413)
print("ok file over 10 MiB -> 413")
upload(c, alice, chat, header_only_png(8000, 6000), "image/png", 413)
print("ok 48 Mpx image -> 413 before decoding")
upload(c, alice, chat, SAMPLE[: len(SAMPLE) // 2], "image/png", 415)
upload(c, alice, chat, SAMPLE[:40] + b"garbage" * 50, "image/png", 415)
print("ok corrupted image -> 415")
upload(c, alice, chat, SAMPLE, "image/jpeg", 415)
upload(c, alice, chat, b"\xff\xd8\xff\xe0" + b"\0" * 200, "image/png", 415)
upload(c, alice, chat, b"MZ not an image at all", "image/png", 415)
upload(c, alice, chat, b"<svg xmlns='http://www.w3.org/2000/svg'/>", "image/png", 415)
upload(c, alice, chat, SAMPLE, "text/plain", 415)
upload(c, alice, chat, SAMPLE, "image/gif", 415)
print("ok MIME spoofing and unsupported types -> 415")
upload(c, alice, chat, b"", "image/png", 400)
for bad in ("../x.png", "a/b.png", "a\\b.png", "a\x00b.png", "a\nb.png", "", "x" * 256):
upload(c, alice, chat, SAMPLE, "image/png", 400, filename=bad)
print("ok dangerous filenames -> 400")
unicode_name = upload(c, alice, chat, SAMPLE, "image/png", 201, filename="фото 🙂.png")["json"]
check(unicode_name["filename"] == "фото 🙂.png", "display filename preserved")
own = upload(c, alice, other, SAMPLE, "image/png", 201)["json"]
foreign = upload(c, eve, eve_chat, SAMPLE, "image/png", 201)["json"]
msg = lambda actor, ch, ids, expected: c.call(
"POST", "/api/v1/chats/%s/messages" % ch["id"], expected, actor=actor,
body={"text": "", "attachment_ids": ids}, headers={"Idempotency-Key": uuid.uuid4().hex}, schema="Message" if expected == 201 else None)
msg(alice, chat, [str(uuid.uuid4())], 404)
msg(alice, chat, [foreign["id"]], 404)
msg(alice, chat, [own["id"]], 404)
msg(alice, chat, [ok["id"], ok["id"]], 400)
msg(alice, chat, ["not-a-uuid"], 400)
msg(alice, chat, [str(uuid.uuid4()) for _ in range(11)], 400)
msg(eve, chat, [ok["id"]], 404)
c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 400, actor=alice, body={"text": " "},
headers={"Idempotency-Key": uuid.uuid4().hex})
print("ok unknown / foreign / other-chat attachment ids rejected, no 500")
sent = msg(bob, chat, [ok["id"]], 201)["json"]
check(sent["attachment_ids"] == [ok["id"]] and sent["text"] == "", "attachment-only message")
history = c.call("GET", "/api/v1/chats/%s/messages" % chat["id"], actor=alice, schema="MessagePage")["json"]
check(any(m["attachment_ids"] == [ok["id"]] for m in history["items"]), "history keeps attachment_ids")
for suffix in ("", "/content"):
c.call("GET", "/api/v1/attachments/" + foreign["id"] + suffix, 404, actor=alice)
c.call("GET", "/api/v1/attachments/" + str(uuid.uuid4()) + suffix, 404, actor=alice)
c.call("GET", "/api/v1/attachments/not-a-uuid" + suffix, 400, actor=alice)
c.call("GET", "/api/v1/attachments/" + ok["id"] + suffix, 401)
parsed = urlparse(c.base)
sock = socket.create_connection((parsed.hostname, parsed.port or 80), timeout=10)
request = ("POST /api/v1/chats/%s/attachments?filename=cut.png HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer %s\r\n"
"Content-Type: image/png\r\nContent-Length: %d\r\n\r\n" % (chat["id"], alice["token"], len(SAMPLE)))
sock.sendall(request.encode() + SAMPLE[: len(SAMPLE) // 2])
sock.close()
print("ok client abort mid-upload sent; server must stay healthy")
c.call("GET", "/health/ready", schema="Health")
after = upload(c, alice, chat, SAMPLE, "image/png", 201)["json"]
check(after["sha256"] == hashlib.sha256(SAMPLE).hexdigest(), "upload works after aborted one")
print("PASS: attachment negative scenarios")
if __name__ == "__main__":
run(main)