-
Notifications
You must be signed in to change notification settings - Fork 58
/
webhook_test.go
658 lines (530 loc) · 25 KB
/
webhook_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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
admissionV1 "k8s.io/api/admission/v1"
corev1 "k8s.io/api/core/v1"
)
func TestValidateCreateRequest(t *testing.T) {
for testCaseName, winOptionsFactory := range map[string]func() *corev1.WindowsSecurityContextOptions{
"with empty GMSA settings": func() *corev1.WindowsSecurityContextOptions {
return &corev1.WindowsSecurityContextOptions{}
},
"with no GMSA settings": func() *corev1.WindowsSecurityContextOptions {
return nil
},
} {
t.Run(testCaseName, func(t *testing.T) {
webhook := newWebhook(nil)
pod := buildPod(dummyServiceAccoutName, winOptionsFactory(), map[string]*corev1.WindowsSecurityContextOptions{dummyContainerName: winOptionsFactory()})
response, err := webhook.validateCreateRequest(context.Background(), pod, dummyNamespace)
assert.Nil(t, err)
require.NotNil(t, response)
assert.True(t, response.Allowed)
})
}
kubeClientFactory := func() *dummyKubeClient {
return &dummyKubeClient{
retrieveCredSpecContentsFunc: func(ctx context.Context, credSpecName string) (contents string, httpCode int, err error) {
if credSpecName == dummyCredSpecName {
contents = dummyCredSpecContents
} else {
contents = credSpecName + "-contents"
}
return
},
}
}
winOptionsFactory := func(containerName string) *corev1.WindowsSecurityContextOptions {
return buildWindowsOptions(containerName+"-cred-spec", containerName+"-cred-spec-contents")
}
runWebhookValidateOrMutateTests(t, winOptionsFactory, map[string]webhookValidateOrMutateTest{
"with matching name & content, it passes": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, _ gmsaResourceKind, _ string) {
webhook := newWebhook(kubeClientFactory())
setWindowsOptions(optionsSelector(pod), dummyCredSpecName, dummyCredSpecContents)
response, err := webhook.validateCreateRequest(context.Background(), pod, dummyNamespace)
assert.Nil(t, err)
require.NotNil(t, response)
assert.True(t, response.Allowed)
},
"if the cred spec contents are not byte-to-byte equal to that of the one named, but still represent equivalent JSONs, it passes": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, _ gmsaResourceKind, _ string) {
webhook := newWebhook(kubeClientFactory())
setWindowsOptions(
optionsSelector(pod),
dummyCredSpecName,
`{"All in all you're just another": {"the":"wall","brick": "in"},"We don't need no":["education", "thought control","dark sarcasm in the classroom"]}`,
)
response, err := webhook.validateCreateRequest(context.Background(), pod, dummyNamespace)
assert.Nil(t, err)
require.NotNil(t, response)
assert.True(t, response.Allowed)
},
"if the cred spec contents are not that of the one named, it fails": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, resourceKind gmsaResourceKind, resourceName string) {
webhook := newWebhook(kubeClientFactory())
setWindowsOptions(
optionsSelector(pod),
dummyCredSpecName,
`{"We don't need no": ["money"], "All in all you're just another": {"brick": "in", "the": "wall"}}`,
)
response, err := webhook.validateCreateRequest(context.Background(), pod, dummyNamespace)
assert.Nil(t, response)
assertPodAdmissionErrorContains(t, err, pod, http.StatusUnprocessableEntity,
"the GMSA cred spec contents for %s %q does not match the contents of GMSA resource %q",
resourceKind, resourceName, dummyCredSpecName)
},
"if the cred spec contents are not byte-to-byte equal to that of the one named, and are not even a valid JSON object, it fails": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, resourceKind gmsaResourceKind, resourceName string) {
webhook := newWebhook(kubeClientFactory())
setWindowsOptions(optionsSelector(pod), dummyCredSpecName, "i ain't no JSON object")
response, err := webhook.validateCreateRequest(context.Background(), pod, dummyNamespace)
assert.Nil(t, response)
assertPodAdmissionErrorContains(t, err, pod, http.StatusUnprocessableEntity,
"the GMSA cred spec contents for %s %q does not match the contents of GMSA resource %q",
resourceKind, resourceName, dummyCredSpecName)
},
"if the contents are set, but the name one isn't provided, it fails": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, resourceKind gmsaResourceKind, resourceName string) {
webhook := newWebhook(kubeClientFactory())
setWindowsOptions(optionsSelector(pod), "", dummyCredSpecContents)
response, err := webhook.validateCreateRequest(context.Background(), pod, dummyNamespace)
assert.Nil(t, response)
assertPodAdmissionErrorContains(t, err, pod, http.StatusUnprocessableEntity,
"%s %q has a GMSA cred spec set, but does not define the name of the corresponding resource",
resourceKind, resourceName)
},
"if the service account is not authorized to use the cred-spec, it fails": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, _ gmsaResourceKind, _ string) {
dummyReason := "dummy reason"
client := kubeClientFactory()
client.isAuthorizedToUseCredSpecFunc = func(ctx context.Context, serviceAccountName, namespace, credSpecName string) (authorized bool, reason string) {
if credSpecName == dummyCredSpecName {
assert.Equal(t, dummyServiceAccoutName, serviceAccountName)
assert.Equal(t, dummyNamespace, namespace)
return false, dummyReason
}
return true, ""
}
webhook := newWebhook(client)
setWindowsOptions(optionsSelector(pod), dummyCredSpecName, dummyCredSpecContents)
response, err := webhook.validateCreateRequest(context.Background(), pod, dummyNamespace)
assert.Nil(t, response)
assertPodAdmissionErrorContains(t, err, pod, http.StatusForbidden,
"service account %q is not authorized to `use` GMSA cred spec %q, reason: %q",
dummyServiceAccoutName, dummyCredSpecName, dummyReason)
},
"if there is an error when retrieving the cred-spec's contents, it fails": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, _ gmsaResourceKind, _ string) {
dummyError := fmt.Errorf("dummy error")
client := kubeClientFactory()
previousRetrieveCredSpecContentsFunc := client.retrieveCredSpecContentsFunc
client.retrieveCredSpecContentsFunc = func(ctx context.Context, credSpecName string) (contents string, httpCode int, err error) {
if credSpecName == dummyCredSpecName {
return "", http.StatusNotFound, dummyError
}
return previousRetrieveCredSpecContentsFunc(ctx, credSpecName)
}
webhook := newWebhook(client)
setWindowsOptions(optionsSelector(pod), dummyCredSpecName, dummyCredSpecContents)
response, err := webhook.validateCreateRequest(context.Background(), pod, dummyNamespace)
assert.Nil(t, response)
assertPodAdmissionErrorContains(t, err, pod, http.StatusNotFound, dummyError.Error())
},
})
}
func TestMutateCreateRequest(t *testing.T) {
for testCaseName, winOptionsFactory := range map[string]func() *corev1.WindowsSecurityContextOptions{
"with empty GMSA settings, it passes and does nothing": func() *corev1.WindowsSecurityContextOptions {
return &corev1.WindowsSecurityContextOptions{}
},
"with no GMSA settings, it passes and does nothing": func() *corev1.WindowsSecurityContextOptions {
return nil
},
} {
t.Run(testCaseName, func(t *testing.T) {
webhook := newWebhookWithOptions(nil, WithRandomHostname(false))
pod := buildPod(dummyServiceAccoutName, winOptionsFactory(), map[string]*corev1.WindowsSecurityContextOptions{dummyContainerName: winOptionsFactory()})
response, err := webhook.mutateCreateRequest(context.Background(), pod)
assert.Nil(t, err)
require.NotNil(t, response)
assert.True(t, response.Allowed)
assert.Nil(t, response.Patch)
})
}
for testCaseName, winOptionsFactory := range map[string]func() *corev1.WindowsSecurityContextOptions{
"with random hostname env set and empty GMSA settings, it passes and does nothing": func() *corev1.WindowsSecurityContextOptions {
return &corev1.WindowsSecurityContextOptions{}
},
"with random hostname env set and no GMSA settings, it passes and does nothing": func() *corev1.WindowsSecurityContextOptions {
return nil
},
} {
t.Run(testCaseName, func(t *testing.T) {
webhook := newWebhookWithOptions(nil, WithRandomHostname(true))
pod := buildPod(dummyServiceAccoutName, winOptionsFactory(), map[string]*corev1.WindowsSecurityContextOptions{dummyContainerName: winOptionsFactory()})
response, err := webhook.mutateCreateRequest(context.Background(), pod)
assert.Nil(t, err)
require.NotNil(t, response)
assert.True(t, response.Allowed)
assert.Nil(t, response.Patch)
})
}
testCaseName, winOptionsFactory1 := "with random hostname env set and dummy GMSA settings, it passes and set random hostname", func() *corev1.WindowsSecurityContextOptions {
dummyCredSpecNameVar := dummyCredSpecName
dummyCredSpecContentsVar := dummyCredSpecContents
return &corev1.WindowsSecurityContextOptions{GMSACredentialSpecName: &dummyCredSpecNameVar, GMSACredentialSpec: &dummyCredSpecContentsVar}
}
t.Run(testCaseName, func(t *testing.T) {
webhook := newWebhookWithOptions(nil, WithRandomHostname(true))
pod := buildPod(dummyServiceAccoutName, winOptionsFactory1(), map[string]*corev1.WindowsSecurityContextOptions{dummyContainerName: winOptionsFactory1()})
response, err := webhook.mutateCreateRequest(context.Background(), pod)
assert.Nil(t, err)
require.NotNil(t, response)
assert.True(t, response.Allowed)
var patches []map[string]string
// one more because we're adding the hostname
if err := json.Unmarshal(response.Patch, &patches); assert.Nil(t, err) && assert.Equal(t, 1, len(patches)) {
foundHostname := false
for _, patch := range patches {
if value, hasValue := patch["value"]; assert.True(t, hasValue) {
if patch["path"] == "/spec/hostname" {
foundHostname = true
assert.Equal(t, "add", patch["op"])
assert.Equal(t, 15, len(value))
}
}
}
assert.True(t, foundHostname)
}
})
testCaseName, winOptionsFactory1 = "with random hostname env set and dummy GMSA settings and hostname set in spec, it passes and do nothing", func() *corev1.WindowsSecurityContextOptions {
dummyCredSpecNameVar := dummyCredSpecName
dummyCredSpecContentsVar := dummyCredSpecContents
return &corev1.WindowsSecurityContextOptions{GMSACredentialSpecName: &dummyCredSpecNameVar, GMSACredentialSpec: &dummyCredSpecContentsVar}
}
t.Run(testCaseName, func(t *testing.T) {
webhook := newWebhookWithOptions(nil, WithRandomHostname(true))
dummyPodNameVar := dummyPodName
pod := buildPodWithHostName(dummyServiceAccoutName, &dummyPodNameVar, winOptionsFactory1(), map[string]*corev1.WindowsSecurityContextOptions{dummyContainerName: winOptionsFactory1()})
response, err := webhook.mutateCreateRequest(context.Background(), pod)
assert.Nil(t, err)
require.NotNil(t, response)
assert.True(t, response.Allowed)
assert.Nil(t, response.Patch)
})
kubeClientFactory := func() *dummyKubeClient {
return &dummyKubeClient{
retrieveCredSpecContentsFunc: func(ctx context.Context, credSpecName string) (contents string, httpCode int, err error) {
if credSpecName == dummyCredSpecName {
contents = dummyCredSpecContents
} else {
contents = credSpecName + "-contents"
}
return
},
}
}
winOptionsFactory := func(containerName string) *corev1.WindowsSecurityContextOptions {
return buildWindowsOptions(containerName+"-cred-spec", "")
}
runWebhookValidateOrMutateTests(t, winOptionsFactory, map[string]webhookValidateOrMutateTest{
"with random hostname env and a GMSA cred spec name, it passes and inlines the cred-spec's contents and generate random hostname": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, resourceKind gmsaResourceKind, resourceName string) {
webhook := newWebhookWithOptions(kubeClientFactory(), WithRandomHostname(true))
setWindowsOptions(optionsSelector(pod), dummyCredSpecName, "")
response, err := webhook.mutateCreateRequest(context.Background(), pod)
assert.Nil(t, err)
require.NotNil(t, response)
assert.True(t, response.Allowed)
if assert.NotNil(t, response.PatchType) {
assert.Equal(t, admissionV1.PatchTypeJSONPatch, *response.PatchType)
}
patchPath := func(kind gmsaResourceKind, name string) string {
partialPath := ""
if kind == containerKind {
containerIndex := -1
for i, container := range pod.Spec.Containers {
if container.Name == name {
containerIndex = i
break
}
}
if containerIndex == -1 {
t.Fatalf("Did not find any container named %q", name)
}
partialPath = fmt.Sprintf("/containers/%d", containerIndex)
}
return fmt.Sprintf("/spec%s/securityContext/windowsOptions/gmsaCredentialSpec", partialPath)
}
// maps the contents to the expected patch for that container
expectedPatches := make(map[string]map[string]string)
for i := 0; i < len(pod.Spec.Containers)-1; i++ {
credSpecContents := extraContainerName(i) + "-cred-spec-contents"
expectedPatches[credSpecContents] = map[string]string{
"op": "add",
"path": patchPath(containerKind, extraContainerName(i)),
"value": credSpecContents,
}
}
// and the patch for this test's specific cred spec
expectedPatches[dummyCredSpecContents] = map[string]string{
"op": "add",
"path": patchPath(resourceKind, resourceName),
"value": dummyCredSpecContents,
}
var patches []map[string]string
// len(pod.Spec.Containers)+1 because we're adding the hostname
if err := json.Unmarshal(response.Patch, &patches); assert.Nil(t, err) && assert.Equal(t, len(pod.Spec.Containers)+1, len(patches)) {
foundHostname := false
for _, patch := range patches {
if value, hasValue := patch["value"]; assert.True(t, hasValue) {
if patch["path"] == "/spec/hostname" {
foundHostname = true
assert.Equal(t, "add", patch["op"])
assert.Equal(t, 15, len(value))
} else if expectedPatch, present := expectedPatches[value]; assert.True(t, present, "value %s not found in expected patches", value) {
assert.Equal(t, expectedPatch, patch)
}
}
}
assert.True(t, foundHostname)
}
},
// random hostname env not set in the following cases, and validated no hostname is set (implicitly)
"it the cred spec's contents are already set, along with its name, it passes and doesn't overwrite the provided contents": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, _ gmsaResourceKind, _ string) {
webhook := newWebhook(kubeClientFactory())
setWindowsOptions(optionsSelector(pod), dummyCredSpecName, `{"pre-set GMSA": "cred contents"}`)
response, err := webhook.mutateCreateRequest(context.Background(), pod)
assert.Nil(t, err)
// all the patches we receive should be for the extra containers
expectedPatchesLen := len(pod.Spec.Containers) - 1
if expectedPatchesLen == 0 {
assert.Nil(t, response.PatchType)
assert.Nil(t, response.Patch)
} else {
var patches []map[string]string
if err := json.Unmarshal(response.Patch, &patches); assert.Nil(t, err) && assert.Equal(t, expectedPatchesLen, len(patches)) {
for _, patch := range patches {
if path, hasPath := patch["path"]; assert.True(t, hasPath) {
assert.NotContains(t, path, dummyCredSpecName)
}
}
}
}
},
"if there is an error when retrieving the cred-spec's contents, it fails": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, _ gmsaResourceKind, _ string) {
dummyError := fmt.Errorf("dummy error")
client := kubeClientFactory()
previousRetrieveCredSpecContentsFunc := client.retrieveCredSpecContentsFunc
client.retrieveCredSpecContentsFunc = func(ctx context.Context, credSpecName string) (contents string, httpCode int, err error) {
if credSpecName == dummyCredSpecName {
return "", http.StatusNotFound, dummyError
}
return previousRetrieveCredSpecContentsFunc(ctx, credSpecName)
}
webhook := newWebhook(client)
setWindowsOptions(optionsSelector(pod), dummyCredSpecName, "")
response, err := webhook.mutateCreateRequest(context.Background(), pod)
assert.Nil(t, response)
assertPodAdmissionErrorContains(t, err, pod, http.StatusNotFound, dummyError.Error())
},
})
}
func TestValidateUpdateRequest(t *testing.T) {
for testCaseName, winOptionsFactory := range map[string]func() *corev1.WindowsSecurityContextOptions{
"with empty GMSA settings, it passes and does nothing": func() *corev1.WindowsSecurityContextOptions {
return &corev1.WindowsSecurityContextOptions{}
},
"with no GMSA settings, it passes and does nothing": func() *corev1.WindowsSecurityContextOptions {
return nil
},
} {
t.Run(testCaseName, func(t *testing.T) {
pod := buildPod(dummyServiceAccoutName, winOptionsFactory(), map[string]*corev1.WindowsSecurityContextOptions{dummyContainerName: winOptionsFactory()})
oldPod := buildPod(dummyServiceAccoutName, winOptionsFactory(), map[string]*corev1.WindowsSecurityContextOptions{dummyContainerName: winOptionsFactory()})
response, err := validateUpdateRequest(pod, oldPod)
assert.Nil(t, err)
require.NotNil(t, response)
assert.True(t, response.Allowed)
})
}
winOptionsFactory := func(containerName string) *corev1.WindowsSecurityContextOptions {
return buildWindowsOptions(containerName+"-cred-spec", containerName+"-cred-spec-contents")
}
runWebhookValidateOrMutateTests(t, winOptionsFactory, map[string]webhookValidateOrMutateTest{
"if there was no changes to GMSA settings, it passes": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, _ gmsaResourceKind, _ string) {
setWindowsOptions(optionsSelector(pod), dummyCredSpecName, dummyCredSpecContents)
oldPod := pod.DeepCopy()
response, err := validateUpdateRequest(pod, oldPod)
assert.Nil(t, err)
require.NotNil(t, response)
assert.True(t, response.Allowed)
},
"if there was a change to a GMSA name, it fails": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, resourceKind gmsaResourceKind, resourceName string) {
setWindowsOptions(optionsSelector(pod), "new-cred-spec-name", dummyCredSpecContents)
oldPod := pod.DeepCopy()
setWindowsOptions(optionsSelector(oldPod), dummyCredSpecName, "")
response, err := validateUpdateRequest(pod, oldPod)
assert.Nil(t, response)
assertPodAdmissionErrorContains(t, err, pod, http.StatusForbidden,
"cannot update an existing pod's GMSA settings (GMSA name modified on %s %q)",
resourceKind, resourceName)
},
"if there was a change to a GMSA contents, it fails": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, resourceKind gmsaResourceKind, resourceName string) {
setWindowsOptions(optionsSelector(pod), dummyCredSpecName, "new-cred-spec-contents")
oldPod := pod.DeepCopy()
setWindowsOptions(optionsSelector(oldPod), "", dummyCredSpecContents)
response, err := validateUpdateRequest(pod, oldPod)
assert.Nil(t, response)
assertPodAdmissionErrorContains(t, err, pod, http.StatusForbidden,
"cannot update an existing pod's GMSA settings (GMSA contents modified on %s %q)",
resourceKind, resourceName)
},
"if there were changes to both GMSA name & contents, it fails": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, resourceKind gmsaResourceKind, resourceName string) {
setWindowsOptions(optionsSelector(pod), "new-cred-spec-name", "new-cred-spec-contents")
oldPod := pod.DeepCopy()
setWindowsOptions(optionsSelector(oldPod), dummyCredSpecName, dummyCredSpecContents)
response, err := validateUpdateRequest(pod, oldPod)
assert.Nil(t, response)
assertPodAdmissionErrorContains(t, err, pod, http.StatusForbidden,
"cannot update an existing pod's GMSA settings (GMSA name and contents modified on %s %q)",
resourceKind, resourceName)
},
})
}
func TestDefaultWebhookConfig(t *testing.T) {
expectedCertReload := false
webhook := newWebhookWithOptions(nil, WithCertReload(expectedCertReload))
assert.Equal(t, expectedCertReload, webhook.config.EnableCertReload)
}
func TestSetWebhookConfig(t *testing.T) {
expectedCertReload := true
expectedRandomHostname := true
randomHostname := true
webhook := newWebhookWithOptions(nil, WithCertReload(expectedCertReload), WithRandomHostname(randomHostname))
assert.Equal(t, expectedCertReload, webhook.config.EnableCertReload)
assert.Equal(t, expectedRandomHostname, webhook.config.EnableRandomHostName)
}
func TestEqualStringPointers(t *testing.T) {
ptrToString := func(s *string) string {
if s == nil {
return "nil"
}
return " = " + *s
}
foo := "foo"
bar := "bar"
for _, testCase := range []struct {
s1 *string
s2 *string
expectedResult bool
}{
{
s1: nil,
s2: nil,
expectedResult: true,
},
{
s1: &foo,
s2: nil,
expectedResult: false,
},
{
s1: &foo,
s2: &foo,
expectedResult: true,
},
{
s1: &foo,
s2: &bar,
expectedResult: false,
},
} {
for _, ptrs := range [][]*string{
{testCase.s1, testCase.s2},
{testCase.s2, testCase.s1},
} {
s1 := ptrs[0]
s2 := ptrs[1]
testName := fmt.Sprintf("with s1 %s and s2 %s, should return %v",
ptrToString(s1),
ptrToString(s2),
testCase.expectedResult)
t.Run(testName, func(t *testing.T) {
assert.Equal(t, testCase.expectedResult, equalStringPointers(s1, s2))
})
}
}
}
/* Helpers below */
type containerWindowsOptionsFactory func(containerName string) *corev1.WindowsSecurityContextOptions
type winOptionsSelector func(pod *corev1.Pod) *corev1.WindowsSecurityContextOptions
// a webhookValidateOrMutateTest function should run a test on one of the webhook's validate or mutate
// functions, given a selector to extract the WindowsSecurityOptions struct it can play with from the pod.
// It should assume that the pod it receives has any number of extra containers with correct
// (in the sense of the test) windows security options generated by a relevant containerWindowsOptionsFactory.
type webhookValidateOrMutateTest func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, resourceKind gmsaResourceKind, resourceName string)
// runWebhookValidateOrMutateTests runs the given tests with 0 to 5 extra containers with correct windows
// security options as generated by winOptionsFactory.
func runWebhookValidateOrMutateTests(t *testing.T, winOptionsFactory containerWindowsOptionsFactory, tests map[string]webhookValidateOrMutateTest) {
for extraContainersCount := 0; extraContainersCount <= 5; extraContainersCount++ {
containerNamesAndWindowsOptions := make(map[string]*corev1.WindowsSecurityContextOptions)
for i := 0; i < extraContainersCount; i++ {
containerName := extraContainerName(i)
containerNamesAndWindowsOptions[containerName] = winOptionsFactory(containerName)
}
testNameSuffix := ""
if extraContainersCount > 0 {
testNameSuffix = fmt.Sprintf(" and %d extra containers", extraContainersCount)
}
for _, resourceKind := range []gmsaResourceKind{podKind, containerKind} {
for testName, testFunc := range tests {
podWindowsOptions := &corev1.WindowsSecurityContextOptions{}
containerNamesAndWindowsOptions[dummyContainerName] = &corev1.WindowsSecurityContextOptions{}
pod := buildPod(dummyServiceAccoutName, podWindowsOptions, containerNamesAndWindowsOptions)
var optionsSelector winOptionsSelector
var resourceName string
switch resourceKind {
case podKind:
optionsSelector = func(pod *corev1.Pod) *corev1.WindowsSecurityContextOptions {
if pod != nil && pod.Spec.SecurityContext != nil {
return pod.Spec.SecurityContext.WindowsOptions
}
return nil
}
resourceName = dummyPodName
case containerKind:
optionsSelector = func(pod *corev1.Pod) *corev1.WindowsSecurityContextOptions {
if pod != nil {
for _, container := range pod.Spec.Containers {
if container.Name == dummyContainerName {
if container.SecurityContext != nil {
return container.SecurityContext.WindowsOptions
}
return nil
}
}
}
return nil
}
resourceName = dummyContainerName
default:
t.Fatalf("Unknown resource kind: %q", resourceKind)
}
t.Run(fmt.Sprintf("%s - with %s-level windows options%s", testName, resourceKind, testNameSuffix), func(t *testing.T) {
testFunc(t, pod, optionsSelector, resourceKind, resourceName)
})
}
}
}
}
func extraContainerName(i int) string {
return fmt.Sprintf("extra-container-%d", i)
}
func assertPodAdmissionErrorContains(t *testing.T, err *podAdmissionError, pod *corev1.Pod, httpCode int, msgFormat string, msgArgs ...interface{}) bool {
if !assert.NotNil(t, err) {
return false
}
result := assert.Equal(t, pod, err.pod)
result = assert.Equal(t, httpCode, err.code) && result
return assert.Contains(t, err.Error(), fmt.Sprintf(msgFormat, msgArgs...)) && result
}