Skip to content

Commit

Permalink
add net.ParseIP() as validation to RealIP middleware (#665)
Browse files Browse the repository at this point in the history
  • Loading branch information
mrpalide committed Jan 3, 2022
1 parent ba10645 commit 06573a6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
5 changes: 4 additions & 1 deletion middleware/realip.go
Expand Up @@ -4,6 +4,7 @@ package middleware
// https://github.com/zenazn/goji/tree/master/web/middleware

import (
"net"
"net/http"
"strings"
)
Expand Down Expand Up @@ -52,6 +53,8 @@ func realIP(r *http.Request) string {
}
ip = xff[:i]
}

if net.ParseIP(ip) == nil {
return ""
}
return ip
}
24 changes: 24 additions & 0 deletions middleware/realip_test.go
Expand Up @@ -89,3 +89,27 @@ func TestXForwardForXRealIPPrecedence(t *testing.T) {
t.Fatal("Test get real IP precedence error.")
}
}

func TestIvalidIP(t *testing.T) {
req, _ := http.NewRequest("GET", "/", nil)
req.Header.Add("X-Real-IP", "100.100.100.1000")
w := httptest.NewRecorder()

r := chi.NewRouter()
r.Use(RealIP)

realIP := ""
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
realIP = r.RemoteAddr
w.Write([]byte("Hello World"))
})
r.ServeHTTP(w, req)

if w.Code != 200 {
t.Fatal("Response Code should be 200")
}

if realIP != "" {
t.Fatal("Invalid IP used.")
}
}

0 comments on commit 06573a6

Please sign in to comment.