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.

Fix: the permission check refused on records the caller never named

Damian Legawiecab7a48033337
diff --git a/spree/api/spec/lib/spree/agent_tools/authorization_spec.rb b/spree/api/spec/lib/spree/agent_tools/authorization_spec.rb
index 1967fe4e2e..74af1f6559 100644
--- a/spree/api/spec/lib/spree/agent_tools/authorization_spec.rb
+++ b/spree/api/spec/lib/spree/agent_tools/authorization_spec.rb
@@ -78,6 +78,44 @@ RSpec.describe 'assistant authorization' do
expect(visible.reload.status).to eq('draft')
end
+ # A create workflow takes `store:`, and the principal is injected into
+ # `created_by:`. Neither is something the caller named, so neither is what
+ # the permission check is about — an order desk may cancel an order
+ # without being allowed to "update" the store it belongs to or the user
+ # they are signed in as.
+ context 'when the workflow takes an injected store and principal' do
+ let(:ability) do
+ Class.new do
+ include CanCan::Ability
+
+ def initialize(*)
+ can :manage, Spree::Product
+ can :read, Spree::Store
+ end
+
+ def permission_keys
+ %w[read_products write_products]
+ end
+ end.new
+ end
+
+ it 'creates without demanding permission over the store or the actor' do
+ tool = Spree.agent_tools.available_for(context).find { |t| t.tool_name == 'products_create' }
+ result = tool.call(attributes: { 'name' => "Agent Made #{SecureRandom.hex(3)}" })
+
+ expect(result[:error]).to be_nil
+ expect(result.dig(:record, :title)).to start_with('Agent Made')
+ end
+
+ it 'names the created record in the summary, not the store' do
+ tool = Spree.agent_tools.available_for(context).find { |t| t.tool_name == 'products_create' }
+ result = tool.call(attributes: { 'name' => 'Summary Subject' })
+
+ expect(result[:summary]).to include('Summary Subject')
+ expect(result[:summary]).not_to include(store.name)
+ end
+ 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
diff --git a/spree/api/spec/lib/spree/api/agent_tools_contract_spec.rb b/spree/api/spec/lib/spree/api/agent_tools_contract_spec.rb
index 382128aab2..54d6cc522a 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
@@ -28,6 +28,19 @@ RSpec.describe 'agent tool contract' do
false
end
+ # Resource keys served by more than one admin controller under different
+ # scopes, which the derivation deliberately makes read-only.
+ def contested_keys
+ by_key = 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.model_name.element.pluralize] << controller._scoped_resource
+ end
+
+ by_key.select { |_key, scopes| scopes.uniq.size > 1 }.keys
+ end
+
let(:catalog) { Spree::AgentTools::DefaultCatalog }
describe 'the workflow allowlist' do
@@ -276,6 +289,36 @@ RSpec.describe 'agent tool contract' do
expect(undocumented.map(&:key)).to be_empty
end
+ # The map keys resources by model name; the OpenAPI document keys them by
+ # URL segment. Where the two disagree a resource silently loses its
+ # writes, so a resource whose controller writes directly and documents a
+ # body must resolve in both.
+ it 'keys a writable resource the same way the OpenAPI document does' do
+ # Everything deliberately read-only, for a reason recorded elsewhere:
+ # written through a workflow, written through a Tier 1 service, gated
+ # per request (imports and exports), or contested between two
+ # controllers and therefore read-only by the collision rule.
+ deliberate = Spree::AgentTools::ResourceMap.all.select do |entry|
+ entry.create_workflow_key.present? || entry.update_workflow_key.present? ||
+ Spree::Api::AgentResourceMap::SERVICE_WRITTEN_MODELS.include?(entry.model_name) ||
+ Spree::Api::AgentResourceMap::DYNAMIC_SCOPE_RESOURCES.key?(entry.key) ||
+ contested_keys.include?(entry.key)
+ end
+
+ # What is left should be writable exactly when the document says so, so
+ # the map's model-derived key and the document's URL segment agree.
+ mismatched = (Spree::AgentTools::ResourceMap.all - deliberate).reject do |entry|
+ entry.generic_writes? == Spree::Api::AgentWriteSchemas.attribute_names(entry.key).any?
+ end
+
+ expect(mismatched.map(&:key)).to be_empty, <<~MESSAGE
+ These resources are keyed one way in the map and another in
+ docs/api-reference/admin.yaml, so their writes are silently lost:
+
+ #{mismatched.map(&:key).join("\n ")}
+ MESSAGE
+ end
+
it 'scopes every registered resource to a store' do
unscoped = 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.rb
index 873bb1c447..f32c58548c 100644
--- a/spree/core/app/tools/spree/agent_tools/create_export.rb
+++ b/spree/core/app/tools/spree/agent_tools/create_export.rb
@@ -11,10 +11,11 @@ module Spree
'optionally, the same filters search_resources accepts. The merchant ' \
'approves before the file is generated.'
# Exports are gated on the READ scope of what is being exported — the
- # Admin API treats an export as a read, because that is what it is.
- # Checked per resource in `call`, since exporting orders and exporting
- # products are different permissions.
- permission 'read_products'
+ # Admin API treats an export as a read, because that is what it is. That
+ # is a per-resource question, so it is answered in `call` rather than
+ # here: a class-level key would hide the tool from a caller who may
+ # export orders but not products.
+ permission nil
mutating!
param :resource, description: 'What to export: products, orders, customers, gift_cards',
diff --git a/spree/core/app/tools/spree/agent_tools/describe_import_mapping.rb b/spree/core/app/tools/spree/agent_tools/describe_import_mapping.rb
index 67e6a68678..85a814af99 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
@@ -8,7 +8,7 @@ module Spree
# judgement about messy human spreadsheets — exactly what the model is
# for — but it can only judge from the real vocabulary, so this hands it
# the schema rather than letting it guess field names.
- class DescribeImportMapping < Spree::AgentTool
+ class DescribeImportMapping < Spree::AgentTools::ImportTool
tool_name 'describe_import_mapping'
description "List an import's unmapped file columns and the Spree fields they can " \
'map onto, so you can propose a mapping. Call this before ' \
@@ -19,7 +19,7 @@ module Spree
required: false
def call(id: nil)
- import = find_import(id)
+ import = find_import(id, status: 'mapping')
return { error: 'No import is waiting to be mapped.' } if import.nil?
{
@@ -40,15 +40,6 @@ module Spree
private
- def find_import(id)
- scope = Spree::AgentTools::ResourceMap.find('imports').scope_for(context)
- return scope.where(status: 'mapping').order(created_at: :desc).first if id.blank?
-
- scope.find_by_prefix_id(id) || scope.find_by(number: id)
- rescue ArgumentError, NoMethodError
- scope.find_by(number: id)
- end
-
# 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.
#
diff --git a/spree/core/app/tools/spree/agent_tools/get_import_status.rb b/spree/core/app/tools/spree/agent_tools/get_import_status.rb
index 45a330361b..519cdad436 100644
--- a/spree/core/app/tools/spree/agent_tools/get_import_status.rb
+++ b/spree/core/app/tools/spree/agent_tools/get_import_status.rb
@@ -5,7 +5,7 @@ module Spree
# A merchant who uploaded a file wants one of two answers: is it done, or
# why did those rows fail? Both are tedious to assemble from the imports
# page and easy to say in a sentence.
- class GetImportStatus < Spree::AgentTool
+ class GetImportStatus < Spree::AgentTools::ImportTool
FAILED_ROW_SAMPLE = 5
tool_name 'get_import_status'
@@ -38,19 +38,6 @@ module Spree
private
- def find_import(id)
- scope = Spree::AgentTools::ResourceMap.find('imports').scope_for(context)
- return scope.order(created_at: :desc).first if id.blank?
-
- scope.find_by_prefix_id(id) || scope.find_by(number: id)
- rescue ArgumentError, NoMethodError
- scope.find_by(number: id)
- end
-
- def import_kind(import)
- import.class.name.demodulize.underscore
- end
-
# Grouped so the assistant can say "12 rows failed because the SKU was
# missing" rather than reciting every row.
def failure_reasons(import)
diff --git a/spree/core/app/tools/spree/agent_tools/get_resource.rb b/spree/core/app/tools/spree/agent_tools/get_resource.rb
index a8c897bbf9..33ffcbd50a 100644
--- a/spree/core/app/tools/spree/agent_tools/get_resource.rb
+++ b/spree/core/app/tools/spree/agent_tools/get_resource.rb
@@ -18,7 +18,7 @@ module Spree
record = find_record(entry, id)
return { error: "No #{entry.key.singularize} found for #{id.inspect}" } if record.nil?
- attributes = Spree::AgentTools::RecordSummary.sanitize(entry.serializer_class.new(record).to_h)
+ attributes = serialize(entry, record)
{
resource: entry.key,
@@ -51,17 +51,31 @@ module Spree
private
+ # A serializer that raises on one record must be a tool error the model
+ # can act on, not a protocol failure — the same guard RecordSummary
+ # applies to the summary row.
+ def serialize(entry, record)
+ Spree::AgentTools::RecordSummary.sanitize(entry.serializer_class.new(record).to_h)
+ rescue StandardError => e
+ Rails.logger.warn("[Spree] #{entry.key} serializer failed: #{e.class}: #{e.message}")
+ {}
+ end
+
# Scoped through the store, so an id belonging to another store is a
# miss rather than a leak.
def find_record(entry, id)
scope = entry.scope_for(context)
- scope.find_by_prefix_id(id) || find_by_natural_key(scope, id)
- # Only the prefixed-id decode is expected to fail here (the model may
- # pass a slug or an order number); anything else is a real error and
- # must not be swallowed into a confusing nil.
+ by_prefixed_id(scope, id) || find_by_natural_key(scope, id)
+ end
+
+ # Only the prefixed-id decode is expected to fail here — the model may
+ # pass a slug or an order number. Guarded around that call alone, so a
+ # failure further along is not swallowed into a confusing nil.
+ def by_prefixed_id(scope, id)
+ scope.find_by_prefix_id(id)
rescue ArgumentError, NoMethodError
- find_by_natural_key(scope, id)
+ nil
end
# Merchants say order numbers and product slugs out loud far more often
diff --git a/spree/core/app/tools/spree/agent_tools/import_tool.rb b/spree/core/app/tools/spree/agent_tools/import_tool.rb
new file mode 100644
index 0000000000..9ed33c6b7a
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/import_tool.rb
@@ -0,0 +1,60 @@
+module Spree
+ module AgentTools
+ # Shared behaviour for the tools that walk a CSV import through its
+ # mapping step.
+ #
+ # They all have to find an import the same way — store-scoped, addressed
+ # by whichever of its prefixed id or its number the merchant said aloud —
+ # and getting that lookup right is the whole of their tenancy story, so it
+ # lives in one place rather than three.
+ class ImportTool < Spree::AgentTool
+ protected
+
+ # The import the caller named, or the most recent one matching `scope`
+ # when they named none.
+ #
+ # @param id [String, nil] a prefixed id or an import number
+ # @param scope [Symbol, nil] narrows the fallback, e.g. `:mapping`
+ # @return [Spree::Import, nil]
+ def find_import(id, status: nil)
+ relation = imports_scope
+ return if relation.nil?
+
+ return latest_import(relation, status) if id.blank?
+
+ by_prefixed_id(relation, id) || relation.find_by(number: id)
+ end
+
+ # The resource map is derived from the admin controllers, so an
+ # installation without them has no imports entry — and a nil here must
+ # read as "nothing found", never as a crash inside a rescue.
+ #
+ # @return [ActiveRecord::Relation, nil]
+ def imports_scope
+ ResourceMap.find('imports')&.scope_for(context)
+ end
+
+ # What kind of import this is, in the merchant's words.
+ #
+ # @return [String]
+ def import_kind(import)
+ import.class.name.demodulize.underscore.tr('_', ' ')
+ end
+
+ private
+
+ def latest_import(relation, status)
+ relation = relation.where(status: status) if status.present?
+ relation.order(created_at: :desc).first
+ end
+
+ # A value that is not a prefixed id at all raises rather than missing,
+ # which is expected here: the merchant may well have said a number.
+ def by_prefixed_id(relation, id)
+ relation.find_by_prefix_id(id)
+ rescue ArgumentError, NoMethodError
+ nil
+ end
+ end
+ end
+end
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.rb
index 5dd5274ce9..c444d79bc9 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
@@ -7,7 +7,7 @@ module Spree
# file becomes: get "Cost" onto `price` instead of `cost_price` and a
# merchant has repriced their whole catalogue in one click. The merchant
# sees the proposed pairing and approves it before anything is written.
- class ProposeImportMapping < Spree::AgentTool
+ class ProposeImportMapping < Spree::AgentTools::ImportTool
tool_name 'propose_import_mapping'
description 'Map the columns of an uploaded import file onto Spree fields. ' \
'Call describe_import_mapping first to see the real column headings ' \
@@ -17,7 +17,9 @@ module Spree
# The Admin API gates every import action on the write scope of the
# resource being imported — `write_products` for a product import —
# never on a settings key. Mirrored here, per-import, in `call`.
- permission 'write_products'
+ # Gated per import kind in `call`, not here: a caller who may import
+ # customers but not products must still be offered the tool.
+ permission nil
mutating!
param :id, description: 'Import id or number', required: true
@@ -44,13 +46,17 @@ module Spree
pairs = sanitize(import, mapping)
return unknown_fields(import, mapping) if pairs.empty?
- apply!(import, pairs)
+ applied = apply!(import, pairs)
start_if_ready(import)
{
ok: true,
id: import.prefixed_id,
- mapped: pairs,
+ # Only what was actually written. Reporting a field as mapped when
+ # its mapping row did not exist would have the model tell the
+ # merchant a column was handled when it was not.
+ mapped: applied,
+ unmapped: (pairs.keys - applied.keys).presence,
status: import.reload.status,
# `mapped_fields` returns mapping records, not names.
still_missing: import.required_fields - import.mappings.mapped.pluck(:schema_field)
@@ -68,18 +74,6 @@ module Spree
private
- def import_kind(import)
- import.class.name.demodulize.underscore.tr('_', ' ')
- end
-
- def find_import(id)
- scope = Spree::AgentTools::ResourceMap.find('imports').scope_for(context)
-
- scope.find_by_prefix_id(id) || scope.find_by(number: id)
- rescue ArgumentError, NoMethodError
- scope.find_by(number: id)
- end
-
# Only fields the schema declares and columns the file actually has —
# a hallucinated pairing must not reach the database.
def sanitize(import, mapping)
@@ -95,16 +89,21 @@ module Spree
end.to_h
end
+ # Loaded in one query rather than one per field: a product import
+ # declares forty-five of them, and a model proposing a full mapping
+ # sends most at once.
+ #
+ # @return [Hash] only the pairs that had a mapping row to write to
def apply!(import, pairs)
- Spree::ImportMapping.transaction do
- pairs.each do |field, column|
- mapping = import.mappings.find_by(schema_field: field)
- next if mapping.nil?
+ rows = import.mappings.where(schema_field: pairs.keys).index_by(&:schema_field)
+ applied = pairs.select { |field, _column| rows.key?(field) }
- mapping.update!(file_column: column)
- end
+ Spree::ImportMapping.transaction do
+ applied.each { |field, column| rows.fetch(field).update!(file_column: column) }
end
import.mappings.reload
+
+ applied
end
# Starting the import is the same transition the dashboard's own mapping
diff --git a/spree/core/app/tools/spree/agent_tools/query_report.rb b/spree/core/app/tools/spree/agent_tools/query_report.rb
index 57bb676518..98b8fc208d 100644
--- a/spree/core/app/tools/spree/agent_tools/query_report.rb
+++ b/spree/core/app/tools/spree/agent_tools/query_report.rb
@@ -21,7 +21,8 @@ module Spree
description: 'A preset such as {"preset": "last_30_days"}, or {"from": "2026-01-01", "to": "2026-03-31"}',
required: false
param :filters, type: :array, items: :object,
- description: 'Dimension filters, e.g. [{"dimension": "channel", "values": ["web"]}]',
+ description: 'Dimension filters, each {"dimension": …, "op": "eq" or "in", "value": …} — ' \
+ 'e.g. [{"dimension": "channel", "op": "in", "value": ["web", "pos"]}]',
required: false
param :sort, description: 'Metric or dimension to sort by, prefixed with - for descending', required: false
param :limit, type: :integer, description: 'Maximum rows to return (default 50)', required: false
diff --git a/spree/core/lib/spree/agent_tools/workflow_tool.rb b/spree/core/lib/spree/agent_tools/workflow_tool.rb
index 3f5cdea874..808ac62454 100644
--- a/spree/core/lib/spree/agent_tools/workflow_tool.rb
+++ b/spree/core/lib/spree/agent_tools/workflow_tool.rb
@@ -148,12 +148,12 @@ module Spree
resolved = resolve_arguments(arguments)
return resolved if resolved.is_a?(Hash) && resolved[:error]
- keywords = resolved.merge(principal_arguments).merge(context_arguments)
-
- refusal = unauthorized_record(keywords)
+ refusal = unauthorized_record(resolved)
return refusal if refusal
- run(keywords)
+ keywords = resolved.merge(principal_arguments).merge(context_arguments)
+
+ run(keywords, subject: subject_record(resolved))
rescue ArgumentError => e
{ error: e.message }
end
@@ -163,12 +163,12 @@ module Spree
#
# @param arguments [Hash]
# @return [String]
- def summary(arguments)
+ def summary(arguments, subject: nil)
return self.class.summary_override.call(context, arguments) if self.class.summary_override
action = workflow_class.workflow_key.tr('.', ' ').humanize
- subject = subject_summary(arguments)
- [action, subject].compact.join(' ')
+ subject ||= subject_record(arguments)
+ [action, label_for(subject)].compact.join(' ')
end
private
@@ -180,24 +180,35 @@ module Spree
# 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)
+ def unauthorized_record(arguments)
+ records(arguments).each do |record|
+ refusal = unauthorized(:update, record)
return refusal if refusal
end
nil
end
- def run(keywords)
- subject = keywords.values.find { |value| value.is_a?(ActiveRecord::Base) }
+ # Only what the caller named. The store and the principal are injected
+ # from the credential, so checking them would ask whether the caller may
+ # "update" their own store or their own user — which an order-desk role
+ # legitimately may not, and which has nothing to do with the write they
+ # actually asked for.
+ def records(arguments)
+ arguments.values.select { |value| value.is_a?(ActiveRecord::Base) }
+ end
+
+ # The record the write is about, for the lock and the confirmation line.
+ def subject_record(arguments)
+ records(arguments).first
+ end
+ def run(keywords, subject: nil)
result = with_subject_lock(subject) { workflow_class.call(**keywords) }
if result.success?
- { summary: summary(keywords), record: record_result(result.value) }
+ { summary: summary(keywords, subject: result.value.is_a?(ActiveRecord::Base) ? result.value : subject),
+ record: record_result(result.value) }
else
{ error: error_text(result) }
end
@@ -309,8 +320,7 @@ module Spree
nil
end
- def subject_summary(arguments)
- record = arguments.values.find { |value| value.is_a?(ActiveRecord::Base) }
+ def label_for(record)
return if record.nil?
record.try(:number) || record.try(:name) || record.try(:prefixed_id)