Skip to content

Commit

Permalink
Update golangci-lint to latest v1.62.2
Browse files Browse the repository at this point in the history
Quite a lot of gosec ones about integers under/overflows - I tried to
fix the ones that weren't problematic, but there were quite a lot.
  • Loading branch information
mstoykov committed Dec 12, 2024
1 parent c6fcb9c commit 1d1afd0
Show file tree
Hide file tree
Showing 45 changed files with 112 additions and 114 deletions.
2 changes: 1 addition & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# v1.60.1
# v1.62.2
# Please don't remove the first line. It uses in CI to determine the golangci version
run:
timeout: 5m
Expand Down
4 changes: 2 additions & 2 deletions cloudapi/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,11 +226,11 @@ func (sfn sleeperFunc) Sleep(d time.Duration) {
// between the latest iteration and the next retry.
// Interval is used as the base to compute an exponential backoff,
// if the computed interval overtakes the max interval then max will be used.
func retry(s sleeper, attempts uint, interval, maxDuration time.Duration, do func() error) (err error) {
func retry(s sleeper, attempts int, interval, maxDuration time.Duration, do func() error) (err error) {
baseInterval := math.Abs(interval.Truncate(time.Second).Seconds())
r := rand.New(rand.NewSource(time.Now().UnixNano())) //nolint:gosec

for i := 0; i < int(attempts); i++ {
for i := 0; i < attempts; i++ {
if i > 0 {
// wait = (interval ^ i) + random milliseconds
wait := time.Duration(math.Pow(baseInterval, float64(i))) * time.Second
Expand Down
2 changes: 1 addition & 1 deletion cmd/report.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func createReport(u *usage.Usage, execScheduler *execution.Scheduler) map[string
m["duration"] = execState.GetCurrentTestRunDuration().String()
m["goos"] = runtime.GOOS
m["goarch"] = runtime.GOARCH
m["vus_max"] = uint64(execState.GetInitializedVUsCount())
m["vus_max"] = uint64(execState.GetInitializedVUsCount()) //nolint:gosec
m["iterations"] = execState.GetFullIterationCount()
executors := make(map[string]int)
for _, ec := range execScheduler.GetExecutorConfigs() {
Expand Down
2 changes: 1 addition & 1 deletion cmd/report_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func TestCreateReport(t *testing.T) {
require.NoError(t, err)

s.GetState().ModInitializedVUsCount(6)
s.GetState().AddFullIterations(uint64(opts.Iterations.Int64))
s.GetState().AddFullIterations(uint64(opts.Iterations.Int64)) //nolint:gosec
s.GetState().MarkStarted()
time.Sleep(10 * time.Millisecond)
s.GetState().MarkEnded()
Expand Down
10 changes: 5 additions & 5 deletions errext/abort_reason.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,20 @@ func WithAbortReasonIfNone(err error, abortReason AbortReason) error {
// The given error already has an abort reason, do nothing
return err
}
return withAbortReason{err, abortReason}
return withAbortReasonError{err, abortReason}
}

type withAbortReason struct {
type withAbortReasonError struct {
error
abortReason AbortReason
}

func (ar withAbortReason) Unwrap() error {
func (ar withAbortReasonError) Unwrap() error {
return ar.error
}

func (ar withAbortReason) AbortReason() AbortReason {
func (ar withAbortReasonError) AbortReason() AbortReason {
return ar.abortReason
}

var _ HasAbortReason = withAbortReason{}
var _ HasAbortReason = withAbortReasonError{}
10 changes: 5 additions & 5 deletions errext/exit_code.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,20 +30,20 @@ func WithExitCodeIfNone(err error, exitCode exitcodes.ExitCode) error {
// The given error already has an exit code, do nothing
return err
}
return withExitCode{err, exitCode}
return withExitCodeError{err, exitCode}
}

type withExitCode struct {
type withExitCodeError struct {
error
exitCode exitcodes.ExitCode
}

func (wh withExitCode) Unwrap() error {
func (wh withExitCodeError) Unwrap() error {
return wh.error
}

func (wh withExitCode) ExitCode() exitcodes.ExitCode {
func (wh withExitCodeError) ExitCode() exitcodes.ExitCode {
return wh.exitCode
}

var _ HasExitCode = withExitCode{}
var _ HasExitCode = withExitCodeError{}
12 changes: 6 additions & 6 deletions errext/format_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func TestFormat(t *testing.T) {

t.Run("Exception", func(t *testing.T) {
t.Parallel()
err := fakeException{error: errors.New("simple error"), stack: "stack trace"}
err := fakeExceptionError{error: errors.New("simple error"), stack: "stack trace"}
errorText, fields := errext.Format(err)
assert.Equal(t, "stack trace", errorText)
assert.Empty(t, fields)
Expand All @@ -44,27 +44,27 @@ func TestFormat(t *testing.T) {

t.Run("ExceptionWithHint", func(t *testing.T) {
t.Parallel()
err := fakeException{error: errext.WithHint(errors.New("error with hint"), "hint message"), stack: "stack trace"}
err := fakeExceptionError{error: errext.WithHint(errors.New("error with hint"), "hint message"), stack: "stack trace"}
errorText, fields := errext.Format(err)
assert.Equal(t, "stack trace", errorText)
assert.Equal(t, map[string]interface{}{"hint": "hint message"}, fields)
})
}

type fakeException struct {
type fakeExceptionError struct {
error
stack string
abort errext.AbortReason
}

func (e fakeException) StackTrace() string {
func (e fakeExceptionError) StackTrace() string {
return e.stack
}

func (e fakeException) AbortReason() errext.AbortReason {
func (e fakeExceptionError) AbortReason() errext.AbortReason {
return e.abort
}

func (e fakeException) Unwrap() error {
func (e fakeExceptionError) Unwrap() error {
return e.error
}
10 changes: 5 additions & 5 deletions errext/hint.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,19 @@ func WithHint(err error, hint string) error {
if err == nil {
return nil // No error, do nothing
}
return withHint{err, hint}
return withHintError{err, hint}
}

type withHint struct {
type withHintError struct {
error
hint string
}

func (wh withHint) Unwrap() error {
func (wh withHintError) Unwrap() error {
return wh.error
}

func (wh withHint) Hint() string {
func (wh withHintError) Hint() string {
hint := wh.hint
var oldhint HasHint
if errors.As(wh.error, &oldhint) {
Expand All @@ -41,4 +41,4 @@ func (wh withHint) Hint() string {
return hint
}

var _ HasHint = withHint{}
var _ HasHint = withHintError{}
4 changes: 2 additions & 2 deletions execution/scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ func (e *Scheduler) getRunStats() string {
status = fmt.Sprintf("%s (%s)", status, pb.GetFixedLengthDuration(dur, e.maxDuration))
}

vusFmt := pb.GetFixedLengthIntFormat(int64(e.maxPossibleVUs))
vusFmt := pb.GetFixedLengthIntFormat(int64(e.maxPossibleVUs)) //nolint:gosec
return fmt.Sprintf(
"%s, "+vusFmt+"/"+vusFmt+" VUs, %d complete and %d interrupted iterations",
status, e.state.GetCurrentlyActiveVUsCount(), e.state.GetInitializedVUsCount(),
Expand Down Expand Up @@ -268,7 +268,7 @@ func (e *Scheduler) initVUsAndExecutors(ctx context.Context, samplesOut chan<- m
doneInits := e.initVUsConcurrently(subctx, samplesOut, vusToInitialize, runtime.GOMAXPROCS(0), logger)

initializedVUs := new(uint64)
vusFmt := pb.GetFixedLengthIntFormat(int64(vusToInitialize))
vusFmt := pb.GetFixedLengthIntFormat(int64(vusToInitialize)) //nolint:gosec
e.initProgress.Modify(
pb.WithProgress(func() (float64, []string) {
doneVUs := atomic.LoadUint64(initializedVUs)
Expand Down
4 changes: 2 additions & 2 deletions js/bundle.go
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ func (b *Bundle) newCompiler(logger logrus.FieldLogger) *compiler.Compiler {

func (b *Bundle) instantiate(vuImpl *moduleVUImpl, vuID uint64) (*BundleInstance, error) {
rt := vuImpl.runtime
err := b.setupJSRuntime(rt, int64(vuID), b.preInitState.Logger)
err := b.setupJSRuntime(rt, vuID, b.preInitState.Logger)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -375,7 +375,7 @@ func (b *Bundle) instantiate(vuImpl *moduleVUImpl, vuID uint64) (*BundleInstance
return bi, nil
}

func (b *Bundle) setupJSRuntime(rt *sobek.Runtime, vuID int64, logger logrus.FieldLogger) error {
func (b *Bundle) setupJSRuntime(rt *sobek.Runtime, vuID uint64, logger logrus.FieldLogger) error {
rt.SetFieldNameMapper(common.FieldNameMapper{})
rt.SetRandSource(common.NewRandSource())

Expand Down
8 changes: 4 additions & 4 deletions js/bundle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -870,15 +870,15 @@ func TestBundleNotSharable(t *testing.T) {
require.NoError(t, err)

bundles := map[string]*Bundle{"Source": b1, "Archive": b2}
vus, iters := 10, 1000
var vus, iters uint64 = 10, 1000
for name, b := range bundles {
b := b
t.Run(name, func(t *testing.T) {
t.Parallel()
for i := 0; i < vus; i++ {
bi, err := b.Instantiate(context.Background(), uint64(i))
for i := uint64(0); i < vus; i++ {
bi, err := b.Instantiate(context.Background(), i)
require.NoError(t, err)
for j := 0; j < iters; j++ {
for j := uint64(0); j < iters; j++ {
require.NoError(t, bi.Runtime.Set("__ITER", j))
_, err := bi.getCallableExport(consts.DefaultFn)(sobek.Undefined())
require.NoError(t, err)
Expand Down
4 changes: 2 additions & 2 deletions js/modules/k6/crypto/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import (
"fmt"
"hash"

"golang.org/x/crypto/md4" //nolint:staticcheck // #nosec G501 // MD4 is weak, but we need it for compatibility
"golang.org/x/crypto/ripemd160" // no lint:staticcheck // #nosec G501 // RIPEMD160 is weak, but we need it for compatibility
"golang.org/x/crypto/md4" //nolint:staticcheck,gosec // MD4 is weak, but we need it for compatibility
"golang.org/x/crypto/ripemd160" //nolint:staticcheck,gosec // RIPEMD160 is weak, but we need it for compatibility

"github.com/grafana/sobek"

Expand Down
2 changes: 1 addition & 1 deletion js/modules/k6/crypto/x509/x509.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
package x509

import (
"crypto/dsa" // #nosec G505 // DSA is weak, but we need it for compatibility
"crypto/dsa" //nolint:staticcheck // DSA is weak, but we need it for compatibility
"crypto/ecdsa"
"crypto/rsa"
"crypto/sha1" // #nosec G505
Expand Down
16 changes: 7 additions & 9 deletions js/modules/k6/execution/execution.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,15 +127,15 @@ func (mi *ModuleInstance) newScenarioInfo() (*sobek.Object, error) {
return newInfoObj(rt, si)
}

//nolint:lll,gochecknoglobals
var instanceInfoInitContextErr = common.NewInitContextError("getting instance information in the init context is not supported")
//nolint:lll
var errInstanceInfoInitContext = common.NewInitContextError("getting instance information in the init context is not supported")

// newInstanceInfo returns a sobek.Object with property accessors to retrieve
// information about the local instance stats.
func (mi *ModuleInstance) newInstanceInfo() (*sobek.Object, error) {
es := lib.GetExecutionState(mi.vu.Context())
if es == nil {
return nil, instanceInfoInitContextErr
return nil, errInstanceInfoInitContext
}
rt := mi.vu.Runtime()

Expand All @@ -160,8 +160,7 @@ func (mi *ModuleInstance) newInstanceInfo() (*sobek.Object, error) {
return newInfoObj(rt, ti)
}

//nolint:gochecknoglobals
var testInfoInitContextErr = common.NewInitContextError("getting test options in the init context is not supported")
var errTestInfoInitContext = common.NewInitContextError("getting test options in the init context is not supported")

// newTestInfo returns a sobek.Object with property accessors to retrieve
// information and control execution of the overall test run.
Expand All @@ -184,7 +183,7 @@ func (mi *ModuleInstance) newTestInfo() (*sobek.Object, error) {
"options": func() interface{} {
vuState := mi.vu.State()
if vuState == nil {
common.Throw(rt, testInfoInitContextErr)
common.Throw(rt, errTestInfoInitContext)
}
if optionsObject == nil {
opts, err := optionsAsObject(rt, vuState.Options)
Expand All @@ -200,15 +199,14 @@ func (mi *ModuleInstance) newTestInfo() (*sobek.Object, error) {
return newInfoObj(rt, ti)
}

//nolint:gochecknoglobals
var vuInfoInitContextErr = common.NewInitContextError("getting VU information in the init context is not supported")
var errVUInfoInitContex = common.NewInitContextError("getting VU information in the init context is not supported")

// newVUInfo returns a sobek.Object with property accessors to retrieve
// information about the currently executing VU.
func (mi *ModuleInstance) newVUInfo() (*sobek.Object, error) {
vuState := mi.vu.State()
if vuState == nil {
return nil, vuInfoInitContextErr
return nil, errVUInfoInitContex
}
rt := mi.vu.Runtime()

Expand Down
2 changes: 1 addition & 1 deletion js/modules/k6/grpc/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ func decryptPrivateKey(key, password []byte) ([]byte, error) {
being used here because it is deprecated due to it not supporting *good* cryptography
ultimately though we want to support something so we will be using it for now.
*/
decryptedKey, err := x509.DecryptPEMBlock(block, password)
decryptedKey, err := x509.DecryptPEMBlock(block, password) //nolint:staticcheck
if err != nil {
return nil, err
}
Expand Down
2 changes: 1 addition & 1 deletion js/modules/k6/timers/timers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ func TestSetTimeoutContextCancel(t *testing.T) {
for i := 0; i < 2000; i++ {
ctx, cancel := context.WithCancel(context.Background())
runtime.CancelContext = cancel
runtime.VU.CtxField = ctx
runtime.VU.CtxField = ctx //nolint:fatcontext
runtime.VU.RuntimeField.ClearInterrupt()
const interruptMsg = "definitely an interrupt"
go func() {
Expand Down
6 changes: 3 additions & 3 deletions js/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,8 @@ func (r *Runner) newVU(
tlsConfig := &tls.Config{
InsecureSkipVerify: r.Bundle.Options.InsecureSkipTLSVerify.Bool, //nolint:gosec
CipherSuites: cipherSuites,
MinVersion: uint16(tlsVersions.Min),
MaxVersion: uint16(tlsVersions.Max),
MinVersion: uint16(tlsVersions.Min), //nolint:gosec
MaxVersion: uint16(tlsVersions.Max), //nolint:gosec
Certificates: certs,
Renegotiation: tls.RenegotiateFreelyAsClient,
KeyLogWriter: r.preInitState.KeyLogger,
Expand All @@ -188,7 +188,7 @@ func (r *Runner) newVU(
"deprecation - https://pkg.go.dev/crypto/[email protected]#Config.",
)
})
tlsConfig.NameToCertificate = nameToCert
tlsConfig.NameToCertificate = nameToCert //nolint:staticcheck
}
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Expand Down
4 changes: 2 additions & 2 deletions js/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1204,7 +1204,7 @@ func TestVUIntegrationTLSConfig(t *testing.T) {
"",
},
"UnsupportedVersion": {
lib.Options{TLSVersion: &lib.TLSVersions{Min: tls.VersionSSL30, Max: tls.VersionSSL30}},
lib.Options{TLSVersion: &lib.TLSVersions{Min: tls.VersionSSL30, Max: tls.VersionSSL30}}, //nolint:staticcheck
unsupportedVersionErrorMsg,
},
}
Expand Down Expand Up @@ -2070,7 +2070,7 @@ func TestSystemTags(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

vu, err := r.NewVU(ctx, uint64(num), 0, samples)
vu, err := r.NewVU(ctx, uint64(num), 0, samples) //nolint:gosec
require.NoError(t, err)
activeVU := vu.Activate(&lib.VUActivationParams{
RunContext: ctx,
Expand Down
4 changes: 2 additions & 2 deletions lib/archive.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ func ReadArchive(in io.Reader) (*Archive, error) {
}
return nil, err
}
if hdr.Typeflag != tar.TypeReg && hdr.Typeflag != tar.TypeRegA {
if hdr.Typeflag != tar.TypeReg && hdr.Typeflag != tar.TypeRegA { //nolint:staticcheck
continue
}

Expand Down Expand Up @@ -166,7 +166,7 @@ func ReadArchive(in io.Reader) (*Archive, error) {
case "https", "file":
fileSystem := arc.getFs(pfx)
name = filepath.FromSlash(name)
if err = fsext.WriteFile(fileSystem, name, data, fs.FileMode(hdr.Mode)); err != nil {
if err = fsext.WriteFile(fileSystem, name, data, fs.FileMode(hdr.Mode)); err != nil { //nolint:gosec
return nil, err
}
if err = fileSystem.Chtimes(name, hdr.AccessTime, hdr.ModTime); err != nil {
Expand Down
4 changes: 2 additions & 2 deletions lib/execution.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ func NewExecutionState(
resumeNotify := make(chan struct{})
close(resumeNotify) // By default the ExecutionState starts unpaused

maxUnplannedUninitializedVUs := int64(maxPossibleVUs - maxPlannedVUs)
maxUnplannedUninitializedVUs := int64(maxPossibleVUs - maxPlannedVUs) //nolint:gosec

segIdx := NewSegmentedIndex(et)
return &ExecutionState{
Expand Down Expand Up @@ -240,7 +240,7 @@ func (es *ExecutionState) GetUniqueVUIdentifiers() (uint64, uint64) {
es.vuIDSegIndexMx.Lock()
defer es.vuIDSegIndexMx.Unlock()
scaled, unscaled := es.vuIDSegIndex.Next()
return uint64(scaled), uint64(unscaled)
return uint64(scaled), uint64(unscaled) //nolint:gosec
}

// GetInitializedVUsCount returns the total number of currently initialized VUs.
Expand Down
2 changes: 1 addition & 1 deletion lib/executor/base_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func (bs *BaseExecutor) nextIterationCounters() (uint64, uint64) {
bs.iterSegIndexMx.Lock()
defer bs.iterSegIndexMx.Unlock()
scaled, unscaled := bs.iterSegIndex.Next()
return uint64(scaled - 1), uint64(unscaled - 1)
return uint64(scaled - 1), uint64(unscaled - 1) //nolint:gosec
}

// Init doesn't do anything for most executors, since initialization of all
Expand Down
Loading

0 comments on commit 1d1afd0

Please sign in to comment.