Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
[SALEOR-6404] Sign webhook paylaod using RS256 and private key used JWT infrastructure (#9977)
Tomasz Magulskidf7c7d4e8466
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex b5f1d65260..8682dfb576 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1300,7 +1300,11 @@ type Webhook implements Node {"""Informs if webhook is activated."""isActive: Boolean!- """Used to create a hash signature with each payload."""+ """+ Used to create a hash signature with each payload.++ If not set, since Saleor 3.5, your payload will be signed using private key used also to sign JWT tokens.+ """secretKey: String"""Used to define payloads for specific events."""diff --git a/saleor/graphql/webhook/types.py b/saleor/graphql/webhook/types.pyindex 354b0cfbaf..ad23ceb86c 100644--- a/saleor/graphql/webhook/types.py+++ b/saleor/graphql/webhook/types.py@@ -177,7 +177,11 @@ class Webhook(ModelObjectType):required=True, description="Informs if webhook is activated.")secret_key = graphene.String(- description="Used to create a hash signature with each payload."+ description=(+ "Used to create a hash signature with each payload."+ "\n\nIf not set, since Saleor 3.5, your payload will be "+ "signed using private key used also to sign JWT tokens."+ ))subscription_query = graphene.String(description="Used to define payloads for specific events."diff --git a/saleor/plugins/webhook/__init__.py b/saleor/plugins/webhook/__init__.pyindex 06141d4fa6..051b9f4b22 100644--- a/saleor/plugins/webhook/__init__.py+++ b/saleor/plugins/webhook/__init__.py@@ -1,9 +1,15 @@import hashlibimport hmac+from jwt.algorithms import get_default_algorithms++from ...core.jwt_manager import get_jwt_manager+def signature_for_payload(body: bytes, secret_key):- if not secret_key:- return ""+ if secret_key is None:+ algorithm = get_default_algorithms()["RS256"]+ private_key = get_jwt_manager().get_private_key()+ return algorithm.sign(body, private_key).hex()hash = hmac.new(bytes(secret_key, "utf-8"), body, hashlib.sha256)return hash.hexdigest()diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.pyindex 7fd738989d..835e799a7e 100644--- a/saleor/plugins/webhook/tasks.py+++ b/saleor/plugins/webhook/tasks.py@@ -537,70 +537,3 @@ def observability_reporter_task():if events:with observability.opentracing_trace("send_events", "webhooks"):send_observability_events(webhooks, events)---# DEPRECATED-# to be removed in task: #1q2x7xw[email protected](compression="zlib")-def trigger_webhooks_for_event(event_type, data):- """Send a webhook request for an event as an async task."""- webhooks = get_webhooks_for_event(event_type)- for webhook in webhooks:- send_webhook_request.delay(- webhook.app.name,- webhook.pk,- webhook.target_url,- webhook.secret_key,- event_type,- data,- )---# to be removed in task: #1q2x7xw- bind=True,- retry_backoff=10,- retry_kwargs={"max_retries": 5},- compression="zlib",-)-def send_webhook_request(- self, app_name, webhook_id, target_url, secret, event_type, data-):- parts = urlparse(target_url)- domain = Site.objects.get_current().domain- message = data.encode("utf-8")- signature = signature_for_payload(message, secret)-- scheme_matrix = {- 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,- ),- }-- if methods := scheme_matrix.get(parts.scheme.lower()):- send_method, send_exception = methods- try:- with webhooks_opentracing_trace(event_type, domain, app_name=app_name):- send_method(target_url, message, domain, signature, event_type)- except send_exception as e:- task_logger.info("[Webhook] Failed request to %r: %r.", target_url, e)- try:- countdown = self.retry_backoff * (2**self.request.retries)- self.retry(countdown=countdown, **self.retry_kwargs)- except MaxRetriesExceededError:- task_logger.warning(- "[Webhook] Failed request to %r: exceeded retry limit.",- target_url,- )- task_logger.info(- "[Webhook ID:%r] Payload sent to %r for event %r",- webhook_id,- target_url,- event_type,- )- else:- raise ValueError("Unknown webhook scheme: %r" % (parts.scheme,))diff --git a/saleor/plugins/webhook/tests/test_webhook_protocols.py b/saleor/plugins/webhook/tests/test_webhook_protocols.pyindex 093c864a8c..594850bfd8 100644--- a/saleor/plugins/webhook/tests/test_webhook_protocols.py+++ b/saleor/plugins/webhook/tests/test_webhook_protocols.py@@ -47,6 +47,7 @@ def test_trigger_webhooks_with_aws_sqs(webhook.save()expected_data = serialize("json", [order_with_lines])+ expected_signature = signature_for_payload(expected_data.encode("utf-8"), None)trigger_webhooks_async(expected_data, WebhookEventAsyncType.ORDER_CREATED, [webhook])@@ -62,6 +63,7 @@ def test_trigger_webhooks_with_aws_sqs("MessageAttributes": {"SaleorDomain": {"DataType": "String", "StringValue": "mirumee.com"},"EventType": {"DataType": "String", "StringValue": "order_created"},+ "Signature": {"DataType": "String", "StringValue": expected_signature},},"MessageBody": expected_data,}@@ -142,6 +144,7 @@ def test_trigger_webhooks_with_google_pub_sub(webhook.target_url = "gcpubsub://cloud.google.com/projects/saleor/topics/test"webhook.save()expected_data = serialize("json", [order_with_lines])+ expected_signature = signature_for_payload(expected_data.encode("utf-8"), None)trigger_webhooks_async(expected_data, WebhookEventAsyncType.ORDER_CREATED, [webhook]@@ -151,7 +154,7 @@ def test_trigger_webhooks_with_google_pub_sub(expected_data.encode("utf-8"),saleorDomain="mirumee.com",eventType=WebhookEventAsyncType.ORDER_CREATED,- signature="",+ signature=expected_signature,)@@ -212,6 +215,9 @@ def test_trigger_webhooks_with_http(webhook.save()expected_data = serialize("json", [order_with_lines])+ expected_signature = signature_for_payload(+ expected_data.encode("utf-8"), webhook.secret_key+ )trigger_webhooks_async(expected_data, WebhookEventAsyncType.ORDER_CREATED, [webhook]@@ -222,10 +228,10 @@ def test_trigger_webhooks_with_http(# X- headers will be deprecated in Saleor 4.0, proper headers are without X-"X-Saleor-Event": "order_created","X-Saleor-Domain": "mirumee.com",- "X-Saleor-Signature": "",+ "X-Saleor-Signature": expected_signature,"Saleor-Event": "order_created","Saleor-Domain": "mirumee.com",- "Saleor-Signature": "",+ "Saleor-Signature": expected_signature,}mock_request.assert_called_once_with(