Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add role/clusterrole to describe.go #46326

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
40 changes: 40 additions & 0 deletions pkg/apis/rbac/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,38 @@ func SubjectsStrings(subjects []Subject) ([]string, []string, []string, []string
return users, groups, sas, others
}

func (r PolicyRule) String() string {
return "PolicyRule" + r.CompactString()
}

// CompactString exposes a compact string representation for use in escalation error messages
func (r PolicyRule) CompactString() string {
formatStringParts := []string{}
formatArgs := []interface{}{}
if len(r.Resources) > 0 {
formatStringParts = append(formatStringParts, "Resources:%q")
formatArgs = append(formatArgs, r.Resources)
}
if len(r.NonResourceURLs) > 0 {
formatStringParts = append(formatStringParts, "NonResourceURLs:%q")
formatArgs = append(formatArgs, r.NonResourceURLs)
}
if len(r.ResourceNames) > 0 {
formatStringParts = append(formatStringParts, "ResourceNames:%q")
formatArgs = append(formatArgs, r.ResourceNames)
}
if len(r.APIGroups) > 0 {
formatStringParts = append(formatStringParts, "APIGroups:%q")
formatArgs = append(formatArgs, r.APIGroups)
}
if len(r.Verbs) > 0 {
formatStringParts = append(formatStringParts, "Verbs:%q")
formatArgs = append(formatArgs, r.Verbs)
}
formatString := "{" + strings.Join(formatStringParts, ", ") + "}"
return fmt.Sprintf(formatString, formatArgs...)
}

// +k8s:deepcopy-gen=false
// PolicyRuleBuilder let's us attach methods. A no-no for API types.
// We use it to construct rules in code. It's more compact than trying to write them
Expand Down Expand Up @@ -341,3 +373,11 @@ func (r *RoleBindingBuilder) Binding() (RoleBinding, error) {

return r.RoleBinding, nil
}

type SortableRuleSlice []PolicyRule

func (s SortableRuleSlice) Len() int { return len(s) }
func (s SortableRuleSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s SortableRuleSlice) Less(i, j int) bool {
return strings.Compare(s[i].String(), s[j].String()) < 0
}
1 change: 1 addition & 0 deletions pkg/printers/internalversion/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ go_library(
"//pkg/controller/deployment/util:go_default_library",
"//pkg/fieldpath:go_default_library",
"//pkg/printers:go_default_library",
"//pkg/registry/rbac/validation:go_default_library",
"//pkg/util/node:go_default_library",
"//pkg/util/slice:go_default_library",
"//vendor/github.com/fatih/camelcase:go_default_library",
Expand Down
98 changes: 98 additions & 0 deletions pkg/printers/internalversion/describe.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ import (
deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util"
"k8s.io/kubernetes/pkg/fieldpath"
"k8s.io/kubernetes/pkg/printers"
"k8s.io/kubernetes/pkg/registry/rbac/validation"
"k8s.io/kubernetes/pkg/util/slice"
)

Expand Down Expand Up @@ -144,6 +145,8 @@ func describerMap(c clientset.Interface) map[schema.GroupKind]printers.Describer
certificates.Kind("CertificateSigningRequest"): &CertificateSigningRequestDescriber{c},
storage.Kind("StorageClass"): &StorageClassDescriber{c},
policy.Kind("PodDisruptionBudget"): &PodDisruptionBudgetDescriber{c},
rbac.Kind("Role"): &RoleDescriber{c},
rbac.Kind("ClusterRole"): &ClusterRoleDescriber{c},
rbac.Kind("RoleBinding"): &RoleBindingDescriber{c},
rbac.Kind("ClusterRoleBinding"): &ClusterRoleBindingDescriber{c},
}
Expand Down Expand Up @@ -2114,6 +2117,101 @@ func describeServiceAccount(serviceAccount *api.ServiceAccount, tokens []api.Sec
})
}

// RoleDescriber generates information about a node.
type RoleDescriber struct {
clientset.Interface
}

func (d *RoleDescriber) Describe(namespace, name string, describerSettings printers.DescriberSettings) (string, error) {
role, err := d.Rbac().Roles(namespace).Get(name, metav1.GetOptions{})
if err != nil {
return "", err
}

breakdownRules := []rbac.PolicyRule{}
for _, rule := range role.Rules {
breakdownRules = append(breakdownRules, validation.BreakdownRule(rule)...)
}

compactRules, err := validation.CompactRules(breakdownRules)
if err != nil {
return "", err
}
sort.Stable(rbac.SortableRuleSlice(compactRules))

return tabbedString(func(out io.Writer) error {
w := NewPrefixWriter(out)
w.Write(LEVEL_0, "Name:\t%s\n", role.Name)
printLabelsMultiline(w, "Labels", role.Labels)
printAnnotationsMultiline(w, "Annotations", role.Annotations)

w.Write(LEVEL_0, "PolicyRule:\n")
w.Write(LEVEL_1, "Resources\tNon-Resource URLs\tResource Names\tVerbs\n")
w.Write(LEVEL_1, "---------\t-----------------\t--------------\t-----\n")
for _, r := range compactRules {
w.Write(LEVEL_1, "%s\t%v\t%v\t%v\n", combineResourceGroup(r.Resources, r.APIGroups), r.NonResourceURLs, r.ResourceNames, r.Verbs)
}

return nil
})
}

// ClusterRoleDescriber generates information about a node.
type ClusterRoleDescriber struct {
clientset.Interface
}

