From 0ed3a079805cddec218b40bd91d718cdd268975f Mon Sep 17 00:00:00 2001 From: kaiyan-sheng Date: Thu, 27 Aug 2020 07:59:56 -0600 Subject: [PATCH] Check host fields type before converting to common.MapStr (#20791) --- .../add_host_metadata/add_host_metadata.go | 29 +++++++++--- .../add_host_metadata_test.go | 46 +++++++++++++++++++ 2 files changed, 69 insertions(+), 6 deletions(-) diff --git a/libbeat/processors/add_host_metadata/add_host_metadata.go b/libbeat/processors/add_host_metadata/add_host_metadata.go index 2c419f840b9..69612bd651f 100644 --- a/libbeat/processors/add_host_metadata/add_host_metadata.go +++ b/libbeat/processors/add_host_metadata/add_host_metadata.go @@ -161,12 +161,29 @@ func skipAddingHostMetadata(event *beat.Event) bool { return false } - hostFieldsMap := hostFields.(common.MapStr) - // or if "name" is the only field, don't skip - hasName, _ := hostFieldsMap.HasKey("name") - if hasName && len(hostFieldsMap) == 1 { + switch m := hostFields.(type) { + case common.MapStr: + // if "name" is the only field, don't skip + hasName, _ := m.HasKey("name") + if hasName && len(m) == 1 { + return false + } + return true + case map[string]interface{}: + hostMapStr := common.MapStr(m) + // if "name" is the only field, don't skip + hasName, _ := hostMapStr.HasKey("name") + if hasName && len(m) == 1 { + return false + } + return true + case map[string]string: + // if "name" is the only field, don't skip + if m["name"] != "" && len(m) == 1 { + return false + } + return true + default: return false } - - return true } diff --git a/libbeat/processors/add_host_metadata/add_host_metadata_test.go b/libbeat/processors/add_host_metadata/add_host_metadata_test.go index 22efa527026..c41c7696635 100644 --- a/libbeat/processors/add_host_metadata/add_host_metadata_test.go +++ b/libbeat/processors/add_host_metadata/add_host_metadata_test.go @@ -357,6 +357,16 @@ func TestEventWithReplaceFieldsTrue(t *testing.T) { } func TestSkipAddingHostMetadata(t *testing.T) { + hostIDMap := map[string]string{} + hostIDMap["id"] = hostID + + hostNameMap := map[string]string{} + hostNameMap["name"] = hostName + + hostIDNameMap := map[string]string{} + hostIDNameMap["id"] = hostID + hostIDNameMap["name"] = hostName + cases := []struct { title string event beat.Event @@ -403,6 +413,42 @@ func TestSkipAddingHostMetadata(t *testing.T) { }, false, }, + { + "event with field type map[string]string hostID", + beat.Event{ + Fields: common.MapStr{ + "host": hostIDMap, + }, + }, + true, + }, + { + "event with field type map[string]string host name", + beat.Event{ + Fields: common.MapStr{ + "host": hostNameMap, + }, + }, + false, + }, + { + "event with field type map[string]string host ID and name", + beat.Event{ + Fields: common.MapStr{ + "host": hostIDNameMap, + }, + }, + true, + }, + { + "event with field type string", + beat.Event{ + Fields: common.MapStr{ + "host": "string", + }, + }, + false, + }, } for _, c := range cases {