webhook.go 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package apimachinery
  14. import (
  15. "context"
  16. "fmt"
  17. "reflect"
  18. "strings"
  19. "time"
  20. "k8s.io/utils/pointer"
  21. admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
  22. appsv1 "k8s.io/api/apps/v1"
  23. v1 "k8s.io/api/core/v1"
  24. rbacv1 "k8s.io/api/rbac/v1"
  25. apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  26. crdclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
  27. apierrors "k8s.io/apimachinery/pkg/api/errors"
  28. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  29. "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
  30. "k8s.io/apimachinery/pkg/types"
  31. "k8s.io/apimachinery/pkg/util/intstr"
  32. "k8s.io/apimachinery/pkg/util/uuid"
  33. "k8s.io/apimachinery/pkg/util/wait"
  34. "k8s.io/client-go/dynamic"
  35. clientset "k8s.io/client-go/kubernetes"
  36. "k8s.io/client-go/util/retry"
  37. "k8s.io/kubernetes/test/e2e/framework"
  38. e2edeploy "k8s.io/kubernetes/test/e2e/framework/deployment"
  39. e2epod "k8s.io/kubernetes/test/e2e/framework/pod"
  40. "k8s.io/kubernetes/test/utils/crd"
  41. imageutils "k8s.io/kubernetes/test/utils/image"
  42. "github.com/onsi/ginkgo"
  43. "github.com/onsi/gomega"
  44. // ensure libs have a chance to initialize
  45. _ "github.com/stretchr/testify/assert"
  46. )
  47. const (
  48. secretName = "sample-webhook-secret"
  49. deploymentName = "sample-webhook-deployment"
  50. serviceName = "e2e-test-webhook"
  51. roleBindingName = "webhook-auth-reader"
  52. skipNamespaceLabelKey = "skip-webhook-admission"
  53. skipNamespaceLabelValue = "yes"
  54. skippedNamespaceName = "exempted-namesapce"
  55. disallowedPodName = "disallowed-pod"
  56. toBeAttachedPodName = "to-be-attached-pod"
  57. hangingPodName = "hanging-pod"
  58. disallowedConfigMapName = "disallowed-configmap"
  59. allowedConfigMapName = "allowed-configmap"
  60. failNamespaceLabelKey = "fail-closed-webhook"
  61. failNamespaceLabelValue = "yes"
  62. failNamespaceName = "fail-closed-namesapce"
  63. addedLabelKey = "added-label"
  64. addedLabelValue = "yes"
  65. )
  66. var _ = SIGDescribe("AdmissionWebhook [Privileged:ClusterAdmin]", func() {
  67. var certCtx *certContext
  68. f := framework.NewDefaultFramework("webhook")
  69. servicePort := int32(8443)
  70. containerPort := int32(8444)
  71. var client clientset.Interface
  72. var namespaceName string
  73. ginkgo.BeforeEach(func() {
  74. client = f.ClientSet
  75. namespaceName = f.Namespace.Name
  76. // Make sure the namespace created for the test is labeled to be selected by the webhooks
  77. labelNamespace(f, f.Namespace.Name)
  78. createWebhookConfigurationReadyNamespace(f)
  79. ginkgo.By("Setting up server cert")
  80. certCtx = setupServerCert(namespaceName, serviceName)
  81. createAuthReaderRoleBinding(f, namespaceName)
  82. deployWebhookAndService(f, imageutils.GetE2EImage(imageutils.Agnhost), certCtx, servicePort, containerPort)
  83. })
  84. ginkgo.AfterEach(func() {
  85. cleanWebhookTest(client, namespaceName)
  86. })
  87. /*
  88. Release : v1.16
  89. Testname: Admission webhook, discovery document
  90. Description: The admissionregistration.k8s.io API group MUST exists in the /apis discovery document.
  91. The admissionregistration.k8s.io/v1 API group/version MUST exists in the /apis discovery document.
  92. The mutatingwebhookconfigurations and validatingwebhookconfigurations resources MUST exist in the
  93. /apis/admissionregistration.k8s.io/v1 discovery document.
  94. */
  95. framework.ConformanceIt("should include webhook resources in discovery documents", func() {
  96. {
  97. ginkgo.By("fetching the /apis discovery document")
  98. apiGroupList := &metav1.APIGroupList{}
  99. err := client.Discovery().RESTClient().Get().AbsPath("/apis").Do(context.TODO()).Into(apiGroupList)
  100. framework.ExpectNoError(err, "fetching /apis")
  101. ginkgo.By("finding the admissionregistration.k8s.io API group in the /apis discovery document")
  102. var group *metav1.APIGroup
  103. for _, g := range apiGroupList.Groups {
  104. if g.Name == admissionregistrationv1.GroupName {
  105. group = &g
  106. break
  107. }
  108. }
  109. framework.ExpectNotEqual(group, nil, "admissionregistration.k8s.io API group not found in /apis discovery document")
  110. ginkgo.By("finding the admissionregistration.k8s.io/v1 API group/version in the /apis discovery document")
  111. var version *metav1.GroupVersionForDiscovery
  112. for _, v := range group.Versions {
  113. if v.Version == admissionregistrationv1.SchemeGroupVersion.Version {
  114. version = &v
  115. break
  116. }
  117. }
  118. framework.ExpectNotEqual(version, nil, "admissionregistration.k8s.io/v1 API group version not found in /apis discovery document")
  119. }
  120. {
  121. ginkgo.By("fetching the /apis/admissionregistration.k8s.io discovery document")
  122. group := &metav1.APIGroup{}
  123. err := client.Discovery().RESTClient().Get().AbsPath("/apis/admissionregistration.k8s.io").Do(context.TODO()).Into(group)
  124. framework.ExpectNoError(err, "fetching /apis/admissionregistration.k8s.io")
  125. framework.ExpectEqual(group.Name, admissionregistrationv1.GroupName, "verifying API group name in /apis/admissionregistration.k8s.io discovery document")
  126. ginkgo.By("finding the admissionregistration.k8s.io/v1 API group/version in the /apis/admissionregistration.k8s.io discovery document")
  127. var version *metav1.GroupVersionForDiscovery
  128. for _, v := range group.Versions {
  129. if v.Version == admissionregistrationv1.SchemeGroupVersion.Version {
  130. version = &v
  131. break
  132. }
  133. }
  134. framework.ExpectNotEqual(version, nil, "admissionregistration.k8s.io/v1 API group version not found in /apis/admissionregistration.k8s.io discovery document")
  135. }
  136. {
  137. ginkgo.By("fetching the /apis/admissionregistration.k8s.io/v1 discovery document")
  138. apiResourceList := &metav1.APIResourceList{}
  139. err := client.Discovery().RESTClient().Get().AbsPath("/apis/admissionregistration.k8s.io/v1").Do(context.TODO()).Into(apiResourceList)
  140. framework.ExpectNoError(err, "fetching /apis/admissionregistration.k8s.io/v1")
  141. framework.ExpectEqual(apiResourceList.GroupVersion, admissionregistrationv1.SchemeGroupVersion.String(), "verifying API group/version in /apis/admissionregistration.k8s.io/v1 discovery document")
  142. ginkgo.By("finding mutatingwebhookconfigurations and validatingwebhookconfigurations resources in the /apis/admissionregistration.k8s.io/v1 discovery document")
  143. var (
  144. mutatingWebhookResource *metav1.APIResource
  145. validatingWebhookResource *metav1.APIResource
  146. )
  147. for i := range apiResourceList.APIResources {
  148. if apiResourceList.APIResources[i].Name == "mutatingwebhookconfigurations" {
  149. mutatingWebhookResource = &apiResourceList.APIResources[i]
  150. }
  151. if apiResourceList.APIResources[i].Name == "validatingwebhookconfigurations" {
  152. validatingWebhookResource = &apiResourceList.APIResources[i]
  153. }
  154. }
  155. framework.ExpectNotEqual(mutatingWebhookResource, nil, "mutatingwebhookconfigurations resource not found in /apis/admissionregistration.k8s.io/v1 discovery document")
  156. framework.ExpectNotEqual(validatingWebhookResource, nil, "validatingwebhookconfigurations resource not found in /apis/admissionregistration.k8s.io/v1 discovery document")
  157. }
  158. })
  159. /*
  160. Release : v1.16
  161. Testname: Admission webhook, deny create
  162. Description: Register an admission webhook configuration that admits pod and configmap. Attempts to create
  163. non-compliant pods and configmaps, or update/patch compliant pods and configmaps to be non-compliant MUST
  164. be denied. An attempt to create a pod that causes a webhook to hang MUST result in a webhook timeout error,
  165. and the pod creation MUST be denied. An attempt to create a non-compliant configmap in a whitelisted
  166. namespace based on the webhook namespace selector MUST be allowed.
  167. */
  168. framework.ConformanceIt("should be able to deny pod and configmap creation", func() {
  169. webhookCleanup := registerWebhook(f, f.UniqueName, certCtx, servicePort)
  170. defer webhookCleanup()
  171. testWebhook(f)
  172. })
  173. /*
  174. Release : v1.16
  175. Testname: Admission webhook, deny attach
  176. Description: Register an admission webhook configuration that denies connecting to a pod's attach sub-resource.
  177. Attempts to attach MUST be denied.
  178. */
  179. framework.ConformanceIt("should be able to deny attaching pod", func() {
  180. webhookCleanup := registerWebhookForAttachingPod(f, f.UniqueName, certCtx, servicePort)
  181. defer webhookCleanup()
  182. testAttachingPodWebhook(f)
  183. })
  184. /*
  185. Release : v1.16
  186. Testname: Admission webhook, deny custom resource create and delete
  187. Description: Register an admission webhook configuration that denies creation, update and deletion of
  188. custom resources. Attempts to create, update and delete custom resources MUST be denied.
  189. */
  190. framework.ConformanceIt("should be able to deny custom resource creation, update and deletion", func() {
  191. testcrd, err := crd.CreateTestCRD(f)
  192. if err != nil {
  193. return
  194. }
  195. defer testcrd.CleanUp()
  196. webhookCleanup := registerWebhookForCustomResource(f, f.UniqueName, certCtx, testcrd, servicePort)
  197. defer webhookCleanup()
  198. testCustomResourceWebhook(f, testcrd.Crd, testcrd.DynamicClients["v1"])
  199. testBlockingCustomResourceUpdateDeletion(f, testcrd.Crd, testcrd.DynamicClients["v1"])
  200. })
  201. /*
  202. Release : v1.16
  203. Testname: Admission webhook, fail closed
  204. Description: Register a webhook with a fail closed policy and without CA bundle so that it cannot be called.
  205. Attempt operations that require the admission webhook; all MUST be denied.
  206. */
  207. framework.ConformanceIt("should unconditionally reject operations on fail closed webhook", func() {
  208. webhookCleanup := registerFailClosedWebhook(f, f.UniqueName, certCtx, servicePort)
  209. defer webhookCleanup()
  210. testFailClosedWebhook(f)
  211. })
  212. /*
  213. Release : v1.16
  214. Testname: Admission webhook, ordered mutation
  215. Description: Register a mutating webhook configuration with two webhooks that admit configmaps, one that
  216. adds a data key if the configmap already has a specific key, and another that adds a key if the key added by
  217. the first webhook is present. Attempt to create a config map; both keys MUST be added to the config map.
  218. */
  219. framework.ConformanceIt("should mutate configmap", func() {
  220. webhookCleanup := registerMutatingWebhookForConfigMap(f, f.UniqueName, certCtx, servicePort)
  221. defer webhookCleanup()
  222. testMutatingConfigMapWebhook(f)
  223. })
  224. /*
  225. Release : v1.16
  226. Testname: Admission webhook, mutation with defaulting
  227. Description: Register a mutating webhook that adds an InitContainer to pods. Attempt to create a pod;
  228. the InitContainer MUST be added the TerminationMessagePolicy MUST be defaulted.
  229. */
  230. framework.ConformanceIt("should mutate pod and apply defaults after mutation", func() {
  231. webhookCleanup := registerMutatingWebhookForPod(f, f.UniqueName, certCtx, servicePort)
  232. defer webhookCleanup()
  233. testMutatingPodWebhook(f)
  234. })
  235. /*
  236. Release : v1.16
  237. Testname: Admission webhook, admission control not allowed on webhook configuration objects
  238. Description: Register webhooks that mutate and deny deletion of webhook configuration objects. Attempt to create
  239. and delete a webhook configuration object; both operations MUST be allowed and the webhook configuration object
  240. MUST NOT be mutated the webhooks.
  241. */
  242. framework.ConformanceIt("should not be able to mutate or prevent deletion of webhook configuration objects", func() {
  243. validatingWebhookCleanup := registerValidatingWebhookForWebhookConfigurations(f, f.UniqueName+"blocking", certCtx, servicePort)
  244. defer validatingWebhookCleanup()
  245. mutatingWebhookCleanup := registerMutatingWebhookForWebhookConfigurations(f, f.UniqueName+"blocking", certCtx, servicePort)
  246. defer mutatingWebhookCleanup()
  247. testWebhooksForWebhookConfigurations(f, f.UniqueName, certCtx, servicePort)
  248. })
  249. /*
  250. Release : v1.16
  251. Testname: Admission webhook, mutate custom resource
  252. Description: Register a webhook that mutates a custom resource. Attempt to create custom resource object;
  253. the custom resource MUST be mutated.
  254. */
  255. framework.ConformanceIt("should mutate custom resource", func() {
  256. testcrd, err := crd.CreateTestCRD(f)
  257. if err != nil {
  258. return
  259. }
  260. defer testcrd.CleanUp()
  261. webhookCleanup := registerMutatingWebhookForCustomResource(f, f.UniqueName, certCtx, testcrd, servicePort)
  262. defer webhookCleanup()
  263. testMutatingCustomResourceWebhook(f, testcrd.Crd, testcrd.DynamicClients["v1"], false)
  264. })
  265. /*
  266. Release : v1.16
  267. Testname: Admission webhook, deny custom resource definition
  268. Description: Register a webhook that denies custom resource definition create. Attempt to create a
  269. custom resource definition; the create request MUST be denied.
  270. */
  271. framework.ConformanceIt("should deny crd creation", func() {
  272. crdWebhookCleanup := registerValidatingWebhookForCRD(f, f.UniqueName, certCtx, servicePort)
  273. defer crdWebhookCleanup()
  274. testCRDDenyWebhook(f)
  275. })
  276. /*
  277. Release : v1.16
  278. Testname: Admission webhook, mutate custom resource with different stored version
  279. Description: Register a webhook that mutates custom resources on create and update. Register a custom resource
  280. definition using v1 as stored version. Create a custom resource. Patch the custom resource definition to use v2 as
  281. the stored version. Attempt to patch the custom resource with a new field and value; the patch MUST be applied
  282. successfully.
  283. */
  284. framework.ConformanceIt("should mutate custom resource with different stored version", func() {
  285. testcrd, err := createAdmissionWebhookMultiVersionTestCRDWithV1Storage(f)
  286. if err != nil {
  287. return
  288. }
  289. defer testcrd.CleanUp()
  290. webhookCleanup := registerMutatingWebhookForCustomResource(f, f.UniqueName, certCtx, testcrd, servicePort)
  291. defer webhookCleanup()
  292. testMultiVersionCustomResourceWebhook(f, testcrd)
  293. })
  294. /*
  295. Release : v1.16
  296. Testname: Admission webhook, mutate custom resource with pruning
  297. Description: Register mutating webhooks that adds fields to custom objects. Register a custom resource definition
  298. with a schema that includes only one of the data keys added by the webhooks. Attempt to a custom resource;
  299. the fields included in the schema MUST be present and field not included in the schema MUST NOT be present.
  300. */
  301. framework.ConformanceIt("should mutate custom resource with pruning", func() {
  302. const prune = true
  303. testcrd, err := createAdmissionWebhookMultiVersionTestCRDWithV1Storage(f, func(crd *apiextensionsv1.CustomResourceDefinition) {
  304. crd.Spec.PreserveUnknownFields = false
  305. for i := range crd.Spec.Versions {
  306. crd.Spec.Versions[i].Schema = &apiextensionsv1.CustomResourceValidation{
  307. OpenAPIV3Schema: &apiextensionsv1.JSONSchemaProps{
  308. Type: "object",
  309. Properties: map[string]apiextensionsv1.JSONSchemaProps{
  310. "data": {
  311. Type: "object",
  312. Properties: map[string]apiextensionsv1.JSONSchemaProps{
  313. "mutation-start": {Type: "string"},
  314. "mutation-stage-1": {Type: "string"},
  315. // mutation-stage-2 is intentionally missing such that it is pruned
  316. },
  317. },
  318. },
  319. },
  320. }
  321. }
  322. })
  323. if err != nil {
  324. return
  325. }
  326. defer testcrd.CleanUp()
  327. webhookCleanup := registerMutatingWebhookForCustomResource(f, f.UniqueName, certCtx, testcrd, servicePort)
  328. defer webhookCleanup()
  329. testMutatingCustomResourceWebhook(f, testcrd.Crd, testcrd.DynamicClients["v1"], prune)
  330. })
  331. /*
  332. Release : v1.16
  333. Testname: Admission webhook, honor timeout
  334. Description: Using a webhook that waits 5 seconds before admitting objects, configure the webhook with combinations
  335. of timeouts and failure policy values. Attempt to create a config map with each combination. Requests MUST
  336. timeout if the configured webhook timeout is less than 5 seconds and failure policy is fail. Requests must not timeout if
  337. the failure policy is ignore. Requests MUST NOT timeout if configured webhook timeout is 10 seconds (much longer
  338. than the webhook wait duration).
  339. */
  340. framework.ConformanceIt("should honor timeout", func() {
  341. policyFail := admissionregistrationv1.Fail
  342. policyIgnore := admissionregistrationv1.Ignore
  343. ginkgo.By("Setting timeout (1s) shorter than webhook latency (5s)")
  344. slowWebhookCleanup := registerSlowWebhook(f, f.UniqueName, certCtx, &policyFail, pointer.Int32Ptr(1), servicePort)
  345. testSlowWebhookTimeoutFailEarly(f)
  346. slowWebhookCleanup()
  347. ginkgo.By("Having no error when timeout is shorter than webhook latency and failure policy is ignore")
  348. slowWebhookCleanup = registerSlowWebhook(f, f.UniqueName, certCtx, &policyIgnore, pointer.Int32Ptr(1), servicePort)
  349. testSlowWebhookTimeoutNoError(f)
  350. slowWebhookCleanup()
  351. ginkgo.By("Having no error when timeout is longer than webhook latency")
  352. slowWebhookCleanup = registerSlowWebhook(f, f.UniqueName, certCtx, &policyFail, pointer.Int32Ptr(10), servicePort)
  353. testSlowWebhookTimeoutNoError(f)
  354. slowWebhookCleanup()
  355. ginkgo.By("Having no error when timeout is empty (defaulted to 10s in v1)")
  356. slowWebhookCleanup = registerSlowWebhook(f, f.UniqueName, certCtx, &policyFail, nil, servicePort)
  357. testSlowWebhookTimeoutNoError(f)
  358. slowWebhookCleanup()
  359. })
  360. /*
  361. Release : v1.16
  362. Testname: Admission webhook, update validating webhook
  363. Description: Register a validating admission webhook configuration. Update the webhook to not apply to the create
  364. operation and attempt to create an object; the webhook MUST NOT deny the create. Patch the webhook to apply to the
  365. create operation again and attempt to create an object; the webhook MUST deny the create.
  366. */
  367. framework.ConformanceIt("patching/updating a validating webhook should work", func() {
  368. client := f.ClientSet
  369. admissionClient := client.AdmissionregistrationV1()
  370. ginkgo.By("Creating a validating webhook configuration")
  371. hook, err := createValidatingWebhookConfiguration(f, &admissionregistrationv1.ValidatingWebhookConfiguration{
  372. ObjectMeta: metav1.ObjectMeta{
  373. Name: f.UniqueName,
  374. },
  375. Webhooks: []admissionregistrationv1.ValidatingWebhook{
  376. newDenyConfigMapWebhookFixture(f, certCtx, servicePort),
  377. newValidatingIsReadyWebhookFixture(f, certCtx, servicePort),
  378. },
  379. })
  380. framework.ExpectNoError(err, "Creating validating webhook configuration")
  381. defer func() {
  382. err := client.AdmissionregistrationV1().ValidatingWebhookConfigurations().Delete(context.TODO(), hook.Name, nil)
  383. framework.ExpectNoError(err, "Deleting validating webhook configuration")
  384. }()
  385. // ensure backend is ready before proceeding
  386. err = waitWebhookConfigurationReady(f)
  387. framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
  388. ginkgo.By("Creating a configMap that does not comply to the validation webhook rules")
  389. err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
  390. cm := namedNonCompliantConfigMap(string(uuid.NewUUID()), f)
  391. _, err = client.CoreV1().ConfigMaps(f.Namespace.Name).Create(context.TODO(), cm, metav1.CreateOptions{})
  392. if err == nil {
  393. err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(context.TODO(), cm.Name, nil)
  394. framework.ExpectNoError(err, "Deleting successfully created configMap")
  395. return false, nil
  396. }
  397. if !strings.Contains(err.Error(), "denied") {
  398. return false, err
  399. }
  400. return true, nil
  401. })
  402. ginkgo.By("Updating a validating webhook configuration's rules to not include the create operation")
  403. err = retry.RetryOnConflict(retry.DefaultRetry, func() error {
  404. h, err := admissionClient.ValidatingWebhookConfigurations().Get(context.TODO(), f.UniqueName, metav1.GetOptions{})
  405. framework.ExpectNoError(err, "Getting validating webhook configuration")
  406. h.Webhooks[0].Rules[0].Operations = []admissionregistrationv1.OperationType{admissionregistrationv1.Update}
  407. _, err = admissionClient.ValidatingWebhookConfigurations().Update(context.TODO(), h, metav1.UpdateOptions{})
  408. return err
  409. })
  410. framework.ExpectNoError(err, "Updating validating webhook configuration")
  411. ginkgo.By("Creating a configMap that does not comply to the validation webhook rules")
  412. err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
  413. cm := namedNonCompliantConfigMap(string(uuid.NewUUID()), f)
  414. _, err = client.CoreV1().ConfigMaps(f.Namespace.Name).Create(context.TODO(), cm, metav1.CreateOptions{})
  415. if err != nil {
  416. if !strings.Contains(err.Error(), "denied") {
  417. return false, err
  418. }
  419. return false, nil
  420. }
  421. err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(context.TODO(), cm.Name, nil)
  422. framework.ExpectNoError(err, "Deleting successfully created configMap")
  423. return true, nil
  424. })
  425. framework.ExpectNoError(err, "Waiting for configMap in namespace %s to be allowed creation since webhook was updated to not validate create", f.Namespace.Name)
  426. ginkgo.By("Patching a validating webhook configuration's rules to include the create operation")
  427. hook, err = admissionClient.ValidatingWebhookConfigurations().Patch(context.TODO(), f.UniqueName,
  428. types.JSONPatchType,
  429. []byte(`[{"op": "replace", "path": "/webhooks/0/rules/0/operations", "value": ["CREATE"]}]`), metav1.PatchOptions{})
  430. framework.ExpectNoError(err, "Patching validating webhook configuration")
  431. ginkgo.By("Creating a configMap that does not comply to the validation webhook rules")
  432. err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
  433. cm := namedNonCompliantConfigMap(string(uuid.NewUUID()), f)
  434. _, err = client.CoreV1().ConfigMaps(f.Namespace.Name).Create(context.TODO(), cm, metav1.CreateOptions{})
  435. if err == nil {
  436. err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(context.TODO(), cm.Name, nil)
  437. framework.ExpectNoError(err, "Deleting successfully created configMap")
  438. return false, nil
  439. }
  440. if !strings.Contains(err.Error(), "denied") {
  441. return false, err
  442. }
  443. return true, nil
  444. })
  445. framework.ExpectNoError(err, "Waiting for configMap in namespace %s to be denied creation by validating webhook", f.Namespace.Name)
  446. })
  447. /*
  448. Release : v1.16
  449. Testname: Admission webhook, update mutating webhook
  450. Description: Register a mutating admission webhook configuration. Update the webhook to not apply to the create
  451. operation and attempt to create an object; the webhook MUST NOT mutate the object. Patch the webhook to apply to the
  452. create operation again and attempt to create an object; the webhook MUST mutate the object.
  453. */
  454. framework.ConformanceIt("patching/updating a mutating webhook should work", func() {
  455. client := f.ClientSet
  456. admissionClient := client.AdmissionregistrationV1()
  457. ginkgo.By("Creating a mutating webhook configuration")
  458. hook, err := createMutatingWebhookConfiguration(f, &admissionregistrationv1.MutatingWebhookConfiguration{
  459. ObjectMeta: metav1.ObjectMeta{
  460. Name: f.UniqueName,
  461. },
  462. Webhooks: []admissionregistrationv1.MutatingWebhook{
  463. newMutateConfigMapWebhookFixture(f, certCtx, 1, servicePort),
  464. newMutatingIsReadyWebhookFixture(f, certCtx, servicePort),
  465. },
  466. })
  467. framework.ExpectNoError(err, "Creating mutating webhook configuration")
  468. defer func() {
  469. err := client.AdmissionregistrationV1().MutatingWebhookConfigurations().Delete(context.TODO(), hook.Name, nil)
  470. framework.ExpectNoError(err, "Deleting mutating webhook configuration")
  471. }()
  472. // ensure backend is ready before proceeding
  473. err = waitWebhookConfigurationReady(f)
  474. framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
  475. hook, err = admissionClient.MutatingWebhookConfigurations().Get(context.TODO(), f.UniqueName, metav1.GetOptions{})
  476. framework.ExpectNoError(err, "Getting mutating webhook configuration")
  477. ginkgo.By("Updating a mutating webhook configuration's rules to not include the create operation")
  478. hook.Webhooks[0].Rules[0].Operations = []admissionregistrationv1.OperationType{admissionregistrationv1.Update}
  479. hook, err = admissionClient.MutatingWebhookConfigurations().Update(context.TODO(), hook, metav1.UpdateOptions{})
  480. framework.ExpectNoError(err, "Updating mutating webhook configuration")
  481. ginkgo.By("Creating a configMap that should not be mutated")
  482. err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
  483. cm := namedToBeMutatedConfigMap(string(uuid.NewUUID()), f)
  484. created, err := client.CoreV1().ConfigMaps(f.Namespace.Name).Create(context.TODO(), cm, metav1.CreateOptions{})
  485. if err != nil {
  486. return false, err
  487. }
  488. err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(context.TODO(), cm.Name, nil)
  489. framework.ExpectNoError(err, "Deleting successfully created configMap")
  490. _, ok := created.Data["mutation-stage-1"]
  491. return !ok, nil
  492. })
  493. framework.ExpectNoError(err, "Waiting for configMap in namespace %s this is not mutated", f.Namespace.Name)
  494. ginkgo.By("Patching a mutating webhook configuration's rules to include the create operation")
  495. hook, err = admissionClient.MutatingWebhookConfigurations().Patch(context.TODO(), f.UniqueName,
  496. types.JSONPatchType,
  497. []byte(`[{"op": "replace", "path": "/webhooks/0/rules/0/operations", "value": ["CREATE"]}]`), metav1.PatchOptions{})
  498. framework.ExpectNoError(err, "Patching mutating webhook configuration")
  499. ginkgo.By("Creating a configMap that should be mutated")
  500. err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
  501. cm := namedToBeMutatedConfigMap(string(uuid.NewUUID()), f)
  502. created, err := client.CoreV1().ConfigMaps(f.Namespace.Name).Create(context.TODO(), cm, metav1.CreateOptions{})
  503. if err != nil {
  504. return false, err
  505. }
  506. err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(context.TODO(), cm.Name, nil)
  507. framework.ExpectNoError(err, "Deleting successfully created configMap")
  508. _, ok := created.Data["mutation-stage-1"]
  509. return ok, nil
  510. })
  511. framework.ExpectNoError(err, "Waiting for configMap in namespace %s to be mutated", f.Namespace.Name)
  512. })
  513. /*
  514. Release : v1.16
  515. Testname: Admission webhook, list validating webhooks
  516. Description: Create 10 validating webhook configurations, all with a label. Attempt to list the webhook
  517. configurations matching the label; all the created webhook configurations MUST be present. Attempt to create an
  518. object; the create MUST be denied. Attempt to remove the webhook configurations matching the label with deletecollection;
  519. all webhook configurations MUST be deleted. Attempt to create an object; the create MUST NOT be denied.
  520. */
  521. framework.ConformanceIt("listing validating webhooks should work", func() {
  522. testListSize := 10
  523. testUUID := string(uuid.NewUUID())
  524. for i := 0; i < testListSize; i++ {
  525. name := fmt.Sprintf("%s-%d", f.UniqueName, i)
  526. _, err := createValidatingWebhookConfiguration(f, &admissionregistrationv1.ValidatingWebhookConfiguration{
  527. ObjectMeta: metav1.ObjectMeta{
  528. Name: name,
  529. Labels: map[string]string{"e2e-list-test-uuid": testUUID},
  530. },
  531. Webhooks: []admissionregistrationv1.ValidatingWebhook{
  532. newDenyConfigMapWebhookFixture(f, certCtx, servicePort),
  533. newValidatingIsReadyWebhookFixture(f, certCtx, servicePort),
  534. },
  535. })
  536. framework.ExpectNoError(err, "Creating validating webhook configuration")
  537. }
  538. selectorListOpts := metav1.ListOptions{LabelSelector: "e2e-list-test-uuid=" + testUUID}
  539. ginkgo.By("Listing all of the created validation webhooks")
  540. list, err := client.AdmissionregistrationV1().ValidatingWebhookConfigurations().List(context.TODO(), selectorListOpts)
  541. framework.ExpectNoError(err, "Listing validating webhook configurations")
  542. framework.ExpectEqual(len(list.Items), testListSize)
  543. // ensure backend is ready before proceeding
  544. err = waitWebhookConfigurationReady(f)
  545. framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
  546. ginkgo.By("Creating a configMap that does not comply to the validation webhook rules")
  547. err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
  548. cm := namedNonCompliantConfigMap(string(uuid.NewUUID()), f)
  549. _, err = client.CoreV1().ConfigMaps(f.Namespace.Name).Create(context.TODO(), cm, metav1.CreateOptions{})
  550. if err == nil {
  551. err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(context.TODO(), cm.Name, nil)
  552. framework.ExpectNoError(err, "Deleting successfully created configMap")
  553. return false, nil
  554. }
  555. if !strings.Contains(err.Error(), "denied") {
  556. return false, err
  557. }
  558. return true, nil
  559. })
  560. framework.ExpectNoError(err, "Waiting for configMap in namespace %s to be denied creation by validating webhook", f.Namespace.Name)
  561. ginkgo.By("Deleting the collection of validation webhooks")
  562. err = client.AdmissionregistrationV1().ValidatingWebhookConfigurations().DeleteCollection(context.TODO(), nil, selectorListOpts)
  563. framework.ExpectNoError(err, "Deleting collection of validating webhook configurations")
  564. ginkgo.By("Creating a configMap that does not comply to the validation webhook rules")
  565. err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
  566. cm := namedNonCompliantConfigMap(string(uuid.NewUUID()), f)
  567. _, err = client.CoreV1().ConfigMaps(f.Namespace.Name).Create(context.TODO(), cm, metav1.CreateOptions{})
  568. if err != nil {
  569. if !strings.Contains(err.Error(), "denied") {
  570. return false, err
  571. }
  572. return false, nil
  573. }
  574. err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(context.TODO(), cm.Name, nil)
  575. framework.ExpectNoError(err, "Deleting successfully created configMap")
  576. return true, nil
  577. })
  578. framework.ExpectNoError(err, "Waiting for configMap in namespace %s to be allowed creation since there are no webhooks", f.Namespace.Name)
  579. })
  580. /*
  581. Release : v1.16
  582. Testname: Admission webhook, list mutating webhooks
  583. Description: Create 10 mutating webhook configurations, all with a label. Attempt to list the webhook
  584. configurations matching the label; all the created webhook configurations MUST be present. Attempt to create an
  585. object; the object MUST be mutated. Attempt to remove the webhook configurations matching the label with deletecollection;
  586. all webhook configurations MUST be deleted. Attempt to create an object; the object MUST NOT be mutated.
  587. */
  588. framework.ConformanceIt("listing mutating webhooks should work", func() {
  589. testListSize := 10
  590. testUUID := string(uuid.NewUUID())
  591. for i := 0; i < testListSize; i++ {
  592. name := fmt.Sprintf("%s-%d", f.UniqueName, i)
  593. _, err := createMutatingWebhookConfiguration(f, &admissionregistrationv1.MutatingWebhookConfiguration{
  594. ObjectMeta: metav1.ObjectMeta{
  595. Name: name,
  596. Labels: map[string]string{"e2e-list-test-uuid": testUUID},
  597. },
  598. Webhooks: []admissionregistrationv1.MutatingWebhook{
  599. newMutateConfigMapWebhookFixture(f, certCtx, 1, servicePort),
  600. newMutatingIsReadyWebhookFixture(f, certCtx, servicePort),
  601. },
  602. })
  603. framework.ExpectNoError(err, "Creating mutating webhook configuration")
  604. }
  605. selectorListOpts := metav1.ListOptions{LabelSelector: "e2e-list-test-uuid=" + testUUID}
  606. ginkgo.By("Listing all of the created validation webhooks")
  607. list, err := client.AdmissionregistrationV1().MutatingWebhookConfigurations().List(context.TODO(), selectorListOpts)
  608. framework.ExpectNoError(err, "Listing mutating webhook configurations")
  609. framework.ExpectEqual(len(list.Items), testListSize)
  610. // ensure backend is ready before proceeding
  611. err = waitWebhookConfigurationReady(f)
  612. framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
  613. ginkgo.By("Creating a configMap that should be mutated")
  614. err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
  615. cm := namedToBeMutatedConfigMap(string(uuid.NewUUID()), f)
  616. created, err := client.CoreV1().ConfigMaps(f.Namespace.Name).Create(context.TODO(), cm, metav1.CreateOptions{})
  617. if err != nil {
  618. return false, err
  619. }
  620. err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(context.TODO(), cm.Name, nil)
  621. framework.ExpectNoError(err, "Deleting successfully created configMap")
  622. _, ok := created.Data["mutation-stage-1"]
  623. return ok, nil
  624. })
  625. framework.ExpectNoError(err, "Waiting for configMap in namespace %s to be mutated", f.Namespace.Name)
  626. ginkgo.By("Deleting the collection of validation webhooks")
  627. err = client.AdmissionregistrationV1().MutatingWebhookConfigurations().DeleteCollection(context.TODO(), nil, selectorListOpts)
  628. framework.ExpectNoError(err, "Deleting collection of mutating webhook configurations")
  629. ginkgo.By("Creating a configMap that should not be mutated")
  630. err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
  631. cm := namedToBeMutatedConfigMap(string(uuid.NewUUID()), f)
  632. created, err := client.CoreV1().ConfigMaps(f.Namespace.Name).Create(context.TODO(), cm, metav1.CreateOptions{})
  633. if err != nil {
  634. return false, err
  635. }
  636. err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(context.TODO(), cm.Name, nil)
  637. framework.ExpectNoError(err, "Deleting successfully created configMap")
  638. _, ok := created.Data["mutation-stage-1"]
  639. return !ok, nil
  640. })
  641. framework.ExpectNoError(err, "Waiting for configMap in namespace %s this is not mutated", f.Namespace.Name)
  642. })
  643. })
  644. func createAuthReaderRoleBinding(f *framework.Framework, namespace string) {
  645. ginkgo.By("Create role binding to let webhook read extension-apiserver-authentication")
  646. client := f.ClientSet
  647. // Create the role binding to allow the webhook read the extension-apiserver-authentication configmap
  648. _, err := client.RbacV1().RoleBindings("kube-system").Create(context.TODO(), &rbacv1.RoleBinding{
  649. ObjectMeta: metav1.ObjectMeta{
  650. Name: roleBindingName,
  651. Annotations: map[string]string{
  652. rbacv1.AutoUpdateAnnotationKey: "true",
  653. },
  654. },
  655. RoleRef: rbacv1.RoleRef{
  656. APIGroup: "",
  657. Kind: "Role",
  658. Name: "extension-apiserver-authentication-reader",
  659. },
  660. Subjects: []rbacv1.Subject{
  661. {
  662. Kind: "ServiceAccount",
  663. Name: "default",
  664. Namespace: namespace,
  665. },
  666. },
  667. }, metav1.CreateOptions{})
  668. if err != nil && apierrors.IsAlreadyExists(err) {
  669. framework.Logf("role binding %s already exists", roleBindingName)
  670. } else {
  671. framework.ExpectNoError(err, "creating role binding %s:webhook to access configMap", namespace)
  672. }
  673. }
  674. func deployWebhookAndService(f *framework.Framework, image string, certCtx *certContext, servicePort int32, containerPort int32) {
  675. ginkgo.By("Deploying the webhook pod")
  676. client := f.ClientSet
  677. // Creating the secret that contains the webhook's cert.
  678. secret := &v1.Secret{
  679. ObjectMeta: metav1.ObjectMeta{
  680. Name: secretName,
  681. },
  682. Type: v1.SecretTypeOpaque,
  683. Data: map[string][]byte{
  684. "tls.crt": certCtx.cert,
  685. "tls.key": certCtx.key,
  686. },
  687. }
  688. namespace := f.Namespace.Name
  689. _, err := client.CoreV1().Secrets(namespace).Create(context.TODO(), secret, metav1.CreateOptions{})
  690. framework.ExpectNoError(err, "creating secret %q in namespace %q", secretName, namespace)
  691. // Create the deployment of the webhook
  692. podLabels := map[string]string{"app": "sample-webhook", "webhook": "true"}
  693. replicas := int32(1)
  694. zero := int64(0)
  695. mounts := []v1.VolumeMount{
  696. {
  697. Name: "webhook-certs",
  698. ReadOnly: true,
  699. MountPath: "/webhook.local.config/certificates",
  700. },
  701. }
  702. volumes := []v1.Volume{
  703. {
  704. Name: "webhook-certs",
  705. VolumeSource: v1.VolumeSource{
  706. Secret: &v1.SecretVolumeSource{SecretName: secretName},
  707. },
  708. },
  709. }
  710. containers := []v1.Container{
  711. {
  712. Name: "sample-webhook",
  713. VolumeMounts: mounts,
  714. Args: []string{
  715. "webhook",
  716. "--tls-cert-file=/webhook.local.config/certificates/tls.crt",
  717. "--tls-private-key-file=/webhook.local.config/certificates/tls.key",
  718. "--alsologtostderr",
  719. "-v=4",
  720. // Use a non-default port for containers.
  721. fmt.Sprintf("--port=%d", containerPort),
  722. },
  723. ReadinessProbe: &v1.Probe{
  724. Handler: v1.Handler{
  725. HTTPGet: &v1.HTTPGetAction{
  726. Scheme: v1.URISchemeHTTPS,
  727. Port: intstr.FromInt(int(containerPort)),
  728. Path: "/readyz",
  729. },
  730. },
  731. PeriodSeconds: 1,
  732. SuccessThreshold: 1,
  733. FailureThreshold: 30,
  734. },
  735. Image: image,
  736. Ports: []v1.ContainerPort{{ContainerPort: containerPort}},
  737. },
  738. }
  739. d := &appsv1.Deployment{
  740. ObjectMeta: metav1.ObjectMeta{
  741. Name: deploymentName,
  742. Labels: podLabels,
  743. },
  744. Spec: appsv1.DeploymentSpec{
  745. Replicas: &replicas,
  746. Selector: &metav1.LabelSelector{
  747. MatchLabels: podLabels,
  748. },
  749. Strategy: appsv1.DeploymentStrategy{
  750. Type: appsv1.RollingUpdateDeploymentStrategyType,
  751. },
  752. Template: v1.PodTemplateSpec{
  753. ObjectMeta: metav1.ObjectMeta{
  754. Labels: podLabels,
  755. },
  756. Spec: v1.PodSpec{
  757. TerminationGracePeriodSeconds: &zero,
  758. Containers: containers,
  759. Volumes: volumes,
  760. },
  761. },
  762. },
  763. }
  764. deployment, err := client.AppsV1().Deployments(namespace).Create(context.TODO(), d, metav1.CreateOptions{})
  765. framework.ExpectNoError(err, "creating deployment %s in namespace %s", deploymentName, namespace)
  766. ginkgo.By("Wait for the deployment to be ready")
  767. err = e2edeploy.WaitForDeploymentRevisionAndImage(client, namespace, deploymentName, "1", image)
  768. framework.ExpectNoError(err, "waiting for the deployment of image %s in %s in %s to complete", image, deploymentName, namespace)
  769. err = e2edeploy.WaitForDeploymentComplete(client, deployment)
  770. framework.ExpectNoError(err, "waiting for the deployment status valid", image, deploymentName, namespace)
  771. ginkgo.By("Deploying the webhook service")
  772. serviceLabels := map[string]string{"webhook": "true"}
  773. service := &v1.Service{
  774. ObjectMeta: metav1.ObjectMeta{
  775. Namespace: namespace,
  776. Name: serviceName,
  777. Labels: map[string]string{"test": "webhook"},
  778. },
  779. Spec: v1.ServiceSpec{
  780. Selector: serviceLabels,
  781. Ports: []v1.ServicePort{
  782. {
  783. Protocol: "TCP",
  784. Port: servicePort,
  785. TargetPort: intstr.FromInt(int(containerPort)),
  786. },
  787. },
  788. },
  789. }
  790. _, err = client.CoreV1().Services(namespace).Create(context.TODO(), service, metav1.CreateOptions{})
  791. framework.ExpectNoError(err, "creating service %s in namespace %s", serviceName, namespace)
  792. ginkgo.By("Verifying the service has paired with the endpoint")
  793. err = framework.WaitForServiceEndpointsNum(client, namespace, serviceName, 1, 1*time.Second, 30*time.Second)
  794. framework.ExpectNoError(err, "waiting for service %s/%s have %d endpoint", namespace, serviceName, 1)
  795. }
  796. func strPtr(s string) *string { return &s }
  797. func registerWebhook(f *framework.Framework, configName string, certCtx *certContext, servicePort int32) func() {
  798. client := f.ClientSet
  799. ginkgo.By("Registering the webhook via the AdmissionRegistration API")
  800. namespace := f.Namespace.Name
  801. // A webhook that cannot talk to server, with fail-open policy
  802. failOpenHook := failingWebhook(namespace, "fail-open.k8s.io", servicePort)
  803. policyIgnore := admissionregistrationv1.Ignore
  804. failOpenHook.FailurePolicy = &policyIgnore
  805. failOpenHook.NamespaceSelector = &metav1.LabelSelector{
  806. MatchLabels: map[string]string{f.UniqueName: "true"},
  807. }
  808. _, err := createValidatingWebhookConfiguration(f, &admissionregistrationv1.ValidatingWebhookConfiguration{
  809. ObjectMeta: metav1.ObjectMeta{
  810. Name: configName,
  811. },
  812. Webhooks: []admissionregistrationv1.ValidatingWebhook{
  813. newDenyPodWebhookFixture(f, certCtx, servicePort),
  814. newDenyConfigMapWebhookFixture(f, certCtx, servicePort),
  815. // Server cannot talk to this webhook, so it always fails.
  816. // Because this webhook is configured fail-open, request should be admitted after the call fails.
  817. failOpenHook,
  818. // Register a webhook that can be probed by marker requests to detect when the configuration is ready.
  819. newValidatingIsReadyWebhookFixture(f, certCtx, servicePort),
  820. },
  821. })
  822. framework.ExpectNoError(err, "registering webhook config %s with namespace %s", configName, namespace)
  823. err = waitWebhookConfigurationReady(f)
  824. framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
  825. return func() {
  826. client.AdmissionregistrationV1().ValidatingWebhookConfigurations().Delete(context.TODO(), configName, nil)
  827. }
  828. }
  829. func registerWebhookForAttachingPod(f *framework.Framework, configName string, certCtx *certContext, servicePort int32) func() {
  830. client := f.ClientSet
  831. ginkgo.By("Registering the webhook via the AdmissionRegistration API")
  832. namespace := f.Namespace.Name
  833. sideEffectsNone := admissionregistrationv1.SideEffectClassNone
  834. _, err := createValidatingWebhookConfiguration(f, &admissionregistrationv1.ValidatingWebhookConfiguration{
  835. ObjectMeta: metav1.ObjectMeta{
  836. Name: configName,
  837. },
  838. Webhooks: []admissionregistrationv1.ValidatingWebhook{
  839. {
  840. Name: "deny-attaching-pod.k8s.io",
  841. Rules: []admissionregistrationv1.RuleWithOperations{{
  842. Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Connect},
  843. Rule: admissionregistrationv1.Rule{
  844. APIGroups: []string{""},
  845. APIVersions: []string{"v1"},
  846. Resources: []string{"pods/attach"},
  847. },
  848. }},
  849. ClientConfig: admissionregistrationv1.WebhookClientConfig{
  850. Service: &admissionregistrationv1.ServiceReference{
  851. Namespace: namespace,
  852. Name: serviceName,
  853. Path: strPtr("/pods/attach"),
  854. Port: pointer.Int32Ptr(servicePort),
  855. },
  856. CABundle: certCtx.signingCert,
  857. },
  858. SideEffects: &sideEffectsNone,
  859. AdmissionReviewVersions: []string{"v1", "v1beta1"},
  860. // Scope the webhook to just this namespace
  861. NamespaceSelector: &metav1.LabelSelector{
  862. MatchLabels: map[string]string{f.UniqueName: "true"},
  863. },
  864. },
  865. // Register a webhook that can be probed by marker requests to detect when the configuration is ready.
  866. newValidatingIsReadyWebhookFixture(f, certCtx, servicePort),
  867. },
  868. })
  869. framework.ExpectNoError(err, "registering webhook config %s with namespace %s", configName, namespace)
  870. err = waitWebhookConfigurationReady(f)
  871. framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
  872. return func() {
  873. client.AdmissionregistrationV1().ValidatingWebhookConfigurations().Delete(context.TODO(), configName, nil)
  874. }
  875. }
  876. func registerMutatingWebhookForConfigMap(f *framework.Framework, configName string, certCtx *certContext, servicePort int32) func() {
  877. client := f.ClientSet
  878. ginkgo.By("Registering the mutating configmap webhook via the AdmissionRegistration API")
  879. namespace := f.Namespace.Name
  880. _, err := createMutatingWebhookConfiguration(f, &admissionregistrationv1.MutatingWebhookConfiguration{
  881. ObjectMeta: metav1.ObjectMeta{
  882. Name: configName,
  883. },
  884. Webhooks: []admissionregistrationv1.MutatingWebhook{
  885. newMutateConfigMapWebhookFixture(f, certCtx, 1, servicePort),
  886. newMutateConfigMapWebhookFixture(f, certCtx, 2, servicePort),
  887. // Register a webhook that can be probed by marker requests to detect when the configuration is ready.
  888. newMutatingIsReadyWebhookFixture(f, certCtx, servicePort),
  889. },
  890. })
  891. framework.ExpectNoError(err, "registering mutating webhook config %s with namespace %s", configName, namespace)
  892. err = waitWebhookConfigurationReady(f)
  893. framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
  894. return func() {
  895. client.AdmissionregistrationV1().MutatingWebhookConfigurations().Delete(context.TODO(), configName, nil)
  896. }
  897. }
  898. func testMutatingConfigMapWebhook(f *framework.Framework) {
  899. ginkgo.By("create a configmap that should be updated by the webhook")
  900. client := f.ClientSet
  901. configMap := toBeMutatedConfigMap(f)
  902. mutatedConfigMap, err := client.CoreV1().ConfigMaps(f.Namespace.Name).Create(context.TODO(), configMap, metav1.CreateOptions{})
  903. framework.ExpectNoError(err)
  904. expectedConfigMapData := map[string]string{
  905. "mutation-start": "yes",
  906. "mutation-stage-1": "yes",
  907. "mutation-stage-2": "yes",
  908. }
  909. if !reflect.DeepEqual(expectedConfigMapData, mutatedConfigMap.Data) {
  910. framework.Failf("\nexpected %#v\n, got %#v\n", expectedConfigMapData, mutatedConfigMap.Data)
  911. }
  912. }
  913. func registerMutatingWebhookForPod(f *framework.Framework, configName string, certCtx *certContext, servicePort int32) func() {
  914. client := f.ClientSet
  915. ginkgo.By("Registering the mutating pod webhook via the AdmissionRegistration API")
  916. namespace := f.Namespace.Name
  917. sideEffectsNone := admissionregistrationv1.SideEffectClassNone
  918. _, err := createMutatingWebhookConfiguration(f, &admissionregistrationv1.MutatingWebhookConfiguration{
  919. ObjectMeta: metav1.ObjectMeta{
  920. Name: configName,
  921. },
  922. Webhooks: []admissionregistrationv1.MutatingWebhook{
  923. {
  924. Name: "adding-init-container.k8s.io",
  925. Rules: []admissionregistrationv1.RuleWithOperations{{
  926. Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Create},
  927. Rule: admissionregistrationv1.Rule{
  928. APIGroups: []string{""},
  929. APIVersions: []string{"v1"},
  930. Resources: []string{"pods"},
  931. },
  932. }},
  933. ClientConfig: admissionregistrationv1.WebhookClientConfig{
  934. Service: &admissionregistrationv1.ServiceReference{
  935. Namespace: namespace,
  936. Name: serviceName,
  937. Path: strPtr("/mutating-pods"),
  938. Port: pointer.Int32Ptr(servicePort),
  939. },
  940. CABundle: certCtx.signingCert,
  941. },
  942. SideEffects: &sideEffectsNone,
  943. AdmissionReviewVersions: []string{"v1", "v1beta1"},
  944. // Scope the webhook to just this namespace
  945. NamespaceSelector: &metav1.LabelSelector{
  946. MatchLabels: map[string]string{f.UniqueName: "true"},
  947. },
  948. },
  949. // Register a webhook that can be probed by marker requests to detect when the configuration is ready.
  950. newMutatingIsReadyWebhookFixture(f, certCtx, servicePort),
  951. },
  952. })
  953. framework.ExpectNoError(err, "registering mutating webhook config %s with namespace %s", configName, namespace)
  954. err = waitWebhookConfigurationReady(f)
  955. framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
  956. return func() {
  957. client.AdmissionregistrationV1().MutatingWebhookConfigurations().Delete(context.TODO(), configName, nil)
  958. }
  959. }
  960. func testMutatingPodWebhook(f *framework.Framework) {
  961. ginkgo.By("create a pod that should be updated by the webhook")
  962. client := f.ClientSet
  963. pod := toBeMutatedPod(f)
  964. mutatedPod, err := client.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{})
  965. gomega.Expect(err).To(gomega.BeNil())
  966. if len(mutatedPod.Spec.InitContainers) != 1 {
  967. framework.Failf("expect pod to have 1 init container, got %#v", mutatedPod.Spec.InitContainers)
  968. }
  969. if got, expected := mutatedPod.Spec.InitContainers[0].Name, "webhook-added-init-container"; got != expected {
  970. framework.Failf("expect the init container name to be %q, got %q", expected, got)
  971. }
  972. if got, expected := mutatedPod.Spec.InitContainers[0].TerminationMessagePolicy, v1.TerminationMessageReadFile; got != expected {
  973. framework.Failf("expect the init terminationMessagePolicy to be default to %q, got %q", expected, got)
  974. }
  975. }
  976. func toBeMutatedPod(f *framework.Framework) *v1.Pod {
  977. return &v1.Pod{
  978. ObjectMeta: metav1.ObjectMeta{
  979. Name: "webhook-to-be-mutated",
  980. },
  981. Spec: v1.PodSpec{
  982. Containers: []v1.Container{
  983. {
  984. Name: "example",
  985. Image: imageutils.GetPauseImageName(),
  986. },
  987. },
  988. },
  989. }
  990. }
  991. func testWebhook(f *framework.Framework) {
  992. ginkgo.By("create a pod that should be denied by the webhook")
  993. client := f.ClientSet
  994. // Creating the pod, the request should be rejected
  995. pod := nonCompliantPod(f)
  996. _, err := client.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{})
  997. framework.ExpectError(err, "create pod %s in namespace %s should have been denied by webhook", pod.Name, f.Namespace.Name)
  998. expectedErrMsg1 := "the pod contains unwanted container name"
  999. if !strings.Contains(err.Error(), expectedErrMsg1) {
  1000. framework.Failf("expect error contains %q, got %q", expectedErrMsg1, err.Error())
  1001. }
  1002. expectedErrMsg2 := "the pod contains unwanted label"
  1003. if !strings.Contains(err.Error(), expectedErrMsg2) {
  1004. framework.Failf("expect error contains %q, got %q", expectedErrMsg2, err.Error())
  1005. }
  1006. ginkgo.By("create a pod that causes the webhook to hang")
  1007. client = f.ClientSet
  1008. // Creating the pod, the request should be rejected
  1009. pod = hangingPod(f)
  1010. _, err = client.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{})
  1011. framework.ExpectError(err, "create pod %s in namespace %s should have caused webhook to hang", pod.Name, f.Namespace.Name)
  1012. // ensure the error is webhook-related, not client-side
  1013. if !strings.Contains(err.Error(), "webhook") {
  1014. framework.Failf("expect error %q, got %q", "webhook", err.Error())
  1015. }
  1016. // ensure the error is a timeout
  1017. if !strings.Contains(err.Error(), "deadline") {
  1018. framework.Failf("expect error %q, got %q", "deadline", err.Error())
  1019. }
  1020. // ensure the pod was not actually created
  1021. if _, err := client.CoreV1().Pods(f.Namespace.Name).Get(context.TODO(), pod.Name, metav1.GetOptions{}); !apierrors.IsNotFound(err) {
  1022. framework.Failf("expect notfound error looking for rejected pod, got %v", err)
  1023. }
  1024. ginkgo.By("create a configmap that should be denied by the webhook")
  1025. // Creating the configmap, the request should be rejected
  1026. configmap := nonCompliantConfigMap(f)
  1027. _, err = client.CoreV1().ConfigMaps(f.Namespace.Name).Create(context.TODO(), configmap, metav1.CreateOptions{})
  1028. framework.ExpectError(err, "create configmap %s in namespace %s should have been denied by the webhook", configmap.Name, f.Namespace.Name)
  1029. expectedErrMsg := "the configmap contains unwanted key and value"
  1030. if !strings.Contains(err.Error(), expectedErrMsg) {
  1031. framework.Failf("expect error contains %q, got %q", expectedErrMsg, err.Error())
  1032. }
  1033. ginkgo.By("create a configmap that should be admitted by the webhook")
  1034. // Creating the configmap, the request should be admitted
  1035. configmap = &v1.ConfigMap{
  1036. ObjectMeta: metav1.ObjectMeta{
  1037. Name: allowedConfigMapName,
  1038. },
  1039. Data: map[string]string{
  1040. "admit": "this",
  1041. },
  1042. }
  1043. _, err = client.CoreV1().ConfigMaps(f.Namespace.Name).Create(context.TODO(), configmap, metav1.CreateOptions{})
  1044. framework.ExpectNoError(err, "failed to create configmap %s in namespace: %s", configmap.Name, f.Namespace.Name)
  1045. ginkgo.By("update (PUT) the admitted configmap to a non-compliant one should be rejected by the webhook")
  1046. toNonCompliantFn := func(cm *v1.ConfigMap) {
  1047. if cm.Data == nil {
  1048. cm.Data = map[string]string{}
  1049. }
  1050. cm.Data["webhook-e2e-test"] = "webhook-disallow"
  1051. }
  1052. _, err = updateConfigMap(client, f.Namespace.Name, allowedConfigMapName, toNonCompliantFn)
  1053. framework.ExpectError(err, "update (PUT) admitted configmap %s in namespace %s to a non-compliant one should be rejected by webhook", allowedConfigMapName, f.Namespace.Name)
  1054. if !strings.Contains(err.Error(), expectedErrMsg) {
  1055. framework.Failf("expect error contains %q, got %q", expectedErrMsg, err.Error())
  1056. }
  1057. ginkgo.By("update (PATCH) the admitted configmap to a non-compliant one should be rejected by the webhook")
  1058. patch := nonCompliantConfigMapPatch()
  1059. _, err = client.CoreV1().ConfigMaps(f.Namespace.Name).Patch(context.TODO(), allowedConfigMapName, types.StrategicMergePatchType, []byte(patch), metav1.PatchOptions{})
  1060. framework.ExpectError(err, "update admitted configmap %s in namespace %s by strategic merge patch to a non-compliant one should be rejected by webhook. Patch: %+v", allowedConfigMapName, f.Namespace.Name, patch)
  1061. if !strings.Contains(err.Error(), expectedErrMsg) {
  1062. framework.Failf("expect error contains %q, got %q", expectedErrMsg, err.Error())
  1063. }
  1064. ginkgo.By("create a namespace that bypass the webhook")
  1065. err = createNamespace(f, &v1.Namespace{ObjectMeta: metav1.ObjectMeta{
  1066. Name: skippedNamespaceName,
  1067. Labels: map[string]string{
  1068. skipNamespaceLabelKey: skipNamespaceLabelValue,
  1069. f.UniqueName: "true",
  1070. },
  1071. }})
  1072. framework.ExpectNoError(err, "creating namespace %q", skippedNamespaceName)
  1073. // clean up the namespace
  1074. defer client.CoreV1().Namespaces().Delete(context.TODO(), skippedNamespaceName, nil)
  1075. ginkgo.By("create a configmap that violates the webhook policy but is in a whitelisted namespace")
  1076. configmap = nonCompliantConfigMap(f)
  1077. _, err = client.CoreV1().ConfigMaps(skippedNamespaceName).Create(context.TODO(), configmap, metav1.CreateOptions{})
  1078. framework.ExpectNoError(err, "failed to create configmap %s in namespace: %s", configmap.Name, skippedNamespaceName)
  1079. }
  1080. func testAttachingPodWebhook(f *framework.Framework) {
  1081. ginkgo.By("create a pod")
  1082. client := f.ClientSet
  1083. pod := toBeAttachedPod(f)
  1084. _, err := client.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{})
  1085. framework.ExpectNoError(err, "failed to create pod %s in namespace: %s", pod.Name, f.Namespace.Name)
  1086. err = e2epod.WaitForPodNameRunningInNamespace(client, pod.Name, f.Namespace.Name)
  1087. framework.ExpectNoError(err, "error while waiting for pod %s to go to Running phase in namespace: %s", pod.Name, f.Namespace.Name)
  1088. ginkgo.By("'kubectl attach' the pod, should be denied by the webhook")
  1089. timer := time.NewTimer(30 * time.Second)
  1090. defer timer.Stop()
  1091. _, err = framework.NewKubectlCommand(f.Namespace.Name, "attach", fmt.Sprintf("--namespace=%v", f.Namespace.Name), pod.Name, "-i", "-c=container1").WithTimeout(timer.C).Exec()
  1092. framework.ExpectError(err, "'kubectl attach' the pod, should be denied by the webhook")
  1093. if e, a := "attaching to pod 'to-be-attached-pod' is not allowed", err.Error(); !strings.Contains(a, e) {
  1094. framework.Failf("unexpected 'kubectl attach' error message. expected to contain %q, got %q", e, a)
  1095. }
  1096. }
  1097. // failingWebhook returns a webhook with rule of create configmaps,
  1098. // but with an invalid client config so that server cannot communicate with it
  1099. func failingWebhook(namespace, name string, servicePort int32) admissionregistrationv1.ValidatingWebhook {
  1100. sideEffectsNone := admissionregistrationv1.SideEffectClassNone
  1101. return admissionregistrationv1.ValidatingWebhook{
  1102. Name: name,
  1103. Rules: []admissionregistrationv1.RuleWithOperations{{
  1104. Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Create},
  1105. Rule: admissionregistrationv1.Rule{
  1106. APIGroups: []string{""},
  1107. APIVersions: []string{"v1"},
  1108. Resources: []string{"configmaps"},
  1109. },
  1110. }},
  1111. ClientConfig: admissionregistrationv1.WebhookClientConfig{
  1112. Service: &admissionregistrationv1.ServiceReference{
  1113. Namespace: namespace,
  1114. Name: serviceName,
  1115. Path: strPtr("/configmaps"),
  1116. Port: pointer.Int32Ptr(servicePort),
  1117. },
  1118. // Without CA bundle, the call to webhook always fails
  1119. CABundle: nil,
  1120. },
  1121. SideEffects: &sideEffectsNone,
  1122. AdmissionReviewVersions: []string{"v1", "v1beta1"},
  1123. }
  1124. }
  1125. func registerFailClosedWebhook(f *framework.Framework, configName string, certCtx *certContext, servicePort int32) func() {
  1126. ginkgo.By("Registering a webhook that server cannot talk to, with fail closed policy, via the AdmissionRegistration API")
  1127. namespace := f.Namespace.Name
  1128. // A webhook that cannot talk to server, with fail-closed policy
  1129. policyFail := admissionregistrationv1.Fail
  1130. hook := failingWebhook(namespace, "fail-closed.k8s.io", servicePort)
  1131. hook.FailurePolicy = &policyFail
  1132. hook.NamespaceSelector = &metav1.LabelSelector{
  1133. MatchLabels: map[string]string{f.UniqueName: "true"},
  1134. MatchExpressions: []metav1.LabelSelectorRequirement{
  1135. {
  1136. Key: failNamespaceLabelKey,
  1137. Operator: metav1.LabelSelectorOpIn,
  1138. Values: []string{failNamespaceLabelValue},
  1139. },
  1140. },
  1141. }
  1142. _, err := createValidatingWebhookConfiguration(f, &admissionregistrationv1.ValidatingWebhookConfiguration{
  1143. ObjectMeta: metav1.ObjectMeta{
  1144. Name: configName,
  1145. },
  1146. Webhooks: []admissionregistrationv1.ValidatingWebhook{
  1147. // Server cannot talk to this webhook, so it always fails.
  1148. // Because this webhook is configured fail-closed, request should be rejected after the call fails.
  1149. hook,
  1150. // Register a webhook that can be probed by marker requests to detect when the configuration is ready.
  1151. newValidatingIsReadyWebhookFixture(f, certCtx, servicePort),
  1152. },
  1153. })
  1154. framework.ExpectNoError(err, "registering webhook config %s with namespace %s", configName, namespace)
  1155. err = waitWebhookConfigurationReady(f)
  1156. framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
  1157. return func() {
  1158. f.ClientSet.AdmissionregistrationV1().ValidatingWebhookConfigurations().Delete(context.TODO(), configName, nil)
  1159. }
  1160. }
  1161. func testFailClosedWebhook(f *framework.Framework) {
  1162. client := f.ClientSet
  1163. ginkgo.By("create a namespace for the webhook")
  1164. err := createNamespace(f, &v1.Namespace{ObjectMeta: metav1.ObjectMeta{
  1165. Name: failNamespaceName,
  1166. Labels: map[string]string{
  1167. failNamespaceLabelKey: failNamespaceLabelValue,
  1168. f.UniqueName: "true",
  1169. },
  1170. }})
  1171. framework.ExpectNoError(err, "creating namespace %q", failNamespaceName)
  1172. defer client.CoreV1().Namespaces().Delete(context.TODO(), failNamespaceName, nil)
  1173. ginkgo.By("create a configmap should be unconditionally rejected by the webhook")
  1174. configmap := &v1.ConfigMap{
  1175. ObjectMeta: metav1.ObjectMeta{
  1176. Name: "foo",
  1177. },
  1178. }
  1179. _, err = client.CoreV1().ConfigMaps(failNamespaceName).Create(context.TODO(), configmap, metav1.CreateOptions{})
  1180. framework.ExpectError(err, "create configmap in namespace: %s should be unconditionally rejected by the webhook", failNamespaceName)
  1181. if !apierrors.IsInternalError(err) {
  1182. framework.Failf("expect an internal error, got %#v", err)
  1183. }
  1184. }
  1185. func registerValidatingWebhookForWebhookConfigurations(f *framework.Framework, configName string, certCtx *certContext, servicePort int32) func() {
  1186. var err error
  1187. client := f.ClientSet
  1188. ginkgo.By("Registering a validating webhook on ValidatingWebhookConfiguration and MutatingWebhookConfiguration objects, via the AdmissionRegistration API")
  1189. namespace := f.Namespace.Name
  1190. failurePolicy := admissionregistrationv1.Fail
  1191. sideEffectsNone := admissionregistrationv1.SideEffectClassNone
  1192. // This webhook denies all requests to Delete validating webhook configuration and
  1193. // mutating webhook configuration objects. It should never be called, however, because
  1194. // dynamic admission webhooks should not be called on requests involving webhook configuration objects.
  1195. _, err = createValidatingWebhookConfiguration(f, &admissionregistrationv1.ValidatingWebhookConfiguration{
  1196. ObjectMeta: metav1.ObjectMeta{
  1197. Name: configName,
  1198. },
  1199. Webhooks: []admissionregistrationv1.ValidatingWebhook{
  1200. {
  1201. Name: "deny-webhook-configuration-deletions.k8s.io",
  1202. Rules: []admissionregistrationv1.RuleWithOperations{{
  1203. Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Delete},
  1204. Rule: admissionregistrationv1.Rule{
  1205. APIGroups: []string{"admissionregistration.k8s.io"},
  1206. APIVersions: []string{"*"},
  1207. Resources: []string{
  1208. "validatingwebhookconfigurations",
  1209. "mutatingwebhookconfigurations",
  1210. },
  1211. },
  1212. }},
  1213. ClientConfig: admissionregistrationv1.WebhookClientConfig{
  1214. Service: &admissionregistrationv1.ServiceReference{
  1215. Namespace: namespace,
  1216. Name: serviceName,
  1217. Path: strPtr("/always-deny"),
  1218. Port: pointer.Int32Ptr(servicePort),
  1219. },
  1220. CABundle: certCtx.signingCert,
  1221. },
  1222. SideEffects: &sideEffectsNone,
  1223. AdmissionReviewVersions: []string{"v1", "v1beta1"},
  1224. FailurePolicy: &failurePolicy,
  1225. // Scope the webhook to just this namespace
  1226. NamespaceSelector: &metav1.LabelSelector{
  1227. MatchLabels: map[string]string{f.UniqueName: "true"},
  1228. },
  1229. },
  1230. // Register a webhook that can be probed by marker requests to detect when the configuration is ready.
  1231. newValidatingIsReadyWebhookFixture(f, certCtx, servicePort),
  1232. },
  1233. })
  1234. framework.ExpectNoError(err, "registering webhook config %s with namespace %s", configName, namespace)
  1235. err = waitWebhookConfigurationReady(f)
  1236. framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
  1237. return func() {
  1238. err := client.AdmissionregistrationV1().ValidatingWebhookConfigurations().Delete(context.TODO(), configName, nil)
  1239. framework.ExpectNoError(err, "deleting webhook config %s with namespace %s", configName, namespace)
  1240. }
  1241. }
  1242. func registerMutatingWebhookForWebhookConfigurations(f *framework.Framework, configName string, certCtx *certContext, servicePort int32) func() {
  1243. var err error
  1244. client := f.ClientSet
  1245. ginkgo.By("Registering a mutating webhook on ValidatingWebhookConfiguration and MutatingWebhookConfiguration objects, via the AdmissionRegistration API")
  1246. namespace := f.Namespace.Name
  1247. failurePolicy := admissionregistrationv1.Fail
  1248. sideEffectsNone := admissionregistrationv1.SideEffectClassNone
  1249. // This webhook adds a label to all requests create to validating webhook configuration and
  1250. // mutating webhook configuration objects. It should never be called, however, because
  1251. // dynamic admission webhooks should not be called on requests involving webhook configuration objects.
  1252. _, err = createMutatingWebhookConfiguration(f, &admissionregistrationv1.MutatingWebhookConfiguration{
  1253. ObjectMeta: metav1.ObjectMeta{
  1254. Name: configName,
  1255. },
  1256. Webhooks: []admissionregistrationv1.MutatingWebhook{
  1257. {
  1258. Name: "add-label-to-webhook-configurations.k8s.io",
  1259. Rules: []admissionregistrationv1.RuleWithOperations{{
  1260. Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Create},
  1261. Rule: admissionregistrationv1.Rule{
  1262. APIGroups: []string{"admissionregistration.k8s.io"},
  1263. APIVersions: []string{"*"},
  1264. Resources: []string{
  1265. "validatingwebhookconfigurations",
  1266. "mutatingwebhookconfigurations",
  1267. },
  1268. },
  1269. }},
  1270. ClientConfig: admissionregistrationv1.WebhookClientConfig{
  1271. Service: &admissionregistrationv1.ServiceReference{
  1272. Namespace: namespace,
  1273. Name: serviceName,
  1274. Path: strPtr("/add-label"),
  1275. Port: pointer.Int32Ptr(servicePort),
  1276. },
  1277. CABundle: certCtx.signingCert,
  1278. },
  1279. SideEffects: &sideEffectsNone,
  1280. AdmissionReviewVersions: []string{"v1", "v1beta1"},
  1281. FailurePolicy: &failurePolicy,
  1282. // Scope the webhook to just this namespace
  1283. NamespaceSelector: &metav1.LabelSelector{
  1284. MatchLabels: map[string]string{f.UniqueName: "true"},
  1285. },
  1286. },
  1287. // Register a webhook that can be probed by marker requests to detect when the configuration is ready.
  1288. newMutatingIsReadyWebhookFixture(f, certCtx, servicePort),
  1289. },
  1290. })
  1291. framework.ExpectNoError(err, "registering webhook config %s with namespace %s", configName, namespace)
  1292. err = waitWebhookConfigurationReady(f)
  1293. framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
  1294. return func() {
  1295. err := client.AdmissionregistrationV1().MutatingWebhookConfigurations().Delete(context.TODO(), configName, nil)
  1296. framework.ExpectNoError(err, "deleting webhook config %s with namespace %s", configName, namespace)
  1297. }
  1298. }
  1299. // This test assumes that the deletion-rejecting webhook defined in
  1300. // registerValidatingWebhookForWebhookConfigurations and the webhook-config-mutating
  1301. // webhook defined in registerMutatingWebhookForWebhookConfigurations already exist.
  1302. func testWebhooksForWebhookConfigurations(f *framework.Framework, configName string, certCtx *certContext, servicePort int32) {
  1303. var err error
  1304. client := f.ClientSet
  1305. ginkgo.By("Creating a dummy validating-webhook-configuration object")
  1306. namespace := f.Namespace.Name
  1307. failurePolicy := admissionregistrationv1.Ignore
  1308. sideEffectsNone := admissionregistrationv1.SideEffectClassNone
  1309. mutatedValidatingWebhookConfiguration, err := createValidatingWebhookConfiguration(f, &admissionregistrationv1.ValidatingWebhookConfiguration{
  1310. ObjectMeta: metav1.ObjectMeta{
  1311. Name: configName,
  1312. },
  1313. Webhooks: []admissionregistrationv1.ValidatingWebhook{
  1314. {
  1315. Name: "dummy-validating-webhook.k8s.io",
  1316. Rules: []admissionregistrationv1.RuleWithOperations{{
  1317. Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Create},
  1318. // This will not match any real resources so this webhook should never be called.
  1319. Rule: admissionregistrationv1.Rule{
  1320. APIGroups: []string{""},
  1321. APIVersions: []string{"v1"},
  1322. Resources: []string{"invalid"},
  1323. },
  1324. }},
  1325. ClientConfig: admissionregistrationv1.WebhookClientConfig{
  1326. Service: &admissionregistrationv1.ServiceReference{
  1327. Namespace: namespace,
  1328. Name: serviceName,
  1329. // This path not recognized by the webhook service,
  1330. // so the call to this webhook will always fail,
  1331. // but because the failure policy is ignore, it will
  1332. // have no effect on admission requests.
  1333. Path: strPtr(""),
  1334. Port: pointer.Int32Ptr(servicePort),
  1335. },
  1336. CABundle: nil,
  1337. },
  1338. SideEffects: &sideEffectsNone,
  1339. AdmissionReviewVersions: []string{"v1", "v1beta1"},
  1340. FailurePolicy: &failurePolicy,
  1341. // Scope the webhook to just this namespace
  1342. NamespaceSelector: &metav1.LabelSelector{
  1343. MatchLabels: map[string]string{f.UniqueName: "true"},
  1344. },
  1345. },
  1346. // Register a webhook that can be probed by marker requests to detect when the configuration is ready.
  1347. newValidatingIsReadyWebhookFixture(f, certCtx, servicePort),
  1348. },
  1349. })
  1350. framework.ExpectNoError(err, "registering webhook config %s with namespace %s", configName, namespace)
  1351. if mutatedValidatingWebhookConfiguration.ObjectMeta.Labels != nil && mutatedValidatingWebhookConfiguration.ObjectMeta.Labels[addedLabelKey] == addedLabelValue {
  1352. framework.Failf("expected %s not to be mutated by mutating webhooks but it was", configName)
  1353. }
  1354. err = waitWebhookConfigurationReady(f)
  1355. framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
  1356. ginkgo.By("Deleting the validating-webhook-configuration, which should be possible to remove")
  1357. err = client.AdmissionregistrationV1().ValidatingWebhookConfigurations().Delete(context.TODO(), configName, nil)
  1358. framework.ExpectNoError(err, "deleting webhook config %s with namespace %s", configName, namespace)
  1359. ginkgo.By("Creating a dummy mutating-webhook-configuration object")
  1360. mutatedMutatingWebhookConfiguration, err := createMutatingWebhookConfiguration(f, &admissionregistrationv1.MutatingWebhookConfiguration{
  1361. ObjectMeta: metav1.ObjectMeta{
  1362. Name: configName,
  1363. },
  1364. Webhooks: []admissionregistrationv1.MutatingWebhook{
  1365. {
  1366. Name: "dummy-mutating-webhook.k8s.io",
  1367. Rules: []admissionregistrationv1.RuleWithOperations{{
  1368. Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Create},
  1369. // This will not match any real resources so this webhook should never be called.
  1370. Rule: admissionregistrationv1.Rule{
  1371. APIGroups: []string{""},
  1372. APIVersions: []string{"v1"},
  1373. Resources: []string{"invalid"},
  1374. },
  1375. }},
  1376. ClientConfig: admissionregistrationv1.WebhookClientConfig{
  1377. Service: &admissionregistrationv1.ServiceReference{
  1378. Namespace: namespace,
  1379. Name: serviceName,
  1380. // This path not recognized by the webhook service,
  1381. // so the call to this webhook will always fail,
  1382. // but because the failure policy is ignore, it will
  1383. // have no effect on admission requests.
  1384. Path: strPtr(""),
  1385. Port: pointer.Int32Ptr(servicePort),
  1386. },
  1387. CABundle: nil,
  1388. },
  1389. SideEffects: &sideEffectsNone,
  1390. AdmissionReviewVersions: []string{"v1", "v1beta1"},
  1391. FailurePolicy: &failurePolicy,
  1392. // Scope the webhook to just this namespace
  1393. NamespaceSelector: &metav1.LabelSelector{
  1394. MatchLabels: map[string]string{f.UniqueName: "true"},
  1395. },
  1396. },
  1397. // Register a webhook that can be probed by marker requests to detect when the configuration is ready.
  1398. newMutatingIsReadyWebhookFixture(f, certCtx, servicePort),
  1399. },
  1400. })
  1401. framework.ExpectNoError(err, "registering webhook config %s with namespace %s", configName, namespace)
  1402. if mutatedMutatingWebhookConfiguration.ObjectMeta.Labels != nil && mutatedMutatingWebhookConfiguration.ObjectMeta.Labels[addedLabelKey] == addedLabelValue {
  1403. framework.Failf("expected %s not to be mutated by mutating webhooks but it was", configName)
  1404. }
  1405. err = waitWebhookConfigurationReady(f)
  1406. framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
  1407. ginkgo.By("Deleting the mutating-webhook-configuration, which should be possible to remove")
  1408. err = client.AdmissionregistrationV1().MutatingWebhookConfigurations().Delete(context.TODO(), configName, nil)
  1409. framework.ExpectNoError(err, "deleting webhook config %s with namespace %s", configName, namespace)
  1410. }
  1411. func createNamespace(f *framework.Framework, ns *v1.Namespace) error {
  1412. return wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
  1413. _, err := f.ClientSet.CoreV1().Namespaces().Create(context.TODO(), ns, metav1.CreateOptions{})
  1414. if err != nil {
  1415. if strings.HasPrefix(err.Error(), "object is being deleted:") {
  1416. return false, nil
  1417. }
  1418. return false, err
  1419. }
  1420. return true, nil
  1421. })
  1422. }
  1423. func nonCompliantPod(f *framework.Framework) *v1.Pod {
  1424. return &v1.Pod{
  1425. ObjectMeta: metav1.ObjectMeta{
  1426. Name: disallowedPodName,
  1427. Labels: map[string]string{
  1428. "webhook-e2e-test": "webhook-disallow",
  1429. },
  1430. },
  1431. Spec: v1.PodSpec{
  1432. Containers: []v1.Container{
  1433. {
  1434. Name: "webhook-disallow",
  1435. Image: imageutils.GetPauseImageName(),
  1436. },
  1437. },
  1438. },
  1439. }
  1440. }
  1441. func hangingPod(f *framework.Framework) *v1.Pod {
  1442. return &v1.Pod{
  1443. ObjectMeta: metav1.ObjectMeta{
  1444. Name: hangingPodName,
  1445. Labels: map[string]string{
  1446. "webhook-e2e-test": "wait-forever",
  1447. },
  1448. },
  1449. Spec: v1.PodSpec{
  1450. Containers: []v1.Container{
  1451. {
  1452. Name: "wait-forever",
  1453. Image: imageutils.GetPauseImageName(),
  1454. },
  1455. },
  1456. },
  1457. }
  1458. }
  1459. func toBeAttachedPod(f *framework.Framework) *v1.Pod {
  1460. return &v1.Pod{
  1461. ObjectMeta: metav1.ObjectMeta{
  1462. Name: toBeAttachedPodName,
  1463. },
  1464. Spec: v1.PodSpec{
  1465. Containers: []v1.Container{
  1466. {
  1467. Name: "container1",
  1468. Image: imageutils.GetPauseImageName(),
  1469. },
  1470. },
  1471. },
  1472. }
  1473. }
  1474. func nonCompliantConfigMap(f *framework.Framework) *v1.ConfigMap {
  1475. return namedNonCompliantConfigMap(disallowedConfigMapName, f)
  1476. }
  1477. func namedNonCompliantConfigMap(name string, f *framework.Framework) *v1.ConfigMap {
  1478. return &v1.ConfigMap{
  1479. ObjectMeta: metav1.ObjectMeta{
  1480. Name: name,
  1481. },
  1482. Data: map[string]string{
  1483. "webhook-e2e-test": "webhook-disallow",
  1484. },
  1485. }
  1486. }
  1487. func toBeMutatedConfigMap(f *framework.Framework) *v1.ConfigMap {
  1488. return namedToBeMutatedConfigMap("to-be-mutated", f)
  1489. }
  1490. func namedToBeMutatedConfigMap(name string, f *framework.Framework) *v1.ConfigMap {
  1491. return &v1.ConfigMap{
  1492. ObjectMeta: metav1.ObjectMeta{
  1493. Name: name,
  1494. },
  1495. Data: map[string]string{
  1496. "mutation-start": "yes",
  1497. },
  1498. }
  1499. }
  1500. func nonCompliantConfigMapPatch() string {
  1501. return fmt.Sprint(`{"data":{"webhook-e2e-test":"webhook-disallow"}}`)
  1502. }
  1503. type updateConfigMapFn func(cm *v1.ConfigMap)
  1504. func updateConfigMap(c clientset.Interface, ns, name string, update updateConfigMapFn) (*v1.ConfigMap, error) {
  1505. var cm *v1.ConfigMap
  1506. pollErr := wait.PollImmediate(2*time.Second, 1*time.Minute, func() (bool, error) {
  1507. var err error
  1508. if cm, err = c.CoreV1().ConfigMaps(ns).Get(context.TODO(), name, metav1.GetOptions{}); err != nil {
  1509. return false, err
  1510. }
  1511. update(cm)
  1512. if cm, err = c.CoreV1().ConfigMaps(ns).Update(context.TODO(), cm, metav1.UpdateOptions{}); err == nil {
  1513. return true, nil
  1514. }
  1515. // Only retry update on conflict
  1516. if !apierrors.IsConflict(err) {
  1517. return false, err
  1518. }
  1519. return false, nil
  1520. })
  1521. return cm, pollErr
  1522. }
  1523. type updateCustomResourceFn func(cm *unstructured.Unstructured)
  1524. func updateCustomResource(c dynamic.ResourceInterface, ns, name string, update updateCustomResourceFn) (*unstructured.Unstructured, error) {
  1525. var cr *unstructured.Unstructured
  1526. pollErr := wait.PollImmediate(2*time.Second, 1*time.Minute, func() (bool, error) {
  1527. var err error
  1528. if cr, err = c.Get(name, metav1.GetOptions{}); err != nil {
  1529. return false, err
  1530. }
  1531. update(cr)
  1532. if cr, err = c.Update(cr, metav1.UpdateOptions{}); err == nil {
  1533. return true, nil
  1534. }
  1535. // Only retry update on conflict
  1536. if !apierrors.IsConflict(err) {
  1537. return false, err
  1538. }
  1539. return false, nil
  1540. })
  1541. return cr, pollErr
  1542. }
  1543. func cleanWebhookTest(client clientset.Interface, namespaceName string) {
  1544. _ = client.CoreV1().Services(namespaceName).Delete(context.TODO(), serviceName, nil)
  1545. _ = client.AppsV1().Deployments(namespaceName).Delete(context.TODO(), deploymentName, nil)
  1546. _ = client.CoreV1().Secrets(namespaceName).Delete(context.TODO(), secretName, nil)
  1547. _ = client.RbacV1().RoleBindings("kube-system").Delete(context.TODO(), roleBindingName, nil)
  1548. }
  1549. func registerWebhookForCustomResource(f *framework.Framework, configName string, certCtx *certContext, testcrd *crd.TestCrd, servicePort int32) func() {
  1550. client := f.ClientSet
  1551. ginkgo.By("Registering the custom resource webhook via the AdmissionRegistration API")
  1552. namespace := f.Namespace.Name
  1553. sideEffectsNone := admissionregistrationv1.SideEffectClassNone
  1554. _, err := createValidatingWebhookConfiguration(f, &admissionregistrationv1.ValidatingWebhookConfiguration{
  1555. ObjectMeta: metav1.ObjectMeta{
  1556. Name: configName,
  1557. },
  1558. Webhooks: []admissionregistrationv1.ValidatingWebhook{
  1559. {
  1560. Name: "deny-unwanted-custom-resource-data.k8s.io",
  1561. Rules: []admissionregistrationv1.RuleWithOperations{{
  1562. Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Create, admissionregistrationv1.Update, admissionregistrationv1.Delete},
  1563. Rule: admissionregistrationv1.Rule{
  1564. APIGroups: []string{testcrd.Crd.Spec.Group},
  1565. APIVersions: servedAPIVersions(testcrd.Crd),
  1566. Resources: []string{testcrd.Crd.Spec.Names.Plural},
  1567. },
  1568. }},
  1569. ClientConfig: admissionregistrationv1.WebhookClientConfig{
  1570. Service: &admissionregistrationv1.ServiceReference{
  1571. Namespace: namespace,
  1572. Name: serviceName,
  1573. Path: strPtr("/custom-resource"),
  1574. Port: pointer.Int32Ptr(servicePort),
  1575. },
  1576. CABundle: certCtx.signingCert,
  1577. },
  1578. SideEffects: &sideEffectsNone,
  1579. AdmissionReviewVersions: []string{"v1", "v1beta1"},
  1580. // Scope the webhook to just this namespace
  1581. NamespaceSelector: &metav1.LabelSelector{
  1582. MatchLabels: map[string]string{f.UniqueName: "true"},
  1583. },
  1584. },
  1585. // Register a webhook that can be probed by marker requests to detect when the configuration is ready.
  1586. newValidatingIsReadyWebhookFixture(f, certCtx, servicePort),
  1587. },
  1588. })
  1589. framework.ExpectNoError(err, "registering custom resource webhook config %s with namespace %s", configName, namespace)
  1590. err = waitWebhookConfigurationReady(f)
  1591. framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
  1592. return func() {
  1593. client.AdmissionregistrationV1().ValidatingWebhookConfigurations().Delete(context.TODO(), configName, nil)
  1594. }
  1595. }
  1596. func registerMutatingWebhookForCustomResource(f *framework.Framework, configName string, certCtx *certContext, testcrd *crd.TestCrd, servicePort int32) func() {
  1597. client := f.ClientSet
  1598. ginkgo.By(fmt.Sprintf("Registering the mutating webhook for custom resource %s via the AdmissionRegistration API", testcrd.Crd.Name))
  1599. namespace := f.Namespace.Name
  1600. sideEffectsNone := admissionregistrationv1.SideEffectClassNone
  1601. _, err := createMutatingWebhookConfiguration(f, &admissionregistrationv1.MutatingWebhookConfiguration{
  1602. ObjectMeta: metav1.ObjectMeta{
  1603. Name: configName,
  1604. },
  1605. Webhooks: []admissionregistrationv1.MutatingWebhook{
  1606. {
  1607. Name: "mutate-custom-resource-data-stage-1.k8s.io",
  1608. Rules: []admissionregistrationv1.RuleWithOperations{{
  1609. Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Create, admissionregistrationv1.Update},
  1610. Rule: admissionregistrationv1.Rule{
  1611. APIGroups: []string{testcrd.Crd.Spec.Group},
  1612. APIVersions: servedAPIVersions(testcrd.Crd),
  1613. Resources: []string{testcrd.Crd.Spec.Names.Plural},
  1614. },
  1615. }},
  1616. ClientConfig: admissionregistrationv1.WebhookClientConfig{
  1617. Service: &admissionregistrationv1.ServiceReference{
  1618. Namespace: namespace,
  1619. Name: serviceName,
  1620. Path: strPtr("/mutating-custom-resource"),
  1621. Port: pointer.Int32Ptr(servicePort),
  1622. },
  1623. CABundle: certCtx.signingCert,
  1624. },
  1625. SideEffects: &sideEffectsNone,
  1626. AdmissionReviewVersions: []string{"v1", "v1beta1"},
  1627. // Scope the webhook to just this namespace
  1628. NamespaceSelector: &metav1.LabelSelector{
  1629. MatchLabels: map[string]string{f.UniqueName: "true"},
  1630. },
  1631. },
  1632. {
  1633. Name: "mutate-custom-resource-data-stage-2.k8s.io",
  1634. Rules: []admissionregistrationv1.RuleWithOperations{{
  1635. Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Create},
  1636. Rule: admissionregistrationv1.Rule{
  1637. APIGroups: []string{testcrd.Crd.Spec.Group},
  1638. APIVersions: servedAPIVersions(testcrd.Crd),
  1639. Resources: []string{testcrd.Crd.Spec.Names.Plural},
  1640. },
  1641. }},
  1642. ClientConfig: admissionregistrationv1.WebhookClientConfig{
  1643. Service: &admissionregistrationv1.ServiceReference{
  1644. Namespace: namespace,
  1645. Name: serviceName,
  1646. Path: strPtr("/mutating-custom-resource"),
  1647. Port: pointer.Int32Ptr(servicePort),
  1648. },
  1649. CABundle: certCtx.signingCert,
  1650. },
  1651. SideEffects: &sideEffectsNone,
  1652. AdmissionReviewVersions: []string{"v1", "v1beta1"},
  1653. // Scope the webhook to just this namespace
  1654. NamespaceSelector: &metav1.LabelSelector{
  1655. MatchLabels: map[string]string{f.UniqueName: "true"},
  1656. },
  1657. },
  1658. // Register a webhook that can be probed by marker requests to detect when the configuration is ready.
  1659. newMutatingIsReadyWebhookFixture(f, certCtx, servicePort),
  1660. },
  1661. })
  1662. framework.ExpectNoError(err, "registering custom resource webhook config %s with namespace %s", configName, namespace)
  1663. err = waitWebhookConfigurationReady(f)
  1664. framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
  1665. return func() {
  1666. client.AdmissionregistrationV1().MutatingWebhookConfigurations().Delete(context.TODO(), configName, nil)
  1667. }
  1668. }
  1669. func testCustomResourceWebhook(f *framework.Framework, crd *apiextensionsv1.CustomResourceDefinition, customResourceClient dynamic.ResourceInterface) {
  1670. ginkgo.By("Creating a custom resource that should be denied by the webhook")
  1671. crInstanceName := "cr-instance-1"
  1672. crInstance := &unstructured.Unstructured{
  1673. Object: map[string]interface{}{
  1674. "kind": crd.Spec.Names.Kind,
  1675. "apiVersion": crd.Spec.Group + "/" + crd.Spec.Versions[0].Name,
  1676. "metadata": map[string]interface{}{
  1677. "name": crInstanceName,
  1678. "namespace": f.Namespace.Name,
  1679. },
  1680. "data": map[string]interface{}{
  1681. "webhook-e2e-test": "webhook-disallow",
  1682. },
  1683. },
  1684. }
  1685. _, err := customResourceClient.Create(crInstance, metav1.CreateOptions{})
  1686. framework.ExpectError(err, "create custom resource %s in namespace %s should be denied by webhook", crInstanceName, f.Namespace.Name)
  1687. expectedErrMsg := "the custom resource contains unwanted data"
  1688. if !strings.Contains(err.Error(), expectedErrMsg) {
  1689. framework.Failf("expect error contains %q, got %q", expectedErrMsg, err.Error())
  1690. }
  1691. }
  1692. func testBlockingCustomResourceUpdateDeletion(f *framework.Framework, crd *apiextensionsv1.CustomResourceDefinition, customResourceClient dynamic.ResourceInterface) {
  1693. ginkgo.By("Creating a custom resource whose deletion would be denied by the webhook")
  1694. crInstanceName := "cr-instance-2"
  1695. crInstance := &unstructured.Unstructured{
  1696. Object: map[string]interface{}{
  1697. "kind": crd.Spec.Names.Kind,
  1698. "apiVersion": crd.Spec.Group + "/" + crd.Spec.Versions[0].Name,
  1699. "metadata": map[string]interface{}{
  1700. "name": crInstanceName,
  1701. "namespace": f.Namespace.Name,
  1702. },
  1703. "data": map[string]interface{}{
  1704. "webhook-e2e-test": "webhook-nondeletable",
  1705. },
  1706. },
  1707. }
  1708. _, err := customResourceClient.Create(crInstance, metav1.CreateOptions{})
  1709. framework.ExpectNoError(err, "failed to create custom resource %s in namespace: %s", crInstanceName, f.Namespace.Name)
  1710. ginkgo.By("Updating the custom resource with disallowed data should be denied")
  1711. toNonCompliantFn := func(cr *unstructured.Unstructured) {
  1712. if _, ok := cr.Object["data"]; !ok {
  1713. cr.Object["data"] = map[string]interface{}{}
  1714. }
  1715. data := cr.Object["data"].(map[string]interface{})
  1716. data["webhook-e2e-test"] = "webhook-disallow"
  1717. }
  1718. _, err = updateCustomResource(customResourceClient, f.Namespace.Name, crInstanceName, toNonCompliantFn)
  1719. framework.ExpectError(err, "updating custom resource %s in namespace: %s should be denied", crInstanceName, f.Namespace.Name)
  1720. expectedErrMsg := "the custom resource contains unwanted data"
  1721. if !strings.Contains(err.Error(), expectedErrMsg) {
  1722. framework.Failf("expect error contains %q, got %q", expectedErrMsg, err.Error())
  1723. }
  1724. ginkgo.By("Deleting the custom resource should be denied")
  1725. err = customResourceClient.Delete(crInstanceName, &metav1.DeleteOptions{})
  1726. framework.ExpectError(err, "deleting custom resource %s in namespace: %s should be denied", crInstanceName, f.Namespace.Name)
  1727. expectedErrMsg1 := "the custom resource cannot be deleted because it contains unwanted key and value"
  1728. if !strings.Contains(err.Error(), expectedErrMsg1) {
  1729. framework.Failf("expect error contains %q, got %q", expectedErrMsg1, err.Error())
  1730. }
  1731. ginkgo.By("Remove the offending key and value from the custom resource data")
  1732. toCompliantFn := func(cr *unstructured.Unstructured) {
  1733. if _, ok := cr.Object["data"]; !ok {
  1734. cr.Object["data"] = map[string]interface{}{}
  1735. }
  1736. data := cr.Object["data"].(map[string]interface{})
  1737. data["webhook-e2e-test"] = "webhook-allow"
  1738. }
  1739. _, err = updateCustomResource(customResourceClient, f.Namespace.Name, crInstanceName, toCompliantFn)
  1740. framework.ExpectNoError(err, "failed to update custom resource %s in namespace: %s", crInstanceName, f.Namespace.Name)
  1741. ginkgo.By("Deleting the updated custom resource should be successful")
  1742. err = customResourceClient.Delete(crInstanceName, &metav1.DeleteOptions{})
  1743. framework.ExpectNoError(err, "failed to delete custom resource %s in namespace: %s", crInstanceName, f.Namespace.Name)
  1744. }
  1745. func testMutatingCustomResourceWebhook(f *framework.Framework, crd *apiextensionsv1.CustomResourceDefinition, customResourceClient dynamic.ResourceInterface, prune bool) {
  1746. ginkgo.By("Creating a custom resource that should be mutated by the webhook")
  1747. crName := "cr-instance-1"
  1748. cr := &unstructured.Unstructured{
  1749. Object: map[string]interface{}{
  1750. "kind": crd.Spec.Names.Kind,
  1751. "apiVersion": crd.Spec.Group + "/" + crd.Spec.Versions[0].Name,
  1752. "metadata": map[string]interface{}{
  1753. "name": crName,
  1754. "namespace": f.Namespace.Name,
  1755. },
  1756. "data": map[string]interface{}{
  1757. "mutation-start": "yes",
  1758. },
  1759. },
  1760. }
  1761. mutatedCR, err := customResourceClient.Create(cr, metav1.CreateOptions{})
  1762. framework.ExpectNoError(err, "failed to create custom resource %s in namespace: %s", crName, f.Namespace.Name)
  1763. expectedCRData := map[string]interface{}{
  1764. "mutation-start": "yes",
  1765. "mutation-stage-1": "yes",
  1766. }
  1767. if !prune {
  1768. expectedCRData["mutation-stage-2"] = "yes"
  1769. }
  1770. if !reflect.DeepEqual(expectedCRData, mutatedCR.Object["data"]) {
  1771. framework.Failf("\nexpected %#v\n, got %#v\n", expectedCRData, mutatedCR.Object["data"])
  1772. }
  1773. }
  1774. func testMultiVersionCustomResourceWebhook(f *framework.Framework, testcrd *crd.TestCrd) {
  1775. customResourceClient := testcrd.DynamicClients["v1"]
  1776. ginkgo.By("Creating a custom resource while v1 is storage version")
  1777. crName := "cr-instance-1"
  1778. cr := &unstructured.Unstructured{
  1779. Object: map[string]interface{}{
  1780. "kind": testcrd.Crd.Spec.Names.Kind,
  1781. "apiVersion": testcrd.Crd.Spec.Group + "/" + testcrd.Crd.Spec.Versions[0].Name,
  1782. "metadata": map[string]interface{}{
  1783. "name": crName,
  1784. "namespace": f.Namespace.Name,
  1785. },
  1786. "data": map[string]interface{}{
  1787. "mutation-start": "yes",
  1788. },
  1789. },
  1790. }
  1791. _, err := customResourceClient.Create(cr, metav1.CreateOptions{})
  1792. framework.ExpectNoError(err, "failed to create custom resource %s in namespace: %s", crName, f.Namespace.Name)
  1793. ginkgo.By("Patching Custom Resource Definition to set v2 as storage")
  1794. apiVersionWithV2StoragePatch := `{
  1795. "spec": {
  1796. "versions": [
  1797. {
  1798. "name": "v1",
  1799. "storage": false,
  1800. "served": true,
  1801. "schema": {
  1802. "openAPIV3Schema": {"x-kubernetes-preserve-unknown-fields": true, "type": "object"}
  1803. }
  1804. },
  1805. {
  1806. "name": "v2",
  1807. "storage": true,
  1808. "served": true,
  1809. "schema": {
  1810. "openAPIV3Schema": {"x-kubernetes-preserve-unknown-fields": true, "type": "object"}
  1811. }
  1812. }
  1813. ]
  1814. }
  1815. }`
  1816. _, err = testcrd.APIExtensionClient.ApiextensionsV1().CustomResourceDefinitions().Patch(context.TODO(), testcrd.Crd.Name, types.StrategicMergePatchType, []byte(apiVersionWithV2StoragePatch), metav1.PatchOptions{})
  1817. framework.ExpectNoError(err, "failed to patch custom resource definition %s in namespace: %s", testcrd.Crd.Name, f.Namespace.Name)
  1818. ginkgo.By("Patching the custom resource while v2 is storage version")
  1819. crDummyPatch := fmt.Sprint(`[{ "op": "add", "path": "/dummy", "value": "test" }]`)
  1820. mutatedCR, err := testcrd.DynamicClients["v2"].Patch(crName, types.JSONPatchType, []byte(crDummyPatch), metav1.PatchOptions{})
  1821. framework.ExpectNoError(err, "failed to patch custom resource %s in namespace: %s", crName, f.Namespace.Name)
  1822. expectedCRData := map[string]interface{}{
  1823. "mutation-start": "yes",
  1824. "mutation-stage-1": "yes",
  1825. "mutation-stage-2": "yes",
  1826. }
  1827. if !reflect.DeepEqual(expectedCRData, mutatedCR.Object["data"]) {
  1828. framework.Failf("\nexpected %#v\n, got %#v\n", expectedCRData, mutatedCR.Object["data"])
  1829. }
  1830. if !reflect.DeepEqual("test", mutatedCR.Object["dummy"]) {
  1831. framework.Failf("\nexpected %#v\n, got %#v\n", "test", mutatedCR.Object["dummy"])
  1832. }
  1833. }
  1834. func registerValidatingWebhookForCRD(f *framework.Framework, configName string, certCtx *certContext, servicePort int32) func() {
  1835. client := f.ClientSet
  1836. ginkgo.By("Registering the crd webhook via the AdmissionRegistration API")
  1837. namespace := f.Namespace.Name
  1838. sideEffectsNone := admissionregistrationv1.SideEffectClassNone
  1839. // This webhook will deny the creation of CustomResourceDefinitions which have the
  1840. // label "webhook-e2e-test":"webhook-disallow"
  1841. // NOTE: Because tests are run in parallel and in an unpredictable order, it is critical
  1842. // that no other test attempts to create CRD with that label.
  1843. _, err := createValidatingWebhookConfiguration(f, &admissionregistrationv1.ValidatingWebhookConfiguration{
  1844. ObjectMeta: metav1.ObjectMeta{
  1845. Name: configName,
  1846. },
  1847. Webhooks: []admissionregistrationv1.ValidatingWebhook{
  1848. {
  1849. Name: "deny-crd-with-unwanted-label.k8s.io",
  1850. Rules: []admissionregistrationv1.RuleWithOperations{{
  1851. Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Create},
  1852. Rule: admissionregistrationv1.Rule{
  1853. APIGroups: []string{"apiextensions.k8s.io"},
  1854. APIVersions: []string{"*"},
  1855. Resources: []string{"customresourcedefinitions"},
  1856. },
  1857. }},
  1858. ClientConfig: admissionregistrationv1.WebhookClientConfig{
  1859. Service: &admissionregistrationv1.ServiceReference{
  1860. Namespace: namespace,
  1861. Name: serviceName,
  1862. Path: strPtr("/crd"),
  1863. Port: pointer.Int32Ptr(servicePort),
  1864. },
  1865. CABundle: certCtx.signingCert,
  1866. },
  1867. SideEffects: &sideEffectsNone,
  1868. AdmissionReviewVersions: []string{"v1", "v1beta1"},
  1869. // Scope the webhook to just this test
  1870. ObjectSelector: &metav1.LabelSelector{
  1871. MatchLabels: map[string]string{f.UniqueName: "true"},
  1872. },
  1873. },
  1874. // Register a webhook that can be probed by marker requests to detect when the configuration is ready.
  1875. newValidatingIsReadyWebhookFixture(f, certCtx, servicePort),
  1876. },
  1877. })
  1878. framework.ExpectNoError(err, "registering crd webhook config %s with namespace %s", configName, namespace)
  1879. err = waitWebhookConfigurationReady(f)
  1880. framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
  1881. return func() {
  1882. client.AdmissionregistrationV1().ValidatingWebhookConfigurations().Delete(context.TODO(), configName, nil)
  1883. }
  1884. }
  1885. func testCRDDenyWebhook(f *framework.Framework) {
  1886. ginkgo.By("Creating a custom resource definition that should be denied by the webhook")
  1887. name := fmt.Sprintf("e2e-test-%s-%s-crd", f.BaseName, "deny")
  1888. kind := fmt.Sprintf("E2e-test-%s-%s-crd", f.BaseName, "deny")
  1889. group := fmt.Sprintf("%s.example.com", f.BaseName)
  1890. apiVersions := []apiextensionsv1.CustomResourceDefinitionVersion{
  1891. {
  1892. Name: "v1",
  1893. Served: true,
  1894. Storage: true,
  1895. Schema: &apiextensionsv1.CustomResourceValidation{
  1896. OpenAPIV3Schema: &apiextensionsv1.JSONSchemaProps{
  1897. XPreserveUnknownFields: pointer.BoolPtr(true),
  1898. Type: "object",
  1899. },
  1900. },
  1901. },
  1902. }
  1903. // Creating a custom resource definition for use by assorted tests.
  1904. config, err := framework.LoadConfig()
  1905. if err != nil {
  1906. framework.Failf("failed to load config: %v", err)
  1907. return
  1908. }
  1909. apiExtensionClient, err := crdclientset.NewForConfig(config)
  1910. if err != nil {
  1911. framework.Failf("failed to initialize apiExtensionClient: %v", err)
  1912. return
  1913. }
  1914. crd := &apiextensionsv1.CustomResourceDefinition{
  1915. ObjectMeta: metav1.ObjectMeta{
  1916. Name: name + "s." + group,
  1917. Labels: map[string]string{
  1918. // this label ensures our object is routed to this test's webhook
  1919. f.UniqueName: "true",
  1920. // this is the label the webhook disallows
  1921. "webhook-e2e-test": "webhook-disallow",
  1922. },
  1923. },
  1924. Spec: apiextensionsv1.CustomResourceDefinitionSpec{
  1925. Group: group,
  1926. Versions: apiVersions,
  1927. Names: apiextensionsv1.CustomResourceDefinitionNames{
  1928. Singular: name,
  1929. Kind: kind,
  1930. ListKind: kind + "List",
  1931. Plural: name + "s",
  1932. },
  1933. Scope: apiextensionsv1.NamespaceScoped,
  1934. },
  1935. }
  1936. // create CRD
  1937. _, err = apiExtensionClient.ApiextensionsV1().CustomResourceDefinitions().Create(context.TODO(), crd, metav1.CreateOptions{})
  1938. framework.ExpectError(err, "create custom resource definition %s should be denied by webhook", crd.Name)
  1939. expectedErrMsg := "the crd contains unwanted label"
  1940. if !strings.Contains(err.Error(), expectedErrMsg) {
  1941. framework.Failf("expect error contains %q, got %q", expectedErrMsg, err.Error())
  1942. }
  1943. }
  1944. func labelNamespace(f *framework.Framework, namespace string) {
  1945. client := f.ClientSet
  1946. // Add a unique label to the namespace
  1947. ns, err := client.CoreV1().Namespaces().Get(context.TODO(), namespace, metav1.GetOptions{})
  1948. framework.ExpectNoError(err, "error getting namespace %s", namespace)
  1949. if ns.Labels == nil {
  1950. ns.Labels = map[string]string{}
  1951. }
  1952. ns.Labels[f.UniqueName] = "true"
  1953. _, err = client.CoreV1().Namespaces().Update(context.TODO(), ns, metav1.UpdateOptions{})
  1954. framework.ExpectNoError(err, "error labeling namespace %s", namespace)
  1955. }
  1956. func registerSlowWebhook(f *framework.Framework, configName string, certCtx *certContext, policy *admissionregistrationv1.FailurePolicyType, timeout *int32, servicePort int32) func() {
  1957. client := f.ClientSet
  1958. ginkgo.By("Registering slow webhook via the AdmissionRegistration API")
  1959. namespace := f.Namespace.Name
  1960. sideEffectsNone := admissionregistrationv1.SideEffectClassNone
  1961. _, err := createValidatingWebhookConfiguration(f, &admissionregistrationv1.ValidatingWebhookConfiguration{
  1962. ObjectMeta: metav1.ObjectMeta{
  1963. Name: configName,
  1964. },
  1965. Webhooks: []admissionregistrationv1.ValidatingWebhook{
  1966. {
  1967. Name: "allow-configmap-with-delay-webhook.k8s.io",
  1968. Rules: []admissionregistrationv1.RuleWithOperations{{
  1969. Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Create},
  1970. Rule: admissionregistrationv1.Rule{
  1971. APIGroups: []string{""},
  1972. APIVersions: []string{"v1"},
  1973. Resources: []string{"configmaps"},
  1974. },
  1975. }},
  1976. ClientConfig: admissionregistrationv1.WebhookClientConfig{
  1977. Service: &admissionregistrationv1.ServiceReference{
  1978. Namespace: namespace,
  1979. Name: serviceName,
  1980. Path: strPtr("/always-allow-delay-5s"),
  1981. Port: pointer.Int32Ptr(servicePort),
  1982. },
  1983. CABundle: certCtx.signingCert,
  1984. },
  1985. // Scope the webhook to just this namespace
  1986. NamespaceSelector: &metav1.LabelSelector{
  1987. MatchLabels: map[string]string{f.UniqueName: "true"},
  1988. },
  1989. FailurePolicy: policy,
  1990. TimeoutSeconds: timeout,
  1991. SideEffects: &sideEffectsNone,
  1992. AdmissionReviewVersions: []string{"v1", "v1beta1"},
  1993. },
  1994. // Register a webhook that can be probed by marker requests to detect when the configuration is ready.
  1995. newValidatingIsReadyWebhookFixture(f, certCtx, servicePort),
  1996. },
  1997. })
  1998. framework.ExpectNoError(err, "registering slow webhook config %s with namespace %s", configName, namespace)
  1999. err = waitWebhookConfigurationReady(f)
  2000. framework.ExpectNoError(err, "waiting for webhook configuration to be ready")
  2001. return func() {
  2002. client.AdmissionregistrationV1().ValidatingWebhookConfigurations().Delete(context.TODO(), configName, nil)
  2003. }
  2004. }
  2005. func testSlowWebhookTimeoutFailEarly(f *framework.Framework) {
  2006. ginkgo.By("Request fails when timeout (1s) is shorter than slow webhook latency (5s)")
  2007. client := f.ClientSet
  2008. name := "e2e-test-slow-webhook-configmap"
  2009. _, err := client.CoreV1().ConfigMaps(f.Namespace.Name).Create(context.TODO(), &v1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: name}}, metav1.CreateOptions{})
  2010. framework.ExpectError(err, "create configmap in namespace %s should have timed-out reaching slow webhook", f.Namespace.Name)
  2011. // http timeout message: context deadline exceeded
  2012. // dial timeout message: dial tcp {address}: i/o timeout
  2013. isTimeoutError := strings.Contains(err.Error(), `context deadline exceeded`) || strings.Contains(err.Error(), `timeout`)
  2014. isErrorQueryingWebhook := strings.Contains(err.Error(), `/always-allow-delay-5s?timeout=1s`)
  2015. if !isTimeoutError || !isErrorQueryingWebhook {
  2016. framework.Failf("expect an HTTP/dial timeout error querying the slow webhook, got: %q", err.Error())
  2017. }
  2018. }
  2019. func testSlowWebhookTimeoutNoError(f *framework.Framework) {
  2020. client := f.ClientSet
  2021. name := "e2e-test-slow-webhook-configmap"
  2022. _, err := client.CoreV1().ConfigMaps(f.Namespace.Name).Create(context.TODO(), &v1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: name}}, metav1.CreateOptions{})
  2023. gomega.Expect(err).To(gomega.BeNil())
  2024. err = client.CoreV1().ConfigMaps(f.Namespace.Name).Delete(context.TODO(), name, &metav1.DeleteOptions{})
  2025. gomega.Expect(err).To(gomega.BeNil())
  2026. }
  2027. // createAdmissionWebhookMultiVersionTestCRDWithV1Storage creates a new CRD specifically
  2028. // for the admissin webhook calling test.
  2029. func createAdmissionWebhookMultiVersionTestCRDWithV1Storage(f *framework.Framework, opts ...crd.Option) (*crd.TestCrd, error) {
  2030. group := fmt.Sprintf("%s.example.com", f.BaseName)
  2031. return crd.CreateMultiVersionTestCRD(f, group, append([]crd.Option{func(crd *apiextensionsv1.CustomResourceDefinition) {
  2032. crd.Spec.Versions = []apiextensionsv1.CustomResourceDefinitionVersion{
  2033. {
  2034. Name: "v1",
  2035. Served: true,
  2036. Storage: true,
  2037. Schema: &apiextensionsv1.CustomResourceValidation{
  2038. OpenAPIV3Schema: &apiextensionsv1.JSONSchemaProps{
  2039. XPreserveUnknownFields: pointer.BoolPtr(true),
  2040. Type: "object",
  2041. },
  2042. },
  2043. },
  2044. {
  2045. Name: "v2",
  2046. Served: true,
  2047. Storage: false,
  2048. Schema: &apiextensionsv1.CustomResourceValidation{
  2049. OpenAPIV3Schema: &apiextensionsv1.JSONSchemaProps{
  2050. XPreserveUnknownFields: pointer.BoolPtr(true),
  2051. Type: "object",
  2052. },
  2053. },
  2054. },
  2055. }
  2056. }}, opts...)...)
  2057. }
  2058. // servedAPIVersions returns the API versions served by the CRD.
  2059. func servedAPIVersions(crd *apiextensionsv1.CustomResourceDefinition) []string {
  2060. ret := []string{}
  2061. for _, v := range crd.Spec.Versions {
  2062. if v.Served {
  2063. ret = append(ret, v.Name)
  2064. }
  2065. }
  2066. return ret
  2067. }
  2068. // createValidatingWebhookConfiguration ensures the webhook config scopes object or namespace selection
  2069. // to avoid interfering with other tests, then creates the config.
  2070. func createValidatingWebhookConfiguration(f *framework.Framework, config *admissionregistrationv1.ValidatingWebhookConfiguration) (*admissionregistrationv1.ValidatingWebhookConfiguration, error) {
  2071. for _, webhook := range config.Webhooks {
  2072. if webhook.NamespaceSelector != nil && webhook.NamespaceSelector.MatchLabels[f.UniqueName] == "true" {
  2073. continue
  2074. }
  2075. if webhook.ObjectSelector != nil && webhook.ObjectSelector.MatchLabels[f.UniqueName] == "true" {
  2076. continue
  2077. }
  2078. framework.Failf(`webhook %s in config %s has no namespace or object selector with %s="true", and can interfere with other tests`, webhook.Name, config.Name, f.UniqueName)
  2079. }
  2080. return f.ClientSet.AdmissionregistrationV1().ValidatingWebhookConfigurations().Create(context.TODO(), config, metav1.CreateOptions{})
  2081. }
  2082. // createMutatingWebhookConfiguration ensures the webhook config scopes object or namespace selection
  2083. // to avoid interfering with other tests, then creates the config.
  2084. func createMutatingWebhookConfiguration(f *framework.Framework, config *admissionregistrationv1.MutatingWebhookConfiguration) (*admissionregistrationv1.MutatingWebhookConfiguration, error) {
  2085. for _, webhook := range config.Webhooks {
  2086. if webhook.NamespaceSelector != nil && webhook.NamespaceSelector.MatchLabels[f.UniqueName] == "true" {
  2087. continue
  2088. }
  2089. if webhook.ObjectSelector != nil && webhook.ObjectSelector.MatchLabels[f.UniqueName] == "true" {
  2090. continue
  2091. }
  2092. framework.Failf(`webhook %s in config %s has no namespace or object selector with %s="true", and can interfere with other tests`, webhook.Name, config.Name, f.UniqueName)
  2093. }
  2094. return f.ClientSet.AdmissionregistrationV1().MutatingWebhookConfigurations().Create(context.TODO(), config, metav1.CreateOptions{})
  2095. }
  2096. func newDenyPodWebhookFixture(f *framework.Framework, certCtx *certContext, servicePort int32) admissionregistrationv1.ValidatingWebhook {
  2097. sideEffectsNone := admissionregistrationv1.SideEffectClassNone
  2098. return admissionregistrationv1.ValidatingWebhook{
  2099. Name: "deny-unwanted-pod-container-name-and-label.k8s.io",
  2100. Rules: []admissionregistrationv1.RuleWithOperations{{
  2101. Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Create},
  2102. Rule: admissionregistrationv1.Rule{
  2103. APIGroups: []string{""},
  2104. APIVersions: []string{"v1"},
  2105. Resources: []string{"pods"},
  2106. },
  2107. }},
  2108. ClientConfig: admissionregistrationv1.WebhookClientConfig{
  2109. Service: &admissionregistrationv1.ServiceReference{
  2110. Namespace: f.Namespace.Name,
  2111. Name: serviceName,
  2112. Path: strPtr("/pods"),
  2113. Port: pointer.Int32Ptr(servicePort),
  2114. },
  2115. CABundle: certCtx.signingCert,
  2116. },
  2117. SideEffects: &sideEffectsNone,
  2118. AdmissionReviewVersions: []string{"v1", "v1beta1"},
  2119. // Scope the webhook to just this namespace
  2120. NamespaceSelector: &metav1.LabelSelector{
  2121. MatchLabels: map[string]string{f.UniqueName: "true"},
  2122. },
  2123. }
  2124. }
  2125. func newDenyConfigMapWebhookFixture(f *framework.Framework, certCtx *certContext, servicePort int32) admissionregistrationv1.ValidatingWebhook {
  2126. sideEffectsNone := admissionregistrationv1.SideEffectClassNone
  2127. return admissionregistrationv1.ValidatingWebhook{
  2128. Name: "deny-unwanted-configmap-data.k8s.io",
  2129. Rules: []admissionregistrationv1.RuleWithOperations{{
  2130. Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Create, admissionregistrationv1.Update, admissionregistrationv1.Delete},
  2131. Rule: admissionregistrationv1.Rule{
  2132. APIGroups: []string{""},
  2133. APIVersions: []string{"v1"},
  2134. Resources: []string{"configmaps"},
  2135. },
  2136. }},
  2137. // The webhook skips the namespace that has label "skip-webhook-admission":"yes"
  2138. NamespaceSelector: &metav1.LabelSelector{
  2139. MatchLabels: map[string]string{f.UniqueName: "true"},
  2140. MatchExpressions: []metav1.LabelSelectorRequirement{
  2141. {
  2142. Key: skipNamespaceLabelKey,
  2143. Operator: metav1.LabelSelectorOpNotIn,
  2144. Values: []string{skipNamespaceLabelValue},
  2145. },
  2146. },
  2147. },
  2148. ClientConfig: admissionregistrationv1.WebhookClientConfig{
  2149. Service: &admissionregistrationv1.ServiceReference{
  2150. Namespace: f.Namespace.Name,
  2151. Name: serviceName,
  2152. Path: strPtr("/configmaps"),
  2153. Port: pointer.Int32Ptr(servicePort),
  2154. },
  2155. CABundle: certCtx.signingCert,
  2156. },
  2157. SideEffects: &sideEffectsNone,
  2158. AdmissionReviewVersions: []string{"v1", "v1beta1"},
  2159. }
  2160. }
  2161. func newMutateConfigMapWebhookFixture(f *framework.Framework, certCtx *certContext, stage int, servicePort int32) admissionregistrationv1.MutatingWebhook {
  2162. sideEffectsNone := admissionregistrationv1.SideEffectClassNone
  2163. return admissionregistrationv1.MutatingWebhook{
  2164. Name: fmt.Sprintf("adding-configmap-data-stage-%d.k8s.io", stage),
  2165. Rules: []admissionregistrationv1.RuleWithOperations{{
  2166. Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Create},
  2167. Rule: admissionregistrationv1.Rule{
  2168. APIGroups: []string{""},
  2169. APIVersions: []string{"v1"},
  2170. Resources: []string{"configmaps"},
  2171. },
  2172. }},
  2173. ClientConfig: admissionregistrationv1.WebhookClientConfig{
  2174. Service: &admissionregistrationv1.ServiceReference{
  2175. Namespace: f.Namespace.Name,
  2176. Name: serviceName,
  2177. Path: strPtr("/mutating-configmaps"),
  2178. Port: pointer.Int32Ptr(servicePort),
  2179. },
  2180. CABundle: certCtx.signingCert,
  2181. },
  2182. SideEffects: &sideEffectsNone,
  2183. AdmissionReviewVersions: []string{"v1", "v1beta1"},
  2184. // Scope the webhook to just this namespace
  2185. NamespaceSelector: &metav1.LabelSelector{
  2186. MatchLabels: map[string]string{f.UniqueName: "true"},
  2187. },
  2188. }
  2189. }
  2190. // createWebhookConfigurationReadyNamespace creates a separate namespace for webhook configuration ready markers to
  2191. // prevent cross-talk with webhook configurations being tested.
  2192. func createWebhookConfigurationReadyNamespace(f *framework.Framework) {
  2193. ns, err := f.ClientSet.CoreV1().Namespaces().Create(context.TODO(), &v1.Namespace{
  2194. ObjectMeta: metav1.ObjectMeta{
  2195. Name: f.Namespace.Name + "-markers",
  2196. Labels: map[string]string{f.UniqueName + "-markers": "true"},
  2197. },
  2198. }, metav1.CreateOptions{})
  2199. framework.ExpectNoError(err, "creating namespace for webhook configuration ready markers")
  2200. f.AddNamespacesToDelete(ns)
  2201. }
  2202. // waitWebhookConfigurationReady sends "marker" requests until a webhook configuration is ready.
  2203. // A webhook created with newValidatingIsReadyWebhookFixture or newMutatingIsReadyWebhookFixture should first be added to
  2204. // the webhook configuration.
  2205. func waitWebhookConfigurationReady(f *framework.Framework) error {
  2206. cmClient := f.ClientSet.CoreV1().ConfigMaps(f.Namespace.Name + "-markers")
  2207. return wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (bool, error) {
  2208. marker := &v1.ConfigMap{
  2209. ObjectMeta: metav1.ObjectMeta{
  2210. Name: string(uuid.NewUUID()),
  2211. Labels: map[string]string{
  2212. f.UniqueName: "true",
  2213. },
  2214. },
  2215. }
  2216. _, err := cmClient.Create(context.TODO(), marker, metav1.CreateOptions{})
  2217. if err != nil {
  2218. // The always-deny webhook does not provide a reason, so check for the error string we expect
  2219. if strings.Contains(err.Error(), "denied") {
  2220. return true, nil
  2221. }
  2222. return false, err
  2223. }
  2224. // best effort cleanup of markers that are no longer needed
  2225. _ = cmClient.Delete(context.TODO(), marker.GetName(), nil)
  2226. framework.Logf("Waiting for webhook configuration to be ready...")
  2227. return false, nil
  2228. })
  2229. }
  2230. // newValidatingIsReadyWebhookFixture creates a validating webhook that can be added to a webhook configuration and then probed
  2231. // with "marker" requests via waitWebhookConfigurationReady to wait for a webhook configuration to be ready.
  2232. func newValidatingIsReadyWebhookFixture(f *framework.Framework, certCtx *certContext, servicePort int32) admissionregistrationv1.ValidatingWebhook {
  2233. sideEffectsNone := admissionregistrationv1.SideEffectClassNone
  2234. failOpen := admissionregistrationv1.Ignore
  2235. return admissionregistrationv1.ValidatingWebhook{
  2236. Name: "validating-is-webhook-configuration-ready.k8s.io",
  2237. Rules: []admissionregistrationv1.RuleWithOperations{{
  2238. Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Create},
  2239. Rule: admissionregistrationv1.Rule{
  2240. APIGroups: []string{""},
  2241. APIVersions: []string{"v1"},
  2242. Resources: []string{"configmaps"},
  2243. },
  2244. }},
  2245. ClientConfig: admissionregistrationv1.WebhookClientConfig{
  2246. Service: &admissionregistrationv1.ServiceReference{
  2247. Namespace: f.Namespace.Name,
  2248. Name: serviceName,
  2249. Path: strPtr("/always-deny"),
  2250. Port: pointer.Int32Ptr(servicePort),
  2251. },
  2252. CABundle: certCtx.signingCert,
  2253. },
  2254. // network failures while the service network routing is being set up should be ignored by the marker
  2255. FailurePolicy: &failOpen,
  2256. SideEffects: &sideEffectsNone,
  2257. AdmissionReviewVersions: []string{"v1", "v1beta1"},
  2258. // Scope the webhook to just the markers namespace
  2259. NamespaceSelector: &metav1.LabelSelector{
  2260. MatchLabels: map[string]string{f.UniqueName + "-markers": "true"},
  2261. },
  2262. // appease createValidatingWebhookConfiguration isolation requirements
  2263. ObjectSelector: &metav1.LabelSelector{
  2264. MatchLabels: map[string]string{f.UniqueName: "true"},
  2265. },
  2266. }
  2267. }
  2268. // newMutatingIsReadyWebhookFixture creates a mutating webhook that can be added to a webhook configuration and then probed
  2269. // with "marker" requests via waitWebhookConfigurationReady to wait for a webhook configuration to be ready.
  2270. func newMutatingIsReadyWebhookFixture(f *framework.Framework, certCtx *certContext, servicePort int32) admissionregistrationv1.MutatingWebhook {
  2271. sideEffectsNone := admissionregistrationv1.SideEffectClassNone
  2272. failOpen := admissionregistrationv1.Ignore
  2273. return admissionregistrationv1.MutatingWebhook{
  2274. Name: "mutating-is-webhook-configuration-ready.k8s.io",
  2275. Rules: []admissionregistrationv1.RuleWithOperations{{
  2276. Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Create},
  2277. Rule: admissionregistrationv1.Rule{
  2278. APIGroups: []string{""},
  2279. APIVersions: []string{"v1"},
  2280. Resources: []string{"configmaps"},
  2281. },
  2282. }},
  2283. ClientConfig: admissionregistrationv1.WebhookClientConfig{
  2284. Service: &admissionregistrationv1.ServiceReference{
  2285. Namespace: f.Namespace.Name,
  2286. Name: serviceName,
  2287. Path: strPtr("/always-deny"),
  2288. Port: pointer.Int32Ptr(servicePort),
  2289. },
  2290. CABundle: certCtx.signingCert,
  2291. },
  2292. // network failures while the service network routing is being set up should be ignored by the marker
  2293. FailurePolicy: &failOpen,
  2294. SideEffects: &sideEffectsNone,
  2295. AdmissionReviewVersions: []string{"v1", "v1beta1"},
  2296. // Scope the webhook to just the markers namespace
  2297. NamespaceSelector: &metav1.LabelSelector{
  2298. MatchLabels: map[string]string{f.UniqueName + "-markers": "true"},
  2299. },
  2300. // appease createMutatingWebhookConfiguration isolation requirements
  2301. ObjectSelector: &metav1.LabelSelector{
  2302. MatchLabels: map[string]string{f.UniqueName: "true"},
  2303. },
  2304. }
  2305. }