/
sdkserviceapi.go
470 lines (411 loc) · 12.1 KB
/
sdkserviceapi.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
/*
Package role manages roles in Kvdb and provides validation
Copyright 2018 Portworx
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package role
import (
"context"
"fmt"
"reflect"
"strings"
"github.com/portworx/kvdb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/libopenstorage/openstorage/api"
"github.com/libopenstorage/openstorage/pkg/grpcserver"
)
const (
rolePrefix = "cluster/roles"
invalidChars = "/ "
negMatchChar = "!"
SystemAdminRoleName = "system.admin"
SystemViewRoleName = "system.view"
SystemUserRoleName = "system.user"
SystemGuestRoleName = "system.guest"
)
// DefaultRole is a role loaded into the system on startup
type DefaultRole struct {
Rules []*api.SdkRule
Mutable bool
}
var (
// DefaultRoles are the default roles to load on system startup
// Should be prefixed by `system.` to avoid collisions
DefaultRoles = map[string]*DefaultRole{
// system:admin role can run any command
SystemAdminRoleName: &DefaultRole{
Rules: []*api.SdkRule{
&api.SdkRule{
Services: []string{"*"},
Apis: []string{"*"},
},
},
Mutable: false,
},
// system:view role can only run read-only commands
SystemViewRoleName: &DefaultRole{
Rules: []*api.SdkRule{
&api.SdkRule{
Services: []string{"*"},
Apis: []string{
"*enumerate*",
"inspect*",
"stats",
"status",
"validate",
"capacityusage",
},
},
&api.SdkRule{
Services: []string{"identity"},
Apis: []string{"*"},
},
},
Mutable: false,
},
// system:user role can only access volume lifecycle commands
SystemUserRoleName: &DefaultRole{
Rules: []*api.SdkRule{
&api.SdkRule{
Services: []string{
"volume",
"cloudbackup",
"credentials",
"objectstore",
"schedulepolicy",
"mountattach",
"migrate",
},
Apis: []string{"*"},
},
&api.SdkRule{
Services: []string{
"cluster",
"node",
},
Apis: []string{
"inspect*",
"enumerate*",
},
},
&api.SdkRule{
Services: []string{"identity"},
Apis: []string{"*"},
},
&api.SdkRule{
Services: []string{"policy"},
Apis: []string{
"*enumerate*",
// This will allow system.user to view default policy also
"*inspect*",
},
},
},
Mutable: false,
},
// system:guest role is used for any unauthenticated user.
// They can only use standard volume lifecycle commands.
SystemGuestRoleName: &DefaultRole{
Rules: []*api.SdkRule{
&api.SdkRule{
Services: []string{"mountattach", "volume", "cloudbackup", "migrate"},
Apis: []string{"*"},
},
&api.SdkRule{
Services: []string{"identity"},
Apis: []string{"version"},
},
&api.SdkRule{
Services: []string{
"cluster",
"node",
},
Apis: []string{
"inspect*",
"enumerate*",
},
},
},
Mutable: true,
},
}
)
// SdkRoleManager is an implementation of the RoleManager for the SDK
type SdkRoleManager struct {
kv kvdb.Kvdb
}
// Check interface
var _ RoleManager = &SdkRoleManager{}
// Simple function which creates key for Kvdb
func prefixWithName(name string) string {
return rolePrefix + "/" + name
}
// Determines if the rules deny string s
func denyRule(rule, s string) bool {
if strings.HasPrefix(rule, negMatchChar) {
return matchRule(strings.TrimSpace(strings.Join(strings.Split(rule, negMatchChar), "")), s)
}
return false
}
// Determines if the rules apply to string s
// rule can be:
// '*' - match all
// '*xxx' - ends with xxx
// 'xxx*' - starts with xxx
// '*xxx*' - contains xxx
func matchRule(rule, s string) bool {
// no rule
rl := len(rule)
if rl == 0 {
return false
}
// '*xxx' || 'xxx*'
if rule[0:1] == "*" || rule[rl-1:rl] == "*" {
// get the matching string from the rule
match := strings.TrimSpace(strings.Join(strings.Split(rule, "*"), ""))
// '*' or '*******'
if len(match) == 0 {
return true
}
// '*xxx*'
if rule[0:1] == "*" && rule[rl-1:rl] == "*" {
return strings.Contains(s, match)
}
// '*xxx'
if rule[0:1] == "*" {
return strings.HasSuffix(s, match)
}
// 'xxx*'
return strings.HasPrefix(s, match)
}
// no wildcard stars given in rule
return rule == s
}
// NewSdkRoleManager returns a new SDK role manager
func NewSdkRoleManager(kv kvdb.Kvdb) (*SdkRoleManager, error) {
s := &SdkRoleManager{
kv: kv,
}
// Load all default roles
for roleName, defaultRole := range DefaultRoles {
roleExists := false
if _, err := kv.Get(prefixWithName(roleName)); err == nil {
roleExists = true
}
// always re-initialize immutable default roles.
// if the role is mutable and does exist, skip kvdb put.
if !roleExists || !defaultRole.Mutable {
role := &api.SdkRole{
Name: roleName,
Rules: defaultRole.Rules,
}
if _, err := kv.Put(prefixWithName(roleName), role, 0); err != nil {
return nil, err
}
}
}
return s, nil
}
// Create saves a role in Kvdb
func (r *SdkRoleManager) Create(
ctx context.Context,
req *api.SdkRoleCreateRequest,
) (*api.SdkRoleCreateResponse, error) {
if req.GetRole() == nil {
return nil, status.Error(codes.InvalidArgument, "Must supply a role")
} else if len(req.GetRole().GetName()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Must supply a name for the role")
} else if err := r.validateRole(req.GetRole()); err != nil {
return nil, err
}
// Determine if there is collision with default roles
if _, ok := DefaultRoles[req.GetRole().GetName()]; ok {
return nil, status.Errorf(
codes.InvalidArgument,
"Name %s already used by system role", req.GetRole().GetName())
}
// Save value in kvdb
_, err := r.kv.Create(prefixWithName(req.GetRole().GetName()), req.GetRole(), 0)
if err == kvdb.ErrExist {
// Idempotency check.
// Check that the new rules are the same.
oldrole, err := r.Inspect(ctx, &api.SdkRoleInspectRequest{
Name: req.GetRole().GetName(),
})
if err != nil {
return nil, err
}
if !reflect.DeepEqual(oldrole.GetRole(), req.GetRole()) {
return nil, status.Error(
codes.AlreadyExists,
"Existing role differs from requested role")
}
} else if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to save role: %v", err)
}
return &api.SdkRoleCreateResponse{
Role: req.GetRole(),
}, nil
}
// Enumerate returns a list of role names
func (r *SdkRoleManager) Enumerate(
ctx context.Context,
req *api.SdkRoleEnumerateRequest,
) (*api.SdkRoleEnumerateResponse, error) {
kvPairs, err := r.kv.Enumerate(rolePrefix + "/")
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to access roles from database: %v", err)
}
var names []string
for _, kvPair := range kvPairs {
names = append(names, strings.TrimPrefix(kvPair.Key, rolePrefix+"/"))
}
return &api.SdkRoleEnumerateResponse{
Names: names,
}, nil
}
// Inspect returns a role object
func (r *SdkRoleManager) Inspect(
ctx context.Context,
req *api.SdkRoleInspectRequest,
) (*api.SdkRoleInspectResponse, error) {
if len(req.GetName()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Must supply a name for role")
}
elem := &api.SdkRole{}
_, err := r.kv.GetVal(prefixWithName(req.GetName()), elem)
if err == kvdb.ErrNotFound {
return nil, status.Errorf(codes.NotFound, "Role %s not found", req.GetName())
} else if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to get role %s information: %v", req.GetName(), err)
}
return &api.SdkRoleInspectResponse{
Role: elem,
}, nil
}
// Delete removes a role from Kvdb
func (r *SdkRoleManager) Delete(
ctx context.Context,
req *api.SdkRoleDeleteRequest,
) (*api.SdkRoleDeleteResponse, error) {
if len(req.GetName()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Must supply a name for role")
}
// Determine if there is collision with default roles
if _, ok := DefaultRoles[req.GetName()]; ok {
return nil, status.Errorf(
codes.InvalidArgument,
"Cannot delete system role %s", req.GetName())
}
_, err := r.kv.Delete(prefixWithName(req.GetName()))
if err != kvdb.ErrNotFound && err != nil {
return nil, status.Errorf(codes.Internal, "Failed to delete role %s: %v", req.GetName(), err)
}
return &api.SdkRoleDeleteResponse{}, nil
}
// Update replaces an existing role.
func (r *SdkRoleManager) Update(
ctx context.Context,
req *api.SdkRoleUpdateRequest,
) (*api.SdkRoleUpdateResponse, error) {
if req.GetRole() == nil {
return nil, status.Error(codes.InvalidArgument, "Must supply a role")
}
if err := r.validateRole(req.GetRole()); err != nil {
return nil, err
}
// Determine if there is collision with default roles.
// We can still update mutable default roles.
if defaultRole, ok := DefaultRoles[req.GetRole().GetName()]; ok && !defaultRole.Mutable {
return nil, status.Errorf(
codes.InvalidArgument,
"System role %s cannot be updated", req.GetRole().GetName())
}
_, err := r.kv.Update(prefixWithName(req.GetRole().GetName()), req.GetRole(), 0)
if err == kvdb.ErrNotFound {
return nil, status.Errorf(codes.NotFound, "Role %s not found", req.GetRole())
} else if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to get role %s information: %v", req.GetRole().GetName(), err)
}
return &api.SdkRoleUpdateResponse{
Role: req.GetRole(),
}, nil
}
// Verify determines if the role has access to `fullmethod`
func (r *SdkRoleManager) Verify(ctx context.Context, roles []string, fullmethod string) error {
// Check all roles
for _, role := range roles {
// Get the role rules
resp, err := r.Inspect(ctx, &api.SdkRoleInspectRequest{
Name: role,
})
if err != nil || resp == nil || resp.GetRole() == nil {
continue
}
if err := r.verifyRules(resp.GetRole().GetRules(), fullmethod); err == nil {
return nil
}
}
return status.Errorf(codes.PermissionDenied, "Access denied to roles: %+s", roles)
}
// verifyRules checks if the rules authorize use of the API called `fullmethod`
func (r *SdkRoleManager) verifyRules(rules []*api.SdkRule, fullmethod string) error {
reqService, reqApi := grpcserver.GetMethodInformation(api.SdkRootPath, fullmethod)
// Look for denials first
for _, rule := range rules {
for _, service := range rule.Services {
// if the service is denied, then return here
if denyRule(service, reqService) {
return fmt.Errorf("access denied to service by role")
}
// If there is a match to the service now check the apis
if matchRule(service, reqService) {
for _, api := range rule.Apis {
if denyRule(api, reqApi) {
return fmt.Errorf("access denied to api by role")
}
}
}
}
}
// Look for permissions
for _, rule := range rules {
for _, service := range rule.Services {
if matchRule(service, reqService) {
for _, api := range rule.Apis {
if matchRule(api, reqApi) {
return nil
}
}
}
}
}
return fmt.Errorf("no accessable rule to authorize access found")
}
func (r *SdkRoleManager) validateRole(role *api.SdkRole) error {
if len(role.GetName()) == 0 {
return status.Error(codes.InvalidArgument, "Must supply a name for role")
} else if len(role.GetRules()) == 0 {
return status.Error(codes.InvalidArgument, "Must supply rules for role")
} else if strings.ContainsAny(role.GetName(), invalidChars) {
return status.Errorf(codes.InvalidArgument, "Name cannot contain any of the following invalid characters: %s", invalidChars)
}
// Check if the rules have services and apis
for _, rule := range role.GetRules() {
if len(rule.GetServices()) == 0 {
return status.Error(codes.InvalidArgument, "Must supply a service in rules for the role")
} else if len(rule.GetApis()) == 0 {
return status.Error(codes.InvalidArgument, "Must supply apis in rules for the role")
}
}
return nil
}