Skip to content

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

Make sure string truncation does not exceed the database field limits (#18062)

Patryk Zawadzki29ac36d1d929
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 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.
+
### Deprecations
Following plugins are now marked as deprecated:
diff --git a/saleor/attribute/tests/fixtures/attribute.py b/saleor/attribute/tests/fixtures/attribute.py
index 4cd3861ef0..50589ddc03 100644
--- a/saleor/attribute/tests/fixtures/attribute.py
+++ b/saleor/attribute/tests/fixtures/attribute.py
@@ -1,10 +1,10 @@
import datetime
import pytest
-from django.template.defaultfilters import truncatechars
from ....core.units import MeasurementUnits
from ....core.utils.editorjs import clean_editor_js
+from ....core.utils.text import safe_truncate
from ....tests.utils import dummy_editorjs
from ... import AttributeEntityType, AttributeInputType, AttributeType
from ...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.py
new file mode 100644
index 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)) == 4
diff --git a/saleor/core/utils/text.py b/saleor/core/utils/text.py
new file mode 100644
index 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.py
index 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_CHECKING
from django.core.exceptions import ValidationError
from django.db.models import Q
-from django.template.defaultfilters import truncatechars
from django.utils.text import slugify
from graphql.error import GraphQLError
from 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_truncate
from ....core.utils.url import get_default_storage_root_url
from ...core.utils import from_global_id_or_error, get_duplicated_values
from ...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.py
index 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 graphene
from django.core.exceptions import ValidationError
-from django.template.defaultfilters import truncatechars
from graphql.error import GraphQLError
from ....attribute import AttributeInputType, models
from ....core.utils.editorjs import clean_editor_js
+from ....core.utils.text import safe_truncate
from ....permission.enums import SitePermissions
from ...attribute.types import AttributeValueTranslation
from ...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.attribute
if 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 validation
diff --git a/saleor/graphql/translations/mutations/attribute_value_translate.py b/saleor/graphql/translations/mutations/attribute_value_translate.py
index 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 truncatechars
from ....attribute import AttributeInputType
from ....attribute import models as attribute_models
from ....core.utils.editorjs import clean_editor_js
+from ....core.utils.text import safe_truncate
from ....permission.enums import SitePermissions
from ...attribute.types import AttributeValue
from ...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
@classmethod
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index f81facf482..e3186f3b8d 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -10,7 +10,6 @@ from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.db import IntegrityError, transaction
from django.db.models import Q
-from django.template.defaultfilters import truncatechars
from django.utils import timezone
from pydantic import ValidationError
@@ -29,6 +28,7 @@ from ..checkout.payment_utils import update_refundable_for_checkout
from ..core.db.connection import allow_writer
from ..core.prices import quantize_price
from ..core.tracing import traced_atomic_transaction
+from ..core.utils.text import safe_truncate
from ..graphql.core.utils import str_to_enum
from ..order import OrderStatus
from ..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.py
index 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, cast
import graphene
from django.conf import settings
-from django.template.defaultfilters import truncatechars
from pydantic import ValidationError
from ...app.models import App
@@ -22,6 +21,7 @@ from ...core.taxes import TAX_ERROR_FIELD_LENGTH, TaxData, TaxDataError, TaxType
from ...core.telemetry import get_task_context
from ...core.utils import build_absolute_uri, get_domain
from ...core.utils.json_serializer import CustomJsonEncoder
+from ...core.utils.text import safe_truncate
from ...csv.notifications import get_default_export_payload
from ...graphql.core.context import SaleorContext
from ...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 e
return tax_data