Skip to content

simple_httpclient percent-encodes the redirect Location host, breaking IDN redirects #3870

Closed

Description

@BlueX888

What happens?

SimpleAsyncHTTPClient follows a redirect by percent-encoding the entire Location header value:

location = _percent_encode_url(self.headers["Location"].encode("latin1"))
new_request.url = urllib.parse.urljoin(self.request.url, location)

When the Location contains a non-ASCII host encoded as latin-1 — the form produced by self.set_header("Location", "http://café.example/") — the host itself gets percent-encoded instead of being IDNA-encoded. A redirect to http://café.example:PORT/final sends caf%E9.example to the resolver, which is not a valid IDNA host; the redirected request never reaches the target.

Before commit 63b2b5cfffe2a64e201e93ff6a0fd433f3a21eb7 (2026-10-30, PR #3860, "simple_httpclient: Percent-encode non-ASCII characters in URLs"), the resolver received café.example and the redirect succeeded. After that commit, the host is rewritten. The commit's intent — percent-encoding non-ASCII bytes and spaces in the path/query of Location — is right, but applying the helper to the whole URL also hits the authority.

Expected behavior

Per WHATWG/browser URL handling, only the path, query and fragment are percent-encoded. The host is percent-decoded and IDNA-encoded (café.example → xn--caf-dma.example), never percent-encoded. The same redirect should resolve and reach the target as it did before 63b2b5cf.

How to reproduce

A loopback server returns 302 with Location: http://café.example:PORT/final, and socket.getaddrinfo is patched to log the host handed to the resolver. On current main (6530be98) the resolver sees caf%E9.example; on the parent of 63b2b5cf it sees café.example and the redirect succeeds with 200 ok. The explorer's script is below; it also covers the UTF-8 variant.

import socket

import tornado.httpclient
import tornado.ioloop
import tornado.web

seen_hosts = []
real_getaddrinfo = socket.getaddrinfo


def getaddrinfo(host, port, *args, **kwargs):
    seen_hosts.append(host)
    if host in ("café.example", "xn--caf-dma.example"):
        return real_getaddrinfo("127.0.0.1", port, *args, **kwargs)
    return real_getaddrinfo(host, port, *args, **kwargs)


socket.getaddrinfo = getaddrinfo


class RedirectHandler(tornado.web.RequestHandler):
    def get(self):
        self.set_header(
            "Location", "http://café.example:%d/final" % self.application.settings["port"]
        )
        self.set_status(302)


class FinalHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("ok")


async def main():
    app = tornado.web.Application(
        [(r"/start", RedirectHandler), (r"/final", FinalHandler)], port=0
    )
    server = app.listen(0, address="127.0.0.1")
    port = server._sockets[0].getsockname()[1]
    app.settings["port"] = port
    client = tornado.httpclient.AsyncHTTPClient()
    try:
        response = await client.fetch("http://127.0.0.1:%d/start" % port)
        print("code=%s body=%r" % (response.code, response.body))
    except Exception as exc:
        print("fetch failed: %r" % (exc,))
    print("resolver saw:", seen_hosts)
    server.stop()


tornado.ioloop.IOLoop.current().run_sync(main)

Observed on current main: the resolver receives caf%E9.example, the redirect target is never contacted, and the fetch times out. On the parent of 63b2b5cf: the resolver receives café.example, and the redirect completes with 200 ok.

Note: the visible end-to-end symptom is a hang rather than a clean error because of the separate, already-known redirect-error bug (#3064, open PR #3692), where errors after a redirect are raised in a done callback. This report is about the hostname rewrite at the resolver boundary, not about #3064.

Notes

(Reported by an AI agent operating the BlueX888 account; the reproduction and pre/post-commit comparison above were run and verified locally.)

Activity

  1. bdarnell commented on Nov 13, 2026

    @bdarnell
    Member

    I've fixed/added IDN support in #3873. However, this doesn't quite solve the original issue reported here. RFC 9110 says that header values should be ascii-only, and what browsers do is to treat any non-ascii characters as utf-8. Treating non-ascii values as latin1 (which is what tornado used to do) is incorrect and inconsistent with the rest of the web ecosystem.

    So if your application is doing something like

            self.set_header(
                "Location", "http://café.example:%d/final" % self.application.settings["port"]
            )
    

    You'll need to update it to (ideally) send the location header in the proper IDNA-encoded way (ideally), or to encode it as utf8 instead of latin1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions