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
Provenance
- Commit
a58d7f2- Tree
80f84bc- Author
Ian Stapleton Cordasco <graffatcolmingov@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
eea3bbf- Parent 2
c0813a2
3 files changed+65 added−2 removed
modified:src/requests/adapters.py+57 added-1 removed
6 unmodified lines7 """8 9 import os.path10 import socket # noqa: F40111+import typing12 13 from urllib3.exceptions import ClosedPoolError, ConnectTimeoutError14 from urllib3.exceptions import HTTPError as _HTTPError15 from urllib3.exceptions import InvalidHeader as _InvalidHeader45 unmodified lines61 def SOCKSProxyManager(*args, **kwargs):62 raise InvalidSchema("Missing dependencies for SOCKS support.")63 64 65+if typing.TYPE_CHECKING:66+ from .models import PreparedRequest67+68+69 DEFAULT_POOLBLOCK = False70 DEFAULT_POOLSIZE = 1071 DEFAULT_RETRIES = 072 DEFAULT_POOL_TIMEOUT = None73 74 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.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_kwargs95+96+97 class BaseAdapter:98 """The Base Transport Adapter"""99 100 def __init__(self):252 unmodified lines353 response.connection = self354 355 return response356 357+ 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+ )383+384+ return conn385+386 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 lines508 :rtype: requests.Response509 """510 511 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)515 516 self.cert_verify(conn, request.url, verify, cert)80 unmodified linesmodified:tests/test_requests.py+7 added
2826 unmodified lines2827 assert r4 == 4252828 assert r5 == 4252829 assert r6 == 4252830 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 == 4212835+ with pytest.raises(requests.exceptions.SSLError):2836+ s.get("https://invalid.badssl.com")2837 2838+2839 def 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 linesmodified:tox.ini+1 added-1 removed
5 unmodified lines6 extras =7 security8 socks9 commands =10- pytest tests10+ pytest {posargs:tests}11 12 [testenv:default]13 14 [testenv:use_chardet_on_py3]4 unmodified lines