Skip to content

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

Refactor media validation in product mutations (#18806)

Przemysław Łada1ead4a863e84
diff --git a/saleor/graphql/core/tests/test_file_validation.py b/saleor/graphql/core/tests/test_file_validation.py
index 4ddef80c78..09e8ca88ab 100644
--- a/saleor/graphql/core/tests/test_file_validation.py
+++ b/saleor/graphql/core/tests/test_file_validation.py
@@ -11,8 +11,8 @@ from ....product.error_codes import ProductErrorCode
from ..validators.file import (
clean_image_file,
detect_mime_type,
+ get_mime_type,
is_image_mimetype,
- is_image_url,
is_supported_image_mimetype,
is_valid_image_content_type,
validate_upload_file,
@@ -274,29 +274,20 @@ def test_clean_image_file_in_avif_format():
@pytest.mark.parametrize(
- ("url", "is_valid"),
+ ("content_type_header", "expected_mime_type"),
[
- ("http://example.com/valid_image.jpg", True),
- ("https://example.com/valid_image.png", True),
- ("http://example.com/valid_image.jpeg", True),
- ("http://example.com/valid_image.gif", True),
- ("http://example.com/valid_image.bmp", True),
- ("http://example.com/valid_image.tiff", True),
- ("http://example.com/valid_image.webp", True),
- ("https://example.com/valid_image.webp", True),
- ("http://example.com/valid_image.avif", True),
- ("http://example.com/invalid_image.pdf", False),
- ("http://example.com/invalid_image.docx", False),
- ("http://example.com/invalid_image.exe", False),
- ("http://example.com/invalid_image.txt", False),
+ (None, None),
+ ("", ""),
+ ("text/html; charset=utf-8", "text/html"),
+ ("text/css; charset=UTF-8", "text/css"),
+ ("image/jpeg", "image/jpeg"),
+ (" image/png; charset=binary", "image/png"),
+ (" Text/HTML ; Charset=UTF-8 ", "text/html"),
+ ("APPLICATION/JSON;CHARSET=UTF-8", "application/json"),
],
)
-def test_is_image_url(url, is_valid):
- # when
- result = is_image_url(url)
-
- # then
- assert result is is_valid
+def test_get_mime_type(content_type_header, expected_mime_type):
+ assert get_mime_type(content_type_header) == expected_mime_type
@pytest.mark.parametrize(
diff --git a/saleor/graphql/core/validators/file.py b/saleor/graphql/core/validators/file.py
index c9b9dea18d..7a909e86e2 100644
--- a/saleor/graphql/core/validators/file.py
+++ b/saleor/graphql/core/validators/file.py
@@ -1,5 +1,4 @@
import logging
-import mimetypes
import os
import magic
@@ -88,7 +87,13 @@ def detect_mime_type(file_data) -> str:
return mime_type
-def is_image_mimetype(mimetype: str) -> bool:
+def get_mime_type(content_type_header: str | None) -> str | None:
+ if content_type_header is None:
+ return None
+ return content_type_header.split(";", maxsplit=1)[0].strip().lower()
+
+
+def is_image_mimetype(mimetype: str | None) -> bool:
"""Check if mimetype is image."""
if mimetype is None:
return False
@@ -102,12 +107,6 @@ def is_supported_image_mimetype(mimetype: str) -> bool:
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."""
- filetype = mimetypes.guess_type(url)[0]
- return filetype is not None and is_image_mimetype(filetype)
-
-
def is_valid_image_content_type(content_type: str | None) -> bool:
"""Check if content type is a valid image content type."""
return content_type is not None and is_supported_image_mimetype(content_type)
diff --git a/saleor/graphql/product/bulk_mutations/product_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
index 4ce465858f..25bb323507 100644
--- a/saleor/graphql/product/bulk_mutations/product_bulk_create.py
+++ b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
@@ -2,6 +2,7 @@ import datetime
from collections import defaultdict
import graphene
+from django.conf import settings
from django.core.exceptions import ValidationError
from django.db.models import F
from django.utils.text import slugify
@@ -44,7 +45,8 @@ from ...core.utils import create_file_from_response, get_duplicated_values
from ...core.validators import clean_seo_fields
from ...core.validators.file import (
clean_image_file,
- is_image_url,
+ get_mime_type,
+ is_image_mimetype,
is_valid_image_content_type,
)
from ...meta.inputs import MetadataInput, MetadataInputDescription
@@ -477,21 +479,27 @@ class ProductBulkCreate(BaseMutation):
media_input["image"] = clean_image_file(
media_input, "image", ProductBulkCreateErrorCode
)
+ media_to_create.append(media_input)
except ValidationError as exc:
cls.add_indexes_to_errors(
product_index, exc, index_error_map, f"media.{index}"
)
continue
elif media_url:
- if is_image_url(media_url):
- with HTTPClient.send_request(
- "GET", media_url, stream=True, timeout=30, allow_redirects=False
- ) as image_data:
- content_type = image_data.headers.get("content-type")
- if is_valid_image_content_type(content_type):
- filename = get_filename_from_url(media_url)
+ with HTTPClient.send_request(
+ "GET",
+ media_url,
+ stream=True,
+ allow_redirects=False,
+ timeout=settings.COMMON_REQUESTS_TIMEOUT,
+ ) as image_data:
+ mime_type = get_mime_type(image_data.headers.get("content-type"))
+ if is_image_mimetype(mime_type):
+ if is_valid_image_content_type(mime_type):
+ filename = get_filename_from_url(media_url, mime_type)
image_file = create_file_from_response(image_data, filename)
media_input["image"] = image_file
+ media_to_create.append(media_input)
else:
validation_error = ValidationError(
{
@@ -507,29 +515,28 @@ class ProductBulkCreate(BaseMutation):
index_error_map,
f"media.{index}",
)
- else:
- try:
- oembed_data, supported_media_type = get_oembed_data(media_url)
- oembed_data["supported_media_type"] = supported_media_type
- except UnsupportedMediaProviderException as exc:
- validation_error = ValidationError(
- {
- "media_url": ValidationError(
- exc.message,
- code=ProductBulkCreateErrorCode.UNSUPPORTED_MEDIA_PROVIDER.value,
- )
- }
- )
- cls.add_indexes_to_errors(
- product_index,
- validation_error,
- index_error_map,
- f"media.{index}",
- )
continue
- media_input["oembed_data"] = oembed_data
-
- media_to_create.append(media_input)
+ try:
+ oembed_data, supported_media_type = get_oembed_data(media_url)
+ oembed_data["supported_media_type"] = supported_media_type
+ except UnsupportedMediaProviderException as exc:
+ validation_error = ValidationError(
+ {
+ "media_url": ValidationError(
+ exc.message,
+ code=ProductBulkCreateErrorCode.UNSUPPORTED_MEDIA_PROVIDER.value,
+ )
+ }
+ )
+ cls.add_indexes_to_errors(
+ product_index,
+ validation_error,
+ index_error_map,
+ f"media.{index}",
+ )
+ continue
+ media_input["oembed_data"] = oembed_data
+ media_to_create.append(media_input)
return media_to_create
diff --git a/saleor/graphql/product/mutations/product/product_media_create.py b/saleor/graphql/product/mutations/product/product_media_create.py
index 5951ba8764..b48910e80a 100644
--- a/saleor/graphql/product/mutations/product/product_media_create.py
+++ b/saleor/graphql/product/mutations/product/product_media_create.py
@@ -1,4 +1,5 @@
import graphene
+from django.conf import settings
from django.core.exceptions import ValidationError
from .....core.exceptions import UnsupportedMediaProviderException
@@ -16,7 +17,8 @@ from ....core.types import BaseInputObjectType, ProductError, Upload
from ....core.utils import create_file_from_response
from ....core.validators.file import (
clean_image_file,
- is_image_url,
+ get_mime_type,
+ is_image_mimetype,
is_valid_image_content_type,
)
from ....plugins.dataloaders import get_plugin_manager_promise
@@ -122,15 +124,16 @@ class ProductMediaCreate(BaseMutation):
# Remote URLs can point to the images or oembed data.
# In case of images, file is downloaded. Otherwise we keep only
# URL to remote media.
- if is_image_url(media_url):
- with HTTPClient.send_request(
- "GET", media_url, stream=True, allow_redirects=False
- ) as image_data:
- content_type = image_data.headers.get("content-type")
- if is_valid_image_content_type(content_type):
- filename = get_filename_from_url(media_url)
- image_file = create_file_from_response(image_data, filename)
- else:
+ with HTTPClient.send_request(
+ "GET",
+ media_url,
+ stream=True,
+ allow_redirects=False,
+ timeout=settings.COMMON_REQUESTS_TIMEOUT,
+ ) as image_data:
+ mime_type = get_mime_type(image_data.headers.get("content-type"))
+ if is_image_mimetype(mime_type):
+ if not is_valid_image_content_type(mime_type):
raise ValidationError(
{
"media_url": ValidationError(
@@ -139,12 +142,14 @@ class ProductMediaCreate(BaseMutation):
)
}
)
- media = product.media.create(
- image=image_file,
- alt=alt,
- type=ProductMediaTypes.IMAGE,
- )
- else:
+ filename = get_filename_from_url(media_url, mime_type)
+ image_file = create_file_from_response(image_data, filename)
+ media = product.media.create(
+ image=image_file,
+ alt=alt,
+ type=ProductMediaTypes.IMAGE,
+ )
+ if media is None:
try:
oembed_data, media_type = get_oembed_data(
media_url,
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 eaffc3c45e..0417d23ff5 100644
--- a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
@@ -1,6 +1,7 @@
import datetime
import json
import os
+from io import BytesIO
from unittest.mock import Mock, patch
from uuid import uuid4
@@ -983,8 +984,10 @@ def test_product_bulk_create_with_media_image_with_invalid_exif(
assert len(error_1) == 1
+@patch("saleor.graphql.product.bulk_mutations.product_bulk_create.HTTPClient")
@pytest.mark.vcr
def test_product_bulk_create_with_media_with_media_url(
+ mock_HTTPClient,
staff_api_client,
product_type,
category,
@@ -993,6 +996,9 @@ def test_product_bulk_create_with_media_with_media_url(
media_root,
):
# given
+ mock_response = Mock()
+ mock_response.headers.get = Mock(return_value="text/html; charset=utf-8")
+ mock_HTTPClient.send_request.return_value.__enter__.return_value = mock_response
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)
@@ -1077,21 +1083,21 @@ def test_product_bulk_create_with_media_with_media_url(
)
-@patch(
- "saleor.graphql.product.bulk_mutations.product_bulk_create.is_image_url",
- return_value=False,
-)
+@patch("saleor.graphql.product.bulk_mutations.product_bulk_create.HTTPClient")
@patch(
"saleor.graphql.product.bulk_mutations.product_bulk_create.get_oembed_data",
)
def test_product_bulk_create_with_media_with_media_url_invalid_provider(
mocked_get_oembed_data,
- _mocked_is_image_url,
+ mock_HTTPClient,
staff_api_client,
product_type,
permission_manage_products,
):
# given
+ mock_response = Mock()
+ mock_response.headers.get = Mock(return_value="text/plain")
+ mock_HTTPClient.send_request.return_value.__enter__.return_value = mock_response
mocked_get_oembed_data.side_effect = UnsupportedMediaProviderException()
product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
@@ -1209,9 +1215,7 @@ def test_product_bulk_create_with_media_with_media_url_invalid_image_type(
assert len(error_1) == 1
-@patch(
- "saleor.graphql.product.bulk_mutations.product_bulk_create.HTTPClient",
-)
+@patch("saleor.graphql.product.bulk_mutations.product_bulk_create.HTTPClient")
def test_product_bulk_create_with_media_invalid_image_file_fetch_only_header(
mock_HTTPClient,
staff_api_client,
@@ -1222,7 +1226,7 @@ def test_product_bulk_create_with_media_invalid_image_file_fetch_only_header(
# given
mock_response = Mock()
mock_response.headers = Mock()
- mock_response.headers.get = Mock(return_value="text/plain")
+ mock_response.headers.get = Mock(return_value="image/not-supported")
mock_response.raw = Mock()
mock_response.raw.read = Mock(return_value=b"fake_image_data")
mock_HTTPClient.send_request.return_value.__enter__.return_value = mock_response
@@ -1331,6 +1335,56 @@ def test_product_bulk_create_with_media_image_file_is_fetched_only_once(
assert img.size[1] > 0 # Ensure the image has dimensions
+@patch("saleor.graphql.product.bulk_mutations.product_bulk_create.HTTPClient")
+def test_product_bulk_create_with_no_extension_media_url(
+ mock_HTTPClient,
+ staff_api_client,
+ product_type,
+ category,
+ permission_manage_products,
+ media_root,
+):
+ # given
+ mock_response = Mock()
+ mock_response.headers.get = Mock(return_value="image/png")
+ # generate PNG image content
+ image_content = BytesIO()
+ PIL.Image.new("RGB", size=(100, 100)).save(image_content, format="PNG")
+ image_content = image_content.read()
+ mock_response.content = image_content
+ mock_HTTPClient.send_request.return_value.__enter__.return_value = mock_response
+ variables = [
+ {
+ "productType": graphene.Node.to_global_id("ProductType", product_type.pk),
+ "category": graphene.Node.to_global_id("Category", category.pk),
+ "name": "test name 1",
+ "media": [
+ {
+ "mediaUrl": "https://saleor.io/image-path",
+ }
+ ],
+ },
+ ]
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_CREATE_MUTATION,
+ variables={"products": variables},
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)["data"]["productBulkCreate"]
+
+ # then
+ assert not content["results"][0]["errors"]
+ # validate image file
+ _, product_id = graphene.Node.from_global_id(content["results"][0]["product"]["id"])
+ product_image = Product.objects.get(id=product_id).media.first()
+ assert product_image.image.name.startswith("products/image-path_")
+ assert product_image.image.name.endswith(".png")
+ with product_image.image.open("rb") as img:
+ assert img.read() == image_content
+
+
def test_product_bulk_create_with_attributes(
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.py
index eab64d52ff..87c39cfeb4 100644
--- a/saleor/graphql/product/tests/mutations/test_product_media_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_media_create.py
@@ -1,9 +1,12 @@
import json
import os
+from io import BytesIO
from unittest.mock import Mock, patch
import graphene
+import PIL
import pytest
+from django.conf import settings
from PIL import Image
from .....graphql.tests.utils import get_graphql_content, get_multipart_request_body
@@ -106,11 +109,15 @@ def test_product_media_create_mutation_without_file(
assert errors[0]["code"] == ProductErrorCode.REQUIRED.name
+@patch("saleor.graphql.product.mutations.product.product_media_create.HTTPClient")
@pytest.mark.vcr
def test_product_media_create_mutation_with_media_url(
- monkeypatch, staff_api_client, product, permission_manage_products, media_root
+ mock_HTTPClient, staff_api_client, product, permission_manage_products, media_root
):
# given
+ mock_response = Mock()
+ mock_response.headers.get = Mock(return_value="text/html; charset=utf-8")
+ mock_HTTPClient.send_request.return_value.__enter__.return_value = mock_response
variables = {
"product": graphene.Node.to_global_id("Product", product.id),
"mediaUrl": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
@@ -197,10 +204,14 @@ def test_product_media_create_mutation_with_both_url_and_image(
assert errors[0]["field"] == "input"
+@patch("saleor.graphql.product.mutations.product.product_media_create.HTTPClient")
def test_product_media_create_mutation_with_unknown_url(
- monkeypatch, staff_api_client, product, permission_manage_products, media_root
+ mock_HTTPClient, staff_api_client, product, permission_manage_products, media_root
):
# given
+ mock_response = Mock()
+ mock_response.headers.get = Mock(return_value="text/html; charset=utf-8")
+ mock_HTTPClient.send_request.return_value.__enter__.return_value = mock_response
variables = {
"product": graphene.Node.to_global_id("Product", product.id),
"mediaUrl": "https://www.videohosting.com/SomeVideoID",
@@ -270,7 +281,7 @@ def test_product_media_create_mutation_invalid_image_file_fetch_only_header(
# given
mock_response = Mock()
mock_response.headers = Mock()
- mock_response.headers.get = Mock(return_value="text/plain")
+ mock_response.headers.get = Mock(return_value="image/not-supported")
mock_response.raw = Mock()
mock_response.raw.read = Mock(return_value=b"fake_image_data")
mock_HTTPClient.send_request.return_value.__enter__.return_value = mock_response
@@ -302,7 +313,11 @@ def test_product_media_create_mutation_invalid_image_file_fetch_only_header(
# Ensure that only headers were fetched
mock_HTTPClient.send_request.assert_called_once_with(
- "GET", url, stream=True, allow_redirects=False
+ "GET",
+ url,
+ stream=True,
+ allow_redirects=False,
+ timeout=settings.COMMON_REQUESTS_TIMEOUT,
)
mock_response.headers.get.assert_called_once_with("content-type")
@@ -355,6 +370,44 @@ def test_product_media_create_mutation_valid_image_file_is_fetched_once(
assert img.size[1] > 0 # Ensure the image has dimensions
+@patch("saleor.graphql.product.mutations.product.product_media_create.HTTPClient")
+def test_product_media_create_mutation_with_no_extension_media_url(
+ mock_HTTPClient, staff_api_client, product, permission_manage_products, media_root
+):
+ # given
+ mock_response = Mock()
+ mock_response.headers.get = Mock(return_value="image/png")
+ # generate PNG image content
+ image_content = BytesIO()
+ PIL.Image.new("RGB", size=(100, 100)).save(image_content, format="PNG")
+ image_content = image_content.read()
+ mock_response.content = image_content
+ mock_HTTPClient.send_request.return_value.__enter__.return_value = mock_response
+ variables = {
+ "product": graphene.Node.to_global_id("Product", product.id),
+ "mediaUrl": "https://saleor.io/image-path",
+ "alt": "",
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_MEDIA_CREATE_QUERY,
+ variables=variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)["data"]["productMediaCreate"]
+
+ # then
+ assert not content["errors"]
+ # validate image file
+ product_image = product.media.last()
+ assert product_image.image.name.startswith("products/image-path_")
+ assert product_image.image.name.endswith(".png")
+ with product_image.image.open("rb") as img:
+ assert img.read() == image_content
+
+
def test_product_media_create_mutation_alt_character_limit(
monkeypatch, staff_api_client, product, permission_manage_products, media_root
):
diff --git a/saleor/thumbnail/tests/test_utils.py b/saleor/thumbnail/tests/test_utils.py
index 315f35b5cb..1686210a9f 100644
--- a/saleor/thumbnail/tests/test_utils.py
+++ b/saleor/thumbnail/tests/test_utils.py
@@ -213,3 +213,15 @@ def test_get_filename_from_url_with_query_params_path(mock_token_hex):
# then
assert result == f"image_{token_hex}.jpg"
+
+
+ ("url", "mimetype", "expected_extension"),
+ [
+ ("http://example.com/image", "image/jpeg", ".jpg"),
+ ("http://example.com/image", "image/png", ".png"),
+ ("http://example.com/image?token=12345/6789", "image/webp", ".webp"),
+ ],
+)
+def test_get_filename_from_url_without_extension(url, mimetype, expected_extension):
+ assert get_filename_from_url(url, mimetype).endswith(expected_extension)
diff --git a/saleor/thumbnail/utils.py b/saleor/thumbnail/utils.py
index 755c9f2c1e..745765f56f 100644
--- a/saleor/thumbnail/utils.py
+++ b/saleor/thumbnail/utils.py
@@ -1,3 +1,4 @@
+import mimetypes
import os
import secrets
from io import BytesIO
@@ -253,10 +254,13 @@ class ProcessedIconImage(ProcessedImage):
LOSSLESS_WEBP = True
-def get_filename_from_url(url: str) -> str:
+def get_filename_from_url(url: str, mime_type: str | None = None) -> str:
"""Prepare a unique filename for file from the URL to avoid overwriting."""
file_name = os.path.basename(urlparse(url).path)
name, format = os.path.splitext(file_name)
+ if not format and mime_type:
+ # If the URL does not include a file extension, guess it based on the mime type
+ format = mimetypes.guess_extension(mime_type, strict=False) or ""
name = name[:FILE_NAME_MAX_LENGTH]
hash = secrets.token_hex(nbytes=4)
return f"{name}_{hash}{format}"