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.

Enforce the completion claim against cart mutations

Damian Legawiec18c8d3b0a9fa
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 1d1ffe0bd3..397288a126 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -330,6 +330,39 @@ 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 — Amount consistency during gateway operations: the completion claim, not a lock
+
+Raised as a challenge to the lock removals: shouldn't the order be locked for
+the whole gateway operation, so it cannot be mutated into a different total
+than the one sent to the gateway? The invariant is right; the mechanism cannot
+be. For session gateways the charge happens client-side before any server
+endpoint runs — no server lock reaches it. And a row lock spanning a gateway
+timeout pins a database connection per in-flight payment; a provider brownout
+turns that into pool exhaustion for the whole store, not one order.
+
+What actually enforces the invariant is Carts::Complete's three layers:
+totals recalculated **inside** the cart's row lock at PREPARE ("not trusted
+from earlier requests") and checked against the client's expected_total; the
+`completing` claim stamped before the lock releases; payment coverage
+re-verified at FINALIZE, with the Y3 undo popping payments back to the cart
+when it fails.
+
+The challenge found a real hole in layer two: the claim was only consulted by
+guard_concurrent_completion — it blocked a second *completion*, but nothing
+blocked a *mutation* during the unlocked gateway window. An AddItem landing
+there changed the cart under a completion whose totals were fixed at PREPARE.
+Now `with_order_lock` — the funnel every store cart mutation passes through —
+refuses mutations while a fresh claim holds the cart (409
+completion_in_progress), checked after acquiring the row lock so it cannot
+race the claim being written, with the same TTL as the completion guard so a
+crashed completion never bricks its cart.
+
+**Consequences:** third-party gateway authors rely on four guarantees, none of
+which is "the order is locked while you talk to your provider": the amount is
+fixed in the session/intent and synced on update; mutations are excluded
+during the completion window by the claim; completion re-verifies coverage
+and compensates; settlement and capture bookkeeping serialize on row locks.
+
## 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
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/order_lock.rb b/spree/api/app/controllers/concerns/spree/api/v3/order_lock.rb
index 952fba0740..1a52a01f97 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/order_lock.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/order_lock.rb
@@ -19,6 +19,22 @@ module Spree
# the row lock alone still serializes the idempotent paths.
next yield if order.readonly?
+ # A completion attempt fixed this cart's totals under the lock and
+ # is now off at the gateway — mutating the cart mid-window would
+ # complete it with different totals than the ones being charged.
+ # The completion claim excludes mutations for exactly that window;
+ # checked after acquiring the lock so it cannot race the claim
+ # being written. The TTL matches guard_concurrent_completion — a
+ # crashed completion must not brick its cart.
+ if order.is_a?(Spree::Cart) && order.completing? &&
+ order.completing_at > Spree::Carts::Complete::COMPLETING_TTL.ago
+ next render_error(
+ code: 'completion_in_progress',
+ message: Spree.t(:cart_completion_in_progress),
+ status: :conflict
+ )
+ end
+
# Persist increment within the transaction so reloads inside yield see the new version
new_version = order.lock_version + 1
order.update_column(:lock_version, new_version)
diff --git a/spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rb
index b85490302f..5c9eb28428 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts/items_controller_spec.rb
@@ -32,6 +32,30 @@ RSpec.describe Spree::Api::V3::Store::Carts::ItemsController, type: :controller
expect(json_response['total_quantity']).to eq(1)
end
+ # A completion attempt fixed the cart's totals and is off at the gateway —
+ # a mutation landing in that window would complete the cart with different
+ # totals than the ones being charged.
+ context 'while a completion holds the cart' do
+ before { order.update_column(:completing_at, Time.current) }
+
+ it 'refuses the mutation with a conflict' do
+ expect do
+ post :create, params: { cart_id: order.prefixed_id, variant_id: variant.prefixed_id }
+ end.not_to change(Spree::LineItem, :count)
+
+ expect(response).to have_http_status(:conflict)
+ expect(json_response['error']['code']).to eq('completion_in_progress')
+ end
+
+ it 'allows the mutation once the claim is stale' do
+ order.update_column(:completing_at, 10.minutes.ago)
+
+ post :create, params: { cart_id: order.prefixed_id, variant_id: variant.prefixed_id }
+
+ expect(response).to have_http_status(:created)
+ end
+ end
+
it 'returns updated totals' do
post :create, params: { cart_id: order.prefixed_id, variant_id: variant.prefixed_id, quantity: 2 }
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 03cfe11825..0194d63c07 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -676,6 +676,7 @@ en:
card_number: Card Number
cart: Cart
cart_already_updated: The cart has already been updated.
+ cart_completion_in_progress: The cart is being completed. Please retry in a moment.
cart_line_item:
currency_unavailable: "%{li_name} is not available in %{currency}"
delivery_unavailable: "%{li_name} cannot be delivered to the selected address"