2022-05-20 16:16:21 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
|
|
|
"math/rand"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
|
|
|
|
"github.com/hashicorp/nomad/api/internal/testutil"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestKeyring_CRUD(t *testing.T) {
|
|
|
|
testutil.Parallel(t)
|
|
|
|
c, s := makeClient(t, nil, nil)
|
|
|
|
defer s.Stop()
|
|
|
|
|
|
|
|
kr := c.Keyring()
|
|
|
|
|
|
|
|
// Create a key by requesting a rotation
|
|
|
|
key, wm, err := kr.Rotate(nil, nil)
|
|
|
|
require.NoError(t, err)
|
|
|
|
require.NotNil(t, key)
|
|
|
|
assertWriteMeta(t, wm)
|
|
|
|
|
|
|
|
// Read all the keys
|
|
|
|
keys, qm, err := kr.List(&QueryOptions{WaitIndex: key.CreateIndex})
|
|
|
|
require.NoError(t, err)
|
|
|
|
assertQueryMeta(t, qm)
|
2022-05-31 12:43:51 +00:00
|
|
|
require.Len(t, keys, 2)
|
2022-05-20 16:16:21 +00:00
|
|
|
|
|
|
|
// Write a new active key, forcing a rotation
|
|
|
|
id := "fd77c376-9785-4c80-8e62-4ec3ab5f8b9a"
|
2022-05-25 19:05:30 +00:00
|
|
|
buf := make([]byte, 32)
|
2022-05-20 16:16:21 +00:00
|
|
|
rand.Read(buf)
|
2022-06-02 17:41:59 +00:00
|
|
|
encodedKey := base64.StdEncoding.EncodeToString(buf)
|
2022-05-20 16:16:21 +00:00
|
|
|
|
|
|
|
wm, err = kr.Update(&RootKey{
|
2022-06-02 17:41:59 +00:00
|
|
|
Key: encodedKey,
|
2022-05-20 16:16:21 +00:00
|
|
|
Meta: &RootKeyMeta{
|
2022-06-02 17:41:59 +00:00
|
|
|
KeyID: id,
|
2022-07-07 17:48:38 +00:00
|
|
|
State: RootKeyStateActive,
|
2022-06-02 17:41:59 +00:00
|
|
|
Algorithm: EncryptionAlgorithmAES256GCM,
|
2022-05-20 16:16:21 +00:00
|
|
|
}}, nil)
|
|
|
|
require.NoError(t, err)
|
|
|
|
assertWriteMeta(t, wm)
|
|
|
|
|
|
|
|
// Delete the old key
|
|
|
|
wm, err = kr.Delete(&KeyringDeleteOptions{KeyID: keys[0].KeyID}, nil)
|
|
|
|
require.NoError(t, err)
|
|
|
|
assertWriteMeta(t, wm)
|
|
|
|
|
|
|
|
// Read all the keys back
|
|
|
|
keys, qm, err = kr.List(&QueryOptions{WaitIndex: key.CreateIndex})
|
|
|
|
require.NoError(t, err)
|
|
|
|
assertQueryMeta(t, qm)
|
2022-05-31 12:43:51 +00:00
|
|
|
require.Len(t, keys, 2)
|
|
|
|
for _, key := range keys {
|
|
|
|
if key.KeyID == id {
|
2022-07-07 17:48:38 +00:00
|
|
|
require.Equal(t, RootKeyState(RootKeyStateActive),
|
|
|
|
key.State, "new key should be active")
|
2022-05-31 12:43:51 +00:00
|
|
|
} else {
|
2022-07-07 17:48:38 +00:00
|
|
|
require.Equal(t, RootKeyState(RootKeyStateInactive),
|
|
|
|
key.State, "initial key should be inactive")
|
2022-05-31 12:43:51 +00:00
|
|
|
}
|
|
|
|
}
|
2022-05-20 16:16:21 +00:00
|
|
|
}
|