Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(security): Enable gosec and default linter set #1076

Merged
merged 1 commit into from
Jan 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
linters:
disable:
enable:
- gosec
10 changes: 8 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
.PHONY: build test clean docker
.PHONY: build test clean docker unittest lint

GO=CGO_ENABLED=0 GO111MODULE=on go
GOCGO=CGO_ENABLED=1 GO111MODULE=on go
Expand Down Expand Up @@ -31,8 +31,14 @@ docker:
-t edgexfoundry/device-simple:$(DOCKER_TAG) \
.

test:
unittest:
GO111MODULE=on go test $(GOTESTFLAGS) -coverprofile=coverage.out ./...

lint:
@which golangci-lint >/dev/null || echo "WARNING: go linter not installed. To install, run\n curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b \$$(go env GOPATH)/bin v1.42.1"
@if [ "z${ARCH}" = "zx86_64" ] && which golangci-lint >/dev/null ; then golangci-lint run --config .golangci.yml ; else echo "WARNING: Linting skipped (not on x86_64 or linter not installed)"; fi

test: unittest lint
GO111MODULE=on go vet ./...
gofmt -l $$(find . -type f -name '*.go'| grep -v "/vendor/")
[ "`gofmt -l $$(find . -type f -name '*.go'| grep -v "/vendor/")`" = "" ]
Expand Down
7 changes: 5 additions & 2 deletions example/driver/simpledriver.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,10 @@ func getImageBytes(imgFile string, buf *bytes.Buffer) error {
return err
}
// Finished with file. Reset file pointer
img.Seek(0, 0)
_, err = img.Seek(0, 0)
if err != nil {
return err
}
if imageType == "jpeg" {
err = jpeg.Encode(buf, imageData, nil)
if err != nil {
Expand Down Expand Up @@ -158,7 +161,7 @@ func (s *SimpleDriver) HandleReadCommands(deviceName string, protocols map[strin
} else if reqs[0].DeviceResourceName == "Image" {
// Show a binary/image representation of the switch's on/off value
buf := new(bytes.Buffer)
if s.switchButton == true {
if s.switchButton {
err = getImageBytes(s.serviceConfig.SimpleCustom.OnImageLocation, buf)
} else {
err = getImageBytes(s.serviceConfig.SimpleCustom.OffImageLocation, buf)
Expand Down
4 changes: 2 additions & 2 deletions internal/autodiscovery/autodiscovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func BootstrapHandler(
configuration := container.ConfigurationFrom(dic.Get)
var runDiscovery bool = true

if configuration.Device.Discovery.Enabled == false {
if !configuration.Device.Discovery.Enabled {
lc.Info("AutoDiscovery stopped: disabled by configuration")
runDiscovery = false
}
Expand All @@ -44,8 +44,8 @@ func BootstrapHandler(
}

if runDiscovery {
wg.Add(1)
go func() {
wg.Add(1)
defer wg.Done()

lc.Info(fmt.Sprintf("Starting auto-discovery with duration %v", duration))
Expand Down
3 changes: 1 addition & 2 deletions internal/autodiscovery/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
package autodiscovery

import (
"fmt"
"sync"

"github.com/edgexfoundry/go-mod-core-contracts/v2/clients/logger"
Expand All @@ -32,7 +31,7 @@ func DiscoveryWrapper(discovery models.ProtocolDiscovery, lc logger.LoggingClien
locker.busy = true
locker.mux.Unlock()

lc.Debug(fmt.Sprintf("protocol discovery triggered"))
lc.Debug("protocol discovery triggered")
discovery.Discover()

// ReleaseLock
Expand Down
4 changes: 2 additions & 2 deletions internal/autoevent/executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,12 @@ func TestCompareReadings(t *testing.T) {
readingsLengthChanged[2].ValueType = common.ValueTypeBinary
readingsLengthChanged[2].ResourceName = "b1"
readingsLengthChanged[2].BinaryValue = make([]byte, 1000)
rand.Read(readingsLengthChanged[2].BinaryValue)
rand.Read(readingsLengthChanged[2].BinaryValue) // nolint: gosec

readingsBinaryValueChanged := make([]dtos.BaseReading, len(readingsLengthChanged))
copy(readingsBinaryValueChanged, readingsLengthChanged)
readingsBinaryValueChanged[2].BinaryValue = make([]byte, 1000)
rand.Read(readingsBinaryValueChanged[2].BinaryValue)
rand.Read(readingsBinaryValueChanged[2].BinaryValue) // nolint: gosec

readingBinaryValueUnchanged := readingsBinaryValueChanged

Expand Down
4 changes: 2 additions & 2 deletions internal/clients/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func InitDependencyClients(ctx context.Context, wg *sync.WaitGroup, startupTimer
return false
}

if checkDependencyServices(ctx, startupTimer, dic) == false {
if !checkDependencyServices(ctx, startupTimer, dic) {
return false
}
initCoreServiceClients(dic)
Expand Down Expand Up @@ -90,7 +90,7 @@ func checkDependencyServices(ctx context.Context, startupTimer startup.Timer, di
for i := 0; i < dependencyCount; i++ {
go func(wg *sync.WaitGroup, serviceKey string) {
defer wg.Done()
if checkServiceAvailable(ctx, serviceKey, startupTimer, dic) == false {
if !checkServiceAvailable(ctx, serviceKey, startupTimer, dic) {
checkingErr = false
}
}(&waitGroup, dependencyList[i])
Expand Down
4 changes: 2 additions & 2 deletions internal/common/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func UpdateOperatingState(name string, state string, lc logger.LoggingClient, dc
func SendEvent(event *dtos.Event, correlationID string, dic *di.Container) {
lc := bootstrapContainer.LoggingClientFrom(dic.Get)
configuration := container.ConfigurationFrom(dic.Get)
ctx := context.WithValue(context.Background(), common.CorrelationHeader, correlationID)
ctx := context.WithValue(context.Background(), common.CorrelationHeader, correlationID) // nolint: staticcheck
req := requests.NewAddEventRequest(*event)

if configuration.Device.UseMessageBus {
Expand All @@ -63,7 +63,7 @@ func SendEvent(event *dtos.Event, correlationID string, dic *di.Container) {
if err != nil {
lc.Error(err.Error())
}
ctx = context.WithValue(ctx, common.ContentType, encoding)
ctx = context.WithValue(ctx, common.ContentType, encoding) // nolint: staticcheck
envelope := types.NewMessageEnvelope(bytes, ctx)
publishTopic := fmt.Sprintf("%s/%s/%s/%s", configuration.MessageQueue.PublishTopicPrefix, event.ProfileName, event.DeviceName, event.SourceName)
err = mc.Publish(envelope, publishTopic)
Expand Down
4 changes: 2 additions & 2 deletions internal/controller/http/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -288,8 +288,8 @@ func doRequest(t *testing.T, method string, api string, handler http.HandlerFunc
}

assert.Equal(t, expectedStatusCode, recorder.Code, "Wrong status code")
assert.Equal(t, common.ContentTypeJSON, recorder.HeaderMap.Get(common.ContentType), "Content type not set or not JSON")
assert.Equal(t, expectedCorrelationId, recorder.HeaderMap.Get(common.CorrelationHeader), "CorrelationHeader not as expected")
assert.Equal(t, common.ContentTypeJSON, recorder.Header().Get(common.ContentType), "Content type not set or not JSON")
assert.Equal(t, expectedCorrelationId, recorder.Header().Get(common.CorrelationHeader), "CorrelationHeader not as expected")

require.NotEmpty(t, recorder.Body.String(), "Response body is empty")

Expand Down
2 changes: 1 addition & 1 deletion internal/controller/http/correlation/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func ManageHeader(next http.Handler) http.Handler {
if hdr == "" {
hdr = uuid.New().String()
}
ctx := context.WithValue(r.Context(), common.CorrelationHeader, hdr)
ctx := context.WithValue(r.Context(), common.CorrelationHeader, hdr) // nolint:staticcheck
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
Expand Down
12 changes: 5 additions & 7 deletions internal/messaging/messaging.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import (
func BootstrapHandler(ctx context.Context, wg *sync.WaitGroup, startupTimer startup.Timer, dic *di.Container) bool {
lc := bootstrapContainer.LoggingClientFrom(dic.Get)
config := container.ConfigurationFrom(dic.Get)
if config.Device.UseMessageBus == false {
if !config.Device.UseMessageBus {
lc.Info("Use of MessageBus disabled, skipping creation of messaging client")
return true
}
Expand Down Expand Up @@ -81,13 +81,11 @@ func BootstrapHandler(ctx context.Context, wg *sync.WaitGroup, startupTimer star
wg.Add(1)
go func() {
defer wg.Done()
select {
case <-ctx.Done():
if msgClient != nil {
_ = msgClient.Disconnect()
}
lc.Infof("Disconnected from MessageBus")
<-ctx.Done()
if msgClient != nil {
_ = msgClient.Disconnect()
}
lc.Infof("Disconnected from MessageBus")
}()

dic.Update(di.ServiceConstructorMap{
Expand Down
2 changes: 1 addition & 1 deletion internal/provision/devices.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ func LoadDevices(path string, dic *di.Container) errors.EdgeX {
return nil
}
dc := bootstrapContainer.MetadataDeviceClientFrom(dic.Get)
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString())
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString()) //nolint: staticcheck
_, edgexErr := dc.Add(ctx, addDevicesReq)
return edgexErr
}
2 changes: 1 addition & 1 deletion internal/provision/profiles.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func LoadProfiles(path string, dic *di.Container) errors.EdgeX {
if len(addProfilesReq) == 0 {
return nil
}
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString())
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString()) // nolint:staticcheck
_, edgexErr := dpc.Add(ctx, addProfilesReq)
return edgexErr
}
1 change: 0 additions & 1 deletion internal/telemetry/telemetry.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ type CpuUsage struct {
Total uint64 // reported sum total of all usage
}

var once sync.Once
var lastSample CpuUsage
var usageAvg float64

Expand Down
1 change: 1 addition & 0 deletions internal/transformer/transform_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
)

func Test_getUniqueOrigin(t *testing.T) {
// nolint: gosec
for i := 0; i < rand.Intn(1000); i++ {
t.Run(fmt.Sprintf("TestCase%d", i), func(t *testing.T) {
t.Parallel()
Expand Down
3 changes: 3 additions & 0 deletions internal/transformer/transformparam.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ func TransformWriteParameter(cv *dsModels.CommandValue, pv models.ResourceProper
}

value, err := commandValueForTransform(cv)
if err != nil {
return errors.NewCommonEdgeXWrapper(err)
}
newValue := value

if pv.Maximum != "" {
Expand Down
3 changes: 3 additions & 0 deletions internal/transformer/transformresult.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ func TransformReadResult(cv *sdkModels.CommandValue, pv models.ResourcePropertie
}

value, err := commandValueForTransform(cv)
if err != nil {
return errors.NewCommonEdgeXWrapper(err)
}
newValue := value

if pv.Mask != "" && pv.Mask != defaultMask &&
Expand Down
2 changes: 1 addition & 1 deletion pkg/models/commandvalue.go
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,7 @@ func validate(valueType string, value interface{}) error {
return errors.NewCommonEdgeX(errors.KindServerError, errMsg, nil)
}
case common.ValueTypeObject:
_, ok = value.(interface{})
_, ok = value.(interface{}) // nolint: gosimple
default:
return errors.NewCommonEdgeX(errors.KindServerError, "unrecognized value type", nil)
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/models/commandvalue_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func TestNewCommandValueWithOrigin(t *testing.T) {

func Test_validate(t *testing.T) {
exceedBinary := make([]byte, MaxBinaryBytes+1)
rand.Read(exceedBinary)
rand.Read(exceedBinary) // nolint: gosec
tests := []struct {
name string
valueType string
Expand Down Expand Up @@ -74,7 +74,7 @@ func TestCommandValue_ValueToString(t *testing.T) {
boolCommandValue, err := NewCommandValue("test-resource", common.ValueTypeBool, true)
require.NoError(t, err)
binaryValue := make([]byte, 100)
rand.Read(binaryValue)
rand.Read(binaryValue) // nolint: gosec
binaryCommandValue, err := NewCommandValue("test-resource", common.ValueTypeBinary, binaryValue)
require.NoError(t, err)
stringArrayValue := []string{"foo", "bar"}
Expand Down
8 changes: 4 additions & 4 deletions pkg/service/manageddevices.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func (s *DeviceService) AddDevice(device models.Device) (string, error) {

s.LoggingClient.Debugf("Adding managed Device %s", device.Name)
req := requests.NewAddDeviceRequest(dtos.FromDeviceModelToDTO(device))
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString())
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString()) // nolint:staticcheck
res, err := s.edgexClients.DeviceClient.Add(ctx, []requests.AddDeviceRequest{req})
if err != nil {
s.LoggingClient.Errorf("failed to add Device %s to Core Metadata: %v", device.Name, err)
Expand Down Expand Up @@ -83,7 +83,7 @@ func (s *DeviceService) RemoveDeviceByName(name string) error {
}

s.LoggingClient.Debugf("Removing managed Device %s", device.Name)
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString())
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString()) // nolint:staticcheck
_, err := s.edgexClients.DeviceClient.DeleteDeviceByName(ctx, name)
if err != nil {
s.LoggingClient.Errorf("failed to delete Device %s in Core Metadata", name)
Expand All @@ -105,7 +105,7 @@ func (s *DeviceService) UpdateDevice(device models.Device) error {
s.LoggingClient.Debugf("Updating managed Device %s", device.Name)
req := requests.NewUpdateDeviceRequest(dtos.FromDeviceModelToUpdateDTO(device))
req.Device.Id = nil
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString())
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString()) // nolint:staticcheck
_, err := s.edgexClients.DeviceClient.Update(ctx, []requests.UpdateDeviceRequest{req})
if err != nil {
s.LoggingClient.Errorf("failed to update Device %s in Core Metadata: %v", device.Name, err)
Expand All @@ -132,7 +132,7 @@ func (s *DeviceService) UpdateDeviceOperatingState(deviceName string, state stri
OperatingState: &state,
},
}
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString())
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString()) // nolint:staticcheck
_, err := s.edgexClients.DeviceClient.Update(ctx, []requests.UpdateDeviceRequest{req})
if err != nil {
s.LoggingClient.Errorf("failed to update Device %s OperatingState in Core Metadata: %v", d.Name, err)
Expand Down
6 changes: 3 additions & 3 deletions pkg/service/managedprofiles.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func (s *DeviceService) AddDeviceProfile(profile models.DeviceProfile) (string,

s.LoggingClient.Debugf("Adding managed Profile %s", profile.Name)
req := requests.NewDeviceProfileRequest(dtos.FromDeviceProfileModelToDTO(profile))
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString())
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString()) // nolint:staticcheck
res, err := s.edgexClients.DeviceProfileClient.Add(ctx, []requests.DeviceProfileRequest{req})
if err != nil {
s.LoggingClient.Errorf("failed to add Profile %s to Core Metadata: %v", profile.Name, err)
Expand Down Expand Up @@ -72,7 +72,7 @@ func (s *DeviceService) RemoveDeviceProfileByName(name string) error {
}

s.LoggingClient.Debugf("Removing managed Profile %s", profile.Name)
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString())
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString()) // nolint:staticcheck
_, err := s.edgexClients.DeviceProfileClient.DeleteByName(ctx, name)
if err != nil {
s.LoggingClient.Errorf("failed to delete Profile %s in Core Metadata", name)
Expand All @@ -95,7 +95,7 @@ func (s *DeviceService) UpdateDeviceProfile(profile models.DeviceProfile) error

s.LoggingClient.Debugf("Updating managed Profile %s", profile.Name)
req := requests.NewDeviceProfileRequest(dtos.FromDeviceProfileModelToDTO(profile))
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString())
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString()) // nolint:staticcheck
_, err := s.edgexClients.DeviceProfileClient.Update(ctx, []requests.DeviceProfileRequest{req})
if err != nil {
s.LoggingClient.Errorf("failed to update Profile %s in Core Metadata: %v", profile.Name, err)
Expand Down
6 changes: 3 additions & 3 deletions pkg/service/managedwatchers.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func (s *DeviceService) AddProvisionWatcher(watcher models.ProvisionWatcher) (st

s.LoggingClient.Debugf("Adding managed ProvisionWatcher %s", watcher.Name)
req := requests.NewAddProvisionWatcherRequest(dtos.FromProvisionWatcherModelToDTO(watcher))
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString())
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString()) // nolint:staticcheck
res, err := s.edgexClients.ProvisionWatcherClient.Add(ctx, []requests.AddProvisionWatcherRequest{req})
if err != nil {
s.LoggingClient.Errorf("failed to add ProvisionWatcher to Core Metadata: %v", watcher.Name, err)
Expand Down Expand Up @@ -82,7 +82,7 @@ func (s *DeviceService) RemoveProvisionWatcher(name string) error {
}

s.LoggingClient.Debugf("Removing managed ProvisionWatcher: %s", pw.Name)
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString())
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString()) // nolint:staticcheck
_, err := s.edgexClients.ProvisionWatcherClient.DeleteProvisionWatcherByName(ctx, name)
if err != nil {
s.LoggingClient.Errorf("failed to delete ProvisionWatcher %s in Core Metadata", name)
Expand All @@ -105,7 +105,7 @@ func (s *DeviceService) UpdateProvisionWatcher(watcher models.ProvisionWatcher)
s.LoggingClient.Debugf("Updating managed ProvisionWatcher: %s", watcher.Name)
req := requests.NewUpdateProvisionWatcherRequest(dtos.FromProvisionWatcherModelToUpdateDTO(watcher))
req.ProvisionWatcher.Id = nil
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString())
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString()) // nolint:staticcheck
_, err := s.edgexClients.ProvisionWatcherClient.Update(ctx, []requests.UpdateProvisionWatcherRequest{req})
if err != nil {
s.LoggingClient.Errorf("failed to update ProvisionWatcher %s in Core Metadata: %v", watcher.Name, err)
Expand Down
2 changes: 1 addition & 1 deletion pkg/service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ func (s *DeviceService) selfRegister() errors.EdgeX {
AdminState: models.Unlocked,
}
*s.deviceService = localDeviceService
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString())
ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.NewString()) // nolint:staticcheck

s.LoggingClient.Debugf("trying to find device service %s", localDeviceService.Name)
res, err := s.edgexClients.DeviceServiceClient.DeviceServiceByName(ctx, localDeviceService.Name)
Expand Down