Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Handle invalid image MIME type during thumbnail generation (#15088)
Iga Karbowiakb76c72bf374e
diff --git a/saleor/graphql/core/tests/test_file_validation.py b/saleor/graphql/core/tests/test_file_validation.pyindex b2f95c66a0..cf80e6748e 100644--- a/saleor/graphql/core/tests/test_file_validation.py+++ b/saleor/graphql/core/tests/test_file_validation.py@@ -1,5 +1,5 @@from io import BytesIO-from unittest.mock import Mock+from unittest.mock import Mock, patchimport pytestfrom django.core.exceptions import ValidationError@@ -137,10 +137,9 @@ def test_clean_image_file():image.save(img_data, format="JPEG")field = "image"- # whenimg = SimpleUploadedFile("product.jpg", img_data.getvalue(), "image/jpeg")- # then+ # when & thenclean_image_file({field: img}, field, ProductErrorCode)@@ -268,3 +267,24 @@ def test_clean_image_file_exif_validation_raising_error(monkeypatch):# thenassert error_msg in exc.value.args[0][field].message+++@patch("saleor.thumbnail.utils.magic.from_buffer")+def test_clean_image_file_invalid_image_mime_type(from_buffer_mock):+ # given+ img_data = BytesIO()+ image = Image.new("RGB", size=(1, 1))+ image.save(img_data, format="WEBP")+ field = "image"++ invalid_mime_type = "application/x-empty"+ from_buffer_mock.return_value = invalid_mime_type+ img = SimpleUploadedFile("product.webp", img_data.getvalue(), "image/webp")++ # when+ with pytest.raises(ValidationError) as exc:+ clean_image_file({field: img}, field, ProductErrorCode)++ # then+ error_msg = f"Unsupported image MIME type: {invalid_mime_type}"+ assert error_msg in exc.value.args[0][field].messagediff --git a/saleor/graphql/core/validators/file.py b/saleor/graphql/core/validators/file.pyindex 318b65981c..0b536f9149 100644--- a/saleor/graphql/core/validators/file.py+++ b/saleor/graphql/core/validators/file.py@@ -6,6 +6,7 @@ from PIL import Image, UnidentifiedImageErrorfrom ....core.http_client import HTTPClientfrom ....thumbnail import MIME_TYPE_TO_PIL_IDENTIFIER+from ....thumbnail.utils import ProcessedImagefrom ..utils import add_hash_to_file_nameImage.init()@@ -76,6 +77,7 @@ def clean_image_file(cleaned_input, img_field_name, error_class):try:with Image.open(img_file) as image:_validate_image_exif(image, img_field_name, error_class)+ img_file.seek(0)except (SyntaxError, TypeError, UnidentifiedImageError) as e:raise ValidationError({@@ -87,6 +89,14 @@ def clean_image_file(cleaned_input, img_field_name, error_class):})+ try:+ # validate if the image MIME type is supported+ ProcessedImage.get_image_metadata_from_file(img_file)+ except ValueError as e:+ raise ValidationError(+ {img_field_name: ValidationError(str(e), code=error_class.INVALID.value)}+ )+add_hash_to_file_name(img_file)return img_filediff --git a/saleor/thumbnail/tests/test_views.py b/saleor/thumbnail/tests/test_views.pyindex 8a32caf60f..dce41b0671 100644--- a/saleor/thumbnail/tests/test_views.py+++ b/saleor/thumbnail/tests/test_views.py@@ -1,3 +1,5 @@+from unittest.mock import patch+import graphenefrom PIL import Image@@ -256,6 +258,27 @@ def test_handle_thumbnail_view_object_does_not_exists(client):assert response.status_code == 404+@patch("saleor.thumbnail.utils.magic.from_buffer")+def test_handle_thumbnail_view_invalid_image_mime_type(+ from_buffer_mock, client, category_with_image+):+ # given+ size = 60+ category_id = graphene.Node.to_global_id("Category", category_with_image.id)+ thumbnail_count = Thumbnail.objects.count()++ invalid_mime_type = "application/x-empty"+ from_buffer_mock.return_value = invalid_mime_type++ # when+ response = client.get(f"/thumbnail/{category_id}/{size}/")++ # then+ assert response.status_code == 400+ assert response.content.decode("utf-8") == "Invalid image."+ assert Thumbnail.objects.count() == thumbnail_count++def test_handle_icon_thumbnail_view_with_format(client, app, icon_image, media_root, settings):diff --git a/saleor/thumbnail/utils.py b/saleor/thumbnail/utils.pyindex e92a249b2c..adca9198be 100644--- a/saleor/thumbnail/utils.py+++ b/saleor/thumbnail/utils.py@@ -133,7 +133,8 @@ class ProcessedImage:image_format = self.get_image_metadata_from_file(image)return (Image.open(image), image_format)- def get_image_metadata_from_file(self, file_like):+ @classmethod+ def get_image_metadata_from_file(cls, file_like):"""Return a image format and InMemoryUploadedFile-friendly save format.Receive a valid image file and returns a 2-tuple of two strings:@@ -143,6 +144,8 @@ class ProcessedImage:"""mime_type = magic.from_buffer(file_like.read(1024), mime=True)file_like.seek(0)+ if mime_type not in MIME_TYPE_TO_PIL_IDENTIFIER:+ raise ValueError(f"Unsupported image MIME type: {mime_type}")image_format = MIME_TYPE_TO_PIL_IDENTIFIER[mime_type]return image_formatdiff --git a/saleor/thumbnail/views.py b/saleor/thumbnail/views.pyindex 67c10bc34f..8da346adec 100644--- a/saleor/thumbnail/views.py+++ b/saleor/thumbnail/views.py@@ -1,8 +1,13 @@+import loggingfrom collections import namedtuplefrom typing import Optionalfrom django.core.exceptions import ObjectDoesNotExist-from django.http import HttpResponseNotFound, HttpResponseRedirect+from django.http import (+ HttpResponseBadRequest,+ HttpResponseNotFound,+ HttpResponseRedirect,+)from graphql.error import GraphQLErrorfrom ..account.models import User@@ -20,6 +25,8 @@ from .utils import (prepare_thumbnail_file_name,)+logger = logging.getLogger(__name__)+ModelData = namedtuple("ModelData", ["model", "image_field", "thumbnail_field"])ICON_TYPE_TO_MODEL_DATA_MAPPING = {@@ -99,7 +106,11 @@ def handle_thumbnail()else:processed_image = ProcessedImage(image.name, size_px, format)- thumbnail_file, _ = processed_image.create_thumbnail()+ try:+ thumbnail_file, _ = processed_image.create_thumbnail()+ except ValueError as error:+ logger.info(str(error))+ return HttpResponseBadRequest("Invalid image.")thumbnail_file_name = prepare_thumbnail_file_name(image.name, size_px, format)