Extend the code snippet included in the issue and refactored how the code snippet is printed

Signed-off-by: Cosmin Cojocar <cosmin.cojocar@gmx.ch>
This commit is contained in:
Cosmin Cojocar 2020-06-25 15:21:23 +02:00 committed by Cosmin Cojocar
parent 37d1af0af3
commit d1467ac998
3 changed files with 62 additions and 24 deletions

View file

@ -15,9 +15,12 @@
package gosec package gosec
import ( import (
"bufio"
"bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"go/ast" "go/ast"
"go/token"
"os" "os"
"strconv" "strconv"
) )
@ -34,6 +37,10 @@ const (
High High
) )
// SnippetOffset defines the number of lines captured before
// the beginning and after the end of a code snippet
const SnippetOffset = 1
// Cwe id and url // Cwe id and url
type Cwe struct { type Cwe struct {
ID string ID string
@ -126,41 +133,53 @@ func (c Score) String() string {
func codeSnippet(file *os.File, start int64, end int64, n ast.Node) (string, error) { func codeSnippet(file *os.File, start int64, end int64, n ast.Node) (string, error) {
if n == nil { if n == nil {
return "", fmt.Errorf("Invalid AST node provided") return "", fmt.Errorf("invalid AST node provided")
} }
var pos int64
var buf bytes.Buffer
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
pos++
if pos > end {
break
} else if pos >= start && pos <= end {
code := fmt.Sprintf("%d: %s\n", pos, scanner.Text())
buf.WriteString(code)
}
}
return buf.String(), nil
}
size := (int)(end - start) // Go bug, os.File.Read should return int64 ... func codeSnippetStartLine(node ast.Node, fobj *token.File) int64 {
_, err := file.Seek(start, 0) // #nosec s := (int64)(fobj.Line(node.Pos()))
if err != nil { if s-SnippetOffset > 0 {
return "", fmt.Errorf("move to the beginning of file: %v", err) return s - SnippetOffset
} }
return s
}
buf := make([]byte, size) func codeSnippetEndLine(node ast.Node, fobj *token.File) int64 {
if nread, err := file.Read(buf); err != nil || nread != size { e := (int64)(fobj.Line(node.End()))
return "", fmt.Errorf("Unable to read code") return e + SnippetOffset
}
return string(buf), nil
} }
// NewIssue creates a new Issue // NewIssue creates a new Issue
func NewIssue(ctx *Context, node ast.Node, ruleID, desc string, severity Score, confidence Score) *Issue { func NewIssue(ctx *Context, node ast.Node, ruleID, desc string, severity Score, confidence Score) *Issue {
var code string
fobj := ctx.FileSet.File(node.Pos()) fobj := ctx.FileSet.File(node.Pos())
name := fobj.Name() name := fobj.Name()
start, end := fobj.Line(node.Pos()), fobj.Line(node.End()) start, end := fobj.Line(node.Pos()), fobj.Line(node.End())
line := strconv.Itoa(start) line := strconv.Itoa(start)
if start != end { if start != end {
line = fmt.Sprintf("%d-%d", start, end) line = fmt.Sprintf("%d-%d", start, end)
} }
col := strconv.Itoa(fobj.Position(node.Pos()).Column) col := strconv.Itoa(fobj.Position(node.Pos()).Column)
// #nosec var code string
if file, err := os.Open(fobj.Name()); err == nil { if file, err := os.Open(fobj.Name()); err == nil {
defer file.Close() defer file.Close() // #nosec
s := (int64)(fobj.Position(node.Pos()).Offset) // Go bug, should be int64 s := codeSnippetStartLine(node, fobj)
e := (int64)(fobj.Position(node.End()).Offset) // Go bug, should be int64 e := codeSnippetEndLine(node, fobj)
code, err = codeSnippet(file, s, e, node) code, err = codeSnippet(file, s, e, node)
if err != nil { if err != nil {
code = err.Error() code = err.Error()

View file

@ -15,6 +15,8 @@
package output package output
import ( import (
"bufio"
"bytes"
"encoding/csv" "encoding/csv"
"encoding/json" "encoding/json"
"encoding/xml" "encoding/xml"
@ -59,7 +61,7 @@ Golang errors in file: [{{ $filePath }}]:
{{end}} {{end}}
{{ range $index, $issue := .Issues }} {{ range $index, $issue := .Issues }}
[{{ highlight $issue.FileLocation $issue.Severity }}] - {{ $issue.RuleID }} (CWE-{{ $issue.Cwe.ID }}): {{ $issue.What }} (Confidence: {{ $issue.Confidence}}, Severity: {{ $issue.Severity }}) [{{ highlight $issue.FileLocation $issue.Severity }}] - {{ $issue.RuleID }} (CWE-{{ $issue.Cwe.ID }}): {{ $issue.What }} (Confidence: {{ $issue.Confidence}}, Severity: {{ $issue.Severity }})
> {{ $issue.Code }} {{ printCode $issue }}
{{ end }} {{ end }}
{{ notice "Summary:" }} {{ notice "Summary:" }}
@ -286,6 +288,7 @@ func plainTextFuncMap(enableColor bool) plainTemplate.FuncMap {
"danger": color.Danger.Render, "danger": color.Danger.Render,
"notice": color.Notice.Render, "notice": color.Notice.Render,
"success": color.Success.Render, "success": color.Success.Render,
"printCode": printCodeSnippet,
} }
} }
@ -294,9 +297,10 @@ func plainTextFuncMap(enableColor bool) plainTemplate.FuncMap {
"highlight": func(t string, s gosec.Score) string { "highlight": func(t string, s gosec.Score) string {
return t return t
}, },
"danger": fmt.Sprint, "danger": fmt.Sprint,
"notice": fmt.Sprint, "notice": fmt.Sprint,
"success": fmt.Sprint, "success": fmt.Sprint,
"printCode": printCodeSnippet,
} }
} }
@ -317,3 +321,18 @@ func highlight(t string, s gosec.Score) string {
return defaultTheme.Sprint(t) return defaultTheme.Sprint(t)
} }
} }
func printCodeSnippet(issue *gosec.Issue) string {
scanner := bufio.NewScanner(strings.NewReader(issue.Code))
var buf bytes.Buffer
for scanner.Scan() {
codeLine := scanner.Text()
if strings.HasPrefix(codeLine, issue.Line) {
codeLine = " > " + codeLine + "\n"
} else {
codeLine = " " + codeLine + "\n"
}
buf.WriteString(codeLine)
}
return buf.String()
}

