chi/middleware/client_ip_bench_test.go
Vojtech Vitek (golang.cz) 7f9b7448f5
middleware: treat RemoteAddr as the rightmost hop in ClientIPFrom* (#1214)
* middleware: treat RemoteAddr as the rightmost hop in ClientIPFrom*

ClientIPFromXFF trusted X-Forwarded-For entries in the configured CIDRs
but never checked that the TCP peer was one of those proxies. A client
reaching the origin directly could pick its own client IP.

- ClientIPFromXFF: a peer outside the trusted prefixes is now the client
  IP and XFF is ignored. Calling it with no prefixes now panics; use
  ClientIPFromXFFTrustedProxies(1) or pass the proxy's address instead.
- ClientIPFromHeader: accepts optional trusted prefixes with the same
  rule, matching nginx set_real_ip_from, Apache RemoteIPTrustedProxy and
  Caddy trusted_proxies. Without prefixes, behavior is unchanged.
- ClientIPFromXFFTrustedProxies: unchanged; it is for unknown proxy IPs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* middleware: note Cloudflare CIDRs in example are a partial list

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 13:22:20 +02:00

58 lines
1.7 KiB
Go

package middleware
import (
"fmt"
"strings"
"testing"
)
// BenchmarkWalkXFF measures the cost of walking a merged X-Forwarded-For
// chain end-to-end (visitor never stops). Exercises the worst case for
// ClientIPFromXFF when every entry is in the trusted prefix list, and
// bounds the absolute cost of a pathologically large attacker-supplied
// XFF header (subject to http.Server.MaxHeaderBytes).
//
// n varies the number of comma-separated entries in a single XFF header.
// All entries are valid IPs of identical length, so total header size
// scales linearly with n.
func BenchmarkWalkXFF(b *testing.B) {
for _, n := range []int{1, 10, 100, 1000, 10000} {
entries := make([]string, n)
for i := range entries {
entries[i] = "1.2.3.4"
}
headers := []string{strings.Join(entries, ", ")}
b.Run(fmt.Sprintf("n=%d", n), func(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
walkXFF(headers, func(entry string) bool {
return false // walk to the leftmost entry
})
}
})
}
}
// BenchmarkWalkXFF_RightmostStop measures the common case for both
// ClientIPFromXFF (rightmost entry untrusted => stop at the first visit)
// and ClientIPFromXFFTrustedProxies(1). Should be near-constant
// regardless of n, since the walker stops after the first visit.
func BenchmarkWalkXFF_RightmostStop(b *testing.B) {
for _, n := range []int{1, 10, 100, 1000, 10000} {
entries := make([]string, n)
for i := range entries {
entries[i] = "1.2.3.4"
}
headers := []string{strings.Join(entries, ", ")}
b.Run(fmt.Sprintf("n=%d", n), func(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
walkXFF(headers, func(entry string) bool {
return true // stop at the rightmost entry
})
}
})
}
}