diff --git a/lib/net/http/response.rb b/lib/net/http/response.rb index 8e05ef56..8a0381ac 100644 --- a/lib/net/http/response.rb +++ b/lib/net/http/response.rb @@ -657,7 +657,12 @@ def read_chunked(dest, chunk_data_io) # :nodoc: chunk_data_io.read len, dest ensure total += len - @socket.read 2 # \r\n + # RFC 9112 requires CRLF after the chunk data. Anything else is + # left on the socket and is read as the next response (net-http#378). + term = @socket.read(2) + unless term == "\r\n" + raise Net::HTTPBadResponse, "wrong chunk terminator: #{term.inspect}" + end end end until self.class.read_line(@socket, MAX_RESPONSE_HEADER_LENGTH).chop.empty? diff --git a/test/net/http/test_httpresponse.rb b/test/net/http/test_httpresponse.rb index 7c213f30..deda7edb 100644 --- a/test/net/http/test_httpresponse.rb +++ b/test/net/http/test_httpresponse.rb @@ -166,6 +166,16 @@ def test_chunk_size_line end end + def test_chunk_terminator_must_be_crlf + io = dummy_io("HTTP/1.1 200 OK\nConnection: close\nTransfer-Encoding: chunked\n\n" \ + "5\nhelloXX0\n\n") + res = Net::HTTPResponse.read_new(io) + e = assert_raise(Net::HTTPBadResponse) do + res.reading_body(io, true) {} + end + assert_match(/wrong chunk terminator/, e.message) + end + def test_read_body_chunked_is_final_transfer_coding io = dummy_io(<