Skip to content

Fix X-Forwarded-For port handling#2820

Closed
mcrolly wants to merge 2 commits intoKludex:mainfrom
mcrolly:fix/xff-port-handling-2789
Closed

Fix X-Forwarded-For port handling#2820
mcrolly wants to merge 2 commits intoKludex:mainfrom
mcrolly:fix/xff-port-handling-2789

Conversation

@mcrolly
Copy link
Copy Markdown

@mcrolly mcrolly commented Feb 16, 2026

Fixes #2789

Problem

X-Forwarded-For entries can include port numbers (e.g. 1.2.3.4:1024, [::1]:8080), but ProxyHeadersMiddleware was:

  1. Ignoring ports entirely — hardcoding port = 0 in scope["client"]
  2. Not recognizing trusted proxies with ports"10.0.0.1:9999" would fail ipaddress.ip_address() parsing and never match trusted hosts, so trusted proxies were treated as untrusted clients

This produced malformed client tuples like ("1.2.3.4:1024", 0).

Fix

  • Added _parse_host_and_port() helper that handles IPv4 with port (1.2.3.4:8080), bracketed IPv6 with port ([::1]:8080), and bare IPv6 (::1)
  • Updated __call__ to use parsed host and port instead of hardcoded port = 0
  • Updated _TrustedHosts.__contains__ to strip ports before IP comparison, while preserving literal matching for unix sockets etc.

Tests

  • IPv4 with port, IPv4 without port
  • Bracketed IPv6 with port, bare IPv6
  • Multi-proxy chain with ports on both client and trusted proxy
  • Unit tests for _parse_host_and_port edge cases (invalid port string, missing brackets, etc.)
  • All 252 existing tests pass, 0 regressions

Fixes Kludex#2789

X-Forwarded-For entries can include port numbers (e.g. '1.2.3.4:1024',
'[::1]:8080'). Previously, the port was discarded and hardcoded to 0,
and entries with ports were not recognized as trusted proxies.

Changes:
- Add _parse_host_and_port() to extract host and port from XFF entries
- Update ProxyHeadersMiddleware to preserve port from XFF when present
- Update _TrustedHosts.__contains__ to recognize IPs with ports as trusted
- Add tests for IPv4:port, [IPv6]:port, and multi-proxy port scenarios
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