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

fix(query): countLines, IgnoreLines and fileCommands #6611

Merged
merged 41 commits into from
Feb 21, 2024
Merged
Show file tree
Hide file tree
Changes from 33 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
3ee0986
fix(Sink): countLines, IgnoreLines and fileCommands fixed
cx-henriqueAlvelos Aug 5, 2023
db329e3
lint
cx-henriqueAlvelos Aug 5, 2023
aaf4c64
fix: helm detector pointer reference
cx-henriqueAlvelos Aug 5, 2023
661b8d8
Merge branch 'master' into kics-987
cx-henriqueAlvelos Aug 8, 2023
7d976b0
fixed lint
cx-henriqueAlvelos Aug 8, 2023
5c86b51
Fixed multiline strings
cx-henriqueAlvelos Aug 9, 2023
29278f8
Merge branch 'master' into kics-987
cx-henriqueAlvelos Aug 9, 2023
f49c8b5
added tests
cx-henriqueAlvelos Aug 9, 2023
c96d868
Merge branch 'master' into kics-987
cx-henriqueAlvelos Aug 12, 2023
33593be
Merge branch 'master' into kics-987
cx-henriqueAlvelos Sep 9, 2023
f17b0fd
Merge branch 'master' into kics-987
cx-henriqueAlvelos Sep 15, 2023
f284f0e
Merge branch 'master' into kics-987
cx-henriqueAlvelos Sep 18, 2023
23cd43e
Merge branch 'master' into kics-987
gabriel-cx Sep 22, 2023
27454a2
Merge branch 'master' into kics-987
JoaoAtGit Oct 18, 2023
a1a864f
Merge branch 'master' into kics-987
JoaoAtGit Jan 31, 2024
71944b6
updating the branch
JoaoAtGit Feb 2, 2024
5ae721e
block
JoaoAtGit Feb 2, 2024
c45c03e
support to ignore
JoaoAtGit Feb 2, 2024
7c36587
test
JoaoAtGit Feb 5, 2024
0ddf08b
fix ignore-block
JoaoAtGit Feb 5, 2024
2fd817f
improve code
JoaoAtGit Feb 5, 2024
fced8ae
Merge branch 'master' into kics-987
JoaoAtGit Feb 5, 2024
5ae5bad
fix
JoaoAtGit Feb 6, 2024
ea24a13
Merge branch 'master' into kics-987
JoaoAtGit Feb 6, 2024
acd713d
e2e to helm ignore and ignore block
JoaoAtGit Feb 6, 2024
b95e6cf
Merge branch 'master' into kics-987
JoaoAtGit Feb 6, 2024
8cb6da5
fix
JoaoAtGit Feb 6, 2024
ed1252c
Merge branch 'kics-987' of github.com:Checkmarx/kics into kics-987
JoaoAtGit Feb 6, 2024
f82787a
fix code
JoaoAtGit Feb 6, 2024
315b876
fix paths
JoaoAtGit Feb 6, 2024
fc2c21d
fix
JoaoAtGit Feb 6, 2024
02643f1
e2e to test the query disable on helm
JoaoAtGit Feb 6, 2024
d8f1bf1
Merge branch 'master' into kics-987
JoaoAtGit Feb 7, 2024
81eeb82
Merge branch 'master' into kics-987
JoaoAtGit Feb 19, 2024
8c28fba
improve logic to count files
JoaoAtGit Feb 21, 2024
f800925
Merge branch 'master' into kics-987
JoaoAtGit Feb 21, 2024
831200d
linter
JoaoAtGit Feb 21, 2024
c8920f2
fix tests
JoaoAtGit Feb 21, 2024
5ac773a
fix e2e
JoaoAtGit Feb 21, 2024
937d5f2
Merge branch 'master' into kics-987
JoaoAtGit Feb 21, 2024
ebf8420
Merge branch 'master' into kics-987
asofsilva Feb 21, 2024
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
28 changes: 28 additions & 0 deletions e2e/fixtures/E2E_CLI_083_RESULT.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"kics_version": "development",
"files_scanned": 4,
"lines_scanned": 89,
"files_parsed": 3,
"lines_parsed": 86,
"lines_ignored": 3,
"files_failed_to_scan": 0,
"queries_total": 1,
"queries_failed_to_execute": 0,
"queries_failed_to_compute_similarity_id": 0,
"scan_id": "console",
"severity_counters": {
"HIGH": 0,
"INFO": 0,
"LOW": 0,
"MEDIUM": 0,
"TRACE": 0
},
"total_counter": 0,
"total_bom_resources": 0,
"start": "2024-02-06T12:29:45.3845776Z",
"end": "2024-02-06T12:29:49.5261723Z",
"paths": [
"/path/test/fixtures/helm_ignore"
],
"queries": []
}
28 changes: 28 additions & 0 deletions e2e/fixtures/E2E_CLI_084_RESULT.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"kics_version": "development",
"files_scanned": 4,
"lines_scanned": 89,
"files_parsed": 3,
"lines_parsed": 34,
"lines_ignored": 55,
"files_failed_to_scan": 0,
"queries_total": 1,
"queries_failed_to_execute": 0,
"queries_failed_to_compute_similarity_id": 0,
"scan_id": "console",
"severity_counters": {
"HIGH": 0,
"INFO": 0,
"LOW": 0,
"MEDIUM": 0,
"TRACE": 0
},
"total_counter": 0,
"total_bom_resources": 0,
"start": "2024-02-06T12:29:45.3845776Z",
"end": "2024-02-06T12:29:49.5261723Z",
"paths": [
"/path/test/fixtures/helm_ignore_block"
],
"queries": []
}
28 changes: 28 additions & 0 deletions e2e/fixtures/E2E_CLI_085_RESULT.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"kics_version": "development",
"files_scanned": 4,
"lines_scanned": 89,
"files_parsed": 3,
"lines_parsed": 86,
"lines_ignored": 3,
"files_failed_to_scan": 0,
"queries_total": 1,
"queries_failed_to_execute": 0,
"queries_failed_to_compute_similarity_id": 0,
"scan_id": "console",
"severity_counters": {
"HIGH": 0,
"INFO": 0,
"LOW": 0,
"MEDIUM": 0,
"TRACE": 0
},
"total_counter": 0,
"total_bom_resources": 0,
"start": "2024-02-06T15:01:20.657455Z",
"end": "2024-02-06T15:01:25.1183483Z",
"paths": [
"/path/test/fixtures/helm_disable_query"
],
"queries": []
}
27 changes: 27 additions & 0 deletions e2e/testcases/e2e-cli-083_helm_ignore.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package testcases

