/
authorizer.go
370 lines (327 loc) · 15.4 KB
/
authorizer.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
// Copyright 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 seed
import (
"context"
"fmt"
"strings"
"github.com/go-logr/logr"
certificatesv1 "k8s.io/api/certificates/v1"
coordinationv1 "k8s.io/api/coordination/v1"
corev1 "k8s.io/api/core/v1"
eventsv1 "k8s.io/api/events/v1"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
auth "k8s.io/apiserver/pkg/authorization/authorizer"
bootstraptokenapi "k8s.io/cluster-bootstrap/token/api"
"github.com/gardener/gardener/pkg/admissioncontroller/seedidentity"
"github.com/gardener/gardener/pkg/admissioncontroller/webhook/auth/seed/graph"
gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
v1beta1constants "github.com/gardener/gardener/pkg/apis/core/v1beta1/constants"
operationsv1alpha1 "github.com/gardener/gardener/pkg/apis/operations/v1alpha1"
seedmanagementv1alpha1 "github.com/gardener/gardener/pkg/apis/seedmanagement/v1alpha1"
gardenletbootstraputil "github.com/gardener/gardener/pkg/gardenlet/bootstrap/util"
"github.com/gardener/gardener/pkg/utils"
gardenerutils "github.com/gardener/gardener/pkg/utils/gardener"
)
// NewAuthorizer returns a new authorizer for requests from gardenlets. It never has an opinion on the request.
func NewAuthorizer(logger logr.Logger, graph graph.Interface) *authorizer {
return &authorizer{
logger: logger,
graph: graph,
}
}
type authorizer struct {
logger logr.Logger
graph graph.Interface
}
var _ = auth.Authorizer(&authorizer{})
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 = operationsv1alpha1.Resource("bastions")
certificateSigningRequestResource = certificatesv1.Resource("certificatesigningrequests")
cloudProfileResource = gardencorev1beta1.Resource("cloudprofiles")
clusterRoleBindingResource = rbacv1.Resource("clusterrolebindings")
configMapResource = corev1.Resource("configmaps")
controllerDeploymentResource = gardencorev1beta1.Resource("controllerdeployments")
controllerInstallationResource = gardencorev1beta1.Resource("controllerinstallations")
controllerRegistrationResource = gardencorev1beta1.Resource("controllerregistrations")
eventCoreResource = corev1.Resource("events")
eventResource = eventsv1.Resource("events")
leaseResource = coordinationv1.Resource("leases")
managedSeedResource = seedmanagementv1alpha1.Resource("managedseeds")
namespaceResource = corev1.Resource("namespaces")
projectResource = gardencorev1beta1.Resource("projects")
secretBindingResource = gardencorev1beta1.Resource("secretbindings")
secretResource = corev1.Resource("secrets")
seedResource = gardencorev1beta1.Resource("seeds")
serviceAccountResource = corev1.Resource("serviceaccounts")
shootResource = gardencorev1beta1.Resource("shoots")
shootStateResource = gardencorev1beta1.Resource("shootstates")
exposureClassResource = gardencorev1beta1.Resource("exposureclasses")
)
// TODO: Revisit all `DecisionNoOpinion` later. Today we cannot deny the request for backwards compatibility
// because older Gardenlet versions might not be compatible at the time this authorization plugin is enabled.
// With `DecisionNoOpinion`, RBAC will be respected in the authorization chain afterwards.
func (a *authorizer) Authorize(_ context.Context, attrs auth.Attributes) (auth.Decision, string, error) {
seedName, isSeed := seedidentity.FromUserInfoInterface(attrs.GetUser())
if !isSeed {
return auth.DecisionNoOpinion, "", nil
}
requestLog := a.logger.WithValues("seedName", seedName, "attributes", fmt.Sprintf("%#v", attrs))
if attrs.IsResourceRequest() {
requestResource := schema.GroupResource{Group: attrs.GetAPIGroup(), Resource: attrs.GetResource()}
switch requestResource {
case backupBucketResource:
return a.authorize(requestLog, seedName, graph.VertexTypeBackupBucket, attrs,
[]string{"update", "patch", "delete"},
[]string{"create", "get", "list", "watch"},
[]string{"status"},
)
case backupEntryResource:
return a.authorize(requestLog, seedName, graph.VertexTypeBackupEntry, attrs,
[]string{"update", "patch", "delete"},
[]string{"create", "get", "list", "watch"},
[]string{"status"},
)
case bastionResource:
return a.authorize(requestLog, seedName, graph.VertexTypeBastion, attrs,
[]string{"update", "patch"},
[]string{"create", "get", "list", "watch"},
[]string{"status"},
)
case certificateSigningRequestResource:
return a.authorize(requestLog, seedName, graph.VertexTypeCertificateSigningRequest, attrs,
[]string{"get", "list", "watch"},
[]string{"create"},
[]string{"seedclient"},
)
case cloudProfileResource:
return a.authorizeRead(requestLog, seedName, graph.VertexTypeCloudProfile, attrs)
case clusterRoleBindingResource:
return a.authorizeClusterRoleBinding(requestLog, seedName, attrs)
case configMapResource:
return a.authorizeRead(requestLog, seedName, graph.VertexTypeConfigMap, attrs)
case controllerDeploymentResource:
return a.authorizeRead(requestLog, seedName, graph.VertexTypeControllerDeployment, attrs)
case controllerInstallationResource:
return a.authorize(requestLog, seedName, graph.VertexTypeControllerInstallation, attrs,
[]string{"update", "patch"},
[]string{"get", "list", "watch"},
[]string{"status"},
)
case controllerRegistrationResource:
return a.authorize(requestLog, seedName, graph.VertexTypeControllerRegistration, attrs,
nil,
[]string{"get", "list", "watch"},
nil,
)
case eventCoreResource, eventResource:
return a.authorizeEvent(requestLog, attrs)
case leaseResource:
return a.authorizeLease(requestLog, seedName, attrs)
case managedSeedResource:
return a.authorize(requestLog, seedName, graph.VertexTypeManagedSeed, attrs,
[]string{"update", "patch"},
[]string{"get", "list", "watch"},
[]string{"status"},
)
case namespaceResource:
return a.authorizeRead(requestLog, seedName, graph.VertexTypeNamespace, attrs)
case projectResource:
return a.authorizeRead(requestLog, seedName, graph.VertexTypeProject, attrs)
case secretBindingResource:
return a.authorizeRead(requestLog, seedName, graph.VertexTypeSecretBinding, attrs)
case secretResource:
return a.authorizeSecret(requestLog, seedName, attrs)
case seedResource:
return a.authorize(requestLog, seedName, graph.VertexTypeSeed, attrs,
nil,
[]string{"create", "update", "patch", "delete", "get", "list", "watch"},
[]string{"status"},
)
case serviceAccountResource:
return a.authorizeServiceAccount(requestLog, seedName, attrs)
case shootResource:
return a.authorize(requestLog, seedName, graph.VertexTypeShoot, attrs,
[]string{"update", "patch"},
[]string{"get", "list", "watch"},
[]string{"status"},
)
case shootStateResource:
return a.authorize(requestLog, seedName, graph.VertexTypeShootState, attrs,
[]string{"get", "update", "patch", "delete", "list", "watch"},
[]string{"create"},
nil,
)
case exposureClassResource:
return a.authorizeRead(requestLog, seedName, graph.VertexTypeExposureClass, attrs)
default:
a.logger.Info(
"Unhandled resource request",
"seed", seedName,
"group", attrs.GetAPIGroup(),
"version", attrs.GetAPIVersion(),
"resource", attrs.GetResource(),
"verb", attrs.GetVerb(),
)
}
}
return auth.DecisionNoOpinion, "", nil
}
func (a *authorizer) authorizeClusterRoleBinding(log logr.Logger, seedName string, attrs auth.Attributes) (auth.Decision, string, error) {
// Allow gardenlet to delete its cluster role binding after bootstrapping (in this case, there is no `Seed` resource
// in the system yet, so we can't rely on the graph).
if attrs.GetVerb() == "delete" &&
strings.HasPrefix(attrs.GetName(), gardenletbootstraputil.ClusterRoleBindingNamePrefix) {
managedSeedNamespace, managedSeedName := gardenletbootstraputil.ManagedSeedInfoFromClusterRoleBindingName(attrs.GetName())
if managedSeedNamespace == v1beta1constants.GardenNamespace && managedSeedName == seedName {
return auth.DecisionAllow, "", nil
}
}
return a.authorize(log, seedName, graph.VertexTypeClusterRoleBinding, attrs,
[]string{"get", "patch", "update"},
[]string{"create"},
nil,
)
}
func (a *authorizer) authorizeEvent(log logr.Logger, attrs auth.Attributes) (auth.Decision, string, error) {
if ok, reason := a.checkVerb(log, attrs, "create", "patch"); !ok {
return auth.DecisionNoOpinion, reason, nil
}
if ok, reason := a.checkSubresource(log, attrs); !ok {
return auth.DecisionNoOpinion, reason, nil
}
return auth.DecisionAllow, "", nil
}
func (a *authorizer) authorizeLease(log logr.Logger, seedName string, attrs auth.Attributes) (auth.Decision, string, error) {
// This is needed if the seed cluster is a garden cluster at the same time.
if attrs.GetName() == "gardenlet-leader-election" &&
utils.ValueExists(attrs.GetVerb(), []string{"create", "get", "list", "watch", "update"}) {
return auth.DecisionAllow, "", nil
}
return a.authorize(log, seedName, graph.VertexTypeLease, attrs,
[]string{"get", "update", "patch", "list", "watch"},
[]string{"create"},
nil,
)
}
func (a *authorizer) authorizeSecret(log logr.Logger, seedName string, attrs auth.Attributes) (auth.Decision, string, error) {
// Allow gardenlets to get/list/watch secrets in their seed-<name> namespaces.
if utils.ValueExists(attrs.GetVerb(), []string{"get", "list", "watch"}) && attrs.GetNamespace() == gardenerutils.ComputeGardenNamespace(seedName) {
return auth.DecisionAllow, "", nil
}
// Allow gardenlet to delete its bootstrap token (in this case, there is no `Seed` resource in the system yet, so
// we can't rely on the graph).
if (attrs.GetVerb() == "delete" &&
attrs.GetNamespace() == metav1.NamespaceSystem &&
strings.HasPrefix(attrs.GetName(), bootstraptokenapi.BootstrapTokenSecretPrefix)) &&
(attrs.GetName() == bootstraptokenapi.BootstrapTokenSecretPrefix+gardenletbootstraputil.TokenID(metav1.ObjectMeta{Name: seedName, Namespace: v1beta1constants.GardenNamespace})) {
return auth.DecisionAllow, "", nil
}
return a.authorize(log, seedName, graph.VertexTypeSecret, attrs,
[]string{"get", "patch", "update", "delete"},
[]string{"create"},
nil,
)
}
func (a *authorizer) authorizeServiceAccount(log logr.Logger, seedName string, attrs auth.Attributes) (auth.Decision, string, error) {
// Allow gardenlet to delete its service account after bootstrapping (in this case, there is no `Seed` resource in
// the system yet, so we can't rely on the graph).
if attrs.GetVerb() == "delete" &&
attrs.GetNamespace() == v1beta1constants.GardenNamespace &&
strings.HasPrefix(attrs.GetName(), gardenletbootstraputil.ServiceAccountNamePrefix) &&
strings.TrimPrefix(attrs.GetName(), gardenletbootstraputil.ServiceAccountNamePrefix) == seedName {
return auth.DecisionAllow, "", nil
}
return a.authorize(log, seedName, graph.VertexTypeServiceAccount, attrs,
[]string{"get", "patch", "update"},
[]string{"create"},
nil,
)
}
func (a *authorizer) authorizeRead(log logr.Logger, seedName string, fromType graph.VertexType, attrs auth.Attributes) (auth.Decision, string, error) {
return a.authorize(log, seedName, fromType, attrs,
[]string{"get", "list", "watch"},
nil,
nil,
)
}
func (a *authorizer) authorize(
log logr.Logger,
seedName string,
fromType graph.VertexType,
attrs auth.Attributes,
allowedVerbs []string,
alwaysAllowedVerbs []string,
allowedSubresources []string,
) (
auth.Decision,
string,
error,
) {
if ok, reason := a.checkSubresource(log, attrs, allowedSubresources...); !ok {
return auth.DecisionNoOpinion, reason, nil
}
// When a new object is created then it doesn't yet exist in the graph, so usually such requests are always allowed
// as the 'create case' is typically handled in the SeedRestriction admission handler. Similarly, resources for
// which the gardenlet has a controller need to be listed/watched, so those verbs would also be allowed here.
if utils.ValueExists(attrs.GetVerb(), alwaysAllowedVerbs) {
return auth.DecisionAllow, "", nil
}
if ok, reason := a.checkVerb(log, attrs, append(alwaysAllowedVerbs, allowedVerbs...)...); !ok {
return auth.DecisionNoOpinion, reason, nil
}
return a.hasPathFrom(log, seedName, fromType, attrs)
}
func (a *authorizer) hasPathFrom(log logr.Logger, seedName string, fromType graph.VertexType, attrs auth.Attributes) (auth.Decision, string, error) {
if len(attrs.GetName()) == 0 {
log.Info("Denying authorization because attributes are missing object name")
return auth.DecisionNoOpinion, "No Object name found", nil
}
// If the request is made for a namespace then the attributes.Namespace field is not empty. It contains the name of
// the namespace.
namespace := attrs.GetNamespace()
if fromType == graph.VertexTypeNamespace {
namespace = ""
}
// If the vertex does not exist in the graph (i.e., the resource does not exist in the system) then we allow the
// request.
if attrs.GetVerb() == "delete" && !a.graph.HasVertex(fromType, namespace, attrs.GetName()) {
return auth.DecisionAllow, "", nil
}
if !a.graph.HasPathFrom(fromType, namespace, attrs.GetName(), graph.VertexTypeSeed, "", seedName) {
log.Info("Denying authorization because no relationship is found between seed and object")
return auth.DecisionNoOpinion, fmt.Sprintf("no relationship found between seed '%s' and this object", seedName), nil
}
return auth.DecisionAllow, "", nil
}
func (a *authorizer) checkVerb(log logr.Logger, attrs auth.Attributes, allowedVerbs ...string) (bool, string) {
if !utils.ValueExists(attrs.GetVerb(), allowedVerbs) {
log.Info("Denying authorization because verb is not allowed for this resource type", "allowedVerbs", allowedVerbs)
return false, fmt.Sprintf("only the following verbs are allowed for this resource type: %+v", allowedVerbs)
}
return true, ""
}
func (a *authorizer) checkSubresource(log logr.Logger, attrs auth.Attributes, allowedSubresources ...string) (bool, string) {
if subresource := attrs.GetSubresource(); len(subresource) > 0 && !utils.ValueExists(attrs.GetSubresource(), allowedSubresources) {
log.Info("Denying authorization because subresource is not allowed for this resource type", "allowedSubresources", allowedSubresources)
return false, fmt.Sprintf("only the following subresources are allowed for this resource type: %+v", allowedSubresources)
}
return true, ""
}