forked from mtusi2026/mtusi2026lab6
280 lines
10 KiB
Python
280 lines
10 KiB
Python
import struct
|
|
import tracemalloc
|
|
import zlib
|
|
from io import BytesIO
|
|
|
|
import pytest
|
|
from PIL import Image, ImageFile
|
|
|
|
from messenger.attachments.domain.errors import PayloadTooLarge, UnsupportedImage
|
|
from messenger.attachments.domain.values import ImageInfo, ImageKind
|
|
from messenger.attachments.infrastructure import png as png_decoder
|
|
from messenger.attachments.infrastructure.images import PillowImageInspector
|
|
from pictures import BROKEN_PNG, DUPLICATE_IHDR_PNG, JPEG, SAMPLE, chunk, png, png_from_idat
|
|
|
|
FORMATS = [(0, d, 1) for d in (1, 2, 4, 8, 16)] + [
|
|
(color, depth, samples)
|
|
for color, depths, samples in (
|
|
(2, (8, 16), 3),
|
|
(3, (1, 2, 4, 8), 1),
|
|
(4, (8, 16), 2),
|
|
(6, (8, 16), 4),
|
|
)
|
|
for depth in depths
|
|
]
|
|
ADAM7_GRID = (
|
|
"16462646",
|
|
"77777777",
|
|
"56565656",
|
|
"77777777",
|
|
"36463646",
|
|
"77777777",
|
|
"56565656",
|
|
"77777777",
|
|
)
|
|
PIXEL = zlib.compress(b"\x00\x11\x22\x33")
|
|
BAD_STREAMS = [
|
|
pytest.param(b"not a zlib stream", id="invalid-zlib"),
|
|
pytest.param(PIXEL[:-1], id="truncated-zlib-footer"),
|
|
pytest.param(PIXEL[:-1] + bytes([PIXEL[-1] ^ 1]), id="bad-adler32"),
|
|
pytest.param(zlib.compress(b"\x00\x11\x22"), id="short-row"),
|
|
pytest.param(zlib.compress(b"\x00\x11\x22\x33\x44"), id="long-row"),
|
|
pytest.param(zlib.compress(b"\x05\x11\x22\x33"), id="invalid-filter"),
|
|
]
|
|
|
|
|
|
def scanlines(width: int, height: int, bits: int, interlace: int, filtering: int = 0) -> bytes:
|
|
rows = []
|
|
for number in range(1, 8) if interlace else (0,):
|
|
for y in range(height):
|
|
columns = (
|
|
sum(int(ADAM7_GRID[y % 8][x % 8]) == number for x in range(width))
|
|
if interlace
|
|
else width
|
|
)
|
|
if columns:
|
|
rows.append(bytes([filtering]) + b"\x00" * ((columns * bits + 7) // 8))
|
|
return b"".join(rows)
|
|
|
|
|
|
async def test_png_with_valid_crc_and_invalid_zlib_is_rejected() -> None:
|
|
assert len(BROKEN_PNG) == 74
|
|
with Image.open(BytesIO(BROKEN_PNG)) as image:
|
|
image.verify()
|
|
with Image.open(BytesIO(BROKEN_PNG)) as image, pytest.raises(OSError):
|
|
image.load()
|
|
with pytest.raises(UnsupportedImage):
|
|
await PillowImageInspector(40_000_000, 1).inspect(BROKEN_PNG, ImageKind.PNG)
|
|
|
|
|
|
async def test_duplicate_ihdr_cannot_disagree_with_pixel_validation() -> None:
|
|
assert len(DUPLICATE_IHDR_PNG) == 94
|
|
with Image.open(BytesIO(DUPLICATE_IHDR_PNG)) as image:
|
|
assert image.size == (2, 2)
|
|
image.verify()
|
|
with Image.open(BytesIO(DUPLICATE_IHDR_PNG)) as image, pytest.raises(OSError):
|
|
image.load()
|
|
with pytest.raises(UnsupportedImage):
|
|
await PillowImageInspector(40_000_000, 1).inspect(DUPLICATE_IHDR_PNG, ImageKind.PNG)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"header",
|
|
[
|
|
(1, 1, 8, 2, 0, 0, 0),
|
|
(2, 2, 8, 2, 0, 0, 0),
|
|
(1, 1, 16, 2, 0, 0, 0),
|
|
(1, 1, 8, 6, 0, 0, 0),
|
|
(1, 1, 8, 2, 0, 0, 1),
|
|
(8001, 5000, 8, 2, 0, 0, 0),
|
|
],
|
|
ids=["identical", "dimensions", "depth", "color", "interlace", "over-pixel-limit"],
|
|
)
|
|
@pytest.mark.parametrize("position", ["before-idat", "between-idat", "after-idat"])
|
|
async def test_duplicate_headers_are_rejected_before_inflating(
|
|
header: tuple[int, ...], position: str, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
data = png_from_idat(PIXEL)
|
|
duplicate = chunk(b"IHDR", struct.pack(">IIBBBBB", *header))
|
|
if position == "before-idat":
|
|
data = data[:33] + duplicate + data[33:]
|
|
elif position == "after-idat":
|
|
data = data[:-12] + duplicate + data[-12:]
|
|
else:
|
|
data = (
|
|
data[:33]
|
|
+ chunk(b"IDAT", PIXEL[:3])
|
|
+ duplicate
|
|
+ chunk(b"IDAT", PIXEL[3:])
|
|
+ data[-12:]
|
|
)
|
|
|
|
def forbidden_inflate(*args: object) -> None:
|
|
pytest.fail("ambiguous PNG header must be rejected before decompression")
|
|
|
|
monkeypatch.setattr(png_decoder.zlib, "decompressobj", forbidden_inflate)
|
|
with pytest.raises(UnsupportedImage):
|
|
await PillowImageInspector(40_000_000, 1).inspect(data, ImageKind.PNG)
|
|
|
|
|
|
@pytest.mark.parametrize("damage", ["not-first", "missing", "short", "long"])
|
|
async def test_ihdr_must_be_first_and_have_exact_length(damage: str) -> None:
|
|
data = png_from_idat(PIXEL)
|
|
if damage == "not-first":
|
|
data = data[:8] + chunk(b"tEXt", b"name\x00value") + data[8:]
|
|
elif damage == "missing":
|
|
data = data[:8] + data[33:]
|
|
else:
|
|
header = data[16:29]
|
|
header = header[:-1] if damage == "short" else header + b"\x00"
|
|
data = data[:8] + chunk(b"IHDR", header) + data[33:]
|
|
with pytest.raises(UnsupportedImage):
|
|
await PillowImageInspector(40_000_000, 1).inspect(data, ImageKind.PNG)
|
|
|
|
|
|
@pytest.mark.parametrize("stream", BAD_STREAMS)
|
|
async def test_corrupt_pixels_are_rejected_even_with_valid_chunk_crc(stream: bytes) -> None:
|
|
data = png_from_idat(stream, chunk_size=1)
|
|
with Image.open(BytesIO(data)) as image:
|
|
image.verify()
|
|
with pytest.raises(UnsupportedImage):
|
|
await PillowImageInspector(40_000_000, 1).inspect(data, ImageKind.PNG)
|
|
|
|
|
|
async def test_idat_chunks_must_be_consecutive() -> None:
|
|
data = png_from_idat(PIXEL)
|
|
data = (
|
|
data[:33]
|
|
+ chunk(b"IDAT", PIXEL[:3])
|
|
+ chunk(b"tEXt", b"name\x00value")
|
|
+ chunk(b"IDAT", PIXEL[3:])
|
|
+ data[-12:]
|
|
)
|
|
with Image.open(BytesIO(data)) as image:
|
|
image.verify()
|
|
with pytest.raises(UnsupportedImage):
|
|
await PillowImageInspector(40_000_000, 1).inspect(data, ImageKind.PNG)
|
|
|
|
|
|
@pytest.mark.parametrize("padding", [b"\x00" * 131_072, b"unused buffer", zlib.compress(b"")])
|
|
async def test_unused_idat_trailing_bytes_are_ignored(padding: bytes) -> None:
|
|
data = png_from_idat(PIXEL + padding, chunk_size=1_000_000)
|
|
with Image.open(BytesIO(data)) as image:
|
|
image.load()
|
|
assert await PillowImageInspector(40_000_000, 1).inspect(data, ImageKind.PNG) == ImageInfo(
|
|
ImageKind.PNG, 1, 1
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(("color", "depth", "samples"), FORMATS)
|
|
@pytest.mark.parametrize(("width", "height"), [(1, 1), (1, 9), (9, 1), (5, 5), (17, 13)])
|
|
@pytest.mark.parametrize("interlace", [0, 1])
|
|
async def test_supported_png_formats_match_pillow_decoding(
|
|
*, color: int, depth: int, samples: int, width: int, height: int, interlace: int
|
|
) -> None:
|
|
raw = scanlines(width, height, depth * samples, interlace)
|
|
data = png_from_idat(
|
|
zlib.compress(raw),
|
|
width,
|
|
height,
|
|
depth=depth,
|
|
color=color,
|
|
interlace=interlace,
|
|
chunk_size=3,
|
|
)
|
|
with Image.open(BytesIO(data)) as image:
|
|
image.load()
|
|
assert image.size == (width, height)
|
|
assert await PillowImageInspector(40_000_000, 1).inspect(data, ImageKind.PNG) == ImageInfo(
|
|
ImageKind.PNG, width, height
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("filtering", range(5))
|
|
@pytest.mark.parametrize("interlace", [0, 1])
|
|
@pytest.mark.parametrize("block_size", [3, 7, 31])
|
|
async def test_filters_and_passes_cross_decompression_blocks(
|
|
filtering: int, interlace: int, block_size: int, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
monkeypatch.setattr(png_decoder, "BLOCK_BYTES", block_size)
|
|
raw = scanlines(17, 13, 32, interlace, filtering)
|
|
data = png_from_idat(zlib.compress(raw), 17, 13, color=6, interlace=interlace)
|
|
with Image.open(BytesIO(data)) as image:
|
|
image.load()
|
|
assert (await PillowImageInspector(40_000_000, 1).inspect(data, ImageKind.PNG)).width == 17
|
|
|
|
|
|
@pytest.mark.parametrize("interlace", [0, 1])
|
|
@pytest.mark.parametrize("damage", ["filter", "short", "long"])
|
|
async def test_corruption_in_later_rows_or_passes(
|
|
interlace: int, damage: str, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
monkeypatch.setattr(png_decoder, "BLOCK_BYTES", 7)
|
|
raw = bytearray(scanlines(17, 13, 32, interlace))
|
|
if damage == "filter":
|
|
raw[-69] = 255
|
|
elif damage == "short":
|
|
raw.pop()
|
|
else:
|
|
raw.append(0)
|
|
data = png_from_idat(zlib.compress(raw), 17, 13, color=6, interlace=interlace, chunk_size=5)
|
|
with pytest.raises(UnsupportedImage):
|
|
await PillowImageInspector(40_000_000, 1).inspect(data, ImageKind.PNG)
|
|
|
|
|
|
@pytest.mark.parametrize(("width", "height"), [(1_000_000, 1), (1000, 1000)])
|
|
def test_png_validation_does_not_allocate_pixels_or_whole_rows(
|
|
width: int, height: int, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
data = png_from_idat(
|
|
zlib.compress(b"\x00" * ((width * 8 + 1) * height)), width, height, depth=16, color=6
|
|
)
|
|
|
|
def forbidden_load(*args: object, **kwargs: object) -> None:
|
|
pytest.fail("PNG validation must not allocate a Pillow pixel buffer")
|
|
|
|
monkeypatch.setattr(ImageFile.ImageFile, "load", forbidden_load)
|
|
inspector = PillowImageInspector(40_000_000, 1)
|
|
tracemalloc.start()
|
|
try:
|
|
assert inspector._inspect(data, ImageKind.PNG) == ImageInfo(ImageKind.PNG, width, height)
|
|
_, peak = tracemalloc.get_traced_memory()
|
|
finally:
|
|
tracemalloc.stop()
|
|
assert peak < 2_000_000
|
|
|
|
|
|
def test_excess_inflated_data_is_rejected_with_bounded_memory() -> None:
|
|
data = png_from_idat(zlib.compress(b"\x00" * 8_000_000))
|
|
inspector = PillowImageInspector(40_000_000, 1)
|
|
tracemalloc.start()
|
|
try:
|
|
with pytest.raises(UnsupportedImage):
|
|
inspector._inspect(data, ImageKind.PNG)
|
|
_, peak = tracemalloc.get_traced_memory()
|
|
finally:
|
|
tracemalloc.stop()
|
|
assert peak < 2_000_000
|
|
|
|
|
|
async def test_pixel_limit_precedes_pixel_validation(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
def forbidden_validation(data: bytes) -> None:
|
|
pytest.fail("oversized PNG must be rejected before decompression")
|
|
|
|
monkeypatch.setattr(
|
|
"messenger.attachments.infrastructure.images.verify_png_pixels", forbidden_validation
|
|
)
|
|
with pytest.raises(PayloadTooLarge):
|
|
await PillowImageInspector(40_000_000, 1).inspect(
|
|
png(8001, 5000, rows=False), ImageKind.PNG
|
|
)
|
|
|
|
|
|
async def test_exact_pixel_limit_and_existing_fixtures_still_work() -> None:
|
|
inspector = PillowImageInspector(40_000_000, 1)
|
|
assert await inspector.inspect(png(8000, 5000), ImageKind.PNG) == ImageInfo(
|
|
ImageKind.PNG, 8000, 5000
|
|
)
|
|
assert (await inspector.inspect(SAMPLE, ImageKind.PNG)).kind is ImageKind.PNG
|
|
assert (await inspector.inspect(JPEG, ImageKind.JPEG)).kind is ImageKind.JPEG
|