webhookconfig_test.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. /*
  2. Copyright © The ESO 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. https://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 webhookconfig
  14. import (
  15. "bytes"
  16. "context"
  17. "time"
  18. admissionregistration "k8s.io/api/admissionregistration/v1"
  19. corev1 "k8s.io/api/core/v1"
  20. discoveryv1 "k8s.io/api/discovery/v1"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/types"
  23. pointer "k8s.io/utils/ptr"
  24. "github.com/external-secrets/external-secrets/runtime/constants"
  25. . "github.com/onsi/ginkgo/v2"
  26. . "github.com/onsi/gomega"
  27. )
  28. const defaultCACert = `-----BEGIN CERTIFICATE-----
  29. MIIDRjCCAi6gAwIBAgIBADANBgkqhkiG9w0BAQsFADA2MRkwFwYDVQQKExBleHRl
  30. cm5hbC1zZWNyZXRzMRkwFwYDVQQDExBleHRlcm5hbC1zZWNyZXRzMB4XDTIyMDIx
  31. NzEwMDYxMFoXDTMyMDIxNTExMDYxMFowNjEZMBcGA1UEChMQZXh0ZXJuYWwtc2Vj
  32. cmV0czEZMBcGA1UEAxMQZXh0ZXJuYWwtc2VjcmV0czCCASIwDQYJKoZIhvcNAQEB
  33. BQADggEPADCCAQoCggEBAKSINgqU2dBdX8JpPjRHWSdpxuoltGl6xXmQHOhbTXAt
  34. /STDu7oi6eiFgepQ2QHuWLGwZgbbYnEhtLvw4dUwPcLyv6WIdeiUSA4pdFxL7asc
  35. WV4tjiRkRTJVrixJTxXpry/CsPqXBlvnu1YGESkrLOYCmA2xnDH8voEBbwYvXXB9
  36. 3g5rOJncSh/7g+H55ZFFyWrIPyDUnfwE3CREjZXpsagFhRYpkuRlXTnU6t0OTEEh
  37. qLHlZ+ebUzL8NaegEgEHD32PrQPXpls1yurIrsA+I6McWkXGykykYHVK+1a1pL1g
  38. e+PBkegtwtX+EmB2ux7PVVeB4TTYqzCKbnObW4mJLZkCAwEAAaNfMF0wDgYDVR0P
  39. AQH/BAQDAgKkMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFHgSu/Im2gyu4TU0
  40. AWrMSFbtoVokMBsGA1UdEQQUMBKCEGV4dGVybmFsLXNlY3JldHMwDQYJKoZIhvcN
  41. AQELBQADggEBAJU88jCcPsAHN8DKLu+QMCoKYbeftX4gXxyoijGSde2w2O8NPtMP
  42. awu4Y5x3LNTwyIIxXi78UD0RI53GbUgHvS+X9v6CC2IZMS65xqKR+EsjzEh7Ldbm
  43. vZoF4ZDnfb2s5SK6MeYf67BE7XWpGfbHmjt6h80xsYjL6ovcik+dlu/AixMyLslS
  44. tDbMybAR8kR0zdQLYcZq7XEX5QsOO8qBn5rTfD6MiYik8ZrP7FqUMHyVpHiBuNio
  45. krnSOvynvuA9mlf2F2727dMt2Ij9uER+9QnhWBQex1h8CwALmm2k9G5Gt+RjB8oe
  46. lNjvmHAXUfOE/cbD7EP++X17kWt41FjmePc=
  47. -----END CERTIFICATE-----
  48. `
  49. type testCase struct {
  50. vwc *admissionregistration.ValidatingWebhookConfiguration
  51. service *corev1.Service
  52. endpointSlice *discoveryv1.EndpointSlice
  53. secret *corev1.Secret
  54. assert func()
  55. }
  56. var _ = Describe("ValidatingWebhookConfig reconcile", Ordered, func() {
  57. var test *testCase
  58. BeforeEach(func() {
  59. test = makeDefaultTestcase()
  60. })
  61. AfterEach(func() {
  62. ctx := context.Background()
  63. k8sClient.Delete(ctx, test.vwc)
  64. k8sClient.Delete(ctx, test.secret)
  65. k8sClient.Delete(ctx, test.service)
  66. k8sClient.Delete(ctx, test.endpointSlice)
  67. })
  68. // Should patch VWC
  69. PatchAndReady := func(tc *testCase) {
  70. // endpoint slice becomes ready in a moment
  71. go func() {
  72. <-time.After(time.Second * 4)
  73. eps := makeEndpointSlice()
  74. err := k8sClient.Update(context.Background(), eps)
  75. Expect(err).ToNot(HaveOccurred())
  76. }()
  77. tc.assert = func() {
  78. Eventually(func() bool {
  79. // the controller should become ready at some point!
  80. err := reconciler.ReadyCheck(nil)
  81. return err == nil
  82. }).
  83. WithTimeout(time.Second * 10).
  84. WithPolling(time.Second).
  85. Should(BeTrue())
  86. Eventually(func() bool {
  87. var vwc admissionregistration.ValidatingWebhookConfiguration
  88. err := k8sClient.Get(context.Background(), types.NamespacedName{
  89. Name: tc.vwc.Name,
  90. }, &vwc)
  91. if err != nil {
  92. return false
  93. }
  94. for _, wc := range vwc.Webhooks {
  95. if !bytes.Equal(wc.ClientConfig.CABundle, []byte(defaultCACert)) {
  96. return false
  97. }
  98. if wc.ClientConfig.Service == nil {
  99. return false
  100. }
  101. if wc.ClientConfig.Service.Name != ctrlSvcName {
  102. return false
  103. }
  104. if wc.ClientConfig.Service.Namespace != ctrlSvcNamespace {
  105. return false
  106. }
  107. }
  108. return true
  109. }).
  110. WithTimeout(time.Second * 10).
  111. WithPolling(time.Second).
  112. Should(BeTrue())
  113. }
  114. }
  115. IgnoreNoMatch := func(tc *testCase) {
  116. delete(tc.vwc.ObjectMeta.Labels, constants.WellKnownLabelKey)
  117. tc.assert = func() {
  118. Consistently(func() bool {
  119. var vwc admissionregistration.ValidatingWebhookConfiguration
  120. err := k8sClient.Get(context.Background(), types.NamespacedName{
  121. Name: tc.vwc.Name,
  122. }, &vwc)
  123. if err != nil {
  124. return false
  125. }
  126. for _, wc := range vwc.Webhooks {
  127. if bytes.Equal(wc.ClientConfig.CABundle, []byte(defaultCACert)) {
  128. return false
  129. }
  130. if wc.ClientConfig.Service.Name == ctrlSvcName {
  131. return false
  132. }
  133. if wc.ClientConfig.Service.Namespace == ctrlSvcNamespace {
  134. return false
  135. }
  136. }
  137. return true
  138. }).
  139. WithTimeout(time.Second * 10).
  140. WithPolling(time.Second).
  141. Should(BeTrue())
  142. }
  143. }
  144. // Should patch and update VWC after requeue duration has passed
  145. PatchAndUpdate := func(tc *testCase) {
  146. foobar := "new value"
  147. // ca cert will change after some time
  148. go func() {
  149. <-time.After(time.Second * 4)
  150. sec := makeSecret()
  151. sec.Data[caCertName] = []byte(foobar)
  152. err := k8sClient.Update(context.Background(), sec)
  153. Expect(err).ToNot(HaveOccurred())
  154. }()
  155. tc.assert = func() {
  156. var resourceVersion string
  157. Eventually(func() bool {
  158. var vwc admissionregistration.ValidatingWebhookConfiguration
  159. err := k8sClient.Get(context.Background(), types.NamespacedName{
  160. Name: tc.vwc.Name,
  161. }, &vwc)
  162. if err != nil {
  163. return false
  164. }
  165. for _, wc := range vwc.Webhooks {
  166. if !bytes.Equal(wc.ClientConfig.CABundle, []byte(foobar)) {
  167. return false
  168. }
  169. if wc.ClientConfig.Service == nil {
  170. return false
  171. }
  172. if wc.ClientConfig.Service.Name != ctrlSvcName {
  173. return false
  174. }
  175. if wc.ClientConfig.Service.Namespace != ctrlSvcNamespace {
  176. return false
  177. }
  178. }
  179. resourceVersion = vwc.ResourceVersion
  180. return true
  181. }).
  182. WithTimeout(time.Second * 10).
  183. WithPolling(time.Second).
  184. Should(BeTrue())
  185. // make sure no additional updates are made
  186. Consistently(func() bool {
  187. var vwc admissionregistration.ValidatingWebhookConfiguration
  188. err := k8sClient.Get(context.Background(), types.NamespacedName{Name: tc.vwc.Name}, &vwc)
  189. if err != nil {
  190. return false
  191. }
  192. return vwc.ResourceVersion == resourceVersion
  193. }).
  194. WithTimeout(time.Second * 10).
  195. WithPolling(time.Second).
  196. Should(BeTrue())
  197. }
  198. }
  199. DescribeTable("Controller Reconcile logic", func(muts ...func(tc *testCase)) {
  200. for _, mut := range muts {
  201. mut(test)
  202. }
  203. ctx := context.Background()
  204. err := k8sClient.Create(ctx, test.vwc)
  205. Expect(err).ToNot(HaveOccurred())
  206. err = k8sClient.Create(ctx, test.secret)
  207. Expect(err).ToNot(HaveOccurred())
  208. err = k8sClient.Create(ctx, test.service)
  209. Expect(err).ToNot(HaveOccurred())
  210. err = k8sClient.Create(ctx, test.endpointSlice)
  211. Expect(err).ToNot(HaveOccurred())
  212. test.assert()
  213. },
  214. Entry("should patch matching webhook configs", PatchAndReady),
  215. Entry("should update vwc with new ca cert after requeue duration", PatchAndUpdate),
  216. Entry("should ignore when vwc labels are missing", IgnoreNoMatch),
  217. )
  218. })
  219. func makeValidatingWebhookConfig() *admissionregistration.ValidatingWebhookConfiguration {
  220. return &admissionregistration.ValidatingWebhookConfiguration{
  221. ObjectMeta: metav1.ObjectMeta{
  222. Name: "name-shouldnt-matter",
  223. Labels: map[string]string{
  224. constants.WellKnownLabelKey: constants.WellKnownLabelValueWebhook,
  225. },
  226. },
  227. Webhooks: []admissionregistration.ValidatingWebhook{
  228. {
  229. Name: "secretstores.external-secrets.io",
  230. SideEffects: (*admissionregistration.SideEffectClass)(pointer.To(string(admissionregistration.SideEffectClassNone))),
  231. AdmissionReviewVersions: []string{"v1"},
  232. ClientConfig: admissionregistration.WebhookClientConfig{
  233. CABundle: []byte("Cg=="),
  234. Service: &admissionregistration.ServiceReference{
  235. Name: "noop",
  236. Namespace: "noop",
  237. Path: new("/validate-secretstore"),
  238. },
  239. },
  240. },
  241. {
  242. Name: "clustersecretstores.external-secrets.io",
  243. SideEffects: (*admissionregistration.SideEffectClass)(pointer.To(string(admissionregistration.SideEffectClassNone))),
  244. AdmissionReviewVersions: []string{"v1"},
  245. ClientConfig: admissionregistration.WebhookClientConfig{
  246. CABundle: []byte("Cg=="),
  247. Service: &admissionregistration.ServiceReference{
  248. Name: "noop",
  249. Namespace: "noop",
  250. Path: new("/validate-clustersecretstore"),
  251. },
  252. },
  253. },
  254. },
  255. }
  256. }
  257. func makeSecret() *corev1.Secret {
  258. return &corev1.Secret{
  259. ObjectMeta: metav1.ObjectMeta{
  260. Name: ctrlSecretName,
  261. Namespace: ctrlSecretNamespace,
  262. },
  263. Data: map[string][]byte{
  264. caCertName: []byte(defaultCACert),
  265. },
  266. }
  267. }
  268. func makeService() *corev1.Service {
  269. return &corev1.Service{
  270. ObjectMeta: metav1.ObjectMeta{
  271. Name: ctrlSvcName,
  272. Namespace: ctrlSvcNamespace,
  273. },
  274. Spec: corev1.ServiceSpec{
  275. Ports: []corev1.ServicePort{
  276. {
  277. Name: "http",
  278. Port: 80,
  279. },
  280. },
  281. },
  282. }
  283. }
  284. func makeEndpointSlice() *discoveryv1.EndpointSlice {
  285. return &discoveryv1.EndpointSlice{
  286. ObjectMeta: metav1.ObjectMeta{
  287. Name: ctrlSvcName + "-slice",
  288. Namespace: ctrlSvcNamespace,
  289. Labels: map[string]string{
  290. "kubernetes.io/service-name": ctrlSvcName,
  291. },
  292. },
  293. AddressType: discoveryv1.AddressTypeIPv4,
  294. Endpoints: []discoveryv1.Endpoint{
  295. {
  296. Addresses: []string{"1.2.3.4"},
  297. Conditions: discoveryv1.EndpointConditions{Ready: new(true)},
  298. },
  299. },
  300. }
  301. }
  302. func makeDefaultTestcase() *testCase {
  303. return &testCase{
  304. assert: func() {
  305. // this is a noop by default
  306. },
  307. vwc: makeValidatingWebhookConfig(),
  308. secret: makeSecret(),
  309. service: makeService(),
  310. endpointSlice: makeEndpointSlice(),
  311. }
  312. }