diff --git a/lib/datadog/appsec/contrib/rack/gateway/request.rb b/lib/datadog/appsec/contrib/rack/gateway/request.rb index b0b57a99087..9b587bc620d 100644 --- a/lib/datadog/appsec/contrib/rack/gateway/request.rb +++ b/lib/datadog/appsec/contrib/rack/gateway/request.rb @@ -41,7 +41,7 @@ def method def headers result = request.env.each_with_object({}) do |(k, v), h| - h[k.gsub(/^HTTP_/, '').downcase!.tr('_', '-')] = v if k =~ /^HTTP_/ + h[k.delete_prefix('HTTP_').tap(&:downcase!).tap { |s| s.tr!('_', '-') }] = v if k.start_with?('HTTP_') end result['content-type'] = request.content_type if request.content_type diff --git a/spec/datadog/appsec/contrib/rack/gateway/request_spec.rb b/spec/datadog/appsec/contrib/rack/gateway/request_spec.rb index ddc1918d06c..4a013808677 100644 --- a/spec/datadog/appsec/contrib/rack/gateway/request_spec.rb +++ b/spec/datadog/appsec/contrib/rack/gateway/request_spec.rb @@ -33,6 +33,36 @@ } expect(request.headers).to eq(expected_headers) end + + context 'with malformed headers' do + let(:request) do + described_class.new( + Rack::MockRequest.env_for( + 'http://example.com:8080/?a=foo&a=bar&b=baz', + { + 'REQUEST_METHOD' => 'GET', 'REMOTE_ADDR' => '10.10.10.10', 'CONTENT_TYPE' => 'text/html', + 'HTTP_COOKIE' => 'foo=bar', 'HTTP_USER_AGENT' => 'WebKit', + 'HTTP_' => 'empty header', 'HTTP_123' => 'numbered header', + 'HTTP_123_FOO' => 'alphanumerical header', 'HTTP_FOO_123' => 'reverse alphanumerical header' + } + ) + ) + end + + it 'returns the header information. Strip the HTTP_ prefix and append content-type and content-length information' do + expected_headers = { + 'content-type' => 'text/html', + 'cookie' => 'foo=bar', + 'user-agent' => 'WebKit', + 'content-length' => '0', + '' => 'empty header', + '123' => 'numbered header', + '123-foo' => 'alphanumerical header', + 'foo-123' => 'reverse alphanumerical header' + } + expect(request.headers).to eq(expected_headers) + end + end end describe '#body' do