Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Allow apps to reference their own webhooks by identifier (#19576)

Lukasz Ostrowski3f5a82c96b2f
diff --git a/docs/adr/0008-webhook-identifier-is-an-app-only-pointer.md b/docs/adr/0008-webhook-identifier-is-an-app-only-pointer.md
new file mode 100644
index 0000000000..4a78f3c0bb
--- /dev/null
+++ b/docs/adr/0008-webhook-identifier-is-an-app-only-pointer.md
@@ -0,0 +1,19 @@
+# Webhook identifier is an app-only pointer
+
+**Tags:** webhook, app, graphql, permissions
+
+`webhookUpdate` and `webhookDelete` accept `identifier` as an alternative to `id`, but only from
+an app referencing its own webhook. Staff users must use `id`.
+
+`Webhook.identifier` is unique per app, not globally, so it names a single webhook only once an
+app scope is fixed, and the caller's own app is the only scope we accept. The pointer exists
+because of an asymmetry in what each client knows: an app learns its identifiers from its own
+manifest but never learns the global IDs Saleor assigns, so without it an app must list and match
+its webhooks before mutating one. Staff have the inverse problem — the dashboard hands them global
+IDs — so an identifier pointer buys them nothing.
+
+The obvious extension is an `app` argument letting staff disambiguate. **Do not add it without
+revisiting this decision.** It was considered and rejected: no known caller needs it, and it costs
+four extra validation branches (`identifier` without `app`, `app` without `identifier`, `app`
+contradicting `id`, an app naming someone else's `app`). Adding an optional argument later is
+backward compatible, so nothing is foreclosed.
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 557c9953be..0bb288a8b5 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -17782,8 +17782,15 @@ type Mutation {
Requires one of the following permissions: MANAGE_APPS, AUTHENTICATED_APP.
"""
webhookDelete(
- """ID of a webhook to delete."""
- id: ID!
+ """ID of a webhook to delete. Cannot be used together with `identifier`."""
+ id: ID
+
+ """
+ App-provided identifier of a webhook to delete. Identifiers are unique per app only, so this argument is available exclusively to an app referencing its own webhook; staff users must use `id`. Cannot be used together with `id`.
+
+ Added in Saleor 3.23.
+ """
+ identifier: String
): WebhookDelete @doc(category: "Webhooks")
"""
@@ -17792,8 +17799,15 @@ type Mutation {
Requires one of the following permissions: MANAGE_APPS, AUTHENTICATED_APP.
"""
webhookUpdate(
- """ID of a webhook to update."""
- id: ID!
+ """ID of a webhook to update. Cannot be used together with `identifier`."""
+ id: ID
+
+ """
+ App-provided identifier of a webhook to update. Identifiers are unique per app only, so this argument is available exclusively to an app referencing its own webhook; staff users must use `id`. Cannot be used together with `id`.
+
+ Added in Saleor 3.23.
+ """
+ identifier: String
"""Fields required to update a webhook."""
input: WebhookUpdateInput!
diff --git a/saleor/graphql/webhook/mutations/utils.py b/saleor/graphql/webhook/mutations/utils.py
new file mode 100644
index 0000000000..dcc1c56d9d
--- /dev/null
+++ b/saleor/graphql/webhook/mutations/utils.py
@@ -0,0 +1,46 @@
+from typing import cast
+
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....app.models import App
+from ....webhook.error_codes import WebhookErrorCode
+from ...core.validators import validate_one_of_args_is_in_mutation
+
+
+def get_webhook_object_id(
+ *, app: App | None, object_id: str | None, identifier: str | None
+) -> str:
+ """Resolve a webhook pointer (`id` or `identifier`) to a global ID.
+
+ `identifier` is accepted only from an app referencing its own webhook, and a falsy
+ one counts as not provided. See
+ `docs/adr/0008-webhook-identifier-is-an-app-only-pointer.md`.
+ """
+ validate_one_of_args_is_in_mutation("id", object_id, "identifier", identifier)
+ if not identifier:
+ # the validation above guarantees `object_id` is set
+ return cast(str, object_id)
+ if app is None:
+ raise ValidationError(
+ {
+ "identifier": ValidationError(
+ "Webhook identifier can only be used by an app to reference its "
+ "own webhook. Use `id` instead.",
+ code=WebhookErrorCode.INVALID.value,
+ )
+ }
+ )
+ webhook_pk = (
+ app.webhooks.filter(identifier=identifier).values_list("pk", flat=True).first()
+ )
+ if webhook_pk is None:
+ raise ValidationError(
+ {
+ "identifier": ValidationError(
+ f"Couldn't resolve to a node: {identifier}",
+ code=WebhookErrorCode.NOT_FOUND.value,
+ )
+ }
+ )
+ return graphene.Node.to_global_id("Webhook", webhook_pk)
diff --git a/saleor/graphql/webhook/mutations/webhook_delete.py b/saleor/graphql/webhook/mutations/webhook_delete.py
index 8a3da535a9..ad5f6e5fa6 100644
--- a/saleor/graphql/webhook/mutations/webhook_delete.py
+++ b/saleor/graphql/webhook/mutations/webhook_delete.py
@@ -10,14 +10,30 @@ from ....webhook import models
from ....webhook.error_codes import WebhookErrorCode
from ...app.dataloaders import get_app_promise
from ...core import ResolveInfo
+from ...core.descriptions import ADDED_IN_323
from ...core.mutations import ModelDeleteMutation
from ...core.types import WebhookError
from ..types import Webhook
+from .utils import get_webhook_object_id
class WebhookDelete(ModelDeleteMutation):
class Arguments:
- id = graphene.ID(required=True, description="ID of a webhook to delete.")
+ id = graphene.ID(
+ required=False,
+ description=(
+ "ID of a webhook to delete. Cannot be used together with `identifier`."
+ ),
+ )
+ identifier = graphene.String(
+ required=False,
+ description=(
+ "App-provided identifier of a webhook to delete. Identifiers are "
+ "unique per app only, so this argument is available exclusively to an "
+ "app referencing its own webhook; staff users must use `id`. Cannot "
+ "be used together with `id`." + ADDED_IN_323
+ ),
+ )
class Meta:
description = (
@@ -38,12 +54,17 @@ class WebhookDelete(ModelDeleteMutation):
@classmethod
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
app = get_app_promise(info.context).get()
- node_id: str = data["id"]
if app and not app.is_active:
raise ValidationError(
"App needs to be active to delete webhook",
code=WebhookErrorCode.INVALID.value,
)
+ node_id = get_webhook_object_id(
+ app=app,
+ object_id=data.get("id"),
+ identifier=data.pop("identifier", None),
+ )
+ data["id"] = node_id
apps = App.objects.filter(removed_at__isnull=True)
webhook = cls.get_node_or_error(
info,
diff --git a/saleor/graphql/webhook/mutations/webhook_update.py b/saleor/graphql/webhook/mutations/webhook_update.py
index feba53112a..b3bb80e140 100644
--- a/saleor/graphql/webhook/mutations/webhook_update.py
+++ b/saleor/graphql/webhook/mutations/webhook_update.py
@@ -16,6 +16,7 @@ from .. import enums
from ..mixins import NotifyUserEventValidationMixin
from ..types import Webhook
from . import WebhookCreate
+from .utils import get_webhook_object_id
class WebhookUpdateInput(BaseInputObjectType):
@@ -80,7 +81,21 @@ class WebhookUpdateInput(BaseInputObjectType):
class WebhookUpdate(WebhookCreate, NotifyUserEventValidationMixin):
class Arguments:
- id = graphene.ID(required=True, description="ID of a webhook to update.")
+ id = graphene.ID(
+ required=False,
+ description=(
+ "ID of a webhook to update. Cannot be used together with `identifier`."
+ ),
+ )
+ identifier = graphene.String(
+ required=False,
+ description=(
+ "App-provided identifier of a webhook to update. Identifiers are "
+ "unique per app only, so this argument is available exclusively to an "
+ "app referencing its own webhook; staff users must use `id`. Cannot "
+ "be used together with `id`." + ADDED_IN_323
+ ),
+ )
input = WebhookUpdateInput(
description="Fields required to update a webhook.", required=True
)
@@ -113,8 +128,14 @@ class WebhookUpdate(WebhookCreate, NotifyUserEventValidationMixin):
@classmethod
def get_instance(cls, info: ResolveInfo, **data):
apps = App.objects.filter(removed_at__isnull=True)
- if app := get_app_promise(info.context).get():
+ app = get_app_promise(info.context).get()
+ if app:
apps = apps.filter(id=app.id)
+ data["id"] = get_webhook_object_id(
+ app=app,
+ object_id=data.get("id"),
+ identifier=data.pop("identifier", None),
+ )
data["qs"] = models.Webhook.objects.filter(
Exists(apps.filter(id=OuterRef("app_id")))
)
diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_delete.py b/saleor/graphql/webhook/tests/mutations/test_webhook_delete.py
index 608d3114d6..4294859cfd 100644
--- a/saleor/graphql/webhook/tests/mutations/test_webhook_delete.py
+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_delete.py
@@ -1,6 +1,7 @@
from unittest.mock import Mock, patch
import graphene
+import pytest
from django.db import IntegrityError
from .....app.models import App
@@ -165,3 +166,231 @@ def test_webhook_delete_by_staff_for_removed_app(
assert app_data["webhook"] is None
assert app_data["errors"][0]["code"] == WebhookErrorCode.NOT_FOUND.name
assert app_data["errors"][0]["field"] == "id"
+
+
+WEBHOOK_DELETE_BY_POINTER = """
+ mutation webhookDelete($id: ID, $identifier: String) {
+ webhookDelete(id: $id, identifier: $identifier) {
+ errors {
+ field
+ message
+ code
+ }
+ webhook {
+ id
+ }
+ }
+ }
+"""
+
+STAFF_POINTER_MESSAGE = (
+ "Webhook identifier can only be used by an app to reference its own webhook. "
+ "Use `id` instead."
+)
+POINTER_REQUIRED_MESSAGE = "At least one of arguments is required: 'id', 'identifier'."
+POINTER_COMBINED_MESSAGE = "Argument 'id' cannot be combined with 'identifier'"
+
+
+def test_webhook_delete_by_identifier(app_api_client, webhook_with_identifier):
+ # given
+ variables = {"identifier": webhook_with_identifier.identifier}
+
+ # when
+ response = app_api_client.post_graphql(
+ WEBHOOK_DELETE_BY_POINTER, variables=variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["webhookDelete"]["errors"] == []
+ assert Webhook.objects.filter(pk=webhook_with_identifier.pk).exists() is False
+
+
+ ("_case", "client_fixture"),
+ [
+ ("Unauthenticated user should be rejected", "api_client"),
+ (
+ "Authenticated unprivileged user (non-staff) should be rejected",
+ "user_api_client",
+ ),
+ ("Staff user without the permission should be rejected", "staff_api_client"),
+ ],
+)
+def test_webhook_delete_by_identifier_by_unauthorized_client(
+ _case, client_fixture, request, webhook_with_identifier
+):
+ # given
+ client = request.getfixturevalue(client_fixture)
+ variables = {"identifier": webhook_with_identifier.identifier}
+
+ # when
+ response = client.post_graphql(WEBHOOK_DELETE_BY_POINTER, variables=variables)
+
+ # then
+ assert_no_permission(response)
+ assert Webhook.objects.filter(pk=webhook_with_identifier.pk).exists() is True
+
+
+def test_webhook_delete_by_identifier_by_staff(
+ staff_api_client, permission_manage_apps, webhook_with_identifier
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_apps)
+ variables = {"identifier": webhook_with_identifier.identifier}
+
+ # when
+ response = staff_api_client.post_graphql(
+ WEBHOOK_DELETE_BY_POINTER, variables=variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["webhookDelete"]
+ assert data["webhook"] is None
+ assert data["errors"] == [
+ {
+ "field": "identifier",
+ "message": STAFF_POINTER_MESSAGE,
+ "code": WebhookErrorCode.INVALID.name,
+ }
+ ]
+ assert Webhook.objects.filter(pk=webhook_with_identifier.pk).exists() is True
+
+
+def test_webhook_delete_by_identifier_of_another_app(
+ app_api_client, webhook_with_identifier
+):
+ # given
+ other_app = App.objects.create(name="other")
+ other_webhook = Webhook.objects.create(
+ app=other_app,
+ target_url="http://www.example.com/other",
+ identifier="other-app-handler",
+ )
+ variables = {"identifier": other_webhook.identifier}
+
+ # when
+ response = app_api_client.post_graphql(
+ WEBHOOK_DELETE_BY_POINTER, variables=variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["webhookDelete"]
+ assert data["webhook"] is None
+ assert data["errors"] == [
+ {
+ "field": "identifier",
+ "message": f"Couldn't resolve to a node: {other_webhook.identifier}",
+ "code": WebhookErrorCode.NOT_FOUND.name,
+ }
+ ]
+ assert Webhook.objects.filter(pk=other_webhook.pk).exists() is True
+
+
+def test_webhook_delete_with_both_pointers(app_api_client, webhook_with_identifier):
+ # given
+ variables = {
+ "id": graphene.Node.to_global_id("Webhook", webhook_with_identifier.pk),
+ "identifier": webhook_with_identifier.identifier,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ WEBHOOK_DELETE_BY_POINTER, variables=variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["webhookDelete"]
+ assert data["webhook"] is None
+ assert data["errors"] == [
+ {
+ "field": None,
+ "message": POINTER_COMBINED_MESSAGE,
+ "code": WebhookErrorCode.GRAPHQL_ERROR.name,
+ }
+ ]
+ assert Webhook.objects.filter(pk=webhook_with_identifier.pk).exists() is True
+
+
+ ("_case", "variables"),
+ [
+ ("identifier omitted", {}),
+ ("identifier explicitly null", {"identifier": None}),
+ ("identifier blank", {"identifier": ""}),
+ ],
+)
+def test_webhook_delete_without_pointer(
+ _case, variables, app_api_client, webhook_with_identifier
+):
+ # when
+ response = app_api_client.post_graphql(
+ WEBHOOK_DELETE_BY_POINTER, variables=variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["webhookDelete"]
+ assert data["webhook"] is None
+ assert data["errors"] == [
+ {
+ "field": None,
+ "message": POINTER_REQUIRED_MESSAGE,
+ "code": WebhookErrorCode.GRAPHQL_ERROR.name,
+ }
+ ]
+ assert Webhook.objects.filter(pk=webhook_with_identifier.pk).exists() is True
+
+
+ ("_case", "identifier"),
+ [
+ ("identifier explicitly null", None),
+ ("identifier blank", ""),
+ ],
+)
+def test_webhook_delete_by_id_with_falsy_identifier(
+ _case, identifier, app_api_client, webhook_with_identifier
+):
+ # given - a falsy identifier counts as not provided, so `id` still resolves
+ variables = {
+ "id": graphene.Node.to_global_id("Webhook", webhook_with_identifier.pk),
+ "identifier": identifier,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ WEBHOOK_DELETE_BY_POINTER, variables=variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["webhookDelete"]["errors"] == []
+ assert Webhook.objects.filter(pk=webhook_with_identifier.pk).exists() is False
+
+
+def test_webhook_delete_null_identifier_never_matches_webhook_without_identifier(
+ app_api_client, webhook
+):
+ # given - the app owns a webhook whose identifier is NULL
+ assert webhook.identifier is None
+ variables = {"identifier": None}
+
+ # when
+ response = app_api_client.post_graphql(
+ WEBHOOK_DELETE_BY_POINTER, variables=variables
+ )
+
+ # then - the NULL-identifier webhook must not be resolved by a null pointer
+ content = get_graphql_content(response)
+ assert content["data"]["webhookDelete"]["errors"] == [
+ {
+ "field": None,
+ "message": POINTER_REQUIRED_MESSAGE,
+ "code": WebhookErrorCode.GRAPHQL_ERROR.name,
+ }
+ ]
+ assert Webhook.objects.filter(pk=webhook.pk).exists() is True
diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_update.py b/saleor/graphql/webhook/tests/mutations/test_webhook_update.py
index c819001479..f2679e8328 100644
--- a/saleor/graphql/webhook/tests/mutations/test_webhook_update.py
+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_update.py
@@ -496,3 +496,319 @@ def test_webhook_create_assigns_filterable_channel_slugs_above_max_limit(
error = content["data"]["webhookUpdate"]["errors"][0]
assert error["field"] == "query"
assert error["code"] == WebhookErrorCode.INVALID.name
+
+
+WEBHOOK_UPDATE_BY_POINTER = """
+ mutation webhookUpdate($id: ID, $identifier: String, $input: WebhookUpdateInput!) {
+ webhookUpdate(id: $id, identifier: $identifier, input: $input) {
+ errors {
+ field
+ message
+ code
+ }
+ webhook {
+ id
+ identifier
+ isActive
+ }
+ }
+ }
+"""
+
+STAFF_POINTER_MESSAGE = (
+ "Webhook identifier can only be used by an app to reference its own webhook. "
+ "Use `id` instead."
+)
+POINTER_REQUIRED_MESSAGE = "At least one of arguments is required: 'id', 'identifier'."
+POINTER_COMBINED_MESSAGE = "Argument 'id' cannot be combined with 'identifier'"
+
+
+def test_webhook_update_by_identifier(app_api_client, webhook_with_identifier):
+ # given
+ assert webhook_with_identifier.is_active is True
+ variables = {
+ "identifier": webhook_with_identifier.identifier,
+ "input": {"isActive": False},
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ WEBHOOK_UPDATE_BY_POINTER, variables=variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["webhookUpdate"]
+ assert data["errors"] == []
+ assert data["webhook"]["identifier"] == webhook_with_identifier.identifier
+ assert data["webhook"]["isActive"] is False
+ webhook_with_identifier.refresh_from_db(fields=("is_active",))
+ assert webhook_with_identifier.is_active is False
+
+
+ ("_case", "client_fixture"),
+ [
+ ("Unauthenticated user should be rejected", "api_client"),
+ (
+ "Authenticated unprivileged user (non-staff) should be rejected",
+ "user_api_client",
+ ),
+ ("Staff user without the permission should be rejected", "staff_api_client"),
+ ],
+)
+def test_webhook_update_by_identifier_by_unauthorized_client(
+ _case, client_fixture, request, webhook_with_identifier
+):
+ # given
+ client = request.getfixturevalue(client_fixture)
+ variables = {
+ "identifier": webhook_with_identifier.identifier,
+ "input": {"isActive": False},
+ }
+
+ # when
+ response = client.post_graphql(WEBHOOK_UPDATE_BY_POINTER, variables=variables)
+
+ # then
+ assert_no_permission(response)
+ webhook_with_identifier.refresh_from_db(fields=("is_active",))
+ assert webhook_with_identifier.is_active is True
+
+
+def test_webhook_update_by_identifier_by_staff(
+ staff_api_client, permission_manage_apps, webhook_with_identifier
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_apps)
+ variables = {
+ "identifier": webhook_with_identifier.identifier,
+ "input": {"isActive": False},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ WEBHOOK_UPDATE_BY_POINTER, variables=variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["webhookUpdate"]
+ assert data["webhook"] is None
+ assert data["errors"] == [
+ {
+ "field": "identifier",
+ "message": STAFF_POINTER_MESSAGE,
+ "code": WebhookErrorCode.INVALID.name,
+ }
+ ]
+ webhook_with_identifier.refresh_from_db(fields=("is_active",))
+ assert webhook_with_identifier.is_active is True
+
+
+def test_webhook_update_by_identifier_of_another_app(
+ app_api_client, webhook_with_identifier
+):
+ # given
+ other_app = App.objects.create(name="other")
+ other_webhook = Webhook.objects.create(
+ app=other_app,
+ target_url="http://www.example.com/other",
+ identifier="other-app-handler",
+ )
+ variables = {"identifier": other_webhook.identifier, "input": {"isActive": False}}
+
+ # when
+ response = app_api_client.post_graphql(
+ WEBHOOK_UPDATE_BY_POINTER, variables=variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["webhookUpdate"]
+ assert data["webhook"] is None
+ assert data["errors"] == [
+ {
+ "field": "identifier",
+ "message": f"Couldn't resolve to a node: {other_webhook.identifier}",
+ "code": WebhookErrorCode.NOT_FOUND.name,
+ }
+ ]
+ other_webhook.refresh_from_db(fields=("is_active",))
+ assert other_webhook.is_active is True
+
+
+def test_webhook_update_by_identifier_renames_identifier(
+ app_api_client, webhook_with_identifier
+):
+ # given
+ new_identifier = "order-created-handler-v2"
+ variables = {
+ "identifier": webhook_with_identifier.identifier,
+ "input": {"identifier": new_identifier},
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ WEBHOOK_UPDATE_BY_POINTER, variables=variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["webhookUpdate"]
+ assert data["errors"] == []
+ assert data["webhook"]["identifier"] == new_identifier
+ webhook_with_identifier.refresh_from_db(fields=("identifier",))
+ assert webhook_with_identifier.identifier == new_identifier
+
+
+def test_webhook_update_by_identifier_rename_to_taken_identifier(
+ app_api_client, app, webhook_with_identifier
+):
+ # given
+ taken_identifier = "already-taken"
+ previous_identifier = webhook_with_identifier.identifier
+ Webhook.objects.create(
+ app=app,
+ target_url="http://www.example.com/other",
+ identifier=taken_identifier,
+ )
+ variables = {
+ "identifier": previous_identifier,
+ "input": {"identifier": taken_identifier},
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ WEBHOOK_UPDATE_BY_POINTER, variables=variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["webhookUpdate"]["errors"] == [
+ {
+ "field": None,
+ "message": "Webhook with this App and Identifier already exists.",
+ "code": WebhookErrorCode.UNIQUE.name,
+ }
+ ]
+ webhook_with_identifier.refresh_from_db(fields=("identifier",))
+ assert webhook_with_identifier.identifier == previous_identifier
+
+
+def test_webhook_update_with_both_pointers(app_api_client, webhook_with_identifier):
+ # given
+ variables = {
+ "id": graphene.Node.to_global_id("Webhook", webhook_with_identifier.pk),
+ "identifier": webhook_with_identifier.identifier,
+ "input": {"isActive": False},
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ WEBHOOK_UPDATE_BY_POINTER, variables=variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["webhookUpdate"]
+ assert data["webhook"] is None
+ assert data["errors"] == [
+ {
+ "field": None,
+ "message": POINTER_COMBINED_MESSAGE,
+ "code": WebhookErrorCode.GRAPHQL_ERROR.name,
+ }
+ ]
+ webhook_with_identifier.refresh_from_db(fields=("is_active",))
+ assert webhook_with_identifier.is_active is True
+
+
+ ("_case", "variables"),
+ [
+ ("identifier omitted", {"input": {"isActive": False}}),
+ (
+ "identifier explicitly null",
+ {"identifier": None, "input": {"isActive": False}},
+ ),
+ ("identifier blank", {"identifier": "", "input": {"isActive": False}}),
+ ],
+)
+def test_webhook_update_without_pointer(
+ _case, variables, app_api_client, webhook_with_identifier
+):
+ # when
+ response = app_api_client.post_graphql(
+ WEBHOOK_UPDATE_BY_POINTER, variables=variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["webhookUpdate"]
+ assert data["webhook"] is None
+ assert data["errors"] == [
+ {
+ "field": None,
+ "message": POINTER_REQUIRED_MESSAGE,
+ "code": WebhookErrorCode.GRAPHQL_ERROR.name,
+ }
+ ]
+ webhook_with_identifier.refresh_from_db(fields=("is_active",))
+ assert webhook_with_identifier.is_active is True
+
+
+ ("_case", "identifier"),
+ [
+ ("identifier explicitly null", None),
+ ("identifier blank", ""),
+ ],
+)
+def test_webhook_update_by_id_with_falsy_identifier(
+ _case, identifier, app_api_client, webhook_with_identifier
+):
+ # given - a falsy identifier counts as not provided, so `id` still resolves
+ variables = {
+ "id": graphene.Node.to_global_id("Webhook", webhook_with_identifier.pk),
+ "identifier": identifier,
+ "input": {"isActive": False},
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ WEBHOOK_UPDATE_BY_POINTER, variables=variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["webhookUpdate"]
+ assert data["errors"] == []
+ assert data["webhook"]["isActive"] is False
+ webhook_with_identifier.refresh_from_db(fields=("is_active",))
+ assert webhook_with_identifier.is_active is False
+
+
+def test_webhook_update_null_identifier_never_matches_webhook_without_identifier(
+ app_api_client, webhook
+):
+ # given - the app owns a webhook whose identifier is NULL
+ assert webhook.identifier is None
+ variables = {"identifier": None, "input": {"isActive": False}}
+
+ # when
+ response = app_api_client.post_graphql(
+ WEBHOOK_UPDATE_BY_POINTER, variables=variables
+ )
+
+ # then - the NULL-identifier webhook must not be resolved by a null pointer
+ content = get_graphql_content(response)
+ assert content["data"]["webhookUpdate"]["errors"] == [
+ {
+ "field": None,
+ "message": POINTER_REQUIRED_MESSAGE,
+ "code": WebhookErrorCode.GRAPHQL_ERROR.name,
+ }
+ ]
+ webhook.refresh_from_db(fields=("is_active",))
+ assert webhook.is_active is True
diff --git a/saleor/webhook/tests/fixtures/webhook.py b/saleor/webhook/tests/fixtures/webhook.py
index 0b76e8ebbc..3f206b4473 100644
--- a/saleor/webhook/tests/fixtures/webhook.py
+++ b/saleor/webhook/tests/fixtures/webhook.py
@@ -14,6 +14,18 @@ def webhook(app):
return webhook
+def webhook_with_identifier(app):
+ webhook = Webhook.objects.create(
+ name="Identified webhook",
+ app=app,
+ target_url="http://www.example.com/identified",
+ identifier="order-created-handler",
+ )
+ webhook.events.create(event_type=WebhookEventAsyncType.ORDER_CREATED)
+ return webhook
+
+
@pytest.fixture
def webhook_without_name(app):
webhook = Webhook.objects.create(app=app, target_url="http://www.example.com/test")