-
Notifications
You must be signed in to change notification settings - Fork 463
/
reconciler.go
252 lines (220 loc) · 10.4 KB
/
reconciler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
// Copyright 2022 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package certificates
import (
"context"
"fmt"
"sync/atomic"
"time"
"github.com/go-logr/logr"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/client-go/util/workqueue"
"k8s.io/utils/clock"
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/webhook"
extensionswebhook "github.com/gardener/gardener/extensions/pkg/webhook"
extensionsshootwebhook "github.com/gardener/gardener/extensions/pkg/webhook/shoot"
"github.com/gardener/gardener/pkg/controllerutils"
kubernetesutils "github.com/gardener/gardener/pkg/utils/kubernetes"
secretsutils "github.com/gardener/gardener/pkg/utils/secrets"
secretsmanager "github.com/gardener/gardener/pkg/utils/secrets/manager"
)
const certificateReconcilerName = "webhook-certificate"
// reconciler is a simple reconciler that manages the webhook CA and server certificate using a secrets manager.
// It runs Generate for both secret configs followed by Cleanup every SyncPeriod and updates the WebhookConfigurations
// accordingly with the new CA bundle.
type reconciler struct {
// Clock is the clock.
Clock clock.Clock
// SyncPeriod is the frequency with which to reload the server cert. Defaults to 5m.
SyncPeriod time.Duration
// SourceWebhookConfigs are the webhook configurations to reconcile in the Source cluster.
SourceWebhookConfigs []client.Object
// ShootWebhookConfig is the webhook configuration to reconcile in all Shoot clusters.
ShootWebhookConfig *admissionregistrationv1.MutatingWebhookConfiguration
// AtomicShootWebhookConfig is an atomic value in which this reconciler will store the updated ShootWebhookConfig.
// It is supposed to be shared with the ControlPlane actuator. I.e. if the CA bundle changes, this reconciler
// updates the CA bundle in this value so that the ControlPlane actuator can configure the correct (the new) CA
// bundle for newly created shoots by loading this value.
AtomicShootWebhookConfig *atomic.Value
// CASecretName is the CA config name.
CASecretName string
// ServerSecretName is the server certificate config name.
ServerSecretName string
// Namespace where the server certificate secret should be located in.
Namespace string
// Identity of the secrets manager used for managing the secret.
Identity string
// Name of the component.
ComponentName string
// ShootWebhookManagedResourceName is the name of the ManagedResource containing the raw shoot webhook config.
ShootWebhookManagedResourceName string
// ShootNamespaceSelector is a label selector for shoot namespaces relevant to the extension.
ShootNamespaceSelector map[string]string
// Mode is the webhook client config mode.
Mode string
// URL is the URL that is used to register the webhooks in Kubernetes.
URL string
serverPort int
client client.Client
}
// AddToManager generates webhook CA and server cert if it doesn't exist on the cluster yet. Then it adds reconciler to
// the given manager in order to periodically regenerate the webhook secrets.
func (r *reconciler) AddToManager(ctx context.Context, mgr manager.Manager) error {
webhookServer := mgr.GetWebhookServer()
defaultServer, ok := webhookServer.(*webhook.DefaultServer)
if !ok {
return fmt.Errorf("expected *webhook.DefaultServer, got %T", webhookServer)
}
r.serverPort = defaultServer.Options.Port
r.client = mgr.GetClient()
present, err := isWebhookServerSecretPresent(ctx, mgr.GetAPIReader(), r.ServerSecretName, r.Namespace, r.Identity)
if err != nil {
return err
}
// if webhook CA and server cert have not been generated yet, we need to generate them for the first time now,
// otherwise the webhook server will not be able to start (which is a non-leader election runnable and is therefore
// started before this controller)
if !present {
// cache is not started yet, we need an uncached client for the initial setup
uncachedClient, err := client.New(mgr.GetConfig(), client.Options{
Cache: &client.CacheOptions{
Reader: mgr.GetAPIReader(),
},
})
if err != nil {
return fmt.Errorf("failed to create new unchached client: %w", err)
}
sm, err := r.newSecretsManager(ctx, mgr.GetLogger(), uncachedClient)
if err != nil {
return fmt.Errorf("failed to create new SecretsManager: %w", err)
}
if _, err = r.generateWebhookCA(ctx, sm); err != nil {
return err
}
if _, err = r.generateWebhookServerCert(ctx, sm); err != nil {
return err
}
}
// add controller, that regenerates the CA and server cert secrets periodically
ctrl, err := controller.New(certificateReconcilerName, mgr, controller.Options{
Reconciler: r,
RecoverPanic: pointer.Bool(true),
// if going into exponential backoff, wait at most the configured sync period
RateLimiter: workqueue.NewWithMaxWaitRateLimiter(workqueue.DefaultControllerRateLimiter(), r.SyncPeriod),
})
if err != nil {
return err
}
return ctrl.Watch(controllerutils.EnqueueOnce, nil)
}
// Reconcile generates new certificates if needed and updates all webhook configurations.
func (r *reconciler) Reconcile(ctx context.Context, _ reconcile.Request) (reconcile.Result, error) {
log := logf.FromContext(ctx)
sm, err := r.newSecretsManager(ctx, log, r.client)
if err != nil {
return reconcile.Result{}, fmt.Errorf("failed to create new SecretsManager: %w", err)
}
caSecret, err := r.generateWebhookCA(ctx, sm)
if err != nil {
return reconcile.Result{}, err
}
caBundleSecret, found := sm.Get(r.CASecretName)
if !found {
return reconcile.Result{}, fmt.Errorf("secret %q not found", r.CASecretName)
}
log = log.WithValues(
"secretNamespace", r.Namespace,
"identity", r.Identity,
"caSecretName", caSecret.Name,
"caBundleSecretName", caBundleSecret.Name,
)
log.Info("Generated webhook CA")
serverSecret, err := r.generateWebhookServerCert(ctx, sm)
if err != nil {
return reconcile.Result{}, err
}
log.Info("Generated webhook server cert", "serverSecretName", serverSecret.Name)
for _, sourceWebhookConfig := range r.SourceWebhookConfigs {
if sourceWebhookConfig == nil {
continue
}
if err := r.reconcileSourceWebhookConfig(ctx, sourceWebhookConfig, caBundleSecret); err != nil {
return reconcile.Result{}, fmt.Errorf("error reconciling source webhook config %s: %w", client.ObjectKeyFromObject(sourceWebhookConfig), err)
}
log.Info("Updated source webhook config with new CA bundle", "webhookConfig", sourceWebhookConfig)
}
if r.ShootWebhookConfig != nil {
// update shoot webhook config object (in memory) with the freshly created CA bundle which is also used by the
// ControlPlane actuator
if err := extensionswebhook.InjectCABundleIntoWebhookConfig(r.ShootWebhookConfig, caBundleSecret.Data[secretsutils.DataKeyCertificateBundle]); err != nil {
return reconcile.Result{}, err
}
r.AtomicShootWebhookConfig.Store(r.ShootWebhookConfig.DeepCopy())
// reconcile all shoot webhook configs with the freshly created CA bundle
if err := extensionsshootwebhook.ReconcileWebhooksForAllNamespaces(ctx, r.client, r.Namespace, r.ComponentName, r.ShootWebhookManagedResourceName, r.ShootNamespaceSelector, r.serverPort, r.ShootWebhookConfig); err != nil {
return reconcile.Result{}, fmt.Errorf("error reconciling all shoot webhook configs: %w", err)
}
log.Info("Updated all shoot webhook configs with new CA bundle", "webhookConfig", r.ShootWebhookConfig)
}
if err := sm.Cleanup(ctx); err != nil {
return reconcile.Result{}, err
}
return reconcile.Result{RequeueAfter: r.SyncPeriod}, nil
}
func (r *reconciler) reconcileSourceWebhookConfig(ctx context.Context, sourceWebhookConfig client.Object, caBundleSecret *corev1.Secret) error {
// copy object so that we don't lose its name on API/client errors
config := sourceWebhookConfig.DeepCopyObject().(client.Object)
if err := r.client.Get(ctx, client.ObjectKeyFromObject(config), config); err != nil {
return err
}
patch := client.MergeFromWithOptions(config.DeepCopyObject().(client.Object), client.MergeFromWithOptimisticLock{})
if err := extensionswebhook.InjectCABundleIntoWebhookConfig(config, caBundleSecret.Data[secretsutils.DataKeyCertificateBundle]); err != nil {
return err
}
return r.client.Patch(ctx, config, patch)
}
func isWebhookServerSecretPresent(ctx context.Context, c client.Reader, secretName, namespace, identity string) (bool, error) {
return kubernetesutils.ResourcesExist(ctx, c, corev1.SchemeGroupVersion.WithKind("SecretList"), client.InNamespace(namespace), client.MatchingLabels{
secretsmanager.LabelKeyName: secretName,
secretsmanager.LabelKeyManagedBy: secretsmanager.LabelValueSecretsManager,
secretsmanager.LabelKeyManagerIdentity: identity,
})
}
func (r *reconciler) newSecretsManager(ctx context.Context, log logr.Logger, c client.Client) (secretsmanager.Interface, error) {
return secretsmanager.New(
ctx,
log.WithName("secretsmanager"),
r.Clock,
c,
r.Namespace,
r.Identity,
secretsmanager.Config{CASecretAutoRotation: true},
)
}
func (r *reconciler) generateWebhookCA(ctx context.Context, sm secretsmanager.Interface) (*corev1.Secret, error) {
return sm.Generate(ctx, getWebhookCAConfig(r.CASecretName),
secretsmanager.Rotate(secretsmanager.KeepOld), secretsmanager.IgnoreOldSecretsAfter(24*time.Hour))
}
func (r *reconciler) generateWebhookServerCert(ctx context.Context, sm secretsmanager.Interface) (*corev1.Secret, error) {
// use current CA for signing server cert to prevent mismatches when dropping the old CA from the webhook config
return sm.Generate(ctx, getWebhookServerCertConfig(r.ServerSecretName, r.Namespace, r.ComponentName, r.Mode, r.URL),
secretsmanager.SignedByCA(r.CASecretName, secretsmanager.UseCurrentCA))
}