Skip to content

Commit

Permalink
feat: enable gosec and default linter set (#353)
Browse files Browse the repository at this point in the history
* feat: enable gosec and default linter set

fixes: #352

Signed-off-by: jpwhitemn <[email protected]>
  • Loading branch information
jpwhitemn authored Apr 5, 2022
1 parent a7b844b commit 6a0d17f
Show file tree
Hide file tree
Showing 7 changed files with 55 additions and 28 deletions.
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
15 changes: 12 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
.PHONY: build test clean prepare update docker
.PHONY: build test unittest lint clean prepare update docker

GO=CGO_ENABLED=0 GO111MODULE=on go
GOCGO=GCO_ENABLED=1 GO111MODULE=on go

MICROSERVICES=cmd/device-mqtt

ARCH=$(shell uname -m)

.PHONY: $(MICROSERVICES)

DOCKERS=docker_device_mqtt_go
Expand All @@ -24,8 +26,15 @@ build: $(MICROSERVICES)
cmd/device-mqtt:
$(GOCGO) build $(GOFLAGS) -o $@ ./cmd

test:
$(GOCGO) test ./... -coverprofile=coverage.out
unittest:
$(GOCGO) test ./... -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
$(GOCGO) vet ./...
gofmt -l $$(find . -type f -name '*.go'| grep -v "/vendor/")
[ "`gofmt -l $$(find . -type f -name '*.go'| grep -v "/vendor/")`" = "" ]
Expand Down
9 changes: 7 additions & 2 deletions internal/driver/driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (
"github.com/edgexfoundry/go-mod-core-contracts/v2/errors"
"github.com/edgexfoundry/go-mod-core-contracts/v2/models"

"github.com/eclipse/paho.mqtt.golang"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/google/uuid"
"github.com/spf13/cast"
)
Expand Down Expand Up @@ -150,7 +150,12 @@ func (d *Driver) handleReadCommandRequest(req sdkModel.CommandRequest, topic str
driver.Logger.Debugf("Parse command response: %v", cmdResponse)

var response map[string]interface{}
json.Unmarshal([]byte(cmdResponse), &response)
err = json.Unmarshal([]byte(cmdResponse), &response)
if err != nil {
driver.Logger.Errorf("Error unmarshaling response: %s", err)
return nil, errors.NewCommonEdgeX(errors.KindIOError, "Error umarshaling the response", err)
}

reading, ok := response[cmd]
if !ok {
return nil, errors.NewCommonEdgeX(errors.KindContractInvalid, fmt.Sprintf("'%s' field not found in the response %s", cmd, cmdResponse), nil)
Expand Down
9 changes: 6 additions & 3 deletions internal/driver/incominglistener.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
"github.com/edgexfoundry/device-sdk-go/v2/pkg/models"
"github.com/edgexfoundry/device-sdk-go/v2/pkg/service"

"github.com/eclipse/paho.mqtt.golang"
mqtt "github.com/eclipse/paho.mqtt.golang"
)

const (
Expand Down Expand Up @@ -42,8 +42,11 @@ func (d *Driver) onIncomingDataReceived(client mqtt.Client, message mqtt.Message
reading = string(message.Payload())
} else {
var data map[string]interface{}
json.Unmarshal(message.Payload(), &data)

err := json.Unmarshal(message.Payload(), &data)
if err != nil {
driver.Logger.Errorf("Error unmarshaling payload: %s", err)
return
}
nameVal, ok := data[name]
if !ok {
driver.Logger.Errorf("[Incoming listener] Incoming reading ignored, reading data `%v` should contain the field `%s` to indicate the device name", data, name)
Expand Down
12 changes: 5 additions & 7 deletions internal/driver/readingchecker.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,20 +45,20 @@ func checkUintValueRange(valueType string, val uint64) bool {
var isValid = false
switch valueType {
case common.ValueTypeUint8:
if val >= 0 && val <= math.MaxUint8 {
if val <= math.MaxUint8 {
isValid = true
}
case common.ValueTypeUint16:
if val >= 0 && val <= math.MaxUint16 {
if val <= math.MaxUint16 {
isValid = true
}
case common.ValueTypeUint32:
if val >= 0 && val <= math.MaxUint32 {
if val <= math.MaxUint32 {
isValid = true
}
case common.ValueTypeUint64:
maxiMum := uint64(math.MaxUint64)
if val >= 0 && val <= maxiMum {
if val <= maxiMum {
isValid = true
}
}
Expand All @@ -81,9 +81,7 @@ func checkIntValueRange(valueType string, val int64) bool {
isValid = true
}
case common.ValueTypeInt64:
if val >= math.MinInt64 && val <= math.MaxInt64 {
isValid = true
}
isValid = true
}
return isValid
}
Expand Down
8 changes: 6 additions & 2 deletions internal/driver/responselistener.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"encoding/json"
"strings"

"github.com/eclipse/paho.mqtt.golang"
mqtt "github.com/eclipse/paho.mqtt.golang"
)

func (d *Driver) onCommandResponseReceived(client mqtt.Client, message mqtt.Message) {
Expand All @@ -30,7 +30,11 @@ func (d *Driver) onCommandResponseReceived(client mqtt.Client, message mqtt.Mess
var response map[string]interface{}
var ok bool

json.Unmarshal(message.Payload(), &response)
err := json.Unmarshal(message.Payload(), &response)
if err != nil {
driver.Logger.Errorf("Error unmarshaling payload: %s", err)
return
}
uuid, ok = response["uuid"].(string)
if !ok {
driver.Logger.Errorf("[Response listener] Command response ignored. No UUID found in the message: topic=%v msg=%v", message.Topic(), string(message.Payload()))
Expand Down
26 changes: 15 additions & 11 deletions mock/device.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
"net/url"
"time"

"github.com/eclipse/paho.mqtt.golang"
mqtt "github.com/eclipse/paho.mqtt.golang"
)

const (
Expand Down Expand Up @@ -91,14 +91,14 @@ func runDataSender() {
data["method"] = "get"

for {
data["randnum"] = rand.Float64()
data["randnum"] = rand.Float64() //nolint:gosec
jsonData, err := json.Marshal(data)
if err != nil {
fmt.Println(err)
}
client.Publish(topic, qos, false, jsonData)

fmt.Println(fmt.Sprintf("Send response: %v", string(jsonData)))
fmt.Printf("Send response: %v", string(jsonData))

time.Sleep(time.Second * time.Duration(30))
}
Expand All @@ -108,7 +108,11 @@ func runDataSender() {
func onCommandReceivedFromBroker(client mqtt.Client, message mqtt.Message) {
var request map[string]interface{}

json.Unmarshal(message.Payload(), &request)
err := json.Unmarshal(message.Payload(), &request)
if err != nil {
log.Println(fmt.Sprintf("Error unmarshaling payload: %s", err))
return
}
uuid, ok := request["uuid"]
if ok {
log.Println(fmt.Sprintf("Command response received: topic=%v uuid=%v msg=%v", message.Topic(), uuid, string(message.Payload())))
Expand All @@ -121,10 +125,10 @@ func onCommandReceivedFromBroker(client mqtt.Client, message mqtt.Message) {
request["ping"] = "pong"
sendTestData(request)
case "randfloat32":
request["randfloat32"] = rand.Float32()
request["randfloat32"] = rand.Float32() //nolint:gosec
sendTestData(request)
case "randfloat64":
request["randfloat64"] = rand.Float64()
request["randfloat64"] = rand.Float64() //nolint:gosec
sendTestData(request)
case "message":
request["message"] = "test-message"
Expand Down Expand Up @@ -159,24 +163,24 @@ func sendTestData(response map[string]interface{}) {
}
client.Publish(topic, qos, false, jsonData)

fmt.Println(fmt.Sprintf("Send response: %v", string(jsonData)))
fmt.Printf("Send response: %v", string(jsonData))
}

func createMqttClient(clientID string, uri *url.URL) (mqtt.Client, error) {
fmt.Println(fmt.Sprintf("Create MQTT client and connection: uri=%v clientID=%v ", uri.String(), clientID))
fmt.Printf("Create MQTT client and connection: uri=%v clientID=%v ", uri.String(), clientID)
opts := mqtt.NewClientOptions()
opts.AddBroker(fmt.Sprintf("%s://%s", uri.Scheme, uri.Host))
opts.SetClientID(clientID)
opts.SetUsername(uri.User.Username())
password, _ := uri.User.Password()
opts.SetPassword(password)
opts.SetConnectionLostHandler(func(client mqtt.Client, e error) {
fmt.Println(fmt.Sprintf("Connection lost : %v", e))
fmt.Printf("Connection lost : %v", e)
token := client.Connect()
if token.Wait() && token.Error() != nil {
fmt.Println(fmt.Sprintf("Reconnection failed : %v", e))
fmt.Printf("Reconnection failed : %v", e)
} else {
fmt.Println(fmt.Sprintf("Reconnection sucessful : %v", e))
fmt.Printf("Reconnection sucessful : %v", e)
}
})

Expand Down

0 comments on commit 6a0d17f

Please sign in to comment.