#!/usr/bin/env python3 """Вложения (lab4, адаптировано к lab5: upload → 202, готовность — по статусу): корректные файлы, лимиты, повреждения, подмена MIME, filename, ACL, чужие ID. Каждая пользовательская ошибка обязана дать 4xx из контракта, а не 500 (Client проверяет код и формат Error). Только синтетические данные; стенд и volumes не трогаются. """ import hashlib import os import socket import time import uuid import zlib from pathlib import Path from urllib.parse import quote, urlsplit from common import BASE_URL, Client, Suite, check, login, make_png, new_user c = Client(BASE_URL, timeout=30) s = Suite("attachments (" + BASE_URL + ")") JPEG = (Path(__file__).parent / "fixtures" / "photo.jpg").read_bytes() MAX = int(os.environ.get("MAX_UPLOAD_BYTES", str(10 * 1024 * 1024))) alice = new_user(c, "aa"); login(c, alice) bob = new_user(c, "ab"); login(c, bob) eve = new_user(c, "ae"); login(c, eve) chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat", body={"title": "files", "member_ids": [alice["id"], bob["id"]]})["json"] other = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat", body={"title": "other", "member_ids": [alice["id"]]})["json"] UP = "/api/v1/chats/" + chat["id"] + "/attachments" def chunk(t, d): return len(d).to_bytes(4, "big") + t + d + zlib.crc32(t + d).to_bytes(4, "big") def png_with(width, height, idat_raw, color_type=2, level=9): ihdr = width.to_bytes(4, "big") + height.to_bytes(4, "big") + bytes([8, color_type, 0, 0, 0]) return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(idat_raw, level)) + chunk(b"IEND", b"")) def big_png(target): """Несжимаемый RGB PNG размером чуть меньше target байт.""" side = int(((target - 4096) / 3) ** 0.5) rows = b"".join(b"\x00" + os.urandom(side * 3) for _ in range(side)) return png_with(side, side, rows, level=1) def post(data, ctype="image/png", filename="f.png", expected=202, actor=None, chat_id=None): path = "/api/v1/chats/" + (chat_id or chat["id"]) + "/attachments?filename=" + quote(filename, safe="") return c.call("POST", path, expected, actor=actor or alice, raw=data, headers={"Content-Type": ctype}, schema="Attachment" if expected == 202 else None) def ready(att): """lab5: content доступен только после ready (до этого — 409).""" return c.wait_ready(alice, att) def raw_http(head: bytes, body: bytes = b"", wait=5.0): """Сырые байты через сокет: запрос, который urllib не умеет отправить (обрыв, ложный Content-Length).""" u = urlsplit(BASE_URL) sock = socket.create_connection((u.hostname, u.port or 80), timeout=wait) try: sock.sendall(head + body) t = time.monotonic() data = b"" while b"\r\n" not in data: part = sock.recv(4096) if not part: break data += part return data.split(b"\r\n", 1)[0].decode(errors="replace"), time.monotonic() - t finally: sock.close() @s.case("valid PNG and JPEG: 202 queued → ready, byte-exact download by other member") def _(): png = make_png(40, 30) for data, ctype, name in ((png, "image/png", "фото отпуска.png"), (JPEG, "image/jpeg", "photo.jpg")): att = post(data, ctype, name)["json"] check(att["status"] in ("queued", "processing", "ready") and att["size_bytes"] == len(data), "bad metadata") att = ready(att) check(att["sha256"] == hashlib.sha256(data).hexdigest() and att["filename"] == name, "sha/filename mismatch") r = c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=bob) check(r["bytes"] == data, "download differs") h = r["headers"] check(h.get_content_type() == ctype and h.get("X-Content-Type-Options") == "nosniff", "unsafe headers") check(int(h["Content-Length"]) == len(data), "Content-Length") check("attachment" in h.get("Content-Disposition", "") or "inline" in h.get("Content-Disposition", ""), "Content-Disposition missing") msg = c.message(alice, chat, "", attachments=[att["id"]])["json"] # пустой текст + вложение check(msg["attachment_ids"] == [att["id"]], "message lost attachment") @s.case("exactly-near limit (~10 MiB) accepted, Content-Length > limit -> 413") def _(): data = big_png(MAX) check(len(data) <= MAX, "fixture too big") att = post(data, filename="big.png")["json"] check(att["size_bytes"] == len(data), "size") over = data + b"\x00" * (MAX + 1 - len(data)) post(over, filename="over.png", expected=413) return "%.2f MiB accepted" % (len(data) / 2**20) @s.case("oversize rejected BEFORE body is read (early 413, socket)") def _(): u = urlsplit(BASE_URL) head = ("POST %s?filename=x.png HTTP/1.1\r\nHost: %s\r\nAuthorization: Bearer %s\r\nContent-Type: image/png\r\n" "Content-Length: %d\r\nConnection: close\r\n\r\n" % (UP, u.netloc, alice["token"], 50 * 2**20)).encode() status, took = raw_http(head, b"\x89PNG\r\n\x1a\n") check(" 413 " in status + " ", "expected 413, got " + status) check(took < 3, "413 took %.2fs (body awaited?)" % took) return "%s in %.3fs, 50 MiB never sent" % (status, took) @s.case("pixel limit: 8000x6000 header -> 413 without decoding") def _(): # 48 млн пикселей > 40 млн: отклоняется по IHDR/SOF, IDAT даже не нужен корректный ihdr = (8000).to_bytes(4, "big") + (6000).to_bytes(4, "big") + bytes([8, 2, 0, 0, 0]) bomb = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(b"\x00" * 1000)) + chunk(b"IEND", b"") t = time.monotonic() post(bomb, expected=413) jpeg = bytearray(JPEG) i = jpeg.find(b"\xff\xc0") jpeg[i + 5:i + 9] = (7000).to_bytes(2, "big") + (7000).to_bytes(2, "big") # SOF: 49 Мп post(bytes(jpeg), "image/jpeg", "big.jpg", expected=413) return "%.3fs" % (time.monotonic() - t) @s.case("decompression bomb: IDAT inflates beyond declared size -> 415") def _(): bomb = png_with(100, 100, b"\x00" * (64 * 2**20)) # 64 МиБ нулей сжимаются в ~64 КиБ check(len(bomb) < 200_000, "bomb not small") t = time.monotonic() post(bomb, expected=415) return "%d-byte file claiming 64 MiB raw, rejected in %.3fs" % (len(bomb), time.monotonic() - t) @s.case("corrupted images -> 415 (truncated, bad CRC, no EOI, garbage, empty)") def _(): png = make_png(20, 20) bad_crc = bytearray(png); bad_crc[30] ^= 0x01 cases = [(png[:-12], "image/png"), (bytes(bad_crc), "image/png"), (JPEG[:-2], "image/jpeg"), (JPEG[:len(JPEG) // 2], "image/jpeg"), (os.urandom(4096), "image/png"), (b"\x89PNG\r\n\x1a\n" + os.urandom(500), "image/png"), (b"\xff\xd8\xff" + os.urandom(500), "image/jpeg"), (png + b"trailing-garbage", "image/png"), (b"", "image/png")] for data, ctype in cases: post(data, ctype, expected=415) return "%d variants" % len(cases) @s.case("MIME spoofing by Content-Type/filename -> 415") def _(): gif = b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;" cases = [(make_png(), "image/jpeg", "a.jpg"), (JPEG, "image/png", "a.png"), (b"", "image/png", "a.png"), (gif, "image/png", "a.png"), (gif, "image/gif", "a.gif"), (make_png(), "application/octet-stream", "a.png"), (make_png(), "text/html", "a.html"), (b"", "image/svg+xml", "a.svg")] for data, ctype, name in cases: post(data, ctype, name, expected=415) @s.case("dangerous/invalid filenames -> 400; filename never becomes a path") def _(): png = make_png() for name in ("", "../../etc/passwd", "a/b.png", "a\\b.png", "x\x00.png", "line\nbreak.png", "\t.png", ".", "..", "x" * 256, "‮evil.png"): post(png, filename=name, expected=400) c.call("POST", UP, 400, actor=alice, raw=png, headers={"Content-Type": "image/png"}) # filename отсутствует ok = post(png, filename="y" * 251 + ".png")["json"] check(len(ok["filename"]) == 255, "255-char name must be accepted") @s.case("missing/invalid Content-Length -> 400 (chunked upload is not accepted)") def _(): u = urlsplit(BASE_URL) head = ("POST %s?filename=x.png HTTP/1.1\r\nHost: %s\r\nAuthorization: Bearer %s\r\nContent-Type: image/png\r\n" "Transfer-Encoding: chunked\r\nConnection: close\r\n\r\n" % (UP, u.netloc, alice["token"])).encode() png = make_png() status, _ = raw_http(head, b"%x\r\n" % len(png) + png + b"\r\n0\r\n\r\n") check(" 400 " in status + " " or " 411 " in status + " ", "chunked upload: " + status) return status @s.case("ACL: outsider gets 404 for upload/metadata/content; anonymous 401") def _(): att = post(make_png())["json"] t = time.monotonic() post(big_png(MAX), actor=eve, expected=404) # посторонний — 404 до чтения 10 МиБ took = time.monotonic() - t for path in ("", "/content", "/content?variant=original"): c.call("GET", "/api/v1/attachments/" + att["id"] + path, 404, actor=eve) c.call("GET", "/api/v1/attachments/" + att["id"] + path, 401) c.call("GET", "/api/v1/attachments/" + str(uuid.uuid4()), 404, actor=alice) c.call("GET", "/api/v1/attachments/not-a-uuid", [400, 404], actor=alice) c.call("POST", UP + "?filename=a.png", 401, raw=make_png(), headers={"Content-Type": "image/png"}) c.call("POST", "/api/v1/chats/" + str(uuid.uuid4()) + "/attachments?filename=a.png", 404, actor=alice, raw=make_png(), headers={"Content-Type": "image/png"}) return "outsider 10 MiB upload rejected in %.2fs" % took @s.case("variants (lab5): original/thumbnail/crop/optimized OK after ready, unknown -> 400") def _(): att = ready(post(make_png())["json"]) for v in ("original", "thumbnail", "crop", "optimized"): c.call("GET", "/api/v1/attachments/" + att["id"] + "/content?variant=" + v, actor=bob) c.call("GET", "/api/v1/attachments/" + att["id"] + "/content?variant=../../x", 400, actor=bob) @s.case("message: foreign/unknown attachment_id -> 404, file of other chat -> 404, limits -> 400") def _(): mine = post(make_png())["json"] foreign = post(make_png(), chat_id=other["id"])["json"] # тот же владелец, ДРУГОЙ чат path = "/api/v1/chats/" + chat["id"] + "/messages" def send(body, expected, actor=alice): return c.call("POST", path, expected, actor=actor, body=body, headers={"Idempotency-Key": uuid.uuid4().hex}) send({"text": "x", "attachment_ids": [foreign["id"]]}, 404) send({"text": "x", "attachment_ids": [mine["id"], foreign["id"]]}, 404) send({"text": "x", "attachment_ids": [str(uuid.uuid4())]}, 404) send({"text": "x", "attachment_ids": ["nope"]}, 400) send({"text": "x", "attachment_ids": [mine["id"], mine["id"]]}, 400) send({"text": "x", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]}, 400) send({"text": "", "attachment_ids": []}, 400) send({"text": ""}, 400) send({"text": "x" * 4001, "attachment_ids": [mine["id"]]}, 400) # постороннему чат не виден вовсе c.call("POST", path, 404, actor=eve, body={"text": "x", "attachment_ids": [mine["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex}) hist = c.call("GET", path + "?limit=50", actor=bob, schema="MessagePage")["json"] check(all(foreign["id"] not in m.get("attachment_ids", []) for m in hist["items"]), "foreign file leaked") @s.case("idempotency includes attachment_ids (replay same, conflict on change)") def _(): a, b = post(make_png())["json"], post(make_png())["json"] path = "/api/v1/chats/" + chat["id"] + "/messages" key = uuid.uuid4().hex first = c.call("POST", path, 201, actor=alice, body={"text": "k", "attachment_ids": [a["id"], b["id"]]}, headers={"Idempotency-Key": key}, schema="Message")["json"] again = c.call("POST", path, [200, 201], actor=alice, body={"text": "k", "attachment_ids": [a["id"], b["id"]]}, headers={"Idempotency-Key": key}, schema="Message")["json"] check(again["id"] == first["id"] and again["attachment_ids"] == [a["id"], b["id"]], "replay differs") c.call("POST", path, 409, actor=alice, body={"text": "k", "attachment_ids": [b["id"], a["id"]]}, headers={"Idempotency-Key": key}) s.run()