From e3d91ee13201035afa857c1862800541bc321ca1 Mon Sep 17 00:00:00 2001 From: Timo Reymann Date: Mon, 2 Dec 2024 16:52:15 +0100 Subject: [PATCH] fix: Patch preloaded SSL context for requests library requests 2.32.0 introduced a preloaded SSL context, which needs to be patched manually unfortunately --- src/truststore/_api.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/truststore/_api.py b/src/truststore/_api.py index d88b1b3..8c50ba4 100644 --- a/src/truststore/_api.py +++ b/src/truststore/_api.py @@ -34,6 +34,7 @@ def inject_into_ssl() -> None: module by replacing :class:`ssl.SSLContext`. """ setattr(ssl, "SSLContext", SSLContext) + # urllib3 holds on to its own reference of ssl.SSLContext # so we need to replace that reference too. try: @@ -43,6 +44,19 @@ def inject_into_ssl() -> None: except ImportError: pass + # requests starting with 3.23.0 added a preloaded SSL context to improve concurrent performance; + # this unfortunately leads to a RecursionError, which can be avoided by patching the preloaded SSL context with + # the truststore patched instance + # also see https://github.com/psf/requests/pull/6667 + try: + import requests.adapters + + preloaded_context = getattr(requests.adapters, "_preloaded_ssl_context", None) + if preloaded_context is not None: + setattr(requests.adapters, "_preloaded_ssl_context", SSLContext(ssl.PROTOCOL_TLS_CLIENT)) + except ImportError: + pass + def extract_from_ssl() -> None: """Restores the :class:`ssl.SSLContext` class to its original state"""