Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unit tests to hashicorpvault handler #5189

Merged
merged 7 commits into from
Nov 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ New deprecation(s):
- **General**: Fix logger in Opentelemetry collector ([#5094](https://github.com/kedacore/keda/issues/5094))
- **General**: Reduce amount of gauge creations for OpenTelemetry metrics ([#5101](https://github.com/kedacore/keda/issues/5101))
- **General**: Support profiling for KEDA components ([#4789](https://github.com/kedacore/keda/issues/4789))
- **Hashicorp Vault**: Improve test coverage in `pkg/scaling/resolver/hashicorpvault_handler` ([#5195](https://github.com/kedacore/keda/issues/5195))

## v2.12.0

Expand Down
2 changes: 1 addition & 1 deletion pkg/scaling/resolver/hashicorpvault_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ func (vh *HashicorpVaultHandler) fetchSecret(secretType kedav1alpha1.VaultSecret
// ResolveSecrets allows to resolve a slice of secrets by vault. The function returns the list of secrets with the value updated.
// If multiple secret refers to the same SecretGroup, the secret will be fetched only once.
func (vh *HashicorpVaultHandler) ResolveSecrets(secrets []kedav1alpha1.VaultSecret) ([]kedav1alpha1.VaultSecret, error) {
// Group secret by path and type, this allows to fetch a path only one. This is useful for dynamic credentials
// Group secret by path and type, this allows to fetch a path only once. This is useful for dynamic credentials
grouped := make(map[SecretGroup][]kedav1alpha1.VaultSecret)
vaultSecrets := make(map[SecretGroup]*vaultapi.Secret)
for _, e := range secrets {
Expand Down
196 changes: 195 additions & 1 deletion pkg/scaling/resolver/hashicorpvault_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ var resolveRequestTestDataSet = []resolveRequestTestData{
key: "array",
isError: false,
expectedValue: "",
secretType: "inexisting_type",
secretType: "non_existing_type",
},
{
name: "existing_pki",
Expand Down Expand Up @@ -435,3 +435,197 @@ func TestHashicorpVaultHandler_ResolveSecrets_SameCertAndKey(t *testing.T) {
assert.Len(t, secrets, 2, "Supposed to get back two secrets")
assert.Equalf(t, secrets[0].Value, secrets[1].Value, "Refetching same path should yield same value")
}

var fetchSecretTestDataSet = []resolveRequestTestData{
{
name: "existing_secret_v2",
path: "kv_v2/data/keda",
key: "test",
isError: false,
expectedValue: kedaSecretValue,
},
{
name: "existing_secret_v1",
path: "kv/keda",
key: "test",
isError: false,
expectedValue: kedaSecretValue,
},
{
name: "existing_pki",
path: "pki/issue/default",
key: "private_key_type",
isError: false,
secretType: kedav1alpha1.VaultSecretTypePki,
pkiData: kedav1alpha1.VaultPkiData{CommonName: "test"},
expectedValue: "rsa",
},
{
name: "existing_pki_ca_chain",
path: "pki/issue/default",
key: "ca_chain",
isError: false,
secretType: kedav1alpha1.VaultSecretTypePki,
pkiData: kedav1alpha1.VaultPkiData{CommonName: "test"},
expectedValue: pkiCaChain,
},
}

func TestHashicorpVaultHandler_fetchSecret(t *testing.T) {
server := mockVault(t, false)
defer server.Close()

vault := kedav1alpha1.HashiCorpVault{
Address: server.URL,
Authentication: kedav1alpha1.VaultAuthenticationToken,
Credential: &kedav1alpha1.Credential{
Token: vaultTestToken,
},
}
vaultHandler := NewHashicorpVaultHandler(&vault)
err := vaultHandler.Initialize(logf.Log.WithName("test"))
defer vaultHandler.Stop()
assert.Nil(t, err)

for _, testData := range fetchSecretTestDataSet {
secretResponse, err := vaultHandler.fetchSecret(testData.secretType, testData.path, &testData.pkiData)
assert.Nil(t, err)

if testData.isError {
assert.NotNilf(t, err, "test %s: expected error but got success, testData - %+v", testData.name, testData)
}
secretStruct := kedav1alpha1.VaultSecret{Parameter: "test", Path: testData.path, Key: testData.key, Type: testData.secretType, PkiData: testData.pkiData}
secret, err := vaultHandler.getSecretValue(&secretStruct, secretResponse)

assert.Nil(t, err)
assert.Equalf(t, testData.expectedValue, secret, "test %s: expected data does not match given secret", testData.name)
}
}

type initializeTestData struct {
name string
namespace string
token string
isError bool
}

var initialiseTestDataSet = []initializeTestData{
{
name: "Namespace and Token",
namespace: "testNamespace",
token: "testToken",
isError: false,
},
{
name: "No Namespace",
namespace: "",
token: "testToken",
isError: false,
},
}

func TestHashicorpVaultHandler_Initialize(t *testing.T) {
server := mockVault(t, false)
defer server.Close()

for _, testData := range initialiseTestDataSet {
func() {
vault := kedav1alpha1.HashiCorpVault{
Address: server.URL,
Authentication: kedav1alpha1.VaultAuthenticationToken,
Credential: &kedav1alpha1.Credential{
Token: testData.token,
},
Namespace: testData.namespace,
}
vaultHandler := NewHashicorpVaultHandler(&vault)
err := vaultHandler.Initialize(logf.Log.WithName("test"))
defer vaultHandler.Stop()
assert.Nil(t, err)

if testData.isError {
assert.NotNilf(t, err, "test %s: expected error but got success, testData - %+v", testData.name, testData)
} else {
assert.Equalf(t, vaultHandler.client.Address(), server.URL, "test case %s", testData.name)
assert.Equalf(t, vaultHandler.client.Token(), testData.token, "test case %s", testData.name)
assert.Equalf(t, vaultHandler.client.Namespace(), testData.namespace, "test case %s", testData.name)
}
}()
}
}

type tokenTestData struct {
name string
isError bool
errorMessage string
authentication kedav1alpha1.VaultAuthentication
credential kedav1alpha1.Credential
mount string
role string
}

var tokenTestDataSet = []tokenTestData{
{
name: "Vault Authentication",
isError: false,
authentication: kedav1alpha1.VaultAuthenticationToken,
credential: kedav1alpha1.Credential{
Token: vaultTestToken,
},
role: "my-role",
mount: "my-mount",
},
{
name: "Kubernetes Authentication",
isError: true, // Because the service account path is non-existent
authentication: kedav1alpha1.VaultAuthenticationKubernetes,
credential: kedav1alpha1.Credential{
ServiceAccount: "random/path",
},
role: "my-role",
mount: "my-mount",
errorMessage: "open random/path: no such file or directory",
},
{
name: "Wrong Authentication Method",
isError: true,
authentication: "random",
credential: kedav1alpha1.Credential{
ServiceAccount: "random/path",
},
role: "my-role",
mount: "my-mount",
errorMessage: "vault auth method random is not supported",
},
}

func TestHashicorpVaultHandler_Token_VaultTokenAuth(t *testing.T) {
server := mockVault(t, false)
defer server.Close()

for _, testData := range tokenTestDataSet {
func() {
vault := kedav1alpha1.HashiCorpVault{
Address: server.URL,
Authentication: testData.authentication,
Credential: &testData.credential,
Role: testData.role,
Mount: testData.mount,
}
vaultHandler := NewHashicorpVaultHandler(&vault)
defer vaultHandler.Stop()

config := vaultapi.DefaultConfig()
client, err := vaultapi.NewClient(config)
assert.Nil(t, err)
token, err := vaultHandler.token(client)
if testData.isError {
assert.Equalf(t, vaultHandler.vault.Credential.ServiceAccount, testData.credential.ServiceAccount, "test %s: expected %s but found %s", testData.name, "random/path", vaultHandler.vault.Credential.ServiceAccount)
assert.NotNilf(t, err, "test %s: expected error but got success, testData - %+v", testData.name, testData)
assert.Contains(t, err.Error(), testData.errorMessage)
} else {
assert.Equalf(t, token, vaultTestToken, "expected %s but got %s", vaultTestToken, token)
}
}()
}
}