Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Serialize capture and refund bookkeeping on row locks

Damian Legawiecfa1338394db7
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index a00ee64163..1d1ffe0bd3 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -330,6 +330,49 @@ ships in the OSS Admin API; first-run configures the one store.
Consequences: Admin API code must never assume `current_store` is the default
store, and store-touching cache keys must carry the store id by construction.
Plan: `6.0-store-context-and-first-run-setup.md`.
+## 2026-08-12 — Payment lock audit: locks live where money is recorded, never around gateway I/O
+
+A sweep of every payment operation with the settle_payment! lens — check-then-act
+on money state without mutual exclusion — after the with_order_lock removals.
+The rule that came out: **the row lock wraps the money bookkeeping with an
+in-lock recheck; the gateway call runs before it, unlocked, relying on provider
+idempotency.**
+
+Two real bugs found and fixed:
+
+- **`Payment#capture!` wrote the capture event before `handle_response`.** A
+ concurrent second capture passed the completed? check, hit the gateway
+ (idempotent at Stripe), persisted a second capture event, then exploded on
+ `complete!` — doubled captured_amount plus an ungraceful error. Now: gateway
+ first, then bookkeeping under `owner.with_lock` with a DB-state recheck
+ (deliberately not a reload — card numbers never persist, and
+ `split_uncaptured_amount` authorizes the remainder at the gateway, so it
+ stays outside the lock). A declined response also no longer leaves a
+ phantom capture event, and its failure transition runs outside the lock so
+ the raise cannot roll it back.
+- **Refund balance validation was unserialized.** Two concurrent partial
+ refunds both validated against the pre-refund balance and both credited —
+ a double-clicked 50% refund refunded 100% (Stripe's credit carries no
+ idempotency key). The refund row is what reserves the balance
+ (credit_allowed sums rows), so creation now takes `payment.with_lock` at
+ all five sites — Refunds::Create, the returns/exchange/claim drain loops,
+ and Stripe's cancel verb — making the create-time validation trustworthy.
+ `perform!` stays outside the lock.
+
+Judged acceptable, with reasons on record:
+
+- **Double void** — no capture events involved; the second void gets the
+ gateway's "already canceled" as a clean failure.
+- **Concurrent `process_payments!`** — the gateway is deduped by the
+ per-payment idempotency key, and the loser's `complete!` raises before its
+ capture-event line, so money math survives; the error is ungraceful. An
+ atomic claim (compare-and-swap on the state column) would make replays
+ graceful — follow-up, not urgent.
+- **Session create/update endpoints still hold with_order_lock across Stripe
+ intent calls** — the same smell the confirm endpoint shed, but fixing it
+ means restructuring gateway-owned code (persist the session row under a
+ short lock after the intent call). Flagged as follow-up.
+
## 2026-08-12 — The payment lifecycle routes through its workflows; refund creation owns the credit
An audit found the two payment workflows were dead code: `Payments::Capture`
diff --git a/spree/core/app/models/spree/payment/processing.rb b/spree/core/app/models/spree/payment/processing.rb
index 5e1820828a..c82a4768c5 100644
--- a/spree/core/app/models/spree/payment/processing.rb
+++ b/spree/core/app/models/spree/payment/processing.rb
@@ -51,6 +51,12 @@ module Spree
# Takes the amount in cents to capture.
# Can be used to capture partial amounts of a payment, and will create
# a new pending payment record for the remaining amount to capture later.
+ #
+ # The gateway call runs outside any lock (capture is idempotent at the
+ # provider — an already-captured intent comes back as success); the
+ # bookkeeping runs under the owner's row lock with a recheck, so a
+ # concurrent capture — or the webhook settling the same payment —
+ # records the capture event exactly once.
def capture!(amount = nil)
return true if completed?
@@ -65,10 +71,29 @@ module Spree
gateway_options
)
end
- money = ::Money.new(amount, currency)
- capture_events.create!(amount: money.to_f)
+
+ # A failed response writes no money records, so it needs no lock —
+ # and handle_response raises, which inside the lock's transaction
+ # would roll the failure state back.
+ handle_response(response, :complete, :failure) unless response.success?
+
+ already_captured = false
+ owner.with_lock do
+ # DB-state recheck, deliberately not a reload — reload would
+ # discard the in-memory source (card numbers never persist).
+ if self.class.where(id: id, state: 'completed').exists?
+ already_captured = true
+ else
+ capture_events.create!(amount: ::Money.new(amount, currency).to_f)
+ handle_response(response, :complete, :failure)
+ end
+ end
+ return true if already_captured
+
+ # Authorizes the remainder at the gateway — its own network call,
+ # so it stays outside the lock.
split_uncaptured_amount
- handle_response(response, :complete, :failure)
+ true
end
end
diff --git a/spree/core/app/workflows/spree/claims/resolve.rb b/spree/core/app/workflows/spree/claims/resolve.rb
index 8ba5d07e37..e7f1c2ca3c 100644
--- a/spree/core/app/workflows/spree/claims/resolve.rb
+++ b/spree/core/app/workflows/spree/claims/resolve.rb
@@ -141,12 +141,16 @@ module Spree
creditable = [payment.credit_allowed.to_d, remaining].min
next unless creditable.positive?
- refund = payment.refunds.create!(
- amount: creditable,
- reason: Spree::RefundReason.return_processing_reason(claim.store),
- refunder: resolver,
- originator: claim
- )
+ # Serialized on the payment row — the balance validation must see any
+ # concurrently created refund rows (credit_allowed sums them).
+ refund = payment.with_lock do
+ payment.refunds.create!(
+ amount: creditable,
+ reason: Spree::RefundReason.return_processing_reason(claim.store),
+ refunder: resolver,
+ originator: claim
+ )
+ end
refund.perform!
@refunds << refund
remaining -= creditable
diff --git a/spree/core/app/workflows/spree/exchanges/fulfill.rb b/spree/core/app/workflows/spree/exchanges/fulfill.rb
index d162dac719..5f475fdf87 100644
--- a/spree/core/app/workflows/spree/exchanges/fulfill.rb
+++ b/spree/core/app/workflows/spree/exchanges/fulfill.rb
@@ -120,12 +120,16 @@ module Spree
creditable = [payment.credit_allowed.to_d, remaining].min
next unless creditable.positive?
- refund = payment.refunds.create!(
- amount: creditable,
- reason: Spree::RefundReason.return_processing_reason(exchange.store),
- refunder: refunder,
- originator: exchange
- )
+ # Serialized on the payment row — the balance validation must see any
+ # concurrently created refund rows (credit_allowed sums them).
+ refund = payment.with_lock do
+ payment.refunds.create!(
+ amount: creditable,
+ reason: Spree::RefundReason.return_processing_reason(exchange.store),
+ refunder: refunder,
+ originator: exchange
+ )
+ end
refund.perform!
@refunds << refund
remaining -= creditable
diff --git a/spree/core/app/workflows/spree/refunds/create.rb b/spree/core/app/workflows/spree/refunds/create.rb
index 22853c5ec8..ef1e1ff301 100644
--- a/spree/core/app/workflows/spree/refunds/create.rb
+++ b/spree/core/app/workflows/spree/refunds/create.rb
@@ -54,13 +54,19 @@ module Spree
failure(payment, :refund_amount_exceeds_balance)
end
+ # The row is what reserves the balance — credit_allowed sums refund rows —
+ # so creation serializes on the payment's row lock. Without it the
+ # balance validation is check-then-act, and two concurrent refunds would
+ # both validate against the pre-refund balance and both credit.
def create_refund
- @refund = payment.refunds.create!(
- amount: @amount_to_refund,
- reason: reason || Spree::RefundReason.return_processing_reason(payment.order&.store),
- refunder: refunder,
- originator: originator
- )
+ payment.with_lock do
+ @refund = payment.refunds.create!(
+ amount: @amount_to_refund,
+ reason: reason || Spree::RefundReason.return_processing_reason(payment.order&.store),
+ refunder: refunder,
+ originator: originator
+ )
+ end
end
def credit_at_gateway
diff --git a/spree/core/app/workflows/spree/returns/refund.rb b/spree/core/app/workflows/spree/returns/refund.rb
index 5e2a265690..8d6b58e8a4 100644
--- a/spree/core/app/workflows/spree/returns/refund.rb
+++ b/spree/core/app/workflows/spree/returns/refund.rb
@@ -126,12 +126,16 @@ module Spree
creditable = [payment.credit_allowed.to_d, remaining].min
next unless creditable.positive?
- refund = payment.refunds.create!(
- amount: creditable,
- reason: Spree::RefundReason.return_processing_reason(return_record.store),
- refunder: refunder,
- originator: return_record
- )
+ # Serialized on the payment row — the balance validation must see any
+ # concurrently created refund rows (credit_allowed sums them).
+ refund = payment.with_lock do
+ payment.refunds.create!(
+ amount: creditable,
+ reason: Spree::RefundReason.return_processing_reason(return_record.store),
+ refunder: refunder,
+ originator: return_record
+ )
+ end
refund.perform!
@refunds << refund
remaining -= creditable
diff --git a/spree/core/spec/models/spree/payment_spec.rb b/spree/core/spec/models/spree/payment_spec.rb
index 1a67b51682..d571f0567b 100644
--- a/spree/core/spec/models/spree/payment_spec.rb
+++ b/spree/core/spec/models/spree/payment_spec.rb
@@ -622,6 +622,22 @@ describe Spree::Payment, type: :model do
end
end
+ it 'records the capture under the owner row lock' do
+ expect(payment.payment_method).to receive(:capture).and_return(success_response)
+ expect(payment.owner).to receive(:with_lock).and_call_original
+
+ payment.capture!
+ end
+
+ it 'records nothing when another caller already completed the payment' do
+ expect(payment.payment_method).to receive(:capture).and_return(success_response)
+ # Simulates the concurrent winner committing between the gateway
+ # call and the bookkeeping lock.
+ allow(Spree::Payment).to receive_message_chain(:where, :exists?).and_return(true)
+
+ expect { payment.capture! }.not_to change { payment.capture_events.count }
+ end
+
context 'for partial amount' do
let(:original_amount) { payment.money.amount_in_cents }
let(:capture_amount) { original_amount - 100 }
diff --git a/spree/core/spec/workflows/spree/refunds/create_spec.rb b/spree/core/spec/workflows/spree/refunds/create_spec.rb
index 44e1fbdb36..7c69aafc95 100644
--- a/spree/core/spec/workflows/spree/refunds/create_spec.rb
+++ b/spree/core/spec/workflows/spree/refunds/create_spec.rb
@@ -58,6 +58,12 @@ RSpec.describe Spree::Refunds::Create do
expect(described_class.call(payment: payment, amount: 0)).to be_failure
end
+ it 'creates the refund row under the payment row lock' do
+ expect(payment).to receive(:with_lock).and_call_original
+
+ described_class.call(payment: payment)
+ end
+
it 'destroys the uncredited refund when the gateway declines' do
allow_any_instance_of(Spree::Refund).to receive(:perform!).
and_raise(Spree::Core::GatewayError, 'declined')
diff --git a/spree/providers/stripe/app/models/spree_stripe/gateway.rb b/spree/providers/stripe/app/models/spree_stripe/gateway.rb
index 2428e86b7a..4b041e309b 100644
--- a/spree/providers/stripe/app/models/spree_stripe/gateway.rb
+++ b/spree/providers/stripe/app/models/spree_stripe/gateway.rb
@@ -102,11 +102,15 @@ module SpreeStripe
return success(payment_intent_id, {}) if amount.zero?
return success(payment_intent_id, {}) if payment.respond_to?(:for_shipment?) && payment.for_shipment?
- refund = payment.refunds.create!(
- amount: amount,
- reason: Spree::RefundReason.order_canceled_reason,
- refunder_id: payment.order.canceler_id
- )
+ # Serialized on the payment row — the balance validation must see any
+ # concurrently created refund rows (credit_allowed sums them).
+ refund = payment.with_lock do
+ payment.refunds.create!(
+ amount: payment.credit_allowed,
+ reason: Spree::RefundReason.order_canceled_reason,
+ refunder_id: payment.order.canceler_id
+ )
+ end
begin
refund.perform!