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 scopes (part 2) (#14190)

Damian Legawiecf6268d638b07
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
index 14191b57c0..d1b40990e6 100644
--- 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
@@ -2,49 +2,107 @@ 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.
+ # Shared guard for staff role grants (admin_users#update and
+ # invitations#create). A grant is rejected when, in order:
#
- # 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).
+ # 1. (opt-in) the caller can't `:create` a Spree::RoleUser — i.e. lacks
+ # the RoleManagement permission set;
+ # 2. it includes the literal `admin` role and the caller does not hold
+ # it on the current store;
+ # 3. it includes any role whose permission sets exceed the caller's own
+ # (catches SuperUser-equivalent custom roles the name check misses).
+ #
+ # API-key principals hold no roles, so they can grant only roles that
+ # activate no permission sets.
module RoleGrantGuard
extend ActiveSupport::Concern
private
# @param role_ids [Array<Integer,String>] resolved (decoded) role ids
+ # @param require_role_management [Boolean] also require CanCanCan
+ # authority to create a RoleUser. Set by `admin_users#update`, whose
+ # own authorization is only `:update` on the user; the invitations
+ # flow leaves it off (its gate is `manage Invitation`).
# @return [Boolean] true if the request was rejected (caller should return)
- def reject_unauthorized_role_grant!(role_ids)
+ def reject_unauthorized_role_grant!(role_ids, require_role_management: false)
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)
+ # The management gate runs whenever a role mutation is attempted —
+ # before resolving ids — so passing unknown ids can't slip the
+ # reconciliation (which would still remove the user's current roles)
+ # past a caller without role-management authority.
+ return true if require_role_management && reject_without_role_management!
+
+ roles = Spree::Role.where(id: role_ids.map(&:to_s)).to_a
+ return false if roles.empty?
+
+ return true if reject_admin_role_grant!(roles)
+ return true if reject_privilege_escalating_grant!(roles)
+
+ false
+ end
+
+ # For API-key principals CanCanCan is permissive (ScopedAuthorization is
+ # their gate), so this only constrains JWT admins.
+ def reject_without_role_management!
+ return false if scope_limited_principal?
+ return false if can?(:create, Spree::RoleUser)
+
+ deny_role_grant!('You are not authorized to assign roles.')
+ end
+
+ def reject_admin_role_grant!(roles)
+ return false unless roles.any? { |role| role.name == Spree::Role::ADMIN_ROLE }
return false if caller_holds_admin_role?
+ deny_role_grant!('You cannot grant the admin role.')
+ end
+
+ # A caller holding the admin role bounds nothing; the literal admin role
+ # is already gated by reject_admin_role_grant!.
+ def reject_privilege_escalating_grant!(roles)
+ return false if caller_holds_admin_role?
+
+ caller_sets = Spree.permissions.permission_sets_for_roles(caller_role_names)
+ escalating = roles.reject { |role| grantable_within?(role, caller_sets) }
+ return false if escalating.empty?
+
+ deny_role_grant!("You cannot grant roles beyond your own privileges: #{escalating.map(&:name).join(', ')}")
+ end
+
+ # A role is grantable when every permission set it activates is one the
+ # caller already holds.
+ def grantable_within?(role, caller_sets)
+ (Spree.permissions.permission_sets_for(role.name) - caller_sets).empty?
+ end
+
+ # The caller's store-scoped role names, fetched once per request.
+ def caller_role_names
+ return @caller_role_names if defined?(@caller_role_names)
+
+ user = try_spree_current_user
+ @caller_role_names =
+ if user.respond_to?(:role_users)
+ user.role_users.where(resource: current_store).joins(:role).
+ pluck("#{Spree::Role.table_name}.name")
+ else
+ []
+ end
+ end
+
+ def caller_holds_admin_role?
+ caller_role_names.include?(Spree::Role::ADMIN_ROLE)
+ end
+
+ def deny_role_grant!(message)
render_error(
code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:access_denied],
- message: 'You cannot grant the admin role.',
+ message: message,
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
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rb
index cfcfcb9923..9db9f629d9 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rb
@@ -39,12 +39,34 @@ module Spree
return true
end
- # Fall back to JWT authentication
- require_authentication!
+ # Fall back to JWT authentication, then bind the admin to the store
+ # they hold a role on (the token itself is store-agnostic).
+ return false unless require_authentication!
+
+ require_store_membership!
end
private
+ # Rejects an authenticated JWT admin who has no role on +current_store+.
+ # API-key principals are already store-bound and skip this check.
+ def require_store_membership!
+ return true if current_user_member_of_store?
+
+ render_error(
+ code: ErrorHandler::ERROR_CODES[:access_denied],
+ message: 'You do not have access to this store.',
+ status: :forbidden
+ )
+ false
+ end
+
+ def current_user_member_of_store?
+ return false unless current_user.respond_to?(:role_users)
+
+ current_user.role_users.exists?(resource: current_store)
+ end
+
def set_no_store_cache
response.headers['Cache-Control'] = 'private, no-store'
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 55db497d16..4d09a51b23 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
@@ -35,8 +35,11 @@ module Spree
# `nil` when the key is absent (leave roles untouched); an array
# (possibly empty, to clear) when the client sends `role_ids`.
+ # `require_role_management:` — this action only authorizes `:update`
+ # on the user, so role assignment must be separately gated by the
+ # RoleManagement permission set, not by profile-edit rights.
role_ids = role_ids_param if params.key?(:role_ids)
- return if role_ids && reject_unauthorized_role_grant!(role_ids)
+ return if role_ids && reject_unauthorized_role_grant!(role_ids, require_role_management: true)
if @resource.update(identity_params)
apply_role_ids(role_ids) if role_ids
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 b97c19ec70..67f71c5f00 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
@@ -10,6 +10,13 @@ module Spree
:credit_cards
end
+ # Customers are global; a saved card belongs to the store-scoped
+ # payment method it was created against, so the nested collection is
+ # bound to the current store's payment methods.
+ def scope
+ @parent.credit_cards.where(payment_method_id: current_store.payment_methods.select(:id))
+ end
+
def model_class
Spree::CreditCard
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 8f5b419c35..363fb73c71 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
@@ -67,6 +67,12 @@ module Spree
:store_credits
end
+ # Customers are global; store credits belong to a store, so the
+ # nested collection is bound to the current store.
+ def scope
+ @parent.store_credits.for_store(current_store)
+ end
+
def model_class
Spree::StoreCredit
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/adjustments_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/adjustments_controller.rb
index b8bbcc0a8c..741d646178 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/adjustments_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/adjustments_controller.rb
@@ -4,8 +4,6 @@ module Spree
module Admin
module Orders
class AdjustmentsController < BaseController
- scoped_resource :orders
-
protected
def model_class
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 0540661b1c..ce1d75ee09 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
@@ -8,6 +8,8 @@ module Spree
before_action :authorize_order_access!
+ scoped_resource :orders
+
protected
def set_parent
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rb
index 78690d72b6..1801228a1b 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rb
@@ -93,8 +93,10 @@ module Spree
:shipments
end
+ # State changes go through the dedicated `fulfill`/`cancel`/`resume`
+ # member actions, not mass assignment.
def permitted_params
- params.permit(:tracking, :selected_shipping_rate_id, :stock_location_id, :state)
+ params.permit(:tracking, :selected_shipping_rate_id, :stock_location_id)
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/gift_cards_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/gift_cards_controller.rb
index 404b5797ce..2af7b7dbf7 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/gift_cards_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/gift_cards_controller.rb
@@ -4,8 +4,6 @@ module Spree
module Admin
module Orders
class GiftCardsController < BaseController
- scoped_resource :gift_cards
-
skip_before_action :set_resource, raise: false
# POST /api/v3/admin/orders/:order_id/gift_cards
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/items_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/items_controller.rb
index 6f31c6c824..5920ee2bf5 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/items_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/items_controller.rb
@@ -4,8 +4,6 @@ module Spree
module Admin
module Orders
class ItemsController < BaseController
- scoped_resource :orders
-
# POST /api/v3/admin/orders/:order_id/items
def create
with_order_lock do
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/store_credits_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/store_credits_controller.rb
index f83b630297..aa6cff7429 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/store_credits_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/store_credits_controller.rb
@@ -4,8 +4,6 @@ module Spree
module Admin
module Orders
class StoreCreditsController < BaseController
- scoped_resource :store_credits
-
skip_before_action :set_resource, raise: false
# POST /api/v3/admin/orders/:order_id/store_credits
diff --git a/spree/api/app/controllers/spree/api/v3/admin/stock_items_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/stock_items_controller.rb
index bb20d45d5e..af7f62226d 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/stock_items_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/stock_items_controller.rb
@@ -28,6 +28,13 @@ module Spree
def apply_collection_sort(collection)
collection.order(Spree::StockItem.arel_table[:id].asc)
end
+
+ # Stock items are auto-created against a (variant, stock_location)
+ # pair and never re-pointed, so update only touches the count and
+ # backorder flag — not the variant or location FKs.
+ def permitted_params
+ params.permit(:count_on_hand, :backorderable, metadata: {})
+ end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/stock_locations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/stock_locations_controller.rb
index 74a59dc21b..0e315de02b 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/stock_locations_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/stock_locations_controller.rb
@@ -15,6 +15,12 @@ module Spree
Spree.api.admin_stock_location_serializer
end
+ # Stock locations are shared across stores, so writes are store-wide
+ # administration: reads need `read_stock`, writes need `write_settings`.
+ def scoped_resource_name
+ read_actions.include?(action_name) ? :stock : :settings
+ end
+
def scope
super.order_default
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/tags_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/tags_controller.rb
index d6a35705c1..0a2954c34b 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/tags_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/tags_controller.rb
@@ -3,24 +3,32 @@ module Spree
module V3
module Admin
class TagsController < BaseController
+ # The required scope depends on the requested `taggable_type`, so it's
+ # resolved per request rather than via a static `scoped_resource`.
+ # `authorize_taggable_scope!` enforces it for API-key principals.
skip_scope_check!
+ before_action :authorize_taggable_scope!, only: :index
+
MAX_RESULTS = 50
+ # Maps a taggable type to the read scope an API key must hold to
+ # enumerate its tag vocabulary. Types absent from this map require
+ # `read_all`.
+ def self.scope_for_taggable_type
+ {
+ 'Spree::Product' => 'read_products',
+ 'Spree::Order' => 'read_orders',
+ Spree.user_class.to_s => 'read_customers'
+ }
+ end
+
def index
- taggable_type = params[:taggable_type].to_s
- unless allowed_taggable_types.include?(taggable_type)
- render_error(
- code: 'invalid_taggable_type',
- message: "taggable_type must be one of #{allowed_taggable_types.join(', ')}",
- status: :unprocessable_content
- )
- return
- end
+ return unless valid_taggable_type?
scope = ActsAsTaggableOn::Tag.
joins(:taggings).
- where(ActsAsTaggableOn.taggings_table => { taggable_type: taggable_type, context: 'tags' }).
+ where(ActsAsTaggableOn.taggings_table => taggings_conditions).
distinct.
order(:name).
limit(MAX_RESULTS)
@@ -37,6 +45,48 @@ module Spree
private
+ def taggable_type
+ params[:taggable_type].to_s
+ end
+
+ def valid_taggable_type?
+ return true if allowed_taggable_types.include?(taggable_type)
+
+ render_error(
+ code: 'invalid_taggable_type',
+ message: "taggable_type must be one of #{allowed_taggable_types.join(', ')}",
+ status: :unprocessable_content
+ )
+ false
+ end
+
+ # Tagging filter. `Spree::Order` carries a `tenant` (store_id) column
+ # via `acts_as_taggable_tenant`, so its tag vocabulary is bounded to
+ # the current store; other taggables fall back to the type filter.
+ def taggings_conditions
+ conditions = { taggable_type: taggable_type, context: 'tags' }
+ conditions[:tenant] = current_store.id.to_s if taggable_type == 'Spree::Order'
+ conditions
+ end
+
+ # Per-type scope check for API-key principals: a key listing product
+ # tags needs `read_products`, order tags `read_orders`, etc. JWT
+ # admins are gated by store membership + CanCanCan, not scopes.
+ def authorize_taggable_scope!
+ return unless current_api_key
+ return unless allowed_taggable_types.include?(taggable_type)
+
+ required = self.class.scope_for_taggable_type.fetch(taggable_type, 'read_all')
+ return if current_api_key.has_scope?(required)
+
+ render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:access_denied],
+ message: "API key lacks scope: #{required}",
+ status: :forbidden,
+ details: { required_scope: required }
+ )
+ end
+
# Sourced from `Spree.taggable_types` (registered in
# `Spree::Core::Engine`'s after_initialize block). Apps extend the
# list in an initializer without overriding this controller:
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
index 65f9e83052..ec6908f221 100644
--- 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
@@ -74,6 +74,70 @@ RSpec.describe Spree::Api::V3::Admin::AdminUsersController, type: :controller do
expect(response).to have_http_status(:forbidden)
expect(target.reload.spree_admin?(store)).to be(false)
end
+
+ it 'forbids assigning any role without role-management authority' do
+ expect {
+ patch :update, params: { id: target.prefixed_id, role_ids: [staff_role.prefixed_id] }, as: :json
+ }.not_to change { target.role_users.where(resource: store).count }
+
+ expect(response).to have_http_status(:forbidden)
+ end
+
+ # Unknown role ids must not slip the management gate: the reconciliation
+ # would otherwise strip the target's existing roles.
+ it 'forbids a role mutation with unresolved role ids' do
+ expect {
+ patch :update, params: { id: target.prefixed_id, role_ids: ['role_nonexistent'] }, as: :json
+ }.not_to change { target.role_users.where(resource: store).count }
+
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
+
+ context 'authenticated as a staff JWT holding RoleManagement' do
+ around do |example|
+ saved = Spree.permissions.dup
+ Spree.permissions.reset!
+ example.run
+ ensure
+ Spree.permissions.replace(saved)
+ end
+
+ let(:role_manager_set) do
+ Class.new(Spree::PermissionSets::Base) do
+ def activate!
+ can :manage, Spree.admin_user_class
+ can :manage, Spree::RoleUser
+ 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, role_manager_set) }
+
+ it 'allows assigning a non-privileged role' do
+ patch :update, params: { id: target.prefixed_id, role_ids: [staff_role.prefixed_id] }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(target.role_users.where(resource: store, role: staff_role)).to exist
+ end
+
+ it 'forbids assigning a SuperUser-equivalent role it does not hold' do
+ owner_role = create(:role, name: 'owner')
+ Spree.permissions.assign(:owner, Spree::PermissionSets::SuperUser)
+
+ patch :update, params: { id: target.prefixed_id, role_ids: [owner_role.prefixed_id] }, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ expect(target.role_users.where(resource: store, role: owner_role)).not_to exist
+ end
end
context 'authenticated as a super-admin JWT' do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/base_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/base_controller_spec.rb
index bac5395fe9..5a55305887 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/base_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/base_controller_spec.rb
@@ -157,7 +157,7 @@ RSpec.describe Spree::Api::V3::Admin::BaseController, type: :controller do
end
end
- context 'with a non-admin user JWT token' do
+ context 'with a non-admin user JWT token (no role on the store)' do
let(:customer) { create(:user) }
let(:customer_admin_jwt) do
Spree::Api::V3::TestingSupport.generate_jwt(
@@ -168,11 +168,33 @@ RSpec.describe Spree::Api::V3::Admin::BaseController, type: :controller do
before { request.headers['Authorization'] = "Bearer #{customer_admin_jwt}" }
- it 'authenticates the user (authorization is handled separately)' do
+ it 'returns 403 forbidden' do
get :index
- expect(response).to have_http_status(:ok)
- expect(json_response['user_id']).to eq(customer.id)
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
+
+ context 'with an admin JWT whose user has no role on the current store' do
+ let(:other_store) { create(:store) }
+ let(:foreign_admin) do
+ create(:admin_user, :without_admin_role).tap do |u|
+ u.role_users.create!(role: Spree::Role.default_admin_role, resource: other_store)
+ end
+ end
+ let(:foreign_admin_jwt) do
+ Spree::Api::V3::TestingSupport.generate_jwt(
+ foreign_admin,
+ audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN
+ )
+ end
+
+ before { request.headers['Authorization'] = "Bearer #{foreign_admin_jwt}" }
+
+ it 'returns 403 forbidden' do
+ get :index
+
+ expect(response).to have_http_status(:forbidden)
end
end
end
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 e1410be9b8..3859bbc101 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
@@ -82,4 +82,31 @@ RSpec.describe Spree::Api::V3::Admin::Customers::CreditCardsController, type: :c
end
end
end
+
+ describe 'cross-store isolation' do
+ let(:other_store) { create(:store) }
+ let(:other_payment_method) { create(:credit_card_payment_method, stores: [other_store]) }
+ let!(:foreign_card) { create(:credit_card, user: customer, payment_method: other_payment_method) }
+
+ it 'excludes cards from other stores in the index' do
+ get :index, params: { customer_id: customer.prefixed_id }, as: :json
+
+ ids = json_response['data'].map { |c| c['id'] }
+ expect(ids).to include(credit_card.prefixed_id)
+ expect(ids).not_to include(foreign_card.prefixed_id)
+ end
+
+ it 'cannot show a card stored against another store' do
+ get :show, params: { customer_id: customer.prefixed_id, id: foreign_card.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it 'cannot delete a card stored against another store' do
+ delete :destroy, params: { customer_id: customer.prefixed_id, id: foreign_card.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(Spree::CreditCard.exists?(foreign_card.id)).to be true
+ end
+ end
end
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 b87c27774f..216b17ab29 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
@@ -180,4 +180,39 @@ RSpec.describe Spree::Api::V3::Admin::Customers::StoreCreditsController, type: :
end
end
end
+
+ describe 'cross-store isolation' do
+ let(:other_store) { create(:store) }
+ let!(:foreign_credit) do
+ create(:store_credit, user: customer, store: other_store, amount: 99.00, category: category)
+ end
+
+ it 'excludes other stores\' credits from the index' do
+ get :index, params: { customer_id: customer.prefixed_id }, as: :json
+
+ ids = json_response['data'].map { |sc| sc['id'] }
+ expect(ids).to include(store_credit.prefixed_id)
+ expect(ids).not_to include(foreign_credit.prefixed_id)
+ end
+
+ it 'cannot show another store\'s credit' do
+ get :show, params: { customer_id: customer.prefixed_id, id: foreign_credit.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it 'cannot update another store\'s credit' do
+ patch :update, params: { customer_id: customer.prefixed_id, id: foreign_credit.prefixed_id, memo: 'pwned' }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(foreign_credit.reload.memo).not_to eq('pwned')
+ end
+
+ it 'cannot delete another store\'s credit' do
+ delete :destroy, params: { customer_id: customer.prefixed_id, id: foreign_credit.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(Spree::StoreCredit.exists?(foreign_credit.id)).to be true
+ end
+ end
end
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
index 219949ba06..274df5085d 100644
--- 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
@@ -70,6 +70,17 @@ RSpec.describe Spree::Api::V3::Admin::InvitationsController, type: :controller d
expect(response).to have_http_status(:created)
expect(Spree::Invitation.last.role).to eq(staff_role)
end
+
+ it 'forbids inviting into a SuperUser-equivalent custom role' do
+ owner_role = create(:role, name: 'owner')
+ Spree.permissions.assign(:owner, Spree::PermissionSets::SuperUser)
+
+ expect {
+ post :create, params: { email: '[email protected]', role_id: owner_role.prefixed_id }, as: :json
+ }.not_to change(Spree::Invitation, :count)
+
+ expect(response).to have_http_status(:forbidden)
+ end
end
context 'authenticated as a super-admin JWT' do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/fulfillments_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/fulfillments_controller_spec.rb
index 23676c8f14..92c13ddd29 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/fulfillments_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/fulfillments_controller_spec.rb
@@ -42,6 +42,20 @@ RSpec.describe Spree::Api::V3::Admin::Orders::FulfillmentsController, type: :con
expect(response).to have_http_status(:ok)
expect(shipment.reload.tracking).to eq('1Z999AA10123456784')
end
+
+ it 'ignores a state parameter' do
+ original_state = shipment.state
+
+ patch :update, params: {
+ order_id: order.prefixed_id,
+ id: shipment.prefixed_id,
+ state: 'shipped'
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(shipment.reload.state).to eq(original_state)
+ expect(shipment.state).not_to eq('shipped')
+ end
end
describe 'PATCH #fulfill' do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/store_credits_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/store_credits_controller_spec.rb
index c371579e0c..8836d1874a 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/store_credits_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/store_credits_controller_spec.rb
@@ -96,4 +96,29 @@ RSpec.describe Spree::Api::V3::Admin::Orders::StoreCreditsController, type: :con
end
end
end
+
+ describe 'API-key scope enforcement' do
+ let(:headers) { { 'x-spree-api-key' => api_key.plaintext_token } }
+
+ context 'with a key holding only write_store_credits' do
+ let(:api_key) { create(:api_key, :secret, store: store, scopes: ['write_store_credits']) }
+
+ it 'forbids applying store credit to the order' do
+ post :create, params: { order_id: order.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ expect(json_response['error']['details']['required_scope']).to eq('write_orders')
+ end
+ end
+
+ context 'with a key holding write_orders' do
+ let(:api_key) { create(:api_key, :secret, store: store, scopes: ['write_orders']) }
+
+ it 'allows applying store credit to the order' do
+ post :create, params: { order_id: order.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:created)
+ end
+ end
+ end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/stock_items_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/stock_items_controller_spec.rb
index 96d31e7cbe..f5d58b5217 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/stock_items_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/stock_items_controller_spec.rb
@@ -45,6 +45,23 @@ RSpec.describe Spree::Api::V3::Admin::StockItemsController, type: :controller do
expect(response).to have_http_status(:ok)
expect(stock_item.reload.backorderable).to be true
end
+
+ it 'ignores variant_id and stock_location_id' do
+ other_variant = create(:variant)
+ other_location = create(:stock_location)
+
+ patch :update, params: {
+ id: stock_item.prefixed_id,
+ variant_id: other_variant.prefixed_id,
+ stock_location_id: other_location.prefixed_id,
+ count_on_hand: 7
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(stock_item.reload.variant_id).to eq(variant.id)
+ expect(stock_item.stock_location_id).to eq(stock_location.id)
+ expect(stock_item.count_on_hand).to eq(7)
+ end
end
describe 'DELETE #destroy' do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/stock_locations_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/stock_locations_controller_spec.rb
index 6bf929ddcd..cfb894b4e2 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/stock_locations_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/stock_locations_controller_spec.rb
@@ -189,4 +189,35 @@ RSpec.describe Spree::Api::V3::Admin::StockLocationsController, type: :controlle
expect(Spree::StockLocation.with_deleted.find(stock_location.id).deleted_at).not_to be_nil
end
end
+
+ describe 'API-key scope enforcement' do
+ let(:headers) { { 'x-spree-api-key' => api_key.plaintext_token } }
+
+ context 'with a key holding only write_stock' do
+ let(:api_key) { create(:api_key, :secret, store: store, scopes: ['write_stock']) }
+
+ it 'allows reading the index' do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:ok)
+ end
+
+ it 'forbids destroying a stock location' do
+ delete :destroy, params: { id: stock_location.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ expect(json_response['error']['details']['required_scope']).to eq('write_settings')
+ end
+ end
+
+ context 'with a key holding write_settings' do
+ let(:api_key) { create(:api_key, :secret, store: store, scopes: ['write_settings', 'read_stock']) }
+
+ it 'allows destroying a stock location' do
+ delete :destroy, params: { id: stock_location.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:no_content)
+ end
+ end
+ end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/tags_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/tags_controller_spec.rb
new file mode 100644
index 0000000000..93ebbafec8
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/tags_controller_spec.rb
@@ -0,0 +1,73 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::TagsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin'
+
+ before { request.headers.merge!(headers) }
+
+ describe 'GET #index' do
+ context 'authenticated as an admin (JWT)' do
+ let(:headers) { bearer_headers }
+
+ let!(:tagged_product) { create(:product, store: store, tag_list: ['summer']) }
+
+ it 'returns matching tag names for the type' do
+ get :index, params: { taggable_type: 'Spree::Product' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data'].map { |t| t['name'] }).to include('summer')
+ end
+
+ it 'rejects an unregistered taggable type' do
+ get :index, params: { taggable_type: 'Spree::Secret' }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+ end
+
+ context 'order tag vocabulary is store-scoped' do
+ let(:headers) { bearer_headers }
+
+ let(:other_store) { create(:store) }
+ let!(:own_order) { create(:order, store: store, tag_list: ['vip']) }
+ let!(:foreign_order) { create(:order, store: other_store, tag_list: ['fraud-watch']) }
+
+ it 'excludes another store\'s order tags' do
+ get :index, params: { taggable_type: 'Spree::Order' }, as: :json
+
+ names = json_response['data'].map { |t| t['name'] }
+ expect(names).to include('vip')
+ expect(names).not_to include('fraud-watch')
+ end
+ end
+
+ describe 'API-key scope enforcement' do
+ let(:headers) { { 'x-spree-api-key' => api_key.plaintext_token } }
+ let!(:tagged_user) { create(:user, tag_list: ['vip']) }
+
+ context 'with a key lacking read_customers' do
+ let(:api_key) { create(:api_key, :secret, store: store, scopes: ['read_products']) }
+
+ it 'forbids listing customer tags' do
+ get :index, params: { taggable_type: Spree.user_class.to_s }, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ expect(json_response['error']['details']['required_scope']).to eq('read_customers')
+ end
+ end
+
+ context 'with a key holding read_customers' do
+ let(:api_key) { create(:api_key, :secret, store: store, scopes: ['read_customers']) }
+
+ it 'allows listing customer tags' do
+ get :index, params: { taggable_type: Spree.user_class.to_s }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data'].map { |t| t['name'] }).to include('vip')
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/ability.rb b/spree/core/app/models/spree/ability.rb
index c2bcd41741..556f8df6d2 100644
--- a/spree/core/app/models/spree/ability.rb
+++ b/spree/core/app/models/spree/ability.rb
@@ -44,15 +44,18 @@ module Spree
activate_permission_sets(permission_sets)
end
- # Determines the role names for the current user.
+ # Determines the role names for the current user, scoped to the current
+ # store. A +Spree::RoleUser+ binds a role to a store via +resource+, so a
+ # role held on one store does not apply on another.
#
# @return [Array<Symbol>] the role names
def determine_role_names
return [:default] unless @user.persisted?
- # First, try to get roles from the spree_roles association
- if @user.respond_to?(:spree_roles)
- role_names = @user.spree_roles.pluck(:name).map(&:to_sym)
+ if @user.respond_to?(:role_users)
+ role_names = @user.role_users.where(resource: @store).
+ joins(:role).
+ pluck("#{Spree::Role.table_name}.name").map(&:to_sym)
return role_names if role_names.any?
end
diff --git a/spree/core/spec/models/spree/ability_spec.rb b/spree/core/spec/models/spree/ability_spec.rb
index 925a8faa4e..d7de3b22c2 100644
--- a/spree/core/spec/models/spree/ability_spec.rb
+++ b/spree/core/spec/models/spree/ability_spec.rb
@@ -269,4 +269,24 @@ describe Spree::Ability, type: :model do
end
end
end
+
+ context 'role resolution is scoped to the current store' do
+ let(:admin) { create(:admin_user, :without_admin_role) }
+ let(:store_a) { @default_store }
+ let(:store_b) { create(:store) }
+
+ before do
+ admin.role_users.create!(role: Spree::Role.default_admin_role, resource: store_a)
+ end
+
+ it 'grants admin authority on the store where the role is held' do
+ ability = Spree::Ability.new(admin, store: store_a)
+ expect(ability).to be_able_to :manage, Spree::Product.new
+ end
+
+ it 'does not grant admin authority on a store where no role is held' do
+ ability = Spree::Ability.new(admin, store: store_b)
+ expect(ability).not_to be_able_to :manage, Spree::Product.new
+ end
+ end
end