Compare commits

...

5 Commits

Author SHA1 Message Date
Shirshendu Bhowmick
55382278e7
Merge 16857146c8961f809f1a6735e84556d5835eaec9 into 5f4f9643258dc2a65e684b63f12c8d543c936c67 2026-05-09 13:45:55 +05:30
Shirshendu Bhowmick
16857146c8
refactor(engine): streamline CIDR preparation for trusted proxies 2026-05-09 13:45:38 +05:30
Shirshendu Bhowmick
334dbdb8ac
test(context): add test for ClientIP method with no valid forwarded headers 2026-05-09 13:44:33 +05:30
Shirshendu Bhowmick
9ef3ade402
fix(context): return empty string for invalid remote IP in ClientIP method
fix(gin): unmap address before checking if it is IPv4 in prepareTrustedCIDRs
2026-05-09 13:38:45 +05:30
Shirshendu Bhowmick
6f54838d7f
fix(engine): improve error handling for invalid trusted proxy CIDR 2026-05-09 13:33:50 +05:30
3 changed files with 15 additions and 4 deletions

View File

@ -1022,6 +1022,9 @@ func (c *Context) ClientIP() string {
}
}
}
if !remoteIP.IsValid() {
return ""
}
return remoteIP.String()
}

View File

@ -1984,6 +1984,12 @@ func TestContextClientIP(t *testing.T) {
c.Request.RemoteAddr = addr.String()
assert.Equal(t, "20.20.20.20", c.ClientIP())
// unix address with no valid forwarded header: remoteIP stays zero, must return ""
c.Request.Header.Del("X-Forwarded-For")
c.Request.Header.Del("X-Real-IP")
assert.Empty(t, c.ClientIP())
resetContextForClientIPTests(c)
// reset
c.Request = c.Request.WithContext(context.Background())
resetContextForClientIPTests(c)

10
gin.go
View File

@ -418,15 +418,17 @@ func (engine *Engine) prepareTrustedCIDRs() ([]netip.Prefix, error) {
if err != nil {
return cidrs, &net.ParseError{Type: "IP address", Text: trustedProxy}
}
addr = addr.Unmap()
bits := 128
if addr.Is4() {
trustedProxy += "/32"
} else {
trustedProxy += "/128"
bits = 32
}
cidrs = append(cidrs, netip.PrefixFrom(addr, bits))
continue
}
prefix, err := netip.ParsePrefix(trustedProxy)
if err != nil {
return cidrs, err
return cidrs, &net.ParseError{Type: "CIDR address", Text: trustedProxy}
}
cidrs = append(cidrs, prefix.Masked())
}