mirror of
https://github.com/gin-gonic/gin.git
synced 2026-11-21 18:13:39 +08:00
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.
This commit is contained in:
parent
0f09c3a9b4
commit
df800e6686
@ -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 ""
|
||||
}
|
||||
|
||||
@ -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) {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user