Add support for SSLKEYLOGFILE (#301)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Skip test if OpenSSL version is lower than 1.1.1 * Use bionic dist for Python 3.8 job * Pass trust_env to SSLConfig use monkeypatch in testing * Don't raise KeyError if SSLKEYLOGFILE is not set * Move trust_env after verify and cert
authored by Tomás Farías · committed by Seth Michael Larson · parent e34d280 · Browse files · 7 files·+89 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+89 added−3 removed
- tests:+31 added−0 removed
- other:+58 added−3 removed
Provenance
- Commit
db7f2d0- Tree
0879855- Author
Tomás Farías <tomasfariassantana@gmail.com>- Committer
Seth Michael Larson <sethmichaellarson@gmail.com>- Parent
e34d280
7 files changed+89 added−3 removed
modified:docs/environment_variables.md+35 added
42 unmodified lines43444546474849505152535455565758596061626364656667686970717273747576777879808142 unmodified lines20:54:17.742 - httpx.dispatch.http2 - receive_event stream_id=1 event=<StreamEnded stream_id:1>20:54:17.742 - httpx.dispatch.http2 - receive_event stream_id=0 event=<PingReceived ping_data:0000000000000000>20:54:17.743 - httpx.dispatch.connection_pool - release_connection connection=HTTPConnection(origin=Origin(scheme='https' host='www.google.com' port=443))```
`SSLKEYLOGFILE`-----------
Valid values: a filename
If this environment variable is set, TLS keys will be appended to the specified file, creating it if it doesn't exist, whenever key material is generated or received. The keylog file is designed for debugging purposes only.
Support for `SSLKEYLOGFILE` requires Python 3.8 and OpenSSL 1.1.1 or newer.
Example:
```python# test_script.py
import httpxclient = httpx.Client()client.get("https://google.com")```
```consoleSSLKEYLOGFILE=test.log python test_script.pycat test.log# TLS secrets log file, generated by OpenSSL / PythonSERVER_HANDSHAKE_TRAFFIC_SECRET XXXXEXPORTER_SECRET XXXXSERVER_TRAFFIC_SECRET_0 XXXXCLIENT_HANDSHAKE_TRAFFIC_SECRET XXXXCLIENT_TRAFFIC_SECRET_0 XXXXSERVER_HANDSHAKE_TRAFFIC_SECRET XXXXEXPORTER_SECRET XXXXSERVER_TRAFFIC_SECRET_0 XXXXCLIENT_HANDSHAKE_TRAFFIC_SECRET XXXXCLIENT_TRAFFIC_SECRET_0 XXXX```modified:httpx/dispatch/connection_pool.py+3 added
82 unmodified lines83 self,84 *,85 verify: VerifyTypes = True,86 cert: CertTypes = None,87+ trust_env: bool = None,88 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,89 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,90 http_versions: HTTPVersionTypes = None,91 backend: ConcurrencyBackend = None,3 unmodified lines95 self.timeout = timeout96 self.pool_limits = pool_limits97 self.http_versions = http_versions98 self.is_closed = False99+ self.trust_env = trust_env100 101 self.keepalive_connections = ConnectionStore()102 self.active_connections = ConnectionStore()103 42 unmodified lines146 timeout=self.timeout,147 http_versions=self.http_versions,148 backend=self.backend,149 release_func=self.release_connection,150+ trust_env=self.trust_env,151 )152 logger.debug(f"new_connection connection={connection!r}")153 else:154 logger.debug(f"reuse_connection connection={connection!r}")27 unmodified linesmodified:httpx/dispatch/connection.py+2 added-1 removed
31 unmodified lines32 self,33 origin: typing.Union[str, Origin],34 verify: VerifyTypes = True,35 cert: CertTypes = None,36+ trust_env: bool = None,37 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,38 http_versions: HTTPVersionTypes = None,39 backend: ConcurrencyBackend = None,40 release_func: typing.Optional[ReleaseCallback] = None,41 ):42 self.origin = Origin(origin) if isinstance(origin, str) else origin42- self.ssl = SSLConfig(cert=cert, verify=verify)43+ self.ssl = SSLConfig(cert=cert, verify=verify, trust_env=trust_env)44 self.timeout = TimeoutConfig(timeout)45 self.http_versions = HTTPVersionConfig(http_versions)46 self.backend = AsyncioBackend() if backend is None else backend47 self.release_func = release_func92 unmodified linesmodified:httpx/client.py+3 added-1 removed
80 unmodified lines81 dispatch = WSGIDispatch(app=app)82 else:83 dispatch = ASGIDispatch(app=app)84 85+ self.trust_env = True if trust_env is None else trust_env86+87 if dispatch is None:88 async_dispatch: AsyncDispatcher = ConnectionPool(89 verify=verify,90 cert=cert,91 timeout=timeout,92 http_versions=http_versions,93 pool_limits=pool_limits,94 backend=backend,95+ trust_env=self.trust_env,96 )97 elif isinstance(dispatch, Dispatcher):98 async_dispatch = ThreadedDispatcher(dispatch, backend)99 else:9 unmodified lines109 self._cookies = Cookies(cookies)110 self.max_redirects = max_redirects111 self.dispatch = async_dispatch112 self.concurrency_backend = backend110- self.trust_env = True if trust_env is None else trust_env113 114 @property115 def headers(self) -> Headers:116 return self._headers894 unmodified linesmodified:httpx/config.py+14 added-1 removed
1+import os2 import ssl3 import typing4 from pathlib import Path5 37 unmodified lines43 """44 SSL Configuration.45 """46 46- def __init__(self, *, cert: CertTypes = None, verify: VerifyTypes = True):47+ def __init__(48+ self,49+ *,50+ cert: CertTypes = None,51+ verify: VerifyTypes = True,52+ trust_env: bool = None,53+ ):54 self.cert = cert55 56 # Allow passing in our own SSLContext object that's pre-configured.57 # If you do this we assume that you want verify=True as well.4 unmodified lines62 self._load_client_certs(ssl_context)63 64 self.ssl_context: typing.Optional[ssl.SSLContext] = ssl_context65 self.verify: typing.Union[str, bool] = verify66+ self.trust_env = trust_env67 68 def __eq__(self, other: typing.Any) -> bool:69 return (70 isinstance(other, self.__class__)102 unmodified lines173 context.set_alpn_protocols(http_versions.alpn_identifiers)174 if ssl.HAS_NPN: # pragma: no cover175 context.set_npn_protocols(http_versions.alpn_identifiers)176 177+ if hasattr(context, "keylog_filename"):178+ keylogfile = os.environ.get("SSLKEYLOGFILE")179+ if keylogfile and self.trust_env:180+ context.keylog_filename = keylogfile # type: ignore181+182 return context183 184 def _load_client_certs(self, ssl_context: ssl.SSLContext) -> None:185 """151 unmodified linesmodified:tests/test_config.py+31 added
1 import ssl2+import sys3 4 import pytest5 6 import httpx164 unmodified lines171 172 def test_timeout_from_config_instance():173 timeout = httpx.TimeoutConfig(timeout=5.0)174 assert httpx.TimeoutConfig(timeout) == httpx.TimeoutConfig(timeout=5.0)175+176+177+@pytest.mark.skipif(178+ not hasattr(ssl.SSLContext, "keylog_filename"),179+ reason="requires OpenSSL 1.1.1 or higher",180+)181+@pytest.mark.skipif(sys.version_info < (3, 8), reason="requires python3.8 or higher")182+def test_ssl_config_support_for_keylog_file(tmpdir, monkeypatch):183+ with monkeypatch.context() as m:184+ m.delenv("SSLKEYLOGFILE", raising=False)185+186+ ssl_config = httpx.SSLConfig(trust_env=True)187+ ssl_config.load_ssl_context()188+189+ assert ssl_config.ssl_context.keylog_filename is None190+191+ filename = str(tmpdir.join("test.log"))192+193+ with monkeypatch.context() as m:194+ m.setenv("SSLKEYLOGFILE", filename)195+196+ ssl_config = httpx.SSLConfig(trust_env=True)197+ ssl_config.load_ssl_context()198+199+ assert ssl_config.ssl_context.keylog_filename == filename200+201+ ssl_config = httpx.SSLConfig(trust_env=False)202+ ssl_config.load_ssl_context()203+204+ assert ssl_config.ssl_context.keylog_filename is Nonemodified:.travis.yml+1 added
18 unmodified lines1920212223242526278 unmodified lines18 unmodified lines - python: 3.7 env: NOX_SESSION=test-3.7 - python: 3.8-dev env: NOX_SESSION=test-3.8 dist: bionic # Required to get OpenSSL 1.1.1+
install: - pip install --upgrade nox
8 unmodified lines