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 Rate Limit headers to API (#13729)

Damian Legawiec05b5fa26cdd9
diff --git a/docs/api-reference/store-api/rate-limitting.mdx b/docs/api-reference/store-api/rate-limitting.mdx
index f7ecdb97bc..b9e1b4e88f 100644
--- a/docs/api-reference/store-api/rate-limitting.mdx
+++ b/docs/api-reference/store-api/rate-limitting.mdx
@@ -20,6 +20,24 @@ The global rate limit is tracked by your publishable API key (`X-Spree-Api-Key`)
Authentication endpoints have stricter per-IP limits to prevent brute-force attacks.
+## Rate Limit Headers
+
+Every Store API response includes headers that show your current rate limit usage:
+
+| Header | Description |
+|--------|-------------|
+| `X-RateLimit-Limit` | Maximum number of requests allowed per window |
+| `X-RateLimit-Remaining` | Number of requests remaining in the current window |
+| `Retry-After` | Seconds to wait before retrying (only present when limit is reached) |
+
+Example response headers:
+
+```
+HTTP/1.1 200 OK
+X-RateLimit-Limit: 300
+X-RateLimit-Remaining: 295
+```
+
## Rate Limit Response
When you exceed the rate limit, the API returns a `429 Too Many Requests` response:
@@ -33,11 +51,13 @@ When you exceed the rate limit, the API returns a `429 Too Many Requests` respon
}
```
-The response includes a `Retry-After` header indicating how many seconds to wait before retrying:
+The response includes rate limit headers and a `Retry-After` header indicating how many seconds to wait before retrying:
```
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
+X-RateLimit-Limit: 300
+X-RateLimit-Remaining: 0
Retry-After: 60
```
@@ -68,6 +88,7 @@ If you're self-hosting Spree, you can adjust rate limits in your initializer:
```ruby
# config/initializers/spree.rb
Spree::Api::Config[:rate_limit_per_key] = 300 # Global limit per API key
+Spree::Api::Config[:rate_limit_window] = 60 # Window in seconds
Spree::Api::Config[:rate_limit_login] = 5 # Login attempts per IP
Spree::Api::Config[:rate_limit_register] = 3 # Registration attempts per IP
Spree::Api::Config[:rate_limit_refresh] = 10 # Token refresh per IP
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
new file mode 100644
index 0000000000..5df1b64f10
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/rate_limit_headers.rb
@@ -0,0 +1,31 @@
+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.
+ module RateLimitHeaders
+ extend ActiveSupport::Concern
+
+ included do
+ after_action :set_rate_limit_headers
+ end
+
+ private
+
+ 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(':')
+ count = Rails.cache.read(cache_key)
+
+ return if count.nil?
+
+ response.headers['X-RateLimit-Limit'] = limit.to_s
+ response.headers['X-RateLimit-Remaining'] = [limit - count.to_i, 0].max.to_s
+ response.headers['Retry-After'] = Spree::Api::Config[:rate_limit_window].to_s if count.to_i >= limit
+ end
+ end
+ end
+ end
+end
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 e6d79d2013..90ad604fd0 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
@@ -4,10 +4,10 @@ module Spree
module Store
class AuthController < Store::BaseController
# Tighter rate limits for auth endpoints (per IP to prevent brute force)
- rate_limit to: Spree::Api::Config[:rate_limit_login], within: 1.minute, store: Rails.cache, only: :create, with: RATE_LIMIT_RESPONSE
- rate_limit to: Spree::Api::Config[:rate_limit_register], within: 1.minute, store: Rails.cache, only: :register, with: RATE_LIMIT_RESPONSE
- rate_limit to: Spree::Api::Config[:rate_limit_refresh], within: 1.minute, store: Rails.cache, only: :refresh, with: RATE_LIMIT_RESPONSE
- rate_limit to: Spree::Api::Config[:rate_limit_oauth], within: 1.minute, store: Rails.cache, only: :oauth_callback, 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: :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: :register, 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_oauth], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :oauth_callback, with: RATE_LIMIT_RESPONSE
skip_before_action :authenticate_user, only: [:create, :register, :oauth_callback]
prepend_before_action :require_authentication!, only: [:refresh]
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 99710d878d..e160e640d7 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,13 +3,23 @@ module Spree
module V3
module Store
class BaseController < Spree::Api::V3::BaseController
+ include Spree::Api::V3::RateLimitHeaders
+
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.' } }
- [429, { 'Content-Type' => 'application/json', 'Retry-After' => '60' }, [body.to_json]]
+ 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]]
}
# Global rate limit per publishable API key
- rate_limit to: Spree::Api::Config[:rate_limit_per_key], within: 1.minute,
+ 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
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 188238daf9..55fc84e6b1 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
@@ -3,6 +3,16 @@ module Spree
module V3
module Store
class ResourceController < Spree::Api::V3::ResourceController
+ include Spree::Api::V3::RateLimitHeaders
+
+ RATE_LIMIT_RESPONSE = Store::BaseController::RATE_LIMIT_RESPONSE
+
+ # Global rate limit per publishable API key
+ 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
+
# Require publishable API key for all Store API requests
before_action :authenticate_api_key!
end
diff --git a/spree/api/lib/spree/api/configuration.rb b/spree/api/lib/spree/api/configuration.rb
index ed61b423e5..a4701c4af5 100644
--- a/spree/api/lib/spree/api/configuration.rb
+++ b/spree/api/lib/spree/api/configuration.rb
@@ -11,8 +11,9 @@ module Spree
preference :jwt_expiration, :integer, default: 3600 # 1 hour in seconds
- # Rate limiting (requests per minute)
+ # Rate limiting
preference :rate_limit_per_key, :integer, default: 300 # per publishable API key
+ 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
preference :rate_limit_refresh, :integer, default: 10 # 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 9bbbfb464d..18ccc35cc4 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
@@ -19,7 +19,9 @@ RSpec.describe 'Rate Limiting', type: :controller do
expect(status).to eq(429)
expect(headers['Content-Type']).to eq('application/json')
- expect(headers['Retry-After']).to eq('60')
+ 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')
parsed = JSON.parse(body.first)
expect(parsed['error']['code']).to eq('rate_limit_exceeded')
@@ -49,6 +51,10 @@ RSpec.describe 'Rate Limiting', type: :controller do
expect(Spree::Api::Config[:rate_limit_oauth]).to eq(5)
end
+ it 'exposes rate_limit_window as a configurable preference' do
+ expect(Spree::Api::Config[:rate_limit_window]).to eq(60)
+ end
+
it 'allows overriding rate limit values' do
original = Spree::Api::Config[:rate_limit_per_key]
Spree::Api::Config[:rate_limit_per_key] = 500
@@ -58,3 +64,68 @@ RSpec.describe 'Rate Limiting', type: :controller do
end
end
end
+
+RSpec.describe Spree::Api::V3::Store::StoresController, 'rate limit headers', type: :controller do
+ render_views
+
+ include_context 'API v3 Store'
+
+ before do
+ request.headers['X-Spree-Api-Key'] = api_key.token
+ end
+
+ it 'skips rate limit headers when cache has no counter' do
+ get :show
+
+ expect(response.headers['X-RateLimit-Limit']).to be_nil
+ expect(response.headers['X-RateLimit-Remaining']).to be_nil
+ expect(response.headers['Retry-After']).to be_nil
+ end
+
+ 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/stores:#{api_key.token}")
+ .and_return(5)
+
+ get :show
+
+ expect(response.headers['X-RateLimit-Limit']).to eq(Spree::Api::Config[:rate_limit_per_key].to_s)
+ expect(response.headers['X-RateLimit-Remaining'].to_i).to eq(Spree::Api::Config[:rate_limit_per_key] - 5)
+ end
+
+ 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/stores:#{api_key.token}")
+ .and_return(5)
+
+ get :show
+
+ expect(response.headers['Retry-After']).to be_nil
+ end
+
+ 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/stores:#{api_key.token}")
+ .and_return(10)
+
+ get :show
+
+ expect(response.headers['X-RateLimit-Remaining'].to_i).to eq(Spree::Api::Config[:rate_limit_per_key] - 10)
+ end
+
+ 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/stores:#{api_key.token}")
+ .and_return(limit)
+
+ get :show
+
+ expect(response.headers['Retry-After']).to eq(Spree::Api::Config[:rate_limit_window].to_s)
+ expect(response.headers['X-RateLimit-Remaining']).to eq('0')
+ end
+end