Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Catch unicode error
Damian Wbf938e731bd8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b960afce19..e7d4b7ac87 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -41,6 +41,7 @@ All notable, unreleased changes to this project will be documented in this file.- Fix dataloader for fetching checkout info - #7084 by @IKarbowiak- Update also draft order line total price after getting the unit price from plugin - #7080 by @IKarbowiak- Fix failing product tasks when instances are removed - #7092 by @IKarbowiak+- Catch invalid ID in query and raise ValidationError - #7114 by @d-wysocki### Breaking- Multichannel MVP: Multicurrency - #6242 by @fowczarek @d-wysockidiff --git a/saleor/graphql/account/resolvers.py b/saleor/graphql/account/resolvers.pyindex 4c4338f98c..1c179cd0cd 100644--- a/saleor/graphql/account/resolvers.py+++ b/saleor/graphql/account/resolvers.py@@ -1,7 +1,6 @@from itertools import chainfrom typing import Optional-import graphenefrom django.contrib.auth import models as auth_modelsfrom i18naddress import get_validation_rules@@ -10,6 +9,7 @@ from ...core.exceptions import PermissionDeniedfrom ...core.permissions import AccountPermissionsfrom ...payment import gatewayfrom ...payment.utils import fetch_customer_id+from ..core.utils import from_global_id_strict_typefrom ..utils import format_permissions_for_display, get_user_or_app_from_contextfrom ..utils.filters import filter_by_query_paramfrom .types import AddressValidationData, ChoiceValue@@ -55,7 +55,7 @@ def resolve_user(info, id=None, email=None):if requester:filter_kwargs = {}if id:- _model, filter_kwargs["pk"] = graphene.Node.from_global_id(id)+ filter_kwargs["pk"] = from_global_id_strict_type(id, only_type="User")if email:filter_kwargs["email"] = emailif requester.has_perms(@@ -151,7 +151,7 @@ def prepare_graphql_payment_sources_type(payment_sources):def resolve_address(info, id):user = info.context.userapp = info.context.app- _model, address_pk = graphene.Node.from_global_id(id)+ address_pk = from_global_id_strict_type(id, only_type="Address")if app and app.has_perm(AccountPermissions.MANAGE_USERS):return models.Address.objects.filter(pk=address_pk).first()if user and not user.is_anonymous:diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.pyindex 955092ce97..ef84b339a2 100644--- a/saleor/graphql/attribute/utils.py+++ b/saleor/graphql/attribute/utils.py@@ -7,7 +7,6 @@ from django.core.exceptions import ValidationErrorfrom django.db.models import Qfrom django.utils.text import slugifyfrom graphql.error import GraphQLError-from graphql_relay import from_global_idfrom ...attribute import AttributeEntityType, AttributeInputType, AttributeTypefrom ...attribute import models as attribute_models@@ -17,7 +16,7 @@ from ...page import models as page_modelsfrom ...page.error_codes import PageErrorCodefrom ...product import models as product_modelsfrom ...product.error_codes import ProductErrorCode-from ..utils import get_nodes+from ..utils import from_global_id_or_error, get_nodesif TYPE_CHECKING:from django.db.models import QuerySet@@ -115,7 +114,9 @@ class AttributeAssignmentMixin:@classmethoddef _resolve_attribute_global_id(cls, error_class, global_id: str) -> int:"""Resolve an Attribute global ID into an internal ID (int)."""- graphene_type, internal_id = from_global_id(global_id) # type: str, str+ graphene_type, internal_id = from_global_id_or_error(+ global_id+ ) # type: str, strif graphene_type != "Attribute":raise ValidationError(f"Must receive an Attribute id, got {graphene_type}.",diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.pyindex 74efc5186f..fa3ca25b91 100644--- a/saleor/graphql/core/mutations.py+++ b/saleor/graphql/core/mutations.py@@ -20,7 +20,11 @@ from ..decorators import staff_member_or_app_requiredfrom ..utils import get_nodesfrom .types import Error, File, Uploadfrom .types.common import UploadError-from .utils import from_global_id_strict_type, snake_to_camel_case+from .utils import (+ from_global_id_or_error,+ from_global_id_strict_type,+ snake_to_camel_case,+)from .utils.error_codes import get_error_code_from_errorregistry = get_global_registry()@@ -160,7 +164,7 @@ class BaseMutation(graphene.Mutation):pk = from_global_id_strict_type(node_id, only_type, field=field)else:# FIXME: warn when supplied only_type is None?- only_type, pk = graphene.Node.from_global_id(node_id)+ only_type, pk = from_global_id_or_error(node_id)if isinstance(only_type, str):only_type = info.schema.get_type(only_type).graphene_typediff --git a/saleor/graphql/core/tests/test_graphql.py b/saleor/graphql/core/tests/test_graphql.pyindex 95c201e5ec..34f9a06373 100644--- a/saleor/graphql/core/tests/test_graphql.py+++ b/saleor/graphql/core/tests/test_graphql.py@@ -4,6 +4,7 @@ from unittest.mock import Mock, patchimport grapheneimport pytestfrom django.contrib.auth.models import AnonymousUser+from django.core.exceptions import ValidationErrorfrom django.db.models import Qfrom django.shortcuts import reversefrom graphql.error import GraphQLError@@ -11,7 +12,7 @@ from graphql_relay import to_global_idfrom ...product.types import Productfrom ...tests.utils import get_graphql_content-from ...utils import get_nodes+from ...utils import from_global_id_or_error, get_nodesfrom ...utils.filters import filter_by_query_param@@ -283,3 +284,13 @@ def test_filter_by_query_param(qs):q_objects |= Q(**{q: test_kwargs[q]})# FIXME: django 1.11 fails on called_once_with(q_objects)qs.filter.call_count == 1+++def test_from_global_id_or_error(product):+ invalid_id = "invalid"+ message = f"Couldn't resolve id: {invalid_id}."++ with pytest.raises(ValidationError) as error:+ from_global_id_or_error(invalid_id)++ assert error.value.error_dict["id"][0].message == messagediff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.pyindex 201edcf482..cd25a3895e 100644--- a/saleor/graphql/core/utils/__init__.py+++ b/saleor/graphql/core/utils/__init__.py@@ -119,3 +119,13 @@ def validate_required_string_field(cleaned_input, field_name: str):else:raise ValidationError(f"{field_name.capitalize()} is required.")return cleaned_input+++def from_global_id_or_error(id):+ """Resolve id from global or raise ValidationError."""+ try:+ return graphene.Node.from_global_id(id)+ except (binascii.Error, UnicodeDecodeError):+ raise ValidationError(+ {"id": ValidationError(f"Couldn't resolve id: {id}.", code="not_found")}+ )diff --git a/saleor/graphql/meta/mutations.py b/saleor/graphql/meta/mutations.pyindex 9f2d39e6cb..7a6d559147 100644--- a/saleor/graphql/meta/mutations.py+++ b/saleor/graphql/meta/mutations.py@@ -12,6 +12,7 @@ from ...shipping import models as shipping_modelsfrom ..channel import ChannelContextfrom ..core.mutations import BaseMutationfrom ..core.types.common import MetadataError+from ..core.utils import from_global_id_or_errorfrom .extra_methods import MODEL_EXTRA_METHODSfrom .permissions import PRIVATE_META_PERMISSION_MAP, PUBLIC_META_PERMISSION_MAPfrom .types import ObjectWithMetadata@@ -84,7 +85,7 @@ class BaseMetadataMutation(BaseMutation):object_id = data.get("id")if not object_id:return []- type_name, object_pk = graphene.Node.from_global_id(object_id)+ type_name, object_pk = from_global_id_or_error(object_id)model = cls.get_model_for_type_name(info, type_name)cls.validate_model_is_model_with_metadata(model, object_id)permission = cls._meta.permission_map.get(type_name)@@ -112,7 +113,7 @@ class BaseMetadataMutation(BaseMutation):@classmethoddef perform_model_extra_actions(cls, root, info, **data):"""Run extra metadata method based on mutating model."""- type_name, _ = graphene.Node.from_global_id(data["id"])+ type_name, _ = from_global_id_or_error(data["id"])if MODEL_EXTRA_METHODS.get(type_name):instance = cls.get_instance(info, **data)MODEL_EXTRA_METHODS[type_name](instance, info, **data)diff --git a/saleor/graphql/page/resolvers.py b/saleor/graphql/page/resolvers.pyindex 96ae96f81c..4928366313 100644--- a/saleor/graphql/page/resolvers.py+++ b/saleor/graphql/page/resolvers.py@@ -1,6 +1,7 @@import graphenefrom ...page import models+from ..core.utils import from_global_id_or_errorfrom ..core.validators import validate_one_of_args_is_in_queryfrom .types import PageType@@ -12,7 +13,7 @@ def resolve_page(info, global_page_id=None, slug=None):if slug is not None:page = models.Page.objects.visible_to_user(user).filter(slug=slug).first()else:- _type, page_pk = graphene.Node.from_global_id(global_page_id)+ _type, page_pk = from_global_id_or_error(global_page_id)page = models.Page.objects.visible_to_user(user).filter(pk=page_pk).first()return pagediff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.pyindex 0806eda51a..7d24dca452 100644--- a/saleor/graphql/product/schema.py+++ b/saleor/graphql/product/schema.py@@ -11,6 +11,7 @@ from ..core.fields import (FilterInputConnectionField,PrefetchingConnectionField,)+from ..core.utils import from_global_id_strict_typefrom ..core.validators import validate_one_of_args_is_in_queryfrom ..decorators import permission_requiredfrom ..translations.mutations import (@@ -19,7 +20,7 @@ from ..translations.mutations import (ProductTranslate,ProductVariantTranslate,)-from ..utils import get_user_or_app_from_context+from ..utils import from_global_id_or_error, get_user_or_app_from_contextfrom .bulk_mutations.products import (CategoryBulkDelete,CollectionBulkDelete,@@ -267,7 +268,7 @@ class ProductQueries(graphene.ObjectType):if channel is None and not is_staff:channel = get_default_channel_slug_or_graphql_error()if id:- _, id = graphene.Node.from_global_id(id)+ _, id = from_global_id_or_error(id)collection = resolve_collection_by_id(info, id, channel, requestor)else:collection = resolve_collection_by_slug(@@ -302,7 +303,7 @@ class ProductQueries(graphene.ObjectType):if channel is None and not is_staff:channel = get_default_channel_slug_or_graphql_error()if id:- _, id = graphene.Node.from_global_id(id)+ id = from_global_id_strict_type(id, only_type="Product")product = resolve_product_by_id(info, id, channel_slug=channel, requestor=requestor)@@ -348,7 +349,7 @@ class ProductQueries(graphene.ObjectType):if channel is None and not is_staff:channel = get_default_channel_slug_or_graphql_error()if id:- _, id = graphene.Node.from_global_id(id)+ _, id = from_global_id_or_error(id)variant = resolve_variant_by_id(info, id, channel_slug=channel, requestor=requestor)diff --git a/saleor/graphql/translations/schema.py b/saleor/graphql/translations/schema.pyindex 013ae0f3c7..abf077a10e 100644--- a/saleor/graphql/translations/schema.py+++ b/saleor/graphql/translations/schema.py@@ -10,6 +10,7 @@ from ...shipping.models import ShippingMethodfrom ..attribute.resolvers import resolve_attributesfrom ..core.connection import CountableConnectionfrom ..core.fields import BaseConnectionField+from ..core.utils import from_global_id_or_errorfrom ..decorators import permission_requiredfrom ..menu.resolvers import resolve_menu_itemsfrom ..page.resolvers import resolve_pages@@ -109,7 +110,7 @@ class TranslationQueries(graphene.ObjectType):@permission_required(SitePermissions.MANAGE_TRANSLATIONS)def resolve_translation(self, info, id, kind, **_kwargs):- _type, kind_id = graphene.Node.from_global_id(id)+ _type, kind_id = from_global_id_or_error(id)if not _type == kind:return Nonemodels = {diff --git a/saleor/graphql/utils/__init__.py b/saleor/graphql/utils/__init__.pyindex acb03edc19..af26b63e95 100644--- a/saleor/graphql/utils/__init__.py+++ b/saleor/graphql/utils/__init__.py@@ -11,6 +11,7 @@ from graphql_relay import from_global_idfrom ...account import models as account_modelsfrom ..core.enums import PermissionEnumfrom ..core.types import Permission+from ..core.utils import from_global_id_or_errorif TYPE_CHECKING:from ..account import types as account_types@@ -28,7 +29,7 @@ REVERSED_DIRECTION = {def get_database_id(info, node_id, only_type):"""Get a database ID from a node ID of given type."""- _type, _id = graphene.relay.Node.from_global_id(node_id)+ _type, _id = from_global_id_or_error(node_id)if _type != str(only_type):raise AssertionError("Must receive a %s id." % str(only_type))return _iddiff --git a/saleor/graphql/utils/sorting.py b/saleor/graphql/utils/sorting.pyindex 5dda28ecae..5953ba4561 100644--- a/saleor/graphql/utils/sorting.py+++ b/saleor/graphql/utils/sorting.py@@ -2,10 +2,10 @@ from typing import Tuplefrom django.db.models import QuerySetfrom graphql.error import GraphQLError-from graphql_relay import from_global_idfrom ..core.enums import OrderDirectionfrom ..core.types import SortInputObjectType+from ..core.utils import from_global_id_or_errorREVERSED_DIRECTION = {"-": "",@@ -15,7 +15,7 @@ REVERSED_DIRECTION = {def _sort_queryset_by_attribute(queryset, sorting_attribute, sorting_direction):if sorting_attribute != "":- graphene_type, sorting_attribute = from_global_id(sorting_attribute)+ graphene_type, sorting_attribute = from_global_id_or_error(sorting_attribute)descending = sorting_direction == OrderDirection.DESCqueryset = queryset.sort_by_attribute(sorting_attribute, descending=descending)return querysetdiff --git a/saleor/graphql/webhook/mutations.py b/saleor/graphql/webhook/mutations.pyindex 761c60a9d9..8483ab4df9 100644--- a/saleor/graphql/webhook/mutations.py+++ b/saleor/graphql/webhook/mutations.py@@ -6,6 +6,7 @@ from ...webhook import modelsfrom ...webhook.error_codes import WebhookErrorCodefrom ..core.mutations import ModelDeleteMutation, ModelMutationfrom ..core.types.common import WebhookError+from ..core.utils import from_global_id_or_errorfrom .enums import WebhookEventTypeEnum@@ -182,7 +183,7 @@ class WebhookDelete(ModelDeleteMutation):@classmethoddef perform_mutation(cls, _root, info, **data):node_id = data["id"]- _, object_id = graphene.Node.from_global_id(node_id)+ _, object_id = from_global_id_or_error(node_id)app = info.context.appif app:diff --git a/saleor/graphql/webhook/resolvers.py b/saleor/graphql/webhook/resolvers.pyindex 840291266c..df08ac0437 100644--- a/saleor/graphql/webhook/resolvers.py+++ b/saleor/graphql/webhook/resolvers.py@@ -4,6 +4,7 @@ from ...core.exceptions import PermissionDeniedfrom ...core.permissions import AppPermissionfrom ...webhook import models, payloadsfrom ...webhook.event_types import WebhookEventType+from ..core.utils import from_global_id_or_errorfrom .types import Webhook, WebhookEvent@@ -22,7 +23,7 @@ def resolve_webhooks(info, **_kwargs):def resolve_webhook(info, webhook_id):app = info.context.appif app:- _, webhook_id = graphene.Node.from_global_id(webhook_id)+ _, webhook_id = from_global_id_or_error(webhook_id)return app.webhooks.filter(id=webhook_id).first()user = info.context.userif user.has_perm(AppPermission.MANAGE_APPS):