webhookconfig.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. "context"
  15. "encoding/base64"
  16. "fmt"
  17. "net/http"
  18. "strings"
  19. "sync"
  20. "time"
  21. "github.com/go-logr/logr"
  22. admissionregistration "k8s.io/api/admissionregistration/v1"
  23. v1 "k8s.io/api/core/v1"
  24. apierrors "k8s.io/apimachinery/pkg/api/errors"
  25. "k8s.io/apimachinery/pkg/runtime"
  26. "k8s.io/apimachinery/pkg/types"
  27. "k8s.io/client-go/tools/record"
  28. ctrl "sigs.k8s.io/controller-runtime"
  29. "sigs.k8s.io/controller-runtime/pkg/client"
  30. "sigs.k8s.io/controller-runtime/pkg/controller"
  31. )
  32. type Reconciler struct {
  33. client.Client
  34. Log logr.Logger
  35. Scheme *runtime.Scheme
  36. recorder record.EventRecorder
  37. RequeueDuration time.Duration
  38. SvcName string
  39. SvcNamespace string
  40. SecretName string
  41. SecretNamespace string
  42. // store state for the readiness probe.
  43. // we're ready when we're not the leader or
  44. // if we've reconciled the webhook config when we're the leader.
  45. leaderChan <-chan struct{}
  46. leaderElected bool
  47. webhookReadyMu *sync.Mutex
  48. webhookReady bool
  49. }
  50. func New(k8sClient client.Client, scheme *runtime.Scheme, leaderChan <-chan struct{},
  51. log logr.Logger, svcName, svcNamespace, secretName, secretNamespace string,
  52. requeueInterval time.Duration) *Reconciler {
  53. return &Reconciler{
  54. Client: k8sClient,
  55. Scheme: scheme,
  56. Log: log,
  57. RequeueDuration: requeueInterval,
  58. SvcName: svcName,
  59. SvcNamespace: svcNamespace,
  60. SecretName: secretName,
  61. SecretNamespace: secretNamespace,
  62. leaderChan: leaderChan,
  63. leaderElected: false,
  64. webhookReadyMu: &sync.Mutex{},
  65. webhookReady: false,
  66. }
  67. }
  68. const (
  69. wellKnownLabelKey = "external-secrets.io/component"
  70. wellKnownLabelValue = "webhook"
  71. ReasonUpdateFailed = "UpdateFailed"
  72. errWebhookNotReady = "webhook not ready"
  73. errSubsetsNotReady = "subsets not ready"
  74. errAddressesNotReady = "addresses not ready"
  75. errCACertNotReady = "ca cert not yet ready"
  76. caCertName = "ca.crt"
  77. )
  78. func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
  79. log := r.Log.WithValues("Webhookconfig", req.NamespacedName)
  80. var cfg admissionregistration.ValidatingWebhookConfiguration
  81. err := r.Get(ctx, req.NamespacedName, &cfg)
  82. if apierrors.IsNotFound(err) {
  83. return ctrl.Result{}, nil
  84. } else if err != nil {
  85. log.Error(err, "unable to get Webhookconfig")
  86. return ctrl.Result{}, err
  87. }
  88. if cfg.Labels[wellKnownLabelKey] != wellKnownLabelValue {
  89. log.Info("ignoring webhook due to missing labels", wellKnownLabelKey, wellKnownLabelValue)
  90. return ctrl.Result{}, nil
  91. }
  92. log.Info("updating webhook config")
  93. err = r.updateConfig(ctx, &cfg)
  94. if err != nil {
  95. log.Error(err, "could not update webhook config")
  96. r.recorder.Eventf(&cfg, v1.EventTypeWarning, ReasonUpdateFailed, err.Error())
  97. return ctrl.Result{
  98. RequeueAfter: time.Minute,
  99. }, err
  100. }
  101. log.Info("updated webhook config")
  102. // right now we only have one single
  103. // webhook config we care about
  104. r.webhookReadyMu.Lock()
  105. defer r.webhookReadyMu.Unlock()
  106. r.webhookReady = true
  107. return ctrl.Result{
  108. RequeueAfter: r.RequeueDuration,
  109. }, nil
  110. }
  111. func (r *Reconciler) SetupWithManager(mgr ctrl.Manager, opts controller.Options) error {
  112. r.recorder = mgr.GetEventRecorderFor("validating-webhook-configuration")
  113. return ctrl.NewControllerManagedBy(mgr).
  114. WithOptions(opts).
  115. For(&admissionregistration.ValidatingWebhookConfiguration{}).
  116. Complete(r)
  117. }
  118. func (r *Reconciler) ReadyCheck(_ *http.Request) error {
  119. // skip readiness check if we're not leader
  120. // as we depend on caches and being able to reconcile Webhooks
  121. if !r.leaderElected {
  122. select {
  123. case <-r.leaderChan:
  124. r.leaderElected = true
  125. default:
  126. return nil
  127. }
  128. }
  129. r.webhookReadyMu.Lock()
  130. defer r.webhookReadyMu.Unlock()
  131. if !r.webhookReady {
  132. return fmt.Errorf(errWebhookNotReady)
  133. }
  134. var eps v1.Endpoints
  135. err := r.Get(context.TODO(), types.NamespacedName{
  136. Name: r.SvcName,
  137. Namespace: r.SvcNamespace,
  138. }, &eps)
  139. if err != nil {
  140. return err
  141. }
  142. if len(eps.Subsets) == 0 {
  143. return fmt.Errorf(errSubsetsNotReady)
  144. }
  145. if len(eps.Subsets[0].Addresses) == 0 {
  146. return fmt.Errorf(errAddressesNotReady)
  147. }
  148. return nil
  149. }
  150. // reads the ca cert and updates the webhook config.
  151. func (r *Reconciler) updateConfig(ctx context.Context, cfg *admissionregistration.ValidatingWebhookConfiguration) error {
  152. secret := v1.Secret{}
  153. secretName := types.NamespacedName{
  154. Name: r.SecretName,
  155. Namespace: r.SecretNamespace,
  156. }
  157. err := r.Get(context.Background(), secretName, &secret)
  158. if err != nil {
  159. return err
  160. }
  161. crt, ok := secret.Data[caCertName]
  162. if !ok {
  163. return fmt.Errorf(errCACertNotReady)
  164. }
  165. if err := r.inject(cfg, r.SvcName, r.SvcNamespace, crt); err != nil {
  166. return err
  167. }
  168. return r.Update(ctx, cfg)
  169. }
  170. func (r *Reconciler) inject(cfg *admissionregistration.ValidatingWebhookConfiguration, svcName, svcNamespace string, certData []byte) error {
  171. r.Log.Info("injecting ca certificate and service names", "cacrt", base64.StdEncoding.EncodeToString(certData), "name", cfg.Name)
  172. for idx, w := range cfg.Webhooks {
  173. if !strings.HasSuffix(w.Name, "external-secrets.io") {
  174. r.Log.Info("skipping webhook", "name", cfg.Name, "webhook-name", w.Name)
  175. continue
  176. }
  177. // we just patch the relevant fields
  178. cfg.Webhooks[idx].ClientConfig.Service.Name = svcName
  179. cfg.Webhooks[idx].ClientConfig.Service.Namespace = svcNamespace
  180. cfg.Webhooks[idx].ClientConfig.CABundle = certData
  181. }
  182. return nil
  183. }