From 5c427bbb5951412a25932e2d20e7192a2f27185c Mon Sep 17 00:00:00 2001 From: Yusuke Endoh Date: Tue, 1 Dec 2026 11:57:13 +0900 Subject: [PATCH] Do not write an empty chunk for an empty file part In a chunked multipart body, a file part of size 0 was written as a chunk of size 0, which marks the end of a chunked body. Skip the chunk when the size is 0. Co-authored-by: Orien Madgwick Co-Authored-By: Claude Opus 5.5 --- lib/net/http/generic_request.rb | 9 ++++++--- test/net/http/test_http.rb | 36 +++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/lib/net/http/generic_request.rb b/lib/net/http/generic_request.rb index 125c09c3..a7a9cb5d 100644 --- a/lib/net/http/generic_request.rb +++ b/lib/net/http/generic_request.rb @@ -379,9 +379,12 @@ def encode_multipart_form_data(out, params, opt) elsif value.respond_to?(:size) && chunked_p # if +out+ is an IO and +value+ is a File, use IO.copy_stream flush_buffer(out, buf, chunked_p) - out << "%x\r\n" % value.size if chunked_p - IO.copy_stream(value, out) - out << "\r\n" if chunked_p + size = value.size + if size > 0 + out << "%x\r\n" % size + IO.copy_stream(value, out) + out << "\r\n" + end else # +out+ is an IO, and +value+ is not a File but an IO flush_buffer(out, buf, chunked_p) diff --git a/test/net/http/test_http.rb b/test/net/http/test_http.rb index 0df1c565..2c9894fd 100644 --- a/test/net/http/test_http.rb +++ b/test/net/http/test_http.rb @@ -967,6 +967,42 @@ def test_set_form_with_file } end + def test_set_form_chunked_with_empty_file + require 'tempfile' + Tempfile.create('ruby-test') {|empty| + data = [ + ['empty', empty, {filename: 'a'}], + ['string_io', StringIO.new(''), {filename: 'b'}], + ['after', 'value'], + ] + expected = <<"__EOM__".gsub(/\n/, "\r\n") +--BOUNDARY +Content-Disposition: form-data; name="empty"; filename="a" +Content-Type: application/octet-stream + + +--BOUNDARY +Content-Disposition: form-data; name="string_io"; filename="b" +Content-Type: application/octet-stream + + +--BOUNDARY +Content-Disposition: form-data; name="after" + +value +--BOUNDARY-- +__EOM__ + start {|http| + @server.mount('/', lambda {|req, res| res.body = req.body }) + req = Net::HTTP::Post.new('/') + req['Transfer-Encoding'] = 'chunked' + req.set_form(data, 'multipart/form-data', boundary: 'BOUNDARY') + res = http.request req + assert_equal(expected, res.body) + } + } + end + def test_set_form_multipart_crlf_injection build = ->(data, opt = {}) { req = Net::HTTP::Post.new('/')