forked from openshift/oc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cani.go
271 lines (227 loc) · 7.16 KB
/
cani.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
package cani
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
"reflect"
"text/tabwriter"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/cli-runtime/pkg/printers"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/scheme"
authorizationv1 "github.com/openshift/api/authorization/v1"
authorizationv1typedclient "github.com/openshift/client-go/authorization/clientset/versioned/typed/authorization/v1"
"github.com/openshift/oc/pkg/cli/admin/policy"
)
const (
CanIRecommendedName = "can-i"
tabWriterMinWidth = 0
tabWriterWidth = 7
tabWriterPadding = 3
tabWriterPadChar = ' '
tabWriterFlags = 0
)
type CanIOptions struct {
PrintFlags *genericclioptions.PrintFlags
ToPrinter func(string) (printers.ResourcePrinter, error)
NoHeaders bool
AllNamespaces bool
ListAll bool
Quiet bool
IgnoreScopes bool
User string
Groups []string
Scopes []string
Namespace string
AuthClient authorizationv1typedclient.AuthorizationV1Interface
Args []string
Verb string
Resource schema.GroupVersionResource
ResourceName string
genericclioptions.IOStreams
}
func NewCanIOptions(streams genericclioptions.IOStreams) *CanIOptions {
return &CanIOptions{
PrintFlags: genericclioptions.NewPrintFlags("").WithTypeSetter(scheme.Scheme),
IOStreams: streams,
}
}
func NewCmdCanI(name, fullName string, f kcmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
o := NewCanIOptions(streams)
cmd := &cobra.Command{
Use: name + " VERB RESOURCE [NAME]",
Short: "Check whether an action is allowed",
Long: "Check whether an action is allowed",
Run: func(cmd *cobra.Command, args []string) {
kcmdutil.CheckErr(o.Complete(cmd, f, args))
kcmdutil.CheckErr(o.Validate())
kcmdutil.CheckErr(o.Run())
},
Deprecated: "use 'oc auth can-i'",
}
cmd.Flags().BoolVarP(&o.AllNamespaces, "all-namespaces", "A", o.AllNamespaces, "If true, check the specified action in all namespaces.")
cmd.Flags().BoolVar(&o.ListAll, "list", o.ListAll, "If true, list all the actions you can perform in a namespace, cannot be specified with --all-namespaces or a VERB RESOURCE")
cmd.Flags().BoolVarP(&o.Quiet, "quiet", "q", o.Quiet, "If true, suppress output and just return the exit code.")
cmd.Flags().BoolVar(&o.IgnoreScopes, "ignore-scopes", o.IgnoreScopes, "If true, disregard any scopes present on this request and evaluate considering full permissions.")
cmd.Flags().StringSliceVar(&o.Scopes, "scopes", o.Scopes, "Check the specified action using these scopes. By default, the scopes on the current token will be used.")
cmd.Flags().StringVar(&o.User, "user", o.User, "Check the specified action using this user instead of your user.")
cmd.Flags().StringSliceVar(&o.Groups, "groups", o.Groups, "Check the specified action using these groups instead of your groups.")
cmd.Flags().BoolVar(&o.NoHeaders, "no-headers", o.NoHeaders, "When using the default output format, don't print headers (default print headers).")
o.PrintFlags.AddFlags(cmd)
return cmd
}
func (o *CanIOptions) Complete(cmd *cobra.Command, f kcmdutil.Factory, args []string) error {
o.Args = args
if o.ListAll && o.AllNamespaces {
return errors.New("--list and --all-namespaces are mutually exclusive")
}
if o.IgnoreScopes && len(o.Scopes) > 0 {
return errors.New("--scopes and --ignore-scopes are mutually exclusive")
}
switch len(args) {
case 3:
o.ResourceName = args[2]
fallthrough
case 2:
if o.ListAll {
return errors.New("VERB RESOURCE and --list are mutually exclusive")
}
restMapper, err := f.ToRESTMapper()
if err != nil {
return err
}
o.Verb = args[0]
o.Resource = policy.ResourceFor(restMapper, args[1], o.ErrOut)
default:
if !o.ListAll {
return errors.New("you must specify two or three arguments: verb, resource, and optional resourceName")
}
}
clientConfig, err := f.ToRESTConfig()
if err != nil {
return err
}
o.AuthClient, err = authorizationv1typedclient.NewForConfig(clientConfig)
if err != nil {
return err
}
o.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {
o.PrintFlags.NamePrintFlags.Operation = operation
return o.PrintFlags.ToPrinter()
}
o.Namespace = metav1.NamespaceAll
if !o.AllNamespaces {
o.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()
if err != nil {
return err
}
}
if o.Quiet {
o.Out = ioutil.Discard
}
return nil
}
func (o *CanIOptions) Validate() error {
if reflect.DeepEqual(o.Args, []string{"educate", "dolphins"}) {
return fmt.Errorf("%s", "Only liggitt can educate dolphins.")
}
return nil
}
func (o *CanIOptions) Run() error {
if o.ListAll {
return o.listAllPermissions()
}
sar := &authorizationv1.SubjectAccessReview{
Action: authorizationv1.Action{
Namespace: o.Namespace,
Verb: o.Verb,
Group: o.Resource.Group,
Resource: o.Resource.Resource,
ResourceName: o.ResourceName,
},
User: o.User,
GroupsSlice: o.Groups,
}
if o.IgnoreScopes {
sar.Scopes = []string{}
}
if len(o.Scopes) > 0 {
sar.Scopes = o.Scopes
}
response, err := o.AuthClient.SubjectAccessReviews().Create(sar)
if err != nil {
return err
}
if response.Allowed {
fmt.Fprintln(o.Out, "yes")
} else {
fmt.Fprint(o.Out, "no")
if len(response.EvaluationError) > 0 {
fmt.Fprintf(o.Out, " - %v", response.EvaluationError)
}
fmt.Fprintln(o.Out)
}
// honor existing exit code convention
if !response.Allowed && o.Quiet {
os.Exit(2)
}
return nil
}
func (o *CanIOptions) listAllPermissions() error {
var rulesReviewObj runtime.Object
var rulesReviewResult []authorizationv1.PolicyRule
if len(o.User) == 0 && len(o.Groups) == 0 {
rulesReview := &authorizationv1.SelfSubjectRulesReview{}
if len(o.Scopes) > 0 {
rulesReview.Spec.Scopes = o.Scopes
}
whatCanIDo, err := o.AuthClient.SelfSubjectRulesReviews(o.Namespace).Create(rulesReview)
if err != nil {
return err
}
rulesReviewResult = whatCanIDo.Status.Rules
rulesReviewObj = whatCanIDo
} else {
rulesReview := &authorizationv1.SubjectRulesReview{
Spec: authorizationv1.SubjectRulesReviewSpec{
User: o.User,
Groups: o.Groups,
Scopes: o.Scopes,
},
}
whatCanYouDo, err := o.AuthClient.SubjectRulesReviews(o.Namespace).Create(rulesReview)
if err != nil {
return err
}
rulesReviewResult = whatCanYouDo.Status.Rules
rulesReviewObj = whatCanYouDo
}
successOutput := bytes.NewBuffer([]byte{})
w := tabwriter.NewWriter(successOutput, tabWriterMinWidth, tabWriterWidth, tabWriterPadding, tabWriterPadChar, tabWriterFlags)
fmt.Fprintln(w)
// print columns
if !o.NoHeaders {
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t\n", "VERBS", "NON-RESOURCE URLS", "RESOURCE NAMES", "API GROUPS", "RESOURCES")
}
for _, rule := range rulesReviewResult {
fmt.Fprintf(w, "%v\t%v\t%v\t%v\t%v\n",
rule.Verbs,
rule.NonResourceURLsSlice,
rule.ResourceNames,
rule.APIGroups,
rule.Resources,
)
}
w.Flush()
p, err := o.ToPrinter(successOutput.String())
if err != nil {
return err
}
return p.PrintObj(rulesReviewObj, o.Out)
}