Skip to content

Commit

Permalink
Patch preloaded SSLContext in Requests
Browse files Browse the repository at this point in the history
Co-authored-by: Seth Michael Larson <sethmichaellarson@gmail.com>
  • Loading branch information
timo-reymann and sethmlarson authored Jan 13, 2025
1 parent 911ceab commit 8e86b91
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 18 additions & 1 deletion src/truststore/_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import sys
import typing

import _ssl # type: ignore[import-not-found]
import _ssl

from ._ssl_constants import (
_original_SSLContext,
Expand Down Expand Up @@ -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"""
Expand Down

0 comments on commit 8e86b91

Please sign in to comment.