From 50795822a0062fbdd03e99862bf7e4c195d8fdfb Mon Sep 17 00:00:00 2001 From: Patrick Ohly Date: Wed, 23 Mar 2022 13:24:30 +0100 Subject: [PATCH] logcheck: fix detection of invalid * regexp in filter Extending the user-supplied regular expression to match the entire string by adding ^ and $ turned invalid regular expressions like * into valid ones (`^*$`) and thus didn't flag them as error. It's better to compile the string exactly as supplied by the user (better error message, properly detects this case) and then checking later whether the entire string was matched. --- hack/tools/logcheck/pkg/filter.go | 19 ++++++++++++++++--- hack/tools/logcheck/pkg/filter_test.go | 6 +++++- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/hack/tools/logcheck/pkg/filter.go b/hack/tools/logcheck/pkg/filter.go index 231a38cb..c2ad9092 100644 --- a/hack/tools/logcheck/pkg/filter.go +++ b/hack/tools/logcheck/pkg/filter.go @@ -88,8 +88,7 @@ func (f *RegexpFilter) Set(filename string) error { line.enabled[c] = enabled } - // Must match entire string. - re, err := regexp.Compile("^" + parts[1] + "$") + re, err := regexp.Compile(parts[1]) if err != nil { return fmt.Errorf("%s:%d: %v", filename, lineNr, err) } @@ -106,7 +105,8 @@ func (f *RegexpFilter) Set(filename string) error { // Enabled checks whether a certain check is enabled for a file. func (f *RegexpFilter) Enabled(check string, enabled bool, filename string) bool { for _, l := range f.lines { - if l.match.MatchString(filename) { + // Must match entire string. + if matchFullString(filename, l.match) { if e, ok := l.enabled[check]; ok { enabled = e } @@ -114,3 +114,16 @@ func (f *RegexpFilter) Enabled(check string, enabled bool, filename string) bool } return enabled } + +func matchFullString(str string, re *regexp.Regexp) bool { + loc := re.FindStringIndex(str) + if loc == nil { + // No match at all. + return false + } + if loc[1]-loc[0] < len(str) { + // Only matches a substring. + return false + } + return true +} diff --git a/hack/tools/logcheck/pkg/filter_test.go b/hack/tools/logcheck/pkg/filter_test.go index 115af49a..eee829a7 100644 --- a/hack/tools/logcheck/pkg/filter_test.go +++ b/hack/tools/logcheck/pkg/filter_test.go @@ -116,7 +116,11 @@ func TestParsing(t *testing.T) { }{ "invalid-regexp": { content: `structured [`, - expectError: filename + ":0: error parsing regexp: missing closing ]: `[$`", + expectError: filename + ":0: error parsing regexp: missing closing ]: `[`", + }, + "wildcard": { + content: `structured *`, + expectError: filename + ":0: error parsing regexp: missing argument to repetition operator: `*`", }, "invalid-line": { content: `structured .