pkg/web: X-Forwarded-For multi-IP handling (#45098)

It is conventionally common for the X-Forwarded-For header to contain a
comma-separated list of IP addresses, with each intermediate proxy
adding an additional item as a request passes through it. This change
makes the web framework handle this case appropriately, always selecting
the first item in the list.
This commit is contained in:
sam boyer 2022-02-08 14:37:19 -05:00 committed by GitHub
parent 2cf421dfe3
commit 6a2255abe7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -77,13 +77,17 @@ func (ctx *Context) run() {
// RemoteAddr returns more real IP address. // RemoteAddr returns more real IP address.
func (ctx *Context) RemoteAddr() string { func (ctx *Context) RemoteAddr() string {
addr := ctx.Req.Header.Get("X-Real-IP") addr := ctx.Req.Header.Get("X-Real-IP")
if len(addr) == 0 { if len(addr) == 0 {
addr = ctx.Req.Header.Get("X-Forwarded-For") // X-Forwarded-For may contain multiple IP addresses, separated by
if addr == "" { // commas.
addr = ctx.Req.RemoteAddr addr = strings.TrimSpace(strings.Split(ctx.Req.Header.Get("X-Forwarded-For"), ",")[0])
if i := strings.LastIndex(addr, ":"); i > -1 { }
addr = addr[:i]
} if len(addr) == 0 {
addr = ctx.Req.RemoteAddr
if i := strings.LastIndex(addr, ":"); i > -1 {
addr = addr[:i]
} }
} }
return addr return addr