mirror of
https://github.com/samsonjs/rack-attack.git
synced 2026-03-25 09:25:49 +00:00
Provide shorthand to blocklist an entire IP subnet
This commit is contained in:
parent
dccce4ee3d
commit
aec03047c5
3 changed files with 46 additions and 1 deletions
|
|
@ -6,6 +6,7 @@ All notable changes to this project will be documented in this file.
|
|||
### Added
|
||||
|
||||
- Shorthand for blocking IP addresses `Rack::Attack.blocklist_ip("1.2.3.4")`
|
||||
- Shorthand for blocking IP subnets `Rack::Attack.blocklist_ip("1.2.0.0/16")`
|
||||
- Throw helpful error message when using `allow2ban` but cache store is misconfigured ([#315](https://github.com/kickstarter/rack-attack/issues/315))
|
||||
- Throw helpful error message when using `fail2ban` but cache store is misconfigured ([#315](https://github.com/kickstarter/rack-attack/issues/315))
|
||||
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ class Rack::Attack
|
|||
|
||||
def blocklist_ip(ip)
|
||||
@ip_blocklists ||= []
|
||||
ip_blocklist_proc = lambda { |request| request.ip == ip }
|
||||
ip_blocklist_proc = lambda { |request| IPAddr.new(ip).include?(IPAddr.new(request.ip)) }
|
||||
@ip_blocklists << Blocklist.new(nil, ip_blocklist_proc)
|
||||
end
|
||||
|
||||
|
|
|
|||
44
spec/acceptance/blocking_subnet_spec.rb
Normal file
44
spec/acceptance/blocking_subnet_spec.rb
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
require_relative "../spec_helper"
|
||||
|
||||
describe "Blocking an IP subnet" do
|
||||
before do
|
||||
Rack::Attack.blocklist_ip("1.2.3.4/31")
|
||||
end
|
||||
|
||||
it "forbids request if IP is inside the subnet" do
|
||||
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
|
||||
|
||||
assert_equal 403, last_response.status
|
||||
end
|
||||
|
||||
it "forbids request for another IP in the subnet" do
|
||||
get "/", {}, "REMOTE_ADDR" => "1.2.3.5"
|
||||
|
||||
assert_equal 403, last_response.status
|
||||
end
|
||||
|
||||
it "succeeds if IP is outside the subnet" do
|
||||
get "/", {}, "REMOTE_ADDR" => "1.2.3.6"
|
||||
|
||||
assert_equal 200, last_response.status
|
||||
end
|
||||
|
||||
it "notifies when the request is blocked" do
|
||||
notified = false
|
||||
notification_type = nil
|
||||
|
||||
ActiveSupport::Notifications.subscribe("rack.attack") do |_name, _start, _finish, _id, request|
|
||||
notified = true
|
||||
notification_type = request.env["rack.attack.match_type"]
|
||||
end
|
||||
|
||||
get "/", {}, "REMOTE_ADDR" => "5.6.7.8"
|
||||
|
||||
refute notified
|
||||
|
||||
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
|
||||
|
||||
assert notified
|
||||
assert_equal :blocklist, notification_type
|
||||
end
|
||||
end
|
||||
Loading…
Reference in a new issue