Request.url turns a // path into an authority when the scope has no host
When a request scope has neither a Host header nor a server entry, Request.url places scope["path"] directly after the scheme, so a path that starts with // is parsed as an authority. A response built from that URL then emits a scheme-relative Location.
Reproduction
from starlette.requests import Request
from starlette.responses import RedirectResponse
scope = {
"type": "http",
"scheme": "http",
"path": "//evil.example/x",
"query_string": b"a=1",
"headers": [],
"server": None,
}
url = Request(scope).url
print(str(url), url.netloc)
print(RedirectResponse(url).headers["location"])On current main (1.7.0) this prints:
//evil.example/x?a=1 evil.example
//evil.example/x?a=1The Location value is scheme-relative, so a browser resolves it to http://evil.example/x?a=1.
As soon as any origin information is present the result is same-origin, which is the expected behaviour:
scope["headers"] = [(b"host", b"victim.example")] # or scope["server"] = ("victim.example", 80)
# -> http://victim.example//evil.example/x?a=1Why this looks wrong
#3326 says the path should not be placed directly against the authority and that the resulting URL should parse back into the components it was built from. That holds when Host or server is available, but the branch that builds the URL without origin metadata still uses the raw path as the whole URL, so the path ends up in netloc.
server is optional in the ASGI HTTP scope, so a scope without it and without a Host header is legal. An application that redirects to request.url then sends the visitor to the host taken from the path.
Suggested fix
In the branch that builds the URL without origin metadata, keep a //-prefixed path out of the authority position, for example by percent-encoding its first character or by producing a URL without a netloc, so urlsplit cannot turn the first path segment into a host.
Source: Kludex/starlette