-
Notifications
You must be signed in to change notification settings - Fork 450
/
admission.go
492 lines (415 loc) · 20.6 KB
/
admission.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// Copyright (c) 2021 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 seedrestriction
import (
"context"
"fmt"
"net/http"
"strings"
"github.com/gardener/gardener/pkg/admissioncontroller/seedidentity"
acadmission "github.com/gardener/gardener/pkg/admissioncontroller/webhooks/admission"
gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
v1beta1constants "github.com/gardener/gardener/pkg/apis/core/v1beta1/constants"
gardenoperationsv1alpha1 "github.com/gardener/gardener/pkg/apis/operations/v1alpha1"
seedmanagementv1alpha1 "github.com/gardener/gardener/pkg/apis/seedmanagement/v1alpha1"
seedmanagementv1alpha1helper "github.com/gardener/gardener/pkg/apis/seedmanagement/v1alpha1/helper"
bootstraputil "github.com/gardener/gardener/pkg/gardenlet/bootstrap/util"
"github.com/gardener/gardener/pkg/utils"
gutil "github.com/gardener/gardener/pkg/utils/gardener"
kutil "github.com/gardener/gardener/pkg/utils/kubernetes"
"github.com/go-logr/logr"
admissionv1 "k8s.io/api/admission/v1"
certificatesv1beta1 "k8s.io/api/certificates/v1beta1"
coordinationv1 "k8s.io/api/coordination/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
bootstraptokenapi "k8s.io/cluster-bootstrap/token/api"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)
const (
// HandlerName is the name of this admission webhook handler.
HandlerName = "seedrestriction"
// WebhookPath is the HTTP handler path for this admission webhook handler.
WebhookPath = "/webhooks/admission/seedrestriction"
)
var (
// Only take v1beta1 for the core.gardener.cloud API group because the Authorize function only checks the resource
// group and the resource (but it ignores the version).
backupBucketResource = gardencorev1beta1.Resource("backupbuckets")
backupEntryResource = gardencorev1beta1.Resource("backupentries")
bastionResource = gardenoperationsv1alpha1.Resource("bastions")
certificateSigningRequestResource = certificatesv1beta1.Resource("certificatesigningrequests")
clusterRoleBindingResource = rbacv1.Resource("clusterrolebindings")
leaseResource = coordinationv1.Resource("leases")
secretResource = corev1.Resource("secrets")
seedResource = gardencorev1beta1.Resource("seeds")
serviceAccountResource = corev1.Resource("serviceaccounts")
shootStateResource = gardencorev1beta1.Resource("shootstates")
)
// New creates a new webhook handler restricting requests by gardenlets. It allows all requests.
func New(ctx context.Context, logger logr.Logger, cache cache.Cache) (*handler, error) {
// Initialize caches here to ensure the readyz informer check will only succeed once informers required for this
// handler have synced so that http requests can be served quicker with pre-syncronized caches.
if _, err := cache.GetInformer(ctx, &gardencorev1beta1.BackupBucket{}); err != nil {
return nil, err
}
if _, err := cache.GetInformer(ctx, &seedmanagementv1alpha1.ManagedSeed{}); err != nil {
return nil, err
}
if _, err := cache.GetInformer(ctx, &gardencorev1beta1.Seed{}); err != nil {
return nil, err
}
if _, err := cache.GetInformer(ctx, &gardencorev1beta1.Shoot{}); err != nil {
return nil, err
}
return &handler{
logger: logger,
cacheReader: cache,
}, nil
}
type handler struct {
logger logr.Logger
cacheReader client.Reader
decoder *admission.Decoder
}
var _ admission.Handler = &handler{}
func (h *handler) InjectDecoder(d *admission.Decoder) error {
h.decoder = d
return nil
}
func (h *handler) Handle(ctx context.Context, request admission.Request) admission.Response {
seedName, isSeed := seedidentity.FromAuthenticationV1UserInfo(request.UserInfo)
if !isSeed {
return acadmission.Allowed("")
}
requestResource := schema.GroupResource{Group: request.Resource.Group, Resource: request.Resource.Resource}
switch requestResource {
case backupBucketResource:
return h.admitBackupBucket(ctx, seedName, request)
case backupEntryResource:
return h.admitBackupEntry(ctx, seedName, request)
case bastionResource:
return h.admitBastion(seedName, request)
case certificateSigningRequestResource:
return h.admitCertificateSigningRequest(seedName, request)
case clusterRoleBindingResource:
return h.admitClusterRoleBinding(ctx, seedName, request)
case leaseResource:
return h.admitLease(seedName, request)
case secretResource:
return h.admitSecret(ctx, seedName, request)
case seedResource:
return h.admitSeed(ctx, seedName, request)
case serviceAccountResource:
return h.admitServiceAccount(ctx, seedName, request)
case shootStateResource:
return h.admitShootState(ctx, seedName, request)
}
return acadmission.Allowed("")
}
func (h *handler) admitBackupBucket(ctx context.Context, seedName string, request admission.Request) admission.Response {
switch request.Operation {
case admissionv1.Create:
// If a gardenlet tries to create a BackupBucket then the request may only be allowed if the used `.spec.seedName`
// is equal to the gardenlet's seed.
backupBucket := &gardencorev1beta1.BackupBucket{}
if err := h.decoder.Decode(request, backupBucket); err != nil {
return admission.Errored(http.StatusBadRequest, err)
}
return h.admit(seedName, backupBucket.Spec.SeedName)
case admissionv1.Delete:
// Allow request if seed name is not known (ambiguous case).
if seedName == "" {
return admission.Allowed("")
}
// If a gardenlet tries to delete a BackupBucket then it may only be allowed if the name is equal to the UID of
// the gardenlet's seed.
seed := &gardencorev1beta1.Seed{}
if err := h.cacheReader.Get(ctx, kutil.Key(seedName), seed); err != nil {
return admission.Errored(http.StatusInternalServerError, err)
}
if string(seed.UID) != request.Name {
return admission.Errored(http.StatusForbidden, fmt.Errorf("cannot delete unrelated BackupBucket"))
}
return admission.Allowed("")
}
return admission.Errored(http.StatusBadRequest, fmt.Errorf("unexpected operation: %q", request.Operation))
}
func (h *handler) admitBackupEntry(ctx context.Context, seedName string, request admission.Request) admission.Response {
if request.Operation != admissionv1.Create {
return admission.Errored(http.StatusBadRequest, fmt.Errorf("unexpected operation: %q", request.Operation))
}
backupEntry := &gardencorev1beta1.BackupEntry{}
if err := h.decoder.Decode(request, backupEntry); err != nil {
return admission.Errored(http.StatusBadRequest, err)
}
if resp := h.admit(seedName, backupEntry.Spec.SeedName); !resp.Allowed {
return resp
}
backupBucket := &gardencorev1beta1.BackupBucket{}
if err := h.cacheReader.Get(ctx, kutil.Key(backupEntry.Spec.BucketName), backupBucket); err != nil {
return admission.Errored(http.StatusInternalServerError, err)
}
return h.admit(seedName, backupBucket.Spec.SeedName)
}
func (h *handler) admitBastion(seedName string, request admission.Request) admission.Response {
if request.Operation != admissionv1.Create {
return admission.Errored(http.StatusBadRequest, fmt.Errorf("unexpected operation: %q", request.Operation))
}
bastion := &gardenoperationsv1alpha1.Bastion{}
if err := h.decoder.Decode(request, bastion); err != nil {
return admission.Errored(http.StatusBadRequest, err)
}
return h.admit(seedName, bastion.Spec.SeedName)
}
func (h *handler) admitCertificateSigningRequest(seedName string, request admission.Request) admission.Response {
if request.Operation != admissionv1.Create {
return admission.Errored(http.StatusBadRequest, fmt.Errorf("unexpected operation: %q", request.Operation))
}
csr := &certificatesv1beta1.CertificateSigningRequest{}
if err := h.decoder.Decode(request, csr); err != nil {
return admission.Errored(http.StatusBadRequest, err)
}
x509cr, err := utils.DecodeCertificateRequest(csr.Spec.Request)
if err != nil {
return admission.Errored(http.StatusBadRequest, err)
}
if !gutil.IsSeedClientCert(x509cr, csr.Spec.Usages) {
return admission.Errored(http.StatusForbidden, fmt.Errorf("can only create CSRs for seed clusters"))
}
seedNameInCSR, _ := seedidentity.FromCertificateSigningRequest(x509cr)
return h.admit(seedName, &seedNameInCSR)
}
func (h *handler) admitClusterRoleBinding(ctx context.Context, seedName string, request admission.Request) admission.Response {
if request.Operation != admissionv1.Create {
return admission.Errored(http.StatusBadRequest, fmt.Errorf("unexpected operation: %q", request.Operation))
}
// Allow gardenlet to create cluster role bindings referencing service accounts which can be used to bootstrap other
// gardenlets deployed as part of the ManagedSeed reconciliation.
if strings.HasPrefix(request.Name, bootstraputil.ClusterRoleBindingNamePrefix) {
clusterRoleBinding := &rbacv1.ClusterRoleBinding{}
if err := h.decoder.Decode(request, clusterRoleBinding); err != nil {
return admission.Errored(http.StatusBadRequest, err)
}
if clusterRoleBinding.RoleRef.APIGroup != rbacv1.GroupName ||
clusterRoleBinding.RoleRef.Kind != "ClusterRole" ||
clusterRoleBinding.RoleRef.Name != bootstraputil.GardenerSeedBootstrapper {
return admission.Errored(http.StatusForbidden, fmt.Errorf("can only bindings referring to the bootstrapper role"))
}
managedSeedNamespace, managedSeedName := bootstraputil.MetadataFromClusterRoleBindingName(request.Name)
return h.allowIfManagedSeedIsNotYetBootstrapped(ctx, seedName, managedSeedNamespace, managedSeedName)
}
return admission.Errored(http.StatusForbidden, fmt.Errorf("object does not belong to seed %q", seedName))
}
func (h *handler) admitLease(seedName string, request admission.Request) admission.Response {
if request.Operation != admissionv1.Create {
return admission.Errored(http.StatusBadRequest, fmt.Errorf("unexpected operation: %q", request.Operation))
}
// This allows the gardenlet to create a Lease for leader election (if the garden cluster is a seed as well).
if request.Name == "gardenlet-leader-election" {
return admission.Allowed("")
}
// Each gardenlet creates a Lease with the name of its own seed in the `gardener-system-seed-lease` namespace.
if request.Namespace == gardencorev1beta1.GardenerSeedLeaseNamespace {
return h.admit(seedName, &request.Name)
}
return admission.Errored(http.StatusForbidden, fmt.Errorf("object does not belong to seed %q", seedName))
}
func (h *handler) admitSecret(ctx context.Context, seedName string, request admission.Request) admission.Response {
if request.Operation != admissionv1.Create {
return admission.Errored(http.StatusBadRequest, fmt.Errorf("unexpected operation: %q", request.Operation))
}
// Check if the secret is related to a BackupBucket assigned to the seed the gardenlet is responsible for.
if strings.HasPrefix(request.Name, v1beta1constants.SecretPrefixGeneratedBackupBucket) {
backupBucket := &gardencorev1beta1.BackupBucket{}
if err := h.cacheReader.Get(ctx, kutil.Key(strings.TrimPrefix(request.Name, v1beta1constants.SecretPrefixGeneratedBackupBucket)), backupBucket); err != nil {
if apierrors.IsNotFound(err) {
return admission.Errored(http.StatusForbidden, err)
}
return admission.Errored(http.StatusInternalServerError, err)
}
return h.admit(seedName, backupBucket.Spec.SeedName)
}
// Check if the secret is related to a Shoot assigned to the seed the gardenlet is responsible for.
if shootName, ok := gutil.IsShootProjectSecret(request.Name); ok {
shoot := &gardencorev1beta1.Shoot{}
if err := h.cacheReader.Get(ctx, kutil.Key(request.Namespace, shootName), shoot); err != nil {
if apierrors.IsNotFound(err) {
return admission.Errored(http.StatusForbidden, err)
}
return admission.Errored(http.StatusInternalServerError, err)
}
return h.admit(seedName, shoot.Spec.SeedName)
}
// Check if the secret is a bootstrap token for a ManagedSeed.
if strings.HasPrefix(request.Name, bootstraptokenapi.BootstrapTokenSecretPrefix) && request.Namespace == metav1.NamespaceSystem {
secret := &corev1.Secret{}
if err := h.decoder.Decode(request, secret); err != nil {
return admission.Errored(http.StatusBadRequest, err)
}
if secret.Type != corev1.SecretTypeBootstrapToken {
return admission.Errored(http.StatusBadRequest, fmt.Errorf("unexpected secret type: %q", secret.Type))
}
if string(secret.Data[bootstraptokenapi.BootstrapTokenUsageAuthentication]) != "true" {
return admission.Errored(http.StatusBadRequest, fmt.Errorf("%q must be set to 'true'", bootstraptokenapi.BootstrapTokenUsageAuthentication))
}
if string(secret.Data[bootstraptokenapi.BootstrapTokenUsageSigningKey]) != "true" {
return admission.Errored(http.StatusBadRequest, fmt.Errorf("%q must be set to 'true'", bootstraptokenapi.BootstrapTokenUsageSigningKey))
}
if _, ok := secret.Data[bootstraptokenapi.BootstrapTokenExtraGroupsKey]; ok {
return admission.Errored(http.StatusBadRequest, fmt.Errorf("%q must not be set", bootstraptokenapi.BootstrapTokenExtraGroupsKey))
}
managedSeedNamespace, managedSeedName := bootstraputil.MetadataFromDescription(
string(secret.Data[bootstraptokenapi.BootstrapTokenDescriptionKey]),
bootstraputil.KindManagedSeed,
)
return h.allowIfManagedSeedIsNotYetBootstrapped(ctx, seedName, managedSeedNamespace, managedSeedName)
}
// Check if the secret is related to a ManagedSeed assigned to the seed the gardenlet is responsible for.
managedSeedList := &seedmanagementv1alpha1.ManagedSeedList{}
if err := h.cacheReader.List(ctx, managedSeedList); err != nil {
return admission.Errored(http.StatusInternalServerError, err)
}
for _, managedSeed := range managedSeedList.Items {
shoot := &gardencorev1beta1.Shoot{}
if err := h.cacheReader.Get(ctx, kutil.Key(managedSeed.Namespace, managedSeed.Spec.Shoot.Name), shoot); err != nil {
return admission.Errored(http.StatusInternalServerError, err)
}
if !h.admit(seedName, shoot.Spec.SeedName).Allowed {
continue
}
seedTemplate, _, err := seedmanagementv1alpha1helper.ExtractSeedTemplateAndGardenletConfig(&managedSeed)
if err != nil {
return admission.Errored(http.StatusInternalServerError, err)
}
if seedTemplate.Spec.SecretRef != nil &&
seedTemplate.Spec.SecretRef.Namespace == request.Namespace &&
seedTemplate.Spec.SecretRef.Name == request.Name {
return admission.Allowed("")
}
if seedTemplate.Spec.Backup != nil &&
seedTemplate.Spec.Backup.SecretRef.Namespace == request.Namespace &&
seedTemplate.Spec.Backup.SecretRef.Name == request.Name {
return admission.Allowed("")
}
}
return admission.Errored(http.StatusForbidden, fmt.Errorf("object does not belong to seed %q", seedName))
}
func (h *handler) admitSeed(ctx context.Context, seedName string, request admission.Request) admission.Response {
if request.Operation == admissionv1.Connect {
return admission.Errored(http.StatusBadRequest, fmt.Errorf("unexpected operation: %q", request.Operation))
}
response := h.admit(seedName, &request.Name)
if response.Allowed {
return response
}
// If the request is not allowed then we check whether the Seed object in question is the result of a ManagedSeed
// reconciliation. In this case, the another gardenlet (the "parent gardenlet") which is usually responsible for a
// different seed is doing the request.
managedSeed := &seedmanagementv1alpha1.ManagedSeed{}
if err := h.cacheReader.Get(ctx, kutil.Key(v1beta1constants.GardenNamespace, request.Name), managedSeed); err != nil {
if apierrors.IsNotFound(err) {
return response
}
return admission.Errored(http.StatusInternalServerError, err)
}
switch request.Operation {
case admissionv1.Create, admissionv1.Update:
// If a gardenlet tries to create/update a Seed belonging to a ManagedSeed then the request may only be
// considered further if the `.spec.seedTemplate` is set.
if managedSeed.Spec.SeedTemplate == nil {
return response
}
case admissionv1.Delete:
// If a gardenlet tries to delete a Seed belonging to a ManagedSeed then the request may only be considered
// further if the `.spec.deletionTimestamp` is set (gardenlets themselves are not allowed to delete ManagedSeeds,
// so it's safe to only continue if somebody else has set this deletion timestamp).
if managedSeed.DeletionTimestamp == nil {
return admission.Errored(http.StatusForbidden, fmt.Errorf("object can only be deleted if corresponding ManagedSeed has a deletion timestamp"))
}
}
// If for whatever reason the `.spec.shoot` is nil then we exit early.
if managedSeed.Spec.Shoot == nil {
return response
}
// Check if the `.spec.seedName` of the Shoot referenced in the `.spec.shoot.name` field of the ManagedSeed matches
// the seed name of the requesting gardenlet.
shoot := &gardencorev1beta1.Shoot{}
if err := h.cacheReader.Get(ctx, kutil.Key(managedSeed.Namespace, managedSeed.Spec.Shoot.Name), shoot); err != nil {
return admission.Errored(http.StatusInternalServerError, err)
}
return h.admit(seedName, shoot.Spec.SeedName)
}
func (h *handler) admitServiceAccount(ctx context.Context, seedName string, request admission.Request) admission.Response {
if request.Operation != admissionv1.Create {
return admission.Errored(http.StatusBadRequest, fmt.Errorf("unexpected operation: %q", request.Operation))
}
// Allow gardenlet to create service accounts which can be used to bootstrap other gardenlets deployed as part of
// the ManagedSeed reconciliation.
if strings.HasPrefix(request.Name, bootstraputil.ServiceAccountNamePrefix) {
return h.allowIfManagedSeedIsNotYetBootstrapped(ctx, seedName, request.Namespace, strings.TrimPrefix(request.Name, bootstraputil.ServiceAccountNamePrefix))
}
return admission.Errored(http.StatusForbidden, fmt.Errorf("object does not belong to seed %q", seedName))
}
func (h *handler) admitShootState(ctx context.Context, seedName string, request admission.Request) admission.Response {
if request.Operation != admissionv1.Create {
return admission.Errored(http.StatusBadRequest, fmt.Errorf("unexpected operation: %q", request.Operation))
}
shoot := &gardencorev1beta1.Shoot{}
if err := h.cacheReader.Get(ctx, kutil.Key(request.Namespace, request.Name), shoot); err != nil {
return admission.Errored(http.StatusInternalServerError, err)
}
return h.admit(seedName, shoot.Spec.SeedName, shoot.Status.SeedName)
}
func (h *handler) admit(seedName string, seedNamesForObject ...*string) admission.Response {
// Allow request if seed name is not known (ambiguous case).
if seedName == "" {
return admission.Allowed("")
}
// Allow request if one of the seed names for the object matches the seed name of the requesting user.
for _, seedNameForObject := range seedNamesForObject {
if seedNameForObject != nil && *seedNameForObject == seedName {
return admission.Allowed("")
}
}
return admission.Errored(http.StatusForbidden, fmt.Errorf("object does not belong to seed %q", seedName))
}
func (h *handler) allowIfManagedSeedIsNotYetBootstrapped(ctx context.Context, seedName, managedSeedNamespace, managedSeedName string) admission.Response {
managedSeed := &seedmanagementv1alpha1.ManagedSeed{}
if err := h.cacheReader.Get(ctx, kutil.Key(managedSeedNamespace, managedSeedName), managedSeed); err != nil {
if apierrors.IsNotFound(err) {
return admission.Errored(http.StatusForbidden, err)
}
return admission.Errored(http.StatusInternalServerError, err)
}
shoot := &gardencorev1beta1.Shoot{}
if err := h.cacheReader.Get(ctx, kutil.Key(managedSeed.Namespace, managedSeed.Spec.Shoot.Name), shoot); err != nil {
return admission.Errored(http.StatusInternalServerError, err)
}
if response := h.admit(seedName, shoot.Spec.SeedName); !response.Allowed {
return response
}
if err := h.cacheReader.Get(ctx, kutil.Key(managedSeedName), &gardencorev1beta1.Seed{}); err != nil {
if !apierrors.IsNotFound(err) {
return admission.Errored(http.StatusInternalServerError, err)
}
return admission.Allowed("")
}
return admission.Errored(http.StatusBadRequest, fmt.Errorf("managed seed %s/%s is already bootstrapped", managedSeed.Namespace, managedSeed.Name))
}