starlette icon indicating copy to clipboard operation
starlette copied to clipboard

TrustedHostMiddleware Doesn't handle IPv6 properly

Open gopackgo90 opened this issue 5 months ago β€’ 5 comments

  • 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.

gopackgo90 avatar Jul 03 '26 04:07 gopackgo90

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.

gopackgo90 avatar Jul 03 '26 15:07 gopackgo90

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.

aryansk avatar Aug 20 '26 13:08 aryansk

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?

Gambit-Checkmate avatar Aug 22 '26 13:08 Gambit-Checkmate

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 malformed Host: [::1 ends up matching [::1]. Same trick makes [::1]junk pass.
  • The lenient branches (#3439, #3444, #3445) treat anything up to/after the closing bracket as the host, so [::1]junk and 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 a base_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.

Mukller avatar Aug 23 '26 01:08 Mukller

It's unacceptable the amount of PRs that were created here. I've banned everyone involved from this repo (besides the first PR).

Kludex avatar Aug 25 '26 13:08 Kludex