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.

Added OAuth sign-in to the MCP endpoint

Damian Legawiec97e491e58f90
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 7bb21a89cc..653b5c3c05 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
@@ -26,14 +26,14 @@ module Spree
# Prepended so it answers before the inherited authentication does.
# The generic "Authentication required" is useless to an agent: this
# text is what both the model and the person actually read when a
- # client is misconfigured, so it has to say which header to set and
- # where a key comes from.
+ # client is misconfigured, so it has to say which credential to
+ # send and where it comes from.
#
- # It also makes this a machine-only surface. A JWT belongs to a
- # signed-in admin, and a browser session is not what should drive an
+ # A JWT is still refused. It belongs to a signed-in admin in a
+ # browser, and a dashboard session is not what should drive an
# agent — the dashboard assistant is that path, over the same
# registry.
- prepend_before_action :require_secret_key!
+ prepend_before_action :require_agent_credential!
def create
render json: server.handle_json(request.body.read), content_type: 'application/json'
@@ -41,6 +41,22 @@ module Spree
protected
+ # An OAuth token is a third credential the inherited concern knows
+ # nothing about, so it is resolved here. The grant already bound
+ # the token to a real admin user and this request's audience check
+ # confirmed it was issued for this store's endpoint, which is the
+ # same assurance `require_store_membership!` gives a JWT.
+ def authenticate_admin!
+ return super if oauth_token.blank?
+
+ owner = oauth_resource_owner
+ return false if owner.nil?
+
+ @current_api_key = nil
+ @current_user = owner
+ true
+ end
+
# The key in either of the two forms clients offer. Several MCP
# clients have a bearer-token field and no way to set a custom
# header, so a secret key is accepted there too. The `sk_` prefix
@@ -57,34 +73,124 @@ module Spree
# header of many spaces, and this one is attacker-supplied on an
# unauthenticated request.
def bearer_secret_key
- scheme, token = request.headers['Authorization'].to_s.split(' ', 2)
+ value = bearer_value
+ value if value&.start_with?(Spree::ApiKey::PREFIXES['secret'])
+ end
+
+ # Split rather than matched, for the same reason: this header is
+ # attacker-supplied on an unauthenticated request.
+ def bearer_value
+ scheme, value = request.headers['Authorization'].to_s.split(' ', 2)
return unless scheme&.casecmp?('Bearer')
- token = token.to_s.strip
- token if token.start_with?(Spree::ApiKey::PREFIXES['secret'])
+ value.to_s.strip.presence
end
def server
Spree::Mcp::Server.for(agent_context)
end
+ # Either credential resolves into the same context, so the tool
+ # catalog never learns which one a request used. A key's authority
+ # is its scopes; a token's is the admin user's own permissions,
+ # resolved fresh here rather than frozen when the token was issued.
def agent_context
- Spree::AgentTools::Context.new(store: current_store, api_key: current_api_key)
+ if oauth_token.present?
+ Spree::AgentTools::Context.new(
+ store: current_store,
+ user: oauth_resource_owner,
+ granted_scopes: oauth_token.scopes.to_a
+ )
+ else
+ Spree::AgentTools::Context.new(store: current_store, api_key: current_api_key)
+ end
+ end
+
+ # RFC 6750: the challenge names where to discover the authorization
+ # server, which is how a consumer client starts its own sign-in.
+ #
+ # The metadata URL is derived from the resource identifier rather
+ # than from route helpers, so both carry the same scheme and host.
+ # A client compares them, and http-versus-https is enough for it to
+ # decide the document describes a different resource and stop.
+ #
+ # No `scope`: it is a SHOULD, and listing every grantable key makes
+ # a header several kilobytes long. A client reads the real list from
+ # the metadata document.
+ def oauth_challenge
+ resource = Spree::Api::Oauth.resource_identifier(:mcp, current_store)
+ base = resource.sub(%r{/api/v3/admin/mcp\z}, '')
+
+ format(
+ 'Bearer realm="%<realm>s", resource_metadata="%<metadata>s"',
+ realm: resource,
+ metadata: "#{base}/api/v3/oauth/protected-resource/mcp"
+ )
+ end
+
+ # A token issued for another resource must not work here, whatever
+ # its scopes say. Doorkeeper binds the audience at issue; this is
+ # the check that it matches.
+ # The hook ScopedAuthorization reads, so a grant narrows this
+ # request's authority through the same path every admin endpoint
+ # uses rather than only here.
+ def current_oauth_token
+ oauth_token
+ end
+
+ def oauth_token
+ return @oauth_token if defined?(@oauth_token)
+
+ @oauth_token = begin
+ raw = bearer_value
+ if raw.blank? || raw.start_with?(Spree::ApiKey::PREFIXES['secret'])
+ nil
+ else
+ token = Spree::OauthAccessToken.by_token(raw)
+ token if token&.accessible? && audience_matches?(token)
+ end
+ end
+ end
+
+ # Deliberately stricter than Doorkeeper's own
+ # `resource_indicators_match?`, which treats "neither side names a
+ # resource" as a match. Here an unbound token must be refused: the
+ # whole point of the audience is that a token minted for another
+ # resource cannot be replayed against this one, and a token with no
+ # audience cannot be shown to have been issued for this endpoint.
+ def audience_matches?(token)
+ expected = Spree::Api::Oauth.resource_identifier(:mcp, current_store)
+ return false if expected.blank?
+
+ token.resource.to_s.split.include?(expected)
+ end
+
+ def oauth_resource_owner
+ owner = oauth_token.resource_owner
+ owner if owner.is_a?(Spree.admin_user_class)
end
# The error text is what both the model and the person read, so it
# says which header to set and where the key comes from rather than
# only that something was missing.
- def require_secret_key!
- return if secret_api_key.present?
+ # Two ways in: a secret key a developer configured, or an OAuth
+ # token a merchant approved. A 401 carries the OAuth challenge, so
+ # a consumer client that arrives with nothing discovers how to sign
+ # in rather than simply failing.
+ def require_agent_credential!
+ return if secret_api_key.present? || oauth_token.present?
+
+ response.headers['WWW-Authenticate'] = oauth_challenge
render json: {
jsonrpc: '2.0',
id: nil,
error: {
code: -32_001,
- message: 'A Spree secret API key is required. Send it as `X-Spree-API-Key: sk_…` ' \
- 'or `Authorization: Bearer sk_…`. Mint one in the dashboard under ' \
+ message: 'Authentication is required. Either sign in through this store (your ' \
+ 'client will offer that when it reads the challenge on this response), ' \
+ 'or send a secret API key as `X-Spree-API-Key: sk_…` or ' \
+ '`Authorization: Bearer sk_…` — mint one in the dashboard under ' \
'Settings → API keys, granting only the scopes this agent needs.'
}
}, status: :unauthorized
diff --git a/spree/mcp/lib/spree/mcp/engine.rb b/spree/mcp/lib/spree/mcp/engine.rb
index 4b4f2ae386..205ee7949c 100644
--- a/spree/mcp/lib/spree/mcp/engine.rb
+++ b/spree/mcp/lib/spree/mcp/engine.rb
@@ -3,6 +3,16 @@ module Spree
class Engine < ::Rails::Engine
isolate_namespace Spree
engine_name 'spree_mcp'
+
+ # Declares this endpoint as an OAuth protected resource, so a token can
+ # be audience-bound to it and a client can discover the authorization
+ # server from a 401 here. The identifier must be the URL a client was
+ # pointed at, path included, or a consumer client refuses to continue.
+ initializer 'spree.mcp.oauth_resource' do
+ Spree::Api::Oauth.register_resource(:mcp) do |store|
+ "#{store.formatted_url}/api/v3/admin/mcp"
+ end
+ end
end
end
end
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 e49b91c6db..4d44c46498 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
@@ -85,6 +85,100 @@ RSpec.describe 'Admin MCP endpoint', type: :request do
expect(response).to have_http_status(:unauthorized)
end
+
+ # An unauthenticated request has to tell a consumer client where to sign
+ # in, otherwise there is nothing for it to act on: hosted connectors read
+ # this header and start the flow themselves.
+ it 'challenges an anonymous request with the discovery document' do
+ post_rpc('tools/list')
+
+ expect(response).to have_http_status(:unauthorized)
+ expect(response.headers['WWW-Authenticate']).to include(
+ 'resource_metadata="', '/api/v3/oauth/protected-resource/mcp'
+ )
+ end
+
+ it 'names the same scheme and host in the realm and the metadata URL' do
+ post_rpc('tools/list')
+
+ challenge = response.headers['WWW-Authenticate']
+ realm = challenge[/realm="([^"]+)"/, 1]
+ metadata = challenge[/resource_metadata="([^"]+)"/, 1]
+
+ expect(URI.parse(metadata).origin).to eq(URI.parse(realm).origin)
+ end
+ end
+
+ # A merchant grants part of their own authority to a client. Two properties
+ # carry the whole arrangement: the grant can only narrow what the user may
+ # do, and a token issued for some other resource cannot be replayed here.
+ describe 'OAuth authentication' do
+ let(:admin) { create(:admin_user) }
+ let(:resource) { Spree::Api::Oauth.resource_identifier(:mcp, store) }
+ let(:application) do
+ store.oauth_applications.create!(
+ name: 'Probe', redirect_uri: 'https://example.test/callback', confidential: false
+ )
+ end
+
+ def oauth_token(scopes:, audience: resource, owner: admin)
+ Spree::OauthAccessToken.create!(
+ application: application, resource_owner: owner,
+ scopes: Array(scopes).join(' '), expires_in: 2.hours.to_i, resource: audience
+ ).token
+ end
+
+ def post_with_token(raw_token, method = 'tools/list')
+ post_rpc(method, headers: { 'Authorization' => "Bearer #{raw_token}" })
+ end
+
+ it 'authenticates a token and acts as its owner' do
+ body = post_with_token(oauth_token(scopes: 'read_products'))
+
+ expect(response).to have_http_status(:ok)
+ expect(body['result']['tools']).to be_present
+ end
+
+ it 'narrows the catalog to what the merchant consented to' do
+ granted = post_with_token(oauth_token(scopes: 'read_products'))['result']['tools']
+ key_offers = post_rpc('tools/list', headers: { 'X-Spree-API-Key' => token })['result']['tools']
+
+ expect(granted.size).to be < key_offers.size
+ expect(granted.map { |tool| tool['name'] }).not_to include('orders_cancel')
+ end
+
+ it 'refuses a token issued for another resource' do
+ post_with_token(oauth_token(scopes: 'read_products', audience: "#{resource}/other"))
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+
+ # Stricter than Doorkeeper's own comparison, which treats two blanks as a
+ # match: a token that names no audience cannot be shown to have been
+ # issued for this endpoint.
+ it 'refuses a token with no audience at all' do
+ post_with_token(oauth_token(scopes: 'read_products', audience: nil))
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+
+ it 'refuses a revoked token' do
+ raw = oauth_token(scopes: 'read_products')
+ Spree::OauthAccessToken.by_token(raw).update!(revoked_at: Time.current)
+
+ post_with_token(raw)
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+
+ it 'refuses an expired token' do
+ raw = oauth_token(scopes: 'read_products')
+ Spree::OauthAccessToken.by_token(raw).update!(created_at: 3.hours.ago)
+
+ post_with_token(raw)
+
+ expect(response).to have_http_status(:unauthorized)
+ end
end
describe 'tenancy' do