Load SSL Context on init (#709)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by GitHub · parent f5eaec7 · Browse files · 3 files·+23 added−51 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+23 added−51 removed
- tests:+10 added−21 removed
- other:+13 added−30 removed
Provenance
- Commit
79a9748- Tree
b863cd2- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
f5eaec7
3 files changed+23 added−51 removed
modified:httpx/dispatch/connection.py+2 added-9 removed
1 import functools2-import ssl2 import typing3 4 import h115 41 unmodified lines47 self, timeout: Timeout48 ) -> typing.Union[HTTP11Connection, HTTP2Connection]:49 host = self.origin.host50 port = self.origin.port52- ssl_context = self.get_ssl_context()51+ ssl_context = None if not self.origin.is_ssl else self.ssl.ssl_context52 53 if self.release_func is None:54 on_release = None55 else:46 unmodified lines102 103 if origin.is_ssl:104 # Pull the socket stream off the internal HTTP connection object,105 # and run start_tls().107- ssl_context = self.get_ssl_context()108- assert ssl_context is not None106+ ssl_context = self.ssl.ssl_context107 108 logger.trace(f"tunnel_start_tls proxy_url={proxy_url!r} origin={origin!r}")109 socket = await socket.start_tls(110 hostname=origin.host, ssl_context=ssl_context, timeout=timeout16 unmodified lines127 )128 else:129 self.connection = HTTP11Connection(socket, on_release=on_release)130 133- def get_ssl_context(self) -> typing.Optional[ssl.SSLContext]:134- if not self.origin.is_ssl:135- return None136- return self.ssl.load_ssl_context()137-131 async def close(self) -> None:132 logger.trace("close_connection")133 if self.connection is not None:134 await self.connection.close()15 unmodified linesmodified:httpx/config.py+11 added-21 removed
61 unmodified lines62 trust_env: bool = None,63 http2: bool = False,64 ):65 self.cert = cert66-67- # Allow passing in our own SSLContext object that's pre-configured.68- # If you do this we assume that you want verify=True as well.69- ssl_context = None70- if isinstance(verify, ssl.SSLContext):71- ssl_context = verify72- verify = True73- self._load_client_certs(ssl_context)74-75- self.ssl_context: typing.Optional[ssl.SSLContext] = ssl_context76- self.verify: typing.Union[str, bool] = verify66+ self.verify = verify67 self.trust_env = trust_env68 self.http2 = http269+ self.ssl_context = self.load_ssl_context()70 71 def __eq__(self, other: typing.Any) -> bool:72 return (73 isinstance(other, self.__class__)13 unmodified lines87 f"trust_env={self.trust_env!r} "88 f"http2={self.http2!r}"89 )90 100- if self.ssl_context is None:101- self.ssl_context = (102- self.load_ssl_context_verify()103- if self.verify104- else self.load_ssl_context_no_verify()105- )91+ if self.verify:92+ return self.load_ssl_context_verify()93+ return self.load_ssl_context_no_verify()94 107- assert self.ssl_context is not None108- return self.ssl_context109-95 def load_ssl_context_no_verify(self) -> ssl.SSLContext:96 """97 Return an SSL context for unverified connections.98 """10 unmodified lines109 ca_bundle = get_ca_bundle_from_env()110 if ca_bundle is not None:111 self.verify = ca_bundle # type: ignore112 128- if isinstance(self.verify, bool):113+ if isinstance(self.verify, ssl.SSLContext):114+ # Allow passing in our own SSLContext object that's pre-configured.115+ context = self.verify116+ self._load_client_certs(context)117+ return context118+ elif isinstance(self.verify, bool):119 ca_bundle_path = self.DEFAULT_CA_BUNDLE_PATH120 elif Path(self.verify).exists():121 ca_bundle_path = Path(self.verify)122 else:191 unmodified linesmodified:tests/test_config.py+10 added-21 removed
11 unmodified lines12 13 14 def test_load_ssl_config():15 ssl_config = SSLConfig()16- context = ssl_config.load_ssl_context()16+ context = ssl_config.ssl_context17 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED18 assert context.check_hostname is True19 20 21 def test_load_ssl_config_verify_non_existing_path():22- ssl_config = SSLConfig(verify="/path/to/nowhere")22 with pytest.raises(IOError):24- ssl_config.load_ssl_context()23+ SSLConfig(verify="/path/to/nowhere")24 25 26 def test_load_ssl_config_verify_existing_file():27 ssl_config = SSLConfig(verify=certifi.where())29- context = ssl_config.load_ssl_context()28+ context = ssl_config.ssl_context29 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED30 assert context.check_hostname is True31 32 4 unmodified lines37 if config.endswith("_FILE")38 else str(Path(ca_cert_pem_file).parent)39 )40 ssl_config = SSLConfig(trust_env=True)42- context = ssl_config.load_ssl_context()41+ context = ssl_config.ssl_context42 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED43 assert context.check_hostname is True44 assert ssl_config.verify == os.environ[config]45 10 unmodified lines56 57 def test_load_ssl_config_verify_directory():58 path = Path(certifi.where()).parent59 ssl_config = SSLConfig(verify=path)61- context = ssl_config.load_ssl_context()60+ context = ssl_config.ssl_context61 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED62 assert context.check_hostname is True63 64 65 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))68- context = ssl_config.load_ssl_context()67+ context = ssl_config.ssl_context68 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED69 assert context.check_hostname is True70 71 3 unmodified lines75 ):76 ssl_config = SSLConfig(77 cert=(cert_pem_file, cert_encrypted_private_key_file, password)78 )80- context = ssl_config.load_ssl_context()79+ context = ssl_config.ssl_context80 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED81 assert context.check_hostname is True82 83 84 def test_load_ssl_config_cert_and_key_invalid_password(85 cert_pem_file, cert_encrypted_private_key_file86 ):88- ssl_config = SSLConfig(89- cert=(cert_pem_file, cert_encrypted_private_key_file, "password1")90- )91-87 with pytest.raises(ssl.SSLError):93- ssl_config.load_ssl_context()88+ SSLConfig(cert=(cert_pem_file, cert_encrypted_private_key_file, "password1"))89 90 91 def test_load_ssl_config_cert_without_key_raises(cert_pem_file):97- ssl_config = SSLConfig(cert=cert_pem_file)92 with pytest.raises(ssl.SSLError):99- ssl_config.load_ssl_context()93+ SSLConfig(cert=cert_pem_file)94 95 96 def test_load_ssl_config_no_verify():97 ssl_config = SSLConfig(verify=False)104- context = ssl_config.load_ssl_context()98+ context = ssl_config.ssl_context99 assert context.verify_mode == ssl.VerifyMode.CERT_NONE100 assert context.check_hostname is False101 102 103 def test_load_ssl_context():104 ssl_context = ssl.create_default_context()105 ssl_config = SSLConfig(verify=ssl_context)106 113- assert ssl_config.verify is True107 assert ssl_config.ssl_context is ssl_context115- assert repr(ssl_config) == "SSLConfig(cert=None, verify=True)"108 109 110 def test_ssl_repr():111 ssl = SSLConfig(verify=False)78 unmodified lines190 with monkeypatch.context() as m:191 m.delenv("SSLKEYLOGFILE", raising=False)192 193 ssl_config = SSLConfig(trust_env=True)202- ssl_config.load_ssl_context()194 195 assert ssl_config.ssl_context.keylog_filename is None196 197 filename = str(tmpdir.join("test.log"))1 unmodified line199 with monkeypatch.context() as m:200 m.setenv("SSLKEYLOGFILE", filename)201 202 ssl_config = SSLConfig(trust_env=True)212- ssl_config.load_ssl_context()203 204 assert ssl_config.ssl_context.keylog_filename == filename205 206 ssl_config = SSLConfig(trust_env=False)217- ssl_config.load_ssl_context()207 208 assert ssl_config.ssl_context.keylog_filename is None