Исправить валидацию изображений и filename

This commit is contained in:
2026-11-18 17:50:48 +03:00
parent 38268f63f8
commit aa0c20c283
2 changed files with 25 additions and 4 deletions
+8 -1
View File
@@ -2,6 +2,7 @@
import io
from PIL import Image, UnidentifiedImageError
from PIL.Image import DecompressionBombError
CONTENT_TYPE_TO_PIL_FORMAT = {"image/png": "PNG", "image/jpeg": "JPEG"}
@@ -10,6 +11,10 @@ class InvalidImage(Exception):
pass
class ImageTooLarge(InvalidImage):
pass
def validate(data: bytes, declared_content_type: str, max_pixels: int) -> None:
"""Raise InvalidImage if the bytes are not a genuine, within-budget PNG/JPEG."""
expected_format = CONTENT_TYPE_TO_PIL_FORMAT.get(declared_content_type)
@@ -23,7 +28,9 @@ def validate(data: bytes, declared_content_type: str, max_pixels: int) -> None:
raise InvalidImage("declared content type does not match actual image format")
width, height = img.size
if width * height > max_pixels:
raise InvalidImage("image exceeds the decoded pixel budget")
raise ImageTooLarge("image exceeds the decoded pixel budget")
img.load() # forces full decode; raises on truncated/corrupted data
except DecompressionBombError as exc:
raise ImageTooLarge("image exceeds the decoded pixel budget") from exc
except (UnidentifiedImageError, OSError, ValueError) as exc:
raise InvalidImage(str(exc)) from exc