"""Bounded image validation: magic+full decode, no trust in declared MIME.""" import io from PIL import Image, ImageFile, UnidentifiedImageError from .domain import ApiError MAX_BYTES = 10 * 1024 * 1024 MAX_PIXELS = 40_000_000 Image.MAX_IMAGE_PIXELS = MAX_PIXELS ImageFile.LOAD_TRUNCATED_IMAGES = False def validate_image(data, declared_type): if declared_type not in ('image/png', 'image/jpeg'): raise ApiError(415, 'unsupported_media_type', 'PNG or JPEG required') if len(data) > MAX_BYTES: raise ApiError(413, 'payload_too_large', 'Image exceeds 10 MiB') if not data: raise ApiError(415, 'unsupported_media_type', 'Empty image') try: with Image.open(io.BytesIO(data)) as im: real_type = {'PNG': 'image/png', 'JPEG': 'image/jpeg'}.get(im.format) if real_type is None or real_type != declared_type: raise ApiError(415, 'unsupported_media_type', 'Image content type mismatch') if im.width * im.height > MAX_PIXELS: raise ApiError(413, 'payload_too_large', 'Image pixel limit exceeded') im.load() # reject malformed/truncated payload before PUT except (UnidentifiedImageError, OSError, ValueError, SyntaxError): raise ApiError(415, 'unsupported_media_type', 'Invalid image') from None except Image.DecompressionBombError: raise ApiError(413, 'payload_too_large', 'Image pixel limit exceeded') from None