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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Improve handling idempotency key (#14824)
Kacper Mękarski62f762864074
diff --git a/docs/api-reference/store-api/idempotency.mdx b/docs/api-reference/store-api/idempotency.mdxindex f9282bb0e1..768c1e221a 100644--- a/docs/api-reference/store-api/idempotency.mdx+++ b/docs/api-reference/store-api/idempotency.mdx@@ -25,6 +25,20 @@ curl -X POST https://api.mystore.com/api/v3/store/carts/cart_xxx/items \If the client retries this exact request with the same idempotency key, the API returns the original response with an `Idempotent-Replayed: true` header — without adding the item again.+## Who A Cached Response Belongs To++A cached response is only ever returned to the caller that produced it, so the request has to say who that caller is. One of these identifies them:++- the **customer's access token** (`Authorization: Bearer ...`), for a signed-in shopper+- the **cart token** (`X-Spree-Token`), for a guest working on a cart they already hold+- a **secret key** (`sk_...`), for a server-to-server caller on the Admin API++Retry with the same credentials you sent the first time. A replay answers from the cache without running the request again, so it never re-checks your access — a retry that drops or swaps a credential is treated as a different caller and runs for real.++Your publishable key (`pk_...`) does not count. Every visitor to your storefront sends the same one, so a key value that two shoppers happen to share — `checkout-1`, an order number, a timestamp — would hand one shopper the other's response, cart token included.++A request that carries none of the credentials above still runs exactly as it always has — it is simply never cached, so the `Idempotency-Key` header has no effect on it. Guests are not second-class here: a guest holds a cart token from the moment their cart exists, which covers the whole of checkout, including the steps where a duplicate costs money.+## Supported Endpoints| Endpoint | Actions |@@ -38,13 +52,15 @@ If the client retries this exact request with the same idempotency key, the API| `POST /carts/:id/coupon_codes` | Applying coupon codes || `POST /carts/:id/store_credits` | Applying store credits |+Every one of these is replayable for a guest as well as for a signed-in shopper, because every one of them is reached with the cart's token. The exception is creating the cart itself: there is no cart yet, so a guest has no token to present and the key is ignored — a retry may leave behind a second, empty cart. Sign the shopper in, or accept the spare cart.+Idempotency keys are ignored on `GET`, `DELETE`, and other non-supported actions.## Key Requirements- Must be a string of **255 characters or less**- Should be unique per distinct operation (UUIDs are recommended)-- Keys are scoped per API key — different API keys can use the same idempotency key without conflict+- Keys are scoped to the caller and the store, so two callers can use the same key value without conflict- Cached responses expire after **24 hours**## Response Headersdiff --git a/spree/api/app/controllers/concerns/spree/api/v3/idempotent.rb b/spree/api/app/controllers/concerns/spree/api/v3/idempotent.rbindex 037eda03fc..42d74d6550 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/idempotent.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/idempotent.rb@@ -29,6 +29,8 @@ module Spreereturnend+ return yield if caller_identity.nil?+cache_key = idempotency_cache_key(key)cached = Rails.cache.read(cache_key)@@ -66,17 +68,30 @@ module SpreeMUTATING_METHODS.include?(request.method)end+ def caller_identity+ return @caller_identity if defined?(@caller_identity)++ credentials = []++ credentials << ['secret_key', Spree::ApiKey.compute_token_digest(extract_api_key)] if secret_key_request?++ bearer_token = extract_token+ credentials << ['bearer', Digest::SHA256.hexdigest(bearer_token)] if bearer_token.present?++ credentials << ['order_token', Digest::SHA256.hexdigest(order_token)] if order_token.present?++ @caller_identity = credentials.presence+ end+def idempotency_cache_key(key)- credential = request.headers['X-Spree-Api-Key'].presence ||- spree_current_user&.id ||- request.remote_ip# The resolved store partitions the namespace: a staff JWT spans# stores, and replaying one store's cached response for a request# aimed at another would cross store boundaries. The resolved# store — not the raw header — so a header naming the default store# and no header at all land in the same partition, as they resolve# to the same store.- "spree:idempotency:#{Digest::SHA256.hexdigest("#{credential}\0#{current_store&.id}\0#{key}")}"+ digest = Digest::SHA256.hexdigest([*caller_identity.flatten, current_store&.id, key].join("\0"))+ "spree:idempotency:#{digest}"enddef request_fingerprintdiff --git a/spree/api/spec/controllers/concerns/spree/api/v3/idempotent_spec.rb b/spree/api/spec/controllers/concerns/spree/api/v3/idempotent_spec.rbindex 63a4b62a86..c155bfe5e4 100644--- a/spree/api/spec/controllers/concerns/spree/api/v3/idempotent_spec.rb+++ b/spree/api/spec/controllers/concerns/spree/api/v3/idempotent_spec.rb@@ -21,6 +21,8 @@ RSpec.describe Spree::Api::V3::Idempotent, type: :controller dodescribe 'idempotency' dolet(:idempotency_key) { SecureRandom.uuid }+ before { request.headers['Authorization'] = "Bearer #{jwt_token}" }+it 'processes normally without Idempotency-Key header' doexpect { post :create }.to change(Spree::Cart, :count).by(1)expect(response).to have_http_status(:created)@@ -59,14 +61,13 @@ RSpec.describe Spree::Api::V3::Idempotent, type: :controller doexpect { post :create }.to change(Spree::Cart, :count).by(1)end- it 'scopes cache by API key' do+ it 'scopes the cache to the caller, not to the shared publishable key' dorequest.headers['Idempotency-Key'] = idempotency_keypost :createfirst_response = json_response- other_api_key = create(:api_key, :publishable, store: store)- request.headers['X-Spree-Api-Key'] = other_api_key.token- request.headers['Idempotency-Key'] = idempotency_key+ other_customer = create(:user)+ request.headers['Authorization'] = "Bearer #{Spree::Api::V3::TestingSupport.generate_jwt(other_customer)}"expect { post :create }.to change(Spree::Cart, :count).by(1)expect(response.headers['Idempotent-Replayed']).to be_nil@@ -94,5 +95,50 @@ RSpec.describe Spree::Api::V3::Idempotent, type: :controller doexpect(response.headers['Idempotent-Replayed']).to be_nilendend++ describe 'callers that share a publishable key' do+ let(:idempotency_key) { 'checkout-1' }++ before { request.headers['Idempotency-Key'] = idempotency_key }++ it 'gives two guests their own cart rather than replaying the first one' do+ expect { post :create }.to change(Spree::Cart, :count).by(1)+ expect(response).to have_http_status(:created)+ first_response = json_response++ expect { post :create }.to change(Spree::Cart, :count).by(1)+ expect(response).to have_http_status(:created)+ expect(response.headers['Idempotent-Replayed']).to be_nil+ expect(json_response['id']).not_to eq(first_response['id'])+ expect(json_response['token']).not_to eq(first_response['token'])+ end++ it 'replays for a guest that holds the cart token' do+ cart = create(:cart, store: store)+ request.headers['x-spree-token'] = cart.token++ patch :update, params: { id: cart.prefixed_id, email: '[email protected]' }+ expect(response).to have_http_status(:ok)++ patch :update, params: { id: cart.prefixed_id, email: '[email protected]' }+ expect(response).to have_http_status(:ok)+ expect(response.headers['Idempotent-Replayed']).to eq('true')+ end++ it 'does not replay once the cart token that authorized the write is gone' do+ cart = create(:cart, store: store)+ request.headers['Authorization'] = "Bearer #{jwt_token}"+ request.headers['x-spree-token'] = cart.token++ patch :update, params: { id: cart.prefixed_id, email: '[email protected]' }+ expect(response).to have_http_status(:ok)++ request.headers['x-spree-token'] = nil+ patch :update, params: { id: cart.prefixed_id, email: '[email protected]' }++ expect(response.headers['Idempotent-Replayed']).to be_nil+ expect(response).not_to have_http_status(:ok)+ end+ endendend