Skip to content

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

Add file format validation for uploaded images (#7447)

Iga Karbowiakd67aca61b5a3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a0bbe2ec30..8d350c4b6e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -112,6 +112,7 @@ All notable, unreleased changes to this project will be documented in this file.
- `channel` from `pluginUpdate` changed to channelId
- Order events performance - #7424 by tomaszszymanski129
- Add hash to uploading images #7453 by @IKarbowiak
+- Add file format validation for uploaded images - #7447 by @IKarbowiak
### Breaking
- Multichannel MVP: Multicurrency - #6242 by @fowczarek @d-wysocki
diff --git a/saleor/graphql/account/mutations/staff.py b/saleor/graphql/account/mutations/staff.py
index 3f78fdd72e..0e9bb641f6 100644
--- a/saleor/graphql/account/mutations/staff.py
+++ b/saleor/graphql/account/mutations/staff.py
@@ -533,9 +533,8 @@ class UserAvatarUpdate(BaseMutation):
def perform_mutation(cls, _root, info, image):
user = info.context.user
image_data = info.context.FILES.get(image)
- validate_image_file(image_data, "image")
+ validate_image_file(image_data, "image", AccountErrorCode)
add_hash_to_file_name(image_data)
-
if user.avatar:
user.avatar.delete_sized_images()
user.avatar.delete()
diff --git a/saleor/graphql/core/tests/test_core.py b/saleor/graphql/core/tests/test_core.py
index 74849e317c..c676fc8119 100644
--- a/saleor/graphql/core/tests/test_core.py
+++ b/saleor/graphql/core/tests/test_core.py
@@ -1,4 +1,5 @@
import os
+from io import BytesIO
from unittest.mock import patch
import django_filters
@@ -6,11 +7,14 @@ import graphene
import pytest
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ImproperlyConfigured, ValidationError
+from django.core.files.uploadedfile import SimpleUploadedFile
from django.utils import timezone
from graphene import InputField
+from PIL import Image
from ....core.utils.validators import get_oembed_data
from ....product import ProductMediaTypes
+from ....product.error_codes import ProductErrorCode
from ....product.models import Category, Product, ProductChannelListing
from ...tests.utils import get_graphql_content, get_graphql_content_from_response
from ...utils import requestor_is_superuser
@@ -24,6 +28,7 @@ from ..utils import (
clean_seo_fields,
get_duplicated_values,
snake_to_camel_case,
+ validate_image_file,
validate_slug_and_generate_if_needed,
)
from . import ErrorTest
@@ -227,6 +232,84 @@ def test_validate_slug_and_generate_if_needed_generate_slug(cleaned_input):
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")
+ img = SimpleUploadedFile("product.jpg", img_data.getvalue(), "image/jpeg")
+ field = "image"
+
+ # when
+ result = validate_image_file(img, field, ProductErrorCode)
+
+ # then
+ assert not result
+
+
+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."
+ )
+
+
@pytest.mark.parametrize(
"value, count, product_indexes",
[
diff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.py
index 9705595b5c..968f4470f9 100644
--- a/saleor/graphql/core/utils/__init__.py
+++ b/saleor/graphql/core/utils/__init__.py
@@ -7,6 +7,7 @@ import graphene
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from graphene import ObjectType
+from PIL import Image
from ....core.utils import generate_unique_slug
@@ -15,6 +16,9 @@ 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)
@@ -36,15 +40,47 @@ def str_to_enum(name):
return name.replace(" ", "_").replace("-", "_").upper()
-def validate_image_file(file, field_name):
+def validate_image_file(file, field_name, error_class):
"""Validate if the file is an image."""
if not file:
raise ValidationError(
- {field_name: ValidationError("File is required", code="required")}
+ {
+ field_name: ValidationError(
+ "File is required.", code=error_class.REQUIRED
+ )
+ }
)
if not file.content_type.startswith("image/"):
raise ValidationError(
- {field_name: ValidationError("Invalid file type", code="invalid")}
+ {
+ 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 = [ext.lower() for ext in Image.EXTENSION]
+ _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,
+ )
+ }
)
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 5ca139df86..ec124a14d2 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -112,7 +112,7 @@ class CategoryCreate(ModelMutation):
cleaned_input["parent"] = parent
if data.get("background_image"):
image_data = info.context.FILES.get(data["background_image"])
- validate_image_file(image_data, "background_image")
+ validate_image_file(image_data, "background_image", ProductErrorCode)
add_hash_to_file_name(image_data)
clean_seo_fields(cleaned_input)
return cleaned_input
@@ -219,7 +219,7 @@ class CollectionCreate(ModelMutation):
raise ValidationError({"slug": error})
if data.get("background_image"):
image_data = info.context.FILES.get(data["background_image"])
- validate_image_file(image_data, "background_image")
+ validate_image_file(image_data, "background_image", CollectionErrorCode)
add_hash_to_file_name(image_data)
is_published = cleaned_input.get("is_published")
publication_date = cleaned_input.get("publication_date")
@@ -1311,7 +1311,7 @@ class ProductMediaCreate(BaseMutation):
media_url = data.get("media_url")
if image:
image_data = info.context.FILES.get(image)
- validate_image_file(image_data, "image")
+ validate_image_file(image_data, "image", ProductErrorCode)
add_hash_to_file_name(image_data)
media = product.media.create(
image=image_data, alt=alt, type=ProductMediaTypes.IMAGE
diff --git a/saleor/graphql/product/tests/test_category.py b/saleor/graphql/product/tests/test_category.py
index f9aa087ccd..d6e93eb341 100644
--- a/saleor/graphql/product/tests/test_category.py
+++ b/saleor/graphql/product/tests/test_category.py
@@ -554,7 +554,7 @@ def test_category_update_mutation_invalid_background_image(
content = get_graphql_content(response)
data = content["data"]["categoryUpdate"]
assert data["errors"][0]["field"] == "backgroundImage"
- assert data["errors"][0]["message"] == "Invalid file type"
+ assert data["errors"][0]["message"] == "Invalid file type."
def test_category_update_mutation_without_background_image(
diff --git a/saleor/graphql/product/tests/test_collection.py b/saleor/graphql/product/tests/test_collection.py
index 6989e642fd..42eb130c26 100644
--- a/saleor/graphql/product/tests/test_collection.py
+++ b/saleor/graphql/product/tests/test_collection.py
@@ -704,7 +704,7 @@ def test_update_collection_invalid_background_image(
content = get_graphql_content(response)
data = content["data"]["collectionUpdate"]
assert data["errors"][0]["field"] == "backgroundImage"
- assert data["errors"][0]["message"] == "Invalid file type"
+ assert data["errors"][0]["message"] == "Invalid file type."
UPDATE_COLLECTION_SLUG_MUTATION = """
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index c88948ed5d..1060a99466 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -7510,7 +7510,7 @@ def test_invalid_product_media_create_mutation(
content = get_graphql_content(response)
assert content["data"]["productMediaCreate"]["errors"] == [
- {"field": "image", "message": "Invalid file type"}
+ {"field": "image", "message": "Invalid file type."}
]
product.refresh_from_db()
assert product.media.count() == 0