RBAC Rule 解析器
示例文件
以下示例文件来自于 https://www.notion.so/RBAC-Rule-9081d97205a14f82b0464ffed550fb8a
Role
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: default
name: pod-reader
rules:
- apiGroups: [""] # "" indicates the core API group
resources: ["pods"]
verbs: ["get", "watch", "list"]
ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
# "namespace" omitted since ClusterRoles are not namespaced
name: secret-reader
rules:
- apiGroups: [""]
#
# at the HTTP level, the name of the resource for accessing Secret
# objects is "secrets"
resources: ["secrets"]
verbs: ["get", "watch", "list"]
RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
# This role binding allows "jane" to read pods in the "default" namespace.
# You need to already have a Role named "pod-reader" in that namespace.
kind: RoleBinding
metadata:
name: read-pods
namespace: default
subjects:
# You can specify more than one "subject"
- kind: User
name: jane # "name" is case sensitive
apiGroup: rbac.authorization.k8s.io
roleRef:
# "roleRef" specifies the binding to a Role / ClusterRole
kind: Role #this must be Role or ClusterRole
name: pod-reader # this must match the name of the Role or ClusterRole you wish to bind to
apiGroup: rbac.authorization.k8s.io
ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
# This cluster role binding allows anyone in the "manager" group to read secrets in any namespace.
kind: ClusterRoleBinding
metadata:
name: read-secrets-global
subjects:
- kind: Group
name: manager # Name is case sensitive
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: secret-reader
apiGroup: rbac.authorization.k8s.io
AuthorizationRuleResolver接口
AuthorizationRuleResolver 定义了RBAC的解析器需要实现的方法
type AuthorizationRuleResolver interface {
// GetRoleReferenceRules attempts to resolve the role reference of a RoleBinding or ClusterRoleBinding. The passed namespace should be the namespace
// of the role binding, the empty string if a cluster role binding.
GetRoleReferenceRules(roleRef rbacv1.RoleRef, namespace string) ([]rbacv1.PolicyRule, error)
// RulesFor returns the list of rules that apply to a given user in a given namespace and error. If an error is returned, the slice of
// PolicyRules may not be complete, but it contains all retrievable rules. This is done because policy rules are purely additive and policy determinations
// can be made on the basis of those rules that are found.
RulesFor(user user.Info, namespace string) ([]rbacv1.PolicyRule, error)
// VisitRulesFor invokes visitor() with each rule that applies to a given user in a given namespace, and each error encountered resolving those rules.
// If visitor() returns false, visiting is short-circuited.
VisitRulesFor(user user.Info, namespace string, visitor func(source fmt.Stringer, rule *rbacv1.PolicyRule, err error) bool)
}
GetRoleReferenceRules 方法
GetRoleReferenceRules
通过roleRef rbacv1.RoleRef
尝试解析role对Rolebinding或ClusterRoleBinding的引用。
其中namespace
如果为空则表示是集群角色绑定,否则role绑定定义的namespace
。
GetRoleReferenceRules
解析传递的roleRef
返回该角色所有的PolicyRule
。
RulesFor 方法
RulesFor
返回指定user
的所有PolicyRule
(包括namespace和cluster),如果返回了错误,[]PolicyRule数据不完整,slice仅包含所有可检索的PolicyRule。返回不完整的PolicyRule切片而不是遇到错误终止的原因在于PolicyRule是纯粹的可追加的策略,即使不完整,上层调用者也可以基于这些不完整的规则做出一些决定。
VisitRulesFor 方法
VisitRulesFor
调用为每个user在给定namespace
中的所有PolicyRule
调用visitor()
,vistior()
返回错误,遍历应该是短路(short-circuited)操作。
DefaultRuleResolver 实现
DefaultRuleResolver
是对AuthorizationRuleResolver
接口的默认实现。
DefaultRuleResolver 数据结构
type DefaultRuleResolver struct {
roleGetter RoleGetter
roleBindingLister RoleBindingLister
clusterRoleGetter ClusterRoleGetter
clusterRoleBindingLister ClusterRoleBindingLister
}
-
RoleGetter
, 接口,用于获取Role -
RoleBindingLister
,接口,用户获取Role的[]RoleBinding
-
ClusterRoleGetter
,接口,集群Role -
ClusterRoleBindingLister
,接口,集群Role的[]ClusterRoleBinding
GetRoleReferenceRules 实现
func (r *DefaultRuleResolver) GetRoleReferenceRules(roleRef rbacv1.RoleRef, bindingNamespace string) ([]rbacv1.PolicyRule, error) {
switch roleRef.Kind {
case "Role":
role, err := r.roleGetter.GetRole(bindingNamespace, roleRef.Name)
if err != nil {
return nil, err
}
return role.Rules, nil
case "ClusterRole":
clusterRole, err := r.clusterRoleGetter.GetClusterRole(roleRef.Name)
if err != nil {
return nil, err
}
return clusterRole.Rules, nil
default:
return nil, fmt.Errorf("unsupported role reference kind: %q", roleRef.Kind)
}
}
首先对roleRef.Kind断言,以判断是namespace级别还是Cluster级别的Role
Namespace Role
- 根据roleRef引用的role name 以及 绑定的namespace,使用roleGetter获取Role资源对象
- 返回Role定义的Rules
Cluster Role
- 根据roleRef引用的role name ,使用clusterRoleGetter获取ClusterRole资源对象
- 返回ClusterRole定义的Rules
VisitRulesFor 实现
VisitRulesFor 接收user、namespace(可为空)和visitor 函数,VisitRulesFor仅执行遍历操作,真正的业务逻辑由visitor函数处理。
func (r *DefaultRuleResolver) VisitRulesFor(user user.Info, namespace string, visitor func(source fmt.Stringer, rule *rbacv1.PolicyRule, err error) bool) {
if clusterRoleBindings, err := r.clusterRoleBindingLister.ListClusterRoleBindings(); err != nil {
if !visitor(nil, nil, err) {
return
}
} else {
// sourceDescriber 建立 ClusterRoleBinding 和subjects数据结构,
// 并将该结构转化为一个可描述string类型
sourceDescriber := &clusterRoleBindingDescriber{}
// 遍历所有的 ClusterRoleBinding
// Note: 时间复杂度 O(N)
for _, clusterRoleBinding := range clusterRoleBindings {
// 查找 ClusterRoleBinding下的 Subject 是否有和该user匹配的
// Note: 时间复杂度 O(N)
subjectIndex, applies := appliesTo(user, clusterRoleBinding.Subjects, "")
// 没有匹配继续查找下一个 ClusterRoleBinding
if !applies {
continue
}
// 到这里说明在 ClusterRoleBinding 中找到了和 user 匹配的 subject, 即这个 ClusterRoleBinding 的 Subject
// 作用于该 user, 因此查找这个 ClusterRoleBinding 引用的 Role 中 定义的所有的 PolicyRules
rules, err := r.GetRoleReferenceRules(clusterRoleBinding.RoleRef, "")
if err != nil {
if !visitor(nil, nil, err) {
return
}
continue
}
// 保存该user 匹配的 binding 和 subject 数据结构
sourceDescriber.binding = clusterRoleBinding
sourceDescriber.subject = &clusterRoleBinding.Subjects[subjectIndex]
// 遍历所有的 Rules
// Note: 时间复杂度O(N)
for i := range rules {
// 将Rule传入visitor函数, 执行相关的业务逻辑, sourceDescriber 实现了String
// 接口, 可以打印 binding 和 subject 的信息
if !visitor(sourceDescriber, &rules[i], nil) {
return
}
}
}
}
// 存在namespace, 收集属于namespace的 RoleBinding
if len(namespace) > 0 {
// 获取该namespace的所有 RoleBinding
if roleBindings, err := r.roleBindingLister.ListRoleBindings(namespace); err != nil {
if !visitor(nil, nil, err) {
return
}
} else {
sourceDescriber := &roleBindingDescriber{}
for _, roleBinding := range roleBindings {
subjectIndex, applies := appliesTo(user, roleBinding.Subjects, namespace)
if !applies {
continue
}
rules, err := r.GetRoleReferenceRules(roleBinding.RoleRef, namespace)
if err != nil {
if !visitor(nil, nil, err) {
return
}
continue
}
sourceDescriber.binding = roleBinding
sourceDescriber.subject = &roleBinding.Subjects[subjectIndex]
for i := range rules {
if !visitor(sourceDescriber, &rules[i], nil) {
return
}
}
}
}
}
}
VisitRulesFor
整体流程为:
- visitor获取所有的ClusterRoleBinding
- 遍历ClusterRoleBinding
- 筛选ClusterRoleBinding和user,筛选条件通过 subject 声明做匹配
- 根据roleRef查找ClusterRoleBinding的Role,然后获取该Role的所有PolicyRules
- 遍历所有的PolicyRules
- 调用visitor传入每个PolicyRule,然后执行特定的业务逻辑
- 当namespace存在时,执行RoleBinding的筛选算法,和ClusterRoleBinding一致
注意:VisitRulesFo
算法的时间复杂度为 O(N^2), N^2 = (ClusterRoleBindings + RoleBindings) * (ClusterRoleBinding Subjects + RoleBinding Subjects)
appliesTo
VisitRulesFor
会调用appliesTo 判断user是否和某个Binding下的Subjects匹配
// Note: O(N)
func appliesTo(user user.Info, bindingSubjects []rbacv1.Subject, namespace string) (int, bool) {
// 遍历某个binding (可以是RoleBinding或者ClusterRoleBinding) 的所有Subject
for i, bindingSubject := range bindingSubjects {
// 判断user是否和subject匹配, 及这个binding是否作用于该user
if appliesToUser(user, bindingSubject, namespace) {
return i, true
}
}
return 0, false
}
appliesTo
遍历所有的Subjects,执行匹配的是appliesToUser
appliesToUser
func appliesToUser(user user.Info, subject rbacv1.Subject, namespace string) bool {
switch subject.Kind {
case rbacv1.UserKind:
return user.GetName() == subject.Name
case rbacv1.GroupKind:
return has(user.GetGroups(), subject.Name)
case rbacv1.ServiceAccountKind:
// default the namespace to namespace we're working in if its available. This allows rolebindings that reference
// SAs in th local namespace to avoid having to qualify them.
saNamespace := namespace
if len(subject.Namespace) > 0 {
saNamespace = subject.Namespace
}
if len(saNamespace) == 0 {
return false
}
// use a more efficient comparison for RBAC checking
return serviceaccount.MatchesUsername(saNamespace, subject.Name, user.GetName())
default:
return false
}
}
ruleAccumulator
在VisitRulesFor
中会调用visitor
函数,ruleAccumulator
是 DefaultRuleResolver
的实现
type ruleAccumulator struct {
rules []rbacv1.PolicyRule
errors []error
}
func (r *ruleAccumulator) visit(source fmt.Stringer, rule *rbacv1.PolicyRule, err error) bool {
if rule != nil {
r.rules = append(r.rules, *rule)
}
if err != nil {
r.errors = append(r.errors, err)
}
return true
}
具体实现也很简单,ruleAccumulator 用两个slice用于保存遍历过程中所有的 PolicyRule
和error
ruleAccumulator
总是返回true
clusterRoleBindingDescriber
visitor
函数需要传入一个 fmt.Stringer
接口,clusterRoleBindingDescriber
是其实现
type roleBindingDescriber struct {
binding *rbacv1.RoleBinding
subject *rbacv1.Subject
}
func (d *roleBindingDescriber) String() string {
return fmt.Sprintf("RoleBinding %q of %s %q to %s",
d.binding.Name+"/"+d.binding.Namespace,
d.binding.RoleRef.Kind,
d.binding.RoleRef.Name,
describeSubject(d.subject, d.binding.Namespace),
)
}
clusterRoleBindingDescriber
数据结构中保存binding
和subject
信息,然后Strig()
方法将其转换为一个string。
describeSubject
根据subject和namespace返回一个string
func describeSubject(s *rbacv1.Subject, bindingNamespace string) string {
switch s.Kind {
case rbacv1.ServiceAccountKind:
// namespace存在, 输出sa绑定的namespace
if len(s.Namespace) > 0 {
return fmt.Sprintf("%s %q", s.Kind, s.Name+"/"+s.Namespace)
}
// namespace不存在, 输出sa默认绑定的namespace
return fmt.Sprintf("%s %q", s.Kind, s.Name+"/"+bindingNamespace)
default:
// 其他kind情况
return fmt.Sprintf("%s %q", s.Kind, s.Name)
}
}
RulesFor 实现
func (r *DefaultRuleResolver) RulesFor(user user.Info, namespace string) ([]rbacv1.PolicyRule, error) {
visitor := &ruleAccumulator{}
r.VisitRulesFor(user, namespace, visitor.visit)
return visitor.rules, utilerrors.NewAggregate(visitor.errors)
}
分析了前面VisitRulesFor
后,RulesFor
实现其实很简单,创建一个ruleAccumulator
对象,然后调用VisitRulesFor
,之后返回所有的PolicyRule
,不过error使用了 NewAggregate
做了一下聚合。
总结
-
AuthorizationRuleResolver
接口定义了解析一个user
和相关的PolicyRule
的基本操作方法 -
DefaultRuleResolver
是AuthorizationRuleResolver
的默认实现,其中比较重要的是VisitRulesFor
的实现,可以看做是一个通用的RoleBinding
和ClusterRolebinding
遍历算法。 -
VisitRulesFor
要求传入一个visitor()
函数,这种设计可以让算法和业务逻辑分离 -
VisitRulesFor
的实现复杂度是O(N^2)的 -
RulesFor
实现了将user所有可检测的PolicyRule
收集的功能,不过如果发生错误,则PolicyRule
是不完整的