Use rack_attack_enabled?

We cannot enable rack attack during the tests as it interferes with features spec.
So we add a flag to enable it during the runtime.
This commit is contained in:
simon lehericey 2019-08-19 15:15:50 +02:00
parent 0f0fecdb25
commit 86d968bb8e
2 changed files with 29 additions and 22 deletions

View file

@ -1,25 +1,27 @@
if Rails.env.production?
class Rack::Attack
throttle('/users/sign_in/ip', limit: 5, period: 20.seconds) do |req|
if req.path == '/users/sign_in' && req.post?
req.remote_ip
end
end
throttle('stats/ip', limit: 5, period: 20.seconds) do |req|
if req.path == '/stats'
req.remote_ip
end
end
throttle('contact/ip', limit: 5, period: 20.seconds) do |req|
if req.path == '/contact' && req.post?
req.remote_ip
end
end
Rack::Attack.safelist('allow from localhost') do |req|
IPService.ip_trusted?(req.remote_ip)
class Rack::Attack
throttle('/users/sign_in/ip', limit: 5, period: 20.seconds) do |req|
if req.path == '/users/sign_in' && req.post? && rack_attack_enabled?
req.remote_ip
end
end
throttle('stats/ip', limit: 5, period: 20.seconds) do |req|
if req.path == '/stats' && rack_attack_enabled?
req.remote_ip
end
end
throttle('contact/ip', limit: 5, period: 20.seconds) do |req|
if req.path == '/contact' && req.post? && rack_attack_enabled?
req.remote_ip
end
end
Rack::Attack.safelist('allow from localhost') do |req|
IPService.ip_trusted?(req.remote_ip)
end
def self.rack_attack_enabled?
ENV['RACK_ATTACK_ENABLE'] == 'true'
end
end

View file

@ -6,10 +6,15 @@ describe Rack::Attack, type: :request do
let(:ip) { "1.2.3.4" }
before(:each) do
ENV['RACK_ATTACK_ENABLE'] = 'true'
setup_rack_attack_cache_store
avoid_test_overlaps_in_cache
end
after do
ENV['RACK_ATTACK_ENABLE'] = 'false'
end
def setup_rack_attack_cache_store
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
end