"""Validate compressed image bytes without trusting filename or HTTP Content-Type.""" import os import threading import struct import zlib from PIL import Image, ImageFile, UnidentifiedImageError from .storage import MAX_IMAGE_PIXELS # Prevent unrestricted decompression of malicious image dimensions. Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS ImageFile.LOAD_TRUNCATED_IMAGES = False _IMAGE_LOCK = threading.BoundedSemaphore(1) class InvalidImage(Exception): pass class TooManyPixels(Exception): pass def validate_image_file(file, declared_type: str) -> None: expected = {"image/png": "PNG", "image/jpeg": "JPEG"}.get(declared_type) if not expected: raise InvalidImage("unsupported image type") with _IMAGE_LOCK: try: file.seek(0) with Image.open(file) as probe: if probe.format != expected: raise InvalidImage("image MIME does not match its content") width, height = probe.size if width <= 0 or height <= 0: raise InvalidImage("image dimensions are invalid") if width * height > MAX_IMAGE_PIXELS: raise TooManyPixels("image dimensions exceed limit") probe.verify() # verify compressed structure file.seek(0) with Image.open(file) as loaded: loaded.load() # detect damaged truncated payloads except Image.DecompressionBombError as e: raise TooManyPixels("image dimensions exceed limit") from e except Image.DecompressionBombWarning as e: raise TooManyPixels("image dimensions exceed limit") from e except (UnidentifiedImageError, OSError, ValueError, SyntaxError, EOFError, struct.error, zlib.error) as e: raise InvalidImage("invalid or truncated PNG/JPEG") from e finally: file.seek(0)