Skip to content

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

Add validators for translation mutations (#8942)

Rafał Pitoń269670831e5f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e3a6cf6359..87b4d0051f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,6 +29,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Do no allow using id for updating checkout and order metadata - #8906 by @IKarbowiak
- Fix crash when querying external shipping method's `translation` field - #8971 by @rafalp
- Add `COLLECTION_CREATED`, `COLLECTION_UPDATED`, `COLLECTION_DELETED` events and webhooks - #8974 by @rafalp
+- Fix crash when too long translation strings were passed to `translate` mutations - #8942 by rafalp
# 3.0.0 [Unreleased]
diff --git a/saleor/core/error_codes.py b/saleor/core/error_codes.py
index eae887dd9e..e0fcda3cd6 100644
--- a/saleor/core/error_codes.py
+++ b/saleor/core/error_codes.py
@@ -20,6 +20,7 @@ class MetadataErrorCode(Enum):
class TranslationErrorCode(Enum):
GRAPHQL_ERROR = "graphql_error"
+ INVALID = "invalid"
NOT_FOUND = "not_found"
REQUIRED = "required"
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 561442b7e6..81560c9d1b 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -6885,6 +6885,7 @@ type TranslationError {
enum TranslationErrorCode {
GRAPHQL_ERROR
+ INVALID
NOT_FOUND
REQUIRED
}
diff --git a/saleor/graphql/translations/mutations.py b/saleor/graphql/translations/mutations.py
index 3ffaaf60e8..395168bd90 100644
--- a/saleor/graphql/translations/mutations.py
+++ b/saleor/graphql/translations/mutations.py
@@ -1,6 +1,7 @@
import graphene
from django.core.exceptions import ValidationError
from django.db import transaction
+from django.db.models import Model
from ...attribute import models as attribute_models
from ...core.permissions import SitePermissions
@@ -10,6 +11,7 @@ from ...menu import models as menu_models
from ...page import models as page_models
from ...product import models as product_models
from ...shipping import models as shipping_models
+from ...site.models import SiteSettings
from ..attribute import types as attribute_types
from ..channel import ChannelContext
from ..core.enums import LanguageCodeEnum
@@ -50,6 +52,14 @@ TRANSLATABLE_CONTENT_TO_TYPE = {
}
+def validate_input_against_model(model: Model, input_data: dict):
+ data_to_validate = {key: value for key, value in input_data.items() if value}
+ instance = model(**data_to_validate) # type: ignore
+ all_fields = [field.name for field in model._meta.fields]
+ exclude_fields = set(all_fields) - set(data_to_validate)
+ instance.full_clean(exclude=exclude_fields, validate_unique=False)
+
+
class BaseTranslateMutation(ModelMutation):
class Meta:
abstract = True
@@ -75,10 +85,16 @@ class BaseTranslateMutation(ModelMutation):
return node_id, model_type
+ @classmethod
+ def validate_input(cls, input_data):
+ validate_input_against_model(cls._meta.model, input_data)
+
@classmethod
def perform_mutation(cls, _root, info, **data):
node_id, model_type = cls.clean_node_id(**data)
instance = cls.get_node_or_error(info, node_id, only_type=model_type)
+ cls.validate_input(data["input"])
+
translation, created = instance.translations.update_or_create(
language_code=data["language_code"], defaults=data["input"]
)
@@ -158,6 +174,7 @@ class ProductTranslate(BaseTranslateMutation):
def perform_mutation(cls, _root, info, **data):
node_id = cls.clean_node_id(**data)[0]
product = cls.get_node_or_error(info, node_id, only_type=product_types.Product)
+ cls.validate_input(data["input"])
translation, created = product.translations.update_or_create(
language_code=data["language_code"], defaults=data["input"]
@@ -228,6 +245,7 @@ class ProductVariantTranslate(BaseTranslateMutation):
variant = product_models.ProductVariant.objects.prefetched_for_webhook().get(
pk=variant_pk
)
+ cls.validate_input(data["input"])
translation, created = variant.translations.update_or_create(
language_code=data["language_code"], defaults=data["input"]
)
@@ -450,6 +468,7 @@ class ShopSettingsTranslate(BaseMutation):
@traced_atomic_transaction()
def perform_mutation(cls, _root, info, language_code, **data):
instance = info.context.site.settings
+ validate_input_against_model(SiteSettings, data["input"])
translation, created = instance.translations.update_or_create(
language_code=language_code, defaults=data.get("input")
)
diff --git a/saleor/graphql/translations/tests/test_translations.py b/saleor/graphql/translations/tests/test_translations.py
index 13613de47a..b5a6691f30 100644
--- a/saleor/graphql/translations/tests/test_translations.py
+++ b/saleor/graphql/translations/tests/test_translations.py
@@ -818,6 +818,10 @@ PRODUCT_TRANSLATE_MUTATION = """
}
}
}
+ errors {
+ field
+ code
+ }
}
}
"""
@@ -922,6 +926,27 @@ def test_product_create_translation_by_translatable_content_id(
assert data["product"]["translation"]["language"]["code"] == "PL"
+def test_product_create_translation_validates_name_length(
+ staff_api_client, product, permission_manage_translations
+):
+ product_id = graphene.Node.to_global_id("Product", product.id)
+ variables = {
+ "productId": product_id,
+ "input": {"description": None, "name": "Long" * 100},
+ }
+ response = staff_api_client.post_graphql(
+ PRODUCT_TRANSLATE_MUTATION,
+ variables,
+ permissions=[permission_manage_translations],
+ )
+ data = get_graphql_content(response)["data"]["productTranslate"]
+
+ assert data["product"] is None
+ assert data["errors"] == [
+ {"field": "name", "code": "INVALID"},
+ ]
+
+
@freeze_time("1914-06-28 10:50")
@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
def test_product_update_translation(
@@ -968,6 +993,10 @@ mutation productVariantTranslate(
}
}
}
+ errors {
+ field
+ code
+ }
}
}
"""
@@ -1053,6 +1082,33 @@ def test_product_variant_update_translation(
)
+def test_product_variant_translation_mutation_validates_inputs_length(
+ staff_api_client,
+ variant,
+ channel_USD,
+ permission_manage_translations,
+):
+ translatable_content_id = graphene.Node.to_global_id(
+ "ProductVariantTranslatableContent", variant.id
+ )
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_TRANSLATE_MUTATION,
+ {
+ "productVariantId": translatable_content_id,
+ "input": {"name": "Wariant PL" * 100},
+ },
+ permissions=[permission_manage_translations],
+ )
+ data = get_graphql_content(response)["data"]["productVariantTranslate"]
+ assert data["productVariant"] is None
+ assert data["errors"] == [
+ {
+ "field": "name",
+ "code": "INVALID",
+ }
+ ]
+
+
COLLECTION_TRANSLATE_MUTATION = """
mutation collectionTranslate($collectionId: ID!, $input: TranslationInput!) {
collectionTranslate(
@@ -1067,6 +1123,10 @@ mutation collectionTranslate($collectionId: ID!, $input: TranslationInput!) {
}
}
}
+ errors {
+ field
+ code
+ }
}
}
"""
@@ -1189,6 +1249,25 @@ def test_collection_update_translation(
)
+def test_collection_translation_mutation_validates_inputs_length(
+ staff_api_client, published_collection, permission_manage_translations
+):
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.id)
+ description = dummy_editorjs("description", True)
+ response = staff_api_client.post_graphql(
+ COLLECTION_TRANSLATE_MUTATION,
+ {
+ "collectionId": collection_id,
+ "input": {"description": description, "name": "long" * 100},
+ },
+ permissions=[permission_manage_translations],
+ )
+ data = get_graphql_content(response)["data"]["collectionTranslate"]
+
+ assert data["collection"] is None
+ assert data["errors"] == [{"field": "name", "code": "INVALID"}]
+
+
CATEGORY_TRANSLATE_MUTATION = """
mutation categoryTranslate($categoryId: ID!, $input: TranslationInput!) {
categoryTranslate(
@@ -2092,6 +2171,27 @@ def test_shop_create_translation(
)
+SHOP_SETTINGS_TRANSLATE_MUTATION = """
+ mutation shopSettingsTranslate($input: ShopSettingsTranslationInput!) {
+ shopSettingsTranslate(
+ languageCode: PL, input: $input) {
+ shop {
+ translation(languageCode: PL) {
+ headerText
+ language {
+ code
+ }
+ }
+ }
+ errors {
+ field
+ code
+ }
+ }
+ }
+"""
+
+
@freeze_time("1914-06-28 10:50")
@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
def test_shop_update_translation(
@@ -2107,24 +2207,10 @@ def test_shop_update_translation(
language_code="pl", header_text="Nagłówek"
)
- query = """
- mutation shopSettingsTranslate {
- shopSettingsTranslate(
- languageCode: PL, input: {headerText: "Nagłówek PL"}) {
- shop {
- translation(languageCode: PL) {
- headerText
- language {
- code
- }
- }
- }
- }
- }
- """
-
response = staff_api_client.post_graphql(
- query, permissions=[permission_manage_translations]
+ SHOP_SETTINGS_TRANSLATE_MUTATION,
+ {"input": {"headerText": "Nagłówek PL"}},
+ permissions=[permission_manage_translations],
)
data = get_graphql_content(response)["data"]["shopSettingsTranslate"]
@@ -2139,6 +2225,28 @@ def test_shop_update_translation(
)
+@freeze_time("1914-06-28 10:50")
+@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_shop_translation_validates_values_lengths(
+ mocked_webhook_trigger,
+ staff_api_client,
+ site_settings,
+ permission_manage_translations,
+ settings,
+):
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ response = staff_api_client.post_graphql(
+ SHOP_SETTINGS_TRANSLATE_MUTATION,
+ {"input": {"headerText": "Nagłówek PL" * 100}},
+ permissions=[permission_manage_translations],
+ )
+ data = get_graphql_content(response)["data"]["shopSettingsTranslate"]
+
+ assert data["shop"] is None
+ assert data["errors"] == [{"field": "headerText", "code": "INVALID"}]
+
+
@pytest.mark.parametrize(
"kind, expected_typename",
[