-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
reconcile_clusterrolebindings.go
306 lines (248 loc) · 10.7 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
package policy
import (
"errors"
"fmt"
"io"
"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"
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/util/clientcmd"
uservalidation "github.com/openshift/origin/pkg/user/api/validation"
)
// ReconcileClusterRoleBindingsRecommendedName is the recommended command name
const ReconcileClusterRoleBindingsRecommendedName = "reconcile-cluster-role-bindings"
type ReconcileClusterRoleBindingsOptions struct {
Confirmed bool
Union bool
ExcludeSubjects []kapi.ObjectReference
Out io.Writer
Output string
RoleBindingClient client.ClusterRoleBindingInterface
}
const (
reconcileBindingsLong = `
Replace 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 = ` # Display the cluster role bindings that would be modified
$ %[1]s
# 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 io.Writer) *cobra.Command {
o := &ReconcileClusterRoleBindingsOptions{
Out: out,
Union: true,
}
excludeUsers := []string{}
excludeGroups := []string{}
cmd := &cobra.Command{
Use: name,
Short: "Replace 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 {
if len(args) != 0 {
return kcmdutil.UsageError(cmd, "no arguments are allowed")
}
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)
return nil
}
func (o *ReconcileClusterRoleBindingsOptions) Validate() error {
if o.RoleBindingClient == nil {
return errors.New("a role binding client is required")
}
if o.Output != "yaml" && o.Output != "json" && o.Output != "" {
return fmt.Errorf("unknown output specified: %s", o.Output)
}
return nil
}
// ReconcileClusterRoleBindingsOptions contains all the necessary functionality for the OpenShift cli reconcile-cluster-role-bindings command
func (o *ReconcileClusterRoleBindingsOptions) RunReconcileClusterRoleBindings(cmd *cobra.Command, f *clientcmd.Factory) error {
changedClusterRoleBindings, err := o.ChangedClusterRoleBindings()
if err != nil {
return err
}
if len(changedClusterRoleBindings) == 0 {
return nil
}
if (len(o.Output) != 0) && !o.Confirmed {
list := &kapi.List{}
for _, item := range changedClusterRoleBindings {
list.Items = append(list.Items, item)
}
if err := f.Factory.PrintObject(cmd, list, o.Out); err != nil {
return err
}
}
if o.Confirmed {
return o.ReplaceChangedRoleBindings(changedClusterRoleBindings)
}
return nil
}
// ChangedClusterRoleBindings returns the role bindings that must be created and/or updated to
// match the recommended bootstrap policy
func (o *ReconcileClusterRoleBindingsOptions) ChangedClusterRoleBindings() ([]*authorizationapi.ClusterRoleBinding, error) {
changedRoleBindings := []*authorizationapi.ClusterRoleBinding{}
bootstrapClusterRoleBindings := bootstrappolicy.GetBootstrapClusterRoleBindings()
for i := range bootstrapClusterRoleBindings {
expectedClusterRoleBinding := &bootstrapClusterRoleBindings[i]
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)
}
}
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 {
for i := range changedRoleBindings {
roleBinding, err := o.RoleBindingClient.Get(changedRoleBindings[i].Name)
if err != nil && !kapierrors.IsNotFound(err) {
return err
}
if kapierrors.IsNotFound(err) {
createdRoleBinding, err := o.RoleBindingClient.Create(changedRoleBindings[i])
if err != nil {
return err
}
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 {
return err
}
createdRoleBinding, err := o.RoleBindingClient.Create(changedRoleBindings[i])
if err != nil {
return err
}
fmt.Fprintf(o.Out, "clusterrolebinding/%s\n", createdRoleBinding.Name)
continue
}
roleBinding.Subjects = changedRoleBindings[i].Subjects
updatedRoleBinding, err := o.RoleBindingClient.Update(roleBinding)
if err != nil {
return err
}
fmt.Fprintf(o.Out, "clusterrolebinding/%s\n", updatedRoleBinding.Name)
}
return nil
}
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
}