Skip to content
Myr

Merge pull request #6655 from sigmavirus24/fix-tls-floppy

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Use TLS settings in selecting connection pool

authored by Ian Stapleton Cordasco · committed by GitHub · parents eea3bbf, c0813a2 · Browse files · 3 files+65 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+65 added−2 removed

  • tests:+7 added−0 removed
  • other:+58 added−2 removed

3 files+65 added−2 removed

modified:src/requests/adapters.py+57 added-1 removed
6 unmodified lines
7"""89import os.path10import socket # noqa: F40111import typing1213from urllib3.exceptions import ClosedPoolError, ConnectTimeoutError14from urllib3.exceptions import HTTPError as _HTTPError15from urllib3.exceptions import InvalidHeader as _InvalidHeader
45 unmodified lines
61 def SOCKSProxyManager(*args, **kwargs):62 raise InvalidSchema("Missing dependencies for SOCKS support.")636465if typing.TYPE_CHECKING:66 from .models import PreparedRequest676869DEFAULT_POOLBLOCK = False70DEFAULT_POOLSIZE = 1071DEFAULT_RETRIES = 072DEFAULT_POOL_TIMEOUT = None737475def _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.port83 cert_reqs = "CERT_REQUIRED"84 if verify is False:85 cert_reqs = "CERT_NONE"86 if isinstance(verify, str):87 pool_kwargs["ca_certs"] = verify88 pool_kwargs["cert_reqs"] = cert_reqs89 host_params = {90 "scheme": scheme,91 "host": parsed_request_url.hostname,92 "port": port,93 }94 return host_params, pool_kwargs959697class BaseAdapter:98 """The Base Transport Adapter"""99100 def __init__(self):
252 unmodified lines
353 response.connection = self354355 return response356357 def _get_connection(self, request, verify, proxies=None):358 # Replace the existing get_connection without breaking things and359 # ensure that TLS settings are considered when we interact with360 # urllib3 HTTP Pools361 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_kwargs377 )378 else:379 # Only scheme should be lower case380 conn = self.poolmanager.connection_from_host(381 **host_params, pool_kwargs=pool_kwargs382 )383384 return conn385386 def get_connection(self, url, proxies=None):387 """Returns a urllib3 connection for the given URL. This should not be388 called from user code, and is only exposed for use when subclassing the389 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
118 unmodified lines
508 :rtype: requests.Response509 """510511 try:456 conn = self.get_connection(request.url, proxies)512 conn = self._get_connection(request, verify, proxies)513 except LocationValueError as e:514 raise InvalidURL(e, request=request)515516 self.cert_verify(conn, request.url, verify, cert)
80 unmodified lines
modified:tests/test_requests.py+7 added
2826 unmodified lines
2827 assert r4 == 4252828 assert r5 == 4252829 assert r6 == 42528302831 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 == 4212835 with pytest.raises(requests.exceptions.SSLError):2836 s.get("https://invalid.badssl.com")283728382839def test_json_decode_errors_are_serializable_deserializable():2840 json_decode_error = requests.exceptions.JSONDecodeError(2841 "Extra data",2842 '{"responseCode":["706"],"data":null}{"responseCode":["706"],"data":null}',
4 unmodified lines
modified:tox.ini+1 added-1 removed
5 unmodified lines
6extras =7 security8 socks9commands =10 pytest tests10 pytest {posargs:tests}1112[testenv:default]1314[testenv:use_chardet_on_py3]
4 unmodified lines