TrustedHostMiddleware Doesn't handle IPv6 properly
- Initially raised as discussion #3321
Say I have the below Starlette app,
# main.py
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.trustedhost import TrustedHostMiddleware
from starlette.responses import JSONResponse
from starlette.routing import Route
async def homepage(request):
return JSONResponse({'hello': 'world'})
routes = [
Route("/", endpoint=homepage)
]
middleware = [
Middleware(TrustedHostMiddleware, allowed_hosts=["[::1]"])
]
app = Starlette(debug=True, routes=routes, middleware=middleware)
and run it with uvicorn main:app --host '::1'. When I go to http://[::1]:8000 in my browser, I get the "Invalid host header" response. This appears to be because Starlette is thinking the host is "[" based on the splitting logic in the middleware, https://github.com/Kludex/starlette/blob/70a3bd4276712f0ee11b161c8b14225a84316df1/starlette/middleware/trustedhost.py#L40.
When I remove the TrustedHostMiddleware, I get the hello world response as expected.
I think the PR I opened, https://github.com/Kludex/starlette/pull/3358, should be preferred as itβs implementation has already been well-tested in Django.
Working on a fix for the IPv6 bracket handling in TrustedHostMiddleware (host extraction for [::1]:8000). Will open a PR against main shortly β PR #3444 already covers this with the minimal bracket-aware split fix.
Hi, Iβd like to investigate the IPv6 handling in TrustedHostMiddleware. I can add a minimal IPv6 host test, compare it with the duplicate report, and keep the fix limited to host normalization. Is this issue still open for community work?
I ran all six open PRs for this issue locally (CPython 3.13 / Windows) against the reported repro plus a probe matrix of malformed Host headers, so the differences are easier to see than from six parallel diffs.
Every branch fixes the reported case (Host: [::1]:8000 with allowed_hosts=["[::1]"]). They diverge on malformed input:
| PR | host extraction | [::1]junk |
[::1]:abc |
[::1 (unclosed) |
fixes TestClient netloc too | targeted tests |
|---|---|---|---|---|---|---|
| #3379 | keeps brackets, validates port after ] |
400 | 400 | 400 | no | 55 passed |
| #3439 | keeps brackets (rindex), lenient |
200 | 200 | 400 | yes | 59 passed |
| #3441 | keeps brackets, strict port + wildcard guard for bracketed hosts | 400 | 400 | 400 | yes | 65 passed |
| #3442 | partition("]")-based |
200 | 200 | 200 | no | 59 passed |
| #3444 | strips brackets, matches patterns with or without brackets | 200 | 200 | 400 | no | 57 passed |
| #3445 | keeps brackets, flexible matching both directions | 200 | 200 | 400 | yes | 59 passed |
Notes from the runs:
- #3442 has a correctness wart:
"[::1".partition("]")[0] + "]"reconstructs a valid-looking host from an unclosed bracket, so a malformedHost: [::1ends up matching[::1]. Same trick makes[::1]junkpass. - The lenient branches (#3439, #3444, #3445) treat anything up to/after the closing bracket as the host, so
[::1]junkand non-numeric ports slip through as[::1]. Not exploitable past the allowlist match itself, but they don't reject garbage either. - Only #3379 and #3441 validate that what follows
]is empty or:digits. - Scope: #3439, #3441 and #3445 also repair
TestClient's own netloc parsing (a real adjacent bug β today abase_url="http://[::1]:8000"gets mangled there), the others touch the middleware only. - Full suite vs the master baseline on this machine (14 pre-existing failures): the five branches other than #3379 add zero new failures; #3379 showed 2 extra in
test_staticfiles.py::test_staticfiles_filename_too_long[asyncio|trio]β almost certainly path-length flakiness on Windows rather than the diff, but worth a CI glance before merging it. - One design decision cuts across everything: whether the extracted host keeps brackets (then configs must be written as
["[::1]"]) or is normalized without them (#3444, which accepts both forms in config). Worth settling explicitly since users will have existing configs in both styles.
It's unacceptable the amount of PRs that were created here. I've banned everyone involved from this repo (besides the first PR).