Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Gracefully handle invalid json string (#19205)
Lukasz Ostrowskie0f2933d58b9
diff --git a/saleor/graphql/core/fields.py b/saleor/graphql/core/fields.pyindex 9081f3bb4a..5b713185e9 100644--- a/saleor/graphql/core/fields.py+++ b/saleor/graphql/core/fields.py@@ -165,5 +165,12 @@ class JSONString(graphene.JSONString):def parse_literal(node):try:return graphene.JSONString.parse_literal(node)- except JSONDecodeError:+ except (JSONDecodeError, TypeError):+ return None++ @staticmethod+ def parse_value(value):+ try:+ return graphene.JSONString.parse_value(value)+ except (JSONDecodeError, TypeError):return Nonediff --git a/saleor/graphql/core/tests/test_json_string_scalar.py b/saleor/graphql/core/tests/test_json_string_scalar.pynew file mode 100644index 0000000000..f650128ffa--- /dev/null+++ b/saleor/graphql/core/tests/test_json_string_scalar.py@@ -0,0 +1,48 @@+import pytest+from graphql.language.ast import IntValue, ObjectValue, StringValue++from ..fields import JSONString+++ ("value", "expected"),+ [+ ('{"a": 1}', {"a": 1}),+ ("[1, 2, 3]", [1, 2, 3]),+ ('"text"', "text"),+ ("null", None),+ ],+)+def test_parse_value_valid_string(value, expected):+ assert JSONString.parse_value(value) == expected+++ "invalid_value",+ [+ {"a": 1},+ [1, 2, 3],+ 123,+ None,+ "{not json}",+ ],+)+def test_parse_value_invalid_returns_none(invalid_value):+ assert JSONString.parse_value(invalid_value) is None+++def test_parse_literal_valid_string():+ node = StringValue(value='{"a": 1}')+ assert JSONString.parse_literal(node) == {"a": 1}+++ "invalid_node",+ [+ StringValue(value="{not json}"),+ IntValue(value="1"),+ ObjectValue(fields=[]),+ ],+)+def test_parse_literal_invalid_returns_none(invalid_node):+ assert JSONString.parse_literal(invalid_node) is Nonediff --git a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_bulk_create.pyindex 634c087b7d..ac7cffc9f7 100644--- a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py@@ -29,6 +29,7 @@ from .....product.tests.utils import (from ....core.enums import ErrorPolicyEnumfrom ....tests.utils import (get_graphql_content,+ get_graphql_content_from_response,get_multipart_request_body_with_multiple_files,)@@ -268,6 +269,69 @@ def test_product_bulk_create_with_base_data(assert rule.variants_dirty is True+def test_product_bulk_create_with_description_as_json_object_does_not_crash(+ staff_api_client,+ product_type,+ category,+ permission_manage_products,+):+ """Ensure Saleor properly handles invalid JSON inputs in rich text inputs.++ Regression for Sentry SALEOR-CORE-845: a client sending the `description`+ JSONString variable as a JSON object (dict) instead of a JSON-encoded+ string used to raise TypeError from graphene's `parse_value` and surface+ as an unhandled 500-style error. After the fix, the invalid value is+ rejected as a normal GraphQL validation error.+ """++ # given+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)+ category_id = graphene.Node.to_global_id("Category", category.pk)+ product_name = "test name"+ # Expects a JSON string (`str`), but we pass an object instead (invalid)+ description = {"foo": "bar"}++ products = [+ {+ "productType": product_type_id,+ "category": category_id,+ "name": product_name,+ "description": description,+ },+ ]++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_BULK_CREATE_MUTATION,+ {"products": products},+ )++ # then+ content = get_graphql_content_from_response(response)+ input_dump = json.dumps(+ [+ {+ "category": category_id,+ "description": description,+ "name": product_name,+ "productType": product_type_id,+ }+ ],+ sort_keys=True,+ )+ description_dump = json.dumps(description, sort_keys=True)+ expected_message = (+ f'Variable "$products" got invalid value {input_dump}.\n'+ f'In element #0: In field "description": '+ f'Expected type "JSONString", found {description_dump}.'+ )+ assert "errors" in content+ assert len(content["errors"]) == 1+ assert content["errors"][0]["message"] == expected_message+ assert not Product.objects.filter(name=product_name).exists()++def test_product_bulk_create_with_base_data_and_collections(staff_api_client,product_type,