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
Fix: a delegated credential could act beyond the scopes it was granted
Damian Legawiec9ebf767362ad
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/params_normalizer.rb b/spree/api/app/controllers/concerns/spree/api/v3/params_normalizer.rbindex 5c8624773a..fe973508f5 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/params_normalizer.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/params_normalizer.rb@@ -144,7 +144,11 @@ module Spreereturn if key.nil? || owner.nil?name = key.to_s.sub(/_ids?\z/, '')- reflection = owner.try(:reflect_on_association, name)+ # `category_ids` names `has_many :categories`, so the singular form+ # finds nothing and the id went through unchecked — the same hole+ # the singular `_id` case had.+ reflection = owner.try(:reflect_on_association, name) ||+ owner.try(:reflect_on_association, name.pluralize)return if reflection.nil? || reflection.polymorphic?reflection.klassdiff --git a/spree/api/app/controllers/spree/api/v3/admin/oauth/authorizations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/oauth/authorizations_controller.rbindex a70ce67bdf..1c8a2923e5 100644--- a/spree/api/app/controllers/spree/api/v3/admin/oauth/authorizations_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/oauth/authorizations_controller.rb@@ -94,7 +94,10 @@ module Spree# a standing credential at all. A staffer who cannot revoke an# agent should not be able to connect one.def require_connect_permission!- return if current_ability.can?(:update, Spree::OauthApplication)+ # Narrowed too: connecting an agent is a write a delegated+ # credential must hold in its own scopes, not merely inherit.+ return if holds_permission?('write_oauth_applications') &&+ current_ability.can?(:update, Spree::OauthApplication)render_error(code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:access_denied],@@ -151,10 +154,14 @@ module Spree# Every individual permission the merchant could hand over, which# is what the consent screen draws a row for.def grantable_scopes- held = current_ability.try(:permission_keys)&.map(&:to_s) || []requested = Spree.permissions.expand_keys(@pre_auth.scopes.to_a)- (requested & held).sort+ # `staff_permission_keys` rather than the role's own keys: when+ # the request arrived on a delegated credential it is already+ # narrowed to that credential's scopes. Reading the role+ # directly let an agent holding `read_products` approve itself+ # a grant carrying everything its owner can do.+ (requested & staff_permission_keys).sortenddiff --git a/spree/api/spec/controllers/spree/api/v3/params_normalizer_spec.rb b/spree/api/spec/controllers/spree/api/v3/params_normalizer_spec.rbindex 672ea564f6..6c6cee4854 100644--- a/spree/api/spec/controllers/spree/api/v3/params_normalizer_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/params_normalizer_spec.rb@@ -156,6 +156,40 @@ RSpec.describe Spree::Api::V3::ParamsNormalizer doexpect(result['items'].first['variant_id']).to eq(variant.id)end+ # `category_ids` names `has_many :categories`, so the singular lookup+ # found nothing and the id went through unchecked.+ context 'inside a plural list' do+ let(:product_controller) do+ Class.new(ActionController::API) do+ include Spree::Api::V3::ParamsNormalizer++ public :resolve_prefixed_ids++ def model_class+ Spree::Product+ end+ end.new+ end++ it 'leaves an id of the wrong kind' do+ product = create(:product)+ hash = { 'category_ids' => [product.prefixed_id] }.with_indifferent_access++ result = product_controller.resolve_prefixed_ids(hash)++ expect(result['category_ids']).to eq([product.prefixed_id])+ end++ it 'decodes an id of the right kind' do+ category = create(:category)+ hash = { 'category_ids' => [category.prefixed_id] }.with_indifferent_access++ result = product_controller.resolve_prefixed_ids(hash)++ expect(result['category_ids']).to eq([category.id])+ end+ end+it 'decodes a top-level association id of the right kind' docustomer = create(:customer)hash = { 'customer_id' => customer.prefixed_id }.with_indifferent_accessdiff --git a/spree/api/spec/requests/spree/api/v3/admin/oauth_access_spec.rb b/spree/api/spec/requests/spree/api/v3/admin/oauth_access_spec.rbindex acedc63b45..0d7870bfec 100644--- a/spree/api/spec/requests/spree/api/v3/admin/oauth_access_spec.rb+++ b/spree/api/spec/requests/spree/api/v3/admin/oauth_access_spec.rb@@ -67,6 +67,24 @@ RSpec.describe 'Admin API OAuth access', type: :request doexpect(product.reload.name).to eq('Espresso Machine')end+ # The widest version of the same fault: the consent endpoint mints+ # grants, so an agent that could reach it with its owner's whole role+ # could approve itself anything that role can do — and a grant is a+ # standing ceiling, not a one-off.+ it 'cannot approve itself a grant wider than its own scopes' do+ verifier = SecureRandom.urlsafe_base64(64)+ challenge = Base64.urlsafe_encode64(Digest::SHA256.digest(verifier), padding: false)++ post '/api/v3/admin/oauth/authorize',+ params: { client_id: application.uid, redirect_uri: application.redirect_uri,+ response_type: 'code', scope: 'write_orders',+ code_challenge: challenge, code_challenge_method: 'S256' },+ headers: { 'Authorization' => "Bearer #{token}" }++ expect(response).to have_http_status(:forbidden)+ expect(Spree::OauthAccessGrant.where(application: application)).to be_empty+ end+# Several resources are guarded by a permission not named after them, so# a name derived from the resource type fell outside the catalog and went# unchecked — a read-only grant could rewrite an option type's or adiff --git a/spree/api/spec/tools/spree/agent_tools/reporting_tools_spec.rb b/spree/api/spec/tools/spree/agent_tools/reporting_tools_spec.rbindex d76f09f698..2b980deae8 100644--- a/spree/api/spec/tools/spree/agent_tools/reporting_tools_spec.rb+++ b/spree/api/spec/tools/spree/agent_tools/reporting_tools_spec.rb@@ -111,4 +111,33 @@ RSpec.describe 'agent reporting tools' doexpect(names).not_to include('query_report', 'describe_reporting')endend+ # A dimension is a permission question, and a delegated credential answers+ # it with its own scopes rather than its owner's whole role — otherwise a+ # grant for reports and orders could group by products too.+ describe 'a dimension the grant does not cover' do+ let(:staff) { create(:admin_user) }+ let(:narrow) do+ Spree::AgentTools::Context.new(+ store: store, user: staff, granted_scopes: %w[read_reports read_orders],+ request_headers: agent_headers_for(staff)+ )+ end++ it 'refuses to group by it' do+ tool = Spree.agent_tools.available_for(narrow).find { |t| t.tool_name == 'query_report' }++ result = tool.call(metrics: ['gross_sales'], dimensions: ['product'])++ expect(result[:error]).to include('permission')+ expect(result[:rows]).to be_nil+ end++ it 'still allows one the grant covers' do+ tool = Spree.agent_tools.available_for(narrow).find { |t| t.tool_name == 'query_report' }++ result = tool.call(metrics: ['gross_sales'], dimensions: ['completed_at'])++ expect(result[:error]).to be_nil+ end+ endenddiff --git a/spree/core/app/tools/spree/agent_tools/query_report.rb b/spree/core/app/tools/spree/agent_tools/query_report.rbindex 8108df24ff..f186f60560 100644--- a/spree/core/app/tools/spree/agent_tools/query_report.rb+++ b/spree/core/app/tools/spree/agent_tools/query_report.rb@@ -75,20 +75,17 @@ module Spree# their ability. A caller who may read orders but not products cannot# reach the product dimension here either.def unauthorized_members(query)- if context.user_principal?- forbidden = query.unreadable_subjects(context.ability).first- return if forbidden.nil?-- { error: "You do not have permission to report on #{forbidden.to_s.demodulize.underscore.humanize.downcase}." }- else- # Through the context, so a key's scopes expand the one way the rest- # of the gate expands them — `has_scope?` treats `read_all` as- # granting scopes no staff key may actually hold.- missing = query.required_key_scopes.reject { |scope| context.holds?(scope) }- return if missing.empty?-- { error: "This API key lacks the #{missing.to_sentence} scope." }- end+ # Asked of the context for every principal, not just a key.+ #+ # `context.ability` is the staff member's whole role, so a token+ # granted `read_reports` and `read_orders` could group by the product+ # dimension its merchant never consented to. `holds?` is the narrowed+ # answer: a key's scopes, or a grant's, or the role when the person is+ # acting directly.+ missing = query.required_key_scopes.reject { |scope| context.holds?(scope) }+ return if missing.empty?++ { error: "You do not have permission to report on #{missing.to_sentence.delete_prefix('read_').tr('_', ' ')}." }end# Totals first: most reporting questions are answered by them alone,