CodeSampleX

示例

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

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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

契约

  1. assert ClientIPFromXFF with unset trusted prefixes returns the rightmost XFF hop rather than the leftmost client IP
  2. assert ClientIPFromXFF leaves RemoteAddr unmodified and stores the resolved IP in context
  3. assert ClientIPFromXFF with explicit trusted CIDR prefixes skips trusted hops to extract the originating client IP
  4. assert ClientIPFromXFF fails closed returning an empty IP when encountering an invalid hop in the chain
  5. 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

下载源代码构件 (tar.gz)

源代码

NOTES.md
# 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.
clientip.go
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
}
clientip_test.go
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)
	}
}
csx.json
{"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"}
go.mod
module example.com/gochi-clientip

go 1.23

require github.com/go-chi/chi/v5 v5.3.1
go.sum
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=

原始种子者

csx-seed