"""Приём изображения: ограниченное чтение тела и проверка PNG/JPEG по содержимому. Порядок выбран так, чтобы ни один лимит не проверялся ПОСЛЕ дорогой операции: 1. Content-Length больше лимита -> 413 сразу, тело не читается; 2. чтение потоком с обрывом на MAX_UPLOAD_BYTES + 1 байте (chunked без длины тоже ограничен); 3. сигнатура (magic bytes) -> тип; несовпадение с Content-Type или чужой формат -> 415; 4. размеры из заголовка изображения (Pillow читает только header) -> > MAX_IMAGE_PIXELS -> 413 ДО распаковки пикселей (защита от decompression bomb); 5. только потом проверка целостности: PNG verify() (CRC чанков), JPEG — декодирование в draft-режиме 1/8. """ import asyncio import io import warnings from fastapi import Request from PIL import Image from .errors import ApiError # Лимит пикселей проверяем сами (п.4) с нужным кодом ответа; встроенный в Pillow оставляем как страховку. Image.MAX_IMAGE_PIXELS = 40_000_000 Image.LOAD_TRUNCATED_IMAGES = False SIGNATURES = { 'image/png': b'\x89PNG\r\n\x1a\n', 'image/jpeg': b'\xff\xd8\xff', } PIL_FORMATS = {'image/png': 'PNG', 'image/jpeg': 'JPEG'} def too_large(message: str = 'Файл превышает лимит') -> ApiError: return ApiError(413, 'payload_too_large', message) def unsupported(message: str = 'Ожидается корректное изображение PNG или JPEG') -> ApiError: return ApiError(415, 'unsupported_media_type', message) def declared_type(request: Request) -> str: media_type = request.headers.get('content-type', '').split(';')[0].strip().lower() if media_type not in SIGNATURES: raise unsupported('Content-Type должен быть image/png или image/jpeg') return media_type async def read_limited(request: Request, limit: int) -> bytes: length = request.headers.get('content-length') if length is not None and length.isdigit() and int(length) > limit: raise too_large() buf = bytearray() async for chunk in request.stream(): buf += chunk if len(buf) > limit: raise too_large() return bytes(buf) class ImageChecker: def __init__(self, max_pixels: int, workers: int): self.max_pixels = max_pixels # Не больше N одновременных проверок на реплику: декодирование занимает CPU и память. self.slots = asyncio.Semaphore(workers) async def inspect(self, data: bytes, declared: str) -> tuple[str, int, int]: detected = next((t for t, sig in SIGNATURES.items() if data.startswith(sig)), None) if detected is None or detected != declared: raise unsupported() async with self.slots: return await asyncio.to_thread(self._inspect, data, detected) def _inspect(self, data: bytes, content_type: str) -> tuple[str, int, int]: with warnings.catch_warnings(): warnings.simplefilter('error', Image.DecompressionBombWarning) try: img = Image.open(io.BytesIO(data)) # ленивый: читает только заголовок width, height = img.size if img.format != PIL_FORMATS[content_type]: raise unsupported() except (Image.DecompressionBombError, Image.DecompressionBombWarning): raise too_large('Изображение превышает лимит пикселей') from None except ApiError: raise except Exception: raise unsupported() from None if width <= 0 or height <= 0: raise unsupported() if width * height > self.max_pixels: raise too_large('Изображение превышает лимит пикселей') try: if content_type == 'image/png': img.verify() # CRC и структура чанков без хранения пикселей check_png_pixel_stream(data) # объём пиксельных данных совпадает с IHDR else: img.draft('RGB', (max(1, width // 8), max(1, height // 8))) img.load() # обрезанный/битый JPEG -> исключение except Exception: raise unsupported() from None finally: img.close() return content_type, width, height # ---------- PNG: потоковая проверка пиксельных данных ---------- # verify() Pillow проверяет только CRC чанков. Файл с честным IHDR 6000x6000 и почти пустым IDAT он # пропустит. Полное декодирование 40 Мпикс заняло бы 160 MiB на запрос, поэтому IDAT распаковывается # потоково кусками по 64 KiB: считаются только байты, пиксели не хранятся. Распакованный объём должен # точно совпасть с вычисленным по IHDR, иначе файл повреждён (или это zip-бомба сверх заявленного). 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)) def _row_bytes(width: int, bits_per_pixel: int) -> int: return (width * bits_per_pixel + 7) // 8 def expected_png_raw_size(width: int, height: int, bit_depth: int, color_type: int, interlace: int) -> int: bpp = CHANNELS[color_type] * bit_depth if not interlace: return height * (1 + _row_bytes(width, bpp)) total = 0 for xs, ys, dx, dy in ADAM7: pw = (width - xs + dx - 1) // dx if width > xs else 0 ph = (height - ys + dy - 1) // dy if height > ys else 0 if pw and ph: total += ph * (1 + _row_bytes(pw, bpp)) return total def check_png_pixel_stream(data: bytes) -> None: import struct import zlib pos, expected, produced = 8, None, 0 inflater = zlib.decompressobj() while pos + 8 <= len(data): length, kind = struct.unpack('>I4s', data[pos:pos + 8]) body = data[pos + 8:pos + 8 + length] pos += 12 + length if kind == b'IHDR': width, height, bit_depth, color_type, _c, _f, interlace = struct.unpack('>IIBBBBB', body) expected = expected_png_raw_size(width, height, bit_depth, color_type, interlace) elif kind == b'IDAT': if expected is None: raise ValueError('IDAT before IHDR') chunk = body while chunk: out = inflater.decompress(chunk, 64 * 1024) produced += len(out) if produced > expected: raise ValueError('pixel data larger than IHDR') chunk = inflater.unconsumed_tail elif kind == b'IEND': break produced += len(inflater.flush()) if expected is None or produced != expected or not inflater.eof: raise ValueError('pixel data does not match IHDR')