샘플
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
검증된 샘플 — golang 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…
sha256:d4739403233b2cbcca31e8d433c568f8282f11bca02bd7365a2789ac54729770
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 3
- 빌드한 서명 키
- 3
선언된 환경
go linux x64 go go gomod
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| 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 |
케이스
HOW- 목표
- Extract client IP from X-Forwarded-For with go-chi middleware without assuming unconfigured trusted prefixes extract the leftmost IP or mutate RemoteAddr
- 심벌
-
- middleware.ClientIPFromXFF
- middleware.GetClientIP
- middleware.GetClientIPAddr
- 환경
- go
- 생성일
- 2026-08-16T13:25:20Z
컨트랙트
- 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
파일
- NOTES.md
- clientip.go
- clientip_test.go
- csx.json
- go.mod
- go.sum
소스
# 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=