Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Webhook manual trigger (#11687)
Piotr Zabieglik85fb992dc008
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3450e56699..1152342d7b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,8 +11,10 @@ All notable, unreleased changes to this project will be documented in this file.- Add `webhookDryRun` mutation - #11548 by @zedzior- Fix adding invalid label to meta fields - #11718 by @IKarbowiak- Add filter by `checkoutToken` to `Query.orders`. - #11689 by @kadewu+- Add `WebhookTrigger` mutation - #11687 by @zedzior### Other changes+- Allow `webhookCreate` and `webhookUpdate` mutations to inherit events from `query` field - #11736 by @zedzior# 3.10.0 [Unreleased]diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.pyindex dd36f084b4..f033d5e7db 100644--- a/saleor/graphql/core/enums.py+++ b/saleor/graphql/core/enums.py@@ -152,3 +152,6 @@ TranslationErrorCode = graphene.Enum.from_enum(core_error_codes.TranslationErrorWebhookDryRunErrorCode = graphene.Enum.from_enum(webhook_error_codes.WebhookDryRunErrorCode)+WebhookTriggerErrorCode = graphene.Enum.from_enum(+ webhook_error_codes.WebhookTriggerErrorCode+)diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.pyindex 88bcf7b616..a6c4e4af8d 100644--- a/saleor/graphql/core/types/__init__.py+++ b/saleor/graphql/core/types/__init__.py@@ -54,6 +54,7 @@ from .common import (WarehouseError,WebhookDryRunError,WebhookError,+ WebhookTriggerError,Weight,)from .event import SubscriptionObjectType@@ -127,6 +128,7 @@ __all__ = ["WarehouseError","WebhookError","WebhookDryRunError",+ "WebhookTriggerError","FilterInputObjectType","SortInputObjectType","ChannelFilterInputObjectType",diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.pyindex ac837a6c97..1da1aec142 100644--- a/saleor/graphql/core/types/common.py+++ b/saleor/graphql/core/types/common.py@@ -45,6 +45,7 @@ from ..enums import (WarehouseErrorCode,WebhookDryRunErrorCode,WebhookErrorCode,+ WebhookTriggerErrorCode,WeightUnitsEnum,)from ..scalars import Date, PositiveDecimal@@ -56,7 +57,6 @@ if TYPE_CHECKING:# deprecated - this is temporary constant that contains the graphql types# which has double id available - uuid and old int id-TYPES_WITH_DOUBLE_ID_AVAILABLE = ["Order", "OrderLine", "OrderDiscount", "CheckoutLine"]@@ -416,6 +416,10 @@ class WebhookDryRunError(Error):code = WebhookDryRunErrorCode(description="The error code.", required=True)+class WebhookTriggerError(Error):+ code = WebhookTriggerErrorCode(description="The error code.", required=True)++class TranslationError(Error):code = TranslationErrorCode(description="The error code.", required=True)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 650cda01fb..2495a29008 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -11947,9 +11947,9 @@ type Mutation {): EventDeliveryRetry"""- Performs a dry run of a webhook event. Supports a single event (the first if multiple provided in the `query`). Requires permission relevant to processed event.+ Performs a dry run of a webhook event. Supports a single event (the first, if multiple provided in the `query`). Requires permission relevant to processed event.- Added in Saleor 3.10.+ Added in Saleor 3.11.Note: this API is currently in Feature Preview and can be subject to changes at later point.@@ -11963,6 +11963,23 @@ type Mutation {query: String!): WebhookDryRun+ """+ Trigger a webhook event. Supports a single event (the first, if multiple provided in the `webhook.subscription_query`). Requires permission relevant to processed event. Successfully delivered webhook returns `delivery` with status='PENDING' and empty payload.++ Added in Saleor 3.11.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.++ Requires one of the following permissions: AUTHENTICATED_STAFF_USER.+ """+ webhookTrigger(+ """The ID of an object to serialize."""+ objectId: ID!++ """The ID of the webhook."""+ webhookId: ID!+ ): WebhookTrigger+"""Creates new warehouse.@@ -15909,9 +15926,9 @@ type EventDeliveryRetry {}"""-Performs a dry run of a webhook event. Supports a single event (the first if multiple provided in the `query`). Requires permission relevant to processed event.+Performs a dry run of a webhook event. Supports a single event (the first, if multiple provided in the `query`). Requires permission relevant to processed event.-Added in Saleor 3.10.+Added in Saleor 3.11.Note: this API is currently in Feature Preview and can be subject to changes at later point.@@ -15946,6 +15963,44 @@ enum WebhookDryRunErrorCode {TYPE_NOT_SUPPORTED}+"""+Trigger a webhook event. Supports a single event (the first, if multiple provided in the `webhook.subscription_query`). Requires permission relevant to processed event. Successfully delivered webhook returns `delivery` with status='PENDING' and empty payload.++Added in Saleor 3.11.++Note: this API is currently in Feature Preview and can be subject to changes at later point.++Requires one of the following permissions: AUTHENTICATED_STAFF_USER.+"""+type WebhookTrigger {+ delivery: EventDelivery+ errors: [WebhookTriggerError!]!+}++type WebhookTriggerError {+ """+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.+ """+ field: String++ """The error message."""+ message: String++ """The error code."""+ code: WebhookTriggerErrorCode!+}++"""An enumeration."""+enum WebhookTriggerErrorCode {+ GRAPHQL_ERROR+ NOT_FOUND+ INVALID_ID+ MISSING_PERMISSION+ MISSING_QUERY+ TYPE_NOT_SUPPORTED+ UNABLE_TO_PARSE+}+"""Creates new warehouse.diff --git a/saleor/graphql/webhook/dataloaders.py b/saleor/graphql/webhook/dataloaders.pyindex b452e91deb..a5eeb80339 100644--- a/saleor/graphql/webhook/dataloaders.py+++ b/saleor/graphql/webhook/dataloaders.py@@ -12,7 +12,11 @@ class PayloadByIdLoader(DataLoader[str, str]):payload = EventPayload.objects.using(self.database_connection_name).in_bulk(keys)- return [payload[payload_id].payload for payload_id in keys]++ return [+ payload[payload_id].payload if payload.get(payload_id) else None+ for payload_id in keys+ ]class WebhookEventsByWebhookIdLoader(DataLoader):diff --git a/saleor/graphql/webhook/mutations.py b/saleor/graphql/webhook/mutations.pydeleted file mode 100644index c4207ed8fe..0000000000--- a/saleor/graphql/webhook/mutations.py+++ /dev/null@@ -1,422 +0,0 @@-import graphene-from django.core.exceptions import ValidationError-from django.db import IntegrityError-from graphene.utils.str_converters import to_camel_case--from ...permission.auth_filters import AuthorizationFilters-from ...permission.enums import AppPermission-from ...webhook import models-from ...webhook.error_codes import WebhookDryRunErrorCode, WebhookErrorCode-from ...webhook.event_types import WebhookEventAsyncType-from ..app.dataloaders import get_app_promise-from ..core import ResolveInfo-from ..core.descriptions import (- ADDED_IN_32,- ADDED_IN_310,- DEPRECATED_IN_3X_INPUT,- PREVIEW_FEATURE,-)-from ..core.fields import JSONString-from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation-from ..core.types import NonNullList, WebhookDryRunError, WebhookError-from ..core.utils import raise_validation_error-from ..plugins.dataloaders import get_plugin_manager_promise-from . import enums-from .subscription_payload import (- generate_payload_from_subscription,- initialize_request,- validate_query,-)-from .subscription_types import WEBHOOK_TYPES_MAP-from .types import EventDelivery, Webhook-from .utils import get_event_type_from_subscription---class WebhookCreateInput(graphene.InputObjectType):- name = graphene.String(description="The name of the webhook.", required=False)- target_url = graphene.String(description="The url to receive the payload.")- events = NonNullList(- enums.WebhookEventTypeEnum,- description=(- f"The events that webhook wants to subscribe. {DEPRECATED_IN_3X_INPUT} "- "Use `asyncEvents` or `syncEvents` instead."- ),- )- async_events = NonNullList(- enums.WebhookEventTypeAsyncEnum,- description="The asynchronous events that webhook wants to subscribe.",- )- sync_events = NonNullList(- enums.WebhookEventTypeSyncEnum,- description="The synchronous events that webhook wants to subscribe.",- )- app = graphene.ID(- required=False,- description="ID of the app to which webhook belongs.",- )- is_active = graphene.Boolean(- description="Determine if webhook will be set active or not.", required=False- )- secret_key = graphene.String(- description="The secret key used to create a hash signature with each payload."- f"{DEPRECATED_IN_3X_INPUT} As of Saleor 3.5, webhook payloads default to "- "signing using a verifiable JWS.",- required=False,- )- query = graphene.String(- description="Subscription query used to define a webhook payload."- + ADDED_IN_32- + PREVIEW_FEATURE,- required=False,- )---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`.- events = data.get("events", [])- if not events:- events += data.pop("async_events", [])- events += data.pop("sync_events", [])- data["events"] = events- return data---class WebhookCreate(ModelMutation):- class Arguments:- input = WebhookCreateInput(- description="Fields required to create a webhook.", required=True- )-- class Meta:- description = "Creates a new webhook subscription."- model = models.Webhook- object_type = Webhook- permissions = (- AppPermission.MANAGE_APPS,- AuthorizationFilters.AUTHENTICATED_APP,- )- error_type_class = WebhookError- error_type_field = "webhook_errors"-- @classmethod- def clean_input(cls, info: ResolveInfo, instance, data, **kwargs):- cleaned_data = super().clean_input(info, instance, data, **kwargs)- app = cleaned_data.get("app")-- # We are not able to check it in `check_permission`.- # We need to confirm that cleaned_data has app_id or- # context has assigned app instance- 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-- @classmethod- def get_instance(cls, info: ResolveInfo, **data):- instance = super().get_instance(info, **data)- app = get_app_promise(info.context).get()- instance.app = app- return instance-- @classmethod- def save(cls, _info: ResolveInfo, instance, cleaned_input):- instance.save()- events = set(cleaned_input.get("events", []))- models.WebhookEvent.objects.bulk_create(- [- models.WebhookEvent(webhook=instance, event_type=event)- for event in events- ]- )---class WebhookUpdateInput(graphene.InputObjectType):- name = graphene.String(description="The new name of the webhook.", required=False)- target_url = graphene.String(- description="The url to receive the payload.", required=False- )- events = NonNullList(- enums.WebhookEventTypeEnum,- description=(- f"The events that webhook wants to subscribe. {DEPRECATED_IN_3X_INPUT} "- "Use `asyncEvents` or `syncEvents` instead."- ),- required=False,- )- async_events = NonNullList(- enums.WebhookEventTypeAsyncEnum,- description="The asynchronous events that webhook wants to subscribe.",- required=False,- )- sync_events = NonNullList(- enums.WebhookEventTypeSyncEnum,- description="The synchronous events that webhook wants to subscribe.",- required=False,- )- app = graphene.ID(- required=False,- description="ID of the app to which webhook belongs.",- )- is_active = graphene.Boolean(- description="Determine if webhook will be set active or not.", required=False- )- secret_key = graphene.String(- description="Use to create a hash signature with each payload."- f"{DEPRECATED_IN_3X_INPUT} As of Saleor 3.5, webhook payloads default to "- "signing using a verifiable JWS.",- required=False,- )- query = graphene.String(- description="Subscription query used to define a webhook payload."- + ADDED_IN_32- + PREVIEW_FEATURE,- required=False,- )---class WebhookUpdate(ModelMutation):- class Arguments:- id = graphene.ID(required=True, description="ID of a webhook to update.")- input = WebhookUpdateInput(- description="Fields required to update a webhook.", required=True- )-- class Meta:- description = "Updates a webhook subscription."- model = models.Webhook- object_type = Webhook- permissions = (AppPermission.MANAGE_APPS,)- error_type_class = WebhookError- error_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-- @classmethod- def save(cls, _info: ResolveInfo, instance, cleaned_input):- instance.save()- events = set(cleaned_input.get("events", []))- if events:- instance.events.all().delete()- models.WebhookEvent.objects.bulk_create(- [- models.WebhookEvent(webhook=instance, event_type=event)- for event in events- ]- )---class WebhookDelete(ModelDeleteMutation):- class Arguments:- id = graphene.ID(required=True, description="ID of a webhook to delete.")-- class Meta:- description = (- "Delete a webhook. Before the deletion, the webhook is deactivated to "- "pause any deliveries that are already scheduled. The deletion might fail "- "if delivery is in progress. In such a case, the webhook is not deleted "- "but remains deactivated."- )- model = models.Webhook- object_type = Webhook- permissions = (- AppPermission.MANAGE_APPS,- AuthorizationFilters.AUTHENTICATED_APP,- )- error_type_class = WebhookError- error_type_field = "webhook_errors"-- @classmethod- def perform_mutation(cls, _root, info: ResolveInfo, /, **data):- app = get_app_promise(info.context).get()- node_id: str = data["id"]- if app and not app.is_active:- raise ValidationError(- "App needs to be active to delete webhook",- code=WebhookErrorCode.INVALID.value,- )- webhook = cls.get_node_or_error(info, node_id, only_type=Webhook)- if app and webhook.app_id != app.id:- raise ValidationError(- f"Couldn't resolve to a node: {node_id}",- code=WebhookErrorCode.GRAPHQL_ERROR.value,- )- webhook.is_active = False- webhook.save(update_fields=["is_active"])-- try:- response = super().perform_mutation(_root, info, **data)- except IntegrityError:- raise ValidationError(- "Webhook couldn't be deleted at this time due to running task."- "Webhook deactivated. Try deleting Webhook later",- code=WebhookErrorCode.DELETE_FAILED.value,- )-- return response---class EventDeliveryRetry(BaseMutation):- delivery = graphene.Field(EventDelivery, description="Event delivery.")-- class Arguments:- id = graphene.ID(- required=True, description="ID of the event delivery to retry."- )-- class Meta:- description = "Retries event delivery."- permissions = (AppPermission.MANAGE_APPS,)- error_type_class = WebhookError-- @classmethod- def perform_mutation(cls, _root, info: ResolveInfo, **data):- delivery = cls.get_node_or_error(- info,- data["id"],- only_type=EventDelivery,- )- manager = get_plugin_manager_promise(info.context).get()- manager.event_delivery_retry(delivery)- return EventDeliveryRetry(delivery=delivery)---class WebhookDryRun(BaseMutation):- payload = JSONString(- description="JSON payload, that would be sent out to webhook's target URL."- )-- class Arguments:- query = graphene.String(- description="The subscription query that defines the webhook event and its "- "payload.",- required=True,- )- object_id = graphene.ID(- description="The ID of an object to serialize.", required=True- )-- class Meta:- description = (- "Performs a dry run of a webhook event. "- "Supports a single event (the first if multiple provided in the `query`). "- "Requires permission relevant to processed event."- + ADDED_IN_310- + PREVIEW_FEATURE- )- permissions = (AuthorizationFilters.AUTHENTICATED_STAFF_USER,)- error_type_class = WebhookDryRunError-- @classmethod- def validate_input(cls, info, **data):- query = data.get("query")- object_id = data.get("object_id")-- event_type = get_event_type_from_subscription(query) if query else None- if not event_type:- raise_validation_error(- field="query",- message="Can't parse an event type from query.",- code=WebhookDryRunErrorCode.UNABLE_TO_PARSE,- )-- 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,- )-- 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]-- if not (model_name or enable_dry_run) 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} not supported.",- code=WebhookDryRunErrorCode.TYPE_NOT_SUPPORTED,- )- if model != model_name:- raise_validation_error(- field="objectId",- message="ObjectId doesn't match event type.",- code=WebhookDryRunErrorCode.INVALID_ID,- )-- object = cls.get_node_or_error(info, object_id, field="objectId")-- if (- permission := WebhookEventAsyncType.PERMISSIONS.get(event_type)- if event_type- else None- ):-- codename = permission.value.split(".")[1]- user_permissions = [- perm.codename for perm in info.context.user.effective_permissions.all()- ]- if codename not in user_permissions:- raise_validation_error(- message=f"The user doesn't have required permission: {codename}.",- code=WebhookDryRunErrorCode.MISSING_PERMISSION,- )-- return event_type, object, query-- @classmethod- def perform_mutation(cls, _root, info, **data):- event_type, object, query = cls.validate_input(info, **data)- payload = None- if all([event_type, object, query]):- request = initialize_request()- payload = generate_payload_from_subscription(- event_type, object, query, request- )- return WebhookDryRun(payload=payload)diff --git a/saleor/graphql/webhook/mutations/__init__.py b/saleor/graphql/webhook/mutations/__init__.pynew file mode 100644index 0000000000..5ff5fe1664--- /dev/null+++ b/saleor/graphql/webhook/mutations/__init__.py@@ -0,0 +1,15 @@+from .event_delivery_retry import EventDeliveryRetry+from .webhook_create import WebhookCreate+from .webhook_delete import WebhookDelete+from .webhook_dry_run import WebhookDryRun+from .webhook_trigger import WebhookTrigger+from .webhook_update import WebhookUpdate++__all__ = [+ "EventDeliveryRetry",+ "WebhookCreate",+ "WebhookDelete",+ "WebhookDryRun",+ "WebhookTrigger",+ "WebhookUpdate",+]diff --git a/saleor/graphql/webhook/mutations/event_delivery_retry.py b/saleor/graphql/webhook/mutations/event_delivery_retry.pynew file mode 100644index 0000000000..6848d48404--- /dev/null+++ b/saleor/graphql/webhook/mutations/event_delivery_retry.py@@ -0,0 +1,33 @@+import graphene++from ....permission.enums import AppPermission+from ...core import ResolveInfo+from ...core.mutations import BaseMutation+from ...core.types import WebhookError+from ...plugins.dataloaders import get_plugin_manager_promise+from ..types import EventDelivery+++class EventDeliveryRetry(BaseMutation):+ delivery = graphene.Field(EventDelivery, description="Event delivery.")++ class Arguments:+ id = graphene.ID(+ required=True, description="ID of the event delivery to retry."+ )++ class Meta:+ description = "Retries event delivery."+ permissions = (AppPermission.MANAGE_APPS,)+ error_type_class = WebhookError++ @classmethod+ def perform_mutation(cls, _root, info: ResolveInfo, **data):+ delivery = cls.get_node_or_error(+ info,+ data["id"],+ only_type=EventDelivery,+ )+ manager = get_plugin_manager_promise(info.context).get()+ manager.event_delivery_retry(delivery)+ return EventDeliveryRetry(delivery=delivery)diff --git a/saleor/graphql/webhook/mutations/webhook_create.py b/saleor/graphql/webhook/mutations/webhook_create.pynew file mode 100644index 0000000000..ed4b708267--- /dev/null+++ b/saleor/graphql/webhook/mutations/webhook_create.py@@ -0,0 +1,138 @@+import graphene+from django.core.exceptions import ValidationError++from ....permission.auth_filters import AuthorizationFilters+from ....permission.enums import AppPermission+from ....webhook import models+from ....webhook.error_codes import WebhookErrorCode+from ...app.dataloaders import get_app_promise+from ...core import ResolveInfo+from ...core.descriptions import ADDED_IN_32, DEPRECATED_IN_3X_INPUT, PREVIEW_FEATURE+from ...core.mutations import ModelMutation+from ...core.types import NonNullList, WebhookError+from .. import enums+from ..subscription_payload import validate_query+from ..types import Webhook+from ..utils import get_event_type_from_subscription+++class WebhookCreateInput(graphene.InputObjectType):+ name = graphene.String(description="The name of the webhook.", required=False)+ target_url = graphene.String(description="The url to receive the payload.")+ events = NonNullList(+ enums.WebhookEventTypeEnum,+ description=(+ f"The events that webhook wants to subscribe. {DEPRECATED_IN_3X_INPUT} "+ "Use `asyncEvents` or `syncEvents` instead."+ ),+ )+ async_events = NonNullList(+ enums.WebhookEventTypeAsyncEnum,+ description="The asynchronous events that webhook wants to subscribe.",+ )+ sync_events = NonNullList(+ enums.WebhookEventTypeSyncEnum,+ description="The synchronous events that webhook wants to subscribe.",+ )+ app = graphene.ID(+ required=False,+ description="ID of the app to which webhook belongs.",+ )+ is_active = graphene.Boolean(+ description="Determine if webhook will be set active or not.", required=False+ )+ secret_key = graphene.String(+ description="The secret key used to create a hash signature with each payload."+ f"{DEPRECATED_IN_3X_INPUT} As of Saleor 3.5, webhook payloads default to "+ "signing using a verifiable JWS.",+ required=False,+ )+ query = graphene.String(+ description="Subscription query used to define a webhook payload."+ + ADDED_IN_32+ + PREVIEW_FEATURE,+ required=False,+ )+++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(+ description="Fields required to create a webhook.", required=True+ )++ class Meta:+ description = "Creates a new webhook subscription."+ model = models.Webhook+ object_type = Webhook+ permissions = (+ AppPermission.MANAGE_APPS,+ AuthorizationFilters.AUTHENTICATED_APP,+ )+ error_type_class = WebhookError+ error_type_field = "webhook_errors"++ @classmethod+ def clean_input(cls, info: ResolveInfo, instance, data, **kwargs):+ cleaned_data = super().clean_input(info, instance, data, **kwargs)+ app = cleaned_data.get("app")++ # We are not able to check it in `check_permission`.+ # We need to confirm that cleaned_data has app_id or+ # context has assigned app instance+ 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++ @classmethod+ def get_instance(cls, info: ResolveInfo, **data):+ instance = super().get_instance(info, **data)+ app = get_app_promise(info.context).get()+ instance.app = app+ return instance++ @classmethod+ def save(cls, _info: ResolveInfo, instance, cleaned_input):+ instance.save()+ events = set(cleaned_input.get("events", []))+ models.WebhookEvent.objects.bulk_create(+ [+ models.WebhookEvent(webhook=instance, event_type=event)+ for event in events+ ]+ )diff --git a/saleor/graphql/webhook/mutations/webhook_delete.py b/saleor/graphql/webhook/mutations/webhook_delete.pynew file mode 100644index 0000000000..ba3a9f6ef9--- /dev/null+++ b/saleor/graphql/webhook/mutations/webhook_delete.py@@ -0,0 +1,63 @@+import graphene+from django.core.exceptions import ValidationError+from django.db import IntegrityError++from ....permission.auth_filters import AuthorizationFilters+from ....permission.enums import AppPermission+from ....webhook import models+from ....webhook.error_codes import WebhookErrorCode+from ...app.dataloaders import get_app_promise+from ...core import ResolveInfo+from ...core.mutations import ModelDeleteMutation+from ...core.types import WebhookError+from ..types import Webhook+++class WebhookDelete(ModelDeleteMutation):+ class Arguments:+ id = graphene.ID(required=True, description="ID of a webhook to delete.")++ class Meta:+ description = (+ "Delete a webhook. Before the deletion, the webhook is deactivated to "+ "pause any deliveries that are already scheduled. The deletion might fail "+ "if delivery is in progress. In such a case, the webhook is not deleted "+ "but remains deactivated."+ )+ model = models.Webhook+ object_type = Webhook+ permissions = (+ AppPermission.MANAGE_APPS,+ AuthorizationFilters.AUTHENTICATED_APP,+ )+ error_type_class = WebhookError+ error_type_field = "webhook_errors"++ @classmethod+ def perform_mutation(cls, _root, info: ResolveInfo, /, **data):+ app = get_app_promise(info.context).get()+ node_id: str = data["id"]+ if app and not app.is_active:+ raise ValidationError(+ "App needs to be active to delete webhook",+ code=WebhookErrorCode.INVALID.value,+ )+ webhook = cls.get_node_or_error(info, node_id, only_type=Webhook)+ if app and webhook.app_id != app.id:+ raise ValidationError(+ f"Couldn't resolve to a node: {node_id}",+ code=WebhookErrorCode.GRAPHQL_ERROR.value,+ )+ webhook.is_active = False+ webhook.save(update_fields=["is_active"])++ try:+ response = super().perform_mutation(_root, info, **data)+ except IntegrityError:+ raise ValidationError(+ "Webhook couldn't be deleted at this time due to running task."+ "Webhook deactivated. Try deleting Webhook later",+ code=WebhookErrorCode.DELETE_FAILED.value,+ )++ return responsediff --git a/saleor/graphql/webhook/mutations/webhook_dry_run.py b/saleor/graphql/webhook/mutations/webhook_dry_run.pynew file mode 100644index 0000000000..293707c2e5--- /dev/null+++ b/saleor/graphql/webhook/mutations/webhook_dry_run.py@@ -0,0 +1,126 @@+import graphene+from graphene.utils.str_converters import to_camel_case++from ....permission.auth_filters import AuthorizationFilters+from ....webhook.error_codes import WebhookDryRunErrorCode+from ....webhook.event_types import WebhookEventAsyncType+from ...core.descriptions import ADDED_IN_311, PREVIEW_FEATURE+from ...core.fields import JSONString+from ...core.mutations import BaseMutation+from ...core.types import WebhookDryRunError+from ...core.utils import raise_validation_error+from ..subscription_payload import (+ generate_payload_from_subscription,+ initialize_request,+)+from ..subscription_types import WEBHOOK_TYPES_MAP+from ..utils import get_event_type_from_subscription+++class WebhookDryRun(BaseMutation):+ payload = JSONString(+ description="JSON payload, that would be sent out to webhook's target URL."+ )++ class Arguments:+ query = graphene.String(+ description="The subscription query that defines the webhook event and its "+ "payload.",+ required=True,+ )+ object_id = graphene.ID(+ description="The ID of an object to serialize.", required=True+ )++ class Meta:+ description = (+ "Performs a dry run of a webhook event. "+ "Supports a single event (the first, if multiple provided in the `query`). "+ "Requires permission relevant to processed event."+ + ADDED_IN_311+ + PREVIEW_FEATURE+ )+ permissions = (AuthorizationFilters.AUTHENTICATED_STAFF_USER,)+ error_type_class = WebhookDryRunError++ @classmethod+ def 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:+ raise_validation_error(+ field="query",+ message="Can't parse an event type from query.",+ code=WebhookDryRunErrorCode.UNABLE_TO_PARSE,+ )+ return event_type++ @classmethod+ def 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,+ )++ 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]++ if not (model_name or enable_dry_run) 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} not supported.",+ code=WebhookDryRunErrorCode.TYPE_NOT_SUPPORTED,+ )+ if model != model_name:+ raise_validation_error(+ field="objectId",+ message="ObjectId doesn't match event type.",+ code=WebhookDryRunErrorCode.INVALID_ID,+ )++ @classmethod+ def validate_permissions(cls, info, event_type):+ if (+ permission := WebhookEventAsyncType.PERMISSIONS.get(event_type)+ if event_type+ else None+ ):+ codename = permission.value.split(".")[1]+ user_permissions = [+ perm.codename for perm in info.context.user.effective_permissions.all()+ ]+ if codename not in user_permissions:+ raise_validation_error(+ message=f"The user doesn't have required permission: {codename}.",+ code=WebhookDryRunErrorCode.MISSING_PERMISSION,+ )++ @classmethod+ def validate_input(cls, info, **data):+ query = data.get("query")+ object_id = data.get("object_id")++ event_type = cls.validate_query(query)+ cls.validate_event_type(event_type, object_id)+ cls.validate_permissions(info, event_type)++ object = cls.get_node_or_error(info, object_id, field="objectId")++ return event_type, object, query++ @classmethod+ def perform_mutation(cls, _root, info, **data):+ event_type, object, query = cls.validate_input(info, **data)+ payload = None+ if all([event_type, object, query]):+ request = initialize_request()+ payload = generate_payload_from_subscription(+ event_type, object, query, request+ )+ return WebhookDryRun(payload=payload)diff --git a/saleor/graphql/webhook/mutations/webhook_trigger.py b/saleor/graphql/webhook/mutations/webhook_trigger.pynew file mode 100644index 0000000000..e49922b3e0--- /dev/null+++ b/saleor/graphql/webhook/mutations/webhook_trigger.py@@ -0,0 +1,141 @@+import graphene+from celery.exceptions import Retry+from graphene.utils.str_converters import to_camel_case++from ....core import EventDeliveryStatus+from ....permission.auth_filters import AuthorizationFilters+from ....webhook.error_codes import WebhookTriggerErrorCode+from ....webhook.event_types import WebhookEventAsyncType+from ...core.descriptions import ADDED_IN_311, PREVIEW_FEATURE+from ...core.mutations import BaseMutation+from ...core.types.common import WebhookTriggerError+from ...core.utils import raise_validation_error+from ..subscription_types import WEBHOOK_TYPES_MAP+from ..types import EventDelivery+from ..utils import get_event_type_from_subscription+++class WebhookTrigger(BaseMutation):+ delivery = graphene.Field(EventDelivery)++ class Arguments:+ webhook_id = graphene.ID(description="The ID of the webhook.", required=True)+ object_id = graphene.ID(+ description="The ID of an object to serialize.", required=True+ )++ class Meta:+ description = (+ "Trigger a webhook event. Supports a single event (the first, if multiple "+ "provided in the `webhook.subscription_query`). Requires permission "+ "relevant to processed event. Successfully delivered webhook returns "+ "`delivery` with status='PENDING' and empty payload."+ + ADDED_IN_311+ + PREVIEW_FEATURE+ )+ permissions = (AuthorizationFilters.AUTHENTICATED_STAFF_USER,)+ error_type_class = WebhookTriggerError++ @classmethod+ def validate_subscription_query(cls, webhook):+ query = getattr(webhook, "subscription_query")+ if not query:+ raise_validation_error(+ field="webhookId",+ message="Missing subscription query for given webhook.",+ code=WebhookTriggerErrorCode.MISSING_QUERY,+ )++ event_types = get_event_type_from_subscription(query)+ if not event_types:+ raise_validation_error(+ message="Can't parse an event type from webhook's subscription query.",+ code=WebhookTriggerErrorCode.UNABLE_TO_PARSE,+ )+ event_type = event_types[0] if event_types else None+ return event_type++ @classmethod+ def 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,+ )++ 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]++ if not (model_name or enable_dry_run) 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 supported.",+ code=WebhookTriggerErrorCode.TYPE_NOT_SUPPORTED,+ )+ if model != model_name:+ raise_validation_error(+ field="objectId",+ message="ObjectId doesn't match event type.",+ code=WebhookTriggerErrorCode.INVALID_ID,+ )++ @classmethod+ def validate_permissions(cls, info, event_type):+ if (+ permission := WebhookEventAsyncType.PERMISSIONS.get(event_type)+ if event_type+ else None+ ):+ codename = permission.value.split(".")[1]+ user_permissions = [+ perm.codename for perm in info.context.user.effective_permissions.all()+ ]+ if codename not in user_permissions:+ raise_validation_error(+ message=f"The user doesn't have required permission: {codename}.",+ code=WebhookTriggerErrorCode.MISSING_PERMISSION,+ )++ @classmethod+ def validate_input(cls, info, **data):+ object_id = data.get("object_id")+ webhook_id = data.get("webhook_id")+ webhook = cls.get_node_or_error(info, webhook_id, field="webhookId")++ event_type = cls.validate_subscription_query(webhook)+ cls.validate_event_type(event_type, object_id)+ cls.validate_permissions(info, event_type)++ object = cls.get_node_or_error(info, object_id, field="objectId")++ return event_type, object, webhook++ @classmethod+ def perform_mutation(cls, _root, info, **data):+ from ....plugins.webhook.tasks import (+ create_deliveries_for_subscriptions,+ send_webhook_request_async,+ )++ event_type, object, webhook = cls.validate_input(info, **data)+ delivery = None++ if all([event_type, object, webhook]):+ deliveries = create_deliveries_for_subscriptions(+ event_type, object, [webhook]+ )+ if deliveries:+ delivery = deliveries[0]+ try:+ send_webhook_request_async(delivery.id)+ return WebhookTrigger(delivery=delivery)+ except Retry:+ delivery.status = EventDeliveryStatus.FAILED+ delivery.save(update_fields=["status"])++ return WebhookTrigger(delivery=delivery)diff --git a/saleor/graphql/webhook/mutations/webhook_update.py b/saleor/graphql/webhook/mutations/webhook_update.pynew file mode 100644index 0000000000..edd67edba8--- /dev/null+++ b/saleor/graphql/webhook/mutations/webhook_update.py@@ -0,0 +1,115 @@+import graphene+from django.core.exceptions import ValidationError++from ....permission.enums import AppPermission+from ....webhook import models+from ....webhook.error_codes import WebhookErrorCode+from ...core import ResolveInfo+from ...core.descriptions import ADDED_IN_32, DEPRECATED_IN_3X_INPUT, PREVIEW_FEATURE+from ...core.mutations import ModelMutation+from ...core.types import NonNullList, WebhookError+from .. import enums+from ..subscription_payload import validate_query+from ..types import Webhook+from .webhook_create import clean_webhook_events+++class WebhookUpdateInput(graphene.InputObjectType):+ name = graphene.String(description="The new name of the webhook.", required=False)+ target_url = graphene.String(+ description="The url to receive the payload.", required=False+ )+ events = NonNullList(+ enums.WebhookEventTypeEnum,+ description=(+ f"The events that webhook wants to subscribe. {DEPRECATED_IN_3X_INPUT} "+ "Use `asyncEvents` or `syncEvents` instead."+ ),+ required=False,+ )+ async_events = NonNullList(+ enums.WebhookEventTypeAsyncEnum,+ description="The asynchronous events that webhook wants to subscribe.",+ required=False,+ )+ sync_events = NonNullList(+ enums.WebhookEventTypeSyncEnum,+ description="The synchronous events that webhook wants to subscribe.",+ required=False,+ )+ app = graphene.ID(+ required=False,+ description="ID of the app to which webhook belongs.",+ )+ is_active = graphene.Boolean(+ description="Determine if webhook will be set active or not.", required=False+ )+ secret_key = graphene.String(+ description="Use to create a hash signature with each payload."+ f"{DEPRECATED_IN_3X_INPUT} As of Saleor 3.5, webhook payloads default to "+ "signing using a verifiable JWS.",+ required=False,+ )+ query = graphene.String(+ description="Subscription query used to define a webhook payload."+ + ADDED_IN_32+ + PREVIEW_FEATURE,+ required=False,+ )+++class WebhookUpdate(ModelMutation):+ class Arguments:+ id = graphene.ID(required=True, description="ID of a webhook to update.")+ input = WebhookUpdateInput(+ description="Fields required to update a webhook.", required=True+ )++ class Meta:+ description = "Updates a webhook subscription."+ model = models.Webhook+ object_type = Webhook+ permissions = (AppPermission.MANAGE_APPS,)+ error_type_class = WebhookError+ error_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++ @classmethod+ def save(cls, _info: ResolveInfo, instance, cleaned_input):+ instance.save()+ events = set(cleaned_input.get("events", []))+ if events:+ instance.events.all().delete()+ models.WebhookEvent.objects.bulk_create(+ [+ models.WebhookEvent(webhook=instance, event_type=event)+ for event in events+ ]+ )diff --git a/saleor/graphql/webhook/schema.py b/saleor/graphql/webhook/schema.pyindex 288aa06544..d5e73670b7 100644--- a/saleor/graphql/webhook/schema.py+++ b/saleor/graphql/webhook/schema.py@@ -13,6 +13,7 @@ from .mutations import (WebhookCreate,WebhookDelete,WebhookDryRun,+ WebhookTrigger,WebhookUpdate,)from .resolvers import resolve_sample_payload, resolve_webhook, resolve_webhook_events@@ -73,3 +74,4 @@ class WebhookMutations(graphene.ObjectType):webhook_update = WebhookUpdate.Field()event_delivery_retry = EventDeliveryRetry.Field()webhook_dry_run = WebhookDryRun.Field()+ webhook_trigger = WebhookTrigger.Field()diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_create.py b/saleor/graphql/webhook/tests/mutations/test_webhook_create.pynew file mode 100644index 0000000000..08388514b5--- /dev/null+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_create.py@@ -0,0 +1,264 @@+import graphene++from .....webhook.models import Webhook+from ....tests.utils import assert_no_permission, get_graphql_content+from ...enums import WebhookEventTypeAsyncEnum, WebhookEventTypeSyncEnum++WEBHOOK_CREATE = """+ mutation webhookCreate($input: WebhookCreateInput!){+ webhookCreate(input: $input) {+ errors {+ field+ message+ }+ webhook {+ id+ }+ }+ }+"""+++def test_webhook_create_by_app(app_api_client, permission_manage_orders):+ query = WEBHOOK_CREATE+ variables = {+ "input": {+ "name": "New integration",+ "targetUrl": "https://www.example.com",+ "asyncEvents": [+ WebhookEventTypeAsyncEnum.ORDER_CREATED.name,+ WebhookEventTypeAsyncEnum.ORDER_CREATED.name,+ ],+ }+ }+ response = app_api_client.post_graphql(+ query,+ variables=variables,+ permissions=[permission_manage_orders],+ check_no_permissions=False,+ )+ get_graphql_content(response)+ new_webhook = Webhook.objects.get()+ assert new_webhook.name == "New integration"+ assert new_webhook.target_url == "https://www.example.com"+ events = new_webhook.events.all()+ assert len(events) == 1+ assert events[0].event_type == WebhookEventTypeAsyncEnum.ORDER_CREATED.value+++def test_webhook_create_inactive_app(app_api_client, app, permission_manage_orders):+ app.is_active = False+ app.save()+ query = WEBHOOK_CREATE+ variables = {+ "input": {+ "targetUrl": "https://www.example.com",+ "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],+ "name": "",+ }+ }++ response = app_api_client.post_graphql(+ query, variables=variables, permissions=[permission_manage_orders]+ )+ assert_no_permission(response)+++def test_webhook_create_without_app(app_api_client, app):+ app_api_client.app = None+ app_api_client.app_token = None+ query = WEBHOOK_CREATE+ variables = {+ "input": {+ "targetUrl": "https://www.example.com",+ "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],+ "name": "",+ }+ }+ response = app_api_client.post_graphql(query, variables=variables)+ assert_no_permission(response)+++def test_webhook_create_app_doesnt_exist(app_api_client, app):+ app.delete()++ query = WEBHOOK_CREATE+ variables = {+ "input": {+ "targetUrl": "https://www.example.com",+ "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],+ "name": "",+ }+ }+ response = app_api_client.post_graphql(query, variables=variables)+ assert_no_permission(response)+++def test_webhook_create_by_staff(+ staff_api_client,+ app,+ permission_manage_apps,+ permission_manage_orders,+):+ query = WEBHOOK_CREATE+ app.permissions.add(permission_manage_orders)+ app_id = graphene.Node.to_global_id("App", app.pk)+ variables = {+ "input": {+ "targetUrl": "https://www.example.com",+ "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],+ "syncEvents": [WebhookEventTypeSyncEnum.PAYMENT_LIST_GATEWAYS.name],+ "app": app_id,+ }+ }+ staff_api_client.user.user_permissions.add(permission_manage_apps)+ response = staff_api_client.post_graphql(query, variables=variables)+ get_graphql_content(response)+ 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 = [events[0].event_type, events[1].event_type]+ assert WebhookEventTypeAsyncEnum.ORDER_CREATED.value in created_event_types+ assert WebhookEventTypeSyncEnum.PAYMENT_LIST_GATEWAYS.value in created_event_types+++def test_webhook_create_by_staff_with_inactive_app(staff_api_client, app):+ app.is_active = False+ query = WEBHOOK_CREATE+ app_id = graphene.Node.to_global_id("App", app.pk)+ variables = {+ "input": {+ "targetUrl": "https://www.example.com",+ "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],+ "app": app_id,+ }+ }+ response = staff_api_client.post_graphql(query, variables=variables)+ assert_no_permission(response)+ assert Webhook.objects.count() == 0+++def test_webhook_create_by_staff_without_permission(staff_api_client, app):+ query = WEBHOOK_CREATE+ app_id = graphene.Node.to_global_id("App", app.pk)+ variables = {+ "input": {+ "targetUrl": "https://www.example.com",+ "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],+ "app": app_id,+ }+ }+ response = staff_api_client.post_graphql(query, variables=variables)+ assert_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+):+ # given+ query = WEBHOOK_CREATE+ subscription_query = subscription_order_created_webhook.subscription_query+ variables = {+ "input": {+ "name": "New integration",+ "targetUrl": "https://www.example.com",+ "query": subscription_query,+ }+ }++ # when+ response = app_api_client.post_graphql(+ query,+ variables=variables,+ permissions=[permission_manage_orders],+ check_no_permissions=False,+ )+ content = get_graphql_content(response)++ # then+ data = 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+++SUBSCRIPTION_QUERY_WITH_MULTIPLE_LVL_FIELDS = """+subscription {+ event {+ ... on PaymentListGateways {+ checkout {+ id+ }+ }+ }+ ... on CheckoutFilterShippingMethods {+ checkout {+ id+ }+ shippingMethods {+ name+ id+ }+ }+}"""+++def test_webhook_create_by_staff_invalid_query_multiple_level_fields(+ 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": SUBSCRIPTION_QUERY_WITH_MULTIPLE_LVL_FIELDS,+ }+ }+ 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_errorsdiff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_delete.py b/saleor/graphql/webhook/tests/mutations/test_webhook_delete.pynew file mode 100644index 0000000000..561922d4a9--- /dev/null+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_delete.py@@ -0,0 +1,122 @@+from unittest.mock import Mock, patch++import graphene+from django.db import IntegrityError++from .....app.models import App+from .....webhook.models import Webhook+from ....tests.utils import assert_no_permission, get_graphql_content++WEBHOOK_DELETE_BY_APP = """+ mutation webhookDelete($id: ID!) {+ webhookDelete(id: $id) {+ errors {+ field+ message+ code+ }+ }+ }+"""+++def test_webhook_delete_by_app(app_api_client, webhook):+ query = WEBHOOK_DELETE_BY_APP+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {"id": webhook_id}+ response = app_api_client.post_graphql(query, variables=variables)+ get_graphql_content(response)+ assert Webhook.objects.count() == 0+++def test_webhook_delete_by_app_and_webhook_assigned_to_other_app(+ app_api_client, webhook+):+ second_app = App.objects.create(name="second")+ webhook.app = second_app+ webhook.save()++ query = WEBHOOK_DELETE_BY_APP+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {"id": webhook_id}+ response = app_api_client.post_graphql(query, variables=variables)+ get_graphql_content(response)++ webhook.refresh_from_db()+ assert Webhook.objects.count() == 1+++def test_webhook_delete_by_app_and_missing_webhook(app_api_client, webhook):+ query = WEBHOOK_DELETE_BY_APP+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {"id": webhook_id}+ webhook.delete()++ response = app_api_client.post_graphql(query, variables=variables)+ content = get_graphql_content(response)+ errors = content["data"]["webhookDelete"]["errors"]+ assert errors[0]["code"] == "NOT_FOUND"+++def test_webhook_delete_by_inactive_app(app_api_client, webhook):+ app = webhook.app+ app.is_active = False+ app.save()+ query = WEBHOOK_DELETE_BY_APP+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {"id": webhook_id}+ response = app_api_client.post_graphql(query, variables=variables)+ assert_no_permission(response)+++@patch("saleor.webhook.models.Webhook.delete")+def test_webhook_delete_deactivates_before_deletion(+ mocked_delete, app_api_client, webhook+):+ # given+ query = WEBHOOK_DELETE_BY_APP+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {"id": webhook_id}++ # when+ response = app_api_client.post_graphql(query, variables=variables)+ get_graphql_content(response)++ # then+ webhook.refresh_from_db()+ assert webhook.is_active is False+++@patch("saleor.webhook.models.Webhook.delete")+def test_webhook_delete_raises_integrity_error(mocked_delete, app_api_client, webhook):+ # given+ query = WEBHOOK_DELETE_BY_APP+ mocked_delete.side_effect = IntegrityError(Mock(return_value={"as": "sa"}))+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {"id": webhook_id}++ # when+ response = app_api_client.post_graphql(query, variables=variables)+ content = get_graphql_content(response)++ # then+ webhook.refresh_from_db()+ errors = content["data"]["webhookDelete"]["errors"]+ assert len(errors) == 1+ assert (+ errors[0]["message"] == "Webhook couldn't be deleted at this time due to "+ "running task.Webhook deactivated. "+ "Try deleting Webhook later"+ )+ assert errors[0]["code"] == "DELETE_FAILED"+ assert webhook.is_active is False+++def test_webhook_delete_when_app_doesnt_exist(app_api_client, app):+ app.delete()++ query = WEBHOOK_DELETE_BY_APP+ webhook_id = graphene.Node.to_global_id("Webhook", 1)+ variables = {"id": webhook_id}+ response = app_api_client.post_graphql(query, variables=variables)+ assert_no_permission(response)diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.pyindex 6a8b00b19b..29909baedf 100644--- a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py@@ -7,6 +7,7 @@ import pytestfrom .....graphql.tests.utils import get_graphql_contentfrom .....webhook.error_codes import WebhookDryRunErrorCodefrom .....webhook.event_types import WebhookEventAsyncType+from ....tests.utils import assert_no_permissionfrom ...subscription_types import WEBHOOK_TYPES_MAPWEBHOOK_DRY_RUN_MUTATION = """@@ -72,6 +73,27 @@ def test_webhook_dry_run_missing_user_permission()+def test_webhook_dry_run_staff_user_not_authorized(+ user_api_client,+ permission_manage_orders,+ order,+ subscription_order_created_webhook,+):+ # given+ query = WEBHOOK_DRY_RUN_MUTATION+ user_api_client.user.user_permissions.add(permission_manage_orders)+ order_id = graphene.Node.to_global_id("Order", order.id)+ webhook = subscription_order_created_webhook++ variables = {"objectId": order_id, "query": webhook.subscription_query}++ # when+ response = user_api_client.post_graphql(query, variables)++ # then+ assert_no_permission(response)++def test_webhook_dry_run_non_existing_id(staff_api_client,permission_manage_orders,diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.py b/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.pynew file mode 100644index 0000000000..5dbd6afc0b--- /dev/null+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.py@@ -0,0 +1,317 @@+import json+from unittest import mock++import graphene++from .....core import EventDeliveryStatus+from .....graphql.tests.utils import get_graphql_content+from .....webhook.error_codes import WebhookTriggerErrorCode+from .....webhook.event_types import WebhookEventAsyncType+from ....tests.utils import assert_no_permission++WEBHOOK_TRIGGER_MUTATION = """+ mutation webhookTrigger($webhookId: ID!, $objectId: ID!) {+ webhookTrigger(webhookId: $webhookId, objectId: $objectId) {+ errors {+ field+ code+ message+ }+ delivery {+ status+ eventType+ payload+ }+ }+ }+ """++[email protected]("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")+def test_webhook_trigger_success(+ mock_send_webhook_using_scheme_method,+ staff_api_client,+ permission_manage_orders,+ order,+ subscription_order_created_webhook,+ webhook_response,+):+ # given+ 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)++ mock_send_webhook_using_scheme_method.return_value = webhook_response++ variables = {"webhookId": webhook_id, "objectId": order_id}++ # when+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)++ # then+ data = content["data"]["webhookTrigger"]+ assert data+ assert not data["errors"]+ assert data["delivery"]["status"] == EventDeliveryStatus.PENDING.upper()+ assert data["delivery"]["eventType"] == WebhookEventAsyncType.ORDER_CREATED.upper()+ assert not data["delivery"]["payload"]++[email protected]("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")+def test_webhook_trigger_fail(+ mock_send_webhook_using_scheme_method,+ staff_api_client,+ permission_manage_orders,+ order,+ subscription_order_created_webhook,+ webhook_response_failed,+):+ # given+ 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)++ mock_send_webhook_using_scheme_method.return_value = webhook_response_failed++ variables = {"webhookId": webhook_id, "objectId": order_id}++ # when+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)++ # then+ data = content["data"]["webhookTrigger"]+ assert data+ assert not data["errors"]+ assert data["delivery"]["status"] == EventDeliveryStatus.FAILED.upper()+ assert data["delivery"]["eventType"] == WebhookEventAsyncType.ORDER_CREATED.upper()+ payload = json.loads(data["delivery"]["payload"])+ assert payload["order"]["id"] == order_id++[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async")+def test_webhook_trigger_missing_user_permission(+ mocked_send_webhook_request,+ staff_api_client,+ order,+ subscription_order_created_webhook,+):+ # given+ mocked_send_webhook_request.return_value = None+ query = WEBHOOK_TRIGGER_MUTATION+ 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)++ 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.MISSING_PERMISSION.name+ assert (+ error["message"] == "The user doesn't have required permission: manage_orders."+ )++[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async")+def test_webhook_trigger_staff_user_not_authorized(+ mocked_send_webhook_request,+ user_api_client,+ order,+ subscription_order_created_webhook,+ permission_manage_orders,+):+ # given+ mocked_send_webhook_request.return_value = None+ user_api_client.user.user_permissions.add(permission_manage_orders)+ query = WEBHOOK_TRIGGER_MUTATION+ 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)++ variables = {"webhookId": webhook_id, "objectId": order_id}++ # when+ response = user_api_client.post_graphql(query, variables)++ # then+ assert_no_permission(response)++[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async")+def test_webhook_trigger_missing_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 = None+ 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 error["field"] == "webhookId"+ assert error["code"] == WebhookTriggerErrorCode.MISSING_QUERY.name+ assert error["message"] == "Missing subscription query for given webhook."++[email protected]("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(+ 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(+ "OrderCreated", "UndefinedEvent"+ )+ 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.GRAPHQL_ERROR.name+ assert (+ error["message"]+ == "Event type: UndefinedEvent, which was parsed from webhook's "+ "subscription query, is not defined in graphql schema."+ )++[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async")+def test_webhook_trigger_event_not_supported(+ mocked_send_webhook_request,+ staff_api_client,+ permission_manage_orders,+ order,+ subscription_payment_authorize_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_payment_authorize_webhook+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.id)++ 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.TYPE_NOT_SUPPORTED.name+ assert (+ error["message"]+ == "Event type: PaymentAuthorize, which was parsed from webhook's "+ "subscription query, is not supported."+ )++[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async")+def test_webhook_trigger_object_id_does_not_match_event(+ mocked_send_webhook_request,+ staff_api_client,+ permission_manage_orders,+ product,+ 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)+ product_id = graphene.Node.to_global_id("Product", product.id)+ webhook = subscription_order_created_webhook+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.id)++ variables = {"webhookId": webhook_id, "objectId": product_id}++ # when+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)++ # then+ error = content["data"]["webhookTrigger"]["errors"][0]+ assert error["field"] == "objectId"+ assert error["code"] == WebhookTriggerErrorCode.INVALID_ID.name+ assert error["message"] == "ObjectId doesn't match event type."diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_update.py b/saleor/graphql/webhook/tests/mutations/test_webhook_update.pynew file mode 100644index 0000000000..262c78beb1--- /dev/null+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_update.py@@ -0,0 +1,113 @@+import graphene++from ....tests.utils import assert_no_permission, get_graphql_content+from ...enums import WebhookEventTypeAsyncEnum++WEBHOOK_UPDATE = """+ mutation webhookUpdate ($id: ID!, $input: WebhookUpdateInput!) {+ webhookUpdate(id: $id, input: $input) {+ errors {+ field+ message+ }+ webhook {+ syncEvents {+ eventType+ }+ asyncEvents {+ eventType+ }+ isActive+ }+ }+ }+"""+++def test_webhook_update_not_allowed_by_app(app_api_client, app, webhook):+ query = WEBHOOK_UPDATE+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {+ "id": webhook_id,+ "input": {+ "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],+ "isActive": False,+ },+ }+ response = app_api_client.post_graphql(query, variables=variables)+ assert_no_permission(response)+++def test_webhook_update_by_staff(+ staff_api_client, app, webhook, permission_manage_apps+):+ query = WEBHOOK_UPDATE+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {+ "id": webhook_id,+ "input": {+ "asyncEvents": [+ WebhookEventTypeAsyncEnum.CUSTOMER_CREATED.name,+ WebhookEventTypeAsyncEnum.CUSTOMER_CREATED.name,+ ],+ "isActive": False,+ },+ }+ staff_api_client.user.user_permissions.add(permission_manage_apps)+ response = staff_api_client.post_graphql(query, variables=variables)+ get_graphql_content(response)+ webhook.refresh_from_db()+ assert webhook.is_active is False+ events = webhook.events.all()+ assert len(events) == 1+ assert events[0].event_type == WebhookEventTypeAsyncEnum.CUSTOMER_CREATED.value+++def test_webhook_update_by_staff_without_permission(staff_api_client, app, webhook):+ query = WEBHOOK_UPDATE+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {+ "id": webhook_id,+ "input": {+ "asyncEvents": [+ WebhookEventTypeAsyncEnum.ORDER_CREATED.name,+ WebhookEventTypeAsyncEnum.CUSTOMER_CREATED.name,+ ],+ "isActive": False,+ },+ }+ response = staff_api_client.post_graphql(query, variables=variables)+ assert_no_permission(response)+++def test_webhook_update_inherit_events_from_query(+ staff_api_client,+ app,+ webhook,+ permission_manage_apps,+ subscription_order_updated_webhook,+):+ # given+ query = WEBHOOK_UPDATE+ subscription_query = subscription_order_updated_webhook.subscription_query+ initial_event = webhook.events.all()[0].event_type+ assert WebhookEventTypeAsyncEnum.ORDER_CREATED.value == initial_event++ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {+ "id": webhook_id,+ "input": {"query": subscription_query},+ }+ staff_api_client.user.user_permissions.add(permission_manage_apps)++ # when+ response = staff_api_client.post_graphql(query, variables=variables)+ content = get_graphql_content(response)+ webhook.refresh_from_db()++ # then+ data = content["data"]["webhookUpdate"]+ assert not data["errors"]+ events = webhook.events.all()+ assert len(events) == 1+ assert WebhookEventTypeAsyncEnum.ORDER_UPDATED.value == events[0].event_typediff --git a/saleor/graphql/webhook/tests/queries/test_sample_payload.py b/saleor/graphql/webhook/tests/queries/test_sample_payload.pynew file mode 100644index 0000000000..d75283ed89--- /dev/null+++ b/saleor/graphql/webhook/tests/queries/test_sample_payload.py@@ -0,0 +1,104 @@+from unittest.mock import patch++import pytest++from ....tests.utils import assert_no_permission, get_graphql_content+from ...enums import WebhookSampleEventTypeEnum++SAMPLE_PAYLOAD_QUERY = """+ query webhookSamplePayload($event_type: WebhookSampleEventTypeEnum!) {+ webhookSamplePayload(eventType: $event_type)+ }+"""+++@patch("saleor.graphql.webhook.resolvers.payloads.generate_sample_payload")+ "event_type, has_access",+ [+ (WebhookSampleEventTypeEnum.ORDER_CREATED, True),+ (WebhookSampleEventTypeEnum.ORDER_CREATED, True),+ (WebhookSampleEventTypeEnum.ORDER_FULLY_PAID, True),+ (WebhookSampleEventTypeEnum.ORDER_UPDATED, True),+ (WebhookSampleEventTypeEnum.ORDER_CANCELLED, True),+ (WebhookSampleEventTypeEnum.ORDER_FULFILLED, True),+ (WebhookSampleEventTypeEnum.CUSTOMER_CREATED, False),+ (WebhookSampleEventTypeEnum.PRODUCT_CREATED, False),+ (WebhookSampleEventTypeEnum.PRODUCT_UPDATED, False),+ (WebhookSampleEventTypeEnum.CHECKOUT_CREATED, False),+ (WebhookSampleEventTypeEnum.CHECKOUT_UPDATED, False),+ (WebhookSampleEventTypeEnum.FULFILLMENT_CREATED, True),+ (WebhookSampleEventTypeEnum.FULFILLMENT_CANCELED, True),+ (WebhookSampleEventTypeEnum.PAGE_CREATED, False),+ (WebhookSampleEventTypeEnum.PAGE_UPDATED, False),+ (WebhookSampleEventTypeEnum.PAGE_DELETED, False),+ ],+)+def test_sample_payload_query_by_app(+ mock_generate_sample_payload,+ event_type,+ has_access,+ app_api_client,+ permission_manage_orders,+):++ mock_generate_sample_payload.return_value = {"mocked_response": ""}+ query = SAMPLE_PAYLOAD_QUERY+ variables = {"event_type": event_type.name}+ response = app_api_client.post_graphql(+ query, variables=variables, permissions=[permission_manage_orders]+ )+ if not has_access:+ assert_no_permission(response)+ mock_generate_sample_payload.assert_not_called()+ else:+ get_graphql_content(response)+ mock_generate_sample_payload.assert_called_with(event_type.value)+++@patch("saleor.graphql.webhook.resolvers.payloads.generate_sample_payload")+ "event_type, has_access",+ [+ (WebhookSampleEventTypeEnum.ORDER_CREATED, False),+ (WebhookSampleEventTypeEnum.ORDER_CREATED, False),+ (WebhookSampleEventTypeEnum.ORDER_FULLY_PAID, False),+ (WebhookSampleEventTypeEnum.ORDER_UPDATED, False),+ (WebhookSampleEventTypeEnum.ORDER_CANCELLED, False),+ (WebhookSampleEventTypeEnum.ORDER_FULFILLED, False),+ (WebhookSampleEventTypeEnum.CUSTOMER_CREATED, True),+ (WebhookSampleEventTypeEnum.PRODUCT_CREATED, True),+ (WebhookSampleEventTypeEnum.PRODUCT_UPDATED, True),+ (WebhookSampleEventTypeEnum.CHECKOUT_CREATED, True),+ (WebhookSampleEventTypeEnum.CHECKOUT_UPDATED, True),+ (WebhookSampleEventTypeEnum.FULFILLMENT_CREATED, False),+ (WebhookSampleEventTypeEnum.FULFILLMENT_CANCELED, False),+ (WebhookSampleEventTypeEnum.PAGE_CREATED, True),+ (WebhookSampleEventTypeEnum.PAGE_UPDATED, True),+ (WebhookSampleEventTypeEnum.PAGE_DELETED, True),+ ],+)+def test_sample_payload_query_by_staff(+ mock_generate_sample_payload,+ event_type,+ has_access,+ staff_api_client,+ permission_manage_users,+ permission_manage_products,+ permission_manage_checkouts,+ permission_manage_pages,+):+ mock_generate_sample_payload.return_value = {"mocked_response": ""}+ query = SAMPLE_PAYLOAD_QUERY+ staff_api_client.user.user_permissions.add(permission_manage_users)+ staff_api_client.user.user_permissions.add(permission_manage_products)+ staff_api_client.user.user_permissions.add(permission_manage_checkouts)+ staff_api_client.user.user_permissions.add(permission_manage_pages)+ variables = {"event_type": event_type.name}+ response = staff_api_client.post_graphql(query, variables=variables)+ if not has_access:+ assert_no_permission(response)+ mock_generate_sample_payload.assert_not_called()+ else:+ get_graphql_content(response)+ mock_generate_sample_payload.assert_called_with(event_type.value)diff --git a/saleor/graphql/webhook/tests/queries/test_webhook.py b/saleor/graphql/webhook/tests/queries/test_webhook.pynew file mode 100644index 0000000000..aa0a379b4e--- /dev/null+++ b/saleor/graphql/webhook/tests/queries/test_webhook.py@@ -0,0 +1,169 @@+import graphene++from .....app.models import App+from .....webhook.models import Webhook+from ....tests.utils import (+ assert_no_permission,+ get_graphql_content,+ get_graphql_content_from_response,+)+from ...enums import WebhookEventTypeAsyncEnum, WebhookEventTypeSyncEnum++QUERY_WEBHOOK = """+ query webhook($id: ID!) {+ webhook(id: $id) {+ id+ isActive+ subscriptionQuery+ asyncEvents {+ eventType+ }+ syncEvents {+ eventType+ }+ }+ }+"""+++def test_query_webhook_by_staff(staff_api_client, webhook, permission_manage_apps):+ query = QUERY_WEBHOOK++ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {"id": webhook_id}+ staff_api_client.user.user_permissions.add(permission_manage_apps)+ response = staff_api_client.post_graphql(query, variables=variables)++ content = get_graphql_content(response)+ webhook_response = content["data"]["webhook"]+ assert webhook_response["id"] == webhook_id+ assert webhook_response["isActive"] == webhook.is_active+ assert webhook_response["subscriptionQuery"] is None+ events = webhook.events.all()+ assert len(events) == 1+ assert events[0].event_type == WebhookEventTypeAsyncEnum.ORDER_CREATED.value+++def test_query_webhook_with_subscription_query_by_staff(+ staff_api_client, subscription_order_created_webhook, permission_manage_apps+):+ query = QUERY_WEBHOOK+ webhook = subscription_order_created_webhook+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {"id": webhook_id}+ staff_api_client.user.user_permissions.add(permission_manage_apps)+ response = staff_api_client.post_graphql(query, variables=variables)++ content = get_graphql_content(response)+ webhook_response = content["data"]["webhook"]+ assert webhook_response["id"] == webhook_id+ assert webhook_response["isActive"] == webhook.is_active+ assert webhook_response["subscriptionQuery"] == webhook.subscription_query+ events = webhook.events.all()+ assert len(events) == 1+ assert events[0].event_type == WebhookEventTypeAsyncEnum.ORDER_CREATED.value+++def test_query_webhook_by_staff_without_permission(staff_api_client, webhook):+ query = QUERY_WEBHOOK+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {"id": webhook_id}+ response = staff_api_client.post_graphql(query, variables=variables)+ assert_no_permission(response)+++def test_query_webhook_by_app(app_api_client, webhook):+ query = QUERY_WEBHOOK++ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {"id": webhook_id}+ response = app_api_client.post_graphql(query, variables=variables)++ content = get_graphql_content(response)+ webhook_response = content["data"]["webhook"]+ assert webhook_response["id"] == webhook_id+ assert webhook_response["isActive"] == webhook.is_active+ events = webhook.events.all()+ assert len(events) == 1+ assert events[0].event_type == WebhookEventTypeAsyncEnum.ORDER_CREATED.value+++def test_query_webhook_by_app_without_permission(app_api_client):+ second_app = App.objects.create(name="Sample app account", is_active=True)+ webhook = Webhook.objects.create(+ app=second_app, target_url="http://www.example.com/test"+ )+ webhook.events.create(event_type="order_created")++ query = QUERY_WEBHOOK+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {"id": webhook_id}+ response = app_api_client.post_graphql(query, variables=variables)+ content = get_graphql_content(response)+ webhook_response = content["data"]["webhook"]+ assert webhook_response is None+++def test_query_webhook_sync_and_async_events(+ staff_api_client, webhook, permission_manage_apps+):+ # given+ webhook.events.all().delete()+ webhook.events.create(event_type=WebhookEventTypeAsyncEnum.ORDER_CREATED.value)+ webhook.events.create(+ event_type=WebhookEventTypeSyncEnum.PAYMENT_LIST_GATEWAYS.value+ )+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {"id": webhook_id}+ staff_api_client.user.user_permissions.add(permission_manage_apps)++ # when+ response = staff_api_client.post_graphql(QUERY_WEBHOOK, variables=variables)++ # then+ content = get_graphql_content(response)+ webhook_response = content["data"]["webhook"]++ assert (+ webhook_response["asyncEvents"][0]["eventType"]+ == WebhookEventTypeAsyncEnum.ORDER_CREATED.name+ )+ assert (+ webhook_response["syncEvents"][0]["eventType"]+ == WebhookEventTypeSyncEnum.PAYMENT_LIST_GATEWAYS.name+ )+++def test_webhook_query_invalid_id(staff_api_client, webhook, permission_manage_apps):+ webhook_id = "'"+ staff_api_client.user.user_permissions.add(permission_manage_apps)+ variables = {+ "id": webhook_id,+ }+ response = staff_api_client.post_graphql(QUERY_WEBHOOK, variables)+ content = get_graphql_content_from_response(response)+ assert len(content["errors"]) == 1+ assert content["errors"][0]["message"] == f"Couldn't resolve id: {webhook_id}."+ assert content["data"]["webhook"] is None+++def test_webhook_query_object_with_given_id_does_not_exist(+ staff_api_client, webhook, permission_manage_apps+):+ webhook_id = graphene.Node.to_global_id("Webhook", -1)+ staff_api_client.user.user_permissions.add(permission_manage_apps)+ variables = {"id": webhook_id}+ response = staff_api_client.post_graphql(QUERY_WEBHOOK, variables)+ content = get_graphql_content(response)+ assert content["data"]["webhook"] is None+++def test_webhook_with_invalid_object_type(+ staff_api_client, webhook, permission_manage_apps+):+ webhook_id = graphene.Node.to_global_id("Product", webhook.pk)+ staff_api_client.user.user_permissions.add(permission_manage_apps)+ variables = {"id": webhook_id}+ response = staff_api_client.post_graphql(QUERY_WEBHOOK, variables)+ content = get_graphql_content(response)+ assert content["data"]["webhook"] is Nonediff --git a/saleor/graphql/webhook/tests/test_utils.py b/saleor/graphql/webhook/tests/test_utils.pyindex 55cd65e0b8..91ea2a1014 100644--- a/saleor/graphql/webhook/tests/test_utils.py+++ b/saleor/graphql/webhook/tests/test_utils.py@@ -19,7 +19,7 @@ from ..utils import get_event_type_from_subscription}}""",- "order_created",+ ["order_created"],),("""@@ -40,7 +40,7 @@ from ..utils import get_event_type_from_subscription}}""",- "order_created",+ ["order_created"],),("""@@ -62,7 +62,7 @@ from ..utils import get_event_type_from_subscription}}""",- "order_updated",+ ["order_updated"],),("""@@ -84,7 +84,7 @@ from ..utils import get_event_type_from_subscription}}""",- "order_updated",+ ["order_updated"],),("""@@ -96,7 +96,31 @@ from ..utils import get_event_type_from_subscription}}""",- None,+ [],+ ),+ (+ """+ subscription {+ event{+ ... on OrderCreated{+ order{+ id+ }+ }+ ... on OrderFullyPaid{+ order{+ id+ }+ }+ ... on ProductCreated{+ product{+ id+ }+ }+ }+ }+ """,+ ["order_created", "order_fully_paid", "product_created"],),],)diff --git a/saleor/graphql/webhook/tests/test_webhook.py b/saleor/graphql/webhook/tests/test_webhook.pydeleted file mode 100644index 6df030d23a..0000000000--- a/saleor/graphql/webhook/tests/test_webhook.py+++ /dev/null@@ -1,695 +0,0 @@-from unittest.mock import Mock, patch--import graphene-import pytest-from django.db import IntegrityError--from ....app.models import App-from ....webhook.models import Webhook-from ...tests.utils import (- assert_no_permission,- get_graphql_content,- get_graphql_content_from_response,-)-from ..enums import (- WebhookEventTypeAsyncEnum,- WebhookEventTypeSyncEnum,- WebhookSampleEventTypeEnum,-)--WEBHOOK_CREATE = """- mutation webhookCreate($input: WebhookCreateInput!){- webhookCreate(input: $input) {- errors {- field- message- }- webhook {- id- }- }- }-"""---def test_webhook_create_by_app(app_api_client, permission_manage_orders):- query = WEBHOOK_CREATE- variables = {- "input": {- "name": "New integration",- "targetUrl": "https://www.example.com",- "asyncEvents": [- WebhookEventTypeAsyncEnum.ORDER_CREATED.name,- WebhookEventTypeAsyncEnum.ORDER_CREATED.name,- ],- }- }- response = app_api_client.post_graphql(- query,- variables=variables,- permissions=[permission_manage_orders],- check_no_permissions=False,- )- get_graphql_content(response)- new_webhook = Webhook.objects.get()- assert new_webhook.name == "New integration"- assert new_webhook.target_url == "https://www.example.com"- events = new_webhook.events.all()- assert len(events) == 1- assert events[0].event_type == WebhookEventTypeAsyncEnum.ORDER_CREATED.value---def test_webhook_create_inactive_app(app_api_client, app, permission_manage_orders):- app.is_active = False- app.save()- query = WEBHOOK_CREATE- variables = {- "input": {- "targetUrl": "https://www.example.com",- "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],- "name": "",- }- }-- response = app_api_client.post_graphql(- query, variables=variables, permissions=[permission_manage_orders]- )- assert_no_permission(response)---def test_webhook_create_without_app(app_api_client, app):- app_api_client.app = None- app_api_client.app_token = None- query = WEBHOOK_CREATE- variables = {- "input": {- "targetUrl": "https://www.example.com",- "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],- "name": "",- }- }- response = app_api_client.post_graphql(query, variables=variables)- assert_no_permission(response)---def test_webhook_create_app_doesnt_exist(app_api_client, app):- app.delete()-- query = WEBHOOK_CREATE- variables = {- "input": {- "targetUrl": "https://www.example.com",- "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],- "name": "",- }- }- response = app_api_client.post_graphql(query, variables=variables)- assert_no_permission(response)---def test_webhook_create_by_staff(- staff_api_client,- app,- permission_manage_apps,- permission_manage_orders,-):- query = WEBHOOK_CREATE- app.permissions.add(permission_manage_orders)- app_id = graphene.Node.to_global_id("App", app.pk)- variables = {- "input": {- "targetUrl": "https://www.example.com",- "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],- "syncEvents": [WebhookEventTypeSyncEnum.PAYMENT_LIST_GATEWAYS.name],- "app": app_id,- }- }- staff_api_client.user.user_permissions.add(permission_manage_apps)- response = staff_api_client.post_graphql(query, variables=variables)- get_graphql_content(response)- 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 = [events[0].event_type, events[1].event_type]- assert WebhookEventTypeAsyncEnum.ORDER_CREATED.value in created_event_types- assert WebhookEventTypeSyncEnum.PAYMENT_LIST_GATEWAYS.value in created_event_types---def test_webhook_create_by_staff_with_inactive_app(staff_api_client, app):- app.is_active = False- query = WEBHOOK_CREATE- app_id = graphene.Node.to_global_id("App", app.pk)- variables = {- "input": {- "targetUrl": "https://www.example.com",- "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],- "app": app_id,- }- }- response = staff_api_client.post_graphql(query, variables=variables)- assert_no_permission(response)- assert Webhook.objects.count() == 0---def test_webhook_create_by_staff_without_permission(staff_api_client, app):- query = WEBHOOK_CREATE- app_id = graphene.Node.to_global_id("App", app.pk)- variables = {- "input": {- "targetUrl": "https://www.example.com",- "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],- "app": app_id,- }- }- response = staff_api_client.post_graphql(query, variables=variables)- assert_no_permission(response)- assert Webhook.objects.count() == 0---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---SUBSCRIPTION_QUERY_WITH_MULTIPLE_LVL_FIELDS = """-subscription {- event {- ... on PaymentListGateways {- checkout {- id- }- }- }- ... on CheckoutFilterShippingMethods {- checkout {- id- }- shippingMethods {- name- id- }- }-}"""---def test_webhook_create_by_staff_invalid_query_multiple_level_fields(- 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": SUBSCRIPTION_QUERY_WITH_MULTIPLE_LVL_FIELDS,- }- }- 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---WEBHOOK_DELETE_BY_APP = """- mutation webhookDelete($id: ID!) {- webhookDelete(id: $id) {- errors {- field- message- code- }- }- }-"""---def test_webhook_delete_by_app(app_api_client, webhook):- query = WEBHOOK_DELETE_BY_APP- webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)- variables = {"id": webhook_id}- response = app_api_client.post_graphql(query, variables=variables)- get_graphql_content(response)- assert Webhook.objects.count() == 0---def test_webhook_delete_by_app_and_webhook_assigned_to_other_app(- app_api_client, webhook-):- second_app = App.objects.create(name="second")- webhook.app = second_app- webhook.save()-- query = WEBHOOK_DELETE_BY_APP- webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)- variables = {"id": webhook_id}- response = app_api_client.post_graphql(query, variables=variables)- get_graphql_content(response)-- webhook.refresh_from_db()- assert Webhook.objects.count() == 1---def test_webhook_delete_by_app_and_missing_webhook(app_api_client, webhook):- query = WEBHOOK_DELETE_BY_APP- webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)- variables = {"id": webhook_id}- webhook.delete()-- response = app_api_client.post_graphql(query, variables=variables)- content = get_graphql_content(response)- errors = content["data"]["webhookDelete"]["errors"]- assert errors[0]["code"] == "NOT_FOUND"---def test_webhook_delete_by_inactive_app(app_api_client, webhook):- app = webhook.app- app.is_active = False- app.save()- query = WEBHOOK_DELETE_BY_APP- webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)- variables = {"id": webhook_id}- response = app_api_client.post_graphql(query, variables=variables)- assert_no_permission(response)---@patch("saleor.webhook.models.Webhook.delete")-def test_webhook_delete_deactivates_before_deletion(- mocked_delete, app_api_client, webhook-):- # given- query = WEBHOOK_DELETE_BY_APP- webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)- variables = {"id": webhook_id}-- # when- response = app_api_client.post_graphql(query, variables=variables)- get_graphql_content(response)-- # then- webhook.refresh_from_db()- assert webhook.is_active is False---@patch("saleor.webhook.models.Webhook.delete")-def test_webhook_delete_raises_integrity_error(mocked_delete, app_api_client, webhook):- # given- query = WEBHOOK_DELETE_BY_APP- mocked_delete.side_effect = IntegrityError(Mock(return_value={"as": "sa"}))- webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)- variables = {"id": webhook_id}-- # when- response = app_api_client.post_graphql(query, variables=variables)- content = get_graphql_content(response)-- # then- webhook.refresh_from_db()- errors = content["data"]["webhookDelete"]["errors"]- assert len(errors) == 1- assert (- errors[0]["message"] == "Webhook couldn't be deleted at this time due to "- "running task.Webhook deactivated. "- "Try deleting Webhook later"- )- assert errors[0]["code"] == "DELETE_FAILED"- assert webhook.is_active is False---def test_webhook_delete_when_app_doesnt_exist(app_api_client, app):- app.delete()-- query = WEBHOOK_DELETE_BY_APP- webhook_id = graphene.Node.to_global_id("Webhook", 1)- variables = {"id": webhook_id}- response = app_api_client.post_graphql(query, variables=variables)- assert_no_permission(response)---WEBHOOK_UPDATE = """- mutation webhookUpdate ($id: ID!, $input: WebhookUpdateInput!) {- webhookUpdate(id: $id, input: $input) {- errors {- field- message- }- webhook {- syncEvents {- eventType- }- asyncEvents {- eventType- }- isActive- }- }- }-"""---def test_webhook_update_not_allowed_by_app(app_api_client, app, webhook):- query = WEBHOOK_UPDATE- webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)- variables = {- "id": webhook_id,- "input": {- "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],- "isActive": False,- },- }- response = app_api_client.post_graphql(query, variables=variables)- assert_no_permission(response)---def test_webhook_update_by_staff(- staff_api_client, app, webhook, permission_manage_apps-):- query = WEBHOOK_UPDATE- webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)- variables = {- "id": webhook_id,- "input": {- "asyncEvents": [- WebhookEventTypeAsyncEnum.CUSTOMER_CREATED.name,- WebhookEventTypeAsyncEnum.CUSTOMER_CREATED.name,- ],- "isActive": False,- },- }- staff_api_client.user.user_permissions.add(permission_manage_apps)- response = staff_api_client.post_graphql(query, variables=variables)- get_graphql_content(response)- webhook.refresh_from_db()- assert webhook.is_active is False- events = webhook.events.all()- assert len(events) == 1- assert events[0].event_type == WebhookEventTypeAsyncEnum.CUSTOMER_CREATED.value---def test_webhook_update_by_staff_without_permission(staff_api_client, app, webhook):- query = WEBHOOK_UPDATE- webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)- variables = {- "id": webhook_id,- "input": {- "asyncEvents": [- WebhookEventTypeAsyncEnum.ORDER_CREATED.name,- WebhookEventTypeAsyncEnum.CUSTOMER_CREATED.name,- ],- "isActive": False,- },- }- response = staff_api_client.post_graphql(query, variables=variables)- assert_no_permission(response)---QUERY_WEBHOOK = """- query webhook($id: ID!) {- webhook(id: $id) {- id- isActive- subscriptionQuery- asyncEvents {- eventType- }- syncEvents {- eventType- }- }- }-"""---def test_query_webhook_by_staff(staff_api_client, webhook, permission_manage_apps):- query = QUERY_WEBHOOK-- webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)- variables = {"id": webhook_id}- staff_api_client.user.user_permissions.add(permission_manage_apps)- response = staff_api_client.post_graphql(query, variables=variables)-- content = get_graphql_content(response)- webhook_response = content["data"]["webhook"]- assert webhook_response["id"] == webhook_id- assert webhook_response["isActive"] == webhook.is_active- assert webhook_response["subscriptionQuery"] is None- events = webhook.events.all()- assert len(events) == 1- assert events[0].event_type == WebhookEventTypeAsyncEnum.ORDER_CREATED.value---def test_query_webhook_with_subscription_query_by_staff(- staff_api_client, subscription_order_created_webhook, permission_manage_apps-):- query = QUERY_WEBHOOK- webhook = subscription_order_created_webhook- webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)- variables = {"id": webhook_id}- staff_api_client.user.user_permissions.add(permission_manage_apps)- response = staff_api_client.post_graphql(query, variables=variables)-- content = get_graphql_content(response)- webhook_response = content["data"]["webhook"]- assert webhook_response["id"] == webhook_id- assert webhook_response["isActive"] == webhook.is_active- assert webhook_response["subscriptionQuery"] == webhook.subscription_query- events = webhook.events.all()- assert len(events) == 1- assert events[0].event_type == WebhookEventTypeAsyncEnum.ORDER_CREATED.value---def test_query_webhook_by_staff_without_permission(staff_api_client, webhook):- query = QUERY_WEBHOOK- webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)- variables = {"id": webhook_id}- response = staff_api_client.post_graphql(query, variables=variables)- assert_no_permission(response)---def test_query_webhook_by_app(app_api_client, webhook):- query = QUERY_WEBHOOK-- webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)- variables = {"id": webhook_id}- response = app_api_client.post_graphql(query, variables=variables)-- content = get_graphql_content(response)- webhook_response = content["data"]["webhook"]- assert webhook_response["id"] == webhook_id- assert webhook_response["isActive"] == webhook.is_active- events = webhook.events.all()- assert len(events) == 1- assert events[0].event_type == WebhookEventTypeAsyncEnum.ORDER_CREATED.value---def test_query_webhook_by_app_without_permission(app_api_client):- second_app = App.objects.create(name="Sample app account", is_active=True)- webhook = Webhook.objects.create(- app=second_app, target_url="http://www.example.com/test"- )- webhook.events.create(event_type="order_created")-- query = QUERY_WEBHOOK- webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)- variables = {"id": webhook_id}- response = app_api_client.post_graphql(query, variables=variables)- content = get_graphql_content(response)- webhook_response = content["data"]["webhook"]- assert webhook_response is None---def test_query_webhook_sync_and_async_events(- staff_api_client, webhook, permission_manage_apps-):- # given- webhook.events.all().delete()- webhook.events.create(event_type=WebhookEventTypeAsyncEnum.ORDER_CREATED.value)- webhook.events.create(- event_type=WebhookEventTypeSyncEnum.PAYMENT_LIST_GATEWAYS.value- )- webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)- variables = {"id": webhook_id}- staff_api_client.user.user_permissions.add(permission_manage_apps)-- # when- response = staff_api_client.post_graphql(QUERY_WEBHOOK, variables=variables)-- # then- content = get_graphql_content(response)- webhook_response = content["data"]["webhook"]-- assert (- webhook_response["asyncEvents"][0]["eventType"]- == WebhookEventTypeAsyncEnum.ORDER_CREATED.name- )- assert (- webhook_response["syncEvents"][0]["eventType"]- == WebhookEventTypeSyncEnum.PAYMENT_LIST_GATEWAYS.name- )---def test_webhook_query_invalid_id(staff_api_client, webhook, permission_manage_apps):- webhook_id = "'"- staff_api_client.user.user_permissions.add(permission_manage_apps)- variables = {- "id": webhook_id,- }- response = staff_api_client.post_graphql(QUERY_WEBHOOK, variables)- content = get_graphql_content_from_response(response)- assert len(content["errors"]) == 1- assert content["errors"][0]["message"] == f"Couldn't resolve id: {webhook_id}."- assert content["data"]["webhook"] is None---def test_webhook_query_object_with_given_id_does_not_exist(- staff_api_client, webhook, permission_manage_apps-):- webhook_id = graphene.Node.to_global_id("Webhook", -1)- staff_api_client.user.user_permissions.add(permission_manage_apps)- variables = {"id": webhook_id}- response = staff_api_client.post_graphql(QUERY_WEBHOOK, variables)- content = get_graphql_content(response)- assert content["data"]["webhook"] is None---def test_webhook_with_invalid_object_type(- staff_api_client, webhook, permission_manage_apps-):- webhook_id = graphene.Node.to_global_id("Product", webhook.pk)- staff_api_client.user.user_permissions.add(permission_manage_apps)- variables = {"id": webhook_id}- response = staff_api_client.post_graphql(QUERY_WEBHOOK, variables)- content = get_graphql_content(response)- assert content["data"]["webhook"] is None---SAMPLE_PAYLOAD_QUERY = """- query webhookSamplePayload($event_type: WebhookSampleEventTypeEnum!) {- webhookSamplePayload(eventType: $event_type)- }-"""---@patch("saleor.graphql.webhook.resolvers.payloads.generate_sample_payload")- "event_type, has_access",- [- (WebhookSampleEventTypeEnum.ORDER_CREATED, True),- (WebhookSampleEventTypeEnum.ORDER_CREATED, True),- (WebhookSampleEventTypeEnum.ORDER_FULLY_PAID, True),- (WebhookSampleEventTypeEnum.ORDER_UPDATED, True),- (WebhookSampleEventTypeEnum.ORDER_CANCELLED, True),- (WebhookSampleEventTypeEnum.ORDER_FULFILLED, True),- (WebhookSampleEventTypeEnum.CUSTOMER_CREATED, False),- (WebhookSampleEventTypeEnum.PRODUCT_CREATED, False),- (WebhookSampleEventTypeEnum.PRODUCT_UPDATED, False),- (WebhookSampleEventTypeEnum.CHECKOUT_CREATED, False),- (WebhookSampleEventTypeEnum.CHECKOUT_UPDATED, False),- (WebhookSampleEventTypeEnum.FULFILLMENT_CREATED, True),- (WebhookSampleEventTypeEnum.FULFILLMENT_CANCELED, True),- (WebhookSampleEventTypeEnum.PAGE_CREATED, False),- (WebhookSampleEventTypeEnum.PAGE_UPDATED, False),- (WebhookSampleEventTypeEnum.PAGE_DELETED, False),- ],-)-def test_sample_payload_query_by_app(- mock_generate_sample_payload,- event_type,- has_access,- app_api_client,- permission_manage_orders,-):-- mock_generate_sample_payload.return_value = {"mocked_response": ""}- query = SAMPLE_PAYLOAD_QUERY- variables = {"event_type": event_type.name}- response = app_api_client.post_graphql(- query, variables=variables, permissions=[permission_manage_orders]- )- if not has_access:- assert_no_permission(response)- mock_generate_sample_payload.assert_not_called()- else:- get_graphql_content(response)- mock_generate_sample_payload.assert_called_with(event_type.value)---@patch("saleor.graphql.webhook.resolvers.payloads.generate_sample_payload")- "event_type, has_access",- [- (WebhookSampleEventTypeEnum.ORDER_CREATED, False),- (WebhookSampleEventTypeEnum.ORDER_CREATED, False),- (WebhookSampleEventTypeEnum.ORDER_FULLY_PAID, False),- (WebhookSampleEventTypeEnum.ORDER_UPDATED, False),- (WebhookSampleEventTypeEnum.ORDER_CANCELLED, False),- (WebhookSampleEventTypeEnum.ORDER_FULFILLED, False),- (WebhookSampleEventTypeEnum.CUSTOMER_CREATED, True),- (WebhookSampleEventTypeEnum.PRODUCT_CREATED, True),- (WebhookSampleEventTypeEnum.PRODUCT_UPDATED, True),- (WebhookSampleEventTypeEnum.CHECKOUT_CREATED, True),- (WebhookSampleEventTypeEnum.CHECKOUT_UPDATED, True),- (WebhookSampleEventTypeEnum.FULFILLMENT_CREATED, False),- (WebhookSampleEventTypeEnum.FULFILLMENT_CANCELED, False),- (WebhookSampleEventTypeEnum.PAGE_CREATED, True),- (WebhookSampleEventTypeEnum.PAGE_UPDATED, True),- (WebhookSampleEventTypeEnum.PAGE_DELETED, True),- ],-)-def test_sample_payload_query_by_staff(- mock_generate_sample_payload,- event_type,- has_access,- staff_api_client,- permission_manage_users,- permission_manage_products,- permission_manage_checkouts,- permission_manage_pages,-):- mock_generate_sample_payload.return_value = {"mocked_response": ""}- query = SAMPLE_PAYLOAD_QUERY- staff_api_client.user.user_permissions.add(permission_manage_users)- staff_api_client.user.user_permissions.add(permission_manage_products)- staff_api_client.user.user_permissions.add(permission_manage_checkouts)- staff_api_client.user.user_permissions.add(permission_manage_pages)- variables = {"event_type": event_type.name}- response = staff_api_client.post_graphql(query, variables=variables)- if not has_access:- assert_no_permission(response)- mock_generate_sample_payload.assert_not_called()- else:- get_graphql_content(response)- mock_generate_sample_payload.assert_called_with(event_type.value)diff --git a/saleor/graphql/webhook/utils.py b/saleor/graphql/webhook/utils.pyindex a8f2e5dc87..edb101b7f3 100644--- a/saleor/graphql/webhook/utils.py+++ b/saleor/graphql/webhook/utils.py@@ -1,58 +1,76 @@-from typing import Dict, Optional+from typing import Dict, List, Optionalfrom graphene.utils.str_converters import to_snake_case-from graphql import parse, print_ast-from graphql.error.syntax_error import GraphQLSyntaxError+from graphql import parse+from graphql.error import GraphQLSyntaxErrorfrom graphql.language.ast import Document-def get_event_type_from_subscription(query: str) -> Optional[str]:+def get_event_type_from_subscription(query: str) -> List[str]:try:ast = parse(query)- subscription = None- fragments = get_event_fragments_from_query(ast)+ subscription = get_subscription(ast)+ if not subscription:+ return []- for definition in ast.definitions:- if (- hasattr(definition, "operation")- and definition.operation == "subscription"- ):- subscription = definition+ event_field = get_event_field_from_subscription(subscription)+ if not event_field:+ return []- if subscription:- subscription_string = print_ast(subscription)+ events = get_events(event_field)+ if not events:+ return []- if fragments:- for fragment_name, event_type in fragments.items():- if fragment_name in subscription_string:- return to_snake_case(event_type)+ fragments = get_event_fragment_names_from_query(ast)+ if fragments:+ events = [fragments.get(event, event) for event in events]- event_type = (- "".join(subscription_string.split())- .split("event{...on")[1]- .split("{")[0]- )- return to_snake_case(event_type)- return None- except (GraphQLSyntaxError, IndexError):- return None+ return list(map(to_snake_case, events))+ except GraphQLSyntaxError:+ return []-def get_event_fragments_from_query(ast: Document) -> Optional[Dict[str, str]]:- fragments = {}++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:- try:+ 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"):- fragment_string = print_ast(definition)- event_type = (- "".join(fragment_string.split())- .split("Event{...on")[1]- .split("{")[0]- )- fragments[definition.name.value] = event_type- except IndexError:- continue- return fragments+ 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/tasks.py b/saleor/plugins/webhook/tasks.pyindex 0cd79ae514..fe4ea801d9 100644--- a/saleor/plugins/webhook/tasks.py+++ b/saleor/plugins/webhook/tasks.py@@ -499,6 +499,7 @@ def send_webhook_request_async(self, event_delivery_id):delivery.event_type,data,)+attempt_update(attempt, response)if response.status == EventDeliveryStatus.FAILED:task_logger.info(diff --git a/saleor/plugins/webhook/utils.py b/saleor/plugins/webhook/utils.pyindex 3c8d69dc6b..5d4eb2b2e7 100644--- a/saleor/plugins/webhook/utils.py+++ b/saleor/plugins/webhook/utils.py@@ -224,7 +224,6 @@ def attempt_update(attempt: "EventDeliveryAttempt",webhook_response: "WebhookResponse",):-attempt.duration = webhook_response.durationattempt.response = webhook_response.contentattempt.response_headers = json.dumps(webhook_response.response_headers)diff --git a/saleor/webhook/error_codes.py b/saleor/webhook/error_codes.pyindex 8d254e1867..0165fbc66c 100644--- a/saleor/webhook/error_codes.py+++ b/saleor/webhook/error_codes.py@@ -17,3 +17,13 @@ class WebhookDryRunErrorCode(Enum):INVALID_ID = "invalid_id"MISSING_PERMISSION = "missing_permission"TYPE_NOT_SUPPORTED = "type_not_supported"+++class WebhookTriggerErrorCode(Enum):+ GRAPHQL_ERROR = "graphql_error"+ NOT_FOUND = "not_found"+ INVALID_ID = "invalid_id"+ MISSING_PERMISSION = "missing_app_permission"+ MISSING_QUERY = "missing_query"+ TYPE_NOT_SUPPORTED = "type_not_supported"+ UNABLE_TO_PARSE = "unable_to_parse"