"""Изображения для тестов вложений: настоящие, повреждённые, огромные. PNG собираются на stdlib — любые IHDR и IDAT, Adam7, точный размер файла чанком-заполнителем `tEXt`, «бомба», порча CRC. JPEG — через Pillow (dev-группа): прогрессивный, серый, CMYK, с EXIF, с подменой размеров в SOF, без таблиц, с изменённым заголовком скана и без данных скана. Большие файлы и «бомбы» живут только в памяти теста и в git не попадают (`tests/fixtures/README.md`). """ import functools import io import random import struct import zlib from pathlib import Path PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" # маркеры JPEG: таблицы квантования и Хаффмана, начало скана, конец JPEG_DQT = 0xDB JPEG_DHT = 0xC4 JPEG_SOS = 0xDA JPEG_EOI = b"\xff\xd9" # 27 байт из замечания к PR: SOI, SOF0 1 × 1, SOS без данных и EOI — ни # таблицы квантования, ни таблиц Хаффмана JPEG_WITHOUT_TABLES = bytes.fromhex( "ffd8ffc0000b080001000101011100ffda0008010100003f00ffd9", ) SAMPLE_PNG_PATH = ( Path(__file__).resolve().parents[1] / "tests" / "fixtures" / "sample.png" ) # лимиты контракта лабы 4 MAX_BYTES = 10 * 1024 * 1024 MAX_PIXELS = 40_000_000 _CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4} _ADAM7 = ( (0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2), ) @functools.cache def sample_png() -> bytes: """Публичный fixture `tests/fixtures/sample.png` (320 × 200).""" return SAMPLE_PNG_PATH.read_bytes() def chunk(kind: bytes, body: bytes) -> bytes: """Чанк PNG с верной CRC.""" crc = zlib.crc32(kind + body) return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", crc) def _rows( width: int, height: int, *, bits_per_pixel: int, interlace: bool, ) -> bytes: """Распакованные данные: строки с фильтром 0 и узором в пикселях.""" passes = _ADAM7 if interlace else ((0, 0, 1, 1),) out = bytearray() for x0, y0, dx, dy in passes: pass_width = (width - x0 + dx - 1) // dx if width > x0 else 0 pass_height = (height - y0 + dy - 1) // dy if height > y0 else 0 if not pass_width or not pass_height: continue row_bytes = (pass_width * bits_per_pixel + 7) // 8 row = bytes((i * 7) % 256 for i in range(row_bytes)) out += (b"\x00" + row) * pass_height return bytes(out) def png( width: int = 64, height: int = 48, *, color: int = 2, depth: int = 8, interlace: bool = False, idat: bytes | None = None, ) -> bytes: """Настоящий PNG: IHDR, PLTE для палитры, IDAT, IEND. `idat` — готовый сжатый поток вместо строк по размерам (огромные размеры в маленьком файле, «бомба»). """ ihdr = struct.pack( ">IIBBBBB", width, height, depth, color, 0, 0, 1 if interlace else 0, ) if idat is None: idat = zlib.compress( _rows( width, height, bits_per_pixel=depth * _CHANNELS[color], interlace=interlace, ), 9, ) palette = chunk(b"PLTE", bytes(range(48))) if color == 3 else b"" return ( PNG_SIGNATURE + chunk(b"IHDR", ihdr) + palette + chunk(b"IDAT", idat) + chunk(b"IEND", b"") ) def png_of_size(size: int) -> bytes: """Настоящий PNG 64 × 48 ровно `size` байт: добор чанком `tEXt`.""" base = png() filler = size - len(base) - 12 assert filler >= 2, f"size {size} is too small" text = chunk(b"tEXt", b"k\x00" + b"x" * (filler - 2)) # tEXt — после IHDR (8 + 25 байт), до IDAT data = base[:33] + text + base[33:] assert len(data) == size return data def png_noise(width: int = 1024, height: int = 341, *, seed: int = 0) -> bytes: """Настоящий RGB PNG из шума: сжимается плохо, поэтому размер файла — около `width × height × 3` байт (по умолчанию ~1 MiB). Разные `seed` — разные байты; один `seed` — одни и те же.""" noise = random.Random(seed) row_bytes = width * 3 rows = b"".join( b"\x00" + noise.randbytes(row_bytes) for _ in range(height) ) return png(width, height, color=2, idat=zlib.compress(rows, 1)) def png_huge(width: int, height: int) -> bytes: """Несколько килобайт с огромными размерами в IHDR.""" return png( width, height, color=0, depth=1, idat=zlib.compress(bytes(4096)), ) def png_bomb(unpacked_mib: int = 200) -> bytes: """PNG 100 × 100, IDAT которого распаковывается в `unpacked_mib` MiB.""" compressor = zlib.compressobj(9) block = bytes(1024 * 1024) stream = b"".join(compressor.compress(block) for _ in range(unpacked_mib)) return png(100, 100, idat=stream + compressor.flush()) def flip_byte(data: bytes, offset: int) -> bytes: damaged = bytearray(data) damaged[offset] ^= 0x55 return bytes(damaged) def png_idat_byte_changed(data: bytes | None = None) -> bytes: """Изменённый байт внутри первого IDAT (CRC чанка не сходится).""" data = data or sample_png() return flip_byte(data, data.index(b"IDAT") + 40) def truncated(data: bytes, keep: float = 0.5) -> bytes: return data[: int(len(data) * keep)] def with_tail(data: bytes, tail: bytes = b"TAIL" * 64) -> bytes: """Байты после IEND или EOI.""" return data + tail def _pillow_image(mode: str, size: tuple[int, int]) -> object: from PIL import Image # noqa: PLC0415 — Pillow только для JPEG width, height = size image = Image.new("RGB", size) image.putdata( [ ((x * 7) % 256, (y * 13) % 256, (x * y) % 256) for y in range(height) for x in range(width) ], ) return image.convert(mode) def jpeg( mode: str = "RGB", size: tuple[int, int] = (64, 48), **save: object, ) -> bytes: """Настоящий JPEG через Pillow; `save` — параметры `Image.save`.""" from PIL import Image # noqa: PLC0415 buffer = io.BytesIO() image = _pillow_image(mode, size) if "exif" in save and save["exif"] is True: exif = Image.Exif() exif[0x010F] = "student-tests" exif[0x0112] = 1 save["exif"] = exif image.save(buffer, "JPEG", **save) return buffer.getvalue() def jpeg_huge(width: int, height: int) -> bytes: """Маленький JPEG с подменёнными размерами в SOF0.""" data = bytearray(jpeg()) sof = data.index(b"\xff\xc0") data[sof + 5 : sof + 9] = struct.pack(">HH", height, width) return bytes(data) def _jpeg_header(data: bytes) -> list[tuple[int, int, int]]: """Сегменты до первого скана включительно: маркер, начало, конец.""" segments = [] pos = 2 while True: marker = data[pos + 1] (length,) = struct.unpack_from(">H", data, pos + 2) segments.append((marker, pos, pos + 2 + length)) pos += 2 + length if marker == JPEG_SOS: return segments def jpeg_without(marker: int, data: bytes | None = None) -> bytes: """JPEG без сегментов `marker` (`JPEG_DQT`, `JPEG_DHT`) до первого скана.""" data = data or jpeg() out = bytearray(data) for found, start, end in reversed(_jpeg_header(data)): if found == marker: del out[start:end] return bytes(out) def jpeg_scan_byte(data: bytes, index: int, value: int) -> bytes: """Байт `index` тела первого SOS заменён на `value`: 1 — id первой компоненты, -3, -2, -1 — Ss, Se и Ah/Al.""" _, start, end = _jpeg_header(data)[-1] out = bytearray(data) out[start + 4 + index if index >= 0 else end + index] = value return bytes(out) def jpeg_empty_scan(data: bytes | None = None) -> bytes: """JPEG, у которого за заголовком первого скана сразу EOI.""" data = data or jpeg() return data[: _jpeg_header(data)[-1][2]] + JPEG_EOI def jpeg_precision_12() -> bytes: """JPEG с 12 битами на компоненту в SOF: структура верна, а Pillow такой не декодирует (спек `attachment-processing`, «Изображение не декодируется»).""" data = bytearray(jpeg()) sof = data.index(b"\xff\xc0") data[sof + 4] = 12 return bytes(data) def jpeg_halves( orientation: int | None = None, size: tuple[int, int] = (400, 200), ) -> bytes: """JPEG: левая половина красная, правая синяя; EXIF orientation — необязательно.""" from PIL import Image # noqa: PLC0415 width, height = size image = Image.new("RGB", size, (255, 0, 0)) image.paste((0, 0, 255), (width // 2, 0, width, height)) save: dict[str, object] = {"quality": 95} if orientation is not None: exif = Image.Exif() exif[0x0112] = orientation save["exif"] = exif buffer = io.BytesIO() image.save(buffer, "JPEG", **save) return buffer.getvalue() def png_half_transparent(size: tuple[int, int] = (200, 100)) -> bytes: """PNG RGBA: левая половина чёрная и непрозрачная, правая прозрачная.""" from PIL import Image # noqa: PLC0415 width, height = size image = Image.new("RGBA", size, (0, 0, 0, 255)) image.paste((0, 0, 0, 0), (width // 2, 0, width, height)) buffer = io.BytesIO() image.save(buffer, "PNG") return buffer.getvalue() def png_palette_transparent(size: tuple[int, int] = (200, 100)) -> bytes: """PNG с палитрой и tRNS: левая половина — чёрный цвет палитры, правая — прозрачный.""" from PIL import Image # noqa: PLC0415 width, height = size image = Image.new("P", size, 0) image.putpalette([0, 0, 0, 0, 0, 0]) image.paste(1, (width // 2, 0, width, height)) buffer = io.BytesIO() image.save(buffer, "PNG", transparency=bytes((255, 0))) return buffer.getvalue() def png_rgba_large(width: int = 8000, height: int = 5000) -> bytes: """PNG RGBA на 40 млн пикселей: пик памяти декодирования — как у настоящего, файл мал и собирается быстро.""" from PIL import Image # noqa: PLC0415 image = Image.new("RGBA", (width, height), (10, 20, 30, 128)) buffer = io.BytesIO() image.save(buffer, "PNG", compress_level=1) return buffer.getvalue() def png_at_pixel_limit( color: int, depth: int, *, transparent: bool = False, width: int = 8000, height: int = 5000, ) -> bytes: """PNG любого типа на 40 млн пикселей из нулей: файл мал, а декодирование разворачивает все пиксели. `transparent` — чанк tRNS (прозрачный цвет): Pillow открывает такой файл без альфы и переводит в RGBA отдельным шагом.""" row = b"\x00" * (1 + (width * depth * _CHANNELS[color] + 7) // 8) compressor = zlib.compressobj(9) parts = [compressor.compress(row) for _ in range(height)] parts.append(compressor.flush()) data = png( width, height, color=color, depth=depth, idat=b"".join(parts), ) if not transparent: return data # tRNS — после IHDR и PLTE (перед первым IDAT): у палитры индекс, иначе цвет index = data.index(b"IDAT") - 4 body = b"\x00" if color == 3 else b"\x00" * (6 if color == 2 else 2) return data[:index] + chunk(b"tRNS", body) + data[index:] def png_stripes( stripes: tuple[tuple[int, tuple[int, int, int]], ...] = ( (100, (255, 0, 0)), (200, (0, 0, 255)), (100, (0, 255, 0)), ), height: int = 200, ) -> bytes: """PNG RGB из вертикальных полос `(ширина, цвет)`: по умолчанию 400 × 200 спека «Crop большого изображения».""" from PIL import Image # noqa: PLC0415 width = sum(stripe for stripe, _ in stripes) image = Image.new("RGB", (width, height)) left = 0 for stripe, color in stripes: image.paste(color, (left, 0, left + stripe, height)) left += stripe buffer = io.BytesIO() image.save(buffer, "PNG") return buffer.getvalue() def png_solid(width: int, height: int) -> bytes: """PNG RGB одного цвета любых размеров в маленьком файле.""" from PIL import Image # noqa: PLC0415 buffer = io.BytesIO() Image.new("RGB", (width, height), (10, 120, 200)).save( buffer, "PNG", compress_level=1, ) return buffer.getvalue() # строка производителя в EXIF `jpeg_with_metadata`: её не должно быть в # вариантах (спек «Optimized без метаданных») JPEG_MAKER = "student-tests-maker" def jpeg_with_metadata(orientation: int = 6) -> bytes: """JPEG 400 × 200, левая половина красная, правая синяя, с EXIF orientation, строкой производителя и профилем ICC.""" from PIL import Image, ImageCms # noqa: PLC0415 image = Image.new("RGB", (400, 200), (255, 0, 0)) image.paste((0, 0, 255), (200, 0, 400, 200)) exif = Image.Exif() exif[0x0112] = orientation exif[0x010F] = JPEG_MAKER profile = ImageCms.ImageCmsProfile(ImageCms.createProfile("sRGB")) buffer = io.BytesIO() image.save( buffer, "JPEG", quality=95, exif=exif, icc_profile=profile.tobytes(), ) return buffer.getvalue() def _scan_end(data: bytes, start: int) -> int: """Конец сжатых данных скана: первый маркер, кроме `FF00` и RST.""" pos = start while True: pos = data.index(b"\xff", pos) marker = data[pos + 1] if marker != 0 and not 0xD0 <= marker <= 0xD7: return pos pos += 2 def jpeg_scan_bomb(size: int = MAX_BYTES - 64) -> bytes: """«Дорогой» JPEG в пределах контракта: прогрессивный 8000 × 5000, самый маленький скан повторён до `size` байт (сотни тысяч сканов). Структурная проверка его принимает, а декодирование занимает больше минуты CPU (design change `pipeline-reliability`, таблица проб).""" from PIL import Image # noqa: PLC0415 buffer = io.BytesIO() Image.new("RGB", (8000, 5000), (128, 128, 128)).save( buffer, "JPEG", progressive=True, quality=50, ) data = buffer.getvalue() scans = [] pos = 0 while (pos := data.find(b"\xff\xda", pos)) != -1: (length,) = struct.unpack_from(">H", data, pos + 2) end = _scan_end(data, pos + 2 + length) scans.append(data[pos:end]) pos = end # только сканы AC (Ss > 0): их можно повторять, не ломая DC repeatable = [ scan for scan in scans if scan[2 + struct.unpack_from(">H", scan, 2)[0] - 3] > 0 ] smallest = min(repeatable, key=len) body = data[: -len(JPEG_EOI)] count = (size - len(data)) // len(smallest) assert count > 100_000, f"scan of {len(smallest)} bytes is too big" bomb = body + smallest * count + JPEG_EOI assert len(bomb) <= MAX_BYTES return bomb def png_variants() -> dict[str, bytes]: """Разновидности PNG спека: палитра, альфа, серый с альфой, 16 и 1 бит, Adam7.""" return { "palette": png(color=3, depth=8), "rgba": png(color=6), "gray-alpha": png(color=4), "rgb-16-bit": png(color=2, depth=16), "gray-1-bit": png(color=0, depth=1), "adam7": png(37, 29, interlace=True), } def jpeg_variants() -> dict[str, bytes]: """Разновидности JPEG спека: прогрессивный, серый, CMYK, с EXIF, baseline без таблиц Хаффмана (кадр Motion JPEG: декодер берёт стандартные).""" return { "progressive": jpeg(progressive=True), "gray": jpeg("L"), "cmyk": jpeg("CMYK"), "exif": jpeg(exif=True), "no-huffman-tables": jpeg_without(JPEG_DHT), } def jpeg_undecodable() -> dict[str, bytes]: """JPEG, которые проходят разбор маркеров, но не декодируются или заведомо оборваны (спек `attachments`, «Недекодируемый JPEG»).""" progressive = jpeg(progressive=True) return { "27 bytes without tables": JPEG_WITHOUT_TABLES, "no quantization tables": jpeg_without(JPEG_DQT), "progressive without huffman tables": jpeg_without( JPEG_DHT, progressive, ), "scan of unknown component": jpeg_scan_byte(jpeg(), 1, 9), # первый скан Pillow — DC трёх компонент; полоса 1–63 делает его # AC-сканом, а у AC-скана компонента одна "progressive ac band of 3 components": jpeg_scan_byte( jpeg_scan_byte(progressive, -3, 1), -2, 63, ), "empty scan data": jpeg_empty_scan(), }