Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion context.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 ""
}
Expand Down
16 changes: 16 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Loading