From 889dfb2e02264843bf79e103ade5f524201961a7 Mon Sep 17 00:00:00 2001 From: Yusuke Endoh Date: Mon, 30 Nov 2026 20:08:10 +0900 Subject: [PATCH] Close the connection when a request does not finish Leaving the block of Net::HTTP#request with break, return, throw or an exception that is not a StandardError left the rest of the response on the connection, and the next request read it as its own response. Close the connection unless the request finished. Fixes ruby/net-http#157 Reported-by: Alexander Medela Ayarzaguena (https://hackerone.com/alexandermedela) Co-Authored-By: Claude Opus 5.5 --- lib/net/http.rb | 6 ++++-- test/net/http/test_http.rb | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/lib/net/http.rb b/lib/net/http.rb index 708a7f2e..09b898db 100644 --- a/lib/net/http.rb +++ b/lib/net/http.rb @@ -2520,6 +2520,7 @@ def send_entity(path, data, initheader, dest, type, &block) def transport_request(req) count = 0 + finished = false begin body_sent = false begin_transport req @@ -2569,17 +2570,18 @@ def transport_request(req) retry end debug "Conn close because of error #{exception}" - @socket.close if @socket raise end @socket.close unless body_sent end_transport req, res + finished = true res rescue => exception debug "Conn close because of error #{exception}" - @socket.close if @socket raise exception + ensure + @socket.close if !finished && @socket && !@socket.closed? end def begin_transport(req) diff --git a/test/net/http/test_http.rb b/test/net/http/test_http.rb index 2c9894fd..5cccb06e 100644 --- a/test/net/http/test_http.rb +++ b/test/net/http/test_http.rb @@ -1621,6 +1621,21 @@ def test_http_no_retry_with_multipart_io } end + def test_leaving_request_block_closes_connection + start {|http| + [ + -> { http.request_get('/') { break } }, + -> { catch(:done) { http.request_get('/') { throw :done } } }, + -> { assert_raise(Interrupt) { http.request_get('/') { raise Interrupt } } }, + ].each do |leave| + leave.call + assert_predicate http.instance_variable_get(:@socket), :closed? + res = http.get('/') + assert_kind_of Net::HTTPResponse, res + end + } + end + def test_keep_alive_server_close def @server.run(sock) sock.close