Skip to content

Commit

Permalink
Merge pull request #66 from digitaloceancloud/master
Browse files Browse the repository at this point in the history
Add instrumentation support
  • Loading branch information
rkh committed Sep 3, 2013
2 parents d9be224 + 4121d4c commit c77a6f8
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
8 changes: 8 additions & 0 deletions rack-protection/README.md
Expand Up @@ -80,3 +80,11 @@ Prevented by:

gem install rack-protection

# Instrumentation

Instrumentation is enabled by passing in an instrumenter as an option.
```
use Rack::Protection, instrumenter: ActiveSupport::Notifications
```

The instrumenter is passed a namespace (String) and environment (Hash). The namespace is 'rack.protection' and the attack type can be obtained from the environment key 'rack.protection.attack'.
7 changes: 7 additions & 0 deletions rack-protection/lib/rack/protection/base.rb
Expand Up @@ -44,6 +44,7 @@ def accepts?(env)
def call(env)
unless accepts? env
warn env, "attack prevented by #{self.class}"
instrument env
result = react env
end
result or app.call(env)
Expand All @@ -60,6 +61,12 @@ def warn(env, message)
l.warn(message)
end

def instrument(env)
return unless i = options[:instrumenter]
env['rack.protection.attack'] = self.class.name.split('::').last.downcase
i.instrument('rack.protection', env)
end

def deny(env)
[options[:status], {'Content-Type' => 'text/plain'}, [options[:message]]]
end
Expand Down
21 changes: 21 additions & 0 deletions rack-protection/spec/protection_spec.rb
Expand Up @@ -46,4 +46,25 @@
it { should be_false }
end
end

describe "#instrument" do
let(:env) { { 'rack.protection.attack' => 'base' } }
let(:instrumenter) { double('Instrumenter') }

after do
app.instrument(env)
end

context 'with an instrumenter specified' do
let(:app) { Rack::Protection::Base.new(nil, :instrumenter => instrumenter) }

it { instrumenter.should_receive(:instrument).with('rack.protection', env) }
end

context 'with no instrumenter specified' do
let(:app) { Rack::Protection::Base.new(nil) }

it { instrumenter.should_not_receive(:instrument) }
end
end
end

0 comments on commit c77a6f8

Please sign in to comment.