Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Enforce gift card customer assignment in the transaction flow (#19676)
Lukasz Ostrowski2621df2675c9
diff --git a/saleor/giftcard/gateway.py b/saleor/giftcard/gateway.pyindex e66050a302..918980496c 100644--- a/saleor/giftcard/gateway.py+++ b/saleor/giftcard/gateway.py@@ -1,3 +1,4 @@+import loggingfrom decimal import Decimalfrom typing import Annotatedfrom uuid import uuid4@@ -33,6 +34,12 @@ from .events import gift_card_refunded_in_order_event, gift_cards_used_in_order_from .models import GiftCardfrom .search import mark_gift_cards_search_index_as_dirty+logger = logging.getLogger(__name__)++# Returned for every reason a code cannot be used, so the response never reveals+# whether the card exists or belongs to another customer.+INVALID_GIFT_CARD_CODE_MESSAGE = "Gift card code is not valid."+class GiftCardPaymentGatewayDataSchema(pydantic.BaseModel):code: Annotated[@@ -68,7 +75,9 @@ def transaction_initialize_session_with_gift_card_payment_method(try:validate_transaction_session_data(transaction_session_data, source_object)- gift_card = validate_and_get_gift_card(transaction_session_data)+ gift_card = validate_and_get_gift_card(+ transaction_session_data, source_object.user_id+ )except GiftCardPaymentGatewayException as exc:return TransactionSessionResult(app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,@@ -125,8 +134,13 @@ def validate_transaction_session_data(def validate_and_get_gift_card(transaction_session_data: "TransactionSessionData",+ source_object_user_id: int | None,):- """Check for the existence of given gift card and lock it for use in a database transaction. Check whether gift card has enough funds to cover transaction amount."""+ """Check for the existence of given gift card and lock it for use in a database transaction.++ Check that a card restricted to a customer is used by that customer, and that the+ gift card has enough funds to cover transaction amount.+ """try:gift_card = (GiftCard.objects.active(date=timezone.now().date())@@ -139,9 +153,19 @@ def validate_and_get_gift_card()except GiftCard.DoesNotExist as exc:raise GiftCardPaymentGatewayException(- msg="Gift card code is not valid."+ msg=INVALID_GIFT_CARD_CODE_MESSAGE) from exc+ # Restriction is checked before the balance so a caller who is not the assignee+ # never learns the card's remaining balance from the rejection message.+ if rejection_reason := gift_card.usage_restriction_reason(source_object_user_id):+ logger.info(+ "Rejected use of gift card %s %s in a payment transaction.",+ gift_card.pk,+ rejection_reason,+ )+ raise GiftCardPaymentGatewayException(msg=INVALID_GIFT_CARD_CODE_MESSAGE)+if transaction_session_data.action.amount > gift_card.current_balance_amount:raise GiftCardPaymentGatewayException(msg=f"Gift card has insufficient amount ({quantize_price(gift_card.current_balance_amount, gift_card.currency)}) "diff --git a/saleor/giftcard/models.py b/saleor/giftcard/models.pyindex 819000fd18..9a8117ef25 100644--- a/saleor/giftcard/models.py+++ b/saleor/giftcard/models.py@@ -151,6 +151,22 @@ class GiftCard(ModelWithMetadata):def display_code(self):return self.code[-4:]+ def usage_restriction_reason(self, user_id: int | None) -> str | None:+ """Return why a customer-restricted card cannot be used by this user, or None.++ A card whose assignee no longer exists (the user was deleted and+ ``assigned_to`` was nulled while ``assigned_to_email`` was kept) cannot+ be validated against an owner, so it is unusable by anyone — including a+ guest whose email happens to match ``assigned_to_email``. Otherwise a+ restricted card is usable only by the assigned, authenticated customer;+ a guest has no user id, so it never matches.+ """+ if self.assigned_to_email and not self.assigned_to_id:+ return "restricted to a deleted customer"+ if self.assigned_to_id and self.assigned_to_id != user_id:+ return "restricted to another customer"+ return None+class GiftCardEvent(models.Model):date = models.DateTimeField(default=timezone.now, editable=False)diff --git a/saleor/giftcard/tests/test_utils.py b/saleor/giftcard/tests/test_utils.pyindex c7f5893c49..52d27ca824 100644--- a/saleor/giftcard/tests/test_utils.py+++ b/saleor/giftcard/tests/test_utils.py@@ -1,5 +1,6 @@import datetimeimport json+from decimal import Decimalfrom unittest.mock import patchimport graphene@@ -17,11 +18,15 @@ from ...core.utils.json_serializer import CustomJsonEncoderfrom ...core.utils.promo_code import InvalidPromoCodefrom ...order import OrderEventsfrom ...order.models import OrderLine+from ...payment import TransactionAction, TransactionEventType+from ...payment.models import TransactionEventfrom ...plugins.manager import get_plugins_managerfrom ...site import GiftCardSettingsExpiryTypefrom ...webhook.event_types import WebhookEventAsyncTypefrom ...webhook.payloads import generate_meta, generate_requestorfrom .. import GiftCardEvents, GiftCardLineData, events+from ..const import GIFT_CARD_PAYMENT_GATEWAY_ID+from ..gateway import cancel_gift_card_transactionfrom ..models import GiftCard, GiftCardEventfrom ..utils import (GiftCardCannotAssign,@@ -941,6 +946,87 @@ def test_assign_blocked_when_checkout_has_transaction(assert checkout.gift_cards.filter(pk=gift_card.pk).exists()+def test_assign_blocked_when_gift_card_authorized_on_checkout(+ gift_card, customer_user, checkout, transaction_item_generator+):+ # given a gateway authorization holding the card on a live checkout. The card+ # is not in the checkout's gift_cards m2m — the gateway never adds it there.+ transaction_item_generator(checkout_id=checkout.pk, gift_card=gift_card)+ assert checkout.gift_cards.filter(pk=gift_card.pk).exists() is False++ # when / then+ with pytest.raises(GiftCardCannotAssign):+ assign_gift_card_to_user(gift_card, customer_user)+ gift_card.refresh_from_db()+ assert gift_card.assigned_to is None+ assert gift_card.assigned_to_email is None+++def test_assign_blocked_when_gift_card_authorized_on_order(+ gift_card, customer_user, order, transaction_item_generator+):+ # given an order-bound authorization that has not been charged yet. The charge+ # happens at order confirmation, which on a manually-confirmed channel can be+ # days later, so the card must stay locked to its current assignee.+ transaction_item_generator(order_id=order.pk, gift_card=gift_card)+ assert gift_card.last_used_on is None++ # when / then+ with pytest.raises(GiftCardCannotAssign):+ assign_gift_card_to_user(gift_card, customer_user)+ gift_card.refresh_from_db()+ assert gift_card.assigned_to is None+ assert gift_card.assigned_to_email is None+++def test_assign_blocked_after_transaction_fully_cancelled(+ gift_card, customer_user, checkout, transaction_item_generator+):+ # given a gateway authorization holding the card, then fully cancelled through+ # the real cancel path — the card stays linked to the transaction+ authorized_value = Decimal(10)+ transaction_item = transaction_item_generator(+ checkout_id=checkout.pk,+ gift_card=gift_card,+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,+ authorized_value=authorized_value,+ available_actions=[TransactionAction.CANCEL],+ )+ request_event = TransactionEvent.objects.create(+ transaction=transaction_item,+ type=TransactionEventType.CANCEL_REQUEST,+ amount_value=authorized_value,+ currency=transaction_item.currency,+ )+ cancel_gift_card_transaction(transaction_item, request_event)+ transaction_item.refresh_from_db()+ assert transaction_item.authorized_value == Decimal(0)+ assert transaction_item.gift_card == gift_card++ # when / then+ with pytest.raises(GiftCardCannotAssign):+ assign_gift_card_to_user(gift_card, customer_user)+ gift_card.refresh_from_db()+ assert gift_card.assigned_to is None+ assert gift_card.assigned_to_email is None+++def test_assign_allowed_when_transaction_has_neither_checkout_nor_order(+ gift_card, customer_user, transaction_item_generator+):+ # given an orphaned transaction: its checkout was deleted (TransactionItem.checkout+ # is SET_NULL) and it never reached an order, yet it still references the card+ transaction_item_generator(gift_card=gift_card)++ # when+ assign_gift_card_to_user(gift_card, customer_user)++ # then a dead row must not make the card permanently unassignable+ gift_card.refresh_from_db()+ assert gift_card.assigned_to == customer_user+ assert gift_card.assigned_to_email == customer_user.email++def test_deactivate_assigned_gift_cards_detaches_and_deactivates(gift_card, customer_user):diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.pyindex a45b55eab0..3e84bbde67 100644--- a/saleor/giftcard/utils.py+++ b/saleor/giftcard/utils.py@@ -8,6 +8,7 @@ from uuid import UUIDfrom dateutil.relativedelta import relativedeltafrom django.core.exceptions import ValidationErrorfrom django.db import transaction+from django.db.models import Qfrom django.db.models.expressions import Exists, OuterReffrom django.utils import timezone@@ -57,24 +58,11 @@ def add_gift_card_code_to_checkout(except GiftCard.DoesNotExist as e:raise InvalidPromoCode() from e- if gift_card.assigned_to_email and not gift_card.assigned_to_id:- # The card is restricted but its assignee no longer exists (the user was- # deleted and assigned_to was nulled). It cannot be validated against an- # owner, so it must not be usable by anyone — including a guest whose- # email happens to match assigned_to_email.+ if rejection_reason := gift_card.usage_restriction_reason(checkout.user_id):logger.info(- "Rejected use of gift card %s restricted to a deleted customer "- "in checkout %s.",- gift_card.pk,- checkout.pk,- )- raise InvalidPromoCode()- if gift_card.assigned_to_id and gift_card.assigned_to_id != checkout.user_id:- # Restricted gift cards can only be used by the assigned customer.- logger.info(- "Rejected use of gift card %s restricted to another customer "- "in checkout %s.",+ "Rejected use of gift card %s %s in checkout %s.",gift_card.pk,+ rejection_reason,checkout.pk,)# Generic error — do not reveal the assignee.@@ -128,6 +116,23 @@ def assign_gift_card_to_user(gift_card: "GiftCard", user: "User") -> None:"Cannot assign a gift card attached to a checkout with payments.")+ # A card used through the gift card payment gateway is linked by+ # TransactionItem.gift_card and never joins the checkouts m2m, so the check+ # above cannot see it. Any such transaction blocks assignment, cancelled ones+ # included — the link is the record that the card was used, and the charge can+ # happen long after the order was placed on a manually-confirmed channel.+ # Rows with neither a checkout nor an order are dead (TransactionItem.checkout+ # is SET_NULL) and must not lock the card forever.+ has_transactions = (+ TransactionItem.objects.filter(gift_card=locked)+ .filter(Q(checkout_id__isnull=False) | Q(order_id__isnull=False))+ .exists()+ )+ if has_transactions:+ raise GiftCardCannotAssign(+ "Cannot assign a gift card used by a payment transaction."+ )+# Detach clean checkouts in bulk (same invalidation that# checkoutRemovePromoCode performs). Batched to keep the row lock short.# Invalidate before clearing because the relation-backed queryset no longerdiff --git a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.pyindex e1c4cdae3e..9609ce935d 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py@@ -22,6 +22,7 @@ from .....giftcard.const import (SALEOR_GIFT_CARD_BRAND,SALEOR_GIFT_CARD_PAYMENT_METHOD_NAME,)+from .....giftcard.gateway import INVALID_GIFT_CARD_CODE_MESSAGEfrom .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderStatusfrom .....order.models import Orderfrom .....payment import (@@ -3561,7 +3562,7 @@ def test_for_checkout_with_gift_card_payment_gateway_gift_card_does_not_exist(request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,response_event_type=TransactionEventType.AUTHORIZATION_FAILURE,app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,- expected_message="Gift card code is not valid.",+ expected_message=INVALID_GIFT_CARD_CODE_MESSAGE,)@@ -3603,7 +3604,7 @@ def test_for_checkout_with_gift_card_payment_gateway_gift_card_has_different_currequest_event_type=TransactionEventType.AUTHORIZATION_REQUEST,response_event_type=TransactionEventType.AUTHORIZATION_FAILURE,app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,- expected_message="Gift card code is not valid.",+ expected_message=INVALID_GIFT_CARD_CODE_MESSAGE,)@@ -3645,7 +3646,7 @@ def test_for_checkout_with_gift_card_payment_gateway_gift_card_is_inactive(request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,response_event_type=TransactionEventType.AUTHORIZATION_FAILURE,app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,- expected_message="Gift card code is not valid.",+ expected_message=INVALID_GIFT_CARD_CODE_MESSAGE,)@@ -3687,7 +3688,7 @@ def test_for_checkout_with_gift_card_payment_gateway_gift_card_is_expired(request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,response_event_type=TransactionEventType.AUTHORIZATION_FAILURE,app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,- expected_message="Gift card code is not valid.",+ expected_message=INVALID_GIFT_CARD_CODE_MESSAGE,)@@ -3733,6 +3734,386 @@ def test_for_checkout_with_gift_card_payment_gateway_gift_card_has_insufficient_)[email protected]("saleor.giftcard.gateway.uuid4")+def test_for_checkout_with_gift_card_payment_gateway_gift_card_assigned_to_checkout_user(+ mocked_uuid4,+ user_api_client,+ checkout_with_prices,+ gift_card_created_by_staff,+ customer_user,+):+ # given+ checkout = checkout_with_prices+ mocked_uuid4.return_value = uuid4()++ assert checkout.user == customer_user+ gift_card_created_by_staff.assigned_to = customer_user+ gift_card_created_by_staff.assigned_to_email = customer_user.email+ gift_card_created_by_staff.save(update_fields=["assigned_to", "assigned_to_email"])++ variables = {+ "action": None,+ "amount": 1,+ "id": to_global_id_or_none(checkout),+ "paymentGateway": {+ "id": GIFT_CARD_PAYMENT_GATEWAY_ID,+ "data": {"code": gift_card_created_by_staff.code},+ },+ }++ # when+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)++ # then+ content = get_graphql_content(response)+ checkout.refresh_from_db()+ _assert_fields(+ content=content,+ source_object=checkout,+ expected_amount=Decimal(1),+ expected_psp_reference=str(mocked_uuid4.return_value),+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,+ response_event_type=TransactionEventType.AUTHORIZATION_SUCCESS,+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,+ authorized_value=Decimal(1),+ gift_card=gift_card_created_by_staff,+ expected_message=f"Gift card (ending: {gift_card_created_by_staff.display_code}).",+ available_actions=[TransactionAction.CANCEL],+ )++[email protected]("saleor.giftcard.gateway.uuid4")+def test_for_checkout_with_gift_card_payment_gateway_gift_card_assigned_to_other_user(+ mocked_uuid4,+ user_api_client,+ checkout_with_prices,+ gift_card_created_by_staff,+ customer_user,+ customer_user2,+):+ # given+ checkout = checkout_with_prices+ mocked_uuid4.return_value = uuid4()++ assert checkout.user == customer_user+ gift_card_created_by_staff.assigned_to = customer_user2+ gift_card_created_by_staff.assigned_to_email = customer_user2.email+ gift_card_created_by_staff.save(update_fields=["assigned_to", "assigned_to_email"])+ balance_before = gift_card_created_by_staff.current_balance_amount++ # when+ response = user_api_client.post_graphql(+ TRANSACTION_INITIALIZE,+ {+ "action": None,+ "amount": 1,+ "id": to_global_id_or_none(checkout),+ "paymentGateway": {+ "id": GIFT_CARD_PAYMENT_GATEWAY_ID,+ "data": {"code": gift_card_created_by_staff.code},+ },+ },+ )++ # then+ content = get_graphql_content(response)+ checkout.refresh_from_db()+ _assert_fields(+ content=content,+ source_object=checkout,+ expected_amount=Decimal(1),+ expected_psp_reference=str(mocked_uuid4.return_value),+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,+ response_event_type=TransactionEventType.AUTHORIZATION_FAILURE,+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,+ # Same message as a nonexistent code — must not reveal that the card+ # exists or that it belongs to somebody else.+ expected_message=INVALID_GIFT_CARD_CODE_MESSAGE,+ )+ gift_card_created_by_staff.refresh_from_db()+ assert gift_card_created_by_staff.current_balance_amount == balance_before++[email protected]("saleor.giftcard.gateway.uuid4")+def test_for_checkout_with_gift_card_payment_gateway_restricted_gift_card_and_guest_checkout(+ mocked_uuid4,+ api_client,+ checkout_with_prices,+ gift_card_created_by_staff,+ customer_user,+):+ # given a guest checkout whose email matches the assignee — matching the email+ # is not enough, the customer must be authenticated+ checkout = checkout_with_prices+ mocked_uuid4.return_value = uuid4()++ checkout.user = None+ checkout.email = customer_user.email+ checkout.save(update_fields=["user", "email"])+ gift_card_created_by_staff.assigned_to = customer_user+ gift_card_created_by_staff.assigned_to_email = customer_user.email+ gift_card_created_by_staff.save(update_fields=["assigned_to", "assigned_to_email"])+ balance_before = gift_card_created_by_staff.current_balance_amount++ # when+ response = api_client.post_graphql(+ TRANSACTION_INITIALIZE,+ {+ "action": None,+ "amount": 1,+ "id": to_global_id_or_none(checkout),+ "paymentGateway": {+ "id": GIFT_CARD_PAYMENT_GATEWAY_ID,+ "data": {"code": gift_card_created_by_staff.code},+ },+ },+ )++ # then+ content = get_graphql_content(response)+ checkout.refresh_from_db()+ _assert_fields(+ content=content,+ source_object=checkout,+ expected_amount=Decimal(1),+ expected_psp_reference=str(mocked_uuid4.return_value),+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,+ response_event_type=TransactionEventType.AUTHORIZATION_FAILURE,+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,+ expected_message=INVALID_GIFT_CARD_CODE_MESSAGE,+ )+ gift_card_created_by_staff.refresh_from_db()+ assert gift_card_created_by_staff.current_balance_amount == balance_before++[email protected]("saleor.giftcard.gateway.uuid4")+def test_for_checkout_with_gift_card_payment_gateway_gift_card_assignee_deleted(+ mocked_uuid4,+ user_api_client,+ checkout_with_prices,+ gift_card_created_by_staff,+ customer_user,+):+ # given a card restricted to a now-deleted user: assigned_to was nulled while+ # assigned_to_email was retained. It can no longer be validated against an+ # owner, so nobody may use it — not even a logged-in user with that email.+ checkout = checkout_with_prices+ mocked_uuid4.return_value = uuid4()++ assert checkout.user == customer_user+ gift_card_created_by_staff.assigned_to = None+ gift_card_created_by_staff.assigned_to_email = customer_user.email+ gift_card_created_by_staff.save(update_fields=["assigned_to", "assigned_to_email"])+ balance_before = gift_card_created_by_staff.current_balance_amount++ # when+ response = user_api_client.post_graphql(+ TRANSACTION_INITIALIZE,+ {+ "action": None,+ "amount": 1,+ "id": to_global_id_or_none(checkout),+ "paymentGateway": {+ "id": GIFT_CARD_PAYMENT_GATEWAY_ID,+ "data": {"code": gift_card_created_by_staff.code},+ },+ },+ )++ # then+ content = get_graphql_content(response)+ checkout.refresh_from_db()+ _assert_fields(+ content=content,+ source_object=checkout,+ expected_amount=Decimal(1),+ expected_psp_reference=str(mocked_uuid4.return_value),+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,+ response_event_type=TransactionEventType.AUTHORIZATION_FAILURE,+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,+ expected_message=INVALID_GIFT_CARD_CODE_MESSAGE,+ )+ gift_card_created_by_staff.refresh_from_db()+ assert gift_card_created_by_staff.current_balance_amount == balance_before++[email protected]("saleor.giftcard.gateway.uuid4")+def test_for_checkout_with_gift_card_payment_gateway_other_users_gift_card_does_not_leak_balance(+ mocked_uuid4,+ user_api_client,+ checkout_with_prices,+ gift_card_created_by_staff,+ customer_user2,+):+ # given a restricted card that also has insufficient funds+ checkout = checkout_with_prices+ mocked_uuid4.return_value = uuid4()++ balance_before = Decimal("0.1")+ gift_card_created_by_staff.assigned_to = customer_user2+ gift_card_created_by_staff.assigned_to_email = customer_user2.email+ gift_card_created_by_staff.current_balance_amount = balance_before+ gift_card_created_by_staff.save(+ update_fields=["assigned_to", "assigned_to_email", "current_balance_amount"]+ )++ # when+ response = user_api_client.post_graphql(+ TRANSACTION_INITIALIZE,+ {+ "action": None,+ "amount": 1,+ "id": to_global_id_or_none(checkout),+ "paymentGateway": {+ "id": GIFT_CARD_PAYMENT_GATEWAY_ID,+ "data": {"code": gift_card_created_by_staff.code},+ },+ },+ )++ # then the assignment check runs before the balance check, so a non-owner never+ # learns the card's remaining balance+ content = get_graphql_content(response)+ checkout.refresh_from_db()+ _assert_fields(+ content=content,+ source_object=checkout,+ expected_amount=Decimal(1),+ expected_psp_reference=str(mocked_uuid4.return_value),+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,+ response_event_type=TransactionEventType.AUTHORIZATION_FAILURE,+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,+ expected_message=INVALID_GIFT_CARD_CODE_MESSAGE,+ )+ gift_card_created_by_staff.refresh_from_db()+ assert gift_card_created_by_staff.current_balance_amount == balance_before++[email protected]("saleor.giftcard.gateway.uuid4")+def test_for_checkout_with_gift_card_payment_gateway_unrestricted_gift_card_and_guest_checkout(+ mocked_uuid4,+ api_client,+ checkout_with_prices,+ gift_card_created_by_staff,+):+ # given+ checkout = checkout_with_prices+ mocked_uuid4.return_value = uuid4()++ checkout.user = None+ checkout.save(update_fields=["user"])+ assert gift_card_created_by_staff.assigned_to_id is None+ assert gift_card_created_by_staff.assigned_to_email is None++ # when+ response = api_client.post_graphql(+ TRANSACTION_INITIALIZE,+ {+ "action": None,+ "amount": 1,+ "id": to_global_id_or_none(checkout),+ "paymentGateway": {+ "id": GIFT_CARD_PAYMENT_GATEWAY_ID,+ "data": {"code": gift_card_created_by_staff.code},+ },+ },+ )++ # then+ content = get_graphql_content(response)+ checkout.refresh_from_db()+ _assert_fields(+ content=content,+ source_object=checkout,+ expected_amount=Decimal(1),+ expected_psp_reference=str(mocked_uuid4.return_value),+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,+ response_event_type=TransactionEventType.AUTHORIZATION_SUCCESS,+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,+ authorized_value=Decimal(1),+ gift_card=gift_card_created_by_staff,+ expected_message=f"Gift card (ending: {gift_card_created_by_staff.display_code}).",+ available_actions=[TransactionAction.CANCEL],+ )++[email protected]("saleor.giftcard.gateway.uuid4")+def test_for_checkout_with_gift_card_payment_gateway_rejection_keeps_owner_authorization(+ mocked_uuid4,+ user2_api_client,+ checkout_with_prices,+ gift_card_created_by_staff,+ customer_user,+ customer_user2,+ transaction_item_generator,+):+ # given the assignee already holds a live authorization on their own checkout+ owner_checkout = checkout_with_prices+ mocked_uuid4.return_value = uuid4()++ gift_card_created_by_staff.assigned_to = customer_user+ gift_card_created_by_staff.assigned_to_email = customer_user.email+ gift_card_created_by_staff.save(update_fields=["assigned_to", "assigned_to_email"])+ owner_transaction = transaction_item_generator(+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,+ checkout_id=owner_checkout.pk,+ gift_card=gift_card_created_by_staff,+ authorized_value=Decimal(5),+ )++ other_checkout = Checkout.objects.create(+ currency=owner_checkout.currency,+ user=customer_user2,+ channel=owner_checkout.channel,+ base_total=Money("15", owner_checkout.currency),+ base_subtotal=Money("10", owner_checkout.currency),+ )++ # when the other customer tries the same code+ response = user2_api_client.post_graphql(+ TRANSACTION_INITIALIZE,+ {+ "action": None,+ "amount": 1,+ "id": to_global_id_or_none(other_checkout),+ "paymentGateway": {+ "id": GIFT_CARD_PAYMENT_GATEWAY_ID,+ "data": {"code": gift_card_created_by_staff.code},+ },+ },+ )++ # then the attempt fails and the assignee's authorization is untouched — a+ # rejected call must not be usable to cancel somebody else's payment+ content = get_graphql_content(response)+ _assert_fields(+ content=content,+ source_object=other_checkout,+ expected_amount=Decimal(1),+ expected_psp_reference=str(mocked_uuid4.return_value),+ request_event_type=TransactionEventType.AUTHORIZATION_REQUEST,+ response_event_type=TransactionEventType.AUTHORIZATION_FAILURE,+ app_identifier=GIFT_CARD_PAYMENT_GATEWAY_ID,+ expected_message=INVALID_GIFT_CARD_CODE_MESSAGE,+ )++ owner_transaction.refresh_from_db()+ assert owner_transaction.gift_card == gift_card_created_by_staff+ assert owner_transaction.authorized_value == Decimal(5)+ assert (+ owner_transaction.events.filter(+ type=TransactionEventType.CANCEL_REQUEST+ ).exists()+ is False+ )+ assert (+ owner_transaction.events.filter(+ type=TransactionEventType.CANCEL_SUCCESS+ ).exists()+ is False+ )++@mock.patch("saleor.giftcard.gateway.uuid4")def test_for_checkout_with_gift_card_payment_gateway_invalidates_previous_authorizations(mocked_uuid4,diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.pyindex 71f6b4211b..94528140d2 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py@@ -1384,7 +1384,7 @@ def test_transaction_request_cancelation_for_checkout_gift_card_authorization(assert transaction.authorized_value == Decimal(10) - expected_cancel_amountassert transaction.charged_value == Decimal(0)- assert transaction.gift_card is not None+ assert transaction.gift_card == gift_card_created_by_staffassert transaction.available_actions == expected_available_actionsassert checkout.authorize_status == expected_authorize_status