Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Subscription query validation (#11797)
Piotr Zabieglik0d7f9e8bb19f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1893dc0bd1..f7ad9fc7a0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,8 @@ All notable, unreleased changes to this project will be documented in this file.### Other changes+- Enhance webhook's subscription query validation. Apply the validation and event inheritance to manifest validation - #11797 by @zedzior+# 3.11.0### Highlightsdiff --git a/saleor/app/manifest_validations.py b/saleor/app/manifest_validations.pyindex b470c3f673..012a6b62b6 100644--- a/saleor/app/manifest_validations.py+++ b/saleor/app/manifest_validations.py@@ -7,7 +7,7 @@ from django.db.models import Valuefrom django.db.models.functions import Concatfrom ..graphql.core.utils import str_to_enum-from ..graphql.webhook.subscription_payload import validate_subscription_query+from ..graphql.webhook.subscription_query import SubscriptionQueryfrom ..permission.enums import (get_permissions,get_permissions_enum_list,@@ -200,14 +200,6 @@ def clean_webhooks(manifest_data, errors):)for webhook in webhooks:- if not validate_subscription_query(webhook["query"]):- errors["webhooks"].append(- ValidationError(- "Subscription query is not valid.",- code=AppErrorCode.INVALID.value,- )- )-webhook["events"] = []for e_type in webhook.get("asyncEvents", []):try:@@ -230,6 +222,26 @@ def clean_webhooks(manifest_data, errors):))+ subscription_query = SubscriptionQuery(webhook["query"])+ if not subscription_query.is_valid:+ errors["webhooks"].append(+ ValidationError(+ "Subscription query is not valid: " + subscription_query.error_msg,+ code=AppErrorCode.INVALID.value,+ )+ )++ if not webhook["events"]:+ webhook["events"] = subscription_query.events+ elif sorted(webhook["events"]) != sorted(subscription_query.events):+ errors["webhooks"].append(+ ValidationError(+ "Events provided in `syncEvents` and `asyncEvents` does not "+ "match events from `query`",+ code=AppErrorCode.INVALID.value,+ )+ )+try:target_url_validator(webhook["targetUrl"])except ValidationError:diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.pyindex b46e572a7f..b583976962 100644--- a/saleor/app/tests/test_installation_utils.py+++ b/saleor/app/tests/test_installation_utils.py@@ -406,7 +406,37 @@ def test_install_app_webhook_incorrect_query(error_dict = excinfo.value.error_dictassert "webhooks" in error_dict- assert error_dict["webhooks"][0].message == "Subscription query is not valid."+ assert "Subscription query is not valid:" in error_dict["webhooks"][0].message+++def test_install_app_with_webhook_mismatch_between_query_and_event_fields(+ app_manifest,+ app_manifest_webhook,+ app_installation,+ monkeypatch,+ subscription_order_created_webhook,+):+ # given+ app_manifest_webhook[+ "query"+ ] = subscription_order_created_webhook.subscription_query+ app_manifest["webhooks"] = [app_manifest_webhook]++ mocked_get_response = Mock()+ mocked_get_response.json.return_value = app_manifest+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))++ # when & then+ with pytest.raises(ValidationError) as excinfo:+ install_app(app_installation, activate=True)++ error_dict = excinfo.value.error_dict+ assert "webhooks" in error_dict+ assert (+ error_dict["webhooks"][0].message+ == "Events provided in `syncEvents` and `asyncEvents` "+ "does not match events from `query`"+ )def test_install_app_lack_of_token_target_url_in_manifest_data(diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex ff12b99b6b..3bd4d7cc61 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -15937,6 +15937,10 @@ enum WebhookErrorCode {REQUIREDUNIQUEDELETE_FAILED+ SYNTAX+ MISSING_SUBSCRIPTION+ UNABLE_TO_PARSE+ MISSING_EVENT}input WebhookCreateInput {@@ -16089,11 +16093,14 @@ type WebhookDryRunError {"""An enumeration."""enum WebhookDryRunErrorCode {GRAPHQL_ERROR- UNABLE_TO_PARSENOT_FOUNDINVALID_IDMISSING_PERMISSIONTYPE_NOT_SUPPORTED+ SYNTAX+ MISSING_SUBSCRIPTION+ UNABLE_TO_PARSE+ MISSING_EVENT}"""@@ -16129,9 +16136,12 @@ enum WebhookTriggerErrorCode {NOT_FOUNDINVALID_IDMISSING_PERMISSION- MISSING_QUERYTYPE_NOT_SUPPORTED+ SYNTAX+ MISSING_SUBSCRIPTIONUNABLE_TO_PARSE+ MISSING_QUERY+ MISSING_EVENT}"""diff --git a/saleor/graphql/webhook/mutations/webhook_create.py b/saleor/graphql/webhook/mutations/webhook_create.pyindex ed4b708267..f5eed1a245 100644--- a/saleor/graphql/webhook/mutations/webhook_create.py+++ b/saleor/graphql/webhook/mutations/webhook_create.py@@ -1,3 +1,5 @@+from typing import Optional+import graphenefrom django.core.exceptions import ValidationError@@ -10,10 +12,10 @@ from ...core import ResolveInfofrom ...core.descriptions import ADDED_IN_32, DEPRECATED_IN_3X_INPUT, PREVIEW_FEATUREfrom ...core.mutations import ModelMutationfrom ...core.types import NonNullList, WebhookError+from ...core.utils import raise_validation_errorfrom .. import enums-from ..subscription_payload import validate_query+from ..subscription_query import SubscriptionQueryfrom ..types import Webhook-from ..utils import get_event_type_from_subscriptionclass WebhookCreateInput(graphene.InputObjectType):@@ -55,23 +57,6 @@ class WebhookCreateInput(graphene.InputObjectType):)-def clean_webhook_events(_info, _instance, data):- # if `events` field is not empty, use this field. Otherwise get event types- # from `async_events` and `sync_events`. If the fields are also empty, parse events- # from `query`.- events = data.get("events", [])- if not events:- events += data.pop("async_events", [])- events += data.pop("sync_events", [])-- query = data.get("query", [])- if not events and query:- events = get_event_type_from_subscription(query)-- data["events"] = events- return data--class WebhookCreate(ModelMutation):class Arguments:input = WebhookCreateInput(@@ -113,12 +98,38 @@ class WebhookCreate(ModelMutation):"App doesn't exist or is disabled",code=WebhookErrorCode.NOT_FOUND.value,)- clean_webhook_events(info, instance, cleaned_data)++ subscription_query = Noneif query := cleaned_data.get("query"):- validate_query(query)+ subscription_query = SubscriptionQuery(query)+ if not subscription_query.is_valid:+ raise_validation_error(+ field="query",+ message=subscription_query.error_msg,+ code=subscription_query.error_code,+ )instance.subscription_query = query++ cls._clean_webhook_events(cleaned_data, subscription_query)+return cleaned_data+ @staticmethod+ def _clean_webhook_events(data, subscription_query: Optional[SubscriptionQuery]):+ # if `events` field is not empty, use this field. Otherwise get event types+ # from `async_events` and `sync_events`. If the fields are also empty,+ # parse events from `query`.+ events = data.get("events", [])+ if not events:+ events += data.pop("async_events", [])+ events += data.pop("sync_events", [])++ if not events and subscription_query:+ events = subscription_query.events++ data["events"] = events+ return data+@classmethoddef get_instance(cls, info: ResolveInfo, **data):instance = super().get_instance(info, **data)diff --git a/saleor/graphql/webhook/mutations/webhook_dry_run.py b/saleor/graphql/webhook/mutations/webhook_dry_run.pyindex 293707c2e5..d505c9b436 100644--- a/saleor/graphql/webhook/mutations/webhook_dry_run.py+++ b/saleor/graphql/webhook/mutations/webhook_dry_run.py@@ -13,8 +13,8 @@ from ..subscription_payload import (generate_payload_from_subscription,initialize_request,)+from ..subscription_query import SubscriptionQueryfrom ..subscription_types import WEBHOOK_TYPES_MAP-from ..utils import get_event_type_from_subscriptionclass WebhookDryRun(BaseMutation):@@ -45,30 +45,23 @@ class WebhookDryRun(BaseMutation):@classmethoddef validate_query(cls, query):- event_types = get_event_type_from_subscription(query) if query else None- event_type = event_types[0] if event_types else None- if not event_type:+ subscription_query = SubscriptionQuery(query)+ if not subscription_query.is_valid:raise_validation_error(field="query",- message="Can't parse an event type from query.",- code=WebhookDryRunErrorCode.UNABLE_TO_PARSE,+ message=subscription_query.error_msg,+ code=subscription_query.error_code,)- return event_type++ events = subscription_query.events+ return events[0] if events else None@classmethoddef validate_event_type(cls, event_type, object_id):- event = WEBHOOK_TYPES_MAP.get(event_type) if event_type else None- if not event and event_type:- event_name = event_type[0].upper() + to_camel_case(event_type)[1:]- raise_validation_error(- field="query",- message=f"Event type: {event_name} is not defined in graphql schema.",- code=WebhookDryRunErrorCode.GRAPHQL_ERROR,- )-+ event = WEBHOOK_TYPES_MAP[event_type]model, _ = graphene.Node.from_global_id(object_id)- model_name = event._meta.root_type # type: ignore[union-attr]- enable_dry_run = event._meta.enable_dry_run # type: ignore[union-attr]+ model_name = event._meta.root_type # type: ignore[attr-defined]+ enable_dry_run = event._meta.enable_dry_run # type: ignore[attr-defined]if not (model_name or enable_dry_run) and event_type:event_name = event_type[0].upper() + to_camel_case(event_type)[1:]diff --git a/saleor/graphql/webhook/mutations/webhook_trigger.py b/saleor/graphql/webhook/mutations/webhook_trigger.pyindex e49922b3e0..72e7c03160 100644--- a/saleor/graphql/webhook/mutations/webhook_trigger.py+++ b/saleor/graphql/webhook/mutations/webhook_trigger.py@@ -10,9 +10,9 @@ from ...core.descriptions import ADDED_IN_311, PREVIEW_FEATUREfrom ...core.mutations import BaseMutationfrom ...core.types.common import WebhookTriggerErrorfrom ...core.utils import raise_validation_error+from ..subscription_query import SubscriptionQueryfrom ..subscription_types import WEBHOOK_TYPES_MAPfrom ..types import EventDelivery-from ..utils import get_event_type_from_subscriptionclass WebhookTrigger(BaseMutation):@@ -46,26 +46,19 @@ class WebhookTrigger(BaseMutation):code=WebhookTriggerErrorCode.MISSING_QUERY,)- event_types = get_event_type_from_subscription(query)- if not event_types:+ subscription_query = SubscriptionQuery(query)+ if not subscription_query.is_valid:raise_validation_error(- message="Can't parse an event type from webhook's subscription query.",- code=WebhookTriggerErrorCode.UNABLE_TO_PARSE,+ message=subscription_query.error_msg,+ code=subscription_query.error_code,)- event_type = event_types[0] if event_types else None- return event_type++ events = subscription_query.events+ return events[0] if events else None@classmethoddef validate_event_type(cls, event_type, object_id):- event = WEBHOOK_TYPES_MAP.get(event_type) if event_type else None- if not event and event_type:- event_name = event_type[0].upper() + to_camel_case(event_type)[1:]- raise_validation_error(- message=f"Event type: {event_name}, which was parsed from webhook's "- f"subscription query, is not defined in graphql schema.",- code=WebhookTriggerErrorCode.GRAPHQL_ERROR,- )-+ event = WEBHOOK_TYPES_MAP[event_type] if event_type else Nonemodel, _ = graphene.Node.from_global_id(object_id)model_name = event._meta.root_type # type: ignore[union-attr]enable_dry_run = event._meta.enable_dry_run # type: ignore[union-attr]diff --git a/saleor/graphql/webhook/mutations/webhook_update.py b/saleor/graphql/webhook/mutations/webhook_update.pyindex edd67edba8..41823fb4b7 100644--- a/saleor/graphql/webhook/mutations/webhook_update.py+++ b/saleor/graphql/webhook/mutations/webhook_update.py@@ -1,17 +1,13 @@import graphene-from django.core.exceptions import ValidationErrorfrom ....permission.enums import AppPermissionfrom ....webhook import models-from ....webhook.error_codes import WebhookErrorCodefrom ...core import ResolveInfofrom ...core.descriptions import ADDED_IN_32, DEPRECATED_IN_3X_INPUT, PREVIEW_FEATURE-from ...core.mutations import ModelMutationfrom ...core.types import NonNullList, WebhookErrorfrom .. import enums-from ..subscription_payload import validate_queryfrom ..types import Webhook-from .webhook_create import clean_webhook_events+from . import WebhookCreateclass WebhookUpdateInput(graphene.InputObjectType):@@ -58,7 +54,7 @@ class WebhookUpdateInput(graphene.InputObjectType):)-class WebhookUpdate(ModelMutation):+class WebhookUpdate(WebhookCreate):class Arguments:id = graphene.ID(required=True, description="ID of a webhook to update.")input = WebhookUpdateInput(@@ -73,34 +69,6 @@ class WebhookUpdate(ModelMutation):error_type_class = WebhookErrorerror_type_field = "webhook_errors"- @classmethod- def clean_input(cls, info, instance, data):- cleaned_data = super().clean_input(info, instance, data)- app = cleaned_data.get("app")-- if not instance.app_id and not app:- raise ValidationError(- "Missing token or app", code=WebhookErrorCode.INVALID.value- )-- if instance.app_id:- # Let's skip app id in case when context has- # app instance- app = instance.app- cleaned_data.pop("app", None)-- if not app or not app.is_active:- raise ValidationError(- "App doesn't exist or is disabled",- code=WebhookErrorCode.NOT_FOUND.value,- )- clean_webhook_events(info, instance, cleaned_data)-- if query := cleaned_data.get("query"):- validate_query(query)- instance.subscription_query = query- return cleaned_data-@classmethoddef save(cls, _info: ResolveInfo, instance, cleaned_input):instance.save()@@ -113,3 +81,7 @@ class WebhookUpdate(ModelMutation):for event in events])++ @classmethod+ def get_instance(cls, info: ResolveInfo, **data):+ return super(WebhookCreate, cls).get_instance(info, **data)diff --git a/saleor/graphql/webhook/subscription_payload.py b/saleor/graphql/webhook/subscription_payload.pyindex 6a64f0d699..65b6b1467b 100644--- a/saleor/graphql/webhook/subscription_payload.py+++ b/saleor/graphql/webhook/subscription_payload.py@@ -2,75 +2,22 @@ from typing import Any, Dict, List, Optionalfrom celery.utils.log import get_task_loggerfrom django.conf import settings-from django.core.exceptions import ValidationErrorfrom django.utils import timezonefrom django.utils.functional import SimpleLazyObject-from graphql import GraphQLDocument, get_default_backend, parse-from graphql.error import GraphQLError, GraphQLSyntaxError-from graphql.language.ast import FragmentDefinition, OperationDefinition+from graphql import get_default_backend, parse+from graphql.error import GraphQLErrorfrom promise import Promisefrom ...app.models import Appfrom ...core.exceptions import PermissionDeniedfrom ...plugins.manager import PluginsManagerfrom ...settings import get_host-from ...webhook.error_codes import WebhookErrorCodefrom ..core import SaleorContextfrom ..utils import format_errorlogger = get_task_logger(__name__)-def validate_subscription_query(query: str) -> bool:- from ..api import schema-- graphql_backend = get_default_backend()- try:- document = graphql_backend.document_from_string(schema, query)- except (ValueError, GraphQLSyntaxError):- return False- if not check_document_is_single_subscription(document):- return False- return True---def validate_query(query):- if not query:- return- is_valid = validate_subscription_query(query)- if not is_valid:- raise ValidationError(- {- "query": ValidationError(- "Subscription query is not valid",- code=WebhookErrorCode.INVALID.value,- )- }- )---def check_document_is_single_subscription(document: GraphQLDocument) -> bool:- """Check if document contains only a single subscription definition.-- Only fragments and single subscription definition are allowed.- """- subscriptions = []- for definition in document.document_ast.definitions:- if isinstance(definition, FragmentDefinition):- pass- elif isinstance(definition, OperationDefinition):- if definition.operation == "subscription":- if len(definition.selection_set.selections) != 1:- return False- subscriptions.append(definition)-- else:- return False- else:- return False- return len(subscriptions) == 1--def initialize_request(requestor=None, sync_event=False) -> SaleorContext:"""Prepare a request object for webhook subscription.diff --git a/saleor/graphql/webhook/subscription_query.py b/saleor/graphql/webhook/subscription_query.pynew file mode 100644index 0000000000..64323f8465--- /dev/null+++ b/saleor/graphql/webhook/subscription_query.py@@ -0,0 +1,146 @@+from enum import Flag+from typing import Dict, List, Optional, Union++from django.core.exceptions import ValidationError+from graphene.utils.str_converters import to_snake_case+from graphql import get_default_backend, validate+from graphql.error import GraphQLSyntaxError+from graphql.language.ast import (+ Document,+ Field,+ FragmentDefinition,+ FragmentSpread,+ InlineFragment,+ OperationDefinition,+)++from ...webhook.error_codes import WebhookErrorCode+++class IsFragment(Flag):+ TRUE = True+ FALSE = False+++class SubscriptionQuery:+ def __init__(self, query: str):+ self.query: str = query+ self.is_valid: bool = False+ self.ast: Document = Document("")+ self.events: List[str] = []+ self.error_code: Optional[str] = None+ self.errors = self.validate_query()+ self.error_msg: str = ";".join(set([str(err.message) for err in self.errors]))++ def validate_query(self) -> List[Union[GraphQLSyntaxError, ValidationError]]:+ from ..api import schema++ graphql_backend = get_default_backend()+ try:+ document = graphql_backend.document_from_string(schema, self.query)+ self.ast = document.document_ast+ errors = validate(schema, self.ast)+ except GraphQLSyntaxError as e:+ self.error_code = WebhookErrorCode.SYNTAX.value+ return [e]++ if errors:+ self.error_code = WebhookErrorCode.GRAPHQL_ERROR.value+ return errors++ try:+ self.events = self.get_events_from_subscription()+ except ValidationError as err:+ self.error_code = err.code+ return [err]++ self.is_valid = True+ return []++ def get_events_from_subscription(self) -> List[str]:+ subscription = self._get_subscription(self.ast)+ if not subscription:+ raise ValidationError(+ message="Subscription operation can't be found.",+ code=WebhookErrorCode.MISSING_SUBSCRIPTION.value,+ )++ event_types = self._get_event_types_from_subscription(subscription)+ if not event_types:+ raise ValidationError(+ message="Event field can't be found.",+ code=WebhookErrorCode.UNABLE_TO_PARSE.value,+ )++ events_and_fragments: Dict[str, IsFragment] = {}+ for event_type in event_types:+ self._get_events_from_field(event_type, events_and_fragments)++ fragment_definitions = self._get_fragment_definitions(self.ast)+ unpacked_events: Dict[str, IsFragment] = {}+ for event_name, is_fragment in events_and_fragments.items():+ if not is_fragment:+ continue+ event_definition = fragment_definitions[event_name]+ self._get_events_from_field(event_definition, unpacked_events)+ events_and_fragments.update(unpacked_events)+ events = [k for k, v in events_and_fragments.items() if not v]++ if not events:+ raise ValidationError(+ message="Can't find a single event.",+ code=WebhookErrorCode.MISSING_EVENT.value,+ )++ return sorted(list(map(to_snake_case, events)))++ @staticmethod+ def _get_subscription(ast: Document) -> Optional[OperationDefinition]:+ for definition in ast.definitions:+ if (+ hasattr(definition, "operation")+ and definition.operation == "subscription"+ ):+ return definition+ return None++ @staticmethod+ def _get_event_types_from_subscription(+ subscription: OperationDefinition,+ ) -> List[Field]:+ return [+ field+ for field in subscription.selection_set.selections+ if field.name.value == "event" and isinstance(field, Field)+ ]++ @staticmethod+ def _get_events_from_field(+ field: Union[Field, FragmentDefinition],+ events: Dict[str, IsFragment],+ ) -> Dict[str, IsFragment]:+ if (+ isinstance(field, FragmentDefinition)+ and field.type_condition+ and field.type_condition.name.value != "Event"+ ):+ events[field.type_condition.name.value] = IsFragment.FALSE+ return events++ if field.selection_set:+ for f in field.selection_set.selections:+ if isinstance(f, InlineFragment) and f.type_condition:+ events[f.type_condition.name.value] = IsFragment.FALSE+ if isinstance(f, FragmentSpread):+ events[f.name.value] = IsFragment.TRUE+ return events++ return events++ @staticmethod+ def _get_fragment_definitions(ast: Document) -> Dict[str, FragmentDefinition]:+ fragments: Dict[str, FragmentDefinition] = {}+ for definition in ast.definitions:+ if isinstance(definition, FragmentDefinition):+ fragments[definition.name.value] = definition+ return fragmentsdiff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_create.py b/saleor/graphql/webhook/tests/mutations/test_webhook_create.pyindex 08388514b5..525afa1a3c 100644--- a/saleor/graphql/webhook/tests/mutations/test_webhook_create.py+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_create.py@@ -1,5 +1,6 @@import graphene+from .....webhook.error_codes import WebhookErrorCodefrom .....webhook.models import Webhookfrom ....tests.utils import assert_no_permission, get_graphql_contentfrom ...enums import WebhookEventTypeAsyncEnum, WebhookEventTypeSyncEnum@@ -10,9 +11,16 @@ WEBHOOK_CREATE = """errors {fieldmessage+ code}webhook {id+ asyncEvents {+ eventType+ }+ syncEvents {+ eventType+ }}}}@@ -20,6 +28,7 @@ WEBHOOK_CREATE = """def test_webhook_create_by_app(app_api_client, permission_manage_orders):+ # givenquery = WEBHOOK_CREATEvariables = {"input": {@@ -31,6 +40,8 @@ def test_webhook_create_by_app(app_api_client, permission_manage_orders):],}}++ # whenresponse = app_api_client.post_graphql(query,variables=variables,@@ -38,6 +49,8 @@ def test_webhook_create_by_app(app_api_client, permission_manage_orders):check_no_permissions=False,)get_graphql_content(response)++ # thennew_webhook = Webhook.objects.get()assert new_webhook.name == "New integration"assert new_webhook.target_url == "https://www.example.com"@@ -47,6 +60,7 @@ def test_webhook_create_by_app(app_api_client, permission_manage_orders):def test_webhook_create_inactive_app(app_api_client, app, permission_manage_orders):+ # givenapp.is_active = Falseapp.save()query = WEBHOOK_CREATE@@ -57,14 +71,16 @@ def test_webhook_create_inactive_app(app_api_client, app, permission_manage_orde"name": "",}}-+ # whenresponse = app_api_client.post_graphql(query, variables=variables, permissions=[permission_manage_orders])+ # thenassert_no_permission(response)def test_webhook_create_without_app(app_api_client, app):+ # givenapp_api_client.app = Noneapp_api_client.app_token = Nonequery = WEBHOOK_CREATE@@ -75,13 +91,14 @@ def test_webhook_create_without_app(app_api_client, app):"name": "",}}+ # whenresponse = app_api_client.post_graphql(query, variables=variables)+ # thenassert_no_permission(response)def test_webhook_create_app_doesnt_exist(app_api_client, app):- app.delete()-+ # givenquery = WEBHOOK_CREATEvariables = {"input": {@@ -90,7 +107,10 @@ def test_webhook_create_app_doesnt_exist(app_api_client, app):"name": "",}}+ # when+ app.delete()response = app_api_client.post_graphql(query, variables=variables)+ # thenassert_no_permission(response)@@ -100,6 +120,7 @@ def test_webhook_create_by_staff(permission_manage_apps,permission_manage_orders,):+ # givenquery = WEBHOOK_CREATEapp.permissions.add(permission_manage_orders)app_id = graphene.Node.to_global_id("App", app.pk)@@ -112,8 +133,12 @@ def test_webhook_create_by_staff(}}staff_api_client.user.user_permissions.add(permission_manage_apps)++ # whenresponse = staff_api_client.post_graphql(query, variables=variables)get_graphql_content(response)++ # thennew_webhook = Webhook.objects.get()assert new_webhook.target_url == "https://www.example.com"assert new_webhook.app == app@@ -126,6 +151,7 @@ def test_webhook_create_by_staff(def test_webhook_create_by_staff_with_inactive_app(staff_api_client, app):+ # givenapp.is_active = Falsequery = WEBHOOK_CREATEapp_id = graphene.Node.to_global_id("App", app.pk)@@ -136,12 +162,17 @@ def test_webhook_create_by_staff_with_inactive_app(staff_api_client, app):"app": app_id,}}++ # whenresponse = staff_api_client.post_graphql(query, variables=variables)assert_no_permission(response)++ # thenassert Webhook.objects.count() == 0def test_webhook_create_by_staff_without_permission(staff_api_client, app):+ # givenquery = WEBHOOK_CREATEapp_id = graphene.Node.to_global_id("App", app.pk)variables = {@@ -151,22 +182,26 @@ def test_webhook_create_by_staff_without_permission(staff_api_client, app):"app": app_id,}}++ # whenresponse = staff_api_client.post_graphql(query, variables=variables)++ # thenassert_no_permission(response)assert Webhook.objects.count() == 0-def test_webhook_create_inherit_events_from_query(- app_api_client, permission_manage_orders, subscription_order_created_webhook-):+def test_webhook_create_by_app_invalid_query(app_api_client, permission_manage_orders):# givenquery = WEBHOOK_CREATE- subscription_query = subscription_order_created_webhook.subscription_queryvariables = {"input": {"name": "New integration","targetUrl": "https://www.example.com",- "query": subscription_query,+ "asyncEvents": [+ WebhookEventTypeAsyncEnum.ORDER_CREATED.name,+ ],+ "query": "invalid_query",}}@@ -181,42 +216,14 @@ def test_webhook_create_inherit_events_from_query(# thendata = content["data"]["webhookCreate"]- assert not data["errors"]- _, id = graphene.Node.from_global_id(data["webhook"]["id"])- new_webhook = Webhook.objects.filter(id=id).get()- events = new_webhook.events.all()- assert len(events) == 1- assert WebhookEventTypeAsyncEnum.ORDER_CREATED.value == events[0].event_type---def test_webhook_create_by_staff_invalid_query(- app_api_client, permission_manage_orders-):- query = WEBHOOK_CREATE- variables = {- "input": {- "name": "New integration",- "targetUrl": "https://www.example.com",- "asyncEvents": [- WebhookEventTypeAsyncEnum.ORDER_CREATED.name,- ],- "query": "invalid_query",- }- }- response = app_api_client.post_graphql(- query,- variables=variables,- permissions=[permission_manage_orders],- check_no_permissions=False,- )- content = get_graphql_content(response)- expected_errors = [{"field": "query", "message": "Subscription query is not valid"}]- content = content["data"]["webhookCreate"]- assert not content["webhook"]- assert content["errors"] == expected_errors+ assert not data["webhook"]+ error = data["errors"][0]+ assert error["field"] == "query"+ assert 'Unexpected Name "invalid_query"' in error["message"]+ assert error["code"] == WebhookErrorCode.SYNTAX.name-SUBSCRIPTION_QUERY_WITH_MULTIPLE_LVL_FIELDS = """+SUBSCRIPTION_QUERY_WITH_MULTIPLE_EVENTS = """subscription {event {... on PaymentListGateways {@@ -224,41 +231,58 @@ subscription {id}}- }- ... on CheckoutFilterShippingMethods {- checkout {- id- }- shippingMethods {- name- id+ ... on OrderCreated {+ order {+ id+ }}}-}"""+}+"""-def test_webhook_create_by_staff_invalid_query_multiple_level_fields(- app_api_client, permission_manage_orders+def test_webhook_create_inherit_events_from_query(+ staff_api_client,+ app,+ permission_manage_apps,+ permission_manage_orders,):+ # givenquery = WEBHOOK_CREATE+ app.permissions.add(permission_manage_orders)+ staff_api_client.user.user_permissions.add(permission_manage_apps)+ app_id = graphene.Node.to_global_id("App", app.pk)variables = {"input": {- "name": "New integration","targetUrl": "https://www.example.com",- "asyncEvents": [- WebhookEventTypeAsyncEnum.ORDER_CREATED.name,- ],- "query": SUBSCRIPTION_QUERY_WITH_MULTIPLE_LVL_FIELDS,+ "app": app_id,+ "query": SUBSCRIPTION_QUERY_WITH_MULTIPLE_EVENTS,}}- response = app_api_client.post_graphql(- query,- variables=variables,- permissions=[permission_manage_orders],- check_no_permissions=False,- )++ # when+ response = staff_api_client.post_graphql(query, variables=variables)content = get_graphql_content(response)- expected_errors = [{"field": "query", "message": "Subscription query is not valid"}]- content = content["data"]["webhookCreate"]- assert not content["webhook"]- assert content["errors"] == expected_errors++ # then+ new_webhook = Webhook.objects.get()+ assert new_webhook.target_url == "https://www.example.com"+ assert new_webhook.app == app+ events = new_webhook.events.all()+ assert len(events) == 2++ created_event_types = [event.event_type for event in events]+ assert WebhookEventTypeAsyncEnum.ORDER_CREATED.value in created_event_types+ assert WebhookEventTypeSyncEnum.PAYMENT_LIST_GATEWAYS.value in created_event_types++ data = content["data"]["webhookCreate"]+ assert not data["errors"]+ assert data["webhook"]+ assert (+ data["webhook"]["asyncEvents"][0]["eventType"]+ == WebhookEventTypeAsyncEnum.ORDER_CREATED.name+ )+ assert (+ data["webhook"]["syncEvents"][0]["eventType"]+ == WebhookEventTypeSyncEnum.PAYMENT_LIST_GATEWAYS.name+ )diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.pyindex 29909baedf..9111501a54 100644--- a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py@@ -119,33 +119,7 @@ def test_webhook_dry_run_non_existing_id(assert error["message"] == f"Couldn't resolve to a node: {order_id}"-def test_webhook_dry_run_wrong_subscription_query(- staff_api_client,- permission_manage_orders,- order,- subscription_order_created_webhook,-):- # given- query = WEBHOOK_DRY_RUN_MUTATION- staff_api_client.user.user_permissions.add(permission_manage_orders)- order_id = graphene.Node.to_global_id("Order", order.id)- webhook = subscription_order_created_webhook- subscription = webhook.subscription_query.replace("subscription", "whatever")-- variables = {"objectId": order_id, "query": subscription}-- # when- response = staff_api_client.post_graphql(query, variables)- content = get_graphql_content(response)-- # then- error = content["data"]["webhookDryRun"]["errors"][0]- assert error["field"] == "query"- assert error["code"] == WebhookDryRunErrorCode.UNABLE_TO_PARSE.name- assert error["message"] == "Can't parse an event type from query."---def test_webhook_dry_run_event_type_doesnt_exist(+def test_webhook_dry_run_invalid_query(staff_api_client,permission_manage_orders,order,@@ -168,10 +142,7 @@ def test_webhook_dry_run_event_type_doesnt_exist(error = content["data"]["webhookDryRun"]["errors"][0]assert error["field"] == "query"assert error["code"] == WebhookDryRunErrorCode.GRAPHQL_ERROR.name- assert (- error["message"]- == "Event type: UndefinedEvent is not defined in graphql schema."- )+ assert 'Unknown type "UndefinedEvent"' in error["message"]def test_webhook_dry_run_object_id_does_not_match_event(diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.py b/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.pyindex 5dbd6afc0b..d7e2f84504 100644--- a/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.py+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.py@@ -181,44 +181,7 @@ def test_webhook_trigger_missing_subscription_query(@mock.patch("saleor.plugins.webhook.tasks.send_webhook_request_async")-def test_webhook_trigger_wrong_subscription_query(- mocked_send_webhook_request,- staff_api_client,- permission_manage_orders,- order,- subscription_order_created_webhook,-):- # given- mocked_send_webhook_request.return_value = None- query = WEBHOOK_TRIGGER_MUTATION- staff_api_client.user.user_permissions.add(permission_manage_orders)- order_id = graphene.Node.to_global_id("Order", order.id)- webhook = subscription_order_created_webhook- webhook_id = graphene.Node.to_global_id("Webhook", webhook.id)-- webhook.subscription_query = webhook.subscription_query.replace(- "subscription", "whatever"- )- webhook.save(update_fields=["subscription_query"])-- variables = {"webhookId": webhook_id, "objectId": order_id}-- # when- response = staff_api_client.post_graphql(query, variables)- content = get_graphql_content(response)-- # then- error = content["data"]["webhookTrigger"]["errors"][0]- assert not error["field"]- assert error["code"] == WebhookTriggerErrorCode.UNABLE_TO_PARSE.name- assert (- error["message"]- == "Can't parse an event type from webhook's subscription query."- )--[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async")-def test_webhook_trigger_event_type_undefined(+def test_webhook_trigger_invalid_subscription_query(mocked_send_webhook_request,staff_api_client,permission_manage_orders,@@ -248,11 +211,7 @@ def test_webhook_trigger_event_type_undefined(error = content["data"]["webhookTrigger"]["errors"][0]assert not error["field"]assert error["code"] == WebhookTriggerErrorCode.GRAPHQL_ERROR.name- assert (- error["message"]- == "Event type: UndefinedEvent, which was parsed from webhook's "- "subscription query, is not defined in graphql schema."- )+ assert 'Unknown type "UndefinedEvent"' in error["message"]@mock.patch("saleor.plugins.webhook.tasks.send_webhook_request_async")diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_update.py b/saleor/graphql/webhook/tests/mutations/test_webhook_update.pyindex 262c78beb1..6bd00d9684 100644--- a/saleor/graphql/webhook/tests/mutations/test_webhook_update.py+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_update.py@@ -25,6 +25,7 @@ WEBHOOK_UPDATE = """def test_webhook_update_not_allowed_by_app(app_api_client, app, webhook):+ # givenquery = WEBHOOK_UPDATEwebhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)variables = {@@ -34,13 +35,15 @@ def test_webhook_update_not_allowed_by_app(app_api_client, app, webhook):"isActive": False,},}+ # whenresponse = app_api_client.post_graphql(query, variables=variables)++ # thenassert_no_permission(response)-def test_webhook_update_by_staff(- staff_api_client, app, webhook, permission_manage_apps-):+def test_webhook_update_by_staff(staff_api_client, webhook, permission_manage_apps):+ # givenquery = WEBHOOK_UPDATEwebhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)variables = {@@ -54,16 +57,29 @@ def test_webhook_update_by_staff(},}staff_api_client.user.user_permissions.add(permission_manage_apps)++ # whenresponse = staff_api_client.post_graphql(query, variables=variables)- get_graphql_content(response)+ content = get_graphql_content(response)webhook.refresh_from_db()++ # thenassert webhook.is_active is Falseevents = webhook.events.all()assert len(events) == 1assert events[0].event_type == WebhookEventTypeAsyncEnum.CUSTOMER_CREATED.value+ data = content["data"]["webhookUpdate"]+ assert not data["errors"]+ assert (+ data["webhook"]["asyncEvents"][0]["eventType"]+ == WebhookEventTypeAsyncEnum.CUSTOMER_CREATED.name+ )+ assert data["webhook"]["isActive"] is False+def test_webhook_update_by_staff_without_permission(staff_api_client, app, webhook):+ # givenquery = WEBHOOK_UPDATEwebhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)variables = {@@ -76,7 +92,11 @@ def test_webhook_update_by_staff_without_permission(staff_api_client, app, webho"isActive": False,},}++ # whenresponse = staff_api_client.post_graphql(query, variables=variables)++ # thenassert_no_permission(response)diff --git a/saleor/graphql/webhook/tests/test_subscription_query.py b/saleor/graphql/webhook/tests/test_subscription_query.pynew file mode 100644index 0000000000..5d3c8342f7--- /dev/null+++ b/saleor/graphql/webhook/tests/test_subscription_query.py@@ -0,0 +1,371 @@+import pytest+from django.core.exceptions import ValidationError+from graphql import GraphQLError+from graphql.error import GraphQLSyntaxError++from saleor.webhook.error_codes import WebhookErrorCode++from ..subscription_query import IsFragment, SubscriptionQuery+++def test_subscription_query():+ # given+ query = """+ fragment EventFragment on Event {+ ... on OrderUpdated {+ order {+ id+ }+ }+ ... on OrderCreated {+ order {+ id+ }+ }+ }++ subscription {+ event {+ ... EventFragment+ ... on ProductCreated {+ product {+ id+ }+ }+ }+ }+ """++ # when+ subscription_query = SubscriptionQuery(query)++ # then+ assert subscription_query.is_valid+ assert subscription_query.ast+ assert not subscription_query.errors+ assert subscription_query.events == [+ "order_created",+ "order_updated",+ "product_created",+ ]+++ "query,events",+ [+ (+ """+ subscription {+ event {+ ...on OrderCreated {+ order {+ id+ }+ }+ }+ }+ """,+ ["order_created"],+ ),+ (+ """+ fragment OrderFragment on Order {+ id+ number+ lines {+ id+ }+ }+ subscription {+ event {+ ...on OrderCreated {+ order {+ ...OrderFragment+ }+ }+ }+ }+ """,+ ["order_created"],+ ),+ (+ """+ fragment OrderFragment on Order {+ id+ }++ fragment EventFragment on Event {+ issuedAt+ ... on OrderUpdated {+ order {+ ... OrderFragment+ }+ }+ }++ subscription {+ event {+ ... EventFragment+ }+ }+ """,+ ["order_updated"],+ ),+ (+ """+ subscription {+ event{+ ... on OrderCreated{+ order{+ id+ }+ }+ ... on OrderFullyPaid{+ order{+ id+ }+ }+ ... on ProductCreated{+ product{+ id+ }+ }+ }+ }+ """,+ ["order_created", "order_fully_paid", "product_created"],+ ),+ (+ """+ fragment MyFragment on Event {+ ... on OrderCreated{+ order{+ id+ }+ }+ ... on OrderUpdated{+ order{+ id+ }+ }+ ... on ProductCreated{+ product{+ id+ }+ }+ }+ subscription {+ event {+ ... MyFragment+ }+ }+ """,+ ["order_created", "order_updated", "product_created"],+ ),+ (+ """+ fragment EventFragment on Event {+ ... on OrderUpdated {+ order {+ id+ }+ }+ ... on OrderCreated {+ order {+ id+ }+ }+ }++ subscription {+ event {+ ... EventFragment+ ... on ProductCreated {+ product {+ id+ }+ }+ }+ }+ """,+ ["order_updated", "order_created", "product_created"],+ ),+ (+ """+ subscription InvoiceRequested {+ event {+ ...InvoiceRequestedPayload+ }+ }+ fragment InvoiceRequestedPayload on InvoiceRequested {+ invoice {+ id+ }+ }+ """,+ ["invoice_requested"],+ ),+ (+ """+ subscription{+ event{+ ...on ProductUpdated{+ product{+ id+ }+ }+ }+ event{+ ...on ProductCreated{+ product{+ id+ }+ }+ }+ }+ """,+ ["product_updated", "product_created"],+ ),+ ],+)+def test_get_event_type_from_subscription(query, events):+ subscription_query = SubscriptionQuery(query)+ assert subscription_query.is_valid+ assert subscription_query.events == sorted(events)+++ "query,error_msg,error_type,error_code",+ [+ (+ """+ mutation SomeMutation {+ someMutation(input: {}) {+ result {+ id+ }+ }+ }+ """,+ 'Cannot query field "someMutation" on type "Mutation".',+ GraphQLError,+ WebhookErrorCode.GRAPHQL_ERROR,+ ),+ (+ """+ subscription {+ event {+ ... MyFragment+ }+ }+ """,+ 'Unknown fragment "MyFragment".',+ GraphQLError,+ WebhookErrorCode.GRAPHQL_ERROR,+ ),+ (+ """+ fragment NotUsedEvents on Order {+ id+ }+ subscription {+ event {+ ... on OrderUpdated {+ order {+ id+ }+ }+ }+ }+ """,+ 'Fragment "NotUsedEvents" is never used.',+ GraphQLError,+ WebhookErrorCode.GRAPHQL_ERROR,+ ),+ (+ """+ query {{+ }+ """,+ "Syntax Error GraphQL (2:20) Expected Name, found",+ GraphQLSyntaxError,+ WebhookErrorCode.SYNTAX,+ ),+ (+ """+ query {+ channels {+ name+ }+ }+ """,+ "Subscription operation can't be found.",+ ValidationError,+ WebhookErrorCode.MISSING_SUBSCRIPTION,+ ),+ (+ """+ subscription {+ event {+ issuedAt+ }+ }+ """,+ "Can't find a single event.",+ ValidationError,+ WebhookErrorCode.MISSING_EVENT,+ ),+ ],+)+def test_query_validation(query, error_msg, error_type, error_code):+ subscription_query = SubscriptionQuery(query)+ assert not subscription_query.is_valid+ error = subscription_query.errors[0]+ assert isinstance(error, error_type)+ assert error_msg in error.message+ assert error_code.value == subscription_query.error_code+++def test_get_events_from_field():+ # given+ query = """+ fragment EventFragment on Event {+ ... on OrderUpdated {+ order {+ id+ }+ }+ }+ subscription {+ event {+ ... on OrderCreated {+ order {+ id+ }+ }+ something+ somethingElse+ ... on OrderFullyPaid {+ order {+ id+ }+ }+ ... EventFragment+ }+ }+ """++ # when+ subscription_query = SubscriptionQuery(query)+ subscription = subscription_query._get_subscription(subscription_query.ast)+ event_fields = subscription_query._get_event_types_from_subscription(subscription)+ result = {}+ for event_field in event_fields:+ subscription_query._get_events_from_field(event_field, result)++ # then+ assert result == {+ "OrderCreated": IsFragment.FALSE,+ "OrderFullyPaid": IsFragment.FALSE,+ "EventFragment": IsFragment.TRUE,+ }diff --git a/saleor/graphql/webhook/tests/test_utils.py b/saleor/graphql/webhook/tests/test_utils.pydeleted file mode 100644index 91ea2a1014..0000000000--- a/saleor/graphql/webhook/tests/test_utils.py+++ /dev/null@@ -1,128 +0,0 @@-import pytest--from ..utils import get_event_type_from_subscription--- "query,event",- [- (- """- subscription {- event {- ...on- OrderCreated {- order {- id- }- }- }- }- """,- ["order_created"],- ),- (- """- fragment OrderFragment on Order {- id- number- lines {- id- }- }- subscription {- event {- ...on OrderCreated {- order {- ...OrderFragment- }- }- }- }- """,- ["order_created"],- ),- (- """- fragment NotUsedEvents on Event {- ... on OrderCreated {- order {- id- }- }- }-- subscription {- event {- ... on OrderUpdated {- order {- id- }- }- }- }- """,- ["order_updated"],- ),- (- """- fragment OrderFragment on Order {- order {- id- }- }-- fragment EventFragment on Event {- ... on OrderUpdated {- ... OrderFragment- }- }-- subscription {- event {- ... EventFragment- }- }- """,- ["order_updated"],- ),- (- """- mutation SomeMutation {- someMutation(input: {}) {- result {- id- }- }- }- """,- [],- ),- (- """- subscription {- event{- ... on OrderCreated{- order{- id- }- }- ... on OrderFullyPaid{- order{- id- }- }- ... on ProductCreated{- product{- id- }- }- }- }- """,- ["order_created", "order_fully_paid", "product_created"],- ),- ],-)-def test_get_event_type_from_subscription(query, event):- assert get_event_type_from_subscription(query) == eventdiff --git a/saleor/graphql/webhook/utils.py b/saleor/graphql/webhook/utils.pydeleted file mode 100644index edb101b7f3..0000000000--- a/saleor/graphql/webhook/utils.py+++ /dev/null@@ -1,76 +0,0 @@-from typing import Dict, List, Optional--from graphene.utils.str_converters import to_snake_case-from graphql import parse-from graphql.error import GraphQLSyntaxError-from graphql.language.ast import Document---def get_event_type_from_subscription(query: str) -> List[str]:- try:- ast = parse(query)- subscription = get_subscription(ast)- if not subscription:- return []-- event_field = get_event_field_from_subscription(subscription)- if not event_field:- return []-- events = get_events(event_field)- if not events:- return []-- fragments = get_event_fragment_names_from_query(ast)- if fragments:- events = [fragments.get(event, event) for event in events]-- return list(map(to_snake_case, events))-- except GraphQLSyntaxError:- return []---def get_event_field_from_subscription(field):- if hasattr(field, "selection_set"):- fields = field.selection_set.selections- for f in fields:- if f.name.value == "event":- return f- get_event_field_from_subscription(f)---def get_subscription(ast):- for definition in ast.definitions:- if hasattr(definition, "operation") and definition.operation == "subscription":- return definition- return None---def get_events(field):- try:- fields = field.selection_set.selections- events = []- for field in fields:- if hasattr(field, "name"):- events.append(field.name.value)- if hasattr(field, "type_condition"):- events.append(field.type_condition.name.value)- return events- except AttributeError:- return []---def get_event_fragment_names_from_query(ast: Document) -> Optional[Dict[str, str]]:- fragments = {}- try:- for definition in ast.definitions:- if (- definition.__class__.__name__ == "FragmentDefinition"- and definition.type_condition.name.value == "Event"- ):- event = definition.selection_set.selections[0].type_condition.name.value- fragments[definition.name.value] = event- return fragments- except AttributeError:- return fragmentsdiff --git a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.pyindex 2d4ab69c0c..16f55c0de9 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py@@ -2034,20 +2034,24 @@ INVALID_MULTIPLE_EVENTS_WITH_FRAGMENTS = (event{...on ProductUpdated{product{- variants{- ...ProductVariant- }- ...CategoryDetails+ variants{+ ...ProductVariant+ }+ category {+ ...CategoryDetails+ }}}}event{...on ProductCreated{product{- variants{+ variants{...ProductVariant}- ...CategoryDetails+ category{+ ...CategoryDetails+ }}}}@@ -2064,10 +2068,12 @@ QUERY_WITH_MULTIPLE_FRAGMENTS = (event{...on ProductUpdated{product{- variants{- ...ProductVariant+ variants{+ ...ProductVariant+ }+ category{+ ...CategoryDetails}- ...CategoryDetails}}}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.pyindex 70d3aa1451..fa327ec0ef 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@@ -7,7 +7,7 @@ from freezegun import freeze_timefrom .....channel.models import Channelfrom .....giftcard.models import GiftCard-from .....graphql.webhook.subscription_payload import validate_subscription_query+from .....graphql.webhook.subscription_query import SubscriptionQueryfrom .....menu.models import Menu, MenuItemfrom .....product.models import Categoryfrom .....shipping.models import ShippingMethod, ShippingZone@@ -2187,62 +2187,61 @@ def test_create_deliveries_for_subscriptions_document_executed_with_error(def test_validate_subscription_query_valid():- result = validate_subscription_query(- subscription_queries.TEST_VALID_SUBSCRIPTION_QUERY- )- assert result is True+ query = SubscriptionQuery(subscription_queries.TEST_VALID_SUBSCRIPTION_QUERY)+ assert query.is_validdef test_validate_subscription_query_invalid():- result = validate_subscription_query("invalid_query")- assert result is False+ query = SubscriptionQuery("invalid_query")+ assert not query.is_validdef test_validate_subscription_query_valid_with_fragment():- result = validate_subscription_query(+ query = SubscriptionQuery(subscription_queries.TEST_VALID_SUBSCRIPTION_QUERY_WITH_FRAGMENT)- assert result is True+ assert query.is_validdef test_validate_invalid_query_and_subscription():- result = validate_subscription_query(- subscription_queries.TEST_INVALID_QUERY_AND_SUBSCRIPTION+ query = SubscriptionQuery(subscription_queries.TEST_INVALID_QUERY_AND_SUBSCRIPTION)+ assert not query.is_valid+ assert (+ "This anonymous operation must be the only defined operation" in query.error_msg)- assert result is Falsedef test_validate_invalid_subscription_and_query():- result = validate_subscription_query(- subscription_queries.TEST_INVALID_SUBSCRIPTION_AND_QUERY+ query = SubscriptionQuery(subscription_queries.TEST_INVALID_SUBSCRIPTION_AND_QUERY)+ assert not query.is_valid+ assert (+ "This anonymous operation must be the only defined operation" in query.error_msg)- assert result is Falsedef test_validate_invalid_multiple_subscriptions():- result = validate_subscription_query(- subscription_queries.TEST_INVALID_MULTIPLE_SUBSCRIPTION+ query = SubscriptionQuery(subscription_queries.TEST_INVALID_MULTIPLE_SUBSCRIPTION)+ assert not query.is_valid+ assert (+ "This anonymous operation must be the only defined operation" in query.error_msg)- assert result is False-def test_vaidate_invalid_multiple_events_in_subscription():- result = validate_subscription_query(subscription_queries.INVALID_MULTIPLE_EVENTS)- assert result is False+def test_validate_valid_multiple_events_in_subscription():+ query = SubscriptionQuery(subscription_queries.INVALID_MULTIPLE_EVENTS)+ assert query.is_valid-def test_vaidate_invalid_multiple_events_and_fragments_in_subscription():- result = validate_subscription_query(+def test_validate_invalid_multiple_events_and_fragments_in_subscription():+ query = SubscriptionQuery(subscription_queries.INVALID_MULTIPLE_EVENTS_WITH_FRAGMENTS)- assert result is False+ assert query.is_validdef test_validate_query_with_multiple_fragments():- result = validate_subscription_query(- subscription_queries.QUERY_WITH_MULTIPLE_FRAGMENTS- )- assert result is True+ query = SubscriptionQuery(subscription_queries.QUERY_WITH_MULTIPLE_FRAGMENTS)+ assert query.is_validdef test_generate_payload_from_subscription_return_permission_errors_in_payload(diff --git a/saleor/webhook/error_codes.py b/saleor/webhook/error_codes.pyindex 0165fbc66c..18cd0e1ed0 100644--- a/saleor/webhook/error_codes.py+++ b/saleor/webhook/error_codes.py@@ -8,22 +8,32 @@ class WebhookErrorCode(Enum):REQUIRED = "required"UNIQUE = "unique"DELETE_FAILED = "delete_failed"+ SYNTAX = "syntax"+ MISSING_SUBSCRIPTION = "missing_subscription"+ UNABLE_TO_PARSE = "unable_to_parse"+ MISSING_EVENT = "missing_event"class WebhookDryRunErrorCode(Enum):GRAPHQL_ERROR = "graphql_error"- UNABLE_TO_PARSE = "unable_to_parse"NOT_FOUND = "not_found"INVALID_ID = "invalid_id"MISSING_PERMISSION = "missing_permission"TYPE_NOT_SUPPORTED = "type_not_supported"+ SYNTAX = "syntax"+ MISSING_SUBSCRIPTION = "missing_subscription"+ UNABLE_TO_PARSE = "unable_to_parse"+ MISSING_EVENT = "missing_event"class WebhookTriggerErrorCode(Enum):GRAPHQL_ERROR = "graphql_error"NOT_FOUND = "not_found"INVALID_ID = "invalid_id"- MISSING_PERMISSION = "missing_app_permission"- MISSING_QUERY = "missing_query"+ MISSING_PERMISSION = "missing_permission"TYPE_NOT_SUPPORTED = "type_not_supported"+ SYNTAX = "syntax"+ MISSING_SUBSCRIPTION = "missing_subscription"UNABLE_TO_PARSE = "unable_to_parse"+ MISSING_QUERY = "missing_query"+ MISSING_EVENT = "missing_event"