Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add exif image validation (#11224)
Iga Karbowiak2ab04a7d0e83
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1a88e41bc5..e94f31921e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -31,6 +31,10 @@ All notable, unreleased changes to this project will be documented in this file.- Re-enable 5 minute database connection persistence by default - #11074 + #11100 by @NyanKiyoshi<br/>Set `DB_CONN_MAX_AGE=0` to disable this behavior (adds overhead to requests)- Bump cryptography to 38.0.3: use OpenSSL 3.0.7 - #11126 by @NyanKiyoshi+- Add `attribute` field to `AttributeValueTranslatableContent` type. #11028 by @zedzior+- Add exif image validation - #11224 by @IKarbowiak++...# 3.8.0diff --git a/saleor/graphql/account/mutations/staff.py b/saleor/graphql/account/mutations/staff.pyindex dd3ece924e..e0a397739c 100644--- a/saleor/graphql/account/mutations/staff.py+++ b/saleor/graphql/account/mutations/staff.py@@ -26,7 +26,7 @@ from ...account.types import Address, AddressInput, Userfrom ...app.dataloaders import load_appfrom ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ...core.types import AccountError, NonNullList, StaffError, Upload-from ...core.utils import add_hash_to_file_name, validate_image_file+from ...core.validators.file import clean_image_filefrom ...plugins.dataloaders import load_plugin_managerfrom ...utils.validators import check_for_duplicatesfrom ..utils import (@@ -647,11 +647,10 @@ class UserAvatarUpdate(BaseMutation):permissions = (AuthorizationFilters.AUTHENTICATED_STAFF_USER,)@classmethod- def perform_mutation(cls, _root, info, image):+ def perform_mutation(cls, _root, info, **data):user = info.context.user- image_data = info.context.FILES.get(image)- validate_image_file(image_data, "image", AccountErrorCode)- add_hash_to_file_name(image_data)+ data["image"] = info.context.FILES.get(data["image"])+ image_data = clean_image_file(data, "image", AccountErrorCode)if user.avatar:user.avatar.delete()thumbnail_models.Thumbnail.objects.filter(user_id=user.id).delete()diff --git a/saleor/graphql/attribute/mutations/mixins.py b/saleor/graphql/attribute/mutations/mixins.pyindex 499d618d51..fc70f02e77 100644--- a/saleor/graphql/attribute/mutations/mixins.py+++ b/saleor/graphql/attribute/mutations/mixins.py@@ -5,7 +5,7 @@ from text_unidecode import unidecodefrom ....attribute import ATTRIBUTE_PROPERTIES_CONFIGURATION, AttributeInputTypefrom ....attribute import models as modelsfrom ....attribute.error_codes import AttributeErrorCode-from ...core.utils import validate_slug_and_generate_if_needed+from ...core.validators import validate_slug_and_generate_if_neededclass AttributeMixin:diff --git a/saleor/graphql/core/tests/test_core.py b/saleor/graphql/core/tests/test_core.pyindex 929cd41282..d6ed222369 100644--- a/saleor/graphql/core/tests/test_core.py+++ b/saleor/graphql/core/tests/test_core.py@@ -1,22 +1,18 @@import enumimport os-from io import BytesIO-from unittest.mock import Mock, patch+from unittest.mock import patchimport django_filtersimport grapheneimport pytestfrom django.core.exceptions import ImproperlyConfigured, ValidationError-from django.core.files.uploadedfile import SimpleUploadedFilefrom django.utils import timezonefrom graphene import InputFieldfrom micawber import ProviderException, ProviderRegistry-from PIL import Imagefrom ....core.utils.validators import get_oembed_datafrom ....product import ProductMediaTypes-from ....product.error_codes import ProductErrorCode-from ....product.models import Category, Product, ProductChannelListing+from ....product.models import Product, ProductChannelListingfrom ...tests.utils import get_graphql_content, get_graphql_content_from_responsefrom ...utils import requestor_is_superuserfrom ...utils.filters import filter_range_field, reporting_period_to_date@@ -24,30 +20,10 @@ from ..enums import ReportingPeriodfrom ..filters import EnumFilterfrom ..mutations import BaseMutationfrom ..types import FilterInputObjectType-from ..utils import (- add_hash_to_file_name,- clean_seo_fields,- get_duplicated_values,- get_filename_from_url,- is_image_mimetype,- is_supported_image_mimetype,- snake_to_camel_case,- validate_image_file,- validate_image_url,- validate_slug_and_generate_if_needed,-)+from ..utils import add_hash_to_file_name, get_duplicated_values, snake_to_camel_casefrom . import ErrorTest-def test_clean_seo_fields():- title = "lady title"- description = "fantasy description"- data = {"seo": {"title": title, "description": description}}- clean_seo_fields(data)- assert data["seo_title"] == title- assert data["seo_description"] == description--def test_user_error_field_name_for_related_object(staff_api_client, permission_manage_products):@@ -205,267 +181,6 @@ def test_mutation_invalid_permission_in_meta(_mocked, should_fail, permissions_v_run_test()- "cleaned_input",- [- {"slug": None, "name": "test"},- {"slug": "", "name": "test"},- {"slug": ""},- {"slug": None},- ],-)-def test_validate_slug_and_generate_if_needed_raises_errors(category, cleaned_input):- with pytest.raises(ValidationError):- validate_slug_and_generate_if_needed(category, "name", cleaned_input)--- "cleaned_input", [{"slug": "test-slug"}, {"slug": "test-slug", "name": "test"}]-)-def test_validate_slug_and_generate_if_needed_not_raises_errors(- category, cleaned_input-):- validate_slug_and_generate_if_needed(category, "name", cleaned_input)--- "cleaned_input",- [- {"slug": None, "name": "test"},- {"slug": "", "name": "test"},- {"slug": ""},- {"slug": None},- {"slug": "test-slug"},- {"slug": "test-slug", "name": "test"},- ],-)-def test_validate_slug_and_generate_if_needed_generate_slug(cleaned_input):- category = Category(name="test")- validate_slug_and_generate_if_needed(category, "name", cleaned_input)---def test_validate_image_file():- # given- img_data = BytesIO()- image = Image.new("RGB", size=(1, 1))- image.save(img_data, format="JPEG")- field = "image"-- # when- img = SimpleUploadedFile("product.jpg", img_data.getvalue(), "image/jpeg")-- # then- validate_image_file(img, field, ProductErrorCode)---def test_validate_image_file_invalid_content_type():- # given- img_data = BytesIO()- image = Image.new("RGB", size=(1, 1))- image.save(img_data, format="JPEG")- img = SimpleUploadedFile("product.jpg", img_data.getvalue(), "text/plain")- field = "image"-- # when- with pytest.raises(ValidationError) as exc:- validate_image_file(img, field, ProductErrorCode)-- # then- assert exc.value.args[0][field].message == "Invalid file type."---def test_validate_image_file_no_file():- # given- field = "image"-- # when- with pytest.raises(ValidationError) as exc:- validate_image_file(None, field, ProductErrorCode)-- # then- assert exc.value.args[0][field].message == "File is required."---def test_validate_image_file_no_file_extension():- # given- img_data = BytesIO()- image = Image.new("RGB", size=(1, 1))- image.save(img_data, format="JPEG")- img = SimpleUploadedFile("product", img_data.getvalue(), "image/jpeg")- field = "image"-- # when- with pytest.raises(ValidationError) as exc:- validate_image_file(img, field, ProductErrorCode)-- # then- assert exc.value.args[0][field].message == "Lack of file extension."---def test_validate_image_file_invalid_file_extension():- # given- img_data = BytesIO()- image = Image.new("RGB", size=(1, 1))- image.save(img_data, format="JPEG")- img = SimpleUploadedFile("product.txt", img_data.getvalue(), "image/jpeg")- field = "image"-- # when- with pytest.raises(ValidationError) as exc:- validate_image_file(img, field, ProductErrorCode)-- # then- assert (- exc.value.args[0][field].message- == "Invalid file extension. Image file required."- )---def test_validate_image_file_file_extension_not_supported_by_thumbnails():- # given- img_data = BytesIO()- image = Image.new("RGB", size=(1, 1))- image.save(img_data, format="JPEG")- img = SimpleUploadedFile("product.pxr", img_data.getvalue(), "image/jpeg")- field = "image"-- # when- with pytest.raises(ValidationError) as exc:- validate_image_file(img, field, ProductErrorCode)-- # then- assert (- exc.value.args[0][field].message- == "Invalid file extension. Image file required."- )---def test_get_filename_from_url_unique():- # given- file_format = "jpg"- file_name = "lenna"- url = f"http://example.com/{file_name}.{file_format}"-- # when- result = get_filename_from_url(url)-- # then- assert result.startswith(file_name)- assert result.endswith(file_format)- assert result != f"{file_name}.{file_format}"---def test_is_image_mimetype_valid_mimetype():- # given- valid_mimetype = "image/jpeg"-- # when- result = is_image_mimetype(valid_mimetype)-- # then- assert result---def test_is_image_mimetype_invalid_mimetype():- # given- invalid_mimetype = "application/javascript"-- # when- result = is_image_mimetype(invalid_mimetype)-- # then- assert not result---def test_is_supported_image_mimetype_valid_mimetype():- # given- valid_mimetype = "image/jpeg"-- # when- result = is_supported_image_mimetype(valid_mimetype)-- # then- assert result---def test_is_supported_image_mimetype_invalid_mimetype():- # given- invalid_mimetype = "application/javascript"-- # when- result = is_supported_image_mimetype(invalid_mimetype)-- # then- assert not result---def test_validate_image_url_valid_image_response(monkeypatch):- # given- valid_image_response_mock = Mock()- valid_image_response_mock.headers = {"content-type": "image/jpeg"}- monkeypatch.setattr(- "saleor.graphql.core.utils.requests.head",- Mock(return_value=valid_image_response_mock),- )- field = "image"-- # when- dummy_url = "http://example.com/valid_url.jpg"-- # then- validate_image_url(- dummy_url,- field,- ProductErrorCode.INVALID.value,- )---def test_validate_image_url_invalid_mimetype_response(monkeypatch):- # given- invalid_response_mock = Mock()- invalid_response_mock.headers = {"content-type": "application/json"}- monkeypatch.setattr(- "saleor.graphql.core.utils.requests.head",- Mock(return_value=invalid_response_mock),- )- field = "image"- dummy_url = "http://example.com/invalid_url.json"-- # when- with pytest.raises(ValidationError) as exc:- validate_image_url(- dummy_url,- field,- ProductErrorCode.INVALID.value,- )-- # then- assert exc.value.args[0][field].message == "Invalid file type."---def test_validate_image_url_response_without_content_headers(monkeypatch):- # given- invalid_response_mock = Mock()- invalid_response_mock.headers = {}- monkeypatch.setattr(- "saleor.graphql.core.utils.requests.head",- Mock(return_value=invalid_response_mock),- )- field = "image"- dummy_url = "http://example.com/broken_url"-- # when- with pytest.raises(ValidationError) as exc:- validate_image_url(- dummy_url,- field,- ProductErrorCode.INVALID.value,- )-- # then- assert exc.value.args[0][field].message == "Invalid file type."--@pytest.mark.parametrize("value, count, product_indexes",[diff --git a/saleor/graphql/core/tests/test_file_upload.py b/saleor/graphql/core/tests/test_file_upload.pyindex b669d5d47b..620d267b87 100644--- a/saleor/graphql/core/tests/test_file_upload.py+++ b/saleor/graphql/core/tests/test_file_upload.py@@ -42,7 +42,7 @@ def test_file_upload_by_staff(staff_api_client, site_settings, media_root):errors = data["errors"]assert not errors- assert data["uploadedFile"]["contentType"] == "image/png"+ assert data["uploadedFile"]["contentType"] == "image/jpeg"file_name, format = os.path.splitext(image_file._name)returned_url = data["uploadedFile"]["url"]file_path = urlparse(returned_url).path@@ -83,7 +83,7 @@ def test_file_upload_by_app(app_api_client, media_root):errors = data["errors"]assert not errors- assert data["uploadedFile"]["contentType"] == "image/png"+ assert data["uploadedFile"]["contentType"] == "image/jpeg"file_name, format = os.path.splitext(image_file._name)returned_url = data["uploadedFile"]["url"]file_path = urlparse(returned_url).path@@ -109,7 +109,7 @@ def test_file_upload_by_superuser(superuser_api_client, media_root):errors = data["errors"]assert not errors- assert data["uploadedFile"]["contentType"] == "image/png"+ assert data["uploadedFile"]["contentType"] == "image/jpeg"file_name, format = os.path.splitext(image_file._name)returned_url = data["uploadedFile"]["url"]file_path = urlparse(returned_url).path@@ -148,7 +148,7 @@ def test_file_upload_file_with_the_same_name_already_exists(domain = site_settings.site.domainassert not errors- assert data["uploadedFile"]["contentType"] == "image/png"+ assert data["uploadedFile"]["contentType"] == "image/jpeg"file_url = data["uploadedFile"]["url"]assert file_url != f"http://{domain}/media/{image_file._name}"assert file_url != f"http://{domain}/media/{path}"@@ -172,7 +172,7 @@ def test_file_upload_file_name_with_space(staff_api_client, media_root):errors = data["errors"]assert not errors- assert data["uploadedFile"]["contentType"] == "image/png"+ assert data["uploadedFile"]["contentType"] == "image/jpeg"file_name, format = os.path.splitext(image_file._name)file_name = file_name.replace(" ", "_")returned_url = data["uploadedFile"]["url"]@@ -199,7 +199,7 @@ def test_file_upload_file_name_with_encoded_value(staff_api_client, media_root):errors = data["errors"]assert not errors- assert data["uploadedFile"]["contentType"] == "image/png"+ assert data["uploadedFile"]["contentType"] == "image/jpeg"file_name, format = os.path.splitext(image_file._name)returned_url = data["uploadedFile"]["url"]file_path = urlparse(returned_url).pathdiff --git a/saleor/graphql/core/tests/test_file_validation.py b/saleor/graphql/core/tests/test_file_validation.pynew file mode 100644index 0000000000..541398952d--- /dev/null+++ b/saleor/graphql/core/tests/test_file_validation.py@@ -0,0 +1,282 @@+from io import BytesIO+from unittest.mock import Mock++import pytest+from django.core.exceptions import ValidationError+from django.core.files.uploadedfile import SimpleUploadedFile+from PIL import Image++from ....product.error_codes import ProductErrorCode+from ..validators.file import (+ clean_image_file,+ get_filename_from_url,+ is_image_mimetype,+ is_supported_image_mimetype,+ validate_image_url,+)+++def test_get_filename_from_url_unique():+ # given+ file_format = "jpg"+ file_name = "lenna"+ url = f"http://example.com/{file_name}.{file_format}"++ # when+ result = get_filename_from_url(url)++ # then+ assert result.startswith(file_name)+ assert result.endswith(file_format)+ assert result != f"{file_name}.{file_format}"+++def test_is_image_mimetype_valid_mimetype():+ # given+ valid_mimetype = "image/jpeg"++ # when+ result = is_image_mimetype(valid_mimetype)++ # then+ assert result+++def test_is_image_mimetype_invalid_mimetype():+ # given+ invalid_mimetype = "application/javascript"++ # when+ result = is_image_mimetype(invalid_mimetype)++ # then+ assert not result+++def test_is_supported_image_mimetype_valid_mimetype():+ # given+ valid_mimetype = "image/jpeg"++ # when+ result = is_supported_image_mimetype(valid_mimetype)++ # then+ assert result+++def test_is_supported_image_mimetype_invalid_mimetype():+ # given+ invalid_mimetype = "application/javascript"++ # when+ result = is_supported_image_mimetype(invalid_mimetype)++ # then+ assert not result+++def test_validate_image_url_valid_image_response(monkeypatch):+ # given+ valid_image_response_mock = Mock()+ valid_image_response_mock.headers = {"content-type": "image/jpeg"}+ monkeypatch.setattr(+ "saleor.graphql.core.validators.file.requests.head",+ Mock(return_value=valid_image_response_mock),+ )+ field = "image"++ # when+ dummy_url = "http://example.com/valid_url.jpg"++ # then+ validate_image_url(+ dummy_url,+ field,+ ProductErrorCode.INVALID.value,+ )+++def test_validate_image_url_invalid_mimetype_response(monkeypatch):+ # given+ invalid_response_mock = Mock()+ invalid_response_mock.headers = {"content-type": "application/json"}+ monkeypatch.setattr(+ "saleor.graphql.core.validators.file.requests.head",+ Mock(return_value=invalid_response_mock),+ )+ field = "image"+ dummy_url = "http://example.com/invalid_url.json"++ # when+ with pytest.raises(ValidationError) as exc:+ validate_image_url(+ dummy_url,+ field,+ ProductErrorCode.INVALID.value,+ )++ # then+ assert exc.value.args[0][field].message == "Invalid file type."+++def test_validate_image_url_response_without_content_headers(monkeypatch):+ # given+ invalid_response_mock = Mock()+ invalid_response_mock.headers = {}+ monkeypatch.setattr(+ "saleor.graphql.core.validators.file.requests.head",+ Mock(return_value=invalid_response_mock),+ )+ field = "image"+ dummy_url = "http://example.com/broken_url"++ # when+ with pytest.raises(ValidationError) as exc:+ validate_image_url(+ dummy_url,+ field,+ ProductErrorCode.INVALID.value,+ )++ # then+ assert exc.value.args[0][field].message == "Invalid file type."+++def test_clean_image_file():+ # given+ img_data = BytesIO()+ image = Image.new("RGB", size=(1, 1))+ image.save(img_data, format="JPEG")+ field = "image"++ # when+ img = SimpleUploadedFile("product.jpg", img_data.getvalue(), "image/jpeg")++ # then+ clean_image_file({field: img}, field, ProductErrorCode)+++def test_clean_image_file_invalid_content_type():+ # given+ img_data = BytesIO()+ image = Image.new("RGB", size=(1, 1))+ image.save(img_data, format="JPEG")+ img = SimpleUploadedFile("product.jpg", img_data.getvalue(), "text/plain")+ field = "image"++ # when+ with pytest.raises(ValidationError) as exc:+ clean_image_file({field: img}, field, ProductErrorCode)++ # then+ assert exc.value.args[0][field].message == "Invalid file type."+++def test_clean_image_file_no_file():+ # given+ field = "image"++ # when+ with pytest.raises(ValidationError) as exc:+ clean_image_file({field: None}, field, ProductErrorCode)++ # then+ assert exc.value.args[0][field].message == "File is required."+++def test_clean_image_file_no_file_extension():+ # given+ img_data = BytesIO()+ image = Image.new("RGB", size=(1, 1))+ image.save(img_data, format="JPEG")+ img = SimpleUploadedFile("product", img_data.getvalue(), "image/jpeg")+ field = "image"++ # when+ with pytest.raises(ValidationError) as exc:+ clean_image_file({field: img}, field, ProductErrorCode)++ # then+ assert exc.value.args[0][field].message == "Lack of file extension."+++def test_clean_image_file_invalid_file_extension():+ # given+ img_data = BytesIO()+ image = Image.new("RGB", size=(1, 1))+ image.save(img_data, format="JPEG")+ img = SimpleUploadedFile("product.txt", img_data.getvalue(), "image/jpeg")+ field = "image"++ # when+ with pytest.raises(ValidationError) as exc:+ clean_image_file({field: img}, field, ProductErrorCode)++ # then+ assert (+ exc.value.args[0][field].message+ == "Invalid file extension. Image file required."+ )+++def test_clean_image_file_file_extension_not_supported_by_thumbnails():+ # given+ img_data = BytesIO()+ image = Image.new("RGB", size=(1, 1))+ image.save(img_data, format="JPEG")+ img = SimpleUploadedFile("product.pxr", img_data.getvalue(), "image/jpeg")+ field = "image"++ # when+ with pytest.raises(ValidationError) as exc:+ clean_image_file({field: img}, field, ProductErrorCode)++ # then+ assert (+ exc.value.args[0][field].message+ == "Invalid file extension. Image file required."+ )+++def test_clean_image_file_issue_with_file_opening(monkeypatch):+ # given+ img_data = BytesIO()+ image = Image.new("RGB", size=(1, 1))+ image.save(img_data, format="JPEG")+ field = "image"++ error_msg = "Test syntax error"+ image_file_mock = Mock(side_effect=SyntaxError(error_msg))+ monkeypatch.setattr(+ "saleor.graphql.core.validators.file.Image.open", image_file_mock+ )+ img = SimpleUploadedFile("product.jpg", img_data.getvalue(), "image/jpeg")++ # when+ with pytest.raises(ValidationError) as exc:+ clean_image_file({field: img}, field, ProductErrorCode)++ # then+ assert error_msg in exc.value.args[0][field].message+++def test_clean_image_file_exif_validation_raising_error(monkeypatch):+ # given+ img_data = BytesIO()+ image = Image.new("RGB", size=(1, 1))+ image.save(img_data, format="JPEG")+ field = "image"++ error_msg = "Test syntax error"+ image_file_mock = Mock(side_effect=SyntaxError(error_msg))+ monkeypatch.setattr(+ "saleor.graphql.core.validators.file._validate_image_exif", image_file_mock+ )+ img = SimpleUploadedFile("product.jpg", img_data.getvalue(), "image/jpeg")++ # when+ with pytest.raises(ValidationError) as exc:+ clean_image_file({field: img}, field, ProductErrorCode)++ # then+ assert error_msg in exc.value.args[0][field].messagediff --git a/saleor/graphql/core/tests/test_validators.py b/saleor/graphql/core/tests/test_validators.pyindex 91b55ae1b5..c57ef55606 100644--- a/saleor/graphql/core/tests/test_validators.py+++ b/saleor/graphql/core/tests/test_validators.py@@ -6,10 +6,13 @@ from django.core.exceptions import ValidationErrorfrom django.utils import timezonefrom graphql.error import GraphQLError+from ....product.models import Categoryfrom ..validators import (+ clean_seo_fields,validate_end_is_after_start,validate_one_of_args_is_in_query,validate_price_precision,+ validate_slug_and_generate_if_needed,)@@ -87,3 +90,76 @@ def test_validate_one_of_args_is_in_query_single_arg_absent():with pytest.raises(GraphQLError) as error:validate_one_of_args_is_in_query("arg1", None) is Noneassert error.value.message == "At least one of arguments is required: 'arg1'."+++def test_clean_seo_fields():+ title = "lady title"+ description = "fantasy description"+ data = {"seo": {"title": title, "description": description}}+ clean_seo_fields(data)+ assert data["seo_title"] == title+ assert data["seo_description"] == description+++ "cleaned_input",+ [+ {"slug": None, "name": "test"},+ {"slug": "", "name": "test"},+ {"slug": ""},+ {"slug": None},+ ],+)+def test_validate_slug_and_generate_if_needed_raises_errors(category, cleaned_input):+ with pytest.raises(ValidationError):+ validate_slug_and_generate_if_needed(category, "name", cleaned_input)+++ "cleaned_input", [{"slug": "test-slug"}, {"slug": "test-slug", "name": "test"}]+)+def test_validate_slug_and_generate_if_needed_not_raises_errors(+ category, cleaned_input+):+ validate_slug_and_generate_if_needed(category, "name", cleaned_input)+++ "cleaned_input",+ [+ {"slug": None, "name": "test"},+ {"slug": "", "name": "test"},+ ],+)+def test_validate_slug_and_generate_if_needed_generate_slug(cleaned_input):+ # given+ category = Category(name="test")+ previous_slug_value = cleaned_input["slug"]++ # when+ validate_slug_and_generate_if_needed(category, "name", cleaned_input)++ # then+ assert previous_slug_value != cleaned_input["slug"]+ assert cleaned_input["slug"] == cleaned_input["name"]+++ "cleaned_input",+ [+ {"slug": ""},+ {"slug": None},+ {"slug": "test-slug"},+ {"slug": "test-slug", "name": "test"},+ ],+)+def test_validate_slug_and_generate_if_needed_slug_not_changed(cleaned_input):+ # given+ category = Category(name="test")+ previous_slug_value = cleaned_input["slug"]++ # when+ validate_slug_and_generate_if_needed(category, "name", cleaned_input)++ # then+ assert cleaned_input["slug"] == previous_slug_valuediff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.pyindex 0ab5bded5e..1a85ff6478 100644--- a/saleor/graphql/core/utils/__init__.py+++ b/saleor/graphql/core/utils/__init__.py@@ -1,34 +1,14 @@import binascii-import mimetypesimport osimport secrets-from typing import TYPE_CHECKING, Union-from uuid import UUID+from typing import Unionimport graphene-import requests-from django.core.exceptions import ValidationErrorfrom graphene import ObjectTypefrom graphql.error import GraphQLError-from PIL import Image-from ....core.utils import generate_unique_slugfrom ....plugins.webhook.utils import APP_ID_PREFIX-from ....thumbnail import MIME_TYPE_TO_PIL_IDENTIFIER--if TYPE_CHECKING:- from django.db.models import Model---Image.init()---def clean_seo_fields(data):- """Extract and assign seo fields to given dictionary."""- seo_fields = data.pop("seo", None)- if seo_fields:- data["seo_title"] = seo_fields.get("title")- data["seo_description"] = seo_fields.get("description")+from ..validators import validate_if_int_or_uuiddef snake_to_camel_case(name):@@ -44,136 +24,6 @@ def str_to_enum(name):return name.replace(" ", "_").replace("-", "_").upper()-def is_image_mimetype(mimetype: str) -> bool:- """Check if mimetype is image."""- if mimetype is None:- return False- return mimetype.startswith("image/")---def is_supported_image_mimetype(mimetype: str) -> bool:- """Check if mimetype is a mimetype that thumbnails support."""- if mimetype is None:- return False- return mimetype in MIME_TYPE_TO_PIL_IDENTIFIER.keys()---def is_image_url(url: str) -> bool:- """Check if file URL seems to be an image."""- if url.endswith(".webp"):- # webp is not recognized by mimetypes as image- # https://bugs.python.org/issue38902- return True- filetype = mimetypes.guess_type(url)[0]- return filetype is not None and is_image_mimetype(filetype)---def validate_image_url(url: str, field_name: str, error_code: str) -> None:- """Check if remote file has content type of image.-- Instead of the whole file, only the headers are fetched.- """- head = requests.head(url)- header = head.headers- content_type = header.get("content-type")- if content_type is None or not is_supported_image_mimetype(content_type):- raise ValidationError(- {field_name: ValidationError("Invalid file type.", code=error_code)}- )---def get_filename_from_url(url: str) -> str:- """Prepare unique filename for file from URL to avoid overwritting."""- file_name = os.path.basename(url)- name, format = os.path.splitext(file_name)- hash = secrets.token_hex(nbytes=4)- return f"{name}_{hash}{format}"---def validate_image_file(file, field_name, error_class) -> None:- """Validate if the file is an image supported by thumbnails."""- if not file:- raise ValidationError(- {- field_name: ValidationError(- "File is required.", code=error_class.REQUIRED- )- }- )- if not is_supported_image_mimetype(file.content_type):- raise ValidationError(- {- field_name: ValidationError(- "Invalid file type.", code=error_class.INVALID- )- }- )- _validate_image_format(file, field_name, error_class)---def _validate_image_format(file, field_name, error_class):- """Validate image file format."""- allowed_extensions = get_allowed_extensions()- _file_name, format = os.path.splitext(file._name)- if not format:- raise ValidationError(- {- field_name: ValidationError(- "Lack of file extension.", code=error_class.INVALID- )- }- )- elif format not in allowed_extensions:- raise ValidationError(- {- field_name: ValidationError(- "Invalid file extension. Image file required.",- code=error_class.INVALID,- )- }- )---def get_allowed_extensions():- """Return image extension lists that are supported by thumbnails."""- return [- ext.lower()- for ext, file_type in Image.EXTENSION.items()- if file_type.upper() in MIME_TYPE_TO_PIL_IDENTIFIER.values()- ]---def validate_slug_and_generate_if_needed(- instance: "Model",- slugable_field: str,- cleaned_input: dict,- slug_field_name: str = "slug",-) -> dict:- """Validate slug from input and generate in create mutation if is not given."""-- # update mutation - just check if slug value is not empty- # _state.adding is True only when it's new not saved instance.- if not instance._state.adding: # type: ignore- validate_slug_value(cleaned_input)- return cleaned_input-- # create mutation - generate slug if slug value is empty- slug = cleaned_input.get(slug_field_name)- if not slug and slugable_field in cleaned_input:- slug = generate_unique_slug(instance, cleaned_input[slugable_field])- cleaned_input[slug_field_name] = slug- return cleaned_input---def validate_slug_value(cleaned_input, slug_field_name: str = "slug"):- if slug_field_name in cleaned_input:- slug = cleaned_input[slug_field_name]- if not slug:- raise ValidationError(- f"{slug_field_name.capitalize()} value cannot be blank."- )--def get_duplicates_items(first_list, second_list):"""Return items that appear on both provided lists."""if first_list and second_list:@@ -186,29 +36,6 @@ def get_duplicated_values(values):return {value for value in values if values.count(value) > 1}-def validate_required_string_field(cleaned_input, field_name: str):- """Strip and validate field value."""- field_value = cleaned_input.get(field_name)- field_value = field_value.strip() if field_value else ""- if field_value:- cleaned_input[field_name] = field_value- else:- raise ValidationError(f"{field_name.capitalize()} is required.")- return cleaned_input---def validate_if_int_or_uuid(id):- result = True- try:- int(id)- except ValueError:- try:- UUID(id)- except (AttributeError, ValueError):- result = False- return result--def from_global_id_or_error(global_id: str,only_type: Union[ObjectType, str, None] = None,diff --git a/saleor/graphql/core/validators/__init__.py b/saleor/graphql/core/validators/__init__.pyindex 35df7454dc..92a6704506 100644--- a/saleor/graphql/core/validators/__init__.py+++ b/saleor/graphql/core/validators/__init__.py@@ -1,15 +1,19 @@from typing import TYPE_CHECKING, Optional+from uuid import UUIDimport graphenefrom django.core.exceptions import ValidationErrorfrom django_prices.utils.formatting import get_currency_fractionfrom graphql.error import GraphQLError+from ....core.utils import generate_unique_slugfrom ....product.models import ProductVariantChannelListingif TYPE_CHECKING:from decimal import Decimal+ from django.db.models import Model+def validate_one_of_args_is_in_mutation(error_class, *args):try:@@ -102,3 +106,65 @@ def validate_end_is_after_start(start_date, end_date):if start_date > end_date:raise ValidationError("End date cannot be before the start date.")+++def validate_slug_and_generate_if_needed(+ instance: "Model",+ slugable_field: str,+ cleaned_input: dict,+ slug_field_name: str = "slug",+) -> dict:+ """Validate slug from input and generate in create mutation if is not given."""++ # update mutation - just check if slug value is not empty+ # _state.adding is True only when it's new not saved instance.+ if not instance._state.adding: # type: ignore+ validate_slug_value(cleaned_input)+ return cleaned_input++ # create mutation - generate slug if slug value is empty+ slug = cleaned_input.get(slug_field_name)+ if not slug and slugable_field in cleaned_input:+ slug = generate_unique_slug(instance, cleaned_input[slugable_field])+ cleaned_input[slug_field_name] = slug+ return cleaned_input+++def validate_slug_value(cleaned_input, slug_field_name: str = "slug"):+ if slug_field_name in cleaned_input:+ slug = cleaned_input[slug_field_name]+ if not slug:+ raise ValidationError(+ f"{slug_field_name.capitalize()} value cannot be blank."+ )+++def clean_seo_fields(data):+ """Extract and assign seo fields to given dictionary."""+ seo_fields = data.pop("seo", None)+ if seo_fields:+ data["seo_title"] = seo_fields.get("title")+ data["seo_description"] = seo_fields.get("description")+++def validate_required_string_field(cleaned_input, field_name: str):+ """Strip and validate field value."""+ field_value = cleaned_input.get(field_name)+ field_value = field_value.strip() if field_value else ""+ if field_value:+ cleaned_input[field_name] = field_value+ else:+ raise ValidationError(f"{field_name.capitalize()} is required.")+ return cleaned_input+++def validate_if_int_or_uuid(id):+ result = True+ try:+ int(id)+ except ValueError:+ try:+ UUID(id)+ except (AttributeError, ValueError):+ result = False+ return resultdiff --git a/saleor/graphql/core/validators/file.py b/saleor/graphql/core/validators/file.pynew file mode 100644index 0000000000..741af02ddb--- /dev/null+++ b/saleor/graphql/core/validators/file.py@@ -0,0 +1,147 @@+import mimetypes+import os+import secrets++import requests+from django.core.exceptions import ValidationError+from PIL import Image, UnidentifiedImageError++from ....thumbnail import MIME_TYPE_TO_PIL_IDENTIFIER+from ..utils import add_hash_to_file_name++Image.init()+++def is_image_mimetype(mimetype: str) -> bool:+ """Check if mimetype is image."""+ if mimetype is None:+ return False+ return mimetype.startswith("image/")+++def is_supported_image_mimetype(mimetype: str) -> bool:+ """Check if mimetype is a mimetype that thumbnails support."""+ if mimetype is None:+ return False+ return mimetype in MIME_TYPE_TO_PIL_IDENTIFIER.keys()+++def is_image_url(url: str) -> bool:+ """Check if file URL seems to be an image."""+ if url.endswith(".webp"):+ # webp is not recognized by mimetypes as image+ # https://bugs.python.org/issue38902+ return True+ filetype = mimetypes.guess_type(url)[0]+ return filetype is not None and is_image_mimetype(filetype)+++def validate_image_url(url: str, field_name: str, error_code: str) -> None:+ """Check if remote file has content type of image.++ Instead of the whole file, only the headers are fetched.+ """+ head = requests.head(url)+ header = head.headers+ content_type = header.get("content-type")+ if content_type is None or not is_supported_image_mimetype(content_type):+ raise ValidationError(+ {field_name: ValidationError("Invalid file type.", code=error_code)}+ )+++def get_filename_from_url(url: str) -> str:+ """Prepare unique filename for file from URL to avoid overwritting."""+ file_name = os.path.basename(url)+ name, format = os.path.splitext(file_name)+ hash = secrets.token_hex(nbytes=4)+ return f"{name}_{hash}{format}"+++def clean_image_file(cleaned_input, img_field_name, error_class):+ """Extract and clean uploaded image file.++ Validate if the file is an image supported by thumbnails.+ """+ img_file = cleaned_input.get(img_field_name)+ if not img_file:+ raise ValidationError(+ {+ img_field_name: ValidationError(+ "File is required.", code=error_class.REQUIRED+ )+ }+ )+ if not is_supported_image_mimetype(img_file.content_type):+ raise ValidationError(+ {+ img_field_name: ValidationError(+ "Invalid file type.", code=error_class.INVALID+ )+ }+ )++ _validate_image_format(img_file, img_field_name, error_class)+ try:+ with Image.open(img_file) as image:+ _validate_image_exif(image, img_field_name, error_class)+ except (SyntaxError, TypeError, UnidentifiedImageError) as e:+ raise ValidationError(+ {+ img_field_name: ValidationError(+ "Invalid file. The following error was raised during the attempt "+ f"of opening the file: {str(e)}",+ code=error_class.INVALID.value,+ )+ }+ )++ add_hash_to_file_name(img_file)+ return img_file+++def _validate_image_format(file, field_name, error_class):+ """Validate image file format."""+ allowed_extensions = _get_allowed_extensions()+ _file_name, format = os.path.splitext(file._name)+ if not format:+ raise ValidationError(+ {+ field_name: ValidationError(+ "Lack of file extension.", code=error_class.INVALID+ )+ }+ )+ elif format not in allowed_extensions:+ raise ValidationError(+ {+ field_name: ValidationError(+ "Invalid file extension. Image file required.",+ code=error_class.INVALID,+ )+ }+ )+++def _get_allowed_extensions():+ """Return image extension lists that are supported by thumbnails."""+ return [+ ext.lower()+ for ext, file_type in Image.EXTENSION.items()+ if file_type.upper() in MIME_TYPE_TO_PIL_IDENTIFIER.values()+ ]+++def _validate_image_exif(img, field_name, error_class):+ try:+ img.getexif()+ except (SyntaxError, TypeError, UnidentifiedImageError) as e:+ raise ValidationError(+ {+ field_name: ValidationError(+ "Invalid file. The following error was raised during the attempt "+ f"of getting the exchangeable image file data: {str(e)}.",+ code=error_class.INVALID.value,+ )+ }+ )diff --git a/saleor/graphql/giftcard/mutations.py b/saleor/graphql/giftcard/mutations.pyindex 1183ee978b..015074664f 100644--- a/saleor/graphql/giftcard/mutations.py+++ b/saleor/graphql/giftcard/mutations.py@@ -23,8 +23,7 @@ from ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_INPUT, PREVIEW_FEAfrom ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ..core.scalars import PositiveDecimalfrom ..core.types import GiftCardError, NonNullList, PriceInput-from ..core.utils import validate_required_string_field-from ..core.validators import validate_price_precision+from ..core.validators import validate_price_precision, validate_required_string_fieldfrom ..plugins.dataloaders import load_plugin_managerfrom ..utils.validators import check_for_duplicatesfrom .types import GiftCard, GiftCardEventdiff --git a/saleor/graphql/menu/mutations.py b/saleor/graphql/menu/mutations.pyindex 7a32a39762..f81933984e 100644--- a/saleor/graphql/menu/mutations.py+++ b/saleor/graphql/menu/mutations.py@@ -14,8 +14,8 @@ from ...product import models as product_modelsfrom ..channel import ChannelContextfrom ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ..core.types import MenuError, NonNullList-from ..core.utils import validate_slug_and_generate_if_neededfrom ..core.utils.reordering import perform_reordering+from ..core.validators import validate_slug_and_generate_if_neededfrom ..page.types import Pagefrom ..plugins.dataloaders import load_plugin_managerfrom ..product.types import Category, Collectiondiff --git a/saleor/graphql/order/mutations/order_add_note.py b/saleor/graphql/order/mutations/order_add_note.pyindex 56b1516117..7e4963fd26 100644--- a/saleor/graphql/order/mutations/order_add_note.py+++ b/saleor/graphql/order/mutations/order_add_note.py@@ -8,7 +8,7 @@ from ....order.error_codes import OrderErrorCodefrom ...app.dataloaders import load_appfrom ...core.mutations import BaseMutationfrom ...core.types import OrderError-from ...core.utils import validate_required_string_field+from ...core.validators import validate_required_string_fieldfrom ...plugins.dataloaders import load_plugin_managerfrom ..types import Order, OrderEventfrom .utils import get_webhook_handler_by_order_statusdiff --git a/saleor/graphql/page/mutations/pages.py b/saleor/graphql/page/mutations/pages.pyindex 36cadfeecc..af680ae870 100644--- a/saleor/graphql/page/mutations/pages.py+++ b/saleor/graphql/page/mutations/pages.py@@ -18,7 +18,7 @@ from ...core.descriptions import ADDED_IN_33, DEPRECATED_IN_3X_INPUT, RICH_CONTEfrom ...core.fields import JSONStringfrom ...core.mutations import ModelDeleteMutation, ModelMutationfrom ...core.types import NonNullList, PageError, SeoInput-from ...core.utils import clean_seo_fields, validate_slug_and_generate_if_needed+from ...core.validators import clean_seo_fields, validate_slug_and_generate_if_neededfrom ...plugins.dataloaders import load_plugin_managerfrom ...utils.validators import check_for_duplicatesfrom ..types import Page, PageTypediff --git a/saleor/graphql/product/mutations/product_type_create.py b/saleor/graphql/product/mutations/product_type_create.pyindex 2c4329be63..55781fa4e1 100644--- a/saleor/graphql/product/mutations/product_type_create.py+++ b/saleor/graphql/product/mutations/product_type_create.py@@ -9,7 +9,7 @@ from ...core.descriptions import DEPRECATED_IN_3X_INPUTfrom ...core.mutations import ModelMutationfrom ...core.scalars import WeightScalarfrom ...core.types import NonNullList, ProductError-from ...core.utils import validate_slug_and_generate_if_needed+from ...core.validators import validate_slug_and_generate_if_neededfrom ..enums import ProductTypeKindEnumfrom ..types import ProductTypediff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex cfd49fdcaf..56d7eab820 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -48,18 +48,19 @@ from ...core.inputs import ReorderInputfrom ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ...core.scalars import WeightScalarfrom ...core.types import CollectionError, NonNullList, ProductError, SeoInput, Upload-from ...core.utils import (- add_hash_to_file_name,+from ...core.utils import get_duplicated_values+from ...core.utils.reordering import perform_reordering+from ...core.validators import (clean_seo_fields,- get_duplicated_values,+ validate_one_of_args_is_in_mutation,+ validate_slug_and_generate_if_needed,+)+from ...core.validators.file import (+ clean_image_file,get_filename_from_url,is_image_url,- validate_image_file,validate_image_url,- validate_slug_and_generate_if_needed,)-from ...core.utils.reordering import perform_reordering-from ...core.validators import validate_one_of_args_is_in_mutationfrom ...meta.mutations import MetadataInputfrom ...plugins.dataloaders import load_plugin_managerfrom ...warehouse.types import Warehouse@@ -139,9 +140,7 @@ class CategoryCreate(ModelMutation):)cleaned_input["parent"] = parentif data.get("background_image"):- image_data = info.context.FILES.get(data["background_image"])- validate_image_file(image_data, "background_image", ProductErrorCode)- add_hash_to_file_name(image_data)+ clean_image_file(cleaned_input, "background_image", ProductErrorCode)clean_seo_fields(cleaned_input)return cleaned_input@@ -279,9 +278,7 @@ class CollectionCreate(ModelMutation):error.code = CollectionErrorCode.REQUIRED.valueraise ValidationError({"slug": error})if data.get("background_image"):- image_data = info.context.FILES.get(data["background_image"])- validate_image_file(image_data, "background_image", CollectionErrorCode)- add_hash_to_file_name(image_data)+ clean_image_file(cleaned_input, "background_image", ProductErrorCode)is_published = cleaned_input.get("is_published")publication_date = cleaned_input.get("publication_date")if is_published and not publication_date:@@ -1453,12 +1450,10 @@ class ProductMediaCreate(BaseMutation):)alt = data.get("alt", "")- image = data.get("image")media_url = data.get("media_url")- if image:- image_data = info.context.FILES.get(image)- validate_image_file(image_data, "image", ProductErrorCode)- add_hash_to_file_name(image_data)+ if img_data := data.get("image"):+ data["image"] = info.context.FILES.get(img_data)+ image_data = clean_image_file(data, "image", ProductErrorCode)media = product.media.create(image=image_data, alt=alt, type=ProductMediaTypes.IMAGE)diff --git a/saleor/graphql/product/tests/mutations/test_product_media_create.py b/saleor/graphql/product/tests/mutations/test_product_media_create.pyindex fbecec95a2..f427b9a7a2 100644--- a/saleor/graphql/product/tests/mutations/test_product_media_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_media_create.py@@ -49,6 +49,7 @@ def test_product_media_create_mutation(permission_manage_products,media_root,):+ 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),@@ -58,9 +59,7 @@ def test_product_media_create_mutation(body = get_multipart_request_body(PRODUCT_MEDIA_CREATE_QUERY, variables, image_file, image_name)- response = staff_api_client.post_multipart(- body, permissions=[permission_manage_products]- )+ response = staff_api_client.post_multipart(body)get_graphql_content(response)product.refresh_from_db()product_image = product.media.last()diff --git a/saleor/graphql/product/tests/test_category.py b/saleor/graphql/product/tests/test_category.pyindex 4862cd9e64..fc01841a51 100644--- a/saleor/graphql/product/tests/test_category.py+++ b/saleor/graphql/product/tests/test_category.py@@ -1,6 +1,6 @@import jsonimport os-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, Mock, patchimport grapheneimport pytest@@ -404,6 +404,8 @@ def test_category_create_mutation(monkeypatch, staff_api_client, permission_manage_products, media_root):# given+ staff_api_client.user.user_permissions.add(permission_manage_products)+category_name = "Test category"description = "description"category_slug = slugify(category_name)@@ -427,9 +429,7 @@ def test_category_create_mutation(body = get_multipart_request_body(CATEGORY_CREATE_MUTATION, variables, image_file, image_name)- response = staff_api_client.post_multipart(- body, permissions=[permission_manage_products]- )+ response = staff_api_client.post_multipart(body)content = get_graphql_content(response)data = content["data"]["categoryCreate"]@@ -478,6 +478,8 @@ def test_category_create_trigger_webhook(media_root,settings,):+ staff_api_client.user.user_permissions.add(permission_manage_products)+query = CATEGORY_CREATE_MUTATIONmocked_get_webhooks_for_event.return_value = [any_webhook]settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]@@ -498,9 +500,7 @@ def test_category_create_trigger_webhook("slug": category_slug,}body = get_multipart_request_body(query, variables, image_file, image_name)- response = staff_api_client.post_multipart(- body, permissions=[permission_manage_products]- )+ response = staff_api_client.post_multipart(body)content = get_graphql_content(response)data = content["data"]["categoryCreate"]category = Category.objects.first()@@ -631,6 +631,7 @@ def test_category_update_mutation(monkeypatch, staff_api_client, category, permission_manage_products, media_root):# given+ staff_api_client.user.user_permissions.add(permission_manage_products)# create child category and test that the update mutation won't change# it's parent@@ -668,9 +669,7 @@ def test_category_update_mutation()# when- response = staff_api_client.post_multipart(- body, permissions=[permission_manage_products]- )+ response = staff_api_client.post_multipart(body)content = get_graphql_content(response)data = content["data"]["categoryUpdate"]@@ -704,6 +703,8 @@ def test_category_update_trigger_webhook(media_root,settings,):+ staff_api_client.user.user_permissions.add(permission_manage_products)+mocked_get_webhooks_for_event.return_value = [any_webhook]settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]@@ -726,9 +727,7 @@ def test_category_update_trigger_webhook(body = get_multipart_request_body(MUTATION_CATEGORY_UPDATE_MUTATION, variables, image_file, image_name)- response = staff_api_client.post_multipart(- body, permissions=[permission_manage_products]- )+ response = staff_api_client.post_multipart(body)content = get_graphql_content(response)data = content["data"]["categoryUpdate"]assert data["errors"] == []@@ -763,6 +762,8 @@ def test_category_update_background_image_mutation(site_settings,):# given+ staff_api_client.user.user_permissions.add(permission_manage_products)+alt_text = "Alt text for an image."background_mock = MagicMock(spec=File)background_mock.name = "image.jpg"@@ -797,9 +798,7 @@ def test_category_update_background_image_mutation()# when- response = staff_api_client.post_multipart(- body, permissions=[permission_manage_products]- )+ response = staff_api_client.post_multipart(body)# thencontent = get_graphql_content(response)@@ -820,7 +819,7 @@ def test_category_update_background_image_mutation(@patch("saleor.core.tasks.delete_from_storage_task.delay")-def test_category_update_mutation_invalid_background_image(+def test_category_update_mutation_invalid_background_image_content_type(delete_from_storage_task_mock,staff_api_client,category,@@ -863,6 +862,58 @@ def test_category_update_mutation_invalid_background_image(delete_from_storage_task_mock.assert_not_called()+@patch("saleor.core.tasks.delete_from_storage_task.delay")+def test_category_update_mutation_invalid_background_image(+ delete_from_storage_task_mock,+ monkeypatch,+ staff_api_client,+ category,+ permission_manage_products,+ media_root,+):+ # given+ staff_api_client.user.user_permissions.add(permission_manage_products)++ image_file, image_name = create_image()+ image_alt = "Alt text for an image."++ error_msg = "Test syntax error"+ image_file_mock = Mock(side_effect=SyntaxError(error_msg))+ monkeypatch.setattr(+ "saleor.graphql.core.validators.file.Image.open", image_file_mock+ )++ size = 128+ thumbnail_mock = MagicMock(spec=File)+ thumbnail_mock.name = "thumbnail_image.jpg"+ Thumbnail.objects.create(category=category, size=size, image=thumbnail_mock)++ variables = {+ "name": "new-name",+ "slug": "new-slug",+ "id": to_global_id("Category", category.id),+ "backgroundImage": image_name,+ "backgroundImageAlt": image_alt,+ "isPublished": True,+ }+ body = get_multipart_request_body(+ MUTATION_CATEGORY_UPDATE_MUTATION, variables, image_file, image_name+ )++ # when+ response = staff_api_client.post_multipart(body)++ # then+ content = get_graphql_content(response)+ data = content["data"]["categoryUpdate"]+ assert data["errors"][0]["field"] == "backgroundImage"+ assert error_msg in data["errors"][0]["message"]++ # ensure that thumbnails for old background image hasn't been deleted+ assert Thumbnail.objects.filter(category_id=category.id)+ delete_from_storage_task_mock.assert_not_called()++def test_category_update_mutation_without_background_image(monkeypatch, staff_api_client, category, permission_manage_products):diff --git a/saleor/graphql/product/tests/test_collection.py b/saleor/graphql/product/tests/test_collection.pyindex 041019da59..9710950266 100644--- a/saleor/graphql/product/tests/test_collection.py+++ b/saleor/graphql/product/tests/test_collection.py@@ -1,6 +1,6 @@import osfrom datetime import datetime, timedelta-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, Mock, patchimport grapheneimport pytest@@ -488,6 +488,8 @@ def test_create_collection(permission_manage_products,):# given+ staff_api_client.user.user_permissions.add(permission_manage_products)+product_ids = [to_global_id("Product", product.pk) for product in product_list]image_file, image_name = create_image()image_alt = "Alt text for an image."@@ -512,9 +514,7 @@ def test_create_collection()# when- response = staff_api_client.post_multipart(- body, permissions=[permission_manage_products]- )+ response = staff_api_client.post_multipart(body)content = get_graphql_content(response)data = content["data"]["collectionCreate"]["collection"]@@ -741,6 +741,8 @@ def test_update_collection_with_background_image(site_settings,):# given+ staff_api_client.user.user_permissions.add(permission_manage_products)+image_file, image_name = create_image()image_alt = "Alt text for an image."@@ -769,9 +771,7 @@ def test_update_collection_with_background_image()# when- response = staff_api_client.post_multipart(- body, permissions=[permission_manage_products]- )+ response = staff_api_client.post_multipart(body)# thencontent = get_graphql_content(response)@@ -790,7 +790,7 @@ def test_update_collection_with_background_image(@patch("saleor.core.tasks.delete_from_storage_task.delay")-def test_update_collection_invalid_background_image(+def test_update_collection_invalid_background_image_content_type(delete_from_storage_task_mock,staff_api_client,collection,@@ -835,6 +835,60 @@ def test_update_collection_invalid_background_image(delete_from_storage_task_mock.assert_not_called()+@patch("saleor.core.tasks.delete_from_storage_task.delay")+def test_update_collection_invalid_background_image(+ delete_from_storage_task_mock,+ monkeypatch,+ staff_api_client,+ collection,+ permission_manage_products,+ media_root,+):+ # given+ image_file, image_name = create_image()+ image_alt = "Alt text for an image."++ error_msg = "Test syntax error"+ image_file_mock = Mock(side_effect=SyntaxError(error_msg))+ monkeypatch.setattr(+ "saleor.graphql.core.validators.file.Image.open", image_file_mock+ )++ size = 128+ thumbnail_mock = MagicMock(spec=File)+ thumbnail_mock.name = "thumbnail_image.jpg"+ Thumbnail.objects.create(collection=collection, size=size, image=thumbnail_mock)++ variables = {+ "name": "new-name",+ "slug": "new-slug",+ "id": to_global_id("Collection", collection.id),+ "backgroundImage": image_name,+ "backgroundImageAlt": image_alt,+ }+ body = get_multipart_request_body(+ MUTATION_UPDATE_COLLECTION_WITH_BACKGROUND_IMAGE,+ variables,+ image_file,+ image_name,+ )++ # when+ response = staff_api_client.post_multipart(+ body, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["collectionUpdate"]+ assert data["errors"][0]["field"] == "backgroundImage"+ assert error_msg in data["errors"][0]["message"]++ # ensure that thumbnails for old background image hasn't been deleted+ assert Thumbnail.objects.filter(collection_id=collection.id)+ delete_from_storage_task_mock.assert_not_called()++UPDATE_COLLECTION_SLUG_MUTATION = """mutation($id: ID!, $slug: String) {collectionUpdate(diff --git a/saleor/graphql/warehouse/mutations.py b/saleor/graphql/warehouse/mutations.pyindex fad4f7d1c5..739be943c0 100644--- a/saleor/graphql/warehouse/mutations.py+++ b/saleor/graphql/warehouse/mutations.py@@ -12,7 +12,7 @@ from ...warehouse.validation import validate_warehouse_count # type: ignorefrom ..account.i18n import I18nMixinfrom ..core.mutations import ModelDeleteMutation, ModelMutationfrom ..core.types import NonNullList, WarehouseError-from ..core.utils import (+from ..core.validators import (validate_required_string_field,validate_slug_and_generate_if_needed,)diff --git a/saleor/product/tests/utils.py b/saleor/product/tests/utils.pyindex 65c0806de1..5d850d18f2 100644--- a/saleor/product/tests/utils.py+++ b/saleor/product/tests/utils.py@@ -8,7 +8,7 @@ def create_image(image_name="product2"):img_data = BytesIO()image = Image.new("RGB", size=(1, 1), color=(255, 0, 0, 0))image.save(img_data, format="JPEG")- image = SimpleUploadedFile(image_name + ".jpg", img_data.getvalue(), "image/png")+ image = SimpleUploadedFile(image_name + ".jpg", img_data.getvalue(), "image/jpeg")return image, image_name