Skip to content

Commit

Permalink
fix: update engine_regexp compile to use '{','}' as start, end delimi…
Browse files Browse the repository at this point in the history
…ters if the regexp contains possessive match or lookbehind syntax.
  • Loading branch information
cmmoran committed Jan 31, 2024
1 parent c064f20 commit 9b67b7c
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 2 deletions.
16 changes: 14 additions & 2 deletions rule/engine_regexp.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
package rule

import (
"errors"
"hash/crc64"
"strings"

"github.com/pkg/errors"

"github.com/dlclark/regexp2"

Expand All @@ -23,7 +25,17 @@ func (re *regexpMatchingEngine) compile(pattern string) error {
re.table = crc64.MakeTable(polynomial)
}
if checksum := crc64.Checksum([]byte(pattern), re.table); checksum != re.checksum {
compiled, err := compiler.CompileRegex(pattern, '<', '>')
startDelim := byte('<')
endDelim := byte('>')
if strings.Contains(pattern, "(?>") || strings.Contains(pattern, "(?<") {
if strings.ContainsRune(pattern, '{') && strings.ContainsRune(pattern, '}') {
startDelim = byte('{')
endDelim = byte('}')
} else {
return errors.Errorf("attempted to use regex 'possessive match' or regex 'lookbehind' without changing delimiters from '<...>' to '{...}' in: %s", pattern)
}
}
compiled, err := compiler.CompileRegex(pattern, startDelim, endDelim)
if err != nil {
return err
}
Expand Down
45 changes: 45 additions & 0 deletions rule/engine_regexp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,24 @@ func TestFindStringSubmatch(t *testing.T) {
want: nil,
wantErr: true,
},
{
name: "bad lookbehind (wrong delimiters)",
args: args{
pattern: `urn:foo:<(?<=foo:)foobar>`,
matchAgainst: "urn:foo:foobar",
},
want: nil,
wantErr: true,
},
{
name: "bad possessive (wrong delimiters)",
args: args{
pattern: `urn:foo:<(?>=foo:)foobar>`,
matchAgainst: "urn:foo:foobar",
},
want: nil,
wantErr: true,
},
{
name: "one group",
args: args{
Expand Down Expand Up @@ -56,6 +74,33 @@ func TestFindStringSubmatch(t *testing.T) {
want: []string{"bar"},
wantErr: false,
},
{
name: "positive lookbehind (?<=foo)bar",
args: args{
pattern: `urn:foo:{(?<=foo:)foobar}`,
matchAgainst: "urn:foo:foobar",
},
want: []string{"foobar"},
wantErr: false,
},
{
name: "negative lookbehind (?<!boo)foobar",
args: args{
pattern: `urn:foo:{(?<!boo:)foobar}`,
matchAgainst: "urn:foo:foobar",
},
want: []string{"foobar"},
wantErr: false,
},
{
name: "negative lookbehind (?<!boo)foobar, not match",
args: args{
pattern: `urn:foo:{(?<!boo:)foobar}`,
matchAgainst: "urn:boo:foobar",
},
want: nil,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down

0 comments on commit 9b67b7c

Please sign in to comment.