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 the OAuth authorization server and resource discovery

Damian Legawiec63609e720e56
diff --git a/spree/api/app/controllers/spree/api/v3/oauth/metadata_controller.rb b/spree/api/app/controllers/spree/api/v3/oauth/metadata_controller.rb
new file mode 100644
index 0000000000..7d00499d89
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/oauth/metadata_controller.rb
@@ -0,0 +1,44 @@
+module Spree
+ module Api
+ module V3
+ module Oauth
+ # RFC 9728 Protected Resource Metadata — the one discovery document
+ # Doorkeeper does not ship (it serves RFC 8414 authorization-server
+ # metadata itself).
+ #
+ # A client reads this to learn which authorization server guards a
+ # resource. It is deliberately unauthenticated: a client has no
+ # credential at the point it asks.
+ class MetadataController < ActionController::API
+ include Spree::Core::ControllerHelpers::Store
+
+ # The `resource` value must equal the URL the client was pointed at,
+ # path and all, or a consumer client refuses to continue — so it is
+ # echoed from the registered identifier rather than rebuilt here.
+ def show
+ resource = Spree::Api::Oauth.resource_identifier(params[:resource_key], current_store)
+ return head :not_found if resource.blank?
+
+ render json: {
+ resource: resource,
+ authorization_servers: [issuer],
+ # Staff keys only: a grant acts for an admin user, so a
+ # seller-only key could never be exercised through it.
+ scopes_supported: Spree.permissions.grantable_keys(
+ Spree::PermissionConfiguration::STAFF_AUDIENCE
+ ),
+ bearer_methods_supported: ['header'],
+ resource_documentation: 'https://spreecommerce.org/docs/developer/agentic/admin-mcp'
+ }
+ end
+
+ private
+
+ def issuer
+ ::Doorkeeper.config.issuer.presence || current_store.formatted_url
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index c7e0ae07f6..81666229f9 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -238,6 +238,17 @@ Spree::Core::Engine.add_routes do
post 'auth/password_resets', to: 'password_resets#create'
patch 'auth/password_resets/:id', to: 'password_resets#update'
+ # OAuth 2.1 consent, read and decided by the dashboard. The admin's
+ # own session authorizes it: a secret key may authenticate here but
+ # can never grant authority on a person's behalf.
+ namespace :oauth do
+ get 'authorize', to: 'authorizations#show'
+ post 'authorize', to: 'authorizations#create'
+ delete 'authorize', to: 'authorizations#destroy'
+
+ resources :applications, only: %i[index destroy]
+ end
+
# Semantic reporting (docs/plans/6.0-analytics-semantic-layer.md)
namespace :reporting do
post :query
@@ -1052,6 +1063,14 @@ Spree::Core::Engine.add_routes do
end
end
+ # RFC 9728 Protected Resource Metadata. One document per protected
+ # resource, named by the surface that registered it, so a client
+ # discovers which authorization server guards the URL it was given.
+ # Unauthenticated: a client has no credential at the point it asks.
+ get 'oauth/protected-resource/:resource_key',
+ to: 'oauth/metadata#show',
+ as: :oauth_protected_resource
+
# Webhooks (outside of store namespace — no API key authentication)
namespace :webhooks do
post 'payments/:payment_method_id', to: 'payments#create', as: :payment_webhook
@@ -1066,4 +1085,16 @@ Spree::Core::Engine.add_routes do
end
end
end
+
+ # The authorization server's own endpoints: /oauth/token, /oauth/revoke and
+ # RFC 8414 metadata. Outside the versioned API namespace — the OAuth
+ # protocol is not a Spree API resource and its paths are fixed by the spec
+ # and by what clients expect to find.
+ #
+ # The authorization and application controllers are skipped: consent is
+ # rendered by the dashboard against the JSON endpoints under
+ # /api/v3/admin/oauth, so Doorkeeper's HTML screens are never reached.
+ use_doorkeeper scope: 'oauth' do
+ skip_controllers :authorizations, :applications, :authorized_applications
+ end
end
diff --git a/spree/api/lib/spree/api/engine.rb b/spree/api/lib/spree/api/engine.rb
index c3f11a8673..02290a0c2b 100644
--- a/spree/api/lib/spree/api/engine.rb
+++ b/spree/api/lib/spree/api/engine.rb
@@ -4,6 +4,7 @@ require_relative 'dependencies'
require_relative 'configuration'
require_relative 'agent_write_schemas'
require_relative 'agent_resource_map'
+require_relative 'oauth'
module Spree
module Api
@@ -16,6 +17,13 @@ module Spree
Spree::Api::Dependencies = Spree::Api::ApiDependencies.new
end
+ # Applied from the engine so an installation gets a correct, locked-down
+ # authorization server by adding the gem. A host that needs to change
+ # something calls `Doorkeeper.configure` afterwards, which wins.
+ initializer 'spree.api.oauth', after: :load_config_initializers do |_app|
+ Spree::Api::Oauth.configure!
+ end
+
initializer 'spree.api.request_size_limit' do |app|
require_relative 'middleware/request_size_limit'
app.middleware.insert_before Rack::Runtime, Spree::Api::Middleware::RequestSizeLimit
diff --git a/spree/api/lib/spree/api/oauth.rb b/spree/api/lib/spree/api/oauth.rb
new file mode 100644
index 0000000000..4f45504e03
--- /dev/null
+++ b/spree/api/lib/spree/api/oauth.rb
@@ -0,0 +1,120 @@
+module Spree
+ module Api
+ # OAuth 2.1 authorization server for the Spree API.
+ #
+ # Spree is the authorization server here, not a client of one: a
+ # self-hosted store has no external identity provider to delegate to, and
+ # requiring one would exclude the installations this exists for. This is
+ # the opposite direction from SSO login, which makes Spree an OIDC client
+ # so staff can sign in through a provider; the two share a spec family and
+ # almost no code.
+ #
+ # The first consumer is the Admin MCP server, whose consumer clients
+ # (hosted connectors) accept no other credential. A marketplace app or a
+ # merchant-approved integration is the same flow with a different client,
+ # which is why this lives in `spree_api` rather than in any one gem that
+ # happens to need it.
+ module Oauth
+ # Protected resources, each registered by the surface that owns it.
+ #
+ # A resource identifier must equal the URL the client was pointed at,
+ # path included, or a consumer client refuses the connection — so the
+ # owning surface supplies it rather than this module guessing.
+ #
+ # Spree.api.oauth.register_resource(:mcp) do |store|
+ # "#{store.formatted_url}/api/v3/admin/mcp"
+ # end
+ mattr_accessor :resources, default: {}
+
+ class << self
+ # @param key [Symbol]
+ # @yieldparam store [Spree::Store]
+ # @yieldreturn [String] the resource identifier for that store
+ def register_resource(key, &identifier)
+ resources[key.to_sym] = identifier
+ end
+
+ # @param store [Spree::Store]
+ # @return [Array<String>] every resource identifier this installation
+ # serves for the store
+ def resource_identifiers(store)
+ resources.values.map { |identifier| identifier.call(store) }
+ end
+
+ # @param key [Symbol]
+ # @param store [Spree::Store]
+ # @return [String, nil]
+ def resource_identifier(key, store)
+ resources[key.to_sym]&.call(store)
+ end
+
+ def configure!
+ ::Doorkeeper.configure do
+ orm :active_record
+
+ application_class 'Spree::OauthApplication'
+ access_grant_class 'Spree::OauthAccessGrant'
+ access_token_class 'Spree::OauthAccessToken'
+
+ # The consent controller signs the user in before Doorkeeper runs,
+ # so the authorization server never needs to know how
+ # authentication works.
+ resource_owner_authenticator { send(:current_oauth_resource_owner) }
+
+ # An admin user today, a customer when a storefront client needs
+ # one — recorded polymorphically so either can own a grant.
+ use_polymorphic_resource_owner
+
+ # Authorization code only. A password grant asks a client to
+ # handle someone's password, and client credentials identify no
+ # person, so neither belongs on a surface whose authority is a
+ # user's own permissions.
+ grant_flows %w[authorization_code]
+
+ # Mandatory, not merely supported: these are public clients, and
+ # without PKCE an intercepted code is enough to obtain a token.
+ force_pkce
+ # S256 only — `plain` is in the gem's defaults and protects
+ # nothing against an intercepted code.
+ pkce_code_challenge_methods %w[S256]
+
+ # RFC 8707. Registering the validator is what binds an audience
+ # into the token; left nil, the `resource` parameter is ignored
+ # and a token minted for another service would be accepted.
+ resource_indicator_validator(lambda do |requested, _client|
+ allowed = Spree::Store.all.flat_map do |store|
+ Spree::Api::Oauth.resource_identifiers(store)
+ end
+ requested.any? && requested.all? { |indicator| allowed.include?(indicator) }
+ end)
+
+ # Spree's own permission catalog is the scope vocabulary, so a
+ # grant carries the same keys an API key would and the tool
+ # registry needs no translation. Resolved at configuration time
+ # from the catalog rather than hardcoded, so a scope an extension
+ # registers is grantable without touching this.
+ optional_scopes(*Spree.permissions.grantable_keys(
+ Spree::PermissionConfiguration::STAFF_AUDIENCE
+ ))
+
+ use_refresh_token
+ # One live token per authorization, so re-consenting does not
+ # leave the previous one usable.
+ revoke_previous_authorization_code_token
+ hash_token_secrets fallback: :plain
+ access_token_expires_in 2.hours
+ # Refresh rotation with replay detection comes from the
+ # `previous_refresh_token` column the migration adds — Doorkeeper
+ # enables it by the column's presence, not by a setting.
+
+ api_only
+ handle_auth_errors :raise
+ # Never from a query parameter: the spec forbids it, and a URL
+ # reaches logs and proxies.
+ access_token_methods :from_bearer_authorization
+ end
+ end
+ end
+ end
+ end
+end