From 8d6eacc2451a3c515ef9519928540f7ac656cba1 Mon Sep 17 00:00:00 2001 From: Ivan Kozlovic Date: Mon, 3 Jan 2022 11:51:35 -0700 Subject: [PATCH] Add X-Forwarded-For IP to the client's remote address Instead of replacing connection's host with value specified by this header, we will simply add the address to the logging only. So instead of having something like: ``` 192.168.1.1:5678 - wid:10 - Client connection created ``` we could have: ``` 1.2.3.4/192.168.1.1:5678 - wid:10 - Client connection created ``` As seen above, this PR simply prefixes the connection's remote address with the header's value (if a valid IP). Related to #2734 Resolves #2767 Signed-off-by: Ivan Kozlovic --- server/client.go | 13 ++++++++----- server/websocket_test.go | 8 ++++---- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/server/client.go b/server/client.go index 1d889fad..9670fd58 100644 --- a/server/client.go +++ b/server/client.go @@ -610,12 +610,15 @@ func (c *client) initClient() { if conn = addr.String(); conn != _EMPTY_ { host, port, _ := net.SplitHostPort(conn) iPort, _ := strconv.Atoi(port) - c.port = uint16(iPort) + c.host, c.port = host, uint16(iPort) if c.isWebsocket() && c.ws.clientIP != _EMPTY_ { - c.host = c.ws.clientIP - conn = net.JoinHostPort(c.host, port) - } else { - c.host = host + cip := c.ws.clientIP + // Surround IPv6 addresses with square brackets, as + // net.JoinHostPort would do... + if strings.Contains(cip, ":") { + cip = "[" + cip + "]" + } + conn = fmt.Sprintf("%s/%s", cip, conn) } // Now that we have extracted host and port, escape // the string because it is going to be used in Sprintf diff --git a/server/websocket_test.go b/server/websocket_test.go index 600f7de6..f3ea54e0 100644 --- a/server/websocket_test.go +++ b/server/websocket_test.go @@ -3989,12 +3989,12 @@ func TestWSXForwardedFor(t *testing.T) { } select { case d := <-l.ch: - ipAndColumn := fmt.Sprintf("%s:", test.expectedValue) + ipAndSlash := fmt.Sprintf("%s/", test.expectedValue) if test.useHdrValue { - if !strings.HasPrefix(d, ipAndColumn) { - t.Fatalf("Expected debug statement to start with: %q, got %q", ipAndColumn, d) + if !strings.HasPrefix(d, ipAndSlash) { + t.Fatalf("Expected debug statement to start with: %q, got %q", ipAndSlash, d) } - } else if strings.HasPrefix(d, ipAndColumn) { + } else if strings.HasPrefix(d, ipAndSlash) { t.Fatalf("Unexpected debug statement: %q", d) } case <-time.After(time.Second):