package platform import ( "log/slog" "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" ) func TestClientIPIgnoresForwardedForUnlessTrusted(t *testing.T) { ip := func(r *gin.Engine) string { r.GET("/ip", func(c *gin.Context) { c.String(http.StatusOK, c.ClientIP()) }) req := httptest.NewRequest(http.MethodGet, "/ip", nil) req.RemoteAddr = "192.0.2.10:4000" req.Header.Set("X-Forwarded-For", "203.0.113.9") w := httptest.NewRecorder() r.ServeHTTP(w, req) return w.Body.String() } if got := ip(NewRouter(slog.New(slog.DiscardHandler))); got != "192.0.2.10" { t.Errorf("ClientIP() without trusted proxies = %s, want the peer address", got) } r := NewRouter(slog.New(slog.DiscardHandler)) if err := TrustProxies(r, []string{"192.0.2.0/24"}); err != nil { t.Fatal(err) } if got := ip(r); got != "203.0.113.9" { t.Errorf("ClientIP() behind a trusted proxy = %s, want the forwarded address", got) } }