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 authentication across the Admin API

Damian Legawiecf5a793a68117
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/store_context.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/store_context.rb
index 9fe577f698..98d2c25432 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/admin/store_context.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/store_context.rb
@@ -60,6 +60,13 @@ module Spree
def resolve_admin_store
return secret_api_key.store if secret_api_key
+ # An OAuth client is registered for one store and consented to on
+ # that store, so its token names the tenancy as surely as a secret
+ # key does. Reading the header instead would let a client name
+ # another merchant's store on a grant that never covered it.
+ oauth_store = respond_to?(:admin_oauth_token, true) && admin_oauth_token&.application&.store
+ return oauth_store if oauth_store
+
if store_id_header
Spree::Store.find_by_prefix_id(store_id_header)
else
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rb
index fbb3169e7d..c5a527486e 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rb
@@ -50,6 +50,11 @@ module Spree
return true
end
+ # Then an OAuth token, which carries both the admin who granted it
+ # and the store its client was registered for, so neither a JWT's
+ # store-membership check nor a key's store selection applies.
+ return true if authenticate_admin_oauth_token
+
# Fall back to JWT authentication, then bind the admin to the store
# they hold a role on (the token itself is store-agnostic).
return false unless require_authentication!
@@ -59,6 +64,62 @@ module Spree
private
+ # An OAuth bearer token, accepted only when it was issued for this
+ # API. A token names the resources it may be used against (RFC 8707),
+ # and a client asking for one endpoint must not receive a credential
+ # good across the rest — so a token naming only the MCP endpoint is
+ # refused here, and the MCP controller refuses one naming only this.
+ #
+ # @return [Boolean] true when the request is now authenticated
+ def authenticate_admin_oauth_token
+ token = admin_oauth_token
+ return false if token.nil?
+
+ owner = token.resource_owner
+ return false unless owner.is_a?(Spree.admin_user_class)
+
+ @current_api_key = nil
+ @current_user = owner
+ true
+ end
+
+ # @return [Spree::OauthAccessToken, nil]
+ def admin_oauth_token
+ return @admin_oauth_token if defined?(@admin_oauth_token)
+
+ @admin_oauth_token = begin
+ token = Spree::OauthAccessToken.by_token(oauth_bearer_value)
+ token if token&.accessible? && admin_audience_matches?(token)
+ end
+ end
+
+ # Split rather than matched: a regex with `\s+(.+)` backtracks on a
+ # header of many spaces, and this one is attacker-supplied on an
+ # unauthenticated request.
+ #
+ # @return [String, nil]
+ def oauth_bearer_value
+ scheme, value = request.headers['Authorization'].to_s.split(' ', 2)
+ return unless scheme&.casecmp?('Bearer')
+
+ value.to_s.strip.presence
+ end
+
+ # Compared by path, because the origin a client was given varies with
+ # how the installation is reached — a tunnel, a proxy, a custom
+ # domain — while the path it names does not. An unbound token is
+ # refused rather than trusted.
+ def admin_audience_matches?(token)
+ expected = Spree::Api::Oauth.resources[:admin]
+ return false if expected.blank?
+
+ token.resource.to_s.split.any? do |indicator|
+ URI.parse(indicator).path == expected
+ rescue URI::InvalidURIError
+ false
+ end
+ end
+
# Rejects an authenticated JWT admin who has no role on +current_store+.
# API-key principals are already store-bound and skip this check.
def require_store_membership!
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/scoped_authorization.rb b/spree/api/app/controllers/concerns/spree/api/v3/scoped_authorization.rb
index f5e35502d1..abe192f2ef 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/scoped_authorization.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/scoped_authorization.rb
@@ -251,9 +251,19 @@ module Spree
Spree.permissions.expand_keys(token.scopes.to_a)
end
+ # The delegated credential this request arrived on.
+ #
+ # Resolved here rather than overridden per controller: this module is
+ # included after the authentication concerns, so an override in one of
+ # them loses to this definition and the narrowing silently stops
+ # happening — which is how a token scoped to `read_products` once
+ # created one.
+ #
# @return [Spree::OauthAccessToken, nil]
def current_oauth_token
- nil
+ return nil unless respond_to?(:admin_oauth_token, true)
+
+ admin_oauth_token
end
end
end
diff --git a/spree/api/lib/spree/api/engine.rb b/spree/api/lib/spree/api/engine.rb
index d0ea5eaf81..b462e0a4fa 100644
--- a/spree/api/lib/spree/api/engine.rb
+++ b/spree/api/lib/spree/api/engine.rb
@@ -26,6 +26,13 @@ module Spree
# 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!
+
+ # The Admin API as a whole, for an app that works across it rather
+ # than through one endpoint. A token naming this audience is accepted
+ # on every admin controller; one naming a narrower resource — the MCP
+ # endpoint, say — is not, so a token taken from an MCP client cannot
+ # be replayed against the rest of the API.
+ Spree::Api::Oauth.register_resource(:admin, '/api/v3/admin')
end
# Extensions register their permission scopes from config initializers,
diff --git a/spree/api/spec/requests/spree/api/v3/admin/oauth_access_spec.rb b/spree/api/spec/requests/spree/api/v3/admin/oauth_access_spec.rb
new file mode 100644
index 0000000000..ffa1f4e96d
--- /dev/null
+++ b/spree/api/spec/requests/spree/api/v3/admin/oauth_access_spec.rb
@@ -0,0 +1,93 @@
+require 'spec_helper'
+
+# An OAuth token reaches the whole Admin API, not just the MCP endpoint, so an
+# app can do the work a merchant connected it for — fetch the export it just
+# made, read an order, update a product.
+RSpec.describe 'Admin API OAuth access', type: :request do
+ let(:store) { @default_store }
+ let(:admin) { create(:admin_user) }
+ let(:application) do
+ store.oauth_applications.create!(name: "App #{SecureRandom.hex(4)}",
+ redirect_uri: 'https://example.com/callback',
+ confidential: false)
+ end
+
+ def token_for(scopes, resource:)
+ Spree::OauthAccessToken.create!(
+ application: application, resource_owner: admin, scopes: scopes,
+ expires_in: 3600, resource: "http://www.example.com#{resource}"
+ ).plaintext_token
+ end
+
+ def get_with(token, path)
+ get path, headers: { 'Authorization' => "Bearer #{token}" }
+ end
+
+ describe 'a token issued for the Admin API' do
+ let(:token) { token_for('read_products', resource: '/api/v3/admin') }
+
+ it 'is accepted' do
+ get_with(token, '/api/v3/admin/products')
+
+ expect(response).to have_http_status(:ok)
+ end
+
+ # The whole point of a grant: it subtracts from what the approver holds.
+ # This regressed once because the module defining the narrowing hook was
+ # included *after* the one overriding it, so the override was dead code
+ # and a `read_products` token could create a product.
+ it 'cannot reach a resource the merchant did not grant' do
+ get_with(token, '/api/v3/admin/orders')
+
+ expect(response).to have_http_status(:forbidden)
+ end
+
+ it 'cannot write where it was granted only read' do
+ post '/api/v3/admin/products',
+ params: { name: 'Should not exist' },
+ headers: { 'Authorization' => "Bearer #{token}" }
+
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
+
+ # RFC 8707: a token names the resources it may be used against. A client
+ # that asked for one endpoint must not receive a credential good across the
+ # rest of the API.
+ describe 'a token issued for another resource' do
+ it 'is refused' do
+ get_with(token_for('read_products', resource: '/api/v3/admin/mcp'),
+ '/api/v3/admin/products')
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+
+ it 'is refused when it names no resource at all' do
+ token = Spree::OauthAccessToken.create!(
+ application: application, resource_owner: admin,
+ scopes: 'read_products', expires_in: 3600
+ ).plaintext_token
+
+ get_with(token, '/api/v3/admin/products')
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+
+ # The client is registered for one store and consented to on that store, so
+ # the token names the tenancy. Reading the header instead would let a client
+ # name another merchant's store on a grant that never covered it.
+ describe 'the store a token acts on' do
+ it 'comes from the application, not the request header' do
+ other = create(:store)
+ token = token_for('read_products', resource: '/api/v3/admin')
+
+ get '/api/v3/admin/products',
+ headers: { 'Authorization' => "Bearer #{token}",
+ 'X-Spree-Store-Id' => other.prefixed_id }
+
+ expect(response).to have_http_status(:ok)
+ expect(assigns(:current_store) || controller.send(:current_store)).to eq(store)
+ end
+ end
+end