diff --git a/.github/workflows/default.yml b/.github/workflows/default.yml index bdf797f35..7741065ba 100644 --- a/.github/workflows/default.yml +++ b/.github/workflows/default.yml @@ -35,23 +35,8 @@ jobs: - name: Run go test bench run: make benchmark - lint: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - - name: Set up Go - uses: actions/setup-go@v2 - with: - go-version: '1.20' - - - name: golangci-lint - uses: golangci/golangci-lint-action@v3 - with: - version: v1.51 - semantic-release: - needs: [test, lint] + needs: test runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml new file mode 100644 index 000000000..77912565b --- /dev/null +++ b/.github/workflows/golangci-lint.yml @@ -0,0 +1,24 @@ +name: golangci-lint + +on: + push: + branches: + - master + - main + pull_request: + +jobs: + golangci: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: '1.21' + + - name: golangci-lint + uses: golangci/golangci-lint-action@v4 + with: + version: v1.56.2 \ No newline at end of file diff --git a/.github/workflows/staticcheck.yaml b/.github/workflows/staticcheck.yaml deleted file mode 100644 index 7cbb6f6aa..000000000 --- a/.github/workflows/staticcheck.yaml +++ /dev/null @@ -1,22 +0,0 @@ ---- -name: "staticcheck" -on: - push: - branches: - - main - paths: - - '**.go' - pull_request: - paths: - - '**.go' -jobs: - ci: - name: "staticcheck" - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 - with: - fetch-depth: 1 - - uses: dominikh/staticcheck-action@v1.2.0 - with: - version: "2022.1.1" diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..aec667949 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,344 @@ +# 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 + + +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/config/config.go b/config/config.go index e9f830308..57d40d849 100644 --- a/config/config.go +++ b/config/config.go @@ -26,17 +26,17 @@ import ( ) var ( - // DEFAULT_SECTION specifies the name of a section if no name provided + // DEFAULT_SECTION specifies the name of a section if no name provided. DEFAULT_SECTION = "default" - // DEFAULT_COMMENT defines what character(s) indicate a comment `#` + // DEFAULT_COMMENT defines what character(s) indicate a comment `#`. DEFAULT_COMMENT = []byte{'#'} - // DEFAULT_COMMENT_SEM defines what alternate character(s) indicate a comment `;` + // DEFAULT_COMMENT_SEM defines what alternate character(s) indicate a comment `;`. DEFAULT_COMMENT_SEM = []byte{';'} - // DEFAULT_MULTI_LINE_SEPARATOR defines what character indicates a multi-line content + // DEFAULT_MULTI_LINE_SEPARATOR defines what character indicates a multi-line content. DEFAULT_MULTI_LINE_SEPARATOR = []byte{'\\'} ) -// ConfigInterface defines the behavior of a Config implementation +// ConfigInterface defines the behavior of a Config implementation. type ConfigInterface interface { String(key string) string Strings(key string) []string @@ -47,7 +47,7 @@ type ConfigInterface interface { Set(key string, value string) error } -// Config represents an implementation of the ConfigInterface +// Config represents an implementation of the ConfigInterface. type Config struct { // Section:key=value data map[string]map[string]string @@ -116,7 +116,7 @@ func (c *Config) parseBuffer(buf *bufio.Reader) error { 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 { + if err = c.write(section, lineNum, &buffer); err != nil { return err } } @@ -185,33 +185,33 @@ func (c *Config) write(section string, lineNum int, b *bytes.Buffer) error { return nil } -// Bool lookups up the value using the provided key and converts the value to a bool +// 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 +// 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 +// 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 +// 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 +// 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 +// by splitting the string by comma. func (c *Config) Strings(key string) []string { v := c.get(key) if v == "" { @@ -220,7 +220,7 @@ func (c *Config) Strings(key string) []string { return strings.Split(v, ",") } -// Set sets the value for the specific key in the Config +// 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") @@ -243,7 +243,7 @@ func (c *Config) Set(key string, value string) error { return nil } -// section.key or key +// section.key or key. func (c *Config) get(key string) string { var ( section string diff --git a/enforcer.go b/enforcer.go index 52cb067b8..d5c3f5571 100644 --- a/enforcer.go +++ b/enforcer.go @@ -57,7 +57,7 @@ type Enforcer struct { logger log.Logger } -// EnforceContext is used as the first element of the parameter "rvals" in method "enforce" +// EnforceContext is used as the first element of the parameter "rvals" in method "enforce". type EnforceContext struct { RType string PType string @@ -539,7 +539,7 @@ func (e *Enforcer) EnableAutoBuildRoleLinks(autoBuildRoleLinks bool) { e.autoBuildRoleLinks = autoBuildRoleLinks } -// EnableAcceptJsonRequest controls whether to accept json as a request parameter +// EnableAcceptJsonRequest controls whether to accept json as a request parameter. func (e *Enforcer) EnableAcceptJsonRequest(acceptJsonRequest bool) { e.acceptJsonRequest = acceptJsonRequest } @@ -571,7 +571,7 @@ func (e *Enforcer) BuildIncrementalConditionalRoleLinks(op model.PolicyOp, ptype return e.model.BuildIncrementalConditionalRoleLinks(e.condRmMap, op, "g", ptype, rules) } -// NewEnforceContext Create a default structure based on the suffix +// NewEnforceContext Create a default structure based on the suffix. func NewEnforceContext(suffix string) EnforceContext { return EnforceContext{ RType: "r" + suffix, @@ -654,7 +654,8 @@ func (e *Enforcer) enforce(matcher string, explains *[]string, rvals ...interfac for i, rval := range rvals { switch rval := rval.(type) { case string: - mapValue, err := util.JsonToMap(rval) + var mapValue map[string]interface{} + mapValue, err = util.JsonToMap(rval) if err == nil { rvals[i] = mapValue } @@ -757,7 +758,6 @@ func (e *Enforcer) enforce(matcher string, explains *[]string, rvals ...interfac } } } 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") } @@ -836,21 +836,21 @@ func (e *Enforcer) EnforceWithMatcher(matcher string, rvals ...interface{}) (boo return e.enforce(matcher, nil, rvals...) } -// EnforceEx explain enforcement by informing matched rules +// 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 +// 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 +// BatchEnforce enforce in batches. func (e *Enforcer) BatchEnforce(requests [][]interface{}) ([]bool, error) { var results []bool for _, request := range requests { @@ -863,7 +863,7 @@ func (e *Enforcer) BatchEnforce(requests [][]interface{}) ([]bool, error) { return results, nil } -// BatchEnforceWithMatcher enforce with matcher in batches +// BatchEnforceWithMatcher enforce with matcher in batches. func (e *Enforcer) BatchEnforceWithMatcher(matcher string, requests [][]interface{}) ([]bool, error) { var results []bool for _, request := range requests { @@ -876,7 +876,7 @@ func (e *Enforcer) BatchEnforceWithMatcher(matcher string, requests [][]interfac return results, nil } -// AddNamedMatchingFunc add MatchingFunc by ptype RoleManager +// 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) @@ -885,7 +885,7 @@ func (e *Enforcer) AddNamedMatchingFunc(ptype, name string, fn rbac.MatchingFunc return false } -// AddNamedDomainMatchingFunc add MatchingFunc by ptype to RoleManager +// 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) @@ -895,7 +895,7 @@ func (e *Enforcer) AddNamedDomainMatchingFunc(ptype, name string, fn rbac.Matchi } // AddNamedLinkConditionFunc Add condition function fn for Link userName->roleName, -// when fn returns true, Link is valid, otherwise invalid +// 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) @@ -905,7 +905,7 @@ func (e *Enforcer) AddNamedLinkConditionFunc(ptype, user, role string, fn rbac.L } // AddNamedDomainLinkConditionFunc Add condition function fn for Link userName-> {roleName, domain}, -// when fn returns true, Link is valid, otherwise invalid +// 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) @@ -914,7 +914,7 @@ func (e *Enforcer) AddNamedDomainLinkConditionFunc(ptype, user, role string, dom return false } -// SetNamedLinkConditionFuncParams Sets the parameters of the condition function fn for Link userName->roleName +// 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...) @@ -924,7 +924,7 @@ func (e *Enforcer) SetNamedLinkConditionFuncParams(ptype, user, role string, par } // SetNamedDomainLinkConditionFuncParams Sets the parameters of the condition function fn -// for Link userName->{roleName, domain} +// 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...) @@ -933,7 +933,7 @@ func (e *Enforcer) SetNamedDomainLinkConditionFuncParams(ptype, user, role, doma return false } -// assumes bounds have already been checked +// assumes bounds have already been checked. type enforceParameters struct { rTokens map[string]int rVals []interface{} @@ -942,7 +942,7 @@ type enforceParameters struct { pVals []string } -// implements govaluate.Parameters +// implements govaluate.Parameters. func (p enforceParameters) Get(name string) (interface{}, error) { if name == "" { return nil, nil diff --git a/enforcer_cached.go b/enforcer_cached.go index 299f8813c..6008a2932 100644 --- a/enforcer_cached.go +++ b/enforcer_cached.go @@ -23,7 +23,7 @@ import ( "github.com/casbin/casbin/v2/persist/cache" ) -// CachedEnforcer wraps Enforcer and provides decision cache +// CachedEnforcer wraps Enforcer and provides decision cache. type CachedEnforcer struct { *Enforcer expireTime time.Duration @@ -61,7 +61,7 @@ func (e *CachedEnforcer) EnableCache(enableCache bool) { } // 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 , ingore the cache +// if rvals is not string , ingore the cache. func (e *CachedEnforcer) Enforce(rvals ...interface{}) (bool, error) { if atomic.LoadInt32(&e.enableCache) == 0 { return e.Enforcer.Enforce(rvals...) diff --git a/enforcer_cached_synced.go b/enforcer_cached_synced.go index 84157ea83..1669444af 100644 --- a/enforcer_cached_synced.go +++ b/enforcer_cached_synced.go @@ -22,7 +22,7 @@ import ( "github.com/casbin/casbin/v2/persist/cache" ) -// SyncedCachedEnforcer wraps Enforcer and provides decision sync cache +// SyncedCachedEnforcer wraps Enforcer and provides decision sync cache. type SyncedCachedEnforcer struct { *SyncedEnforcer expireTime time.Duration @@ -56,7 +56,7 @@ func (e *SyncedCachedEnforcer) EnableCache(enableCache bool) { } // 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 , ingore the cache +// if rvals is not string , ingore the cache. func (e *SyncedCachedEnforcer) Enforce(rvals ...interface{}) (bool, error) { if atomic.LoadInt32(&e.enableCache) == 0 { return e.SyncedEnforcer.Enforce(rvals...) @@ -129,7 +129,7 @@ func (e *SyncedCachedEnforcer) SetExpireTime(expireTime time.Duration) { e.expireTime = expireTime } -// SetCache need to be sync cache +// SetCache need to be sync cache. func (e *SyncedCachedEnforcer) SetCache(c cache.Cache) { e.locker.Lock() defer e.locker.Unlock() diff --git a/enforcer_distributed.go b/enforcer_distributed.go index c8743c4e9..a6e15d6e6 100644 --- a/enforcer_distributed.go +++ b/enforcer_distributed.go @@ -64,7 +64,7 @@ func (d *DistributedEnforcer) RemovePoliciesSelf(shouldPersist func() bool, sec 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 = d.adapter.(persist.BatchAdapter).RemovePolicies(sec, ptype, rules); err != nil { if err.Error() != notImplemented { return nil, err } @@ -74,7 +74,7 @@ func (d *DistributedEnforcer) RemovePoliciesSelf(shouldPersist func() bool, sec affected = d.model.RemovePoliciesWithAffected(sec, ptype, rules) if sec == "g" { - err := d.BuildIncrementalRoleLinks(model.PolicyRemove, ptype, affected) + err = d.BuildIncrementalRoleLinks(model.PolicyRemove, ptype, affected) if err != nil { return affected, err } diff --git a/enforcer_interface.go b/enforcer_interface.go index 58423e0ff..11cc9e4fd 100644 --- a/enforcer_interface.go +++ b/enforcer_interface.go @@ -26,7 +26,7 @@ var _ IEnforcer = &Enforcer{} var _ IEnforcer = &SyncedEnforcer{} var _ IEnforcer = &CachedEnforcer{} -// IEnforcer is the API interface of Enforcer +// IEnforcer is the API interface of Enforcer. type IEnforcer interface { /* Enforcer API */ InitWithFile(modelPath string, policyPath string) error diff --git a/enforcer_synced.go b/enforcer_synced.go index 16c2c8566..743f26c75 100644 --- a/enforcer_synced.go +++ b/enforcer_synced.go @@ -26,7 +26,7 @@ import ( defaultrolemanager "github.com/casbin/casbin/v2/rbac/default-role-manager" ) -// SyncedEnforcer wraps Enforcer and provides synchronized access +// SyncedEnforcer wraps Enforcer and provides synchronized access. type SyncedEnforcer struct { *Enforcer m sync.RWMutex @@ -48,17 +48,17 @@ func NewSyncedEnforcer(params ...interface{}) (*SyncedEnforcer, error) { return e, nil } -// GetLock return the private RWMutex lock +// GetLock return the private RWMutex lock. func (e *SyncedEnforcer) GetLock() *sync.RWMutex { return &e.m } -// IsAutoLoadingRunning check if SyncedEnforcer is auto loading policies +// 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 +// 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) { @@ -204,28 +204,28 @@ func (e *SyncedEnforcer) EnforceWithMatcher(matcher string, rvals ...interface{} return e.Enforcer.EnforceWithMatcher(matcher, rvals...) } -// EnforceEx explain enforcement by informing matched rules +// 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 +// 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 +// 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 +// BatchEnforceWithMatcher enforce with matcher in batches. func (e *SyncedEnforcer) BatchEnforceWithMatcher(matcher string, requests [][]interface{}) ([]bool, error) { e.m.RLock() defer e.m.RUnlock() @@ -378,7 +378,7 @@ func (e *SyncedEnforcer) AddPolicies(rules [][]string) (bool, error) { // 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 +// 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() @@ -405,7 +405,7 @@ func (e *SyncedEnforcer) AddNamedPolicies(ptype string, rules [][]string) (bool, // 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 +// 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() @@ -526,7 +526,7 @@ func (e *SyncedEnforcer) AddGroupingPolicies(rules [][]string) (bool, error) { // 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 +// 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() @@ -553,7 +553,7 @@ func (e *SyncedEnforcer) AddNamedGroupingPolicies(ptype string, rules [][]string // 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 +// 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() diff --git a/enforcer_synced_test.go b/enforcer_synced_test.go index 92c7dac2d..9a5ee4597 100644 --- a/enforcer_synced_test.go +++ b/enforcer_synced_test.go @@ -15,11 +15,12 @@ package casbin import ( - "github.com/casbin/casbin/v2/errors" - "github.com/casbin/casbin/v2/util" "sort" "testing" "time" + + "github.com/casbin/casbin/v2/errors" + "github.com/casbin/casbin/v2/util" ) func testEnforceSync(t *testing.T, e *SyncedEnforcer, sub string, obj interface{}, act string, res bool) { diff --git a/error_test.go b/error_test.go index 75e66a2bd..d0860c61b 100644 --- a/error_test.go +++ b/error_test.go @@ -58,7 +58,7 @@ func TestModelError(t *testing.T) { } } -//func TestPolicyError(t *testing.T) { +// func TestPolicyError(t *testing.T) { // _, err := NewEnforcer("examples/basic_model.conf", "examples/error/error_policy.csv") // if err == nil { // t.Errorf("Should be error here.") diff --git a/errors/rbac_errors.go b/errors/rbac_errors.go index 2f8974b48..2f358b372 100644 --- a/errors/rbac_errors.go +++ b/errors/rbac_errors.go @@ -16,7 +16,7 @@ package errors import "errors" -// Global errors for rbac defined here +// Global errors for rbac defined here. var ( ErrNameNotFound = errors.New("error: name does not exist") ErrDomainParameter = errors.New("error: domain should be 1 parameter") @@ -24,7 +24,7 @@ var ( ErrUseDomainParameter = errors.New("error: useDomain should be 1 parameter") ErrInvalidFieldValuesParameter = errors.New("fieldValues requires at least one parameter") - // GetAllowedObjectConditions errors + // 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/filter_test.go b/filter_test.go index 6fa7858ee..178495be8 100644 --- a/filter_test.go +++ b/filter_test.go @@ -133,7 +133,7 @@ func TestAppendFilteredPolicy(t *testing.T) { testHasPolicy(t, e, []string{"admin", "domain1", "data1", "read"}, true) testHasPolicy(t, e, []string{"admin", "domain2", "data2", "read"}, false) - //disable clear policy and load second domain + // disable clear policy and load second domain if err := e.LoadIncrementalFilteredPolicy(&fileadapter.Filter{ P: []string{"", "domain2"}, G: []string{"", "", "domain2"}, @@ -141,7 +141,7 @@ func TestAppendFilteredPolicy(t *testing.T) { t.Errorf("unexpected error in LoadFilteredPolicy: %v", err) } - //both domain policies should be loaded + // both domain policies should be loaded testHasPolicy(t, e, []string{"admin", "domain1", "data1", "read"}, true) testHasPolicy(t, e, []string{"admin", "domain2", "data2", "read"}, true) } diff --git a/internal_api.go b/internal_api.go index 42991b54a..d8183ed03 100644 --- a/internal_api.go +++ b/internal_api.go @@ -66,7 +66,7 @@ func (e *Enforcer) addPolicyWithoutNotify(sec string, ptype string, rule []strin // addPoliciesWithoutNotify adds rules to the current policy without notify // If autoRemoveRepeat == true, existing rules are automatically filtered -// Otherwise, false is returned directly +// 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) @@ -329,7 +329,7 @@ func (e *Enforcer) addPolicy(sec string, ptype string, rule []string) (bool, err // addPolicies adds rules to the current policy. // If autoRemoveRepeat == true, existing rules are automatically filtered -// Otherwise, false is returned directly +// 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 { @@ -364,7 +364,6 @@ func (e *Enforcer) removePolicy(sec string, ptype string, rule []string) (bool, err = e.watcher.Update() } return true, err - } return true, nil diff --git a/log/log_util.go b/log/log_util.go index 617c03931..7edabf899 100644 --- a/log/log_util.go +++ b/log/log_util.go @@ -46,7 +46,7 @@ func LogPolicy(policy map[string][][]string) { logger.LogPolicy(policy) } -// LogError logs the error information +// LogError logs the error information. func LogError(err error, msg ...string) { logger.LogError(err, msg...) } diff --git a/management_api.go b/management_api.go index 8613c6d91..de2e81fe4 100644 --- a/management_api.go +++ b/management_api.go @@ -216,7 +216,7 @@ func (e *Enforcer) AddPolicies(rules [][]string) (bool, error) { // 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 +// 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) } @@ -246,7 +246,7 @@ func (e *Enforcer) AddNamedPolicies(ptype string, rules [][]string) (bool, error // 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 +// 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) } @@ -350,7 +350,7 @@ func (e *Enforcer) AddGroupingPolicies(rules [][]string) (bool, error) { // 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 +// 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) } @@ -384,7 +384,7 @@ func (e *Enforcer) AddNamedGroupingPolicies(ptype string, rules [][]string) (boo // 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 +// 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) } diff --git a/model/assertion.go b/model/assertion.go index cbe0edd7f..2183e66c4 100644 --- a/model/assertion.go +++ b/model/assertion.go @@ -23,7 +23,7 @@ import ( ) // Assertion represents an expression in a section of the model. -// For example: r = sub, obj, act +// For example: r = sub, obj, act. type Assertion struct { Key string Value string @@ -147,7 +147,7 @@ func (ast *Assertion) buildConditionalRoleLinks(condRM rbac.ConditionalRoleManag return nil } -// addConditionalRoleLinks adds Link to rbac.ConditionalRoleManager and sets the parameters for LinkConditionFunc +// addConditionalRoleLinks 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 { diff --git a/model/function.go b/model/function.go index 1febb6d9e..f1a8d0075 100644 --- a/model/function.go +++ b/model/function.go @@ -53,7 +53,7 @@ func LoadFunctionMap() FunctionMap { return *fm } -// GetFunctions return a map with all the functions +// GetFunctions return a map with all the functions. func (fm *FunctionMap) GetFunctions() map[string]govaluate.ExpressionFunction { ret := make(map[string]govaluate.ExpressionFunction) diff --git a/model/model.go b/model/model.go index 5db4c2c3b..bf751bc04 100644 --- a/model/model.go +++ b/model/model.go @@ -46,7 +46,7 @@ var sectionNameMap = map[string]string{ "m": "matchers", } -// Minimal required sections for a model to be valid +// 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 { @@ -56,7 +56,7 @@ func loadAssertion(model Model, cfg config.ConfigInterface, sec string, key stri var paramsRegex = regexp.MustCompile(`\((.*?)\)`) -// getParamsToken Get ParamsToken from Assertion.Value +// getParamsToken Get ParamsToken from Assertion.Value. func getParamsToken(value string) []string { paramsString := paramsRegex.FindString(value) if paramsString == "" { diff --git a/model_test.go b/model_test.go index ab955b998..dd284f009 100644 --- a/model_test.go +++ b/model_test.go @@ -599,7 +599,7 @@ func CustomFunctionWrapper(args ...interface{}) (interface{}, error) { key1 := args[0].(string) key2 := args[1].(string) - return bool(CustomFunction(key1, key2)), nil + return CustomFunction(key1, key2), nil } func TestKeyMatchCustomModel(t *testing.T) { diff --git a/persist/dispatcher.go b/persist/dispatcher.go index 3eb4605b5..ceaed8385 100644 --- a/persist/dispatcher.go +++ b/persist/dispatcher.go @@ -14,7 +14,7 @@ package persist -// Dispatcher is the interface for Casbin dispatcher +// 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 diff --git a/persist/file-adapter/adapter_mock.go b/persist/file-adapter/adapter_mock.go index 8f8632b8f..fcc5f8218 100644 --- a/persist/file-adapter/adapter_mock.go +++ b/persist/file-adapter/adapter_mock.go @@ -73,12 +73,12 @@ func (a *AdapterMock) loadPolicyFile(model model.Model, handler func(string, mod } } -// SetMockErr sets string to be returned by of the mock during testing +// 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 +// GetMockErr returns a mock error or nil. func (a *AdapterMock) GetMockErr() error { var returnError error if a.errorValue != "" { diff --git a/persist/persist_test.go b/persist/persist_test.go index e37bfcb54..63077de84 100644 --- a/persist/persist_test.go +++ b/persist/persist_test.go @@ -23,7 +23,7 @@ import ( ) func TestPersist(t *testing.T) { - //No tests yet + // No tests yet } func testRuleCount(t *testing.T, model model.Model, expected int, sec string, ptype string, tag string) { @@ -45,7 +45,7 @@ func TestDuplicateRuleInAdapter(t *testing.T) { e.ClearPolicy() - //simulate adapter.LoadPolicy with duplicate rules + // simulate adapter.LoadPolicy with duplicate rules _ = persist.LoadPolicyArray([]string{"p", "alice", "data1", "read"}, e.GetModel()) _ = persist.LoadPolicyArray([]string{"p", "alice", "data1", "read"}, e.GetModel()) diff --git a/rbac/default-role-manager/role_manager.go b/rbac/default-role-manager/role_manager.go index 3b6ad8b44..a6ae8693c 100644 --- a/rbac/default-role-manager/role_manager.go +++ b/rbac/default-role-manager/role_manager.go @@ -59,12 +59,12 @@ func (r *Role) removeRole(role *Role) { role.removeUser(r) } -// should only be called inside addRole +// should only be called inside addRole. func (r *Role) addUser(user *Role) { r.users.Store(user.name, user) } -// should only be called inside removeRole +// should only be called inside removeRole. func (r *Role) removeUser(user *Role) { r.users.Delete(user.name) } @@ -195,7 +195,7 @@ func (r *Role) getLinkConditionFuncParams(role *Role, domain string) ([]string, return params.([]string), ok } -// RoleManagerImpl provides a default implementation for the RoleManager interface +// RoleManagerImpl provides a default implementation for the RoleManager interface. type RoleManagerImpl struct { allRoles *sync.Map maxHierarchyLevel int @@ -209,20 +209,20 @@ type RoleManagerImpl struct { // default RoleManager implementation. func NewRoleManagerImpl(maxHierarchyLevel int) *RoleManagerImpl { rm := RoleManagerImpl{} - _ = rm.Clear() //init allRoles and matchingFuncCache + _ = rm.Clear() // init allRoles and matchingFuncCache rm.maxHierarchyLevel = maxHierarchyLevel rm.SetLogger(&log.DefaultLogger{}) return &rm } -// use this constructor to avoid rebuild of AddMatchingFunc +// 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 +// rebuilds role cache. func (rm *RoleManagerImpl) rebuild() { roles := rm.allRoles _ = rm.Clear() @@ -263,7 +263,7 @@ func (rm *RoleManagerImpl) load(name interface{}) (value *Role, ok bool) { return nil, false } -// loads or creates a role +// loads or creates a role. func (rm *RoleManagerImpl) getRole(name string) (r *Role, created bool) { var role *Role var ok bool @@ -302,13 +302,13 @@ func (rm *RoleManagerImpl) removeRole(name string) { } } -// AddMatchingFunc support use pattern in g +// 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 +// AddDomainMatchingFunc support use domain pattern in g. func (rm *RoleManagerImpl) AddDomainMatchingFunc(name string, fn rbac.MatchingFunc) { rm.domainMatchingFunc = fn } @@ -424,13 +424,13 @@ func (rm *RoleManagerImpl) PrintRoles() error { return nil } -// GetDomains gets domains that a user has +// 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 +// GetAllDomains gets all domains. func (rm *RoleManagerImpl) GetAllDomains() ([]string, error) { domains := []string{defaultDomain} return domains, nil @@ -458,7 +458,7 @@ func (rm *RoleManagerImpl) Range(fn func(name1, name2 string, domain ...string) rangeLinks(rm.allRoles, fn) } -// Deprecated: BuildRelationship is no longer required +// Deprecated: BuildRelationship is no longer required. func (rm *RoleManagerImpl) BuildRelationship(name1 string, name2 string, domain ...string) error { return nil } @@ -486,7 +486,7 @@ func (dm *DomainManager) SetLogger(logger log.Logger) { dm.logger = logger } -// AddMatchingFunc support use pattern in g +// 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 { @@ -495,7 +495,7 @@ func (dm *DomainManager) AddMatchingFunc(name string, fn rbac.MatchingFunc) { }) } -// AddDomainMatchingFunc support use domain pattern in g +// 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 { @@ -505,7 +505,7 @@ func (dm *DomainManager) AddDomainMatchingFunc(name string, fn rbac.MatchingFunc dm.rebuild() } -// clears the map of RoleManagers +// clears the map of RoleManagers. func (dm *DomainManager) rebuild() { rmMap := dm.rmMap _ = dm.Clear() @@ -568,7 +568,7 @@ func (dm *DomainManager) load(name interface{}) (value *RoleManagerImpl, ok bool return nil, false } -// load or create a RoleManager instance of domain +// load or create a RoleManager instance of domain. func (dm *DomainManager) getRoleManager(domain string, store bool) *RoleManagerImpl { var rm *RoleManagerImpl var ok bool @@ -599,7 +599,7 @@ func (dm *DomainManager) AddLink(name1 string, name2 string, domains ...string) if err != nil { return err } - roleManager := dm.getRoleManager(domain, true) //create role manager if it does not exist + roleManager := dm.getRoleManager(domain, true) // create role manager if it does not exist _ = roleManager.AddLink(name1, name2, domains...) dm.rangeAffectedRoleManagers(domain, func(rm *RoleManagerImpl) { @@ -615,7 +615,7 @@ func (dm *DomainManager) DeleteLink(name1 string, name2 string, domains ...strin if err != nil { return err } - roleManager := dm.getRoleManager(domain, true) //create role manager if it does not exist + roleManager := dm.getRoleManager(domain, true) // create role manager if it does not exist _ = roleManager.DeleteLink(name1, name2, domains...) dm.rangeAffectedRoleManagers(domain, func(rm *RoleManagerImpl) { @@ -679,7 +679,7 @@ func (dm *DomainManager) PrintRoles() error { return nil } -// GetDomains gets domains that a user has +// 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 { @@ -697,18 +697,18 @@ func (dm *DomainManager) GetDomains(name string) ([]string, error) { return domains, nil } -// GetAllDomains gets all domains -func (rm *DomainManager) GetAllDomains() ([]string, error) { +// GetAllDomains gets all domains. +func (dm *DomainManager) GetAllDomains() ([]string, error) { var domains []string - rm.rmMap.Range(func(key, value interface{}) bool { + 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 (rm *DomainManager) BuildRelationship(name1 string, name2 string, domain ...string) error { +// Deprecated: BuildRelationship is no longer required. +func (dm *DomainManager) BuildRelationship(name1 string, name2 string, domain ...string) error { return nil } @@ -733,7 +733,7 @@ func (crm *ConditionalRoleManager) copyFrom(other *ConditionalRoleManager) { }) } -// use this constructor to avoid rebuild of AddMatchingFunc +// use this constructor to avoid rebuild of AddMatchingFunc. func newConditionalRoleManagerWithMatchingFunc(maxHierarchyLevel int, fn rbac.MatchingFunc) *ConditionalRoleManager { rm := NewConditionalRoleManager(maxHierarchyLevel) rm.matchingFunc = fn @@ -744,7 +744,7 @@ func newConditionalRoleManagerWithMatchingFunc(maxHierarchyLevel int, fn rbac.Ma // ConditionalRoleManager implementation. func NewConditionalRoleManager(maxHierarchyLevel int) *ConditionalRoleManager { rm := ConditionalRoleManager{} - _ = rm.Clear() //init allRoles and matchingFuncCache + _ = rm.Clear() // init allRoles and matchingFuncCache rm.maxHierarchyLevel = maxHierarchyLevel rm.SetLogger(&log.DefaultLogger{}) return &rm @@ -770,7 +770,7 @@ func (crm *ConditionalRoleManager) HasLink(name1 string, name2 string, domains . } // 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 +// 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 @@ -817,12 +817,12 @@ func (crm *ConditionalRoleManager) getNextRoles(currentRole, nextRole *Role, dom return true } -// GetLinkConditionFunc get LinkConditionFunc based on userName, roleName +// 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 +// 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) @@ -840,7 +840,7 @@ func (crm *ConditionalRoleManager) GetDomainLinkConditionFunc(userName, roleName return user.getLinkConditionFunc(role, domain) } -// GetLinkConditionFuncParams gets parameters of LinkConditionFunc based on userName, roleName, 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) @@ -867,12 +867,12 @@ func (crm *ConditionalRoleManager) GetLinkConditionFuncParams(userName, roleName } } -// AddLinkConditionFunc is based on userName, roleName, add LinkConditionFunc +// 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 +// 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) @@ -880,12 +880,12 @@ func (crm *ConditionalRoleManager) AddDomainLinkConditionFunc(userName, roleName user.addLinkConditionFunc(role, domain, fn) } -// SetLinkConditionFuncParams sets parameters of LinkConditionFunc based on userName, roleName, domain +// 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 +// 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) @@ -902,20 +902,20 @@ type ConditionalDomainManager struct { // ConditionalDomainManager implementation. func NewConditionalDomainManager(maxHierarchyLevel int) *ConditionalDomainManager { rm := ConditionalDomainManager{} - _ = rm.Clear() //init allRoles and matchingFuncCache + _ = rm.Clear() // init allRoles and matchingFuncCache rm.maxHierarchyLevel = maxHierarchyLevel rm.SetLogger(&log.DefaultLogger{}) return &rm } -func (dm *ConditionalDomainManager) load(name interface{}) (value *ConditionalRoleManager, ok bool) { - if r, ok := dm.rmMap.Load(name); ok { +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 +// load or create a ConditionalRoleManager instance of domain. func (cdm *ConditionalDomainManager) getConditionalRoleManager(domain string, store bool) *ConditionalRoleManager { var rm *ConditionalRoleManager var ok bool @@ -956,7 +956,7 @@ func (cdm *ConditionalDomainManager) AddLink(name1 string, name2 string, domains if err != nil { return err } - conditionalRoleManager := cdm.getConditionalRoleManager(domain, true) //create role manager if it does not exist + conditionalRoleManager := cdm.getConditionalRoleManager(domain, true) // create role manager if it does not exist _ = conditionalRoleManager.AddLink(name1, name2, domain) cdm.rangeAffectedRoleManagers(domain, func(rm *RoleManagerImpl) { @@ -972,7 +972,7 @@ func (cdm *ConditionalDomainManager) DeleteLink(name1 string, name2 string, doma if err != nil { return err } - conditionalRoleManager := cdm.getConditionalRoleManager(domain, true) //create role manager if it does not exist + conditionalRoleManager := cdm.getConditionalRoleManager(domain, true) // create role manager if it does not exist _ = conditionalRoleManager.DeleteLink(name1, name2, domain) cdm.rangeAffectedRoleManagers(domain, func(rm *RoleManagerImpl) { @@ -981,7 +981,7 @@ func (cdm *ConditionalDomainManager) DeleteLink(name1 string, name2 string, doma return nil } -// AddLinkConditionFunc is based on userName, roleName, add LinkConditionFunc +// 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) @@ -989,7 +989,7 @@ func (cdm *ConditionalDomainManager) AddLinkConditionFunc(userName, roleName str }) } -// AddDomainLinkConditionFunc is based on userName, roleName, domain, add LinkConditionFunc +// 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) @@ -997,7 +997,7 @@ func (cdm *ConditionalDomainManager) AddDomainLinkConditionFunc(userName, roleNa }) } -// SetLinkConditionFuncParams sets parameters of LinkConditionFunc based on userName, roleName +// 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...) @@ -1005,7 +1005,7 @@ func (cdm *ConditionalDomainManager) SetLinkConditionFuncParams(userName, roleNa }) } -// SetDomainLinkConditionFuncParams sets parameters of LinkConditionFunc based on userName, roleName, domain +// 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...) diff --git a/rbac/role_manager.go b/rbac/role_manager.go index d8a366913..28b40a352 100644 --- a/rbac/role_manager.go +++ b/rbac/role_manager.go @@ -58,7 +58,7 @@ type RoleManager interface { } // ConditionalRoleManager provides interface to define the operations for managing roles. -// Link with conditions is supported +// Link with conditions is supported. type ConditionalRoleManager interface { RoleManager diff --git a/rbac_api.go b/rbac_api.go index bee36b92c..49946b80b 100644 --- a/rbac_api.go +++ b/rbac_api.go @@ -223,7 +223,6 @@ func (e *Enforcer) GetImplicitRolesForUser(name string, domain ...string) ([]str res := []string{} for _, rm := range e.rmMap { - roleSet := make(map[string]bool) roleSet[name] = true q := make([]string, 0) @@ -255,7 +254,6 @@ func (e *Enforcer) GetImplicitUsersForRole(name string, domain ...string) ([]str res := []string{} for _, rm := range e.rmMap { - roleSet := make(map[string]bool) roleSet[name] = true q := make([]string, 0) @@ -303,7 +301,7 @@ func (e *Enforcer) GetImplicitPermissionsForUser(user string, domain ...string) // 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") +// But you can specify the named policy "p2" to get: [["admin", "create"]] by GetNamedImplicitPermissionsForUser("p2","alice"). func (e *Enforcer) GetNamedImplicitPermissionsForUser(ptype string, user string, domain ...string) ([][]string, error) { permission := make([][]string, 0) rm := e.GetRoleManager() @@ -370,7 +368,7 @@ func (e *Enforcer) GetImplicitUsersForPermission(permission ...string) ([]string return res, nil } -// GetDomainsForUser gets all domains +// GetDomainsForUser gets all domains. func (e *Enforcer) GetDomainsForUser(user string) ([]string, error) { var domains []string for _, rm := range e.rmMap { @@ -383,7 +381,7 @@ func (e *Enforcer) GetDomainsForUser(user string) ([]string, error) { return domains, nil } -// GetImplicitResourcesForUser returns all policies that user obtaining in domain +// 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 { @@ -422,7 +420,7 @@ func (e *Enforcer) GetImplicitResourcesForUser(user string, domain ...string) ([ return res, nil } -// deepCopyPolicy returns a deepcopy version of the policy to prevent changing policies through returned slice +// 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) @@ -533,7 +531,7 @@ func (e *Enforcer) GetImplicitUsersForResource(resource string) ([][]string, err } // GetImplicitUsersForResourceByDomain return implicit user based on resource and domain. -// Compared to GetImplicitUsersForResource, domain is supported +// 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") diff --git a/rbac_api_synced.go b/rbac_api_synced.go index a63b31e85..0bbf73849 100644 --- a/rbac_api_synced.go +++ b/rbac_api_synced.go @@ -181,7 +181,7 @@ func (e *SyncedEnforcer) GetImplicitPermissionsForUser(user string, domain ...st // 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") +// But you can specify the named policy "p2" to get: [["admin", "create"]] by GetNamedImplicitPermissionsForUser("p2","alice"). func (e *SyncedEnforcer) GetNamedImplicitPermissionsForUser(ptype string, user string, domain ...string) ([][]string, error) { e.m.RLock() defer e.m.RUnlock() diff --git a/rbac_api_test.go b/rbac_api_test.go index eed7e101e..c1edbc159 100644 --- a/rbac_api_test.go +++ b/rbac_api_test.go @@ -171,7 +171,6 @@ func TestRoleAPI_Domains(t *testing.T) { testGetPermissions(t, e, "admin", [][]string{{"admin", "domain1", "data1", "read"}, {"admin", "domain1", "data1", "write"}}, "domain1") testGetPermissions(t, e, "admin", [][]string{{"admin", "domain2", "data2", "read"}, {"admin", "domain2", "data2", "write"}}, "domain2") - } func TestEnforcer_AddRolesForUser(t *testing.T) { @@ -316,7 +315,7 @@ func TestImplicitRoleAPI(t *testing.T) { e.GetRoleManager().AddMatchingFunc("matcher", util.KeyMatch) e.AddNamedMatchingFunc("g2", "matcher", util.KeyMatch) - //testGetImplicitRoles(t, e, "cathy", []string{"/book/1/2/3/4/5", "pen_admin", "/book/*", "book_group"}) + // testGetImplicitRoles(t, e, "cathy", []string{"/book/1/2/3/4/5", "pen_admin", "/book/*", "book_group"}) testGetImplicitRoles(t, e, "cathy", []string{"/book/1/2/3/4/5", "pen_admin"}) testGetRoles(t, e, []string{"/book/1/2/3/4/5", "pen_admin"}, "cathy") } @@ -378,7 +377,6 @@ func TestImplicitPermissionAPI(t *testing.T) { testGetNamedImplicitPermissions(t, e, "p", "alice", [][]string{{"user", "/data", "GET"}, {"admin", "/data", "POST"}}) testGetNamedImplicitPermissions(t, e, "p2", "alice", [][]string{{"user", "view"}, {"admin", "create"}}) - } func TestImplicitPermissionAPIWithDomain(t *testing.T) { diff --git a/rbac_api_with_domains.go b/rbac_api_with_domains.go index 432143bb3..c96ec73c4 100644 --- a/rbac_api_with_domains.go +++ b/rbac_api_with_domains.go @@ -16,10 +16,11 @@ package casbin import ( "fmt" + "github.com/casbin/casbin/v2/constant" ) -// GetUsersForRoleInDomain gets the users that has a role inside a domain. Add by Gordon +// 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 diff --git a/rbac_api_with_domains_synced.go b/rbac_api_with_domains_synced.go index bf194e05b..26f6ce4ba 100644 --- a/rbac_api_with_domains_synced.go +++ b/rbac_api_with_domains_synced.go @@ -14,7 +14,7 @@ package casbin -// GetUsersForRoleInDomain gets the users that has a role inside a domain. Add by Gordon +// 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() diff --git a/rbac_api_with_domains_test.go b/rbac_api_with_domains_test.go index b1df57e68..d4826fffc 100644 --- a/rbac_api_with_domains_test.go +++ b/rbac_api_with_domains_test.go @@ -21,7 +21,7 @@ import ( "github.com/casbin/casbin/v2/util" ) -// testGetUsersInDomain: Add by Gordon +// testGetUsersInDomain: Add by Gordon. func testGetUsersInDomain(t *testing.T, e *Enforcer, name string, domain string, res []string) { t.Helper() myRes := e.GetUsersForRoleInDomain(name, domain) @@ -52,7 +52,7 @@ func TestGetImplicitRolesForDomainUser(t *testing.T) { testGetImplicitRolesInDomain(t, e, "alice", "domain1", []string{"role:global_admin", "role:reader", "role:writer"}) } -// TestUserAPIWithDomains: Add by Gordon +// TestUserAPIWithDomains: Add by Gordon. func TestUserAPIWithDomains(t *testing.T) { e, _ := NewEnforcer("examples/rbac_with_domains_model.conf", "examples/rbac_with_domains_policy.csv") @@ -164,7 +164,6 @@ func TestRoleAPIWithDomains(t *testing.T) { testGetRoles(t, e, []string{}, "non_exist", "domain2") testGetRolesInDomain(t, e, "non_exist", "domain2", []string{}) - } func testGetPermissionsInDomain(t *testing.T, e *Enforcer, name string, domain string, res [][]string) { @@ -251,7 +250,7 @@ func TestDeleteAllUsersByDomain(t *testing.T) { }) } -// testGetAllDomains tests GetAllDomains() +// testGetAllDomains tests GetAllDomains(). func testGetAllDomains(t *testing.T, e *Enforcer, res []string) { t.Helper() myRes, _ := e.GetAllDomains() @@ -285,5 +284,4 @@ func TestGetAllRolesByDomain(t *testing.T) { testGetAllRolesByDomain(t, e, "domain1", []string{"admin"}) testGetAllRolesByDomain(t, e, "domain2", []string{"admin"}) testGetAllRolesByDomain(t, e, "domain3", []string{"user"}) - } diff --git a/role_manager_b_test.go b/role_manager_b_test.go index 3d1657b8c..32da7f107 100644 --- a/role_manager_b_test.go +++ b/role_manager_b_test.go @@ -166,7 +166,6 @@ func BenchmarkHasLinkWithDomainPatternLarge(b *testing.B) { for i := 0; i < b.N; i++ { _, _ = rm.HasLink("staffUser1001", "staff001", "/orgs/1/sites/site001") } - } func BenchmarkHasLinkWithPatternAndDomainPatternLarge(b *testing.B) { diff --git a/util/builtin_operators.go b/util/builtin_operators.go index 80c9e43fb..bab9b0b3c 100644 --- a/util/builtin_operators.go +++ b/util/builtin_operators.go @@ -33,7 +33,7 @@ var ( keyMatch4Re *regexp.Regexp = regexp.MustCompile(`{([^/]+)}`) ) -// validate the variadic parameter size and type as string +// 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)) @@ -49,7 +49,7 @@ func validateVariadicArgs(expectedLen int, args ...interface{}) error { return nil } -// validate the variadic string parameter size +// 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)) @@ -58,7 +58,7 @@ func validateVariadicStringArgs(expectedLen int, args ...string) error { } // KeyMatch determines whether key1 matches the pattern of key2 (similar to RESTful path), key2 can contain a *. -// For example, "/foo/bar" matches "/foo/*" +// For example, "/foo/bar" matches "/foo/*". func KeyMatch(key1 string, key2 string) bool { i := strings.Index(key2, "*") if i == -1 { @@ -74,18 +74,18 @@ func KeyMatch(key1 string, key2 string) bool { // KeyMatchFunc is the wrapper for KeyMatch. func KeyMatchFunc(args ...interface{}) (interface{}, error) { if err := validateVariadicArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %s", "keyMatch", err) + return false, fmt.Errorf("%s: %w", "keyMatch", err) } name1 := args[0].(string) name2 := args[1].(string) - return bool(KeyMatch(name1, name2)), nil + return KeyMatch(name1, name2), nil } // KeyGet returns the matched part // For example, "/foo/bar/foo" matches "/foo/*" -// "bar/foo" will been returned +// "bar/foo" will been returned. func KeyGet(key1, key2 string) string { i := strings.Index(key2, "*") if i == -1 { @@ -99,10 +99,10 @@ func KeyGet(key1, key2 string) string { return "" } -// KeyGetFunc is the wrapper for KeyGet +// KeyGetFunc is the wrapper for KeyGet. func KeyGetFunc(args ...interface{}) (interface{}, error) { if err := validateVariadicArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %s", "keyGet", err) + return false, fmt.Errorf("%s: %w", "keyGet", err) } name1 := args[0].(string) @@ -112,7 +112,7 @@ func KeyGetFunc(args ...interface{}) (interface{}, error) { } // 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" +// For example, "/foo/bar" matches "/foo/*", "/resource1" matches "/:resource". func KeyMatch2(key1 string, key2 string) bool { key2 = strings.Replace(key2, "/*", "/.*", -1) @@ -125,18 +125,18 @@ func KeyMatch2(key1 string, key2 string) bool { // KeyMatch2Func is the wrapper for KeyMatch2. func KeyMatch2Func(args ...interface{}) (interface{}, error) { if err := validateVariadicArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %s", "keyMatch2", err) + return false, fmt.Errorf("%s: %w", "keyMatch2", err) } name1 := args[0].(string) name2 := args[1].(string) - return bool(KeyMatch2(name1, name2)), nil + return KeyMatch2(name1, name2), nil } // KeyGet2 returns value matched pattern // For example, "/resource1" matches "/:resource" -// if the pathVar == "resource", then "resource1" will be returned +// if the pathVar == "resource", then "resource1" will be returned. func KeyGet2(key1, key2 string, pathVar string) string { key2 = strings.Replace(key2, "/*", "/.*", -1) @@ -157,10 +157,10 @@ func KeyGet2(key1, key2 string, pathVar string) string { return "" } -// KeyGet2Func is the wrapper for KeyGet2 +// KeyGet2Func is the wrapper for KeyGet2. func KeyGet2Func(args ...interface{}) (interface{}, error) { if err := validateVariadicArgs(3, args...); err != nil { - return false, fmt.Errorf("%s: %s", "keyGet2", err) + return false, fmt.Errorf("%s: %w", "keyGet2", err) } name1 := args[0].(string) @@ -171,7 +171,7 @@ func KeyGet2Func(args ...interface{}) (interface{}, error) { } // 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}" +// For example, "/foo/bar" matches "/foo/*", "/resource1" matches "/{resource}". func KeyMatch3(key1 string, key2 string) bool { key2 = strings.Replace(key2, "/*", "/.*", -1) @@ -184,18 +184,18 @@ func KeyMatch3(key1 string, key2 string) bool { // KeyMatch3Func is the wrapper for KeyMatch3. func KeyMatch3Func(args ...interface{}) (interface{}, error) { if err := validateVariadicArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %s", "keyMatch3", err) + return false, fmt.Errorf("%s: %w", "keyMatch3", err) } name1 := args[0].(string) name2 := args[1].(string) - return bool(KeyMatch3(name1, name2)), nil + 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 +// if the pathVar == "project", then "project1" will be returned. func KeyGet3(key1, key2 string, pathVar string) string { key2 = strings.Replace(key2, "/*", "/.*", -1) @@ -216,10 +216,10 @@ func KeyGet3(key1, key2 string, pathVar string) string { return "" } -// KeyGet3Func is the wrapper for KeyGet3 +// KeyGet3Func is the wrapper for KeyGet3. func KeyGet3Func(args ...interface{}) (interface{}, error) { if err := validateVariadicArgs(3, args...); err != nil { - return false, fmt.Errorf("%s: %s", "keyGet3", err) + return false, fmt.Errorf("%s: %w", "keyGet3", err) } name1 := args[0].(string) @@ -273,20 +273,20 @@ func KeyMatch4(key1 string, key2 string) bool { // KeyMatch4Func is the wrapper for KeyMatch4. func KeyMatch4Func(args ...interface{}) (interface{}, error) { if err := validateVariadicArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %s", "keyMatch4", err) + return false, fmt.Errorf("%s: %w", "keyMatch4", err) } name1 := args[0].(string) name2 := args[1].(string) - return bool(KeyMatch4(name1, name2)), nil + 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/*" +// - "/parent/child1?status=1" matches "/parent/*". func KeyMatch5(key1 string, key2 string) bool { i := strings.Index(key1, "?") @@ -305,13 +305,13 @@ func KeyMatch5(key1 string, key2 string) bool { // KeyMatch5Func is the wrapper for KeyMatch5. func KeyMatch5Func(args ...interface{}) (interface{}, error) { if err := validateVariadicArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %s", "keyMatch5", err) + return false, fmt.Errorf("%s: %w", "keyMatch5", err) } name1 := args[0].(string) name2 := args[1].(string) - return bool(KeyMatch5(name1, name2)), nil + return KeyMatch5(name1, name2), nil } // RegexMatch determines whether key1 matches the pattern of key2 in regular expression. @@ -326,17 +326,17 @@ func RegexMatch(key1 string, key2 string) bool { // RegexMatchFunc is the wrapper for RegexMatch. func RegexMatchFunc(args ...interface{}) (interface{}, error) { if err := validateVariadicArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %s", "regexMatch", err) + return false, fmt.Errorf("%s: %w", "regexMatch", err) } name1 := args[0].(string) name2 := args[1].(string) - return bool(RegexMatch(name1, name2)), nil + 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" +// 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 { @@ -359,16 +359,16 @@ func IPMatch(ip1 string, ip2 string) bool { // IPMatchFunc is the wrapper for IPMatch. func IPMatchFunc(args ...interface{}) (interface{}, error) { if err := validateVariadicArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %s", "ipMatch", err) + return false, fmt.Errorf("%s: %w", "ipMatch", err) } ip1 := args[0].(string) ip2 := args[1].(string) - return bool(IPMatch(ip1, ip2)), nil + return IPMatch(ip1, ip2), nil } -// GlobMatch determines whether key1 matches the pattern of key2 using glob pattern +// 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) } @@ -376,7 +376,7 @@ func GlobMatch(key1 string, key2 string) (bool, error) { // GlobMatchFunc is the wrapper for GlobMatch. func GlobMatchFunc(args ...interface{}) (interface{}, error) { if err := validateVariadicArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %s", "globMatch", err) + return false, fmt.Errorf("%s: %w", "globMatch", err) } name1 := args[0].(string) @@ -453,13 +453,13 @@ func GenerateConditionalGFunction(crm rbac.ConditionalRoleManager) govaluate.Exp // TimeMatchFunc is the wrapper for TimeMatch. func TimeMatchFunc(args ...string) (bool, error) { if err := validateVariadicStringArgs(2, args...); err != nil { - return false, fmt.Errorf("%s: %s", "TimeMatch", err) + 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 +// You can use "_" to indicate that the parameter is ignored. func TimeMatch(startTime, endTime string) (bool, error) { now := time.Now() if startTime != "_" { diff --git a/util/builtin_operators_test.go b/util/builtin_operators_test.go index 70ea4c732..728bce7a2 100644 --- a/util/builtin_operators_test.go +++ b/util/builtin_operators_test.go @@ -479,7 +479,6 @@ func TestKeyMatch4Func(t *testing.T) { testKeyMatch4Func(t, true, "", "/parent/123/child/123", "/parent/{id}/child/{another_id}") testKeyMatch4Func(t, true, "", "/parent/123/child/456", "/parent/{id}/child/{another_id}") - } func TestKeyMatch5Func(t *testing.T) { @@ -522,7 +521,6 @@ func TestKeyMatch5Func(t *testing.T) { testKeyMatch5Func(t, true, "", "/proxy/myid/res/res2?status=1&type=2", "/proxy/{id}/*") testKeyMatch5Func(t, true, "", "/proxy/myid/res/res2/res3?status=1&type=2", "/proxy/{id}/*") testKeyMatch5Func(t, false, "", "/proxy/", "/proxy/{id}/*") - } func TestIPMatchFunc(t *testing.T) { diff --git a/util/util.go b/util/util.go index d91394eaf..0891e0dac 100644 --- a/util/util.go +++ b/util/util.go @@ -80,7 +80,7 @@ func Array2DEquals(a [][]string, b [][]string) bool { return true } -// SortArray2D Sorts the two-dimensional string array +// SortArray2D Sorts the two-dimensional string array. func SortArray2D(arr [][]string) { if len(arr) != 0 { sort.Slice(arr, func(i, j int) bool { @@ -233,12 +233,12 @@ func SetSubtract(a []string, b []string) []string { return diff } -// HasEval determine whether matcher contains function eval +// 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 +// ReplaceEval replace function eval with the value of its parameters. func ReplaceEval(s string, rule string) string { return evalReg.ReplaceAllString(s, "("+rule+")") } @@ -259,7 +259,7 @@ func ReplaceEvalWithMap(src string, sets map[string]string) string { }) } -// GetEvalValue returns the parameters of function eval +// GetEvalValue returns the parameters of function eval. func GetEvalValue(s string) []string { subMatch := evalReg.FindAllStringSubmatch(s, -1) var rules []string diff --git a/watcher_test.go b/watcher_test.go index 9edb792fe..1fe6c86b0 100644 --- a/watcher_test.go +++ b/watcher_test.go @@ -45,7 +45,7 @@ func TestSetWatcher(t *testing.T) { if err != nil { t.Fatal(err) } - err = e.SavePolicy() //calls watcher.Update() + err = e.SavePolicy() // calls watcher.Update() if err != nil { t.Fatal(err) } @@ -69,7 +69,7 @@ func TestSelfModify(t *testing.T) { _ = e.watcher.SetUpdateCallback(func(s string) { called = 1 }) - _, err = e.AddPolicy("eva", "data", "read") //calls watcher.Update() + _, err = e.AddPolicy("eva", "data", "read") // calls watcher.Update() if err != nil { t.Fatal(err) } @@ -81,7 +81,7 @@ func TestSelfModify(t *testing.T) { _ = e.watcher.SetUpdateCallback(func(s string) { called = 1 }) - _, err = e.SelfAddPolicy("p", "p", []string{"eva", "data", "write"}) //calls watcher.Update() + _, err = e.SelfAddPolicy("p", "p", []string{"eva", "data", "write"}) // calls watcher.Update() if err != nil { t.Fatal(err) } diff --git a/watcher_update_test.go b/watcher_update_test.go index 953a2fba9..081384fc8 100644 --- a/watcher_update_test.go +++ b/watcher_update_test.go @@ -37,5 +37,4 @@ func TestSetWatcherUpdatable(t *testing.T) { _ = e.SavePolicy() // calls watcherEx.UpdateForSavePolicy() _, _ = e.UpdatePolicy([]string{"admin", "data1", "read"}, []string{"admin", "data2", "read"}) // calls watcherEx.UpdateForUpdatePolicy() - }