1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
# frozen_string_literal: true
require_relative "../spec_helper"
describe "Customizing throttled response" do
before do
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
Rack::Attack.throttle("by ip", limit: 1, period: 60) do |request|
request.ip
end
end
it "can be customized" do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 429, last_response.status
Rack::Attack.throttled_responder = lambda do |_req|
[503, {}, ["Throttled"]]
end
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 503, last_response.status
assert_equal "Throttled", last_response.body
end
it "exposes match data" do
matched = nil
match_type = nil
match_data = nil
match_discriminator = nil
Rack::Attack.throttled_responder = lambda do |req|
matched = req.env['rack.attack.matched']
match_type = req.env['rack.attack.match_type']
match_data = req.env['rack.attack.match_data']
match_discriminator = req.env['rack.attack.match_discriminator']
[429, {}, ["Throttled"]]
end
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal "by ip", matched
assert_equal :throttle, match_type
assert_equal 60, match_data[:period]
assert_equal 1, match_data[:limit]
assert_equal 2, match_data[:count]
assert_equal "1.2.3.4", match_discriminator
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 3, match_data[:count]
end
it "supports old style" do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 429, last_response.status
silence_warnings do
Rack::Attack.throttled_response = lambda do |_req|
[503, {}, ["Throttled"]]
end
end
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 503, last_response.status
assert_equal "Throttled", last_response.body
end
end
|