/
subjutil.go
64 lines (57 loc) · 1.66 KB
/
subjutil.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
package explorer
import (
"context"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"github.com/Ladicle/kubectl-rolesum/pkg/util/subject"
)
// subjectRoles retrieve RoleBindings for the specified subject.
func subjectRoleBindings(ctx context.Context, client *kubernetes.Clientset, sbj *rbacv1.Subject) ([]rbacv1.RoleBinding, error) {
list, err := client.RbacV1().RoleBindings(sbj.Namespace).
List(ctx, metav1.ListOptions{})
if err != nil {
return nil, err
}
var sbjrs []rbacv1.RoleBinding
for _, b := range list.Items {
if containSubject(sbj, b.Subjects) {
sbjrs = append(sbjrs, b)
}
}
return sbjrs, nil
}
// subjectClusterRoles retrieve ClusterRoleBindings for the specified subject.
func subjectClusterRoleBindings(ctx context.Context, client *kubernetes.Clientset, sbj *rbacv1.Subject) ([]rbacv1.ClusterRoleBinding, error) {
list, err := client.RbacV1().ClusterRoleBindings().
List(ctx, metav1.ListOptions{})
if err != nil {
return nil, err
}
var sbjcrs []rbacv1.ClusterRoleBinding
for _, b := range list.Items {
if containSubject(sbj, b.Subjects) {
sbjcrs = append(sbjcrs, b)
}
}
return sbjcrs, nil
}
// containSubject returns true if the specified subject is on the list.
func containSubject(s *rbacv1.Subject, list []rbacv1.Subject) bool {
for _, sub := range list {
if sameSubject(&sub, s) {
return true
}
}
return false
}
// sameSubject returns true if s1 equals s2.
func sameSubject(s1, s2 *rbacv1.Subject) bool {
if s1.Kind != s2.Kind || s1.Name != s2.Name {
return false
}
if s1.Kind == subject.KindSA && s1.Namespace != s2.Namespace {
return false
}
return true
}