forked from mtusi2026/mtusi2026lab5
128 lines
5.5 KiB
Python
128 lines
5.5 KiB
Python
import asyncio
|
|
import struct
|
|
import warnings
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from typing import IO
|
|
|
|
from PIL import Image, UnidentifiedImageError
|
|
from starlette.requests import HTTPConnection
|
|
|
|
from domain import AttachmentContentType, InspectedImageSchema
|
|
from domain.errors import PayloadTooLargeError, UnsupportedMediaTypeError
|
|
|
|
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
|
JPEG_SIGNATURE = b"\xff\xd8\xff"
|
|
|
|
PILLOW_FORMATS = {
|
|
AttachmentContentType.PNG: "PNG",
|
|
AttachmentContentType.JPEG: "JPEG",
|
|
}
|
|
|
|
# Как Pillow сообщает о повреждённом или чужом содержимом
|
|
DECODE_ERRORS: tuple[type[Exception], ...] = (
|
|
UnidentifiedImageError,
|
|
OSError,
|
|
SyntaxError,
|
|
ValueError,
|
|
EOFError,
|
|
struct.error,
|
|
)
|
|
|
|
|
|
class ImageInspector:
|
|
"""
|
|
Проверка PNG/JPEG по содержимому, а не по Content-Type клиента.
|
|
|
|
1. Формат — по сигнатуре; несовпадение с заявленным Content-Type — 415.
|
|
2. Ширина и высота читаются из заголовка, лимит пикселей проверяется до
|
|
распаковки: 413 без выделения памяти под изображение.
|
|
3. Целостность: PNG — CRC каждого chunk и наличие IEND (verify, без
|
|
распаковки); JPEG — декодирование в draft-режиме libjpeg (масштаб 1/8).
|
|
|
|
Проверка идёт в отдельном пуле потоков: event loop не блокируется, а число
|
|
одновременных декодирований и их память ограничены workers. Худший случай —
|
|
progressive JPEG на пределе пикселей: libjpeg держит коэффициенты всего
|
|
изображения (до ~6 байт на пиксель) даже в draft-режиме.
|
|
"""
|
|
|
|
def __init__(self, workers: int, max_pixels: int) -> None:
|
|
self._max_pixels = max_pixels
|
|
# Вторая линия защиты Pillow: Image.open отказывает выше 2 * max_pixels.
|
|
# Предупреждение в диапазоне (max, 2 * max] не нужно: такой файл
|
|
# отклоняется явной проверкой ниже.
|
|
Image.MAX_IMAGE_PIXELS = max_pixels
|
|
warnings.simplefilter("ignore", Image.DecompressionBombWarning)
|
|
self._executor = ThreadPoolExecutor(
|
|
max_workers=workers, thread_name_prefix="image-inspect"
|
|
)
|
|
|
|
async def inspect(
|
|
self, file: IO[bytes], declared: AttachmentContentType
|
|
) -> InspectedImageSchema:
|
|
"""
|
|
Raises:
|
|
UnsupportedMediaTypeError: не PNG/JPEG, повреждено или подмена MIME
|
|
PayloadTooLargeError: пикселей больше лимита
|
|
"""
|
|
loop = asyncio.get_running_loop()
|
|
return await loop.run_in_executor(
|
|
self._executor, self._inspect, file, declared
|
|
)
|
|
|
|
def close(self) -> None:
|
|
self._executor.shutdown(wait=False, cancel_futures=True)
|
|
|
|
def _inspect(
|
|
self, file: IO[bytes], declared: AttachmentContentType
|
|
) -> InspectedImageSchema:
|
|
file.seek(0)
|
|
actual = self._sniff(file.read(len(PNG_SIGNATURE)))
|
|
if actual is None:
|
|
raise UnsupportedMediaTypeError(
|
|
"Содержимое не является изображением PNG или JPEG"
|
|
)
|
|
if actual is not declared:
|
|
raise UnsupportedMediaTypeError(
|
|
"Content-Type не соответствует содержимому файла"
|
|
)
|
|
file.seek(0)
|
|
try:
|
|
with Image.open(file, formats=[PILLOW_FORMATS[actual]]) as image:
|
|
width, height = image.size
|
|
if width * height > self._max_pixels:
|
|
raise PayloadTooLargeError(
|
|
f"Изображение больше {self._max_pixels} пикселей"
|
|
)
|
|
self._verify(image, actual)
|
|
except Image.DecompressionBombError:
|
|
raise PayloadTooLargeError(
|
|
f"Изображение больше {self._max_pixels} пикселей"
|
|
) from None
|
|
except DECODE_ERRORS:
|
|
raise UnsupportedMediaTypeError("Изображение повреждено") from None
|
|
return InspectedImageSchema(content_type=actual, width=width, height=height)
|
|
|
|
@staticmethod
|
|
def _sniff(header: bytes) -> AttachmentContentType | None:
|
|
if header.startswith(PNG_SIGNATURE):
|
|
return AttachmentContentType.PNG
|
|
if header.startswith(JPEG_SIGNATURE):
|
|
return AttachmentContentType.JPEG
|
|
return None
|
|
|
|
@staticmethod
|
|
def _verify(image: Image.Image, content_type: AttachmentContentType) -> None:
|
|
if content_type is AttachmentContentType.PNG:
|
|
image.verify()
|
|
return
|
|
# draft выбирает наименьший масштаб libjpeg (1/8): весь поток данных
|
|
# разбирается, но выходной буфер в 64 раза меньше полного
|
|
image.draft(image.mode, (1, 1))
|
|
image.load()
|
|
|
|
|
|
def get_image_inspector(connection: HTTPConnection) -> ImageInspector:
|
|
"""Получение проверки изображений, созданной в lifespan."""
|
|
inspector: ImageInspector = connection.app.state.image_inspector
|
|
return inspector
|