View file

@ -21,7 +21,7 @@ func createIssue(ruleID string, cwe gosec.Cwe) gosec.Issue {
What: "test", What: "test",
Confidence: gosec.High, Confidence: gosec.High,
Severity: gosec.High, Severity: gosec.High,
Code: "testcode", Code: "1: testcode",
Cwe: cwe, Cwe: cwe,
} }
} }
@ -264,7 +264,7 @@ var _ = Describe("Formatter", func() {
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
err := CreateReport(buf, "csv", false, []string{}, []*gosec.Issue{&issue}, &gosec.Metrics{}, error) err := CreateReport(buf, "csv", false, []string{}, []*gosec.Issue{&issue}, &gosec.Metrics{}, error)
Expect(err).ShouldNot(HaveOccurred()) Expect(err).ShouldNot(HaveOccurred())
pattern := "/home/src/project/test.go,1,test,HIGH,HIGH,testcode,CWE-%s\n" pattern := "/home/src/project/test.go,1,test,HIGH,HIGH,1: testcode,CWE-%s\n"
expect := fmt.Sprintf(pattern, cwe.ID) expect := fmt.Sprintf(pattern, cwe.ID)
Expect(string(buf.String())).To(Equal(expect)) Expect(string(buf.String())).To(Equal(expect))
} }
@ -278,7 +278,7 @@ var _ = Describe("Formatter", func() {
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
err := CreateReport(buf, "xml", false, []string{}, []*gosec.Issue{&issue}, &gosec.Metrics{NumFiles: 0, NumLines: 0, NumNosec: 0, NumFound: 0}, error) err := CreateReport(buf, "xml", false, []string{}, []*gosec.Issue{&issue}, &gosec.Metrics{NumFiles: 0, NumLines: 0, NumNosec: 0, NumFound: 0}, error)
Expect(err).ShouldNot(HaveOccurred()) Expect(err).ShouldNot(HaveOccurred())
pattern := "Results:\n\n\n[/home/src/project/test.go:1] - %s (CWE-%s): test (Confidence: HIGH, Severity: HIGH)\n > testcode\n\n\nSummary:\n Files: 0\n Lines: 0\n Nosec: 0\n Issues: 0\n\n" pattern := "Results:\n\n\n[/home/src/project/test.go:1] - %s (CWE-%s): test (Confidence: HIGH, Severity: HIGH)\n > 1: testcode\n\n\n\nSummary:\n Files: 0\n Lines: 0\n Nosec: 0\n Issues: 0\n\n"
expect := fmt.Sprintf(pattern, rule, cwe.ID) expect := fmt.Sprintf(pattern, rule, cwe.ID)
Expect(string(buf.String())).To(Equal(expect)) Expect(string(buf.String())).To(Equal(expect))
} }