From 392baf53cf6c3bf059f49d1132bdbe8902133d00 Mon Sep 17 00:00:00 2001 From: Daniel Adam Date: Thu, 4 Apr 2024 13:03:48 +0200 Subject: [PATCH 1/2] Update golangci-lint configuration and fix issues --- .golangci.yml | 25 ++++++++++++---------- bridge/resources/resource.go | 2 +- client/core/discover.go | 3 ++- client/core/getDevice_test.go | 11 +++++----- client/getDevice.go | 2 +- pkg/eventloop/eventloop_internal_test.go | 9 ++++---- pkg/security/generateCertificate/config.go | 2 +- pkg/security/signer/signer.go | 15 ++++++------- 8 files changed, 37 insertions(+), 32 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index c69976d2..05d872c0 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -20,9 +20,6 @@ linters-settings: # STxxxx checks in https://staticcheck.io/docs/configuration/options/#checks # Default: ["*"] checks: ["all", "-ST1000", "-ST1003"] - testifylint: - disable: - - go-require linters: enable: @@ -31,12 +28,13 @@ linters: - bidichk # Checks for dangerous unicode character sequences - bodyclose # Checks whether HTTP response body is closed successfully # - copyloopvar # Detects places where loop variables are copied - - decorder # check declaration order and count of types, constants, variables and functions + - decorder # Check declaration order and count of types, constants, variables and functions - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - dupl # Tool for code clone detection - - durationcheck # check for two durations multiplied together + - dupword # A linter that checks for duplicate words in the source code (usually miswritten) + - durationcheck # Check for two durations multiplied together - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases - - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted. + - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted. - errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. - execinquery # Execinquery is a linter about query string checker in Query function which reads your Go src files and warning it finds. @@ -68,12 +66,15 @@ linters: - loggercheck # Checks key value pairs for common logger libraries (kitlog,klog,logr,zap). - mirror # Reports wrong mirror patterns of bytes/strings usage - misspell # Finds commonly misspelled English words in comments + - nakedret # Finds naked returns in functions greater than a specified function length + - nestif # Reports deeply nested if statements - nilerr # Finds the code that returns nil even if it checks that the error is not nil. - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. - noctx # noctx finds sending http request without context.Context - nolintlint # Reports ill-formed or insufficient nolint directives - nosprintfhostport # Checks for misuse of Sprintf to construct a host with port in a URL - perfsprint # Checks that fmt.Sprintf can be replaced with a faster alternative. + - prealloc # Finds slice declarations that could potentially be preallocated - predeclared # find code that shadows one of Go's predeclared identifiers - protogetter # Reports direct reads from proto message fields when getters should be used. - revive # golint replacement, finds style mistakes @@ -114,18 +115,15 @@ linters: - maintidx # maintidx measures the maintainability index of each function. - makezero # Finds slice declarations with non-zero initial length - maligned # Tool to detect Go structs that would take less memory if their fields were sorted - - nakedret # Finds naked returns in functions greater than a specified function length - - nestif # Reports deeply nested if statements - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity - nonamedreturns # Reports all named returns - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test - - prealloc # Finds slice declarations that could potentially be preallocated - promlinter # Check Prometheus metrics naming via promlint - rowserrcheck # checks whether Err of rows is checked successfully - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. - - structcheck # Finds unused struct fields - tagalign # Check that struct tags are well aligned. - tagliatelle # Checks the struct tags. + - testableexamples # linter checks if examples are testable (have an expected output) - testpackage # linter that makes you use a separate _test package - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers - varnamelen # checks that the length of a variable's name matches its scope @@ -138,9 +136,10 @@ issues: # Allow complex tests, better to be self contained - path: _test\.go linters: + - dupword - forcetypeassert - gocognit - - gocyclo + - gocyclo # Allow complex main function and lower security in examples - path: cmd/ocfclient/main\.go @@ -149,6 +148,7 @@ issues: - goconst - gocyclo - gosec + - nestif - path: pkg/error text: "package name error has same name as predeclared identifier" @@ -161,3 +161,6 @@ issues: # Fix found issues (if it's supported by the linter). # fix: true + +run: + go: "1.20" diff --git a/bridge/resources/resource.go b/bridge/resources/resource.go index 85cbea48..8d90d65f 100644 --- a/bridge/resources/resource.go +++ b/bridge/resources/resource.go @@ -272,7 +272,7 @@ func (r *Resource) observerHandler(req *net.Request, createSubscription bool) (* } func (r *Resource) HandleRequest(req *net.Request) (*pool.Message, error) { - if req.Code() == codes.GET && r.getHandler != nil { + if req.Code() == codes.GET && r.getHandler != nil { //nolint:nestif var resp *pool.Message var err error if obs, errObs := req.Observe(); errObs == nil && r.createSubscription != nil && r.PolicyBitMask&schema.Observable != 0 { diff --git a/client/core/discover.go b/client/core/discover.go index 87348381..7af1bd5b 100644 --- a/client/core/discover.go +++ b/client/core/discover.go @@ -122,7 +122,8 @@ func DialDiscoveryAddresses(ctx context.Context, cfg DiscoveryConfiguration, err return nil, errors.New("context has not set deadline") } timeout := time.Until(v) - var out []*DiscoveryClient + + out := make([]*DiscoveryClient, 0, len(cfg.MulticastAddressUDP4)+len(cfg.MulticastAddressUDP6)) // We need to separate messageIDs for upd4 and udp6, because if any docker container has isolated network // iotivity-lite gets error EINVAL(22) for sendmsg with UDP6 for some interfaces. If it happens, the device is diff --git a/client/core/getDevice_test.go b/client/core/getDevice_test.go index 9cb35229..7f56d2b8 100644 --- a/client/core/getDevice_test.go +++ b/client/core/getDevice_test.go @@ -26,6 +26,7 @@ import ( "github.com/plgd-dev/device/v2/client/core/otm" "github.com/plgd-dev/device/v2/schema/platform" "github.com/plgd-dev/device/v2/test" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -75,15 +76,15 @@ func TestClientGetDeviceParallel(t *testing.T) { go func() { defer wg.Done() got, err := c.GetDeviceByIP(ctx, ip) - require.NoError(t, err) - require.NotEmpty(t, got) + assert.NoError(t, err) + assert.NotEmpty(t, got) links, err := got.GetResourceLinks(ctx, got.GetEndpoints()) - require.NoError(t, err) + assert.NoError(t, err) link, ok := links.GetResourceLink(platform.ResourceURI) - require.True(t, ok) + assert.True(t, ok) var v interface{} err = got.GetResource(ctx, link, &v) - require.NoError(t, err) + assert.NoError(t, err) }() } wg.Wait() diff --git a/client/getDevice.go b/client/getDevice.go index 63f153c0..0573d068 100644 --- a/client/getDevice.go +++ b/client/getDevice.go @@ -119,7 +119,7 @@ func (c *Client) getDeviceByIPWithUpdateCache(ctx context.Context, ip string, ex if err != nil { return nil, err } - var devs []*core.Device + devs := make([]*core.Device, 0, len(newDevices)) oldDevs := make(map[string]*core.Device) if expectedDeviceID != "" { d, ok := c.deviceCache.GetDevice(expectedDeviceID) diff --git a/pkg/eventloop/eventloop_internal_test.go b/pkg/eventloop/eventloop_internal_test.go index 197e4204..7a4b76ac 100644 --- a/pkg/eventloop/eventloop_internal_test.go +++ b/pkg/eventloop/eventloop_internal_test.go @@ -5,6 +5,7 @@ import ( "sync" "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -67,7 +68,7 @@ func TestEventLoopAddThreadSafety(t *testing.T) { startedCh := make(chan struct{}) wg.Add(1) loop.Add(NewReadHandler(reflect.ValueOf(startedCh), func(_ reflect.Value, closed bool) { - require.True(t, closed, "Channel should be closed") + assert.True(t, closed, "Channel should be closed") wg.Done() })) close(startedCh) @@ -79,7 +80,7 @@ func TestEventLoopAddThreadSafety(t *testing.T) { ch := make(chan struct{}) loop.Add(NewReadHandler(reflect.ValueOf(ch), func(_ reflect.Value, closed bool) { // Simulate task processing - require.True(t, closed, "Channel should be closed") + assert.True(t, closed, "Channel should be closed") wg.Done() })) close(ch) @@ -105,7 +106,7 @@ func TestEventLoopRemoveThreadSafety(t *testing.T) { startedCh := make(chan struct{}) wg.Add(1) loop.Add(NewReadHandler(reflect.ValueOf(startedCh), func(_ reflect.Value, closed bool) { - require.True(t, closed, "Channel should be closed") + assert.True(t, closed, "Channel should be closed") wg.Done() })) close(startedCh) @@ -118,7 +119,7 @@ func TestEventLoopRemoveThreadSafety(t *testing.T) { // Simulate adding a task ch := make(chan struct{}) loop.Add(NewReadHandler(reflect.ValueOf(ch), func(reflect.Value, bool) { - require.Fail(t, "Task should not be processed") + assert.Fail(t, "Task should not be processed") })) go func() { defer wg.Done() diff --git a/pkg/security/generateCertificate/config.go b/pkg/security/generateCertificate/config.go index c3a7d2fe..1aacdf29 100644 --- a/pkg/security/generateCertificate/config.go +++ b/pkg/security/generateCertificate/config.go @@ -293,7 +293,7 @@ func (cfg Configuration) AsnExtensionKeyUsages() ([]asn1.ObjectIdentifier, error } func (cfg Configuration) ToIPAddresses() ([]net.IP, error) { - var ips []net.IP + ips := make([]net.IP, 0, len(cfg.SubjectAlternativeName.IPAddresses)) for _, ip := range cfg.SubjectAlternativeName.IPAddresses { v := net.ParseIP(ip) if v == nil { diff --git a/pkg/security/signer/signer.go b/pkg/security/signer/signer.go index ed18471a..2479b94f 100644 --- a/pkg/security/signer/signer.go +++ b/pkg/security/signer/signer.go @@ -43,7 +43,7 @@ func NewOCFIdentityCertificate(caCert []*x509.Certificate, caKey crypto.PrivateK return &OCFIdentityCertificate{caCert: caCert, caKey: caKey, validNotBefore: validNotBefore, validNotAfter: validNotAfter} } -func (s *OCFIdentityCertificate) Sign(_ context.Context, csr []byte) (signedCsr []byte, err error) { +func (s *OCFIdentityCertificate) Sign(_ context.Context, csr []byte) ([]byte, error) { now := time.Now() notBefore := s.validNotBefore notAfter := s.validNotAfter @@ -67,24 +67,23 @@ func (s *OCFIdentityCertificate) Sign(_ context.Context, csr []byte) (signedCsr csrBlock, _ := pem.Decode(csr) if csrBlock == nil { - err = errors.New("pem not found") - return + return nil, errors.New("pem not found") } certificateRequest, err := x509.ParseCertificateRequest(csrBlock.Bytes) if err != nil { - return + return nil, err } err = certificateRequest.CheckSignature() if err != nil { - return + return nil, err } serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { - return + return nil, err } template := x509.Certificate{ @@ -102,9 +101,9 @@ func (s *OCFIdentityCertificate) Sign(_ context.Context, csr []byte) (signedCsr if len(s.caCert) == 0 { return nil, errors.New("cannot sign with empty signer CA certificates") } - signedCsr, err = x509.CreateCertificate(rand.Reader, &template, s.caCert[0], certificateRequest.PublicKey, s.caKey) + signedCsr, err := x509.CreateCertificate(rand.Reader, &template, s.caCert[0], certificateRequest.PublicKey, s.caKey) if err != nil { - return + return nil, err } return pkgX509.CreatePemChain(s.caCert, signedCsr) } From ab27cfe08cab386b628274c1141d41ace38a9f12 Mon Sep 17 00:00:00 2001 From: Daniel Adam Date: Thu, 4 Apr 2024 13:06:43 +0200 Subject: [PATCH 2/2] Upgrade dependencies Direct: github.com/plgd-dev/go-coap/v3 v3.3.4-0.20240404104253-8d54d1cdfc79 google.golang.org/grpc v1.63.0 Indirect: golang.org/x/net v0.23.0 --- go.mod | 7 +++---- go.sum | 13 ++++++------- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/go.mod b/go.mod index 8e5cd2fb..0420bbf1 100644 --- a/go.mod +++ b/go.mod @@ -12,20 +12,19 @@ require ( github.com/karrick/tparse/v2 v2.8.2 github.com/pion/dtls/v2 v2.2.8-0.20240327211025-8244c4570c01 github.com/pion/logging v0.2.2 - github.com/plgd-dev/go-coap/v3 v3.3.4-0.20240403064319-6ed2ef2c4664 + github.com/plgd-dev/go-coap/v3 v3.3.4-0.20240404104253-8d54d1cdfc79 github.com/plgd-dev/kit/v2 v2.0.0-20211006190727-057b33161b90 github.com/stretchr/testify v1.9.0 github.com/ugorji/go/codec v1.2.12 go.uber.org/atomic v1.11.0 golang.org/x/sync v0.6.0 - google.golang.org/grpc v1.62.1 + google.golang.org/grpc v1.63.0 gopkg.in/yaml.v3 v3.0.1 ) require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/dsnet/golib/memfile v1.0.0 // indirect - github.com/golang/protobuf v1.5.4 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/kr/text v0.2.0 // indirect github.com/pion/transport/v3 v3.0.2 // indirect @@ -33,7 +32,7 @@ require ( github.com/x448/float16 v0.8.4 // indirect golang.org/x/crypto v0.21.0 // indirect golang.org/x/exp v0.0.0-20240325151524-a685a6edb6d8 // indirect - golang.org/x/net v0.22.0 // indirect + golang.org/x/net v0.23.0 // indirect golang.org/x/sys v0.18.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20240401170217-c3f982113cda // indirect google.golang.org/protobuf v1.33.0 // indirect diff --git a/go.sum b/go.sum index 89fc64c8..3cfca72e 100644 --- a/go.sum +++ b/go.sum @@ -44,8 +44,6 @@ github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrU github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= -github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= -github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= @@ -98,8 +96,8 @@ github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/plgd-dev/go-coap/v2 v2.0.4-0.20200819112225-8eb712b901bc/go.mod h1:+tCi9Q78H/orWRtpVWyBgrr4vKFo2zYtbbxUllerBp4= github.com/plgd-dev/go-coap/v2 v2.4.1-0.20210517130748-95c37ac8e1fa/go.mod h1:rA7fc7ar+B/qa+Q0hRqv7yj/EMtIlmo1l7vkQGSrHPU= -github.com/plgd-dev/go-coap/v3 v3.3.4-0.20240403064319-6ed2ef2c4664 h1:iMMYyd666v1oHmR642hYFoRgRyrN/qMoCoY0X/Cj6RE= -github.com/plgd-dev/go-coap/v3 v3.3.4-0.20240403064319-6ed2ef2c4664/go.mod h1:flkLrn0JqGJyW25Uybwg0g0PZUt+pZ1O7aaPeIhEEbs= +github.com/plgd-dev/go-coap/v3 v3.3.4-0.20240404104253-8d54d1cdfc79 h1:Kaf/67M7+UVsRbNHQx3DDOLzpDI6RE/oYZz2v+a4csg= +github.com/plgd-dev/go-coap/v3 v3.3.4-0.20240404104253-8d54d1cdfc79/go.mod h1:UKObEIXVvPfdNGv7QoKegxPwT12UBy26tNUEOebFkls= github.com/plgd-dev/kit v0.0.0-20200819113605-d5fcf3e94f63/go.mod h1:Yl9zisyXfPdtP9hTWlJqjJYXmgU/jtSDKttz9/CeD90= github.com/plgd-dev/kit/v2 v2.0.0-20211006190727-057b33161b90 h1:TC1HJ/UbyflJFPvaOdGmNZ5TeFGex1/dyr9urNGLy7M= github.com/plgd-dev/kit/v2 v2.0.0-20211006190727-057b33161b90/go.mod h1:Z7oKFLSGQjdi8eInxwFCs0tSApuEM1o0qNck+sJYp4M= @@ -182,8 +180,9 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= -golang.org/x/net v0.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc= golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= +golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs= +golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -257,8 +256,8 @@ google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyac google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= -google.golang.org/grpc v1.62.1 h1:B4n+nfKzOICUXMgyrNd19h/I9oH0L1pizfk1d4zSgTk= -google.golang.org/grpc v1.62.1/go.mod h1:IWTG0VlJLCh1SkC58F7np9ka9mx/WNkjl4PGJaiq+QE= +google.golang.org/grpc v1.63.0 h1:WjKe+dnvABXyPJMD7KDNLxtoGk5tgk+YFWN6cBWjZE8= +google.golang.org/grpc v1.63.0/go.mod h1:WAX/8DgncnokcFUldAxq7GeB5DXHDbMF+lLvDomNkRA= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=