Skip to content

Commit

Permalink
Merge 5c52a25 into f146898
Browse files Browse the repository at this point in the history
  • Loading branch information
starsz authored Apr 30, 2021
2 parents f146898 + 5c52a25 commit 5e04afc
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{"127.0.0.1"}
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", "127.0.0.1")
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", "127.0.0.1")
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, 403, w.Code)
}

0 comments on commit 5e04afc

Please sign in to comment.