Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Harden Admin API (#14158)

Damian Legawiecdea12cdc7767
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/role_grant_guard.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/role_grant_guard.rb
new file mode 100644
index 0000000000..14191b57c0
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/role_grant_guard.rb
@@ -0,0 +1,52 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # Shared guard preventing role-assignment privilege escalation. Staff
+ # role grants (via admin_users#update and invitations#create) must not
+ # let a caller hand out the `admin` super-role unless they already hold
+ # it on the current store. API-key principals have no human identity to
+ # bound the grant, so they can never grant the admin role.
+ #
+ # Without this, any principal able to write staff (`write_settings`
+ # scope, or a `UserManagement`/`RoleManagement` JWT role) could promote
+ # an account to store super-admin. See the 2026-06 admin API security
+ # review (Vulns 2-4).
+ module RoleGrantGuard
+ extend ActiveSupport::Concern
+
+ private
+
+ # @param role_ids [Array<Integer,String>] resolved (decoded) role ids
+ # @return [Boolean] true if the request was rejected (caller should return)
+ def reject_unauthorized_role_grant!(role_ids)
+ return false if role_ids.blank?
+
+ admin_role_id = Spree::Role.admin.pick(:id)
+ return false if admin_role_id.blank?
+ return false unless role_ids.map(&:to_s).include?(admin_role_id.to_s)
+ return false if caller_holds_admin_role?
+
+ render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:access_denied],
+ message: 'You cannot grant the admin role.',
+ status: :forbidden
+ )
+ true
+ end
+
+ # Mirrors how Spree::Ability activates the super-user permission set:
+ # admin-ness is decided by `spree_roles` membership (resource-agnostic),
+ # not by a per-store RoleUser. API-key principals have no user and so
+ # never count as holding the admin role.
+ def caller_holds_admin_role?
+ user = try_spree_current_user
+ return false unless user.respond_to?(:spree_roles)
+
+ user.spree_roles.exists?(name: Spree::Role::ADMIN_ROLE)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/admin_users_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/admin_users_controller.rb
index 1eedc0ab68..67d502a928 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/admin_users_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/admin_users_controller.rb
@@ -8,6 +8,8 @@ module Spree
# this v3 endpoint instead removes the per-store `RoleUser` rows so
# the user keeps their account (and access to other stores).
class AdminUsersController < ResourceController
+ include Spree::Api::V3::Admin::RoleGrantGuard
+
scoped_resource :settings
# POST is not exposed — staff are created via invitations.
@@ -31,9 +33,13 @@ module Spree
def update
authorize!(:update, @resource)
- attrs = identity_params
- if @resource.update(attrs)
- apply_role_ids(role_ids_param) if params.key?(:role_ids)
+ # `nil` when the key is absent (leave roles untouched); an array
+ # (possibly empty, to clear) when the client sends `role_ids`.
+ role_ids = role_ids_param if params.key?(:role_ids)
+ return if role_ids && reject_unauthorized_role_grant!(role_ids)
+
+ if @resource.update(identity_params)
+ apply_role_ids(role_ids) if role_ids
render json: serialize_resource(@resource)
else
render_validation_error(@resource.errors)
diff --git a/spree/api/app/controllers/spree/api/v3/admin/api_keys_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/api_keys_controller.rb
index 9b794ed85a..b41bbe9847 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/api_keys_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/api_keys_controller.rb
@@ -5,6 +5,26 @@ module Spree
class ApiKeysController < ResourceController
scoped_resource :settings
+ # POST /api/v3/admin/api_keys
+ # Prevents scope amplification: a key minted via a secret API key can
+ # only carry scopes that key already holds. A JWT admin is governed by
+ # CanCanCan (not scopes) and may grant any valid scope — so when a JWT
+ # user authenticated the request, `current_ability` ignores the API key
+ # (see AdminAuthentication#current_ability) and we skip the scope cap
+ # too, even if an `X-Spree-Api-Key` header was also sent.
+ def create
+ if scope_limited_principal? && (excess = requested_scopes.reject { |s| current_api_key.has_scope?(s) }).any?
+ return render_error(
+ code: ERROR_CODES[:access_denied],
+ message: "Cannot grant scopes beyond your own: #{excess.join(', ')}",
+ status: :forbidden,
+ details: { excess_scopes: excess }
+ )
+ end
+
+ super
+ end
+
# PATCH /api/v3/admin/api_keys/:id/revoke
# Marks the key revoked rather than deleting it — the row stays so
# audit logs and `created_by`/`revoked_by` remain queryable. Hard
@@ -48,6 +68,19 @@ module Spree
attrs.delete(:key_type) if action_name == 'update'
attrs
end
+
+ private
+
+ # True when authorization derives from the API key's scopes rather
+ # than a JWT admin's CanCanCan ability. Mirrors the credential
+ # precedence in AdminAuthentication#current_ability (JWT user wins).
+ def scope_limited_principal?
+ current_api_key.present? && current_user.blank?
+ end
+
+ def requested_scopes
+ Array(params[:scopes]).map(&:to_s).reject(&:blank?)
+ end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb
index a8b62ba757..1b41c66870 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb
@@ -53,7 +53,18 @@ module Spree
# defensive guard against a future route nesting that doesn't.
raise ActiveRecord::RecordNotFound, 'Parent resource not found' unless parent_lookup
- @parent = parent_lookup.klass.find_by_prefix_id!(parent_lookup.value)
+ @parent = parent_relation.find_by_prefix_id!(parent_lookup.value)
+ authorize!(:show, @parent)
+ end
+
+ # Resolves the parent within the current store so a token for one
+ # store can't read or write custom fields on another store's records.
+ # Users are intentionally global in Spree (`User.for_store` is a
+ # no-op), so the store boundary for customer parents is enforced by
+ # the `authorize!(:show, @parent)` ability check above.
+ def parent_relation
+ klass = parent_lookup.klass
+ klass.respond_to?(:for_store) ? klass.for_store(current_store) : klass
end
# Per-parent scope check: a key holding `write_products` may write a
diff --git a/spree/api/app/controllers/spree/api/v3/admin/customers/addresses_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customers/addresses_controller.rb
index 4de10f3552..caf1b2fac7 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/customers/addresses_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/customers/addresses_controller.rb
@@ -3,8 +3,7 @@ module Spree
module V3
module Admin
module Customers
- class AddressesController < ResourceController
- scoped_resource :customers
+ class AddressesController < BaseController
# POST /api/v3/admin/customers/:customer_id/addresses
def create
@@ -46,10 +45,6 @@ module Spree
protected
- def set_parent
- @parent = Spree.user_class.find_by_prefix_id!(params[:customer_id])
- end
-
def parent_association
:addresses
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/customers/base_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customers/base_controller.rb
new file mode 100644
index 0000000000..d6fb3e6130
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/customers/base_controller.rb
@@ -0,0 +1,33 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module Customers
+ # Shared base for resources nested under a customer
+ # (`/admin/customers/:customer_id/...`). Resolves the parent customer
+ # and authorizes it per action (`:show` for reads, `:update` for
+ # writes) so a role that can only view a customer can't mutate its
+ # nested collections. Mirrors `Orders::BaseController`.
+ class BaseController < ResourceController
+ scoped_resource :customers
+
+ protected
+
+ # Resolve the customer through the ability-scoped relation, using
+ # the action-appropriate ability on the parent (`:show` for reads,
+ # `:update` for writes — see `parent_ability_action`). A customer
+ # the caller can't access for the requested action is filtered out
+ # and 404s, rather than leaking its existence as a 403. Users are
+ # global in Spree (`User.for_store` is a no-op), so the ability is
+ # the only boundary here.
+ def set_parent
+ @parent = Spree.user_class.
+ accessible_by(current_ability, parent_ability_action).
+ find_by_prefix_id!(params[:customer_id])
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/customers/credit_cards_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customers/credit_cards_controller.rb
index e7aadab2f9..b97c19ec70 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/customers/credit_cards_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/customers/credit_cards_controller.rb
@@ -3,15 +3,9 @@ module Spree
module V3
module Admin
module Customers
- class CreditCardsController < ResourceController
- scoped_resource :customers
-
+ class CreditCardsController < BaseController
protected
- def set_parent
- @parent = Spree.user_class.find_by_prefix_id!(params[:customer_id])
- end
-
def parent_association
:credit_cards
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/customers/store_credits_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customers/store_credits_controller.rb
index af7bb81572..8f5b419c35 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/customers/store_credits_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/customers/store_credits_controller.rb
@@ -3,7 +3,10 @@ module Spree
module V3
module Admin
module Customers
- class StoreCreditsController < ResourceController
+ class StoreCreditsController < BaseController
+ # Store credits gate on their own scope rather than the parent's
+ # `:customers`, so a store-credit integration key doesn't need
+ # broad customer access.
scoped_resource :store_credits
# POST /api/v3/admin/customers/:customer_id/store_credits
@@ -60,10 +63,6 @@ module Spree
protected
- def set_parent
- @parent = Spree.user_class.find_by_prefix_id!(params[:customer_id])
- end
-
def parent_association
:store_credits
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/invitations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/invitations_controller.rb
index b7ef87cd3e..c56f25550b 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/invitations_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/invitations_controller.rb
@@ -7,8 +7,19 @@ module Spree
# via the invitation's `after_accept` callback and the invitee
# becomes a member of the staff list for this store.
class InvitationsController < ResourceController
+ include Spree::Api::V3::Admin::RoleGrantGuard
+
scoped_resource :settings
+ # POST /api/v3/admin/invitations
+ # Guards against inviting a new staff member straight into the admin
+ # super-role unless the inviter already holds it.
+ def create
+ return if reject_unauthorized_role_grant!(Array(permitted_params[:role_id]))
+
+ super
+ end
+
# PATCH /api/v3/admin/invitations/:id/resend
# Issues a fresh token + email for an existing pending invitation.
# The model's `resend!` is responsible for resetting `expires_at`
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/base_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/base_controller.rb
index f543e784d5..0540661b1c 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/base_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/base_controller.rb
@@ -15,8 +15,13 @@ module Spree
@order = @parent
end
+ # Read actions require only :show on the parent order; every write
+ # (create/update/destroy and custom member actions like capture,
+ # void, fulfill, split, apply gift card / store credit) requires
+ # :update, so a read-only role can't mutate an order it can view.
+ # Subclasses with custom read-only actions extend +read_actions+.
def authorize_order_access!
- authorize!(:show, @parent)
+ authorize_parent!(@parent)
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb
index 3dd97f60e8..604d72ab28 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb
@@ -105,7 +105,7 @@ module Spree
end
def permitted_params
- normalize_params(
+ attrs = normalize_params(
params.permit(
:name, :description, :position,
:starts_at, :ends_at, :match_policy,
@@ -114,6 +114,29 @@ module Spree
prices: [:id, :variant_id, :currency, :amount, :compare_at_amount]
)
)
+ reject_foreign_membership(attrs)
+ end
+
+ # The PriceList model setters (`product_ids=`, `prices=`) resolve
+ # member ids with no store scoping, so a list in this store could
+ # otherwise be populated with another store's products/variants.
+ # Drop any id that isn't in the current store before assignment.
+ def reject_foreign_membership(attrs)
+ if attrs[:product_ids].present?
+ store_product_ids = current_store.products.where(id: attrs[:product_ids]).pluck(:id).map(&:to_s).to_set
+ attrs[:product_ids] = Array(attrs[:product_ids]).select { |id| store_product_ids.include?(id.to_s) }
+ end
+
+ if attrs[:prices].present?
+ incoming = Array(attrs[:prices])
+ store_variant_ids = current_store.variants.where(id: incoming.map { |r| r[:variant_id] }.compact).
+ pluck(:id).map(&:to_s).to_set
+ attrs[:prices] = incoming.select do |row|
+ row[:variant_id].blank? || store_variant_ids.include?(row[:variant_id].to_s)
+ end
+ end
+
+ attrs
end
private
diff --git a/spree/api/app/controllers/spree/api/v3/admin/prices_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/prices_controller.rb
index 2609d57358..19d5b1a020 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/prices_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/prices_controller.rb
@@ -35,6 +35,16 @@ module Spree
)
end
+ foreign = foreign_rows(rows)
+ if foreign.any?
+ return render_error(
+ code: 'invalid_prices',
+ message: 'Each row must reference a variant and price list in the current store.',
+ status: :unprocessable_content,
+ details: { rows: foreign }
+ )
+ end
+
result = Spree::Prices::BulkUpsert.call(rows: rows)
render json: result.value
end
@@ -122,6 +132,24 @@ module Spree
Spree::PrefixedId.prefixed_id?(value) ? Spree::PrefixedId.decode_prefixed_id(value) : value
end
+
+ # Rejects rows whose variant or price list belongs to another store.
+ # `Spree::Prices::BulkUpsert` writes rows keyed on the raw variant_id
+ # with no ownership check, so the store boundary is enforced here.
+ def foreign_rows(rows)
+ variant_ids = rows.map { |r| r[:variant_id] }.compact.uniq
+ price_list_ids = rows.map { |r| r[:price_list_id] }.compact.uniq
+
+ store_variant_ids = current_store.variants.where(id: variant_ids).pluck(:id).map(&:to_s).to_set
+ store_price_list_ids = Spree::PriceList.for_store(current_store).where(id: price_list_ids).pluck(:id).map(&:to_s).to_set
+
+ rows.each_with_index.filter_map do |row, idx|
+ variant_ok = store_variant_ids.include?(row[:variant_id].to_s)
+ price_list_ok = row[:price_list_id].blank? || store_price_list_ids.include?(row[:price_list_id].to_s)
+
+ { index: idx } unless variant_ok && price_list_ok
+ end
+ end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/stock_reservations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/stock_reservations_controller.rb
index b52f86325d..28af295a6d 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/stock_reservations_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/stock_reservations_controller.rb
@@ -16,7 +16,7 @@ module Spree
end
def scope
- Spree::StockReservation.for_store(current_store)
+ Spree::StockReservation.for_store(current_store).accessible_by(current_ability, ability_action_for_request)
end
def collection_includes
diff --git a/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb
index 78c03dd71c..53a573a2ea 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb
@@ -16,7 +16,7 @@ module Spree
end
def scope
- current_store.variants.eligible
+ current_store.variants.eligible.accessible_by(current_ability, ability_action_for_request)
end
def scope_includes
diff --git a/spree/api/app/controllers/spree/api/v3/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/resource_controller.rb
index 0dddb25129..ecfe29687b 100644
--- a/spree/api/app/controllers/spree/api/v3/resource_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/resource_controller.rb
@@ -261,27 +261,54 @@ module Spree
else
model_class.for_store(current_store)
end
- unless @parent.present?
- action_name = case request.method
- when 'GET', 'HEAD'
- :show
- when 'POST'
- :create
- when 'PATCH', 'PUT'
- :update
- when 'DELETE'
- :destroy
- else
- raise ActionController::MethodNotAllowed, request.method
- end
-
- base_scope = base_scope.accessible_by(current_ability, action_name)
- 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_lazily
model_class.include?(Spree::TranslatableResource) ? base_scope.i18n : base_scope
end
+ # Action names treated as reads. Override in subclasses with custom
+ # read-only member/collection actions (e.g. add `analytics`, `types`)
+ # so they map to the `:show` ability instead of a write.
+ def read_actions
+ %w[index show]
+ end
+
+ # Maps the current request to the CanCanCan action used to scope the
+ # collection. Read actions (see +read_actions+) map to `:show`; every
+ # other request maps by HTTP method. Exposed so controllers that
+ # override +scope+ can keep the same `accessible_by` action as the
+ # base implementation.
+ def ability_action_for_request
+ return :show if read_actions.include?(action_name)
+
+ case request.method
+ when 'GET', 'HEAD' then :show
+ when 'POST' then :create
+ when 'PATCH', 'PUT' then :update
+ when 'DELETE' then :destroy
+ else
+ raise ActionController::MethodNotAllowed, request.method
+ end
+ end
+
+ # The ability action a nested resource needs on its PARENT: read
+ # actions (see +read_actions+) need only `:show`; every write needs
+ # `:update`, since mutating a nested collection is an update to the
+ # parent (not a create/destroy of it). Distinct from
+ # +ability_action_for_request+, which maps POST/DELETE to
+ # `:create`/`:destroy` for the resource itself.
+ def parent_ability_action
+ read_actions.include?(action_name) ? :show : :update
+ end
+
+ # 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
+
# Override to specify the association name on @parent
# Defaults to controller_name (e.g., 'wished_items' for WishlistItemsController)
def parent_association
diff --git a/spree/api/lib/spree/api/testing_support/v3/base.rb b/spree/api/lib/spree/api/testing_support/v3/base.rb
index a7557a123e..caeb9d8ad5 100644
--- a/spree/api/lib/spree/api/testing_support/v3/base.rb
+++ b/spree/api/lib/spree/api/testing_support/v3/base.rb
@@ -70,6 +70,34 @@ shared_context 'API v3 Admin authenticated' do
let(:headers) { bearer_headers }
end
+# Authenticates as an admin whose ability is restricted to a single custom
+# permission set, so authorization specs can assert what a limited role can and
+# cannot do. Define `custom_permission_set` (a Spree::PermissionSets::Base
+# subclass) in the including example. The global permission registry is saved
+# and restored around each example so it doesn't leak into other specs.
+shared_context 'API v3 Admin with custom permissions' do
+ include_context 'API v3 Admin'
+
+ around do |example|
+ saved = Spree.permissions.dup
+ Spree.permissions.reset!
+ example.run
+ ensure
+ Spree.permissions.replace(saved)
+ end
+
+ let(:custom_role) { create(:role, name: 'limited') }
+ let(:custom_admin) { create(:admin_user, :without_admin_role) }
+ let(:headers) do
+ { 'Authorization' => "Bearer #{Spree::Api::V3::TestingSupport.generate_jwt(custom_admin, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN)}" }
+ end
+
+ before do
+ custom_admin.spree_roles << custom_role
+ Spree.permissions.assign(:limited, custom_permission_set)
+ end
+end
+
# Shared examples for common response patterns
shared_examples 'returns 200 OK' do
it 'returns 200 status' do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/admin_users_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/admin_users_controller_spec.rb
new file mode 100644
index 0000000000..65f9e83052
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/admin_users_controller_spec.rb
@@ -0,0 +1,90 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::AdminUsersController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin'
+
+ let!(:admin_role) { Spree::Role.default_admin_role }
+ let(:staff_role) { create(:role, name: 'staff') }
+ # A staff member already on this store (so the controller's store-scoped
+ # `scope` resolves them) but without the admin role.
+ let!(:target) do
+ create(:admin_user, :without_admin_role).tap do |u|
+ u.role_users.create!(role: staff_role, resource: store)
+ end
+ end
+
+ before { request.headers.merge!(headers) }
+
+ describe 'PATCH #update — role-grant privilege escalation' do
+ context 'authenticated via a secret API key (no human identity)' do
+ let(:caller_key) { create(:api_key, :secret, store: store, scopes: ['write_settings']) }
+ let(:headers) { { 'x-spree-api-key' => caller_key.plaintext_token } }
+
+ it 'forbids granting the admin role' do
+ patch :update, params: { id: target.prefixed_id, role_ids: [admin_role.prefixed_id] }, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ expect(target.reload.spree_admin?(store)).to be(false)
+ end
+
+ it 'still allows assigning a non-admin role' do
+ other_role = create(:role, name: 'support')
+
+ patch :update, params: { id: target.prefixed_id, role_ids: [other_role.prefixed_id] }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(target.role_users.where(resource: store, role: other_role)).to exist
+ end
+ end
+
+ context 'authenticated as a non-admin staff JWT' do
+ around do |example|
+ saved = Spree.permissions.dup
+ Spree.permissions.reset!
+ example.run
+ ensure
+ Spree.permissions.replace(saved)
+ end
+
+ let(:user_manager_set) do
+ Class.new(Spree::PermissionSets::Base) do
+ def activate!
+ can :manage, Spree.admin_user_class
+ can [:read, :admin], Spree::Role
+ end
+ end
+ end
+
+ let(:staff_admin) do
+ create(:admin_user, :without_admin_role).tap { |u| u.role_users.create!(role: staff_role, resource: store) }
+ end
+ let(:headers) do
+ api_key_headers.merge('Authorization' => "Bearer #{Spree::Api::V3::TestingSupport.generate_jwt(staff_admin, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN)}")
+ end
+
+ before do
+ Spree.permissions.assign(:staff, user_manager_set)
+ end
+
+ it 'forbids a non-admin from promoting an account to admin' do
+ patch :update, params: { id: target.prefixed_id, role_ids: [admin_role.prefixed_id] }, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ expect(target.reload.spree_admin?(store)).to be(false)
+ end
+ end
+
+ context 'authenticated as a super-admin JWT' do
+ let(:headers) { bearer_headers }
+
+ it 'allows granting the admin role' do
+ patch :update, params: { id: target.prefixed_id, role_ids: [admin_role.prefixed_id] }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(target.reload.spree_admin?(store)).to be(true)
+ end
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/api_keys_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/api_keys_controller_spec.rb
new file mode 100644
index 0000000000..a62584400b
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/api_keys_controller_spec.rb
@@ -0,0 +1,61 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::ApiKeysController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin'
+
+ before { request.headers.merge!(headers) }
+
+ describe 'POST #create — scope amplification guard' do
+ # Authenticate as a secret key holding only `write_settings` so the
+ # request passes the scope check for the `:settings`-scoped controller
+ # but is bounded by what that key actually holds.
+ let(:caller_key) { create(:api_key, :secret, store: store, scopes: ['write_settings']) }
+ let(:headers) { { 'x-spree-api-key' => caller_key.plaintext_token } }
+
+ it 'rejects minting a key with scopes beyond the caller\'s own' do
+ expect {
+ post :create, params: { name: 'escalated', key_type: 'secret', scopes: ['write_all'] }, as: :json
+ }.not_to change { Spree::ApiKey.secret.count }
+
+ expect(response).to have_http_status(:forbidden)
+ expect(json_response['error']['details']['excess_scopes']).to include('write_all')
+ end
+
+ it 'allows minting a key with scopes the caller already holds' do
+ post :create, params: { name: 'sibling', key_type: 'secret', scopes: ['write_settings'] }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['scopes']).to eq(['write_settings'])
+ end
+
+ it 'allows the implied read scope of a held write scope' do
+ post :create, params: { name: 'reader', key_type: 'secret', scopes: ['read_settings'] }, as: :json
+
+ expect(response).to have_http_status(:created)
+ end
+
+ context 'when the caller holds write_all' do
+ let(:caller_key) { create(:api_key, :secret, store: store, scopes: ['write_all']) }
+
+ it 'may mint any scope' do
+ post :create, params: { name: 'broad', key_type: 'secret', scopes: ['write_orders'] }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['scopes']).to eq(['write_orders'])
+ end
+ end
+
+ context 'when authenticated as a JWT admin (super-user)' do
+ let(:headers) { bearer_headers }
+
+ it 'may grant any valid scope (bounded by CanCanCan, not scopes)' do
+ post :create, params: { name: 'jwt-minted', key_type: 'secret', scopes: ['write_all'] }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['scopes']).to eq(['write_all'])
+ end
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_controller_spec.rb
index 775d08d5f6..ef230256b6 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_controller_spec.rb
@@ -165,6 +165,43 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldsController, type: :controller
end
end
+ describe 'cross-store IDOR — a product in another store' do
+ let(:other_store) { create(:store) }
+ let(:other_product) { create(:product, store: other_store) }
+ let!(:foreign_field) do
+ create(:metafield, resource: other_product, metafield_definition: short_text_definition, value: 'secret')
+ end
+
+ it 'does not list custom fields of another store\'s product' do
+ get :index, params: { product_id: other_product.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it 'does not create a custom field on another store\'s product' do
+ expect {
+ post :create,
+ params: {
+ product_id: other_product.prefixed_id,
+ custom_field_definition_id: long_text_definition.prefixed_id,
+ value: 'injected'
+ },
+ as: :json
+ }.not_to change { other_product.metafields.count }
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it 'does not update a custom field on another store\'s product' do
+ patch :update,
+ params: { product_id: other_product.prefixed_id, id: foreign_field.prefixed_id, value: 'tampered' },
+ as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(foreign_field.reload.value).to eq('secret')
+ end
+ end
+
describe 'API key scope enforcement' do
let(:api_key) { create(:api_key, :secret, store: store, scopes: [granted_scope]) }
let(:api_key_headers) { { 'x-spree-api-key' => api_key.plaintext_token } }
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/customers/addresses_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/customers/addresses_controller_spec.rb
index d99deb1e48..a1bf1d6a43 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/customers/addresses_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/customers/addresses_controller_spec.rb
@@ -18,6 +18,28 @@ RSpec.describe Spree::Api::V3::Admin::Customers::AddressesController, type: :con
expect(json_response['data']).to be_an(Array)
expect(json_response['data'].map { |a| a['id'] }).to include(address.prefixed_id)
end
+
+ # Broken object-level authorization: the nested index must enforce the
+ # caller's ability on the parent customer. A customer the caller can't view
+ # is filtered out of the ability-scoped lookup, so it 404s rather than
+ # leaking its existence as a 403.
+ context 'with a limited-role admin that cannot read customers' do
+ include_context 'API v3 Admin with custom permissions'
+
+ let(:custom_permission_set) do
+ Class.new(Spree::PermissionSets::Base) do
+ def activate!
+ can [:read, :admin], Spree::Product
+ end
+ end
+ end
+
+ it 'cannot read another customer\'s addresses' do
+ get :index, params: { customer_id: customer.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
end
describe 'POST #create' do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/customers/credit_cards_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/customers/credit_cards_controller_spec.rb
index d87c63853e..e1410be9b8 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/customers/credit_cards_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/customers/credit_cards_controller_spec.rb
@@ -39,6 +39,28 @@ RSpec.describe Spree::Api::V3::Admin::Customers::CreditCardsController, type: :c
expect(response).to have_http_status(:not_found)
end
end
+
+ # Broken object-level authorization: the nested index must enforce the
+ # caller's ability on the parent customer. A customer the caller can't view
+ # is filtered out of the ability-scoped lookup, so it 404s rather than
+ # leaking its existence as a 403.
+ context 'with a limited-role admin that cannot read customers' do
+ include_context 'API v3 Admin with custom permissions'
+
+ let(:custom_permission_set) do
+ Class.new(Spree::PermissionSets::Base) do
+ def activate!
+ can [:read, :admin], Spree::Product
+ end
+ end
+ end
+
+ it 'cannot read another customer\'s credit cards' do
+ get :index, params: { customer_id: customer.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
end
describe 'GET #show' do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/customers/store_credits_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/customers/store_credits_controller_spec.rb
index 205d4962ff..b87c27774f 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/customers/store_credits_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/customers/store_credits_controller_spec.rb
@@ -18,6 +18,104 @@ RSpec.describe Spree::Api::V3::Admin::Customers::StoreCreditsController, type: :
expect(response).to have_http_status(:ok)
expect(json_response['data'].map { |sc| sc['id'] }).to include(store_credit.prefixed_id)
end
+
+ # Broken object-level authorization: the nested index must enforce the
+ # caller's ability on the parent customer. A customer the caller can't view
+ # is filtered out of the ability-scoped lookup, so it 404s rather than
+ # leaking its existence as a 403.
+ context 'with a limited-role admin that cannot read customers' do
+ include_context 'API v3 Admin with custom permissions'
+
+ let(:custom_permission_set) do
+ Class.new(Spree::PermissionSets::Base) do
+ def activate!
+ can [:read, :admin], Spree::Product
+ end
+ end
+ end
+
+ it 'cannot read another customer\'s store credits' do
+ get :index, params: { customer_id: customer.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+ end
+
+ # A role that can only VIEW customers must not be able to write to a
+ # customer's nested collection. `set_parent` resolves the parent via the
+ # write ability for write actions, so a view-only role can't reach the
+ # customer to mutate it (404, not a leaky 403).
+ describe 'write authorization with a read-only customer role' do
+ include_context 'API v3 Admin with custom permissions'
+
+ let(:custom_permission_set) do
+ Class.new(Spree::PermissionSets::Base) do
+ def activate!
+ can [:read, :admin], Spree.user_class
+ can :manage, Spree::StoreCredit
+ end
+ end
+ end
+
+ it 'allows reading the customer\'s store credits' do
+ get :index, params: { customer_id: customer.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ end
+
+ it 'cannot create a store credit on a customer it can only view' do
+ expect {
+ post :create, params: {
+ customer_id: customer.prefixed_id, amount: 10.0, currency: 'USD', category_id: category.id
+ }, as: :json
+ }.not_to change(customer.store_credits, :count)
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ # A secret API key authorizes purely on scopes (no CanCanCan): a read-only
+ # `read_store_credits` key must be rejected on any write at the scope-check
+ # layer, while `write_store_credits` succeeds.
+ describe 'secret API key scope enforcement on writes' do
+ let(:secret_api_key) { create(:api_key, :secret, store: store, scopes: [granted_scope]) }
+ let(:headers) { { 'x-spree-api-key' => secret_api_key.plaintext_token } }
+
+ let(:create_params) do
+ { customer_id: customer.prefixed_id, amount: 10.0, currency: 'USD', category_id: category.id }
+ end
+
+ context 'with a key granting only read_store_credits' do
+ let(:granted_scope) { 'read_store_credits' }
+
+ it 'allows reading' do
+ get :index, params: { customer_id: customer.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ end
+
+ it 'rejects creating a store credit with 403' do
+ expect {
+ post :create, params: create_params, as: :json
+ }.not_to change(customer.store_credits, :count)
+
+ expect(response).to have_http_status(:forbidden)
+ expect(json_response['error']['details']['required_scope']).to eq('write_store_credits')
+ end
+ end
+
+ context 'with a key granting write_store_credits' do
+ let(:granted_scope) { 'write_store_credits' }
+
+ it 'allows creating a store credit' do
+ expect {
+ post :create, params: create_params, as: :json
+ }.to change(customer.store_credits, :count).by(1)
+
+ expect(response).to have_http_status(:created)
+ end
+ end
end
describe 'POST #create' do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/invitations_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/invitations_controller_spec.rb
new file mode 100644
index 0000000000..219949ba06
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/invitations_controller_spec.rb
@@ -0,0 +1,88 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::InvitationsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin'
+
+ let!(:admin_role) { Spree::Role.default_admin_role }
+ let(:staff_role) { create(:role, name: 'staff') }
+
+ before { request.headers.merge!(headers) }
+
+ describe 'POST #create — role-grant privilege escalation' do
+ # The admin-role grant is rejected before the inviter is even resolved, so
+ # a secret API key (which has no human inviter) is the strictest principal
+ # to assert the guard against.
+ context 'authenticated via a secret API key (no human identity)' do
+ let(:caller_key) { create(:api_key, :secret, store: store, scopes: ['write_settings']) }
+ let(:headers) { { 'x-spree-api-key' => caller_key.plaintext_token } }
+
+ it 'forbids inviting straight into the admin role' do
+ expect {
+ post :create, params: { email: '[email protected]', role_id: admin_role.prefixed_id }, as: :json
+ }.not_to change(Spree::Invitation, :count)
+
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
+
+ context 'authenticated as a non-admin staff JWT' do
+ around do |example|
+ saved = Spree.permissions.dup
+ Spree.permissions.reset!
+ example.run
+ ensure
+ Spree.permissions.replace(saved)
+ end
+
+ let(:inviter_set) do
+ Class.new(Spree::PermissionSets::Base) do
+ def activate!
+ can :manage, Spree::Invitation
+ can [:read, :admin], Spree::Role
+ end
+ end
+ end
+
+ let(:staff_admin) do
+ create(:admin_user, :without_admin_role).tap { |u| u.role_users.create!(role: staff_role, resource: store) }
+ end
+ let(:headers) do
+ api_key_headers.merge('Authorization' => "Bearer #{Spree::Api::V3::TestingSupport.generate_jwt(staff_admin, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN)}")
+ end
+
+ before { Spree.permissions.assign(:staff, inviter_set) }
+
+ it 'forbids a non-admin from inviting into the admin role' do
+ expect {
+ post :create, params: { email: '[email protected]', role_id: admin_role.prefixed_id }, as: :json
+ }.not_to change(Spree::Invitation, :count)
+
+ expect(response).to have_http_status(:forbidden)
+ end
+
+ it 'allows inviting with a non-admin role' do
+ expect {
+ post :create, params: { email: '[email protected]', role_id: staff_role.prefixed_id }, as: :json
+ }.to change(Spree::Invitation, :count).by(1)
+
+ expect(response).to have_http_status(:created)
+ expect(Spree::Invitation.last.role).to eq(staff_role)
+ end
+ end
+
+ context 'authenticated as a super-admin JWT' do
+ let(:headers) { bearer_headers }
+
+ it 'allows inviting with the admin role' do
+ expect {
+ post :create, params: { email: '[email protected]', role_id: admin_role.prefixed_id }, as: :json
+ }.to change(Spree::Invitation, :count).by(1)
+
+ expect(response).to have_http_status(:created)
+ expect(Spree::Invitation.last.role).to eq(admin_role)
+ end
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/items_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/items_controller_spec.rb
index d87167679d..49d9dd6945 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/items_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/items_controller_spec.rb
@@ -35,6 +35,56 @@ RSpec.describe Spree::Api::V3::Admin::Orders::ItemsController, type: :controller
expect(response).to have_http_status(:created)
expect(json_response['quantity']).to eq(2)
end
+
+ # Authorization bypass: a read-only order role must not be able to mutate
+ # an order it can only view. `authorize_order_access!` requires :update for
+ # writes, so OrderDisplay (read-only) is rejected.
+ context 'with a read-only order role' do
+ include_context 'API v3 Admin with custom permissions'
+
+ let(:custom_permission_set) do
+ Class.new(Spree::PermissionSets::Base) do
+ def activate!
+ can [:read, :admin], Spree::Order
+ can [:read, :admin], Spree::LineItem
+ end
+ end
+ end
+
+ it 'forbids adding a line item' do
+ expect { subject }.not_to change(order.line_items, :count)
+
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
+
+ # The same property via the secret-API-key path: a read-only
+ # `read_orders` key is rejected at the scope-check layer on a write.
+ context 'with a read-only secret API key' do
+ let(:secret_api_key) { create(:api_key, :secret, store: store, scopes: [granted_scope]) }
+ let(:headers) { { 'x-spree-api-key' => secret_api_key.plaintext_token } }
+
+ context 'granting only read_orders' do
+ let(:granted_scope) { 'read_orders' }
+
+ it 'forbids adding a line item with 403' do
+ expect { subject }.not_to change(order.line_items, :count)
+
+ expect(response).to have_http_status(:forbidden)
+ expect(json_response['error']['details']['required_scope']).to eq('write_orders')
+ end
+ end
+
+ context 'granting write_orders' do
+ let(:granted_scope) { 'write_orders' }
+
+ it 'adds a line item' do
+ expect { subject }.to change(order.line_items, :count).by(1)
+
+ expect(response).to have_http_status(:created)
+ end
+ end
+ end
end
describe 'PATCH #update' do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rb
index dd41f79b13..2b416986d5 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rb
@@ -92,6 +92,36 @@ RSpec.describe Spree::Api::V3::Admin::PriceListsController, type: :controller do
expect(list.price_rules.first).to be_a(Spree::PriceRules::VolumeRule)
end
end
+
+ context 'cross-store IDOR — membership in another store' do
+ let(:other_store) { create(:store) }
+ let(:foreign_product) { create(:product, store: other_store) }
+ let(:foreign_variant) { foreign_product.master }
+
+ it 'ignores another store\'s product in product_ids' do
+ post :create,
+ params: { name: 'Sneaky list', match_policy: 'all', product_ids: [foreign_product.prefixed_id] },
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ list = Spree::PriceList.for_store(store).find_by!(name: 'Sneaky list')
+ expect(list.products).to be_empty
+ end
+
+ it 'ignores another store\'s variant in nested prices' do
+ post :create,
+ params: {
+ name: 'Sneaky price list',
+ match_policy: 'all',
+ prices: [{ variant_id: foreign_variant.prefixed_id, currency: 'USD', amount: '0.01' }]
+ },
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ list = Spree::PriceList.for_store(store).find_by!(name: 'Sneaky price list')
+ expect(list.prices.where(variant_id: foreign_variant.id)).to be_empty
+ end
+ end
end
describe 'POST #create — per rule type' do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rb
index b7311cc941..7226dc504f 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rb
@@ -329,6 +329,52 @@ RSpec.describe Spree::Api::V3::Admin::PricesController, type: :controller do
expect(foreign.price_list_id).to eq(other_list.id)
end
end
+
+ context 'cross-store IDOR — a variant in another store' do
+ let(:other_store) { create(:store) }
+ let(:other_product) { create(:product, store: other_store) }
+ let(:other_variant) { other_product.master }
+
+ it 'rejects writing a price on another store\'s variant and leaves it untouched' do
+ # The factory seeds a USD base price on the foreign master; capture it
+ # so we prove an in-place update didn't slip through (count alone wouldn't).
+ foreign_price = other_variant.prices.find_by!(currency: 'USD', price_list_id: nil)
+
+ post :bulk_upsert,
+ params: {
+ prices: [{
+ variant_id: other_variant.prefixed_id,
+ currency: 'USD',
+ amount: '0.01'
+ }]
+ },
+ as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['code']).to eq('invalid_prices')
+ expect(foreign_price.reload.amount).not_to eq(BigDecimal('0.01'))
+ end
+
+ it 'rejects targeting another store\'s price list and leaves its rows untouched' do
+ other_list = create(:price_list, store: other_store)
+ foreign_row = create(:price, variant: variant, price_list: other_list, currency: 'USD', amount: 42.0)
+
+ post :bulk_upsert,
+ params: {
+ prices: [{
+ variant_id: variant.prefixed_id,
+ currency: 'USD',
+ price_list_id: other_list.prefixed_id,
+ amount: '0.01'
+ }]
+ },
+ as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['code']).to eq('invalid_prices')
+ expect(foreign_row.reload.amount).to eq(BigDecimal('42.0'))
+ end
+ end
end
describe 'DELETE #bulk_destroy' do