Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enclose IPv6 address in X-Forwarded-Host in brackets #1213

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 7 additions & 1 deletion lib/rack/request.rb
@@ -1,5 +1,6 @@
require 'rack/utils'
require 'rack/media_type'
require 'resolv'

module Rack
# Rack::Request provides a convenient interface to a Rack
Expand Down Expand Up @@ -224,7 +225,12 @@ def xhr?

def host_with_port
if forwarded = get_header(HTTP_X_FORWARDED_HOST)
forwarded.split(/,\s?/).last
host = forwarded.split(/,\s?/).last

# If the reverse proxy sends an IPv6 address without brackets,
# prevent the last hextet from being stripped off by host() by
# enclosing the address in brackets.
host =~ Resolv::IPv6::Regex ? "[#{host}]" : host
else
get_header(HTTP_HOST) || "#{get_header(SERVER_NAME) || get_header(SERVER_ADDR)}:#{get_header(SERVER_PORT)}"
end
Expand Down
8 changes: 8 additions & 0 deletions test/spec_request.rb
Expand Up @@ -124,6 +124,14 @@ class RackRequestTest < Minitest::Spec
Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org:9292")
req.host.must_equal "example.org"

req = make_request \
Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "192.168.1.1")
req.host.must_equal "192.168.1.1"

req = make_request \
Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "1:2:3:4:5:6:7:8")
req.host.must_equal "[1:2:3:4:5:6:7:8]"

env = Rack::MockRequest.env_for("/", "SERVER_ADDR" => "192.168.1.1", "SERVER_PORT" => "9292")
env.delete("SERVER_NAME")
req = make_request(env)
Expand Down