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.

Guard every unit of work that declares a store (#14439)

Damian Legawiec0609d6ec0927
diff --git a/docs/plans/6.0-store-context-and-first-run-setup.md b/docs/plans/6.0-store-context-and-first-run-setup.md
index 00c2e8d67f..d59e70c2e5 100644
--- a/docs/plans/6.0-store-context-and-first-run-setup.md
+++ b/docs/plans/6.0-store-context-and-first-run-setup.md
@@ -111,7 +111,7 @@ Open-core isolation rests on the controller discipline — every lookup through
- **Cache-key audit** — a static spec (`spec/lib/spree/store_scoped_cache_keys_spec.rb`) walks every `Rails.cache` call site in core and api: each must visibly carry the store (or a record `cache_key_with_version`) in its key, or hold a reviewed allowlist entry justifying why the data is global. A new unscoped call site fails the suite with instructions. The audit also fixed a real one: idempotency replay caching was keyed per credential but not per store, so a staff JWT reusing an `Idempotency-Key` across stores replayed the first store's response — the key now partitions by the resolved store.
- **List-position audit** — a store-owned model with an unscoped `acts_as_list` numbers positions across the whole table, shifting every store's rows on create/reorder; a spec (`spec/lib/spree/store_scoped_list_positions_spec.rb`) fails on any such model. PaymentMethod shipped that bug — fixed with `scope: :store_id` plus a per-store renumber in `spree:upgrade:populate_single_store_associations` for upgraded data.
-**Honest coverage, and the next increment.** The guard exempts id/FK filters (loads from rows already reached through a scoped association) and `SELECT 1 AS one` existence checks (dominated by uniqueness validations on deliberately global columns, like document numbers) — so its net is secondary-key lookups and unscoped scans, with attacker-controlled raw ids covered structurally by `for_store(current_store)` in resource controllers. It also watches only the v3 controller surface: jobs, the webhook controllers (which inherit `ActionController::API` directly), and model callbacks run unguarded today. The right extension is opening the window where `Spree::Current.store` is assigned rather than per-entry-point registration — deferred deliberately, since it re-triages every job and callback in the suite. First harvest of the tripwires beyond the guard's own findings: the pickup-location fallback listing every store's counters, the stock-location default flag demoting across stores, variant stock items propagating into every store's warehouses, and data-feed name uniqueness blocking reuse across stores.
+**Honest coverage, and the next increment.** The guard exempts id/FK filters (loads from rows already reached through a scoped association) and `SELECT 1 AS one` existence checks (dominated by uniqueness validations on deliberately global columns, like document numbers) — so its net is secondary-key lookups and unscoped scans, with attacker-controlled raw ids covered structurally by `for_store(current_store)` in resource controllers. **Coverage follows the store context, not the entry point (2026-08-14).** `Spree::Current#store=` arms the guard for the rest of that unit of work, so anything declaring a store — jobs, the webhook controllers (which inherit `ActionController::API` directly and never saw the v3 `around_action`), console scripts, entry points not yet written — is watched with no registration. The latch lives on `Spree::Current` because `CurrentAttributes` is what Rails resets per request *and* per job; a `RequestStore` flag would leak across jobs on a reused worker thread. Deliberately asymmetric: work that never declares a store stays unguarded, since reading the default store through `Spree::Current.store`'s fallback is not a scoping claim worth checking — guarding all 35 jobs unconditionally would produce noise rather than signal. The v3 `around_action` stays for the window before store resolution. First harvest of the tripwires beyond the guard's own findings: the pickup-location fallback listing every store's counters, the stock-location default flag demoting across stores, variant stock items propagating into every store's warehouses, and data-feed name uniqueness blocking reuse across stores.
## Constraints on Current Work
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 40806af2be..557dea2d28 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -766,10 +766,13 @@ test failure, not a review comment — wrap genuinely global lookups in
existence checks are exempt (they are dominated by loads from already-scoped
rows and uniqueness validations) — exemption is NOT proof of scoping, so a
lookup fed a request-derived id still requires `current_store` fetching even
-though the guard stays silent on it; and only the v3 controller surface is
-watched — jobs, webhooks and callbacks are a future extension, ideally keyed
-off `Spree::Current.store` assignment rather than per-entry-point
-registration. A new `Rails.cache` call without a store-scoped key fails the
+though the guard stays silent on it. Coverage follows the store context
+rather than the entry point (extended 2026-08-14): declaring a store through
+`Spree::Current#store=` arms the guard for that unit of work, so jobs,
+webhook controllers and console scripts are watched without registering
+each one, while work that never declares a store stays unguarded — reading
+the default store through the fallback is not a scoping claim worth
+checking. A new `Rails.cache` call without a store-scoped key fails the
core suite until scoped or reviewed onto the allowlist, and a store-owned
model with an unscoped `acts_as_list` fails it too (positions would bleed
across stores — the bug PaymentMethod shipped with, fixed alongside three
diff --git a/spree/core/app/models/spree/current.rb b/spree/core/app/models/spree/current.rb
index 8dc8f1d8bd..61f768fd75 100644
--- a/spree/core/app/models/spree/current.rb
+++ b/spree/core/app/models/spree/current.rb
@@ -5,6 +5,10 @@ module Spree
# Fallback chains ensure sensible defaults when attributes are not explicitly set.
class Current < ::ActiveSupport::CurrentAttributes
attribute :store, :channel, :market, :currency, :locale, :content_locale, :tax_country, :price_lists, :applicable_catalogs, :applicable_catalog_groups, :quantity_rules_resolvers, :standing_companies, :global_pricing_context, :provider_cache, :integrations
+ # Latch for the cross-store leak tripwire — see #store= below. Lives here
+ # so it clears exactly when the store context does, which Rails does per
+ # request and per job.
+ attribute :store_scope_guard_armed
# Scratch space for provider strategies to memoize a call across the
# request — part of the delivery rate provider contract (nothing in core
@@ -17,6 +21,17 @@ module Spree
super || (self.provider_cache = {})
end
+ # Declaring a store context arms the cross-store leak tripwire for the
+ # rest of this unit of work — a request, a job, a webhook — so the guard
+ # follows the context rather than a list of entry points
+ # (docs/plans/6.0-store-context-and-first-run-setup.md). Work that never
+ # declares a store is left alone: it reads the default store through the
+ # fallback below, which is not a scoping claim to check.
+ def store=(value)
+ Spree::StoreScopeGuard.arm! if value
+ super
+ end
+
# Returns the current store, falling back to the default store.
# @return [Spree::Store]
def store
diff --git a/spree/core/lib/spree/store_scope_guard.rb b/spree/core/lib/spree/store_scope_guard.rb
index 7814540e76..d37bd3dd20 100644
--- a/spree/core/lib/spree/store_scope_guard.rb
+++ b/spree/core/lib/spree/store_scope_guard.rb
@@ -72,6 +72,19 @@ module Spree
RequestStore.store[ACTIVE_KEY] = previous
end
+ # Opens the window for whatever declared a store context — a job, a
+ # webhook, a console script — and leaves it open until Spree::Current
+ # resets, which Rails does per request and per job. Called from
+ # `Spree::Current#store=`; work that never declares a store stays
+ # unguarded, since reading the default store through the fallback is
+ # not a scoping claim.
+ def arm!
+ return unless enabled?
+
+ install!
+ Spree::Current.store_scope_guard_armed = true
+ end
+
# Suppresses the guard for a deliberately store-less lookup.
def skip
previous = RequestStore.store[SKIP_KEY]
@@ -82,7 +95,9 @@ module Spree
end
def active?
- RequestStore.store[ACTIVE_KEY] && !RequestStore.store[SKIP_KEY]
+ return false if RequestStore.store[SKIP_KEY]
+
+ RequestStore.store[ACTIVE_KEY] || Spree::Current.store_scope_guard_armed.present?
end
# Forgets memoized environment/schema state (specs, migrations).
diff --git a/spree/core/spec/lib/spree/store_scope_guard_spec.rb b/spree/core/spec/lib/spree/store_scope_guard_spec.rb
index fbb1684ed9..fbbfd70004 100644
--- a/spree/core/spec/lib/spree/store_scope_guard_spec.rb
+++ b/spree/core/spec/lib/spree/store_scope_guard_spec.rb
@@ -85,6 +85,43 @@ RSpec.describe Spree::StoreScopeGuard do
end
end
+ # Declaring a store context arms the guard for the rest of the unit of
+ # work, so jobs, webhook controllers and console scripts are covered
+ # without registering each entry point.
+ describe 'arming through Spree::Current.store' do
+ before { Spree::Config.store_scope_guard = 'raise' }
+
+ after { Spree::Current.reset }
+
+ it 'guards work that declared a store, with no watch block' do
+ Spree::Current.store = @default_store
+
+ expect { Spree::Product.where(name: 'x').to_a }.
+ to raise_error(described_class::UnscopedQueryError, /spree_products/)
+ end
+
+ it 'leaves work that never declared a store alone' do
+ Spree::Current.reset
+
+ expect { Spree::Product.where(name: 'x').to_a }.not_to raise_error
+ end
+
+ it 'stops guarding once the context resets, as it does between jobs' do
+ Spree::Current.store = @default_store
+ Spree::Current.reset
+
+ expect { Spree::Product.where(name: 'x').to_a }.not_to raise_error
+ end
+
+ it 'still honors skip for deliberately global lookups' do
+ Spree::Current.store = @default_store
+
+ expect {
+ described_class.skip { Spree::Product.where(name: 'x').to_a }
+ }.not_to raise_error
+ end
+ end
+
describe 'log mode' do
before { Spree::Config.store_scope_guard = 'log' }