Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ All notable changes to this project will be documented in this file. For info on
- `Rack::Headers` added to support lower-case header keys. ([@jeremyevans](https://github.com/jeremyevans))
- `Rack::RewindableInput` supports size. ([@ahorek](https://github.com/ahorek))
- `Rack::RewindableInput::Middleware` added for making `rack.input` rewindable. ([@jeremyevans](https://github.com/jeremyevans))
- Rack::Session::Pool now accepts `:allow_fallback` option to disable fallback to public id. ([#1431](https://github.com/rack/rack/issues/1431), [@jeremyevans](https://github.com/jeremyevans))
- The RFC 7239 Forwarded header is now supported and considered by default when looking for information on forwarding, falling back to the the X-Forwarded-* headers. `Rack::Request.forwarded_priority` accessor has been added for configuring the priority of which header to check. ([#1423](https://github.com/rack/rack/issues/1423), [@jeremyevans](https://github.com/jeremyevans))

### Changed

Expand All @@ -47,6 +47,8 @@ All notable changes to this project will be documented in this file. For info on
- Explicitly deprecate `Rack::File` which was an alias for `Rack::Files`. ([#1811](https://github.com/rack/rack/pull/1720), [@ioquatix](https://github.com/ioquatix)).
- Moved `Rack::Session` into [separate gem](https://github.com/rack/rack-session). ([#1805](https://github.com/rack/rack/pull/1805), [@ioquatix](https://github.com/ioquatix))
- rackup -D option to daemonizes no longer changes the working directory to the root. ([#1813](https://github.com/rack/rack/pull/1813), [@jeremyevans](https://github.com/jeremyevans))
- The X-Forwarded-Proto header is now considered before the X-Forwarded-Scheme header for determining the forwarded protocol. `Rack::Request.x_forwarded_proto_priority` accessor has been added for configuring the priority of which header to check. ([#1809](https://github.com/rack/rack/issues/1809), [@jeremyevans](https://github.com/jeremyevans))
- `Rack::Request.forwarded_authority` (and methods that call it, such as `host`) now returns the last authority in the forwarded header, instead of the first, as earlier forwarded authorities can be forged by clients. This restores the Rack 2.1 behavior. ([#1829](https://github.com/rack/rack/issues/1809), [@jeremyevans](https://github.com/jeremyevans))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This restores the Rack 2.1 behavior.

Would it be possible to clearly mark this change as a breaking change in the changelog of the release where this different behavior was included?

Would it also be possible to backport the fix to the v2 branch?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean backport this entire PR?


### Fixed

Expand Down
22 changes: 12 additions & 10 deletions lib/rack/common_logger.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
require_relative 'constants'
require_relative 'utils'
require_relative 'body_proxy'
require_relative 'request'

module Rack
# Rack::CommonLogger forwards every request to the given +app+, and
Expand Down Expand Up @@ -47,23 +48,24 @@ def call(env)
private

# Log the request to the configured logger.
def log(env, status, headers, began_at)
length = extract_content_length(headers)
def log(env, status, response_headers, began_at)
request = Rack::Request.new(env)
length = extract_content_length(response_headers)

msg = FORMAT % [
env['HTTP_X_FORWARDED_FOR'] || env["REMOTE_ADDR"] || "-",
env["REMOTE_USER"] || "-",
request.ip || "-",
request.get_header("REMOTE_USER") || "-",
Time.now.strftime("%d/%b/%Y:%H:%M:%S %z"),
env[REQUEST_METHOD],
env[SCRIPT_NAME],
env[PATH_INFO],
env[QUERY_STRING].empty? ? "" : "?#{env[QUERY_STRING]}",
env[SERVER_PROTOCOL],
request.request_method,
request.script_name,
request.path_info,
request.query_string.empty? ? "" : "?#{request.query_string}",
request.get_header(SERVER_PROTOCOL),
status.to_s[0..3],
length,
Utils.clock_time - began_at ]

logger = @logger || env[RACK_ERRORS]
logger = @logger || request.get_header(RACK_ERRORS)
# Standard library logger doesn't support write but it supports << which actually
# calls to write on the log device without formatting
if logger.respond_to?(:write)
Expand Down
123 changes: 112 additions & 11 deletions lib/rack/request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,33 @@ module Rack
class Request
class << self
attr_accessor :ip_filter

# The priority when checking forwarded headers. The default
# is <tt>[:forwarded, :x_forwarded]</tt>, which means, check the
# +Forwarded+ header first, followed by the appropriate
# <tt>X-Forwarded-*</tt> header. You can revert the priority by
# reversing the priority, or remove checking of either
# or both headers by removing elements from the array.
#
# This should be set as appropriate in your environment
# based on what reverse proxies are in use. If you are not
# using reverse proxies, you should probably use an empty
# array.
attr_accessor :forwarded_priority

# The priority when checking either the <tt>X-Forwarded-Proto</tt>
# or <tt>X-Forwarded-Scheme</tt> header for the forwarded protocol.
# The default is <tt>[:proto, :scheme]</tt>, to try the
# <tt>X-Forwarded-Proto</tt> header before the
# <tt>X-Forwarded-Scheme</tt> header. Rack 2 had behavior
# similar to <tt>[:scheme, :proto]</tt>. You can remove either or
# both of the entries in array to ignore that respective header.
attr_accessor :x_forwarded_proto_priority
end

@forwarded_priority = [:forwarded, :x_forwarded]
@x_forwarded_proto_priority = [:proto, :scheme]

valid_ipv4_octet = /\.(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])/

trusted_proxies = Regexp.union(
Expand Down Expand Up @@ -152,6 +177,8 @@ module Helpers
# The contents of the host/:authority header sent to the proxy.
HTTP_X_FORWARDED_HOST = 'HTTP_X_FORWARDED_HOST'

HTTP_FORWARDED = 'HTTP_FORWARDED'

# The value of the scheme sent to the proxy.
HTTP_X_FORWARDED_SCHEME = 'HTTP_X_FORWARDED_SCHEME'

Expand Down Expand Up @@ -331,7 +358,7 @@ def port
end

if forwarded_port = self.forwarded_port
return forwarded_port.first
return forwarded_port.last
end

if scheme = self.scheme
Expand All @@ -344,23 +371,60 @@ def port
end

def forwarded_for
if value = get_header(HTTP_X_FORWARDED_FOR)
split_header(value).map do |authority|
split_authority(wrap_ipv6(authority))[1]
forwarded_priority.each do |type|
case type
when :forwarded
if forwarded_for = get_http_forwarded(:for)
return(forwarded_for.map! do |authority|
split_authority(authority)[1]
end)
end
when :x_forwarded
if value = get_header(HTTP_X_FORWARDED_FOR)
return(split_header(value).map do |authority|
split_authority(wrap_ipv6(authority))[1]
end)
end
end
end

nil
end

def forwarded_port
if value = get_header(HTTP_X_FORWARDED_PORT)
split_header(value).map(&:to_i)
forwarded_priority.each do |type|
case type
when :forwarded
if forwarded = get_http_forwarded(:for)
return(forwarded.map do |authority|
split_authority(authority)[2]
end.compact)
end
when :x_forwarded
if value = get_header(HTTP_X_FORWARDED_PORT)
return split_header(value).map(&:to_i)
end
end
end

nil
end

def forwarded_authority
if value = get_header(HTTP_X_FORWARDED_HOST)
wrap_ipv6(split_header(value).first)
forwarded_priority.each do |type|
case type
when :forwarded
if forwarded = get_http_forwarded(:host)
return forwarded.last
end
when :x_forwarded
if value = get_header(HTTP_X_FORWARDED_HOST)
return wrap_ipv6(split_header(value).last)
end
end
end

nil
end

def ssl?
Expand All @@ -372,7 +436,7 @@ def ip
external_addresses = reject_trusted_ip_addresses(remote_addresses)

unless external_addresses.empty?
return external_addresses.first
return external_addresses.last
end

if forwarded_for = self.forwarded_for
Expand Down Expand Up @@ -593,6 +657,11 @@ def parse_http_accept_header(header)
end
end

# Get an array of values set in the RFC 7239 `Forwarded` request header.
def get_http_forwarded(token)
Utils.forwarded_values(get_header(HTTP_FORWARDED))&.[](token)
end

def query_parser
Utils.default_query_parser
end
Expand Down Expand Up @@ -638,9 +707,33 @@ def reject_trusted_ip_addresses(ip_addresses)
ip_addresses.reject { |ip| trusted_proxy?(ip) }
end

FORWARDED_SCHEME_HEADERS = {
proto: HTTP_X_FORWARDED_PROTO,
scheme: HTTP_X_FORWARDED_SCHEME
}.freeze
private_constant :FORWARDED_SCHEME_HEADERS
def forwarded_scheme
allowed_scheme(get_header(HTTP_X_FORWARDED_SCHEME)) ||
allowed_scheme(extract_proto_header(get_header(HTTP_X_FORWARDED_PROTO)))
forwarded_priority.each do |type|
case type

@ioquatix ioquatix Apr 4, 2022 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel using a case statement here is a little bit cumbersome. Like, we know in advance what code should be executed. Using an array is flexible and could even contain the same entry more than once even thought it doesn't make sense.

Thinking longer term, does the symbol list in forwarded_priority make it hard to evolve this implementation? If we wanted to get rid of the case statement and make the internal implementation more streamlined.

Does it matter? My main thought is performance. I guess probably not. If it was a big issue, maybe later we can construct a lambda based on the expected behaviour and just cache it?

I guess the alternative would be self.send(:"forwarded_scheme_#{type}")??? This would allow users to introduce their own methods if they had a strong desire to do so. Another option would be Rack::Request mixins using prepend which call super...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not attached to the particular approach used. If we want to change to use send instead of case, that seems fine with me. The important part is that the solution implemented allows the user to choose which header to respect in which order, and allows configuring to explicitly ignore either header or both headers.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you have the energy to make that change and do you prefer it? I'm happy to defer to your judgement here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm fine keeping the case. We can optimize using send later in a backwards compatible manner if it turns out to be a bottleneck.

when :forwarded
if (forwarded_proto = get_http_forwarded(:proto)) &&
(scheme = allowed_scheme(forwarded_proto.last))
return scheme
end
when :x_forwarded
x_forwarded_proto_priority.each do |x_type|
if header = FORWARDED_SCHEME_HEADERS[x_type]
split_header(get_header(header)).reverse_each do |scheme|
if allowed_scheme(scheme)
return scheme
end
end
end
end
end
end

nil
end

def allowed_scheme(header)
Expand All @@ -656,6 +749,14 @@ def extract_proto_header(header)
end
end
end

def forwarded_priority
Request.forwarded_priority
end

def x_forwarded_proto_priority
Request.x_forwarded_proto_priority
end
end

include Env
Expand Down
13 changes: 13 additions & 0 deletions lib/rack/utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,19 @@ def q_values(q_value_header)
end
end

def forwarded_values(forwarded_header)
return nil unless forwarded_header
forwarded_header = forwarded_header.to_s.gsub("\n", ";")

forwarded_header.split(/\s*;\s*/).each_with_object({}) do |field, values|
field.split(/\s*,\s*/).each do |pair|
return nil unless pair =~ /\A\s*(by|for|host|proto)\s*=\s*"?([^"]+)"?\s*\Z/i
(values[$1.downcase.to_sym] ||= []) << $2
end
end
end
module_function :forwarded_values

# Return best accept value to use, based on the algorithm
# in RFC 2616 Section 14. If there are multiple best
# matches (same specificity and quality), the value returned
Expand Down
14 changes: 14 additions & 0 deletions test/spec_common_logger.rb
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,20 @@
res.errors.must_match(/"GET \/ " 200 - /)
end

it "log - records host from X-Forwarded-For header" do
res = Rack::MockRequest.new(Rack::CommonLogger.new(app)).get("/", 'HTTP_X_FORWARDED_FOR' => '203.0.113.0')

res.errors.wont_be :empty?
res.errors.must_match(/203\.0\.113\.0 - /)
end

it "log - records host from RFC 7239 forwarded for header" do
res = Rack::MockRequest.new(Rack::CommonLogger.new(app)).get("/", 'HTTP_FORWARDED' => 'for=203.0.113.0')

res.errors.wont_be :empty?
res.errors.must_match(/203\.0\.113\.0 - /)
end

def with_mock_time(t = 0)
mc = class << Time; self; end
mc.send :alias_method, :old_now, :now
Expand Down
Loading