From d047685b52b540069a4b63875a25bf67a5020e84 Mon Sep 17 00:00:00 2001 From: Neil Twigg Date: Wed, 31 Jul 2024 13:20:01 +0100 Subject: [PATCH] Ensure `ClientURL()` properly formats IPv6 literal addresses Using `net.JoinHostPort()` properly surrounds IPv6 literals with square brackets. Using `url.URL` ensures that hostnames will be properly encoded. Signed-off-by: Neil Twigg --- server/server.go | 9 ++++++--- server/server_test.go | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/server/server.go b/server/server.go index 6d8a60648a6..7c37d38b757 100644 --- a/server/server.go +++ b/server/server.go @@ -27,6 +27,7 @@ import ( "math/rand" "net" "net/http" + "net/url" "regexp" "runtime/pprof" @@ -997,11 +998,13 @@ func (s *Server) serverName() string { func (s *Server) ClientURL() string { // FIXME(dlc) - should we add in user and pass if defined single? opts := s.getOpts() - scheme := "nats://" + var u url.URL + u.Scheme = "nats" if opts.TLSConfig != nil { - scheme = "tls://" + u.Scheme = "tls" } - return fmt.Sprintf("%s%s:%d", scheme, opts.Host, opts.Port) + u.Host = net.JoinHostPort(opts.Host, fmt.Sprintf("%d", opts.Port)) + return u.String() } func validateCluster(o *Options) error { diff --git a/server/server_test.go b/server/server_test.go index 45ea9f93557..784c3d00935 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -2200,3 +2200,18 @@ func TestServerClusterAndGatewayNameNoSpace(t *testing.T) { _, err = NewServer(o) require_Error(t, err, ErrGatewayNameHasSpaces) } + +func TestServerClientURL(t *testing.T) { + for host, expected := range map[string]string{ + "host.com": "nats://host.com:12345", + "1.2.3.4": "nats://1.2.3.4:12345", + "2000::1": "nats://[2000::1]:12345", + } { + o := DefaultOptions() + o.Host = host + o.Port = 12345 + s, err := NewServer(o) + require_NoError(t, err) + require_Equal(t, s.ClientURL(), expected) + } +}