Sample
github.com/go-chi/chi/v5 v5.3.1: Extract client IP from X-Forwarded-For with go-chi middleware without assuming unconfigured trusted prefixes extract the leftmost IP or mutate RemoteAddr
Verified sample for golang github.com/go-chi/chi/v5 v5.3.1: Extract client IP from X-Forwarded-For with go-chi middleware without assuming unconfigured…
sha256:d4739403233b2cbcca31e8d433c568f8282f11bca02bd7365a2789ac54729770
This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured.
How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people.
MIT-0
Execution evidence
The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.
- Evidence basis
- Signed contract pass
- Verification receipts
- 3
- Signing keys that built it
- 3
Declared environment
go linux x64 go go gomod
Verification-run environments
| Environment | Contract | Stages | Run |
|---|---|---|---|
| go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1 |
2026-08-16 |
| go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1 |
2026-08-18 |
| go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f… |
2026-09-07 |
Case
HOW- Goal
- Extract client IP from X-Forwarded-For with go-chi middleware without assuming unconfigured trusted prefixes extract the leftmost IP or mutate RemoteAddr
- Packages
- Symbols
-
- middleware.ClientIPFromXFF
- middleware.GetClientIP
- middleware.GetClientIPAddr
- Environment
- go
- Created
- 2026-08-16T13:25:20Z
Contract
- assert ClientIPFromXFF with unset trusted prefixes returns the rightmost XFF hop rather than the leftmost client IP
- assert ClientIPFromXFF leaves RemoteAddr unmodified and stores the resolved IP in context
- assert ClientIPFromXFF with explicit trusted CIDR prefixes skips trusted hops to extract the originating client IP
- assert ClientIPFromXFF fails closed returning an empty IP when encountering an invalid hop in the chain
- assert ClientIPFromXFF merges multiple X-Forwarded-For headers and evaluates hops right to left
Files
- NOTES.md
- clientip.go
- clientip_test.go
- csx.json
- go.mod
- go.sum
Source
# Notes: github.com/go-chi/chi/v5 ClientIPFromXFF Default Behavior
## 1. Network Search Result
`search_known_solution` returned existing sample `sha256:8a05cf61b89bea84e9ae1dc410f9f500c1009e51fec9897152bcdb81c072752f` (*"Read URL parameters and nest routers with go-chi"*). That sample covers URL parameter extraction with nested routing trees, but does not address IP extraction or middleware default arguments.
## 2. What a Model Would Have Written Instead
A model would have written `r.Use(middleware.ClientIPFromXFF())` expecting it to act as a direct replacement for deprecated `middleware.RealIP`, assuming it extracts the client IP from the start of the `X-Forwarded-For` chain (the leftmost IP) and mutates `req.RemoteAddr`.
## 3. How the Wrong Assumption Fails
It fails silently with a green build: requests passing through reverse proxies return the rightmost proxy hop address instead of the client IP, and downstream logging or rate limiting inspecting `req.RemoteAddr` receives the socket remote address without mutation.
package clientip
import (
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
// NewRouter builds a chi router with ClientIPFromXFF middleware.
// Passing no trusted prefixes causes ClientIPFromXFF to extract the rightmost
// hop rather than the leftmost originating IP, and leaves RemoteAddr unmodified.
func NewRouter(trustedPrefixes ...string) http.Handler {
r := chi.NewRouter()
r.Use(middleware.ClientIPFromXFF(trustedPrefixes...))
r.Get("/ip", func(w http.ResponseWriter, req *http.Request) {
ip := middleware.GetClientIP(req.Context())
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(ip))
})
return r
}
package clientip_test
import (
"net/http"
"net/http/httptest"
"net/netip"
"testing"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
func TestClientIPFromXFF_DefaultBehavior(t *testing.T) {
// Router configured with ClientIPFromXFF() using default unset trusted prefixes.
r := chi.NewRouter()
r.Use(middleware.ClientIPFromXFF()) // zero trusted prefixes passed
var observedIP string
var observedRemoteAddr string
var observedAddr netip.Addr
r.Get("/ip", func(w http.ResponseWriter, req *http.Request) {
observedIP = middleware.GetClientIP(req.Context())
observedAddr = middleware.GetClientIPAddr(req.Context())
observedRemoteAddr = req.RemoteAddr
w.WriteHeader(http.StatusOK)
})
// 203.0.113.195 is the client, 198.51.100.10 is intermediate proxy, 198.51.100.20 is the edge proxy hop.
req := httptest.NewRequest(http.MethodGet, "/ip", nil)
req.RemoteAddr = "192.0.2.1:1234"
req.Header.Set("X-Forwarded-For", "203.0.113.195, 198.51.100.10, 198.51.100.20")
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
// Contradicts naive expectation: ClientIPFromXFF() without arguments does NOT return
// the leftmost client IP (203.0.113.195). It returns the rightmost hop (198.51.100.20).
if observedIP != "198.51.100.20" {
t.Fatalf("expected rightmost XFF hop 198.51.100.20 with unset prefixes, got %q", observedIP)
}
if !observedAddr.IsValid() || observedAddr.String() != "198.51.100.20" {
t.Fatalf("expected valid netip.Addr for 198.51.100.20, got %v", observedAddr)
}
// RemoteAddr remains unmodified (unlike deprecated middleware.RealIP).
if observedRemoteAddr != "192.0.2.1:1234" {
t.Fatalf("expected RemoteAddr to remain unmodified as 192.0.2.1:1234, got %q", observedRemoteAddr)
}
}
func TestClientIPFromXFF_ConfiguredTrustedPrefixes(t *testing.T) {
// When trusted proxy CIDRs are provided, ClientIPFromXFF walks right-to-left,
// skips all trusted hops, and extracts the first untrusted IP (the originating client).
r := chi.NewRouter()
r.Use(middleware.ClientIPFromXFF("198.51.100.0/24"))
var observedIP string
r.Get("/ip", func(w http.ResponseWriter, req *http.Request) {
observedIP = middleware.GetClientIP(req.Context())
w.WriteHeader(http.StatusOK)
})
req := httptest.NewRequest(http.MethodGet, "/ip", nil)
req.Header.Set("X-Forwarded-For", "203.0.113.195, 198.51.100.10, 198.51.100.20")
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
if observedIP != "203.0.113.195" {
t.Fatalf("expected originating client 203.0.113.195 when proxy range is trusted, got %q", observedIP)
}
}
func TestClientIPFromXFF_FailClosedOnInvalidHop(t *testing.T) {
// If any hop encountered during the right-to-left walk is unparseable,
// ClientIPFromXFF fails closed and sets no client IP (returns "" / invalid netip.Addr).
r := chi.NewRouter()
r.Use(middleware.ClientIPFromXFF("198.51.100.0/24"))
var observedIP string
var observedAddr netip.Addr
r.Get("/ip", func(w http.ResponseWriter, req *http.Request) {
observedIP = middleware.GetClientIP(req.Context())
observedAddr = middleware.GetClientIPAddr(req.Context())
w.WriteHeader(http.StatusOK)
})
req := httptest.NewRequest(http.MethodGet, "/ip", nil)
req.Header.Set("X-Forwarded-For", "203.0.113.195, bad-proxy-token")
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
if observedIP != "" {
t.Fatalf("expected fail-closed empty IP on invalid hop, got %q", observedIP)
}
if observedAddr.IsValid() {
t.Fatalf("expected invalid netip.Addr on invalid hop, got %v", observedAddr)
}
}
func TestClientIPFromXFF_MultipleHeadersMergedRightToLeft(t *testing.T) {
// Multiple X-Forwarded-For headers are merged in order of arrival and walked right-to-left.
r := chi.NewRouter()
r.Use(middleware.ClientIPFromXFF("198.51.100.0/24"))
var observedIP string
r.Get("/ip", func(w http.ResponseWriter, req *http.Request) {
observedIP = middleware.GetClientIP(req.Context())
w.WriteHeader(http.StatusOK)
})
req := httptest.NewRequest(http.MethodGet, "/ip", nil)
req.Header.Add("X-Forwarded-For", "203.0.113.195")
req.Header.Add("X-Forwarded-For", "198.51.100.10, 198.51.100.20")
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
if observedIP != "203.0.113.195" {
t.Fatalf("expected merged multi-header extraction to yield 203.0.113.195, got %q", observedIP)
}
}
{"case":{"believed":"Calling ClientIPFromXFF with no arguments extracts the originating client IP from the leftmost entry in X-Forwarded-For and updates RemoteAddr like RealIP.","caseId":"case:sha256:b7c17f49f0a73fcdc197b26e3a710c2758fdc9e6f85ac548e24b770cd24ce049","contract":["assert ClientIPFromXFF with unset trusted prefixes returns the rightmost XFF hop rather than the leftmost client IP","assert ClientIPFromXFF leaves RemoteAddr unmodified and stores the resolved IP in context","assert ClientIPFromXFF with explicit trusted CIDR prefixes skips trusted hops to extract the originating client IP","assert ClientIPFromXFF fails closed returning an empty IP when encountering an invalid hop in the chain","assert ClientIPFromXFF merges multiple X-Forwarded-For headers and evaluates hops right to left"],"goal":"Extract client IP from X-Forwarded-For with go-chi middleware without assuming unconfigured trusted prefixes extract the leftmost IP or mutate RemoteAddr","kind":"HOW","packages":["pkg:golang/github.com/go-chi/chi/v5@5.3.1"],"schemaVersion":1,"symbols":["middleware.ClientIPFromXFF","middleware.GetClientIP","middleware.GetClientIPAddr"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"gomod","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/go-chi/chi/v5@5.3.1"],"schemaVersion":1,"symbols":["middleware.ClientIPFromXFF","middleware.GetClientIP","middleware.GetClientIPAddr"],"verifierAdapter":"golang@1"}
module example.com/gochi-clientip
go 1.23
require github.com/go-chi/chi/v5 v5.3.1
github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8=
github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=