Help users understand more clearly when the store is misconfigured

This commit is contained in:
Gonzalo Rodriguez 2018-02-01 10:06:39 -03:00
parent 9f79ab272e
commit 7bb7a05987
4 changed files with 38 additions and 7 deletions

View file

@ -2,6 +2,9 @@ require 'rack'
require 'forwardable'
class Rack::Attack
class MisconfiguredStoreError < StandardError; end
class MissingStoreError < StandardError; end
autoload :Cache, 'rack/attack/cache'
autoload :PathNormalizer, 'rack/attack/path_normalizer'
autoload :Check, 'rack/attack/check'

View file

@ -46,15 +46,20 @@ module Rack
end
def do_count(key, expires_in)
result = store.increment(key, 1, :expires_in => expires_in)
if store.nil?
raise Rack::Attack::MissingStoreError
elsif !store.respond_to?(:increment)
raise Rack::Attack::MisconfiguredStoreError, "Store needs to respond to #increment"
else
result = store.increment(key, 1, :expires_in => expires_in)
# NB: Some stores return nil when incrementing uninitialized values
if result.nil?
store.write(key, 1, :expires_in => expires_in)
# NB: Some stores return nil when incrementing uninitialized values
if result.nil?
store.write(key, 1, :expires_in => expires_in)
end
result || 1
end
result || 1
end
end
end
end

View file

@ -0,0 +1,20 @@
require_relative 'spec_helper'
describe 'Store configuration' do
it "gives clear error when store it's not configured if it's needed" do
Rack::Attack.throttle('ip/sec', limit: 1, period: 60) { |req| req.ip }
assert_raises(Rack::Attack::MissingStoreError) do
get '/'
end
end
it "gives clear error when store isn't configured properly" do
Rack::Attack.cache.store = Object.new
Rack::Attack.throttle('ip/sec', limit: 1, period: 60) { |req| req.ip }
assert_raises(Rack::Attack::MisconfiguredStoreError) do
get '/'
end
end
end

View file

@ -19,7 +19,10 @@ class MiniTest::Spec
include Rack::Test::Methods
after { Rack::Attack.clear! }
after do
Rack::Attack.clear!
Rack::Attack.instance_variable_set(:@cache, nil)
end
def app
Rack::Builder.new {