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.

Make API-key scope guard fail closed (F3)

Damian Legawiec36abdce80fcc
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 ce59c7530d..dfb2075b3e 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
@@ -56,10 +56,34 @@ module Spree
private
def authorize_api_key_scope!
- return unless current_api_key
+ # Endpoints explicitly exempt from the scope mechanism (auth, me, public
+ # invitation acceptance, per-type-filtered exports, etc.) opt out first,
+ # before any key resolution or enforcement.
return if self.class._scope_check_skipped
return if self.class._scope_check_skipped_actions&.include?(action_name)
+ # Fail CLOSED, not open. A nil `current_api_key` legitimately means a
+ # non-secret-key request (JWT admin / publishable) authorized by other
+ # means, which correctly skips scope checks. But it ALSO happens when
+ # this guard runs before authentication resolved the key: a bare
+ # `return unless current_api_key` would then skip scope enforcement for
+ # an attacker-supplied secret key. So resolve the secret key in place
+ # here — never rely on before_action ordering. Only truly non-secret-key
+ # requests (nothing to resolve) are waved through.
+ resolve_current_api_key_for_scope_check!
+
+ unless current_api_key
+ return unless secret_key_request?
+
+ # A secret-key token was presented but did not resolve to a live key
+ # for this store — reject rather than silently skip the scope check.
+ return render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:invalid_token],
+ message: 'Valid secret API key required',
+ status: :unauthorized
+ )
+ end
+
resource = scoped_resource_name
# Fail closed: a controller authenticated by API key MUST declare
# either `scoped_resource :name`, override `scoped_resource_name`,
@@ -77,6 +101,29 @@ module Spree
)
end
+ # True when the request presents a secret API key token (`sk_` prefix),
+ # regardless of whether authentication has resolved it into
+ # `current_api_key` yet. Used to keep the scope guard fail-closed even if
+ # it runs before the API key is loaded: a secret-key request whose key is
+ # still nil must be denied, never waved through.
+ def secret_key_request?
+ extract_api_key.to_s.start_with?(Spree::ApiKey::PREFIXES['secret'])
+ end
+
+ # Resolves the request's secret API key into `@current_api_key` if a
+ # secret-key token is present and it hasn't been resolved yet, so the scope
+ # check does not depend on `authenticate_admin!` having already run. Mirrors
+ # the secret-key resolution + store binding in AdminAuthentication, and is
+ # idempotent: when the key is already loaded (guard runs after auth) it does
+ # nothing.
+ def resolve_current_api_key_for_scope_check!
+ return if @current_api_key
+ return unless secret_key_request?
+
+ key = Spree::ApiKey.find_by_secret_token(extract_api_key)
+ @current_api_key = key if key && key.store_id == current_store.id
+ end
+
# The resource name used in scope strings (`read_<name>` / `write_<name>`).
# Defaults to the class-level `scoped_resource :name` declaration.
# Override in controllers that resolve scope at request time (e.g. the
diff --git a/spree/api/spec/controllers/spree/api/v3/scoped_authorization_spec.rb b/spree/api/spec/controllers/spree/api/v3/scoped_authorization_spec.rb
index 33f5dad32b..64021b2a03 100644
--- a/spree/api/spec/controllers/spree/api/v3/scoped_authorization_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/scoped_authorization_spec.rb
@@ -132,3 +132,53 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
end
end
end
+
+# Regression for the Admin::BaseController ordering bypass: on this branch the
+# `authorize_api_key_scope!` before_action runs BEFORE `authenticate_admin!`, so
+# `current_api_key` is nil at guard time. The guard must resolve the secret key
+# itself and fail CLOSED — never wave the request through — while still letting
+# JWT-authenticated admins (authorized by CanCanCan, no secret key) pass.
+RSpec.describe Spree::Api::V3::Admin::DashboardController, type: :controller do
+ render_views
+ include_context 'API v3 Admin'
+
+ describe 'secret-key request reaching the guard before the key is resolved' do
+ let(:secret_key) { create(:api_key, :secret, store: store, created_by: admin_user, scopes: scopes) }
+
+ before { request.headers['X-Spree-Api-Key'] = secret_key.plaintext_token }
+
+ context 'with the required scope' do
+ let(:scopes) { ['read_dashboard'] }
+
+ it 'enforces the scope and allows the read' do
+ get :analytics, as: :json
+ expect(response).to have_http_status(:ok)
+ end
+ end
+
+ context 'without the required scope' do
+ let(:scopes) { ['read_orders'] }
+
+ it 'denies rather than silently skipping the scope check' do
+ get :analytics, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ body = JSON.parse(response.body)
+ expect(body['error']['code']).to eq('access_denied')
+ expect(body['error']['details']['required_scope']).to eq('read_dashboard')
+ end
+ end
+ end
+
+ describe 'JWT-authenticated admin (no secret key)' do
+ before do
+ request.headers['X-Spree-Api-Key'] = nil
+ request.headers['Authorization'] = "Bearer #{admin_jwt_token}"
+ end
+
+ it 'passes the scope guard (CanCanCan applies instead)' do
+ get :analytics, as: :json
+ expect(response).to have_http_status(:ok)
+ end
+ end
+end