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: agent write tools skipped the record-level permission check
Damian Legawiecc644be1db11a
diff --git a/spree/api/lib/spree/api/agent_resource_map.rb b/spree/api/lib/spree/api/agent_resource_map.rbindex 6237bc2377..a46cb3bec1 100644--- a/spree/api/lib/spree/api/agent_resource_map.rb+++ b/spree/api/lib/spree/api/agent_resource_map.rb@@ -104,12 +104,9 @@ module Spreedef install(map: Spree::AgentTools::ResourceMap)map.reset!- controllers.each do |controller|- entry = derive(controller)- next if entry.nil?+ derived = controllers.filter_map { |controller| derive(controller) }- map.register(**entry)- end+ resolve_collisions(derived).each { |entry| map.register(**entry) }DYNAMIC_SCOPE_RESOURCES.each { |key, attributes| map.register(key: key, **attributes) }@@ -166,6 +163,48 @@ module Spreeprivate+ # A model can be served by more than one controller under different+ # permission scopes — a tax identifier through customers and through+ # orders, media through products and through the media library. One+ # resource key can carry only one permission, and whichever controller+ # happened to sort last is not an answer: it would grant a key holding+ # `read_orders` the customers' records too.+ #+ # So a collision resolves to the narrowest scope offered, and the+ # resource stays read-only, because the two controllers do not agree+ # on who may write it. A caller holding the wider scope reaches the+ # record through the endpoint, as before.+ def resolve_collisions(entries)+ entries.group_by { |entry| entry[:key] }.map do |_key, candidates|+ next candidates.first if candidates.one?++ narrowest = candidates.min_by { |entry| [scope_breadth(entry[:permission]), entry[:permission]] }+ contested = candidates.map { |entry| entry[:permission] }.uniq.size > 1++ # A workflow declaration is not in dispute — whichever controller+ # declares one, that is how the resource is written, and the+ # refusal has to keep naming that tool. Only the generic write is+ # withdrawn, and only when the controllers disagree about the+ # scope guarding it.+ narrowest.merge(+ create_workflow_key: candidates.filter_map { |entry| entry[:create_workflow_key] }.first,+ update_workflow_key: candidates.filter_map { |entry| entry[:update_workflow_key] }.first,+ write_permission: contested ? nil : narrowest[:write_permission],+ writable_attributes: contested ? [] : narrowest[:writable_attributes]+ )+ end+ end++ # How much a scope covers, so the narrowest wins a collision. Measured+ # by the number of resources the catalog grants it, which is the only+ # ranking the catalog actually gives us.+ def scope_breadth(permission)+ _kind, scope = Spree.permissions.resolve_key(permission)+ scope ? Array(scope.resources).size : Float::INFINITY+ rescue StandardError+ Float::INFINITY+ end+# A resource is generically writable only when the Admin API writes it# by saving the record, and the OpenAPI document says what a write may# set. A workflow-written resource keeps its workflow key instead (sodiff --git a/spree/api/spec/lib/spree/agent_tools/authorization_spec.rb b/spree/api/spec/lib/spree/agent_tools/authorization_spec.rbindex d91e322fd3..1967fe4e2e 100644--- a/spree/api/spec/lib/spree/agent_tools/authorization_spec.rb+++ b/spree/api/spec/lib/spree/agent_tools/authorization_spec.rb@@ -77,5 +77,40 @@ RSpec.describe 'assistant authorization' doexpect(result[:error]).to be_nilexpect(visible.reload.status).to eq('draft')end++ # The rule that matters, and the one a `can :manage` fixture hides:+ # reading every product and editing one is an ordinary shape for a+ # marketplace role, and a write tool that only checks readability would+ # let an agent change all of them.+ context 'when the admin may read every product but edit only one' do+ let(:ability) do+ Class.new do+ include CanCan::Ability++ def initialize(editable)+ can :read, Spree::Product+ can :update, Spree::Product, id: editable.id+ end++ def permission_keys+ Spree.permissions.catalog_keys+ end+ end.new(visible)+ end++ it 'refuses to change the one it may only read' do+ result = tool.call(product: hidden.prefixed_id)++ expect(result[:error]).to be_present+ expect(hidden.reload.status).to eq('active')+ end++ it 'still changes the one it may edit' do+ result = tool.call(product: visible.prefixed_id)++ expect(result[:error]).to be_nil+ expect(visible.reload.status).to eq('draft')+ end+ endendenddiff --git a/spree/api/spec/lib/spree/api/agent_tools_contract_spec.rb b/spree/api/spec/lib/spree/api/agent_tools_contract_spec.rbindex 6226cc1647..4b9981e7e0 100644--- a/spree/api/spec/lib/spree/api/agent_tools_contract_spec.rb+++ b/spree/api/spec/lib/spree/api/agent_tools_contract_spec.rb@@ -217,6 +217,30 @@ RSpec.describe 'agent tool contract' doMESSAGEend+ # A model served by two controllers under different scopes has no single+ # right permission, and picking whichever sorted last would grant a key+ # holding the wider scope records the narrower one guards. So the narrower+ # wins and the resource stays read-only.+ it 'resolves a resource served under two scopes to the narrower, read-only' do+ by_model = Spree::Api::AgentResourceMap.controllers.each_with_object(Hash.new { |h, k| h[k] = [] }) do |controller, result|+ model = Spree::Api::AgentResourceMap.send(:safely, controller.allocate, :model_class)+ next if model.nil? || controller._scoped_resource.blank?++ result[model.name] << "read_#{controller._scoped_resource}"+ end++ contested = by_model.select { |_model, permissions| permissions.uniq.size > 1 }++ contested.each do |model_name, permissions|+ entry = Spree::AgentTools::ResourceMap.all.find { |candidate| candidate.model_name == model_name }+ next if entry.nil?++ expect(permissions).to include(entry.permission)+ expect(entry.generic_writes?).to be(false),+ "#{entry.key} is served under #{permissions.uniq.to_sentence} yet accepts generic writes"+ end+ end+it 'scopes every registered resource to a store' dounscoped = Spree::AgentTools::ResourceMap.all.reject(&:store_scoped?)diff --git a/spree/core/app/tools/spree/agent_tools/create_export.rb b/spree/core/app/tools/spree/agent_tools/create_export.rbindex ba4a702044..873bb1c447 100644--- a/spree/core/app/tools/spree/agent_tools/create_export.rb+++ b/spree/core/app/tools/spree/agent_tools/create_export.rb@@ -27,15 +27,17 @@ module Spreereturn unknown_resource(resource) if export_class.nil?required = "read_#{export_class.required_scope}"- unless context.permitted?(required)+ unless context.holds?(required)return { error: "You do not have permission to export #{resource.to_s.tr('_', ' ')}." }endexport = export_class.new(store: context.store,- # The export builds its own ability from this user, so the file- # contains exactly the records that admin could see — record-level- # rules included.+ # For a signed-in admin the export builds an ability from this user,+ # so the file holds exactly the records that admin could see,+ # record-level rules included. For an API key there is no user and+ # no ability: the scope check above is the whole filter, which is+ # how the Admin API treats key requests everywhere else.user: context.user,format: 'csv',search_params: filters.presencediff --git a/spree/core/app/tools/spree/agent_tools/describe_import_mapping.rb b/spree/core/app/tools/spree/agent_tools/describe_import_mapping.rbindex d3352cfc7c..67e6a68678 100644--- a/spree/core/app/tools/spree/agent_tools/describe_import_mapping.rb+++ b/spree/core/app/tools/spree/agent_tools/describe_import_mapping.rb@@ -51,11 +51,13 @@ module Spree# Name, human label and whether it must be filled — the model needs all# three to explain its choices and to know what it cannot leave out.+ #+ # Read from `schema_fields`, which is what a mapping is validated+ # against: it adds the model's custom-field definitions to the schema's+ # own list. Describing the schema alone would accept a custom field on+ # write while never telling the model it exists.def describe_fields(import)- schema = import.import_schema- return [] if schema.nil?-- schema.fields.map do |field|+ Array(import.schema_fields).map do |field|{field: field[:name],label: field[:label],diff --git a/spree/core/app/tools/spree/agent_tools/propose_import_mapping.rb b/spree/core/app/tools/spree/agent_tools/propose_import_mapping.rbindex 69fcae6aae..5dd5274ce9 100644--- a/spree/core/app/tools/spree/agent_tools/propose_import_mapping.rb+++ b/spree/core/app/tools/spree/agent_tools/propose_import_mapping.rb@@ -32,7 +32,7 @@ module Spree# Per-import, because a customer import needs `write_customers`# while a product import needs `write_products`.required = "write_#{import.class.required_scope}"- unless context.permitted?(required)+ unless context.holds?(required)return { error: "You do not have permission to run a #{import_kind(import)} import." }end@@ -107,10 +107,13 @@ module Spreeimport.mappings.reloadend- # Starting the import is the same transition the dashboard's own- # mapping step makes, and only once every required field is satisfied.+ # Starting the import is the same transition the dashboard's own mapping+ # step makes, and only once every required field is satisfied. Through+ # the workflow rather than the deprecated model method it replaced.def start_if_ready(import)- import.complete_mapping! if import.mapping_done?+ return unless import.mapping_done?++ Spree.import_complete_mapping_workflow.call(import: import)enddef unknown_fields(import, mapping)diff --git a/spree/core/app/tools/spree/agent_tools/query_report.rb b/spree/core/app/tools/spree/agent_tools/query_report.rbindex aa9fb31ef5..57bb676518 100644--- a/spree/core/app/tools/spree/agent_tools/query_report.rb+++ b/spree/core/app/tools/spree/agent_tools/query_report.rb@@ -11,15 +11,18 @@ module Spree'describe_reporting first for the exact names this store has.'permission 'read_reports'- param :metrics, type: :array, description: 'Metric names, e.g. ["revenue", "orders"]', required: true- param :dimensions, type: :array,+ param :metrics, type: :array, items: :string,+ description: 'Metric names, e.g. ["orders", "net_sales"]', required: true+ param :dimensions, type: :array, items: :string,description: 'Dimensions to group by, as named by describe_reporting ' \'(e.g. ["completed_at", "channel"]). Omit for a single total.',required: falseparam :time_range, type: :object,description: 'A preset such as {"preset": "last_30_days"}, or {"from": "2026-01-01", "to": "2026-03-31"}',required: false- param :filters, type: :array, description: 'Dimension filters, e.g. [{"dimension": "channel", "values": ["web"]}]', required: false+ param :filters, type: :array, items: :object,+ description: 'Dimension filters, e.g. [{"dimension": "channel", "values": ["web"]}]',+ required: falseparam :sort, description: 'Metric or dimension to sort by, prefixed with - for descending', required: falseparam :limit, type: :integer, description: 'Maximum rows to return (default 50)', required: falseparam :currency, description: 'Currency for money metrics; defaults to the store currency', required: falsediff --git a/spree/core/lib/spree/agent_tool.rb b/spree/core/lib/spree/agent_tool.rbindex fed5fe16f7..80d1b236f2 100644--- a/spree/core/lib/spree/agent_tool.rb+++ b/spree/core/lib/spree/agent_tool.rb@@ -72,12 +72,15 @@ class AgentTool# @param type [Symbol] JSON schema type# @param description [String]# @param required [Boolean]+ # @param items [Symbol] what an array holds — a JSON Schema array without+ # it is ambiguous, and a client that validates arguments against the+ # schema rejects the call before the tool ever runs# @return [void]- def param(name, type: :string, description: nil, required: false)+ def param(name, type: :string, description: nil, required: false, items: nil)# Reassigned rather than mutated, so declaring a param on a subclass# does not reach back and change the parent's list.self.declared_params = declared_params.merge(- name => { type: type, description: description, required: required }+ name => { type: type, description: description, required: required, items: items }).freezeenddiff --git a/spree/core/lib/spree/agent_tools/context.rb b/spree/core/lib/spree/agent_tools/context.rbindex c5da4fc52f..9d7b527659 100644--- a/spree/core/lib/spree/agent_tools/context.rb+++ b/spree/core/lib/spree/agent_tools/context.rb@@ -96,8 +96,10 @@ module Spreeability.can?(action, record)end+ # Whether the caller holds a permission a tool *declares*.+ ## @param permission_key [String, nil]- # @return [Boolean] whether the caller holds this permission+ # @return [Boolean]def permitted?(permission_key)return true if permission_key.blank?@@ -111,6 +113,26 @@ module Spreepermission_keys.include?(key)end+ # Whether the caller holds a permission computed at call time — an+ # export's or import's own scope, which comes from whichever subclass+ # the caller named.+ #+ # Unlike {#permitted?} this refuses an unregistered key rather than+ # raising on it: a tool's declaration is ours to get right, but a host+ # app's export subclass may derive a key outside the catalog, and an+ # agent asking for it should be told no, not crash the request.+ #+ # @param permission_key [String, nil]+ # @return [Boolean]+ def holds?(permission_key)+ return true if permission_key.blank?++ key = permission_key.to_s+ return false unless Spree.permissions.key?(key)++ permission_keys.include?(key)+ end+# The catalog keys this caller holds, in the one currency both gates# speak: an admin's activated role keys, or a secret key's scopes# expanded the way the Admin API expands them (`write_x` impliesdiff --git a/spree/core/lib/spree/agent_tools/workflow_schema.rb b/spree/core/lib/spree/agent_tools/workflow_schema.rbindex af25b9b825..bd5cb6add3 100644--- a/spree/core/lib/spree/agent_tools/workflow_schema.rb+++ b/spree/core/lib/spree/agent_tools/workflow_schema.rb@@ -131,11 +131,14 @@ module Spreetypes = doc[:types]model_name = types.filter_map { |type| model_name_for(type) }.first+ json_type = model_name ? 'string' : json_type_for(types)+{name: name,required: required,model_name: model_name,- json_type: model_name ? 'string' : json_type_for(types),+ json_type: json_type,+ item_type: json_type == 'array' ? item_type_for(types) : nil,description: description_for(doc[:description], model_name)}end@@ -143,7 +146,7 @@ module Spreedef property_for(parameter)property = { type: parameter[:json_type] }property[:description] = parameter[:description] if parameter[:description].present?- property[:items] = { type: 'object' } if parameter[:json_type] == 'array'+ property[:items] = { type: parameter[:item_type] } if parameter[:json_type] == 'array'propertyend@@ -173,6 +176,15 @@ module Spreeconstant.nameend+ # What an array holds, read from the documented type: `Array<Hash>` holds+ # objects, and anything else is treated as strings — the common case for+ # a list of names or codes.+ def item_type_for(types)+ inner = types.filter_map { |type| type[/\AArray<(.+)>\z/, 1] }.first++ PRIMITIVES[inner] || 'string'+ end+def json_type_for(types)concrete = types.reject { |type| type == 'nil' }# `Array<Hash>` and friends — the outer container is what JSON sees.diff --git a/spree/core/lib/spree/agent_tools/workflow_tool.rb b/spree/core/lib/spree/agent_tools/workflow_tool.rbindex d0c2a39b42..f0438cc13c 100644--- a/spree/core/lib/spree/agent_tools/workflow_tool.rb+++ b/spree/core/lib/spree/agent_tools/workflow_tool.rb@@ -28,8 +28,15 @@ module Spreeworkflow_class = resolve_workflow(dependency_key)return if workflow_class.nil?- cache_key = [dependency_key, workflow_class.name, permission, except, summary.object_id]- cache[cache_key] ||= build(dependency_key, workflow_class, permission, except, summary)+ # Keyed by what actually shapes the class. A summary override is a+ # callable with no stable identity, so its presence is part of the+ # key but the object is not — otherwise every code reload would add+ # a permanent entry for the same tool.+ cache_key = [dependency_key, workflow_class.name, permission, except, !summary.nil?]+ cached = cache[cache_key]+ return cached if cached && cached.summary_override.equal?(summary)++ cache[cache_key] = build(dependency_key, workflow_class, permission, except, summary)end# @return [void]@@ -142,6 +149,9 @@ module Spreekeywords = resolved.merge(principal_arguments).merge(context_arguments)+ refusal = unauthorized_record(keywords)+ return refusal if refusal+run(keywords)rescue ArgumentError => e{ error: e.message }@@ -162,6 +172,24 @@ module Spreeprivate+ # Holding `write_orders` says an admin may change orders; it does not say+ # they may change *this* one. A host app narrows that with a+ # record-level rule, the Admin API honours it, and a workflow tool must+ # too — otherwise an agent writes records its user could not touch by+ # clicking. Every record the workflow was handed is checked, not just the+ # subject, since a cancellation reason from another seller is as much a+ # leak as the order itself.+ def unauthorized_record(keywords)+ keywords.each_value do |value|+ next unless value.is_a?(ActiveRecord::Base)++ refusal = unauthorized(:update, value)+ return refusal if refusal+ end++ nil+ end+def run(keywords)subject = keywords.values.find { |value| value.is_a?(ActiveRecord::Base) }diff --git a/spree/mcp/lib/spree/mcp/tool_adapter.rb b/spree/mcp/lib/spree/mcp/tool_adapter.rbindex d3406a928b..736e60c1d7 100644--- a/spree/mcp/lib/spree/mcp/tool_adapter.rb+++ b/spree/mcp/lib/spree/mcp/tool_adapter.rb@@ -32,7 +32,9 @@ module Spreeproperties = tool.params.to_h do |name, options|property = { type: json_type(options[:type]) }property[:description] = options[:description] if options[:description].present?- property[:items] = { type: 'object' } if property[:type] == 'array'+ # An array must say what it holds: a client validating arguments+ # against the schema refuses the call otherwise.+ property[:items] = { type: json_type(options[:items] || :string) } if property[:type] == 'array'[name.to_s, property]enddiff --git a/spree/mcp/spec/lib/spree/mcp/server_spec.rb b/spree/mcp/spec/lib/spree/mcp/server_spec.rbindex 1967cc226d..afe4ed9ffb 100644--- a/spree/mcp/spec/lib/spree/mcp/server_spec.rb+++ b/spree/mcp/spec/lib/spree/mcp/server_spec.rb@@ -111,12 +111,34 @@ RSpec.describe Spree::Mcp::Server doit 'gives every tool a name the protocol accepts' doexpect(names).to all(match(/\A[a-zA-Z0-9_-]{1,64}\z/))end++ # A JSON Schema array without `items` is ambiguous, and the client+ # validates arguments against the schema before the tool runs — so a+ # list parameter that does not say what it holds is refused as invalid+ # arguments, whatever the caller sends.+ it 'says what every array parameter holds' do+ arrays = tools.flat_map do |tool|+ tool.dig('inputSchema', 'properties').filter_map do |name, property|+ "#{tool['name']}.#{name}" if property['type'] == 'array' && property['items'].blank?+ end+ end++ expect(arrays).to be_empty+ endendenddescribe 'tools/call' dolet(:scopes) { ['write_all'] }+ # The bug this guards: metrics is a list of names, and an `items: object`+ # schema made every real call fail validation before reaching the tool.+ it 'accepts a list of names for a reporting query' do+ response = call('tools/call', name: 'query_report', arguments: { 'metrics' => %w[orders] })++ expect(response.dig('result', 'isError')).to be(false)+ end+it 'returns structured content from a read tool' docreate(:product, store: store, name: 'Rotary Shaver 9000')