Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Keep the agent catalog honest against the admin controllers
Damian Legawiecbf8efe1469be
diff --git a/spree/api/lib/spree/api/agent_resource_map.rb b/spree/api/lib/spree/api/agent_resource_map.rbindex ad3e4438d7..8040677fcb 100644--- a/spree/api/lib/spree/api/agent_resource_map.rb+++ b/spree/api/lib/spree/api/agent_resource_map.rb@@ -133,6 +133,7 @@ module Spreecreate_workflow = workflow_key(instance, :create_workflow)update_workflow = workflow_key(instance, :update_workflow)+ writable = AgentWriteSchemas.attribute_names(key){key: key,@@ -140,8 +141,8 @@ module Spreepermission: "read_#{scope}",serializer_name: serializer.name,dashboard_path: DASHBOARD_PATHS[key],- write_permission: write_permission_for(model, scope, create_workflow, update_workflow),- writable_attributes: AgentWriteSchemas.attribute_names(key),+ write_permission: write_permission_for(model, scope, create_workflow, update_workflow, writable),+ writable_attributes: writable,create_workflow_key: create_workflow,update_workflow_key: update_workflow}@@ -150,13 +151,16 @@ module Spreeprivate# A resource is generically writable only when the Admin API writes it- # by saving the record, and it documents what a write may set. A- # workflow-written resource keeps its workflow key instead (so the- # refusal can name the tool), and a service-written one is not- # writable at all.- def write_permission_for(model, scope, create_workflow, update_workflow)+ # by saving the record, and the OpenAPI document says what a write may+ # set. A workflow-written resource keeps its workflow key instead (so+ # the refusal can name the tool); a service-written one is not writable+ # 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.+ def write_permission_for(model, scope, create_workflow, update_workflow, writable)return if SERVICE_WRITTEN_MODELS.include?(model.name)return if create_workflow.present? || update_workflow.present?+ return if writable.empty?"write_#{scope}"enddiff --git a/spree/api/spec/lib/spree/api/agent_tools_contract_spec.rb b/spree/api/spec/lib/spree/api/agent_tools_contract_spec.rbnew file mode 100644index 0000000000..6226cc1647--- /dev/null+++ b/spree/api/spec/lib/spree/api/agent_tools_contract_spec.rb@@ -0,0 +1,226 @@+require 'spec_helper'++# The Admin API's controllers are the reference wiring for what an agent may+# do: they define which workflow writes a resource, which permission gates it,+# and how a request becomes workflow keywords. These examples keep the agent+# catalog honest against them, so a new admin endpoint cannot quietly arrive+# without an agent deciding what to do about it.+#+# See docs/plans/6.0-mcp-server.md.+RSpec.describe 'agent tool contract' do+ # Every `Spree.<key>_workflow` an admin controller calls, found by reading+ # the controller sources — the same way a reviewer would.+ def workflows_invoked_by_admin_controllers+ root = Spree::Api::Engine.root.join('app', 'controllers', 'spree', 'api', 'v3', 'admin')++ Dir.glob(root.join('**', '*.rb')).flat_map do |path|+ File.read(path).scan(/Spree\.([a-z_]+_workflow)\b/).flatten+ end.uniq.map(&:to_sym).sort+ end++ # Whether an unmapped model reaches the store through a parent the map does+ # hold, which is how Spree::AgentTools::WorkflowTool resolves it.+ def mapped_parent?(model_name, mapped)+ model_name.constantize.reflect_on_all_associations(:belongs_to).any? do |association|+ !association.polymorphic? && mapped.include?(association.klass.name)+ end+ rescue StandardError+ false+ end++ let(:catalog) { Spree::AgentTools::DefaultCatalog }++ describe 'the workflow allowlist' do+ it 'accounts for every workflow an admin controller invokes' do+ invoked = workflows_invoked_by_admin_controllers+ accounted = catalog::WORKFLOWS.keys + catalog::EXCLUDED_WORKFLOWS.keys++ unaccounted = invoked - accounted++ expect(unaccounted).to be_empty, <<~MESSAGE+ These workflows are called by an admin controller but are neither exposed+ as agent tools nor excluded with a reason:++ #{unaccounted.join("\n ")}++ Add each to Spree::AgentTools::DefaultCatalog::WORKFLOWS with the write+ permission its controller declares, or to EXCLUDED_WORKFLOWS saying why+ an agent must not run it.+ MESSAGE+ end++ it 'exposes nothing an admin controller does not invoke' do+ # A workflow no controller reaches has no reference wiring: nothing says+ # how a request becomes its keywords, or which permission gates it.+ stray = catalog::WORKFLOWS.keys - workflows_invoked_by_admin_controllers -+ # The products status workflows are reached through the products+ # controller's own status actions, which call them by a+ # dynamically built key rather than a literal.+ %i[product_activate_workflow product_draft_workflow product_archive_workflow]++ expect(stray).to be_empty+ end++ it 'gives every exclusion a reason' do+ expect(catalog::EXCLUDED_WORKFLOWS.values).to all(be_present)+ end++ it 'names a permission the catalog knows for every exposed workflow' do+ unknown = catalog::WORKFLOWS.filter_map do |key, options|+ permission = options.is_a?(Hash) ? options[:permission] : options+ "#{key} => #{permission}" unless Spree.permissions.key?(permission)+ end++ expect(unknown).to be_empty+ end++ it 'gates every exposed workflow with a write permission' do+ reads = catalog::WORKFLOWS.filter_map do |key, options|+ permission = options.is_a?(Hash) ? options[:permission] : options+ key unless permission.start_with?('write_')+ end++ expect(reads).to be_empty+ end++ it 'resolves every exposed workflow to a class' do+ unresolved = catalog::WORKFLOWS.keys.reject { |key| Spree.public_send(key).is_a?(Class) }++ expect(unresolved).to be_empty+ end+ end++ describe 'schema derivation' do+ it 'derives a schema for every exposed workflow' do+ failures = catalog::WORKFLOWS.filter_map do |key, options|+ options = { permission: options } unless options.is_a?(Hash)+ Spree::AgentTools::WorkflowSchema.new(Spree.public_send(key), except: Array(options[:except])).to_json_schema+ nil+ rescue StandardError => e+ "#{key}: #{e.message}"+ end++ expect(failures).to be_empty, <<~MESSAGE+ Every parameter of an exposed workflow needs a YARD `@param` with a type,+ because the tool's schema is derived from it:++ #{failures.join("\n ")}+ MESSAGE+ end++ # A prefixed id can only be turned into a record under the caller's store.+ # The map answers that directly for a store-scoped model; a model scoped+ # through its parent (a certificate through its company) is resolved+ # through that parent. A model with neither has no tenancy answer at all,+ # and must not be a parameter of an exposed workflow.+ it 'can resolve every record parameter within a store' do+ Spree::Api::AgentResourceMap.install+ mapped = Spree::AgentTools::ResourceMap.all.map(&:model_name)++ unresolvable = catalog::WORKFLOWS.flat_map do |key, options|+ options = { permission: options } unless options.is_a?(Hash)+ schema = Spree::AgentTools::WorkflowSchema.new(Spree.public_send(key), except: Array(options[:except]))++ schema.parameters.filter_map do |parameter|+ model_name = parameter[:model_name]+ next if model_name.blank? || mapped.include?(model_name)+ next if mapped_parent?(model_name, mapped)++ "#{key}.#{parameter[:name]} => #{model_name}"+ end+ end++ expect(unresolvable).to be_empty, <<~MESSAGE+ A record parameter is filled from a prefixed id, which is only safe when+ the record can be narrowed to the caller's store — through the resource+ map, or through a parent the map holds. These can be narrowed by neither:++ #{unresolvable.join("\n ")}+ MESSAGE+ end++ it 'never offers a principal parameter to the caller' do+ offered = catalog::WORKFLOWS.flat_map do |key, options|+ options = { permission: options } unless options.is_a?(Hash)+ schema = Spree::AgentTools::WorkflowSchema.new(Spree.public_send(key), except: Array(options[:except]))++ schema.parameters.filter_map do |parameter|+ "#{key}.#{parameter[:name]}" if Spree::AgentTools::WorkflowSchema::PRINCIPAL_PARAMETERS.include?(parameter[:name])+ end+ end++ expect(offered).to be_empty+ end++ it 'gives every exposed workflow a unique tool name' do+ names = catalog::WORKFLOWS.keys.map { |key| Spree::AgentTools::WorkflowTool.tool_name_for(Spree.public_send(key)) }++ expect(names).to match_array(names.uniq)+ end++ it 'gives every tool a name the protocol accepts' do+ invalid = catalog::WORKFLOWS.keys.map { |key| Spree::AgentTools::WorkflowTool.tool_name_for(Spree.public_send(key)) }.+ reject { |name| name.match?(/\A[a-zA-Z0-9_-]{1,64}\z/) }++ expect(invalid).to be_empty+ end+ end++ describe 'the derived resource map' do+ before { Spree::Api::AgentResourceMap.install }++ it 'registers every admin resource controller that serves a store-scoped model' do+ expect(Spree::AgentTools::ResourceMap.all).not_to be_empty+ end++ it 'never registers a resource whose serializer carries a credential' do+ registered = Spree::AgentTools::ResourceMap.all.map(&:model_name)++ expect(registered).not_to include(*Spree::Api::AgentResourceMap::WITHHELD_MODELS)+ end++ it 'names a permission the catalog knows for every resource' do+ unknown = Spree::AgentTools::ResourceMap.all.reject { |entry| Spree.permissions.key?(entry.permission) }++ expect(unknown.map(&:key)).to be_empty+ end++ it 'refuses generic writes for a resource written through a workflow' do+ with_workflow = Spree::AgentTools::ResourceMap.all.select do |entry|+ entry.create_workflow_key.present? || entry.update_workflow_key.present?+ end++ expect(with_workflow).not_to be_empty+ expect(with_workflow.map(&:generic_writes?).uniq).to eq([false])+ 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++ expect(service_written.map(&:generic_writes?).uniq - [false]).to be_empty+ end++ it 'gives every generically writable resource a documented attribute list' do+ empty = Spree::AgentTools::ResourceMap.all.select(&:generic_writes?).+ select { |entry| entry.writable_attribute_names.empty? }++ expect(empty.map(&:key)).to be_empty, <<~MESSAGE+ These resources accept generic writes but document no writable attributes+ in docs/api-reference/admin.yaml, so an agent has nothing to fill in:++ #{empty.map(&:key).join("\n ")}++ Regenerate the spec (bundle exec rake rswag:specs:swaggerize), or give the+ resource a write workflow.+ MESSAGE+ end++ it 'scopes every registered resource to a store' do+ unscoped = Spree::AgentTools::ResourceMap.all.reject(&:store_scoped?)++ expect(unscoped.map(&:key)).to be_empty+ end+ end+enddiff --git a/spree/core/lib/spree/agent_tools/workflow_schema.rb b/spree/core/lib/spree/agent_tools/workflow_schema.rbindex 417d6b86b5..af25b9b825 100644--- a/spree/core/lib/spree/agent_tools/workflow_schema.rb+++ b/spree/core/lib/spree/agent_tools/workflow_schema.rb@@ -19,6 +19,12 @@ module Spreeendend+ # Tenancy, which comes from the credential and never from the caller.+ # A workflow that takes `store:` is given the context's store; offering+ # it would invite a model to name another merchant's store, and the+ # answer to "which store" is the API key or the signed-in admin.+ CONTEXT_PARAMETERS = %i[store].freeze+# Parameters the caller never supplies: they say who acted, and the# answer is the authenticated principal, not something a model should be# free to name. The adapter injects `context.principal` for whichever of@@ -64,11 +70,11 @@ module Spreedef parameters@parameters ||= begindocumented = docs- undocumented = keywords.keys - documented.keys - PRINCIPAL_PARAMETERS - @except+ undocumented = keywords.keys - documented.keys - injected_parameters - @exceptraise UndocumentedParameterError.new(workflow_class, undocumented) if undocumented.any?keywords.filter_map do |name, required|- next if @except.include?(name) || PRINCIPAL_PARAMETERS.include?(name)+ next if @except.include?(name) || injected_parameters.include?(name)build_parameter(name, required, documented.fetch(name))end@@ -83,6 +89,20 @@ module Spreekeywords.keys & PRINCIPAL_PARAMETERSend+ # The tenancy keywords this workflow accepts.+ #+ # @return [Array<Symbol>]+ def context_parameters+ keywords.keys & CONTEXT_PARAMETERS+ end++ # Everything filled from the context rather than by the caller.+ #+ # @return [Array<Symbol>]+ def injected_parameters+ PRINCIPAL_PARAMETERS + CONTEXT_PARAMETERS+ end+# @return [Hash] a JSON Schema object for the tool's argumentsdef to_json_schemaproperties = parameters.to_h do |parameter|@@ -109,7 +129,7 @@ module Spreedef build_parameter(name, required, doc)types = doc[:types]- model_name = types.find { |type| model_type?(type) }+ model_name = types.filter_map { |type| model_name_for(type) }.first{name: name,@@ -134,14 +154,23 @@ module Spreetext.present? ? "#{prefix} — #{text}" : prefixend- # A Spree model, addressed by prefixed id. `Spree.admin_user_class` and- # the bare `Object` of a principal parameter are not: they never reach- # the schema, because principal parameters are stripped first.- def model_type?(type)- return false unless type.start_with?('Spree::')+ # A Spree model, addressed by prefixed id, as its canonical class name.+ # A YARD block may name a deprecated alias (`Spree::ShippingMethod` for+ # `Spree::DeliveryMethod`), and the alias is a constant pointing at the+ # same class — so resolve the constant and ask it for its own name+ # rather than trusting the spelling.+ #+ # `Spree.admin_user_class` and the bare `Object` of a principal+ # parameter never reach here: those parameters are stripped first.+ #+ # @return [String, nil]+ def model_name_for(type)+ return unless type.start_with?('Spree::')constant = type.safe_constantize- constant.is_a?(Class) && constant < ActiveRecord::Base+ return unless constant.is_a?(Class) && constant < ActiveRecord::Base++ constant.nameenddef json_type_for(types)diff --git a/spree/core/lib/spree/agent_tools/workflow_tool.rb b/spree/core/lib/spree/agent_tools/workflow_tool.rbindex 36fec7e857..d0c2a39b42 100644--- a/spree/core/lib/spree/agent_tools/workflow_tool.rb+++ b/spree/core/lib/spree/agent_tools/workflow_tool.rb@@ -140,7 +140,7 @@ module Spreeresolved = resolve_arguments(arguments)return resolved if resolved.is_a?(Hash) && resolved[:error]- keywords = resolved.merge(principal_arguments)+ keywords = resolved.merge(principal_arguments).merge(context_arguments)run(keywords)rescue ArgumentError => e@@ -208,6 +208,11 @@ module Spreeschema.principal_parameters.index_with { context.principal }end+ # Tenancy comes from the credential, never from a parameter.+ def context_arguments+ schema.context_parameters.index_with { context.store }+ end+# Turns the caller's JSON arguments into what `perform` expects,# resolving every model-typed parameter from its prefixed id.#@@ -237,15 +242,44 @@ module Spree# Resolves a prefixed id within the caller's store, through the resource# map — so tenancy is answered the same way every read is.+ #+ # A model the map does not hold is one with no store scoping of its own+ # (a certificate belongs to a company, a submission to a seller). Those+ # resolve through the mapped parent, so the id still has to belong to+ # this store; a model with neither is not resolvable and the caller is+ # told so rather than being handed another store's record.def find_record(model_name, value)- entry = ResourceMap.all.find { |candidate| candidate.model_name == model_name }- relation = entry ? entry.scope_for(context) : model_name.constantize.for_store(context.store)+ relation = store_scoped_relation(model_name)+ return if relation.nil?relation.find_by_prefix_id(value)rescue StandardErrornilend+ def store_scoped_relation(model_name)+ entry = ResourceMap.all.find { |candidate| candidate.model_name == model_name }+ return entry.scope_for(context) if entry++ parent_scoped_relation(model_name.constantize)+ end++ # Narrows an unscoped model through whichever of its parents the map+ # knows, so `certificate` is looked up among this store's companies'+ # certificates rather than every store's.+ def parent_scoped_relation(model_class)+ model_class.reflect_on_all_associations(:belongs_to).each do |association|+ next if association.polymorphic?++ entry = ResourceMap.all.find { |candidate| candidate.model_name == association.klass.name }+ next if entry.nil?++ return model_class.where(association.foreign_key => entry.scope_for(context).select(:id))+ end++ nil+ end+def subject_summary(arguments)record = arguments.values.find { |value| value.is_a?(ActiveRecord::Base) }return if record.nil?