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.

Resolve the API store from the credential, not the request host

Damian Legawiec908de44f122d
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId.tsx
index a18d824268..2b454cca7e 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId.tsx
@@ -20,6 +20,13 @@ import { getAvailableUiLocales } from '../../i18n-setup'
const UI_LOCALES = getAvailableUiLocales()
export const Route = createFileRoute('/_authenticated/$storeId')({
+ // The X-Spree-Store-Id header must be set before ANY query under this route
+ // fires — child effects (where React Query starts fetches) run before a
+ // parent effect would, so an effect here is too late and the first fetch
+ // after a store switch would carry the previous store's header.
+ beforeLoad: ({ params }) => {
+ adminClient.setStore(params.storeId)
+ },
component: StoreLayout,
})
@@ -30,11 +37,12 @@ function StoreLayout() {
const { refresh: refreshPermissions } = usePermissions()
const isFirstStore = useRef(true)
+ // Permissions are store-scoped (roles are held per store). The provider
+ // already loaded them for the initial store on login; reload only when the
+ // admin switches to a different store — `storeId` is in the deps for
+ // exactly that re-run, even though the body doesn't read it.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: storeId drives the store-switch re-run
useEffect(() => {
- adminClient.setStore(storeId)
- // Permissions are store-scoped (roles are held per store). The provider
- // already loaded them for the initial store on login; reload only when
- // the admin switches to a different store.
if (isFirstStore.current) {
isFirstStore.current = false
return
diff --git a/packages/dashboard/src/routes/_authenticated/index.tsx b/packages/dashboard/src/routes/_authenticated/index.tsx
index b1e3e0cdb4..79dc7de052 100644
--- a/packages/dashboard/src/routes/_authenticated/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/index.tsx
@@ -1,4 +1,4 @@
-import { adminClient } from '@spree/dashboard-core'
+import { adminClient, useAuth } from '@spree/dashboard-core'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useEffect } from 'react'
@@ -8,21 +8,27 @@ export const Route = createFileRoute('/_authenticated/')({
function IndexRedirect() {
const navigate = useNavigate()
+ const { user } = useAuth()
+ // The authenticated user's stores list is the source of the initial store —
+ // no request needed. The header-less `store.get()` fallback covers sessions
+ // whose cached user predates the stores field; it resolves the default
+ // store server-side.
useEffect(() => {
+ const firstStoreId = user?.stores?.[0]?.id
+ if (firstStoreId) {
+ navigate({ to: '/$storeId', params: { storeId: firstStoreId }, replace: true })
+ return
+ }
+
let cancelled = false
- adminClient.store
- .get()
- .then((store) => {
- if (!cancelled) navigate({ to: '/$storeId', params: { storeId: store.id }, replace: true })
- })
- .catch(() => {
- if (!cancelled) navigate({ to: '/$storeId', params: { storeId: 'default' }, replace: true })
- })
+ adminClient.store.get().then((store) => {
+ if (!cancelled) navigate({ to: '/$storeId', params: { storeId: store.id }, replace: true })
+ })
return () => {
cancelled = true
}
- }, [navigate])
+ }, [navigate, user])
return null
}
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
new file mode 100644
index 0000000000..cbcea0a953
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/store_context.rb
@@ -0,0 +1,83 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # Admin API store context (docs/plans/6.0-store-context-and-first-run-setup.md):
+ # a secret key selects its bound store; JWT staff sessions select via
+ # the +X-Spree-Store-Id+ header (the admin SDK sends it on every
+ # request) and are membership-checked against the store resolved here
+ # by AdminAuthentication#require_store_membership!. The request host
+ # is never consulted.
+ #
+ # Included in both Admin API branch anchors (Admin::BaseController and
+ # Admin::ResourceController) alongside AdminAuthentication.
+ module StoreContext
+ extend ActiveSupport::Concern
+
+ STORE_HEADER = 'X-Spree-Store-Id'.freeze
+
+ included do
+ # Prepended so Spree::Current.store reflects the requested store
+ # before any other callback (locale/currency fallbacks, resource
+ # lookups) reads it. The store-presence guard 404s an unknown
+ # header ID right after this runs.
+ prepend_before_action :set_current_store_context
+ end
+
+ # Resolution order: the secret key's bound store, then the header,
+ # then the default store — deprecated for JWT requests; the header
+ # becomes required in 6.1.
+ #
+ # @return [Spree::Store, nil]
+ def current_store
+ return @current_store if defined?(@current_store)
+
+ @current_store = resolve_admin_store
+ end
+
+ private
+
+ def set_current_store_context
+ if secret_api_key && store_id_header && secret_api_key.store&.prefixed_id != store_id_header
+ render_error(
+ code: ErrorHandler::ERROR_CODES[:access_denied],
+ message: Spree.t('api.errors.store_mismatch', default: 'The requested store does not match the store this API key belongs to.'),
+ status: :forbidden
+ )
+ return
+ end
+
+ Spree::Current.store = current_store if current_store
+ end
+
+ def resolve_admin_store
+ return secret_api_key.store if secret_api_key
+
+ if store_id_header
+ Spree::Store.find_by_prefix_id(store_id_header)
+ else
+ # Only warn for authenticated staff traffic — credential-less
+ # requests (login, refresh, invitation acceptance) are
+ # store-agnostic and legitimately send no header.
+ warn_missing_store_header if request.authorization.present?
+ Spree::Store.default
+ end
+ end
+
+ def store_id_header
+ request.headers[STORE_HEADER].presence
+ end
+
+ def warn_missing_store_header
+ return unless defined?(Spree::Deprecation)
+
+ Spree::Deprecation.warn(
+ "Admin API v3 requests without an #{STORE_HEADER} header fall back to the default store. " \
+ 'The header becomes required for JWT requests in Spree 6.1.'
+ )
+ end
+ end
+ end
+ end
+ end
+end
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 72fff191fd..85399d5f27 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
@@ -30,9 +30,9 @@ module Spree
# Secret keys are checked first (server-to-server integrations),
# then JWT tokens (admin SPA sessions).
def authenticate_admin!
- # Try secret API key first
- @current_api_key = Spree::ApiKey.find_by_secret_token(extract_api_key)
- @current_api_key = nil if @current_api_key && @current_api_key.store_id != current_store.id
+ # Try secret API key first — the key selects the request's store
+ # (Admin::StoreContext), so there is no store check to make here.
+ @current_api_key = secret_api_key
if @current_api_key
touch_api_key_if_needed(@current_api_key)
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/api_key_authentication.rb b/spree/api/app/controllers/concerns/spree/api/v3/api_key_authentication.rb
index 414a0eabc1..d472770001 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/api_key_authentication.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/api_key_authentication.rb
@@ -12,11 +12,13 @@ module Spree
end
# Authenticates a publishable API key (pk_*) for Store API requests.
- # Looks up the key by plaintext token scoped to the current store.
+ # The key SELECTS the store — lookup is global by token and
+ # +current_store+ derives from the key (see KeyStoreContext); the key
+ # is never validated against a host-resolved store.
#
# @return [Boolean] true if authentication succeeded, false otherwise
def authenticate_api_key!
- @current_api_key = current_store.api_keys.active.publishable.find_by(token: extract_api_key)
+ @current_api_key = publishable_api_key
unless @current_api_key
render_error(
@@ -33,12 +35,12 @@ module Spree
# Authenticates a secret API key (sk_*) for Admin API requests.
# Computes the HMAC-SHA256 digest of the provided token and looks up
- # by +token_digest+, then verifies it belongs to the current store.
+ # by +token_digest+. The key is store-bound and selects the request's
+ # store (see Admin::StoreContext).
#
# @return [Boolean] true if authentication succeeded, false otherwise
def authenticate_secret_key!
- @current_api_key = Spree::ApiKey.find_by_secret_token(extract_api_key)
- @current_api_key = nil if @current_api_key && @current_api_key.store_id != current_store.id
+ @current_api_key = secret_api_key
unless @current_api_key
render_error(
@@ -55,6 +57,28 @@ module Spree
private
+ # Memoized global publishable-key lookup. Deliberately NOT scoped to
+ # +current_store+ — the store derives from the key, not the other way
+ # around. Memoizes misses too, so pre-authentication callers (store
+ # resolution) don't re-query.
+ #
+ # @return [Spree::ApiKey, nil]
+ def publishable_api_key
+ return @publishable_api_key if defined?(@publishable_api_key)
+
+ @publishable_api_key =
+ extract_api_key ? Spree::ApiKey.active.publishable.find_by(token: extract_api_key) : nil
+ end
+
+ # Memoized global secret-key lookup (digest-based, active keys only).
+ #
+ # @return [Spree::ApiKey, nil]
+ def secret_api_key
+ return @secret_api_key if defined?(@secret_api_key)
+
+ @secret_api_key = Spree::ApiKey.find_by_secret_token(extract_api_key)
+ end
+
# Marks the API key as used at most once per hour
# to avoid unnecessary DB writes and job queue pressure on every request.
# This follows the same approach as GitHub's personal access tokens.
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/key_store_context.rb b/spree/api/app/controllers/concerns/spree/api/v3/key_store_context.rb
new file mode 100644
index 0000000000..70a812b2d7
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/key_store_context.rb
@@ -0,0 +1,31 @@
+module Spree
+ module Api
+ module V3
+ # Store API store context: the publishable key selects the store (the
+ # key belongs to exactly one store) — the request host is never
+ # consulted. See docs/plans/6.0-store-context-and-first-run-setup.md.
+ #
+ # Included in both Store API branch anchors (Store::BaseController and
+ # Store::ResourceController) alongside ApiKeyAuthentication, whose
+ # memoized +publishable_api_key+ lookup this reads — pre-authentication
+ # callbacks (channel resolution, locale fallbacks) resolve the same key
+ # row authentication later verifies.
+ module KeyStoreContext
+ extend ActiveSupport::Concern
+
+ included do
+ # An invalid or missing key must render 401 from
+ # +authenticate_api_key!+ — without this skip the store-presence
+ # guard would 404 first on the ResourceController branch, where it
+ # runs ahead of authentication.
+ skip_before_action :raise_record_not_found_if_store_is_not_found
+ end
+
+ # @return [Spree::Store, nil]
+ def current_store
+ @current_store ||= publishable_api_key&.store
+ end
+ end
+ end
+ end
+end
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 d8cf2e7039..42cd0cf7aa 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
@@ -167,16 +167,15 @@ module Spree
# 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.
+ # check does not depend on `authenticate_admin!` having already run. Uses
+ # the same memoized lookup as AdminAuthentication (the key selects the
+ # request's store — see Admin::StoreContext), 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
+ @current_api_key = secret_api_key
end
# The resource name used in scope strings (`read_<name>` / `write_<name>`).
diff --git a/spree/api/app/controllers/spree/api/v3/admin/base_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/base_controller.rb
index 63ec8e4b5b..3eafc286a8 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/base_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/base_controller.rb
@@ -3,6 +3,7 @@ module Spree
module V3
module Admin
class BaseController < Spree::Api::V3::BaseController
+ include Spree::Api::V3::Admin::StoreContext
include Spree::Api::V3::AdminAuthentication
# Must be registered before ScopedAuthorization so authenticate_admin!
diff --git a/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb
index 2e9f98ab8c..f3a21b1ca2 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb
@@ -6,6 +6,7 @@ module Spree
# inheritance branches (V3::BaseController vs V3::ResourceController);
# any concern added here MUST also be added to Admin::BaseController.
class ResourceController < Spree::Api::V3::ResourceController
+ include Spree::Api::V3::Admin::StoreContext
include Spree::Api::V3::AdminAuthentication
include Spree::Api::V3::ScopedAuthorization
diff --git a/spree/api/app/controllers/spree/api/v3/store/base_controller.rb b/spree/api/app/controllers/spree/api/v3/store/base_controller.rb
index 86f034ddb4..451134a352 100644
--- a/spree/api/app/controllers/spree/api/v3/store/base_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/base_controller.rb
@@ -3,6 +3,9 @@ module Spree
module V3
module Store
class BaseController < Spree::Api::V3::BaseController
+ # The publishable key selects the store — must come before
+ # ChannelResolution, whose store-context callback reads it.
+ include Spree::Api::V3::KeyStoreContext
# Channel resolution is a Store API concern — admin endpoints return
# data across all channels and filter via Ransack instead. Including
# this here keeps the +X-Spree-Channel+ header from accidentally
diff --git a/spree/api/app/controllers/spree/api/v3/store/data_feeds_controller.rb b/spree/api/app/controllers/spree/api/v3/store/data_feeds_controller.rb
index 16edcc16f7..f0dac183ad 100644
--- a/spree/api/app/controllers/spree/api/v3/store/data_feeds_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/data_feeds_controller.rb
@@ -13,6 +13,17 @@ module Spree
render xml: presenter.call
end
+
+ protected
+
+ # Feed URLs carry only a slug (unique per store, not globally), and
+ # no credential accompanies the request — so feeds are served for
+ # the default store. This matches the pre-6.0 behavior in practice:
+ # the old finder resolved every host to the default store too. A
+ # store-carrying feed URL shape is future work.
+ def current_store
+ @current_store ||= Spree::Store.default
+ end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/store/digitals_controller.rb b/spree/api/app/controllers/spree/api/v3/store/digitals_controller.rb
index 4a8671633e..7fbf7a7e30 100644
--- a/spree/api/app/controllers/spree/api/v3/store/digitals_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/digitals_controller.rb
@@ -24,12 +24,21 @@ module Spree
private
+ # The download token is the request's credential and selects the
+ # store (tokens are globally unique via has_secure_token) — no
+ # publishable key accompanies emailed download links, so there is
+ # no other credential to derive store context from.
def set_resource
@resource = digital_link_scope.find_by!(token: params[:token])
+ Spree::Current.store = current_store
end
def digital_link_scope
- current_store.digital_links
+ Spree::DigitalLink
+ end
+
+ def current_store
+ @current_store ||= @resource&.order&.store || super
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/store/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/store/resource_controller.rb
index f2e5b8daa0..4a551cb3c9 100644
--- a/spree/api/app/controllers/spree/api/v3/store/resource_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/resource_controller.rb
@@ -6,6 +6,7 @@ module Spree
# inheritance branches (V3::BaseController vs V3::ResourceController);
# any concern added here MUST also be added to Store::BaseController.
class ResourceController < Spree::Api::V3::ResourceController
+ include Spree::Api::V3::KeyStoreContext
include Spree::Api::V3::ChannelResolution
include Spree::Api::V3::StorefrontGating
include Spree::Api::V3::StorefrontAccess
diff --git a/spree/api/config/locales/en.yml b/spree/api/config/locales/en.yml
index 0cded76343..c808fcfd7e 100644
--- a/spree/api/config/locales/en.yml
+++ b/spree/api/config/locales/en.yml
@@ -14,6 +14,7 @@ en:
channel_inactive: The channel this API key is bound to is not active.
channel_mismatch: The requested channel does not match the channel this API key is bound to.
guest_checkout_not_allowed: You must be signed in to complete checkout.
+ store_mismatch: The requested store does not match the store this API key belongs to.
storefront_login_required: Authentication required to access this store.
negative_quantity: quantity is negative
newsletter_unsubscribe_token_invalid: Newsletter unsubscribe token is invalid or has expired.
diff --git a/spree/api/lib/spree/api/testing_support/v3/base.rb b/spree/api/lib/spree/api/testing_support/v3/base.rb
index 59b65a1d37..4bb4781ed6 100644
--- a/spree/api/lib/spree/api/testing_support/v3/base.rb
+++ b/spree/api/lib/spree/api/testing_support/v3/base.rb
@@ -34,7 +34,13 @@ shared_context 'API v3 Store' do
let(:bearer_headers) { api_key_headers.merge('Authorization' => "Bearer #{jwt_token}") }
before do
+ # Stubbed on both branch anchors, not just the shared base — the anchors
+ # define their own `current_store` (KeyStoreContext), which would shadow
+ # a stub installed on the base class. Specs stub methods on this exact
+ # `store` instance, so resolution must return it by identity.
allow_any_instance_of(Spree::Api::V3::BaseController).to receive(:current_store).and_return(store)
+ allow_any_instance_of(Spree::Api::V3::Store::BaseController).to receive(:current_store).and_return(store)
+ allow_any_instance_of(Spree::Api::V3::Store::ResourceController).to receive(:current_store).and_return(store)
end
end
@@ -60,7 +66,11 @@ shared_context 'API v3 Admin' do
let(:bearer_headers) { api_key_headers.merge('Authorization' => "Bearer #{admin_jwt_token}") }
before do
+ # See the 'API v3 Store' context — the admin anchors define their own
+ # `current_store` (Admin::StoreContext), which shadows a base-class stub.
allow_any_instance_of(Spree::Api::V3::BaseController).to receive(:current_store).and_return(store)
+ allow_any_instance_of(Spree::Api::V3::Admin::BaseController).to receive(:current_store).and_return(store)
+ allow_any_instance_of(Spree::Api::V3::Admin::ResourceController).to receive(:current_store).and_return(store)
end
end
diff --git a/spree/api/spec/controllers/concerns/spree/api/v3/admin/store_context_spec.rb b/spree/api/spec/controllers/concerns/spree/api/v3/admin/store_context_spec.rb
new file mode 100644
index 0000000000..c911a78c3b
--- /dev/null
+++ b/spree/api/spec/controllers/concerns/spree/api/v3/admin/store_context_spec.rb
@@ -0,0 +1,105 @@
+require 'spec_helper'
+
+# Covers Admin::StoreContext using TaxCategoriesController as a representative
+# Admin::ResourceController. Deliberately does NOT use the 'API v3 Admin'
+# shared context — that stubs +current_store+, which is the mechanic under
+# test here.
+RSpec.describe Spree::Api::V3::Admin::TaxCategoriesController, type: :controller do
+ render_views
+
+ let(:store) { @default_store }
+ let(:other_store) { create(:store) }
+
+ let(:admin_user) { create(:admin_user) } # membership on the default store
+ let(:admin_jwt) do
+ Spree::Api::V3::TestingSupport.generate_jwt(
+ admin_user,
+ audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN
+ )
+ end
+
+ describe 'JWT sessions' do
+ before { request.headers['Authorization'] = "Bearer #{admin_jwt}" }
+
+ context 'with X-Spree-Store-Id naming a store the admin has a role on' do
+ before do
+ create(:role_user, user: admin_user, role: Spree::Role.default_admin_role, resource: other_store)
+ request.headers['X-Spree-Store-Id'] = other_store.prefixed_id
+ end
+
+ it 'resolves the requested store' do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(controller.send(:current_store)).to eq(other_store)
+ end
+ end
+
+ context 'with X-Spree-Store-Id naming a store the admin has NO role on' do
+ before { request.headers['X-Spree-Store-Id'] = other_store.prefixed_id }
+
+ it 'returns 403' do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
+
+ context 'with an unknown X-Spree-Store-Id' do
+ before { request.headers['X-Spree-Store-Id'] = 'store_doesnotexist' }
+
+ it 'returns 404' do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ context 'without the header' do
+ it 'falls back to the default store with a deprecation warning' do
+ expect(Spree::Deprecation).to receive(:warn).with(/X-Spree-Store-Id/)
+
+ get :index, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(controller.send(:current_store)).to eq(store)
+ end
+ end
+ end
+
+ describe 'secret API keys' do
+ let(:foreign_key) { create(:api_key, :secret, store: other_store) }
+
+ before { request.headers['X-Spree-Api-Key'] = foreign_key.plaintext_token }
+
+ context 'without a header' do
+ it "resolves the key's bound store" do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(controller.send(:current_store)).to eq(other_store)
+ end
+ end
+
+ context 'with a matching X-Spree-Store-Id' do
+ before { request.headers['X-Spree-Store-Id'] = other_store.prefixed_id }
+
+ it 'authenticates normally' do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(controller.send(:current_store)).to eq(other_store)
+ end
+ end
+
+ context 'with a conflicting X-Spree-Store-Id' do
+ before { request.headers['X-Spree-Store-Id'] = store.prefixed_id }
+
+ it 'returns 403' do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/concerns/spree/api/v3/admin_authentication_spec.rb b/spree/api/spec/controllers/concerns/spree/api/v3/admin_authentication_spec.rb
index 0b01fb6da9..4f588e547d 100644
--- a/spree/api/spec/controllers/concerns/spree/api/v3/admin_authentication_spec.rb
+++ b/spree/api/spec/controllers/concerns/spree/api/v3/admin_authentication_spec.rb
@@ -46,10 +46,11 @@ RSpec.describe Spree::Api::V3::Admin::TaxCategoriesController, type: :controller
before { request.headers['X-Spree-Api-Key'] = foreign_key.plaintext_token }
- it 'returns 401 (cross-store keys are rejected)' do
+ it 'authenticates — the key selects its own store (see Admin::StoreContext)' do
get :index, as: :json
- expect(response).to have_http_status(:unauthorized)
+ expect(response).to have_http_status(:ok)
+ expect(controller.send(:current_api_key)).to eq(foreign_key)
end
end
end
diff --git a/spree/api/spec/controllers/concerns/spree/api/v3/key_store_context_spec.rb b/spree/api/spec/controllers/concerns/spree/api/v3/key_store_context_spec.rb
new file mode 100644
index 0000000000..2435e65f14
--- /dev/null
+++ b/spree/api/spec/controllers/concerns/spree/api/v3/key_store_context_spec.rb
@@ -0,0 +1,53 @@
+require 'spec_helper'
+
+# Covers KeyStoreContext using CountriesController as a representative Store
+# API controller. Deliberately does NOT use the 'API v3 Store' shared context
+# — that stubs +current_store+, which is the mechanic under test here.
+RSpec.describe Spree::Api::V3::Store::CountriesController, type: :controller do
+ render_views
+
+ let(:other_store) { create(:store) }
+
+ context 'with a publishable key of a non-default store' do
+ let(:api_key) { create(:api_key, :publishable, store: other_store) }
+
+ before { request.headers['X-Spree-Api-Key'] = api_key.token }
+
+ it "resolves the key's store, never the host or the default store" do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(controller.send(:current_store)).to eq(other_store)
+ end
+ end
+
+ context 'without a key' do
+ it 'returns 401, not 404 from the store-presence guard' do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+
+ context 'with an unknown key' do
+ before { request.headers['X-Spree-Api-Key'] = 'pk_does_not_exist' }
+
+ it 'returns 401' do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+
+ context 'with a revoked key' do
+ let(:api_key) { create(:api_key, :publishable, store: other_store, revoked_at: 1.day.ago) }
+
+ before { request.headers['X-Spree-Api-Key'] = api_key.token }
+
+ it 'returns 401' do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/base_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/base_controller_spec.rb
index 526c4e2399..3878e86d96 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/base_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/base_controller_spec.rb
@@ -82,10 +82,10 @@ RSpec.describe Spree::Api::V3::Admin::BaseController, type: :controller do
before { request.headers['X-Spree-Api-Key'] = other_secret_key.plaintext_token }
- it 'returns 401 unauthorized' do
+ it 'authenticates — the key selects its own store (see Admin::StoreContext)' do
get :index
- expect(response).to have_http_status(:unauthorized)
+ expect(response).to have_http_status(:ok)
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/me_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/me_controller_spec.rb
index d23dd28706..69bccda580 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/me_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/me_controller_spec.rb
@@ -105,7 +105,7 @@ RSpec.describe Spree::Api::V3::Admin::MeController, type: :controller do
end
it 'returns the other store keys under that store context' do
- allow_any_instance_of(Spree::Api::V3::BaseController).to receive(:current_store).and_return(store_b)
+ allow_any_instance_of(Spree::Api::V3::Admin::BaseController).to receive(:current_store).and_return(store_b)
subject
expect(json_response['permission_keys']).to eq(%w[read_products])
diff --git a/spree/api/spec/controllers/spree/api/v3/store/digitals_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/digitals_controller_spec.rb
index 6cea174ae7..98ec481c34 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/digitals_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/digitals_controller_spec.rb
@@ -74,10 +74,13 @@ RSpec.describe Spree::Api::V3::Store::DigitalsController, type: :controller do
let(:other_digital) { create(:digital, variant: other_line_item.variant) }
let(:other_digital_link) { create(:digital_link, digital: other_digital, line_item: other_line_item) }
- it 'returns not found' do
+ # The globally unique token is the credential and selects the store —
+ # download links arrive by email with no API key, so there is no other
+ # credential to scope by (see KeyStoreContext).
+ it 'downloads the file' do
get :show, params: { token: other_digital_link.token }
- expect(response).to have_http_status(:not_found)
+ expect(response).to have_http_status(:ok)
end
end