fix: support IPv6 addresses in TrustedHostMiddleware - #3379
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 255bd37301
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| host = headers.get("host", "") | ||
| if host.startswith("["): | ||
| closing_bracket = host.find("]") | ||
| if closing_bracket != -1 and (closing_bracket == len(host) - 1 or host[closing_bracket + 1] == ":"): |
There was a problem hiding this comment.
Reject non-port suffixes after IPv6 literals
When allowed_hosts contains an IPv6 literal such as [::1], this condition strips everything after ] as long as the next character is :, so a malformed Host header like [::1]:attacker is treated as [::1] and the request is allowed through. Since this middleware is meant to reject incorrectly set Host headers, the IPv6 path should only ignore a numeric port (or otherwise reject the malformed suffix) instead of accepting arbitrary text after ]:.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
All reported issues were addressed across 2 files (changes from recent commits).
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
Summary
HostTrustedHostMiddlewarecoverage for[::1]:8000Root cause
The middleware split
Hoston the first colon, converting[::1]:8000to[. A configured[::1]host was therefore rejected.Fixes #3357
Validation
python -m pytest tests/middleware/test_trusted_host.py -qruff check starlette/middleware/trustedhost.py tests/middleware/test_trusted_host.pyruff format --check starlette/middleware/trustedhost.py tests/middleware/test_trusted_host.pymypy starlette/middleware/trustedhost.py tests/middleware/test_trusted_host.py