Skip to content

Commit

Permalink
style: Enable gosec linter and associated recommendations (#3737)
Browse files Browse the repository at this point in the history
See #3565

Signed-off-by: Bryon Nevis <[email protected]>

Co-authored-by: Lenny Goodell <[email protected]>
  • Loading branch information
bnevis-i and Lenny Goodell authored Sep 30, 2021
1 parent ddfefb1 commit 3e61d8d
Show file tree
Hide file tree
Showing 18 changed files with 34 additions and 23 deletions.
2 changes: 2 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
linters:
disable:
enable:
- gosec
8 changes: 4 additions & 4 deletions internal/security/bootstrapper/command/setupacl/acltokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ const (

// consul API related:
consulCheckAgentAPI = "/v1/agent/self"
consulSetAgentTokenAPI = "/v1/agent/token/%s"
consulListTokensAPI = "/v1/acl/tokens"
consulCreateTokenAPI = "/v1/acl/token"
consulSetAgentTokenAPI = "/v1/agent/token/%s" // nolint:gosec
consulListTokensAPI = "/v1/acl/tokens" // nolint:gosec
consulCreateTokenAPI = "/v1/acl/token" // nolint:gosec
// RUD: Read Update Delete
consulTokenRUDAPI = "/v1/acl/token/%s"
consulTokenRUDAPI = "/v1/acl/token/%s" //nolint:gosec
)

// CreateRegistryToken is the structure to create a new registry token
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ func TestGetUniqueRoleNames(t *testing.T) {
testConfigOneRole["testRole1"] = config.ACLRoleInfo{Description: "role1"}

// random number of roles between 2 and 4
numOfConfigRoles := rand.Intn(1)*3 + 2
numOfConfigRoles := rand.Intn(1)*3 + 2 // nolint:gosec
testConfigMultipleRoles := make(map[string]config.ACLRoleInfo)
for i := 0; i < numOfConfigRoles; i++ {
roleName := "testRole" + strconv.Itoa(i+1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ package share

const (
// ConsulTokenHeader is the HTTP header for Consul token access
ConsulTokenHeader = "X-Consul-Token"
ConsulTokenHeader = "X-Consul-Token" // nolint:gosec
// EmptyToken represents an empty token
EmptyToken = ""
)
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package setupacl

// this is just the stub for test data related
const (
// nolint:gosec
secretstoreTokenJsonStub = `
{
"auth": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ func TestExecute(t *testing.T) {
}()

// literally make random delay between 0 to 3 seconds before running the tcp server
time.Sleep(time.Duration(rand.Intn(3)) * time.Second)
time.Sleep(time.Duration(rand.Intn(3)) * time.Second) // nolint:gosec

tcpSrvErr := make(chan error, 1)
go func() {
Expand Down
6 changes: 3 additions & 3 deletions internal/security/bootstrapper/helper/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,15 @@ func writeFile(aFileName string) error {
return os.WriteFile(aFileName, timestamp, 0400)
}

// GenerateRandomString will return a randomized string of characters at the
// GeneratePseudoRandomString will return a randomized string of characters at the
// length specified via input variable `n`
func GenerateRandomString(n int) string {
func GeneratePseudoRandomString(n int) string {
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

if n > 0 {
s := make([]rune, n)
for i := range s {
s[i] = letters[rand.Intn(len(letters))]
s[i] = letters[rand.Intn(len(letters))] // nolint:gosec
}
return string(s)
}
Expand Down
2 changes: 1 addition & 1 deletion internal/security/proxy/const.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const (
CertificatesPath = "certificates"
PluginsPath = "plugins"
EdgeXKong = "edgex-kong"
VaultToken = "X-Vault-Token"
VaultToken = "X-Vault-Token" // nolint:gosec
OAuth2GrantType = "client_credentials"
OAuth2Scopes = "all"
URLEncodedForm = "application/x-www-form-urlencoded"
Expand Down
5 changes: 4 additions & 1 deletion internal/security/proxy/requestor.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ func NewRequestor(
var tr *http.Transport
if skipVerify {
tr = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
InsecureSkipVerify: true, // nolint:gosec
},
}
} else {
caCert, err := os.ReadFile(caCertPath)
Expand Down
5 changes: 3 additions & 2 deletions internal/security/proxy/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,8 @@ func (s *Service) Init() error {

for serviceKey, route := range mergedRoutes {

err := s.initKongService(&route)
var routeCopy = route // gosec -- memory aliasing in for loop
err := s.initKongService(&routeCopy)
if err != nil {
return err
}
Expand All @@ -158,7 +159,7 @@ func (s *Service) Init() error {
// see details on https://docs.konghq.com/hub/kong-inc/request-transformer/#enabling-the-plugin-on-a-service
if serviceKey == edgeXCoreConsulServiceKey {
s.loggingClient.Infof("try to enable service plugin for %s", edgeXCoreConsulServiceKey)
if err := s.addConsulTokenHeaderTo(&route); err != nil {
if err := s.addConsulTokenHeaderTo(&routeCopy); err != nil {
s.loggingClient.Errorf("failed to enable service plugin for %s: %v", edgeXCoreConsulServiceKey, err)
return err
}
Expand Down
5 changes: 3 additions & 2 deletions internal/security/proxy/serviceplugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/edgexfoundry/go-mod-core-contracts/v2/common"
"io"
"net/http"
"net/url"
Expand All @@ -29,6 +28,8 @@ import (
"path/filepath"
"strings"

"github.com/edgexfoundry/go-mod-core-contracts/v2/common"

"github.com/edgexfoundry/edgex-go/internal"
"github.com/edgexfoundry/edgex-go/internal/security/bootstrapper/helper"
"github.com/edgexfoundry/edgex-go/internal/security/proxy/models"
Expand All @@ -37,7 +38,7 @@ import (

const (
requestTransformerPlugin = "request-transformer"
consulTokenHeader = "X-Consul-Token"
consulTokenHeader = "X-Consul-Token" // nolint:gosec
)

// addConsulHeader is to enable request transformer plugin on a service
Expand Down
1 change: 1 addition & 0 deletions internal/security/proxy/serviceplugin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ func TestAddConsulHeaderTo(t *testing.T) {
Name: testServiceName,
}
// setup access token file
// nolint:gosec
tokenData := `{
"SecretID":"test-access-token",
"Policies": [
Expand Down
3 changes: 2 additions & 1 deletion internal/security/secretstore/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,12 @@ const (
// and the the length of the name is upto 512 characters
ServiceNameValidationRegx = `^[\w. \~\^\-\|\<\>\{\}]{1,512}$`

VaultToken = "X-Vault-Token"
VaultToken = "X-Vault-Token" // nolint:gosec
TokenCreatorPolicyName = "privileged-token-creator"

// This is an admin token policy that allow for creation of
// per-service tokens and policies
// nolint:gosec
TokenCreatorPolicy = `
path "auth/token/create" {
capabilities = ["create", "update", "sudo"]
Expand Down
2 changes: 1 addition & 1 deletion internal/security/secretstore/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ const (
serviceListBegin = "["
serviceListEnd = "]"
serviceListSeparator = ";"
secretBasePath = "/v1/secret/edgex"
secretBasePath = "/v1/secret/edgex" // nolint:gosec
)

var errNotFound = errors.New("credential NOT found")
Expand Down
5 changes: 3 additions & 2 deletions internal/security/secretstore/kongadminapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ func (k *KongAdminAPI) Setup() error {

// Set random string for JWT issuer payload value - the default issuer value assigned
// by Kong is 32 bytes in length - simply mirroring that for consistency
k.secrets.jwt.issuer = helper.GenerateRandomString(32)
k.secrets.jwt.issuer = helper.GeneratePseudoRandomString(32)

// Insert public key
configTemplateText := strings.Replace(string(configTemplateBytes),
Expand All @@ -133,7 +133,8 @@ func (k *KongAdminAPI) Setup() error {
"<<INSERT-ADMIN-JWT-ISSUER-KEY>>", k.secrets.jwt.issuer, -1)

// Write the config file to the configured save path
err = os.WriteFile(k.paths.config, []byte(configTemplateText), 0644)
// note: config file contains no confidential data -- 0644 since it is owned by root
err = os.WriteFile(k.paths.config, []byte(configTemplateText), 0644) // nolint:gosec
if err != nil {
return fmt.Errorf("%s Failed to write config template to file %s: %w", k.prefixes.errText, k.paths.config, err)
}
Expand Down
2 changes: 1 addition & 1 deletion internal/security/secretstore/password_linux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (
)

func TestGenerateWithAPG(t *testing.T) {
rootToken := "s.Ga5jyNq6kNfRMVQk2LY1j9iu"
rootToken := "s.Ga5jyNq6kNfRMVQk2LY1j9iu" // nolint:gosec
mockLogger := logger.MockLogger{}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
Expand Down
2 changes: 1 addition & 1 deletion internal/security/secretstore/password_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import (
)

func TestGenerateWithDefaults(t *testing.T) {
rootToken := "s.Ga5jyNq6kNfRMVQk2LY1j9iu"
rootToken := "s.Ga5jyNq6kNfRMVQk2LY1j9iu" // nolint:gosec
mockLogger := logger.MockLogger{}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ func sendEmail(s config.SmtpInfo, auth mail.Auth, to []string, msg []byte) error
return errors.NewCommonEdgeXWrapper(err)
}
if ok, _ := c.Extension("STARTTLS"); ok {
config := &tls.Config{ServerName: serverName}
config := &tls.Config{MinVersion: tls.VersionTLS12, ServerName: serverName}
config.InsecureSkipVerify = s.EnableSelfSignedCert
if err = c.StartTLS(config); err != nil {
return errors.NewCommonEdgeXWrapper(err)
Expand Down

0 comments on commit 3e61d8d

Please sign in to comment.