From e14238224d4f6f2512e99150fb9a4514c79754fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveirinha?= Date: Fri, 28 Oct 2022 10:33:23 +0100 Subject: [PATCH] TUN-6898: Fix bug handling IPv6 based ingresses with missing port --- ingress/origin_service.go | 10 +++++++++- ingress/origin_service_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 ingress/origin_service_test.go diff --git a/ingress/origin_service.go b/ingress/origin_service.go index b45ec6a2..5aaa26be 100644 --- a/ingress/origin_service.go +++ b/ingress/origin_service.go @@ -9,6 +9,7 @@ import ( "net" "net/http" "net/url" + "strings" "time" "github.com/pkg/errors" @@ -155,8 +156,15 @@ func newSocksProxyOverWSService(accessPolicy *ipaccess.Policy) *socksProxyOverWS } func addPortIfMissing(uri *url.URL, port int) { + hostname := uri.Hostname() + + // check if it is an IPv6 address and wrap it with brackets + if ip := net.ParseIP(hostname); ip != nil && strings.Count(hostname, ":") > 0 { + hostname = fmt.Sprintf("[%s]", hostname) + } + if uri.Port() == "" { - uri.Host = fmt.Sprintf("%s:%d", uri.Hostname(), port) + uri.Host = fmt.Sprintf("%s:%d", hostname, port) } } diff --git a/ingress/origin_service_test.go b/ingress/origin_service_test.go new file mode 100644 index 00000000..081b08ae --- /dev/null +++ b/ingress/origin_service_test.go @@ -0,0 +1,29 @@ +package ingress + +import ( + "net/url" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestAddPortIfMissing(t *testing.T) { + testCases := []struct { + input string + expected string + }{ + {"ssh://[::1]", "[::1]:22"}, + {"ssh://[::1]:38", "[::1]:38"}, + {"ssh://abc:38", "abc:38"}, + {"ssh://127.0.0.1:38", "127.0.0.1:38"}, + {"ssh://127.0.0.1", "127.0.0.1:22"}, + } + + for _, tc := range testCases { + t.Run(tc.input, func(t *testing.T) { + url1, _ := url.Parse(tc.input) + addPortIfMissing(url1, 22) + require.Equal(t, tc.expected, url1.Host) + }) + } +}