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.

Added a ceiling for delegated credentials

Damian Legawiec51eab0a9e6a5
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/scoped_authorization.rb b/spree/api/app/controllers/concerns/spree/api/v3/scoped_authorization.rb
index 3ed90db39a..f5e35502d1 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/scoped_authorization.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/scoped_authorization.rb
@@ -142,7 +142,7 @@ module Spree
# fallback, host-registered types) defer to CanCanCan's `authorize!`
# — the caller stays gated per subject, just not by key.
return unless Spree.permissions.key?(required)
- return if ability.permission_keys.include?(required)
+ return if staff_permission_keys.include?(required)
Rails.logger.info do
"[Spree] Access denied: user=#{current_user.id} required=#{required} " \
@@ -216,7 +216,44 @@ module Spree
ability = current_ability
return true unless ability.respond_to?(:permission_keys)
- ability.permission_keys.include?(key.to_s)
+ staff_permission_keys.include?(key.to_s)
+ end
+
+ # What a staff principal may do here, as catalog keys.
+ #
+ # Usually their roles' keys. When the request arrived on a delegated
+ # credential — an OAuth token a staff member approved for an agent or
+ # an app — the grant's scopes narrow that set: the person consented to
+ # part of their authority, not all of it. The grant can only ever
+ # subtract, so approving a client never widens what its owner holds.
+ #
+ # @return [Array<String>]
+ def staff_permission_keys
+ @staff_permission_keys ||= begin
+ ability = current_ability
+ held = ability.respond_to?(:permission_keys) ? ability.permission_keys.map(&:to_s) : []
+ granted = delegated_permission_keys
+ granted.nil? ? held : held & granted
+ end
+ end
+
+ # The scopes of the delegated credential this request arrived on, or
+ # nil when the staff member is acting directly (a dashboard session).
+ #
+ # Controllers that accept an OAuth token override
+ # `current_oauth_token`; everything else inherits nil and is unchanged.
+ #
+ # @return [Array<String>, nil]
+ def delegated_permission_keys
+ token = current_oauth_token
+ return nil if token.blank?
+
+ Spree.permissions.expand_keys(token.scopes.to_a)
+ end
+
+ # @return [Spree::OauthAccessToken, nil]
+ def current_oauth_token
+ nil
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/scoped_authorization_spec.rb b/spree/api/spec/controllers/spree/api/v3/scoped_authorization_spec.rb
index b19ca3cdf5..ac8f8b6884 100644
--- a/spree/api/spec/controllers/spree/api/v3/scoped_authorization_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/scoped_authorization_spec.rb
@@ -136,6 +136,63 @@ RSpec.describe Spree::Api::V3::Admin::OrdersController, type: :controller do
end
end
end
+
+ # A staff member can delegate part of their authority to an agent or an app
+ # through an OAuth grant. The grant is a ceiling on top of their roles, so
+ # the gate asks for the intersection — approving a client must never be a
+ # way to gain permissions the person does not have.
+ describe 'request on a delegated credential' do
+ before do
+ request.headers['X-Spree-Api-Key'] = nil
+ request.headers['Authorization'] = "Bearer #{admin_jwt_token}"
+ allow(controller).to receive(:current_oauth_token).and_return(delegated_token)
+ end
+
+ let(:scopes) { ['read_customers'] }
+
+ def token_granting(*granted)
+ instance_double(Spree::OauthAccessToken, scopes: Doorkeeper::OAuth::Scopes.from_array(granted))
+ end
+
+ context 'when the grant covers the action' do
+ let(:delegated_token) { token_granting('read_orders') }
+
+ it 'allows it' do
+ get :index, as: :json
+ expect(response).to have_http_status(:ok)
+ end
+ end
+
+ context 'when the grant does not cover the action' do
+ let(:delegated_token) { token_granting('read_products') }
+
+ it 'denies it even though the admin could do it directly' do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ expect(JSON.parse(response.body)['error']['details']['required_permission']).to eq('read_orders')
+ end
+ end
+
+ context 'when the grant names more than the person holds' do
+ let(:staffer) do
+ create(:admin_user, :without_admin_role).tap do |user|
+ create(:role_user, user: user, role: create(:role, name: 'products-only', permissions: %w[read_products], resource: store))
+ end
+ end
+ let(:delegated_token) { token_granting(*Spree.permissions.catalog_keys) }
+
+ before do
+ request.headers['Authorization'] =
+ "Bearer #{Spree::Api::V3::TestingSupport.generate_jwt(staffer, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN)}"
+ end
+
+ it 'grants nothing extra' do
+ get :index, as: :json
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
+ end
end
# Regression: the promotions controllers declare `scoped_resource :promotions`,
diff --git a/spree/core/lib/spree/agent_tools/context.rb b/spree/core/lib/spree/agent_tools/context.rb
index ca87f00977..a6d7ab5e44 100644
--- a/spree/core/lib/spree/agent_tools/context.rb
+++ b/spree/core/lib/spree/agent_tools/context.rb
@@ -35,12 +35,18 @@ module Spree
# @param api_key [Spree::ApiKey, nil] a secret key
# @param ability [Spree::Ability, nil] defaults to the user's ability for
# this store — abilities are store-scoped, so the store must be passed
- def initialize(store:, user: nil, api_key: nil, ability: nil)
+ # @param granted_scopes [Array<String>, nil] when the caller acts for a
+ # user through a delegated grant (an OAuth token), the scopes that
+ # grant carries. They *narrow* the user's own authority and can never
+ # widen it, so a merchant who consented to reading products does not
+ # hand over everything their role could do.
+ def initialize(store:, user: nil, api_key: nil, ability: nil, granted_scopes: nil)
raise ArgumentError, 'Spree::AgentTools::Context needs a user or an api_key' if user.nil? && api_key.nil?
@store = store
@user = user
@api_key = api_key
+ @granted_scopes = granted_scopes
@ability = ability || (Spree::Dependencies.ability_class.constantize.new(user, store: store) if user)
end
@@ -91,10 +97,31 @@ module Spree
# @return [Boolean]
def can?(action, record)
return true unless user_principal?
+ # A delegated grant narrows what the user may do here, so a record
+ # check has to honour it too: being offered a tool is not permission
+ # to use it on a record the grant does not cover.
+ return false unless granted_for?(action, record)
ability.can?(action, record)
end
+ # Whether the grant covers an action on this record's resource. A
+ # context without a grant is the user acting directly and is unlimited
+ # by this; a grant that names no scope for the resource refuses.
+ #
+ # @return [Boolean]
+ def granted_for?(action, record)
+ return true if @granted_scopes.nil?
+
+ scope = Spree.permissions.scope_for_resource(record.is_a?(Class) ? record : record.class)
+ return true if scope.nil?
+
+ write = !%i[read show index].include?(action.to_sym)
+ key = "#{write ? 'write' : 'read'}_#{scope.name}"
+ permission_keys.include?(key) ||
+ (!write && permission_keys.include?("write_#{scope.name}"))
+ end
+
# Whether the caller holds a permission a tool *declares*.
#
# @param permission_key [String, nil]
@@ -145,7 +172,8 @@ module Spree
def permission_keys
@permission_keys ||=
if user_principal?
- ability.respond_to?(:permission_keys) ? Array(ability.permission_keys).map(&:to_s) : []
+ held = ability.respond_to?(:permission_keys) ? Array(ability.permission_keys).map(&:to_s) : []
+ @granted_scopes.nil? ? held : held & Spree.permissions.expand_keys(@granted_scopes)
else
Spree.permissions.expand_keys(api_key.scopes)
end
diff --git a/spree/core/spec/lib/spree/agent_tools/context_spec.rb b/spree/core/spec/lib/spree/agent_tools/context_spec.rb
new file mode 100644
index 0000000000..babd60cd5e
--- /dev/null
+++ b/spree/core/spec/lib/spree/agent_tools/context_spec.rb
@@ -0,0 +1,64 @@
+require 'spec_helper'
+
+RSpec.describe Spree::AgentTools::Context do
+ let(:store) { @default_store }
+ let(:admin) { create(:admin_user) }
+
+ # An OAuth grant lets a merchant hand an agent part of their own authority.
+ # The grant has to be a ceiling: a merchant who consented to reading
+ # products must not hand over everything their role happens to allow.
+ describe 'a delegated grant' do
+ subject(:context) do
+ described_class.new(store: store, user: admin, granted_scopes: ['read_products'])
+ end
+
+ let(:unrestricted) { described_class.new(store: store, user: admin) }
+
+ it 'narrows the permissions the user holds' do
+ expect(unrestricted.permitted?('write_orders')).to be(true)
+ expect(context.permitted?('write_orders')).to be(false)
+ expect(context.permitted?('read_products')).to be(true)
+ end
+
+ it 'never widens them' do
+ limited = described_class.new(
+ store: store,
+ user: create(:admin_user, :without_admin_role),
+ granted_scopes: Spree.permissions.catalog_keys
+ )
+
+ expect(limited.permitted?('write_orders')).to be(false)
+ end
+
+ it 'refuses a record the grant does not cover' do
+ product = build(:product, store: store)
+
+ expect(context.can?(:show, product)).to be(true)
+ # Being offered a read tool is not permission to write through it.
+ expect(context.can?(:update, product)).to be(false)
+ end
+
+ it 'refuses a resource outside the granted scope entirely' do
+ order = build(:order, store: store)
+
+ expect(unrestricted.can?(:show, order)).to be(true)
+ expect(context.can?(:show, order)).to be(false)
+ end
+
+ it 'offers only the tools the grant covers' do
+ expect(Spree.agent_tools.available_for(context).size).
+ to be < Spree.agent_tools.available_for(unrestricted).size
+ end
+ end
+
+ # Without a grant the caller is the user acting directly, and the ability is
+ # the whole answer — this is the dashboard assistant's path.
+ describe 'no grant' do
+ it 'leaves the user’s own authority untouched' do
+ context = described_class.new(store: store, user: admin)
+
+ expect(context.permitted?('write_orders')).to be(true)
+ expect(context.can?(:update, build(:product, store: store))).to be(true)
+ end
+ end
+end