Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Mutations breaks on partially invalid IDs for 3.1 (#9227)
Jakube3b6df2eba77
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex 2e31c5aab8..a927521784 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -327,6 +327,38 @@ def test_checkout_create_with_unavailable_variant(assert error["variants"] == [variant_id]+def test_checkout_create_with_malicious_variant_id(+ api_client, stock, graphql_address_data, channel_USD+):++ variant = stock.product_variant+ variant.channel_listings.filter(channel=channel_USD).update(price_amount=None)+ test_email = "[email protected]"+ shipping_address = graphql_address_data+ variant_id = (+ "UHJvZHVjdFZhcmlhbnQ6NDkxMyd8fERCTVNfUElQRS5SRUNFSVZFX01FU1N"+ "BR0UoQ0hSKDk4KXx8Q0hSKDk4KXx8Q0hSKDk4KSwxNSl8fCc="+ )+ # This string translates to+ # ProductVariant:4913'||DBMS_PIPE.RECEIVE_MESSAGE(CHR(98)||CHR(98)||CHR(98),15)||'++ variables = {+ "checkoutInput": {+ "channel": channel_USD.slug,+ "lines": [{"quantity": 1, "variantId": variant_id}],+ "email": test_email,+ "shippingAddress": shipping_address,+ }+ }++ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)++ error = get_graphql_content(response)["data"]["checkoutCreate"]["errors"][0]++ assert error["field"] == "variantId"+ assert error["code"] == "GRAPHQL_ERROR"++def test_checkout_create_with_inactive_default_channel(api_client, stock, graphql_address_data, channel_USD):diff --git a/saleor/graphql/checkout/tests/test_checkout_lines.py b/saleor/graphql/checkout/tests/test_checkout_lines.pyindex 6f542a5f67..5ae8e6125a 100644--- a/saleor/graphql/checkout/tests/test_checkout_lines.py+++ b/saleor/graphql/checkout/tests/test_checkout_lines.py@@ -1287,11 +1287,9 @@ def tests_checkout_lines_delete_invalid_lines_ids(user_api_client, checkout_withvariables = {"token": checkout.token, "linesIds": lines_list}response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_DELETE, variables)- content = get_graphql_content(response)- errors = content["data"]["checkoutLinesDelete"]["errors"][0]- assert errors["code"] == CheckoutErrorCode.INVALID.name- assert errors["lines"] == lines_list[1:]- assert errors["field"] == "lineId"+ content = get_graphql_content(response, ignore_errors=True)+ errors = content["errors"][0]+ assert errors["extensions"]["exception"]["code"] == "GraphQLError"assert checkout.last_change == previous_last_changediff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.pyindex 8e24fee864..acfebe3683 100644--- a/saleor/graphql/core/utils/__init__.py+++ b/saleor/graphql/core/utils/__init__.py@@ -2,6 +2,7 @@ import binasciiimport osimport secretsfrom typing import TYPE_CHECKING, Type, Union+from uuid import UUIDimport graphenefrom django.core.exceptions import ValidationError@@ -11,6 +12,7 @@ from graphql.error import GraphQLErrorfrom PIL import Imagefrom ....core.utils import generate_unique_slug+from ....plugins.webhook.utils import APP_ID_PREFIXif TYPE_CHECKING:# flake8: noqa@@ -139,24 +141,46 @@ def validate_required_string_field(cleaned_input, field_name: str):return cleaned_input+def validate_if_int_or_uuid(id):+ result = True+ try:+ int(id)+ except ValueError:+ try:+ UUID(id)+ except (AttributeError, ValueError):+ result = False+ return result++def from_global_id_or_error(- id: str, only_type: Union[ObjectType, str] = None, raise_error: bool = False+ global_id: str, only_type: Union[ObjectType, str] = None, raise_error: bool = False):- """Resolve database ID from global ID or raise ValidationError.+ """Resolve global ID or raise GraphQLError.+ Validates if given ID is a proper ID handled by Saleor.+ Valid IDs formats, base64 encoded:+ 'app:<int>:<str>' : External app ID with 'app' prefix+ '<type>:<int>' : Internal ID containing object type and ID as integer+ '<type>:<UUID>' : Internal ID containing object type and UUIDOptionally validate the object type, if `only_type` is provided,raise GraphQLError when `raise_error` is set to True."""try:- _type, _id = graphene.Node.from_global_id(id)+ type_, id_ = graphene.Node.from_global_id(global_id)except (binascii.Error, UnicodeDecodeError, ValueError):- raise GraphQLError(f"Couldn't resolve id: {id}.")+ raise GraphQLError(f"Couldn't resolve id: {global_id}.")+ if type_ == APP_ID_PREFIX:+ id_ = global_id+ else:+ if not validate_if_int_or_uuid(id_):+ raise GraphQLError(f"Error occurred during ID - {global_id} validation.")- if only_type and str(_type) != str(only_type):+ if only_type and str(type_) != str(only_type):if not raise_error:- return _type, None+ return type_, Noneraise GraphQLError(f"Must receive a {only_type} id.")- return _type, _id+ return type_, id_def add_hash_to_file_name(file):diff --git a/saleor/graphql/product/tests/test_product_sorting_attributes.py b/saleor/graphql/product/tests/test_product_sorting_attributes.pyindex f9bdf9ce8d..011d34bfca 100644--- a/saleor/graphql/product/tests/test_product_sorting_attributes.py+++ b/saleor/graphql/product/tests/test_product_sorting_attributes.py@@ -603,7 +603,6 @@ def test_sort_product_not_having_attribute_data(api_client, category, count_quer"attribute_id",["",- graphene.Node.to_global_id("Attribute", "not a number"),graphene.Node.to_global_id("Attribute", -1),],)@@ -622,13 +621,38 @@ def test_sort_product_by_attribute_using_invalid_attribute_id("channel": channel_USD.slug,}- response = get_graphql_content(api_client.post_graphql(query, variables))+ response = get_graphql_content(+ api_client.post_graphql(+ query,+ variables,+ ),+ ignore_errors=True,+ )products = response["data"]["products"]["edges"]assert len(products) == product_models.Product.objects.count()assert products[0]["node"]["name"] == product_models.Product.objects.first().name+def test_sort_product_by_attribute_using_string_as_attribute_id(+ api_client, product_list_published, channel_USD+):+ """Ensure passing an invalid attribute ID as sorting field return error."""++ query = QUERY_SORT_PRODUCTS_BY_ATTRIBUTE+ variables = {+ "attributeId": graphene.Node.to_global_id("Attribute", "not a number"),+ "direction": "DESC",+ "channel": channel_USD.slug,+ }++ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response, ignore_errors=True)+ errors = content["errors"][0]++ assert errors["extensions"]["exception"]["code"] == "GraphQLError"++@pytest.mark.parametrize("direction", ["ASC", "DESC"])def test_sort_product_by_attribute_using_attribute_having_no_products(api_client, product_list_published, direction, channel_USDdiff --git a/saleor/graphql/translations/mutations.py b/saleor/graphql/translations/mutations.pyindex 10bc593edb..4bdb79d2d7 100644--- a/saleor/graphql/translations/mutations.py+++ b/saleor/graphql/translations/mutations.py@@ -2,6 +2,7 @@ import graphenefrom django.core.exceptions import ValidationErrorfrom django.db import transactionfrom django.db.models import Model+from graphql import GraphQLErrorfrom ...attribute import models as attribute_modelsfrom ...core.permissions import SitePermissions@@ -14,10 +15,11 @@ from ...shipping import models as shipping_modelsfrom ...site.models import SiteSettingsfrom ..attribute.types import Attribute, AttributeValuefrom ..channel import ChannelContext-from ..core.enums import LanguageCodeEnum+from ..core.enums import LanguageCodeEnum, TranslationErrorCodefrom ..core.fields import JSONStringfrom ..core.mutations import BaseMutation, ModelMutationfrom ..core.types.common import TranslationError+from ..core.utils import from_global_id_or_errorfrom ..discount.types import Sale, Voucherfrom ..menu.types import MenuItemfrom ..product.types import Category, Collection, Product, ProductVariant@@ -81,7 +83,17 @@ class BaseTranslateMutation(ModelMutation):)node_id = data["id"]- node_type, node_pk = graphene.Node.from_global_id(node_id)+ try:+ node_type, node_pk = from_global_id_or_error(node_id)+ except GraphQLError:+ raise ValidationError(+ {+ "id": ValidationError(+ "Invalid ID has been provided.",+ code=TranslationErrorCode.INVALID,+ )+ }+ )# This mutation accepts either model IDs or translatable content IDs. Below we# check if provided ID refers to a translatable content which matches with thediff --git a/saleor/graphql/translations/tests/test_translations.py b/saleor/graphql/translations/tests/test_translations.pyindex eccef0845c..c95193b4d8 100644--- a/saleor/graphql/translations/tests/test_translations.py+++ b/saleor/graphql/translations/tests/test_translations.py@@ -951,6 +951,29 @@ def test_product_create_translation_validates_name_length(]+def test_product_create_translation_by_invalid_translatable_content_id(+ staff_api_client, product, permission_manage_translations+):+ translatable_content_id = (+ "UHJvZHVjdFRyYW5zbGF0YWJsZUNvbnRlbnQ6NDkxMyd8fERCTVN"+ "fUElQRS5SRUNFSVZFX01FU1NBR0UoQ0hSKDk4KXx8Q0hSKDk4KXx8Q"+ "0hSKDk4KSwxNSl8fA=="+ )++ # String decodes to+ # ProductTranslatableContent:4913'||+ # DBMS_PIPE.RECEIVE_MESSAGE(CHR(98)||CHR(98)||CHR(98),15)||+ response = staff_api_client.post_graphql(+ PRODUCT_TRANSLATE_MUTATION,+ {"productId": translatable_content_id, "input": {"name": "Produkt PL"}},+ permissions=[permission_manage_translations],+ )+ data = get_graphql_content(response)["data"]["productTranslate"]+ errors = data["errors"][0]+ assert errors["code"] == "INVALID"+ assert errors["field"] == "id"++@freeze_time("1914-06-28 10:50")@patch("saleor.plugins.webhook.plugin._get_webhooks_for_event")@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")diff --git a/saleor/graphql/utils/__init__.py b/saleor/graphql/utils/__init__.pyindex 0c1a0cfccc..cef25670de 100644--- a/saleor/graphql/utils/__init__.py+++ b/saleor/graphql/utils/__init__.py@@ -6,10 +6,10 @@ from django.db.models import Valuefrom django.db.models.functions import Concatfrom graphql import GraphQLDocumentfrom graphql.error import GraphQLError-from graphql_relay import from_global_idfrom ..core.enums import PermissionEnumfrom ..core.types import Permission+from ..core.utils import from_global_id_or_errorERROR_COULD_NO_RESOLVE_GLOBAL_ID = ("Could not resolve to a node with the global id list of '%s'."@@ -33,7 +33,7 @@ def resolve_global_ids_to_primary_keys(continuetry:- node_type, _id = from_global_id(graphql_id)+ node_type, _id = from_global_id_or_error(graphql_id)except Exception:invalid_ids.append(graphql_id)continue@@ -79,7 +79,6 @@ def get_nodes(nodes_type, pks = resolve_global_ids_to_primary_keys(ids, graphene_type, raise_error=True)-# If `graphene_type` was not provided, check if all resolved types are# the same. This prevents from accidentally mismatching IDs of different# types.diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_get_payment.py b/saleor/payment/gateways/adyen/tests/webhooks/test_get_payment.pyindex 915d50d50a..b2e9e5a46f 100644--- a/saleor/payment/gateways/adyen/tests/webhooks/test_get_payment.py+++ b/saleor/payment/gateways/adyen/tests/webhooks/test_get_payment.py@@ -8,7 +8,7 @@ from ...webhooks import get_paymentlogger = logging.getLogger(__name__)[email protected]("payment_id", ["123", "Test payment ID"])[email protected]("payment_id", ["123", "Test payment ID", "ó À È Ì Ò Ù Ỳ"])def test_get_payment_invalid_payment_id(payment_id, caplog):# givencaplog.set_level(logging.WARNING)@@ -41,7 +41,7 @@ def test_get_payment_not_active_payment(payment_dummy, caplog):payment_dummy.is_active = Falsepayment_dummy.save(update_fields=["is_active"])- payment_id = graphene.Node.to_global_id("Payemnt", payment_dummy.pk)+ payment_id = graphene.Node.to_global_id("Payment", payment_dummy.pk)transaction_id = "psp reference"# whendiff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.pyindex 02fee373dd..ec20550147 100644--- a/saleor/payment/gateways/adyen/webhooks.py+++ b/saleor/payment/gateways/adyen/webhooks.py@@ -24,7 +24,7 @@ from django.http import ()from django.http.request import HttpHeadersfrom django.http.response import HttpResponseRedirect-from graphql_relay import from_global_id+from graphql import GraphQLErrorfrom ....checkout.calculations import calculate_checkout_total_with_gift_cardsfrom ....checkout.complete_checkout import complete_checkout@@ -34,6 +34,7 @@ from ....core.prices import quantize_pricefrom ....core.transactions import transaction_with_commit_on_errorsfrom ....core.utils.url import prepare_urlfrom ....discount.utils import fetch_active_discounts+from ....graphql.core.utils import from_global_id_or_errorfrom ....order.actions import (cancel_order,order_authorized,@@ -74,8 +75,8 @@ def get_payment(logger.warning("Missing payment ID. Reference %s", transaction_id)return Nonetry:- _type, db_payment_id = from_global_id(payment_id)- except (UnicodeDecodeError, binascii.Error):+ _type, db_payment_id = from_global_id_or_error(payment_id)+ except (UnicodeDecodeError, binascii.Error, GraphQLError):logger.warning("Unable to decode the payment ID %s. Reference %s",payment_id,diff --git a/saleor/plugins/webhook/shipping.py b/saleor/plugins/webhook/shipping.pyindex 9941000f23..63b53a0bd1 100644--- a/saleor/plugins/webhook/shipping.py+++ b/saleor/plugins/webhook/shipping.py@@ -3,11 +3,13 @@ import loggingfrom collections import defaultdictfrom typing import TYPE_CHECKING, Any, Callable, Dict, List-import graphenefrom django.core.cache import cachefrom django.db.models import QuerySet+from graphql import GraphQLErrorfrom prices import Money+from ...graphql.core.utils import from_global_id_or_error+from ...graphql.shipping.types import ShippingMethodfrom ...shipping.interface import ShippingMethodDatafrom ..base_plugin import ExcludedShippingMethodfrom .const import CACHE_EXCLUDED_SHIPPING_TIME, EXCLUDED_SHIPPING_REQUEST_TIMEOUT@@ -127,18 +129,14 @@ def get_excluded_shipping_methods_from_response(excluded_methods = []for method_data in response_data.get("excluded_methods", []):try:- raw_id = method_data["id"]- typename, _id = graphene.Node.from_global_id(raw_id)- if typename == APP_ID_PREFIX:- method_id = raw_id- elif typename == "ShippingMethod":- method_id = _id- else:+ type_name, method_id = from_global_id_or_error(method_data["id"])+ if type_name not in (APP_ID_PREFIX, str(ShippingMethod)):logger.warning(- "Invalid type received. Expected ShippingMethod, got %s", typename+ "Invalid type received. Expected ShippingMethod, got %s", type_name)continue- except (KeyError, ValueError, TypeError) as e:++ except (KeyError, ValueError, TypeError, GraphQLError) as e:logger.warning("Malformed ShippingMethod id was provided: %s", e)continueexcluded_methods.append(