Skip to content

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

Allow apps to receive their own lifecycle webhooks (#19155)

Lukasz Ostrowski68f9c9da39ae
diff --git a/saleor/app/actions.py b/saleor/app/actions.py
new file mode 100644
index 0000000000..2dc89207ce
--- /dev/null
+++ b/saleor/app/actions.py
@@ -0,0 +1,75 @@
+import logging
+
+from django.utils import timezone
+
+from ..core.telemetry import get_task_context
+from ..core.utils.events import call_event
+from ..plugins.manager import PluginsManager
+from ..webhook.event_types import WebhookEventAsyncType
+from ..webhook.transport.asynchronous.transport import (
+ create_deliveries_for_subscriptions,
+ send_webhook_request_async,
+)
+from ..webhook.utils import get_webhooks_for_app_lifecycle_event
+from .models import App
+
+logger = logging.getLogger(__name__)
+
+
+def delete_app(app: App, manager: PluginsManager, *, force_sync: bool = False) -> None:
+ """Soft-delete an app and dispatch APP_DELETED.
+
+ Sets `removed_at` and `is_active=False`, then fires the lifecycle
+ webhook. The row is removed by the `remove_apps_task` Celery job once
+ `DELETE_APP_TTL` elapses.
+
+ When `force_sync` is True, deliveries are persisted and the webhook
+ task is executed in-process via Celery's eager `.apply()` instead of
+ being queued.
+ """
+ app.removed_at = timezone.now()
+ app.is_active = False
+ app.save(update_fields=["removed_at", "is_active"])
+
+ if force_sync:
+ _dispatch_app_deleted_sync(app)
+ else:
+ call_event(manager.app_deleted, app)
+
+
+def _dispatch_app_deleted_sync(app: App) -> None:
+ event_type = WebhookEventAsyncType.APP_DELETED
+ # Legacy (non-subscription) webhooks are intentionally not supported here.
+ # They are deprecated and slated for removal; this path will not emit to
+ # them. Only webhooks with a subscription query receive the event.
+ # Apps are validated to always provide subscription query as required
+ webhooks = [
+ webhook
+ for webhook in get_webhooks_for_app_lifecycle_event(event_type, app)
+ if webhook.subscription_query
+ ]
+ if not webhooks:
+ return
+
+ deliveries = create_deliveries_for_subscriptions(
+ event_type=event_type,
+ subscribable_object=app,
+ webhooks=webhooks,
+ )
+
+ telemetry_context = get_task_context().to_dict()
+ for delivery in deliveries:
+ try:
+ send_webhook_request_async.apply(
+ kwargs={
+ "event_delivery_id": delivery.pk,
+ "telemetry_context": telemetry_context,
+ },
+ )
+ except Exception:
+ logger.warning(
+ "Sync APP_DELETED dispatch failed for app pk=%s delivery pk=%s",
+ app.pk,
+ delivery.pk,
+ exc_info=True,
+ )
diff --git a/saleor/app/management/commands/app_delete_all.py b/saleor/app/management/commands/app_delete_all.py
new file mode 100644
index 0000000000..20a8ded258
--- /dev/null
+++ b/saleor/app/management/commands/app_delete_all.py
@@ -0,0 +1,42 @@
+from typing import Any
+
+from django.core.management import BaseCommand
+from django.core.management.base import CommandParser
+
+from ....plugins.manager import get_plugins_manager
+from ...actions import delete_app
+from ...models import App
+
+
+class Command(BaseCommand):
+ help = (
+ "Soft-delete every installed app. Iterates over all apps that have "
+ "not been soft-deleted yet uses the same logic as appDelete mutation "
+ )
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument(
+ "--force-sync",
+ dest="force_sync",
+ action="store_true",
+ help="Emit APP_DELETED synchronously instead of queueing on Celery.",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ apps = App.objects.not_removed().order_by("pk")
+ if not apps.exists():
+ self.stdout.write("No active apps to delete.")
+ return
+
+ force_sync = options["force_sync"]
+ manager = get_plugins_manager(allow_replica=False)
+ for app in apps:
+ delete_app(app, manager, force_sync=force_sync)
+ self.stdout.write(
+ self.style.SUCCESS(
+ f"Deleted app pk={app.pk} identifier={app.identifier!r} "
+ f"name={app.name!r}."
+ )
+ )
+
+ self.stdout.write(self.style.SUCCESS(f"Deleted {len(apps)} app(s)."))
diff --git a/saleor/app/tests/test_app_actions.py b/saleor/app/tests/test_app_actions.py
new file mode 100644
index 0000000000..601f663a56
--- /dev/null
+++ b/saleor/app/tests/test_app_actions.py
@@ -0,0 +1,115 @@
+import json
+from unittest.mock import Mock, patch
+
+import graphene
+
+from ...core.models import EventDelivery, EventPayload
+from ...webhook.event_types import WebhookEventAsyncType
+from ...webhook.models import Webhook
+from ..actions import delete_app
+from ..models import App
+
+
+def test_delete_app_soft_deletes_and_calls_app_deleted(
+ app, django_capture_on_commit_callbacks
+):
+ # given
+ manager = Mock()
+ assert app.removed_at is None
+ assert app.is_active is True
+
+ # when
+ with django_capture_on_commit_callbacks(execute=True):
+ delete_app(app, manager)
+
+ # then
+ app_from_db = App.objects.get(pk=app.pk)
+ assert app_from_db.removed_at is not None
+ assert app_from_db.is_active is False
+ manager.app_deleted.assert_called_once_with(app)
+
+
+@patch("saleor.app.actions.send_webhook_request_async.apply")
+def test_delete_app_force_sync_renders_subscription_inline(mocked_apply, app):
+ # given
+ manager = Mock()
+ subscription_query = """
+ subscription { event { ... on AppDeleted { app { id isActive name } } } }
+ """
+ webhook = Webhook.objects.create(
+ name="subscription",
+ app=app,
+ target_url="http://example.com/sub",
+ is_active=True,
+ subscription_query=subscription_query,
+ )
+ webhook.events.create(event_type=WebhookEventAsyncType.APP_DELETED)
+
+ # when
+ delete_app(app, manager, force_sync=True)
+
+ # then
+ delivery = EventDelivery.objects.get(webhook=webhook)
+ assert delivery.event_type == WebhookEventAsyncType.APP_DELETED
+ payload = json.loads(delivery.payload.get_payload())
+ assert payload == {
+ "app": {
+ "id": graphene.Node.to_global_id("App", app.id),
+ "isActive": False,
+ "name": app.name,
+ }
+ }
+
+ mocked_apply.assert_called_once()
+ call_kwargs = mocked_apply.call_args.kwargs["kwargs"]
+ assert call_kwargs["event_delivery_id"] == delivery.pk
+ assert "telemetry_context" in call_kwargs
+
+
+@patch("saleor.app.actions.send_webhook_request_async.apply")
+def test_delete_app_force_sync_skips_legacy_webhooks_without_subscription(
+ mocked_apply, app
+):
+ # Legacy non-subscription webhooks are not supported. Effectively these webhooks
+ # exist in the code, but app installation enforces subscription, so we don't have
+ # to support them.
+ # static_payload should be eventually removed from the codebase
+
+ # given
+ manager = Mock()
+ legacy_webhook = Webhook.objects.create(
+ name="legacy",
+ app=app,
+ target_url="http://example.com/legacy",
+ is_active=True,
+ )
+ legacy_webhook.events.create(event_type=WebhookEventAsyncType.APP_DELETED)
+
+ # when
+ delete_app(app, manager, force_sync=True)
+
+ # then
+ assert not EventDelivery.objects.filter(webhook=legacy_webhook).exists()
+ assert not EventPayload.objects.exists()
+ mocked_apply.assert_not_called()
+
+
+@patch("saleor.app.actions.send_webhook_request_async.apply")
+def test_delete_app_force_sync_with_no_webhooks_does_not_create_deliveries(
+ mocked_apply, app
+):
+ # given
+ manager = Mock()
+ assert not app.webhooks.exists()
+
+ # when
+ delete_app(app, manager, force_sync=True)
+
+ # then
+ app_from_db = App.objects.get(pk=app.pk)
+ assert app_from_db.removed_at is not None
+ assert app_from_db.is_active is False
+ manager.app_deleted.assert_not_called()
+ assert not EventDelivery.objects.exists()
+ assert not EventPayload.objects.exists()
+ mocked_apply.assert_not_called()
diff --git a/saleor/app/tests/test_app_commands.py b/saleor/app/tests/test_app_commands.py
index 8345f36501..c1b0448355 100644
--- a/saleor/app/tests/test_app_commands.py
+++ b/saleor/app/tests/test_app_commands.py
@@ -4,11 +4,15 @@ import graphene
import pytest
from django.core.management import CommandError, call_command
from django.forms import ValidationError
+from django.utils import timezone
from requests_hardened import HTTPSession
from ... import schema_version
from ...core import JobStatus
+from ...core.models import EventDelivery
from ...permission.enums import AppPermission, get_permissions
+from ...webhook.event_types import WebhookEventAsyncType
+from ...webhook.models import Webhook
from ..models import App, AppInstallation
from ..types import AppType
@@ -282,3 +286,143 @@ def test_creates_app_with_identifier():
assert len(tokens) == 1
assert app.uuid is not None
assert app.identifier == "test.test"
+
+
+APP_DELETE_ALL_COMMAND_MODULE = "saleor.app.management.commands.app_delete_all"
+
+
+def _patched_plugins_manager():
+ with patch(
+ f"{APP_DELETE_ALL_COMMAND_MODULE}.get_plugins_manager"
+ ) as mocked_get_manager:
+ mocked_manager = Mock()
+ mocked_get_manager.return_value = mocked_manager
+ yield mocked_manager
+
+
+def test_app_delete_all_deletes_every_installed_app(db):
+ # given
+ app_a = App.objects.create(name="App A", identifier="a", is_active=True)
+ app_b = App.objects.create(name="App B", identifier="b", is_active=False)
+ app_c = App.objects.create(name="App C", identifier="c", is_active=True)
+
+ # when
+ call_command("app_delete_all")
+
+ # then
+ app_a.refresh_from_db()
+ app_b.refresh_from_db()
+ app_c.refresh_from_db()
+
+ assert app_a.is_active is False
+ assert app_a.removed_at is not None
+
+ assert app_b.is_active is False
+ assert app_b.removed_at is not None
+
+ assert app_c.is_active is False
+ assert app_c.removed_at is not None
+
+
+def test_app_delete_all_skips_already_removed_apps(db):
+ # given
+ active_app = App.objects.create(name="Active", identifier="active", is_active=True)
+ removed_app = App.objects.create(
+ name="Removed",
+ identifier="removed",
+ is_active=False,
+ removed_at=timezone.now(),
+ )
+ removed_app.refresh_from_db()
+ original_removed_at = removed_app.removed_at
+
+ # when
+ call_command("app_delete_all")
+
+ # then
+ active_app.refresh_from_db()
+ removed_app.refresh_from_db()
+
+ assert active_app.is_active is False
+ assert active_app.removed_at is not None
+
+ assert removed_app.is_active is False
+ assert removed_app.removed_at == original_removed_at
+
+
+def test_app_delete_all_with_no_apps_does_not_call_manager(
+ db, _patched_plugins_manager
+):
+ # given
+ assert not App.objects.exists()
+
+ # when
+ call_command("app_delete_all")
+
+ # then
+ _patched_plugins_manager.app_deleted.assert_not_called()
+
+
+def test_app_delete_all_without_force_sync_calls_app_deleted_on_manager(
+ db, _patched_plugins_manager, django_capture_on_commit_callbacks
+):
+ # given
+ app_a = App.objects.create(name="App A", identifier="a", is_active=True)
+ app_b = App.objects.create(name="App B", identifier="b", is_active=True)
+
+ # when
+ with django_capture_on_commit_callbacks(execute=True):
+ call_command("app_delete_all")
+
+ # then
+ app_a.refresh_from_db()
+ app_b.refresh_from_db()
+
+ assert app_a.removed_at is not None
+ assert app_b.removed_at is not None
+ assert _patched_plugins_manager.app_deleted.call_args_list == [
+ call(app_a),
+ call(app_b),
+ ]
+
+
+@patch("saleor.app.actions.send_webhook_request_async.apply")
+def test_app_delete_all_with_force_sync_dispatches_sync_webhooks(
+ mocked_apply, db, _patched_plugins_manager
+):
+ # given
+ app_a = App.objects.create(name="App A", identifier="a", is_active=True)
+ app_b = App.objects.create(name="App B", identifier="b", is_active=True)
+ subscription_query = "subscription { event { ... on AppDeleted { app { id } } } }"
+ for current_app in (app_a, app_b):
+ webhook = Webhook.objects.create(
+ name=f"hook-{current_app.identifier}",
+ app=current_app,
+ target_url=f"http://example.com/{current_app.identifier}",
+ is_active=True,
+ subscription_query=subscription_query,
+ )
+ webhook.events.create(event_type=WebhookEventAsyncType.APP_DELETED)
+
+ # when
+ call_command("app_delete_all", force_sync=True)
+
+ # then
+ app_a.refresh_from_db()
+ app_b.refresh_from_db()
+
+ assert app_a.removed_at is not None
+ assert app_b.removed_at is not None
+ _patched_plugins_manager.app_deleted.assert_not_called()
+
+ deliveries = EventDelivery.objects.filter(
+ event_type=WebhookEventAsyncType.APP_DELETED
+ )
+ assert deliveries.count() == 2
+ delivery_pks = set(deliveries.values_list("pk", flat=True))
+ called_pks = {
+ call.kwargs["kwargs"]["event_delivery_id"]
+ for call in mocked_apply.call_args_list
+ }
+ assert called_pks == delivery_pks
diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.py
index 892782e8b4..06cc3f695c 100644
--- a/saleor/app/tests/test_installation_utils.py
+++ b/saleor/app/tests/test_installation_utils.py
@@ -216,7 +216,7 @@ def test_install_app_with_brand_data(app_manifest, app_installation, monkeypatch
@freeze_time("2022-05-12 12:00:00")
-@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
+@patch("saleor.plugins.webhook.plugin.get_webhooks_for_app_lifecycle_event")
@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
def test_install_app_created_app_trigger_webhook(
mocked_webhook_trigger,
diff --git a/saleor/graphql/app/mutations/app_delete.py b/saleor/graphql/app/mutations/app_delete.py
index 1e11db1ac1..fee07017e8 100644
--- a/saleor/graphql/app/mutations/app_delete.py
+++ b/saleor/graphql/app/mutations/app_delete.py
@@ -1,8 +1,8 @@
import graphene
from django.core.exceptions import ValidationError
-from django.utils import timezone
from ....app import models
+from ....app.actions import delete_app
from ....app.error_codes import AppErrorCode
from ....permission.enums import AppPermission
from ....webhook.event_types import WebhookEventAsyncType
@@ -50,19 +50,12 @@ class AppDelete(DeprecatedModelMutation):
code = AppErrorCode.OUT_OF_SCOPE_APP.value
raise ValidationError({"id": ValidationError(msg, code=code)})
- @classmethod
- def post_save_action(cls, info, instance, cleaned_input):
- manager = get_plugin_manager_promise(info.context).get()
- cls.call_event(manager.app_deleted, instance)
-
@classmethod
def perform_mutation(cls, _root, info, /, **data):
instance = cls.get_instance(info, **data)
cls.clean_instance(info, instance)
- instance.removed_at = timezone.now()
- instance.is_active = False
- instance.save(update_fields=["removed_at", "is_active"])
+ manager = get_plugin_manager_promise(info.context).get()
+ delete_app(instance, manager)
- cls.post_save_action(info, instance, {})
return cls.success_response(instance)
diff --git a/saleor/graphql/app/tests/mutations/test_app_activate.py b/saleor/graphql/app/tests/mutations/test_app_activate.py
index 2629127630..72010b9807 100644
--- a/saleor/graphql/app/tests/mutations/test_app_activate.py
+++ b/saleor/graphql/app/tests/mutations/test_app_activate.py
@@ -52,7 +52,7 @@ def test_activate_app(app, staff_api_client, permission_manage_apps):
@freeze_time("2022-05-12 12:00:00")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_app_lifecycle_event")
@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
def test_activate_app_trigger_webhook(
mocked_webhook_trigger,
diff --git a/saleor/graphql/app/tests/mutations/test_app_create.py b/saleor/graphql/app/tests/mutations/test_app_create.py
index 2532a3dc59..ad51792c3e 100644
--- a/saleor/graphql/app/tests/mutations/test_app_create.py
+++ b/saleor/graphql/app/tests/mutations/test_app_create.py
@@ -111,7 +111,7 @@ def test_app_create_no_identifier_mutation(
@freeze_time("2022-05-12 12:00:00")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_app_lifecycle_event")
@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
def test_app_create_trigger_webhook(
mocked_webhook_trigger,
diff --git a/saleor/graphql/app/tests/mutations/test_app_deactivate.py b/saleor/graphql/app/tests/mutations/test_app_deactivate.py
index c12e13de2a..6ca5516ba5 100644
--- a/saleor/graphql/app/tests/mutations/test_app_deactivate.py
+++ b/saleor/graphql/app/tests/mutations/test_app_deactivate.py
@@ -52,7 +52,7 @@ def test_deactivate_app(app, staff_api_client, permission_manage_apps):
@freeze_time("2022-05-12 12:00:00")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_app_lifecycle_event")
@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
def test_deactivate_app_trigger_webhook(
mocked_webhook_trigger,
diff --git a/saleor/graphql/app/tests/mutations/test_app_delete.py b/saleor/graphql/app/tests/mutations/test_app_delete.py
index 22afceb602..aa85c9afce 100644
--- a/saleor/graphql/app/tests/mutations/test_app_delete.py
+++ b/saleor/graphql/app/tests/mutations/test_app_delete.py
@@ -56,7 +56,7 @@ def test_app_delete(
@freeze_time("2022-05-12 12:00:00")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_app_lifecycle_event")
@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
def test_app_delete_trigger_webhook(
mocked_webhook_trigger,
diff --git a/saleor/graphql/app/tests/mutations/test_app_update.py b/saleor/graphql/app/tests/mutations/test_app_update.py
index fec27c4565..42da285130 100644
--- a/saleor/graphql/app/tests/mutations/test_app_update.py
+++ b/saleor/graphql/app/tests/mutations/test_app_update.py
@@ -80,7 +80,7 @@ def test_app_update_mutation(
@freeze_time("2022-05-12 12:00:00")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_app_lifecycle_event")
@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
def test_app_update_trigger_mutation(
mocked_webhook_trigger,
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 4e81267fad..c78365c150 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -118,7 +118,11 @@ from ...webhook.transport.utils import (
get_meta_description_key,
get_sqs_message_group_id,
)
-from ...webhook.utils import filter_webhooks_for_channel, get_webhooks_for_event
+from ...webhook.utils import (
+ filter_webhooks_for_channel,
+ get_webhooks_for_app_lifecycle_event,
+ get_webhooks_for_event,
+)
from ..base_plugin import BasePlugin
if TYPE_CHECKING:
@@ -394,7 +398,7 @@ class WebhookPlugin(BasePlugin):
return previous_value
def _trigger_app_event(self, event_type, app):
- if webhooks := get_webhooks_for_event(event_type):
+ if webhooks := get_webhooks_for_app_lifecycle_event(event_type, app):
payload = self._serialize_payload(
{
"id": graphene.Node.to_global_id("App", app.id),
diff --git a/saleor/plugins/webhook/tests/test_app_lifecycle_webhooks.py b/saleor/plugins/webhook/tests/test_app_lifecycle_webhooks.py
new file mode 100644
index 0000000000..38dbfa05fb
--- /dev/null
+++ b/saleor/plugins/webhook/tests/test_app_lifecycle_webhooks.py
@@ -0,0 +1,276 @@
+"""End-to-end tests for app lifecycle webhook self-receive.
+
+Confirms an app without MANAGE_APPS permission receives its own
+APP_INSTALLED, APP_UPDATED, APP_DELETED, APP_STATUS_CHANGED events,
+and that the delivery-time gate keeps lifecycle deliveries when the
+receiving app is inactive (soft-deleted or deactivated).
+"""
+
+import json
+from unittest import mock
+
+import graphene
+import pytest
+from django.utils import timezone
+
+from ....app.models import App
+from ....core import EventDeliveryStatus
+from ....core.models import EventDelivery
+from ....webhook.event_types import WebhookEventAsyncType
+from ....webhook.models import Webhook
+from ....webhook.transport.utils import get_multiple_deliveries_for_webhooks
+from ...manager import get_plugins_manager
+
+APP_STATUS_CHANGED_SUBSCRIPTION = """
+subscription {
+ event {
+ ... on AppStatusChanged {
+ app {
+ id
+ isActive
+ }
+ }
+ }
+}
+"""
+
+
+def app_with_lifecycle_webhook(db, settings):
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ def factory(event_type, *, is_active=True, removed_at=None, subscription_query=""):
+ app = App.objects.create(name="Self-receive app", is_active=is_active)
+ if removed_at:
+ app.removed_at = removed_at
+ app.save(update_fields=["removed_at"])
+ webhook = Webhook.objects.create(
+ name="lifecycle",
+ app=app,
+ target_url="http://example.com/webhook",
+ is_active=True,
+ subscription_query=subscription_query,
+ )
+ webhook.events.create(event_type=event_type)
+ return app, webhook
+
+ return factory
+
+
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_app_receives_own_app_installed_without_manage_apps(
+ mocked_trigger, app_with_lifecycle_webhook
+):
+ # given
+ app, webhook = app_with_lifecycle_webhook(WebhookEventAsyncType.APP_INSTALLED)
+ assert not app.permissions.exists()
+
+ # when
+ manager = get_plugins_manager(allow_replica=False)
+ manager.app_installed(app)
+
+ # then
+ mocked_trigger.assert_called_once()
+ delivered_webhooks = mocked_trigger.call_args.args[2]
+ assert webhook in list(delivered_webhooks)
+
+
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_app_receives_own_app_updated_without_manage_apps(
+ mocked_trigger, app_with_lifecycle_webhook
+):
+ # given
+ app, webhook = app_with_lifecycle_webhook(WebhookEventAsyncType.APP_UPDATED)
+ assert not app.permissions.exists()
+
+ # when
+ manager = get_plugins_manager(allow_replica=False)
+ manager.app_updated(app)
+
+ # then
+ mocked_trigger.assert_called_once()
+ delivered_webhooks = mocked_trigger.call_args.args[2]
+ assert webhook in list(delivered_webhooks)
+
+
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_app_receives_own_app_deleted_without_manage_apps(
+ mocked_trigger, app_with_lifecycle_webhook
+):
+ """Verify self-receive for the soft-deleted app.
+
+ The affected app is soft-deleted (is_active=False, removed_at set)
+ at dispatch time, yet must still receive APP_DELETED.
+ """
+ # given
+ app, webhook = app_with_lifecycle_webhook(
+ WebhookEventAsyncType.APP_DELETED,
+ is_active=False,
+ removed_at=timezone.now(),
+ )
+ assert not app.permissions.exists()
+
+ # when
+ manager = get_plugins_manager(allow_replica=False)
+ manager.app_deleted(app)
+
+ # then
+ mocked_trigger.assert_called_once()
+ delivered_webhooks = mocked_trigger.call_args.args[2]
+ assert webhook in list(delivered_webhooks)
+
+
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_app_receives_own_app_status_changed_on_deactivate(
+ mocked_trigger, app_with_lifecycle_webhook
+):
+ """Verify self-receive for the deactivated app.
+
+ A deactivated app (is_active=False) must still receive its own
+ APP_STATUS_CHANGED webhook.
+ """
+ # given
+ app, webhook = app_with_lifecycle_webhook(
+ WebhookEventAsyncType.APP_STATUS_CHANGED, is_active=False
+ )
+ assert not app.permissions.exists()
+
+ # when
+ manager = get_plugins_manager(allow_replica=False)
+ manager.app_status_changed(app)
+
+ # then
+ mocked_trigger.assert_called_once()
+ delivered_webhooks = mocked_trigger.call_args.args[2]
+ assert webhook in list(delivered_webhooks)
+
+
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_unrelated_app_without_manage_apps_does_not_receive_lifecycle_event(
+ mocked_trigger, app_with_lifecycle_webhook
+):
+ """An app subscribed to APP_DELETED must not receive events about other apps."""
+ # given
+ affected_app = App.objects.create(name="Target", is_active=True)
+ app_with_lifecycle_webhook(WebhookEventAsyncType.APP_DELETED)
+
+ # when
+ manager = get_plugins_manager(allow_replica=False)
+ manager.app_deleted(affected_app)
+
+ # then
+ assert not mocked_trigger.called
+
+
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_admin_app_with_manage_apps_does_not_receive_events_about_other_apps(
+ mocked_trigger, app_with_lifecycle_webhook, permission_manage_apps
+):
+ """App lifecycle events are self-only — MANAGE_APPS does not grant visibility."""
+ # given
+ affected_app = App.objects.create(name="Target", is_active=True)
+ admin_app, _ = app_with_lifecycle_webhook(WebhookEventAsyncType.APP_DELETED)
+ admin_app.permissions.add(permission_manage_apps)
+
+ # when
+ manager = get_plugins_manager(allow_replica=False)
+ manager.app_deleted(affected_app)
+
+ # then
+ assert not mocked_trigger.called
+
+
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
+)
+def test_app_deleted_delivery_survives_worker_active_check(
+ _mocked_apply_async, app_with_lifecycle_webhook
+):
+ """APP_DELETED on a soft-deleted app passes the delivery-time gate."""
+ # given
+ app, webhook = app_with_lifecycle_webhook(
+ WebhookEventAsyncType.APP_DELETED,
+ is_active=False,
+ removed_at=timezone.now(),
+ )
+
+ # when
+ manager = get_plugins_manager(allow_replica=False)
+ manager.app_deleted(app)
+ delivery = EventDelivery.objects.get(webhook=webhook)
+ active, inactive = get_multiple_deliveries_for_webhooks([delivery.pk])
+
+ # then
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.pk in active
+ assert delivery.pk not in inactive
+ delivery.refresh_from_db()
+ assert delivery.status == EventDeliveryStatus.PENDING
+
+
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
+)
+def test_app_status_changed_delivery_survives_worker_active_check(
+ _mocked_apply_async, app_with_lifecycle_webhook
+):
+ """APP_STATUS_CHANGED on a deactivated app passes the delivery-time gate."""
+ # given
+ app, webhook = app_with_lifecycle_webhook(
+ WebhookEventAsyncType.APP_STATUS_CHANGED, is_active=False
+ )
+
+ # when
+ manager = get_plugins_manager(allow_replica=False)
+ manager.app_status_changed(app)
+ delivery = EventDelivery.objects.get(webhook=webhook)
+ active, _ = get_multiple_deliveries_for_webhooks([delivery.pk])
+
+ # then
+ assert delivery.pk in active
+ delivery.refresh_from_db()
+ assert delivery.status == EventDeliveryStatus.PENDING
+
+
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
+)
+def test_app_status_changed_subscription_payload_snapshots_state_per_event(
+ _mocked_apply_async, app_with_lifecycle_webhook
+):
+ """Subscription payload reflects app.is_active at dispatch time.
+
+ With delivery deferred (apply_async mocked), back-to-back deactivate
+ then activate must produce two PENDING deliveries whose subscription
+ payloads carry isActive=False and isActive=True respectively. This
+ proves payloads are snapshotted at event time and survive the queue
+ delay independent of the app's current state.
+ """
+ # given
+ app, webhook = app_with_lifecycle_webhook(
+ WebhookEventAsyncType.APP_STATUS_CHANGED,
+ is_active=True,
+ subscription_query=APP_STATUS_CHANGED_SUBSCRIPTION,
+ )
+ app_global_id = graphene.Node.to_global_id("App", app.id)
+ manager = get_plugins_manager(allow_replica=False)
+
+ # when
+ app.is_active = False
+ app.save(update_fields=["is_active"])
+ manager.app_status_changed(app)
+
+ app.is_active = True
+ app.save(update_fields=["is_active"])
+ manager.app_status_changed(app)
+
+ # then
+ deliveries = list(EventDelivery.objects.filter(webhook=webhook).order_by("pk"))
+ assert len(deliveries) == 2
+ assert all(d.status == EventDeliveryStatus.PENDING for d in deliveries)
+
+ deactivate_payload = json.loads(deliveries[0].payload.get_payload())
+ activate_payload = json.loads(deliveries[1].payload.get_payload())
+
+ assert deactivate_payload == {"app": {"id": app_global_id, "isActive": False}}
+ assert activate_payload == {"app": {"id": app_global_id, "isActive": True}}
diff --git a/saleor/webhook/tests/test_utils.py b/saleor/webhook/tests/test_utils.py
index b32114dbcb..9782f66d83 100644
--- a/saleor/webhook/tests/test_utils.py
+++ b/saleor/webhook/tests/test_utils.py
@@ -1,4 +1,5 @@
import pytest
+from django.utils import timezone
from ...app.models import App
from ..event_types import WebhookEventAsyncType, WebhookEventSyncType
@@ -12,7 +13,11 @@ from ..observability.payload_schema import ObservabilityEventTypes
from ..transport.utils import (
generate_cache_key_for_webhook,
)
-from ..utils import get_webhooks_for_event, get_webhooks_for_multiple_events
+from ..utils import (
+ get_webhooks_for_app_lifecycle_event,
+ get_webhooks_for_event,
+ get_webhooks_for_multiple_events,
+)
@pytest.fixture
@@ -117,6 +122,152 @@ def test_get_webhook_for_event_not_returning_any_webhook_for_sync_event_types(
assert set(webhooks) == {sync_webhook}
+def app_lifecycle_app_factory(db):
+ """Create an app + webhook subscribed to an app lifecycle event.
+
+ The created app intentionally does NOT hold MANAGE_APPS, mirroring how
+ third-party apps cannot grant themselves admin-only permissions.
+ """
+
+ def create_app(
+ event_type=WebhookEventAsyncType.APP_DELETED,
+ active_app=True,
+ active_webhook=True,
+ removed=False,
+ ):
+ app = App.objects.create(name="Lifecycle App", is_active=active_app)
+ app.tokens.create(name="Default")
+ if removed:
+ app.removed_at = timezone.now()
+ app.save(update_fields=["removed_at"])
+ webhook = Webhook.objects.create(
+ name="lifecycle-webhook", app=app, is_active=active_webhook
+ )
+ webhook.events.create(event_type=event_type)
+ return app, webhook
+
+ return create_app
+
+
+def test_app_lifecycle_returns_self_webhook_without_manage_apps(
+ app_lifecycle_app_factory,
+):
+ # given
+ affected_app, affected_webhook = app_lifecycle_app_factory()
+
+ # when
+ webhooks = get_webhooks_for_app_lifecycle_event(
+ WebhookEventAsyncType.APP_DELETED, affected_app
+ )
+
+ # then
+ assert set(webhooks) == {affected_webhook}
+
+
+def test_app_lifecycle_does_not_leak_to_other_apps(app_lifecycle_app_factory):
+ # given
+ affected_app, _ = app_lifecycle_app_factory()
+ _, other_webhook = app_lifecycle_app_factory()
+
+ # when
+ webhooks = get_webhooks_for_app_lifecycle_event(
+ WebhookEventAsyncType.APP_DELETED, affected_app
+ )
+
+ # then
+ assert other_webhook not in set(webhooks)
+
+
+def test_app_lifecycle_ignores_manage_apps_holders(
+ app_lifecycle_app_factory, permission_manage_apps
+):
+ """An admin app with MANAGE_APPS must not receive events about other apps."""
+
+ # given
+ affected_app, affected_webhook = app_lifecycle_app_factory()
+ admin_app, admin_webhook = app_lifecycle_app_factory()
+ admin_app.permissions.add(permission_manage_apps)
+
+ # when
+ webhooks = get_webhooks_for_app_lifecycle_event(
+ WebhookEventAsyncType.APP_DELETED, affected_app
+ )
+
+ # then
+ assert set(webhooks) == {affected_webhook}
+ assert admin_webhook not in set(webhooks)
+
+
+def test_app_lifecycle_includes_soft_deleted_app(app_lifecycle_app_factory):
+ # given
+ affected_app, affected_webhook = app_lifecycle_app_factory(removed=True)
+
+ # when
+ webhooks = get_webhooks_for_app_lifecycle_event(
+ WebhookEventAsyncType.APP_DELETED, affected_app
+ )
+
+ # then
+ assert set(webhooks) == {affected_webhook}
+
+
+def test_app_lifecycle_includes_inactive_app(app_lifecycle_app_factory):
+ # given
+ affected_app, affected_webhook = app_lifecycle_app_factory(
+ event_type=WebhookEventAsyncType.APP_STATUS_CHANGED, active_app=False
+ )
+
+ # when
+ webhooks = get_webhooks_for_app_lifecycle_event(
+ WebhookEventAsyncType.APP_STATUS_CHANGED, affected_app
+ )
+
+ # then
+ assert set(webhooks) == {affected_webhook}
+
+
+def test_app_lifecycle_excludes_inactive_webhook(app_lifecycle_app_factory):
+ # given
+ affected_app, _ = app_lifecycle_app_factory(active_webhook=False)
+
+ # when
+ webhooks = get_webhooks_for_app_lifecycle_event(
+ WebhookEventAsyncType.APP_DELETED, affected_app
+ )
+
+ # then
+ assert set(webhooks) == set()
+
+
+def test_app_lifecycle_matches_any_subscription(app_lifecycle_app_factory):
+ """A webhook subscribed via ANY must also receive lifecycle events."""
+
+ # given
+ affected_app, affected_webhook = app_lifecycle_app_factory(
+ event_type=WebhookEventAsyncType.ANY
+ )
+
+ # when
+ webhooks = get_webhooks_for_app_lifecycle_event(
+ WebhookEventAsyncType.APP_DELETED, affected_app
+ )
+
+ # then
+ assert set(webhooks) == {affected_webhook}
+
+
+def test_app_lifecycle_rejects_non_lifecycle_event(app_lifecycle_app_factory):
+ # given
+ affected_app, _ = app_lifecycle_app_factory()
+
+ # when & then
+ with pytest.raises(ValueError, match="not an app lifecycle event"):
+ get_webhooks_for_app_lifecycle_event(
+ WebhookEventAsyncType.ORDER_CREATED, affected_app
+ )
+
+
@pytest.mark.parametrize(
("error", "event_type"),
[
diff --git a/saleor/webhook/transport/tests/test_utils.py b/saleor/webhook/transport/tests/test_utils.py
index 342a024aea..515d236ced 100644
--- a/saleor/webhook/transport/tests/test_utils.py
+++ b/saleor/webhook/transport/tests/test_utils.py
@@ -254,6 +254,51 @@ def test_get_delivery_for_webhook_inactive_app(event_delivery, caplog):
assert not_found is False
+ "event_type",
+ [
+ WebhookEventAsyncType.APP_DELETED,
+ WebhookEventAsyncType.APP_STATUS_CHANGED,
+ ],
+)
+def test_get_delivery_for_webhook_inactive_app_self_lifecycle_event(
+ event_delivery, event_type
+):
+ # given
+ event_delivery.webhook.app.is_active = False
+ event_delivery.webhook.app.save(update_fields=["is_active"])
+ event_delivery.event_type = event_type
+ event_delivery.save(update_fields=["event_type"])
+
+ # when
+ delivery, not_found = get_delivery_for_webhook(event_delivery.pk)
+
+ # then
+ assert delivery == event_delivery
+ event_delivery.refresh_from_db()
+ assert event_delivery.status == EventDeliveryStatus.PENDING
+ assert not_found is False
+
+
+def test_get_delivery_for_webhook_inactive_webhook_self_lifecycle_event(
+ event_delivery, caplog
+):
+ # given
+ event_delivery.webhook.is_active = False
+ event_delivery.webhook.save(update_fields=["is_active"])
+ event_delivery.event_type = WebhookEventAsyncType.APP_DELETED
+ event_delivery.save(update_fields=["event_type"])
+
+ # when
+ delivery, not_found = get_delivery_for_webhook(event_delivery.pk)
+
+ # then
+ assert delivery is None
+ event_delivery.refresh_from_db()
+ assert event_delivery.status == EventDeliveryStatus.FAILED
+ assert not_found is False
+
+
def test_get_multiple_deliveries_for_webhooks(event_deliveries):
# given
all_deliveries = EventDelivery.objects.all()
diff --git a/saleor/webhook/transport/utils.py b/saleor/webhook/transport/utils.py
index dd95a9224c..cfc81246b2 100644
--- a/saleor/webhook/transport/utils.py
+++ b/saleor/webhook/transport/utils.py
@@ -520,7 +520,17 @@ def get_multiple_deliveries_for_webhooks(
logger.warning("Event delivery id: %r not found", not_found_delivery_id)
for delivery in deliveries:
- if delivery.webhook.is_active and delivery.webhook.app.is_active:
+ # For these 2 apps will (if deleted) or can (if deactivated) be inactive at this point
+ # For these two, we bypass active app check and emit anyway
+ bypass_inactive_check = delivery.event_type in (
+ WebhookEventAsyncType.APP_DELETED,
+ WebhookEventAsyncType.APP_STATUS_CHANGED,
+ )
+ should_deliver = delivery.webhook.is_active and (
+ delivery.webhook.app.is_active or bypass_inactive_check
+ )
+
+ if should_deliver:
active_deliveries[delivery.pk] = delivery
else:
logger.info("Event delivery id: %r app/webhook is disabled.", delivery.pk)
diff --git a/saleor/webhook/utils.py b/saleor/webhook/utils.py
index a5efd313dc..894037bfb0 100644
--- a/saleor/webhook/utils.py
+++ b/saleor/webhook/utils.py
@@ -14,6 +14,16 @@ if TYPE_CHECKING:
from django.db.models import QuerySet
+APP_LIFECYCLE_EVENTS = frozenset(
+ {
+ WebhookEventAsyncType.APP_INSTALLED,
+ WebhookEventAsyncType.APP_UPDATED,
+ WebhookEventAsyncType.APP_DELETED,
+ WebhookEventAsyncType.APP_STATUS_CHANGED,
+ }
+)
+
+
def get_filter_for_single_webhook_event(
event_type: str,
apps_ids: Optional["list[int]"] = None,
@@ -81,6 +91,41 @@ def get_webhooks_for_event(
)
+def get_webhooks_for_app_lifecycle_event(
+ event_type: str,
+ app: "App",
+) -> "QuerySet[Webhook]":
+ """Get webhooks for an app's own lifecycle event.
+
+ App lifecycle events are self-only: only the affected app's own webhook
+ subscriptions receive them. MANAGE_APPS grants no access to events about
+ other apps. The app is intentionally not filtered by is_active /
+ removed_at — it may be deactivated or soft-deleted at dispatch time
+ (APP_DELETED, APP_STATUS_CHANGED on deactivate).
+ """
+ if event_type not in APP_LIFECYCLE_EVENTS:
+ raise ValueError(
+ f"{event_type} is not an app lifecycle event. Use "
+ "get_webhooks_for_event instead."
+ )
+
+ event_types = [event_type, WebhookEventAsyncType.ANY]
+ webhook_events = WebhookEvent.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).filter(event_type__in=event_types)
+
+ return (
+ Webhook.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .filter(
+ is_active=True,
+ app_id=app.id,
+ )
+ .filter(Exists(webhook_events.filter(webhook_id=OuterRef("id"))))
+ .select_related("app")
+ .prefetch_related("app__permissions__content_type")
+ )
+
+
def get_webhooks_for_multiple_events(
event_types: Iterable[str],
) -> dict[str, set[Webhook]]: