Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
[SALEOR-6404] Validate webhooks with asyncEvents and syncEvents
Tomasz Magulski19d21f0c6107
diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.pyindex b60259db61..fe9722e3e7 100644--- a/saleor/app/installation_utils.py+++ b/saleor/app/installation_utils.py@@ -1,7 +1,6 @@import requestsfrom django.conf import settingsfrom django.contrib.sites.models import Site-from django.db import transactionfrom ..core.permissions import get_permission_namesfrom ..plugins.manager import PluginsManager@@ -63,23 +62,25 @@ def install_app(app_installation: AppInstallation, activate: bool = False):)extension.permissions.set(extension_data.get("permissions", []))- for webhook_data in manifest_data.get("webhooks", []):- with transaction.atomic():- webhook = Webhook(- app=app,- name=webhook_data["name"],- target_url=webhook_data["targetUrl"],- is_active=webhook_data["isActive"],- subscription_query=webhook_data["query"],- )- webhook.full_clean()- webhook.save()- WebhookEvent.objects.bulk_create(- [- WebhookEvent(webhook=webhook, event_type=event)- for event in (webhook_data.get("asyncEvents", []) + webhook_data.get("syncEvents", []))- ]+ webhooks = Webhook.objects.bulk_create(+ Webhook(+ app=app,+ name=webhook["name"],+ target_url=webhook["targetUrl"],+ subscription_query=webhook["query"],+ )+ for webhook in manifest_data.get("webhooks", [])+ )++ webhook_events = []+ for db_webhook, manifest_webhook in zip(+ webhooks, manifest_data.get("webhooks", [])+ ):+ for event_type in manifest_webhook["events"]:+ webhook_events.append(+ WebhookEvent(webhook=db_webhook, event_type=event_type))+ WebhookEvent.objects.bulk_create(webhook_events)_, token = app.tokens.create(name="Default token")diff --git a/saleor/app/manifest_validations.py b/saleor/app/manifest_validations.pyindex a90f66a713..bf1eb0f241 100644--- a/saleor/app/manifest_validations.py+++ b/saleor/app/manifest_validations.py@@ -12,7 +12,9 @@ from ..core.permissions import (get_permissions_enum_list,split_permission_codename,)-from ..graphql.webhook.subscription_payload import validate_query+from ..graphql.core.utils import str_to_enum+from ..graphql.webhook.subscription_payload import validate_subscription_query+from ..webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom .error_codes import AppErrorCodefrom .types import AppExtensionMount, AppExtensionTargetfrom .validators import AppURLValidator@@ -121,7 +123,7 @@ def clean_manifest_data(manifest_data):if not errors:clean_extensions(manifest_data, app_permissions, errors)- clean_webhooks(manifest_data, app_permissions, errors)+ clean_webhooks(manifest_data, errors)if errors:raise ValidationError(errors)@@ -180,16 +182,66 @@ def clean_extensions(manifest_data, app_permissions, errors):_clean_extension_permissions(extension, app_permissions, errors)-def clean_webhooks(manifest_data, app_permissions, errors):+def clean_webhooks(manifest_data, errors):webhooks = manifest_data.get("webhooks", [])++ async_types = {+ str_to_enum(e_type[0]): e_type[0] for e_type in WebhookEventAsyncType.CHOICES+ }+ sync_types = {+ str_to_enum(e_type[0]): e_type[0] for e_type in WebhookEventSyncType.CHOICES+ }++ target_url_validator = AppURLValidator(+ schemes=["http", "https", "awssqs", "gcpubsub"]+ )+for webhook in webhooks:- validate_query(webhook["query"], required=True)+ if not validate_subscription_query(webhook["query"]):+ errors["webhooks"].append(+ ValidationError(+ "Subscription query is not valid.",+ code=AppErrorCode.INVALID.value,+ )+ )++ webhook["events"] = []+ for e_type in webhook.get("asyncEvents", []):+ try:+ webhook["events"].append(async_types[e_type])+ except KeyError:+ errors["webhooks"].append(+ ValidationError(+ "Invalid asynchronous event.",+ code=AppErrorCode.INVALID.value,+ )+ )+ for e_type in webhook.get("syncEvents", []):+ try:+ webhook["events"].append(sync_types[e_type])+ except KeyError:+ errors["webhooks"].append(+ ValidationError(+ "Invalid synchronous event.",+ code=AppErrorCode.INVALID.value,+ )+ )++ try:+ target_url_validator(webhook["targetUrl"])+ except ValidationError:+ errors["webhooks"].append(+ ValidationError(+ "Invalid target url.",+ code=AppErrorCode.INVALID_URL_FORMAT.value,+ )+ )def validate_required_fields(manifest_data, errors):manifest_required_fields = {"id", "version", "name", "tokenTargetUrl"}extension_required_fields = {"label", "url", "mount"}- webhook_required_fields = {"name", "targetUrl", "isActive", "query"}+ webhook_required_fields = {"name", "targetUrl", "query"}if manifest_missing_fields := manifest_required_fields.difference(manifest_data):for missing_field in manifest_missing_fields:diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.pyindex 89fbcd9d55..4e9d0a6569 100644--- a/saleor/app/tests/test_installation_utils.py+++ b/saleor/app/tests/test_installation_utils.py@@ -290,7 +290,7 @@ def test_install_app_with_webhook()assert webhook.subscription_query == app_manifest_webhook["query"]assert webhook.target_url == app_manifest_webhook["targetUrl"]- assert webhook.is_active == app_manifest_webhook["isActive"]+ assert webhook.is_active is Truedef test_install_app_webhook_incorrect_url(@@ -309,8 +309,8 @@ def test_install_app_webhook_incorrect_url(install_app(app_installation, activate=True)error_dict = excinfo.value.error_dict- assert "target_url" in error_dict- assert error_dict["target_url"][0].message == "Enter a valid URL."+ assert "webhooks" in error_dict+ assert error_dict["webhooks"][0].message == "Invalid target url."def test_install_app_webhook_incorrect_query(@@ -343,5 +343,5 @@ def test_install_app_webhook_incorrect_query(install_app(app_installation, activate=True)error_dict = excinfo.value.error_dict- assert "query" in error_dict- assert error_dict["query"][0].message == "Subscription query is not valid"+ assert "webhooks" in error_dict+ assert error_dict["webhooks"][0].message == "Subscription query is not valid."diff --git a/saleor/graphql/app/types.py b/saleor/graphql/app/types.pyindex 693781cfcd..63910b12a2 100644--- a/saleor/graphql/app/types.py+++ b/saleor/graphql/app/types.py@@ -13,7 +13,7 @@ from ...core.permissions import ()from ..account.utils import is_owner_or_has_one_of_permsfrom ..core.connection import CountableConnection-from ..core.descriptions import ADDED_IN_31, ADDED_IN_34, PREVIEW_FEATURE+from ..core.descriptions import ADDED_IN_31, ADDED_IN_35, PREVIEW_FEATUREfrom ..core.federation import federated_entity, resolve_federation_referencesfrom ..core.types import Job, ModelObjectType, NonNullList, Permissionfrom ..core.utils import from_global_id_or_error@@ -167,9 +167,6 @@ class AppManifestWebhook(graphene.ObjectType):target_url = graphene.String(description="The url to receive the payload.", required=True)- is_active = graphene.Boolean(- description="Determine if webhook will be set active or not.", required=True- )@staticmethoddef resolve_async_events(root, info):@@ -183,10 +180,6 @@ class AppManifestWebhook(graphene.ObjectType):def resolve_target_url(root, info):return root["targetUrl"]- @staticmethod- def resolve_is_active(root, info):- return root["isActive"]-class Manifest(graphene.ObjectType):identifier = graphene.String(required=True)@@ -204,7 +197,7 @@ class Manifest(graphene.ObjectType):extensions = NonNullList(AppManifestExtension, required=True)webhooks = NonNullList(AppManifestWebhook,- description="List of the app's webhooks." + ADDED_IN_34 + PREVIEW_FEATURE,+ description="List of the app's webhooks." + ADDED_IN_35 + PREVIEW_FEATURE,required=True,)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 9771fb225d..597ad2b6dc 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -19822,6 +19822,14 @@ type Manifest {homepageUrl: StringsupportUrl: Stringextensions: [AppManifestExtension!]!++ """+ List of the app's webhooks.++ Added in Saleor 3.5.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """webhooks: [AppManifestWebhook!]!}@@ -19843,11 +19851,20 @@ type AppManifestExtension {}type AppManifestWebhook {+ """The name of the webhook."""name: String!- events: [WebhookEventTypeEnum!]!++ """The asynchronous events that webhook wants to subscribe."""+ asyncEvents: [WebhookEventTypeAsyncEnum!]++ """The synchronous events that webhook wants to subscribe."""+ syncEvents: [WebhookEventTypeSyncEnum!]++ """Subscription query of a webhook"""query: String!++ """The url to receive the payload."""targetUrl: String!- isActive: Boolean!}"""diff --git a/saleor/graphql/webhook/subscription_payload.py b/saleor/graphql/webhook/subscription_payload.pyindex 18a2e32956..c9483b2596 100644--- a/saleor/graphql/webhook/subscription_payload.py+++ b/saleor/graphql/webhook/subscription_payload.py@@ -36,8 +36,8 @@ def validate_subscription_query(query: str) -> bool:return True-def validate_query(query, required=False):- if not query and not required:+def validate_query(query):+ if not query:returnis_valid = validate_subscription_query(query)if not is_valid:diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 6a049a9b53..c6032a754c 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -5861,7 +5861,6 @@ def app_manifest_webhook():}""","targetUrl": "https://app.example/api/webhook",- "isActive": True,}