From 9a8b67ac85c1cbe7d5eeae802fd87e45a4c5c1ad Mon Sep 17 00:00:00 2001 From: Yusuf Efe <120668197+yuefdev@users.noreply.github.com> Date: Thu, 22 Oct 2026 05:29:35 +0300 Subject: [PATCH] fix(package): [netutil] skip invalid forwarded IP values (#397) --- netutil/net.go | 4 ++-- netutil/request_ip_test.go | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 netutil/request_ip_test.go diff --git a/netutil/net.go b/netutil/net.go index baf9d3b..432744d 100644 --- a/netutil/net.go +++ b/netutil/net.go @@ -70,12 +70,12 @@ func GetInternalIp() string { func GetRequestPublicIp(req *http.Request) string { var ip string 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 } } - 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 } diff --git a/netutil/request_ip_test.go b/netutil/request_ip_test.go new file mode 100644 index 0000000..84a08ff --- /dev/null +++ b/netutil/request_ip_test.go @@ -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) + } + } +}