Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[receiver/splunkhec] Drop events when nested indexed fields are present #18068

Merged
merged 3 commits into from
Feb 2, 2023
Merged
Show file tree
Hide file tree
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
16 changes: 16 additions & 0 deletions .chloggen/handle_nested_map_splunkhec_receiver.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: bug_fix

# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
component: receiver/splunkhec

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Return 400 status code when nested indextime fields are present

# One or more tracking issues related to the change
issues: [17308]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext:
24 changes: 23 additions & 1 deletion receiver/splunkhecreceiver/receiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ const (
responseErrInternalServerError = "Internal Server Error"
responseErrUnsupportedMetricEvent = "Unsupported metric event"
responseErrUnsupportedLogEvent = "Unsupported log event"

responseErrHandlingIndexedFields = `{"text":"Error in handling indexed fields","code":15,"invalid-event-number":%d}`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any reason to have a JSON formatted string here with substitution?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, splunk returns the message in JSON format that I have used for responseErrHandlingIndexedFields. And invalid-event-number points to the index of the event where the problem is.

failRequest method sets Content-Type as application/json but response body is raw text.

resp.Header().Add("Content-Type", "application/json")

We also need to change other err messages to JSON format with respect to the actual splunk response. I'll create a separate issue for that.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Huh, interesting. Thanks for checking that for me.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Created #18097

// Centralizing some HTTP and related string constants.
gzipEncoding = "gzip"
httpContentEncodingHeader = "Content-Encoding"
Expand Down Expand Up @@ -341,6 +341,13 @@ func (r *splunkReceiver) handleReq(resp http.ResponseWriter, req *http.Request)
r.failRequest(ctx, resp, http.StatusBadRequest, errUnmarshalBodyRespBody, len(events), err)
return
}

for _, v := range msg.Fields {
if !isFlatJSONField(v) {
r.failRequest(ctx, resp, http.StatusBadRequest, []byte(fmt.Sprintf(responseErrHandlingIndexedFields, len(events))), len(events), nil)
return
}
}
if msg.IsMetric() {
if r.metricsConsumer == nil {
r.failRequest(ctx, resp, http.StatusBadRequest, errUnsupportedMetricEvent, len(events), err)
Expand Down Expand Up @@ -458,3 +465,18 @@ func initJSONResponse(s string) []byte {
}
return respBody
}

func isFlatJSONField(field interface{}) bool {
switch value := field.(type) {
case map[string]interface{}:
return false
case []interface{}:
for _, v := range value {
switch v.(type) {
case map[string]interface{}, []interface{}:
return false
}
}
}
return true
}
72 changes: 72 additions & 0 deletions receiver/splunkhecreceiver/receiver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"testing"
"time"

jsoniter "github.com/json-iterator/go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/collector/component"
Expand Down Expand Up @@ -1004,6 +1005,77 @@ func Test_splunkhecreceiver_handleHealthPath(t *testing.T) {
assert.Equal(t, 200, resp.StatusCode)
}

func Test_splunkhecreceiver_handle_nested_fields(t *testing.T) {
tests := []struct {
name string
field interface{}
success bool
}{
{
name: "map",
field: map[string]interface{}{},
success: false,
},
{
name: "flat_array",
field: []interface{}{1, 2, 3},
success: true,
},
{
name: "nested_array",
hvaghani221 marked this conversation as resolved.
Show resolved Hide resolved
field: []interface{}{1, []interface{}{1, 2}},
success: false,
},
{
name: "array_of_map",
field: []interface{}{
map[string]interface{}{
"key": "value",
},
},
success: false,
},
{
name: "int",
field: int(0),
success: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
config := createDefaultConfig().(*Config)
sink := new(consumertest.LogsSink)
rcv, err := newLogsReceiver(receivertest.NewNopCreateSettings(), *config, sink)
assert.NoError(t, err)

r := rcv.(*splunkReceiver)
assert.NoError(t, r.Start(context.Background(), componenttest.NewNopHost()))
defer func() {
assert.NoError(t, r.Shutdown(context.Background()))
}()
currentTime := float64(time.Now().UnixNano()) / 1e6
event := buildSplunkHecMsg(currentTime, 3)
event.Fields["nested_map"] = tt.field
msgBytes, err := jsoniter.Marshal(event)
require.NoError(t, err)
req := httptest.NewRequest("POST", "http://localhost/services/collector", bytes.NewReader(msgBytes))

w := httptest.NewRecorder()
r.handleReq(w, req)

if tt.success {
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, 1, sink.LogRecordCount())
} else {
assert.Equal(t, http.StatusBadRequest, w.Code)
assert.Equal(t, fmt.Sprintf(responseErrHandlingIndexedFields, 0), w.Body.String())
}

})
}
}

func BenchmarkHandleReq(b *testing.B) {
config := createDefaultConfig().(*Config)
config.Endpoint = "localhost:0"
Expand Down