github.com/trustbloc/kms-go@v1.1.2/wrapper/localsuite/creator_test.go (about)

     1  /*
     2  Copyright Gen Digital Inc. All Rights Reserved.
     3  SPDX-License-Identifier: Apache-2.0
     4  */
     5  
     6  package localsuite
     7  
     8  import (
     9  	"crypto/ed25519"
    10  	"crypto/rand"
    11  	"errors"
    12  	"testing"
    13  
    14  	"github.com/stretchr/testify/require"
    15  	mockkms "github.com/trustbloc/kms-go/mock/kms"
    16  	kmsapi "github.com/trustbloc/kms-go/spi/kms"
    17  )
    18  
    19  func TestKeyCreator(t *testing.T) {
    20  	t.Run("success", func(t *testing.T) {
    21  		keyBytes, _, err := ed25519.GenerateKey(rand.Reader)
    22  		require.NoError(t, err)
    23  
    24  		keyID := "foo"
    25  
    26  		creator := newKeyCreator(&mockkms.KeyManager{
    27  			CrAndExportPubKeyValue: keyBytes,
    28  			CrAndExportPubKeyID:    keyID,
    29  		})
    30  
    31  		pubJWK, err := creator.Create(kmsapi.ED25519Type)
    32  		require.NoError(t, err)
    33  		require.NotNil(t, pubJWK)
    34  		require.IsType(t, ed25519.PublicKey{}, pubJWK.Key)
    35  
    36  		kid, pubRaw, err := creator.CreateRaw(kmsapi.ED25519Type)
    37  		require.NoError(t, err)
    38  		require.NotNil(t, pubRaw)
    39  		require.Equal(t, keyID, kid)
    40  		require.IsType(t, ed25519.PublicKey{}, pubRaw)
    41  	})
    42  
    43  	t.Run("kms create err", func(t *testing.T) {
    44  		errExpected := errors.New("expected error")
    45  
    46  		creator := newKeyCreator(&mockkms.KeyManager{
    47  			CrAndExportPubKeyErr: errExpected,
    48  		})
    49  
    50  		pubJWK, err := creator.Create(kmsapi.ED25519Type)
    51  		require.ErrorIs(t, err, errExpected)
    52  		require.Nil(t, pubJWK)
    53  
    54  		kid, pubRaw, err := creator.CreateRaw(kmsapi.ED25519Type)
    55  		require.ErrorIs(t, err, errExpected)
    56  		require.Nil(t, pubRaw)
    57  		require.Empty(t, kid)
    58  	})
    59  
    60  	t.Run("kms exports invalid key value", func(t *testing.T) {
    61  		creator := newKeyCreator(&mockkms.KeyManager{
    62  			CrAndExportPubKeyValue: []byte("foo"),
    63  		})
    64  
    65  		pubJWK, err := creator.Create(kmsapi.ECDSAP256DER)
    66  		require.Error(t, err)
    67  		require.Nil(t, pubJWK)
    68  
    69  		kid, pubRaw, err := creator.CreateRaw(kmsapi.ECDSAP256DER)
    70  		require.Error(t, err)
    71  		require.Nil(t, pubRaw)
    72  		require.Empty(t, kid)
    73  	})
    74  }