-
Notifications
You must be signed in to change notification settings - Fork 87
/
vaultpkisecret_integration_test.go
349 lines (313 loc) · 10.3 KB
/
vaultpkisecret_integration_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package integration
import (
"context"
"encoding/json"
"fmt"
"os"
"path"
"path/filepath"
"strings"
"testing"
"time"
"github.com/gruntwork-io/terratest/modules/k8s"
"github.com/gruntwork-io/terratest/modules/random"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
secretsv1beta1 "github.com/hashicorp/vault-secrets-operator/api/v1beta1"
)
func TestVaultPKISecret(t *testing.T) {
testID := strings.ToLower(random.UniqueId())
testK8sNamespace := "k8s-tenant-" + testID
testPKIMountPath := "pki-" + testID
testVaultNamespace := ""
testVaultConnectionName := "vaultconnection-test-tenant-1"
testVaultAuthMethodName := "vaultauth-test-tenant-1"
testVaultAuthMethodRole := "role1"
operatorNS := os.Getenv("OPERATOR_NAMESPACE")
require.NotEmpty(t, operatorNS, "OPERATOR_NAMESPACE is not set")
clusterName := os.Getenv("KIND_CLUSTER_NAME")
require.NotEmpty(t, clusterName, "KIND_CLUSTER_NAME is not set")
k8sConfigContext := os.Getenv("K8S_CLUSTER_CONTEXT")
if k8sConfigContext == "" {
k8sConfigContext = "kind-" + clusterName
}
k8sOpts := &k8s.KubectlOptions{
ContextName: k8sConfigContext,
Namespace: operatorNS,
}
// The Helm based integration test is expecting to use the default VaultAuthMethod+VaultConnection
// so in order to get the controller to use the deployed default VaultAuthMethod we need set the VaultAuthRef to "".
if testWithHelm {
testVaultAuthMethodName = ""
}
tempDir, err := os.MkdirTemp(os.TempDir(), t.Name())
require.Nil(t, err)
tfDir := copyTerraformDir(t, path.Join(testRoot, "vaultpkisecret/terraform"), tempDir)
copyModulesDir(t, tfDir)
chartDestDir := copyChartDir(t, tfDir)
// Construct the terraform options with default retryable errors to handle the most common
// retryable errors in terraform testing.
tfOptions := &terraform.Options{
// Set the path to the Terraform code that will be tested.
TerraformDir: tfDir,
Vars: map[string]interface{}{
"deploy_operator_via_helm": testWithHelm,
"k8s_vault_connection_address": testVaultAddress,
"k8s_test_namespace": testK8sNamespace,
"k8s_config_context": k8sConfigContext,
"vault_pki_mount_path": testPKIMountPath,
},
}
if entTests {
testVaultNamespace = "vault-tenant-" + testID
tfOptions.Vars["vault_enterprise"] = true
tfOptions.Vars["vault_test_namespace"] = testVaultNamespace
}
tfOptions = setCommonTFOptions(t, tfOptions)
kustomizeConfigPath := filepath.Join(kustomizeConfigRoot, "default")
if !testWithHelm {
// deploy the Operator with Kustomize
deployOperatorWithKustomize(t, k8sOpts, kustomizeConfigPath)
} else {
tfOptions.Vars["deploy_operator_via_helm"] = true
tfOptions.Vars["operator_helm_chart_path"] = chartDestDir
if operatorImageRepo != "" {
tfOptions.Vars["operator_image_repo"] = operatorImageRepo
}
if operatorImageTag != "" {
tfOptions.Vars["operator_image_tag"] = operatorImageTag
}
tfOptions.Vars["enable_default_auth_method"] = true
tfOptions.Vars["enable_default_connection"] = true
tfOptions.Vars["k8s_vault_connection_address"] = testVaultAddress
}
ctx := context.Background()
crdClient := getCRDClient(t)
var created []ctrlclient.Object
skipCleanup := os.Getenv("SKIP_CLEANUP") != ""
// Clean up resources with "terraform destroy" at the end of the test.
t.Cleanup(func() {
exportKindLogs(t)
if !skipCleanup {
for _, c := range created {
// test that the custom resources can be deleted before tf destroy
// removes the k8s namespace
assert.Nil(t, crdClient.Delete(ctx, c))
}
terraform.Destroy(t, tfOptions)
os.RemoveAll(tempDir)
// Undeploy Kustomize
if !testWithHelm {
k8s.KubectlDeleteFromKustomize(t, k8sOpts, kustomizeConfigPath)
}
} else {
t.Logf("Skipping cleanup, tfdir=%s", tfDir)
}
})
// Run "terraform init" and "terraform apply". Fail the test if there are any errors.
terraform.InitAndApply(t, tfOptions)
if skipCleanup {
// save vars to re-run terraform, useful when SKIP_CLEANUP is set.
b, err := json.Marshal(tfOptions.Vars)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(
filepath.Join(tfOptions.TerraformDir, "terraform.tfvars.json"), b, 0o644); err != nil {
t.Fatal(err)
}
}
// When we deploy the operator with Helm it will also deploy default VaultConnection/AuthMethod
// resources, so these are not needed. In this case, we will also clear the VaultAuthRef field of
// the target secret so that the controller uses the default AuthMethod.
if !testWithHelm {
// Create a VaultConnection CR
testVaultConnection := &secretsv1beta1.VaultConnection{
ObjectMeta: v1.ObjectMeta{
Name: testVaultConnectionName,
Namespace: testK8sNamespace,
},
Spec: secretsv1beta1.VaultConnectionSpec{
Address: testVaultAddress,
},
}
require.NoError(t, crdClient.Create(ctx, testVaultConnection))
created = append(created, testVaultConnection)
// Create a VaultAuth CR
testVaultAuth := &secretsv1beta1.VaultAuth{
ObjectMeta: v1.ObjectMeta{
Name: testVaultAuthMethodName,
Namespace: testK8sNamespace,
},
Spec: secretsv1beta1.VaultAuthSpec{
VaultConnectionRef: testVaultConnectionName,
Namespace: testVaultNamespace,
Method: "kubernetes",
Mount: "kubernetes",
Kubernetes: &secretsv1beta1.VaultAuthConfigKubernetes{
Role: testVaultAuthMethodRole,
ServiceAccount: "default",
TokenAudiences: []string{"vault"},
},
},
}
require.NoError(t, crdClient.Create(ctx, testVaultAuth))
created = append(created, testVaultAuth)
}
// Create a VaultPKI CR to trigger the sync
getExisting := func() []*secretsv1beta1.VaultPKISecret {
return []*secretsv1beta1.VaultPKISecret{
{
ObjectMeta: v1.ObjectMeta{
Name: "vaultpki-test-tenant-1",
Namespace: testK8sNamespace,
},
Spec: secretsv1beta1.VaultPKISecretSpec{
VaultAuthRef: testVaultAuthMethodName,
Namespace: testVaultNamespace,
Mount: testPKIMountPath,
Role: "secret",
CommonName: "test1.example.com",
Format: "pem",
Revoke: true,
Clear: true,
ExpiryOffset: "1s",
TTL: "10s",
AltNames: []string{"alt1.example.com", "alt2.example.com"},
URISans: []string{"uri1.example.com", "uri2.example.com"},
IPSans: []string{"127.1.1.1", "127.0.0.1"},
Destination: secretsv1beta1.Destination{
Name: "pki1",
Create: false,
},
RolloutRestartTargets: []secretsv1beta1.RolloutRestartTarget{
{
Kind: "Deployment",
Name: "vso",
},
},
},
},
}
}
tests := []struct {
name string
existing []*secretsv1beta1.VaultPKISecret
create int
secretType corev1.SecretType
}{
{
name: "existing-only",
existing: getExisting(),
},
{
name: "create-only",
create: 10,
},
{
name: "mixed",
existing: getExisting(),
create: 5,
},
{
name: "create-tls",
create: 2,
secretType: corev1.SecretTypeTLS,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var toTest []*secretsv1beta1.VaultPKISecret
for idx, obj := range tt.existing {
name := fmt.Sprintf("%s-existing-%d", tt.name, idx)
obj.Name = name
toTest = append(toTest, obj)
}
for idx := 0; idx < tt.create; idx++ {
dest := fmt.Sprintf("%s-create-%d", tt.name, idx)
toTest = append(toTest, &secretsv1beta1.VaultPKISecret{
ObjectMeta: v1.ObjectMeta{
Name: dest,
Namespace: testK8sNamespace,
},
Spec: secretsv1beta1.VaultPKISecretSpec{
Role: "secret",
Namespace: testVaultNamespace,
Mount: testPKIMountPath,
CommonName: fmt.Sprintf("%s.example.com", dest),
Format: "pem",
Revoke: true,
ExpiryOffset: "2s",
TTL: "10s",
VaultAuthRef: testVaultAuthMethodName,
AltNames: []string{"alt1.example.com", "alt2.example.com"},
URISans: []string{"uri1.example.com", "uri2.example.com"},
IPSans: []string{"127.1.1.1", "127.0.0.1"},
Destination: secretsv1beta1.Destination{
Name: dest,
Create: true,
Type: tt.secretType,
},
},
})
}
require.Equal(t, len(toTest), tt.create+len(tt.existing))
var count int
for _, vpsObj := range toTest {
count++
name := fmt.Sprintf("%s", vpsObj.Name)
t.Run(name, func(t *testing.T) {
// capture vpsObj for parallel test
vpsObj := vpsObj
t.Parallel()
t.Cleanup(func() {
if !skipCleanup {
assert.NoError(t, crdClient.Delete(ctx, vpsObj))
}
})
require.NoError(t, crdClient.Create(ctx, vpsObj))
// Wait for the operator to sync Vault PKI --> k8s Secret, and return the
// serial number of the generated cert
serialNumber, secret, err := waitForPKIData(t, 30, 2*time.Second,
vpsObj, "",
)
require.NoError(t, err)
assert.NotEmpty(t, serialNumber)
assertSyncableSecret(t, crdClient, vpsObj, secret)
if vpsObj.Spec.Destination.Create {
expectedType := vpsObj.Spec.Destination.Type
if expectedType == "" {
expectedType = corev1.SecretTypeOpaque
}
assert.Equal(t, expectedType, secret.Type)
}
// Use the serial number of the first generated cert to check that the cert
// is updated
newSerialNumber, secret, err := waitForPKIData(t, 30, 2*time.Second,
vpsObj, serialNumber,
)
require.NoError(t, err)
assert.NotEmpty(t, newSerialNumber)
assertSyncableSecret(t, crdClient, vpsObj, secret)
if len(vpsObj.Spec.RolloutRestartTargets) > 0 {
awaitRolloutRestarts(t, ctx, crdClient, vpsObj, vpsObj.Spec.RolloutRestartTargets)
}
if vpsObj.Spec.Destination.Create && !t.Failed() {
d, err := time.ParseDuration(vpsObj.Spec.TTL)
if assert.NoError(t, err) {
assertRemediationOnDestinationDeletion(t, ctx, crdClient, vpsObj,
time.Millisecond*500, uint64(d.Seconds()*3))
}
}
})
}
assert.Greater(t, count, 0, "no tests were run")
})
}
}