// E2E-CLI-083 - KICS scan
// should perform a scan and return zero results ignoring the file
func init() { //nolint
testSample := TestCase{
Name: "should perform a scan and return zero results ignoring the file [E2E-CLI-083]",
Args: args{
Args: []cmdArgs{
[]string{"scan", "-o", "/path/e2e/output",
"--output-name", "E2E_CLI_083_RESULT",
"-p", "\"/path/test/fixtures/helm_ignore\"",
"-i", "b7652612-de4e-4466-a0bf-1cd81f0c6063",
},
},
ExpectedResult: []ResultsValidation{
{
ResultsFile: "E2E_CLI_083_RESULT",
ResultsFormats: []string{"json"},
},
},
},
WantStatus: []int{0},
}

Tests = append(Tests, testSample)
}
27 changes: 27 additions & 0 deletions e2e/testcases/e2e-cli-084_helm_ignore_block.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package testcases

// E2E-CLI-084 - KICS scan
// should perform a scan and return zero results ignoring the block
func init() { //nolint
testSample := TestCase{
Name: "should perform a scan and return zero results ignoring the block [E2E-CLI-084]",
Args: args{
Args: []cmdArgs{
[]string{"scan", "-o", "/path/e2e/output",
"--output-name", "E2E_CLI_084_RESULT",
"-p", "\"/path/test/fixtures/helm_ignore_block\"",
"-i", "b7652612-de4e-4466-a0bf-1cd81f0c6063",
},
},
ExpectedResult: []ResultsValidation{
{
ResultsFile: "E2E_CLI_084_RESULT",
ResultsFormats: []string{"json"},
},
},
},
WantStatus: []int{0},
}

Tests = append(Tests, testSample)
}
27 changes: 27 additions & 0 deletions e2e/testcases/e2e-cli-085_helm_disable_query.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package testcases

