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
Fix: Resolve provider webhooks in the store that owns the payment method or integration (#14718)
Damian Legawiec599d0f17d96f
diff --git a/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rb b/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rbindex 755c385e7f..d02d0c8f86 100644--- a/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rb@@ -15,7 +15,6 @@ module Spree# sender's timeout.class FulfillmentsController < ActionController::APIinclude ActionController::RateLimiting- include Spree::Core::ControllerHelpers::Store# Must render — instance_exec'd in a before_action, where only# render/redirect halts the chain.@@ -31,12 +30,17 @@ module Spreewith: RATE_LIMIT_RESPONSEdef create- integration = current_store.integrations.active.find_by_prefix_id!(params[:integration_id])+ # By id alone: providers call back without an API key or store+ # header, so the request cannot name the store — the record does.+ # The signature check below, against the record's own secret, is+ # what authenticates the request.+ integration = Spree::Integration.active.find_by_prefix_id!(params[:integration_id])+ Spree::Current.store = integration.storeevent = integration.parse_webhook_event(request.raw_post, request.headers)return head :ok if event.nil?- delivery = find_delivery(event[:tracking_code])+ delivery = find_delivery(integration.store, event[:tracking_code])return head :ok if delivery.nil?Spree.delivery_update_tracking_workflow.call(@@ -57,7 +61,7 @@ module Spreeprivate# Scoped to the store the verified integration belongs to — a- # tracking code can never address another tenant's parcel — and to+ # tracking code can never address another store's parcel — and to# consignments whose parcel was not canceled, so a recycled code# cannot reopen an old one. The newest wins when a code was reused.# Carriers reuse tracking numbers across years, so a code can match@@ -67,14 +71,14 @@ module Spree# database. The newest survivor wins.CANDIDATE_LIMIT = 20- def find_delivery(tracking_code)+ def find_delivery(store, tracking_code)return if tracking_code.blank?# Paged rather than capped: a tracking number reused across# canceled owners would otherwise fill the window and hide the# live delivery behind them, and the webhook would be# acknowledged without applying the carrier's update.- current_store.deliveries.+ store.deliveries.where(tracking_number: tracking_code).order(created_at: :desc, id: :desc).includes(:owner).diff --git a/spree/api/app/controllers/spree/api/v3/webhooks/payments_controller.rb b/spree/api/app/controllers/spree/api/v3/webhooks/payments_controller.rbindex 993b3abdc8..b414de289d 100644--- a/spree/api/app/controllers/spree/api/v3/webhooks/payments_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/webhooks/payments_controller.rb@@ -4,7 +4,6 @@ module Spreemodule Webhooksclass PaymentsController < ActionController::APIinclude ActionController::RateLimiting- include Spree::Core::ControllerHelpers::Store# Must render — instance_exec'd in a before_action, where only# render/redirect halts the chain.@@ -24,7 +23,12 @@ module Spree# Verifies the webhook signature synchronously (returns 401 if invalid),# then enqueues async processing and returns 200 immediately.def create- payment_method = current_store.payment_methods.find_by_prefix_id!(params[:payment_method_id])+ # By id alone: providers call back without an API key or store+ # header, so the request cannot name the store — the record does.+ # The signature check below, against the record's own secret, is+ # what authenticates the request.+ payment_method = Spree::PaymentMethod.find_by_prefix_id!(params[:payment_method_id])+ Spree::Current.store = payment_method.store# Signature verification must be synchronous — invalid = 401result = payment_method.parse_webhook_event(request.raw_post, request.headers)diff --git a/spree/api/app/controllers/spree/api/v3/webhooks/payouts_controller.rb b/spree/api/app/controllers/spree/api/v3/webhooks/payouts_controller.rbindex 48e46a6e12..b593cbbe06 100644--- a/spree/api/app/controllers/spree/api/v3/webhooks/payouts_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/webhooks/payouts_controller.rb@@ -19,7 +19,6 @@ module Spree# database writes, well inside any sender's timeout.class PayoutsController < ActionController::APIinclude ActionController::RateLimiting- include Spree::Core::ControllerHelpers::Store# Must render — instance_exec'd in a before_action, where only# render/redirect halts the chain.@@ -35,7 +34,12 @@ module Spreewith: RATE_LIMIT_RESPONSEdef create- payment_method = current_store.payment_methods.find_by_prefix_id!(params[:payment_method_id])+ # By id alone: providers call back without an API key or store+ # header, so the request cannot name the store — the record does.+ # The signature check below, against the record's own secret, is+ # what authenticates the request.+ payment_method = Spree::PaymentMethod.find_by_prefix_id!(params[:payment_method_id])+ Spree::Current.store = payment_method.storereturn head :not_found unless payment_method.respond_to?(:handle_payout_webhook)payment_method.handle_payout_webhook(request.raw_post, request.headers)diff --git a/spree/api/spec/controllers/spree/api/v3/webhooks/payments_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/webhooks/payments_controller_spec.rbindex 93d3d38f8f..fdc1899e31 100644--- a/spree/api/spec/controllers/spree/api/v3/webhooks/payments_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/webhooks/payments_controller_spec.rb@@ -7,19 +7,6 @@ RSpec.describe Spree::Api::V3::Webhooks::PaymentsController, type: :controller dlet(:payment_method) { create(:bogus_payment_method) }describe 'POST #create' do- context 'when resolving the current store' do- before do- allow_any_instance_of(Spree::PaymentMethod).to receive(:parse_webhook_event).and_return(nil)- request.host = store.url- end-- it 'sets current_store from the request' do- post :create, params: { payment_method_id: payment_method.prefixed_id }-- expect(controller.current_store).to eq(store)- end- end-context 'when webhook event is unsupported' dobefore doallow_any_instance_of(Spree::PaymentMethod).to receive(:parse_webhook_event).and_return(nil)@@ -53,14 +40,45 @@ RSpec.describe Spree::Api::V3::Webhooks::PaymentsController, type: :controller dendend- context 'when payment method belongs to a different store' do+ # Providers call back without an API key or store header, so the request+ # host names the default store — the payment method decides the store.+ context 'when the payment method belongs to another store' dolet(:other_store) { create(:store) }let(:other_payment_method) { create(:bogus_payment_method, store: other_store) }+ let(:order) { create(:order_with_line_items, store: other_store) }+ let(:payment_session) { create(:bogus_payment_session, order: order, payment_method: other_payment_method) }+ let(:handled_in) { [] }- it 'returns not found' do- post :create, params: { payment_method_id: other_payment_method.prefixed_id }+ before do+ request.host = store.url+ allow_any_instance_of(Spree::PaymentMethod).to receive(:parse_webhook_event) do+ handled_in << Spree::Current.store+ { action: :captured, payment_session: payment_session, metadata: {} }+ end+ end- expect(response).to have_http_status(:not_found)+ it 'processes the webhook in that store' do+ expect {+ post :create, params: { payment_method_id: other_payment_method.prefixed_id }+ }.to have_enqueued_job(Spree::Payments::HandleWebhookJob).with(+ payment_method_id: other_payment_method.id,+ action: 'captured',+ payment_session_id: payment_session.id+ )++ expect(response).to have_http_status(:ok)+ expect(handled_in).to eq([other_store])+ end++ it 'returns unauthorized when the signature does not verify' do+ allow_any_instance_of(Spree::PaymentMethod).to receive(:parse_webhook_event)+ .and_raise(Spree::PaymentMethod::WebhookSignatureError)++ expect {+ post :create, params: { payment_method_id: other_payment_method.prefixed_id }+ }.not_to have_enqueued_job(Spree::Payments::HandleWebhookJob)++ expect(response).to have_http_status(:unauthorized)endenddiff --git a/spree/api/spec/controllers/spree/api/v3/webhooks/payouts_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/webhooks/payouts_controller_spec.rbnew file mode 100644index 0000000000..0e352520bd--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/webhooks/payouts_controller_spec.rb@@ -0,0 +1,59 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Webhooks::PayoutsController, type: :controller do+ render_views++ let(:store) { @default_store }+ let(:other_store) { create(:store) }+ let(:payment_method) { create(:bogus_payment_method, store: other_store) }+ let(:handled_in) { [] }++ # Providers call back without an API key or store header, so the request+ # host names the default store — the payment method decides the store.+ before do+ request.host = store.url+ allow_any_instance_of(Spree::Gateway::Bogus).to receive(:handle_payout_webhook) { handled_in << Spree::Current.store }+ end++ describe 'POST #create' do+ it "handles the event in the payment method's store" do+ post :create, params: { payment_method_id: payment_method.prefixed_id }++ expect(response).to have_http_status(:ok)+ expect(handled_in).to eq([other_store])+ end++ it 'returns unauthorized when the signature does not verify' do+ allow_any_instance_of(Spree::Gateway::Bogus).to receive(:handle_payout_webhook)+ .and_raise(Spree::PaymentMethod::WebhookSignatureError)++ post :create, params: { payment_method_id: payment_method.prefixed_id }++ expect(response).to have_http_status(:unauthorized)+ end++ it 'returns not found for an unknown payment method' do+ post :create, params: { payment_method_id: 'pm_nonexistent' }++ expect(response).to have_http_status(:not_found)+ expect(handled_in).to be_empty+ end++ it 'returns not found for a payment method without payout events' do+ check_payment_method = create(:check_payment_method, store: other_store)++ post :create, params: { payment_method_id: check_payment_method.prefixed_id }++ expect(response).to have_http_status(:not_found)+ end++ it 'returns a server error when handling fails, so the provider retries' do+ allow_any_instance_of(Spree::Gateway::Bogus).to receive(:handle_payout_webhook).and_raise(StandardError, 'unexpected')+ expect(Rails.error).to receive(:report).with(kind_of(StandardError), hash_including(source: 'spree.webhooks.payouts'))++ post :create, params: { payment_method_id: payment_method.prefixed_id }++ expect(response).to have_http_status(:internal_server_error)+ end+ end+enddiff --git a/spree/core/app/jobs/spree/payments/handle_webhook_job.rb b/spree/core/app/jobs/spree/payments/handle_webhook_job.rbindex fecf223243..2bf9dd49be 100644--- a/spree/core/app/jobs/spree/payments/handle_webhook_job.rb+++ b/spree/core/app/jobs/spree/payments/handle_webhook_job.rb@@ -9,6 +9,7 @@ module Spreedef perform(payment_method_id:, action:, payment_session_id:)payment_method = Spree::PaymentMethod.find(payment_method_id)+ Spree::Current.store = payment_method.storepayment_session = Spree::PaymentSession.find(payment_session_id)Spree.payments_handle_webhook_workflow.call(diff --git a/spree/core/app/jobs/spree/seller_transfers/execute_pending_job.rb b/spree/core/app/jobs/spree/seller_transfers/execute_pending_job.rbindex 696d53a25c..e0592fa403 100644--- a/spree/core/app/jobs/spree/seller_transfers/execute_pending_job.rb+++ b/spree/core/app/jobs/spree/seller_transfers/execute_pending_job.rb@@ -26,6 +26,7 @@ module Spreeseller = Spree::Seller.find_by(id: seller_id)return if seller.nil? || !seller.payouts_enabled?+ Spree::Current.store = seller.storeprovider = seller.store.payout_provider_instance# Earnings only — see the scope. A reversal is retryable the same waydiff --git a/spree/core/spec/jobs/spree/payments/handle_webhook_job_spec.rb b/spree/core/spec/jobs/spree/payments/handle_webhook_job_spec.rbindex 96a7f52a1e..5696c7238b 100644--- a/spree/core/spec/jobs/spree/payments/handle_webhook_job_spec.rb+++ b/spree/core/spec/jobs/spree/payments/handle_webhook_job_spec.rb@@ -40,6 +40,24 @@ RSpec.describe Spree::Payments::HandleWebhookJob, type: :job dopayment_session_id: payment_session.id)end+ context 'when the payment method belongs to another store' do+ let(:other_store) { create(:store) }+ let(:payment_method) { create(:bogus_payment_method, store: other_store) }+ let(:order) { create(:order_with_line_items, store: other_store) }++ it 'handles the webhook in that store' do+ handled_in = nil+ allow_any_instance_of(Spree::Payments::HandleWebhook).to receive(:call) { handled_in = Spree::Current.store }++ described_class.perform_now(+ payment_method_id: payment_method.id,+ action: 'captured',+ payment_session_id: payment_session.id+ )++ expect(handled_in).to eq(other_store)+ end+ endenddescribe 'queue' dodiff --git a/spree/core/spec/jobs/spree/seller_transfers/execute_pending_job_spec.rb b/spree/core/spec/jobs/spree/seller_transfers/execute_pending_job_spec.rbindex 7b312957a2..02339adb6a 100644--- a/spree/core/spec/jobs/spree/seller_transfers/execute_pending_job_spec.rb+++ b/spree/core/spec/jobs/spree/seller_transfers/execute_pending_job_spec.rb@@ -32,6 +32,19 @@ RSpec.describe Spree::SellerTransfers::ExecutePendingJob doexpect(transfer.reload).to be_pendingend+ it "sends the earnings in the seller's own store" do+ other_store = create(:store)+ seller = create(:seller, :approved, store: other_store, payouts_enabled_at: Time.current)+ create(:seller_transfer, seller: seller, amount: 40, status: 'pending',+ order: create(:order, store: other_store, seller: seller))+ sent_in = []+ allow_any_instance_of(Spree::PayoutProvider::System).to receive(:transfer!) { sent_in << Spree::Current.store }++ described_class.perform_now(seller.id)++ expect(sent_in).to eq([other_store])+ end+# One seller's stuck earning must not stop the rest.it 'carries on past an earning the provider refuses' dofirst = pending_earning(40)diff --git a/spree/providers/easypost/spec/requests/spree_easypost/fulfillment_webhooks_spec.rb b/spree/providers/easypost/spec/requests/spree_easypost/fulfillment_webhooks_spec.rbindex a2f16a0d59..d8c9ea53f7 100644--- a/spree/providers/easypost/spec/requests/spree_easypost/fulfillment_webhooks_spec.rb+++ b/spree/providers/easypost/spec/requests/spree_easypost/fulfillment_webhooks_spec.rb@@ -135,6 +135,35 @@ RSpec.describe 'EasyPost fulfillment webhooks', type: :request doexpect(other_fulfillment.reload.primary_delivery.status).to eq('pending')end+ # Carriers call back without an API key or store header, so the request+ # host names the default store — the integration decides the store.+ context 'when the integration belongs to another store' do+ let(:store) { create(:store, code: "other-#{SecureRandom.hex(4)}") }++ before { host! @default_store.url }++ it "records the carrier update in the integration's store" do+ recorded_in = []+ allow_any_instance_of(Spree::Deliveries::UpdateTracking).to receive(:call).and_wrap_original do |original, **arguments|+ recorded_in << Spree::Current.store+ original.call(**arguments)+ end++ post_tracker(status: 'out_for_delivery')++ expect(response).to have_http_status(:ok)+ expect(delivery.reload.status).to eq('out_for_delivery')+ expect(recorded_in).to eq([store])+ end++ it 'refuses a wrong signature' do+ post_tracker(status: 'delivered', secret: 'not-the-secret')++ expect(response).to have_http_status(:unauthorized)+ expect(delivery.reload.status).to eq('pending')+ end+ end+it 'answers 404 for an unknown integration' dobody = { description: 'tracker.updated', result: {} }.to_json