fix: avoid unintended effects on load_config_initializers and other gems load order

Because of the sort algorithm rails uses to satisfy `after` and `before`
constraints, gems can have unintended effects on others. See
0a120a818d

Prefer making rack-attack middleware idempotent instead of relying on
the load order and the contents of the middleware stack too much.

closes #452
closes #456
This commit is contained in:
Gonzalo Rodriguez 2019-10-29 15:45:26 -03:00
parent 9bfec1ac70
commit e3056e737f
No known key found for this signature in database
GPG key ID: 5DB8B81B049B8AB1
4 changed files with 6 additions and 17 deletions

View file

@ -153,8 +153,9 @@ module Rack
end
def call(env)
return @app.call(env) unless self.class.enabled
return @app.call(env) if !self.class.enabled || env["rack.attack.called"]
env["rack.attack.called"] = true
env['PATH_INFO'] = PathNormalizer.normalize_path(env['PATH_INFO'])
request = Rack::Attack::Request.new(env)

View file

@ -3,17 +3,9 @@
module Rack
class Attack
class Railtie < ::Rails::Railtie
initializer 'rack.attack.middleware', after: :load_config_initializers, before: :build_middleware_stack do |app|
initializer "rack-attack.middleware" do |app|
if Gem::Version.new(::Rails::VERSION::STRING) >= Gem::Version.new("5.1")
middlewares = app.config.middleware
operations = middlewares.send(:operations) + middlewares.send(:delete_operations)
use_middleware = operations.none? do |operation|
middleware = operation[1]
middleware.include?(Rack::Attack)
end
middlewares.use(Rack::Attack) if use_middleware
app.middleware.use(Rack::Attack)
end
end
end

View file

@ -18,12 +18,6 @@ if defined?(Rails)
assert_equal 1, @app.middleware.count(Rack::Attack)
end
it "is not added when it was added explicitly" do
@app.config.middleware.use(Rack::Attack)
@app.initialize!
assert_equal 1, @app.middleware.count(Rack::Attack)
end
it "is not added when it was explicitly deleted" do
@app.config.middleware.delete(Rack::Attack)
@app.initialize!

View file

@ -46,6 +46,8 @@ class MiniTest::Spec
Rack::Builder.new do
# Use Rack::Lint to test that rack-attack is complying with the rack spec
use Rack::Lint
# Intentionally added twice to test idempotence property
use Rack::Attack
use Rack::Attack
use Rack::Lint