Repository navigation
requests: Fix redirect handling. - #1185
Open
joshdoesthis wants to merge 3 commits into
Open
joshdoesthis wants to merge 3 commits into
joshdoesthis wants to merge 3 commits into
Conversation
requests builds its own tls.SSLContext with verify_mode CERT_NONE and offers no way to change it, so HTTPS requests accept any certificate. Add an optional ssl argument to request() and the method helpers that takes an SSLContext, as umqtt.simple does. When given, the socket is wrapped with it and the host passed as server_hostname, and redirects to https keep using it. An http URL, or a redirect to one, raises ValueError instead of sending the request unencrypted. When ssl is None, requests are sent as before. Close the socket on any exception, not only OSError: a certificate that fails verification raises ValueError, and running out of memory raises MemoryError. This also stops the socket leaking on other errors, such as a non-redirect status with a Location header. Co-Authored-By: Claude <noreply@anthropic.com> Signed-off-by: Joshua Wilson <joshua@qualithm.com>
A response to HEAD has no body, but its Content-Length or Transfer-Encoding was read as one, so .content raised ValueError: "Connection closed before body complete", or an invalid chunk size for a chunked response. It's now empty. The three ways of making the Response are merged into one, which more than pays for the change. Co-Authored-By: Claude <noreply@anthropic.com> Signed-off-by: Joshua Wilson <joshua@qualithm.com>
Following a redirect had these problems, all already in master: - The Authorization header, from auth= or headers=, went to any redirect target, including another host and plain http. It's now dropped when the scheme, host or port changes, except from http to https on the default ports, as CPython requests does. - timeout and parse_headers weren't passed on, so a redirect to a slow server ignored the timeout. - After a 301, 302 or 303, the GET kept the first request's Content-Length, Content-Type and Transfer-Encoding, so a server that reads the declared body waited for one that never came. They're now removed, as CPython requests does. A HEAD now stays a HEAD, instead of becoming a GET that reads the whole body. CPython requests also keeps HEAD when it follows a redirect, though its head() doesn't follow redirects by default. - After a 307 or 308, a request made with json= raised AssertionError, because json was passed on along with data, which already holds it encoded. - Redirects had no limit, so a loop recursed until RuntimeError. At most 30 are now followed, as in CPython requests, and one more raises ValueError. - Each redirect was followed from inside the call that got it, and each of those calls kept its closed socket until the chain ended, so on an ESP32-S3 a chain of https redirects ran out of memory at the 12th request. Redirects are now followed in a loop instead of by recursion, which passes every argument on and lets go of each socket before the next request, without adding arguments to request(). Co-Authored-By: Claude <noreply@anthropic.com> Signed-off-by: Joshua Wilson <joshua@qualithm.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Following a redirect in
requestsgoes wrong in several ways, all already in master. Testing #1175 (ssl=) turned them up. This PR is on top of #1175, because both change the redirect code: its first commit is #1175's, and I'll rebase once that's merged.Authorizationgoes to any redirect target. The header built fromauth=, or given inheaders=, is passed on to whatever theLocationnames, including another host or plainhttp://. A server that redirects https to http gets the credentials in clear text. CPython requests drops the header when the scheme, host or port changes, except from http to https on the default ports (Session.should_strip_auth), and this does the same.timeoutandparse_headersare dropped. The redirected request is made without them. Withtimeout=2, a redirect to a slow server waits as long as the server takes, andparse_headers=Falseor a callable only applies to the first response.headersis changed in place and onlyHostis removed, so the GET carriesContent-Length,Content-Typeand, for a generator body,Transfer-Encoding: chunked, with no body. A server that reads the declared body waits for one that never comes. CPython requests removes those three headers, and so does this. A HEAD now stays a HEAD, instead of becoming a GET that downloads the whole body; CPython requests also keeps HEAD when it follows a redirect (see Trade-offs forhead()).json=followed by a 307 or 308 raisesAssertionError. By thendataholds the encoded JSON, and bothdataandjsonare passed on.RuntimeError: maximum recursion depth exceeded, which took 203 requests on the unix port. This follows at most 30, CPython's default, and the next one raisesValueError("Too many redirects").OSError: [Errno 12] ENOMEMat the 12th request.head(url).contentraises. A response to HEAD has no body, but itsContent-LengthorTransfer-Encoding: chunkedwas read as one, so.contentraisedValueError. It's nowb"".The redirect fix follows redirects in a loop instead of by recursion. That passes every argument on and lets go of each socket before the next request, without adding arguments to
request(). It re-indents most ofrequest(), so the diff reads better with whitespace changes hidden: against #1175,__init__.pythen changes by 43 lines instead of 339.The HEAD fix is a separate commit. The README gets a short section on redirects, and the version goes to 1.2.1.
Testing
test_requests.pygains eight tests, and each fails without its commit:.contentof a HEAD response isb"", withContent-Lengthor chunked.Authorizationis kept for the same origin and for http to https on the default ports, and dropped for another host, port or scheme, including http to https on another host or port. Each redirect is judged against the request it came from, and a dropped header stays dropped, fromauth=orheaders=.timeoutreaches the redirected socket, aparse_headerscallable sees the redirected response's headers, andparse_headers=Falsestill leaves the final response without.headers.Content-Length,Content-TypeorTransfer-Encoding, whether the body came fromdata=(a str or a generator) orjson=, or the caller setContent-Type.json=request is sent again with the same body and headers.ValueError, with all 31 sockets closed.I also extended the path test from #1175 (https://gist.github.com/joshdoesthis/03410378b6b2a9b837abb11510661892) with
test_redirect_paths.pyand some server paths: a redirect to any scheme, host and port, a chain of N redirects, a loop that counts its requests, and an endpoint that reads the body its headers declare, as a strict server would. "Another host" is the test server's address written as a 32-bit number, which the client treats as a different host name. The servers use only CPython's standard library, as before.Results with this PR on the unix port and on stock MicroPython 1.29.0 release images, with #1175 alone ("before") on the unix port:
auth=, http, same originauth=, another hostauth=, https, another portauth=, https to httpauth=, https, same originauth=, http to https, non-default portsAuthorizationinheaders=, another hostjson=, then 302Content-Length,Content-Typedata=str, then 303Content-Lengthdata=generator, then 301Transfer-Encodingjson=, then 307 / 308AssertionErrordata=bytes, then 307b""b""b""timeout=2, then a redirect to a 6 s responseOSError2 s into the second requestOSErrorafter 2.0 sOSErrorafter 4.0 sOSErrorafter 2.8 stimeout=2, then a redirect to a stalled handshakeOSError2 s into the second requestOSErrorafter 2.0 sOSErrorafter 3.6 sOSErrorafter 2.5 sparse_headers=False, then a redirect.headers.headers.headers.headers.headersparse_headerscallable, then a redirectValueErrorafter 31 requestsRuntimeErrorafter 203ValueErrorafter 31ValueErrorafter 31ValueErrorafter 31ssl=, redirect loopValueErrorafter 31 requestsRuntimeErrorafter 203ValueErrorafter 31ValueErrorafter 31ValueErrorafter 31ssl=, 30 redirects then 200ssl, 30 redirects then 200Content-Length.contentisb""ValueErrorb""b""b"".contentisb""ValueErrorb""b""b"".contentisb""ValueErrorb""b""b""The times include the first request: the timeout applies to each request in the chain. On the boards, a chain of 31 https requests took 6.5 s (C6, without
ssl) to 34.3 s (S3, withssl), a handshake for each.On #1175 alone, the S3 failed a 20-redirect https chain with
OSError: [Errno 12] ENOMEMat the 12th request, because each call that followed a redirect kept its closed socket until the chain ended. A first version of this PR kept the recursion and failed the same way after 16 requests on both boards. The loop fixes that.#1175's own cases (certificates, its redirect cases, errors, bodies) all still hold with this PR on the unix port and the C6. On the S3, the ESP32-S3 stopped answering
mpremoteafter the redirect groups, so its run of the certificate, error and body cases is from the first version of this PR, where they all held.Not tested: esp8266 and the other ports.
Trade-offs and Alternatives
.mpygoes from 3270 to 3396 bytes (+126) against requests: Add ssl argument to pass a verifying SSLContext. #1175, measured with mpy-cross 1.29.0. The HEAD commit saves 10, because the three ways of making theResponsebecome one. In the redirect commit, the loop itself is 22 bytes smaller than the recursion, and the fixes add 158. Measured one at a time,Authorizationcosts 69, the limit 43 (30 of it the error), the body headers 30, keeping HEAD 6 andjson=None3.request()to carry the redirect count and the previous origin, and an explicit release of each socket. A recursive version with the same fixes passes the same tests, and is 27 bytes bigger, or 38 if the recursive call passes its arguments by keyword. The cost of the loop is the re-indented function.ValueError, like the module's other protocol errors. CPython raisesTooManyRedirects, which is anOSErrorthere.head()follows redirects. CPython'srequests.head()defaults toallow_redirects=False, so it returns the redirect response itself. This module has noallow_redirects, andhead()follows redirects, as it did before; with this PR, the redirected request stays a HEAD, as it does in CPython when redirects are followed. Stopping at the redirect would change what existing code gets back, so I've left that alone.requestsmatches request header names case-sensitively everywhere (Host,Content-Type), so onlyAuthorizationspelt that way is dropped; a header given asauthorizationis still sent on. Matching any case costs about 40 bytes; I've documented it instead. Host names are compared as written too, so a redirect that only changes their case also drops the header, where CPython lowercases them first.Cookieheader given inheaders=goes to any redirect target. CPython drops it on every redirect and rebuilds it from its cookie jar.Content-Length, which RFC 9110 allows, still raises in.content, as HEAD did.Generative AI
I used generative AI tools when creating this PR, but a human has checked the code and is responsible for the code and the description above.