|
| 1 | +// Copyright 2024 Democratized Data Foundation |
| 2 | +// |
| 3 | +// Use of this software is governed by the Business Source License |
| 4 | +// included in the file licenses/BSL.txt. |
| 5 | +// |
| 6 | +// As of the Change Date specified in that file, in accordance with |
| 7 | +// the Business Source License, use of this software will be governed |
| 8 | +// by the Apache License, Version 2.0, included in the file |
| 9 | +// licenses/APL.txt. |
| 10 | + |
| 11 | +package cli |
| 12 | + |
| 13 | +import ( |
| 14 | + "bytes" |
| 15 | + "encoding/hex" |
| 16 | + "os" |
| 17 | + "regexp" |
| 18 | + "testing" |
| 19 | + |
| 20 | + "github.com/sourcenetwork/defradb/crypto" |
| 21 | + |
| 22 | + "github.com/stretchr/testify/assert" |
| 23 | + "github.com/stretchr/testify/require" |
| 24 | +) |
| 25 | + |
| 26 | +func TestKeyringList(t *testing.T) { |
| 27 | + rootdir := t.TempDir() |
| 28 | + |
| 29 | + err := os.Setenv("DEFRA_KEYRING_SECRET", "password") |
| 30 | + require.NoError(t, err) |
| 31 | + |
| 32 | + keyNames := []string{"keyname1", "keyname2", "keyname3"} |
| 33 | + |
| 34 | + // Insert the keys into the keyring |
| 35 | + for _, keyName := range keyNames { |
| 36 | + keyBytes, err := crypto.GenerateAES256() |
| 37 | + require.NoError(t, err) |
| 38 | + keyHex := hex.EncodeToString(keyBytes) |
| 39 | + cmd := NewDefraCommand() |
| 40 | + cmd.SetArgs([]string{"keyring", "import", "--rootdir", rootdir, keyName, keyHex}) |
| 41 | + err = cmd.Execute() |
| 42 | + require.NoError(t, err) |
| 43 | + } |
| 44 | + |
| 45 | + // Run the 'keyring list' command, and require no error on the output |
| 46 | + var output bytes.Buffer |
| 47 | + cmd := NewDefraCommand() |
| 48 | + cmd.SetOut(&output) |
| 49 | + cmd.SetArgs([]string{"keyring", "list", "--rootdir", rootdir}) |
| 50 | + err = cmd.Execute() |
| 51 | + require.NoError(t, err) |
| 52 | + |
| 53 | + outputString := output.String() |
| 54 | + |
| 55 | + // Use regex to extract the keys, and compare with the expected values |
| 56 | + // We know what the format the output should be, which is: |
| 57 | + // "Keys in the keyring:\n- keyname1\n- keyname2\n- keyname3\n" |
| 58 | + re := regexp.MustCompile(`-\s([^\n]+)`) |
| 59 | + matches := re.FindAllStringSubmatch(outputString, -1) |
| 60 | + var extractedKeys []string |
| 61 | + for _, match := range matches { |
| 62 | + extractedKeys = append(extractedKeys, match[1]) |
| 63 | + } |
| 64 | + |
| 65 | + assert.ElementsMatch(t, keyNames, extractedKeys, "The listed keys do not match the expected keys.") |
| 66 | +} |
0 commit comments