From 295404d66e8858b440f26a961c9c7cbce9313646 Mon Sep 17 00:00:00 2001 From: Brian Kelly Date: Thu, 25 Jul 2024 08:40:34 -0500 Subject: [PATCH] Adds rack-attack to throttle requests and use memcached for it --- Gemfile | 1 + Gemfile.lock | 3 +++ config/environments/production.rb | 2 +- config/initializers/rack_attack.rb | 8 ++++++++ 4 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 config/initializers/rack_attack.rb diff --git a/Gemfile b/Gemfile index 9dc3bbe4..a517340c 100644 --- a/Gemfile +++ b/Gemfile @@ -21,6 +21,7 @@ gem 'omniauth', '1.9.2' gem 'omniauth-oauth2' gem 'omniauth-rails_csrf_protection' gem 'puma', '~> 5.0' +gem 'rack-attack' gem 'rails', '~> 7.0.6' gem 'rsolr', '>= 1.0', '< 3' gem 'sassc-rails', '~> 2.1' diff --git a/Gemfile.lock b/Gemfile.lock index 52944dd5..c9c2e17c 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -376,6 +376,8 @@ GEM nio4r (~> 2.0) racc (1.8.0) rack (2.2.9) + rack-attack (6.7.0) + rack (>= 1.0, < 4) rack-test (2.1.0) rack (>= 1.3) rails (7.0.8.4) @@ -595,6 +597,7 @@ DEPENDENCIES omniauth-oauth2 omniauth-rails_csrf_protection puma (~> 5.0) + rack-attack rails (~> 7.0.6) rsolr (>= 1.0, < 3) rspec-rails diff --git a/config/environments/production.rb b/config/environments/production.rb index 186e2a07..6ddc47f6 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -56,7 +56,7 @@ config.log_tags = [ :request_id ] # Use a different cache store in production. - # config.cache_store = :mem_cache_store + config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment). # config.active_job.queue_adapter = :resque diff --git a/config/initializers/rack_attack.rb b/config/initializers/rack_attack.rb new file mode 100644 index 00000000..e89455b7 --- /dev/null +++ b/config/initializers/rack_attack.rb @@ -0,0 +1,8 @@ +class Rack::Attack + # Throttle all requests by IP (60rpm) + # + # Key: "rack::attack:#{Time.now.to_i/:period}:req/ip:#{req.ip}" + throttle('req/ip', limit: 300, period: 5.minutes) do |req| + req.ip unless req.path.start_with?('/assets') + end +end