Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Fix: the OAuth flow had no HTTP entry point

Damian Legawiec63a638ce5e51
diff --git a/spree/api/app/controllers/spree/api/v3/admin/oauth/applications_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/oauth/applications_controller.rb
index 8d332acbb6..8968ea2342 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/oauth/applications_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/oauth/applications_controller.rb
@@ -43,15 +43,28 @@ module Spree
select(:application_id)
end
+ # Scopes come from the live tokens, not the registration: a
+ # client is registered once and granted per consent, so the
+ # registration's own `scopes` column stays empty and what the
+ # merchant actually approved lives on the tokens.
def serialize(application)
+ tokens = live_tokens_by_application[application.id].to_a
+
{
id: application.prefixed_id,
name: application.name,
- scopes: application.scopes.to_a.sort,
- last_used_at: application.last_used_at,
+ scopes: tokens.flat_map { |token| token.scopes.to_a }.uniq.sort,
+ last_used_at: tokens.map(&:created_at).max,
created_at: application.created_at
}
end
+
+ def live_tokens_by_application
+ @live_tokens_by_application ||=
+ Spree::OauthAccessToken.where(revoked_at: nil).
+ where(resource_owner_type: Spree.admin_user_class.name).
+ group_by(&:application_id)
+ end
end
end
end
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 72bca87dfb..51211fa117 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
@@ -19,6 +19,7 @@ module Spree
skip_scope_check!(jwt_only: true)
before_action :require_signed_in_admin!
+ before_action :require_client_of_this_store!
before_action :load_pre_authorization
def show
@@ -55,6 +56,21 @@ module Spree
)
end
+ # Doorkeeper resolves a client id globally, so without this an
+ # admin of one store could consent to another store's registered
+ # client. Reading it through the store's own association turns
+ # that into a 404, the same defence every other admin lookup
+ # uses.
+ def require_client_of_this_store!
+ return if current_store.oauth_applications.exists?(uid: params[:client_id])
+
+ render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:record_not_found],
+ message: 'Unknown application.',
+ status: :not_found
+ )
+ end
+
def load_pre_authorization
@pre_auth = ::Doorkeeper::OAuth::PreAuthorization.new(
::Doorkeeper.config,
diff --git a/spree/api/app/controllers/spree/api/v3/oauth/authorizations_controller.rb b/spree/api/app/controllers/spree/api/v3/oauth/authorizations_controller.rb
new file mode 100644
index 0000000000..11c62d04c4
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/oauth/authorizations_controller.rb
@@ -0,0 +1,43 @@
+module Spree
+ module Api
+ module V3
+ module Oauth
+ # The authorization endpoint a client sends the browser to.
+ #
+ # It renders nothing itself: consent belongs in the dashboard, where
+ # the merchant is already signed in and the screen matches the rest of
+ # the admin. This hands the request over with its parameters intact,
+ # and the dashboard reads them back through the JSON endpoints under
+ # /api/v3/admin/oauth.
+ #
+ # It is a real route rather than a skipped one because RFC 8414
+ # requires the metadata document to name an `authorization_endpoint`,
+ # and a consumer client refuses a document that advertises the
+ # authorization-code flow without one.
+ class AuthorizationsController < ActionController::Base
+ include Spree::Core::ControllerHelpers::Store
+
+ # Carried across to the dashboard. Everything else is dropped, so a
+ # crafted link cannot smuggle extra parameters into the consent page.
+ FORWARDED_PARAMETERS = %w[
+ client_id redirect_uri response_type scope state
+ code_challenge code_challenge_method resource
+ ].freeze
+
+ def new
+ redirect_to consent_url, allow_other_host: true
+ end
+
+ private
+
+ def consent_url
+ query = params.permit(*FORWARDED_PARAMETERS).to_h.compact_blank.to_query
+ base = Spree::Stores::DashboardUrl.call(store: current_store)
+
+ "#{base}/#{current_store.prefixed_id}/oauth/authorize?#{query}"
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/oauth/server_metadata_controller.rb b/spree/api/app/controllers/spree/api/v3/oauth/server_metadata_controller.rb
new file mode 100644
index 0000000000..4beab9aa5e
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/oauth/server_metadata_controller.rb
@@ -0,0 +1,57 @@
+module Spree
+ module Api
+ module V3
+ module Oauth
+ # RFC 8414 Authorization Server Metadata.
+ #
+ # The document itself is entirely Doorkeeper's. Only URL generation is
+ # Spree's problem: Doorkeeper asks for each endpoint by controller name
+ # anchored at the application root, and these routes are drawn inside
+ # an isolated engine, which cannot generate from such a name. The
+ # injected resolver answers from the engine's own router instead.
+ class ServerMetadataController < ::Doorkeeper::MetadataController
+ private
+
+ def metadata_response
+ @metadata_response ||= ::Doorkeeper::OAuth::MetadataResponse.new(
+ request.base_url,
+ ->(**arguments) { resolve_endpoint(**arguments) }
+ )
+ end
+
+ # Doorkeeper hands over a controller name anchored at the
+ # application root (`/api/v3/…`), while the engine's router knows
+ # its own controllers by their engine-qualified names
+ # (`spree/api/v3/…`). Doorkeeper's own controllers are already
+ # absolute and generate from the application router unchanged.
+ def resolve_endpoint(**arguments)
+ # Doorkeeper prepends a slash to whatever the route mapping
+ # held, so a name configured as "/doorkeeper/tokens" arrives
+ # doubled.
+ name = arguments[:controller].to_s.sub(%r{\A/+}, '')
+
+ if name.start_with?('doorkeeper/')
+ return Spree::Core::Engine.routes.url_for(
+ **arguments.except(:controller),
+ controller: "/#{name}",
+ only_path: false,
+ host: request.host,
+ protocol: request.protocol,
+ port: request.optional_port
+ )
+ end
+
+ Spree::Core::Engine.routes.url_for(
+ **arguments.except(:controller),
+ controller: "spree/#{name}",
+ only_path: false,
+ host: request.host,
+ protocol: request.protocol,
+ port: request.optional_port
+ )
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 81666229f9..642a5b947e 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -1086,15 +1086,33 @@ Spree::Core::Engine.add_routes do
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 server's own endpoints: /oauth/authorize, /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.
+ # `authorizations` is NOT skipped. Skipping it would leave the metadata
+ # document without an `authorization_endpoint`, which is required for the
+ # code flow, so a consumer client would have nowhere to send the browser.
+ # The controller is Spree's own and redirects to the dashboard's consent
+ # screen instead of rendering Doorkeeper's HTML.
+ #
+ # The application-management controllers stay skipped: connected apps are
+ # managed through /api/v3/admin/oauth/applications, under the Admin API's
+ # own authentication.
+ # `controllers` is a block method, not an option to `use_doorkeeper`.
+ #
+ # Doorkeeper's own controllers need a leading slash because these routes are
+ # drawn inside Spree::Core::Engine, which isolates the namespace — a bare
+ # `doorkeeper/tokens` resolves as `Spree::Doorkeeper::Tokens` and fails on
+ # the first request. Spree's own authorizations controller is named from the
+ # application root WITHOUT a slash, because the metadata document builds its
+ # URL with `url_for(controller: "/#{name}")` and adds the slash itself.
use_doorkeeper scope: 'oauth' do
- skip_controllers :authorizations, :applications, :authorized_applications
+ controllers authorizations: 'api/v3/oauth/authorizations',
+ tokens: '/doorkeeper/tokens',
+ token_info: '/doorkeeper/token_info',
+ metadata: '/spree/api/v3/oauth/server_metadata'
+ skip_controllers :applications, :authorized_applications
end
end
diff --git a/spree/api/lib/spree/api/engine.rb b/spree/api/lib/spree/api/engine.rb
index 02290a0c2b..32c8e0f170 100644
--- a/spree/api/lib/spree/api/engine.rb
+++ b/spree/api/lib/spree/api/engine.rb
@@ -18,9 +18,13 @@ module Spree
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|
+ # authorization server by adding the gem.
+ #
+ # Before host initializers, not after: `Doorkeeper.configure` replaces
+ # the whole configuration, so running later would silently discard a
+ # host's own `config/initializers/doorkeeper.rb`. This way the host's
+ # file wins, which is what "configure it yourself" has to mean.
+ initializer 'spree.api.oauth', before: :load_config_initializers do |_app|
Spree::Api::Oauth.configure!
end
diff --git a/spree/api/spec/requests/spree/api/v3/oauth/discovery_spec.rb b/spree/api/spec/requests/spree/api/v3/oauth/discovery_spec.rb
new file mode 100644
index 0000000000..1194c76701
--- /dev/null
+++ b/spree/api/spec/requests/spree/api/v3/oauth/discovery_spec.rb
@@ -0,0 +1,79 @@
+require 'spec_helper'
+
+# The two discovery documents are the whole of a consumer client's first
+# impression: it reads them before it has any credential, and a missing or
+# inconsistent field makes it stop rather than ask. Each required field gets
+# its own assertion for that reason.
+RSpec.describe 'OAuth discovery', type: :request do
+ let(:store) { @default_store }
+
+ before do
+ Spree::Api::Oauth.register_resource(:mcp) do |registered_store|
+ "#{registered_store.formatted_url}/api/v3/admin/mcp"
+ end
+ end
+
+ describe 'GET /.well-known/oauth-authorization-server' do
+ subject(:document) do
+ get '/.well-known/oauth-authorization-server'
+ JSON.parse(response.body)
+ end
+
+ it 'names every endpoint a client needs to run the code flow' do
+ expect(document['authorization_endpoint']).to be_present
+ expect(document['token_endpoint']).to be_present
+ end
+
+ # A client verifies PKCE support before it will proceed, so an absent or
+ # `plain`-carrying list is enough for it to refuse the connection.
+ it 'offers S256 and nothing weaker' do
+ expect(document['code_challenge_methods_supported']).to eq(['S256'])
+ end
+
+ it 'advertises only the authorization-code family' do
+ expect(document['grant_types_supported']).to include('authorization_code')
+ expect(document['grant_types_supported']).not_to include('password', 'client_credentials')
+ end
+
+ it 'advertises audience-restricted tokens' do
+ expect(document['resource_indicators_supported']).to be(true)
+ end
+
+ it 'offers Spree permission keys as scopes' do
+ expect(document['scopes_supported']).to include('read_products', 'write_orders')
+ end
+ end
+
+ describe 'GET /api/v3/oauth/protected-resource/:resource_key' do
+ it 'echoes the resource identifier a token must be bound to' do
+ get '/api/v3/oauth/protected-resource/mcp'
+
+ expect(response).to have_http_status(:ok)
+ body = JSON.parse(response.body)
+ expect(body['resource']).to eq(Spree::Api::Oauth.resource_identifier(:mcp, store))
+ expect(body['authorization_servers']).to be_present
+ expect(body['bearer_methods_supported']).to eq(['header'])
+ end
+
+ it 'is not found for a resource nothing registered' do
+ get '/api/v3/oauth/protected-resource/nothing_here'
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ # The endpoint exists so the metadata document can name it; it renders
+ # nothing itself and hands the browser to the dashboard.
+ describe 'GET /oauth/authorize' do
+ it 'sends the browser to the dashboard with the request intact' do
+ get '/oauth/authorize', params: {
+ client_id: 'abc', redirect_uri: 'https://example.test/cb',
+ response_type: 'code', scope: 'read_products', state: 'xyz'
+ }
+
+ expect(response).to have_http_status(:found)
+ expect(response.location).to include('/oauth/authorize')
+ expect(response.location).to include('state=xyz', 'client_id=abc')
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/oauth_application.rb b/spree/core/app/models/spree/oauth_application.rb
index 150eb45d8a..a27e2ae4bb 100644
--- a/spree/core/app/models/spree/oauth_application.rb
+++ b/spree/core/app/models/spree/oauth_application.rb
@@ -21,11 +21,14 @@ module Spree
foreign_key: :application_id,
dependent: :destroy
- # When someone last used this application, for the connections screen.
+ # When this application was last granted a token that is still live.
+ # Revoked and expired tokens are excluded, so a merchant who has just
+ # revoked an app does not see a recent timestamp suggesting it still
+ # works.
#
# @return [ActiveSupport::TimeWithZone, nil]
def last_used_at
- access_tokens.order(:created_at).last&.created_at
+ access_tokens.where(revoked_at: nil).maximum(:created_at)
end
end
end
diff --git a/spree/core/db/migrate/20261005120000_create_spree_oauth_tables.rb b/spree/core/db/migrate/20261005120000_create_spree_oauth_tables.rb
index ced21fb212..33d5bd33bc 100644
--- a/spree/core/db/migrate/20261005120000_create_spree_oauth_tables.rb
+++ b/spree/core/db/migrate/20261005120000_create_spree_oauth_tables.rb
@@ -54,13 +54,14 @@ class CreateSpreeOauthTables < ActiveRecord::Migration[8.1]
t.timestamps
end
- add_index :spree_oauth_access_tokens, :refresh_token, unique: true
- # Hashed tokens are long, so the lookup index covers a prefix on MySQL,
- # where a full-length text index is rejected.
+ # Hashed tokens are long, so both lookup indexes cover a prefix on MySQL,
+ # where an index over a full-length text column is rejected outright.
if connection.adapter_name.match?(/mysql/i)
add_index :spree_oauth_access_tokens, :token, unique: true, length: 255
+ add_index :spree_oauth_access_tokens, :refresh_token, unique: true, length: 255
else
add_index :spree_oauth_access_tokens, :token, unique: true
+ add_index :spree_oauth_access_tokens, :refresh_token, unique: true
end
end
end
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 653b5c3c05..c11d6416e4 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
@@ -138,6 +138,24 @@ module Spree
oauth_token
end
+ # A token selects its own store, the way a secret key does.
+ #
+ # An MCP client sends a URL and a bearer token and nothing else — it
+ # has no way to set the store header the Admin API otherwise uses —
+ # so without this a token granted for any store but the default one
+ # would be measured against the default store's resource identifier
+ # and always fail its audience check.
+ def resolve_admin_store
+ application_store || super
+ end
+
+ def application_store
+ return if bearer_value.blank?
+ return if bearer_value.start_with?(Spree::ApiKey::PREFIXES['secret'])
+
+ Spree::OauthAccessToken.by_token(bearer_value)&.application&.store
+ end
+
def oauth_token
return @oauth_token if defined?(@oauth_token)
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 4d44c46498..12737b47fc 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
@@ -179,6 +179,26 @@ RSpec.describe 'Admin MCP endpoint', type: :request do
expect(response).to have_http_status(:unauthorized)
end
+
+ # An MCP client sends a URL and a bearer token and nothing else, so the
+ # token has to select its own store: measured against the default store's
+ # resource identifier, every other store's token would fail its audience
+ # check and the endpoint would be single-store in practice.
+ it 'serves the store its application belongs to, with no store header' do
+ other = create(:store, code: "other-#{SecureRandom.hex(4)}")
+ application = other.oauth_applications.create!(
+ name: 'Other store client', redirect_uri: 'https://example.test/cb', confidential: false
+ )
+ 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, other)
+ ).token
+
+ body = post_with_token(raw)
+
+ expect(response).to have_http_status(:ok)
+ expect(body['result']['tools']).to be_present
+ end
end
describe 'tenancy' do