From 0c810fe031b49b2fe91a05cbb8cf2f6a67211d20 Mon Sep 17 00:00:00 2001 From: Brian Kelly Date: Mon, 29 Jul 2024 14:58:32 -0500 Subject: [PATCH] Adds rack-attack to throttle requests and use memcached for it (#337) --- 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 bf99e93f..339fc110 100644 --- a/Gemfile +++ b/Gemfile @@ -22,6 +22,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 fd13cca1..db07ce54 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -377,6 +377,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) @@ -597,6 +599,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