Skip to content

Commit

Permalink
[1.26] Avoid socket leak if HTTPSConnection.connect() fails
Browse files Browse the repository at this point in the history
Co-authored-by: Thomas Grainger <tagrain@gmail.com>
  • Loading branch information
sethmlarson and graingert committed Mar 3, 2022
1 parent 5cf6d03 commit c0a182c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
6 changes: 2 additions & 4 deletions src/urllib3/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,17 +355,15 @@ def set_cert(

def connect(self):
# Add certificate verification
conn = self._new_conn()
self.sock = conn = self._new_conn()
hostname = self.host
tls_in_tls = False

if self._is_using_tunnel():
if self.tls_in_tls_required:
conn = self._connect_tls_proxy(hostname, conn)
self.sock = conn = self._connect_tls_proxy(hostname, conn)
tls_in_tls = True

self.sock = conn

# Calls self._set_hostport(), so self.host is
# self._tunnel_host below.
self._tunnel()
Expand Down
16 changes: 16 additions & 0 deletions test/with_dummyserver/test_https.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,22 @@ def test_verified_with_bad_ca_certs(self):
"Expected 'certificate verify failed', instead got: %r" % e.value.reason
)

def test_wrap_socket_failure_resource_leak(self):
with HTTPSConnectionPool(
self.host,
self.port,
cert_reqs="CERT_REQUIRED",
ca_certs=self.bad_ca_path,
) as https_pool:
conn = https_pool._get_conn()
try:
with pytest.raises(ssl.SSLError):
conn.connect()

assert conn.sock
finally:
conn.close()

def test_verified_without_ca_certs(self):
# default is cert_reqs=None which is ssl.CERT_NONE
with HTTPSConnectionPool(
Expand Down

0 comments on commit c0a182c

Please sign in to comment.