webhookconfig.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. "errors"
  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. "github.com/external-secrets/external-secrets/pkg/constants"
  32. )
  33. type Reconciler struct {
  34. client.Client
  35. Log logr.Logger
  36. Scheme *runtime.Scheme
  37. recorder record.EventRecorder
  38. RequeueDuration time.Duration
  39. SvcName string
  40. SvcNamespace string
  41. SecretName string
  42. SecretNamespace string
  43. // store state for the readiness probe.
  44. // we're ready when we're not the leader or
  45. // if we've reconciled the webhook config when we're the leader.
  46. leaderChan <-chan struct{}
  47. leaderElected bool
  48. webhookReadyMu *sync.Mutex
  49. webhookReady bool
  50. }
  51. type Opts struct {
  52. SvcName string
  53. SvcNamespace string
  54. SecretName string
  55. SecretNamespace string
  56. RequeueInterval time.Duration
  57. }
  58. func New(k8sClient client.Client, scheme *runtime.Scheme, leaderChan <-chan struct{}, log logr.Logger, opts Opts) *Reconciler {
  59. return &Reconciler{
  60. Client: k8sClient,
  61. Scheme: scheme,
  62. Log: log,
  63. RequeueDuration: opts.RequeueInterval,
  64. SvcName: opts.SvcName,
  65. SvcNamespace: opts.SvcNamespace,
  66. SecretName: opts.SecretName,
  67. SecretNamespace: opts.SecretNamespace,
  68. leaderChan: leaderChan,
  69. leaderElected: false,
  70. webhookReadyMu: &sync.Mutex{},
  71. webhookReady: false,
  72. }
  73. }
  74. const (
  75. ReasonUpdateFailed = "UpdateFailed"
  76. errWebhookNotReady = "webhook not ready"
  77. errSubsetsNotReady = "subsets not ready"
  78. errAddressesNotReady = "addresses not ready"
  79. errCACertNotReady = "ca cert not yet ready"
  80. caCertName = "ca.crt"
  81. )
  82. func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
  83. log := r.Log.WithValues("Webhookconfig", req.NamespacedName)
  84. var cfg admissionregistration.ValidatingWebhookConfiguration
  85. err := r.Get(ctx, req.NamespacedName, &cfg)
  86. if apierrors.IsNotFound(err) {
  87. return ctrl.Result{}, nil
  88. } else if err != nil {
  89. log.Error(err, "unable to get Webhookconfig")
  90. return ctrl.Result{}, err
  91. }
  92. if cfg.Labels[constants.WellKnownLabelKey] != constants.WellKnownLabelValueWebhook {
  93. log.Info("ignoring webhook due to missing labels", constants.WellKnownLabelKey, constants.WellKnownLabelValueWebhook)
  94. return ctrl.Result{}, nil
  95. }
  96. log.Info("updating webhook config")
  97. err = r.updateConfig(ctx, &cfg)
  98. if err != nil {
  99. log.Error(err, "could not update webhook config")
  100. r.recorder.Eventf(&cfg, v1.EventTypeWarning, ReasonUpdateFailed, err.Error())
  101. return ctrl.Result{
  102. RequeueAfter: time.Minute,
  103. }, err
  104. }
  105. log.Info("updated webhook config")
  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. var eps v1.Endpoints
  139. err := r.Get(context.TODO(), types.NamespacedName{
  140. Name: r.SvcName,
  141. Namespace: r.SvcNamespace,
  142. }, &eps)
  143. if err != nil {
  144. return err
  145. }
  146. if len(eps.Subsets) == 0 {
  147. return errors.New(errSubsetsNotReady)
  148. }
  149. if len(eps.Subsets[0].Addresses) == 0 {
  150. return errors.New(errAddressesNotReady)
  151. }
  152. return nil
  153. }
  154. // reads the ca cert and updates the webhook config.
  155. func (r *Reconciler) updateConfig(ctx context.Context, cfg *admissionregistration.ValidatingWebhookConfiguration) error {
  156. secret := v1.Secret{}
  157. secretName := types.NamespacedName{
  158. Name: r.SecretName,
  159. Namespace: r.SecretNamespace,
  160. }
  161. err := r.Get(context.Background(), secretName, &secret)
  162. if err != nil {
  163. return err
  164. }
  165. crt, ok := secret.Data[caCertName]
  166. if !ok {
  167. return errors.New(errCACertNotReady)
  168. }
  169. if err := r.inject(cfg, r.SvcName, r.SvcNamespace, crt); err != nil {
  170. return err
  171. }
  172. return r.Update(ctx, cfg)
  173. }
  174. func (r *Reconciler) inject(cfg *admissionregistration.ValidatingWebhookConfiguration, svcName, svcNamespace string, certData []byte) error {
  175. r.Log.Info("injecting ca certificate and service names", "cacrt", base64.StdEncoding.EncodeToString(certData), "name", cfg.Name)
  176. for idx, w := range cfg.Webhooks {
  177. if !strings.HasSuffix(w.Name, "external-secrets.io") {
  178. r.Log.Info("skipping webhook", "name", cfg.Name, "webhook-name", w.Name)
  179. continue
  180. }
  181. // we just patch the relevant fields
  182. cfg.Webhooks[idx].ClientConfig.Service.Name = svcName
  183. cfg.Webhooks[idx].ClientConfig.Service.Namespace = svcNamespace
  184. cfg.Webhooks[idx].ClientConfig.CABundle = certData
  185. }
  186. return nil
  187. }