From 35af340d07255059323f0c56a121a5e400be0b62 Mon Sep 17 00:00:00 2001 From: Yiwei Ding <87166810+Yiwei-Ding@users.noreply.github.com> Date: Tue, 14 Dec 2021 00:45:47 +0800 Subject: [PATCH] Fix #736 (#738) --- analyzer.go | 8 ++++---- analyzer_test.go | 19 ++++++++++++++++++- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/analyzer.go b/analyzer.go index 0efb9a9..f605d58 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 21e9af4..0630f72 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]