Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Introduce maximum file size limit for uploaded images (#19073)
Marcin Wcisło087b5328da9b
diff --git a/saleor/account/error_codes.py b/saleor/account/error_codes.pyindex 6a41180618..1f356f1312 100644--- a/saleor/account/error_codes.py+++ b/saleor/account/error_codes.py@@ -39,6 +39,7 @@ class AccountErrorCode(Enum):LOGIN_ATTEMPT_DELAYED = "login_attempt_delayed"DISABLED_AUTHENTICATION_METHOD = "disabled_authentication_method"UNKNOWN_IP_ADDRESS = "unknown_ip_address"+ FILE_SIZE_LIMIT_EXCEEDED = "file_size_limit_exceeded"class CustomerBulkUpdateErrorCode(Enum):diff --git a/saleor/graphql/account/tests/mutations/staff/test_user_avatar_update.py b/saleor/graphql/account/tests/mutations/staff/test_user_avatar_update.pyindex a9d9ab55f3..94dc08bf5b 100644--- a/saleor/graphql/account/tests/mutations/staff/test_user_avatar_update.py+++ b/saleor/graphql/account/tests/mutations/staff/test_user_avatar_update.py@@ -3,6 +3,7 @@ from unittest.mock import MagicMockfrom django.core.files import File+from ......account.error_codes import AccountErrorCodefrom ......product.tests.utils import create_imagefrom ......thumbnail.models import Thumbnailfrom .....tests.utils import (@@ -19,6 +20,11 @@ USER_AVATAR_UPDATE_MUTATION = """url}}+ accountErrors {+ field+ code+ message+ }}}"""@@ -97,3 +103,28 @@ def test_user_avatar_update_mutation_image_exists(staff_api_client, media_root):"https://example.com/media/user-avatars/new_image")assert not user.thumbnails.exists()+++def test_user_avatar_update_mutation_file_size_exceeds_limit(+ staff_api_client, media_root, settings+):+ # given+ settings.MAX_IMAGE_FILE_SIZE = 1+ image_file, image_name = create_image("avatar")+ variables = {"image": image_name}+ body = get_multipart_request_body(+ USER_AVATAR_UPDATE_MUTATION, variables, image_file, image_name+ )++ # when+ response = staff_api_client.post_multipart(body)+ content = get_graphql_content(response)++ # then+ errors = content["data"]["userAvatarUpdate"]["accountErrors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "image"+ assert errors[0]["code"] == AccountErrorCode.FILE_SIZE_LIMIT_EXCEEDED.name+ assert "File size exceeds the maximum allowed size" in errors[0]["message"]+ staff_api_client.user.refresh_from_db()+ assert not staff_api_client.user.avatardiff --git a/saleor/graphql/core/tests/test_file_validation.py b/saleor/graphql/core/tests/test_file_validation.pyindex 250b89d6a1..3380991034 100644--- a/saleor/graphql/core/tests/test_file_validation.py+++ b/saleor/graphql/core/tests/test_file_validation.py@@ -4,6 +4,7 @@ from unittest.mock import Mock, patchimport pytestfrom django.core.exceptions import ValidationErrorfrom django.core.files.uploadedfile import SimpleUploadedFile+from django.test import override_settingsfrom PIL import Imagefrom ....core.error_codes import UploadErrorCode@@ -51,6 +52,39 @@ def test_clean_image_file():clean_image_file({field: img}, field, ProductErrorCode)+@override_settings(MAX_IMAGE_FILE_SIZE=1)+def test_clean_image_file_file_size_exceeds_limit():+ # given+ img_data = BytesIO()+ image = Image.new("RGB", size=(1, 1))+ image.save(img_data, format="JPEG")+ img = SimpleUploadedFile("product.jpg", 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].code == ProductErrorCode.FILE_SIZE_LIMIT_EXCEEDED+ assert (+ "File size exceeds the maximum allowed size" in exc.value.args[0][field].message+ )+++@override_settings(MAX_IMAGE_FILE_SIZE=10 * 1024 * 1024)+def test_clean_image_file_file_size_within_limit():+ # given+ img_data = BytesIO()+ image = Image.new("RGB", size=(1, 1))+ image.save(img_data, format="JPEG")+ img = SimpleUploadedFile("product.jpg", img_data.getvalue(), "image/jpeg")+ field = "image"++ # when/then - should not raise+ clean_image_file({field: img}, field, ProductErrorCode)++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 fb87dfa397..e79e6815dc 100644--- a/saleor/graphql/core/validators/file.py+++ b/saleor/graphql/core/validators/file.py@@ -108,6 +108,16 @@ def clean_image_file(cleaned_input, img_field_name, error_class):)})+ if img_file.size > settings.MAX_IMAGE_FILE_SIZE:+ raise ValidationError(+ {+ img_field_name: ValidationError(+ f"File size exceeds the maximum allowed size "+ f"of {settings.MAX_IMAGE_FILE_SIZE / (1024 * 1024):.0f}MB.",+ code=error_class.FILE_SIZE_LIMIT_EXCEEDED,+ )+ }+ )if not is_supported_image_mimetype(img_file.content_type):raise ValidationError({diff --git a/saleor/graphql/product/tests/mutations/test_category_create.py b/saleor/graphql/product/tests/mutations/test_category_create.pyindex f623d3c9f6..4e7ce810d6 100644--- a/saleor/graphql/product/tests/mutations/test_category_create.py+++ b/saleor/graphql/product/tests/mutations/test_category_create.py@@ -9,6 +9,7 @@ from django.utils.text import slugifyfrom freezegun import freeze_timefrom .....core.utils.json_serializer import CustomJsonEncoder+from .....product.error_codes import ProductErrorCodefrom .....product.models import Categoryfrom .....product.tests.utils import create_imagefrom .....tests.utils import dummy_editorjs@@ -255,3 +256,33 @@ def test_category_create_mutation_without_background_image(content = get_graphql_content(response)data = content["data"]["categoryCreate"]assert data["errors"] == []+++def test_category_create_mutation_file_size_exceeds_limit(+ staff_api_client, permission_manage_products, media_root, settings+):+ # given+ settings.MAX_IMAGE_FILE_SIZE = 1+ staff_api_client.user.user_permissions.add(permission_manage_products)+ category_name = "Test category"+ image_file, image_name = create_image()+ variables = {+ "name": category_name,+ "backgroundImage": image_name,+ "backgroundImageAlt": "Alt text",+ }+ body = get_multipart_request_body(+ CATEGORY_CREATE_MUTATION, variables, image_file, image_name+ )++ # when+ response = staff_api_client.post_multipart(body)+ content = get_graphql_content(response)++ # then+ errors = content["data"]["categoryCreate"]["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "backgroundImage"+ assert errors[0]["code"] == ProductErrorCode.FILE_SIZE_LIMIT_EXCEEDED.name+ assert "File size exceeds the maximum allowed size" in errors[0]["message"]+ assert not Category.objects.filter(name=category_name).exists()diff --git a/saleor/graphql/product/tests/mutations/test_collection_create.py b/saleor/graphql/product/tests/mutations/test_collection_create.pyindex 5a2933f076..9323ea7d98 100644--- a/saleor/graphql/product/tests/mutations/test_collection_create.py+++ b/saleor/graphql/product/tests/mutations/test_collection_create.py@@ -4,6 +4,7 @@ from unittest.mock import patchimport grapheneimport pytest+from .....product.error_codes import CollectionErrorCodefrom .....product.models import Collectionfrom .....product.tests.utils import create_imagefrom .....tests.utils import dummy_editorjs@@ -212,3 +213,33 @@ def test_create_collection_name_with_unicode(assert not data["errors"]assert data["collection"]["name"] == nameassert data["collection"]["slug"] == "watasi-wa-nitupon-desu"+++def test_create_collection_file_size_exceeds_limit(+ staff_api_client, permission_manage_products, media_root, settings+):+ # given+ settings.MAX_IMAGE_FILE_SIZE = 1+ staff_api_client.user.user_permissions.add(permission_manage_products)+ collection_name = "Test collection"+ image_file, image_name = create_image()+ variables = {+ "name": collection_name,+ "backgroundImage": image_name,+ "backgroundImageAlt": "Alt text",+ }+ body = get_multipart_request_body(+ CREATE_COLLECTION_MUTATION, variables, image_file, image_name+ )++ # when+ response = staff_api_client.post_multipart(body)+ content = get_graphql_content(response)++ # then+ errors = content["data"]["collectionCreate"]["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "backgroundImage"+ assert errors[0]["code"] == CollectionErrorCode.FILE_SIZE_LIMIT_EXCEEDED.name+ assert "File size exceeds the maximum allowed size" in errors[0]["message"]+ assert not Collection.objects.filter(name=collection_name).exists()diff --git a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_bulk_create.pyindex a7fe7835a4..634c087b7d 100644--- a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py@@ -818,6 +818,66 @@ def test_product_bulk_create_with_media_invalid_extension(assert len(error_2) == 1+def test_product_bulk_create_with_media_file_size_exceeds_limit(+ staff_api_client,+ product_type,+ category,+ description_json,+ permission_manage_products,+ media_root,+ settings,+):+ # given+ settings.MAX_IMAGE_FILE_SIZE = 1+ 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 = "test name"+ base_product_slug = "product-test-slug"++ image_file, image_name = create_image(image_name="prod_img")++ media = {+ "alt": "",+ "image": image_name,+ }++ products = [+ {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name,+ "slug": f"{base_product_slug}-1",+ "description": description_json_string,+ "media": [media],+ },+ ]++ files = [image_file]+ 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+ errors = data["results"][0]["errors"]+ assert len(errors) == 1+ assert errors[0]["code"] == ProductBulkCreateErrorCode.FILE_SIZE_LIMIT_EXCEEDED.name+ assert errors[0]["path"] == "media.0.image"+ assert "File size exceeds the maximum allowed size" in errors[0]["message"]++def test_product_bulk_create_with_media_invalid_media_type(staff_api_client,product_type,diff --git a/saleor/graphql/product/tests/mutations/test_product_media_create.py b/saleor/graphql/product/tests/mutations/test_product_media_create.pyindex caa338117d..386c21fe14 100644--- a/saleor/graphql/product/tests/mutations/test_product_media_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_media_create.py@@ -86,6 +86,35 @@ def test_product_media_create_mutation(product_media_created.assert_called_once_with(product_image)+def test_product_media_create_mutation_file_size_exceeds_limit(+ staff_api_client, product, permission_manage_products, media_root, settings+):+ # given+ settings.MAX_IMAGE_FILE_SIZE = 1+ 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 "File size exceeds the maximum allowed size" in errors[0]["message"]+ assert product.media.count() == 0++def test_product_media_create_mutation_without_file(monkeypatch, staff_api_client, product, permission_manage_products, media_root):diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 1fac28fbe3..dd8e3bbb67 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -23642,6 +23642,7 @@ enum ProductErrorCode @doc(category: "Products") {PREORDER_VARIANT_CANNOT_BE_DEACTIVATEDINVALID_FILE_TYPEUNSUPPORTED_MIME_TYPE+ FILE_SIZE_LIMIT_EXCEEDED}input ProductAttributeAssignInput @doc(category: "Products") {@@ -23853,6 +23854,7 @@ enum CollectionErrorCode @doc(category: "Products") {REQUIREDUNIQUECANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT @deprecated(reason: "Products without variants can now be assigned to collections. This error will never be returned.")+ FILE_SIZE_LIMIT_EXCEEDED}"""@@ -24317,6 +24319,7 @@ enum ProductBulkCreateErrorCode @doc(category: "Products") {UNIQUEPRODUCT_NOT_ASSIGNED_TO_CHANNELUNSUPPORTED_MEDIA_PROVIDER+ FILE_SIZE_LIMIT_EXCEEDED}input ProductBulkCreateInput @doc(category: "Products") {@@ -32454,6 +32457,7 @@ enum AccountErrorCode @doc(category: "Users") {LOGIN_ATTEMPT_DELAYEDDISABLED_AUTHENTICATION_METHODUNKNOWN_IP_ADDRESS+ FILE_SIZE_LIMIT_EXCEEDED}"""diff --git a/saleor/product/error_codes.py b/saleor/product/error_codes.pyindex 6e016762ac..4b0fab6ef8 100644--- a/saleor/product/error_codes.py+++ b/saleor/product/error_codes.py@@ -23,6 +23,7 @@ class ProductErrorCode(Enum):PREORDER_VARIANT_CANNOT_BE_DEACTIVATED = "preorder_variant_cannot_be_deactivated"INVALID_FILE_TYPE = "invalid_file_type"UNSUPPORTED_MIME_TYPE = "unsupported_mime_type"+ FILE_SIZE_LIMIT_EXCEEDED = "file_size_limit_exceeded"class CollectionErrorCode(Enum):@@ -33,6 +34,7 @@ class CollectionErrorCode(Enum):REQUIRED = "required"UNIQUE = "unique"CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT = "cannot_manage_product_without_variant"+ FILE_SIZE_LIMIT_EXCEEDED = "file_size_limit_exceeded"class ProductVariantBulkErrorCode(Enum):@@ -67,3 +69,4 @@ class ProductBulkCreateErrorCode(Enum):UNIQUE = "unique"PRODUCT_NOT_ASSIGNED_TO_CHANNEL = "product_not_assigned_to_channel"UNSUPPORTED_MEDIA_PROVIDER = "unsupported_media_provider"+ FILE_SIZE_LIMIT_EXCEEDED = "file_size_limit_exceeded"diff --git a/saleor/settings.py b/saleor/settings.pyindex 5bf701ce2e..b0ca368dd6 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -497,6 +497,9 @@ COUNTRIES_OVERRIDE = {}MAX_USER_ADDRESSES = int(os.environ.get("MAX_USER_ADDRESSES", 100))+MAX_IMAGE_FILE_SIZE = int(+ os.environ.get("MAX_IMAGE_FILE_SIZE", 10 * 1024 * 1024)+) # 10MBTEST_RUNNER = "saleor.tests.runner.PytestTestRunner"