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.

Changed the read tools to run through the Admin API

Damian Legawiecb164988cbafb
diff --git a/docs/plans/6.0-mcp-server.md b/docs/plans/6.0-mcp-server.md
index dba18f1191..5127f44783 100644
--- a/docs/plans/6.0-mcp-server.md
+++ b/docs/plans/6.0-mcp-server.md
@@ -728,6 +728,22 @@ gem, so `pnpm test:changed` picks its specs up.
permission check, the second error shape. The measure of this step is
how much Ruby it removes.
+ **Built 2026-10-10.** 415 lines deleted against 381 added, with the
+ dispatcher itself counted in the additions. What went: the hand-written
+ writable-attribute lists, the second store scoping in every read, the
+ `SERVICE_WRITTEN_MODELS` list that withheld writes for fourteen models,
+ the refusal rule that made a resource with a workflow unwritable
+ generically, and the row-lock and actor-injection machinery the
+ controller already performs.
+
+ Two guards stayed, because the Admin API does not make them yet, and
+ both are recorded rather than quietly kept: an unknown filter is named
+ back instead of silently widening a search, and an attribute the
+ controller does not permit is named instead of dropped behind a 200
+ that reports a change which never happened. Both go when strict
+ filters and strict attributes land, and `search_resources` is three
+ lines longer than before because of the first.
+
7. **Later, outside this plan:** `spree mcp` stdio wrapper in `@spree/cli`
that proxies to the mounted endpoint and prints client configs; a
shopper-facing Storefront MCP (own plan). At 7 the catalog runs under
diff --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.rb
index 8801d38b83..1481610575 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
@@ -180,8 +180,45 @@ module Spree
params[:scope].to_s.split.select { |scope| accepted.include?(scope) }.join(' ')
end
+ # The audiences the grant is bound to.
+ #
+ # A client asking for the MCP endpoint is granted the Admin API
+ # alongside it, because an MCP tool call reaches data by
+ # dispatching to an Admin API operation — as the same grant, with
+ # the same scopes, so the ceiling the merchant approved is the one
+ # that applies. Without it the dispatched call carries a token
+ # bound to a path the Admin API does not serve, and every tool
+ # answers "authentication required".
+ #
+ # This widens the audience, not the authority: the scopes are
+ # unchanged, and a token for the Admin API alone is still refused
+ # at the MCP endpoint. RFC 8707 takes a list for exactly this —
+ # one grant, the surfaces it legitimately needs.
def requested_resource
- @pre_auth.resource_indicators&.first
+ requested = @pre_auth.resource_indicators.to_a
+ return requested.first if requested.empty?
+
+ mcp = Spree::Api::Oauth.resources[:mcp]
+ return requested.join(' ') unless requested.any? { |value| path_of(value) == mcp }
+
+ Spree::Api::Oauth.granted_audience(:mcp, origin_of(requested.first))
+ end
+
+ # The scheme and host the client was given — a tunnel, a proxy, a
+ # custom domain — so both audiences name the same origin.
+ def origin_of(indicator)
+ uri = URI.parse(indicator.to_s)
+ return if uri.host.blank?
+
+ "#{uri.scheme}://#{uri.host}#{":#{uri.port}" unless uri.default_port == uri.port}"
+ rescue URI::InvalidURIError
+ nil
+ end
+
+ def path_of(value)
+ URI.parse(value.to_s).path
+ rescue URI::InvalidURIError
+ nil
end
# Every capability the requested scopes imply, so a merchant sees
diff --git a/spree/api/lib/spree/api/agent_membership_map.rb b/spree/api/lib/spree/api/agent_membership_map.rb
index 125276b5b9..4abcb84c10 100644
--- a/spree/api/lib/spree/api/agent_membership_map.rb
+++ b/spree/api/lib/spree/api/agent_membership_map.rb
@@ -27,7 +27,8 @@ module Spree
model_name: entry.model_name,
permission: write_permission_for(entry),
positioned: controller.method_defined?(:reposition),
- service_namespace: service_namespace_for(target)
+ service_namespace: service_namespace_for(target),
+ api_path: membership_path_for(controller)
)
end
@@ -36,6 +37,18 @@ module Spree
private
+ # Where this parent's products are added and removed, read from the
+ # routes. The nested path carries the parent's id, which a tool fills
+ # in from the parent it was given.
+ def membership_path_for(controller)
+ route = Spree::Core::Engine.routes.routes.find do |candidate|
+ candidate.defaults[:controller] == controller.controller_path &&
+ candidate.defaults[:action] == 'create'
+ end
+
+ route&.path&.spec.to_s.sub('(.:format)', '').presence
+ end
+
def curating_controllers
Rails.application.eager_load! unless Rails.application.config.eager_load
diff --git a/spree/api/lib/spree/api/agent_resource_map.rb b/spree/api/lib/spree/api/agent_resource_map.rb
index a14acc591a..d47876eea2 100644
--- a/spree/api/lib/spree/api/agent_resource_map.rb
+++ b/spree/api/lib/spree/api/agent_resource_map.rb
@@ -43,30 +43,6 @@ module Spree
'imports' => '/settings/imports'
}.freeze
- # Resources whose controller writes through a Tier 1 service rather
- # than a workflow. Order editing, fees, discounts, addresses, stock
- # levels and store credits reach agents when those paths become
- # workflows (the 6.1 order-change substrate covers most of them), never
- # through a generic write that would bypass the orchestration the
- # service performs. See docs/plans/6.0-mcp-server.md, "What is not
- # exposed at 6.0".
- SERVICE_WRITTEN_MODELS = %w[
- Spree::Order
- Spree::Return
- Spree::Exchange
- Spree::Claim
- Spree::StockLevel
- Spree::StoreCredit
- Spree::Refund
- Spree::Payment
- Spree::ShippingLabel
- Spree::StockMovement
- Spree::StockReservation
- Spree::SellerPayout
- Spree::SellerTransfer
- Spree::Delivery
- ].freeze
-
# Resources withheld whatever their controller says, because their
# serializer carries a live credential or a bearer instrument. Every
# tool result reaches a model and, for a hosted client, a third party.
@@ -287,9 +263,20 @@ module Spree
# at all; and a resource with no documented body is read-only here,
# because a write tool with no attributes is one an agent can only get
# wrong.
+ # Writable when the controller documents a body and does not hand out
+ # authority.
+ #
+ # The list of service-written models this used to consult is gone
+ # (2026-10-10). It existed because a generic write assigned
+ # attributes and saved, so reaching a record whose controller
+ # orchestrates — an order, a refund, a stock level — would have
+ # skipped that orchestration. A dispatched write IS the controller,
+ # so there is nothing left to skip, and the list only withheld writes
+ # the API performs correctly.
+ #
+ # A declared workflow no longer withholds it either: the controller
+ # runs its own workflow, which is what the generic write now reaches.
def write_permission_for(model, scope, create_workflow, update_workflow, writable, controller)
- return if SERVICE_WRITTEN_MODELS.include?(model.name)
- return if create_workflow.present? || update_workflow.present?
return if writable.empty?
return if hands_out_authority?(controller)
diff --git a/spree/api/lib/spree/api/oauth.rb b/spree/api/lib/spree/api/oauth.rb
index 5e8901bc74..e4b1cf06f2 100644
--- a/spree/api/lib/spree/api/oauth.rb
+++ b/spree/api/lib/spree/api/oauth.rb
@@ -61,6 +61,23 @@ module Spree
resources.values.map { |path| "#{base}#{path}" }
end
+ # The audiences a grant for one surface is bound to.
+ #
+ # An MCP grant carries the Admin API too, because a tool call reaches
+ # data by dispatching to an Admin API operation — as the same grant,
+ # with the same scopes. Widening the audience is not widening the
+ # authority: a token for the Admin API alone is still refused at the
+ # MCP endpoint.
+ #
+ # @param key [Symbol]
+ # @param origin [String, nil] scheme and host the client used
+ # @return [String] space-separated indicators, as RFC 8707 takes them
+ def granted_audience(key, origin = nil)
+ keys = key.to_sym == :mcp ? %i[mcp admin] : [key.to_sym]
+
+ keys.filter_map { |name| resource_identifier(name, origin) }.uniq.join(' ')
+ end
+
# @param key [Symbol]
# @param origin [String, nil] scheme and host the client used
# @return [String, nil]
diff --git a/spree/api/spec/lib/spree/agent_tools/api_dispatch_spec.rb b/spree/api/spec/lib/spree/agent_tools/api_dispatch_spec.rb
index 3994e46fbc..a35e0fea4c 100644
--- a/spree/api/spec/lib/spree/agent_tools/api_dispatch_spec.rb
+++ b/spree/api/spec/lib/spree/agent_tools/api_dispatch_spec.rb
@@ -21,7 +21,7 @@ RSpec.describe Spree::AgentTools::ApiDispatch do
it 'returns what the endpoint rendered' do
create(:product, store: store, name: 'Dispatched')
- response = dispatcher_for(reader).call(method: :get, path: '/products')
+ response = dispatcher_for(reader).call(method: :get, path: '/api/v3/admin/products')
expect(response).to be_success
expect(response.data.map { |row| row['name'] }).to include('Dispatched')
@@ -35,7 +35,7 @@ RSpec.describe Spree::AgentTools::ApiDispatch do
product = create(:product, store: store)
response = dispatcher_for(reader).
- call(method: :get, path: '/variants', params: { q: { product_id_eq: product.prefixed_id } })
+ call(method: :get, path: '/api/v3/admin/variants', params: { q: { product_id_eq: product.prefixed_id } })
expect(response).to be_success
expect(response.meta['count']).to eq(product.variants.count)
@@ -49,7 +49,7 @@ RSpec.describe Spree::AgentTools::ApiDispatch do
it 'is what the API authenticates, so a scope it lacks is refused' do
key = create(:api_key, :secret, store: store, scopes: ['read_products'])
- response = dispatcher_for(key).call(method: :post, path: '/products', body: { name: 'No' })
+ response = dispatcher_for(key).call(method: :post, path: '/api/v3/admin/products', body: { name: 'No' })
expect(response.status).to eq(403)
expect(response.error_message).to include('write_products')
@@ -57,7 +57,7 @@ RSpec.describe Spree::AgentTools::ApiDispatch do
it 'is required: a call carrying none is unauthorized' do
response = dispatcher_for(reader, headers: { 'HTTP_HOST' => 'www.example.com' }).
- call(method: :get, path: '/products')
+ call(method: :get, path: '/api/v3/admin/products')
expect(response.status).to eq(401)
end
@@ -72,7 +72,7 @@ RSpec.describe Spree::AgentTools::ApiDispatch do
Spree::Current.currency = 'GBP'
Spree::Current.locale = 'de'
- dispatcher_for(reader).call(method: :get, path: '/products')
+ dispatcher_for(reader).call(method: :get, path: '/api/v3/admin/products')
# Asserted on the stored attributes, not the readers: `currency` falls
# back to the store's default, which would agree with 'GBP' only by
@@ -86,7 +86,7 @@ RSpec.describe Spree::AgentTools::ApiDispatch do
it 'restores the outer state even when the call fails' do
Spree::Current.currency = 'GBP'
- dispatcher_for(reader).call(method: :get, path: '/not_a_real_endpoint')
+ dispatcher_for(reader).call(method: :get, path: '/api/v3/admin/not_a_real_endpoint')
expect(Spree::Current.attributes[:currency]).to eq('GBP')
end
@@ -96,7 +96,7 @@ RSpec.describe Spree::AgentTools::ApiDispatch do
it 'does not hand the inner request the outer currency' do
Spree::Current.currency = 'GBP'
- response = dispatcher_for(reader).call(method: :get, path: '/products')
+ response = dispatcher_for(reader).call(method: :get, path: '/api/v3/admin/products')
expect(response).to be_success
end
@@ -104,7 +104,7 @@ RSpec.describe Spree::AgentTools::ApiDispatch do
describe 'a failing call' do
it 'carries the API error rather than raising' do
- response = dispatcher_for(reader).call(method: :get, path: '/products/prod_nope')
+ response = dispatcher_for(reader).call(method: :get, path: '/api/v3/admin/products/prod_nope')
expect(response).not_to be_success
expect(response.error_message).to be_present
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 8ee8d5d476..4cd266b389 100644
--- a/spree/api/spec/lib/spree/agent_tools/authorization_spec.rb
+++ b/spree/api/spec/lib/spree/agent_tools/authorization_spec.rb
@@ -7,25 +7,41 @@ require 'spec_helper'
RSpec.describe 'assistant authorization' do
let(:store) { @default_store }
let(:admin) { create(:admin_user) }
- let(:context) { Spree::AgentTools::Context.new(store: store, user: admin, ability: ability) }
+ let(:context) { Spree::AgentTools::Context.new(store: store, user: admin, ability: ability,
+ request_headers: agent_headers_for(admin)) }
let!(:visible) { create(:product, store: store, name: 'Visible Product', status: 'active') }
let!(:hidden) { create(:product, store: store, name: 'Hidden Product', status: 'active') }
- # Stands in for a host app's record-level rule: this admin may see and edit
- # one product, not the other.
- let(:ability) do
- Class.new do
- include CanCan::Ability
-
- def initialize(allowed)
- can :manage, Spree::Product, id: allowed.id
- end
+ # Stands in for a host app's record-level rule. Declared on the real ability
+ # class rather than injected into the context, because a dispatched tool
+ # call builds its own ability from the credential — which is the point: the
+ # rule the dashboard obeys is the rule agents obey, not a copy of it.
+ let(:ability) { full_ability }
+ let(:full_ability) { Spree::Dependencies.ability_class.constantize.new(admin, store: store) }
+
+ # Defined once at load rather than built per example: a dispatched request
+ # resolves the class by name through `Spree::Dependencies`, and an
+ # anonymous class stubbed onto a constant inside `before` was not always
+ # the one it found when the whole suite ran.
+ # Keyed on the record's own id, not on its name: a rule matching
+ # 'Hidden Product' also matched any leftover of that name another spec had
+ # created, and then the example was asserting about the wrong record.
+ class NarrowedTestAbility < Spree::Ability
+ def initialize(user, options = {})
+ super
+ hidden_id = RSpec.current_example&.metadata&.dig(:hidden_product_id)
+ cannot %i[read update destroy], Spree::Product, id: hidden_id if hidden_id
+ end
+ end
- def permission_keys
- Spree.permissions.catalog_keys
- end
- end.new(visible)
+ before do
+ RSpec.current_example.metadata[:hidden_product_id] = hidden.id
+ # `Spree.ability_class` is what the controller calls, and it answers a
+ # class rather than a name — stubbing `Spree::Dependencies.ability_class`
+ # left the dispatched request building the default ability.
+ allow(Spree).to receive(:ability_class).and_return(NarrowedTestAbility)
+ allow(Spree::Dependencies).to receive(:ability_class).and_return('NarrowedTestAbility')
end
describe 'reads' do
@@ -38,11 +54,13 @@ RSpec.describe 'assistant authorization' do
end
it 'counts only what the admin may see' do
- result = Spree::AgentTools::SearchResources.new(context).call(resource: 'products')
+ result = Spree::AgentTools::SearchResources.new(context).call(resource: 'products', limit: 25)
+ titles = result[:records].map { |record| record[:title] }
- # The assistant states this number out loud, so a leak here is a leak the
- # merchant reads.
- expect(result[:total]).to eq(1)
+ # The assistant states this number out loud, so a leak here is a leak
+ # the merchant reads.
+ expect(result[:total]).to eq(titles.size)
+ expect(titles).not_to include('Hidden Product')
end
it 'cannot fetch an excluded record directly' do
diff --git a/spree/api/spec/lib/spree/agent_tools/extension_path_spec.rb b/spree/api/spec/lib/spree/agent_tools/extension_path_spec.rb
index 8e1d3fe357..aba28652dc 100644
--- a/spree/api/spec/lib/spree/agent_tools/extension_path_spec.rb
+++ b/spree/api/spec/lib/spree/agent_tools/extension_path_spec.rb
@@ -7,7 +7,7 @@ require 'spec_helper'
RSpec.describe 'the extension path the docs describe' do
let(:store) { @default_store }
let(:key) { create(:api_key, :secret, store: store, scopes: ['read_purchasing']) }
- let(:context) { Spree::AgentTools::Context.new(store: store, api_key: key) }
+ let(:context) { Spree::AgentTools::Context.new(store: store, api_key: key, request_headers: agent_headers_for_key(key)) }
before do
stub_const('MyShop', Module.new)
@@ -41,7 +41,7 @@ RSpec.describe 'the extension path the docs describe' do
it 'is hidden from a key without the permission' do
other = create(:api_key, :secret, store: store, scopes: ['read_products'])
- ctx = Spree::AgentTools::Context.new(store: store, api_key: other)
+ ctx = Spree::AgentTools::Context.new(store: store, api_key: other, request_headers: agent_headers_for_key(other))
expect(Spree.agent_tools.available_for(ctx).map(&:tool_name)).not_to include('supplier_stock')
end
diff --git a/spree/api/spec/lib/spree/agent_tools/resource_map_spec.rb b/spree/api/spec/lib/spree/agent_tools/resource_map_spec.rb
index ba0fb6cd54..b6bd0a5e81 100644
--- a/spree/api/spec/lib/spree/agent_tools/resource_map_spec.rb
+++ b/spree/api/spec/lib/spree/agent_tools/resource_map_spec.rb
@@ -4,7 +4,8 @@ RSpec.describe Spree::AgentTools::ResourceMap do
let(:store) { @default_store }
let(:admin) { create(:admin_user) }
let(:context) do
- Spree::AgentTools::Context.new(store: store, user: admin, ability: full_ability)
+ Spree::AgentTools::Context.new(store: store, user: admin, ability: full_ability,
+ request_headers: agent_headers_for(admin))
end
let(:full_ability) do
Class.new do
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 b1b3a0dca0..1ef137c2cf 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
@@ -237,15 +237,21 @@ RSpec.describe 'agent tool contract' do
end
expect(with_workflow).not_to be_empty
- expect(with_workflow.map(&:generic_writes?).uniq).to eq([false])
+ # Writable through the generic tools too, since those dispatch to the
+ # controller that runs the workflow — one way to write, reached two
+ # ways by name.
+ expect(with_workflow.select(&:generic_writes?)).not_to be_empty
end
- it 'refuses generic writes for a resource written through a Tier 1 service' do
- service_written = Spree::AgentTools::ResourceMap.all.select do |entry|
- Spree::Api::AgentResourceMap::SERVICE_WRITTEN_MODELS.include?(entry.model_name)
- end
+ # The list of service-written models this used to assert over is gone
+ # (2026-10-10). A generic write dispatches to the controller, so a
+ # resource whose controller orchestrates is reached through that
+ # orchestration rather than around it — an order is writable now, and
+ # correctly.
+ it 'allows a generic write for a resource whose controller orchestrates' do
+ orders = Spree::AgentTools::ResourceMap.find('orders')
- expect(service_written.map(&:generic_writes?).uniq - [false]).to be_empty
+ expect(orders.write_permission).to eq('write_orders')
end
it 'gives every generically writable resource a documented attribute list' do
@@ -306,12 +312,11 @@ RSpec.describe 'agent tool contract' do
# 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
+ # written through a workflow it declares, gated per request (imports
+ # and exports), handing out authority, 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) ||
authority_keys.include?(entry.key) ||
contested_keys.include?(entry.key)
diff --git a/spree/api/spec/support/agent_dispatch_headers.rb b/spree/api/spec/support/agent_dispatch_headers.rb
new file mode 100644
index 0000000000..547e79a6ad
--- /dev/null
+++ b/spree/api/spec/support/agent_dispatch_headers.rb
@@ -0,0 +1,23 @@
+# A tool that dispatches to the Admin API authenticates as the caller did, so
+# a spec building a context by hand has to supply the credential a real
+# request would have carried. Minting one belongs here, in test support —
+# never in the dispatcher, which forwards and nothing else.
+module AgentDispatchHeaders
+ # @param user [Object] a Spree admin user
+ # @return [Hash] Rack headers carrying that user's admin JWT
+ def agent_headers_for(user)
+ token = Spree::Api::V3::TestingSupport.generate_jwt(
+ user, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN
+ )
+
+ { 'HTTP_AUTHORIZATION' => "Bearer #{token}", 'HTTP_HOST' => 'www.example.com' }
+ end
+
+ # @param api_key [Spree::ApiKey] a secret key, still holding its plaintext
+ # @return [Hash] Rack headers carrying that key
+ def agent_headers_for_key(api_key)
+ { 'HTTP_X_SPREE_API_KEY' => api_key.plaintext_token, 'HTTP_HOST' => 'www.example.com' }
+ end
+end
+
+RSpec.configure { |config| config.include AgentDispatchHeaders }
diff --git a/spree/api/spec/tools/spree/agent_tools/create_export_spec.rb b/spree/api/spec/tools/spree/agent_tools/create_export_spec.rb
index 3277c5fa50..ec2e24bc44 100644
--- a/spree/api/spec/tools/spree/agent_tools/create_export_spec.rb
+++ b/spree/api/spec/tools/spree/agent_tools/create_export_spec.rb
@@ -5,7 +5,8 @@ RSpec.describe Spree::AgentTools::CreateExport do
let(:store) { @default_store }
let(:admin) { create(:admin_user) }
- let(:context) { Spree::AgentTools::Context.new(store: store, user: admin, ability: ability) }
+ let(:context) { Spree::AgentTools::Context.new(store: store, user: admin, ability: ability,
+ request_headers: agent_headers_for(admin)) }
let(:ability) do
Class.new do
include CanCan::Ability
diff --git a/spree/api/spec/tools/spree/agent_tools/create_order_spec.rb b/spree/api/spec/tools/spree/agent_tools/create_order_spec.rb
index 9243efc028..f7069612fa 100644
--- a/spree/api/spec/tools/spree/agent_tools/create_order_spec.rb
+++ b/spree/api/spec/tools/spree/agent_tools/create_order_spec.rb
@@ -6,7 +6,7 @@ require 'spec_helper'
RSpec.describe 'agent draft order creation' do
let(:store) { @default_store }
let(:api_key) { create(:api_key, :secret, store: store, scopes: ['write_all']) }
- let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key) }
+ let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key, request_headers: agent_headers_for_key(api_key)) }
let(:product) { create(:product, store: store, status: 'active') }
let(:variant) { product.variants.first || create(:variant, product: product) }
@@ -98,7 +98,7 @@ RSpec.describe 'agent draft order creation' do
it 'is withheld from a caller who may only read orders' do
read_only = create(:api_key, :secret, store: store, scopes: ['read_orders'])
- expect(tool(Spree::AgentTools::Context.new(store: store, api_key: read_only))).to be_nil
+ expect(tool(Spree::AgentTools::Context.new(store: store, api_key: read_only, request_headers: agent_headers_for_key(read_only)))).to be_nil
end
# The service's own refusal, in its words — a draft product cannot be sold,
diff --git a/spree/api/spec/tools/spree/agent_tools/curate_products_spec.rb b/spree/api/spec/tools/spree/agent_tools/curate_products_spec.rb
index 40e26eef5a..09082eef06 100644
--- a/spree/api/spec/tools/spree/agent_tools/curate_products_spec.rb
+++ b/spree/api/spec/tools/spree/agent_tools/curate_products_spec.rb
@@ -6,7 +6,7 @@ require 'spec_helper'
RSpec.describe 'agent product curation' do
let(:store) { @default_store }
let(:api_key) { create(:api_key, :secret, store: store, scopes: ['write_all']) }
- let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key) }
+ let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key, request_headers: agent_headers_for_key(api_key)) }
def tool(ctx = context)
Spree.agent_tools.available_for(ctx).find { |candidate| candidate.tool_name == 'curate_products' }
@@ -44,8 +44,11 @@ RSpec.describe 'agent product curation' do
tool.call(target: 'category', id: category.prefixed_id, products: [product.prefixed_id])
result = tool.call(target: 'category', id: category.prefixed_id, products: [product.prefixed_id])
+ # The endpoint counts what changed, and an id already a member changes
+ # nothing. It does not report how many were already there — the old
+ # tool worked that out with extra queries of its own, which is exactly
+ # the second implementation this replaces.
expect(result[:added]).to eq(0)
- expect(result[:already_present]).to eq(1)
end
it 'removes a product' do
@@ -62,7 +65,6 @@ RSpec.describe 'agent product curation' do
products: [product.prefixed_id], operation: 'remove')
expect(result[:removed]).to eq(0)
- expect(result[:not_a_member]).to eq(1)
end
end
@@ -81,7 +83,7 @@ RSpec.describe 'agent product curation' do
# not granted, so a write offered to a read-only grant breaks that promise.
it 'is not offered to a caller who can curate nothing' do
read_only = create(:api_key, :secret, store: store, scopes: %w[read_categories read_products])
- read_context = Spree::AgentTools::Context.new(store: store, api_key: read_only)
+ read_context = Spree::AgentTools::Context.new(store: store, api_key: read_only, request_headers: agent_headers_for_key(read_only))
expect(tool(read_context)).to be_nil
end
@@ -90,7 +92,7 @@ RSpec.describe 'agent product curation' do
# refused for.
it 'names only the parents the caller may curate' do
partial = create(:api_key, :secret, store: store, scopes: %w[write_categories read_products])
- partial_context = Spree::AgentTools::Context.new(store: store, api_key: partial)
+ partial_context = Spree::AgentTools::Context.new(store: store, api_key: partial, request_headers: agent_headers_for_key(partial))
result = tool(partial_context).call(target: 'shelf', id: category.prefixed_id,
products: [product.prefixed_id])
@@ -101,12 +103,13 @@ RSpec.describe 'agent product curation' do
it 'refuses a caller holding only the read permission' do
elsewhere = create(:api_key, :secret, store: store, scopes: %w[write_collections read_categories read_products])
- limited = Spree::AgentTools::Context.new(store: store, api_key: elsewhere)
+ limited = Spree::AgentTools::Context.new(store: store, api_key: elsewhere, request_headers: agent_headers_for_key(elsewhere))
result = tool(limited).call(target: 'category', id: category.prefixed_id,
products: [product.prefixed_id])
- expect(result[:error]).to include('permission')
+ # The endpoint's own refusal, in its own words.
+ expect(result[:error]).to include('write_products')
expect(category.reload.products).to be_empty
end
@@ -118,7 +121,7 @@ RSpec.describe 'agent product curation' do
result = tool.call(target: 'category', id: other_category.prefixed_id,
products: [product.prefixed_id])
- expect(result[:error]).to include('No category found')
+ expect(result[:error]).to be_present
expect(other_category.reload.products).to be_empty
end
@@ -127,7 +130,9 @@ RSpec.describe 'agent product curation' do
result = tool.call(target: 'category', id: category.prefixed_id, products: [foreign.prefixed_id])
- expect(result[:error]).to include('name a product in this store')
+ # Silently dropped by the endpoint, which counts what changed — so the
+ # count is zero and the other store's product is untouched.
+ expect(result[:added]).to eq(0)
expect(category.reload.products).to be_empty
end
end
diff --git a/spree/api/spec/tools/spree/agent_tools/import_tools_spec.rb b/spree/api/spec/tools/spree/agent_tools/import_tools_spec.rb
index c47a233b37..73c9647e28 100644
--- a/spree/api/spec/tools/spree/agent_tools/import_tools_spec.rb
+++ b/spree/api/spec/tools/spree/agent_tools/import_tools_spec.rb
@@ -4,7 +4,8 @@ require 'csv'
RSpec.describe 'assistant import tools' do
let(:store) { @default_store }
let(:admin) { create(:admin_user) }
- let(:context) { Spree::AgentTools::Context.new(store: store, user: admin, ability: ability) }
+ let(:context) { Spree::AgentTools::Context.new(store: store, user: admin, ability: ability,
+ request_headers: agent_headers_for(admin)) }
let(:ability) do
Class.new do
include CanCan::Ability
diff --git a/spree/api/spec/tools/spree/agent_tools/reporting_tools_spec.rb b/spree/api/spec/tools/spree/agent_tools/reporting_tools_spec.rb
index d74c69de64..4dea26db84 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
@@ -8,7 +8,7 @@ RSpec.describe 'agent reporting tools' do
let(:store) { @default_store }
let(:api_key) { create(:api_key, :secret, store: store, scopes: scopes) }
let(:scopes) { ['read_all'] }
- let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key) }
+ let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key, request_headers: agent_headers_for_key(api_key)) }
def tool(name)
Spree.agent_tools.available_for(context).find { |candidate| candidate.tool_name == name }
diff --git a/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rb b/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rb
index 445d0b9cbb..fb7020366a 100644
--- a/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rb
+++ b/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rb
@@ -6,7 +6,7 @@ require 'spec_helper'
RSpec.describe 'agent generic record writes' do
let(:store) { @default_store }
let(:api_key) { create(:api_key, :secret, store: store, scopes: ['write_all']) }
- let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key) }
+ let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key, request_headers: agent_headers_for_key(api_key)) }
def tool(name)
Spree.agent_tools.available_for(context).find { |candidate| candidate.tool_name == name }
@@ -34,23 +34,28 @@ RSpec.describe 'agent generic record writes' do
# A resource with a workflow has exactly one way to be written, and the
# refusal names it so the model retries with the right tool instead of
# giving up.
- it 'refuses a resource written through a workflow, naming its tool' do
+ # The old refusal rule is gone. It existed because the generic writes
+ # assigned attributes and saved, which would have been a second way to
+ # write the same record; dispatched, this IS the controller's way, and
+ # the controller runs whatever workflow it declares.
+ it 'writes a resource whose controller declares a workflow' do
product = create(:product, store: store)
result = tool('update_resource').call(resource: 'products', id: product.prefixed_id,
attributes: { 'name' => 'Renamed' })
- expect(result[:error]).to include('products_update')
- expect(product.reload.name).not_to eq('Renamed')
+ expect(result[:error]).to be_nil
+ expect(product.reload.name).to eq('Renamed')
end
- it 'refuses a resource written through a Tier 1 service' do
+ it 'writes a resource whose controller calls a service' do
order = create(:order, store: store)
result = tool('update_resource').call(resource: 'orders', id: order.prefixed_id,
attributes: { 'email' => '[email protected]' })
- expect(result[:error]).to be_present
+ expect(result[:error]).to be_nil
+ expect(order.reload.email).to eq('[email protected]')
end
# Silently dropping an attribute leaves the model believing it set
@@ -60,7 +65,7 @@ RSpec.describe 'agent generic record writes' do
attributes: { 'colour' => 'blue' })
expect(result[:error]).to include('colour')
- expect(result[:error]).to include('currency')
+ expect(result[:accepted_attributes]).to include('currency')
end
it 'does not reach another store\'s record' do
@@ -96,10 +101,12 @@ RSpec.describe 'agent generic record writes' do
expect(Spree::Market.for_store(store).where(name: name)).to exist
end
- it 'refuses a resource written through a workflow' do
- result = tool('create_resource').call(resource: 'products', attributes: { 'name' => 'New' })
+ it 'creates a resource whose controller declares a workflow' do
+ result = tool('create_resource').call(resource: 'products',
+ attributes: { 'name' => "Dispatched #{SecureRandom.hex(3)}" })
- expect(result[:error]).to include('products_create')
+ expect(result[:error]).to be_nil
+ expect(result[:record][:id]).to be_present
end
end
@@ -121,31 +128,33 @@ RSpec.describe 'agent generic record writes' do
expect(described[:created_by_tool]).to eq('products_create')
expect(described[:updated_by_tool]).to eq('products_update')
- expect(described).not_to have_key(:writable_attributes)
+ # Reported now where it used to be withheld: the generic writes reach
+ # the controller, so a resource with a workflow is writable through
+ # them too and the model needs its attribute list either way.
+ expect(described[:writable_attributes]).to include('name')
end
end
- # The documented attribute list is the API's CREATE body, and a create body
- # can carry a parameter the controller translates rather than assigns — a
- # delivery profile's `kind` picks the STI subclass and is not a column.
- # Handing that to assign_attributes raises, which must not escape as a
- # protocol failure.
- describe 'an attribute the model does not accept' do
+ # A create body can carry a parameter the controller translates rather than
+ # assigns — a delivery profile's `kind` picks the STI subclass and is not a
+ # column. The old generic write handed it to `assign_attributes` and had to
+ # catch the raise; dispatched, the controller decides what to do with it,
+ # so the whole class of problem belongs to the endpoint.
+ describe 'an attribute the controller translates rather than assigns' do
let(:profile) { store.delivery_profiles.first || create(:delivery_profile, store: store) }
- it 'refuses instead of raising when nothing assignable is left' do
+ it 'leaves it to the endpoint rather than raising' do
result = tool('update_resource').call(resource: 'delivery_profiles', id: profile.prefixed_id,
attributes: { 'kind' => 'shipping' })
- expect(result[:error]).to include('kind')
+ expect(result[:error]).to be_nil
end
- it 'applies what it can and names what it could not' do
+ it 'applies the attributes alongside it' do
result = tool('update_resource').call(resource: 'delivery_profiles', id: profile.prefixed_id,
attributes: { 'name' => 'Renamed Profile', 'kind' => 'shipping' })
expect(result[:error]).to be_nil
- expect(result[:unsupported]).to eq(['kind'])
expect(profile.reload.name).to eq('Renamed Profile')
end
end
diff --git a/spree/api/spec/tools/spree/agent_tools/search_resources_spec.rb b/spree/api/spec/tools/spree/agent_tools/search_resources_spec.rb
index e1d02f7f15..54ddf571ea 100644
--- a/spree/api/spec/tools/spree/agent_tools/search_resources_spec.rb
+++ b/spree/api/spec/tools/spree/agent_tools/search_resources_spec.rb
@@ -5,7 +5,8 @@ RSpec.describe Spree::AgentTools::SearchResources do
let(:store) { @default_store }
let(:admin) { create(:admin_user) }
- let(:context) { Spree::AgentTools::Context.new(store: store, user: admin, ability: ability) }
+ let(:context) { Spree::AgentTools::Context.new(store: store, user: admin, ability: ability,
+ request_headers: agent_headers_for(admin)) }
let(:ability) { full_ability_for(admin) }
# A real ability rather than a double: the tools now call `accessible_by`,
# which needs CanCanCan's actual machinery. `admin` here is a full admin, so
@@ -107,7 +108,8 @@ RSpec.describe Spree::AgentTools::SearchResources, 'filter validation' do
let(:store) { @default_store }
let(:admin) { create(:admin_user) }
- let(:context) { Spree::AgentTools::Context.new(store: store, user: admin, ability: ability) }
+ let(:context) { Spree::AgentTools::Context.new(store: store, user: admin, ability: ability,
+ request_headers: agent_headers_for(admin)) }
let(:ability) do
Class.new do
include CanCan::Ability
diff --git a/spree/api/spec/tools/spree/agent_tools/set_stock_spec.rb b/spree/api/spec/tools/spree/agent_tools/set_stock_spec.rb
new file mode 100644
index 0000000000..743e12c9f6
--- /dev/null
+++ b/spree/api/spec/tools/spree/agent_tools/set_stock_spec.rb
@@ -0,0 +1,102 @@
+require 'spec_helper'
+
+# "Forty in stock" is the thing a merchant says that an agent could not do at
+# all before: setting a count needs an endpoint, and reaching the workflow
+# directly skipped the store scoping its one caller performed.
+RSpec.describe 'agent stock setting' do
+ let(:store) { @default_store }
+ let(:api_key) { create(:api_key, :secret, store: store, scopes: ['write_all']) }
+ let(:context) do
+ Spree::AgentTools::Context.new(store: store, api_key: api_key,
+ request_headers: agent_headers_for_key(api_key))
+ end
+ let(:variant) { create(:product, store: store).variants.first }
+ let(:location) { store.stock_locations.first || create(:stock_location, store: store) }
+ let(:level) do
+ Spree::StockLevel.find_or_create_by!(variant: variant, stock_location: location) do |record|
+ record.count_on_hand = 5
+ end
+ end
+
+ def tool(ctx = context)
+ Spree.agent_tools.available_for(ctx).find { |candidate| candidate.tool_name == 'set_stock' }
+ end
+
+ def row(**attributes)
+ { 'variant_id' => variant.prefixed_id, 'stock_location_id' => location.prefixed_id }.merge(
+ attributes.transform_keys(&:to_s)
+ )
+ end
+
+ describe 'counting a shelf' do
+ it 'sets it to the figure given' do
+ level
+
+ result = tool.call(rows: [row(count_on_hand: 40, reason: 'received')])
+
+ expect(result[:error]).to be_nil
+ expect(level.reload.count_on_hand).to eq(40)
+ end
+
+ it 'adjusts it by a difference' do
+ level.update!(count_on_hand: 10)
+
+ tool.call(rows: [row(adjustment: -2, reason: 'damaged')])
+
+ expect(level.reload.count_on_hand).to eq(8)
+ end
+
+ # Stock changes are movements so a merchant can see why a figure changed.
+ it 'records the change in the stock history' do
+ level
+
+ expect { tool.call(rows: [row(count_on_hand: 40, reason: 'received')]) }.
+ to change { level.reload.stock_movements.count }.by(1)
+ end
+ end
+
+ describe 'refusals' do
+ it 'needs at least one row' do
+ expect(tool.call(rows: [])[:error]).to include('at least one row')
+ end
+
+ it 'needs a variant and a location on every row' do
+ expect(tool.call(rows: [{ 'count_on_hand' => 5 }])[:error]).to include('variant_id')
+ end
+
+ # The endpoint's own refusal: a count and an adjustment together is
+ # ambiguous, and it says so rather than picking one.
+ it 'passes on the endpoint refusal for a contradictory row' do
+ level
+
+ result = tool.call(rows: [row(count_on_hand: 10, adjustment: 5)])
+
+ expect(result[:error]).to be_present
+ expect(result[:ok]).to be_nil
+ end
+
+ it 'is withheld from a caller who cannot write stock' do
+ read_only = create(:api_key, :secret, store: store, scopes: ['read_stock'])
+ read_context = Spree::AgentTools::Context.new(store: store, api_key: read_only,
+ request_headers: agent_headers_for_key(read_only))
+
+ expect(tool(read_context)).to be_nil
+ end
+
+ # Another store's shelf is resolved through this store's scope, so the row
+ # names nothing and nothing changes.
+ it 'leaves another store\'s shelf alone' do
+ theirs = create(:product, store: create(:store, code: "other-#{SecureRandom.hex(4)}")).variants.first
+ their_location = create(:stock_location, store: theirs.product.store)
+ their_level = Spree::StockLevel.find_or_create_by!(variant: theirs, stock_location: their_location) do |record|
+ record.count_on_hand = 7
+ end
+
+ tool.call(rows: [{ 'variant_id' => theirs.prefixed_id,
+ 'stock_location_id' => their_location.prefixed_id,
+ 'count_on_hand' => 999 }])
+
+ expect(their_level.reload.count_on_hand).to eq(7)
+ end
+ end
+end
diff --git a/spree/api/spec/tools/spree/agent_tools/upload_chain_spec.rb b/spree/api/spec/tools/spree/agent_tools/upload_chain_spec.rb
index b954f5f2bb..ac52ee884e 100644
--- a/spree/api/spec/tools/spree/agent_tools/upload_chain_spec.rb
+++ b/spree/api/spec/tools/spree/agent_tools/upload_chain_spec.rb
@@ -7,15 +7,24 @@ RSpec.describe 'agent tools that consume an upload' do
let(:admin) { create(:admin_user) }
let(:context) do
Spree::AgentTools::Context.new(store: store, user: admin,
- granted_scopes: %w[write_products read_products write_media write_customers])
+ granted_scopes: %w[write_products read_products write_media write_customers],
+ request_headers: agent_headers_for(admin))
end
def tool(name, ctx = context)
Spree.agent_tools.available_for(ctx).find { |candidate| candidate.tool_name == name }
end
+ # Text as text. A model emits every byte of its arguments, so base64 is
+ # only asked for where the bytes are not text — said explicitly rather
+ # than sniffed, since some binary happens to be valid UTF-8.
def upload(filename, bytes, ctx = context)
- tool('upload_file', ctx).call(filename: filename, content: Base64.strict_encode64(bytes))[:file_id]
+ tool('upload_file', ctx).call(filename: filename, content: bytes)[:file_id]
+ end
+
+ def upload_binary(filename, bytes, ctx = context)
+ tool('upload_file', ctx).
+ call(filename: filename, content: Base64.strict_encode64(bytes), encoding: 'base64')[:file_id]
end
# One transparent pixel. A real PNG, because the type is read from bytes.
@@ -27,7 +36,7 @@ RSpec.describe 'agent tools that consume an upload' do
let(:product) { create(:product, store: store) }
it 'places an uploaded file in a product gallery' do
- result = tool('media_create').call(file_id: upload('shot.png', png),
+ result = tool('media_create').call(file_id: upload_binary('shot.png', png),
product_id: product.prefixed_id, alt: 'Studio shot')
expect(result[:error]).to be_nil
@@ -40,7 +49,7 @@ RSpec.describe 'agent tools that consume an upload' do
# A row with no owner is a library file: uploaded, not yet placed.
it 'leaves it unplaced when no product is named' do
- result = tool('media_create').call(file_id: upload('lib.png', png))
+ result = tool('media_create').call(file_id: upload_binary('lib.png', png))
expect(result[:error]).to be_nil
expect(Spree::Media.find_by_prefix_id(result[:id]).viewable).to be_nil
@@ -53,7 +62,7 @@ RSpec.describe 'agent tools that consume an upload' do
it 'refuses a product in another store' do
theirs = create(:product, store: create(:store, code: "other-#{SecureRandom.hex(4)}"))
- expect(tool('media_create').call(file_id: upload('x.png', png), product_id: theirs.prefixed_id)[:error]).
+ expect(tool('media_create').call(file_id: upload_binary('x.png', png), product_id: theirs.prefixed_id)[:error]).
to include('No product found')
end
@@ -113,7 +122,7 @@ RSpec.describe 'agent tools that consume an upload' do
end
it 'says so when the file is not CSV at all' do
- result = tool('create_import').call(resource: 'products', file_id: upload('shot.png', png))
+ result = tool('create_import').call(resource: 'products', file_id: upload_binary('shot.png', png))
expect(result[:error]).to be_present
expect(result[:ok]).to be_nil
diff --git a/spree/api/spec/tools/spree/agent_tools/upload_file_spec.rb b/spree/api/spec/tools/spree/agent_tools/upload_file_spec.rb
index 47392711af..f6f23d9f04 100644
--- a/spree/api/spec/tools/spree/agent_tools/upload_file_spec.rb
+++ b/spree/api/spec/tools/spree/agent_tools/upload_file_spec.rb
@@ -5,14 +5,20 @@ require 'spec_helper'
RSpec.describe 'agent file upload' do
let(:store) { @default_store }
let(:api_key) { create(:api_key, :secret, store: store, scopes: ['write_all']) }
- let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key) }
+ let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key, request_headers: agent_headers_for_key(api_key)) }
def tool(ctx = context)
Spree.agent_tools.available_for(ctx).find { |candidate| candidate.tool_name == 'upload_file' }
end
+ # Text as text, which is the default now: a model has to emit every byte
+ # of a tool call's arguments, and base64 is a third larger again.
def upload(filename, bytes, **extra)
- tool.call(filename: filename, content: Base64.strict_encode64(bytes), **extra)
+ tool.call(filename: filename, content: bytes, **extra)
+ end
+
+ def upload_binary(filename, bytes, **extra)
+ tool.call(filename: filename, content: Base64.strict_encode64(bytes), encoding: 'base64', **extra)
end
describe 'storing a file' do
@@ -38,7 +44,8 @@ RSpec.describe 'agent file upload' do
end
it 'accepts base64 a model wrapped in newlines' do
- result = tool.call(filename: 'products.csv', content: Base64.encode64("sku,name\nA-1,Thing\n"))
+ result = tool.call(filename: 'shot.png', content: Base64.encode64("\x89PNG\r\n\x1a\n#{"\0" * 40}"),
+ encoding: 'base64')
expect(result[:ok]).to be(true)
end
@@ -49,12 +56,12 @@ RSpec.describe 'agent file upload' do
# recognise, so prose decoded to a few bytes and the refusal talked about
# content types instead of encoding.
it 'refuses content that is not base64 at all' do
- expect(tool.call(filename: 'a.csv', content: 'here is the file I mentioned')[:error])
+ expect(tool.call(filename: 'a.csv', content: '!!!not base64!!!', encoding: 'base64')[:error])
.to include('base64')
end
it 'refuses an empty file' do
- expect(upload('a.csv', '')[:error]).to include('empty')
+ expect(upload('a.csv', '')[:error]).to be_present
end
# The type is read from the bytes, so renaming a file does not smuggle it
@@ -67,19 +74,19 @@ RSpec.describe 'agent file upload' do
end
it 'refuses an executable however it is named' do
- expect(upload('data.csv', "#!/bin/sh\nrm -rf /\n")[:error]).to include('does not store')
+ expect(upload('data.csv', "#!/bin/sh\nrm -rf /\n")[:error]).to include('not accepted')
end
it 'refuses a file beyond the cap' do
- stub_const('Spree::AgentTools::UploadFile::MAX_BYTES', 16)
+ allow(Spree::Config).to receive(:max_multipart_upload_size).and_return(16)
- expect(upload('big.csv', 'x' * 64)[:error]).to include('must be under')
+ expect(upload('big.csv', 'x' * 64)[:error]).to match(/less than or equal to|must be under/)
end
it 'is withheld from a caller who cannot write' do
read_only = create(:api_key, :secret, store: store, scopes: ['read_products'])
- expect(tool(Spree::AgentTools::Context.new(store: store, api_key: read_only))).to be_nil
+ expect(tool(Spree::AgentTools::Context.new(store: store, api_key: read_only, request_headers: agent_headers_for_key(read_only)))).to be_nil
end
end
diff --git a/spree/api/spec/tools/spree/agent_tools/workflow_tool_arguments_spec.rb b/spree/api/spec/tools/spree/agent_tools/workflow_tool_arguments_spec.rb
index 690255265a..de390451af 100644
--- a/spree/api/spec/tools/spree/agent_tools/workflow_tool_arguments_spec.rb
+++ b/spree/api/spec/tools/spree/agent_tools/workflow_tool_arguments_spec.rb
@@ -6,7 +6,7 @@ require 'spec_helper'
RSpec.describe 'agent workflow tool arguments' do
let(:store) { @default_store }
let(:api_key) { create(:api_key, :secret, store: store, scopes: ['write_all']) }
- let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key) }
+ let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key, request_headers: agent_headers_for_key(api_key)) }
def tool(name)
Spree.agent_tools.available_for(context).find { |candidate| candidate.tool_name == name }
@@ -119,7 +119,7 @@ RSpec.describe 'agent workflow tool arguments' do
it 'records an admin user, which the association does accept' do
admin = create(:admin_user)
- admin_context = Spree::AgentTools::Context.new(store: store, user: admin)
+ admin_context = Spree::AgentTools::Context.new(store: store, user: admin, request_headers: agent_headers_for(admin))
admin_tool = Spree.agent_tools.available_for(admin_context).
find { |candidate| candidate.tool_name == 'purchase_orders_create' }
diff --git a/spree/core/app/tools/spree/agent_tools/create_resource.rb b/spree/core/app/tools/spree/agent_tools/create_resource.rb
index baadb92164..83e3dc7c8a 100644
--- a/spree/core/app/tools/spree/agent_tools/create_resource.rb
+++ b/spree/core/app/tools/spree/agent_tools/create_resource.rb
@@ -1,50 +1,32 @@
module Spree
module AgentTools
- # Creates a record of a resource the Admin API writes directly.
+ # Creates a record, through the Admin API's own create operation.
class CreateResource < Spree::AgentTools::ResourceWrite
tool_name 'create_resource'
- description 'Create a store setup record — a market, channel, delivery method, payment ' \
- 'method, tax rate and so on. Call describe_resource first for the attributes ' \
- 'a resource accepts. Catalog and order records are created by their own tools.'
+ description 'Create a record — a market, channel, delivery method, payment method, tax ' \
+ 'rate and so on. Call describe_resource first for the attributes a resource ' \
+ 'accepts. Records with an action of their own (an order, a refund) have a ' \
+ 'tool named for it.'
param :resource, description: 'Resource key — call describe_resource for the list', required: true
param :attributes, type: :object, description: 'Attributes to set on the new record', required: true
def call(resource:, attributes: {})
- entry, refusal = writable_entry(resource)
+ entry, refusal = writable_entry(resource, :create)
return refusal if refusal
- permitted, rejection = permitted_attributes(entry, attributes)
+ body, rejection = body_for(entry, attributes)
return rejection if rejection
- record = build_record(entry, permitted)
- return { error: "You do not have permission to create this #{entry.key.singularize}." } unless context.can?(:create, record)
+ response = dispatch.call(method: :post, path: entry.api_path(:create), body: body)
- save_record(entry, record)
+ result_for(response, entry, summary: summary(resource: resource, attributes: attributes))
end
- protected
+ def summary(arguments)
+ named = arguments[:attributes].to_h.values_at('name', :name, 'number', :number).compact.first
- def preferred_workflow_key(entry)
- entry.create_workflow_key.presence || entry.update_workflow_key
- end
-
- private
-
- # Built through the store's own association where there is one, so the
- # record carries its tenancy from where it was built rather than from an
- # attribute assigned afterwards — the same rule the API's build_resource
- # follows.
- def build_record(entry, attributes)
- association = entry.key.to_sym
- scope = context.store.respond_to?(association) ? context.store.public_send(association) : entry.model_class
-
- scope.new(attributes)
- rescue ActiveModel::UnknownAttributeError => e
- # A documented create parameter the model does not accept as an
- # attribute (an STI selector the controller translates, say) is a tool
- # error naming it, not a protocol failure.
- raise ArgumentError, "#{entry.key.singularize.humanize} does not accept that attribute: #{e.message}"
+ "Create #{arguments[:resource].to_s.singularize.tr('_', ' ')} #{named}".strip
end
end
end
diff --git a/spree/core/app/tools/spree/agent_tools/curate_products.rb b/spree/core/app/tools/spree/agent_tools/curate_products.rb
index 5116f9bd7e..30969f381f 100644
--- a/spree/core/app/tools/spree/agent_tools/curate_products.rb
+++ b/spree/core/app/tools/spree/agent_tools/curate_products.rb
@@ -1,23 +1,19 @@
module Spree
module AgentTools
# Puts products into a category, collection, catalog or price list, and
- # takes them out again.
+ # takes them out again — through the Admin API's own nested products
+ # endpoint, which every curating parent exposes the same way.
#
- # Merchandising is largely membership — what sits in which category, what
- # a wholesale catalog carries, what a price list prices — so this is one
- # of the writes a merchant asks for most. One tool over every curating
- # parent, derived from the membership map, because the Admin API gives
- # them all one nested surface and a parent that adopts it later should
- # need no new tool.
+ # Merchandising is largely membership, so this is the write a merchant
+ # asks for most. One tool over every parent, because the endpoint is
+ # uniform and the registry derives which parents have it.
class CurateProducts < Spree::AgentTool
tool_name 'curate_products'
description 'Add products to a category, collection, catalog or price list, or remove ' \
'them. Find the parent and the products with search_resources first and pass ' \
- 'their ids. Ids naming nothing in this store are ignored, and the result ' \
- 'says how many memberships actually changed.'
+ 'their ids. The result says how many memberships actually changed.'
# Gated per parent in `call`: curating a category needs
- # write_categories and a price list write_products, so a class-level
- # key would hide the tool from a caller holding one but not the other.
+ # write_categories and a price list write_products.
permission nil
mutating!
@@ -30,11 +26,6 @@ module Spree
param :operation, description: '"add" (the default) or "remove"'
# Offered only to a caller who can curate at least one parent.
- #
- # The class declares no permission, because each parent carries its own
- # — but without this a read-only grant was shown a write it could never
- # use, which is exactly the "a tool you cannot see is one this store has
- # not granted" promise the server makes in its instructions.
def permitted?
MembershipMap.all.any? { |entry| context.holds?(entry.permission) }
end
@@ -42,21 +33,20 @@ module Spree
def call(target:, id:, products:, operation: nil)
entry = MembershipMap.find(target)
return unknown_target(target) if entry.nil?
- return forbidden(entry) unless context.holds?(entry.permission)
+ return { error: "#{entry.target} cannot be curated." } if entry.api_path.blank?
- parent = find_parent(entry, id)
- return missing_parent(entry, id) if parent.nil?
+ ids = Array(products).map(&:to_s).reject(&:blank?)
+ return { error: 'Give at least one product.' } if ids.empty?
- # The scope check answers tenancy; this answers which records within
- # it — a role that may edit only its own categories cannot curate
- # another's, the same two steps the controller takes.
- refusal = unauthorized(:update, parent)
- return refusal if refusal
+ removing = operation.to_s.casecmp('remove').zero?
+ response = dispatch.call(
+ method: removing ? :delete : :post,
+ path: entry.api_path.sub(/:\w+_id/, id.to_s),
+ body: { product_ids: ids }
+ )
+ return { error: response.error_message } unless response.success?
- records = find_products(products)
- return no_products if records.empty?
-
- removing?(operation) ? remove(entry, parent, records) : add(entry, parent, records)
+ result(entry, id, response.body, removing)
end
def summary(arguments)
@@ -64,7 +54,7 @@ module Spree
noun = 'product'.pluralize(count)
parent = arguments[:target].to_s.tr('_', ' ')
- if removing?(arguments[:operation])
+ if arguments[:operation].to_s.casecmp('remove').zero?
"Remove #{count} #{noun} from #{parent} #{arguments[:id]}"
else
"Add #{count} #{noun} to #{parent} #{arguments[:id]}"
@@ -73,74 +63,28 @@ module Spree
private
- def removing?(operation)
- operation.to_s.casecmp('remove').zero?
- end
-
- # Counted by re-reading membership rather than by trusting the input: a
- # product already a member changes nothing, and the merchant is told
- # what actually happened rather than what was asked for.
- def add(entry, parent, records)
- before = member_ids(parent, records)
- entry.add(parent, records.reject { |record| before.include?(record.id) })
- gained = member_ids(parent, records) - before
-
- { ok: true, target: entry.target, id: parent.prefixed_id,
- added: gained.size, already_present: before.size }
+ def dispatch
+ @dispatch ||= ApiDispatch.new(context)
end
- def remove(entry, parent, records)
- before = member_ids(parent, records)
- entry.remove(parent, records.select { |record| before.include?(record.id) })
- lost = before - member_ids(parent, records)
-
- { ok: true, target: entry.target, id: parent.prefixed_id,
- removed: lost.size, not_a_member: records.size - before.size }
+ # The endpoint counts what actually changed — an id already a member
+ # changes nothing, and one naming no product in this store is ignored.
+ def result(entry, id, body, removing)
+ counted = body.is_a?(Hash) ? body : {}
+
+ {
+ ok: true,
+ target: entry.target,
+ id: id,
+ removing ? :removed : :added => counted['removed_count'] || counted['added_count'] || 0
+ }
end
- def member_ids(parent, records)
- parent.products.where(id: records.map(&:id)).reorder(nil).distinct.pluck(:id).to_set
- end
-
- def find_parent(entry, id)
- context.accessible(entry.model_class.for_store(context.store), :update).find_by_prefix_id(id)
- end
-
- # An id naming nothing is dropped rather than refused, which is what the
- # Admin API's own bulk writes do — the counts are what tell the merchant
- # which ones landed.
- def find_products(ids)
- decoded = Array(ids).filter_map do |id|
- Spree::Product.decode_prefixed_id(id) if Spree::PrefixedId.prefixed_id?(id.to_s)
- end
- return [] if decoded.empty?
-
- context.accessible(Spree::Product.for_store(context.store), :update).where(id: decoded).to_a
- end
-
- # Only the parents this caller can actually curate, so a model
- # correcting itself does not pick one it will then be refused.
def unknown_target(target)
allowed = MembershipMap.all.select { |entry| context.holds?(entry.permission) }.map(&:target).sort
{ error: "Cannot curate #{target.inspect}.", available_targets: allowed }
end
-
- def forbidden(entry)
- { error: "You do not have permission to change which products a #{label(entry)} holds." }
- end
-
- def missing_parent(entry, id)
- { error: "No #{label(entry)} found for #{id.inspect}." }
- end
-
- def no_products
- { error: 'None of those ids name a product in this store.' }
- end
-
- def label(entry)
- entry.target.tr('_', ' ')
- end
end
end
end
diff --git a/spree/core/app/tools/spree/agent_tools/delete_resource.rb b/spree/core/app/tools/spree/agent_tools/delete_resource.rb
index a3bdd804fe..b2611154c4 100644
--- a/spree/core/app/tools/spree/agent_tools/delete_resource.rb
+++ b/spree/core/app/tools/spree/agent_tools/delete_resource.rb
@@ -1,44 +1,28 @@
module Spree
module AgentTools
- # Removes a record of a resource the Admin API deletes directly.
+ # Removes a record, through the Admin API's own destroy operation —
+ # which soft-deletes, archives or refuses exactly as the dashboard does.
class DeleteResource < Spree::AgentTools::ResourceWrite
tool_name 'delete_resource'
- description 'Delete a store setup record. Catalog and order records are removed by their ' \
- 'own tools, which run the workflow the dashboard runs.'
+ description 'Delete a record. The endpoint decides what deleting means for it — some ' \
+ 'resources archive, some refuse while they are in use.'
param :resource, description: 'Resource key — call describe_resource for the list', required: true
param :id, description: 'The record id as shown in search results', required: true
def call(resource:, id:)
- entry, refusal = writable_entry(resource)
+ entry, refusal = writable_entry(resource, :destroy)
return refusal if refusal
- record = entry.scope_for(context, :destroy).find_by_prefix_id(id)
- return { error: "No #{entry.key.singularize} found for #{id.inspect}." } if record.nil?
- return { error: "You do not have permission to delete this #{entry.key.singularize}." } unless context.can?(:destroy, record)
+ response = dispatch.call(method: :delete, path: entry.api_path(:destroy).sub(':id', id.to_s))
+ return { error: response.error_message } unless response.success?
- label = RecordSummary.call(entry: entry, record: record)[:title]
-
- if record.destroy
- { summary: "Delete #{entry.key.singularize.humanize.downcase} #{label}" }
- else
- { error: record.errors.full_messages.to_sentence.presence || "#{label} could not be deleted." }
- end
+ { summary: summary(resource: resource, id: id) }
end
- protected
-
- # A delete has no workflow key of its own in the map, so naming the
- # update workflow would send the model to a tool that cannot delete.
- # The refusal points at the resource's workflow family instead and
- # lets `describe_resource` list what is actually callable.
- def refusal_for(entry)
- family = entry.update_workflow_key.presence || entry.create_workflow_key
- return super if family.blank?
- "#{entry.key} is written through workflows — call describe_resource to see " \
- "which #{family.split('.').first}_* tool removes one."
+ def summary(arguments)
+ "Delete #{arguments[:resource].to_s.singularize.tr('_', ' ')} #{arguments[:id]}"
end
-
end
end
end
diff --git a/spree/core/app/tools/spree/agent_tools/describe_resource.rb b/spree/core/app/tools/spree/agent_tools/describe_resource.rb
index 97baf0b674..2535b5334d 100644
--- a/spree/core/app/tools/spree/agent_tools/describe_resource.rb
+++ b/spree/core/app/tools/spree/agent_tools/describe_resource.rb
@@ -30,9 +30,12 @@ module Spree
private
+ # Every dispatchable resource reports its attributes now: the generic
+ # writes reach the controller, which runs whatever workflow it
+ # declares, so there is no longer a class of resource they refuse.
def writable_attributes_for(entry)
- return unless entry.generic_writes?
- return unless context.permitted?(entry.write_permission)
+ return unless entry.api_path(:update).present? || entry.api_path(:create).present?
+ return unless entry.write_permission.present? && context.permitted?(entry.write_permission)
entry.writable_attribute_names.presence
end
@@ -46,8 +49,9 @@ module Spree
# which is what create_resource and update_resource tell it to do.
# Offered only where the caller could actually write.
writable_attributes: writable_attributes_for(entry),
- # Named per operation, because they are different tools: a caller
- # preparing a creation must not be handed the update tool's name.
+ # The action tool for a record that has one of its own — cancel,
+ # complete, approve. Ordinary attribute changes go through
+ # update_resource whatever the controller does internally.
created_by_tool: entry.create_workflow_key&.tr('.', '_'),
updated_by_tool: entry.update_workflow_key&.tr('.', '_'),
# Named queries answer things no column can — stock levels live
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 7c83ec176e..48999bf34b 100644
--- a/spree/core/app/tools/spree/agent_tools/get_resource.rb
+++ b/spree/core/app/tools/spree/agent_tools/get_resource.rb
@@ -1,7 +1,7 @@
module Spree
module AgentTools
- # Fetches one record in full, for when the summary from a search is not
- # enough to answer the question.
+ # Fetches one record in full, through the Admin API's own show operation,
+ # for when the summary from a search is not enough to answer the question.
class GetResource < Spree::AgentTool
tool_name 'get_resource'
description 'Fetch one record in full by its id, e.g. prod_86Rf07xd4z or an order number.'
@@ -11,30 +11,29 @@ module Spree
param :id, description: 'The record id as shown in search results', required: true
def call(resource:, id:)
- entry = Spree::AgentTools::ResourceMap.find(resource)
+ entry = ResourceMap.find(resource)
return unknown_resource(resource) if entry.nil?
- return { error: "You do not have permission to read #{entry.key}." } unless context.permitted?(entry.permission)
+ return { error: "You do not have permission to read #{entry.key}." } unless
+ context.permitted?(entry.permission)
- record = find_record(entry, id)
- return { error: "No #{entry.key.singularize} found for #{id.inspect}" } if record.nil?
+ path = entry.api_path(:show)
+ return { error: "#{entry.key} cannot be fetched one at a time." } if path.blank? || path.include?('/:') && path.count(':') > 1
- attributes = serialize(entry, record)
+ response = dispatch.call(method: :get, path: path.sub(':id', id.to_s))
+ return { error: not_found(entry, id, response) } unless response.success?
+
+ attributes = sanitize(response.data, entry)
# An empty hash would be reported as a successful lookup of a record
# with no fields, which is worse than saying the read failed.
- return { error: "Could not read this #{entry.key.singularize}." } if attributes.nil?
+ return { error: "Could not read this #{entry.key.singularize}." } if attributes.blank?
{
resource: entry.key,
# The full record for the model to answer from, plus the same
# compact row `search_resources` returns so the panel can show it
# as something the merchant can click through to.
- #
- # Sanitized like every other outbound record: this is the one tool
- # that emits a whole serializer hash, so without the filter a
- # serializer that gains a token field would send it straight to the
- # AI vendor — the exact case the filter exists for.
record: attributes,
- records: [Spree::AgentTools::RecordSummary.call(entry: entry, record: record, attributes: attributes)],
+ records: [RecordSummary.from_payload(entry: entry, payload: attributes)],
count: 1,
total: 1
}
@@ -43,55 +42,31 @@ module Spree
# Named, not identified: "Look up Rotary Shaver 9000" is what the
# merchant is watching happen. A prefixed id is our plumbing.
def summary(arguments)
- entry = Spree::AgentTools::ResourceMap.find(arguments[:resource])
- record = entry && find_record(entry, arguments[:id])
- label = record && Spree::AgentTools::RecordSummary.call(entry: entry, record: record)[:title]
-
- "Look up #{label.presence || arguments[:id]}"
- rescue StandardError
- "Look up #{arguments[:resource]}"
+ "Look up #{arguments[:id]}"
end
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, entry.key)
- rescue StandardError => e
- Rails.logger.warn("[Spree] #{entry.key} serializer failed: #{e.class}: #{e.message}")
- nil
+ def dispatch
+ @dispatch ||= ApiDispatch.new(context)
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)
+ # Sanitized like every other outbound record: this is the one tool that
+ # emits a whole serializer hash, so without the filter a serializer that
+ # gains a token field would send it straight to the AI vendor — the
+ # exact case the filter exists for.
+ def sanitize(payload, entry)
+ return {} unless payload.is_a?(Hash)
- by_prefixed_id(scope, id) || find_by_natural_key(scope, id)
+ RecordSummary.sanitize(payload.stringify_keys, entry.key)
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
- nil
- end
-
- # Merchants say order numbers and product slugs out loud far more often
- # than prefixed ids, and the model repeats what the merchant said.
- def find_by_natural_key(scope, id)
- %i[number slug].each do |column|
- next unless scope.klass.column_names.include?(column.to_s)
-
- record = scope.find_by(column => id)
- return record if record
- end
+ # A record in another store and one that does not exist answer the same
+ # way, so a probe learns nothing from the difference.
+ def not_found(entry, id, response)
+ return response.error_message if response.status != 404
- nil
+ "No #{entry.key.singularize} found for #{id.inspect}"
end
end
end
diff --git a/spree/core/app/tools/spree/agent_tools/resource_write.rb b/spree/core/app/tools/spree/agent_tools/resource_write.rb
index 2457262ca5..b02e1f73e0 100644
--- a/spree/core/app/tools/spree/agent_tools/resource_write.rb
+++ b/spree/core/app/tools/spree/agent_tools/resource_write.rb
@@ -1,126 +1,98 @@
module Spree
module AgentTools
- # Shared behaviour for the generic record writes.
+ # Shared by the generic writes, which dispatch to the Admin API's own
+ # create, update and destroy operations.
#
- # These exist only for resources whose controller saves the record
- # directly — store, market, channel, delivery, payment and tax setup. A
- # resource written through a workflow refuses them and names its workflow
- # tool instead, so there is exactly one way to write each thing and every
- # write goes through the same validations, hooks and events the dashboard
- # fires.
+ # The controller behind each decides everything that matters: which
+ # attributes it accepts, whether it writes through a workflow, what the
+ # refusal reads like. So these three are correct for every resource, and
+ # the rule that a resource with a workflow refuses the generic write is
+ # gone — there was only ever one way to write a record, and now these
+ # take it.
class ResourceWrite < Spree::AgentTool
- mutating!
-
- # Ungated at the class level because the gate is per resource: a key with
- # `write_settings` may update a market but not a seller, and the resource
- # is not known until the call. {#call} checks the entry's own write
- # permission, and {#permitted?} offers the tool to anyone holding any
- # write key at all.
+ # Gated per resource in `call`, since each names its own write scope —
+ # so the class declares none.
permission nil
+ mutating!
- # Offered only to a caller who may write something, so a read-only key
- # is never told these tools exist.
+ # Offered only to a caller who can write something.
#
- # @return [Boolean]
+ # The endpoint would refuse anyway, but a tool a credential can never
+ # use should not be named to the model: the server promises that a tool
+ # you cannot see is one the store has not granted.
def permitted?
- ResourceMap.all.any? { |entry| writable_for?(entry) }
+ ResourceMap.all.any? do |entry|
+ entry.write_permission.present? && context.permitted?(entry.write_permission)
+ end
end
protected
- # Resolves the resource and refuses, in the model's own vocabulary, when
- # it cannot be written generically.
+ def dispatch
+ @dispatch ||= ApiDispatch.new(context)
+ end
+
+ # The entry, or the refusal naming why not.
#
- # @param key [String]
- # @return [Array(ResourceMap::Entry, nil), Array(nil, Hash)]
- def writable_entry(key)
+ # @return [Array(Entry, nil), Array(nil, Hash)]
+ def writable_entry(key, action)
entry = ResourceMap.find(key)
return [nil, unknown_resource(key)] if entry.nil?
- unless entry.generic_writes?
- return [nil, { error: refusal_for(entry) }]
- end
+ path = entry.api_path(action)
+ return [nil, { error: not_writable(entry, action) }] if path.blank?
- unless context.permitted?(entry.write_permission)
- return [nil, { error: "You do not have permission to change #{entry.key}." }]
- end
+ # The endpoint answers 403 for a scope the credential lacks, in its
+ # own words. This check only avoids offering a tool that cannot work
+ # — a resource the caller cannot even read.
+ return [nil, { error: "You do not have permission to change #{entry.key}." }] unless
+ context.permitted?(entry.permission)
[entry, nil]
end
- # A resource with a workflow is not written here — the tool that does
- # it is named, so the model retries correctly instead of giving up.
- # Which tool depends on what was asked for, so each subclass names its
- # own.
- def refusal_for(entry)
- workflow_key = preferred_workflow_key(entry)
-
- if workflow_key.blank?
- return "#{entry.key} cannot be written with this tool — it is managed elsewhere in the dashboard."
- end
-
- "#{entry.key} is written through a workflow — use the #{workflow_key.tr('.', '_')} tool instead."
- end
-
- # Overridden by CreateResource, which wants the create workflow named.
- def preferred_workflow_key(entry)
- entry.update_workflow_key.presence || entry.create_workflow_key
- end
-
- # Only the attributes the Admin API itself would accept. Anything else is
- # named back rather than silently dropped, so a model that guessed a
- # field name learns the real one from `describe_resource`.
+ # Attributes travel as the request body, so what the controller accepts
+ # is the only list — including the attributes an extension added, which
+ # the hand-written list this replaces could not see.
+ #
+ # An attribute the controller does not permit is dropped silently and
+ # the response is a 200, so a model would report a change that never
+ # happened. Named back instead, the way an unknown filter is.
+ #
+ # The list comes from the generated OpenAPI body, which is the contract
+ # clients already read — so an attribute the endpoint accepts and the
+ # document omits is a documentation bug, fixed in the integration spec
+ # that generates it, not worked around here.
#
# @return [Array(Hash, nil), Array(nil, Hash)]
- def permitted_attributes(entry, attributes)
- attributes = (attributes || {}).transform_keys(&:to_s)
- allowed = entry.writable_attribute_names
- rejected = attributes.keys - allowed
-
- if rejected.any?
- return [nil, { error: "#{entry.key} does not accept #{rejected.to_sentence}. " \
- "Accepted attributes: #{allowed.to_sentence}." }]
- end
+ def body_for(entry, attributes)
+ body = (attributes || {}).to_h.deep_transform_keys(&:to_s)
+ accepted = entry.writable_attribute_names
+ return [body, nil] if accepted.blank?
- [attributes, nil]
- end
+ unknown = body.keys - accepted
+ return [body, nil] if unknown.empty?
- # Assigns only what the model will actually accept.
- #
- # The documented attribute list is the API's create body, and a create
- # body can carry a parameter the controller translates rather than
- # assigns — a delivery profile's `kind` picks the STI subclass and is
- # not a column. Handing that to `assign_attributes` raises
- # ActiveModel::UnknownAttributeError, which escapes as a protocol
- # failure instead of something the model can correct.
- #
- # @return [Array(Hash, Array<String>)] what was assigned, and what the
- # model does not accept
- def assignable_attributes(record, attributes)
- attributes.partition { |name, _value| record.respond_to?(:"#{name}=") }.
- then { |accepted, rejected| [accepted.to_h, rejected.map(&:first)] }
+ [nil, { error: "#{entry.key} does not accept #{unknown.to_sentence}.",
+ accepted_attributes: accepted }]
end
- # Saves through the model's own validations, and hands their messages
- # back verbatim when it refuses.
- def save_record(entry, record)
- return { error: record.errors.full_messages.to_sentence } unless record.save
-
- # One serialization: the summary line needs the record's title, which
- # is what the summary row already carries.
- row = RecordSummary.call(entry: entry, record: record)
+ def result_for(response, entry, summary:)
+ return { error: response.error_message } unless response.success?
- { summary: summary_for(entry, row[:title]), record: row }
- end
+ payload = response.data
+ record = payload.is_a?(Hash) ? RecordSummary.sanitize(payload.stringify_keys, entry.key) : nil
- def summary_for(entry, label)
- "#{self.class.tool_name.humanize} #{entry.key.singularize.humanize.downcase} #{label}"
+ {
+ summary: summary,
+ record: record && RecordSummary.from_payload(entry: entry, payload: record)
+ }.compact
end
- private
+ def not_writable(entry, action)
+ verb = { create: 'created', update: 'updated', destroy: 'deleted' }.fetch(action, 'changed')
- def writable_for?(entry)
- entry.generic_writes? && context.permitted?(entry.write_permission)
+ "#{entry.key} cannot be #{verb} this way — call describe_resource to see what can."
end
end
end
diff --git a/spree/core/app/tools/spree/agent_tools/search_resources.rb b/spree/core/app/tools/spree/agent_tools/search_resources.rb
index 0168f9866b..55f398f329 100644
--- a/spree/core/app/tools/spree/agent_tools/search_resources.rb
+++ b/spree/core/app/tools/spree/agent_tools/search_resources.rb
@@ -1,10 +1,12 @@
module Spree
module AgentTools
- # Searches store records.
+ # Searches store records, through the Admin API's own list operation.
#
- # Every lookup starts from the current store's own association and is
- # filtered through the model's Ransack allowlist, so the assistant can
- # reach exactly what the Admin API would let this admin reach — no more.
+ # Filters, sorting, pagination, store scoping and record-level permissions
+ # are the endpoint's, not this tool's. That is the point: the tool used to
+ # call `.ransack` itself and skipped the step that decodes prefixed ids,
+ # so filtering by an id it had just handed the model matched nothing and
+ # reported it as a fact.
class SearchResources < Spree::AgentTool
DEFAULT_LIMIT = 10
MAX_LIMIT = 25
@@ -15,8 +17,9 @@ module Spree
'bare key, e.g. {"out_of_stock": true} for stock questions or ' \
'{"price_lte": 20} for price. Call describe_resource to see every ' \
'resource, field and scope available.'
- # Per-resource permissions are enforced per call — this tool is offered
- # whenever the admin can read anything at all.
+ # Per-resource permissions are the endpoint's to enforce — it answers
+ # 403 for a scope the credential lacks. This tool is offered whenever
+ # the caller can read anything at all.
permission nil
param :resource, description: 'Resource key — call describe_resource for the list', required: true
@@ -25,39 +28,38 @@ module Spree
param :limit, type: :integer, description: "Max records to return (default #{DEFAULT_LIMIT})"
def call(resource:, filters: nil, sort: nil, limit: nil)
- entry = Spree::AgentTools::ResourceMap.find(resource)
+ entry = ResourceMap.find(resource)
return unknown_resource(resource) if entry.nil?
+ return not_searchable(entry) unless entry.dispatchable?
return forbidden(entry) unless context.permitted?(entry.permission)
applied = sanitize_filters(filters)
- # Ransack silently drops filters it does not recognise, so an invented
- # field would quietly widen the search to everything and the assistant
- # would report the result as a match. Reject it instead, and say which
- # fields exist so the model can correct itself.
+ # Ransack drops a filter it does not recognise and returns the whole
+ # collection, which a model reports as the answer ("you have 38
+ # products with status notreal"). The Admin API will refuse those
+ # itself once strict filters land; until then this is the only thing
+ # between a typo and a confident wrong answer, so it stays.
unrecognised = unrecognised_filters(entry, applied)
return invalid_filters(entry, unrecognised) if unrecognised.any?
- query = build_query(entry, applied, sort)
- # `accessible_by` builds LEFT JOINs for an association condition
- # (`can :read, Product, categories: {...}`), so without `distinct` a
- # record repeats once per matching row and the count is inflated —
- # and the assistant states that count as fact.
- #
- # Except where the resource's own controller has turned it off:
- # Postgres rejects SELECT DISTINCT beside an ORDER BY the select list
- # does not carry, which is why `Admin::PricesController` disables it.
- # Applying it here anyway made every price search answer with a 500.
- result = entry.distinct? ? query.result.distinct : query.result
- records = result.limit(capped_limit(limit)).to_a
+ response = dispatch.call(
+ method: :get,
+ path: entry.api_path(:index),
+ params: query_for(applied, sort, limit)
+ )
+ return { error: response.error_message } unless response.success?
+
+ rows = Array(response.data)
+ meta = response.meta || {}
{
resource: entry.key,
- # How many matched, not how many were returned. The assistant is
- # asked to say how many there are, so handing it the page size would
- # have it state "10 products" for a store holding hundreds.
- total: result.count,
- count: records.size,
- records: records.map { |record| Spree::AgentTools::RecordSummary.call(entry: entry, record: record) }
+ # What the endpoint counted, not what this page holds — the model is
+ # asked how many there are, and would otherwise say "10 products"
+ # for a store holding hundreds.
+ total: meta['count'] || rows.size,
+ count: rows.size,
+ records: rows.map { |row| RecordSummary.from_payload(entry: entry, payload: row) }
}
end
@@ -66,34 +68,42 @@ module Spree
filters = arguments[:filters]
return "Search #{label}" if filters.blank?
- # Name the filter in words, so the activity line says what is being
- # looked for rather than only where.
described = filters.keys.map { |key| key.to_s.tr('_', ' ') }.join(', ')
"Search #{label} by #{described}"
end
private
- # Preloaded the way the admin controllers preload: the summary row runs
- # the resource's own serializer, whose associations would otherwise be
- # one query per record.
- def searchable_scope(entry)
- scope = entry.scope_for(context)
- scope.respond_to?(:preload_associations_lazily) ? scope.preload_associations_lazily : scope
+ def dispatch
+ @dispatch ||= ApiDispatch.new(context)
+ end
+
+ # Ransack filters travel under `q`, the way every other client sends
+ # them — so an unknown one is refused by the API's own filter
+ # validation rather than silently widening the search here.
+ def query_for(filters, sort, limit)
+ params = { limit: capped_limit(limit) }
+ params[:q] = filters if filters.any?
+ params[:sort] = sort if sort.present?
+ params
+ end
+
+ # Empty values match everything, so they are dropped — but `false` is a
+ # real filter value (`{"out_of_stock": false}`), which `compact_blank`
+ # would have thrown away.
+ def sanitize_filters(filters)
+ (filters || {}).to_h.reject { |_key, value| value.nil? || value == '' }
end
- def build_query(entry, filters, sort)
- query = searchable_scope(entry).ransack(filters)
- query.sorts = sort if sort.present?
- query
+ def capped_limit(limit)
+ return DEFAULT_LIMIT if limit.blank?
+
+ [[limit.to_i, 1].max, MAX_LIMIT].min
end
# A filter key is either a named scope (`out_of_stock`) or an
- # `<attribute>_<predicate>` pair. BOTH halves must be checked: Ransack
- # runs with `ignore_unknown_conditions` on, so it silently drops a key
- # it cannot parse and returns the whole collection — which the
- # assistant then reports as the answer ("you have 38 products with
- # status notreal"). Checking only the attribute prefix let exactly that
+ # `<attribute>_<predicate>` pair. BOTH halves are checked, because
+ # checking only the attribute prefix let `status_notarealpredicate`
# through.
def unrecognised_filters(entry, filters)
scopes = entry.filterable_scopes
@@ -109,16 +119,12 @@ module Spree
def valid_attribute_predicate?(entry, key)
entry.filterable_fields.sort_by { |field| -field.length }.any? do |field|
next false unless key.start_with?(field)
- # A bare attribute means Ransack's default `eq`.
next true if key == field
- predicate = key.delete_prefix("#{field}_")
- ransack_predicates.include?(predicate)
+ ransack_predicates.include?(key.delete_prefix("#{field}_"))
end
end
- # Every predicate Ransack knows, including the compound `_any`/`_all`
- # suffixes it generates.
def ransack_predicates
@ransack_predicates ||= Ransack.predicates.keys.to_set
end
@@ -131,22 +137,19 @@ module Spree
}
end
- # Empty values match everything, so they are dropped — but `false` is a
- # real filter value (`{"out_of_stock": false}`), and `compact_blank`
- # would have thrown it away and quietly returned the whole collection.
- def sanitize_filters(filters)
- (filters || {}).to_h.reject { |_key, value| value.nil? || value == '' }
- end
-
- def capped_limit(limit)
- return DEFAULT_LIMIT if limit.blank?
-
- [[limit.to_i, 1].max, MAX_LIMIT].min
- end
-
def forbidden(entry)
{ error: "You do not have permission to read #{entry.key}." }
end
+
+ # A resource reached only under a parent, or one whose controller
+ # resolves its scope per request. Named rather than guessed at, because
+ # a tool cannot invent the parent id such a path needs.
+ def not_searchable(entry)
+ {
+ error: "#{entry.key} cannot be searched on its own.",
+ available: ResourceMap.available_for(context).select(&:dispatchable?).map(&:key).sort
+ }
+ end
end
end
end
diff --git a/spree/core/app/tools/spree/agent_tools/set_stock.rb b/spree/core/app/tools/spree/agent_tools/set_stock.rb
new file mode 100644
index 0000000000..453aaffba6
--- /dev/null
+++ b/spree/core/app/tools/spree/agent_tools/set_stock.rb
@@ -0,0 +1,51 @@
+module Spree
+ module AgentTools
+ # Sets how many of something is on a shelf, through the Admin API's own
+ # bulk endpoint.
+ #
+ # Named for what a merchant says — "forty in stock", "two fewer, damaged"
+ # — rather than for the operation. Either an absolute figure or a signed
+ # change, per variant and location, as many at once as the merchant has
+ # counted.
+ class SetStock < Spree::AgentTool
+ tool_name 'set_stock'
+ description 'Set how many units are on hand, or adjust by a difference. Each row names ' \
+ 'a variant and a stock location, then either count_on_hand (the figure it ' \
+ 'should end at) or adjustment (a signed change). Give a reason so the stock ' \
+ 'history explains it.'
+ permission 'write_stock'
+ mutating!
+
+ param :rows, type: :array, items: :object, required: true,
+ description: 'One per shelf: {"variant_id": "variant_x", ' \
+ '"stock_location_id": "sl_y", "count_on_hand": 40, ' \
+ '"reason": "received"}'
+
+ def call(rows:)
+ prepared = Array(rows).map { |row| row.respond_to?(:to_h) ? row.to_h.stringify_keys : {} }
+ return { error: 'Give at least one row.' } if prepared.empty?
+
+ missing = prepared.each_with_index.filter_map do |row, index|
+ index if row['variant_id'].blank? || row['stock_location_id'].blank?
+ end
+ return { error: "Every row needs a variant_id and a stock_location_id (rows #{missing.join(', ')})." } if
+ missing.any?
+
+ response = ApiDispatch.new(context).call(
+ method: :post, path: '/api/v3/admin/stock_levels/bulk_upsert', body: { stock_levels: prepared }
+ )
+ return { error: response.error_message } unless response.success?
+
+ changed = response.body.is_a?(Hash) ? response.body['stock_level_count'] : nil
+
+ { ok: true, shelves_changed: changed || prepared.size }
+ end
+
+ def summary(arguments)
+ count = Array(arguments[:rows]).size
+
+ "Set stock on #{count} #{'shelf'.pluralize(count)}"
+ end
+ end
+ end
+end
diff --git a/spree/core/app/tools/spree/agent_tools/update_resource.rb b/spree/core/app/tools/spree/agent_tools/update_resource.rb
index fb3c683812..5bdbb11dba 100644
--- a/spree/core/app/tools/spree/agent_tools/update_resource.rb
+++ b/spree/core/app/tools/spree/agent_tools/update_resource.rb
@@ -1,39 +1,38 @@
module Spree
module AgentTools
- # Changes a record of a resource the Admin API writes directly.
+ # Changes a record, through the Admin API's own update operation — which
+ # runs whatever workflow the controller declares, so this is the same
+ # write the dashboard performs.
class UpdateResource < Spree::AgentTools::ResourceWrite
tool_name 'update_resource'
- description 'Change a store setup record — a market, channel, delivery method, payment ' \
- 'method, tax rate and so on. Call describe_resource first for the attributes ' \
- 'a resource accepts. Catalog and order records are changed by their own tools.'
+ description 'Change a record. Call describe_resource first for the attributes a ' \
+ 'resource accepts, and send only the ones to change.'
param :resource, description: 'Resource key — call describe_resource for the list', required: true
param :id, description: 'The record id as shown in search results', required: true
param :attributes, type: :object, description: 'Attributes to change', required: true
def call(resource:, id:, attributes: {})
- entry, refusal = writable_entry(resource)
+ entry, refusal = writable_entry(resource, :update)
return refusal if refusal
- record = entry.scope_for(context, :update).find_by_prefix_id(id)
- return { error: "No #{entry.key.singularize} found for #{id.inspect}." } if record.nil?
- return { error: "You do not have permission to change this #{entry.key.singularize}." } unless context.can?(:update, record)
-
- permitted, rejection = permitted_attributes(entry, attributes)
+ body, rejection = body_for(entry, attributes)
return rejection if rejection
- assignable, unsupported = assignable_attributes(record, permitted)
+ response = dispatch.call(
+ method: :patch,
+ path: entry.api_path(:update).sub(':id', id.to_s),
+ body: body
+ )
+
+ result_for(response, entry, summary: summary(resource: resource, id: id, attributes: attributes))
+ end
- if assignable.empty?
- return { error: "#{entry.key.singularize.humanize} does not accept #{unsupported.to_sentence} on update." }
- end
+ def summary(arguments)
+ changed = arguments[:attributes].to_h.keys.map { |key| key.to_s.tr('_', ' ') }
- record.assign_attributes(assignable)
- save_record(entry, record).tap do |result|
- # Named back rather than silently ignored, so the model does not
- # believe it changed something it did not.
- result[:unsupported] = unsupported if unsupported.any? && result[:error].nil?
- end
+ "Update #{arguments[:resource].to_s.singularize.tr('_', ' ')} #{arguments[:id]}" \
+ "#{": #{changed.to_sentence}" if changed.any?}"
end
end
end
diff --git a/spree/core/app/tools/spree/agent_tools/upload_file.rb b/spree/core/app/tools/spree/agent_tools/upload_file.rb
index 5ce1ffb95f..8b5303ec1a 100644
--- a/spree/core/app/tools/spree/agent_tools/upload_file.rb
+++ b/spree/core/app/tools/spree/agent_tools/upload_file.rb
@@ -1,13 +1,13 @@
module Spree
module AgentTools
- # Takes a file the merchant handed over and stores it, answering with the
- # id every other write accepts.
+ # Stores a file the merchant provided, through the Admin API's own upload
+ # endpoint, and answers with the id every other write accepts.
#
- # The dashboard uploads in two steps: ask for a presigned URL, then PUT
- # the bytes to it. An agent has no second request to make — its arguments
- # are JSON, so the file arrives as base64 and is stored here in one go.
- # What comes back is an ordinary ActiveStorage signed id, so nothing
- # downstream needs to know a model produced it.
+ # The dashboard uploads in two steps: ask for a storage target, then PUT
+ # the bytes to it. An agent has no second request to make, so this sends
+ # the bytes with the request — the multipart shape `POST /files` already
+ # accepts — and the endpoint owns the type allowlist, the size cap and
+ # which store the file belongs to.
#
# Storing a file is not yet using it: the id is attached by whichever
# tool the merchant asked for next, under that tool's own permission.
@@ -15,66 +15,70 @@ module Spree
tool_name 'upload_file'
description 'Store a file the merchant provided — a CSV to import, an image for a ' \
'product, a document to attach — and return the id other tools accept. ' \
- 'Send the bytes base64 encoded. Storing a file does nothing on its own; ' \
- 'pass the id to the tool that uses it.'
- # Storing a file changes nothing a merchant can see until the id is
- # used, so the permission that matters is the one on that write. This
- # gate is the floor: the same one the dashboard's upload endpoint uses.
+ 'Send text as text; use encoding "base64" only for images, PDFs and other ' \
+ 'binary files. Storing a file does nothing on its own.'
+ # The endpoint's own floor, which is the gate the dashboard's uploader
+ # passes; whatever uses the file checks its own permission after.
permission 'write_products'
mutating!
- # Base64 is a third larger than the bytes it carries, and the whole
- # argument passes through the model's context on its way here. Beyond
- # this a file belongs in the dashboard's uploader.
- MAX_BYTES = 10.megabytes
+ param :filename, description: 'The file name, with its extension', required: true
+ param :content, description: 'The file contents — text as text, binary base64 encoded',
+ required: true
+ param :encoding, description: '"base64" for a binary file; omit for text'
+ param :content_type, description: "The file's media type, e.g. text/csv or application/pdf"
- # What a merchant plausibly hands an agent. Deliberately not "anything":
- # a stored blob is attached later by a tool that may not check, and the
- # formats below are the ones the attachments themselves accept.
+ # A private upload accepts any type, which is right for the dashboard —
+ # a merchant picking a file has already decided. A model repeating a
+ # filename back has decided nothing, so an agent is held to the kinds
+ # it has a reason to send.
PERMITTED_CONTENT_TYPES = %w[
text/csv
+ text/plain
application/pdf
image/jpeg
image/png
image/webp
- image/heic
image/gif
- application/zip
- application/msword
- application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
].freeze
- param :filename, description: 'The file name, with its extension', required: true
- param :content, description: 'The file bytes, base64 encoded', required: true
- param :content_type, description: "The file's media type, e.g. text/csv or application/pdf"
-
- def call(filename:, content:, content_type: nil)
- bytes = decode(content)
- return { error: 'content must be base64 encoded.' } if bytes.nil?
- return { error: 'The file is empty.' } if bytes.empty?
- return too_large(bytes) if bytes.bytesize > MAX_BYTES
+ def call(filename:, content:, encoding: nil, content_type: nil)
+ bytes, error = decode(content, encoding)
+ return { error: error } if error
- # Read from the bytes rather than trusting what the caller named it:
- # a model repeating a filename it was told is the same weak evidence
- # as an uploader's own header, which is why the attachment validators
- # look at content too.
- declared = content_type.presence || Marcel::MimeType.for(StringIO.new(bytes), name: filename)
- return unsupported(declared) unless PERMITTED_CONTENT_TYPES.include?(declared)
+ # Read from the bytes, not from what the caller named it: Marcel
+ # places the content first, so a renamed script is not a CSV.
+ kind = Marcel::MimeType.for(StringIO.new(bytes), name: filename,
+ declared_type: content_type.presence)
+ unless PERMITTED_CONTENT_TYPES.include?(kind)
+ return { error: "Files of type #{kind.inspect} are not accepted here.",
+ supported_content_types: PERMITTED_CONTENT_TYPES }
+ end
- blob = ActiveStorage::Blob.create_and_upload!(
- io: StringIO.new(bytes),
- filename: filename,
- content_type: declared,
- service_name: Spree.private_storage_service_name
+ response = ApiDispatch.new(context).call(
+ method: :post,
+ path: '/api/v3/admin/files',
+ body: {
+ 'filename' => filename,
+ 'content_type' => kind,
+ # Agent uploads are private: a purchase order or a customer list
+ # is not something to put behind a public URL, and a private
+ # upload is the one that accepts a document at all.
+ 'visibility' => 'private',
+ 'file' => StringIO.new(bytes)
+ }.compact
)
+ return { error: response.error_message } unless response.success?
+
+ data = response.data.to_h
{
ok: true,
- file_id: blob.signed_id,
- filename: blob.filename.to_s,
- content_type: blob.content_type,
- byte_size: blob.byte_size
+ file_id: data['signed_id'],
+ filename: data['filename'],
+ content_type: data['content_type'],
+ byte_size: data['byte_size']
}
end
@@ -84,30 +88,16 @@ module Spree
private
- # A model that wrapped the payload in newlines is forgiven; one that
- # sent something else entirely is not. `decode64` cannot be used as the
- # test: it skips whatever it does not recognise, so a sentence of prose
- # decodes to a handful of bytes and the refusal that followed talked
- # about content types rather than about encoding.
- def decode(content)
- Base64.strict_decode64(content.to_s.gsub(/\s+/, ''))
- rescue ArgumentError
- nil
- end
+ # Text arrives as text. Base64 is a third larger and a model has to
+ # emit every byte of it, so it is asked for only where the bytes are
+ # not text at all.
+ def decode(content, encoding)
+ raw = content.to_s
+ return [raw, nil] unless encoding.to_s == 'base64'
- def too_large(bytes)
- {
- error: "That file is #{ActiveSupport::NumberHelper.number_to_human_size(bytes.bytesize)}. " \
- "Files this tool stores must be under #{ActiveSupport::NumberHelper.number_to_human_size(MAX_BYTES)} — " \
- 'upload a larger one from the dashboard.'
- }
- end
-
- def unsupported(content_type)
- {
- error: "This tool does not store #{content_type.inspect} files.",
- supported_content_types: PERMITTED_CONTENT_TYPES
- }
+ [Base64.strict_decode64(raw.gsub(/\s+/, '')), nil]
+ rescue ArgumentError
+ [nil, 'content is not valid base64. Send text as text, without the encoding parameter.']
end
end
end
diff --git a/spree/core/lib/spree/agent_tools/api_dispatch.rb b/spree/core/lib/spree/agent_tools/api_dispatch.rb
index 2200c02839..a9191df70d 100644
--- a/spree/core/lib/spree/agent_tools/api_dispatch.rb
+++ b/spree/core/lib/spree/agent_tools/api_dispatch.rb
@@ -56,9 +56,12 @@ module Spree
end
# @param method [Symbol] :get, :post, :patch, :delete
- # @param path [String] the operation's path, already interpolated
+ # @param path [String] the operation's full path, already interpolated —
+ # the resource map's paths are absolute (`/api/v3/admin/products`)
# @param params [Hash] query parameters for a read
- # @param body [Hash, nil] the request body for a write
+ # @param body [Hash, nil] the request body for a write. A value that
+ # responds to `read` makes the request multipart, which is how the
+ # upload endpoint takes bytes.
# @return [Response]
def call(method:, path:, params: {}, body: nil)
env = build_env(method, path, params, body)
@@ -74,14 +77,26 @@ module Spree
# helper that yields, it ran before the executor finished unwinding
# and the outer values were lost again.
saved = Spree::Current.attributes.to_a
- Spree::Current.reset
+ # `RequestStore` is per-request too, and the inner request's middleware
+ # clears it on the way out — leaving `RequestStore.store` nil, which
+ # the store scope guard indexes into on the outer request's next
+ # query. Saved unconditionally, including when it is already empty:
+ # restoring an empty hash is what keeps it a hash.
+ saved_request_store = defined?(RequestStore) ? RequestStore.store.to_h.dup : nil
begin
status, headers, rack_body = Rails.application.call(env)
Response.new(status: status, headers: headers, body: parse(rack_body))
ensure
- Spree::Current.reset
+ # The executor flushes `ActiveSupport::ExecutionContext` as the
+ # inner request unwinds, and that is where `CurrentAttributes` keeps
+ # its per-thread instances — so the outer request's next read of
+ # `Spree::Current` found no registry and raised inside Rails. A
+ # frame has to be pushed back BEFORE the values are written, or the
+ # writes land in a frame that is then replaced and read as nil.
+ ActiveSupport::ExecutionContext.push if defined?(ActiveSupport::ExecutionContext)
saved.each { |name, value| Spree::Current.public_send(:"#{name}=", value) }
+ RequestStore.store = saved_request_store unless saved_request_store.nil?
end
end
@@ -89,14 +104,12 @@ module Spree
def build_env(method, path, params, body)
query = params.present? ? Rack::Utils.build_nested_query(stringify(params)) : nil
- payload = body.present? ? JSON.generate(body) : nil
env = Rack::MockRequest.env_for(
- [mount_path, path].join,
+ path,
method: method.to_s.upcase,
params: query,
- input: payload,
- 'CONTENT_TYPE' => ('application/json' if payload)
+ **payload_env(body)
).compact
forwarded.each { |name, value| env[name] = value }
@@ -104,6 +117,46 @@ module Spree
env
end
+ # JSON unless the body carries an IO, in which case the request is
+ # multipart — the shape `POST /files` reads bytes from, and the only
+ # way to hand it a file without a second request from outside.
+ def payload_env(body)
+ return {} if body.blank?
+
+ file = body.find { |_name, value| value.respond_to?(:read) }
+ return { input: JSON.generate(body), 'CONTENT_TYPE' => 'application/json' } if file.nil?
+
+ boundary = "SpreeAgentTools#{SecureRandom.hex(16)}"
+ {
+ input: multipart_body(body, file, boundary),
+ 'CONTENT_TYPE' => "multipart/form-data; boundary=#{boundary}"
+ }
+ end
+
+ # Written out rather than taken from `Rack::Test`, which is a test
+ # dependency of neither gem and would be missing from a real install.
+ def multipart_body(body, file, boundary)
+ name, io = file
+ filename = body['filename'].presence || 'file'
+ content_type = body['content_type'].presence || 'application/octet-stream'
+
+ parts = body.except(name).filter_map do |field, value|
+ next if value.nil?
+
+ "--#{boundary}\r\nContent-Disposition: form-data; name=\"#{field}\"\r\n\r\n#{value}\r\n"
+ end
+
+ parts << "--#{boundary}\r\n" \
+ "Content-Disposition: form-data; name=\"#{name}\"; filename=\"#{filename}\"\r\n" \
+ "Content-Type: #{content_type}\r\n\r\n"
+
+ # Binary, because the bytes are: joining them into a UTF-8 string
+ # raises on the first image that is not valid UTF-8.
+ parts.join.dup.force_encoding(Encoding::BINARY) +
+ io.read.dup.force_encoding(Encoding::BINARY) +
+ "\r\n--#{boundary}--\r\n".dup.force_encoding(Encoding::BINARY)
+ end
+
# The credential the caller authenticated with, repeated verbatim. Never
# an internal header that skips authentication: that would rebuild the
# second security boundary this class exists to remove.
@@ -111,10 +164,6 @@ module Spree
@context.request_headers.slice(*FORWARDED_HEADERS)
end
- def mount_path
- Spree::Api::Oauth.resources[:admin] if defined?(Spree::Api::Oauth)
- end
-
def parse(rack_body)
text = +''
rack_body.each { |chunk| text << chunk }
diff --git a/spree/core/lib/spree/agent_tools/default_catalog.rb b/spree/core/lib/spree/agent_tools/default_catalog.rb
index 6d593ba5a8..b4a1148753 100644
--- a/spree/core/lib/spree/agent_tools/default_catalog.rb
+++ b/spree/core/lib/spree/agent_tools/default_catalog.rb
@@ -24,6 +24,7 @@ module Spree
Spree::AgentTools::CreateOrder
Spree::AgentTools::CreateMedia
Spree::AgentTools::CreateImport
+ Spree::AgentTools::SetStock
Spree::AgentTools::QueryReport
Spree::AgentTools::DescribeReporting
Spree::AgentTools::CreateExport
@@ -76,7 +77,6 @@ module Spree
# Orders. `restock_items` is hidden: it is deprecated and ignored, so
# offering it would invite a model to set something that does nothing.
order_cancel_workflow: { permission: 'write_orders', except: %i[restock_items] },
- stock_level_bulk_upsert_workflow: 'write_stock',
order_complete_workflow: 'write_orders',
# Fulfillment
@@ -154,6 +154,10 @@ module Spree
seller_payout_complete_workflow:
'Settles a payout against the payment provider. Belongs to the payouts pipeline, which ' \
'reconciles against provider state the agent cannot see.',
+ stock_level_bulk_upsert_workflow:
+ 'Reached through its endpoint by set_stock, not run in process. The workflow takes ' \
+ 'ids it trusts; the endpoint resolves them against the store first, and that is the ' \
+ 'check an agent must not be able to skip.',
import_start_mapping_workflow:
'Reads the uploaded file and proposes its column mapping. Runs as part of creating ' \
'an import rather than on its own — a mapping proposal against a file nobody has ' \
diff --git a/spree/core/lib/spree/agent_tools/membership_map.rb b/spree/core/lib/spree/agent_tools/membership_map.rb
index c972bdb918..1bef4f76f2 100644
--- a/spree/core/lib/spree/agent_tools/membership_map.rb
+++ b/spree/core/lib/spree/agent_tools/membership_map.rb
@@ -9,7 +9,7 @@ module Spree
# parent that adopts it later is curated without a new tool.
module MembershipMap
Entry = Struct.new(:target, :model_name, :permission, :positioned, :service_namespace,
- keyword_init: true) do
+ :api_path, keyword_init: true) do
# @return [Class]
def model_class
model_name.constantize
@@ -71,10 +71,12 @@ module Spree
all.map(&:target).sort
end
- def register(target:, model_name:, permission:, positioned: false, service_namespace: nil)
+ def register(target:, model_name:, permission:, positioned: false, service_namespace: nil,
+ api_path: nil)
entries[target.to_s] = Entry.new(target: target.to_s, model_name: model_name,
permission: permission, positioned: positioned,
- service_namespace: service_namespace)
+ service_namespace: service_namespace,
+ api_path: api_path)
end
def reset!
diff --git a/spree/core/lib/spree/agent_tools/record_summary.rb b/spree/core/lib/spree/agent_tools/record_summary.rb
index 6be73929b1..500f67a0fc 100644
--- a/spree/core/lib/spree/agent_tools/record_summary.rb
+++ b/spree/core/lib/spree/agent_tools/record_summary.rb
@@ -130,8 +130,50 @@ module Spree
}.compact
end
+ # A summary from what the Admin API returned, rather than from a
+ # record.
+ #
+ # The payload is already the serializer's own output, so there is no
+ # second serialization and no second set of association queries. It
+ # still passes the credential filter: the API may hand an authorised
+ # admin a gift card code, and a model is not an authorised admin.
+ #
+ # @param entry [Spree::AgentTools::ResourceMap::Entry]
+ # @param payload [Hash] one record as the endpoint rendered it
+ # @return [Hash]
+ def from_payload(entry:, payload:)
+ attributes = sanitize(payload.to_h.stringify_keys, entry.key)
+ title = title_from(attributes)
+
+ {
+ id: attributes['id'],
+ resource: entry.key,
+ title: title,
+ subtitle: subtitle_for(attributes, title),
+ status: attributes['status'],
+ image_url: attributes['thumbnail_url'],
+ path: dashboard_path_from(entry, attributes['id'])
+ }.compact
+ end
+
private
+ # The same preference order as a record's title, read from the payload.
+ def title_from(attributes)
+ %w[name number label title email sku].each do |field|
+ value = attributes[field]
+ return value.to_s if value.is_a?(String) && value.present?
+ end
+
+ attributes['id'].to_s
+ end
+
+ def dashboard_path_from(entry, id)
+ return if entry.dashboard_path.blank? || id.blank?
+
+ format(entry.dashboard_path, id: id)
+ end
+
# Whether a value is itself a credential — a link that authenticates on
# nothing but the link.
def credential_value?(value)
diff --git a/spree/core/lib/spree/agent_tools/resource_map.rb b/spree/core/lib/spree/agent_tools/resource_map.rb
index 00abe00842..a29349be9f 100644
--- a/spree/core/lib/spree/agent_tools/resource_map.rb
+++ b/spree/core/lib/spree/agent_tools/resource_map.rb
@@ -46,13 +46,17 @@ module Spree
distinct.nil? ? true : distinct
end
- # Whether the generic write tools may touch this resource at all.
- # A resource written through a workflow must be written through its
- # workflow tool, so there is exactly one way to write each thing.
+ # Whether the generic write tools may touch this resource.
+ #
+ # A declared workflow no longer excludes it: the generic writes
+ # dispatch to the controller, which runs its own workflow, so there
+ # is still exactly one way to write each thing and this is it.
+ # What is left to answer is whether the endpoint accepts a body at
+ # all.
#
# @return [Boolean]
def generic_writes?
- create_workflow_key.blank? && update_workflow_key.blank? && write_permission.present?
+ write_permission.present?
end
# The attributes the Admin API would accept on a write, so the generic
diff --git a/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rb b/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rb
index f6f2650eaa..9c01019419 100644
--- a/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rb
+++ b/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rb
@@ -82,7 +82,12 @@ module Spree
Spree::AgentTools::Context.new(
store: current_store,
user: oauth_resource_owner,
- granted_scopes: current_oauth_token.scopes.to_a
+ granted_scopes: current_oauth_token.scopes.to_a,
+ # What a dispatched tool call authenticates with: this request's
+ # own credential, repeated. The grant is what bounds the agent,
+ # so the inner request must be the same grant — not a wider one
+ # minted on its behalf.
+ request_headers: request.env.slice(*Spree::AgentTools::ApiDispatch::FORWARDED_HEADERS)
)
end
diff --git a/spree/mcp/lib/spree/mcp/attachments.rb b/spree/mcp/lib/spree/mcp/attachments.rb
index 1d2e80dbb3..aa623904ec 100644
--- a/spree/mcp/lib/spree/mcp/attachments.rb
+++ b/spree/mcp/lib/spree/mcp/attachments.rb
@@ -13,10 +13,13 @@ module Spree
module Attachments
URI_SCHEME = 'spree+file'.freeze
- # Base64 adds a third again on the wire, and the body is read into
- # memory to send it. Beyond this a file is named and sized but not
- # inlined — the merchant opens it in the dashboard instead.
- MAX_INLINE_BYTES = 4_000_000
+ # Base64 adds a third again, and a model has to read every byte of it:
+ # the 4 MB this used to allow is about 1.4 million tokens, which no
+ # context window holds, so the promise could never be kept. 300 KB of
+ # binary is roughly 100,000 tokens — the size of a scanned page, which
+ # is what these files are. Beyond it a file is named and sized but not
+ # inlined, and the merchant opens it in the dashboard.
+ MAX_INLINE_BYTES = 300_000
# Per resource, newest first. A store accumulates these indefinitely and
# every descriptor is sent on each listing.
diff --git a/spree/mcp/lib/spree/mcp/exports.rb b/spree/mcp/lib/spree/mcp/exports.rb
index 3c065ad1b0..9f58cf295c 100644
--- a/spree/mcp/lib/spree/mcp/exports.rb
+++ b/spree/mcp/lib/spree/mcp/exports.rb
@@ -14,10 +14,11 @@ module Spree
module Exports
URI_SCHEME = 'spree+export'.freeze
- # Beyond this the body is not something a model can usefully read, and
- # returning it would push out the conversation that asked for it. The
- # client is told the size, so it can offer the download instead.
- MAX_INLINE_BYTES = 1_000_000
+ # Set by what a model can read, not by what storage can hold. A CSV is
+ # text, so this is roughly 50,000 tokens — a large but survivable share
+ # of a context window. Beyond it the client is told the size and given
+ # the dashboard link.
+ MAX_INLINE_BYTES = 200_000
class << self
# @param context [Spree::AgentTools::Context]
diff --git a/spree/mcp/spec/lib/spree/mcp/server_spec.rb b/spree/mcp/spec/lib/spree/mcp/server_spec.rb
index 24fbb19f45..89d453ee9f 100644
--- a/spree/mcp/spec/lib/spree/mcp/server_spec.rb
+++ b/spree/mcp/spec/lib/spree/mcp/server_spec.rb
@@ -8,7 +8,15 @@ RSpec.describe Spree::Mcp::Server do
let(:store) { @default_store }
let(:api_key) { create(:api_key, :secret, store: store, scopes: scopes) }
let(:scopes) { ['read_all'] }
- let(:context) { Spree::AgentTools::Context.new(store: store, api_key: api_key) }
+ # A tool that dispatches authenticates as the caller did, so a context
+ # built by hand carries the credential a real request would have.
+ let(:context) do
+ Spree::AgentTools::Context.new(
+ store: store, api_key: api_key,
+ request_headers: { 'HTTP_X_SPREE_API_KEY' => api_key.plaintext_token,
+ 'HTTP_HOST' => 'www.example.com' }
+ )
+ end
let(:server) { described_class.for(context) }
def call(method, **params)
diff --git a/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb b/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb
index db753aba3d..d3b8f5f946 100644
--- a/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb
+++ b/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb
@@ -13,7 +13,10 @@ RSpec.describe 'Admin MCP endpoint', type: :request do
name: 'Probe', redirect_uri: 'https://example.test/callback', confidential: false
)
end
- let(:resource) { Spree::Api::Oauth.resource_identifier(:mcp) }
+ # What consent mints for an MCP client: the MCP endpoint and the Admin API,
+ # because a tool call dispatches to an Admin API operation as the same
+ # grant. A token naming only one surface is exercised below.
+ let(:resource) { Spree::Api::Oauth.granted_audience(:mcp) }
let(:token) { oauth_token(scopes: scopes) }
before { Spree::Api::Oauth.register_resource(:mcp, '/api/v3/admin/mcp') }
@@ -143,7 +146,11 @@ RSpec.describe 'Admin MCP endpoint', type: :request do
end
it 'refuses a token issued for another resource' do
- post_with_token(oauth_token(scopes: 'read_products', audience: "#{resource}/other"))
+ # Built from the identifier, not from the granted pair: that is two
+ # space-separated indicators now, so appending to it would leave the
+ # first one valid and the token would rightly be accepted.
+ post_with_token(oauth_token(scopes: 'read_products',
+ audience: "#{Spree::Api::Oauth.resource_identifier(:mcp)}/other"))
expect(response).to have_http_status(:unauthorized)
end
@@ -185,7 +192,7 @@ RSpec.describe 'Admin MCP endpoint', type: :request do
)
raw = Spree::OauthAccessToken.create!(
application: application, resource_owner: admin, scopes: 'read_products',
- expires_in: 2.hours.to_i, resource: Spree::Api::Oauth.resource_identifier(:mcp)
+ expires_in: 2.hours.to_i, resource: Spree::Api::Oauth.granted_audience(:mcp)
).plaintext_token
body = post_with_token(raw)