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
5 changes: 5 additions & 0 deletions lib/net/http/generic_request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,10 @@ def send_request_with_body_stream(sock, ver, path, f)
raise ArgumentError,
"Content-Length not given and Transfer-Encoding is not `chunked'"
end
# Transfer-Encoding: chunked and Content-Length must not both be sent (RFC 9112 §6.1):
# emitting both is a request-smuggling primitive. When chunking, the chunk framing is
# authoritative, so drop any Content-Length the caller also set.
delete 'Content-Length' if chunked?
write_header sock, ver, path
wait_for_continue sock, ver if sock.continue_timeout
if chunked?
Expand All @@ -316,6 +320,7 @@ def send_request_with_body_data(sock, ver, path, params)
opt[:boundary] ||= SecureRandom.urlsafe_base64(40)
self.set_content_type(self.content_type, boundary: opt[:boundary])
if chunked?
delete 'Content-Length' # chunked framing is authoritative; never emit both (smuggling)
write_header sock, ver, path
encode_multipart_form_data(sock, params, opt)
else
Expand Down
22 changes: 22 additions & 0 deletions test/net/http/test_http_request.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# frozen_string_literal: false
require 'net/http'
require 'stringio'
require 'test/unit'

class HTTPRequestTest < Test::Unit::TestCase
Expand Down Expand Up @@ -122,4 +123,25 @@ def test_update_uri
assert_equal "[2001:db8::1]", req.uri.host
assert_equal 8080, req.uri.port
end

def test_chunked_request_omits_conflicting_content_length
# RFC 9112 6.1: Transfer-Encoding: chunked and Content-Length must not both be sent on a
# request -- together they are a request-smuggling primitive. When a caller sets both,
# Net::HTTP must drop Content-Length and send only the chunked framing.
req = Net::HTTP::Post.new('/')
req['Transfer-Encoding'] = 'chunked'
req.content_length = 3
req.body_stream = StringIO.new('abc')

captured = +''
sock = Object.new
sock.define_singleton_method(:write) { |*a| a.each { |s| captured << s.to_s }; captured.bytesize }
sock.define_singleton_method(:continue_timeout) { nil }

req.exec(sock, '1.1', '/')
header = captured.split("\r\n\r\n", 2).first

assert_match(/Transfer-Encoding: chunked/i, header)
assert_no_match(/Content-Length/i, header)
end
end
Loading