forked from kcp-dev/kcp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworkspace_content_authorizer.go
303 lines (262 loc) · 11.8 KB
/
workspace_content_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
/*
Copyright 2022 The KCP Authors.
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 authorization
import (
"context"
"fmt"
"strings"
"github.com/kcp-dev/logicalcluster/v2"
"k8s.io/apimachinery/pkg/api/errors"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
kaudit "k8s.io/apiserver/pkg/audit"
authserviceaccount "k8s.io/apiserver/pkg/authentication/serviceaccount"
"k8s.io/apiserver/pkg/authentication/user"
"k8s.io/apiserver/pkg/authorization/authorizer"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
kubernetesinformers "k8s.io/client-go/informers"
rbacinformers "k8s.io/client-go/informers/rbac/v1"
rbaclisters "k8s.io/client-go/listers/rbac/v1"
"k8s.io/client-go/tools/clusters"
"k8s.io/kubernetes/pkg/genericcontrolplane"
"k8s.io/kubernetes/plugin/pkg/auth/authorizer/rbac"
tenancyv1alpha1 "github.com/kcp-dev/kcp/pkg/apis/tenancy/v1alpha1"
tenancyv1beta1 "github.com/kcp-dev/kcp/pkg/apis/tenancy/v1beta1"
"github.com/kcp-dev/kcp/pkg/authorization/bootstrap"
tenancylisters "github.com/kcp-dev/kcp/pkg/client/listers/tenancy/v1alpha1"
rbacwrapper "github.com/kcp-dev/kcp/pkg/virtual/framework/wrappers/rbac"
)
const (
WorkspaceAccessNotPermittedReason = "workspace access not permitted"
WorkspaceContentAuditPrefix = "content.authorization.kcp.dev/"
WorkspaceContentAuditDecision = WorkspaceContentAuditPrefix + "decision"
WorkspaceContentAuditReason = WorkspaceContentAuditPrefix + "reason"
)
func NewWorkspaceContentAuthorizer(versionedInformers kubernetesinformers.SharedInformerFactory, clusterWorkspaceLister tenancylisters.ClusterWorkspaceLister, delegate authorizer.Authorizer) authorizer.Authorizer {
return &workspaceContentAuthorizer{
rbacInformers: versionedInformers.Rbac().V1(),
roleLister: versionedInformers.Rbac().V1().Roles().Lister(),
roleBindingLister: versionedInformers.Rbac().V1().RoleBindings().Lister(),
clusterRoleLister: versionedInformers.Rbac().V1().ClusterRoles().Lister(),
clusterRoleBindingLister: versionedInformers.Rbac().V1().ClusterRoleBindings().Lister(),
clusterWorkspaceLister: clusterWorkspaceLister,
delegate: delegate,
}
}
type workspaceContentAuthorizer struct {
roleLister rbaclisters.RoleLister
roleBindingLister rbaclisters.RoleBindingLister
clusterRoleBindingLister rbaclisters.ClusterRoleBindingLister
clusterRoleLister rbaclisters.ClusterRoleLister
clusterWorkspaceLister tenancylisters.ClusterWorkspaceLister
// TODO: this will go away when scoping lands. Then we only have those 4 listers above.
rbacInformers rbacinformers.Interface
// union of local and bootstrap authorizer
delegate authorizer.Authorizer
}
func (a *workspaceContentAuthorizer) Authorize(ctx context.Context, attr authorizer.Attributes) (authorizer.Decision, string, error) {
cluster := genericapirequest.ClusterFrom(ctx)
// empty or non-root based workspaces have no meaning in the context of authorizing workspace content.
if cluster == nil || cluster.Name.Empty() || !cluster.Name.HasPrefix(tenancyv1alpha1.RootCluster) {
kaudit.AddAuditAnnotations(
ctx,
WorkspaceContentAuditDecision, DecisionNoOpinion,
WorkspaceContentAuditReason, "empty or non root workspace",
)
return authorizer.DecisionNoOpinion, WorkspaceAccessNotPermittedReason, nil
}
subjectClusters := map[logicalcluster.Name]bool{}
for _, sc := range attr.GetUser().GetExtra()[authserviceaccount.ClusterNameKey] {
subjectClusters[logicalcluster.New(sc)] = true
}
isAuthenticated := sets.NewString(attr.GetUser().GetGroups()...).Has("system:authenticated")
isUser := len(subjectClusters) == 0
isServiceAccountFromRootCluster := subjectClusters[tenancyv1alpha1.RootCluster]
isServiceAccountFromCluster := subjectClusters[cluster.Name]
if IsDeepSubjectAccessReviewFrom(ctx, attr) {
attr := deepCopyAttributes(attr)
// this is a deep SAR request, we have to skip the checks here and delegate to the subsequent authorizer.
if isAuthenticated && !isUser && !isServiceAccountFromCluster {
// service accounts from other workspaces might conflict with local service accounts by name.
// This could lead to unwanted side effects of unwanted applied permissions.
// Hence, these requests have to be anonymized.
attr.User = &user.DefaultInfo{
Name: "system:anonymous",
Groups: []string{"system:authenticated"},
}
}
kaudit.AddAuditAnnotations(
ctx,
WorkspaceContentAuditDecision, DecisionAllowed,
WorkspaceContentAuditReason, "deep SAR request",
)
return a.delegate.Authorize(ctx, attr)
}
// Every authenticated user has access to the root workspace but not every service account.
// For root, only service accounts declared in root have access.
if cluster.Name == tenancyv1alpha1.RootCluster {
if isAuthenticated && (isUser || isServiceAccountFromRootCluster) {
withGroups := deepCopyAttributes(attr)
withGroups.User.(*user.DefaultInfo).Groups = append(attr.GetUser().GetGroups(), bootstrap.SystemKcpClusterWorkspaceAccessGroup)
kaudit.AddAuditAnnotations(
ctx,
WorkspaceContentAuditDecision, DecisionAllowed,
WorkspaceContentAuditReason, "subject is either an authenticated user or a serviceaccount in root",
)
return a.delegate.Authorize(ctx, withGroups)
}
kaudit.AddAuditAnnotations(
ctx,
WorkspaceContentAuditDecision, DecisionNoOpinion,
WorkspaceContentAuditReason, "root workspace access by non-root service account not permitted",
)
return authorizer.DecisionNoOpinion, WorkspaceAccessNotPermittedReason, nil
}
// non-root workspaces must have a parent
parentClusterName, hasParent := cluster.Name.Parent()
if !hasParent {
kaudit.AddAuditAnnotations(
ctx,
WorkspaceContentAuditDecision, DecisionNoOpinion,
WorkspaceContentAuditReason, "non-root workspace that does not have a parent",
)
return authorizer.DecisionNoOpinion, WorkspaceAccessNotPermittedReason, nil
}
parentWorkspaceKubeInformer := rbacwrapper.FilterInformers(parentClusterName, a.rbacInformers)
bootstrapInformer := rbacwrapper.FilterInformers(genericcontrolplane.LocalAdminCluster, a.rbacInformers)
mergedClusterRoleLister := rbacwrapper.NewMergedClusterRoleLister(parentWorkspaceKubeInformer.ClusterRoles().Lister(), bootstrapInformer.ClusterRoles().Lister())
mergedRoleLister := rbacwrapper.NewMergedRoleLister(parentWorkspaceKubeInformer.Roles().Lister(), bootstrapInformer.Roles().Lister())
mergedClusterRoleBindingsLister := rbacwrapper.NewMergedClusterRoleBindingLister(parentWorkspaceKubeInformer.ClusterRoleBindings().Lister(), bootstrapInformer.ClusterRoleBindings().Lister())
parentAuthorizer := rbac.New(
&rbac.RoleGetter{Lister: mergedRoleLister},
&rbac.RoleBindingLister{Lister: parentWorkspaceKubeInformer.RoleBindings().Lister()},
&rbac.ClusterRoleGetter{Lister: mergedClusterRoleLister},
&rbac.ClusterRoleBindingLister{Lister: mergedClusterRoleBindingsLister},
)
extraGroups := sets.NewString()
// check the workspace even exists
ws, err := a.clusterWorkspaceLister.Get(clusters.ToClusterAwareKey(parentClusterName, cluster.Name.Base()))
if err != nil {
if errors.IsNotFound(err) {
kaudit.AddAuditAnnotations(
ctx,
WorkspaceContentAuditDecision, DecisionDenied,
WorkspaceContentAuditReason, "clusterworkspace not found",
)
return authorizer.DecisionDeny, WorkspaceAccessNotPermittedReason, nil
}
kaudit.AddAuditAnnotations(
ctx,
WorkspaceContentAuditDecision, DecisionNoOpinion,
WorkspaceContentAuditReason, fmt.Sprintf("error getting clusterworkspace: %v", err),
)
return authorizer.DecisionNoOpinion, "", err
}
if ws.Status.Phase != tenancyv1alpha1.ClusterWorkspacePhaseInitializing && ws.Status.Phase != tenancyv1alpha1.ClusterWorkspacePhaseReady {
kaudit.AddAuditAnnotations(
ctx,
WorkspaceContentAuditDecision, DecisionNoOpinion,
WorkspaceContentAuditReason, fmt.Sprintf("not permitted due to phase %q", ws.Status.Phase),
)
return authorizer.DecisionNoOpinion, WorkspaceAccessNotPermittedReason, nil
}
switch {
case isServiceAccountFromCluster:
// A service account declared in the requested workspace is authorized inside that workspace.
// Referencing such a service account in the parent workspace is not possible,
// hence authorization against "admin" or "access" verbs in the parent is not possible either.
extraGroups.Insert(bootstrap.SystemKcpClusterWorkspaceAccessGroup)
case isUser:
verbToGroupMembership := map[string][]string{
"admin": {bootstrap.SystemKcpClusterWorkspaceAccessGroup, bootstrap.SystemKcpClusterWorkspaceAdminGroup},
"access": {bootstrap.SystemKcpClusterWorkspaceAccessGroup},
}
var (
errList []error
reasonList []string
)
for verb, groups := range verbToGroupMembership {
workspaceAttr := authorizer.AttributesRecord{
User: attr.GetUser(),
Verb: verb,
APIGroup: tenancyv1beta1.SchemeGroupVersion.Group,
APIVersion: tenancyv1beta1.SchemeGroupVersion.Version,
Resource: "workspaces",
Subresource: "content",
Name: cluster.Name.Base(),
ResourceRequest: true,
}
dec, reason, err := parentAuthorizer.Authorize(ctx, workspaceAttr)
if err != nil {
errList = append(errList, err)
reasonList = append(reasonList, reason)
continue
}
if dec == authorizer.DecisionAllow {
extraGroups.Insert(groups...)
}
}
if len(errList) > 0 {
kaudit.AddAuditAnnotations(
ctx,
WorkspaceContentAuditDecision, DecisionNoOpinion,
WorkspaceContentAuditReason, fmt.Sprintf("errors from parent authorizer: %v", utilerrors.NewAggregate(errList)),
)
return authorizer.DecisionNoOpinion, strings.Join(reasonList, "\n"), utilerrors.NewAggregate(errList)
}
}
// non-admin subjects don't have access to initializing workspaces.
if ws.Status.Phase == tenancyv1alpha1.ClusterWorkspacePhaseInitializing && !extraGroups.Has(bootstrap.SystemKcpClusterWorkspaceAdminGroup) {
kaudit.AddAuditAnnotations(
ctx,
WorkspaceContentAuditDecision, DecisionNoOpinion,
WorkspaceContentAuditReason, "not permitted, clusterworkspace is in initializing phase",
)
return authorizer.DecisionNoOpinion, WorkspaceAccessNotPermittedReason, nil
}
if len(extraGroups) == 0 {
kaudit.AddAuditAnnotations(
ctx,
WorkspaceContentAuditDecision, DecisionNoOpinion,
WorkspaceContentAuditReason, "not permitted, subject has not been granted any groups",
)
return authorizer.DecisionNoOpinion, WorkspaceAccessNotPermittedReason, nil
}
withGroups := deepCopyAttributes(attr)
withGroups.User.(*user.DefaultInfo).Groups = append(attr.GetUser().GetGroups(), extraGroups.List()...)
kaudit.AddAuditAnnotations(
ctx,
WorkspaceContentAuditDecision, DecisionAllowed,
WorkspaceContentAuditReason, fmt.Sprintf("allowed with additional groups: %v", extraGroups),
)
return a.delegate.Authorize(ctx, withGroups)
}
func deepCopyAttributes(attr authorizer.Attributes) authorizer.AttributesRecord {
return authorizer.AttributesRecord{
User: &user.DefaultInfo{
Name: attr.GetUser().GetName(),
UID: attr.GetUser().GetUID(),
Groups: attr.GetUser().GetGroups(),
Extra: attr.GetUser().GetExtra(),
},
Verb: attr.GetVerb(),
Namespace: attr.GetNamespace(),
APIGroup: attr.GetAPIGroup(),
APIVersion: attr.GetAPIVersion(),
Resource: attr.GetResource(),
Subresource: attr.GetSubresource(),
Name: attr.GetName(),
ResourceRequest: attr.IsResourceRequest(),
Path: attr.GetPath(),
}
}