Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Fix image validation in ProductBulkCreate mutation (#18173)

Filip Owczarek8911bc276ad4
diff --git a/saleor/graphql/product/bulk_mutations/product_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
index ea5eebd7cc..8681d98176 100644
--- a/saleor/graphql/product/bulk_mutations/product_bulk_create.py
+++ b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
@@ -61,12 +61,14 @@ def get_results(instances_data_with_errors_list, reject_everything=False):
for data in instances_data_with_errors_list
]
return [
- ProductBulkResult(
- product=ChannelContext(node=data.get("instance"), channel_slug=None),
- errors=data.get("errors"),
+ (
+ ProductBulkResult(
+ product=ChannelContext(node=data.get("instance"), channel_slug=None),
+ errors=data.get("errors"),
+ )
+ if data.get("instance")
+ else ProductBulkResult(product=None, errors=data.get("errors"))
)
- if data.get("instance")
- else ProductBulkResult(product=None, errors=data.get("errors"))
for data in instances_data_with_errors_list
]
@@ -426,7 +428,7 @@ class ProductBulkCreate(BaseMutation):
return listings_to_create
@classmethod
- def clean_media(cls, media_inputs, product_index, index_error_map):
+ def clean_media(cls, info, media_inputs, product_index, index_error_map):
media_to_create = []
for index, media_input in enumerate(media_inputs):
@@ -464,6 +466,35 @@ class ProductBulkCreate(BaseMutation):
)
)
continue
+
+ if image:
+ media_input["image"] = info.context.FILES.get(image)
+ try:
+ media_input["image"] = clean_image_file(
+ media_input, "image", ProductBulkCreateErrorCode
+ )
+ except ValidationError as exc:
+ cls.add_indexes_to_errors(
+ product_index, exc, index_error_map, f"media.{index}"
+ )
+ continue
+ elif media_url and is_image_url(media_url):
+ try:
+ validate_image_url(
+ media_url, "media_url", ProductBulkCreateErrorCode.INVALID.value
+ )
+ except ValidationError as exc:
+ cls.add_indexes_to_errors(
+ product_index, exc, index_error_map, f"media.{index}"
+ )
+ continue
+ filename = get_filename_from_url(media_url)
+ image_data = HTTPClient.send_request(
+ "GET", media_url, stream=True, timeout=30, allow_redirects=False
+ )
+ image_data = File(image_data.raw, filename)
+ media_input["image"] = image_data
+
media_to_create.append(media_input)
return media_to_create
@@ -518,9 +549,11 @@ class ProductBulkCreate(BaseMutation):
for error in errors:
index_error_map[product_index].append(
ProductBulkCreateError(
- path=f"variants.{index}.{error.path}"
- if error.path
- else f"variants.{index}",
+ path=(
+ f"variants.{index}.{error.path}"
+ if error.path
+ else f"variants.{index}"
+ ),
message=error.message,
code=error.code,
attributes=error.attributes,
@@ -567,7 +600,7 @@ class ProductBulkCreate(BaseMutation):
if media_inputs := cleaned_input.get("media"):
cleaned_input["media"] = cls.clean_media(
- media_inputs, product_index, index_error_map
+ info, media_inputs, product_index, index_error_map
)
if listings_inputs := cleaned_input.get("channel_listings"):
@@ -850,37 +883,16 @@ class ProductBulkCreate(BaseMutation):
alt = media_input.get("alt", "")
media_url = media_input.get("media_url")
if img_data := media_input.get("image"):
- media_input["image"] = info.context.FILES.get(img_data)
- image_data = clean_image_file(
- media_input, "image", ProductBulkCreateErrorCode
- )
media_to_create.append(
models.ProductMedia(
- image=image_data,
+ image=img_data,
alt=alt,
product=product,
type=ProductMediaTypes.IMAGE,
)
)
if media_url:
- if is_image_url(media_url):
- validate_image_url(
- media_url, "media_url", ProductBulkCreateErrorCode.INVALID.value
- )
- filename = get_filename_from_url(media_url)
- image_data = HTTPClient.send_request(
- "GET", media_url, stream=True, timeout=30, allow_redirects=False
- )
- image_data = File(image_data.raw, filename)
- media_to_create.append(
- models.ProductMedia(
- image=image_data,
- alt=alt,
- product=product,
- type=ProductMediaTypes.IMAGE,
- )
- )
- else:
+ if not is_image_url(media_url):
oembed_data, media_type = get_oembed_data(media_url, "media_url")
media_to_create.append(
models.ProductMedia(
diff --git a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
index f817620c19..739d3e3c9e 100644
--- a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
@@ -1,10 +1,11 @@
import datetime
import json
import os
-from unittest.mock import patch
+from unittest.mock import Mock, patch
from uuid import uuid4
import graphene
+import PIL
import pytest
from .....attribute.tests.model_helpers import (
@@ -14,7 +15,11 @@ from .....attribute.tests.model_helpers import (
from .....discount.utils.promotion import get_active_catalogue_promotion_rules
from .....product.error_codes import ProductBulkCreateErrorCode
from .....product.models import Product
-from .....product.tests.utils import create_image
+from .....product.tests.utils import (
+ create_image,
+ create_image_without_extension,
+ create_zip_file_with_image_ext,
+)
from ....core.enums import ErrorPolicyEnum
from ....tests.utils import (
get_graphql_content,
@@ -710,6 +715,272 @@ def test_product_bulk_create_with_media(
assert file_3_name.endswith(format)
+def test_product_bulk_create_with_media_invalid_extension(
+ staff_api_client,
+ product_type,
+ category,
+ description_json,
+ permission_manage_products,
+ media_root,
+):
+ # given
+ description_json_string = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ product_name_2 = "test name 2"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ image_file_1, image_name_1 = create_image(image_name="prod1_img1")
+ image_file_2, image_name_2 = create_image(image_name="prod1_img2")
+ invalid_image_file, invalid_image_name = create_image_without_extension(
+ image_name="prod2_img1_invalid"
+ )
+
+ media_1 = {
+ "alt": "",
+ "image": image_name_1,
+ }
+
+ media_2 = {
+ "alt": "",
+ "image": image_name_2,
+ }
+
+ media_3 = {
+ "alt": "",
+ "image": invalid_image_name,
+ }
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "description": description_json_string,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ "media": [media_1, media_2],
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_2,
+ "slug": f"{base_product_slug}-2",
+ "description": description_json_string,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "media": [media_3],
+ },
+ ]
+
+ files = [image_file_1, image_file_2, invalid_image_file]
+
+ map_dict = {
+ 0: ["variables.products.0.media.0.image"],
+ 1: ["variables.products.0.media.1.image"],
+ 2: ["variables.products.1.media.0.image"],
+ }
+
+ # when
+ body = get_multipart_request_body_with_multiple_files(
+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}, files, map_dict
+ )
+
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_multipart(body)
+
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ assert data["count"] == 0
+ # Check in first product we have no errors
+ error_1 = data["results"][0]["errors"]
+ assert not error_1
+ # Check in second product we have error related to invalid image extension
+ error_2 = data["results"][1]["errors"]
+ assert error_2[0]["code"] == ProductBulkCreateErrorCode.INVALID.name
+ assert error_2[0]["path"] == "media.0.image"
+ assert error_2[0]["message"] == "Lack of file extension."
+ assert len(error_2) == 1
+
+
+def test_product_bulk_create_with_media_invalid_media_type(
+ staff_api_client,
+ product_type,
+ category,
+ description_json,
+ permission_manage_products,
+ media_root,
+):
+ # given
+ description_json_string = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ product_name_2 = "test name 2"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ image_file_1, image_name_1 = create_image(image_name="prod1_img1")
+ image_file_2, image_name_2 = create_image(image_name="prod1_img2")
+ invalid_image_file, invalid_image_name = create_zip_file_with_image_ext()
+
+ media_1 = {
+ "alt": "",
+ "image": image_name_1,
+ }
+
+ media_2 = {
+ "alt": "",
+ "image": image_name_2,
+ }
+
+ media_3 = {
+ "alt": "",
+ "image": invalid_image_name,
+ }
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "description": description_json_string,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ "media": [media_1, media_2],
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_2,
+ "slug": f"{base_product_slug}-2",
+ "description": description_json_string,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "media": [media_3],
+ },
+ ]
+
+ files = [image_file_1, image_file_2, invalid_image_file]
+
+ map_dict = {
+ 0: ["variables.products.0.media.0.image"],
+ 1: ["variables.products.0.media.1.image"],
+ 2: ["variables.products.1.media.0.image"],
+ }
+
+ # when
+ body = get_multipart_request_body_with_multiple_files(
+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}, files, map_dict
+ )
+
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_multipart(body)
+
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ assert data["count"] == 0
+ # Check in first product we have no errors
+ error_1 = data["results"][0]["errors"]
+ assert not error_1
+ # Check in second product we have error related to invalid image extension
+ error_2 = data["results"][1]["errors"]
+ assert error_2[0]["code"] == ProductBulkCreateErrorCode.INVALID.name
+ assert error_2[0]["path"] == "media.0.image"
+ assert error_2[0]["message"] == "Invalid file type."
+ assert len(error_2) == 1
+
+
+@patch("saleor.graphql.core.validators.file.Image.open")
+def test_product_bulk_create_with_media_image_with_invalid_exif(
+ mocked_image_open,
+ staff_api_client,
+ product_type,
+ category,
+ description_json,
+ permission_manage_products,
+ media_root,
+):
+ # given
+ description_json_string = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ image_file_1, image_name_1 = create_image(image_name="img_with_invalid_exif")
+
+ def open_image_side_effect(img_file, *args, **kwargs):
+ img = PIL.Image.open(img_file)
+ img.getexif = Mock(side_effect=PIL.UnidentifiedImageError)
+ return img
+
+ mocked_image_open.return_value = open_image_side_effect
+
+ media_1 = {
+ "alt": "",
+ "image": image_name_1,
+ }
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "description": description_json_string,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ "media": [media_1],
+ },
+ ]
+
+ files = [image_file_1]
+
+ map_dict = {
+ 0: ["variables.products.0.media.0.image"],
+ }
+
+ # when
+ body = get_multipart_request_body_with_multiple_files(
+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}, files, map_dict
+ )
+
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_multipart(body)
+
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ assert data["count"] == 0
+ error_1 = data["results"][0]["errors"]
+ assert error_1[0]["code"] == ProductBulkCreateErrorCode.INVALID.name
+ assert error_1[0]["path"] == "media.0.image"
+ assert error_1[0]["message"].startswith(
+ "Invalid file. The following error was raised during the attempt"
+ )
+ assert len(error_1) == 1
+
+
@pytest.mark.vcr
def test_product_bulk_create_with_media_with_media_url(
staff_api_client,
@@ -804,6 +1075,75 @@ def test_product_bulk_create_with_media_with_media_url(
)
+@patch(
+ "saleor.graphql.core.validators.file.is_supported_image_mimetype",
+ return_value=False,
+)
+@patch(
+ "saleor.graphql.core.validators.file.HTTPClient",
+)
+def test_product_bulk_create_with_media_with_media_url_invalid_image_type(
+ mocked_http_client,
+ mocked_is_supported_image_mimetype,
+ staff_api_client,
+ product_type,
+ category,
+ description_json,
+ permission_manage_products,
+ media_root,
+):
+ # given
+ description_json_string = json.dumps(description_json)
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ base_product_slug = "product-test-slug"
+ product_charge_taxes = True
+ product_tax_rate = "STANDARD"
+
+ alt = "Invalid_image"
+ url = "https://www.example.com/image.png"
+
+ media_1 = {
+ "alt": alt,
+ "mediaUrl": url,
+ }
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "description": description_json_string,
+ "chargeTaxes": product_charge_taxes,
+ "taxCode": product_tax_rate,
+ "weight": 2,
+ "media": [media_1],
+ },
+ ]
+
+ # when
+ body = get_multipart_request_body_with_multiple_files(
+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}, [], {}
+ )
+
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_multipart(body)
+
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ assert data["count"] == 0
+ error_1 = data["results"][0]["errors"]
+ assert error_1[0]["code"] == ProductBulkCreateErrorCode.INVALID.name
+ assert error_1[0]["path"] == "media.0.mediaUrl"
+ assert error_1[0]["message"] == "Invalid file type."
+ assert len(error_1) == 1
+
+
def test_product_bulk_create_with_attributes(
staff_api_client,
product_type,
diff --git a/saleor/product/tests/utils.py b/saleor/product/tests/utils.py
index 5d850d18f2..4f1b3a577b 100644
--- a/saleor/product/tests/utils.py
+++ b/saleor/product/tests/utils.py
@@ -12,6 +12,16 @@ def create_image(image_name="product2"):
return image, image_name
+def create_image_without_extension(image_name="product_img_without_extension"):
+ # Ensure the image_name does not have an extension
+ image_name = image_name.split(".")[0]
+ img_data = BytesIO()
+ image = Image.new("RGB", size=(1, 1))
+ image.save(img_data, format="JPEG")
+ img = SimpleUploadedFile(image_name, img_data.getvalue(), "image/jpeg")
+ return img, image_name
+
+
def create_zip_file_with_image_ext():
file_name = "product.jpg"
file_data = SimpleUploadedFile(file_name, b"product_data", "application/zip")