Skip to content

Commit 9464cae

Browse files
committed
Handle ActionDispatch unrecognized routes
1 parent 6db44b4 commit 9464cae

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

lib/datadog/appsec/api_security/route_extractor.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@ def self.route_pattern(request)
4949
pattern = request.env[RAILS_ROUTES_KEY].router
5050
.recognize(request) { |route, _| break route.path.spec.to_s }
5151

52+
# NOTE: If rails is unable to recognize request it returns empty Array
53+
pattern = nil if pattern&.empty?
54+
5255
# NOTE: If rails can't recognize the request, we are going to fallback
5356
# to generic request path
5457
(pattern || request.path).delete_suffix(RAILS_FORMAT_SUFFIX)

spec/datadog/appsec/api_security/route_extractor_spec.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,19 @@
9191

9292
it { expect(described_class.route_pattern(request)).to eq('/api/v1/users/:id/posts/:post_id') }
9393
end
94+
95+
context 'when Rails router cannot recognize request' do
96+
before do
97+
allow(request).to receive(:env).and_return({'action_dispatch.routes' => route_set})
98+
allow(request).to receive(:path).and_return('/unmatched/route')
99+
allow(router).to receive(:recognize).with(request).and_return([])
100+
end
101+
102+
let(:router) { double('ActionDispatch::Routing::RouteSet::Router') }
103+
let(:route_set) { double('ActionDispatch::Routing::RouteSet', router: router) }
104+
105+
it { expect(described_class.route_pattern(request)).to eq('/unmatched/route') }
106+
end
94107
end
95108

96109
context 'when Rack routing is present' do

0 commit comments

Comments
 (0)