webhookconfig.go 6.0 KB

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