Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Webhook custom headers (#11978)
Piotr Zabieglik723aecb7ba25
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 17e1b26bb3..31359b4996 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -48,6 +48,7 @@ All notable, unreleased changes to this project will be documented in this file.- Add meta fields to `ProductMedia` model - #11894 by @zedzior- Make `oldPassword` argument on `passwordChange` mutation optional; support accounts without usable passwords - @11999 by @rafalp- Added support for AVIF images, added `AVIF` and `ORIGINAL` to `ThumbnailFormatEnum` - #11998 by @patrys+- Introduce custom headers for webhook requests - #11978 by @zedzior### Other changesdiff --git a/saleor/app/error_codes.py b/saleor/app/error_codes.pyindex dd79d64984..76a5fb35fd 100644--- a/saleor/app/error_codes.py+++ b/saleor/app/error_codes.py@@ -9,6 +9,7 @@ class AppErrorCode(Enum):INVALID_PERMISSION = "invalid_permission"INVALID_URL_FORMAT = "invalid_url_format"INVALID_MANIFEST_FORMAT = "invalid_manifest_format"+ INVALID_CUSTOM_HEADERS = "invalid_custom_headers"MANIFEST_URL_CANT_CONNECT = "manifest_url_cant_connect"NOT_FOUND = "not_found"REQUIRED = "required"diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.pyindex 6b2442209f..05950e3c4f 100644--- a/saleor/app/installation_utils.py+++ b/saleor/app/installation_utils.py@@ -92,6 +92,7 @@ def install_app(app_installation: AppInstallation, activate: bool = False):name=webhook["name"],target_url=webhook["targetUrl"],subscription_query=webhook["query"],+ custom_headers=webhook.get("customHeaders", None),)for webhook in manifest_data.get("webhooks", []))diff --git a/saleor/app/manifest_validations.py b/saleor/app/manifest_validations.pyindex 012a6b62b6..f8d33db9d4 100644--- a/saleor/app/manifest_validations.py+++ b/saleor/app/manifest_validations.py@@ -15,6 +15,7 @@ from ..permission.enums import ()from ..permission.models import Permissionfrom ..webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType+from ..webhook.validators import custom_headers_validatorfrom .error_codes import AppErrorCodefrom .types import AppExtensionMount, AppExtensionTargetfrom .validators import AppURLValidator@@ -252,6 +253,17 @@ def clean_webhooks(manifest_data, errors):))+ if custom_headers := webhook.get("customHeaders"):+ try:+ custom_headers_validator(custom_headers)+ except ValidationError as err:+ errors["webhooks"].append(+ ValidationError(+ f"Invalid custom headers: {err.message}",+ code=AppErrorCode.INVALID_CUSTOM_HEADERS.value,+ )+ )+def validate_required_fields(manifest_data, errors):manifest_required_fields = {"id", "version", "name", "tokenTargetUrl"}diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.pyindex b583976962..439e0091a7 100644--- a/saleor/app/tests/test_installation_utils.py+++ b/saleor/app/tests/test_installation_utils.py@@ -257,7 +257,7 @@ def test_install_app_extension_incorrect_url(install_app(app_installation, activate=True)-def test_install_app_extension_ivalid_permission(+def test_install_app_extension_invalid_permission(app_manifest, app_installation, monkeypatch):# given@@ -332,6 +332,8 @@ def test_install_app_with_webhook(app_manifest, app_manifest_webhook, app_installation, monkeypatch):# given+ custom_headers = {"X-Key": "Value"}+ app_manifest_webhook["customHeaders"] = custom_headersapp_manifest["webhooks"] = [app_manifest_webhook]mocked_get_response = Mock()@@ -353,6 +355,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 is True+ assert webhook.custom_headers == custom_headersdef test_install_app_webhook_incorrect_url(@@ -409,6 +412,30 @@ def test_install_app_webhook_incorrect_query(assert "Subscription query is not valid:" in error_dict["webhooks"][0].message+def test_install_app_webhook_incorrect_custom_headers(+ app_manifest, app_manifest_webhook, app_installation, monkeypatch+):+ # given+ custom_headers = {"InvalidKey": "Value"}+ app_manifest_webhook["customHeaders"] = custom_headers+ app_manifest["webhooks"] = [app_manifest_webhook]++ mocked_get_response = Mock()+ mocked_get_response.json.return_value = app_manifest+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))++ # when & then+ with pytest.raises(ValidationError) as excinfo:+ install_app(app_installation, activate=True)++ error_dict = excinfo.value.error_dict+ assert "webhooks" in error_dict+ assert error_dict["webhooks"][0].message == (+ 'Invalid custom headers: "InvalidKey" '+ 'does not match allowed key pattern: "X-*" or "Authorization*".'+ )++def test_install_app_with_webhook_mismatch_between_query_and_event_fields(app_manifest,app_manifest_webhook,diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex a6aa59082e..5394e133cd 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1484,6 +1484,15 @@ type Webhook implements Node {"""Used to define payloads for specific events."""subscriptionQuery: String++ """+ Custom headers, which will be added to HTTP request.++ Added in Saleor 3.12.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ customHeaders: JSONString}"""An object with an ID"""@@ -16085,6 +16094,7 @@ enum WebhookErrorCode {MISSING_SUBSCRIPTIONUNABLE_TO_PARSEMISSING_EVENT+ INVALID_CUSTOM_HEADERS}input WebhookCreateInput {@@ -16128,6 +16138,15 @@ input WebhookCreateInput {Note: this API is currently in Feature Preview and can be subject to changes at later point."""query: String++ """+ Custom headers, which will be added to HTTP request. There is a limitation of 5 headers per webhook and 998 characters per header.Only "X-*" and "Authorization*" keys are allowed.++ Added in Saleor 3.12.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ customHeaders: JSONString}"""@@ -16193,6 +16212,15 @@ input WebhookUpdateInput {Note: this API is currently in Feature Preview and can be subject to changes at later point."""query: String++ """+ Custom headers, which will be added to HTTP request. There is a limitation of 5 headers per webhook and 998 characters per header.Only "X-*" and "Authorization*" keys are allowed.++ Added in Saleor 3.12.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ customHeaders: JSONString}"""@@ -23135,6 +23163,7 @@ enum AppErrorCode {INVALID_PERMISSIONINVALID_URL_FORMATINVALID_MANIFEST_FORMAT+ INVALID_CUSTOM_HEADERSMANIFEST_URL_CANT_CONNECTNOT_FOUNDREQUIREDdiff --git a/saleor/graphql/webhook/mutations/webhook_create.py b/saleor/graphql/webhook/mutations/webhook_create.pyindex f5eed1a245..e43c1045c4 100644--- a/saleor/graphql/webhook/mutations/webhook_create.py+++ b/saleor/graphql/webhook/mutations/webhook_create.py@@ -7,9 +7,20 @@ from ....permission.auth_filters import AuthorizationFiltersfrom ....permission.enums import AppPermissionfrom ....webhook import modelsfrom ....webhook.error_codes import WebhookErrorCode+from ....webhook.validators import (+ HEADERS_LENGTH_LIMIT,+ HEADERS_NUMBER_LIMIT,+ custom_headers_validator,+)from ...app.dataloaders import get_app_promisefrom ...core import ResolveInfo-from ...core.descriptions import ADDED_IN_32, DEPRECATED_IN_3X_INPUT, PREVIEW_FEATURE+from ...core.descriptions import (+ ADDED_IN_32,+ ADDED_IN_312,+ DEPRECATED_IN_3X_INPUT,+ PREVIEW_FEATURE,+)+from ...core.fields import JSONStringfrom ...core.mutations import ModelMutationfrom ...core.types import NonNullList, WebhookErrorfrom ...core.utils import raise_validation_error@@ -51,8 +62,15 @@ class WebhookCreateInput(graphene.InputObjectType):)query = graphene.String(description="Subscription query used to define a webhook payload."- + ADDED_IN_32- + PREVIEW_FEATURE,+ f"{ADDED_IN_32}{PREVIEW_FEATURE}",+ required=False,+ )+ custom_headers = JSONString(+ description=f"Custom headers, which will be added to HTTP request. "+ f"There is a limitation of {HEADERS_NUMBER_LIMIT} headers per webhook "+ f"and {HEADERS_LENGTH_LIMIT} characters per header."+ f'Only "X-*" and "Authorization*" keys are allowed.'+ f"{ADDED_IN_312}{PREVIEW_FEATURE}",required=False,)@@ -110,6 +128,16 @@ class WebhookCreate(ModelMutation):)instance.subscription_query = query+ if headers := cleaned_data.get("custom_headers"):+ try:+ custom_headers_validator(headers)+ except ValidationError as err:+ raise_validation_error(+ field="customHeaders",+ message=err.message,+ code=WebhookErrorCode.INVALID_CUSTOM_HEADERS,+ )+cls._clean_webhook_events(cleaned_data, subscription_query)return cleaned_datadiff --git a/saleor/graphql/webhook/mutations/webhook_update.py b/saleor/graphql/webhook/mutations/webhook_update.pyindex 41823fb4b7..b32188a171 100644--- a/saleor/graphql/webhook/mutations/webhook_update.py+++ b/saleor/graphql/webhook/mutations/webhook_update.py@@ -2,8 +2,15 @@ import graphenefrom ....permission.enums import AppPermissionfrom ....webhook import models+from ....webhook.validators import HEADERS_LENGTH_LIMIT, HEADERS_NUMBER_LIMITfrom ...core import ResolveInfo-from ...core.descriptions import ADDED_IN_32, DEPRECATED_IN_3X_INPUT, PREVIEW_FEATURE+from ...core.descriptions import (+ ADDED_IN_32,+ ADDED_IN_312,+ DEPRECATED_IN_3X_INPUT,+ PREVIEW_FEATURE,+)+from ...core.fields import JSONStringfrom ...core.types import NonNullList, WebhookErrorfrom .. import enumsfrom ..types import Webhook@@ -48,8 +55,15 @@ class WebhookUpdateInput(graphene.InputObjectType):)query = graphene.String(description="Subscription query used to define a webhook payload."- + ADDED_IN_32- + PREVIEW_FEATURE,+ f"{ADDED_IN_32}{PREVIEW_FEATURE}",+ required=False,+ )+ custom_headers = JSONString(+ description=f"Custom headers, which will be added to HTTP request. "+ f"There is a limitation of {HEADERS_NUMBER_LIMIT} headers per webhook "+ f"and {HEADERS_LENGTH_LIMIT} characters per header."+ f'Only "X-*" and "Authorization*" keys are allowed.'+ f"{ADDED_IN_312}{PREVIEW_FEATURE}",required=False,)diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_create.py b/saleor/graphql/webhook/tests/mutations/test_webhook_create.pyindex 525afa1a3c..ef088a0767 100644--- a/saleor/graphql/webhook/tests/mutations/test_webhook_create.py+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_create.py@@ -1,3 +1,5 @@+import json+import graphenefrom .....webhook.error_codes import WebhookErrorCode@@ -30,6 +32,7 @@ WEBHOOK_CREATE = """def test_webhook_create_by_app(app_api_client, permission_manage_orders):# givenquery = WEBHOOK_CREATE+ custom_headers = {"X-Key": "Value", "Authorization-Key": "Value"}variables = {"input": {"name": "New integration",@@ -38,6 +41,7 @@ def test_webhook_create_by_app(app_api_client, permission_manage_orders):WebhookEventTypeAsyncEnum.ORDER_CREATED.name,WebhookEventTypeAsyncEnum.ORDER_CREATED.name,],+ "customHeaders": json.dumps(custom_headers),}}@@ -54,6 +58,7 @@ def test_webhook_create_by_app(app_api_client, permission_manage_orders):new_webhook = Webhook.objects.get()assert new_webhook.name == "New integration"assert new_webhook.target_url == "https://www.example.com"+ assert new_webhook.custom_headers == custom_headersevents = new_webhook.events.all()assert len(events) == 1assert events[0].event_type == WebhookEventTypeAsyncEnum.ORDER_CREATED.value@@ -286,3 +291,31 @@ def test_webhook_create_inherit_events_from_query(data["webhook"]["syncEvents"][0]["eventType"]== WebhookEventTypeSyncEnum.PAYMENT_LIST_GATEWAYS.name)+++def test_webhook_create_invalid_custom_headers(app_api_client):+ # given+ query = WEBHOOK_CREATE+ custom_headers = {"DisallowedKey": "Value"}+ variables = {+ "input": {+ "name": "New integration",+ "targetUrl": "https://www.example.com",+ "customHeaders": json.dumps(custom_headers),+ }+ }++ # when+ response = app_api_client.post_graphql(query, variables=variables)+ content = get_graphql_content(response)++ # then+ data = content["data"]["webhookCreate"]+ assert not data["webhook"]+ error = data["errors"][0]+ assert error["field"] == "customHeaders"+ assert (+ error["message"] == '"DisallowedKey" does not match allowed key pattern: '+ '"X-*" or "Authorization*".'+ )+ assert error["code"] == WebhookErrorCode.INVALID_CUSTOM_HEADERS.namediff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_update.py b/saleor/graphql/webhook/tests/mutations/test_webhook_update.pyindex 6bd00d9684..b1f636075e 100644--- a/saleor/graphql/webhook/tests/mutations/test_webhook_update.py+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_update.py@@ -1,5 +1,8 @@+import json+import graphene+from ....core.enums import WebhookErrorCodefrom ....tests.utils import assert_no_permission, get_graphql_contentfrom ...enums import WebhookEventTypeAsyncEnum@@ -9,6 +12,7 @@ WEBHOOK_UPDATE = """errors {fieldmessage+ code}webhook {syncEvents {@@ -18,6 +22,7 @@ WEBHOOK_UPDATE = """eventType}isActive+ customHeaders}}}@@ -46,6 +51,7 @@ def test_webhook_update_by_staff(staff_api_client, webhook, permission_manage_ap# givenquery = WEBHOOK_UPDATEwebhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ custom_headers = {"X-Key": "Value", "Authorization-Key": "Value"}variables = {"id": webhook_id,"input": {@@ -54,6 +60,7 @@ def test_webhook_update_by_staff(staff_api_client, webhook, permission_manage_apWebhookEventTypeAsyncEnum.CUSTOMER_CREATED.name,],"isActive": False,+ "customHeaders": json.dumps(custom_headers),},}staff_api_client.user.user_permissions.add(permission_manage_apps)@@ -65,6 +72,7 @@ def test_webhook_update_by_staff(staff_api_client, webhook, permission_manage_ap# thenassert webhook.is_active is False+ assert webhook.custom_headers == custom_headersevents = webhook.events.all()assert len(events) == 1assert events[0].event_type == WebhookEventTypeAsyncEnum.CUSTOMER_CREATED.value@@ -76,6 +84,7 @@ def test_webhook_update_by_staff(staff_api_client, webhook, permission_manage_ap== WebhookEventTypeAsyncEnum.CUSTOMER_CREATED.name)assert data["webhook"]["isActive"] is False+ assert data["webhook"]["customHeaders"] == json.dumps(custom_headers)def test_webhook_update_by_staff_without_permission(staff_api_client, app, webhook):@@ -131,3 +140,36 @@ def test_webhook_update_inherit_events_from_query(events = webhook.events.all()assert len(events) == 1assert WebhookEventTypeAsyncEnum.ORDER_UPDATED.value == events[0].event_type+++def test_webhook_update_invalid_custom_headers(+ staff_api_client,+ webhook,+ permission_manage_apps,+):+ # given+ query = WEBHOOK_UPDATE+ custom_headers = {"DisallowedKey": "Value"}+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ staff_api_client.user.user_permissions.add(permission_manage_apps)+ variables = {+ "id": webhook_id,+ "input": {+ "customHeaders": json.dumps(custom_headers),+ },+ }++ # when+ response = staff_api_client.post_graphql(query, variables=variables)+ content = get_graphql_content(response)++ # then+ data = content["data"]["webhookUpdate"]+ assert not data["webhook"]+ error = data["errors"][0]+ assert error["field"] == "customHeaders"+ assert (+ error["message"] == '"DisallowedKey" does not match allowed key pattern: '+ '"X-*" or "Authorization*".'+ )+ assert error["code"] == WebhookErrorCode.INVALID_CUSTOM_HEADERS.namediff --git a/saleor/graphql/webhook/types.py b/saleor/graphql/webhook/types.pyindex e1c246455d..0a6d0abb8c 100644--- a/saleor/graphql/webhook/types.py+++ b/saleor/graphql/webhook/types.py@@ -12,8 +12,8 @@ from ..core.connection import (create_connection_slice,filter_connection_queryset,)-from ..core.descriptions import DEPRECATED_IN_3X_FIELD-from ..core.fields import FilterConnectionField+from ..core.descriptions import ADDED_IN_312, DEPRECATED_IN_3X_FIELD, PREVIEW_FEATURE+from ..core.fields import FilterConnectionField, JSONStringfrom ..core.types import ModelObjectType, NonNullListfrom ..webhook.enums import EventDeliveryStatusEnum, WebhookEventTypeEnumfrom ..webhook.filters import EventDeliveryFilterInput@@ -187,6 +187,11 @@ class Webhook(ModelObjectType[models.Webhook]):subscription_query = graphene.String(description="Used to define payloads for specific events.")+ custom_headers = JSONString(+ description="Custom headers, which will be added to HTTP request."+ + ADDED_IN_312+ + PREVIEW_FEATURE+ )class Meta:description = "Webhook."diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.pyindex 5f47e06a4d..f6a6879a55 100644--- a/saleor/plugins/webhook/tasks.py+++ b/saleor/plugins/webhook/tasks.py@@ -300,7 +300,13 @@ def trigger_all_webhooks_sync(def send_webhook_using_http(- target_url, message, domain, signature, event_type, timeout=settings.WEBHOOK_TIMEOUT+ target_url,+ message,+ domain,+ signature,+ event_type,+ timeout=settings.WEBHOOK_TIMEOUT,+ custom_headers: Optional[Dict[str, str]] = None,) -> WebhookResponse:"""Send a webhook request using http / https protocol.@@ -310,6 +316,7 @@ def send_webhook_using_http(:param signature: Webhook secret key checksum.:param event_type: Webhook event type.:param timeout: Request timeout.+ :param custom_headers: Custom headers which will be added to request headers.:return: WebhookResponse object."""@@ -324,6 +331,10 @@ def send_webhook_using_http(AppHeaders.SIGNATURE: signature,AppHeaders.API_URL: build_absolute_uri(reverse("api"), domain),}++ if custom_headers:+ headers.update(custom_headers)+try:response = requests.post(target_url, data=message, headers=headers, timeout=timeout@@ -357,7 +368,9 @@ def send_webhook_using_http()-def send_webhook_using_aws_sqs(target_url, message, domain, signature, event_type):+def send_webhook_using_aws_sqs(+ target_url, message, domain, signature, event_type, **kwargs+):parts = urlparse(target_url)region = "us-east-1"hostname_parts = parts.hostname.split(".")@@ -415,7 +428,7 @@ def send_webhook_using_aws_sqs(target_url, message, domain, signature, event_typdef send_webhook_using_google_cloud_pubsub(- target_url, message, domain, signature, event_type+ target_url, message, domain, signature, event_type, **kwargs):parts = urlparse(target_url)client = pubsub_v1.PublisherClient()@@ -438,7 +451,12 @@ def send_webhook_using_google_cloud_pubsub(def send_webhook_using_scheme_method(- target_url, domain, secret, event_type, data+ target_url,+ domain,+ secret,+ event_type,+ data,+ custom_headers=None,) -> WebhookResponse:parts = urlparse(target_url)message = data.encode("utf-8")@@ -449,6 +467,7 @@ def send_webhook_using_scheme_method(WebhookSchemes.AWS_SQS: send_webhook_using_aws_sqs,WebhookSchemes.GOOGLE_CLOUD_PUBSUB: send_webhook_using_google_cloud_pubsub,}+if send_method := scheme_matrix.get(parts.scheme.lower()):# try:return send_method(@@ -457,6 +476,7 @@ def send_webhook_using_scheme_method(domain,signature,event_type,+ custom_headers=custom_headers,)raise ValueError("Unknown webhook scheme: %r" % (parts.scheme,))@@ -500,6 +520,7 @@ def send_webhook_request_async(self, event_delivery_id):webhook.secret_key,delivery.event_type,data,+ webhook.custom_headers,)attempt_update(attempt, response)@@ -581,6 +602,7 @@ def send_webhook_request_sync(signature,delivery.event_type,timeout=timeout,+ custom_headers=webhook.custom_headers,)response_data = json.loads(response.content)diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.pyindex be53df9963..381fa4d82e 100644--- a/saleor/plugins/webhook/tests/test_webhook.py+++ b/saleor/plugins/webhook/tests/test_webhook.py@@ -53,8 +53,8 @@ from ....webhook.payloads import ()from ....webhook.utils import get_webhooks_for_eventfrom ...manager import get_plugins_manager-from ...webhook.tasks import send_webhook_request_async, trigger_webhooks_asyncfrom .. import signature_for_payload+from ..tasks import send_webhook_request_async, trigger_webhooks_asyncfrom .utils import generate_request_headersfirst_url = "http://www.example.com/first/"@@ -1383,6 +1383,7 @@ def test_send_webhook_request_async(event_delivery.webhook.secret_key,event_delivery.event_type,event_delivery.payload.payload,+ event_delivery.webhook.custom_headers,)mocked_clear_delivery.assert_called_once_with(event_delivery)attempt = EventDeliveryAttempt.objects.filter(delivery=event_delivery).first()@@ -1397,6 +1398,26 @@ def test_send_webhook_request_async(mocked_observability.assert_called_once_with(attempt)[email protected]("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")+def test_send_webhook_request_async_with_custom_headers(+ mocked_send_response,+ event_delivery,+ webhook_response,+):+ # given+ mocked_send_response.return_value = webhook_response+ custom_headers = {"X-Key": "Value", "Authorization-Key": "Value"}+ event_delivery.webhook.custom_headers = custom_headers+ event_delivery.webhook.save(update_fields=["custom_headers"])++ # when+ send_webhook_request_async(event_delivery.pk)++ # then+ mocked_send_response.assert_called_once()+ assert custom_headers in mocked_send_response.call_args[0]++@mock.patch("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")@mock.patch("saleor.plugins.webhook.tasks.clear_successful_delivery")def test_send_webhook_request_async_when_webhook_is_disabled(diff --git a/saleor/plugins/webhook/tests/test_webhook_protocols.py b/saleor/plugins/webhook/tests/test_webhook_protocols.pyindex dd8be5173f..1ce1505ea8 100644--- a/saleor/plugins/webhook/tests/test_webhook_protocols.py+++ b/saleor/plugins/webhook/tests/test_webhook_protocols.py@@ -352,3 +352,38 @@ def test_trigger_webhooks_with_http_and_secret_key_as_empty_string(headers=expected_headers,timeout=10,)+++@patch("saleor.plugins.webhook.tasks.requests.post")+def test_trigger_webhooks_with_http_and_custom_headers(+ mock_request, webhook, order_with_lines, permission_manage_orders+):+ # given+ webhook.app.permissions.add(permission_manage_orders)+ webhook.custom_headers = {"X-Key": "Value", "Authorization-Key": "Value"}+ webhook.secret_key = ""+ webhook.save()++ expected_data = serialize("json", [order_with_lines])+ expected_signature = signature_for_payload(expected_data.encode("utf-8"), "")+ expected_headers = {+ "Content-Type": "application/json",+ "X-Saleor-Event": "order_created",+ "X-Saleor-Domain": "mirumee.com",+ "X-Saleor-Signature": expected_signature,+ "Saleor-Event": "order_created",+ "Saleor-Domain": "mirumee.com",+ "Saleor-Signature": expected_signature,+ "Saleor-Api-Url": "http://mirumee.com/graphql/",+ "X-Key": "Value",+ "Authorization-Key": "Value",+ }++ # when+ trigger_webhooks_async(+ expected_data, WebhookEventAsyncType.ORDER_CREATED, [webhook]+ )++ # then+ mock_request.assert_called_once()+ assert mock_request.call_args[1]["headers"] == expected_headersdiff --git a/saleor/site/tests/test_site_settings.py b/saleor/site/tests/test_site_settings.pyindex 73eb688443..a14a508b83 100644--- a/saleor/site/tests/test_site_settings.py+++ b/saleor/site/tests/test_site_settings.py@@ -1,4 +1,6 @@+import pytestfrom django.contrib.sites.models import Site+from django.core.exceptions import ImproperlyConfiguredfrom ..models import SiteSettings@@ -8,3 +10,12 @@ def test_new_get_current():assert result.name == "mirumee.com"assert result.domain == "mirumee.com"assert type(result.settings) == SiteSettings+++def test_site_settings_default_from_email(settings):+ site = Site.objects.get_current()+ site.settings.default_mail_sender_address = None+ assert site.settings.default_from_email == settings.DEFAULT_FROM_EMAIL+ settings.DEFAULT_FROM_EMAIL = None+ with pytest.raises(ImproperlyConfigured):+ site.settings.default_from_emaildiff --git a/saleor/webhook/error_codes.py b/saleor/webhook/error_codes.pyindex 18cd0e1ed0..441531f0ed 100644--- a/saleor/webhook/error_codes.py+++ b/saleor/webhook/error_codes.py@@ -12,6 +12,7 @@ class WebhookErrorCode(Enum):MISSING_SUBSCRIPTION = "missing_subscription"UNABLE_TO_PARSE = "unable_to_parse"MISSING_EVENT = "missing_event"+ INVALID_CUSTOM_HEADERS = "invalid_custom_headers"class WebhookDryRunErrorCode(Enum):diff --git a/saleor/webhook/migrations/0009_webhook_custom_headers.py b/saleor/webhook/migrations/0009_webhook_custom_headers.pynew file mode 100644index 0000000000..0c377b7a98--- /dev/null+++ b/saleor/webhook/migrations/0009_webhook_custom_headers.py@@ -0,0 +1,25 @@+# Generated by Django 3.2.17 on 2023-02-09 11:28++from django.db import migrations, models+import saleor.core.utils.json_serializer+import saleor.webhook.validators+++class Migration(migrations.Migration):+ dependencies = [+ ("webhook", "0008_webhook_subscription_query"),+ ]++ operations = [+ migrations.AddField(+ model_name="webhook",+ name="custom_headers",+ field=models.JSONField(+ blank=True,+ default=dict,+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,+ null=True,+ validators=[saleor.webhook.validators.custom_headers_validator],+ ),+ ),+ ]diff --git a/saleor/webhook/models.py b/saleor/webhook/models.pyindex c1be5677e6..eeb453c1d3 100644--- a/saleor/webhook/models.py+++ b/saleor/webhook/models.py@@ -2,6 +2,8 @@ from django.db import modelsfrom ..app.models import Appfrom ..app.validators import AppURLValidator+from ..core.utils.json_serializer import CustomJsonEncoder+from .validators import custom_headers_validatorclass WebhookURLField(models.URLField):@@ -17,6 +19,13 @@ class Webhook(models.Model):is_active = models.BooleanField(default=True)secret_key = models.CharField(max_length=255, null=True, blank=True)subscription_query = models.TextField(null=True, blank=True)+ custom_headers = models.JSONField(+ blank=True,+ null=True,+ default=dict,+ encoder=CustomJsonEncoder,+ validators=[custom_headers_validator],+ )class Meta:ordering = ("pk",)diff --git a/saleor/webhook/tests/test_webhook_validators.py b/saleor/webhook/tests/test_webhook_validators.pynew file mode 100644index 0000000000..13327dfb58--- /dev/null+++ b/saleor/webhook/tests/test_webhook_validators.py@@ -0,0 +1,60 @@+import pytest+from django.core.exceptions import ValidationError++from ..validators import (+ HEADERS_LENGTH_LIMIT,+ HEADERS_NUMBER_LIMIT,+ custom_headers_validator,+)+++ "headers,err_msg",+ [+ (+ {+ "Key1": "Value1",+ "Key2": "Value2",+ "Key3": "Value3",+ "Key4": "Value4",+ "Key5": "Value5",+ "Key6": "Value6",+ },+ f"Number of headers exceeds the limit: {HEADERS_NUMBER_LIMIT}.",+ ),+ (+ {"Key": "Value"},+ '"Key" does not match allowed key pattern: "X-*" or "Authorization*".',+ ),+ (+ {"X-Key": 123},+ "Header must consist of strings.",+ ),+ (+ {"Ke:y": "Value"},+ 'Key "Ke:y" contains invalid character.',+ ),+ (+ {"Key": "Val:ue"},+ 'Value "Val:ue" contains invalid character.',+ ),+ (+ {"Key": "X" * HEADERS_LENGTH_LIMIT},+ f'Header with key: "Key" exceeds the limit of characters: '+ f"{HEADERS_LENGTH_LIMIT}.",+ ),+ (+ {"ABCX-Key": "Value"},+ '"ABCX-Key" does not match allowed key pattern: "X-*" or "Authorization*".',+ ),+ (+ {"ABCAuthorization-Key": "Value"},+ '"ABCAuthorization-Key" does not match allowed key pattern:'+ ' "X-*" or "Authorization*".',+ ),+ ],+)+def test_webhook_validator(headers, err_msg):+ with pytest.raises(ValidationError) as err:+ custom_headers_validator(headers)+ assert err.value.message == err_msgdiff --git a/saleor/webhook/validators.py b/saleor/webhook/validators.pynew file mode 100644index 0000000000..668c97c051--- /dev/null+++ b/saleor/webhook/validators.py@@ -0,0 +1,49 @@+from typing import Dict++from django.core.exceptions import ValidationError++HEADERS_NUMBER_LIMIT = 5+HEADERS_LENGTH_LIMIT = 998+KEY_CHARS_ALLOWED = (+ "!\"#$%&'()*+,-./0123456789;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"+ "[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"+)+VALUE_CHARS_ALLOWED = (+ "!\"#$%&'()*+,-./0123456789;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"+ "[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ \t"+)+++def custom_headers_validator(headers: Dict[str, str]) -> Dict[str, str]:+ """Validate headers in accordance with RFC5322.++ https://www.rfc-editor.org/rfc/rfc5322#section-2.2+ """+ if len(headers) > HEADERS_NUMBER_LIMIT:+ raise ValidationError(+ f"Number of headers exceeds the limit: {HEADERS_NUMBER_LIMIT}."+ )++ for key, value in headers.items():+ if not isinstance(key, str) or not isinstance(value, str):+ raise ValidationError("Header must consist of strings.")++ if len(key) + len(value) + 2 > HEADERS_LENGTH_LIMIT:+ raise ValidationError(+ f'Header with key: "{key}" exceeds the limit of characters:'+ f" {HEADERS_LENGTH_LIMIT}."+ )++ if not set(key).issubset(set(KEY_CHARS_ALLOWED)):+ raise ValidationError(f'Key "{key}" contains invalid character.')++ if not set(value).issubset(set(VALUE_CHARS_ALLOWED)):+ raise ValidationError(f'Value "{value}" contains invalid character.')++ if not (key.startswith("X-") or key.startswith("Authorization")):+ raise ValidationError(+ f'"{key}" does not match allowed key pattern: '+ f'"X-*" or "Authorization*".'+ )++ return headers