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 scope based API key authentication for Admin API

Damian Legawiec5a08e6268377
diff --git a/CLAUDE.md b/CLAUDE.md
index f858015f40..e8af2c1337 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -34,6 +34,7 @@ Current plans:
- `5.5-6.0-order-cancellation-and-approval.md` — First-class `OrderCancellation` + `OrderApproval` models, capture reasons/restock/refund decisions, polymorphic actor; 6.0 drops denormalized columns
+- `5.5-admin-api-key-scopes.md` — Shopify-style `read_*`/`write_*` scopes on `Spree::ApiKey` for Admin API authorization (apps), independent of CanCanCan (which stays for JWT users)
- `5.4-disjunctive-option-faceting.md` — Per-option-type filter params with disjunctive facet counts (OR within option type, AND across)
- `5.4-option-type-enhancements.md` — Add `kind` (dropdown/color_swatch/buttons) to OptionType, `color_code` + `image` to OptionValue for swatch support
- `5.4-6.0-custom-fields-rename.md` — Rename Metafields → Custom Fields (5.4 API bridge + 6.0 model rename)
diff --git a/docs/plans/5.5-admin-api-key-scopes.md b/docs/plans/5.5-admin-api-key-scopes.md
new file mode 100644
index 0000000000..d962edc5bf
--- /dev/null
+++ b/docs/plans/5.5-admin-api-key-scopes.md
@@ -0,0 +1,242 @@
+# Admin API Key Scopes
+
+**Status:** Design Finalized
+**Target:** Spree 5.5
+**Depends on:** `6.0-admin-api.md`
+**Author:** Damian
+**Last updated:** 2026-04-29
+
+## Summary
+
+Today the Admin API authenticates via either a secret API key or an admin JWT, and uses CanCanCan abilities for authorization on both. CanCanCan resolves abilities from a `current_user` — it works for JWT-authenticated admin users but is a poor fit for API keys, which represent integrations / apps, not users.
+
+This plan introduces **scopes** on `Spree::ApiKey` so secret keys can carry their own permissions independent of any user, mirroring how Shopify access scopes and Saleor app permissions work. JWT admin users continue to use CanCanCan unchanged.
+
+## Key Decisions (do not deviate without discussion)
+
+- **Scope vocabulary is `read_<resource>` / `write_<resource>` per top-level admin resource** (~15 scopes). `write_*` implies `read_*`.
+- **Convenience aliases `read_all` and `write_all`** for full read or full read+write. Aliases expand at check time, not at storage time, so admins can re-toggle later without rewriting stored values.
+- **Scopes apply to API keys only.** JWT admin users keep CanCanCan-based authorization (they have `Spree::Role`s; that surface is unchanged).
+- **No backward compatibility for legacy admin keys** — Admin API hasn't shipped to production yet; all secret keys created from this point require explicit scopes.
+- **Resource granularity, not action granularity.** No separate `cancel_orders`, `approve_orders`, etc. — `write_orders` covers all writes including state transitions and member actions.
+- **Action mapping:** `index`/`show` → `read_<resource>`, every other action (including custom member actions like `cancel`/`approve`) → `write_<resource>`.
+- **Scope is declared per controller via `scoped_resource :name`**, not auto-derived from controller name. Lets nested controllers map to a different scope than their parent (e.g., `Orders::PaymentsController` → `payments`).
+
+## Design Details
+
+### Storage
+
+```ruby
+class AddScopesToSpreeApiKeys < ActiveRecord::Migration[7.2]
+ def change
+ add_column :spree_api_keys, :scopes, :text, default: '[]', null: false
+ end
+end
+```
+
+Cross-DB compatible (text column with JSON-serialized array). Default `[]` so a key with no explicit scopes can do nothing on the Admin API — fail closed.
+
+```ruby
+class Spree::ApiKey < Spree.base_class
+ serialize :scopes, type: Array, coder: JSON
+
+ validates :scopes, presence: true, if: :secret?
+ validate :scopes_must_be_known, if: :secret?
+
+ KNOWN_SCOPES = %w[
+ read_orders write_orders
+ read_products write_products
+ read_customers write_customers
+ read_payments write_payments
+ read_fulfillments write_fulfillments
+ read_refunds write_refunds
+ read_gift_cards write_gift_cards
+ read_store_credits write_store_credits
+ read_categories write_categories
+ read_settings write_settings
+ read_webhooks write_webhooks
+ read_dashboard
+ read_all write_all
+ ].freeze
+
+ def has_scope?(scope)
+ return true if scopes.include?(scope)
+ return true if scope.start_with?('read_') && scopes.include?("write_#{scope.delete_prefix('read_')}")
+ return true if scopes.include?('write_all')
+ return true if scope.start_with?('read_') && scopes.include?('read_all')
+ false
+ end
+
+ private
+
+ def scopes_must_be_known
+ invalid = scopes - KNOWN_SCOPES
+ errors.add(:scopes, "contains unknown scopes: #{invalid.join(', ')}") if invalid.any?
+ end
+end
+```
+
+### Scope vocabulary
+
+| Scope | Endpoints |
+|---|---|
+| `read_orders` / `write_orders` | `/orders/*`, `/orders/:id/items` (line items roll into orders) |
+| `read_products` / `write_products` | `/products/*`, `/variants/*`, `/option_types/*`, `/prices/*`, `/media/*` |
+| `read_customers` / `write_customers` | `/customers/*`, `/customers/:id/addresses`, `/customers/:id/credit_cards` (PII rides along) |
+| `read_payments` / `write_payments` | `/orders/:id/payments`, `/payments/*` |
+| `read_fulfillments` / `write_fulfillments` | `/orders/:id/fulfillments` |
+| `read_refunds` / `write_refunds` | `/orders/:id/refunds` |
+| `read_gift_cards` / `write_gift_cards` | `/orders/:id/gift_cards`, future `/gift_cards/*` |
+| `read_store_credits` / `write_store_credits` | `/customers/:id/store_credits`, `/orders/:id/store_credits` |
+| `read_categories` / `write_categories` | `/categories/*` |
+| `read_settings` / `write_settings` | `/payment_methods`, `/markets`, `/countries`, `/tax_categories`, `/stores` |
+| `read_webhooks` / `write_webhooks` | future `/webhooks/*` |
+| `read_dashboard` | `/dashboard/*` (analytics; no write counterpart) |
+| `read_all` | every `read_*` scope |
+| `write_all` | every `read_*` and `write_*` scope (full admin) |
+
+**Heuristic for splitting:** add a separate scope when a partner integration realistically wants one without the other. "Analytics tool reads orders but not customers" → split. "Order management writes line items" → no split.
+
+**Endpoints intentionally not scope-gated:**
+- `/auth/*` — login/refresh; pre-auth
+- `/me` — returns the calling user's permissions; no scope needed
+- `/tags` — read-only enum, low-risk autocomplete
+- `/direct_uploads` — pre-signed URL helper (already auth-gated; storage is the scope boundary)
+
+### Enforcement
+
+A `ScopedAuthorization` concern is included in `Spree::Api::V3::Admin::BaseController`:
+
+```ruby
+module Spree::Api::V3::ScopedAuthorization
+ extend ActiveSupport::Concern
+
+ class_methods do
+ def scoped_resource(name)
+ class_attribute :_scoped_resource, instance_accessor: false
+ self._scoped_resource = name.to_sym
+ end
+ end
+
+ included do
+ before_action :authorize_api_key_scope!
+ end
+
+ private
+
+ def authorize_api_key_scope!
+ return unless @current_api_key # JWT user → CanCanCan handles it
+ return unless self.class.respond_to?(:_scoped_resource) && self.class._scoped_resource
+
+ required = "#{action_kind}_#{self.class._scoped_resource}"
+ return if @current_api_key.has_scope?(required)
+
+ raise CanCan::AccessDenied.new("API key lacks scope: #{required}")
+ end
+
+ def action_kind
+ %w[index show].include?(action_name) ? 'read' : 'write'
+ end
+end
+```
+
+Each admin controller declares its scope:
+
+```ruby
+class Spree::Api::V3::Admin::OrdersController < ResourceController
+ scoped_resource :orders
+end
+```
+
+For nested controllers under `/orders/:id/payments`, declare separately:
+
+```ruby
+class Spree::Api::V3::Admin::Orders::PaymentsController < ResourceController
+ scoped_resource :payments
+end
+```
+
+### Interaction with CanCanCan
+
+- **API key requests**: `authorize_api_key_scope!` runs first. If the API key has the scope, the request proceeds. CanCanCan still runs but its abilities resolve from the API key's `created_by` user (so per-record rules — store scoping, soft-deleted resources — still apply). When `created_by` is nil, ability is a no-op (everything allowed) since the scope check has already gated the resource.
+- **JWT user requests**: scope check is a no-op (`@current_api_key` is nil); CanCanCan runs unchanged.
+
+### `current_ability` for API keys
+
+```ruby
+def current_ability
+ @current_ability ||= Spree::Ability.new(ability_user, ability_options)
+end
+
+def ability_user
+ return current_user if current_user
+ return @current_api_key&.created_by if @current_api_key&.created_by
+ nil
+end
+```
+
+`Spree::Ability.new(nil, store: store)` returns a guest ability — which is fine because the scope check has already authorized the action at the resource level. CanCanCan just provides per-record filtering (store scoping etc.).
+
+### UI: API key creation
+
+In the existing API keys admin, when minting a **secret** key:
+
+- Show a checkbox tree of resources, with read/write columns
+- "Select all read" / "Select all write" / "Full admin (write_all)" quick presets
+- Display scope descriptions inline ("Read orders — view orders, line items, status")
+- Validate at least one scope is selected before save
+- Stored as the explicit array, not aliases
+
+### SDK and OpenAPI documentation
+
+- OpenAPI spec gains a `security` declaration listing the required scope per endpoint (rswag `security [api_key: [scopes...]]` syntax).
+- SDK doesn't need to know about scopes — the server enforces them and returns `403 access_denied_scope_required` with the missing scope name in the error message.
+
+### Error response
+
+```json
+{
+ "error": {
+ "code": "access_denied",
+ "message": "API key lacks scope: write_orders"
+ }
+}
+```
+
+Status: `403`. New error code variant `missing_scope` (optional) inside `details: { required_scope: 'write_orders' }` for clients that want to handle it programmatically.
+
+## Migration Path
+
+1. Add `scopes` column to `spree_api_keys` (default `[]`).
+2. Add `KNOWN_SCOPES` and `has_scope?` to `Spree::ApiKey`.
+3. Add `ScopedAuthorization` concern; include in `Admin::BaseController`.
+4. Update `current_ability` resolution to fall back to `@current_api_key.created_by`.
+5. Declare `scoped_resource` on every admin controller (one line each, ~25 controllers).
+6. Update API key admin UI to expose scope checkboxes.
+7. Add a controller spec for each admin controller covering: (a) request with required scope succeeds, (b) request without required scope returns 403, (c) `read_all` / `write_all` aliases work.
+8. Update `docs/api-reference/admin-api/authentication.mdx` with scope reference.
+
+No data migration needed — there are no production admin API keys to migrate.
+
+## Constraints on Current Work
+
+Work in progress that should account for this plan:
+
+- **Any new admin controller** must call `scoped_resource :name` after this plan ships. Reviewers should reject admin PRs that don't.
+- **Don't add per-action scopes** (`cancel_orders`, etc.) without revisiting this plan. Resource granularity is the agreed default.
+- **Don't add scope checks to JWT-authenticated paths.** Scopes are an API-key concept only.
+- **OpenAPI specs** added before this ships should expect a future `security` enrichment — don't manually duplicate scope info in descriptions.
+
+## Open Questions
+
+- **Should `read_dashboard` be split further?** Currently lumps all analytics endpoints together. If we add per-team dashboards (revenue, fulfillment, customers), we may want `read_revenue_dashboard` etc. Defer until there's a real partner request.
+- **Scopes in OAuth flows?** Not in scope for 5.5. If we build a public app marketplace later, OAuth-issued tokens would carry scopes the same way; the `KNOWN_SCOPES` enum would be reused.
+- **Audit log of scope-denied requests?** Useful for app developers debugging permission errors. Could ride on the existing `Spree::EventBus` pattern; out of scope for the first cut.
+- **What about webhook subscriptions?** Listed as `read_webhooks` / `write_webhooks` but the webhook admin endpoints don't exist yet. Reserve the name; implement when those endpoints land.
+
+## References
+
+- `6.0-admin-api.md` — Admin REST API endpoint inventory
+- Shopify access scopes: https://shopify.dev/docs/api/usage/access-scopes
+- Saleor app permissions: https://docs.saleor.io/api-reference/apps/enums/permission-enum
+- Medusa v2 admin tokens: https://docs.medusajs.com/v2/resources/commerce-modules/api-key
diff --git a/packages/admin-sdk/src/client.ts b/packages/admin-sdk/src/client.ts
index 5393e0f47d..c467f00e0b 100644
--- a/packages/admin-sdk/src/client.ts
+++ b/packages/admin-sdk/src/client.ts
@@ -65,11 +65,12 @@ export function createAdminClient(config: AdminClientConfig): Client {
};
const makeRequest = () => {
- const requestFn = createRequestFn(
- requestConfig,
- basePath,
- { headerName: 'Authorization', headerValue: config.secretKey ? `Bearer ${config.secretKey}` : currentToken ? `Bearer ${currentToken}` : '' },
- );
+ // Secret keys go in `X-Spree-Api-Key` (server-to-server integrations).
+ // JWT tokens go in `Authorization: Bearer` (admin SPA sessions).
+ const auth = config.secretKey
+ ? { headerName: 'X-Spree-Api-Key', headerValue: config.secretKey }
+ : { headerName: 'Authorization', headerValue: currentToken ? `Bearer ${currentToken}` : '' };
+ const requestFn = createRequestFn(requestConfig, basePath, auth);
return requestFn<T>(method, path, mergedOptions);
};
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 3343934202..ad0be7c44d 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
@@ -16,6 +16,17 @@ module Spree
Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN
end
+ # API-key-only requests bypass CanCanCan: the ScopedAuthorization
+ # concern is the authoritative gate (read_/write_ scopes per resource).
+ # JWT admin users keep CanCanCan abilities; if both credentials are
+ # present, the JWT user wins for permission resolution.
+ def current_ability
+ return super if current_user
+ return super unless @current_api_key
+
+ @current_ability ||= Spree::ApiKeyAbility.new(ability_options)
+ end
+
# Authenticates admin requests via secret API key OR JWT token.
# Secret keys are checked first (server-to-server integrations),
# then JWT tokens (admin SPA sessions).
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
new file mode 100644
index 0000000000..92926d6258
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/scoped_authorization.rb
@@ -0,0 +1,77 @@
+module Spree
+ module Api
+ module V3
+ # Per-resource scope check for Admin API requests authenticated via API key.
+ # JWT-authenticated admin users bypass this and rely on CanCanCan abilities.
+ #
+ # Controllers declare their scope:
+ #
+ # class Spree::Api::V3::Admin::OrdersController < ResourceController
+ # scoped_resource :orders
+ # end
+ #
+ # The before_action maps the action to a `read_*` (index/show) or `write_*`
+ # (everything else, including custom member actions) scope and verifies the
+ # API key carries it.
+ #
+ # See docs/plans/5.5-admin-api-key-scopes.md.
+ module ScopedAuthorization
+ extend ActiveSupport::Concern
+
+ READ_ACTIONS = %w[index show].freeze
+
+ class MissingScopedResource < StandardError
+ def initialize(controller_class)
+ super("#{controller_class} must declare `scoped_resource :name` " \
+ '(or `skip_scope_check!` for endpoints exempt from scope checks).')
+ end
+ end
+
+ class_methods do
+ def scoped_resource(name)
+ self._scoped_resource = name.to_sym
+ self._scope_check_skipped = false
+ end
+
+ # Opt out of scope checks (auth, me, tags, direct uploads, etc).
+ def skip_scope_check!
+ self._scope_check_skipped = true
+ end
+ end
+
+ included do
+ class_attribute :_scoped_resource, instance_accessor: false
+ class_attribute :_scope_check_skipped, instance_accessor: false, default: false
+ before_action :authorize_api_key_scope!
+ end
+
+ private
+
+ def authorize_api_key_scope!
+ return unless current_api_key
+ return if self.class._scope_check_skipped
+
+ # Fail closed: a controller authenticated by API key MUST declare
+ # either `scoped_resource :name` or `skip_scope_check!`.
+ raise MissingScopedResource, self.class unless self.class._scoped_resource
+
+ required = "#{action_kind}_#{self.class._scoped_resource}"
+ return if current_api_key.has_scope?(required)
+
+ render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:access_denied],
+ message: "API key lacks scope: #{required}",
+ status: :forbidden,
+ details: { required_scope: required }
+ )
+ end
+
+ # Override in controllers with non-REST custom actions (e.g. dashboard
+ # `analytics` should map to a read).
+ def action_kind
+ READ_ACTIONS.include?(action_name) ? 'read' : 'write'
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb
index 50be04908d..199ab50f2b 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb
@@ -3,6 +3,8 @@ module Spree
module V3
module Admin
class AuthController < Admin::BaseController
+ skip_scope_check!
+
rate_limit to: Spree::Api::Config[:rate_limit_login], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :create, with: RATE_LIMIT_RESPONSE
rate_limit to: Spree::Api::Config[:rate_limit_refresh], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :refresh, with: RATE_LIMIT_RESPONSE
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 c6ff1f7b46..78ea9b5eb7 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
@@ -4,6 +4,7 @@ module Spree
module Admin
class BaseController < Spree::Api::V3::BaseController
include Spree::Api::V3::AdminAuthentication
+ include Spree::Api::V3::ScopedAuthorization
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb
index e32c1d548d..ffb5ad5b9c 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb
@@ -3,6 +3,8 @@ module Spree
module V3
module Admin
class CategoriesController < ResourceController
+ scoped_resource :categories
+
protected
def model_class
diff --git a/spree/api/app/controllers/spree/api/v3/admin/countries_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/countries_controller.rb
index 45456c5c68..a89652537a 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/countries_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/countries_controller.rb
@@ -3,6 +3,8 @@ module Spree
module V3
module Admin
class CountriesController < ResourceController
+ scoped_resource :settings
+
# Override base index to skip pagination — there are ~250 countries
# and address-form dropdowns need them all at once. Pagy's global
# max_limit (100) prevents using the paginated path for this.
diff --git a/spree/api/app/controllers/spree/api/v3/admin/customers/addresses_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customers/addresses_controller.rb
index b2d5f9827e..4de10f3552 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/customers/addresses_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/customers/addresses_controller.rb
@@ -4,6 +4,8 @@ module Spree
module Admin
module Customers
class AddressesController < ResourceController
+ scoped_resource :customers
+
# POST /api/v3/admin/customers/:customer_id/addresses
def create
@resource = @parent.addresses.new(address_attrs)
diff --git a/spree/api/app/controllers/spree/api/v3/admin/customers/credit_cards_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customers/credit_cards_controller.rb
index 21ad9c3e67..e7aadab2f9 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/customers/credit_cards_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/customers/credit_cards_controller.rb
@@ -4,6 +4,8 @@ module Spree
module Admin
module Customers
class CreditCardsController < ResourceController
+ scoped_resource :customers
+
protected
def set_parent
diff --git a/spree/api/app/controllers/spree/api/v3/admin/customers/store_credits_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customers/store_credits_controller.rb
index 704ad87cd2..af7bb81572 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/customers/store_credits_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/customers/store_credits_controller.rb
@@ -4,6 +4,8 @@ module Spree
module Admin
module Customers
class StoreCreditsController < ResourceController
+ scoped_resource :store_credits
+
# POST /api/v3/admin/customers/:customer_id/store_credits
def create
@resource = @parent.store_credits.new(create_attrs)
diff --git a/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb
index 0f2ad55056..463ad03319 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb
@@ -3,6 +3,8 @@ module Spree
module V3
module Admin
class CustomersController < ResourceController
+ scoped_resource :customers
+
def create
@resource = Spree.user_class.new(permitted_params)
authorize!(:create, @resource)
diff --git a/spree/api/app/controllers/spree/api/v3/admin/dashboard_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/dashboard_controller.rb
index 438b65c604..54abe71eee 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/dashboard_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/dashboard_controller.rb
@@ -3,6 +3,8 @@ module Spree
module V3
module Admin
class DashboardController < Admin::BaseController
+ scoped_resource :dashboard
+
# GET /api/v3/admin/dashboard/analytics
def analytics
date_from = (params[:date_from] || 30.days.ago).to_time.beginning_of_day
@@ -21,6 +23,10 @@ module Spree
private
+ def action_kind
+ 'read'
+ end
+
def serializer_params
{
store: current_store,
diff --git a/spree/api/app/controllers/spree/api/v3/admin/direct_uploads_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/direct_uploads_controller.rb
index e16f23da6a..c7c611f04c 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/direct_uploads_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/direct_uploads_controller.rb
@@ -3,6 +3,16 @@ module Spree
module V3
module Admin
class DirectUploadsController < Admin::BaseController
+ # Direct uploads is a write-adjacent presigning helper: callers exchange
+ # blob metadata for an upload URL, then reference the resulting
+ # signed_id when creating/updating a resource (product media, customer
+ # avatar, etc). The narrowest scope it can map to is `write_products`
+ # since that covers the dominant upload flow (product/variant media).
+ # Other admin-write flows that take signed_ids (e.g. customer avatar)
+ # already require the relevant `write_<resource>` scope on the
+ # subsequent PATCH, so this gate is the floor, not the only check.
+ scoped_resource :products
+
skip_before_action :authenticate_user
# POST /api/v3/admin/direct_uploads
diff --git a/spree/api/app/controllers/spree/api/v3/admin/me_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/me_controller.rb
index 3826692744..99ef61cbd9 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/me_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/me_controller.rb
@@ -3,6 +3,8 @@ module Spree
module V3
module Admin
class MeController < Admin::BaseController
+ skip_scope_check!
+
# GET /api/v3/admin/me
# Returns the current admin user along with a serialized representation
# of their permissions (derived from CanCanCan rules). The SPA uses
diff --git a/spree/api/app/controllers/spree/api/v3/admin/media_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/media_controller.rb
index 54c085fa26..df9dc7ff8e 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/media_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/media_controller.rb
@@ -3,6 +3,8 @@ module Spree
module V3
module Admin
class MediaController < ResourceController
+ scoped_resource :products
+
def create
if permitted_params[:url].present?
create_from_url
diff --git a/spree/api/app/controllers/spree/api/v3/admin/option_types_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/option_types_controller.rb
index fe8b2dbbc1..e2d8e7da02 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/option_types_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/option_types_controller.rb
@@ -3,6 +3,8 @@ module Spree
module V3
module Admin
class OptionTypesController < ResourceController
+ scoped_resource :products
+
# POST /api/v3/admin/option_types
def create
authorize!(:create, Spree::OptionType)
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/adjustments_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/adjustments_controller.rb
index 741d646178..b8bbcc0a8c 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/adjustments_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/adjustments_controller.rb
@@ -4,6 +4,8 @@ module Spree
module Admin
module Orders
class AdjustmentsController < BaseController
+ scoped_resource :orders
+
protected
def model_class
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rb
index c98c2f2a2b..b6ac73a633 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rb
@@ -4,6 +4,8 @@ module Spree
module Admin
module Orders
class FulfillmentsController < BaseController
+ scoped_resource :fulfillments
+
before_action :set_resource, only: [:show, :update, :fulfill, :cancel, :resume, :split]
# PATCH /api/v3/admin/orders/:order_id/fulfillments/:id
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/gift_cards_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/gift_cards_controller.rb
index 2af7b7dbf7..404b5797ce 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/gift_cards_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/gift_cards_controller.rb
@@ -4,6 +4,8 @@ module Spree
module Admin
module Orders
class GiftCardsController < BaseController
+ scoped_resource :gift_cards
+
skip_before_action :set_resource, raise: false
# POST /api/v3/admin/orders/:order_id/gift_cards
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/items_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/items_controller.rb
index 5920ee2bf5..6f31c6c824 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/items_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/items_controller.rb
@@ -4,6 +4,8 @@ module Spree
module Admin
module Orders
class ItemsController < BaseController
+ scoped_resource :orders
+
# POST /api/v3/admin/orders/:order_id/items
def create
with_order_lock do
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/payments_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/payments_controller.rb
index 4385760807..9f7b8f9e4d 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/payments_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/payments_controller.rb
@@ -4,6 +4,8 @@ module Spree
module Admin
module Orders
class PaymentsController < BaseController
+ scoped_resource :payments
+
before_action :set_resource, only: [:show, :capture, :void]
# POST /api/v3/admin/orders/:order_id/payments
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/refunds_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/refunds_controller.rb
index 70f3906530..8c37034768 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/refunds_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/refunds_controller.rb
@@ -4,6 +4,8 @@ module Spree
module Admin
module Orders
class RefundsController < BaseController
+ scoped_resource :refunds
+
# POST /api/v3/admin/orders/:order_id/refunds
def create
with_order_lock do
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/store_credits_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/store_credits_controller.rb
index aa6cff7429..f83b630297 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/store_credits_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/store_credits_controller.rb
@@ -4,6 +4,8 @@ module Spree
module Admin
module Orders
class StoreCreditsController < BaseController
+ scoped_resource :store_credits
+
skip_before_action :set_resource, raise: false
# POST /api/v3/admin/orders/:order_id/store_credits
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb
index 8572272018..41fb725bdf 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb
@@ -5,6 +5,8 @@ module Spree
class OrdersController < ResourceController
include Spree::Api::V3::OrderLock
+ scoped_resource :orders
+
skip_before_action :set_resource, only: [:index, :create]
before_action :set_resource, only: [:show, :update, :destroy, :complete, :cancel, :approve, :resume, :resend_confirmation]
@@ -42,13 +44,6 @@ module Spree
end
end
- # DELETE /api/v3/admin/orders/:id
- # CanCanCan restricts destroy to orders where can_be_deleted? is true
- def destroy
- @resource.destroy
- head :no_content
- end
-
# PATCH /api/v3/admin/orders/:id/complete
def complete
with_order_lock do
diff --git a/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb
index d173395fa5..8e41a9ebae 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb
@@ -3,6 +3,8 @@ module Spree
module V3
module Admin
class PaymentMethodsController < ResourceController
+ scoped_resource :settings
+
protected
def model_class
diff --git a/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rb
index 94618fde46..a9cb3c74bc 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rb
@@ -4,6 +4,8 @@ module Spree
module Admin
module Products
class VariantsController < ResourceController
+ scoped_resource :products
+
protected
def model_class
diff --git a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
index 3baad6d110..fac6495183 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
@@ -3,6 +3,8 @@ module Spree
module V3
module Admin
class ProductsController < ResourceController
+ scoped_resource :products
+
# POST /api/v3/admin/products/:id/clone
def clone
@resource = find_resource
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 03b8af70b7..a6f62c33a4 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
@@ -2,8 +2,12 @@ module Spree
module Api
module V3
module Admin
+ # Mirrors Admin::BaseController's concerns. Both classes anchor parallel
+ # 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::AdminAuthentication
+ include Spree::Api::V3::ScopedAuthorization
protected
diff --git a/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb
index 00645749e1..f801eb314f 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb
@@ -3,6 +3,8 @@ module Spree
module V3
module Admin
class StoreController < Admin::BaseController
+ scoped_resource :settings
+
# GET /api/v3/admin/store
def show
authorize! :show, current_store
diff --git a/spree/api/app/controllers/spree/api/v3/admin/tags_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/tags_controller.rb
index 854f2be081..cbfeecf063 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/tags_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/tags_controller.rb
@@ -3,6 +3,8 @@ module Spree
module V3
module Admin
class TagsController < BaseController
+ skip_scope_check!
+
MAX_RESULTS = 50
def index
diff --git a/spree/api/app/controllers/spree/api/v3/admin/tax_categories_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/tax_categories_controller.rb
index 9f69b43171..df08636ab7 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/tax_categories_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/tax_categories_controller.rb
@@ -3,6 +3,8 @@ module Spree
module V3
module Admin
class TaxCategoriesController < ResourceController
+ scoped_resource :settings
+
protected
def model_class
diff --git a/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb
index 8d70e11c52..78c03dd71c 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb
@@ -3,6 +3,8 @@ module Spree
module V3
module Admin
class VariantsController < ResourceController
+ scoped_resource :products
+
protected
def model_class
diff --git a/spree/api/app/controllers/spree/api/v3/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/resource_controller.rb
index c06d1ee24a..f73a45a29b 100644
--- a/spree/api/app/controllers/spree/api/v3/resource_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/resource_controller.rb
@@ -50,9 +50,18 @@ module Spree
end
# DELETE /api/v3/resource/:id
+ # Honors `can_be_deleted?` if the model defines it — domain rules like
+ # "completed orders cannot be deleted" live on the model, not on
+ # CanCanCan abilities, so they apply to all callers (JWT and API key).
def destroy
- @resource.destroy
+ if @resource.respond_to?(:can_be_deleted?) && [email protected]_be_deleted?
+ raise CanCan::AccessDenied.new("#{@resource.class.model_name.human} cannot be deleted")
+ end
+
+ @resource.destroy!
head :no_content
+ rescue ActiveRecord::RecordNotDestroyed => e
+ render_validation_error(e.record.errors.presence || e.message)
end
protected
diff --git a/spree/api/app/models/spree/api_key_ability.rb b/spree/api/app/models/spree/api_key_ability.rb
new file mode 100644
index 0000000000..5735f73173
--- /dev/null
+++ b/spree/api/app/models/spree/api_key_ability.rb
@@ -0,0 +1,16 @@
+module Spree
+ # CanCanCan ability used for API-key-authenticated admin requests.
+ # Grants full access — authorization happens at the scope-check layer
+ # (Spree::Api::V3::ScopedAuthorization), not at the per-record CanCanCan
+ # layer. This exists so that `accessible_by(current_ability, :show)` in
+ # admin controllers returns the unrestricted scope (it would otherwise
+ # require a real Spree::Ability with role lookups, which doesn't apply
+ # to API key principals).
+ class ApiKeyAbility
+ include CanCan::Ability
+
+ def initialize(_options = {})
+ can :manage, :all
+ 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 0381555e7d..bac5395fe9 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
@@ -2,6 +2,8 @@ require 'spec_helper'
# Anonymous controller to test Admin::BaseController authentication and audience enforcement
class Spree::Api::V3::Admin::TestController < Spree::Api::V3::Admin::BaseController
+ skip_scope_check!
+
def index
render json: { ok: true }
end
@@ -9,6 +11,8 @@ end
RSpec.describe Spree::Api::V3::Admin::BaseController, type: :controller do
controller(Spree::Api::V3::Admin::TestController) do
+ skip_scope_check!
+
def index
if current_user
render json: { ok: true, user_id: current_user.id }
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 04fda0b457..f99e492df7 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
@@ -5,6 +5,11 @@ RSpec.describe Spree::Api::V3::Admin::MeController, type: :controller do
include_context 'API v3 Admin authenticated'
+ # /admin/me reflects the calling admin user — exercise JWT-only here
+ # (sending a secret key would route to the API-key principal, which has
+ # no Spree user to introspect).
+ let(:headers) { { 'Authorization' => "Bearer #{admin_jwt_token}" } }
+
before { request.headers.merge!(headers) }
describe 'GET #show' do
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
new file mode 100644
index 0000000000..e9dbcf715d
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/scoped_authorization_spec.rb
@@ -0,0 +1,102 @@
+require 'spec_helper'
+
+# Verifies the ScopedAuthorization concern that gates Admin API requests
+# authenticated via secret API key. Uses OrdersController as a representative
+# resource — the same mechanic applies to every admin controller via the
+# `scoped_resource` declaration.
+RSpec.describe Spree::Api::V3::Admin::OrdersController, type: :controller do
+ render_views
+ include_context 'API v3 Admin'
+
+ let!(:order) { create(:order, store: store, state: 'cart') }
+ 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 }
+
+ describe 'with required scope' do
+ let(:scopes) { ['read_orders'] }
+
+ it 'allows reads' do
+ get :index, as: :json
+ expect(response).to have_http_status(:ok)
+ end
+ end
+
+ describe 'without required scope' do
+ let(:scopes) { ['read_customers'] }
+
+ it 'returns 403 with access_denied + required_scope details' do
+ get :index, 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_orders')
+ end
+ end
+
+ describe 'write action with read-only scope' do
+ let(:scopes) { ['read_orders'] }
+
+ it 'denies the write' do
+ delete :destroy, params: { id: order.prefixed_id }, 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('write_orders')
+ end
+ end
+
+ describe 'write_X implies read_X' do
+ let(:scopes) { ['write_orders'] }
+
+ it 'allows reads' do
+ get :index, as: :json
+ expect(response).to have_http_status(:ok)
+ end
+ end
+
+ describe 'read_all alias' do
+ let(:scopes) { ['read_all'] }
+
+ it 'allows reads on any resource' do
+ get :index, as: :json
+ expect(response).to have_http_status(:ok)
+ end
+
+ it 'denies writes' do
+ delete :destroy, params: { id: order.prefixed_id }, as: :json
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
+
+ describe 'write_all alias' do
+ let(:scopes) { ['write_all'] }
+
+ it 'allows reads' do
+ get :index, as: :json
+ expect(response).to have_http_status(:ok)
+ end
+
+ it 'allows writes' do
+ delete :destroy, params: { id: order.prefixed_id }, as: :json
+ expect(response).to have_http_status(:no_content)
+ end
+ end
+
+ describe 'JWT-authenticated request' do
+ # JWT bypasses scope checks; CanCanCan abilities apply instead.
+ before do
+ request.headers['X-Spree-Api-Key'] = nil
+ request.headers['Authorization'] = "Bearer #{admin_jwt_token}"
+ end
+
+ let(:scopes) { ['read_customers'] } # irrelevant — JWT auth doesn't read scopes
+
+ it 'bypasses scope checks' do
+ get :index, as: :json
+ expect(response).to have_http_status(:ok)
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/api_key.rb b/spree/core/app/models/spree/api_key.rb
index 9135f80ff1..42ef0b8457 100644
--- a/spree/core/app/models/spree/api_key.rb
+++ b/spree/core/app/models/spree/api_key.rb
@@ -6,6 +6,29 @@ module Spree
PREFIXES = { 'publishable' => 'pk_', 'secret' => 'sk_' }.freeze
TOKEN_LENGTH = 24
+ # Admin API authorization scopes. Granted to secret keys at creation; checked
+ # by ScopedAuthorization on every admin request. See
+ # docs/plans/5.5-admin-api-key-scopes.md for the full design.
+ SCOPES = %w[
+ read_orders write_orders
+ read_products write_products
+ read_customers write_customers
+ read_payments write_payments
+ read_fulfillments write_fulfillments
+ read_refunds write_refunds
+ read_gift_cards write_gift_cards
+ read_store_credits write_store_credits
+ read_categories write_categories
+ read_settings write_settings
+ read_webhooks write_webhooks
+ read_dashboard
+ read_all write_all
+ ].freeze
+
+ # Scopes are stored in a JSON column (jsonb on PostgreSQL, json elsewhere).
+ # The DB driver handles array <-> JSON conversion; no `serialize` needed.
+ attribute :scopes, default: []
+
# Returns the raw token value. For publishable keys this is the persisted
# +token+ column. For secret keys it is only available in memory immediately
# after creation (not persisted).
@@ -25,6 +48,8 @@ module Spree
validates :token_digest, presence: true, uniqueness: true, if: :secret?
validates :token_prefix, presence: true, if: :secret?
validates :store, presence: true
+ validates :scopes, presence: true, if: :secret?
+ validate :validate_known_scopes, if: :secret?
before_validation :generate_token, on: :create
@@ -83,8 +108,29 @@ module Spree
update!(revoked_at: Time.current, revoked_by: user)
end
+ # Whether this key carries the given scope. `write_*` implies the matching
+ # `read_*`; `read_all` / `write_all` aliases expand to every read / read+write
+ # scope respectively.
+ #
+ # @param scope [String]
+ # @return [Boolean]
+ def has_scope?(scope)
+ scope = scope.to_s
+ return true if scopes.include?(scope)
+ return true if scope.start_with?('read_') && scopes.include?("write_#{scope.delete_prefix('read_')}")
+ return true if scopes.include?('write_all')
+ return true if scope.start_with?('read_') && scopes.include?('read_all')
+
+ false
+ end
+
private
+ def validate_known_scopes
+ invalid = scopes - SCOPES
+ errors.add(:scopes, "contains unknown scopes: #{invalid.join(', ')}") if invalid.any?
+ end
+
# Generates the token on creation. For publishable keys, stores the raw token
# in the +token+ column. For secret keys, computes an HMAC-SHA256 digest stored
# in +token_digest+, saves the first 12 characters as +token_prefix+ for display,
diff --git a/spree/core/db/migrate/20260429000004_add_scopes_to_spree_api_keys.rb b/spree/core/db/migrate/20260429000004_add_scopes_to_spree_api_keys.rb
new file mode 100644
index 0000000000..89de978c88
--- /dev/null
+++ b/spree/core/db/migrate/20260429000004_add_scopes_to_spree_api_keys.rb
@@ -0,0 +1,11 @@
+class AddScopesToSpreeApiKeys < ActiveRecord::Migration[7.2]
+ def change
+ change_table :spree_api_keys do |t|
+ if t.respond_to?(:jsonb)
+ t.jsonb :scopes
+ else
+ t.json :scopes
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/testing_support/factories/api_key_factory.rb b/spree/core/lib/spree/testing_support/factories/api_key_factory.rb
index 5136e6536a..7f1c0aec36 100644
--- a/spree/core/lib/spree/testing_support/factories/api_key_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/api_key_factory.rb
@@ -10,6 +10,7 @@ FactoryBot.define do
trait :secret do
key_type { 'secret' }
+ scopes { ['write_all'] }
end
trait :revoked do
diff --git a/spree/core/spec/models/spree/api_key_spec.rb b/spree/core/spec/models/spree/api_key_spec.rb
index 9b86f70a24..44624f86d5 100644
--- a/spree/core/spec/models/spree/api_key_spec.rb
+++ b/spree/core/spec/models/spree/api_key_spec.rb
@@ -256,4 +256,63 @@ RSpec.describe Spree::ApiKey, type: :model do
expect(api_key.revoked_by).to eq(user)
end
end
+
+ describe 'scopes (Admin API authorization)' do
+ describe 'validation' do
+ it 'requires scopes for secret keys' do
+ key = build(:api_key, :secret, store: store, scopes: [])
+ expect(key).not_to be_valid
+ expect(key.errors[:scopes]).to be_present
+ end
+
+ it 'rejects unknown scopes for secret keys' do
+ key = build(:api_key, :secret, store: store, scopes: ['read_orders', 'bogus_scope'])
+ expect(key).not_to be_valid
+ expect(key.errors[:scopes].join).to include('bogus_scope')
+ end
+
+ it 'accepts known scopes for secret keys' do
+ key = build(:api_key, :secret, store: store, scopes: %w[read_orders write_customers])
+ expect(key).to be_valid
+ end
+
+ it 'does not require scopes for publishable keys' do
+ key = build(:api_key, :publishable, store: store, scopes: [])
+ expect(key).to be_valid
+ end
+ end
+
+ describe '#has_scope?' do
+ it 'returns true for an exact scope match' do
+ key = build(:api_key, :secret, store: store, scopes: ['read_orders'])
+ expect(key.has_scope?('read_orders')).to be true
+ end
+
+ it 'returns false for a scope not granted' do
+ key = build(:api_key, :secret, store: store, scopes: ['read_orders'])
+ expect(key.has_scope?('write_orders')).to be false
+ expect(key.has_scope?('read_customers')).to be false
+ end
+
+ it 'treats write_X as implying read_X' do
+ key = build(:api_key, :secret, store: store, scopes: ['write_orders'])
+ expect(key.has_scope?('read_orders')).to be true
+ expect(key.has_scope?('write_orders')).to be true
+ end
+
+ it 'expands read_all to every read_* scope' do
+ key = build(:api_key, :secret, store: store, scopes: ['read_all'])
+ expect(key.has_scope?('read_orders')).to be true
+ expect(key.has_scope?('read_customers')).to be true
+ expect(key.has_scope?('write_orders')).to be false
+ end
+
+ it 'expands write_all to every read_* and write_* scope' do
+ key = build(:api_key, :secret, store: store, scopes: ['write_all'])
+ expect(key.has_scope?('read_orders')).to be true
+ expect(key.has_scope?('write_orders')).to be true
+ expect(key.has_scope?('write_customers')).to be true
+ end
+ end
+ end
end