Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add identifier field to Webhook model (#19557)
Lukasz Ostrowskie9b9dcdb5a84
diff --git a/saleor/app/error_codes.py b/saleor/app/error_codes.pyindex 2d7cecf2f8..77c125e30c 100644--- a/saleor/app/error_codes.py+++ b/saleor/app/error_codes.py@@ -11,6 +11,7 @@ class AppErrorCode(Enum):INVALID_MANIFEST_FORMAT = "invalid_manifest_format"INVALID_CUSTOM_HEADERS = "invalid_custom_headers"DUPLICATED_EXTENSION_IDENTIFIER = "duplicated_extension_identifier"+ DUPLICATED_WEBHOOK_IDENTIFIER = "duplicated_webhook_identifier"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 7ccd93573f..c8e0f71e96 100644--- a/saleor/app/installation_utils.py+++ b/saleor/app/installation_utils.py@@ -309,6 +309,7 @@ def install_app(target_url=webhook["targetUrl"],subscription_query=webhook["query"],custom_headers=webhook.get("customHeaders", None),+ identifier=webhook.get("identifier"),)for webhook in manifest_data.get("webhooks", []))diff --git a/saleor/app/manifest_schema.py b/saleor/app/manifest_schema.pyindex 1e8548c334..f799063826 100644--- a/saleor/app/manifest_schema.py+++ b/saleor/app/manifest_schema.py@@ -12,6 +12,7 @@ from .types import DEFAULT_APP_TARGETfrom .validators import AppURLValidator, image_url_validatorEXTENSION_IDENTIFIER_MAX_LENGTH = 256+WEBHOOK_IDENTIFIER_MAX_LENGTH = 256_CAMEL_CONFIG = ConfigDict(extra="ignore",@@ -63,29 +64,6 @@ class ManifestExtensionSchema(BaseModel):options: dict = {}identifier: str | None = None- @field_validator("identifier")- @classmethod- def validate_identifier(cls, v: str | None) -> str | None:- """Validate the identifier length.-- Normalization (stripping whitespace, treating blank values as not- provided) happens later in ``manifest_validations``: the validated- model returned by ``model_validate`` is discarded, so any value- returned here would not reach the manifest data. Length is checked- here because it is a purely structural constraint. The raw value is- measured (whitespace included) since that is what would be persisted.- """- if v is None:- return None- if len(v) > EXTENSION_IDENTIFIER_MAX_LENGTH:- raise PydanticCustomError(- AppErrorCode.INVALID.value,- "Identifier is too long. Maximum length is "- f"{EXTENSION_IDENTIFIER_MAX_LENGTH} characters.",- {"error_code": AppErrorCode.INVALID.value},- )- return v-class ManifestWebhookSchema(BaseModel):model_config = _CAMEL_CONFIG@@ -97,6 +75,7 @@ class ManifestWebhookSchema(BaseModel):async_events: list[str] = []sync_events: list[str] = []custom_headers: dict | None = None+ identifier: str | None = None@field_validator("target_url")@classmethoddiff --git a/saleor/app/manifest_validations.py b/saleor/app/manifest_validations.pyindex 08d6a06b2e..35c7880d57 100644--- a/saleor/app/manifest_validations.py+++ b/saleor/app/manifest_validations.py@@ -24,7 +24,11 @@ from ..permission.models import Permissionfrom ..webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ..webhook.validators import custom_headers_validatorfrom .error_codes import AppErrorCode-from .manifest_schema import ManifestSchema+from .manifest_schema import (+ EXTENSION_IDENTIFIER_MAX_LENGTH,+ WEBHOOK_IDENTIFIER_MAX_LENGTH,+ ManifestSchema,+)from .models import Appfrom .types import DEFAULT_APP_TARGETfrom .validators import AppURLValidator@@ -221,10 +225,12 @@ def _clean_extensions(manifest_data, app_permissions, errors):def _clean_extension_identifier(extension, seen_identifiers, errors):- """Normalize and ensure the extension identifier is unique within the manifest.+ """Normalize, length-check and dedupe the extension identifier.Blank or whitespace-only identifiers are treated as not provided (``None``)- and may repeat freely. Non-empty identifiers must be unique per app.+ and may repeat freely. The length is measured on the stripped value (the+ value actually persisted), matching the extensionCreate/Update mutations.+ Non-empty identifiers must be unique per app."""identifier = (extension.get("identifier") or "").strip() or Noneextension["identifier"] = identifier@@ -232,6 +238,16 @@ def _clean_extension_identifier(extension, seen_identifiers, errors):if identifier is None:return+ if len(identifier) > EXTENSION_IDENTIFIER_MAX_LENGTH:+ errors["extensions"].append(+ ValidationError(+ "Identifier is too long. Maximum length is "+ f"{EXTENSION_IDENTIFIER_MAX_LENGTH} characters.",+ code=AppErrorCode.INVALID.value,+ )+ )+ return+if identifier in seen_identifiers:errors["extensions"].append(ValidationError(@@ -242,6 +258,40 @@ def _clean_extension_identifier(extension, seen_identifiers, errors):seen_identifiers.add(identifier)+def _clean_webhook_identifier(webhook, seen_identifiers, errors):+ """Normalize, length-check and dedupe the webhook identifier.++ Blank or whitespace-only identifiers are treated as not provided (``None``)+ and may repeat freely. The length is measured on the stripped value (the+ value actually persisted), matching the webhookCreate/Update mutations.+ Non-empty identifiers must be unique per app.+ """+ identifier = (webhook.get("identifier") or "").strip() or None+ webhook["identifier"] = identifier++ if identifier is None:+ return++ if len(identifier) > WEBHOOK_IDENTIFIER_MAX_LENGTH:+ errors["webhooks"].append(+ ValidationError(+ "Identifier is too long. Maximum length is "+ f"{WEBHOOK_IDENTIFIER_MAX_LENGTH} characters.",+ code=AppErrorCode.INVALID.value,+ )+ )+ return++ if identifier in seen_identifiers:+ errors["webhooks"].append(+ ValidationError(+ f"Duplicate webhook identifier: {identifier}.",+ code=AppErrorCode.DUPLICATED_WEBHOOK_IDENTIFIER.value,+ )+ )+ seen_identifiers.add(identifier)++def _clean_webhooks(manifest_data, errors):webhooks = manifest_data.get("webhooks", [])@@ -252,7 +302,10 @@ def _clean_webhooks(manifest_data, errors):str_to_enum(e_type[0]): e_type[0] for e_type in WebhookEventSyncType.CHOICES}+ seen_identifiers: set[str] = set()for webhook in webhooks:+ _clean_webhook_identifier(webhook, seen_identifiers, errors)+webhook["isActive"] = webhook.get("isActive", True)webhook["events"] = []diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.pyindex 465f1d74e5..46ad008101 100644--- a/saleor/app/tests/test_installation_utils.py+++ b/saleor/app/tests/test_installation_utils.py@@ -675,6 +675,47 @@ def test_install_app_with_webhook(assert webhook.custom_headers == {"x-key": "Value"}+def test_install_app_with_webhook_identifier(+ app_manifest, app_manifest_webhook, app_installation, monkeypatch+):+ # given+ identifier = "order-created-handler"+ app_manifest_webhook["identifier"] = identifier+ app_manifest["webhooks"] = [app_manifest_webhook]++ mocked_get_response = Mock()+ mocked_get_response.json.return_value = app_manifest+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))+ monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())++ # when+ app, _ = install_app(app_installation, activate=True)++ # then+ webhook = app.webhooks.get()+ assert webhook.identifier == identifier+++def test_install_app_with_webhook_blank_identifier_stored_as_none(+ app_manifest, app_manifest_webhook, app_installation, monkeypatch+):+ # given+ app_manifest_webhook["identifier"] = " "+ app_manifest["webhooks"] = [app_manifest_webhook]++ mocked_get_response = Mock()+ mocked_get_response.json.return_value = app_manifest+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))+ monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())++ # when+ app, _ = install_app(app_installation, activate=True)++ # then+ webhook = app.webhooks.get()+ assert webhook.identifier is None++def test_install_app_webhook_incorrect_url(app_manifest, app_manifest_webhook, app_installation, monkeypatch):diff --git a/saleor/app/tests/test_manifest_validations.py b/saleor/app/tests/test_manifest_validations.pyindex 1d3fe74282..1e2844ad71 100644--- a/saleor/app/tests/test_manifest_validations.py+++ b/saleor/app/tests/test_manifest_validations.py@@ -7,7 +7,7 @@ from ..error_codes import AppErrorCodefrom ..manifest_schema import (EXTENSION_IDENTIFIER_MAX_LENGTH,ICON_MIME_TYPES,- ManifestExtensionSchema,+ WEBHOOK_IDENTIFIER_MAX_LENGTH,ManifestSchema,)from ..manifest_validations import clean_manifest_data@@ -436,6 +436,17 @@ def _extension(label, identifier=None):return extension+def _webhook(name, identifier=None):+ webhook = {+ "name": name,+ "targetUrl": "https://example.com/webhook",+ "query": "subscription { event { ... on OrderCreated { order { id } } } }",+ }+ if identifier is not None:+ webhook["identifier"] = identifier+ return webhook++@pytest.mark.django_dbdef test_clean_manifest_data_accepts_unique_extension_identifiers():# given - two extensions with distinct identifiers@@ -573,37 +584,172 @@ def test_clean_manifest_data_rejects_too_long_identifier():assert error.message == expected_message-def test_manifest_extension_schema_rejects_too_long_identifier():+def test_clean_manifest_data_length_check_ignores_surrounding_whitespace():+ # given - at-max identifier padded with whitespace: over the limit raw,+ # at the limit once stripped (the value that is actually persisted)+ stripped = "a" * EXTENSION_IDENTIFIER_MAX_LENGTH+ manifest_data = {+ **MINIMAL_MANIFEST,+ "extensions": [_extension("First", identifier=f" {stripped} ")],+ }++ # when+ clean_manifest_data(manifest_data)++ # then+ assert manifest_data["extensions"][0]["identifier"] == stripped+++def test_clean_manifest_data_accepts_unique_webhook_identifiers():+ # given - two webhooks with distinct identifiers+ manifest_data = {+ **MINIMAL_MANIFEST,+ "webhooks": [+ _webhook("First", identifier="first-webhook"),+ _webhook("Second", identifier="second-webhook"),+ ],+ }++ # when+ clean_manifest_data(manifest_data)++ # then - identifiers are preserved on the cleaned manifest+ assert manifest_data["webhooks"][0]["identifier"] == "first-webhook"+ assert manifest_data["webhooks"][1]["identifier"] == "second-webhook"+++def test_clean_manifest_data_rejects_duplicate_webhook_identifiers():+ # given - two webhooks reuse the same identifier within one manifest+ duplicate_identifier = "order-created-handler"+ manifest_data = {+ **MINIMAL_MANIFEST,+ "webhooks": [+ _webhook("First", identifier=duplicate_identifier),+ _webhook("Second", identifier=duplicate_identifier),+ ],+ }++ # when+ with pytest.raises(ValidationError) as exc_info:+ clean_manifest_data(manifest_data)++ # then+ webhook_errors = exc_info.value.error_dict["webhooks"]+ assert len(webhook_errors) == 1+ error = webhook_errors[0]+ assert error.code == AppErrorCode.DUPLICATED_WEBHOOK_IDENTIFIER.value+ assert error.message == f"Duplicate webhook identifier: {duplicate_identifier}."+++def test_clean_manifest_data_allows_multiple_webhooks_without_identifier():+ # given - several webhooks omit the identifier entirely+ manifest_data = {+ **MINIMAL_MANIFEST,+ "webhooks": [_webhook("First"), _webhook("Second")],+ }++ # when+ clean_manifest_data(manifest_data)++ # then - absent identifiers are normalized to None and do not collide+ assert manifest_data["webhooks"][0]["identifier"] is None+ assert manifest_data["webhooks"][1]["identifier"] is None+++def test_clean_manifest_data_coerces_blank_webhook_identifier_to_none():+ # given - blank and whitespace-only identifiers+ manifest_data = {+ **MINIMAL_MANIFEST,+ "webhooks": [+ _webhook("First", identifier=" "),+ _webhook("Second", identifier=""),+ ],+ }++ # when+ clean_manifest_data(manifest_data)++ # then - both are treated as not provided, so no duplicate error is raised+ assert manifest_data["webhooks"][0]["identifier"] is None+ assert manifest_data["webhooks"][1]["identifier"] is None+++def test_clean_manifest_data_strips_surrounding_whitespace_from_webhook_identifier():+ # given - identifier padded with whitespace+ manifest_data = {+ **MINIMAL_MANIFEST,+ "webhooks": [_webhook("First", identifier=" order-created ")],+ }++ # when+ clean_manifest_data(manifest_data)++ # then+ assert manifest_data["webhooks"][0]["identifier"] == "order-created"+++def test_clean_manifest_data_accepts_webhook_identifier_at_max_length():+ # given - identifier exactly at the maximum allowed length+ identifier = "a" * WEBHOOK_IDENTIFIER_MAX_LENGTH+ manifest_data = {+ **MINIMAL_MANIFEST,+ "webhooks": [_webhook("First", identifier=identifier)],+ }++ # when+ clean_manifest_data(manifest_data)++ # then+ assert manifest_data["webhooks"][0]["identifier"] == identifier+++def test_clean_manifest_data_rejects_too_long_webhook_identifier():# given - identifier exceeding the maximum allowed length- identifier = "a" * (EXTENSION_IDENTIFIER_MAX_LENGTH + 1)- extension_data = _extension("First", identifier=identifier)+ identifier = "a" * (WEBHOOK_IDENTIFIER_MAX_LENGTH + 1)+ manifest_data = {+ **MINIMAL_MANIFEST,+ "webhooks": [_webhook("First", identifier=identifier)],+ }# when- with pytest.raises(PydanticValidationError) as exc_info:- ManifestExtensionSchema.model_validate(extension_data)+ with pytest.raises(ValidationError) as exc_info:+ clean_manifest_data(manifest_data)# thenexpected_message = (f"Identifier is too long. Maximum length is "- f"{EXTENSION_IDENTIFIER_MAX_LENGTH} characters."+ f"{WEBHOOK_IDENTIFIER_MAX_LENGTH} characters.")- errors = exc_info.value.errors()- assert len(errors) == 1- assert errors[0]["loc"] == ("identifier",)- assert errors[0]["msg"] == expected_message- assert errors[0]["ctx"]["error_code"] == AppErrorCode.INVALID.value+ webhook_errors = exc_info.value.error_dict["webhooks"]+ assert len(webhook_errors) == 1+ error = webhook_errors[0]+ assert error.code == AppErrorCode.INVALID.value+ assert error.message == expected_message-def test_manifest_extension_schema_accepts_identifier_at_max_length():- # given - identifier exactly at the maximum allowed length- identifier = "a" * EXTENSION_IDENTIFIER_MAX_LENGTH- extension_data = _extension("First", identifier=identifier)+def test_clean_manifest_data_webhook_length_check_ignores_surrounding_whitespace():+ # given - at-max identifier padded with whitespace: over the limit raw,+ # at the limit once stripped (the value that is actually persisted)+ stripped = "a" * WEBHOOK_IDENTIFIER_MAX_LENGTH+ manifest_data = {+ **MINIMAL_MANIFEST,+ "webhooks": [_webhook("First", identifier=f" {stripped} ")],+ }# when- schema = ManifestExtensionSchema.model_validate(extension_data)+ clean_manifest_data(manifest_data)# then- assert schema.identifier == identifier+ assert manifest_data["webhooks"][0]["identifier"] == strippeddef test_manifest_schema_deprecated_fields_accepted():diff --git a/saleor/graphql/core/utils/error_codes.py b/saleor/graphql/core/utils/error_codes.pyindex a980cce071..32548b2ae3 100644--- a/saleor/graphql/core/utils/error_codes.py+++ b/saleor/graphql/core/utils/error_codes.py@@ -37,7 +37,7 @@ def get_error_code_from_error(error) -> str:code = error.codeif code in ["required", "blank", "null"]:return "required"- if code in ["unique", "unique_for_date"]:+ if code in ["unique", "unique_for_date", "unique_together"]:return "unique"if (code is Nonediff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 4a6952d360..c599506c5a 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1658,6 +1658,13 @@ type Webhook implements Node @doc(category: "Webhooks") {"""The name of webhook."""name: String+ """+ The unique identifier of the webhook, set by the app. Unique per app, null when not set.++ Added in Saleor 3.23.+ """+ identifier: String+"""List of webhook events."""events: [WebhookEvent!]! @deprecated(reason: "Use `asyncEvents` or `syncEvents` instead.")@@ -22352,6 +22359,13 @@ input WebhookCreateInput @doc(category: "Webhooks") {"""The name of the webhook."""name: String+ """+ The unique identifier of the webhook, set by the app. Unique per app. Maximum length is 256 characters.++ Added in Saleor 3.23.+ """+ identifier: String+"""The url to receive the payload."""targetUrl: String@@ -22408,6 +22422,13 @@ input WebhookUpdateInput @doc(category: "Webhooks") {"""The new name of the webhook."""name: String+ """+ The unique identifier of the webhook, set by the app. Unique per app. Maximum length is 256 characters. Pass a blank value to clear it.++ Added in Saleor 3.23.+ """+ identifier: String+"""The url to receive the payload."""targetUrl: String@@ -32271,6 +32292,7 @@ enum AppErrorCode @doc(category: "Apps") {INVALID_MANIFEST_FORMATINVALID_CUSTOM_HEADERSDUPLICATED_EXTENSION_IDENTIFIER+ DUPLICATED_WEBHOOK_IDENTIFIERMANIFEST_URL_CANT_CONNECTNOT_FOUNDREQUIREDdiff --git a/saleor/graphql/webhook/mutations/webhook_create.py b/saleor/graphql/webhook/mutations/webhook_create.pyindex a8985e1108..23cb7d41d2 100644--- a/saleor/graphql/webhook/mutations/webhook_create.py+++ b/saleor/graphql/webhook/mutations/webhook_create.py@@ -14,7 +14,7 @@ from ....webhook.validators import (from ...app.dataloaders import get_app_promisefrom ...app.utils import validate_app_is_not_removedfrom ...core import ResolveInfo-from ...core.descriptions import DEPRECATED_IN_3X_INPUT+from ...core.descriptions import ADDED_IN_323, DEPRECATED_IN_3X_INPUTfrom ...core.doc_category import DOC_CATEGORY_WEBHOOKSfrom ...core.fields import JSONStringfrom ...core.mutations import DeprecatedModelMutation@@ -28,6 +28,13 @@ from ..types import Webhookclass WebhookCreateInput(BaseInputObjectType):name = graphene.String(description="The name of the webhook.", required=False)+ identifier = graphene.String(+ description=(+ "The unique identifier of the webhook, set by the app. Unique per "+ "app. Maximum length is 256 characters." + ADDED_IN_323+ ),+ required=False,+ )target_url = graphene.String(description="The url to receive the payload.")events = NonNullList(enums.WebhookEventTypeEnum,@@ -93,6 +100,16 @@ class WebhookCreate(DeprecatedModelMutation, NotifyUserEventValidationMixin):@classmethoddef clean_input(cls, info: ResolveInfo, instance, data, **kwargs):cleaned_data = super().clean_input(info, instance, data, **kwargs)++ if "identifier" in cleaned_data:+ # Treat blank/whitespace-only as "unset" (NULL). This matches the+ # manifest normalization and keeps the identifier out of the+ # not-blank CheckConstraint. Uniqueness and max length are enforced+ # by the model's full_clean during clean_instance.+ cleaned_data["identifier"] = (+ cleaned_data["identifier"] or ""+ ).strip() or None+app = cleaned_data.get("app")# We are not able to check it in `check_permission`.diff --git a/saleor/graphql/webhook/mutations/webhook_update.py b/saleor/graphql/webhook/mutations/webhook_update.pyindex 0e794d4f52..feba53112a 100644--- a/saleor/graphql/webhook/mutations/webhook_update.py+++ b/saleor/graphql/webhook/mutations/webhook_update.py@@ -8,7 +8,7 @@ from ....webhook import modelsfrom ....webhook.validators import HEADERS_LENGTH_LIMIT, HEADERS_NUMBER_LIMITfrom ...app.dataloaders import get_app_promisefrom ...core import ResolveInfo-from ...core.descriptions import DEPRECATED_IN_3X_INPUT+from ...core.descriptions import ADDED_IN_323, DEPRECATED_IN_3X_INPUTfrom ...core.doc_category import DOC_CATEGORY_WEBHOOKSfrom ...core.fields import JSONStringfrom ...core.types import BaseInputObjectType, NonNullList, WebhookError@@ -20,6 +20,14 @@ from . import WebhookCreateclass WebhookUpdateInput(BaseInputObjectType):name = graphene.String(description="The new name of the webhook.", required=False)+ identifier = graphene.String(+ description=(+ "The unique identifier of the webhook, set by the app. Unique per "+ "app. Maximum length is 256 characters. Pass a blank value to clear "+ "it." + ADDED_IN_323+ ),+ required=False,+ )target_url = graphene.String(description="The url to receive the payload.", required=False)diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_create.py b/saleor/graphql/webhook/tests/mutations/test_webhook_create.pyindex 96e001a3fb..07c94ff6bf 100644--- a/saleor/graphql/webhook/tests/mutations/test_webhook_create.py+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_create.py@@ -20,6 +20,7 @@ WEBHOOK_CREATE = """}webhook {id+ identifierasyncEvents {eventType}@@ -71,6 +72,137 @@ def test_webhook_create_by_app(app_api_client, permission_manage_orders):assert events[0].event_type == WebhookEventTypeAsyncEnum.ORDER_CREATED.value+def test_webhook_create_with_identifier(app_api_client, permission_manage_orders):+ # given+ identifier = "order-created-handler"+ variables = {+ "input": {+ "name": "New integration",+ "identifier": identifier,+ "targetUrl": "https://www.example.com",+ "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],+ }+ }++ # when+ response = app_api_client.post_graphql(+ WEBHOOK_CREATE,+ variables=variables,+ permissions=[permission_manage_orders],+ check_no_permissions=False,+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["webhookCreate"]+ assert data["errors"] == []+ assert data["webhook"]["identifier"] == identifier+ assert Webhook.objects.get().identifier == identifier+++def test_webhook_create_blank_identifier_stored_as_none(+ app_api_client, permission_manage_orders+):+ # given+ variables = {+ "input": {+ "name": "New integration",+ "identifier": " ",+ "targetUrl": "https://www.example.com",+ "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],+ }+ }++ # when+ response = app_api_client.post_graphql(+ WEBHOOK_CREATE,+ variables=variables,+ permissions=[permission_manage_orders],+ check_no_permissions=False,+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["webhookCreate"]+ assert data["errors"] == []+ assert data["webhook"]["identifier"] is None+ assert Webhook.objects.get().identifier is None+++def test_webhook_create_duplicate_identifier_for_same_app(+ app_api_client, permission_manage_orders+):+ # given - the app already owns a webhook with this identifier+ identifier = "order-created-handler"+ app = app_api_client.app+ Webhook.objects.create(+ app=app, target_url="https://www.example.com/existing", identifier=identifier+ )+ variables = {+ "input": {+ "name": "New integration",+ "identifier": identifier,+ "targetUrl": "https://www.example.com",+ "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],+ }+ }++ # when+ response = app_api_client.post_graphql(+ WEBHOOK_CREATE,+ variables=variables,+ permissions=[permission_manage_orders],+ check_no_permissions=False,+ )++ # then - rejected and no second webhook created+ content = get_graphql_content(response)+ data = content["data"]["webhookCreate"]+ assert data["errors"] == [+ {+ "field": None,+ "message": "Webhook with this App and Identifier already exists.",+ "code": WebhookErrorCode.UNIQUE.name,+ }+ ]+ assert data["webhook"] is None+ assert Webhook.objects.filter(app=app, identifier=identifier).count() == 1+++def test_webhook_create_too_long_identifier(app_api_client, permission_manage_orders):+ # given+ identifier = "a" * 257+ variables = {+ "input": {+ "name": "New integration",+ "identifier": identifier,+ "targetUrl": "https://www.example.com",+ "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],+ }+ }++ # when+ response = app_api_client.post_graphql(+ WEBHOOK_CREATE,+ variables=variables,+ permissions=[permission_manage_orders],+ check_no_permissions=False,+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["webhookCreate"]+ assert data["errors"] == [+ {+ "field": "identifier",+ "message": "Ensure this value has at most 256 characters (it has 257).",+ "code": WebhookErrorCode.INVALID.name,+ }+ ]+ assert data["webhook"] is None+ assert Webhook.objects.exists() is False++def test_webhook_create_inactive_app(app_api_client, app, permission_manage_orders):# givenapp.is_active = Falsediff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_update.py b/saleor/graphql/webhook/tests/mutations/test_webhook_update.pyindex 85fe987e36..c819001479 100644--- a/saleor/graphql/webhook/tests/mutations/test_webhook_update.py+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_update.py@@ -5,6 +5,7 @@ import grapheneimport pytestfrom .....app.models import App+from .....webhook.models import Webhookfrom ....core.enums import WebhookErrorCodefrom ....tests.utils import assert_no_permission, get_graphql_contentfrom ...enums import WebhookEventTypeAsyncEnum@@ -18,6 +19,7 @@ WEBHOOK_UPDATE = """code}webhook {+ identifiersyncEvents {eventType}@@ -67,6 +69,70 @@ def test_webhook_update_by_app(app_api_client, app, webhook):assert data["webhook"]["customHeaders"] == json.dumps(custom_headers)+def test_webhook_update_identifier(app_api_client, webhook):+ # given+ identifier = "order-created-handler"+ assert webhook.identifier is None+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {"id": webhook_id, "input": {"identifier": identifier}}++ # when+ response = app_api_client.post_graphql(WEBHOOK_UPDATE, variables=variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["webhookUpdate"]+ assert not data["errors"]+ assert data["webhook"]["identifier"] == identifier+ webhook.refresh_from_db()+ assert webhook.identifier == identifier+++def test_webhook_update_blank_identifier_clears_it(app_api_client, webhook):+ # given+ webhook.identifier = "order-created-handler"+ webhook.save(update_fields=["identifier"])+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {"id": webhook_id, "input": {"identifier": " "}}++ # when+ response = app_api_client.post_graphql(WEBHOOK_UPDATE, variables=variables)++ # then - blank clears the identifier back to NULL+ content = get_graphql_content(response)+ data = content["data"]["webhookUpdate"]+ assert not data["errors"]+ assert data["webhook"]["identifier"] is None+ webhook.refresh_from_db()+ assert webhook.identifier is None+++def test_webhook_update_duplicate_identifier_for_same_app(app_api_client, app, webhook):+ # given - the app owns another webhook already using the target identifier+ identifier = "order-created-handler"+ Webhook.objects.create(+ app=app, target_url="https://www.example.com/other", identifier=identifier+ )+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {"id": webhook_id, "input": {"identifier": identifier}}++ # when+ response = app_api_client.post_graphql(WEBHOOK_UPDATE, variables=variables)++ # then - rejected and the webhook keeps its previous (unset) identifier+ content = get_graphql_content(response)+ data = content["data"]["webhookUpdate"]+ assert data["errors"] == [+ {+ "field": None,+ "message": "Webhook with this App and Identifier already exists.",+ "code": WebhookErrorCode.UNIQUE.name,+ }+ ]+ webhook.refresh_from_db()+ assert webhook.identifier is None++def test_webhook_update_by_other_app(app_api_client, webhook):# givenother_app = App.objects.create(name="other")diff --git a/saleor/graphql/webhook/tests/queries/test_webhook.py b/saleor/graphql/webhook/tests/queries/test_webhook.pyindex 0b0538cb9d..f44fcfda62 100644--- a/saleor/graphql/webhook/tests/queries/test_webhook.py+++ b/saleor/graphql/webhook/tests/queries/test_webhook.py@@ -15,6 +15,7 @@ QUERY_WEBHOOK = """idisActivename+ identifiersubscriptionQueryasyncEvents {eventType@@ -39,12 +40,33 @@ def test_query_webhook_by_staff(staff_api_client, webhook, permission_manage_appwebhook_response = content["data"]["webhook"]assert webhook_response["id"] == webhook_idassert webhook_response["isActive"] == webhook.is_active+ assert webhook_response["identifier"] == webhook.identifierassert webhook_response["subscriptionQuery"] is Noneevents = webhook.events.all()assert len(events) == 1assert events[0].event_type == WebhookEventTypeAsyncEnum.ORDER_CREATED.value+def test_query_webhook_identifier_by_staff(+ staff_api_client, webhook, permission_manage_apps+):+ # given+ identifier = "order-created-handler"+ webhook.identifier = identifier+ webhook.save(update_fields=["identifier"])+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {"id": webhook_id}+ staff_api_client.user.user_permissions.add(permission_manage_apps)++ # when+ response = staff_api_client.post_graphql(QUERY_WEBHOOK, variables=variables)++ # then+ content = get_graphql_content(response)+ webhook_response = content["data"]["webhook"]+ assert webhook_response["identifier"] == identifier++def test_query_webhook_with_subscription_query_by_staff(staff_api_client, subscription_order_created_webhook, permission_manage_apps):@@ -107,6 +129,23 @@ def test_query_webhook_by_app(app_api_client, webhook):assert events[0].event_type == WebhookEventTypeAsyncEnum.ORDER_CREATED.value+def test_query_webhook_identifier_by_app(app_api_client, webhook):+ # given+ identifier = "order-created-handler"+ webhook.identifier = identifier+ webhook.save(update_fields=["identifier"])+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {"id": webhook_id}++ # when+ response = app_api_client.post_graphql(QUERY_WEBHOOK, variables=variables)++ # then+ content = get_graphql_content(response)+ webhook_response = content["data"]["webhook"]+ assert webhook_response["identifier"] == identifier++def test_query_webhook_by_app_without_permission(app_api_client):second_app = App.objects.create(name="Sample app account", is_active=True)webhook = Webhook.objects.create(diff --git a/saleor/graphql/webhook/types.py b/saleor/graphql/webhook/types.pyindex c57f415143..812ded558c 100644--- a/saleor/graphql/webhook/types.py+++ b/saleor/graphql/webhook/types.py@@ -11,6 +11,7 @@ from ..core.connection import (filter_connection_queryset,)from ..core.context import get_database_connection_name+from ..core.descriptions import ADDED_IN_323from ..core.fields import FilterConnectionField, JSONStringfrom ..core.scalars import DateTimefrom ..core.types import ModelObjectType, NonNullList@@ -155,6 +156,13 @@ class EventDeliveryCountableConnection(CountableConnection):class Webhook(ModelObjectType[models.Webhook]):id = graphene.GlobalID(required=True, description="The ID of webhook.")name = graphene.String(required=False, description="The name of webhook.")+ identifier = graphene.String(+ required=False,+ description=(+ "The unique identifier of the webhook, set by the app. Unique per "+ "app, null when not set." + ADDED_IN_323+ ),+ )events = NonNullList(WebhookEvent,description="List of webhook events.",diff --git a/saleor/webhook/migrations/0013_webhook_identifier_and_more.py b/saleor/webhook/migrations/0013_webhook_identifier_and_more.pynew file mode 100644index 0000000000..d5d0037b85--- /dev/null+++ b/saleor/webhook/migrations/0013_webhook_identifier_and_more.py@@ -0,0 +1,22 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("webhook", "0012_webhook_filterable_channel_slugs_idx"),+ ]++ operations = [+ migrations.AddField(+ model_name="webhook",+ name="identifier",+ field=models.CharField(blank=True, max_length=256, null=True),+ ),+ migrations.AddConstraint(+ model_name="webhook",+ constraint=models.CheckConstraint(+ condition=~models.Q(identifier=""),+ name="webhook_identifier_not_blank",+ ),+ ),+ ]diff --git a/saleor/webhook/migrations/0014_webhook_identifier_unique_constraint.py b/saleor/webhook/migrations/0014_webhook_identifier_unique_constraint.pynew file mode 100644index 0000000000..304f2d970c--- /dev/null+++ b/saleor/webhook/migrations/0014_webhook_identifier_unique_constraint.py@@ -0,0 +1,49 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ # The unique index is built CONCURRENTLY so it does not hold an ACCESS+ # EXCLUSIVE lock on webhook_webhook while it is created. CONCURRENTLY+ # cannot run inside a transaction, hence atomic = False and its own+ # migration, separate from the fast, atomic schema changes in 0013.+ atomic = False++ dependencies = [+ ("webhook", "0013_webhook_identifier_and_more"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ database_operations=[+ migrations.RunSQL(+ sql="""+ CREATE UNIQUE INDEX CONCURRENTLY unique_webhook_identifier+ ON webhook_webhook ("app_id", "identifier");+ """,+ reverse_sql="""+ DROP INDEX CONCURRENTLY IF EXISTS unique_webhook_identifier;+ """,+ ),+ migrations.RunSQL(+ sql="""+ ALTER TABLE webhook_webhook+ ADD CONSTRAINT unique_webhook_identifier+ UNIQUE USING INDEX unique_webhook_identifier;+ """,+ reverse_sql="""+ ALTER TABLE webhook_webhook DROP CONSTRAINT+ IF EXISTS unique_webhook_identifier;+ """,+ ),+ ],+ state_operations=[+ migrations.AddConstraint(+ model_name="webhook",+ constraint=models.UniqueConstraint(+ fields=("app", "identifier"),+ name="unique_webhook_identifier",+ ),+ ),+ ],+ ),+ ]diff --git a/saleor/webhook/models.py b/saleor/webhook/models.pyindex 27d61f179e..8003aea8d9 100644--- a/saleor/webhook/models.py+++ b/saleor/webhook/models.py@@ -35,6 +35,12 @@ class Webhook(models.Model):default=list,size=MAX_FILTERABLE_CHANNEL_SLUGS_LIMIT,)+ # blank=True is required because webhookCreate/webhookUpdate run full_clean:+ # Django's field validation rejects an unset value (None is in empty_values)+ # when blank=False, even with null=True, which would break every mutation+ # that doesn't set an identifier. Empty string stays blocked by the+ # identifier_not_blank CheckConstraint below.+ identifier = models.CharField(max_length=256, null=True, blank=True)class Meta:ordering = ("pk",)@@ -44,6 +50,16 @@ class Webhook(models.Model):fields=["filterable_channel_slugs"],)]+ constraints = [+ models.UniqueConstraint(+ fields=["app", "identifier"],+ name="unique_webhook_identifier",+ ),+ models.CheckConstraint(+ condition=~models.Q(identifier=""),+ name="webhook_identifier_not_blank",+ ),+ ]def __str__(self):return self.namediff --git a/saleor/webhook/tests/test_models.py b/saleor/webhook/tests/test_models.pynew file mode 100644index 0000000000..3fa819b164--- /dev/null+++ b/saleor/webhook/tests/test_models.py@@ -0,0 +1,49 @@+import pytest+from django.db import IntegrityError+from django.db.transaction import atomic++from ...app.models import App+from ..models import Webhook++TARGET_URL = "http://www.example.com/test"+++def test_webhook_identifier_must_be_unique_per_app(app):+ # given+ identifier = "order-created-handler"+ Webhook.objects.create(app=app, target_url=TARGET_URL, identifier=identifier)++ # when / then - reusing the identifier within the same app is rejected+ with pytest.raises(IntegrityError, match="unique_webhook_identifier"), atomic():+ Webhook.objects.create(app=app, target_url=TARGET_URL, identifier=identifier)+++def test_webhook_identifier_can_be_reused_across_apps(app):+ # given+ identifier = "order-created-handler"+ other_app = App.objects.create(name="Other app")+ Webhook.objects.create(app=app, target_url=TARGET_URL, identifier=identifier)++ # when - a different app uses the same identifier+ webhook = Webhook.objects.create(+ app=other_app, target_url=TARGET_URL, identifier=identifier+ )++ # then+ assert webhook.identifier == identifier+++def test_webhook_allows_multiple_null_identifiers_per_app(app):+ # given / when - two webhooks of the same app omit the identifier+ first = Webhook.objects.create(app=app, target_url=TARGET_URL)+ second = Webhook.objects.create(app=app, target_url=TARGET_URL)++ # then - NULL identifiers are exempt from the uniqueness constraint+ assert first.identifier is None+ assert second.identifier is None+++def test_webhook_identifier_cannot_be_blank(app):+ # given / when / then - a blank identifier is rejected at the database level+ with pytest.raises(IntegrityError, match="webhook_identifier_not_blank"), atomic():+ Webhook.objects.create(app=app, target_url=TARGET_URL, identifier="")