Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Deactivate webhook before deletion (#11475)
Jakub0491163b00ea
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2078298278..2881a3ca50 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -53,6 +53,7 @@ All notable, unreleased changes to this project will be documented in this file.- Make email authentication case-insensitive. #11284 by @zedzior- Fix the observability reporter to obfuscate URLs. #11282 by @przlada- Add HTTP headers filtering to observability reporter. #11285 by @przlada+- Deactivate Webhook before deleting and handle IntegrityErrors - #11239 @jakubkuc# 3.8.0diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 8f30371bfa..cc2d07ab55 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -11758,7 +11758,7 @@ type Mutation {): WebhookCreate"""- Deletes a webhook subscription.+ 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.Requires one of the following permissions: MANAGE_APPS, AUTHENTICATED_APP."""@@ -15522,6 +15522,7 @@ enum WebhookErrorCode {NOT_FOUNDREQUIREDUNIQUE+ DELETE_FAILED}input WebhookCreateInput {@@ -15568,7 +15569,7 @@ input WebhookCreateInput {}"""-Deletes a webhook subscription.+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.Requires one of the following permissions: MANAGE_APPS, AUTHENTICATED_APP."""diff --git a/saleor/graphql/webhook/mutations.py b/saleor/graphql/webhook/mutations.pyindex 2d448acea9..d25543a852 100644--- a/saleor/graphql/webhook/mutations.py+++ b/saleor/graphql/webhook/mutations.py@@ -1,5 +1,6 @@import graphenefrom django.core.exceptions import ValidationError+from django.db import IntegrityErrorfrom ...core.permissions import AppPermission, AuthorizationFiltersfrom ...webhook import models@@ -232,7 +233,12 @@ class WebhookDelete(ModelDeleteMutation):id = graphene.ID(required=True, description="ID of a webhook to delete.")class Meta:- description = "Deletes a webhook subscription."+ 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.Webhookobject_type = Webhookpermissions = (@@ -244,25 +250,32 @@ class WebhookDelete(ModelDeleteMutation):@classmethoddef perform_mutation(cls, _root, info, **data):- node_id = data["id"]- object_id = cls.get_global_id_or_error(node_id)-app = get_app_promise(info.context).get()- if app:- if not app.is_active:- raise ValidationError(- "App needs to be active to delete webhook",- code=WebhookErrorCode.INVALID,- )- try:- app.webhooks.get(id=object_id)- except models.Webhook.DoesNotExist:- raise ValidationError(- f"Couldn't resolve to a node: {node_id}",- code=WebhookErrorCode.GRAPHQL_ERROR,- )-- return super().perform_mutation(_root, info, **data)+ node_id = data.get("id")+ if app and not app.is_active:+ raise ValidationError(+ "App needs to be active to delete webhook",+ code=WebhookErrorCode.INVALID,+ )+ 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,+ )+ 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,+ )++ return responseclass EventDeliveryRetry(BaseMutation):diff --git a/saleor/graphql/webhook/tests/test_webhook.py b/saleor/graphql/webhook/tests/test_webhook.pyindex dfda57a974..6df030d23a 100644--- a/saleor/graphql/webhook/tests/test_webhook.py+++ b/saleor/graphql/webhook/tests/test_webhook.py@@ -1,7 +1,8 @@-from unittest.mock import patch+from unittest.mock import Mock, patchimport grapheneimport pytest+from django.db import IntegrityErrorfrom ....app.models import Appfrom ....webhook.models import Webhook@@ -291,7 +292,7 @@ def test_webhook_delete_by_app_and_missing_webhook(app_api_client, webhook):response = app_api_client.post_graphql(query, variables=variables)content = get_graphql_content(response)errors = content["data"]["webhookDelete"]["errors"]- assert errors[0]["code"] == "GRAPHQL_ERROR"+ assert errors[0]["code"] == "NOT_FOUND"def test_webhook_delete_by_inactive_app(app_api_client, webhook):@@ -305,6 +306,49 @@ def test_webhook_delete_by_inactive_app(app_api_client, webhook):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()diff --git a/saleor/webhook/error_codes.py b/saleor/webhook/error_codes.pyindex 86a9c07945..82cd8ae91c 100644--- a/saleor/webhook/error_codes.py+++ b/saleor/webhook/error_codes.py@@ -7,3 +7,4 @@ class WebhookErrorCode(Enum):NOT_FOUND = "not_found"REQUIRED = "required"UNIQUE = "unique"+ DELETE_FAILED = "delete_failed"