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
Remove CanCanCan from the Store API behind a swappable access policy
Damian Legawiec7475f3c21f82
diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdxindex 446a82ca9d..e89b47a078 100644--- a/docs/developer/upgrades/5.6-to-6.0.mdx+++ b/docs/developer/upgrades/5.6-to-6.0.mdx@@ -396,7 +396,7 @@ Permission sets are **removed with no bridge**. Staff roles now hold flat permis|---|---|| `Spree::PermissionSets::*` (all classes) | catalog keys on the role row: `Spree::Role#permissions` || `Spree.permissions.assign(:role, [sets])` | the role editor, `POST /api/v3/admin/roles`, or plain ActiveRecord in seeds |-| Custom permission sets with record-level rules | `Spree::Ability.register_ability(MyAbility)` — a plain `CanCan::Ability` class |+| Custom permission sets with record-level rules | Replace the ability class: `Spree::Dependencies.ability_class = 'MyApp::Ability'` || `Spree::ApiKey::SCOPES` | `Spree::ApiKey.known_scopes` (derived from the catalog) |Old initializers fail loudly at boot: the set constants raise `NameError`, and `Spree.permissions.assign` raises with directions. **Recreate your custom roles before deploying** — a pre-existing role row comes up with no permissions, so staff holding it are locked out (fail closed) until its permissions are filled in:@@ -407,7 +407,7 @@ Spree::Role.find_or_create_by!(name: 'support').update!(permissions: %w[read_orders read_customers])```-Storefront customers are not part of this system: the old `:default` role and `DefaultCustomer` set became internal ability code, and customers never resolve roles. Extensions register their resources into the catalog once, which makes them grantable to roles **and** mintable as API-key scopes:+Storefront customers are not part of this system: the old `:default` role and `DefaultCustomer` set are gone, customers never resolve roles, and the Store API no longer consults CanCanCan at all — customer authorization is ownership-scoped queries plus `Spree::Storefront::AccessPolicy` (swappable via `Spree::Dependencies.storefront_access_policy_class`). If an extension added storefront `can` rules, move them into an access-policy subclass or a checkout workflow `validate` hook. Extensions register their resources into the catalog once, which makes them grantable to roles **and** mintable as API-key scopes:```rubySpree.permissions.register_resource(:reviews, group: :catalog, subjects: -> { [SpreeReviews::Review] })diff --git a/docs/plans/6.0-admin-rbac.md b/docs/plans/6.0-admin-rbac.mdindex 304a5046db..c56f0f1891 100644--- a/docs/plans/6.0-admin-rbac.md+++ b/docs/plans/6.0-admin-rbac.md@@ -63,8 +63,9 @@ pages.Fail-closed is the right failure mode for permissions — nothing boots withstaff silently over- or under-privileged. Custom rules that mixedrecord-level conditions into sets migrate to- `Spree::Ability.register_ability` — the single remaining low-level escape- hatch. (Two earlier same-day drafts — sets kept as "bundles" over the+ `Spree::Dependencies.ability_class` — replacing the ability class outright+ is the remaining low-level escape hatch (2026-08-08: `register_ability` was+ dropped too; the catalog plus a full class swap is the whole surface). (Two earlier same-day drafts — sets kept as "bundles" over thecatalog, then a one-release `assign` bridge with an import task — were bothrejected as complexity serving only back-compat comfort in the breakingwindow.)@@ -99,12 +100,47 @@ pages.the storefront baseline directly — which also drops a per-request `role_users`query for logged-in customers and aligns with the platform-auth Customer/Staffsplit (a customer holding the admin role stops being a concept at 6.0).-- **The storefront baseline is internal code, not a registry entry- (2026-08-07).** `:default` and `DefaultCustomer` cease to be public concepts.- What remains is a fixed storefront ability (ownership hash conditions, guest- cart tokens, invitation acceptance) behind the Store API, with scope-fetching- as the primary enforcement — which it already is. Merchants never configure- customer permissions; there is nothing to configure.+- **The Store API does not use CanCanCan at all (2026-08-08, superseding the+ 2026-08-07 "internal baseline" decision).** `Spree::Ability` is staff-only;+ an ability built for a customer principal has no rules. Storefront+ authorization is ownership, enforced two ways: **scope-fetching** (every+ account controller reads through `current_user` — addresses, cards, gift+ cards, store credits, wishlists — and catalog endpoints read the store's+ public data with no per-record check), and **`Spree::Storefront::AccessPolicy`**+ for the checks a scope cannot express: cart/order access proven by JWT+ ownership OR a guest token. The policy is swappable via+ `Spree::Dependencies.storefront_access_policy_class`; denials raise+ `Spree::Storefront::AccessDenied`, rendered as the same 403 payload as+ CanCan's. The generic `authorize_resource!`/`authorize_parent!` hooks and+ the `accessible_by` collection filter moved from the shared v3+ `ResourceController` down to the Admin branch — the shared base carries+ no authorization framework.+- **B2B company accounts extend the storefront through seams, not controller+ decoration (2026-08-08).** The Enterprise B2B module+ (`6.1-channels-catalogs-b2b.md`: Company → CompanyLocation →+ CompanyContact, buyer/approver/viewer contact roles, approvals, spending+ limits) needs exactly three kinds of authority change, and each has an+ open-source injection point already in place:+ 1. **Access widening** ("an approver sees every purchase of their company+ location") — subclass `Spree::Storefront::AccessPolicy`, override+ `orders_scope`/`purchase_readable?`, register via+ `Spree::Dependencies.storefront_access_policy_class`. Relational scoping+ is the natural shape here; a rule engine is not — CanCanCan's+ `accessible_by` cannot translate block rules (the token checks) to SQL,+ which is why the old ability needed `authorize!` calls on top of scopes+ in the first place.+ 2. **Action vetoes** ("orders over the spending limit need approval") —+ checkout workflow `validate` hooks (`carts.complete.validate`), shipped+ with `6.0-service-workflows.md`. These are order-state policies, not+ access rules; they never fit an ability cleanly.+ 3. **Catalog visibility** (per-location catalogs/price lists) — data+ scoping through the products-for-context seam, per the 2026-08-07+ decision below.+ Enterprise implements policy subclasses and hook handlers; open source owns+ the seams. No CanCanCan and no controller decoration on the storefront —+ matching Medusa/Saleor/Vendure, none of which ship a storefront rule+ engine, and Shopify B2B, whose company-contact permissions are fixed roles+ resolved server-side.- **B2B company roles are out of scope and must stay a separate system(2026-08-07).** Company-account permissions (buyer/approver, location roles,hierarchies, spend limits, order approvals) are ownership-scoped and@@ -133,7 +169,7 @@ pages.JWT-authenticated paths" (noted there).- **CanCanCan is demoted to internal plumbing, not dropped (2026-08-07).** Keyscompile to CanCanCan rules behind the gate, because three things still need it:- the storefront baseline's record-level rules, `register_ability` host rules,+ the storefront baseline's record-level rules, host ability-class swaps,and sixty-odd admin controllers plus the SPA mirror that speak`authorize!`/rules today — rewriting the enforcement layer and the grant modelin one release doubles the risk. Nothing public configures CanCanCan anymore.@@ -292,17 +328,18 @@ add_column :spree_roles, :mutable, :boolean, default: true, null: false`assign` raises with an upgrade-guide pointer (tripwire for 5.x initializers);there is no `grant`, no bridge, no union.-The storefront baseline moves out of the registry entirely: `Spree::Ability`-applies it directly for customer/guest principals (ownership hash conditions,-guest tokens — today's `DefaultCustomer` body, now internal). Role resolution+The storefront leaves CanCanCan entirely: customer/guest requests are+authorized by ownership-scoped queries plus `Spree::Storefront::AccessPolicy`+(cart/order token checks, order-listing scope), swappable through+`Spree::Dependencies.storefront_access_policy_class`. Role resolution(`determine_role_names` + key activation from the role rows) runs only foradmin-user principals. The `admin` role activates the full catalog; its formersafety rules are model guards by then.-`Spree::Ability.register_ability` remains the single low-level escape hatch for-host rules that don't fit keys ("support sees only their region's orders") and-the migration target for custom permission sets that mixed record-level-conditions into grants.+`Spree::Dependencies.ability_class` — swapping the whole ability class — is the+remaining low-level escape hatch for host rules that don't fit keys ("support+sees only their region's orders") and the migration target for custom+permission sets that mixed record-level conditions into grants.### Admin API@@ -331,7 +368,7 @@ DELETE /api/v3/admin/roles/:id # newstore) alongside the existing rules dump.- **Enforcement:** the generalized key gate checks every admin request'sprincipal key set against `<read|write>_<scoped_resource>`; CanCanCan runs- behind it (compiled from the same keys + `register_ability` rules), so+ behind it (compiled from the same keys), so`authorize!`/`accessible_by` in controllers keep working unchanged during 6.0.- **403 diagnostics:** `details.required_permission` from the `scoped_resource`declaration; development logs include roles + effective keys.@@ -413,8 +450,8 @@ Phase 2 — dashboard:Phase 3 — docs + cleanup:10. Rewrite `docs/developer/customization/permissions.mdx` around the editor,- the Admin API, and seeds (with `register_ability` as the advanced escape- hatch); write the 6.0 upgrade-guide entry (below).+ the Admin API, and seeds (with an ability-class swap as the advanced+ escape hatch); write the 6.0 upgrade-guide entry (below).11. 6.1: evaluate removing CanCanCan from the admin path (the storefront keepsit).@@ -439,7 +476,7 @@ closed) until the matrix is filled in.reach the endpoint. Reviewers should reject admin PRs that add subjects noentry covers.- **Grants stay flat.** Record-level conditions belong on models/workflows- (Axis B) or in `register_ability` — never in the catalog.+ (Axis B) or in a host ability-class swap — never in the catalog.- **Don't remove the `cannot …, Spree::Role, name: ['admin']` ability rules**until the model guards land with specs (extraction order: guard first).- **New sensitive resources get their own catalog resource** rather than riding@@ -494,7 +531,7 @@ all resolved 2026-08-07 and live in Key Decisions. Genuinely deferred:- **Audit trail for role/permission changes** — rides a future admin audit-logfeature; not blocking the editor.- **CanCanCan-free admin path** — becomes possible once nothing public speaks- it; evaluate in 6.1 with real data on `register_ability` usage.+ it; evaluate in 6.1.## Referencesdiff --git a/docs/plans/6.1-channels-catalogs-b2b.md b/docs/plans/6.1-channels-catalogs-b2b.mdindex 2c42c83b32..efc5ec042e 100644--- a/docs/plans/6.1-channels-catalogs-b2b.md+++ b/docs/plans/6.1-channels-catalogs-b2b.md@@ -297,6 +297,16 @@ class Spree::CompanyContact < Spree.base_classend```+Contact roles enforce through the storefront seams, never by decorating Store+API controllers (decisions.md 2026-08-08): access widening (an approver sees+every purchase of their company location) subclasses+`Spree::Storefront::AccessPolicy` via+`Spree::Dependencies.storefront_access_policy_class`; approvals and spending+limits are checkout workflow `validate` hooks; per-location catalogs are data+scoping. Enterprise ships the policy subclass and hook handlers; the seams are+open source. Contact roles never touch `Spree::Ability` or the staff+permission catalog (`6.0-admin-rbac.md`).+### Order gains Channel and CompanyLocation```rubydiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 51f82281a8..9b3ac1f34f 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1576,7 +1576,9 @@ no runtime merge, no union — the editor is WYSIWYG; "roles as code" is seedsnever roles (matching Saleor/Vendure/Shopify — roles are rows everywhere). A`mutable` column (NamedType pattern) covers locked roles: admin seeds`mutable: false`; hosts can lock compliance roles the same way. Record-level-custom rules migrate to `register_ability`, the single low-level escape hatch.+custom rules migrate to a `Spree::Dependencies.ability_class` swap — the one+low-level escape hatch (`register_ability` was dropped with the sets, 6.0+having no undocumented registration API to inherit).Upgrade is fail-closed: pre-existing custom role rows come up with emptypermissions until filled in the editor. Enforcement unifies onthe key gate: `ScopedAuthorization` generalizes so every admin request — JWT@@ -1618,3 +1620,39 @@ anywhere; every model a new admin controller authorizes must be covered by acatalog entry, or custom roles cannot reach the endpoint; new sensitiveresources get their own catalog resource instead of riding `settings`;storefront code must never consult `Spree::Role` or the catalog.++## 2026-08-08 — Store API drops CanCanCan; storefront access is a swappable policy++**Decision:** The Store API (v3) no longer consults CanCanCan anywhere.+`Spree::Ability` is staff-only — a customer principal's ability has no rules —+and the generic `authorize_resource!`/`authorize_parent!` hooks plus the+`accessible_by` collection filter moved from the shared v3 `ResourceController`+down to the Admin branch. Storefront authorization is ownership: account+controllers read through `current_user` (scope-fetching, unchanged), catalog+endpoints have no per-record check (the old `accessible_by` calls sat on+unconditional `can :read` grants — no-op filters), and the two checks a scope+cannot express — cart/order access proven by JWT ownership OR a guest token,+plus the guest-token order-listing scope — live in+`Spree::Storefront::AccessPolicy`, swappable via+`Spree::Dependencies.storefront_access_policy_class`. Denials raise+`Spree::Storefront::AccessDenied`, rendered identically to CanCan's 403.++**Why:** Two reasons converged. First, the storefront never needed a rule+engine — its "rules" were ownership conditions and token blocks, and CanCanCan+block rules can't power `accessible_by`, so controllers carried both a scope+AND an `authorize!` for the same fact. Second, the Enterprise B2B module+(`6.1-channels-catalogs-b2b.md`) must extend storefront authority without+decorating controllers, and a policy object is the right seam: **access+widening** (approver sees company-location purchases) = subclass the policy and+override `orders_scope`/`purchase_readable?`; **action vetoes** (approvals,+spending limits) = checkout workflow `validate` hooks; **catalog visibility**+(per-location catalogs) = the products-for-context data scoping. Enterprise+implements, open source owns the seams. Competitors ship no storefront rule+engine (Medusa/Saleor/Vendure); Shopify B2B contact permissions are fixed+server-side roles.++**Consequences:** Extensions must not add storefront `can` rules or call+`authorize!` in Store API controllers — widen the access policy or hook a+workflow instead. The admin side is untouched: staff JWT + CanCanCan, secret+keys + scopes. `register_ability`/`remove_ability` are gone with the sets+(`Spree::Dependencies.ability_class` is the admin-side escape hatch).diff --git a/docs/v6/developer/customization/permissions.mdx b/docs/v6/developer/customization/permissions.mdxindex 49a7446fbc..4be0be046d 100644--- a/docs/v6/developer/customization/permissions.mdx+++ b/docs/v6/developer/customization/permissions.mdx@@ -38,29 +38,33 @@ Spree.permissions.register_resource(:reviews, group: :catalog, subjects: -> {Localize the labels in your engine's locale file under `spree.permissions_catalog.resources.<name>` (`label` and `description`), and declare the same resource on your admin controllers with `scoped_resource :reviews`.-## Record-level custom rules+## Beyond the catalog-The catalog is deliberately flat. For rules it cannot express — regional restrictions, ownership conditions — register a plain `CanCan::Ability` class; its rules merge into every ability:+The catalog is deliberately flat: it answers "may this role touch this kind of record", and that is the whole grant vocabulary. Two rules that do *not* belong in it:++- **Record-state rules** ("a completed order cannot be deleted") live on models and workflows, so they bind every caller — including secret API keys, which never consult CanCanCan.+- **Row-level restrictions** (a support agent limited to one market) are not expressible as keys. Replace the ability class outright:```ruby-class RegionalSupportAbility- include CanCan::Ability+# config/initializers/spree.rb+Spree::Dependencies.ability_class = 'MyApp::Ability'+```- def initialize(user)+```ruby+# app/models/my_app/ability.rb+class MyApp::Ability < Spree::Ability+ def initialize(user, options = {})+ superreturn unless user.respond_to?(:market_id) && user.market_idcannot :manage, Spree::Ordercan [:read, :admin], Spree::Order, market_id: user.market_idendend--Spree::Ability.register_ability(RegionalSupportAbility)```-Keep record-state rules ("a completed order cannot be deleted") on models and workflows instead — they must bind every caller, including secret API keys that never consult CanCanCan.-## How enforcement worksEvery Admin API controller declares its resource (`scoped_resource :orders`). Each request checks the principal's keys — a staff member's role permissions on the current store, or a secret key's scopes — against `read_<resource>` or `write_<resource>` for the action. A missing key produces a 403 naming it in `details.required_permission`. Behind that gate, keys compile to CanCanCan rules for record-level concerns, and `GET /api/v3/admin/me` returns both the rule dump the dashboard mirrors and `permission_keys`, the flat key list.-Storefront customers are not part of this system — customer authorization is ownership, enforced by the Store API's scoped lookups, with nothing to configure.+Storefront customers are not part of this system — customer authorization is ownership, enforced by the Store API's scoped lookups, with nothing to configure. The one swappable piece is `Spree::Storefront::AccessPolicy` (via `Spree::Dependencies.storefront_access_policy_class`), which decides cart and order access for owners and guest-token bearers; replace it only when access must widen beyond the owner, such as company accounts.diff --git a/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb b/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rbindex 39db20d08f..22451cafac 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb@@ -6,23 +6,29 @@ module Spreeprotected- # Find cart by prefixed ID and authorize access via CanCanCan.- # Completed carts are not carts anymore — they 404 unless the caller- # opts in (idempotent completion, payment-session confirm races).+ # Find cart by prefixed ID and authorize read access (owner or guest+ # token). Completed carts are not carts anymore — they 404 unless the+ # caller opts in (idempotent completion, payment-session confirm races).# @return [Spree::Cart]def find_cart(include_completed: false)@cart = resolve_cart(include_completed: include_completed)- authorize!(:show, @cart, cart_token)+ authorize_purchase_read!(@cart, cart_token)@cartend- # Find the cart and authorize it for update. A completed cart resolves- # only for opted-in flows, where mutation is impossible — :show is the- # right check there (the ability denies :update once completed).+ # Find the cart and authorize it for mutation. A completed cart+ # resolves only for opted-in flows, where mutation is impossible — a+ # read check is the right bar there.# @return [Spree::Cart]def find_cart!(include_completed: false)@cart = resolve_cart(include_completed: include_completed)- authorize!(@cart.completed? ? :show : :update, @cart, cart_token)++ if @cart.completed?+ authorize_purchase_read!(@cart, cart_token)+ else+ authorize_purchase_write!(@cart, cart_token)+ end+@cartenddiff --git a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rbindex 40dc319458..c405ca1317 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb@@ -90,6 +90,7 @@ module Spree# Override base controller error handlersrescue_from ActiveRecord::RecordNotFound, with: :handle_record_not_foundrescue_from CanCan::AccessDenied, with: :handle_access_denied+ rescue_from Spree::Storefront::AccessDenied, with: :handle_access_deniedrescue_from Spree::Core::GatewayError, with: :handle_gateway_errorrescue_from ActionController::ParameterMissing, with: :handle_parameter_missingrescue_from ActiveRecord::RecordInvalid, with: :handle_record_invaliddiff --git a/spree/api/app/controllers/concerns/spree/api/v3/storefront_access.rb b/spree/api/app/controllers/concerns/spree/api/v3/storefront_access.rbnew file mode 100644index 0000000000..351e0664ef--- /dev/null+++ b/spree/api/app/controllers/concerns/spree/api/v3/storefront_access.rb@@ -0,0 +1,38 @@+module Spree+ module Api+ module V3+ # Storefront access checks backed by Spree::Storefront::AccessPolicy —+ # the Store API's replacement for CanCanCan. Ownership scoping remains+ # the primary enforcement; these helpers cover the checks a scope cannot+ # express (guest-token access to a specific cart or order).+ module StorefrontAccess+ extend ActiveSupport::Concern++ protected++ def storefront_access_policy+ @storefront_access_policy ||= Spree.storefront_access_policy_class.new(+ user: current_user,+ store: current_store+ )+ end++ # @raise [Spree::Storefront::AccessDenied] when the caller can neither+ # prove ownership nor present the purchase's guest token+ def authorize_purchase_read!(purchase, token)+ return if storefront_access_policy.purchase_readable?(purchase, token: token)++ raise Spree::Storefront::AccessDenied+ end++ # @raise [Spree::Storefront::AccessDenied] when unreadable or already+ # completed+ def authorize_purchase_write!(purchase, token)+ return if storefront_access_policy.purchase_writable?(purchase, token: token)++ raise Spree::Storefront::AccessDenied+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rbindex 12dffa6ea9..2e9f98ab8c 100644--- a/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb@@ -15,6 +15,25 @@ module Spreeauthenticate_admin!end+ # CanCanCan lives on the admin branch only. The shared base leaves+ # these as no-ops because the Store API authorizes by ownership+ # scoping; back-office callers are authorized per record and per+ # collection by their role's catalog keys.+ def scope+ base_scope = super+ return base_scope if @parent.present?++ base_scope.accessible_by(current_ability, ability_action_for_request)+ end++ def authorize_resource!(resource = @resource, action = action_name.to_sym)+ authorize!(action, resource)+ end++ def authorize_parent!(parent)+ authorize!(parent_ability_action, parent)+ end+# Render error from ServiceModule::Result, extracting ActiveModel::Errors# from the ResultError wrapper to get proper validation_error responses.def decode_ids(ids, klass)diff --git a/spree/api/app/controllers/spree/api/v3/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/resource_controller.rbindex 9320c78fe3..8fc2df897d 100644--- a/spree/api/app/controllers/spree/api/v3/resource_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/resource_controller.rb@@ -123,10 +123,11 @@ module Spreescope.find_by_prefix_id!(params[:id])end- # Authorize resource with CanCanCan- def authorize_resource!(resource = @resource, action = action_name.to_sym)- authorize!(action, resource)- end+ # Per-record authorization hook. A no-op in the shared base: the Store+ # API's resources are reachable only through owner-scoped queries, so+ # loading one already proves the caller may act on it. The Admin API+ # overrides this with a CanCanCan check.+ def authorize_resource!(resource = @resource, action = action_name.to_sym); end# Returns ransack-filtered, sorted and paginated collection# ar_lazy_preload handles automatic association preloading@@ -251,15 +252,16 @@ module Spree}end- # Base scope with store and ability- # When @parent is set (nested resources), uses parent association instead+ # Base scope, store-scoped (or parent-scoped for nested resources).+ # Deliberately free of CanCanCan: the Store API authorizes by ownership+ # — every account controller scopes through `current_user` — while the+ # Admin API layers `accessible_by` on top in its own subclass.def scopebase_scope = if @parent.present?@parent.send(parent_association)elsemodel_class.for_store(current_store)end- base_scope = base_scope.accessible_by(current_ability, ability_action_for_request) unless @parent.present?base_scope = base_scope.includes(scope_includes) if scope_includes.any?base_scope = base_scope.preload_associations_lazilymodel_class.include?(Spree::TranslatableResource) ? base_scope.i18n : base_scope@@ -300,12 +302,11 @@ module Spreeread_actions.include?(action_name) ? :show : :updateend- # Authorizes the parent resource for nested controllers: a role that- # can view a parent can't mutate its nested collection. Call from- # +set_parent+ after loading the parent.- def authorize_parent!(parent)- authorize!(parent_ability_action, parent)- end+ # Parent authorization hook for nested controllers. A no-op in the+ # shared base for the same reason as +authorize_resource!+; the Admin+ # API overrides it so a role that can only view a parent cannot mutate+ # its nested collection.+ def authorize_parent!(parent); end# Override to specify the association name on @parent# Defaults to controller_name (e.g., 'wished_items' for WishlistItemsController)diff --git a/spree/api/app/controllers/spree/api/v3/store/base_controller.rb b/spree/api/app/controllers/spree/api/v3/store/base_controller.rbindex 5fa25c7f58..86f034ddb4 100644--- a/spree/api/app/controllers/spree/api/v3/store/base_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/base_controller.rb@@ -13,6 +13,7 @@ module Spree# ResourceController ones. Public endpoints opt out with# +allow_guest_storefront_access!+.include Spree::Api::V3::StorefrontGating+ include Spree::Api::V3::StorefrontAccess# Require publishable API key for all Store API requests. Prepended so# the key is authenticated BEFORE ChannelResolution'sdiff --git a/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rbindex f8a9de3f32..2b172ce390 100644--- a/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb@@ -73,7 +73,7 @@ module Spreeprivatedef variant- @variant ||= current_store.variants.accessible_by(current_ability).find_by_prefix_id!(permitted_params[:variant_id])+ @variant ||= current_store.variants.find_by_prefix_id!(permitted_params[:variant_id])enddef permitted_paramsdiff --git a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rbindex 5296925122..21b75b81a3 100644--- a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb@@ -90,7 +90,7 @@ module Spree# is already the caller's own.def associate@cart = find_cart_for_association- authorize!(:update, @cart, cart_token)+ authorize_purchase_write!(@cart, cart_token)require_cart_token!result = Spree.cart_associate_service.call(guest_cart: @cart, customer: current_user, guest_only: true)@@ -130,7 +130,7 @@ module Spree# prefixes never decode against carts, so this only fires for# order_ ids (or genuinely unknown ids, which 404 below).@cart = current_store.orders.complete.find_by_prefix_id!(params[:id])- authorize!(:show, @cart, cart_token)+ authorize_purchase_read!(@cart, cart_token)render_orderend@@ -198,7 +198,7 @@ module Spreedef require_cart_token!valid = cart_token.present? && cart_token == @cart.token- raise CanCan::AccessDenied.new(nil, :update, @cart) unless valid+ raise Spree::Storefront::AccessDenied unless validendendenddiff --git a/spree/api/app/controllers/spree/api/v3/store/collections/products_controller.rb b/spree/api/app/controllers/spree/api/v3/store/collections/products_controller.rbindex 5063600ce3..f44db23b0e 100644--- a/spree/api/app/controllers/spree/api/v3/store/collections/products_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/collections/products_controller.rb@@ -14,7 +14,7 @@ module Spreereturn @collection if @collection.present?result = search_provider.search_and_filter(- scope: scope.includes(collection_includes).preload_associations_lazily.accessible_by(current_ability, :show),+ scope: scope.includes(collection_includes).preload_associations_lazily,query: search_query,filters: (search_filters || {}).merge('in_collection' => current_collection.prefixed_id),sort: sort_param.presence || collection_default_sort,diff --git a/spree/api/app/controllers/spree/api/v3/store/customer/store_credits_controller.rb b/spree/api/app/controllers/spree/api/v3/store/customer/store_credits_controller.rbindex 7e3fc3b1ed..f7b8f47fde 100644--- a/spree/api/app/controllers/spree/api/v3/store/customer/store_credits_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/customer/store_credits_controller.rb@@ -28,9 +28,6 @@ module SpreeSpree.api.store_credit_serializerend- # Authorization is handled by set_parent scoping to current_user- def authorize_resource!(*)- endendendenddiff --git a/spree/api/app/controllers/spree/api/v3/store/delivery_methods_controller.rb b/spree/api/app/controllers/spree/api/v3/store/delivery_methods_controller.rbindex 7a739319e0..1bd9751b97 100644--- a/spree/api/app/controllers/spree/api/v3/store/delivery_methods_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/delivery_methods_controller.rb@@ -60,7 +60,7 @@ module Spreereturn @pickup_cart = nil if params[:cart_id].blank?cart = current_store.carts.incomplete.find_by_prefix_id!(params[:cart_id])- authorize!(:show, cart, request.headers['x-spree-token'])+ authorize_purchase_read!(cart, request.headers['x-spree-token'])@pickup_cart = cartenddiff --git a/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb b/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rbindex e1274fce5a..aac6048352 100644--- a/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb@@ -117,7 +117,7 @@ module SpreeSpree::NewsletterSubscriber.for_store(current_store).- accessible_by(current_ability, :destroy).+ where(user_id: current_user.id).find_by_prefix_id(params[:id])enddiff --git a/spree/api/app/controllers/spree/api/v3/store/orders/claims_controller.rb b/spree/api/app/controllers/spree/api/v3/store/orders/claims_controller.rbindex f6f01180b4..30132f2e15 100644--- a/spree/api/app/controllers/spree/api/v3/store/orders/claims_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/orders/claims_controller.rb@@ -50,7 +50,6 @@ module Spreeelseorder_scope.find_by_prefix_id!(params[:order_id])end- authorize!(:show, @parent, order_token)end# Authorization is the parent order's — see the returns@@ -60,15 +59,7 @@ module Spreeenddef order_scope- base = current_store.orders.complete-- if current_user.present?- base.where(customer: current_user)- elsif order_token.present?- base.where(token: order_token)- else- base.none- end+ storefront_access_policy.orders_scope(current_store.orders.complete, token: order_token)enddef create_paramsdiff --git a/spree/api/app/controllers/spree/api/v3/store/orders/returns_controller.rb b/spree/api/app/controllers/spree/api/v3/store/orders/returns_controller.rbindex 110cdd103d..61c978fd46 100644--- a/spree/api/app/controllers/spree/api/v3/store/orders/returns_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/orders/returns_controller.rb@@ -46,10 +46,7 @@ module Spree# Authorization is the parent order's: set_parent already proved# this customer owns it (by JWT or guest token), and the scope is- # that order's own returns. A second record-level ability check- # would require giving customers a CanCanCan rule for- # Spree::Return, which would be a broader grant than the order- # ownership this endpoint actually depends on.+ # that order's own returns.def set_resource@resource = find_resourceend@@ -63,19 +60,10 @@ module Spreeelseorder_scope.find_by_prefix_id!(params[:order_id])end- authorize!(:show, @parent, order_token)enddef order_scope- base = current_store.orders.complete-- if current_user.present?- base.where(customer: current_user)- elsif order_token.present?- base.where(token: order_token)- else- base.none- end+ storefront_access_policy.orders_scope(current_store.orders.complete, token: order_token)enddef create_paramsdiff --git a/spree/api/app/controllers/spree/api/v3/store/orders_controller.rb b/spree/api/app/controllers/spree/api/v3/store/orders_controller.rbindex cd41e14320..12fa72acd0 100644--- a/spree/api/app/controllers/spree/api/v3/store/orders_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/orders_controller.rb@@ -19,19 +19,10 @@ module Spreedef find_order!cart_pk = Spree::Cart.decode_own_prefixed_id(params[:id])@order = cart_pk ? scope.find_by!(cart_id: cart_pk) : scope.find_by_prefix_id!(params[:id])- authorize!(:show, @order, order_token)enddef scope- base = current_store.orders.complete-- if current_user.present?- base.where(customer: current_user)- elsif order_token.present?- base.where(token: order_token)- else- base.none- end+ storefront_access_policy.orders_scope(current_store.orders.complete, token: order_token)enddef serializer_classdiff --git a/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb b/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rbindex 01ab2befc8..4f5a6cbed6 100644--- a/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb@@ -59,7 +59,7 @@ module Spreescope = current_store.products.available(Time.current, current_currency, include_preorderable: true)scope = scope.in_category(category) if category.present?scope = scope.in_collection(collection) if collection.present?- scope.accessible_by(current_ability, :show)+ scopeenddef categorydiff --git a/spree/api/app/controllers/spree/api/v3/store/products_controller.rb b/spree/api/app/controllers/spree/api/v3/store/products_controller.rbindex 0b3295910a..963b8b96a8 100644--- a/spree/api/app/controllers/spree/api/v3/store/products_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/products_controller.rb@@ -48,7 +48,7 @@ module Spreereturn @collection if @collection.present?result = search_provider.search_and_filter(- scope: scope.includes(collection_includes).preload_associations_lazily.accessible_by(current_ability, :show),+ scope: scope.includes(collection_includes).preload_associations_lazily,query: search_query,filters: search_filters,sort: sort_param,diff --git a/spree/api/app/controllers/spree/api/v3/store/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/store/resource_controller.rbindex 9ebc89673c..f2e5b8daa0 100644--- a/spree/api/app/controllers/spree/api/v3/store/resource_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/resource_controller.rb@@ -8,6 +8,7 @@ module Spreeclass ResourceController < Spree::Api::V3::ResourceControllerinclude Spree::Api::V3::ChannelResolutioninclude Spree::Api::V3::StorefrontGating+ include Spree::Api::V3::StorefrontAccess# The inherited +set_parent+/+set_resource+ callbacks were registered# before the two concerns above, so they'd run resource lookups aheaddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/resource_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/resource_controller_spec.rbnew file mode 100644index 0000000000..ba258fabc9--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/resource_controller_spec.rb@@ -0,0 +1,81 @@+require 'spec_helper'++# Unit spec for `Spree::Api::V3::Admin::ResourceController#scope` — CanCanCan+# lives on the admin branch only. The scope infers the ability action from+# `request.method` and narrows the relation via `accessible_by`, but only when+# there's no `@parent` (nested resources defer to their parent's+# authorization).+RSpec.describe Spree::Api::V3::Admin::ResourceController, type: :controller do+ controller(described_class) do+ def model_class+ Spree::TaxCategory+ end++ public :scope+ end++ let(:store) { @default_store || create(:store, default: true) }+ let!(:default_tax_category) { create(:tax_category, name: 'Default', is_default: true) }+ let!(:other_tax_category) { create(:tax_category, name: 'Other') }++ before do+ allow(controller).to receive(:current_store).and_return(store)+ end++ describe '#scope without @parent' do+ # Each HTTP method should narrow with a different CanCanCan action.+ # We prove that by giving the ability rule a different visible set+ # per action and asserting which slice comes back.+ {+ 'GET' => :show,+ 'HEAD' => :show,+ 'POST' => :create,+ 'PATCH' => :update,+ 'PUT' => :update,+ 'DELETE' => :destroy+ }.each do |http_method, expected_action|+ it "narrows via accessible_by(_, :#{expected_action}) on #{http_method}" do+ ability = Spree::Ability.new(nil)+ ability.cannot :manage, Spree::TaxCategory+ # Only the expected action sees the default record; every other+ # action sees nothing. If the method-to-action mapping is wrong,+ # the wrong slice will be returned.+ ability.can expected_action, Spree::TaxCategory, is_default: true+ allow(controller).to receive(:current_ability).and_return(ability)+ allow(request).to receive(:method).and_return(http_method)++ ids = controller.scope.pluck(:id)++ expect(ids).to contain_exactly(default_tax_category.id)+ end+ end++ it 'raises MethodNotAllowed (405) on unsupported HTTP methods' do+ allow(controller).to receive(:current_ability).and_return(Spree::Ability.new(nil))+ allow(request).to receive(:method).and_return('TRACE')++ expect { controller.scope }.to raise_error(ActionController::MethodNotAllowed)+ end+ end++ describe '#scope with @parent' do+ # When loading a nested resource the parent is assumed to have+ # been authorized at `set_parent` time — the per-action narrowing+ # is deliberately skipped so the parent's permissions win.+ let(:promotion) { create(:promotion) }++ before do+ controller.instance_variable_set(:@parent, promotion)+ allow(controller).to receive(:parent_association).and_return(:promotion_rules)+ allow_any_instance_of(ActiveRecord::Relation).to receive(:accessible_by).and_wrap_original do |_method, *|+ raise 'accessible_by should not be called when @parent is present'+ end+ allow(request).to receive(:method).and_return('DELETE')+ end++ it 'returns the parent association without invoking accessible_by' do+ expect { controller.scope }.not_to raise_error+ expect(controller.scope.klass).to eq(Spree::PromotionRule)+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/resource_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/resource_controller_spec.rbindex 626a9943a4..840dfd14fc 100644--- a/spree/api/spec/controllers/spree/api/v3/resource_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/resource_controller_spec.rb@@ -1,14 +1,11 @@require 'spec_helper'# Unit spec for `Spree::Api::V3::ResourceController#scope` — the base-# scope-resolution method shared by every admin/store resource. The-# new behavior (post-`scope_for` removal in subclasses) infers the-# CanCanCan action from `request.method` and narrows the relation-# via `accessible_by`, but only when there's no `@parent` (nested-# resources defer to their parent's authorization).+# scope-resolution shared by every admin/store resource. The shared base+# carries no authorization framework: it scopes to the store (or the parent+# association) and never consults CanCanCan. The admin branch layers+# `accessible_by` on top — see the Admin::ResourceController spec.RSpec.describe Spree::Api::V3::ResourceController, type: :controller do- # Minimal subclass — we only need `model_class` and a way to call- # `scope` from outside.controller(described_class) dodef model_classSpree::TaxCategory@@ -23,74 +20,28 @@ RSpec.describe Spree::Api::V3::ResourceController, type: :controller dobefore doallow(controller).to receive(:current_store).and_return(store)+ allow(request).to receive(:method).and_return('GET')end- describe '#scope without @parent' do- # Each HTTP method should narrow with a different CanCanCan action.- # We prove that by giving the ability rule a different visible set- # per action and asserting which slice comes back.- {- 'GET' => :show,- 'HEAD' => :show,- 'POST' => :create,- 'PATCH' => :update,- 'PUT' => :update,- 'DELETE' => :destroy- }.each do |http_method, expected_action|- it "narrows via accessible_by(_, :#{expected_action}) on #{http_method}" do- ability = Spree::Ability.new(nil)- ability.cannot :manage, Spree::TaxCategory- # Only the expected action sees the default record; every other- # action sees nothing. If the method-to-action mapping is wrong,- # the wrong slice will be returned.- ability.can expected_action, Spree::TaxCategory, is_default: true- allow(controller).to receive(:current_ability).and_return(ability)- allow(request).to receive(:method).and_return(http_method)-- ids = controller.scope.pluck(:id)-- expect(ids).to contain_exactly(default_tax_category.id)- end- end-- it 'raises MethodNotAllowed (405) on unsupported HTTP methods' do- allow(controller).to receive(:current_ability).and_return(Spree::Ability.new(nil))- allow(request).to receive(:method).and_return('TRACE')-- expect { controller.scope }.to raise_error(ActionController::MethodNotAllowed)- end-+ describe '#scope' doit 'returns a model_class relation' do- allow(controller).to receive(:current_ability).and_return(Spree::Ability.new(nil))- allow(request).to receive(:method).and_return('GET')-expect(controller.scope).to be_a(ActiveRecord::Relation)expect(controller.scope.klass).to eq(Spree::TaxCategory)end- end-- describe '#scope with @parent' do- # When loading a nested resource the parent is assumed to have- # been authorized at `set_parent` time — the per-action narrowing- # is deliberately skipped so the parent's permission set wins.- let(:promotion) { create(:promotion) }- before do- controller.instance_variable_set(:@parent, promotion)- allow(controller).to receive(:parent_association).and_return(:promotion_rules)- # Anything the controller forwards into accessible_by would be a- # bug now — block it loudly rather than letting the test pass- # quietly by coincidence.+ it 'does not narrow via accessible_by — authorization is not the base scope''s job' doallow_any_instance_of(ActiveRecord::Relation).to receive(:accessible_by).and_wrap_original do |_method, *|- raise 'accessible_by should not be called when @parent is present'+ raise 'accessible_by should not be called by the shared base scope'end- # `request.method` would matter for the ability branch; assert- # the branch is skipped regardless of method.- allow(request).to receive(:method).and_return('DELETE')++ expect(controller.scope.pluck(:id)).to contain_exactly(default_tax_category.id, other_tax_category.id)end- it 'returns the parent association without invoking accessible_by' do- expect { controller.scope }.not_to raise_error+ it 'uses the parent association when @parent is present' do+ promotion = create(:promotion)+ controller.instance_variable_set(:@parent, promotion)+ allow(controller).to receive(:parent_association).and_return(:promotion_rules)+expect(controller.scope.klass).to eq(Spree::PromotionRule)endenddiff --git a/spree/core/app/models/spree/ability.rb b/spree/core/app/models/spree/ability.rbindex 88c94b4c8c..dcd5453100 100644--- a/spree/core/app/models/spree/ability.rb+++ b/spree/core/app/models/spree/ability.rb@@ -1,28 +1,16 @@-# CanCanCan ability for both halves of Spree authorization:+# CanCanCan ability for staff (back-office) authorization only: admin-user+# principals are authorized through the permission catalog — their+# store-scoped roles hold flat `read_<resource>` / `write_<resource>` keys+# (see Spree::PermissionConfiguration and docs/plans/6.0-admin-rbac.md),+# which compile to CanCanCan rules here. The `admin` role grants everything.#-# - **Staff** (admin-user principals) are authorized through the permission-# catalog: their store-scoped roles hold flat `read_<resource>` /-# `write_<resource>` keys (see Spree::PermissionConfiguration and-# docs/plans/6.0-admin-rbac.md), which compile to CanCanCan rules here. The-# `admin` role grants everything.-# - **Customers and guests** get the fixed storefront baseline: read the-# catalog, own their carts/orders/account. It is not configurable and is not-# part of the permission catalog — customer authorization is ownership, not-# RBAC.-#-# Host applications needing rules the catalog cannot express (record-level-# conditions, regional restrictions) register a plain CanCan::Ability class:-#-# class RegionalSupportAbility-# include CanCan::Ability-#-# def initialize(user)-# can :read, Spree::Order, market_id: user.market_id if user-# end-# end-#-# Spree::Ability.register_ability(RegionalSupportAbility)+# Customers and guests never touch CanCanCan: the Store API authorizes by+# ownership-scoped queries plus Spree::Storefront::AccessPolicy (carried by+# `Spree::Dependencies.storefront_access_policy_class`). An ability built for+# a customer principal simply has no rules.#+# Replace the whole class via `Spree::Dependencies.ability_class` when an+# application needs rules the catalog cannot express.require 'cancan'module Spree@@ -37,29 +25,9 @@ module Spreeattr_reader :store# @return [Array<String>] the expanded catalog keys this ability activated- # (empty for storefront principals). Feeds `/me` and the admin key gate.+ # (empty for non-staff principals). Feeds `/me` and the admin key gate.attr_reader :permission_keys- class << self- # Registers an extra ability class merged into every Spree::Ability.- #- # @param ability_class [Class] a CanCan::Ability whose initializer takes- # the user- def register_ability(ability_class)- abilities.add(ability_class)- end-- # @param ability_class [Class]- def remove_ability(ability_class)- abilities.delete(ability_class)- end-- # @return [Set<Class>]- def abilities- @abilities ||= Set.new- end- end-def initialize(user, options = {})alias_cancan_delete_action@@ -67,15 +35,12 @@ module Spree@store = options[:store] || Spree::Current.store@permission_keys = []- apply_storefront_permissions if storefront_principal?apply_staff_permissions if staff_principal?-- merge_registered_abilitiesend# Applies a single catalog key's grants and records it as activated.- # Public so `register_ability` classes and host subclasses can grant- # catalog capabilities in the same currency the key gate checks.+ # Public so host subclasses can grant catalog capabilities in the same+ # currency the key gate checks.## @param key [String, Symbol] a catalog key (`'write_orders'`)# @return [Boolean] whether the key resolved@@ -100,14 +65,6 @@ module Spree@user.persisted? && @user.is_a?(Spree.admin_user_class)end- # Customers and guests get the storefront baseline. When the host shares- # one class between customers and admin users (the install generator does- # this when only `user_class` is provided), a persisted user is both — the- # baseline applies alongside staff role resolution.- def storefront_principal?- !staff_principal? || Spree.admin_user_class == Spree.customer_class- end-# --- staff ---def apply_staff_permissions@@ -162,91 +119,5 @@ module Spreecan :read, Spree::Storeend- # --- storefront (customers and guests) ----- # The fixed storefront baseline: browse the catalog, own your cart, order- # and account. Ownership is expressed through hash conditions and cart- # tokens; the Store API's scope-fetching remains the primary enforcement.- def apply_storefront_permissions- apply_storefront_catalog_permissions- apply_storefront_purchase_permissions- apply_storefront_account_permissions- end-- def apply_storefront_catalog_permissions- can :read, Spree::Collection- can :read, Spree::Country- can :read, Spree::OptionType- can :read, Spree::OptionValue- can :read, Spree::Product- can :read, Spree::State- can :read, Spree::Store- can :read, Spree::Category- can :read, Spree::Taxonomy- can :read, Spree::Variant- can :read, Spree::Zone- can :read, Spree::Policy- end-- def apply_storefront_purchase_permissions- can :create, Spree::Order- can :show, Spree::Order do |order, token|- order.customer == user || order.token && token == order.token- end- can :update, Spree::Order do |order, token|- !order.completed? && (order.customer == user || order.token && token == order.token)- end-- can :create, Spree::Cart- can :show, Spree::Cart do |cart, token|- cart.customer == user || cart.token && token == cart.token- end- can [:update, :destroy], Spree::Cart do |cart, token|- !cart.completed? && (cart.customer == user || cart.token && token == cart.token)- end-- can :create, Spree::LineItem do |line_item, token|- owner = line_item.owner- owner.customer == user || owner.token && token == owner.token- end- can [:update, :destroy], Spree::LineItem do |line_item, token|- owner = line_item.owner- !owner.completed? && (owner.customer == user || owner.token && token == owner.token)- end-- # Digital downloads - token-based access- can :show, Spree::DigitalLink do |digital_link, token|- digital_link.token == token- end- end-- def apply_storefront_account_permissions- can :create, Spree.customer_class- can [:show, :update, :destroy], Spree.customer_class, id: user.id-- can :manage, Spree::Address, user_id: user.id if user.persisted?- can [:read, :destroy], Spree::CreditCard, user_id: user.id- can :read, Spree::GiftCard, user_id: user.id- can [:show, :destroy], Spree::NewsletterSubscriber, user_id: user.id-- can :manage, Spree::Wishlist, user_id: user.id- can :show, Spree::Wishlist do |wishlist|- wishlist.customer == user || wishlist.is_private == false- end- can [:create, :update, :destroy], Spree::WishedItem do |wished_item|- wished_item.wishlist.customer == user- end-- can :accept, Spree::Invitation,- invitee_id: [user.id, nil], invitee_type: user.class.name, status: 'pending'- end-- # --- extensions ----- def merge_registered_abilities- self.class.abilities.each do |ability_class|- merge(ability_class.new(@user))- end- endendenddiff --git a/spree/core/app/models/spree/export.rb b/spree/core/app/models/spree/export.rbindex e5b09da4b2..450962e832 100644--- a/spree/core/app/models/spree/export.rb+++ b/spree/core/app/models/spree/export.rb@@ -134,7 +134,10 @@ module Spreescope = model_classscope = scope.for_store(store) if model_class.respond_to?(:for_store)scope = scope.for_vendor(vendor) if model_class.respond_to?(:for_vendor) && vendor.present?- scope.accessible_by(current_ability)+ # A staff-created export only contains what its creator may read; a+ # userless export (console, system jobs) is unfiltered.+ scope = scope.accessible_by(current_ability) if user.present?+ scopeenddef records_to_exportdiff --git a/spree/core/app/models/spree/storefront/access_denied.rb b/spree/core/app/models/spree/storefront/access_denied.rbnew file mode 100644index 0000000000..9f25f75689--- /dev/null+++ b/spree/core/app/models/spree/storefront/access_denied.rb@@ -0,0 +1,22 @@+module Spree+ module Storefront+ # Raised when a storefront access check fails. Rendered by the API's+ # error handler as the same 403 payload CanCan::AccessDenied produces on+ # the admin side, so the two branches stay indistinguishable to clients.+ class AccessDenied < StandardError+ DEFAULT_MESSAGE = 'You are not authorized to access this page.'.freeze++ def initialize(message = nil)+ super(message || default_message)+ end++ private++ # CanCan's key first, so a host that translated admin denials gets the+ # same wording here.+ def default_message+ I18n.t(:default, scope: :unauthorized, default: DEFAULT_MESSAGE)+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/storefront/access_policy.rb b/spree/core/app/models/spree/storefront/access_policy.rbnew file mode 100644index 0000000000..4dc1927ee6--- /dev/null+++ b/spree/core/app/models/spree/storefront/access_policy.rb@@ -0,0 +1,75 @@+module Spree+ module Storefront+ # Storefront record access in one swappable object. The Store API never+ # consults CanCanCan — customer authorization is ownership, enforced by+ # scope-fetching, with this policy holding the two checks that cannot be a+ # scope (cart/order access proven by JWT ownership OR a guest token) and+ # the ownership scopes worth widening.+ #+ # This class is the storefront's extension seam: replace it via+ # `Spree::Dependencies.storefront_access_policy_class` when access must+ # widen beyond the owner — e.g. B2B company accounts where an approver+ # sees every purchase placed by their company location+ # (docs/plans/6.1-channels-catalogs-b2b.md). Action vetoes (approval+ # required, spending limits) do not belong here — they are checkout+ # workflow `validate` hooks.+ class AccessPolicy+ # @return [Object, nil] the authenticated customer, or nil for guests+ attr_reader :user++ # @return [Spree::Store]+ attr_reader :store++ def initialize(user:, store:)+ @user = user+ @store = store+ end++ # Whether the caller may read a cart or order: its owner (by JWT) or the+ # bearer of its guest token.+ #+ # @param purchase [Spree::Cart, Spree::Order]+ # @param token [String, nil] the X-Spree-Token header value+ # @return [Boolean]+ def purchase_readable?(purchase, token: nil)+ purchase_owner?(purchase) || purchase_token_match?(purchase, token)+ end++ # Whether the caller may mutate a cart or order — readable and not yet+ # completed.+ #+ # @param purchase [Spree::Cart, Spree::Order]+ # @param token [String, nil]+ # @return [Boolean]+ def purchase_writable?(purchase, token: nil)+ !purchase.completed? && purchase_readable?(purchase, token: token)+ end++ # The completed orders the caller may list and look up. Owner-only by+ # default; the guest-token branch serves order-confirmation lookups.+ #+ # @param base [ActiveRecord::Relation] pre-scoped orders (store, complete)+ # @param token [String, nil]+ # @return [ActiveRecord::Relation]+ def orders_scope(base, token: nil)+ if user.present?+ base.where(customer: user)+ elsif token.present?+ base.where(token: token)+ else+ base.none+ end+ end++ protected++ def purchase_owner?(purchase)+ user.present? && purchase.customer == user+ end++ def purchase_token_match?(purchase, token)+ purchase.token.present? && token == purchase.token+ end+ end+ end+enddiff --git a/spree/core/config/i18n-tasks.yml b/spree/core/config/i18n-tasks.ymlindex 8642d48919..1f3483af04 100644--- a/spree/core/config/i18n-tasks.yml+++ b/spree/core/config/i18n-tasks.yml@@ -137,9 +137,10 @@ search:# # Keep in mind the context of all the strings for a more accurate translation.## Do not consider these keys missing:-# ignore_missing:-# - 'errors.messages.{accepted,blank,invalid,too_short,too_long}'-# - '{devise,simple_form}.*'+ignore_missing:+ # CanCan's namespace — Spree::Storefront::AccessDenied reads it with an+ # inline English default so the two 403 branches share host translations.+ - 'unauthorized.default'## Consider these keys used:# ignore_unused:diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rbindex 108e421c92..189e46419a 100644--- a/spree/core/lib/spree/core/dependencies.rb+++ b/spree/core/lib/spree/core/dependencies.rb@@ -4,9 +4,13 @@ module Spreemodule Coreclass DependenciesINJECTION_POINTS_WITH_DEFAULTS = {- # ability+ # ability (staff / back-office authorization)ability_class: 'Spree::Ability',+ # storefront record access (ownership + guest tokens); the B2B seam —+ # see Spree::Storefront::AccessPolicy+ storefront_access_policy_class: 'Spree::Storefront::AccessPolicy',+# cart — the legacy Spree::Cart::* namespace is gone (Spree::Cart is the# cart model since 6.0); surviving services live under Spree::Carts::.# cart_create/update/estimate_shipping_rates/change_currency servicediff --git a/spree/core/lib/spree/core/permission_configuration.rb b/spree/core/lib/spree/core/permission_configuration.rbindex 8e036e453e..5e8500f97f 100644--- a/spree/core/lib/spree/core/permission_configuration.rb+++ b/spree/core/lib/spree/core/permission_configuration.rb@@ -220,7 +220,6 @@ module Spree'Permission sets were removed in Spree 6.0. Remove the permission lines from ' \'config/initializers/spree.rb — roles and their permissions are data now, ' \'managed in the dashboard (Settings → Roles), via the Admin API, or in seeds. ' \- 'For record-level custom rules use Spree::Ability.register_ability. ' \"Upgrade guide: https://spreecommerce.org/docs/developer/upgrades/5.6-to-6.0"end@@ -248,7 +247,7 @@ module SpreeSpree::Asset, Spree::ProductPublication, Spree::Metafield]})register_resource(:categories, group: :catalog, subjects: -> {- [Spree::Category, Spree::Taxonomy, Spree::ProductCategory]+ [Spree::Category, Spree::ProductCategory]})register_resource(:collections, group: :catalog, subjects: -> {[Spree::Collection, Spree::ProductCollection, Spree::CollectionRule]diff --git a/spree/core/spec/models/spree/ability_spec.rb b/spree/core/spec/models/spree/ability_spec.rbindex c7a466f272..e02e1c3405 100644--- a/spree/core/spec/models/spree/ability_spec.rb+++ b/spree/core/spec/models/spree/ability_spec.rb@@ -267,7 +267,7 @@ describe Spree::Ability, type: :model dodescribe 'shared customer/admin user class' do# The install generator falls back to `user_class` for the admin user class# when a host provides only one — persisted customers are then admin-class- # principals and must keep the storefront baseline alongside role resolution.+ # principals and resolve staff roles like any admin user.around do |example|original = Spree.admin_user_class(constantize: false)Spree.admin_user_class = Spree.customer_class.to_s@@ -276,16 +276,15 @@ describe Spree::Ability, type: :model doSpree.admin_user_class = originalend- it 'keeps the storefront baseline for persisted customers' do+ it 'grants nothing to customers holding no roles' docustomer = create(:user)shared_ability = Spree::Ability.new(customer, store: store)- expect(shared_ability).to be_able_to :read, Spree::Product- expect(shared_ability).to be_able_to :create, Spree::Orderexpect(shared_ability).not_to be_able_to :manage, Spree::Order.new+ expect(shared_ability.permission_keys).to eq([])end- it 'resolves staff roles without losing the storefront baseline' do+ it 'resolves staff roles for persisted customers' domanager = create(:user)manager.role_users.create!(role: create(:role, name: 'shared_manager', permissions: %w[write_orders]),@@ -294,206 +293,18 @@ describe Spree::Ability, type: :model doshared_ability = Spree::Ability.new(manager, store: store)expect(shared_ability).to be_able_to :manage, Spree::Order.new- expect(shared_ability).to be_able_to :read, Spree::Productendend- describe '.register_ability' do- let(:custom_ability_class) do- Class.new do- include CanCan::Ability+ context 'as a customer or guest principal' do+ it 'has no rules at all — the Store API authorizes by ownership scoping' do+ customer_ability = Spree::Ability.new(create(:user))+ guest_ability = Spree::Ability.new(nil)- def initialize(user)- can :read, Spree::Order if user- end- end- end-- after { Spree::Ability.remove_ability(custom_ability_class) }-- it 'merges registered ability rules into every ability' do- Spree::Ability.register_ability(custom_ability_class)-- expect(Spree::Ability.new(create(:user))).to be_able_to :read, Spree::Order.new- end- end-- context 'as Guest User' do- context 'for Country' do- let(:resource) { Spree::Country.new }-- context 'requested by any user' do- it_behaves_like 'read only'- end- end-- context 'for OptionType' do- let(:resource) { Spree::OptionType.new }-- context 'requested by any user' do- it_behaves_like 'read only'- end- end-- context 'for OptionValue' do- let(:resource) { Spree::OptionType.new }-- context 'requested by any user' do- it_behaves_like 'read only'- end- end-- context 'for Order' do- let(:resource) { Spree::Order.new }-- context 'requested by same user' do- before { resource.user = user }-- it_behaves_like 'access granted'- it_behaves_like 'no index allowed'- end-- context 'requested by other user' do- before { resource.user = Spree.customer_class.new }-- it_behaves_like 'create only'- end-- context 'requested with proper token' do- let(:token) { 'TOKEN123' }-- before { allow(resource).to receive_messages token: token }-- it_behaves_like 'access granted'- it_behaves_like 'no index allowed'- end-- context 'requested with improper token' do- let(:token) { 'FAIL' }-- before { allow(resource).to receive_messages token: token }-- it_behaves_like 'create only'- end- end-- context 'for Product' do- let(:resource) { store.products.new }-- context 'requested by any user' do- it_behaves_like 'read only'- end- end-- context 'for ProductProperty' do- let(:resource) { store.products.new }-- context 'requested by any user' do- it_behaves_like 'read only'- end- end-- context 'for Property' do- let(:resource) { store.products.new }-- context 'requested by any user' do- it_behaves_like 'read only'- end- end-- context 'for State' do- let(:resource) { Spree::State.new }-- context 'requested by any user' do- it_behaves_like 'read only'- end- end-- context 'for Taxons' do- let(:resource) { Spree::Category.new }-- context 'requested by any user' do- it_behaves_like 'read only'- end- end-- context 'for User' do- context 'requested by same user' do- let(:resource) { user }-- it_behaves_like 'access granted'- it_behaves_like 'no index allowed'- end-- context 'requested by other user' do- let(:resource) { create(:user) }-- it_behaves_like 'create only'- end- end-- context 'for Variant' do- let(:resource) { Spree::Variant.new }-- context 'requested by any user' do- it_behaves_like 'read only'- end- end-- context 'for Zone' do- let(:resource) { Spree::Zone.new }-- context 'requested by any user' do- it_behaves_like 'read only'- end- end-- context 'for Address (IDOR vulnerability prevention)' do- let(:guest_address) { create(:address, user_id: nil) }-- context 'with non-persisted guest user' do- let(:guest_user) { Spree.customer_class.new }- let(:guest_ability) { Spree::Ability.new(guest_user) }-- it 'cannot read guest addresses with nil user_id' do- expect(guest_ability).not_to be_able_to :read, guest_address- end-- it 'cannot edit guest addresses with nil user_id' do- expect(guest_ability).not_to be_able_to :edit, guest_address- end-- it 'cannot update guest addresses with nil user_id' do- expect(guest_ability).not_to be_able_to :update, guest_address- end-- it 'cannot destroy guest addresses with nil user_id' do- expect(guest_ability).not_to be_able_to :destroy, guest_address- end-- it 'cannot manage any address' do- expect(guest_ability).not_to be_able_to :manage, guest_address- end- end-- context 'with persisted user' do- let(:persisted_user) { create(:user) }- let(:persisted_ability) { Spree::Ability.new(persisted_user) }- let(:own_address) { create(:address, user_id: persisted_user.id) }-- it 'can manage own address' do- expect(persisted_ability).to be_able_to :manage, own_address- end-- it 'cannot manage guest addresses' do- expect(persisted_ability).not_to be_able_to :manage, guest_address- end-- it 'cannot manage other user addresses' do- other_user = create(:user)- other_address = create(:address, user_id: other_user.id)- expect(persisted_ability).not_to be_able_to :manage, other_address- end+ [customer_ability, guest_ability].each do |ability|+ expect(ability).not_to be_able_to :read, store.products.new+ expect(ability).not_to be_able_to :create, Spree::Order+ expect(ability.permission_keys).to eq([])endendenddiff --git a/spree/core/spec/models/spree/ability_storefront_spec.rb b/spree/core/spec/models/spree/ability_storefront_spec.rbdeleted file mode 100644index 9788c1b5e4..0000000000--- a/spree/core/spec/models/spree/ability_storefront_spec.rb+++ /dev/null@@ -1,200 +0,0 @@-require 'spec_helper'-require 'cancan/matchers'--# The fixed storefront baseline customers and guests get from Spree::Ability —-# formerly the DefaultCustomer permission set, now internal ability code.-RSpec.describe Spree::Ability, 'storefront baseline', type: :model do- let(:user) { create(:user) }- let(:ability) { Spree::Ability.new(user) }-- context 'catalog read access' do- it 'grants read access to Country' do- expect(ability.can?(:read, Spree::Country)).to be true- end-- it 'grants read access to Product' do- expect(ability.can?(:read, Spree::Product)).to be true- end-- it 'grants read access to Variant' do- expect(ability.can?(:read, Spree::Variant)).to be true- end-- it 'grants read access to Category' do- expect(ability.can?(:read, Spree::Category)).to be true- end-- it 'grants read access to Store' do- expect(ability.can?(:read, Spree::Store)).to be true- end- end-- context 'order permissions' do- it 'allows creating orders' do- expect(ability.can?(:create, Spree::Order)).to be true- end-- context 'with user order' do- let(:order) { build(:order, customer: user) }-- it 'allows viewing own order' do- expect(ability.can?(:show, order)).to be true- end-- it 'allows updating own incomplete order' do- allow(order).to receive(:completed?).and_return(false)- expect(ability.can?(:update, order)).to be true- end-- it 'prevents updating own completed order' do- allow(order).to receive(:completed?).and_return(true)- expect(ability.can?(:update, order)).to be false- end- end-- context 'with token' do- let(:order) { build(:order, customer: nil, token: 'secret') }-- it 'allows viewing order with correct token' do- expect(ability.can?(:show, order, 'secret')).to be true- end-- it 'allows updating incomplete order with correct token' do- allow(order).to receive(:completed?).and_return(false)- expect(ability.can?(:update, order, 'secret')).to be true- end-- it 'prevents viewing order with incorrect token' do- expect(ability.can?(:show, order, 'wrong')).to be false- end- end- end-- context 'user account permissions' do- it 'allows viewing own user' do- expect(ability.can?(:show, user)).to be true- end-- it 'allows updating own user' do- expect(ability.can?(:update, user)).to be true- end-- it 'allows destroying own user' do- expect(ability.can?(:destroy, user)).to be true- end-- it 'prevents viewing other user' do- other_user = create(:user)- expect(ability.can?(:show, other_user)).to be false- end-- it 'allows creating new user' do- expect(ability.can?(:create, Spree.customer_class)).to be true- end- end-- context 'with non-persisted user' do- let(:guest_user) { build(:user) }- let(:guest_ability) { Spree::Ability.new(guest_user) }-- it 'allows viewing self' do- expect(guest_ability.can?(:show, guest_user)).to be true- end-- it 'allows updating self' do- expect(guest_ability.can?(:update, guest_user)).to be true- end- end-- context 'address permissions' do- let(:own_address) { build(:address, user_id: user.id) }- let(:other_address) { build(:address, user_id: create(:user).id) }-- it 'allows managing own address' do- expect(ability.can?(:manage, own_address)).to be true- end-- it 'prevents managing other user address' do- expect(ability.can?(:manage, other_address)).to be false- end-- context 'with guest user (non-persisted)' do- let(:guest_user) { Spree.customer_class.new }- let(:guest_ability) { Spree::Ability.new(guest_user) }- let(:guest_address) { build(:address, user_id: nil) }- let(:other_guest_address) { create(:address, user_id: nil) }-- it 'prevents guest user from managing addresses with nil user_id (IDOR protection)' do- expect(guest_ability.can?(:manage, guest_address)).to be false- end-- it 'prevents guest user from editing other guest addresses (IDOR protection)' do- expect(guest_ability.can?(:edit, other_guest_address)).to be false- end-- it 'prevents guest user from updating other guest addresses (IDOR protection)' do- expect(guest_ability.can?(:update, other_guest_address)).to be false- end-- it 'prevents guest user from reading other guest addresses (IDOR protection)' do- expect(guest_ability.can?(:read, other_guest_address)).to be false- end- end- end-- context 'credit card permissions' do- let(:own_card) { build(:credit_card, user_id: user.id) }- let(:other_card) { build(:credit_card, user_id: create(:user).id) }-- it 'allows reading own credit card' do- expect(ability.can?(:read, own_card)).to be true- end-- it 'allows destroying own credit card' do- expect(ability.can?(:destroy, own_card)).to be true- end-- it 'prevents reading other user credit card' do- expect(ability.can?(:read, other_card)).to be false- end- end-- context 'wishlist permissions' do- let(:own_wishlist) { build(:wishlist, customer: user) }- let(:public_wishlist) { build(:wishlist, customer: create(:user), is_private: false) }- let(:private_wishlist) { build(:wishlist, customer: create(:user), is_private: true) }-- it 'allows managing own wishlist' do- expect(ability.can?(:manage, own_wishlist)).to be true- end-- it 'allows viewing public wishlist' do- expect(ability.can?(:show, public_wishlist)).to be true- end-- it 'prevents viewing private wishlist' do- expect(ability.can?(:show, private_wishlist)).to be false- end- end-- context 'admin permissions' do- it 'does not grant admin access' do- expect(ability.can?(:admin, :all)).to be false- end-- it 'does not grant manage access to Product' do- expect(ability.can?(:manage, Spree::Product)).to be false- end-- it 'never resolves roles for customer principals' do- role = create(:role, name: 'support', permissions: %w[write_orders])- user.spree_roles << role-- expect(Spree::Ability.new(user).can?(:manage, Spree::Order)).to be false- end- end-- it 'reports no permission keys' do- expect(ability.permission_keys).to eq([])- end-enddiff --git a/spree/core/spec/models/spree/storefront/access_policy_spec.rb b/spree/core/spec/models/spree/storefront/access_policy_spec.rbnew file mode 100644index 0000000000..40ec2329f5--- /dev/null+++ b/spree/core/spec/models/spree/storefront/access_policy_spec.rb@@ -0,0 +1,91 @@+require 'spec_helper'++RSpec.describe Spree::Storefront::AccessPolicy, type: :model do+ let(:store) { @default_store }+ let(:user) { create(:user) }+ let(:policy) { described_class.new(user: user, store: store) }+ let(:guest_policy) { described_class.new(user: nil, store: store) }++ describe '#purchase_readable?' do+ context 'with an owned order' do+ let(:order) { build(:order, customer: user) }++ it 'allows the owner' do+ expect(policy.purchase_readable?(order)).to be true+ end++ it 'denies other users' do+ other_policy = described_class.new(user: create(:user), store: store)+ expect(other_policy.purchase_readable?(order)).to be false+ end+ end++ context 'with a guest-token order' do+ let(:order) { build(:order, customer: nil, token: 'secret') }++ it 'allows the token bearer' do+ expect(guest_policy.purchase_readable?(order, token: 'secret')).to be true+ end++ it 'denies a wrong token' do+ expect(guest_policy.purchase_readable?(order, token: 'wrong')).to be false+ end++ it 'denies a missing token' do+ expect(guest_policy.purchase_readable?(order)).to be false+ end+ end++ context 'with a tokenless purchase' do+ let(:order) { build(:order, customer: nil, token: nil) }++ it 'never matches, even on a nil token' do+ expect(guest_policy.purchase_readable?(order, token: nil)).to be false+ end+ end++ it 'covers carts the same way' do+ cart = build(:cart, customer: user)+ expect(policy.purchase_readable?(cart)).to be true+ expect(guest_policy.purchase_readable?(cart)).to be false+ end+ end++ describe '#purchase_writable?' do+ let(:order) { build(:order, customer: user) }++ it 'allows the owner while incomplete' do+ allow(order).to receive(:completed?).and_return(false)+ expect(policy.purchase_writable?(order)).to be true+ end++ it 'denies once completed' do+ allow(order).to receive(:completed?).and_return(true)+ expect(policy.purchase_writable?(order)).to be false+ end++ it 'allows the token bearer while incomplete' do+ guest_order = build(:order, customer: nil, token: 'secret')+ allow(guest_order).to receive(:completed?).and_return(false)+ expect(guest_policy.purchase_writable?(guest_order, token: 'secret')).to be true+ end+ end++ describe '#orders_scope' do+ let!(:own_order) { create(:completed_order_with_totals, customer: user, store: store) }+ let!(:other_order) { create(:completed_order_with_totals, store: store) }++ it 'returns only the customer''s orders for an authenticated user' do+ expect(policy.orders_scope(store.orders.complete)).to contain_exactly(own_order)+ end++ it 'returns the token''s order for a guest' do+ scope = guest_policy.orders_scope(store.orders.complete, token: other_order.token)+ expect(scope).to contain_exactly(other_order)+ end++ it 'returns nothing for a guest without a token' do+ expect(guest_policy.orders_scope(store.orders.complete)).to be_empty+ end+ end+enddiff --git a/spree/lib/generators/spree/install/templates/config/initializers/spree.rb b/spree/lib/generators/spree/install/templates/config/initializers/spree.rbindex 3bb1a78330..6437870efe 100644--- a/spree/lib/generators/spree/install/templates/config/initializers/spree.rb+++ b/spree/lib/generators/spree/install/templates/config/initializers/spree.rb@@ -91,8 +91,8 @@ Rails.application.config.after_initialize do# Extensions can register additional permission resources:# Spree.permissions.register_resource(:reviews, group: :catalog, subjects: -> { [MyApp::Review] })#- # For record-level custom rules, register a plain CanCan::Ability class:- # Spree::Ability.register_ability(MyApp::RegionalSupportAbility)+ # To customize authorization beyond the catalog, replace the ability class:+ # Spree::Dependencies.ability_class = 'MyApp::Ability'## More: https://spreecommerce.org/docs/developer/customization/permissionsend