forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
overwrite_bootstrappolicy.go
333 lines (296 loc) · 13 KB
/
overwrite_bootstrappolicy.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
package admin
import (
"errors"
"fmt"
"io"
"reflect"
"github.com/spf13/cobra"
kapierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
kerrors "k8s.io/apimachinery/pkg/util/errors"
apirequest "k8s.io/apiserver/pkg/endpoints/request"
kapi "k8s.io/kubernetes/pkg/api"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/resource"
authorizationapi "github.com/openshift/origin/pkg/authorization/apis/authorization"
configapilatest "github.com/openshift/origin/pkg/cmd/server/api/latest"
originrest "github.com/openshift/origin/pkg/cmd/server/origin/rest"
"github.com/openshift/origin/pkg/oc/cli/describe"
templateapi "github.com/openshift/origin/pkg/template/apis/template"
"github.com/openshift/origin/pkg/util/restoptions"
"github.com/openshift/origin/pkg/authorization/rulevalidation"
clusterpolicyregistry "github.com/openshift/origin/pkg/cmd/server/admin/legacyetcd/clusterpolicy"
clusterpolicyetcd "github.com/openshift/origin/pkg/cmd/server/admin/legacyetcd/clusterpolicy/etcd"
clusterpolicybindingregistry "github.com/openshift/origin/pkg/cmd/server/admin/legacyetcd/clusterpolicybinding"
clusterpolicybindingetcd "github.com/openshift/origin/pkg/cmd/server/admin/legacyetcd/clusterpolicybinding/etcd"
"github.com/openshift/origin/pkg/cmd/server/admin/legacyetcd/clusterrole"
clusterrolestorage "github.com/openshift/origin/pkg/cmd/server/admin/legacyetcd/clusterrole/proxy"
"github.com/openshift/origin/pkg/cmd/server/admin/legacyetcd/clusterrolebinding"
clusterrolebindingstorage "github.com/openshift/origin/pkg/cmd/server/admin/legacyetcd/clusterrolebinding/proxy"
policyregistry "github.com/openshift/origin/pkg/cmd/server/admin/legacyetcd/policy"
policyetcd "github.com/openshift/origin/pkg/cmd/server/admin/legacyetcd/policy/etcd"
policybindingregistry "github.com/openshift/origin/pkg/cmd/server/admin/legacyetcd/policybinding"
policybindingetcd "github.com/openshift/origin/pkg/cmd/server/admin/legacyetcd/policybinding/etcd"
"github.com/openshift/origin/pkg/cmd/server/admin/legacyetcd/role"
rolestorage "github.com/openshift/origin/pkg/cmd/server/admin/legacyetcd/role/policybased"
"github.com/openshift/origin/pkg/cmd/server/admin/legacyetcd/rolebinding"
rolebindingstorage "github.com/openshift/origin/pkg/cmd/server/admin/legacyetcd/rolebinding/policybased"
"github.com/openshift/origin/pkg/cmd/util/clientcmd"
)
const OverwriteBootstrapPolicyCommandName = "overwrite-policy"
type OverwriteBootstrapPolicyOptions struct {
File string
MasterConfigFile string
Force bool
Out io.Writer
CreateBootstrapPolicyCommand string
}
func NewCommandOverwriteBootstrapPolicy(commandName string, fullName string, createBootstrapPolicyCommand string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
options := &OverwriteBootstrapPolicyOptions{Out: out}
options.CreateBootstrapPolicyCommand = createBootstrapPolicyCommand
cmd := &cobra.Command{
Use: commandName,
Short: "Reset the policy to the default values",
Run: func(cmd *cobra.Command, args []string) {
kcmdutil.CheckErr(options.Complete(f))
if err := options.Validate(args); err != nil {
kcmdutil.CheckErr(kcmdutil.UsageErrorf(cmd, err.Error()))
}
kcmdutil.CheckErr(options.OverwriteBootstrapPolicy())
},
Deprecated: fmt.Sprintf("will not work against 3.7 servers"),
}
flags := cmd.Flags()
flags.BoolVarP(&options.Force, "force", "f", false, "You must confirm you really want to reset your policy. This will delete any custom settings you may have.")
flags.StringVar(&options.File, "filename", "", "The policy template file containing roles and bindings. One can be created with '"+createBootstrapPolicyCommand+"'.")
flags.StringVar(&options.MasterConfigFile, "master-config", "openshift.local.config/master/master-config.yaml", "Location of the master configuration file to run from in order to connect to etcd and directly modify the policy.")
// autocompletion hints
cmd.MarkFlagFilename("filename")
cmd.MarkFlagFilename("master-config", "yaml", "yml")
return cmd
}
func (o OverwriteBootstrapPolicyOptions) Validate(args []string) error {
if len(args) != 0 {
return errors.New("no arguments are supported")
}
if len(o.File) == 0 {
return errors.New("filename must be provided")
}
if len(o.MasterConfigFile) == 0 {
return errors.New("master-config must be provided")
}
return nil
}
func (o OverwriteBootstrapPolicyOptions) Complete(f *clientcmd.Factory) error {
kclient, err := f.ClientSet()
if err != nil {
return err
}
return clientcmd.LegacyPolicyResourceGate(kclient.Discovery())
}
func (o OverwriteBootstrapPolicyOptions) OverwriteBootstrapPolicy() error {
masterConfig, err := configapilatest.ReadAndResolveMasterConfig(o.MasterConfigFile)
if err != nil {
return err
}
// this brings in etcd server client libraries
optsGetter, err := originrest.StorageOptions(*masterConfig)
if err != nil {
return err
}
return OverwriteBootstrapPolicy(optsGetter, o.File, o.CreateBootstrapPolicyCommand, o.Force, o.Out)
}
type authorizationStorage struct {
Role role.Storage
RoleBinding rolebinding.Storage
ClusterRole clusterrole.Storage
ClusterRoleBinding clusterrolebinding.Storage
}
func newLiveRuleResolver(policyRegistry policyregistry.Registry, policyBindingRegistry policybindingregistry.Registry, clusterPolicyRegistry clusterpolicyregistry.Registry, clusterBindingRegistry clusterpolicybindingregistry.Registry) rulevalidation.AuthorizationRuleResolver {
return rulevalidation.NewDefaultRuleResolver(
&policyregistry.ReadOnlyPolicyListerNamespacer{
Registry: policyRegistry,
},
&policybindingregistry.ReadOnlyPolicyBindingListerNamespacer{
Registry: policyBindingRegistry,
},
&clusterpolicyregistry.ReadOnlyClusterPolicyClientShim{
ReadOnlyClusterPolicy: clusterpolicyregistry.ReadOnlyClusterPolicy{Registry: clusterPolicyRegistry},
},
&clusterpolicybindingregistry.ReadOnlyClusterPolicyBindingClientShim{
ReadOnlyClusterPolicyBinding: clusterpolicybindingregistry.ReadOnlyClusterPolicyBinding{Registry: clusterBindingRegistry},
},
)
}
func getAuthorizationStorage(optsGetter restoptions.Getter) (*authorizationStorage, error) {
policyStorage, err := policyetcd.NewREST(optsGetter)
if err != nil {
return nil, err
}
policyBindingStorage, err := policybindingetcd.NewREST(optsGetter)
if err != nil {
return nil, err
}
clusterPolicyStorage, err := clusterpolicyetcd.NewREST(optsGetter)
if err != nil {
return nil, err
}
clusterPolicyBindingStorage, err := clusterpolicybindingetcd.NewREST(optsGetter)
if err != nil {
return nil, err
}
policyRegistry := policyregistry.NewRegistry(policyStorage)
policyBindingRegistry := policybindingregistry.NewRegistry(policyBindingStorage)
clusterPolicyRegistry := clusterpolicyregistry.NewRegistry(clusterPolicyStorage)
clusterPolicyBindingRegistry := clusterpolicybindingregistry.NewRegistry(clusterPolicyBindingStorage)
liveRuleResolver := newLiveRuleResolver(policyRegistry, policyBindingRegistry, clusterPolicyRegistry, clusterPolicyBindingRegistry)
return &authorizationStorage{
Role: rolestorage.NewVirtualStorage(policyRegistry, liveRuleResolver, nil),
RoleBinding: rolebindingstorage.NewVirtualStorage(policyBindingRegistry, liveRuleResolver, nil),
ClusterRole: clusterrolestorage.NewClusterRoleStorage(clusterPolicyRegistry, liveRuleResolver, nil),
ClusterRoleBinding: clusterrolebindingstorage.NewClusterRoleBindingStorage(clusterPolicyBindingRegistry, liveRuleResolver, nil),
}, nil
}
func OverwriteBootstrapPolicy(optsGetter restoptions.Getter, policyFile, createBootstrapPolicyCommand string, change bool, out io.Writer) error {
if !change {
fmt.Fprintf(out, "Performing a dry run of policy overwrite:\n\n")
}
mapper := kapi.Registry.RESTMapper()
typer := kapi.Scheme
clientMapper := resource.ClientMapperFunc(func(mapping *meta.RESTMapping) (resource.RESTClient, error) {
return nil, nil
})
r := resource.NewBuilder(mapper, resource.SimpleCategoryExpander{}, typer, clientMapper, kapi.Codecs.UniversalDecoder()).
FilenameParam(false, &resource.FilenameOptions{Recursive: false, Filenames: []string{policyFile}}).
Flatten().
Do()
if r.Err() != nil {
return r.Err()
}
authStorage, err := getAuthorizationStorage(optsGetter)
if err != nil {
return err
}
return r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
template, ok := info.Object.(*templateapi.Template)
if !ok {
return errors.New("policy must be contained in a template. One can be created with '" + createBootstrapPolicyCommand + "'.")
}
runtime.DecodeList(template.Objects, kapi.Codecs.UniversalDecoder())
// For each object, we attempt the following to maximize our ability to persist the desired objects, while minimizing etcd write thrashing:
// 1. Create the object (no-ops if the object already exists)
// 2. If the object already exists, attempt to update the object (no-ops if an identical object is already persisted)
// 3. If we encounter any error updating, delete and recreate
errs := []error{}
for _, item := range template.Objects {
switch t := item.(type) {
case *authorizationapi.Role:
ctx := apirequest.WithNamespace(apirequest.NewContext(), t.Namespace)
if change {
// Attempt to create
_, err := authStorage.Role.CreateRoleWithEscalation(ctx, t)
// Unconditional replace if it already exists
if kapierrors.IsAlreadyExists(err) {
_, _, err = authStorage.Role.UpdateRoleWithEscalation(ctx, t)
}
// Delete and recreate as a last resort
if err != nil {
authStorage.Role.Delete(ctx, t.Name, nil)
_, err = authStorage.Role.CreateRoleWithEscalation(ctx, t)
}
// Gather any error
if err != nil {
errs = append(errs, err)
}
} else {
fmt.Fprintf(out, "Overwrite role %s/%s\n", t.Namespace, t.Name)
if s, err := describe.DescribeRole(t); err == nil {
fmt.Fprintf(out, "%s\n", s)
}
}
case *authorizationapi.RoleBinding:
ctx := apirequest.WithNamespace(apirequest.NewContext(), t.Namespace)
if change {
// Attempt to create
_, err := authStorage.RoleBinding.CreateRoleBindingWithEscalation(ctx, t)
// Unconditional replace if it already exists
if kapierrors.IsAlreadyExists(err) {
_, _, err = authStorage.RoleBinding.UpdateRoleBindingWithEscalation(ctx, t)
}
// Delete and recreate as a last resort
if err != nil {
authStorage.RoleBinding.Delete(ctx, t.Name, nil)
_, err = authStorage.RoleBinding.CreateRoleBindingWithEscalation(ctx, t)
}
// Gather any error
if err != nil {
errs = append(errs, err)
}
} else {
fmt.Fprintf(out, "Overwrite role binding %s/%s\n", t.Namespace, t.Name)
if s, err := describe.DescribeRoleBinding(t, nil, nil); err == nil {
fmt.Fprintf(out, "%s\n", s)
}
}
case *authorizationapi.ClusterRole:
ctx := apirequest.WithNamespace(apirequest.NewContext(), t.Namespace)
if change {
// Attempt to create
_, err := authStorage.ClusterRole.CreateClusterRoleWithEscalation(ctx, t)
// Unconditional replace if it already exists
if kapierrors.IsAlreadyExists(err) {
_, _, err = authStorage.ClusterRole.UpdateClusterRoleWithEscalation(ctx, t)
}
// Delete and recreate as a last resort
if err != nil {
authStorage.ClusterRole.Delete(ctx, t.Name, nil)
_, err = authStorage.ClusterRole.CreateClusterRoleWithEscalation(ctx, t)
}
// Gather any error
if err != nil {
errs = append(errs, err)
}
} else {
fmt.Fprintf(out, "Overwrite role %s/%s\n", t.Namespace, t.Name)
if s, err := describe.DescribeRole(authorizationapi.ToRole(t)); err == nil {
fmt.Fprintf(out, "%s\n", s)
}
}
case *authorizationapi.ClusterRoleBinding:
ctx := apirequest.WithNamespace(apirequest.NewContext(), t.Namespace)
if change {
// Attempt to create
_, err := authStorage.ClusterRoleBinding.CreateClusterRoleBindingWithEscalation(ctx, t)
// Unconditional replace if it already exists
if kapierrors.IsAlreadyExists(err) {
_, _, err = authStorage.ClusterRoleBinding.UpdateClusterRoleBindingWithEscalation(ctx, t)
}
// Delete and recreate as a last resort
if err != nil {
authStorage.ClusterRoleBinding.Delete(ctx, t.Name, nil)
_, err = authStorage.ClusterRoleBinding.CreateClusterRoleBindingWithEscalation(ctx, t)
}
// Gather any error
if err != nil {
errs = append(errs, err)
}
} else {
fmt.Fprintf(out, "Overwrite role binding %s/%s\n", t.Namespace, t.Name)
if s, err := describe.DescribeRoleBinding(authorizationapi.ToRoleBinding(t), nil, nil); err == nil {
fmt.Fprintf(out, "%s\n", s)
}
}
default:
errs = append(errs, fmt.Errorf("only roles and rolebindings may be created in this mode, not: %v", reflect.TypeOf(t)))
}
}
if !change {
fmt.Fprintf(out, "To make the changes described above, pass --force\n")
}
return kerrors.NewAggregate(errs)
})
}