Can rack_attack safelist a dynamically-created list of IPs (such as IPs recently used by admins)?

484 Views Asked by At

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
1

There are 1 best solutions below

1
On BEST ANSWER

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