Files
mtusi2026lab4/app/images.py
T

93 lines
3.8 KiB
Python

"""Bounded PNG/JPEG checks. Pixel count is taken from headers before bitmap decode."""
from PIL import Image, ImageFile, UnidentifiedImageError
from app.errors import ApiError
ImageFile.LOAD_TRUNCATED_IMAGES = False
_PNG = b"\x89PNG\r\n\x1a\n"
_JPEG_SOF = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}
def _png_size(path: str) -> tuple[int, int] | None:
with open(path, "rb") as handle:
if handle.read(8) != _PNG:
return None
length = handle.read(4)
kind = handle.read(4)
if kind != b"IHDR" or len(length) != 4 or int.from_bytes(length, "big") < 13:
return None
header = handle.read(8)
if len(header) != 8:
return None
width = int.from_bytes(header[0:4], "big")
height = int.from_bytes(header[4:8], "big")
return width, height
def _jpeg_size(path: str) -> tuple[int, int] | None:
with open(path, "rb") as handle:
if handle.read(2) != b"\xff\xd8":
return None
while True:
marker_byte = handle.read(1)
if marker_byte != b"\xff":
return None
while marker_byte == b"\xff":
marker_byte = handle.read(1)
if not marker_byte:
return None
marker = marker_byte[0]
if marker in {0xD8, 0xD9, 0x01} or 0xD0 <= marker <= 0xD7:
continue
length_bytes = handle.read(2)
if len(length_bytes) != 2:
return None
length = int.from_bytes(length_bytes, "big")
if length < 2:
return None
if marker in _JPEG_SOF:
payload = handle.read(length - 2)
if len(payload) < 5:
return None
height = int.from_bytes(payload[1:3], "big")
width = int.from_bytes(payload[3:5], "big")
return width, height
handle.seek(length - 2, 1)
def _detect(path: str) -> str | None:
with open(path, "rb") as handle:
header = handle.read(12)
if header.startswith(_PNG):
return "image/png"
if header.startswith(b"\xff\xd8\xff"):
return "image/jpeg"
return None
def validate_image(path: str, declared: str, max_pixels: int, full_decode_pixels: int) -> None:
detected = _detect(path)
if detected is None or detected != declared:
raise ApiError(415, "unsupported_media_type", "Файл не является PNG или JPEG заявленного типа")
size = _png_size(path) if detected == "image/png" else _jpeg_size(path)
if size is None:
raise ApiError(415, "unsupported_media_type", "Не удалось прочитать размеры изображения")
width, height = size
if width <= 0 or height <= 0:
raise ApiError(415, "unsupported_media_type", "Некорректные размеры изображения")
if width > max_pixels or height > max_pixels or width * height > max_pixels:
raise ApiError(413, "payload_too_large", "Изображение превышает лимит пикселей")
Image.MAX_IMAGE_PIXELS = max_pixels
try:
with Image.open(path) as image:
image.verify()
if width * height <= full_decode_pixels:
with Image.open(path) as image:
image.load()
except Image.DecompressionBombError as exc:
raise ApiError(413, "payload_too_large", "Изображение превышает лимит пикселей") from exc
except (UnidentifiedImageError, OSError, SyntaxError, ValueError) as exc:
raise ApiError(415, "unsupported_media_type", "Повреждённое или неподдерживаемое изображение") from exc