forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
compact_rules.go
64 lines (54 loc) · 2.4 KB
/
compact_rules.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 rulevalidation
import (
"reflect"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/sets"
authorizationapi "github.com/openshift/origin/pkg/authorization/apis/authorization"
)
// 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 []authorizationapi.PolicyRule) ([]authorizationapi.PolicyRule, error) {
compacted := make([]authorizationapi.PolicyRule, 0, len(rules))
simpleRules := map[schema.GroupResource]*authorizationapi.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 = sets.NewString()
}
existingRule.Verbs.Insert(rule.Verbs.List()...)
} else {
// Copy the rule to accumulate matching simple resource rules into
ruleCopy := rule.DeepCopy()
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 *authorizationapi.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 || rule.AttributeRestrictions != nil {
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 := &authorizationapi.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.List()[0]}
return resource, true
}