Skip to content
Myr

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

3 files+23 added−51 removed

modified:httpx/dispatch/connection.py+2 added-9 removed
1import functools2import ssl2import typing34import h115
41 unmodified lines
47 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_context5253 if self.release_func is None:54 on_release = None55 else:
46 unmodified lines
102103 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_context107108 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=timeout
16 unmodified lines
127 )128 else:129 self.connection = HTTP11Connection(socket, on_release=on_release)130133 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()137131 async def close(self) -> None:132 logger.trace("close_connection")133 if self.connection is not None:134 await self.connection.close()
15 unmodified lines
modified:httpx/config.py+11 added-21 removed
61 unmodified lines
62 trust_env: bool = None,63 http2: bool = False,64 ):65 self.cert = cert6667 # 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)7475 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()7071 def __eq__(self, other: typing.Any) -> bool:72 return (73 isinstance(other, self.__class__)
13 unmodified lines
87 f"trust_env={self.trust_env!r} "88 f"http2={self.http2!r}"89 )90100 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()94107 assert self.ssl_context is not None108 return self.ssl_context10995 def load_ssl_context_no_verify(self) -> ssl.SSLContext:96 """97 Return an SSL context for unverified connections.98 """
10 unmodified lines
109 ca_bundle = get_ca_bundle_from_env()110 if ca_bundle is not None:111 self.verify = ca_bundle # type: ignore112128 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 lines
modified:tests/test_config.py+10 added-21 removed
11 unmodified lines
121314def 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 True192021def 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")242526def 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 True3132
4 unmodified lines
37 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 lines
5657def 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 True636465def 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 True7071
3 unmodified lines
75):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 True828384def 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 )9187 with pytest.raises(ssl.SSLError):93 ssl_config.load_ssl_context()88 SSLConfig(cert=(cert_pem_file, cert_encrypted_private_key_file, "password1"))899091def 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)949596def 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 False101102103def test_load_ssl_context():104 ssl_context = ssl.create_default_context()105 ssl_config = SSLConfig(verify=ssl_context)106113 assert ssl_config.verify is True107 assert ssl_config.ssl_context is ssl_context115 assert repr(ssl_config) == "SSLConfig(cert=None, verify=True)"108109110def test_ssl_repr():111 ssl = SSLConfig(verify=False)
78 unmodified lines
190 with monkeypatch.context() as m:191 m.delenv("SSLKEYLOGFILE", raising=False)192193 ssl_config = SSLConfig(trust_env=True)202 ssl_config.load_ssl_context()194195 assert ssl_config.ssl_context.keylog_filename is None196197 filename = str(tmpdir.join("test.log"))
1 unmodified line
199 with monkeypatch.context() as m:200 m.setenv("SSLKEYLOGFILE", filename)201202 ssl_config = SSLConfig(trust_env=True)212 ssl_config.load_ssl_context()203204 assert ssl_config.ssl_context.keylog_filename == filename205206 ssl_config = SSLConfig(trust_env=False)217 ssl_config.load_ssl_context()207208 assert ssl_config.ssl_context.keylog_filename is None