Skip to content

Commit

Permalink
Ensure ClientURL() properly formats IPv6 literal addresses (#5725)
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
derekcollison authored Jul 31, 2024
2 parents 548544b + d047685 commit 32ba330
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
9 changes: 6 additions & 3 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"math/rand"
"net"
"net/http"
"net/url"
"regexp"
"runtime/pprof"

Expand Down Expand Up @@ -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 {
Expand Down
15 changes: 15 additions & 0 deletions server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit 32ba330

Please sign in to comment.