generated from vshn/go-bootstrap
/
userinfo.go
67 lines (57 loc) · 2.03 KB
/
userinfo.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
package userinfo
import (
"context"
"fmt"
authenticationv1 "k8s.io/api/authentication/v1"
rbacv1 "k8s.io/api/rbac/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
//+kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=clusterrolebindings,verbs=get;list;watch
const (
// saPrefix represents the service account prefix in admission requests
saPrefix = "system:serviceaccount:"
clusterRoleKind = "ClusterRole"
)
// ClusterRoleRefsForUser gets the list of roles and cluster roles for the given user information.
// Only cluster roles bound by a cluster role binding are returned.
// Role bindings are ignored.
func ClusterRoleRefsForUser(ctx context.Context, cli client.Reader, user authenticationv1.UserInfo) (clusterroles []string, err error) {
crbs, err := listClusterRoleBindings(ctx, cli)
if err != nil {
return nil, fmt.Errorf("failed to list clusterrolebindings: %v", err)
}
return clusterRoleRefs(crbs, user), nil
}
func clusterRoleRefs(clusterroleBindings []rbacv1.ClusterRoleBinding, userInfo authenticationv1.UserInfo) (clusterRoles []string) {
for _, clusterRoleBinding := range clusterroleBindings {
for _, subject := range clusterRoleBinding.Subjects {
if clusterRoleBinding.RoleRef.Kind == clusterRoleKind && matchSubject(subject, userInfo) {
clusterRoles = append(clusterRoles, clusterRoleBinding.RoleRef.Name)
}
}
}
return clusterRoles
}
func matchSubject(subject rbacv1.Subject, userInfo authenticationv1.UserInfo) bool {
switch subject.Kind {
case rbacv1.ServiceAccountKind:
return userInfo.Username == saPrefix+subject.Namespace+":"+subject.Name
case rbacv1.UserKind:
return userInfo.Username == subject.Name
case rbacv1.GroupKind:
for _, group := range userInfo.Groups {
if subject.Name == group {
return true
}
}
return false
}
return false
}
func listClusterRoleBindings(ctx context.Context, cli client.Reader) ([]rbacv1.ClusterRoleBinding, error) {
var crbs rbacv1.ClusterRoleBindingList
if err := cli.List(ctx, &crbs); err != nil {
return nil, err
}
return crbs.Items, nil
}