Skip to content

Commit 1403cc8

Browse files
authored
Merge pull request #4260 from gofiber/fix-x-real-ip-header-handling-in-balancerforward
2 parents 40c0a52 + 907306a commit 1403cc8

3 files changed

Lines changed: 28 additions & 2 deletions

File tree

docs/middleware/proxy.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ app.Use(proxy.Balancer(proxy.Config{
126126
"http://localhost:3003",
127127
},
128128
ModifyRequest: func(c fiber.Ctx) error {
129-
c.Request().Header.Add("X-Real-IP", c.IP())
129+
c.Request().Header.Set("X-Real-IP", c.IP())
130130
return nil
131131
},
132132
ModifyResponse: func(c fiber.Ctx) error {

middleware/proxy/proxy.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -279,7 +279,7 @@ func BalancerForward(servers []string, clients ...*fasthttp.Client) fiber.Handle
279279
if !strings.HasPrefix(server, "http") {
280280
server = "http://" + server
281281
}
282-
c.Request().Header.Add("X-Real-IP", c.IP())
282+
c.Request().Header.Set("X-Real-IP", c.IP())
283283
return Do(c, server+c.OriginalURL(), clients...)
284284
}
285285
}

middleware/proxy/proxy_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -985,6 +985,32 @@ func Test_Proxy_Balancer_Forward_Local(t *testing.T) {
985985
require.Equal(t, "forwarded", string(b))
986986
}
987987

988+
func Test_Proxy_Balancer_Forward_OverwritesXRealIP(t *testing.T) {
989+
t.Parallel()
990+
991+
const (
992+
spoofedIP = "10.0.0.1"
993+
appTestClientIP = "0.0.0.0"
994+
)
995+
996+
_, addr := createProxyTestServerIPv4(t, func(c fiber.Ctx) error {
997+
value := c.Get("X-Real-IP")
998+
require.Equal(t, appTestClientIP, value)
999+
require.NotEqual(t, spoofedIP, value)
1000+
return c.SendStatus(fiber.StatusOK)
1001+
})
1002+
1003+
app := fiber.New()
1004+
app.Use(BalancerForward([]string{addr}))
1005+
1006+
req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)
1007+
req.Header.Set("X-Real-IP", spoofedIP)
1008+
1009+
resp, err := app.Test(req)
1010+
require.NoError(t, err)
1011+
require.Equal(t, fiber.StatusOK, resp.StatusCode)
1012+
}
1013+
9881014
func Test_Proxy_Immutable(t *testing.T) {
9891015
t.Parallel()
9901016

0 commit comments

Comments
 (0)