forked from ProtocolONE/rbac
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenforcer.go
472 lines (398 loc) · 14.1 KB
/
enforcer.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
471
472
package rbac
import (
"fmt"
"github.com/casbin/casbin"
"github.com/casbin/casbin/model"
"github.com/casbin/casbin/persist"
casbin_rbac "github.com/casbin/casbin/rbac"
"strings"
)
const (
// AllowAccess should be used as effect for policies that allow access.
AllowAccess = "allow"
// SkipResourceId should be used for policies that should skip
// resource identity check in permissions.
SkipResourceId = "skip"
permissionOwner = 0
permissionRole = 1
permissionResourceId = 2
maxHierarchyLevel = 3
)
// CustomFunction used to add custom functions to match.
type CustomFunction func(args ...interface{}) (interface{}, error)
// Enforcer. By default role modelText in Qilin role manager works with RBAC with domains for all users.
// We also uses elements of ABAC to check specific policy rules for resources and users.
type Enforcer struct {
roleManager casbin_rbac.RoleManager
enforcer *casbin.SyncedEnforcer
}
// Context used to identity enforce request.
type Context struct {
User string `json:"user"`
Domain string `json:"domain"`
Resource string `json:"resource"`
ResourceId string `json:"resourceId"`
ResourceOwner string `json:"resourceOwner"`
Action string `json:"action"`
}
// Role used to add new roles for user with given restrictions to resource.
type Role struct {
User string `json:"user"`
Role string `json:"role"`
Domain string `json:"domain"`
Owner string `json:"owner"`
RestrictedResourceId []string `json:"restrictedResourceId"`
}
// Policy used to declare new RBAC model policy in casbin.
type Policy struct {
Role string `json:"role"`
Domain string `json:"domain"`
ResourceType string `json:"resourceType"`
ResourceId string `json:"resourceId"`
Action string `json:"action"`
Effect string `json:"effect"`
}
// Restriction define one permission rule.
type Restriction struct {
Owner string `json:"owner"`
Role string `json:"role"`
UUID string `json:"uuid"`
}
// UserPermissions contains detailed information about user roles and permissions.
type UserPermissions struct {
User string `json:"user"`
Domain string `json:"domain"`
Permissions []*UserPermission `json:"permissions"`
UnmatchedRestrictions []*Restriction `json:"unmatchedRestrictions"`
}
// UserPermission defines a single permission.
type UserPermission struct {
Role string `json:"role"`
Domain string `json:"domain"`
Resource string `json:"resource"`
UUID string `json:"uuid"`
Action string `json:"action"`
Allowed bool `json:"allowed"`
// Restrictions defines all permissions and restriction for given user and role.
Restrictions []*Restriction `json:"restrictions"`
}
// Enforcer create and init then Enforcer instance.
func NewEnforcer(params ...interface{}) *Enforcer {
rm := &Enforcer{}
m := casbin.NewModel(modelText)
if len(params) == 1 {
switch p0 := params[0].(type) {
case *casbin.SyncedEnforcer:
rm.enforcer = p0
return rm
case persist.Adapter:
rm.createEnforcer(m, p0)
case model.Model:
rm.createEnforcer(m, nil)
default:
panic("Unknown parameter type for Enforcer.")
}
} else if len(params) == 2 {
switch p0 := params[0].(type) {
case persist.Adapter:
rm.createEnforcer(m, p0)
default:
panic("Invalid parameters for enforcer.")
}
switch p1 := params[1].(type) {
case persist.Watcher:
rm.enforcer.SetWatcher(p1)
default:
panic("Invalid parameters for enforcer.")
}
} else if len(params) == 0 {
rm.createEnforcer(m, nil)
} else {
panic("Invalid parameters for enforcer.")
}
return rm
}
func (rm *Enforcer) createEnforcer(m model.Model, a persist.Adapter) {
rm.enforcer = casbin.NewSyncedEnforcer()
rm.enforcer.InitWithModelAndAdapter(m, a)
rm.roleManager = NewRoleManager(maxHierarchyLevel)
// If creating enforser with our own we redeclare internal role manager to custom role manager
// which support wildcard check for domain based `g` function.
//
// Example:
// p, role, domain/*, obj
// g, alise, role, domain/*
// r, alise, domain/5, obj
//
// g(r.sub, p.sub, r.dom) -> true
rm.enforcer.SetRoleManager(rm.roleManager)
// We need rebuild it forcibly due to casbin internal initialization realization.
rm.enforcer.BuildRoleLinks()
rm.enforcer.AddFunction("has_access_to_resource", rm.hasAccessToResource)
rm.enforcer.AddFunction("matchKeys", MatchKeysFunc)
rm.enforcer.AddFunction("bothSideMatchKeys", BothSideMatchKeysFunc)
}
// AddFunction adds a customized function.
func (rm *Enforcer) AddFunction(name string, function CustomFunction) {
rm.enforcer.AddFunction(name, function)
}
// Enforce decides whether a "subject" in "domain" can access a "resource" with the operation "action",
// input parameters are usually: (subject, domain, resource, action).
func (rm *Enforcer) Enforce(pr Context) bool {
return rm.enforcer.Enforce(pr)
}
// AddPolicy adds an authorization rule to the current policy.
// If the rule already exists, the function returns false and the rule will not be added.
// Otherwise the function returns true by adding the new rule.
func (rm *Enforcer) AddPolicy(p Policy) bool {
return rm.enforcer.AddPolicy(
p.Role,
p.Domain,
p.ResourceType,
p.ResourceId,
p.Action,
p.Effect,
) && rm.Save() == nil
}
// RemovePolicy removes an authorization rule from the current policy.
func (rm *Enforcer) RemovePolicy(p Policy) bool {
return rm.enforcer.RemovePolicy(
p.Role,
p.Domain,
p.ResourceType,
p.ResourceId,
p.Action,
p.Effect,
) && rm.Save() == nil
}
// LinkRoles adds a role inheritance rule to the current policy in domain.
// If the rule already exists, the function returns false and the rule will not be added.
// Otherwise the function returns true by adding the new rule.
func (rm *Enforcer) LinkRoles(role1, role2, domain string) bool {
return rm.enforcer.AddGroupingPolicy(role1, role2, domain) && rm.Save() == nil
}
// UnlinkRoles removes a role inheritance rule from the current policy in domain.
// If the rule not exists, the function returns false and the rule will not be deleted.
// Otherwise the function returns true by deleting the rule.
func (rm *Enforcer) UnlinkRoles(role1, role2, domain string) bool {
return rm.enforcer.RemoveGroupingPolicy(role1, role2, domain) && rm.Save() == nil
}
// HasLink determines whether a role inheritance rule exists.
func (rm *Enforcer) HasLink(role1, role2, domain string) bool {
return rm.enforcer.HasGroupingPolicy(role1, role2, domain)
}
// AddRole adds a role for a user inside a domain with given permissions.
// Returns false if the user already has the role (aka not affected).
func (rm *Enforcer) AddRole(rr Role) bool {
restrict := true
for _, r := range rr.RestrictedResourceId {
restrict = restrict && rm.AddRestrictionToUser(rr.User, &Restriction{rr.Owner, rr.Role, r})
}
addRoleG1 := rm.enforcer.AddRoleForUserInDomain(rr.User, rr.Role, rr.Domain)
return (restrict || addRoleG1) && rm.Save() == nil
}
// RemoveRole deletes a role for a user inside a domain.
// Returns false if the user does not have the role (aka not affected).
func (rm *Enforcer) RemoveRole(rr Role) bool {
restrict := true
for _, r := range rr.RestrictedResourceId {
restrict = restrict && rm.RemoveRestrictionFromUser(rr.User, &Restriction{rr.Owner, rr.Role, r})
}
removeRoleG1 := rm.enforcer.DeleteRoleForUserInDomain(rr.User, rr.Role, rr.Domain)
return (restrict || removeRoleG1) && rm.Save() == nil
}
// DeleteUser deletes a user.
// Returns false if the user does not exist (aka not affected).
func (rm *Enforcer) DeleteUser(user string) bool {
rm.enforcer.RemoveFilteredNamedGroupingPolicy("g2", 0, user)
return rm.enforcer.RemoveFilteredGroupingPolicy(0, user)
}
// AddRestrictionToUser add the resource identity to `g2` grouping policy. This used to
// implement access filtering for special resources in domain role. By default each role in domain
// have full access to all resources in domain. This restrictions allow to restrict access just for
// given resources.
func (rm *Enforcer) AddRestrictionToUser(user string, r *Restriction) bool {
return rm.enforcer.AddNamedGroupingPolicy("g2", user, r.GetRaw()) && rm.Save() == nil
}
// RemoveRestrictionFromUser removes a role inheritance rule from the `g2` named policy.
func (rm *Enforcer) RemoveRestrictionFromUser(user string, r *Restriction) bool {
return rm.enforcer.RemoveNamedGroupingPolicy("g2", user, r.GetRaw()) && rm.Save() == nil
}
// GetUserRestrictions return unassigned list of restrictions
func (rm *Enforcer) GetUserRestrictions(user string) []*Restriction {
var data []*Restriction
res := rm.enforcer.GetFilteredNamedGroupingPolicy("g2", 0, user)
for _, n := range res {
data = append(data, rm.createUserRestriction(n[1]))
}
return data
}
// GetUsersForRole gets the users that has a role inside a domain with given filtering. By default
// you could provide onwer, role and uuid as string of pass *Restriction to check.
func (rm *Enforcer) GetUsersForRole(role string, domain string, filters ...interface{}) []string {
users := rm.enforcer.GetUsersForRoleInDomain(role, domain)
if len(filters) == 0 {
return users
}
restrictionFilter := rm.buildRestrictionFilter(filters...)
var filteredUsers []string
for _, u := range users {
userRestrictions := rm.GetUserRestrictions(u)
if len(userRestrictions) == 0 {
filteredUsers = append(filteredUsers, u)
continue
}
for _, r := range userRestrictions {
if rm.passRestrictionFilter(r, restrictionFilter) {
filteredUsers = append(filteredUsers, u)
}
}
}
return filteredUsers
}
func (rm *Enforcer) passRestrictionFilter(r *Restriction, restrictionFilter *Restriction) bool {
if restrictionFilter == nil {
return true
}
if restrictionFilter.UUID != "" && restrictionFilter.UUID != r.UUID {
return false
}
if restrictionFilter.Role != "" && restrictionFilter.Role != r.Role {
return false
}
if restrictionFilter.Owner != r.Owner {
return false
}
return true
}
func (rm *Enforcer) buildRestrictionFilter(filters ...interface{}) (restrictionFilter *Restriction) {
if len(filters) > 0 {
switch filters[0].(type) {
case *Restriction:
restrictionFilter = filters[0].(*Restriction)
case string:
restrictionFilter = &Restriction{Owner: filters[0].(string)}
if len(filters) >= 2 {
switch filters[1].(type) {
case string:
restrictionFilter.Role = filters[1].(string)
}
}
if len(filters) == 3 {
switch filters[2].(type) {
case string:
restrictionFilter.UUID = filters[2].(string)
}
}
default:
panic(fmt.Sprintf("Invalid arguments in filter %+v", filters))
}
}
return
}
// GetRolesForUser gets the roles that a user has inside a domain.
func (rm *Enforcer) GetRolesForUser(user, domain string) []string {
return rm.enforcer.GetRolesForUserInDomain(user, domain)
}
// GetPermissionsForUser returns all the allow and deny permissions for a user
func (rm *Enforcer) GetPermissionsForUser(user, domain string, filters ...interface{}) *UserPermissions {
up := UserPermissions{
User: user,
Domain: domain,
}
subjects := rm.enforcer.GetRolesForUserInDomain(user, domain)
subjects = append(subjects, user)
up.Permissions = rm.buildPermissions(subjects, domain)
restrictionFilter := rm.buildRestrictionFilter(filters...)
unmatchedPerms := make(map[string]bool)
for _, r := range rm.GetUserRestrictions(user) {
if !rm.passRestrictionFilter(r, restrictionFilter) {
continue
}
for _, p := range up.Permissions {
if rm.matchRestriction(r.GetRaw(), r.Owner, p.Role, p.Domain, SkipResourceId, SkipResourceId) {
p.Restrictions = append(p.Restrictions, r)
} else {
key := r.Owner + r.Role + r.UUID
if _, ok := unmatchedPerms[key]; !ok {
unmatchedPerms[key] = true
up.UnmatchedRestrictions = append(up.UnmatchedRestrictions, r)
}
}
}
}
return &up
}
func (rm *Enforcer) Save() error {
if rm.enforcer.GetAdapter() == nil {
return nil
}
return rm.enforcer.SavePolicy()
}
func (rm *Enforcer) buildPermissions(subjects []string, domain string) []*UserPermission {
var permissions []*UserPermission
perms := make(map[string]*UserPermission)
for _, subject := range subjects {
for _, p := range rm.enforcer.GetPermissionsForUserInDomain(subject, domain) {
permission := &UserPermission{Role: p[0], Domain: p[1], Resource: p[2], UUID: p[3], Action: p[4], Allowed: p[5] == AllowAccess}
key := permission.Role + permission.Domain + permission.Resource + permission.UUID + permission.Action
if _, ok := perms[key]; !ok {
perms[key] = permission
permissions = append(permissions, permission)
}
}
}
return permissions
}
func (rm *Enforcer) createUserRestriction(res string) *Restriction {
parts := strings.Split(res, "/")
switch len(parts) {
case 1:
return &Restriction{parts[0], "", ""}
case 2:
return &Restriction{parts[0], parts[1], ""}
case 3:
return &Restriction{parts[0], parts[1], parts[2]}
}
panic("Can`t create Restriction with given res")
}
func (rm *Enforcer) hasAccessToResource(args ...interface{}) (interface{}, error) {
pr := args[0].(Context)
res := rm.enforcer.GetFilteredNamedGroupingPolicy("g2", 0, pr.User)
if len(res) == 0 {
return true, nil
}
policyRole := args[1].(string)
policyUUID := args[2].(string)
for _, n := range res {
if rm.matchRestriction(n[1], pr.ResourceOwner, policyRole, pr.Domain, policyUUID, pr.ResourceId) {
return true, nil
}
}
return false, nil
}
func (rm *Enforcer) matchRestriction(res, owner, policyRole, domain, policyUUID, resourceId string) bool {
ok := false
parts := strings.Split(res, "/")
if len(parts) >= 1 {
ok = MatchKeys(owner, parts[permissionOwner])
}
if len(parts) >= 2 && parts[permissionRole] != "*" {
matchRole, err := rm.roleManager.HasLink(parts[permissionRole], policyRole, domain)
ok = ok && matchRole && err == nil
}
if len(parts) == 3 && policyUUID != SkipResourceId {
ok = ok && MatchKeys(resourceId, parts[permissionResourceId])
}
return ok
}
// GetRaw return raw string for permission in `g2`
func (ur *Restriction) GetRaw() string {
if ur.Role == "" {
return ur.Owner
}
if ur.UUID == "" {
return ur.Owner + "/" + ur.Role
}
return ur.Owner + "/" + ur.Role + "/" + ur.UUID
}