Skip to content

Commit

Permalink
[CWS] small optimizations to regex parsing in SECL (#31792)
Browse files Browse the repository at this point in the history
  • Loading branch information
paulcacheux authored Dec 9, 2024
1 parent b027f60 commit 2491564
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 12 deletions.
4 changes: 2 additions & 2 deletions pkg/security/secl/compiler/eval/strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ type RegexpStringMatcher struct {
re *regexp.Regexp
}

var stringBigOrRe = regexp.MustCompile(`^\.\*\(([a-zA-Z_|]+)\)\.\*$`)
var stringBigOrRe = regexp.MustCompile(`^(?:\.\*)?\(([a-zA-Z_|]+)\)(?:\.\*)?$`)

// Compile a regular expression based pattern
func (r *RegexpStringMatcher) Compile(pattern string, caseInsensitive bool) error {
Expand All @@ -135,7 +135,7 @@ func (r *RegexpStringMatcher) Compile(pattern string, caseInsensitive bool) erro
}
}

if caseInsensitive {
if caseInsensitive && !strings.HasPrefix(pattern, "(?i)") {
pattern = "(?i)" + pattern
}

Expand Down
38 changes: 28 additions & 10 deletions pkg/security/secl/compiler/eval/strings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,17 +260,35 @@ func TestRegexp(t *testing.T) {
}

func BenchmarkRegexpEvaluator(b *testing.B) {
pattern := ".*(restore|recovery|readme|instruction|how_to|ransom).*"
b.Run("with stars", func(b *testing.B) {
pattern := ".*(restore|recovery|readme|instruction|how_to|ransom).*"

var matcher RegexpStringMatcher
if err := matcher.Compile(pattern, false); err != nil {
b.Fatal(err)
}
var matcher RegexpStringMatcher
if err := matcher.Compile(pattern, false); err != nil {
b.Fatal(err)
}

b.ResetTimer()
for i := 0; i < b.N; i++ {
if !matcher.Matches("123ransom456.txt") {
b.Fatal("unexpected result")
}
}
})

b.ResetTimer()
for i := 0; i < b.N; i++ {
if !matcher.Matches("123ransom456.txt") {
b.Fatal("unexpected result")
b.Run("without stars", func(b *testing.B) {
pattern := "(restore|recovery|readme|instruction|how_to|ransom)"

var matcher RegexpStringMatcher
if err := matcher.Compile(pattern, false); err != nil {
b.Fatal(err)
}

b.ResetTimer()
for i := 0; i < b.N; i++ {
if !matcher.Matches("123ransom456.txt") {
b.Fatal("unexpected result")
}
}
}
})
}

0 comments on commit 2491564

Please sign in to comment.