Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Limit the number of pixels of images we decode (#19678)
Lukasz Ostrowskiabfc51af0b27
diff --git a/saleor/core/apps.py b/saleor/core/apps.pyindex 0ab62118d1..7de4089ebb 100644--- a/saleor/core/apps.py+++ b/saleor/core/apps.py@@ -1,9 +1,11 @@+import warningsfrom collections.abc import Callablefrom django.apps import AppConfigfrom django.conf import settingsfrom django.db.models import CharField, TextFieldfrom django.utils.module_loading import import_string+from PIL import Imagefrom .db.filters import PostgresILike@@ -18,6 +20,24 @@ class CoreAppConfig(AppConfig):settings.SENTRY_INIT(settings.SENTRY_DSN, settings.SENTRY_OPTS)self.validate_jwt_manager()self.validate_advisory_lock_namespace_import()+ self.set_pillow_pixel_limit()++ @staticmethod+ def set_pillow_pixel_limit() -> None:+ """Apply `settings.MAX_IMAGE_PIXELS` to Pillow.++ Pillow warns above `Image.MAX_IMAGE_PIXELS` but only raises above *twice* that+ value, so halve our limit to make `MAX_IMAGE_PIXELS` the value actually+ enforced. Assigned once at app startup, so tests cannot override it via the+ `settings` fixture - patch `PIL.Image.MAX_IMAGE_PIXELS` directly instead.++ The halving puts Pillow's warning threshold at half of the enforced limit, so+ every legitimately large image would warn. The warning carries no reference to+ the object being processed, so it is useless for tracking; we log with context+ at the point we catch `DecompressionBombError` instead - hence the filter.+ """+ Image.MAX_IMAGE_PIXELS = settings.MAX_IMAGE_PIXELS // 2+ warnings.filterwarnings("ignore", category=Image.DecompressionBombWarning)def validate_jwt_manager(self) -> None:jwt_manager_path = getattr(settings, "JWT_MANAGER_PATH", None)diff --git a/saleor/graphql/core/tests/test_file_validation.py b/saleor/graphql/core/tests/test_file_validation.pyindex 3380991034..83d42e30f7 100644--- a/saleor/graphql/core/tests/test_file_validation.py+++ b/saleor/graphql/core/tests/test_file_validation.py@@ -1,7 +1,9 @@+import loggingfrom io import BytesIOfrom unittest.mock import Mock, patchimport pytest+from django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom django.core.files.uploadedfile import SimpleUploadedFilefrom django.test import override_settings@@ -85,6 +87,45 @@ def test_clean_image_file_file_size_within_limit():clean_image_file({field: img}, field, ProductErrorCode)+def test_clean_image_file_pixel_count_exceeds_limit(monkeypatch, caplog):+ # given+ # Pillow only raises above *twice* `MAX_IMAGE_PIXELS`, so 0 rejects any image and a+ # tiny image trips the same check a real oversized image would. The `settings`+ # fixture cannot be used here: `settings.MAX_IMAGE_PIXELS` is applied to+ # `PIL.Image.MAX_IMAGE_PIXELS` once at app startup.+ pillow_limit = 0+ monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", pillow_limit)+ caplog.set_level(logging.WARNING)+ file_name = "product.jpg"+ width, height = 1, 1+ img_data = BytesIO()+ image = Image.new("RGB", size=(width, height))+ image.save(img_data, format="JPEG")+ img = SimpleUploadedFile(file_name, img_data.getvalue(), "image/jpeg")+ field = "image"++ # when+ with pytest.raises(ValidationError) as exc:+ clean_image_file({field: img}, field, ProductErrorCode)++ # then+ pillow_error = (+ f"Image size ({width * height} pixels) exceeds limit of "+ f"{2 * pillow_limit} pixels, could be decompression bomb DOS attack."+ )+ assert exc.value.args[0][field].code == ProductErrorCode.FILE_SIZE_LIMIT_EXCEEDED+ # the Pillow message must not leak to the user; it is only logged+ assert exc.value.args[0][field].message == (+ "Image exceeds the maximum allowed number of pixels of "+ f"{settings.MAX_IMAGE_PIXELS}."+ )+ # the rejection must be traceable back to the file that caused it+ assert len(caplog.records) == 1+ assert caplog.records[0].levelno == logging.WARNING+ assert caplog.records[0].image_source == file_name+ assert caplog.records[0].pillow_error == pillow_error++def test_clean_image_file_invalid_content_type():# givenimg_data = BytesIO()diff --git a/saleor/graphql/core/validators/file.py b/saleor/graphql/core/validators/file.pyindex e79e6815dc..1b17555359 100644--- a/saleor/graphql/core/validators/file.py+++ b/saleor/graphql/core/validators/file.py@@ -132,6 +132,22 @@ def clean_image_file(cleaned_input, img_field_name, error_class):with Image.open(img_file) as image:_validate_image_exif(image, img_field_name, error_class)img_file.seek(0)+ except Image.DecompressionBombError as e:+ logger.warning(+ "Upload for file %s was blocked, it exceeds the pixel limit: %s",+ img_file.name,+ e,+ extra={"image_source": img_file.name, "pillow_error": str(e)},+ )+ raise ValidationError(+ {+ img_field_name: ValidationError(+ "Image exceeds the maximum allowed number of pixels of "+ f"{settings.MAX_IMAGE_PIXELS}.",+ code=error_class.FILE_SIZE_LIMIT_EXCEEDED,+ )+ }+ ) from eexcept (SyntaxError, TypeError, UnidentifiedImageError) as e:raise ValidationError({diff --git a/saleor/graphql/product/tests/mutations/test_product_media_create.py b/saleor/graphql/product/tests/mutations/test_product_media_create.pyindex 919143e956..7f37996e70 100644--- a/saleor/graphql/product/tests/mutations/test_product_media_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_media_create.py@@ -5,6 +5,7 @@ from unittest.mock import Mock, patchimport grapheneimport pytestfrom django.conf import settings+from PIL import Imagefrom requests import RequestExceptionfrom requests.exceptions import InvalidSchemafrom requests_hardened.ip_filter import InvalidIPAddress@@ -115,6 +116,40 @@ def test_product_media_create_mutation_file_size_exceeds_limit(assert product.media.count() == 0+def test_product_media_create_mutation_pixel_count_exceeds_limit(+ monkeypatch, staff_api_client, product, permission_manage_products, media_root+):+ # given+ # `settings.MAX_IMAGE_PIXELS` is applied to `PIL.Image.MAX_IMAGE_PIXELS` once at+ # app startup, so patch Pillow directly; 0 rejects any image.+ monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", 0)+ staff_api_client.user.user_permissions.add(permission_manage_products)+ image_file, image_name = create_image()+ variables = {+ "product": graphene.Node.to_global_id("Product", product.id),+ "alt": "",+ "image": image_name,+ }+ body = get_multipart_request_body(+ PRODUCT_MEDIA_CREATE_QUERY, variables, image_file, image_name+ )++ # when+ response = staff_api_client.post_multipart(body)+ content = get_graphql_content(response)++ # then+ errors = content["data"]["productMediaCreate"]["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "image"+ assert errors[0]["code"] == ProductErrorCode.FILE_SIZE_LIMIT_EXCEEDED.name+ assert errors[0]["message"] == (+ "Image exceeds the maximum allowed number of pixels of "+ f"{settings.MAX_IMAGE_PIXELS}."+ )+ assert product.media.exists() is False++def test_product_media_create_mutation_without_file(monkeypatch, staff_api_client, product, permission_manage_products, media_root):diff --git a/saleor/product/tasks.py b/saleor/product/tasks.pyindex 1cf54f0fa4..0f7c781b0c 100644--- a/saleor/product/tasks.py+++ b/saleor/product/tasks.py@@ -16,11 +16,13 @@ from ..core.db.connection import allow_writerfrom ..core.exceptions import PreorderAllocationErrorfrom ..core.http_client import HTTPClientfrom ..core.utils.events import call_event+from ..core.utils.url import sanitize_url_for_loggingfrom ..core.utils.validators import get_mime_typefrom ..discount import PromotionTypefrom ..discount.models import Promotion, PromotionRulefrom ..plugins.manager import get_plugins_managerfrom ..product import ProductMediaTypes+from ..thumbnail.exceptions import ImageTooLargeErrorfrom ..warehouse.management import deactivate_preorder_for_variantfrom ..webhook.event_types import WebhookEventAsyncTypefrom ..webhook.utils import get_webhooks_for_event@@ -450,5 +452,19 @@ def fetch_product_media_image_task(product_media_id: int):image = create_image(product_media, mime_type, response)validate_image_mime_type(image)- validate_image_exif(image)+ try:+ validate_image_exif(image)+ except ImageTooLargeError as error:+ logger.warning(+ "Image fetched for product media %s exceeds the pixel limit: %s",+ product_media.pk,+ sanitize_url_for_logging(product_media.external_url),+ extra={+ "image_source": sanitize_url_for_logging(product_media.external_url),+ "object_type": "ProductMedia",+ "object_pk": product_media.pk,+ "pillow_error": str(error),+ },+ )+ raiseupdate_product_media(product_media, image)diff --git a/saleor/product/tests/test_tasks.py b/saleor/product/tests/test_tasks.pyindex 2b1cc5851d..42912d164f 100644--- a/saleor/product/tests/test_tasks.py+++ b/saleor/product/tests/test_tasks.py@@ -13,6 +13,7 @@ from requests.exceptions import HTTPError, InvalidSchema, RequestExceptionfrom ...discount import PromotionType, RewardValueTypefrom ...discount.models import Promotion, PromotionRule+from ...thumbnail.exceptions import ImageTooLargeErrorfrom ..interface import VariantDiscountedPriceChangefrom ..models import (Product,@@ -462,6 +463,45 @@ def test_fetch_product_media_image_success(assert product_media.image+def test_fetch_product_media_image_pixel_count_exceeds_limit_sanitizes_url(+ product_media_image_not_yet_fetched,+ caplog,+):+ # given+ product_media = product_media_image_not_yet_fetched+ product_media.external_url = "https://username:[email protected]/image.jpg"+ product_media.save(update_fields=("external_url",))+ pillow_error = "Image exceeds the pixel limit."+ image_buffer = BytesIO()+ Image.new("RGB", (1, 1)).save(image_buffer, format="JPEG")+ image_bytes = image_buffer.getvalue()++ # when+ with (+ mock_http_response_for_product_task(+ status_code=200, content_type="image/jpeg", content=image_bytes+ ),+ patch(+ "saleor.product.tasks.validate_image_exif",+ side_effect=ImageTooLargeError(pillow_error),+ ),+ pytest.raises(ImageTooLargeError),+ ):+ fetch_product_media_image_task(product_media.pk)++ # then+ sanitized_url = "https://***:***@example.com/image.jpg"+ assert len(caplog.records) == 1+ assert caplog.records[0].getMessage() == (+ f"Image fetched for product media {product_media.pk} exceeds the pixel "+ f"limit: {sanitized_url}"+ )+ assert caplog.records[0].image_source == sanitized_url+ assert caplog.records[0].object_type == "ProductMedia"+ assert caplog.records[0].object_pk == product_media.pk+ assert caplog.records[0].pillow_error == pillow_error++def test_fetch_product_media_image_unsupported_image_content_type(product_media_image_not_yet_fetched,caplog,diff --git a/saleor/product/utils/tasks_utils.py b/saleor/product/utils/tasks_utils.pyindex 7eab20f092..1932f369af 100644--- a/saleor/product/utils/tasks_utils.py+++ b/saleor/product/utils/tasks_utils.py@@ -5,6 +5,7 @@ from requests.exceptions import HTTPErrorfrom ...core.utils import create_file_from_responsefrom ...core.utils.validators import is_valid_image_content_type+from ...thumbnail.exceptions import ImageTooLargeErrorfrom ...thumbnail.utils import ProcessedImage, get_filename_from_url@@ -42,6 +43,8 @@ def validate_image_exif(image: IO[bytes]):# Validate by getting exif.pil_image_obj = Image.open(image)pil_image_obj.getexif()+ except Image.DecompressionBombError as exc:+ raise ImageTooLargeError(exc) from excexcept (ValueError,TypeError,diff --git a/saleor/settings.py b/saleor/settings.pyindex 481fce096c..2d3081ee01 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -501,6 +501,13 @@ MAX_IMAGE_FILE_SIZE = int(os.environ.get("MAX_IMAGE_FILE_SIZE", 10 * 1024 * 1024)) # 10MB+# Maximum number of pixels (width * height) of an image we are willing to decode.+# This bounds decode memory, which `MAX_IMAGE_FILE_SIZE` does not: an 8000x8000 WebP+# is 0.11MB on disk but needs ~1GB of RAM to decode, because the encoded size says+# nothing about the decoded size. The default admits 5000x5000 with some headroom.+# Applied to Pillow in `CoreAppConfig.ready`.+MAX_IMAGE_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", 30_000_000))+TEST_RUNNER = "saleor.tests.runner.PytestTestRunner"diff --git a/saleor/tests/test_image_pixel_limit.py b/saleor/tests/test_image_pixel_limit.pynew file mode 100644index 0000000000..e4f1212bb9--- /dev/null+++ b/saleor/tests/test_image_pixel_limit.py@@ -0,0 +1,12 @@+from django.conf import settings+from PIL import Image+++def test_pillow_pixel_limit_enforces_max_image_pixels():+ """Pillow must reject exactly at `settings.MAX_IMAGE_PIXELS`.++ Pillow warns above `Image.MAX_IMAGE_PIXELS` but only raises above twice that value,+ so `CoreAppConfig.ready` halves the limit. Dropping the halving would silently+ double the number of pixels we are willing to decode.+ """+ assert Image.MAX_IMAGE_PIXELS == settings.MAX_IMAGE_PIXELS // 2diff --git a/saleor/thumbnail/exceptions.py b/saleor/thumbnail/exceptions.pynew file mode 100644index 0000000000..75caaac7da--- /dev/null+++ b/saleor/thumbnail/exceptions.py@@ -0,0 +1,7 @@+class ImageTooLargeError(ValueError):+ """Raised when an image has more pixels than we are willing to decode.++ Subclasses `ValueError` so that callers already handling unusable images - the+ thumbnail view and `fetch_product_media_image_task` - treat it as an expected+ failure without needing to know about it.+ """diff --git a/saleor/thumbnail/tests/test_views.py b/saleor/thumbnail/tests/test_views.pyindex 0057a8b821..a523d2afd4 100644--- a/saleor/thumbnail/tests/test_views.py+++ b/saleor/thumbnail/tests/test_views.py@@ -1,3 +1,4 @@+import loggingfrom unittest.mock import patchimport graphene@@ -600,3 +601,44 @@ def test_handle_original_image_for_product_media_image_type_with_external_url_bu# thenassert response.status_code == 503assert response["Retry-After"] == "60"+++def test_handle_thumbnail_view_image_exceeds_pixel_limit(+ client, category_with_image, monkeypatch, caplog+):+ # given+ # Pillow only raises above *twice* `MAX_IMAGE_PIXELS`, so 0 rejects any image and+ # the tiny fixture image trips the same check a real oversized image would. The+ # `settings` fixture cannot be used here: `settings.MAX_IMAGE_PIXELS` is applied to+ # `PIL.Image.MAX_IMAGE_PIXELS` once at app startup.+ image_name = category_with_image.background_image.name+ with Image.open(category_with_image.background_image) as stored_image:+ width, height = stored_image.size+ # patched only after reading the size above, which would otherwise be rejected too+ pillow_limit = 0+ monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", pillow_limit)+ caplog.set_level(logging.WARNING)+ size = 128+ category_id = graphene.Node.to_global_id("Category", category_with_image.pk)+ thumbnail_count = Thumbnail.objects.count()++ # when+ response = client.get(f"/thumbnail/{category_id}/{size}/")++ # then+ assert response.status_code == 400+ assert response.content == b"Image is too large."+ assert Thumbnail.objects.count() == thumbnail_count++ # the rejection must be traceable back to both the stored file and the object,+ # so an operator can find every affected row from the logs alone+ assert len(caplog.records) == 2+ decode_record, view_record = caplog.records+ assert decode_record.image_source == image_name+ assert decode_record.pillow_error == (+ f"Image size ({width * height} pixels) exceeds limit of "+ f"{2 * pillow_limit} pixels, could be decompression bomb DOS attack."+ )+ assert view_record.image_source == image_name+ assert view_record.object_type == "Category"+ assert view_record.object_pk == str(category_with_image.pk)diff --git a/saleor/thumbnail/utils.py b/saleor/thumbnail/utils.pyindex 32ab428681..d0954dcba4 100644--- a/saleor/thumbnail/utils.py+++ b/saleor/thumbnail/utils.py@@ -1,3 +1,4 @@+import loggingimport mimetypesimport osimport secrets@@ -21,10 +22,13 @@ from . import (IconThumbnailFormat,ThumbnailFormat,)+from .exceptions import ImageTooLargeErrorif TYPE_CHECKING:from .models import Thumbnail+logger = logging.getLogger(__name__)+def get_image_or_proxy_url(thumbnail: Optional["Thumbnail"],@@ -142,7 +146,25 @@ class ProcessedImage:if isinstance(self.image_source, str):image = self.storage.open(self.image_source, "rb")image_format = self.get_image_metadata_from_file(image)- return (Image.open(image), image_format)+ try:+ return (Image.open(image), image_format)+ except Image.DecompressionBombError as e:+ source = self.get_image_source_name()+ logger.warning(+ "Refusing to decode image %s, it exceeds the pixel limit: %s",+ source,+ e,+ extra={"image_source": source, "pillow_error": str(e)},+ )+ raise ImageTooLargeError(+ f"Image {source} exceeds the maximum allowed number of pixels: {e}"+ ) from e++ def get_image_source_name(self) -> str:+ """Return the storage path of the source image, for logging."""+ if isinstance(self.image_source, str):+ return self.image_source+ return getattr(self.image_source, "name", "") or ""@classmethoddef get_image_metadata_from_file(cls, file_like):diff --git a/saleor/thumbnail/validators.py b/saleor/thumbnail/validators.pyindex fa8791af81..b8b48b321e 100644--- a/saleor/thumbnail/validators.py+++ b/saleor/thumbnail/validators.py@@ -1,3 +1,4 @@+import loggingfrom collections.abc import Collectionfrom django.core.exceptions import ValidationError@@ -10,6 +11,8 @@ from . import (PIL_IDENTIFIER_TO_MIME_TYPE,)+logger = logging.getLogger(__name__)+def validate_image_format(img: Image.Image,@@ -57,11 +60,22 @@ def validate_icon_image(image_file, error_code: str):with Image.open(image_file) as image:validate_image_format(image, error_code, ICON_MIME_TYPES)validate_image_size(image, error_code, MIN_ICON_SIZE, square_required=True)+ except Image.DecompressionBombError as e:+ image_source = getattr(image_file, "name", "") or ""+ logger.warning(+ "Icon image %s exceeds the pixel limit: %s",+ image_source,+ e,+ extra={"image_source": image_source, "pillow_error": str(e)},+ )+ raise ValidationError(+ "Invalid file. The image exceeds the maximum allowed number of pixels",+ code=error_code,+ ) from eexcept (SyntaxError,TypeError,UnidentifiedImageError,- Image.DecompressionBombError,) as e:raise ValidationError("Invalid file. The following error was raised during the attempt "diff --git a/saleor/thumbnail/views.py b/saleor/thumbnail/views.pyindex 610f19265c..ae863bda23 100644--- a/saleor/thumbnail/views.py+++ b/saleor/thumbnail/views.py@@ -20,6 +20,7 @@ from ..plugins.manager import get_plugins_managerfrom ..product.models import Category, Collection, ProductMediafrom ..thumbnail.models import Thumbnailfrom . import ALLOWED_ICON_THUMBNAIL_FORMATS, ALLOWED_THUMBNAIL_FORMATS+from .exceptions import ImageTooLargeErrorfrom .utils import (ProcessedIconImage,ProcessedImage,@@ -127,6 +128,19 @@ def handle_thumbnail(request, instance_id: str, size: str, format: str | None =except FileNotFoundError as error:logger.info(str(error))return HttpResponseNotFound("Cannot found image file.")+ except ImageTooLargeError as error:+ # Logged at warning level rather than error: this view is unauthenticated, so+ # repeated requests for a known-oversized image are attacker-controlled volume.+ logger.warning(+ "Cannot create a thumbnail, image exceeds the pixel limit: %s",+ error,+ extra={+ "image_source": image.name,+ "object_type": object_type,+ "object_pk": pk,+ },+ )+ return HttpResponseBadRequest("Image is too large.")except ValueError as error:logger.info(str(error))return HttpResponseBadRequest("Invalid image.")