-
Notifications
You must be signed in to change notification settings - Fork 10
/
rbac.go
436 lines (395 loc) · 11.9 KB
/
rbac.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
/*`rbac`` is role based access control library for GOlang. At core uses
sync.Map so, it can be used from multiple goroutines concurrently.
"Keep it simple" is also in core.
It supports role inheritance.
It can be used in middleware.
*/package rbac
import (
"encoding/json"
"fmt"
"io"
"sync"
)
var log Logger
// RBAC is role bases access control manager
type RBAC struct {
sync.Map // key: role.ID, value: role
permissions sync.Map // registered permissions
}
type jsRBAC struct {
Permissions []*Permission `json:"permissions"`
Roles []*RoleGrants `json:"roles"`
}
// New returns a new RBAC instance
func New(logger Logger) *RBAC {
SetLogger(logger)
return &RBAC{}
}
// SetLogger sets rbac logger
func SetLogger(logger Logger) {
if logger != nil {
log = logger
} else {
log = &NullLogger{}
}
}
// Clone clones RBAC instance
func (r *RBAC) Clone(roles bool) (trg *RBAC) {
trg = &RBAC{}
r.permissions.Range(func(k, v interface{}) bool {
trg.permissions.Store(k, v)
return true
})
if roles {
r.Range(func(k, v interface{}) bool {
trg.Store(k, v)
return true
})
}
return
}
// RegisterPermission defines and registers a permission
func (r *RBAC) RegisterPermission(permissionID, description string, actions ...Action) (*Permission, error) {
if r.IsPermissionExist(permissionID, "") {
log.Errorf("permission %s is already registered", permissionID)
return r.GetPermission(permissionID), fmt.Errorf("permission %s is already registered", permissionID)
}
perm := newPermission(permissionID, description, actions...)
r.permissions.Store(permissionID, perm)
return perm, nil
}
// IsPermissionExist checks if a permission with target ID and action is defined
func (r *RBAC) IsPermissionExist(permissionID string, action Action) (res bool) {
perm, res := r.permissions.Load(permissionID)
if res && action != None {
_, res = perm.(*Permission).Load(action)
}
return res
}
// GetPermission returns the permission if exists. perm is nil if not found.
func (r *RBAC) GetPermission(permissionID string) *Permission {
perm, ok := r.permissions.Load(permissionID)
if !ok {
log.Errorf("permission %s is not registered", permissionID)
return nil
}
return perm.(*Permission)
}
//RegisterRole defines and registers a role
func (r *RBAC) RegisterRole(roleID string, description string) (*Role, error) {
if r.IsRoleExist(roleID) {
log.Errorf("role %s is already registered", roleID)
return nil, fmt.Errorf("role %s is already registered", roleID)
}
role := &Role{ID: roleID, Description: description}
r.Store(roleID, role)
return role, nil
}
// GetRole finds and returns role from instance, if role is not found returns nil
func (r *RBAC) GetRole(roleID string) *Role {
rol, ok := r.Load(roleID)
if !ok {
log.Errorf("role %s is not registered", roleID)
return nil
}
return rol.(*Role)
}
// RemoveRole deletes role from instance
func (r *RBAC) RemoveRole(roleID string) error {
delRole := r.GetRole(roleID)
if delRole == nil {
log.Errorf("role %s is not registered", roleID)
return fmt.Errorf("role %s is not registered", roleID)
}
for _, role := range r.Roles() {
if role != nil {
if role.HasParent(roleID) {
role.RemoveParent(delRole)
}
}
}
r.Delete(roleID)
return nil
}
// Roles returns all registered roles
func (r *RBAC) Roles() (res []*Role) {
r.Range(func(k, v interface{}) bool {
res = append(res, v.(*Role))
return true
})
return res
}
// IsRoleExist checks if a role with target ID is defined
func (r *RBAC) IsRoleExist(roleID string) (res bool) {
_, res = r.Load(roleID)
return res
}
// Permit grants a permission with defined actions to a role
func (r *RBAC) Permit(roleID string, perm *Permission, actions ...Action) error {
if perm == nil {
log.Errorf("nil perm is sent for revoking from role %s", roleID)
return fmt.Errorf("permission can not be nil")
}
if role, ok := r.Load(roleID); ok {
for _, a := range actions {
// Check if this action is valid for this permission:
if !r.IsPermissionExist(perm.ID, a) {
log.Errorf("action %s is not registered for permission %s", a, perm.ID)
return fmt.Errorf("action %s is not registered for permission %s", a, perm.ID)
}
}
role.(*Role).grant(perm, actions...)
} else {
log.Errorf("role %s is not registered")
return fmt.Errorf("role %s is not registered", roleID)
}
return nil
}
// Revoke removes a permission from a role
func (r *RBAC) Revoke(roleID string, perm *Permission, actions ...Action) error {
if perm == nil {
log.Errorf("nil perm is sent for revoking from roleRoles %s", roleID)
return fmt.Errorf("permission can not be nil")
}
if role, ok := r.Load(roleID); ok {
for _, a := range actions {
if !r.IsPermissionExist(perm.ID, a) {
log.Errorf("action %s is not registered for permission %s", a, perm.ID)
return fmt.Errorf("action %s is not registered for permission %s", a, perm.ID)
}
}
role.(*Role).revoke(perm, actions...)
} else {
log.Errorf("role %s is not registered", roleID)
return fmt.Errorf("role %s is not registered", roleID)
}
return nil
}
// IsGranted checks if a role with target permission and actions has a grant
func (r *RBAC) IsGranted(roleID string, perm *Permission, actions ...Action) bool {
if perm == nil {
log.Errorf("Nil perm is sent for granted check for role %s", roleID)
return false
}
return r.IsGrantedStr(roleID, perm.ID, actions...)
}
// IsGrantedStr checks if permID is granted with target actions for role
func (r *RBAC) IsGrantedStr(roleID string, permID string, actions ...Action) bool {
if role, ok := r.Load(roleID); ok {
validActions := []Action{}
for _, a := range actions {
// Check if this action is valid for this permission:
if !r.IsPermissionExist(permID, a) {
log.Errorf("Action %s for permission %s is not defined, while checking grants for role %s", a, permID, roleID)
return false
}
validActions = append(validActions, a)
}
if role.(*Role).isGrantedStr(permID, validActions...) {
return true
}
}
return false
}
// IsGrantInherited checks if a role with target permission and actions has a grant
func (r *RBAC) IsGrantInherited(roleID string, perm *Permission, actions ...Action) bool {
if perm == nil {
log.Errorf("Nil perm is sent for granted check for role %s", roleID)
return false
}
return r.IsGrantInheritedStr(roleID, perm.ID, actions...)
}
// IsGrantInheritedStr checks if permID is granted with target actions for role
func (r *RBAC) IsGrantInheritedStr(roleID string, permID string, actions ...Action) bool {
if role, ok := r.Load(roleID); ok {
return role.(*Role).isGrantInheritedStr(permID, actions...)
}
return false
}
func hasAction(actions []Action, action Action) bool {
for _, a := range actions {
if a == action {
return true
}
}
return false
}
// GetAllPermissions returns granted permissions for a role(including inherited permissions from parents)
func (r *RBAC) GetAllPermissions(roleIDs []string) map[string][]Action {
perms := map[string][]Action{}
for _, roleID := range roleIDs {
if role, ok := r.Load(roleID); ok {
// Merge permission actions
for k, v := range role.(*Role).getGrants() {
if actions, ok := perms[k]; ok {
for _, a := range v {
if !hasAction(actions, a) {
actions = append(actions, a)
}
}
perms[k] = actions
} else {
perms[k] = v
}
}
// Merge permission actions with parent's actions
for _, pr := range role.(*Role).Parents() {
for k, v := range pr.getGrants() {
if actions, ok := perms[k]; ok {
for _, a := range v {
if !hasAction(actions, a) {
actions = append(actions, a)
}
}
perms[k] = actions
} else {
perms[k] = v
}
}
}
} else {
log.Errorf("Role with ID %s is not found", roleID)
}
}
return perms
}
// AnyGranted checks if any role has the permission.
func (r *RBAC) AnyGranted(roleIDs []string, perm *Permission, action ...Action) (res bool) {
return r.AnyGrantedStr(roleIDs, perm.ID, action...)
}
// AnyGrantedStr checks if any role has the permission.
func (r *RBAC) AnyGrantedStr(roleIDs []string, permName string, action ...Action) (res bool) {
for _, roleID := range roleIDs {
if r.IsGrantedStr(roleID, permName, action...) {
res = true
break
}
}
return res
}
// AllGranted checks if all roles have the permission.
func (r *RBAC) AllGranted(roleIDs []string, perm *Permission, action ...Action) (res bool) {
return r.AllGrantedStr(roleIDs, perm.ID, action...)
}
// AllGrantedStr checks if all roles have the permission.
func (r *RBAC) AllGrantedStr(roleIDs []string, permName string, action ...Action) (res bool) {
for _, roleID := range roleIDs {
if !r.IsGrantedStr(roleID, permName, action...) {
res = true
break
}
}
return !res
}
// AnyGrantInherited checks if any role has the permission.
func (r *RBAC) AnyGrantInherited(roleIDs []string, perm *Permission, action ...Action) (res bool) {
return r.AnyGrantInheritedStr(roleIDs, perm.ID, action...)
}
// AnyGrantInheritedStr checks if any role has the permission.
func (r *RBAC) AnyGrantInheritedStr(roleIDs []string, permName string, action ...Action) (res bool) {
for _, roleID := range roleIDs {
if r.IsGrantInheritedStr(roleID, permName, action...) {
res = true
break
}
}
return res
}
// AllGrantInherited checks if all roles have the permission.
func (r *RBAC) AllGrantInherited(roleIDs []string, perm *Permission, action ...Action) bool {
return r.AllGrantInheritedStr(roleIDs, perm.ID, action...)
}
// AllGrantInheritedStr checks if all roles have the permission.
func (r *RBAC) AllGrantInheritedStr(roleIDs []string, permName string, action ...Action) bool {
for _, roleID := range roleIDs {
if !r.IsGrantInheritedStr(roleID, permName, action...) {
return false
}
}
return true
}
// RoleGrants returns all roles
func (r *RBAC) RoleGrants() []*RoleGrants {
res := []*RoleGrants{}
r.Range(func(_, v interface{}) bool {
res = append(res, &RoleGrants{
ID: v.(*Role).ID,
Description: v.(*Role).Description,
Grants: v.(*Role).getGrants(),
Parents: v.(*Role).ParentIDs(),
})
return true
})
return res
}
// Permissions returns all Permissions
func (r *RBAC) Permissions() []*Permission {
res := []*Permission{}
r.permissions.Range(func(_, v interface{}) bool {
res = append(res, v.(*Permission))
return true
})
return res
}
// MarshalJSON serializes a all roles to JSON
func (r *RBAC) MarshalJSON() ([]byte, error) {
return json.Marshal(jsRBAC{
Roles: r.RoleGrants(),
Permissions: r.Permissions(),
})
}
// UnmarshalJSON parses RBAC from JSON
func (r *RBAC) UnmarshalJSON(b []byte) (err error) {
s := jsRBAC{}
if err = json.Unmarshal(b, &s); err != nil {
return err
}
for _, roleGrants := range s.Roles {
_, err := r.RegisterRole(roleGrants.ID, roleGrants.Description)
if err != nil {
return err
}
for permID, actions := range roleGrants.Grants {
perm, ok := r.permissions.Load(permID)
if !ok {
return fmt.Errorf("permission %s for role %s is not registered", permID, roleGrants.ID)
}
if err = r.Permit(roleGrants.ID, perm.(*Permission), actions...); err != nil {
return err
}
}
}
for _, roleGrants := range s.Roles {
role := r.GetRole(roleGrants.ID)
if role == nil {
log.Errorf("can not find role %s", roleGrants.ID)
} else {
for _, parentID := range roleGrants.Parents {
parentRole := r.GetRole(parentID)
if parentRole == nil {
log.Errorf("can not find parent role %s for role %s", parentID, parentRole.ID)
} else {
role.AddParent(parentRole)
}
}
}
}
return nil
}
// LoadJSON loads all data from a reader
func (r *RBAC) LoadJSON(reader io.Reader) error {
return json.NewDecoder(reader).Decode(r)
}
// SaveJSON saves all to a writer
func (r *RBAC) SaveJSON(writer io.Writer) (err error) {
enc := json.NewEncoder(writer)
enc.SetIndent("", " ")
if err = enc.Encode(jsRBAC{
Roles: r.RoleGrants(),
Permissions: r.Permissions(),
}); err != nil {
log.Errorf("can not encode to json, err:%v", err)
return err
}
return nil
}