"""Short-lived bounded pixel validation; no DB, credentials or application imports.""" import json import resource import subprocess import sys from io import BytesIO from PIL import Image, UnidentifiedImageError from .domain import Failure MAX_BYTES = 10 * 1024 * 1024 MAX_PIXELS = 40_000_000 Image.MAX_IMAGE_PIXELS = MAX_PIXELS def inspect_image(fileobj, declared_type): if declared_type not in {"image/png", "image/jpeg"}: raise Failure(415, "Ожидается PNG или JPEG") try: fileobj.seek(0) with Image.open(fileobj) as header: width, height = header.size if width * height > MAX_PIXELS: raise Failure(413, "Слишком много пикселей") actual = {"PNG": "image/png", "JPEG": "image/jpeg"}.get(header.format) if actual != declared_type: raise Failure(415, "Формат изображения не соответствует MIME") frames = getattr(header, "n_frames", 1) default_image = bool(getattr(header, "default_image", False)) if width * height * frames > MAX_PIXELS: raise Failure(413, "Слишком много пикселей во всех кадрах") header.verify() # Drop parsed metadata before the separate strict decoder process starts. del header if actual == "image/png": # verify() checks CRC, but does not compare acTL's frame count with # every fcTL. Do not let a forged count hide a corrupt later frame. fileobj.seek(8) controls = frame_controls = 0 declared_frames = None animation_data = False while True: chunk_header = fileobj.read(8) if len(chunk_header) != 8: raise ValueError("Truncated PNG chunk") length = int.from_bytes(chunk_header[:4], "big") kind = chunk_header[4:] controls += kind == b"acTL" frame_controls += kind == b"fcTL" animation_data |= kind == b"fdAT" if kind == b"acTL": if length != 8: raise ValueError("Invalid acTL length") declared_frames = int.from_bytes(fileobj.read(4), "big") fileobj.seek(length, 1) # remaining payload plus CRC else: fileobj.seek(length + 4, 1) if kind == b"IEND": break if controls: if ( controls != 1 or not declared_frames or frame_controls != declared_frames or declared_frames + int(default_image) != frames ): raise ValueError("Invalid APNG frame count") elif frame_controls or animation_data: raise ValueError("Animation chunks without acTL") if actual == "image/jpeg": # Validate scan warnings before allocating Pillow's decoded canvas. # 384 MiB covers coefficient arrays for <=40M pixels and <=4 channels; # keeping both full decoded buffers alive could exceed the API cgroup. fileobj.seek(0) # A bounded compressed copy avoids sharing buffered file-descriptor # offsets with the child, and supports BytesIO callers as well. encoded = fileobj.read(MAX_BYTES + 1) if len(encoded) > MAX_BYTES: raise Failure(413, "Файл больше 10 MiB") try: decoded = subprocess.run( ["djpeg", "-strict", "-maxmemory", "384m", "-outfile", "/dev/null"], input=encoded, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, timeout=4, check=False, ) except subprocess.TimeoutExpired: raise Failure(415, "Изображение не прошло ограниченную проверку") from None finally: del encoded if decoded.returncode: raise Failure(415, "Повреждённое изображение") # djpeg has already decoded every JPEG pixel, streaming output rows. # A second Pillow load would overlap full progressive coefficient # arrays with a 160 MiB CMYK canvas and violate the API's 512 MiB cap. fileobj.seek(0) return actual, width, height # Decode one frame at a time. Pillow may retain a previous APNG canvas # for compositing, but no list/copies of every decoded frame is collected. fileobj.seek(0) with Image.open(fileobj) as image: decoded_pixels = 0 for frame in range(frames): if decoded_pixels + width * height > MAX_PIXELS: raise Failure(413, "Слишком много пикселей во всех кадрах") image.seek(frame) decoded_pixels += image.size[0] * image.size[1] if decoded_pixels > MAX_PIXELS: raise Failure(413, "Слишком много пикселей во всех кадрах") image.load() # Image's context manager closes its input handle, not the decoded core. # Releasing the object frees native canvases before hashing/S3 publication. del image fileobj.seek(0) return actual, width, height except Image.DecompressionBombError: raise Failure(413, "Слишком много пикселей") from None except (UnidentifiedImageError, OSError, ValueError, SyntaxError, EOFError): raise Failure(415, "Повреждённое изображение") from None def main(): resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) resource.setrlimit(resource.RLIMIT_CPU, (4, 5)) if sys.platform == "linux": resource.setrlimit(resource.RLIMIT_AS, (512 * 1024 * 1024, 512 * 1024 * 1024)) try: data = sys.stdin.buffer.read(MAX_BYTES + 1) if len(data) > MAX_BYTES: raise Failure(413, "Файл больше 10 MiB") result = inspect_image(BytesIO(data), sys.argv[1]) print(json.dumps({"ok": result})) except Failure as exc: print(json.dumps({"error": exc.status})) except MemoryError: print(json.dumps({"error": 415})) except Exception: print(json.dumps({"error": 415})) if __name__ == "__main__": main()