110 lines
5.0 KiB
Python
110 lines
5.0 KiB
Python
#!/usr/bin/env python3
|
||
"""Негативные сценарии вложений. Запускается против запущенного стенда."""
|
||
import struct
|
||
import sys
|
||
import uuid
|
||
import zlib
|
||
from pathlib import Path
|
||
from urllib.parse import quote
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
sys.path.insert(0, str(ROOT / "tests"))
|
||
|
||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||
|
||
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
|
||
|
||
|
||
def make_broken_png():
|
||
"""PNG с корректными CRC чанков, но битым потоком IDAT."""
|
||
def chunk(t, d):
|
||
c = t + d
|
||
return struct.pack(">I", len(d)) + c + struct.pack(">I", zlib.crc32(c) & 0xFFFFFFFF)
|
||
ihdr = struct.pack(">IIBBBBB", 64, 64, 8, 2, 0, 0, 0)
|
||
# Валидный zlib-заголовок + мусор: decompress() упадёт.
|
||
bad_idat = b"\x78\x9c" + b"\xff" * 100
|
||
return PNG_MAGIC + chunk(b"IHDR", ihdr) + chunk(b"IDAT", bad_idat) + chunk(b"IEND", b"")
|
||
|
||
|
||
def main():
|
||
args = arguments("Lab4 attachment negative tests")
|
||
c = Client(args.base_url, args.ca_file)
|
||
alice, bob, eve, chat = c.bootstrap()
|
||
other_chat = c.call(
|
||
"POST", "/api/v1/chats", 201, actor=bob,
|
||
body={"title": "Другой чат", "member_ids": [bob["id"]]}, schema="Chat")["json"]
|
||
base = "/api/v1/chats/%s/attachments" % chat["id"]
|
||
png_fixture = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||
|
||
# 1. Слишком большой файл.
|
||
big = PNG_MAGIC + b"\x00" * 10485760
|
||
c.call("POST", base + "?filename=big.png", 413, actor=alice, raw=big,
|
||
headers={"Content-Type": "image/png"})
|
||
|
||
# 2. Подмена MIME.
|
||
c.call("POST", base + "?filename=x.png", 415, actor=alice,
|
||
raw=b"not an image at all", headers={"Content-Type": "image/png"})
|
||
|
||
# 3. Повреждённый PNG (валидный заголовок, битая структура).
|
||
broken = png_fixture[:20] + b"\x00" * 32 + png_fixture[52:]
|
||
c.call("POST", base + "?filename=broken.png", 415, actor=alice, raw=broken,
|
||
headers={"Content-Type": "image/png"})
|
||
|
||
# 3b. PNG с корректными CRC, но битым IDAT — ловится только load().
|
||
c.call("POST", base + "?filename=broken-idat.png", 415, actor=alice,
|
||
raw=make_broken_png(), headers={"Content-Type": "image/png"})
|
||
|
||
# 4. Опасные имена: path traversal, \, NUL, DEL 0x7F, control 0x01.
|
||
for bad in ("../etc/passwd", "a\\b.png", "a\x00b.png", "a/b.png",
|
||
"a\x7fb.png", "a\x01b.png"):
|
||
c.call("POST", base + "?filename=" + quote(bad, safe=""), 400, actor=alice,
|
||
raw=png_fixture, headers={"Content-Type": "image/png"})
|
||
|
||
# 5. Чужой чат — 404 до чтения тела.
|
||
c.call("POST", base + "?filename=sample.png", 404, actor=eve,
|
||
raw=png_fixture, headers={"Content-Type": "image/png"})
|
||
|
||
# 6. Сослаться на чужое вложение — 404 (не 400).
|
||
foreign = c.call("POST", "/api/v1/chats/%s/attachments?filename=s.png" % other_chat["id"],
|
||
201, actor=bob, raw=png_fixture,
|
||
headers={"Content-Type": "image/png"}, schema="Attachment")["json"]
|
||
c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 404,
|
||
actor=alice,
|
||
body={"text": "hi", "attachment_ids": [foreign["id"]]},
|
||
headers={"Idempotency-Key": uuid.uuid4().hex})
|
||
|
||
# 6b. Случайный UUID вложения — тоже 404.
|
||
c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 404,
|
||
actor=alice,
|
||
body={"text": "hi", "attachment_ids": [str(uuid.uuid4())]},
|
||
headers={"Idempotency-Key": uuid.uuid4().hex})
|
||
|
||
# 7. Чтение чужого attachment_id — 404 на metadata и bytes.
|
||
c.call("GET", "/api/v1/attachments/" + foreign["id"], 404, actor=eve)
|
||
c.call("GET", "/api/v1/attachments/" + foreign["id"] + "/content", 404, actor=eve)
|
||
|
||
# 8. Несуществующий id — 404, не 500.
|
||
ghost = str(uuid.uuid4())
|
||
c.call("GET", "/api/v1/attachments/" + ghost, 404, actor=alice)
|
||
c.call("GET", "/api/v1/attachments/" + ghost + "/content", 404, actor=alice)
|
||
|
||
# 9. Идемпотентность: {"text":"x"} и {"text":"x","attachment_ids":[]} равны.
|
||
key = uuid.uuid4().hex
|
||
m1 = c.message(alice, chat, "idem-normalize", key=key)["json"]
|
||
m2 = c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 201,
|
||
actor=alice,
|
||
body={"text": "idem-normalize", "attachment_ids": []},
|
||
headers={"Idempotency-Key": key}, schema="Message")["json"]
|
||
check(m1["id"] == m2["id"], "idempotency: attachment_ids=[] must equal absent")
|
||
|
||
# 10. Idempotency-Key с пробелом — 400.
|
||
c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 400,
|
||
actor=alice,
|
||
body={"text": "x"},
|
||
headers={"Idempotency-Key": "contains space"})
|
||
|
||
print("PASS: 10 negative attachment scenarios")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
run(main) |