forked from mtusi2026/mtusi2026lab4
4: исправление по ревью — проверка смысла чанков PNG (палитра, tRNS, порядок, текст), регрессионные тесты, evidence
This commit is contained in:
+22
-3
@@ -22,7 +22,7 @@ def chunk(kind: bytes, data: bytes) -> bytes:
|
||||
def png(width, height, *, gray=False, noise=False, interlace=0, pad_to=None, idat=None) -> bytes:
|
||||
"""PNG width x height. noise=True — случайные пиксели (почти не сжимаются, файл большой).
|
||||
|
||||
pad_to — дополнить файл служебным чанком prVt до точного размера в байтах.
|
||||
pad_to — дополнить файл текстовым чанком tEXt после IDAT до точного размера в байтах.
|
||||
idat — готовые сжатые данные (для «бомбы»: заголовок обещает одно, данных другое).
|
||||
"""
|
||||
channels = 1 if gray else 3
|
||||
@@ -43,9 +43,9 @@ def png(width, height, *, gray=False, noise=False, interlace=0, pad_to=None, ida
|
||||
idat = b"".join(parts)
|
||||
body = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", idat)
|
||||
if pad_to is not None:
|
||||
need = pad_to - len(body) - 12 - 12 # чанк-заполнитель + IEND
|
||||
need = pad_to - len(body) - 12 - 12 - 8 # заголовок чанка-заполнителя, IEND, ключ "Comment\0"
|
||||
assert need >= 0, "image is already larger than pad_to"
|
||||
body += chunk(b"prVt", bytes(need))
|
||||
body += chunk(b"tEXt", b"Comment\x00" + b"a" * need)
|
||||
return body + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
@@ -72,3 +72,22 @@ def flip_byte(data: bytes, position: int) -> bytes:
|
||||
|
||||
|
||||
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;"
|
||||
|
||||
|
||||
# --- сборка PNG из произвольных чанков (для проверок смысла чанков при верных CRC) ---
|
||||
|
||||
def ihdr(width, height, depth=8, color=2, interlace=0):
|
||||
return b"IHDR", struct.pack(">IIBBBBB", width, height, depth, color, 0, 0, interlace)
|
||||
|
||||
|
||||
def zero_idat(width, height, depth=8, channels=3):
|
||||
"""Сжатые пиксели: каждая строка = байт фильтра 0 + нули (индекс палитры 0 / чёрный)."""
|
||||
row_bytes = (width * depth * channels + 7) // 8
|
||||
return b"IDAT", zlib.compress((b"\x00" + bytes(row_bytes)) * height)
|
||||
|
||||
|
||||
def assemble(*chunks):
|
||||
"""PNG из чанков (kind, data) с ВЕРНЫМИ CRC; IEND добавляется, если не передан."""
|
||||
if not chunks or chunks[-1][0] != b"IEND":
|
||||
chunks = chunks + ((b"IEND", b""),)
|
||||
return b"\x89PNG\r\n\x1a\n" + b"".join(chunk(kind, data) for kind, data in chunks)
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import hashlib
|
||||
import http.client
|
||||
import socket
|
||||
import struct
|
||||
import urllib.parse
|
||||
import uuid
|
||||
import zlib
|
||||
@@ -135,6 +136,73 @@ def test_damaged_images():
|
||||
print("PASS: damaged and foreign files are rejected with 415, never 500")
|
||||
|
||||
|
||||
def test_png_chunk_semantics():
|
||||
"""CRC у всех чанков верные, но содержимое нарушает спецификацию PNG -> 415, а не 201.
|
||||
|
||||
Регрессия: PNG 1x1, глубина 8, палитровый, PLTE из 771 байта (257 записей) раньше получал 201 ready,
|
||||
хотя Pillow его отклоняет (invalid palette size).
|
||||
"""
|
||||
alice, bob, _, chat = setup()
|
||||
from images import assemble, ihdr, zero_idat
|
||||
pal = lambda entries: (b"PLTE", bytes(3 * entries))
|
||||
idat_p = zero_idat(1, 1, 8, 1)
|
||||
bad = [
|
||||
("PLTE 771 bytes = 257 entries (review case)",
|
||||
assemble(ihdr(1, 1, 8, 3), (b"PLTE", bytes(771)), (b"IDAT", zlib.compress(b"\0\0")))),
|
||||
("PLTE length not a multiple of 3", assemble(ihdr(1, 1, 8, 3), (b"PLTE", bytes(4)), idat_p)),
|
||||
("empty PLTE", assemble(ihdr(1, 1, 8, 3), (b"PLTE", b""), idat_p)),
|
||||
("palette larger than bit depth allows (depth 1, 3 entries)",
|
||||
assemble(ihdr(1, 1, 1, 3), pal(3), zero_idat(1, 1, 1, 1))),
|
||||
("palette image without PLTE", assemble(ihdr(1, 1, 8, 3), idat_p)),
|
||||
("PLTE in a grayscale image", assemble(ihdr(1, 1, 8, 0), pal(2), zero_idat(1, 1, 8, 1))),
|
||||
("PLTE after IDAT", assemble(ihdr(1, 1, 8, 3), idat_p, pal(2))),
|
||||
("two PLTE chunks", assemble(ihdr(1, 1, 8, 3), pal(2), pal(2), idat_p)),
|
||||
("tRNS longer than the palette", assemble(ihdr(1, 1, 8, 3), pal(2), (b"tRNS", bytes(3)), idat_p)),
|
||||
("tRNS before PLTE", assemble(ihdr(1, 1, 8, 3), (b"tRNS", bytes(1)), pal(2), idat_p)),
|
||||
("tRNS of wrong size for RGB (4 bytes instead of 6)",
|
||||
assemble(ihdr(1, 1, 8, 2), (b"tRNS", bytes(4)), zero_idat(1, 1, 8, 3))),
|
||||
("tRNS in an image with alpha channel",
|
||||
assemble(ihdr(1, 1, 8, 6), (b"tRNS", bytes(2)), zero_idat(1, 1, 8, 4))),
|
||||
("IEND with data", assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"IEND", b"x"))),
|
||||
("unknown critical chunk", assemble(ihdr(1, 1, 8, 2), (b"ABCD", b""), zero_idat(1, 1, 8, 3))),
|
||||
("IDAT chunks not consecutive",
|
||||
assemble(ihdr(1, 2, 8, 2), (b"IDAT", zero_idat(1, 2, 8, 3)[1][:5]), (b"tEXt", b"k\0v"),
|
||||
(b"IDAT", zero_idat(1, 2, 8, 3)[1][5:]))),
|
||||
("gAMA after IDAT", assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"gAMA", bytes(4)))),
|
||||
("gAMA of 2 bytes instead of 4", assemble(ihdr(1, 1, 8, 2), (b"gAMA", bytes(2)), zero_idat(1, 1, 8, 3))),
|
||||
("3 MiB metadata chunk before IDAT", assemble(ihdr(1, 1, 8, 2), (b"prVt", bytes(3 * 1024 * 1024)),
|
||||
zero_idat(1, 1, 8, 3))),
|
||||
("private chunk after IDAT", assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"prVt", bytes(100)))),
|
||||
("animated PNG frame (fdAT)", assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"fdAT", bytes(10)))),
|
||||
("tIME of 2 bytes instead of 7", assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"tIME", bytes(2)))),
|
||||
("tEXt without keyword separator", assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"tEXt", b"nokey"))),
|
||||
("zTXt with broken zlib after IDAT",
|
||||
assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"zTXt", b"k\0\0garbage"))),
|
||||
("zTXt text bomb: 50 MB of text in ~50 KB after IDAT",
|
||||
assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"zTXt", b"k\0\0" + zlib.compress(bytes(50_000_000))))),
|
||||
]
|
||||
for name, data in bad:
|
||||
check_error(upload(alice, chat["id"], data, filename="bad.png", expected=415), "unsupported_media_type")
|
||||
print(f"{name} ({len(data)} bytes, valid CRCs) -> 415")
|
||||
good = [
|
||||
("palette 256 entries + tRNS + tEXt and tIME after IDAT",
|
||||
assemble(ihdr(2, 2, 8, 3), pal(256), (b"tRNS", bytes(256)), zero_idat(2, 2, 8, 1),
|
||||
(b"tEXt", b"Comment\0ok"), (b"tIME", struct.pack(">HBBBBB", 2026, 10, 22, 12, 0, 0)))),
|
||||
("palette depth 2 with 4 entries", assemble(ihdr(3, 1, 2, 3), pal(4), zero_idat(3, 1, 2, 1))),
|
||||
("RGB with 6-byte tRNS and gAMA", assemble(ihdr(1, 1, 8, 2), (b"gAMA", struct.pack(">I", 45455)),
|
||||
(b"tRNS", bytes(6)), zero_idat(1, 1, 8, 3))),
|
||||
("compressed zTXt (100 KB of text) and iTXt after IDAT",
|
||||
assemble(ihdr(1, 1, 8, 2), zero_idat(1, 1, 8, 3), (b"zTXt", b"Comment\0\0" + zlib.compress(b"a" * 100_000)),
|
||||
(b"iTXt", b"Title\0\1\0ru\0\0" + zlib.compress("Привет".encode())))),
|
||||
]
|
||||
for name, data in good:
|
||||
att = upload(alice, chat["id"], data, filename="good.png").json
|
||||
got = call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"])
|
||||
check(got.data == data, "valid PNG changed")
|
||||
print(f"{name} -> 201, downloaded byte for byte")
|
||||
print("PASS: chunk contents are checked, not only CRCs; valid PNGs with metadata are still accepted")
|
||||
|
||||
|
||||
def test_mime_substitution():
|
||||
alice, _, _, chat = setup()
|
||||
cases = [
|
||||
@@ -264,5 +332,5 @@ def test_aborted_upload():
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests([test_png_and_jpeg_roundtrip, test_size_limit_exact_boundary, test_size_limit_streaming,
|
||||
test_pixel_limit, test_damaged_images, test_mime_substitution, test_filenames, test_access_control,
|
||||
test_pixel_limit, test_damaged_images, test_png_chunk_semantics, test_mime_substitution, test_filenames, test_access_control,
|
||||
test_message_attachments, test_idempotency_with_attachments, test_aborted_upload])
|
||||
|
||||
Reference in New Issue
Block a user