|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require_relative '../spec_helper' |
| 4 | + |
| 5 | +describe '.with_calling' do |
| 6 | + |
| 7 | + it 'can specify a calling scope' do |
| 8 | + refute Rack::Attack.calling? |
| 9 | + assert_nil Thread.current['rack.attack.calling'] |
| 10 | + |
| 11 | + Rack::Attack.with_calling do |
| 12 | + assert Rack::Attack.calling? |
| 13 | + assert Thread.current['rack.attack.calling'] |
| 14 | + end |
| 15 | + |
| 16 | + refute Rack::Attack.calling? |
| 17 | + assert_nil Thread.current['rack.attack.calling'] |
| 18 | + end |
| 19 | + |
| 20 | + it 'uses RequestStore if available' do |
| 21 | + store = double('RequestStore', store: {}) |
| 22 | + stub_const('RequestStore', store) |
| 23 | + |
| 24 | + refute Rack::Attack.calling? |
| 25 | + assert_nil Thread.current['rack.attack.calling'] |
| 26 | + |
| 27 | + Rack::Attack.with_calling do |
| 28 | + assert Rack::Attack.calling? |
| 29 | + assert store.store['rack.attack.calling'] |
| 30 | + assert_nil Thread.current['rack.attack.calling'] |
| 31 | + end |
| 32 | + |
| 33 | + refute Rack::Attack.calling? |
| 34 | + assert_nil store.store['rack.attack.calling'] |
| 35 | + assert_nil Thread.current['rack.attack.calling'] |
| 36 | + end |
| 37 | + |
| 38 | + it 'is true within error handler scope' do |
| 39 | + allow(Rack::Attack.cache.store).to receive(:read).and_raise(RuntimeError) |
| 40 | + |
| 41 | + Rack::Attack.blocklist("fail2ban pentesters") do |request| |
| 42 | + Rack::Attack::Fail2Ban.filter(request.ip, maxretry: 0, bantime: 600, findtime: 30) { true } |
| 43 | + end |
| 44 | + |
| 45 | + error_raised = false |
| 46 | + Rack::Attack.error_handler = -> (_error) do |
| 47 | + error_raised = true |
| 48 | + assert Rack::Attack.calling? |
| 49 | + end |
| 50 | + |
| 51 | + refute Rack::Attack.calling? |
| 52 | + |
| 53 | + get "/", {}, "REMOTE_ADDR" => "1.2.3.4" |
| 54 | + |
| 55 | + assert error_raised |
| 56 | + refute Rack::Attack.calling? |
| 57 | + end |
| 58 | +end |
0 commit comments