Skip to content

Commit

Permalink
Attempt to prevent responses with Transfer-Encoding: chunked
Browse files Browse the repository at this point in the history
It's probably a bad idea to implement Transfer-Encoding
chunked inside an application, since only HTTP/1.1 supports
it.  However, some applications and frameworks still do so.
However, they should only do so if they receive an HTTP/1.1
request, it's certainly a bug in the application to use
Transfer-Encoding: chunked for HTTP/1.0 requests.

Set SERVER_PROTOCOL and HTTP_VERSION to HTTP/1.0 in requests
to try to avoid responses with Transfer-Encoding: chunked.

While here, avoid 4 unnecessary hash allocations by using
either Hash#merge! instead of #merge, or using Hash#[]=
instead of allocating a hash to pass to Hash#update.
  • Loading branch information
jeremyevans committed May 2, 2022
1 parent 19c1eab commit a68ea95
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
6 changes: 3 additions & 3 deletions lib/rack/test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -219,11 +219,11 @@ def parse_uri(path, env)
end

def env_for(uri, env)
env = default_env.merge(env)
env = default_env.merge!(env)

env['HTTP_HOST'] ||= [uri.host, (uri.port if uri.port != uri.default_port)].compact.join(':')

env.update('HTTPS' => 'on') if URI::HTTPS === uri
env['HTTPS'] = 'on' if URI::HTTPS === uri
env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' if env[:xhr]

# TODO: Remove this after Rack 1.1 has been released.
Expand Down Expand Up @@ -312,7 +312,7 @@ def digest_auth_configured?
end

def default_env
{ 'rack.test' => true, 'REMOTE_ADDR' => '127.0.0.1' }.merge(@env).merge(headers_for_env)
{ 'rack.test' => true, 'REMOTE_ADDR' => '127.0.0.1', 'SERVER_PROTOCOL' => 'HTTP/1.0', 'HTTP_VERSION' => 'HTTP/1.0' }.merge!(@env).merge!(headers_for_env)
end

def headers_for_env
Expand Down
6 changes: 6 additions & 0 deletions spec/rack/test_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@
expect(last_request.env['X-Foo']).to eq('bar')
end

it 'sets SERVER_PROTOCOL and HTTP_VERSION to HTTP/1.0 by default' do
request '/'
expect(last_request.env['SERVER_PROTOCOL']).to eq('HTTP/1.0')
expect(last_request.env['HTTP_VERSION']).to eq('HTTP/1.0')
end

it 'allows HTTP_HOST to be set' do
request '/', 'HTTP_HOST' => 'www.example.ua'
expect(last_request.env['HTTP_HOST']).to eq('www.example.ua')
Expand Down

0 comments on commit a68ea95

Please sign in to comment.