Included create_ssl_context function to create the same context with SSLConfig and serve as API (#996)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Included create_ssl_context function to create the same context with SSLConfig and serve as API. * Changed create_ssl_context with SSLConfig into the client implementation and tests. * Dropped the __repr__ and __eq__ methods from SSLConfig and removed SSLConfig using from tests * Fixed test issue regarding cert_authority trust of ssl context
authored by Can Sarıgöl · committed by GitHub · parent 35f09d1 · Browse files · 6 files·+72 added−83 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Tom Christie <tom@tomchristie.com>
- Co-authored-by: Florimond Manca <florimond.manca@gmail.com>
Diff stats
6 files+72 added−83 removed
- tests:+30 added−47 removed
- other:+42 added−36 removed
Provenance
- Commit
926a55a- Tree
4244594- Author
Can Sarıgöl <ertugrulsarigol@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
35f09d1
6 files changed+72 added−83 removed
modified:docs/advanced.md+17 added
598 unmodified lines599 >>> httpx.get('https://example.org', verify=context)600 <Response [200 OK]>601 ```602 603+We also include a helper function for creating properly configured `SSLContext` instances.604+605+```python606+>>> context = httpx.create_ssl_context()607+```608+609+The `create_ssl_context` function accepts the same set of SSL configuration arguments 610+(`trust_env`, `verify`, `cert` and `http2` arguments) 611+as `httpx.Client` or `httpx.AsyncClient`612+613+```python614+>>> import httpx615+>>> context = httpx.create_ssl_context(verify="/tmp/client.pem")616+>>> httpx.get('https://example.org', verify=context)617+<Response [200 OK]>618+```619+620 Or you can also disable the SSL verification entirely, which is _not_ recommended.621 622 ```python623 import httpx86 unmodified linesmodified:httpx/_transports/urllib3.py+7 added-11 removed
1 unmodified line2 from typing import Dict, Iterator, List, Optional, Tuple3 4 import httpcore5 6-from .._config import SSLConfig6+from .._config import create_ssl_context7 from .._content_streams import ByteStream, IteratorStream8 from .._exceptions import NetworkError, map_exceptions9 from .._types import CertTypes, VerifyTypes10 18 unmodified lines29 assert (30 urllib3 is not None31 ), "urllib3 must be installed in order to use URLLib3Transport"32 33- ssl_config = SSLConfig(34- verify=verify, cert=cert, trust_env=trust_env, http2=False35- )36-33 self.pool = urllib3.PoolManager(38- ssl_context=ssl_config.ssl_context,34+ ssl_context=create_ssl_context(35+ verify=verify, cert=cert, trust_env=trust_env, http2=False36+ ),37 num_pools=pool_connections,38 maxsize=pool_maxsize,39 block=pool_block,40 )95 unmodified lines136 assert (137 urllib3 is not None138 ), "urllib3 must be installed in order to use URLLib3ProxyTransport"139 142- ssl_config = SSLConfig(143- verify=verify, cert=cert, trust_env=trust_env, http2=False144- )145-140 self.pool = urllib3.ProxyManager(141 proxy_url=proxy_url,142 proxy_headers=proxy_headers,149- ssl_context=ssl_config.ssl_context,143+ ssl_context=create_ssl_context(144+ verify=verify, cert=cert, trust_env=trust_env, http2=False145+ ),146 num_pools=pool_connections,147 maxsize=pool_maxsize,148 block=pool_block,149 )modified:httpx/__init__.py+2 added-1 removed
1 from .__version__ import __description__, __title__, __version__2 from ._api import delete, get, head, options, patch, post, put, request, stream3 from ._auth import Auth, BasicAuth, DigestAuth4 from ._client import AsyncClient, Client5-from ._config import PoolLimits, Proxy, Timeout5+from ._config import PoolLimits, Proxy, Timeout, create_ssl_context6 from ._exceptions import (7 CloseError,8 ConnectError,9 ConnectTimeout,50 unmodified lines60 "DigestAuth",61 "PoolLimits",62 "Proxy",63 "Timeout",64+ "create_ssl_context",65 "CloseError",66 "ConnectError",67 "ConnectTimeout",68 "CookieConflict",34 unmodified linesmodified:httpx/_client.py+5 added-13 removed
11 unmodified lines12 DEFAULT_TIMEOUT_CONFIG,13 UNSET,14 PoolLimits,15 Proxy,16- SSLConfig,16 Timeout,17 UnsetType,18+ create_ssl_context,19 )20 from ._content_streams import ContentStream21 from ._exceptions import (22 HTTPCORE_EXC_MAP,475 unmodified lines498 499 if app is not None:500 return WSGITransport(app=app)501 502- ssl_context = SSLConfig(503- verify=verify, cert=cert, trust_env=trust_env504- ).ssl_context502+ ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)503 504 return httpcore.SyncConnectionPool(505 ssl_context=ssl_context,506 max_keepalive=pool_limits.max_keepalive,10 unmodified lines517 http2: bool = False,518 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,519 trust_env: bool = True,520 ) -> httpcore.SyncHTTPTransport:523- ssl_context = SSLConfig(524- verify=verify, cert=cert, trust_env=trust_env525- ).ssl_context521+ ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)522 523 return httpcore.SyncHTTPProxy(524 proxy_url=proxy.url.raw,525 proxy_headers=proxy.headers.raw,501 unmodified lines1027 1028 if app is not None:1029 return ASGITransport(app=app)1030 1035- ssl_context = SSLConfig(1036- verify=verify, cert=cert, trust_env=trust_env1037- ).ssl_context1031+ ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)1032 1033 return httpcore.AsyncConnectionPool(1034 ssl_context=ssl_context,1035 max_keepalive=pool_limits.max_keepalive,10 unmodified lines1046 http2: bool = False,1047 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,1048 trust_env: bool = True,1049 ) -> httpcore.AsyncHTTPTransport:1056- ssl_context = SSLConfig(1057- verify=verify, cert=cert, trust_env=trust_env1058- ).ssl_context1050+ ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)1051 1052 return httpcore.AsyncHTTPProxy(1053 proxy_url=proxy.url.raw,1054 proxy_headers=proxy.headers.raw,446 unmodified linesmodified:httpx/_config.py+11 added-11 removed
38 unmodified lines39 40 UNSET = UnsetType()41 42 43+def create_ssl_context(44+ cert: CertTypes = None,45+ verify: VerifyTypes = True,46+ trust_env: bool = None,47+ http2: bool = False,48+) -> ssl.SSLContext:49+ return SSLConfig(50+ cert=cert, verify=verify, trust_env=trust_env, http2=http251+ ).ssl_context52+53+54 class SSLConfig:55 """56 SSL Configuration.57 """13 unmodified lines71 self.trust_env = trust_env72 self.http2 = http273 self.ssl_context = self.load_ssl_context()74 64- def __eq__(self, other: typing.Any) -> bool:65- return (66- isinstance(other, self.__class__)67- and self.cert == other.cert68- and self.verify == other.verify69- )70-71- def __repr__(self) -> str:72- class_name = self.__class__.__name__73- return f"{class_name}(cert={self.cert}, verify={self.verify})"74-75 def load_ssl_context(self) -> ssl.SSLContext:76 logger.trace(77 f"load_ssl_context "78 f"verify={self.verify!r} "280 unmodified linesmodified:tests/test_config.py+30 added-47 removed
1 import os2-import socket2 import ssl3 import sys4 from pathlib import Path5 6 import certifi7 import pytest8 9 import httpx11-from httpx._config import SSLConfig10 11 12 def test_load_ssl_config():15- ssl_config = SSLConfig()16- context = ssl_config.ssl_context13+ context = httpx.create_ssl_context()14 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED15 assert context.check_hostname is True16 17 18 def test_load_ssl_config_verify_non_existing_path():19 with pytest.raises(IOError):23- SSLConfig(verify="/path/to/nowhere")20+ httpx.create_ssl_context(verify="/path/to/nowhere")21 22 23 def test_load_ssl_config_verify_existing_file():27- ssl_config = SSLConfig(verify=certifi.where())28- context = ssl_config.ssl_context24+ context = httpx.create_ssl_context(verify=certifi.where())25 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED26 assert context.check_hostname is True27 28 29 @pytest.mark.parametrize("config", ("SSL_CERT_FILE", "SSL_CERT_DIR"))34-def test_load_ssl_config_verify_env_file(https_server, ca_cert_pem_file, config):30+def test_load_ssl_config_verify_env_file(31+ https_server, ca_cert_pem_file, config, cert_authority32+):33 os.environ[config] = (34 ca_cert_pem_file35 if config.endswith("_FILE")36 else str(Path(ca_cert_pem_file).parent)37 )40- ssl_config = SSLConfig(trust_env=True)41- context = ssl_config.ssl_context38+ context = httpx.create_ssl_context(trust_env=True)39+ cert_authority.configure_trust(context)40+41 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED42 assert context.check_hostname is True44- assert ssl_config.verify == os.environ[config]43+ assert len(context.get_ca_certs()) == 144 46- # Skipping 'SSL_CERT_DIR' functional test for now because47- # we're unable to get the certificate within the directory to48- # load into the SSLContext. :(49- if config == "SSL_CERT_FILE":50- host = https_server.url.host51- port = https_server.url.port52- conn = socket.create_connection((host, port))53- context.wrap_socket(conn, server_hostname=host)54- assert len(context.get_ca_certs()) == 145 56-46 def test_load_ssl_config_verify_directory():47 path = Path(certifi.where()).parent59- ssl_config = SSLConfig(verify=str(path))60- context = ssl_config.ssl_context48+ context = httpx.create_ssl_context(verify=str(path))49 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED50 assert context.check_hostname is True51 52 53 def test_load_ssl_config_cert_and_key(cert_pem_file, cert_private_key_file):66- ssl_config = SSLConfig(cert=(cert_pem_file, cert_private_key_file))67- context = ssl_config.ssl_context54+ context = httpx.create_ssl_context(cert=(cert_pem_file, cert_private_key_file))55 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED56 assert context.check_hostname is True57 58 59 @pytest.mark.parametrize("password", [b"password", "password"])60 def test_load_ssl_config_cert_and_encrypted_key(61 cert_pem_file, cert_encrypted_private_key_file, password62 ):76- ssl_config = SSLConfig(63+ context = httpx.create_ssl_context(64 cert=(cert_pem_file, cert_encrypted_private_key_file, password)65 )79- context = ssl_config.ssl_context66 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED67 assert context.check_hostname is True68 69 70 def test_load_ssl_config_cert_and_key_invalid_password(71 cert_pem_file, cert_encrypted_private_key_file72 ):73 with pytest.raises(ssl.SSLError):88- SSLConfig(cert=(cert_pem_file, cert_encrypted_private_key_file, "password1"))74+ httpx.create_ssl_context(75+ cert=(cert_pem_file, cert_encrypted_private_key_file, "password1")76+ )77 78 79 def test_load_ssl_config_cert_without_key_raises(cert_pem_file):80 with pytest.raises(ssl.SSLError):93- SSLConfig(cert=cert_pem_file)81+ httpx.create_ssl_context(cert=cert_pem_file)82 83 84 def test_load_ssl_config_no_verify():97- ssl_config = SSLConfig(verify=False)98- context = ssl_config.ssl_context85+ context = httpx.create_ssl_context(verify=False)86 assert context.verify_mode == ssl.VerifyMode.CERT_NONE87 assert context.check_hostname is False88 89 90 def test_load_ssl_context():91 ssl_context = ssl.create_default_context()105- ssl_config = SSLConfig(verify=ssl_context)92+ context = httpx.create_ssl_context(verify=ssl_context)93 107- assert ssl_config.ssl_context is ssl_context94+ assert context is ssl_context95 96 110-def test_ssl_repr():111- ssl = SSLConfig(verify=False)112- assert repr(ssl) == "SSLConfig(cert=None, verify=False)"97+def test_create_ssl_context_with_get_request(server, cert_pem_file):98+ context = httpx.create_ssl_context(verify=cert_pem_file)99+ response = httpx.get(server.url, verify=context)100+ assert response.status_code == 200101 102 115-def test_ssl_eq():116- ssl = SSLConfig(verify=False)117- assert ssl == SSLConfig(verify=False)118-119-103 def test_limits_repr():104 limits = httpx.PoolLimits(max_connections=100)105 assert repr(limits) == "PoolLimits(max_keepalive=None, max_connections=100)"106 65 unmodified lines172 def test_ssl_config_support_for_keylog_file(tmpdir, monkeypatch): # pragma: nocover173 with monkeypatch.context() as m:174 m.delenv("SSLKEYLOGFILE", raising=False)175 193- ssl_config = SSLConfig(trust_env=True)176+ context = httpx.create_ssl_context(trust_env=True)177 195- assert ssl_config.ssl_context.keylog_filename is None # type: ignore178+ assert context.keylog_filename is None # type: ignore179 180 filename = str(tmpdir.join("test.log"))181 182 with monkeypatch.context() as m:183 m.setenv("SSLKEYLOGFILE", filename)184 202- ssl_config = SSLConfig(trust_env=True)185+ context = httpx.create_ssl_context(trust_env=True)186 204- assert ssl_config.ssl_context.keylog_filename == filename # type: ignore187+ assert context.keylog_filename == filename # type: ignore188 206- ssl_config = SSLConfig(trust_env=False)189+ context = httpx.create_ssl_context(trust_env=False)190 208- assert ssl_config.ssl_context.keylog_filename is None # type: ignore191+ assert context.keylog_filename is None # type: ignore192 193 194 @pytest.mark.parametrize(195 "url,expected_url,expected_headers,expected_mode",29 unmodified lines