Skip to content

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

Fix CVE-2026-22849

Mikail Kocakb67a0b9d9f24
diff --git a/pyproject.toml b/pyproject.toml
index 7a56f4cdc8..0b096cb11e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -85,6 +85,8 @@ dependencies = [
"django-storages[google]~=1.11",
"python-magic>=0.4.27,<0.5 ; sys_platform != 'win32'",
"python-magic-bin>=0.4.14,<0.5 ; sys_platform == 'win32'",
+ "nh3>=0.2.20",
+ "idna>=3.10",
]
[project.urls]
diff --git a/saleor/core/cleaners/__init__.py b/saleor/core/cleaners/__init__.py
new file mode 100644
index 0000000000..666f6ae4ff
--- /dev/null
+++ b/saleor/core/cleaners/__init__.py
@@ -0,0 +1,15 @@
+from .urls import (
+ URL_SCHEME_CLEANERS,
+ URLCleanerError,
+ clean_mailto,
+ clean_tel,
+ normalize_host,
+)
+
+__all__ = (
+ "URL_SCHEME_CLEANERS",
+ "URLCleanerError",
+ "clean_tel",
+ "clean_mailto",
+ "normalize_host",
+)
diff --git a/saleor/core/cleaners/html.py b/saleor/core/cleaners/html.py
new file mode 100644
index 0000000000..b3217592a0
--- /dev/null
+++ b/saleor/core/cleaners/html.py
@@ -0,0 +1,87 @@
+import json
+import os
+import warnings
+from copy import deepcopy
+from dataclasses import dataclass, field
+from typing import Self
+
+import nh3
+
+from ..deprecations import SaleorDeprecationWarning
+
+
+@dataclass
+class HtmlCleanerSettings:
+ allowed_schemes: set[str] = field(default_factory=set)
+ allowed_attributes: dict[str, set[str]] = field(
+ default_factory=lambda: deepcopy(nh3.ALLOWED_ATTRIBUTES)
+ )
+
+ # NOTE: nh3 doesn't expose the default values, however it's OK as
+ # the default value is empty https://github.com/rust-ammonia/ammonia/blob/6d803b5677006947da7d2f495dbae83090db4909/src/lib.rs#L447
+ allowed_attribute_values: dict[str, dict[str, set[str]]] = field(
+ default_factory=dict
+ )
+
+ # Configures the 'rel' attribute that will be added on links. `None` disables it.
+ #
+ # Recommended value: 'noopener noreferrer'
+ #
+ # - noopener: This prevents a particular type of XSS attack, and should usually be turned on for untrusted HTML.
+ # - noreferrer: This prevents the browser from sending the source URL to the website that is linked to.
+ # - nofollow: This prevents search engines from using this link for ranking, which disincentivizes spammers.
+ #
+ # Learn more: https://nh3.readthedocs.io/en/latest/#nh3.Cleaner
+ #
+ link_rel: str | None = "noopener noreferrer"
+
+ def reload(self) -> Self:
+ # NOTE: 'or None' is needed as blank string should be treated as None
+ self.link_rel = os.getenv("EDITOR_JS_LINK_REL") or None
+ if self.link_rel is None:
+ warnings.warn(
+ (
+ "EDITOR_JS_LINK_REL=None default will be removed in Saleor 3.23.0, "
+ 'use EDITOR_JS_LINK_REL="noopener noreferrer" instead'
+ ),
+ category=SaleorDeprecationWarning,
+ stacklevel=2,
+ )
+
+ if allowed_schemes_str := os.getenv("UNSAFE_EDITOR_JS_ALLOWED_URL_SCHEMES"):
+ # This is deprecated, each URL scheme must have a cleaner implemented
+ # we cannot continue to allow to add custom schemes without cleaners
+ # as this is risky.
+ warnings.warn(
+ (
+ "UNSAFE_EDITOR_JS_ALLOWED_URL_SCHEMES will be removed in Saleor 3.23.0, "
+ "open a feature request at https://github.com/saleor/saleor/issues "
+ "to add out of the box support for the URL scheme(s) you need"
+ ),
+ category=SaleorDeprecationWarning,
+ stacklevel=3,
+ )
+ self.allowed_schemes = {x.strip() for x in allowed_schemes_str.split(",")}
+
+ if allowed_attributes_str := os.getenv("EDITOR_JS_ALLOWED_ATTRIBUTES"):
+ for html_tag, allowed_attributes in json.loads(
+ allowed_attributes_str
+ ).items():
+ attr_list = self.allowed_attributes.setdefault(html_tag, set())
+ attr_list.update(allowed_attributes)
+
+ if allowed_values_str := os.getenv("EDITOR_JS_ALLOWED_ATTRIBUTE_VALUES"):
+ allowed_values: dict[str, dict[str, list[str]]] = json.loads(
+ allowed_values_str
+ )
+
+ # Converts raw values' list[str] to set[str] type as nh3 wants `set[str]`
+ for key, nested_dict in allowed_values.items():
+ self.allowed_attribute_values[key] = {
+ k: set(v) for k, v in nested_dict.items()
+ }
+ return self
+
+ @classmethod
+ def parse(cls) -> Self:
+ return cls().reload()
diff --git a/saleor/core/cleaners/tests/__init__.py b/saleor/core/cleaners/tests/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/core/cleaners/tests/test_urls.py b/saleor/core/cleaners/tests/test_urls.py
new file mode 100644
index 0000000000..0955ec01ca
--- /dev/null
+++ b/saleor/core/cleaners/tests/test_urls.py
@@ -0,0 +1,129 @@
+import pytest
+
+from .. import clean_mailto, clean_tel
+
+
+ "input_url",
+ [
+ # All valid inputs (should be unchanged by the cleaner)
+ "tel:1234567890",
+ "tel:+1234567890",
+ "tel:+1-202-555-0123",
+ "tel:+1(202)555.0123",
+ "tel:*123#",
+ "tel:#21#",
+ "tel:+49(30)123456",
+ "tel:123;ext=456",
+ "tel:+1;phone-context=example.com",
+ "tel:+1;isub=12345",
+ "tel:+123%;ext=1",
+ "tel:1-2-3-4-5",
+ "tel:1...(2)...3",
+ "tel:((123))",
+ "tel:+1.-()",
+ "tel:",
+ "tel:+",
+ "tel:*",
+ "tel:#",
+ ],
+)
+def test_clean_url_tel_scheme_valid(input_url: str):
+ """Test valid `tel` URL inputs are unchanged (RFC 3966)."""
+ actual = clean_tel(input_url)
+ assert actual == input_url, "URL shouldn't have been changed"
+
+
+ ("input_url", "expected_cleaned_url"),
+ [
+ # It must be 'tel:' not 'tel://'
+ ("tel://", "tel:%2F%2F"),
+ ('tel:+3300"<>', "tel:+3300%22%3C%3E"),
+ ("tel:+3300\n", "tel:+3300%0A"),
+ # Ensures all parts/components are quoted
+ ('tel:"\n#"\n;"\n', "tel:%22%0A#%22%0A;%22%0A"),
+ ],
+)
+def test_clean_url_tel_scheme_invalid(input_url: str, expected_cleaned_url: str):
+ """Test invalid characters in `tel` URLs are quoted."""
+ actual = clean_tel(input_url)
+ assert actual == expected_cleaned_url
+
+
+ ("input_url", "changed_to"),
+ [
+ ("mailto:", None),
+ ("mailto:chris@[::1]", None), # IPv6 should work
+ (
+ # Should quote all parts
+ 'mailto:"@example.com?"="',
+ "mailto:%[email protected]?%22=%22",
+ ),
+ (
+ # Should quote all parts, including control characters
+ "mailto:\[email protected]?\n=\n",
+ "mailto:%[email protected]?%0A=%0A",
+ ),
+ # Based on https://www.rfc-editor.org/rfc/rfc6068#section-6
+ ("mailto:[email protected]", None),
+ ("mailto:[email protected]?subject=current-issue", None),
+ ("mailto:[email protected]?body=send%20current-issue", None),
+ (
+ "mailto:[email protected]?body=send%20current-issue%0D%0Asend%20index",
+ None,
+ ),
+ ("mailto:[email protected]?In-Reply-To=%[email protected]%3E", None),
+ ("mailto:[email protected]?body=subscribe%20bamboo-l", None),
+ ("mailto:[email protected][email protected]&body=hello", None),
+ ("mailto:%22not%40me%[email protected]", None),
+ ("mailto:%22oh%5C%5Cno%[email protected]", None),
+ (
+ "mailto:%22%5C%5C%5C%22it's%5C%20ugly%5C%5C%5C%22%[email protected]",
+ # We don't allow single quotes (')
+ "mailto:%22%5C%5C%5C%22it%27s%5C%20ugly%5C%5C%5C%22%[email protected]",
+ ),
+ ("mailto:[email protected]?subject=caf%C3%A9", None),
+ ("mailto:[email protected]?subject=%3D%3Futf-8%3FQ%3Fcaf%3DC3%3DA9%3F%3D", None),
+ ("mailto:[email protected]?subject=%3D%3Fiso-8859-1%3FQ%3Fcaf%3DE9%3F%3D", None),
+ ("mailto:[email protected]?subject=caf%C3%A9&body=caf%C3%A9", None),
+ (
+ "mailto:user@%E7%B4%8D%E8%B1%86.example.org?subject=Test&body=NATTO",
+ # We IDNA encode unicode characters
+ "mailto:[email protected]?subject=Test&body=NATTO",
+ ),
+ # Shouldn't be getting re-quoted when something was already quoted (%25)
+ ("mailto:foo%[email protected]", None),
+ ],
+)
+def test_clean_url_mailto_scheme_valid(input_url: str, changed_to: str | None):
+ """Test valid `mailto` URL inputs are unchanged (RFC 6068)."""
+ changed_to = changed_to or input_url
+ actual = clean_mailto(input_url)
+ assert actual == changed_to
+
+
+ ("_case", "input_url", "expected_error"),
+ [
+ (
+ "rejects mailto URIs that contain too many addresses",
+ "mailto:" + ",".join(["[email protected]"] * 11),
+ "Too many addresses in mailto URL",
+ ),
+ (
+ "rejects invalid domains",
+ 'mailto:foo@Exam"ple.com',
+ "Invalid characters found in hostname",
+ ),
+ ("rejects invalid IPv6", "mailto:chris@[not-an-ip]", "Invalid IPv6 address"),
+ ],
+)
+def test_clean_url_mailto_scheme_invalid_urls(
+ _case: str, input_url: str, expected_error: str
+):
+ with pytest.raises(ValueError, match=expected_error):
+ clean_mailto(input_url)
diff --git a/saleor/core/cleaners/urls.py b/saleor/core/cleaners/urls.py
new file mode 100644
index 0000000000..01e04ef291
--- /dev/null
+++ b/saleor/core/cleaners/urls.py
@@ -0,0 +1,145 @@
+import ipaddress
+import urllib.parse
+from typing import Protocol
+
+import idna
+
+MAILTO_SAFE_CHARS = ".-_+,"
+
+
+class UrlCleaner(Protocol):
+ def __call__(self, dirty_url: str) -> str: ...
+
+
+class URLCleanerError(ValueError):
+ """Base exception class for all URL cleaner-related exceptions."""
+
+
+class InvalidHostname(URLCleanerError):
+ """Raised when an invalid domain or hostname is provided."""
+
+
+class InvalidURL(URLCleanerError):
+ """Raised when the URL syntax is wrong."""
+
+
+class InvalidUsage(RuntimeError):
+ """Raised when a cleaner function wasn't used properly, indicates a code bug."""
+
+
+def normalize_host(dirty_domain: str) -> str:
+ """Normalize a hostname/domain field."""
+
+ dirty_domain = dirty_domain.lower()
+
+ # If it's an IPv6 address, then try to parse it and return the normalized
+ # value from Python's ipaddress module
+ if dirty_domain.startswith("["):
+ dirty_domain = dirty_domain.strip("[]")
+ try:
+ clean_ip = str(ipaddress.IPv6Address(dirty_domain))
+ return f"[{clean_ip}]"
+ except ipaddress.AddressValueError as exc:
+ raise InvalidHostname("Invalid IPv6 address") from exc
+
+ # If it's not IPv6, then we use idna to validate & to normalize
+ try:
+ parts = [
+ idna.encode(
+ part,
+ strict=True,
+ std3_rules=True, # Follows RFC 1123 for the hostname
+ ).decode("utf-8")
+ for part in dirty_domain.split(".")
+ ]
+ except idna.IDNAError as exc:
+ raise InvalidHostname("Invalid characters found in hostname") from exc
+
+ return ".".join(parts)
+
+
+def clean_tel(dirty_url: str) -> str:
+ """Clean a 'tel' URL (e.g., 'tel:+3312345678')."""
+
+ scheme, _, dirty_tel = dirty_url.partition(":")
+
+ # This should never happen, as a safeguard we are raising
+ if scheme != "tel":
+ raise InvalidUsage(f"Expected url scheme to be 'tel', found {scheme} instead")
+ # Keeps special characters listed by RFC 3966 as is, and encodes anything else
+ # (such as dangerous characters like "<>)
+ cleaned_path = urllib.parse.quote(dirty_tel, safe="+-.()*#;=%")
+ return f"tel:{cleaned_path}"
+
+
+def clean_mailto(
+ dirty_url: str,
+ *,
+ max_address_count: int = 10,
+ max_header_count: int = 10,
+) -> str:
+ """Clean a mailto URL based on RFC 6068 (leniently)."""
+
+ scheme, _, dirty_url = dirty_url.partition(":")
+
+ if scheme != "mailto":
+ raise InvalidUsage(
+ f"Expected url scheme to be 'mailto', found {scheme} instead"
+ )
+
+ # raw_dirty_addr_list is the address list before the '?' character, e.g., from:
+ # `[email protected]?body=text`
+ raw_dirty_addr_list, _, raw_dirty_qs = dirty_url.partition("?")
+
+ # Retrieves the list of email addresses before the '?' delimiter (if any)
+ #
+ # Note: an empty list of addresses is allowed (per RFC 6068), i.e.,
+ # the user can do `mailto:?<headers>` instead of
+ # `mailto:[email protected]?<headers>` - this is used for things like:
+ #
+ # Thus we shouldn't raise if we see an empty list.
+ if raw_dirty_addr_list:
+ dirty_addr_list = raw_dirty_addr_list.split(",", maxsplit=max_address_count + 1)
+ if len(dirty_addr_list) > max_address_count:
+ raise InvalidURL("Too many addresses in mailto URL")
+ else:
+ dirty_addr_list = []
+
+ cleaned_addresses = []
+ for dirty_addr in dirty_addr_list:
+ # Example: user@domain
+ dirty_local_part, _, dirty_domain = dirty_addr.partition("@")
+
+ if not all((dirty_local_part, dirty_domain)):
+ raise InvalidURL("Invalid email address")
+
+ dirty_local_part = urllib.parse.unquote(dirty_local_part)
+ clean_local_part = urllib.parse.quote(dirty_local_part, safe=MAILTO_SAFE_CHARS)
+
+ dirty_domain = urllib.parse.unquote(dirty_domain)
+ clean_domain = normalize_host(dirty_domain)
+ cleaned_addresses.append(f"{clean_local_part}@{clean_domain}")
+
+ cleaned_url = "mailto:"
+ if cleaned_addresses:
+ cleaned_url += ",".join(cleaned_addresses)
+
+ # Clean the email headers (query), the RFC specs are similar to HTTP URLs
+ # thus we can use urllib
+ if raw_dirty_qs:
+ headers_dict = urllib.parse.parse_qs(
+ raw_dirty_qs, max_num_fields=max_header_count
+ )
+ cleaned_raw_headers = urllib.parse.urlencode(
+ headers_dict,
+ doseq=True,
+ safe=f"{MAILTO_SAFE_CHARS}@",
+ quote_via=urllib.parse.quote,
+ )
+ cleaned_url += f"?{cleaned_raw_headers}"
+
+ return cleaned_url
+
+
+URL_SCHEME_CLEANERS: dict[str, UrlCleaner] = {"mailto": clean_mailto, "tel": clean_tel}
diff --git a/saleor/core/deprecations.py b/saleor/core/deprecations.py
new file mode 100644
index 0000000000..4a83a9b37b
--- /dev/null
+++ b/saleor/core/deprecations.py
@@ -0,0 +1,5 @@
+class SaleorDeprecationWarning(UserWarning):
+ """Custom deprecation warning as DeprecationWarning is usually ignored.
+
+ Learn more: https://sethmlarson.dev/deprecations-via-warnings-dont-work-for-python-libraries
+ """
diff --git a/saleor/core/management/commands/clean_editorjs_fields.py b/saleor/core/management/commands/clean_editorjs_fields.py
new file mode 100644
index 0000000000..8769aefb28
--- /dev/null
+++ b/saleor/core/management/commands/clean_editorjs_fields.py
@@ -0,0 +1,242 @@
+import difflib
+import json
+import traceback
+
+from django.core.exceptions import ValidationError
+from django.core.management.base import BaseCommand, CommandError
+from django.db import models
+
+from ....attribute.models import AttributeValue, AttributeValueTranslation
+from ....discount.models import (
+ Promotion,
+ PromotionRule,
+ PromotionRuleTranslation,
+ PromotionTranslation,
+)
+from ....page.models import Page, PageTranslation
+from ....product.models import (
+ Category,
+ CategoryTranslation,
+ Collection,
+ CollectionTranslation,
+ Product,
+ ProductTranslation,
+)
+from ....shipping.models import ShippingMethod, ShippingMethodTranslation
+from ...utils.editorjs import clean_editor_js
+
+# ((<model class>, <field to clean>), ...)
+MODELS: tuple[tuple[type[models.Model], str], ...] = (
+ # Product module
+ (Product, "description"),
+ (ProductTranslation, "description"),
+ (Collection, "description"),
+ (CollectionTranslation, "description"),
+ (Category, "description"),
+ (CategoryTranslation, "description"),
+ # Page module
+ (Page, "content"),
+ (PageTranslation, "content"),
+ # Shipping module
+ (ShippingMethod, "description"),
+ (ShippingMethodTranslation, "description"),
+ # Discount module
+ (Promotion, "description"),
+ (PromotionTranslation, "description"),
+ (PromotionRule, "description"),
+ (PromotionRuleTranslation, "description"),
+ # Attribute module
+ (AttributeValue, "rich_text"),
+ (AttributeValueTranslation, "rich_text"),
+)
+
+
+class Command(BaseCommand):
+ help = "Runs the Editorjs cleaner against all rows and all models."
+
+ def add_arguments(self, parser):
+ parser.add_argument(
+ "--apply",
+ dest="is_dry_run",
+ action="store_false",
+ help=(
+ "When provided, it applies the changes instead of only printing what "
+ "it would do (dry run)"
+ ),
+ )
+ parser.add_argument(
+ "--stop-on-error",
+ action="store_true",
+ help=(
+ "When provided, the script doesn't continue migrating the data "
+ "when invalid data is found (e.g., invalid EditorJS syntax)"
+ ),
+ )
+ parser.add_argument(
+ "--progress",
+ dest="report_frequency",
+ type=int,
+ default=1000,
+ metavar="N",
+ help="Reports the progress (in percents) every N rows processed",
+ )
+ parser.add_argument(
+ "--verbose",
+ action="store_true",
+ help="Enable debug logs and send more details",
+ )
+
+ model_names = [model.__name__ for [model, _field] in MODELS]
+
+ model_filter = parser.add_mutually_exclusive_group()
+ model_filter.add_argument(
+ "--only",
+ type=str,
+ choices=model_names,
+ action="extend",
+ nargs="+",
+ metavar="MODEL",
+ help=(
+ "Only clean given models. "
+ "See Available Models for the list of allowed values."
+ ),
+ )
+ model_filter.add_argument(
+ "--exclude",
+ type=str,
+ choices=model_names,
+ action="extend",
+ nargs="+",
+ metavar="MODEL",
+ help=(
+ "Exclude given models from cleaning. "
+ "See Available Models for the list of allowed values."
+ ),
+ )
+
+ parser.epilog = "Available Models: " + ", ".join(model_names)
+
+ def handle(
+ self,
+ is_dry_run: bool,
+ verbose: bool,
+ stop_on_error: bool,
+ report_frequency: int,
+ only: list[str],
+ exclude: list[str],
+ **_options,
+ ):
+ self.is_dry_run = is_dry_run
+ self.verbose = verbose
+ self.stop_on_error = stop_on_error
+
+ # Reports the % progress every N rows (where N is `report_frequency`)
+ self.report_frequency = report_frequency
+
+ # Makes django use the default color for stderr, otherwise everything is red
+ # despite we don't log an error
+ self.stderr.style_func = None
+ self.differ = difflib.Differ()
+
+ for [model_cls, field] in MODELS:
+ # Skip model if --only was provided but this model's name wasn't provided in
+ # --only
+ if only and model_cls.__name__ not in only:
+ if self.verbose:
+ self.stderr.write(f"Skipped: {model_cls.__name__} (not in --only)")
+ continue
+
+ if exclude and model_cls.__name__ in exclude:
+ if self.verbose:
+ self.stderr.write(
+ f"Skipped: {model_cls.__name__} (not in --exclude)"
+ )
+ continue
+
+ self.clean_model(model_cls, field)
+
+ self.stderr.write(
+ "To apply the changes, rerun this command with --apply", self.style.NOTICE
+ )
+
+ def clean_model(self, cls, field: str):
+ table_name = cls.__name__
+
+ if self.is_dry_run is False:
+ self.stderr.write(f"Cleaning {table_name} table...")
+ elif self.verbose:
+ self.stderr.write(f"Checking {table_name}...")
+
+ # Excludes 'null'::jsonb (see https://code.djangoproject.com/ticket/35381)
+ qs = (
+ cls.objects.all()
+ .only("pk", field)
+ .filter(~models.Q(**{field: models.Value(None, models.JSONField())}))
+ )
+ obj_count = qs.count()
+
+ for processed_count, row in enumerate(qs.iterator(chunk_size=100), start=1):
+ # Sends a progress update every N rows to prevent the command from looking
+ # stuck if there are lot of objects to process
+ if (
+ processed_count == obj_count
+ or (processed_count % self.report_frequency) == 0
+ ):
+ progress_perc = round(((processed_count) / obj_count) * 100)
+ self.stderr.write(f"Progress for {table_name}: {progress_perc}%")
+
+ contents = getattr(row, field)
+
+ # Skip row if type is invalid
+ if isinstance(contents, dict) is False:
+ self.stderr.write(
+ (
+ f"Expected a dict object but got instead {type(contents)} "
+ f"for table {table_name} with pk={row.pk!r}"
+ ),
+ self.style.NOTICE,
+ )
+ continue
+
+ # Dump to string before cleaning as the object will be mutated
+ before = json.dumps(contents, indent=2)
+
+ # Perform the cleaning
+
+ try:
+ cleaned = clean_editor_js(contents)
+ except (KeyError, ValidationError, ValueError) as exc:
+ msg = f"Found invalid data for row #{row.pk} ({table_name})"
+ if self.stop_on_error is True:
+ raise CommandError(msg) from exc
+
+ self.stderr.write(f"ERROR: {msg}", self.style.ERROR)
+ self.stderr.write(
+ "\n".join(traceback.format_exception_only(exc)).strip(),
+ self.style.ERROR,
+ )
+ continue
+
+ after = json.dumps(cleaned, indent=2)
+
+ if after == before:
+ continue
+
+ if self.is_dry_run is False:
+ row.save(update_fields=[field])
+ else:
+ self.stdout.write(
+ f"Row #{row.pk} would be changed ({table_name}):",
+ self.style.WARNING,
+ )
+ for line in self.differ.compare(
+ before.splitlines(),
+ after.splitlines(),
+ ):
+ style = None
+ if line:
+ if line[0] == "-":
+ style = self.style.ERROR # red color for deleted lines
+ elif line[0] == "+":
+ style = self.style.SUCCESS # green color for added lines
+ self.stdout.write(f"\t{line}", style, ending="\n")
diff --git a/saleor/core/tests/commands/__init__.py b/saleor/core/tests/commands/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/core/tests/commands/test_clean_editorjs_fields.py b/saleor/core/tests/commands/test_clean_editorjs_fields.py
new file mode 100644
index 0000000000..7fc4eb55b2
--- /dev/null
+++ b/saleor/core/tests/commands/test_clean_editorjs_fields.py
@@ -0,0 +1,250 @@
+# ruff: noqa: UP031 # printf-style string formatting are more readable for JSON
+import random
+import re
+from copy import deepcopy
+from io import StringIO
+from unittest import mock
+
+import pytest
+from django.core.management import call_command
+from django.core.management.base import CommandError
+
+from ....attribute.models.base import AttributeValue
+from ....page.models import Page
+from ....product.models import Category, Collection
+from ...management.commands.clean_editorjs_fields import MODELS
+
+MODELS_NAMES = [model_cls.__name__ for [model_cls, _field] in MODELS]
+
+
+def dirty():
+ """Return a dirty EditorJS object that needs cleaning."""
+ return {
+ "blocks": [{"type": "paragraph", "data": {"text": "<img src=x onerror=y>"}}]
+ }
+
+
+def cleaned():
+ """Return a cleaned EditorJS object."""
+ return {"blocks": [{"type": "paragraph", "data": {"text": '<img src="x">'}}]}
+
+
+def create_dirty_category(data: None | dict = None) -> Category:
+ with mock.patch.object(
+ Category.description.field, "_sanitizer_method", side_effect=lambda x: x
+ ):
+ original_data = deepcopy(data) if data else dirty()
+ category = Category(
+ name="my-category",
+ slug=f"my-category-{random.random()}",
+ # Note: we call dirty() again as it will mutate,
+ # original_data thus needs to have a different pointer address
+ description=data or dirty(),
+ )
+ category.save()
+ assert category.description == original_data, (
+ "The description shouldn't have changed. Was the cleaner mocked properly?"
+ )
+ return category
+
+
+def test_handles_errors():
+ """Ensure that error caused by invalid data are handled."""
+
+ # Creates an invalid category in order to cause the cleaner to return an error
+ data = {"blocks": [{"type": "invalid", "data": {"foo": "bar"}}]}
+ category = create_dirty_category(data)
+ assert category.description == data
+
+ out_fp = StringIO()
+ call_command("clean_editorjs_fields", "--only=Category", stderr=out_fp)
+
+ expected_error = f"Found invalid data for row #{category.pk} (Category)"
+ assert expected_error in out_fp.getvalue()
+
+ # Should fail if '--stop-on-error' was provided
+ with pytest.raises(CommandError, match=re.escape(expected_error)):
+ call_command(
+ "clean_editorjs_fields", "--stop-on-error", "--only=Category", stderr=out_fp
+ )
+
+
+def test_detects_dirty_rows():
+ """Ensure rows that would be modified are shown in the command's output."""
+
+ category = create_dirty_category()
+
+ out_fp = StringIO()
+ call_command("clean_editorjs_fields", "--only=Category", stdout=out_fp)
+
+ # Should have detected a difference
+ actual_output = out_fp.getvalue()
+ expected_output = (
+ """Row #%d would be changed (Category):
+\t {
+\t "blocks": [
+\t {
+\t "data": {
+\t- "text": "<img src=x onerror=y>"
+\t? ^^^^^^^^^^
+\t+ "text": "<img src=\\"x\\">"
+\t? ++ ^^
+\t },
+\t "type": "paragraph"
+\t }
+\t ]
+\t }"""
+ % category.pk
+ )
+ assert expected_output in actual_output
+
+ # Then, should successfully clean it
+ assert "onerror" in category.description["blocks"][0]["data"]["text"]
+ call_command("clean_editorjs_fields", "--only=Category", "--apply")
+ category.refresh_from_db(fields=["description"])
+ assert "onerror" not in category.description["blocks"][0]["data"]["text"]
+
+
+def test_track_progress():
+ """Ensures progress is only reported every N rows and at 100% done."""
+
+ # We create clean categories as we are not trying to check the cleaning behavior
+ # it saves a bit of compute time
+ Category.objects.bulk_create(
+ [
+ Category(
+ slug=f"category-{i}",
+ name=f"category-{i}",
+ description={},
+ lft=4,
+ rght=5,
+ tree_id=0,
+ level=0,
+ )
+ for i in range(10)
+ ]
+ )
+
+ out_fp = StringIO()
+ call_command(
+ "clean_editorjs_fields",
+ "--progress=4",
+ "--only=Category",
+ stderr=out_fp,
+ )
+
+ lines = [
+ line
+ for line in out_fp.getvalue().splitlines()
+ if line.startswith("Progress for") # Excludes unrelated logs
+ ]
+
+ # Should report three times: 2 times because of --progress=4 (every 4 rows)
+ # and a 3rd time when it reaches the last row (100%)
+ assert lines == [
+ "Progress for Category: 40%",
+ "Progress for Category: 80%",
+ "Progress for Category: 100%",
+ ]
+
+
+ ("cmd_args", "expected_models"),
+ [
+ (
+ # Given
+ ("--only", "Category", "Collection"),
+ # Then, only the following should be scanned
+ ("Category", "Collection"),
+ ),
+ (
+ # Given
+ ("--exclude", "Category", "Collection"),
+ # Then, only the following should be scanned
+ list({*MODELS_NAMES} - {"Category", "Collection"}),
+ ),
+ ],
+)
+def test_filter_models(cmd_args: tuple[str, ...], expected_models: list[str]):
+ """Ensures progress is only reported every N rows and at 100% done."""
+
+ out_fp = StringIO()
+ call_command(
+ "clean_editorjs_fields",
+ "--verbose",
+ *cmd_args,
+ stderr=out_fp,
+ )
+
+ lines = sorted(
+ [
+ line
+ for line in out_fp.getvalue().splitlines()
+ if line.startswith("Checking ") # Excludes unrelated logs
+ ]
+ )
+
+ expected_lines = sorted([f"Checking {model}..." for model in expected_models])
+ assert lines == expected_lines
+
+
+ ("model_cls", "editorjs_field", "create_entry"),
+ # This test takes a sample of 3 models:
+ # - Page - uses '.content'
+ # - Collection - uses '.description'
+ # - AttributeValue - uses '.rich_text'
+ [
+ (
+ Page,
+ "content", # => page.content - the EditorJS DB field
+ lambda request: Page(
+ slug="x",
+ title="x",
+ page_type=request.getfixturevalue("page_type"),
+ content=dirty(),
+ ),
+ ),
+ (
+ Collection,
+ "description", # => collection.description - the EditorJS DB field
+ lambda _request: Collection(slug="x", name="x", description=dirty()),
+ ),
+ (
+ AttributeValue,
+ "rich_text", # => AttributeValue.description - the EditorJS DB field
+ lambda request: AttributeValue(
+ slug="x",
+ name="x",
+ rich_text=dirty(),
+ attribute=request.getfixturevalue("rich_text_attribute"),
+ ),
+ ),
+ ],
+)
+def test_can_clean_all_models(
+ request,
+ model_cls,
+ editorjs_field: str,
+ create_entry,
+):
+ """Ensure rows that would be modified are shown in the command's output."""
+
+ with mock.patch.object(
+ # Temporarily disables the cleaner so it doesn't clean the dirty input
+ getattr(model_cls, editorjs_field).field,
+ "_sanitizer_method",
+ side_effect=lambda x: x,
+ ):
+ entry = create_entry(request)
+ entry.save() # insert into the DB
+
+ # Ensures the field is indeed dirty before we try to clean it
+ assert getattr(entry, editorjs_field) == dirty()
+
+ # Start the cleaning
+ call_command("clean_editorjs_fields", "--apply", f"--only={model_cls.__name__}")
+
+ # Should have cleaned the model properly
+ entry.refresh_from_db(fields=[editorjs_field])
+ assert getattr(entry, editorjs_field) == cleaned()
diff --git a/saleor/core/utils/editorjs.py b/saleor/core/utils/editorjs.py
index 82a7184676..8716de5d06 100644
--- a/saleor/core/utils/editorjs.py
+++ b/saleor/core/utils/editorjs.py
@@ -1,20 +1,127 @@
-import re
import warnings
-from typing import Literal, overload
+from typing import Any, Literal, TypedDict, cast, overload
+import nh3
+from django.conf import settings
+from django.core.exceptions import ValidationError
from django.utils.html import strip_tags
from urllib3.util import parse_url
-BLACKLISTED_URL_SCHEMES = ("javascript",)
-HYPERLINK_TAG_WITH_URL_PATTERN = r"(.*?<a\s+href=\\?\")(\w+://\S+[^\\])(\\?\">)"
+from ..cleaners import URL_SCHEME_CLEANERS, URLCleanerError
+
+# An allow list that lists the supported block types for ``clean_text_items()``
+# We return an error when the type is not part of the allow list
+# as a safety measure.
+#
+# Note: we only support the types that the Saleor Dashboard implements;
+# they are listed here: https://github.com/saleor/saleor-dashboard/blob/2b2311eb2a0a98567efbbe5eef5c3daf66eeeb92/pnpm-lock.yaml#L38-L49
+ALLOWED_TEXT_BLOCK_TYPES = ("paragraph", "header", "quote")
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),
+ "quote": lambda *params: clean_quote_item(*params),
+}
+
+ALLOWED_URL_SCHEMES = {
+ # WARNING: do NOT add new schemes in directly to this list, only HTTP and HTTPS
+ # should be listed as they are cleaned by urllib3. Instead, add it to
+ # URL_SCHEME_CLEANERS and implement a cleaner that (at minimum) quotes
+ # special characters like "'<> and ASCII control characters
+ # (use urllib.util.parse.quote())
+ "http",
+ "https",
+ *URL_SCHEME_CLEANERS.keys(),
}
+def maybe_to_int(o: Any, *, name: str) -> int:
+ """Cast a given object to an integer if it's possible, otherwise it raises.
+
+ It's a lenient parsing for backward compatibility.
+ """
+
+ if isinstance(o, str):
+ if o.isnumeric() is False:
+ raise ValidationError(f"{name} must be an integer")
+ return int(o)
+
+ if isinstance(o, int) is False:
+ raise ValidationError(f"{name} must be an integer")
+
+ return o
+
+
+class NestedListItemType(TypedDict):
+ """The EditorJS inner items of a nested list.
+
+ Example:
+ {
+ "type" : "list",
+ "data" : {
+ "style": "ordered",
+ "meta": {
+ "start": 2,
+ "counterType": "upper-roman",
+ },
+ "items" : [
+ { # <---
+ "content": "Apples", # <---
+ "meta": {}, # <---
+ "items": [ # <---
+ {
+ "content": "Red",
+ "meta": {},
+ "items": []
+ },
+ ]
+ },
+ ]
+ }
+ }
+
+ """
+
+ content: str # The text
+ meta: dict
+ items: list["NestedListItemType"]
+
+
+class NestedListBlockType(TypedDict):
+ """The EditorJS outer block of a nested list.
+
+ Example:
+ {
+ "type" : "list",
+ "data" : {
+ "style": "ordered", # <---
+ "meta": { # <---
+ "start": 2, # <---
+ "counterType": "upper-roman", # <---
+ }, # <---
+ "items" : [ # <---
+ {
+ "content": "Apples",
+ "meta": {},
+ "items": [
+ {
+ "content": "Red",
+ "meta": {},
+ "items": []
+ },
+ ]
+ },
+ ]
+ }
+ }
+
+ """
+
+ style: str
+ meta: dict
+ items: list["NestedListItemType"]
+
+
@overload
def clean_editor_js(
definitions: dict | str | None, *, to_string: Literal[True]
@@ -48,107 +155,367 @@ def clean_editor_js(definitions, *, to_string=False) -> dict | str | None:
plain_text_list: list[str] = []
for index, block in enumerate(blocks):
- block_type = block["type"]
+ block_type = block.get("type")
+
+ if not block_type or isinstance(block_type, str) is False:
+ raise ValidationError("Missing required key: 'type'")
+
data = block.get("data")
if not data or not isinstance(data, dict):
continue
params = [blocks, block, plain_text_list, to_string, index]
if clean_func := ITEM_TYPE_TO_CLEAN_FUNC_MAP.get(block_type):
+ for field in ("width", "height"):
+ if (field_value := data.get(field)) is not None:
+ data[field] = maybe_to_int(field_value, name=field)
clean_func(*params)
+ elif block_type == "list":
+ clean_list_item(
+ block=block,
+ to_string=to_string,
+ plain_text_list=plain_text_list,
+ max_depth=settings.EDITOR_JS_LISTS_MAX_DEPTH,
+ )
else:
- clean_other_items(*params)
+ clean_text_items(*params, block_type=block_type)
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
+def clean_legacy_list(items: list[str], *, to_string: bool, plain_text_list: list[str]):
+ for item_index, item in enumerate(items):
+ if isinstance(item, str) is False:
+ # Mixing types or version (legacy vs new lists) isn't allowed by Saleor,
+ # nor by EditorJS.
+ raise ValidationError("Invalid EditorJS list: items must be strings")
+
if to_string:
- plain_text_list.append(strip_tags(item))
+ # Only appends the text if it's not empty as we do a `' '.join(...)`
+ # i.e., otherwise it will create unneeded (and ugly) whitespaces.
+ if item:
+ plain_text_list.append(strip_tags(item))
else:
new_text = clean_text_data_block(item)
- blocks[index]["data"]["items"][item_index] = new_text
+ 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:
+def clean_meta_block(block: NestedListItemType | dict) -> None:
+ """Clean the meta property of a given block.
+
+ Args:
+ block: the EditorJS block to clean which contains (or may contain) the 'meta' key
+ at the root of the object.
+
+ """
+
+ key_count = 0
+
+ meta = block.get("meta") or {}
+ if isinstance(meta, (dict)) is False:
+ raise ValidationError(
+ "Invalid meta block for EditorJS: meta property must be an object"
+ )
+
+ for k, v in meta.items():
+ # Validate the key
+ if isinstance(k, str) is False:
+ raise ValidationError(
+ "Invalid property for a meta member for EditorJS: must a string"
+ )
+
+ # Validate the value
+ if isinstance(v, str):
+ meta[k] = clean_text_data_block(v)
+ elif isinstance(v, int | float | bool) is False and v is not None:
+ raise ValidationError(
+ "Invalid meta block for EditorJS: value of a meta must either "
+ "a string, an integer, or a float"
+ )
+
+ # Stop processing if an excessive key count is found
+ key_count += 1
+ if key_count > 10:
+ raise ValidationError("Invalid meta block for EditorJS: too many fields")
+
+
+def clean_nested_list(
+ items: list[NestedListItemType],
+ *,
+ current_depth: int,
+ max_depth: int,
+ to_string: bool,
+ plain_text_list: list[str],
+):
+ # Note: this already validated by ``clean_list_item()`` however, we still need
+ # to perform this check as we are doing recursive checks which thus weren't
+ # checked yet.
+ if isinstance(items, list) is False:
+ raise ValidationError("Invalid EditorJS list: items must be inside an array")
+
+ if current_depth > max_depth:
+ raise ValidationError("Invalid EditorJS list: maximum nesting level exceeeded")
+
+ for item in items:
+ if isinstance(item, dict) is False:
+ # Mixing types or version (legacy vs new lists) isn't allowed by Saleor,
+ # nor by EditorJS.
+ raise ValidationError("Invalid EditorJS list: items must be objects")
+
+ text = item.get("content", "")
+ if isinstance(text, str) is False:
+ raise ValidationError(
+ "Invalid EditorJS list: the text contents must be a string"
+ )
+
if to_string:
- plain_text_list.append(strip_tags(file_url))
+ # Only append the text if it's not empty as we do a `' '.join(...)`
+ # i.e., otherwise it will create unneeded (and ugly) whitespaces.
+ if text:
+ plain_text_list.append(strip_tags(text))
else:
- file_url = clean_text_data_block(file_url)
- blocks[index]["data"]["file"]["ulr"] = file_url
- if caption:
+ item["content"] = clean_text_data_block(text)
+ clean_meta_block(item)
+
+ # Cleans the children (if any)
+ clean_nested_list(
+ items=item.get("items", []),
+ current_depth=current_depth + 1,
+ max_depth=max_depth,
+ to_string=to_string,
+ plain_text_list=plain_text_list,
+ )
+
+
+def clean_list_item(
+ block: dict,
+ plain_text_list,
+ to_string: bool,
+ *,
+ max_depth: int,
+):
+ """Clean EditorJS lists, both legacy (non-nested) and the latest format (nested).
+
+ Args:
+ blocks: the list of blocks inside the EditorJS data that we are currently
+ cleaning.
+
+ block: the block to clean (`type: list`)
+
+ to_string: whether the results should be exported to plaintext instead of
+ EditorJS format.
+
+ plain_text_list: array of plaintext values to append into when ``to_string``
+ is set to ``True``.
+
+ index: the block's position in the ``blocks`` array.
+
+ max_depth: the maximum level of the list nesting. Limits the amount of recursions
+ done. Must not be set too high (recommended value: 10)
+
+ current_depth: should be set to 0 on the first call, then it gets automatically
+ incremented during the recursive calls in order to keep track of
+ the call depth.
+
+ """
+
+ data = block["data"]
+ clean_meta_block(data)
+
+ items = data.get("items", [])
+ if isinstance(items, list) is False:
+ raise ValidationError("Invalid EditorJS list: items property must be an array")
+ items = cast(list, items)
+
+ # Cleans the list style (unordered|ordered|checklist)
+ # It's valid both for legacy and new (nested) list formats
+ style: None | str
+ if style := data.get("style"):
+ if isinstance(style, str) is False:
+ raise ValidationError(
+ "Invalid EditorJS list: style property must be a string"
+ )
+ data["style"] = clean_text_data_block(style)
+
+ # List empty
+ if not items:
+ return
+
+ # Looks at the first item to determine whether it's legacy or nested (the new type).
+ # We do not do this in a loop as we shouldn't allow users to mix legacy and
+ # non-legacy within a block, this isn't valid EditorJS and thus should be rejected
+ # by `clean_legacy_list()` and `clean_nested_list()` but this validation is deferred
+ # to these functions in order to not iterate multiple times the lists.
+ if isinstance(items[0], str):
+ # Support for **legacy** lists (https://github.com/editor-js/list-legacy/blob/381254443234ebbec9cc508fa8a7b982b6a79418/README.md#output-data)
+ clean_legacy_list(items, to_string=to_string, plain_text_list=plain_text_list)
+ elif isinstance(items[0], dict):
+ # Support for the new format (nested lists, https://github.com/editor-js/list/blob/f8cde313224499ed5bcf3e93864fc11c45fe7efb/README.md#output-data)
+ clean_nested_list(
+ items,
+ max_depth=max_depth,
+ current_depth=0,
+ to_string=to_string,
+ plain_text_list=plain_text_list,
+ )
+ else:
+ raise ValidationError(
+ "Invalid EditorJS list: items must be either a string or an object"
+ )
+
+
+def clean_image_item(blocks, block, plain_text_list, to_string, index):
+ data = block["data"]
+
+ for obj in (
+ # data.file.url -> support for newer versions of Edjs (2.x)
+ data.get("file", {}),
+ # data.url -> support for older version (1.x)
+ data,
+ ):
+ if file_url := obj.get("url"):
+ if to_string:
+ plain_text_list.append(strip_tags(file_url))
+ else:
+ file_url = clean_url(file_url)
+ obj["url"] = file_url
+
+ if caption := data.get("caption"):
if to_string:
plain_text_list.append(strip_tags(caption))
else:
caption = clean_text_data_block(caption)
- blocks[index]["data"]["caption"] = caption
+ data["caption"] = caption
def clean_embed_item(blocks, block, plain_text_list, to_string, index):
- for field in ["source", "embed", "caption"]:
+ for field in ["source", "embed"]:
data = block["data"].get(field)
if not data:
- return
+ continue
if to_string:
plain_text_list.append(strip_tags(data))
else:
- data = clean_text_data_block(data)
+ data = clean_url(data)
blocks[index]["data"][field] = data
+ caption = block["data"].get("caption")
+ if caption:
+ if to_string:
+ plain_text_list.append(strip_tags(caption))
+ else:
+ blocks[index]["data"]["caption"] = clean_text_data_block(caption)
+
+ if service := block["data"].get("service"):
+ block["data"]["service"] = clean_text_data_block(service)
+
+
+def clean_quote_item(blocks, block, plain_text_list, to_string, index):
+ """Clean a EditorJS `quote` block.
+
+ Follows the specs from https://github.com/editor-js/quote/blob/78f70cf2391cc8aaf2d2e59615de3ad833d180c3/README.md#output-data
+ """
+
+ # Cleans all EditorJS fields from the data block
+ for field in ["text", "caption", "alignment", "align"]:
+ data = block["data"].get(field)
+ if not data:
+ continue
+ blocks[index]["data"][field] = clean_text_data_block(data)
+
+ if text := block["data"].get("text"):
+ plain_text_list.append(strip_tags(text))
+
-def clean_other_items(
+def clean_text_items(
blocks,
block,
plain_text_list,
to_string,
index,
+ *,
+ block_type: str,
):
- text = block["data"].get("text")
- if not text:
- return
- if to_string:
- plain_text_list.append(strip_tags(text))
- else:
- new_text = clean_text_data_block(text)
- blocks[index]["data"]["text"] = new_text
+ if block_type not in ALLOWED_TEXT_BLOCK_TYPES:
+ raise ValidationError(f"Unsupported block type: {block_type!r}")
+ data = block["data"]
-def clean_text_data_block(text: str) -> str:
- """Look for url in text, check if URL is allowed and return the cleaned URL.
+ text = data.get("text")
+ if text:
+ if to_string:
+ plain_text_list.append(strip_tags(text))
+ else:
+ new_text = clean_text_data_block(text)
+ data["text"] = new_text
- By default, only the protocol ``javascript`` is denied.
- """
+ for field in ("alignment", "align"):
+ if value := data.get(field):
+ data[field] = clean_text_data_block(value)
- if not text:
- return text
+ if heading_level := data.get("level"):
+ data["level"] = maybe_to_int(heading_level, name="Heading level")
- 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
- url_scheme = url.scheme
- if url_scheme in BLACKLISTED_URL_SCHEMES:
- warnings.warn(
- f"An invalid url was sent: {original_url} "
- f"-- Scheme: {url_scheme} is blacklisted",
- stacklevel=1,
- )
- 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:]
+def clean_text_data_block(text: str) -> str:
+ """Sanitize the text using nh3 to remove malicious tags and attributes."""
+ if not text:
+ return text
- return new_text if new_text else text
+ return nh3.clean(
+ text,
+ url_schemes=ALLOWED_URL_SCHEMES | settings.HTML_CLEANER_PREFS.allowed_schemes,
+ attributes=settings.HTML_CLEANER_PREFS.allowed_attributes,
+ tag_attribute_values=settings.HTML_CLEANER_PREFS.allowed_attribute_values,
+ link_rel=settings.HTML_CLEANER_PREFS.link_rel,
+ )
+
+
+def clean_url(dirty_url: str) -> str:
+ """Check if URL scheme is allowed."""
+ if not dirty_url:
+ return ""
+
+ try:
+ parsed_url = parse_url(dirty_url.strip())
+ except ValueError:
+ parsed_url = None
+
+ if (
+ parsed_url is None
+ or parsed_url.scheme
+ not in ALLOWED_URL_SCHEMES | settings.HTML_CLEANER_PREFS.allowed_schemes
+ ):
+ warnings.warn(
+ f"An invalid url or disallowed URL was sent: {dirty_url}",
+ stacklevel=3,
+ )
+ return "#invalid"
+
+ # If the scheme is HTTP(S), then urllib3 already took care of normalization
+ # and thus quoted everything that should be quoted (such as dangerous characters
+ # like `"`)
+ # See https://github.com/urllib3/urllib3/blob/bd37a23af4552548f55d3c723fcb604f9a4983ca/src/urllib3/util/url.py#L415-L446
+ if parsed_url.scheme in ("https", "http"):
+ return parsed_url.url
+
+ url_cleaner = URL_SCHEME_CLEANERS.get(parsed_url.scheme, None)
+
+ if url_cleaner is None:
+ if parsed_url.scheme in settings.HTML_CLEANER_PREFS.allowed_schemes:
+ # Deprecated: this is only for backward compatibility - it doesn't define
+ # a cleaner which is dangerous.
+ return dirty_url
+ # NOTE: this exception should never happen unless a maintainer didn't read the
+ # comment in ALLOWED_URL_SCHEMES
+ raise KeyError("No URL cleaner defined", parsed_url.scheme)
+
+ try:
+ return url_cleaner(dirty_url=dirty_url)
+ except URLCleanerError as exc:
+ # Note: InvalidUsage must NOT be handled (should return "Internal Error")
+ # it indicates a code bug if it's raised
+ raise ValidationError(str(exc)) from exc
+ except ValueError as exc:
+ # Note: we do not do str(exc) as may reveal sensitive information
+ raise ValidationError("Invalid URL") from exc
diff --git a/saleor/core/utils/tests/test_editorjs.py b/saleor/core/utils/tests/test_editorjs.py
index e6753c60fe..029f2d423a 100644
--- a/saleor/core/utils/tests/test_editorjs.py
+++ b/saleor/core/utils/tests/test_editorjs.py
@@ -1,10 +1,309 @@
+import json
import warnings
-from unittest import mock
+from copy import deepcopy
import pytest
+from django.core.exceptions import ValidationError
from django.utils.html import strip_tags
-from ..editorjs import clean_editor_js
+from ...cleaners.html import HtmlCleanerSettings
+from ...deprecations import SaleorDeprecationWarning
+from ..editorjs import clean_editor_js, clean_text_data_block, clean_url
+
+DIRTY = "<img src=x onerror=alert(1)>"
+CLEAN = '<img src="x">'
+
+XSS_URLS = [
+ "javascript:prompt(1)",
+ "javascript://alert(1)",
+ "javascript://anything%0D%0A%0D%0Awindow.alert(1)",
+ "javascript://%0Aalert(1)",
+ "javascript:%0Aalert(1)",
+ 'vbscript:MsgBox("XSS")',
+ "ftp://example.com",
+ # HTML entities will be replaced by the browser to 'javascript:alert(1)'
+ # in attributes (including `src="..."` and `href="..."`)
+ "&#x6A;avascript&#0000058&#0000097lert(1)",
+ "&#x6A;avascript:%20alert(1)",
+]
+
+
+def cleaner_settings(settings):
+ old_prefs = settings.HTML_CLEANER_PREFS
+
+ # NOTE: use env vars to control the settings (using prefs.reload())
+ # to ensure the parsing logic of env var is tested
+ #
+ # Warnings need to be captured due to deprecation warnings for Saleor v3.23.0
+ with warnings.catch_warnings(record=True, category=SaleorDeprecationWarning):
+ prefs = HtmlCleanerSettings()
+ settings.HTML_CLEANER_PREFS = prefs
+
+ yield prefs
+ settings.HTML_CLEANER_PREFS = old_prefs
+
+
+ ("input_url", "expected_cleaned_url", "is_allowed"),
+ # Invalid cases
+ [(url, "#invalid", False) for url in XSS_URLS]
+ + [
+ # Valid cases
+ ("https://example.com", "https://example.com", True),
+ ("http://example.com", "http://example.com", True),
+ # We shouldn't trust anything in the URL, quote everything
+ ('https://example.com?x="', "https://example.com?x=%22", True),
+ ('https://example.com/"', "https://example.com/%22", True),
+ # Special characters must be encoded
+ ('https://example.com/path"?x="', "https://example.com/path%22?x=%22", True),
+ ('https://example.com#"<>', "https://example.com#%22%3C%3E", True),
+ ("https://example.com/\x00", "https://example.com/%00", True),
+ ("https://example.com/\nonerror=1", "https://example.com/%0Aonerror=1", True),
+ ("https://exampleß.test/", "https://xn--example-6va.test/", True),
+ # Tel and mailto should be cleaned
+ ('tel:">', "tel:%22%3E", True),
+ ('mailto:?body=">', "mailto:?body=%22%3E", True),
+ ],
+)
+def test_clean_url(input_url, expected_cleaned_url, is_allowed):
+ with warnings.catch_warnings(record=True) as warns:
+ actual = clean_url(input_url)
+
+ expected_warning_count = 0 if is_allowed else 1
+ assert len(warns) == expected_warning_count
+
+ assert actual == expected_cleaned_url
+
+
+ ("input_url", "expected_error"),
+ [
+ ("mailto:joe@[1]", "Invalid IPv6 address"),
+ (
+ "mailto:[email protected]?1" + "&".join(f"{i}={i}" for i in range(11)),
+ # Actual error is from urllib: "ValueError: Max number of fields exceeded"
+ "Invalid URL",
+ ),
+ ],
+)
+def test_clean_url_error_handling(input_url: str, expected_error: str):
+ with pytest.raises(ValidationError, match=expected_error):
+ clean_url(input_url)
+
+
+def test_clean_url_allows_custom_allow_list(monkeypatch, cleaner_settings):
+ """Ensure that we allow to override the settings to add more allowed URL schemes.
+
+ This is a backward compatibility check, it will be removed in 3.23.0.
+ """
+
+ url = "non-default:foo"
+
+ # Should refuse the URL scheme if it's not allowed
+ with warnings.catch_warnings(record=True):
+ assert clean_url(url) == "#invalid"
+
+ # Catches warnings due to deprecation notices from Saleor (v3.23.0)
+ with warnings.catch_warnings(record=True):
+ monkeypatch.setenv("UNSAFE_EDITOR_JS_ALLOWED_URL_SCHEMES", "non-default,other")
+ cleaner_settings.reload()
+
+ # When allowed it should allow the use of that URL scheme even if a cleaner
+ # isn't defined.
+ assert clean_url(url) == url
+ assert clean_url("other:") == "other:"
+ with warnings.catch_warnings(record=True):
+ assert clean_url("not-ok:") == "#invalid"
+
+
+ ("_case", "text", "expected_cleaned_text"),
+ [
+ # Invalid URLs
+ (
+ f"XSS URL: {url}",
+ f'<a href="{url}">link</a>',
+ '<a rel="noopener noreferrer">link</a>',
+ )
+ for url in XSS_URLS
+ ]
+ + [
+ (
+ "SVG should be fully deleted",
+ (
+ "<p>My SVG:</p>"
+ # Safe SVG (draws a rectangle) but we expect nh3 to not try clean inside
+ # the SVG body instead it should drop the whole block.
+ # SVG is fairly complex to parse and thus <img> should be used instead
+ # when dealing with untrusted data as it already removes all scripts
+ # that could running within an SVG file.
+ '<svg width="300" height="130" xmlns="http://www.w3.org/2000/svg">'
+ '<rect width="100" height="100" />'
+ "</svg>"
+ ),
+ "<p>My SVG:</p>", # we expect the <svg> to be deleted
+ ),
+ (
+ "Script blocks should be deleted",
+ "<script>alert(1)</script>",
+ "",
+ ),
+ (
+ # '<style>' is an XSS vector and poses other security risks
+ "Style blocks should be deleted",
+ "<style>a {color: red}</style>",
+ "",
+ ),
+ (
+ # 'style' attribute is an XSS vector and poses other security risks
+ "Style attributes should be deleted",
+ '<span style="color: red">text</span>',
+ "<span>text</span>",
+ ),
+ (
+ "Common XSS Bypass: Backticks",
+ "<img src=javascript:alert(1)>",
+ "<img>",
+ ),
+ ("VBScript", "<img src='vbscript:msgbox(1)'>", "<img>"),
+ ("Slash Delimer", "<img/onload=alert(1)>", "<img>"),
+ (
+ "Body Image",
+ "<body background='javascript:alert(1)'>",
+ "",
+ ),
+ ("SVG attributes are removed", "<svg/onload=alert('XSS')>", ""),
+ (
+ "Unsupported URL schemes are dropped",
+ '<a href="wss://foo.test">link</a>',
+ '<a rel="noopener noreferrer">link</a>',
+ ),
+ (
+ "Supported URL schemes are kept",
+ '<a href="https://foo.test">link</a>',
+ '<a href="https://foo.test" rel="noopener noreferrer">link</a>',
+ ),
+ (
+ # Will be denied in a future Saleor release due to being unsupported
+ # by nh3 currently
+ "Relative URLs are allowed",
+ '<a href="example-relative-url">link</a>',
+ '<a href="example-relative-url" rel="noopener noreferrer">link</a>',
+ ),
+ ],
+)
+def test_clean_text_data_block(_case: str, text: str, expected_cleaned_text: str):
+ actual = clean_text_data_block(text)
+ assert actual == expected_cleaned_text
+
+
+ ("_case", "allowed_attributes", "html_input", "expected_output"),
+ [
+ (
+ "a[is] is allowed => shouldn't drop 'is' attr",
+ {"a": ["is"]},
+ '<a href="https://example.com" is="dummy">Link</a>',
+ '<a href="https://example.com" is="dummy">Link</a>',
+ ),
+ (
+ "a[is] is allowed only on <a> => MUST drop 'is' attr on <div>",
+ {"a": ["is"]},
+ '<div is="dummy">x</div>',
+ "<div>x</div>",
+ ),
+ (
+ "a[foo] is NOT allowed => MUST drop 'foo'",
+ {"a": ["is"]},
+ '<a href="https://example.com" is="dummy" foo="bar">Link</a>',
+ '<a href="https://example.com" is="dummy">Link</a>',
+ ),
+ ],
+)
+def test_clean_text_data_block_allow_custom_attributes(
+ monkeypatch,
+ cleaner_settings,
+ _case: str,
+ allowed_attributes: dict[str, list[str]],
+ html_input: str,
+ expected_output: str,
+):
+ monkeypatch.setenv(
+ "EDITOR_JS_ALLOWED_ATTRIBUTES",
+ json.dumps(allowed_attributes),
+ )
+ cleaner_settings.reload()
+
+ actual = clean_text_data_block(html_input)
+ assert actual == expected_output
+
+
+ ("_case", "html_input", "expected_output"),
+ [
+ (
+ "Does not drop allowed tag values",
+ '<a href="https://example.com" is="allowed">Link</a>',
+ '<a href="https://example.com" is="allowed">Link</a>',
+ ),
+ (
+ "Removes attribute value if not allowed",
+ '<a href="https://example.com" is="bad">Link</a>',
+ '<a href="https://example.com">Link</a>',
+ ),
+ (
+ "Keeps the attribute values if ALL words match",
+ '<a href="https://example.com" is="multiple words">Link</a>',
+ '<a href="https://example.com" is="multiple words">Link</a>',
+ ),
+ (
+ "Drops the attribute if the values isn't exactly equal",
+ '<a href="https://example.com" is="this is allowed here">Link</a>',
+ # ammonia doesn't attempt to parse the list of attributes (which is good)
+ '<a href="https://example.com">Link</a>',
+ ),
+ (
+ # rel is a special case, there is special logic in ammonia thus we need
+ # to make sure it doesn't drop these
+ "a[rel] values are kept when it matches",
+ '<a href="https://example.com" rel="noopener noreferrer">Link</a>',
+ '<a href="https://example.com" rel="noopener noreferrer">Link</a>',
+ ),
+ (
+ "a[rel] is dropped when it does not match",
+ '<a href="https://example.com" rel="bad">Link</a>',
+ '<a href="https://example.com">Link</a>',
+ ),
+ (
+ "If <a> is allowed, shouldn't be able to use it for <div>",
+ '<div is="allowed">x</div>',
+ "<div>x</div>",
+ ),
+ ],
+)
+def test_clean_text_data_block_allow_custom_attribute_values(
+ monkeypatch,
+ cleaner_settings,
+ _case: str,
+ html_input: str,
+ expected_output: str,
+):
+ monkeypatch.setenv(
+ "EDITOR_JS_ALLOWED_ATTRIBUTE_VALUES",
+ json.dumps(
+ {
+ "a": {
+ "is": ["allowed", "multiple words"],
+ "rel": ["noopener noreferrer"],
+ }
+ }
+ ),
+ )
+ cleaner_settings.reload()
+
+ actual = clean_text_data_block(html_input)
+ assert actual == expected_output
@pytest.mark.parametrize(
@@ -72,33 +371,31 @@ def test_clean_editor_js_no_data():
assert result == ""
[email protected]("saleor.core.utils.editorjs.parse_url")
-def test_clean_editor_js_invalid_url(parse_url_mock):
+def test_clean_editor_js_invalid_url():
# 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"
+ url_invalid = "javascript:alert('Saleor')"
+ url_valid = "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."
+ "but the Saleor demo store is a genuine e-commerce leader. "
+ 'Check this out: <a href="{}">'
)
- data = {"blocks": [{"data": {"text": text.format(url)}, "type": "paragraph"}]}
+ data = {
+ "blocks": [
+ {"data": {"text": text.format(url_invalid, url_valid)}, "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)
+ result = clean_editor_js(data)
# then
- new_url = "#invalid"
- assert result["blocks"][0]["data"]["text"] == text.format(new_url)
+ cleaned_text = result["blocks"][0]["data"]["text"]
+ assert "javascript:" not in cleaned_text
+ assert url_valid in cleaned_text
+ assert "The Saleor Winter Sale" in cleaned_text
def test_clean_editor_js_for_list():
@@ -148,29 +445,23 @@ def test_clean_editor_js_for_list():
)
[email protected]("saleor.core.utils.editorjs.parse_url")
-def test_clean_editor_js_for_list_invalid_url(parse_url_mock):
+def test_clean_editor_js_for_list_invalid_url():
# 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/"
- url2 = "https://github.com/editor-js"
+ url_invalid = "javascript:alert(1)"
+ url_valid = "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"},
+ {"data": {"text": text1.format(url_invalid)}, "type": "paragraph"},
{
"type": "list",
"data": {
"style": "unordered",
"items": [
"It returns clean data output in JSON",
- item_text_with_url.format(url2),
+ item_text_with_url.format(url_valid),
"Designed to be extendable and pluggable with a simple API",
],
},
@@ -179,18 +470,16 @@ def test_clean_editor_js_for_list_invalid_url(parse_url_mock):
}
# 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)
+ result = clean_editor_js(data)
# then
- assert result["blocks"][0]["data"]["text"] == text1.format("#invalid")
- assert result["blocks"][1]["data"]["items"][1] == item_text_with_url.format(
- "#invalid"
- )
+ # Paragraph with invalid url should be cleaned
+ assert "javascript:" not in result["blocks"][0]["data"]["text"]
+
+ # List item with valid url should be preserved
+ assert url_valid in result["blocks"][1]["data"]["items"][1]
+
+ # Unchanged
assert (
result["blocks"][1]["data"]["items"][0] == data["blocks"][1]["data"]["items"][0]
)
@@ -294,3 +583,705 @@ def test_clean_editor_js_for_complex_description():
" https://www.youtube.com/embed/erz"
" How To Use"
)
+
+
+def test_clean_editor_js_for_malicious_value():
+ # given
+ data = {
+ "blocks": [
+ {
+ "data": {
+ "text": "<img src=x onerror=alert(1)><script>alert(2);</script>Check"
+ },
+ "type": "paragraph",
+ }
+ ]
+ }
+
+ # when
+ result = clean_editor_js(data)
+
+ # then
+ # Malicious elements should be stripped.
+ # nh3 allows img but strips onerror. script is removed.
+ text = result["blocks"][0]["data"]["text"]
+ assert "onerror" not in text
+ assert "<script>" not in text
+ assert "alert" not in text
+ assert "Check" in text
+
+
+def test_clean_editor_js_image_invalid_url():
+ # given
+ url = "javascript:alert('XSS')"
+ data = {"blocks": [{"type": "image", "data": {"file": {"url": url}}}]}
+
+ # when
+ with warnings.catch_warnings(record=True) as warns:
+ result = clean_editor_js(data)
+
+ assert len(warns) == 1
+ assert "disallowed URL was sent" in str(warns[0].message)
+
+ # then
+ assert result["blocks"][0]["data"]["file"]["url"] == "#invalid"
+
+
+def test_clean_editor_js_image_disallowed_scheme():
+ # given
+ url = "ftp://example.com/image.png"
+ data = {"blocks": [{"type": "image", "data": {"file": {"url": url}}}]}
+
+ # when
+ with warnings.catch_warnings(record=True) as warns:
+ result = clean_editor_js(data)
+
+ assert len(warns) == 1
+ assert "disallowed URL was sent" in str(warns[0].message)
+
+ # then
+ assert result["blocks"][0]["data"]["file"]["url"] == "#invalid"
+
+
+ ("_case", "data", "expected_results"),
+ [
+ (
+ "Should clean list items",
+ {
+ "type": "list",
+ "data": {
+ "style": "unordered",
+ "items": ["<img src=invalid onerror=alert(1) />"],
+ },
+ },
+ # Expects:
+ {
+ "type": "list",
+ "data": {
+ "style": "unordered",
+ "items": ['<img src="invalid">'],
+ },
+ },
+ ),
+ (
+ "Should be able to clean when 1st item is empty",
+ {
+ "type": "list",
+ "data": {
+ "style": "unordered",
+ "items": ["", "<img src=invalid onerror=alert(1) />"],
+ },
+ },
+ # Expects:
+ {
+ "type": "list",
+ "data": {
+ "style": "unordered",
+ "items": ["", '<img src="invalid">'],
+ },
+ },
+ ),
+ (
+ "Should clean the style field",
+ {
+ "type": "list",
+ "data": {
+ "style": 'unordered"/><script>alert(1) <!--',
+ "items": [],
+ },
+ },
+ # Expects:
+ {
+ "type": "list",
+ "data": {
+ "style": 'unordered"/&gt;',
+ "items": [],
+ },
+ },
+ ),
+ ],
+)
+def test_clean_editorjs_legacy(_case: str, data: dict, expected_results: dict):
+ """Ensure that legacy lists (non-nested) are supported.
+
+ Format: https://github.com/editor-js/list-legacy/blob/381254443234ebbec9cc508fa8a7b982b6a79418/README.md#output-data
+ """
+
+ data = {"blocks": [data]}
+
+ actual_results = clean_editor_js(data)
+ blocks = actual_results["blocks"]
+ assert len(blocks) == 1
+
+ assert blocks[0] == expected_results
+
+
+ ("_case", "data"),
+ [
+ (
+ "No Items",
+ {
+ "type": "list",
+ "data": {
+ "items": [], # empty list should work fine
+ },
+ },
+ ),
+ (
+ "Empty item",
+ {
+ "type": "list",
+ "data": {
+ "items": [""], # empty item should work fine
+ },
+ },
+ ),
+ (
+ "Basic HTML",
+ {
+ "type": "list",
+ "data": {
+ # Basic HTML shouldn't cause differences or any issues
+ "items": ["<strong>Apple</strong>", "Kiwi"],
+ },
+ },
+ ),
+ (
+ "Meta fields with allowed types",
+ {
+ "type": "list",
+ "data": {
+ "meta": {
+ "integer": 1,
+ "boolean": True,
+ "float": 3.14,
+ "string": "my string",
+ "null": None,
+ },
+ },
+ },
+ ),
+ (
+ "Nulled meta is OK",
+ {
+ "type": "list",
+ "data": {
+ "meta": None,
+ },
+ },
+ ),
+ ],
+)
+def test_clean_editorjs_legacy_works_for_valid_inputs(_case: str, data: dict):
+ data = {"blocks": [data]}
+
+ expected = deepcopy(data)
+ actual = clean_editor_js(data)
+
+ # Valid data shouldn't have alterated
+ assert actual == expected
+
+
+ ("_case", "data", "expected_error"),
+ [
+ ("Missing type", {}, "Missing required key: 'type'"),
+ (
+ "Items invalid type",
+ {
+ "type": "list",
+ "data": {
+ "items": 1,
+ },
+ },
+ "Invalid EditorJS list: items property must be an array",
+ ),
+ (
+ "Items invalid type inside array",
+ {
+ "type": "list",
+ "data": {
+ "items": [1],
+ },
+ },
+ "Invalid EditorJS list: items must be either a string or an object",
+ ),
+ (
+ "Items invalid type inside array after valid value",
+ {
+ "type": "list",
+ "data": {
+ "items": ["valid", 1],
+ },
+ },
+ "Invalid EditorJS list: items must be strings",
+ ),
+ (
+ "Items invalid type inside style field",
+ {
+ "type": "list",
+ "data": {
+ "style": 1,
+ "items": ["valid"],
+ },
+ },
+ "Invalid EditorJS list: style property must be a string",
+ ),
+ ],
+)
+def test_clean_editorjs_legacy_rejects_invalid(
+ _case: str, data: dict, expected_error: str
+):
+ """Ensure when invalid data is provided as legacy lists, it's rejected."""
+
+ data = {"blocks": [data]}
+
+ with pytest.raises(ValidationError, match=expected_error):
+ clean_editor_js(data)
+
+
+ ("_case", "data", "expected_results"),
+ [
+ (
+ "Deep lists should be cleaned properly",
+ # DATA
+ {
+ "type": "list",
+ "data": {
+ "style": "unordered",
+ "meta": {
+ # NOTE: key is considered as "trusted" but value isn't
+ "key": DIRTY,
+ },
+ "items": [
+ {
+ "content": f"{DIRTY} - depth level 1",
+ "meta": {
+ "key": DIRTY,
+ },
+ "items": [
+ {
+ "content": f"{DIRTY} - depth level 2",
+ "meta": {
+ "key": DIRTY,
+ },
+ "items": [
+ {
+ "content": f"{DIRTY} - depth level 3",
+ "meta": {
+ "key": DIRTY,
+ },
+ "items": [
+ {
+ "content": f"{DIRTY} - depth level 4",
+ "meta": {},
+ "items": [],
+ }
+ ],
+ },
+ {
+ "content": f"{DIRTY} - depth level 3",
+ "meta": {
+ "key": DIRTY,
+ },
+ "items": [],
+ },
+ ],
+ },
+ {
+ "content": f"{DIRTY} - depth level 2",
+ "meta": {
+ "key": DIRTY,
+ },
+ "items": [],
+ },
+ ],
+ },
+ {
+ "content": f"{DIRTY} - depth level 1",
+ "meta": {
+ "key": DIRTY,
+ },
+ "items": [],
+ },
+ {
+ "content": f"{DIRTY} - Item next to the previous level 1 item",
+ "meta": {
+ "key": DIRTY,
+ },
+ "items": [
+ {
+ "content": f"Another level inside level 1 (again) {DIRTY}",
+ "meta": {
+ "key": DIRTY,
+ },
+ "items": [],
+ }
+ ],
+ },
+ ],
+ },
+ },
+ # RESULTS
+ {
+ "type": "list",
+ "data": {
+ "style": "unordered",
+ "meta": {
+ "key": CLEAN,
+ },
+ "items": [
+ {
+ "content": f"{CLEAN} - depth level 1",
+ "meta": {
+ "key": CLEAN,
+ },
+ "items": [
+ {
+ "content": f"{CLEAN} - depth level 2",
+ "meta": {
+ "key": CLEAN,
+ },
+ "items": [
+ {
+ "content": f"{CLEAN} - depth level 3",
+ "meta": {
+ "key": CLEAN,
+ },
+ "items": [
+ {
+ "content": f"{CLEAN} - depth level 4",
+ "meta": {},
+ "items": [],
+ }
+ ],
+ },
+ {
+ "content": f"{CLEAN} - depth level 3",
+ "meta": {
+ "key": CLEAN,
+ },
+ "items": [],
+ },
+ ],
+ },
+ {
+ "content": f"{CLEAN} - depth level 2",
+ "meta": {
+ "key": CLEAN,
+ },
+ "items": [],
+ },
+ ],
+ },
+ {
+ "content": f"{CLEAN} - depth level 1",
+ "meta": {
+ "key": CLEAN,
+ },
+ "items": [],
+ },
+ {
+ "content": f"{CLEAN} - Item next to the previous level 1 item",
+ "meta": {
+ "key": CLEAN,
+ },
+ "items": [
+ {
+ "content": f"Another level inside level 1 (again) {CLEAN}",
+ "meta": {
+ "key": CLEAN,
+ },
+ "items": [],
+ }
+ ],
+ },
+ ],
+ },
+ },
+ ),
+ ],
+)
+def test_cleans_editorjs_nested_lists(_case: str, data: dict, expected_results: dict):
+ data = {"blocks": [data]}
+
+ actual = clean_editor_js(data)
+
+ blocks = actual["blocks"]
+ assert len(blocks) == 1
+
+ assert blocks[0] == expected_results
+
+
+ ("_case", "data", "expected_error"),
+ [
+ (
+ "Item contains invalid type",
+ {
+ "type": "list",
+ "data": {
+ "items": [
+ {
+ "content": "Apples",
+ "items": [
+ # OK: valid
+ {
+ "content": "Red",
+ "meta": {},
+ "items": [],
+ },
+ # Not OK: invalid
+ 1,
+ ],
+ },
+ ],
+ },
+ },
+ "Invalid EditorJS list: items must be objects",
+ ),
+ (
+ "Invalid type in meta",
+ {
+ "type": "list",
+ "data": {"meta": {"key": object()}},
+ },
+ (
+ "Invalid meta block for EditorJS: value of a meta must either a string, "
+ "an integer, or a float"
+ ),
+ ),
+ (
+ "Too many fields in meta",
+ {
+ "type": "list",
+ "data": {"meta": {str(i): i for i in range(11)}},
+ },
+ "Invalid meta block for EditorJS: too many fields",
+ ),
+ (
+ "Keys must be a string",
+ {"type": "list", "data": {"meta": {1: "string"}}},
+ "Invalid property for a meta member for EditorJS: must a string",
+ ),
+ (
+ "List too deep",
+ {
+ "type": "list",
+ "data": {
+ "items": [
+ {
+ "items": [
+ {
+ "items": [
+ {
+ "items": [
+ {"items": [{"items": [{"items": []}]}]}
+ ]
+ }
+ ]
+ },
+ ],
+ },
+ ]
+ },
+ },
+ "Invalid EditorJS list: maximum nesting level exceeeded",
+ ),
+ ],
+)
+def test_clean_editorjs_rejects_invalid_nested_lists(
+ _case: str,
+ data: dict,
+ expected_error: str,
+ settings,
+):
+ """Ensure when invalid data is provided a nested lists, it's rejected."""
+
+ settings.EDITOR_JS_LISTS_MAX_DEPTH = 3
+
+ data = {"blocks": [data]}
+
+ with pytest.raises(ValidationError, match=expected_error):
+ clean_editor_js(data)
+
+
+def test_heading_level_cleaned():
+ """Ensure heading blocks have their heading level cleaned."""
+
+ data_input = {"type": "header", "data": {"level": DIRTY}}
+
+ with pytest.raises(ValidationError, match="Heading level must be an integer"):
+ clean_editor_js({"blocks": [data_input]})
+
+
[email protected]("block_type", ["image", "quote", "embed"])
+ ("data_field", "expected_results", "excepted_error"),
+ [
+ (
+ {"width": "1", "height": "1"},
+ # Should normalize to integer
+ {"width": 1, "height": 1},
+ None,
+ ),
+ (
+ # Should be kept as is
+ {"width": 1, "height": 1},
+ {"width": 1, "height": 1},
+ None,
+ ),
+ (
+ {"width": DIRTY},
+ None,
+ "width must be an integer",
+ ),
+ (
+ {"height": DIRTY},
+ None,
+ "height must be an integer",
+ ),
+ ],
+)
+def test_cleans_size_caption_blocks(
+ block_type: str,
+ data_field: dict,
+ expected_results: dict | None,
+ excepted_error: str | None,
+):
+ """Ensure all block types that have a caption field have their size fields cleaned."""
+
+ data = {"blocks": [{"type": block_type, "data": data_field}]}
+ error = None
+
+ try:
+ actual = clean_editor_js(data)
+ except ValidationError as exc:
+ error = exc
+
+ if excepted_error is not None:
+ assert error is not None, "Expected an error but didn't find one"
+ assert error.message == excepted_error
+ else:
+ assert error is None, "Didn't expect an error"
+
+ if expected_results is not None:
+ blocks = actual["blocks"]
+ assert len(blocks) == 1
+ block = blocks[0]
+
+ assert block["type"] == block_type
+ assert block["data"] == expected_results
+
+
+# Supported: paragraph, header, list (tested in other test cases due to being a complex
+# structure), quote, embed, image
+ ("_case", "data", "expected_data"),
+ [
+ (
+ "Paragraph",
+ {
+ "type": "paragraph",
+ "data": {"text": DIRTY, "alignment": DIRTY, "align": DIRTY},
+ },
+ {
+ "type": "paragraph",
+ "data": {"text": CLEAN, "alignment": CLEAN, "align": CLEAN},
+ },
+ ),
+ (
+ "Header",
+ {"type": "header", "data": {"text": DIRTY, "level": 2}},
+ {"type": "header", "data": {"text": CLEAN, "level": 2}},
+ ),
+ (
+ "Quote",
+ {
+ "type": "quote",
+ "data": {
+ "text": DIRTY,
+ "caption": DIRTY,
+ "alignment": DIRTY,
+ "align": DIRTY,
+ },
+ },
+ {
+ "type": "quote",
+ "data": {
+ "text": CLEAN,
+ "caption": CLEAN,
+ "alignment": CLEAN,
+ "align": CLEAN,
+ },
+ },
+ ),
+ (
+ "Embed",
+ {
+ "type": "embed",
+ "data": {
+ "service": DIRTY,
+ "source": DIRTY,
+ "embed": DIRTY,
+ "width": 580,
+ "height": 320,
+ "caption": DIRTY,
+ },
+ },
+ {
+ "type": "embed",
+ "data": {
+ "service": CLEAN,
+ "source": "#invalid",
+ "embed": "#invalid",
+ "width": 580,
+ "height": 320,
+ "caption": CLEAN,
+ },
+ },
+ ),
+ (
+ "Image",
+ {
+ "type": "image",
+ "data": {
+ "file": {
+ "url": DIRTY,
+ },
+ "url": DIRTY,
+ "caption": DIRTY,
+ "withBorder": False,
+ "withBackground": False,
+ "stretched": True,
+ },
+ },
+ {
+ "type": "image",
+ "data": {
+ "file": {
+ "url": "#invalid",
+ },
+ "url": "#invalid",
+ "caption": CLEAN,
+ "withBorder": False,
+ "withBackground": False,
+ "stretched": True,
+ },
+ },
+ ),
+ ],
+)
+def test_cleans_all_editor_js_blocks(_case, data, expected_data):
+ """Check all block types supported by Saleor and ensure they all gets cleaned."""
+
+ with warnings.catch_warnings(record=True):
+ actual = clean_editor_js({"blocks": [data]})
+
+ assert len(actual["blocks"]) == 1
+ actual = actual["blocks"][0]
+
+ assert actual == expected_data
diff --git a/saleor/settings.py b/saleor/settings.py
index 4df5873d34..fb7c7ab8b6 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -28,6 +28,7 @@ from sentry_sdk.scrubber import DEFAULT_DENYLIST, DEFAULT_PII_DENYLIST, EventScr
from . import PatchedSubscriberExecutionContext, __version__
from .account.i18n_rules_override import i18n_rules_override
+from .core.cleaners.html import HtmlCleanerSettings
from .core.db.patch import patch_db
from .core.languages import LANGUAGES as CORE_LANGUAGES
from .core.rlimit import validate_and_set_rlimit
@@ -1140,6 +1141,16 @@ TELEMETRY_SLOW_GRAPHQL_OPERATION_THRESHOLD = float(
# For development envs, where schema may change often, it may be convenient to set it to e.g. commit hash value.
GRAPHQL_CACHE_SUFFIX = os.environ.get("GRAPHQL_CACHE_SUFFIX", "")
+# Maximum depth for EditorJS nested lists. This value shouldn't be set too high to
+# prevent abuses. It's not recommended to increase it further than 10, if strictly
+# necessary (not recommended), it could be increase up to 100.
+#
+# HINT: in the frontend configuration, set `maxLevel` to the same value to improve
+# user-experience on the client-side (https://github.com/editor-js/list/blob/f8cde313224499ed5bcf3e93864fc11c45fe7efb/README.md#config-params)
+EDITOR_JS_LISTS_MAX_DEPTH = int(os.environ.get("EDITOR_JS_LISTS_MAX_DEPTH", 10))
+
+HTML_CLEANER_PREFS = HtmlCleanerSettings.parse()
+
# Library `google-i18n-address` use `AddressValidationMetadata` form Google to provide address validation rules.
# Patch `i18n` module to allows to override the default address rules.
i18n_rules_override()
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index d0ee4bc220..aae6e8b0e1 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -609,9 +609,10 @@ def description_json():
"key": "",
"data": {
"text": "E-commerce for the PWA era",
+ "level": 2,
},
"text": "E-commerce for the PWA era",
- "type": "header-two",
+ "type": "header",
"depth": 0,
"entityRanges": [],
"inlineStyleRanges": [],
@@ -695,9 +696,10 @@ def other_description_json():
"text": (
"A GRAPHQL-FIRST <b>ECOMMERCE</b> PLATFORM FOR PERFECTIONISTS"
),
+ "level": 2,
},
"text": "A GRAPHQL-FIRST ECOMMERCE PLATFORM FOR PERFECTIONISTS",
- "type": "header-two",
+ "type": "header",
"depth": 0,
"entityRanges": [],
"inlineStyleRanges": [],
diff --git a/saleor/tests/settings.py b/saleor/tests/settings.py
index 9910d2b7a1..54050fc0ff 100644
--- a/saleor/tests/settings.py
+++ b/saleor/tests/settings.py
@@ -104,3 +104,6 @@ BREAKER_BOARD_ENABLED = False
TELEMETRY_RAISE_UNIT_CONVERSION_ERRORS = True
TELEMETRY_TRACER_CLASS = "saleor.core.telemetry.tests.TestTracer"
TELEMETRY_METER_CLASS = "saleor.core.telemetry.tests.TestMeter"
+
+# New default in Saleor v3.23.0
+HTML_CLEANER_PREFS.link_rel = "noopener noreferrer" # noqa: F405 # HTML_CLEANER_PREFS exists
diff --git a/uv.lock b/uv.lock
index 931918cbfc..a9521f7c62 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1516,6 +1516,29 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963, upload-time = "2025-04-22T14:54:22.983Z" },
]
+[[package]]
+name = "nh3"
+version = "0.3.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/ca/a5/34c26015d3a434409f4d2a1cd8821a06c05238703f49283ffeb937bef093/nh3-0.3.2.tar.gz", hash = "sha256:f394759a06df8b685a4ebfb1874fb67a9cbfd58c64fc5ed587a663c0e63ec376", size = 19288, upload-time = "2025-10-30T11:17:45.948Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b6/3e/f5a5cc2885c24be13e9b937441bd16a012ac34a657fe05e58927e8af8b7a/nh3-0.3.2-cp38-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:7064ccf5ace75825bd7bf57859daaaf16ed28660c1c6b306b649a9eda4b54b1e", size = 1431980, upload-time = "2025-10-30T11:17:25.457Z" },
+ { url = "https://files.pythonhosted.org/packages/7f/f7/529a99324d7ef055de88b690858f4189379708abae92ace799365a797b7f/nh3-0.3.2-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c8745454cdd28bbbc90861b80a0111a195b0e3961b9fa2e672be89eb199fa5d8", size = 820805, upload-time = "2025-10-30T11:17:26.98Z" },
+ { url = "https://files.pythonhosted.org/packages/3d/62/19b7c50ccd1fa7d0764822d2cea8f2a320f2fd77474c7a1805cb22cf69b0/nh3-0.3.2-cp38-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:72d67c25a84579f4a432c065e8b4274e53b7cf1df8f792cf846abfe2c3090866", size = 803527, upload-time = "2025-10-30T11:17:28.284Z" },
+ { url = "https://files.pythonhosted.org/packages/4a/ca/f022273bab5440abff6302731a49410c5ef66b1a9502ba3fbb2df998d9ff/nh3-0.3.2-cp38-abi3-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:13398e676a14d6233f372c75f52d5ae74f98210172991f7a3142a736bd92b131", size = 1051674, upload-time = "2025-10-30T11:17:29.909Z" },
+ { url = "https://files.pythonhosted.org/packages/fa/f7/5728e3b32a11daf5bd21cf71d91c463f74305938bc3eb9e0ac1ce141646e/nh3-0.3.2-cp38-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:03d617e5c8aa7331bd2659c654e021caf9bba704b109e7b2b28b039a00949fe5", size = 1004737, upload-time = "2025-10-30T11:17:31.205Z" },
+ { url = "https://files.pythonhosted.org/packages/53/7f/f17e0dba0a99cee29e6cee6d4d52340ef9cb1f8a06946d3a01eb7ec2fb01/nh3-0.3.2-cp38-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f2f55c4d2d5a207e74eefe4d828067bbb01300e06e2a7436142f915c5928de07", size = 911745, upload-time = "2025-10-30T11:17:32.945Z" },
+ { url = "https://files.pythonhosted.org/packages/42/0f/c76bf3dba22c73c38e9b1113b017cf163f7696f50e003404ec5ecdb1e8a6/nh3-0.3.2-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7bb18403f02b655a1bbe4e3a4696c2ae1d6ae8f5991f7cacb684b1ae27e6c9f7", size = 797184, upload-time = "2025-10-30T11:17:34.226Z" },
+ { url = "https://files.pythonhosted.org/packages/08/a1/73d8250f888fb0ddf1b119b139c382f8903d8bb0c5bd1f64afc7e38dad1d/nh3-0.3.2-cp38-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:6d66f41672eb4060cf87c037f760bdbc6847852ca9ef8e9c5a5da18f090abf87", size = 838556, upload-time = "2025-10-30T11:17:35.875Z" },
+ { url = "https://files.pythonhosted.org/packages/d1/09/deb57f1fb656a7a5192497f4a287b0ade5a2ff6b5d5de4736d13ef6d2c1f/nh3-0.3.2-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:f97f8b25cb2681d25e2338148159447e4d689aafdccfcf19e61ff7db3905768a", size = 1006695, upload-time = "2025-10-30T11:17:37.071Z" },
+ { url = "https://files.pythonhosted.org/packages/b6/61/8f4d41c4ccdac30e4b1a4fa7be4b0f9914d8314a5058472f84c8e101a418/nh3-0.3.2-cp38-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:2ab70e8c6c7d2ce953d2a58102eefa90c2d0a5ed7aa40c7e29a487bc5e613131", size = 1075471, upload-time = "2025-10-30T11:17:38.225Z" },
+ { url = "https://files.pythonhosted.org/packages/b0/c6/966aec0cb4705e69f6c3580422c239205d5d4d0e50fac380b21e87b6cf1b/nh3-0.3.2-cp38-abi3-musllinux_1_2_i686.whl", hash = "sha256:1710f3901cd6440ca92494ba2eb6dc260f829fa8d9196b659fa10de825610ce0", size = 1002439, upload-time = "2025-10-30T11:17:39.553Z" },
+ { url = "https://files.pythonhosted.org/packages/e2/c8/97a2d5f7a314cce2c5c49f30c6f161b7f3617960ade4bfc2fd1ee092cb20/nh3-0.3.2-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:91e9b001101fb4500a2aafe3e7c92928d85242d38bf5ac0aba0b7480da0a4cd6", size = 987439, upload-time = "2025-10-30T11:17:40.81Z" },
+ { url = "https://files.pythonhosted.org/packages/0d/95/2d6fc6461687d7a171f087995247dec33e8749a562bfadd85fb5dbf37a11/nh3-0.3.2-cp38-abi3-win32.whl", hash = "sha256:169db03df90da63286e0560ea0efa9b6f3b59844a9735514a1d47e6bb2c8c61b", size = 589826, upload-time = "2025-10-30T11:17:42.239Z" },
+ { url = "https://files.pythonhosted.org/packages/64/9a/1a1c154f10a575d20dd634e5697805e589bbdb7673a0ad00e8da90044ba7/nh3-0.3.2-cp38-abi3-win_amd64.whl", hash = "sha256:562da3dca7a17f9077593214a9781a94b8d76de4f158f8c895e62f09573945fe", size = 596406, upload-time = "2025-10-30T11:17:43.773Z" },
+ { url = "https://files.pythonhosted.org/packages/9e/7e/a96255f63b7aef032cbee8fc4d6e37def72e3aaedc1f72759235e8f13cb1/nh3-0.3.2-cp38-abi3-win_arm64.whl", hash = "sha256:cf5964d54edd405e68583114a7cba929468bcd7db5e676ae38ee954de1cfc104", size = 584162, upload-time = "2025-10-30T11:17:44.96Z" },
+]
+
[[package]]
name = "nodeenv"
version = "1.9.1"
@@ -2558,11 +2581,13 @@ dependencies = [
{ name = "graphql-core", marker = "platform_python_implementation != 'PyPy'" },
{ name = "graphql-relay", marker = "platform_python_implementation != 'PyPy'" },
{ name = "html-to-draftjs", marker = "platform_python_implementation != 'PyPy'" },
+ { name = "idna", marker = "platform_python_implementation != 'PyPy'" },
{ name = "kombu", extra = ["sqs"], marker = "platform_python_implementation != 'PyPy'" },
{ name = "lxml", marker = "platform_python_implementation != 'PyPy'" },
{ name = "markdown", marker = "platform_python_implementation != 'PyPy'" },
{ name = "measurement", marker = "platform_python_implementation != 'PyPy'" },
{ name = "micawber", marker = "platform_python_implementation != 'PyPy'" },
+ { name = "nh3", marker = "platform_python_implementation != 'PyPy'" },
{ name = "oauthlib", marker = "platform_python_implementation != 'PyPy'" },
{ name = "opentelemetry-api", marker = "platform_python_implementation != 'PyPy'" },
{ name = "opentelemetry-distro", extra = ["otlp"], marker = "platform_python_implementation != 'PyPy'" },
@@ -2672,11 +2697,13 @@ requires-dist = [
{ name = "graphql-core", specifier = ">=2.3.2,<3" },
{ name = "graphql-relay", specifier = ">=2.0.1,<3" },
{ name = "html-to-draftjs", specifier = ">=1.0.1,<2" },
+ { name = "idna", specifier = ">=3.10" },
{ name = "kombu", extras = ["sqs"], specifier = ">=4.6.11,<6.0.0" },
{ name = "lxml", specifier = ">=4.9.3,<5" },
{ name = "markdown", specifier = ">=3.1.1,<4" },
{ name = "measurement", specifier = ">=3.2.2,<4" },
{ name = "micawber", specifier = ">=0.5.5,<0.6" },
+ { name = "nh3", specifier = ">=0.2.20" },
{ name = "oauthlib", specifier = "~=3.1" },
{ name = "opentelemetry-api", specifier = ">=1.32.1,<2" },
{ name = "opentelemetry-distro", extras = ["otlp"], specifier = ">=0.53b1,<0.54" },