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.

Fixed: make Admin API rate limits stricter per client/not endpoint (#14426)

Damian Legawieccb81e856c0d6
diff --git a/docs/plans/6.0-platform-auth.md b/docs/plans/6.0-platform-auth.md
index 4935bc46fc..9673b7aeea 100644
--- a/docs/plans/6.0-platform-auth.md
+++ b/docs/plans/6.0-platform-auth.md
@@ -399,8 +399,12 @@ Shipped earlier (5.4 + prior 6.0 work):
- `Spree::RefreshToken` model (issue/rotate/revoke) — `create_for` / `rotate!` / `revoke_all_for`.
- `AuthController` issues refresh tokens alongside access JWTs, and `POST /auth/refresh` +
`POST /auth/logout` for both store (refresh token in body) and admin (HttpOnly cookie).
-- Rate limiting (Rails `rate_limit`) on login/refresh/register/password-reset + per-publishable-key
- throttle + `X-RateLimit-*` headers, all config-driven via `Spree::Api::Config[:rate_limit_*]`.
+- Rate limiting (Rails `rate_limit`) on login/refresh/register/password-reset + a global per-caller
+ throttle + `X-RateLimit-*` headers, all config-driven via `Spree::Api::Config[:rate_limit_*]`:
+ one bucket per caller across all v3 controllers (`scope: 'api_v3'`), split by credential —
+ secret keys get `rate_limit_per_secret_key` (600/min) per key, publishable keys get
+ `rate_limit_per_key` (300/min) per key + client IP (per visitor, never per storefront),
+ keyless/JWT traffic per IP.
- Account-lockout **methods** + `failed_attempts`/`locked_at` columns on Customer/AdminUser.
Landed:
diff --git a/docs/v6/developer/customization/configuration.mdx b/docs/v6/developer/customization/configuration.mdx
index 87fc0b0128..9031080de0 100644
--- a/docs/v6/developer/customization/configuration.mdx
+++ b/docs/v6/developer/customization/configuration.mdx
@@ -128,7 +128,8 @@ Spree::Api::Config.jwt_expiration = 1800
| Setting | Default | What it does |
|---|---|---|
| `rate_limit_window` | `60` | Length of the rate-limit window, in seconds. |
-| `rate_limit_per_key` | `300` | Requests allowed per publishable API key per window. |
+| `rate_limit_per_key` | `300` | Requests allowed per window for each publishable API key + client IP pair (per visitor), and for keyless traffic per IP. Applies across the whole API, not per endpoint. |
+| `rate_limit_per_secret_key` | `600` | Requests allowed per secret API key per window, across the whole API. |
| `rate_limit_login` | `5` | Sign-in attempts allowed per IP per window. |
| `rate_limit_register` | `3` | Registration attempts per IP. |
| `rate_limit_refresh` | `10` | Token refresh attempts per IP. |
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 bd1c5a36a5..414a0eabc1 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
@@ -70,6 +70,15 @@ module Spree
def extract_api_key
request.headers['X-Spree-Api-Key'].presence
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. The token is unverified until
+ # `authenticate_secret_key!` resolves it, so consumers (the scope
+ # guard, rate limiting) must stay fail-closed on this signal alone.
+ def secret_key_request?
+ extract_api_key.to_s.start_with?(Spree::ApiKey::PREFIXES['secret'])
+ end
end
end
end
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/rate_limit_headers.rb b/spree/api/app/controllers/concerns/spree/api/v3/rate_limit_headers.rb
index 5df1b64f10..e023a586e6 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/rate_limit_headers.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/rate_limit_headers.rb
@@ -1,22 +1,56 @@
module Spree
module Api
module V3
- # Sets X-RateLimit-Limit, X-RateLimit-Remaining, and Retry-After headers
- # on every Store API response by reading the same cache counter that
- # Rails' built-in `rate_limit` writes to.
+ # Owns the request-throttling identity shared by the `rate_limit`
+ # declarations in BaseController and the X-RateLimit-Limit /
+ # X-RateLimit-Remaining / Retry-After headers set on every v3 response:
+ # which bucket a request counts against and which ceiling applies.
+ #
+ # Secret keys (sk_*) are single server-to-server callers, so each key
+ # gets one bucket across the whole API. Publishable keys (pk_*) are
+ # shared by every storefront visitor, so their bucket includes the
+ # client IP — the limit is per visitor, never per storefront. Requests
+ # without an API key (admin JWT traffic) fall back to the client IP.
module RateLimitHeaders
extend ActiveSupport::Concern
+ # Shared `scope:` for the API-wide throttle — one bucket per caller
+ # across all v3 controllers, instead of Rails' default of one bucket
+ # per controller.
+ RATE_LIMIT_SCOPE = 'api_v3'.freeze
+
included do
after_action :set_rate_limit_headers
end
private
+ def rate_limit_ceiling
+ if secret_key_request?
+ Spree::Api::Config[:rate_limit_per_secret_key]
+ else
+ Spree::Api::Config[:rate_limit_per_key]
+ end
+ end
+
+ # Secret tokens are digested first — plaintext secrets must never
+ # become cache keys (Solid Cache persists them to the database, while
+ # the model itself stores only +token_digest+).
+ def rate_limit_bucket
+ api_key = extract_api_key
+
+ if secret_key_request?
+ Spree::ApiKey.compute_token_digest(api_key)
+ elsif api_key
+ "#{api_key}:#{request.remote_ip}"
+ else
+ request.remote_ip
+ end
+ end
+
def set_rate_limit_headers
- limit = Spree::Api::Config[:rate_limit_per_key]
- by = request.headers['X-Spree-Api-Key'] || request.remote_ip
- cache_key = ['rate-limit', controller_path, by].compact.join(':')
+ limit = rate_limit_ceiling
+ cache_key = ['rate-limit', RATE_LIMIT_SCOPE, rate_limit_bucket].join(':')
count = Rails.cache.read(cache_key)
return if count.nil?
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 a539eba271..d8cf2e7039 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
@@ -165,15 +165,6 @@ module Spree
self.class._scope_check_skipped_actions&.include?(action_name) || false
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
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 ae919e0676..e3a4dd12e8 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
@@ -14,13 +14,16 @@ module Spree
# not be refused because the login form was submitted a few times.
RATE_LIMITED_CALLBACK_RESPONSE = -> { redirect_to_dashboard(error: 'rate_limit_exceeded') }
- 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
- # Each of these gets its own counter. The login page fetches providers on
- # every load, so sharing the login budget would let ordinary page views —
- # or an attacker hitting providers alone — lock staff out of signing in.
- rate_limit to: Spree::Api::Config[:rate_limit_refresh], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :providers, with: RATE_LIMIT_RESPONSE
- rate_limit to: Spree::Api::Config[:rate_limit_login], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :callback, with: RATE_LIMITED_CALLBACK_RESPONSE
- rate_limit to: Spree::Api::Config[:rate_limit_refresh], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: [:refresh, :logout], with: RATE_LIMIT_RESPONSE
+ # Each declaration carries a distinct `name:` — without one, Rails
+ # keys every counter in this controller on the same
+ # (controller, client) cache entry, silently merging the budgets.
+ # The login page fetches providers on every load, so sharing the
+ # login budget would let ordinary page views — or an attacker
+ # hitting providers alone — lock staff out of signing in.
+ rate_limit to: Spree::Api::Config[:rate_limit_login], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :create, name: 'login', with: -> { render_rate_limited(limit: Spree::Api::Config[:rate_limit_login]) }
+ rate_limit to: Spree::Api::Config[:rate_limit_refresh], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :providers, name: 'providers', with: -> { render_rate_limited(limit: Spree::Api::Config[:rate_limit_refresh]) }
+ rate_limit to: Spree::Api::Config[:rate_limit_login], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :callback, name: 'callback', with: RATE_LIMITED_CALLBACK_RESPONSE
+ rate_limit to: Spree::Api::Config[:rate_limit_refresh], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: [:refresh, :logout], name: 'refresh', with: -> { render_rate_limited(limit: Spree::Api::Config[:rate_limit_refresh]) }
skip_before_action :authenticate_admin!, only: [:create, :refresh, :logout, :providers, :callback]
@@ -129,6 +132,15 @@ module Spree
private
+ # The callback answers a browser navigation, so even the API-wide
+ # throttle must return the person to the login page — a JSON 429
+ # would strand them on a raw error body.
+ def render_rate_limited(**)
+ return redirect_to_dashboard(error: 'rate_limit_exceeded') if action_name == 'callback'
+
+ super
+ end
+
OAUTH_STATE_PURPOSE = 'spree/admin/oauth_state'.freeze
OAUTH_STATE_EXPIRY = 15.minutes
diff --git a/spree/api/app/controllers/spree/api/v3/admin/invitation_acceptances_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/invitation_acceptances_controller.rb
index 4ec565740c..af9f8dc98d 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/invitation_acceptances_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/invitation_acceptances_controller.rb
@@ -14,7 +14,7 @@ module Spree
within: Spree::Api::Config[:rate_limit_window].seconds,
store: Rails.cache,
only: [:lookup, :accept],
- with: RATE_LIMIT_RESPONSE
+ with: -> { render_rate_limited(limit: Spree::Api::Config[:rate_limit_login]) }
# GET /api/v3/admin/auth/invitations/:id/lookup?token=:token
def lookup
diff --git a/spree/api/app/controllers/spree/api/v3/base_controller.rb b/spree/api/app/controllers/spree/api/v3/base_controller.rb
index 8cf16f5499..443b0da5a9 100644
--- a/spree/api/app/controllers/spree/api/v3/base_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/base_controller.rb
@@ -19,29 +19,45 @@ module Spree
include Spree::Api::V3::Idempotent
include Pagy::Method
- RATE_LIMIT_RESPONSE = -> {
- limit = Spree::Api::Config[:rate_limit_per_key]
- window = Spree::Api::Config[:rate_limit_window]
- body = { error: { code: 'rate_limit_exceeded', message: 'Too many requests. Please retry later.' } }
- headers = {
- 'Content-Type' => 'application/json',
- 'Retry-After' => window.to_s,
- 'X-RateLimit-Limit' => limit.to_s,
- 'X-RateLimit-Remaining' => '0'
- }
- [429, headers, [body.to_json]]
- }
+ RATE_LIMIT_RESPONSE = -> { render_rate_limited }
+
+ # One global budget per caller (see RateLimitHeaders for the bucket
+ # rules); the two declarations are mutually exclusive so a request
+ # only ever counts against one ceiling.
+ rate_limit to: Spree::Api::Config[:rate_limit_per_secret_key], within: Spree::Api::Config[:rate_limit_window].seconds,
+ store: Rails.cache,
+ scope: RateLimitHeaders::RATE_LIMIT_SCOPE,
+ by: :rate_limit_bucket,
+ with: RATE_LIMIT_RESPONSE,
+ if: :secret_key_request?
rate_limit to: Spree::Api::Config[:rate_limit_per_key], within: Spree::Api::Config[:rate_limit_window].seconds,
store: Rails.cache,
- by: -> { request.headers['X-Spree-Api-Key'] || request.remote_ip },
- with: RATE_LIMIT_RESPONSE
+ scope: RateLimitHeaders::RATE_LIMIT_SCOPE,
+ by: :rate_limit_bucket,
+ with: RATE_LIMIT_RESPONSE,
+ unless: :secret_key_request?
# Optional JWT authentication by default
before_action :authenticate_user
protected
+ # Refuses a throttled request. Must render (not return a value) —
+ # Rails runs `with:` responders via instance_exec inside a
+ # before_action, where only render/redirect halts the chain. Headers
+ # are set here because a halted chain skips after_actions, so
+ # RateLimitHeaders never runs for a 429. Endpoint throttles pass the
+ # +limit+ that actually tripped so the header reports their ceiling,
+ # not the API-wide one.
+ def render_rate_limited(limit: rate_limit_ceiling)
+ response.headers['Retry-After'] = Spree::Api::Config[:rate_limit_window].to_s
+ response.headers['X-RateLimit-Limit'] = limit.to_s
+ response.headers['X-RateLimit-Remaining'] = '0'
+ render json: { error: { code: 'rate_limit_exceeded', message: 'Too many requests. Please retry later.' } },
+ status: :too_many_requests
+ end
+
# Guest authorization for a specific order or cart. Defined here
# because Store::BaseController and Store::ResourceController anchor
# parallel inheritance branches — both need it.
diff --git a/spree/api/app/controllers/spree/api/v3/store/auth_controller.rb b/spree/api/app/controllers/spree/api/v3/store/auth_controller.rb
index 264678d486..4ff81c0452 100644
--- a/spree/api/app/controllers/spree/api/v3/store/auth_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/auth_controller.rb
@@ -6,10 +6,13 @@ module Spree
include Spree::Api::V3::AuthenticationStrategies
allow_guest_storefront_access!
- # Tighter rate limits for auth endpoints (per IP to prevent brute force)
- 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
- rate_limit to: Spree::Api::Config[:rate_limit_refresh], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :logout, with: RATE_LIMIT_RESPONSE
+ # Tighter rate limits for auth endpoints (per IP to prevent brute
+ # force). Distinct `name:` per declaration — without one, Rails keys
+ # every counter in this controller on the same (controller, client)
+ # cache entry, silently merging the budgets.
+ rate_limit to: Spree::Api::Config[:rate_limit_login], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :create, name: 'login', with: -> { render_rate_limited(limit: Spree::Api::Config[:rate_limit_login]) }
+ rate_limit to: Spree::Api::Config[:rate_limit_refresh], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :refresh, name: 'refresh', with: -> { render_rate_limited(limit: Spree::Api::Config[:rate_limit_refresh]) }
+ rate_limit to: Spree::Api::Config[:rate_limit_refresh], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :logout, name: 'logout', with: -> { render_rate_limited(limit: Spree::Api::Config[:rate_limit_refresh]) }
skip_before_action :authenticate_user, only: [:create, :refresh, :logout]
diff --git a/spree/api/app/controllers/spree/api/v3/store/customers_controller.rb b/spree/api/app/controllers/spree/api/v3/store/customers_controller.rb
index 29d2db9da4..50b39d7d2d 100644
--- a/spree/api/app/controllers/spree/api/v3/store/customers_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/customers_controller.rb
@@ -4,7 +4,7 @@ module Spree
module Store
class CustomersController < Store::BaseController
allow_guest_storefront_access!
- rate_limit to: Spree::Api::Config[:rate_limit_register], 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_register], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :create, with: -> { render_rate_limited(limit: Spree::Api::Config[:rate_limit_register]) }
skip_before_action :authenticate_user, only: [:create]
prepend_before_action :require_authentication!, only: [:show, :update]
diff --git a/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb b/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb
index 2b97f2cac2..10903e5402 100644
--- a/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb
@@ -8,7 +8,7 @@ module Spree
within: Spree::Api::Config[:rate_limit_window].seconds,
store: Rails.cache,
only: [:create, :verify, :request_unsubscribe],
- with: RATE_LIMIT_RESPONSE
+ with: -> { render_rate_limited(limit: Spree::Api::Config[:rate_limit_register]) }
# POST /api/v3/store/newsletter_subscribers
def create
diff --git a/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rb b/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rb
index f113cf1f02..17fccafd8b 100644
--- a/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rb
@@ -17,9 +17,12 @@ module Spree
include ActionController::RateLimiting
include Spree::Core::ControllerHelpers::Store
+ # Must render — instance_exec'd in a before_action, where only
+ # render/redirect halts the chain.
RATE_LIMIT_RESPONSE = -> {
- [429, { 'Content-Type' => 'application/json', 'Retry-After' => '60' },
- [{ error: { code: 'rate_limit_exceeded', message: 'Too many requests' } }.to_json]]
+ response.headers['Retry-After'] = '60'
+ render json: { error: { code: 'rate_limit_exceeded', message: 'Too many requests' } },
+ status: :too_many_requests
}
rate_limit to: 120, within: 1.minute,
diff --git a/spree/api/app/controllers/spree/api/v3/webhooks/payments_controller.rb b/spree/api/app/controllers/spree/api/v3/webhooks/payments_controller.rb
index a80f314532..993b3abdc8 100644
--- a/spree/api/app/controllers/spree/api/v3/webhooks/payments_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/webhooks/payments_controller.rb
@@ -6,9 +6,12 @@ module Spree
include ActionController::RateLimiting
include Spree::Core::ControllerHelpers::Store
+ # Must render — instance_exec'd in a before_action, where only
+ # render/redirect halts the chain.
RATE_LIMIT_RESPONSE = -> {
- [429, { 'Content-Type' => 'application/json', 'Retry-After' => '60' },
- [{ error: { code: 'rate_limit_exceeded', message: 'Too many requests' } }.to_json]]
+ response.headers['Retry-After'] = '60'
+ render json: { error: { code: 'rate_limit_exceeded', message: 'Too many requests' } },
+ status: :too_many_requests
}
rate_limit to: 120, within: 1.minute,
diff --git a/spree/api/lib/spree/api/configuration.rb b/spree/api/lib/spree/api/configuration.rb
index 435c9b6965..8fbe46f1a4 100644
--- a/spree/api/lib/spree/api/configuration.rb
+++ b/spree/api/lib/spree/api/configuration.rb
@@ -15,7 +15,8 @@ module Spree
preference :refresh_token_expiry, :integer, default: 2_592_000 # 30 days in seconds
# Rate limiting
- preference :rate_limit_per_key, :integer, default: 300 # per publishable API key
+ preference :rate_limit_per_key, :integer, default: 300 # per publishable API key + client IP (per visitor)
+ preference :rate_limit_per_secret_key, :integer, default: 600 # per secret API key, across the whole API
preference :rate_limit_window, :integer, default: 60 # window in seconds
preference :rate_limit_login, :integer, default: 5 # per IP
preference :rate_limit_register, :integer, default: 3 # per IP
diff --git a/spree/api/spec/controllers/concerns/spree/api/v3/rate_limiting_spec.rb b/spree/api/spec/controllers/concerns/spree/api/v3/rate_limiting_spec.rb
index 3b5ace67f5..82d98adc4c 100644
--- a/spree/api/spec/controllers/concerns/spree/api/v3/rate_limiting_spec.rb
+++ b/spree/api/spec/controllers/concerns/spree/api/v3/rate_limiting_spec.rb
@@ -1,31 +1,111 @@
require 'spec_helper'
RSpec.describe 'Rate Limiting', type: :controller do
- describe Spree::Api::V3::Store::CountriesController do
- controller(Spree::Api::V3::Store::CountriesController) {}
+ describe 'secret API keys' do
+ describe Spree::Api::V3::Admin::CountriesController do
+ controller(Spree::Api::V3::Admin::CountriesController) {}
- render_views
+ render_views
- include_context 'API v3 Store'
+ include_context 'API v3 Admin'
- before do
- request.headers['X-Spree-Api-Key'] = api_key.token
+ before do
+ request.headers['X-Spree-Api-Key'] = secret_api_key.plaintext_token
+ end
+
+ it 'counts against one API-wide bucket keyed by the digested secret key' do
+ allow(Rails.cache).to receive(:increment).and_return(1)
+
+ get :index
+
+ digest = Spree::ApiKey.compute_token_digest(secret_api_key.plaintext_token)
+ expect(Rails.cache).to have_received(:increment)
+ .with("rate-limit:api_v3:#{digest}", 1, expires_in: 60.seconds)
+ end
+
+ it 'never uses the plaintext secret token as a cache key' do
+ allow(Rails.cache).to receive(:increment).and_return(1)
+
+ get :index
+
+ expect(Rails.cache).not_to have_received(:increment)
+ .with(a_string_including(secret_api_key.plaintext_token), anything, anything)
+ end
+
+ it 'refuses the request with a 429 once the limit is exceeded' do
+ allow(Rails.cache).to receive(:increment)
+ .and_return(Spree::Api::Config[:rate_limit_per_secret_key] + 1)
+
+ get :index
+
+ expect(response).to have_http_status(:too_many_requests)
+ expect(json_response[:error][:code]).to eq('rate_limit_exceeded')
+ expect(response.headers['Retry-After']).to eq(Spree::Api::Config[:rate_limit_window].to_s)
+ expect(response.headers['X-RateLimit-Limit']).to eq(Spree::Api::Config[:rate_limit_per_secret_key].to_s)
+ expect(response.headers['X-RateLimit-Remaining']).to eq('0')
+ end
+
+ it 'does not refuse requests at or under the limit' do
+ allow(Rails.cache).to receive(:increment)
+ .and_return(Spree::Api::Config[:rate_limit_per_secret_key])
+
+ get :index
+
+ expect(response).not_to have_http_status(:too_many_requests)
+ end
end
+ end
- describe 'rate limit response format' do
- it 'returns JSON error with rate_limit_exceeded code' do
- response_proc = Spree::Api::V3::BaseController::RATE_LIMIT_RESPONSE
- status, headers, body = response_proc.call
+ describe 'publishable API keys' do
+ describe Spree::Api::V3::Store::CountriesController do
+ controller(Spree::Api::V3::Store::CountriesController) {}
- expect(status).to eq(429)
- expect(headers['Content-Type']).to eq('application/json')
- expect(headers['Retry-After']).to eq(Spree::Api::Config[:rate_limit_window].to_s)
- expect(headers['X-RateLimit-Limit']).to eq(Spree::Api::Config[:rate_limit_per_key].to_s)
- expect(headers['X-RateLimit-Remaining']).to eq('0')
+ render_views
- parsed = JSON.parse(body.first)
- expect(parsed['error']['code']).to eq('rate_limit_exceeded')
- expect(parsed['error']['message']).to be_present
+ include_context 'API v3 Store'
+
+ before do
+ request.headers['X-Spree-Api-Key'] = api_key.token
+ end
+
+ it 'counts against a per-visitor bucket keyed by the key and client IP' do
+ allow(Rails.cache).to receive(:increment).and_return(1)
+
+ get :index
+
+ expect(Rails.cache).to have_received(:increment)
+ .with("rate-limit:api_v3:#{api_key.token}:0.0.0.0", 1, expires_in: 60.seconds)
+ end
+
+ it 'refuses the request with a 429 once the limit is exceeded' do
+ allow(Rails.cache).to receive(:increment)
+ .and_return(Spree::Api::Config[:rate_limit_per_key] + 1)
+
+ get :index
+
+ expect(response).to have_http_status(:too_many_requests)
+ expect(json_response[:error][:code]).to eq('rate_limit_exceeded')
+ expect(response.headers['X-RateLimit-Limit']).to eq(Spree::Api::Config[:rate_limit_per_key].to_s)
+ end
+ end
+ end
+
+ describe 'keyless requests (admin JWT traffic)' do
+ describe Spree::Api::V3::Admin::CountriesController do
+ controller(Spree::Api::V3::Admin::CountriesController) {}
+
+ render_views
+
+ include_context 'API v3 Admin'
+
+ it 'counts against a per-IP bucket when no API key is present' do
+ request.headers['Authorization'] = "Bearer #{admin_jwt_token}"
+ allow(Rails.cache).to receive(:increment).and_return(1)
+
+ get :index
+
+ expect(Rails.cache).to have_received(:increment)
+ .with('rate-limit:api_v3:0.0.0.0', 1, expires_in: 60.seconds)
end
end
end
@@ -35,6 +115,10 @@ RSpec.describe 'Rate Limiting', type: :controller do
expect(Spree::Api::Config[:rate_limit_per_key]).to eq(300)
end
+ it 'exposes rate_limit_per_secret_key as a configurable preference' do
+ expect(Spree::Api::Config[:rate_limit_per_secret_key]).to eq(600)
+ end
+
it 'exposes rate_limit_login as a configurable preference' do
expect(Spree::Api::Config[:rate_limit_login]).to eq(5)
end
@@ -66,6 +150,8 @@ RSpec.describe Spree::Api::V3::Store::CountriesController, 'rate limit headers',
include_context 'API v3 Store'
+ let(:bucket_cache_key) { "rate-limit:api_v3:#{api_key.token}:0.0.0.0" }
+
before do
request.headers['X-Spree-Api-Key'] = api_key.token
end
@@ -80,9 +166,7 @@ RSpec.describe Spree::Api::V3::Store::CountriesController, 'rate limit headers',
it 'sets X-RateLimit-Limit and X-RateLimit-Remaining headers' do
allow(Rails.cache).to receive(:read).and_call_original
- allow(Rails.cache).to receive(:read)
- .with("rate-limit:spree/api/v3/store/countries:#{api_key.token}")
- .and_return(5)
+ allow(Rails.cache).to receive(:read).with(bucket_cache_key).and_return(5)
get :index
@@ -92,9 +176,7 @@ RSpec.describe Spree::Api::V3::Store::CountriesController, 'rate limit headers',
it 'does not set Retry-After header when under the limit' do
allow(Rails.cache).to receive(:read).and_call_original
- allow(Rails.cache).to receive(:read)
- .with("rate-limit:spree/api/v3/store/countries:#{api_key.token}")
- .and_return(5)
+ allow(Rails.cache).to receive(:read).with(bucket_cache_key).and_return(5)
get :index
@@ -103,9 +185,7 @@ RSpec.describe Spree::Api::V3::Store::CountriesController, 'rate limit headers',
it 'decreases X-RateLimit-Remaining based on request count' do
allow(Rails.cache).to receive(:read).and_call_original
- allow(Rails.cache).to receive(:read)
- .with("rate-limit:spree/api/v3/store/countries:#{api_key.token}")
- .and_return(10)
+ allow(Rails.cache).to receive(:read).with(bucket_cache_key).and_return(10)
get :index
@@ -115,9 +195,7 @@ RSpec.describe Spree::Api::V3::Store::CountriesController, 'rate limit headers',
it 'sets Retry-After when limit is reached' do
limit = Spree::Api::Config[:rate_limit_per_key]
allow(Rails.cache).to receive(:read).and_call_original
- allow(Rails.cache).to receive(:read)
- .with("rate-limit:spree/api/v3/store/countries:#{api_key.token}")
- .and_return(limit)
+ allow(Rails.cache).to receive(:read).with(bucket_cache_key).and_return(limit)
get :index