diff --git a/.go-version b/.go-version index d8c40e539c..53cc1a6f92 100644 --- a/.go-version +++ b/.go-version @@ -1 +1 @@ -1.23.6 +1.24.0 diff --git a/.golangci.yaml b/.golangci.yaml index ce14ebccd3..0a9649e662 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -3,6 +3,10 @@ run: issues: max-same-issues: 0 # don't hide issues in CI runs because they are the same type + exclude-dirs: + - internal/gojsonschema + - internal/gqlparser + - internal/jwx exclude-rules: - path: ast/ linters: @@ -140,6 +144,37 @@ issues: linters-settings: lll: line-length: 200 + gocritic: + disabled-checks: + - appendAssign + # NOTE(ae): this one should be enabled, but there were too + # many violations to fix in one go... revisit later + - singleCaseSwitch + # Reasonable rule, but not sure what to replace with in + # many locations, so disabling for now + - exitAfterDefer + # The following 3 rules are disabled from the perfomance tag + # enabled further down. The first two are reasonable, but not + # super important. appendCombine is really nice though! And + # should be enabled. Just many places to fix.. + - hugeParam + - preferFprint + - appendCombine + enabled-checks: + # NOTE that these are rules enabled in addition to the default set + - filepathJoin + - dupImport + - redundantSprint + - stringConcatSimplify + enabled-tags: + - performance + settings: + ifElseChain: + # ridiculous value set for now, but this should be + # lowered to something more reasonable, as the rule + # is reasonable (replace long if-else chains with + # switch)... just too many violations right now + minThreshold: 10 govet: enable: - deepequalerrors @@ -175,4 +210,5 @@ linters: - unconvert - copyloopvar - perfsprint + - gocritic # - gosec # too many false positives diff --git a/ast/compile_test.go b/ast/compile_test.go index a2064c57fc..3560843342 100644 --- a/ast/compile_test.go +++ b/ast/compile_test.go @@ -66,10 +66,8 @@ func TestCompile_DefaultRegoVersion(t *testing.T) { if len(tc.expErrs) > 0 { assertErrors(t, compiler.Errors, tc.expErrs) - } else { - if len(compiler.Errors) > 0 { - t.Fatalf("Unexpected errors: %v", compiler.Errors) - } + } else if len(compiler.Errors) > 0 { + t.Fatalf("Unexpected errors: %v", compiler.Errors) } }) } diff --git a/ast/compilehelper_test.go b/ast/compilehelper_test.go index 4ffc4f213a..e6828be8a6 100644 --- a/ast/compilehelper_test.go +++ b/ast/compilehelper_test.go @@ -108,10 +108,8 @@ func TestCompileModules_DefaultRegoVersion(t *testing.T) { t.Fatalf("Expected error to contain:\n\n%s\n\nbut got:\n\n%s", expErr, err) } } - } else { - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error: %v", err) } }) } @@ -216,10 +214,8 @@ func TestCompileModulesWithOpt_DefaultRegoVersion(t *testing.T) { t.Fatalf("Expected error to contain:\n\n%s\n\nbut got:\n\n%s", expErr, err) } } - } else { - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error: %v", err) } }) } diff --git a/ast/parser_test.go b/ast/parser_test.go index c494c536a7..24487e2d06 100644 --- a/ast/parser_test.go +++ b/ast/parser_test.go @@ -21,7 +21,7 @@ func TestParser_DefaultRegoVersion(t *testing.T) { p[x] { c = ["a", "b", "c"][i] }`, - expStmtCount: 2, //package, p + expStmtCount: 2, // package, p }, { note: "v1", @@ -30,7 +30,7 @@ p contains x if { c = ["a", "b", "c"][i] }`, // v1 Keywords are not recognized, and interpreted as individual statements - expStmtCount: 5, //package, p, contains, x, if + expStmtCount: 5, // package, p, contains, x, if }, } diff --git a/build/generate-cli-docs/generate.go b/build/generate-cli-docs/generate.go index a5f1cb748b..b58b8de01b 100644 --- a/build/generate-cli-docs/generate.go +++ b/build/generate-cli-docs/generate.go @@ -47,7 +47,7 @@ func main() { err = doc.GenMarkdownTree(command, dir) if err != nil { - log.Fatal(err) + log.Fatal(err) //nolint: gocritic } files, err := os.ReadDir(dir) diff --git a/bundle/store_test.go b/bundle/store_test.go index 405779c230..8084050648 100644 --- a/bundle/store_test.go +++ b/bundle/store_test.go @@ -86,18 +86,6 @@ func TestHasRootsOverlap(t *testing.T) { } } - //err := hasRootsOverlap(ctx, mockStore, txn, bundles) - //if !tc.overlaps && err != nil { - // t.Fatalf("unepected error: %s", err) - //} else if tc.overlaps && (err == nil || !strings.Contains(err.Error(), "detected overlapping roots in bundle manifest")) { - // t.Fatalf("expected overlapping roots error, got: %s", err) - //} - - //err = mockStore.Commit(ctx, txn) - //if err != nil { - // t.Fatalf("unexpected error: %s", err) - //} - mockStore.AssertValid(t) }) } diff --git a/cmd/bench_test.go b/cmd/bench_test.go index d701228eb4..09c624bf27 100644 --- a/cmd/bench_test.go +++ b/cmd/bench_test.go @@ -175,7 +175,7 @@ func TestRunBenchmarkE2EWithOPAConfigFile(t *testing.T) { params := testBenchParams() params.e2e = true - params.configFile = filepath.Join(testDirRoot, "/config.yaml") + params.configFile = filepath.Join(testDirRoot, "config.yaml") args := []string{"1 + 1"} var buf bytes.Buffer @@ -580,7 +580,7 @@ func TestBenchMainInvalidInputFile(t *testing.T) { } args := []string{"1+1"} test.WithTempFS(files, func(path string) { - params.inputPath = filepath.Join(path, "definitely/not/input.yaml") + params.inputPath = filepath.Join(path, "definitely", "not", "input.yaml") var buf bytes.Buffer @@ -662,7 +662,7 @@ func TestBenchMainInvalidInputFileE2E(t *testing.T) { } args := []string{"1+1"} test.WithTempFS(files, func(path string) { - params.inputPath = filepath.Join(path, "definitely/not/input.yaml") + params.inputPath = filepath.Join(path, "definitely", "not", "input.yaml") var buf bytes.Buffer diff --git a/cmd/build_test.go b/cmd/build_test.go index 4bfef8a629..82f02e7549 100644 --- a/cmd/build_test.go +++ b/cmd/build_test.go @@ -190,7 +190,7 @@ import rego.v1`, for i := range tests { tc := tests[i] tc.bundleMode = true - tc.note = tc.note + " (as bundle)" + tc.note += " (as bundle)" tests = append(tests, tc) } diff --git a/cmd/check_test.go b/cmd/check_test.go index 64f5b7e48d..ae7f227b3e 100644 --- a/cmd/check_test.go +++ b/cmd/check_test.go @@ -149,7 +149,7 @@ import rego.v1`, for i := range tests { tc := tests[i] tc.bundleMode = true - tc.note = tc.note + " (as bundle)" + tc.note += " (as bundle)" tests = append(tests, tc) } diff --git a/cmd/deps_test.go b/cmd/deps_test.go index 4335f34a73..6e25d620ee 100644 --- a/cmd/deps_test.go +++ b/cmd/deps_test.go @@ -70,10 +70,8 @@ a contains x if { t.Fatalf("Expected error:\n\n%s\n\ngot:\n\n%s", expErr, err.Error()) } } - } else { - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error: %v", err) } }) }) @@ -249,10 +247,8 @@ p contains 3 if { t.Fatalf("Expected error:\n\n%s\n\ngot:\n\n%s", expErr, err.Error()) } } - } else { - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error: %v", err) } }) }) @@ -566,10 +562,8 @@ p contains 4 if { t.Fatalf("Expected error:\n\n%s\n\ngot:\n\n%s", expErr, err.Error()) } } - } else { - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error: %v", err) } }) }) diff --git a/cmd/inspect_test.go b/cmd/inspect_test.go index 2793150ff7..baa9f049eb 100644 --- a/cmd/inspect_test.go +++ b/cmd/inspect_test.go @@ -680,10 +680,8 @@ p contains v if { t.Fatalf("Expected error:\n\n%v\n\nbut got:\n\n%v", expErr, err.Error()) } } - } else { - if err != nil { - t.Fatalf("Unexpected error %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error %v", err) } }) }) diff --git a/cmd/internal/env/env.go b/cmd/internal/env/env.go index 54200f8a14..3d0adbe97a 100644 --- a/cmd/internal/env/env.go +++ b/cmd/internal/env/env.go @@ -33,7 +33,7 @@ func (cf cmdFlagsImpl) CheckEnvironmentVariables(command *cobra.Command) error { } command.Flags().VisitAll(func(f *pflag.Flag) { configName := f.Name - configName = strings.Replace(configName, "-", "_", -1) + configName = strings.ReplaceAll(configName, "-", "_") if !f.Changed && v.IsSet(configName) { val := v.Get(configName) err := command.Flags().Set(f.Name, fmt.Sprintf("%v", val)) diff --git a/cmd/internal/exec/exec_test.go b/cmd/internal/exec/exec_test.go index 38e49979d9..6a42e3c79f 100644 --- a/cmd/internal/exec/exec_test.go +++ b/cmd/internal/exec/exec_test.go @@ -237,7 +237,7 @@ func TestExec(t *testing.T) { }) err := Exec(ctx, opa, params) - output := strings.Replace(buf.String(), dir, "%ROOT%", -1) + output := strings.ReplaceAll(buf.String(), dir, "%ROOT%") tt.assertion(t, output, err) }) }) diff --git a/cmd/parse_test.go b/cmd/parse_test.go index ea09bdce0a..6a09632f5b 100644 --- a/cmd/parse_test.go +++ b/cmd/parse_test.go @@ -144,7 +144,7 @@ p = 1 t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr)) } - expectedOutput := strings.Replace(`{ + expectedOutput := strings.ReplaceAll(`{ "package": { "location": { "file": "TEMPDIR/x.rego", @@ -238,7 +238,7 @@ p = 1 } ] } -`, "TEMPDIR", tempDirPath, -1) +`, "TEMPDIR", tempDirPath) gotLines := strings.Split(string(stdout), "\n") wantLines := strings.Split(expectedOutput, "\n") @@ -350,7 +350,7 @@ a.b.c := true t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr)) } - expectedOutput := strings.Replace(`{ + expectedOutput := strings.ReplaceAll(`{ "package": { "location": { "file": "TEMPDIR/x.rego", @@ -464,7 +464,7 @@ a.b.c := true } ] } -`, "TEMPDIR", tempDirPath, -1) +`, "TEMPDIR", tempDirPath) gotLines := strings.Split(string(stdout), "\n") wantLines := strings.Split(expectedOutput, "\n") @@ -508,7 +508,7 @@ allow = true if { t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr)) } - expectedOutput := strings.Replace(`{ + expectedOutput := strings.ReplaceAll(`{ "package": { "location": { "file": "TEMPDIR/x.rego", @@ -925,7 +925,7 @@ allow = true if { } ] } -`, "TEMPDIR", tempDirPath, -1) +`, "TEMPDIR", tempDirPath) gotLines := strings.Split(string(stdout), "\n") wantLines := strings.Split(expectedOutput, "\n") @@ -1015,10 +1015,8 @@ a contains x if { t.Fatalf("Expected error:\n\n%q\n\ngot:\n\n%s", expErr, errs) } } - } else { - if len(stderr) > 0 { - t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr)) - } + } else if len(stderr) > 0 { + t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr)) } }) } @@ -1172,10 +1170,8 @@ p contains v if { t.Fatalf("Expected error:\n\n%q\n\ngot:\n\n%s", expErr, errs) } } - } else { - if len(stderr) > 0 { - t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr)) - } + } else if len(stderr) > 0 { + t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr)) } }) } diff --git a/cmd/sign_test.go b/cmd/sign_test.go index f7a832a5c6..47f0c67e02 100644 --- a/cmd/sign_test.go +++ b/cmd/sign_test.go @@ -176,10 +176,8 @@ func TestValidateSignParams(t *testing.T) { if tc.err != nil && tc.err.Error() != err.Error() { t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error()) } - } else { - if err != nil { - t.Fatalf("Unexpected error %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error %v", err) } }) } diff --git a/compile/compile_test.go b/compile/compile_test.go index e10291a006..78dbc82a07 100644 --- a/compile/compile_test.go +++ b/compile/compile_test.go @@ -386,10 +386,8 @@ p contains "B" if { t.Fatalf("expected error to contain:\n\n%s\n\ngot:\n\n%v", expErr, err) } } - } else { - if err != nil { - t.Fatal(err) - } + } else if err != nil { + t.Fatal(err) } }) }) diff --git a/internal/bundle/inspect/inspect_test.go b/internal/bundle/inspect/inspect_test.go index 70d7f818ea..757302caf3 100644 --- a/internal/bundle/inspect/inspect_test.go +++ b/internal/bundle/inspect/inspect_test.go @@ -54,8 +54,8 @@ func TestGenerateBundleInfoWithFileDir(t *testing.T) { expectedNamespaces := map[string][]string{ "data": {filepath.Join(rootDir, "data.json")}, "data.bar": {filepath.Join(rootDir, "base.rego")}, - "data.foo": {filepath.Join(rootDir, "baz/authz.rego"), filepath.Join(rootDir, "foo/policy.rego")}, - "data.fuz": {filepath.Join(rootDir, "fuz/fuz.rego"), filepath.Join(rootDir, "fuz/data.json")}, + "data.foo": {filepath.Join(rootDir, "baz", "authz.rego"), filepath.Join(rootDir, "foo", "policy.rego")}, + "data.fuz": {filepath.Join(rootDir, "fuz", "fuz.rego"), filepath.Join(rootDir, "fuz", "data.json")}, } if !reflect.DeepEqual(info.Namespaces, expectedNamespaces) { @@ -253,7 +253,7 @@ func TestGenerateBundleInfoWithBundleTarGz(t *testing.T) { expectedWasmModules := []map[string]interface{}{} expectedWasmModule1 := map[string]interface{}{ "path": "/example/policy.wasm", - "url": filepath.Join(bundleFile, "/example/policy.wasm"), + "url": filepath.Join(bundleFile, "example", "policy.wasm"), "entrypoints": []string{"data.http.example.foo.allow"}, } diff --git a/internal/bundle/utils.go b/internal/bundle/utils.go index 7252172ca8..836aa586b9 100644 --- a/internal/bundle/utils.go +++ b/internal/bundle/utils.go @@ -98,7 +98,7 @@ func LoadBundleFromDiskForRegoVersion(regoVersion ast.RegoVersion, path, name st _, err := os.Stat(bundlePath) if err == nil { - f, err := os.Open(filepath.Join(bundlePath)) + f, err := os.Open(bundlePath) if err != nil { return nil, err } diff --git a/internal/cidr/merge/merge.go b/internal/cidr/merge/merge.go index a019cde128..c2392b6775 100644 --- a/internal/cidr/merge/merge.go +++ b/internal/cidr/merge/merge.go @@ -114,7 +114,7 @@ func GetAddressRange(ipNet net.IPNet) (net.IP, net.IP) { copy(lastIPMask, ipNet.Mask) for i := range lastIPMask { lastIPMask[len(lastIPMask)-i-1] = ^lastIPMask[len(lastIPMask)-i-1] - lastIP[net.IPv6len-i-1] = lastIP[net.IPv6len-i-1] | lastIPMask[len(lastIPMask)-i-1] + lastIP[net.IPv6len-i-1] |= lastIPMask[len(lastIPMask)-i-1] } return firstIP, lastIP diff --git a/internal/compiler/utils_test.go b/internal/compiler/utils_test.go index 3471e7be9e..0bf2a25b72 100644 --- a/internal/compiler/utils_test.go +++ b/internal/compiler/utils_test.go @@ -127,10 +127,8 @@ func TestVerifyAuthorizationPolicySchema(t *testing.T) { t.Errorf("Expected error %v not found", e) } } - } else { - if err != nil { - t.Fatalf("Unexpected error %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error %v", err) } }) } diff --git a/internal/compiler/wasm/wasm.go b/internal/compiler/wasm/wasm.go index 22a84d67e5..25cbc13b47 100644 --- a/internal/compiler/wasm/wasm.go +++ b/internal/compiler/wasm/wasm.go @@ -340,7 +340,7 @@ func (c *Compiler) initModule() error { // two times. But let's deal with that when it happens. if _, ok := c.funcs[name]; ok { // already seen c.debug.Printf("function name duplicate: %s (%d)", name, fn.Index) - name = name + ".1" + name += ".1" } c.funcs[name] = fn.Index } @@ -348,7 +348,7 @@ func (c *Compiler) initModule() error { for _, fn := range c.policy.Funcs.Funcs { params := make([]types.ValueType, len(fn.Params)) - for i := 0; i < len(params); i++ { + for i := range params { params[i] = types.I32 } @@ -996,12 +996,16 @@ func (c *Compiler) compileBlock(block *ir.Block) ([]instruction.Instruction, err for _, stmt := range block.Stmts { switch stmt := stmt.(type) { case *ir.ResultSetAddStmt: - instrs = append(instrs, instruction.GetLocal{Index: c.lrs}) - instrs = append(instrs, instruction.GetLocal{Index: c.local(stmt.Value)}) - instrs = append(instrs, instruction.Call{Index: c.function(opaSetAdd)}) + instrs = append(instrs, + instruction.GetLocal{Index: c.lrs}, + instruction.GetLocal{Index: c.local(stmt.Value)}, + instruction.Call{Index: c.function(opaSetAdd)}, + ) case *ir.ReturnLocalStmt: - instrs = append(instrs, instruction.GetLocal{Index: c.local(stmt.Source)}) - instrs = append(instrs, instruction.Return{}) + instrs = append(instrs, + instruction.GetLocal{Index: c.local(stmt.Source)}, + instruction.Return{}, + ) case *ir.BlockStmt: for i := range stmt.Blocks { block, err := c.compileBlock(stmt.Blocks[i]) @@ -1029,8 +1033,10 @@ func (c *Compiler) compileBlock(block *ir.Block) ([]instruction.Instruction, err return instrs, err } case *ir.AssignVarStmt: - instrs = append(instrs, c.instrRead(stmt.Source)) - instrs = append(instrs, instruction.SetLocal{Index: c.local(stmt.Target)}) + instrs = append(instrs, + c.instrRead(stmt.Source), + instruction.SetLocal{Index: c.local(stmt.Target)}, + ) case *ir.AssignVarOnceStmt: instrs = append(instrs, instruction.Block{ Instrs: []instruction.Instruction{ @@ -1535,8 +1541,7 @@ func (c *Compiler) compileExternalCall(stmt *ir.CallStmt, ef externalFunc, resul } instrs := *result - instrs = append(instrs, instruction.I32Const{Value: ef.ID}) - instrs = append(instrs, instruction.I32Const{Value: 0}) // unused context parameter + instrs = append(instrs, instruction.I32Const{Value: ef.ID}, instruction.I32Const{Value: 0}) // unused context parameter for _, arg := range stmt.Args { instrs = append(instrs, c.instrRead(arg)) @@ -1545,9 +1550,11 @@ func (c *Compiler) compileExternalCall(stmt *ir.CallStmt, ef externalFunc, resul instrs = append(instrs, instruction.Call{Index: c.function(builtinDispatchers[len(stmt.Args)])}) if ef.Decl.Result() != nil { - instrs = append(instrs, instruction.TeeLocal{Index: c.local(stmt.Result)}) - instrs = append(instrs, instruction.I32Eqz{}) - instrs = append(instrs, instruction.BrIf{Index: 0}) + instrs = append(instrs, + instruction.TeeLocal{Index: c.local(stmt.Result)}, + instruction.I32Eqz{}, + instruction.BrIf{Index: 0}, + ) } else { instrs = append(instrs, instruction.Drop{}) } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index bc46cd71d4..694f399212 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -306,7 +306,7 @@ discovery: `} test.WithTempFS(fs, func(rootDir string) { - configFile := filepath.Join(rootDir, "/some/config.yaml") + configFile := filepath.Join(rootDir, "some", "config.yaml") configOverrides := []string{"services.acmecorp.credentials.bearer.token=bGFza2RqZmxha3NkamZsa2Fqc2Rsa2ZqYWtsc2RqZmtramRmYWxkc2tm"} configBytes, err := Load(configFile, configOverrides, nil) @@ -361,8 +361,8 @@ discovery: } test.WithTempFS(fs, func(rootDir string) { - configFile := filepath.Join(rootDir, "/some/config.yaml") - secretFile := filepath.Join(rootDir, "/some/secret.txt") + configFile := filepath.Join(rootDir, "some", "config.yaml") + secretFile := filepath.Join(rootDir, "some", "secret.txt") overrideFiles := []string{"services.acmecorp.credentials.bearer.token=" + secretFile} configBytes, err := Load(configFile, nil, overrideFiles) diff --git a/internal/distributedtracing/distributedtracing.go b/internal/distributedtracing/distributedtracing.go index 3fe11d3c13..e46928c48c 100644 --- a/internal/distributedtracing/distributedtracing.go +++ b/internal/distributedtracing/distributedtracing.go @@ -85,7 +85,7 @@ func Init(ctx context.Context, raw []byte, id string) (*otlptrace.Exporter, *tra return nil, nil, nil, err } - if strings.ToLower(distributedTracingConfig.Type) != "grpc" { + if !strings.EqualFold(distributedTracingConfig.Type, "grpc") { return nil, nil, nil, nil } diff --git a/internal/edittree/bitvector/bitvector.go b/internal/edittree/bitvector/bitvector.go index 89e7e137b7..8e4d65ed3f 100644 --- a/internal/edittree/bitvector/bitvector.go +++ b/internal/edittree/bitvector/bitvector.go @@ -36,7 +36,7 @@ func (vector *BitVector) Length() int { // position of the last byte in the slice. // This returns the bit that was shifted off of the last byte. func shiftLower(bit byte, b []byte) byte { - bit = bit << 7 + bit <<= 7 for i := len(b) - 1; i >= 0; i-- { newByte := b[i] >> 1 newByte |= bit diff --git a/internal/edittree/edittree.go b/internal/edittree/edittree.go index 0f2fec7b7b..378fe99a32 100644 --- a/internal/edittree/edittree.go +++ b/internal/edittree/edittree.go @@ -1180,5 +1180,5 @@ func (e *EditTree) Filter(paths []ast.Ref) *ast.Term { type termSlice []*ast.Term func (s termSlice) Less(i, j int) bool { return ast.Compare(s[i].Value, s[j].Value) < 0 } -func (s termSlice) Swap(i, j int) { x := s[i]; s[i] = s[j]; s[j] = x } +func (s termSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s termSlice) Len() int { return len(s) } diff --git a/internal/gqlparser/parser/testrunner/runner.go b/internal/gqlparser/parser/testrunner/runner.go index aac2ffa89b..7349ec78eb 100644 --- a/internal/gqlparser/parser/testrunner/runner.go +++ b/internal/gqlparser/parser/testrunner/runner.go @@ -86,7 +86,7 @@ func Test(t *testing.T, filename string, f func(t *testing.T, input string) Spec for i, tok := range result.Tokens { expected := spec.Tokens[i] - if !strings.EqualFold(strings.Replace(expected.Kind, "_", "", -1), tok.Kind) { + if !strings.EqualFold(strings.ReplaceAll(expected.Kind, "_", ""), tok.Kind) { t.Errorf("token[%d].kind should be %s, was %s", i, expected.Kind, tok.Kind) } if expected.Value != "undefined" && expected.Value != tok.Value { diff --git a/internal/gqlparser/validator/rules/values_of_correct_type.go b/internal/gqlparser/validator/rules/values_of_correct_type.go index 8858023d4e..afd9f54f10 100644 --- a/internal/gqlparser/validator/rules/values_of_correct_type.go +++ b/internal/gqlparser/validator/rules/values_of_correct_type.go @@ -159,8 +159,6 @@ func unexpectedTypeMessageOnly(v *ast.Value) ErrorOption { return Message(`Float cannot represent non numeric value: %s`, v.String()) case "ID", "ID!": return Message(`ID cannot represent a non-string and non-integer value: %s`, v.String()) - //case "Enum": - // return Message(`Enum "%s" cannot represent non-enum value: %s`, v.ExpectedType.String(), v.String()) default: if v.Definition.Kind == ast.Enum { return Message(`Enum "%s" cannot represent non-enum value: %s.`, v.ExpectedType.String(), v.String()) diff --git a/internal/gqlparser/validator/vars.go b/internal/gqlparser/validator/vars.go index 2329590154..66924148ba 100644 --- a/internal/gqlparser/validator/vars.go +++ b/internal/gqlparser/validator/vars.go @@ -223,7 +223,7 @@ func (v *varValidator) validateVarType(typ *ast.Type, val reflect.Value) (reflec if fieldDef.Type.NonNull && field.IsNil() { return val, gqlerror.ErrorPathf(v.path, "cannot be null") } - //allow null object field and skip it + // allow null object field and skip it if !fieldDef.Type.NonNull && field.IsNil() { continue } diff --git a/internal/json/patch/patch.go b/internal/json/patch/patch.go index 5506180799..9ddb93506e 100644 --- a/internal/json/patch/patch.go +++ b/internal/json/patch/patch.go @@ -37,8 +37,8 @@ func ParsePatchPathEscaped(str string) (path storage.Path, ok bool) { // the substitutions in this order, an implementation avoids the error of // turning '~01' first into '~1' and then into '/', which would be // incorrect (the string '~01' correctly becomes '~1' after transformation)." - path[i] = strings.Replace(path[i], "~1", "/", -1) - path[i] = strings.Replace(path[i], "~0", "~", -1) + path[i] = strings.ReplaceAll(path[i], "~1", "/") + path[i] = strings.ReplaceAll(path[i], "~0", "~") } return diff --git a/internal/jwx/jwk/jwk.go b/internal/jwx/jwk/jwk.go index aa22a3830f..7de27d4e4e 100644 --- a/internal/jwx/jwk/jwk.go +++ b/internal/jwx/jwk/jwk.go @@ -114,7 +114,7 @@ func parse(jwkSrc string) (*Set, error) { // ParseBytes parses JWK from the incoming byte buffer. func ParseBytes(buf []byte) (*Set, error) { - return parse(string(buf[:])) + return parse(string(buf)) } // ParseString parses JWK from the incoming string. diff --git a/internal/jwx/jws/jws.go b/internal/jwx/jws/jws.go index 2a5fe3c173..20fb957d3e 100644 --- a/internal/jwx/jws/jws.go +++ b/internal/jwx/jws/jws.go @@ -111,7 +111,7 @@ func Verify(buf []byte, alg jwa.SignatureAlgorithm, key interface{}) (ret []byte return nil, errors.New(`attempt to verify empty buffer`) } - parts, err := SplitCompact(string(buf[:])) + parts, err := SplitCompact(string(buf)) if err != nil { return nil, fmt.Errorf("failed extract from compact serialization format: %w", err) } @@ -164,7 +164,7 @@ func VerifyWithJWKSet(buf []byte, keyset *jwk.Set) (payload []byte, err error) { // ParseByte parses a JWS value serialized via compact serialization and provided as []byte. func ParseByte(jwsCompact []byte) (m *Message, err error) { - return parseCompact(string(jwsCompact[:])) + return parseCompact(string(jwsCompact)) } // ParseString parses a JWS value serialized via compact serialization and provided as string. diff --git a/internal/jwx/jws/jws_test.go b/internal/jwx/jws/jws_test.go index 3a694d4814..e6e7cafae8 100644 --- a/internal/jwx/jws/jws_test.go +++ b/internal/jwx/jws/jws_test.go @@ -336,7 +336,7 @@ func TestEncode(t *testing.T) { } // Verify with standard ecdsa library - parts, err := jws.SplitCompact(string(jwsCompact[:])) + parts, err := jws.SplitCompact(string(jwsCompact)) if err != nil { t.Fatal("Failed to split compact JWT") } diff --git a/internal/planner/planner.go b/internal/planner/planner.go index ae00580c48..2abde17216 100644 --- a/internal/planner/planner.go +++ b/internal/planner/planner.go @@ -497,7 +497,6 @@ func (p *Planner) planDotOr(obj ir.Local, key ir.Operand, or stmtFactory, iter p func (p *Planner) planNestedObjects(obj ir.Local, ref ast.Ref, iter planLocalIter) error { if len(ref) == 0 { - //return fmt.Errorf("nested object construction didn't create object") return iter(obj) } @@ -991,8 +990,7 @@ func (p *Planner) planExprCall(e *ast.Expr, iter planiter) error { op := e.Operator() if replacement := p.mocks.Lookup(operator); replacement != nil { - switch r := replacement.Value.(type) { - case ast.Ref: + if r, ok := replacement.Value.(ast.Ref); ok { if !r.HasPrefix(ast.DefaultRootRef) && !r.HasPrefix(ast.InputRootRef) { // replacement is builtin operator = r.String() diff --git a/internal/presentation/presentation.go b/internal/presentation/presentation.go index 9c2af88668..3168c63b2f 100644 --- a/internal/presentation/presentation.go +++ b/internal/presentation/presentation.go @@ -492,7 +492,7 @@ func prettyASTNode(x interface{}, regoVersion ast.RegoVersion) (string, int, err return "", 0, fmt.Errorf("format error: %w", err) } var maxLineWidth int - s := strings.Trim(strings.Replace(string(bs), "\t", " ", -1), "\n") + s := strings.Trim(strings.ReplaceAll(string(bs), "\t", " "), "\n") for _, line := range strings.Split(s, "\n") { width := tablewriter.DisplayWidth(line) if width > maxLineWidth { diff --git a/internal/providers/aws/signing_v4a.go b/internal/providers/aws/signing_v4a.go index bb7b65ba2a..59e49c1f30 100644 --- a/internal/providers/aws/signing_v4a.go +++ b/internal/providers/aws/signing_v4a.go @@ -216,7 +216,7 @@ func (s *httpSigner) Build() (signedRequest, error) { signedHeaders, signedHeadersStr, canonicalHeaderStr := s.buildCanonicalHeaders(host, v4Internal.IgnoredHeaders, unsignedHeaders, s.Request.ContentLength) - rawQuery := strings.Replace(query.Encode(), "+", "%20", -1) + rawQuery := strings.ReplaceAll(query.Encode(), "+", "%20") canonicalURI := v4Internal.GetURIPath(req.URL) diff --git a/internal/runtime/init/init_test.go b/internal/runtime/init/init_test.go index 9f60beb989..fe2983da8b 100644 --- a/internal/runtime/init/init_test.go +++ b/internal/runtime/init/init_test.go @@ -434,8 +434,7 @@ func TestWalkPaths(t *testing.T) { test.WithTempFS(files, func(rootDir string) { paths := []string{} - paths = append(paths, filepath.Join(rootDir, "bundle1")) - paths = append(paths, filepath.Join(rootDir, "bundle2")) + paths = append(paths, filepath.Join(rootDir, "bundle1"), filepath.Join(rootDir, "bundle2")) // bundle mode loaded, err := WalkPaths(paths, nil, true) diff --git a/internal/strings/strings.go b/internal/strings/strings.go index 08f3bf9182..f2838ac36a 100644 --- a/internal/strings/strings.go +++ b/internal/strings/strings.go @@ -57,7 +57,7 @@ func TruncateFilePaths(maxIdealWidth, maxWidth int, path ...string) (map[string] } // Drop the overall length down to match our substitution - longestLocation = longestLocation - (len(lcs) - 3) + longestLocation -= (len(lcs) - 3) } return result, longestLocation diff --git a/internal/strvals/parser.go b/internal/strvals/parser.go index 1eceb83df9..3b12d9526b 100644 --- a/internal/strvals/parser.go +++ b/internal/strvals/parser.go @@ -148,8 +148,6 @@ func (t *parser) key(data map[string]interface{}) error { return err } return fmt.Errorf("key %q has no value", string(k)) - //set(data, string(k), "") - //return err case last == '[': // We are in a list index context, so we need to set an index. i, err := t.keyIndex() @@ -168,7 +166,7 @@ func (t *parser) key(data map[string]interface{}) error { set(data, kk, list) return err case last == '=': - //End of key. Consume =, Get value. + // End of key. Consume =, Get value. // FIXME: Get value list first vl, e := t.valList() switch e { diff --git a/internal/strvals/parser_test.go b/internal/strvals/parser_test.go index a31410d809..c395430c84 100644 --- a/internal/strvals/parser_test.go +++ b/internal/strvals/parser_test.go @@ -16,6 +16,7 @@ limitations under the License. package strvals import ( + "bytes" "testing" "sigs.k8s.io/yaml" @@ -382,7 +383,7 @@ func TestParseSet(t *testing.T) { t.Fatalf("Error serializing parsed value: %s", err) } - if string(y1) != string(y2) { + if !bytes.Equal(y1, y2) { t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.str, y1, y2) } } @@ -407,7 +408,7 @@ func TestParseSet(t *testing.T) { t.Fatalf("Error serializing parsed value: %s", err) } - if string(y1) != string(y2) { + if !bytes.Equal(y1, y2) { t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.str, y1, y2) } } @@ -443,7 +444,7 @@ func TestParseInto(t *testing.T) { t.Fatalf("Error serializing parsed value: %s", err) } - if string(y1) != string(y2) { + if !bytes.Equal(y1, y2) { t.Errorf("%s: Expected:\n%s\nGot:\n%s", input, y1, y2) } } @@ -476,7 +477,7 @@ func TestParseIntoString(t *testing.T) { t.Fatalf("Error serializing parsed value: %s", err) } - if string(y1) != string(y2) { + if !bytes.Equal(y1, y2) { t.Errorf("%s: Expected:\n%s\nGot:\n%s", input, y1, y2) } } @@ -509,7 +510,7 @@ func TestParseIntoFile(t *testing.T) { t.Fatalf("Error serializing parsed value: %s", err) } - if string(y1) != string(y2) { + if !bytes.Equal(y1, y2) { t.Errorf("%s: Expected:\n%s\nGot:\n%s", input, y1, y2) } } diff --git a/v1/ast/annotations.go b/v1/ast/annotations.go index 5c817fb3e9..def7604edf 100644 --- a/v1/ast/annotations.go +++ b/v1/ast/annotations.go @@ -330,8 +330,7 @@ func scopeCompare(s1, s2 string) int { } func scopeOrder(s string) int { - switch s { - case annotationScopeRule: + if s == annotationScopeRule { return 1 } return 0 diff --git a/v1/ast/builtins.go b/v1/ast/builtins.go index 876296dd07..32ab2d153f 100644 --- a/v1/ast/builtins.go +++ b/v1/ast/builtins.go @@ -3401,7 +3401,7 @@ func (b *Builtin) IsTargetPos(i int) bool { func init() { BuiltinMap = map[string]*Builtin{} - for _, b := range DefaultBuiltins { + for _, b := range &DefaultBuiltins { RegisterBuiltin(b) } } diff --git a/v1/ast/check.go b/v1/ast/check.go index 6f00620349..ecfb320649 100644 --- a/v1/ast/check.go +++ b/v1/ast/check.go @@ -306,10 +306,8 @@ func (tc *typeChecker) checkRule(env *TypeEnv, as *AnnotationSet, rule *Rule) { tc.err([]*Error{NewError(TypeErr, rule.Head.Location, err.Error())}) //nolint:govet tpe = nil } - } else { - if typeV != nil { - tpe = typeV - } + } else if typeV != nil { + tpe = typeV } case MultiValue: typeK := cpy.GetByValue(rule.Head.Key.Value) @@ -732,8 +730,8 @@ func (rc *refChecker) Visit(x interface{}) bool { } func (rc *refChecker) checkApply(curr *TypeEnv, ref Ref) *Error { - switch tpe := curr.GetByRef(ref).(type) { - case *types.Function: // NOTE(sr): We don't support first-class functions, except for `with`. + if tpe, ok := curr.GetByRef(ref).(*types.Function); ok { + // NOTE(sr): We don't support first-class functions, except for `with`. return newRefErrUnsupported(ref[0].Location, rc.varRewriter(ref), len(ref)-1, tpe) } @@ -1003,7 +1001,7 @@ type ArgErrDetail struct { func (d *ArgErrDetail) Lines() []string { lines := make([]string, 2) lines[0] = "have: " + formatArgs(d.Have) - lines[1] = "want: " + fmt.Sprint(d.Want) + lines[1] = "want: " + d.Want.String() return lines } diff --git a/v1/ast/check_test.go b/v1/ast/check_test.go index b3c8e4b7b3..9fb9c5d3b9 100644 --- a/v1/ast/check_test.go +++ b/v1/ast/check_test.go @@ -1529,9 +1529,7 @@ func TestCheckErrorOrdering(t *testing.T) { inputReversed[i] = mod.Rules[i] } - tmp := inputReversed[1] - inputReversed[1] = inputReversed[2] - inputReversed[2] = tmp + inputReversed[1], inputReversed[2] = inputReversed[2], inputReversed[1] _, errs1 := newTypeChecker().CheckTypes(nil, input, nil) _, errs2 := newTypeChecker().CheckTypes(nil, inputReversed, nil) diff --git a/v1/ast/compare.go b/v1/ast/compare.go index 6a2524815d..452c6365a3 100644 --- a/v1/ast/compare.go +++ b/v1/ast/compare.go @@ -236,7 +236,7 @@ func Compare(a, b interface{}) int { type termSlice []*Term func (s termSlice) Less(i, j int) bool { return Compare(s[i].Value, s[j].Value) < 0 } -func (s termSlice) Swap(i, j int) { x := s[i]; s[i] = s[j]; s[j] = x } +func (s termSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s termSlice) Len() int { return len(s) } func sortOrder(x interface{}) int { diff --git a/v1/ast/compile.go b/v1/ast/compile.go index d0b3764125..2092708af6 100644 --- a/v1/ast/compile.go +++ b/v1/ast/compile.go @@ -3545,10 +3545,8 @@ func (n *TreeNode) add(path Ref, rule *Rule) { } node.Children[sub.Key] = sub node.Sorted = append(node.Sorted, sub.Key) - } else { - if rule != nil { - node.Values = append(node.Values, rule) - } + } else if rule != nil { + node.Values = append(node.Values, rule) } } diff --git a/v1/ast/compile_test.go b/v1/ast/compile_test.go index b045872568..f380e04b77 100644 --- a/v1/ast/compile_test.go +++ b/v1/ast/compile_test.go @@ -10164,10 +10164,8 @@ func runStrictnessQueryTestCase(t *testing.T, cases []strictnessQueryTestCase) { if !strings.Contains(err.Error(), tc.expectedErrors.Error()) { t.Fatalf("Expected error %v but got: %v", tc.expectedErrors, err) } - } else { - if err != nil { - t.Fatalf("Unexpected error from %v: %v", tc.query, err) - } + } else if err != nil { + t.Fatalf("Unexpected error from %v: %v", tc.query, err) } } } @@ -11493,10 +11491,8 @@ func TestCompile_DefaultRegoVersion(t *testing.T) { if len(tc.expErrs) > 0 { assertErrors(t, compiler.Errors, tc.expErrs, false) - } else { - if len(compiler.Errors) > 0 { - t.Fatalf("Unexpected errors: %v", compiler.Errors) - } + } else if len(compiler.Errors) > 0 { + t.Fatalf("Unexpected errors: %v", compiler.Errors) } }) } diff --git a/v1/ast/compilehelper_test.go b/v1/ast/compilehelper_test.go index 28a024efd0..0e50f8912e 100644 --- a/v1/ast/compilehelper_test.go +++ b/v1/ast/compilehelper_test.go @@ -113,10 +113,8 @@ func TestCompileModules_DefaultRegoVersion(t *testing.T) { t.Fatalf("Expected error to contain:\n\n%s\n\nbut got:\n\n%s", expErr, err) } } - } else { - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error: %v", err) } }) } @@ -226,10 +224,8 @@ func TestCompileModulesWithOpt_DefaultRegoVersion(t *testing.T) { t.Fatalf("Expected error to contain:\n\n%s\n\nbut got:\n\n%s", expErr, err) } } - } else { - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error: %v", err) } }) } diff --git a/v1/ast/internal/scanner/scanner.go b/v1/ast/internal/scanner/scanner.go index d3c7a1e5e2..d70253bc5c 100644 --- a/v1/ast/internal/scanner/scanner.go +++ b/v1/ast/internal/scanner/scanner.go @@ -101,8 +101,8 @@ func (s *Scanner) Keyword(lit string) tokens.Token { func (s *Scanner) AddKeyword(kw string, tok tokens.Token) { s.keywords[kw] = tok - switch tok { - case tokens.Every: // importing 'every' means also importing 'in' + if tok == tokens.Every { + // importing 'every' means also importing 'in' s.keywords["in"] = tokens.In } } @@ -398,7 +398,7 @@ func (s *Scanner) scanComment() string { end := s.offset - 1 // Trim carriage returns that precede the newline if s.offset > 1 && s.bs[s.offset-2] == '\r' { - end = end - 1 + end -= 1 } return util.ByteSliceToString(s.bs[start:end]) diff --git a/v1/ast/parser.go b/v1/ast/parser.go index d0597ccf45..c048fc65d9 100644 --- a/v1/ast/parser.go +++ b/v1/ast/parser.go @@ -134,7 +134,7 @@ func (c parsedTermCache) String() string { s.WriteRune('{') var e *parsedTermCacheItem for e = c.m; e != nil; e = e.next { - s.WriteString(fmt.Sprintf("%v", e)) + s.WriteString(e.String()) } s.WriteRune('}') return s.String() @@ -2063,7 +2063,7 @@ func (p *Parser) parseTermPairList(end tokens.Token, r [][2]*Term) [][2]*Term { func (p *Parser) parseTermOp(values ...tokens.Token) *Term { for i := range values { if p.s.tok == values[i] { - r := RefTerm(VarTerm(fmt.Sprint(p.s.tok)).SetLocation(p.s.Loc())).SetLocation(p.s.Loc()) + r := RefTerm(VarTerm(p.s.tok.String()).SetLocation(p.s.Loc())).SetLocation(p.s.Loc()) p.scan() return r } @@ -2612,7 +2612,7 @@ func parseAuthorString(s string) (*AuthorAnnotation, error) { strings.HasSuffix(trailing, emailSuffix) { email = trailing[len(emailPrefix):] email = email[0 : len(email)-len(emailSuffix)] - namePartCount = namePartCount - 1 + namePartCount -= 1 } name := strings.Join(parts[0:namePartCount], " ") diff --git a/v1/ast/schema_test.go b/v1/ast/schema_test.go index a937b66b99..2f0364c20a 100644 --- a/v1/ast/schema_test.go +++ b/v1/ast/schema_test.go @@ -140,7 +140,7 @@ func TestSetTypesWithPodSchema(t *testing.T) { } func TestAllOfSchemas(t *testing.T) { - //Test 1: object schema + // Test 1: object schema objectSchemaStaticProps := []*types.StaticProperty{} objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "AddressLine1", Value: types.S}) objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "AddressLine2", Value: types.S}) @@ -151,10 +151,10 @@ func TestAllOfSchemas(t *testing.T) { objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "PostCode", Value: types.S}) objectSchemaExpectedType := types.NewObject(objectSchemaStaticProps, nil) - //Test 2: array schema + // Test 2: array schema arrayExpectedType := types.NewArray(nil, types.N) - //Test 3: parent variation + // Test 3: parent variation parentVariationStaticProps := []*types.StaticProperty{} parentVariationStaticProps = append(parentVariationStaticProps, &types.StaticProperty{Key: "State", Value: types.S}) parentVariationStaticProps = append(parentVariationStaticProps, &types.StaticProperty{Key: "ZipCode", Value: types.S}) @@ -162,13 +162,13 @@ func TestAllOfSchemas(t *testing.T) { parentVariationStaticProps = append(parentVariationStaticProps, &types.StaticProperty{Key: "PostCode", Value: types.S}) parentVariationExpectedType := types.NewObject(parentVariationStaticProps, nil) - //Test 4: empty schema with allOf + // Test 4: empty schema with allOf emptyExpectedType := types.A - //Tests 5 & 6: schema with array of arrays, object and array as siblings + // Tests 5 & 6: schema with array of arrays, object and array as siblings expectedError := errors.New("unable to merge these schemas") - //Test 7: array of objects + // Test 7: array of objects arrayOfObjectsStaticProps := []*types.StaticProperty{} arrayOfObjectsStaticProps = append(arrayOfObjectsStaticProps, &types.StaticProperty{Key: "State", Value: types.S}) arrayOfObjectsStaticProps = append(arrayOfObjectsStaticProps, &types.StaticProperty{Key: "ZipCode", Value: types.S}) @@ -179,7 +179,7 @@ func TestAllOfSchemas(t *testing.T) { innerType := types.NewObject(arrayOfObjectsStaticProps, nil) arrayOfObjectsExpectedType := types.NewArray(nil, innerType) - //Tests 8 & 9: allOf schema with type not specified + // Tests 8 & 9: allOf schema with type not specified objectMissingStaticProps := []*types.StaticProperty{} objectMissingStaticProps = append(objectMissingStaticProps, &types.StaticProperty{Key: "AddressLine", Value: types.S}) objectMissingStaticProps = append(objectMissingStaticProps, &types.StaticProperty{Key: "State", Value: types.S}) @@ -189,10 +189,10 @@ func TestAllOfSchemas(t *testing.T) { objectMissingExpectedType := types.NewObject(objectMissingStaticProps, nil) arrayMissingExpectedType := types.NewArray([]types.Type{types.N, types.N}, nil) - //Tests 10 & 11: allOf schema with array that contains different types (with and without error) + // Tests 10 & 11: allOf schema with array that contains different types (with and without error) arrayDifTypesExpectedType := types.NewArray([]types.Type{types.S, types.N}, nil) - //Test 12: array inside of object + // Test 12: array inside of object arrayInObjectstaticProps := []*types.StaticProperty{} arrayInObjectstaticProps = append(arrayInObjectstaticProps, &types.StaticProperty{Key: "age", Value: types.N}) arrayInObjectstaticProps = append(arrayInObjectstaticProps, &types.StaticProperty{Key: "name", Value: types.S}) @@ -203,7 +203,7 @@ func TestAllOfSchemas(t *testing.T) { arrayInObjectExpectedType := types.NewObject([]*types.StaticProperty{ types.NewStaticProperty("familyMembers", arrayInObjectInnerType)}, nil) - //Test 13: allOf inside core schema + // Test 13: allOf inside core schema coreStaticProps := []*types.StaticProperty{} coreStaticProps = append(coreStaticProps, &types.StaticProperty{Key: "accessMe", Value: types.S}) coreStaticProps = append(coreStaticProps, &types.StaticProperty{Key: "accessYou", Value: types.S}) @@ -213,12 +213,12 @@ func TestAllOfSchemas(t *testing.T) { outerType = append(outerType, &types.StaticProperty{Key: "AddressLine", Value: types.S}) coreSchemaExpectedType := types.NewObject(outerType, nil) - //Tests 14-17: other types besides array and object + // Tests 14-17: other types besides array and object expectedStringType := types.NewString() expectedIntegerType := types.NewNumber() expectedBooleanType := types.NewBoolean() - //Test 18: array with uneven numbers of items children to merge + // Test 18: array with uneven numbers of items children to merge expectedUnevenArrayType := types.NewArray([]types.Type{types.N, types.N, types.S}, nil) tests := []struct { @@ -357,7 +357,7 @@ func TestAllOfSchemas(t *testing.T) { } func TestParseSchemaUntypedField(t *testing.T) { - //Expected type is: object + // Expected type is: object staticProps := []*types.StaticProperty{} staticProps = append(staticProps, &types.StaticProperty{Key: "foo", Value: types.A}) expectedType := types.NewObject(staticProps, nil) @@ -365,13 +365,13 @@ func TestParseSchemaUntypedField(t *testing.T) { } func TestParseSchemaNoChildren(t *testing.T) { - //Expected type is: object[any: any] + // Expected type is: object[any: any] expectedType := types.NewObject(nil, &types.DynamicProperty{Key: types.A, Value: types.A}) testParseSchema(t, noChildrenObjectSchema, expectedType, nil) } func TestParseSchemaArrayNoItems(t *testing.T) { - //Expected type is: object + // Expected type is: object staticProps := []*types.StaticProperty{} staticProps = append(staticProps, &types.StaticProperty{Key: "b", Value: types.NewArray(nil, types.A)}) expectedType := types.NewObject(staticProps, nil) @@ -379,7 +379,7 @@ func TestParseSchemaArrayNoItems(t *testing.T) { } func TestParseSchemaBooleanField(t *testing.T) { - //Expected type is: object + // Expected type is: object staticProps := []*types.StaticProperty{} staticProps = append(staticProps, &types.StaticProperty{Key: "a", Value: types.B}) expectedType := types.NewObject(staticProps, nil) diff --git a/v1/ast/term.go b/v1/ast/term.go index b9d652f4f1..866fc4ddb6 100644 --- a/v1/ast/term.go +++ b/v1/ast/term.go @@ -1391,14 +1391,14 @@ func (arr *Array) String() string { defer sbPool.Put(sb) - sb.WriteRune('[') + sb.WriteByte('[') for i, e := range arr.elems { if i > 0 { sb.WriteString(", ") } sb.WriteString(e.String()) } - sb.WriteRune(']') + sb.WriteByte(']') return sb.String() } @@ -1589,14 +1589,14 @@ func (s *set) String() string { defer sbPool.Put(sb) - sb.WriteRune('{') + sb.WriteByte('{') for i := range s.sortedKeys() { if i > 0 { sb.WriteString(", ") } sb.WriteString(s.keys[i].Value.String()) } - sb.WriteRune('}') + sb.WriteByte('}') return sb.String() } @@ -2217,7 +2217,7 @@ type objectElem struct { type objectElemSlice []*objectElem func (s objectElemSlice) Less(i, j int) bool { return Compare(s[i].key.Value, s[j].key.Value) < 0 } -func (s objectElemSlice) Swap(i, j int) { x := s[i]; s[i] = s[j]; s[j] = x } +func (s objectElemSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s objectElemSlice) Len() int { return len(s) } // Item is a helper for constructing an tuple containing two Terms @@ -2502,7 +2502,7 @@ func (obj *object) String() string { defer sbPool.Put(sb) - sb.WriteRune('{') + sb.WriteByte('{') for i, elem := range obj.sortedKeys() { if i > 0 { @@ -2512,7 +2512,7 @@ func (obj *object) String() string { sb.WriteString(": ") sb.WriteString(elem.value.String()) } - sb.WriteRune('}') + sb.WriteByte('}') return sb.String() } diff --git a/v1/ast/term_bench_test.go b/v1/ast/term_bench_test.go index a5fa440c1b..8ea7112cde 100644 --- a/v1/ast/term_bench_test.go +++ b/v1/ast/term_bench_test.go @@ -324,8 +324,8 @@ func BenchmarkObjectConstruction(b *testing.B) { for i := range n { es = append(es, struct{ k, v int }{i, i}) } - rand.New(rand.NewSource(seed)) // Seed the PRNG. - rand.Shuffle(len(es), func(i, j int) { es[i], es[j] = es[j], es[i] }) + r := rand.New(rand.NewSource(seed)) // Seed the PRNG. + r.Shuffle(len(es), func(i, j int) { es[i], es[j] = es[j], es[i] }) b.ResetTimer() for range b.N { obj := NewObject() diff --git a/v1/ast/term_test.go b/v1/ast/term_test.go index fdaf66c7f1..5aa99752b2 100644 --- a/v1/ast/term_test.go +++ b/v1/ast/term_test.go @@ -867,7 +867,6 @@ func TestSetConcurrentReads(t *testing.T) { numbers[i] = IntNumberTerm(i) } // Shuffle numbers array for random insertion order. - rand.New(rand.NewSource(10000)) // Seed the PRNG. rand.Shuffle(len(numbers), func(i, j int) { numbers[i], numbers[j] = numbers[j], numbers[i] }) @@ -909,8 +908,8 @@ func TestObjectConcurrentReads(t *testing.T) { numbers[i] = IntNumberTerm(i) } // Shuffle numbers array for random insertion order. - rand.New(rand.NewSource(10000)) // Seed the PRNG. - rand.Shuffle(len(numbers), func(i, j int) { + r := rand.New(rand.NewSource(10000)) // Seed the PRNG. + r.Shuffle(len(numbers), func(i, j int) { numbers[i], numbers[j] = numbers[j], numbers[i] }) // Build an object with numbers in unsorted order. diff --git a/v1/bundle/bundle_test.go b/v1/bundle/bundle_test.go index d02ff771e6..74e7416c6b 100644 --- a/v1/bundle/bundle_test.go +++ b/v1/bundle/bundle_test.go @@ -599,10 +599,8 @@ func TestReadWithSignatures(t *testing.T) { if tc.err != nil && tc.err.Error() != err.Error() { t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error()) } - } else { - if err != nil { - t.Fatalf("Unexpected error %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error %v", err) } }) } diff --git a/v1/bundle/keys_test.go b/v1/bundle/keys_test.go index 713910ff67..2d108423d2 100644 --- a/v1/bundle/keys_test.go +++ b/v1/bundle/keys_test.go @@ -52,10 +52,8 @@ func TestValidateAndInjectDefaultsVerificationConfig(t *testing.T) { if tc.err != nil && tc.err.Error() != err.Error() { t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error()) } - } else { - if err != nil { - t.Fatalf("Unexpected error %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error %v", err) } if !reflect.DeepEqual(tc.vc.PublicKeys, tc.publicKeys) { @@ -99,10 +97,8 @@ func TestGetPublicKey(t *testing.T) { if tc.err != nil && tc.err.Error() != err.Error() { t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error()) } - } else { - if err != nil { - t.Fatalf("Unexpected error %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error %v", err) } if !reflect.DeepEqual(kc, tc.kc) { @@ -328,7 +324,7 @@ func TestGetClaimsErrors(t *testing.T) { } test.WithTempFS(files, func(rootDir string) { - //json unmarshal error + // json unmarshal error sc := NewSigningConfig("secret", "HS256", filepath.Join(rootDir, "claims.json")) _, err := sc.GetClaims() if err == nil { diff --git a/v1/bundle/sign.go b/v1/bundle/sign.go index cf9a3e183a..710e296860 100644 --- a/v1/bundle/sign.go +++ b/v1/bundle/sign.go @@ -101,11 +101,9 @@ func generatePayload(files []FileInfo, sc *SigningConfig, keyID string) ([]byte, for claim, value := range claims { payload[claim] = value } - } else { - if keyID != "" { - // keyid claim is deprecated but include it for backwards compatibility. - payload["keyid"] = keyID - } + } else if keyID != "" { + // keyid claim is deprecated but include it for backwards compatibility. + payload["keyid"] = keyID } return json.Marshal(payload) } diff --git a/v1/bundle/store_test.go b/v1/bundle/store_test.go index 0ef48ef1be..d218b56f0a 100644 --- a/v1/bundle/store_test.go +++ b/v1/bundle/store_test.go @@ -6621,10 +6621,8 @@ func TestDoDFS(t *testing.T) { if tc.err != nil && tc.err.Error() != err.Error() { t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error()) } - } else { - if err != nil { - t.Fatalf("Unexpected error %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error %v", err) } }) } diff --git a/v1/bundle/verify_test.go b/v1/bundle/verify_test.go index 3d5de0a6de..c73b293d99 100644 --- a/v1/bundle/verify_test.go +++ b/v1/bundle/verify_test.go @@ -63,10 +63,8 @@ func TestVerifyBundleSignature(t *testing.T) { if tc.err != nil && tc.err.Error() != err.Error() { t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error()) } - } else { - if err != nil { - t.Fatalf("Unexpected error %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error %v", err) } }) } @@ -210,10 +208,8 @@ yQjtQ8mbDOsiLLvh7wIDAQAB== if tc.err != nil && tc.err.Error() != err.Error() { t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error()) } - } else { - if err != nil { - t.Fatalf("Unexpected error %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error %v", err) } }) } @@ -277,10 +273,8 @@ func TestVerifyBundleFile(t *testing.T) { if tc.err != nil && tc.err.Error() != err.Error() { t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error()) } - } else { - if err != nil { - t.Fatalf("Unexpected error %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error %v", err) } }) } diff --git a/v1/compile/compile_bench_test.go b/v1/compile/compile_bench_test.go index b6b84137ef..0a01b6ebbc 100644 --- a/v1/compile/compile_bench_test.go +++ b/v1/compile/compile_bench_test.go @@ -40,7 +40,7 @@ func BenchmarkCompileDynamicPolicy(b *testing.B) { } } -func generateDynamicPolicyBenchmarkData(N int) map[string]string { +func generateDynamicPolicyBenchmarkData(n int) map[string]string { files := map[string]string{ "main.rego": ` package main @@ -56,19 +56,19 @@ func generateDynamicPolicyBenchmarkData(N int) map[string]string { }`, } - for i := range N { + for i := range n { files[fmt.Sprintf("policy%d.rego", i)] = generateDynamicMockPolicy(i) } return files } -func generateDynamicMockPolicy(N int) string { +func generateDynamicMockPolicy(n int) string { return fmt.Sprintf(`package policies["%d"]["%d"].policy%d denies contains x if { input.attribute == "%d" x := "policy%d" -}`, N, N, N, N, N) +}`, n, n, n, n, n) } func BenchmarkLargePartialRulePolicy(b *testing.B) { @@ -95,13 +95,13 @@ func BenchmarkLargePartialRulePolicy(b *testing.B) { } } -func generateLargePartialRuleBenchmarkData(N int) map[string]string { +func generateLargePartialRuleBenchmarkData(n int) map[string]string { var policy strings.Builder - policy.Grow((140 * N) + 100) // Each rule takes around 130 characters. + policy.Grow((140 * n) + 100) // Each rule takes around 130 characters. policy.WriteString(`package example.large.partial.rules.policy["dynamic_part"].main`) policy.WriteString("\n\n") - for i := range N { + for i := range n { policy.WriteString(generateLargePartialRuleMockRule(i)) policy.WriteString("\n\n") } @@ -115,11 +115,11 @@ func generateLargePartialRuleBenchmarkData(N int) map[string]string { return files } -func generateLargePartialRuleMockRule(N int) string { +func generateLargePartialRuleMockRule(n int) string { return fmt.Sprintf(`deny contains [resource, errormsg] if { resource := "example.%d" i := %d i %% 2 != 0 errormsg := "denied because %d is an odd number." -}`, N, N, N) +}`, n, n, n) } diff --git a/v1/compile/compile_test.go b/v1/compile/compile_test.go index 547bd14fea..f641df05be 100644 --- a/v1/compile/compile_test.go +++ b/v1/compile/compile_test.go @@ -481,10 +481,8 @@ p contains "B" if { t.Fatalf("expected error to contain:\n\n%s\n\ngot:\n\n%v", expErr, err) } } - } else { - if err != nil { - t.Fatal(err) - } + } else if err != nil { + t.Fatal(err) } }) }) @@ -1246,10 +1244,8 @@ func TestCompilerOptimizationL2(t *testing.T) { if !compiler.bundle.Modules[1].Parsed.Equal(prunedExp) { t.Fatalf("expected pruned module to be:\n\n%v\n\ngot:\n\n%v", prunedExp, compiler.bundle.Modules[1]) } - } else { - if !compiler.bundle.Modules[1].Parsed.Equal(optimizedExp) { - t.Fatalf("expected optimized module to be:\n\n%v\n\ngot:\n\n%v", optimizedExp, compiler.bundle.Modules[1]) - } + } else if !compiler.bundle.Modules[1].Parsed.Equal(optimizedExp) { + t.Fatalf("expected optimized module to be:\n\n%v\n\ngot:\n\n%v", optimizedExp, compiler.bundle.Modules[1]) } }) } diff --git a/v1/config/config.go b/v1/config/config.go index 36538655c9..490f90b905 100644 --- a/v1/config/config.go +++ b/v1/config/config.go @@ -99,7 +99,7 @@ func (c Config) PluginNames() (result []string) { // PluginsEnabled returns true if one or more plugin features are enabled. // -// Deprecated. Use PluginNames instead. +// Deprecated: Use PluginNames instead. func (c Config) PluginsEnabled() bool { return c.Bundle != nil || c.Bundles != nil || c.DecisionLogs != nil || c.Status != nil || len(c.Plugins) > 0 } diff --git a/v1/cover/cover.go b/v1/cover/cover.go index ea79fc9ef4..c99d8f5051 100644 --- a/v1/cover/cover.go +++ b/v1/cover/cover.go @@ -299,12 +299,7 @@ func hasFileLocation(loc *ast.Location) bool { // Check the expression and return true if it should be included in the coverage report func includeExprInCoverage(x *ast.Expr) bool { - includeExprType := true + _, excludeExprType := x.Terms.(*ast.SomeDecl) - switch x.Terms.(type) { - case *ast.SomeDecl: - includeExprType = false - } - - return includeExprType && hasFileLocation(x.Location) + return !excludeExprType && hasFileLocation(x.Location) } diff --git a/v1/debug/debugger.go b/v1/debug/debugger.go index c19ea84f58..93caf4f8b5 100644 --- a/v1/debug/debugger.go +++ b/v1/debug/debugger.go @@ -850,7 +850,7 @@ func (s *session) AddBreakpoint(loc location.Location) (Breakpoint, error) { return s.breakpoints.add(loc), nil } -func (s *session) RemoveBreakpoint(ID BreakpointID) (Breakpoint, error) { +func (s *session) RemoveBreakpoint(id BreakpointID) (Breakpoint, error) { if s == nil { return nil, errors.New("no active debug session") } @@ -858,9 +858,9 @@ func (s *session) RemoveBreakpoint(ID BreakpointID) (Breakpoint, error) { s.mtx.Lock() defer s.mtx.Unlock() - bp := s.breakpoints.remove(ID) + bp := s.breakpoints.remove(id) if bp == nil { - return nil, fmt.Errorf("breakpoint %d not found", ID) + return nil, fmt.Errorf("breakpoint %d not found", id) } return bp, nil diff --git a/v1/debug/debugger_test.go b/v1/debug/debugger_test.go index db765f8755..1498570a4c 100644 --- a/v1/debug/debugger_test.go +++ b/v1/debug/debugger_test.go @@ -2096,10 +2096,8 @@ func assertVariables(t *testing.T, s Session, variables []Variable, exp map[stri t.Fatalf("Unexpected error: %v", err) } assertVariables(t, s, vars, expVar.children) - } else { - if v.VariablesReference() != 0 { - t.Errorf("Expected zero variables reference") - } + } else if v.VariablesReference() != 0 { + t.Errorf("Expected zero variables reference") } } } diff --git a/v1/download/download.go b/v1/download/download.go index 0596cb64c0..b318aa5ce2 100644 --- a/v1/download/download.go +++ b/v1/download/download.go @@ -232,16 +232,14 @@ func (d *Downloader) loop(ctx context.Context) { if err != nil { delay = util.DefaultBackoff(float64(minRetryDelay), float64(*d.config.Polling.MaxDelaySeconds), retry) - } else { - if !d.longPollingEnabled || d.config.Polling.LongPollingTimeoutSeconds == nil { - // revert the response header timeout value on the http client's transport - if *d.client.Config().ResponseHeaderTimeoutSeconds == 0 { - d.client = d.client.SetResponseHeaderTimeout(&d.respHdrTimeoutSec) - } - min := float64(*d.config.Polling.MinDelaySeconds) - max := float64(*d.config.Polling.MaxDelaySeconds) - delay = time.Duration(((max - min) * rand.Float64()) + min) + } else if !d.longPollingEnabled || d.config.Polling.LongPollingTimeoutSeconds == nil { + // revert the response header timeout value on the http client's transport + if *d.client.Config().ResponseHeaderTimeoutSeconds == 0 { + d.client = d.client.SetResponseHeaderTimeout(&d.respHdrTimeoutSec) } + min := float64(*d.config.Polling.MinDelaySeconds) + max := float64(*d.config.Polling.MaxDelaySeconds) + delay = time.Duration(((max - min) * rand.Float64()) + min) } d.logger.Debug("Waiting %v before next download/retry.", delay) diff --git a/v1/format/format.go b/v1/format/format.go index 7e1e365f3d..ed5770d83b 100644 --- a/v1/format/format.go +++ b/v1/format/format.go @@ -63,12 +63,10 @@ func SourceWithOpts(filename string, src []byte, opts Opts) ([]byte, error) { var parserOpts ast.ParserOptions if opts.ParserOptions != nil { parserOpts = *opts.ParserOptions - } else { - if regoVersion == ast.RegoV1 { - // If the rego version is V1, we need to parse it as such, to allow for future keywords not being imported. - // Otherwise, we'll default to the default rego-version. - parserOpts.RegoVersion = ast.RegoV1 - } + } else if regoVersion == ast.RegoV1 { + // If the rego version is V1, we need to parse it as such, to allow for future keywords not being imported. + // Otherwise, we'll default to the default rego-version. + parserOpts.RegoVersion = ast.RegoV1 } if parserOpts.RegoVersion == ast.RegoUndefined { diff --git a/v1/keys/keys_test.go b/v1/keys/keys_test.go index 150b50d708..480ef9d926 100644 --- a/v1/keys/keys_test.go +++ b/v1/keys/keys_test.go @@ -72,10 +72,8 @@ func TestParseKeysConfig(t *testing.T) { if tc.err != nil && tc.err.Error() != err.Error() { t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error()) } - } else { - if err != nil { - t.Fatalf("Unexpected error %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error %v", err) } if !reflect.DeepEqual(kc, tc.result) { diff --git a/v1/loader/loader_test.go b/v1/loader/loader_test.go index c431c858c2..1f5b87ffdc 100644 --- a/v1/loader/loader_test.go +++ b/v1/loader/loader_test.go @@ -504,8 +504,8 @@ func TestLoadDirRecursive(t *testing.T) { } mod1 := ast.MustParseModule(files["/a/e.rego"]) mod2 := ast.MustParseModule(files["/b/d/e.rego"]) - expectedMod1 := loaded.Modules[CleanPath(filepath.Join(rootDir, "/a/e.rego"))].Parsed - expectedMod2 := loaded.Modules[CleanPath(filepath.Join(rootDir, "/b/d/e.rego"))].Parsed + expectedMod1 := loaded.Modules[CleanPath(filepath.Join(rootDir, "a", "e.rego"))].Parsed + expectedMod2 := loaded.Modules[CleanPath(filepath.Join(rootDir, "b", "d", "e.rego"))].Parsed if !mod1.Equal(expectedMod1) { t.Fatalf("Expected:\n%v\n\nGot:\n%v", expectedMod1, mod1) } @@ -807,8 +807,8 @@ func TestAsBundleWithDir(t *testing.T) { } expectedModulePaths := map[string]struct{}{ - filepath.Join(rootDir, "foo/policy.rego"): {}, - filepath.Join(rootDir, "base.rego"): {}, + filepath.Join(rootDir, "foo", "policy.rego"): {}, + filepath.Join(rootDir, "base.rego"): {}, } for _, mf := range b.Modules { if _, found := expectedModulePaths[mf.Path]; !found { @@ -849,7 +849,7 @@ func TestAsBundleWithFileURLDir(t *testing.T) { t.Fatalf("expected 1 modules, got %d", len(b.Modules)) } expectedModulePaths := map[string]struct{}{ - filepath.Join(rootDir, "/foo/policy.rego"): {}, + filepath.Join(rootDir, "foo", "policy.rego"): {}, } for _, mf := range b.Modules { if _, found := expectedModulePaths[mf.Path]; !found { @@ -977,10 +977,8 @@ func TestCheckForUNCPath(t *testing.T) { if tc.err != nil && tc.err.Error() != err.Error() { t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error()) } - } else { - if err != nil { - t.Fatalf("Unexpected error %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error %v", err) } }) } diff --git a/v1/plugins/bundle/config.go b/v1/plugins/bundle/config.go index 32458f9543..ee32ed9781 100644 --- a/v1/plugins/bundle/config.go +++ b/v1/plugins/bundle/config.go @@ -175,10 +175,8 @@ func (c *Config) validateAndInjectDefaults(services []string, keys map[string]*k if err != nil { return fmt.Errorf("invalid configuration for bundle %q: %s", name, err.Error()) } - } else { - if len(keys) > 0 { - source.Signing = bundle.NewVerificationConfig(keys, "", "", nil) - } + } else if len(keys) > 0 { + source.Signing = bundle.NewVerificationConfig(keys, "", "", nil) } if strings.HasPrefix(source.Resource, "file://") { diff --git a/v1/plugins/bundle/plugin.go b/v1/plugins/bundle/plugin.go index 6de987f318..8d5577f2d7 100644 --- a/v1/plugins/bundle/plugin.go +++ b/v1/plugins/bundle/plugin.go @@ -434,17 +434,14 @@ func (p *Plugin) loadAndActivateBundlesFromDisk(ctx context.Context) { func (p *Plugin) newDownloader(name string, source *Source, bundles map[string]*Source) Loader { - if u, err := url.Parse(source.Resource); err == nil { - switch u.Scheme { - case "file": - return &fileLoader{ - name: name, - path: u.Path, - bvc: source.Signing, - sizeLimitBytes: source.SizeLimitBytes, - f: p.oneShot, - bundleParserOpts: p.manager.ParserOptions(), - } + if u, err := url.Parse(source.Resource); err == nil && u.Scheme == "file" { + return &fileLoader{ + name: name, + path: u.Path, + bvc: source.Signing, + sizeLimitBytes: source.SizeLimitBytes, + f: p.oneShot, + bundleParserOpts: p.manager.ParserOptions(), } } diff --git a/v1/plugins/bundle/plugin_test.go b/v1/plugins/bundle/plugin_test.go index a309fa9f01..9711397cb3 100644 --- a/v1/plugins/bundle/plugin_test.go +++ b/v1/plugins/bundle/plugin_test.go @@ -921,10 +921,8 @@ func TestPluginStartLazyLoadInMem(t *testing.T) { if ast.Compare(result, expected) != 0 { t.Fatalf("expected data to be %v but got %v", expected, result) } - } else { - if !reflect.DeepEqual(result, mockBundle1.Data["p"]) { - t.Fatalf("expected data to be %v but got %v", mockBundle1.Data, result) - } + } else if !reflect.DeepEqual(result, mockBundle1.Data["p"]) { + t.Fatalf("expected data to be %v but got %v", mockBundle1.Data, result) } result, err = storage.ReadOne(ctx, manager.Store, storage.Path{"q"}) @@ -937,10 +935,8 @@ func TestPluginStartLazyLoadInMem(t *testing.T) { if ast.Compare(result, expected) != 0 { t.Fatalf("expected data to be %v but got %v", expected, result) } - } else { - if !reflect.DeepEqual(result, mockBundle2.Data["q"]) { - t.Fatalf("expected data to be %v but got %v", mockBundle2.Data, result) - } + } else if !reflect.DeepEqual(result, mockBundle2.Data["q"]) { + t.Fatalf("expected data to be %v but got %v", mockBundle2.Data, result) } txn := storage.NewTransactionOrDie(ctx, manager.Store) @@ -1348,7 +1344,7 @@ func TestStop(t *testing.T) { serviceName := "test-svc" err := manager.Reconfigure(&config.Config{ - Services: []byte(fmt.Sprintf("{\"%s\":{ \"url\": \"%s\"}}", serviceName, ts.URL+tsURLBase)), + Services: []byte(fmt.Sprintf("{%q:{ \"url\": %q}}", serviceName, ts.URL+tsURLBase)), }) if err != nil { t.Fatalf("Error configuring plugin manager: %s", err) @@ -3008,7 +3004,7 @@ p contains x`), txn := storage.NewTransactionOrDie(ctx, manager.Store) - _, err := manager.Store.GetPolicy(ctx, txn, filepath.Join(bundleName, "/example.rego")) + _, err := manager.Store.GetPolicy(ctx, txn, filepath.Join(bundleName, "example.rego")) if err != nil { t.Fatalf("Unexpected error: %v", err) } @@ -3037,7 +3033,7 @@ p contains x`), txn = storage.NewTransactionOrDie(ctx, manager.Store) - _, err = manager.Store.GetPolicy(ctx, txn, filepath.Join(bundleName, "/example.rego")) + _, err = manager.Store.GetPolicy(ctx, txn, filepath.Join(bundleName, "example.rego")) if err != nil { t.Fatalf("Unexpected error: %v", err) } @@ -3149,7 +3145,7 @@ func TestPluginOneShotActivationRemovesOld(t *testing.T) { ids, err := manager.Store.ListPolicies(ctx, txn) if err != nil { return err - } else if !slices.Equal([]string{filepath.Join(bundleName, "/example2.rego")}, ids) { + } else if !slices.Equal([]string{filepath.Join(bundleName, "example2.rego")}, ids) { return errors.New("expected updated policy ids") } data, err := manager.Store.Read(ctx, txn, storage.Path{}) @@ -3813,7 +3809,7 @@ func TestPluginActivateScopedBundle(t *testing.T) { } else { expData = util.MustUnmarshalJSON([]byte(exp)) } - expIDs := []string{filepath.Join(bundleName, "bundle/id1"), "some/id2", "some/id3"} + expIDs := []string{filepath.Join(bundleName, "bundle", "id1"), "some/id2", "some/id3"} validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, bundleName, "quickbrownfaux", nil) // Activate a bundle that is scoped to a/a3 ad a/a6. Include a function @@ -3853,7 +3849,7 @@ func TestPluginActivateScopedBundle(t *testing.T) { } else { expData = util.MustUnmarshalJSON([]byte(exp)) } - expIDs = []string{filepath.Join(bundleName, "bundle/id2"), "some/id3"} + expIDs = []string{filepath.Join(bundleName, "bundle", "id2"), "some/id3"} validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, bundleName, "quickbrownfaux-2", map[string]interface{}{ "a": map[string]interface{}{"a1": "deadbeef"}, @@ -3877,7 +3873,7 @@ func TestPluginActivateScopedBundle(t *testing.T) { // Ensure bundle activation failed by checking that previous revision is // still active. - expIDs = []string{filepath.Join(bundleName, "bundle/id2"), "not_scoped", "some/id3"} + expIDs = []string{filepath.Join(bundleName, "bundle", "id2"), "not_scoped", "some/id3"} validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, bundleName, "quickbrownfaux-2", map[string]interface{}{ "a": map[string]interface{}{"a1": "deadbeef"}, @@ -3943,7 +3939,7 @@ func TestPluginSetCompilerOnContext(t *testing.T) { t.Fatalf("Expected 2 events but got: %+v", events) } else if compiler := plugins.GetCompilerOnContext(events[1].Context); compiler == nil { t.Fatalf("Expected compiler on 2nd event but got: %+v", events) - } else if !compiler.Modules[filepath.Join(bundleName, "/test.rego")].Equal(exp) { + } else if !compiler.Modules[filepath.Join(bundleName, "test.rego")].Equal(exp) { t.Fatalf("Expected module on compiler but got: %v", compiler.Modules) } } @@ -5420,10 +5416,8 @@ p contains 7 if { t.Fatalf("expected error:\n\n%s\n\nbut got:\n\n%v", expErr, s.Errors) } } - } else { - if s.LastSuccessfulActivation.IsZero() { - t.Fatal("expected successful activation") - } + } else if s.LastSuccessfulActivation.IsZero() { + t.Fatal("expected successful activation") } }) }) @@ -5737,10 +5731,8 @@ p contains 7 if { t.Fatalf("expected error:\n\n%s\n\nbut got:\n\n%v", expErr, s.Errors) } } - } else { - if s.LastSuccessfulActivation.IsZero() { - t.Fatal("expected successful activation") - } + } else if s.LastSuccessfulActivation.IsZero() { + t.Fatal("expected successful activation") } }) }) @@ -5942,10 +5934,8 @@ p contains 7 if { t.Fatalf("expected error:\n\n%s\n\nbut got:\n\n%v", expErr, s.Errors) } } - } else { - if s.LastSuccessfulActivation.IsZero() { - t.Fatal("expected successful activation") - } + } else if s.LastSuccessfulActivation.IsZero() { + t.Fatal("expected successful activation") } }) }) @@ -6236,10 +6226,8 @@ p contains 7 if { t.Fatalf("expected error:\n\n%s\n\nbut got:\n\n%v", expErr, s.Errors) } } - } else { - if s.LastSuccessfulActivation.IsZero() { - t.Fatal("expected successful activation") - } + } else if s.LastSuccessfulActivation.IsZero() { + t.Fatal("expected successful activation") } }) }) diff --git a/v1/plugins/discovery/config.go b/v1/plugins/discovery/config.go index db17d5b8d1..dac9060da7 100644 --- a/v1/plugins/discovery/config.go +++ b/v1/plugins/discovery/config.go @@ -101,10 +101,8 @@ func (c *Config) validateAndInjectDefaults(services []string, confKeys map[strin if err != nil { return fmt.Errorf("invalid configuration for discovery service: %s", err.Error()) } - } else { - if len(confKeys) > 0 { - c.Signing = bundle.NewVerificationConfig(cpy, "", "", nil) - } + } else if len(confKeys) > 0 { + c.Signing = bundle.NewVerificationConfig(cpy, "", "", nil) } if c.Resource != nil { @@ -126,9 +124,9 @@ func (c *Config) validateAndInjectDefaults(services []string, confKeys map[strin c.service = service if c.Decision != nil { - c.query = fmt.Sprintf("%v.%v", ast.DefaultRootDocument, strings.Replace(strings.Trim(*c.Decision, "/"), "/", ".", -1)) + c.query = fmt.Sprintf("%v.%v", ast.DefaultRootDocument, strings.ReplaceAll(strings.Trim(*c.Decision, "/"), "/", ".")) } else if c.Name != nil { - c.query = fmt.Sprintf("%v.%v", ast.DefaultRootDocument, strings.Replace(strings.Trim(*c.Name, "/"), "/", ".", -1)) + c.query = fmt.Sprintf("%v.%v", ast.DefaultRootDocument, strings.ReplaceAll(strings.Trim(*c.Name, "/"), "/", ".")) } else { c.query = ast.DefaultRootDocument.String() } diff --git a/v1/plugins/discovery/discovery_test.go b/v1/plugins/discovery/discovery_test.go index a7813cbcb1..fcf8bda7e9 100644 --- a/v1/plugins/discovery/discovery_test.go +++ b/v1/plugins/discovery/discovery_test.go @@ -30,7 +30,6 @@ import ( "github.com/open-policy-agent/opa/v1/logging/test" "github.com/open-policy-agent/opa/v1/metrics" "github.com/open-policy-agent/opa/v1/plugins" - "github.com/open-policy-agent/opa/v1/plugins/bundle" bundlePlugin "github.com/open-policy-agent/opa/v1/plugins/bundle" "github.com/open-policy-agent/opa/v1/plugins/logs" "github.com/open-policy-agent/opa/v1/plugins/status" @@ -3339,10 +3338,8 @@ bundles: if tc.err != nil && tc.err.Error() != err.Error() { t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error()) } - } else { - if err != nil { - t.Fatalf("Unexpected error %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error %v", err) } }) } @@ -3406,10 +3403,8 @@ decision_logs: if tc.err != nil && tc.err.Error() != err.Error() { t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error()) } - } else { - if err != nil { - t.Fatalf("Unexpected error %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error %v", err) } }) } @@ -3479,10 +3474,8 @@ status: if tc.err != nil && tc.err.Error() != err.Error() { t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error()) } - } else { - if err != nil { - t.Fatalf("Unexpected error %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error %v", err) } }) } @@ -3832,8 +3825,8 @@ func TestListeners(t *testing.T) { ensurePluginState(t, disco, plugins.StateNotReady) - var status *bundle.Status - disco.RegisterListener("testlistener", func(s bundle.Status) { + var status *bundlePlugin.Status + disco.RegisterListener("testlistener", func(s bundlePlugin.Status) { status = &s }) @@ -3954,7 +3947,7 @@ func (t *testFixture) runQuery(ctx context.Context, query string, m metrics.Metr rego.Metrics(m), ) - //Run evaluation. + // Run evaluation. rs, err := r.Eval(ctx) if err != nil { return nil, err diff --git a/v1/plugins/logs/encoder.go b/v1/plugins/logs/encoder.go index 4a24b35401..b46a1561f9 100644 --- a/v1/plugins/logs/encoder.go +++ b/v1/plugins/logs/encoder.go @@ -183,8 +183,8 @@ func (enc *chunkEncoder) reset() ([][]byte, error) { enc.initialize() var result [][]byte - for _, event := range events { - chunk, err := enc.Write(event) + for i := range events { + chunk, err := enc.Write(events[i]) if err != nil { return nil, err } diff --git a/v1/plugins/logs/plugin.go b/v1/plugins/logs/plugin.go index e33f3e1175..c25dff29d7 100644 --- a/v1/plugins/logs/plugin.go +++ b/v1/plugins/logs/plugin.go @@ -893,8 +893,8 @@ func (p *Plugin) oneShot(ctx context.Context) (ok bool, err error) { continue } - for _, event := range events { - p.encodeAndBufferEvent(event) + for i := range events { + p.encodeAndBufferEvent(events[i]) } } else { // requeue the chunk diff --git a/v1/plugins/plugins.go b/v1/plugins/plugins.go index 4f2d75511c..8313e2523c 100644 --- a/v1/plugins/plugins.go +++ b/v1/plugins/plugins.go @@ -803,7 +803,7 @@ func (m *Manager) Reconfigure(config *config.Config) error { m.Config = config m.interQueryBuiltinCacheConfig = interQueryBuiltinCacheConfig - for name, client := range services { + for name, client := range services { //nolint:gocritic m.services[name] = client } diff --git a/v1/plugins/rest/auth.go b/v1/plugins/rest/auth.go index 7a896761be..abd391f015 100644 --- a/v1/plugins/rest/auth.go +++ b/v1/plugins/rest/auth.go @@ -206,7 +206,7 @@ func convertSignatureToBase64(alg string, der []byte) (string, error) { return signatureData, nil } -func pointsFromDER(der []byte) (R, S *big.Int, err error) { +func pointsFromDER(der []byte) (R, S *big.Int, err error) { //nolint:gocritic R, S = &big.Int{}, &big.Int{} data := asn1.RawValue{} if _, err := asn1.Unmarshal(der, &data); err != nil { @@ -394,12 +394,7 @@ func (ap *oauth2ClientCredentialsAuthPlugin) SignWithKMS(ctx context.Context, pa encodedHdr := base64.RawURLEncoding.EncodeToString(hdrBuf) encodedPayload := base64.RawURLEncoding.EncodeToString(payload) - input := strings.Join( - []string{ - encodedHdr, - encodedPayload, - }, ".", - ) + input := encodedHdr + "." + encodedPayload digest, err := messageDigest([]byte(input), ap.AWSKmsKey.Algorithm) if err != nil { return nil, err @@ -628,7 +623,7 @@ func (ap *oauth2ClientCredentialsAuthPlugin) requestToken(ctx context.Context) ( return nil, err } - if strings.ToLower(tokenResponse.TokenType) != "bearer" { + if !strings.EqualFold(tokenResponse.TokenType, "bearer") { return nil, errors.New("unknown token type returned from token endpoint") } diff --git a/v1/plugins/rest/rest.go b/v1/plugins/rest/rest.go index 1089ac6975..e5d8e0f0d6 100644 --- a/v1/plugins/rest/rest.go +++ b/v1/plugins/rest/rest.go @@ -341,7 +341,7 @@ func (c Client) Do(ctx context.Context, method, path string) (*http.Response, er return nil, err } - if len(string(dump)) < defaultResponseSizeLimitBytes { + if len(dump) < defaultResponseSizeLimitBytes { c.loggerFields["response"] = string(dump) } else { c.loggerFields["response"] = fmt.Sprintf("%v...", string(dump[:defaultResponseSizeLimitBytes])) diff --git a/v1/plugins/rest/rest_test.go b/v1/plugins/rest/rest_test.go index 656515ee40..98ac5be881 100644 --- a/v1/plugins/rest/rest_test.go +++ b/v1/plugins/rest/rest_test.go @@ -939,10 +939,8 @@ func TestDoWithResponseHeaderTimeout(t *testing.T) { if !strings.Contains(err.Error(), tc.errMsg) { t.Fatalf("Expected error %v but got %v", tc.errMsg, err.Error()) } - } else { - if err != nil { - t.Fatalf("Unexpected error %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error %v", err) } }) } @@ -2013,10 +2011,8 @@ func TestAWSCredentialServiceChain(t *testing.T) { if !strings.Contains(err.Error(), tc.errMsg) { t.Fatalf("Expected error message %v but got %v", tc.errMsg, err.Error()) } - } else { - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error: %v", err) } }) } diff --git a/v1/rego/rego_test.go b/v1/rego/rego_test.go index 79f08532c6..9881637f2d 100644 --- a/v1/rego/rego_test.go +++ b/v1/rego/rego_test.go @@ -2149,7 +2149,7 @@ func TestRegoEvalWithBundle(t *testing.T) { t.Fatalf("expected %d modules, found %d", exp, act) } for act := range mods { - if exp := filepath.Join(path, "x/x.rego"); exp != act { + if exp := filepath.Join(path, "x", "x.rego"); exp != act { t.Errorf("expected module name %q, got %q", exp, act) } } @@ -2176,7 +2176,7 @@ func TestRegoEvalWithBundleURL(t *testing.T) { t.Fatalf("expected %d modules, found %d", exp, act) } for act := range mods { - if exp := filepath.Join(path, "x/x.rego"); exp != act { + if exp := filepath.Join(path, "x", "x.rego"); exp != act { t.Errorf("expected module name %q, got %q", exp, act) } } diff --git a/v1/repl/repl.go b/v1/repl/repl.go index dbbf5736c1..3fb9d928d8 100644 --- a/v1/repl/repl.go +++ b/v1/repl/repl.go @@ -513,7 +513,7 @@ func (r *REPL) cmdShow(args []string) error { } fmt.Fprint(r.output, string(bs)) return nil - } else if strings.Compare(args[0], "debug") == 0 { + } else if args[0] == "debug" { debug := replDebugState{ Explain: r.explain, Metrics: r.metricsEnabled(), @@ -707,7 +707,7 @@ func (r *REPL) unsetRule(ctx context.Context, name ast.Var) (bool, error) { } func (r *REPL) unsetPackage(_ context.Context, pkg *ast.Package) (bool, error) { - path := fmt.Sprintf("%v", pkg.Path) + path := pkg.Path.String() _, ok := r.modules[path] if ok { delete(r.modules, path) @@ -1418,10 +1418,10 @@ func newCommand(line string) *command { return nil } inputCommand := strings.ToLower(p[0]) - for _, c := range builtin { - if c.name == inputCommand { + for i := range builtin { + if builtin[i].name == inputCommand { return &command{ - op: c.name, + op: builtin[i].name, args: p[1:], } } diff --git a/v1/runtime/plugins_test.go b/v1/runtime/plugins_test.go index e69569d7b7..30e12f4022 100644 --- a/v1/runtime/plugins_test.go +++ b/v1/runtime/plugins_test.go @@ -66,7 +66,7 @@ func TestRegisterPlugin(t *testing.T) { RegisterPlugin("test", Factory{}) - params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml") + params.ConfigFile = filepath.Join(testDirRoot, "config.yaml") rt, err := NewRuntime(context.Background(), params) if err != nil { @@ -98,7 +98,7 @@ func TestRegisterPluginNotStartedWithoutConfig(t *testing.T) { RegisterPlugin("test", Factory{}) - params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml") + params.ConfigFile = filepath.Join(testDirRoot, "config.yaml") rt, err := NewRuntime(context.Background(), params) if err != nil { @@ -130,7 +130,7 @@ func TestRegisterPluginBadBootConfig(t *testing.T) { RegisterPlugin("test", Factory{}) - params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml") + params.ConfigFile = filepath.Join(testDirRoot, "config.yaml") _, err := NewRuntime(context.Background(), params) if err == nil || !strings.Contains(err.Error(), "config error: test") { @@ -151,7 +151,7 @@ func TestWaitPluginsReady(t *testing.T) { RegisterPlugin("test", Factory{}) params := NewParams() - params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml") + params.ConfigFile = filepath.Join(testDirRoot, "config.yaml") rt, err := NewRuntime(context.Background(), params) if err != nil { diff --git a/v1/runtime/runtime.go b/v1/runtime/runtime.go index 9000348aa9..4c8012299f 100644 --- a/v1/runtime/runtime.go +++ b/v1/runtime/runtime.go @@ -697,7 +697,7 @@ func (rt *Runtime) Serve(ctx context.Context) error { return rt.gracefulServerShutdown(rt.server) case err := <-errc: rt.logger.WithFields(map[string]interface{}{"err": err}).Error("Listener failed.") - os.Exit(1) + os.Exit(1) //nolint:gocritic } } } @@ -744,7 +744,7 @@ func (rt *Runtime) StartREPL(ctx context.Context) { if rt.Params.Watch { if err := rt.startWatcher(ctx, rt.Params.Paths, onReloadPrinter(rt.Params.Output)); err != nil { fmt.Fprintln(rt.Params.Output, "error opening watch:", err) - os.Exit(1) + os.Exit(1) //nolint:gocritic } } diff --git a/v1/runtime/runtime_test.go b/v1/runtime/runtime_test.go index 2f0a408444..63b7fa4a7f 100644 --- a/v1/runtime/runtime_test.go +++ b/v1/runtime/runtime_test.go @@ -140,10 +140,8 @@ func testRuntimeProcessWatchEvents(t *testing.T, asBundle bool, readAst bool) { if ast.Compare(val, exp) == 0 { return // success } - } else { - if reflect.DeepEqual(val, expected) { - return // success - } + } else if reflect.DeepEqual(val, expected) { + return // success } } @@ -1402,7 +1400,7 @@ func TestGracefulTracerShutdown(t *testing.T) { logger := testLog.New() params := NewParams() - params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml") + params.ConfigFile = filepath.Join(testDirRoot, "config.yaml") params.Addrs = &[]string{"localhost:0"} params.GracefulShutdownPeriod = 1 params.Logger = logger @@ -1603,7 +1601,7 @@ func TestRuntimeWithExplicitMetricConfiguration(t *testing.T) { test.WithTempFS(fs, func(testDirRoot string) { params := NewParams() - params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml") + params.ConfigFile = filepath.Join(testDirRoot, "config.yaml") _, err := NewRuntime(context.Background(), params) if err != nil { @@ -1619,7 +1617,7 @@ func TestRuntimeWithExplicitBadMetricConfiguration(t *testing.T) { test.WithTempFS(fs, func(testDirRoot string) { params := NewParams() - params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml") + params.ConfigFile = filepath.Join(testDirRoot, "config.yaml") _, err := NewRuntime(context.Background(), params) if err == nil { diff --git a/v1/sdk/test/test.go b/v1/sdk/test/test.go index ca9084eff2..04b9ce66ff 100644 --- a/v1/sdk/test/test.go +++ b/v1/sdk/test/test.go @@ -276,7 +276,7 @@ func (s *Server) handleOCIBundles(w http.ResponseWriter, r *http.Request) { tag := "" // image tag used in request path verification repo := "" // image repo used in request path verification var buf bytes.Buffer - //get first key that matches request url pattern + // get first key that matches request url pattern for key := range s.bundles { // extract tag parsedRef := strings.Split(key, ":") diff --git a/v1/server/authorizer/authorizer_test.go b/v1/server/authorizer/authorizer_test.go index 70634718c8..fa58443f52 100644 --- a/v1/server/authorizer/authorizer_test.go +++ b/v1/server/authorizer/authorizer_test.go @@ -268,13 +268,9 @@ func TestBasicEscapeError(t *testing.T) { req.URL.Path = `/invalid/path/foo%LALALA` - compiler := func() *ast.Compiler { - return ast.NewCompiler() - } - store := inmem.New() - NewBasic(&mockHandler{}, compiler, store).ServeHTTP(recorder, req) + NewBasic(&mockHandler{}, ast.NewCompiler, store).ServeHTTP(recorder, req) if recorder.Code != http.StatusBadRequest { t.Fatalf("Expected bad request but got: %v", recorder) diff --git a/v1/server/handlers/compress.go b/v1/server/handlers/compress.go index 17b097489e..26cfc02e55 100644 --- a/v1/server/handlers/compress.go +++ b/v1/server/handlers/compress.go @@ -131,7 +131,7 @@ func (w *compressResponseWriter) doCompressedResponse() error { w.Header().Del(contentLengthHeader) w.writeHeader() // there's nothing to write - if len(w.buffer) <= 0 { + if len(w.buffer) == 0 { return nil } gzipWriter := gzipPool.Get().(*gzip.Writer) diff --git a/v1/server/server.go b/v1/server/server.go index 4db3c40904..94e7c80937 100644 --- a/v1/server/server.go +++ b/v1/server/server.go @@ -581,9 +581,9 @@ func (b *baseHTTPListener) Type() httpListenerType { return b.t } -func isMinTLSVersionSupported(TLSVersion uint16) bool { +func isMinTLSVersionSupported(tlsVersion uint16) bool { for _, version := range supportedTLSVersions { - if TLSVersion == version { + if tlsVersion == version { return true } } @@ -2722,7 +2722,7 @@ func getBoolParam(url *url.URL, name string, ifEmpty bool) bool { } for _, x := range p { - if strings.ToLower(x) == "true" { + if strings.EqualFold(x, "true") { return true } } diff --git a/v1/server/types/types.go b/v1/server/types/types.go index e943ef884e..add9d91916 100644 --- a/v1/server/types/types.go +++ b/v1/server/types/types.go @@ -207,7 +207,7 @@ func (t TraceV1) MarshalJSON() ([]byte, error) { // UnmarshalJSON unmarshals the TraceV1 from a JSON representation. func (t *TraceV1) UnmarshalJSON(b []byte) error { - *t = TraceV1(b[:]) + *t = TraceV1(b) return nil } diff --git a/v1/storage/errors.go b/v1/storage/errors.go index 8c789052ed..a3d1c00737 100644 --- a/v1/storage/errors.go +++ b/v1/storage/errors.go @@ -56,8 +56,7 @@ func (err *Error) Error() string { // IsNotFound returns true if this error is a NotFoundErr. func IsNotFound(err error) bool { - switch err := err.(type) { - case *Error: + if err, ok := err.(*Error); ok { return err.Code == NotFoundErr } return false diff --git a/v1/storage/inmem/inmem_test.go b/v1/storage/inmem/inmem_test.go index fb2da20b89..fe1495ae80 100644 --- a/v1/storage/inmem/inmem_test.go +++ b/v1/storage/inmem/inmem_test.go @@ -1109,10 +1109,8 @@ func TestInMemoryTriggers(t *testing.T) { if err != nil || ast.Compare(expAstValue, result) != 0 { t.Fatalf("Expected result to be %v for trigger read but got: %v (err: %v)", expectedValue, result, err) } - } else { - if err != nil || !reflect.DeepEqual(result, expectedValue) { - t.Fatalf("Expected result to be %v for trigger read but got: %v (err: %v)", expectedValue, result, err) - } + } else if err != nil || !reflect.DeepEqual(result, expectedValue) { + t.Fatalf("Expected result to be %v for trigger read but got: %v (err: %v)", expectedValue, result, err) } event = evt }, diff --git a/v1/test/cases/internal/fmtcases/main.go b/v1/test/cases/internal/fmtcases/main.go index 48987fc9e8..8c66076758 100644 --- a/v1/test/cases/internal/fmtcases/main.go +++ b/v1/test/cases/internal/fmtcases/main.go @@ -89,7 +89,7 @@ func copyEntry(sourceRoot string, sourceRegoVersion ast.RegoVersion, e os.DirEnt } // Format test modules - for _, testCase := range testCases.Cases { + for _, testCase := range testCases.Cases { //nolint:gocritic for i, module := range testCase.Modules { bs, err := format.SourceWithOpts(fmt.Sprintf("mod%d.rego", i), []byte(module), format.Opts{ diff --git a/v1/test/e2e/authz/authz_bench_integration_test.go b/v1/test/e2e/authz/authz_bench_integration_test.go index 6362436cc8..5ebaeae476 100644 --- a/v1/test/e2e/authz/authz_bench_integration_test.go +++ b/v1/test/e2e/authz/authz_bench_integration_test.go @@ -82,7 +82,7 @@ func runAuthzBenchmark(b *testing.B, mode testAuthz.InputMode, numPaths int) { b.Fatal(err) } - queryPath := strings.Replace(testAuthz.AllowQuery, ".", "/", -1) + queryPath := strings.ReplaceAll(testAuthz.AllowQuery, ".", "/") url := testRuntime.URL() + "/v1/" + queryPath input, expected := testAuthz.GenerateInput(profile, mode) diff --git a/v1/test/e2e/h2c/h2c_test.go b/v1/test/e2e/h2c/h2c_test.go index 8e3da44124..11364c4d17 100644 --- a/v1/test/e2e/h2c/h2c_test.go +++ b/v1/test/e2e/h2c/h2c_test.go @@ -55,7 +55,6 @@ func TestH2CHTTPListeners(t *testing.T) { if err != nil { t.Fatalf("failed to GET %s: %s", u, err) } - defer resp.Body.Close() if expected, actual := http.StatusOK, resp.StatusCode; expected != actual { t.Errorf("resp status: expected %d, got %d", expected, actual) @@ -63,5 +62,7 @@ func TestH2CHTTPListeners(t *testing.T) { if expected, actual := 2, resp.ProtoMajor; expected != actual { t.Errorf("resp.ProtoMajor: expected %d, got %d", expected, actual) } + + resp.Body.Close() } } diff --git a/v1/test/e2e/testing.go b/v1/test/e2e/testing.go index e244449b2d..903d056829 100644 --- a/v1/test/e2e/testing.go +++ b/v1/test/e2e/testing.go @@ -15,7 +15,6 @@ import ( "net/http" "net/url" "os" - "path/filepath" "strings" "sync" "testing" @@ -353,19 +352,19 @@ func (t *TestRuntime) UploadData(data io.Reader) error { func (t *TestRuntime) UploadDataToPath(path string, data io.Reader) error { client := &http.Client{} - urlPath := strings.TrimSuffix(filepath.Join("/v1/data"+path), "/") + urlPath := strings.TrimSuffix("/v1/data"+path, "/") req, err := http.NewRequest("PUT", t.URL()+urlPath, data) if err != nil { - return fmt.Errorf("Unexpected error creating request: %s", err) + return fmt.Errorf("unexpected error creating request: %s", err) } resp, err := client.Do(req) if err != nil { - return fmt.Errorf("Failed to PUT data: %s", err) + return fmt.Errorf("failed to PUT data: %s", err) } if resp.StatusCode != http.StatusNoContent { - return fmt.Errorf("Unexpected response: %d %s", resp.StatusCode, resp.Status) + return fmt.Errorf("unexpected response: %d %s", resp.StatusCode, resp.Status) } return nil } diff --git a/v1/test/wasm/cmd/wasm-rego-testgen/main.go b/v1/test/wasm/cmd/wasm-rego-testgen/main.go index 23ca3fea2c..ad694f1c5f 100644 --- a/v1/test/wasm/cmd/wasm-rego-testgen/main.go +++ b/v1/test/wasm/cmd/wasm-rego-testgen/main.go @@ -42,7 +42,7 @@ type compiledTestCase struct { func compileTestCases(ctx context.Context, tests cases.Set) (*compiledTestCaseSet, error) { result := make([]compiledTestCase, 0, len(tests.Cases)) - for _, tc := range tests.Cases { + for _, tc := range tests.Cases { //nolint:gocritic var numExpects int @@ -171,7 +171,7 @@ func run(params params) error { return err } - dst := strings.Replace(files[i].Name(), ".yaml", ".json", -1) + dst := strings.ReplaceAll(files[i].Name(), ".yaml", ".json") return writeFile(tw, dst, bs) }() if err != nil { diff --git a/v1/tester/reporter.go b/v1/tester/reporter.go index 0b5f8f5423..eae2f5652e 100644 --- a/v1/tester/reporter.go +++ b/v1/tester/reporter.go @@ -219,7 +219,7 @@ func (r PrettyReporter) fmtBenchmark(tr *Result) string { // This converts the test case name like data.foo.bar.test_auth to be more // like BenchmarkDataFooBarTestAuth. camelCaseName := "" - for _, part := range strings.Split(strings.Replace(name, "_", ".", -1), ".") { + for _, part := range strings.Split(strings.ReplaceAll(name, "_", "."), ".") { camelCaseName += strings.Title(part) //nolint:staticcheck // SA1019, no unicode here } name = "Benchmark" + camelCaseName diff --git a/v1/topdown/bindings.go b/v1/topdown/bindings.go index e7d548d3de..8c7bfbd178 100644 --- a/v1/topdown/bindings.go +++ b/v1/topdown/bindings.go @@ -314,12 +314,12 @@ func (b *bindingsArrayHashmap) Put(key *ast.Term, value value) { if b.a == nil { b.a = new([maxLinearScan]bindingArrayKeyValue) } else if i := b.find(key); i >= 0 { - (*b.a)[i].value = value + b.a[i].value = value return } if b.n < maxLinearScan { - (*b.a)[b.n] = bindingArrayKeyValue{key, value} + b.a[b.n] = bindingArrayKeyValue{key, value} b.n++ return } @@ -342,7 +342,7 @@ func (b *bindingsArrayHashmap) Put(key *ast.Term, value value) { func (b *bindingsArrayHashmap) Get(key *ast.Term) (value, bool) { if b.m == nil { if i := b.find(key); i >= 0 { - return (*b.a)[i].value, true + return b.a[i].value, true } return value{}, false @@ -361,7 +361,7 @@ func (b *bindingsArrayHashmap) Delete(key *ast.Term) { if i := b.find(key); i >= 0 { n := b.n - 1 if i < n { - (*b.a)[i] = (*b.a)[n] + b.a[i] = b.a[n] } b.n = n @@ -375,7 +375,7 @@ func (b *bindingsArrayHashmap) Delete(key *ast.Term) { func (b *bindingsArrayHashmap) Iter(f func(k *ast.Term, v value) bool) { if b.m == nil { for i := range b.n { - if f((*b.a)[i].key, (*b.a)[i].value) { + if f(b.a[i].key, b.a[i].value) { return } } @@ -392,7 +392,7 @@ func (b *bindingsArrayHashmap) Iter(f func(k *ast.Term, v value) bool) { func (b *bindingsArrayHashmap) find(key *ast.Term) int { v := key.Value.(ast.Var) for i := range b.n { - if (*b.a)[i].key.Value.(ast.Var) == v { + if b.a[i].key.Value.(ast.Var) == v { return i } } diff --git a/v1/topdown/casts.go b/v1/topdown/casts.go index cf8bdedcaa..f395324841 100644 --- a/v1/topdown/casts.go +++ b/v1/topdown/casts.go @@ -46,7 +46,7 @@ func builtinToNumber(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term return builtins.NewOperandTypeErr(1, operands[0].Value, "null", "boolean", "number", "string") } -// Deprecated in v0.13.0. +// Deprecated: deprecated in v0.13.0. func builtinToArray(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { switch val := operands[0].Value.(type) { case *ast.Array: @@ -64,7 +64,7 @@ func builtinToArray(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) } } -// Deprecated in v0.13.0. +// Deprecated: deprecated in v0.13.0. func builtinToSet(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { switch val := operands[0].Value.(type) { case *ast.Array: @@ -80,7 +80,7 @@ func builtinToSet(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) e } } -// Deprecated in v0.13.0. +// Deprecated: deprecated in v0.13.0. func builtinToString(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { switch val := operands[0].Value.(type) { case ast.String: @@ -90,7 +90,7 @@ func builtinToString(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term } } -// Deprecated in v0.13.0. +// Deprecated: deprecated in v0.13.0. func builtinToBoolean(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { switch val := operands[0].Value.(type) { case ast.Boolean: @@ -100,7 +100,7 @@ func builtinToBoolean(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Ter } } -// Deprecated in v0.13.0. +// Deprecated: deprecated in v0.13.0. func builtinToNull(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { switch val := operands[0].Value.(type) { case ast.Null: @@ -110,7 +110,7 @@ func builtinToNull(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) } } -// Deprecated in v0.13.0. +// Deprecated: deprecated in v0.13.0. func builtinToObject(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { switch val := operands[0].Value.(type) { case ast.Object: diff --git a/v1/topdown/cidr.go b/v1/topdown/cidr.go index 01c82f59a8..00c034656b 100644 --- a/v1/topdown/cidr.go +++ b/v1/topdown/cidr.go @@ -255,7 +255,7 @@ func (c cidrBlockRanges) Less(i, j int) bool { } // Then compare first IP. - cmp = bytes.Compare(*c[i].First, *c[i].First) + cmp = bytes.Compare(*c[i].First, *c[j].First) if cmp < 0 { return true } else if cmp > 0 { diff --git a/v1/topdown/crypto.go b/v1/topdown/crypto.go index 63d8245bcb..dafbac7850 100644 --- a/v1/topdown/crypto.go +++ b/v1/topdown/crypto.go @@ -236,11 +236,11 @@ func extractVerifyOpts(options ast.Object) (verifyOpt x509.VerifyOptions, err er Foreach(func(*ast.Term)) } var ks forEach - switch options.Get(key).Value.(type) { + switch v := options.Get(key).Value.(type) { case *ast.Array: - ks = options.Get(key).Value.(*ast.Array) + ks = v case ast.Set: - ks = options.Get(key).Value.(ast.Set) + ks = v default: return verifyOpt, errors.New("'KeyUsages' should be an Array or Set") } diff --git a/v1/topdown/crypto_test.go b/v1/topdown/crypto_test.go index 748d1f0899..d91bf9b33b 100644 --- a/v1/topdown/crypto_test.go +++ b/v1/topdown/crypto_test.go @@ -201,7 +201,7 @@ func TestX509ParseAndVerify(t *testing.T) { t.Run("TestMissingIntermediate", func(t *testing.T) { t.Parallel() - chain := strings.Join([]string{rootCA, leaf}, "\n") + chain := rootCA + "\n" + leaf parsed, err := getX509CertsFromString(chain) if err != nil { diff --git a/v1/topdown/eval.go b/v1/topdown/eval.go index 6a3081658f..635ea38451 100644 --- a/v1/topdown/eval.go +++ b/v1/topdown/eval.go @@ -162,10 +162,10 @@ func (e *eval) String() string { func (e *eval) string(s *strings.Builder) { fmt.Fprintf(s, "') + s.WriteByte('>') } func (e *eval) builtinFunc(name string) (*ast.Builtin, BuiltinFunc, bool) { @@ -2669,7 +2669,7 @@ func maxRefLength(rules []*ast.Rule, ceil int) int { for _, r := range rules { rl := len(r.Ref()) if r.Head.RuleKind() == ast.MultiValue { - rl = rl + 1 + rl++ } if rl >= ceil { return ceil diff --git a/v1/topdown/http.go b/v1/topdown/http.go index 58ffd2c122..2d29c12f4d 100644 --- a/v1/topdown/http.go +++ b/v1/topdown/http.go @@ -607,7 +607,7 @@ func createHTTPRequest(bctx BuiltinContext, obj ast.Object) (*http.Request, *htt } if len(tlsCaCert) != 0 { - tlsCaCert = bytes.Replace(tlsCaCert, []byte("\\n"), []byte("\n"), -1) + tlsCaCert = bytes.ReplaceAll(tlsCaCert, []byte("\\n"), []byte("\n")) pool, err := addCACertsFromBytes(tlsConfig.RootCAs, tlsCaCert) if err != nil { return nil, nil, err diff --git a/v1/topdown/http_test.go b/v1/topdown/http_test.go index a21537611a..575b055b12 100644 --- a/v1/topdown/http_test.go +++ b/v1/topdown/http_test.go @@ -332,7 +332,7 @@ func TestHTTPSendCustomRequestHeaders(t *testing.T) { if err != nil { panic(err) } - s := string(jsonString[:]) + s := string(jsonString) // expected result with custom User-Agent @@ -344,7 +344,7 @@ func TestHTTPSendCustomRequestHeaders(t *testing.T) { if err != nil { panic(err) } - s2 := string(jsonString[:]) + s2 := string(jsonString) // run the test tests := []struct { @@ -1589,8 +1589,6 @@ func TestHTTPSendInterQueryForceCaching(t *testing.T) { })) defer ts.Close() - //runTopDownTestCase(t, data, tc.note, []string{strings.ReplaceAll(tc.ruleTemplate, "%URL%", ts.URL)}, tc.response, opts) - qStr := strings.ReplaceAll(tc.query, "%URL%", ts.URL) q := newQuery(qStr, t0) @@ -2163,10 +2161,8 @@ func TestParseMaxAgeCacheDirective(t *testing.T) { if tc.err != nil && tc.err.Error() != err.Error() { t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error()) } - } else { - if err != nil { - t.Fatalf("Unexpected error %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error %v", err) } if actual != tc.expected { @@ -2298,10 +2294,8 @@ func TestGetBoolValFromReqObj(t *testing.T) { if tc.err != nil && tc.err.Error() != err.Error() { t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error()) } - } else { - if err != nil { - t.Fatalf("Unexpected error %v", err) - } + } else if err != nil { + t.Fatalf("Unexpected error %v", err) } if actual != tc.expected { @@ -2647,7 +2641,7 @@ func TestHTTPSClient(t *testing.T) { data := loadSmallTestData() rules := append( httpSendHelperRules, - fmt.Sprintf(`p = x { http.send({"method": "get", "url": "%s", "tls_use_system_certs": true, "tls_ca_cert_env_variable": "CLIENT_CA_ENV", "tls_client_cert_env_variable": "CLIENT_CERT_ENV", "tls_client_key_env_variable": "CLIENT_KEY_ENV", "tls_ca_cert_file": "%s", "tls_client_cert_file": "%s", "tls_client_key_file": "%s"}, resp); x := clean_headers(resp) }`, s.URL, localCaFile, localClientCertFile, localClientKeyFile), + fmt.Sprintf(`p = x { http.send({"method": "get", "url": %q, "tls_use_system_certs": true, "tls_ca_cert_env_variable": "CLIENT_CA_ENV", "tls_client_cert_env_variable": "CLIENT_CERT_ENV", "tls_client_key_env_variable": "CLIENT_KEY_ENV", "tls_ca_cert_file": "%s", "tls_client_cert_file": "%s", "tls_client_key_file": "%s"}, resp); x := clean_headers(resp) }`, s.URL, localCaFile, localClientCertFile, localClientKeyFile), ) // run the test @@ -2678,7 +2672,7 @@ func TestHTTPSClient(t *testing.T) { expectedResult := &Error{Code: BuiltinErr, Message: fixupDarwinGo118("x509: certificate signed by unknown authority", `“my-server” certificate is not standards compliant`), Location: nil} data := loadSmallTestData() rule := []string{fmt.Sprintf( - `p = x { http.send({"method": "get", "url": "%s", "tls_client_cert_file": "%s", "tls_client_key_file": "%s", "tls_use_system_certs": true}, x) }`, s.URL, localClientCertFile, localClientKeyFile)} + `p = x { http.send({"method": "get", "url": %q, "tls_client_cert_file": %q, "tls_client_key_file": %q, "tls_use_system_certs": true}, x) }`, s.URL, localClientCertFile, localClientKeyFile)} // run the test runTopDownTestCase(t, data, "http.send", rule, expectedResult) @@ -2710,7 +2704,7 @@ func TestHTTPSClient(t *testing.T) { data := loadSmallTestData() rule := []string{fmt.Sprintf( - `p = x { http.send({"method": "get", "url": "%s", "tls_ca_cert_file": "%s", "tls_client_cert_file": "%s", "tls_client_key_file": "%s", "tls_server_name": "%s"}, x) }`, url, localCaFile, localClientCertFile, localClientKeyFile, hostname)} + `p = x { http.send({"method": "get", "url": %q, "tls_ca_cert_file": %q, "tls_client_cert_file": %q, "tls_client_key_file": %q, "tls_server_name": %q}, x) }`, url, localCaFile, localClientCertFile, localClientKeyFile, hostname)} // run the test runTopDownTestCase(t, data, "http.send", rule, expected) @@ -2917,7 +2911,7 @@ func TestHTTPSNoClientCerts(t *testing.T) { expectedResult := &Error{Code: BuiltinErr, Message: fixupDarwinGo118("x509: certificate signed by unknown authority", `“my-server” certificate is not standards compliant`), Location: nil} data := loadSmallTestData() rule := []string{fmt.Sprintf( - `p = x { http.send({"method": "get", "url": "%s", "tls_use_system_certs": true}, x) }`, s.URL)} + `p = x { http.send({"method": "get", "url": %q, "tls_use_system_certs": true}, x) }`, s.URL)} // run the test runTopDownTestCase(t, data, "http.send", rule, expectedResult) @@ -3612,9 +3606,9 @@ func TestSocketHTTPGetRequest(t *testing.T) { expected interface{} }{ {"http.send", []string{fmt.Sprintf( - `p = x { http.send({"method": "get", "url": "%s", "force_json_decode": true}, resp); x := clean_headers(resp) }`, rawURL)}, resultObj.String()}, + `p = x { http.send({"method": "get", "url": %q, "force_json_decode": true}, resp); x := clean_headers(resp) }`, rawURL)}, resultObj.String()}, {"http.send skip verify no HTTPS", []string{fmt.Sprintf( - `p = x { http.send({"method": "get", "url": "%s", "force_json_decode": true, "tls_insecure_skip_verify": true}, resp); x := clean_headers(resp) }`, rawURL)}, resultObj.String()}, + `p = x { http.send({"method": "get", "url": %q, "force_json_decode": true, "tls_insecure_skip_verify": true}, resp); x := clean_headers(resp) }`, rawURL)}, resultObj.String()}, } data := loadSmallTestData() @@ -3718,7 +3712,7 @@ func TestHTTPGetRequestAllowNet(t *testing.T) { expectedError := &Error{Code: "eval_builtin_error", Message: "http.send: unallowed host: " + serverHost} rules := []string{fmt.Sprintf( - `p = x { http.send({"method": "get", "url": "%s", "force_json_decode": true}, resp); x := remove_headers(resp) }`, ts.URL)} + `p = x { http.send({"method": "get", "url": %q, "force_json_decode": true}, resp); x := remove_headers(resp) }`, ts.URL)} // run the test tests := []struct { diff --git a/v1/topdown/json_bench_test.go b/v1/topdown/json_bench_test.go index dafd3e1c42..3207e6a9d6 100644 --- a/v1/topdown/json_bench_test.go +++ b/v1/topdown/json_bench_test.go @@ -405,7 +405,7 @@ func BenchmarkJSONPatchPathologicalNestedAddChainObject(b *testing.B) { [2]*ast.Term{ast.StringTerm("value"), ast.ObjectTerm()}, ) - path = path + "/a" + path += "/a" patchObj.Insert(ast.StringTerm("path"), ast.StringTerm(path)) patchList[i] = ast.NewTerm(patchObj) @@ -436,7 +436,7 @@ func BenchmarkJSONPatchPathologicalNestedAddChainArray(b *testing.B) { [2]*ast.Term{ast.StringTerm("value"), ast.ArrayTerm()}, ) - path = path + "/0" + path += "/0" patchObj.Insert(ast.StringTerm("path"), ast.StringTerm(path)) patchList[i] = ast.NewTerm(patchObj) diff --git a/v1/topdown/parse_bytes.go b/v1/topdown/parse_bytes.go index dcc8e21997..cd36b87b17 100644 --- a/v1/topdown/parse_bytes.go +++ b/v1/topdown/parse_bytes.go @@ -109,7 +109,7 @@ func builtinNumBytes(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term func formatString(s ast.String) string { str := string(s) lower := strings.ToLower(str) - return strings.Replace(lower, "\"", "", -1) + return strings.ReplaceAll(lower, "\"", "") } // Splits the string into a number string à la "10" or "10.2" and a unit diff --git a/v1/topdown/parse_units.go b/v1/topdown/parse_units.go index 47e459510a..44aec86299 100644 --- a/v1/topdown/parse_units.go +++ b/v1/topdown/parse_units.go @@ -50,7 +50,7 @@ func builtinUnits(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) e // We remove escaped quotes from strings here to retain parity with units.parse_bytes. s := string(raw) - s = strings.Replace(s, "\"", "", -1) + s = strings.ReplaceAll(s, "\"", "") if strings.Contains(s, " ") { return errIncludesSpaces diff --git a/v1/topdown/sets.go b/v1/topdown/sets.go index b7566b8e6e..9df2d328a0 100644 --- a/v1/topdown/sets.go +++ b/v1/topdown/sets.go @@ -9,7 +9,7 @@ import ( "github.com/open-policy-agent/opa/v1/topdown/builtins" ) -// Deprecated in v0.4.2 in favour of minus/infix "-" operation. +// Deprecated: deprecated in v0.4.2 in favour of minus/infix "-" operation. func builtinSetDiff(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { s1, err := builtins.SetOperand(operands[0].Value, 1) diff --git a/v1/topdown/strings.go b/v1/topdown/strings.go index 0b7c8a5180..d9c56b5818 100644 --- a/v1/topdown/strings.go +++ b/v1/topdown/strings.go @@ -232,6 +232,9 @@ func builtinIndexOf(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) } if isASCII(string(base)) && isASCII(string(search)) { + // this is a false positive in the indexAlloc rule that thinks + // we're converting byte arrays to strings + //nolint:gocritic return iter(ast.InternedIntNumberTerm(strings.Index(string(base), string(search)))) } @@ -475,7 +478,7 @@ func builtinReplace(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) return err } - replaced := strings.Replace(string(s), string(old), string(n), -1) + replaced := strings.ReplaceAll(string(s), string(old), string(n)) if replaced == string(s) { return iter(operands[0]) } diff --git a/v1/topdown/tokens.go b/v1/topdown/tokens.go index 21e0e3a4e1..2050e82d63 100644 --- a/v1/topdown/tokens.go +++ b/v1/topdown/tokens.go @@ -1105,7 +1105,7 @@ func builtinJWTDecodeVerify(bctx BuiltinContext, operands []*ast.Term, iter func } // RFC7159 7.2 #8 and 5.2 cty - if strings.ToUpper(header.cty) == headerJwt { + if strings.EqualFold(header.cty, headerJwt) { // Nested JWT, go round again with payload as first argument a = p.Value continue @@ -1149,11 +1149,11 @@ func builtinJWTDecodeVerify(bctx BuiltinContext, operands []*ast.Term, iter func } // RFC7159 4.1.4 exp if exp := payload.Get(jwtExpKey); exp != nil { - switch exp.Value.(type) { + switch v := exp.Value.(type) { case ast.Number: // constraints.time is in nanoseconds but exp Value is in seconds compareTime := ast.FloatNumberTerm(constraints.time / 1000000000) - if ast.Compare(compareTime, exp.Value.(ast.Number)) != -1 { + if ast.Compare(compareTime, v) != -1 { return iter(unverified) } default: @@ -1162,11 +1162,11 @@ func builtinJWTDecodeVerify(bctx BuiltinContext, operands []*ast.Term, iter func } // RFC7159 4.1.5 nbf if nbf := payload.Get(jwtNbfKey); nbf != nil { - switch nbf.Value.(type) { + switch v := nbf.Value.(type) { case ast.Number: // constraints.time is in nanoseconds but nbf Value is in seconds compareTime := ast.FloatNumberTerm(constraints.time / 1000000000) - if ast.Compare(compareTime, nbf.Value.(ast.Number)) == -1 { + if ast.Compare(compareTime, v) == -1 { return iter(unverified) } default: diff --git a/v1/topdown/tokens_test.go b/v1/topdown/tokens_test.go index 2c37ee21d2..a7fdf3eb43 100644 --- a/v1/topdown/tokens_test.go +++ b/v1/topdown/tokens_test.go @@ -983,13 +983,8 @@ func createJwt(payload string, privateKey string) (string, error) { hdrStr := base64.RawURLEncoding.EncodeToString([]byte(hdr)) payloadStr := base64.RawURLEncoding.EncodeToString([]byte(payload)) + signingInput := hdrStr + "." + payloadStr - signingInput := strings.Join( - []string{ - hdrStr, - payloadStr, - }, ".", - ) pk, err := jwkKeySet.Keys[0].Materialize() if err != nil { return "", fmt.Errorf("failed to materialize key: %s", err.Error()) @@ -999,13 +994,7 @@ func createJwt(payload string, privateKey string) (string, error) { return "", fmt.Errorf("failed to sign message: %s", err.Error()) } encSignature := base64.RawURLEncoding.EncodeToString(signature) - - encoded := strings.Join( - []string{ - signingInput, - encSignature, - }, ".", - ) + encoded := signingInput + "." + encSignature return encoded, nil } diff --git a/v1/topdown/topdown_test.go b/v1/topdown/topdown_test.go index 0556dc628b..3386b5e869 100644 --- a/v1/topdown/topdown_test.go +++ b/v1/topdown/topdown_test.go @@ -2328,9 +2328,7 @@ func (rs resultSet) Less(i, j int) bool { } func (rs resultSet) Swap(i, j int) { - tmp := rs[i] - rs[i] = rs[j] - rs[j] = tmp + rs[i], rs[j] = rs[j], rs[i] } func (rs resultSet) Len() int { diff --git a/v1/topdown/trace.go b/v1/topdown/trace.go index e68c467dc8..85143bf711 100644 --- a/v1/topdown/trace.go +++ b/v1/topdown/trace.go @@ -373,10 +373,6 @@ func exprLocalVars(e *Event) *ast.ValueMap { vars := ast.NewValueMap() findVars := func(term *ast.Term) bool { - //if r, ok := term.Value.(ast.Ref); ok { - // fmt.Printf("ref: %v\n", r) - // //return true - //} if name, ok := term.Value.(ast.Var); ok { if meta, ok := e.LocalMetadata[name]; ok { if val := e.Locals.Get(name); val != nil { diff --git a/v1/types/types.go b/v1/types/types.go index c41f387e14..1bf4d6aed0 100644 --- a/v1/types/types.go +++ b/v1/types/types.go @@ -860,7 +860,7 @@ func Compare(a, b Type) int { } else if x < y { return -1 } - switch a.(type) { + switch a.(type) { //nolint:gocritic case nil, Null, Boolean, Number, String: return 0 case *Array: @@ -1174,7 +1174,7 @@ func TypeOf(x interface{}) Type { type typeSlice []Type func (s typeSlice) Less(i, j int) bool { return Compare(s[i], s[j]) < 0 } -func (s typeSlice) Swap(i, j int) { x := s[i]; s[i] = s[j]; s[j] = x } +func (s typeSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s typeSlice) Len() int { return len(s) } func typeSliceCompare(a, b []Type) int { diff --git a/v1/util/backoff.go b/v1/util/backoff.go index 36d57f14e2..1558f0cff8 100644 --- a/v1/util/backoff.go +++ b/v1/util/backoff.go @@ -9,17 +9,6 @@ import ( "time" ) -func init() { - // NOTE(sr): We don't need good random numbers here; it's used for jittering - // the backup timing a bit. But anyways, let's make it random enough; without - // a call to rand.Seed() we'd get the same stream of numbers for each program - // run. (Or not, if some other packages happens to seed the global randomness - // source.) - // Note(philipc): rand.Seed() was deprecated in Go 1.20, so we've switched to - // using the recommended rand.New(rand.NewSource(seed)) style. - rand.New(rand.NewSource(time.Now().UnixNano())) -} - // DefaultBackoff returns a delay with an exponential backoff based on the // number of retries. func DefaultBackoff(base, maxNS float64, retries int) time.Duration { diff --git a/v1/version/version.go b/v1/version/version.go index d62a9a882a..7a109fb237 100644 --- a/v1/version/version.go +++ b/v1/version/version.go @@ -44,6 +44,6 @@ func init() { } } if dirty { - Vcs = Vcs + "-dirty" + Vcs += "-dirty" } }