Skip to content

requests: Fix redirect handling. - #1185

Open
joshdoesthis wants to merge 3 commits into
micropython:masterfrom
joshdoesthis:requests-redirects
Open

joshdoesthis wants to merge 3 commits into
micropython:masterfrom
joshdoesthis:requests-redirects

Conversation

@joshdoesthis

Copy link
Copy Markdown

Summary

Following a redirect in requests goes 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.

  • Authorization goes to any redirect target. The header built from auth=, or given in headers=, is passed on to whatever the Location names, including another host or plain http://. 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.
  • timeout and parse_headers are dropped. The redirected request is made without them. With timeout=2, a redirect to a slow server waits as long as the server takes, and parse_headers=False or a callable only applies to the first response.
  • A 301, 302 or 303 sends the first request's body headers with the GET. headers is changed in place and only Host is removed, so the GET carries Content-Length, Content-Type and, 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 for head()).
  • json= followed by a 307 or 308 raises AssertionError. By then data holds the encoded JSON, and both data and json are passed on.
  • There's no limit on redirects. A loop recurses until 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 raises ValueError("Too many redirects").
  • Long https chains run out of memory on an ESP32. Each redirect is followed from inside the call that got it, and each of those calls keeps its socket, closed but still in memory, until the chain ends. On an ESP32-S3, a chain of https redirects failed with OSError: [Errno 12] ENOMEM at the 12th request.
  • head(url).content raises. A response to HEAD has no body, but its Content-Length or Transfer-Encoding: chunked was read as one, so .content raised ValueError. It's now b"".

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 of request(), so the diff reads better with whitespace changes hidden: against #1175, __init__.py then 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.py gains eight tests, and each fails without its commit:

  1. .content of a HEAD response is b"", with Content-Length or chunked.
  2. Authorization is 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, from auth= or headers=.
  3. timeout reaches the redirected socket, a parse_headers callable sees the redirected response's headers, and parse_headers=False still leaves the final response without .headers.
  4. After a 301, 302 or 303, the GET has no Content-Length, Content-Type or Transfer-Encoding, whether the body came from data= (a str or a generator) or json=, or the caller set Content-Type.
  5. A 301, 302 or 303 keeps HEAD, with no body read.
  6. After a 307 or 308, a json= request is sent again with the same body and headers.
  7. 30 redirects are followed; a 31st raises ValueError, with all 31 sockets closed.
  8. A redirect's socket can be freed while the redirect is followed.

I also extended the path test from #1175 (https://gist.github.com/joshdoesthis/03410378b6b2a9b837abb11510661892) with test_redirect_paths.py and 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:

Case Expected before unix ESP32_GENERIC_S3 ESP32_GENERIC_C6
auth=, http, same origin sent sent sent sent sent
auth=, another host not sent sent not sent not sent not sent
auth=, https, another port not sent sent not sent not sent not sent
auth=, https to http not sent sent, in clear text not sent not sent not sent
auth=, https, same origin sent sent sent sent sent
auth=, http to https, non-default ports not sent sent not sent not sent not sent
Authorization in headers=, another host not sent sent not sent not sent not sent
POST json=, then 302 GET, no body headers Content-Length, Content-Type GET, none GET, none GET, none
POST data= str, then 303 GET, no body headers Content-Length GET, none GET, none GET, none
POST data= generator, then 301 GET, no body headers Transfer-Encoding GET, none GET, none GET, none
POST, then 302, to a server that reads the declared body 200 at once 408 after 10 s 200 200 200
POST json=, then 307 / 308 POST, same body AssertionError POST, same body POST, same body POST, same body
POST data= bytes, then 307 POST, same body POST, same body POST, same body POST, same body POST, same body
HEAD, then 302 HEAD, no body GET, body read HEAD, b"" HEAD, b"" HEAD, b""
timeout=2, then a redirect to a 6 s response OSError 2 s into the second request 200 after 6.0 s OSError after 2.0 s OSError after 4.0 s OSError after 2.8 s
timeout=2, then a redirect to a stalled handshake OSError 2 s into the second request no return in 30 s OSError after 2.0 s OSError after 3.6 s OSError after 2.5 s
parse_headers=False, then a redirect no .headers has .headers no .headers no .headers no .headers
parse_headers callable, then a redirect sees the final headers doesn't sees them sees them sees them
http redirect loop ValueError after 31 requests RuntimeError after 203 ValueError after 31 ValueError after 31 ValueError after 31
http, 30 redirects then 200 200 200 200 200 200
https with ssl=, redirect loop ValueError after 31 requests RuntimeError after 203 ValueError after 31 ValueError after 31 ValueError after 31
https with ssl=, 30 redirects then 200 200 200 200 200 200
https without ssl, 30 redirects then 200 200 200 200 200 200
HEAD, Content-Length .content is b"" ValueError b"" b"" b""
HEAD, chunked .content is b"" ValueError b"" b"" b""
HEAD, then 307 .content is b"" ValueError b"" 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, with ssl), a handshake for each.

On #1175 alone, the S3 failed a 20-redirect https chain with OSError: [Errno 12] ENOMEM at 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 mpremote after 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

  • Code size: the .mpy goes 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 the Response become 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, Authorization costs 69, the limit 43 (30 of it the error), the body headers 30, keeping HEAD 6 and json=None 3.
  • A loop, not recursion. Keeping the recursion needs two extra keyword arguments on 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.
  • The error for too many redirects is ValueError, like the module's other protocol errors. CPython raises TooManyRedirects, which is an OSError there.
  • head() follows redirects. CPython's requests.head() defaults to allow_redirects=False, so it returns the redirect response itself. This module has no allow_redirects, and head() 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.
  • Names are matched as written. requests matches request header names case-sensitively everywhere (Host, Content-Type), so only Authorization spelt that way is dropped; a header given as authorization is 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.
  • Not changed here (found while testing, all in master):
    • A 301 turns PUT and DELETE into GET. CPython only rewrites POST on a 301.
    • A Cookie header given in headers= goes to any redirect target. CPython drops it on every redirect and rebuilds it from its cookie jar.
    • A 304 with 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.

joshdoesthis and others added 3 commits November 17, 2026 17:31
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant