Repository navigation
Cache default SSLContext in create_ssl_context() - #3863
Burakceliks wants to merge 1 commit into
Conversation
ege-arhan
left a comment
There was a problem hiding this comment.
Caching the default SSLContext makes it a shared mutable object, and httpcore mutates it per connection: ssl_context.set_alpn_protocols(alpn_protocols) in httpcore/_sync/connection.py:147 (and the proxy variants), where the list depends on the client's http2 flag. With the cache on httpx/_config.py:24, every Client with verify=True, cert=None now gets the same object, so whichever client connected last decides the ALPN list for all of them.
Repro against this branch, SSL_CERT_FILE pointing at a test CA:
cached = httpx.create_ssl_context()
cached.set_alpn_protocols(["h2"]) # Client(http2=True)
cached.set_alpn_protocols(["http/1.1"]) # a plain Client() connects, httpcore rewrites ALPN
# http2=True client's next handshake now offers only http/1.1Against an h2-only server the handshake comes back with selected_alpn_protocol() is None, so the http2 client silently downgrades or fails to negotiate; on main the same client negotiates h2. I hit this with two clients in one process, but it is also a race for concurrent clients since the mutation happens on each connection.
The cache is still a reasonable idea, but the value cannot be the object handed to httpcore. Either cache the inputs (the loaded CA bundle) and build a fresh context per client, or have the transport copy: ssl.SSLContext has no copy(), so ssl.create_default_context(cafile=...) per client with a cached certifi path is the simple version. If you keep sharing, ALPN has to stop being set on the shared object, which means a change in httpcore, not here.
Also note test_default_ssl_context_is_cached asserts the identity that causes this, so it would need to flip to asserting the per-client isolation.
Fixes #3734
Summary
Caches the default
ssl.SSLContextcreated bycreate_ssl_context()viafunctools.lru_cachewhenverify=Trueandcert=None, avoiding repeated OpenSSL CA bundle allocations across clients/requests.(cafile, capath, keylog_file)soSSL_CERT_FILE,SSL_CERT_DIR, andSSLKEYLOGFILEenvironment overrides continue to work as expected.certis provided soctx.load_cert_chain(...)never mutates a shared context.test_default_ssl_context_is_cachedintests/test_config.py(29/29 passed,ruff checkpassed).