Skip to content

Commit 065b082

Browse files
authored
Merge pull request #369 from frandle331-yh/ignore-content-length-when-chunked
Ignore Content-Length when sending a chunked request body
2 parents aa45648 + 5bb4b6a commit 065b082

2 files changed

Lines changed: 27 additions & 0 deletions

File tree

‎lib/net/http/generic_request.rb‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,10 @@ def send_request_with_body_stream(sock, ver, path, f)
294294
raise ArgumentError,
295295
"Content-Length not given and Transfer-Encoding is not `chunked'"
296296
end
297+
# Transfer-Encoding: chunked and Content-Length must not both be sent (RFC 9112 §6.1):
298+
# emitting both is a request-smuggling primitive. When chunking, the chunk framing is
299+
# authoritative, so drop any Content-Length the caller also set.
300+
delete 'Content-Length' if chunked?
297301
write_header sock, ver, path
298302
wait_for_continue sock, ver if sock.continue_timeout
299303
if chunked?
@@ -316,6 +320,7 @@ def send_request_with_body_data(sock, ver, path, params)
316320
opt[:boundary] ||= SecureRandom.urlsafe_base64(40)
317321
self.set_content_type(self.content_type, boundary: opt[:boundary])
318322
if chunked?
323+
delete 'Content-Length' # chunked framing is authoritative; never emit both (smuggling)
319324
write_header sock, ver, path
320325
encode_multipart_form_data(sock, params, opt)
321326
else

‎test/net/http/test_http_request.rb‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# frozen_string_literal: false
22
require 'net/http'
3+
require 'stringio'
34
require 'test/unit'
45

56
class HTTPRequestTest < Test::Unit::TestCase
@@ -122,4 +123,25 @@ def test_update_uri
122123
assert_equal "[2001:db8::1]", req.uri.host
123124
assert_equal 8080, req.uri.port
124125
end
126+
127+
def test_chunked_request_omits_conflicting_content_length
128+
# RFC 9112 6.1: Transfer-Encoding: chunked and Content-Length must not both be sent on a
129+
# request -- together they are a request-smuggling primitive. When a caller sets both,
130+
# Net::HTTP must drop Content-Length and send only the chunked framing.
131+
req = Net::HTTP::Post.new('/')
132+
req['Transfer-Encoding'] = 'chunked'
133+
req.content_length = 3
134+
req.body_stream = StringIO.new('abc')
135+
136+
captured = +''
137+
sock = Object.new
138+
sock.define_singleton_method(:write) { |*a| a.each { |s| captured << s.to_s }; captured.bytesize }
139+
sock.define_singleton_method(:continue_timeout) { nil }
140+
141+
req.exec(sock, '1.1', '/')
142+
header = captured.split("\r\n\r\n", 2).first
143+
144+
assert_match(/Transfer-Encoding: chunked/i, header)
145+
assert_no_match(/Content-Length/i, header)
146+
end
125147
end

0 commit comments

Comments
 (0)