/
etcd.go
353 lines (304 loc) · 12.6 KB
/
etcd.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// Copyright 2023 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 secretsrotation
import (
"context"
"fmt"
"slices"
"strings"
"github.com/go-logr/logr"
"golang.org/x/time/rate"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
apiequality "k8s.io/apimachinery/pkg/api/equality"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/discovery"
"sigs.k8s.io/controller-runtime/pkg/client"
v1beta1constants "github.com/gardener/gardener/pkg/apis/core/v1beta1/constants"
"github.com/gardener/gardener/pkg/client/kubernetes"
"github.com/gardener/gardener/pkg/utils"
"github.com/gardener/gardener/pkg/utils/flow"
kubernetesutils "github.com/gardener/gardener/pkg/utils/kubernetes"
secretsmanager "github.com/gardener/gardener/pkg/utils/secrets/manager"
)
// RewriteEncryptedDataAddLabel patches all encrypted data in all namespaces in the target clusters and adds a label
// whose value is the name of the current ETCD encryption key secret. This function is useful for the ETCD encryption
// key secret rotation which requires all encrypted data to be rewritten to ETCD so that they become encrypted with the
// new key. After it's done, it snapshots ETCD so that we can restore backups in case we lose the cluster before the
// next incremental snapshot has been taken.
func RewriteEncryptedDataAddLabel(
ctx context.Context,
log logr.Logger,
runtimeClient client.Client,
clientSet kubernetes.Interface,
secretsManager secretsmanager.Interface,
namespace string,
name string,
resourcesToEncrypt []string,
encryptedResources []string,
defaultGVKs []schema.GroupVersionKind,
) error {
// Check if we have to label the resources to rewrite the data.
meta := &metav1.PartialObjectMetadata{}
meta.SetGroupVersionKind(appsv1.SchemeGroupVersion.WithKind("Deployment"))
if err := runtimeClient.Get(ctx, kubernetesutils.Key(namespace, name), meta); err != nil {
return err
}
if metav1.HasAnnotation(meta.ObjectMeta, AnnotationKeyResourcesLabeled) {
return nil
}
encryptedGVKs, message, err := GetResourcesForRewrite(clientSet.Kubernetes().Discovery(), resourcesToEncrypt, encryptedResources, defaultGVKs)
if err != nil {
return err
}
etcdEncryptionKeySecret, found := secretsManager.Get(v1beta1constants.SecretNameETCDEncryptionKey, secretsmanager.Current)
if !found {
return fmt.Errorf("secret %q not found", v1beta1constants.SecretNameETCDEncryptionKey)
}
if err := rewriteEncryptedData(
ctx,
log,
clientSet.Client(),
utils.MustNewRequirement(labelKeyRotationKeyName, selection.NotEquals, etcdEncryptionKeySecret.Name),
func(objectMeta *metav1.ObjectMeta) {
metav1.SetMetaDataLabel(objectMeta, labelKeyRotationKeyName, etcdEncryptionKeySecret.Name)
},
message+" (Add label)",
encryptedGVKs...,
); err != nil {
return err
}
// If we have hit this point then we have labeled all the resources successfully. Now we can mark this step as "completed"
// (via an annotation) so that we do not start labeling the resources in a future reconciliation in case the flow fails in
// "Removing the label" and labels were only partially removed.
return PatchAPIServerDeploymentMeta(ctx, runtimeClient, namespace, name, func(meta *metav1.PartialObjectMetadata) {
metav1.SetMetaDataAnnotation(&meta.ObjectMeta, AnnotationKeyResourcesLabeled, "true")
})
}
// RewriteEncryptedDataRemoveLabel patches all encrypted data in all namespaces in the target clusters and removes the
// label whose value is the name of the current ETCD encryption key secret. This function is useful for the ETCD
// encryption key secret rotation which requires all encrypted data to be rewritten to ETCD so that they become
// encrypted with the new key.
func RewriteEncryptedDataRemoveLabel(
ctx context.Context,
log logr.Logger,
runtimeClient client.Client,
targetClientSet kubernetes.Interface,
namespace string,
name string,
resourcesToEncrypt []string,
encryptedResources []string,
defaultGVKs []schema.GroupVersionKind,
) error {
encryptedGVKs, message, err := GetResourcesForRewrite(targetClientSet.Kubernetes().Discovery(), resourcesToEncrypt, encryptedResources, defaultGVKs)
if err != nil {
return err
}
if err := rewriteEncryptedData(
ctx,
log,
targetClientSet.Client(),
utils.MustNewRequirement(labelKeyRotationKeyName, selection.Exists),
func(objectMeta *metav1.ObjectMeta) {
delete(objectMeta.Labels, labelKeyRotationKeyName)
},
message+" (Remove label)",
encryptedGVKs...,
); err != nil {
return err
}
return PatchAPIServerDeploymentMeta(ctx, runtimeClient, namespace, name, func(meta *metav1.PartialObjectMetadata) {
delete(meta.Annotations, AnnotationKeyEtcdSnapshotted)
delete(meta.Annotations, AnnotationKeyResourcesLabeled)
})
}
func rewriteEncryptedData(
ctx context.Context,
log logr.Logger,
c client.Client,
requirement labels.Requirement,
mutateObjectMeta func(*metav1.ObjectMeta),
message string,
gvks ...schema.GroupVersionKind,
) error {
var (
limiter = rate.NewLimiter(rate.Limit(rotationQPS), rotationQPS)
taskFns []flow.TaskFn
)
for _, gvk := range gvks {
var fns []flow.TaskFn
objList := &metav1.PartialObjectMetadataList{}
objList.SetGroupVersionKind(gvk)
if err := c.List(ctx, objList, client.MatchingLabelsSelector{Selector: labels.NewSelector().Add(requirement)}); err != nil {
return err
}
log.Info(message, "gvk", gvk, "number", len(objList.Items)) //nolint:logcheck
for _, o := range objList.Items {
obj := o
fns = append(fns, func(ctx context.Context) error {
// client.StrategicMergeFrom is not used here because CRDs don't support strategic-merge-patch.
// See https://github.com/kubernetes-sigs/controller-runtime/blob/a550f29c8781d1f7f9f19ab435ffac337b35a313/pkg/client/patch.go#L164-L173
// This should be okay since we don't modify any lists here.
patch := client.MergeFrom(obj.DeepCopy())
mutateObjectMeta(&obj.ObjectMeta)
// Wait until we are allowed by the limiter to not overload the API server with too many requests.
if err := limiter.Wait(ctx); err != nil {
return err
}
return c.Patch(ctx, &obj, patch)
})
}
// Execute the tasks for the current GVK in parallel.
taskFns = append(taskFns, flow.Parallel(fns...))
}
// Execute the sets of tasks for different GVKs in sequence.
return flow.Sequential(taskFns...)(ctx)
}
// SnapshotETCDAfterRewritingEncryptedData performs a full snapshot on ETCD after the encrypted data (like secrets) have
// been rewritten as part of the ETCD encryption secret rotation. It adds an annotation to the API server deployment
// after it's done so that it does not take another snapshot again after it succeeded once.
func SnapshotETCDAfterRewritingEncryptedData(
ctx context.Context,
runtimeClient client.Client,
snapshotEtcd func(ctx context.Context) error,
namespace string,
name string,
) error {
// Check if we have to snapshot ETCD now that we have rewritten all encrypted data.
meta := &metav1.PartialObjectMetadata{}
meta.SetGroupVersionKind(appsv1.SchemeGroupVersion.WithKind("Deployment"))
if err := runtimeClient.Get(ctx, kubernetesutils.Key(namespace, name), meta); err != nil {
return err
}
if metav1.HasAnnotation(meta.ObjectMeta, AnnotationKeyEtcdSnapshotted) {
return nil
}
if err := snapshotEtcd(ctx); err != nil {
return err
}
// If we have hit this point then we have snapshotted ETCD successfully. Now we can mark this step as "completed"
// (via an annotation) so that we do not trigger a snapshot again in a future reconciliation in case the current one
// fails after this step.
return PatchAPIServerDeploymentMeta(ctx, runtimeClient, namespace, name, func(meta *metav1.PartialObjectMetadata) {
metav1.SetMetaDataAnnotation(&meta.ObjectMeta, AnnotationKeyEtcdSnapshotted, "true")
})
}
// PatchAPIServerDeploymentMeta patches metadata of an API Server deployment.
func PatchAPIServerDeploymentMeta(ctx context.Context, c client.Client, namespace, name string, mutate func(deployment *metav1.PartialObjectMetadata)) error {
meta := &metav1.PartialObjectMetadata{}
meta.SetGroupVersionKind(appsv1.SchemeGroupVersion.WithKind("Deployment"))
if err := c.Get(ctx, kubernetesutils.Key(namespace, name), meta); err != nil {
return err
}
patch := client.MergeFrom(meta.DeepCopy())
mutate(meta)
return c.Patch(ctx, meta, patch)
}
// GetResourcesForRewrite returns a list of schema.GroupVersionKind for all the resources that needs to be rewritten, either due to a encryption
// key rotation or a change in the list of resources requiring encryption.
func GetResourcesForRewrite(
discoveryClient discovery.DiscoveryInterface,
resourcesToEncrypt []string,
encryptedResources []string,
defaultGVKs []schema.GroupVersionKind,
) (
[]schema.GroupVersionKind,
string,
error,
) {
var (
resourcesForRewrite = resourcesToEncrypt
encryptionConfigHasChanged = !apiequality.Semantic.DeepEqual(resourcesToEncrypt, encryptedResources)
encryptedGVKs = sets.New[schema.GroupVersionKind]()
coreResourcesToEncrypt = sets.New[string]()
groupResourcesToEncrypt = map[string]sets.Set[string]{}
message = "Objects requiring to be rewritten after ETCD encryption key rotation"
)
// This means the function is invoked due to ETCD encryption configuration change, so include only the modified resources.
if encryptionConfigHasChanged {
resourcesForRewrite = getModifiedResources(resourcesToEncrypt, encryptedResources)
message = "Objects requiring to be rewritten after modification of encryption config"
}
for _, resource := range resourcesForRewrite {
var (
split = strings.Split(resource, ".")
group = strings.Join(split[1:], ".")
resource = split[0]
)
if len(split) == 1 {
coreResourcesToEncrypt.Insert(resource)
continue
}
if _, ok := groupResourcesToEncrypt[group]; !ok {
groupResourcesToEncrypt[group] = sets.New[string]()
}
groupResourcesToEncrypt[group].Insert(resource)
}
resourceLists, err := discoveryClient.ServerPreferredResources()
if err != nil {
return encryptedGVKs.UnsortedList(), "", fmt.Errorf("error discovering server preferred resources: %w", err)
}
for _, list := range resourceLists {
if len(list.APIResources) == 0 {
continue
}
gv, err := schema.ParseGroupVersion(list.GroupVersion)
if err != nil {
return encryptedGVKs.UnsortedList(), "", fmt.Errorf("error parsing groupVersion: %w", err)
}
for _, apiResource := range list.APIResources {
// If the resource doesn't support get, list and patch, we cannot list and rewrite it
if !slices.Contains(apiResource.Verbs, "get") ||
!slices.Contains(apiResource.Verbs, "list") ||
!slices.Contains(apiResource.Verbs, "patch") {
continue
}
var (
group = gv.Group
version = gv.Version
)
if apiResource.Group != "" {
group = apiResource.Group
}
if apiResource.Version != "" {
version = apiResource.Version
}
if group == corev1.SchemeGroupVersion.Group && coreResourcesToEncrypt.Has(apiResource.Name) {
encryptedGVKs.Insert(schema.GroupVersionKind{Group: group, Version: version, Kind: apiResource.Kind})
continue
}
if resources, ok := groupResourcesToEncrypt[group]; ok && resources.Has(apiResource.Name) {
encryptedGVKs.Insert(schema.GroupVersionKind{Group: group, Version: version, Kind: apiResource.Kind})
}
}
}
// This means the function is invoked due to ETCD encryption key rotation, so include default GVKs as well.
if !encryptionConfigHasChanged {
encryptedGVKs.Insert(defaultGVKs...)
}
return encryptedGVKs.UnsortedList(), message, nil
}
func getModifiedResources(resourcesToEncrypt []string, encryptedResources []string) []string {
var (
oldResources = sets.New(encryptedResources...)
newResources = sets.New(resourcesToEncrypt...)
addedResources = newResources.Difference(oldResources)
removedResources = oldResources.Difference(newResources)
)
return sets.List(addedResources.Union(removedResources))
}