forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
remove_from_project.go
237 lines (194 loc) · 7.42 KB
/
remove_from_project.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
package policy
import (
"fmt"
"io"
"sort"
"github.com/spf13/cobra"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/sets"
rbacv1client "k8s.io/client-go/kubernetes/typed/rbac/v1"
rbacv1helpers "k8s.io/kubernetes/pkg/apis/rbac/v1"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
authorizationutil "github.com/openshift/origin/pkg/authorization/util"
)
const (
RemoveGroupRecommendedName = "remove-group"
RemoveUserRecommendedName = "remove-user"
)
type RemoveFromProjectOptions struct {
BindingNamespace string
Client rbacv1client.RoleBindingsGetter
Groups []string
Users []string
DryRun bool
PrintObject func(runtime.Object) error
Output string
Out io.Writer
}
// NewCmdRemoveGroupFromProject implements the OpenShift cli remove-group command
func NewCmdRemoveGroupFromProject(name, fullName string, f kcmdutil.Factory, out io.Writer) *cobra.Command {
options := &RemoveFromProjectOptions{Out: out}
cmd := &cobra.Command{
Use: name + " GROUP [GROUP ...]",
Short: "Remove group from the current project",
Long: `Remove group from the current project`,
Run: func(cmd *cobra.Command, args []string) {
if err := options.Complete(f, cmd, args, &options.Groups, "group"); err != nil {
kcmdutil.CheckErr(kcmdutil.UsageErrorf(cmd, err.Error()))
}
if err := options.Validate(f, cmd, args); err != nil {
kcmdutil.CheckErr(kcmdutil.UsageErrorf(cmd, err.Error()))
}
if err := options.Run(); err != nil {
kcmdutil.CheckErr(err)
}
},
}
kcmdutil.AddOutputFlags(cmd)
kcmdutil.AddDryRunFlag(cmd)
return cmd
}
// NewCmdRemoveUserFromProject implements the OpenShift cli remove-user command
func NewCmdRemoveUserFromProject(name, fullName string, f kcmdutil.Factory, out io.Writer) *cobra.Command {
options := &RemoveFromProjectOptions{Out: out}
cmd := &cobra.Command{
Use: name + " USER [USER ...]",
Short: "Remove user from the current project",
Long: `Remove user from the current project`,
Run: func(cmd *cobra.Command, args []string) {
if err := options.Complete(f, cmd, args, &options.Users, "user"); err != nil {
kcmdutil.CheckErr(kcmdutil.UsageErrorf(cmd, err.Error()))
}
if err := options.Validate(f, cmd, args); err != nil {
kcmdutil.CheckErr(kcmdutil.UsageErrorf(cmd, err.Error()))
}
if err := options.Run(); err != nil {
kcmdutil.CheckErr(err)
}
},
}
kcmdutil.AddPrinterFlags(cmd)
kcmdutil.AddDryRunFlag(cmd)
return cmd
}
func (o *RemoveFromProjectOptions) Complete(f kcmdutil.Factory, cmd *cobra.Command, args []string, target *[]string, targetName string) error {
if len(args) < 1 {
return fmt.Errorf("you must specify at least one argument: <%s> [%s]...", targetName, targetName)
}
o.Output = kcmdutil.GetFlagString(cmd, "output")
o.DryRun = kcmdutil.GetFlagBool(cmd, "dry-run")
*target = append(*target, args...)
clientConfig, err := f.ToRESTConfig()
if err != nil {
return err
}
o.Client, err = rbacv1client.NewForConfig(clientConfig)
if err != nil {
return err
}
if o.BindingNamespace, _, err = f.ToRawKubeConfigLoader().Namespace(); err != nil {
return err
}
o.PrintObject = func(obj runtime.Object) error {
return kcmdutil.PrintObject(cmd, obj, o.Out)
}
return nil
}
func (o *RemoveFromProjectOptions) Validate(f kcmdutil.Factory, cmd *cobra.Command, args []string) error {
if len(o.Output) > 0 && o.Output != "yaml" && o.Output != "json" {
return fmt.Errorf("invalid output format %q, only yaml|json supported", o.Output)
}
return nil
}
func (o *RemoveFromProjectOptions) Run() error {
roleBindings, err := o.Client.RoleBindings(o.BindingNamespace).List(metav1.ListOptions{})
if err != nil {
return err
}
// maintain David's hack from #1973 (see #1975, #1976 and https://bugzilla.redhat.com/show_bug.cgi?id=1215969)
sort.Sort(sort.Reverse(roleBindingSorter(roleBindings.Items)))
usersRemoved := sets.String{}
groupsRemoved := sets.String{}
sasRemoved := sets.String{}
othersRemoved := sets.String{}
dryRunText := ""
if o.DryRun {
dryRunText = " (dry run)"
}
updatedBindings := &rbacv1.RoleBindingList{
TypeMeta: metav1.TypeMeta{
Kind: "List",
APIVersion: "v1",
},
ListMeta: metav1.ListMeta{},
}
subjectsToRemove := authorizationutil.BuildRBACSubjects(o.Users, o.Groups)
for _, currBinding := range roleBindings.Items {
originalSubjects := make([]rbacv1.Subject, len(currBinding.Subjects))
copy(originalSubjects, currBinding.Subjects)
oldUsers, oldGroups, oldSAs, oldOthers := rbacv1helpers.SubjectsStrings(originalSubjects)
oldUsersSet, oldGroupsSet, oldSAsSet, oldOtherSet := sets.NewString(oldUsers...), sets.NewString(oldGroups...), sets.NewString(oldSAs...), sets.NewString(oldOthers...)
currBinding.Subjects, _ = removeSubjects(currBinding.Subjects, subjectsToRemove)
newUsers, newGroups, newSAs, newOthers := rbacv1helpers.SubjectsStrings(currBinding.Subjects)
newUsersSet, newGroupsSet, newSAsSet, newOtherSet := sets.NewString(newUsers...), sets.NewString(newGroups...), sets.NewString(newSAs...), sets.NewString(newOthers...)
if len(currBinding.Subjects) == len(originalSubjects) {
continue
}
if len(o.Output) > 0 {
updatedBindings.Items = append(updatedBindings.Items, currBinding)
continue
}
if !o.DryRun {
if len(currBinding.Subjects) > 0 {
_, err = o.Client.RoleBindings(o.BindingNamespace).Update(&currBinding)
} else {
err = o.Client.RoleBindings(o.BindingNamespace).Delete(currBinding.Name, &metav1.DeleteOptions{})
}
if err != nil {
return err
}
}
roleDisplayName := fmt.Sprintf("%s/%s", currBinding.Namespace, currBinding.RoleRef.Name)
if currBinding.RoleRef.Kind == "ClusterRole" {
roleDisplayName = currBinding.RoleRef.Name
}
if diff := oldUsersSet.Difference(newUsersSet); len(diff) != 0 {
fmt.Fprintf(o.Out, "Removing %s from users %v in project %s%s.\n", roleDisplayName, diff.List(), o.BindingNamespace, dryRunText)
usersRemoved.Insert(diff.List()...)
}
if diff := oldGroupsSet.Difference(newGroupsSet); len(diff) != 0 {
fmt.Fprintf(o.Out, "Removing %s from groups %v in project %s%s.\n", roleDisplayName, diff.List(), o.BindingNamespace, dryRunText)
groupsRemoved.Insert(diff.List()...)
}
if diff := oldSAsSet.Difference(newSAsSet); len(diff) != 0 {
fmt.Fprintf(o.Out, "Removing %s from serviceaccounts %v in project %s%s.\n", roleDisplayName, diff.List(), o.BindingNamespace, dryRunText)
sasRemoved.Insert(diff.List()...)
}
if diff := oldOtherSet.Difference(newOtherSet); len(diff) != 0 {
fmt.Fprintf(o.Out, "Removing %s from subjects %v in project %s%s.\n", roleDisplayName, diff.List(), o.BindingNamespace, dryRunText)
othersRemoved.Insert(diff.List()...)
}
}
if len(o.Output) > 0 {
return o.PrintObject(updatedBindings)
}
if diff := sets.NewString(o.Users...).Difference(usersRemoved); len(diff) != 0 {
fmt.Fprintf(o.Out, "Users %v were not bound to roles in project %s%s.\n", diff.List(), o.BindingNamespace, dryRunText)
}
if diff := sets.NewString(o.Groups...).Difference(groupsRemoved); len(diff) != 0 {
fmt.Fprintf(o.Out, "Groups %v were not bound to roles in project %s%s.\n", diff.List(), o.BindingNamespace, dryRunText)
}
return nil
}
type roleBindingSorter []rbacv1.RoleBinding
func (s roleBindingSorter) Len() int {
return len(s)
}
func (s roleBindingSorter) Less(i, j int) bool {
return s[i].Name < s[j].Name
}
func (s roleBindingSorter) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}