webhookconfig_test.go 8.9 KB

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