Debian Codegraph @

auth/rbac/reconciliation/reconcile_role.go

raw symbols SCIP
1 /*
2 Copyright 2017 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package reconciliation
18
19 import (
20 "fmt"
21 "reflect"
22
23 rbacv1 "k8s.io/api/rbac/v1"
24 "k8s.io/apimachinery/pkg/api/equality"
25 "k8s.io/apimachinery/pkg/api/errors"
26 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
27 "k8s.io/apimachinery/pkg/runtime"
28 "k8s.io/component-helpers/auth/rbac/validation"
29 )
30
31 type ReconcileOperation string
32
33 var (
34 ReconcileCreate ReconcileOperation = "create"
35 ReconcileUpdate ReconcileOperation = "update"
36 ReconcileRecreate ReconcileOperation = "recreate"
37 ReconcileNone ReconcileOperation = "none"
38 )
39
40 type RuleOwnerModifier interface {
41 Get(namespace, name string) (RuleOwner, error)
42 Create(RuleOwner) (RuleOwner, error)
43 Update(RuleOwner) (RuleOwner, error)
44 }
45
46 type RuleOwner interface {
47 GetObject() runtime.Object
48 GetNamespace() string
49 GetName() string
50 GetLabels() map[string]string
51 SetLabels(map[string]string)
52 GetAnnotations() map[string]string
53 SetAnnotations(map[string]string)
54 GetRules() []rbacv1.PolicyRule
55 SetRules([]rbacv1.PolicyRule)
56 GetAggregationRule() *rbacv1.AggregationRule
57 SetAggregationRule(*rbacv1.AggregationRule)
58 DeepCopyRuleOwner() RuleOwner
59 }
60
61 type ReconcileRoleOptions struct {
62 // Role is the expected role that will be reconciled
63 Role RuleOwner
64 // Confirm indicates writes should be performed. When false, results are returned as a dry-run.
65 Confirm bool
66 // RemoveExtraPermissions indicates reconciliation should remove extra permissions from an existing role
67 RemoveExtraPermissions bool
68 // Client is used to look up existing roles, and create/update the role when Confirm=true
69 Client RuleOwnerModifier
70 }
71
72 type ReconcileClusterRoleResult struct {
73 // Role is the reconciled role from the reconciliation operation.
74 // If the reconcile was performed as a dry-run, or the existing role was protected, the reconciled role is not persisted.
75 Role RuleOwner
76
77 // MissingRules contains expected rules that were missing from the currently persisted role
78 MissingRules []rbacv1.PolicyRule
79 // ExtraRules contains extra permissions the currently persisted role had
80 ExtraRules []rbacv1.PolicyRule
81
82 // MissingAggregationRuleSelectors contains expected selectors that were missing from the currently persisted role
83 MissingAggregationRuleSelectors []metav1.LabelSelector
84 // ExtraAggregationRuleSelectors contains extra selectors the currently persisted role had
85 ExtraAggregationRuleSelectors []metav1.LabelSelector
86
87 // Operation is the API operation required to reconcile.
88 // If no reconciliation was needed, it is set to ReconcileNone.
89 // If options.Confirm == false, the reconcile was in dry-run mode, so the operation was not performed.
90 // If result.Protected == true, the role opted out of reconciliation, so the operation was not performed.
91 // Otherwise, the operation was performed.
92 Operation ReconcileOperation
93 // Protected indicates an existing role prevented reconciliation
94 Protected bool
95 }
96
97 func (o *ReconcileRoleOptions) Run() (*ReconcileClusterRoleResult, error) {
98 return o.run(0)
99 }
100
101 func (o *ReconcileRoleOptions) run(attempts int) (*ReconcileClusterRoleResult, error) {
102 // This keeps us from retrying forever if a role keeps appearing and disappearing as we reconcile.
103 // Conflict errors on update are handled at a higher level.
104 if attempts > 2 {
105 return nil, fmt.Errorf("exceeded maximum attempts")
106 }
107
108 var result *ReconcileClusterRoleResult
109
110 existing, err := o.Client.Get(o.Role.GetNamespace(), o.Role.GetName())
111 switch {
112 case errors.IsNotFound(err):
113 aggregationRule := o.Role.GetAggregationRule()
114 if aggregationRule == nil {
115 aggregationRule = &rbacv1.AggregationRule{}
116 }
117 result = &ReconcileClusterRoleResult{
118 Role: o.Role,
119 MissingRules: o.Role.GetRules(),
120 MissingAggregationRuleSelectors: aggregationRule.ClusterRoleSelectors,
121 Operation: ReconcileCreate,
122 }
123
124 case err != nil:
125 return nil, err
126
127 default:
128 result, err = computeReconciledRole(existing, o.Role, o.RemoveExtraPermissions)
129 if err != nil {
130 return nil, err
131 }
132 }
133
134 // If reconcile-protected, short-circuit
135 if result.Protected {
136 return result, nil
137 }
138 // If we're in dry-run mode, short-circuit
139 if !o.Confirm {
140 return result, nil
141 }
142
143 switch result.Operation {
144 case ReconcileCreate:
145 created, err := o.Client.Create(result.Role)
146 // If created since we started this reconcile, re-run
147 if errors.IsAlreadyExists(err) {
148 return o.run(attempts + 1)
149 }
150 if err != nil {
151 return nil, err
152 }
153 result.Role = created
154
155 case ReconcileUpdate:
156 updated, err := o.Client.Update(result.Role)
157 // If deleted since we started this reconcile, re-run
158 if errors.IsNotFound(err) {
159 return o.run(attempts + 1)
160 }
161 if err != nil {
162 return nil, err
163 }
164 result.Role = updated
165
166 case ReconcileNone:
167 // no-op
168
169 default:
170 return nil, fmt.Errorf("invalid operation: %v", result.Operation)
171 }
172
173 return result, nil
174 }
175
176 // computeReconciledRole returns the role that must be created and/or updated to make the
177 // existing role's permissions match the expected role's permissions
178 func computeReconciledRole(existing, expected RuleOwner, removeExtraPermissions bool) (*ReconcileClusterRoleResult, error) {
179 result := &ReconcileClusterRoleResult{Operation: ReconcileNone}
180
181 result.Protected = (existing.GetAnnotations()[rbacv1.AutoUpdateAnnotationKey] == "false")
182
183 // Start with a copy of the existing object
184 result.Role = existing.DeepCopyRuleOwner()
185
186 // Merge expected annotations and labels
187 result.Role.SetAnnotations(merge(expected.GetAnnotations(), result.Role.GetAnnotations()))
188 if !reflect.DeepEqual(result.Role.GetAnnotations(), existing.GetAnnotations()) {
189 result.Operation = ReconcileUpdate
190 }
191 result.Role.SetLabels(merge(expected.GetLabels(), result.Role.GetLabels()))
192 if !reflect.DeepEqual(result.Role.GetLabels(), existing.GetLabels()) {
193 result.Operation = ReconcileUpdate
194 }
195
196 // Compute extra and missing rules
197 // Don't compute extra permissions if expected and existing roles are both aggregated
198 if expected.GetAggregationRule() == nil || existing.GetAggregationRule() == nil {
199 _, result.ExtraRules = validation.Covers(expected.GetRules(), existing.GetRules())
200 }
201 _, result.MissingRules = validation.Covers(existing.GetRules(), expected.GetRules())
202
203 switch {
204 case !removeExtraPermissions && len(result.MissingRules) > 0:
205 // add missing rules in the union case
206 result.Role.SetRules(append(result.Role.GetRules(), result.MissingRules...))
207 result.Operation = ReconcileUpdate
208
209 case removeExtraPermissions && (len(result.MissingRules) > 0 || len(result.ExtraRules) > 0):
210 // stomp to expected rules in the non-union case
211 result.Role.SetRules(expected.GetRules())
212 result.Operation = ReconcileUpdate
213 }
214
215 // Compute extra and missing rules
216 _, result.ExtraAggregationRuleSelectors = aggregationRuleCovers(expected.GetAggregationRule(), existing.GetAggregationRule())
217 _, result.MissingAggregationRuleSelectors = aggregationRuleCovers(existing.GetAggregationRule(), expected.GetAggregationRule())
218
219 switch {
220 case expected.GetAggregationRule() == nil && existing.GetAggregationRule() != nil:
221 // we didn't expect this to be an aggregated role at all, remove the existing aggregation
222 result.Role.SetAggregationRule(nil)
223 result.Operation = ReconcileUpdate
224
225 case !removeExtraPermissions && len(result.MissingAggregationRuleSelectors) > 0:
226 // add missing rules in the union case
227 aggregationRule := result.Role.GetAggregationRule()
228 if aggregationRule == nil {
229 aggregationRule = &rbacv1.AggregationRule{}
230 }
231 aggregationRule.ClusterRoleSelectors = append(aggregationRule.ClusterRoleSelectors, result.MissingAggregationRuleSelectors...)
232 result.Role.SetAggregationRule(aggregationRule)
233 result.Operation = ReconcileUpdate
234
235 case removeExtraPermissions && (len(result.MissingAggregationRuleSelectors) > 0 || len(result.ExtraAggregationRuleSelectors) > 0):
236 result.Role.SetAggregationRule(expected.GetAggregationRule())
237 result.Operation = ReconcileUpdate
238 }
239
240 return result, nil
241 }
242
243 // merge combines the given maps with the later annotations having higher precedence
244 func merge(maps ...map[string]string) map[string]string {
245 var output map[string]string = nil
246 for _, m := range maps {
247 if m != nil && output == nil {
248 output = map[string]string{}
249 }
250 for k, v := range m {
251 output[k] = v
252 }
253 }
254 return output
255 }
256
257 // aggregationRuleCovers determines whether or not the ownerSelectors cover the servantSelectors in terms of semantically
258 // equal label selectors.
259 // It returns whether or not the ownerSelectors cover and a list of the rules that the ownerSelectors do not cover.
260 func aggregationRuleCovers(ownerRule, servantRule *rbacv1.AggregationRule) (bool, []metav1.LabelSelector) {
261 switch {
262 case ownerRule == nil && servantRule == nil:
263 return true, []metav1.LabelSelector{}
264 case ownerRule == nil && servantRule != nil:
265 return false, servantRule.ClusterRoleSelectors
266 case ownerRule != nil && servantRule == nil:
267 return true, []metav1.LabelSelector{}
268
269 }
270
271 ownerSelectors := ownerRule.ClusterRoleSelectors
272 servantSelectors := servantRule.ClusterRoleSelectors
273 uncoveredSelectors := []metav1.LabelSelector{}
274
275 for _, servantSelector := range servantSelectors {
276 covered := false
277 for _, ownerSelector := range ownerSelectors {
278 if equality.Semantic.DeepEqual(ownerSelector, servantSelector) {
279 covered = true
280 break
281 }
282 }
283 if !covered {
284 uncoveredSelectors = append(uncoveredSelectors, servantSelector)
285 }
286 }
287
288 return (len(uncoveredSelectors) == 0), uncoveredSelectors
289 }