Skip to content

Comments

Fix X-Forwarded-For not properly handling ports#2809

Open
veeceey wants to merge 4 commits intoKludex:mainfrom
veeceey:fix/issue-2789
Open

Fix X-Forwarded-For not properly handling ports#2809
veeceey wants to merge 4 commits intoKludex:mainfrom
veeceey:fix/issue-2789

Conversation

@veeceey
Copy link

@veeceey veeceey commented Feb 8, 2026

Summary

Fixes #2789.

  • Add _parse_host_port() helper to properly extract host and port from X-Forwarded-For entries, handling IPv4 with port (1.2.3.4:1024), bracketed IPv6 with port ([::1]:8080), bare addresses, and edge cases
  • Update get_trusted_client_host() to use the helper so trust checking works correctly for entries with ports (previously 1.2.3.4:1024 failed ipaddress.ip_address() and fell through to literal matching)
  • Update ProxyHeadersMiddleware.__call__() to use the parsed port in scope["client"] instead of always hardcoding 0

Before this fix, an X-Forwarded-For value of 1.2.3.4:1024 would produce scope["client"] = ("1.2.3.4:1024", 0). After this fix, it correctly produces scope["client"] = ("1.2.3.4", 1024).

Test plan

  • All 248 existing proxy header tests continue to pass
  • Added 13 unit tests for _parse_host_port() covering IPv4, IPv4+port, bare IPv6, bracketed IPv6+port, edge cases
  • Added 8 integration tests for X-Forwarded-For with ports across trust scenarios (always trust, trusted proxy, untrusted proxy, multiple proxies, trusted networks)

@veeceey veeceey force-pushed the fix/issue-2789 branch 2 times, most recently from d6f3d96 to 9a701f1 Compare February 16, 2026 07:43
veeceey and others added 4 commits February 19, 2026 23:50
The proxy headers middleware now correctly parses port numbers from
X-Forwarded-For entries (e.g. "1.2.3.4:1024", "[::1]:8080") instead
of blindly appending ":0", which previously produced malformed client
addresses like "1.2.3.4:1024:0".

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Move the `_parse_host_port` import from mid-file (line 500) to the
existing import block at the top of the test file, fixing the ruff E402
"Module level import not at top of file" error that caused all 18 CI
matrix jobs to fail.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Adds test case for `[::1]:abc` to cover the ValueError/IndexError
exception handler in `_parse_host_port()`, fixing the coverage gap
on lines 85-86.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

X-Forwarded-For doesn't properly handle ports

1 participant