Drop first-write-wins semantics, we want users to use exactly one middleware

This commit is contained in:
Vojtech Vitek 2026-05-17 20:30:20 +02:00
parent 716b67ae54
commit 482e855993
No known key found for this signature in database
3 changed files with 29 additions and 49 deletions

View file

@ -27,10 +27,6 @@ var clientIPCtxKey = &contextKey{"clientIP"}
func ClientIPFromHeader(trustedHeader string) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if hasClientIP(r.Context()) {
h.ServeHTTP(w, r)
return
}
if ip, err := netip.ParseAddr(r.Header.Get(trustedHeader)); err == nil {
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, ip))
}
@ -68,10 +64,6 @@ func ClientIPFromXFF(trustedIPPrefixes ...string) func(http.Handler) http.Handle
}
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if hasClientIP(r.Context()) {
h.ServeHTTP(w, r)
return
}
if ip, ok := rightmostUntrustedXFF(r.Header.Values("X-Forwarded-For"), prefixes); ok {
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, ip))
}
@ -110,10 +102,6 @@ func ClientIPFromXFFTrustedProxies(numTrustedProxies int) func(http.Handler) htt
}
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if hasClientIP(r.Context()) {
h.ServeHTTP(w, r)
return
}
xff := mergeXFF(r.Header.Values("X-Forwarded-For"))
if i := len(xff) - numTrustedProxies; i >= 0 {
if ip, err := netip.ParseAddr(xff[i]); err == nil {
@ -135,10 +123,6 @@ func ClientIPFromXFFTrustedProxies(numTrustedProxies int) func(http.Handler) htt
// [ClientIPFromXFF] instead.
func ClientIPFromRemoteAddr(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if hasClientIP(r.Context()) {
h.ServeHTTP(w, r)
return
}
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
host = r.RemoteAddr // RemoteAddr may already be a bare IP (e.g. in tests).
@ -170,12 +154,6 @@ func GetClientIPAddr(ctx context.Context) netip.Addr {
return ip
}
// hasClientIP reports whether an upstream ClientIPFrom* middleware has
// already set a valid client IP on the context.
func hasClientIP(ctx context.Context) bool {
return GetClientIPAddr(ctx).IsValid()
}
// mergeXFF merges all X-Forwarded-For header values into a single ordered
// list of trimmed entries (left-to-right, in the order received). Empty
// entries are dropped. Entries are not validated as IPs here.

View file

@ -29,10 +29,7 @@ import (
//
// Read the resulting IP with [middleware.GetClientIP] (string) or
// [middleware.GetClientIPAddr] ([net/netip.Addr]). These middlewares never
// mutate [net/http.Request.RemoteAddr]. If a middleware earlier in the chain
// already set a client IP, later ClientIPFrom* middlewares are no-ops; this
// lets you chain a primary with a fallback, e.g. ClientIPFromXFF("10.0.0.0/8")
// followed by ClientIPFromRemoteAddr.
// mutate [net/http.Request.RemoteAddr].
//
// The legacy [middleware.RealIP] middleware is deprecated; it is vulnerable
// to IP spoofing (GHSA-3fxj-6jh8-hvhx, GHSA-rjr7-jggh-pgcp, GHSA-9g5q-2w5x-hmxf).

View file

@ -247,13 +247,16 @@ func TestClientIPFromRemoteAddr(t *testing.T) {
}
}
// Chaining (the first middleware to set wins; later ones are no-ops)
// Chaining: each ClientIPFrom* middleware always runs and overwrites if it
// finds a value; the last one with a value wins. To get primary+fallback
// behavior, order is "fallback first, preferred last".
func TestClientIPChaining(t *testing.T) {
t.Run("header_wins_over_xff", func(t *testing.T) {
// Preferred middleware runs LAST and overrides the fallback.
t.Run("header_overrides_xff_when_set", func(t *testing.T) {
got := runChain(t,
[]func(http.Handler) http.Handler{
ClientIPFromHeader("CF-Connecting-IP"),
ClientIPFromXFF(),
ClientIPFromXFF(), // fallback.
ClientIPFromHeader("CF-Connecting-IP"), // preferred.
},
func(r *http.Request) {
r.Header.Set("CF-Connecting-IP", "1.1.1.1")
@ -264,33 +267,35 @@ func TestClientIPChaining(t *testing.T) {
}
})
t.Run("xff_falls_through_to_remoteaddr", func(t *testing.T) {
// Preferred middleware finds nothing, so the fallback's value persists.
t.Run("xff_persists_when_header_missing", func(t *testing.T) {
got := runChain(t,
[]func(http.Handler) http.Handler{
ClientIPFromXFF("10.0.0.0/8"),
ClientIPFromRemoteAddr,
},
func(r *http.Request) {
// XFF contains only trusted values → no IP set by ClientIPFromXFF.
r.Header.Set("X-Forwarded-For", "10.0.0.1, 10.0.0.2")
r.RemoteAddr = "192.0.2.1:1234"
})
if got != "192.0.2.1" {
t.Errorf("want 192.0.2.1 (RemoteAddr fallback), got %q", got)
}
})
t.Run("missing_header_falls_through_to_xff", func(t *testing.T) {
got := runChain(t,
[]func(http.Handler) http.Handler{
ClientIPFromHeader("CF-Connecting-IP"),
ClientIPFromXFF(),
ClientIPFromHeader("CF-Connecting-IP"), // missing → no-op.
},
func(r *http.Request) {
r.Header.Set("X-Forwarded-For", "8.8.8.8")
})
if got != "8.8.8.8" {
t.Errorf("want 8.8.8.8 (XFF fallback), got %q", got)
t.Errorf("want 8.8.8.8, got %q", got)
}
})
// RemoteAddr as last-resort baseline; XFF would override but finds only
// trusted IPs, so the baseline persists.
t.Run("remoteaddr_fills_in_when_xff_finds_nothing", func(t *testing.T) {
got := runChain(t,
[]func(http.Handler) http.Handler{
ClientIPFromRemoteAddr,
ClientIPFromXFF("10.0.0.0/8"), // all trusted → no-op.
},
func(r *http.Request) {
r.Header.Set("X-Forwarded-For", "10.0.0.1, 10.0.0.2")
r.RemoteAddr = "192.0.2.1:1234"
})
if got != "192.0.2.1" {
t.Errorf("want 192.0.2.1, got %q", got)
}
})
}