Skip to content

Commit

Permalink
logcheck: fix detection of invalid * regexp in filter
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
pohly committed Mar 23, 2022
1 parent c697110 commit 5079582
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
19 changes: 16 additions & 3 deletions hack/tools/logcheck/pkg/filter.go
Expand Up @@ -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)
}
Expand All @@ -106,11 +105,25 @@ 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
}
}
}
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
}
6 changes: 5 additions & 1 deletion hack/tools/logcheck/pkg/filter_test.go
Expand Up @@ -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 .
Expand Down

0 comments on commit 5079582

Please sign in to comment.