From df800e6686c43926b0498212ed24afaffa4d213b Mon Sep 17 00:00:00 2001 From: b84330808 Date: Wed, 4 Nov 2026 22:37:00 +0900 Subject: [PATCH] fix(context): handle zoned IPv6 RemoteAddr in ClientIP A client connecting over a link-local IPv6 address gets a RemoteAddr such as "[fe80::1%eth0]:1234". RemoteIP keeps the zone and net.ParseIP rejects it, so ClientIP returned an empty string and never looked at the forwarding headers. Drop the zone before parsing. --- context.go | 5 ++++- context_test.go | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index 582d00f2..9bd8bdd2 100644 --- a/context.go +++ b/context.go @@ -1026,7 +1026,10 @@ func (c *Context) ClientIP() string { // It also checks if the remoteIP is a trusted proxy or not. // In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks // defined by Engine.SetTrustedProxies() - remoteIP = net.ParseIP(c.RemoteIP()) + // net.ParseIP rejects IPv6 zones, so drop the zone of a link-local + // address such as "fe80::1%eth0" first. + ip, _, _ := strings.Cut(c.RemoteIP(), "%") + remoteIP = net.ParseIP(ip) if remoteIP == nil { return "" } diff --git a/context_test.go b/context_test.go index b82e04d5..ad8bacd1 100644 --- a/context_test.go +++ b/context_test.go @@ -1304,6 +1304,22 @@ func TestContextClientIPWithSingleHeader(t *testing.T) { assert.Equal(t, "1.2.3.4", c.ClientIP()) } +func TestContextClientIPWithZonedIPv6RemoteAddr(t *testing.T) { + c, _ := CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodGet, "/test", nil) + c.Request.Header.Set("X-Forwarded-For", "1.2.3.4") + // A client connecting over a link-local IPv6 address gets a zone in RemoteAddr. + c.Request.RemoteAddr = "[fe80::1%eth0]:1234" + + c.engine.ForwardedByClientIP = true + c.engine.RemoteIPHeaders = []string{"X-Forwarded-For"} + _ = c.engine.SetTrustedProxies([]string{"fe80::/10"}) + assert.Equal(t, "1.2.3.4", c.ClientIP()) + + _ = c.engine.SetTrustedProxies(nil) + assert.Equal(t, "fe80::1", c.ClientIP()) +} + // Tests that the response is serialized as Secure JSON // and Content-Type is set to application/json func TestContextRenderSecureJSON(t *testing.T) {