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 consent screen narrowed a grant in the browser, not on the server

Damian Legawiec437cfc2af6ad
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 a430e7d64c..3517a48f9a 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
@@ -40,12 +40,18 @@ module Spree
}
end
- # The merchant may approve less than the client asked for. Doing
- # so narrows the grant, not the request: Doorkeeper records
- # whatever scope reaches it here, so a trimmed list becomes the
- # token's authority.
+ # The merchant may approve less than the client asked for, and
+ # never more than they themselves hold.
+ #
+ # The ceiling is applied here rather than trusted from the
+ # request. Doorkeeper validates a requested scope against the
+ # catalog, not against the person, so a crafted POST naming
+ # `write_settings` would otherwise be recorded verbatim on a
+ # staffer who holds only `read_products` — and a grant is a
+ # standing ceiling, so it would widen on its own the day that
+ # person is promoted.
def create
- render json: { redirect_uri: code_request.authorize.redirect_uri }
+ render json: { redirect_uri: granted_code_request.authorize.redirect_uri }
end
def destroy
@@ -142,6 +148,31 @@ module Spree
def code_request
@code_request ||= ::Doorkeeper::OAuth::CodeRequest.new(@pre_auth, current_actor)
end
+
+ # The same thing, over a pre-authorization whose scope has been
+ # cut to what this person can actually hand over. Rebuilt rather
+ # than mutated, because the scope is read in several places on
+ # the way to the grant.
+ def granted_code_request
+ bounded = ::Doorkeeper::OAuth::PreAuthorization.new(
+ ::Doorkeeper.config,
+ pre_authorization_params.merge(scope: grantable_scopes.join(' ')),
+ current_actor
+ )
+
+ # Validation is what resolves `client`, and the grant is written
+ # from `pre_auth.client.id` — an unvalidated pre-authorization
+ # carries a nil client and fails deep inside the gem.
+ unless bounded.authorizable?
+ return render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:resource_invalid],
+ message: bounded.error_response.body[:error_description].to_s,
+ status: :unprocessable_content
+ )
+ end
+
+ ::Doorkeeper::OAuth::CodeRequest.new(bounded, current_actor)
+ end
end
end
end
diff --git a/spree/api/lib/spree/api/oauth.rb b/spree/api/lib/spree/api/oauth.rb
index 394f4d8c95..250442d9fe 100644
--- a/spree/api/lib/spree/api/oauth.rb
+++ b/spree/api/lib/spree/api/oauth.rb
@@ -116,10 +116,17 @@ module Spree
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) }
+ # Consent is Spree's own, at
+ # `Spree::Api::V3::Admin::Oauth::AuthorizationsController`, and
+ # Doorkeeper's authorization controllers are not mounted — so
+ # this is only reached if a host app mounts them. Failing loudly
+ # beats a NoMethodError inside a before_action, which
+ # `handle_auth_errors :raise` would turn into a 500 on an
+ # authorization endpoint.
+ resource_owner_authenticator do
+ raise "Doorkeeper's own consent screens are not mounted in Spree. " \
+ 'Consent is served by the Admin API at /api/v3/admin/oauth/authorize.'
+ end
# An admin user today, a customer when a storefront client needs
# one — recorded polymorphically so either can own a grant.
@@ -155,7 +162,10 @@ module Spree
# 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
+ # No `fallback: :plain`: every token this server writes is
+ # hashed, so a plaintext lookup could never match and keeping
+ # the path alive only invites a future migration to rely on it.
+ hash_token_secrets
access_token_expires_in 2.hours
# Refresh rotation with replay detection comes from the
# `previous_refresh_token` column the migration adds — Doorkeeper
diff --git a/spree/api/spec/requests/spree/api/v3/admin/oauth/applications_spec.rb b/spree/api/spec/requests/spree/api/v3/admin/oauth/applications_spec.rb
index 02758ae4ed..044bf2f83e 100644
--- a/spree/api/spec/requests/spree/api/v3/admin/oauth/applications_spec.rb
+++ b/spree/api/spec/requests/spree/api/v3/admin/oauth/applications_spec.rb
@@ -85,7 +85,7 @@ RSpec.describe 'Admin connected applications', type: :request do
describe 'revoking' do
it 'stops the application working without deleting its registration' do
- raw = token_for(admin).token
+ raw = token_for(admin).plaintext_token
delete "/api/v3/admin/oauth/applications/#{application.prefixed_id}",
headers: { 'X-Spree-API-Key' => api_key.plaintext_token }
diff --git a/spree/api/spec/requests/spree/api/v3/admin/oauth/authorizations_spec.rb b/spree/api/spec/requests/spree/api/v3/admin/oauth/authorizations_spec.rb
new file mode 100644
index 0000000000..7e35c36455
--- /dev/null
+++ b/spree/api/spec/requests/spree/api/v3/admin/oauth/authorizations_spec.rb
@@ -0,0 +1,76 @@
+require 'spec_helper'
+
+# Consent is where a person hands part of their authority to an agent. The
+# whole arrangement rests on that being a narrowing, so the ceiling is the
+# server's to apply — a client that asks for more, or a browser driven to
+# post more, must not get it.
+RSpec.describe 'Admin OAuth consent', type: :request do
+ let(:store) { @default_store }
+ let(:application) do
+ store.oauth_applications.create!(
+ name: 'Claude', redirect_uri: 'https://example.test/cb', confidential: false
+ )
+ end
+ let(:challenge) { Base64.urlsafe_encode64(Digest::SHA256.digest('v' * 64), padding: false) }
+
+ # Products only — nothing this role could cancel, refund or configure.
+ let(:staffer) do
+ create(:admin_user, :without_admin_role).tap do |user|
+ role = create(:role, name: "products-only-#{SecureRandom.hex(4)}",
+ permissions: %w[read_products], resource: store)
+ create(:role_user, user: user, role: role)
+ end
+ end
+
+ def authorize_params(scope:)
+ {
+ client_id: application.uid, redirect_uri: application.redirect_uri,
+ response_type: 'code', scope: scope,
+ code_challenge: challenge, code_challenge_method: 'S256'
+ }
+ end
+
+ def jwt_for(user)
+ Spree::Api::V3::TestingSupport.generate_jwt(
+ user, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN
+ )
+ end
+
+ def approve(user, scope:)
+ post '/api/v3/admin/oauth/authorize',
+ params: authorize_params(scope: scope),
+ headers: { 'Authorization' => "Bearer #{jwt_for(user)}" }
+ end
+
+ describe 'a scope the approver does not hold' do
+ # A grant is a standing ceiling that outlives the moment it was given, so
+ # recording more than the person held would widen on its own the day they
+ # are promoted — without anyone approving anything.
+ it 'is cut from the grant rather than recorded' do
+ approve(staffer, scope: 'write_orders write_settings read_products')
+
+ expect(response).to have_http_status(:ok)
+ expect(Spree::OauthAccessGrant.order(:id).last.scopes.to_a).to contain_exactly('read_products')
+ end
+
+ it 'is not offered on the consent screen either' do
+ get '/api/v3/admin/oauth/authorize',
+ params: authorize_params(scope: 'write_orders read_products'),
+ headers: { 'Authorization' => "Bearer #{jwt_for(staffer)}" }
+
+ body = JSON.parse(response.body)
+ expect(body['grantable_scopes']).to contain_exactly('read_products')
+ expect(body['grantable_scopes']).not_to include('write_orders')
+ end
+ end
+
+ # The merchant may hand over less than was asked for; that choice has to
+ # survive, or the checkboxes are decoration.
+ it 'honours a narrower selection than the client requested' do
+ admin = create(:admin_user)
+
+ approve(admin, scope: 'read_products')
+
+ expect(Spree::OauthAccessGrant.order(:id).last.scopes.to_a).to contain_exactly('read_products')
+ end
+end
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index 95d77ef775..f468378363 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -597,7 +597,14 @@ module Spree
:verification_value,
:client_id,
:client_secret,
- :refresh_token
+ :refresh_token,
+ # The OAuth token exchange posts these. The code is single-use and
+ # spent the moment it is logged, but the verifier beside it is what
+ # PKCE relies on — logging both hands anyone who can read the log
+ # everything they need to race the exchange.
+ :code,
+ :code_verifier,
+ :code_challenge
]
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 fffc7d4b28..f6f2650eaa 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
@@ -47,7 +47,11 @@ module Spree
# is the assurance `require_store_membership!` gives a JWT.
def authenticate_admin!
owner = oauth_resource_owner
- return false if owner.nil?
+ # A `before_action` halts on a render, not on a falsy return, so
+ # refusing has to render. The grant's owner is an admin in every
+ # path that exists today; a customer-owned token would otherwise
+ # reach the action and die as a confusing 422 further in.
+ return refuse_unauthenticated if owner.nil?
@current_api_key = nil
@current_user = owner
@@ -175,6 +179,10 @@ module Spree
def require_oauth_token!
return if current_oauth_token.present?
+ refuse_unauthenticated
+ end
+
+ def refuse_unauthenticated
response.headers['WWW-Authenticate'] = oauth_challenge
render json: {
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 b845911465..db753aba3d 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
@@ -22,7 +22,7 @@ RSpec.describe 'Admin MCP endpoint', type: :request do
Spree::OauthAccessToken.create!(
application: application, resource_owner: owner,
scopes: Array(scopes).join(' '), expires_in: 2.hours.to_i, resource: audience
- ).token
+ ).plaintext_token
end
def post_rpc(method, params = nil, headers: {}, id: 1)
@@ -186,7 +186,7 @@ RSpec.describe 'Admin MCP endpoint', type: :request do
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)
- ).token
+ ).plaintext_token
body = post_with_token(raw)