Skip to content

Commit

Permalink
Preserve forwarded IP address for trusted proxy chains
Browse files Browse the repository at this point in the history
Sometimes proxies make requests to Rack applications, for example
HAProxy health checks and so on.

Previously the forwarded IP implementation ate up these IP addresses,
making it hard to tell in Rack applications who made the request
  • Loading branch information
SamSaffron authored and larsxschneider committed Feb 19, 2019
1 parent cb1fdb6 commit 1bf2188
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/rack/request.rb
Expand Up @@ -261,7 +261,7 @@ def ip

forwarded_ips = split_ip_addresses(get_header('HTTP_X_FORWARDED_FOR'))

return reject_trusted_ip_addresses(forwarded_ips).last || get_header("REMOTE_ADDR")
return reject_trusted_ip_addresses(forwarded_ips).last || forwarded_ips.first || get_header("REMOTE_ADDR")
end

# The media type (type/subtype) portion of the CONTENT_TYPE header
Expand Down
11 changes: 10 additions & 1 deletion test/spec_request.rb
Expand Up @@ -1286,7 +1286,16 @@ def ip_app
res.body.must_equal '2.2.2.3'
end

it "regard local addresses as proxies" do
it "preserves ip for trusted proxy chain" do
mock = Rack::MockRequest.new(Rack::Lint.new(ip_app))
res = mock.get '/',
'HTTP_X_FORWARDED_FOR' => '192.168.0.11, 192.168.0.7',
'HTTP_CLIENT_IP' => '127.0.0.1'
res.body.must_equal '192.168.0.11'

end

it "regards local addresses as proxies" do
req = make_request(Rack::MockRequest.env_for("/"))
req.trusted_proxy?('127.0.0.1').must_equal 0
req.trusted_proxy?('10.0.0.1').must_equal 0
Expand Down

0 comments on commit 1bf2188

Please sign in to comment.