From 8e86b9145f7de9fbc2c999cd9b5dab42e32272b6 Mon Sep 17 00:00:00 2001 From: Timo Reymann Date: Mon, 13 Jan 2025 20:05:30 +0100 Subject: [PATCH] Patch preloaded SSLContext in Requests Co-authored-by: Seth Michael Larson --- .github/workflows/ci.yml | 2 +- src/truststore/_api.py | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7c24213..812d236 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -84,7 +84,7 @@ jobs: compileall: # Run 'python -m compileall' on an old Python version # to ensure that pip can vendor truststore successfully. - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 # pin to 22.04, as with 24.04 Python 3.7 is no longer available name: compileall steps: - uses: actions/checkout@v4 diff --git a/src/truststore/_api.py b/src/truststore/_api.py index d88b1b3..47b7a63 100644 --- a/src/truststore/_api.py +++ b/src/truststore/_api.py @@ -5,7 +5,7 @@ import sys import typing -import _ssl # type: ignore[import-not-found] +import _ssl from ._ssl_constants import ( _original_SSLContext, @@ -43,6 +43,23 @@ def inject_into_ssl() -> None: except ImportError: pass + # requests starting with 2.32.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"""