From 3019995a6f2527a4154f78738c1155f8db274fd3 Mon Sep 17 00:00:00 2001 From: armadi1809 <46684200+armadi1809@users.noreply.github.com> Date: Sun, 15 Oct 2023 17:43:07 -0500 Subject: [PATCH] Fix geo details for viewers not showing on CDN connection (#3359) * Added extraction of first IP address from X-FORWARDED-FOR header * Added tests to the GetIPAddressFromRequest util method --------- Co-authored-by: Aziz Rmadi --- utils/clientId.go | 9 ++++++++- utils/clientId_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 utils/clientId_test.go diff --git a/utils/clientId.go b/utils/clientId.go index e40b0d104..38188bcdc 100644 --- a/utils/clientId.go +++ b/utils/clientId.go @@ -5,6 +5,7 @@ import ( "encoding/hex" "net" "net/http" + "strings" log "github.com/sirupsen/logrus" ) @@ -24,7 +25,13 @@ func GetIPAddressFromRequest(req *http.Request) string { ipAddressString := req.RemoteAddr xForwardedFor := req.Header.Get("X-FORWARDED-FOR") if xForwardedFor != "" { - return xForwardedFor + clientIpString := strings.Split(xForwardedFor, ", ")[0] + ip, _, err := net.SplitHostPort(clientIpString) + if err != nil { + log.Errorln(err) + return "" + } + return ip } ip, _, err := net.SplitHostPort(ipAddressString) diff --git a/utils/clientId_test.go b/utils/clientId_test.go new file mode 100644 index 000000000..9af802828 --- /dev/null +++ b/utils/clientId_test.go @@ -0,0 +1,27 @@ +package utils + +import ( + "net/http/httptest" + "testing" +) + +func TestGetIPAddressFromRequest(t *testing.T) { + + expectedResult := "203.0.113.195" + + request := httptest.NewRequest("GET", "/", nil) + request.RemoteAddr = "203.0.113.195:41237" + //First Test without X-FORWARDED-FOR header + result := GetIPAddressFromRequest(request) + if result != expectedResult { + t.Errorf("Remote address only test failed: Expected %s, got %s", expectedResult, result) + } + + //Test with X-FORWARDED-FOR header + request.Header.Set("X-FORWARDED-FOR header", "203.0.113.195:41237, 198.51.100.100:38523, 140.248.67.176:12345") + result = GetIPAddressFromRequest(request) + if result != expectedResult { + t.Errorf("X-FORWARD-FOR header test failed: Expected %s, got %s", expectedResult, result) + } + +}