2

The rack_attack gem offers easy safelisting of a static list of IPs for example:

  # config/rack_attack.rb
  ok_ips="1.1.1.1, 2.2.2.2, 3.3.3.3"

  Rack::Attack.safelist('safelist these IPs') do |req|
    ok_ips.include?(req.ip)
  end

But is there any way to dynamically update a list of safelisted IPs without requiring a server restart to take effect?

For example, if the safelisted IPs are in Memcache under the key "OK_IPS", whatever IPs are in Memcache as of the last server restart will be safelisted, but any newly-added IPs will not be safelisted until the next server restart.

  # config/rack_attack.rb
  ok_ips = my_cache_read_method("OK_IPS") # "1.1.1.1, 2.2.2.2, 3.3.3.3 etc etc"

  Rack::Attack.safelist('safelist these IPs') do |req|
    ok_ips.include?(req.ip)  # IPs added after server restart wont be included yet
  end
Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
jpw
  • 18,697
  • 25
  • 111
  • 187
  • The only thing I can find in the readme is that the Throttle, allow2ban and fail2ban state is stored in a configurable cache. Maybe try setting `Rack::Attack.cache.store = nil` or use duck typing to create a cache that never caches if that causes errors? – max Apr 15 '21 at 09:52
  • One other thing - if you load the definition of the whitelist into the the block itself is it not evaluated per request? `Rack::Attack.safelist('safelist these IPs') do |req|; ok_ips = my_cache_read_method("OK_IPS"); end` – max Apr 15 '21 at 12:52
  • great idea, max. i will try fetching it inside the request. and will post back here. – jpw Apr 15 '21 at 20:46
  • bingo. thanks. if you feel like making that an answer i'll accept it. – jpw Apr 15 '21 at 20:55

1 Answers1

1

Apparently if you move the method into the block it will be evaluated per request instead:

Rack::Attack.safelist('safelist these IPs') do |req|
  ok_ips = my_cache_read_method("OK_IPS") # "1.1.1.1, 2.2.2.2, 3.3.3.3 etc etc"
  ok_ips.include?(req.ip)  # IPs added after server restart wont be included yet
end
max
  • 96,212
  • 14
  • 104
  • 165
  • yes, and since i'm using Memcache as cache, there's no meaningful impact on per-request performance – jpw Apr 15 '21 at 21:21