Skip to content

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

Always use active app to process transactionAPI actions (#14933)

Maciej Korycinski6816d630a3a0
diff --git a/saleor/graphql/app/dataloaders.py b/saleor/graphql/app/dataloaders.py
index c0fa280fc4..b6f55d69b1 100644
--- a/saleor/graphql/app/dataloaders.py
+++ b/saleor/graphql/app/dataloaders.py
@@ -50,12 +50,12 @@ class AppExtensionByAppIdLoader(DataLoader):
return [extensions_map.get(app_id, []) for app_id in keys]
-class AppsByAppIdentifierLoader(DataLoader):
+class ActiveAppsByAppIdentifierLoader(DataLoader):
context_key = "apps_by_app_identifier"
def batch_load(self, keys):
apps = App.objects.using(self.database_connection_name).filter(
- identifier__in=keys, removed_at__isnull=True
+ identifier__in=keys, is_active=True, removed_at__isnull=True
)
apps_map = defaultdict(list)
for app in apps:
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_initialize.py b/saleor/graphql/payment/mutations/transaction/transaction_initialize.py
index fea746b300..f9832d3cb8 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_initialize.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_initialize.py
@@ -94,7 +94,11 @@ class TransactionInitialize(TransactionSessionBase):
@classmethod
def clean_app_from_payment_gateway(cls, payment_gateway: PaymentGatewayData) -> App:
- app = App.objects.filter(identifier=payment_gateway.app_identifier).first()
+ app = App.objects.filter(
+ identifier=payment_gateway.app_identifier,
+ removed_at__isnull=True,
+ is_active=True,
+ ).first()
if not app:
raise ValidationError(
{
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_process.py b/saleor/graphql/payment/mutations/transaction/transaction_process.py
index f31bbc366a..9cfd9cf59e 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_process.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_process.py
@@ -149,7 +149,9 @@ class TransactionProcess(BaseMutation):
}
)
app = App.objects.filter(
- identifier=transaction_item.app_identifier, removed_at__isnull=True
+ identifier=transaction_item.app_identifier,
+ removed_at__isnull=True,
+ is_active=True,
).first()
if not app:
raise ValidationError(
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
index 34e497c53d..820d7e6204 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
@@ -937,6 +937,71 @@ def test_uses_default_channel_action(
)
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_transaction_initialize_for_removed_app(
+ mocked_initialize,
+ user_api_client,
+ checkout_with_prices,
+ removed_app,
+):
+ # given
+ expected_amount = Decimal("10.00")
+ checkout = checkout_with_prices
+ expected_app_identifier = "webhook.app.identifier"
+ removed_app.identifier = expected_app_identifier
+ removed_app.save()
+
+ variables = {
+ "action": None,
+ "amount": expected_amount,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["transactionInitialize"]
+ assert data["errors"][0]["code"] == TransactionInitializeErrorCode.NOT_FOUND.name
+ assert data["errors"][0]["field"] == "paymentGateway"
+ mocked_initialize.assert_not_called()
+
+
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_transaction_initialize_for_disabled_app(
+ mocked_initialize,
+ user_api_client,
+ checkout_with_prices,
+ app,
+):
+ # given
+ expected_amount = Decimal("10.00")
+ checkout = checkout_with_prices
+ expected_app_identifier = "webhook.app.identifier"
+ app.identifier = expected_app_identifier
+ app.is_active = False
+ app.save()
+
+ variables = {
+ "action": None,
+ "amount": expected_amount,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["transactionInitialize"]
+ assert data["errors"][0]["code"] == TransactionInitializeErrorCode.NOT_FOUND.name
+ assert data["errors"][0]["field"] == "paymentGateway"
+ mocked_initialize.assert_not_called()
+
+
@mock.patch("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
def test_app_with_action_field(
mocked_initialize,
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_process.py b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
index ea0d42d7d2..abdf213982 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_process.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
@@ -1293,6 +1293,47 @@ def test_customer_ip_address_ipv6(
)
+def test_transaction_process_for_disabled_app(
+ user_api_client,
+ checkout_with_prices,
+ app,
+ transaction_item_generator,
+):
+ # given
+ expected_amount = Decimal("10.00")
+ expected_app_identifier = "webhook.app.identifier"
+ app.identifier = expected_app_identifier
+ app.is_active = False
+ app.save()
+
+ transaction_item = transaction_item_generator(
+ checkout_id=checkout_with_prices.pk, app=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)
+ 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"
+
+
@freeze_time("2023-03-18 12:00:00")
@pytest.mark.parametrize(
"previous_last_transaction_modified_at",
diff --git a/saleor/graphql/payment/tests/queries/test_transaction.py b/saleor/graphql/payment/tests/queries/test_transaction.py
index 25cba0ef75..3437f16b74 100644
--- a/saleor/graphql/payment/tests/queries/test_transaction.py
+++ b/saleor/graphql/payment/tests/queries/test_transaction.py
@@ -1,7 +1,9 @@
+from datetime import datetime
from decimal import Decimal
import graphene
import pytest
+from freezegun import freeze_time
from .....payment import TransactionEventType
from .....payment.models import TransactionEvent
@@ -260,6 +262,47 @@ def test_transaction_created_by_app_query_by_staff(
)
+@freeze_time("2022-05-12 12:00:00")
+def test_transaction_created_by_app_marked_to_remove(
+ staff_api_client,
+ transaction_item_created_by_app,
+ permission_manage_payments,
+ app,
+ webhook_app,
+):
+ # given
+ app.is_active = False
+ app.removed_at = datetime.now()
+ app.save()
+
+ webhook_app.identifier = app.identifier
+ webhook_app.save()
+
+ event = transaction_item_created_by_app.events.filter(
+ type=TransactionEventType.CHARGE_SUCCESS
+ ).get()
+
+ variables = {
+ "id": graphene.Node.to_global_id(
+ "TransactionItem", transaction_item_created_by_app.token
+ )
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ TRANSACTION_QUERY, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ _assert_transaction_fields_created_by(
+ content,
+ transaction_item_created_by_app,
+ event,
+ webhook_app,
+ )
+
+
def test_transaction_create_by_app_query_no_permission(
app_api_client, transaction_item_created_by_app
):
@@ -629,3 +672,58 @@ def test_transaction_event_by_reinstalled_app(
assert event_data["amount"]["currency"] == event.currency
assert event_data["type"] == event.type.upper()
assert event_data["createdBy"]["id"] == to_global_id_or_none(app_api_client.app)
+
+
+@freeze_time("2022-05-12 12:00:00")
+def test_transaction_event_by_app_marked_to_remove(
+ transaction_item_created_by_app,
+ permission_manage_payments,
+ permission_manage_staff,
+ staff_api_client,
+ app,
+ webhook_app,
+):
+ # given
+ identifier = "app.identifier"
+ app.identifier = identifier
+ app.is_active = False
+ app.removed_at = datetime.now()
+ app.save()
+ webhook_app.identifier = identifier
+ webhook_app.save()
+
+ psp_reference = "psp-ref-123"
+ event = TransactionEvent.objects.create(
+ transaction=transaction_item_created_by_app,
+ psp_reference=psp_reference,
+ message="Sucesfull charge",
+ currency="USD",
+ type=TransactionEventType.CHARGE_SUCCESS,
+ amount_value=Decimal("10.00"),
+ external_url=f"http://`{TEST_SERVER_DOMAIN}/test",
+ app_identifier=app.identifier,
+ app=app,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id(
+ "TransactionItem", transaction_item_created_by_app.token
+ )
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ TRANSACTION_QUERY,
+ variables,
+ permissions=[permission_manage_payments, permission_manage_staff],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ events = content["data"]["transaction"]["events"]
+ assert len(events) == 2
+ event_data = [event for event in events if event["pspReference"] == psp_reference][
+ 0
+ ]
+ assert event_data["amount"]["currency"] == event.currency
+ assert event_data["createdBy"]["id"] == to_global_id_or_none(webhook_app)
diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.py
index 1106ddf970..03df05f978 100644
--- a/saleor/graphql/payment/types.py
+++ b/saleor/graphql/payment/types.py
@@ -10,7 +10,7 @@ from ...payment import models
from ...payment.interface import PaymentMethodData
from ...permission.enums import OrderPermissions
from ..account.dataloaders import UserByUserIdLoader
-from ..app.dataloaders import AppByIdLoader, AppsByAppIdentifierLoader
+from ..app.dataloaders import ActiveAppsByAppIdentifierLoader, AppByIdLoader
from ..checkout.dataloaders import CheckoutByTokenLoader
from ..core import ResolveInfo
from ..core.connection import CountableConnection
@@ -370,20 +370,33 @@ class TransactionEvent(ModelObjectType[models.TransactionEvent]):
This covers a case when a third-party app was re-installed, but we're still able
to determine which one is the owner of the transaction.
"""
- if root.app_id:
- return AppByIdLoader(info.context).load(root.app_id)
- if root.app_identifier:
- def get_first_app(apps):
- if apps:
- return apps[0]
- return None
+ def get_first_app_by_identifier(apps):
+ if apps:
+ return apps[0]
+ return None
+
+ def get_active_app(app):
+ if app and app.is_active and not app.removed_at:
+ return app
+
+ if root.app_identifier:
+ return (
+ ActiveAppsByAppIdentifierLoader(info.context)
+ .load(root.app_identifier)
+ .then(get_first_app_by_identifier)
+ )
+ if root.app_id:
+ return AppByIdLoader(info.context).load(root.app_id).then(get_active_app)
+
+ if root.app_identifier:
return (
- AppsByAppIdentifierLoader(info.context)
+ ActiveAppsByAppIdentifierLoader(info.context)
.load(root.app_identifier)
- .then(get_first_app)
+ .then(get_first_app_by_identifier)
)
+
if root.user_id:
return UserByUserIdLoader(info.context).load(root.user_id)
return None
@@ -549,20 +562,32 @@ class TransactionItem(ModelObjectType[models.TransactionItem]):
to determine which one is the owner of the transaction.
"""
- if root.app_id:
- return AppByIdLoader(info.context).load(root.app_id)
- if root.app_identifier:
+ def get_first_app_by_identifier(apps):
+ if apps:
+ return apps[0]
+ return None
+
+ def get_active_app(app):
+ if app and app.is_active and not app.removed_at:
+ return app
- def get_first_app(apps):
- if apps:
- return apps[0]
- return None
+ if root.app_identifier:
+ return (
+ ActiveAppsByAppIdentifierLoader(info.context)
+ .load(root.app_identifier)
+ .then(get_first_app_by_identifier)
+ )
+ if root.app_id:
+ return AppByIdLoader(info.context).load(root.app_id).then(get_active_app)
+
+ if root.app_identifier:
return (
- AppsByAppIdentifierLoader(info.context)
+ ActiveAppsByAppIdentifierLoader(info.context)
.load(root.app_identifier)
- .then(get_first_app)
+ .then(get_first_app_by_identifier)
)
+
if root.user_id:
return UserByUserIdLoader(info.context).load(root.user_id)
return None
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index b56d07528a..9a834d9e9f 100644
--- a/saleor/payment/gateway.py
+++ b/saleor/payment/gateway.py
@@ -1,6 +1,6 @@
import logging
from decimal import Decimal
-from typing import TYPE_CHECKING, Callable, Optional
+from typing import TYPE_CHECKING, Callable, Optional, cast
from ..account.models import User
from ..app.models import App
@@ -200,10 +200,15 @@ def _create_transaction_data(
):
app_owner = None
if transaction.app_id:
- app_owner = transaction.app
- elif transaction.app_identifier:
+ app_owner = cast(App, transaction.app)
+ if not app_owner.is_active or app_owner.removed_at:
+ app_owner = None
+
+ if not app_owner and transaction.app_identifier:
app_owner = App.objects.filter(
- identifier=transaction.app_identifier, removed_at__isnull=True
+ identifier=transaction.app_identifier,
+ removed_at__isnull=True,
+ is_active=True,
).first()
return TransactionActionData(
diff --git a/saleor/payment/tests/test_gateway.py b/saleor/payment/tests/test_gateway.py
index 71b187bd52..737e4d8ba3 100644
--- a/saleor/payment/tests/test_gateway.py
+++ b/saleor/payment/tests/test_gateway.py
@@ -6,6 +6,7 @@ import pytest
from ...order import OrderEvents
from ...plugins.manager import get_plugins_manager
from ...webhook.event_types import WebhookEventSyncType
+from ...webhook.models import Webhook
from .. import (
ChargeStatus,
CustomPaymentChoices,
@@ -496,11 +497,103 @@ 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
+def test_request_action_by_removed_app(mocked_transaction_request, order, removed_app):
+ # given
+ app_identifier = "webhook.app.identifier"
+ removed_app.identifier = app_identifier
+ removed_app.save()
+ 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_identifier=app_identifier,
+ )
+ action_value = Decimal("5.00")
+ requested_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ # when & then
+ with pytest.raises(PaymentError):
+ 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,
+ )
+ assert not mocked_transaction_request.called
+
+
+@patch("saleor.plugins.manager.PluginsManager.transaction_charge_requested")
+def test_request_action_by_disabled_app(mocked_transaction_request, order, app):
+ # given
+ app_identifier = "webhook.app.identifier"
+ app.identifier = app_identifier
+ app.is_active = False
+ app.save()
+ 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_identifier=app_identifier,
+ )
+ action_value = Decimal("5.00")
+ requested_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ # when & then
+ with pytest.raises(PaymentError):
+ request_charge_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ charge_value=action_value,
+ channel_slug=order.channel.slug,
+ user=None,
+ app=app,
+ request_event=requested_event,
+ )
+ assert not mocked_transaction_request.called
+
+
+@patch("saleor.plugins.manager.PluginsManager.transaction_charge_requested")
+def test_request_action_by_removed_app_and_second_active(
+ mocked_transaction_request,
+ order,
+ removed_app,
+ webhook_app,
+ permission_manage_payments,
):
+ # given
+ app_identifier = "webhook.app.identifier"
+ active_app = webhook_app
+ active_app.identifier = app_identifier
+ active_app.save()
+ active_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=active_app,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED
+ webhook.events.create(event_type=event_type)
+
+ removed_app.identifier = app_identifier
+ removed_app.save()
+
transaction = TransactionItem.objects.create(
name="Credit card",
psp_reference="PSP ref",
@@ -508,6 +601,7 @@ def test_request_charge_action_by_removed_app(
currency="USD",
order_id=order.pk,
authorized_value=Decimal("10"),
+ app_identifier=app_identifier,
app=removed_app,
)
action_value = Decimal("5.00")
@@ -516,7 +610,6 @@ def test_request_charge_action_by_removed_app(
currency=transaction.currency,
type=TransactionEventType.CHARGE_REQUEST,
)
- mocked_is_active.side_effect = [True, True]
# when
request_charge_action(
@@ -525,20 +618,80 @@ def test_request_charge_action_by_removed_app(
charge_value=action_value,
channel_slug=order.channel.slug,
user=None,
- app=removed_app,
+ app=None,
request_event=requested_event,
)
# then
- assert mocked_is_active.called
mocked_transaction_request.assert_called_once_with(
TransactionActionData(
- action_type=TransactionAction.CHARGE,
transaction=transaction,
+ action_type=TransactionAction.CHARGE,
+ action_value=action_value,
event=requested_event,
- transaction_app_owner=removed_app,
+ transaction_app_owner=active_app,
+ ),
+ order.channel.slug,
+ )
+
+
+@patch("saleor.plugins.manager.PluginsManager.transaction_charge_requested")
+def test_request_action_by_disabled_app_and_second_active(
+ mocked_transaction_request, order, app, webhook_app, permission_manage_payments
+):
+ # given
+ app_identifier = "webhook.app.identifier"
+ active_app = webhook_app
+ active_app.identifier = app_identifier
+ active_app.save()
+ active_app.permissions.add(permission_manage_payments)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=active_app,
+ )
+ event_type = WebhookEventSyncType.TRANSACTION_CHARGE_REQUESTED
+ webhook.events.create(event_type=event_type)
+
+ app.identifier = app_identifier
+ app.is_active = False
+ app.save()
+
+ 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_identifier=app_identifier,
+ app=app,
+ )
+ action_value = Decimal("5.00")
+ requested_event = transaction.events.create(
+ amount_value=action_value,
+ currency=transaction.currency,
+ type=TransactionEventType.CHARGE_REQUEST,
+ )
+
+ # when
+ request_charge_action(
+ transaction=transaction,
+ manager=get_plugins_manager(),
+ charge_value=action_value,
+ channel_slug=order.channel.slug,
+ user=None,
+ app=None,
+ request_event=requested_event,
+ )
+
+ # then
+ mocked_transaction_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CHARGE,
action_value=action_value,
- granted_refund=None,
+ event=requested_event,
+ transaction_app_owner=active_app,
),
order.channel.slug,
)