-
Notifications
You must be signed in to change notification settings - Fork 0
/
prtb_handler.go
364 lines (322 loc) · 10.1 KB
/
prtb_handler.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
package rbac
import (
"fmt"
"reflect"
"strings"
"github.com/pkg/errors"
"github.com/rancher/norman/types/slice"
"github.com/rancher/types/apis/management.cattle.io/v3"
"github.com/sirupsen/logrus"
"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/labels"
)
const owner = "owner-user"
var globalResourcesNeededInProjects = []string{"persistentvolumes", "storageclasses"}
func newPRTBLifecycle(m *manager) *prtbLifecycle {
return &prtbLifecycle{m: m}
}
type prtbLifecycle struct {
m *manager
}
func (p *prtbLifecycle) Create(obj *v3.ProjectRoleTemplateBinding) (*v3.ProjectRoleTemplateBinding, error) {
err := p.syncPRTB(obj)
return obj, err
}
func (p *prtbLifecycle) Updated(obj *v3.ProjectRoleTemplateBinding) (*v3.ProjectRoleTemplateBinding, error) {
err := p.syncPRTB(obj)
return obj, err
}
func (p *prtbLifecycle) Remove(obj *v3.ProjectRoleTemplateBinding) (*v3.ProjectRoleTemplateBinding, error) {
err := p.ensurePRTBDelete(obj)
return obj, err
}
func (p *prtbLifecycle) syncPRTB(binding *v3.ProjectRoleTemplateBinding) error {
if binding.RoleTemplateName == "" {
logrus.Warnf("ProjectRoleTemplateBinding %v has no role template set. Skipping.", binding.Name)
return nil
}
if binding.UserName == "" && binding.GroupPrincipalName == "" && binding.GroupName == "" {
return nil
}
rt, err := p.m.rtLister.Get("", binding.RoleTemplateName)
if err != nil {
return errors.Wrapf(err, "couldn't get role template %v", binding.RoleTemplateName)
}
// Get namespaces belonging to project
namespaces, err := p.m.nsIndexer.ByIndex(nsByProjectIndex, binding.ProjectName)
if err != nil {
return errors.Wrapf(err, "couldn't list namespaces with project ID %v", binding.ProjectName)
}
roles := map[string]*v3.RoleTemplate{}
if err := p.m.gatherRoles(rt, roles); err != nil {
return err
}
if err := p.m.ensureRoles(roles); err != nil {
return errors.Wrap(err, "couldn't ensure roles")
}
for _, n := range namespaces {
ns := n.(*v1.Namespace)
if err := p.m.ensureProjectRoleBindings(ns.Name, roles, binding); err != nil {
return errors.Wrapf(err, "couldn't ensure binding %v in %v", binding.Name, ns.Name)
}
}
return p.reconcileProjectAccessToGlobalResources(binding, roles)
}
func (p *prtbLifecycle) ensurePRTBDelete(binding *v3.ProjectRoleTemplateBinding) error {
// Get namespaces belonging to project
namespaces, err := p.m.nsIndexer.ByIndex(nsByProjectIndex, binding.ProjectName)
if err != nil {
return errors.Wrapf(err, "couldn't list namespaces with project ID %v", binding.ProjectName)
}
set := labels.Set(map[string]string{rtbOwnerLabel: string(binding.UID)})
for _, n := range namespaces {
ns := n.(*v1.Namespace)
bindingCli := p.m.workload.K8sClient.RbacV1().RoleBindings(ns.Name)
rbs, err := p.m.rbLister.List(ns.Name, set.AsSelector())
if err != nil {
return errors.Wrapf(err, "couldn't list rolebindings with selector %s", set.AsSelector())
}
for _, rb := range rbs {
if err := bindingCli.Delete(rb.Name, &metav1.DeleteOptions{}); err != nil {
if !apierrors.IsNotFound(err) {
return errors.Wrapf(err, "error deleting rolebinding %v", rb.Name)
}
}
}
}
return p.reconcileProjectAccessToGlobalResourcesForDelete(binding)
}
func (p *prtbLifecycle) reconcileProjectAccessToGlobalResources(binding *v3.ProjectRoleTemplateBinding, rts map[string]*v3.RoleTemplate) error {
var role string
var createNSPerms bool
var roles []string
if parts := strings.SplitN(binding.ProjectName, ":", 2); len(parts) == 2 && len(parts[1]) > 0 {
projectName := parts[1]
var roleVerb, roleSuffix string
for _, r := range rts {
for _, rule := range r.Rules {
if slice.ContainsString(rule.Resources, "namespaces") && len(rule.ResourceNames) == 0 {
if slice.ContainsString(rule.Verbs, "*") || slice.ContainsString(rule.Verbs, "create") {
roleVerb = "*"
createNSPerms = true
break
}
}
}
}
if roleVerb == "" {
roleVerb = "get"
}
roleSuffix = projectNSVerbToSuffix[roleVerb]
role = fmt.Sprintf(projectNSGetClusterRoleNameFmt, projectName, roleSuffix)
roles = append(roles, role)
for _, rt := range rts {
for _, resource := range globalResourcesNeededInProjects {
verbs, err := p.m.checkForGlobalResourceRules(rt, resource)
if err != nil {
return err
}
if len(verbs) > 0 {
roleName, err := p.m.reconcileRoleForProjectAccessToGlobalResource(resource, rt, verbs)
if err != nil {
return err
}
roles = append(roles, roleName)
}
}
}
}
if len(roles) == 0 {
return nil
}
bindingCli := p.m.workload.K8sClient.RbacV1().ClusterRoleBindings()
if createNSPerms {
roles = append(roles, "create-ns")
if nsRole, _ := p.m.crLister.Get("", "create-ns"); nsRole == nil {
createNSRT, err := p.m.rtLister.Get("", "create-ns")
if err != nil {
return err
}
if err := p.m.ensureRoles(map[string]*v3.RoleTemplate{"create-ns": createNSRT}); err != nil && !apierrors.IsAlreadyExists(err) {
return err
}
}
}
rtbUID := string(binding.UID)
subject, err := buildSubjectFromRTB(binding)
if err != nil {
return err
}
for _, role := range roles {
crbKey := rbRoleSubjectKey(role, subject)
crbs, _ := p.m.crbIndexer.ByIndex(crbByRoleAndSubjectIndex, crbKey)
if len(crbs) == 0 {
logrus.Infof("Creating clusterRoleBinding for project access to global resource for subject %v role %v.", subject.Name, role)
_, err := bindingCli.Create(&rbacv1.ClusterRoleBinding{
ObjectMeta: metav1.ObjectMeta{
GenerateName: "clusterrolebinding-",
Labels: map[string]string{
rtbUID: owner,
},
},
Subjects: []rbacv1.Subject{subject},
RoleRef: rbacv1.RoleRef{
Kind: "ClusterRole",
Name: role,
},
})
if err != nil {
return err
}
} else {
CRBs:
for _, obj := range crbs {
crb, ok := obj.(*rbacv1.ClusterRoleBinding)
if !ok {
continue
}
for owner := range crb.Labels {
if rtbUID == owner {
continue CRBs
}
}
crb = crb.DeepCopy()
if crb.Labels == nil {
crb.Labels = map[string]string{}
}
crb.Labels[rtbUID] = owner
logrus.Infof("Updating clusterRoleBinding %v for project access to global resource for subject %v role %v.", crb.Name, subject.Name, role)
_, err := bindingCli.Update(crb)
if err != nil {
return err
}
}
}
}
return nil
}
func (p *prtbLifecycle) reconcileProjectAccessToGlobalResourcesForDelete(binding *v3.ProjectRoleTemplateBinding) error {
prtbs, err := p.m.prtbIndexer.ByIndex(prtbByProjecSubjectIndex, getPRTBProjectAndSubjectKey(binding))
if err != nil {
return err
}
if len(prtbs) != 0 {
for _, p := range prtbs {
pr := p.(*v3.ProjectRoleTemplateBinding)
if pr.DeletionTimestamp == nil {
return nil
}
}
}
bindingCli := p.m.workload.K8sClient.RbacV1().ClusterRoleBindings()
rtbUID := string(binding.UID)
set := labels.Set(map[string]string{rtbUID: owner})
crbs, err := p.m.crbLister.List("", set.AsSelector())
if err != nil {
return err
}
for _, crb := range crbs {
crb = crb.DeepCopy()
for k, v := range crb.Labels {
if k == rtbUID && v == owner {
delete(crb.Labels, k)
}
}
if len(crb.Labels) == 0 {
if err := bindingCli.Delete(crb.Name, &metav1.DeleteOptions{}); err != nil {
if apierrors.IsNotFound(err) {
continue
}
return err
}
} else {
if _, err := bindingCli.Update(crb); err != nil {
return err
}
}
}
return nil
}
// If the roleTemplate has rules granting access to non-namespaced (global) resource, return the verbs for those rules
func (m *manager) checkForGlobalResourceRules(role *v3.RoleTemplate, resource string) (map[string]bool, error) {
var rules []rbacv1.PolicyRule
if role.External {
externalRole, err := m.crLister.Get("", role.Name)
if err != nil && !apierrors.IsNotFound(err) {
// dont error if it doesnt exist
return nil, err
}
if externalRole != nil {
rules = externalRole.Rules
}
} else {
rules = role.Rules
}
verbs := map[string]bool{}
for _, rule := range rules {
if (slice.ContainsString(rule.Resources, resource) || slice.ContainsString(rule.Resources, "*")) && len(rule.ResourceNames) == 0 {
for _, v := range rule.Verbs {
verbs[v] = true
}
}
}
return verbs, nil
}
// Ensure the clusterRole used to grant access of global resources to users/groups in projects has appropriate rulesfor the give resource and verbs
func (m *manager) reconcileRoleForProjectAccessToGlobalResource(resource string, rt *v3.RoleTemplate, newVerbs map[string]bool) (string, error) {
clusterRoles := m.workload.RBAC.ClusterRoles("")
roleName := rt.Name + "-promoted"
if role, err := m.crLister.Get("", roleName); err == nil && role != nil {
currentVerbs := map[string]bool{}
for _, rule := range role.Rules {
if slice.ContainsString(rule.Resources, resource) {
for _, v := range rule.Verbs {
currentVerbs[v] = true
}
}
}
if !reflect.DeepEqual(currentVerbs, newVerbs) {
role = role.DeepCopy()
added := false
for i, rule := range role.Rules {
if slice.ContainsString(rule.Resources, resource) {
role.Rules[i] = buildRule(resource, newVerbs)
added = true
}
}
if !added {
role.Rules = append(role.Rules, buildRule(resource, newVerbs))
}
logrus.Infof("Updating clusterRole %v for project access to global resource.", role.Name)
_, err := clusterRoles.Update(role)
return roleName, err
}
return roleName, nil
}
logrus.Infof("Creating clusterRole %v for project access to global resource.", roleName)
rules := []rbacv1.PolicyRule{buildRule(resource, newVerbs)}
_, err := clusterRoles.Create(&rbacv1.ClusterRole{
ObjectMeta: metav1.ObjectMeta{
Name: roleName,
},
Rules: rules,
})
if err != nil {
return roleName, errors.Wrapf(err, "couldn't create role %v", roleName)
}
return roleName, nil
}
func buildRule(resource string, verbs map[string]bool) rbacv1.PolicyRule {
var vs []string
for v := range verbs {
vs = append(vs, v)
}
return rbacv1.PolicyRule{
Resources: []string{resource},
Verbs: vs,
APIGroups: []string{"*"},
}
}