"""Content-based validation of uploaded PNG/JPEG images. The declared Content-Type is never trusted: the format is detected from the first bytes and must match it. Dimensions are read from the header and the pixel limit is applied BEFORE any decoding, so a small "pixel bomb" file cannot make the API allocate gigabytes. - PNG is validated by our own streaming reader: chunk lengths, CRC of every chunk, IHDR, and the IDAT zlib stream is decompressed in 64 KiB pieces that are counted and thrown away. Memory stays O(64 KiB) for any image. - JPEG: Pillow reads the header (lazy open); then the image is decoded with draft() at 1/8 scale, which makes libjpeg read the whole entropy-coded stream (a truncated/corrupted file raises) while allocating only 1/64 of the full-size pixel buffer. Large progressive JPEGs keep all DCT coefficients in memory even with draft(), so above PROGRESSIVE_DECODE_MAX_PIXELS only the marker structure is checked. The functions are synchronous (CPU work); call them via asyncio.to_thread. """ from __future__ import annotations import struct import zlib from dataclasses import dataclass from typing import BinaryIO from PIL import Image # Our own limit is applied before Pillow decodes anything. Image.MAX_IMAGE_PIXELS = None PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" JPEG_SIGNATURE = b"\xff\xd8\xff" CHUNK = 64 * 1024 PROGRESSIVE_DECODE_MAX_PIXELS = 16_000_000 class InvalidImage(Exception): """Not a PNG/JPEG, a corrupted file or a Content-Type mismatch (-> 415).""" class TooManyPixels(Exception): """Decoded image would exceed MAX_IMAGE_PIXELS (-> 413).""" @dataclass(frozen=True) class ImageInfo: content_type: str width: int height: int def sniff_content_type(head: bytes) -> str | None: if head.startswith(PNG_SIGNATURE): return "image/png" if head.startswith(JPEG_SIGNATURE): return "image/jpeg" return None def validate_image( file: BinaryIO, declared_content_type: str, max_pixels: int, ) -> ImageInfo: file.seek(0) detected = sniff_content_type(file.read(len(PNG_SIGNATURE))) file.seek(0) if detected is None: raise InvalidImage("Content is not a PNG or JPEG image.") if detected != declared_content_type: raise InvalidImage("Content-Type does not match the image content.") if detected == "image/png": width, height = _validate_png(file, max_pixels) else: width, height = _validate_jpeg(file, max_pixels) return ImageInfo(detected, width, height) # --- PNG ------------------------------------------------------------------- # color type -> (channels, allowed bit depths) _PNG_COLOR_TYPES = { 0: (1, {1, 2, 4, 8, 16}), 2: (3, {8, 16}), 3: (1, {1, 2, 4, 8}), 4: (2, {8, 16}), 6: (4, {8, 16}), } _ADAM7_PASSES = ( (0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2), ) def _read_exact(file: BinaryIO, size: int) -> bytes: data = file.read(size) if len(data) != size: raise InvalidImage("Image file is truncated.") return data def _png_raw_size(width: int, height: int, bits_per_pixel: int, interlace: int) -> int: """Size of the decompressed IDAT stream: filter byte + packed row bytes.""" def scanlines(w: int, h: int) -> int: if w == 0 or h == 0: return 0 return h * (1 + (w * bits_per_pixel + 7) // 8) if interlace == 0: return scanlines(width, height) total = 0 for x0, y0, dx, dy in _ADAM7_PASSES: pass_width = (width - x0 + dx - 1) // dx if width > x0 else 0 pass_height = (height - y0 + dy - 1) // dy if height > y0 else 0 total += scanlines(pass_width, pass_height) return total def _validate_png(file: BinaryIO, max_pixels: int) -> tuple[int, int]: _read_exact(file, len(PNG_SIGNATURE)) width = height = 0 expected_raw = 0 produced_raw = 0 inflater = zlib.decompressobj() color_type = -1 seen_plte = False idat_state = "before" # before -> inside -> after first = True while True: header = _read_exact(file, 8) length, chunk_type = struct.unpack(">I4s", header) if length > 0x7FFFFFFF: raise InvalidImage("Invalid PNG chunk length.") if first and chunk_type != b"IHDR": raise InvalidImage("PNG must start with IHDR.") crc = zlib.crc32(chunk_type) is_idat = chunk_type == b"IDAT" if is_idat: if idat_state == "after": raise InvalidImage("PNG IDAT chunks are not consecutive.") if color_type == 3 and not seen_plte: raise InvalidImage("PNG palette image without PLTE.") idat_state = "inside" elif idat_state == "inside": idat_state = "after" data = b"" remaining = length while remaining: piece = _read_exact(file, min(CHUNK, remaining)) remaining -= len(piece) crc = zlib.crc32(piece, crc) if is_idat: produced_raw += _inflate_counting( inflater, piece, expected_raw - produced_raw ) elif chunk_type == b"IHDR": data += piece (stored_crc,) = struct.unpack(">I", _read_exact(file, 4)) if stored_crc != crc: raise InvalidImage("PNG chunk CRC mismatch.") if first: first = False if length != 13: raise InvalidImage("Invalid PNG IHDR.") (width, height, bit_depth, color_type, compression, filter_method, interlace) = struct.unpack(">IIBBBBB", data) if width == 0 or height == 0 or width > 0x7FFFFFFF or height > 0x7FFFFFFF: raise InvalidImage("Invalid PNG dimensions.") if width * height > max_pixels: # Before a single IDAT byte is decompressed. raise TooManyPixels() if color_type not in _PNG_COLOR_TYPES: raise InvalidImage("Invalid PNG color type.") channels, depths = _PNG_COLOR_TYPES[color_type] if bit_depth not in depths or compression != 0 or filter_method != 0 \ or interlace not in (0, 1): raise InvalidImage("Invalid PNG IHDR.") expected_raw = _png_raw_size(width, height, channels * bit_depth, interlace) elif chunk_type == b"PLTE": seen_plte = True elif chunk_type == b"IEND": break if idat_state == "before": raise InvalidImage("PNG has no image data.") produced_raw += len(inflater.flush()) if not inflater.eof or produced_raw != expected_raw: raise InvalidImage("PNG image data is corrupted or truncated.") return width, height def _inflate_counting(inflater, data: bytes, allowed: int) -> int: """Decompress and discard; return the number of produced bytes.""" produced = 0 try: while data: if inflater.eof: raise InvalidImage("PNG has data after the end of the zlib stream.") out = inflater.decompress(data, CHUNK) produced += len(out) if produced > allowed: raise InvalidImage("PNG image data is larger than IHDR declares.") data = inflater.unconsumed_tail except zlib.error: raise InvalidImage("PNG image data is corrupted.") from None return produced # --- JPEG ------------------------------------------------------------------ def _validate_jpeg(file: BinaryIO, max_pixels: int) -> tuple[int, int]: try: with Image.open(file, formats=["JPEG"]) as image: width, height = image.size if width < 1 or height < 1: raise InvalidImage("Invalid JPEG dimensions.") if width * height > max_pixels: # Header only: no pixel has been decoded yet. raise TooManyPixels() progressive = bool( image.info.get("progressive") or image.info.get("progression") ) if progressive and width * height > PROGRESSIVE_DECODE_MAX_PIXELS: _check_jpeg_end(file) else: image.draft("RGB", (max(1, width // 8), max(1, height // 8))) image.load() except (InvalidImage, TooManyPixels): raise except Exception: # Pillow raises OSError/SyntaxError/ValueError/... for broken data. raise InvalidImage("JPEG image is corrupted or truncated.") from None return width, height def _check_jpeg_end(file: BinaryIO) -> None: file.seek(0, 2) size = file.tell() file.seek(max(0, size - 2)) if file.read(2) != b"\xff\xd9": raise InvalidImage("JPEG image is truncated.")