From 71fa103e0a679aa69a53ceac679b15a877150a1b Mon Sep 17 00:00:00 2001 From: Yiwei Ding Date: Mon, 13 Dec 2021 15:24:10 +0800 Subject: [PATCH] Fix #736 --- analyzer.go | 8 ++++---- analyzer_test.go | 19 ++++++++++++++++++- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/analyzer.go b/analyzer.go index 0efb9a9ccc..f605d58bac 100644 --- a/analyzer.go +++ b/analyzer.go @@ -319,16 +319,16 @@ func (gosec *Analyzer) ignore(n ast.Node) map[string]SuppressionInfo { } for _, group := range groups { - - foundDefaultTag := strings.HasPrefix(group.Text(), noSecDefaultTag) - foundAlternativeTag := strings.HasPrefix(group.Text(), noSecAlternativeTag) + comment := strings.TrimSpace(group.Text()) + foundDefaultTag := strings.HasPrefix(comment, noSecDefaultTag) + foundAlternativeTag := strings.HasPrefix(comment, noSecAlternativeTag) if foundDefaultTag || foundAlternativeTag { gosec.stats.NumNosec++ // Extract the directive and the justification. justification := "" - commentParts := regexp.MustCompile(`-{2,}`).Split(group.Text(), 2) + commentParts := regexp.MustCompile(`-{2,}`).Split(comment, 2) directive := commentParts[0] if len(commentParts) > 1 { justification = strings.TrimSpace(strings.TrimRight(commentParts[1], "\n")) diff --git a/analyzer_test.go b/analyzer_test.go index 21e9af49d7..0630f72b5f 100644 --- a/analyzer_test.go +++ b/analyzer_test.go @@ -139,7 +139,7 @@ var _ = Describe("Analyzer", func() { } }) - It("should not report errors when a nosec comment is present", func() { + It("should not report errors when a nosec line comment is present", func() { sample := testutils.SampleCodeG401[0] source := sample.Code[0] analyzer.LoadRules(rules.Generate(false, rules.NewRuleFilter(false, "G401")).RulesInfo()) @@ -156,6 +156,23 @@ var _ = Describe("Analyzer", func() { Expect(nosecIssues).Should(BeEmpty()) }) + It("should not report errors when a nosec block comment is present", func() { + sample := testutils.SampleCodeG401[0] + source := sample.Code[0] + analyzer.LoadRules(rules.Generate(false, rules.NewRuleFilter(false, "G401")).RulesInfo()) + + nosecPackage := testutils.NewTestPackage() + defer nosecPackage.Close() + nosecSource := strings.Replace(source, "h := md5.New()", "h := md5.New() /* #nosec */", 1) + nosecPackage.AddFile("md5.go", nosecSource) + err := nosecPackage.Build() + Expect(err).ShouldNot(HaveOccurred()) + err = analyzer.Process(buildTags, nosecPackage.Path) + Expect(err).ShouldNot(HaveOccurred()) + nosecIssues, _, _ := analyzer.Report() + Expect(nosecIssues).Should(BeEmpty()) + }) + It("should not report errors when an exclude comment is present for the correct rule", func() { // Rule for MD5 weak crypto usage sample := testutils.SampleCodeG401[0]