fix(package): [netutil] skip invalid forwarded IP values (#397)

This commit is contained in:
Yusuf Efe authored and GitHub committed 2026-10-22 10:29:35 +08:00
1 parent 19ccb13893
commit 9a8b67ac85
2 files changed
+24 -2

No files matched your search

+2 -2
View File
@@ -70,12 +70,12 @@ func GetInternalIp() string {
func GetRequestPublicIp(req *http.Request) string { func GetRequestPublicIp(req *http.Request) string {
var ip string var ip string
for _, ip = range strings.Split(req.Header.Get("X-Forwarded-For"), ",") { for _, ip = range strings.Split(req.Header.Get("X-Forwarded-For"), ",") {
if ip = strings.TrimSpace(ip); ip != "" && !IsInternalIP(net.ParseIP(ip)) { if ip = strings.TrimSpace(ip); net.ParseIP(ip) != nil && !IsInternalIP(net.ParseIP(ip)) {
return ip return ip
} }
} }
if ip = strings.TrimSpace(req.Header.Get("X-Real-Ip")); ip != "" && !IsInternalIP(net.ParseIP(ip)) { if ip = strings.TrimSpace(req.Header.Get("X-Real-Ip")); net.ParseIP(ip) != nil && !IsInternalIP(net.ParseIP(ip)) {
return ip return ip
} }
+22
View File
@@ -0,0 +1,22 @@
package netutil
import (
"net/http/httptest"
"testing"
)
func TestGetRequestPublicIpInvalidHeaders(t *testing.T) {
for _, test := range []struct{ forwarded, real, want string }{
{"unknown, 8.8.8.8", "", "8.8.8.8"},
{"unknown", "invalid", "1.1.1.1"},
{"10.0.0.1", "8.8.4.4", "8.8.4.4"},
} {
req := httptest.NewRequest("GET", "http://example.com", nil)
req.RemoteAddr = "1.1.1.1:1234"
req.Header.Set("X-Forwarded-For", test.forwarded)
req.Header.Set("X-Real-Ip", test.real)
if got := GetRequestPublicIp(req); got != test.want {
t.Errorf("got %q, want %q", got, test.want)
}
}
}