import struct import threading import unicodedata import zlib from PIL import Image, UnidentifiedImageError from src.errors import DomainError, invalid MAX_BYTES = 10 * 1024 * 1024 MAX_PIXELS = 40_000_000 Image.MAX_IMAGE_PIXELS = MAX_PIXELS DECODE_SLOT = threading.BoundedSemaphore(1) def filename(value): if ( not value or not 1 <= len(value) <= 255 or not value.strip() or any( c in "/\\" or unicodedata.category(c) in {"Cc", "Cs"} for c in value ) ): raise invalid() return value def verify(stream, *, declared): if declared not in {"image/png", "image/jpeg"}: raise DomainError( 415, "unsupported_media_type", "PNG or JPEG required" ) with DECODE_SLOT: try: stream.seek(0) with Image.open(stream, formats=["PNG", "JPEG"]) as image: actual = {"PNG": "image/png", "JPEG": "image/jpeg"}.get( image.format ) if actual != declared: raise DomainError( 415, "unsupported_media_type", "Image type mismatch" ) if image.width * image.height > MAX_PIXELS: raise DomainError( 413, "payload_too_large", "Pixel limit exceeded" ) image.verify() # JPEG verify alone does not decode entropy data. stream.seek(0) with Image.open(stream, formats=["PNG", "JPEG"]) as image: image.load() except Image.DecompressionBombError: raise DomainError( 413, "payload_too_large", "Pixel limit exceeded" ) from None except ( UnidentifiedImageError, OSError, ValueError, SyntaxError, struct.error, zlib.error, EOFError, ): raise DomainError( 415, "unsupported_media_type", "Invalid image" ) from None except MemoryError: raise DomainError( 503, "unavailable", "Image memory budget exceeded" ) from None finally: stream.seek(0) return declared