Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix product media create with an image URL containing query params (#17522)
Tomasz Szymański10379afda08e
diff --git a/saleor/thumbnail/tests/test_utils.py b/saleor/thumbnail/tests/test_utils.pyindex db5d308ed6..315f35b5cb 100644--- a/saleor/thumbnail/tests/test_utils.py+++ b/saleor/thumbnail/tests/test_utils.py@@ -1,5 +1,5 @@from unittest import mock-from unittest.mock import MagicMock+from unittest.mock import MagicMock, patchimport grapheneimport pytest@@ -185,3 +185,31 @@ def test_get_filename_from_url_with_short_name_is_not_trimmed():assert result.endswith(file_format)assert result != f"{file_name}.{file_format}"assert len(result.split("_")[0]) < FILE_NAME_MAX_LENGTH+++@patch("saleor.thumbnail.utils.secrets.token_hex")+def test_get_filename_from_url_with_query_params(mock_token_hex):+ # given+ token_hex = 1234+ mock_token_hex.return_value = token_hex+ url = "http://example.com/image.jpg?query=param"++ # when+ result = get_filename_from_url(url)++ # then+ assert result == f"image_{token_hex}.jpg"+++@patch("saleor.thumbnail.utils.secrets.token_hex")+def test_get_filename_from_url_with_query_params_path(mock_token_hex):+ # given+ token_hex = 1234+ mock_token_hex.return_value = token_hex+ url = "http://example.com/image.jpg?token=12345/6789"++ # when+ result = get_filename_from_url(url)++ # then+ assert result == f"image_{token_hex}.jpg"diff --git a/saleor/thumbnail/utils.py b/saleor/thumbnail/utils.pyindex 76aa2e4e82..755c9f2c1e 100644--- a/saleor/thumbnail/utils.py+++ b/saleor/thumbnail/utils.py@@ -2,6 +2,7 @@ import osimport secretsfrom io import BytesIOfrom typing import TYPE_CHECKING, Optional+from urllib.parse import urlparseimport grapheneimport magic@@ -254,7 +255,7 @@ class ProcessedIconImage(ProcessedImage):def get_filename_from_url(url: str) -> str:"""Prepare a unique filename for file from the URL to avoid overwriting."""- file_name = os.path.basename(url)+ file_name = os.path.basename(urlparse(url).path)name, format = os.path.splitext(file_name)name = name[:FILE_NAME_MAX_LENGTH]hash = secrets.token_hex(nbytes=4)