-
Notifications
You must be signed in to change notification settings - Fork 39.1k
/
webhook.go
2502 lines (2301 loc) · 103 KB
/
webhook.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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apimachinery
import (
"fmt"
"reflect"
"strings"
"time"
"k8s.io/utils/pointer"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
crdclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/uuid"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/dynamic"
clientset "k8s.io/client-go/kubernetes"
"k8s.io/client-go/util/retry"
"k8s.io/kubernetes/test/e2e/framework"
e2edeploy "k8s.io/kubernetes/test/e2e/framework/deployment"
e2epod "k8s.io/kubernetes/test/e2e/framework/pod"
"k8s.io/kubernetes/test/utils/crd"
imageutils "k8s.io/kubernetes/test/utils/image"
"github.com/onsi/ginkgo"
"github.com/onsi/gomega"
// ensure libs have a chance to initialize
_ "github.com/stretchr/testify/assert"
)
const (
secretName = "sample-webhook-secret"
deploymentName = "sample-webhook-deployment"
serviceName = "e2e-test-webhook"
roleBindingName = "webhook-auth-reader"
skipNamespaceLabelKey = "skip-webhook-admission"
skipNamespaceLabelValue = "yes"
skippedNamespaceName = "exempted-namesapce"
disallowedPodName = "disallowed-pod"
toBeAttachedPodName = "to-be-attached-pod"
hangingPodName = "hanging-pod"
disallowedConfigMapName = "disallowed-configmap"
allowedConfigMapName = "allowed-configmap"
failNamespaceLabelKey = "fail-closed-webhook"
failNamespaceLabelValue = "yes"
failNamespaceName = "fail-closed-namesapce"
addedLabelKey = "added-label"
addedLabelValue = "yes"
)
var _ = SIGDescribe("AdmissionWebhook [Privileged:ClusterAdmin]", func() {
var context *certContext
f := framework.NewDefaultFramework("webhook")
servicePort := int32(8443)
containerPort := int32(8444)
var client clientset.Interface
var namespaceName string
ginkgo.BeforeEach(func() {
client = f.ClientSet
namespaceName = f.Namespace.Name
// Make sure the namespace created for the test is labeled to be selected by the webhooks
labelNamespace(f, f.Namespace.Name)
createWebhookConfigurationReadyNamespace(f)
ginkgo.By("Setting up server cert")
context = setupServerCert(namespaceName, serviceName)
createAuthReaderRoleBinding(f, namespaceName)
deployWebhookAndService(f, imageutils.GetE2EImage(imageutils.Agnhost), context, servicePort, containerPort)
})
ginkgo.AfterEach(func() {
cleanWebhookTest(client, namespaceName)
})
/*
Release : v1.16
Testname: Admission webhook, discovery document
Description: The admissionregistration.k8s.io API group MUST exists in the /apis discovery document.
The admissionregistration.k8s.io/v1 API group/version MUST exists in the /apis discovery document.
The mutatingwebhookconfigurations and validatingwebhookconfigurations resources MUST exist in the
/apis/admissionregistration.k8s.io/v1 discovery document.
*/
framework.ConformanceIt("should include webhook resources in discovery documents", func() {
{
ginkgo.By("fetching the /apis discovery document")
apiGroupList := &metav1.APIGroupList{}
err := client.Discovery().RESTClient().Get().AbsPath("/apis").Do().Into(apiGroupList)
framework.ExpectNoError(err, "fetching /apis")
ginkgo.By("finding the admissionregistration.k8s.io API group in the /apis discovery document")
var group *metav1.APIGroup
for _, g := range apiGroupList.Groups {
if g.Name == admissionregistrationv1.GroupName {
group = &g
break
}
}
framework.ExpectNotEqual(group, nil, "admissionregistration.k8s.io API group not found in /apis discovery document")
ginkgo.By("finding the admissionregistration.k8s.io/v1 API group/version in the /apis discovery document")
var version *metav1.GroupVersionForDiscovery
for _, v := range group.Versions {
if v.Version == admissionregistrationv1.SchemeGroupVersion.Version {
version = &v
break
}
}
framework.ExpectNotEqual(version, nil, "admissionregistration.k8s.io/v1 API group version not found in /apis discovery document")
}
{
ginkgo.By("fetching the /apis/admissionregistration.k8s.io discovery document")
group := &metav1.APIGroup{}
err := client.Discovery().RESTClient().Get().AbsPath("/apis/admissionregistration.k8s.io").Do().Into(group)
framework.ExpectNoError(err, "fetching /apis/admissionregistration.k8s.io")
framework.ExpectEqual(group.Name, admissionregistrationv1.GroupName, "verifying API group name in /apis/admissionregistration.k8s.io discovery document")
ginkgo.By("finding the admissionregistration.k8s.io/v1 API group/version in the /apis/admissionregistration.k8s.io discovery document")
var version *metav1.GroupVersionForDiscovery
for _, v := range group.Versions {
if v.Version == admissionregistrationv1.SchemeGroupVersion.Version {
version = &v
break
}
}
framework.ExpectNotEqual(version, nil, "admissionregistration.k8s.io/v1 API group version not found in /apis/admissionregistration.k8s.io discovery document")
}
{
ginkgo.By("fetching the /apis/admissionregistration.k8s.io/v1 discovery document")
apiResourceList := &metav1.APIResourceList{}
err := client.Discovery().RESTClient().Get().AbsPath("/apis/admissionregistration.k8s.io/v1").Do().Into(apiResourceList)
framework.ExpectNoError(err, "fetching /apis/admissionregistration.k8s.io/v1")
framework.ExpectEqual(apiResourceList.GroupVersion, admissionregistrationv1.SchemeGroupVersion.String(), "verifying API group/version in /apis/admissionregistration.k8s.io/v1 discovery document")
ginkgo.By("finding mutatingwebhookconfigurations and validatingwebhookconfigurations resources in the /apis/admissionregistration.k8s.io/v1 discovery document")
var (
mutatingWebhookResource *metav1.APIResource
validatingWebhookResource *metav1.APIResource
)
for i := range apiResourceList.APIResources {
if apiResourceList.APIResources[i].Name == "mutatingwebhookconfigurations" {
mutatingWebhookResource = &apiResourceList.APIResources[i]
}
if apiResourceList.APIResources[i].Name == "validatingwebhookconfigurations" {
validatingWebhookResource = &apiResourceList.APIResources[i]
}
}
framework.ExpectNotEqual(mutatingWebhookResource, nil, "mutatingwebhookconfigurations resource not found in /apis/admissionregistration.k8s.io/v1 discovery document")
framework.ExpectNotEqual(validatingWebhookResource, nil, "validatingwebhookconfigurations resource not found in /apis/admissionregistration.k8s.io/v1 discovery document")
}
})
/*
Release : v1.16
Testname: Admission webhook, deny create
Description: Register an admission webhook configuration that admits pod and configmap. Attempts to create
non-compliant pods and configmaps, or update/patch compliant pods and configmaps to be non-compliant MUST
be denied. An attempt to create a pod that causes a webhook to hang MUST result in a webhook timeout error,
and the pod creation MUST be denied. An attempt to create a non-compliant configmap in a whitelisted
namespace based on the webhook namespace selector MUST be allowed.
*/
framework.ConformanceIt("should be able to deny pod and configmap creation", func() {
webhookCleanup := registerWebhook(f, f.UniqueName, context, servicePort)
defer webhookCleanup()
testWebhook(f)
})
/*
Release : v1.16
Testname: Admission webhook, deny attach
Description: Register an admission webhook configuration that denies connecting to a pod's attach sub-resource.
Attempts to attach MUST be denied.
*/
framework.ConformanceIt("should be able to deny attaching pod", func() {
webhookCleanup := registerWebhookForAttachingPod(f, f.UniqueName, context, servicePort)
defer webhookCleanup()
testAttachingPodWebhook(f)
})
/*
Release : v1.16
Testname: Admission webhook, deny custom resource create and delete
Description: Register an admission webhook configuration that denies creation, update and deletion of
custom resources. Attempts to create, update and delete custom resources MUST be denied.
*/
framework.ConformanceIt("should be able to deny custom resource creation, update and deletion", func() {
testcrd, err := crd.CreateTestCRD(f)
if err != nil {
return
}
defer testcrd.CleanUp()
webhookCleanup := registerWebhookForCustomResource(f, f.UniqueName, context, testcrd, servicePort)
defer webhookCleanup()
testCustomResourceWebhook(f, testcrd.Crd, testcrd.DynamicClients["v1"])
testBlockingCustomResourceUpdateDeletion(f, testcrd.Crd, testcrd.DynamicClients["v1"])
})
/*
Release : v1.16
Testname: Admission webhook, fail closed
Description: Register a webhook with a fail closed policy and without CA bundle so that it cannot be called.
Attempt operations that require the admission webhook; all MUST be denied.
*/
framework.ConformanceIt("should unconditionally reject operations on fail closed webhook", func() {
webhookCleanup := registerFailClosedWebhook(f, f.UniqueName, context, servicePort)
defer webhookCleanup()
testFailClosedWebhook(f)
})
/*
Release : v1.16
Testname: Admission webhook, ordered mutation
Description: Register a mutating webhook configuration with two webhooks that admit configmaps, one that
adds a data key if the configmap already has a specific key, and another that adds a key if the key added by
the first webhook is present. Attempt to create a config map; both keys MUST be added to the config map.
*/
framework.ConformanceIt("should mutate configmap", func() {
webhookCleanup := registerMutatingWebhookForConfigMap(f, f.UniqueName, context, servicePort)
defer webhookCleanup()
testMutatingConfigMapWebhook(f)
})
/*
Release : v1.16
Testname: Admission webhook, mutation with defaulting
Description: Register a mutating webhook that adds an InitContainer to pods. Attempt to create a pod;
the InitContainer MUST be added the TerminationMessagePolicy MUST be defaulted.
*/
framework.ConformanceIt("should mutate pod and apply defaults after mutation", func() {
webhookCleanup := registerMutatingWebhookForPod(f, f.UniqueName, context, servicePort)
defer webhookCleanup()
testMutatingPodWebhook(f)
})
/*
Release : v1.16
Testname: Admission webhook, admission control not allowed on webhook configuration objects
Description: Register webhooks that mutate and deny deletion of webhook configuration objects. Attempt to create
and delete a webhook configuration object; both operations MUST be allowed and the webhook configuration object
MUST NOT be mutated the webhooks.
*/
framework.ConformanceIt("should not be able to mutate or prevent deletion of webhook configuration objects", func() {
validatingWebhookCleanup := registerValidatingWebhookForWebhookConfigurations(f, f.UniqueName+"blocking", context, servicePort)
defer validatingWebhookCleanup()
mutatingWebhookCleanup := registerMutatingWebhookForWebhookConfigurations(f, f.UniqueName+"blocking", context, servicePort)
defer mutatingWebhookCleanup()
testWebhooksForWebhookConfigurations(f, f.UniqueName, context, servicePort)
})
/*
Release : v1.16
Testname: Admission webhook, mutate custom resource
Description: Register a webhook that mutates a custom resource. Attempt to create custom resource object;
the custom resource MUST be mutated.
*/
framework.ConformanceIt("should mutate custom resource", func() {
testcrd, err := crd.CreateTestCRD(f)
if err != nil {
return
}
defer testcrd.CleanUp()
webhookCleanup := registerMutatingWebhookForCustomResource(f, f.UniqueName, context, testcrd, servicePort)
defer webhookCleanup()
testMutatingCustomResourceWebhook(f, testcrd.Crd, testcrd.DynamicClients["v1"], false)
})
/*
Release : v1.16
Testname: Admission webhook, deny custom resource definition
Description: Register a webhook that denies custom resource definition create. Attempt to create a
custom resource definition; the create request MUST be denied.
*/
framework.ConformanceIt("should deny crd creation", func() {
crdWebhookCleanup := registerValidatingWebhookForCRD(f, f.UniqueName, context, servicePort)
defer crdWebhookCleanup()
testCRDDenyWebhook(f)
})
/*
Release : v1.16
Testname: Admission webhook, mutate custom resource with different stored version
Description: Register a webhook that mutates custom resources on create and update. Register a custom resource
definition using v1 as stored version. Create a custom resource. Patch the custom resource definition to use v2 as
the stored version. Attempt to patch the custom resource with a new field and value; the patch MUST be applied
successfully.
*/
framework.ConformanceIt("should mutate custom resource with different stored version", func() {
testcrd, err := createAdmissionWebhookMultiVersionTestCRDWithV1Storage(f)
if err != nil {
return
}
defer testcrd.CleanUp()
webhookCleanup := registerMutatingWebhookForCustomResource(f, f.UniqueName, context, testcrd, servicePort)
defer webhookCleanup()
testMultiVersionCustomResourceWebhook(f, testcrd)
})
/*
Release : v1.16
Testname: Admission webhook, mutate custom resource with pruning
Description: Register mutating webhooks that adds fields to custom objects. Register a custom resource definition
with a schema that includes only one of the data keys added by the webhooks. Attempt to a custom resource;
the fields included in the schema MUST be present and field not included in the schema MUST NOT be present.
*/
framework.ConformanceIt("should mutate custom resource with pruning", func() {
const prune = true
testcrd, err := createAdmissionWebhookMultiVersionTestCRDWithV1Storage(f, func(crd *apiextensionsv1.CustomResourceDefinition) {
crd.Spec.PreserveUnknownFields = false
for i := range crd.Spec.Versions {
crd.Spec.Versions[i].Schema = &apiextensionsv1.CustomResourceValidation{
OpenAPIV3Schema: &apiextensionsv1.JSONSchemaProps{
Type: "object",
Properties: map[string]apiextensionsv1.JSONSchemaProps{
"data": {
Type: "object",
Properties: map[string]apiextensionsv1.JSONSchemaProps{
"mutation-start": {Type: "string"},
"mutation-stage-1": {Type: "string"},
// mutation-stage-2 is intentionally missing such that it is pruned
},
},
},
},
}
}
})
if err != nil {
return
}
defer testcrd.CleanUp()
webhookCleanup := registerMutatingWebhookForCustomResource(f, f.UniqueName, context, testcrd, servicePort)
defer webhookCleanup()
testMutatingCustomResourceWebhook(f, testcrd.Crd, testcrd.DynamicClients["v1"], prune)
})
/*
Release : v1.16
Testname: Admission webhook, honor timeout
Description: Using a webhook that waits 5 seconds before admitting objects, configure the webhook with combinations
of timeouts and failure policy values. Attempt to create a config map with each combination. Requests MUST
timeout if the configured webhook timeout is less than 5 seconds and failure policy is fail. Requests must not timeout if
the failure policy is ignore. Requests MUST NOT timeout if configured webhook timeout is 10 seconds (much longer
than the webhook wait duration).
*/
framework.ConformanceIt("should honor timeout", func() {
policyFail := admissionregistrationv1.Fail
policyIgnore := admissionregistrationv1.Ignore
ginkgo.By("Setting timeout (1s) shorter than webhook latency (5s)")
slowWebhookCleanup := registerSlowWebhook(f, f.UniqueName, context, &policyFail, pointer.Int32Ptr(1), servicePort)
testSlowWebhookTimeoutFailEarly(f)
slowWebhookCleanup()
ginkgo.By("Having no error when timeout is shorter than webhook latency and failure policy is ignore")
slowWebhookCleanup = registerSlowWebhook(f, f.UniqueName, context, &policyIgnore, pointer.Int32Ptr(1), servicePort)
testSlowWebhookTimeoutNoError(f)
slowWebhookCleanup()
ginkgo.By("Having no error when timeout is longer than webhook latency")
slowWebhookCleanup = registerSlowWebhook(f, f.UniqueName, context, &policyFail, pointer.Int32Ptr(10), servicePort)
testSlowWebhookTimeoutNoError(f)
slowWebhookCleanup()
ginkgo.By("Having no error when timeout is empty (defaulted to 10s in v1)")
slowWebhookCleanup = registerSlowWebhook(f, f.UniqueName, context, &policyFail, nil, servicePort)
testSlowWebhookTimeoutNoError(f)
slowWebhookCleanup()
})
/*
Release : v1.16
Testname: Admission webhook, update validating webhook
Description: Register a validating admission webhook configuration. Update the webhook to not apply to the create
operation and attempt to create an object; the webhook MUST NOT deny the create. Patch the webhook to apply to the
create operation again and attempt to create an object; the webhook MUST deny the create.
*/
framework.ConformanceIt("patching/updating a validating webhook should work", func() {
client := f.ClientSet
admissionClient := client.AdmissionregistrationV1()
ginkgo.By("Creating a validating webhook configuration")
hook, err := createValidatingWebhookConfiguration(f, &admissionregistrationv1.ValidatingWebhookConfiguration{
ObjectMeta: metav1.ObjectMeta{
Name: f.UniqueName,
},
Webhooks: []admissionregistrationv1.ValidatingWebhook{
newDenyConfigMapWebhookFixture(f, context, servicePort),
newValidatingIsReadyWebhookFixture(f, context, servicePort),
},
})
framework.ExpectNoError(err, "Creating validating webhook configuration")
defer func() {
err := client.AdmissionregistrationV1().ValidatingWebhookConfigurations().Delete(hook.Name, nil)
framework.ExpectNoError(err, "Deleting validating webhook configuration")
}()
// ensure backend is ready before proceeding
err = waitWebhookConfigurationReady(f)
framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
ginkgo.By("Creating a configMap that does not comply to the validation webhook rules")
err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
cm := namedNonCompliantConfigMap(string(uuid.NewUUID()), f)
_, err = client.CoreV1().ConfigMaps(f.Namespace.Name).Create(cm)
if err == nil {
err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(cm.Name, nil)
framework.ExpectNoError(err, "Deleting successfully created configMap")
return false, nil
}
if !strings.Contains(err.Error(), "denied") {
return false, err
}
return true, nil
})
ginkgo.By("Updating a validating webhook configuration's rules to not include the create operation")
err = retry.RetryOnConflict(retry.DefaultRetry, func() error {
h, err := admissionClient.ValidatingWebhookConfigurations().Get(f.UniqueName, metav1.GetOptions{})
framework.ExpectNoError(err, "Getting validating webhook configuration")
h.Webhooks[0].Rules[0].Operations = []admissionregistrationv1.OperationType{admissionregistrationv1.Update}
_, err = admissionClient.ValidatingWebhookConfigurations().Update(h)
return err
})
framework.ExpectNoError(err, "Updating validating webhook configuration")
ginkgo.By("Creating a configMap that does not comply to the validation webhook rules")
err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
cm := namedNonCompliantConfigMap(string(uuid.NewUUID()), f)
_, err = client.CoreV1().ConfigMaps(f.Namespace.Name).Create(cm)
if err != nil {
if !strings.Contains(err.Error(), "denied") {
return false, err
}
return false, nil
}
err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(cm.Name, nil)
framework.ExpectNoError(err, "Deleting successfully created configMap")
return true, nil
})
framework.ExpectNoError(err, "Waiting for configMap in namespace %s to be allowed creation since webhook was updated to not validate create", f.Namespace.Name)
ginkgo.By("Patching a validating webhook configuration's rules to include the create operation")
hook, err = admissionClient.ValidatingWebhookConfigurations().Patch(
f.UniqueName,
types.JSONPatchType,
[]byte(`[{"op": "replace", "path": "/webhooks/0/rules/0/operations", "value": ["CREATE"]}]`))
framework.ExpectNoError(err, "Patching validating webhook configuration")
ginkgo.By("Creating a configMap that does not comply to the validation webhook rules")
err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
cm := namedNonCompliantConfigMap(string(uuid.NewUUID()), f)
_, err = client.CoreV1().ConfigMaps(f.Namespace.Name).Create(cm)
if err == nil {
err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(cm.Name, nil)
framework.ExpectNoError(err, "Deleting successfully created configMap")
return false, nil
}
if !strings.Contains(err.Error(), "denied") {
return false, err
}
return true, nil
})
framework.ExpectNoError(err, "Waiting for configMap in namespace %s to be denied creation by validating webhook", f.Namespace.Name)
})
/*
Release : v1.16
Testname: Admission webhook, update mutating webhook
Description: Register a mutating admission webhook configuration. Update the webhook to not apply to the create
operation and attempt to create an object; the webhook MUST NOT mutate the object. Patch the webhook to apply to the
create operation again and attempt to create an object; the webhook MUST mutate the object.
*/
framework.ConformanceIt("patching/updating a mutating webhook should work", func() {
client := f.ClientSet
admissionClient := client.AdmissionregistrationV1()
ginkgo.By("Creating a mutating webhook configuration")
hook, err := createMutatingWebhookConfiguration(f, &admissionregistrationv1.MutatingWebhookConfiguration{
ObjectMeta: metav1.ObjectMeta{
Name: f.UniqueName,
},
Webhooks: []admissionregistrationv1.MutatingWebhook{
newMutateConfigMapWebhookFixture(f, context, 1, servicePort),
newMutatingIsReadyWebhookFixture(f, context, servicePort),
},
})
framework.ExpectNoError(err, "Creating mutating webhook configuration")
defer func() {
err := client.AdmissionregistrationV1().MutatingWebhookConfigurations().Delete(hook.Name, nil)
framework.ExpectNoError(err, "Deleting mutating webhook configuration")
}()
// ensure backend is ready before proceeding
err = waitWebhookConfigurationReady(f)
framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
hook, err = admissionClient.MutatingWebhookConfigurations().Get(f.UniqueName, metav1.GetOptions{})
framework.ExpectNoError(err, "Getting mutating webhook configuration")
ginkgo.By("Updating a mutating webhook configuration's rules to not include the create operation")
hook.Webhooks[0].Rules[0].Operations = []admissionregistrationv1.OperationType{admissionregistrationv1.Update}
hook, err = admissionClient.MutatingWebhookConfigurations().Update(hook)
framework.ExpectNoError(err, "Updating mutating webhook configuration")
ginkgo.By("Creating a configMap that should not be mutated")
err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
cm := namedToBeMutatedConfigMap(string(uuid.NewUUID()), f)
created, err := client.CoreV1().ConfigMaps(f.Namespace.Name).Create(cm)
if err != nil {
return false, err
}
err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(cm.Name, nil)
framework.ExpectNoError(err, "Deleting successfully created configMap")
_, ok := created.Data["mutation-stage-1"]
return !ok, nil
})
framework.ExpectNoError(err, "Waiting for configMap in namespace %s this is not mutated", f.Namespace.Name)
ginkgo.By("Patching a mutating webhook configuration's rules to include the create operation")
hook, err = admissionClient.MutatingWebhookConfigurations().Patch(
f.UniqueName,
types.JSONPatchType,
[]byte(`[{"op": "replace", "path": "/webhooks/0/rules/0/operations", "value": ["CREATE"]}]`))
framework.ExpectNoError(err, "Patching mutating webhook configuration")
ginkgo.By("Creating a configMap that should be mutated")
err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
cm := namedToBeMutatedConfigMap(string(uuid.NewUUID()), f)
created, err := client.CoreV1().ConfigMaps(f.Namespace.Name).Create(cm)
if err != nil {
return false, err
}
err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(cm.Name, nil)
framework.ExpectNoError(err, "Deleting successfully created configMap")
_, ok := created.Data["mutation-stage-1"]
return ok, nil
})
framework.ExpectNoError(err, "Waiting for configMap in namespace %s to be mutated", f.Namespace.Name)
})
/*
Release : v1.16
Testname: Admission webhook, list validating webhooks
Description: Create 10 validating webhook configurations, all with a label. Attempt to list the webhook
configurations matching the label; all the created webhook configurations MUST be present. Attempt to create an
object; the create MUST be denied. Attempt to remove the webhook configurations matching the label with deletecollection;
all webhook configurations MUST be deleted. Attempt to create an object; the create MUST NOT be denied.
*/
framework.ConformanceIt("listing validating webhooks should work", func() {
testListSize := 10
testUUID := string(uuid.NewUUID())
for i := 0; i < testListSize; i++ {
name := fmt.Sprintf("%s-%d", f.UniqueName, i)
_, err := createValidatingWebhookConfiguration(f, &admissionregistrationv1.ValidatingWebhookConfiguration{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Labels: map[string]string{"e2e-list-test-uuid": testUUID},
},
Webhooks: []admissionregistrationv1.ValidatingWebhook{
newDenyConfigMapWebhookFixture(f, context, servicePort),
newValidatingIsReadyWebhookFixture(f, context, servicePort),
},
})
framework.ExpectNoError(err, "Creating validating webhook configuration")
}
selectorListOpts := metav1.ListOptions{LabelSelector: "e2e-list-test-uuid=" + testUUID}
ginkgo.By("Listing all of the created validation webhooks")
list, err := client.AdmissionregistrationV1().ValidatingWebhookConfigurations().List(selectorListOpts)
framework.ExpectNoError(err, "Listing validating webhook configurations")
framework.ExpectEqual(len(list.Items), testListSize)
// ensure backend is ready before proceeding
err = waitWebhookConfigurationReady(f)
framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
ginkgo.By("Creating a configMap that does not comply to the validation webhook rules")
err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
cm := namedNonCompliantConfigMap(string(uuid.NewUUID()), f)
_, err = client.CoreV1().ConfigMaps(f.Namespace.Name).Create(cm)
if err == nil {
err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(cm.Name, nil)
framework.ExpectNoError(err, "Deleting successfully created configMap")
return false, nil
}
if !strings.Contains(err.Error(), "denied") {
return false, err
}
return true, nil
})
framework.ExpectNoError(err, "Waiting for configMap in namespace %s to be denied creation by validating webhook", f.Namespace.Name)
ginkgo.By("Deleting the collection of validation webhooks")
err = client.AdmissionregistrationV1().ValidatingWebhookConfigurations().DeleteCollection(nil, selectorListOpts)
framework.ExpectNoError(err, "Deleting collection of validating webhook configurations")
ginkgo.By("Creating a configMap that does not comply to the validation webhook rules")
err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
cm := namedNonCompliantConfigMap(string(uuid.NewUUID()), f)
_, err = client.CoreV1().ConfigMaps(f.Namespace.Name).Create(cm)
if err != nil {
if !strings.Contains(err.Error(), "denied") {
return false, err
}
return false, nil
}
err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(cm.Name, nil)
framework.ExpectNoError(err, "Deleting successfully created configMap")
return true, nil
})
framework.ExpectNoError(err, "Waiting for configMap in namespace %s to be allowed creation since there are no webhooks", f.Namespace.Name)
})
/*
Release : v1.16
Testname: Admission webhook, list mutating webhooks
Description: Create 10 mutating webhook configurations, all with a label. Attempt to list the webhook
configurations matching the label; all the created webhook configurations MUST be present. Attempt to create an
object; the object MUST be mutated. Attempt to remove the webhook configurations matching the label with deletecollection;
all webhook configurations MUST be deleted. Attempt to create an object; the object MUST NOT be mutated.
*/
framework.ConformanceIt("listing mutating webhooks should work", func() {
testListSize := 10
testUUID := string(uuid.NewUUID())
for i := 0; i < testListSize; i++ {
name := fmt.Sprintf("%s-%d", f.UniqueName, i)
_, err := createMutatingWebhookConfiguration(f, &admissionregistrationv1.MutatingWebhookConfiguration{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Labels: map[string]string{"e2e-list-test-uuid": testUUID},
},
Webhooks: []admissionregistrationv1.MutatingWebhook{
newMutateConfigMapWebhookFixture(f, context, 1, servicePort),
newMutatingIsReadyWebhookFixture(f, context, servicePort),
},
})
framework.ExpectNoError(err, "Creating mutating webhook configuration")
}
selectorListOpts := metav1.ListOptions{LabelSelector: "e2e-list-test-uuid=" + testUUID}
ginkgo.By("Listing all of the created validation webhooks")
list, err := client.AdmissionregistrationV1().MutatingWebhookConfigurations().List(selectorListOpts)
framework.ExpectNoError(err, "Listing mutating webhook configurations")
framework.ExpectEqual(len(list.Items), testListSize)
// ensure backend is ready before proceeding
err = waitWebhookConfigurationReady(f)
framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
ginkgo.By("Creating a configMap that should be mutated")
err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
cm := namedToBeMutatedConfigMap(string(uuid.NewUUID()), f)
created, err := client.CoreV1().ConfigMaps(f.Namespace.Name).Create(cm)
if err != nil {
return false, err
}
err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(cm.Name, nil)
framework.ExpectNoError(err, "Deleting successfully created configMap")
_, ok := created.Data["mutation-stage-1"]
return ok, nil
})
framework.ExpectNoError(err, "Waiting for configMap in namespace %s to be mutated", f.Namespace.Name)
ginkgo.By("Deleting the collection of validation webhooks")
err = client.AdmissionregistrationV1().MutatingWebhookConfigurations().DeleteCollection(nil, selectorListOpts)
framework.ExpectNoError(err, "Deleting collection of mutating webhook configurations")
ginkgo.By("Creating a configMap that should not be mutated")
err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
cm := namedToBeMutatedConfigMap(string(uuid.NewUUID()), f)
created, err := client.CoreV1().ConfigMaps(f.Namespace.Name).Create(cm)
if err != nil {
return false, err
}
err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(cm.Name, nil)
framework.ExpectNoError(err, "Deleting successfully created configMap")
_, ok := created.Data["mutation-stage-1"]
return !ok, nil
})
framework.ExpectNoError(err, "Waiting for configMap in namespace %s this is not mutated", f.Namespace.Name)
})
})
func createAuthReaderRoleBinding(f *framework.Framework, namespace string) {
ginkgo.By("Create role binding to let webhook read extension-apiserver-authentication")
client := f.ClientSet
// Create the role binding to allow the webhook read the extension-apiserver-authentication configmap
_, err := client.RbacV1().RoleBindings("kube-system").Create(&rbacv1.RoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: roleBindingName,
Annotations: map[string]string{
rbacv1.AutoUpdateAnnotationKey: "true",
},
},
RoleRef: rbacv1.RoleRef{
APIGroup: "",
Kind: "Role",
Name: "extension-apiserver-authentication-reader",
},
// Webhook uses the default service account.
Subjects: []rbacv1.Subject{
{
Kind: "ServiceAccount",
Name: "default",
Namespace: namespace,
},
},
})
if err != nil && errors.IsAlreadyExists(err) {
framework.Logf("role binding %s already exists", roleBindingName)
} else {
framework.ExpectNoError(err, "creating role binding %s:webhook to access configMap", namespace)
}
}
func deployWebhookAndService(f *framework.Framework, image string, context *certContext, servicePort int32, containerPort int32) {
ginkgo.By("Deploying the webhook pod")
client := f.ClientSet
// Creating the secret that contains the webhook's cert.
secret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: secretName,
},
Type: v1.SecretTypeOpaque,
Data: map[string][]byte{
"tls.crt": context.cert,
"tls.key": context.key,
},
}
namespace := f.Namespace.Name
_, err := client.CoreV1().Secrets(namespace).Create(secret)
framework.ExpectNoError(err, "creating secret %q in namespace %q", secretName, namespace)
// Create the deployment of the webhook
podLabels := map[string]string{"app": "sample-webhook", "webhook": "true"}
replicas := int32(1)
zero := int64(0)
mounts := []v1.VolumeMount{
{
Name: "webhook-certs",
ReadOnly: true,
MountPath: "/webhook.local.config/certificates",
},
}
volumes := []v1.Volume{
{
Name: "webhook-certs",
VolumeSource: v1.VolumeSource{
Secret: &v1.SecretVolumeSource{SecretName: secretName},
},
},
}
containers := []v1.Container{
{
Name: "sample-webhook",
VolumeMounts: mounts,
Args: []string{
"webhook",
"--tls-cert-file=/webhook.local.config/certificates/tls.crt",
"--tls-private-key-file=/webhook.local.config/certificates/tls.key",
"--alsologtostderr",
"-v=4",
// Use a non-default port for containers.
fmt.Sprintf("--port=%d", containerPort),
},
ReadinessProbe: &v1.Probe{
Handler: v1.Handler{
HTTPGet: &v1.HTTPGetAction{
Scheme: v1.URISchemeHTTPS,
Port: intstr.FromInt(int(containerPort)),
Path: "/readyz",
},
},
PeriodSeconds: 1,
SuccessThreshold: 1,
FailureThreshold: 30,
},
Image: image,
Ports: []v1.ContainerPort{{ContainerPort: containerPort}},
},
}
d := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: deploymentName,
Labels: podLabels,
},
Spec: appsv1.DeploymentSpec{
Replicas: &replicas,
Selector: &metav1.LabelSelector{
MatchLabels: podLabels,
},
Strategy: appsv1.DeploymentStrategy{
Type: appsv1.RollingUpdateDeploymentStrategyType,
},
Template: v1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: podLabels,
},
Spec: v1.PodSpec{
TerminationGracePeriodSeconds: &zero,
Containers: containers,
Volumes: volumes,
},
},
},
}
deployment, err := client.AppsV1().Deployments(namespace).Create(d)
framework.ExpectNoError(err, "creating deployment %s in namespace %s", deploymentName, namespace)
ginkgo.By("Wait for the deployment to be ready")
err = e2edeploy.WaitForDeploymentRevisionAndImage(client, namespace, deploymentName, "1", image)
framework.ExpectNoError(err, "waiting for the deployment of image %s in %s in %s to complete", image, deploymentName, namespace)
err = e2edeploy.WaitForDeploymentComplete(client, deployment)
framework.ExpectNoError(err, "waiting for the deployment status valid", image, deploymentName, namespace)
ginkgo.By("Deploying the webhook service")
serviceLabels := map[string]string{"webhook": "true"}
service := &v1.Service{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
Name: serviceName,
Labels: map[string]string{"test": "webhook"},
},
Spec: v1.ServiceSpec{
Selector: serviceLabels,
Ports: []v1.ServicePort{
{
Protocol: "TCP",
Port: servicePort,
TargetPort: intstr.FromInt(int(containerPort)),
},
},
},
}
_, err = client.CoreV1().Services(namespace).Create(service)
framework.ExpectNoError(err, "creating service %s in namespace %s", serviceName, namespace)
ginkgo.By("Verifying the service has paired with the endpoint")
err = framework.WaitForServiceEndpointsNum(client, namespace, serviceName, 1, 1*time.Second, 30*time.Second)
framework.ExpectNoError(err, "waiting for service %s/%s have %d endpoint", namespace, serviceName, 1)
}
func strPtr(s string) *string { return &s }
func registerWebhook(f *framework.Framework, configName string, context *certContext, servicePort int32) func() {
client := f.ClientSet
ginkgo.By("Registering the webhook via the AdmissionRegistration API")
namespace := f.Namespace.Name
// A webhook that cannot talk to server, with fail-open policy
failOpenHook := failingWebhook(namespace, "fail-open.k8s.io", servicePort)
policyIgnore := admissionregistrationv1.Ignore
failOpenHook.FailurePolicy = &policyIgnore
failOpenHook.NamespaceSelector = &metav1.LabelSelector{
MatchLabels: map[string]string{f.UniqueName: "true"},
}
_, err := createValidatingWebhookConfiguration(f, &admissionregistrationv1.ValidatingWebhookConfiguration{
ObjectMeta: metav1.ObjectMeta{
Name: configName,
},
Webhooks: []admissionregistrationv1.ValidatingWebhook{
newDenyPodWebhookFixture(f, context, servicePort),
newDenyConfigMapWebhookFixture(f, context, servicePort),
// Server cannot talk to this webhook, so it always fails.
// Because this webhook is configured fail-open, request should be admitted after the call fails.
failOpenHook,
// Register a webhook that can be probed by marker requests to detect when the configuration is ready.
newValidatingIsReadyWebhookFixture(f, context, servicePort),
},
})
framework.ExpectNoError(err, "registering webhook config %s with namespace %s", configName, namespace)
err = waitWebhookConfigurationReady(f)
framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
return func() {
client.AdmissionregistrationV1().ValidatingWebhookConfigurations().Delete(configName, nil)
}
}
func registerWebhookForAttachingPod(f *framework.Framework, configName string, context *certContext, servicePort int32) func() {
client := f.ClientSet
ginkgo.By("Registering the webhook via the AdmissionRegistration API")
namespace := f.Namespace.Name
sideEffectsNone := admissionregistrationv1.SideEffectClassNone
_, err := createValidatingWebhookConfiguration(f, &admissionregistrationv1.ValidatingWebhookConfiguration{
ObjectMeta: metav1.ObjectMeta{
Name: configName,
},
Webhooks: []admissionregistrationv1.ValidatingWebhook{
{
Name: "deny-attaching-pod.k8s.io",
Rules: []admissionregistrationv1.RuleWithOperations{{
Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Connect},
Rule: admissionregistrationv1.Rule{
APIGroups: []string{""},
APIVersions: []string{"v1"},
Resources: []string{"pods/attach"},
},
}},
ClientConfig: admissionregistrationv1.WebhookClientConfig{
Service: &admissionregistrationv1.ServiceReference{
Namespace: namespace,
Name: serviceName,
Path: strPtr("/pods/attach"),
Port: pointer.Int32Ptr(servicePort),
},
CABundle: context.signingCert,
},
SideEffects: &sideEffectsNone,
AdmissionReviewVersions: []string{"v1", "v1beta1"},
// Scope the webhook to just this namespace
NamespaceSelector: &metav1.LabelSelector{
MatchLabels: map[string]string{f.UniqueName: "true"},
},
},
// Register a webhook that can be probed by marker requests to detect when the configuration is ready.
newValidatingIsReadyWebhookFixture(f, context, servicePort),
},
})
framework.ExpectNoError(err, "registering webhook config %s with namespace %s", configName, namespace)
err = waitWebhookConfigurationReady(f)
framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
return func() {
client.AdmissionregistrationV1().ValidatingWebhookConfigurations().Delete(configName, nil)
}
}
func registerMutatingWebhookForConfigMap(f *framework.Framework, configName string, context *certContext, servicePort int32) func() {
client := f.ClientSet
ginkgo.By("Registering the mutating configmap webhook via the AdmissionRegistration API")
namespace := f.Namespace.Name
_, err := createMutatingWebhookConfiguration(f, &admissionregistrationv1.MutatingWebhookConfiguration{
ObjectMeta: metav1.ObjectMeta{
Name: configName,
},
Webhooks: []admissionregistrationv1.MutatingWebhook{
newMutateConfigMapWebhookFixture(f, context, 1, servicePort),
newMutateConfigMapWebhookFixture(f, context, 2, servicePort),
// Register a webhook that can be probed by marker requests to detect when the configuration is ready.
newMutatingIsReadyWebhookFixture(f, context, servicePort),
},
})
framework.ExpectNoError(err, "registering mutating webhook config %s with namespace %s", configName, namespace)
err = waitWebhookConfigurationReady(f)
framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
return func() { client.AdmissionregistrationV1().MutatingWebhookConfigurations().Delete(configName, nil) }
}
func testMutatingConfigMapWebhook(f *framework.Framework) {
ginkgo.By("create a configmap that should be updated by the webhook")
client := f.ClientSet
configMap := toBeMutatedConfigMap(f)
mutatedConfigMap, err := client.CoreV1().ConfigMaps(f.Namespace.Name).Create(configMap)
framework.ExpectNoError(err)
expectedConfigMapData := map[string]string{
"mutation-start": "yes",