TrustedHostMiddleware Doesn't handle IPv6 properly #3321
Unanswered
gopackgo90
asked this question in
Potential Issue
Replies: 2 comments
|
Confirmed, this is a real bug and your diagnosis is spot on. The middleware does There's no config flag around it since that parsing is hardcoded. Cleanest stopgap is a subclass that fixes the Host header to its bracket-only form before the parent's check runs: from starlette.datastructures import Headers
from starlette.middleware.trustedhost import TrustedHostMiddleware
class IPv6SafeTrustedHost(TrustedHostMiddleware):
async def __call__(self, scope, receive, send):
if scope["type"] in ("http", "websocket") and not self.allow_any:
raw = Headers(scope=scope).get("host", "")
fixed = raw[: raw.index("]") + 1] if raw.startswith("[") else raw.split(":")[0]
scope = {
**scope,
"headers": [
(k, fixed.encode() if k == b"host" else v) for k, v in scope["headers"]
],
}
await super().__call__(scope, receive, send)Then Worth opening a PR too if there isn't one, the real fix is just teaching that |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Say I have the below Starlette app,
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,starlette/starlette/middleware/trustedhost.py
Line 40 in 70a3bd4
When I remove the
TrustedHostMiddleware, I get the hello world response as expected.All reactions