forked from casbin/casbin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
enforcer.go
658 lines (559 loc) · 17.2 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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
// Copyright 2017 The casbin Authors. All Rights Reserved.
//
// 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 casbin
import (
"errors"
"fmt"
"strings"
"github.com/Knetic/govaluate"
"github.com/casbin/casbin/v2/effect"
"github.com/casbin/casbin/v2/log"
"github.com/casbin/casbin/v2/model"
"github.com/casbin/casbin/v2/persist"
fileadapter "github.com/casbin/casbin/v2/persist/file-adapter"
"github.com/casbin/casbin/v2/rbac"
defaultrolemanager "github.com/casbin/casbin/v2/rbac/default-role-manager"
"github.com/casbin/casbin/v2/util"
)
// Enforcer is the main interface for authorization enforcement and policy management.
type Enforcer struct {
modelPath string
model model.Model
fm model.FunctionMap
eft effect.Effector
adapter persist.Adapter
watcher persist.Watcher
rm rbac.RoleManager
enabled bool
autoSave bool
autoBuildRoleLinks bool
autoNotifyWatcher bool
logger log.Logger
}
// NewEnforcer creates an enforcer via file or DB.
//
// File:
//
// e := casbin.NewEnforcer("path/to/basic_model.conf", "path/to/basic_policy.csv")
//
// MySQL DB:
//
// a := mysqladapter.NewDBAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/")
// e := casbin.NewEnforcer("path/to/basic_model.conf", a)
//
func NewEnforcer(params ...interface{}) (*Enforcer, error) {
e := &Enforcer{logger: &log.DefaultLogger{}}
parsedParamLen := 0
paramLen := len(params)
if paramLen >= 1 {
enableLog, ok := params[paramLen-1].(bool)
if ok {
e.EnableLog(enableLog)
parsedParamLen++
}
}
if paramLen-parsedParamLen >= 1 {
logger, ok := params[paramLen-parsedParamLen-1].(log.Logger)
if ok {
e.logger = logger
parsedParamLen++
}
}
if paramLen-parsedParamLen == 2 {
switch p0 := params[0].(type) {
case string:
switch p1 := params[1].(type) {
case string:
err := e.InitWithFile(p0, p1)
if err != nil {
return nil, err
}
default:
err := e.InitWithAdapter(p0, p1.(persist.Adapter))
if err != nil {
return nil, err
}
}
default:
switch params[1].(type) {
case string:
return nil, errors.New("invalid parameters for enforcer")
default:
err := e.InitWithModelAndAdapter(p0.(model.Model), params[1].(persist.Adapter))
if err != nil {
return nil, err
}
}
}
} else if paramLen-parsedParamLen == 1 {
switch p0 := params[0].(type) {
case string:
err := e.InitWithFile(p0, "")
if err != nil {
return nil, err
}
default:
err := e.InitWithModelAndAdapter(p0.(model.Model), nil)
if err != nil {
return nil, err
}
}
} else if paramLen-parsedParamLen == 0 {
return e, nil
} else {
return nil, errors.New("invalid parameters for enforcer")
}
return e, nil
}
// InitWithFile initializes an enforcer with a model file and a policy file.
func (e *Enforcer) InitWithFile(modelPath string, policyPath string) error {
a := fileadapter.NewAdapter(policyPath)
return e.InitWithAdapter(modelPath, a)
}
// InitWithAdapter initializes an enforcer with a database adapter.
func (e *Enforcer) InitWithAdapter(modelPath string, adapter persist.Adapter) error {
m, err := model.NewModelFromFile(modelPath)
if err != nil {
return err
}
m.SetLogger(e.logger)
err = e.InitWithModelAndAdapter(m, adapter)
if err != nil {
return err
}
e.modelPath = modelPath
return nil
}
// InitWithModelAndAdapter initializes an enforcer with a model and a database adapter.
func (e *Enforcer) InitWithModelAndAdapter(m model.Model, adapter persist.Adapter) error {
e.adapter = adapter
e.model = m
m.SetLogger(e.logger)
e.model.PrintModel()
e.fm = model.LoadFunctionMap()
e.initialize()
// Do not initialize the full policy when using a filtered adapter
fa, ok := e.adapter.(persist.FilteredAdapter)
if e.adapter != nil && (!ok || ok && !fa.IsFiltered()) {
err := e.LoadPolicy()
if err != nil {
return err
}
}
return nil
}
// SetLogger changes the current enforcer's logger.
func (e *Enforcer) SetLogger(logger log.Logger) {
e.logger = logger
e.model.SetLogger(e.logger)
e.rm.SetLogger(e.logger)
}
func (e *Enforcer) initialize() {
e.rm = defaultrolemanager.NewRoleManager(10)
e.eft = effect.NewDefaultEffector()
e.watcher = nil
e.enabled = true
e.autoSave = true
e.autoBuildRoleLinks = true
e.autoNotifyWatcher = true
e.rm.SetLogger(e.logger)
}
// LoadModel reloads the model from the model CONF file.
// Because the policy is attached to a model, so the policy is invalidated and needs to be reloaded by calling LoadPolicy().
func (e *Enforcer) LoadModel() error {
var err error
e.model, err = model.NewModelFromFile(e.modelPath)
if err != nil {
return err
}
e.model.SetLogger(e.logger)
e.model.PrintModel()
e.fm = model.LoadFunctionMap()
e.initialize()
return nil
}
// GetModel gets the current model.
func (e *Enforcer) GetModel() model.Model {
return e.model
}
// SetModel sets the current model.
func (e *Enforcer) SetModel(m model.Model) {
e.model = m
e.fm = model.LoadFunctionMap()
e.model.SetLogger(e.logger)
e.initialize()
}
// GetAdapter gets the current adapter.
func (e *Enforcer) GetAdapter() persist.Adapter {
return e.adapter
}
// SetAdapter sets the current adapter.
func (e *Enforcer) SetAdapter(adapter persist.Adapter) {
e.adapter = adapter
}
// SetWatcher sets the current watcher.
func (e *Enforcer) SetWatcher(watcher persist.Watcher) error {
e.watcher = watcher
return watcher.SetUpdateCallback(func(string) { _ = e.LoadPolicy() })
}
// GetRoleManager gets the current role manager.
func (e *Enforcer) GetRoleManager() rbac.RoleManager {
return e.rm
}
// SetRoleManager sets the current role manager.
func (e *Enforcer) SetRoleManager(rm rbac.RoleManager) {
e.rm = rm
}
// SetEffector sets the current effector.
func (e *Enforcer) SetEffector(eft effect.Effector) {
e.eft = eft
}
// ClearPolicy clears all policy.
func (e *Enforcer) ClearPolicy() {
e.model.ClearPolicy()
}
// LoadPolicy reloads the policy from file/database.
func (e *Enforcer) LoadPolicy() error {
e.model.ClearPolicy()
if err := e.adapter.LoadPolicy(e.model); err != nil && err.Error() != "invalid file path, file path cannot be empty" {
return err
}
if e.autoBuildRoleLinks {
err := e.BuildRoleLinks()
if err != nil {
return err
}
}
return nil
}
func (e *Enforcer) loadFilteredPolicy(filter interface{}) error {
var filteredAdapter persist.FilteredAdapter
// Attempt to cast the Adapter as a FilteredAdapter
switch adapter := e.adapter.(type) {
case persist.FilteredAdapter:
filteredAdapter = adapter
default:
return errors.New("filtered policies are not supported by this adapter")
}
if err := filteredAdapter.LoadFilteredPolicy(e.model, filter); err != nil && err.Error() != "invalid file path, file path cannot be empty" {
return err
}
e.model.PrintPolicy()
if e.autoBuildRoleLinks {
err := e.BuildRoleLinks()
if err != nil {
return err
}
}
return nil
}
// LoadFilteredPolicy reloads a filtered policy from file/database.
func (e *Enforcer) LoadFilteredPolicy(filter interface{}) error {
e.model.ClearPolicy()
return e.loadFilteredPolicy(filter)
}
// LoadIncrementalFilteredPolicy append a filtered policy from file/database.
func (e *Enforcer) LoadIncrementalFilteredPolicy(filter interface{}) error {
return e.loadFilteredPolicy(filter)
}
// IsFiltered returns true if the loaded policy has been filtered.
func (e *Enforcer) IsFiltered() bool {
filteredAdapter, ok := e.adapter.(persist.FilteredAdapter)
if !ok {
return false
}
return filteredAdapter.IsFiltered()
}
// SavePolicy saves the current policy (usually after changed with Casbin API) back to file/database.
func (e *Enforcer) SavePolicy() error {
if e.IsFiltered() {
return errors.New("cannot save a filtered policy")
}
if err := e.adapter.SavePolicy(e.model); err != nil {
return err
}
if e.watcher != nil {
var err error
if watcher, ok := e.watcher.(persist.WatcherEx); ok {
err = watcher.UpdateForSavePolicy(e.model)
} else {
err = e.watcher.Update()
}
return err
}
return nil
}
// EnableEnforce changes the enforcing state of Casbin, when Casbin is disabled, all access will be allowed by the Enforce() function.
func (e *Enforcer) EnableEnforce(enable bool) {
e.enabled = enable
}
// EnableLog changes whether Casbin will log messages to the Logger.
func (e *Enforcer) EnableLog(enable bool) {
e.logger.EnableLog(enable)
}
// IsLogEnabled returns the current logger's enabled status.
func (e *Enforcer) IsLogEnabled() bool {
return e.logger.IsEnabled()
}
// EnableAutoNotifyWatcher controls whether to save a policy rule automatically notify the Watcher when it is added or removed.
func (e *Enforcer) EnableAutoNotifyWatcher(enable bool) {
e.autoNotifyWatcher = enable
}
// EnableAutoSave controls whether to save a policy rule automatically to the adapter when it is added or removed.
func (e *Enforcer) EnableAutoSave(autoSave bool) {
e.autoSave = autoSave
}
// EnableAutoBuildRoleLinks controls whether to rebuild the role inheritance relations when a role is added or deleted.
func (e *Enforcer) EnableAutoBuildRoleLinks(autoBuildRoleLinks bool) {
e.autoBuildRoleLinks = autoBuildRoleLinks
}
// BuildRoleLinks manually rebuild the role inheritance relations.
func (e *Enforcer) BuildRoleLinks() error {
err := e.rm.Clear()
if err != nil {
return err
}
return e.model.BuildRoleLinks(e.rm)
}
// BuildIncrementalRoleLinks provides incremental build the role inheritance relations.
func (e *Enforcer) BuildIncrementalRoleLinks(op model.PolicyOp, ptype string, rules [][]string) error {
return e.model.BuildIncrementalRoleLinks(e.rm, op, "g", ptype, rules)
}
// enforce use a custom matcher to decides whether a "subject" can access a "object" with the operation "action", input parameters are usually: (matcher, sub, obj, act), use model matcher by default when matcher is "".
func (e *Enforcer) enforce(matcher string, explains *[]string, rvals ...interface{}) (ok bool, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic: %v", r)
}
}()
if !e.enabled {
return true, nil
}
functions := e.fm.GetFunctions()
if _, ok := e.model["g"]; ok {
for key, ast := range e.model["g"] {
rm := ast.RM
functions[key] = util.GenerateGFunction(rm)
}
}
var expString string
if matcher == "" {
expString = e.model["m"]["m"].Value
} else {
expString = util.RemoveComments(util.EscapeAssertion(matcher))
}
var expression *govaluate.EvaluableExpression
hasEval := util.HasEval(expString)
if !hasEval {
expression, err = govaluate.NewEvaluableExpressionWithFunctions(expString, functions)
if err != nil {
return false, err
}
}
rTokens := make(map[string]int, len(e.model["r"]["r"].Tokens))
for i, token := range e.model["r"]["r"].Tokens {
rTokens[token] = i
}
pTokens := make(map[string]int, len(e.model["p"]["p"].Tokens))
for i, token := range e.model["p"]["p"].Tokens {
pTokens[token] = i
}
parameters := enforceParameters{
rTokens: rTokens,
rVals: rvals,
pTokens: pTokens,
}
var policyEffects []effect.Effect
var matcherResults []float64
if policyLen := len(e.model["p"]["p"].Policy); policyLen != 0 {
policyEffects = make([]effect.Effect, policyLen)
matcherResults = make([]float64, policyLen)
if len(e.model["r"]["r"].Tokens) != len(rvals) {
return false, fmt.Errorf(
"invalid request size: expected %d, got %d, rvals: %v",
len(e.model["r"]["r"].Tokens),
len(rvals),
rvals)
}
for i, pvals := range e.model["p"]["p"].Policy {
// log.LogPrint("Policy Rule: ", pvals)
if len(e.model["p"]["p"].Tokens) != len(pvals) {
return false, fmt.Errorf(
"invalid policy size: expected %d, got %d, pvals: %v",
len(e.model["p"]["p"].Tokens),
len(pvals),
pvals)
}
parameters.pVals = pvals
if hasEval {
ruleNames := util.GetEvalValue(expString)
replacements := make(map[string]string)
for _, ruleName := range ruleNames {
if j, ok := parameters.pTokens[ruleName]; ok {
rule := util.EscapeAssertion(pvals[j])
replacements[ruleName] = rule
} else {
return false, errors.New("please make sure rule exists in policy when using eval() in matcher")
}
}
expWithRule := util.ReplaceEvalWithMap(expString, replacements)
expression, err = govaluate.NewEvaluableExpressionWithFunctions(expWithRule, functions)
if err != nil {
return false, fmt.Errorf("p.sub_rule should satisfy the syntax of matcher: %s", err)
}
}
result, err := expression.Eval(parameters)
// log.LogPrint("Result: ", result)
if err != nil {
return false, err
}
switch result := result.(type) {
case bool:
if !result {
policyEffects[i] = effect.Indeterminate
continue
}
case float64:
if result == 0 {
policyEffects[i] = effect.Indeterminate
continue
} else {
matcherResults[i] = result
}
default:
return false, errors.New("matcher result should be bool, int or float")
}
if j, ok := parameters.pTokens["p_eft"]; ok {
eft := parameters.pVals[j]
if eft == "allow" {
policyEffects[i] = effect.Allow
} else if eft == "deny" {
policyEffects[i] = effect.Deny
} else {
policyEffects[i] = effect.Indeterminate
}
} else {
policyEffects[i] = effect.Allow
}
if e.model["e"]["e"].Value == "priority(p_eft) || deny" {
break
}
}
} else {
if hasEval && len(e.model["p"]["p"].Policy) == 0 {
return false, errors.New("please make sure rule exists in policy when using eval() in matcher")
}
policyEffects = make([]effect.Effect, 1)
matcherResults = make([]float64, 1)
parameters.pVals = make([]string, len(parameters.pTokens))
result, err := expression.Eval(parameters)
// log.LogPrint("Result: ", result)
if err != nil {
return false, err
}
if result.(bool) {
policyEffects[0] = effect.Allow
} else {
policyEffects[0] = effect.Indeterminate
}
}
// log.LogPrint("Rule Results: ", policyEffects)
result, explainIndex, err := e.eft.MergeEffects(e.model["e"]["e"].Value, policyEffects, matcherResults)
if err != nil {
return false, err
}
if explains != nil {
if explainIndex != -1 && len(e.model["p"]["p"].Policy) > explainIndex {
*explains = e.model["p"]["p"].Policy[explainIndex]
}
}
// Log request.
if e.logger.IsEnabled() {
var reqStr strings.Builder
reqStr.WriteString("Request: ")
for i, rval := range rvals {
if i != len(rvals)-1 {
reqStr.WriteString(fmt.Sprintf("%v, ", rval))
} else {
reqStr.WriteString(fmt.Sprintf("%v", rval))
}
}
reqStr.WriteString(fmt.Sprintf(" ---> %t\n", result))
if explains != nil {
reqStr.WriteString("Hit Policy: ")
for i, pval := range *explains {
if i != len(*explains)-1 {
reqStr.WriteString(fmt.Sprintf("%v, ", pval))
} else {
reqStr.WriteString(fmt.Sprintf("%v \n", pval))
}
}
}
logType := log.LogTypeGrantedAccessRequest
if !result {
logType = log.LogTypeRejectedAccessRequest
}
e.logger.LogEnforce(logType, reqStr.String(), &rvals, explains, &[]interface{}{result})
}
return result, nil
}
// Enforce decides whether a "subject" can access a "object" with the operation "action", input parameters are usually: (sub, obj, act).
func (e *Enforcer) Enforce(rvals ...interface{}) (bool, error) {
return e.enforce("", nil, rvals...)
}
// EnforceWithMatcher use a custom matcher to decides whether a "subject" can access a "object" with the operation "action", input parameters are usually: (matcher, sub, obj, act), use model matcher by default when matcher is "".
func (e *Enforcer) EnforceWithMatcher(matcher string, rvals ...interface{}) (bool, error) {
return e.enforce(matcher, nil, rvals...)
}
// EnforceEx explain enforcement by informing matched rules
func (e *Enforcer) EnforceEx(rvals ...interface{}) (bool, []string, error) {
explain := []string{}
result, err := e.enforce("", &explain, rvals...)
return result, explain, err
}
// EnforceExWithMatcher use a custom matcher and explain enforcement by informing matched rules
func (e *Enforcer) EnforceExWithMatcher(matcher string, rvals ...interface{}) (bool, []string, error) {
explain := []string{}
result, err := e.enforce(matcher, &explain, rvals...)
return result, explain, err
}
// assumes bounds have already been checked
type enforceParameters struct {
rTokens map[string]int
rVals []interface{}
pTokens map[string]int
pVals []string
}
// implements govaluate.Parameters
func (p enforceParameters) Get(name string) (interface{}, error) {
if name == "" {
return nil, nil
}
switch name[0] {
case 'p':
i, ok := p.pTokens[name]
if !ok {
return nil, errors.New("No parameter '" + name + "' found.")
}
return p.pVals[i], nil
case 'r':
i, ok := p.rTokens[name]
if !ok {
return nil, errors.New("No parameter '" + name + "' found.")
}
return p.rVals[i], nil
default:
return nil, errors.New("No parameter '" + name + "' found.")
}
}