Browse Source

Fix port cutting, cover by tests

Volodymyr Tkach 2 years ago
parent
commit
31f210cddb
2 changed files with 26 additions and 2 deletions
  1. 6 2
      utils/http/helpers/helpers.go
  2. 20 0
      utils/http/helpers/helpers_test.go

+ 6 - 2
utils/http/helpers/helpers.go

@@ -65,8 +65,12 @@ func ClientIPs(r *http.Request) []string {
 	res := []string{}
 	ips := strings.Split(ra, ",")
 	for _, ip := range ips {
-		ipPort := strings.Split(ip, ":")
-		res = append(res, strings.Trim(ipPort[0], " "))
+		i := strings.LastIndex(ip, ":")
+		if i < 0 {
+			res = append(res, strings.Trim(ip, " "))
+		} else {
+			res = append(res, strings.Trim(string([]rune(ip)[:i]), " "))
+		}
 	}
 	return res
 }

+ 20 - 0
utils/http/helpers/helpers_test.go

@@ -91,6 +91,26 @@ var _ = Describe("helpers", func() {
 				"192.168.0.50", "192.168.0.1", "127.0.0.1",
 			))
 		})
+
+		It("return array of client IPs without port", func() {
+			Expect(helpers.ClientIPs(&http.Request{
+				RemoteAddr: "[::1]:544722",
+			})).To(ConsistOf(
+				"[::1]",
+			))
+
+			Expect(helpers.ClientIPs(&http.Request{
+				RemoteAddr: "127.0.0.1:8080",
+			})).To(ConsistOf(
+				"127.0.0.1",
+			))
+
+			Expect(helpers.ClientIPs(&http.Request{
+				RemoteAddr: "192.168.0.1:80,127.0.0.1:443",
+			})).To(ConsistOf(
+				"192.168.0.1", "127.0.0.1",
+			))
+		})
 	})
 
 	Context("Handles", func() {