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 escaped the ceiling the merchant consented to
Damian Legawiec5755e2c8001c
diff --git a/spree/api/app/controllers/spree/api/v3/admin/exports_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/exports_controller.rbindex d7d2e3a338..619a5ddbd4 100644--- a/spree/api/app/controllers/spree/api/v3/admin/exports_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/exports_controller.rb@@ -75,10 +75,16 @@ module Spree[:user, { attachment_attachment: :blob }]end+ # Narrowed to the kinds this caller may read.+ #+ # Filtered for every principal that carries a ceiling, not only a+ # secret key: an OAuth token resolves as a staff user with no key,+ # so testing for one let an agent list every export in the store —+ # including that customer and gift-card exports exist — whatever the+ # merchant consented to. A staff member on a narrow role was+ # unfiltered for the same reason.def scopecollection = super- return collection unless scope_limited_principal?-collection.where(type: readable_export_types)end@@ -144,10 +150,16 @@ module Spreeaction_name == 'create' ? resolve_export_type(params[:type]) : find_resource.classend+ # `read_all` is not a catalog key, so it is asked of a secret key+ # directly; every shipped export declares a required scope, and an+ # extension type that declares none is readable only by a key that+ # holds everything.def readable_export_typesSpree::Export.available_types.select do |type|required = type.required_scope- required ? current_api_key.has_scope?("read_#{required}") : current_api_key.has_scope?('read_all')+ next current_api_key&.has_scope?('read_all') if required.blank?++ holds_permission?("read_#{required}")end.map(&:to_s)endenddiff --git a/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rbindex e4ce2933b6..79d6d61669 100644--- a/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb@@ -247,10 +247,15 @@ module Spree[:user, :mappings, { attachment_attachment: :blob }]end+ # Narrowed to the kinds this caller may write.+ #+ # Filtered for every principal that carries a ceiling, not only a+ # secret key — see the matching note on Admin::ExportsController.+ # It matters more here: an import row carries `sample_row`, a real+ # line from the uploaded file, so an unfiltered list handed a+ # read-only agent live customer data rather than only metadata.def scopecollection = super- return collection unless scope_limited_principal?-collection.where(type: writable_import_types)end@@ -363,10 +368,14 @@ module Spreeendend+ # `write_all` is not a catalog key, so it is asked of a secret key+ # directly; every shipped import declares a required scope.def writable_import_typesSpree::Import.available_types.select do |type|required = type.required_scope- required ? current_api_key.has_scope?("write_#{required}") : current_api_key.has_scope?('write_all')+ next current_api_key&.has_scope?('write_all') if required.blank?++ holds_permission?("write_#{required}")end.map(&:to_s)enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/translations/batches_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/translations/batches_controller.rbindex daa83cae93..7903564297 100644--- a/spree/api/app/controllers/spree/api/v3/admin/translations/batches_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/translations/batches_controller.rb@@ -20,9 +20,10 @@ module Spree# authorization, and rendering.class BatchesController < Admin::BaseController# The batch spans heterogeneous resource types, so a single static- # scope can't gate it. We verify the API key holds the matching- # write_<resource> scope for EVERY entry (see require_batch_scopes!),- # which is stricter than the static check and keeps the audit model.+ # scope can't gate it. We verify the caller holds the matching+ # write_<resource> permission for EVERY entry (see+ # require_batch_scopes!), which is stricter than the static check+ # and keeps the audit model.skip_scope_check!request_params 'TranslationBatchParams' do |body|@@ -63,19 +64,24 @@ module Spreeprivate- # For API-key callers, require write_<resource> for every distinct- # resource type in the batch. JWT callers bypass (current_api_key is- # nil) and rely on the per-record authorize!(:update, record) above.- # Returns false (and renders 403) when a scope is missing.+ # Require write_<resource> for every distinct resource type in the+ # batch.+ #+ # Asked of the caller rather than of a secret key, because there+ # are three principals and only one of them carries scopes on a+ # key. An OAuth token resolves as a staff user with no key, so+ # reading `current_api_key` here waved it through and the ceiling+ # the merchant consented to went unenforced on the one write this+ # controller performs — `holds_permission?` answers for all three.+ #+ # Returns false (and renders 403) when a permission is missing.def require_batch_scopes!(batch)- return true unless current_api_key-- missing = batch.required_scopes.reject { |scope| current_api_key.has_scope?(scope) }+ missing = batch.required_scopes.reject { |scope| holds_permission?(scope) }return true if missing.empty?render_error(code: ERROR_CODES[:access_denied],- message: "API key lacks scope(s): #{missing.join(', ')}",+ message: "You do not have permission to #{missing.map { |key| key.tr('_', ' ') }.to_sentence}.",status: :forbidden,details: { required_scopes: missing })diff --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 ffa1f4e96d..acedc63b45 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@@ -49,6 +49,65 @@ RSpec.describe 'Admin API OAuth access', type: :request doexpect(response).to have_http_status(:forbidden)end++ # The narrowing lives in the scope gate, so an endpoint that skips that+ # gate and guards itself has to ask about the caller rather than about a+ # secret key — a token resolves as a staff user and carries none, which+ # once let a read-only grant rewrite a product's translations.+ it 'cannot write through an endpoint that guards itself' do+ configure_supported_locales(store, %w[en de])+ product = create(:product, store: store, name: 'Espresso Machine')++ post '/api/v3/admin/translations/batch',+ params: { translations: [{ resource_type: 'product', resource_id: product.prefixed_id,+ translations: { de: { name: 'Rewritten' } } }] }.to_json,+ headers: { 'Authorization' => "Bearer #{token}", 'CONTENT_TYPE' => 'application/json' }++ expect(response).to have_http_status(:forbidden)+ expect(product.reload.name).to eq('Espresso Machine')+ 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 a+ # policy's translations.+ it 'cannot write a resource whose permission is not named after it' do+ configure_supported_locales(store, %w[en de])+ option_type = create(:option_type, label: 'Size')++ post '/api/v3/admin/translations/batch',+ params: { translations: [{ resource_type: 'option_type', resource_id: option_type.prefixed_id,+ values: { de: { label: 'Rewritten' } } }] }.to_json,+ headers: { 'Authorization' => "Bearer #{token}", 'CONTENT_TYPE' => 'application/json' }++ expect(response).to have_http_status(:forbidden)+ expect(json_response['error']['details']['required_scopes']).to eq(['write_products'])+ end++ # A list filtered only for secret keys told an agent which kinds of+ # export exist — including customers and gift cards. An import row goes+ # further and carries a real line from the uploaded file.+ it 'lists only the kinds of export the merchant granted' do+ Spree::Exports::Products.create!(store: store, user: admin)+ Spree::Exports::Customers.create!(store: store, user: admin)++ get_with(token, '/api/v3/admin/exports')+ types = json_response['data'].map { |row| row['type'] }.uniq++ expect(types).to include('products')+ expect(types).not_to include('customers')+ end++ it 'lists only the kinds of import the merchant granted' do+ Spree::Imports::Products.create!(store: store, user: admin)+ Spree::Imports::Customers.create!(store: store, user: admin)++ get_with(token_for('write_products', resource: '/api/v3/admin'), '/api/v3/admin/imports')+ types = json_response['data'].map { |row| row['type'] }.uniq++ expect(types).to include('products')+ expect(types).not_to include('customers')+ endend# RFC 8707: a token names the resources it may be used against. A clientdiff --git a/spree/core/app/models/concerns/spree/translatable_resource.rb b/spree/core/app/models/concerns/spree/translatable_resource.rbindex a91e865cc1..99751fa73f 100644--- a/spree/core/app/models/concerns/spree/translatable_resource.rb+++ b/spree/core/app/models/concerns/spree/translatable_resource.rb@@ -12,6 +12,21 @@ module Spreeconst_get(:TRANSLATABLE_FIELDS)end+ # The permission a caller needs in order to write this resource's+ # translations.+ #+ # Declared rather than derived from the class name, because several+ # resources are guarded by a permission that is not named after them:+ # option types and values ride `write_products`, a policy rides+ # `write_settings`. Deriving it produced names outside the permission+ # catalog, which a credential could never hold and which the API+ # therefore could not check at all.+ #+ # @return [String]+ def translation_write_permission+ "write_#{Spree::Base.polymorphic_api_type(name).pluralize}"+ end+# Maps a public API field name to the internal Mobility field, for a# model whose translatable column is named differently from the field the# API exposes. The public name is what the serializer and the translationdiff --git a/spree/core/app/models/spree/option_type.rb b/spree/core/app/models/spree/option_type.rbindex 93467779fb..34a938a070 100644--- a/spree/core/app/models/spree/option_type.rb+++ b/spree/core/app/models/spree/option_type.rb@@ -12,6 +12,11 @@ module SpreeTRANSLATABLE_FIELDS = Spree::LabelTranslatable::TRANSLATABLE_FIELDS+ # Option types are managed under the catalog, so the products permission guards them — see Admin::OptionTypesController.+ def self.translation_write_permission+ 'write_products'+ end+# Option values are translated alongside their type — the translations# endpoint nests their matrices so the editor fetches both in one read.def self.translatable_childrendiff --git a/spree/core/app/models/spree/option_value.rb b/spree/core/app/models/spree/option_value.rbindex 0242b474a1..761dac013c 100644--- a/spree/core/app/models/spree/option_value.rb+++ b/spree/core/app/models/spree/option_value.rb@@ -7,6 +7,11 @@ module Spreeinclude Spree::Metadatainclude Spree::LabelTranslatable+ # Values are written through their option type, so they ride the same permission.+ def self.translation_write_permission+ 'write_products'+ end+TRANSLATABLE_FIELDS = Spree::LabelTranslatable::TRANSLATABLE_FIELDS#diff --git a/spree/core/app/models/spree/policy.rb b/spree/core/app/models/spree/policy.rbindex 14f517f0ce..7a03f1153b 100644--- a/spree/core/app/models/spree/policy.rb+++ b/spree/core/app/models/spree/policy.rb@@ -4,6 +4,12 @@ module Spreeextend FriendlyIdinclude Spree::TranslatableResource++ # Policies are store settings — see Admin::PoliciesController.+ def self.translation_write_permission+ 'write_settings'+ end+include Spree::SanitizableRichTextUNIQUENESS_SCOPE = %i[owner_id owner_type].freezediff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rbindex 940ff0fba5..9c6e22521e 100644--- a/spree/core/app/models/spree/store.rb+++ b/spree/core/app/models/spree/store.rb@@ -8,6 +8,12 @@ module Spreeinclude FriendlyIdinclude Spree::TranslatableResource++ # The store itself is settings — see Admin::StoreController.+ def self.translation_write_permission+ 'write_settings'+ end+include Spree::HasCustomFieldsinclude Spree::Metadatainclude Spree::Stores::Setupdiff --git a/spree/core/app/models/spree/translations/batch.rb b/spree/core/app/models/spree/translations/batch.rbindex 427de82148..d70e80c6ad 100644--- a/spree/core/app/models/spree/translations/batch.rb+++ b/spree/core/app/models/spree/translations/batch.rb@@ -45,12 +45,22 @@ module Spree@records = []end- # Distinct +write_<resource>+ scopes a caller needs to authorize this- # batch — one per resource type present. Lets the API layer gate an- # API-key request without re-deriving scope names.+ # Distinct write permissions a caller needs to authorize this batch —+ # one per resource type present.+ #+ # Each resource names its own, because several are guarded by a+ # permission not named after them: an option type rides+ # `write_products`, a policy rides `write_settings`. Deriving the name+ # from the type produced strings outside the permission catalog, which+ # no credential could hold and which the API therefore skipped — so a+ # grant narrowed to reading could still rewrite a store's policy text.+ #+ # A type that resolves to nothing is left out; `resolve_record!` is what+ # reports it, one entry at a time with its index.+ ## @return [Array<String>]def required_scopes- @entries.map { |entry| "write_#{entry[:resource_type].to_s.pluralize}" }.uniq+ @entries.filter_map { |entry| resource_class(entry[:resource_type])&.translation_write_permission }.uniqend# Upserts every entry in one transaction. Yields each resolved recorddiff --git a/spree/core/spec/models/spree/translations/batch_spec.rb b/spree/core/spec/models/spree/translations/batch_spec.rbindex 8155831cd3..226e369b71 100644--- a/spree/core/spec/models/spree/translations/batch_spec.rb+++ b/spree/core/spec/models/spree/translations/batch_spec.rb@@ -82,14 +82,25 @@ RSpec.describe Spree::Translations::Batch doenddescribe '#required_scopes' do- it 'returns one write_<resource> scope per distinct resource type' do+ # Named by each resource, not derived from the type: an option type is+ # guarded by `write_products`, so a derived `write_option_types` was a+ # permission nothing could hold and the API could not check — which let a+ # read-only grant rewrite translations.+ it 'returns the permission each resource actually declares' dobatch = described_class.new([entry('option_type', option_type, {}),entry('option_value', option_value, {}),entry('option_type', option_type, {})])- expect(batch.required_scopes).to contain_exactly('write_option_types', 'write_option_values')+ expect(batch.required_scopes).to contain_exactly('write_products')+ end++ it 'names a permission the catalog knows, for every translatable resource' do+ unknown = Spree.translatable_resources.map(&:translation_write_permission).uniq.+ reject { |key| Spree.permissions.key?(key) }++ expect(unknown).to be_emptyendendend