Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 6 additions & 20 deletions internal/codeguard/checks/security/security_regex_cache.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,11 @@
package security

import (
"regexp"
"sync"
)
import "regexp"

// dynamicPatternCache memoizes regexes compiled from runtime-derived text such
// as import aliases, namespaces, and module names. The same handful of aliases
// and modules recur across many files in a project, so compiling each distinct
// pattern once and reusing it avoids recompiling identical regexes per file.
var dynamicPatternCache sync.Map // map[string]*regexp.Regexp

// compileDynamicPattern returns the compiled form of expr, reusing a previously
// compiled instance when one exists. The expressions passed here are always
// valid (fixed fragments plus regexp.QuoteMeta-escaped input), so it mirrors the
// regexp.MustCompile contract and panics on a genuinely malformed pattern.
// compileDynamicPattern compiles expressions built from runtime-derived text.
// Do not cache these expressions globally: aliases and module names originate
// in scanned source, so an unbounded process-wide cache would retain
// attacker-controlled entries across scans in long-lived processes.
func compileDynamicPattern(expr string) *regexp.Regexp {
if cached, ok := dynamicPatternCache.Load(expr); ok {
return cached.(*regexp.Regexp)
}
compiled := regexp.MustCompile(expr)
actual, _ := dynamicPatternCache.LoadOrStore(expr, compiled)
return actual.(*regexp.Regexp)
return regexp.MustCompile(expr)
}
Loading