Skip to content

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

Fix rich-text attribute validation for non-text blocks (#11484)

Iga Karbowiak43f72a14a242
diff --git a/saleor/core/tests/test_editorjs.py b/saleor/core/tests/test_editorjs.py
index 0d9ec8e7fa..02bc14b174 100644
--- a/saleor/core/tests/test_editorjs.py
+++ b/saleor/core/tests/test_editorjs.py
@@ -240,6 +240,29 @@ def test_clean_editor_js_for_complex_description():
],
},
},
+ {
+ "type": "image",
+ "data": {
+ "file": {
+ "url": "https://codex.so/public/app/img/external/codex2x.png"
+ },
+ "caption": "Test caption",
+ "withBorder": False,
+ "stretched": False,
+ "withBackground": False,
+ },
+ },
+ {
+ "type": "embed",
+ "data": {
+ "service": "youtube",
+ "source": "https://www.youtube.com/erz",
+ "embed": "https://www.youtube.com/embed/erz",
+ "width": 580,
+ "height": 320,
+ "caption": "How To Use",
+ },
+ },
]
}
@@ -265,4 +288,9 @@ def test_clean_editor_js_for_complex_description():
" warm clothes"
" test item"
" item test"
+ " https://codex.so/public/app/img/external/codex2x.png"
+ " Test caption"
+ " https://www.youtube.com/erz"
+ " https://www.youtube.com/embed/erz"
+ " How To Use"
)
diff --git a/saleor/core/utils/editorjs.py b/saleor/core/utils/editorjs.py
index 599ea7013c..c47318427e 100644
--- a/saleor/core/utils/editorjs.py
+++ b/saleor/core/utils/editorjs.py
@@ -1,6 +1,6 @@
import re
import warnings
-from typing import Dict, Optional
+from typing import Dict, List, Optional
from django.utils.html import strip_tags
from urllib3.util import parse_url
@@ -8,6 +8,12 @@ from urllib3.util import parse_url
BLACKLISTED_URL_SCHEMES = ("javascript",)
HYPERLINK_TAG_WITH_URL_PATTERN = r"(.*?<a\s+href=\\?\")(\w+://\S+[^\\])(\\?\">)"
+ITEM_TYPE_TO_CLEAN_FUNC_MAP = {
+ "list": lambda *params: clean_list_item(*params),
+ "image": lambda *params: clean_image_item(*params),
+ "embed": lambda *params: clean_embed_item(*params),
+}
+
def clean_editor_js(definitions: Optional[Dict], *, to_string: bool = False):
"""Sanitize a given EditorJS JSON definitions.
@@ -25,7 +31,7 @@ def clean_editor_js(definitions: Optional[Dict], *, to_string: bool = False):
if not blocks or not isinstance(blocks, list):
return "" if to_string else definitions
- plain_text_list = []
+ plain_text_list: List[str] = []
for index, block in enumerate(blocks):
block_type = block["type"]
@@ -33,28 +39,66 @@ def clean_editor_js(definitions: Optional[Dict], *, to_string: bool = False):
if not data or not isinstance(data, dict):
continue
- if block_type == "list":
- for item_index, item in enumerate(block["data"]["items"]):
- if not item:
- continue
- new_text = clean_text_data(item)
- if to_string:
- plain_text_list.append(strip_tags(new_text))
- else:
- blocks[index]["data"]["items"][item_index] = new_text
+ params = [blocks, block, plain_text_list, to_string, index]
+ if clean_func := ITEM_TYPE_TO_CLEAN_FUNC_MAP.get(block_type):
+ clean_func(*params)
else:
- text = block["data"].get("text")
- if not text:
- continue
- new_text = clean_text_data(text)
- if to_string:
- plain_text_list.append(strip_tags(new_text))
- else:
- blocks[index]["data"]["text"] = new_text
+ clean_other_items(*params)
return " ".join(plain_text_list) if to_string else definitions
+def clean_list_item(blocks, block, plain_text_list, to_string, index):
+ for item_index, item in enumerate(block["data"]["items"]):
+ if not item:
+ return
+ new_text = clean_text_data(item)
+ if to_string:
+ plain_text_list.append(strip_tags(new_text))
+ else:
+ blocks[index]["data"]["items"][item_index] = new_text
+
+
+def clean_image_item(blocks, block, plain_text_list, to_string, index):
+ file_url = block["data"].get("file", {}).get("url")
+ caption = block["data"].get("caption")
+ if file_url:
+ file_url = clean_text_data(file_url)
+ if to_string:
+ plain_text_list.append(strip_tags(file_url))
+ else:
+ blocks[index]["data"]["file"]["ulr"] = file_url
+ if caption:
+ caption = clean_text_data(caption)
+ if to_string:
+ plain_text_list.append(strip_tags(caption))
+ else:
+ blocks[index]["data"]["caption"] = caption
+
+
+def clean_embed_item(blocks, block, plain_text_list, to_string, index):
+ for field in ["source", "embed", "caption"]:
+ data = block["data"].get(field)
+ if not data:
+ return
+ data = clean_text_data(data)
+ if to_string:
+ plain_text_list.append(strip_tags(data))
+ else:
+ blocks[index]["data"][field] = data
+
+
+def clean_other_items(blocks, block, plain_text_list, to_string, index):
+ text = block["data"].get("text")
+ if not text:
+ return
+ new_text = clean_text_data(text)
+ if to_string:
+ plain_text_list.append(strip_tags(new_text))
+ else:
+ blocks[index]["data"]["text"] = new_text
+
+
def clean_text_data(text: str) -> str:
"""Look for url in text, check if URL is allowed and return the cleaned URL.
diff --git a/saleor/graphql/attribute/tests/test_utils.py b/saleor/graphql/attribute/tests/test_utils.py
index 8ef3bb447e..ae11ecf788 100644
--- a/saleor/graphql/attribute/tests/test_utils.py
+++ b/saleor/graphql/attribute/tests/test_utils.py
@@ -1806,6 +1806,110 @@ def test_validate_numeric_attributes_value_required(
assert errors[0].code == ProductErrorCode.REQUIRED.value
[email protected]("creation", [True, False])
+def test_validate_rich_text_attributes_input_for_product_only_embed_block(
+ creation, rich_text_attribute, product_type
+):
+ # given
+ rich_text_attribute.value_required = True
+ rich_text_attribute.save(update_fields=["value_required"])
+
+ input_data = [
+ (
+ rich_text_attribute,
+ AttrValuesInput(
+ global_id=graphene.Node.to_global_id(
+ "Attribute", rich_text_attribute.pk
+ ),
+ values=["12.34"],
+ file_url=None,
+ content_type=None,
+ references=[],
+ rich_text={
+ "time": 1670422589533,
+ "blocks": [
+ {
+ "id": "6sWdDeIffS",
+ "type": "embed",
+ "data": {
+ "service": "youtube",
+ "source": "https://www.youtube.com/watch?v=xyz",
+ "embed": "https://www.youtube.com/embed/xyz",
+ "width": 580,
+ "height": 320,
+ "caption": "How To Use",
+ },
+ }
+ ],
+ "version": "2.22.2",
+ },
+ ),
+ ),
+ ]
+
+ # when
+ errors = validate_attributes_input(
+ input_data,
+ product_type.product_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
+ )
+
+ # then
+ assert not errors
+
+
[email protected]("creation", [True, False])
+def test_validate_rich_text_attributes_input_for_product_only_image_block(
+ creation, rich_text_attribute, product_type
+):
+ # given
+ rich_text_attribute.value_required = True
+ rich_text_attribute.save(update_fields=["value_required"])
+
+ input_data = [
+ (
+ rich_text_attribute,
+ AttrValuesInput(
+ global_id=graphene.Node.to_global_id(
+ "Attribute", rich_text_attribute.pk
+ ),
+ values=["12.34"],
+ file_url=None,
+ content_type=None,
+ references=[],
+ rich_text={
+ "time": 1670422589533,
+ "blocks": [
+ {
+ "id": "6n7TFTMU8y",
+ "type": "image",
+ "data": {
+ "file": {"url": "https://codex.so/public/codex2x.png"},
+ "caption": "",
+ "withBorder": False,
+ "stretched": False,
+ "withBackground": False,
+ },
+ }
+ ],
+ },
+ ),
+ ),
+ ]
+
+ # when
+ errors = validate_attributes_input(
+ input_data,
+ product_type.product_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
+ )
+
+ # then
+ assert not errors
+
+
def test_clean_file_url_in_attribute_assignment_mixin(site_settings):
# given
name = "Test.jpg"