Skip to content

Commit

Permalink
fix: use remote_addr instead of client ip
Browse files Browse the repository at this point in the history
  • Loading branch information
starsz committed Apr 27, 2021
1 parent 2f3717f commit 99fca5e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
6 changes: 5 additions & 1 deletion api/internal/filter/ip_filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package filter
import (
"net"
"net/http"
"strings"

"github.com/gin-gonic/gin"

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

if len(conf.AllowList) < 1 {
c.Next()
Expand Down
19 changes: 19 additions & 0 deletions api/internal/filter/ip_filter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package filter

import (
"net/http/httptest"
"testing"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -55,4 +56,22 @@ func TestIPFilter_Handle(t *testing.T) {
})
w = performRequest(r, "GET", "/test")
assert.Equal(t, 200, w.Code)

// should forbidden
conf.AllowList = []string{"8.8.8.8"}
r = gin.New()
r.Use(IPFilter())
r.GET("/test", func(c *gin.Context) {})

req := httptest.NewRequest("GET", "/test", nil)
req.Header.Set("X-Forwarded-For", "8.8.8.8")
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, 403, w.Code)

req = httptest.NewRequest("GET", "/test", nil)
req.Header.Set("X-Real-Ip", "8.8.8.8")
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, 403, w.Code)
}

0 comments on commit 99fca5e

Please sign in to comment.