Merge branch 'psf:main' into patch-1
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by anupam-arista · committed by GitHub · parents 1286261, 0e322af · Browse files · 64 files·+1288 added−113 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
64 files+1288 added−113 removed
- tests:+789 added−3 removed
- other:+499 added−110 removed
Provenance
- Commit
06d2a38- Tree
fc4d2b7- Author
anupam-arista <118899211+anupam-arista@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
1286261- Parent 2
0e322af
64 files changed+1288 added−113 removed
modified:.github/ISSUE_TEMPLATE/Custom.md+3 added
12345678910---name: Request for Helpabout: Guidance on using Requests.labels:- "Question/Not a bug"- "actions/autoclose-qa"
---
Please refer to our [Stack Overflow tag](https://stackoverflow.com/questions/tagged/python-requests) for guidance.modified:.github/ISSUE_TEMPLATE/Feature_request.md+3 added
12345678910---name: Feature requestabout: Suggest an idea for this projectlabels:- "Feature Request"- "actions/autoclose-feat"
---
Requests is not accepting feature requests at this time.added:.github/workflows/close-issues.yml+35 added
1234567891011121314151617181920212223242526272829303132333435name: 'Autoclose Issues'
on: issues: types: - labeled
permissions: issues: write
jobs: close_qa: if: github.event.label.name == 'actions/autoclose-qa' runs-on: ubuntu-latest steps: - env: ISSUE_URL: ${{ github.event.issue.html_url }} GH_TOKEN: ${{ github.token }} run: | gh issue close $ISSUE_URL \ --comment "As described in the template, we won't be able to answer questions on this issue tracker. Please use [Stack Overflow](https://stackoverflow.com/)" \ --reason completed gh issue lock $ISSUE_URL --reason off_topic close_feature_request: if: github.event.label.name == 'actions/autoclose-feat' runs-on: ubuntu-latest steps: - env: ISSUE_URL: ${{ github.event.issue.html_url }} GH_TOKEN: ${{ github.token }} run: | gh issue close $ISSUE_URL \ --comment "As described in the template, Requests is not accepting feature requests" \ --reason "not planned" gh issue lock $ISSUE_URL --reason off_topicmodified:.github/workflows/codeql-analysis.yml+4 added-4 removed
30 unmodified lines313233343535363738394 unmodified lines444546474848495051522 unmodified lines555657585959606162635 unmodified lines69707172737330 unmodified lines
steps: - name: Checkout repository uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # v4.0.0 uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # v4.1.0 with: # We must fetch at least the immediate parents so that if this is # a pull request then we can checkout the head. fetch-depth: 24 unmodified lines if: ${{ github.event_name == 'pull_request' }}
# Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@5b6282e01c62d02e720b81eb8a51204f527c3624 # v2.21.3 uses: github/codeql-action/init@df5a14dc28094dc936e103b37d749c6628682b60 # v3.25.0 with: languages: "python" # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file.2 unmodified lines
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild uses: github/codeql-action/autobuild@5b6282e01c62d02e720b81eb8a51204f527c3624 # v2.21.3 uses: github/codeql-action/autobuild@df5a14dc28094dc936e103b37d749c6628682b60 # v3.25.0
# ℹ️ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl
5 unmodified lines # make bootstrap # make release
- name: Perform CodeQL Analysis uses: github/codeql-action/analyze@5b6282e01c62d02e720b81eb8a51204f527c3624 # v2.21.3 uses: github/codeql-action/analyze@df5a14dc28094dc936e103b37d749c6628682b60 # v3.25.0modified:.github/workflows/lint.yml+2 added-2 removed
9 unmodified lines101112131414151616171819209 unmodified lines runs-on: ubuntu-20.04 timeout-minutes: 10
steps: - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # v4.0.0 - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # v4.1.0 - name: Set up Python uses: actions/setup-python@61a6322f88396a6271a6ee3565807d608ecaddd1 # v4.7.0 uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.0 with: python-version: "3.x" - name: Run pre-commit uses: pre-commit/action@646c83fcd040023954eafda54b4db0192ce70507 # v3.0.0modified:.github/workflows/lock-issues.yml+1 added-1 removed
11 unmodified lines12131415161617181911 unmodified lines action: if: github.repository_owner == 'psf' runs-on: ubuntu-latest steps: - uses: dessant/lock-threads@be8aa5be94131386884a6da4189effda9b14aa21 # v4.0.1 - uses: dessant/lock-threads@d42e5f49803f3c4e14ffee0378e31481265dda22 # v5.0.0 with: issue-lock-inactive-days: 90 pr-lock-inactive-days: 90modified:.github/workflows/run-tests.yml+31 added-7 removed
10 unmodified lines111213141515161718192021222318192021242526272428292630313233343536373839404142434445464748495051525354555657585910 unmodified lines timeout-minutes: 10 strategy: fail-fast: false matrix: python-version: ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12-dev", "pypy-3.8", "pypy-3.9"] python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "pypy-3.9", "pypy-3.10"] os: [ubuntu-22.04, macOS-latest, windows-latest] # Python 3.8 and 3.9 do not run on macOS-latest which # is now using arm64 hardware. # https://github.com/actions/setup-python/issues/696#issuecomment-1637587760 exclude: - { python-version: "3.8", os: "macos-latest" } - { python-version: "3.9", os: "macos-latest" } include: # pypy-3.7 on Windows and Mac OS currently fails trying to compile # cryptography. Moving pypy-3.7 to only test linux. - python-version: pypy-3.7 os: ubuntu-latest - { python-version: "3.8", os: "macos-13" } - { python-version: "3.9", os: "macos-13" }
steps: - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # v4.0.0 - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # v4.1.0 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@61a6322f88396a6271a6ee3565807d608ecaddd1 # v4.7.0 uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.0 with: python-version: ${{ matrix.python-version }} cache: 'pip' - name: Install dependencies run: | make - name: Run tests run: | make ci
no_chardet: name: "No Character Detection" runs-on: ubuntu-latest strategy: fail-fast: true
steps: - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 - name: 'Set up Python 3.8' uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d with: python-version: '3.8' - name: Install dependencies run: | make python -m pip uninstall -y "charset_normalizer" "chardet" - name: Run tests run: | make cimodified:docs/_templates/sidebarintro.html+6 added-6 removed
14 unmodified lines15 </p>16 17 <h3>Useful Links</h3>18 <ul>19- <li><a href="https://requests.readthedocs.io/en/latest/user/quickstart/">Quickstart</a></li>20- <li><a href="https://requests.readthedocs.io/en/latest/user/advanced/">Advanced Usage</a></li>21- <li><a href="https://requests.readthedocs.io/en/latest/api/">API Reference</a></li>22- <li><a href="https://requests.readthedocs.io/en/latest/community/updates/#release-history">Release History</a></li>23- <li><a href="https://requests.readthedocs.io/en/latest/dev/contributing/">Contributors Guide</a></li>19+ <li><a href="{{ pathto('user/quickstart') }}">Quickstart</a></li>20+ <li><a href="{{ pathto('user/advanced') }}">Advanced Usage</a></li>21+ <li><a href="{{ pathto('api') }}">API Reference</a></li>22+ <li><a href="{{ pathto('community/updates') + '#release-history' }}">Release History</a></li>23+ <li><a href="{{ pathto('dev/contributing') }}">Contributors Guide</a></li>24 25 <p></p>26 27- <li><a href="https://requests.readthedocs.io/en/latest/community/recommended/">Recommended Packages and Extensions</a></li>27+ <li><a href="{{ pathto('community/recommended') }}">Recommended Packages and Extensions</a></li>28 29 <p></p>30 31 <li><a href="https://github.com/psf/requests">Requests @ GitHub</a></li>6 unmodified linesmodified:docs/_templates/sidebarlogo.html+6 added-6 removed
9 unmodified lines10 </p>11 12 <h3>Useful Links</h3>13 <ul>14- <li><a href="https://requests.readthedocs.io/en/latest/user/quickstart/">Quickstart</a></li>15- <li><a href="https://requests.readthedocs.io/en/latest/user/advanced/">Advanced Usage</a></li>16- <li><a href="https://requests.readthedocs.io/en/latest/api/">API Reference</a></li>17- <li><a href="https://requests.readthedocs.io/en/latest/community/updates/#release-history">Release History</a></li>18- <li><a href="https://requests.readthedocs.io/en/latest/dev/contributing/">Contributors Guide</a></li>14+ <li><a href="{{ pathto('user/quickstart') }}">Quickstart</a></li>15+ <li><a href="{{ pathto('user/advanced') }}">Advanced Usage</a></li>16+ <li><a href="{{ pathto('api') }}">API Reference</a></li>17+ <li><a href="{{ pathto('community/updates') + '#release-history' }}">Release History</a></li>18+ <li><a href="{{ pathto('dev/contributing') }}">Contributors Guide</a></li>19 20 <p></p>21 22- <li><a href="https://requests.readthedocs.io/en/latest/community/recommended/">Recommended Packages and Extensions</a></li>22+ <li><a href="{{ pathto('community/recommended') }}">Recommended Packages and Extensions</a></li>23 24 <p></p>25 26 <li><a href="https://github.com/psf/requests">Requests @ GitHub</a></li>4 unmodified linesmodified:docs/community/faq.rst+2 added-2 removed
20 unmodified lines21 Custom User-Agents?22 -------------------23 24 Requests allows you to easily override User-Agent strings, along with25-any other HTTP Header. See `documentation about headers <https://requests.readthedocs.io/en/latest/user/quickstart/#custom-headers>`_.25+any other HTTP Header. See :ref:`documentation about headers <custom-headers>`.26 27 28 29 Why not Httplib2?24 unmodified lines54 55 Python 3 Support?56 -----------------57 58-Yes! Requests officially supports Python 3.7+ and PyPy.58+Yes! Requests officially supports Python 3.8+ and PyPy.59 60 Python 2 Support?61 -----------------62 27 unmodified linesmodified:docs/community/out-there.rst+1 added-13 removed
1 Integrations2 ============3 4-Python for iOS5---------------6-7-Requests is built into the wonderful `Python for iOS <https://itunes.apple.com/us/app/python-2.7-for-ios/id485729872?mt=Python8>`_ runtime!8-9-To give it a try, simply::10-11- import requests12-13-4 Articles & Talks5 ================16-- `Python for the Web <https://www.gun.io/blog/python-for-the-web>`_ teaches how to use Python to interact with the web, using Requests.6 - `Daniel Greenfeld's Review of Requests <https://pydanny.blogspot.com/2011/05/python-http-requests-for-humans.html>`_18-- `My 'Python for Humans' talk <http://python-for-humans.heroku.com>`_ ( `audio <https://codeconf.s3.amazonaws.com/2011/pycodeconf/talks/PyCodeConf2011%20-%20Kenneth%20Reitz.m4a>`_ )19-- `Issac Kelly's 'Consuming Web APIs' talk <https://issackelly.github.com/Consuming-Web-APIs-with-Python-Talk/slides/slides.html>`_7+- `Issac Kelly's 'Consuming Web APIs' talk <https://issackelly.github.io/Consuming-Web-APIs-with-Python-Talk/slides/slides.html>`_8 - `Blog post about Requests via Yum <https://arunsag.wordpress.com/2011/08/17/new-package-python-requests-http-for-humans/>`_9 - `Russian blog post introducing Requests <https://habr.com/post/126262/>`_10 - `Sending JSON in Requests <http://www.coglib.com/~icordasc/blog/2014/11/sending-json-in-requests.html>`_modified:docs/user/advanced.rst+19 added-3 removed
289 unmodified lines290 291 For the sake of security we recommend upgrading certifi frequently!292 293 .. _HTTP persistent connection: https://en.wikipedia.org/wiki/HTTP_persistent_connection294-.. _connection pooling: https://urllib3.readthedocs.io/en/latest/reference/index.html#module-urllib3.connectionpool294+.. _connection pooling: https://urllib3.readthedocs.io/en/latest/reference/urllib3.connectionpool.html295 .. _certifi: https://certifiio.readthedocs.io/296 .. _Mozilla trust store: https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt297 298 .. _body-content-workflow:366 unmodified lines665 $ python666 >>> import requests667 >>> requests.get('https://example.org')668 669+.. _socks:670+671 SOCKS672 ^^^^^673 674 .. versionadded:: 2.10.0272 unmodified lines947 948 Many HTTP APIs feature Link headers. They make APIs more self describing and949 discoverable.950 949-GitHub uses these for `pagination <https://developer.github.com/v3/#pagination>`_951+GitHub uses these for `pagination <https://docs.github.com/en/rest/guides/using-pagination-in-the-rest-api>`_952 in their API, for example::953 954 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'955 >>> r = requests.head(url=url)142 unmodified lines1098 The **connect** timeout is the number of seconds Requests will wait for your1099 client to establish a connection to a remote machine (corresponding to the1100 `connect()`_) call on the socket. It's a good practice to set connect timeouts1101 to slightly larger than a multiple of 3, which is the default `TCP packet1100-retransmission window <https://www.hjp.at/doc/rfc/rfc2988.txt>`_.1102+retransmission window <https://datatracker.ietf.org/doc/html/rfc2988>`_.1103 1104 Once your client has connected to the server and sent the HTTP request, the1105 **read** timeout is the number of seconds the client will wait for the server1106 to send a response. (Specifically, it's the number of seconds that the client16 unmodified lines1123 ::1124 1125 r = requests.get('https://github.com', timeout=None)1126 1127+.. note:: The connect timeout applies to each connection attempt to an IP address.1128+ If multiple addresses exist for a domain name, the underlying ``urllib3`` will1129+ try each address sequentially until one successfully connects.1130+ This may lead to an effective total connection timeout *multiple* times longer1131+ than the specified time, e.g. an unresponsive server having both IPv4 and IPv61132+ addresses will have its perceived timeout *doubled*, so take that into account1133+ when setting the connection timeout.1134+.. note:: Neither the connect nor read timeouts are `wall clock`_. This means1135+ that if you start a request, and look at the time, and then look at1136+ the time when the request finishes or times out, the real-world time1137+ may be greater than what you specified.1138+1139+1140+.. _`wall clock`: https://wiki.php.net/rfc/max_execution_wall_time1141 .. _`connect()`: https://linux.die.net/man/2/connectmodified:docs/user/quickstart.rst+2 added-3 removed
199 unmodified lines200 transform the response content. If you really need access to the bytes as they201 were returned, use ``Response.raw``.202 203 204+.. _custom-headers:205+206 Custom Headers207 --------------208 209 If you'd like to add HTTP headers to a request, simply pass in a ``dict`` to the357 unmodified lines567 568 -----------------------569 570 Ready for more? Check out the :ref:`advanced <advanced>` section.569-570-571-If you're on the job market, consider taking `this programming quiz <https://triplebyte.com/a/b1i2FB8/requests-docs-1>`_. A substantial donation will be made to this project, if you find a job through this platform.modified:docs/index.rst+1 added-1 removed
70 unmodified lines71 - Connection Timeouts72 - Chunked Requests73 - ``.netrc`` Support74 75-Requests officially supports Python 3.7+, and runs great on PyPy.75+Requests officially supports Python 3.8+, and runs great on PyPy.76 77 78 The User Guide79 --------------61 unmodified linesmodified:docs/requirements.txt+1 added-1 removed
1 # Pinning to avoid unexpected breakages.2 # Used by RTD to generate docs.3-Sphinx==4.2.03+Sphinx==7.2.6modified:src/requests/__init__.py+5 added-1 removed
81 unmodified lines82 major, minor, patch = int(major), int(minor), int(patch)83 # charset_normalizer >= 2.0.0 < 4.0.084 assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0)85 else:86- raise Exception("You need either charset_normalizer or chardet installed")86+ warnings.warn(87+ "Unable to find acceptable character detection dependency "88+ "(chardet or charset_normalizer).",89+ RequestsDependencyWarning,90+ )91 92 93 def _check_cryptography(cryptography_version):94 # cryptography < 1.3.490 unmodified linesmodified:src/requests/__version__.py+2 added-2 removed
3 unmodified lines4 5 __title__ = "requests"6 __description__ = "Python HTTP for Humans."7 __url__ = "https://requests.readthedocs.io"8-__version__ = "2.31.0"9-__build__ = 0x0231008+__version__ = "2.32.3"9+__build__ = 0x02320310 __author__ = "Kenneth Reitz"11 __author_email__ = "me@kennethreitz.org"12 __license__ = "Apache-2.0"13 __copyright__ = "Copyright Kenneth Reitz"1 unmodified linemodified:src/requests/adapters.py+200 added-18 removed
6 unmodified lines7 """8 9 import os.path10 import socket # noqa: F40111+import typing12+import warnings13 14 from urllib3.exceptions import ClosedPoolError, ConnectTimeoutError15 from urllib3.exceptions import HTTPError as _HTTPError16 from urllib3.exceptions import InvalidHeader as _InvalidHeader9 unmodified lines26 from urllib3.poolmanager import PoolManager, proxy_from_url27 from urllib3.util import Timeout as TimeoutSauce28 from urllib3.util import parse_url29 from urllib3.util.retry import Retry30+from urllib3.util.ssl_ import create_urllib3_context31 32 from .auth import _basic_auth_str33 from .compat import basestring, urlparse34 from .cookies import extract_cookies_to_jar28 unmodified lines63 def SOCKSProxyManager(*args, **kwargs):64 raise InvalidSchema("Missing dependencies for SOCKS support.")65 66 67+if typing.TYPE_CHECKING:68+ from .models import PreparedRequest69+70+71 DEFAULT_POOLBLOCK = False72 DEFAULT_POOLSIZE = 1073 DEFAULT_RETRIES = 074 DEFAULT_POOL_TIMEOUT = None75 76 77+try:78+ import ssl # noqa: F40179+80+ _preloaded_ssl_context = create_urllib3_context()81+ _preloaded_ssl_context.load_verify_locations(82+ extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)83+ )84+except ImportError:85+ # Bypass default SSLContext creation when Python86+ # interpreter isn't built with the ssl module.87+ _preloaded_ssl_context = None88+89+90+def _urllib3_request_context(91+ request: "PreparedRequest",92+ verify: "bool | str | None",93+ client_cert: "typing.Tuple[str, str] | str | None",94+ poolmanager: "PoolManager",95+) -> "(typing.Dict[str, typing.Any], typing.Dict[str, typing.Any])":96+ host_params = {}97+ pool_kwargs = {}98+ parsed_request_url = urlparse(request.url)99+ scheme = parsed_request_url.scheme.lower()100+ port = parsed_request_url.port101+102+ # Determine if we have and should use our default SSLContext103+ # to optimize performance on standard requests.104+ poolmanager_kwargs = getattr(poolmanager, "connection_pool_kw", {})105+ has_poolmanager_ssl_context = poolmanager_kwargs.get("ssl_context")106+ should_use_default_ssl_context = (107+ _preloaded_ssl_context is not None and not has_poolmanager_ssl_context108+ )109+110+ cert_reqs = "CERT_REQUIRED"111+ if verify is False:112+ cert_reqs = "CERT_NONE"113+ elif verify is True and should_use_default_ssl_context:114+ pool_kwargs["ssl_context"] = _preloaded_ssl_context115+ elif isinstance(verify, str):116+ if not os.path.isdir(verify):117+ pool_kwargs["ca_certs"] = verify118+ else:119+ pool_kwargs["ca_cert_dir"] = verify120+ pool_kwargs["cert_reqs"] = cert_reqs121+ if client_cert is not None:122+ if isinstance(client_cert, tuple) and len(client_cert) == 2:123+ pool_kwargs["cert_file"] = client_cert[0]124+ pool_kwargs["key_file"] = client_cert[1]125+ else:126+ # According to our docs, we allow users to specify just the client127+ # cert path128+ pool_kwargs["cert_file"] = client_cert129+ host_params = {130+ "scheme": scheme,131+ "host": parsed_request_url.hostname,132+ "port": port,133+ }134+ return host_params, pool_kwargs135+136+137 class BaseAdapter:138 """The Base Transport Adapter"""139 140 def __init__(self):172 unmodified lines313 to a CA bundle to use314 :param cert: The SSL certificate to verify.315 """316 if url.lower().startswith("https") and verify:250- cert_loc = None317+ conn.cert_reqs = "CERT_REQUIRED"318 252- # Allow self-specified cert location.319+ # Only load the CA certificates if 'verify' is a string indicating the CA bundle to use.320+ # Otherwise, if verify is a boolean, we don't load anything since321+ # the connection will be using a context with the default certificates already loaded,322+ # and this avoids a call to the slow load_verify_locations()323 if verify is not True:324+ # `verify` must be a str with a path then325 cert_loc = verify326 256- if not cert_loc:257- cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)327+ if not os.path.exists(cert_loc):328+ raise OSError(329+ f"Could not find a suitable TLS CA certificate bundle, "330+ f"invalid path: {cert_loc}"331+ )332 259- if not cert_loc or not os.path.exists(cert_loc):260- raise OSError(261- f"Could not find a suitable TLS CA certificate bundle, "262- f"invalid path: {cert_loc}"263- )264-265- conn.cert_reqs = "CERT_REQUIRED"266-267- if not os.path.isdir(cert_loc):268- conn.ca_certs = cert_loc269- else:270- conn.ca_cert_dir = cert_loc333+ if not os.path.isdir(cert_loc):334+ conn.ca_certs = cert_loc335+ else:336+ conn.ca_cert_dir = cert_loc337 else:338 conn.cert_reqs = "CERT_NONE"339 conn.ca_certs = None340 conn.ca_cert_dir = None51 unmodified lines392 response.connection = self393 394 return response395 396+ def build_connection_pool_key_attributes(self, request, verify, cert=None):397+ """Build the PoolKey attributes used by urllib3 to return a connection.398+399+ This looks at the PreparedRequest, the user-specified verify value,400+ and the value of the cert parameter to determine what PoolKey values401+ to use to select a connection from a given urllib3 Connection Pool.402+403+ The SSL related pool key arguments are not consistently set. As of404+ this writing, use the following to determine what keys may be in that405+ dictionary:406+407+ * If ``verify`` is ``True``, ``"ssl_context"`` will be set and will be the408+ default Requests SSL Context409+ * If ``verify`` is ``False``, ``"ssl_context"`` will not be set but410+ ``"cert_reqs"`` will be set411+ * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)412+ ``"ca_certs"`` will be set if the string is not a directory recognized413+ by :py:func:`os.path.isdir`, otherwise ``"ca_certs_dir"`` will be414+ set.415+ * If ``"cert"`` is specified, ``"cert_file"`` will always be set. If416+ ``"cert"`` is a tuple with a second item, ``"key_file"`` will also417+ be present418+419+ To override these settings, one may subclass this class, call this420+ method and use the above logic to change parameters as desired. For421+ example, if one wishes to use a custom :py:class:`ssl.SSLContext` one422+ must both set ``"ssl_context"`` and based on what else they require,423+ alter the other keys to ensure the desired behaviour.424+425+ :param request:426+ The PreparedReqest being sent over the connection.427+ :type request:428+ :class:`~requests.models.PreparedRequest`429+ :param verify:430+ Either a boolean, in which case it controls whether431+ we verify the server's TLS certificate, or a string, in which case it432+ must be a path to a CA bundle to use.433+ :param cert:434+ (optional) Any user-provided SSL certificate for client435+ authentication (a.k.a., mTLS). This may be a string (i.e., just436+ the path to a file which holds both certificate and key) or a437+ tuple of length 2 with the certificate file path and key file438+ path.439+ :returns:440+ A tuple of two dictionaries. The first is the "host parameters"441+ portion of the Pool Key including scheme, hostname, and port. The442+ second is a dictionary of SSLContext related parameters.443+ """444+ return _urllib3_request_context(request, verify, cert, self.poolmanager)445+446+ def get_connection_with_tls_context(self, request, verify, proxies=None, cert=None):447+ """Returns a urllib3 connection for the given request and TLS settings.448+ This should not be called from user code, and is only exposed for use449+ when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.450+451+ :param request:452+ The :class:`PreparedRequest <PreparedRequest>` object to be sent453+ over the connection.454+ :param verify:455+ Either a boolean, in which case it controls whether we verify the456+ server's TLS certificate, or a string, in which case it must be a457+ path to a CA bundle to use.458+ :param proxies:459+ (optional) The proxies dictionary to apply to the request.460+ :param cert:461+ (optional) Any user-provided SSL certificate to be used for client462+ authentication (a.k.a., mTLS).463+ :rtype:464+ urllib3.ConnectionPool465+ """466+ proxy = select_proxy(request.url, proxies)467+ try:468+ host_params, pool_kwargs = self.build_connection_pool_key_attributes(469+ request,470+ verify,471+ cert,472+ )473+ except ValueError as e:474+ raise InvalidURL(e, request=request)475+ if proxy:476+ proxy = prepend_scheme_if_needed(proxy, "http")477+ proxy_url = parse_url(proxy)478+ if not proxy_url.host:479+ raise InvalidProxyURL(480+ "Please check proxy URL. It is malformed "481+ "and could be missing the host."482+ )483+ proxy_manager = self.proxy_manager_for(proxy)484+ conn = proxy_manager.connection_from_host(485+ **host_params, pool_kwargs=pool_kwargs486+ )487+ else:488+ # Only scheme should be lower case489+ conn = self.poolmanager.connection_from_host(490+ **host_params, pool_kwargs=pool_kwargs491+ )492+493+ return conn494+495 def get_connection(self, url, proxies=None):496+ """DEPRECATED: Users should move to `get_connection_with_tls_context`497+ for all subclasses of HTTPAdapter using Requests>=2.32.2.498+331- """Returns a urllib3 connection for the given URL. This should not be499+ Returns a urllib3 connection for the given URL. This should not be500 called from user code, and is only exposed for use when subclassing the501 :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.502 503 :param url: The URL to connect to.504 :param proxies: (optional) A Requests-style dictionary of proxies used on this request.505 :rtype: urllib3.ConnectionPool506 """507+ warnings.warn(508+ (509+ "`get_connection` has been deprecated in favor of "510+ "`get_connection_with_tls_context`. Custom HTTPAdapter subclasses "511+ "will need to migrate for Requests>=2.32.2. Please see "512+ "https://github.com/psf/requests/pull/6710 for more details."513+ ),514+ DeprecationWarning,515+ )516 proxy = select_proxy(url, proxies)517 518 if proxy:519 proxy = prepend_scheme_if_needed(proxy, "http")46 unmodified lines566 proxy_scheme = urlparse(proxy).scheme.lower()567 using_socks_proxy = proxy_scheme.startswith("socks")568 569 url = request.path_url570+ if url.startswith("//"): # Don't confuse urllib3571+ url = f"/{url.lstrip('/')}"572+573 if is_proxied_http_request and not using_socks_proxy:574 url = urldefragauth(request.url)575 576 return url52 unmodified lines629 :rtype: requests.Response630 """631 632 try:453- conn = self.get_connection(request.url, proxies)633+ conn = self.get_connection_with_tls_context(634+ request, verify, proxies=proxies, cert=cert635+ )636 except LocationValueError as e:637 raise InvalidURL(e, request=request)638 639 self.cert_verify(conn, request.url, verify, cert)80 unmodified linesmodified:src/requests/compat.py+20 added-5 removed
5 unmodified lines6 between Python 2 and Python 3. It remains for backwards7 compatibility until the next major version.8 """9 10-try:11- import chardet12-except ImportError:13- import charset_normalizer as chardet14-10+import importlib11 import sys12 13+# -------------------14+# Character Detection15+# -------------------16+17+18+def _resolve_char_detection():19+ """Find supported character detection libraries."""20+ chardet = None21+ for lib in ("chardet", "charset_normalizer"):22+ if chardet is None:23+ try:24+ chardet = importlib.import_module(lib)25+ except ImportError:26+ pass27+ return chardet28+29+30+chardet = _resolve_char_detection()31+32 # -------33 # Pythons34 # -------35 59 unmodified linesmodified:src/requests/exceptions.py+10 added
39 unmodified lines40 """41 CompatJSONDecodeError.__init__(self, *args)42 InvalidJSONError.__init__(self, *self.args, **kwargs)43 44+ def __reduce__(self):45+ """46+ The __reduce__ method called when pickling the object must47+ be the one from the JSONDecodeError (be it json/simplejson)48+ as it expects all the arguments for instantiation, not just49+ one like the IOError, and the MRO would by default call the50+ __reduce__ method from the IOError due to the inheritance order.51+ """52+ return CompatJSONDecodeError.__reduce__(self)53 54+55 class HTTPError(RequestException):56 """An HTTP error occurred."""57 58 93 unmodified linesmodified:src/requests/models.py+6 added-1 removed
787 unmodified lines788 789 @property790 def apparent_encoding(self):791 """The apparent encoding, provided by the charset_normalizer or chardet libraries."""792+ if chardet is not None:792- return chardet.detect(self.content)["encoding"]793+ return chardet.detect(self.content)["encoding"]794+ else:795+ # If no character detection library is available, we'll fall back796+ # to a standard Python utf-8 str.797+ return "utf-8"798 799 def iter_content(self, chunk_size=1, decode_unicode=False):800 """Iterates over the response data. When stream=True is set on the801 request, this avoids reading the content at once into memory for236 unmodified linesmodified:src/requests/packages.py+9 added-14 removed
1 import sys2 3-try:4- import chardet3+from .compat import chardet5-except ImportError:6- import warnings4 8- import charset_normalizer as chardet9-10- warnings.filterwarnings("ignore", "Trying to detect", module="charset_normalizer")11-5 # This code exists for backwards compatibility reasons.6 # I don't like it either. Just look the other way. :)7 8 for package in ("urllib3", "idna"):3 unmodified lines12 for mod in list(sys.modules):13 if mod == package or mod.startswith(f"{package}."):14 sys.modules[f"requests.packages.{mod}"] = sys.modules[mod]15 16+if chardet is not None:23-target = chardet.__name__24-for mod in list(sys.modules):25- if mod == target or mod.startswith(f"{target}."):26- target = target.replace(target, "chardet")27- sys.modules[f"requests.packages.{target}"] = sys.modules[mod]28-# Kinda cool, though, right?17+ target = chardet.__name__18+ for mod in list(sys.modules):19+ if mod == target or mod.startswith(f"{target}."):20+ imported_mod = sys.modules[mod]21+ sys.modules[f"requests.packages.{mod}"] = imported_mod22+ mod = mod.replace(target, "chardet")23+ sys.modules[f"requests.packages.{mod}"] = imported_modmodified:src/requests/status_codes.py+5 added-5 removed
22 unmodified lines23 _codes = {24 # Informational.25 100: ("continue",),26 101: ("switching_protocols",),27- 102: ("processing",),27+ 102: ("processing", "early-hints"),28 103: ("checkpoint",),29 122: ("uri_too_long", "request_uri_too_long"),30 200: ("ok", "okay", "all_ok", "all_okay", "all_good", "\\o/", "✓"),31 201: ("created",),32 unmodified lines64 409: ("conflict",),65 410: ("gone",),66 411: ("length_required",),67 412: ("precondition_failed", "precondition"),68- 413: ("request_entity_too_large",),69- 414: ("request_uri_too_large",),68+ 413: ("request_entity_too_large", "content_too_large"),69+ 414: ("request_uri_too_large", "uri_too_long"),70 415: ("unsupported_media_type", "unsupported_media", "media_type"),71 416: (72 "requested_range_not_satisfiable",73 "requested_range",1 unmodified line75 ),76 417: ("expectation_failed",),77 418: ("im_a_teapot", "teapot", "i_am_a_teapot"),78 421: ("misdirected_request",),79- 422: ("unprocessable_entity", "unprocessable"),79+ 422: ("unprocessable_entity", "unprocessable", "unprocessable_content"),80 423: ("locked",),81 424: ("failed_dependency", "dependency"),82- 425: ("unordered_collection", "unordered"),82+ 425: ("unordered_collection", "unordered", "too_early"),83 426: ("upgrade_required", "upgrade"),84 428: ("precondition_required", "precondition"),85 429: ("too_many_requests", "too_many"),86 431: ("header_fields_too_large", "fields_too_large"),42 unmodified linesmodified:src/requests/utils.py+7 added-2 removed
95 unmodified lines96 # make a check value list from the registry entry: replace the97 # '<local>' string by the localhost entry and the corresponding98 # canonical entry.99 proxyOverride = proxyOverride.split(";")100+ # filter out empty strings to avoid re.match return true in the following code.101+ proxyOverride = filter(None, proxyOverride)102 # now check if we match one of the registry values.103 for test in proxyOverride:104 if test == "<local>":105 if "." not in host:29 unmodified lines135 def super_len(o):136 total_length = None137 current_position = 0138 139+ if isinstance(o, str):140+ o = o.encode("utf-8")141+142 if hasattr(o, "__len__"):143 total_length = len(o)144 145 elif hasattr(o, "len"):717 unmodified lines863 864 def resolve_proxies(request, proxies, trust_env=True):865 """This method takes proxy information from a request and configuration866 input to resolve a mapping of target proxies. This will consider settings862- such a NO_PROXY to strip proxy configurations.867+ such as NO_PROXY to strip proxy configurations.868 869 :param request: Request or PreparedRequest870 :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs871 :param trust_env: Boolean declaring whether to trust environment configs183 unmodified lines1055 1056 if not validator.match(header_part):1057 header_kind = "name" if header_validator_index == 0 else "value"1058 raise InvalidHeader(1054- f"Invalid leading whitespace, reserved character(s), or return"1059+ f"Invalid leading whitespace, reserved character(s), or return "1060 f"character(s) in header {header_kind}: {header_part!r}"1061 )1062 1063 33 unmodified linesadded:tests/certs/expired/ca/ca-private.key+28 added
1+-----BEGIN PRIVATE KEY-----2+MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHlIhe7GLCeSk83+RZOKdtmyKns6KdZgGw/LcxPkYvQlu1g0zV8X0DqVr2LdMumWUTNCc9sPdSlAG+He4+mQp2TMoWUMumMuwDtit9RT0Sb6Eh9svWgjY9ferovPJRfCWUTsA2Ug8uoh0wyEXK5+na7X6fHt5E3B9vj0+b9a4vDibdBXV11FheLT02/uEmAEJDdP/zeBgvVbhcVyumO66+fAGMIWzR2ukhe8z/ma5H9zoi4gZA8nsK6reZUD8+6affnPe+jIt/AdzggtV9jkWm7+zSpr+RHeZ0y+q4eik2ZNUGg4XcF6JsJ9yu/AqLBXxd38uLdFfgyhP2y6K628yzgy8+e6lzFyWnAgMBAAECggEAFwzHhzcD3PQDWCus85PwZoxTeQ817BmUBGpBBOKM0gLG9+GCsT7XsmGP2NjICBy9OK+QTKawmb/wR5XK0OMUWDHXqtWn+NFIyojyo8+HEeCf8n10+4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JJ4Xdslf8n1nkq3qqqDQbd7kkQRgwGzVr0uVg7ZfS27+26qSPQ0/aF9nagb5eHX3AuU=28+-----END PRIVATE KEY-----added:tests/certs/expired/ca/ca.cnf+12 added
1+[req]2+default_bits = 20483+prompt = no4+default_md = sha2565+encrypt_key = no6+distinguished_name = dn7+8+[dn]9+C = US # country code10+O = Python Software Foundation # organization11+OU = python-requests # organization unit/department12+CN = Self-Signed Root CA # common name / your cert nameadded:tests/certs/expired/ca/ca.crt+20 added
1+-----BEGIN CERTIFICATE-----2+MIIDWzCCAkMCFA9wdtNh/V99DRwYp8vXjPxSjJnWMA0GCSqGSIb3DQEBCwUAMGox3+CzAJBgNVBAYTAlVTMSMwIQYDVQQKDBpQeXRob24gU29mdHdhcmUgRm91bmRhdGlv4+bjEYMBYGA1UECwwPcHl0aG9uLXJlcXVlc3RzMRwwGgYDVQQDDBNTZWxmLVNpZ25l5+ZCBSb290IENBMB4XDTI0MDMxMjIxMDQwM1oXDTQ0MDMwNzIxMDQwM1owajELMAkG6+A1UEBhMCVVMxIzAhBgNVBAoMGlB5dGhvbiBTb2Z0d2FyZSBGb3VuZGF0aW9uMRgw7+FgYDVQQLDA9weXRob24tcmVxdWVzdHMxHDAaBgNVBAMME1NlbGYtU2lnbmVkIFJv8+b3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDHlIhe7GLCeSk89+RZOKdtmyKns6KdZgGw/LcxPkYvQlu1g0zV8X0DqVr2LdMumWUTNCc9sPdSlAG+He10+mQp2TMoWUMumMuwDtit9RT0Sb6Eh9svWgjY9ferovPJRfCWUTsA2Ug8uoh0wyEXK11+na7X6fHt5E3B9vj0+b9a4vDibdBXV11FheLT02/uEmAEJDdP/zeBgvVbhcVyumO612+fAGMIWzR2ukhe8z/ma5H9zoi4gZA8nsK6reZUD8+6affnPe+jIt/AdzggtV9jkWm13+zSpr+RHeZ0y+q4eik2ZNUGg4XcF6JsJ9yu/AqLBXxd38uLdFfgyhP2y6K628yzgy14+e6lzFyWnAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAGymNVTsKSAq8Ju6zV+AWAyV15+GcUNBmLpgzDA0e7pkVYhHTdWKlGH4GnrRcp0nvnSbr6iq1Ob/8yEUUoRzK55Flws16+Kt1OLwnZyhfRoSUesoEqpP68vzWEgiYv0QuIWvzNt0YfAAvEgGoc3iri44MelKLn17+9ZMT8m91nVamA35R8ZjfeAkNp2xcz0a67V0ww6o4wSXrG7o5ZRXyjqZ/9K7SfwUJ18+rV9RciccsjH/MzKbfrx73QwsbPWiFmjzHopdasIO0lDlmgm/r9gKfkbzfKoGCgLZ19+6an6FlmLftLSXijf/QwtqeSP9fODeE3dzBmnTM3jdoVS53ZegUDWNl14o25v2Kg=20+-----END CERTIFICATE-----added:tests/certs/expired/ca/ca.srl+1 added
1+4F36C3A7E075BA6452D10EEB81E7F189FF489B74added:tests/certs/expired/ca/Makefile+13 added
1+.PHONY: all clean2+3+root_files = ca-private.key ca.crt4+5+ca-private.key:6+ openssl genrsa -out ca-private.key 20487+8+all: ca-private.key9+ openssl req -x509 -sha256 -days 7300 -key ca-private.key -out ca.crt -config ca.cnf10+ ln -s ca.crt cacert.pem11+12+clean:13+ rm -f cacert.pem ca.crt ca-private.key *.csradded:tests/certs/expired/server/cert.cnf+24 added
1+[req]2+req_extensions = v3_req3+distinguished_name = req_distinguished_name4+prompt=no5+6+[req_distinguished_name]7+C = US8+ST = DE9+O = Python Software Foundation10+OU = python-requests11+CN = localhost12+13+[v3_req]14+# Extensions to add to a certificate request15+basicConstraints = CA:FALSE16+keyUsage = digitalSignature, keyEncipherment17+extendedKeyUsage = serverAuth18+subjectAltName = @alt_names19+20+[alt_names]21+DNS.1 = *.localhost22+DNS.1 = localhost23+IP.1 = 127.0.0.124+IP.2 = ::1added:tests/certs/expired/server/Makefile+16 added
1+.PHONY: all clean2+3+server.key:4+ openssl genrsa -out $@ 20485+6+server.csr: server.key7+ openssl req -key $< -new -out $@ -config cert.cnf8+9+server.pem: server.csr10+ openssl x509 -req -CA ../ca/ca.crt -CAkey ../ca/ca-private.key -in server.csr -outform PEM -out server.pem -days 0 -CAcreateserial11+ openssl x509 -in ../ca/ca.crt -outform PEM >> $@12+13+all: server.pem14+15+clean:16+ rm -f server.*added:tests/certs/expired/server/server.csr+19 added
1+-----BEGIN CERTIFICATE REQUEST-----2+MIIDHjCCAgYCAQAwbTELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkRFMSMwIQYDVQQK3+DBpQeXRob24gU29mdHdhcmUgRm91bmRhdGlvbjEYMBYGA1UECwwPcHl0aG9uLXJl4+cXVlc3RzMRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IB5+DwAwggEKAoIBAQCKulIMpo633iCgbkKv1UoiLC4sQt5xWpgguujywu3hLYwmPFp96+kvPt//imqtl8FhuhKqJ8FCGrVl2YIGj1RJIB3GW7MSPNCuIBFL/gwNi35LxDPtoA7+IPyXytIR7VH9+ch9DFInJaoA/BekMuKvbXk54VW9whpHbwkXSG2lBS2vKL0XemYh8+9VjvtuRDji2iOZpznlVE2PEN80bojArp6oYKakv2kYzgzgxAJiI/NZGvC7mbSI4e9+ja7ad3R9G0kB1FzNj36jrNO5WtxHO/mrRiXSpDeyUbitYvt0HKoM0vhTnOR+BspP10+IltfwOQh8qq2Q2AaMHNcVjMH3gHCZADfhk/zAgMBAAGgbDBqBgkqhkiG9w0BCQ4x11+XTBbMAkGA1UdEwQCMAAwCwYDVR0PBAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMB12+MCwGA1UdEQQlMCOCCWxvY2FsaG9zdIcEfwAAAYcQAAAAAAAAAAAAAAAAAAAAATAN13+BgkqhkiG9w0BAQsFAAOCAQEAfAhEhrulsZae71YFqgvzwJHm/hzXh47hErtgDXVJ14+mFqAxgF6XrnzYujlt3XQXUx/8vdrU7jH+Pe8WO1rDvFwRPMDGoBF3RX29SzyX/2F15+e102egnoRR+Hlf0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V5eQKBgQC++1Wn3v/dxtczjA+I14+tN4a7zyjhazpB25lde55HVfCQPxmYxIYct+j6S0JkMaoLrjiEDb4pnu4Gt4MDqZa15+r0Xm8t3wD1YKUUbhpBEGvsMhAEZEIsBOcwkTiEwsoF0mKFa2mTyqAImgIQa8uFt816+Y/oTj55XFe1x6pZKEJRg+K+QSwKBgQC59ONVkMSBirLGS+G+b2kqiBdwZB/3s3wr17+feS1xTa+deL3AChnKT9+MsVqOkxdE2TRj/mAeF+5Woa5bPMvgr9Kl7u8bulTH80l18+YA/N6FneO11/ncnkgK9wN54kd5TiOtGsGB5S5t/nEAIMUIwWrM/cRau72xNEWOhT19+Tvw7TOSF+QKBgQCa/texeiYmE24sA4vH4yIuseKAw8hlBwbtiRyVZt8GZD9zyQuy20+k+g02tUWYk0XyXN65LX4bwURkZyMJIeWKZGNsaW1YnzturDQB5tZ4g/zBIoCWkHA21+aVQAaimIPk3a3foiD5NQVUdckfEp0GVPOsSGg5R6EO23+i8mxPXnDW1OqQKBgGvf22+lelTO8tyLFdAOcqBUt6rZ/1499p3snaAZ6bSqvk95dYnr0h48y5AQaln/FiaIYg423+HyLZsZ4S18jFXSWYkWOyNeQP6yafciBWY5StT0TN52VaoX3+8McGXKUHAcVjHbLZ24+ou2wpP6jmKyQJVQaF9LOT9uAMOMbOFrrnQLBjmfxAoGAQAnUhMFG5mwi9Otxt6Mz25+g+Gr+3JTlzwC3L7UwGdlFc3G2vSdGx/yOrfzpxPImfIBS95mibDfdvEBMer26pvw26+a/ycqybyX9d/5nPDIaJ1lc4M4cbHC/cB52JI6avr/1g8OMK7lR7b/FsPVHS1w8kl27+n6uwEjVt2+gP2o9DFTGs158=28+-----END PRIVATE KEY-----added:tests/certs/expired/server/server.pem+41 added
1+-----BEGIN CERTIFICATE-----2+MIIDXjCCAkYCFE82w6fgdbpkUtEO64Hn8Yn/SJt0MA0GCSqGSIb3DQEBCwUAMGox3+CzAJBgNVBAYTAlVTMSMwIQYDVQQKDBpQeXR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ww6o4wSXrG7o5ZRXyjqZ/9K7SfwUJ39+rV9RciccsjH/MzKbfrx73QwsbPWiFmjzHopdasIO0lDlmgm/r9gKfkbzfKoGCgLZ40+6an6FlmLftLSXijf/QwtqeSP9fODeE3dzBmnTM3jdoVS53ZegUDWNl14o25v2Kg=41+-----END CERTIFICATE-----added:tests/certs/expired/Makefile+13 added
1+.PHONY: all clean ca server2+3+ca:4+ make -C $@ all5+6+server:7+ make -C $@ all8+9+all: ca server10+11+clean:12+ make -C ca clean13+ make -C server cleanadded:tests/certs/expired/README.md+11 added
1+# Expired Certificates and Configuration for Testing2+3+This has a valid certificate authority in [ca](./ca) and an invalid server4+certificate in [server](./server).5+6+This can all be regenerated with:7+8+```9+make clean10+make all11+```added:tests/certs/mtls/client/ca+1 added
1+../../expired/ca/added:tests/certs/mtls/client/cert.cnf+26 added
1+[req]2+req_extensions = v3_req3+distinguished_name = req_distinguished_name4+prompt=no5+6+[req_distinguished_name]7+C = US8+ST = DE9+O = Python Software Foundation10+OU = python-requests11+CN = requests12+13+[v3_req]14+# Extensions to add to a certificate request15+basicConstraints = CA:FALSE16+keyUsage = digitalSignature, keyEncipherment17+extendedKeyUsage = clientAuth18+subjectAltName = @alt_names19+20+[alt_names]21+DNS.1 = *.localhost22+IP.1 = 127.0.0.123+IP.2 = ::124+URI.1 = spiffe://trust.python.org/v0/maintainer/sigmavirus24/project/requests/org/psf25+URI.2 = spiffe://trust.python.org/v1/maintainer:sigmavirus24/project:requests/org:psf26+URI.3 = spiffe://trust.python.org/v1/maintainer=sigmavirus24/project=requests/org=psfadded:tests/certs/mtls/client/client.csr+24 added
1+-----BEGIN CERTIFICATE REQUEST-----2+MIIEGjCCAwICAQAwbDELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkRFMSMwIQYDVQQK3+DBpQeXRob24gU29mdHdhcmUgRm91bmRhdGlvbjEYMBYGA1UECwwPcHl0aG9uLXJl4+cXVlc3RzMREwDwYDVQQDDAhyZXF1ZXN0czCCASIw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v29uQTWkfg+GbZ9q1hm2m2GHhYLGLAUdJdtv7JI+yq5uxdsWaCANpH6kc8SnK22+2rik6D3iItDhHCmToHBpdEnP8J+KDzf5pJrv/g3WH8XVrl4ZzBsOhmciWF4C3Hbf23+9eu8eAsp1AsIrZOEGTfClBd7vFCES5DmI0/iRs4czQooqZPnHjOw3Azp/LujrA==24+-----END CERTIFICATE REQUEST-----added:tests/certs/mtls/client/client.key+28 added
1+-----BEGIN PRIVATE KEY-----2+MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDJ94kMnE41M6Si3+QoUTZHJt91AdvNnFMKcXqijeGoR8QaUtPR0YZHEGDu8hKxFEMM0JwUBHCKc83iDG4+SKh7gpIJ8ko3hCXfeQCMzcxsqCy5EudU3CcIEb/NwL0/JYwPPLPYd/Khk8uP0wsS5+YH++qXxyLgtaqClUIdwLh4/ZzsSGS1LK3Q21hVqC6iklck28vkV70gKaQEfnLgQm6+lkrUOsRTkZ+PER33Ord9IIA+KwwI8lOlc+qEfKLd15hnStIeNlHaonVFpESWoxG67+ZAp0El0ttSL31ysRebBagFya4/YlW1H6TT6WmlvCKxwcp4MlfGpmsxmawErLVFUR8+bVq563FhAgMBAAECggEABhWX97JJxN6JFNOjhgGzqiPA3R8lrFlv3zhNbODS9u9U9+q404xYBZIKaYhkucLzgNJUBrevhZbsL+V8WJQIH0JlU57nw5ATIjAHA+uqiXraen10+zRhTcLHK28b1AeRUA4LU+YN7jWnnawN075kf9WgjtfOJ0gcDimOkE7uCFjyyvPJA11+LG9bG+8enGjvUleKXNgmwP4Sq/GlEdGz9Qy+8ga3mtfAULUWe8haFNZXK8CN3xPp12+wmVqy7QzgH2TGN1p6Dyxib9ksSN/lOg0dShL8zgu+QXDNx2VwmVrI8Vr02vmB//013+bYxCo5pfICPIFLjLl5yo30dvrUfYqF29PperStHGlQKBgQD/TdemlLjJNP0fvSs714+KEVJj/22YuHK+wurNr2ZFbSdcF3v9sfiwysllmEyGr5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asIO0lDlmgm/r9gKfkbzfKoGCgLZ40+6an6FlmLftLSXijf/QwtqeSP9fODeE3dzBmnTM3jdoVS53ZegUDWNl14o25v2Kg=41+-----END CERTIFICATE-----added:tests/certs/mtls/client/Makefile+16 added
1+.PHONY: all clean2+3+client.key:4+ openssl genrsa -out $@ 20485+6+client.csr: client.key7+ openssl req -key $< -new -out $@ -config cert.cnf8+9+client.pem: client.csr10+ openssl x509 -req -CA ./ca/ca.crt -CAkey ./ca/ca-private.key -in client.csr -outform PEM -out client.pem -days 730 -CAcreateserial11+ openssl x509 -in ./ca/ca.crt -outform PEM >> $@12+13+all: client.pem14+15+clean:16+ rm -f client.*added:tests/certs/mtls/Makefile+7 added
1+.PHONY: all clean2+3+all:4+ make -C client all5+6+clean:7+ make -C client cleanadded:tests/certs/mtls/README.md+4 added
1+# Certificate Examples for mTLS2+3+This has some generated certificates for mTLS utilization. The idea is to be4+able to have testing around how Requests handles client certificates.added:tests/certs/valid/server/cert.cnf+31 added
1+[req]2+req_extensions = v3_req3+distinguished_name = req_distinguished_name4+prompt=no5+6+[req_distinguished_name]7+C = US8+ST = DE9+O = Python Software Foundation10+OU = python-requests11+CN = localhost12+13+[v3_req]14+# Extensions to add to a certificate request15+basicConstraints = critical, CA:FALSE16+keyUsage = critical, digitalSignature, keyEncipherment17+extendedKeyUsage = critical, serverAuth18+subjectAltName = critical, @alt_names19+20+[v3_ca]21+# Extensions to add to a certificate request22+basicConstraints = critical, CA:FALSE23+keyUsage = critical, digitalSignature, keyEncipherment24+extendedKeyUsage = critical, serverAuth25+subjectAltName = critical, @alt_names26+27+[alt_names]28+DNS.1 = *.localhost29+DNS.1 = localhost30+IP.1 = 127.0.0.131+IP.2 = ::1added:tests/certs/valid/server/Makefile+16 added
1+.PHONY: all clean2+3+server.key:4+ openssl genrsa -out $@ 20485+6+server.csr: server.key7+ openssl req -key $< -config cert.cnf -new -out $@8+9+server.pem: server.csr10+ openssl x509 -req -CA ../ca/ca.crt -CAkey ../ca/ca-private.key -in server.csr -outform PEM -out server.pem -extfile cert.cnf -extensions v3_ca -days 7200 -CAcreateserial11+ openssl x509 -in ../ca/ca.crt -outform PEM >> $@12+13+all: server.pem14+15+clean:16+ rm -f server.*added:tests/certs/valid/server/server.csr+19 added
1+-----BEGIN CERTIFICATE REQUEST-----2+MIIDKjCCAhICAQAwbTELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkRFMSMwIQYDVQQK3+DBpQeXRob24gU29mdHdhcmUgRm91bmRhdGlvbjEYMBYGA1UECwwPcHl0aG9uLXJl4+cXVlc3RzMRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IB5+DwAwggEKAoIBAQChEKOx377ymuDg23By5Re1DHi2RiBKSHr85/ZTZuwP/69lHN7q6+TQEO//EMEFZ9+ZwezeJJsejjP2HO5lQZbcsWok3hbM0wVT+vApkogPvJ8WNFFWFe7+ZBnGLi/1WM9cSZpUsDJ0XCsG0RTtO27wfgZQlKQMZxTkfi971oPYxNVSjTm2JcLT8+kvwYIwxjJXPDTOgRo9TEAY3cWkCrBJN4w74GWBTM5KDDA230T7WwLuv81XD2LvYj9+YYdMBGcxPr5tYTIlp3LncbcrDRNk3pbYQk0bRJgkw2vUkteiRGjkt+dgVnLc6+MI10+W+VLXEpj+zsOZ5/R4d1pofqj9sDyDPhtNr1JAgMBAAGgeDB2BgkqhkiG9w0BCQ4x11+aTBnMAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgWgMBYGA1UdJQEB/wQMMAoG12+CCsGAQUFBwMBMC8GA1UdEQEB/wQlMCOCCWxvY2FsaG9zdIcEfwAAAYcQAAAAAAAA13+AAAAAAAAAAAAATANBgkqhkiG9w0BAQsFAAOCAQEAFTlFTn5Mn8JXtqB5bGjuiChe14+ClA6Y32Co4l7N0CtAlf+bExwLdpLOleTX3WnryIPALl9uBUI/67dy/STn/J1Yn8615+jWPEFwpmYNSKgQljYWcwtBdYLWfIsJO11kKdaAkOUHBEN5DKrXJ46Vs4918bD1/Q16+6ztqdrThiKc646u9xB58Hg7F0IyMWbHfs0x16ZpcN9otrIkbqOE2wzTmc65O1t1i17+HDljcSk7OnNy3a9wtLEnyPiyMqHf2k/bTlmiDRVe3cSy9xieoqmzHTnOCSASe1y918+7lcEBQild18Jo4nACV4vCYOUwrMi/58LWW+lD6OmMnPiWUqOvMbgMffMNDpWPA==19+-----END CERTIFICATE REQUEST-----added:tests/certs/valid/server/server.key+28 added
1+-----BEGIN PRIVATE KEY-----2+MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQChEKOx377ymuDg3+23By5Re1DHi2RiBKSHr85/ZTZuwP/69lHN7qTQEO//EMEFZ9+ZwezeJJsejjP2HO4+5lQZbcsWok3hbM0wVT+vApkogPvJ8WNFFWFeZBnGLi/1WM9cSZpUsDJ0XCsG0RTt5+O27wfgZQlKQMZxTkfi971oPYxNVSjTm2JcLTkvwYIwxjJXPDTOgRo9TEAY3cWkCr6+BJN4w74GWBTM5KDDA230T7WwLuv81XD2LvYjYYdMBGcxPr5tYTIlp3LncbcrDRNk7+3pbYQk0bRJgkw2vUkteiRGjkt+dgVnLc6+MIW+VLXEpj+zsOZ5/R4d1pofqj9sDy8+DPhtNr1JAgMBAAECggEAIuLzBfXgCvXzlBjL2kMXd7p4EgkN+PEKnKmUr/t40b1Q9+zR6sBQWBX3GeET4fseElSQHQzCQaPNCve4xltm1S4jftFREHP7sTVHHEYWLQxuy/10+Uwkewj5927CI6ERgg82YfVP91bjaA/u5I+pt7O7rKLyNbPdN7fEMEW+FNuhpiVvg11+JMrcK1BCFL6pmIT21LyTwkacMKZSPko58pWE24MA9aSCHk6cXdwQWQK0AfQT3XGT12+C4I0hRed7LgqMH+gMuhpakiO13t8yTwxt2iQC9+aa4oSHD3BOi/CwIWfe1mHwmlr13+cj4Kof1JSnK4SVTD16T++PlnWZkF6oaLUNg+/c2C9QKBgQDOFSYIY7+HzinT2hbI14+yTIJCHpp+Iee+WVvvxjdZIPMDINrlIiHcMfXb0itUdcUO6tz0KYDMDLRC9CSP0ar15+6mBWUTHfAKF2S4JpI9JYI4PNtIpOP1NiYuyJlnh5+ytU1yIeIvl39hmLcRwI9mgz16+njy/D7yEoDCrG1dhcltubKpNXQKBgQDIFAVg0A7MNcxBZDLlk1NAME2JKOSszX8E17+VNucvZD+9l+L9V9BmwwPQdzYifv/dNp3nYn+lxRPPgze3ZWu4+PeDuGudxu0I6ll18+beFdbIcp1wbeQguzHYLjBYJqsMb4Pao5HPInjPu/HWfZlg9oZpJbKVucQwbonJLX19+lgca9KaE3QKBgA+OUx+g/+0tZ8ThGoUvgsJhzHPBWeNrKfgEcckMdFJrw2PUg3XN20+0pf1g4PpwJV7Z5bHcjCda8iR3r2bXydM+tapLF2L+6QlUQPEu3UBwUo+zY3Yg9/S21+Xc6I+DEk/4FY9+9UboZaolT/RcF7cCQtVqKJeo58VRAlcTQe4L32H+jVAoGALXX322+Ht9HbXkP1w/YTLej4+LVy0OCag0rPiW13LBqALSkUx3GrhZ3sAPMFVuM6ad4eFNQ23+ZouXbsXvkLgSabGYNf11o/mmTtEHjWdhHKQrNgOIqPmixOkAs2quDmXqX79LLTz524+fKkZDny0+wiQqa0cth/4k9HbAQGKj/ej16kdKPUCgYAz08Y39NnJYxRNz3tu/7C625+jKyXKxhuZCZCt3cSWto5Tg0mVVB+2Jk2GhG1hCfZoRCP25R3FFBR1HOJgOc59T7C26+LL67FdO0+7mj/WNzHj3+9gyOYQyQgPVDaTmsJLbuzT2S+GpR94ZNliwL2NEa5baG27+B/Nb2ruRNj0GgZVw48N4XQ==28+-----END PRIVATE KEY-----added:tests/certs/valid/server/server.pem+47 added
1+-----BEGIN CERTIFICATE-----2+MIIEhTCCA22gAwIBAgIUTzbDp+B1umRS0Q7rgefxif9Im3wwDQYJKoZIhvcNAQEL3+BQAwajELMAkGA1UEBhMCVVMxIzAhBgNVBAoMGlB5dGhvbiBTb2Z0d2FyZSBGb3V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4vDibdBXV11FheLT02/uEmAEJDdP/zeBgvVbhcVyumO639+fAGMIWzR2ukhe8z/ma5H9zoi4gZA8nsK6reZUD8+6affnPe+jIt/AdzggtV9jkWm40+zSpr+RHeZ0y+q4eik2ZNUGg4XcF6JsJ9yu/AqLBXxd38uLdFfgyhP2y6K628yzgy41+e6lzFyWnAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAGymNVTsKSAq8Ju6zV+AWAyV42+GcUNBmLpgzDA0e7pkVYhHTdWKlGH4GnrRcp0nvnSbr6iq1Ob/8yEUUoRzK55Flws43+Kt1OLwnZyhfRoSUesoEqpP68vzWEgiYv0QuIWvzNt0YfAAvEgGoc3iri44MelKLn44+9ZMT8m91nVamA35R8ZjfeAkNp2xcz0a67V0ww6o4wSXrG7o5ZRXyjqZ/9K7SfwUJ45+rV9RciccsjH/MzKbfrx73QwsbPWiFmjzHopdasIO0lDlmgm/r9gKfkbzfKoGCgLZ46+6an6FlmLftLSXijf/QwtqeSP9fODeE3dzBmnTM3jdoVS53ZegUDWNl14o25v2Kg=47+-----END CERTIFICATE-----added:tests/certs/valid/ca+1 added
1+../expired/caadded:tests/certs/README.md+10 added
1+# Testing Certificates2+3+This is a collection of certificates useful for testing aspects of Requests'4+behaviour.5+6+The certificates include:7+8+* [expired](./expired) server certificate with a valid certificate authority9+* [mtls](./mtls) provides a valid client certificate with a 2 year validity10+* [valid](./valid) has a valid server certificatemodified:tests/testserver/server.py+42 added
1 import select2 import socket3+import ssl4 import threading5 6 7 def consume_socket_content(sock, timeout=0.5):124 unmodified lines132 # ensure server thread doesn't get stuck waiting for connections133 self._close_server_sock_ignore_errors()134 self.join()135 return False # allow exceptions to propagate136+137+138+class TLSServer(Server):139+ def __init__(140+ self,141+ *,142+ handler=None,143+ host="localhost",144+ port=0,145+ requests_to_handle=1,146+ wait_to_close_event=None,147+ cert_chain=None,148+ keyfile=None,149+ mutual_tls=False,150+ cacert=None,151+ ):152+ super().__init__(153+ handler=handler,154+ host=host,155+ port=port,156+ requests_to_handle=requests_to_handle,157+ wait_to_close_event=wait_to_close_event,158+ )159+ self.cert_chain = cert_chain160+ self.keyfile = keyfile161+ self.ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)162+ self.ssl_context.load_cert_chain(self.cert_chain, keyfile=self.keyfile)163+ self.mutual_tls = mutual_tls164+ self.cacert = cacert165+ if mutual_tls:166+ # For simplicity, we're going to assume that the client cert is167+ # issued by the same CA as our Server certificate168+ self.ssl_context.verify_mode = ssl.CERT_OPTIONAL169+ self.ssl_context.load_verify_locations(self.cacert)170+171+ def _create_socket_and_bind(self):172+ sock = socket.socket()173+ sock = self.ssl_context.wrap_socket(sock, server_side=True)174+ sock.bind((self.host, self.port))175+ sock.listen()176+ return sockadded:tests/test_adapters.py+8 added
1+import requests.adapters2+3+4+def test_request_url_trims_leading_path_separators():5+ """See also https://github.com/psf/requests/issues/6643."""6+ a = requests.adapters.HTTPAdapter()7+ p = requests.Request(method="GET", url="http://127.0.0.1:10000//v:h").prepare()8+ assert "/v:h" == a.request_url(p, {})modified:tests/test_requests.py+182 added-3 removed
5 unmodified lines6 import json7 import os8 import pickle9 import re10+import threading11 import warnings12 from unittest import mock13 14 import pytest36 unmodified lines51 from requests.structures import CaseInsensitiveDict52 53 from . import SNIMissingWarning54 from .compat import StringIO55+from .testserver.server import TLSServer, consume_socket_content56 from .utils import override_environ57 58 # Requests to this URL should always fail with a connection timeout (nothing59 # listening on that port)942 unmodified lines1002 "InsecurePlatformWarning",1003 "SubjectAltNameWarning",1004 )1005 1004- with pytest.warns(None) as warning_records:1006+ with pytest.warns() as warning_records:1007 warnings.simplefilter("always")1008 requests.get(f"https://localhost:{port}/", verify=ca_bundle)1009 1010 warning_records = [692 unmodified lines1703 "qux": "1",1704 }1705 r = requests.get(httpbin("get"), headers=valid_headers)1706 for key in valid_headers.keys():1705- valid_headers[key] == r.request.headers[key]1707+ assert valid_headers[key] == r.request.headers[key]1708 1709 @pytest.mark.parametrize(1710 "invalid_header, key",1711 (97 unmodified lines1809 p = req.prepare()1810 1811 assert p.headers["Content-Length"] == length1812 1813+ def test_content_length_for_bytes_data(self, httpbin):1814+ data = "This is a string containing multi-byte UTF-8 ☃️"1815+ encoded_data = data.encode("utf-8")1816+ length = str(len(encoded_data))1817+ req = requests.Request("POST", httpbin("post"), data=encoded_data)1818+ p = req.prepare()1819+1820+ assert p.headers["Content-Length"] == length1821+1822+ def test_content_length_for_string_data_counts_bytes(self, httpbin):1823+ data = "This is a string containing multi-byte UTF-8 ☃️"1824+ length = str(len(data.encode("utf-8")))1825+ req = requests.Request("POST", httpbin("post"), data=data)1826+ p = req.prepare()1827+1828+ assert p.headers["Content-Length"] == length1829+1830 def test_nonhttp_schemes_dont_check_URLs(self):1831 test_urls = (1832 "data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==",1833 "file:///etc/passwd",886 unmodified lines2720 r = requests.Request("GET", url=url)2721 with pytest.raises(requests.exceptions.InvalidURL):2722 r.prepare()2723 2705- @pytest.mark.parametrize("url, exception", (("http://localhost:-1", InvalidURL),))2724+ @pytest.mark.parametrize("url, exception", (("http://:1", InvalidURL),))2725 def test_redirecting_to_bad_url(self, httpbin, url, exception):2726 with pytest.raises(exception):2727 requests.get(httpbin("redirect-to"), params={"url": url})2728 84 unmodified lines2813 r = requests.get(httpbin("bytes/20"))2814 with pytest.raises(requests.exceptions.JSONDecodeError) as excinfo:2815 r.json()2816 assert excinfo.value.doc == r.text2817+2818+ def test_status_code_425(self):2819+ r1 = requests.codes.get("TOO_EARLY")2820+ r2 = requests.codes.get("too_early")2821+ r3 = requests.codes.get("UNORDERED")2822+ r4 = requests.codes.get("unordered")2823+ r5 = requests.codes.get("UNORDERED_COLLECTION")2824+ r6 = requests.codes.get("unordered_collection")2825+2826+ assert r1 == 4252827+ assert r2 == 4252828+ assert r3 == 4252829+ assert r4 == 4252830+ assert r5 == 4252831+ assert r6 == 4252832+2833+ def test_different_connection_pool_for_tls_settings_verify_True(self):2834+ def response_handler(sock):2835+ consume_socket_content(sock, timeout=0.5)2836+ sock.send(2837+ b"HTTP/1.1 200 OK\r\n"2838+ b"Content-Length: 18\r\n\r\n"2839+ b'\xff\xfe{\x00"\x00K0"\x00=\x00"\x00\xab0"\x00\r\n'2840+ )2841+2842+ s = requests.Session()2843+ close_server = threading.Event()2844+ server = TLSServer(2845+ handler=response_handler,2846+ wait_to_close_event=close_server,2847+ requests_to_handle=3,2848+ cert_chain="tests/certs/expired/server/server.pem",2849+ keyfile="tests/certs/expired/server/server.key",2850+ )2851+2852+ with server as (host, port):2853+ url = f"https://{host}:{port}"2854+ r1 = s.get(url, verify=False)2855+ assert r1.status_code == 2002856+2857+ # Cannot verify self-signed certificate2858+ with pytest.raises(requests.exceptions.SSLError):2859+ s.get(url)2860+2861+ close_server.set()2862+ assert 2 == len(s.adapters["https://"].poolmanager.pools)2863+2864+ def test_different_connection_pool_for_tls_settings_verify_bundle_expired_cert(2865+ self,2866+ ):2867+ def response_handler(sock):2868+ consume_socket_content(sock, timeout=0.5)2869+ sock.send(2870+ b"HTTP/1.1 200 OK\r\n"2871+ b"Content-Length: 18\r\n\r\n"2872+ b'\xff\xfe{\x00"\x00K0"\x00=\x00"\x00\xab0"\x00\r\n'2873+ )2874+2875+ s = requests.Session()2876+ close_server = threading.Event()2877+ server = TLSServer(2878+ handler=response_handler,2879+ wait_to_close_event=close_server,2880+ requests_to_handle=3,2881+ cert_chain="tests/certs/expired/server/server.pem",2882+ keyfile="tests/certs/expired/server/server.key",2883+ )2884+2885+ with server as (host, port):2886+ url = f"https://{host}:{port}"2887+ r1 = s.get(url, verify=False)2888+ assert r1.status_code == 2002889+2890+ # Has right trust bundle, but certificate expired2891+ with pytest.raises(requests.exceptions.SSLError):2892+ s.get(url, verify="tests/certs/expired/ca/ca.crt")2893+2894+ close_server.set()2895+ assert 2 == len(s.adapters["https://"].poolmanager.pools)2896+2897+ def test_different_connection_pool_for_tls_settings_verify_bundle_unexpired_cert(2898+ self,2899+ ):2900+ def response_handler(sock):2901+ consume_socket_content(sock, timeout=0.5)2902+ sock.send(2903+ b"HTTP/1.1 200 OK\r\n"2904+ b"Content-Length: 18\r\n\r\n"2905+ b'\xff\xfe{\x00"\x00K0"\x00=\x00"\x00\xab0"\x00\r\n'2906+ )2907+2908+ s = requests.Session()2909+ close_server = threading.Event()2910+ server = TLSServer(2911+ handler=response_handler,2912+ wait_to_close_event=close_server,2913+ requests_to_handle=3,2914+ cert_chain="tests/certs/valid/server/server.pem",2915+ keyfile="tests/certs/valid/server/server.key",2916+ )2917+2918+ with server as (host, port):2919+ url = f"https://{host}:{port}"2920+ r1 = s.get(url, verify=False)2921+ assert r1.status_code == 2002922+2923+ r2 = s.get(url, verify="tests/certs/valid/ca/ca.crt")2924+ assert r2.status_code == 2002925+2926+ close_server.set()2927+ assert 2 == len(s.adapters["https://"].poolmanager.pools)2928+2929+ def test_different_connection_pool_for_mtls_settings(self):2930+ client_cert = None2931+2932+ def response_handler(sock):2933+ nonlocal client_cert2934+ client_cert = sock.getpeercert()2935+ consume_socket_content(sock, timeout=0.5)2936+ sock.send(2937+ b"HTTP/1.1 200 OK\r\n"2938+ b"Content-Length: 18\r\n\r\n"2939+ b'\xff\xfe{\x00"\x00K0"\x00=\x00"\x00\xab0"\x00\r\n'2940+ )2941+2942+ s = requests.Session()2943+ close_server = threading.Event()2944+ server = TLSServer(2945+ handler=response_handler,2946+ wait_to_close_event=close_server,2947+ requests_to_handle=2,2948+ cert_chain="tests/certs/expired/server/server.pem",2949+ keyfile="tests/certs/expired/server/server.key",2950+ mutual_tls=True,2951+ cacert="tests/certs/expired/ca/ca.crt",2952+ )2953+2954+ cert = (2955+ "tests/certs/mtls/client/client.pem",2956+ "tests/certs/mtls/client/client.key",2957+ )2958+ with server as (host, port):2959+ url = f"https://{host}:{port}"2960+ r1 = s.get(url, verify=False, cert=cert)2961+ assert r1.status_code == 2002962+ with pytest.raises(requests.exceptions.SSLError):2963+ s.get(url, cert=cert)2964+ close_server.set()2965+2966+ assert client_cert is not None2967+2968+2969+def test_json_decode_errors_are_serializable_deserializable():2970+ json_decode_error = requests.exceptions.JSONDecodeError(2971+ "Extra data",2972+ '{"responseCode":["706"],"data":null}{"responseCode":["706"],"data":null}',2973+ 36,2974+ )2975+ deserialized_error = pickle.loads(pickle.dumps(json_decode_error))2976+ assert repr(json_decode_error) == repr(deserialized_error)modified:tests/test_utils.py+32 added
922 unmodified lines923 with set_environ("test1", None):924 raise Exception("Expected exception")925 926 assert "Expected exception" in str(exception.value)927+928+929+@pytest.mark.skipif(os.name != "nt", reason="Test only on Windows")930+def test_should_bypass_proxies_win_registry_ProxyOverride_value(monkeypatch):931+ """Tests for function should_bypass_proxies to check if proxy932+ can be bypassed or not with Windows ProxyOverride registry value ending with a semicolon.933+ """934+ import winreg935+936+ class RegHandle:937+ def Close(self):938+ pass939+940+ ie_settings = RegHandle()941+942+ def OpenKey(key, subkey):943+ return ie_settings944+945+ def QueryValueEx(key, value_name):946+ if key is ie_settings:947+ if value_name == "ProxyEnable":948+ return [1]949+ elif value_name == "ProxyOverride":950+ return [951+ "192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1;<-loopback>;"952+ ]953+954+ monkeypatch.setenv("NO_PROXY", "")955+ monkeypatch.setenv("no_proxy", "")956+ monkeypatch.setattr(winreg, "OpenKey", OpenKey)957+ monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx)958+ assert should_bypass_proxies("http://example.com/", None) is Falseadded:.readthedocs.yaml+29 added
1+# Read the Docs configuration file for Sphinx projects2+# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details3+4+# Required5+version: 26+7+# Set the OS, Python version and other tools you might need8+build:9+ os: ubuntu-22.0410+ tools:11+ python: "3.12"12+13+# Build documentation in the "docs/" directory with Sphinx14+sphinx:15+ configuration: docs/conf.py16+ builder: "dirhtml"17+18+# Optionally build your docs in additional formats such as PDF and ePub19+formats:20+ - pdf21+ - epub22+23+# Optional but recommended, declare the Python requirements required24+# to build your documentation25+# See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html26+python:27+ install:28+ - path: .29+ - requirements: docs/requirements.txtmodified:AUTHORS.rst+2 added-1 removed
6 unmodified lines7 - Seth M. Larson `@sethmlarson <https://github.com/sethmlarson>`_.8 9 Previous Keepers of Crystals10 ````````````````````````````11-- Kenneth Reitz <me@kennethreitz.org> `@ken-reitz <https://github.com/ken-reitz>`_, reluctant Keeper of the Master Crystal.11+- Kenneth Reitz <me@kennethreitz.org> `@kennethreitz <https://github.com/kennethreitz>`_, reluctant Keeper of the Master Crystal.12 - Cory Benfield <cory@lukasa.co.uk> `@lukasa <https://github.com/lukasa>`_13 - Ian Cordasco <graffatcolmingov@gmail.com> `@sigmavirus24 <https://github.com/sigmavirus24>`_.14 15 175 unmodified lines191 - "Dull Bananas" <dull.bananas0@gmail.com> (`@dullbananas <https://github.com/dullbananas>`_)192 - Alessio Izzo (`@aless10 <https://github.com/aless10>`_)193 - Sylvain Marié (`@smarie <https://github.com/smarie>`_)194 - Hod Bin Noon (`@hodbn <https://github.com/hodbn>`_)195+- Mike Fiedler (`@miketheman <https://github.com/miketheman>`_)modified:HISTORY.md+77 added-1 removed
4 unmodified lines5 ---6 7 - \[Short description of non-trivial change.\]8 9+2.32.3 (2024-05-29)10+-------------------11+12+**Bugfixes**13+- Fixed bug breaking the ability to specify custom SSLContexts in sub-classes of14+ HTTPAdapter. (#6716)15+- Fixed issue where Requests started failing to run on Python versions compiled16+ without the `ssl` module. (#6724)17+18+2.32.2 (2024-05-21)19+-------------------20+21+**Deprecations**22+- To provide a more stable migration for custom HTTPAdapters impacted23+ by the CVE changes in 2.32.0, we've renamed `_get_connection` to24+ a new public API, `get_connection_with_tls_context`. Existing custom25+ HTTPAdapters will need to migrate their code to use this new API.26+ `get_connection` is considered deprecated in all versions of Requests>=2.32.0.27+28+ A minimal (2-line) example has been provided in the linked PR to ease29+ migration, but we strongly urge users to evaluate if their custom adapter30+ is subject to the same issue described in CVE-2024-35195. (#6710)31+32+2.32.1 (2024-05-20)33+-------------------34+35+**Bugfixes**36+- Add missing test certs to the sdist distributed on PyPI.37+38+39+2.32.0 (2024-05-20)40+-------------------41+42+**Security**43+- Fixed an issue where setting `verify=False` on the first request from a44+ Session will cause subsequent requests to the _same origin_ to also ignore45+ cert verification, regardless of the value of `verify`.46+ (https://github.com/psf/requests/security/advisories/GHSA-9wx4-h78v-vm56)47+48+**Improvements**49+- `verify=True` now reuses a global SSLContext which should improve50+ request time variance between first and subsequent requests. It should51+ also minimize certificate load time on Windows systems when using a Python52+ version built with OpenSSL 3.x. (#6667)53+- Requests now supports optional use of character detection54+ (`chardet` or `charset_normalizer`) when repackaged or vendored.55+ This enables `pip` and other projects to minimize their vendoring56+ surface area. The `Response.text()` and `apparent_encoding` APIs57+ will default to `utf-8` if neither library is present. (#6702)58+59+**Bugfixes**60+- Fixed bug in length detection where emoji length was incorrectly61+ calculated in the request content-length. (#6589)62+- Fixed deserialization bug in JSONDecodeError. (#6629)63+- Fixed bug where an extra leading `/` (path separator) could lead64+ urllib3 to unnecessarily reparse the request URI. (#6644)65+66+**Deprecations**67+68+- Requests has officially added support for CPython 3.12 (#6503)69+- Requests has officially added support for PyPy 3.9 and 3.10 (#6641)70+- Requests has officially dropped support for CPython 3.7 (#6642)71+- Requests has officially dropped support for PyPy 3.7 and 3.8 (#6641)72+73+**Documentation**74+- Various typo fixes and doc improvements.75+76+**Packaging**77+- Requests has started adopting some modern packaging practices.78+ The source files for the projects (formerly `requests`) is now located79+ in `src/requests` in the Requests sdist. (#6506)80+- Starting in Requests 2.33.0, Requests will migrate to a PEP 517 build system81+ using `hatchling`. This should not impact the average user, but extremely old82+ versions of packaging utilities may have issues with the new packaging format.83+84+85 2.31.0 (2023-05-22)86 -------------------87 88 **Security**89 - Versions of Requests between v2.3.0 and v2.30.0 are vulnerable to potential90 forwarding of `Proxy-Authorization` headers to destination servers when91 following HTTPS redirects.92 17- When proxies are defined with user info (https://user:pass@proxy:8080), Requests93+ When proxies are defined with user info (`https://user:pass@proxy:8080`), Requests94 will construct a `Proxy-Authorization` header that is attached to the request to95 authenticate with the proxy.96 97 In cases where Requests receives a redirect response, it previously reattached1885 unmodified linesmodified:MANIFEST.in+1 added
1 include README.md LICENSE NOTICE HISTORY.md requirements-dev.txt2 recursive-include tests *.py3+recursive-include tests/certs *modified:README.md+1 added-1 removed
31 unmodified lines32 ```console33 $ python -m pip install requests34 ```35 36-Requests officially supports Python 3.7+.36+Requests officially supports Python 3.8+.37 38 ## Supported Features & Best–Practices39 40 Requests is ready for the demands of building robust and reliable HTTP–speaking applications, for the needs of today.38 unmodified linesmodified:requirements-dev.txt+2 added-3 removed
1 -e .[socks]2-pytest>=2.8.0,<=6.2.52+pytest>=2.8.0,<93 pytest-cov4 pytest-httpbin==2.0.05-httpbin==0.10.05+httpbin~=0.10.06 trustme7 wheel8-cryptography<40.0.0; python_version <= '3.7' and platform_python_implementation == 'PyPy'modified:setup.cfg+1 added-1 removed
5 unmodified lines6 requires-dist =7 certifi>=2017.4.178 charset_normalizer>=2,<49 idna>=2.5,<410- urllib3>=1.21.1,<1.2710+ urllib3>=1.21.1,<311 12 [flake8]13 ignore = E203, E501, W50314 per-file-ignores =3 unmodified linesmodified:setup.py+3 added-4 removed
5 unmodified lines6 from setuptools import setup7 from setuptools.command.test import test as TestCommand8 9 CURRENT_PYTHON = sys.version_info[:2]10-REQUIRED_PYTHON = (3, 7)10+REQUIRED_PYTHON = (3, 8)11 12 if CURRENT_PYTHON < REQUIRED_PYTHON:13 sys.stderr.write(14 """4 unmodified lines19 you're trying to install it on Python {}.{}. To resolve this,20 consider upgrading to a supported Python version.21 22 If you can't upgrade your Python version, you'll need to23-pin to an older version of Requests (<2.28).23+pin to an older version of Requests (<2.32.0).24 """.format(25 *(REQUIRED_PYTHON + CURRENT_PYTHON)26 )27 )65 unmodified lines93 packages=["requests"],94 package_data={"": ["LICENSE", "NOTICE"]},95 package_dir={"": "src"},96 include_package_data=True,97- python_requires=">=3.7",97+ python_requires=">=3.8",98 install_requires=requires,99 license=about["__license__"],100 zip_safe=False,101 classifiers=[4 unmodified lines106 "Natural Language :: English",107 "Operating System :: OS Independent",108 "Programming Language :: Python",109 "Programming Language :: Python :: 3",110- "Programming Language :: Python :: 3.7",110 "Programming Language :: Python :: 3.8",111 "Programming Language :: Python :: 3.9",112 "Programming Language :: Python :: 3.10",113 "Programming Language :: Python :: 3.11",19 unmodified linesmodified:tox.ini+2 added-2 removed
1 [tox]2-envlist = py{37,38,39,310,311,312}-{default, use_chardet_on_py3}2+envlist = py{38,39,310,311,312}-{default, use_chardet_on_py3}3 4 [testenv]5 deps = -rrequirements-dev.txt6 extras =7 security8 socks9 commands =10- pytest tests10+ pytest {posargs:tests}11 12 [testenv:default]13 14 [testenv:use_chardet_on_py3]4 unmodified lines