Reject ambiguous PNG headers before pixel validation
This commit is contained in:
@@ -10,7 +10,7 @@ from httpx import AsyncClient, Response
|
||||
from conftest import actor, make_chat, register, resolve, running_app, scalar
|
||||
from fakes import MemoryObjectStorage
|
||||
from messenger.attachments.application.ports import ObjectStorage
|
||||
from pictures import BROKEN_PNG, GIF, JPEG, SAMPLE, WEBP, png
|
||||
from pictures import BROKEN_PNG, DUPLICATE_IHDR_PNG, GIF, JPEG, SAMPLE, WEBP, png
|
||||
|
||||
LIMIT = 10_485_760
|
||||
PNG = {"Content-Type": "image/png"}
|
||||
@@ -182,6 +182,7 @@ async def test_pixel_limit_is_read_from_header(
|
||||
("content", "header"),
|
||||
[
|
||||
(BROKEN_PNG, "image/png"),
|
||||
(DUPLICATE_IHDR_PNG, "image/png"),
|
||||
(JPEG, "image/png"),
|
||||
(GIF, "image/png"),
|
||||
(WEBP, "image/png"),
|
||||
@@ -194,6 +195,8 @@ async def test_pixel_limit_is_read_from_header(
|
||||
(SAMPLE, "image/gif"),
|
||||
],
|
||||
ids=[
|
||||
"invalid-zlib",
|
||||
"duplicate-ihdr",
|
||||
"jpeg-as-png",
|
||||
"gif-as-png",
|
||||
"webp-as-png",
|
||||
|
||||
@@ -34,6 +34,11 @@ def png_from_idat(
|
||||
|
||||
|
||||
BROKEN_PNG = png_from_idat(b"not a zlib stream")
|
||||
DUPLICATE_IHDR_PNG = (
|
||||
SIGNATURE
|
||||
+ chunk(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0))
|
||||
+ png_from_idat(zlib.compress(bytes(4)), 2, 2)[len(SIGNATURE) :]
|
||||
)
|
||||
|
||||
|
||||
def png(width: int, height: int, *, size: int | None = None, rows: bool = True) -> bytes:
|
||||
|
||||
@@ -15,7 +15,7 @@ import httpx
|
||||
import pytest
|
||||
from httpx import AsyncClient, Response
|
||||
|
||||
from pictures import BROKEN_PNG, GIF, JPEG, SAMPLE, WEBP, png
|
||||
from pictures import BROKEN_PNG, DUPLICATE_IHDR_PNG, GIF, JPEG, SAMPLE, WEBP, png
|
||||
from stand import BASE_URL, bearer, compose, enroll, lb_up, psql, waited
|
||||
|
||||
pytestmark = pytest.mark.stack
|
||||
@@ -311,6 +311,7 @@ async def test_user_errors_never_become_500(http: AsyncClient) -> None:
|
||||
expect("PNG 8001×5000", await upload(http, alice, chat, png(8001, 5000, rows=False)), 413)
|
||||
for label, content, kind in (
|
||||
("PNG с корректными CRC и битым IDAT", BROKEN_PNG, "image/png"),
|
||||
("PNG с повторным IHDR", DUPLICATE_IHDR_PNG, "image/png"),
|
||||
("обрезанный PNG", SAMPLE[: len(SAMPLE) // 2], "image/png"),
|
||||
("обрезанный JPEG", JPEG[: len(JPEG) // 2], "image/jpeg"),
|
||||
("JPEG как image/png", JPEG, "image/png"),
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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"
|
||||
|
||||
Reference in New Issue
Block a user