Debian Codegraph @

auth/rbac/reconciliation/reconcile_rolebindings.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/errors"
25 "k8s.io/apimachinery/pkg/runtime"
26 "k8s.io/apimachinery/pkg/types"
27 )
28
29 type RoleBindingModifier interface {
30 Get(namespace, name string) (RoleBinding, error)
31 Delete(namespace, name string, uid types.UID) error
32 Create(RoleBinding) (RoleBinding, error)
33 Update(RoleBinding) (RoleBinding, error)
34 }
35
36 type RoleBinding interface {
37 GetObject() runtime.Object
38 GetNamespace() string
39 GetName() string
40 GetUID() types.UID
41 GetLabels() map[string]string
42 SetLabels(map[string]string)
43 GetAnnotations() map[string]string
44 SetAnnotations(map[string]string)
45 GetRoleRef() rbacv1.RoleRef
46 GetSubjects() []rbacv1.Subject
47 SetSubjects([]rbacv1.Subject)
48 DeepCopyRoleBinding() RoleBinding
49 }
50
51 // ReconcileRoleBindingOptions holds options for running a role binding reconciliation
52 type ReconcileRoleBindingOptions struct {
53 // RoleBinding is the expected rolebinding that will be reconciled
54 RoleBinding RoleBinding
55 // Confirm indicates writes should be performed. When false, results are returned as a dry-run.
56 Confirm bool
57 // RemoveExtraSubjects indicates reconciliation should remove extra subjects from an existing role binding
58 RemoveExtraSubjects bool
59 // Client is used to look up existing rolebindings, and create/update the rolebinding when Confirm=true
60 Client RoleBindingModifier
61 }
62
63 // ReconcileClusterRoleBindingResult holds the result of a reconciliation operation.
64 type ReconcileClusterRoleBindingResult struct {
65 // RoleBinding is the reconciled rolebinding from the reconciliation operation.
66 // If the reconcile was performed as a dry-run, or the existing rolebinding was protected, the reconciled rolebinding is not persisted.
67 RoleBinding RoleBinding
68
69 // MissingSubjects contains expected subjects that were missing from the currently persisted rolebinding
70 MissingSubjects []rbacv1.Subject
71 // ExtraSubjects contains extra subjects the currently persisted rolebinding had
72 ExtraSubjects []rbacv1.Subject
73
74 // Operation is the API operation required to reconcile.
75 // If no reconciliation was needed, it is set to ReconcileNone.
76 // If options.Confirm == false, the reconcile was in dry-run mode, so the operation was not performed.
77 // If result.Protected == true, the rolebinding opted out of reconciliation, so the operation was not performed.
78 // Otherwise, the operation was performed.
79 Operation ReconcileOperation
80 // Protected indicates an existing role prevented reconciliation
81 Protected bool
82 }
83
84 func (o *ReconcileRoleBindingOptions) Run() (*ReconcileClusterRoleBindingResult, error) {
85 return o.run(0)
86 }
87
88 func (o *ReconcileRoleBindingOptions) run(attempts int) (*ReconcileClusterRoleBindingResult, error) {
89 // This keeps us from retrying forever if a rolebinding keeps appearing and disappearing as we reconcile.
90 // Conflict errors on update are handled at a higher level.
91 if attempts > 3 {
92 return nil, fmt.Errorf("exceeded maximum attempts")
93 }
94
95 var result *ReconcileClusterRoleBindingResult
96
97 existingBinding, err := o.Client.Get(o.RoleBinding.GetNamespace(), o.RoleBinding.GetName())
98 switch {
99 case errors.IsNotFound(err):
100 result = &ReconcileClusterRoleBindingResult{
101 RoleBinding: o.RoleBinding,
102 MissingSubjects: o.RoleBinding.GetSubjects(),
103 Operation: ReconcileCreate,
104 }
105
106 case err != nil:
107 return nil, err
108
109 default:
110 result, err = computeReconciledRoleBinding(existingBinding, o.RoleBinding, o.RemoveExtraSubjects)
111 if err != nil {
112 return nil, err
113 }
114 }
115
116 // If reconcile-protected, short-circuit
117 if result.Protected {
118 return result, nil
119 }
120 // If we're in dry-run mode, short-circuit
121 if !o.Confirm {
122 return result, nil
123 }
124
125 switch result.Operation {
126 case ReconcileRecreate:
127 // Try deleting
128 err := o.Client.Delete(existingBinding.GetNamespace(), existingBinding.GetName(), existingBinding.GetUID())
129 switch {
130 case err == nil, errors.IsNotFound(err):
131 // object no longer exists, as desired
132 case errors.IsConflict(err):
133 // delete failed because our UID precondition conflicted
134 // this could mean another object exists with a different UID, re-run
135 return o.run(attempts + 1)
136 default:
137 // return other errors
138 return nil, err
139 }
140 // continue to create
141 fallthrough
142 case ReconcileCreate:
143 created, err := o.Client.Create(result.RoleBinding)
144 // If created since we started this reconcile, re-run
145 if errors.IsAlreadyExists(err) {
146 return o.run(attempts + 1)
147 }
148 if err != nil {
149 return nil, err
150 }
151 result.RoleBinding = created
152
153 case ReconcileUpdate:
154 updated, err := o.Client.Update(result.RoleBinding)
155 // If deleted since we started this reconcile, re-run
156 if errors.IsNotFound(err) {
157 return o.run(attempts + 1)
158 }
159 if err != nil {
160 return nil, err
161 }
162 result.RoleBinding = updated
163
164 case ReconcileNone:
165 // no-op
166
167 default:
168 return nil, fmt.Errorf("invalid operation: %v", result.Operation)
169 }
170
171 return result, nil
172 }
173
174 // computeReconciledRoleBinding returns the rolebinding that must be created and/or updated to make the
175 // existing rolebinding's subjects, roleref, labels, and annotations match the expected rolebinding
176 func computeReconciledRoleBinding(existing, expected RoleBinding, removeExtraSubjects bool) (*ReconcileClusterRoleBindingResult, error) {
177 result := &ReconcileClusterRoleBindingResult{Operation: ReconcileNone}
178
179 result.Protected = (existing.GetAnnotations()[rbacv1.AutoUpdateAnnotationKey] == "false")
180
181 // Reset the binding completely if the roleRef is different
182 if expected.GetRoleRef() != existing.GetRoleRef() {
183 result.RoleBinding = expected
184 result.Operation = ReconcileRecreate
185 return result, nil
186 }
187
188 // Start with a copy of the existing object
189 result.RoleBinding = existing.DeepCopyRoleBinding()
190
191 // Merge expected annotations and labels
192 result.RoleBinding.SetAnnotations(merge(expected.GetAnnotations(), result.RoleBinding.GetAnnotations()))
193 if !reflect.DeepEqual(result.RoleBinding.GetAnnotations(), existing.GetAnnotations()) {
194 result.Operation = ReconcileUpdate
195 }
196 result.RoleBinding.SetLabels(merge(expected.GetLabels(), result.RoleBinding.GetLabels()))
197 if !reflect.DeepEqual(result.RoleBinding.GetLabels(), existing.GetLabels()) {
198 result.Operation = ReconcileUpdate
199 }
200
201 // Compute extra and missing subjects
202 result.MissingSubjects, result.ExtraSubjects = diffSubjectLists(expected.GetSubjects(), existing.GetSubjects())
203
204 switch {
205 case !removeExtraSubjects && len(result.MissingSubjects) > 0:
206 // add missing subjects in the union case
207 result.RoleBinding.SetSubjects(append(result.RoleBinding.GetSubjects(), result.MissingSubjects...))
208 result.Operation = ReconcileUpdate
209
210 case removeExtraSubjects && (len(result.MissingSubjects) > 0 || len(result.ExtraSubjects) > 0):
211 // stomp to expected subjects in the non-union case
212 result.RoleBinding.SetSubjects(expected.GetSubjects())
213 result.Operation = ReconcileUpdate
214 }
215
216 return result, nil
217 }
218
219 func contains(list []rbacv1.Subject, item rbacv1.Subject) bool {
220 for _, listItem := range list {
221 if listItem == item {
222 return true
223 }
224 }
225 return false
226 }
227
228 // diffSubjectLists returns lists containing the items unique to each provided list:
229 //
230 // list1Only = list1 - list2
231 // list2Only = list2 - list1
232 //
233 // if both returned lists are empty, the provided lists are equal
234 func diffSubjectLists(list1 []rbacv1.Subject, list2 []rbacv1.Subject) (list1Only []rbacv1.Subject, list2Only []rbacv1.Subject) {
235 for _, list1Item := range list1 {
236 if !contains(list2, list1Item) {
237 if !contains(list1Only, list1Item) {
238 list1Only = append(list1Only, list1Item)
239 }
240 }
241 }
242 for _, list2Item := range list2 {
243 if !contains(list1, list2Item) {
244 if !contains(list2Only, list2Item) {
245 list2Only = append(list2Only, list2Item)
246 }
247 }
248 }
249 return
250 }