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.

Add rate limits to admin user login and password reset (#14170)

Łukasz Adamczykfffaea96fa08
diff --git a/spree/admin/app/controllers/concerns/spree/admin/auth_rate_limiting.rb b/spree/admin/app/controllers/concerns/spree/admin/auth_rate_limiting.rb
new file mode 100644
index 0000000000..58c64508e6
--- /dev/null
+++ b/spree/admin/app/controllers/concerns/spree/admin/auth_rate_limiting.rb
@@ -0,0 +1,58 @@
+module Spree
+ module Admin
+ module AuthRateLimiting
+ extend ActiveSupport::Concern
+
+ class_methods do
+ # @param limit_preference [Symbol] e.g. :rate_limit_login / :rate_limit_password_reset
+ # @param redirect_to [Proc] evaluated in controller context to the path to bounce
+ # back to when rate limited, e.g. `-> { new_session_path(resource_name) }`.
+ # @return [void]
+ def auth_rate_limit(limit_preference, redirect_to:)
+ limit = Spree::Admin::RuntimeConfig[limit_preference] || 5
+ window = (Spree::Admin::RuntimeConfig[:rate_limit_window] || 60).seconds
+ prefix = limit_preference.to_s # unique namespace per controller/action
+
+ # By IP — always present; backstops blank-email floods.
+ rate_limit(
+ to: limit,
+ within: window,
+ by: -> { "#{prefix}-ip:#{request.remote_ip}" },
+ with: -> { admin_auth_rate_limit_response(redirect_to) },
+ store: Rails.cache,
+ only: :create
+ )
+
+ # By submitted email (case-insensitive). Falls back to per-IP bucketing when
+ # the email is blank, so blank submissions don't all share one global bucket.
+ rate_limit(
+ to: limit,
+ within: window,
+ by: lambda {
+ email = admin_auth_rate_limit_email
+ email.present? ? "#{prefix}-email:#{email}" : "#{prefix}-email-ip:#{request.remote_ip}"
+ },
+ with: -> { admin_auth_rate_limit_response(redirect_to) },
+ store: Rails.cache,
+ only: :create
+ )
+ end
+ end
+
+ private
+
+ # Email is read via Devise's `resource_params` so it works regardless of the
+ # configured admin user class / resource param key.
+ def admin_auth_rate_limit_email
+ resource_params[:email].to_s.strip.downcase.presence
+ rescue StandardError
+ nil
+ end
+
+ def admin_auth_rate_limit_response(redirect_path)
+ flash[:alert] = I18n.t('devise.failure.too_many_attempts')
+ redirect_to instance_exec(&redirect_path)
+ end
+ end
+ end
+end
diff --git a/spree/admin/app/controllers/spree/admin/user_passwords_controller.rb b/spree/admin/app/controllers/spree/admin/user_passwords_controller.rb
index 03d89b37e6..8a5cf31240 100644
--- a/spree/admin/app/controllers/spree/admin/user_passwords_controller.rb
+++ b/spree/admin/app/controllers/spree/admin/user_passwords_controller.rb
@@ -1,8 +1,12 @@
module Spree
module Admin
class UserPasswordsController < defined?(Devise::PasswordsController) ? Devise::PasswordsController : Spree::Admin::BaseController
+ include Spree::Admin::AuthRateLimiting
+
layout 'spree/minimal'
+ auth_rate_limit :rate_limit_password_reset, redirect_to: -> { new_password_path(resource_name) }
+
def create
self.resource = resource_class.send_reset_password_instructions(resource_params)
yield resource if block_given?
diff --git a/spree/admin/app/controllers/spree/admin/user_sessions_controller.rb b/spree/admin/app/controllers/spree/admin/user_sessions_controller.rb
index b93b79d210..5b21537fd8 100644
--- a/spree/admin/app/controllers/spree/admin/user_sessions_controller.rb
+++ b/spree/admin/app/controllers/spree/admin/user_sessions_controller.rb
@@ -1,8 +1,12 @@
module Spree
module Admin
class UserSessionsController < defined?(Devise::SessionsController) ? Devise::SessionsController : Spree::Admin::BaseController
+ include Spree::Admin::AuthRateLimiting
+
layout 'spree/minimal'
+ auth_rate_limit :rate_limit_login, redirect_to: -> { new_session_path(resource_name) }
+
# We need to overwrite this action because `return_to` url may be in a different domain
# So we need to pass `allow_other_host` option to `redirect_to` method
def create
diff --git a/spree/admin/lib/spree/admin/runtime_configuration.rb b/spree/admin/lib/spree/admin/runtime_configuration.rb
index 53015f5bdf..52db4804e9 100644
--- a/spree/admin/lib/spree/admin/runtime_configuration.rb
+++ b/spree/admin/lib/spree/admin/runtime_configuration.rb
@@ -17,6 +17,11 @@ module Spree
preference :legacy_sidebar_navigation, :boolean, default: false
preference :reports_line_items_limit, :integer, default: 1000
+
+ # Brute-force rate limiting for the admin dashboard auth endpoints (login / password reset).
+ preference :rate_limit_window, :integer, default: 60 # window in seconds
+ preference :rate_limit_login, :integer, default: 5 # per IP and per email
+ preference :rate_limit_password_reset, :integer, default: 3 # per IP and per email
end
end
end
diff --git a/spree/admin/spec/controllers/spree/admin/auth_rate_limiting_spec.rb b/spree/admin/spec/controllers/spree/admin/auth_rate_limiting_spec.rb
new file mode 100644
index 0000000000..43bbaad6e7
--- /dev/null
+++ b/spree/admin/spec/controllers/spree/admin/auth_rate_limiting_spec.rb
@@ -0,0 +1,132 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Admin::AuthRateLimiting, type: :controller do
+ # Counters live in Rails.cache, which is :null_store in the test env.
+ # Replace increment with a real in-memory counter so the rate limit trips.
+ let(:counts) { Hash.new(0) }
+
+ before do
+ allow(Rails.cache).to receive(:increment) { |key, amount = 1, **_opts| counts[key] += amount }
+ end
+
+ it 'includes the AuthRateLimiting concern in devise controllers' do
+ expect(Spree::Admin::UserSessionsController.include?(described_class)).to be(true)
+ expect(Spree::Admin::UserPasswordsController.include?(described_class)).to be(true)
+ end
+
+ describe 'login rate limit' do
+ controller(ActionController::Base) do
+ include Spree::Admin::AuthRateLimiting
+
+ auth_rate_limit :rate_limit_login, redirect_to: -> { new_session_path(resource_name) }
+
+ def create
+ head :ok
+ end
+
+ private
+
+ # Minimal Devise stand-ins used by the concern.
+ def resource_name
+ :admin_user
+ end
+
+ def resource_params
+ params.fetch(:admin_user, {})
+ end
+
+ def new_session_path(_resource)
+ '/admin_user/sign_in'
+ end
+
+ def new_password_path(_resource)
+ '/admin_user/password'
+ end
+ end
+
+ let(:limit) { Spree::Admin::RuntimeConfig[:rate_limit_login] }
+
+ before { routes.draw { post 'create' => 'anonymous#create' } }
+
+ def attempt(email: nil, ip: '203.0.113.1')
+ request.remote_addr = ip
+ post :create, params: { admin_user: { email: email } }
+ end
+
+ it 'allows attempts up to the per-IP limit, then rate limits the next one' do
+ limit.times { attempt(ip: '203.0.113.7') }
+ expect(response).to have_http_status(:ok)
+
+ attempt(ip: '203.0.113.7')
+ expect(response).to redirect_to('/admin_user/sign_in')
+ expect(flash[:alert]).to eq(I18n.t('devise.failure.too_many_attempts'))
+ end
+
+ it 'rate limits a single account across rotating IPs (per-email bucket)' do
+ limit.times { |i| attempt(email: '[email protected]', ip: "198.51.100.#{i}") }
+ expect(response).to have_http_status(:ok)
+
+ attempt(email: '[email protected]', ip: '198.51.100.250')
+ expect(response).to redirect_to('/admin_user/sign_in')
+ end
+
+ it 'normalizes email case ([email protected] and [email protected] share a bucket)' do
+ limit.times { |i| attempt(email: (i.even? ? '[email protected]' : '[email protected]'), ip: "198.51.100.#{i}") }
+ attempt(email: '[email protected]', ip: '198.51.100.250')
+ expect(response).to redirect_to('/admin_user/sign_in')
+ end
+
+ it 'does not globally lock out blank-email attempts from different IPs' do
+ (limit + 5).times { |i| attempt(email: '', ip: "10.0.0.#{i}") }
+ expect(response).to have_http_status(:ok)
+ end
+ end
+
+ describe 'password-reset rate limit' do
+ controller(ActionController::Base) do
+ include Spree::Admin::AuthRateLimiting
+
+ auth_rate_limit :rate_limit_password_reset, redirect_to: -> { new_password_path(resource_name) }
+
+ def create
+ head :ok
+ end
+
+ private
+
+ def resource_name
+ :admin_user
+ end
+
+ def resource_params
+ params.fetch(:admin_user, {})
+ end
+
+ def new_session_path(_resource)
+ '/admin_user/sign_in'
+ end
+
+ def new_password_path(_resource)
+ '/admin_user/password'
+ end
+ end
+
+ let(:limit) { Spree::Admin::RuntimeConfig[:rate_limit_password_reset] }
+
+ before { routes.draw { post 'create' => 'anonymous#create' } }
+
+ def attempt(ip:)
+ request.remote_addr = ip
+ post :create, params: { admin_user: { email: '[email protected]' } }
+ end
+
+ it 'rate limits past the password-reset limit and redirects to the password page' do
+ limit.times { |i| attempt(ip: "198.51.100.#{i}") }
+ expect(response).to have_http_status(:ok)
+
+ attempt(ip: '198.51.100.250')
+ expect(response).to redirect_to('/admin_user/password')
+ expect(flash[:alert]).to eq(I18n.t('devise.failure.too_many_attempts'))
+ end
+ end
+end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 59c924b221..3d08e1f166 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -578,6 +578,7 @@ en:
invalid_token: Invalid authentication token.
locked: Your account is locked.
timeout: Your session expired, please sign in again to continue.
+ too_many_attempts: Too many attempts. Please wait a moment and try again.
unauthenticated: You need to sign in or sign up before continuing.
unconfirmed: You have to confirm your account before continuing.
mailer: