Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix failed event delivery request headers (#10108)
Jakubd1b652115b9f
diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.pyindex 132cf7f400..3f1a8fc00e 100644--- a/saleor/plugins/webhook/tasks.py+++ b/saleor/plugins/webhook/tasks.py@@ -3,7 +3,7 @@ import loggingfrom dataclasses import dataclassfrom enum import Enumfrom json import JSONDecodeError-from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Type+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optionalfrom urllib.parse import unquote, urlparse, urlunparseimport boto3@@ -204,8 +204,20 @@ def send_webhook_using_http("Saleor-Domain": domain,"Saleor-Signature": signature,}+ try:+ response = requests.post(+ target_url, data=message, headers=headers, timeout=timeout+ )+ except (RequestException,) as e:+ response = WebhookResponse(+ content=str(e), status=EventDeliveryStatus.FAILED, request_headers=headers+ )+ if e.response:+ response.content = e.response.text+ response.response_headers = dict(e.response.headers)+ response.response_status_code = e.response.status_code+ return response- response = requests.post(target_url, data=message, headers=headers, timeout=timeout)return WebhookResponse(content=response.text,request_headers=headers,@@ -233,7 +245,14 @@ def send_webhook_using_aws_sqs(target_url, message, domain, signature, event_typ),)queue_url = urlunparse(- ("https", parts.hostname, parts.path, parts.params, parts.query, parts.fragment)+ (+ "https",+ parts.hostname,+ parts.path,+ parts.params,+ parts.query,+ parts.fragment,+ ))is_fifo = parts.path.endswith(".fifo")@@ -242,7 +261,10 @@ def send_webhook_using_aws_sqs(target_url, message, domain, signature, event_typ"EventType": {"DataType": "String", "StringValue": event_type},}if signature:- msg_attributes["Signature"] = {"DataType": "String", "StringValue": signature}+ msg_attributes["Signature"] = {+ "DataType": "String",+ "StringValue": signature,+ }message_kwargs = {"QueueUrl": queue_url,@@ -252,7 +274,12 @@ def send_webhook_using_aws_sqs(target_url, message, domain, signature, event_typif is_fifo:message_kwargs["MessageGroupId"] = domainwith catch_duration_time() as duration:- response = client.send_message(**message_kwargs)+ try:+ response = client.send_message(**message_kwargs)+ except (ClientError,) as e:+ return WebhookResponse(+ content=str(e), status=EventDeliveryStatus.FAILED, duration=duration()+ )return WebhookResponse(content=response, duration=duration())@@ -263,13 +290,16 @@ def send_webhook_using_google_cloud_pubsub(client = pubsub_v1.PublisherClient()topic_name = parts.path[1:] # drop the leading slashwith catch_duration_time() as duration:- future = client.publish(- topic_name,- message,- saleorDomain=domain,- eventType=event_type,- signature=signature,- )+ try:+ future = client.publish(+ topic_name,+ message,+ saleorDomain=domain,+ eventType=event_type,+ signature=signature,+ )+ except (pubsub_v1.publisher.exceptions.MessageTooLargeError, RuntimeError) as e:+ return WebhookResponse(content=str(e), status=EventDeliveryStatus.FAILED)response_duration = duration()response = future.result()return WebhookResponse(content=response, duration=response_duration)@@ -281,29 +311,21 @@ def send_webhook_using_scheme_method(parts = urlparse(target_url)message = data.encode("utf-8")signature = signature_for_payload(message, secret)- scheme_matrix: Dict[- WebhookSchemes, Tuple[Callable, Tuple[Type[Exception], ...]]- ] = {- WebhookSchemes.HTTP: (send_webhook_using_http, (RequestException,)),- WebhookSchemes.HTTPS: (send_webhook_using_http, (RequestException,)),- WebhookSchemes.AWS_SQS: (send_webhook_using_aws_sqs, (ClientError,)),- WebhookSchemes.GOOGLE_CLOUD_PUBSUB: (- send_webhook_using_google_cloud_pubsub,- (pubsub_v1.publisher.exceptions.MessageTooLargeError, RuntimeError),- ),+ scheme_matrix: Dict[WebhookSchemes, Callable] = {+ WebhookSchemes.HTTP: send_webhook_using_http,+ WebhookSchemes.HTTPS: send_webhook_using_http,+ WebhookSchemes.AWS_SQS: send_webhook_using_aws_sqs,+ WebhookSchemes.GOOGLE_CLOUD_PUBSUB: send_webhook_using_google_cloud_pubsub,}- if method := scheme_matrix.get(parts.scheme.lower()):- send_method, send_exception = method- try:- return send_method(- target_url,- message,- domain,- signature,- event_type,- )- except send_exception as e:- return WebhookResponse(content=str(e), status=EventDeliveryStatus.FAILED)+ if send_method := scheme_matrix.get(parts.scheme.lower()):+ # try:+ return send_method(+ target_url,+ message,+ domain,+ signature,+ event_type,+ )raise ValueError("Unknown webhook scheme: %r" % (parts.scheme,))@@ -423,19 +445,6 @@ def send_webhook_request_sync(timeout=timeout,)response_data = json.loads(response.content)- except RequestException as e:- logger.warning(- "[Webhook] Failed request to %r: %r. "- "ID of failed DeliveryAttempt: %r . ",- webhook.target_url,- e,- attempt.id,- )- response.status = EventDeliveryStatus.FAILED- if e.response:- response.content = e.response.text- response.response_headers = dict(e.response.headers)- response.response_status_code = e.response.status_codeexcept JSONDecodeError as e:logger.warning(@@ -447,6 +456,14 @@ def send_webhook_request_sync()response.status = EventDeliveryStatus.FAILEDelse:+ if response.status == EventDeliveryStatus.FAILED:+ logger.warning(+ "[Webhook] Failed request to %r: %r. "+ "ID of failed DeliveryAttempt: %r . ",+ webhook.target_url,+ response.content,+ attempt.id,+ )if response.status == EventDeliveryStatus.SUCCESS:logger.debug("[Webhook] Success response from %r."diff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.pyindex e563713e94..301d327c53 100644--- a/saleor/plugins/webhook/tests/test_payment_webhook.py+++ b/saleor/plugins/webhook/tests/test_payment_webhook.py@@ -5,6 +5,7 @@ from unittest import mockimport pytestfrom django.conf import settings+from django.contrib.sites.models import Sitefrom requests import RequestException, TooManyRedirectsfrom ....app.models import App@@ -14,12 +15,14 @@ from ....payment import PaymentError, TransactionKindfrom ....payment.utils import create_payment_informationfrom ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ....webhook.models import Webhook, WebhookEvent+from .. import signature_for_payloadfrom ..tasks import send_webhook_request_sync, trigger_webhook_syncfrom ..utils import (parse_list_payment_gateways_response,parse_payment_action_response,to_payment_app_id,)+from .utils import generate_request_headers@pytest.fixture@@ -153,6 +156,17 @@ def test_send_webhook_request_sync_successful_attempt(def test_send_webhook_request_sync_request_exception(mock_post, mock_observability, app, event_delivery):+ # given+ event_payload = event_delivery.payload+ data = event_payload.payload+ webhook = event_delivery.webhook+ domain = Site.objects.get_current().domain+ message = data.encode("utf-8")+ signature = signature_for_payload(message, webhook.secret_key)+ expected_request_headers = generate_request_headers(+ event_delivery.event_type, domain, signature+ )+# whenresponse_data = send_webhook_request_sync(app.name, event_delivery)attempt = EventDeliveryAttempt.objects.first()@@ -164,7 +178,7 @@ def test_send_webhook_request_sync_request_exception(assert attempt.response == ""assert attempt.response_headers == "null"assert attempt.response_status_code is None- assert attempt.request_headers == "null"+ assert json.loads(attempt.request_headers) == expected_request_headersassert response_data is Nonemock_observability.assert_called_once_with(attempt)diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.pyindex bd76698118..08f7a24ba9 100644--- a/saleor/plugins/webhook/tests/test_webhook.py+++ b/saleor/plugins/webhook/tests/test_webhook.py@@ -11,10 +11,12 @@ import pytestfrom celery.exceptions import MaxRetriesExceededErrorfrom celery.exceptions import Retry as CeleryTaskRetryErrorfrom django.contrib.auth.tokens import default_token_generator+from django.contrib.sites.models import Sitefrom django.core.serializers import serializefrom django.utils import timezonefrom freezegun import freeze_timefrom kombu.asynchronous.aws.sqs.connection import AsyncSQSConnection+from requests import RequestExceptionfrom .... import __version__from ....account.notifications import (@@ -51,6 +53,8 @@ from ....webhook.payloads import (from ....webhook.utils import get_webhooks_for_eventfrom ...manager import get_plugins_managerfrom ...webhook.tasks import send_webhook_request_async, trigger_webhooks_async+from .. import signature_for_payload+from .utils import generate_request_headersfirst_url = "http://www.example.com/first/"third_url = "http://www.example.com/third/"@@ -1181,6 +1185,35 @@ def test_send_webhook_request_async_when_delivery_attempt_failed(mocked_observability.assert_called_once_with(attempt, None)[email protected]("saleor.plugins.webhook.tasks.requests.post", side_effect=RequestException)[email protected]("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")+def test_send_webhook_request_async_with_request_exception(+ mocked_observability, mocked_post, event_delivery, webhook_response_failed+):+ # given+ event_payload = event_delivery.payload+ data = event_payload.payload+ webhook = event_delivery.webhook+ domain = Site.objects.get_current().domain+ message = data.encode("utf-8")+ signature = signature_for_payload(message, webhook.secret_key)+ expected_request_headers = generate_request_headers(+ event_delivery.event_type, domain, signature+ )+ # when+ with pytest.raises(CeleryTaskRetryError):+ send_webhook_request_async(event_delivery.pk)++ # then++ attempt = EventDeliveryAttempt.objects.filter(delivery=event_delivery).first()+ delivery = EventDelivery.objects.get(id=event_delivery.pk)+ assert attempt.status == EventDeliveryStatus.FAILED+ assert json.loads(attempt.request_headers) == expected_request_headers+ assert delivery.status == EventDeliveryStatus.PENDING+ mocked_observability.assert_called_once_with(attempt, None)++@mock.patch("saleor.plugins.webhook.tasks.send_webhook_request_async.retry")@mock.patch("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")@mock.patch("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")diff --git a/saleor/plugins/webhook/tests/utils.py b/saleor/plugins/webhook/tests/utils.pynew file mode 100644index 0000000000..6580de70a3--- /dev/null+++ b/saleor/plugins/webhook/tests/utils.py@@ -0,0 +1,11 @@+def generate_request_headers(event_type, domain, signature):+ return {+ "Content-Type": "application/json",+ # X- headers will be deprecated in Saleor 4.0, proper headers are without X-+ "X-Saleor-Event": event_type,+ "X-Saleor-Domain": domain,+ "X-Saleor-Signature": signature,+ "Saleor-Event": event_type,+ "Saleor-Domain": domain,+ "Saleor-Signature": signature,+ }