From 4e752e6aa8df2a83f0bc92a82089ef9d38cfb758 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. --- logcheck/pkg/filter.go | 19 ++++++++++++++++--- logcheck/pkg/filter_test.go | 6 +++++- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/logcheck/pkg/filter.go b/logcheck/pkg/filter.go index 231a38cb8..c2ad90925 100644 --- a/logcheck/pkg/filter.go +++ b/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/logcheck/pkg/filter_test.go b/logcheck/pkg/filter_test.go index 115af49af..eee829a7b 100644 --- a/logcheck/pkg/filter_test.go +++ b/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 .