Skip to content

Commit

Permalink
Merge pull request #837 from ripienaar/832_remoteaddress_auth
Browse files Browse the repository at this point in the history
[ADDED] RemoteAddress() to the CustomClientAuthentication interface
  • Loading branch information
derekcollison committed Dec 6, 2018
2 parents 0bb8562 + 08eafd8 commit 519d365
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
3 changes: 3 additions & 0 deletions server/auth.go
Expand Up @@ -16,6 +16,7 @@ package server
import (
"crypto/tls"
"encoding/base64"
"net"
"strings"

"github.com/nats-io/jwt"
Expand All @@ -37,6 +38,8 @@ type ClientAuthentication interface {
GetTLSConnectionState() *tls.ConnectionState
// Optionally map a user after auth.
RegisterUser(*User)
// RemoteAddress expose the connection information of the client
RemoteAddress() net.Addr
}

// NkeyUser is for multiple nkey based users
Expand Down
13 changes: 13 additions & 0 deletions server/client.go
Expand Up @@ -390,6 +390,19 @@ func (c *client) initClient() {
}
}

// RemoteAddress expose the Address of the client connection,
// nil when not connected or unknown
func (c *client) RemoteAddress() net.Addr {
c.mu.Lock()
defer c.mu.Unlock()

if c.nc == nil {
return nil
}

return c.nc.RemoteAddr()
}

// Helper function to report errors.
func (c *client) reportErrRegisterAccount(acc *Account, err error) {
if err == ErrTooManyAccountConnections {
Expand Down
31 changes: 31 additions & 0 deletions server/client_test.go
Expand Up @@ -260,6 +260,26 @@ func TestClientConnectProto(t *testing.T) {
wg.Wait()
}

func TestRemoteAddress(t *testing.T) {
c := &client{}

// though in reality this will panic if it does not, adding coverage anyway
if c.RemoteAddress() != nil {
t.Errorf("RemoteAddress() did not handle nil connection correctly")
}

_, c, _ = setupClient()
addr := c.RemoteAddress()

if addr.Network() != "pipe" {
t.Errorf("RemoteAddress() returned invalid network: %s", addr.Network())
}

if addr.String() != "pipe" {
t.Errorf("RemoteAddress() returned invalid string: %s", addr.String())
}
}

func TestClientPing(t *testing.T) {
_, c, cr := setupClient()

Expand Down Expand Up @@ -841,6 +861,17 @@ func TestTLSCloseClientConnection(t *testing.T) {
if state == nil {
t.Error("GetTLSConnectionState() returned nil")
}

// Test RemoteAddress
addr := cli.RemoteAddress()
if addr == nil {
t.Error("RemoteAddress() returned nil")
}

if addr.(*net.TCPAddr).IP.String() != "127.0.0.1" {
t.Error("RemoteAddress() returned incorrect ip " + addr.String())
}

// Fill the buffer. Need to send 1 byte at a time so that we timeout here
// the nc.Close() would block due to a write that can not complete.
done := false
Expand Down

0 comments on commit 519d365

Please sign in to comment.