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
Generalize the storefront access policy beyond carts and orders
Damian Legawiecbf9b8aad8f85
diff --git a/docs/plans/6.0-admin-rbac.md b/docs/plans/6.0-admin-rbac.mdindex c56f0f1891..a8eff3234c 100644--- a/docs/plans/6.0-admin-rbac.md+++ b/docs/plans/6.0-admin-rbac.md@@ -123,7 +123,7 @@ pages.open-source injection point already in place:1. **Access widening** ("an approver sees every purchase of their companylocation") — subclass `Spree::Storefront::AccessPolicy`, override- `orders_scope`/`purchase_readable?`, register via+ `scope`/`readable?`/`writable?`, register via`Spree::Dependencies.storefront_access_policy_class`. Relational scopingis the natural shape here; a rule engine is not — CanCanCan's`accessible_by` cannot translate block rules (the token checks) to SQL,diff --git a/docs/plans/6.1-channels-catalogs-b2b.md b/docs/plans/6.1-channels-catalogs-b2b.mdindex efc5ec042e..fc6bf1e89c 100644--- a/docs/plans/6.1-channels-catalogs-b2b.md+++ b/docs/plans/6.1-channels-catalogs-b2b.md@@ -297,15 +297,54 @@ class Spree::CompanyContact < Spree.base_classend```+### Company roles and approvals — storefront authorization (Enterprise on OSS seams)+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`).+API controllers (decisions.md 2026-08-08). The full architecture, settled+2026-08-08 while designing the seams:++**Company roles are data, not code.** The string `role` attribute above is a+placeholder; the real model is an Enterprise `Spree::CompanyRole` —+`capabilities` JSON array over a fixed company capability vocabulary+(`place_orders`, `approve_orders`, `view_location_purchases`,+`view_company_purchases`, `manage_company_contacts`,+`manage_company_addresses`, …) with `CompanyContact` referencing a role. Data+because the company admin manages contacts and roles themselves, through+Enterprise storefront endpoints (`/api/v3/store/company/*`) gated by+`manage_company_contacts`, with anti-escalation mirroring the staff+`RoleGrantGuard` pattern. This is the commercetools associate-roles shape+(data roles over a fixed capability vocabulary) and the reason storefront+permission sets were not revived: code-defined sets cannot be edited by a+company admin in a UI. The vocabulary is Enterprise-owned and **never shared+with the staff catalog** (`6.0-admin-rbac.md`: `write_orders` means "manage+the store's orders" to staff, "place my company's orders" to a buyer).++**Visibility is a policy subclass.** Enterprise `CompanyAccessPolicy <+Spree::Storefront::AccessPolicy`, registered via+`Spree::Dependencies.storefront_access_policy_class`. `scope` / `readable?` /+`writable?` widen carts, orders and shared wishlists per the contact's+capabilities — an approver lists their location's pending carts through the+same core endpoints every customer uses.++**The approval flow rides the cart-side approval substrate**+(`5.5-6.0-order-cancellation-and-approval.md` defers buyer-organization+approvals to land here; the approver is already polymorphic with+`Spree::CompanyContact` anticipated):++1. An employee checks out → an Enterprise `carts.complete.validate` hook+ rejects when the contact lacks `place_orders` or exceeds their spending+ limit (well-known `approval_required` error).+2. The client calls the Enterprise submit-for-approval endpoint → cart-side+ approval record created, event published.+3. The manager (`approve_orders`) sees the pending cart via the widened+ policy and approves → an Enterprise workflow completes the cart as the+ approver, recording the approval (append-only history per the approval+ plan).++No new core seams are required: the access policy, the checkout `validate`+hooks, and events cover it. A standardized `approval_required` error code on+cart completion is a nice-to-have for this release. Contact roles never touch+`Spree::Ability` or the staff permission catalog.### Order gains Channel and CompanyLocationdiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 9b3ac1f34f..bd3fb96bc0 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1644,7 +1644,7 @@ AND an `authorize!` for the same fact. Second, the Enterprise B2B module(`6.1-channels-catalogs-b2b.md`) must extend storefront authority withoutdecorating controllers, and a policy object is the right seam: **accesswidening** (approver sees company-location purchases) = subclass the policy and-override `orders_scope`/`purchase_readable?`; **action vetoes** (approvals,+override `scope`/`readable?`/`writable?`; **action vetoes** (approvals,spending limits) = checkout workflow `validate` hooks; **catalog visibility**(per-location catalogs) = the products-for-context data scoping. Enterpriseimplements, open source owns the seams. Competitors ship no storefront rule@@ -1656,3 +1656,20 @@ server-side roles.workflow instead. The admin side is untouched: staff JWT + CanCanCan, secretkeys + scopes. `register_ability`/`remove_ability` are gone with the sets(`Spree::Dependencies.ability_class` is the admin-side escape hatch).++**Alternative considered and rejected (2026-08-08):** a dedicated storefront+ability class fed by permission sets — two abilities, staff (catalog keys) and+storefront (sets/code). Rejected on three grounds: a storefront rule engine+only means something if store controllers consult it, which restores the+scope-plus-`authorize!` dual bookkeeping across the store surface; OSS+customers are all identical, so a storefront set registry would hold exactly+one configuration (the old `DefaultCustomer`) — code plus registry+indirection; and the B2B requirement itself decides it — a company admin+managing roles/employees in a UI needs **data** roles (Enterprise+`CompanyRole` with capability keys, the commercetools associate-roles shape),+which code-defined sets cannot provide. The policy protocol is generic+(`readable?`/`writable?`/`scope` with an ownership default), so wishlists,+newsletter subscriptions and any new resource route through the same seam+with no wiring; `/customers/me/*` endpoints stay owner-scoped by definition.+Full B2B architecture: `6.1-channels-catalogs-b2b.md` → "Company roles and+approvals".diff --git a/docs/v6/developer/customization/permissions.mdx b/docs/v6/developer/customization/permissions.mdxindex 4be0be046d..2dafadb918 100644--- a/docs/v6/developer/customization/permissions.mdx+++ b/docs/v6/developer/customization/permissions.mdx@@ -67,4 +67,4 @@ endEvery 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. 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.+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`): a generic `readable?` / `writable?` / `scope` protocol that defaults to "the caller owns the record", with carts and orders adding guest-token access. Replace it only when access must widen beyond the owner, such as company accounts sharing purchases or wishlists.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 22451cafac..cf7e897aaa 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@@ -12,7 +12,7 @@ module Spree# @return [Spree::Cart]def find_cart(include_completed: false)@cart = resolve_cart(include_completed: include_completed)- authorize_purchase_read!(@cart, cart_token)+ authorize_storefront_read!(@cart, token: cart_token)@cartend@@ -24,9 +24,9 @@ module Spree@cart = resolve_cart(include_completed: include_completed)if @cart.completed?- authorize_purchase_read!(@cart, cart_token)+ authorize_storefront_read!(@cart, token: cart_token)else- authorize_purchase_write!(@cart, cart_token)+ authorize_storefront_write!(@cart, token: cart_token)end@cartdiff --git a/spree/api/app/controllers/concerns/spree/api/v3/storefront_access.rb b/spree/api/app/controllers/concerns/spree/api/v3/storefront_access.rbindex 351e0664ef..8df3a5c774 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/storefront_access.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/storefront_access.rb@@ -18,17 +18,17 @@ module Spreeend# @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)+ # prove ownership nor (for carts/orders) present the guest token+ def authorize_storefront_read!(record, token: nil)+ return if storefront_access_policy.readable?(record, token: token)raise Spree::Storefront::AccessDeniedend- # @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] when unreadable — or, for+ # carts and orders, already completed+ def authorize_storefront_write!(record, token: nil)+ return if storefront_access_policy.writable?(record, token: token)raise Spree::Storefront::AccessDeniedenddiff --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 21b75b81a3..1dfca9e147 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_purchase_write!(@cart, cart_token)+ authorize_storefront_write!(@cart, token: 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_purchase_read!(@cart, cart_token)+ authorize_storefront_read!(@cart, token: cart_token)render_orderend@@ -151,7 +151,9 @@ module Spree# Explicit by-ID lookups (show/update) stay cross-channel so a shared# checkout can load any cart the caller is authorized for.def scope- current_store.carts.incomplete.where(customer: current_user, channel: current_channel).order(updated_at: :desc)+ storefront_access_policy.+ scope(current_store.carts.incomplete.where(channel: current_channel)).+ order(updated_at: :desc)endprivatediff --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 1bd9751b97..9d37fdd50e 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_purchase_read!(cart, request.headers['x-spree-token'])+ authorize_storefront_read!(cart, token: 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 aac6048352..2b97f2cac2 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@@ -115,9 +115,8 @@ module Spreedef find_owned_subscriberreturn unless current_user- Spree::NewsletterSubscriber.- for_store(current_store).- where(user_id: current_user.id).+ storefront_access_policy.+ scope(Spree::NewsletterSubscriber.for_store(current_store)).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 30132f2e15..f66148fc67 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@@ -59,7 +59,7 @@ module Spreeenddef order_scope- storefront_access_policy.orders_scope(current_store.orders.complete, token: order_token)+ storefront_access_policy.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 61c978fd46..905cc2c0cf 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@@ -63,7 +63,7 @@ module Spreeenddef order_scope- storefront_access_policy.orders_scope(current_store.orders.complete, token: order_token)+ storefront_access_policy.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 12fa72acd0..2a2b42c6ef 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@@ -22,7 +22,7 @@ module Spreeenddef scope- storefront_access_policy.orders_scope(current_store.orders.complete, token: order_token)+ storefront_access_policy.scope(current_store.orders.complete, token: order_token)enddef serializer_classdiff --git a/spree/api/app/controllers/spree/api/v3/store/wishlist_items_controller.rb b/spree/api/app/controllers/spree/api/v3/store/wishlist_items_controller.rbindex 398b901b25..4652f5bb18 100644--- a/spree/api/app/controllers/spree/api/v3/store/wishlist_items_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/wishlist_items_controller.rb@@ -8,7 +8,10 @@ module Spreeprotecteddef set_parent- @parent = current_user.wishlists.find_by_prefix_id!(params[:wishlist_id])+ @parent = storefront_access_policy.+ scope(Spree::Wishlist.for_store(current_store)).+ find_by_prefix_id!(params[:wishlist_id])+ authorize_storefront_write!(@parent)enddef parent_associationdiff --git a/spree/api/app/controllers/spree/api/v3/store/wishlists_controller.rb b/spree/api/app/controllers/spree/api/v3/store/wishlists_controller.rbindex 3d03eefc11..8b30469ef0 100644--- a/spree/api/app/controllers/spree/api/v3/store/wishlists_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/wishlists_controller.rb@@ -20,7 +20,7 @@ module Spreeprotecteddef scope- current_user.wishlists.for_store(current_store)+ storefront_access_policy.scope(Spree::Wishlist.for_store(current_store))enddef model_classdiff --git a/spree/core/app/models/spree/storefront/access_policy.rb b/spree/core/app/models/spree/storefront/access_policy.rbindex 4dc1927ee6..04bba6e804 100644--- a/spree/core/app/models/spree/storefront/access_policy.rb+++ b/spree/core/app/models/spree/storefront/access_policy.rb@@ -1,18 +1,37 @@module Spreemodule 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.+ # consults CanCanCan — customer authorization is ownership, and this+ # policy is where ownership is decided, for any resource:+ #+ # - `readable?` / `writable?` answer per-record access,+ # - `scope` narrows a relation to what the caller may list.+ #+ # The default answer is "the caller owns the record" (guests own+ # nothing); carts and orders specialize it with guest-token access and a+ # completed?-guard on writes. New resources — core or extension — get the+ # ownership default with no wiring.## 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.+ # sees every purchase or shared wishlist of their company location+ # (docs/plans/6.1-channels-catalogs-b2b.md). Override the entry points+ # and fall through to `super`:+ #+ # class Enterprise::CompanyAccessPolicy < Spree::Storefront::AccessPolicy+ # def scope(base, token: nil)+ # return base.where(company_location_id: approver_location_ids) if+ # base.klass <= Spree::Order && approver?+ #+ # super+ # end+ # end+ #+ # Two things deliberately stay out of the policy: action vetoes (approval+ # required, spending limits) are checkout workflow `validate` hooks, and+ # the `/customers/me/*` endpoints stay owner-scoped by definition —+ # company-wide surfaces are their own endpoints built on this policy.class AccessPolicy# @return [Object, nil] the authenticated customer, or nil for guestsattr_reader :user@@ -25,33 +44,57 @@ module Spree@store = storeend- # Whether the caller may read a cart or order: its owner (by JWT) or the- # bearer of its guest token.+ # Whether the caller may read a record: its owner by default; for carts+ # and orders, the owner (by JWT) or the bearer of the guest token.#- # @param purchase [Spree::Cart, Spree::Order]+ # @param record [ActiveRecord::Base]# @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)+ def readable?(record, token: nil)+ return purchase_readable?(record, token: token) if purchase?(record)++ owned?(record)end- # Whether the caller may mutate a cart or order — readable and not yet- # completed.+ # Whether the caller may mutate a record. Same as +readable?+ by+ # default; carts and orders additionally refuse once completed.#- # @param purchase [Spree::Cart, Spree::Order]+ # @param record [ActiveRecord::Base]# @param token [String, nil]# @return [Boolean]- def purchase_writable?(purchase, token: nil)- !purchase.completed? && purchase_readable?(purchase, token: token)+ def writable?(record, token: nil)+ return purchase_writable?(record, token: token) if purchase?(record)++ owned?(record)end- # The completed orders the caller may list and look up. Owner-only by- # default; the guest-token branch serves order-confirmation lookups.+ # Narrows a relation to the records the caller may list: the caller's+ # own by default; for orders, the guest-token branch serves+ # order-confirmation lookups.#- # @param base [ActiveRecord::Relation] pre-scoped orders (store, complete)+ # @param base [ActiveRecord::Relation] pre-scoped by the controller+ # (store, completeness, channel — every axis but ownership)# @param token [String, nil]# @return [ActiveRecord::Relation]- def orders_scope(base, token: nil)+ def scope(base, token: nil)+ return purchases_scope(base, token: token) if purchase_class?(base.klass)++ owned_scope(base)+ end++ protected++ # --- carts and orders: token semantics ---++ def purchase_readable?(purchase, token:)+ purchase_owner?(purchase) || purchase_token_match?(purchase, token)+ end++ def purchase_writable?(purchase, token:)+ !purchase.completed? && purchase_readable?(purchase, token: token)+ end++ def purchases_scope(base, token:)if user.present?base.where(customer: user)elsif token.present?@@ -61,8 +104,6 @@ module Spreeendend- protected-def purchase_owner?(purchase)user.present? && purchase.customer == userend@@ -70,6 +111,26 @@ module Spreedef purchase_token_match?(purchase, token)purchase.token.present? && token == purchase.tokenend++ def purchase?(record)+ record.is_a?(Spree::Cart) || record.is_a?(Spree::Order)+ end++ def purchase_class?(klass)+ klass <= Spree::Cart || klass <= Spree::Order+ end++ # --- everything else: ownership ---++ def owned?(record)+ user.present? && record.respond_to?(:user_id) && record.user_id == user.id+ end++ def owned_scope(base)+ return base.none if user.blank?++ base.where(user_id: user.id)+ endendendenddiff --git a/spree/core/spec/models/spree/storefront/access_policy_spec.rb b/spree/core/spec/models/spree/storefront/access_policy_spec.rbindex 40ec2329f5..6c5e6eef29 100644--- a/spree/core/spec/models/spree/storefront/access_policy_spec.rb+++ b/spree/core/spec/models/spree/storefront/access_policy_spec.rb@@ -6,17 +6,17 @@ RSpec.describe Spree::Storefront::AccessPolicy, type: :model dolet(:policy) { described_class.new(user: user, store: store) }let(:guest_policy) { described_class.new(user: nil, store: store) }- describe '#purchase_readable?' do+ describe '#readable? / #writable? for carts and orders' docontext 'with an owned order' dolet(:order) { build(:order, customer: user) }it 'allows the owner' do- expect(policy.purchase_readable?(order)).to be true+ expect(policy.readable?(order)).to be trueendit 'denies other users' doother_policy = described_class.new(user: create(:user), store: store)- expect(other_policy.purchase_readable?(order)).to be false+ expect(other_policy.readable?(order)).to be falseendend@@ -24,15 +24,15 @@ RSpec.describe Spree::Storefront::AccessPolicy, type: :model dolet(:order) { build(:order, customer: nil, token: 'secret') }it 'allows the token bearer' do- expect(guest_policy.purchase_readable?(order, token: 'secret')).to be true+ expect(guest_policy.readable?(order, token: 'secret')).to be trueendit 'denies a wrong token' do- expect(guest_policy.purchase_readable?(order, token: 'wrong')).to be false+ expect(guest_policy.readable?(order, token: 'wrong')).to be falseendit 'denies a missing token' do- expect(guest_policy.purchase_readable?(order)).to be false+ expect(guest_policy.readable?(order)).to be falseendend@@ -40,52 +40,93 @@ RSpec.describe Spree::Storefront::AccessPolicy, type: :model dolet(: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+ expect(guest_policy.readable?(order, token: nil)).to be falseendendit 'covers carts the same way' docart = build(:cart, customer: user)- expect(policy.purchase_readable?(cart)).to be true- expect(guest_policy.purchase_readable?(cart)).to be false+ expect(policy.readable?(cart)).to be true+ expect(guest_policy.readable?(cart)).to be false+ end++ describe 'writes' do+ let(:order) { build(:order, customer: user) }++ it 'allows the owner while incomplete' do+ allow(order).to receive(:completed?).and_return(false)+ expect(policy.writable?(order)).to be true+ end++ it 'denies once completed' do+ allow(order).to receive(:completed?).and_return(true)+ expect(policy.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.writable?(guest_order, token: 'secret')).to be true+ endendend- describe '#purchase_writable?' do- let(:order) { build(:order, customer: user) }+ describe '#readable? / #writable? ownership default' do+ let(:own_wishlist) { build(:wishlist, customer: user) }+ let(:other_wishlist) { build(:wishlist, customer: create(:user)) }++ it 'allows the owner, read and write' do+ expect(policy.readable?(own_wishlist)).to be true+ expect(policy.writable?(own_wishlist)).to be true+ end- it 'allows the owner while incomplete' do- allow(order).to receive(:completed?).and_return(false)- expect(policy.purchase_writable?(order)).to be true+ it 'denies other users' do+ expect(policy.readable?(other_wishlist)).to be false+ expect(policy.writable?(other_wishlist)).to be falseend- it 'denies once completed' do- allow(order).to receive(:completed?).and_return(true)- expect(policy.purchase_writable?(order)).to be false+ it 'denies guests everything' do+ expect(guest_policy.readable?(own_wishlist)).to be false+ expect(guest_policy.writable?(own_wishlist)).to be falseend- 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+ it 'denies unowned records to everyone' do+ unowned = build(:address, user_id: nil)+ expect(policy.readable?(unowned)).to be false+ expect(guest_policy.readable?(unowned)).to be falseendend- 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) }+ describe '#scope' do+ context 'for orders (token semantics)' 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 only the customer''s orders for an authenticated user' do+ expect(policy.scope(store.orders.complete)).to contain_exactly(own_order)+ end++ it 'returns the token''s order for a guest' do+ scope = guest_policy.scope(store.orders.complete, token: other_order.token)+ expect(scope).to contain_exactly(other_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)+ it 'returns nothing for a guest without a token' do+ expect(guest_policy.scope(store.orders.complete)).to be_empty+ endend- it 'returns nothing for a guest without a token' do- expect(guest_policy.orders_scope(store.orders.complete)).to be_empty+ context 'for any other resource (ownership default)' do+ let!(:own_wishlist) { create(:wishlist, customer: user, store: store) }+ let!(:other_wishlist) { create(:wishlist, customer: create(:user), store: store) }++ it 'returns only the caller''s records' do+ expect(policy.scope(Spree::Wishlist.for_store(store))).to contain_exactly(own_wishlist)+ end++ it 'returns nothing for guests' do+ expect(guest_policy.scope(Spree::Wishlist.for_store(store))).to be_empty+ endendendend