// E2E-CLI-085 - KICS scan
// should perform a scan and return zero results ignoring the query
func init() { //nolint
testSample := TestCase{
Name: "should perform a scan and return zero results ignoring the query [E2E-CLI-085]",
Args: args{
Args: []cmdArgs{
[]string{"scan", "-o", "/path/e2e/output",
"--output-name", "E2E_CLI_085_RESULT",
"-p", "\"/path/test/fixtures/helm_disable_query\"",
"-i", "b7652612-de4e-4466-a0bf-1cd81f0c6063",
},
},
ExpectedResult: []ResultsValidation{
{
ResultsFile: "E2E_CLI_085_RESULT",
ResultsFormats: []string{"json"},
},
},
},
WantStatus: []int{0},
}

Tests = append(Tests, testSample)
}
5 changes: 4 additions & 1 deletion pkg/detector/helm/helm_detect.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ const (
func (d DetectKindLine) DetectLine(file *model.FileMetadata, searchKey string,
outputLines int, logWithFields *zerolog.Logger) model.VulnerabilityLines {
searchKey = fmt.Sprintf("%s.%s", strings.TrimRight(strings.TrimLeft(file.HelmID, "# "), ":"), searchKey)
lines := *file.LinesOriginalData

lines := make([]string, len(*file.LinesOriginalData))
copy(lines, *file.LinesOriginalData)

curLineRes := detectCurlLine{
foundRes: false,
lineRes: 0,
Expand Down
33 changes: 31 additions & 2 deletions pkg/kics/resolver_sink.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"fmt"
"regexp"
"sort"

sentryReport "github.com/Checkmarx/kics/internal/sentry"
Expand All @@ -28,8 +29,6 @@ func (s *Service) resolverSink(ctx context.Context, filename, scanID string, ope

for _, rfile := range resFiles.File {
s.Tracker.TrackFileFound()
countLines := bytes.Count(rfile.Content, []byte{'\n'}) + 1
s.Tracker.TrackFileFoundCountLines(countLines)

isMinified := minified.IsMinified(rfile.FileName, rfile.Content)
documents, err := s.Parser.Parse(rfile.FileName, rfile.Content, openAPIResolveReferences, isMinified)
Expand All @@ -40,6 +39,21 @@ func (s *Service) resolverSink(ctx context.Context, filename, scanID string, ope
log.Err(err).Msgf("failed to parse file content")
return []string{}, nil
}

if kind == model.KindHELM {
ignoreList, errorIL := s.getOriginalIgnoreLines(rfile.FileName, rfile.OriginalData, openAPIResolveReferences, isMinified)
if errorIL == nil {
documents.IgnoreLines = ignoreList

// Need to ignore #KICS_HELM_ID Line
documents.CountLines = bytes.Count(rfile.OriginalData, []byte{'\n'})
}
} else {
documents.CountLines = bytes.Count(rfile.OriginalData, []byte{'\n'}) + 1
}

fileCommands := s.Parser.CommentsCommands(rfile.FileName, rfile.OriginalData)

for _, document := range documents.Docs {
_, err = json.Marshal(document)
if err != nil {
Expand Down Expand Up @@ -67,6 +81,7 @@ func (s *Service) resolverSink(ctx context.Context, filename, scanID string, ope
FilePath: rfile.FileName,
Content: string(rfile.Content),
HelmID: rfile.SplitID,
Commands: fileCommands,
IDInfo: rfile.IDInfo,
LinesIgnore: documents.IgnoreLines,
ResolvedFiles: documents.ResolvedFiles,
Expand All @@ -76,8 +91,22 @@ func (s *Service) resolverSink(ctx context.Context, filename, scanID string, ope
s.saveToFile(ctx, &file)
}
s.Tracker.TrackFileParse()
s.Tracker.TrackFileFoundCountLines(documents.CountLines)
cxMiguelSilva marked this conversation as resolved.
Show resolved Hide resolved
s.Tracker.TrackFileParseCountLines(documents.CountLines - len(documents.IgnoreLines))
s.Tracker.TrackFileIgnoreCountLines(len(documents.IgnoreLines))
}
return resFiles.Excluded, nil
}

func (s *Service) getOriginalIgnoreLines(filename string,
originalFile []uint8,
openAPIResolveReferences, isMinified bool) (ignoreLines []int, err error) {
refactor := regexp.MustCompile(`.*\n?.*KICS\_HELM\_ID.+\n`).ReplaceAll(originalFile, []uint8{})
refactor = regexp.MustCompile(`{{-\s*(.*?)\s*}}`).ReplaceAll(refactor, []uint8{})

documentsOriginal, err := s.Parser.Parse(filename, refactor, openAPIResolveReferences, isMinified)
if err == nil {
ignoreLines = documentsOriginal.IgnoreLines
}
return
}
28 changes: 22 additions & 6 deletions pkg/model/comment_yaml.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package model

import (
"reflect"
"strings"
"sync"

Expand Down Expand Up @@ -150,6 +151,7 @@ func processLine(kind yaml.Kind, content *yaml.Node, position int) (linesIgnore
} else {
nodeToIgnore = content.Content[position]
}

linesIgnore = append(linesIgnore, nodeToIgnore.Line-1, nodeToIgnore.Line)
return
}
Expand All @@ -175,13 +177,17 @@ func processBlock(kind yaml.Kind, content []*yaml.Node, position int) (linesIgno
// getNodeLastLine returns the last line of a node
func getNodeLastLine(node *yaml.Node) (lastLine int) {
lastLine = node.Line
for _, content := range node.Content {
if content.Line > lastLine {
lastLine = content.Line
}
if lineContent := getNodeLastLine(content); lineContent > lastLine {
lastLine = lineContent
if len(node.Content) > 0 {
for _, content := range node.Content {
if content.Line > lastLine {
lastLine = content.Line
}
if lineContent := getNodeLastLine(content); lineContent > lastLine {
lastLine = lineContent
}
}
} else if reflect.TypeOf(node.Value).Kind() == reflect.String {
lastLine += strings.Count(node.Value, "\n")
}

return
Expand All @@ -190,6 +196,12 @@ func getNodeLastLine(node *yaml.Node) (lastLine int) {
// value returns the value of the comment
func (c *comment) value() (value CommentCommand) {
comment := strings.ToLower(string(*c))
if isHelm(comment) {
res := KICSGetContentCommentRgxp.FindString(comment)
if len(res) > 0 {
comment = res
}
}
// check if we are working with kics command
if KICSCommentRgxp.MatchString(comment) {
comment = KICSCommentRgxp.ReplaceAllString(comment, "")
Expand All @@ -200,3 +212,7 @@ func (c *comment) value() (value CommentCommand) {
}
return CommentCommand(comment)
}

func isHelm(comment string) bool {
return strings.Contains(comment, "helm")
}
51 changes: 51 additions & 0 deletions pkg/model/comment_yaml_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package model

import (
"github.com/stretchr/testify/assert"
"sort"
"testing"

Expand Down Expand Up @@ -634,6 +635,30 @@ func Test_ignoreCommentsYAML(t *testing.T) {
},
},
},
{
name: "test_7: ignore_multiline_string",
want: []int{4, 5, 6, 7, 8, 9},
args: args{
&yaml.Node{
Kind: yaml.MappingNode,
Content: []*yaml.Node{
{
Kind: yaml.ScalarNode,
Value: "deploy.yml",
HeadComment: "# kics-scan ignore-block",
Line: 5,
Column: 3,
},
{
Kind: yaml.ScalarNode,
Value: "---\nfoo\n bar: abc\nuploader-token: my-awesome-token\n",
Line: 5,
Column: 15,
},
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand All @@ -647,3 +672,29 @@ func Test_ignoreCommentsYAML(t *testing.T) {
})
}
}

func Test_value(t *testing.T) {
tests := []struct {
name string
input comment
want string
}{
{
name: "Should return ignore-block",
input: comment("# source: test/templates/deployment.yaml\n# kics-scan ignore-block\n# kics_helm_id_2:"),
want: "ignore-block",
},
{
name: "Should Not return ignore-block",
input: comment("# source: test/templates/deployment.yaml\n# kics ignore-block\n# kics_helm_id_2:"),
want: "# source: test/templates/deployment.yaml\n# kics ignore-block\n# kics_helm_id_2:",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
res := tt.input.value()
assert.Equal(t, string(res), tt.want)
})
}
}
4 changes: 3 additions & 1 deletion pkg/model/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ var (

var (
// KICSCommentRgxp is the regexp to identify if a comment is a KICS comment
KICSCommentRgxp = regexp.MustCompile(`^((/{2})|#|;)*\s*kics-scan\s*`)
KICSCommentRgxp = regexp.MustCompile(`(^|\n)((/{2})|#|;)*\s*kics-scan\s*`)
// KICSGetContentCommentRgxp to gets the kics comment on the hel case
KICSGetContentCommentRgxp = regexp.MustCompile(`(^|\n)((/{2})|#|;)*\s*kics-scan([^\n]*)\n`)
// KICSCommentRgxpYaml is the regexp to identify if the comment has KICS comment at the end of the comment in YAML
KICSCommentRgxpYaml = regexp.MustCompile(`((/{2})|#)*\s*kics-scan\s*(ignore-line|ignore-block)\s*\n*$`)
)
Expand Down
Loading
Loading