Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add editorjs sanitizer (#6456)
Iga Karbowiakd99115b006a0
diff --git a/.isort.cfg b/.isort.cfgindex 98af768127..c4efe71a05 100644--- a/.isort.cfg+++ b/.isort.cfg@@ -1,2 +1,2 @@[settings]-known_third_party = Adyen,PIL,babel,boto3,braintree,celery,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,geolite2,google,google_measurement_protocol,graphene,graphene_django,graphene_federation,graphql,graphql_relay,html_to_draftjs,i18naddress,jaeger_client,jwt,kombu,markdown,measurement,mptt,oauthlib,openpyxl,opentracing,petl,phonenumber_field,phonenumbers,pkg_resources,prices,promise,pytest,pythonjsonlogger,pytimeparse,pytz,razorpay,requests,sentry_sdk,storages,stripe,templated_email,tqdm,versatileimagefield,weasyprint+known_third_party = Adyen,PIL,babel,boto3,braintree,celery,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,geolite2,google,google_measurement_protocol,graphene,graphene_django,graphene_federation,graphql,graphql_relay,html_to_draftjs,i18naddress,jaeger_client,jwt,kombu,markdown,measurement,mptt,oauthlib,openpyxl,opentracing,petl,phonenumber_field,phonenumbers,pkg_resources,prices,promise,pytest,pythonjsonlogger,pytimeparse,pytz,razorpay,requests,sentry_sdk,storages,stripe,templated_email,tqdm,urllib3,versatileimagefield,weasyprintdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex fd9e19cad0..c4c06800ab 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,8 +6,9 @@ All notable, unreleased changes to this project will be documented in this file.- Add metadata to shipping zones and shipping methods - #6340 by @maarcingebala- Drop deprecated meta mutations - #6422 by @maarcingebala-- Migrate draftjs content to editorjs format - by @IKarbowiak #6430+- Migrate draftjs content to editorjs format - #6430 by @IKarbowiak- Drop deprecated service accounts and webhooks API - #6431 by @maarcingebala+- Add editorjs sanitizer - #6456 by @IKarbowiak## 2.11.0diff --git a/saleor/core/sanitizers/__init__.py b/saleor/core/sanitizers/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/core/sanitizers/editorjs_sanitizer.py b/saleor/core/sanitizers/editorjs_sanitizer.pynew file mode 100644index 0000000000..4acfaa041b--- /dev/null+++ b/saleor/core/sanitizers/editorjs_sanitizer.py@@ -0,0 +1,75 @@+import re+import warnings++from urllib3.util import parse_url++BLACKLISTED_URL_SCHEMES = ("javascript",)+HYPERLINK_TAG_WITH_URL_PATTERN = (+ r"(.*?<a\s+href=\\?\")((?:https://|http://)\S+[^\\])(\\?\">)"+)+++def clean_editor_js(definitions: dict):+ """Sanitize a given EditorJS JSON definitions.++ Look for not allowed URLs, replaced them with `invalid` value, and clean valid ones.+ """+ blocks = definitions.get("blocks")++ if not blocks or not isinstance(blocks, list):+ return definitions++ for index, block in enumerate(blocks):+ block_type = block["type"]+ data = block.get("data")+ 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)+ blocks[index]["data"]["items"][item_index] = new_text+ else:+ text = block["data"]["text"]+ if not text:+ continue+ new_text = clean_text_data(text)++ blocks[index]["data"]["text"] = new_text++ return definitions+++def clean_text_data(text: str):+ """Look for url in text, check if URL is allowed and return the cleaned URL.++ By default, only the protocol ``javascript`` is denied.+ """++ if not text:+ return++ end_of_match = 0+ new_text = ""+ for match in re.finditer(HYPERLINK_TAG_WITH_URL_PATTERN, text):+ original_url = match.group(2)+ original_url.strip()++ url = parse_url(original_url)+ new_url = url.url+ if url.scheme in BLACKLISTED_URL_SCHEMES:+ warnings.warn(+ f"An invalid url was sent: {original_url} "+ f"-- Scheme: {url.scheme} is blacklisted"+ )+ new_url = "#invalid"++ new_text += match.group(1) + new_url + match.group(3)+ end_of_match = match.end()++ if end_of_match:+ new_text += text[end_of_match:]++ return new_text if new_text else textdiff --git a/saleor/core/tests/test_editorjs_sanitizer.py b/saleor/core/tests/test_editorjs_sanitizer.pynew file mode 100644index 0000000000..fad1fef737--- /dev/null+++ b/saleor/core/tests/test_editorjs_sanitizer.py@@ -0,0 +1,167 @@+import warnings+from unittest import mock++import pytest++from ..sanitizers.editorjs_sanitizer import clean_editor_js+++ "text",+ [+ "The Saleor Winter Sale is snowed under with seasonal offers. Unreal products "+ "at unreal prices. Literally, they are not real products, but the Saleor demo "+ "store is a genuine e-commerce leader.",+ 'The Saleor Winter Sale is snowed <a href="https://docs.saleor.io/docs/">',+ 'The Saleor Sale is snowed <a href="https://docs.saleor.io/docs/">. Test.',+ 'The Saleor Winter Sale is snowed <a href="https://docs.saleor.io/docs/">. '+ 'Test <a href="https://docs.saleor.io/docs/">.',+ "",+ "The Saleor Winter Sale is snowed <a >",+ ],+)+def test_clean_editor_js(text):+ # given+ data = {"blocks": [{"data": {"text": text}, "type": "paragraph"}]}++ # when+ result = clean_editor_js(data)++ # then+ assert result == data+++def test_clean_editor_js_no_blocks():+ # given+ data = {}++ # when+ result = clean_editor_js(data)++ # then+ assert result == data+++def test_clean_editor_js_no_data():+ # given+ data = {"blocks": []}++ # when+ result = clean_editor_js(data)++ # then+ assert result == data++[email protected]("saleor.core.sanitizers.editorjs_sanitizer.parse_url")+def test_clean_editor_js_invalid_url(parse_url_mock):+ # given+ response_mock = mock.Mock()+ response_mock.scheme = "javascript"+ mocked_parse = mock.Mock(return_value=response_mock)+ parse_url_mock.side_effect = mocked_parse++ url = "https://github.com/editor-js"+ text = (+ 'The Saleor Winter Sale is snowed under with seasonal offers. <a href="{}"> '+ "Unreal products at unreal prices. Literally, they are not real products, "+ "but the Saleor demo store is a genuine e-commerce leader."+ )++ data = {"blocks": [{"data": {"text": text.format(url)}, "type": "paragraph"}]}++ # when+ with warnings.catch_warnings(record=True) as warns:+ result = clean_editor_js(data)++ assert len(warns) == 1+ assert f"An invalid url was sent: {url}" in str(warns[0].message)++ # then+ new_url = "#invalid"+ assert result["blocks"][0]["data"]["text"] == text.format(new_url)+++def test_clean_editor_js_for_list():+ # given+ data = {+ "blocks": [+ {+ "data": {+ "text": "The Saleor Winter Sale is snowed "+ '<a href="https://docs.saleor.io/docs/">. Test.'+ },+ "type": "paragraph",+ },+ {+ "type": "list",+ "data": {+ "style": "unordered",+ "items": [+ "It is a block-styled editor "+ '<a href="https://docs.saleor.io/docs/">.',+ "It returns clean data output in JSON",+ "Designed to be extendable and pluggable with a simple API",+ "",+ ],+ },+ },+ ]+ }++ # when+ result = clean_editor_js(data)++ # then+ assert result == data++[email protected]("saleor.core.sanitizers.editorjs_sanitizer.parse_url")+def test_clean_editor_js_for_list_invalid_url(parse_url_mock):+ # given+ response_mock = mock.Mock()+ response_mock.scheme = "javascript"+ mocked_parse = mock.Mock(return_value=response_mock)+ parse_url_mock.side_effect = mocked_parse++ url1 = "https://docs.saleor.io/docs/"+ url2 = "https://github.com/editor-js"+ text1 = 'The Saleor Winter Sale is snowed <a href="{}">. Test.'+ item_text_with_url = 'It is a block-styled editor <a href="{}">.'++ data = {+ "blocks": [+ {"data": {"text": text1.format(url1)}, "type": "paragraph"},+ {+ "type": "list",+ "data": {+ "style": "unordered",+ "items": [+ "It returns clean data output in JSON",+ item_text_with_url.format(url2),+ "Designed to be extendable and pluggable with a simple API",+ ],+ },+ },+ ]+ }++ # when+ with warnings.catch_warnings(record=True) as warns:+ result = clean_editor_js(data)++ assert len(warns) == 2+ assert f"An invalid url was sent: {url1}" in str(warns[0].message)+ assert f"An invalid url was sent: {url2}" in str(warns[1].message)++ # then+ assert result["blocks"][0]["data"]["text"] == text1.format("#invalid")+ assert result["blocks"][1]["data"]["items"][1] == item_text_with_url.format(+ "#invalid"+ )+ assert (+ result["blocks"][1]["data"]["items"][0] == data["blocks"][1]["data"]["items"][0]+ )+ assert (+ result["blocks"][1]["data"]["items"][2] == data["blocks"][1]["data"]["items"][2]+ )diff --git a/saleor/page/migrations/0016_auto_20201112_0904.py b/saleor/page/migrations/0016_auto_20201112_0904.pynew file mode 100644index 0000000000..283003f5e5--- /dev/null+++ b/saleor/page/migrations/0016_auto_20201112_0904.py@@ -0,0 +1,34 @@+# Generated by Django 3.1 on 2020-11-12 09:04++from django.db import migrations++import saleor.core.db.fields+import saleor.core.sanitizers.editorjs_sanitizer+++class Migration(migrations.Migration):++ dependencies = [+ ("page", "0015_migrate_from_draftjs_to_editorjs_format"),+ ]++ operations = [+ migrations.AlterField(+ model_name="page",+ name="content_json",+ field=saleor.core.db.fields.SanitizedJSONField(+ blank=True,+ default=dict,+ sanitizer=saleor.core.sanitizers.editorjs_sanitizer.clean_editor_js,+ ),+ ),+ migrations.AlterField(+ model_name="pagetranslation",+ name="content_json",+ field=saleor.core.db.fields.SanitizedJSONField(+ blank=True,+ default=dict,+ sanitizer=saleor.core.sanitizers.editorjs_sanitizer.clean_editor_js,+ ),+ ),+ ]diff --git a/saleor/page/models.py b/saleor/page/models.pyindex 760fee1148..7019b09110 100644--- a/saleor/page/models.py+++ b/saleor/page/models.py@@ -1,9 +1,9 @@from django.db import models-from draftjs_sanitizer import clean_draft_jsfrom ..core.db.fields import SanitizedJSONFieldfrom ..core.models import ModelWithMetadata, PublishableModel, PublishedQuerySetfrom ..core.permissions import PagePermissions+from ..core.sanitizers.editorjs_sanitizer import clean_editor_jsfrom ..core.utils.translations import TranslationProxyfrom ..seo.models import SeoModel, SeoModelTranslation@@ -19,7 +19,7 @@ class Page(ModelWithMetadata, SeoModel, PublishableModel):title = models.CharField(max_length=250)content = models.TextField(blank=True)content_json = SanitizedJSONField(- blank=True, default=dict, sanitizer=clean_draft_js+ blank=True, default=dict, sanitizer=clean_editor_js)created = models.DateTimeField(auto_now_add=True)@@ -42,7 +42,7 @@ class PageTranslation(SeoModelTranslation):title = models.CharField(max_length=255, blank=True)content = models.TextField(blank=True)content_json = SanitizedJSONField(- blank=True, default=dict, sanitizer=clean_draft_js+ blank=True, default=dict, sanitizer=clean_editor_js)class Meta:diff --git a/saleor/product/migrations/0131_auto_20201112_0904.py b/saleor/product/migrations/0131_auto_20201112_0904.pynew file mode 100644index 0000000000..f51969d379--- /dev/null+++ b/saleor/product/migrations/0131_auto_20201112_0904.py@@ -0,0 +1,70 @@+# Generated by Django 3.1 on 2020-11-12 09:04++from django.db import migrations++import saleor.core.db.fields+import saleor.core.sanitizers.editorjs_sanitizer+++class Migration(migrations.Migration):++ dependencies = [+ ("product", "0130_migrate_from_draftjs_to_editorjs_format"),+ ]++ operations = [+ migrations.AlterField(+ model_name="category",+ name="description_json",+ field=saleor.core.db.fields.SanitizedJSONField(+ blank=True,+ default=dict,+ sanitizer=saleor.core.sanitizers.editorjs_sanitizer.clean_editor_js,+ ),+ ),+ migrations.AlterField(+ model_name="categorytranslation",+ name="description_json",+ field=saleor.core.db.fields.SanitizedJSONField(+ blank=True,+ default=dict,+ sanitizer=saleor.core.sanitizers.editorjs_sanitizer.clean_editor_js,+ ),+ ),+ migrations.AlterField(+ model_name="collection",+ name="description_json",+ field=saleor.core.db.fields.SanitizedJSONField(+ blank=True,+ default=dict,+ sanitizer=saleor.core.sanitizers.editorjs_sanitizer.clean_editor_js,+ ),+ ),+ migrations.AlterField(+ model_name="collectiontranslation",+ name="description_json",+ field=saleor.core.db.fields.SanitizedJSONField(+ blank=True,+ default=dict,+ sanitizer=saleor.core.sanitizers.editorjs_sanitizer.clean_editor_js,+ ),+ ),+ migrations.AlterField(+ model_name="product",+ name="description_json",+ field=saleor.core.db.fields.SanitizedJSONField(+ blank=True,+ default=dict,+ sanitizer=saleor.core.sanitizers.editorjs_sanitizer.clean_editor_js,+ ),+ ),+ migrations.AlterField(+ model_name="producttranslation",+ name="description_json",+ field=saleor.core.db.fields.SanitizedJSONField(+ blank=True,+ default=dict,+ sanitizer=saleor.core.sanitizers.editorjs_sanitizer.clean_editor_js,+ ),+ ),+ ]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 990a7f54a1..f75cd8d4d0 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -5,14 +5,12 @@ from uuid import uuid4from django.conf import settingsfrom django.contrib.postgres.aggregates import StringAggfrom django.db import models-from django.db.models import JSONField # type: ignorefrom django.db.models import Case, Count, F, FilteredRelation, Q, Sum, Value, Whenfrom django.db.models.functions import Coalescefrom django.urls import reversefrom django.utils.encoding import smart_textfrom django_measurement.models import MeasurementFieldfrom django_prices.models import MoneyField-from draftjs_sanitizer import clean_draft_jsfrom measurement.measures import Weightfrom mptt.managers import TreeManagerfrom mptt.models import MPTTModel@@ -26,6 +24,7 @@ from ..core.models import (SortableModel,)from ..core.permissions import ProductPermissions, ProductTypePermissions+from ..core.sanitizers.editorjs_sanitizer import clean_editor_jsfrom ..core.utils import build_absolute_urifrom ..core.utils.draftjs import json_content_to_raw_textfrom ..core.utils.translations import TranslationProxy@@ -47,7 +46,9 @@ class Category(MPTTModel, ModelWithMetadata, SeoModel):name = models.CharField(max_length=250)slug = models.SlugField(max_length=255, unique=True, allow_unicode=True)description = models.TextField(blank=True)- description_json = JSONField(blank=True, default=dict)+ description_json = SanitizedJSONField(+ blank=True, default=dict, sanitizer=clean_editor_js+ )parent = models.ForeignKey("self", null=True, blank=True, related_name="children", on_delete=models.CASCADE)@@ -71,7 +72,9 @@ class CategoryTranslation(SeoModelTranslation):)name = models.CharField(max_length=128)description = models.TextField(blank=True)- description_json = JSONField(blank=True, default=dict)+ description_json = SanitizedJSONField(+ blank=True, default=dict, sanitizer=clean_editor_js+ )class Meta:unique_together = (("language_code", "category"),)@@ -243,7 +246,7 @@ class Product(SeoModel, ModelWithMetadata, PublishableModel):slug = models.SlugField(max_length=255, unique=True, allow_unicode=True)description = models.TextField(blank=True)description_json = SanitizedJSONField(- blank=True, default=dict, sanitizer=clean_draft_js+ blank=True, default=dict, sanitizer=clean_editor_js)category = models.ForeignKey(Category,@@ -335,7 +338,7 @@ class ProductTranslation(SeoModelTranslation):name = models.CharField(max_length=250)description = models.TextField(blank=True)description_json = SanitizedJSONField(- blank=True, default=dict, sanitizer=clean_draft_js+ blank=True, default=dict, sanitizer=clean_editor_js)class Meta:@@ -873,7 +876,9 @@ class Collection(SeoModel, ModelWithMetadata, PublishableModel):)background_image_alt = models.CharField(max_length=128, blank=True)description = models.TextField(blank=True)- description_json = JSONField(blank=True, default=dict)+ description_json = SanitizedJSONField(+ blank=True, default=dict, sanitizer=clean_editor_js+ )translated = TranslationProxy()@@ -891,7 +896,9 @@ class CollectionTranslation(SeoModelTranslation):)name = models.CharField(max_length=128)description = models.TextField(blank=True)- description_json = JSONField(blank=True, default=dict)+ description_json = SanitizedJSONField(+ blank=True, default=dict, sanitizer=clean_editor_js+ )class Meta:unique_together = (("language_code", "collection"),)