import base64, hashlib, json, os, random, struct, sys, urllib.error, urllib.request, uuid, zlib BASE = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080" PWD = "correct-horse-battery-staple" LIMIT = 10 * 1024 * 1024 def call(method, path, body=None, headers=None, token=None, basic=None): h = dict(headers or {}) if token: h["Authorization"] = "Bearer " + token if basic: h["Authorization"] = "Basic " + base64.b64encode(basic.encode()).decode() req = urllib.request.Request(BASE + path, data=body, method=method, headers=h) try: with urllib.request.urlopen(req, timeout=30) as r: return r.status, r.headers, r.read() except urllib.error.HTTPError as e: return e.code, e.headers, e.read() def jcall(method, path, obj, token=None, key=None): h = {"Content-Type": "application/json"} if key: h["Idempotency-Key"] = key st, _, raw = call(method, path, json.dumps(obj).encode(), h, token) return st, (json.loads(raw) if raw else None) def chunk(t, d): c = struct.pack(">I", len(d)) + t + d return c + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF) def png(width, height, idat=None): raw = idat if idat is not None else b"".join(b"\x00" + b"\x10\x80\xf0" * width for _ in range(height)) return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw) if idat is None else raw) + chunk(b"IEND", b"")) def noise_png(target_bytes): w = 1000 rows = max(1, target_bytes // (3 * w + 1)) raw = b"".join(b"\x00" + os.urandom(3 * w) for _ in range(rows)) return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, rows, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw, 0)) + chunk(b"IEND", b"")) ok = True def check(name, got, want): global ok good = got in want if isinstance(want, set) else got == want ok &= good print("PASS" if good else "FAIL", name, "->", got) def register(prefix): name = f"{prefix}_{uuid.uuid4().hex[:8]}" _, u = jcall("POST", "/api/v1/users", {"username": name, "display_name": prefix, "password": PWD}) _, _, raw = call("POST", "/api/v1/auth/sessions", basic=f"{name}:{PWD}") return u, json.loads(raw)["token"] alice, ta = register("alice") bob, tb = register("bob") carol, tc = register("carol") _, chat1 = jcall("POST", "/api/v1/chats", {"title": "c1", "member_ids": [alice["id"], bob["id"]]}, ta) _, chat2 = jcall("POST", "/api/v1/chats", {"title": "c2", "member_ids": [alice["id"]]}, ta) up = lambda chat, data, ct="image/png", fn="a.png", tok=None: call( "POST", f"/api/v1/chats/{chat}/attachments?filename={fn}", data, {"Content-Type": ct}, tok or ta) msg = lambda chat, obj, tok=None, key=None: jcall( "POST", f"/api/v1/chats/{chat}/messages", obj, tok or ta, key or uuid.uuid4().hex) good_png = png(8, 8) st, _, raw = up(chat1["id"], good_png) check("валидный PNG", st, 201) att = json.loads(raw) check("sha256 в ответе", att["sha256"], hashlib.sha256(good_png).hexdigest()) check("status/variants/error_code", (att["status"], att["variants"], att["error_code"]), ("ready", [], None)) st, hdr, data = call("GET", f"/api/v1/attachments/{att['id']}/content", token=tb) check("скачивание участником: статус", st, 200) check("скачивание: байты совпадают", hashlib.sha256(data).hexdigest(), att["sha256"]) check("скачивание: Content-Type", hdr.get("Content-Type"), "image/png") check("метаданные: посторонний", call("GET", f"/api/v1/attachments/{att['id']}", token=tc)[0], 404) check("байты: посторонний", call("GET", f"/api/v1/attachments/{att['id']}/content", token=tc)[0], 404) check("без токена", call("GET", f"/api/v1/attachments/{att['id']}/content")[0], 401) check("неизвестный id", call("GET", f"/api/v1/attachments/{uuid.uuid4()}", token=ta)[0], 404) check("id не UUID", call("GET", "/api/v1/attachments/not-a-uuid", token=ta)[0], 400) check("variant=thumbnail", call("GET", f"/api/v1/attachments/{att['id']}/content?variant=thumbnail", token=ta)[0], {400, 404}) check("загрузка в чужой чат", up(chat1["id"], good_png, tok=tc)[0], 404) check("слишком большой (Content-Length)", up(chat1["id"], good_png[:8] + b"\0" * (LIMIT + 1))[0], 413) check("слишком много пикселей (8000x8000)", up(chat1["id"], png(8000, 8000, idat=b"\x00"))[0], 413) check("повреждённый PNG", up(chat1["id"], good_png[:-20])[0], 415) check("PNG под видом JPEG", up(chat1["id"], good_png, ct="image/jpeg")[0], 415) check("текст под видом PNG", up(chat1["id"], b"hello, not an image")[0], 415) check("пустое тело", up(chat1["id"], b"")[0], 415) check("image/gif", up(chat1["id"], b"GIF89a....", ct="image/gif")[0], 415) for label, fn in [("слэш", "a%2Fb.png"), ("обратный слэш", "a%5Cb.png"), ("NUL", "a%00b.png"), ("управляющий символ", "a%0Ab.png"), ("256 символов", "a" * 256), ("пустое", "")]: check(f"filename: {label}", up(chat1["id"], good_png, fn=fn)[0], 400) st, _, _ = call("POST", f"/api/v1/chats/{chat1['id']}/attachments", good_png, {"Content-Type": "image/png"}, ta) check("filename отсутствует", st, 400) check("валидный большой файл (~9 МиБ)", up(chat1["id"], noise_png(9 * 1024 * 1024))[0], 201) # ---- сообщения с вложениями st, m1 = msg(chat1["id"], {"text": "", "attachment_ids": [att["id"]]}, key="k-" + uuid.uuid4().hex) check("пустой текст с вложением", st, 201) check("в ответе attachment_ids", m1["attachment_ids"], [att["id"]]) check("пустой текст без вложений", msg(chat1["id"], {"text": ""})[0], 400) check("вложение из другого чата (я участник обоих)", msg(chat2["id"], {"text": "x", "attachment_ids": [att["id"]]})[0], 404) check("неизвестное вложение", msg(chat1["id"], {"text": "x", "attachment_ids": [str(uuid.uuid4())]})[0], 404) check("attachment_ids не UUID", msg(chat1["id"], {"text": "x", "attachment_ids": ["zzz"]})[0], 400) check("дубликаты в attachment_ids", msg(chat1["id"], {"text": "x", "attachment_ids": [att["id"], att["id"]]})[0], 400) check("11 вложений", msg(chat1["id"], {"text": "x", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]})[0], 400) check("посторонний шлёт чужое вложение", msg(chat1["id"], {"text": "x", "attachment_ids": [att["id"]]}, tok=tc)[0], 404) _, page = jcall("GET", f"/api/v1/chats/{chat1['id']}/messages", None, ta) st, _, raw = call("GET", f"/api/v1/chats/{chat1['id']}/messages", token=bob and tb) items = json.loads(raw)["items"] check("история содержит attachment_ids", any(i["attachment_ids"] == [att["id"]] for i in items), True) # ---- идемпотентность с вложениями k = "idem-" + uuid.uuid4().hex s1, a = msg(chat1["id"], {"text": "same", "attachment_ids": []}, key=k) s2, b = msg(chat1["id"], {"text": "same"}, key=k) check("attachment_ids отсутствует == []", (s1, s2, a["id"] == b["id"]), (201, 201, True)) k2 = "idem-" + uuid.uuid4().hex msg(chat1["id"], {"text": "t", "attachment_ids": [att["id"]]}, key=k2) check("тот же ключ, другой список вложений", msg(chat1["id"], {"text": "t"}, key=k2)[0], 409) sys.exit(0 if ok else 1)