Skip to content

Commit 2360b52

Browse files
starszjohzchen
authored andcommitted
fix: use remote address instead of client ip (#1831)
1 parent 73b5cfd commit 2360b52

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

api/internal/filter/ip_filter.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ package filter
1919
import (
2020
"net"
2121
"net/http"
22+
"strings"
2223

2324
"github.com/gin-gonic/gin"
2425

@@ -81,7 +82,10 @@ func checkIP(ipStr string, ips map[string]bool, subnets []*subnet) bool {
8182
func IPFilter() gin.HandlerFunc {
8283
ips, subnets := generateIPSet(conf.AllowList)
8384
return func(c *gin.Context) {
84-
ipStr := c.ClientIP()
85+
var ipStr string
86+
if ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)); err == nil {
87+
ipStr = ip
88+
}
8589

8690
if len(conf.AllowList) < 1 {
8791
c.Next()

api/internal/filter/ip_filter_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package filter
1818

1919
import (
20+
"net/http/httptest"
2021
"testing"
2122

2223
"github.com/gin-gonic/gin"
@@ -55,4 +56,22 @@ func TestIPFilter_Handle(t *testing.T) {
5556
})
5657
w = performRequest(r, "GET", "/test")
5758
assert.Equal(t, 200, w.Code)
59+
60+
// should forbidden
61+
conf.AllowList = []string{"127.0.0.1"}
62+
r = gin.New()
63+
r.Use(IPFilter())
64+
r.GET("/test", func(c *gin.Context) {})
65+
66+
req := httptest.NewRequest("GET", "/test", nil)
67+
req.Header.Set("X-Forwarded-For", "127.0.0.1")
68+
w = httptest.NewRecorder()
69+
r.ServeHTTP(w, req)
70+
assert.Equal(t, 403, w.Code)
71+
72+
req = httptest.NewRequest("GET", "/test", nil)
73+
req.Header.Set("X-Real-Ip", "127.0.0.1")
74+
w = httptest.NewRecorder()
75+
r.ServeHTTP(w, req)
76+
assert.Equal(t, 403, w.Code)
5877
}

0 commit comments

Comments
 (0)