diff --git a/pkg/alertcontext/alertcontext.go b/pkg/alertcontext/alertcontext.go index 0afcb2abd3f..0b38336a698 100644 --- a/pkg/alertcontext/alertcontext.go +++ b/pkg/alertcontext/alertcontext.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "net/http" + "reflect" "slices" "strconv" @@ -202,6 +203,10 @@ func EvalAlertContextRules(evt types.Event, match *types.MatchedRule, request *h } } default: + r := reflect.ValueOf(output) + if r.IsZero() || r.IsNil() { + continue + } val := fmt.Sprintf("%v", output) if val != "" && !slices.Contains(tmpContext[key], val) { tmpContext[key] = append(tmpContext[key], val) diff --git a/pkg/alertcontext/alertcontext_test.go b/pkg/alertcontext/alertcontext_test.go index b1572edd76b..9d9373bcd36 100644 --- a/pkg/alertcontext/alertcontext_test.go +++ b/pkg/alertcontext/alertcontext_test.go @@ -363,3 +363,49 @@ func TestAppsecEventToContext(t *testing.T) { assert.ElementsMatch(t, test.expectedResult, metas) } } + +func TestEvalAlertContextRules(t *testing.T) { + tests := []struct { + name string + contextToSend map[string][]string + event types.Event + match types.MatchedRule + req *http.Request + expectedResult map[string][]string + expectedErrLen int + }{ + { + name: "no appsec match", + contextToSend: map[string][]string{ + "source_ip": {"evt.Parsed.source_ip"}, + "id": {"match.id"}, + }, + event: types.Event{ + Parsed: map[string]string{ + "source_ip": "1.2.3.4", + "source_machine": "mymachine", + "uri": "/test/test/test/../../../../../../../../", + }, + }, + expectedResult: map[string][]string{ + "source_ip": {"1.2.3.4"}, + "id": {}, + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + contextDict := make(map[string][]string) + + alertContext = Context{} + if err := NewAlertContext(test.contextToSend, 100); err != nil { + t.Fatalf("failed to compile %s: %s", test.name, err) + } + + errs := EvalAlertContextRules(test.event, &test.match, test.req, contextDict) + assert.Len(t, errs, test.expectedErrLen) + assert.Equal(t, test.expectedResult, contextDict) + }) + } +}