Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Make sure string truncation does not exceed the database field limits (#18062)
Patryk Zawadzki29ac36d1d929
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ff4cb14f15..cba4cff40a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -133,6 +133,8 @@ Like `reference`, the `single-reference` type can target entities defined in the- Checkouts having total gross amount equal to 0 will get their authorization statuses updated to `CheckoutAuthorizeStatus.FULL` upon fetching checkout data.+- Fixed a bug that could prevent rich text attributes written in scripts using combining diacritical marks (for example, Arabic) from being saved properly.+### DeprecationsFollowing plugins are now marked as deprecated:diff --git a/saleor/attribute/tests/fixtures/attribute.py b/saleor/attribute/tests/fixtures/attribute.pyindex 4cd3861ef0..50589ddc03 100644--- a/saleor/attribute/tests/fixtures/attribute.py+++ b/saleor/attribute/tests/fixtures/attribute.py@@ -1,10 +1,10 @@import datetimeimport pytest-from django.template.defaultfilters import truncatecharsfrom ....core.units import MeasurementUnitsfrom ....core.utils.editorjs import clean_editor_js+from ....core.utils.text import safe_truncatefrom ....tests.utils import dummy_editorjsfrom ... import AttributeEntityType, AttributeInputType, AttributeTypefrom ...models import Attribute, AttributeValue@@ -325,7 +325,7 @@ def rich_text_attribute(db):text = "Rich text attribute content."AttributeValue.objects.create(attribute=attribute,- name=truncatechars(clean_editor_js(dummy_editorjs(text), to_string=True), 50),+ name=safe_truncate(clean_editor_js(dummy_editorjs(text), to_string=True), 50),slug=f"instance_{attribute.id}",rich_text=dummy_editorjs(text),)@@ -346,7 +346,7 @@ def rich_text_attribute_page_type(db):text = "Rich text attribute content."AttributeValue.objects.create(attribute=attribute,- name=truncatechars(clean_editor_js(dummy_editorjs(text), to_string=True), 50),+ name=safe_truncate(clean_editor_js(dummy_editorjs(text), to_string=True), 50),slug=f"instance_{attribute.id}",rich_text=dummy_editorjs(text),)@@ -362,7 +362,7 @@ def rich_text_attribute_with_many_values(rich_text_attribute):values.append(AttributeValue(attribute=attribute,- name=truncatechars(+ name=safe_truncate(clean_editor_js(dummy_editorjs(text), to_string=True), 50),slug=f"instance_{attribute.id}_{i}",@@ -387,7 +387,7 @@ def plain_text_attribute(db):text = "Plain text attribute content."AttributeValue.objects.create(attribute=attribute,- name=truncatechars(text, 50),+ name=safe_truncate(text, 50),slug=f"instance_{attribute.id}",plain_text=text,)@@ -408,7 +408,7 @@ def plain_text_attribute_page_type(db):text = "Plain text attribute content."AttributeValue.objects.create(attribute=attribute,- name=truncatechars(text, 50),+ name=safe_truncate(text, 50),slug=f"instance_{attribute.id}",plain_text=text,)diff --git a/saleor/core/utils/tests/test_text.py b/saleor/core/utils/tests/test_text.pynew file mode 100644index 0000000000..e753fab9a0--- /dev/null+++ b/saleor/core/utils/tests/test_text.py@@ -0,0 +1,16 @@+from ..text import safe_truncate+++def test_safe_truncate():+ assert safe_truncate("Hello, world!", 5) == "Hell…"+ assert safe_truncate("Hello, world!", 20) == "Hello, world!"+ assert safe_truncate("Hello, 世界!", 9) == "Hello, 世…"+ assert safe_truncate("Hello, 世界!", 15) == "Hello, 世界!"+ assert safe_truncate("Hello, world!", 1) == "…"+++def test_safe_truncate_with_combining_characters():+ # characters at positions 6 and 7 are combining marks for character at position 5+ # so we want to either preserve all three or skip all three+ assert len(safe_truncate("مُـحمَّـد", 7)) == 7+ assert len(safe_truncate("مُـحمَّـد", 6)) == 4diff --git a/saleor/core/utils/text.py b/saleor/core/utils/text.pynew file mode 100644index 0000000000..92e56a1861--- /dev/null+++ b/saleor/core/utils/text.py@@ -0,0 +1,19 @@+import unicodedata+++def safe_truncate(text: str, max_length: int) -> str:+ """Truncate text to a safe length while avoiding breaking combining diacritical marks."""+ if max_length <= 0:+ raise ValueError("max_length must be greater than 0")+ # normalize text to its shortest Unicode representation+ text = unicodedata.normalize("NFC", text)+ if len(text) <= max_length:+ return text+ end_pos = max_length - 1+ if unicodedata.combining(text[end_pos + 1]):+ # if the first truncated character was a combining mark, truncate the entire+ # combination to avoid breaking characters+ while unicodedata.combining(text[end_pos]):+ end_pos -= 1+ end_pos -= 1+ return text[:end_pos] + "…"diff --git a/saleor/graphql/attribute/utils/type_handlers.py b/saleor/graphql/attribute/utils/type_handlers.pyindex 3f79359b0c..39c4abb3f3 100644--- a/saleor/graphql/attribute/utils/type_handlers.py+++ b/saleor/graphql/attribute/utils/type_handlers.py@@ -6,7 +6,6 @@ from typing import TYPE_CHECKINGfrom django.core.exceptions import ValidationErrorfrom django.db.models import Q-from django.template.defaultfilters import truncatecharsfrom django.utils.text import slugifyfrom graphql.error import GraphQLErrorfrom text_unidecode import unidecode@@ -20,6 +19,7 @@ from ....core.utils import (prepare_unique_slug,)from ....core.utils.editorjs import clean_editor_js+from ....core.utils.text import safe_truncatefrom ....core.utils.url import get_default_storage_root_urlfrom ...core.utils import from_global_id_or_error, get_duplicated_valuesfrom ...utils import get_nodes@@ -505,7 +505,7 @@ class PlainTextAttributeHandler(AttributeTypeHandler):defaults = {"plain_text": plain_text,- "name": truncatechars(plain_text, 200),+ "name": safe_truncate(plain_text, 200),}return self._update_or_create_value(instance, defaults)@@ -528,7 +528,7 @@ class RichTextAttributeHandler(AttributeTypeHandler):defaults = {"rich_text": rich_text,- "name": truncatechars(clean_editor_js(rich_text, to_string=True), 200),+ "name": safe_truncate(clean_editor_js(rich_text, to_string=True), 200),}return self._update_or_create_value(instance, defaults)diff --git a/saleor/graphql/translations/mutations/attribute_value_bulk_translate.py b/saleor/graphql/translations/mutations/attribute_value_bulk_translate.pyindex 515c168303..99d1ecc6c1 100644--- a/saleor/graphql/translations/mutations/attribute_value_bulk_translate.py+++ b/saleor/graphql/translations/mutations/attribute_value_bulk_translate.py@@ -1,10 +1,10 @@import graphenefrom django.core.exceptions import ValidationError-from django.template.defaultfilters import truncatecharsfrom graphql.error import GraphQLErrorfrom ....attribute import AttributeInputType, modelsfrom ....core.utils.editorjs import clean_editor_js+from ....core.utils.text import safe_truncatefrom ....permission.enums import SitePermissionsfrom ...attribute.types import AttributeValueTranslationfrom ...core.doc_category import DOC_CATEGORY_ATTRIBUTES@@ -137,11 +137,11 @@ class AttributeValueBulkTranslate(BaseBulkTranslateMutation):if input_data.get("name") is None:attribute = instance.attribute_value.attributeif attribute.input_type == AttributeInputType.RICH_TEXT:- input_data["name"] = truncatechars(+ input_data["name"] = safe_truncate(clean_editor_js(input_data["rich_text"], to_string=True), 250)elif attribute.input_type == AttributeInputType.PLAIN_TEXT:- input_data["name"] = truncatechars(input_data["plain_text"], 250)+ input_data["name"] = safe_truncate(input_data["plain_text"], 250)# Set this value on the instance too as at this point it was already created# input_data will be used for validationdiff --git a/saleor/graphql/translations/mutations/attribute_value_translate.py b/saleor/graphql/translations/mutations/attribute_value_translate.pyindex 9bccbf6944..1b32a46380 100644--- a/saleor/graphql/translations/mutations/attribute_value_translate.py+++ b/saleor/graphql/translations/mutations/attribute_value_translate.py@@ -1,9 +1,9 @@import graphene-from django.template.defaultfilters import truncatecharsfrom ....attribute import AttributeInputTypefrom ....attribute import models as attribute_modelsfrom ....core.utils.editorjs import clean_editor_js+from ....core.utils.text import safe_truncatefrom ....permission.enums import SitePermissionsfrom ...attribute.types import AttributeValuefrom ...core.context import ChannelContext@@ -45,11 +45,11 @@ class AttributeValueTranslate(BaseTranslateMutation):def pre_update_or_create(cls, instance, input_data, language_code):if "name" not in input_data.keys() or input_data["name"] is None:if instance.attribute.input_type == AttributeInputType.RICH_TEXT:- input_data["name"] = truncatechars(+ input_data["name"] = safe_truncate(clean_editor_js(input_data["rich_text"], to_string=True), 250)elif instance.attribute.input_type == AttributeInputType.PLAIN_TEXT:- input_data["name"] = truncatechars(input_data["plain_text"], 250)+ input_data["name"] = safe_truncate(input_data["plain_text"], 250)return input_data@classmethoddiff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex f81facf482..e3186f3b8d 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -10,7 +10,6 @@ from django.conf import settingsfrom django.core.serializers.json import DjangoJSONEncoderfrom django.db import IntegrityError, transactionfrom django.db.models import Q-from django.template.defaultfilters import truncatecharsfrom django.utils import timezonefrom pydantic import ValidationError@@ -29,6 +28,7 @@ from ..checkout.payment_utils import update_refundable_for_checkoutfrom ..core.db.connection import allow_writerfrom ..core.prices import quantize_pricefrom ..core.tracing import traced_atomic_transaction+from ..core.utils.text import safe_truncatefrom ..graphql.core.utils import str_to_enumfrom ..order import OrderStatusfrom ..order.actions import order_transaction_updated@@ -1055,7 +1055,7 @@ def parse_available_actions(available_actions):def truncate_transaction_event_message(message: str):- return truncatechars(message, TRANSACTION_EVENT_MSG_MAX_LENGTH)+ return safe_truncate(message, TRANSACTION_EVENT_MSG_MAX_LENGTH)def get_failed_transaction_event_type_for_request_event(diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 5122d48e69..a9ef8a641b 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -8,7 +8,6 @@ from typing import TYPE_CHECKING, Any, Final, Optional, Union, castimport graphenefrom django.conf import settings-from django.template.defaultfilters import truncatecharsfrom pydantic import ValidationErrorfrom ...app.models import App@@ -22,6 +21,7 @@ from ...core.taxes import TAX_ERROR_FIELD_LENGTH, TaxData, TaxDataError, TaxTypefrom ...core.telemetry import get_task_contextfrom ...core.utils import build_absolute_uri, get_domainfrom ...core.utils.json_serializer import CustomJsonEncoder+from ...core.utils.text import safe_truncatefrom ...csv.notifications import get_default_export_payloadfrom ...graphql.core.context import SaleorContextfrom ...graphql.webhook.subscription_payload import (@@ -3525,7 +3525,7 @@ class WebhookPlugin(BasePlugin):str(e),extra={"errors": errors},)- error_msg = truncatechars(parse_validation_error(e), TAX_ERROR_FIELD_LENGTH)+ error_msg = safe_truncate(parse_validation_error(e), TAX_ERROR_FIELD_LENGTH)raise TaxDataError(error_msg, errors=errors) from ereturn tax_data