Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix returning errors in payloads from subscription webhooks. (#9905)
SzymJeb609c301b5f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e4391ddf1a..20e8faf0c3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ All notable, unreleased changes to this project will be documented in this file.#### Saleor Apps- Add webhooks `PAGE_TYPE_CREATED`, `PAGE_TYPE_UPDATED` and `PAGE_TYPE_DELETED` - #9859 by @SzymJ- Add webhooks `ADDRESS_CREATED`, `ADDRESS_UPDATED` and `ADDRESS_DELETED` - #9860 by @SzymJ+- Returning errors in subscription webhooks payloads fix - #9905 by @SzymJ# 3.4.0diff --git a/saleor/__init__.py b/saleor/__init__.pyindex 7fddeaecc1..80e7e18e06 100644--- a/saleor/__init__.py+++ b/saleor/__init__.py@@ -2,3 +2,17 @@ from .celeryconf import app as celery_app__all__ = ["celery_app"]__version__ = "3.5.0-a"+++class PatchedSubscriberExecutionContext(object):+ __slots__ = "exe_context", "errors"++ def __init__(self, exe_context):+ self.exe_context = exe_context+ self.errors = self.exe_context.errors++ def reset(self):+ self.errors = []++ def __getattr__(self, name):+ return getattr(self.exe_context, name)diff --git a/saleor/graphql/tests/fixtures.py b/saleor/graphql/tests/fixtures.pyindex be2816c88e..13ae98187b 100644--- a/saleor/graphql/tests/fixtures.py+++ b/saleor/graphql/tests/fixtures.py@@ -14,7 +14,7 @@ from ...account.models import Userfrom ...core.jwt import create_access_tokenfrom ...plugins.manager import get_plugins_managerfrom ...tests.utils import flush_post_commit_hooks-from ..views import handled_errors_logger, unhandled_errors_logger+from ..utils import handled_errors_logger, unhandled_errors_loggerfrom .utils import assert_no_permissionAPI_PATH = reverse("api")@@ -94,7 +94,7 @@ class ApiClient(Client):if permissions:if check_no_permissions:- with mock.patch("saleor.graphql.views.handled_errors_logger"):+ with mock.patch("saleor.graphql.utils.handled_errors_logger"):response = super().post(API_PATH, data, **kwargs)assert_no_permission(response)if self.app:diff --git a/saleor/graphql/utils/__init__.py b/saleor/graphql/utils/__init__.pyindex 64e4eda887..a2a408487f 100644--- a/saleor/graphql/utils/__init__.py+++ b/saleor/graphql/utils/__init__.py@@ -1,17 +1,25 @@import hashlib+import logging+import tracebackfrom typing import Unionfrom uuid import UUIDimport graphene+from django.conf import settingsfrom django.db.models import Q, Valuefrom django.db.models.functions import Concatfrom graphql import GraphQLDocumentfrom graphql.error import GraphQLError+from graphql.error import format_error as format_graphql_errorfrom ..core.enums import PermissionEnumfrom ..core.types import TYPES_WITH_DOUBLE_ID_AVAILABLE, Permissionfrom ..core.utils import from_global_id_or_error+unhandled_errors_logger = logging.getLogger("saleor.graphql.errors.unhandled")+handled_errors_logger = logging.getLogger("saleor.graphql.errors.handled")++ERROR_COULD_NO_RESOLVE_GLOBAL_ID = ("Could not resolve to a node with the global id list of '%s'.")@@ -186,3 +194,33 @@ def query_fingerprint(document: GraphQLDocument) -> str:breakquery_hash = hashlib.md5(document.document_string.encode("utf-8")).hexdigest()return f"{label}:{query_hash}"+++def format_error(error, handled_exceptions):+ if isinstance(error, GraphQLError):+ result = format_graphql_error(error)+ else:+ result = {"message": str(error)}++ if "extensions" not in result:+ result["extensions"] = {}++ exc = error+ while isinstance(exc, GraphQLError) and hasattr(exc, "original_error"):+ exc = exc.original_error+ if isinstance(exc, AssertionError):+ exc = GraphQLError(str(exc))+ if isinstance(exc, handled_exceptions):+ handled_errors_logger.info("A query had an error", exc_info=exc)+ else:+ unhandled_errors_logger.error("A query failed unexpectedly", exc_info=exc)++ result["extensions"]["exception"] = {"code": type(exc).__name__}+ if settings.DEBUG:+ lines = []++ if isinstance(exc, BaseException):+ for line in traceback.format_exception(type(exc), exc, exc.__traceback__):+ lines.extend(line.rstrip().splitlines())+ result["extensions"]["exception"]["stacktrace"] = lines+ return resultdiff --git a/saleor/graphql/views.py b/saleor/graphql/views.pyindex d7c8387794..35f16e93ed 100644--- a/saleor/graphql/views.py+++ b/saleor/graphql/views.py@@ -2,8 +2,6 @@ import fnmatchimport hashlibimport importlibimport json-import logging-import tracebackfrom inspect import isclassfrom typing import Any, Dict, List, Optional, Tuple, Union@@ -18,7 +16,6 @@ from django.shortcuts import renderfrom django.views.generic import Viewfrom graphql import GraphQLDocument, get_default_backendfrom graphql.error import GraphQLError, GraphQLSyntaxError-from graphql.error import format_error as format_graphql_errorfrom graphql.execution import ExecutionResultfrom jwt.exceptions import PyJWTError@@ -30,13 +27,10 @@ from .api import API_PATH, schemafrom .context import get_context_valuefrom .core.validators.query_cost import validate_query_costfrom .query_cost_map import COST_MAP-from .utils import query_fingerprint+from .utils import format_error, query_fingerprintINT_ERROR_MSG = "Int cannot represent non 32-bit signed integer value"-unhandled_errors_logger = logging.getLogger("saleor.graphql.errors.unhandled")-handled_errors_logger = logging.getLogger("saleor.graphql.errors.handled")-def tracing_wrapper(execute, sql, params, many, context):conn: DatabaseWrapper = context["connection"]@@ -392,35 +386,7 @@ class GraphQLView(View):@classmethoddef format_error(cls, error):- if isinstance(error, GraphQLError):- result = format_graphql_error(error)- else:- result = {"message": str(error)}-- if "extensions" not in result:- result["extensions"] = {}-- exc = error- while isinstance(exc, GraphQLError) and hasattr(exc, "original_error"):- exc = exc.original_error- if isinstance(exc, AssertionError):- exc = GraphQLError(str(exc))- if isinstance(exc, cls.HANDLED_EXCEPTIONS):- handled_errors_logger.info("A query had an error", exc_info=exc)- else:- unhandled_errors_logger.error("A query failed unexpectedly", exc_info=exc)-- result["extensions"]["exception"] = {"code": type(exc).__name__}- if settings.DEBUG:- lines = []-- if isinstance(exc, BaseException):- for line in traceback.format_exception(- type(exc), exc, exc.__traceback__- ):- lines.extend(line.rstrip().splitlines())- result["extensions"]["exception"]["stacktrace"] = lines- return result+ return format_error(error, cls.HANDLED_EXCEPTIONS)def get_key(key):diff --git a/saleor/graphql/webhook/subscription_payload.py b/saleor/graphql/webhook/subscription_payload.pyindex 2475284d89..e08dfd0111 100644--- a/saleor/graphql/webhook/subscription_payload.py+++ b/saleor/graphql/webhook/subscription_payload.py@@ -7,14 +7,16 @@ from django.http import HttpRequestfrom django.utils import timezonefrom django.utils.functional import SimpleLazyObjectfrom graphql import GraphQLDocument, get_default_backend, parse-from graphql.error import GraphQLSyntaxError+from graphql.error import GraphQLError, GraphQLSyntaxErrorfrom graphql.language.ast import FragmentDefinition, OperationDefinitionfrom promise import Promisefrom ...app.models import App+from ...core.exceptions import PermissionDeniedfrom ...discount.utils import fetch_discountsfrom ...plugins.manager import PluginsManagerfrom ...settings import get_host+from ..utils import format_errorlogger = get_task_logger(__name__)@@ -84,6 +86,14 @@ def initialize_request(requestor=None) -> HttpRequest:return request+def get_event_payload(event):+ # Queries that use dataloaders return Promise object for the "event" field. In that+ # case, we need to resolve them first.+ if isinstance(event, Promise):+ return event.get()+ return event++def generate_payload_from_subscription(event_type: str,subscribable_object,@@ -96,7 +106,7 @@ def generate_payload_from_subscription(It uses a graphql's engine to build payload by using the same logic as response.As an input it expects given event type and object and the query which will beused to resolve a payload.- event_type: is a event which will be triggered.+ event_type: is an event which will be triggered.subscribable_object: is an object which have a dedicated own type in Subscriptiondefinition.subscription_query: query used to prepare a payload via graphql engine.@@ -132,6 +142,7 @@ def generate_payload_from_subscription(extra={"query": subscription_query, "app": app_id},)return None+payload = [] # type: ignoreresults.subscribe(payload.append)@@ -143,11 +154,12 @@ def generate_payload_from_subscription(return Nonepayload_instance = payload[0]- event_payload = payload_instance.data.get("event")+ event_payload = get_event_payload(payload_instance.data.get("event"))- # Queries that use dataloaders return Promise object for the "event" field. In that- # case, we need to resolve them first.- if isinstance(event_payload, Promise):- return event_payload.get()+ if payload_instance.errors:+ event_payload["errors"] = [+ format_error(error, (GraphQLError, PermissionDenied))+ for error in payload_instance.errors+ ]return event_payloaddiff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.pyindex aa019f9ab7..21c1be5bb1 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py@@ -1428,3 +1428,27 @@ def test_validate_invalid_multiple_subscriptions():subscription_queries.TEST_INVALID_MULTIPLE_SUBSCRIPTION)assert result is False+++def test_generate_payload_from_subscription_return_permission_errors_in_payload(+ gift_card, subscription_gift_card_created_webhook, permission_manage_gift_card+):+ # given+ subscription_gift_card_created_webhook.app.permissions.remove(+ permission_manage_gift_card+ )+ webhooks = [subscription_gift_card_created_webhook]++ # when+ deliveries = create_deliveries_for_subscriptions(+ WebhookEventAsyncType.GIFT_CARD_CREATED, gift_card, webhooks+ )++ # then+ payload = json.loads(deliveries[0].payload.payload)+ error_code = "PermissionDenied"++ assert not payload["giftCard"]+ assert payload["errors"][0]["extensions"]["exception"]["code"] == error_code+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]diff --git a/saleor/settings.py b/saleor/settings.pyindex c1d25ac8d8..b15f426875 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -14,12 +14,13 @@ import sentry_sdk.utilsfrom celery.schedules import crontabfrom django.core.exceptions import ImproperlyConfiguredfrom django.core.management.utils import get_random_secret_key+from graphql.execution import executorfrom pytimeparse import parsefrom sentry_sdk.integrations.celery import CeleryIntegrationfrom sentry_sdk.integrations.django import DjangoIntegrationfrom sentry_sdk.integrations.logging import ignore_logger-from . import __version__+from . import PatchedSubscriberExecutionContext, __version__from .core.languages import LANGUAGES as CORE_LANGUAGES@@ -729,4 +730,8 @@ JWT_TTL_REQUEST_EMAIL_CHANGE = timedelta(seconds=parse(os.environ.get("JWT_TTL_REQUEST_EMAIL_CHANGE", "1 hour")),)-# Support multiple interface notation in schema for Apollo tooling.++# Patch SubscriberExecutionContext class from `graphql-core-legacy` package+# to fix bug causing not returning errors for subscription queries.++executor.SubscriberExecutionContext = PatchedSubscriberExecutionContext # type: ignore