исправила замечания

This commit is contained in:
2026-10-31 11:02:37 +03:00
parent e135f1c5d4
commit e3d441c629
6 changed files with 127 additions and 77 deletions
+53 -18
View File
@@ -1,7 +1,9 @@
#!/usr/bin/env python3
"""Негативные сценарии вложений. Запускается против запущенного стенда."""
import struct
import sys
import uuid
import zlib
from pathlib import Path
from urllib.parse import quote
@@ -13,6 +15,17 @@ 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)
@@ -23,42 +36,49 @@ def main():
base = "/api/v1/chats/%s/attachments" % chat["id"]
png_fixture = (ROOT / "tests/fixtures/sample.png").read_bytes()
# 1. Слишком большой файл: 10 MiB + 1 байт, Content-Length сразу отвергается.
big = PNG_MAGIC + b"\x00" * (10485760)
r = c.call("POST", base + "?filename=big.png", 413, actor=alice, raw=big,
headers={"Content-Type": "image/png"})
check(r["status"] == 413, "oversize not rejected")
# 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: объявляем image/png, а байты не PNG.
r = c.call("POST", base + "?filename=x.png", 415, actor=alice,
raw=b"not an image at all",
headers={"Content-Type": "image/png"})
check(r["status"] == 415, "mime mismatch not rejected")
# 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: валидный заголовок, битая структура.
# 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"})
# 4. Опасное имя файла. URL-кодируем: NUL, /, \ в URL напрямую запрещены
# клиентом (http.client), но после декодирования сервер обязан отклонить.
for bad in ("../etc/passwd", "a\\b.png", "a\x00b.png", "a/b.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. Чужой чат: eve не участник — 404 до чтения тела.
# 5. Чужой чат — 404 до чтения тела.
c.call("POST", base + "?filename=sample.png", 404, actor=eve,
raw=png_fixture, headers={"Content-Type": "image/png"})
# 6. Сослаться на чужое вложение в сообщении.
# 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"], 400,
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)
@@ -68,7 +88,22 @@ def main():
c.call("GET", "/api/v1/attachments/" + ghost, 404, actor=alice)
c.call("GET", "/api/v1/attachments/" + ghost + "/content", 404, actor=alice)
print("PASS: 8 negative attachment scenarios")
# 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__":