Scan the X-Forwarded-For chain without splitting it (closes #133)
All checks were successful
check / check (push) Successful in 3m20s

The 64-hop cap bounded the walk but not the allocation: the chain was
split before it was capped, so a padded header cost a []string
proportional to its whole length on every request to the
unauthenticated receiver.

Cut hops off the right end of each header value in place with
strings.LastIndexByte instead, and walk multiple header values in
reverse rather than joining them. Bucket assignment is unchanged: the
walk still counts every comma-separated entry against the cap, skips
empty ones, stops at the first hop that is not a trusted proxy, and
falls back to the peer on an unreadable hop or an exhausted cap.

Measured over a 1 MB chain: 1,606,043 bytes allocated per call before,
16 bytes after.
This commit is contained in:
2026-08-12 10:04:55 +00:00
parent fd6397154a
commit b1eb2466f6
3 changed files with 99 additions and 17 deletions

View File

@@ -81,29 +81,45 @@ func (m *Middleware) isTrustedProxy(addr netip.Addr) bool {
// Only the last maxForwardedHops entries are examined. A longer chain
// is padding, and running out of hops falls back to the peer address
// the same way an unreadable hop does.
//
// The entries are cut off the right end of each header value in place
// rather than split out of it: the receiver is unauthenticated and a
// client can pad the header up to MaxHeaderBytes, so splitting would
// allocate in proportion to the padding (about 8 MB for a 1 MB
// header) before the cap could discard any of it. Multiple header
// values are walked in reverse for the same reason, since joining
// them copies the whole chain.
func (m *Middleware) forwardedClientAddr(
r *http.Request,
) (netip.Addr, bool) {
hops := strings.Split(
strings.Join(r.Header.Values("X-Forwarded-For"), ","), ",",
)
if len(hops) > maxForwardedHops {
hops = hops[len(hops)-maxForwardedHops:]
}
seen := 0
for _, hop := range slices.Backward(hops) {
hop = strings.TrimSpace(hop)
if hop == "" {
continue
}
for _, value := range slices.Backward(
r.Header.Values("X-Forwarded-For"),
) {
for last := false; !last && seen < maxForwardedHops; seen++ {
hop := value
addr, err := netip.ParseAddr(hop)
if err != nil {
return netip.Addr{}, false
}
comma := strings.LastIndexByte(value, ',')
if comma < 0 {
last = true
} else {
hop, value = value[comma+1:], value[:comma]
}
if addr = normalizeAddr(addr); !m.isTrustedProxy(addr) {
return addr, true
hop = strings.TrimSpace(hop)
if hop == "" {
continue
}
addr, err := netip.ParseAddr(hop)
if err != nil {
return netip.Addr{}, false
}
if addr = normalizeAddr(addr); !m.isTrustedProxy(addr) {
return addr, true
}
}
}