-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
reconcile_clusterrolebindings.go
379 lines (313 loc) · 13.2 KB
/
reconcile_clusterrolebindings.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
package policy
import (
"errors"
"fmt"
"io"
"strings"
"github.com/spf13/cobra"
kapi "k8s.io/kubernetes/pkg/api"
kapierrors "k8s.io/kubernetes/pkg/api/errors"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
kutilerrors "k8s.io/kubernetes/pkg/util/errors"
"k8s.io/kubernetes/pkg/util/sets"
authorizationapi "github.com/openshift/origin/pkg/authorization/api"
"github.com/openshift/origin/pkg/client"
"github.com/openshift/origin/pkg/cmd/server/bootstrappolicy"
"github.com/openshift/origin/pkg/cmd/templates"
cmdutil "github.com/openshift/origin/pkg/cmd/util"
"github.com/openshift/origin/pkg/cmd/util/clientcmd"
uservalidation "github.com/openshift/origin/pkg/user/api/validation"
)
// ReconcileClusterRoleBindingsRecommendedName is the recommended command name
const ReconcileClusterRoleBindingsRecommendedName = "reconcile-cluster-role-bindings"
// ReconcileClusterRoleBindingsOptions contains all the necessary functionality for the OpenShift cli reconcile-cluster-role-bindings command
type ReconcileClusterRoleBindingsOptions struct {
// RolesToReconcile says which roles should have their default bindings reconciled.
// An empty or nil slice means reconcile all of them.
RolesToReconcile []string
Confirmed bool
Union bool
ExcludeSubjects []kapi.ObjectReference
Out io.Writer
Err io.Writer
Output string
RoleBindingClient client.ClusterRoleBindingInterface
}
var (
reconcileBindingsLong = templates.LongDesc(`
Update cluster role bindings to match the recommended bootstrap policy
This command will inspect the cluster role bindings against the recommended bootstrap policy.
Any cluster role binding that does not match will be replaced by the recommended bootstrap role binding.
This command will not remove any additional cluster role bindings.
You can see which recommended cluster role bindings have changed by choosing an output type.`)
reconcileBindingsExample = templates.Examples(`
# Display the names of cluster role bindings that would be modified
%[1]s -o name
# Display the cluster role bindings that would be modified, removing any extra subjects
%[1]s --additive-only=false
# Update cluster role bindings that don't match the current defaults
%[1]s --confirm
# Update cluster role bindings that don't match the current defaults, avoid adding roles to the system:authenticated group
%[1]s --confirm --exclude-groups=system:authenticated
# Update cluster role bindings that don't match the current defaults, removing any extra subjects from the binding
%[1]s --confirm --additive-only=false`)
)
// NewCmdReconcileClusterRoleBindings implements the OpenShift cli reconcile-cluster-role-bindings command
func NewCmdReconcileClusterRoleBindings(name, fullName string, f *clientcmd.Factory, out, err io.Writer) *cobra.Command {
o := &ReconcileClusterRoleBindingsOptions{
Out: out,
Err: err,
Union: true,
}
excludeUsers := []string{}
excludeGroups := []string{}
cmd := &cobra.Command{
Use: name + " [ClusterRoleName]...",
Short: "Update cluster role bindings to match the recommended bootstrap policy",
Long: reconcileBindingsLong,
Example: fmt.Sprintf(reconcileBindingsExample, fullName),
Run: func(cmd *cobra.Command, args []string) {
if err := o.Complete(cmd, f, args, excludeUsers, excludeGroups); err != nil {
kcmdutil.CheckErr(err)
}
if err := o.Validate(); err != nil {
kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
}
if err := o.RunReconcileClusterRoleBindings(cmd, f); err != nil {
kcmdutil.CheckErr(err)
}
},
}
cmd.Flags().BoolVar(&o.Confirmed, "confirm", o.Confirmed, "Specify that cluster role bindings should be modified. Defaults to false, displaying what would be replaced but not actually replacing anything.")
cmd.Flags().BoolVar(&o.Union, "additive-only", o.Union, "Preserves extra subjects in cluster role bindings.")
cmd.Flags().StringSliceVar(&excludeUsers, "exclude-users", excludeUsers, "Do not add cluster role bindings for these user names.")
cmd.Flags().StringSliceVar(&excludeGroups, "exclude-groups", excludeGroups, "Do not add cluster role bindings for these group names.")
kcmdutil.AddPrinterFlags(cmd)
cmd.Flags().Lookup("output").DefValue = "yaml"
cmd.Flags().Lookup("output").Value.Set("yaml")
return cmd
}
func (o *ReconcileClusterRoleBindingsOptions) Complete(cmd *cobra.Command, f *clientcmd.Factory, args []string, excludeUsers, excludeGroups []string) error {
oclient, _, err := f.Clients()
if err != nil {
return err
}
o.RoleBindingClient = oclient.ClusterRoleBindings()
o.Output = kcmdutil.GetFlagString(cmd, "output")
o.ExcludeSubjects = authorizationapi.BuildSubjects(excludeUsers, excludeGroups, uservalidation.ValidateUserName, uservalidation.ValidateGroupName)
mapper, _ := f.Object(false)
for _, resourceString := range args {
resource, name, err := cmdutil.ResolveResource(authorizationapi.Resource("clusterroles"), resourceString, mapper)
if err != nil {
return err
}
if resource != authorizationapi.Resource("clusterroles") {
return fmt.Errorf("%v is not a valid resource type for this command", resource)
}
if len(name) == 0 {
return fmt.Errorf("%s did not contain a name", resourceString)
}
o.RolesToReconcile = append(o.RolesToReconcile, name)
}
return nil
}
func (o *ReconcileClusterRoleBindingsOptions) Validate() error {
if o.RoleBindingClient == nil {
return errors.New("a role binding client is required")
}
return nil
}
func (o *ReconcileClusterRoleBindingsOptions) RunReconcileClusterRoleBindings(cmd *cobra.Command, f *clientcmd.Factory) error {
changedClusterRoleBindings, fetchErr := o.ChangedClusterRoleBindings()
if fetchErr != nil && !IsClusterRoleBindingLookupError(fetchErr) {
// we got an error that isn't due to a partial match, so we can't continue
return fetchErr
}
if len(changedClusterRoleBindings) == 0 {
return fetchErr
}
errs := []error{}
if fetchErr != nil {
errs = append(errs, fetchErr)
}
if (len(o.Output) != 0) && !o.Confirmed {
list := &kapi.List{}
for _, item := range changedClusterRoleBindings {
list.Items = append(list.Items, item)
}
mapper, _ := f.Object(false)
fn := cmdutil.VersionedPrintObject(f.PrintObject, cmd, mapper, o.Out)
if err := fn(list); err != nil {
errs = append(errs, err)
return kutilerrors.NewAggregate(errs)
}
}
if o.Confirmed {
if err := o.ReplaceChangedRoleBindings(changedClusterRoleBindings); err != nil {
errs = append(errs, err)
return kutilerrors.NewAggregate(errs)
}
}
return fetchErr
}
// ChangedClusterRoleBindings returns the role bindings that must be created and/or updated to
// match the recommended bootstrap policy. If roles to reconcile are provided, but not all are
// found, all partial results are returned.
func (o *ReconcileClusterRoleBindingsOptions) ChangedClusterRoleBindings() ([]*authorizationapi.ClusterRoleBinding, error) {
changedRoleBindings := []*authorizationapi.ClusterRoleBinding{}
rolesToReconcile := sets.NewString(o.RolesToReconcile...)
rolesNotFound := sets.NewString(o.RolesToReconcile...)
bootstrapClusterRoleBindings := bootstrappolicy.GetBootstrapClusterRoleBindings()
for i := range bootstrapClusterRoleBindings {
expectedClusterRoleBinding := &bootstrapClusterRoleBindings[i]
if (len(rolesToReconcile) > 0) && !rolesToReconcile.Has(expectedClusterRoleBinding.RoleRef.Name) {
continue
}
rolesNotFound.Delete(expectedClusterRoleBinding.RoleRef.Name)
actualClusterRoleBinding, err := o.RoleBindingClient.Get(expectedClusterRoleBinding.Name)
if kapierrors.IsNotFound(err) {
// Remove excluded subjects from the new role binding
expectedClusterRoleBinding.Subjects, _ = DiffObjectReferenceLists(expectedClusterRoleBinding.Subjects, o.ExcludeSubjects)
changedRoleBindings = append(changedRoleBindings, expectedClusterRoleBinding)
continue
}
if err != nil {
return nil, err
}
// Copy any existing labels/annotations, so the displayed update is correct
// This assumes bootstrap role bindings will not set any labels/annotations
// These aren't actually used during update; the latest labels/annotations are pulled from the existing object again
expectedClusterRoleBinding.Labels = actualClusterRoleBinding.Labels
expectedClusterRoleBinding.Annotations = actualClusterRoleBinding.Annotations
if updatedClusterRoleBinding, needsUpdating := computeUpdatedBinding(*expectedClusterRoleBinding, *actualClusterRoleBinding, o.ExcludeSubjects, o.Union); needsUpdating {
changedRoleBindings = append(changedRoleBindings, updatedClusterRoleBinding)
}
}
if len(rolesNotFound) != 0 {
// return the known changes and the error so that a caller can decide if he wants a partial update
return changedRoleBindings, NewClusterRoleBindingLookupError(rolesNotFound.List())
}
return changedRoleBindings, nil
}
// ReplaceChangedRoleBindings will reconcile all the changed system role bindings back to the recommended bootstrap policy
func (o *ReconcileClusterRoleBindingsOptions) ReplaceChangedRoleBindings(changedRoleBindings []*authorizationapi.ClusterRoleBinding) error {
errs := []error{}
for i := range changedRoleBindings {
roleBinding, err := o.RoleBindingClient.Get(changedRoleBindings[i].Name)
if err != nil && !kapierrors.IsNotFound(err) {
errs = append(errs, err)
continue
}
if kapierrors.IsNotFound(err) {
createdRoleBinding, err := o.RoleBindingClient.Create(changedRoleBindings[i])
if err != nil {
errs = append(errs, err)
continue
}
fmt.Fprintf(o.Out, "clusterrolebinding/%s\n", createdRoleBinding.Name)
continue
}
// RoleRef is immutable, to reset this, we have to delete/recreate
if !kapi.Semantic.DeepEqual(roleBinding.RoleRef, changedRoleBindings[i].RoleRef) {
roleBinding.RoleRef = changedRoleBindings[i].RoleRef
roleBinding.Subjects = changedRoleBindings[i].Subjects
// TODO: for extra credit, determine whether the right to delete/create this rolebinding for the current user came from this rolebinding before deleting it
err := o.RoleBindingClient.Delete(roleBinding.Name)
if err != nil {
errs = append(errs, err)
continue
}
createdRoleBinding, err := o.RoleBindingClient.Create(changedRoleBindings[i])
if err != nil {
errs = append(errs, err)
continue
}
fmt.Fprintf(o.Out, "clusterrolebinding/%s\n", createdRoleBinding.Name)
continue
}
roleBinding.Subjects = changedRoleBindings[i].Subjects
updatedRoleBinding, err := o.RoleBindingClient.Update(roleBinding)
if err != nil {
errs = append(errs, err)
continue
}
fmt.Fprintf(o.Out, "clusterrolebinding/%s\n", updatedRoleBinding.Name)
}
return kutilerrors.NewAggregate(errs)
}
func computeUpdatedBinding(expected authorizationapi.ClusterRoleBinding, actual authorizationapi.ClusterRoleBinding, excludeSubjects []kapi.ObjectReference, union bool) (*authorizationapi.ClusterRoleBinding, bool) {
needsUpdating := false
// Always reset the roleref if it is different
if !kapi.Semantic.DeepEqual(expected.RoleRef, actual.RoleRef) {
needsUpdating = true
}
// compute the list of subjects we should not add roles for (existing subjects in the exclude list should be preserved)
doNotAddSubjects, _ := DiffObjectReferenceLists(excludeSubjects, actual.Subjects)
// remove any excluded subjects that do not exist from our expected subject list (so we don't add them)
expectedSubjects, _ := DiffObjectReferenceLists(expected.Subjects, doNotAddSubjects)
missingSubjects, extraSubjects := DiffObjectReferenceLists(expectedSubjects, actual.Subjects)
// Always add missing expected subjects
if len(missingSubjects) > 0 {
needsUpdating = true
}
// extra subjects only require a change if we're not unioning
if len(extraSubjects) > 0 && !union {
needsUpdating = true
}
if !needsUpdating {
return nil, false
}
updated := expected
updated.Subjects = expectedSubjects
if union {
updated.Subjects = append(updated.Subjects, extraSubjects...)
}
return &updated, true
}
func contains(list []kapi.ObjectReference, item kapi.ObjectReference) bool {
for _, listItem := range list {
if kapi.Semantic.DeepEqual(listItem, item) {
return true
}
}
return false
}
// DiffObjectReferenceLists returns lists containing the items unique to each provided list:
// list1Only = list1 - list2
// list2Only = list2 - list1
// if both returned lists are empty, the provided lists are equal
func DiffObjectReferenceLists(list1 []kapi.ObjectReference, list2 []kapi.ObjectReference) (list1Only []kapi.ObjectReference, list2Only []kapi.ObjectReference) {
for _, list1Item := range list1 {
if !contains(list2, list1Item) {
if !contains(list1Only, list1Item) {
list1Only = append(list1Only, list1Item)
}
}
}
for _, list2Item := range list2 {
if !contains(list1, list2Item) {
if !contains(list2Only, list2Item) {
list2Only = append(list2Only, list2Item)
}
}
}
return
}
func NewClusterRoleBindingLookupError(rolesNotFound []string) error {
return &clusterRoleBindingLookupError{
rolesNotFound: rolesNotFound,
}
}
type clusterRoleBindingLookupError struct {
rolesNotFound []string
}
func (e *clusterRoleBindingLookupError) Error() string {
return fmt.Sprintf("did not find requested cluster roles: %s", strings.Join(e.rolesNotFound, ", "))
}
func IsClusterRoleBindingLookupError(err error) bool {
if err == nil {
return false
}
_, ok := err.(*clusterRoleBindingLookupError)
return ok
}