Fix ssl context being recreated frequently in httpx (#89932)

* Fix ssl context being created every time in httpx

* its expensive, only do it once
This commit is contained in:
J. Nick Koston 2023-03-18 23:13:48 -10:00 committed by GitHub
parent 0e7bd401f2
commit 87264d219a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 12 additions and 2 deletions

View File

@ -271,7 +271,7 @@ def _async_get_connector(
return cast(aiohttp.BaseConnector, hass.data[key])
if verify_ssl:
ssl_context: bool | SSLContext = ssl_util.client_context()
ssl_context: bool | SSLContext = ssl_util.get_default_context()
else:
ssl_context = False

View File

@ -11,6 +11,7 @@ from typing_extensions import Self
from homeassistant.const import APPLICATION_NAME, EVENT_HOMEASSISTANT_CLOSE, __version__
from homeassistant.core import Event, HomeAssistant, callback
from homeassistant.loader import bind_hass
from homeassistant.util import ssl as ssl_util
from .frame import warn_use
@ -65,7 +66,7 @@ def create_async_httpx_client(
This method must be run in the event loop.
"""
client = HassHttpXAsyncClient(
verify=verify_ssl,
verify=ssl_util.get_default_context() if verify_ssl else False,
headers={USER_AGENT: SERVER_SOFTWARE},
**kwargs,
)

View File

@ -16,6 +16,15 @@ def client_context() -> ssl.SSLContext:
return ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH, cafile=cafile)
# Create this only once and reuse it
_DEFAULT_SSL_CONTEXT = client_context()
def get_default_context() -> ssl.SSLContext:
"""Return the default SSL context."""
return _DEFAULT_SSL_CONTEXT
def server_context_modern() -> ssl.SSLContext:
"""Return an SSL context following the Mozilla recommendations.