func (d *ClusterRoleDescriber) Describe(namespace, name string, describerSettings printers.DescriberSettings) (string, error) {
role, err := d.Rbac().ClusterRoles().Get(name, metav1.GetOptions{})
if err != nil {
return "", err
}

breakdownRules := []rbac.PolicyRule{}
for _, rule := range role.Rules {
breakdownRules = append(breakdownRules, validation.BreakdownRule(rule)...)
}

compactRules, err := validation.CompactRules(breakdownRules)
if err != nil {
return "", err
}
sort.Stable(rbac.SortableRuleSlice(compactRules))

return tabbedString(func(out io.Writer) error {
w := NewPrefixWriter(out)
w.Write(LEVEL_0, "Name:\t%s\n", role.Name)
printLabelsMultiline(w, "Labels", role.Labels)
printAnnotationsMultiline(w, "Annotations", role.Annotations)

w.Write(LEVEL_0, "PolicyRule:\n")
w.Write(LEVEL_1, "Resources\tNon-Resource URLs\tResource Names\tVerbs\n")
w.Write(LEVEL_1, "---------\t-----------------\t--------------\t-----\n")
for _, r := range compactRules {
w.Write(LEVEL_1, "%s\t%v\t%v\t%v\n", combineResourceGroup(r.Resources, r.APIGroups), r.NonResourceURLs, r.ResourceNames, r.Verbs)
}

return nil
})
}

func combineResourceGroup(resource, group []string) string {
if len(resource) == 0 {
return ""
}
parts := strings.SplitN(resource[0], "/", 2)
combine := parts[0]

if len(group) > 0 && group[0] != "" {
combine = combine + "." + group[0]
}

if len(parts) == 2 {
combine = combine + "/" + parts[1]
}
return combine
}

// RoleBindingDescriber generates information about a node.
type RoleBindingDescriber struct {
clientset.Interface
Expand Down
6 changes: 6 additions & 0 deletions pkg/registry/rbac/validation/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,17 @@ load(
go_test(
name = "go_default_test",
srcs = [
"policy_compact_test.go",
"policy_comparator_test.go",
"rule_test.go",
],
library = ":go_default_library",
tags = ["automanaged"],
deps = [
"//pkg/api:go_default_library",
"//pkg/apis/rbac:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/diff:go_default_library",
"//vendor/k8s.io/apiserver/pkg/authentication/user:go_default_library",
],
Expand All @@ -27,14 +30,17 @@ go_test(
go_library(
name = "go_default_library",
srcs = [
"policy_compact.go",
"policy_comparator.go",
"rule.go",
],
tags = ["automanaged"],
deps = [
"//pkg/api:go_default_library",
"//pkg/apis/rbac:go_default_library",
"//vendor/github.com/golang/glog:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/api/errors:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/errors:go_default_library",
"//vendor/k8s.io/apiserver/pkg/authentication/serviceaccount:go_default_library",
"//vendor/k8s.io/apiserver/pkg/authentication/user:go_default_library",
Expand Down
89 changes: 89 additions & 0 deletions pkg/registry/rbac/validation/policy_compact.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
Copyright 2017 The Kubernetes 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 validation

import (
"fmt"
"reflect"

"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/apis/rbac"
)

// CompactRules combines rules that contain a single APIGroup/Resource, differ only by verb, and contain no other attributes.
// this is a fast check, and works well with the decomposed "missing rules" list from a Covers check.
func CompactRules(rules []rbac.PolicyRule) ([]rbac.PolicyRule, error) {
compacted := make([]rbac.PolicyRule, 0, len(rules))

simpleRules := map[schema.GroupResource]*rbac.PolicyRule{}
for _, rule := range rules {
if resource, isSimple := isSimpleResourceRule(&rule); isSimple {
if existingRule, ok := simpleRules[resource]; ok {
// Add the new verbs to the existing simple resource rule
if existingRule.Verbs == nil {
existingRule.Verbs = []string{}
}
existingRule.Verbs = append(existingRule.Verbs, rule.Verbs...)
} else {
// Copy the rule to accumulate matching simple resource rules into
objCopy, err := api.Scheme.DeepCopy(rule)
if err != nil {
// Unit tests ensure this should not ever happen
return nil, err
}
ruleCopy, ok := objCopy.(rbac.PolicyRule)
if !ok {
// Unit tests ensure this should not ever happen
return nil, fmt.Errorf("expected rbac.PolicyRule, got %#v", objCopy)
}
simpleRules[resource] = &ruleCopy
}
} else {
compacted = append(compacted, rule)
}
}

// Once we've consolidated the simple resource rules, add them to the compacted list
for _, simpleRule := range simpleRules {
compacted = append(compacted, *simpleRule)
}

return compacted, nil
}

// isSimpleResourceRule returns true if the given rule contains verbs, a single resource, a single API group, and no other values
func isSimpleResourceRule(rule *rbac.PolicyRule) (schema.GroupResource, bool) {
resource := schema.GroupResource{}

// If we have "complex" rule attributes, return early without allocations or expensive comparisons
if len(rule.ResourceNames) > 0 || len(rule.NonResourceURLs) > 0 {
return resource, false
}
// If we have multiple api groups or resources, return early
if len(rule.APIGroups) != 1 || len(rule.Resources) != 1 {
return resource, false
}

// Test if this rule only contains APIGroups/Resources/Verbs
simpleRule := &rbac.PolicyRule{APIGroups: rule.APIGroups, Resources: rule.Resources, Verbs: rule.Verbs}
if !reflect.DeepEqual(simpleRule, rule) {
return resource, false
}
resource = schema.GroupResource{Group: rule.APIGroups[0], Resource: rule.Resources[0]}
return resource, true
}