Skip to content

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

Refactor app removal process. (#14804)

Artur8d64849187da
diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.py
index cd1e3089a5..e60cd9489a 100644
--- a/saleor/app/installation_utils.py
+++ b/saleor/app/installation_utils.py
@@ -154,7 +154,7 @@ def fetch_brand_data_task(
self, brand_data: dict, *, app_installation_id=None, app_id=None
):
"""Task to fetch app's brand data. Last retry delayed 24H."""
- app = App.objects.filter(id=app_id).first()
+ app = App.objects.filter(id=app_id, removed_at__isnull=True).first()
app_inst = AppInstallation.objects.filter(id=app_installation_id).first()
if not app_inst or (app_inst and app_inst.brand_logo_default):
if not app or (app and app.brand_logo_default):
diff --git a/saleor/app/migrations/0026_app_removed_at.py b/saleor/app/migrations/0026_app_removed_at.py
new file mode 100644
index 0000000000..b26202953e
--- /dev/null
+++ b/saleor/app/migrations/0026_app_removed_at.py
@@ -0,0 +1,17 @@
+# Generated by Django 3.2.22 on 2023-11-07 14:31
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("app", "0025_auto_20230420_1544"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="app",
+ name="removed_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ ]
diff --git a/saleor/app/models.py b/saleor/app/models.py
index 9628f7da76..5bc9208eef 100644
--- a/saleor/app/models.py
+++ b/saleor/app/models.py
@@ -40,6 +40,7 @@ class App(ModelWithMetadata):
name = models.CharField(max_length=60)
created_at = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
+ removed_at = models.DateTimeField(blank=True, null=True)
type = models.CharField(
choices=AppType.CHOICES, default=AppType.LOCAL, max_length=60
)
diff --git a/saleor/app/tasks.py b/saleor/app/tasks.py
index c47d6361ad..4ac2fa1d79 100644
--- a/saleor/app/tasks.py
+++ b/saleor/app/tasks.py
@@ -1,12 +1,17 @@
import logging
+from django.conf import settings
from django.core.exceptions import ValidationError
+from django.db.models import Exists, OuterRef, Q
+from django.utils import timezone
from requests import HTTPError, RequestException
from .. import celeryconf
from ..core import JobStatus
+from ..core.models import EventDelivery, EventDeliveryAttempt, EventPayload
+from ..webhook.models import Webhook
from .installation_utils import AppInstallationError, install_app
-from .models import AppInstallation
+from .models import App, AppExtension, AppInstallation, AppToken
logger = logging.getLogger(__name__)
@@ -46,3 +51,58 @@ def install_app_task(job_id, activate=False):
app_installation.message = "Unknown error. Contact with app support."
app_installation.status = JobStatus.FAILED
app_installation.save(update_fields=["message", "status"])
+
+
+def _raw_remove_deliveries(deliveries_ids):
+ deliveries = EventDelivery.objects.filter(id__in=deliveries_ids)
+ payloads_ids = list(
+ EventPayload.objects.filter(
+ Exists(deliveries.filter(payload_id=OuterRef("id")))
+ ).values_list("id", flat=True)
+ )
+ payloads = EventPayload.objects.filter(id__in=payloads_ids)
+ attempts = EventDeliveryAttempt.objects.filter(
+ Exists(deliveries.filter(id=OuterRef("delivery_id")))
+ )
+ attempts._raw_delete(attempts.db) # type: ignore[attr-defined] # raw access # noqa: E501
+ deliveries._raw_delete(deliveries.db) # type: ignore[attr-defined] # raw access # noqa: E501
+ payloads._raw_delete(payloads.db) # type: ignore[attr-defined] # raw access # noqa: E501
+
+
+def remove_apps_task():
+ app_delete_period = timezone.now() - settings.DELETE_APP_TTL
+ apps = App.objects.filter(removed_at__lte=app_delete_period)
+
+ # Saleor needs to remove app by app to prevent timeouts
+ # on database when removing many deliveries.
+ for app in apps.iterator():
+ webhooks = Webhook.objects.filter(app_id=app.id)
+
+ # Saleor uses batch size here to prevent timeouts on database.
+ # Batch size determines how many deliveries will be removed,
+ # each delivery contains attempts and payloads.
+ batch_size = 10000
+ last_id = 0
+ while True:
+ deliveries_ids = list(
+ EventDelivery.objects.filter(
+ Q(id__gt=last_id),
+ Q(Exists(webhooks.filter(id=OuterRef("webhook_id")))),
+ )
+ .order_by("id")
+ .values_list("id", flat=True)[:batch_size]
+ )
+ if not deliveries_ids:
+ break
+ last_id = deliveries_ids[-1]
+
+ _raw_remove_deliveries(deliveries_ids)
+
+ webhooks.delete()
+
+ AppToken.objects.filter(app_id=app.id).delete()
+
+ AppExtension.objects.filter(app_id=app.id).delete()
+
+ app.delete()
diff --git a/saleor/app/tests/test_app_tasks.py b/saleor/app/tests/test_app_tasks.py
index cd2bb5b82a..1cb8e36297 100644
--- a/saleor/app/tests/test_app_tasks.py
+++ b/saleor/app/tests/test_app_tasks.py
@@ -1,13 +1,16 @@
from unittest.mock import Mock
import pytest
+from django.utils import timezone
from requests import RequestException
from requests_hardened import HTTPSession
from ...core import JobStatus
+from ...core.models import EventDelivery, EventDeliveryAttempt, EventPayload
+from ...webhook.models import Webhook
from ..installation_utils import AppInstallationError
-from ..models import App, AppInstallation
-from ..tasks import install_app_task
+from ..models import App, AppExtension, AppInstallation, AppToken
+from ..tasks import install_app_task, remove_apps_task
@pytest.mark.vcr
@@ -84,3 +87,70 @@ def test_install_app_task_undefined_error(monkeypatch, app_installation):
app_installation.refresh_from_db()
assert app_installation.status == JobStatus.FAILED
assert app_installation.message == "Unknown error. Contact with app support."
+
+
+# Saleor should use `transaction=True` to check if IntegrityError is not raised.
+# IntegrityError is raised when we try to remove app with related objects.
+# Without `transaction=True` test will pass due to be in one atomic bloc.
[email protected]_db(transaction=True)
+def test_remove_app_task(
+ event_attempt_removed_app, removed_app_with_extensions, removed_app
+):
+ # given
+ removed_app.tokens.create(name="token1")
+ assert App.objects.count() > 0
+ assert AppToken.objects.count() > 0
+ assert AppExtension.objects.count() > 0
+ assert Webhook.objects.count() > 0
+ assert EventDelivery.objects.count() > 0
+ assert EventPayload.objects.count() > 0
+ assert EventDeliveryAttempt.objects.count() > 0
+
+ # when
+ remove_apps_task()
+
+ # then
+ assert App.objects.count() == 0
+ assert AppToken.objects.count() == 0
+ assert AppExtension.objects.count() == 0
+ assert Webhook.objects.count() == 0
+ assert EventDelivery.objects.count() == 0
+ assert EventPayload.objects.count() == 0
+ assert EventDeliveryAttempt.objects.count() == 0
+
+
+def test_remove_app_task_not_remove_not_own_payloads(
+ event_attempt_removed_app,
+):
+ # given
+ EventPayload.objects.create(payload="")
+ assert EventPayload.objects.count() == 2
+
+ # when
+ remove_apps_task()
+
+ # then
+ assert EventPayload.objects.count() == 1
+
+
+def test_remove_app_task_no_app_to_remove(app):
+ # given
+ assert App.objects.count() == 1
+
+ # when
+ remove_apps_task()
+
+ # then
+ assert App.objects.count() == 1
+
+
+def test_remove_app_task_delete_period_in_progress():
+ # given
+ App.objects.create(name="App", is_active=True, removed_at=timezone.now())
+ assert App.objects.count() == 1
+
+ # when
+ remove_apps_task()
+
+ # then
+ assert App.objects.count() == 1
diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.py
index 3835faaf6a..a167cca0bd 100644
--- a/saleor/app/tests/test_installation_utils.py
+++ b/saleor/app/tests/test_installation_utils.py
@@ -747,6 +747,14 @@ def test_fetch_brand_data_task_terminated(
mock_fetch_icon_image.assert_not_called()
+@patch("saleor.app.installation_utils.fetch_icon_image")
+def test_fetch_brand_data_task_for_removed_app(
+ mock_fetch_icon_image, removed_app, media_root
+):
+ fetch_brand_data_task({}, app_id=removed_app.id)
+ mock_fetch_icon_image.assert_not_called()
+
+
@patch("saleor.app.installation_utils.fetch_icon_image")
def test_fetch_brand_data_task_terminated_when_brand_data_fetched(
mock_fetch_icon_image, app_installation, app, media_root
diff --git a/saleor/core/tests/test_taxes.py b/saleor/core/tests/test_taxes.py
index e87d884cd9..7a4b81251e 100644
--- a/saleor/core/tests/test_taxes.py
+++ b/saleor/core/tests/test_taxes.py
@@ -1,4 +1,5 @@
import pytest
+from django.utils import timezone
from ...app.models import App
from ...permission.enums import (
@@ -65,6 +66,12 @@ def test_get_current_tax_app(tax_app):
assert tax_app == get_current_tax_app()
+def test_get_current_tax_app_removed_app(tax_app):
+ tax_app.removed_at = timezone.now()
+ tax_app.save(update_fields=["removed_at"])
+ assert get_current_tax_app() is None
+
+
def test_get_current_tax_app_multiple_apps(app_factory, tax_app_factory):
# given
tax_app_factory(
diff --git a/saleor/graphql/account/tests/queries/test_account_events.py b/saleor/graphql/account/tests/queries/test_account_events.py
index dfc41a94da..8c95acf016 100644
--- a/saleor/graphql/account/tests/queries/test_account_events.py
+++ b/saleor/graphql/account/tests/queries/test_account_events.py
@@ -398,3 +398,26 @@ def test_account_event_staff_user_assigned_email_to_customer_event_resolves_prop
)
assert expected_data == received_data
+
+
+def test_account_event_created_by_removed_app(
+ staff_api_client,
+ customer_user,
+ permission_manage_users,
+ permission_manage_apps,
+ removed_app,
+):
+ # given
+ account_events.customer_account_activated_event(
+ staff_user=customer_user, app=removed_app, account_id=7
+ )
+
+ # then
+ received_data = _get_event_from_graphql(
+ staff_api_client,
+ customer_user,
+ (permission_manage_users, permission_manage_apps),
+ )
+
+ # when
+ assert received_data["app"] is None
diff --git a/saleor/graphql/app/dataloaders.py b/saleor/graphql/app/dataloaders.py
index 689148c18b..c0fa280fc4 100644
--- a/saleor/graphql/app/dataloaders.py
+++ b/saleor/graphql/app/dataloaders.py
@@ -17,7 +17,11 @@ class AppByIdLoader(DataLoader):
context_key = "app_by_id"
def batch_load(self, keys):
- apps = App.objects.using(self.database_connection_name).in_bulk(keys)
+ apps = (
+ App.objects.using(self.database_connection_name)
+ .filter(removed_at__isnull=True)
+ .in_bulk(keys)
+ )
return [apps.get(key) for key in keys]
@@ -51,7 +55,7 @@ class AppsByAppIdentifierLoader(DataLoader):
def batch_load(self, keys):
apps = App.objects.using(self.database_connection_name).filter(
- identifier__in=keys
+ identifier__in=keys, removed_at__isnull=True
)
apps_map = defaultdict(list)
for app in apps:
@@ -64,7 +68,7 @@ class AppTokensByAppIdLoader(DataLoader):
def batch_load(self, keys):
tokens = AppToken.objects.using(self.database_connection_name).filter(
- app_id__in=keys
+ app_id__in=keys, app__removed_at__isnull=True
)
tokens_by_app_map = defaultdict(list)
for token in tokens:
@@ -93,7 +97,9 @@ class AppByTokenLoader(DataLoader):
apps = (
App.objects.using(self.database_connection_name)
- .filter(id__in=authed_apps.values(), is_active=True)
+ .filter(
+ id__in=authed_apps.values(), is_active=True, removed_at__isnull=True
+ )
.in_bulk()
)
diff --git a/saleor/graphql/app/mutations/app_activate.py b/saleor/graphql/app/mutations/app_activate.py
index d4bbbabe47..9b61dddcf9 100644
--- a/saleor/graphql/app/mutations/app_activate.py
+++ b/saleor/graphql/app/mutations/app_activate.py
@@ -30,7 +30,12 @@ class AppActivate(ModelMutation):
@classmethod
def perform_mutation(cls, _root, info, /, *, id):
- app = cls.get_instance(info, id=id)
+ qs = models.App.objects.filter(removed_at__isnull=True)
+ app = cls.get_instance(
+ info,
+ id=id,
+ qs=qs,
+ )
app.is_active = True
cls.save(info, app, None)
manager = get_plugin_manager_promise(info.context).get()
diff --git a/saleor/graphql/app/mutations/app_deactivate.py b/saleor/graphql/app/mutations/app_deactivate.py
index 097e8e1740..a2ad852aef 100644
--- a/saleor/graphql/app/mutations/app_deactivate.py
+++ b/saleor/graphql/app/mutations/app_deactivate.py
@@ -30,7 +30,12 @@ class AppDeactivate(ModelMutation):
@classmethod
def perform_mutation(cls, _root, info, /, *, id):
- app = cls.get_instance(info, id=id)
+ qs = models.App.objects.filter(removed_at__isnull=True)
+ app = cls.get_instance(
+ info,
+ id=id,
+ qs=qs,
+ )
app.is_active = False
cls.save(info, app, None)
manager = get_plugin_manager_promise(info.context).get()
diff --git a/saleor/graphql/app/mutations/app_delete.py b/saleor/graphql/app/mutations/app_delete.py
index 5c7f4179c4..2ded2780ca 100644
--- a/saleor/graphql/app/mutations/app_delete.py
+++ b/saleor/graphql/app/mutations/app_delete.py
@@ -1,5 +1,6 @@
import graphene
from django.core.exceptions import ValidationError
+from django.utils import timezone
from ....app import models
from ....app.error_codes import AppErrorCode
@@ -7,7 +8,7 @@ from ....permission.enums import AppPermission
from ....webhook.event_types import WebhookEventAsyncType
from ...account.utils import can_manage_app
from ...core import ResolveInfo
-from ...core.mutations import ModelDeleteMutation
+from ...core.mutations import ModelMutation
from ...core.types import AppError
from ...core.utils import WebhookEventInfo
from ...plugins.dataloaders import get_plugin_manager_promise
@@ -15,7 +16,7 @@ from ...utils import get_user_or_app_from_context, requestor_is_superuser
from ..types import App
-class AppDelete(ModelDeleteMutation):
+class AppDelete(ModelMutation):
class Arguments:
id = graphene.ID(description="ID of an app to delete.", required=True)
@@ -33,6 +34,12 @@ class AppDelete(ModelDeleteMutation):
),
]
+ @classmethod
+ def get_instance(cls, info: ResolveInfo, **data):
+ data["qs"] = models.App.objects.filter(removed_at__isnull=True)
+ instance = super().get_instance(info, **data)
+ return instance
+
@classmethod
def clean_instance(cls, info: ResolveInfo, instance):
requestor = get_user_or_app_from_context(info.context)
@@ -47,3 +54,15 @@ class AppDelete(ModelDeleteMutation):
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"])
+
+ cls.post_save_action(info, instance, {})
+ return cls.success_response(instance)
diff --git a/saleor/graphql/app/mutations/app_token_create.py b/saleor/graphql/app/mutations/app_token_create.py
index 5e23348559..bd9e4752d8 100644
--- a/saleor/graphql/app/mutations/app_token_create.py
+++ b/saleor/graphql/app/mutations/app_token_create.py
@@ -11,6 +11,7 @@ from ...core.mutations import ModelMutation
from ...core.types import AppError, BaseInputObjectType
from ...utils import get_user_or_app_from_context, requestor_is_superuser
from ..types import AppToken
+from ..utils import validate_app_is_not_removed
class AppTokenInput(BaseInputObjectType):
@@ -58,6 +59,7 @@ class AppTokenCreate(ModelMutation):
def clean_input(cls, info, instance, data):
cleaned_input = super().clean_input(info, instance, data)
app = cleaned_input.get("app")
+ validate_app_is_not_removed(app, data.get("app"), "app")
requestor = get_user_or_app_from_context(info.context)
if not requestor_is_superuser(requestor) and not can_manage_app(requestor, app):
msg = "You can't manage this app."
diff --git a/saleor/graphql/app/mutations/app_token_delete.py b/saleor/graphql/app/mutations/app_token_delete.py
index 1e21cd2d0d..2d87fd00c1 100644
--- a/saleor/graphql/app/mutations/app_token_delete.py
+++ b/saleor/graphql/app/mutations/app_token_delete.py
@@ -1,3 +1,5 @@
+from typing import cast
+
import graphene
from django.core.exceptions import ValidationError
@@ -10,6 +12,7 @@ from ...core.mutations import ModelDeleteMutation
from ...core.types import AppError
from ...utils import get_user_or_app_from_context, requestor_is_superuser
from ..types import AppToken
+from ..utils import validate_app_is_not_removed
class AppTokenDelete(ModelDeleteMutation):
@@ -24,6 +27,15 @@ class AppTokenDelete(ModelDeleteMutation):
error_type_class = AppError
error_type_field = "app_errors"
+ @classmethod
+ def get_instance(cls, info: ResolveInfo, **data):
+ token_id = data.get("id")
+ # ID is required. The type could be cast to str.
+ token_id = cast(str, token_id)
+ instance = super(ModelDeleteMutation, cls).get_instance(info, id=token_id)
+ validate_app_is_not_removed(instance.app, token_id, "id")
+ return instance
+
@classmethod
def clean_instance(cls, info: ResolveInfo, instance):
app = instance.app
diff --git a/saleor/graphql/app/mutations/app_token_verify.py b/saleor/graphql/app/mutations/app_token_verify.py
index 13ede47cec..9878f838c0 100644
--- a/saleor/graphql/app/mutations/app_token_verify.py
+++ b/saleor/graphql/app/mutations/app_token_verify.py
@@ -1,5 +1,6 @@
import graphene
from django.contrib.auth.hashers import check_password
+from django.db.models import Exists, OuterRef, Q
from ....app import models
from ...core.doc_category import DOC_CATEGORY_APPS
@@ -25,8 +26,11 @@ class AppTokenVerify(BaseMutation):
@classmethod
def perform_mutation(cls, _root, _info, /, *, token: str): # type: ignore[override]
+ apps = models.App.objects.filter(
+ is_active=True, removed_at__isnull=True
+ ).values("pk")
tokens = models.AppToken.objects.filter(
- app__is_active=True, token_last_4=token[-4:]
+ Q(token_last_4=token[-4:]), Exists(apps.filter(pk=OuterRef("app_id")))
).values_list("auth_token", flat=True)
valid = any([check_password(token, auth_token) for auth_token in tokens])
return AppTokenVerify(valid=valid)
diff --git a/saleor/graphql/app/mutations/app_update.py b/saleor/graphql/app/mutations/app_update.py
index e2d15d7f28..79d2f73ad7 100644
--- a/saleor/graphql/app/mutations/app_update.py
+++ b/saleor/graphql/app/mutations/app_update.py
@@ -6,6 +6,7 @@ from ....app.error_codes import AppErrorCode
from ....permission.enums import AppPermission, get_permissions
from ....webhook.event_types import WebhookEventAsyncType
from ...account.utils import can_manage_app
+from ...core import ResolveInfo
from ...core.mutations import ModelMutation
from ...core.types import AppError
from ...core.utils import WebhookEventInfo
@@ -38,6 +39,12 @@ class AppUpdate(ModelMutation):
),
]
+ @classmethod
+ def get_instance(cls, info: ResolveInfo, **data):
+ data["qs"] = models.App.objects.filter(removed_at__isnull=True)
+ instance = super().get_instance(info, **data)
+ return instance
+
@classmethod
def clean_input(cls, info, instance, data, **kwargs):
cleaned_input = super().clean_input(info, instance, data, **kwargs)
diff --git a/saleor/graphql/app/resolvers.py b/saleor/graphql/app/resolvers.py
index bcece42702..519ad0e207 100644
--- a/saleor/graphql/app/resolvers.py
+++ b/saleor/graphql/app/resolvers.py
@@ -1,5 +1,7 @@
from urllib.parse import urljoin, urlparse
+from django.db.models import Exists, OuterRef
+
from ...app import models
from ...app.types import AppExtensionTarget
from ...core.jwt import (
@@ -20,7 +22,7 @@ def resolve_apps_installations(info):
def resolve_apps(info):
return (
models.App.objects.using(get_database_connection_name(info.context))
- .filter(is_installed=True)
+ .filter(is_installed=True, removed_at__isnull=True)
.all()
)
@@ -56,15 +58,21 @@ def resolve_app(info, id):
_, id = from_global_id_or_error(id, "App")
return (
models.App.objects.using(get_database_connection_name(info.context))
- .filter(id=id, is_installed=True)
+ .filter(id=id, is_installed=True, removed_at__isnull=True)
.first()
)
def resolve_app_extensions(info):
- return models.AppExtension.objects.using(
- get_database_connection_name(info.context)
- ).filter(app__is_active=True)
+ connection = get_database_connection_name(info.context)
+ apps = (
+ models.App.objects.using(connection)
+ .filter(is_active=True, removed_at__isnull=True)
+ .values("pk")
+ )
+ return models.AppExtension.objects.using(connection).filter(
+ Exists(apps.filter(id=OuterRef("app_id")))
+ )
def resolve_app_extension_url(root):
diff --git a/saleor/graphql/app/schema.py b/saleor/graphql/app/schema.py
index 6f21294631..816792b6bc 100644
--- a/saleor/graphql/app/schema.py
+++ b/saleor/graphql/app/schema.py
@@ -153,7 +153,7 @@ class AppQueries(graphene.ObjectType):
def resolve_app_extension(_root, info: ResolveInfo, *, id):
def app_is_active(app_extension):
def is_active(app):
- if app.is_active:
+ if app and app.is_active:
return app_extension
return None
diff --git a/saleor/graphql/app/tests/mutations/test_app_activate.py b/saleor/graphql/app/tests/mutations/test_app_activate.py
index 6ad388db05..fc929ac68f 100644
--- a/saleor/graphql/app/tests/mutations/test_app_activate.py
+++ b/saleor/graphql/app/tests/mutations/test_app_activate.py
@@ -5,6 +5,7 @@ import graphene
from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
+from .....app.error_codes import AppErrorCode
from .....app.models import App
from .....core.utils.json_serializer import CustomJsonEncoder
from .....webhook.event_types import WebhookEventAsyncType
@@ -226,3 +227,28 @@ def test_app_has_more_permission_than_app_requestor(
assert not app_errors
assert app_data["isActive"] is True
assert app.is_active
+
+
+def test_app_activate_mutation_removed_app(
+ removed_app,
+ permission_manage_apps,
+ staff_api_client,
+):
+ # given
+ query = APP_ACTIVATE_MUTATION
+ id = graphene.Node.to_global_id("App", removed_app.id)
+ variables = {
+ "id": id,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables=variables, permissions=(permission_manage_apps,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ app_data = content["data"]["appActivate"]
+ assert app_data["app"] is None
+ assert app_data["errors"][0]["code"] == AppErrorCode.NOT_FOUND.name
+ assert app_data["errors"][0]["field"] == "id"
diff --git a/saleor/graphql/app/tests/mutations/test_app_deactivate.py b/saleor/graphql/app/tests/mutations/test_app_deactivate.py
index d64fb632d3..387fcf438c 100644
--- a/saleor/graphql/app/tests/mutations/test_app_deactivate.py
+++ b/saleor/graphql/app/tests/mutations/test_app_deactivate.py
@@ -5,6 +5,7 @@ import graphene
from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
+from .....app.error_codes import AppErrorCode
from .....app.models import App
from .....core.utils.json_serializer import CustomJsonEncoder
from .....webhook.event_types import WebhookEventAsyncType
@@ -226,3 +227,26 @@ def test_app_has_more_permission_than_app_requestor(
assert not app_errors
assert not app.is_active
assert app_data["isActive"] is False
+
+
+def test_deactivate_app_for_removed_app(
+ removed_app, staff_api_client, permission_manage_apps
+):
+ # given
+ query = APP_DEACTIVATE_MUTATION
+ id = graphene.Node.to_global_id("App", removed_app.id)
+ variables = {
+ "id": id,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables=variables, permissions=(permission_manage_apps,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ app_data = content["data"]["appDeactivate"]
+ assert app_data["app"] is None
+ assert app_data["errors"][0]["code"] == AppErrorCode.NOT_FOUND.name
+ assert app_data["errors"][0]["field"] == "id"
diff --git a/saleor/graphql/app/tests/mutations/test_app_delete.py b/saleor/graphql/app/tests/mutations/test_app_delete.py
index f04c36d2b5..f377c6116b 100644
--- a/saleor/graphql/app/tests/mutations/test_app_delete.py
+++ b/saleor/graphql/app/tests/mutations/test_app_delete.py
@@ -49,7 +49,10 @@ def test_app_delete(
data = content["data"]["appDelete"]
assert data["app"]
assert not data["errors"]
- assert not App.objects.filter(id=app.id)
+ assert data["app"]["name"] == app.name
+ app.refresh_from_db()
+ assert app.removed_at is not None
+ assert app.is_active is False
@freeze_time("2022-05-12 12:00:00")
@@ -88,7 +91,7 @@ def test_app_delete_trigger_webhook(
json.dumps(
{
"id": app_global_id,
- "is_active": app.is_active,
+ "is_active": False,
"name": app.name,
"meta": generate_meta(
requestor_data=generate_requestor(
@@ -126,7 +129,10 @@ def test_app_delete_for_app(
data = content["data"]["appDelete"]
assert data["app"]
assert not data["errors"]
- assert not App.objects.filter(id=app.id).exists()
+ assert data["app"]["name"] == app.name
+ app.refresh_from_db()
+ assert app.removed_at is not None
+ assert app.is_active is False
def test_app_delete_out_of_scope_app(
@@ -176,7 +182,10 @@ def test_app_delete_superuser_can_delete_any_app(
data = content["data"]["appDelete"]
assert data["app"]
assert not data["errors"]
- assert not App.objects.filter(id=app.id).exists()
+ assert data["app"]["name"] == app.name
+ app.refresh_from_db()
+ assert app.removed_at is not None
+ assert app.is_active is False
def test_app_delete_for_app_out_of_scope_app(
@@ -202,3 +211,26 @@ def test_app_delete_for_app_out_of_scope_app(
error = errors[0]
assert error["code"] == AppErrorCode.OUT_OF_SCOPE_APP.name
assert error["field"] == "id"
+
+
+def test_app_delete_with_removed_app(
+ staff_api_client,
+ staff_user,
+ removed_app,
+ permission_manage_orders,
+ permission_manage_apps,
+):
+ query = APP_DELETE_MUTATION
+ staff_user.user_permissions.add(permission_manage_orders)
+ id = graphene.Node.to_global_id("App", removed_app.id)
+
+ variables = {"id": id}
+ response = staff_api_client.post_graphql(
+ query, variables=variables, permissions=(permission_manage_apps,)
+ )
+ content = get_graphql_content(response)
+
+ app_data = content["data"]["appDelete"]
+ assert app_data["app"] is None
+ assert app_data["errors"][0]["code"] == AppErrorCode.NOT_FOUND.name
+ assert app_data["errors"][0]["field"] == "id"
diff --git a/saleor/graphql/app/tests/mutations/test_app_token_create.py b/saleor/graphql/app/tests/mutations/test_app_token_create.py
index 5e3f2ccf84..27a999dbac 100644
--- a/saleor/graphql/app/tests/mutations/test_app_token_create.py
+++ b/saleor/graphql/app/tests/mutations/test_app_token_create.py
@@ -189,3 +189,33 @@ def test_app_token_create_no_permissions(staff_api_client, staff_user):
# then
assert_no_permission(response)
+
+
+def test_app_token_create_for_removed_app(
+ permission_manage_apps,
+ staff_api_client,
+ staff_user,
+ permission_manage_orders,
+ removed_app,
+):
+ # given
+ app = removed_app
+ query = APP_TOKEN_CREATE_MUTATION
+ staff_user.user_permissions.add(permission_manage_orders)
+ app.permissions.add(permission_manage_orders)
+
+ id = graphene.Node.to_global_id("App", app.id)
+ variables = {"name": "Default token", "app": id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables={"input": variables}, permissions=(permission_manage_apps,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ app_data = content["data"]["appTokenCreate"]
+ assert app_data["appToken"] is None
+ assert app_data["errors"][0]["code"] == AppErrorCode.NOT_FOUND.name
+ assert app_data["errors"][0]["field"] == "app"
+ assert app_data["errors"][0]["message"] == f"Couldn't resolve to a node: {id}"
diff --git a/saleor/graphql/app/tests/mutations/test_app_token_delete.py b/saleor/graphql/app/tests/mutations/test_app_token_delete.py
index a7dd36897c..4d3b236a9f 100644
--- a/saleor/graphql/app/tests/mutations/test_app_token_delete.py
+++ b/saleor/graphql/app/tests/mutations/test_app_token_delete.py
@@ -158,3 +158,33 @@ def test_app_token_delete_for_app_out_of_scope_app(
assert error["code"] == AppErrorCode.OUT_OF_SCOPE_APP.name
assert error["field"] == "id"
assert AppToken.objects.filter(id=token.id).exists()
+
+
+def test_app_token_delete_for_removed_app(
+ permission_manage_apps,
+ staff_api_client,
+ staff_user,
+ removed_app,
+ permission_manage_products,
+):
+ # given
+ query = APP_TOKEN_DELETE_MUTATION
+ app = removed_app
+ token, _ = app.tokens.create()
+ staff_user.user_permissions.add(permission_manage_products)
+ app.permissions.add(permission_manage_products)
+ id = graphene.Node.to_global_id("AppToken", token.id)
+ variables = {"id": id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables=variables, permissions=(permission_manage_apps,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ app_data = content["data"]["appTokenDelete"]
+ assert app_data["appToken"] is None
+ assert app_data["errors"][0]["code"] == AppErrorCode.NOT_FOUND.name
+ assert app_data["errors"][0]["field"] == "id"
+ assert app_data["errors"][0]["message"] == f"Couldn't resolve to a node: {id}"
diff --git a/saleor/graphql/app/tests/mutations/test_app_token_verify.py b/saleor/graphql/app/tests/mutations/test_app_token_verify.py
index 98accc1a52..0d4911edb4 100644
--- a/saleor/graphql/app/tests/mutations/test_app_token_verify.py
+++ b/saleor/graphql/app/tests/mutations/test_app_token_verify.py
@@ -4,27 +4,74 @@ APP_TOKEN_VERIFY_MUTATION = """
mutation AppTokenVerify($token: String!){
appTokenVerify(token:$token){
valid
+ errors {
+ field
+ message
+ code
+ }
}
}
"""
def test_app_token_verify_valid_token(app, api_client):
+ # given
_, token = app.tokens.create()
query = APP_TOKEN_VERIFY_MUTATION
-
variables = {"token": token}
+
+ # when
response = api_client.post_graphql(query, variables=variables)
+
+ # then
content = get_graphql_content(response)
assert content["data"]["appTokenVerify"]["valid"]
def test_app_token_verify_invalid_token(app, api_client):
+ # given
_, token = app.tokens.create()
token += "incorrect"
query = APP_TOKEN_VERIFY_MUTATION
-
variables = {"token": token}
+
+ # when
response = api_client.post_graphql(query, variables=variables)
+
+ # then
content = get_graphql_content(response)
assert not content["data"]["appTokenVerify"]["valid"]
+
+
+def test_app_token_verify_app_turned_off(app, api_client):
+ # given
+ app.is_active = False
+ app.save()
+ _, token = app.tokens.create()
+ query = APP_TOKEN_VERIFY_MUTATION
+ variables = {"token": token}
+
+ # when
+ response = api_client.post_graphql(query, variables=variables)
+
+ # then
+ content = get_graphql_content(response)
+ app_data = content["data"]["appTokenVerify"]
+ assert app_data["valid"] is False
+ assert not app_data["errors"]
+
+
+def test_app_token_verify_removed_app(removed_app, api_client):
+ # given
+ _, token = removed_app.tokens.create()
+ query = APP_TOKEN_VERIFY_MUTATION
+ variables = {"token": token}
+
+ # when
+ response = api_client.post_graphql(query, variables=variables)
+
+ # then
+ content = get_graphql_content(response)
+ app_data = content["data"]["appTokenVerify"]
+ assert app_data["valid"] is False
+ assert not app_data["errors"]
diff --git a/saleor/graphql/app/tests/mutations/test_app_update.py b/saleor/graphql/app/tests/mutations/test_app_update.py
index c94e9a7ee6..e8b7b59298 100644
--- a/saleor/graphql/app/tests/mutations/test_app_update.py
+++ b/saleor/graphql/app/tests/mutations/test_app_update.py
@@ -420,3 +420,39 @@ def test_app_update_no_permission(app, staff_api_client, staff_user):
}
response = staff_api_client.post_graphql(query, variables=variables)
assert_no_permission(response)
+
+
+def test_app_update_mutation_removed_app(
+ removed_app,
+ permission_manage_apps,
+ permission_manage_products,
+ permission_manage_users,
+ staff_api_client,
+ staff_user,
+):
+ # given
+ query = APP_UPDATE_MUTATION
+ app = removed_app
+ staff_user.user_permissions.add(permission_manage_products, permission_manage_users)
+ id = graphene.Node.to_global_id("App", app.id)
+
+ variables = {
+ "id": id,
+ "permissions": [
+ PermissionEnum.MANAGE_PRODUCTS.name,
+ PermissionEnum.MANAGE_USERS.name,
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables=variables, permissions=(permission_manage_apps,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ app_data = content["data"]["appUpdate"]
+ assert app_data["app"] is None
+ assert app_data["errors"][0]["code"] == AppErrorCode.NOT_FOUND.name
+ assert app_data["errors"][0]["field"] == "id"
diff --git a/saleor/graphql/app/tests/queries/test_app.py b/saleor/graphql/app/tests/queries/test_app.py
index 4804f05f36..e640df8628 100644
--- a/saleor/graphql/app/tests/queries/test_app.py
+++ b/saleor/graphql/app/tests/queries/test_app.py
@@ -7,6 +7,7 @@ from .....app.types import AppType
from .....core.jwt import create_access_token_for_app, jwt_decode
from .....thumbnail import IconThumbnailFormat
from .....thumbnail.models import Thumbnail
+from ....tests.fixtures import ApiClient
from ....tests.utils import assert_no_permission, get_graphql_content
QUERY_APP = """
@@ -227,6 +228,21 @@ def test_own_app_without_id(
assert app_data["privateMetadata"][0]["value"] == "metadata"
+def test_own_app_without_id_as_removed_app(
+ removed_app,
+):
+ # given
+ removed_app_api_client = ApiClient(app=removed_app)
+
+ # when
+ response = removed_app_api_client.post_graphql(
+ QUERY_APP,
+ )
+
+ # then
+ assert_no_permission(response)
+
+
def test_app_query_without_permission(
app_api_client,
app,
@@ -342,6 +358,30 @@ def test_app_query_pending_installation(staff_api_client, app):
assert content["data"]["app"] is None
+def test_app_query_app_marked_as_removed(
+ staff_api_client,
+ permission_manage_apps,
+ removed_app,
+):
+ # given
+ app = removed_app
+ id = graphene.Node.to_global_id("App", app.id)
+ variables = {"id": id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_APP,
+ variables,
+ permissions=[permission_manage_apps],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ app_data = content["data"]["app"]
+ assert not app_data
+
+
QUERY_APP_AVAILABLE_FOR_STAFF_WITHOUT_MANAGE_APPS = """
query ($id: ID, $size: Int, $format: IconThumbnailFormatEnum){
app(id: $id){
diff --git a/saleor/graphql/app/tests/queries/test_app_extension.py b/saleor/graphql/app/tests/queries/test_app_extension.py
index 5e5e77bcf4..2f2aaff867 100644
--- a/saleor/graphql/app/tests/queries/test_app_extension.py
+++ b/saleor/graphql/app/tests/queries/test_app_extension.py
@@ -86,6 +86,32 @@ def test_app_extension_by_app(app, app_api_client, permission_manage_products):
assert app_extension.permissions.first().codename == permission_code
+def test_app_extensions_app_removed_app(
+ staff_api_client, removed_app, permission_manage_products
+):
+ # given
+ app_extension = AppExtension.objects.create(
+ app=removed_app,
+ label="Create product with App",
+ url="https://www.example.com/app-product",
+ mount=AppExtensionMount.PRODUCT_OVERVIEW_MORE_ACTIONS,
+ )
+ app_extension.permissions.add(permission_manage_products)
+ id = graphene.Node.to_global_id("AppExtension", app_extension.id)
+ variables = {"id": id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_APP_EXTENSION,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ extension_data = content["data"]["appExtension"]
+ assert extension_data is None
+
+
def test_app_extension_normal_user(app, user_api_client, permission_manage_products):
# given
app_extension = AppExtension.objects.create(
diff --git a/saleor/graphql/app/tests/queries/test_app_extensions.py b/saleor/graphql/app/tests/queries/test_app_extensions.py
index 9d3dc7f9db..decbee135d 100644
--- a/saleor/graphql/app/tests/queries/test_app_extensions.py
+++ b/saleor/graphql/app/tests/queries/test_app_extensions.py
@@ -96,6 +96,33 @@ def test_app_extensions_app_not_active(
assert len(extensions_data) == 0
+def test_app_extensions_app_removed_app(
+ staff_api_client, removed_app, permission_manage_products
+):
+ # given
+ app_extension = AppExtension.objects.create(
+ app=removed_app,
+ label="Create product with App",
+ url="https://www.example.com/app-product",
+ mount=AppExtensionMount.PRODUCT_OVERVIEW_MORE_ACTIONS,
+ )
+ app_extension.permissions.add(permission_manage_products)
+ variables = {}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_APP_EXTENSIONS,
+ variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ extensions_data = content["data"]["appExtensions"]["edges"]
+
+ assert len(extensions_data) == 0
+
+
def test_app_extensions_user_not_staff(
user_api_client, app, permission_manage_products
):
diff --git a/saleor/graphql/app/tests/queries/test_apps.py b/saleor/graphql/app/tests/queries/test_apps.py
index 5abc13493c..3e01634277 100644
--- a/saleor/graphql/app/tests/queries/test_apps.py
+++ b/saleor/graphql/app/tests/queries/test_apps.py
@@ -160,6 +160,26 @@ def test_apps_query_no_permission(
assert_no_permission(response)
+def test_apps_query_marked_as_removed(
+ staff_api_client, permission_manage_apps, app, removed_app
+):
+ # given
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_APPS_WITH_FILTER,
+ {},
+ permissions=[permission_manage_apps],
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ apps_data = content["data"]["apps"]["edges"]
+ assert apps_data[0]["node"]["name"] == app.name
+ assert len(apps_data) == 1
+
+
QUERY_APPS_WITH_SORT = """
query ($sort_by: AppSortingInput!) {
apps(first:5, sortBy: $sort_by) {
diff --git a/saleor/graphql/app/utils.py b/saleor/graphql/app/utils.py
index 02711d46c8..748fc0538d 100644
--- a/saleor/graphql/app/utils.py
+++ b/saleor/graphql/app/utils.py
@@ -1,5 +1,8 @@
+from typing import Optional
+
from django.core.exceptions import ValidationError
+from ...app.models import App
from ..account.utils import get_out_of_scope_permissions
from ..core.enums import AppErrorCode
from ..utils import requestor_is_superuser
@@ -21,3 +24,19 @@ def ensure_can_manage_permissions(requestor, permission_items):
raise ValidationError(
{"permissions": ValidationError(error_msg, code=code, params=params)}
)
+
+
+def validate_app_is_not_removed(
+ app: Optional[App],
+ app_global_id: str,
+ field_name: str,
+ code: str = AppErrorCode.NOT_FOUND.value,
+):
+ if app and app.removed_at is not None:
+ raise ValidationError(
+ {
+ field_name: ValidationError(
+ f"Couldn't resolve to a node: {app_global_id}", code=code
+ )
+ }
+ )
diff --git a/saleor/graphql/csv/tests/queries/test_export_file.py b/saleor/graphql/csv/tests/queries/test_export_file.py
index 48312d7caf..64027a3c08 100644
--- a/saleor/graphql/csv/tests/queries/test_export_file.py
+++ b/saleor/graphql/csv/tests/queries/test_export_file.py
@@ -172,6 +172,48 @@ def test_query_export_file_export_file_with_app(
assert event["app"]["name"] == app.name
+def test_query_export_file_export_file_with_removed_app(
+ app,
+ staff_api_client,
+ removed_app_export_file,
+ permission_manage_products,
+ permission_manage_apps,
+ permission_manage_staff,
+ removed_app_export_event,
+):
+ # given
+ query = EXPORT_FILE_BY_APP_QUERY
+ variables = {
+ "id": graphene.Node.to_global_id("ExportFile", removed_app_export_file.pk)
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables=variables,
+ permissions=[
+ permission_manage_products,
+ permission_manage_apps,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["exportFile"]
+
+ assert data["status"] == JobStatus.PENDING.upper()
+ assert data["createdAt"]
+ assert data["updatedAt"]
+ assert data["app"] is None
+ assert not data["url"]
+ assert len(data["events"]) == 1
+ event = data["events"][0]
+ assert event["date"]
+ assert event["message"] == removed_app_export_event.parameters.get("message")
+ assert event["type"] == ExportEvents.EXPORT_FAILED.upper()
+ assert event["app"] is None
+
+
def test_query_export_file_as_app(
app_api_client,
user_export_file,
diff --git a/saleor/graphql/csv/types.py b/saleor/graphql/csv/types.py
index b6fd81bdc1..2321300cd2 100644
--- a/saleor/graphql/csv/types.py
+++ b/saleor/graphql/csv/types.py
@@ -64,7 +64,7 @@ class ExportEvent(ModelObjectType[models.ExportEvent]):
check_is_owner_or_has_one_of_perms(
requestor, root.user, AppPermission.MANAGE_APPS
)
- return root.app
+ return AppByIdLoader(info.context).load(root.app_id) if root.app_id else None
@staticmethod
def resolve_message(root: models.ExportEvent, _info: ResolveInfo):
diff --git a/saleor/graphql/giftcard/tests/queries/test_gift_card.py b/saleor/graphql/giftcard/tests/queries/test_gift_card.py
index d715a732e6..70d75f6db0 100644
--- a/saleor/graphql/giftcard/tests/queries/test_gift_card.py
+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card.py
@@ -166,6 +166,38 @@ def test_query_gift_card_by_app(
assert data["app"]["name"] == app.name
+def test_query_gift_card_by_removed_app(
+ staff_api_client,
+ gift_card,
+ removed_app,
+ permission_manage_gift_card,
+ permission_manage_users,
+ permission_manage_apps,
+):
+ # given
+ gift_card.app = removed_app
+ gift_card.save(update_fields=["app"])
+ query = QUERY_GIFT_CARD_BY_ID
+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.pk)
+ variables = {"id": gift_card_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[
+ permission_manage_gift_card,
+ permission_manage_users,
+ permission_manage_apps,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["giftCard"]
+ assert data["app"] is None
+
+
def test_query_gift_card_by_app_no_premissions(
app_api_client, gift_card_created_by_staff
):
@@ -486,6 +518,44 @@ def test_query_gift_card_events(
assert events_data[1]["oldExpiryDate"] == parameters["old_expiry_date"].isoformat()
+def test_query_gift_card_event_with_removed_app(
+ staff_api_client,
+ removed_app,
+ gift_card,
+ permission_manage_gift_card,
+ permission_manage_apps,
+ permission_manage_users,
+):
+ # given
+ staff_api_client.user
+
+ GiftCardEvent.objects.create(
+ app=removed_app,
+ gift_card=gift_card,
+ type=GiftCardEvents.ISSUED,
+ date=timezone.now(),
+ )
+
+ variables = {"id": graphene.Node.to_global_id("GiftCard", gift_card.pk)}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_GIFT_CARD_EVENTS,
+ variables,
+ permissions=[
+ permission_manage_gift_card,
+ permission_manage_apps,
+ permission_manage_users,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ events_data = content["data"]["giftCard"]["events"]
+ assert len(events_data) == 1
+ assert events_data[0]["app"] is None
+
+
def test_query_gift_card_expiry_date_set_event(
staff_api_client,
gift_card,
diff --git a/saleor/graphql/order/bulk_mutations/order_bulk_create.py b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
index ec19698c41..baf87cc544 100644
--- a/saleor/graphql/order/bulk_mutations/order_bulk_create.py
+++ b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
@@ -703,7 +703,9 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
pk__in=identifiers.shipping_method_ids.keys
)
tax_classes = TaxClass.objects.filter(pk__in=identifiers.tax_class_ids.keys)
- apps = App.objects.filter(pk__in=identifiers.app_ids.keys)
+ apps = App.objects.filter(
+ pk__in=identifiers.app_ids.keys, removed_at__isnull=True
+ )
gift_cards = GiftCard.objects.filter(code__in=identifiers.gift_card_codes.keys)
orders = Order.objects.filter(
external_reference__in=identifiers.order_external_references.keys
diff --git a/saleor/graphql/order/tests/queries/test_order_events.py b/saleor/graphql/order/tests/queries/test_order_events.py
index 20e5f79a6f..c374d6c7d2 100644
--- a/saleor/graphql/order/tests/queries/test_order_events.py
+++ b/saleor/graphql/order/tests/queries/test_order_events.py
@@ -305,6 +305,9 @@ QUERY_GET_FIRST_EVENT = """
fulfilledItems {
id
}
+ app {
+ name
+ }
}
}
}
@@ -377,3 +380,21 @@ def test_retrieving_event_lines_with_missing_line_pk_in_data(
assert len(data["lines"]) == 1
assert received_line["quantity"] == line.quantity
assert received_line["orderLine"] is None
+
+
+def test_related_order_events_query_with_removed_app(
+ staff_api_client, permission_group_manage_orders, order, payment_dummy, removed_app
+):
+ event = order_events.fulfillment_fulfilled_items_event(
+ order=order,
+ user=None,
+ app=removed_app,
+ fulfillment_lines=[],
+ )
+
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ response = staff_api_client.post_graphql(QUERY_GET_FIRST_EVENT)
+ content = get_graphql_content(response)
+
+ event = content["data"]["orders"]["edges"][0]["node"]["events"][0]
+ assert event["app"] is None
diff --git a/saleor/graphql/order/tests/queries/test_order_granted_refunds.py b/saleor/graphql/order/tests/queries/test_order_granted_refunds.py
index 0e5e01f650..05405a7f63 100644
--- a/saleor/graphql/order/tests/queries/test_order_granted_refunds.py
+++ b/saleor/graphql/order/tests/queries/test_order_granted_refunds.py
@@ -442,3 +442,33 @@ def test_order_total_granted_refund_query_by_app(
total_granted_refund["amount"]
== first_granted_refund_amount + second_granted_refund_amount
)
+
+
+def test_order_granted_refunds_query_with_removed_app(
+ staff_user,
+ removed_app,
+ staff_api_client,
+ permission_group_manage_orders,
+ fulfilled_order,
+ shipping_zone,
+):
+ # given
+ order = fulfilled_order
+ first_granted_refund_amount = Decimal("10.00")
+ order.granted_refunds.create(
+ amount_value=first_granted_refund_amount,
+ currency="USD",
+ reason="Test reason",
+ app=removed_app,
+ )
+
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(ORDERS_QUERY)
+ content = get_graphql_content(response)
+
+ # then
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ granted_refund = order_data["grantedRefunds"][0]
+ assert granted_refund["app"] is None
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_process.py b/saleor/graphql/payment/mutations/transaction/transaction_process.py
index ea25a40515..f31bbc366a 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_process.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_process.py
@@ -148,7 +148,9 @@ class TransactionProcess(BaseMutation):
)
}
)
- app = App.objects.filter(identifier=transaction_item.app_identifier).first()
+ app = App.objects.filter(
+ identifier=transaction_item.app_identifier, removed_at__isnull=True
+ ).first()
if not app:
raise ValidationError(
{
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_process.py b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
index 3a5e0cc1c5..2e6f9f8ee3 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_process.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
@@ -939,6 +939,45 @@ def test_transaction_process_doesnt_accept_old_id(
)
+def test_transaction_process_for_removed_app(
+ user_api_client,
+ checkout_with_prices,
+ removed_app,
+ transaction_item_generator,
+):
+ # given
+ expected_amount = Decimal("10.00")
+ expected_app_identifier = "webhook.app.identifier"
+ removed_app.identifier = expected_app_identifier
+ removed_app.save()
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout_with_prices.pk, app=removed_app
+ )
+ TransactionEvent.objects.create(
+ transaction=transaction_item,
+ amount_value=expected_amount,
+ currency=transaction_item.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction_item.token)
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_PROCESS, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["transactionProcess"]
+ assert (
+ data["errors"][0]["code"]
+ == TransactionProcessErrorCode.MISSING_PAYMENT_APP.name
+ )
+ assert data["errors"][0]["field"] == "id"
+
+
def test_user_missing_permission_for_customer_ip_address(
user_api_client,
checkout_with_prices,
diff --git a/saleor/graphql/webhook/mutations/event_delivery_retry.py b/saleor/graphql/webhook/mutations/event_delivery_retry.py
index b6220145dc..9c81fde7c5 100644
--- a/saleor/graphql/webhook/mutations/event_delivery_retry.py
+++ b/saleor/graphql/webhook/mutations/event_delivery_retry.py
@@ -1,6 +1,10 @@
import graphene
+from django.db.models import Exists, OuterRef
+from ....app.models import App
+from ....core import models
from ....permission.enums import AppPermission
+from ....webhook.models import Webhook
from ...core import ResolveInfo
from ...core.doc_category import DOC_CATEGORY_WEBHOOKS
from ...core.mutations import BaseMutation
@@ -25,10 +29,19 @@ class EventDeliveryRetry(BaseMutation):
@classmethod
def perform_mutation(cls, _root, info: ResolveInfo, **data):
+ apps = App.objects.filter(removed_at__isnull=True).values("pk")
+ webhook = Webhook.objects.filter(
+ Exists(apps.filter(id=OuterRef("app_id")))
+ ).values("pk")
+ deliveries = models.EventDelivery.objects.filter(
+ Exists(webhook.filter(id=OuterRef("webhook_id")))
+ )
+
delivery = cls.get_node_or_error(
info,
data["id"],
only_type=EventDelivery,
+ qs=deliveries,
)
manager = get_plugin_manager_promise(info.context).get()
cls.call_event(manager.event_delivery_retry, delivery)
diff --git a/saleor/graphql/webhook/mutations/webhook_create.py b/saleor/graphql/webhook/mutations/webhook_create.py
index 9133ef62b0..356c32e5bb 100644
--- a/saleor/graphql/webhook/mutations/webhook_create.py
+++ b/saleor/graphql/webhook/mutations/webhook_create.py
@@ -13,6 +13,7 @@ from ....webhook.validators import (
custom_headers_validator,
)
from ...app.dataloaders import get_app_promise
+from ...app.utils import validate_app_is_not_removed
from ...core import ResolveInfo
from ...core.descriptions import (
ADDED_IN_32,
@@ -108,7 +109,8 @@ class WebhookCreate(ModelMutation, NotifyUserEventValidationMixin):
# context has assigned app instance
if not instance.app_id and not app:
raise ValidationError(
- "Missing token or app", code=WebhookErrorCode.INVALID.value
+ "Missing app id. Fill in the app field or run the mutation by the app",
+ code=WebhookErrorCode.INVALID.value,
)
if instance.app_id:
@@ -117,6 +119,7 @@ class WebhookCreate(ModelMutation, NotifyUserEventValidationMixin):
app = instance.app
cleaned_data.pop("app", None)
+ validate_app_is_not_removed(app, data.get("input", {}).get("app"), "app")
if not app or not app.is_active:
raise ValidationError(
"App doesn't exist or is disabled",
diff --git a/saleor/graphql/webhook/mutations/webhook_delete.py b/saleor/graphql/webhook/mutations/webhook_delete.py
index ba3a9f6ef9..62493fad84 100644
--- a/saleor/graphql/webhook/mutations/webhook_delete.py
+++ b/saleor/graphql/webhook/mutations/webhook_delete.py
@@ -1,7 +1,9 @@
import graphene
from django.core.exceptions import ValidationError
from django.db import IntegrityError
+from django.db.models import Exists, OuterRef
+from ....app.models import App
from ....permission.auth_filters import AuthorizationFilters
from ....permission.enums import AppPermission
from ....webhook import models
@@ -42,7 +44,15 @@ class WebhookDelete(ModelDeleteMutation):
"App needs to be active to delete webhook",
code=WebhookErrorCode.INVALID.value,
)
- webhook = cls.get_node_or_error(info, node_id, only_type=Webhook)
+ apps = App.objects.filter(removed_at__isnull=True)
+ webhook = cls.get_node_or_error(
+ info,
+ node_id,
+ only_type=Webhook,
+ qs=models.Webhook.objects.filter(
+ Exists(apps.filter(id=OuterRef("app_id")))
+ ),
+ )
if app and webhook.app_id != app.id:
raise ValidationError(
f"Couldn't resolve to a node: {node_id}",
diff --git a/saleor/graphql/webhook/mutations/webhook_dry_run.py b/saleor/graphql/webhook/mutations/webhook_dry_run.py
index 2bb4257b5d..18808ea962 100644
--- a/saleor/graphql/webhook/mutations/webhook_dry_run.py
+++ b/saleor/graphql/webhook/mutations/webhook_dry_run.py
@@ -1,6 +1,7 @@
import graphene
from graphene.utils.str_converters import to_camel_case
+from ....app.models import App
from ....discount import models as discount_models
from ....permission.auth_filters import AuthorizationFilters
from ....webhook.error_codes import WebhookDryRunErrorCode
@@ -103,7 +104,6 @@ class WebhookDryRun(BaseMutation):
event_type = cls.validate_query(query)
cls.validate_event_type(event_type, object_id)
cls.validate_permissions(info, event_type)
-
object = cls.get_instance(info, object_id)
return event_type, object, query
@@ -114,7 +114,11 @@ class WebhookDryRun(BaseMutation):
if type == "Sale":
object_id = cls.get_global_id_or_error(object_id, "Sale")
return discount_models.Promotion.objects.get(old_sale_id=object_id)
- return cls.get_node_or_error(info, object_id, field="objectId")
+ elif type == "App":
+ qs = App.objects.filter(removed_at__isnull=True)
+ return cls.get_node_or_error(info, object_id, field="objectId", qs=qs)
+ else:
+ return cls.get_node_or_error(info, object_id, field="objectId")
@classmethod
def perform_mutation(cls, _root, info, **data):
diff --git a/saleor/graphql/webhook/mutations/webhook_trigger.py b/saleor/graphql/webhook/mutations/webhook_trigger.py
index 069aadd9e7..e993a3e6ee 100644
--- a/saleor/graphql/webhook/mutations/webhook_trigger.py
+++ b/saleor/graphql/webhook/mutations/webhook_trigger.py
@@ -1,12 +1,15 @@
import graphene
from celery.exceptions import Retry
+from django.db.models import Exists, OuterRef
from graphene.utils.str_converters import to_camel_case
+from ....app.models import App
from ....core import EventDeliveryStatus
from ....discount import models as discount_models
from ....permission.auth_filters import AuthorizationFilters
from ....webhook.error_codes import WebhookTriggerErrorCode
from ....webhook.event_types import WebhookEventAsyncType
+from ....webhook.models import Webhook
from ...core import ResolveInfo
from ...core.descriptions import ADDED_IN_311, PREVIEW_FEATURE
from ...core.doc_category import DOC_CATEGORY_WEBHOOKS
@@ -102,7 +105,12 @@ class WebhookTrigger(BaseMutation):
def validate_input(cls, info, **data):
object_id = data.get("object_id")
webhook_id = data.get("webhook_id")
- webhook = cls.get_node_or_error(info, webhook_id, field="webhookId")
+
+ apps = App.objects.filter(removed_at__isnull=True)
+ webhooks = Webhook.objects.filter(Exists(apps.filter(id=OuterRef("app_id"))))
+ webhook = cls.get_node_or_error(
+ info, webhook_id, field="webhookId", qs=webhooks
+ )
event_type = cls.validate_subscription_query(webhook)
cls.validate_event_type(event_type, object_id)
diff --git a/saleor/graphql/webhook/mutations/webhook_update.py b/saleor/graphql/webhook/mutations/webhook_update.py
index 5db42a0a15..0873db85de 100644
--- a/saleor/graphql/webhook/mutations/webhook_update.py
+++ b/saleor/graphql/webhook/mutations/webhook_update.py
@@ -1,5 +1,7 @@
import graphene
+from django.db.models import Exists, OuterRef
+from ....app.models import App
from ....permission.auth_filters import AuthorizationFilters
from ....permission.enums import AppPermission
from ....webhook import models
@@ -110,6 +112,10 @@ 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():
- data["qs"] = app.webhooks
+ apps = apps.filter(id=app.id)
+ data["qs"] = models.Webhook.objects.filter(
+ Exists(apps.filter(id=OuterRef("app_id")))
+ )
return super(WebhookCreate, cls).get_instance(info, **data)
diff --git a/saleor/graphql/webhook/resolvers.py b/saleor/graphql/webhook/resolvers.py
index 113fbb669a..ff5ede36eb 100644
--- a/saleor/graphql/webhook/resolvers.py
+++ b/saleor/graphql/webhook/resolvers.py
@@ -1,3 +1,6 @@
+from django.db.models import Exists, OuterRef, Q
+
+from ...app.models import App
from ...checkout.fetch import (
fetch_checkout_info,
fetch_checkout_lines,
@@ -21,11 +24,14 @@ def resolve_webhook(info: ResolveInfo, id, app):
return app.webhooks.filter(id=id).first()
user = info.context.user
if user and user.has_perm(AppPermission.MANAGE_APPS):
- return (
- models.Webhook.objects.using(get_database_connection_name(info.context))
- .filter(pk=id)
- .first()
+ apps = (
+ App.objects.using(get_database_connection_name(info.context))
+ .filter(removed_at__isnull=True)
+ .values("pk")
)
+ return models.Webhook.objects.filter(
+ Q(pk=id), Exists(apps.filter(id=OuterRef("app_id")))
+ ).first()
raise PermissionDenied(permissions=[AppPermission.MANAGE_APPS])
diff --git a/saleor/graphql/webhook/tests/mutations/test_delivery_retry.py b/saleor/graphql/webhook/tests/mutations/test_delivery_retry.py
index 00b3583b0e..86180e7ea2 100644
--- a/saleor/graphql/webhook/tests/mutations/test_delivery_retry.py
+++ b/saleor/graphql/webhook/tests/mutations/test_delivery_retry.py
@@ -3,12 +3,14 @@ from unittest.mock import patch
import graphene
from .....graphql.tests.utils import assert_no_permission, get_graphql_content
+from .....webhook.error_codes import WebhookErrorCode
WEBHOOK_DELIVERY_RETRY_MUTATION = """
mutation eventDeliveryRetry($id: ID!){
eventDeliveryRetry(id: $id){
errors{
field
+ code
message
}
delivery{
@@ -102,3 +104,26 @@ def test_delivery_retry_mutation_wrong_id(
assert len(errors) == 1
assert errors[0]["field"] == "id"
assert errors[0]["message"] == expected_message
+
+
+def test_delivery_retry_mutation_for_removed_app(
+ app_api_client, permission_manage_apps, event_delivery_removed_app
+):
+ # given
+ query = WEBHOOK_DELIVERY_RETRY_MUTATION
+ delivery_id = graphene.Node.to_global_id(
+ "EventDelivery", event_delivery_removed_app.pk
+ )
+ variables = {"id": delivery_id}
+
+ # when
+ response = app_api_client.post_graphql(
+ query, variables=variables, permissions=[permission_manage_apps]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ app_data = content["data"]["eventDeliveryRetry"]
+ assert app_data["delivery"] is None
+ assert app_data["errors"][0]["code"] == WebhookErrorCode.NOT_FOUND.name
+ assert app_data["errors"][0]["field"] == "id"
diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_create.py b/saleor/graphql/webhook/tests/mutations/test_webhook_create.py
index 47b8668062..9f034a2aa7 100644
--- a/saleor/graphql/webhook/tests/mutations/test_webhook_create.py
+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_create.py
@@ -2,6 +2,7 @@ import json
import graphene
+from .....app.error_codes import AppErrorCode
from .....webhook.error_codes import WebhookErrorCode
from .....webhook.models import Webhook
from ....tests.utils import assert_no_permission, get_graphql_content
@@ -231,6 +232,35 @@ def test_webhook_create_by_app_invalid_query(app_api_client, permission_manage_o
assert error["code"] == WebhookErrorCode.SYNTAX.name
+def test_webhook_create_by_staff_for_removed_app(
+ staff_api_client,
+ removed_app,
+ permission_manage_apps,
+):
+ # given
+ query = WEBHOOK_CREATE
+ app_id = graphene.Node.to_global_id("App", removed_app.pk)
+ variables = {
+ "input": {
+ "targetUrl": "https://www.example.com",
+ "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_CREATED.name],
+ "syncEvents": [WebhookEventTypeSyncEnum.PAYMENT_LIST_GATEWAYS.name],
+ "app": app_id,
+ }
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_apps)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables=variables)
+
+ # then
+ content = get_graphql_content(response)
+ app_data = content["data"]["webhookCreate"]
+ assert app_data["webhook"] is None
+ assert app_data["errors"][0]["code"] == AppErrorCode.NOT_FOUND.name
+ assert app_data["errors"][0]["field"] == "app"
+
+
SUBSCRIPTION_QUERY_WITH_MULTIPLE_EVENTS = """
subscription {
event {
diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_delete.py b/saleor/graphql/webhook/tests/mutations/test_webhook_delete.py
index 561922d4a9..608d3114d6 100644
--- a/saleor/graphql/webhook/tests/mutations/test_webhook_delete.py
+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_delete.py
@@ -4,6 +4,7 @@ import graphene
from django.db import IntegrityError
from .....app.models import App
+from .....webhook.error_codes import WebhookErrorCode
from .....webhook.models import Webhook
from ....tests.utils import assert_no_permission, get_graphql_content
@@ -15,6 +16,9 @@ WEBHOOK_DELETE_BY_APP = """
message
code
}
+ webhook {
+ id
+ }
}
}
"""
@@ -29,6 +33,24 @@ def test_webhook_delete_by_app(app_api_client, webhook):
assert Webhook.objects.count() == 0
+def test_webhook_delete_by_staff(staff_api_client, webhook, permission_manage_apps):
+ # given
+ query = WEBHOOK_DELETE_BY_APP
+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)
+ variables = {"id": webhook_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables=variables,
+ permissions=[permission_manage_apps],
+ )
+
+ # then
+ get_graphql_content(response)
+ assert Webhook.objects.count() == 0
+
+
def test_webhook_delete_by_app_and_webhook_assigned_to_other_app(
app_api_client, webhook
):
@@ -120,3 +142,26 @@ def test_webhook_delete_when_app_doesnt_exist(app_api_client, app):
variables = {"id": webhook_id}
response = app_api_client.post_graphql(query, variables=variables)
assert_no_permission(response)
+
+
+def test_webhook_delete_by_staff_for_removed_app(
+ staff_api_client, webhook_removed_app, permission_manage_apps
+):
+ # given
+ query = WEBHOOK_DELETE_BY_APP
+ webhook_id = graphene.Node.to_global_id("Webhook", webhook_removed_app.pk)
+ variables = {"id": webhook_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables=variables,
+ permissions=[permission_manage_apps],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ app_data = content["data"]["webhookDelete"]
+ assert app_data["webhook"] is None
+ assert app_data["errors"][0]["code"] == WebhookErrorCode.NOT_FOUND.name
+ assert app_data["errors"][0]["field"] == "id"
diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py
index 03b7af1edf..43a304f6d3 100644
--- a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py
+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py
@@ -279,3 +279,107 @@ def test_webhook_dry_run_root_type_for_transaction_item_metadata_updated(
assert not content["data"]["webhookDryRun"]["errors"]
payload = content["data"]["webhookDryRun"]["payload"]
assert json.loads(payload)["transaction"]["id"] == object_id
+
+
+def test_webhook_dry_run_app_installed_for_removed_app(
+ staff_api_client,
+ permission_manage_apps,
+ order,
+ subscription_app_installed_webhook_removed_app,
+ removed_app,
+):
+ # given
+ query = WEBHOOK_DRY_RUN_MUTATION
+ staff_api_client.user.user_permissions.add(permission_manage_apps)
+ app_id = graphene.Node.to_global_id("App", removed_app.id)
+ webhook = subscription_app_installed_webhook_removed_app
+
+ variables = {"objectId": app_id, "query": webhook.subscription_query}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ app_data = content["data"]["webhookDryRun"]
+ assert app_data["payload"] is None
+ assert app_data["errors"][0]["code"] == WebhookDryRunErrorCode.NOT_FOUND.name
+ assert app_data["errors"][0]["field"] == "objectId"
+
+
+def test_webhook_dry_run_app_updated_for_removed_app(
+ staff_api_client,
+ permission_manage_apps,
+ order,
+ subscription_app_updated_webhook_removed_app,
+ removed_app,
+):
+ # given
+ query = WEBHOOK_DRY_RUN_MUTATION
+ staff_api_client.user.user_permissions.add(permission_manage_apps)
+ app_id = graphene.Node.to_global_id("App", removed_app.id)
+ webhook = subscription_app_updated_webhook_removed_app
+
+ variables = {"objectId": app_id, "query": webhook.subscription_query}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ app_data = content["data"]["webhookDryRun"]
+ assert app_data["payload"] is None
+ assert app_data["errors"][0]["code"] == WebhookDryRunErrorCode.NOT_FOUND.name
+ assert app_data["errors"][0]["field"] == "objectId"
+
+
+def test_webhook_dry_run_app_deleted_for_removed_app(
+ staff_api_client,
+ permission_manage_apps,
+ order,
+ subscription_app_deleted_webhook_removed_app,
+ removed_app,
+):
+ # given
+ query = WEBHOOK_DRY_RUN_MUTATION
+ staff_api_client.user.user_permissions.add(permission_manage_apps)
+ app_id = graphene.Node.to_global_id("App", removed_app.id)
+ webhook = subscription_app_deleted_webhook_removed_app
+
+ variables = {"objectId": app_id, "query": webhook.subscription_query}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ app_data = content["data"]["webhookDryRun"]
+ assert app_data["payload"] is None
+ assert app_data["errors"][0]["code"] == WebhookDryRunErrorCode.NOT_FOUND.name
+ assert app_data["errors"][0]["field"] == "objectId"
+
+
+def test_webhook_dry_run_app_status_changed_for_removed_app(
+ staff_api_client,
+ permission_manage_apps,
+ order,
+ subscription_app_status_changed_webhook_removed_app,
+ removed_app,
+):
+ # given
+ query = WEBHOOK_DRY_RUN_MUTATION
+ staff_api_client.user.user_permissions.add(permission_manage_apps)
+ app_id = graphene.Node.to_global_id("App", removed_app.id)
+ webhook = subscription_app_status_changed_webhook_removed_app
+
+ variables = {"objectId": app_id, "query": webhook.subscription_query}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ app_data = content["data"]["webhookDryRun"]
+ assert app_data["payload"] is None
+ assert app_data["errors"][0]["code"] == WebhookDryRunErrorCode.NOT_FOUND.name
+ assert app_data["errors"][0]["field"] == "objectId"
diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.py b/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.py
index 6c02fc20f1..bd4cf48171 100644
--- a/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.py
+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.py
@@ -164,17 +164,12 @@ def test_webhook_trigger_fail(
assert payload["order"]["id"] == order_id
- "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async"
-)
def test_webhook_trigger_missing_user_permission(
- mocked_send_webhook_request,
staff_api_client,
order,
subscription_order_created_webhook,
):
# given
- mocked_send_webhook_request.return_value = None
query = WEBHOOK_TRIGGER_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
webhook = subscription_order_created_webhook
@@ -195,18 +190,13 @@ def test_webhook_trigger_missing_user_permission(
)
- "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async"
-)
def test_webhook_trigger_staff_user_not_authorized(
- mocked_send_webhook_request,
user_api_client,
order,
subscription_order_created_webhook,
permission_manage_orders,
):
# given
- mocked_send_webhook_request.return_value = None
user_api_client.user.user_permissions.add(permission_manage_orders)
query = WEBHOOK_TRIGGER_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
@@ -222,18 +212,13 @@ def test_webhook_trigger_staff_user_not_authorized(
assert_no_permission(response)
- "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async"
-)
def test_webhook_trigger_missing_subscription_query(
- mocked_send_webhook_request,
staff_api_client,
permission_manage_orders,
order,
subscription_order_created_webhook,
):
# given
- mocked_send_webhook_request.return_value = None
query = WEBHOOK_TRIGGER_MUTATION
staff_api_client.user.user_permissions.add(permission_manage_orders)
order_id = graphene.Node.to_global_id("Order", order.id)
@@ -256,18 +241,13 @@ def test_webhook_trigger_missing_subscription_query(
assert error["message"] == "Missing subscription query for given webhook."
- "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async"
-)
def test_webhook_trigger_invalid_subscription_query(
- mocked_send_webhook_request,
staff_api_client,
permission_manage_orders,
order,
subscription_order_created_webhook,
):
# given
- mocked_send_webhook_request.return_value = None
query = WEBHOOK_TRIGGER_MUTATION
staff_api_client.user.user_permissions.add(permission_manage_orders)
order_id = graphene.Node.to_global_id("Order", order.id)
@@ -292,18 +272,13 @@ def test_webhook_trigger_invalid_subscription_query(
assert 'Unknown type "UndefinedEvent"' in error["message"]
- "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async"
-)
def test_webhook_trigger_event_not_supported(
- mocked_send_webhook_request,
staff_api_client,
permission_manage_orders,
order,
subscription_payment_authorize_webhook,
):
# given
- mocked_send_webhook_request.return_value = None
query = WEBHOOK_TRIGGER_MUTATION
staff_api_client.user.user_permissions.add(permission_manage_orders)
order_id = graphene.Node.to_global_id("Order", order.id)
@@ -327,18 +302,13 @@ def test_webhook_trigger_event_not_supported(
)
- "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async"
-)
def test_webhook_trigger_object_id_does_not_match_event(
- mocked_send_webhook_request,
staff_api_client,
permission_manage_orders,
product,
subscription_order_created_webhook,
):
# given
- mocked_send_webhook_request.return_value = None
query = WEBHOOK_TRIGGER_MUTATION
staff_api_client.user.user_permissions.add(permission_manage_orders)
product_id = graphene.Node.to_global_id("Product", product.id)
@@ -356,3 +326,27 @@ def test_webhook_trigger_object_id_does_not_match_event(
assert error["field"] == "objectId"
assert error["code"] == WebhookTriggerErrorCode.INVALID_ID.name
assert error["message"] == "ObjectId doesn't match event type."
+
+
+def test_webhook_trigger_for_removed_app(
+ staff_api_client,
+ order,
+ subscription_app_updated_webhook_removed_app,
+):
+ # given
+ query = WEBHOOK_TRIGGER_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ webhook = subscription_app_updated_webhook_removed_app
+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.id)
+
+ variables = {"webhookId": webhook_id, "objectId": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ app_data = content["data"]["webhookTrigger"]
+ assert app_data["delivery"] is None
+ assert app_data["errors"][0]["code"] == WebhookTriggerErrorCode.NOT_FOUND.name
+ assert app_data["errors"][0]["field"] == "webhookId"
diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_update.py b/saleor/graphql/webhook/tests/mutations/test_webhook_update.py
index 8ac6c35b09..8e6efe7b9f 100644
--- a/saleor/graphql/webhook/tests/mutations/test_webhook_update.py
+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_update.py
@@ -187,6 +187,37 @@ def test_webhook_update_by_staff(staff_api_client, webhook, permission_manage_ap
assert data["webhook"]["customHeaders"] == json.dumps(custom_headers)
+def test_webhook_update_by_staff_for_removed_app(
+ staff_api_client, webhook_removed_app, permission_manage_apps
+):
+ # given
+ query = WEBHOOK_UPDATE
+ webhook_id = graphene.Node.to_global_id("Webhook", webhook_removed_app.pk)
+ custom_headers = {"x-key": "Value", "authorization-key": "Value"}
+ variables = {
+ "id": webhook_id,
+ "input": {
+ "asyncEvents": [
+ WebhookEventTypeAsyncEnum.CUSTOMER_CREATED.name,
+ WebhookEventTypeAsyncEnum.CUSTOMER_CREATED.name,
+ ],
+ "isActive": False,
+ "customHeaders": json.dumps(custom_headers),
+ },
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_apps)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables=variables)
+
+ # then
+ content = get_graphql_content(response)
+ app_data = content["data"]["webhookUpdate"]
+ assert app_data["webhook"] is None
+ assert app_data["errors"][0]["code"] == WebhookErrorCode.NOT_FOUND.name
+ assert app_data["errors"][0]["field"] == "id"
+
+
def test_webhook_update_by_staff_without_permission(staff_api_client, app, webhook):
# given
query = WEBHOOK_UPDATE
diff --git a/saleor/graphql/webhook/tests/queries/test_webhook.py b/saleor/graphql/webhook/tests/queries/test_webhook.py
index 52a5a7d839..0b0538cb9d 100644
--- a/saleor/graphql/webhook/tests/queries/test_webhook.py
+++ b/saleor/graphql/webhook/tests/queries/test_webhook.py
@@ -73,6 +73,24 @@ def test_query_webhook_by_staff_without_permission(staff_api_client, webhook):
assert_no_permission(response)
+def test_query_webhook_removed_app(
+ staff_api_client, webhook_removed_app, permission_manage_apps
+):
+ # given
+ query = QUERY_WEBHOOK
+ webhook_id = graphene.Node.to_global_id("Webhook", webhook_removed_app.pk)
+ variables = {"id": webhook_id}
+ staff_api_client.user.user_permissions.add(permission_manage_apps)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables=variables)
+
+ # then
+ content = get_graphql_content(response)
+ webhook_response = content["data"]["webhook"]
+ assert webhook_response is None
+
+
def test_query_webhook_by_app(app_api_client, webhook):
query = QUERY_WEBHOOK
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index dec610e66c..7ddcb84475 100644
--- a/saleor/payment/gateway.py
+++ b/saleor/payment/gateway.py
@@ -201,7 +201,9 @@ def _create_transaction_data(
if transaction.app_id:
app_owner = transaction.app
elif transaction.app_identifier:
- app_owner = App.objects.filter(identifier=transaction.app_identifier).first()
+ app_owner = App.objects.filter(
+ identifier=transaction.app_identifier, removed_at__isnull=True
+ ).first()
return TransactionActionData(
transaction=transaction,
@@ -224,14 +226,12 @@ def _request_payment_action(
transaction_request_event_active = manager.is_event_active_for_any_plugin(
plugin_func_name, channel_slug=channel_slug
)
-
webhooks = None
if transaction_action_data.transaction_app_owner:
webhooks = get_webhooks_for_event(
event_type=event_type,
apps_ids=[transaction_action_data.transaction_app_owner.pk],
)
-
if not transaction_request_event_active and not webhooks:
create_failed_transaction_event(
transaction_action_data.event,
diff --git a/saleor/payment/tests/test_gateway.py b/saleor/payment/tests/test_gateway.py
index b85db87318..0d66293c8c 100644
--- a/saleor/payment/tests/test_gateway.py
+++ b/saleor/payment/tests/test_gateway.py
@@ -496,6 +496,54 @@ def test_request_charge_action_by_app(
assert event.app == app
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_charge_requested")
+def test_request_charge_action_by_removed_app(
+ mocked_transaction_request, mocked_is_active, order, removed_app
+):
+ transaction = TransactionItem.objects.create(
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["capture", "void"],
+ currency="USD",
+ order_id=order.pk,
+ authorized_value=Decimal("10"),
+ app=removed_app,
+ )
+ action_value = Decimal("5.00")
+ requested_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+ mocked_is_active.side_effect = [True, True]
+
+ # when
+ request_charge_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ charge_value=action_value,
+ channel_slug=order.channel.slug,
+ user=None,
+ app=removed_app,
+ request_event=requested_event,
+ )
+
+ # then
+ assert mocked_is_active.called
+ mocked_transaction_request.assert_called_once_with(
+ TransactionActionData(
+ action_type=TransactionAction.CHARGE,
+ transaction=transaction,
+ event=requested_event,
+ transaction_app_owner=removed_app,
+ action_value=action_value,
+ granted_refund=None,
+ ),
+ order.channel.slug,
+ )
+
+
@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
@patch("saleor.plugins.manager.PluginsManager.transaction_charge_requested")
def test_request_charge_action_on_checkout(
@@ -545,10 +593,10 @@ def test_request_charge_action_on_checkout(
assert mocked_is_active.called
mocked_transaction_request.assert_called_once_with(
TransactionActionData(
- transaction=transaction,
action_type=TransactionAction.CHARGE,
- action_value=action_value,
+ transaction=transaction,
event=requested_event,
+ action_value=action_value,
transaction_app_owner=app,
),
checkout.channel.slug,
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index bc65bd3979..6ed347eabd 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -2537,13 +2537,16 @@ class WebhookPlugin(BasePlugin):
apps = (
App.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
.for_event_type(event_type)
- .filter(identifier=payment_app_data.app_identifier)
+ .filter(
+ identifier=payment_app_data.app_identifier,
+ removed_at__isnull=True,
+ )
)
else:
apps = (
App.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
.for_event_type(event_type)
- .filter(pk=payment_app_data.app_pk)
+ .filter(pk=payment_app_data.app_pk, removed_at__isnull=True)
)
if not apps:
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
index 28bbc65f27..a316737ed1 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
@@ -7,10 +7,10 @@ from . import subscription_queries as queries
@pytest.fixture
def subscription_webhook(webhook_app):
- def fun(query, event_type, name="Subscription"):
+ def fun(query, event_type, name="Subscription", app=webhook_app):
webhook = Webhook.objects.create(
name=name,
- app=webhook_app,
+ app=app,
target_url="http://www.example.com/any",
subscription_query=query,
)
@@ -1169,3 +1169,35 @@ def subscription_calculate_taxes_for_order(
queries.ORDER_CALCULATE_TAXES,
WebhookEventSyncType.ORDER_CALCULATE_TAXES,
)
+
+
+def subscription_app_installed_webhook_removed_app(subscription_webhook, removed_app):
+ return subscription_webhook(
+ queries.APP_INSTALLED, WebhookEventAsyncType.APP_INSTALLED, app=removed_app
+ )
+
+
+def subscription_app_updated_webhook_removed_app(subscription_webhook, removed_app):
+ return subscription_webhook(
+ queries.APP_UPDATED, WebhookEventAsyncType.APP_UPDATED, app=removed_app
+ )
+
+
+def subscription_app_deleted_webhook_removed_app(subscription_webhook, removed_app):
+ return subscription_webhook(
+ queries.APP_DELETED, WebhookEventAsyncType.APP_DELETED, app=removed_app
+ )
+
+
+def subscription_app_status_changed_webhook_removed_app(
+ subscription_webhook, removed_app
+):
+ return subscription_webhook(
+ queries.APP_STATUS_CHANGED,
+ WebhookEventAsyncType.APP_STATUS_CHANGED,
+ app=removed_app,
+ )
diff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.py
index cba66b288e..e688db45da 100644
--- a/saleor/plugins/webhook/tests/test_payment_webhook.py
+++ b/saleor/plugins/webhook/tests/test_payment_webhook.py
@@ -6,6 +6,7 @@ from unittest import mock
import pytest
from django.conf import settings
from django.contrib.sites.models import Site
+from django.utils import timezone
from requests import RequestException, TooManyRedirects
from requests_hardened import HTTPSession
@@ -23,6 +24,7 @@ from ....webhook.transport.synchronous.transport import (
trigger_webhook_sync,
)
from ....webhook.transport.utils import (
+ from_payment_app_id,
parse_list_payment_gateways_response,
parse_payment_action_response,
to_payment_app_id,
@@ -40,6 +42,18 @@ def payment_invalid_app(payment_dummy):
return payment_dummy
+def payment_removed_app(payment_dummy):
+ app = App.objects.create(
+ name="Dummy app", is_active=True, removed_at=timezone.now()
+ )
+ gateway_id = "credit-card"
+ gateway = to_payment_app_id(app, gateway_id)
+ payment_dummy.gateway = gateway
+ payment_dummy.save()
+ return payment_dummy
+
+
WebhookTestData = namedtuple("WebhookTestData", "secret, event_type, data, message")
@@ -492,6 +506,42 @@ def test_run_payment_webhook_invalid_app(payment_invalid_app, webhook_plugin):
)
+def test_run_payment_webhook_removed_app_by_id(payment_removed_app, webhook_plugin):
+ # given
+ plugin = webhook_plugin()
+ payment_information = create_payment_information(payment_removed_app, "token")
+
+ # when
+ with pytest.raises(PaymentError):
+ plugin._WebhookPlugin__run_payment_webhook(
+ WebhookEventSyncType.PAYMENT_AUTHORIZE,
+ TransactionKind.AUTH,
+ payment_information,
+ None,
+ )
+
+
+def test_run_payment_webhook_removed_app_by_app_identifier(
+ payment, payment_app, webhook_plugin
+):
+ # given
+ payment_app.removed_at = timezone.now()
+ payment_app.save(update_fields=["removed_at"])
+ plugin = webhook_plugin()
+ payment_information = create_payment_information(payment, "token")
+ payment_data = from_payment_app_id(payment_information.gateway)
+ assert payment_data.app_identifier == payment_app.identifier
+
+ # when
+ with pytest.raises(PaymentError):
+ plugin._WebhookPlugin__run_payment_webhook(
+ WebhookEventSyncType.PAYMENT_AUTHORIZE,
+ TransactionKind.AUTH,
+ payment_information,
+ None,
+ )
+
+
def test_run_payment_webhook_no_payment_app_data(payment, webhook_plugin):
plugin = webhook_plugin()
payment_information = create_payment_information(payment, "token")
diff --git a/saleor/plugins/webhook/tests/test_sync_webhooks_for_removed_app.py b/saleor/plugins/webhook/tests/test_sync_webhooks_for_removed_app.py
new file mode 100644
index 0000000000..2fd269ef8a
--- /dev/null
+++ b/saleor/plugins/webhook/tests/test_sync_webhooks_for_removed_app.py
@@ -0,0 +1,29 @@
+from unittest import mock
+
+from django.utils import timezone
+
+from ....core.models import EventDelivery, EventPayload
+from ....webhook.event_types import WebhookEventSyncType
+from ....webhook.transport.synchronous.transport import trigger_all_webhooks_sync
+from ....webhook.transport.utils import parse_tax_data
+
+
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_not_trigger_sync_webhook_for_removed_app(
+ mock_request,
+ tax_checkout_webhook,
+):
+ # given
+ app = tax_checkout_webhook.app
+ app.removed_at = timezone.now()
+ app.save(update_fields=["removed_at"])
+ event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ data = '{"key": "value"}'
+
+ # when
+ trigger_all_webhooks_sync(event_type, lambda: data, parse_tax_data)
+
+ # then
+ assert EventPayload.objects.count() == 0
+ assert EventDelivery.objects.count() == 0
+ mock_request.assert_not_called()
diff --git a/saleor/settings.py b/saleor/settings.py
index c67362612e..ad40d07efe 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -619,6 +619,10 @@ CELERY_BEAT_SCHEDULE = {
"task": "saleor.order.tasks.expire_orders_task",
"schedule": BEAT_EXPIRE_ORDERS_AFTER_TIMEDELTA,
},
+ "remove-apps-marked-as-removed": {
+ "task": "saleor.app.tasks.remove_apps_task",
+ "schedule": crontab(hour=3, minute=0),
+ },
}
# The maximum wait time between each is_due() call on schedulers
@@ -629,6 +633,12 @@ CELERY_BEAT_MAX_LOOP_INTERVAL = 300 # 5 minutes
EVENT_PAYLOAD_DELETE_PERIOD = timedelta(
seconds=parse(os.environ.get("EVENT_PAYLOAD_DELETE_PERIOD", "14 days"))
)
+# Time between marking app "to remove" and removing the app from the database.
+# App is not visible for the user after removing, but it still exists in the database.
+# Saleor needs time to process sending `APP_DELETED` webhook and possible retrying,
+# so we need to wait for some time before removing the App from the database.
+DELETE_APP_TTL = timedelta(seconds=parse(os.environ.get("DELETE_APP_TTL", "1 day")))
+
# Observability settings
OBSERVABILITY_BROKER_URL = os.environ.get("OBSERVABILITY_BROKER_URL")
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index db4dd7a6b2..3f59625645 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -6863,6 +6863,16 @@ def app_with_token(db):
return app
+def removed_app(db):
+ app = App.objects.create(
+ name="Deleted app ",
+ is_active=True,
+ removed_at=(timezone.now() - datetime.timedelta(days=1, hours=1)),
+ )
+ return app
+
+
@pytest.fixture
def app_with_extensions(app_with_token, permission_manage_products):
first_app_extension = AppExtension(
@@ -6886,6 +6896,29 @@ def app_with_extensions(app_with_token, permission_manage_products):
return app_with_token, extensions
+def removed_app_with_extensions(removed_app, permission_manage_products):
+ first_app_extension = AppExtension(
+ app=removed_app,
+ label="Create product with App",
+ url="www.example.com/app-product",
+ mount=AppExtensionMount.PRODUCT_OVERVIEW_MORE_ACTIONS,
+ )
+ extensions = AppExtension.objects.bulk_create(
+ [
+ first_app_extension,
+ AppExtension(
+ app=removed_app,
+ label="Update product with App",
+ url="www.example.com/app-product-update",
+ mount=AppExtensionMount.PRODUCT_DETAILS_MORE_ACTIONS,
+ ),
+ ]
+ )
+ first_app_extension.permissions.add(permission_manage_products)
+ return removed_app, extensions
+
+
@pytest.fixture
def payment_app(db, permission_manage_payments):
app = App.objects.create(
@@ -7141,6 +7174,17 @@ def webhook_without_name(app):
return webhook
+def webhook_removed_app(removed_app):
+ webhook = Webhook.objects.create(
+ name="Removed app webhook",
+ app=removed_app,
+ target_url="http://www.example.com/test",
+ )
+ webhook.events.create(event_type=WebhookEventAsyncType.ORDER_CREATED)
+ return webhook
+
+
@pytest.fixture
def any_webhook(app):
webhook = Webhook.objects.create(
@@ -7646,6 +7690,12 @@ def app_export_file(app):
return job
+def removed_app_export_file(removed_app):
+ job = ExportFile.objects.create(app=removed_app)
+ return job
+
+
@pytest.fixture
def export_file_list(staff_user):
export_file_list = list(
@@ -7717,6 +7767,16 @@ def app_export_event(app_export_file):
)
+def removed_app_export_event(removed_app_export_file):
+ return ExportEvent.objects.create(
+ type=ExportEvents.EXPORT_FAILED,
+ export_file=removed_app_export_file,
+ app=removed_app_export_file.app,
+ parameters={"message": "Example error message"},
+ )
+
+
@pytest.fixture
def app_manifest():
return {
@@ -7791,6 +7851,15 @@ def event_delivery(event_payload, webhook, app):
)
+def event_delivery_removed_app(event_payload, webhook_removed_app):
+ return EventDelivery.objects.create(
+ event_type=WebhookEventAsyncType.ANY,
+ payload=event_payload,
+ webhook=webhook_removed_app,
+ )
+
+
@pytest.fixture
def event_attempt(event_delivery):
"""Return an event delivery attempt object."""
@@ -7826,6 +7895,19 @@ def webhook_list_stored_payment_methods_response():
}
+def event_attempt_removed_app(event_delivery_removed_app):
+ """Return event delivery attempt object""" # noqa: D400, D415
+ return EventDeliveryAttempt.objects.create(
+ delivery=event_delivery_removed_app,
+ task_id="example_task_id",
+ duration=None,
+ response="example_response",
+ response_headers=None,
+ request_headers=None,
+ )
+
+
@pytest.fixture
def webhook_response():
return WebhookResponse(
diff --git a/saleor/webhook/transport/utils.py b/saleor/webhook/transport/utils.py
index a223a85d19..d67a57a568 100644
--- a/saleor/webhook/transport/utils.py
+++ b/saleor/webhook/transport/utils.py
@@ -595,6 +595,7 @@ def get_current_tax_app() -> Optional[App]:
"""Return currently used tax app or None, if there aren't any."""
return (
App.objects.order_by("pk")
+ .filter(removed_at__isnull=True)
.for_event_type(WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES)
.for_event_type(WebhookEventSyncType.ORDER_CALCULATE_TAXES)
.last()
diff --git a/saleor/webhook/utils.py b/saleor/webhook/utils.py
index 409cca913b..6ceae01e2f 100644
--- a/saleor/webhook/utils.py
+++ b/saleor/webhook/utils.py
@@ -37,6 +37,8 @@ def get_webhooks_for_event(
webhooks = Webhook.objects.all()
app_kwargs: dict = {"is_active": True, **permissions}
+ if event_type != WebhookEventAsyncType.APP_DELETED:
+ app_kwargs["removed_at__isnull"] = True
if apps_ids:
app_kwargs["id__in"] = apps_ids
if apps_identifier:
@@ -55,7 +57,8 @@ def get_webhooks_for_event(
return (
webhooks.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
.filter(
- Q(is_active=True, app__in=apps)
+ Q(is_active=True)
+ & Q(Exists(apps.filter(id=OuterRef("app_id"))))
& Q(Exists(webhook_events.filter(webhook_id=OuterRef("id"))))
)
.select_related("app")