|
| 1 | +package candle_binding |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "regexp" |
| 7 | + "strings" |
| 8 | + "time" |
| 9 | +) |
| 10 | + |
| 11 | +// RegexProviderConfig holds the configuration for the regex provider. |
| 12 | +type RegexProviderConfig struct { |
| 13 | + MaxPatterns int `yaml:"max_patterns"` |
| 14 | + MaxPatternLength int `yaml:"max_pattern_length"` |
| 15 | + MaxInputLength int `yaml:"max_input_length"` |
| 16 | + DefaultTimeoutMs int `yaml:"default_timeout_ms"` |
| 17 | + Patterns []RegexPattern `yaml:"patterns"` |
| 18 | +} |
| 19 | + |
| 20 | +// RegexPattern defines a single regex pattern. |
| 21 | +type RegexPattern struct { |
| 22 | + ID string `yaml:"id"` |
| 23 | + Pattern string `yaml:"pattern"` |
| 24 | + Flags string `yaml:"flags"` |
| 25 | + Category string `yaml:"category"` |
| 26 | +} |
| 27 | + |
| 28 | +// RegexProvider is a ReDoS-safe regex scanner. |
| 29 | +// It uses Go's built-in regexp package, which is based on RE2 and is not |
| 30 | +// vulnerable to regular expression denial of service attacks. |
| 31 | +type RegexProvider struct { |
| 32 | + compiled []*regexp.Regexp |
| 33 | + patterns []RegexPattern |
| 34 | + timeout time.Duration |
| 35 | + maxInputLength int |
| 36 | + testDelay time.Duration // For testing purposes |
| 37 | +} |
| 38 | + |
| 39 | +// MatchResult represents a single regex match. |
| 40 | +type MatchResult struct { |
| 41 | + PatternID string |
| 42 | + Category string |
| 43 | + Match string |
| 44 | + StartIndex int |
| 45 | + EndIndex int |
| 46 | +} |
| 47 | + |
| 48 | +// NewRegexProvider creates a new RegexProvider. |
| 49 | +func NewRegexProvider(cfg RegexProviderConfig, options ...func(*RegexProvider)) (*RegexProvider, error) { |
| 50 | + if len(cfg.Patterns) > cfg.MaxPatterns { |
| 51 | + return nil, fmt.Errorf("number of patterns (%d) exceeds max_patterns (%d)", len(cfg.Patterns), cfg.MaxPatterns) |
| 52 | + } |
| 53 | + |
| 54 | + compiled := make([]*regexp.Regexp, 0, len(cfg.Patterns)) |
| 55 | + for _, p := range cfg.Patterns { |
| 56 | + if len(p.Pattern) > cfg.MaxPatternLength { |
| 57 | + return nil, fmt.Errorf("pattern length for ID '%s' (%d) exceeds max_pattern_length (%d)", p.ID, len(p.Pattern), cfg.MaxPatternLength) |
| 58 | + } |
| 59 | + |
| 60 | + pattern := p.Pattern |
| 61 | + if strings.Contains(p.Flags, "i") { |
| 62 | + pattern = "(?i)" + pattern |
| 63 | + } |
| 64 | + |
| 65 | + re, err := regexp.Compile(pattern) |
| 66 | + if err != nil { |
| 67 | + return nil, fmt.Errorf("failed to compile pattern ID '%s': %w", p.ID, err) |
| 68 | + } |
| 69 | + compiled = append(compiled, re) |
| 70 | + } |
| 71 | + |
| 72 | + rp := &RegexProvider{ |
| 73 | + compiled: compiled, |
| 74 | + patterns: cfg.Patterns, |
| 75 | + timeout: time.Duration(cfg.DefaultTimeoutMs) * time.Millisecond, |
| 76 | + maxInputLength: cfg.MaxInputLength, |
| 77 | + } |
| 78 | + |
| 79 | + for _, option := range options { |
| 80 | + option(rp) |
| 81 | + } |
| 82 | + |
| 83 | + return rp, nil |
| 84 | +} |
| 85 | + |
| 86 | +// WithTestDelay is a functional option to add a delay for testing timeouts. |
| 87 | +func WithTestDelay(d time.Duration) func(*RegexProvider) { |
| 88 | + return func(rp *RegexProvider) { |
| 89 | + rp.testDelay = d |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +// Scan scans the input string for matches. |
| 94 | +// The scan is performed in a separate goroutine and is subject to a timeout. |
| 95 | +// The timeout check is performed between each pattern, so a single very slow |
| 96 | +// pattern can still block for longer than the timeout. However, Go's regex |
| 97 | +// engine is very fast and not vulnerable to ReDoS, so this is not a major |
| 98 | +// concern in practice. |
| 99 | +func (rp *RegexProvider) Scan(input string) ([]MatchResult, error) { |
| 100 | + if len(input) > rp.maxInputLength { |
| 101 | + return nil, fmt.Errorf("input length (%d) exceeds max_input_length (%d)", len(input), rp.maxInputLength) |
| 102 | + } |
| 103 | + |
| 104 | + ctx, cancel := context.WithTimeout(context.Background(), rp.timeout) |
| 105 | + defer cancel() |
| 106 | + |
| 107 | + resultChan := make(chan struct { |
| 108 | + matches []MatchResult |
| 109 | + err error |
| 110 | + }, 1) |
| 111 | + |
| 112 | + go func() { |
| 113 | + var matches []MatchResult |
| 114 | + for i, re := range rp.compiled { |
| 115 | + select { |
| 116 | + case <-ctx.Done(): |
| 117 | + // The context was cancelled, so we don't need to continue. |
| 118 | + return |
| 119 | + default: |
| 120 | + // Introduce a delay for testing purposes |
| 121 | + if rp.testDelay > 0 { |
| 122 | + time.Sleep(rp.testDelay) |
| 123 | + } |
| 124 | + |
| 125 | + locs := re.FindAllStringIndex(input, -1) |
| 126 | + for _, loc := range locs { |
| 127 | + matches = append(matches, MatchResult{ |
| 128 | + PatternID: rp.patterns[i].ID, |
| 129 | + Category: rp.patterns[i].Category, |
| 130 | + Match: input[loc[0]:loc[1]], |
| 131 | + StartIndex: loc[0], |
| 132 | + EndIndex: loc[1], |
| 133 | + }) |
| 134 | + } |
| 135 | + } |
| 136 | + } |
| 137 | + resultChan <- struct { |
| 138 | + matches []MatchResult |
| 139 | + err error |
| 140 | + }{matches, nil} |
| 141 | + }() |
| 142 | + |
| 143 | + select { |
| 144 | + case res := <-resultChan: |
| 145 | + return res.matches, res.err |
| 146 | + case <-ctx.Done(): |
| 147 | + return nil, fmt.Errorf("regex scan timed out after %v", rp.timeout) |
| 148 | + } |
| 149 | +} |
0 commit comments