Reject ambiguous PNG headers before pixel validation

This commit is contained in:
Artyom
2026-11-06 21:33:09 +03:00
parent bcbd4ebc02
commit 7c8a1a6489
21 changed files with 498 additions and 34 deletions
+67 -1
View File
@@ -1,3 +1,4 @@
import struct
import tracemalloc
import zlib
from io import BytesIO
@@ -9,7 +10,7 @@ from messenger.attachments.domain.errors import PayloadTooLarge, UnsupportedImag
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, JPEG, SAMPLE, chunk, png, png_from_idat
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)
@@ -66,6 +67,71 @@ async def test_png_with_valid_crc_and_invalid_zlib_is_rejected() -> None:
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)
+11 -5
View File
@@ -1,7 +1,9 @@
from datetime import UTC, datetime
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
from uuid import uuid4
import pytest
from fastapi import FastAPI
from httpx import ASGITransport, AsyncClient
from starlette.types import Scope
@@ -22,12 +24,16 @@ from messenger.attachments.infrastructure.images import PillowImageInspector
from messenger.shared.application.ports import Clock, IdGenerator
from messenger.shared.entrypoints.errors import install
from messenger.shared.entrypoints.pipeline import RequestPipeline
from pictures import BROKEN_PNG
from pictures import BROKEN_PNG, DUPLICATE_IHDR_PNG
async def test_broken_png_returns_415_before_any_storage_write() -> None:
@pytest.mark.parametrize(
"data", [BROKEN_PNG, DUPLICATE_IHDR_PNG], ids=["bad-zlib", "duplicate-ihdr"]
)
async def test_broken_png_returns_415_before_any_storage_write(data: bytes) -> None:
uow = Mock(spec=AttachmentsUnitOfWork)
uow.attachments = AsyncMock(spec=AttachmentRepository)
uow.transaction.return_value = AsyncMock()
uow.collect_new_events.return_value = []
storage = AsyncMock(spec=ObjectStorage)
membership = AsyncMock(spec=ChatMembership)
@@ -39,8 +45,8 @@ async def test_broken_png_returns_415_before_any_storage_write() -> None:
membership,
PillowImageInspector(40_000_000, 1),
storage,
clock=Mock(spec=Clock),
ids=Mock(spec=IdGenerator),
clock=Mock(spec=Clock, now=Mock(return_value=datetime(2026, 11, 6, tzinfo=UTC))),
ids=Mock(spec=IdGenerator, new_id=Mock(side_effect=uuid4)),
limit=10_485_760,
slots=UploadSlots(1),
logger=logger,
@@ -62,7 +68,7 @@ async def test_broken_png_returns_415_before_any_storage_write() -> None:
response = await http.post(
f"/api/v1/chats/{chat}/attachments?filename=broken.png",
headers={"Content-Type": "image/png", "X-Request-Id": "png-regression"},
content=BROKEN_PNG,
content=data,
)
assert response.status_code == 415, response.text
assert response.json()["error"]["code"] == "unsupported_media_type"