Skip to content

Commit ea24496

Browse files
authored
feat: add WAFWithRules interface with RulesCount() (#1492)
Add WAFWithRules interface with RulesCount()
1 parent 70e8933 commit ea24496

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

experimental/waf.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,11 @@ type Options = corazawaf.Options
1515
type WAFWithOptions interface {
1616
NewTransactionWithOptions(Options) types.Transaction
1717
}
18+
19+
// WAFWithRules is an interface that allows to inspect the number of
20+
// rules loaded in a WAF instance. This is useful for connectors that
21+
// need to verify rule loading or implement configuration caching.
22+
type WAFWithRules interface {
23+
// RulesCount returns the number of rules in this WAF.
24+
RulesCount() int
25+
}

waf.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,3 +154,8 @@ func (w wafWrapper) NewTransactionWithID(id string) types.Transaction {
154154
func (w wafWrapper) NewTransactionWithOptions(opts corazawaf.Options) types.Transaction {
155155
return w.waf.NewTransactionWithOptions(opts)
156156
}
157+
158+
// RulesCount returns the number of rules in this WAF.
159+
func (w wafWrapper) RulesCount() int {
160+
return w.waf.Rules.Count()
161+
}

waf_test.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,11 @@ import (
1313
"github.com/corazawaf/coraza/v3/types"
1414
)
1515

16+
// wafWithRules mirrors experimental.WAFWithRules for testing without import cycle.
17+
type wafWithRules interface {
18+
RulesCount() int
19+
}
20+
1621
func TestRequestBodyLimit(t *testing.T) {
1722
testCases := map[string]struct {
1823
expectedErr error
@@ -178,3 +183,33 @@ func TestPopulateAuditLog(t *testing.T) {
178183
})
179184
}
180185
}
186+
187+
func TestRulesCount(t *testing.T) {
188+
waf, err := NewWAF(NewWAFConfig())
189+
if err != nil {
190+
t.Fatal(err)
191+
}
192+
193+
rules, ok := waf.(wafWithRules)
194+
if !ok {
195+
t.Fatal("WAF does not implement WAFWithRules")
196+
}
197+
if rules.RulesCount() != 0 {
198+
t.Fatalf("expected 0 rules, got %d", rules.RulesCount())
199+
}
200+
201+
waf, err = NewWAF(NewWAFConfig().
202+
WithDirectives(`SecRule REMOTE_ADDR "127.0.0.1" "id:1,phase:1,deny,status:403"`).
203+
WithDirectives(`SecRule REQUEST_URI "/test" "id:2,phase:1,deny,status:403"`))
204+
if err != nil {
205+
t.Fatal(err)
206+
}
207+
208+
rules, ok = waf.(wafWithRules)
209+
if !ok {
210+
t.Fatal("WAF does not implement WAFWithRules")
211+
}
212+
if rules.RulesCount() != 2 {
213+
t.Fatalf("expected 2 rules, got %d", rules.RulesCount())
214+
}
215+
}

0 commit comments

Comments
 (0)