Skip to content

Commit

Permalink
Add UserJWTAndSeed helper function
Browse files Browse the repository at this point in the history
The motivation for this is to support situations when
the JWT and seed are passed as environment variables or
other means that don't rely on a file.

Signed-off-by: Byron Ruth <b@devel.io>
  • Loading branch information
bruth committed Aug 12, 2022
1 parent fb5ca2c commit 893829b
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
22 changes: 22 additions & 0 deletions nats.go
Original file line number Diff line number Diff line change
Expand Up @@ -1083,6 +1083,28 @@ func UserCredentials(userOrChainedFile string, seedFiles ...string) Option {
return UserJWT(userCB, sigCB)
}

// UserJWTAndSeed is a convenience function that takes the JWT and seed
// values as strings.
func UserJWTAndSeed(jwt string, seed string) Option {
userCB := func() (string, error) {
return jwt, nil
}

sigCB := func(nonce []byte) ([]byte, error) {
kp, err := nkeys.FromSeed([]byte(seed))
if err != nil {
return nil, fmt.Errorf("unable to extract key pair from seed: %v", err)
}
// Wipe our key on exit.
defer kp.Wipe()

sig, _ := kp.Sign(nonce)
return sig, nil
}

return UserJWT(userCB, sigCB)
}

// UserJWT will set the callbacks to retrieve the user's JWT and
// the signature callback to sign the server nonce. This an the Nkey
// option are mutually exclusive.
Expand Down
15 changes: 15 additions & 0 deletions nats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1576,6 +1576,21 @@ func TestUserCredentialsChainedFile(t *testing.T) {
}
}

func TestUserJWTAndSeed(t *testing.T) {
if server.VERSION[0] == '1' {
t.Skip()
}
ts := runTrustServer()
defer ts.Shutdown()

url := fmt.Sprintf("nats://127.0.0.1:%d", TEST_PORT)
nc, err := Connect(url, UserJWTAndSeed(uJWT, string(uSeed)))
if err != nil {
t.Fatalf("Expected to connect, got %v", err)
}
nc.Close()
}

func TestExpiredAuthentication(t *testing.T) {
// The goal of these tests was to check how a client with an expiring JWT
// behaves. It should receive an async -ERR indicating that the auth
Expand Down

0 comments on commit 893829b

Please sign in to comment.