Skip to content

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

Fix returning errors in payloads from subscription webhooks. (#9905)

SzymJeb609c301b5f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 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.0
diff --git a/saleor/__init__.py b/saleor/__init__.py
index 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.py
index be2816c88e..13ae98187b 100644
--- a/saleor/graphql/tests/fixtures.py
+++ b/saleor/graphql/tests/fixtures.py
@@ -14,7 +14,7 @@ from ...account.models import User
from ...core.jwt import create_access_token
from ...plugins.manager import get_plugins_manager
from ...tests.utils import flush_post_commit_hooks
-from ..views import handled_errors_logger, unhandled_errors_logger
+from ..utils import handled_errors_logger, unhandled_errors_logger
from .utils import assert_no_permission
API_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__.py
index 64e4eda887..a2a408487f 100644
--- a/saleor/graphql/utils/__init__.py
+++ b/saleor/graphql/utils/__init__.py
@@ -1,17 +1,25 @@
import hashlib
+import logging
+import traceback
from typing import Union
from uuid import UUID
import graphene
+from django.conf import settings
from django.db.models import Q, Value
from django.db.models.functions import Concat
from graphql import GraphQLDocument
from graphql.error import GraphQLError
+from graphql.error import format_error as format_graphql_error
from ..core.enums import PermissionEnum
from ..core.types import TYPES_WITH_DOUBLE_ID_AVAILABLE, Permission
from ..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:
break
query_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 result
diff --git a/saleor/graphql/views.py b/saleor/graphql/views.py
index d7c8387794..35f16e93ed 100644
--- a/saleor/graphql/views.py
+++ b/saleor/graphql/views.py
@@ -2,8 +2,6 @@ import fnmatch
import hashlib
import importlib
import json
-import logging
-import traceback
from inspect import isclass
from typing import Any, Dict, List, Optional, Tuple, Union
@@ -18,7 +16,6 @@ from django.shortcuts import render
from django.views.generic import View
from graphql import GraphQLDocument, get_default_backend
from graphql.error import GraphQLError, GraphQLSyntaxError
-from graphql.error import format_error as format_graphql_error
from graphql.execution import ExecutionResult
from jwt.exceptions import PyJWTError
@@ -30,13 +27,10 @@ from .api import API_PATH, schema
from .context import get_context_value
from .core.validators.query_cost import validate_query_cost
from .query_cost_map import COST_MAP
-from .utils import query_fingerprint
+from .utils import format_error, query_fingerprint
INT_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):
@classmethod
def 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.py
index 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 HttpRequest
from django.utils import timezone
from django.utils.functional import SimpleLazyObject
from graphql import GraphQLDocument, get_default_backend, parse
-from graphql.error import GraphQLSyntaxError
+from graphql.error import GraphQLError, GraphQLSyntaxError
from graphql.language.ast import FragmentDefinition, OperationDefinition
from promise import Promise
from ...app.models import App
+from ...core.exceptions import PermissionDenied
from ...discount.utils import fetch_discounts
from ...plugins.manager import PluginsManager
from ...settings import get_host
+from ..utils import format_error
logger = 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 be
used 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 Subscription
definition.
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: ignore
results.subscribe(payload.append)
@@ -143,11 +154,12 @@ def generate_payload_from_subscription(
return None
payload_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_payload
diff --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.py
index 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.py
index c1d25ac8d8..b15f426875 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -14,12 +14,13 @@ import sentry_sdk.utils
from celery.schedules import crontab
from django.core.exceptions import ImproperlyConfigured
from django.core.management.utils import get_random_secret_key
+from graphql.execution import executor
from pytimeparse import parse
from sentry_sdk.integrations.celery import CeleryIntegration
from sentry_sdk.integrations.django import DjangoIntegration
from 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