Add null pointer check in G601

fixes: #475
This commit is contained in:
Grant Murphy 2020-05-21 01:17:44 +10:00 committed by Cosmin Cojocar
parent 1418b856ea
commit 8630c43b66
3 changed files with 36 additions and 17 deletions

View file

@ -215,7 +215,7 @@ var _ = Describe("Analyzer", func() {
})
It("should pass the build tags", func() {
sample := testutils.SampleCode601[0]
sample := testutils.SampleCodeBuildTag[0]
source := sample.Code[0]
analyzer.LoadRules(rules.Generate().Builders())
pkg := testutils.NewTestPackage()

View file

@ -2,9 +2,10 @@ package rules
import (
"fmt"
"github.com/securego/gosec/v2"
"go/ast"
"go/token"
"github.com/securego/gosec/v2"
)
type implicitAliasing struct {
@ -33,6 +34,7 @@ func (r *implicitAliasing) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, er
// When presented with a range statement, get the underlying Object bound to
// by assignment and add it to our set (r.aliases) of objects to check for.
if key, ok := node.Value.(*ast.Ident); ok {
if key.Obj != nil {
if assignment, ok := key.Obj.Decl.(*ast.AssignStmt); ok {
if len(assignment.Lhs) < 2 {
return nil, nil
@ -47,6 +49,8 @@ func (r *implicitAliasing) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, er
}
}
}
}
case *ast.UnaryExpr:
// If this unary expression is outside of the last range statement we were looking at
// then clear the list of objects we're concerned about because they're no longer in

View file

@ -1849,13 +1849,14 @@ func main() {
}
}`}, 1, gosec.NewConfig()}}
// SampleCodeG601 - Implicit ForRange aliasing
SampleCodeG601 = []CodeSample{{[]string{`package main
// SampleCodeG601 - Implicit aliasing over range statement
SampleCodeG601 = []CodeSample{
{[]string{`
package main
import "fmt"
var vector []*string
func appendVector(s *string) {
vector = append(vector, s)
}
@ -1882,12 +1883,26 @@ func main() {
zero, c_star, c := foo()
fmt.Printf("%d %v %s", zero, c_start, c)
}`}, 1, gosec.NewConfig()}}
}`,
}, 1, gosec.NewConfig()},
{[]string{`
// see: github.com/securego/gosec/issues/475
package main
import (
"fmt"
)
func main() {
sampleMap := map[string]string{}
sampleString := "A string"
for sampleString, _ = range sampleMap {
fmt.Println(sampleString)
}
}`}, 0, gosec.NewConfig()},
}
// SampleCode601 - Go build tags
SampleCode601 = []CodeSample{{[]string{`
// SampleCodeBuildTag - G601 build tags
SampleCodeBuildTag = []CodeSample{{[]string{`
// +build tag
package main
func main() {
fmt.Println("no package imported error")