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.

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.rb
index 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::API
include 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 Spree
with: RATE_LIMIT_RESPONSE
def 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.store
event = 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 Spree
private
# 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.rb
index 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 Spree
module Webhooks
class PaymentsController < ActionController::API
include 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 = 401
result = 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.rb
index 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::API
include 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 Spree
with: RATE_LIMIT_RESPONSE
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
return 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.rb
index 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 d
let(: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' do
before do
allow_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 d
end
end
- 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' do
let(: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)
end
end
diff --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.rb
new file mode 100644
index 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
+end
diff --git a/spree/core/app/jobs/spree/payments/handle_webhook_job.rb b/spree/core/app/jobs/spree/payments/handle_webhook_job.rb
index 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 Spree
def perform(payment_method_id:, action:, payment_session_id:)
payment_method = Spree::PaymentMethod.find(payment_method_id)
+ Spree::Current.store = payment_method.store
payment_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.rb
index 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 Spree
seller = Spree::Seller.find_by(id: seller_id)
return if seller.nil? || !seller.payouts_enabled?
+ Spree::Current.store = seller.store
provider = seller.store.payout_provider_instance
# Earnings only — see the scope. A reversal is retryable the same way
diff --git a/spree/core/spec/jobs/spree/payments/handle_webhook_job_spec.rb b/spree/core/spec/jobs/spree/payments/handle_webhook_job_spec.rb
index 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 do
payment_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
+ end
end
describe 'queue' do
diff --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.rb
index 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 do
expect(transfer.reload).to be_pending
end
+ 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' do
first = 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.rb
index 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 do
expect(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' do
body = { description: 'tracker.updated', result: {} }.to_json