Skip to content

Commit a58d7f2

Browse files
authored
Merge pull request #6655 from sigmavirus24/fix-tls-floppy
Use TLS settings in selecting connection pool
2 parents eea3bbf + c0813a2 commit a58d7f2

File tree

3 files changed

+65
-2
lines changed

3 files changed

+65
-2
lines changed

src/requests/adapters.py

+57-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import os.path
1010
import socket # noqa: F401
11+
import typing
1112

1213
from urllib3.exceptions import ClosedPoolError, ConnectTimeoutError
1314
from urllib3.exceptions import HTTPError as _HTTPError
@@ -61,12 +62,38 @@ def SOCKSProxyManager(*args, **kwargs):
6162
raise InvalidSchema("Missing dependencies for SOCKS support.")
6263

6364

65+
if typing.TYPE_CHECKING:
66+
from .models import PreparedRequest
67+
68+
6469
DEFAULT_POOLBLOCK = False
6570
DEFAULT_POOLSIZE = 10
6671
DEFAULT_RETRIES = 0
6772
DEFAULT_POOL_TIMEOUT = None
6873

6974

75+
def _urllib3_request_context(
76+
request: "PreparedRequest", verify: "bool | str | None"
77+
) -> "(typing.Dict[str, typing.Any], typing.Dict[str, typing.Any])":
78+
host_params = {}
79+
pool_kwargs = {}
80+
parsed_request_url = urlparse(request.url)
81+
scheme = parsed_request_url.scheme.lower()
82+
port = parsed_request_url.port
83+
cert_reqs = "CERT_REQUIRED"
84+
if verify is False:
85+
cert_reqs = "CERT_NONE"
86+
if isinstance(verify, str):
87+
pool_kwargs["ca_certs"] = verify
88+
pool_kwargs["cert_reqs"] = cert_reqs
89+
host_params = {
90+
"scheme": scheme,
91+
"host": parsed_request_url.hostname,
92+
"port": port,
93+
}
94+
return host_params, pool_kwargs
95+
96+
7097
class BaseAdapter:
7198
"""The Base Transport Adapter"""
7299

@@ -327,6 +354,35 @@ def build_response(self, req, resp):
327354

328355
return response
329356

357+
def _get_connection(self, request, verify, proxies=None):
358+
# Replace the existing get_connection without breaking things and
359+
# ensure that TLS settings are considered when we interact with
360+
# urllib3 HTTP Pools
361+
proxy = select_proxy(request.url, proxies)
362+
try:
363+
host_params, pool_kwargs = _urllib3_request_context(request, verify)
364+
except ValueError as e:
365+
raise InvalidURL(e, request=request)
366+
if proxy:
367+
proxy = prepend_scheme_if_needed(proxy, "http")
368+
proxy_url = parse_url(proxy)
369+
if not proxy_url.host:
370+
raise InvalidProxyURL(
371+
"Please check proxy URL. It is malformed "
372+
"and could be missing the host."
373+
)
374+
proxy_manager = self.proxy_manager_for(proxy)
375+
conn = proxy_manager.connection_from_host(
376+
**host_params, pool_kwargs=pool_kwargs
377+
)
378+
else:
379+
# Only scheme should be lower case
380+
conn = self.poolmanager.connection_from_host(
381+
**host_params, pool_kwargs=pool_kwargs
382+
)
383+
384+
return conn
385+
330386
def get_connection(self, url, proxies=None):
331387
"""Returns a urllib3 connection for the given URL. This should not be
332388
called from user code, and is only exposed for use when subclassing the
@@ -453,7 +509,7 @@ def send(
453509
"""
454510

455511
try:
456-
conn = self.get_connection(request.url, proxies)
512+
conn = self._get_connection(request, verify, proxies)
457513
except LocationValueError as e:
458514
raise InvalidURL(e, request=request)
459515

tests/test_requests.py

+7
Original file line numberDiff line numberDiff line change
@@ -2828,6 +2828,13 @@ def test_status_code_425(self):
28282828
assert r5 == 425
28292829
assert r6 == 425
28302830

2831+
def test_different_connection_pool_for_tls_settings(self):
2832+
s = requests.Session()
2833+
r1 = s.get("https://invalid.badssl.com", verify=False)
2834+
assert r1.status_code == 421
2835+
with pytest.raises(requests.exceptions.SSLError):
2836+
s.get("https://invalid.badssl.com")
2837+
28312838

28322839
def test_json_decode_errors_are_serializable_deserializable():
28332840
json_decode_error = requests.exceptions.JSONDecodeError(

tox.ini

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ extras =
77
security
88
socks
99
commands =
10-
pytest tests
10+
pytest {posargs:tests}
1111

1212
[testenv:default]
1313

0 commit comments

Comments
 (0)