-
Notifications
You must be signed in to change notification settings - Fork 14
/
admit_funcs_test.go
618 lines (584 loc) · 24.3 KB
/
admit_funcs_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
package admissioncontrol
import (
"encoding/json"
"fmt"
"strings"
"testing"
admission "k8s.io/api/admission/v1beta1"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
meta "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
)
var (
testErrAdmissionMismatch = "admission mismatch (kind: %v): got allowed=%t - wanted allowed=%t)"
testErrMessageMismatch = "error message does not match: got %q - expected %q"
)
type objectTest struct {
testName string
admitFunc AdmitFunc
cloudProvider CloudProvider
requiredAnnotations map[string]func(string) bool
kind meta.GroupVersionKind
object interface{}
rawObject []byte
ignoredNamespaces []string
expectedMessage string
shouldAllow bool
}
func newTestAdmissionRequest(kind meta.GroupVersionKind, object []byte, expected bool) *admission.AdmissionReview {
ar := &admission.AdmissionReview{
Request: &admission.AdmissionRequest{
Kind: kind,
Object: runtime.RawExtension{
Raw: object,
},
},
Response: &admission.AdmissionResponse{},
}
return ar
}
// TestDenyIngress validates that the DenyIngress AdmitFunc correctly rejects
// admission of Ingress objects to a cluster.
func TestDenyIngress(t *testing.T) {
t.Parallel()
var deniedIngressError = "Ingress objects cannot be deployed to this cluster"
var denyTests = []objectTest{
{
testName: "Reject Ingress (<= v1.13)",
kind: meta.GroupVersionKind{
Group: "extensions",
Kind: "Ingress",
Version: "v1beta1",
},
rawObject: []byte(`{"kind":"Ingress","apiVersion":"v1beta1","group":"extensions","metadata":{"name":"hello-ingress","namespace":"default","annotations":{}},"spec":{"rules":[]}}`),
expectedMessage: deniedIngressError,
shouldAllow: false,
},
{
testName: "Reject Ingress (>= v1.14)",
kind: meta.GroupVersionKind{
Group: "networking.k8s.io",
Kind: "Ingress",
Version: "v1beta1",
},
rawObject: []byte(`{"kind":"Ingress","apiVersion":"v1beta1","group":"networking.k8s.io","metadata":{"name":"hello-ingress","namespace":"default","annotations":{}},"spec":{"rules":[]}}`),
expectedMessage: deniedIngressError,
shouldAllow: false,
},
{
testName: "Allow admission to a whitelisted namespace",
kind: meta.GroupVersionKind{
Group: "extensions",
Kind: "Ingress",
Version: "v1beta1",
},
rawObject: []byte(`{"kind":"Ingress","apiVersion":"v1beta1","group":"extensions","metadata":{"name":"hello-ingress","namespace":"istio-system","annotations":{}},"spec":{"rules":[]}}`),
ignoredNamespaces: []string{"istio-system"},
expectedMessage: "",
shouldAllow: true,
},
{
testName: "Reject Ingress in incorrectly whitelisted namespace (case-sensitive)",
kind: meta.GroupVersionKind{
Group: "extensions",
Kind: "Ingress",
Version: "v1beta1",
},
rawObject: []byte(`{"kind":"Ingress","apiVersion":"v1beta1","group":"extensions","metadata":{"name":"hello-ingress","namespace":"UPPER-CASE","annotations":{}},"spec":{"rules":[]}}`),
ignoredNamespaces: []string{"upper-case"},
expectedMessage: deniedIngressError,
shouldAllow: false,
},
{
testName: "Don't reject Services",
kind: meta.GroupVersionKind{
Group: "",
Kind: "Service",
Version: "v1",
},
rawObject: []byte(`{"kind":"Service","apiVersion":"v1","metadata":{"name":"hello-service","namespace":"default","annotations":{}},"spec":{"ports":[{"protocol":"TCP","port":8000,"targetPort":8080,"nodePort":31433}],"selector":{"app":"hello-app"},"type":"LoadBalancer","externalTrafficPolicy":"Cluster"}}`),
expectedMessage: "Service objects of type: LoadBalancer without an internal-only annotation cannot be deployed to this cluster",
shouldAllow: true,
},
{
testName: "Don't reject Pods",
kind: meta.GroupVersionKind{
Group: "",
Kind: "Pod",
Version: "v1",
},
rawObject: nil,
expectedMessage: "",
shouldAllow: true,
},
{
testName: "Don't reject Deployments",
kind: meta.GroupVersionKind{
Group: "apps",
Kind: "Deployment",
Version: "v1",
},
rawObject: nil,
expectedMessage: "",
shouldAllow: true,
},
}
for _, tt := range denyTests {
t.Run(tt.testName, func(t *testing.T) {
incomingReview := admission.AdmissionReview{
Request: &admission.AdmissionRequest{},
}
incomingReview.Request.Kind = tt.kind
incomingReview.Request.Object.Raw = tt.rawObject
resp, err := DenyIngresses(tt.ignoredNamespaces)(&incomingReview)
if err != nil {
if tt.expectedMessage != err.Error() {
t.Fatalf(testErrMessageMismatch, err.Error(), tt.expectedMessage)
}
if tt.shouldAllow {
t.Fatalf("incorrectly rejected admission for Kind: %v: %s", tt.kind, err.Error())
}
t.Logf("correctly rejected admission for Kind: %v: %s", tt.kind, err.Error())
return
}
if resp.Allowed != tt.shouldAllow {
t.Fatalf(testErrAdmissionMismatch, tt.kind, resp.Allowed, tt.shouldAllow)
}
})
}
}
// TestDenyPublicServices checks that the DenyPublicServices AdmitFunc correctly
// rejects non-internal load balancer admission to a cluster.
func TestDenyPublicLoadBalancers(t *testing.T) {
t.Parallel()
var missingLBAnnotationsMessage = "Service objects of type: LoadBalancer without an internal-only annotation cannot be deployed to this cluster"
var denyTests = []objectTest{
{
testName: "Reject Public Service",
cloudProvider: GCP,
kind: meta.GroupVersionKind{
Group: "",
Kind: "Service",
Version: "v1",
},
rawObject: []byte(`{"kind":"Service","apiVersion":"v1","metadata":{"name":"hello-service","namespace":"default","annotations":{}},"spec":{"ports":[{"protocol":"TCP","port":8000,"targetPort":8080,"nodePort":31433}],"selector":{"app":"hello-app"},"type":"LoadBalancer","externalTrafficPolicy":"Cluster"}}`),
expectedMessage: "Service objects of type: LoadBalancer without an internal-only annotation cannot be deployed to this cluster",
shouldAllow: false,
},
{
testName: "Allow Annotated Private Service (GCP)",
cloudProvider: GCP,
kind: meta.GroupVersionKind{
Group: "",
Kind: "Service",
Version: "v1",
},
rawObject: []byte(`{"kind":"Service","apiVersion":"v1","metadata":{"name":"hello-service","namespace":"default","annotations":{"cloud.google.com/load-balancer-type":"Internal"}},"spec":{"ports":[{"protocol":"TCP","port":8000,"targetPort":8080,"nodePort":31433}],"selector":{"app":"hello-app"},"type":"LoadBalancer","externalTrafficPolicy":"Cluster"}}`),
expectedMessage: "",
shouldAllow: true,
},
{
testName: "Allow Public Service in Whitelisted Namespace",
cloudProvider: GCP,
kind: meta.GroupVersionKind{
Group: "",
Kind: "Service",
Version: "v1",
},
rawObject: []byte(`{"kind":"Service","apiVersion":"v1","metadata":{"name":"hello-service","namespace":"web-services","annotations":{}},"spec":{"ports":[{"protocol":"TCP","port":8000,"targetPort":8080,"nodePort":31433}],"selector":{"app":"hello-app"},"type":"LoadBalancer","externalTrafficPolicy":"Cluster"}}`),
ignoredNamespaces: []string{"web-services"},
expectedMessage: "",
shouldAllow: true,
},
{
testName: "Reject public Service in incorrectly whitelisted namespace (case-sensitive)",
cloudProvider: GCP,
kind: meta.GroupVersionKind{
Group: "",
Kind: "Service",
Version: "v1",
},
rawObject: []byte(`{"kind":"Service","apiVersion":"v1","metadata":{"name":"hello-service","namespace":"WEB-SERVICES","annotations":{}},"spec":{"ports":[{"protocol":"TCP","port":8000,"targetPort":8080,"nodePort":31433}],"selector":{"app":"hello-app"},"type":"LoadBalancer","externalTrafficPolicy":"Cluster"}}`),
ignoredNamespaces: []string{"web-services"},
expectedMessage: missingLBAnnotationsMessage,
shouldAllow: false,
},
{
testName: "Allow Annotated Private Service (Azure)",
cloudProvider: Azure,
kind: meta.GroupVersionKind{
Group: "",
Kind: "Service",
Version: "v1",
},
rawObject: []byte(`{"kind":"Service","apiVersion":"v1","metadata":{"name":"hello-service","namespace":"default","annotations":{"service.beta.kubernetes.io/azure-load-balancer-internal":"true"}},"spec":{"ports":[{"protocol":"TCP","port":8000,"targetPort":8080,"nodePort":31433}],"selector":{"app":"hello-app"},"type":"LoadBalancer","externalTrafficPolicy":"Cluster"}}`),
expectedMessage: "",
shouldAllow: true,
},
{
testName: "Allow Annotated Private Service (AWS)",
cloudProvider: AWS,
kind: meta.GroupVersionKind{
Group: "",
Kind: "Service",
Version: "v1",
},
rawObject: []byte(`{"kind":"Service","apiVersion":"v1","metadata":{"name":"hello-service","namespace":"default","annotations":{"service.beta.kubernetes.io/aws-load-balancer-internal":"0.0.0.0/0"}},"spec":{"ports":[{"protocol":"TCP","port":8000,"targetPort":8080,"nodePort":31433}],"selector":{"app":"hello-app"},"type":"LoadBalancer","externalTrafficPolicy":"Cluster"}}`),
expectedMessage: missingLBAnnotationsMessage,
shouldAllow: true,
},
{
testName: "Reject Incorrectly Annotated Private Service (no annotation)",
cloudProvider: GCP,
kind: meta.GroupVersionKind{
Group: "",
Kind: "Service",
Version: "v1",
},
rawObject: []byte(`{"kind":"Service","apiVersion":"v1","metadata":{"name":"hello-service","namespace":"default","annotations":{"cloud.google.com/load-balancer-type": ""}},"spec":{"ports":[{"protocol":"TCP","port":8000,"targetPort":8080,"nodePort":31433}],"selector":{"app":"hello-app"},"type":"LoadBalancer","externalTrafficPolicy":"Cluster"}}`),
expectedMessage: missingLBAnnotationsMessage,
shouldAllow: false,
},
{
testName: "Reject Incorrectly Annotated Private Service (missing annotation val)",
cloudProvider: GCP,
kind: meta.GroupVersionKind{
Group: "",
Kind: "Service",
Version: "v1",
},
rawObject: []byte(`{"kind":"Service","apiVersion":"v1","metadata":{"name":"hello-service","namespace":"default","annotations":{"cloud.google.com/load-balancer-type": ""}},"spec":{"ports":[{"protocol":"TCP","port":8000,"targetPort":8080,"nodePort":31433}],"selector":{"app":"hello-app"},"type":"LoadBalancer","externalTrafficPolicy":"Cluster"}}`),
expectedMessage: missingLBAnnotationsMessage,
shouldAllow: false,
},
{
testName: "Reject Incorrectly Annotated Private Service (Azure provider, AWS annotation)",
cloudProvider: Azure,
kind: meta.GroupVersionKind{
Group: "",
Kind: "Service",
Version: "v1",
},
rawObject: []byte(`{"kind":"Service","apiVersion":"v1","metadata":{"name":"hello-service","namespace":"default","annotations":{"service.beta.kubernetes.io/aws-load-balancer-internal": "0.0.0.0/0"}},"spec":{"ports":[{"protocol":"TCP","port":8000,"targetPort":8080,"nodePort":31433}],"selector":{"app":"hello-app"},"type":"LoadBalancer","externalTrafficPolicy":"Cluster"}}`),
expectedMessage: "Service objects of type: LoadBalancer without an internal-only annotation cannot be deployed to this cluster",
shouldAllow: false,
},
{
testName: "Don't reject Ingress (<= v1.13)",
kind: meta.GroupVersionKind{
Group: "extensions",
Kind: "Ingress",
Version: "v1beta1",
},
rawObject: []byte(`{"kind":"Ingress","apiVersion":"v1beta1","group":"extensions","metadata":{"name":"hello-ingress","namespace":"default","annotations":{}},"spec":{"rules":[]}}`),
expectedMessage: "",
shouldAllow: true,
},
{
testName: "Don't reject Ingress (>= v1.14)",
kind: meta.GroupVersionKind{
Group: "networking.k8s.io",
Kind: "Ingress",
Version: "v1beta1",
},
rawObject: []byte(`{"kind":"Ingress","apiVersion":"v1beta1","group":"networking.k8s.io","metadata":{"name":"hello-ingress","namespace":"default","annotations":{}},"spec":{"rules":[]}}`),
expectedMessage: "",
shouldAllow: true,
},
{
testName: "Don't reject Pods",
kind: meta.GroupVersionKind{
Group: "",
Kind: "Pod",
Version: "v1",
},
rawObject: nil,
expectedMessage: "",
shouldAllow: true,
},
{
testName: "Don't reject Deployments",
kind: meta.GroupVersionKind{
Group: "apps",
Kind: "Deployment",
Version: "v1",
},
rawObject: nil,
expectedMessage: "",
shouldAllow: true,
},
}
for _, tt := range denyTests {
t.Run(tt.testName, func(t *testing.T) {
incomingReview := admission.AdmissionReview{
Request: &admission.AdmissionRequest{},
}
incomingReview.Request.Kind = tt.kind
incomingReview.Request.Object.Raw = tt.rawObject
resp, err := DenyPublicLoadBalancers(tt.ignoredNamespaces, tt.cloudProvider)(&incomingReview)
if err != nil {
if tt.expectedMessage != err.Error() {
t.Fatalf(testErrMessageMismatch, err.Error(), tt.expectedMessage)
}
if tt.shouldAllow {
t.Fatalf("incorrectly rejected admission for Kind: %v: %s", tt.kind, err.Error())
}
t.Logf("correctly rejected admission for Kind: %v: %s", tt.kind, err.Error())
return
}
if resp.Allowed != tt.shouldAllow {
t.Fatalf(testErrAdmissionMismatch, tt.kind, resp.Allowed, tt.shouldAllow)
}
})
}
}
func TestEnforcePodAnnotations(t *testing.T) {
t.Parallel()
var denyTests = []objectTest{
{
testName: "Allow Pod with required annotations",
requiredAnnotations: map[string]func(string) bool{
"questionable.services/hostname": func(s string) bool { return true },
"buildVersion": func(s string) bool { return strings.HasPrefix(s, "v") },
},
kind: meta.GroupVersionKind{
Group: "",
Kind: "Pod",
Version: "v1",
},
rawObject: []byte(`{"kind":"Pod","apiVersion":"v1","group":"","metadata":{"name":"hello-app","namespace":"default","annotations":{"questionable.services/hostname":"hello-app.questionable.services","buildVersion":"v1.0.2"}},"spec":{"containers":[{"name":"nginx","image":"nginx:latest"}]}}`),
expectedMessage: "",
shouldAllow: true,
},
{
testName: "Reject Pod with missing annotations",
requiredAnnotations: map[string]func(string) bool{
"questionable.services/hostname": func(s string) bool { return true },
},
kind: meta.GroupVersionKind{
Group: "",
Kind: "Pod",
Version: "v1",
},
// missing the "hostname" annotation
rawObject: []byte(`{"kind":"Pod","apiVersion":"v1","group":"","metadata":{"name":"hello-app","namespace":"default","annotations":{"buildVersion":"v1.0.2"}},"spec":{"containers":[{"name":"nginx","image":"nginx:latest"}]}}`),
expectedMessage: fmt.Sprintf("%s %s", podDeniedError, "map[questionable.services/hostname:key was not found]"),
shouldAllow: false,
},
{
testName: "Reject Pod with invalid annotation value",
requiredAnnotations: map[string]func(string) bool{
"buildVersion": func(s string) bool { return strings.HasPrefix(s, "v") }},
kind: meta.GroupVersionKind{
Group: "",
Kind: "Pod",
Version: "v1",
},
// buildVersion is missing the "v" in the version number
rawObject: []byte(`{"kind":"Pod","apiVersion":"v1","group":"","metadata":{"name":"hello-app","namespace":"default","annotations":{"buildVersion":"1.0.2"}},"spec":{"containers":[{"name":"nginx","image":"nginx:latest"}]}}`),
expectedMessage: fmt.Sprintf("%s %s", podDeniedError, "map[buildVersion:value did not match]"),
shouldAllow: false,
},
{
testName: "Allow admission to a whitelisted namespace",
requiredAnnotations: map[string]func(string) bool{
"buildVersion": func(s string) bool { return strings.HasPrefix(s, "v") }},
kind: meta.GroupVersionKind{
Group: "",
Kind: "Pod",
Version: "v1",
},
ignoredNamespaces: []string{"istio-system"},
object: &corev1.Pod{
TypeMeta: meta.TypeMeta{Kind: "Pod", APIVersion: "v1"},
ObjectMeta: meta.ObjectMeta{Namespace: "istio-system"},
Spec: corev1.PodSpec{Containers: []corev1.Container{{Name: "nginx", Image: "nginx:latest"}}},
},
expectedMessage: "",
shouldAllow: true,
},
{
testName: "Unhandled Kinds (Service) are correctly rejected",
kind: meta.GroupVersionKind{
Group: "",
Kind: "Service",
Version: "v1",
},
rawObject: []byte(`{"kind":"Service","apiVersion":"v1","metadata":{"name":"hello-service","namespace":"default","annotations":{}},"spec":{"ports":[{"protocol":"TCP","port":8000,"targetPort":8080,"nodePort":31433}],"selector":{"app":"hello-app"},"type":"LoadBalancer","externalTrafficPolicy":"Cluster"}}`),
expectedMessage: fmt.Sprintf("%s %s", unsupportedKindError, "Service"),
shouldAllow: false,
},
{
testName: "Allow correctly annotated Pods in a Deployment",
requiredAnnotations: map[string]func(string) bool{
"buildVersion": func(s string) bool { return strings.HasPrefix(s, "v") }},
kind: meta.GroupVersionKind{
Group: "apps",
Kind: "Deployment",
Version: "v1",
},
object: &appsv1.Deployment{
TypeMeta: meta.TypeMeta{Kind: "Deployment", APIVersion: "apps/v1"},
ObjectMeta: meta.ObjectMeta{Namespace: "default"},
Spec: appsv1.DeploymentSpec{Template: corev1.PodTemplateSpec{ObjectMeta: meta.ObjectMeta{Annotations: map[string]string{"buildVersion": "v1.0.0"}}, Spec: corev1.PodSpec{Containers: []corev1.Container{{Name: "nginx", Image: "nginx:latest"}}}}},
},
expectedMessage: "",
shouldAllow: true,
},
{
testName: "Reject unannotated Pods in a Deployment",
requiredAnnotations: map[string]func(string) bool{
"buildVersion": func(s string) bool { return strings.HasPrefix(s, "v") }},
kind: meta.GroupVersionKind{
Group: "apps",
Kind: "Deployment",
Version: "v1",
},
object: &appsv1.Deployment{
TypeMeta: meta.TypeMeta{Kind: "Deployment", APIVersion: "apps/v1"},
ObjectMeta: meta.ObjectMeta{Namespace: "default"},
Spec: appsv1.DeploymentSpec{Template: corev1.PodTemplateSpec{ObjectMeta: meta.ObjectMeta{}, Spec: corev1.PodSpec{Containers: []corev1.Container{{Name: "nginx", Image: "nginx:latest"}}}}},
},
expectedMessage: fmt.Sprintf("%s %s", podDeniedError, "map[buildVersion:key was not found]"),
shouldAllow: false,
},
{
testName: "Allow correctly annotated Pods in a DaemonSet",
requiredAnnotations: map[string]func(string) bool{
"buildVersion": func(s string) bool { return strings.HasPrefix(s, "v") }},
kind: meta.GroupVersionKind{
Group: "apps",
Kind: "DaemonSet",
Version: "v1",
},
rawObject: []byte(`{"kind":"DaemonSet","apiVersion":"v1","group":"apps","metadata":{"name":"hello-daemonset","namespace":"default","annotations":{}},"spec":{"template":{"metadata":{"annotations":{"buildVersion":"v1.0.0"}},"spec":{"containers":[{"name":"nginx","image":"nginx:latest"}]}}}}`),
expectedMessage: "",
shouldAllow: true,
},
{
testName: "Reject unannotated Pods in a DaemonSet",
requiredAnnotations: map[string]func(string) bool{
"buildVersion": func(s string) bool { return strings.HasPrefix(s, "v") }},
kind: meta.GroupVersionKind{
Group: "apps",
Kind: "DaemonSet",
Version: "v1",
},
rawObject: []byte(`{"kind":"DaemonSet","apiVersion":"v1","group":"apps","metadata":{"name":"hello-daemonset","namespace":"default","annotations":{}},"spec":{"template":{"metadata":{"annotations":{}},"spec":{"containers":[{"name":"nginx","image":"nginx:latest"}]}}}}`),
expectedMessage: fmt.Sprintf("%s %s", podDeniedError, "map[buildVersion:key was not found]"),
shouldAllow: false,
},
{
testName: "Allow correctly annotated Pods in a StatefulSet",
requiredAnnotations: map[string]func(string) bool{
"buildVersion": func(s string) bool { return strings.HasPrefix(s, "v") }},
kind: meta.GroupVersionKind{
Group: "apps",
Kind: "StatefulSet",
Version: "v1",
},
rawObject: []byte(`{"kind":"StatefulSet","apiVersion":"v1","group":"apps","metadata":{"name":"hello-statefulset","namespace":"default","annotations":{}},"spec":{"template":{"metadata":{"annotations":{"buildVersion":"v1.0.0"}},"spec":{"containers":[{"name":"nginx","image":"nginx:latest"}]}}}}`),
expectedMessage: "",
shouldAllow: true,
},
{
testName: "Reject unannotated Pods in a StatefulSet",
requiredAnnotations: map[string]func(string) bool{
"buildVersion": func(s string) bool { return strings.HasPrefix(s, "v") }},
kind: meta.GroupVersionKind{
Group: "apps",
Kind: "StatefulSet",
Version: "v1",
},
rawObject: []byte(`{"kind":"StatefulSet","apiVersion":"v1","group":"apps","metadata":{"name":"hello-statefulset","namespace":"default","annotations":{}},"spec":{"template":{"metadata":{"annotations":{}},"spec":{"containers":[{"name":"nginx","image":"nginx:latest"}]}}}}`),
expectedMessage: fmt.Sprintf("%s %s", podDeniedError, "map[buildVersion:key was not found]"),
shouldAllow: false,
},
{
testName: "Allow correctly annotated Pods in a Job",
requiredAnnotations: map[string]func(string) bool{
"buildVersion": func(s string) bool { return strings.HasPrefix(s, "v") }},
kind: meta.GroupVersionKind{
Group: "batch",
Kind: "Job",
Version: "v1",
},
object: &batchv1.Job{
TypeMeta: meta.TypeMeta{Kind: "Job", APIVersion: "batch/v1"},
ObjectMeta: meta.ObjectMeta{Name: "", Namespace: "default"},
Spec: batchv1.JobSpec{Template: corev1.PodTemplateSpec{ObjectMeta: meta.ObjectMeta{Annotations: map[string]string{"buildVersion": "v1.0.0"}}, Spec: corev1.PodSpec{Containers: []corev1.Container{{Name: "nginx", Image: "nginx:latest"}}}}},
},
expectedMessage: "",
shouldAllow: true,
},
{
testName: "Reject unannotated Pods in a Job",
requiredAnnotations: map[string]func(string) bool{
"buildVersion": func(s string) bool { return strings.HasPrefix(s, "v") }},
kind: meta.GroupVersionKind{
Group: "batch",
Kind: "Job",
Version: "v1",
},
object: &batchv1.Job{
TypeMeta: meta.TypeMeta{Kind: "Job", APIVersion: "batch/v1"},
ObjectMeta: meta.ObjectMeta{Name: "", Namespace: "default"},
Spec: batchv1.JobSpec{Template: corev1.PodTemplateSpec{ObjectMeta: meta.ObjectMeta{Name: ""}, Spec: corev1.PodSpec{Containers: []corev1.Container{{Name: "nginx", Image: "nginx:latest"}}}}},
},
expectedMessage: fmt.Sprintf("%s %s", podDeniedError, "map[buildVersion:key was not found]"),
shouldAllow: false,
},
{
testName: "Reject cases where the outer object is annotated, but the PodTemplateSpec is not",
requiredAnnotations: map[string]func(string) bool{
"buildVersion": func(s string) bool { return strings.HasPrefix(s, "v") }},
kind: meta.GroupVersionKind{
Group: "apps",
Kind: "Deployment",
Version: "v1",
},
object: &appsv1.Deployment{
TypeMeta: meta.TypeMeta{Kind: "Deployment", APIVersion: "apps/v1"},
ObjectMeta: meta.ObjectMeta{Namespace: "default", Annotations: map[string]string{
"buildVersion": "v1.0.0",
}},
Spec: appsv1.DeploymentSpec{Template: corev1.PodTemplateSpec{ObjectMeta: meta.ObjectMeta{Name: ""}, Spec: corev1.PodSpec{Containers: []corev1.Container{{Name: "nginx", Image: "nginx:latest"}}}}},
},
expectedMessage: fmt.Sprintf("%s %s", podDeniedError, "map[buildVersion:key was not found]"),
shouldAllow: false,
},
}
for _, tt := range denyTests {
t.Run(tt.testName, func(t *testing.T) {
incomingReview := admission.AdmissionReview{
Request: &admission.AdmissionRequest{},
}
incomingReview.Request.Kind = tt.kind
if tt.rawObject == nil {
serialized, err := json.Marshal(tt.object)
if err != nil {
t.Fatalf("could not marshal k8s API object: %v", err)
}
incomingReview.Request.Object.Raw = serialized
} else {
incomingReview.Request.Object.Raw = tt.rawObject
}
resp, err := EnforcePodAnnotations(tt.ignoredNamespaces, tt.requiredAnnotations)(&incomingReview)
if err != nil {
if tt.expectedMessage != err.Error() {
t.Fatalf(testErrMessageMismatch, err.Error(), tt.expectedMessage)
}
if tt.shouldAllow {
t.Fatalf("incorrectly rejected admission for Kind: %v: %s", tt.kind, err.Error())
}
t.Logf("correctly rejected admission for Kind: %v: %s", tt.kind, err.Error())
return
}
if resp.Allowed != tt.shouldAllow {
t.Fatalf(testErrAdmissionMismatch, tt.kind, resp.Allowed, tt.shouldAllow)
}
})
}
}