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.

Store isolation tripwires + six cross-store leak fixes (#14435)

Damian Legawiec55d17463bd52
diff --git a/CLAUDE.md b/CLAUDE.md
index 29e147091b..7acd340a8e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -26,7 +26,7 @@ Active plans (6.0 target, work pending):
- `6.0-fulfillment-and-delivery.md` — Shipment→Fulfillment, ShippingMethod→DeliveryMethod, drop ShippingCategory, FulfillmentProvider strategy, pickup (merchant StockLocation) + pickup_point (third-party PickupPointProvider). **Shipped to 6-0-dev (Waves 2+4+6):** renames + deprecated twins, providers (Manual/Digital/Pickup/PickupPoint), dual-emit events, store pickup discovery endpoints, admin delivery_methods/delivery_zones CRUD + dashboard settings pages, FulfillmentMailer; Wave 7 shipping→delivery data migration remains. Pickup work beyond shipped code deferred to 6.1 (2026-08-06): contract hardening (`new(delivery_method)` ctor, `find_nearby` zipcode/query) + how-to guide; `PickupPointProvider::Base` stays **undocumented in 6.0** (v6 docs cover only the delivery rate provider interface) — never add pickup-provider docs in 6.0 work. Delivery mechanics live on provider classes (`pickup_point` provider ships but stays unregistered until 6.1; `local_delivery` cut = shipping + postal-code zone); the string fulfillment-type registry was deleted by `6.0-delivery-profiles.md`. **Partial fulfillment (2026-08-10, resolved question 12):** shipping a subset is `Spree::Fulfillments::Fulfill` (optional per-line-item `items:` + `tracking:` + `notify_customer:`; splits then fulfills in one transaction) — never a state-machine event, since split-then-ship in an `after_transition` is what service-workflows prohibits. **Side effects left the machine (2026-08-10, question 13):** `after_cancel`/`after_resume` are gone as transition callbacks — restock + carrier stand-down live in `Fulfillments::Cancel`/`::Resume` as inline steps (provider call is an `external_step`; `notify_provider: false` lets `Orders::Cancel` delegate and batch carrier I/O after its own transaction), `after_cancel`/`after_resume` are deprecated shells and the only trace left on the model — never add public model methods for workflows to call. **Status model (2026-08-11, question 14): the machine is REMOVED.** `status` = plain `HasStatus` `unfulfilled → fulfilled → delivered | canceled` (`pending`/`ready`/`ready_for_pickup` collapse — payment/stock gating is a `Fulfillments::Fulfill` validate guard, pickup renders modality-aware labels); `delivered` = confirmed receipt (`Fulfillments::MarkDelivered`, `delivered_at`, `fulfillment.delivered`) — the returns window + EU withdrawal anchor; carrier truth is the separate `tracking_status` axis (data, never a machine) written by `Fulfillments::UpdateTracking`, fed by EasyPost tracker webhooks (opt-in trackers for hand-entered numbers). Rollup domain `backorder | canceled | partial | unfulfilled | fulfilled | delivered`. **Phase 7 shipped 2026-08-11** (core + API + dashboard + EasyPost tracker webhook + `spree:migrate_fulfillment_statuses`); **label leads, fulfilled follows (2026-08-12):** `Fulfillments::PurchaseLabel` = explicit pre-ship label buy (loud failure, no email); `Fulfill` buys label BEFORE marking fulfilled (email always carries tracking; post-split failure keeps the split, never rolls it back); providers declare `generates_labels?` + idempotent `create_fulfillment`. **One tracking number per fulfillment (2026-08-11, question 15):** diverging parcels are split fulfillments; a `spree_fulfillment_trackings` model is 6.1 work and must absorb the entire carrier axis (per-row status/`delivered_at`, webhook matching by row) — never split the axis across fulfillment and tracking rows
- `6.0-returns-exchanges-claims.md` — First-class Return, Exchange, Claim models replacing ReturnAuthorization/Reimbursement chain. **COMPLETE (2026-08-05):** all three entities (+ permanent `ReturnLineItem`/`ExchangeLineItem`/`ClaimLineItem` line items), `Spree::HasStatus`, all fifteen workflows (each with a leading `validate` hook), `Refund#originator`, admin + store v3 APIs (transitions as PATCH member actions; no destroy — cancel instead), dashboard pages. Legacy chain **removed**: ReturnAuthorization/CustomerReturn/Reimbursement/ReimbursementType/legacy ReturnItem + eligibility validators + ReturnsCalculator classes all deleted, but their **tables deliberately survive to 6.1** as the data migration's source and rollback path. `spree:upgrade:migrate_returns` (`Spree::ReturnsMigrator`, defined in the rake file like its sibling upgrade tasks; anonymous-AR readers) is in the 5.6→6.0 manifest after the adjustments step; it needs no cursor because the preserved `number` is uniquely indexed on the new tables, so "what's left" is a `where.not(number: ...)` query and an interrupted run resumes for free. `ReturnAuthorizationReason`→`ReturnReason` (alias one release) + new `ClaimReason`; `Metafields` on all three. Capability replacements: `Spree::ReturnMailer#refunded_email` on `return.refunded` (replaces the reimbursement email), `Order#outstanding_balance` drops the reimbursement term (refunds already net out of `payment_total`), `Return#refunded_total` counts store credits too, `StoreCreditCategory.default_refund_category` (alias kept). **Reasons** ship admin-only CRUD (`/api/v3/admin/{return,claim,refund}_reasons`, `settings` scope) + a combined Settings → Reasons dashboard page + reason pickers on the create dialogs; `mutable` is never client-writable and the immutability guard lives on `Spree::NamedType` (`can_be_deleted?` + rename/destroy guards) because secret API keys authorize by scope and never consult CanCanCan. **No state machines (2026-08-02):** plain `status` string + inclusion validation; all fifteen transitions are workflows (`Returns::Receive`, `Exchanges::Fulfill`, `Claims::Resolve`, …) with `validate` hooks for return-eligibility policy and refunds as `external_step`. Nothing happens in a model or transition callback. Statuses live in a `class_attribute` via the core `Spree::HasStatus` concern (`has_status` + additive `add_status(value, after:)`, generating predicates and scopes) — extensible by design, additive only, and no transition graph (that would be a state machine again). **Return eligibility is a hook, not a policy engine (2026-08-03):** no window/restocking-fee/final-sale flag in core — a `validate` handler decides, enforcing for customers while letting staff override (it reads `created_by`), and region-varying policy reads `order.market`. Medusa/Saleor/Vendure ship no policy at all; Shopify's engine has no API. A `ReturnPolicy` model can arrive later behind the same hook.
- `6.0-platform-auth.md` — Drop Devise, own auth stack, User→Customer/Staff rename (RefreshToken shipped in 5.4)
-- `6.0-store-context-and-first-run-setup.md` — Store context becomes credential-derived (design finalized 2026-08-13): publishable key selects the store on the Store API, Admin API honors `X-Spree-Store-Id` with membership checked against the *requested* store (header-less JWT → default store + deprecation, required 6.1), hostname-based store resolution retired (`FindDefault`'s `url:` is dead; never read `request.host` to pick a store). First-run setup replaces the `[email protected]`/`spree123` dummy seed: seed creates an admin only when `ADMIN_EMAIL`/`ADMIN_PASSWORD` are explicitly set; otherwise a one-time setup-token flow (dashboard `/setup` + unauthenticated `auth/setup` endpoints; `has_secure_token :setup_token` on Store — plaintext like invitation tokens, printed by installer, `spree:setup:token` reprints, cleared on completion — required in EVERY environment; `Spree::Stores::DashboardUrl` is the single resolver for the dashboard origin — used by the setup link, invitation emails and the SSO callback — resolving `dashboard_url` pref/`SPREE_DASHBOARD_URL` → deprecated `admin_url` → this app's own `/dashboard` mount when `spree_dashboard` serves a build → dev Vite → store URL; never a hardcoded port, and the CLI rebuilds the link host-side since the seed runs before any dashboard is up). **App configuration reads ENV:** `RuntimeConfiguration.preference` accepts `env:` (precedence: explicit value → env var → coded default), so deployment settings are configurable without touching Ruby; `dashboard_url` is env-backed via `SPREE_DASHBOARD_URL` and `admin_url` is deprecated in its favour. Applies to `Spree::Config` only — per-store behavior belongs in Store preferences. The setup flow creates the first admin and adopts/renames the seeded store; no general store CRUD in the OSS Admin API. **Constraints now:** never assume `current_store == Store.default` in Admin API code; store-touching cache keys include the store id by construction; new scripts pass `ADMIN_EMAIL`/`ADMIN_PASSWORD` explicitly.
+- `6.0-store-context-and-first-run-setup.md` — Store context becomes credential-derived (design finalized 2026-08-13): publishable key selects the store on the Store API, Admin API honors `X-Spree-Store-Id` with membership checked against the *requested* store (header-less JWT → default store + deprecation, required 6.1), hostname-based store resolution retired (`FindDefault`'s `url:` is dead; never read `request.host` to pick a store). First-run setup replaces the `[email protected]`/`spree123` dummy seed: seed creates an admin only when `ADMIN_EMAIL`/`ADMIN_PASSWORD` are explicitly set; otherwise a one-time setup-token flow (dashboard `/setup` + unauthenticated `auth/setup` endpoints; `has_secure_token :setup_token` on Store — plaintext like invitation tokens, printed by installer, `spree:setup:token` reprints, cleared on completion — required in EVERY environment; `Spree::Stores::DashboardUrl` is the single resolver for the dashboard origin — used by the setup link, invitation emails and the SSO callback — resolving `dashboard_url` pref/`SPREE_DASHBOARD_URL` → deprecated `admin_url` → this app's own `/dashboard` mount when `spree_dashboard` serves a build → dev Vite → store URL; never a hardcoded port, and the CLI rebuilds the link host-side since the seed runs before any dashboard is up). **App configuration reads ENV:** `RuntimeConfiguration.preference` accepts `env:` (precedence: explicit value → env var → coded default), so deployment settings are configurable without touching Ruby; `dashboard_url` is env-backed via `SPREE_DASHBOARD_URL` and `admin_url` is deprecated in its favour. Applies to `Spree::Config` only — per-store behavior belongs in Store preferences. The setup flow creates the first admin and adopts/renames the seeded store; no general store CRUD in the OSS Admin API. **Constraints now:** never assume `current_store == Store.default` in Admin API code; store-touching cache keys include the store id by construction (enforced by the cache-key audit spec in core — global data needs a reviewed allowlist entry); new scripts pass `ADMIN_EMAIL`/`ADMIN_PASSWORD` explicitly. **Isolation tripwires (2026-08-13):** `Spree::StoreScopeGuard` wraps every v3 API request in dev/test and flags store-less secondary-key lookups and unscoped scans on store-owned tables (schema-derived set; id/FK filters and `SELECT 1 AS one` are exempt as loads-from-scoped-rows and uniqueness validations — exemption is NOT proof of scoping, request-derived ids still need `current_store` fetching; `log` default, `raise` in this repo's API suite, `SPREE_STORE_SCOPE_GUARD` to change) — wrap deliberately global lookups in `Spree::StoreScopeGuard.skip { }`. A store-owned model with an unscoped `acts_as_list` also fails the core suite (positions bleed across stores).
- `6.0-tax-provider.md` — Per-Market TaxProvider, replaces TaxRate.adjust + Calculator; TaxRate gets direct country/state FKs (tax decoupled from Zone; Zone model dropped in 6.0 via `6.0-delivery-zones.md`); reference provider: Avalara (decisions.md 2026-07-30)
- `6.0-delivery-rate-provider.md` — Per-DeliveryMethod DeliveryRateProvider wrapping Stock::Estimator (calculators stay — 2026-07-27 reversal), `store_id` on ShippingMethod; monorepo ships one reference multi-carrier provider (**EasyPost** — decisions.md 2026-08-06 reversal: BYOCA fit for larger merchants + only maintained official Ruby SDK; Shippo's ruby gem dead since 2020); method rows stay regional (no cross-market method entity). **Dynamic carrier rates (2026-08-09):** a carrier method is the carrier connection — `estimates(package)` returns one Estimate per service, each becoming its own named DeliveryRate (unique (fulfillment, method) rate index dropped; `DeliveryRate#name` falls back to the method name); `Spree::DeliveryMethodService` rows narrow/rename/mark-up services (no rows = all, method-level markup columns as default); selection + EasyPost label buy key off the selected rate's carrier/service; seeds/sample data reshaped Shopify-style (Domestic + International zones with basic methods)
- `6.0-delivery-zones.md` — Zone → DeliveryZone with postal-code-range/prefix members (country-scoped); owns the full ~183-reference Zone consumer inventory; `Spree::Zone` dropped entirely by end of 6.0 (2026-07-27 — 6.0 is the breaking-change window)
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 c98718edfa..eb3cd73336 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
@@ -83,11 +83,22 @@ A `StoreContext` concern in the v3 Admin base controller resolves `current_store
2. **Phase 2 — first-run setup.** `setup_token` column on `spree_stores`, seed changes, the two `auth/setup` endpoints, the `/setup` dashboard route, CLI/template/scripts updates, `spree:setup:token` rake task. **Shipped 2026-08-13** (`has_secure_token :setup_token` on Store; `Seeds::AdminUser` env-only; `spree:cli:create_admin` made idempotent; `spree init` prompts for credentials, `spree dev` reads the remembered email; create-spree-app no longer prints dummy credentials; worktree template passes explicit credentials).
3. **6.1 cleanup.** Header becomes required for JWT Admin API requests; `FindDefault`'s ignored `url:` parameter is dropped from the finder contract.
+### 6. Isolation tripwires (added 2026-08-13)
+
+Open-core isolation rests on the controller discipline — every lookup through a `current_store` association — because row-level enforcement is deliberately not a core feature. Two nets now sit under that discipline:
+
+- **`Spree::StoreScopeGuard`** — development/test only, wrapped around every v3 API request. A `SELECT` against a store-owned table (any `spree_*` table with a `store_id` column, derived from the schema — no registry) that carries no `store_id` predicate is reported with the SQL and call site. Modes via `SPREE_STORE_SCOPE_GUARD` / `Spree::Config[:store_scope_guard]`: `log` (default), `raise` (this repo's API suite), `off`. Deliberately global lookups (credential searches — the key selects the store) opt out with `Spree::StoreScopeGuard.skip { }`, which doubles as documentation. `watchable_environment?` is overridable so a multi-tenant enforcement layer can run the guard as a production log-mode canary; the schema-derived watched set means tables stamped with `store_id` later are watched with zero registration.
+- **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.
+
## Constraints on Current Work
- **Never assume `current_store == Spree::Store.default`** in Admin API controllers, serializers, or jobs — after Phase 1 the requested store can be any store the caller has a role on. The existing rule (every lookup through `current_store.<association>`) is what makes this safe; violations are now cross-store leaks, not just IDOR risks.
- **No new hostname-based store logic anywhere** — don't read `request.host`/`SERVER_NAME` to pick a store, don't add URL-matching to finders.
-- **Store-touching cache keys must include the store id** by construction (`cache_key_with_version` on the store, or an explicit store-id component), never a bare global key.
+- **Store-touching cache keys must include the store id** by construction (`cache_key_with_version` on the store, or an explicit store-id component), never a bare global key — enforced by the cache-key audit spec; genuinely global data gets a reviewed allowlist entry there, not an exemption in review.
+- **A deliberately store-less query in request handling wraps itself in `Spree::StoreScopeGuard.skip`** — an unscoped lookup on a store-owned table inside an API request otherwise fails the API suite.
- **New scripts and tooling must pass `ADMIN_EMAIL`/`ADMIN_PASSWORD` explicitly** instead of relying on the dummy defaults, which are removed at 6.0.
## Open Questions
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index c84f2a5deb..d00a526af0 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -38,6 +38,50 @@ changes only affect future numbers; and code saving a numbered record with
normally assigns one is `before_validation`. Plan:
`6.0-document-numbers.md`.
+## 2026-08-13: Isolation tripwires — the guard under the store-scoping discipline
+
+Open-core isolation is the controller discipline (every lookup through a
+`current_store` association); row-level enforcement is deliberately not a
+core feature. Two nets now sit under that discipline rather than trusting
+review alone.
+
+`Spree::StoreScopeGuard` wraps every v3 API request in development and test:
+a SELECT against a store-owned table (schema-derived — any `spree_*` table
+with a `store_id` column) carrying no `store_id` predicate is reported with
+the SQL and call site. `log` by default, `raise` in this repo's API suite,
+never active in production. Deliberately global lookups — the API-key
+searches, where the key selects the store — opt out with
+`StoreScopeGuard.skip`, which doubles as documentation of intent.
+`watchable_environment?` is overridable so a multi-tenant enforcement layer
+can run the guard as a production log-mode canary, and the schema-derived
+watched set means tables stamped with `store_id` later are watched with no
+registration.
+
+Cache keys get a static audit spec: every `Rails.cache` call site in core
+and api must visibly carry the store in its key or hold a reviewed allowlist
+entry saying why the data is global. Writing the audit surfaced a real bug —
+idempotency replay caching 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 requested store.
+
+Consequences: a store-less secondary-key lookup (slug, number, code, email,
+token) or unscoped scan on a store-owned table inside an API request is a
+test failure, not a review comment — wrap genuinely global lookups in
+`skip`. Honest limits: id/foreign-key filters and `SELECT 1 AS one`
+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
+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
+sibling leaks the tripwires surfaced: the pickup-location fallback, the
+stock-location default flag, variant stock-item propagation, and data-feed
+name uniqueness). Plan: `6.0-store-context-and-first-run-setup.md`.
+
## 2026-08-13: Store context is credential-derived — hostname resolution retired; first-run setup replaces the dummy admin
Every v3 API request resolved to `Spree::Store.default`: the configured finder
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/api_key_authentication.rb b/spree/api/app/controllers/concerns/spree/api/v3/api_key_authentication.rb
index d472770001..3e044ff2ca 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/api_key_authentication.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/api_key_authentication.rb
@@ -66,8 +66,9 @@ module Spree
def publishable_api_key
return @publishable_api_key if defined?(@publishable_api_key)
- @publishable_api_key =
+ @publishable_api_key = Spree::StoreScopeGuard.skip do
extract_api_key ? Spree::ApiKey.active.publishable.find_by(token: extract_api_key) : nil
+ end
end
# Memoized global secret-key lookup (digest-based, active keys only).
@@ -76,7 +77,9 @@ module Spree
def secret_api_key
return @secret_api_key if defined?(@secret_api_key)
- @secret_api_key = Spree::ApiKey.find_by_secret_token(extract_api_key)
+ @secret_api_key = Spree::StoreScopeGuard.skip do
+ Spree::ApiKey.find_by_secret_token(extract_api_key)
+ end
end
# Marks the API key as used at most once per hour
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/idempotent.rb b/spree/api/app/controllers/concerns/spree/api/v3/idempotent.rb
index ca1d2f1d4d..53c749f484 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/idempotent.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/idempotent.rb
@@ -67,10 +67,16 @@ module Spree
end
def idempotency_cache_key(key)
- owner_id = request.headers['X-Spree-Api-Key'].presence ||
- spree_current_user&.id ||
- request.remote_ip
- "spree:idempotency:#{Digest::SHA256.hexdigest(owner_id.to_s)}:#{Digest::SHA256.hexdigest(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}")}"
end
def request_fingerprint
diff --git a/spree/api/app/controllers/spree/api/v3/base_controller.rb b/spree/api/app/controllers/spree/api/v3/base_controller.rb
index 443b0da5a9..90ff273b60 100644
--- a/spree/api/app/controllers/spree/api/v3/base_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/base_controller.rb
@@ -38,6 +38,12 @@ module Spree
with: RATE_LIMIT_RESPONSE,
unless: :secret_key_request?
+ # Cross-store leak tripwire, active in development/test only:
+ # registered ahead of the authentication callbacks so resource
+ # lookups run inside the guarded window. Deliberately global lookups
+ # (credential searches) opt out with Spree::StoreScopeGuard.skip.
+ around_action { |_controller, action| Spree::StoreScopeGuard.watch(&action) }
+
# Optional JWT authentication by default
before_action :authenticate_user
diff --git a/spree/api/spec/spec_helper.rb b/spree/api/spec/spec_helper.rb
index ae0c4a05b9..cbe6cf3971 100644
--- a/spree/api/spec/spec_helper.rb
+++ b/spree/api/spec/spec_helper.rb
@@ -67,6 +67,11 @@ end
RSpec.configure do |config|
config.color = true
config.default_formatter = 'progress'
+
+ # Cross-store leaks fail this suite rather than warn: a store-less query on
+ # a store-owned table inside a guarded request raises (see
+ # Spree::StoreScopeGuard — wrap deliberately global lookups in `skip`).
+ config.before(:suite) { Spree::Config.store_scope_guard = 'raise' }
config.fail_fast = ENV['FAIL_FAST'] || false
config.infer_spec_type_from_file_location!
config.raise_errors_for_deprecations!
diff --git a/spree/core/app/models/spree/data_feed.rb b/spree/core/app/models/spree/data_feed.rb
index 2f76e73079..8b9afab66c 100644
--- a/spree/core/app/models/spree/data_feed.rb
+++ b/spree/core/app/models/spree/data_feed.rb
@@ -11,7 +11,7 @@ module Spree
with_options presence: true do
validates :store
- validates :name, uniqueness: true
+ validates :name, uniqueness: { scope: :store_id }
validates :slug, uniqueness: { scope: :store_id }
end
diff --git a/spree/core/app/models/spree/delivery_method.rb b/spree/core/app/models/spree/delivery_method.rb
index 5df5081ba4..6a7af9c33f 100644
--- a/spree/core/app/models/spree/delivery_method.rb
+++ b/spree/core/app/models/spree/delivery_method.rb
@@ -305,12 +305,13 @@ module Spree
end
# Stock locations this method can fulfill from. For pickup methods an
- # empty set means every active pickup-enabled location qualifies.
+ # empty set means every active pickup-enabled location of the method's
+ # own store qualifies — never other stores' counters.
#
# @return [ActiveRecord::Relation<Spree::StockLocation>]
def available_pickup_locations
configured = pickup_locations.merge(Spree::StockLocation.active)
- configured.exists? ? configured : Spree::StockLocation.active.pickup_enabled
+ configured.exists? ? configured : store.stock_locations.active.pickup_enabled
end
# The third-party pickup point network behind a pickup_point method.
diff --git a/spree/core/app/models/spree/payment_method.rb b/spree/core/app/models/spree/payment_method.rb
index 554b269935..326e86415a 100644
--- a/spree/core/app/models/spree/payment_method.rb
+++ b/spree/core/app/models/spree/payment_method.rb
@@ -3,7 +3,10 @@ module Spree
has_prefix_id :pm # Stripe: pm_
acts_as_paranoid
- acts_as_list
+ # Scoped like every other store-owned list (Collection, Market,
+ # PriceList): without it, position assignment and reordering shift rows
+ # across ALL stores.
+ acts_as_list scope: :store_id
include Spree::SingleStoreResource
include Spree::StorePreferences
diff --git a/spree/core/app/models/spree/stock_location.rb b/spree/core/app/models/spree/stock_location.rb
index d47cbd2cf9..0dcd896da6 100644
--- a/spree/core/app/models/spree/stock_location.rb
+++ b/spree/core/app/models/spree/stock_location.rb
@@ -229,10 +229,12 @@ module Spree
Spree::StockLocations::StockItems::CreateJob.perform_later(self)
end
+ # One default per STORE — scoping to the whole table would let one
+ # store's default demote every other store's.
def ensure_one_default
if default
- StockLocation.where(default: true).where.not(id: id).update_all(default: false)
- StockLocation.where.not(id: id).update_all(updated_at: Time.current)
+ store.stock_locations.where(default: true).where.not(id: id).update_all(default: false)
+ store.stock_locations.where.not(id: id).update_all(updated_at: Time.current)
end
end
diff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rb
index 27ba729620..ff35046fdd 100644
--- a/spree/core/app/models/spree/variant.rb
+++ b/spree/core/app/models/spree/variant.rb
@@ -730,8 +730,11 @@ module Spree
self.cost_currency = Spree::Store.default.default_currency if cost_currency.blank?
end
+ # Only the product's own store's locations — a new variant must not grow
+ # stock items in every other store's warehouses.
def create_stock_items
- StockLocation.where(propagate_all_variants: true).each do |stock_location|
+ locations = product&.store ? product.store.stock_locations : StockLocation.all
+ locations.where(propagate_all_variants: true).each do |stock_location|
stock_location.propagate_variant(self)
end
end
diff --git a/spree/core/db/migrate/20260813130001_add_unique_indexes_to_spree_data_feeds.rb b/spree/core/db/migrate/20260813130001_add_unique_indexes_to_spree_data_feeds.rb
new file mode 100644
index 0000000000..11f1923c7f
--- /dev/null
+++ b/spree/core/db/migrate/20260813130001_add_unique_indexes_to_spree_data_feeds.rb
@@ -0,0 +1,10 @@
+class AddUniqueIndexesToSpreeDataFeeds < ActiveRecord::Migration[8.1]
+ # Backs the model's per-store name/slug uniqueness with real constraints —
+ # both validations were index-less (race-unsafe) before. Existing data
+ # cannot violate them: names were validated globally unique (a strict
+ # superset of per-store), and slugs were already validated per store.
+ def change
+ add_index :spree_data_feeds, [:store_id, :name], unique: true
+ add_index :spree_data_feeds, [:store_id, :slug], unique: true
+ end
+end
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index ceefc8e6b8..e179591e85 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -644,6 +644,7 @@ require 'spree/service_module'
require 'spree/workflow'
require 'spree/analytics'
require 'spree/events'
+require 'spree/store_scope_guard'
require 'spree/core/partials'
require 'spree/core/controller_helpers/auth'
diff --git a/spree/core/lib/spree/core/configuration.rb b/spree/core/lib/spree/core/configuration.rb
index 5710c17476..07e90551a8 100644
--- a/spree/core/lib/spree/core/configuration.rb
+++ b/spree/core/lib/spree/core/configuration.rb
@@ -97,6 +97,11 @@ module Spree
preference :reserve_stock_on, :string, default: 'checkout', deprecated: 'Nothing reads this in Spree 6 — see the stock_reservations_enabled preference on the store'
preference :stock_reservations_enabled, :boolean, default: true, deprecated: 'Set it on the store instead' # Hold stock during checkout to prevent overselling
preference :default_stock_reservation_ttl_minutes, :integer, default: 10, deprecated: 'Use the stock_reservation_ttl_minutes preference on the store'
+ # Cross-store leak tripwire for development and test (never active in
+ # production) — see Spree::StoreScopeGuard. 'log' warns about store-less
+ # queries on store-owned tables inside API requests; 'raise' turns them
+ # into failures (what this repo's API test suite runs); 'off' disables.
+ preference :store_scope_guard, :string, default: 'log', env: 'SPREE_STORE_SCOPE_GUARD'
# Tiered cart-expiry reaper (docs/plans/6.0-cart-order-split.md Decision 5)
preference :guest_cart_expiry_days, :integer, default: 30
preference :customer_cart_expiry_days, :integer, default: 90
diff --git a/spree/core/lib/spree/core/preferences/runtime_configuration.rb b/spree/core/lib/spree/core/preferences/runtime_configuration.rb
index 9136677594..219236998d 100644
--- a/spree/core/lib/spree/core/preferences/runtime_configuration.rb
+++ b/spree/core/lib/spree/core/preferences/runtime_configuration.rb
@@ -80,8 +80,12 @@ module Spree
attr_writer name
if env
+ # The ivar symbol is built once here — interpolating it inside
+ # the reader would allocate a String on every read of an
+ # env-backed setting, some of which sit on the request path.
+ ivar = :"@#{name}"
define_method(name) do
- value = instance_variable_get("@#{name}")
+ value = instance_variable_get(ivar)
return value unless value.nil?
ENV[env].presence || default
diff --git a/spree/core/lib/spree/store_scope_guard.rb b/spree/core/lib/spree/store_scope_guard.rb
new file mode 100644
index 0000000000..7814540e76
--- /dev/null
+++ b/spree/core/lib/spree/store_scope_guard.rb
@@ -0,0 +1,180 @@
+require 'request_store'
+
+module Spree
+ # Development/test tripwire for cross-store data leaks
+ # (docs/plans/6.0-store-context-and-first-run-setup.md): while a guarded
+ # request runs, a SELECT against a store-owned table (any spree_* table
+ # carrying a store_id column) that is neither store-scoped nor id-filtered
+ # is reported — that is the shape of an IDOR/cross-store leak, since every
+ # controller lookup must go through a current_store association. Open-core
+ # isolation rests on that discipline (row-level enforcement is not a core
+ # feature), so this is the net under it.
+ #
+ # Never active in production — it is a correctness net for development and
+ # CI, not an enforcement layer. Mode comes from
+ # `Spree::Config[:store_scope_guard]` / SPREE_STORE_SCOPE_GUARD:
+ # 'log' (default), 'raise', or 'off'.
+ #
+ # A deliberately store-less lookup (a global credential search, a
+ # cross-store listing for the store switcher) opts out explicitly:
+ #
+ # Spree::StoreScopeGuard.skip { Spree::ApiKey.find_by(token: token) }
+ #
+ # Flags live in RequestStore — like Spree::Events' disable flags — so a
+ # request that leaks mid-flight cannot leave a reused server thread
+ # permanently skipped or watched.
+ class StoreScopeGuard
+ class UnscopedQueryError < StandardError; end
+
+ ACTIVE_KEY = :spree_store_scope_guard_active
+ SKIP_KEY = :spree_store_scope_guard_skip
+
+ # Tables that answer store-less queries by design. spree_stores is the
+ # tenant root itself; the *_stores join tables are the legacy multi-store
+ # bridges, filtered by their other foreign key.
+ IGNORED_TABLES = %w[
+ spree_stores
+ spree_products_stores
+ spree_promotions_stores
+ spree_payment_methods_stores
+ ].freeze
+
+ class << self
+ def enabled?
+ watchable_environment? && mode != 'off'
+ end
+
+ # Overridable: OSS keeps the guard out of production, but a
+ # multi-tenant enforcement layer may run it there as a log-mode canary.
+ # Memoized — this sits on the production request path, where it must
+ # answer "no" for free.
+ def watchable_environment?
+ return @watchable_environment if defined?(@watchable_environment)
+
+ @watchable_environment = Rails.env.development? || Rails.env.test?
+ end
+
+ # @return [String] 'log', 'raise' or 'off'
+ def mode
+ Spree::Config[:store_scope_guard]
+ end
+
+ # Wraps a unit of work (an API request) in the guarded window. No-op
+ # when the guard is disabled.
+ def watch
+ return yield unless enabled?
+
+ install!
+ previous = RequestStore.store[ACTIVE_KEY]
+ RequestStore.store[ACTIVE_KEY] = true
+ yield
+ ensure
+ RequestStore.store[ACTIVE_KEY] = previous
+ end
+
+ # Suppresses the guard for a deliberately store-less lookup.
+ def skip
+ previous = RequestStore.store[SKIP_KEY]
+ RequestStore.store[SKIP_KEY] = true
+ yield
+ ensure
+ RequestStore.store[SKIP_KEY] = previous
+ end
+
+ def active?
+ RequestStore.store[ACTIVE_KEY] && !RequestStore.store[SKIP_KEY]
+ end
+
+ # Forgets memoized environment/schema state (specs, migrations).
+ def reset!
+ remove_instance_variable(:@watchable_environment) if defined?(@watchable_environment)
+ @watched_tables = nil
+ end
+
+ private
+
+ def install!
+ @installed ||= begin
+ ActiveSupport::Notifications.subscribe('sql.active_record') do |*, payload|
+ check(payload) if active?
+ end
+ true
+ end
+ end
+
+ def check(payload)
+ return if payload[:cached]
+
+ sql = payload[:sql].to_s
+ # Active Record emits uppercase keywords; hand-written lowercase SQL
+ # is out of scope for a tripwire.
+ return unless sql.start_with?('SELECT')
+
+ table = sql[/ FROM ["'`]?([a-z0-9_]+)/, 1]
+ return if table.nil? || !watched_tables.include?(table)
+ return if scoped?(sql)
+
+ report(table, sql, payload[:name])
+ end
+
+ # Deliberately crude — parsing SQL to never false-negative is not the
+ # point; catching the common leak shapes cheaply is. A statement counts
+ # as scoped when it carries:
+ #
+ # - a store_id predicate anywhere, or
+ # - any id/_id predicate: primary-key and foreign-key filters use ids
+ # that came from rows already loaded through a scoped association, or
+ # - the `SELECT 1 AS one` existence shape, which is dominated by
+ # uniqueness validations on deliberately global columns (document
+ # numbers are unique across stores by design).
+ #
+ # What that trades away, honestly: attacker-controlled raw ids in
+ # store-less finds/FK filters and `exists?` probes slip through — those
+ # shapes are covered structurally (v3 resource lookups run through
+ # `for_store(current_store)`). The net catches what has no structural
+ # cover: secondary-key lookups (slug, number, code, email, token) and
+ # unscoped scans.
+ def scoped?(sql)
+ # A store_id COMPARISON, not a mention — a projected column
+ # (`select(:store_id)`) must not count, and neither does
+ # `store_id IS [NOT] NULL`, which matches storeless or all-store rows
+ # rather than a store. The optional closing quote covers every
+ # adapter: PostgreSQL/SQLite double-quote identifiers, MySQL
+ # backticks them.
+ sql.match?(/\bstore_id["'`]?\s+(=|!=|IN)\s/) ||
+ sql.start_with?('SELECT 1 AS one') ||
+ sql.match?(/\b(id|[a-z_]+_id)["'`]?\s+(=|!=|IN)\s/)
+ end
+
+ # Store-owned tables, derived from the live schema so new store-scoped
+ # models are watched without registration. The introspection itself
+ # issues queries, so it runs inside `skip` — otherwise the subscriber
+ # re-enters this method forever.
+ def watched_tables
+ @watched_tables ||= skip do
+ connection = ActiveRecord::Base.connection
+ connection.tables.select do |table|
+ table.start_with?('spree_') &&
+ !IGNORED_TABLES.include?(table) &&
+ connection.column_exists?(table, :store_id)
+ end.to_set
+ end
+ end
+
+ def report(table, sql, name)
+ # Bounded window: the interesting frame sits a few levels above the
+ # notification subscriber, and materializing a full request backtrace
+ # per violation is what makes log mode expensive.
+ frames = caller(3, 30) || []
+ location = frames.find { |line| !line.include?('/gems/') } || frames.first
+ message = "[Spree::StoreScopeGuard] store-less query on #{table} inside a guarded request " \
+ "(#{name}): #{sql.truncate(300)}\n at #{location}\n" \
+ ' Scope the lookup through current_store, or wrap a deliberately global lookup in Spree::StoreScopeGuard.skip { }.'
+
+ raise UnscopedQueryError, message if mode == 'raise'
+
+ Rails.logger.warn(message)
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/tasks/single_store_associations.rake b/spree/core/lib/tasks/single_store_associations.rake
index e3ff0b4fe1..28830bb404 100644
--- a/spree/core/lib/tasks/single_store_associations.rake
+++ b/spree/core/lib/tasks/single_store_associations.rake
@@ -60,6 +60,17 @@ namespace :spree do
puts " #{shared[:promotions]} promotion(s) and #{shared[:payment_methods]} payment method(s) " \
"were shared across stores — only the owner store keeps them unless spree_multi_store is installed."
end
+
+ # Positions were numbered across the whole table before acts_as_list
+ # was scoped per store; renumber each store's list so reordering
+ # behaves on upgraded data (a sparse, non-1-based list confuses
+ # acts_as_list's move operations). Idempotent: renumbering an already
+ # per-store list reproduces it.
+ Spree::Store.ids.each do |store_id|
+ Spree::PaymentMethod.with_deleted.where(store_id: store_id).order(:position, :id).each.with_index(1) do |payment_method, index|
+ payment_method.update_column(:position, index) unless payment_method.position == index
+ end
+ end
end
end
end
diff --git a/spree/core/spec/lib/spree/store_scope_guard_spec.rb b/spree/core/spec/lib/spree/store_scope_guard_spec.rb
new file mode 100644
index 0000000000..ac874cf4f7
--- /dev/null
+++ b/spree/core/spec/lib/spree/store_scope_guard_spec.rb
@@ -0,0 +1,107 @@
+require 'spec_helper'
+
+RSpec.describe Spree::StoreScopeGuard do
+ after { Spree::Config.store_scope_guard = nil }
+
+ describe 'raise mode' do
+ before { Spree::Config.store_scope_guard = 'raise' }
+
+ it 'raises for a store-less query on a store-owned table inside the window' do
+ expect {
+ described_class.watch { Spree::Product.where(name: 'x').to_a }
+ }.to raise_error(described_class::UnscopedQueryError, /spree_products/)
+ end
+
+ it 'passes a query carrying a store_id predicate' do
+ expect {
+ described_class.watch { Spree::Product.where(store_id: 1).to_a }
+ }.not_to raise_error
+ end
+
+ it 'is not fooled by a projected store_id column without a predicate' do
+ expect {
+ described_class.watch { Spree::Product.select(:store_id, :name).where(name: 'x').to_a }
+ }.to raise_error(described_class::UnscopedQueryError, /spree_products/)
+ end
+
+ # The suite runs on one adapter at a time, so pin the predicate matching
+ # against every adapter's quoting directly — MySQL's backticks broke it
+ # once while PostgreSQL and SQLite passed.
+ it 'recognizes predicates under every identifier quoting style' do
+ [
+ %(SELECT * FROM "spree_products" WHERE "spree_products"."store_id" = 1),
+ %(SELECT * FROM `spree_products` WHERE `spree_products`.`store_id` = 1),
+ %(SELECT * FROM spree_products WHERE store_id = 1),
+ ].each do |sql|
+ expect(described_class.send(:scoped?, sql)).to be(true), "not recognized: #{sql}"
+ end
+ end
+
+ # Same reasoning as above, from the other side: a null check matches
+ # storeless or all-store rows rather than a store, under any quoting.
+ it 'does not count store_id null checks as store scoping' do
+ [
+ %(SELECT * FROM "spree_products" WHERE "spree_products"."store_id" IS NULL),
+ %(SELECT * FROM "spree_products" WHERE "spree_products"."store_id" IS NOT NULL),
+ %(SELECT * FROM `spree_products` WHERE `spree_products`.`store_id` IS NULL),
+ %(SELECT * FROM `spree_products` WHERE `spree_products`.`store_id` IS NOT NULL),
+ %(SELECT * FROM spree_products WHERE store_id IS NULL),
+ %(SELECT * FROM spree_products WHERE store_id IS NOT NULL),
+ ].each do |sql|
+ expect(described_class.send(:scoped?, sql)).to be(false), "incorrectly recognized: #{sql}"
+ end
+ end
+
+ it 'passes id and foreign-key filters (ids in hand came from scoped rows)' do
+ expect {
+ described_class.watch { Spree::Order.where(customer_id: 1).to_a }
+ }.not_to raise_error
+ end
+
+ it 'ignores tables without a store_id column' do
+ expect {
+ described_class.watch { Spree::Country.where(iso: 'US').to_a }
+ }.not_to raise_error
+ end
+
+ it 'ignores the stores table itself' do
+ expect {
+ described_class.watch { Spree::Store.where(default: true).to_a }
+ }.not_to raise_error
+ end
+
+ it 'is inert outside a watched window' do
+ described_class.watch { Spree::Store.default } # installs the subscriber
+
+ expect { Spree::Product.where(name: 'x').to_a }.not_to raise_error
+ end
+
+ it 'lets a deliberately global lookup opt out with skip' do
+ expect {
+ described_class.watch do
+ described_class.skip { Spree::Product.where(name: 'x').to_a }
+ end
+ }.not_to raise_error
+ end
+ end
+
+ describe 'log mode' do
+ before { Spree::Config.store_scope_guard = 'log' }
+
+ it 'warns instead of raising' do
+ expect(Rails.logger).to receive(:warn).with(/spree_products/)
+
+ described_class.watch { Spree::Product.where(name: 'x').to_a }
+ end
+ end
+
+ describe 'off mode' do
+ before { Spree::Config.store_scope_guard = 'off' }
+
+ it 'does not watch at all' do
+ expect(Rails.logger).not_to receive(:warn)
+
+ described_class.watch { Spree::Product.where(name: 'x').to_a }
+ end
+ end
+end
diff --git a/spree/core/spec/lib/spree/store_scoped_cache_keys_spec.rb b/spree/core/spec/lib/spree/store_scoped_cache_keys_spec.rb
new file mode 100644
index 0000000000..1e97d7b61a
--- /dev/null
+++ b/spree/core/spec/lib/spree/store_scoped_cache_keys_spec.rb
@@ -0,0 +1,89 @@
+require 'spec_helper'
+
+# Tripwire for the store-scoped cache-key constraint
+# (docs/plans/6.0-store-context-and-first-run-setup.md): a cache entry whose
+# key omits the store leaks one store's data into another's responses the
+# moment two stores share a deployment. Every Rails.cache call site in core
+# and api must either build its key from the store (or a store-scoped
+# record's cache_key_with_version) or appear in the reviewed allowlist below
+# with the reason it is global by design.
+#
+# When this spec fails on a call site you added: include the store in the
+# key, or — only if the data is genuinely installation-wide — add an
+# allowlist entry with a justification.
+RSpec.describe 'Store-scoped cache keys' do
+ CACHE_CALL = /Rails\.cache\.(?:fetch|read|write|delete)\b/
+ # A call line counts as store-scoped when the key expression visibly
+ # carries the store or a record identity (record cache keys embed globally
+ # unique ids, so they cannot collide across stores).
+ SCOPED_HINT = /cache_key_with_version|current_store|store\.id|store_id/
+
+ # path (relative to the spree/ directory) => [reviewed call count,
+ # justification]. Every reason must say why the cached data is safe to
+ # share across stores. The count pins the review: adding a cache call to
+ # an allowlisted file fails the audit until the new call is reviewed and
+ # the count bumped.
+ ALLOWLIST = {
+ 'core/app/models/spree/authentication/strategies/oidc_strategy.rb' => [3,
+ 'JWKS + discovery documents are per identity provider, keyed by the ' \
+ 'provider\'s configured cache_key_prefix; providers are application-level ' \
+ 'configuration, not store data.'],
+ 'api/app/controllers/spree/api/v3/store/products/filters_controller.rb' => [1,
+ 'filters_cache_key embeds current_store.id, currency, locale and the ' \
+ 'catalog fingerprint — scoped, just built outside the call line.'],
+ 'api/app/controllers/concerns/spree/api/v3/rate_limit_headers.rb' => [1,
+ 'Rate-limit budgets are per credential by design: API keys are ' \
+ 'store-bound, and a staff JWT\'s budget deliberately spans stores.'],
+ 'api/app/controllers/concerns/spree/api/v3/idempotent.rb' => [2,
+ 'idempotency_cache_key partitions by credential AND the resolved ' \
+ 'store, so replays cannot cross stores.'],
+ }.freeze
+
+ SPREE_ROOT = File.expand_path('../../../../..', __dir__)
+
+ # Computed once at load — both examples read it, and the glob + scan over
+ # two gem trees is the expensive part of this spec.
+ CALL_SITES = Dir.glob(File.join(SPREE_ROOT, 'spree', '{core,api}', '{app,lib}', '**', '*.rb')).flat_map do |file|
+ content = File.read(file)
+ next [] unless content.include?('Rails.cache')
+
+ relative = file.delete_prefix("#{SPREE_ROOT}/spree/")
+ content.each_line.with_index(1).filter_map do |line, line_number|
+ next unless line.match?(CACHE_CALL)
+
+ { file: relative, line: line_number, source: line.strip }
+ end
+ end.freeze
+
+ def call_sites
+ CALL_SITES
+ end
+
+ it 'every Rails.cache call site is store-scoped or allowlisted with a reason' do
+ unaccounted = call_sites.reject do |site|
+ site[:source].match?(SCOPED_HINT) || ALLOWLIST.key?(site[:file])
+ end
+
+ expect(unaccounted).to be_empty, lambda {
+ list = unaccounted.map { |s| " #{s[:file]}:#{s[:line]} #{s[:source]}" }.join("\n")
+ "Cache call sites without a store-scoped key or an allowlist entry:\n#{list}\n\n" \
+ 'Include the store (or a record cache_key_with_version) in the key, or add a ' \
+ "reviewed allowlist entry in #{__FILE__} explaining why the data is global."
+ }
+ end
+
+ it 'allowlisted files carry exactly their reviewed number of cache calls' do
+ actual_counts = call_sites.group_by { |site| site[:file] }.transform_values(&:size)
+
+ mismatched = ALLOWLIST.filter_map do |file, (expected, _reason)|
+ actual = actual_counts[file] || 0
+ "#{file}: reviewed #{expected}, found #{actual}" if actual != expected
+ end
+
+ expect(mismatched).to be_empty, lambda {
+ "Allowlisted files changed their cache calls — re-review and update the count:\n" \
+ " #{mismatched.join("\n ")}\n" \
+ '(A count of 0 means the entry is stale — remove it.)'
+ }
+ end
+end
diff --git a/spree/core/spec/lib/spree/store_scoped_list_positions_spec.rb b/spree/core/spec/lib/spree/store_scoped_list_positions_spec.rb
new file mode 100644
index 0000000000..75d4ada4f6
--- /dev/null
+++ b/spree/core/spec/lib/spree/store_scoped_list_positions_spec.rb
@@ -0,0 +1,35 @@
+require 'spec_helper'
+
+# Tripwire for cross-store position bleed: a store-owned model whose
+# acts_as_list is not scoped by its store numbers positions across the whole
+# table, so creating or reordering rows in one store shifts every other
+# store's list (the bug PaymentMethod shipped with). A list scoped by a
+# parent that is itself store-owned (product, option_type, collection…) is
+# transitively fine.
+RSpec.describe 'Store-scoped list positions' do
+ it 'every store-owned acts_as_list scopes by store or a parent association' do
+ Rails.application.eager_load!
+
+ offenders = Spree.base_class.descendants.select do |model|
+ next false if model.abstract_class? || !model.table_exists?
+ next false unless model.column_names.include?('store_id')
+ next false unless model.include?(ActiveRecord::Acts::List::InstanceMethods)
+
+ # acts_as_list encodes its scope in the generated scope_condition. A
+ # Hash with store_id or a foreign key counts as scoped (a parent FK is
+ # transitively store-scoped); anything else — the unscoped '1 = 1'
+ # sentinel, a raw SQL string, or a Hash of non-FK columns like
+ # {deleted_at: nil} — is unverifiable here and must be reviewed.
+ condition = model.new.send(:scope_condition)
+ !(condition.is_a?(Hash) &&
+ condition.keys.any? { |key| key.to_s == 'store_id' || key.to_s.end_with?('_id') })
+ end
+
+ expect(offenders).to be_empty, lambda {
+ "Store-owned models whose acts_as_list scope is missing or not verifiably store-derived " \
+ "(positions bleed across stores):\n" \
+ "#{offenders.map(&:name).join(', ')}\n" \
+ 'Declare acts_as_list scope: :store_id or a parent association (see Spree::Collection, Spree::Market, Spree::PriceList).'
+ }
+ end
+end
diff --git a/spree/core/spec/models/spree/delivery_method_spec.rb b/spree/core/spec/models/spree/delivery_method_spec.rb
index 9ad89bd547..2fc527d6e9 100644
--- a/spree/core/spec/models/spree/delivery_method_spec.rb
+++ b/spree/core/spec/models/spree/delivery_method_spec.rb
@@ -391,4 +391,14 @@ describe Spree::DeliveryMethod, type: :model do
it { expect(delivery_method.display_estimated_price).to eq('Flat rate: Free') }
end
end
+ describe '#available_pickup_locations' do
+ let(:delivery_method) { create(:delivery_method, store: @default_store) }
+
+ it "falls back to the method's own store's pickup counters, never another store's" do
+ own_location = create(:stock_location, store: @default_store, active: true, pickup_enabled: true)
+ create(:stock_location, store: create(:store), active: true, pickup_enabled: true)
+
+ expect(delivery_method.available_pickup_locations).to contain_exactly(own_location)
+ end
+ end
end
diff --git a/spree/core/spec/models/spree/payment_method_spec.rb b/spree/core/spec/models/spree/payment_method_spec.rb
index 6f741b0bf7..2f29a1ae82 100644
--- a/spree/core/spec/models/spree/payment_method_spec.rb
+++ b/spree/core/spec/models/spree/payment_method_spec.rb
@@ -270,4 +270,14 @@ describe Spree::PaymentMethod, type: :model do
expect(credit_card.reload.deleted_at).not_to be_nil
end
end
+ describe 'position scoping' do
+ it 'numbers positions per store, not across the whole table' do
+ create(:payment_method, store: @default_store)
+ other_store = create(:store)
+
+ first_in_other_store = create(:payment_method, store: other_store)
+
+ expect(first_in_other_store.position).to eq(1)
+ end
+ end
end