Skip to content
Myr

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

6 files+72 added−83 removed

modified:docs/advanced.md+17 added
598 unmodified lines
599>>> httpx.get('https://example.org', verify=context)600<Response [200 OK]>601```602603We also include a helper function for creating properly configured `SSLContext` instances.604605```python606>>> context = httpx.create_ssl_context()607```608609The `create_ssl_context` function accepts the same set of SSL configuration arguments 610(`trust_env`, `verify`, `cert` and `http2` arguments) 611as `httpx.Client` or `httpx.AsyncClient`612613```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```619620Or you can also disable the SSL verification entirely, which is _not_ recommended.621622```python623import httpx
86 unmodified lines
modified:httpx/_transports/urllib3.py+7 added-11 removed
1 unmodified line
2from typing import Dict, Iterator, List, Optional, Tuple34import httpcore56from .._config import SSLConfig6from .._config import create_ssl_context7from .._content_streams import ByteStream, IteratorStream8from .._exceptions import NetworkError, map_exceptions9from .._types import CertTypes, VerifyTypes10
18 unmodified lines
29 assert (30 urllib3 is not None31 ), "urllib3 must be installed in order to use URLLib3Transport"3233 ssl_config = SSLConfig(34 verify=verify, cert=cert, trust_env=trust_env, http2=False35 )3633 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 lines
136 assert (137 urllib3 is not None138 ), "urllib3 must be installed in order to use URLLib3ProxyTransport"139142 ssl_config = SSLConfig(143 verify=verify, cert=cert, trust_env=trust_env, http2=False144 )145140 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
1from .__version__ import __description__, __title__, __version__2from ._api import delete, get, head, options, patch, post, put, request, stream3from ._auth import Auth, BasicAuth, DigestAuth4from ._client import AsyncClient, Client5from ._config import PoolLimits, Proxy, Timeout5from ._config import PoolLimits, Proxy, Timeout, create_ssl_context6from ._exceptions import (7 CloseError,8 ConnectError,9 ConnectTimeout,
50 unmodified lines
60 "DigestAuth",61 "PoolLimits",62 "Proxy",63 "Timeout",64 "create_ssl_context",65 "CloseError",66 "ConnectError",67 "ConnectTimeout",68 "CookieConflict",
34 unmodified lines
modified:httpx/_client.py+5 added-13 removed
11 unmodified lines
12 DEFAULT_TIMEOUT_CONFIG,13 UNSET,14 PoolLimits,15 Proxy,16 SSLConfig,16 Timeout,17 UnsetType,18 create_ssl_context,19)20from ._content_streams import ContentStream21from ._exceptions import (22 HTTPCORE_EXC_MAP,
475 unmodified lines
498499 if app is not None:500 return WSGITransport(app=app)501502 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)503504 return httpcore.SyncConnectionPool(505 ssl_context=ssl_context,506 max_keepalive=pool_limits.max_keepalive,
10 unmodified lines
517 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)522523 return httpcore.SyncHTTPProxy(524 proxy_url=proxy.url.raw,525 proxy_headers=proxy.headers.raw,
501 unmodified lines
10271028 if app is not None:1029 return ASGITransport(app=app)10301035 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)10321033 return httpcore.AsyncConnectionPool(1034 ssl_context=ssl_context,1035 max_keepalive=pool_limits.max_keepalive,
10 unmodified lines
1046 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)10511052 return httpcore.AsyncHTTPProxy(1053 proxy_url=proxy.url.raw,1054 proxy_headers=proxy.headers.raw,
446 unmodified lines
modified:httpx/_config.py+11 added-11 removed
38 unmodified lines
3940UNSET = UnsetType()414243def 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_context525354class SSLConfig:55 """56 SSL Configuration.57 """
13 unmodified lines
71 self.trust_env = trust_env72 self.http2 = http273 self.ssl_context = self.load_ssl_context()7464 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 )7071 def __repr__(self) -> str:72 class_name = self.__class__.__name__73 return f"{class_name}(cert={self.cert}, verify={self.verify})"7475 def load_ssl_context(self) -> ssl.SSLContext:76 logger.trace(77 f"load_ssl_context "78 f"verify={self.verify!r} "
280 unmodified lines
modified:tests/test_config.py+30 added-47 removed
1import os2import socket2import ssl3import sys4from pathlib import Path56import certifi7import pytest89import httpx11from httpx._config import SSLConfig101112def 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 True161718def 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")212223def 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 True272829@pytest.mark.parametrize("config", ("SSL_CERT_FILE", "SSL_CERT_DIR"))34def test_load_ssl_config_verify_env_file(https_server, ca_cert_pem_file, config):30def 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)4041 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()) == 14446 # 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()) == 1455646def 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 True515253def 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 True575859@pytest.mark.parametrize("password", [b"password", "password"])60def 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 True686970def 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 )777879def 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)828384def 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 False888990def 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)93107 assert ssl_config.ssl_context is ssl_context94 assert context is ssl_context9596110def test_ssl_repr():111 ssl = SSLConfig(verify=False)112 assert repr(ssl) == "SSLConfig(cert=None, verify=False)"97def 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 == 200101102115def test_ssl_eq():116 ssl = SSLConfig(verify=False)117 assert ssl == SSLConfig(verify=False)118119103def test_limits_repr():104 limits = httpx.PoolLimits(max_connections=100)105 assert repr(limits) == "PoolLimits(max_keepalive=None, max_connections=100)"106
65 unmodified lines
172def test_ssl_config_support_for_keylog_file(tmpdir, monkeypatch): # pragma: nocover173 with monkeypatch.context() as m:174 m.delenv("SSLKEYLOGFILE", raising=False)175193 ssl_config = SSLConfig(trust_env=True)176 context = httpx.create_ssl_context(trust_env=True)177195 assert ssl_config.ssl_context.keylog_filename is None # type: ignore178 assert context.keylog_filename is None # type: ignore179180 filename = str(tmpdir.join("test.log"))181182 with monkeypatch.context() as m:183 m.setenv("SSLKEYLOGFILE", filename)184202 ssl_config = SSLConfig(trust_env=True)185 context = httpx.create_ssl_context(trust_env=True)186204 assert ssl_config.ssl_context.keylog_filename == filename # type: ignore187 assert context.keylog_filename == filename # type: ignore188206 ssl_config = SSLConfig(trust_env=False)189 context = httpx.create_ssl_context(trust_env=False)190208 assert ssl_config.ssl_context.keylog_filename is None # type: ignore191 assert context.keylog_filename is None # type: ignore192193194@pytest.mark.parametrize(195 "url,expected_url,expected_headers,expected_mode",
29 unmodified lines