From 54b1fe8e86bbcb0e90b0431ca14b43f8572dd203 Mon Sep 17 00:00:00 2001 From: Ingo Oppermann Date: Tue, 23 Jul 2024 15:54:09 +0200 Subject: [PATCH] Dump casbin, replace with own policy enforcer --- app/api/api.go | 14 +- cluster/client/client.go | 4 +- cluster/cluster.go | 4 +- cluster/forwarder/iam.go | 4 +- cluster/iam.go | 8 +- cluster/iam/adapter/policy.go | 43 +- cluster/iam/iam.go | 4 +- cluster/store/identity_test.go | 4 +- cluster/store/policy.go | 6 +- cluster/store/policy_test.go | 6 +- cluster/store/store.go | 10 +- go.mod | 4 +- go.sum | 10 - http/api/iam.go | 10 +- http/handler/api/cluster_iam.go | 6 +- http/handler/api/process_test.go | 4 +- http/middleware/iam/iam_test.go | 4 +- iam/access/access.go | 182 --- iam/access/adapter.go | 588 ---------- iam/access/functions.go | 116 -- iam/iam.go | 29 +- iam/policy/access.go | 35 + iam/policy/adapter.go | 418 +++++++ iam/{access => policy}/adapter_test.go | 65 +- iam/policy/enforcer.go | 93 ++ iam/{access => policy}/fixtures/policy.json | 0 iam/policy/manager.go | 92 ++ .../access_test.go => policy/manager_test.go} | 63 +- iam/policy/matcher.go | 72 ++ iam/policy/matcher_test.go | 35 + iam/policy/model.go | 238 ++++ iam/policy/model_test.go | 354 ++++++ restream/core_test.go | 4 +- restream/rewrite/rewrite_test.go | 4 +- vendor/github.com/casbin/casbin/v2/.gitignore | 30 - .../github.com/casbin/casbin/v2/.golangci.yml | 354 ------ .../casbin/casbin/v2/.releaserc.json | 16 - .../github.com/casbin/casbin/v2/.travis.yml | 15 - .../casbin/casbin/v2/CONTRIBUTING.md | 35 - vendor/github.com/casbin/casbin/v2/LICENSE | 201 ---- vendor/github.com/casbin/casbin/v2/Makefile | 18 - vendor/github.com/casbin/casbin/v2/README.md | 296 ----- .../casbin/casbin/v2/casbin-logo.png | Bin 34267 -> 0 bytes .../casbin/casbin/v2/config/config.go | 267 ----- .../casbin/casbin/v2/constant/constants.go | 31 - .../casbin/v2/effector/default_effector.go | 109 -- .../casbin/casbin/v2/effector/effector.go | 31 - .../github.com/casbin/casbin/v2/enforcer.go | 1004 ---------------- .../casbin/casbin/v2/enforcer_cached.go | 185 --- .../casbin/v2/enforcer_cached_synced.go | 180 --- .../casbin/casbin/v2/enforcer_distributed.go | 239 ---- .../casbin/casbin/v2/enforcer_interface.go | 177 --- .../casbin/casbin/v2/enforcer_synced.go | 650 ----------- .../casbin/casbin/v2/errors/rbac_errors.go | 30 - .../github.com/casbin/casbin/v2/frontend.go | 57 - .../casbin/casbin/v2/frontend_old.go | 30 - .../casbin/casbin/v2/internal_api.go | 497 -------- .../casbin/casbin/v2/log/default_logger.go | 104 -- .../casbin/casbin/v2/log/log_util.go | 52 - .../github.com/casbin/casbin/v2/log/logger.go | 41 - .../casbin/casbin/v2/management_api.go | 500 -------- .../casbin/casbin/v2/model/assertion.go | 194 ---- .../casbin/casbin/v2/model/function.go | 66 -- .../casbin/casbin/v2/model/model.go | 434 ------- .../casbin/casbin/v2/model/policy.go | 482 -------- .../casbin/casbin/v2/persist/adapter.go | 74 -- .../casbin/v2/persist/adapter_context.go | 39 - .../casbin/v2/persist/adapter_filtered.go | 29 - .../v2/persist/adapter_filtered_context.go | 31 - .../casbin/casbin/v2/persist/batch_adapter.go | 26 - .../v2/persist/batch_adapter_context.go | 29 - .../casbin/casbin/v2/persist/cache/cache.go | 39 - .../casbin/v2/persist/cache/cache_sync.go | 86 -- .../casbin/v2/persist/cache/default-cache.go | 69 -- .../casbin/casbin/v2/persist/dispatcher.go | 33 - .../casbin/v2/persist/file-adapter/adapter.go | 149 --- .../persist/file-adapter/adapter_filtered.go | 156 --- .../v2/persist/file-adapter/adapter_mock.go | 122 -- .../casbin/v2/persist/update_adapter.go | 27 - .../v2/persist/update_adapter_context.go | 30 - .../casbin/casbin/v2/persist/watcher.go | 29 - .../casbin/casbin/v2/persist/watcher_ex.go | 40 - .../casbin/v2/persist/watcher_update.go | 26 - .../casbin/v2/rbac/context_role_manager.go | 46 - .../rbac/default-role-manager/role_manager.go | 1014 ----------------- .../casbin/casbin/v2/rbac/role_manager.go | 76 -- .../github.com/casbin/casbin/v2/rbac_api.go | 644 ----------- .../casbin/casbin/v2/rbac_api_synced.go | 203 ---- .../casbin/casbin/v2/rbac_api_with_domains.go | 192 ---- .../casbin/v2/rbac_api_with_domains_synced.go | 60 - .../casbin/v2/util/builtin_operators.go | 482 -------- .../github.com/casbin/casbin/v2/util/util.go | 383 ------- vendor/github.com/casbin/govaluate/.gitignore | 28 - .../casbin/govaluate/.releaserc.json | 16 - .../github.com/casbin/govaluate/CONTRIBUTORS | 15 - .../casbin/govaluate/EvaluableExpression.go | 276 ----- .../govaluate/EvaluableExpression_sql.go | 167 --- .../casbin/govaluate/ExpressionToken.go | 9 - vendor/github.com/casbin/govaluate/LICENSE | 21 - vendor/github.com/casbin/govaluate/MANUAL.md | 176 --- .../casbin/govaluate/OperatorSymbol.go | 309 ----- vendor/github.com/casbin/govaluate/README.md | 232 ---- .../github.com/casbin/govaluate/TokenKind.go | 75 -- .../casbin/govaluate/evaluationStage.go | 542 --------- .../casbin/govaluate/expressionFunctions.go | 8 - .../govaluate/expressionOutputStream.go | 46 - .../github.com/casbin/govaluate/lexerState.go | 373 ------ .../casbin/govaluate/lexerStream.go | 37 - .../github.com/casbin/govaluate/parameters.go | 32 - vendor/github.com/casbin/govaluate/parsing.go | 509 --------- .../casbin/govaluate/sanitizedParameters.go | 43 - .../casbin/govaluate/stagePlanner.go | 728 ------------ vendor/github.com/casbin/govaluate/test.sh | 33 - .../casbin/govaluate/tokenStream.go | 30 - vendor/modules.txt | 18 - 115 files changed, 1515 insertions(+), 15200 deletions(-) delete mode 100644 iam/access/access.go delete mode 100644 iam/access/adapter.go delete mode 100644 iam/access/functions.go create mode 100644 iam/policy/access.go create mode 100644 iam/policy/adapter.go rename iam/{access => policy}/adapter_test.go (61%) create mode 100644 iam/policy/enforcer.go rename iam/{access => policy}/fixtures/policy.json (100%) create mode 100644 iam/policy/manager.go rename iam/{access/access_test.go => policy/manager_test.go} (66%) create mode 100644 iam/policy/matcher.go create mode 100644 iam/policy/matcher_test.go create mode 100644 iam/policy/model.go create mode 100644 iam/policy/model_test.go delete mode 100644 vendor/github.com/casbin/casbin/v2/.gitignore delete mode 100644 vendor/github.com/casbin/casbin/v2/.golangci.yml delete mode 100644 vendor/github.com/casbin/casbin/v2/.releaserc.json delete mode 100644 vendor/github.com/casbin/casbin/v2/.travis.yml delete mode 100644 vendor/github.com/casbin/casbin/v2/CONTRIBUTING.md delete mode 100644 vendor/github.com/casbin/casbin/v2/LICENSE delete mode 100644 vendor/github.com/casbin/casbin/v2/Makefile delete mode 100644 vendor/github.com/casbin/casbin/v2/README.md delete mode 100644 vendor/github.com/casbin/casbin/v2/casbin-logo.png delete mode 100644 vendor/github.com/casbin/casbin/v2/config/config.go delete mode 100644 vendor/github.com/casbin/casbin/v2/constant/constants.go delete mode 100644 vendor/github.com/casbin/casbin/v2/effector/default_effector.go delete mode 100644 vendor/github.com/casbin/casbin/v2/effector/effector.go delete mode 100644 vendor/github.com/casbin/casbin/v2/enforcer.go delete mode 100644 vendor/github.com/casbin/casbin/v2/enforcer_cached.go delete mode 100644 vendor/github.com/casbin/casbin/v2/enforcer_cached_synced.go delete mode 100644 vendor/github.com/casbin/casbin/v2/enforcer_distributed.go delete mode 100644 vendor/github.com/casbin/casbin/v2/enforcer_interface.go delete mode 100644 vendor/github.com/casbin/casbin/v2/enforcer_synced.go delete mode 100644 vendor/github.com/casbin/casbin/v2/errors/rbac_errors.go delete mode 100644 vendor/github.com/casbin/casbin/v2/frontend.go delete mode 100644 vendor/github.com/casbin/casbin/v2/frontend_old.go delete mode 100644 vendor/github.com/casbin/casbin/v2/internal_api.go delete mode 100644 vendor/github.com/casbin/casbin/v2/log/default_logger.go delete mode 100644 vendor/github.com/casbin/casbin/v2/log/log_util.go delete mode 100644 vendor/github.com/casbin/casbin/v2/log/logger.go delete mode 100644 vendor/github.com/casbin/casbin/v2/management_api.go delete mode 100644 vendor/github.com/casbin/casbin/v2/model/assertion.go delete mode 100644 vendor/github.com/casbin/casbin/v2/model/function.go delete mode 100644 vendor/github.com/casbin/casbin/v2/model/model.go delete mode 100644 vendor/github.com/casbin/casbin/v2/model/policy.go delete mode 100644 vendor/github.com/casbin/casbin/v2/persist/adapter.go delete mode 100644 vendor/github.com/casbin/casbin/v2/persist/adapter_context.go delete mode 100644 vendor/github.com/casbin/casbin/v2/persist/adapter_filtered.go delete mode 100644 vendor/github.com/casbin/casbin/v2/persist/adapter_filtered_context.go delete mode 100644 vendor/github.com/casbin/casbin/v2/persist/batch_adapter.go delete mode 100644 vendor/github.com/casbin/casbin/v2/persist/batch_adapter_context.go delete mode 100644 vendor/github.com/casbin/casbin/v2/persist/cache/cache.go delete mode 100644 vendor/github.com/casbin/casbin/v2/persist/cache/cache_sync.go delete mode 100644 vendor/github.com/casbin/casbin/v2/persist/cache/default-cache.go delete mode 100644 vendor/github.com/casbin/casbin/v2/persist/dispatcher.go delete mode 100644 vendor/github.com/casbin/casbin/v2/persist/file-adapter/adapter.go delete mode 100644 vendor/github.com/casbin/casbin/v2/persist/file-adapter/adapter_filtered.go delete mode 100644 vendor/github.com/casbin/casbin/v2/persist/file-adapter/adapter_mock.go delete mode 100644 vendor/github.com/casbin/casbin/v2/persist/update_adapter.go delete mode 100644 vendor/github.com/casbin/casbin/v2/persist/update_adapter_context.go delete mode 100644 vendor/github.com/casbin/casbin/v2/persist/watcher.go delete mode 100644 vendor/github.com/casbin/casbin/v2/persist/watcher_ex.go delete mode 100644 vendor/github.com/casbin/casbin/v2/persist/watcher_update.go delete mode 100644 vendor/github.com/casbin/casbin/v2/rbac/context_role_manager.go delete mode 100644 vendor/github.com/casbin/casbin/v2/rbac/default-role-manager/role_manager.go delete mode 100644 vendor/github.com/casbin/casbin/v2/rbac/role_manager.go delete mode 100644 vendor/github.com/casbin/casbin/v2/rbac_api.go delete mode 100644 vendor/github.com/casbin/casbin/v2/rbac_api_synced.go delete mode 100644 vendor/github.com/casbin/casbin/v2/rbac_api_with_domains.go delete mode 100644 vendor/github.com/casbin/casbin/v2/rbac_api_with_domains_synced.go delete mode 100644 vendor/github.com/casbin/casbin/v2/util/builtin_operators.go delete mode 100644 vendor/github.com/casbin/casbin/v2/util/util.go delete mode 100644 vendor/github.com/casbin/govaluate/.gitignore delete mode 100644 vendor/github.com/casbin/govaluate/.releaserc.json delete mode 100644 vendor/github.com/casbin/govaluate/CONTRIBUTORS delete mode 100644 vendor/github.com/casbin/govaluate/EvaluableExpression.go delete mode 100644 vendor/github.com/casbin/govaluate/EvaluableExpression_sql.go delete mode 100644 vendor/github.com/casbin/govaluate/ExpressionToken.go delete mode 100644 vendor/github.com/casbin/govaluate/LICENSE delete mode 100644 vendor/github.com/casbin/govaluate/MANUAL.md delete mode 100644 vendor/github.com/casbin/govaluate/OperatorSymbol.go delete mode 100644 vendor/github.com/casbin/govaluate/README.md delete mode 100644 vendor/github.com/casbin/govaluate/TokenKind.go delete mode 100644 vendor/github.com/casbin/govaluate/evaluationStage.go delete mode 100644 vendor/github.com/casbin/govaluate/expressionFunctions.go delete mode 100644 vendor/github.com/casbin/govaluate/expressionOutputStream.go delete mode 100644 vendor/github.com/casbin/govaluate/lexerState.go delete mode 100644 vendor/github.com/casbin/govaluate/lexerStream.go delete mode 100644 vendor/github.com/casbin/govaluate/parameters.go delete mode 100644 vendor/github.com/casbin/govaluate/parsing.go delete mode 100644 vendor/github.com/casbin/govaluate/sanitizedParameters.go delete mode 100644 vendor/github.com/casbin/govaluate/stagePlanner.go delete mode 100644 vendor/github.com/casbin/govaluate/test.sh delete mode 100644 vendor/github.com/casbin/govaluate/tokenStream.go diff --git a/app/api/api.go b/app/api/api.go index 6a7f65cb..25b5875a 100644 --- a/app/api/api.go +++ b/app/api/api.go @@ -28,8 +28,8 @@ import ( httpfs "github.com/datarhei/core/v16/http/fs" "github.com/datarhei/core/v16/http/router" "github.com/datarhei/core/v16/iam" - iamaccess "github.com/datarhei/core/v16/iam/access" iamidentity "github.com/datarhei/core/v16/iam/identity" + iampolicy "github.com/datarhei/core/v16/iam/policy" "github.com/datarhei/core/v16/io/fs" "github.com/datarhei/core/v16/log" "github.com/datarhei/core/v16/math/rand" @@ -669,7 +669,7 @@ func (a *api) start(ctx context.Context) error { return err } - policyAdapter, err := iamaccess.NewJSONAdapter(rfs, "./policy.json", nil) + policyAdapter, err := iampolicy.NewJSONAdapter(rfs, "./policy.json", nil) if err != nil { return err } @@ -694,7 +694,7 @@ func (a *api) start(ctx context.Context) error { // Check if there are already file created by IAM. If not, create policies // and users based on the config in order to mimic the behaviour before IAM. if len(rfs.List("/", fs.ListOptions{Pattern: "/*.json"})) == 0 { - policies := []iamaccess.Policy{ + policies := []iampolicy.Policy{ { Name: "$anon", Domain: "$none", @@ -730,7 +730,7 @@ func (a *api) start(ctx context.Context) error { }, } - policies = append(policies, iamaccess.Policy{ + policies = append(policies, iampolicy.Policy{ Name: cfg.Storage.Memory.Auth.Username, Domain: "$none", Types: []string{"fs"}, @@ -756,7 +756,7 @@ func (a *api) start(ctx context.Context) error { users[s.Auth.Username] = user } - policies = append(policies, iamaccess.Policy{ + policies = append(policies, iampolicy.Policy{ Name: s.Auth.Username, Domain: "$none", Types: []string{"fs"}, @@ -767,7 +767,7 @@ func (a *api) start(ctx context.Context) error { } if cfg.RTMP.Enable && len(cfg.RTMP.Token) == 0 { - policies = append(policies, iamaccess.Policy{ + policies = append(policies, iampolicy.Policy{ Name: "$anon", Domain: "$none", Types: []string{"rtmp"}, @@ -777,7 +777,7 @@ func (a *api) start(ctx context.Context) error { } if cfg.SRT.Enable && len(cfg.SRT.Token) == 0 { - policies = append(policies, iamaccess.Policy{ + policies = append(policies, iampolicy.Policy{ Name: "$anon", Domain: "$none", Types: []string{"srt"}, diff --git a/cluster/client/client.go b/cluster/client/client.go index c5b1b98f..3040c036 100644 --- a/cluster/client/client.go +++ b/cluster/client/client.go @@ -13,8 +13,8 @@ import ( "github.com/datarhei/core/v16/config" "github.com/datarhei/core/v16/encoding/json" "github.com/datarhei/core/v16/ffmpeg/skills" - iamaccess "github.com/datarhei/core/v16/iam/access" iamidentity "github.com/datarhei/core/v16/iam/identity" + iampolicy "github.com/datarhei/core/v16/iam/policy" "github.com/datarhei/core/v16/restream/app" ) @@ -57,7 +57,7 @@ type UpdateIdentityRequest struct { } type SetPoliciesRequest struct { - Policies []iamaccess.Policy `json:"policies"` + Policies []iampolicy.Policy `json:"policies"` } type LockRequest struct { diff --git a/cluster/cluster.go b/cluster/cluster.go index eeb825ce..13848bae 100644 --- a/cluster/cluster.go +++ b/cluster/cluster.go @@ -23,8 +23,8 @@ import ( "github.com/datarhei/core/v16/encoding/json" "github.com/datarhei/core/v16/ffmpeg/skills" "github.com/datarhei/core/v16/iam" - iamaccess "github.com/datarhei/core/v16/iam/access" iamidentity "github.com/datarhei/core/v16/iam/identity" + iampolicy "github.com/datarhei/core/v16/iam/policy" "github.com/datarhei/core/v16/log" "github.com/datarhei/core/v16/net" "github.com/datarhei/core/v16/resources" @@ -70,7 +70,7 @@ type Cluster interface { IAMIdentityAdd(origin string, identity iamidentity.User) error IAMIdentityUpdate(origin, name string, identity iamidentity.User) error IAMIdentityRemove(origin string, name string) error - IAMPoliciesSet(origin, name string, policies []iamaccess.Policy) error + IAMPoliciesSet(origin, name string, policies []iampolicy.Policy) error LockCreate(origin string, name string, validUntil time.Time) (*kvs.Lock, error) LockDelete(origin string, name string) error diff --git a/cluster/forwarder/iam.go b/cluster/forwarder/iam.go index bd695380..b310604d 100644 --- a/cluster/forwarder/iam.go +++ b/cluster/forwarder/iam.go @@ -2,8 +2,8 @@ package forwarder import ( apiclient "github.com/datarhei/core/v16/cluster/client" - iamaccess "github.com/datarhei/core/v16/iam/access" iamidentity "github.com/datarhei/core/v16/iam/identity" + iampolicy "github.com/datarhei/core/v16/iam/policy" ) func (f *Forwarder) IAMIdentityAdd(origin string, identity iamidentity.User) error { @@ -38,7 +38,7 @@ func (f *Forwarder) IAMIdentityUpdate(origin, name string, identity iamidentity. return reconstructError(client.IAMIdentityUpdate(origin, name, r)) } -func (f *Forwarder) IAMPoliciesSet(origin, name string, policies []iamaccess.Policy) error { +func (f *Forwarder) IAMPoliciesSet(origin, name string, policies []iampolicy.Policy) error { if origin == "" { origin = f.ID } diff --git a/cluster/iam.go b/cluster/iam.go index 2dc30616..03b044e7 100644 --- a/cluster/iam.go +++ b/cluster/iam.go @@ -8,8 +8,8 @@ import ( clusteriamadapter "github.com/datarhei/core/v16/cluster/iam/adapter" "github.com/datarhei/core/v16/cluster/store" "github.com/datarhei/core/v16/iam" - iamaccess "github.com/datarhei/core/v16/iam/access" iamidentity "github.com/datarhei/core/v16/iam/identity" + iampolicy "github.com/datarhei/core/v16/iam/policy" ) func (c *cluster) IAM(superuser iamidentity.User, jwtRealm, jwtSecret string) (iam.IAM, error) { @@ -54,13 +54,13 @@ func (c *cluster) ListIdentity(name string) (time.Time, iamidentity.User, error) return user.UpdatedAt, user.Users[0], nil } -func (c *cluster) ListPolicies() (time.Time, []iamaccess.Policy) { +func (c *cluster) ListPolicies() (time.Time, []iampolicy.Policy) { policies := c.store.IAMPolicyList() return policies.UpdatedAt, policies.Policies } -func (c *cluster) ListUserPolicies(name string) (time.Time, []iamaccess.Policy) { +func (c *cluster) ListUserPolicies(name string) (time.Time, []iampolicy.Policy) { policies := c.store.IAMIdentityPolicyList(name) return policies.UpdatedAt, policies.Policies @@ -101,7 +101,7 @@ func (c *cluster) IAMIdentityUpdate(origin, name string, identity iamidentity.Us return c.applyCommand(cmd) } -func (c *cluster) IAMPoliciesSet(origin, name string, policies []iamaccess.Policy) error { +func (c *cluster) IAMPoliciesSet(origin, name string, policies []iampolicy.Policy) error { if !c.IsRaftLeader() { return c.forwarder.IAMPoliciesSet(origin, name, policies) } diff --git a/cluster/iam/adapter/policy.go b/cluster/iam/adapter/policy.go index b6250ece..7df2d203 100644 --- a/cluster/iam/adapter/policy.go +++ b/cluster/iam/adapter/policy.go @@ -4,9 +4,7 @@ import ( "sync" "github.com/datarhei/core/v16/cluster/store" - iamaccess "github.com/datarhei/core/v16/iam/access" - - "github.com/casbin/casbin/v2/model" + "github.com/datarhei/core/v16/iam/policy" ) type policyAdapter struct { @@ -15,7 +13,7 @@ type policyAdapter struct { lock sync.RWMutex } -func NewPolicyAdapter(store store.Store) (iamaccess.Adapter, error) { +func NewPolicyAdapter(store store.Store) (policy.Adapter, error) { a := &policyAdapter{ store: store, domains: map[string]struct{}{}, @@ -24,13 +22,13 @@ func NewPolicyAdapter(store store.Store) (iamaccess.Adapter, error) { return a, nil } -func (a *policyAdapter) LoadPolicy(model model.Model) error { - policies := a.store.IAMPolicyList() +func (a *policyAdapter) LoadPolicy(model policy.Model) error { + storePolicies := a.store.IAMPolicyList() - rules := [][]string{} + policies := []policy.Policy{} domains := map[string]struct{}{} - for _, p := range policies.Policies { + for _, p := range storePolicies.Policies { if len(p.Domain) == 0 { p.Domain = "$none" } @@ -39,19 +37,20 @@ func (a *policyAdapter) LoadPolicy(model model.Model) error { p.Types = []string{"$none"} } - rule := []string{ - p.Name, - p.Domain, - iamaccess.EncodeResource(p.Types, p.Resource), - iamaccess.EncodeActions(p.Actions), + policy := policy.Policy{ + Name: p.Name, + Domain: p.Domain, + Types: p.Types, + Resource: p.Resource, + Actions: p.Actions, } domains[p.Domain] = struct{}{} - rules = append(rules, rule) + policies = append(policies, policy) } - model.AddPolicies("p", "p", rules) + model.AddPolicies(policies) a.lock.Lock() a.domains = domains @@ -60,27 +59,23 @@ func (a *policyAdapter) LoadPolicy(model model.Model) error { return nil } -func (a *policyAdapter) SavePolicy(model model.Model) error { +func (a *policyAdapter) SavePolicy(_ policy.Model) error { return nil } -func (a *policyAdapter) AddPolicy(sec, ptype string, rule []string) error { +func (a *policyAdapter) AddPolicy(_ policy.Policy) error { return nil } -func (a *policyAdapter) AddPolicies(sec string, ptype string, rules [][]string) error { +func (a *policyAdapter) AddPolicies(_ []policy.Policy) error { return nil } -func (a *policyAdapter) RemovePolicy(sec string, ptype string, rule []string) error { +func (a *policyAdapter) RemovePolicy(_ policy.Policy) error { return nil } -func (a *policyAdapter) RemovePolicies(sec string, ptype string, rules [][]string) error { - return nil -} - -func (a *policyAdapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error { +func (a *policyAdapter) RemovePolicies(_ []policy.Policy) error { return nil } diff --git a/cluster/iam/iam.go b/cluster/iam/iam.go index fc57fdc0..0b119d4c 100644 --- a/cluster/iam/iam.go +++ b/cluster/iam/iam.go @@ -5,8 +5,8 @@ import ( "github.com/datarhei/core/v16/cluster/store" "github.com/datarhei/core/v16/iam" - "github.com/datarhei/core/v16/iam/access" "github.com/datarhei/core/v16/iam/identity" + "github.com/datarhei/core/v16/iam/policy" "github.com/datarhei/core/v16/log" ) @@ -84,7 +84,7 @@ func (m *manager) RemovePolicy(name, domain string, types []string, resource str return ErrClusterMode } -func (m *manager) ListPolicies(name, domain string, types []string, resource string, actions []string) []access.Policy { +func (m *manager) ListPolicies(name, domain string, types []string, resource string, actions []string) []policy.Policy { return m.iam.ListPolicies(name, domain, types, resource, actions) } diff --git a/cluster/store/identity_test.go b/cluster/store/identity_test.go index 0253040e..7f74d765 100644 --- a/cluster/store/identity_test.go +++ b/cluster/store/identity_test.go @@ -4,8 +4,8 @@ import ( "testing" "time" - "github.com/datarhei/core/v16/iam/access" "github.com/datarhei/core/v16/iam/identity" + "github.com/datarhei/core/v16/iam/policy" "github.com/stretchr/testify/require" ) @@ -394,7 +394,7 @@ func TestUpdateIdentityWithPolicies(t *testing.T) { Name: "foobar", } - policies := []access.Policy{ + policies := []policy.Policy{ { Name: "bla", Domain: "bla", diff --git a/cluster/store/policy.go b/cluster/store/policy.go index 2060cf7f..04ded03a 100644 --- a/cluster/store/policy.go +++ b/cluster/store/policy.go @@ -4,7 +4,7 @@ import ( "fmt" "time" - "github.com/datarhei/core/v16/iam/access" + "github.com/datarhei/core/v16/iam/policy" ) func (s *store) setPolicies(cmd CommandSetPolicies) error { @@ -80,9 +80,9 @@ func (s *store) IAMIdentityPolicyList(name string) Policies { } // updatePolicy updates a policy such that the resource type is split off the resource -func (s *store) updatePolicy(p access.Policy) access.Policy { +func (s *store) updatePolicy(p policy.Policy) policy.Policy { if len(p.Types) == 0 { - p.Types, p.Resource = access.DecodeResource(p.Resource) + p.Types, p.Resource = policy.DecodeResource(p.Resource) } return p diff --git a/cluster/store/policy_test.go b/cluster/store/policy_test.go index dde9cfc3..c00efc76 100644 --- a/cluster/store/policy_test.go +++ b/cluster/store/policy_test.go @@ -3,8 +3,8 @@ package store import ( "testing" - "github.com/datarhei/core/v16/iam/access" "github.com/datarhei/core/v16/iam/identity" + "github.com/datarhei/core/v16/iam/policy" "github.com/stretchr/testify/require" ) @@ -30,7 +30,7 @@ func TestSetPoliciesCommand(t *testing.T) { Operation: OpSetPolicies, Data: CommandSetPolicies{ Name: "foobar", - Policies: []access.Policy{ + Policies: []policy.Policy{ { Name: "bla", Domain: "bla", @@ -59,7 +59,7 @@ func TestSetPolicies(t *testing.T) { Name: "foobar", } - policies := []access.Policy{ + policies := []policy.Policy{ { Name: "bla", Domain: "bla", diff --git a/cluster/store/store.go b/cluster/store/store.go index d26b7e13..4476ad82 100644 --- a/cluster/store/store.go +++ b/cluster/store/store.go @@ -7,8 +7,8 @@ import ( "time" "github.com/datarhei/core/v16/encoding/json" - "github.com/datarhei/core/v16/iam/access" "github.com/datarhei/core/v16/iam/identity" + "github.com/datarhei/core/v16/iam/policy" "github.com/datarhei/core/v16/log" "github.com/datarhei/core/v16/restream/app" @@ -56,7 +56,7 @@ type Users struct { type Policies struct { UpdatedAt time.Time - Policies []access.Policy + Policies []policy.Policy } type Value struct { @@ -154,7 +154,7 @@ type CommandRemoveIdentity struct { type CommandSetPolicies struct { Name string - Policies []access.Policy + Policies []policy.Policy } type CommandCreateLock struct { @@ -196,7 +196,7 @@ type storeData struct { Policies struct { UpdatedAt time.Time - Policies map[string][]access.Policy + Policies map[string][]policy.Policy } Locks map[string]time.Time @@ -217,7 +217,7 @@ func (s *storeData) init() { s.Users.Users = map[string]identity.User{} s.Users.userlist = identity.NewUserList() s.Policies.UpdatedAt = now - s.Policies.Policies = map[string][]access.Policy{} + s.Policies.Policies = map[string][]policy.Policy{} s.Locks = map[string]time.Time{} s.KVS = map[string]Value{} s.Nodes = map[string]Node{} diff --git a/go.mod b/go.mod index 95e0ac01..d41163e9 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/datarhei/core/v16 -go 1.21.0 +go 1.22.0 toolchain go1.22.1 @@ -11,7 +11,6 @@ require ( github.com/andybalholm/brotli v1.1.0 github.com/atrox/haikunatorgo/v2 v2.0.1 github.com/caddyserver/certmagic v0.21.3 - github.com/casbin/casbin/v2 v2.97.0 github.com/datarhei/gosrt v0.6.0 github.com/datarhei/joy4 v0.0.0-20240603190808-b1407345907e github.com/fujiwara/shapeio v1.0.0 @@ -60,7 +59,6 @@ require ( github.com/beorn7/perks v1.0.1 // indirect github.com/boltdb/bolt v1.3.1 // indirect github.com/caddyserver/zerossl v0.1.3 // indirect - github.com/casbin/govaluate v1.2.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.4 // indirect github.com/davecgh/go-spew v1.1.1 // indirect diff --git a/go.sum b/go.sum index 1b8f149c..4d098652 100644 --- a/go.sum +++ b/go.sum @@ -39,11 +39,6 @@ github.com/caddyserver/certmagic v0.21.3 h1:pqRRry3yuB4CWBVq9+cUqu+Y6E2z8TswbhNx github.com/caddyserver/certmagic v0.21.3/go.mod h1:Zq6pklO9nVRl3DIFUw9gVUfXKdpc/0qwTUAQMBlfgtI= github.com/caddyserver/zerossl v0.1.3 h1:onS+pxp3M8HnHpN5MMbOMyNjmTheJyWRaZYwn+YTAyA= github.com/caddyserver/zerossl v0.1.3/go.mod h1:CxA0acn7oEGO6//4rtrRjYgEoa4MFw/XofZnrYwGqG4= -github.com/casbin/casbin/v2 v2.97.0 h1:FFHIzY+6fLIcoAB/DKcG5xvscUo9XqRpBniRYhlPWkg= -github.com/casbin/casbin/v2 v2.97.0/go.mod h1:jX8uoN4veP85O/n2674r2qtfSXI6myvxW85f6TH50fw= -github.com/casbin/govaluate v1.1.0/go.mod h1:G/UnbIjZk/0uMNaLwZZmFQrR72tYRZWQkO70si/iR7A= -github.com/casbin/govaluate v1.2.0 h1:wXCXFmqyY+1RwiKfYo3jMKyrtZmOL3kHwaqDyCPOYak= -github.com/casbin/govaluate v1.2.0/go.mod h1:G/UnbIjZk/0uMNaLwZZmFQrR72tYRZWQkO70si/iR7A= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= @@ -109,8 +104,6 @@ github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOW github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= -github.com/golang/mock v1.4.4 h1:l75CXGRSwbaYNpl/Z2X1XIIAMSCquvXgpVZDhwEIJsc= -github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -338,13 +331,11 @@ golang.org/x/crypto v0.25.0/go.mod h1:T+wALwcMOSE0kXgUAnPAHqTLW+XHgcELELW8VaDgm/ golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8= golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys= golang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= @@ -372,7 +363,6 @@ golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= -golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg= golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/http/api/iam.go b/http/api/iam.go index 3109e51f..816b27fc 100644 --- a/http/api/iam.go +++ b/http/api/iam.go @@ -3,8 +3,8 @@ package api import ( "time" - "github.com/datarhei/core/v16/iam/access" "github.com/datarhei/core/v16/iam/identity" + "github.com/datarhei/core/v16/iam/policy" ) type IAMUser struct { @@ -17,7 +17,7 @@ type IAMUser struct { Policies []IAMPolicy `json:"policies"` } -func (u *IAMUser) Marshal(user identity.User, policies []access.Policy) { +func (u *IAMUser) Marshal(user identity.User, policies []policy.Policy) { u.CreatedAt = user.CreatedAt.Unix() u.UpdatedAt = user.UpdatedAt.Unix() u.Name = user.Name @@ -52,7 +52,7 @@ func (u *IAMUser) Marshal(user identity.User, policies []access.Policy) { } } -func (u *IAMUser) Unmarshal() (identity.User, []access.Policy) { +func (u *IAMUser) Unmarshal() (identity.User, []policy.Policy) { iamuser := identity.User{ CreatedAt: time.Unix(u.CreatedAt, 0), UpdatedAt: time.Unix(u.UpdatedAt, 0), @@ -79,10 +79,10 @@ func (u *IAMUser) Unmarshal() (identity.User, []access.Policy) { }, } - iampolicies := []access.Policy{} + iampolicies := []policy.Policy{} for _, p := range u.Policies { - iampolicies = append(iampolicies, access.Policy{ + iampolicies = append(iampolicies, policy.Policy{ Name: u.Name, Domain: p.Domain, Types: p.Types, diff --git a/http/handler/api/cluster_iam.go b/http/handler/api/cluster_iam.go index 91ed30e0..3b177734 100644 --- a/http/handler/api/cluster_iam.go +++ b/http/handler/api/cluster_iam.go @@ -7,8 +7,8 @@ import ( "github.com/datarhei/core/v16/cluster/store" "github.com/datarhei/core/v16/http/api" "github.com/datarhei/core/v16/http/handler/util" - "github.com/datarhei/core/v16/iam/access" "github.com/datarhei/core/v16/iam/identity" + "github.com/datarhei/core/v16/iam/policy" "github.com/labstack/echo/v4" ) @@ -198,14 +198,14 @@ func (h *ClusterHandler) IAMIdentityUpdatePolicies(c echo.Context) error { } } - accessPolicies := []access.Policy{} + accessPolicies := []policy.Policy{} for _, p := range policies { if !h.iam.Enforce(ctxuser, p.Domain, "iam", iamuser.Name, "write") { return api.Err(http.StatusForbidden, "", "not allowed to write policy: %v", p) } - accessPolicies = append(accessPolicies, access.Policy{ + accessPolicies = append(accessPolicies, policy.Policy{ Name: name, Domain: p.Domain, Types: p.Types, diff --git a/http/handler/api/process_test.go b/http/handler/api/process_test.go index fd94b385..bf076af3 100644 --- a/http/handler/api/process_test.go +++ b/http/handler/api/process_test.go @@ -12,8 +12,8 @@ import ( "github.com/datarhei/core/v16/http/api" "github.com/datarhei/core/v16/http/mock" "github.com/datarhei/core/v16/iam" - "github.com/datarhei/core/v16/iam/access" "github.com/datarhei/core/v16/iam/identity" + "github.com/datarhei/core/v16/iam/policy" "github.com/datarhei/core/v16/io/fs" "github.com/labstack/echo/v4" @@ -37,7 +37,7 @@ func getDummyRestreamHandler() (*ProcessHandler, error) { return nil, fmt.Errorf("failed to create memory filesystem: %w", err) } - policyAdapter, err := access.NewJSONAdapter(memfs, "./policy.json", nil) + policyAdapter, err := policy.NewJSONAdapter(memfs, "./policy.json", nil) if err != nil { return nil, err } diff --git a/http/middleware/iam/iam_test.go b/http/middleware/iam/iam_test.go index 621c5bee..62a495b0 100644 --- a/http/middleware/iam/iam_test.go +++ b/http/middleware/iam/iam_test.go @@ -14,8 +14,8 @@ import ( apihandler "github.com/datarhei/core/v16/http/handler/api" "github.com/datarhei/core/v16/http/validator" "github.com/datarhei/core/v16/iam" - iamaccess "github.com/datarhei/core/v16/iam/access" iamidentity "github.com/datarhei/core/v16/iam/identity" + "github.com/datarhei/core/v16/iam/policy" "github.com/datarhei/core/v16/io/fs" "github.com/labstack/echo/v4" @@ -30,7 +30,7 @@ func getIAM() (iam.IAM, error) { return nil, err } - policyAdapter, err := iamaccess.NewJSONAdapter(dummyfs, "./policy.json", nil) + policyAdapter, err := policy.NewJSONAdapter(dummyfs, "./policy.json", nil) if err != nil { return nil, err } diff --git a/iam/access/access.go b/iam/access/access.go deleted file mode 100644 index 13d9c088..00000000 --- a/iam/access/access.go +++ /dev/null @@ -1,182 +0,0 @@ -package access - -import ( - "sort" - "strings" - - "github.com/datarhei/core/v16/log" - - "github.com/casbin/casbin/v2" - "github.com/casbin/casbin/v2/model" -) - -type Policy struct { - Name string - Domain string - Types []string - Resource string - Actions []string -} - -type Enforcer interface { - Enforce(name, domain, rtype, resource, action string) (bool, string) - - HasDomain(name string) bool - ListDomains() []string -} - -type Manager interface { - Enforcer - - HasPolicy(name, domain string, types []string, resource string, actions []string) bool - AddPolicy(name, domain string, types []string, resource string, actions []string) error - RemovePolicy(name, domain string, types []string, resource string, actions []string) error - ListPolicies(name, domain string, types []string, resource string, actions []string) []Policy - ReloadPolicies() error -} - -type access struct { - logger log.Logger - - adapter Adapter - model model.Model - enforcer *casbin.SyncedEnforcer -} - -type Config struct { - Adapter Adapter - Logger log.Logger -} - -func New(config Config) (Manager, error) { - am := &access{ - adapter: config.Adapter, - logger: config.Logger, - } - - if am.logger == nil { - am.logger = log.New("") - } - - m := model.NewModel() - m.AddDef("r", "r", "sub, dom, obj, act") - m.AddDef("p", "p", "sub, dom, obj, act") - m.AddDef("g", "g", "_, _, _") - m.AddDef("e", "e", "some(where (p.eft == allow))") - m.AddDef("m", "m", `g(r.sub, p.sub, r.dom) && r.dom == p.dom && ResourceMatch(r.obj, p.obj) && ActionMatch(r.act, p.act) || r.sub == "$superuser"`) - - e, err := casbin.NewSyncedEnforcer(m, am.adapter) - if err != nil { - return nil, err - } - - e.AddFunction("ResourceMatch", resourceMatchFunc) - e.AddFunction("ActionMatch", actionMatchFunc) - - am.enforcer = e - am.model = m - - return am, nil -} - -func (am *access) HasPolicy(name, domain string, types []string, resource string, actions []string) bool { - policy := []string{name, domain, EncodeResource(types, resource), EncodeActions(actions)} - - hasPolicy, _ := am.enforcer.HasPolicy(policy) - - return hasPolicy -} - -func (am *access) AddPolicy(name, domain string, types []string, resource string, actions []string) error { - policy := []string{name, domain, EncodeResource(types, resource), EncodeActions(actions)} - - if hasPolicy, _ := am.enforcer.HasPolicy(policy); hasPolicy { - return nil - } - - _, err := am.enforcer.AddPolicy(policy) - - return err -} - -func (am *access) RemovePolicy(name, domain string, types []string, resource string, actions []string) error { - policies, err := am.enforcer.GetFilteredPolicy(0, name, domain, EncodeResource(types, resource), EncodeActions(actions)) - if err != nil { - return err - } - - _, err = am.enforcer.RemovePolicies(policies) - - return err -} - -func (am *access) ListPolicies(name, domain string, types []string, resource string, actions []string) []Policy { - policies := []Policy{} - - ps, err := am.enforcer.GetFilteredPolicy(0, name, domain, EncodeResource(types, resource), EncodeActions(actions)) - if err != nil { - return policies - } - - for _, p := range ps { - types, resource := DecodeResource(p[2]) - policies = append(policies, Policy{ - Name: p[0], - Domain: p[1], - Types: types, - Resource: resource, - Actions: DecodeActions(p[3]), - }) - } - - return policies -} - -func (am *access) ReloadPolicies() error { - am.enforcer.ClearPolicy() - - return am.enforcer.LoadPolicy() -} - -func (am *access) HasDomain(name string) bool { - return am.adapter.HasDomain(name) -} - -func (am *access) ListDomains() []string { - return am.adapter.AllDomains() -} - -func (am *access) Enforce(name, domain, rtype, resource, action string) (bool, string) { - resource = rtype + ":" + resource - - ok, rule, _ := am.enforcer.EnforceEx(name, domain, resource, action) - - return ok, strings.Join(rule, ", ") -} - -func EncodeActions(actions []string) string { - return strings.Join(actions, "|") -} - -func DecodeActions(actions string) []string { - return strings.Split(actions, "|") -} - -func EncodeResource(types []string, resource string) string { - if len(types) == 0 { - return resource - } - - sort.Strings(types) - - return strings.Join(types, "|") + ":" + resource -} - -func DecodeResource(resource string) ([]string, string) { - before, after, found := strings.Cut(resource, ":") - if !found { - return []string{"$none"}, resource - } - - return strings.Split(before, "|"), after -} diff --git a/iam/access/adapter.go b/iam/access/adapter.go deleted file mode 100644 index 308bd578..00000000 --- a/iam/access/adapter.go +++ /dev/null @@ -1,588 +0,0 @@ -package access - -import ( - "errors" - "fmt" - "sort" - "strings" - "sync" - - "github.com/datarhei/core/v16/encoding/json" - "github.com/datarhei/core/v16/io/fs" - "github.com/datarhei/core/v16/log" - - "github.com/casbin/casbin/v2/model" - "github.com/casbin/casbin/v2/persist" -) - -// Adapter is the file adapter for Casbin. -// It can load policy from file or save policy to file. -type adapter struct { - fs fs.Filesystem - filePath string - logger log.Logger - domains []Domain - lock sync.Mutex -} - -type Adapter interface { - persist.BatchAdapter - - AllDomains() []string - HasDomain(string) bool -} - -func NewJSONAdapter(fs fs.Filesystem, filePath string, logger log.Logger) (Adapter, error) { - a := &adapter{ - fs: fs, - filePath: filePath, - logger: logger, - } - - if a.fs == nil { - return nil, fmt.Errorf("a filesystem has to be provided") - } - - if len(a.filePath) == 0 { - return nil, fmt.Errorf("invalid file path, file path cannot be empty") - } - - if a.logger == nil { - a.logger = log.New("") - } - - return a, nil -} - -// Adapter -func (a *adapter) LoadPolicy(model model.Model) error { - a.lock.Lock() - defer a.lock.Unlock() - - return a.loadPolicyFile(model) -} - -func (a *adapter) loadPolicyFile(model model.Model) error { - if _, err := a.fs.Stat(a.filePath); err != nil { - if errors.Is(err, fs.ErrNotExist) { - a.domains = []Domain{} - return nil - } - - return err - } - - data, err := a.fs.ReadFile(a.filePath) - if err != nil { - return err - } - - domains := []Domain{} - - err = json.Unmarshal(data, &domains) - if err != nil { - return err - } - - rule := [5]string{} - for _, domain := range domains { - rule[0] = "p" - rule[2] = domain.Name - for name, roles := range domain.Roles { - rule[1] = "role:" + name - for _, role := range roles { - rule[3] = role.Resource - rule[4] = formatList(role.Actions) - - if err := a.importPolicy(model, rule[0:5]); err != nil { - return err - } - } - } - - for _, policy := range domain.Policies { - rule[1] = policy.Username - rule[3] = policy.Resource - rule[4] = formatList(policy.Actions) - - if err := a.importPolicy(model, rule[0:5]); err != nil { - return err - } - } - - rule[0] = "g" - rule[3] = domain.Name - - for _, ug := range domain.UserRoles { - rule[1] = ug.Username - rule[2] = "role:" + ug.Role - - if err := a.importPolicy(model, rule[0:4]); err != nil { - return err - } - } - } - - a.domains = domains - - return nil -} - -func (a *adapter) importPolicy(model model.Model, rule []string) error { - copiedRule := make([]string, len(rule)) - copy(copiedRule, rule) - - a.logger.Debug().WithFields(log.Fields{ - "subject": copiedRule[1], - "domain": copiedRule[2], - "resource": copiedRule[3], - "actions": copiedRule[4], - }).Log("Imported policy") - - ok, err := model.HasPolicyEx(copiedRule[0], copiedRule[0], copiedRule[1:]) - if err != nil { - return err - } - if ok { - return nil // skip duplicated policy - } - - model.AddPolicy(copiedRule[0], copiedRule[0], copiedRule[1:]) - - return nil -} - -// Adapter -func (a *adapter) SavePolicy(model model.Model) error { - a.lock.Lock() - defer a.lock.Unlock() - - return a.savePolicyFile() -} - -func (a *adapter) savePolicyFile() error { - jsondata, err := json.MarshalIndent(a.domains, "", " ") - if err != nil { - return err - } - - _, _, err = a.fs.WriteFileSafe(a.filePath, jsondata) - - return err -} - -// Adapter (auto-save) -func (a *adapter) AddPolicy(sec, ptype string, rule []string) error { - a.lock.Lock() - defer a.lock.Unlock() - - err := a.addPolicy(ptype, rule) - if err != nil { - return err - } - - return a.savePolicyFile() -} - -// BatchAdapter (auto-save) -func (a *adapter) AddPolicies(sec string, ptype string, rules [][]string) error { - a.lock.Lock() - defer a.lock.Unlock() - - for _, rule := range rules { - err := a.addPolicy(ptype, rule) - if err != nil { - return err - } - } - - return a.savePolicyFile() -} - -func (a *adapter) addPolicy(ptype string, rule []string) error { - ok, err := a.hasPolicy(ptype, rule) - if err != nil { - return err - } - - if ok { - // the policy is already there, nothing to add - return nil - } - - username := "" - role := "" - domain := "" - resource := "" - actions := "" - - if ptype == "p" { - username = rule[0] - domain = rule[1] - resource = rule[2] - actions = formatList(rule[3]) - - a.logger.Debug().WithFields(log.Fields{ - "subject": username, - "domain": domain, - "resource": resource, - "actions": actions, - }).Log("Adding policy") - } else if ptype == "g" { - username = rule[0] - role = rule[1] - domain = rule[2] - - a.logger.Debug().WithFields(log.Fields{ - "subject": username, - "role": role, - "domain": domain, - }).Log("Adding role mapping") - } else { - return fmt.Errorf("unknown ptype: %s", ptype) - } - - var dom *Domain = nil - for i := range a.domains { - if a.domains[i].Name == domain { - dom = &a.domains[i] - break - } - } - - if dom == nil { - g := Domain{ - Name: domain, - Roles: map[string][]Role{}, - UserRoles: []MapUserRole{}, - Policies: []DomainPolicy{}, - } - - a.domains = append(a.domains, g) - dom = &a.domains[len(a.domains)-1] - } - - if ptype == "p" { - if strings.HasPrefix(username, "role:") { - if dom.Roles == nil { - dom.Roles = make(map[string][]Role) - } - - role := strings.TrimPrefix(username, "role:") - dom.Roles[role] = append(dom.Roles[role], Role{ - Resource: resource, - Actions: actions, - }) - } else { - dom.Policies = append(dom.Policies, DomainPolicy{ - Username: username, - Role: Role{ - Resource: resource, - Actions: actions, - }, - }) - } - } else { - dom.UserRoles = append(dom.UserRoles, MapUserRole{ - Username: username, - Role: strings.TrimPrefix(role, "role:"), - }) - } - - return nil -} - -func (a *adapter) hasPolicy(ptype string, rule []string) (bool, error) { - var username string - var role string - var domain string - var resource string - var actions string - - if ptype == "p" { - if len(rule) < 4 { - return false, fmt.Errorf("invalid rule length. must be 'user/role, domain, resource, actions'") - } - - username = rule[0] - domain = rule[1] - resource = rule[2] - actions = formatList(rule[3]) - } else if ptype == "g" { - if len(rule) < 3 { - return false, fmt.Errorf("invalid rule length. must be 'user, role, domain'") - } - - username = rule[0] - role = rule[1] - domain = rule[2] - } else { - return false, fmt.Errorf("unknown ptype: %s", ptype) - } - - var dom *Domain = nil - for i := range a.domains { - if a.domains[i].Name == domain { - dom = &a.domains[i] - break - } - } - - if dom == nil { - // if we can't find any domain with that name, then the policy doesn't exist - return false, nil - } - - if ptype == "p" { - isRole := false - if strings.HasPrefix(username, "role:") { - isRole = true - username = strings.TrimPrefix(username, "role:") - } - - if isRole { - roles, ok := dom.Roles[username] - if !ok { - // unknown role, policy doesn't exist - return false, nil - } - - for _, role := range roles { - if role.Resource == resource && formatList(role.Actions) == actions { - return true, nil - } - } - } else { - for _, p := range dom.Policies { - if p.Username == username && p.Resource == resource && formatList(p.Actions) == actions { - return true, nil - } - } - } - } else { - role = strings.TrimPrefix(role, "role:") - for _, user := range dom.UserRoles { - if user.Username == username && user.Role == role { - return true, nil - } - } - } - - return false, nil -} - -// Adapter (auto-save) -func (a *adapter) RemovePolicy(sec string, ptype string, rule []string) error { - a.lock.Lock() - defer a.lock.Unlock() - - err := a.removePolicy(ptype, rule) - if err != nil { - return err - } - - return a.savePolicyFile() -} - -// BatchAdapter (auto-save) -func (a *adapter) RemovePolicies(sec string, ptype string, rules [][]string) error { - a.lock.Lock() - defer a.lock.Unlock() - - for _, rule := range rules { - err := a.removePolicy(ptype, rule) - if err != nil { - return err - } - } - - return a.savePolicyFile() -} - -func (a *adapter) removePolicy(ptype string, rule []string) error { - ok, err := a.hasPolicy(ptype, rule) - if err != nil { - return err - } - - if !ok { - // the policy is not there, nothing to remove - return nil - } - - username := "" - role := "" - domain := "" - resource := "" - actions := "" - - if ptype == "p" { - username = rule[0] - domain = rule[1] - resource = rule[2] - actions = formatList(rule[3]) - - a.logger.Debug().WithFields(log.Fields{ - "subject": username, - "domain": domain, - "resource": resource, - "actions": actions, - }).Log("Removing policy") - } else if ptype == "g" { - username = rule[0] - role = rule[1] - domain = rule[2] - - a.logger.Debug().WithFields(log.Fields{ - "subject": username, - "role": role, - "domain": domain, - }).Log("Removing role mapping") - } else { - return fmt.Errorf("unknown ptype: %s", ptype) - } - - var dom *Domain = nil - for i := range a.domains { - if a.domains[i].Name == domain { - dom = &a.domains[i] - break - } - } - - if ptype == "p" { - isRole := false - if strings.HasPrefix(username, "role:") { - isRole = true - username = strings.TrimPrefix(username, "role:") - } - - if isRole { - roles := dom.Roles[username] - - newRoles := []Role{} - - for _, role := range roles { - if role.Resource == resource && formatList(role.Actions) == actions { - continue - } - - newRoles = append(newRoles, role) - } - - dom.Roles[username] = newRoles - } else { - policies := []DomainPolicy{} - - for _, p := range dom.Policies { - if p.Username == username && p.Resource == resource && formatList(p.Actions) == actions { - continue - } - - policies = append(policies, p) - } - - dom.Policies = policies - } - } else { - role = strings.TrimPrefix(role, "role:") - - users := []MapUserRole{} - - for _, user := range dom.UserRoles { - if user.Username == username && user.Role == role { - continue - } - - users = append(users, user) - } - - dom.UserRoles = users - } - - // Remove the group if there are no rules and policies - if len(dom.Roles) == 0 && len(dom.UserRoles) == 0 && len(dom.Policies) == 0 { - groups := []Domain{} - - for _, g := range a.domains { - if g.Name == dom.Name { - continue - } - - groups = append(groups, g) - } - - a.domains = groups - } - - return nil -} - -// Adapter -func (a *adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error { - return fmt.Errorf("not implemented") -} - -func (a *adapter) AllDomains() []string { - a.lock.Lock() - defer a.lock.Unlock() - - names := []string{} - - for _, domain := range a.domains { - if domain.Name[0] == '$' { - continue - } - - names = append(names, domain.Name) - } - - return names -} - -func (a *adapter) HasDomain(name string) bool { - a.lock.Lock() - defer a.lock.Unlock() - - for _, domain := range a.domains { - if domain.Name[0] == '$' { - continue - } - - if domain.Name == name { - return true - } - } - - return false -} - -type Domain struct { - Name string `json:"name"` - Roles map[string][]Role `json:"roles"` - UserRoles []MapUserRole `json:"userroles"` - Policies []DomainPolicy `json:"policies"` -} - -type Role struct { - Resource string `json:"resource"` - Actions string `json:"actions"` -} - -type MapUserRole struct { - Username string `json:"username"` - Role string `json:"role"` -} - -type DomainPolicy struct { - Username string `json:"username"` - Role -} - -func formatList(list string) string { - a := strings.Split(list, "|") - - sort.Strings(a) - - return strings.Join(a, "|") -} diff --git a/iam/access/functions.go b/iam/access/functions.go deleted file mode 100644 index 07bc70e9..00000000 --- a/iam/access/functions.go +++ /dev/null @@ -1,116 +0,0 @@ -package access - -import ( - "strings" - "sync" - - "github.com/datarhei/core/v16/glob" -) - -var globcache = map[string]glob.Glob{} -var globcacheMu = sync.RWMutex{} - -func resourceMatch(request, policy string) bool { - reqPrefix, reqResource := getPrefix(request) - polPrefix, polResource := getPrefix(policy) - - var match bool = false - var err error = nil - - reqType := strings.ToLower(reqPrefix) - polTypes := strings.Split(strings.ToLower(polPrefix), "|") - - for _, polType := range polTypes { - if reqType != polType { - continue - } - - match = true - break - } - - if !match { - return false - } - - match = false - - key := reqType + polResource - - if reqType == "api" || reqType == "fs" || reqType == "rtmp" || reqType == "srt" { - globcacheMu.RLock() - matcher, ok := globcache[key] - globcacheMu.RUnlock() - if !ok { - matcher, err = glob.Compile(polResource, rune('/')) - if err != nil { - return false - } - globcacheMu.Lock() - globcache[key] = matcher - globcacheMu.Unlock() - } - - match = matcher.Match(reqResource) - } else { - globcacheMu.RLock() - matcher, ok := globcache[key] - globcacheMu.RUnlock() - if !ok { - matcher, err = glob.Compile(polResource) - if err != nil { - return false - } - globcacheMu.Lock() - globcache[key] = matcher - globcacheMu.Unlock() - } - - match = matcher.Match(reqResource) - } - - return match -} - -func resourceMatchFunc(args ...interface{}) (interface{}, error) { - request := args[0].(string) - policy := args[1].(string) - - return (bool)(resourceMatch(request, policy)), nil -} - -func actionMatch(request string, policy string) bool { - request = strings.ToUpper(request) - actions := strings.Split(strings.ToUpper(policy), "|") - if len(actions) == 0 { - return false - } - - if len(actions) == 1 && actions[0] == "ANY" { - return true - } - - for _, a := range actions { - if request == a { - return true - } - } - - return false -} - -func actionMatchFunc(args ...interface{}) (interface{}, error) { - request := args[0].(string) - policy := args[1].(string) - - return (bool)(actionMatch(request, policy)), nil -} - -func getPrefix(s string) (string, string) { - prefix, resource, found := strings.Cut(s, ":") - if !found { - return "", s - } - - return prefix, resource -} diff --git a/iam/iam.go b/iam/iam.go index 6b22404b..d84230e3 100644 --- a/iam/iam.go +++ b/iam/iam.go @@ -1,8 +1,8 @@ package iam import ( - "github.com/datarhei/core/v16/iam/access" "github.com/datarhei/core/v16/iam/identity" + "github.com/datarhei/core/v16/iam/policy" "github.com/datarhei/core/v16/log" ) @@ -19,7 +19,7 @@ type IAM interface { HasPolicy(name, domain string, types []string, resource string, actions []string) bool AddPolicy(name, domain string, types []string, resource string, actions []string) error RemovePolicy(name, domain string, types []string, resource string, actions []string) error - ListPolicies(name, domain string, types []string, resource string, actions []string) []access.Policy + ListPolicies(name, domain string, types []string, resource string, actions []string) []policy.Policy ReloadPolicies() error Validators() []string @@ -42,13 +42,13 @@ type IAM interface { type iam struct { im identity.Manager - am access.Manager + am policy.Manager logger log.Logger } type Config struct { - PolicyAdapter access.Adapter + PolicyAdapter policy.Adapter IdentityAdapter identity.Adapter Superuser identity.User JWTRealm string @@ -68,9 +68,10 @@ func New(config Config) (IAM, error) { return nil, err } - am, err := access.New(access.Config{ - Adapter: config.PolicyAdapter, - Logger: config.Logger, + am, err := policy.New(policy.Config{ + Superuser: "$superuser", + Adapter: config.PolicyAdapter, + Logger: config.Logger, }) if err != nil { return nil, err @@ -126,16 +127,12 @@ func (i *iam) Enforce(name, domain, rtype, resource, action string) bool { name = "$superuser" } - ok, rule := i.am.Enforce(name, domain, rtype, resource, action) + ok, policy := i.am.Enforce(name, domain, rtype, resource, action) if !ok { l.Log("no match") } else { - if name == "$superuser" { - rule = "" - } - - l.WithField("rule", rule).Log("match") + l.WithField("policy", policy).Log("match") } return ok @@ -234,11 +231,11 @@ func (i *iam) RemovePolicy(name, domain string, types []string, resource string, } } - return i.am.RemovePolicy(name, domain, types, resource, actions) + return i.am.RemovePolicy(name, domain) } -func (i *iam) ListPolicies(name, domain string, types []string, resource string, actions []string) []access.Policy { - return i.am.ListPolicies(name, domain, types, resource, actions) +func (i *iam) ListPolicies(name, domain string, types []string, resource string, actions []string) []policy.Policy { + return i.am.ListPolicies(name, domain) } func (i *iam) ReloadPolicies() error { diff --git a/iam/policy/access.go b/iam/policy/access.go new file mode 100644 index 00000000..1d69bfce --- /dev/null +++ b/iam/policy/access.go @@ -0,0 +1,35 @@ +package policy + +import ( + "fmt" + "strings" +) + +type Policy struct { + Name string + Domain string + Types []string + Resource string + Actions []string +} + +func (p Policy) String() string { + return fmt.Sprintf("%s@%s (%s):%s %s", p.Name, p.Domain, strings.Join(p.Types, "|"), p.Resource, strings.Join(p.Actions, "|")) +} + +type Enforcer interface { + Enforce(name, domain, rtype, resource, action string) (bool, Policy) + + HasDomain(name string) bool + ListDomains() []string +} + +type Manager interface { + Enforcer + + HasPolicy(name, domain string, types []string, resource string, actions []string) bool + AddPolicy(name, domain string, types []string, resource string, actions []string) error + RemovePolicy(name, domain string) error + ListPolicies(name, domain string) []Policy + ReloadPolicies() error +} diff --git a/iam/policy/adapter.go b/iam/policy/adapter.go new file mode 100644 index 00000000..ccc0c21c --- /dev/null +++ b/iam/policy/adapter.go @@ -0,0 +1,418 @@ +package policy + +import ( + "encoding/json" + "errors" + "fmt" + "sort" + "strings" + "sync" + + "github.com/datarhei/core/v16/io/fs" + "github.com/datarhei/core/v16/log" +) + +type policyadapter struct { + fs fs.Filesystem + filePath string + logger log.Logger + domains []Domain + lock sync.Mutex +} + +type Adapter interface { + AddPolicy(policy Policy) error + LoadPolicy(model Model) error + RemovePolicy(policy Policy) error + SavePolicy(model Model) error + AddPolicies(policies []Policy) error + RemovePolicies(policies []Policy) error + + AllDomains() []string + HasDomain(string) bool +} + +func NewJSONAdapter(fs fs.Filesystem, filePath string, logger log.Logger) (Adapter, error) { + a := &policyadapter{ + fs: fs, + filePath: filePath, + logger: logger, + } + + if a.fs == nil { + return nil, fmt.Errorf("a filesystem has to be provided") + } + + if len(a.filePath) == 0 { + return nil, fmt.Errorf("invalid file path, file path cannot be empty") + } + + if a.logger == nil { + a.logger = log.New("") + } + + return a, nil +} + +// Adapter +func (a *policyadapter) LoadPolicy(model Model) error { + a.lock.Lock() + defer a.lock.Unlock() + + return a.loadPolicyFile(model) +} + +func (a *policyadapter) loadPolicyFile(model Model) error { + if _, err := a.fs.Stat(a.filePath); err != nil { + if errors.Is(err, fs.ErrNotExist) { + a.domains = []Domain{} + return nil + } + + return err + } + + data, err := a.fs.ReadFile(a.filePath) + if err != nil { + return err + } + + domains := []Domain{} + + err = json.Unmarshal(data, &domains) + if err != nil { + return err + } + + for _, domain := range domains { + for _, policy := range domain.Policies { + rtypes, resource := DecodeResource(policy.Resource) + p := normalizePolicy(Policy{ + Name: policy.Username, + Domain: domain.Name, + Types: rtypes, + Resource: resource, + Actions: DecodeActions(policy.Actions), + }) + + if err := a.importPolicy(model, p); err != nil { + return err + } + } + } + + a.domains = domains + + return nil +} + +func (a *policyadapter) importPolicy(model Model, policy Policy) error { + a.logger.Debug().WithFields(log.Fields{ + "subject": policy.Name, + "domain": policy.Domain, + "types": policy.Types, + "resource": policy.Resource, + "actions": policy.Actions, + }).Log("Imported policy") + + model.AddPolicy(policy) + + return nil +} + +// Adapter +func (a *policyadapter) SavePolicy(model Model) error { + a.lock.Lock() + defer a.lock.Unlock() + + return a.savePolicyFile() +} + +func (a *policyadapter) savePolicyFile() error { + jsondata, err := json.MarshalIndent(a.domains, "", " ") + if err != nil { + return err + } + + _, _, err = a.fs.WriteFileSafe(a.filePath, jsondata) + + return err +} + +// Adapter (auto-save) +func (a *policyadapter) AddPolicy(policy Policy) error { + a.lock.Lock() + defer a.lock.Unlock() + + err := a.addPolicy(policy) + if err != nil { + return err + } + + return a.savePolicyFile() +} + +// BatchAdapter (auto-save) +func (a *policyadapter) AddPolicies(policies []Policy) error { + a.lock.Lock() + defer a.lock.Unlock() + + for _, policy := range policies { + err := a.addPolicy(policy) + if err != nil { + return err + } + } + + return a.savePolicyFile() +} + +func (a *policyadapter) addPolicy(policy Policy) error { + ok, err := a.hasPolicy(policy) + if err != nil { + return err + } + + if ok { + // the policy is already there, nothing to add + return nil + } + + policy = normalizePolicy(policy) + + username := policy.Name + domain := policy.Domain + resource := EncodeResource(policy.Types, policy.Resource) + actions := EncodeActions(policy.Actions) + + a.logger.Debug().WithFields(log.Fields{ + "subject": username, + "domain": domain, + "resource": resource, + "actions": actions, + }).Log("Adding policy") + + var dom *Domain = nil + for i := range a.domains { + if a.domains[i].Name == domain { + dom = &a.domains[i] + break + } + } + + if dom == nil { + g := Domain{ + Name: domain, + Policies: []DomainPolicy{}, + } + + a.domains = append(a.domains, g) + dom = &a.domains[len(a.domains)-1] + } + + dom.Policies = append(dom.Policies, DomainPolicy{ + Username: username, + Resource: resource, + Actions: actions, + }) + + return nil +} + +func (a *policyadapter) hasPolicy(policy Policy) (bool, error) { + policy = normalizePolicy(policy) + + username := policy.Name + domain := policy.Domain + resource := EncodeResource(policy.Types, policy.Resource) + actions := EncodeActions(policy.Actions) + + var dom *Domain = nil + for i := range a.domains { + if a.domains[i].Name == domain { + dom = &a.domains[i] + break + } + } + + if dom == nil { + // if we can't find any domain with that name, then the policy doesn't exist + return false, nil + } + + for _, p := range dom.Policies { + if p.Username == username && p.Resource == resource && p.Actions == actions { + return true, nil + } + } + + return false, nil +} + +// Adapter (auto-save) +func (a *policyadapter) RemovePolicy(policy Policy) error { + a.lock.Lock() + defer a.lock.Unlock() + + err := a.removePolicy(policy) + if err != nil { + return err + } + + return a.savePolicyFile() +} + +// BatchAdapter (auto-save) +func (a *policyadapter) RemovePolicies(policies []Policy) error { + a.lock.Lock() + defer a.lock.Unlock() + + for _, policy := range policies { + err := a.removePolicy(policy) + if err != nil { + return err + } + } + + return a.savePolicyFile() +} + +func (a *policyadapter) removePolicy(policy Policy) error { + ok, err := a.hasPolicy(policy) + if err != nil { + return err + } + + if !ok { + // the policy is not there, nothing to remove + return nil + } + + policy = normalizePolicy(policy) + + username := policy.Name + domain := policy.Domain + resource := EncodeResource(policy.Types, policy.Resource) + actions := EncodeActions(policy.Actions) + + a.logger.Debug().WithFields(log.Fields{ + "subject": username, + "domain": domain, + "resource": resource, + "actions": actions, + }).Log("Removing policy") + + var dom *Domain = nil + for i := range a.domains { + if a.domains[i].Name == domain { + dom = &a.domains[i] + break + } + } + + policies := []DomainPolicy{} + + for _, p := range dom.Policies { + if p.Username == username && p.Resource == resource && p.Actions == actions { + continue + } + + policies = append(policies, p) + } + + dom.Policies = policies + + // Remove the group if there are no rules and policies + if len(dom.Policies) == 0 { + groups := []Domain{} + + for _, g := range a.domains { + if g.Name == dom.Name { + continue + } + + groups = append(groups, g) + } + + a.domains = groups + } + + return nil +} + +// Adapter +func (a *policyadapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error { + return fmt.Errorf("not implemented") +} + +func (a *policyadapter) AllDomains() []string { + a.lock.Lock() + defer a.lock.Unlock() + + names := []string{} + + for _, domain := range a.domains { + if domain.Name[0] == '$' { + continue + } + + names = append(names, domain.Name) + } + + return names +} + +func (a *policyadapter) HasDomain(name string) bool { + a.lock.Lock() + defer a.lock.Unlock() + + for _, domain := range a.domains { + if domain.Name[0] == '$' { + continue + } + + if domain.Name == name { + return true + } + } + + return false +} + +type Domain struct { + Name string `json:"name"` + Policies []DomainPolicy `json:"policies"` +} + +type DomainPolicy struct { + Username string `json:"username"` + Resource string `json:"resource"` + Actions string `json:"actions"` +} + +func EncodeActions(actions []string) string { + return strings.Join(actions, "|") +} + +func DecodeActions(actions string) []string { + return strings.Split(actions, "|") +} + +func EncodeResource(types []string, resource string) string { + if len(types) == 0 { + return resource + } + + sort.Strings(types) + + return strings.Join(types, "|") + ":" + resource +} + +func DecodeResource(resource string) ([]string, string) { + before, after, found := strings.Cut(resource, ":") + if !found { + return []string{"$none"}, resource + } + + return strings.Split(before, "|"), after +} diff --git a/iam/access/adapter_test.go b/iam/policy/adapter_test.go similarity index 61% rename from iam/access/adapter_test.go rename to iam/policy/adapter_test.go index fbc72806..16a0ae89 100644 --- a/iam/access/adapter_test.go +++ b/iam/policy/adapter_test.go @@ -1,4 +1,4 @@ -package access +package policy import ( "testing" @@ -16,10 +16,16 @@ func TestAddPolicy(t *testing.T) { ai, err := NewJSONAdapter(memfs, "/policy.json", nil) require.NoError(t, err) - a, ok := ai.(*adapter) + a, ok := ai.(*policyadapter) require.True(t, ok) - err = a.AddPolicy("p", "p", []string{"foobar", "group", "resource", "action"}) + err = a.AddPolicy(Policy{ + Name: "foobar", + Domain: "group", + Types: []string{}, + Resource: "resource", + Actions: []string{"action"}, + }) require.NoError(t, err) require.Equal(t, 1, len(a.domains)) @@ -35,24 +41,11 @@ func TestAddPolicy(t *testing.T) { require.Equal(t, 1, len(g[0].Policies)) require.Equal(t, DomainPolicy{ Username: "foobar", - Role: Role{ - Resource: "resource", - Actions: "action", - }, + Resource: "resource", + Actions: "action", }, g[0].Policies[0]) } -func TestFormatActions(t *testing.T) { - data := [][]string{ - {"a|b|c", "a|b|c"}, - {"b|c|a", "a|b|c"}, - } - - for _, d := range data { - require.Equal(t, d[1], formatList(d[0]), d[0]) - } -} - func TestRemovePolicy(t *testing.T) { memfs, err := fs.NewMemFilesystem(fs.MemConfig{}) require.NoError(t, err) @@ -60,25 +53,49 @@ func TestRemovePolicy(t *testing.T) { ai, err := NewJSONAdapter(memfs, "/policy.json", nil) require.NoError(t, err) - a, ok := ai.(*adapter) + a, ok := ai.(*policyadapter) require.True(t, ok) - err = a.AddPolicies("p", "p", [][]string{ - {"foobar1", "group", "resource1", "action1"}, - {"foobar2", "group", "resource2", "action2"}, + err = a.AddPolicies([]Policy{ + { + Name: "foobar1", + Domain: "group", + Types: []string{}, + Resource: "resource1", + Actions: []string{"action1"}, + }, + { + Name: "foobar2", + Domain: "group", + Types: []string{}, + Resource: "resource2", + Actions: []string{"action2"}, + }, }) require.NoError(t, err) require.Equal(t, 1, len(a.domains)) require.Equal(t, 2, len(a.domains[0].Policies)) - err = a.RemovePolicy("p", "p", []string{"foobar1", "group", "resource1", "action1"}) + err = a.RemovePolicy(Policy{ + Name: "foobar1", + Domain: "group", + Types: []string{}, + Resource: "resource1", + Actions: []string{"action1"}, + }) require.NoError(t, err) require.Equal(t, 1, len(a.domains)) require.Equal(t, 1, len(a.domains[0].Policies)) - err = a.RemovePolicy("p", "p", []string{"foobar2", "group", "resource2", "action2"}) + err = a.RemovePolicy(Policy{ + Name: "foobar2", + Domain: "group", + Types: []string{}, + Resource: "resource2", + Actions: []string{"action2"}, + }) require.NoError(t, err) require.Equal(t, 0, len(a.domains)) diff --git a/iam/policy/enforcer.go b/iam/policy/enforcer.go new file mode 100644 index 00000000..ea3e6e9d --- /dev/null +++ b/iam/policy/enforcer.go @@ -0,0 +1,93 @@ +package policy + +import ( + "github.com/puzpuzpuz/xsync/v3" +) + +type PolicyEnforcer struct { + model Model + adapter Adapter + lock *xsync.RBMutex +} + +func NewEnforcer(model Model, adapter Adapter) *PolicyEnforcer { + e := &PolicyEnforcer{ + model: model, + adapter: adapter, + lock: xsync.NewRBMutex(), + } + + e.ReloadPolicies() + + return e +} + +func (e *PolicyEnforcer) HasPolicy(policy Policy) bool { + token := e.lock.RLock() + defer e.lock.RUnlock(token) + + return e.model.HasPolicy(policy) +} + +func (e *PolicyEnforcer) AddPolicy(policy Policy) error { + token := e.lock.RLock() + defer e.lock.RUnlock(token) + + err := e.model.AddPolicy(policy) + if err != nil { + return err + } + + if e.adapter != nil { + e.adapter.AddPolicy(policy) + } + + return nil +} + +func (e *PolicyEnforcer) RemovePolicies(policies []Policy) error { + token := e.lock.RLock() + defer e.lock.RUnlock(token) + + err := e.model.RemovePolicies(policies) + if err != nil { + return err + } + + if e.adapter != nil { + e.adapter.RemovePolicies(policies) + } + + return nil +} + +func (e *PolicyEnforcer) GetFilteredPolicy(name, domain string) []Policy { + token := e.lock.RLock() + defer e.lock.RUnlock(token) + + return e.model.GetFilteredPolicy(name, domain) +} + +func (e *PolicyEnforcer) ReloadPolicies() error { + e.lock.Lock() + defer e.lock.Unlock() + + e.model.ClearPolicy() + + return e.adapter.LoadPolicy(e.model) +} + +func (e *PolicyEnforcer) Enforce(name, domain, rtype, resource, action string) (bool, Policy) { + token := e.lock.RLock() + defer e.lock.RUnlock(token) + + return e.model.Enforce(name, domain, rtype, resource, action) +} + +func (e *PolicyEnforcer) HasDomain(name string) bool { + return e.adapter.HasDomain(name) +} + +func (e *PolicyEnforcer) ListDomains() []string { + return e.adapter.AllDomains() +} diff --git a/iam/access/fixtures/policy.json b/iam/policy/fixtures/policy.json similarity index 100% rename from iam/access/fixtures/policy.json rename to iam/policy/fixtures/policy.json diff --git a/iam/policy/manager.go b/iam/policy/manager.go new file mode 100644 index 00000000..ffb83636 --- /dev/null +++ b/iam/policy/manager.go @@ -0,0 +1,92 @@ +package policy + +import ( + "fmt" + + "github.com/datarhei/core/v16/log" +) + +type policyaccess struct { + logger log.Logger + + adapter Adapter + model Model + enforcer *PolicyEnforcer +} + +type Config struct { + Adapter Adapter + Logger log.Logger + Superuser string +} + +func New(config Config) (Manager, error) { + am := &policyaccess{ + adapter: config.Adapter, + logger: config.Logger, + } + + if am.adapter == nil { + return nil, fmt.Errorf("missing adapter") + } + + if am.logger == nil { + am.logger = log.New("") + } + + m := NewModel(config.Superuser) + e := NewEnforcer(m, am.adapter) + + am.enforcer = e + am.model = m + + return am, nil +} + +func (am *policyaccess) Enforce(name, domain, rtype, resource, action string) (bool, Policy) { + return am.enforcer.Enforce(name, domain, rtype, resource, action) +} + +func (am *policyaccess) HasPolicy(name, domain string, types []string, resource string, actions []string) bool { + return am.enforcer.HasPolicy(Policy{ + Name: name, + Domain: domain, + Types: types, + Resource: resource, + Actions: actions, + }) +} + +func (am *policyaccess) AddPolicy(name, domain string, types []string, resource string, actions []string) error { + policy := Policy{ + Name: name, + Domain: domain, + Types: types, + Resource: resource, + Actions: actions, + } + + return am.enforcer.AddPolicy(policy) +} + +func (am *policyaccess) RemovePolicy(name, domain string) error { + policies := am.enforcer.GetFilteredPolicy(name, domain) + + return am.enforcer.RemovePolicies(policies) +} + +func (am *policyaccess) ListPolicies(name, domain string) []Policy { + return am.enforcer.GetFilteredPolicy(name, domain) +} + +func (am *policyaccess) ReloadPolicies() error { + return am.enforcer.ReloadPolicies() +} + +func (am *policyaccess) HasDomain(name string) bool { + return am.adapter.HasDomain(name) +} + +func (am *policyaccess) ListDomains() []string { + return am.adapter.AllDomains() +} diff --git a/iam/access/access_test.go b/iam/policy/manager_test.go similarity index 66% rename from iam/access/access_test.go rename to iam/policy/manager_test.go index b857dd69..830fb3ad 100644 --- a/iam/access/access_test.go +++ b/iam/policy/manager_test.go @@ -1,9 +1,13 @@ -package access +package policy import ( + "fmt" + "math/rand/v2" + "sync" "testing" "github.com/datarhei/core/v16/io/fs" + "github.com/stretchr/testify/require" ) @@ -26,7 +30,7 @@ func TestAccessManager(t *testing.T) { }) require.NoError(t, err) - policies := am.ListPolicies("", "", nil, "", nil) + policies := am.ListPolicies("", "") require.ElementsMatch(t, []Policy{ { Name: "ingo", @@ -46,7 +50,7 @@ func TestAccessManager(t *testing.T) { am.AddPolicy("foobar", "group", []string{"bla", "blubb"}, "/", []string{"write"}) - policies = am.ListPolicies("", "", nil, "", nil) + policies = am.ListPolicies("", "") require.ElementsMatch(t, []Policy{ { Name: "ingo", @@ -75,9 +79,9 @@ func TestAccessManager(t *testing.T) { require.True(t, am.HasDomain("group")) require.False(t, am.HasDomain("$none")) - am.RemovePolicy("ingo", "", nil, "", nil) + am.RemovePolicy("ingo", "") - policies = am.ListPolicies("", "", nil, "", nil) + policies = am.ListPolicies("", "") require.ElementsMatch(t, []Policy{ { Name: "foobar", @@ -112,12 +116,57 @@ func BenchmarkEnforce(b *testing.B) { }) require.NoError(b, err) - am.AddPolicy("$anon", "$none", []string{"foobar"}, "**", []string{"ANY"}) + names := []string{} + + for i := 0; i < 1000; i++ { + name := fmt.Sprintf("user%d", i) + names = append(names, name) + am.AddPolicy(name, "$none", []string{"foobar"}, "**", []string{"ANY"}) + } b.ResetTimer() for i := 0; i < b.N; i++ { - ok, _ := am.Enforce("$anon", "$none", "foobar", "baz", "read") + name := names[rand.IntN(1000)] + ok, _ := am.Enforce(name, "$none", "foobar", "baz", "read") require.True(b, ok) } } + +func BenchmarkConcurrentEnforce(b *testing.B) { + adapter, err := createAdapter() + require.NoError(b, err) + + am, err := New(Config{ + Adapter: adapter, + Logger: nil, + }) + require.NoError(b, err) + + names := []string{} + + for i := 0; i < 1000; i++ { + name := fmt.Sprintf("user%d", i) + names = append(names, name) + am.AddPolicy(name, "$none", []string{"foobar"}, "**", []string{"ANY"}) + } + + b.ResetTimer() + + readerWg := sync.WaitGroup{} + + for i := 0; i < 1000; i++ { + readerWg.Add(1) + go func() { + defer readerWg.Done() + + for i := 0; i < b.N; i++ { + name := names[rand.IntN(1000)] + ok, _ := am.Enforce(name, "$none", "foobar", "baz", "read") + require.True(b, ok) + } + }() + } + + readerWg.Wait() +} diff --git a/iam/policy/matcher.go b/iam/policy/matcher.go new file mode 100644 index 00000000..799ca7b5 --- /dev/null +++ b/iam/policy/matcher.go @@ -0,0 +1,72 @@ +package policy + +import ( + "slices" + "sync" + + "github.com/datarhei/core/v16/glob" +) + +var globcache = map[string]glob.Glob{} +var globcacheMu = sync.RWMutex{} + +func resourceMatch(requestType, requestResource string, policyTypes []string, policyResource string) bool { + var match bool = false + var err error = nil + + if !slices.Contains(policyTypes, requestType) { + return false + } + + key := requestType + policyResource + + if requestType == "api" || requestType == "fs" || requestType == "rtmp" || requestType == "srt" { + globcacheMu.RLock() + matcher, ok := globcache[key] + globcacheMu.RUnlock() + if !ok { + matcher, err = glob.Compile(policyResource, rune('/')) + if err != nil { + return false + } + globcacheMu.Lock() + globcache[key] = matcher + globcacheMu.Unlock() + } + + match = matcher.Match(requestResource) + } else { + globcacheMu.RLock() + matcher, ok := globcache[key] + globcacheMu.RUnlock() + if !ok { + matcher, err = glob.Compile(policyResource) + if err != nil { + return false + } + globcacheMu.Lock() + globcache[key] = matcher + globcacheMu.Unlock() + } + + match = matcher.Match(requestResource) + } + + return match +} + +func actionMatch(requestAction string, policyActions []string, wildcard string) bool { + if len(policyActions) == 0 { + return false + } + + if len(policyActions) == 1 && policyActions[0] == wildcard { + return true + } + + if slices.Contains(policyActions, requestAction) { + return true + } + + return false +} diff --git a/iam/policy/matcher_test.go b/iam/policy/matcher_test.go new file mode 100644 index 00000000..520bb72f --- /dev/null +++ b/iam/policy/matcher_test.go @@ -0,0 +1,35 @@ +package policy + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestResourceMatcher(t *testing.T) { + ok := resourceMatch("fs", "/", []string{"api", "fs"}, "/") + require.True(t, ok) + + ok = resourceMatch("bla", "/", []string{"api", "fs"}, "/") + require.False(t, ok) + + ok = resourceMatch("fs", "/foo", []string{"api", "fs"}, "/") + require.False(t, ok) + + ok = resourceMatch("fs", "/foo", []string{"api", "fs"}, "/*") + require.True(t, ok) + + ok = resourceMatch("fs", "/foo/boz", []string{"api", "fs"}, "/*") + require.False(t, ok) + + ok = resourceMatch("fs", "/foo/boz", []string{"api", "fs"}, "/**") + require.True(t, ok) +} + +func TestActionMatcher(t *testing.T) { + ok := actionMatch("get", []string{"any"}, "any") + require.True(t, ok) + + ok = actionMatch("get", []string{"get", "head"}, "any") + require.True(t, ok) +} diff --git a/iam/policy/model.go b/iam/policy/model.go new file mode 100644 index 00000000..9f9e36f6 --- /dev/null +++ b/iam/policy/model.go @@ -0,0 +1,238 @@ +package policy + +import ( + "slices" + "strings" + + "github.com/puzpuzpuz/xsync/v3" +) + +type Model interface { + Enforce(name, domain, rtype, resource, action string) (bool, Policy) + HasPolicy(policy Policy) bool + AddPolicy(policy Policy) error + AddPolicies(policies []Policy) error + RemovePolicy(policy Policy) error + RemovePolicies(policies []Policy) error + GetFilteredPolicy(name, domain string) []Policy + ClearPolicy() +} + +type model struct { + superuser string + policies map[string][]Policy // user@domain + lock *xsync.RBMutex +} + +func NewModel(superuser string) Model { + m := &model{ + superuser: superuser, + policies: map[string][]Policy{}, + lock: xsync.NewRBMutex(), + } + + return m +} + +func (m *model) HasPolicy(policy Policy) bool { + token := m.lock.RLock() + defer m.lock.RUnlock(token) + + return m.hasPolicy(policy) +} + +func (m *model) hasPolicy(policy Policy) bool { + key := policy.Name + "@" + policy.Domain + + policies, hasKey := m.policies[key] + if !hasKey { + return false + } + + policy = normalizePolicy(policy) + + for _, p := range policies { + if slices.Equal(p.Types, policy.Types) && p.Resource == policy.Resource && slices.Equal(p.Actions, policy.Actions) { + return true + } + } + + return false +} + +func (m *model) AddPolicy(policy Policy) error { + m.lock.Lock() + defer m.lock.Unlock() + + return m.addPolicy(policy) +} + +func (m *model) AddPolicies(policies []Policy) error { + m.lock.Lock() + defer m.lock.Unlock() + + for _, policy := range policies { + m.addPolicy(policy) + } + + return nil +} + +func (m *model) addPolicy(policy Policy) error { + if m.hasPolicy(policy) { + return nil + } + + policy = normalizePolicy(policy) + key := policy.Name + "@" + policy.Domain + + policies, hasKey := m.policies[key] + if !hasKey { + policies = []Policy{} + } + + policies = append(policies, policy) + m.policies[key] = policies + + return nil +} + +func (m *model) RemovePolicy(policy Policy) error { + m.lock.Lock() + defer m.lock.Unlock() + + return m.removePolicy(policy) +} + +func (m *model) RemovePolicies(policies []Policy) error { + m.lock.Lock() + defer m.lock.Unlock() + + for _, policy := range policies { + m.removePolicy(policy) + } + + return nil +} + +func (m *model) removePolicy(policy Policy) error { + if !m.hasPolicy(policy) { + return nil + } + + policy = normalizePolicy(policy) + key := policy.Name + "@" + policy.Domain + + policies := m.policies[key] + + newPolicies := []Policy{} + + for _, p := range policies { + if slices.Equal(p.Types, policy.Types) && p.Resource == policy.Resource && slices.Equal(p.Actions, policy.Actions) { + continue + } + + newPolicies = append(newPolicies, p) + } + + if len(newPolicies) != 0 { + m.policies[key] = newPolicies + } else { + delete(m.policies, key) + } + + return nil +} + +func (m *model) GetFilteredPolicy(name, domain string) []Policy { + token := m.lock.RLock() + defer m.lock.RUnlock(token) + + filteredPolicies := []Policy{} + + if len(name) == 0 && len(domain) == 0 { + for _, policies := range m.policies { + filteredPolicies = append(filteredPolicies, policies...) + } + } else if len(name) != 0 && len(domain) == 0 { + for key, policies := range m.policies { + if !strings.HasPrefix(key, name+"@") { + continue + } + + filteredPolicies = append(filteredPolicies, policies...) + } + } else if len(name) == 0 && len(domain) != 0 { + for key, policies := range m.policies { + if !strings.HasSuffix(key, "@"+domain) { + continue + } + + filteredPolicies = append(filteredPolicies, policies...) + } + } else { + for key, policies := range m.policies { + before, after, _ := strings.Cut(key, "@") + + if name != before || domain != after { + continue + } + + filteredPolicies = append(filteredPolicies, policies...) + } + } + + return filteredPolicies +} + +func (m *model) ClearPolicy() { + m.lock.Lock() + defer m.lock.Unlock() + + m.policies = map[string][]Policy{} +} + +func (m *model) Enforce(name, domain, rtype, resource, action string) (bool, Policy) { + token := m.lock.RLock() + defer m.lock.RUnlock(token) + + if name == m.superuser { + return true, Policy{ + Name: m.superuser, + } + } + + key := name + "@" + domain + + policies, hasKey := m.policies[key] + if !hasKey { + return false, Policy{} + } + + rtype = strings.ToLower(rtype) + action = strings.ToLower(action) + + for _, p := range policies { + if resourceMatch(rtype, resource, p.Types, p.Resource) && actionMatch(action, p.Actions, "any") { + return true, p + } + } + + return false, Policy{} +} + +func normalizePolicy(p Policy) Policy { + for i, t := range p.Types { + p.Types[i] = strings.ToLower(t) + } + + slices.Sort(p.Types) + + for i, a := range p.Actions { + p.Actions[i] = strings.ToLower(a) + } + + slices.Sort(p.Actions) + + return p +} diff --git a/iam/policy/model_test.go b/iam/policy/model_test.go new file mode 100644 index 00000000..fe1b1392 --- /dev/null +++ b/iam/policy/model_test.go @@ -0,0 +1,354 @@ +package policy + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestNormalizePolicy(t *testing.T) { + p := Policy{ + Name: "foobar", + Domain: "domain", + Types: []string{"fs", "API", "rtMp", "srt"}, + Resource: "/foo/**", + Actions: []string{"Head", "OPtionS", "GET"}, + } + + p = normalizePolicy(p) + + require.Equal(t, Policy{ + Name: "foobar", + Domain: "domain", + Types: []string{"api", "fs", "rtmp", "srt"}, + Resource: "/foo/**", + Actions: []string{"get", "head", "options"}, + }, p) +} + +func TestModelNew(t *testing.T) { + m := NewModel("$superuser").(*model) + require.Equal(t, m.superuser, "$superuser") + require.NotNil(t, m.policies) + require.NotNil(t, m.lock) +} + +func TestModelAddPolicy(t *testing.T) { + p := Policy{ + Name: "foobar", + Domain: "domain", + Types: []string{"fs", "API", "rtMp", "srt"}, + Resource: "/foo/**", + Actions: []string{"Head", "OPtionS", "GET"}, + } + + m := NewModel("$superuser").(*model) + + err := m.AddPolicy(p) + require.NoError(t, err) + + require.Equal(t, 1, len(m.policies)) + require.Equal(t, 1, len(m.policies["foobar@domain"])) + require.Equal(t, Policy{ + Name: "foobar", + Domain: "domain", + Types: []string{"api", "fs", "rtmp", "srt"}, + Resource: "/foo/**", + Actions: []string{"get", "head", "options"}, + }, m.policies["foobar@domain"][0]) + + m.AddPolicies([]Policy{p, p, p}) + + require.Equal(t, 1, len(m.policies)) + require.Equal(t, 1, len(m.policies["foobar@domain"])) + + p.Resource = "/bar/*" + m.AddPolicy(p) + + require.Equal(t, 2, len(m.policies["foobar@domain"])) + + p.Name = "foobaz" + m.AddPolicy(p) + + require.Equal(t, 2, len(m.policies)) + require.Equal(t, 1, len(m.policies["foobaz@domain"])) +} + +func TestModelHasPolicy(t *testing.T) { + p := Policy{ + Name: "foobar", + Domain: "domain", + Types: []string{"fs", "API", "rtMp", "srt"}, + Resource: "/foo/**", + Actions: []string{"Head", "OPtionS", "GET"}, + } + + m := NewModel("$superuser").(*model) + + ok := m.HasPolicy(p) + require.False(t, ok) + + m.AddPolicy(p) + + ok = m.HasPolicy(p) + require.True(t, ok) + + ok = m.HasPolicy(Policy{ + Name: "foobaz", + Domain: "domain", + Types: []string{"fs", "API", "rtMp", "srt"}, + Resource: "/foo/**", + Actions: []string{"Head", "OPtionS", "GET", "put"}, + }) + require.False(t, ok) + + ok = m.HasPolicy(Policy{ + Name: "foobar", + Domain: "domaim", + Types: []string{"fs", "API", "rtMp", "srt"}, + Resource: "/foo/**", + Actions: []string{"Head", "OPtionS", "GET", "put"}, + }) + require.False(t, ok) + + ok = m.HasPolicy(Policy{ + Name: "foobar", + Domain: "domain", + Types: []string{"API", "rtMp", "srt"}, + Resource: "/foo/**", + Actions: []string{"Head", "OPtionS", "GET", "put"}, + }) + require.False(t, ok) + + ok = m.HasPolicy(Policy{ + Name: "foobar", + Domain: "domain", + Types: []string{"fs", "API", "rtMp", "srt"}, + Resource: "/foo/*", + Actions: []string{"Head", "OPtionS", "GET", "put"}, + }) + require.False(t, ok) + + ok = m.HasPolicy(Policy{ + Name: "foobar", + Domain: "domain", + Types: []string{"fs", "API", "rtMp", "srt"}, + Resource: "/foo/**", + Actions: []string{"Head", "OPtionS", "GET", "pot"}, + }) + require.False(t, ok) +} + +func TestModelRemovePolicy(t *testing.T) { + p := Policy{ + Name: "foobar", + Domain: "domain", + Types: []string{"fs", "API", "rtMp", "srt"}, + Resource: "/foo/**", + Actions: []string{"Head", "OPtionS", "GET"}, + } + + m := NewModel("$superuser").(*model) + m.AddPolicy(p) + + p.Resource = "/bar/*" + m.AddPolicy(p) + + require.Equal(t, 2, len(m.policies["foobar@domain"])) + + err := m.RemovePolicy(Policy{ + Name: "foobar", + Domain: "domain", + Types: []string{"fs", "API", "rtMp", "srt"}, + Resource: "/foo/**", + Actions: []string{"Head", "OPtionS", "GET", "put"}, + }) + require.NoError(t, err) + + require.Equal(t, 2, len(m.policies["foobar@domain"])) + + err = m.RemovePolicy(p) + require.NoError(t, err) + + require.Equal(t, 1, len(m.policies)) + require.Equal(t, 1, len(m.policies["foobar@domain"])) +} + +func TestModelListPolicies(t *testing.T) { + p := Policy{ + Name: "foobar", + Domain: "domain", + Types: []string{"fs", "API", "rtMp", "srt"}, + Resource: "/foo/**", + Actions: []string{"Head", "OPtionS", "GET"}, + } + + m := NewModel("$superuser").(*model) + + policies := m.GetFilteredPolicy("", "") + require.Equal(t, 0, len(policies)) + + m.addPolicy(p) + + p.Resource = "/bar/*" + m.addPolicy(p) + + p.Name = "foobaz" + m.addPolicy(p) + + p.Domain = "group" + m.addPolicy(p) + + policies = m.GetFilteredPolicy("", "") + require.Equal(t, 4, len(policies)) + require.ElementsMatch(t, []Policy{ + { + Name: "foobar", + Domain: "domain", + Types: []string{"api", "fs", "rtmp", "srt"}, + Resource: "/foo/**", + Actions: []string{"get", "head", "options"}, + }, + { + Name: "foobar", + Domain: "domain", + Types: []string{"api", "fs", "rtmp", "srt"}, + Resource: "/bar/*", + Actions: []string{"get", "head", "options"}, + }, + { + Name: "foobaz", + Domain: "domain", + Types: []string{"api", "fs", "rtmp", "srt"}, + Resource: "/bar/*", + Actions: []string{"get", "head", "options"}, + }, + { + Name: "foobaz", + Domain: "group", + Types: []string{"api", "fs", "rtmp", "srt"}, + Resource: "/bar/*", + Actions: []string{"get", "head", "options"}, + }, + }, policies) + + policies = m.GetFilteredPolicy("foobar", "") + require.Equal(t, 2, len(policies)) + require.ElementsMatch(t, []Policy{ + { + Name: "foobar", + Domain: "domain", + Types: []string{"api", "fs", "rtmp", "srt"}, + Resource: "/foo/**", + Actions: []string{"get", "head", "options"}, + }, + { + Name: "foobar", + Domain: "domain", + Types: []string{"api", "fs", "rtmp", "srt"}, + Resource: "/bar/*", + Actions: []string{"get", "head", "options"}, + }, + }, policies) + + policies = m.GetFilteredPolicy("", "group") + require.Equal(t, 1, len(policies)) + require.ElementsMatch(t, []Policy{ + { + Name: "foobaz", + Domain: "group", + Types: []string{"api", "fs", "rtmp", "srt"}, + Resource: "/bar/*", + Actions: []string{"get", "head", "options"}, + }, + }, policies) + + policies = m.GetFilteredPolicy("foobaz", "domain") + require.Equal(t, 1, len(policies)) + require.ElementsMatch(t, []Policy{ + { + Name: "foobaz", + Domain: "domain", + Types: []string{"api", "fs", "rtmp", "srt"}, + Resource: "/bar/*", + Actions: []string{"get", "head", "options"}, + }, + }, policies) + + policies = m.GetFilteredPolicy("foobar", "group") + require.Equal(t, 0, len(policies)) +} + +func TestModelEnforce(t *testing.T) { + p := Policy{ + Name: "foobar", + Domain: "domain", + Types: []string{"fs", "API", "rtMp", "srt"}, + Resource: "/foo/**", + Actions: []string{"Head", "OPtionS", "GET", "play"}, + } + + m := NewModel("$superuser").(*model) + + policies := m.GetFilteredPolicy("", "") + require.Equal(t, 0, len(policies)) + + m.addPolicy(p) + + ok, _ := m.Enforce("$superuser", "xxx", "something", "/nothing", "anything") + require.True(t, ok) + + ok, _ = m.Enforce("foobar", "domain", "rtmp", "/foo/bar/baz", "play") + require.True(t, ok) + + ok, _ = m.Enforce("foobar", "domain", "rtmp", "/foo/bar/baz", "publish") + require.False(t, ok) + + ok, _ = m.Enforce("foobar", "domain", "rtmp", "/fo/bar/baz", "play") + require.False(t, ok) + + ok, _ = m.Enforce("foobar", "domain", "rtsp", "/foo/bar/baz", "play") + require.False(t, ok) + + ok, _ = m.Enforce("foobar", "group", "rtmp", "/foo/bar/baz", "play") + require.False(t, ok) + + ok, _ = m.Enforce("foobaz", "domain", "rtmp", "/foo/bar/baz", "play") + require.False(t, ok) +} + +func TestModelClear(t *testing.T) { + p := Policy{ + Name: "foobar", + Domain: "domain", + Types: []string{"fs", "API", "rtMp", "srt"}, + Resource: "/foo/**", + Actions: []string{"Head", "OPtionS", "GET"}, + } + + m := NewModel("$superuser").(*model) + + policies := m.GetFilteredPolicy("", "") + require.Equal(t, 0, len(policies)) + + m.addPolicy(p) + + p.Resource = "/bar/*" + m.addPolicy(p) + + p.Name = "foobaz" + m.addPolicy(p) + + p.Domain = "group" + m.addPolicy(p) + + policies = m.GetFilteredPolicy("", "") + require.Equal(t, 4, len(policies)) + + m.ClearPolicy() + + policies = m.GetFilteredPolicy("", "") + require.Equal(t, 0, len(policies)) + + require.Empty(t, m.policies) +} diff --git a/restream/core_test.go b/restream/core_test.go index 7b68f5b5..aad54bec 100644 --- a/restream/core_test.go +++ b/restream/core_test.go @@ -10,8 +10,8 @@ import ( "github.com/datarhei/core/v16/ffmpeg" "github.com/datarhei/core/v16/iam" - iamaccess "github.com/datarhei/core/v16/iam/access" iamidentity "github.com/datarhei/core/v16/iam/identity" + "github.com/datarhei/core/v16/iam/policy" "github.com/datarhei/core/v16/internal/testhelper" "github.com/datarhei/core/v16/io/fs" "github.com/datarhei/core/v16/net" @@ -47,7 +47,7 @@ func getDummyRestreamer(portrange net.Portranger, validatorIn, validatorOut ffmp return nil, err } - policyAdapter, err := iamaccess.NewJSONAdapter(memfs, "./policy.json", nil) + policyAdapter, err := policy.NewJSONAdapter(memfs, "./policy.json", nil) if err != nil { return nil, err } diff --git a/restream/rewrite/rewrite_test.go b/restream/rewrite/rewrite_test.go index 10a3cac8..b8cd6337 100644 --- a/restream/rewrite/rewrite_test.go +++ b/restream/rewrite/rewrite_test.go @@ -5,8 +5,8 @@ import ( "testing" "github.com/datarhei/core/v16/iam" - iamaccess "github.com/datarhei/core/v16/iam/access" iamidentity "github.com/datarhei/core/v16/iam/identity" + "github.com/datarhei/core/v16/iam/policy" "github.com/datarhei/core/v16/io/fs" "github.com/stretchr/testify/require" @@ -18,7 +18,7 @@ func getIAM(enableBasic bool) (iam.IAM, error) { return nil, err } - policyAdapter, err := iamaccess.NewJSONAdapter(memfs, "./policy.json", nil) + policyAdapter, err := policy.NewJSONAdapter(memfs, "./policy.json", nil) if err != nil { return nil, err } diff --git a/vendor/github.com/casbin/casbin/v2/.gitignore b/vendor/github.com/casbin/casbin/v2/.gitignore deleted file mode 100644 index da27805f..00000000 --- a/vendor/github.com/casbin/casbin/v2/.gitignore +++ /dev/null @@ -1,30 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof - -.idea/ -*.iml - -# vendor files -vendor diff --git a/vendor/github.com/casbin/casbin/v2/.golangci.yml b/vendor/github.com/casbin/casbin/v2/.golangci.yml deleted file mode 100644 index b8d36201..00000000 --- a/vendor/github.com/casbin/casbin/v2/.golangci.yml +++ /dev/null @@ -1,354 +0,0 @@ -# Based on https://gist.github.com/maratori/47a4d00457a92aa426dbd48a18776322 -# This code is licensed under the terms of the MIT license https://opensource.org/license/mit -# Copyright (c) 2021 Marat Reymers - -## Golden config for golangci-lint v1.56.2 -# -# This is the best config for golangci-lint based on my experience and opinion. -# It is very strict, but not extremely strict. -# Feel free to adapt and change it for your needs. - -run: - # Timeout for analysis, e.g. 30s, 5m. - # Default: 1m - timeout: 3m - - -# This file contains only configs which differ from defaults. -# All possible options can be found here https://github.com/golangci/golangci-lint/blob/master/.golangci.reference.yml -linters-settings: - cyclop: - # The maximal code complexity to report. - # Default: 10 - max-complexity: 30 - # The maximal average package complexity. - # If it's higher than 0.0 (float) the check is enabled - # Default: 0.0 - package-average: 10.0 - - errcheck: - # Report about not checking of errors in type assertions: `a := b.(MyStruct)`. - # Such cases aren't reported by default. - # Default: false - check-type-assertions: true - - exhaustive: - # Program elements to check for exhaustiveness. - # Default: [ switch ] - check: - - switch - - map - - exhaustruct: - # List of regular expressions to exclude struct packages and their names from checks. - # Regular expressions must match complete canonical struct package/name/structname. - # Default: [] - exclude: - # std libs - - "^net/http.Client$" - - "^net/http.Cookie$" - - "^net/http.Request$" - - "^net/http.Response$" - - "^net/http.Server$" - - "^net/http.Transport$" - - "^net/url.URL$" - - "^os/exec.Cmd$" - - "^reflect.StructField$" - # public libs - - "^github.com/Shopify/sarama.Config$" - - "^github.com/Shopify/sarama.ProducerMessage$" - - "^github.com/mitchellh/mapstructure.DecoderConfig$" - - "^github.com/prometheus/client_golang/.+Opts$" - - "^github.com/spf13/cobra.Command$" - - "^github.com/spf13/cobra.CompletionOptions$" - - "^github.com/stretchr/testify/mock.Mock$" - - "^github.com/testcontainers/testcontainers-go.+Request$" - - "^github.com/testcontainers/testcontainers-go.FromDockerfile$" - - "^golang.org/x/tools/go/analysis.Analyzer$" - - "^google.golang.org/protobuf/.+Options$" - - "^gopkg.in/yaml.v3.Node$" - - funlen: - # Checks the number of lines in a function. - # If lower than 0, disable the check. - # Default: 60 - lines: 100 - # Checks the number of statements in a function. - # If lower than 0, disable the check. - # Default: 40 - statements: 50 - # Ignore comments when counting lines. - # Default false - ignore-comments: true - - gocognit: - # Minimal code complexity to report. - # Default: 30 (but we recommend 10-20) - min-complexity: 20 - - gocritic: - # Settings passed to gocritic. - # The settings key is the name of a supported gocritic checker. - # The list of supported checkers can be find in https://go-critic.github.io/overview. - settings: - captLocal: - # Whether to restrict checker to params only. - # Default: true - paramsOnly: false - underef: - # Whether to skip (*x).method() calls where x is a pointer receiver. - # Default: true - skipRecvDeref: false - - gomnd: - # List of function patterns to exclude from analysis. - # Values always ignored: `time.Date`, - # `strconv.FormatInt`, `strconv.FormatUint`, `strconv.FormatFloat`, - # `strconv.ParseInt`, `strconv.ParseUint`, `strconv.ParseFloat`. - # Default: [] - ignored-functions: - - flag.Arg - - flag.Duration.* - - flag.Float.* - - flag.Int.* - - flag.Uint.* - - os.Chmod - - os.Mkdir.* - - os.OpenFile - - os.WriteFile - - prometheus.ExponentialBuckets.* - - prometheus.LinearBuckets - - gomodguard: - blocked: - # List of blocked modules. - # Default: [] - modules: - - github.com/golang/protobuf: - recommendations: - - google.golang.org/protobuf - reason: "see https://developers.google.com/protocol-buffers/docs/reference/go/faq#modules" - - github.com/satori/go.uuid: - recommendations: - - github.com/google/uuid - reason: "satori's package is not maintained" - - github.com/gofrs/uuid: - recommendations: - - github.com/gofrs/uuid/v5 - reason: "gofrs' package was not go module before v5" - - govet: - # Enable all analyzers. - # Default: false - enable-all: true - # Disable analyzers by name. - # Run `go tool vet help` to see all analyzers. - # Default: [] - disable: - - fieldalignment # too strict - # Settings per analyzer. - settings: - shadow: - # Whether to be strict about shadowing; can be noisy. - # Default: false - #strict: true - - inamedparam: - # Skips check for interface methods with only a single parameter. - # Default: false - skip-single-param: true - - nakedret: - # Make an issue if func has more lines of code than this setting, and it has naked returns. - # Default: 30 - max-func-lines: 0 - - nolintlint: - # Exclude following linters from requiring an explanation. - # Default: [] - allow-no-explanation: [ funlen, gocognit, lll ] - # Enable to require an explanation of nonzero length after each nolint directive. - # Default: false - require-explanation: true - # Enable to require nolint directives to mention the specific linter being suppressed. - # Default: false - require-specific: true - - perfsprint: - # Optimizes into strings concatenation. - # Default: true - strconcat: false - - rowserrcheck: - # database/sql is always checked - # Default: [] - packages: - - github.com/jmoiron/sqlx - - tenv: - # The option `all` will run against whole test files (`_test.go`) regardless of method/function signatures. - # Otherwise, only methods that take `*testing.T`, `*testing.B`, and `testing.TB` as arguments are checked. - # Default: false - all: true - - stylecheck: - # STxxxx checks in https://staticcheck.io/docs/configuration/options/#checks - # Default: ["*"] - checks: ["all", "-ST1003"] - - revive: - rules: - # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unused-parameter - - name: unused-parameter - disabled: true - -linters: - disable-all: true - enable: - ## enabled by default - #- errcheck # checking for unchecked errors, these unchecked errors can be critical bugs in some cases - - gosimple # specializes in simplifying a code - - govet # reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - - ineffassign # detects when assignments to existing variables are not used - - staticcheck # is a go vet on steroids, applying a ton of static analysis checks - - typecheck # like the front-end of a Go compiler, parses and type-checks Go code - - unused # checks for unused constants, variables, functions and types - ## disabled by default - - asasalint # checks for pass []any as any in variadic func(...any) - - asciicheck # checks that your code does not contain non-ASCII identifiers - - bidichk # checks for dangerous unicode character sequences - - bodyclose # checks whether HTTP response body is closed successfully - - cyclop # checks function and package cyclomatic complexity - - dupl # tool for code clone detection - - durationcheck # checks for two durations multiplied together - - errname # checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error - #- errorlint # finds code that will cause problems with the error wrapping scheme introduced in Go 1.13 - - execinquery # checks query string in Query function which reads your Go src files and warning it finds - - exhaustive # checks exhaustiveness of enum switch statements - - exportloopref # checks for pointers to enclosing loop variables - #- forbidigo # forbids identifiers - - funlen # tool for detection of long functions - - gocheckcompilerdirectives # validates go compiler directive comments (//go:) - #- gochecknoglobals # checks that no global variables exist - - gochecknoinits # checks that no init functions are present in Go code - - gochecksumtype # checks exhaustiveness on Go "sum types" - #- gocognit # computes and checks the cognitive complexity of functions - #- goconst # finds repeated strings that could be replaced by a constant - #- gocritic # provides diagnostics that check for bugs, performance and style issues - - gocyclo # computes and checks the cyclomatic complexity of functions - - godot # checks if comments end in a period - - goimports # in addition to fixing imports, goimports also formats your code in the same style as gofmt - #- gomnd # detects magic numbers - - gomoddirectives # manages the use of 'replace', 'retract', and 'excludes' directives in go.mod - - gomodguard # allow and block lists linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations - - goprintffuncname # checks that printf-like functions are named with f at the end - - gosec # inspects source code for security problems - #- lll # reports long lines - - loggercheck # checks key value pairs for common logger libraries (kitlog,klog,logr,zap) - - makezero # finds slice declarations with non-zero initial length - - mirror # reports wrong mirror patterns of bytes/strings usage - - musttag # enforces field tags in (un)marshaled structs - - nakedret # finds naked returns in functions greater than a specified function length - - nestif # reports deeply nested if statements - - nilerr # finds the code that returns nil even if it checks that the error is not nil - #- nilnil # checks that there is no simultaneous return of nil error and an invalid value - - noctx # finds sending http request without context.Context - - nolintlint # reports ill-formed or insufficient nolint directives - #- nonamedreturns # reports all named returns - - nosprintfhostport # checks for misuse of Sprintf to construct a host with port in a URL - #- perfsprint # checks that fmt.Sprintf can be replaced with a faster alternative - - predeclared # finds code that shadows one of Go's predeclared identifiers - - promlinter # checks Prometheus metrics naming via promlint - - protogetter # reports direct reads from proto message fields when getters should be used - - reassign # checks that package variables are not reassigned - - revive # fast, configurable, extensible, flexible, and beautiful linter for Go, drop-in replacement of golint - - rowserrcheck # checks whether Err of rows is checked successfully - - sloglint # ensure consistent code style when using log/slog - - spancheck # checks for mistakes with OpenTelemetry/Census spans - - sqlclosecheck # checks that sql.Rows and sql.Stmt are closed - - stylecheck # is a replacement for golint - - tenv # detects using os.Setenv instead of t.Setenv since Go1.17 - - testableexamples # checks if examples are testable (have an expected output) - - testifylint # checks usage of github.com/stretchr/testify - #- testpackage # makes you use a separate _test package - - tparallel # detects inappropriate usage of t.Parallel() method in your Go test codes - - unconvert # removes unnecessary type conversions - #- unparam # reports unused function parameters - - usestdlibvars # detects the possibility to use variables/constants from the Go standard library - - wastedassign # finds wasted assignment statements - - whitespace # detects leading and trailing whitespace - - ## you may want to enable - #- decorder # checks declaration order and count of types, constants, variables and functions - #- exhaustruct # [highly recommend to enable] checks if all structure fields are initialized - #- gci # controls golang package import order and makes it always deterministic - #- ginkgolinter # [if you use ginkgo/gomega] enforces standards of using ginkgo and gomega - #- godox # detects FIXME, TODO and other comment keywords - #- goheader # checks is file header matches to pattern - #- inamedparam # [great idea, but too strict, need to ignore a lot of cases by default] reports interfaces with unnamed method parameters - #- interfacebloat # checks the number of methods inside an interface - #- ireturn # accept interfaces, return concrete types - #- prealloc # [premature optimization, but can be used in some cases] finds slice declarations that could potentially be preallocated - #- tagalign # checks that struct tags are well aligned - #- varnamelen # [great idea, but too many false positives] checks that the length of a variable's name matches its scope - #- wrapcheck # checks that errors returned from external packages are wrapped - #- zerologlint # detects the wrong usage of zerolog that a user forgets to dispatch zerolog.Event - - ## disabled - #- containedctx # detects struct contained context.Context field - #- contextcheck # [too many false positives] checks the function whether use a non-inherited context - #- depguard # [replaced by gomodguard] checks if package imports are in a list of acceptable packages - #- dogsled # checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - #- dupword # [useless without config] checks for duplicate words in the source code - #- errchkjson # [don't see profit + I'm against of omitting errors like in the first example https://github.com/breml/errchkjson] checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted - #- forcetypeassert # [replaced by errcheck] finds forced type assertions - #- goerr113 # [too strict] checks the errors handling expressions - #- gofmt # [replaced by goimports] checks whether code was gofmt-ed - #- gofumpt # [replaced by goimports, gofumports is not available yet] checks whether code was gofumpt-ed - #- gosmopolitan # reports certain i18n/l10n anti-patterns in your Go codebase - #- grouper # analyzes expression groups - #- importas # enforces consistent import aliases - #- maintidx # measures the maintainability index of each function - #- misspell # [useless] finds commonly misspelled English words in comments - #- nlreturn # [too strict and mostly code is not more readable] checks for a new line before return and branch statements to increase code clarity - #- paralleltest # [too many false positives] detects missing usage of t.Parallel() method in your Go test - #- tagliatelle # checks the struct tags - #- thelper # detects golang test helpers without t.Helper() call and checks the consistency of test helpers - #- wsl # [too strict and mostly code is not more readable] whitespace linter forces you to use empty lines - - ## deprecated - #- deadcode # [deprecated, replaced by unused] finds unused code - #- exhaustivestruct # [deprecated, replaced by exhaustruct] checks if all struct's fields are initialized - #- golint # [deprecated, replaced by revive] golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes - #- ifshort # [deprecated] checks that your code uses short syntax for if-statements whenever possible - #- interfacer # [deprecated] suggests narrower interface types - #- maligned # [deprecated, replaced by govet fieldalignment] detects Go structs that would take less memory if their fields were sorted - #- nosnakecase # [deprecated, replaced by revive var-naming] detects snake case of variable naming and function name - #- scopelint # [deprecated, replaced by exportloopref] checks for unpinned variables in go programs - #- structcheck # [deprecated, replaced by unused] finds unused struct fields - #- varcheck # [deprecated, replaced by unused] finds unused global variables and constants - - -issues: - # Maximum count of issues with the same text. - # Set to 0 to disable. - # Default: 3 - max-same-issues: 50 - - exclude-rules: - - source: "(noinspection|TODO)" - linters: [ godot ] - - source: "//noinspection" - linters: [ gocritic ] - - path: "_test\\.go" - linters: - - bodyclose - - dupl - - funlen - - goconst - - gosec - - noctx - - wrapcheck - # TODO: remove after PR is released https://github.com/golangci/golangci-lint/pull/4386 - - text: "fmt.Sprintf can be replaced with string addition" - linters: [ perfsprint ] \ No newline at end of file diff --git a/vendor/github.com/casbin/casbin/v2/.releaserc.json b/vendor/github.com/casbin/casbin/v2/.releaserc.json deleted file mode 100644 index 58cb0bb4..00000000 --- a/vendor/github.com/casbin/casbin/v2/.releaserc.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "debug": true, - "branches": [ - "+([0-9])?(.{+([0-9]),x}).x", - "master", - { - "name": "beta", - "prerelease": true - } - ], - "plugins": [ - "@semantic-release/commit-analyzer", - "@semantic-release/release-notes-generator", - "@semantic-release/github" - ] -} diff --git a/vendor/github.com/casbin/casbin/v2/.travis.yml b/vendor/github.com/casbin/casbin/v2/.travis.yml deleted file mode 100644 index a35e0622..00000000 --- a/vendor/github.com/casbin/casbin/v2/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -language: go - -sudo: false - -env: - - GO111MODULE=on - -go: - - "1.11.13" - - "1.12" - - "1.13" - - "1.14" - -script: - - make test diff --git a/vendor/github.com/casbin/casbin/v2/CONTRIBUTING.md b/vendor/github.com/casbin/casbin/v2/CONTRIBUTING.md deleted file mode 100644 index 4bab59c9..00000000 --- a/vendor/github.com/casbin/casbin/v2/CONTRIBUTING.md +++ /dev/null @@ -1,35 +0,0 @@ -# How to contribute - -The following is a set of guidelines for contributing to casbin and its libraries, which are hosted at [casbin organization at Github](https://github.com/casbin). - -This project adheres to the [Contributor Covenant 1.2.](https://www.contributor-covenant.org/version/1/2/0/code-of-conduct.html) By participating, you are expected to uphold this code. Please report unacceptable behavior to info@casbin.com. - -## Questions - -- We do our best to have an [up-to-date documentation](https://casbin.org/docs/overview) -- [Stack Overflow](https://stackoverflow.com) is the best place to start if you have a question. Please use the [casbin tag](https://stackoverflow.com/tags/casbin/info) we are actively monitoring. We encourage you to use Stack Overflow specially for Modeling Access Control Problems, in order to build a shared knowledge base. -- You can also join our [Discord](https://discord.gg/S5UjpzGZjN). - -## Reporting issues - -Reporting issues are a great way to contribute to the project. We are perpetually grateful about a well-written, through bug report. - -Before raising a new issue, check our [issue list](https://github.com/casbin/casbin/issues) to determine if it already contains the problem that you are facing. - -A good bug report shouldn't leave others needing to chase you for more information. Please be as detailed as possible. The following questions might serve as a template for writing a detailed report: - -What were you trying to achieve? -What are the expected results? -What are the received results? -What are the steps to reproduce the issue? -In what environment did you encounter the issue? - -Feature requests can also be submitted as issues. - -## Pull requests - -Good pull requests (e.g. patches, improvements, new features) are a fantastic help. They should remain focused in scope and avoid unrelated commits. - -Please ask first before embarking on any significant pull request (e.g. implementing new features, refactoring code etc.), otherwise you risk spending a lot of time working on something that the maintainers might not want to merge into the project. - -First add an issue to the project to discuss the improvement. Please adhere to the coding conventions used throughout the project. If in doubt, consult the [Effective Go style guide](https://golang.org/doc/effective_go.html). diff --git a/vendor/github.com/casbin/casbin/v2/LICENSE b/vendor/github.com/casbin/casbin/v2/LICENSE deleted file mode 100644 index 8dada3ed..00000000 --- a/vendor/github.com/casbin/casbin/v2/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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. diff --git a/vendor/github.com/casbin/casbin/v2/Makefile b/vendor/github.com/casbin/casbin/v2/Makefile deleted file mode 100644 index 6db2b920..00000000 --- a/vendor/github.com/casbin/casbin/v2/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -SHELL = /bin/bash -export PATH := $(shell yarn global bin):$(PATH) - -default: lint test - -test: - go test -race -v ./... - -benchmark: - go test -bench=. - -lint: - golangci-lint run --verbose - -release: - yarn global add semantic-release@17.2.4 - semantic-release - diff --git a/vendor/github.com/casbin/casbin/v2/README.md b/vendor/github.com/casbin/casbin/v2/README.md deleted file mode 100644 index 36549f55..00000000 --- a/vendor/github.com/casbin/casbin/v2/README.md +++ /dev/null @@ -1,296 +0,0 @@ -Casbin -==== - -[![Go Report Card](https://goreportcard.com/badge/github.com/casbin/casbin)](https://goreportcard.com/report/github.com/casbin/casbin) -[![Build](https://github.com/casbin/casbin/actions/workflows/default.yml/badge.svg)](https://github.com/casbin/casbin/actions/workflows/default.yml) -[![Coverage Status](https://coveralls.io/repos/github/casbin/casbin/badge.svg?branch=master)](https://coveralls.io/github/casbin/casbin?branch=master) -[![Godoc](https://godoc.org/github.com/casbin/casbin?status.svg)](https://pkg.go.dev/github.com/casbin/casbin/v2) -[![Release](https://img.shields.io/github/release/casbin/casbin.svg)](https://github.com/casbin/casbin/releases/latest) -[![Discord](https://img.shields.io/discord/1022748306096537660?logo=discord&label=discord&color=5865F2)](https://discord.gg/S5UjpzGZjN) -[![Sourcegraph](https://sourcegraph.com/github.com/casbin/casbin/-/badge.svg)](https://sourcegraph.com/github.com/casbin/casbin?badge) - -**News**: still worry about how to write the correct Casbin policy? ``Casbin online editor`` is coming to help! Try it at: https://casbin.org/editor/ - -![casbin Logo](casbin-logo.png) - -Casbin is a powerful and efficient open-source access control library for Golang projects. It provides support for enforcing authorization based on various [access control models](https://en.wikipedia.org/wiki/Computer_security_model). - -

- Sponsored by -
- - - - - - -
- Build auth with fraud prevention, faster.
Try Stytch for API-first authentication, user & org management, multi-tenant SSO, MFA, device fingerprinting, and more.
-
-

- -## All the languages supported by Casbin: - -| [![golang](https://casbin.org/img/langs/golang.png)](https://github.com/casbin/casbin) | [![java](https://casbin.org/img/langs/java.png)](https://github.com/casbin/jcasbin) | [![nodejs](https://casbin.org/img/langs/nodejs.png)](https://github.com/casbin/node-casbin) | [![php](https://casbin.org/img/langs/php.png)](https://github.com/php-casbin/php-casbin) | -|----------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------| -| [Casbin](https://github.com/casbin/casbin) | [jCasbin](https://github.com/casbin/jcasbin) | [node-Casbin](https://github.com/casbin/node-casbin) | [PHP-Casbin](https://github.com/php-casbin/php-casbin) | -| production-ready | production-ready | production-ready | production-ready | - -| [![python](https://casbin.org/img/langs/python.png)](https://github.com/casbin/pycasbin) | [![dotnet](https://casbin.org/img/langs/dotnet.png)](https://github.com/casbin-net/Casbin.NET) | [![c++](https://casbin.org/img/langs/cpp.png)](https://github.com/casbin/casbin-cpp) | [![rust](https://casbin.org/img/langs/rust.png)](https://github.com/casbin/casbin-rs) | -|------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------| -| [PyCasbin](https://github.com/casbin/pycasbin) | [Casbin.NET](https://github.com/casbin-net/Casbin.NET) | [Casbin-CPP](https://github.com/casbin/casbin-cpp) | [Casbin-RS](https://github.com/casbin/casbin-rs) | -| production-ready | production-ready | production-ready | production-ready | - -## Table of contents - -- [Supported models](#supported-models) -- [How it works?](#how-it-works) -- [Features](#features) -- [Installation](#installation) -- [Documentation](#documentation) -- [Online editor](#online-editor) -- [Tutorials](#tutorials) -- [Get started](#get-started) -- [Policy management](#policy-management) -- [Policy persistence](#policy-persistence) -- [Policy consistence between multiple nodes](#policy-consistence-between-multiple-nodes) -- [Role manager](#role-manager) -- [Benchmarks](#benchmarks) -- [Examples](#examples) -- [Middlewares](#middlewares) -- [Our adopters](#our-adopters) - -## Supported models - -1. [**ACL (Access Control List)**](https://en.wikipedia.org/wiki/Access_control_list) -2. **ACL with [superuser](https://en.wikipedia.org/wiki/Superuser)** -3. **ACL without users**: especially useful for systems that don't have authentication or user log-ins. -3. **ACL without resources**: some scenarios may target for a type of resources instead of an individual resource by using permissions like ``write-article``, ``read-log``. It doesn't control the access to a specific article or log. -4. **[RBAC (Role-Based Access Control)](https://en.wikipedia.org/wiki/Role-based_access_control)** -5. **RBAC with resource roles**: both users and resources can have roles (or groups) at the same time. -6. **RBAC with domains/tenants**: users can have different role sets for different domains/tenants. -7. **[ABAC (Attribute-Based Access Control)](https://en.wikipedia.org/wiki/Attribute-Based_Access_Control)**: syntax sugar like ``resource.Owner`` can be used to get the attribute for a resource. -8. **[RESTful](https://en.wikipedia.org/wiki/Representational_state_transfer)**: supports paths like ``/res/*``, ``/res/:id`` and HTTP methods like ``GET``, ``POST``, ``PUT``, ``DELETE``. -9. **Deny-override**: both allow and deny authorizations are supported, deny overrides the allow. -10. **Priority**: the policy rules can be prioritized like firewall rules. - -## How it works? - -In Casbin, an access control model is abstracted into a CONF file based on the **PERM metamodel (Policy, Effect, Request, Matchers)**. So switching or upgrading the authorization mechanism for a project is just as simple as modifying a configuration. You can customize your own access control model by combining the available models. For example, you can get RBAC roles and ABAC attributes together inside one model and share one set of policy rules. - -The most basic and simplest model in Casbin is ACL. ACL's model CONF is: - -```ini -# Request definition -[request_definition] -r = sub, obj, act - -# Policy definition -[policy_definition] -p = sub, obj, act - -# Policy effect -[policy_effect] -e = some(where (p.eft == allow)) - -# Matchers -[matchers] -m = r.sub == p.sub && r.obj == p.obj && r.act == p.act - -``` - -An example policy for ACL model is like: - -``` -p, alice, data1, read -p, bob, data2, write -``` - -It means: - -- alice can read data1 -- bob can write data2 - -We also support multi-line mode by appending '\\' in the end: - -```ini -# Matchers -[matchers] -m = r.sub == p.sub && r.obj == p.obj \ - && r.act == p.act -``` - -Further more, if you are using ABAC, you can try operator `in` like following in Casbin **golang** edition (jCasbin and Node-Casbin are not supported yet): - -```ini -# Matchers -[matchers] -m = r.obj == p.obj && r.act == p.act || r.obj in ('data2', 'data3') -``` - -But you **SHOULD** make sure that the length of the array is **MORE** than **1**, otherwise there will cause it to panic. - -For more operators, you may take a look at [govaluate](https://github.com/casbin/govaluate) - -## Features - -What Casbin does: - -1. enforce the policy in the classic ``{subject, object, action}`` form or a customized form as you defined, both allow and deny authorizations are supported. -2. handle the storage of the access control model and its policy. -3. manage the role-user mappings and role-role mappings (aka role hierarchy in RBAC). -4. support built-in superuser like ``root`` or ``administrator``. A superuser can do anything without explicit permissions. -5. multiple built-in operators to support the rule matching. For example, ``keyMatch`` can map a resource key ``/foo/bar`` to the pattern ``/foo*``. - -What Casbin does NOT do: - -1. authentication (aka verify ``username`` and ``password`` when a user logs in) -2. manage the list of users or roles. I believe it's more convenient for the project itself to manage these entities. Users usually have their passwords, and Casbin is not designed as a password container. However, Casbin stores the user-role mapping for the RBAC scenario. - -## Installation - -``` -go get github.com/casbin/casbin/v2 -``` - -## Documentation - -https://casbin.org/docs/overview - -## Online editor - -You can also use the online editor (https://casbin.org/editor/) to write your Casbin model and policy in your web browser. It provides functionality such as ``syntax highlighting`` and ``code completion``, just like an IDE for a programming language. - -## Tutorials - -https://casbin.org/docs/tutorials - -## Get started - -1. New a Casbin enforcer with a model file and a policy file: - - ```go - e, _ := casbin.NewEnforcer("path/to/model.conf", "path/to/policy.csv") - ``` - -Note: you can also initialize an enforcer with policy in DB instead of file, see [Policy-persistence](#policy-persistence) section for details. - -2. Add an enforcement hook into your code right before the access happens: - - ```go - sub := "alice" // the user that wants to access a resource. - obj := "data1" // the resource that is going to be accessed. - act := "read" // the operation that the user performs on the resource. - - if res, _ := e.Enforce(sub, obj, act); res { - // permit alice to read data1 - } else { - // deny the request, show an error - } - ``` - -3. Besides the static policy file, Casbin also provides API for permission management at run-time. For example, You can get all the roles assigned to a user as below: - - ```go - roles, _ := e.GetImplicitRolesForUser(sub) - ``` - -See [Policy management APIs](#policy-management) for more usage. - -## Policy management - -Casbin provides two sets of APIs to manage permissions: - -- [Management API](https://casbin.org/docs/management-api): the primitive API that provides full support for Casbin policy management. -- [RBAC API](https://casbin.org/docs/rbac-api): a more friendly API for RBAC. This API is a subset of Management API. The RBAC users could use this API to simplify the code. - -We also provide a [web-based UI](https://casbin.org/docs/admin-portal) for model management and policy management: - -![model editor](https://hsluoyz.github.io/casbin/ui_model_editor.png) - -![policy editor](https://hsluoyz.github.io/casbin/ui_policy_editor.png) - -## Policy persistence - -https://casbin.org/docs/adapters - -## Policy consistence between multiple nodes - -https://casbin.org/docs/watchers - -## Role manager - -https://casbin.org/docs/role-managers - -## Benchmarks - -https://casbin.org/docs/benchmark - -## Examples - -| Model | Model file | Policy file | -|---------------------------|----------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------| -| ACL | [basic_model.conf](https://github.com/casbin/casbin/blob/master/examples/basic_model.conf) | [basic_policy.csv](https://github.com/casbin/casbin/blob/master/examples/basic_policy.csv) | -| ACL with superuser | [basic_model_with_root.conf](https://github.com/casbin/casbin/blob/master/examples/basic_with_root_model.conf) | [basic_policy.csv](https://github.com/casbin/casbin/blob/master/examples/basic_policy.csv) | -| ACL without users | [basic_model_without_users.conf](https://github.com/casbin/casbin/blob/master/examples/basic_without_users_model.conf) | [basic_policy_without_users.csv](https://github.com/casbin/casbin/blob/master/examples/basic_without_users_policy.csv) | -| ACL without resources | [basic_model_without_resources.conf](https://github.com/casbin/casbin/blob/master/examples/basic_without_resources_model.conf) | [basic_policy_without_resources.csv](https://github.com/casbin/casbin/blob/master/examples/basic_without_resources_policy.csv) | -| RBAC | [rbac_model.conf](https://github.com/casbin/casbin/blob/master/examples/rbac_model.conf) | [rbac_policy.csv](https://github.com/casbin/casbin/blob/master/examples/rbac_policy.csv) | -| RBAC with resource roles | [rbac_model_with_resource_roles.conf](https://github.com/casbin/casbin/blob/master/examples/rbac_with_resource_roles_model.conf) | [rbac_policy_with_resource_roles.csv](https://github.com/casbin/casbin/blob/master/examples/rbac_with_resource_roles_policy.csv) | -| RBAC with domains/tenants | [rbac_model_with_domains.conf](https://github.com/casbin/casbin/blob/master/examples/rbac_with_domains_model.conf) | [rbac_policy_with_domains.csv](https://github.com/casbin/casbin/blob/master/examples/rbac_with_domains_policy.csv) | -| ABAC | [abac_model.conf](https://github.com/casbin/casbin/blob/master/examples/abac_model.conf) | N/A | -| RESTful | [keymatch_model.conf](https://github.com/casbin/casbin/blob/master/examples/keymatch_model.conf) | [keymatch_policy.csv](https://github.com/casbin/casbin/blob/master/examples/keymatch_policy.csv) | -| Deny-override | [rbac_model_with_deny.conf](https://github.com/casbin/casbin/blob/master/examples/rbac_with_deny_model.conf) | [rbac_policy_with_deny.csv](https://github.com/casbin/casbin/blob/master/examples/rbac_with_deny_policy.csv) | -| Priority | [priority_model.conf](https://github.com/casbin/casbin/blob/master/examples/priority_model.conf) | [priority_policy.csv](https://github.com/casbin/casbin/blob/master/examples/priority_policy.csv) | - -## Middlewares - -Authz middlewares for web frameworks: https://casbin.org/docs/middlewares - -## Our adopters - -https://casbin.org/docs/adopters - -## How to Contribute - -Please read the [contributing guide](CONTRIBUTING.md). - -## Contributors - -This project exists thanks to all the people who contribute. - - -## Backers - -Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/casbin#backer)] - - - -## Sponsors - -Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/casbin#sponsor)] - - - - - - - - - - - - -## Star History - -[![Star History Chart](https://api.star-history.com/svg?repos=casbin/casbin&type=Date)](https://star-history.com/#casbin/casbin&Date) - -## License - -This project is licensed under the [Apache 2.0 license](LICENSE). - -## Contact - -If you have any issues or feature requests, please contact us. PR is welcomed. -- https://github.com/casbin/casbin/issues -- hsluoyz@gmail.com -- Tencent QQ group: [546057381](//shang.qq.com/wpa/qunwpa?idkey=8ac8b91fc97ace3d383d0035f7aa06f7d670fd8e8d4837347354a31c18fac885) diff --git a/vendor/github.com/casbin/casbin/v2/casbin-logo.png b/vendor/github.com/casbin/casbin/v2/casbin-logo.png deleted file mode 100644 index 7e5d1ecf95b4f0a47e297dc1269b2faa309837d3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 34267 zcmeFZ1yo$iwy@i{1cHSi!QE-xU4v_|;56>;?!h6!-3bl>0>Le~g`mM5f(Mt^*}~4* z=bZoMzvsU9#vLPT4Cu*PbIz*zs%lo%?54vM`fS%xVX3&fy|7|%=BOldIvXaM}1d%YX{Qbo&4!X z6y#uNZ)WRgW@AnC-LJlZjguoE3CZ_@9p}su>wFf-FH+AZtelupQICw6is}akOzTwfQ$iK0N-n1%vxUR`#Lne_3BE ztAAOvgQJ);7{MP%|D~maikmHnQ3>Q=<796L5_1MOh4f#w-oa4`^jGivge$Q6zjWki zX8dpbe1Gz9A%I-X{*Br9C%>EhHl}{>YF;ojZV`KszN3x3ij9pW|L?<9;m^Jx5)mPy zQZutQvT<>s=4Jf5_FrS>FGnCzeMb;KcuaH91KH?-tSZdR+$=zDCU#mNCpQrIgOlGi z|K>y1#>mXr?Vo(GaI-LTGco<>;|I;Z`vA{DBYj8xpYrmf?hk&947rVM?5*@2`OU2K zO+bvc)+W4+f8G2+^I>Fii`ZD&*n_JD;%DJy{8zVsu=;JZazD3raMZUp1U(n!2j5^Y zGc)35(&q#LSq+%!LB^cM^qkDBO!NjuOic8K`kYK40}zPA*uda7h_bRjn*Wn)Q5!?2 z?=$WX*G6F1tVSS^F^eIPo`aLgn4XK3m6hIrL!XNt1Y|bmVg~B7a~T``>G}ure{wBv zZw8K*`j$WFe6RiYB8)-ITpY|mV|sS5Lwa@=R%3AOjg9G2w z?B~`u{2mec4ZqI?5SYS0-2JOs50-zJnf-GI{v3ke{r_P8@5^v81zG=}Ce-h)e$)E* zP8@8E9bNS8K|&_rG4Wqa^WPo*qs8An^D=&4JS@%rU+4n|edqtI2RIBttn4f-Ec76D z@M6f$#>z~u&jA9DNoE697NEYdp^*{$pFRBF?EzMHZdR5*!_ogQJ@D7qH8jNF!34rVq^W+QqK3yT3gy8$?IaIte3(i`Xl4fKscTx^Ey9Dla&zuReS zOx!G7zdFtFA==qkJA>^1Z{i&|s_KKcxFCB6eq(zZE24+Rk;u`8NZ;1h(#%l*dmv?W zwl?}>!}zce{@Hs!`1t>DfEt19&HiuV$`7?P{1X$=|FSm!$C32sb`1a7TJ~#F{^J(p zKkhU(W>!`mp=FxIFd5cbFyJI`yodCuZ*Psd)oXTPf8G*5eR&QGoWYX;$)>~0Uy5T^^J{L z=s7u!nGJ!=AZGBa{j*ztP0H`btlv&~|IuOYKkl@jJB$A(%irJf8vnZw62G4b|M6h{ z=VAY!5AxqrM&KNV=JA*-);XgRkb#A0!RmXq^Y?t5GC0Ez;%8@LV`1ZE{QK>{TPT>hf-KcV&A^E>hwtei7EW+b{>|v` zPyVH)#$T3P;0(iGhCe*`!|?aH@ewTsq;cbQ=y6qwV^gl2B)uR7- z-wz&t74m@MXM|t4eumP6&M#aKD1Juxh3jW1J?Q+x^?>4MgkQLRhSG!1FI*2Oen$9( z>t`rE=={R{ z_=W3dC_U)>!u5dSXM|t4eumP6&M#aKD1Juxh3jW1J?Q+x^?>4MgkQLRhSG!1FI*2O zen$9(>t`rE=={R{_=W3dC_U)>!u5dSXM|t4eumP6&M#aKD1Juxh3jW1J?Q+x^?>4MgkQLRhSG!1 zFI*2Oen$8|;zIoEi+e!U;BV`30e>wI2O35=_$z&g3?-Fh0RVS$0Khi@0JyvdzitBn zPCx))M-KqtP67b1Y~pmg#Q^|5hv%X~Dz3A8=`KkGs?EIuCjE1D2gX|Nq<*N7#KeMv zCBFWw0Yo&2Ikr_E-~3;{vd6^iwh$_HL{kjS$vL$z_5&yhqmO&k9ke*@y!T0)F~V>@ z_o@d;Z=`N|IoGfpBqy_M-ngSFNeKtSqmgvo!R5xpd!Oz_*%pXn_gn0!-z_OwUkzS& z_Q5md0Bsg{pEBymFelG{U$?Ar!=R}8hJ|8fvAA4RlCpS+5@Z60{rG17Mwx0^e@Yag#)pvE9o9BT`Tp!wVHcO zX+&lU$OWwWK5v86!&N}+0^oQ$5_M*0|~%7@8Uqm4w59|)HO`3dqhjOP@bGwh(AavRbe z@&`yu_(aiAR1v6=lOz_C$0Gvwp7p)7G&Cfyp3*l~7Zt(#20g;kxtwZZWRitthccMwbHrXTP|?t6^7`C)lElKtN(OeKWXhYFZO=&H z*>xdkkCYV`>-Q&6XP*j);|Lgra&zbRmH*pLC+@Q?-zM-ao> zY7!m!AOa;uy>R@*50Uy&(7wABgcp*Qe&nz@OpY4~3G_JId-UqnE0koP>1;A|gthSA zm}fc^1kp9N%aHv81M(Sc7N7gFR&F+j)1|=|HUw)Ac3YyKPd15%IL(fqhu=YP8vw{BoQeg4eswDaknhK9zV zCj!SbMO?jI?~rUR)|U|Co-2Igt3{DyUNrg!dLVoioXkWQ5GgOADbJBu6p8AH*QR=v zvxX&k@RSSO%8HT_ZqMtpuW;TMorDFY4e+}|61I!pPf3^tofwsPZ{g**x5?hnYdO#Q z!#v6;E-Uk@DK6f&(w^eL2|g-7HF$+eLK|2qTmWRo@qLVkdb8jc-hSZtCAH1QH#)N8 zJrCT)qe^Jg-Q#o3EZ(HKp>~!Kc%~|h{i_l4SIEWB?AF3+Li<28neA#8xm$KVuua<{y1`J z^?K_sD@M%kIn(9hrSd--*Sug(9@KpEZUz{E2@VaZufoF@(1qz>G&|RsZjhE-mr~ot z{D76p9hwj}5LycC_hWea4(NxRwpa?Z%X$zjevNvDEf6=1wh|4WgpttYpoWEmgyoTv z+MZ@Xs6W1W`Vn~(xm>&HO&A8{0;kz{o{O4_itWX6i1N#qG9VE7`Z_4$Z8_+r6Y}fT z9>o_=)QpMSG*9sMk3Ghu-a>@c>{;)vGE(xNNHTml6b6iQrEY8(Yo_3u*;qu@)z*q? zX=x4cjqn()_rFee3NCd$;%0}o3eY6Q& z0*)j;=_Mu0p~yIxh^@2bySJ6asD~T>xCpoFuO#IN72Z$NiTUCF`Aw@ZsKurG!_sCq zRs5P&r&n%dWF*I%#6-ekGtIsklguGMID+Z*A{5h$@__VxUm04~@^-g1N_bvYZ2;t= zOV#}mKIi&L=&S}RBc*Xq5^r`!ABOq%PKTwn^+t+CIdQU#Gx(d5c%L!6UIqcUZC^tx z!wV_Sua!m0erSG|jI&Cc%$1EkcXZerIwU7W6`pKqZfepU3`;TfhRH^gemiaAGD1KM zgkwVxv1`^S$Nn1hm3EmM<$RaNb_u>=WI7y^Hsg@@Ktj1tu6d&%)q16$w!)|*5Md1u z>+Y7LH1RHCam;tI4!`=VsrBP!qp_9sCECU;@_xHTcO;J?2T4-cFvQw%&D!vzuBW=t za2b-HM$N!AhZDGfpj9hRc*bsdkqMrwyvU+{Ksi=IdYl|P6TktcWWTgQ>Fj*hc;Vv8 zdrU3$ckh!$>HJ5bgJOKfhC&zw;Gl9+GjmX;VkEGn}IAjdcwwNdGv`D955yY>7&IrIf>%V%ORH~N-*eqq(hk3w>ZA98e)-6%11~37 zj^_17<8JwCabbqRmqw>n%^Kq&j3+NJ=(rIa*6X8R4~G&u1GoU8CF z)F5g7Q)@hhLTF8$ST+6SL*B-oL1#SK%JCT#1T+HVg?p5zOzmp5r?zcj-Y||LCXo?C z_mvKf!O81=&Z8N}fm@7+&#nystio~^w;Z6+(vYM`9&Qr840}p84h}z9@z~btf;=%A z@9o#iz*lt3&GEoXuWysJ_4S6IhqKmd&d~%eJ1@$kPa*hl;W_!0`oA}BTQP5!gq&>n z4zfG(OPB@|0d3-H<8DhQcrou8PUkt$0MGbLNZ2Ik4%TITBfzd72bq7JO4NI03r^>K zqn-X&)b!zT@94KvP0jMQ5%oJF=WBW zq%PR2b~SFtX(P*InO@G#;N3dmoD4Bm1xL1?q*l|onSe`SEjUh~FqQ;s6J ziu-*$%)Ed?pMcIwDLW8#z2~=8-t)w{qfTxrVsQ#y6{B&vEW61PRSsk3WUNfr6@>3W zHf~@Yh>@S*c`A-h`O^P@(={XL)YEeWB}wqGX>+xS%M(G&L`UohMnI4S$#Zd&Qs9>Q zeDR)Rc5d$eo%ijPmY=bnhpm->Co&9tM^M-BSqAuJ1^NV;QK~Jm+~=pQVWN8ppkRY1u0_5%?%AvV?io zW`!`Uo0@@fGcmI%28*zP=jHorN-5t&h4oR7j(T4U@sGE-MU`8coj~K^6t>-_I;)Y3 zEeU~swbnB>Rm6_r@#EE+N?i}=nmp(+vE0O>=KVVIFnkvXOttwSMpo7(N`XrRjxUZF z<-7bf)?XSAB&l7XyINzv=x^kTfS%>zx9dR4ePTVT-M!9pV26hOz_GHpVVcL=e!V;4 zX=D)Bm?X^&9AVXvT9J3dO^F$#c5X0I3P1m3Wa0 zXCeU!g<~t`tTVVnb<9kvVxDh46*ky<;>NJf;s$TsitRKKr8`tUIns?R0fHO9Xm<8I z;q}Sek&rHdt|I?OtPn%xyX9I<&R<=8BU>-J85>TbcoGz_!btlmmo%2#`7;hy-51Ii z`9^w&{9bV3K(6@gmen7x65b~{a^D_becQE(QQAj>_c<{oy)&GI{uDOlhrvo*e#C3G zZdu=Zh2QA=SfcX`hA<_@Sn<7BeA$H2?zA7h4pzVC>T}8W{`ha?nsV)gL2qg-Sd4g) zdk+@y$N+O8PbF5HCp8v$7({vk(%*=Wqq)ZMl`q3;b~q0#Wud={mXkr7ATN^}kpXXN zhMkXi3AHfC3D?HOc_wZppp^9*iUgwUQYkYq8eZ{D+ufI-Zw}Nalv+0^W zrD@4NduKQ^U52w)#~QV|^8C=T(xr4}9pn41bGpuI?oB$6%ia9>Z6w694O#6q3NjSc z_&}(+o#Pl|VJ@7fG`!qI;Pfp0GBh3`bITIcH)>NKXd!i`(GxXIN_LDzzqDTgdFjB|`DNp2`h(Sj(@P$7s|bz11fLtoBCto_t7K<$R`CrtN|n z?D-fUsv&>bTt`;GPbjeHO;)BKtUToX))@tK?KJMIeuqJNr|CGhCw^0HPWY3wwdHS$ zl?$2mJD|b)Gbj8&R8wI$j})u)+yMub6n=aUG*je{SN@0-t4ZN_vUS05 zOE?0?$k!^RpnK)0;f0P)d0yvdt2O6~27b}UJ{+onU%gcP?9>kX; zCsN?k185x+FwHX+lf)9%kK!57g(eM@DoKb|;E=?-XEF#$6F#14GQFHYu}f7Y0EvOf z#l*zy=IW#^=N?<#iIhPkY^!c{B69WG4kzs-O1qv{0aX#V~5Q*(9y+{eeKVyw{a-#M`pM+EPa~H6p@FulBWuSLJ@I zueAGK640={XV_Wp`+_E!PQSCWLwVdPaK}XWev3p-VATt+`2w5&c=^$oV*mmMr6CV{ zFa>z7hsF%jzN@++Xl{R9R6TZ^c;}UwV)mNXdo!|@!xBZ!ER+dqpxQiVjB3@NJ-Vv+ zB-wVzFd^L$CpM0Tb!j<-aN`@tf*{;r|B*_|!GKJ|88HbP3q(;#DG5QeMaE_ja>^MD zRE#7mtJEnXZhBd1{X&)st=Jj;r#kqett&W)>5Mj1VAIF;W0;Hz%cE{`aut=R)i`N} z4XoCNu&+GMhpCG-Jm`I#Y#&m9!^NuAJJ;Qy6nxSC{ z@(rCv$MrC00ByyGxXHI_P^g)_(H|isNb>VaO5)V%f;Zh*I&i+gA?YO=h09mzh=0(#kAIvaPWk-?QfD_ zj^a63n@mhp*3xQvl`2_$gD|V}TuTWN8eO?^*LSxOe0r-koMX3c+!i+;$rxJei%;VB z;x;A|W_`N4ZIZEkHg}L!&_Xcfq-tDUsAw$NPkL7_v)o+9A!ygC8(O~l{xReHy@Y1H z&0{sw(5m2BS6(?;SvFxRtD9t#%=Oho&xo2~?pNU42W7kr1>tP1*@W_xu1~W^KXu{Z zWQAuChgxads8b-Sike!yB-v8B*pculnim7CTB+)x`IVg`(s0oY^!T}5o-D*WKCiRz zv9B_xR7{>ELgw3Uhe&B6p!m(RWHC*f93?w`NIDTZji#N z8$9b8&)t5tNpt2(HR9dD%;sVK+JeXZVBC3Y=BBPIg!U9Q4Rw3}y87L*y^UiMy1+>k{`@kHz~twAQ9eV}_Os1BT{PB`|B*CD9DJK=`JB zuhOtYN7Q4q8gH&BTMjvER_p^S^atp2T!K1sQxA!C;bpR`ZSjlCN0Vt4R2AP#Ycf(( zXTQr2%9lj)#xTf_q68YTOUQ#GeIG4A>e z0}L@XhxL3p^CNJz{hlt1ES)~}4a*C0qTDt~N;q&!n0jq@@>(r>+g*K!xJ%s-;H14xUthf;jMMmPWdOW4fxUrtqOmRWBhVPS;?mTH9 zb$M18LF882_jxSP9@ioTyc3_(aP1tkbpPso5tc*?F8LjbxqwhA^I zojjj#&+bx8j*FdwCmK#Gl)O7%vhU5lb=H@$kC*;|41I1iybj=8hfFGe!1cjBIHz_& zoPz7TsWOzr6wq{kN{LXwqHxRZ@e0oS)o5KiKE z^Ec}Ufw2O_Jv8GPn`KVgQ_uv^8OL4%n5cJ8Rm5#94t>yWS|N*sHEaoCbO2E`bi1s? zft??ze41OC0L~g*Qr~D626+c|lTA45cP0iS2?Meb=meVUf%ASeXguY+@C6iR4y<)+ zjvKG19UW6Npi8x`*$dO`X+{Ljkz5w+C~eAK4*A2Jyx+=+R?^k&O__ZAL?2elvF~$Q z`{y*du;l~&j3aU~q)aP~^hlg^s8{%PTHIr%3HWn$OrRZB0!xo{Gu-ZAC?YC0 zZ&1=k6eS3UHX?VORkIz)RkjIi3T0C))9oh?hLIA!zLmlizYCm3$$Cx=-W}l%C?vNN zG!1ap!gv(EJ)Q2u(}WUNz(Boeg&4?Buqv|jh^)NYY%vC;i_RC$7j?hUAh2vo-{c|K zqShGPj{=Ib0$E+(llEtmvomRzY~c<8ct4kE3?)2|Z`hcdGMIZBE14ie(>GhMW|&0L zGCCS7%G!5Q#+3J@%h8rM?BKejF{|J$`Y2?E%_}?Gux9DGP*D=g*;>Dy9bEqNAV&Kj zD?@RayxmIuuXC;~(fZgI=p>LNDQl4`&;mebr#&v|lXzznmLg{9v}$nco+KFue*XMIQ%h^q zN!4Qh+>2GV6MnxPj-rcK=OFaZID|&vOF-e2aDFq^9Xc$>u>@3a$4P1VX} zT>qgOg2@8=Az*1!avO0Qnaavbyve0`c(M*TkHybRCogPUNg*(NJN=5=)5K@+qZ*iq zRCxT5+i2SlNYR|YDe}iO5++K5N%gRz@6pu#sw-TO5R(;l~BKeM=-Cai!1%v2G`(8sfdEct3YrgQKGk{!n4+xy#ah@$!?9u2zndI$Ll zWSPj}<%VkVPsz%rPS5xx8fOfev7z(6kTs6Rz&mCQ#_&!jWYMg!y!{AD&0oGKDUhcm zRX}fs?-0u#Jf!CE$}o#OQBY1`)?Y;kxPscLjN@{)ei@Ausl<~1c!PhajYz}*>a$&c3WOUZ(Z83t}_`Gdjexth$yg-5lJtG#K)kG zx-F<}-nXsi(Z#~B-VuL*IoaJ6YVkNmz%>u1>VP+7iJWKlGy$-r&`$t1!a_F(c5?hA zP0yMV^P(9ULdXlc;h8$u;58rmhY)$dNgtua0pzZ4qMvTgj@vgZ?@Go}UmRDDv21w& z7WA(3OWUs-zL)b)Ke*uRRj{i}RSb*Xdn&p-Qs6@`@psvVl_|o!u&%uG$c-(8!h(tL zanG;-`PKWG_}#<2h%|jy8iPFxm8df=fu=&bX|i>wnH0|%o*OQ2qPeHnAF(3f*iej; z;{Jp%)A%i#h$(z_E~%LVnrx#^}+NvuW)lHFxGUwE63B_Ag8_**h+X+36 zH=@)SlwxkXeyxXX6+Xjr1DWJ0RK}lk4BbY0?*lX_Gx|T%o1Gf*$VRp6gBS`Y^QgzY z;>yK8tD%XePcgGfLQiR?GF_b1k>F7mv3gh`olpQP6ok#iN%Q9BF7ASQ&w4Ml9(%%H zAlZ%rru;Ecr=MX9-up8YK}Nyx6G+O61=JeTFYzxGww+uHO5KqhK0oU>IDo5$K)YUq z09N|326B;JTz7cu%t77ZMBI-Pjhtw->3VQwKu006#@)fcM}egLW_wfROYK~*D-Tr; z`xIp<{T}H;sBN$jD%3OtM*Kng=5_rOWMo~XFjJY z?z)YXs$0Ai1*fz4a`9PAI=XtUYF>#jYSji)!Pj17b&Re&R>wZ{OtTIOFXGywp4b)5 z3+~4ItYPThT=5`iDDWuH{)sRy$FHiU5)r8}%;L=pReKii=iVw`? z@=oEBmr$3H%1>4GdT3Z4xE?8QPM++J_=JVnyw9$P_rN{$S{fx*$2te7!Ju3EST^fI zGawH>5((S&tw0`|K7g>M6I|Iv;fK8OCS(G?uT}5&3hwBx6&qOH-XYfZwHa>&q8Ebk z%y4g9u#zh;WOcyT@QhhZ720DrKH$`o);D@wq+!RF8DMA{l9)sy^^S}B%E*2@|32~N zTCDNw*w|RxxtdShxqM^9Wqu+0WXZ<{f;WQ-ICj*`WQ_H@ACg&<(`<{QTt$Pr#72#G zE$d`v@zP0_l{E}j%(+9FJu!O4a4+@<_jf+0u0ht{ZZ*-B4ab&yp`;ez$;+BkK7U4F zDtQ>O%)+&=WOkJVX^9{k)l(25G&@lQ^fE{poI__;xO|io-@U%h>#-UFX3+^@DqkFad90ybqNWIK0}9Hj+Q(pw~GF^5DWn8dHxV(ZJbZz?3l zyxvN0n|{DYm3iLYbciGh^5&3m?k}aw&lH{S+B?$p2)&3##l?|=;~-Rsl4zEpWzDhF zTvs=^GQ^G=>>^&t8*N6h%^#mR@oL}6Z@k7If#`lz9Q6r(l7@;Ut3NOeg&J$N@dJsh zVAbPEw9uqc)3&_z)&k>+3CkpJ&cgItZvyRetvZf(`*tj#Zm~4So^3}{F}%}$o2qZv zJiAzmJ2s@je(UW!weM+N00=3tip0fXMZ&h$`Voy~G4YNQUFYPjH-nc(%3g@Z7vG4a zD4O+o4?_fxHMQF=4`BB}fS|*xFb7{<7^OA6r4nL_yDU$32Sw+Vc5#LaH#fnLr^N2T z(b=Aega(ee7QjU=DxXe;(&ae4J(p}x=-hA!JVM(Fx{_WKiMDsmONOwSje@h-Ax0^V zw<38J5j*Z(MC>h)xy*iZvANv#06FQDp|5Y%C$4D3#*|8Oz9mTPP_va3g?>Vvdd0+w zAtHL19}*I>t2Nycw4QG^_A-i&D>zrvC58@1UPS8+m-6n##CgTq5!RyKWI>rEHJ6?e zp9G;h(YM!_mX^=aU#YTKeOuh3%8bgV1b)Cn(2jxke4ftlTP|>&m5KMQd)Xo3a9OHravtUqNopZK*yl6nvcMs1z8yKOp+rE^O&JENev)GMyyu7FGk+J-fGx# zM(^y?@9vK&pFc@%Gr zOC@UW-Uq?)UD-&vQS$Z*fRncu(QUbS&}tdNhLr(u*l1~MiC_q__tsnQ#kS3Kz983| zM@-bbp*vS~+^E60Q2sgr;ReaU$75+y9DG233uIM+{Snv`wa|i5UqsDme?-g-KSZ0z z^JRCn+#FK^+7cYGT+E$hXk$2!;sTT@Eo{?60USOg!If3%h-2)I(b)2e zGe0Erb4O?WDH!1?)L?*!#H%g%2?ahc?XXOTPgtHYZ{GIMaEuKgNqr@e!b91pr=8Cwk=gk-M;kaxl$nWeZ7P6;8^pe5*^T@fgV%wg3 zr{)r(in@tQTGPb-1x+QZUW5tE_r%a@4ln*n^Y+)}K7KTV7bA;yRrrqrR|SLy1)`AtE+Zee~tj>j>YW$F#XxEMw#2)7B_ z9TvGc{8UM*gyKc@X|Gz%*RLFpa7LiLb(Y>`BIPA}F544S;#}w-x(U#v7(-kxTFQ^- zeSS5wfd!ejH4;MaD} zyqw*h(n%fuAecaZ5(P0I_oc$@WX8HQ6b!pr_F^DVc7jb10kkFE2kdC^*HPYQle3xgHD$^z(Kxk>%^un4>nJJ zGLJ9gX{_Wuw;p29Mb0oG0#cUEC;7Elmu{WRmYl+a^L}+`rHRnBxGt8+C)Z}RDv#tm zFkX1DB%i%tE|Yz7jU$DO!tzCwcOv460ad6^Vb=nwRPW?rzX;0lCqf_XkLt04=7S+7 zP!3TnzSnX&9W?SN@Zyv@ls-uWexEML`uV-x_0C+~P&dDA_P66!rS+;j6oDCXF{ z*9|yCk^@Slo-GsTBBaertSn+?3ac&+hG-OpR#o}px8v@k_}$_63nZXWW(`*6hC)Q> z!E2NH_Xayhr!i7R3KmlrMRZ&=^akhkZaAlsER(Q#RSxlMD}HW*C9*BWE4RXA{``Ke ze!C7%Q`kIa|30&*D@hm1Mai{eB)&bzdxQvWVBc26FR-YhXvE=${P>zqoa9AL+88bP z<0L`MWthh|(mep`nLy@md@R09Ei&HM-bku77Ai@;;=Fl*%oBy}>=$3(p!Xyb6vT8n zf?RZynVAB29s#?Y45d%L6uxLUsgJ?lUCbuog2mWXuv;TV9#DuHSTLVHEmXV+ARvtADHp0yFg?Z)a;h083Sr9hWs>r zcD2C1N7y&aixtZ1N6oq7%PIDX`fc*aD@n8;4|a9<)*dU0n=W#ah+G+6KAUIep`LLX$Vkla}n>mnU~R*o4Z>= z0oS#Q>ZP(z-hqDq|%13ai%8&%a|%*@e7A`DhZz?B_>d#v?X!2 zW)&L>>X648klmtsq5SObK>$VlxFfn3?^=gkP%f}rQ}4OnMDPU9pJC4BaT};ri5Fn-f`L&ZK*kXy*vqOciayA(N2iEdx(q{Ep4LJn zdh@Qx9z7S~h&ZjnbGC#f4TazGdrRO0*g3jO&Qxzkgc6S?X9$Vnr6%SVpmEb)yz@;+ z1tn|)?A$}4$0Ombka=A98S6Kn8RA~zCs)*rlxdMdZWH6ykIvFzWoh2sVg+m-64INB zzwX>Z2CbpI{h|w8c{Yh+j%{k9B`M-~Hukz<+#`fXjU>zzjk%@!YK^-*-HS^%(+MKk zC?(-_PC*gk)LDaJ@2ZMe|Dgm{IxX6G#f~>uLsGC@X;I)y?wL948bntPi{5EtYGig9 z#jK|T1Y`w$B96DcicaCfj7#%jMJ;fdLX&eoq3yEn&x$KQ9t4Cjx#Ml*Dr(^;BMCk~ zrO+5LD4Pt7ly26Ld#4dh|Ak>wNJaFcE7uFB(v534uM}F7^pMF|@~=kNiA5dJxM}q_ zbG)CAaYLTUcgHSlxy~t(1cho;9XBu{1?zkd|k!^|j#tTA?ZJ|7D>lrQyb zY{p6zeB|OPc~wFTd7$e}@AKv8iGwssSNz>p((~1-mdv#y`ECMdD4ww0(sa{0+ZIdBJm;RW$$u6ORQv^+?#Ls z7Vn+UKuv@EIJ83zqU6jZ?++&rsvNJC@szw#xpM&9KG=|aP3h3cv@eDuR8fFl>*EJk z;-~AP1^SrUI7taIr8vEVM{WZliCDJXb&8cOa$=Lv+zz4S=j~ksMI@&6qpjWpH31{N zkY!6IRGIDSLd3{66hV1Tj#&znm3t&TEvs1!th4j1V(tmjy9>>`2XN#R$D<$KauMnD zwkq#RN+;IG*_<>7@DFf2zKLPJp6=fhnO~bi)O00A<93%(z`;tyqw?%-nyz+ z+4pNL824zM>vz)@7QEW=-cJ(i2urBk#h}k`N0&)e@BIK(aK>[F1lucH={v$u@` zNr)%b)rwJ(wS)VG)t70dC`w}_$D9VAP25zRm^hw15L+5aaJm^`CgZdi7`}bTJpbk5 zl%RKq6qA?l-b03o*3Dt_{-}8-(Qa~&JTHzqPA+99$GkSF-HlOuK(}6?n-~N~63dtB z-DMsBDuKT-6o`I2!^4A}TFB5zRvVJn&zzV$ zWh}TP(2bP_q94Caoe-8l?DgCNA-1ntP>m|$$zoqw}lMSfR=?GCa|FK5Op}Nx|VEC3TOWO67i|f*; z1?M}@dW3I>aX5H7%ur-TrFg3=ulx5-#_KP4qwWoLE`=nG^w9)_NwiVq-4jwUw^G_p zv}^UBW5)|6y$#;b*lG!Q!Y$lLBN!6p=U3u^4;n4s|AHyE6Z2cJGbR$0#LH?mI(3kS#xuI9X!8({1R2=W4zob zbc5DF1komsO!O2Q8g5~$GxGWHEscp9!>qFHIbRQEBos^N83Nh8T#dX=pRV#3gS=JZ zQ7Wdl{?_`P>+nyP-X62az6)X2pHO~6ULQwaqQfwzGtKiv1p{)f`lCj(d0)^4pn#<^ zWj!E_>&XI#9$!Dx6&GmM0x{2m2#uWFrj=e8X?>; z1)@|5sSQT=Oc)UcXT(6b6j$OZ?R*2}{lO9~SB<@k#xw1yqx_Me3eV{LxwD8f>gm_J z(!6u+qogY0J0X0EGUnV>mMmqf8^>4v1I06!{nbaQ8Mg{u=F%Ql8N|12QUwnlss+ZYgMg+0q{<^gw67xD(E3gseHv5{qVq?yyPbb~3d(n^s&u-D~k zy?954!cK2uy-i2PpON78Xyp?O$!csBPtpr#cvWM34aOk$K{v6I*2+Apclh$Jl2Qwr zpUogEo0kURKRZDj*j3c1awn)6kZjX{Njqs`lDRpj@XmyKlatnbX}&^-fZa2!cxd|pTt{5SUAP(~Z+JqL5x3%hvsJlG zi_-VhOTW<`VD<|$^66M@b1R}a3*&|U)~476Fn*HdW^HVl*nzFQCCxc|VhYJEl%mBrhZ2WeZ$k7^nAN0bBoP(07<9)VT z4~`z(rF7qmZ1Wu?${fL#z~El&bUr7za1%uk@v(m8Gyk>V!(>D=gF9T}9x^Cbc-g$$ z+DJ#wz-%lT7tkTfR%_=A$l%9y@)Fgt)u!}tPw=HaKZ{+@funh?_2hHL{=B~T@XXrC zv6s8Rf^Iz~(HBbC%M^*n%O`ZyOKDi}OcXe6sluTg`LstY?80+XqG}|p$Q+(ObBCNIeb;`XvF8Vrz^h zv0p}T?vjiFS+4|0+pGpi*aR0PWCZ#KMo;rUmig6zU~(u)If<}bi^_E z#0==e?-;fB?s=i<+k(O}D~p_LFKLXMtmKKxf^lNzG8@cyQv(M(YKWb7AU$Y`M2bGd zG29RN4m=6d!UDoHRha5cwwk>orM<7`28BLU(E7fT7`sD<0hYcYZaj1GqlGgoji)ND zo8TjUjz53|aL%%Dd9J(i&iFNs5iR?1Dls=PpwyG zq7X0fr99y-Fm7r4te}M@iSsQENFweRQLug2$Q_T=wyzrKaabp)$V#j3Ri0xk1xzIr z3|SZ*H8@a5C&V4ab*kLZGwSSo&D!MZl9r+_DWWkdWnT)0tndI;BJ_SUME*cYbhEgT zF1LB}isyUc zzsa4CvY6~^ZmKMqr$JjHVINvm0Rf0RKveEE>s!jV68(gYOD`xT`bn^EjB(18y?fGz0~2+70?FErN{V{>72$)-*2;@*`>N)$$ms}k@C4xq zRn_x)a#a6Pi3eA5yhrSt8pad`E2uvE6`F?9?SUWbCzjqx$342WahP*Q`P{V3=u;v4 zCIZ!zOQ9v%v(x8EMG?cKj}rRhPcvpNfixz|4ZN#(FdyJ=&{fs$#TGQ!U71TTrqB^- znV7J*!cgT<;4fYLe4rz4xttTY_3P5M5S3Ws^G@cW$0Y>L{fbH@<1_>x(0jL3Z?O z++RRRwQIL!`0#;9eJG{0{= zJGDEaj-mmw4s*s*uPnH1I!vB7ve#vHK8cOxOsr7WLyve}mCS3xf3%`hUF;tpe9sdz zEzlU9xeK=@|HA!=>dt$GoHu~S+ncv9LulTdzY=n9QT5{F5V|YM5VoZb(1q1}baoP1 z^d_Qp0nTDofNGu>#{k+O%Q-;+L3^Hz)$d&urdd;H!H$b$q$M`&TV>xVg zeF-*77-iWr*4V{enQgU-3Yzx2XB2YRYnU=AEUgt&7tq(`CB{7cVVCESBdzGFi{4a6 zi$#?^gMgsKa@QEIL~TnbLc^_KYLPNlq*^in35E(fv#gKF=_EZ(Gv(6Ig>SM$e1m^YqoIj=Z)W>|X zjET*Kna3r;H$GW=qar~bieDcmo-OlmsWfa>1TT5N$Rbg1!M|yxi>A(Fe9<8bkvj+M zvM_QxM5;d^jl5$l3O)^TI@OAg*aY%xje7FA^J4 z^Bf_qFF+7j&7#aHF(_g@!SL24kwHe|$nK`7e;GI@zN~1HV#Gm zC`ho8)>GBoKdQi+L+(mdFw2J{G@=b6Lr@GoeM){(2X=5{up)j~@%>mEj3fo;7 zigw$>E8PdS>o^3W21lk;!b!#hD+u#qpk9~OgRAA-p<<_l6RuH?TZAu~T)un&fTQL@ zRd7$vGQV`)oNW}kCEUWT{TeBX&_W%@ceY3=qr5u;G@iKjnSF(|5KR$--kOGh(t{#U za~@ijsNQ&My7slxuvQw|CCf|RZGo8-i_T*@M}461QG8p(D2I9KfZa`y+7l)89LiEe z8DUCDft-6)>`a6fA1UDHF9ASGj@)Vs0r`6p?Kj~6ItksFQW)+jcTLHNkGhleD`;r0 zgu=WRAbgEt%W^9}e(dX$-C>87opwGWlr)7$<6gvLxi8f8Flna`=O9R1x0;6eQFxhEP;<%X{&q)Fj|mSW>l4|Be+*koiF)RKSB<&!ZFY{EU2TU zT)cDqfbzUogfYxeg?to)LU=;Z_mo_R8H-8)cl;aCS3NeT(a|ah4iYY(aV)NyGsrqk zdZRB$!N8EJZI239R-!bo7Ou{S92{6Re1YN$G$Fq1i7IZm$#-THG-RU-()J5ci1!{W zF~^HWrdCTNL?tzl2As&4?W;~)3{ZX7Wxl94O@J^b<^v=(8JI!CN`+VbMj4ocyGG6~ zmvP$r;DzbfSfyyoSw*2ufylpKM{Y0Qtt`LtMZ^T;h9`+FKw)8B+Z3YxB?j-vE2x!-kju}!l^-%qGm?h7ci8uDS%W^kWcHBFfS2LxjNI2L8QAh23)mhoJQZ>@ z)I4%C@fHsy?)v_|ZfM4qc;H3qQ#O9MwDrw2sGA66p>GNTh5-k;npEz!7JYE?sorL% zX;<&RM_zv{yZyE-In;*19mSL9*ol*E zv4GQkJ&7+}YZAdHABxrvc*34-nI(XV=EWbn>I)U?9W=@|`tGUrgzncvo(xk57I{K7 zcRah1>rbueYtch1N3o&t9kp@3qK}nNqc=QU8->^v1NNIlS!7k%%Np2JxsTB0S(v`y z-GTs(6wf7}iA;&-Z()P~PcH`Ii9akEiod4<+c!*HNLK2bTH6`34i6S(&b@Ad*zN&_ zh{QRo*KneBa^6^d)kkDXLtApN#i`e}nq3zpV)1L94ptao2HOk%QNQ^aq-NkmOL6rmLi#Pjmy79J7U?^5ZzLQvV;Wz%@pkTd@X2sBh6u4A zV(dAA^DuyPHp>(%!KIB;sjwp?W7etlF&^{^fJ>* zoq(zrlNh4;aE0`ntZ4Z&v24qh!(RB&XJWZ#JykXt$4H=i4iXt;Z-}oj2t}|W5tFu5 znlJzOX4Y=m5$=W%AwmYQ&#=#f>un@uzQNZ!>Zmn++G8n75!-C3KQAOlX@O5F8?V7l zc$Dw>_w%vhnb)W54sJKCR1BDi3SXNXd}>kQj`gT+Q3fhhE`mzLhyfNV4%-esPVoON zsF1y_s7%l`z)B~YXsO-wEb-*_RqZtgepaGS*F7r=!qNpBTq*u81-A``E|Rh=W=)+) zSxIrY6GDUtF}4{1fFT7D0gmPo0bFyso2IvTgel}nT>7LahkO&;J_$Gn4MM{4mh$;!K8gjXSv>YT; zl&)zcGg%xr48{l%BE){c095Rmil_J4Bhd3{fvk{-SqRwx^07V+o$iLPn~KNuF`jf+ zmou3I@j}2{GW4O|LX1?1;j}-62oWMgh~a}4PCkey:value to the configuration. -func (c *Config) AddConfig(section string, option string, value string) bool { - if section == "" { - section = DEFAULT_SECTION - } - - if _, ok := c.data[section]; !ok { - c.data[section] = make(map[string]string) - } - - _, ok := c.data[section][option] - c.data[section][option] = value - - return !ok -} - -func (c *Config) parse(fname string) (err error) { - f, err := os.Open(fname) - if err != nil { - return err - } - defer f.Close() - - buf := bufio.NewReader(f) - return c.parseBuffer(buf) -} - -func (c *Config) parseBuffer(buf *bufio.Reader) error { - var section string - var lineNum int - var buffer bytes.Buffer - var canWrite bool - for { - if canWrite { - if err := c.write(section, lineNum, &buffer); err != nil { - return err - } else { - canWrite = false - } - } - lineNum++ - line, _, err := buf.ReadLine() - if err == io.EOF { - // force write when buffer is not flushed yet - if buffer.Len() > 0 { - if err = c.write(section, lineNum, &buffer); err != nil { - return err - } - } - break - } else if err != nil { - return err - } - - line = bytes.TrimSpace(line) - switch { - case bytes.Equal(line, []byte{}), bytes.HasPrefix(line, DEFAULT_COMMENT_SEM), - bytes.HasPrefix(line, DEFAULT_COMMENT): - canWrite = true - continue - case bytes.HasPrefix(line, []byte{'['}) && bytes.HasSuffix(line, []byte{']'}): - // force write when buffer is not flushed yet - if buffer.Len() > 0 { - if err := c.write(section, lineNum, &buffer); err != nil { - return err - } - canWrite = false - } - section = string(line[1 : len(line)-1]) - default: - var p []byte - if bytes.HasSuffix(line, DEFAULT_MULTI_LINE_SEPARATOR) { - p = bytes.TrimSpace(line[:len(line)-1]) - p = append(p, " "...) - } else { - p = line - canWrite = true - } - - end := len(p) - for i, value := range p { - if value == DEFAULT_COMMENT[0] || value == DEFAULT_COMMENT_SEM[0] { - end = i - break - } - } - if _, err := buffer.Write(p[:end]); err != nil { - return err - } - } - } - - return nil -} - -func (c *Config) write(section string, lineNum int, b *bytes.Buffer) error { - if b.Len() <= 0 { - return nil - } - - optionVal := bytes.SplitN(b.Bytes(), []byte{'='}, 2) - if len(optionVal) != 2 { - return fmt.Errorf("parse the content error : line %d , %s = ? ", lineNum, optionVal[0]) - } - option := bytes.TrimSpace(optionVal[0]) - value := bytes.TrimSpace(optionVal[1]) - c.AddConfig(section, string(option), string(value)) - - // flush buffer after adding - b.Reset() - - return nil -} - -// Bool lookups up the value using the provided key and converts the value to a bool. -func (c *Config) Bool(key string) (bool, error) { - return strconv.ParseBool(c.get(key)) -} - -// Int lookups up the value using the provided key and converts the value to a int. -func (c *Config) Int(key string) (int, error) { - return strconv.Atoi(c.get(key)) -} - -// Int64 lookups up the value using the provided key and converts the value to a int64. -func (c *Config) Int64(key string) (int64, error) { - return strconv.ParseInt(c.get(key), 10, 64) -} - -// Float64 lookups up the value using the provided key and converts the value to a float64. -func (c *Config) Float64(key string) (float64, error) { - return strconv.ParseFloat(c.get(key), 64) -} - -// String lookups up the value using the provided key and converts the value to a string. -func (c *Config) String(key string) string { - return c.get(key) -} - -// Strings lookups up the value using the provided key and converts the value to an array of string -// by splitting the string by comma. -func (c *Config) Strings(key string) []string { - v := c.get(key) - if v == "" { - return nil - } - return strings.Split(v, ",") -} - -// Set sets the value for the specific key in the Config. -func (c *Config) Set(key string, value string) error { - if len(key) == 0 { - return errors.New("key is empty") - } - - var ( - section string - option string - ) - - keys := strings.Split(strings.ToLower(key), "::") - if len(keys) >= 2 { - section = keys[0] - option = keys[1] - } else { - option = keys[0] - } - - c.AddConfig(section, option, value) - return nil -} - -// section.key or key. -func (c *Config) get(key string) string { - var ( - section string - option string - ) - - keys := strings.Split(strings.ToLower(key), "::") - if len(keys) >= 2 { - section = keys[0] - option = keys[1] - } else { - section = DEFAULT_SECTION - option = keys[0] - } - - if value, ok := c.data[section][option]; ok { - return value - } - - return "" -} diff --git a/vendor/github.com/casbin/casbin/v2/constant/constants.go b/vendor/github.com/casbin/casbin/v2/constant/constants.go deleted file mode 100644 index 4140ecf3..00000000 --- a/vendor/github.com/casbin/casbin/v2/constant/constants.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2022 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 constant - -const ( - ActionIndex = "act" - DomainIndex = "dom" - SubjectIndex = "sub" - ObjectIndex = "obj" - PriorityIndex = "priority" -) - -const ( - AllowOverrideEffect = "some(where (p_eft == allow))" - DenyOverrideEffect = "!some(where (p_eft == deny))" - AllowAndDenyEffect = "some(where (p_eft == allow)) && !some(where (p_eft == deny))" - PriorityEffect = "priority(p_eft) || deny" - SubjectPriorityEffect = "subjectPriority(p_eft) || deny" -) diff --git a/vendor/github.com/casbin/casbin/v2/effector/default_effector.go b/vendor/github.com/casbin/casbin/v2/effector/default_effector.go deleted file mode 100644 index feb083a6..00000000 --- a/vendor/github.com/casbin/casbin/v2/effector/default_effector.go +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright 2018 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 effector - -import ( - "errors" - - "github.com/casbin/casbin/v2/constant" -) - -// DefaultEffector is default effector for Casbin. -type DefaultEffector struct { -} - -// NewDefaultEffector is the constructor for DefaultEffector. -func NewDefaultEffector() *DefaultEffector { - e := DefaultEffector{} - return &e -} - -// MergeEffects merges all matching results collected by the enforcer into a single decision. -func (e *DefaultEffector) MergeEffects(expr string, effects []Effect, matches []float64, policyIndex int, policyLength int) (Effect, int, error) { - result := Indeterminate - explainIndex := -1 - - switch expr { - case constant.AllowOverrideEffect: - if matches[policyIndex] == 0 { - break - } - // only check the current policyIndex - if effects[policyIndex] == Allow { - result = Allow - explainIndex = policyIndex - break - } - case constant.DenyOverrideEffect: - // only check the current policyIndex - if matches[policyIndex] != 0 && effects[policyIndex] == Deny { - result = Deny - explainIndex = policyIndex - break - } - // if no deny rules are matched at last, then allow - if policyIndex == policyLength-1 { - result = Allow - } - case constant.AllowAndDenyEffect: - // short-circuit if matched deny rule - if matches[policyIndex] != 0 && effects[policyIndex] == Deny { - result = Deny - // set hit rule to the (first) matched deny rule - explainIndex = policyIndex - break - } - - // short-circuit some effects in the middle - if policyIndex < policyLength-1 { - // choose not to short-circuit - return result, explainIndex, nil - } - // merge all effects at last - for i, eft := range effects { - if matches[i] == 0 { - continue - } - - if eft == Allow { - result = Allow - // set hit rule to first matched allow rule - explainIndex = i - break - } - } - case constant.PriorityEffect, constant.SubjectPriorityEffect: - // reverse merge, short-circuit may be earlier - for i := len(effects) - 1; i >= 0; i-- { - if matches[i] == 0 { - continue - } - - if effects[i] != Indeterminate { - if effects[i] == Allow { - result = Allow - } else { - result = Deny - } - explainIndex = i - break - } - } - default: - return Deny, -1, errors.New("unsupported effect") - } - - return result, explainIndex, nil -} diff --git a/vendor/github.com/casbin/casbin/v2/effector/effector.go b/vendor/github.com/casbin/casbin/v2/effector/effector.go deleted file mode 100644 index 49b84c3e..00000000 --- a/vendor/github.com/casbin/casbin/v2/effector/effector.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2018 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 effector //nolint:cyclop // TODO - -// Effect is the result for a policy rule. -type Effect int - -// Values for policy effect. -const ( - Allow Effect = iota - Indeterminate - Deny -) - -// Effector is the interface for Casbin effectors. -type Effector interface { - // MergeEffects merges all matching results collected by the enforcer into a single decision. - MergeEffects(expr string, effects []Effect, matches []float64, policyIndex int, policyLength int) (Effect, int, error) -} diff --git a/vendor/github.com/casbin/casbin/v2/enforcer.go b/vendor/github.com/casbin/casbin/v2/enforcer.go deleted file mode 100644 index fd3f43a8..00000000 --- a/vendor/github.com/casbin/casbin/v2/enforcer.go +++ /dev/null @@ -1,1004 +0,0 @@ -// 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" - "runtime/debug" - "strings" - "sync" - - "github.com/casbin/casbin/v2/effector" - "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" - - "github.com/casbin/govaluate" -) - -// Enforcer is the main interface for authorization enforcement and policy management. -type Enforcer struct { - modelPath string - model model.Model - fm model.FunctionMap - eft effector.Effector - - adapter persist.Adapter - watcher persist.Watcher - dispatcher persist.Dispatcher - rmMap map[string]rbac.RoleManager - condRmMap map[string]rbac.ConditionalRoleManager - matcherMap sync.Map - - enabled bool - autoSave bool - autoBuildRoleLinks bool - autoNotifyWatcher bool - autoNotifyDispatcher bool - acceptJsonRequest bool - - logger log.Logger -} - -// EnforceContext is used as the first element of the parameter "rvals" in method "enforce". -type EnforceContext struct { - RType string - PType string - EType string - MType string -} - -func (e EnforceContext) GetCacheKey() string { - return "EnforceContext{" + e.RType + "-" + e.PType + "-" + e.EType + "-" + e.MType + "}" -} - -// 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++ - } - } - - switch paramLen - parsedParamLen { - case 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 - } - } - } - case 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 - } - } - case 0: - return e, nil - default: - 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 - } - - 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) - for k := range e.rmMap { - e.rmMap[k].SetLogger(e.logger) - } - for k := range e.condRmMap { - e.condRmMap[k].SetLogger(e.logger) - } -} - -func (e *Enforcer) initialize() { - e.rmMap = map[string]rbac.RoleManager{} - e.condRmMap = map[string]rbac.ConditionalRoleManager{} - e.eft = effector.NewDefaultEffector() - e.watcher = nil - e.matcherMap = sync.Map{} - - e.enabled = true - e.autoSave = true - e.autoBuildRoleLinks = true - e.autoNotifyWatcher = true - e.autoNotifyDispatcher = true - e.initRmMap() -} - -// 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 - if _, ok := e.watcher.(persist.WatcherEx); ok { - // The callback of WatcherEx has no generic implementation. - return nil - } else { - // In case the Watcher wants to use a customized callback function, call `SetUpdateCallback` after `SetWatcher`. - return watcher.SetUpdateCallback(func(string) { _ = e.LoadPolicy() }) - } -} - -// GetRoleManager gets the current role manager. -func (e *Enforcer) GetRoleManager() rbac.RoleManager { - if e.rmMap != nil && e.rmMap["g"] != nil { - return e.rmMap["g"] - } else { - return nil - } -} - -// GetNamedRoleManager gets the role manager for the named policy. -func (e *Enforcer) GetNamedRoleManager(ptype string) rbac.RoleManager { - if e.rmMap != nil && e.rmMap[ptype] != nil { - return e.rmMap[ptype] - } else { - return nil - } -} - -// SetRoleManager sets the current role manager. -func (e *Enforcer) SetRoleManager(rm rbac.RoleManager) { - e.invalidateMatcherMap() - e.rmMap["g"] = rm -} - -// SetNamedRoleManager sets the role manager for the named policy. -func (e *Enforcer) SetNamedRoleManager(ptype string, rm rbac.RoleManager) { - e.invalidateMatcherMap() - e.rmMap[ptype] = rm -} - -// SetEffector sets the current effector. -func (e *Enforcer) SetEffector(eft effector.Effector) { - e.eft = eft -} - -// ClearPolicy clears all policy. -func (e *Enforcer) ClearPolicy() { - e.invalidateMatcherMap() - - if e.dispatcher != nil && e.autoNotifyDispatcher { - _ = e.dispatcher.ClearPolicy() - return - } - e.model.ClearPolicy() -} - -// LoadPolicy reloads the policy from file/database. -func (e *Enforcer) LoadPolicy() error { - newModel, err := e.loadPolicyFromAdapter(e.model) - if err != nil { - return err - } - err = e.applyModifiedModel(newModel) - if err != nil { - return err - } - return nil -} - -func (e *Enforcer) loadPolicyFromAdapter(baseModel model.Model) (model.Model, error) { - newModel := baseModel.Copy() - newModel.ClearPolicy() - - if err := e.adapter.LoadPolicy(newModel); err != nil && err.Error() != "invalid file path, file path cannot be empty" { - return nil, err - } - - if err := newModel.SortPoliciesBySubjectHierarchy(); err != nil { - return nil, err - } - - if err := newModel.SortPoliciesByPriority(); err != nil { - return nil, err - } - - return newModel, nil -} - -func (e *Enforcer) applyModifiedModel(newModel model.Model) error { - var err error - needToRebuild := false - defer func() { - if err != nil { - if e.autoBuildRoleLinks && needToRebuild { - _ = e.BuildRoleLinks() - } - } - }() - - if e.autoBuildRoleLinks { - needToRebuild = true - - if err := e.rebuildRoleLinks(newModel); err != nil { - return err - } - - if err := e.rebuildConditionalRoleLinks(newModel); err != nil { - return err - } - } - - e.model = newModel - e.invalidateMatcherMap() - return nil -} - -func (e *Enforcer) rebuildRoleLinks(newModel model.Model) error { - if len(e.rmMap) != 0 { - for _, rm := range e.rmMap { - err := rm.Clear() - if err != nil { - return err - } - } - - err := newModel.BuildRoleLinks(e.rmMap) - if err != nil { - return err - } - } - - return nil -} - -func (e *Enforcer) rebuildConditionalRoleLinks(newModel model.Model) error { - if len(e.condRmMap) != 0 { - for _, crm := range e.condRmMap { - err := crm.Clear() - if err != nil { - return err - } - } - - err := newModel.BuildConditionalRoleLinks(e.condRmMap) - if err != nil { - return err - } - } - return nil -} - -func (e *Enforcer) loadFilteredPolicy(filter interface{}) error { - e.invalidateMatcherMap() - - 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 - } - - if err := e.model.SortPoliciesBySubjectHierarchy(); err != nil { - return err - } - - if err := e.model.SortPoliciesByPriority(); err != nil { - return err - } - - e.initRmMap() - 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 -} - -func (e *Enforcer) initRmMap() { - for ptype, assertion := range e.model["g"] { - if rm, ok := e.rmMap[ptype]; ok { - _ = rm.Clear() - continue - } - if len(assertion.Tokens) <= 2 && len(assertion.ParamsTokens) == 0 { - assertion.RM = defaultrolemanager.NewRoleManagerImpl(10) - e.rmMap[ptype] = assertion.RM - } - if len(assertion.Tokens) <= 2 && len(assertion.ParamsTokens) != 0 { - assertion.CondRM = defaultrolemanager.NewConditionalRoleManager(10) - e.condRmMap[ptype] = assertion.CondRM - } - if len(assertion.Tokens) > 2 { - if len(assertion.ParamsTokens) == 0 { - assertion.RM = defaultrolemanager.NewRoleManager(10) - e.rmMap[ptype] = assertion.RM - } else { - assertion.CondRM = defaultrolemanager.NewConditionalDomainManager(10) - e.condRmMap[ptype] = assertion.CondRM - } - matchFun := "keyMatch(r_dom, p_dom)" - if strings.Contains(e.model["m"]["m"].Value, matchFun) { - e.AddNamedDomainMatchingFunc(ptype, "g", util.KeyMatch) - } - } - } -} - -// 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 -} - -// EnableAutoNotifyDispatcher controls whether to save a policy rule automatically notify the Dispatcher when it is added or removed. -func (e *Enforcer) EnableAutoNotifyDispatcher(enable bool) { - e.autoNotifyDispatcher = 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 -} - -// EnableAcceptJsonRequest controls whether to accept json as a request parameter. -func (e *Enforcer) EnableAcceptJsonRequest(acceptJsonRequest bool) { - e.acceptJsonRequest = acceptJsonRequest -} - -// BuildRoleLinks manually rebuild the role inheritance relations. -func (e *Enforcer) BuildRoleLinks() error { - if e.rmMap == nil { - return errors.New("rmMap is nil") - } - for _, rm := range e.rmMap { - err := rm.Clear() - if err != nil { - return err - } - } - - return e.model.BuildRoleLinks(e.rmMap) -} - -// BuildIncrementalRoleLinks provides incremental build the role inheritance relations. -func (e *Enforcer) BuildIncrementalRoleLinks(op model.PolicyOp, ptype string, rules [][]string) error { - e.invalidateMatcherMap() - return e.model.BuildIncrementalRoleLinks(e.rmMap, op, "g", ptype, rules) -} - -// BuildIncrementalConditionalRoleLinks provides incremental build the role inheritance relations with conditions. -func (e *Enforcer) BuildIncrementalConditionalRoleLinks(op model.PolicyOp, ptype string, rules [][]string) error { - e.invalidateMatcherMap() - return e.model.BuildIncrementalConditionalRoleLinks(e.condRmMap, op, "g", ptype, rules) -} - -// NewEnforceContext Create a default structure based on the suffix. -func NewEnforceContext(suffix string) EnforceContext { - return EnforceContext{ - RType: "r" + suffix, - PType: "p" + suffix, - EType: "e" + suffix, - MType: "m" + suffix, - } -} - -func (e *Enforcer) invalidateMatcherMap() { - e.matcherMap = sync.Map{} -} - -// 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) { //nolint:funlen,cyclop,gocyclo // TODO: reduce function complexity - defer func() { - if r := recover(); r != nil { - err = fmt.Errorf("panic: %v\n%s", r, debug.Stack()) - } - }() - - if !e.enabled { - return true, nil - } - - functions := e.fm.GetFunctions() - if _, ok := e.model["g"]; ok { - for key, ast := range e.model["g"] { - // g must be a normal role definition (ast.RM != nil) - // or a conditional role definition (ast.CondRM != nil) - // ast.RM and ast.CondRM shouldn't be nil at the same time - if ast.RM != nil { - functions[key] = util.GenerateGFunction(ast.RM) - } - if ast.CondRM != nil { - functions[key] = util.GenerateConditionalGFunction(ast.CondRM) - } - } - } - - var ( - rType = "r" - pType = "p" - eType = "e" - mType = "m" - ) - if len(rvals) != 0 { - switch rvals[0].(type) { - case EnforceContext: - enforceContext := rvals[0].(EnforceContext) - rType = enforceContext.RType - pType = enforceContext.PType - eType = enforceContext.EType - mType = enforceContext.MType - rvals = rvals[1:] - default: - break - } - } - - var expString string - if matcher == "" { - expString = e.model["m"][mType].Value - } else { - expString = util.RemoveComments(util.EscapeAssertion(matcher)) - } - - rTokens := make(map[string]int, len(e.model["r"][rType].Tokens)) - for i, token := range e.model["r"][rType].Tokens { - rTokens[token] = i - } - pTokens := make(map[string]int, len(e.model["p"][pType].Tokens)) - for i, token := range e.model["p"][pType].Tokens { - pTokens[token] = i - } - - if e.acceptJsonRequest { - // try to parse all request values from json to map[string]interface{} - // skip if there is an error - for i, rval := range rvals { - switch rval := rval.(type) { - case string: - var mapValue map[string]interface{} - mapValue, err = util.JsonToMap(rval) - if err == nil { - rvals[i] = mapValue - } - } - } - } - - parameters := enforceParameters{ - rTokens: rTokens, - rVals: rvals, - - pTokens: pTokens, - } - - hasEval := util.HasEval(expString) - if hasEval { - functions["eval"] = generateEvalFunction(functions, ¶meters) - } - var expression *govaluate.EvaluableExpression - expression, err = e.getAndStoreMatcherExpression(hasEval, expString, functions) - if err != nil { - return false, err - } - - if len(e.model["r"][rType].Tokens) != len(rvals) { - return false, fmt.Errorf( - "invalid request size: expected %d, got %d, rvals: %v", - len(e.model["r"][rType].Tokens), - len(rvals), - rvals) - } - - var policyEffects []effector.Effect - var matcherResults []float64 - - var effect effector.Effect - var explainIndex int - - if policyLen := len(e.model["p"][pType].Policy); policyLen != 0 && strings.Contains(expString, pType+"_") { //nolint:nestif // TODO: reduce function complexity - policyEffects = make([]effector.Effect, policyLen) - matcherResults = make([]float64, policyLen) - - for policyIndex, pvals := range e.model["p"][pType].Policy { - // log.LogPrint("Policy Rule: ", pvals) - if len(e.model["p"][pType].Tokens) != len(pvals) { - return false, fmt.Errorf( - "invalid policy size: expected %d, got %d, pvals: %v", - len(e.model["p"][pType].Tokens), - len(pvals), - pvals) - } - - parameters.pVals = pvals - - result, err := expression.Eval(parameters) - // log.LogPrint("Result: ", result) - - if err != nil { - return false, err - } - - // set to no-match at first - matcherResults[policyIndex] = 0 - switch result := result.(type) { - case bool: - if result { - matcherResults[policyIndex] = 1 - } - case float64: - if result != 0 { - matcherResults[policyIndex] = 1 - } - default: - return false, errors.New("matcher result should be bool, int or float") - } - - if j, ok := parameters.pTokens[pType+"_eft"]; ok { - eft := parameters.pVals[j] - if eft == "allow" { - policyEffects[policyIndex] = effector.Allow - } else if eft == "deny" { - policyEffects[policyIndex] = effector.Deny - } else { - policyEffects[policyIndex] = effector.Indeterminate - } - } else { - policyEffects[policyIndex] = effector.Allow - } - - // if e.model["e"]["e"].Value == "priority(p_eft) || deny" { - // break - // } - - effect, explainIndex, err = e.eft.MergeEffects(e.model["e"][eType].Value, policyEffects, matcherResults, policyIndex, policyLen) - if err != nil { - return false, err - } - if effect != effector.Indeterminate { - break - } - } - } else { - if hasEval && len(e.model["p"][pType].Policy) == 0 { - return false, errors.New("please make sure rule exists in policy when using eval() in matcher") - } - - policyEffects = make([]effector.Effect, 1) - matcherResults = make([]float64, 1) - matcherResults[0] = 1 - - parameters.pVals = make([]string, len(parameters.pTokens)) - - result, err := expression.Eval(parameters) - - if err != nil { - return false, err - } - - if result.(bool) { - policyEffects[0] = effector.Allow - } else { - policyEffects[0] = effector.Indeterminate - } - - effect, explainIndex, err = e.eft.MergeEffects(e.model["e"][eType].Value, policyEffects, matcherResults, 0, 1) - if err != nil { - return false, err - } - } - - var logExplains [][]string - - if explains != nil { - if len(*explains) > 0 { - logExplains = append(logExplains, *explains) - } - - if explainIndex != -1 && len(e.model["p"][pType].Policy) > explainIndex { - *explains = e.model["p"][pType].Policy[explainIndex] - logExplains = append(logExplains, *explains) - } - } - - // effect -> result - result := false - if effect == effector.Allow { - result = true - } - e.logger.LogEnforce(expString, rvals, result, logExplains) - - return result, nil -} - -func (e *Enforcer) getAndStoreMatcherExpression(hasEval bool, expString string, functions map[string]govaluate.ExpressionFunction) (*govaluate.EvaluableExpression, error) { - var expression *govaluate.EvaluableExpression - var err error - var cachedExpression, isPresent = e.matcherMap.Load(expString) - - if !hasEval && isPresent { - expression = cachedExpression.(*govaluate.EvaluableExpression) - } else { - expression, err = govaluate.NewEvaluableExpressionWithFunctions(expString, functions) - if err != nil { - return nil, err - } - e.matcherMap.Store(expString, expression) - } - return expression, 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 -} - -// BatchEnforce enforce in batches. -func (e *Enforcer) BatchEnforce(requests [][]interface{}) ([]bool, error) { - var results []bool - for _, request := range requests { - result, err := e.enforce("", nil, request...) - if err != nil { - return results, err - } - results = append(results, result) - } - return results, nil -} - -// BatchEnforceWithMatcher enforce with matcher in batches. -func (e *Enforcer) BatchEnforceWithMatcher(matcher string, requests [][]interface{}) ([]bool, error) { - var results []bool - for _, request := range requests { - result, err := e.enforce(matcher, nil, request...) - if err != nil { - return results, err - } - results = append(results, result) - } - return results, nil -} - -// AddNamedMatchingFunc add MatchingFunc by ptype RoleManager. -func (e *Enforcer) AddNamedMatchingFunc(ptype, name string, fn rbac.MatchingFunc) bool { - if rm, ok := e.rmMap[ptype]; ok { - rm.AddMatchingFunc(name, fn) - return true - } - return false -} - -// AddNamedDomainMatchingFunc add MatchingFunc by ptype to RoleManager. -func (e *Enforcer) AddNamedDomainMatchingFunc(ptype, name string, fn rbac.MatchingFunc) bool { - if rm, ok := e.rmMap[ptype]; ok { - rm.AddDomainMatchingFunc(name, fn) - return true - } - return false -} - -// AddNamedLinkConditionFunc Add condition function fn for Link userName->roleName, -// when fn returns true, Link is valid, otherwise invalid. -func (e *Enforcer) AddNamedLinkConditionFunc(ptype, user, role string, fn rbac.LinkConditionFunc) bool { - if rm, ok := e.condRmMap[ptype]; ok { - rm.AddLinkConditionFunc(user, role, fn) - return true - } - return false -} - -// AddNamedDomainLinkConditionFunc Add condition function fn for Link userName-> {roleName, domain}, -// when fn returns true, Link is valid, otherwise invalid. -func (e *Enforcer) AddNamedDomainLinkConditionFunc(ptype, user, role string, domain string, fn rbac.LinkConditionFunc) bool { - if rm, ok := e.condRmMap[ptype]; ok { - rm.AddDomainLinkConditionFunc(user, role, domain, fn) - return true - } - return false -} - -// SetNamedLinkConditionFuncParams Sets the parameters of the condition function fn for Link userName->roleName. -func (e *Enforcer) SetNamedLinkConditionFuncParams(ptype, user, role string, params ...string) bool { - if rm, ok := e.condRmMap[ptype]; ok { - rm.SetLinkConditionFuncParams(user, role, params...) - return true - } - return false -} - -// SetNamedDomainLinkConditionFuncParams Sets the parameters of the condition function fn -// for Link userName->{roleName, domain}. -func (e *Enforcer) SetNamedDomainLinkConditionFuncParams(ptype, user, role, domain string, params ...string) bool { - if rm, ok := e.condRmMap[ptype]; ok { - rm.SetDomainLinkConditionFuncParams(user, role, domain, params...) - return true - } - return false -} - -// 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.") - } -} - -func generateEvalFunction(functions map[string]govaluate.ExpressionFunction, parameters *enforceParameters) govaluate.ExpressionFunction { - return func(args ...interface{}) (interface{}, error) { - if len(args) != 1 { - return nil, fmt.Errorf("function eval(subrule string) expected %d arguments, but got %d", 1, len(args)) - } - - expression, ok := args[0].(string) - if !ok { - return nil, errors.New("argument of eval(subrule string) must be a string") - } - expression = util.EscapeAssertion(expression) - expr, err := govaluate.NewEvaluableExpressionWithFunctions(expression, functions) - if err != nil { - return nil, fmt.Errorf("error while parsing eval parameter: %s, %s", expression, err.Error()) - } - return expr.Eval(parameters) - } -} diff --git a/vendor/github.com/casbin/casbin/v2/enforcer_cached.go b/vendor/github.com/casbin/casbin/v2/enforcer_cached.go deleted file mode 100644 index b89bad78..00000000 --- a/vendor/github.com/casbin/casbin/v2/enforcer_cached.go +++ /dev/null @@ -1,185 +0,0 @@ -// Copyright 2018 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 ( - "strings" - "sync" - "sync/atomic" - "time" - - "github.com/casbin/casbin/v2/persist/cache" -) - -// CachedEnforcer wraps Enforcer and provides decision cache. -type CachedEnforcer struct { - *Enforcer - expireTime time.Duration - cache cache.Cache - enableCache int32 - locker *sync.RWMutex -} - -type CacheableParam interface { - GetCacheKey() string -} - -// NewCachedEnforcer creates a cached enforcer via file or DB. -func NewCachedEnforcer(params ...interface{}) (*CachedEnforcer, error) { - e := &CachedEnforcer{} - var err error - e.Enforcer, err = NewEnforcer(params...) - if err != nil { - return nil, err - } - - e.enableCache = 1 - e.cache, _ = cache.NewDefaultCache() - e.locker = new(sync.RWMutex) - return e, nil -} - -// EnableCache determines whether to enable cache on Enforce(). When enableCache is enabled, cached result (true | false) will be returned for previous decisions. -func (e *CachedEnforcer) EnableCache(enableCache bool) { - var enabled int32 - if enableCache { - enabled = 1 - } - atomic.StoreInt32(&e.enableCache, enabled) -} - -// Enforce decides whether a "subject" can access a "object" with the operation "action", input parameters are usually: (sub, obj, act). -// if rvals is not string , ignore the cache. -func (e *CachedEnforcer) Enforce(rvals ...interface{}) (bool, error) { - if atomic.LoadInt32(&e.enableCache) == 0 { - return e.Enforcer.Enforce(rvals...) - } - - key, ok := e.getKey(rvals...) - if !ok { - return e.Enforcer.Enforce(rvals...) - } - - if res, err := e.getCachedResult(key); err == nil { - return res, nil - } else if err != cache.ErrNoSuchKey { - return res, err - } - - res, err := e.Enforcer.Enforce(rvals...) - if err != nil { - return false, err - } - - err = e.setCachedResult(key, res, e.expireTime) - return res, err -} - -func (e *CachedEnforcer) LoadPolicy() error { - if atomic.LoadInt32(&e.enableCache) != 0 { - if err := e.cache.Clear(); err != nil { - return err - } - } - return e.Enforcer.LoadPolicy() -} - -func (e *CachedEnforcer) RemovePolicy(params ...interface{}) (bool, error) { - if atomic.LoadInt32(&e.enableCache) != 0 { - key, ok := e.getKey(params...) - if ok { - if err := e.cache.Delete(key); err != nil && err != cache.ErrNoSuchKey { - return false, err - } - } - } - return e.Enforcer.RemovePolicy(params...) -} - -func (e *CachedEnforcer) RemovePolicies(rules [][]string) (bool, error) { - if len(rules) != 0 { - if atomic.LoadInt32(&e.enableCache) != 0 { - irule := make([]interface{}, len(rules[0])) - for _, rule := range rules { - for i, param := range rule { - irule[i] = param - } - key, _ := e.getKey(irule...) - if err := e.cache.Delete(key); err != nil && err != cache.ErrNoSuchKey { - return false, err - } - } - } - } - return e.Enforcer.RemovePolicies(rules) -} - -func (e *CachedEnforcer) getCachedResult(key string) (res bool, err error) { - e.locker.Lock() - defer e.locker.Unlock() - return e.cache.Get(key) -} - -func (e *CachedEnforcer) SetExpireTime(expireTime time.Duration) { - e.expireTime = expireTime -} - -func (e *CachedEnforcer) SetCache(c cache.Cache) { - e.cache = c -} - -func (e *CachedEnforcer) setCachedResult(key string, res bool, extra ...interface{}) error { - e.locker.Lock() - defer e.locker.Unlock() - return e.cache.Set(key, res, extra...) -} - -func (e *CachedEnforcer) getKey(params ...interface{}) (string, bool) { - return GetCacheKey(params...) -} - -// InvalidateCache deletes all the existing cached decisions. -func (e *CachedEnforcer) InvalidateCache() error { - e.locker.Lock() - defer e.locker.Unlock() - return e.cache.Clear() -} - -func GetCacheKey(params ...interface{}) (string, bool) { - key := strings.Builder{} - for _, param := range params { - switch typedParam := param.(type) { - case string: - key.WriteString(typedParam) - case CacheableParam: - key.WriteString(typedParam.GetCacheKey()) - default: - return "", false - } - key.WriteString("$$") - } - return key.String(), true -} - -// ClearPolicy clears all policy. -func (e *CachedEnforcer) ClearPolicy() { - if atomic.LoadInt32(&e.enableCache) != 0 { - if err := e.cache.Clear(); err != nil { - e.logger.LogError(err, "clear cache failed") - return - } - } - e.Enforcer.ClearPolicy() -} diff --git a/vendor/github.com/casbin/casbin/v2/enforcer_cached_synced.go b/vendor/github.com/casbin/casbin/v2/enforcer_cached_synced.go deleted file mode 100644 index 0032460f..00000000 --- a/vendor/github.com/casbin/casbin/v2/enforcer_cached_synced.go +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright 2018 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 ( - "sync" - "sync/atomic" - "time" - - "github.com/casbin/casbin/v2/persist/cache" -) - -// SyncedCachedEnforcer wraps Enforcer and provides decision sync cache. -type SyncedCachedEnforcer struct { - *SyncedEnforcer - expireTime time.Duration - cache cache.Cache - enableCache int32 - locker *sync.RWMutex -} - -// NewSyncedCachedEnforcer creates a sync cached enforcer via file or DB. -func NewSyncedCachedEnforcer(params ...interface{}) (*SyncedCachedEnforcer, error) { - e := &SyncedCachedEnforcer{} - var err error - e.SyncedEnforcer, err = NewSyncedEnforcer(params...) - if err != nil { - return nil, err - } - - e.enableCache = 1 - e.cache, _ = cache.NewSyncCache() - e.locker = new(sync.RWMutex) - return e, nil -} - -// EnableCache determines whether to enable cache on Enforce(). When enableCache is enabled, cached result (true | false) will be returned for previous decisions. -func (e *SyncedCachedEnforcer) EnableCache(enableCache bool) { - var enabled int32 - if enableCache { - enabled = 1 - } - atomic.StoreInt32(&e.enableCache, enabled) -} - -// Enforce decides whether a "subject" can access a "object" with the operation "action", input parameters are usually: (sub, obj, act). -// if rvals is not string , ignore the cache. -func (e *SyncedCachedEnforcer) Enforce(rvals ...interface{}) (bool, error) { - if atomic.LoadInt32(&e.enableCache) == 0 { - return e.SyncedEnforcer.Enforce(rvals...) - } - - key, ok := e.getKey(rvals...) - if !ok { - return e.SyncedEnforcer.Enforce(rvals...) - } - - if res, err := e.getCachedResult(key); err == nil { - return res, nil - } else if err != cache.ErrNoSuchKey { - return res, err - } - - res, err := e.SyncedEnforcer.Enforce(rvals...) - if err != nil { - return false, err - } - - err = e.setCachedResult(key, res, e.expireTime) - return res, err -} - -func (e *SyncedCachedEnforcer) LoadPolicy() error { - if atomic.LoadInt32(&e.enableCache) != 0 { - if err := e.cache.Clear(); err != nil { - return err - } - } - return e.SyncedEnforcer.LoadPolicy() -} - -func (e *SyncedCachedEnforcer) AddPolicy(params ...interface{}) (bool, error) { - if ok, err := e.checkOneAndRemoveCache(params...); !ok { - return ok, err - } - return e.SyncedEnforcer.AddPolicy(params...) -} - -func (e *SyncedCachedEnforcer) AddPolicies(rules [][]string) (bool, error) { - if ok, err := e.checkManyAndRemoveCache(rules); !ok { - return ok, err - } - return e.SyncedEnforcer.AddPolicies(rules) -} - -func (e *SyncedCachedEnforcer) RemovePolicy(params ...interface{}) (bool, error) { - if ok, err := e.checkOneAndRemoveCache(params...); !ok { - return ok, err - } - return e.SyncedEnforcer.RemovePolicy(params...) -} - -func (e *SyncedCachedEnforcer) RemovePolicies(rules [][]string) (bool, error) { - if ok, err := e.checkManyAndRemoveCache(rules); !ok { - return ok, err - } - return e.SyncedEnforcer.RemovePolicies(rules) -} - -func (e *SyncedCachedEnforcer) getCachedResult(key string) (res bool, err error) { - return e.cache.Get(key) -} - -func (e *SyncedCachedEnforcer) SetExpireTime(expireTime time.Duration) { - e.locker.Lock() - defer e.locker.Unlock() - e.expireTime = expireTime -} - -// SetCache need to be sync cache. -func (e *SyncedCachedEnforcer) SetCache(c cache.Cache) { - e.locker.Lock() - defer e.locker.Unlock() - e.cache = c -} - -func (e *SyncedCachedEnforcer) setCachedResult(key string, res bool, extra ...interface{}) error { - return e.cache.Set(key, res, extra...) -} - -func (e *SyncedCachedEnforcer) getKey(params ...interface{}) (string, bool) { - return GetCacheKey(params...) -} - -// InvalidateCache deletes all the existing cached decisions. -func (e *SyncedCachedEnforcer) InvalidateCache() error { - return e.cache.Clear() -} - -func (e *SyncedCachedEnforcer) checkOneAndRemoveCache(params ...interface{}) (bool, error) { - if atomic.LoadInt32(&e.enableCache) != 0 { - key, ok := e.getKey(params...) - if ok { - if err := e.cache.Delete(key); err != nil && err != cache.ErrNoSuchKey { - return false, err - } - } - } - return true, nil -} - -func (e *SyncedCachedEnforcer) checkManyAndRemoveCache(rules [][]string) (bool, error) { - if len(rules) != 0 { - if atomic.LoadInt32(&e.enableCache) != 0 { - irule := make([]interface{}, len(rules[0])) - for _, rule := range rules { - for i, param := range rule { - irule[i] = param - } - key, _ := e.getKey(irule...) - if err := e.cache.Delete(key); err != nil && err != cache.ErrNoSuchKey { - return false, err - } - } - } - } - return true, nil -} diff --git a/vendor/github.com/casbin/casbin/v2/enforcer_distributed.go b/vendor/github.com/casbin/casbin/v2/enforcer_distributed.go deleted file mode 100644 index 09f66723..00000000 --- a/vendor/github.com/casbin/casbin/v2/enforcer_distributed.go +++ /dev/null @@ -1,239 +0,0 @@ -package casbin - -import ( - "github.com/casbin/casbin/v2/model" - "github.com/casbin/casbin/v2/persist" -) - -// DistributedEnforcer wraps SyncedEnforcer for dispatcher. -type DistributedEnforcer struct { - *SyncedEnforcer -} - -func NewDistributedEnforcer(params ...interface{}) (*DistributedEnforcer, error) { - e := &DistributedEnforcer{} - var err error - e.SyncedEnforcer, err = NewSyncedEnforcer(params...) - if err != nil { - return nil, err - } - - return e, nil -} - -// SetDispatcher sets the current dispatcher. -func (d *DistributedEnforcer) SetDispatcher(dispatcher persist.Dispatcher) { - d.dispatcher = dispatcher -} - -// AddPoliciesSelf provides a method for dispatcher to add authorization rules to the current policy. -// The function returns the rules affected and error. -func (d *DistributedEnforcer) AddPoliciesSelf(shouldPersist func() bool, sec string, ptype string, rules [][]string) (affected [][]string, err error) { - d.m.Lock() - defer d.m.Unlock() - if shouldPersist != nil && shouldPersist() { - var noExistsPolicy [][]string - for _, rule := range rules { - var hasPolicy bool - hasPolicy, err = d.model.HasPolicy(sec, ptype, rule) - if err != nil { - return nil, err - } - if !hasPolicy { - noExistsPolicy = append(noExistsPolicy, rule) - } - } - - if err = d.adapter.(persist.BatchAdapter).AddPolicies(sec, ptype, noExistsPolicy); err != nil && err.Error() != notImplemented { - return nil, err - } - } - - affected, err = d.model.AddPoliciesWithAffected(sec, ptype, rules) - if err != nil { - return affected, err - } - - if sec == "g" { - err := d.BuildIncrementalRoleLinks(model.PolicyAdd, ptype, affected) - if err != nil { - return affected, err - } - } - - return affected, nil -} - -// RemovePoliciesSelf provides a method for dispatcher to remove a set of rules from current policy. -// The function returns the rules affected and error. -func (d *DistributedEnforcer) RemovePoliciesSelf(shouldPersist func() bool, sec string, ptype string, rules [][]string) (affected [][]string, err error) { - d.m.Lock() - defer d.m.Unlock() - if shouldPersist != nil && shouldPersist() { - if err = d.adapter.(persist.BatchAdapter).RemovePolicies(sec, ptype, rules); err != nil { - if err.Error() != notImplemented { - return nil, err - } - } - } - - affected, err = d.model.RemovePoliciesWithAffected(sec, ptype, rules) - if err != nil { - return affected, err - } - - if sec == "g" { - err = d.BuildIncrementalRoleLinks(model.PolicyRemove, ptype, affected) - if err != nil { - return affected, err - } - } - - return affected, err -} - -// RemoveFilteredPolicySelf provides a method for dispatcher to remove an authorization rule from the current policy, field filters can be specified. -// The function returns the rules affected and error. -func (d *DistributedEnforcer) RemoveFilteredPolicySelf(shouldPersist func() bool, sec string, ptype string, fieldIndex int, fieldValues ...string) (affected [][]string, err error) { - d.m.Lock() - defer d.m.Unlock() - if shouldPersist != nil && shouldPersist() { - if err = d.adapter.RemoveFilteredPolicy(sec, ptype, fieldIndex, fieldValues...); err != nil { - if err.Error() != notImplemented { - return nil, err - } - } - } - - _, affected, err = d.model.RemoveFilteredPolicy(sec, ptype, fieldIndex, fieldValues...) - if err != nil { - return affected, err - } - - if sec == "g" { - err := d.BuildIncrementalRoleLinks(model.PolicyRemove, ptype, affected) - if err != nil { - return affected, err - } - } - - return affected, nil -} - -// ClearPolicySelf provides a method for dispatcher to clear all rules from the current policy. -func (d *DistributedEnforcer) ClearPolicySelf(shouldPersist func() bool) error { - d.m.Lock() - defer d.m.Unlock() - if shouldPersist != nil && shouldPersist() { - err := d.adapter.SavePolicy(nil) - if err != nil { - return err - } - } - - d.model.ClearPolicy() - - return nil -} - -// UpdatePolicySelf provides a method for dispatcher to update an authorization rule from the current policy. -func (d *DistributedEnforcer) UpdatePolicySelf(shouldPersist func() bool, sec string, ptype string, oldRule, newRule []string) (affected bool, err error) { - d.m.Lock() - defer d.m.Unlock() - if shouldPersist != nil && shouldPersist() { - err = d.adapter.(persist.UpdatableAdapter).UpdatePolicy(sec, ptype, oldRule, newRule) - if err != nil { - return false, err - } - } - - ruleUpdated, err := d.model.UpdatePolicy(sec, ptype, oldRule, newRule) - if !ruleUpdated || err != nil { - return ruleUpdated, err - } - - if sec == "g" { - err := d.BuildIncrementalRoleLinks(model.PolicyRemove, ptype, [][]string{oldRule}) // remove the old rule - if err != nil { - return ruleUpdated, err - } - err = d.BuildIncrementalRoleLinks(model.PolicyAdd, ptype, [][]string{newRule}) // add the new rule - if err != nil { - return ruleUpdated, err - } - } - - return ruleUpdated, nil -} - -// UpdatePoliciesSelf provides a method for dispatcher to update a set of authorization rules from the current policy. -func (d *DistributedEnforcer) UpdatePoliciesSelf(shouldPersist func() bool, sec string, ptype string, oldRules, newRules [][]string) (affected bool, err error) { - d.m.Lock() - defer d.m.Unlock() - if shouldPersist != nil && shouldPersist() { - err = d.adapter.(persist.UpdatableAdapter).UpdatePolicies(sec, ptype, oldRules, newRules) - if err != nil { - return false, err - } - } - - ruleUpdated, err := d.model.UpdatePolicies(sec, ptype, oldRules, newRules) - if !ruleUpdated || err != nil { - return ruleUpdated, err - } - - if sec == "g" { - err := d.BuildIncrementalRoleLinks(model.PolicyRemove, ptype, oldRules) // remove the old rule - if err != nil { - return ruleUpdated, err - } - err = d.BuildIncrementalRoleLinks(model.PolicyAdd, ptype, newRules) // add the new rule - if err != nil { - return ruleUpdated, err - } - } - - return ruleUpdated, nil -} - -// UpdateFilteredPoliciesSelf provides a method for dispatcher to update a set of authorization rules from the current policy. -func (d *DistributedEnforcer) UpdateFilteredPoliciesSelf(shouldPersist func() bool, sec string, ptype string, newRules [][]string, fieldIndex int, fieldValues ...string) (bool, error) { - d.m.Lock() - defer d.m.Unlock() - var ( - oldRules [][]string - err error - ) - if shouldPersist != nil && shouldPersist() { - oldRules, err = d.adapter.(persist.UpdatableAdapter).UpdateFilteredPolicies(sec, ptype, newRules, fieldIndex, fieldValues...) - if err != nil { - return false, err - } - } - - ruleChanged, err := d.model.RemovePolicies(sec, ptype, oldRules) - if err != nil { - return ruleChanged, err - } - err = d.model.AddPolicies(sec, ptype, newRules) - if err != nil { - return ruleChanged, err - } - ruleChanged = ruleChanged && len(newRules) != 0 - if !ruleChanged { - return ruleChanged, nil - } - - if sec == "g" { - err := d.BuildIncrementalRoleLinks(model.PolicyRemove, ptype, oldRules) // remove the old rule - if err != nil { - return ruleChanged, err - } - err = d.BuildIncrementalRoleLinks(model.PolicyAdd, ptype, newRules) // add the new rule - if err != nil { - return ruleChanged, err - } - } - - return true, nil -} diff --git a/vendor/github.com/casbin/casbin/v2/enforcer_interface.go b/vendor/github.com/casbin/casbin/v2/enforcer_interface.go deleted file mode 100644 index d22dcf10..00000000 --- a/vendor/github.com/casbin/casbin/v2/enforcer_interface.go +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright 2019 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 ( - "github.com/casbin/casbin/v2/effector" - "github.com/casbin/casbin/v2/model" - "github.com/casbin/casbin/v2/persist" - "github.com/casbin/casbin/v2/rbac" - "github.com/casbin/govaluate" -) - -var _ IEnforcer = &Enforcer{} -var _ IEnforcer = &SyncedEnforcer{} -var _ IEnforcer = &CachedEnforcer{} - -// IEnforcer is the API interface of Enforcer. -type IEnforcer interface { - /* Enforcer API */ - InitWithFile(modelPath string, policyPath string) error - InitWithAdapter(modelPath string, adapter persist.Adapter) error - InitWithModelAndAdapter(m model.Model, adapter persist.Adapter) error - LoadModel() error - GetModel() model.Model - SetModel(m model.Model) - GetAdapter() persist.Adapter - SetAdapter(adapter persist.Adapter) - SetWatcher(watcher persist.Watcher) error - GetRoleManager() rbac.RoleManager - SetRoleManager(rm rbac.RoleManager) - SetEffector(eft effector.Effector) - ClearPolicy() - LoadPolicy() error - LoadFilteredPolicy(filter interface{}) error - LoadIncrementalFilteredPolicy(filter interface{}) error - IsFiltered() bool - SavePolicy() error - EnableEnforce(enable bool) - EnableLog(enable bool) - EnableAutoNotifyWatcher(enable bool) - EnableAutoSave(autoSave bool) - EnableAutoBuildRoleLinks(autoBuildRoleLinks bool) - BuildRoleLinks() error - Enforce(rvals ...interface{}) (bool, error) - EnforceWithMatcher(matcher string, rvals ...interface{}) (bool, error) - EnforceEx(rvals ...interface{}) (bool, []string, error) - EnforceExWithMatcher(matcher string, rvals ...interface{}) (bool, []string, error) - BatchEnforce(requests [][]interface{}) ([]bool, error) - BatchEnforceWithMatcher(matcher string, requests [][]interface{}) ([]bool, error) - - /* RBAC API */ - GetRolesForUser(name string, domain ...string) ([]string, error) - GetUsersForRole(name string, domain ...string) ([]string, error) - HasRoleForUser(name string, role string, domain ...string) (bool, error) - AddRoleForUser(user string, role string, domain ...string) (bool, error) - AddPermissionForUser(user string, permission ...string) (bool, error) - AddPermissionsForUser(user string, permissions ...[]string) (bool, error) - DeletePermissionForUser(user string, permission ...string) (bool, error) - DeletePermissionsForUser(user string) (bool, error) - GetPermissionsForUser(user string, domain ...string) ([][]string, error) - HasPermissionForUser(user string, permission ...string) (bool, error) - GetImplicitRolesForUser(name string, domain ...string) ([]string, error) - GetImplicitPermissionsForUser(user string, domain ...string) ([][]string, error) - GetImplicitUsersForPermission(permission ...string) ([]string, error) - DeleteRoleForUser(user string, role string, domain ...string) (bool, error) - DeleteRolesForUser(user string, domain ...string) (bool, error) - DeleteUser(user string) (bool, error) - DeleteRole(role string) (bool, error) - DeletePermission(permission ...string) (bool, error) - - /* RBAC API with domains*/ - GetUsersForRoleInDomain(name string, domain string) []string - GetRolesForUserInDomain(name string, domain string) []string - GetPermissionsForUserInDomain(user string, domain string) [][]string - AddRoleForUserInDomain(user string, role string, domain string) (bool, error) - DeleteRoleForUserInDomain(user string, role string, domain string) (bool, error) - GetAllUsersByDomain(domain string) ([]string, error) - DeleteRolesForUserInDomain(user string, domain string) (bool, error) - DeleteAllUsersByDomain(domain string) (bool, error) - DeleteDomains(domains ...string) (bool, error) - GetAllDomains() ([]string, error) - GetAllRolesByDomain(domain string) ([]string, error) - - /* Management API */ - GetAllSubjects() ([]string, error) - GetAllNamedSubjects(ptype string) ([]string, error) - GetAllObjects() ([]string, error) - GetAllNamedObjects(ptype string) ([]string, error) - GetAllActions() ([]string, error) - GetAllNamedActions(ptype string) ([]string, error) - GetAllRoles() ([]string, error) - GetAllNamedRoles(ptype string) ([]string, error) - GetPolicy() ([][]string, error) - GetFilteredPolicy(fieldIndex int, fieldValues ...string) ([][]string, error) - GetNamedPolicy(ptype string) ([][]string, error) - GetFilteredNamedPolicy(ptype string, fieldIndex int, fieldValues ...string) ([][]string, error) - GetGroupingPolicy() ([][]string, error) - GetFilteredGroupingPolicy(fieldIndex int, fieldValues ...string) ([][]string, error) - GetNamedGroupingPolicy(ptype string) ([][]string, error) - GetFilteredNamedGroupingPolicy(ptype string, fieldIndex int, fieldValues ...string) ([][]string, error) - HasPolicy(params ...interface{}) (bool, error) - HasNamedPolicy(ptype string, params ...interface{}) (bool, error) - AddPolicy(params ...interface{}) (bool, error) - AddPolicies(rules [][]string) (bool, error) - AddNamedPolicy(ptype string, params ...interface{}) (bool, error) - AddNamedPolicies(ptype string, rules [][]string) (bool, error) - AddPoliciesEx(rules [][]string) (bool, error) - AddNamedPoliciesEx(ptype string, rules [][]string) (bool, error) - RemovePolicy(params ...interface{}) (bool, error) - RemovePolicies(rules [][]string) (bool, error) - RemoveFilteredPolicy(fieldIndex int, fieldValues ...string) (bool, error) - RemoveNamedPolicy(ptype string, params ...interface{}) (bool, error) - RemoveNamedPolicies(ptype string, rules [][]string) (bool, error) - RemoveFilteredNamedPolicy(ptype string, fieldIndex int, fieldValues ...string) (bool, error) - HasGroupingPolicy(params ...interface{}) (bool, error) - HasNamedGroupingPolicy(ptype string, params ...interface{}) (bool, error) - AddGroupingPolicy(params ...interface{}) (bool, error) - AddGroupingPolicies(rules [][]string) (bool, error) - AddGroupingPoliciesEx(rules [][]string) (bool, error) - AddNamedGroupingPolicy(ptype string, params ...interface{}) (bool, error) - AddNamedGroupingPolicies(ptype string, rules [][]string) (bool, error) - AddNamedGroupingPoliciesEx(ptype string, rules [][]string) (bool, error) - RemoveGroupingPolicy(params ...interface{}) (bool, error) - RemoveGroupingPolicies(rules [][]string) (bool, error) - RemoveFilteredGroupingPolicy(fieldIndex int, fieldValues ...string) (bool, error) - RemoveNamedGroupingPolicy(ptype string, params ...interface{}) (bool, error) - RemoveNamedGroupingPolicies(ptype string, rules [][]string) (bool, error) - RemoveFilteredNamedGroupingPolicy(ptype string, fieldIndex int, fieldValues ...string) (bool, error) - AddFunction(name string, function govaluate.ExpressionFunction) - - UpdatePolicy(oldPolicy []string, newPolicy []string) (bool, error) - UpdatePolicies(oldPolicies [][]string, newPolicies [][]string) (bool, error) - UpdateFilteredPolicies(newPolicies [][]string, fieldIndex int, fieldValues ...string) (bool, error) - - UpdateGroupingPolicy(oldRule []string, newRule []string) (bool, error) - UpdateGroupingPolicies(oldRules [][]string, newRules [][]string) (bool, error) - UpdateNamedGroupingPolicy(ptype string, oldRule []string, newRule []string) (bool, error) - UpdateNamedGroupingPolicies(ptype string, oldRules [][]string, newRules [][]string) (bool, error) - - /* Management API with autoNotifyWatcher disabled */ - SelfAddPolicy(sec string, ptype string, rule []string) (bool, error) - SelfAddPolicies(sec string, ptype string, rules [][]string) (bool, error) - SelfAddPoliciesEx(sec string, ptype string, rules [][]string) (bool, error) - SelfRemovePolicy(sec string, ptype string, rule []string) (bool, error) - SelfRemovePolicies(sec string, ptype string, rules [][]string) (bool, error) - SelfRemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) (bool, error) - SelfUpdatePolicy(sec string, ptype string, oldRule, newRule []string) (bool, error) - SelfUpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) (bool, error) -} - -var _ IDistributedEnforcer = &DistributedEnforcer{} - -// IDistributedEnforcer defines dispatcher enforcer. -type IDistributedEnforcer interface { - IEnforcer - SetDispatcher(dispatcher persist.Dispatcher) - /* Management API for DistributedEnforcer*/ - AddPoliciesSelf(shouldPersist func() bool, sec string, ptype string, rules [][]string) (affected [][]string, err error) - RemovePoliciesSelf(shouldPersist func() bool, sec string, ptype string, rules [][]string) (affected [][]string, err error) - RemoveFilteredPolicySelf(shouldPersist func() bool, sec string, ptype string, fieldIndex int, fieldValues ...string) (affected [][]string, err error) - ClearPolicySelf(shouldPersist func() bool) error - UpdatePolicySelf(shouldPersist func() bool, sec string, ptype string, oldRule, newRule []string) (affected bool, err error) - UpdatePoliciesSelf(shouldPersist func() bool, sec string, ptype string, oldRules, newRules [][]string) (affected bool, err error) - UpdateFilteredPoliciesSelf(shouldPersist func() bool, sec string, ptype string, newRules [][]string, fieldIndex int, fieldValues ...string) (bool, error) -} diff --git a/vendor/github.com/casbin/casbin/v2/enforcer_synced.go b/vendor/github.com/casbin/casbin/v2/enforcer_synced.go deleted file mode 100644 index ae2fc7c4..00000000 --- a/vendor/github.com/casbin/casbin/v2/enforcer_synced.go +++ /dev/null @@ -1,650 +0,0 @@ -// 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 ( - "sync" - "sync/atomic" - "time" - - "github.com/casbin/govaluate" - - "github.com/casbin/casbin/v2/persist" -) - -// SyncedEnforcer wraps Enforcer and provides synchronized access. -type SyncedEnforcer struct { - *Enforcer - m sync.RWMutex - stopAutoLoad chan struct{} - autoLoadRunning int32 -} - -// NewSyncedEnforcer creates a synchronized enforcer via file or DB. -func NewSyncedEnforcer(params ...interface{}) (*SyncedEnforcer, error) { - e := &SyncedEnforcer{} - var err error - e.Enforcer, err = NewEnforcer(params...) - if err != nil { - return nil, err - } - - e.stopAutoLoad = make(chan struct{}, 1) - e.autoLoadRunning = 0 - return e, nil -} - -// GetLock return the private RWMutex lock. -func (e *SyncedEnforcer) GetLock() *sync.RWMutex { - return &e.m -} - -// IsAutoLoadingRunning check if SyncedEnforcer is auto loading policies. -func (e *SyncedEnforcer) IsAutoLoadingRunning() bool { - return atomic.LoadInt32(&(e.autoLoadRunning)) != 0 -} - -// StartAutoLoadPolicy starts a go routine that will every specified duration call LoadPolicy. -func (e *SyncedEnforcer) StartAutoLoadPolicy(d time.Duration) { - // Don't start another goroutine if there is already one running - if !atomic.CompareAndSwapInt32(&e.autoLoadRunning, 0, 1) { - return - } - - ticker := time.NewTicker(d) - go func() { - defer func() { - ticker.Stop() - atomic.StoreInt32(&(e.autoLoadRunning), int32(0)) - }() - n := 1 - for { - select { - case <-ticker.C: - // error intentionally ignored - _ = e.LoadPolicy() - // Uncomment this line to see when the policy is loaded. - // log.Print("Load policy for time: ", n) - n++ - case <-e.stopAutoLoad: - return - } - } - }() -} - -// StopAutoLoadPolicy causes the go routine to exit. -func (e *SyncedEnforcer) StopAutoLoadPolicy() { - if e.IsAutoLoadingRunning() { - e.stopAutoLoad <- struct{}{} - } -} - -// SetWatcher sets the current watcher. -func (e *SyncedEnforcer) SetWatcher(watcher persist.Watcher) error { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.SetWatcher(watcher) -} - -// LoadModel reloads the model from the model CONF file. -func (e *SyncedEnforcer) LoadModel() error { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.LoadModel() -} - -// ClearPolicy clears all policy. -func (e *SyncedEnforcer) ClearPolicy() { - e.m.Lock() - defer e.m.Unlock() - e.Enforcer.ClearPolicy() -} - -// LoadPolicy reloads the policy from file/database. -func (e *SyncedEnforcer) LoadPolicy() error { - e.m.RLock() - newModel, err := e.loadPolicyFromAdapter(e.model) - e.m.RUnlock() - if err != nil { - return err - } - e.m.Lock() - err = e.applyModifiedModel(newModel) - e.m.Unlock() - if err != nil { - return err - } - return nil -} - -// LoadFilteredPolicy reloads a filtered policy from file/database. -func (e *SyncedEnforcer) LoadFilteredPolicy(filter interface{}) error { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.LoadFilteredPolicy(filter) -} - -// LoadIncrementalFilteredPolicy reloads a filtered policy from file/database. -func (e *SyncedEnforcer) LoadIncrementalFilteredPolicy(filter interface{}) error { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.LoadIncrementalFilteredPolicy(filter) -} - -// SavePolicy saves the current policy (usually after changed with Casbin API) back to file/database. -func (e *SyncedEnforcer) SavePolicy() error { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.SavePolicy() -} - -// BuildRoleLinks manually rebuild the role inheritance relations. -func (e *SyncedEnforcer) BuildRoleLinks() error { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.BuildRoleLinks() -} - -// Enforce decides whether a "subject" can access a "object" with the operation "action", input parameters are usually: (sub, obj, act). -func (e *SyncedEnforcer) Enforce(rvals ...interface{}) (bool, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.Enforce(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 *SyncedEnforcer) EnforceWithMatcher(matcher string, rvals ...interface{}) (bool, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.EnforceWithMatcher(matcher, rvals...) -} - -// EnforceEx explain enforcement by informing matched rules. -func (e *SyncedEnforcer) EnforceEx(rvals ...interface{}) (bool, []string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.EnforceEx(rvals...) -} - -// EnforceExWithMatcher use a custom matcher and explain enforcement by informing matched rules. -func (e *SyncedEnforcer) EnforceExWithMatcher(matcher string, rvals ...interface{}) (bool, []string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.EnforceExWithMatcher(matcher, rvals...) -} - -// BatchEnforce enforce in batches. -func (e *SyncedEnforcer) BatchEnforce(requests [][]interface{}) ([]bool, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.BatchEnforce(requests) -} - -// BatchEnforceWithMatcher enforce with matcher in batches. -func (e *SyncedEnforcer) BatchEnforceWithMatcher(matcher string, requests [][]interface{}) ([]bool, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.BatchEnforceWithMatcher(matcher, requests) -} - -// GetAllSubjects gets the list of subjects that show up in the current policy. -func (e *SyncedEnforcer) GetAllSubjects() ([]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetAllSubjects() -} - -// GetAllNamedSubjects gets the list of subjects that show up in the current named policy. -func (e *SyncedEnforcer) GetAllNamedSubjects(ptype string) ([]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetAllNamedSubjects(ptype) -} - -// GetAllObjects gets the list of objects that show up in the current policy. -func (e *SyncedEnforcer) GetAllObjects() ([]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetAllObjects() -} - -// GetAllNamedObjects gets the list of objects that show up in the current named policy. -func (e *SyncedEnforcer) GetAllNamedObjects(ptype string) ([]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetAllNamedObjects(ptype) -} - -// GetAllActions gets the list of actions that show up in the current policy. -func (e *SyncedEnforcer) GetAllActions() ([]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetAllActions() -} - -// GetAllNamedActions gets the list of actions that show up in the current named policy. -func (e *SyncedEnforcer) GetAllNamedActions(ptype string) ([]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetAllNamedActions(ptype) -} - -// GetAllRoles gets the list of roles that show up in the current policy. -func (e *SyncedEnforcer) GetAllRoles() ([]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetAllRoles() -} - -// GetAllNamedRoles gets the list of roles that show up in the current named policy. -func (e *SyncedEnforcer) GetAllNamedRoles(ptype string) ([]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetAllNamedRoles(ptype) -} - -// GetPolicy gets all the authorization rules in the policy. -func (e *SyncedEnforcer) GetPolicy() ([][]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetPolicy() -} - -// GetFilteredPolicy gets all the authorization rules in the policy, field filters can be specified. -func (e *SyncedEnforcer) GetFilteredPolicy(fieldIndex int, fieldValues ...string) ([][]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetFilteredPolicy(fieldIndex, fieldValues...) -} - -// GetNamedPolicy gets all the authorization rules in the named policy. -func (e *SyncedEnforcer) GetNamedPolicy(ptype string) ([][]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetNamedPolicy(ptype) -} - -// GetFilteredNamedPolicy gets all the authorization rules in the named policy, field filters can be specified. -func (e *SyncedEnforcer) GetFilteredNamedPolicy(ptype string, fieldIndex int, fieldValues ...string) ([][]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetFilteredNamedPolicy(ptype, fieldIndex, fieldValues...) -} - -// GetGroupingPolicy gets all the role inheritance rules in the policy. -func (e *SyncedEnforcer) GetGroupingPolicy() ([][]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetGroupingPolicy() -} - -// GetFilteredGroupingPolicy gets all the role inheritance rules in the policy, field filters can be specified. -func (e *SyncedEnforcer) GetFilteredGroupingPolicy(fieldIndex int, fieldValues ...string) ([][]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetFilteredGroupingPolicy(fieldIndex, fieldValues...) -} - -// GetNamedGroupingPolicy gets all the role inheritance rules in the policy. -func (e *SyncedEnforcer) GetNamedGroupingPolicy(ptype string) ([][]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetNamedGroupingPolicy(ptype) -} - -// GetFilteredNamedGroupingPolicy gets all the role inheritance rules in the policy, field filters can be specified. -func (e *SyncedEnforcer) GetFilteredNamedGroupingPolicy(ptype string, fieldIndex int, fieldValues ...string) ([][]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetFilteredNamedGroupingPolicy(ptype, fieldIndex, fieldValues...) -} - -// HasPolicy determines whether an authorization rule exists. -func (e *SyncedEnforcer) HasPolicy(params ...interface{}) (bool, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.HasPolicy(params...) -} - -// HasNamedPolicy determines whether a named authorization rule exists. -func (e *SyncedEnforcer) HasNamedPolicy(ptype string, params ...interface{}) (bool, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.HasNamedPolicy(ptype, params...) -} - -// 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 (e *SyncedEnforcer) AddPolicy(params ...interface{}) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.AddPolicy(params...) -} - -// AddPolicies adds authorization rules to the current policy. -// If the rule already exists, the function returns false for the corresponding rule and the rule will not be added. -// Otherwise the function returns true for the corresponding rule by adding the new rule. -func (e *SyncedEnforcer) AddPolicies(rules [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.AddPolicies(rules) -} - -// AddPoliciesEx adds authorization rules to the current policy. -// If the rule already exists, the rule will not be added. -// But unlike AddPolicies, other non-existent rules are added instead of returning false directly. -func (e *SyncedEnforcer) AddPoliciesEx(rules [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.AddPoliciesEx(rules) -} - -// AddNamedPolicy adds an authorization rule to the current named 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 (e *SyncedEnforcer) AddNamedPolicy(ptype string, params ...interface{}) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.AddNamedPolicy(ptype, params...) -} - -// AddNamedPolicies adds authorization rules to the current named policy. -// If the rule already exists, the function returns false for the corresponding rule and the rule will not be added. -// Otherwise the function returns true for the corresponding by adding the new rule. -func (e *SyncedEnforcer) AddNamedPolicies(ptype string, rules [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.AddNamedPolicies(ptype, rules) -} - -// AddNamedPoliciesEx adds authorization rules to the current named policy. -// If the rule already exists, the rule will not be added. -// But unlike AddNamedPolicies, other non-existent rules are added instead of returning false directly. -func (e *SyncedEnforcer) AddNamedPoliciesEx(ptype string, rules [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.AddNamedPoliciesEx(ptype, rules) -} - -// RemovePolicy removes an authorization rule from the current policy. -func (e *SyncedEnforcer) RemovePolicy(params ...interface{}) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.RemovePolicy(params...) -} - -// UpdatePolicy updates an authorization rule from the current policy. -func (e *SyncedEnforcer) UpdatePolicy(oldPolicy []string, newPolicy []string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.UpdatePolicy(oldPolicy, newPolicy) -} - -func (e *SyncedEnforcer) UpdateNamedPolicy(ptype string, p1 []string, p2 []string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.UpdateNamedPolicy(ptype, p1, p2) -} - -// UpdatePolicies updates authorization rules from the current policies. -func (e *SyncedEnforcer) UpdatePolicies(oldPolices [][]string, newPolicies [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.UpdatePolicies(oldPolices, newPolicies) -} - -func (e *SyncedEnforcer) UpdateNamedPolicies(ptype string, p1 [][]string, p2 [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.UpdateNamedPolicies(ptype, p1, p2) -} - -func (e *SyncedEnforcer) UpdateFilteredPolicies(newPolicies [][]string, fieldIndex int, fieldValues ...string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.UpdateFilteredPolicies(newPolicies, fieldIndex, fieldValues...) -} - -func (e *SyncedEnforcer) UpdateFilteredNamedPolicies(ptype string, newPolicies [][]string, fieldIndex int, fieldValues ...string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.UpdateFilteredNamedPolicies(ptype, newPolicies, fieldIndex, fieldValues...) -} - -// RemovePolicies removes authorization rules from the current policy. -func (e *SyncedEnforcer) RemovePolicies(rules [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.RemovePolicies(rules) -} - -// RemoveFilteredPolicy removes an authorization rule from the current policy, field filters can be specified. -func (e *SyncedEnforcer) RemoveFilteredPolicy(fieldIndex int, fieldValues ...string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.RemoveFilteredPolicy(fieldIndex, fieldValues...) -} - -// RemoveNamedPolicy removes an authorization rule from the current named policy. -func (e *SyncedEnforcer) RemoveNamedPolicy(ptype string, params ...interface{}) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.RemoveNamedPolicy(ptype, params...) -} - -// RemoveNamedPolicies removes authorization rules from the current named policy. -func (e *SyncedEnforcer) RemoveNamedPolicies(ptype string, rules [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.RemoveNamedPolicies(ptype, rules) -} - -// RemoveFilteredNamedPolicy removes an authorization rule from the current named policy, field filters can be specified. -func (e *SyncedEnforcer) RemoveFilteredNamedPolicy(ptype string, fieldIndex int, fieldValues ...string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.RemoveFilteredNamedPolicy(ptype, fieldIndex, fieldValues...) -} - -// HasGroupingPolicy determines whether a role inheritance rule exists. -func (e *SyncedEnforcer) HasGroupingPolicy(params ...interface{}) (bool, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.HasGroupingPolicy(params...) -} - -// HasNamedGroupingPolicy determines whether a named role inheritance rule exists. -func (e *SyncedEnforcer) HasNamedGroupingPolicy(ptype string, params ...interface{}) (bool, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.HasNamedGroupingPolicy(ptype, params...) -} - -// AddGroupingPolicy adds a role inheritance 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 (e *SyncedEnforcer) AddGroupingPolicy(params ...interface{}) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.AddGroupingPolicy(params...) -} - -// AddGroupingPolicies adds role inheritance rulea to the current policy. -// If the rule already exists, the function returns false for the corresponding policy rule and the rule will not be added. -// Otherwise the function returns true for the corresponding policy rule by adding the new rule. -func (e *SyncedEnforcer) AddGroupingPolicies(rules [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.AddGroupingPolicies(rules) -} - -// AddGroupingPoliciesEx adds role inheritance rules to the current policy. -// If the rule already exists, the rule will not be added. -// But unlike AddGroupingPolicies, other non-existent rules are added instead of returning false directly. -func (e *SyncedEnforcer) AddGroupingPoliciesEx(rules [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.AddGroupingPoliciesEx(rules) -} - -// AddNamedGroupingPolicy adds a named role inheritance 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 (e *SyncedEnforcer) AddNamedGroupingPolicy(ptype string, params ...interface{}) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.AddNamedGroupingPolicy(ptype, params...) -} - -// AddNamedGroupingPolicies adds named role inheritance rules to the current policy. -// If the rule already exists, the function returns false for the corresponding policy rule and the rule will not be added. -// Otherwise the function returns true for the corresponding policy rule by adding the new rule. -func (e *SyncedEnforcer) AddNamedGroupingPolicies(ptype string, rules [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.AddNamedGroupingPolicies(ptype, rules) -} - -// AddNamedGroupingPoliciesEx adds named role inheritance rules to the current policy. -// If the rule already exists, the rule will not be added. -// But unlike AddNamedGroupingPolicies, other non-existent rules are added instead of returning false directly. -func (e *SyncedEnforcer) AddNamedGroupingPoliciesEx(ptype string, rules [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.AddNamedGroupingPoliciesEx(ptype, rules) -} - -// RemoveGroupingPolicy removes a role inheritance rule from the current policy. -func (e *SyncedEnforcer) RemoveGroupingPolicy(params ...interface{}) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.RemoveGroupingPolicy(params...) -} - -// RemoveGroupingPolicies removes role inheritance rules from the current policy. -func (e *SyncedEnforcer) RemoveGroupingPolicies(rules [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.RemoveGroupingPolicies(rules) -} - -// RemoveFilteredGroupingPolicy removes a role inheritance rule from the current policy, field filters can be specified. -func (e *SyncedEnforcer) RemoveFilteredGroupingPolicy(fieldIndex int, fieldValues ...string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.RemoveFilteredGroupingPolicy(fieldIndex, fieldValues...) -} - -// RemoveNamedGroupingPolicy removes a role inheritance rule from the current named policy. -func (e *SyncedEnforcer) RemoveNamedGroupingPolicy(ptype string, params ...interface{}) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.RemoveNamedGroupingPolicy(ptype, params...) -} - -// RemoveNamedGroupingPolicies removes role inheritance rules from the current named policy. -func (e *SyncedEnforcer) RemoveNamedGroupingPolicies(ptype string, rules [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.RemoveNamedGroupingPolicies(ptype, rules) -} - -func (e *SyncedEnforcer) UpdateGroupingPolicy(oldRule []string, newRule []string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.UpdateGroupingPolicy(oldRule, newRule) -} - -func (e *SyncedEnforcer) UpdateGroupingPolicies(oldRules [][]string, newRules [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.UpdateGroupingPolicies(oldRules, newRules) -} - -func (e *SyncedEnforcer) UpdateNamedGroupingPolicy(ptype string, oldRule []string, newRule []string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.UpdateNamedGroupingPolicy(ptype, oldRule, newRule) -} - -func (e *SyncedEnforcer) UpdateNamedGroupingPolicies(ptype string, oldRules [][]string, newRules [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.UpdateNamedGroupingPolicies(ptype, oldRules, newRules) -} - -// RemoveFilteredNamedGroupingPolicy removes a role inheritance rule from the current named policy, field filters can be specified. -func (e *SyncedEnforcer) RemoveFilteredNamedGroupingPolicy(ptype string, fieldIndex int, fieldValues ...string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.RemoveFilteredNamedGroupingPolicy(ptype, fieldIndex, fieldValues...) -} - -// AddFunction adds a customized function. -func (e *SyncedEnforcer) AddFunction(name string, function govaluate.ExpressionFunction) { - e.m.Lock() - defer e.m.Unlock() - e.Enforcer.AddFunction(name, function) -} - -func (e *SyncedEnforcer) SelfAddPolicy(sec string, ptype string, rule []string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.SelfAddPolicy(sec, ptype, rule) -} - -func (e *SyncedEnforcer) SelfAddPolicies(sec string, ptype string, rules [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.SelfAddPolicies(sec, ptype, rules) -} - -func (e *SyncedEnforcer) SelfAddPoliciesEx(sec string, ptype string, rules [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.SelfAddPoliciesEx(sec, ptype, rules) -} - -func (e *SyncedEnforcer) SelfRemovePolicy(sec string, ptype string, rule []string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.SelfRemovePolicy(sec, ptype, rule) -} - -func (e *SyncedEnforcer) SelfRemovePolicies(sec string, ptype string, rules [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.SelfRemovePolicies(sec, ptype, rules) -} - -func (e *SyncedEnforcer) SelfRemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.SelfRemoveFilteredPolicy(sec, ptype, fieldIndex, fieldValues...) -} - -func (e *SyncedEnforcer) SelfUpdatePolicy(sec string, ptype string, oldRule, newRule []string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.SelfUpdatePolicy(sec, ptype, oldRule, newRule) -} - -func (e *SyncedEnforcer) SelfUpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.SelfUpdatePolicies(sec, ptype, oldRules, newRules) -} diff --git a/vendor/github.com/casbin/casbin/v2/errors/rbac_errors.go b/vendor/github.com/casbin/casbin/v2/errors/rbac_errors.go deleted file mode 100644 index 2f358b37..00000000 --- a/vendor/github.com/casbin/casbin/v2/errors/rbac_errors.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2018 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 errors - -import "errors" - -// Global errors for rbac defined here. -var ( - ErrNameNotFound = errors.New("error: name does not exist") - ErrDomainParameter = errors.New("error: domain should be 1 parameter") - ErrLinkNotFound = errors.New("error: link between name1 and name2 does not exist") - ErrUseDomainParameter = errors.New("error: useDomain should be 1 parameter") - ErrInvalidFieldValuesParameter = errors.New("fieldValues requires at least one parameter") - - // GetAllowedObjectConditions errors. - ErrObjCondition = errors.New("need to meet the prefix required by the object condition") - ErrEmptyCondition = errors.New("GetAllowedObjectConditions have an empty condition") -) diff --git a/vendor/github.com/casbin/casbin/v2/frontend.go b/vendor/github.com/casbin/casbin/v2/frontend.go deleted file mode 100644 index 101a23a5..00000000 --- a/vendor/github.com/casbin/casbin/v2/frontend.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 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 ( - "bytes" - "encoding/json" -) - -func CasbinJsGetPermissionForUser(e IEnforcer, user string) (string, error) { - model := e.GetModel() - m := map[string]interface{}{} - - m["m"] = model.ToText() - - pRules := [][]string{} - for ptype := range model["p"] { - policies, err := model.GetPolicy("p", ptype) - if err != nil { - return "", err - } - for _, rules := range policies { - pRules = append(pRules, append([]string{ptype}, rules...)) - } - } - m["p"] = pRules - - gRules := [][]string{} - for ptype := range model["g"] { - policies, err := model.GetPolicy("g", ptype) - if err != nil { - return "", err - } - for _, rules := range policies { - gRules = append(gRules, append([]string{ptype}, rules...)) - } - } - m["g"] = gRules - - result := bytes.NewBuffer([]byte{}) - encoder := json.NewEncoder(result) - encoder.SetEscapeHTML(false) - err := encoder.Encode(m) - return result.String(), err -} diff --git a/vendor/github.com/casbin/casbin/v2/frontend_old.go b/vendor/github.com/casbin/casbin/v2/frontend_old.go deleted file mode 100644 index 139b164f..00000000 --- a/vendor/github.com/casbin/casbin/v2/frontend_old.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2021 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 "encoding/json" - -func CasbinJsGetPermissionForUserOld(e IEnforcer, user string) ([]byte, error) { - policy, err := e.GetImplicitPermissionsForUser(user) - if err != nil { - return nil, err - } - permission := make(map[string][]string) - for i := 0; i < len(policy); i++ { - permission[policy[i][2]] = append(permission[policy[i][2]], policy[i][1]) - } - b, _ := json.Marshal(permission) - return b, nil -} diff --git a/vendor/github.com/casbin/casbin/v2/internal_api.go b/vendor/github.com/casbin/casbin/v2/internal_api.go deleted file mode 100644 index cd329016..00000000 --- a/vendor/github.com/casbin/casbin/v2/internal_api.go +++ /dev/null @@ -1,497 +0,0 @@ -// 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 ( - "fmt" - - Err "github.com/casbin/casbin/v2/errors" - "github.com/casbin/casbin/v2/model" - "github.com/casbin/casbin/v2/persist" -) - -const ( - notImplemented = "not implemented" -) - -func (e *Enforcer) shouldPersist() bool { - return e.adapter != nil && e.autoSave -} - -func (e *Enforcer) shouldNotify() bool { - return e.watcher != nil && e.autoNotifyWatcher -} - -// addPolicy adds a rule to the current policy. -func (e *Enforcer) addPolicyWithoutNotify(sec string, ptype string, rule []string) (bool, error) { - if e.dispatcher != nil && e.autoNotifyDispatcher { - return true, e.dispatcher.AddPolicies(sec, ptype, [][]string{rule}) - } - - hasPolicy, err := e.model.HasPolicy(sec, ptype, rule) - if hasPolicy || err != nil { - return hasPolicy, err - } - - if e.shouldPersist() { - if err = e.adapter.AddPolicy(sec, ptype, rule); err != nil { - if err.Error() != notImplemented { - return false, err - } - } - } - - err = e.model.AddPolicy(sec, ptype, rule) - if err != nil { - return false, err - } - - if sec == "g" { - err := e.BuildIncrementalRoleLinks(model.PolicyAdd, ptype, [][]string{rule}) - if err != nil { - return true, err - } - } - - return true, nil -} - -// addPoliciesWithoutNotify adds rules to the current policy without notify -// If autoRemoveRepeat == true, existing rules are automatically filtered -// Otherwise, false is returned directly. -func (e *Enforcer) addPoliciesWithoutNotify(sec string, ptype string, rules [][]string, autoRemoveRepeat bool) (bool, error) { - if e.dispatcher != nil && e.autoNotifyDispatcher { - return true, e.dispatcher.AddPolicies(sec, ptype, rules) - } - - if !autoRemoveRepeat { - hasPolicies, err := e.model.HasPolicies(sec, ptype, rules) - if hasPolicies || err != nil { - return false, err - } - } - - if e.shouldPersist() { - if err := e.adapter.(persist.BatchAdapter).AddPolicies(sec, ptype, rules); err != nil { - if err.Error() != notImplemented { - return false, err - } - } - } - - err := e.model.AddPolicies(sec, ptype, rules) - if err != nil { - return false, err - } - - if sec == "g" { - err := e.BuildIncrementalRoleLinks(model.PolicyAdd, ptype, rules) - if err != nil { - return true, err - } - - err = e.BuildIncrementalConditionalRoleLinks(model.PolicyAdd, ptype, rules) - if err != nil { - return true, err - } - } - - return true, nil -} - -// removePolicy removes a rule from the current policy. -func (e *Enforcer) removePolicyWithoutNotify(sec string, ptype string, rule []string) (bool, error) { - if e.dispatcher != nil && e.autoNotifyDispatcher { - return true, e.dispatcher.RemovePolicies(sec, ptype, [][]string{rule}) - } - - if e.shouldPersist() { - if err := e.adapter.RemovePolicy(sec, ptype, rule); err != nil { - if err.Error() != notImplemented { - return false, err - } - } - } - - ruleRemoved, err := e.model.RemovePolicy(sec, ptype, rule) - if !ruleRemoved || err != nil { - return ruleRemoved, err - } - - if sec == "g" { - err := e.BuildIncrementalRoleLinks(model.PolicyRemove, ptype, [][]string{rule}) - if err != nil { - return ruleRemoved, err - } - } - - return ruleRemoved, nil -} - -func (e *Enforcer) updatePolicyWithoutNotify(sec string, ptype string, oldRule []string, newRule []string) (bool, error) { - if e.dispatcher != nil && e.autoNotifyDispatcher { - return true, e.dispatcher.UpdatePolicy(sec, ptype, oldRule, newRule) - } - - if e.shouldPersist() { - if err := e.adapter.(persist.UpdatableAdapter).UpdatePolicy(sec, ptype, oldRule, newRule); err != nil { - if err.Error() != notImplemented { - return false, err - } - } - } - ruleUpdated, err := e.model.UpdatePolicy(sec, ptype, oldRule, newRule) - if !ruleUpdated || err != nil { - return ruleUpdated, err - } - - if sec == "g" { - err := e.BuildIncrementalRoleLinks(model.PolicyRemove, ptype, [][]string{oldRule}) // remove the old rule - if err != nil { - return ruleUpdated, err - } - err = e.BuildIncrementalRoleLinks(model.PolicyAdd, ptype, [][]string{newRule}) // add the new rule - if err != nil { - return ruleUpdated, err - } - } - - return ruleUpdated, nil -} - -func (e *Enforcer) updatePoliciesWithoutNotify(sec string, ptype string, oldRules [][]string, newRules [][]string) (bool, error) { - if len(newRules) != len(oldRules) { - return false, fmt.Errorf("the length of oldRules should be equal to the length of newRules, but got the length of oldRules is %d, the length of newRules is %d", len(oldRules), len(newRules)) - } - - if e.dispatcher != nil && e.autoNotifyDispatcher { - return true, e.dispatcher.UpdatePolicies(sec, ptype, oldRules, newRules) - } - - if e.shouldPersist() { - if err := e.adapter.(persist.UpdatableAdapter).UpdatePolicies(sec, ptype, oldRules, newRules); err != nil { - if err.Error() != notImplemented { - return false, err - } - } - } - - ruleUpdated, err := e.model.UpdatePolicies(sec, ptype, oldRules, newRules) - if !ruleUpdated || err != nil { - return ruleUpdated, err - } - - if sec == "g" { - err := e.BuildIncrementalRoleLinks(model.PolicyRemove, ptype, oldRules) // remove the old rules - if err != nil { - return ruleUpdated, err - } - err = e.BuildIncrementalRoleLinks(model.PolicyAdd, ptype, newRules) // add the new rules - if err != nil { - return ruleUpdated, err - } - } - - return ruleUpdated, nil -} - -// removePolicies removes rules from the current policy. -func (e *Enforcer) removePoliciesWithoutNotify(sec string, ptype string, rules [][]string) (bool, error) { - if hasPolicies, err := e.model.HasPolicies(sec, ptype, rules); !hasPolicies || err != nil { - return hasPolicies, err - } - - if e.dispatcher != nil && e.autoNotifyDispatcher { - return true, e.dispatcher.RemovePolicies(sec, ptype, rules) - } - - if e.shouldPersist() { - if err := e.adapter.(persist.BatchAdapter).RemovePolicies(sec, ptype, rules); err != nil { - if err.Error() != notImplemented { - return false, err - } - } - } - - rulesRemoved, err := e.model.RemovePolicies(sec, ptype, rules) - if !rulesRemoved || err != nil { - return rulesRemoved, err - } - - if sec == "g" { - err := e.BuildIncrementalRoleLinks(model.PolicyRemove, ptype, rules) - if err != nil { - return rulesRemoved, err - } - } - return rulesRemoved, nil -} - -// removeFilteredPolicy removes rules based on field filters from the current policy. -func (e *Enforcer) removeFilteredPolicyWithoutNotify(sec string, ptype string, fieldIndex int, fieldValues []string) (bool, error) { - if len(fieldValues) == 0 { - return false, Err.ErrInvalidFieldValuesParameter - } - - if e.dispatcher != nil && e.autoNotifyDispatcher { - return true, e.dispatcher.RemoveFilteredPolicy(sec, ptype, fieldIndex, fieldValues...) - } - - if e.shouldPersist() { - if err := e.adapter.RemoveFilteredPolicy(sec, ptype, fieldIndex, fieldValues...); err != nil { - if err.Error() != notImplemented { - return false, err - } - } - } - - ruleRemoved, effects, err := e.model.RemoveFilteredPolicy(sec, ptype, fieldIndex, fieldValues...) - if !ruleRemoved || err != nil { - return ruleRemoved, err - } - - if sec == "g" { - err := e.BuildIncrementalRoleLinks(model.PolicyRemove, ptype, effects) - if err != nil { - return ruleRemoved, err - } - } - - return ruleRemoved, nil -} - -func (e *Enforcer) updateFilteredPoliciesWithoutNotify(sec string, ptype string, newRules [][]string, fieldIndex int, fieldValues ...string) ([][]string, error) { - var ( - oldRules [][]string - err error - ) - - if _, err = e.model.GetAssertion(sec, ptype); err != nil { - return oldRules, err - } - - if e.shouldPersist() { - if oldRules, err = e.adapter.(persist.UpdatableAdapter).UpdateFilteredPolicies(sec, ptype, newRules, fieldIndex, fieldValues...); err != nil { - if err.Error() != notImplemented { - return nil, err - } - } - // For compatibility, because some adapters return oldRules containing ptype, see https://github.com/casbin/xorm-adapter/issues/49 - for i, oldRule := range oldRules { - if len(oldRules[i]) == len(e.model[sec][ptype].Tokens)+1 { - oldRules[i] = oldRule[1:] - } - } - } - - if e.dispatcher != nil && e.autoNotifyDispatcher { - return oldRules, e.dispatcher.UpdateFilteredPolicies(sec, ptype, oldRules, newRules) - } - - ruleChanged, err := e.model.RemovePolicies(sec, ptype, oldRules) - if err != nil { - return oldRules, err - } - err = e.model.AddPolicies(sec, ptype, newRules) - if err != nil { - return oldRules, err - } - ruleChanged = ruleChanged && len(newRules) != 0 - if !ruleChanged { - return make([][]string, 0), nil - } - - if sec == "g" { - err := e.BuildIncrementalRoleLinks(model.PolicyRemove, ptype, oldRules) // remove the old rules - if err != nil { - return oldRules, err - } - err = e.BuildIncrementalRoleLinks(model.PolicyAdd, ptype, newRules) // add the new rules - if err != nil { - return oldRules, err - } - } - - return oldRules, nil -} - -// addPolicy adds a rule to the current policy. -func (e *Enforcer) addPolicy(sec string, ptype string, rule []string) (bool, error) { - ok, err := e.addPolicyWithoutNotify(sec, ptype, rule) - if !ok || err != nil { - return ok, err - } - - if e.shouldNotify() { - var err error - if watcher, ok := e.watcher.(persist.WatcherEx); ok { - err = watcher.UpdateForAddPolicy(sec, ptype, rule...) - } else { - err = e.watcher.Update() - } - return true, err - } - - return true, nil -} - -// addPolicies adds rules to the current policy. -// If autoRemoveRepeat == true, existing rules are automatically filtered -// Otherwise, false is returned directly. -func (e *Enforcer) addPolicies(sec string, ptype string, rules [][]string, autoRemoveRepeat bool) (bool, error) { - ok, err := e.addPoliciesWithoutNotify(sec, ptype, rules, autoRemoveRepeat) - if !ok || err != nil { - return ok, err - } - - if e.shouldNotify() { - var err error - if watcher, ok := e.watcher.(persist.WatcherEx); ok { - err = watcher.UpdateForAddPolicies(sec, ptype, rules...) - } else { - err = e.watcher.Update() - } - return true, err - } - - return true, nil -} - -// removePolicy removes a rule from the current policy. -func (e *Enforcer) removePolicy(sec string, ptype string, rule []string) (bool, error) { - ok, err := e.removePolicyWithoutNotify(sec, ptype, rule) - if !ok || err != nil { - return ok, err - } - - if e.shouldNotify() { - var err error - if watcher, ok := e.watcher.(persist.WatcherEx); ok { - err = watcher.UpdateForRemovePolicy(sec, ptype, rule...) - } else { - err = e.watcher.Update() - } - return true, err - } - - return true, nil -} - -func (e *Enforcer) updatePolicy(sec string, ptype string, oldRule []string, newRule []string) (bool, error) { - ok, err := e.updatePolicyWithoutNotify(sec, ptype, oldRule, newRule) - if !ok || err != nil { - return ok, err - } - - if e.shouldNotify() { - var err error - if watcher, ok := e.watcher.(persist.UpdatableWatcher); ok { - err = watcher.UpdateForUpdatePolicy(sec, ptype, oldRule, newRule) - } else { - err = e.watcher.Update() - } - return true, err - } - - return true, nil -} - -func (e *Enforcer) updatePolicies(sec string, ptype string, oldRules [][]string, newRules [][]string) (bool, error) { - ok, err := e.updatePoliciesWithoutNotify(sec, ptype, oldRules, newRules) - if !ok || err != nil { - return ok, err - } - - if e.shouldNotify() { - var err error - if watcher, ok := e.watcher.(persist.UpdatableWatcher); ok { - err = watcher.UpdateForUpdatePolicies(sec, ptype, oldRules, newRules) - } else { - err = e.watcher.Update() - } - return true, err - } - - return true, nil -} - -// removePolicies removes rules from the current policy. -func (e *Enforcer) removePolicies(sec string, ptype string, rules [][]string) (bool, error) { - ok, err := e.removePoliciesWithoutNotify(sec, ptype, rules) - if !ok || err != nil { - return ok, err - } - - if e.shouldNotify() { - var err error - if watcher, ok := e.watcher.(persist.WatcherEx); ok { - err = watcher.UpdateForRemovePolicies(sec, ptype, rules...) - } else { - err = e.watcher.Update() - } - return true, err - } - - return true, nil -} - -// removeFilteredPolicy removes rules based on field filters from the current policy. -func (e *Enforcer) removeFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues []string) (bool, error) { - ok, err := e.removeFilteredPolicyWithoutNotify(sec, ptype, fieldIndex, fieldValues) - if !ok || err != nil { - return ok, err - } - - if e.shouldNotify() { - var err error - if watcher, ok := e.watcher.(persist.WatcherEx); ok { - err = watcher.UpdateForRemoveFilteredPolicy(sec, ptype, fieldIndex, fieldValues...) - } else { - err = e.watcher.Update() - } - return true, err - } - - return true, nil -} - -func (e *Enforcer) updateFilteredPolicies(sec string, ptype string, newRules [][]string, fieldIndex int, fieldValues ...string) (bool, error) { - oldRules, err := e.updateFilteredPoliciesWithoutNotify(sec, ptype, newRules, fieldIndex, fieldValues...) - ok := len(oldRules) != 0 - if !ok || err != nil { - return ok, err - } - - if e.shouldNotify() { - var err error - if watcher, ok := e.watcher.(persist.UpdatableWatcher); ok { - err = watcher.UpdateForUpdatePolicies(sec, ptype, oldRules, newRules) - } else { - err = e.watcher.Update() - } - return true, err - } - - return true, nil -} - -func (e *Enforcer) GetFieldIndex(ptype string, field string) (int, error) { - return e.model.GetFieldIndex(ptype, field) -} - -func (e *Enforcer) SetFieldIndex(ptype string, field string, index int) { - assertion := e.model["p"][ptype] - assertion.FieldIndexMap[field] = index -} diff --git a/vendor/github.com/casbin/casbin/v2/log/default_logger.go b/vendor/github.com/casbin/casbin/v2/log/default_logger.go deleted file mode 100644 index 9994f390..00000000 --- a/vendor/github.com/casbin/casbin/v2/log/default_logger.go +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2018 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 log - -import ( - "fmt" - "log" - "strings" -) - -// DefaultLogger is the implementation for a Logger using golang log. -type DefaultLogger struct { - enabled bool -} - -func (l *DefaultLogger) EnableLog(enable bool) { - l.enabled = enable -} - -func (l *DefaultLogger) IsEnabled() bool { - return l.enabled -} - -func (l *DefaultLogger) LogModel(model [][]string) { - if !l.enabled { - return - } - var str strings.Builder - str.WriteString("Model: ") - for _, v := range model { - str.WriteString(fmt.Sprintf("%v\n", v)) - } - - log.Println(str.String()) -} - -func (l *DefaultLogger) LogEnforce(matcher string, request []interface{}, result bool, explains [][]string) { - if !l.enabled { - return - } - - var reqStr strings.Builder - reqStr.WriteString("Request: ") - for i, rval := range request { - if i != len(request)-1 { - reqStr.WriteString(fmt.Sprintf("%v, ", rval)) - } else { - reqStr.WriteString(fmt.Sprintf("%v", rval)) - } - } - reqStr.WriteString(fmt.Sprintf(" ---> %t\n", result)) - - 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)) - } - } - - log.Println(reqStr.String()) -} - -func (l *DefaultLogger) LogPolicy(policy map[string][][]string) { - if !l.enabled { - return - } - - var str strings.Builder - str.WriteString("Policy: ") - for k, v := range policy { - str.WriteString(fmt.Sprintf("%s : %v\n", k, v)) - } - - log.Println(str.String()) -} - -func (l *DefaultLogger) LogRole(roles []string) { - if !l.enabled { - return - } - - log.Println("Roles: ", strings.Join(roles, "\n")) -} - -func (l *DefaultLogger) LogError(err error, msg ...string) { - if !l.enabled { - return - } - log.Println(msg, err) -} diff --git a/vendor/github.com/casbin/casbin/v2/log/log_util.go b/vendor/github.com/casbin/casbin/v2/log/log_util.go deleted file mode 100644 index 7edabf89..00000000 --- a/vendor/github.com/casbin/casbin/v2/log/log_util.go +++ /dev/null @@ -1,52 +0,0 @@ -// 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 log - -var logger Logger = &DefaultLogger{} - -// SetLogger sets the current logger. -func SetLogger(l Logger) { - logger = l -} - -// GetLogger returns the current logger. -func GetLogger() Logger { - return logger -} - -// LogModel logs the model information. -func LogModel(model [][]string) { - logger.LogModel(model) -} - -// LogEnforce logs the enforcer information. -func LogEnforce(matcher string, request []interface{}, result bool, explains [][]string) { - logger.LogEnforce(matcher, request, result, explains) -} - -// LogRole log info related to role. -func LogRole(roles []string) { - logger.LogRole(roles) -} - -// LogPolicy logs the policy information. -func LogPolicy(policy map[string][][]string) { - logger.LogPolicy(policy) -} - -// LogError logs the error information. -func LogError(err error, msg ...string) { - logger.LogError(err, msg...) -} diff --git a/vendor/github.com/casbin/casbin/v2/log/logger.go b/vendor/github.com/casbin/casbin/v2/log/logger.go deleted file mode 100644 index 8982cae6..00000000 --- a/vendor/github.com/casbin/casbin/v2/log/logger.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2018 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 log - -//go:generate mockgen -destination=./mocks/mock_logger.go -package=mocks github.com/casbin/casbin/v2/log Logger - -// Logger is the logging interface implementation. -type Logger interface { - // EnableLog controls whether print the message. - EnableLog(bool) - - // IsEnabled returns if logger is enabled. - IsEnabled() bool - - // LogModel log info related to model. - LogModel(model [][]string) - - // LogEnforce log info related to enforce. - LogEnforce(matcher string, request []interface{}, result bool, explains [][]string) - - // LogRole log info related to role. - LogRole(roles []string) - - // LogPolicy log info related to policy. - LogPolicy(policy map[string][][]string) - - // LogError log info relate to error - LogError(err error, msg ...string) -} diff --git a/vendor/github.com/casbin/casbin/v2/management_api.go b/vendor/github.com/casbin/casbin/v2/management_api.go deleted file mode 100644 index 6641f834..00000000 --- a/vendor/github.com/casbin/casbin/v2/management_api.go +++ /dev/null @@ -1,500 +0,0 @@ -// 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/casbin/casbin/v2/constant" - "github.com/casbin/casbin/v2/util" - "github.com/casbin/govaluate" -) - -// GetAllSubjects gets the list of subjects that show up in the current policy. -func (e *Enforcer) GetAllSubjects() ([]string, error) { - return e.model.GetValuesForFieldInPolicyAllTypesByName("p", constant.SubjectIndex) -} - -// GetAllNamedSubjects gets the list of subjects that show up in the current named policy. -func (e *Enforcer) GetAllNamedSubjects(ptype string) ([]string, error) { - fieldIndex, err := e.model.GetFieldIndex(ptype, constant.SubjectIndex) - if err != nil { - return nil, err - } - return e.model.GetValuesForFieldInPolicy("p", ptype, fieldIndex) -} - -// GetAllObjects gets the list of objects that show up in the current policy. -func (e *Enforcer) GetAllObjects() ([]string, error) { - return e.model.GetValuesForFieldInPolicyAllTypesByName("p", constant.ObjectIndex) -} - -// GetAllNamedObjects gets the list of objects that show up in the current named policy. -func (e *Enforcer) GetAllNamedObjects(ptype string) ([]string, error) { - fieldIndex, err := e.model.GetFieldIndex(ptype, constant.ObjectIndex) - if err != nil { - return nil, err - } - return e.model.GetValuesForFieldInPolicy("p", ptype, fieldIndex) -} - -// GetAllActions gets the list of actions that show up in the current policy. -func (e *Enforcer) GetAllActions() ([]string, error) { - return e.model.GetValuesForFieldInPolicyAllTypesByName("p", constant.ActionIndex) -} - -// GetAllNamedActions gets the list of actions that show up in the current named policy. -func (e *Enforcer) GetAllNamedActions(ptype string) ([]string, error) { - fieldIndex, err := e.model.GetFieldIndex(ptype, constant.ActionIndex) - if err != nil { - return nil, err - } - return e.model.GetValuesForFieldInPolicy("p", ptype, fieldIndex) -} - -// GetAllRoles gets the list of roles that show up in the current policy. -func (e *Enforcer) GetAllRoles() ([]string, error) { - return e.model.GetValuesForFieldInPolicyAllTypes("g", 1) -} - -// GetAllNamedRoles gets the list of roles that show up in the current named policy. -func (e *Enforcer) GetAllNamedRoles(ptype string) ([]string, error) { - return e.model.GetValuesForFieldInPolicy("g", ptype, 1) -} - -// GetPolicy gets all the authorization rules in the policy. -func (e *Enforcer) GetPolicy() ([][]string, error) { - return e.GetNamedPolicy("p") -} - -// GetFilteredPolicy gets all the authorization rules in the policy, field filters can be specified. -func (e *Enforcer) GetFilteredPolicy(fieldIndex int, fieldValues ...string) ([][]string, error) { - return e.GetFilteredNamedPolicy("p", fieldIndex, fieldValues...) -} - -// GetNamedPolicy gets all the authorization rules in the named policy. -func (e *Enforcer) GetNamedPolicy(ptype string) ([][]string, error) { - return e.model.GetPolicy("p", ptype) -} - -// GetFilteredNamedPolicy gets all the authorization rules in the named policy, field filters can be specified. -func (e *Enforcer) GetFilteredNamedPolicy(ptype string, fieldIndex int, fieldValues ...string) ([][]string, error) { - return e.model.GetFilteredPolicy("p", ptype, fieldIndex, fieldValues...) -} - -// GetGroupingPolicy gets all the role inheritance rules in the policy. -func (e *Enforcer) GetGroupingPolicy() ([][]string, error) { - return e.GetNamedGroupingPolicy("g") -} - -// GetFilteredGroupingPolicy gets all the role inheritance rules in the policy, field filters can be specified. -func (e *Enforcer) GetFilteredGroupingPolicy(fieldIndex int, fieldValues ...string) ([][]string, error) { - return e.GetFilteredNamedGroupingPolicy("g", fieldIndex, fieldValues...) -} - -// GetNamedGroupingPolicy gets all the role inheritance rules in the policy. -func (e *Enforcer) GetNamedGroupingPolicy(ptype string) ([][]string, error) { - return e.model.GetPolicy("g", ptype) -} - -// GetFilteredNamedGroupingPolicy gets all the role inheritance rules in the policy, field filters can be specified. -func (e *Enforcer) GetFilteredNamedGroupingPolicy(ptype string, fieldIndex int, fieldValues ...string) ([][]string, error) { - return e.model.GetFilteredPolicy("g", ptype, fieldIndex, fieldValues...) -} - -// GetFilteredNamedPolicyWithMatcher gets rules based on matcher from the policy. -func (e *Enforcer) GetFilteredNamedPolicyWithMatcher(ptype string, matcher string) ([][]string, error) { - var res [][]string - var err error - - functions := e.fm.GetFunctions() - if _, ok := e.model["g"]; ok { - for key, ast := range e.model["g"] { - // g must be a normal role definition (ast.RM != nil) - // or a conditional role definition (ast.CondRM != nil) - // ast.RM and ast.CondRM shouldn't be nil at the same time - if ast.RM != nil { - functions[key] = util.GenerateGFunction(ast.RM) - } - if ast.CondRM != nil { - functions[key] = util.GenerateConditionalGFunction(ast.CondRM) - } - } - } - - var expString string - if matcher == "" { - return res, fmt.Errorf("matcher is empty") - } else { - expString = util.RemoveComments(util.EscapeAssertion(matcher)) - } - - var expression *govaluate.EvaluableExpression - - expression, err = govaluate.NewEvaluableExpressionWithFunctions(expString, functions) - if err != nil { - return res, err - } - - pTokens := make(map[string]int, len(e.model["p"][ptype].Tokens)) - for i, token := range e.model["p"][ptype].Tokens { - pTokens[token] = i - } - - parameters := enforceParameters{ - pTokens: pTokens, - } - - if policyLen := len(e.model["p"][ptype].Policy); policyLen != 0 && strings.Contains(expString, ptype+"_") { - for _, pvals := range e.model["p"][ptype].Policy { - if len(e.model["p"][ptype].Tokens) != len(pvals) { - return res, fmt.Errorf( - "invalid policy size: expected %d, got %d, pvals: %v", - len(e.model["p"][ptype].Tokens), - len(pvals), - pvals) - } - - parameters.pVals = pvals - - result, err := expression.Eval(parameters) - - if err != nil { - return res, err - } - - switch result := result.(type) { - case bool: - if result { - res = append(res, pvals) - } - case float64: - if result != 0 { - res = append(res, pvals) - } - default: - return res, errors.New("matcher result should be bool, int or float") - } - } - } - return res, nil -} - -// HasPolicy determines whether an authorization rule exists. -func (e *Enforcer) HasPolicy(params ...interface{}) (bool, error) { - return e.HasNamedPolicy("p", params...) -} - -// HasNamedPolicy determines whether a named authorization rule exists. -func (e *Enforcer) HasNamedPolicy(ptype string, params ...interface{}) (bool, error) { - if strSlice, ok := params[0].([]string); len(params) == 1 && ok { - return e.model.HasPolicy("p", ptype, strSlice) - } - - policy := make([]string, 0) - for _, param := range params { - policy = append(policy, param.(string)) - } - - return e.model.HasPolicy("p", ptype, policy) -} - -// 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 (e *Enforcer) AddPolicy(params ...interface{}) (bool, error) { - return e.AddNamedPolicy("p", params...) -} - -// AddPolicies adds authorization rules to the current policy. -// If the rule already exists, the function returns false for the corresponding rule and the rule will not be added. -// Otherwise the function returns true for the corresponding rule by adding the new rule. -func (e *Enforcer) AddPolicies(rules [][]string) (bool, error) { - return e.AddNamedPolicies("p", rules) -} - -// AddPoliciesEx adds authorization rules to the current policy. -// If the rule already exists, the rule will not be added. -// But unlike AddPolicies, other non-existent rules are added instead of returning false directly. -func (e *Enforcer) AddPoliciesEx(rules [][]string) (bool, error) { - return e.AddNamedPoliciesEx("p", rules) -} - -// AddNamedPolicy adds an authorization rule to the current named 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 (e *Enforcer) AddNamedPolicy(ptype string, params ...interface{}) (bool, error) { - if strSlice, ok := params[0].([]string); len(params) == 1 && ok { - strSlice = append(make([]string, 0, len(strSlice)), strSlice...) - return e.addPolicy("p", ptype, strSlice) - } - policy := make([]string, 0) - for _, param := range params { - policy = append(policy, param.(string)) - } - - return e.addPolicy("p", ptype, policy) -} - -// AddNamedPolicies adds authorization rules to the current named policy. -// If the rule already exists, the function returns false for the corresponding rule and the rule will not be added. -// Otherwise the function returns true for the corresponding by adding the new rule. -func (e *Enforcer) AddNamedPolicies(ptype string, rules [][]string) (bool, error) { - return e.addPolicies("p", ptype, rules, false) -} - -// AddNamedPoliciesEx adds authorization rules to the current named policy. -// If the rule already exists, the rule will not be added. -// But unlike AddNamedPolicies, other non-existent rules are added instead of returning false directly. -func (e *Enforcer) AddNamedPoliciesEx(ptype string, rules [][]string) (bool, error) { - return e.addPolicies("p", ptype, rules, true) -} - -// RemovePolicy removes an authorization rule from the current policy. -func (e *Enforcer) RemovePolicy(params ...interface{}) (bool, error) { - return e.RemoveNamedPolicy("p", params...) -} - -// UpdatePolicy updates an authorization rule from the current policy. -func (e *Enforcer) UpdatePolicy(oldPolicy []string, newPolicy []string) (bool, error) { - return e.UpdateNamedPolicy("p", oldPolicy, newPolicy) -} - -func (e *Enforcer) UpdateNamedPolicy(ptype string, p1 []string, p2 []string) (bool, error) { - return e.updatePolicy("p", ptype, p1, p2) -} - -// UpdatePolicies updates authorization rules from the current policies. -func (e *Enforcer) UpdatePolicies(oldPolices [][]string, newPolicies [][]string) (bool, error) { - return e.UpdateNamedPolicies("p", oldPolices, newPolicies) -} - -func (e *Enforcer) UpdateNamedPolicies(ptype string, p1 [][]string, p2 [][]string) (bool, error) { - return e.updatePolicies("p", ptype, p1, p2) -} - -func (e *Enforcer) UpdateFilteredPolicies(newPolicies [][]string, fieldIndex int, fieldValues ...string) (bool, error) { - return e.UpdateFilteredNamedPolicies("p", newPolicies, fieldIndex, fieldValues...) -} - -func (e *Enforcer) UpdateFilteredNamedPolicies(ptype string, newPolicies [][]string, fieldIndex int, fieldValues ...string) (bool, error) { - return e.updateFilteredPolicies("p", ptype, newPolicies, fieldIndex, fieldValues...) -} - -// RemovePolicies removes authorization rules from the current policy. -func (e *Enforcer) RemovePolicies(rules [][]string) (bool, error) { - return e.RemoveNamedPolicies("p", rules) -} - -// RemoveFilteredPolicy removes an authorization rule from the current policy, field filters can be specified. -func (e *Enforcer) RemoveFilteredPolicy(fieldIndex int, fieldValues ...string) (bool, error) { - return e.RemoveFilteredNamedPolicy("p", fieldIndex, fieldValues...) -} - -// RemoveNamedPolicy removes an authorization rule from the current named policy. -func (e *Enforcer) RemoveNamedPolicy(ptype string, params ...interface{}) (bool, error) { - if strSlice, ok := params[0].([]string); len(params) == 1 && ok { - return e.removePolicy("p", ptype, strSlice) - } - policy := make([]string, 0) - for _, param := range params { - policy = append(policy, param.(string)) - } - - return e.removePolicy("p", ptype, policy) -} - -// RemoveNamedPolicies removes authorization rules from the current named policy. -func (e *Enforcer) RemoveNamedPolicies(ptype string, rules [][]string) (bool, error) { - return e.removePolicies("p", ptype, rules) -} - -// RemoveFilteredNamedPolicy removes an authorization rule from the current named policy, field filters can be specified. -func (e *Enforcer) RemoveFilteredNamedPolicy(ptype string, fieldIndex int, fieldValues ...string) (bool, error) { - return e.removeFilteredPolicy("p", ptype, fieldIndex, fieldValues) -} - -// HasGroupingPolicy determines whether a role inheritance rule exists. -func (e *Enforcer) HasGroupingPolicy(params ...interface{}) (bool, error) { - return e.HasNamedGroupingPolicy("g", params...) -} - -// HasNamedGroupingPolicy determines whether a named role inheritance rule exists. -func (e *Enforcer) HasNamedGroupingPolicy(ptype string, params ...interface{}) (bool, error) { - if strSlice, ok := params[0].([]string); len(params) == 1 && ok { - return e.model.HasPolicy("g", ptype, strSlice) - } - - policy := make([]string, 0) - for _, param := range params { - policy = append(policy, param.(string)) - } - - return e.model.HasPolicy("g", ptype, policy) -} - -// AddGroupingPolicy adds a role inheritance 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 (e *Enforcer) AddGroupingPolicy(params ...interface{}) (bool, error) { - return e.AddNamedGroupingPolicy("g", params...) -} - -// AddGroupingPolicies adds role inheritance rules to the current policy. -// If the rule already exists, the function returns false for the corresponding policy rule and the rule will not be added. -// Otherwise the function returns true for the corresponding policy rule by adding the new rule. -func (e *Enforcer) AddGroupingPolicies(rules [][]string) (bool, error) { - return e.AddNamedGroupingPolicies("g", rules) -} - -// AddGroupingPoliciesEx adds role inheritance rules to the current policy. -// If the rule already exists, the rule will not be added. -// But unlike AddGroupingPolicies, other non-existent rules are added instead of returning false directly. -func (e *Enforcer) AddGroupingPoliciesEx(rules [][]string) (bool, error) { - return e.AddNamedGroupingPoliciesEx("g", rules) -} - -// AddNamedGroupingPolicy adds a named role inheritance 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 (e *Enforcer) AddNamedGroupingPolicy(ptype string, params ...interface{}) (bool, error) { - var ruleAdded bool - var err error - if strSlice, ok := params[0].([]string); len(params) == 1 && ok { - ruleAdded, err = e.addPolicy("g", ptype, strSlice) - } else { - policy := make([]string, 0) - for _, param := range params { - policy = append(policy, param.(string)) - } - - ruleAdded, err = e.addPolicy("g", ptype, policy) - } - - return ruleAdded, err -} - -// AddNamedGroupingPolicies adds named role inheritance rules to the current policy. -// If the rule already exists, the function returns false for the corresponding policy rule and the rule will not be added. -// Otherwise the function returns true for the corresponding policy rule by adding the new rule. -func (e *Enforcer) AddNamedGroupingPolicies(ptype string, rules [][]string) (bool, error) { - return e.addPolicies("g", ptype, rules, false) -} - -// AddNamedGroupingPoliciesEx adds named role inheritance rules to the current policy. -// If the rule already exists, the rule will not be added. -// But unlike AddNamedGroupingPolicies, other non-existent rules are added instead of returning false directly. -func (e *Enforcer) AddNamedGroupingPoliciesEx(ptype string, rules [][]string) (bool, error) { - return e.addPolicies("g", ptype, rules, true) -} - -// RemoveGroupingPolicy removes a role inheritance rule from the current policy. -func (e *Enforcer) RemoveGroupingPolicy(params ...interface{}) (bool, error) { - return e.RemoveNamedGroupingPolicy("g", params...) -} - -// RemoveGroupingPolicies removes role inheritance rules from the current policy. -func (e *Enforcer) RemoveGroupingPolicies(rules [][]string) (bool, error) { - return e.RemoveNamedGroupingPolicies("g", rules) -} - -// RemoveFilteredGroupingPolicy removes a role inheritance rule from the current policy, field filters can be specified. -func (e *Enforcer) RemoveFilteredGroupingPolicy(fieldIndex int, fieldValues ...string) (bool, error) { - return e.RemoveFilteredNamedGroupingPolicy("g", fieldIndex, fieldValues...) -} - -// RemoveNamedGroupingPolicy removes a role inheritance rule from the current named policy. -func (e *Enforcer) RemoveNamedGroupingPolicy(ptype string, params ...interface{}) (bool, error) { - var ruleRemoved bool - var err error - if strSlice, ok := params[0].([]string); len(params) == 1 && ok { - ruleRemoved, err = e.removePolicy("g", ptype, strSlice) - } else { - policy := make([]string, 0) - for _, param := range params { - policy = append(policy, param.(string)) - } - - ruleRemoved, err = e.removePolicy("g", ptype, policy) - } - - return ruleRemoved, err -} - -// RemoveNamedGroupingPolicies removes role inheritance rules from the current named policy. -func (e *Enforcer) RemoveNamedGroupingPolicies(ptype string, rules [][]string) (bool, error) { - return e.removePolicies("g", ptype, rules) -} - -func (e *Enforcer) UpdateGroupingPolicy(oldRule []string, newRule []string) (bool, error) { - return e.UpdateNamedGroupingPolicy("g", oldRule, newRule) -} - -// UpdateGroupingPolicies updates authorization rules from the current policies. -func (e *Enforcer) UpdateGroupingPolicies(oldRules [][]string, newRules [][]string) (bool, error) { - return e.UpdateNamedGroupingPolicies("g", oldRules, newRules) -} - -func (e *Enforcer) UpdateNamedGroupingPolicy(ptype string, oldRule []string, newRule []string) (bool, error) { - return e.updatePolicy("g", ptype, oldRule, newRule) -} - -func (e *Enforcer) UpdateNamedGroupingPolicies(ptype string, oldRules [][]string, newRules [][]string) (bool, error) { - return e.updatePolicies("g", ptype, oldRules, newRules) -} - -// RemoveFilteredNamedGroupingPolicy removes a role inheritance rule from the current named policy, field filters can be specified. -func (e *Enforcer) RemoveFilteredNamedGroupingPolicy(ptype string, fieldIndex int, fieldValues ...string) (bool, error) { - return e.removeFilteredPolicy("g", ptype, fieldIndex, fieldValues) -} - -// AddFunction adds a customized function. -func (e *Enforcer) AddFunction(name string, function govaluate.ExpressionFunction) { - e.fm.AddFunction(name, function) -} - -func (e *Enforcer) SelfAddPolicy(sec string, ptype string, rule []string) (bool, error) { - return e.addPolicyWithoutNotify(sec, ptype, rule) -} - -func (e *Enforcer) SelfAddPolicies(sec string, ptype string, rules [][]string) (bool, error) { - return e.addPoliciesWithoutNotify(sec, ptype, rules, false) -} - -func (e *Enforcer) SelfAddPoliciesEx(sec string, ptype string, rules [][]string) (bool, error) { - return e.addPoliciesWithoutNotify(sec, ptype, rules, true) -} - -func (e *Enforcer) SelfRemovePolicy(sec string, ptype string, rule []string) (bool, error) { - return e.removePolicyWithoutNotify(sec, ptype, rule) -} - -func (e *Enforcer) SelfRemovePolicies(sec string, ptype string, rules [][]string) (bool, error) { - return e.removePoliciesWithoutNotify(sec, ptype, rules) -} - -func (e *Enforcer) SelfRemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) (bool, error) { - return e.removeFilteredPolicyWithoutNotify(sec, ptype, fieldIndex, fieldValues) -} - -func (e *Enforcer) SelfUpdatePolicy(sec string, ptype string, oldRule, newRule []string) (bool, error) { - return e.updatePolicyWithoutNotify(sec, ptype, oldRule, newRule) -} - -func (e *Enforcer) SelfUpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) (bool, error) { - return e.updatePoliciesWithoutNotify(sec, ptype, oldRules, newRules) -} diff --git a/vendor/github.com/casbin/casbin/v2/model/assertion.go b/vendor/github.com/casbin/casbin/v2/model/assertion.go deleted file mode 100644 index 7c5381d7..00000000 --- a/vendor/github.com/casbin/casbin/v2/model/assertion.go +++ /dev/null @@ -1,194 +0,0 @@ -// 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 model - -import ( - "errors" - "strings" - - "github.com/casbin/casbin/v2/log" - "github.com/casbin/casbin/v2/rbac" -) - -// Assertion represents an expression in a section of the model. -// For example: r = sub, obj, act. -type Assertion struct { - Key string - Value string - Tokens []string - ParamsTokens []string - Policy [][]string - PolicyMap map[string]int - RM rbac.RoleManager - CondRM rbac.ConditionalRoleManager - FieldIndexMap map[string]int - - logger log.Logger -} - -func (ast *Assertion) buildIncrementalRoleLinks(rm rbac.RoleManager, op PolicyOp, rules [][]string) error { - ast.RM = rm - count := strings.Count(ast.Value, "_") - if count < 2 { - return errors.New("the number of \"_\" in role definition should be at least 2") - } - - for _, rule := range rules { - if len(rule) < count { - return errors.New("grouping policy elements do not meet role definition") - } - if len(rule) > count { - rule = rule[:count] - } - switch op { - case PolicyAdd: - err := rm.AddLink(rule[0], rule[1], rule[2:]...) - if err != nil { - return err - } - case PolicyRemove: - err := rm.DeleteLink(rule[0], rule[1], rule[2:]...) - if err != nil { - return err - } - } - } - return nil -} - -func (ast *Assertion) buildRoleLinks(rm rbac.RoleManager) error { - ast.RM = rm - count := strings.Count(ast.Value, "_") - if count < 2 { - return errors.New("the number of \"_\" in role definition should be at least 2") - } - for _, rule := range ast.Policy { - if len(rule) < count { - return errors.New("grouping policy elements do not meet role definition") - } - if len(rule) > count { - rule = rule[:count] - } - err := ast.RM.AddLink(rule[0], rule[1], rule[2:]...) - if err != nil { - return err - } - } - - return nil -} - -func (ast *Assertion) buildIncrementalConditionalRoleLinks(condRM rbac.ConditionalRoleManager, op PolicyOp, rules [][]string) error { - ast.CondRM = condRM - count := strings.Count(ast.Value, "_") - if count < 2 { - return errors.New("the number of \"_\" in role definition should be at least 2") - } - - for _, rule := range rules { - if len(rule) < count { - return errors.New("grouping policy elements do not meet role definition") - } - if len(rule) > count { - rule = rule[:count] - } - - var err error - domainRule := rule[2:len(ast.Tokens)] - - switch op { - case PolicyAdd: - err = ast.addConditionalRoleLink(rule, domainRule) - case PolicyRemove: - err = ast.CondRM.DeleteLink(rule[0], rule[1], rule[2:]...) - } - if err != nil { - return err - } - } - - return nil -} - -func (ast *Assertion) buildConditionalRoleLinks(condRM rbac.ConditionalRoleManager) error { - ast.CondRM = condRM - count := strings.Count(ast.Value, "_") - if count < 2 { - return errors.New("the number of \"_\" in role definition should be at least 2") - } - for _, rule := range ast.Policy { - if len(rule) < count { - return errors.New("grouping policy elements do not meet role definition") - } - if len(rule) > count { - rule = rule[:count] - } - - domainRule := rule[2:len(ast.Tokens)] - - err := ast.addConditionalRoleLink(rule, domainRule) - if err != nil { - return err - } - } - - return nil -} - -// addConditionalRoleLink adds Link to rbac.ConditionalRoleManager and sets the parameters for LinkConditionFunc. -func (ast *Assertion) addConditionalRoleLink(rule []string, domainRule []string) error { - var err error - if len(domainRule) == 0 { - err = ast.CondRM.AddLink(rule[0], rule[1]) - if err == nil { - ast.CondRM.SetLinkConditionFuncParams(rule[0], rule[1], rule[len(ast.Tokens):]...) - } - } else { - domain := domainRule[0] - err = ast.CondRM.AddLink(rule[0], rule[1], domain) - if err == nil { - ast.CondRM.SetDomainLinkConditionFuncParams(rule[0], rule[1], domain, rule[len(ast.Tokens):]...) - } - } - return err -} - -func (ast *Assertion) setLogger(logger log.Logger) { - ast.logger = logger -} - -func (ast *Assertion) copy() *Assertion { - tokens := append([]string(nil), ast.Tokens...) - policy := make([][]string, len(ast.Policy)) - - for i, p := range ast.Policy { - policy[i] = append(policy[i], p...) - } - policyMap := make(map[string]int) - for k, v := range ast.PolicyMap { - policyMap[k] = v - } - - newAst := &Assertion{ - Key: ast.Key, - Value: ast.Value, - PolicyMap: policyMap, - Tokens: tokens, - Policy: policy, - FieldIndexMap: ast.FieldIndexMap, - } - - return newAst -} diff --git a/vendor/github.com/casbin/casbin/v2/model/function.go b/vendor/github.com/casbin/casbin/v2/model/function.go deleted file mode 100644 index f1a8d007..00000000 --- a/vendor/github.com/casbin/casbin/v2/model/function.go +++ /dev/null @@ -1,66 +0,0 @@ -// 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 model - -import ( - "sync" - - "github.com/casbin/casbin/v2/util" - "github.com/casbin/govaluate" -) - -// FunctionMap represents the collection of Function. -type FunctionMap struct { - fns *sync.Map -} - -// [string]govaluate.ExpressionFunction - -// AddFunction adds an expression function. -func (fm *FunctionMap) AddFunction(name string, function govaluate.ExpressionFunction) { - fm.fns.LoadOrStore(name, function) -} - -// LoadFunctionMap loads an initial function map. -func LoadFunctionMap() FunctionMap { - fm := &FunctionMap{} - fm.fns = &sync.Map{} - - fm.AddFunction("keyMatch", util.KeyMatchFunc) - fm.AddFunction("keyGet", util.KeyGetFunc) - fm.AddFunction("keyMatch2", util.KeyMatch2Func) - fm.AddFunction("keyGet2", util.KeyGet2Func) - fm.AddFunction("keyMatch3", util.KeyMatch3Func) - fm.AddFunction("keyGet3", util.KeyGet3Func) - fm.AddFunction("keyMatch4", util.KeyMatch4Func) - fm.AddFunction("keyMatch5", util.KeyMatch5Func) - fm.AddFunction("regexMatch", util.RegexMatchFunc) - fm.AddFunction("ipMatch", util.IPMatchFunc) - fm.AddFunction("globMatch", util.GlobMatchFunc) - - return *fm -} - -// GetFunctions return a map with all the functions. -func (fm *FunctionMap) GetFunctions() map[string]govaluate.ExpressionFunction { - ret := make(map[string]govaluate.ExpressionFunction) - - fm.fns.Range(func(k interface{}, v interface{}) bool { - ret[k.(string)] = v.(govaluate.ExpressionFunction) - return true - }) - - return ret -} diff --git a/vendor/github.com/casbin/casbin/v2/model/model.go b/vendor/github.com/casbin/casbin/v2/model/model.go deleted file mode 100644 index 938072f4..00000000 --- a/vendor/github.com/casbin/casbin/v2/model/model.go +++ /dev/null @@ -1,434 +0,0 @@ -// 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 model - -import ( - "container/list" - "errors" - "fmt" - "regexp" - "sort" - "strconv" - "strings" - - "github.com/casbin/casbin/v2/config" - "github.com/casbin/casbin/v2/constant" - "github.com/casbin/casbin/v2/log" - "github.com/casbin/casbin/v2/util" -) - -// Model represents the whole access control model. -type Model map[string]AssertionMap - -// AssertionMap is the collection of assertions, can be "r", "p", "g", "e", "m". -type AssertionMap map[string]*Assertion - -const defaultDomain string = "" -const defaultSeparator = "::" - -var sectionNameMap = map[string]string{ - "r": "request_definition", - "p": "policy_definition", - "g": "role_definition", - "e": "policy_effect", - "m": "matchers", -} - -// Minimal required sections for a model to be valid. -var requiredSections = []string{"r", "p", "e", "m"} - -func loadAssertion(model Model, cfg config.ConfigInterface, sec string, key string) bool { - value := cfg.String(sectionNameMap[sec] + "::" + key) - return model.AddDef(sec, key, value) -} - -var paramsRegex = regexp.MustCompile(`\((.*?)\)`) - -// getParamsToken Get ParamsToken from Assertion.Value. -func getParamsToken(value string) []string { - paramsString := paramsRegex.FindString(value) - if paramsString == "" { - return nil - } - paramsString = strings.TrimSuffix(strings.TrimPrefix(paramsString, "("), ")") - return strings.Split(paramsString, ",") -} - -// AddDef adds an assertion to the model. -func (model Model) AddDef(sec string, key string, value string) bool { - if value == "" { - return false - } - - ast := Assertion{} - ast.Key = key - ast.Value = value - ast.PolicyMap = make(map[string]int) - ast.FieldIndexMap = make(map[string]int) - ast.setLogger(model.GetLogger()) - - if sec == "r" || sec == "p" { - ast.Tokens = strings.Split(ast.Value, ",") - for i := range ast.Tokens { - ast.Tokens[i] = key + "_" + strings.TrimSpace(ast.Tokens[i]) - } - } else if sec == "g" { - ast.ParamsTokens = getParamsToken(ast.Value) - ast.Tokens = strings.Split(ast.Value, ",") - ast.Tokens = ast.Tokens[:len(ast.Tokens)-len(ast.ParamsTokens)] - } else { - ast.Value = util.RemoveComments(util.EscapeAssertion(ast.Value)) - } - - if sec == "m" && strings.Contains(ast.Value, "in") { - ast.Value = strings.Replace(strings.Replace(ast.Value, "[", "(", -1), "]", ")", -1) - } - - _, ok := model[sec] - if !ok { - model[sec] = make(AssertionMap) - } - - model[sec][key] = &ast - return true -} - -func getKeySuffix(i int) string { - if i == 1 { - return "" - } - - return strconv.Itoa(i) -} - -func loadSection(model Model, cfg config.ConfigInterface, sec string) { - i := 1 - for { - if !loadAssertion(model, cfg, sec, sec+getKeySuffix(i)) { - break - } else { - i++ - } - } -} - -// SetLogger sets the model's logger. -func (model Model) SetLogger(logger log.Logger) { - for _, astMap := range model { - for _, ast := range astMap { - ast.logger = logger - } - } - model["logger"] = AssertionMap{"logger": &Assertion{logger: logger}} -} - -// GetLogger returns the model's logger. -func (model Model) GetLogger() log.Logger { - return model["logger"]["logger"].logger -} - -// NewModel creates an empty model. -func NewModel() Model { - m := make(Model) - m.SetLogger(&log.DefaultLogger{}) - - return m -} - -// NewModelFromFile creates a model from a .CONF file. -func NewModelFromFile(path string) (Model, error) { - m := NewModel() - - err := m.LoadModel(path) - if err != nil { - return nil, err - } - - return m, nil -} - -// NewModelFromString creates a model from a string which contains model text. -func NewModelFromString(text string) (Model, error) { - m := NewModel() - - err := m.LoadModelFromText(text) - if err != nil { - return nil, err - } - - return m, nil -} - -// LoadModel loads the model from model CONF file. -func (model Model) LoadModel(path string) error { - cfg, err := config.NewConfig(path) - if err != nil { - return err - } - - return model.loadModelFromConfig(cfg) -} - -// LoadModelFromText loads the model from the text. -func (model Model) LoadModelFromText(text string) error { - cfg, err := config.NewConfigFromText(text) - if err != nil { - return err - } - - return model.loadModelFromConfig(cfg) -} - -func (model Model) loadModelFromConfig(cfg config.ConfigInterface) error { - for s := range sectionNameMap { - loadSection(model, cfg, s) - } - ms := make([]string, 0) - for _, rs := range requiredSections { - if !model.hasSection(rs) { - ms = append(ms, sectionNameMap[rs]) - } - } - if len(ms) > 0 { - return fmt.Errorf("missing required sections: %s", strings.Join(ms, ",")) - } - return nil -} - -func (model Model) hasSection(sec string) bool { - section := model[sec] - return section != nil -} - -func (model Model) GetAssertion(sec string, ptype string) (*Assertion, error) { - if model[sec] == nil { - return nil, fmt.Errorf("missing required section %s", sec) - } - if model[sec][ptype] == nil { - return nil, fmt.Errorf("missiong required definition %s in section %s", ptype, sec) - } - return model[sec][ptype], nil -} - -// PrintModel prints the model to the log. -func (model Model) PrintModel() { - if !model.GetLogger().IsEnabled() { - return - } - - var modelInfo [][]string - for k, v := range model { - if k == "logger" { - continue - } - - for i, j := range v { - modelInfo = append(modelInfo, []string{k, i, j.Value}) - } - } - - model.GetLogger().LogModel(modelInfo) -} - -func (model Model) SortPoliciesBySubjectHierarchy() error { - if model["e"]["e"].Value != constant.SubjectPriorityEffect { - return nil - } - g, err := model.GetAssertion("g", "g") - if err != nil { - return err - } - subIndex := 0 - for ptype, assertion := range model["p"] { - domainIndex, err := model.GetFieldIndex(ptype, constant.DomainIndex) - if err != nil { - domainIndex = -1 - } - policies := assertion.Policy - subjectHierarchyMap, err := getSubjectHierarchyMap(g.Policy) - if err != nil { - return err - } - sort.SliceStable(policies, func(i, j int) bool { - domain1, domain2 := defaultDomain, defaultDomain - if domainIndex != -1 { - domain1 = policies[i][domainIndex] - domain2 = policies[j][domainIndex] - } - name1, name2 := getNameWithDomain(domain1, policies[i][subIndex]), getNameWithDomain(domain2, policies[j][subIndex]) - p1 := subjectHierarchyMap[name1] - p2 := subjectHierarchyMap[name2] - return p1 > p2 - }) - for i, policy := range assertion.Policy { - assertion.PolicyMap[strings.Join(policy, ",")] = i - } - } - return nil -} - -func getSubjectHierarchyMap(policies [][]string) (map[string]int, error) { - subjectHierarchyMap := make(map[string]int) - // Tree structure of role - policyMap := make(map[string][]string) - for _, policy := range policies { - if len(policy) < 2 { - return nil, errors.New("policy g expect 2 more params") - } - domain := defaultDomain - if len(policy) != 2 { - domain = policy[2] - } - child := getNameWithDomain(domain, policy[0]) - parent := getNameWithDomain(domain, policy[1]) - policyMap[parent] = append(policyMap[parent], child) - if _, ok := subjectHierarchyMap[child]; !ok { - subjectHierarchyMap[child] = 0 - } - if _, ok := subjectHierarchyMap[parent]; !ok { - subjectHierarchyMap[parent] = 0 - } - subjectHierarchyMap[child] = 1 - } - // Use queues for levelOrder - queue := list.New() - for k, v := range subjectHierarchyMap { - root := k - if v != 0 { - continue - } - lv := 0 - queue.PushBack(root) - for queue.Len() != 0 { - sz := queue.Len() - for i := 0; i < sz; i++ { - node := queue.Front() - queue.Remove(node) - nodeValue := node.Value.(string) - subjectHierarchyMap[nodeValue] = lv - if _, ok := policyMap[nodeValue]; ok { - for _, child := range policyMap[nodeValue] { - queue.PushBack(child) - } - } - } - lv++ - } - } - return subjectHierarchyMap, nil -} - -func getNameWithDomain(domain string, name string) string { - return domain + defaultSeparator + name -} - -func (model Model) SortPoliciesByPriority() error { - for ptype, assertion := range model["p"] { - priorityIndex, err := model.GetFieldIndex(ptype, constant.PriorityIndex) - if err != nil { - continue - } - policies := assertion.Policy - sort.SliceStable(policies, func(i, j int) bool { - p1, err := strconv.Atoi(policies[i][priorityIndex]) - if err != nil { - return true - } - p2, err := strconv.Atoi(policies[j][priorityIndex]) - if err != nil { - return true - } - return p1 < p2 - }) - for i, policy := range assertion.Policy { - assertion.PolicyMap[strings.Join(policy, ",")] = i - } - } - return nil -} - -func (model Model) ToText() string { - tokenPatterns := make(map[string]string) - - pPattern, rPattern := regexp.MustCompile("^p_"), regexp.MustCompile("^r_") - for _, ptype := range []string{"r", "p"} { - for _, token := range model[ptype][ptype].Tokens { - tokenPatterns[token] = rPattern.ReplaceAllString(pPattern.ReplaceAllString(token, "p."), "r.") - } - } - if strings.Contains(model["e"]["e"].Value, "p_eft") { - tokenPatterns["p_eft"] = "p.eft" - } - s := strings.Builder{} - writeString := func(sec string) { - for ptype := range model[sec] { - value := model[sec][ptype].Value - for tokenPattern, newToken := range tokenPatterns { - value = strings.Replace(value, tokenPattern, newToken, -1) - } - s.WriteString(fmt.Sprintf("%s = %s\n", sec, value)) - } - } - s.WriteString("[request_definition]\n") - writeString("r") - s.WriteString("[policy_definition]\n") - writeString("p") - if _, ok := model["g"]; ok { - s.WriteString("[role_definition]\n") - for ptype := range model["g"] { - s.WriteString(fmt.Sprintf("%s = %s\n", ptype, model["g"][ptype].Value)) - } - } - s.WriteString("[policy_effect]\n") - writeString("e") - s.WriteString("[matchers]\n") - writeString("m") - return s.String() -} - -func (model Model) Copy() Model { - newModel := NewModel() - - for sec, m := range model { - newAstMap := make(AssertionMap) - for ptype, ast := range m { - newAstMap[ptype] = ast.copy() - } - newModel[sec] = newAstMap - } - - newModel.SetLogger(model.GetLogger()) - return newModel -} - -func (model Model) GetFieldIndex(ptype string, field string) (int, error) { - assertion := model["p"][ptype] - if index, ok := assertion.FieldIndexMap[field]; ok { - return index, nil - } - pattern := fmt.Sprintf("%s_"+field, ptype) - index := -1 - for i, token := range assertion.Tokens { - if token == pattern { - index = i - break - } - } - if index == -1 { - return index, fmt.Errorf(field + " index is not set, please use enforcer.SetFieldIndex() to set index") - } - assertion.FieldIndexMap[field] = index - return index, nil -} diff --git a/vendor/github.com/casbin/casbin/v2/model/policy.go b/vendor/github.com/casbin/casbin/v2/model/policy.go deleted file mode 100644 index 875da090..00000000 --- a/vendor/github.com/casbin/casbin/v2/model/policy.go +++ /dev/null @@ -1,482 +0,0 @@ -// 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 model - -import ( - "fmt" - "strconv" - "strings" - - "github.com/casbin/casbin/v2/constant" - "github.com/casbin/casbin/v2/rbac" - "github.com/casbin/casbin/v2/util" -) - -type ( - PolicyOp int -) - -const ( - PolicyAdd PolicyOp = iota - PolicyRemove -) - -const DefaultSep = "," - -// BuildIncrementalRoleLinks provides incremental build the role inheritance relations. -func (model Model) BuildIncrementalRoleLinks(rmMap map[string]rbac.RoleManager, op PolicyOp, sec string, ptype string, rules [][]string) error { - if sec == "g" && rmMap[ptype] != nil { - _, err := model.GetAssertion(sec, ptype) - if err != nil { - return err - } - return model[sec][ptype].buildIncrementalRoleLinks(rmMap[ptype], op, rules) - } - return nil -} - -// BuildRoleLinks initializes the roles in RBAC. -func (model Model) BuildRoleLinks(rmMap map[string]rbac.RoleManager) error { - model.PrintPolicy() - for ptype, ast := range model["g"] { - if rm := rmMap[ptype]; rm != nil { - err := ast.buildRoleLinks(rm) - if err != nil { - return err - } - } - } - - return nil -} - -// BuildIncrementalConditionalRoleLinks provides incremental build the role inheritance relations. -func (model Model) BuildIncrementalConditionalRoleLinks(condRmMap map[string]rbac.ConditionalRoleManager, op PolicyOp, sec string, ptype string, rules [][]string) error { - if sec == "g" && condRmMap[ptype] != nil { - _, err := model.GetAssertion(sec, ptype) - if err != nil { - return err - } - return model[sec][ptype].buildIncrementalConditionalRoleLinks(condRmMap[ptype], op, rules) - } - return nil -} - -// BuildConditionalRoleLinks initializes the roles in RBAC. -func (model Model) BuildConditionalRoleLinks(condRmMap map[string]rbac.ConditionalRoleManager) error { - model.PrintPolicy() - for ptype, ast := range model["g"] { - if condRm := condRmMap[ptype]; condRm != nil { - err := ast.buildConditionalRoleLinks(condRm) - if err != nil { - return err - } - } - } - - return nil -} - -// PrintPolicy prints the policy to log. -func (model Model) PrintPolicy() { - if !model.GetLogger().IsEnabled() { - return - } - - policy := make(map[string][][]string) - - for key, ast := range model["p"] { - value, found := policy[key] - if found { - value = append(value, ast.Policy...) - policy[key] = value - } else { - policy[key] = ast.Policy - } - } - - for key, ast := range model["g"] { - value, found := policy[key] - if found { - value = append(value, ast.Policy...) - policy[key] = value - } else { - policy[key] = ast.Policy - } - } - - model.GetLogger().LogPolicy(policy) -} - -// ClearPolicy clears all current policy. -func (model Model) ClearPolicy() { - for _, ast := range model["p"] { - ast.Policy = nil - ast.PolicyMap = map[string]int{} - } - - for _, ast := range model["g"] { - ast.Policy = nil - ast.PolicyMap = map[string]int{} - } -} - -// GetPolicy gets all rules in a policy. -func (model Model) GetPolicy(sec string, ptype string) ([][]string, error) { - _, err := model.GetAssertion(sec, ptype) - if err != nil { - return nil, err - } - return model[sec][ptype].Policy, nil -} - -// GetFilteredPolicy gets rules based on field filters from a policy. -func (model Model) GetFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) ([][]string, error) { - _, err := model.GetAssertion(sec, ptype) - if err != nil { - return nil, err - } - res := [][]string{} - - for _, rule := range model[sec][ptype].Policy { - matched := true - for i, fieldValue := range fieldValues { - if fieldValue != "" && rule[fieldIndex+i] != fieldValue { - matched = false - break - } - } - - if matched { - res = append(res, rule) - } - } - - return res, nil -} - -// HasPolicyEx determines whether a model has the specified policy rule with error. -func (model Model) HasPolicyEx(sec string, ptype string, rule []string) (bool, error) { - assertion, err := model.GetAssertion(sec, ptype) - if err != nil { - return false, err - } - switch sec { - case "p": - if len(rule) != len(assertion.Tokens) { - return false, fmt.Errorf( - "invalid policy rule size: expected %d, got %d, rule: %v", - len(model["p"][ptype].Tokens), - len(rule), - rule) - } - case "g": - if len(rule) < len(assertion.Tokens) { - return false, fmt.Errorf( - "invalid policy rule size: expected %d, got %d, rule: %v", - len(model["g"][ptype].Tokens), - len(rule), - rule) - } - } - return model.HasPolicy(sec, ptype, rule) -} - -// HasPolicy determines whether a model has the specified policy rule. -func (model Model) HasPolicy(sec string, ptype string, rule []string) (bool, error) { - _, err := model.GetAssertion(sec, ptype) - if err != nil { - return false, err - } - _, ok := model[sec][ptype].PolicyMap[strings.Join(rule, DefaultSep)] - return ok, nil -} - -// HasPolicies determines whether a model has any of the specified policies. If one is found we return true. -func (model Model) HasPolicies(sec string, ptype string, rules [][]string) (bool, error) { - for i := 0; i < len(rules); i++ { - ok, err := model.HasPolicy(sec, ptype, rules[i]) - if err != nil { - return false, err - } - if ok { - return true, nil - } - } - - return false, nil -} - -// AddPolicy adds a policy rule to the model. -func (model Model) AddPolicy(sec string, ptype string, rule []string) error { - assertion, err := model.GetAssertion(sec, ptype) - if err != nil { - return err - } - assertion.Policy = append(assertion.Policy, rule) - assertion.PolicyMap[strings.Join(rule, DefaultSep)] = len(model[sec][ptype].Policy) - 1 - - hasPriority := false - if _, ok := assertion.FieldIndexMap[constant.PriorityIndex]; ok { - hasPriority = true - } - if sec == "p" && hasPriority { - if idxInsert, err := strconv.Atoi(rule[assertion.FieldIndexMap[constant.PriorityIndex]]); err == nil { - i := len(assertion.Policy) - 1 - for ; i > 0; i-- { - idx, err := strconv.Atoi(assertion.Policy[i-1][assertion.FieldIndexMap[constant.PriorityIndex]]) - if err != nil || idx <= idxInsert { - break - } - assertion.Policy[i] = assertion.Policy[i-1] - assertion.PolicyMap[strings.Join(assertion.Policy[i-1], DefaultSep)]++ - } - assertion.Policy[i] = rule - assertion.PolicyMap[strings.Join(rule, DefaultSep)] = i - } - } - return nil -} - -// AddPolicies adds policy rules to the model. -func (model Model) AddPolicies(sec string, ptype string, rules [][]string) error { - _, err := model.AddPoliciesWithAffected(sec, ptype, rules) - return err -} - -// AddPoliciesWithAffected adds policy rules to the model, and returns affected rules. -func (model Model) AddPoliciesWithAffected(sec string, ptype string, rules [][]string) ([][]string, error) { - _, err := model.GetAssertion(sec, ptype) - if err != nil { - return nil, err - } - var affected [][]string - for _, rule := range rules { - hashKey := strings.Join(rule, DefaultSep) - _, ok := model[sec][ptype].PolicyMap[hashKey] - if ok { - continue - } - affected = append(affected, rule) - err = model.AddPolicy(sec, ptype, rule) - if err != nil { - return affected, err - } - } - return affected, err -} - -// RemovePolicy removes a policy rule from the model. -// Deprecated: Using AddPoliciesWithAffected instead. -func (model Model) RemovePolicy(sec string, ptype string, rule []string) (bool, error) { - _, err := model.GetAssertion(sec, ptype) - if err != nil { - return false, err - } - index, ok := model[sec][ptype].PolicyMap[strings.Join(rule, DefaultSep)] - if !ok { - return false, err - } - - model[sec][ptype].Policy = append(model[sec][ptype].Policy[:index], model[sec][ptype].Policy[index+1:]...) - delete(model[sec][ptype].PolicyMap, strings.Join(rule, DefaultSep)) - for i := index; i < len(model[sec][ptype].Policy); i++ { - model[sec][ptype].PolicyMap[strings.Join(model[sec][ptype].Policy[i], DefaultSep)] = i - } - - return true, err -} - -// UpdatePolicy updates a policy rule from the model. -func (model Model) UpdatePolicy(sec string, ptype string, oldRule []string, newRule []string) (bool, error) { - _, err := model.GetAssertion(sec, ptype) - if err != nil { - return false, err - } - oldPolicy := strings.Join(oldRule, DefaultSep) - index, ok := model[sec][ptype].PolicyMap[oldPolicy] - if !ok { - return false, nil - } - - model[sec][ptype].Policy[index] = newRule - delete(model[sec][ptype].PolicyMap, oldPolicy) - model[sec][ptype].PolicyMap[strings.Join(newRule, DefaultSep)] = index - - return true, nil -} - -// UpdatePolicies updates a policy rule from the model. -func (model Model) UpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) (bool, error) { - _, err := model.GetAssertion(sec, ptype) - if err != nil { - return false, err - } - rollbackFlag := false - // index -> []{oldIndex, newIndex} - modifiedRuleIndex := make(map[int][]int) - // rollback - defer func() { - if rollbackFlag { - for index, oldNewIndex := range modifiedRuleIndex { - model[sec][ptype].Policy[index] = oldRules[oldNewIndex[0]] - oldPolicy := strings.Join(oldRules[oldNewIndex[0]], DefaultSep) - newPolicy := strings.Join(newRules[oldNewIndex[1]], DefaultSep) - delete(model[sec][ptype].PolicyMap, newPolicy) - model[sec][ptype].PolicyMap[oldPolicy] = index - } - } - }() - - newIndex := 0 - for oldIndex, oldRule := range oldRules { - oldPolicy := strings.Join(oldRule, DefaultSep) - index, ok := model[sec][ptype].PolicyMap[oldPolicy] - if !ok { - rollbackFlag = true - return false, nil - } - - model[sec][ptype].Policy[index] = newRules[newIndex] - delete(model[sec][ptype].PolicyMap, oldPolicy) - model[sec][ptype].PolicyMap[strings.Join(newRules[newIndex], DefaultSep)] = index - modifiedRuleIndex[index] = []int{oldIndex, newIndex} - newIndex++ - } - - return true, nil -} - -// RemovePolicies removes policy rules from the model. -func (model Model) RemovePolicies(sec string, ptype string, rules [][]string) (bool, error) { - affected, err := model.RemovePoliciesWithAffected(sec, ptype, rules) - return len(affected) != 0, err -} - -// RemovePoliciesWithAffected removes policy rules from the model, and returns affected rules. -func (model Model) RemovePoliciesWithAffected(sec string, ptype string, rules [][]string) ([][]string, error) { - _, err := model.GetAssertion(sec, ptype) - if err != nil { - return nil, err - } - var affected [][]string - for _, rule := range rules { - index, ok := model[sec][ptype].PolicyMap[strings.Join(rule, DefaultSep)] - if !ok { - continue - } - - affected = append(affected, rule) - model[sec][ptype].Policy = append(model[sec][ptype].Policy[:index], model[sec][ptype].Policy[index+1:]...) - delete(model[sec][ptype].PolicyMap, strings.Join(rule, DefaultSep)) - for i := index; i < len(model[sec][ptype].Policy); i++ { - model[sec][ptype].PolicyMap[strings.Join(model[sec][ptype].Policy[i], DefaultSep)] = i - } - } - return affected, nil -} - -// RemoveFilteredPolicy removes policy rules based on field filters from the model. -func (model Model) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) (bool, [][]string, error) { - _, err := model.GetAssertion(sec, ptype) - if err != nil { - return false, nil, err - } - var tmp [][]string - var effects [][]string - res := false - model[sec][ptype].PolicyMap = map[string]int{} - - for _, rule := range model[sec][ptype].Policy { - matched := true - for i, fieldValue := range fieldValues { - if fieldValue != "" && rule[fieldIndex+i] != fieldValue { - matched = false - break - } - } - - if matched { - effects = append(effects, rule) - } else { - tmp = append(tmp, rule) - model[sec][ptype].PolicyMap[strings.Join(rule, DefaultSep)] = len(tmp) - 1 - } - } - - if len(tmp) != len(model[sec][ptype].Policy) { - model[sec][ptype].Policy = tmp - res = true - } - - return res, effects, nil -} - -// GetValuesForFieldInPolicy gets all values for a field for all rules in a policy, duplicated values are removed. -func (model Model) GetValuesForFieldInPolicy(sec string, ptype string, fieldIndex int) ([]string, error) { - values := []string{} - - _, err := model.GetAssertion(sec, ptype) - if err != nil { - return nil, err - } - - for _, rule := range model[sec][ptype].Policy { - values = append(values, rule[fieldIndex]) - } - - util.ArrayRemoveDuplicates(&values) - - return values, nil -} - -// GetValuesForFieldInPolicyAllTypes gets all values for a field for all rules in a policy of all ptypes, duplicated values are removed. -func (model Model) GetValuesForFieldInPolicyAllTypes(sec string, fieldIndex int) ([]string, error) { - values := []string{} - - for ptype := range model[sec] { - v, err := model.GetValuesForFieldInPolicy(sec, ptype, fieldIndex) - if err != nil { - return nil, err - } - values = append(values, v...) - } - - util.ArrayRemoveDuplicates(&values) - - return values, nil -} - -// GetValuesForFieldInPolicyAllTypesByName gets all values for a field for all rules in a policy of all ptypes, duplicated values are removed. -func (model Model) GetValuesForFieldInPolicyAllTypesByName(sec string, field string) ([]string, error) { - values := []string{} - - for ptype := range model[sec] { - // GetFieldIndex will return (-1, err) if field is not found, ignore it - index, err := model.GetFieldIndex(ptype, field) - if err != nil { - continue - } - v, err := model.GetValuesForFieldInPolicy(sec, ptype, index) - if err != nil { - return nil, err - } - values = append(values, v...) - } - - util.ArrayRemoveDuplicates(&values) - - return values, nil -} diff --git a/vendor/github.com/casbin/casbin/v2/persist/adapter.go b/vendor/github.com/casbin/casbin/v2/persist/adapter.go deleted file mode 100644 index 0525657a..00000000 --- a/vendor/github.com/casbin/casbin/v2/persist/adapter.go +++ /dev/null @@ -1,74 +0,0 @@ -// 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 persist - -import ( - "encoding/csv" - "strings" - - "github.com/casbin/casbin/v2/model" -) - -// LoadPolicyLine loads a text line as a policy rule to model. -func LoadPolicyLine(line string, m model.Model) error { - if line == "" || strings.HasPrefix(line, "#") { - return nil - } - - r := csv.NewReader(strings.NewReader(line)) - r.Comma = ',' - r.Comment = '#' - r.TrimLeadingSpace = true - - tokens, err := r.Read() - if err != nil { - return err - } - - return LoadPolicyArray(tokens, m) -} - -// LoadPolicyArray loads a policy rule to model. -func LoadPolicyArray(rule []string, m model.Model) error { - key := rule[0] - sec := key[:1] - ok, err := m.HasPolicyEx(sec, key, rule[1:]) - if err != nil { - return err - } - if ok { - return nil // skip duplicated policy - } - m.AddPolicy(sec, key, rule[1:]) - return nil -} - -// Adapter is the interface for Casbin adapters. -type Adapter interface { - // LoadPolicy loads all policy rules from the storage. - LoadPolicy(model model.Model) error - // SavePolicy saves all policy rules to the storage. - SavePolicy(model model.Model) error - - // AddPolicy adds a policy rule to the storage. - // This is part of the Auto-Save feature. - AddPolicy(sec string, ptype string, rule []string) error - // RemovePolicy removes a policy rule from the storage. - // This is part of the Auto-Save feature. - RemovePolicy(sec string, ptype string, rule []string) error - // RemoveFilteredPolicy removes policy rules that match the filter from the storage. - // This is part of the Auto-Save feature. - RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error -} diff --git a/vendor/github.com/casbin/casbin/v2/persist/adapter_context.go b/vendor/github.com/casbin/casbin/v2/persist/adapter_context.go deleted file mode 100644 index bda78a7e..00000000 --- a/vendor/github.com/casbin/casbin/v2/persist/adapter_context.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2023 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 persist - -import ( - "context" - - "github.com/casbin/casbin/v2/model" -) - -// ContextAdapter provides a context-aware interface for Casbin adapters. -type ContextAdapter interface { - // LoadPolicyCtx loads all policy rules from the storage with context. - LoadPolicyCtx(ctx context.Context, model model.Model) error - // SavePolicyCtx saves all policy rules to the storage with context. - SavePolicyCtx(ctx context.Context, model model.Model) error - - // AddPolicyCtx adds a policy rule to the storage with context. - // This is part of the Auto-Save feature. - AddPolicyCtx(ctx context.Context, sec string, ptype string, rule []string) error - // RemovePolicyCtx removes a policy rule from the storage with context. - // This is part of the Auto-Save feature. - RemovePolicyCtx(ctx context.Context, sec string, ptype string, rule []string) error - // RemoveFilteredPolicyCtx removes policy rules that match the filter from the storage with context. - // This is part of the Auto-Save feature. - RemoveFilteredPolicyCtx(ctx context.Context, sec string, ptype string, fieldIndex int, fieldValues ...string) error -} diff --git a/vendor/github.com/casbin/casbin/v2/persist/adapter_filtered.go b/vendor/github.com/casbin/casbin/v2/persist/adapter_filtered.go deleted file mode 100644 index 82c9a0e7..00000000 --- a/vendor/github.com/casbin/casbin/v2/persist/adapter_filtered.go +++ /dev/null @@ -1,29 +0,0 @@ -// 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 persist - -import ( - "github.com/casbin/casbin/v2/model" -) - -// FilteredAdapter is the interface for Casbin adapters supporting filtered policies. -type FilteredAdapter interface { - Adapter - - // LoadFilteredPolicy loads only policy rules that match the filter. - LoadFilteredPolicy(model model.Model, filter interface{}) error - // IsFiltered returns true if the loaded policy has been filtered. - IsFiltered() bool -} diff --git a/vendor/github.com/casbin/casbin/v2/persist/adapter_filtered_context.go b/vendor/github.com/casbin/casbin/v2/persist/adapter_filtered_context.go deleted file mode 100644 index 7893ce1b..00000000 --- a/vendor/github.com/casbin/casbin/v2/persist/adapter_filtered_context.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2024 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 persist - -import ( - "context" - - "github.com/casbin/casbin/v2/model" -) - -// ContextFilteredAdapter is the context-aware interface for Casbin adapters supporting filtered policies. -type ContextFilteredAdapter interface { - ContextAdapter - - // LoadFilteredPolicyCtx loads only policy rules that match the filter. - LoadFilteredPolicyCtx(ctx context.Context, model model.Model, filter interface{}) error - // IsFilteredCtx returns true if the loaded policy has been filtered. - IsFilteredCtx(ctx context.Context) bool -} diff --git a/vendor/github.com/casbin/casbin/v2/persist/batch_adapter.go b/vendor/github.com/casbin/casbin/v2/persist/batch_adapter.go deleted file mode 100644 index 56ec415f..00000000 --- a/vendor/github.com/casbin/casbin/v2/persist/batch_adapter.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2020 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 persist - -// BatchAdapter is the interface for Casbin adapters with multiple add and remove policy functions. -type BatchAdapter interface { - Adapter - // AddPolicies adds policy rules to the storage. - // This is part of the Auto-Save feature. - AddPolicies(sec string, ptype string, rules [][]string) error - // RemovePolicies removes policy rules from the storage. - // This is part of the Auto-Save feature. - RemovePolicies(sec string, ptype string, rules [][]string) error -} diff --git a/vendor/github.com/casbin/casbin/v2/persist/batch_adapter_context.go b/vendor/github.com/casbin/casbin/v2/persist/batch_adapter_context.go deleted file mode 100644 index 741c184d..00000000 --- a/vendor/github.com/casbin/casbin/v2/persist/batch_adapter_context.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2024 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 persist - -import "context" - -// ContextBatchAdapter is the context-aware interface for Casbin adapters with multiple add and remove policy functions. -type ContextBatchAdapter interface { - ContextAdapter - - // AddPoliciesCtx adds policy rules to the storage. - // This is part of the Auto-Save feature. - AddPoliciesCtx(ctx context.Context, sec string, ptype string, rules [][]string) error - // RemovePoliciesCtx removes policy rules from the storage. - // This is part of the Auto-Save feature. - RemovePoliciesCtx(ctx context.Context, sec string, ptype string, rules [][]string) error -} diff --git a/vendor/github.com/casbin/casbin/v2/persist/cache/cache.go b/vendor/github.com/casbin/casbin/v2/persist/cache/cache.go deleted file mode 100644 index 08447b83..00000000 --- a/vendor/github.com/casbin/casbin/v2/persist/cache/cache.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2021 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 cache - -import "errors" - -var ErrNoSuchKey = errors.New("there's no such key existing in cache") - -type Cache interface { - // Set puts key and value into cache. - // First parameter for extra should be time.Time object denoting expected survival time. - // If survival time equals 0 or less, the key will always be survival. - Set(key string, value bool, extra ...interface{}) error - - // Get returns result for key, - // If there's no such key existing in cache, - // ErrNoSuchKey will be returned. - Get(key string) (bool, error) - - // Delete will remove the specific key in cache. - // If there's no such key existing in cache, - // ErrNoSuchKey will be returned. - Delete(key string) error - - // Clear deletes all the items stored in cache. - Clear() error -} diff --git a/vendor/github.com/casbin/casbin/v2/persist/cache/cache_sync.go b/vendor/github.com/casbin/casbin/v2/persist/cache/cache_sync.go deleted file mode 100644 index 816e12dc..00000000 --- a/vendor/github.com/casbin/casbin/v2/persist/cache/cache_sync.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2021 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 cache - -import ( - "sync" - "time" -) - -type SyncCache struct { - cache DefaultCache - sync.RWMutex -} - -func (c *SyncCache) Set(key string, value bool, extra ...interface{}) error { - ttl := time.Duration(-1) - if len(extra) > 0 { - ttl = extra[0].(time.Duration) - } - c.Lock() - defer c.Unlock() - c.cache[key] = cacheItem{ - value: value, - expiresAt: time.Now().Add(ttl), - ttl: ttl, - } - return nil -} - -func (c *SyncCache) Get(key string) (bool, error) { - c.RLock() - res, ok := c.cache[key] - c.RUnlock() - if !ok { - return false, ErrNoSuchKey - } else { - if res.ttl > 0 && time.Now().After(res.expiresAt) { - c.Lock() - defer c.Unlock() - delete(c.cache, key) - return false, ErrNoSuchKey - } - return res.value, nil - } -} - -func (c *SyncCache) Delete(key string) error { - c.RLock() - _, ok := c.cache[key] - c.RUnlock() - if !ok { - return ErrNoSuchKey - } else { - c.Lock() - defer c.Unlock() - delete(c.cache, key) - return nil - } -} - -func (c *SyncCache) Clear() error { - c.Lock() - c.cache = make(DefaultCache) - c.Unlock() - return nil -} - -func NewSyncCache() (Cache, error) { - cache := SyncCache{ - make(DefaultCache), - sync.RWMutex{}, - } - return &cache, nil -} diff --git a/vendor/github.com/casbin/casbin/v2/persist/cache/default-cache.go b/vendor/github.com/casbin/casbin/v2/persist/cache/default-cache.go deleted file mode 100644 index 9108e7d6..00000000 --- a/vendor/github.com/casbin/casbin/v2/persist/cache/default-cache.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2021 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 cache - -import "time" - -type cacheItem struct { - value bool - expiresAt time.Time - ttl time.Duration -} - -type DefaultCache map[string]cacheItem - -func (c *DefaultCache) Set(key string, value bool, extra ...interface{}) error { - ttl := time.Duration(-1) - if len(extra) > 0 { - ttl = extra[0].(time.Duration) - } - (*c)[key] = cacheItem{ - value: value, - expiresAt: time.Now().Add(ttl), - ttl: ttl, - } - return nil -} - -func (c *DefaultCache) Get(key string) (bool, error) { - if res, ok := (*c)[key]; !ok { - return false, ErrNoSuchKey - } else { - if res.ttl > 0 && time.Now().After(res.expiresAt) { - delete(*c, key) - return false, ErrNoSuchKey - } - return res.value, nil - } -} - -func (c *DefaultCache) Delete(key string) error { - if _, ok := (*c)[key]; !ok { - return ErrNoSuchKey - } else { - delete(*c, key) - return nil - } -} - -func (c *DefaultCache) Clear() error { - *c = make(DefaultCache) - return nil -} - -func NewDefaultCache() (Cache, error) { - cache := make(DefaultCache) - return &cache, nil -} diff --git a/vendor/github.com/casbin/casbin/v2/persist/dispatcher.go b/vendor/github.com/casbin/casbin/v2/persist/dispatcher.go deleted file mode 100644 index ceaed838..00000000 --- a/vendor/github.com/casbin/casbin/v2/persist/dispatcher.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2020 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 persist - -// Dispatcher is the interface for Casbin dispatcher. -type Dispatcher interface { - // AddPolicies adds policies rule to all instance. - AddPolicies(sec string, ptype string, rules [][]string) error - // RemovePolicies removes policies rule from all instance. - RemovePolicies(sec string, ptype string, rules [][]string) error - // RemoveFilteredPolicy removes policy rules that match the filter from all instance. - RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error - // ClearPolicy clears all current policy in all instances - ClearPolicy() error - // UpdatePolicy updates policy rule from all instance. - UpdatePolicy(sec string, ptype string, oldRule, newRule []string) error - // UpdatePolicies updates some policy rules from all instance - UpdatePolicies(sec string, ptype string, oldrules, newRules [][]string) error - // UpdateFilteredPolicies deletes old rules and adds new rules. - UpdateFilteredPolicies(sec string, ptype string, oldRules [][]string, newRules [][]string) error -} diff --git a/vendor/github.com/casbin/casbin/v2/persist/file-adapter/adapter.go b/vendor/github.com/casbin/casbin/v2/persist/file-adapter/adapter.go deleted file mode 100644 index c68f0eaa..00000000 --- a/vendor/github.com/casbin/casbin/v2/persist/file-adapter/adapter.go +++ /dev/null @@ -1,149 +0,0 @@ -// 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 fileadapter - -import ( - "bufio" - "bytes" - "errors" - "os" - "strings" - - "github.com/casbin/casbin/v2/model" - "github.com/casbin/casbin/v2/persist" - "github.com/casbin/casbin/v2/util" -) - -// Adapter is the file adapter for Casbin. -// It can load policy from file or save policy to file. -type Adapter struct { - filePath string -} - -func (a *Adapter) UpdatePolicy(sec string, ptype string, oldRule, newRule []string) error { - return errors.New("not implemented") -} - -func (a *Adapter) UpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) error { - return errors.New("not implemented") -} - -func (a *Adapter) UpdateFilteredPolicies(sec string, ptype string, newRules [][]string, fieldIndex int, fieldValues ...string) ([][]string, error) { - return nil, errors.New("not implemented") -} - -// NewAdapter is the constructor for Adapter. -func NewAdapter(filePath string) *Adapter { - return &Adapter{filePath: filePath} -} - -// LoadPolicy loads all policy rules from the storage. -func (a *Adapter) LoadPolicy(model model.Model) error { - if a.filePath == "" { - return errors.New("invalid file path, file path cannot be empty") - } - - return a.loadPolicyFile(model, persist.LoadPolicyLine) -} - -// SavePolicy saves all policy rules to the storage. -func (a *Adapter) SavePolicy(model model.Model) error { - if a.filePath == "" { - return errors.New("invalid file path, file path cannot be empty") - } - - var tmp bytes.Buffer - - for ptype, ast := range model["p"] { - for _, rule := range ast.Policy { - tmp.WriteString(ptype + ", ") - tmp.WriteString(util.ArrayToString(rule)) - tmp.WriteString("\n") - } - } - - for ptype, ast := range model["g"] { - for _, rule := range ast.Policy { - tmp.WriteString(ptype + ", ") - tmp.WriteString(util.ArrayToString(rule)) - tmp.WriteString("\n") - } - } - - return a.savePolicyFile(strings.TrimRight(tmp.String(), "\n")) -} - -func (a *Adapter) loadPolicyFile(model model.Model, handler func(string, model.Model) error) error { - f, err := os.Open(a.filePath) - if err != nil { - return err - } - defer f.Close() - - scanner := bufio.NewScanner(f) - for scanner.Scan() { - line := strings.TrimSpace(scanner.Text()) - err = handler(line, model) - if err != nil { - return err - } - } - return scanner.Err() -} - -func (a *Adapter) savePolicyFile(text string) error { - f, err := os.Create(a.filePath) - if err != nil { - return err - } - w := bufio.NewWriter(f) - - _, err = w.WriteString(text) - if err != nil { - return err - } - - err = w.Flush() - if err != nil { - return err - } - - return f.Close() -} - -// AddPolicy adds a policy rule to the storage. -func (a *Adapter) AddPolicy(sec string, ptype string, rule []string) error { - return errors.New("not implemented") -} - -// AddPolicies adds policy rules to the storage. -func (a *Adapter) AddPolicies(sec string, ptype string, rules [][]string) error { - return errors.New("not implemented") -} - -// RemovePolicy removes a policy rule from the storage. -func (a *Adapter) RemovePolicy(sec string, ptype string, rule []string) error { - return errors.New("not implemented") -} - -// RemovePolicies removes policy rules from the storage. -func (a *Adapter) RemovePolicies(sec string, ptype string, rules [][]string) error { - return errors.New("not implemented") -} - -// RemoveFilteredPolicy removes policy rules that match the filter from the storage. -func (a *Adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error { - return errors.New("not implemented") -} diff --git a/vendor/github.com/casbin/casbin/v2/persist/file-adapter/adapter_filtered.go b/vendor/github.com/casbin/casbin/v2/persist/file-adapter/adapter_filtered.go deleted file mode 100644 index 1a074c9a..00000000 --- a/vendor/github.com/casbin/casbin/v2/persist/file-adapter/adapter_filtered.go +++ /dev/null @@ -1,156 +0,0 @@ -// 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 fileadapter - -import ( - "bufio" - "errors" - "os" - "strings" - - "github.com/casbin/casbin/v2/model" - "github.com/casbin/casbin/v2/persist" -) - -// FilteredAdapter is the filtered file adapter for Casbin. It can load policy -// from file or save policy to file and supports loading of filtered policies. -type FilteredAdapter struct { - *Adapter - filtered bool -} - -// Filter defines the filtering rules for a FilteredAdapter's policy. Empty values -// are ignored, but all others must match the filter. -type Filter struct { - P []string - G []string - G1 []string - G2 []string - G3 []string - G4 []string - G5 []string -} - -// NewFilteredAdapter is the constructor for FilteredAdapter. -func NewFilteredAdapter(filePath string) *FilteredAdapter { - a := FilteredAdapter{} - a.filtered = true - a.Adapter = NewAdapter(filePath) - return &a -} - -// LoadPolicy loads all policy rules from the storage. -func (a *FilteredAdapter) LoadPolicy(model model.Model) error { - a.filtered = false - return a.Adapter.LoadPolicy(model) -} - -// LoadFilteredPolicy loads only policy rules that match the filter. -func (a *FilteredAdapter) LoadFilteredPolicy(model model.Model, filter interface{}) error { - if filter == nil { - return a.LoadPolicy(model) - } - if a.filePath == "" { - return errors.New("invalid file path, file path cannot be empty") - } - - filterValue, ok := filter.(*Filter) - if !ok { - return errors.New("invalid filter type") - } - err := a.loadFilteredPolicyFile(model, filterValue, persist.LoadPolicyLine) - if err == nil { - a.filtered = true - } - return err -} - -func (a *FilteredAdapter) loadFilteredPolicyFile(model model.Model, filter *Filter, handler func(string, model.Model) error) error { - f, err := os.Open(a.filePath) - if err != nil { - return err - } - defer f.Close() - - scanner := bufio.NewScanner(f) - for scanner.Scan() { - line := strings.TrimSpace(scanner.Text()) - - if filterLine(line, filter) { - continue - } - - err = handler(line, model) - if err != nil { - return err - } - } - return scanner.Err() -} - -// IsFiltered returns true if the loaded policy has been filtered. -func (a *FilteredAdapter) IsFiltered() bool { - return a.filtered -} - -// SavePolicy saves all policy rules to the storage. -func (a *FilteredAdapter) SavePolicy(model model.Model) error { - if a.filtered { - return errors.New("cannot save a filtered policy") - } - return a.Adapter.SavePolicy(model) -} - -func filterLine(line string, filter *Filter) bool { - if filter == nil { - return false - } - p := strings.Split(line, ",") - if len(p) == 0 { - return true - } - var filterSlice []string - switch strings.TrimSpace(p[0]) { - case "p": - filterSlice = filter.P - case "g": - filterSlice = filter.G - case "g1": - filterSlice = filter.G1 - case "g2": - filterSlice = filter.G2 - case "g3": - filterSlice = filter.G3 - case "g4": - filterSlice = filter.G4 - case "g5": - filterSlice = filter.G5 - } - return filterWords(p, filterSlice) -} - -func filterWords(line []string, filter []string) bool { - if len(line) < len(filter)+1 { - return true - } - var skipLine bool - for i, v := range filter { - if len(v) > 0 && strings.TrimSpace(v) != strings.TrimSpace(line[i+1]) { - skipLine = true - break - } - } - return skipLine -} diff --git a/vendor/github.com/casbin/casbin/v2/persist/file-adapter/adapter_mock.go b/vendor/github.com/casbin/casbin/v2/persist/file-adapter/adapter_mock.go deleted file mode 100644 index fcc5f821..00000000 --- a/vendor/github.com/casbin/casbin/v2/persist/file-adapter/adapter_mock.go +++ /dev/null @@ -1,122 +0,0 @@ -// 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 fileadapter - -import ( - "bufio" - "errors" - "io" - "os" - "strings" - - "github.com/casbin/casbin/v2/model" - "github.com/casbin/casbin/v2/persist" -) - -// AdapterMock is the file adapter for Casbin. -// It can load policy from file or save policy to file. -type AdapterMock struct { - filePath string - errorValue string -} - -// NewAdapterMock is the constructor for AdapterMock. -func NewAdapterMock(filePath string) *AdapterMock { - a := AdapterMock{} - a.filePath = filePath - return &a -} - -// LoadPolicy loads all policy rules from the storage. -func (a *AdapterMock) LoadPolicy(model model.Model) error { - err := a.loadPolicyFile(model, persist.LoadPolicyLine) - return err -} - -// SavePolicy saves all policy rules to the storage. -func (a *AdapterMock) SavePolicy(model model.Model) error { - return nil -} - -func (a *AdapterMock) loadPolicyFile(model model.Model, handler func(string, model.Model) error) error { - f, err := os.Open(a.filePath) - if err != nil { - return err - } - defer f.Close() - - buf := bufio.NewReader(f) - for { - line, err := buf.ReadString('\n') - line = strings.TrimSpace(line) - if err2 := handler(line, model); err2 != nil { - return err2 - } - if err != nil { - if err == io.EOF { - return nil - } - return err - } - } -} - -// SetMockErr sets string to be returned by of the mock during testing. -func (a *AdapterMock) SetMockErr(errorToSet string) { - a.errorValue = errorToSet -} - -// GetMockErr returns a mock error or nil. -func (a *AdapterMock) GetMockErr() error { - var returnError error - if a.errorValue != "" { - returnError = errors.New(a.errorValue) - } - return returnError -} - -// AddPolicy adds a policy rule to the storage. -func (a *AdapterMock) AddPolicy(sec string, ptype string, rule []string) error { - return a.GetMockErr() -} - -// AddPolicies removes policy rules from the storage. -func (a *AdapterMock) AddPolicies(sec string, ptype string, rules [][]string) error { - return a.GetMockErr() -} - -// RemovePolicy removes a policy rule from the storage. -func (a *AdapterMock) RemovePolicy(sec string, ptype string, rule []string) error { - return a.GetMockErr() -} - -// RemovePolicies removes policy rules from the storage. -func (a *AdapterMock) RemovePolicies(sec string, ptype string, rules [][]string) error { - return a.GetMockErr() -} - -// UpdatePolicy removes a policy rule from the storage. -func (a *AdapterMock) UpdatePolicy(sec string, ptype string, oldRule, newPolicy []string) error { - return a.GetMockErr() -} - -func (a *AdapterMock) UpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) error { - return a.GetMockErr() -} - -// RemoveFilteredPolicy removes policy rules that match the filter from the storage. -func (a *AdapterMock) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error { - return a.GetMockErr() -} diff --git a/vendor/github.com/casbin/casbin/v2/persist/update_adapter.go b/vendor/github.com/casbin/casbin/v2/persist/update_adapter.go deleted file mode 100644 index fe9204af..00000000 --- a/vendor/github.com/casbin/casbin/v2/persist/update_adapter.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2020 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 persist - -// UpdatableAdapter is the interface for Casbin adapters with add update policy function. -type UpdatableAdapter interface { - Adapter - // UpdatePolicy updates a policy rule from storage. - // This is part of the Auto-Save feature. - UpdatePolicy(sec string, ptype string, oldRule, newRule []string) error - // UpdatePolicies updates some policy rules to storage, like db, redis. - UpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) error - // UpdateFilteredPolicies deletes old rules and adds new rules. - UpdateFilteredPolicies(sec string, ptype string, newRules [][]string, fieldIndex int, fieldValues ...string) ([][]string, error) -} diff --git a/vendor/github.com/casbin/casbin/v2/persist/update_adapter_context.go b/vendor/github.com/casbin/casbin/v2/persist/update_adapter_context.go deleted file mode 100644 index 55b8ba9d..00000000 --- a/vendor/github.com/casbin/casbin/v2/persist/update_adapter_context.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2024 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 persist - -import "context" - -// ContextUpdatableAdapter is the context-aware interface for Casbin adapters with add update policy function. -type ContextUpdatableAdapter interface { - ContextAdapter - - // UpdatePolicyCtx updates a policy rule from storage. - // This is part of the Auto-Save feature. - UpdatePolicyCtx(ctx context.Context, sec string, ptype string, oldRule, newRule []string) error - // UpdatePoliciesCtx updates some policy rules to storage, like db, redis. - UpdatePoliciesCtx(ctx context.Context, sec string, ptype string, oldRules, newRules [][]string) error - // UpdateFilteredPoliciesCtx deletes old rules and adds new rules. - UpdateFilteredPoliciesCtx(ctx context.Context, sec string, ptype string, newRules [][]string, fieldIndex int, fieldValues ...string) ([][]string, error) -} diff --git a/vendor/github.com/casbin/casbin/v2/persist/watcher.go b/vendor/github.com/casbin/casbin/v2/persist/watcher.go deleted file mode 100644 index 0d843606..00000000 --- a/vendor/github.com/casbin/casbin/v2/persist/watcher.go +++ /dev/null @@ -1,29 +0,0 @@ -// 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 persist - -// Watcher is the interface for Casbin watchers. -type Watcher interface { - // SetUpdateCallback sets the callback function that the watcher will call - // when the policy in DB has been changed by other instances. - // A classic callback is Enforcer.LoadPolicy(). - SetUpdateCallback(func(string)) error - // Update calls the update callback of other instances to synchronize their policy. - // It is usually called after changing the policy in DB, like Enforcer.SavePolicy(), - // Enforcer.AddPolicy(), Enforcer.RemovePolicy(), etc. - Update() error - // Close stops and releases the watcher, the callback function will not be called any more. - Close() -} diff --git a/vendor/github.com/casbin/casbin/v2/persist/watcher_ex.go b/vendor/github.com/casbin/casbin/v2/persist/watcher_ex.go deleted file mode 100644 index 1c6f4299..00000000 --- a/vendor/github.com/casbin/casbin/v2/persist/watcher_ex.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2020 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 persist - -import "github.com/casbin/casbin/v2/model" - -// WatcherEx is the strengthened Casbin watchers. -type WatcherEx interface { - Watcher - // UpdateForAddPolicy calls the update callback of other instances to synchronize their policy. - // It is called after Enforcer.AddPolicy() - UpdateForAddPolicy(sec, ptype string, params ...string) error - // UpdateForRemovePolicy calls the update callback of other instances to synchronize their policy. - // It is called after Enforcer.RemovePolicy() - UpdateForRemovePolicy(sec, ptype string, params ...string) error - // UpdateForRemoveFilteredPolicy calls the update callback of other instances to synchronize their policy. - // It is called after Enforcer.RemoveFilteredNamedGroupingPolicy() - UpdateForRemoveFilteredPolicy(sec, ptype string, fieldIndex int, fieldValues ...string) error - // UpdateForSavePolicy calls the update callback of other instances to synchronize their policy. - // It is called after Enforcer.RemoveFilteredNamedGroupingPolicy() - UpdateForSavePolicy(model model.Model) error - // UpdateForAddPolicies calls the update callback of other instances to synchronize their policy. - // It is called after Enforcer.AddPolicies() - UpdateForAddPolicies(sec string, ptype string, rules ...[]string) error - // UpdateForRemovePolicies calls the update callback of other instances to synchronize their policy. - // It is called after Enforcer.RemovePolicies() - UpdateForRemovePolicies(sec string, ptype string, rules ...[]string) error -} diff --git a/vendor/github.com/casbin/casbin/v2/persist/watcher_update.go b/vendor/github.com/casbin/casbin/v2/persist/watcher_update.go deleted file mode 100644 index 694123c4..00000000 --- a/vendor/github.com/casbin/casbin/v2/persist/watcher_update.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2020 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 persist - -// UpdatableWatcher is strengthened for Casbin watchers. -type UpdatableWatcher interface { - Watcher - // UpdateForUpdatePolicy calls the update callback of other instances to synchronize their policy. - // It is called after Enforcer.UpdatePolicy() - UpdateForUpdatePolicy(sec string, ptype string, oldRule, newRule []string) error - // UpdateForUpdatePolicies calls the update callback of other instances to synchronize their policy. - // It is called after Enforcer.UpdatePolicies() - UpdateForUpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) error -} diff --git a/vendor/github.com/casbin/casbin/v2/rbac/context_role_manager.go b/vendor/github.com/casbin/casbin/v2/rbac/context_role_manager.go deleted file mode 100644 index dcaa37f7..00000000 --- a/vendor/github.com/casbin/casbin/v2/rbac/context_role_manager.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2023 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 rbac - -import "context" - -// ContextRoleManager provides a context-aware interface to define the operations for managing roles. -// Prefer this over RoleManager interface for context propagation, which is useful for things like handling -// request timeouts. -type ContextRoleManager interface { - RoleManager - - // ClearCtx clears all stored data and resets the role manager to the initial state with context. - ClearCtx(ctx context.Context) error - // AddLinkCtx adds the inheritance link between two roles. role: name1 and role: name2 with context. - // domain is a prefix to the roles (can be used for other purposes). - AddLinkCtx(ctx context.Context, name1 string, name2 string, domain ...string) error - // DeleteLinkCtx deletes the inheritance link between two roles. role: name1 and role: name2 with context. - // domain is a prefix to the roles (can be used for other purposes). - DeleteLinkCtx(ctx context.Context, name1 string, name2 string, domain ...string) error - // HasLinkCtx determines whether a link exists between two roles. role: name1 inherits role: name2 with context. - // domain is a prefix to the roles (can be used for other purposes). - HasLinkCtx(ctx context.Context, name1 string, name2 string, domain ...string) (bool, error) - // GetRolesCtx gets the roles that a user inherits with context. - // domain is a prefix to the roles (can be used for other purposes). - GetRolesCtx(ctx context.Context, name string, domain ...string) ([]string, error) - // GetUsersCtx gets the users that inherits a role with context. - // domain is a prefix to the users (can be used for other purposes). - GetUsersCtx(ctx context.Context, name string, domain ...string) ([]string, error) - // GetDomainsCtx gets domains that a user has with context. - GetDomainsCtx(ctx context.Context, name string) ([]string, error) - // GetAllDomainsCtx gets all domains with context. - GetAllDomainsCtx(ctx context.Context) ([]string, error) -} diff --git a/vendor/github.com/casbin/casbin/v2/rbac/default-role-manager/role_manager.go b/vendor/github.com/casbin/casbin/v2/rbac/default-role-manager/role_manager.go deleted file mode 100644 index a6ae8693..00000000 --- a/vendor/github.com/casbin/casbin/v2/rbac/default-role-manager/role_manager.go +++ /dev/null @@ -1,1014 +0,0 @@ -// 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 defaultrolemanager - -import ( - "fmt" - "strings" - "sync" - - "github.com/casbin/casbin/v2/log" - "github.com/casbin/casbin/v2/rbac" - "github.com/casbin/casbin/v2/util" -) - -const defaultDomain string = "" - -// Role represents the data structure for a role in RBAC. -type Role struct { - name string - roles *sync.Map - users *sync.Map - matched *sync.Map - matchedBy *sync.Map - linkConditionFuncMap *sync.Map - linkConditionFuncParamsMap *sync.Map -} - -func newRole(name string) *Role { - r := Role{} - r.name = name - r.roles = &sync.Map{} - r.users = &sync.Map{} - r.matched = &sync.Map{} - r.matchedBy = &sync.Map{} - r.linkConditionFuncMap = &sync.Map{} - r.linkConditionFuncParamsMap = &sync.Map{} - return &r -} - -func (r *Role) addRole(role *Role) { - r.roles.Store(role.name, role) - role.addUser(r) -} - -func (r *Role) removeRole(role *Role) { - r.roles.Delete(role.name) - role.removeUser(r) -} - -// should only be called inside addRole. -func (r *Role) addUser(user *Role) { - r.users.Store(user.name, user) -} - -// should only be called inside removeRole. -func (r *Role) removeUser(user *Role) { - r.users.Delete(user.name) -} - -func (r *Role) addMatch(role *Role) { - r.matched.Store(role.name, role) - role.matchedBy.Store(r.name, r) -} - -func (r *Role) removeMatch(role *Role) { - r.matched.Delete(role.name) - role.matchedBy.Delete(r.name) -} - -func (r *Role) removeMatches() { - r.matched.Range(func(key, value interface{}) bool { - r.removeMatch(value.(*Role)) - return true - }) - r.matchedBy.Range(func(key, value interface{}) bool { - value.(*Role).removeMatch(r) - return true - }) -} - -func (r *Role) rangeRoles(fn func(key, value interface{}) bool) { - r.roles.Range(fn) - r.roles.Range(func(key, value interface{}) bool { - role := value.(*Role) - role.matched.Range(fn) - return true - }) - r.matchedBy.Range(func(key, value interface{}) bool { - role := value.(*Role) - role.roles.Range(fn) - return true - }) -} - -func (r *Role) rangeUsers(fn func(key, value interface{}) bool) { - r.users.Range(fn) - r.users.Range(func(key, value interface{}) bool { - role := value.(*Role) - role.matched.Range(fn) - return true - }) - r.matchedBy.Range(func(key, value interface{}) bool { - role := value.(*Role) - role.users.Range(fn) - return true - }) -} - -func (r *Role) toString() string { - roles := r.getRoles() - - if len(roles) == 0 { - return "" - } - - var sb strings.Builder - sb.WriteString(r.name) - sb.WriteString(" < ") - if len(roles) != 1 { - sb.WriteString("(") - } - - for i, role := range roles { - if i == 0 { - sb.WriteString(role) - } else { - sb.WriteString(", ") - sb.WriteString(role) - } - } - - if len(roles) != 1 { - sb.WriteString(")") - } - - return sb.String() -} - -func (r *Role) getRoles() []string { - var names []string - r.rangeRoles(func(key, value interface{}) bool { - names = append(names, key.(string)) - return true - }) - return util.RemoveDuplicateElement(names) -} - -func (r *Role) getUsers() []string { - var names []string - r.rangeUsers(func(key, value interface{}) bool { - names = append(names, key.(string)) - return true - }) - return names -} - -type linkConditionFuncKey struct { - roleName string - domainName string -} - -func (r *Role) addLinkConditionFunc(role *Role, domain string, fn rbac.LinkConditionFunc) { - r.linkConditionFuncMap.Store(linkConditionFuncKey{role.name, domain}, fn) -} - -func (r *Role) getLinkConditionFunc(role *Role, domain string) (rbac.LinkConditionFunc, bool) { - fn, ok := r.linkConditionFuncMap.Load(linkConditionFuncKey{role.name, domain}) - if fn == nil { - return nil, ok - } - return fn.(rbac.LinkConditionFunc), ok -} - -func (r *Role) setLinkConditionFuncParams(role *Role, domain string, params ...string) { - r.linkConditionFuncParamsMap.Store(linkConditionFuncKey{role.name, domain}, params) -} - -func (r *Role) getLinkConditionFuncParams(role *Role, domain string) ([]string, bool) { - params, ok := r.linkConditionFuncParamsMap.Load(linkConditionFuncKey{role.name, domain}) - if params == nil { - return nil, ok - } - return params.([]string), ok -} - -// RoleManagerImpl provides a default implementation for the RoleManager interface. -type RoleManagerImpl struct { - allRoles *sync.Map - maxHierarchyLevel int - matchingFunc rbac.MatchingFunc - domainMatchingFunc rbac.MatchingFunc - logger log.Logger - matchingFuncCache *util.SyncLRUCache -} - -// NewRoleManagerImpl is the constructor for creating an instance of the -// default RoleManager implementation. -func NewRoleManagerImpl(maxHierarchyLevel int) *RoleManagerImpl { - rm := RoleManagerImpl{} - _ = rm.Clear() // init allRoles and matchingFuncCache - rm.maxHierarchyLevel = maxHierarchyLevel - rm.SetLogger(&log.DefaultLogger{}) - return &rm -} - -// use this constructor to avoid rebuild of AddMatchingFunc. -func newRoleManagerWithMatchingFunc(maxHierarchyLevel int, fn rbac.MatchingFunc) *RoleManagerImpl { - rm := NewRoleManagerImpl(maxHierarchyLevel) - rm.matchingFunc = fn - return rm -} - -// rebuilds role cache. -func (rm *RoleManagerImpl) rebuild() { - roles := rm.allRoles - _ = rm.Clear() - rangeLinks(roles, func(name1, name2 string, domain ...string) bool { - _ = rm.AddLink(name1, name2, domain...) - return true - }) -} - -func (rm *RoleManagerImpl) Match(str string, pattern string) bool { - if str == pattern { - return true - } - - if rm.matchingFunc != nil { - return rm.matchingFunc(str, pattern) - } else { - return false - } -} - -func (rm *RoleManagerImpl) rangeMatchingRoles(name string, isPattern bool, fn func(role *Role) bool) { - rm.allRoles.Range(func(key, value interface{}) bool { - name2 := key.(string) - if isPattern && name != name2 && rm.Match(name2, name) { - fn(value.(*Role)) - } else if !isPattern && name != name2 && rm.Match(name, name2) { - fn(value.(*Role)) - } - return true - }) -} - -func (rm *RoleManagerImpl) load(name interface{}) (value *Role, ok bool) { - if r, ok := rm.allRoles.Load(name); ok { - return r.(*Role), true - } - return nil, false -} - -// loads or creates a role. -func (rm *RoleManagerImpl) getRole(name string) (r *Role, created bool) { - var role *Role - var ok bool - - if role, ok = rm.load(name); !ok { - role = newRole(name) - rm.allRoles.Store(name, role) - - if rm.matchingFunc != nil { - rm.rangeMatchingRoles(name, false, func(r *Role) bool { - r.addMatch(role) - return true - }) - - rm.rangeMatchingRoles(name, true, func(r *Role) bool { - role.addMatch(r) - return true - }) - } - } - - return role, !ok -} - -func loadAndDelete(m *sync.Map, name string) (value interface{}, loaded bool) { - value, loaded = m.Load(name) - if loaded { - m.Delete(name) - } - return value, loaded -} - -func (rm *RoleManagerImpl) removeRole(name string) { - if role, ok := loadAndDelete(rm.allRoles, name); ok { - role.(*Role).removeMatches() - } -} - -// AddMatchingFunc support use pattern in g. -func (rm *RoleManagerImpl) AddMatchingFunc(name string, fn rbac.MatchingFunc) { - rm.matchingFunc = fn - rm.rebuild() -} - -// AddDomainMatchingFunc support use domain pattern in g. -func (rm *RoleManagerImpl) AddDomainMatchingFunc(name string, fn rbac.MatchingFunc) { - rm.domainMatchingFunc = fn -} - -// SetLogger sets role manager's logger. -func (rm *RoleManagerImpl) SetLogger(logger log.Logger) { - rm.logger = logger -} - -// Clear clears all stored data and resets the role manager to the initial state. -func (rm *RoleManagerImpl) Clear() error { - rm.matchingFuncCache = util.NewSyncLRUCache(100) - rm.allRoles = &sync.Map{} - return nil -} - -// AddLink adds the inheritance link between role: name1 and role: name2. -// aka role: name1 inherits role: name2. -func (rm *RoleManagerImpl) AddLink(name1 string, name2 string, domains ...string) error { - user, _ := rm.getRole(name1) - role, _ := rm.getRole(name2) - user.addRole(role) - return nil -} - -// DeleteLink deletes the inheritance link between role: name1 and role: name2. -// aka role: name1 does not inherit role: name2 any more. -func (rm *RoleManagerImpl) DeleteLink(name1 string, name2 string, domains ...string) error { - user, _ := rm.getRole(name1) - role, _ := rm.getRole(name2) - user.removeRole(role) - return nil -} - -// HasLink determines whether role: name1 inherits role: name2. -func (rm *RoleManagerImpl) HasLink(name1 string, name2 string, domains ...string) (bool, error) { - if name1 == name2 || (rm.matchingFunc != nil && rm.Match(name1, name2)) { - return true, nil - } - - user, userCreated := rm.getRole(name1) - role, roleCreated := rm.getRole(name2) - - if userCreated { - defer rm.removeRole(user.name) - } - if roleCreated { - defer rm.removeRole(role.name) - } - - return rm.hasLinkHelper(role.name, map[string]*Role{user.name: user}, rm.maxHierarchyLevel), nil -} - -func (rm *RoleManagerImpl) hasLinkHelper(targetName string, roles map[string]*Role, level int) bool { - if level < 0 || len(roles) == 0 { - return false - } - - nextRoles := map[string]*Role{} - for _, role := range roles { - if targetName == role.name || (rm.matchingFunc != nil && rm.Match(role.name, targetName)) { - return true - } - role.rangeRoles(func(key, value interface{}) bool { - nextRoles[key.(string)] = value.(*Role) - return true - }) - } - - return rm.hasLinkHelper(targetName, nextRoles, level-1) -} - -// GetRoles gets the roles that a user inherits. -func (rm *RoleManagerImpl) GetRoles(name string, domains ...string) ([]string, error) { - user, created := rm.getRole(name) - if created { - defer rm.removeRole(user.name) - } - return user.getRoles(), nil -} - -// GetUsers gets the users of a role. -// domain is an unreferenced parameter here, may be used in other implementations. -func (rm *RoleManagerImpl) GetUsers(name string, domain ...string) ([]string, error) { - role, created := rm.getRole(name) - if created { - defer rm.removeRole(role.name) - } - return role.getUsers(), nil -} - -func (rm *RoleManagerImpl) toString() []string { - var roles []string - - rm.allRoles.Range(func(key, value interface{}) bool { - role := value.(*Role) - if text := role.toString(); text != "" { - roles = append(roles, text) - } - return true - }) - - return roles -} - -// PrintRoles prints all the roles to log. -func (rm *RoleManagerImpl) PrintRoles() error { - if !(rm.logger).IsEnabled() { - return nil - } - roles := rm.toString() - rm.logger.LogRole(roles) - return nil -} - -// GetDomains gets domains that a user has. -func (rm *RoleManagerImpl) GetDomains(name string) ([]string, error) { - domains := []string{defaultDomain} - return domains, nil -} - -// GetAllDomains gets all domains. -func (rm *RoleManagerImpl) GetAllDomains() ([]string, error) { - domains := []string{defaultDomain} - return domains, nil -} - -func (rm *RoleManagerImpl) copyFrom(other *RoleManagerImpl) { - other.Range(func(name1, name2 string, domain ...string) bool { - _ = rm.AddLink(name1, name2, domain...) - return true - }) -} - -func rangeLinks(users *sync.Map, fn func(name1, name2 string, domain ...string) bool) { - users.Range(func(_, value interface{}) bool { - user := value.(*Role) - user.roles.Range(func(key, _ interface{}) bool { - roleName := key.(string) - return fn(user.name, roleName, defaultDomain) - }) - return true - }) -} - -func (rm *RoleManagerImpl) Range(fn func(name1, name2 string, domain ...string) bool) { - rangeLinks(rm.allRoles, fn) -} - -// Deprecated: BuildRelationship is no longer required. -func (rm *RoleManagerImpl) BuildRelationship(name1 string, name2 string, domain ...string) error { - return nil -} - -type DomainManager struct { - rmMap *sync.Map - maxHierarchyLevel int - matchingFunc rbac.MatchingFunc - domainMatchingFunc rbac.MatchingFunc - logger log.Logger - matchingFuncCache *util.SyncLRUCache -} - -// NewDomainManager is the constructor for creating an instance of the -// default DomainManager implementation. -func NewDomainManager(maxHierarchyLevel int) *DomainManager { - dm := &DomainManager{} - _ = dm.Clear() // init rmMap and rmCache - dm.maxHierarchyLevel = maxHierarchyLevel - return dm -} - -// SetLogger sets role manager's logger. -func (dm *DomainManager) SetLogger(logger log.Logger) { - dm.logger = logger -} - -// AddMatchingFunc support use pattern in g. -func (dm *DomainManager) AddMatchingFunc(name string, fn rbac.MatchingFunc) { - dm.matchingFunc = fn - dm.rmMap.Range(func(key, value interface{}) bool { - value.(*RoleManagerImpl).AddMatchingFunc(name, fn) - return true - }) -} - -// AddDomainMatchingFunc support use domain pattern in g. -func (dm *DomainManager) AddDomainMatchingFunc(name string, fn rbac.MatchingFunc) { - dm.domainMatchingFunc = fn - dm.rmMap.Range(func(key, value interface{}) bool { - value.(*RoleManagerImpl).AddDomainMatchingFunc(name, fn) - return true - }) - dm.rebuild() -} - -// clears the map of RoleManagers. -func (dm *DomainManager) rebuild() { - rmMap := dm.rmMap - _ = dm.Clear() - rmMap.Range(func(key, value interface{}) bool { - domain := key.(string) - rm := value.(*RoleManagerImpl) - - rm.Range(func(name1, name2 string, _ ...string) bool { - _ = dm.AddLink(name1, name2, domain) - return true - }) - return true - }) -} - -// Clear clears all stored data and resets the role manager to the initial state. -func (dm *DomainManager) Clear() error { - dm.rmMap = &sync.Map{} - dm.matchingFuncCache = util.NewSyncLRUCache(100) - return nil -} - -func (dm *DomainManager) getDomain(domains ...string) (domain string, err error) { - switch len(domains) { - case 0: - return defaultDomain, nil - default: - return domains[0], nil - } -} - -func (dm *DomainManager) Match(str string, pattern string) bool { - if str == pattern { - return true - } - - if dm.domainMatchingFunc != nil { - return dm.domainMatchingFunc(str, pattern) - } else { - return false - } -} - -func (dm *DomainManager) rangeAffectedRoleManagers(domain string, fn func(rm *RoleManagerImpl)) { - if dm.domainMatchingFunc != nil { - dm.rmMap.Range(func(key, value interface{}) bool { - domain2 := key.(string) - if domain != domain2 && dm.Match(domain2, domain) { - fn(value.(*RoleManagerImpl)) - } - return true - }) - } -} - -func (dm *DomainManager) load(name interface{}) (value *RoleManagerImpl, ok bool) { - if r, ok := dm.rmMap.Load(name); ok { - return r.(*RoleManagerImpl), true - } - return nil, false -} - -// load or create a RoleManager instance of domain. -func (dm *DomainManager) getRoleManager(domain string, store bool) *RoleManagerImpl { - var rm *RoleManagerImpl - var ok bool - - if rm, ok = dm.load(domain); !ok { - rm = newRoleManagerWithMatchingFunc(dm.maxHierarchyLevel, dm.matchingFunc) - if store { - dm.rmMap.Store(domain, rm) - } - if dm.domainMatchingFunc != nil { - dm.rmMap.Range(func(key, value interface{}) bool { - domain2 := key.(string) - rm2 := value.(*RoleManagerImpl) - if domain != domain2 && dm.Match(domain, domain2) { - rm.copyFrom(rm2) - } - return true - }) - } - } - return rm -} - -// AddLink adds the inheritance link between role: name1 and role: name2. -// aka role: name1 inherits role: name2. -func (dm *DomainManager) AddLink(name1 string, name2 string, domains ...string) error { - domain, err := dm.getDomain(domains...) - if err != nil { - return err - } - roleManager := dm.getRoleManager(domain, true) // create role manager if it does not exist - _ = roleManager.AddLink(name1, name2, domains...) - - dm.rangeAffectedRoleManagers(domain, func(rm *RoleManagerImpl) { - _ = rm.AddLink(name1, name2, domains...) - }) - return nil -} - -// DeleteLink deletes the inheritance link between role: name1 and role: name2. -// aka role: name1 does not inherit role: name2 any more. -func (dm *DomainManager) DeleteLink(name1 string, name2 string, domains ...string) error { - domain, err := dm.getDomain(domains...) - if err != nil { - return err - } - roleManager := dm.getRoleManager(domain, true) // create role manager if it does not exist - _ = roleManager.DeleteLink(name1, name2, domains...) - - dm.rangeAffectedRoleManagers(domain, func(rm *RoleManagerImpl) { - _ = rm.DeleteLink(name1, name2, domains...) - }) - return nil -} - -// HasLink determines whether role: name1 inherits role: name2. -func (dm *DomainManager) HasLink(name1 string, name2 string, domains ...string) (bool, error) { - domain, err := dm.getDomain(domains...) - if err != nil { - return false, err - } - rm := dm.getRoleManager(domain, false) - return rm.HasLink(name1, name2, domains...) -} - -// GetRoles gets the roles that a subject inherits. -func (dm *DomainManager) GetRoles(name string, domains ...string) ([]string, error) { - domain, err := dm.getDomain(domains...) - if err != nil { - return nil, err - } - rm := dm.getRoleManager(domain, false) - return rm.GetRoles(name, domains...) -} - -// GetUsers gets the users of a role. -func (dm *DomainManager) GetUsers(name string, domains ...string) ([]string, error) { - domain, err := dm.getDomain(domains...) - if err != nil { - return nil, err - } - rm := dm.getRoleManager(domain, false) - return rm.GetUsers(name, domains...) -} - -func (dm *DomainManager) toString() []string { - var roles []string - - dm.rmMap.Range(func(key, value interface{}) bool { - domain := key.(string) - rm := value.(*RoleManagerImpl) - domainRoles := rm.toString() - roles = append(roles, fmt.Sprintf("%s: %s", domain, strings.Join(domainRoles, ", "))) - return true - }) - - return roles -} - -// PrintRoles prints all the roles to log. -func (dm *DomainManager) PrintRoles() error { - if !(dm.logger).IsEnabled() { - return nil - } - - roles := dm.toString() - dm.logger.LogRole(roles) - return nil -} - -// GetDomains gets domains that a user has. -func (dm *DomainManager) GetDomains(name string) ([]string, error) { - var domains []string - dm.rmMap.Range(func(key, value interface{}) bool { - domain := key.(string) - rm := value.(*RoleManagerImpl) - role, created := rm.getRole(name) - if created { - defer rm.removeRole(role.name) - } - if len(role.getUsers()) > 0 || len(role.getRoles()) > 0 { - domains = append(domains, domain) - } - return true - }) - return domains, nil -} - -// GetAllDomains gets all domains. -func (dm *DomainManager) GetAllDomains() ([]string, error) { - var domains []string - dm.rmMap.Range(func(key, value interface{}) bool { - domains = append(domains, key.(string)) - return true - }) - return domains, nil -} - -// Deprecated: BuildRelationship is no longer required. -func (dm *DomainManager) BuildRelationship(name1 string, name2 string, domain ...string) error { - return nil -} - -type RoleManager struct { - *DomainManager -} - -func NewRoleManager(maxHierarchyLevel int) *RoleManager { - rm := &RoleManager{} - rm.DomainManager = NewDomainManager(maxHierarchyLevel) - return rm -} - -type ConditionalRoleManager struct { - RoleManagerImpl -} - -func (crm *ConditionalRoleManager) copyFrom(other *ConditionalRoleManager) { - other.Range(func(name1, name2 string, domain ...string) bool { - _ = crm.AddLink(name1, name2, domain...) - return true - }) -} - -// use this constructor to avoid rebuild of AddMatchingFunc. -func newConditionalRoleManagerWithMatchingFunc(maxHierarchyLevel int, fn rbac.MatchingFunc) *ConditionalRoleManager { - rm := NewConditionalRoleManager(maxHierarchyLevel) - rm.matchingFunc = fn - return rm -} - -// NewConditionalRoleManager is the constructor for creating an instance of the -// ConditionalRoleManager implementation. -func NewConditionalRoleManager(maxHierarchyLevel int) *ConditionalRoleManager { - rm := ConditionalRoleManager{} - _ = rm.Clear() // init allRoles and matchingFuncCache - rm.maxHierarchyLevel = maxHierarchyLevel - rm.SetLogger(&log.DefaultLogger{}) - return &rm -} - -// HasLink determines whether role: name1 inherits role: name2. -func (crm *ConditionalRoleManager) HasLink(name1 string, name2 string, domains ...string) (bool, error) { - if name1 == name2 || (crm.matchingFunc != nil && crm.Match(name1, name2)) { - return true, nil - } - - user, userCreated := crm.getRole(name1) - role, roleCreated := crm.getRole(name2) - - if userCreated { - defer crm.removeRole(user.name) - } - if roleCreated { - defer crm.removeRole(role.name) - } - - return crm.hasLinkHelper(role.name, map[string]*Role{user.name: user}, crm.maxHierarchyLevel, domains...), nil -} - -// hasLinkHelper use the Breadth First Search algorithm to traverse the Role tree -// Judging whether the user has a role (has link) is to judge whether the role node can be reached from the user node. -func (crm *ConditionalRoleManager) hasLinkHelper(targetName string, roles map[string]*Role, level int, domains ...string) bool { - if level < 0 || len(roles) == 0 { - return false - } - nextRoles := map[string]*Role{} - for _, role := range roles { - if targetName == role.name || (crm.matchingFunc != nil && crm.Match(role.name, targetName)) { - return true - } - role.rangeRoles(func(key, value interface{}) bool { - nextRole := value.(*Role) - return crm.getNextRoles(role, nextRole, domains, nextRoles) - }) - } - - return crm.hasLinkHelper(targetName, nextRoles, level-1) -} - -func (crm *ConditionalRoleManager) getNextRoles(currentRole, nextRole *Role, domains []string, nextRoles map[string]*Role) bool { - passLinkConditionFunc := true - var err error - // If LinkConditionFunc exists, it needs to pass the verification to get nextRole - if len(domains) == 0 { - if linkConditionFunc, existLinkCondition := crm.GetLinkConditionFunc(currentRole.name, nextRole.name); existLinkCondition { - params, _ := crm.GetLinkConditionFuncParams(currentRole.name, nextRole.name) - passLinkConditionFunc, err = linkConditionFunc(params...) - } - } else { - if linkConditionFunc, existLinkCondition := crm.GetDomainLinkConditionFunc(currentRole.name, nextRole.name, domains[0]); existLinkCondition { - params, _ := crm.GetLinkConditionFuncParams(currentRole.name, nextRole.name, domains[0]) - passLinkConditionFunc, err = linkConditionFunc(params...) - } - } - - if err != nil { - crm.logger.LogError(err, "hasLinkHelper LinkCondition Error") - return false - } - - if passLinkConditionFunc { - nextRoles[nextRole.name] = nextRole - } - - return true -} - -// GetLinkConditionFunc get LinkConditionFunc based on userName, roleName. -func (crm *ConditionalRoleManager) GetLinkConditionFunc(userName, roleName string) (rbac.LinkConditionFunc, bool) { - return crm.GetDomainLinkConditionFunc(userName, roleName, defaultDomain) -} - -// GetDomainLinkConditionFunc get LinkConditionFunc based on userName, roleName, domain. -func (crm *ConditionalRoleManager) GetDomainLinkConditionFunc(userName, roleName, domain string) (rbac.LinkConditionFunc, bool) { - user, userCreated := crm.getRole(userName) - role, roleCreated := crm.getRole(roleName) - - if userCreated { - crm.removeRole(user.name) - return nil, false - } - - if roleCreated { - crm.removeRole(role.name) - return nil, false - } - - return user.getLinkConditionFunc(role, domain) -} - -// GetLinkConditionFuncParams gets parameters of LinkConditionFunc based on userName, roleName, domain. -func (crm *ConditionalRoleManager) GetLinkConditionFuncParams(userName, roleName string, domain ...string) ([]string, bool) { - user, userCreated := crm.getRole(userName) - role, roleCreated := crm.getRole(roleName) - - if userCreated { - crm.removeRole(user.name) - return nil, false - } - - if roleCreated { - crm.removeRole(role.name) - return nil, false - } - - domainName := defaultDomain - if len(domain) != 0 { - domainName = domain[0] - } - - if params, ok := user.getLinkConditionFuncParams(role, domainName); ok { - return params, true - } else { - return nil, false - } -} - -// AddLinkConditionFunc is based on userName, roleName, add LinkConditionFunc. -func (crm *ConditionalRoleManager) AddLinkConditionFunc(userName, roleName string, fn rbac.LinkConditionFunc) { - crm.AddDomainLinkConditionFunc(userName, roleName, defaultDomain, fn) -} - -// AddDomainLinkConditionFunc is based on userName, roleName, domain, add LinkConditionFunc. -func (crm *ConditionalRoleManager) AddDomainLinkConditionFunc(userName, roleName, domain string, fn rbac.LinkConditionFunc) { - user, _ := crm.getRole(userName) - role, _ := crm.getRole(roleName) - - user.addLinkConditionFunc(role, domain, fn) -} - -// SetLinkConditionFuncParams sets parameters of LinkConditionFunc based on userName, roleName, domain. -func (crm *ConditionalRoleManager) SetLinkConditionFuncParams(userName, roleName string, params ...string) { - crm.SetDomainLinkConditionFuncParams(userName, roleName, defaultDomain, params...) -} - -// SetDomainLinkConditionFuncParams sets parameters of LinkConditionFunc based on userName, roleName, domain. -func (crm *ConditionalRoleManager) SetDomainLinkConditionFuncParams(userName, roleName, domain string, params ...string) { - user, _ := crm.getRole(userName) - role, _ := crm.getRole(roleName) - - user.setLinkConditionFuncParams(role, domain, params...) -} - -type ConditionalDomainManager struct { - ConditionalRoleManager - DomainManager -} - -// NewConditionalDomainManager is the constructor for creating an instance of the -// ConditionalDomainManager implementation. -func NewConditionalDomainManager(maxHierarchyLevel int) *ConditionalDomainManager { - rm := ConditionalDomainManager{} - _ = rm.Clear() // init allRoles and matchingFuncCache - rm.maxHierarchyLevel = maxHierarchyLevel - rm.SetLogger(&log.DefaultLogger{}) - return &rm -} - -func (cdm *ConditionalDomainManager) load(name interface{}) (value *ConditionalRoleManager, ok bool) { - if r, ok := cdm.rmMap.Load(name); ok { - return r.(*ConditionalRoleManager), true - } - return nil, false -} - -// load or create a ConditionalRoleManager instance of domain. -func (cdm *ConditionalDomainManager) getConditionalRoleManager(domain string, store bool) *ConditionalRoleManager { - var rm *ConditionalRoleManager - var ok bool - - if rm, ok = cdm.load(domain); !ok { - rm = newConditionalRoleManagerWithMatchingFunc(cdm.maxHierarchyLevel, cdm.matchingFunc) - if store { - cdm.rmMap.Store(domain, rm) - } - if cdm.domainMatchingFunc != nil { - cdm.rmMap.Range(func(key, value interface{}) bool { - domain2 := key.(string) - rm2 := value.(*ConditionalRoleManager) - if domain != domain2 && cdm.Match(domain, domain2) { - rm.copyFrom(rm2) - } - return true - }) - } - } - return rm -} - -// HasLink determines whether role: name1 inherits role: name2. -func (cdm *ConditionalDomainManager) HasLink(name1 string, name2 string, domains ...string) (bool, error) { - domain, err := cdm.getDomain(domains...) - if err != nil { - return false, err - } - rm := cdm.getConditionalRoleManager(domain, false) - return rm.HasLink(name1, name2, domains...) -} - -// AddLink adds the inheritance link between role: name1 and role: name2. -// aka role: name1 inherits role: name2. -func (cdm *ConditionalDomainManager) AddLink(name1 string, name2 string, domains ...string) error { - domain, err := cdm.getDomain(domains...) - if err != nil { - return err - } - conditionalRoleManager := cdm.getConditionalRoleManager(domain, true) // create role manager if it does not exist - _ = conditionalRoleManager.AddLink(name1, name2, domain) - - cdm.rangeAffectedRoleManagers(domain, func(rm *RoleManagerImpl) { - _ = rm.AddLink(name1, name2, domain) - }) - return nil -} - -// DeleteLink deletes the inheritance link between role: name1 and role: name2. -// aka role: name1 does not inherit role: name2 any more. -func (cdm *ConditionalDomainManager) DeleteLink(name1 string, name2 string, domains ...string) error { - domain, err := cdm.getDomain(domains...) - if err != nil { - return err - } - conditionalRoleManager := cdm.getConditionalRoleManager(domain, true) // create role manager if it does not exist - _ = conditionalRoleManager.DeleteLink(name1, name2, domain) - - cdm.rangeAffectedRoleManagers(domain, func(rm *RoleManagerImpl) { - _ = rm.DeleteLink(name1, name2, domain) - }) - return nil -} - -// AddLinkConditionFunc is based on userName, roleName, add LinkConditionFunc. -func (cdm *ConditionalDomainManager) AddLinkConditionFunc(userName, roleName string, fn rbac.LinkConditionFunc) { - cdm.rmMap.Range(func(key, value interface{}) bool { - value.(*ConditionalRoleManager).AddLinkConditionFunc(userName, roleName, fn) - return true - }) -} - -// AddDomainLinkConditionFunc is based on userName, roleName, domain, add LinkConditionFunc. -func (cdm *ConditionalDomainManager) AddDomainLinkConditionFunc(userName, roleName, domain string, fn rbac.LinkConditionFunc) { - cdm.rmMap.Range(func(key, value interface{}) bool { - value.(*ConditionalRoleManager).AddDomainLinkConditionFunc(userName, roleName, domain, fn) - return true - }) -} - -// SetLinkConditionFuncParams sets parameters of LinkConditionFunc based on userName, roleName. -func (cdm *ConditionalDomainManager) SetLinkConditionFuncParams(userName, roleName string, params ...string) { - cdm.rmMap.Range(func(key, value interface{}) bool { - value.(*ConditionalRoleManager).SetLinkConditionFuncParams(userName, roleName, params...) - return true - }) -} - -// SetDomainLinkConditionFuncParams sets parameters of LinkConditionFunc based on userName, roleName, domain. -func (cdm *ConditionalDomainManager) SetDomainLinkConditionFuncParams(userName, roleName, domain string, params ...string) { - cdm.rmMap.Range(func(key, value interface{}) bool { - value.(*ConditionalRoleManager).SetDomainLinkConditionFuncParams(userName, roleName, domain, params...) - return true - }) -} diff --git a/vendor/github.com/casbin/casbin/v2/rbac/role_manager.go b/vendor/github.com/casbin/casbin/v2/rbac/role_manager.go deleted file mode 100644 index 28b40a35..00000000 --- a/vendor/github.com/casbin/casbin/v2/rbac/role_manager.go +++ /dev/null @@ -1,76 +0,0 @@ -// 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 rbac - -import "github.com/casbin/casbin/v2/log" - -type MatchingFunc func(arg1 string, arg2 string) bool - -type LinkConditionFunc = func(args ...string) (bool, error) - -// RoleManager provides interface to define the operations for managing roles. -type RoleManager interface { - // Clear clears all stored data and resets the role manager to the initial state. - Clear() error - // AddLink adds the inheritance link between two roles. role: name1 and role: name2. - // domain is a prefix to the roles (can be used for other purposes). - AddLink(name1 string, name2 string, domain ...string) error - // Deprecated: BuildRelationship is no longer required - BuildRelationship(name1 string, name2 string, domain ...string) error - // DeleteLink deletes the inheritance link between two roles. role: name1 and role: name2. - // domain is a prefix to the roles (can be used for other purposes). - DeleteLink(name1 string, name2 string, domain ...string) error - // HasLink determines whether a link exists between two roles. role: name1 inherits role: name2. - // domain is a prefix to the roles (can be used for other purposes). - HasLink(name1 string, name2 string, domain ...string) (bool, error) - // GetRoles gets the roles that a user inherits. - // domain is a prefix to the roles (can be used for other purposes). - GetRoles(name string, domain ...string) ([]string, error) - // GetUsers gets the users that inherits a role. - // domain is a prefix to the users (can be used for other purposes). - GetUsers(name string, domain ...string) ([]string, error) - // GetDomains gets domains that a user has - GetDomains(name string) ([]string, error) - // GetAllDomains gets all domains - GetAllDomains() ([]string, error) - // PrintRoles prints all the roles to log. - PrintRoles() error - // SetLogger sets role manager's logger. - SetLogger(logger log.Logger) - // Match matches the domain with the pattern - Match(str string, pattern string) bool - // AddMatchingFunc adds the matching function - AddMatchingFunc(name string, fn MatchingFunc) - // AddDomainMatchingFunc adds the domain matching function - AddDomainMatchingFunc(name string, fn MatchingFunc) -} - -// ConditionalRoleManager provides interface to define the operations for managing roles. -// Link with conditions is supported. -type ConditionalRoleManager interface { - RoleManager - - // AddLinkConditionFunc Add condition function fn for Link userName->roleName, - // when fn returns true, Link is valid, otherwise invalid - AddLinkConditionFunc(userName, roleName string, fn LinkConditionFunc) - // SetLinkConditionFuncParams Sets the parameters of the condition function fn for Link userName->roleName - SetLinkConditionFuncParams(userName, roleName string, params ...string) - // AddDomainLinkConditionFunc Add condition function fn for Link userName-> {roleName, domain}, - // when fn returns true, Link is valid, otherwise invalid - AddDomainLinkConditionFunc(user string, role string, domain string, fn LinkConditionFunc) - // SetDomainLinkConditionFuncParams Sets the parameters of the condition function fn - // for Link userName->{roleName, domain} - SetDomainLinkConditionFuncParams(user string, role string, domain string, params ...string) -} diff --git a/vendor/github.com/casbin/casbin/v2/rbac_api.go b/vendor/github.com/casbin/casbin/v2/rbac_api.go deleted file mode 100644 index fe2a6e7a..00000000 --- a/vendor/github.com/casbin/casbin/v2/rbac_api.go +++ /dev/null @@ -1,644 +0,0 @@ -// 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 ( - "fmt" - "strings" - - "github.com/casbin/casbin/v2/constant" - "github.com/casbin/casbin/v2/errors" - "github.com/casbin/casbin/v2/util" -) - -// GetRolesForUser gets the roles that a user has. -func (e *Enforcer) GetRolesForUser(name string, domain ...string) ([]string, error) { - rm := e.GetRoleManager() - if rm == nil { - return nil, fmt.Errorf("role manager is not initialized") - } - res, err := rm.GetRoles(name, domain...) - return res, err -} - -// GetUsersForRole gets the users that has a role. -func (e *Enforcer) GetUsersForRole(name string, domain ...string) ([]string, error) { - rm := e.GetRoleManager() - if rm == nil { - return nil, fmt.Errorf("role manager is not initialized") - } - res, err := rm.GetUsers(name, domain...) - return res, err -} - -// HasRoleForUser determines whether a user has a role. -func (e *Enforcer) HasRoleForUser(name string, role string, domain ...string) (bool, error) { - roles, err := e.GetRolesForUser(name, domain...) - if err != nil { - return false, err - } - hasRole := false - for _, r := range roles { - if r == role { - hasRole = true - break - } - } - - return hasRole, nil -} - -// AddRoleForUser adds a role for a user. -// Returns false if the user already has the role (aka not affected). -func (e *Enforcer) AddRoleForUser(user string, role string, domain ...string) (bool, error) { - args := []string{user, role} - args = append(args, domain...) - return e.AddGroupingPolicy(args) -} - -// AddRolesForUser adds roles for a user. -// Returns false if the user already has the roles (aka not affected). -func (e *Enforcer) AddRolesForUser(user string, roles []string, domain ...string) (bool, error) { - var rules [][]string - for _, role := range roles { - rule := []string{user, role} - rule = append(rule, domain...) - rules = append(rules, rule) - } - return e.AddGroupingPolicies(rules) -} - -// DeleteRoleForUser deletes a role for a user. -// Returns false if the user does not have the role (aka not affected). -func (e *Enforcer) DeleteRoleForUser(user string, role string, domain ...string) (bool, error) { - args := []string{user, role} - args = append(args, domain...) - return e.RemoveGroupingPolicy(args) -} - -// DeleteRolesForUser deletes all roles for a user. -// Returns false if the user does not have any roles (aka not affected). -func (e *Enforcer) DeleteRolesForUser(user string, domain ...string) (bool, error) { - var args []string - if len(domain) == 0 { - args = []string{user} - } else if len(domain) > 1 { - return false, errors.ErrDomainParameter - } else { - args = []string{user, "", domain[0]} - } - return e.RemoveFilteredGroupingPolicy(0, args...) -} - -// DeleteUser deletes a user. -// Returns false if the user does not exist (aka not affected). -func (e *Enforcer) DeleteUser(user string) (bool, error) { - var err error - res1, err := e.RemoveFilteredGroupingPolicy(0, user) - if err != nil { - return res1, err - } - - subIndex, err := e.GetFieldIndex("p", constant.SubjectIndex) - if err != nil { - return false, err - } - res2, err := e.RemoveFilteredPolicy(subIndex, user) - return res1 || res2, err -} - -// DeleteRole deletes a role. -// Returns false if the role does not exist (aka not affected). -func (e *Enforcer) DeleteRole(role string) (bool, error) { - var err error - res1, err := e.RemoveFilteredGroupingPolicy(0, role) - if err != nil { - return res1, err - } - - res2, err := e.RemoveFilteredGroupingPolicy(1, role) - if err != nil { - return res1, err - } - - subIndex, err := e.GetFieldIndex("p", constant.SubjectIndex) - if err != nil { - return false, err - } - res3, err := e.RemoveFilteredPolicy(subIndex, role) - return res1 || res2 || res3, err -} - -// DeletePermission deletes a permission. -// Returns false if the permission does not exist (aka not affected). -func (e *Enforcer) DeletePermission(permission ...string) (bool, error) { - return e.RemoveFilteredPolicy(1, permission...) -} - -// AddPermissionForUser adds a permission for a user or role. -// Returns false if the user or role already has the permission (aka not affected). -func (e *Enforcer) AddPermissionForUser(user string, permission ...string) (bool, error) { - return e.AddPolicy(util.JoinSlice(user, permission...)) -} - -// AddPermissionsForUser adds multiple permissions for a user or role. -// Returns false if the user or role already has one of the permissions (aka not affected). -func (e *Enforcer) AddPermissionsForUser(user string, permissions ...[]string) (bool, error) { - var rules [][]string - for _, permission := range permissions { - rules = append(rules, util.JoinSlice(user, permission...)) - } - return e.AddPolicies(rules) -} - -// DeletePermissionForUser deletes a permission for a user or role. -// Returns false if the user or role does not have the permission (aka not affected). -func (e *Enforcer) DeletePermissionForUser(user string, permission ...string) (bool, error) { - return e.RemovePolicy(util.JoinSlice(user, permission...)) -} - -// DeletePermissionsForUser deletes permissions for a user or role. -// Returns false if the user or role does not have any permissions (aka not affected). -func (e *Enforcer) DeletePermissionsForUser(user string) (bool, error) { - subIndex, err := e.GetFieldIndex("p", constant.SubjectIndex) - if err != nil { - return false, err - } - return e.RemoveFilteredPolicy(subIndex, user) -} - -// GetPermissionsForUser gets permissions for a user or role. -func (e *Enforcer) GetPermissionsForUser(user string, domain ...string) ([][]string, error) { - return e.GetNamedPermissionsForUser("p", user, domain...) -} - -// GetNamedPermissionsForUser gets permissions for a user or role by named policy. -func (e *Enforcer) GetNamedPermissionsForUser(ptype string, user string, domain ...string) ([][]string, error) { - permission := make([][]string, 0) - for pType, assertion := range e.model["p"] { - if pType != ptype { - continue - } - args := make([]string, len(assertion.Tokens)) - subIndex, err := e.GetFieldIndex("p", constant.SubjectIndex) - if err != nil { - subIndex = 0 - } - args[subIndex] = user - - if len(domain) > 0 { - var index int - index, err = e.GetFieldIndex(ptype, constant.DomainIndex) - if err != nil { - return permission, err - } - args[index] = domain[0] - } - perm, err := e.GetFilteredNamedPolicy(ptype, 0, args...) - if err != nil { - return permission, err - } - permission = append(permission, perm...) - } - return permission, nil -} - -// HasPermissionForUser determines whether a user has a permission. -func (e *Enforcer) HasPermissionForUser(user string, permission ...string) (bool, error) { - return e.HasPolicy(util.JoinSlice(user, permission...)) -} - -// GetImplicitRolesForUser gets implicit roles that a user has. -// Compared to GetRolesForUser(), this function retrieves indirect roles besides direct roles. -// For example: -// g, alice, role:admin -// g, role:admin, role:user -// -// GetRolesForUser("alice") can only get: ["role:admin"]. -// But GetImplicitRolesForUser("alice") will get: ["role:admin", "role:user"]. -func (e *Enforcer) GetImplicitRolesForUser(name string, domain ...string) ([]string, error) { - var res []string - - for v := range e.rmMap { - roles, err := e.GetNamedImplicitRolesForUser(v, name, domain...) - if err != nil { - return nil, err - } - res = append(res, roles...) - } - - return res, nil -} - -// GetNamedImplicitRolesForUser gets implicit roles that a user has by named role definition. -// Compared to GetImplicitRolesForUser(), this function retrieves indirect roles besides direct roles. -// For example: -// g, alice, role:admin -// g, role:admin, role:user -// g2, alice, role:admin2 -// -// GetImplicitRolesForUser("alice") can only get: ["role:admin", "role:user"]. -// But GetNamedImplicitRolesForUser("g2", "alice") will get: ["role:admin2"]. -func (e *Enforcer) GetNamedImplicitRolesForUser(ptype string, name string, domain ...string) ([]string, error) { - var res []string - - rm := e.GetNamedRoleManager(ptype) - if rm == nil { - return nil, fmt.Errorf("role manager %s is not initialized", ptype) - } - roleSet := make(map[string]bool) - roleSet[name] = true - q := make([]string, 0) - q = append(q, name) - - for len(q) > 0 { - name := q[0] - q = q[1:] - - roles, err := rm.GetRoles(name, domain...) - if err != nil { - return nil, err - } - for _, r := range roles { - if _, ok := roleSet[r]; !ok { - res = append(res, r) - q = append(q, r) - roleSet[r] = true - } - } - } - - return res, nil -} - -// GetImplicitUsersForRole gets implicit users for a role. -func (e *Enforcer) GetImplicitUsersForRole(name string, domain ...string) ([]string, error) { - res := []string{} - - for _, rm := range e.rmMap { - roleSet := make(map[string]bool) - roleSet[name] = true - q := make([]string, 0) - q = append(q, name) - - for len(q) > 0 { - name := q[0] - q = q[1:] - - roles, err := rm.GetUsers(name, domain...) - if err != nil && err.Error() != "error: name does not exist" { - return nil, err - } - for _, r := range roles { - if _, ok := roleSet[r]; !ok { - res = append(res, r) - q = append(q, r) - roleSet[r] = true - } - } - } - } - - return res, nil -} - -// GetImplicitPermissionsForUser gets implicit permissions for a user or role. -// Compared to GetPermissionsForUser(), this function retrieves permissions for inherited roles. -// For example: -// p, admin, data1, read -// p, alice, data2, read -// g, alice, admin -// -// GetPermissionsForUser("alice") can only get: [["alice", "data2", "read"]]. -// But GetImplicitPermissionsForUser("alice") will get: [["admin", "data1", "read"], ["alice", "data2", "read"]]. -func (e *Enforcer) GetImplicitPermissionsForUser(user string, domain ...string) ([][]string, error) { - return e.GetNamedImplicitPermissionsForUser("p", "g", user, domain...) -} - -// GetNamedImplicitPermissionsForUser gets implicit permissions for a user or role by named policy. -// Compared to GetNamedPermissionsForUser(), this function retrieves permissions for inherited roles. -// For example: -// p, admin, data1, read -// p2, admin, create -// g, alice, admin -// -// GetImplicitPermissionsForUser("alice") can only get: [["admin", "data1", "read"]], whose policy is default policy "p" -// But you can specify the named policy "p2" to get: [["admin", "create"]] by GetNamedImplicitPermissionsForUser("p2","alice"). -func (e *Enforcer) GetNamedImplicitPermissionsForUser(ptype string, gtype string, user string, domain ...string) ([][]string, error) { - permission := make([][]string, 0) - rm := e.GetNamedRoleManager(gtype) - if rm == nil { - return nil, fmt.Errorf("role manager %s is not initialized", gtype) - } - - roles, err := e.GetNamedImplicitRolesForUser(gtype, user, domain...) - if err != nil { - return nil, err - } - policyRoles := make(map[string]struct{}, len(roles)+1) - policyRoles[user] = struct{}{} - for _, r := range roles { - policyRoles[r] = struct{}{} - } - - domainIndex, err := e.GetFieldIndex(ptype, constant.DomainIndex) - for _, rule := range e.model["p"][ptype].Policy { - if len(domain) == 0 { - if _, ok := policyRoles[rule[0]]; ok { - permission = append(permission, deepCopyPolicy(rule)) - } - continue - } - if len(domain) > 1 { - return nil, errors.ErrDomainParameter - } - if err != nil { - return nil, err - } - d := domain[0] - matched := rm.Match(d, rule[domainIndex]) - if !matched { - continue - } - if _, ok := policyRoles[rule[0]]; ok { - newRule := deepCopyPolicy(rule) - newRule[domainIndex] = d - permission = append(permission, newRule) - } - } - return permission, nil -} - -// GetImplicitUsersForPermission gets implicit users for a permission. -// For example: -// p, admin, data1, read -// p, bob, data1, read -// g, alice, admin -// -// GetImplicitUsersForPermission("data1", "read") will get: ["alice", "bob"]. -// Note: only users will be returned, roles (2nd arg in "g") will be excluded. -func (e *Enforcer) GetImplicitUsersForPermission(permission ...string) ([]string, error) { - pSubjects, err := e.GetAllSubjects() - if err != nil { - return nil, err - } - gInherit, err := e.model.GetValuesForFieldInPolicyAllTypes("g", 1) - if err != nil { - return nil, err - } - gSubjects, err := e.model.GetValuesForFieldInPolicyAllTypes("g", 0) - if err != nil { - return nil, err - } - - subjects := append(pSubjects, gSubjects...) - util.ArrayRemoveDuplicates(&subjects) - - subjects = util.SetSubtract(subjects, gInherit) - - res := []string{} - for _, user := range subjects { - req := util.JoinSliceAny(user, permission...) - allowed, err := e.Enforce(req...) - if err != nil { - return nil, err - } - - if allowed { - res = append(res, user) - } - } - - return res, nil -} - -// GetDomainsForUser gets all domains. -func (e *Enforcer) GetDomainsForUser(user string) ([]string, error) { - var domains []string - for _, rm := range e.rmMap { - domain, err := rm.GetDomains(user) - if err != nil { - return nil, err - } - domains = append(domains, domain...) - } - return domains, nil -} - -// GetImplicitResourcesForUser returns all policies that user obtaining in domain. -func (e *Enforcer) GetImplicitResourcesForUser(user string, domain ...string) ([][]string, error) { - permissions, err := e.GetImplicitPermissionsForUser(user, domain...) - if err != nil { - return nil, err - } - res := make([][]string, 0) - for _, permission := range permissions { - if permission[0] == user { - res = append(res, permission) - continue - } - resLocal := [][]string{{user}} - tokensLength := len(permission) - t := make([][]string, 1, tokensLength) - for _, token := range permission[1:] { - tokens, err := e.GetImplicitUsersForRole(token, domain...) - if err != nil { - return nil, err - } - tokens = append(tokens, token) - t = append(t, tokens) - } - for i := 1; i < tokensLength; i++ { - n := make([][]string, 0) - for _, tokens := range t[i] { - for _, policy := range resLocal { - t := append([]string(nil), policy...) - t = append(t, tokens) - n = append(n, t) - } - } - resLocal = n - } - res = append(res, resLocal...) - } - return res, nil -} - -// deepCopyPolicy returns a deepcopy version of the policy to prevent changing policies through returned slice. -func deepCopyPolicy(src []string) []string { - newRule := make([]string, len(src)) - copy(newRule, src) - return newRule -} - -// GetAllowedObjectConditions returns a string array of object conditions that the user can access. -// For example: conditions, err := e.GetAllowedObjectConditions("alice", "read", "r.obj.") -// Note: -// -// 0. prefix: You can customize the prefix of the object conditions, and "r.obj." is commonly used as a prefix. -// After removing the prefix, the remaining part is the condition of the object. -// If there is an obj policy that does not meet the prefix requirement, an errors.ERR_OBJ_CONDITION will be returned. -// -// 1. If the 'objectConditions' array is empty, return errors.ERR_EMPTY_CONDITION -// This error is returned because some data adapters' ORM return full table data by default -// when they receive an empty condition, which tends to behave contrary to expectations.(e.g. GORM) -// If you are using an adapter that does not behave like this, you can choose to ignore this error. -func (e *Enforcer) GetAllowedObjectConditions(user string, action string, prefix string) ([]string, error) { - permissions, err := e.GetImplicitPermissionsForUser(user) - if err != nil { - return nil, err - } - - var objectConditions []string - for _, policy := range permissions { - // policy {sub, obj, act} - if policy[2] == action { - if !strings.HasPrefix(policy[1], prefix) { - return nil, errors.ErrObjCondition - } - objectConditions = append(objectConditions, strings.TrimPrefix(policy[1], prefix)) - } - } - - if len(objectConditions) == 0 { - return nil, errors.ErrEmptyCondition - } - - return objectConditions, nil -} - -// removeDuplicatePermissions Convert permissions to string as a hash to deduplicate. -func removeDuplicatePermissions(permissions [][]string) [][]string { - permissionsSet := make(map[string]bool) - res := make([][]string, 0) - for _, permission := range permissions { - permissionStr := util.ArrayToString(permission) - if permissionsSet[permissionStr] { - continue - } - permissionsSet[permissionStr] = true - res = append(res, permission) - } - return res -} - -// GetImplicitUsersForResource return implicit user based on resource. -// for example: -// p, alice, data1, read -// p, bob, data2, write -// p, data2_admin, data2, read -// p, data2_admin, data2, write -// g, alice, data2_admin -// GetImplicitUsersForResource("data2") will return [[bob data2 write] [alice data2 read] [alice data2 write]] -// GetImplicitUsersForResource("data1") will return [[alice data1 read]] -// Note: only users will be returned, roles (2nd arg in "g") will be excluded. -func (e *Enforcer) GetImplicitUsersForResource(resource string) ([][]string, error) { - permissions := make([][]string, 0) - subjectIndex, _ := e.GetFieldIndex("p", "sub") - objectIndex, _ := e.GetFieldIndex("p", "obj") - rm := e.GetRoleManager() - if rm == nil { - return nil, fmt.Errorf("role manager is not initialized") - } - - isRole := make(map[string]bool) - roles, err := e.GetAllRoles() - if err != nil { - return nil, err - } - for _, role := range roles { - isRole[role] = true - } - - for _, rule := range e.model["p"]["p"].Policy { - obj := rule[objectIndex] - if obj != resource { - continue - } - - sub := rule[subjectIndex] - - if !isRole[sub] { - permissions = append(permissions, rule) - } else { - users, err := rm.GetUsers(sub) - if err != nil { - return nil, err - } - - for _, user := range users { - implicitUserRule := deepCopyPolicy(rule) - implicitUserRule[subjectIndex] = user - permissions = append(permissions, implicitUserRule) - } - } - } - - res := removeDuplicatePermissions(permissions) - return res, nil -} - -// GetImplicitUsersForResourceByDomain return implicit user based on resource and domain. -// Compared to GetImplicitUsersForResource, domain is supported. -func (e *Enforcer) GetImplicitUsersForResourceByDomain(resource string, domain string) ([][]string, error) { - permissions := make([][]string, 0) - subjectIndex, _ := e.GetFieldIndex("p", "sub") - objectIndex, _ := e.GetFieldIndex("p", "obj") - domIndex, _ := e.GetFieldIndex("p", "dom") - rm := e.GetRoleManager() - if rm == nil { - return nil, fmt.Errorf("role manager is not initialized") - } - - isRole := make(map[string]bool) - - if roles, err := e.GetAllRolesByDomain(domain); err != nil { - return nil, err - } else { - for _, role := range roles { - isRole[role] = true - } - } - - for _, rule := range e.model["p"]["p"].Policy { - obj := rule[objectIndex] - if obj != resource { - continue - } - - sub := rule[subjectIndex] - - if !isRole[sub] { - permissions = append(permissions, rule) - } else { - if domain != rule[domIndex] { - continue - } - users, err := rm.GetUsers(sub, domain) - if err != nil { - return nil, err - } - - for _, user := range users { - implicitUserRule := deepCopyPolicy(rule) - implicitUserRule[subjectIndex] = user - permissions = append(permissions, implicitUserRule) - } - } - } - - res := removeDuplicatePermissions(permissions) - return res, nil -} diff --git a/vendor/github.com/casbin/casbin/v2/rbac_api_synced.go b/vendor/github.com/casbin/casbin/v2/rbac_api_synced.go deleted file mode 100644 index 7b10e565..00000000 --- a/vendor/github.com/casbin/casbin/v2/rbac_api_synced.go +++ /dev/null @@ -1,203 +0,0 @@ -// 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 - -// GetRolesForUser gets the roles that a user has. -func (e *SyncedEnforcer) GetRolesForUser(name string, domain ...string) ([]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetRolesForUser(name, domain...) -} - -// GetUsersForRole gets the users that has a role. -func (e *SyncedEnforcer) GetUsersForRole(name string, domain ...string) ([]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetUsersForRole(name, domain...) -} - -// HasRoleForUser determines whether a user has a role. -func (e *SyncedEnforcer) HasRoleForUser(name string, role string, domain ...string) (bool, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.HasRoleForUser(name, role, domain...) -} - -// AddRoleForUser adds a role for a user. -// Returns false if the user already has the role (aka not affected). -func (e *SyncedEnforcer) AddRoleForUser(user string, role string, domain ...string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.AddRoleForUser(user, role, domain...) -} - -// AddRolesForUser adds roles for a user. -// Returns false if the user already has the roles (aka not affected). -func (e *SyncedEnforcer) AddRolesForUser(user string, roles []string, domain ...string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.AddRolesForUser(user, roles, domain...) -} - -// DeleteRoleForUser deletes a role for a user. -// Returns false if the user does not have the role (aka not affected). -func (e *SyncedEnforcer) DeleteRoleForUser(user string, role string, domain ...string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.DeleteRoleForUser(user, role, domain...) -} - -// DeleteRolesForUser deletes all roles for a user. -// Returns false if the user does not have any roles (aka not affected). -func (e *SyncedEnforcer) DeleteRolesForUser(user string, domain ...string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.DeleteRolesForUser(user, domain...) -} - -// DeleteUser deletes a user. -// Returns false if the user does not exist (aka not affected). -func (e *SyncedEnforcer) DeleteUser(user string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.DeleteUser(user) -} - -// DeleteRole deletes a role. -// Returns false if the role does not exist (aka not affected). -func (e *SyncedEnforcer) DeleteRole(role string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.DeleteRole(role) -} - -// DeletePermission deletes a permission. -// Returns false if the permission does not exist (aka not affected). -func (e *SyncedEnforcer) DeletePermission(permission ...string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.DeletePermission(permission...) -} - -// AddPermissionForUser adds a permission for a user or role. -// Returns false if the user or role already has the permission (aka not affected). -func (e *SyncedEnforcer) AddPermissionForUser(user string, permission ...string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.AddPermissionForUser(user, permission...) -} - -// AddPermissionsForUser adds permissions for a user or role. -// Returns false if the user or role already has the permissions (aka not affected). -func (e *SyncedEnforcer) AddPermissionsForUser(user string, permissions ...[]string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.AddPermissionsForUser(user, permissions...) -} - -// DeletePermissionForUser deletes a permission for a user or role. -// Returns false if the user or role does not have the permission (aka not affected). -func (e *SyncedEnforcer) DeletePermissionForUser(user string, permission ...string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.DeletePermissionForUser(user, permission...) -} - -// DeletePermissionsForUser deletes permissions for a user or role. -// Returns false if the user or role does not have any permissions (aka not affected). -func (e *SyncedEnforcer) DeletePermissionsForUser(user string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.DeletePermissionsForUser(user) -} - -// GetPermissionsForUser gets permissions for a user or role. -func (e *SyncedEnforcer) GetPermissionsForUser(user string, domain ...string) ([][]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetPermissionsForUser(user, domain...) -} - -// GetNamedPermissionsForUser gets permissions for a user or role by named policy. -func (e *SyncedEnforcer) GetNamedPermissionsForUser(ptype string, user string, domain ...string) ([][]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetNamedPermissionsForUser(ptype, user, domain...) -} - -// HasPermissionForUser determines whether a user has a permission. -func (e *SyncedEnforcer) HasPermissionForUser(user string, permission ...string) (bool, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.HasPermissionForUser(user, permission...) -} - -// GetImplicitRolesForUser gets implicit roles that a user has. -// Compared to GetRolesForUser(), this function retrieves indirect roles besides direct roles. -// For example: -// g, alice, role:admin -// g, role:admin, role:user -// -// GetRolesForUser("alice") can only get: ["role:admin"]. -// But GetImplicitRolesForUser("alice") will get: ["role:admin", "role:user"]. -func (e *SyncedEnforcer) GetImplicitRolesForUser(name string, domain ...string) ([]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetImplicitRolesForUser(name, domain...) -} - -// GetImplicitPermissionsForUser gets implicit permissions for a user or role. -// Compared to GetPermissionsForUser(), this function retrieves permissions for inherited roles. -// For example: -// p, admin, data1, read -// p, alice, data2, read -// g, alice, admin -// -// GetPermissionsForUser("alice") can only get: [["alice", "data2", "read"]]. -// But GetImplicitPermissionsForUser("alice") will get: [["admin", "data1", "read"], ["alice", "data2", "read"]]. -func (e *SyncedEnforcer) GetImplicitPermissionsForUser(user string, domain ...string) ([][]string, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.GetImplicitPermissionsForUser(user, domain...) -} - -// GetNamedImplicitPermissionsForUser gets implicit permissions for a user or role by named policy. -// Compared to GetNamedPermissionsForUser(), this function retrieves permissions for inherited roles. -// For example: -// p, admin, data1, read -// p2, admin, create -// g, alice, admin -// -// GetImplicitPermissionsForUser("alice") can only get: [["admin", "data1", "read"]], whose policy is default policy "p" -// But you can specify the named policy "p2" to get: [["admin", "create"]] by GetNamedImplicitPermissionsForUser("p2","alice"). -func (e *SyncedEnforcer) GetNamedImplicitPermissionsForUser(ptype string, gtype string, user string, domain ...string) ([][]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetNamedImplicitPermissionsForUser(ptype, gtype, user, domain...) -} - -// GetImplicitUsersForPermission gets implicit users for a permission. -// For example: -// p, admin, data1, read -// p, bob, data1, read -// g, alice, admin -// -// GetImplicitUsersForPermission("data1", "read") will get: ["alice", "bob"]. -// Note: only users will be returned, roles (2nd arg in "g") will be excluded. -func (e *SyncedEnforcer) GetImplicitUsersForPermission(permission ...string) ([]string, error) { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetImplicitUsersForPermission(permission...) -} diff --git a/vendor/github.com/casbin/casbin/v2/rbac_api_with_domains.go b/vendor/github.com/casbin/casbin/v2/rbac_api_with_domains.go deleted file mode 100644 index f6fc4a24..00000000 --- a/vendor/github.com/casbin/casbin/v2/rbac_api_with_domains.go +++ /dev/null @@ -1,192 +0,0 @@ -// 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 ( - "fmt" - - "github.com/casbin/casbin/v2/constant" -) - -// GetUsersForRoleInDomain gets the users that has a role inside a domain. Add by Gordon. -func (e *Enforcer) GetUsersForRoleInDomain(name string, domain string) []string { - if e.GetRoleManager() == nil { - return nil - } - res, _ := e.GetRoleManager().GetUsers(name, domain) - return res -} - -// GetRolesForUserInDomain gets the roles that a user has inside a domain. -func (e *Enforcer) GetRolesForUserInDomain(name string, domain string) []string { - if e.GetRoleManager() == nil { - return nil - } - res, _ := e.GetRoleManager().GetRoles(name, domain) - return res -} - -// GetPermissionsForUserInDomain gets permissions for a user or role inside a domain. -func (e *Enforcer) GetPermissionsForUserInDomain(user string, domain string) [][]string { - res, _ := e.GetImplicitPermissionsForUser(user, domain) - return res -} - -// AddRoleForUserInDomain adds a role for a user inside a domain. -// Returns false if the user already has the role (aka not affected). -func (e *Enforcer) AddRoleForUserInDomain(user string, role string, domain string) (bool, error) { - return e.AddGroupingPolicy(user, role, domain) -} - -// DeleteRoleForUserInDomain deletes a role for a user inside a domain. -// Returns false if the user does not have the role (aka not affected). -func (e *Enforcer) DeleteRoleForUserInDomain(user string, role string, domain string) (bool, error) { - return e.RemoveGroupingPolicy(user, role, domain) -} - -// DeleteRolesForUserInDomain deletes all roles for a user inside a domain. -// Returns false if the user does not have any roles (aka not affected). -func (e *Enforcer) DeleteRolesForUserInDomain(user string, domain string) (bool, error) { - if e.GetRoleManager() == nil { - return false, fmt.Errorf("role manager is not initialized") - } - roles, err := e.GetRoleManager().GetRoles(user, domain) - if err != nil { - return false, err - } - - var rules [][]string - for _, role := range roles { - rules = append(rules, []string{user, role, domain}) - } - - return e.RemoveGroupingPolicies(rules) -} - -// GetAllUsersByDomain would get all users associated with the domain. -func (e *Enforcer) GetAllUsersByDomain(domain string) ([]string, error) { - m := make(map[string]struct{}) - g, err := e.model.GetAssertion("g", "g") - if err != nil { - return []string{}, err - } - p := e.model["p"]["p"] - users := make([]string, 0) - index, err := e.GetFieldIndex("p", constant.DomainIndex) - if err != nil { - return []string{}, err - } - - getUser := func(index int, policies [][]string, domain string, m map[string]struct{}) []string { - if len(policies) == 0 || len(policies[0]) <= index { - return []string{} - } - res := make([]string, 0) - for _, policy := range policies { - if _, ok := m[policy[0]]; policy[index] == domain && !ok { - res = append(res, policy[0]) - m[policy[0]] = struct{}{} - } - } - return res - } - - users = append(users, getUser(2, g.Policy, domain, m)...) - users = append(users, getUser(index, p.Policy, domain, m)...) - return users, nil -} - -// DeleteAllUsersByDomain would delete all users associated with the domain. -func (e *Enforcer) DeleteAllUsersByDomain(domain string) (bool, error) { - g, err := e.model.GetAssertion("g", "g") - if err != nil { - return false, err - } - p := e.model["p"]["p"] - index, err := e.GetFieldIndex("p", constant.DomainIndex) - if err != nil { - return false, err - } - - getUser := func(index int, policies [][]string, domain string) [][]string { - if len(policies) == 0 || len(policies[0]) <= index { - return [][]string{} - } - res := make([][]string, 0) - for _, policy := range policies { - if policy[index] == domain { - res = append(res, policy) - } - } - return res - } - - users := getUser(2, g.Policy, domain) - if _, err = e.RemoveGroupingPolicies(users); err != nil { - return false, err - } - users = getUser(index, p.Policy, domain) - if _, err = e.RemovePolicies(users); err != nil { - return false, err - } - return true, nil -} - -// DeleteDomains would delete all associated users and roles. -// It would delete all domains if parameter is not provided. -func (e *Enforcer) DeleteDomains(domains ...string) (bool, error) { - if len(domains) == 0 { - e.ClearPolicy() - return true, nil - } - for _, domain := range domains { - if _, err := e.DeleteAllUsersByDomain(domain); err != nil { - return false, err - } - } - return true, nil -} - -// GetAllDomains would get all domains. -func (e *Enforcer) GetAllDomains() ([]string, error) { - if e.GetRoleManager() == nil { - return nil, fmt.Errorf("role manager is not initialized") - } - return e.GetRoleManager().GetAllDomains() -} - -// GetAllRolesByDomain would get all roles associated with the domain. -// note: Not applicable to Domains with inheritance relationship (implicit roles) -func (e *Enforcer) GetAllRolesByDomain(domain string) ([]string, error) { - g, err := e.model.GetAssertion("g", "g") - if err != nil { - return []string{}, err - } - policies := g.Policy - roles := make([]string, 0) - existMap := make(map[string]bool) // remove duplicates - - for _, policy := range policies { - if policy[len(policy)-1] == domain { - role := policy[len(policy)-2] - if _, ok := existMap[role]; !ok { - roles = append(roles, role) - existMap[role] = true - } - } - } - - return roles, nil -} diff --git a/vendor/github.com/casbin/casbin/v2/rbac_api_with_domains_synced.go b/vendor/github.com/casbin/casbin/v2/rbac_api_with_domains_synced.go deleted file mode 100644 index 26f6ce4b..00000000 --- a/vendor/github.com/casbin/casbin/v2/rbac_api_with_domains_synced.go +++ /dev/null @@ -1,60 +0,0 @@ -// 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 - -// GetUsersForRoleInDomain gets the users that has a role inside a domain. Add by Gordon. -func (e *SyncedEnforcer) GetUsersForRoleInDomain(name string, domain string) []string { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetUsersForRoleInDomain(name, domain) -} - -// GetRolesForUserInDomain gets the roles that a user has inside a domain. -func (e *SyncedEnforcer) GetRolesForUserInDomain(name string, domain string) []string { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetRolesForUserInDomain(name, domain) -} - -// GetPermissionsForUserInDomain gets permissions for a user or role inside a domain. -func (e *SyncedEnforcer) GetPermissionsForUserInDomain(user string, domain string) [][]string { - e.m.RLock() - defer e.m.RUnlock() - return e.Enforcer.GetPermissionsForUserInDomain(user, domain) -} - -// AddRoleForUserInDomain adds a role for a user inside a domain. -// Returns false if the user already has the role (aka not affected). -func (e *SyncedEnforcer) AddRoleForUserInDomain(user string, role string, domain string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.AddRoleForUserInDomain(user, role, domain) -} - -// DeleteRoleForUserInDomain deletes a role for a user inside a domain. -// Returns false if the user does not have the role (aka not affected). -func (e *SyncedEnforcer) DeleteRoleForUserInDomain(user string, role string, domain string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.DeleteRoleForUserInDomain(user, role, domain) -} - -// DeleteRolesForUserInDomain deletes all roles for a user inside a domain. -// Returns false if the user does not have any roles (aka not affected). -func (e *SyncedEnforcer) DeleteRolesForUserInDomain(user string, domain string) (bool, error) { - e.m.Lock() - defer e.m.Unlock() - return e.Enforcer.DeleteRolesForUserInDomain(user, domain) -} diff --git a/vendor/github.com/casbin/casbin/v2/util/builtin_operators.go b/vendor/github.com/casbin/casbin/v2/util/builtin_operators.go deleted file mode 100644 index bab9b0b3..00000000 --- a/vendor/github.com/casbin/casbin/v2/util/builtin_operators.go +++ /dev/null @@ -1,482 +0,0 @@ -// 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 util - -import ( - "errors" - "fmt" - "net" - "path" - "regexp" - "strings" - "sync" - "time" - - "github.com/casbin/casbin/v2/rbac" - - "github.com/casbin/govaluate" -) - -var ( - keyMatch4Re *regexp.Regexp = regexp.MustCompile(`{([^/]+)}`) -) - -// validate the variadic parameter size and type as string. -func validateVariadicArgs(expectedLen int, args ...interface{}) error { - if len(args) != expectedLen { - return fmt.Errorf("expected %d arguments, but got %d", expectedLen, len(args)) - } - - for _, p := range args { - _, ok := p.(string) - if !ok { - return errors.New("argument must be a string") - } - } - - return nil -} - -// validate the variadic string parameter size. -func validateVariadicStringArgs(expectedLen int, args ...string) error { - if len(args) != expectedLen { - return fmt.Errorf("expected %d arguments, but got %d", expectedLen, len(args)) - } - return nil -} - -// KeyMatch determines whether key1 matches the pattern of key2 (similar to RESTful path), key2 can contain a *. -// For example, "/foo/bar" matches "/foo/*". -func KeyMatch(key1 string, key2 string) bool { - i := strings.Index(key2, "*") - if i == -1 { - return key1 == key2 - } - - if len(key1) > i { - return key1[:i] == key2[:i] - } - return key1 == key2[:i] -} - -// KeyMatchFunc is the wrapper for KeyMatch. -func KeyMatchFunc(args ...interface{}) (interface{}, error) { - if err := validateVariadicArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %w", "keyMatch", err) - } - - name1 := args[0].(string) - name2 := args[1].(string) - - return KeyMatch(name1, name2), nil -} - -// KeyGet returns the matched part -// For example, "/foo/bar/foo" matches "/foo/*" -// "bar/foo" will been returned. -func KeyGet(key1, key2 string) string { - i := strings.Index(key2, "*") - if i == -1 { - return "" - } - if len(key1) > i { - if key1[:i] == key2[:i] { - return key1[i:] - } - } - return "" -} - -// KeyGetFunc is the wrapper for KeyGet. -func KeyGetFunc(args ...interface{}) (interface{}, error) { - if err := validateVariadicArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %w", "keyGet", err) - } - - name1 := args[0].(string) - name2 := args[1].(string) - - return KeyGet(name1, name2), nil -} - -// KeyMatch2 determines whether key1 matches the pattern of key2 (similar to RESTful path), key2 can contain a *. -// For example, "/foo/bar" matches "/foo/*", "/resource1" matches "/:resource". -func KeyMatch2(key1 string, key2 string) bool { - key2 = strings.Replace(key2, "/*", "/.*", -1) - - re := regexp.MustCompile(`:[^/]+`) - key2 = re.ReplaceAllString(key2, "$1[^/]+$2") - - return RegexMatch(key1, "^"+key2+"$") -} - -// KeyMatch2Func is the wrapper for KeyMatch2. -func KeyMatch2Func(args ...interface{}) (interface{}, error) { - if err := validateVariadicArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %w", "keyMatch2", err) - } - - name1 := args[0].(string) - name2 := args[1].(string) - - return KeyMatch2(name1, name2), nil -} - -// KeyGet2 returns value matched pattern -// For example, "/resource1" matches "/:resource" -// if the pathVar == "resource", then "resource1" will be returned. -func KeyGet2(key1, key2 string, pathVar string) string { - key2 = strings.Replace(key2, "/*", "/.*", -1) - - re := regexp.MustCompile(`:[^/]+`) - keys := re.FindAllString(key2, -1) - key2 = re.ReplaceAllString(key2, "$1([^/]+)$2") - key2 = "^" + key2 + "$" - re2 := regexp.MustCompile(key2) - values := re2.FindAllStringSubmatch(key1, -1) - if len(values) == 0 { - return "" - } - for i, key := range keys { - if pathVar == key[1:] { - return values[0][i+1] - } - } - return "" -} - -// KeyGet2Func is the wrapper for KeyGet2. -func KeyGet2Func(args ...interface{}) (interface{}, error) { - if err := validateVariadicArgs(3, args...); err != nil { - return false, fmt.Errorf("%s: %w", "keyGet2", err) - } - - name1 := args[0].(string) - name2 := args[1].(string) - key := args[2].(string) - - return KeyGet2(name1, name2, key), nil -} - -// KeyMatch3 determines whether key1 matches the pattern of key2 (similar to RESTful path), key2 can contain a *. -// For example, "/foo/bar" matches "/foo/*", "/resource1" matches "/{resource}". -func KeyMatch3(key1 string, key2 string) bool { - key2 = strings.Replace(key2, "/*", "/.*", -1) - - re := regexp.MustCompile(`\{[^/]+\}`) - key2 = re.ReplaceAllString(key2, "$1[^/]+$2") - - return RegexMatch(key1, "^"+key2+"$") -} - -// KeyMatch3Func is the wrapper for KeyMatch3. -func KeyMatch3Func(args ...interface{}) (interface{}, error) { - if err := validateVariadicArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %w", "keyMatch3", err) - } - - name1 := args[0].(string) - name2 := args[1].(string) - - return KeyMatch3(name1, name2), nil -} - -// KeyGet3 returns value matched pattern -// For example, "project/proj_project1_admin/" matches "project/proj_{project}_admin/" -// if the pathVar == "project", then "project1" will be returned. -func KeyGet3(key1, key2 string, pathVar string) string { - key2 = strings.Replace(key2, "/*", "/.*", -1) - - re := regexp.MustCompile(`\{[^/]+?\}`) // non-greedy match of `{...}` to support multiple {} in `/.../` - keys := re.FindAllString(key2, -1) - key2 = re.ReplaceAllString(key2, "$1([^/]+?)$2") - key2 = "^" + key2 + "$" - re2 := regexp.MustCompile(key2) - values := re2.FindAllStringSubmatch(key1, -1) - if len(values) == 0 { - return "" - } - for i, key := range keys { - if pathVar == key[1:len(key)-1] { - return values[0][i+1] - } - } - return "" -} - -// KeyGet3Func is the wrapper for KeyGet3. -func KeyGet3Func(args ...interface{}) (interface{}, error) { - if err := validateVariadicArgs(3, args...); err != nil { - return false, fmt.Errorf("%s: %w", "keyGet3", err) - } - - name1 := args[0].(string) - name2 := args[1].(string) - key := args[2].(string) - - return KeyGet3(name1, name2, key), nil -} - -// KeyMatch4 determines whether key1 matches the pattern of key2 (similar to RESTful path), key2 can contain a *. -// Besides what KeyMatch3 does, KeyMatch4 can also match repeated patterns: -// "/parent/123/child/123" matches "/parent/{id}/child/{id}" -// "/parent/123/child/456" does not match "/parent/{id}/child/{id}" -// But KeyMatch3 will match both. -func KeyMatch4(key1 string, key2 string) bool { - key2 = strings.Replace(key2, "/*", "/.*", -1) - - tokens := []string{} - - re := keyMatch4Re - key2 = re.ReplaceAllStringFunc(key2, func(s string) string { - tokens = append(tokens, s[1:len(s)-1]) - return "([^/]+)" - }) - - re = regexp.MustCompile("^" + key2 + "$") - matches := re.FindStringSubmatch(key1) - if matches == nil { - return false - } - matches = matches[1:] - - if len(tokens) != len(matches) { - panic(errors.New("KeyMatch4: number of tokens is not equal to number of values")) - } - - values := map[string]string{} - - for key, token := range tokens { - if _, ok := values[token]; !ok { - values[token] = matches[key] - } - if values[token] != matches[key] { - return false - } - } - - return true -} - -// KeyMatch4Func is the wrapper for KeyMatch4. -func KeyMatch4Func(args ...interface{}) (interface{}, error) { - if err := validateVariadicArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %w", "keyMatch4", err) - } - - name1 := args[0].(string) - name2 := args[1].(string) - - return KeyMatch4(name1, name2), nil -} - -// KeyMatch5 determines whether key1 matches the pattern of key2 (similar to RESTful path), key2 can contain a * -// For example, -// - "/foo/bar?status=1&type=2" matches "/foo/bar" -// - "/parent/child1" and "/parent/child1" matches "/parent/*" -// - "/parent/child1?status=1" matches "/parent/*". -func KeyMatch5(key1 string, key2 string) bool { - i := strings.Index(key1, "?") - - if i != -1 { - key1 = key1[:i] - } - - key2 = strings.Replace(key2, "/*", "/.*", -1) - - re := regexp.MustCompile(`\{[^/]+\}`) - key2 = re.ReplaceAllString(key2, "$1[^/]+$2") - - return RegexMatch(key1, "^"+key2+"$") -} - -// KeyMatch5Func is the wrapper for KeyMatch5. -func KeyMatch5Func(args ...interface{}) (interface{}, error) { - if err := validateVariadicArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %w", "keyMatch5", err) - } - - name1 := args[0].(string) - name2 := args[1].(string) - - return KeyMatch5(name1, name2), nil -} - -// RegexMatch determines whether key1 matches the pattern of key2 in regular expression. -func RegexMatch(key1 string, key2 string) bool { - res, err := regexp.MatchString(key2, key1) - if err != nil { - panic(err) - } - return res -} - -// RegexMatchFunc is the wrapper for RegexMatch. -func RegexMatchFunc(args ...interface{}) (interface{}, error) { - if err := validateVariadicArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %w", "regexMatch", err) - } - - name1 := args[0].(string) - name2 := args[1].(string) - - return RegexMatch(name1, name2), nil -} - -// IPMatch determines whether IP address ip1 matches the pattern of IP address ip2, ip2 can be an IP address or a CIDR pattern. -// For example, "192.168.2.123" matches "192.168.2.0/24". -func IPMatch(ip1 string, ip2 string) bool { - objIP1 := net.ParseIP(ip1) - if objIP1 == nil { - panic("invalid argument: ip1 in IPMatch() function is not an IP address.") - } - - _, cidr, err := net.ParseCIDR(ip2) - if err != nil { - objIP2 := net.ParseIP(ip2) - if objIP2 == nil { - panic("invalid argument: ip2 in IPMatch() function is neither an IP address nor a CIDR.") - } - - return objIP1.Equal(objIP2) - } - - return cidr.Contains(objIP1) -} - -// IPMatchFunc is the wrapper for IPMatch. -func IPMatchFunc(args ...interface{}) (interface{}, error) { - if err := validateVariadicArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %w", "ipMatch", err) - } - - ip1 := args[0].(string) - ip2 := args[1].(string) - - return IPMatch(ip1, ip2), nil -} - -// GlobMatch determines whether key1 matches the pattern of key2 using glob pattern. -func GlobMatch(key1 string, key2 string) (bool, error) { - return path.Match(key2, key1) -} - -// GlobMatchFunc is the wrapper for GlobMatch. -func GlobMatchFunc(args ...interface{}) (interface{}, error) { - if err := validateVariadicArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %w", "globMatch", err) - } - - name1 := args[0].(string) - name2 := args[1].(string) - - return GlobMatch(name1, name2) -} - -// GenerateGFunction is the factory method of the g(_, _[, _]) function. -func GenerateGFunction(rm rbac.RoleManager) govaluate.ExpressionFunction { - memorized := sync.Map{} - return func(args ...interface{}) (interface{}, error) { - // Like all our other govaluate functions, all args are strings. - - // Allocate and generate a cache key from the arguments... - total := len(args) - for _, a := range args { - aStr := a.(string) - total += len(aStr) - } - builder := strings.Builder{} - builder.Grow(total) - for _, arg := range args { - builder.WriteByte(0) - builder.WriteString(arg.(string)) - } - key := builder.String() - - // ...and see if we've already calculated this. - v, found := memorized.Load(key) - if found { - return v, nil - } - - // If not, do the calculation. - // There are guaranteed to be exactly 2 or 3 arguments. - name1, name2 := args[0].(string), args[1].(string) - if rm == nil { - v = name1 == name2 - } else if len(args) == 2 { - v, _ = rm.HasLink(name1, name2) - } else { - domain := args[2].(string) - v, _ = rm.HasLink(name1, name2, domain) - } - - memorized.Store(key, v) - return v, nil - } -} - -// GenerateConditionalGFunction is the factory method of the g(_, _[, _]) function with conditions. -func GenerateConditionalGFunction(crm rbac.ConditionalRoleManager) govaluate.ExpressionFunction { - return func(args ...interface{}) (interface{}, error) { - // Like all our other govaluate functions, all args are strings. - var hasLink bool - - name1, name2 := args[0].(string), args[1].(string) - if crm == nil { - hasLink = name1 == name2 - } else if len(args) == 2 { - hasLink, _ = crm.HasLink(name1, name2) - } else { - domain := args[2].(string) - hasLink, _ = crm.HasLink(name1, name2, domain) - } - - return hasLink, nil - } -} - -// builtin LinkConditionFunc - -// TimeMatchFunc is the wrapper for TimeMatch. -func TimeMatchFunc(args ...string) (bool, error) { - if err := validateVariadicStringArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %w", "TimeMatch", err) - } - return TimeMatch(args[0], args[1]) -} - -// TimeMatch determines whether the current time is between startTime and endTime. -// You can use "_" to indicate that the parameter is ignored. -func TimeMatch(startTime, endTime string) (bool, error) { - now := time.Now() - if startTime != "_" { - if start, err := time.Parse("2006-01-02 15:04:05", startTime); err != nil { - return false, err - } else if !now.After(start) { - return false, nil - } - } - - if endTime != "_" { - if end, err := time.Parse("2006-01-02 15:04:05", endTime); err != nil { - return false, err - } else if !now.Before(end) { - return false, nil - } - } - - return true, nil -} diff --git a/vendor/github.com/casbin/casbin/v2/util/util.go b/vendor/github.com/casbin/casbin/v2/util/util.go deleted file mode 100644 index f247b27b..00000000 --- a/vendor/github.com/casbin/casbin/v2/util/util.go +++ /dev/null @@ -1,383 +0,0 @@ -// 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 util - -import ( - "encoding/json" - "regexp" - "sort" - "strings" - "sync" -) - -var evalReg = regexp.MustCompile(`\beval\((?P[^)]*)\)`) - -var escapeAssertionRegex = regexp.MustCompile(`\b((r|p)[0-9]*)\.`) - -func JsonToMap(jsonStr string) (map[string]interface{}, error) { - result := make(map[string]interface{}) - err := json.Unmarshal([]byte(jsonStr), &result) - if err != nil { - return result, err - } - return result, nil -} - -// EscapeAssertion escapes the dots in the assertion, because the expression evaluation doesn't support such variable names. -func EscapeAssertion(s string) string { - s = escapeAssertionRegex.ReplaceAllStringFunc(s, func(m string) string { - return strings.Replace(m, ".", "_", 1) - }) - return s -} - -// RemoveComments removes the comments starting with # in the text. -func RemoveComments(s string) string { - pos := strings.Index(s, "#") - if pos == -1 { - return s - } - return strings.TrimSpace(s[0:pos]) -} - -// ArrayEquals determines whether two string arrays are identical. -func ArrayEquals(a []string, b []string) bool { - if len(a) != len(b) { - return false - } - - for i, v := range a { - if v != b[i] { - return false - } - } - return true -} - -// Array2DEquals determines whether two 2-dimensional string arrays are identical. -func Array2DEquals(a [][]string, b [][]string) bool { - if len(a) != len(b) { - return false - } - - for i, v := range a { - if !ArrayEquals(v, b[i]) { - return false - } - } - return true -} - -// SortArray2D Sorts the two-dimensional string array. -func SortArray2D(arr [][]string) { - if len(arr) != 0 { - sort.Slice(arr, func(i, j int) bool { - elementLen := len(arr[0]) - for k := 0; k < elementLen; k++ { - if arr[i][k] < arr[j][k] { - return true - } else if arr[i][k] > arr[j][k] { - return false - } - } - return true - }) - } -} - -// SortedArray2DEquals determines whether two 2-dimensional string arrays are identical. -func SortedArray2DEquals(a [][]string, b [][]string) bool { - if len(a) != len(b) { - return false - } - copyA := make([][]string, len(a)) - copy(copyA, a) - copyB := make([][]string, len(b)) - copy(copyB, b) - - SortArray2D(copyA) - SortArray2D(copyB) - - for i, v := range copyA { - if !ArrayEquals(v, copyB[i]) { - return false - } - } - return true -} - -// ArrayRemoveDuplicates removes any duplicated elements in a string array. -func ArrayRemoveDuplicates(s *[]string) { - found := make(map[string]bool) - j := 0 - for i, x := range *s { - if !found[x] { - found[x] = true - (*s)[j] = (*s)[i] - j++ - } - } - *s = (*s)[:j] -} - -// ArrayToString gets a printable string for a string array. -func ArrayToString(s []string) string { - return strings.Join(s, ", ") -} - -// ParamsToString gets a printable string for variable number of parameters. -func ParamsToString(s ...string) string { - return strings.Join(s, ", ") -} - -// SetEquals determines whether two string sets are identical. -func SetEquals(a []string, b []string) bool { - if len(a) != len(b) { - return false - } - - sort.Strings(a) - sort.Strings(b) - - for i, v := range a { - if v != b[i] { - return false - } - } - return true -} - -// SetEquals determines whether two int sets are identical. -func SetEqualsInt(a []int, b []int) bool { - if len(a) != len(b) { - return false - } - - sort.Ints(a) - sort.Ints(b) - - for i, v := range a { - if v != b[i] { - return false - } - } - return true -} - -// Set2DEquals determines whether two string slice sets are identical. -func Set2DEquals(a [][]string, b [][]string) bool { - if len(a) != len(b) { - return false - } - - var aa []string - for _, v := range a { - sort.Strings(v) - aa = append(aa, strings.Join(v, ", ")) - } - var bb []string - for _, v := range b { - sort.Strings(v) - bb = append(bb, strings.Join(v, ", ")) - } - - return SetEquals(aa, bb) -} - -// JoinSlice joins a string and a slice into a new slice. -func JoinSlice(a string, b ...string) []string { - res := make([]string, 0, len(b)+1) - - res = append(res, a) - res = append(res, b...) - - return res -} - -// JoinSliceAny joins a string and a slice into a new interface{} slice. -func JoinSliceAny(a string, b ...string) []interface{} { - res := make([]interface{}, 0, len(b)+1) - - res = append(res, a) - for _, s := range b { - res = append(res, s) - } - - return res -} - -// SetSubtract returns the elements in `a` that aren't in `b`. -func SetSubtract(a []string, b []string) []string { - mb := make(map[string]struct{}, len(b)) - for _, x := range b { - mb[x] = struct{}{} - } - var diff []string - for _, x := range a { - if _, found := mb[x]; !found { - diff = append(diff, x) - } - } - return diff -} - -// HasEval determine whether matcher contains function eval. -func HasEval(s string) bool { - return evalReg.MatchString(s) -} - -// ReplaceEval replace function eval with the value of its parameters. -func ReplaceEval(s string, rule string) string { - return evalReg.ReplaceAllString(s, "("+rule+")") -} - -// ReplaceEvalWithMap replace function eval with the value of its parameters via given sets. -func ReplaceEvalWithMap(src string, sets map[string]string) string { - return evalReg.ReplaceAllStringFunc(src, func(s string) string { - subs := evalReg.FindStringSubmatch(s) - if subs == nil { - return s - } - key := subs[1] - value, found := sets[key] - if !found { - return s - } - return evalReg.ReplaceAllString(s, value) - }) -} - -// GetEvalValue returns the parameters of function eval. -func GetEvalValue(s string) []string { - subMatch := evalReg.FindAllStringSubmatch(s, -1) - var rules []string - for _, rule := range subMatch { - rules = append(rules, rule[1]) - } - return rules -} - -func RemoveDuplicateElement(s []string) []string { - result := make([]string, 0, len(s)) - temp := map[string]struct{}{} - for _, item := range s { - if _, ok := temp[item]; !ok { - temp[item] = struct{}{} - result = append(result, item) - } - } - return result -} - -type node struct { - key interface{} - value interface{} - prev *node - next *node -} - -type LRUCache struct { - capacity int - m map[interface{}]*node - head *node - tail *node -} - -func NewLRUCache(capacity int) *LRUCache { - cache := &LRUCache{} - cache.capacity = capacity - cache.m = map[interface{}]*node{} - - head := &node{} - tail := &node{} - - head.next = tail - tail.prev = head - - cache.head = head - cache.tail = tail - - return cache -} - -func (cache *LRUCache) remove(n *node, listOnly bool) { - if !listOnly { - delete(cache.m, n.key) - } - n.prev.next = n.next - n.next.prev = n.prev -} - -func (cache *LRUCache) add(n *node, listOnly bool) { - if !listOnly { - cache.m[n.key] = n - } - headNext := cache.head.next - cache.head.next = n - headNext.prev = n - n.next = headNext - n.prev = cache.head -} - -func (cache *LRUCache) moveToHead(n *node) { - cache.remove(n, true) - cache.add(n, true) -} - -func (cache *LRUCache) Get(key interface{}) (value interface{}, ok bool) { - n, ok := cache.m[key] - if ok { - cache.moveToHead(n) - return n.value, ok - } else { - return nil, ok - } -} - -func (cache *LRUCache) Put(key interface{}, value interface{}) { - n, ok := cache.m[key] - if ok { - cache.remove(n, false) - } else { - n = &node{key, value, nil, nil} - if len(cache.m) >= cache.capacity { - cache.remove(cache.tail.prev, false) - } - } - cache.add(n, false) -} - -type SyncLRUCache struct { - rwm sync.RWMutex - *LRUCache -} - -func NewSyncLRUCache(capacity int) *SyncLRUCache { - cache := &SyncLRUCache{} - cache.LRUCache = NewLRUCache(capacity) - return cache -} - -func (cache *SyncLRUCache) Get(key interface{}) (value interface{}, ok bool) { - cache.rwm.Lock() - defer cache.rwm.Unlock() - return cache.LRUCache.Get(key) -} - -func (cache *SyncLRUCache) Put(key interface{}, value interface{}) { - cache.rwm.Lock() - defer cache.rwm.Unlock() - cache.LRUCache.Put(key, value) -} diff --git a/vendor/github.com/casbin/govaluate/.gitignore b/vendor/github.com/casbin/govaluate/.gitignore deleted file mode 100644 index 5ac0c3fc..00000000 --- a/vendor/github.com/casbin/govaluate/.gitignore +++ /dev/null @@ -1,28 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -coverage.out - -manual_test.go -*.out -*.err diff --git a/vendor/github.com/casbin/govaluate/.releaserc.json b/vendor/github.com/casbin/govaluate/.releaserc.json deleted file mode 100644 index 58cb0bb4..00000000 --- a/vendor/github.com/casbin/govaluate/.releaserc.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "debug": true, - "branches": [ - "+([0-9])?(.{+([0-9]),x}).x", - "master", - { - "name": "beta", - "prerelease": true - } - ], - "plugins": [ - "@semantic-release/commit-analyzer", - "@semantic-release/release-notes-generator", - "@semantic-release/github" - ] -} diff --git a/vendor/github.com/casbin/govaluate/CONTRIBUTORS b/vendor/github.com/casbin/govaluate/CONTRIBUTORS deleted file mode 100644 index c1a7fe42..00000000 --- a/vendor/github.com/casbin/govaluate/CONTRIBUTORS +++ /dev/null @@ -1,15 +0,0 @@ -This library was authored by George Lester, and contains contributions from: - -vjeantet (regex support) -iasci (ternary operator) -oxtoacart (parameter structures, deferred parameter retrieval) -wmiller848 (bitwise operators) -prashantv (optimization of bools) -dpaolella (exposure of variables used in an expression) -benpaxton (fix for missing type checks during literal elide process) -abrander (panic-finding testing tool, float32 conversions) -xfennec (fix for dates being parsed in the current Location) -bgaifullin (lifting restriction on complex/struct types) -gautambt (hexadecimal literals) -felixonmars (fix multiple typos in test names) -sambonfire (automatic type conversion for accessor function calls) \ No newline at end of file diff --git a/vendor/github.com/casbin/govaluate/EvaluableExpression.go b/vendor/github.com/casbin/govaluate/EvaluableExpression.go deleted file mode 100644 index a5fe50d4..00000000 --- a/vendor/github.com/casbin/govaluate/EvaluableExpression.go +++ /dev/null @@ -1,276 +0,0 @@ -package govaluate - -import ( - "errors" - "fmt" -) - -const isoDateFormat string = "2006-01-02T15:04:05.999999999Z0700" -const shortCircuitHolder int = -1 - -var DUMMY_PARAMETERS = MapParameters(map[string]interface{}{}) - -/* - EvaluableExpression represents a set of ExpressionTokens which, taken together, - are an expression that can be evaluated down into a single value. -*/ -type EvaluableExpression struct { - - /* - Represents the query format used to output dates. Typically only used when creating SQL or Mongo queries from an expression. - Defaults to the complete ISO8601 format, including nanoseconds. - */ - QueryDateFormat string - - /* - Whether or not to safely check types when evaluating. - If true, this library will return error messages when invalid types are used. - If false, the library will panic when operators encounter types they can't use. - - This is exclusively for users who need to squeeze every ounce of speed out of the library as they can, - and you should only set this to false if you know exactly what you're doing. - */ - ChecksTypes bool - - tokens []ExpressionToken - evaluationStages *evaluationStage - inputExpression string -} - -/* - Parses a new EvaluableExpression from the given [expression] string. - Returns an error if the given expression has invalid syntax. -*/ -func NewEvaluableExpression(expression string) (*EvaluableExpression, error) { - - functions := make(map[string]ExpressionFunction) - return NewEvaluableExpressionWithFunctions(expression, functions) -} - -/* - Similar to [NewEvaluableExpression], except that instead of a string, an already-tokenized expression is given. - This is useful in cases where you may be generating an expression automatically, or using some other parser (e.g., to parse from a query language) -*/ -func NewEvaluableExpressionFromTokens(tokens []ExpressionToken) (*EvaluableExpression, error) { - - var ret *EvaluableExpression - var err error - - ret = new(EvaluableExpression) - ret.QueryDateFormat = isoDateFormat - - err = checkBalance(tokens) - if err != nil { - return nil, err - } - - err = checkExpressionSyntax(tokens) - if err != nil { - return nil, err - } - - ret.tokens, err = optimizeTokens(tokens) - if err != nil { - return nil, err - } - - ret.evaluationStages, err = planStages(ret.tokens) - if err != nil { - return nil, err - } - - ret.ChecksTypes = true - return ret, nil -} - -/* - Similar to [NewEvaluableExpression], except enables the use of user-defined functions. - Functions passed into this will be available to the expression. -*/ -func NewEvaluableExpressionWithFunctions(expression string, functions map[string]ExpressionFunction) (*EvaluableExpression, error) { - - var ret *EvaluableExpression - var err error - - ret = new(EvaluableExpression) - ret.QueryDateFormat = isoDateFormat - ret.inputExpression = expression - - ret.tokens, err = parseTokens(expression, functions) - if err != nil { - return nil, err - } - - err = checkBalance(ret.tokens) - if err != nil { - return nil, err - } - - err = checkExpressionSyntax(ret.tokens) - if err != nil { - return nil, err - } - - ret.tokens, err = optimizeTokens(ret.tokens) - if err != nil { - return nil, err - } - - ret.evaluationStages, err = planStages(ret.tokens) - if err != nil { - return nil, err - } - - ret.ChecksTypes = true - return ret, nil -} - -/* - Same as `Eval`, but automatically wraps a map of parameters into a `govalute.Parameters` structure. -*/ -func (this EvaluableExpression) Evaluate(parameters map[string]interface{}) (interface{}, error) { - - if parameters == nil { - return this.Eval(nil) - } - - return this.Eval(MapParameters(parameters)) -} - -/* - Runs the entire expression using the given [parameters]. - e.g., If the expression contains a reference to the variable "foo", it will be taken from `parameters.Get("foo")`. - - This function returns errors if the combination of expression and parameters cannot be run, - such as if a variable in the expression is not present in [parameters]. - - In all non-error circumstances, this returns the single value result of the expression and parameters given. - e.g., if the expression is "1 + 1", this will return 2.0. - e.g., if the expression is "foo + 1" and parameters contains "foo" = 2, this will return 3.0 -*/ -func (this EvaluableExpression) Eval(parameters Parameters) (interface{}, error) { - - if this.evaluationStages == nil { - return nil, nil - } - - if parameters != nil { - parameters = &sanitizedParameters{parameters} - } else { - parameters = DUMMY_PARAMETERS - } - - return this.evaluateStage(this.evaluationStages, parameters) -} - -func (this EvaluableExpression) evaluateStage(stage *evaluationStage, parameters Parameters) (interface{}, error) { - - var left, right interface{} - var err error - - if stage.leftStage != nil { - left, err = this.evaluateStage(stage.leftStage, parameters) - if err != nil { - return nil, err - } - } - - if stage.isShortCircuitable() { - switch stage.symbol { - case AND: - if left == false { - return false, nil - } - case OR: - if left == true { - return true, nil - } - case COALESCE: - if left != nil { - return left, nil - } - - case TERNARY_TRUE: - if left == false { - right = shortCircuitHolder - } - case TERNARY_FALSE: - if left != nil { - right = shortCircuitHolder - } - } - } - - if right != shortCircuitHolder && stage.rightStage != nil { - right, err = this.evaluateStage(stage.rightStage, parameters) - if err != nil { - return nil, err - } - } - - if this.ChecksTypes { - if stage.typeCheck == nil { - - err = typeCheck(stage.leftTypeCheck, left, stage.symbol, stage.typeErrorFormat) - if err != nil { - return nil, err - } - - err = typeCheck(stage.rightTypeCheck, right, stage.symbol, stage.typeErrorFormat) - if err != nil { - return nil, err - } - } else { - // special case where the type check needs to know both sides to determine if the operator can handle it - if !stage.typeCheck(left, right) { - errorMsg := fmt.Sprintf(stage.typeErrorFormat, left, stage.symbol.String()) - return nil, errors.New(errorMsg) - } - } - } - - return stage.operator(left, right, parameters) -} - -func typeCheck(check stageTypeCheck, value interface{}, symbol OperatorSymbol, format string) error { - - if check == nil { - return nil - } - - if check(value) { - return nil - } - - errorMsg := fmt.Sprintf(format, value, symbol.String()) - return errors.New(errorMsg) -} - -/* - Returns an array representing the ExpressionTokens that make up this expression. -*/ -func (this EvaluableExpression) Tokens() []ExpressionToken { - - return this.tokens -} - -/* - Returns the original expression used to create this EvaluableExpression. -*/ -func (this EvaluableExpression) String() string { - - return this.inputExpression -} - -/* - Returns an array representing the variables contained in this EvaluableExpression. -*/ -func (this EvaluableExpression) Vars() []string { - var varlist []string - for _, val := range this.Tokens() { - if val.Kind == VARIABLE { - varlist = append(varlist, val.Value.(string)) - } - } - return varlist -} diff --git a/vendor/github.com/casbin/govaluate/EvaluableExpression_sql.go b/vendor/github.com/casbin/govaluate/EvaluableExpression_sql.go deleted file mode 100644 index 52409fa2..00000000 --- a/vendor/github.com/casbin/govaluate/EvaluableExpression_sql.go +++ /dev/null @@ -1,167 +0,0 @@ -package govaluate - -import ( - "errors" - "fmt" - "regexp" - "time" -) - -/* -Returns a string representing this expression as if it were written in SQL. -This function assumes that all parameters exist within the same table, and that the table essentially represents -a serialized object of some sort (e.g., hibernate). -If your data model is more normalized, you may need to consider iterating through each actual token given by `Tokens()` -to create your query. - -Boolean values are considered to be "1" for true, "0" for false. - -Times are formatted according to this.QueryDateFormat. -*/ -func (this EvaluableExpression) ToSQLQuery() (string, error) { - - var stream *tokenStream - var transactions *expressionOutputStream - var transaction string - var err error - - stream = newTokenStream(this.tokens) - transactions = new(expressionOutputStream) - - for stream.hasNext() { - - transaction, err = this.findNextSQLString(stream, transactions) - if err != nil { - return "", err - } - - transactions.add(transaction) - } - - return transactions.createString(" "), nil -} - -func (this EvaluableExpression) findNextSQLString(stream *tokenStream, transactions *expressionOutputStream) (string, error) { - - var token ExpressionToken - var ret string - - token = stream.next() - - switch token.Kind { - - case STRING: - ret = fmt.Sprintf("'%v'", token.Value) - case PATTERN: - ret = fmt.Sprintf("'%s'", token.Value.(*regexp.Regexp).String()) - case TIME: - ret = fmt.Sprintf("'%s'", token.Value.(time.Time).Format(this.QueryDateFormat)) - - case LOGICALOP: - switch logicalSymbols[token.Value.(string)] { - - case AND: - ret = "AND" - case OR: - ret = "OR" - } - - case BOOLEAN: - if token.Value.(bool) { - ret = "1" - } else { - ret = "0" - } - - case VARIABLE: - ret = fmt.Sprintf("[%s]", token.Value.(string)) - - case NUMERIC: - ret = fmt.Sprintf("%g", token.Value.(float64)) - - case COMPARATOR: - switch comparatorSymbols[token.Value.(string)] { - - case EQ: - ret = "=" - case NEQ: - ret = "<>" - case REQ: - ret = "RLIKE" - case NREQ: - ret = "NOT RLIKE" - default: - ret = fmt.Sprintf("%s", token.Value) - } - - case TERNARY: - - switch ternarySymbols[token.Value.(string)] { - - case COALESCE: - - left := transactions.rollback() - right, err := this.findNextSQLString(stream, transactions) - if err != nil { - return "", err - } - - ret = fmt.Sprintf("COALESCE(%v, %v)", left, right) - case TERNARY_TRUE: - fallthrough - case TERNARY_FALSE: - return "", errors.New("Ternary operators are unsupported in SQL output") - } - case PREFIX: - switch prefixSymbols[token.Value.(string)] { - - case INVERT: - ret = "NOT" - default: - - right, err := this.findNextSQLString(stream, transactions) - if err != nil { - return "", err - } - - ret = fmt.Sprintf("%s%s", token.Value.(string), right) - } - case MODIFIER: - - switch modifierSymbols[token.Value.(string)] { - - case EXPONENT: - - left := transactions.rollback() - right, err := this.findNextSQLString(stream, transactions) - if err != nil { - return "", err - } - - ret = fmt.Sprintf("POW(%s, %s)", left, right) - case MODULUS: - - left := transactions.rollback() - right, err := this.findNextSQLString(stream, transactions) - if err != nil { - return "", err - } - - ret = fmt.Sprintf("MOD(%s, %s)", left, right) - default: - ret = fmt.Sprintf("%s", token.Value) - } - case CLAUSE: - ret = "(" - case CLAUSE_CLOSE: - ret = ")" - case SEPARATOR: - ret = "," - - default: - errorMsg := fmt.Sprintf("Unrecognized query token '%s' of kind '%s'", token.Value, token.Kind) - return "", errors.New(errorMsg) - } - - return ret, nil -} diff --git a/vendor/github.com/casbin/govaluate/ExpressionToken.go b/vendor/github.com/casbin/govaluate/ExpressionToken.go deleted file mode 100644 index f849f381..00000000 --- a/vendor/github.com/casbin/govaluate/ExpressionToken.go +++ /dev/null @@ -1,9 +0,0 @@ -package govaluate - -/* - Represents a single parsed token. -*/ -type ExpressionToken struct { - Kind TokenKind - Value interface{} -} diff --git a/vendor/github.com/casbin/govaluate/LICENSE b/vendor/github.com/casbin/govaluate/LICENSE deleted file mode 100644 index 0ef0f41e..00000000 --- a/vendor/github.com/casbin/govaluate/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014-2016 George Lester - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/casbin/govaluate/MANUAL.md b/vendor/github.com/casbin/govaluate/MANUAL.md deleted file mode 100644 index e0658285..00000000 --- a/vendor/github.com/casbin/govaluate/MANUAL.md +++ /dev/null @@ -1,176 +0,0 @@ -govaluate -==== - -This library contains quite a lot of functionality, this document is meant to be formal documentation on the operators and features of it. -Some of this documentation may duplicate what's in README.md, but should never conflict. - -# Types - -This library only officially deals with four types; `float64`, `bool`, `string`, and arrays. - -All numeric literals, with or without a radix, will be converted to `float64` for evaluation. For instance; in practice, there is no difference between the literals "1.0" and "1", they both end up as `float64`. This matters to users because if you intend to return numeric values from your expressions, then the returned value will be `float64`, not any other numeric type. - -Any string _literal_ (not parameter) which is interpretable as a date will be converted to a `float64` representation of that date's unix time. Any `time.Time` parameters will not be operable with these date literals; such parameters will need to use the `time.Time.Unix()` method to get a numeric representation. - -Arrays are untyped, and can be mixed-type. Internally they're all just `interface{}`. Only two operators can interact with arrays, `IN` and `,`. All other operators will refuse to operate on arrays. - -# Operators - -## Modifiers - -### Addition, concatenation `+` - -If either left or right sides of the `+` operator are a `string`, then this operator will perform string concatenation and return that result. If neither are string, then both must be numeric, and this will return a numeric result. - -Any other case is invalid. - -### Arithmetic `-` `*` `/` `**` `%` - -`**` refers to "take to the power of". For instance, `3 ** 4` == 81. - -* _Left side_: numeric -* _Right side_: numeric -* _Returns_: numeric - -### Bitwise shifts, masks `>>` `<<` `|` `&` `^` - -All of these operators convert their `float64` left and right sides to `int64`, perform their operation, and then convert back. -Given how this library assumes numeric are represented (as `float64`), it is unlikely that this behavior will change, even though it may cause havoc with extremely large or small numbers. - -* _Left side_: numeric -* _Right side_: numeric -* _Returns_: numeric - -### Negation `-` - -Prefix only. This can never have a left-hand value. - -* _Right side_: numeric -* _Returns_: numeric - -### Inversion `!` - -Prefix only. This can never have a left-hand value. - -* _Right side_: bool -* _Returns_: bool - -### Bitwise NOT `~` - -Prefix only. This can never have a left-hand value. - -* _Right side_: numeric -* _Returns_: numeric - -## Logical Operators - -For all logical operators, this library will short-circuit the operation if the left-hand side is sufficient to determine what to do. For instance, `true || expensiveOperation()` will not actually call `expensiveOperation()`, since it knows the left-hand side is `true`. - -### Logical AND/OR `&&` `||` - -* _Left side_: bool -* _Right side_: bool -* _Returns_: bool - -### Ternary true `?` - -Checks if the left side is `true`. If so, returns the right side. If the left side is `false`, returns `nil`. -In practice, this is commonly used with the other ternary operator. - -* _Left side_: bool -* _Right side_: Any type. -* _Returns_: Right side or `nil` - -### Ternary false `:` - -Checks if the left side is `nil`. If so, returns the right side. If the left side is non-nil, returns the left side. -In practice, this is commonly used with the other ternary operator. - -* _Left side_: Any type. -* _Right side_: Any type. -* _Returns_: Right side or `nil` - -### Null coalescence `??` - -Similar to the C# operator. If the left value is non-nil, it returns that. If not, then the right-value is returned. - -* _Left side_: Any type. -* _Right side_: Any type. -* _Returns_: No specific type - whichever is passed to it. - -## Comparators - -### Numeric/lexicographic comparators `>` `<` `>=` `<=` - -If both sides are numeric, this returns the usual greater/lesser behavior that would be expected. -If both sides are string, this returns the lexicographic comparison of the strings. This uses Go's standard lexicographic compare. - -* _Accepts_: Left and right side must either be both string, or both numeric. -* _Returns_: bool - -### Regex comparators `=~` `!~` - -These use go's standard `regexp` flavor of regex. The left side is expected to be the candidate string, the right side is the pattern. `=~` returns whether or not the candidate string matches the regex pattern given on the right. `!~` is the inverted version of the same logic. - -* _Left side_: string -* _Right side_: string -* _Returns_: bool - -## Arrays - -### Separator `,` - -The separator, always paired with parenthesis, creates arrays. It must always have both a left and right-hand value, so for instance `(, 0)` and `(0,)` are invalid uses of it. - -Again, this should always be used with parenthesis; like `(1, 2, 3, 4)`. - -### Membership `IN` - -The only operator with a text name, this operator checks the right-hand side array to see if it contains a value that is equal to the left-side value. -Equality is determined by the use of the `==` operator, and this library doesn't check types between the values. Any two values, when cast to `interface{}`, and can still be checked for equality with `==` will act as expected. - -Note that you can use a parameter for the array, but it must be an `[]interface{}`. - -* _Left side_: Any type. -* _Right side_: array -* _Returns_: bool - -# Parameters - -Parameters must be passed in every time the expression is evaluated. Parameters can be of any type, but will not cause errors unless actually used in an erroneous way. There is no difference in behavior for any of the above operators for parameters - they are type checked when used. - -All `int` and `float` values of any width will be converted to `float64` before use. - -At no point is the parameter structure, or any value thereof, modified by this library. - -## Alternates to maps - -The default form of parameters as a map may not serve your use case. You may have parameters in some other structure, you may want to change the no-parameter-found behavior, or maybe even just have some debugging print statements invoked when a parameter is accessed. - -To do this, define a type that implements the `govaluate.Parameters` interface. When you want to evaluate, instead call `EvaluableExpression.Eval` and pass your parameter structure. - -# Functions - -During expression parsing (_not_ evaluation), a map of functions can be given to `govaluate.NewEvaluableExpressionWithFunctions` (the lengthiest and finest of function names). The resultant expression will be able to invoke those functions during evaluation. Once parsed, an expression cannot have functions added or removed - a new expression will need to be created if you want to change the functions, or behavior of said functions. - -Functions always take the form `()`, including parens. Functions can have an empty list of parameters, like `()`, but still must have parens. - -If the expression contains something that looks like it ought to be a function (such as `foo()`), but no such function was given to it, it will error on parsing. - -Functions must be of type `map[string]govaluate.ExpressionFunction`. `ExpressionFunction`, for brevity, has the following signature: - -`func(args ...interface{}) (interface{}, error)` - -Where `args` is whatever is passed to the function when called. If a non-nil error is returned from a function during evaluation, the evaluation stops and ultimately returns that error to the caller of `Evaluate()` or `Eval()`. - -## Built-in functions - -There aren't any builtin functions. The author is opposed to maintaining a standard library of functions to be used. - -Every use case of this library is different, and even in simple use cases (such as parameters, see above) different users need different behavior, naming, or even functionality. The author prefers that users make their own decisions about what functions they need, and how they operate. - -# Equality - -The `==` and `!=` operators involve a moderately complex workflow. They use [`reflect.DeepEqual`](https://golang.org/pkg/reflect/#DeepEqual). This is for complicated reasons, but there are some types in Go that cannot be compared with the native `==` operator. Arrays, in particular, cannot be compared - Go will panic if you try. One might assume this could be handled with the type checking system in `govaluate`, but unfortunately without reflection there is no way to know if a variable is a slice/array. Worse, structs can be incomparable if they _contain incomparable types_. - -It's all very complicated. Fortunately, Go includes the `reflect.DeepEqual` function to handle all the edge cases. Currently, `govaluate` uses that for all equality/inequality. diff --git a/vendor/github.com/casbin/govaluate/OperatorSymbol.go b/vendor/github.com/casbin/govaluate/OperatorSymbol.go deleted file mode 100644 index 4b810658..00000000 --- a/vendor/github.com/casbin/govaluate/OperatorSymbol.go +++ /dev/null @@ -1,309 +0,0 @@ -package govaluate - -/* - Represents the valid symbols for operators. - -*/ -type OperatorSymbol int - -const ( - VALUE OperatorSymbol = iota - LITERAL - NOOP - EQ - NEQ - GT - LT - GTE - LTE - REQ - NREQ - IN - - AND - OR - - PLUS - MINUS - BITWISE_AND - BITWISE_OR - BITWISE_XOR - BITWISE_LSHIFT - BITWISE_RSHIFT - MULTIPLY - DIVIDE - MODULUS - EXPONENT - - NEGATE - INVERT - BITWISE_NOT - - TERNARY_TRUE - TERNARY_FALSE - COALESCE - - FUNCTIONAL - ACCESS - SEPARATE -) - -type operatorPrecedence int - -const ( - noopPrecedence operatorPrecedence = iota - valuePrecedence - functionalPrecedence - prefixPrecedence - exponentialPrecedence - additivePrecedence - bitwisePrecedence - bitwiseShiftPrecedence - multiplicativePrecedence - comparatorPrecedence - ternaryPrecedence - logicalAndPrecedence - logicalOrPrecedence - separatePrecedence -) - -func findOperatorPrecedenceForSymbol(symbol OperatorSymbol) operatorPrecedence { - - switch symbol { - case NOOP: - return noopPrecedence - case VALUE: - return valuePrecedence - case EQ: - fallthrough - case NEQ: - fallthrough - case GT: - fallthrough - case LT: - fallthrough - case GTE: - fallthrough - case LTE: - fallthrough - case REQ: - fallthrough - case NREQ: - fallthrough - case IN: - return comparatorPrecedence - case AND: - return logicalAndPrecedence - case OR: - return logicalOrPrecedence - case BITWISE_AND: - fallthrough - case BITWISE_OR: - fallthrough - case BITWISE_XOR: - return bitwisePrecedence - case BITWISE_LSHIFT: - fallthrough - case BITWISE_RSHIFT: - return bitwiseShiftPrecedence - case PLUS: - fallthrough - case MINUS: - return additivePrecedence - case MULTIPLY: - fallthrough - case DIVIDE: - fallthrough - case MODULUS: - return multiplicativePrecedence - case EXPONENT: - return exponentialPrecedence - case BITWISE_NOT: - fallthrough - case NEGATE: - fallthrough - case INVERT: - return prefixPrecedence - case COALESCE: - fallthrough - case TERNARY_TRUE: - fallthrough - case TERNARY_FALSE: - return ternaryPrecedence - case ACCESS: - fallthrough - case FUNCTIONAL: - return functionalPrecedence - case SEPARATE: - return separatePrecedence - } - - return valuePrecedence -} - -/* - Map of all valid comparators, and their string equivalents. - Used during parsing of expressions to determine if a symbol is, in fact, a comparator. - Also used during evaluation to determine exactly which comparator is being used. -*/ -var comparatorSymbols = map[string]OperatorSymbol{ - "==": EQ, - "!=": NEQ, - ">": GT, - ">=": GTE, - "<": LT, - "<=": LTE, - "=~": REQ, - "!~": NREQ, - "in": IN, -} - -var logicalSymbols = map[string]OperatorSymbol{ - "&&": AND, - "||": OR, -} - -var bitwiseSymbols = map[string]OperatorSymbol{ - "^": BITWISE_XOR, - "&": BITWISE_AND, - "|": BITWISE_OR, -} - -var bitwiseShiftSymbols = map[string]OperatorSymbol{ - ">>": BITWISE_RSHIFT, - "<<": BITWISE_LSHIFT, -} - -var additiveSymbols = map[string]OperatorSymbol{ - "+": PLUS, - "-": MINUS, -} - -var multiplicativeSymbols = map[string]OperatorSymbol{ - "*": MULTIPLY, - "/": DIVIDE, - "%": MODULUS, -} - -var exponentialSymbolsS = map[string]OperatorSymbol{ - "**": EXPONENT, -} - -var prefixSymbols = map[string]OperatorSymbol{ - "-": NEGATE, - "!": INVERT, - "~": BITWISE_NOT, -} - -var ternarySymbols = map[string]OperatorSymbol{ - "?": TERNARY_TRUE, - ":": TERNARY_FALSE, - "??": COALESCE, -} - -// this is defined separately from additiveSymbols et al because it's needed for parsing, not stage planning. -var modifierSymbols = map[string]OperatorSymbol{ - "+": PLUS, - "-": MINUS, - "*": MULTIPLY, - "/": DIVIDE, - "%": MODULUS, - "**": EXPONENT, - "&": BITWISE_AND, - "|": BITWISE_OR, - "^": BITWISE_XOR, - ">>": BITWISE_RSHIFT, - "<<": BITWISE_LSHIFT, -} - -var separatorSymbols = map[string]OperatorSymbol{ - ",": SEPARATE, -} - -/* - Returns true if this operator is contained by the given array of candidate symbols. - False otherwise. -*/ -func (this OperatorSymbol) IsModifierType(candidate []OperatorSymbol) bool { - - for _, symbolType := range candidate { - if this == symbolType { - return true - } - } - - return false -} - -/* - Generally used when formatting type check errors. - We could store the stringified symbol somewhere else and not require a duplicated codeblock to translate - OperatorSymbol to string, but that would require more memory, and another field somewhere. - Adding operators is rare enough that we just stringify it here instead. -*/ -func (this OperatorSymbol) String() string { - - switch this { - case NOOP: - return "NOOP" - case VALUE: - return "VALUE" - case EQ: - return "=" - case NEQ: - return "!=" - case GT: - return ">" - case LT: - return "<" - case GTE: - return ">=" - case LTE: - return "<=" - case REQ: - return "=~" - case NREQ: - return "!~" - case AND: - return "&&" - case OR: - return "||" - case IN: - return "in" - case BITWISE_AND: - return "&" - case BITWISE_OR: - return "|" - case BITWISE_XOR: - return "^" - case BITWISE_LSHIFT: - return "<<" - case BITWISE_RSHIFT: - return ">>" - case PLUS: - return "+" - case MINUS: - return "-" - case MULTIPLY: - return "*" - case DIVIDE: - return "/" - case MODULUS: - return "%" - case EXPONENT: - return "**" - case NEGATE: - return "-" - case INVERT: - return "!" - case BITWISE_NOT: - return "~" - case TERNARY_TRUE: - return "?" - case TERNARY_FALSE: - return ":" - case COALESCE: - return "??" - } - return "" -} diff --git a/vendor/github.com/casbin/govaluate/README.md b/vendor/github.com/casbin/govaluate/README.md deleted file mode 100644 index 576a9df1..00000000 --- a/vendor/github.com/casbin/govaluate/README.md +++ /dev/null @@ -1,232 +0,0 @@ -govaluate -==== - -[![Build Status](https://github.com/casbin/govaluate/actions/workflows/build.yml/badge.svg)](https://github.com/casbin/govaluate/actions/workflows/build.yml) -[![Godoc](https://godoc.org/github.com/casbin/govaluate?status.svg)](https://pkg.go.dev/github.com/casbin/govaluate) -[![Go Report Card](https://goreportcard.com/badge/github.com/casbin/govaluate)](https://goreportcard.com/report/github.com/casbin/govaluate) - -Provides support for evaluating arbitrary C-like artithmetic/string expressions. - -Why can't you just write these expressions in code? --- - -Sometimes, you can't know ahead-of-time what an expression will look like, or you want those expressions to be configurable. -Perhaps you've got a set of data running through your application, and you want to allow your users to specify some validations to run on it before committing it to a database. Or maybe you've written a monitoring framework which is capable of gathering a bunch of metrics, then evaluating a few expressions to see if any metrics should be alerted upon, but the conditions for alerting are different for each monitor. - -A lot of people wind up writing their own half-baked style of evaluation language that fits their needs, but isn't complete. Or they wind up baking the expression into the actual executable, even if they know it's subject to change. These strategies may work, but they take time to implement, time for users to learn, and induce technical debt as requirements change. This library is meant to cover all the normal C-like expressions, so that you don't have to reinvent one of the oldest wheels on a computer. - -How do I use it? --- - -You create a new EvaluableExpression, then call "Evaluate" on it. - -```go - expression, err := govaluate.NewEvaluableExpression("10 > 0"); - result, err := expression.Evaluate(nil); - // result is now set to "true", the bool value. -``` - -Cool, but how about with parameters? - -```go - expression, err := govaluate.NewEvaluableExpression("foo > 0"); - - parameters := make(map[string]interface{}, 8) - parameters["foo"] = -1; - - result, err := expression.Evaluate(parameters); - // result is now set to "false", the bool value. -``` - -That's cool, but we can almost certainly have done all that in code. What about a complex use case that involves some math? - -```go - expression, err := govaluate.NewEvaluableExpression("(requests_made * requests_succeeded / 100) >= 90"); - - parameters := make(map[string]interface{}, 8) - parameters["requests_made"] = 100; - parameters["requests_succeeded"] = 80; - - result, err := expression.Evaluate(parameters); - // result is now set to "false", the bool value. -``` - -Or maybe you want to check the status of an alive check ("smoketest") page, which will be a string? - -```go - expression, err := govaluate.NewEvaluableExpression("http_response_body == 'service is ok'"); - - parameters := make(map[string]interface{}, 8) - parameters["http_response_body"] = "service is ok"; - - result, err := expression.Evaluate(parameters); - // result is now set to "true", the bool value. -``` - -These examples have all returned boolean values, but it's equally possible to return numeric ones. - -```go - expression, err := govaluate.NewEvaluableExpression("(mem_used / total_mem) * 100"); - - parameters := make(map[string]interface{}, 8) - parameters["total_mem"] = 1024; - parameters["mem_used"] = 512; - - result, err := expression.Evaluate(parameters); - // result is now set to "50.0", the float64 value. -``` - -You can also do date parsing, though the formats are somewhat limited. Stick to RF3339, ISO8061, unix date, or ruby date formats. If you're having trouble getting a date string to parse, check the list of formats actually used: [parsing.go:248](https://github.com/casbin/govaluate/blob/0580e9b47a69125afa0e4ebd1cf93c49eb5a43ec/parsing.go#L258). - -```go - expression, err := govaluate.NewEvaluableExpression("'2014-01-02' > '2014-01-01 23:59:59'"); - result, err := expression.Evaluate(nil); - - // result is now set to true -``` - -Expressions are parsed once, and can be re-used multiple times. Parsing is the compute-intensive phase of the process, so if you intend to use the same expression with different parameters, just parse it once. Like so; - -```go - expression, err := govaluate.NewEvaluableExpression("response_time <= 100"); - parameters := make(map[string]interface{}, 8) - - for { - parameters["response_time"] = pingSomething(); - result, err := expression.Evaluate(parameters) - } -``` - -The normal C-standard order of operators is respected. When writing an expression, be sure that you either order the operators correctly, or use parenthesis to clarify which portions of an expression should be run first. - -Escaping characters --- - -Sometimes you'll have parameters that have spaces, slashes, pluses, ampersands or some other character -that this library interprets as something special. For example, the following expression will not -act as one might expect: - - "response-time < 100" - -As written, the library will parse it as "[response] minus [time] is less than 100". In reality, -"response-time" is meant to be one variable that just happens to have a dash in it. - -There are two ways to work around this. First, you can escape the entire parameter name: - - "[response-time] < 100" - -Or you can use backslashes to escape only the minus sign. - - "response\\-time < 100" - -Backslashes can be used anywhere in an expression to escape the very next character. Square bracketed parameter names can be used instead of plain parameter names at any time. - -Functions --- - -You may have cases where you want to call a function on a parameter during execution of the expression. Perhaps you want to aggregate some set of data, but don't know the exact aggregation you want to use until you're writing the expression itself. Or maybe you have a mathematical operation you want to perform, for which there is no operator; like `log` or `tan` or `sqrt`. For cases like this, you can provide a map of functions to `NewEvaluableExpressionWithFunctions`, which will then be able to use them during execution. For instance; - -```go - functions := map[string]govaluate.ExpressionFunction { - "strlen": func(args ...interface{}) (interface{}, error) { - length := len(args[0].(string)) - return (float64)(length), nil - }, - } - - expString := "strlen('someReallyLongInputString') <= 16" - expression, _ := govaluate.NewEvaluableExpressionWithFunctions(expString, functions) - - result, _ := expression.Evaluate(nil) - // result is now "false", the boolean value -``` - -Functions can accept any number of arguments, correctly handles nested functions, and arguments can be of any type (even if none of this library's operators support evaluation of that type). For instance, each of these usages of functions in an expression are valid (assuming that the appropriate functions and parameters are given): - -```go -"sqrt(x1 ** y1, x2 ** y2)" -"max(someValue, abs(anotherValue), 10 * lastValue)" -``` - -Functions cannot be passed as parameters, they must be known at the time when the expression is parsed, and are unchangeable after parsing. - -Accessors --- - -If you have structs in your parameters, you can access their fields and methods in the usual way. For instance, given a struct that has a method "Echo", present in the parameters as `foo`, the following is valid: - - "foo.Echo('hello world')" - -Fields are accessed in a similar way. Assuming `foo` has a field called "Length": - - "foo.Length > 9000" - -The values of a `map` are accessed in the same way. Assuming the parameter `foo` is `map[string]int{ "bar": 1 }` - - "foo.bar == 1" - -Accessors can be nested to any depth, like the following - - "foo.Bar.Baz.SomeFunction()" - -This may be convenient, but note that using accessors involves a _lot_ of reflection. This makes the expression about four times slower than just using a parameter (consult the benchmarks for more precise measurements on your system). -If at all reasonable, the author recommends extracting the values you care about into a parameter map beforehand, or defining a struct that implements the `Parameters` interface, and which grabs fields as required. If there are functions you want to use, it's better to pass them as expression functions (see the above section). These approaches use no reflection, and are designed to be fast and clean. - -What operators and types does this support? --- - -* Modifiers: `+` `-` `/` `*` `&` `|` `^` `**` `%` `>>` `<<` -* Comparators: `>` `>=` `<` `<=` `==` `!=` `=~` `!~` -* Logical ops: `||` `&&` -* Numeric constants, as 64-bit floating point (`12345.678`) -* String constants (single quotes: `'foobar'`) -* Date constants (single quotes, using any permutation of RFC3339, ISO8601, ruby date, or unix date; date parsing is automatically tried with any string constant) -* Boolean constants: `true` `false` -* Parenthesis to control order of evaluation `(` `)` -* Arrays (anything separated by `,` within parenthesis: `(1, 2, 'foo')`) -* Prefixes: `!` `-` `~` -* Ternary conditional: `?` `:` -* Null coalescence: `??` - -See [MANUAL.md](https://github.com/casbin/govaluate/blob/master/MANUAL.md) for exacting details on what types each operator supports. - -Types --- - -Some operators don't make sense when used with some types. For instance, what does it mean to get the modulo of a string? What happens if you check to see if two numbers are logically AND'ed together? - -Everyone has a different intuition about the answers to these questions. To prevent confusion, this library will _refuse to operate_ upon types for which there is not an unambiguous meaning for the operation. See [MANUAL.md](https://github.com/casbin/govaluate/blob/master/MANUAL.md) for details about what operators are valid for which types. - -Benchmarks --- - -If you're concerned about the overhead of this library, a good range of benchmarks are built into this repo. You can run them with `go test -bench=.`. The library is built with an eye towards being quick, but has not been aggressively profiled and optimized. For most applications, though, it is completely fine. - -For a very rough idea of performance, here are the results output from a benchmark run on a 3rd-gen Macbook Pro (Linux Mint 17.1). - -``` -BenchmarkSingleParse-12 1000000 1382 ns/op -BenchmarkSimpleParse-12 200000 10771 ns/op -BenchmarkFullParse-12 30000 49383 ns/op -BenchmarkEvaluationSingle-12 50000000 30.1 ns/op -BenchmarkEvaluationNumericLiteral-12 10000000 119 ns/op -BenchmarkEvaluationLiteralModifiers-12 10000000 236 ns/op -BenchmarkEvaluationParameters-12 5000000 260 ns/op -BenchmarkEvaluationParametersModifiers-12 3000000 547 ns/op -BenchmarkComplexExpression-12 2000000 963 ns/op -BenchmarkRegexExpression-12 100000 20357 ns/op -BenchmarkConstantRegexExpression-12 1000000 1392 ns/op -ok -``` - -API Breaks --- - -While this library has very few cases which will ever result in an API break, it can happen. If you are using this in production, vendor the commit you've tested against, or use gopkg.in to redirect your import (e.g., `import "gopkg.in/casbin/govaluate.v1"`). Master branch (while infrequent) _may_ at some point contain API breaking changes, and the author will have no way to communicate these to downstreams, other than creating a new major release. - -Releases will explicitly state when an API break happens, and if they do not specify an API break it should be safe to upgrade. - -License --- - -This project is licensed under the MIT general use license. You're free to integrate, fork, and play with this code as you feel fit without consulting the author, as long as you provide proper credit to the author in your works. diff --git a/vendor/github.com/casbin/govaluate/TokenKind.go b/vendor/github.com/casbin/govaluate/TokenKind.go deleted file mode 100644 index 7c9516d2..00000000 --- a/vendor/github.com/casbin/govaluate/TokenKind.go +++ /dev/null @@ -1,75 +0,0 @@ -package govaluate - -/* - Represents all valid types of tokens that a token can be. -*/ -type TokenKind int - -const ( - UNKNOWN TokenKind = iota - - PREFIX - NUMERIC - BOOLEAN - STRING - PATTERN - TIME - VARIABLE - FUNCTION - SEPARATOR - ACCESSOR - - COMPARATOR - LOGICALOP - MODIFIER - - CLAUSE - CLAUSE_CLOSE - - TERNARY -) - -/* - GetTokenKindString returns a string that describes the given TokenKind. - e.g., when passed the NUMERIC TokenKind, this returns the string "NUMERIC". -*/ -func (kind TokenKind) String() string { - - switch kind { - - case PREFIX: - return "PREFIX" - case NUMERIC: - return "NUMERIC" - case BOOLEAN: - return "BOOLEAN" - case STRING: - return "STRING" - case PATTERN: - return "PATTERN" - case TIME: - return "TIME" - case VARIABLE: - return "VARIABLE" - case FUNCTION: - return "FUNCTION" - case SEPARATOR: - return "SEPARATOR" - case COMPARATOR: - return "COMPARATOR" - case LOGICALOP: - return "LOGICALOP" - case MODIFIER: - return "MODIFIER" - case CLAUSE: - return "CLAUSE" - case CLAUSE_CLOSE: - return "CLAUSE_CLOSE" - case TERNARY: - return "TERNARY" - case ACCESSOR: - return "ACCESSOR" - } - - return "UNKNOWN" -} diff --git a/vendor/github.com/casbin/govaluate/evaluationStage.go b/vendor/github.com/casbin/govaluate/evaluationStage.go deleted file mode 100644 index 965040a7..00000000 --- a/vendor/github.com/casbin/govaluate/evaluationStage.go +++ /dev/null @@ -1,542 +0,0 @@ -package govaluate - -import ( - "errors" - "fmt" - "math" - "reflect" - "regexp" - "strings" - "unicode" -) - -const ( - logicalErrorFormat string = "Value '%v' cannot be used with the logical operator '%v', it is not a bool" - modifierErrorFormat string = "Value '%v' cannot be used with the modifier '%v', it is not a number" - comparatorErrorFormat string = "Value '%v' cannot be used with the comparator '%v', it is not a number" - ternaryErrorFormat string = "Value '%v' cannot be used with the ternary operator '%v', it is not a bool" - prefixErrorFormat string = "Value '%v' cannot be used with the prefix '%v'" -) - -type evaluationOperator func(left interface{}, right interface{}, parameters Parameters) (interface{}, error) -type stageTypeCheck func(value interface{}) bool -type stageCombinedTypeCheck func(left interface{}, right interface{}) bool - -type evaluationStage struct { - symbol OperatorSymbol - - leftStage, rightStage *evaluationStage - - // the operation that will be used to evaluate this stage (such as adding [left] to [right] and return the result) - operator evaluationOperator - - // ensures that both left and right values are appropriate for this stage. Returns an error if they aren't operable. - leftTypeCheck stageTypeCheck - rightTypeCheck stageTypeCheck - - // if specified, will override whatever is used in "leftTypeCheck" and "rightTypeCheck". - // primarily used for specific operators that don't care which side a given type is on, but still requires one side to be of a given type - // (like string concat) - typeCheck stageCombinedTypeCheck - - // regardless of which type check is used, this string format will be used as the error message for type errors - typeErrorFormat string -} - -var ( - _true = interface{}(true) - _false = interface{}(false) -) - -func (this *evaluationStage) swapWith(other *evaluationStage) { - - temp := *other - other.setToNonStage(*this) - this.setToNonStage(temp) -} - -func (this *evaluationStage) setToNonStage(other evaluationStage) { - - this.symbol = other.symbol - this.operator = other.operator - this.leftTypeCheck = other.leftTypeCheck - this.rightTypeCheck = other.rightTypeCheck - this.typeCheck = other.typeCheck - this.typeErrorFormat = other.typeErrorFormat -} - -func (this *evaluationStage) isShortCircuitable() bool { - - switch this.symbol { - case AND: - fallthrough - case OR: - fallthrough - case TERNARY_TRUE: - fallthrough - case TERNARY_FALSE: - fallthrough - case COALESCE: - return true - } - - return false -} - -func noopStageRight(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return right, nil -} - -func addStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - - // string concat if either are strings - if isString(left) || isString(right) { - return fmt.Sprintf("%v%v", left, right), nil - } - - return left.(float64) + right.(float64), nil -} -func subtractStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return left.(float64) - right.(float64), nil -} -func multiplyStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return left.(float64) * right.(float64), nil -} -func divideStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return left.(float64) / right.(float64), nil -} -func exponentStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return math.Pow(left.(float64), right.(float64)), nil -} -func modulusStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return math.Mod(left.(float64), right.(float64)), nil -} -func gteStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - if isString(left) && isString(right) { - return boolIface(left.(string) >= right.(string)), nil - } - return boolIface(left.(float64) >= right.(float64)), nil -} -func gtStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - if isString(left) && isString(right) { - return boolIface(left.(string) > right.(string)), nil - } - return boolIface(left.(float64) > right.(float64)), nil -} -func lteStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - if isString(left) && isString(right) { - return boolIface(left.(string) <= right.(string)), nil - } - return boolIface(left.(float64) <= right.(float64)), nil -} -func ltStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - if isString(left) && isString(right) { - return boolIface(left.(string) < right.(string)), nil - } - return boolIface(left.(float64) < right.(float64)), nil -} -func equalStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return boolIface(reflect.DeepEqual(left, right)), nil -} -func notEqualStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return boolIface(!reflect.DeepEqual(left, right)), nil -} -func andStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return boolIface(left.(bool) && right.(bool)), nil -} -func orStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return boolIface(left.(bool) || right.(bool)), nil -} -func negateStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return -right.(float64), nil -} -func invertStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return boolIface(!right.(bool)), nil -} -func bitwiseNotStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return float64(^int64(right.(float64))), nil -} -func ternaryIfStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - if left.(bool) { - return right, nil - } - return nil, nil -} -func ternaryElseStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - if left != nil { - return left, nil - } - return right, nil -} - -func regexStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - - var pattern *regexp.Regexp - var err error - - switch right := right.(type) { - case string: - pattern, err = regexp.Compile(right) - if err != nil { - return nil, fmt.Errorf("Unable to compile regexp pattern '%v': %v", right, err) - } - case *regexp.Regexp: - pattern = right - } - - return pattern.Match([]byte(left.(string))), nil -} - -func notRegexStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - - ret, err := regexStage(left, right, parameters) - if err != nil { - return nil, err - } - - return !(ret.(bool)), nil -} - -func bitwiseOrStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return float64(int64(left.(float64)) | int64(right.(float64))), nil -} -func bitwiseAndStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return float64(int64(left.(float64)) & int64(right.(float64))), nil -} -func bitwiseXORStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return float64(int64(left.(float64)) ^ int64(right.(float64))), nil -} -func leftShiftStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return float64(uint64(left.(float64)) << uint64(right.(float64))), nil -} -func rightShiftStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return float64(uint64(left.(float64)) >> uint64(right.(float64))), nil -} - -func makeParameterStage(parameterName string) evaluationOperator { - - return func(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - value, err := parameters.Get(parameterName) - if err != nil { - return nil, err - } - - return value, nil - } -} - -func makeLiteralStage(literal interface{}) evaluationOperator { - return func(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - return literal, nil - } -} - -func makeFunctionStage(function ExpressionFunction) evaluationOperator { - - return func(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - - if right == nil { - return function() - } - - switch right := right.(type) { - case []interface{}: - return function(right...) - default: - return function(right) - } - } -} - -func typeConvertParam(p reflect.Value, t reflect.Type) (ret reflect.Value, err error) { - defer func() { - if r := recover(); r != nil { - errorMsg := fmt.Sprintf("Argument type conversion failed: failed to convert '%s' to '%s'", p.Kind().String(), t.Kind().String()) - err = errors.New(errorMsg) - ret = p - } - }() - - return p.Convert(t), nil -} - -func typeConvertParams(method reflect.Value, params []reflect.Value) ([]reflect.Value, error) { - - methodType := method.Type() - numIn := methodType.NumIn() - numParams := len(params) - - if numIn != numParams { - if numIn > numParams { - return nil, fmt.Errorf("Too few arguments to parameter call: got %d arguments, expected %d", len(params), numIn) - } - return nil, fmt.Errorf("Too many arguments to parameter call: got %d arguments, expected %d", len(params), numIn) - } - - for i := 0; i < numIn; i++ { - t := methodType.In(i) - p := params[i] - pt := p.Type() - - if t.Kind() != pt.Kind() { - np, err := typeConvertParam(p, t) - if err != nil { - return nil, err - } - params[i] = np - } - } - - return params, nil -} - -func makeAccessorStage(pair []string) evaluationOperator { - - reconstructed := strings.Join(pair, ".") - - return func(left interface{}, right interface{}, parameters Parameters) (ret interface{}, err error) { - - var params []reflect.Value - - value, err := parameters.Get(pair[0]) - if err != nil { - return nil, err - } - - // while this library generally tries to handle panic-inducing cases on its own, - // accessors are a sticky case which have a lot of possible ways to fail. - // therefore every call to an accessor sets up a defer that tries to recover from panics, converting them to errors. - defer func() { - if r := recover(); r != nil { - errorMsg := fmt.Sprintf("Failed to access '%s': %v", reconstructed, r.(string)) - err = errors.New(errorMsg) - ret = nil - } - }() - - LOOP: - for i := 1; i < len(pair); i++ { - - coreValue := reflect.ValueOf(value) - - var corePtrVal reflect.Value - - // if this is a pointer, resolve it. - if coreValue.Kind() == reflect.Ptr { - corePtrVal = coreValue - coreValue = coreValue.Elem() - } - - var field reflect.Value - var method reflect.Value - - switch coreValue.Kind() { - case reflect.Struct: - // check if field is exported - firstCharacter := getFirstRune(pair[i]) - if unicode.ToUpper(firstCharacter) != firstCharacter { - errorMsg := fmt.Sprintf("Unable to access unexported field '%s' in '%s'", pair[i], pair[i-1]) - return nil, errors.New(errorMsg) - } - - field = coreValue.FieldByName(pair[i]) - if field != (reflect.Value{}) { - value = field.Interface() - continue LOOP - } - - method = coreValue.MethodByName(pair[i]) - if method == (reflect.Value{}) { - if corePtrVal.IsValid() { - method = corePtrVal.MethodByName(pair[i]) - } - } - case reflect.Map: - field = coreValue.MapIndex(reflect.ValueOf(pair[i])) - if field != (reflect.Value{}) { - inter := field.Interface() - if inter != nil && reflect.TypeOf(inter).Kind() == reflect.Func { - method = reflect.ValueOf(inter) - } else { - value = inter - continue LOOP - } - } - default: - return nil, errors.New("Unable to access '" + pair[i] + "', '" + pair[i-1] + "' is not a struct or map") - } - - if method == (reflect.Value{}) { - return nil, errors.New("No method or field '" + pair[i] + "' present on parameter '" + pair[i-1] + "'") - } - - switch right := right.(type) { - case []interface{}: - - givenParams := right - params = make([]reflect.Value, len(givenParams)) - for idx := range givenParams { - params[idx] = reflect.ValueOf(givenParams[idx]) - } - - default: - - if right == nil { - params = []reflect.Value{} - break - } - - params = []reflect.Value{reflect.ValueOf(right)} - } - - params, err = typeConvertParams(method, params) - - if err != nil { - return nil, errors.New("Method call failed - '" + pair[0] + "." + pair[1] + "': " + err.Error()) - } - - returned := method.Call(params) - retLength := len(returned) - - if retLength == 0 { - return nil, errors.New("Method call '" + pair[i-1] + "." + pair[i] + "' did not return any values.") - } - - if retLength == 1 { - - value = returned[0].Interface() - continue - } - - if retLength == 2 { - - errIface := returned[1].Interface() - err, validType := errIface.(error) - - if validType && errIface != nil { - return returned[0].Interface(), err - } - - value = returned[0].Interface() - continue - } - - return nil, errors.New("Method call '" + pair[0] + "." + pair[1] + "' did not return either one value, or a value and an error. Cannot interpret meaning.") - } - - value = castToFloat64(value) - return value, nil - } -} - -func separatorStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - - var ret []interface{} - - switch left := left.(type) { - case []interface{}: - ret = append(left, right) - default: - ret = []interface{}{left, right} - } - - return ret, nil -} - -func inStage(left interface{}, right interface{}, parameters Parameters) (interface{}, error) { - - for _, value := range right.([]interface{}) { - value = castToFloat64(value) - if left == value { - return true, nil - } - } - return false, nil -} - -// - -func isString(value interface{}) bool { - - switch value.(type) { - case string: - return true - } - return false -} - -func isRegexOrString(value interface{}) bool { - - switch value.(type) { - case string: - return true - case *regexp.Regexp: - return true - } - return false -} - -func isBool(value interface{}) bool { - switch value.(type) { - case bool: - return true - } - return false -} - -func isFloat64(value interface{}) bool { - switch value.(type) { - case float64: - return true - } - return false -} - -/* -Addition usually means between numbers, but can also mean string concat. -String concat needs one (or both) of the sides to be a string. -*/ -func additionTypeCheck(left interface{}, right interface{}) bool { - - if isFloat64(left) && isFloat64(right) { - return true - } - if !isString(left) && !isString(right) { - return false - } - return true -} - -/* -Comparison can either be between numbers, or lexicographic between two strings, -but never between the two. -*/ -func comparatorTypeCheck(left interface{}, right interface{}) bool { - - if isFloat64(left) && isFloat64(right) { - return true - } - if isString(left) && isString(right) { - return true - } - return false -} - -func isArray(value interface{}) bool { - switch value.(type) { - case []interface{}: - return true - } - return false -} - -/* -Converting a boolean to an interface{} requires an allocation. -We can use interned bools to avoid this cost. -*/ -func boolIface(b bool) interface{} { - if b { - return _true - } - return _false -} diff --git a/vendor/github.com/casbin/govaluate/expressionFunctions.go b/vendor/github.com/casbin/govaluate/expressionFunctions.go deleted file mode 100644 index ac6592b3..00000000 --- a/vendor/github.com/casbin/govaluate/expressionFunctions.go +++ /dev/null @@ -1,8 +0,0 @@ -package govaluate - -/* - Represents a function that can be called from within an expression. - This method must return an error if, for any reason, it is unable to produce exactly one unambiguous result. - An error returned will halt execution of the expression. -*/ -type ExpressionFunction func(arguments ...interface{}) (interface{}, error) diff --git a/vendor/github.com/casbin/govaluate/expressionOutputStream.go b/vendor/github.com/casbin/govaluate/expressionOutputStream.go deleted file mode 100644 index 88a84163..00000000 --- a/vendor/github.com/casbin/govaluate/expressionOutputStream.go +++ /dev/null @@ -1,46 +0,0 @@ -package govaluate - -import ( - "bytes" -) - -/* - Holds a series of "transactions" which represent each token as it is output by an outputter (such as ToSQLQuery()). - Some outputs (such as SQL) require a function call or non-c-like syntax to represent an expression. - To accomplish this, this struct keeps track of each translated token as it is output, and can return and rollback those transactions. -*/ -type expressionOutputStream struct { - transactions []string -} - -func (this *expressionOutputStream) add(transaction string) { - this.transactions = append(this.transactions, transaction) -} - -func (this *expressionOutputStream) rollback() string { - - index := len(this.transactions) - 1 - ret := this.transactions[index] - - this.transactions = this.transactions[:index] - return ret -} - -func (this *expressionOutputStream) createString(delimiter string) string { - - var retBuffer bytes.Buffer - var transaction string - - penultimate := len(this.transactions) - 1 - - for i := 0; i < penultimate; i++ { - - transaction = this.transactions[i] - - retBuffer.WriteString(transaction) - retBuffer.WriteString(delimiter) - } - retBuffer.WriteString(this.transactions[penultimate]) - - return retBuffer.String() -} diff --git a/vendor/github.com/casbin/govaluate/lexerState.go b/vendor/github.com/casbin/govaluate/lexerState.go deleted file mode 100644 index 6726e909..00000000 --- a/vendor/github.com/casbin/govaluate/lexerState.go +++ /dev/null @@ -1,373 +0,0 @@ -package govaluate - -import ( - "errors" - "fmt" -) - -type lexerState struct { - isEOF bool - isNullable bool - kind TokenKind - validNextKinds []TokenKind -} - -// lexer states. -// Constant for all purposes except compiler. -var validLexerStates = []lexerState{ - - lexerState{ - kind: UNKNOWN, - isEOF: false, - isNullable: true, - validNextKinds: []TokenKind{ - - PREFIX, - NUMERIC, - BOOLEAN, - VARIABLE, - PATTERN, - FUNCTION, - ACCESSOR, - STRING, - TIME, - CLAUSE, - }, - }, - - lexerState{ - - kind: CLAUSE, - isEOF: false, - isNullable: true, - validNextKinds: []TokenKind{ - - PREFIX, - NUMERIC, - BOOLEAN, - VARIABLE, - PATTERN, - FUNCTION, - ACCESSOR, - STRING, - TIME, - CLAUSE, - CLAUSE_CLOSE, - }, - }, - - lexerState{ - - kind: CLAUSE_CLOSE, - isEOF: true, - isNullable: true, - validNextKinds: []TokenKind{ - - COMPARATOR, - MODIFIER, - NUMERIC, - BOOLEAN, - VARIABLE, - STRING, - PATTERN, - TIME, - CLAUSE, - CLAUSE_CLOSE, - LOGICALOP, - TERNARY, - SEPARATOR, - }, - }, - - lexerState{ - - kind: NUMERIC, - isEOF: true, - isNullable: false, - validNextKinds: []TokenKind{ - - MODIFIER, - COMPARATOR, - LOGICALOP, - CLAUSE_CLOSE, - TERNARY, - SEPARATOR, - }, - }, - lexerState{ - - kind: BOOLEAN, - isEOF: true, - isNullable: false, - validNextKinds: []TokenKind{ - - MODIFIER, - COMPARATOR, - LOGICALOP, - CLAUSE_CLOSE, - TERNARY, - SEPARATOR, - }, - }, - lexerState{ - - kind: STRING, - isEOF: true, - isNullable: false, - validNextKinds: []TokenKind{ - - MODIFIER, - COMPARATOR, - LOGICALOP, - CLAUSE_CLOSE, - TERNARY, - SEPARATOR, - }, - }, - lexerState{ - - kind: TIME, - isEOF: true, - isNullable: false, - validNextKinds: []TokenKind{ - - MODIFIER, - COMPARATOR, - LOGICALOP, - CLAUSE_CLOSE, - SEPARATOR, - }, - }, - lexerState{ - - kind: PATTERN, - isEOF: true, - isNullable: false, - validNextKinds: []TokenKind{ - - MODIFIER, - COMPARATOR, - LOGICALOP, - CLAUSE_CLOSE, - SEPARATOR, - }, - }, - lexerState{ - - kind: VARIABLE, - isEOF: true, - isNullable: false, - validNextKinds: []TokenKind{ - - MODIFIER, - COMPARATOR, - LOGICALOP, - CLAUSE_CLOSE, - TERNARY, - SEPARATOR, - }, - }, - lexerState{ - - kind: MODIFIER, - isEOF: false, - isNullable: false, - validNextKinds: []TokenKind{ - - PREFIX, - NUMERIC, - VARIABLE, - FUNCTION, - ACCESSOR, - STRING, - BOOLEAN, - CLAUSE, - CLAUSE_CLOSE, - }, - }, - lexerState{ - - kind: COMPARATOR, - isEOF: false, - isNullable: false, - validNextKinds: []TokenKind{ - - PREFIX, - NUMERIC, - BOOLEAN, - VARIABLE, - FUNCTION, - ACCESSOR, - STRING, - TIME, - CLAUSE, - CLAUSE_CLOSE, - PATTERN, - }, - }, - lexerState{ - - kind: LOGICALOP, - isEOF: false, - isNullable: false, - validNextKinds: []TokenKind{ - - PREFIX, - NUMERIC, - BOOLEAN, - VARIABLE, - FUNCTION, - ACCESSOR, - STRING, - TIME, - CLAUSE, - CLAUSE_CLOSE, - }, - }, - lexerState{ - - kind: PREFIX, - isEOF: false, - isNullable: false, - validNextKinds: []TokenKind{ - - NUMERIC, - BOOLEAN, - VARIABLE, - FUNCTION, - ACCESSOR, - CLAUSE, - CLAUSE_CLOSE, - }, - }, - - lexerState{ - - kind: TERNARY, - isEOF: false, - isNullable: false, - validNextKinds: []TokenKind{ - - PREFIX, - NUMERIC, - BOOLEAN, - STRING, - TIME, - VARIABLE, - FUNCTION, - ACCESSOR, - CLAUSE, - SEPARATOR, - }, - }, - lexerState{ - - kind: FUNCTION, - isEOF: false, - isNullable: false, - validNextKinds: []TokenKind{ - CLAUSE, - }, - }, - lexerState{ - - kind: ACCESSOR, - isEOF: true, - isNullable: false, - validNextKinds: []TokenKind{ - CLAUSE, - MODIFIER, - COMPARATOR, - LOGICALOP, - CLAUSE_CLOSE, - TERNARY, - SEPARATOR, - }, - }, - lexerState{ - - kind: SEPARATOR, - isEOF: false, - isNullable: true, - validNextKinds: []TokenKind{ - - PREFIX, - NUMERIC, - BOOLEAN, - STRING, - TIME, - VARIABLE, - FUNCTION, - ACCESSOR, - CLAUSE, - }, - }, -} - -func (this lexerState) canTransitionTo(kind TokenKind) bool { - - for _, validKind := range this.validNextKinds { - - if validKind == kind { - return true - } - } - - return false -} - -func checkExpressionSyntax(tokens []ExpressionToken) error { - - var state lexerState - var lastToken ExpressionToken - var err error - - state = validLexerStates[0] - - for _, token := range tokens { - - if !state.canTransitionTo(token.Kind) { - - // call out a specific error for tokens looking like they want to be functions. - if lastToken.Kind == VARIABLE && token.Kind == CLAUSE { - return errors.New("Undefined function " + lastToken.Value.(string)) - } - - firstStateName := fmt.Sprintf("%s [%v]", state.kind.String(), lastToken.Value) - nextStateName := fmt.Sprintf("%s [%v]", token.Kind.String(), token.Value) - - return errors.New("Cannot transition token types from " + firstStateName + " to " + nextStateName) - } - - state, err = getLexerStateForToken(token.Kind) - if err != nil { - return err - } - - if !state.isNullable && token.Value == nil { - - errorMsg := fmt.Sprintf("Token kind '%v' cannot have a nil value", token.Kind.String()) - return errors.New(errorMsg) - } - - lastToken = token - } - - if !state.isEOF { - return errors.New("Unexpected end of expression") - } - return nil -} - -func getLexerStateForToken(kind TokenKind) (lexerState, error) { - - for _, possibleState := range validLexerStates { - - if possibleState.kind == kind { - return possibleState, nil - } - } - - errorMsg := fmt.Sprintf("No lexer state found for token kind '%v'\n", kind.String()) - return validLexerStates[0], errors.New(errorMsg) -} diff --git a/vendor/github.com/casbin/govaluate/lexerStream.go b/vendor/github.com/casbin/govaluate/lexerStream.go deleted file mode 100644 index c6ed76ec..00000000 --- a/vendor/github.com/casbin/govaluate/lexerStream.go +++ /dev/null @@ -1,37 +0,0 @@ -package govaluate - -type lexerStream struct { - source []rune - position int - length int -} - -func newLexerStream(source string) *lexerStream { - - var ret *lexerStream - var runes []rune - - for _, character := range source { - runes = append(runes, character) - } - - ret = new(lexerStream) - ret.source = runes - ret.length = len(runes) - return ret -} - -func (this *lexerStream) readCharacter() rune { - - character := this.source[this.position] - this.position += 1 - return character -} - -func (this *lexerStream) rewind(amount int) { - this.position -= amount -} - -func (this lexerStream) canRead() bool { - return this.position < this.length -} diff --git a/vendor/github.com/casbin/govaluate/parameters.go b/vendor/github.com/casbin/govaluate/parameters.go deleted file mode 100644 index 6c5b9ecb..00000000 --- a/vendor/github.com/casbin/govaluate/parameters.go +++ /dev/null @@ -1,32 +0,0 @@ -package govaluate - -import ( - "errors" -) - -/* - Parameters is a collection of named parameters that can be used by an EvaluableExpression to retrieve parameters - when an expression tries to use them. -*/ -type Parameters interface { - - /* - Get gets the parameter of the given name, or an error if the parameter is unavailable. - Failure to find the given parameter should be indicated by returning an error. - */ - Get(name string) (interface{}, error) -} - -type MapParameters map[string]interface{} - -func (p MapParameters) Get(name string) (interface{}, error) { - - value, found := p[name] - - if !found { - errorMessage := "No parameter '" + name + "' found." - return nil, errors.New(errorMessage) - } - - return value, nil -} diff --git a/vendor/github.com/casbin/govaluate/parsing.go b/vendor/github.com/casbin/govaluate/parsing.go deleted file mode 100644 index dae78f7d..00000000 --- a/vendor/github.com/casbin/govaluate/parsing.go +++ /dev/null @@ -1,509 +0,0 @@ -package govaluate - -import ( - "bytes" - "errors" - "fmt" - "regexp" - "strconv" - "strings" - "time" - "unicode" -) - -func parseTokens(expression string, functions map[string]ExpressionFunction) ([]ExpressionToken, error) { - - var ret []ExpressionToken - var token ExpressionToken - var stream *lexerStream - var state lexerState - var err error - var found bool - - stream = newLexerStream(expression) - state = validLexerStates[0] - - for stream.canRead() { - - token, err, found = readToken(stream, state, functions) - - if err != nil { - return ret, err - } - - if !found { - break - } - - state, err = getLexerStateForToken(token.Kind) - if err != nil { - return ret, err - } - - // append this valid token - ret = append(ret, token) - } - - err = checkBalance(ret) - if err != nil { - return nil, err - } - - return ret, nil -} - -func readToken(stream *lexerStream, state lexerState, functions map[string]ExpressionFunction) (ExpressionToken, error, bool) { - - var function ExpressionFunction - var ret ExpressionToken - var tokenValue interface{} - var tokenTime time.Time - var tokenString string - var kind TokenKind - var character rune - var found bool - var completed bool - var err error - - // numeric is 0-9, or . or 0x followed by digits - // string starts with ' - // variable is alphanumeric, always starts with a letter - // bracket always means variable - // symbols are anything non-alphanumeric - // all others read into a buffer until they reach the end of the stream - for stream.canRead() { - - character = stream.readCharacter() - - if unicode.IsSpace(character) { - continue - } - - // numeric constant - if isNumeric(character) { - - if stream.canRead() && character == '0' { - character = stream.readCharacter() - - if stream.canRead() && character == 'x' { - tokenString, _ = readUntilFalse(stream, false, true, true, isHexDigit) - tokenValueInt, err := strconv.ParseUint(tokenString, 16, 64) - - if err != nil { - errorMsg := fmt.Sprintf("Unable to parse hex value '%v' to uint64\n", tokenString) - return ExpressionToken{}, errors.New(errorMsg), false - } - - kind = NUMERIC - tokenValue = float64(tokenValueInt) - break - } else { - stream.rewind(1) - } - } - - tokenString = readTokenUntilFalse(stream, isNumeric) - tokenValue, err = strconv.ParseFloat(tokenString, 64) - - if err != nil { - errorMsg := fmt.Sprintf("Unable to parse numeric value '%v' to float64\n", tokenString) - return ExpressionToken{}, errors.New(errorMsg), false - } - kind = NUMERIC - break - } - - // comma, separator - if character == ',' { - - tokenValue = "," - kind = SEPARATOR - break - } - - // escaped variable - if character == '[' { - - tokenValue, completed = readUntilFalse(stream, true, false, true, isNotClosingBracket) - kind = VARIABLE - - if !completed { - return ExpressionToken{}, errors.New("Unclosed parameter bracket"), false - } - - // above method normally rewinds us to the closing bracket, which we want to skip. - stream.rewind(-1) - break - } - - // regular variable - or function? - if unicode.IsLetter(character) { - - tokenString = readTokenUntilFalse(stream, isVariableName) - - tokenValue = tokenString - kind = VARIABLE - - // boolean? - if tokenValue == "true" { - - kind = BOOLEAN - tokenValue = true - } else { - - if tokenValue == "false" { - - kind = BOOLEAN - tokenValue = false - } - } - - // textual operator? - if tokenValue == "in" || tokenValue == "IN" { - - // force lower case for consistency - tokenValue = "in" - kind = COMPARATOR - } - - // function? - function, found = functions[tokenString] - if found { - kind = FUNCTION - tokenValue = function - } - - // accessor? - accessorIndex := strings.Index(tokenString, ".") - if accessorIndex > 0 { - - // check that it doesn't end with a hanging period - if tokenString[len(tokenString)-1] == '.' { - errorMsg := fmt.Sprintf("Hanging accessor on token '%s'", tokenString) - return ExpressionToken{}, errors.New(errorMsg), false - } - - kind = ACCESSOR - splits := strings.Split(tokenString, ".") - tokenValue = splits - } - break - } - - if !isNotQuote(character) { - tokenValue, completed = readUntilFalse(stream, true, false, true, isNotQuote) - - if !completed { - return ExpressionToken{}, errors.New("Unclosed string literal"), false - } - - // advance the stream one position, since reading until false assumes the terminator is a real token - stream.rewind(-1) - - // check to see if this can be parsed as a time. - tokenTime, found = tryParseTime(tokenValue.(string)) - if found { - kind = TIME - tokenValue = tokenTime - } else { - kind = STRING - } - break - } - - if character == '(' { - tokenValue = character - kind = CLAUSE - break - } - - if character == ')' { - tokenValue = character - kind = CLAUSE_CLOSE - break - } - - // must be a known symbol - tokenString = readTokenUntilFalse(stream, isNotAlphanumeric) - tokenValue = tokenString - - // quick hack for the case where "-" can mean "prefixed negation" or "minus", which are used - // very differently. - if state.canTransitionTo(PREFIX) { - _, found = prefixSymbols[tokenString] - if found { - - kind = PREFIX - break - } - } - _, found = modifierSymbols[tokenString] - if found { - - kind = MODIFIER - break - } - - _, found = logicalSymbols[tokenString] - if found { - - kind = LOGICALOP - break - } - - _, found = comparatorSymbols[tokenString] - if found { - - kind = COMPARATOR - break - } - - _, found = ternarySymbols[tokenString] - if found { - - kind = TERNARY - break - } - - errorMessage := fmt.Sprintf("Invalid token: '%s'", tokenString) - return ret, errors.New(errorMessage), false - } - - ret.Kind = kind - ret.Value = tokenValue - - return ret, nil, (kind != UNKNOWN) -} - -func readTokenUntilFalse(stream *lexerStream, condition func(rune) bool) string { - - var ret string - - stream.rewind(1) - ret, _ = readUntilFalse(stream, false, true, true, condition) - return ret -} - -/* -Returns the string that was read until the given [condition] was false, or whitespace was broken. -Returns false if the stream ended before whitespace was broken or condition was met. -*/ -func readUntilFalse(stream *lexerStream, includeWhitespace bool, breakWhitespace bool, allowEscaping bool, condition func(rune) bool) (string, bool) { - - var tokenBuffer bytes.Buffer - var character rune - var conditioned bool - - conditioned = false - - for stream.canRead() { - - character = stream.readCharacter() - - // Use backslashes to escape anything - if allowEscaping && character == '\\' { - - character = stream.readCharacter() - tokenBuffer.WriteString(string(character)) - continue - } - - if unicode.IsSpace(character) { - - if breakWhitespace && tokenBuffer.Len() > 0 { - conditioned = true - break - } - if !includeWhitespace { - continue - } - } - - if condition(character) { - tokenBuffer.WriteString(string(character)) - } else { - conditioned = true - stream.rewind(1) - break - } - } - - return tokenBuffer.String(), conditioned -} - -/* -Checks to see if any optimizations can be performed on the given [tokens], which form a complete, valid expression. -The returns slice will represent the optimized (or unmodified) list of tokens to use. -*/ -func optimizeTokens(tokens []ExpressionToken) ([]ExpressionToken, error) { - - var token ExpressionToken - var symbol OperatorSymbol - var err error - var index int - - for index, token = range tokens { - - // if we find a regex operator, and the right-hand value is a constant, precompile and replace with a pattern. - if token.Kind != COMPARATOR { - continue - } - - symbol = comparatorSymbols[token.Value.(string)] - if symbol != REQ && symbol != NREQ { - continue - } - - index++ - token = tokens[index] - if token.Kind == STRING { - - token.Kind = PATTERN - token.Value, err = regexp.Compile(token.Value.(string)) - - if err != nil { - return tokens, err - } - - tokens[index] = token - } - } - return tokens, nil -} - -/* -Checks the balance of tokens which have multiple parts, such as parenthesis. -*/ -func checkBalance(tokens []ExpressionToken) error { - - var stream *tokenStream - var token ExpressionToken - var parens int - - stream = newTokenStream(tokens) - - for stream.hasNext() { - - token = stream.next() - if token.Kind == CLAUSE { - parens++ - continue - } - if token.Kind == CLAUSE_CLOSE { - parens-- - continue - } - } - - if parens != 0 { - return errors.New("Unbalanced parenthesis") - } - return nil -} - -func isHexDigit(character rune) bool { - - character = unicode.ToLower(character) - - return unicode.IsDigit(character) || - character == 'a' || - character == 'b' || - character == 'c' || - character == 'd' || - character == 'e' || - character == 'f' -} - -func isNumeric(character rune) bool { - - return unicode.IsDigit(character) || character == '.' -} - -func isNotQuote(character rune) bool { - - return character != '\'' && character != '"' -} - -func isNotAlphanumeric(character rune) bool { - - return !(unicode.IsDigit(character) || - unicode.IsLetter(character) || - character == '(' || - character == ')' || - character == '[' || - character == ']' || // starting to feel like there needs to be an `isOperation` func (#59) - !isNotQuote(character)) -} - -func isVariableName(character rune) bool { - - return unicode.IsLetter(character) || - unicode.IsDigit(character) || - character == '_' || - character == '.' -} - -func isNotClosingBracket(character rune) bool { - - return character != ']' -} - -/* -Attempts to parse the [candidate] as a Time. -Tries a series of standardized date formats, returns the Time if one applies, -otherwise returns false through the second return. -*/ -func tryParseTime(candidate string) (time.Time, bool) { - - var ret time.Time - var found bool - - timeFormats := [...]string{ - time.ANSIC, - time.UnixDate, - time.RubyDate, - time.Kitchen, - time.RFC3339, - time.RFC3339Nano, - "2006-01-02", // RFC 3339 - "2006-01-02 15:04", // RFC 3339 with minutes - "2006-01-02 15:04:05", // RFC 3339 with seconds - "2006-01-02 15:04:05-07:00", // RFC 3339 with seconds and timezone - "2006-01-02T15Z0700", // ISO8601 with hour - "2006-01-02T15:04Z0700", // ISO8601 with minutes - "2006-01-02T15:04:05Z0700", // ISO8601 with seconds - "2006-01-02T15:04:05.999999999Z0700", // ISO8601 with nanoseconds - } - - for _, format := range timeFormats { - - ret, found = tryParseExactTime(candidate, format) - if found { - return ret, true - } - } - - return time.Now(), false -} - -func tryParseExactTime(candidate string, format string) (time.Time, bool) { - - var ret time.Time - var err error - - ret, err = time.ParseInLocation(format, candidate, time.Local) - if err != nil { - return time.Now(), false - } - - return ret, true -} - -func getFirstRune(candidate string) rune { - - for _, character := range candidate { - return character - } - - return 0 -} diff --git a/vendor/github.com/casbin/govaluate/sanitizedParameters.go b/vendor/github.com/casbin/govaluate/sanitizedParameters.go deleted file mode 100644 index b254bff6..00000000 --- a/vendor/github.com/casbin/govaluate/sanitizedParameters.go +++ /dev/null @@ -1,43 +0,0 @@ -package govaluate - -// sanitizedParameters is a wrapper for Parameters that does sanitization as -// parameters are accessed. -type sanitizedParameters struct { - orig Parameters -} - -func (p sanitizedParameters) Get(key string) (interface{}, error) { - value, err := p.orig.Get(key) - if err != nil { - return nil, err - } - - return castToFloat64(value), nil -} - -func castToFloat64(value interface{}) interface{} { - switch value := value.(type) { - case uint8: - return float64(value) - case uint16: - return float64(value) - case uint32: - return float64(value) - case uint64: - return float64(value) - case int8: - return float64(value) - case int16: - return float64(value) - case int32: - return float64(value) - case int64: - return float64(value) - case int: - return float64(value) - case float32: - return float64(value) - } - - return value -} diff --git a/vendor/github.com/casbin/govaluate/stagePlanner.go b/vendor/github.com/casbin/govaluate/stagePlanner.go deleted file mode 100644 index 400a2879..00000000 --- a/vendor/github.com/casbin/govaluate/stagePlanner.go +++ /dev/null @@ -1,728 +0,0 @@ -package govaluate - -import ( - "errors" - "fmt" - "time" -) - -var stageSymbolMap = map[OperatorSymbol]evaluationOperator{ - EQ: equalStage, - NEQ: notEqualStage, - GT: gtStage, - LT: ltStage, - GTE: gteStage, - LTE: lteStage, - REQ: regexStage, - NREQ: notRegexStage, - AND: andStage, - OR: orStage, - IN: inStage, - BITWISE_OR: bitwiseOrStage, - BITWISE_AND: bitwiseAndStage, - BITWISE_XOR: bitwiseXORStage, - BITWISE_LSHIFT: leftShiftStage, - BITWISE_RSHIFT: rightShiftStage, - PLUS: addStage, - MINUS: subtractStage, - MULTIPLY: multiplyStage, - DIVIDE: divideStage, - MODULUS: modulusStage, - EXPONENT: exponentStage, - NEGATE: negateStage, - INVERT: invertStage, - BITWISE_NOT: bitwiseNotStage, - TERNARY_TRUE: ternaryIfStage, - TERNARY_FALSE: ternaryElseStage, - COALESCE: ternaryElseStage, - SEPARATE: separatorStage, -} - -/* -A "precedent" is a function which will recursively parse new evaluateionStages from a given stream of tokens. -It's called a `precedent` because it is expected to handle exactly what precedence of operator, -and defer to other `precedent`s for other operators. -*/ -type precedent func(stream *tokenStream) (*evaluationStage, error) - -/* -A convenience function for specifying the behavior of a `precedent`. -Most `precedent` functions can be described by the same function, just with different type checks, symbols, and error formats. -This struct is passed to `makePrecedentFromPlanner` to create a `precedent` function. -*/ -type precedencePlanner struct { - validSymbols map[string]OperatorSymbol - validKinds []TokenKind - - typeErrorFormat string - - next precedent - nextRight precedent -} - -var planPrefix precedent -var planExponential precedent -var planMultiplicative precedent -var planAdditive precedent -var planBitwise precedent -var planShift precedent -var planComparator precedent -var planLogicalAnd precedent -var planLogicalOr precedent -var planTernary precedent -var planSeparator precedent - -func init() { - - // all these stages can use the same code (in `planPrecedenceLevel`) to execute, - // they simply need different type checks, symbols, and recursive precedents. - // While not all precedent phases are listed here, most can be represented this way. - planPrefix = makePrecedentFromPlanner(&precedencePlanner{ - validSymbols: prefixSymbols, - validKinds: []TokenKind{PREFIX}, - typeErrorFormat: prefixErrorFormat, - nextRight: planFunction, - }) - planExponential = makePrecedentFromPlanner(&precedencePlanner{ - validSymbols: exponentialSymbolsS, - validKinds: []TokenKind{MODIFIER}, - typeErrorFormat: modifierErrorFormat, - next: planFunction, - }) - planMultiplicative = makePrecedentFromPlanner(&precedencePlanner{ - validSymbols: multiplicativeSymbols, - validKinds: []TokenKind{MODIFIER}, - typeErrorFormat: modifierErrorFormat, - next: planExponential, - }) - planAdditive = makePrecedentFromPlanner(&precedencePlanner{ - validSymbols: additiveSymbols, - validKinds: []TokenKind{MODIFIER}, - typeErrorFormat: modifierErrorFormat, - next: planMultiplicative, - }) - planShift = makePrecedentFromPlanner(&precedencePlanner{ - validSymbols: bitwiseShiftSymbols, - validKinds: []TokenKind{MODIFIER}, - typeErrorFormat: modifierErrorFormat, - next: planAdditive, - }) - planBitwise = makePrecedentFromPlanner(&precedencePlanner{ - validSymbols: bitwiseSymbols, - validKinds: []TokenKind{MODIFIER}, - typeErrorFormat: modifierErrorFormat, - next: planShift, - }) - planComparator = makePrecedentFromPlanner(&precedencePlanner{ - validSymbols: comparatorSymbols, - validKinds: []TokenKind{COMPARATOR}, - typeErrorFormat: comparatorErrorFormat, - next: planBitwise, - }) - planLogicalAnd = makePrecedentFromPlanner(&precedencePlanner{ - validSymbols: map[string]OperatorSymbol{"&&": AND}, - validKinds: []TokenKind{LOGICALOP}, - typeErrorFormat: logicalErrorFormat, - next: planComparator, - }) - planLogicalOr = makePrecedentFromPlanner(&precedencePlanner{ - validSymbols: map[string]OperatorSymbol{"||": OR}, - validKinds: []TokenKind{LOGICALOP}, - typeErrorFormat: logicalErrorFormat, - next: planLogicalAnd, - }) - planTernary = makePrecedentFromPlanner(&precedencePlanner{ - validSymbols: ternarySymbols, - validKinds: []TokenKind{TERNARY}, - typeErrorFormat: ternaryErrorFormat, - next: planLogicalOr, - }) - planSeparator = makePrecedentFromPlanner(&precedencePlanner{ - validSymbols: separatorSymbols, - validKinds: []TokenKind{SEPARATOR}, - next: planTernary, - }) -} - -/* -Given a planner, creates a function which will evaluate a specific precedence level of operators, -and link it to other `precedent`s which recurse to parse other precedence levels. -*/ -func makePrecedentFromPlanner(planner *precedencePlanner) precedent { - - var generated precedent - var nextRight precedent - - generated = func(stream *tokenStream) (*evaluationStage, error) { - return planPrecedenceLevel( - stream, - planner.typeErrorFormat, - planner.validSymbols, - planner.validKinds, - nextRight, - planner.next, - ) - } - - if planner.nextRight != nil { - nextRight = planner.nextRight - } else { - nextRight = generated - } - - return generated -} - -/* -Creates a `evaluationStageList` object which represents an execution plan (or tree) -which is used to completely evaluate a set of tokens at evaluation-time. -The three stages of evaluation can be thought of as parsing strings to tokens, then tokens to a stage list, then evaluation with parameters. -*/ -func planStages(tokens []ExpressionToken) (*evaluationStage, error) { - - stream := newTokenStream(tokens) - - stage, err := planTokens(stream) - if err != nil { - return nil, err - } - - // while we're now fully-planned, we now need to re-order same-precedence operators. - // this could probably be avoided with a different planning method - reorderStages(stage) - - stage = elideLiterals(stage) - return stage, nil -} - -func planTokens(stream *tokenStream) (*evaluationStage, error) { - - if !stream.hasNext() { - return nil, nil - } - - return planSeparator(stream) -} - -/* -The most usual method of parsing an evaluation stage for a given precedence. -Most stages use the same logic -*/ -func planPrecedenceLevel( - stream *tokenStream, - typeErrorFormat string, - validSymbols map[string]OperatorSymbol, - validKinds []TokenKind, - rightPrecedent precedent, - leftPrecedent precedent) (*evaluationStage, error) { - - var token ExpressionToken - var symbol OperatorSymbol - var leftStage, rightStage *evaluationStage - var checks typeChecks - var err error - var keyFound bool - - if leftPrecedent != nil { - - leftStage, err = leftPrecedent(stream) - if err != nil { - return nil, err - } - } - - rewind := func() (*evaluationStage, error) { - stream.rewind() - return leftStage, nil - } - - if stream.hasNext() { - - token = stream.next() - - if len(validKinds) > 0 { - - keyFound = false - for _, kind := range validKinds { - if kind == token.Kind { - keyFound = true - break - } - } - - if !keyFound { - return rewind() - } - } - - if validSymbols != nil { - - if !isString(token.Value) { - return rewind() - } - - symbol, keyFound = validSymbols[token.Value.(string)] - if !keyFound { - return rewind() - } - } - - if rightPrecedent != nil { - rightStage, err = rightPrecedent(stream) - if err != nil { - return nil, err - } - } - - checks = findTypeChecks(symbol) - - return &evaluationStage{ - - symbol: symbol, - leftStage: leftStage, - rightStage: rightStage, - operator: stageSymbolMap[symbol], - - leftTypeCheck: checks.left, - rightTypeCheck: checks.right, - typeCheck: checks.combined, - typeErrorFormat: typeErrorFormat, - }, nil - } - - return rewind() -} - -/* -A special case where functions need to be of higher precedence than values, and need a special wrapped execution stage operator. -*/ -func planFunction(stream *tokenStream) (*evaluationStage, error) { - - var token ExpressionToken - var rightStage *evaluationStage - var err error - - token = stream.next() - - if token.Kind != FUNCTION { - stream.rewind() - return planAccessor(stream) - } - - rightStage, err = planAccessor(stream) - if err != nil { - return nil, err - } - - return &evaluationStage{ - - symbol: FUNCTIONAL, - rightStage: rightStage, - operator: makeFunctionStage(token.Value.(ExpressionFunction)), - typeErrorFormat: "Unable to run function '%v': %v", - }, nil -} - -func planAccessor(stream *tokenStream) (*evaluationStage, error) { - - var token, otherToken ExpressionToken - var rightStage *evaluationStage - var err error - - if !stream.hasNext() { - return nil, nil - } - - token = stream.next() - - if token.Kind != ACCESSOR { - stream.rewind() - return planValue(stream) - } - - // check if this is meant to be a function or a field. - // fields have a clause next to them, functions do not. - // if it's a function, parse the arguments. Otherwise leave the right stage null. - if stream.hasNext() { - - otherToken = stream.next() - if otherToken.Kind == CLAUSE { - - stream.rewind() - - rightStage, err = planTokens(stream) - if err != nil { - return nil, err - } - } else { - stream.rewind() - } - } - - return &evaluationStage{ - - symbol: ACCESS, - rightStage: rightStage, - operator: makeAccessorStage(token.Value.([]string)), - typeErrorFormat: "Unable to access parameter field or method '%v': %v", - }, nil -} - -/* -A truly special precedence function, this handles all the "lowest-case" errata of the process, including literals, parmeters, -clauses, and prefixes. -*/ -func planValue(stream *tokenStream) (*evaluationStage, error) { - - var token ExpressionToken - var symbol OperatorSymbol - var ret *evaluationStage - var operator evaluationOperator - var err error - - if !stream.hasNext() { - return nil, nil - } - - token = stream.next() - - switch token.Kind { - - case CLAUSE: - - ret, err = planTokens(stream) - if err != nil { - return nil, err - } - - // advance past the CLAUSE_CLOSE token. We know that it's a CLAUSE_CLOSE, because at parse-time we check for unbalanced parens. - stream.next() - - // the stage we got represents all of the logic contained within the parens - // but for technical reasons, we need to wrap this stage in a "noop" stage which breaks long chains of precedence. - // see github #33. - ret = &evaluationStage{ - rightStage: ret, - operator: noopStageRight, - symbol: NOOP, - } - - return ret, nil - - case CLAUSE_CLOSE: - - // when functions have empty params, this will be hit. In this case, we don't have any evaluation stage to do, - // so we just return nil so that the stage planner continues on its way. - stream.rewind() - return nil, nil - - case VARIABLE: - operator = makeParameterStage(token.Value.(string)) - - case NUMERIC: - fallthrough - case STRING: - fallthrough - case PATTERN: - fallthrough - case BOOLEAN: - symbol = LITERAL - operator = makeLiteralStage(token.Value) - case TIME: - symbol = LITERAL - operator = makeLiteralStage(float64(token.Value.(time.Time).Unix())) - - case PREFIX: - stream.rewind() - return planPrefix(stream) - } - - if operator == nil { - errorMsg := fmt.Sprintf("Unable to plan token kind: '%s', value: '%v'", token.Kind.String(), token.Value) - return nil, errors.New(errorMsg) - } - - return &evaluationStage{ - symbol: symbol, - operator: operator, - }, nil -} - -/* -Convenience function to pass a triplet of typechecks between `findTypeChecks` and `planPrecedenceLevel`. -Each of these members may be nil, which indicates that type does not matter for that value. -*/ -type typeChecks struct { - left stageTypeCheck - right stageTypeCheck - combined stageCombinedTypeCheck -} - -/* -Maps a given [symbol] to a set of typechecks to be used during runtime. -*/ -func findTypeChecks(symbol OperatorSymbol) typeChecks { - - switch symbol { - case GT: - fallthrough - case LT: - fallthrough - case GTE: - fallthrough - case LTE: - return typeChecks{ - combined: comparatorTypeCheck, - } - case REQ: - fallthrough - case NREQ: - return typeChecks{ - left: isString, - right: isRegexOrString, - } - case AND: - fallthrough - case OR: - return typeChecks{ - left: isBool, - right: isBool, - } - case IN: - return typeChecks{ - right: isArray, - } - case BITWISE_LSHIFT: - fallthrough - case BITWISE_RSHIFT: - fallthrough - case BITWISE_OR: - fallthrough - case BITWISE_AND: - fallthrough - case BITWISE_XOR: - return typeChecks{ - left: isFloat64, - right: isFloat64, - } - case PLUS: - return typeChecks{ - combined: additionTypeCheck, - } - case MINUS: - fallthrough - case MULTIPLY: - fallthrough - case DIVIDE: - fallthrough - case MODULUS: - fallthrough - case EXPONENT: - return typeChecks{ - left: isFloat64, - right: isFloat64, - } - case NEGATE: - return typeChecks{ - right: isFloat64, - } - case INVERT: - return typeChecks{ - right: isBool, - } - case BITWISE_NOT: - return typeChecks{ - right: isFloat64, - } - case TERNARY_TRUE: - return typeChecks{ - left: isBool, - } - - // unchecked cases - case EQ: - fallthrough - case NEQ: - return typeChecks{} - case TERNARY_FALSE: - fallthrough - case COALESCE: - fallthrough - default: - return typeChecks{} - } -} - -/* -During stage planning, stages of equal precedence are parsed such that they'll be evaluated in reverse order. -For commutative operators like "+" or "-", it's no big deal. But for order-specific operators, it ruins the expected result. -*/ -func reorderStages(rootStage *evaluationStage) { - - // traverse every rightStage until we find multiples in a row of the same precedence. - var identicalPrecedences []*evaluationStage - var currentStage, nextStage *evaluationStage - var precedence, currentPrecedence operatorPrecedence - - nextStage = rootStage - precedence = findOperatorPrecedenceForSymbol(rootStage.symbol) - - for nextStage != nil { - - currentStage = nextStage - nextStage = currentStage.rightStage - - // left depth first, since this entire method only looks for precedences down the right side of the tree - if currentStage.leftStage != nil { - reorderStages(currentStage.leftStage) - } - - currentPrecedence = findOperatorPrecedenceForSymbol(currentStage.symbol) - - if currentPrecedence == precedence { - identicalPrecedences = append(identicalPrecedences, currentStage) - continue - } - - // precedence break. - // See how many in a row we had, and reorder if there's more than one. - if len(identicalPrecedences) > 1 { - mirrorStageSubtree(identicalPrecedences) - } - - identicalPrecedences = []*evaluationStage{currentStage} - precedence = currentPrecedence - } - - if len(identicalPrecedences) > 1 { - mirrorStageSubtree(identicalPrecedences) - } -} - -/* -Performs a "mirror" on a subtree of stages. -This mirror functionally inverts the order of execution for all members of the [stages] list. -That list is assumed to be a root-to-leaf (ordered) list of evaluation stages, where each is a right-hand stage of the last. -*/ -func mirrorStageSubtree(stages []*evaluationStage) { - - var rootStage, inverseStage, carryStage, frontStage *evaluationStage - - stagesLength := len(stages) - - // reverse all right/left - for _, frontStage = range stages { - - carryStage = frontStage.rightStage - frontStage.rightStage = frontStage.leftStage - frontStage.leftStage = carryStage - } - - // end left swaps with root right - rootStage = stages[0] - frontStage = stages[stagesLength-1] - - carryStage = frontStage.leftStage - frontStage.leftStage = rootStage.rightStage - rootStage.rightStage = carryStage - - // for all non-root non-end stages, right is swapped with inverse stage right in list - for i := 0; i < (stagesLength-2)/2+1; i++ { - - frontStage = stages[i+1] - inverseStage = stages[stagesLength-i-1] - - carryStage = frontStage.rightStage - frontStage.rightStage = inverseStage.rightStage - inverseStage.rightStage = carryStage - } - - // swap all other information with inverse stages - for i := 0; i < stagesLength/2; i++ { - - frontStage = stages[i] - inverseStage = stages[stagesLength-i-1] - frontStage.swapWith(inverseStage) - } -} - -/* -Recurses through all operators in the entire tree, eliding operators where both sides are literals. -*/ -func elideLiterals(root *evaluationStage) *evaluationStage { - - if root.leftStage != nil { - root.leftStage = elideLiterals(root.leftStage) - } - - if root.rightStage != nil { - root.rightStage = elideLiterals(root.rightStage) - } - - return elideStage(root) -} - -/* -Elides a specific stage, if possible. -Returns the unmodified [root] stage if it cannot or should not be elided. -Otherwise, returns a new stage representing the condensed value from the elided stages. -*/ -func elideStage(root *evaluationStage) *evaluationStage { - - var leftValue, rightValue, result interface{} - var err error - - // right side must be a non-nil value. Left side must be nil or a value. - if root.rightStage == nil || - root.rightStage.symbol != LITERAL || - root.leftStage == nil || - root.leftStage.symbol != LITERAL { - return root - } - - // don't elide some operators - switch root.symbol { - case SEPARATE: - fallthrough - case IN: - return root - } - - // both sides are values, get their actual values. - // errors should be near-impossible here. If we encounter them, just abort this optimization. - leftValue, err = root.leftStage.operator(nil, nil, nil) - if err != nil { - return root - } - - rightValue, err = root.rightStage.operator(nil, nil, nil) - if err != nil { - return root - } - - // typcheck, since the grammar checker is a bit loose with which operator symbols go together. - err = typeCheck(root.leftTypeCheck, leftValue, root.symbol, root.typeErrorFormat) - if err != nil { - return root - } - - err = typeCheck(root.rightTypeCheck, rightValue, root.symbol, root.typeErrorFormat) - if err != nil { - return root - } - - if root.typeCheck != nil && !root.typeCheck(leftValue, rightValue) { - return root - } - - // pre-calculate, and return a new stage representing the result. - result, err = root.operator(leftValue, rightValue, nil) - if err != nil { - return root - } - - return &evaluationStage{ - symbol: LITERAL, - operator: makeLiteralStage(result), - } -} diff --git a/vendor/github.com/casbin/govaluate/test.sh b/vendor/github.com/casbin/govaluate/test.sh deleted file mode 100644 index 11aa8b33..00000000 --- a/vendor/github.com/casbin/govaluate/test.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/bash - -# Script that runs tests, code coverage, and benchmarks all at once. -# Builds a symlink in /tmp, mostly to avoid messing with GOPATH at the user's shell level. - -TEMPORARY_PATH="/tmp/govaluate_test" -SRC_PATH="${TEMPORARY_PATH}/src" -FULL_PATH="${TEMPORARY_PATH}/src/govaluate" - -# set up temporary directory -rm -rf "${FULL_PATH}" -mkdir -p "${SRC_PATH}" - -ln -s $(pwd) "${FULL_PATH}" -export GOPATH="${TEMPORARY_PATH}" - -pushd "${TEMPORARY_PATH}/src/govaluate" - -# run the actual tests. -export GOVALUATE_TORTURE_TEST="true" -go test -bench=. -benchmem #-coverprofile coverage.out -status=$? - -if [ "${status}" != 0 ]; -then - exit $status -fi - -# coverage -# disabled because travis go1.4 seems not to support it suddenly? -#go tool cover -func=coverage.out - -popd diff --git a/vendor/github.com/casbin/govaluate/tokenStream.go b/vendor/github.com/casbin/govaluate/tokenStream.go deleted file mode 100644 index 7c7c40ab..00000000 --- a/vendor/github.com/casbin/govaluate/tokenStream.go +++ /dev/null @@ -1,30 +0,0 @@ -package govaluate - -type tokenStream struct { - tokens []ExpressionToken - index int - tokenLength int -} - -func newTokenStream(tokens []ExpressionToken) *tokenStream { - ret := new(tokenStream) - ret.tokens = tokens - ret.tokenLength = len(tokens) - return ret -} - -func (this *tokenStream) rewind() { - this.index -= 1 -} - -func (this *tokenStream) next() ExpressionToken { - token := this.tokens[this.index] - - this.index += 1 - return token -} - -func (this tokenStream) hasNext() bool { - - return this.index < this.tokenLength -} diff --git a/vendor/modules.txt b/vendor/modules.txt index e102940a..ff1e8cfe 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -61,24 +61,6 @@ github.com/caddyserver/certmagic # github.com/caddyserver/zerossl v0.1.3 ## explicit; go 1.21.0 github.com/caddyserver/zerossl -# github.com/casbin/casbin/v2 v2.97.0 -## explicit; go 1.13 -github.com/casbin/casbin/v2 -github.com/casbin/casbin/v2/config -github.com/casbin/casbin/v2/constant -github.com/casbin/casbin/v2/effector -github.com/casbin/casbin/v2/errors -github.com/casbin/casbin/v2/log -github.com/casbin/casbin/v2/model -github.com/casbin/casbin/v2/persist -github.com/casbin/casbin/v2/persist/cache -github.com/casbin/casbin/v2/persist/file-adapter -github.com/casbin/casbin/v2/rbac -github.com/casbin/casbin/v2/rbac/default-role-manager -github.com/casbin/casbin/v2/util -# github.com/casbin/govaluate v1.2.0 -## explicit; go 1.13 -github.com/casbin/govaluate # github.com/cespare/xxhash/v2 v2.3.0 ## explicit; go 1.11 github.com/cespare/xxhash/v2