From f9508938ac04260d9226b0b270abdb1e1df41fa6 Mon Sep 17 00:00:00 2001 From: Tiago Queiroz Date: Thu, 22 Oct 2026 09:47:46 -0400 Subject: [PATCH 1/2] Restore Heartbeat monitor state in OTel mode (#16902) Restore Heartbeat monitor state in OTel mode Configure output-scoped Elasticsearch authentication for Heartbeat receivers and delegate transport settings to beatsauth. Assisted-by: Cursor, Model: GPT-5.6 Terra & Sol (High) Assisted-by: Cursor, Model: Gemini 3.8 Flash (High) (cherry picked from commit fe0cdc3dcad3cdec395c726cf7189fa035a36674) # Conflicts: # internal/pkg/otel/translate/otelconfig_test.go --- ...-heartbeat-monitor-state-in-otel-mode.yaml | 4 + internal/pkg/otel/translate/otelconfig.go | 18 +- .../pkg/otel/translate/otelconfig_test.go | 138 +++++++++++- .../otel/translate/output_elasticsearch.go | 162 ++++++++++++-- .../translate/output_elasticsearch_test.go | 201 ++++++++++++++++++ .../testdata/certs/client-unencrypted.key | 28 +++ .../ess/heartbeat_monitoring_test.go | 73 +++++-- 7 files changed, 593 insertions(+), 31 deletions(-) create mode 100644 changelog/fragments/1790701465-restore-heartbeat-monitor-state-in-otel-mode.yaml create mode 100644 internal/pkg/otel/translate/testdata/certs/client-unencrypted.key diff --git a/changelog/fragments/1790701465-restore-heartbeat-monitor-state-in-otel-mode.yaml b/changelog/fragments/1790701465-restore-heartbeat-monitor-state-in-otel-mode.yaml new file mode 100644 index 00000000000..08bd9f69328 --- /dev/null +++ b/changelog/fragments/1790701465-restore-heartbeat-monitor-state-in-otel-mode.yaml @@ -0,0 +1,4 @@ +kind: bug-fix +summary: Restore Heartbeat monitor state in OTel mode +component: elastic-agent +issue: https://github.com/elastic/elastic-agent/issues/16284 diff --git a/internal/pkg/otel/translate/otelconfig.go b/internal/pkg/otel/translate/otelconfig.go index c62b2d58945..b2ae580d3f6 100644 --- a/internal/pkg/otel/translate/otelconfig.go +++ b/internal/pkg/otel/translate/otelconfig.go @@ -476,6 +476,11 @@ func getReceiversConfigForComponent( if comp.OutputType == "kafka" || comp.OutputType == "logstash" { sharedConfig["include_metadata"] = true } + if beatName == "heartbeat" && comp.OutputType == "elasticsearch" { + sharedConfig["monitor_state"] = map[string]any{ + "elasticsearch": getBeatsAuthExtensionID(comp.OutputName).String(), + } + } if beatName == "filebeat" && fbfeatures.IsElasticsearchStateStoreEnabled() { sharedConfig["storage"] = elasticsearchStateStoreExtensionName } @@ -645,7 +650,18 @@ func getExporterConfigForComponent(comp *component.Component, exporterType otelc if !ok { return nil, nil, nil, nil, nil } - return unitToExporterConfig(outputUnit, comp.OutputName, exporterType, logger) + + exporterCfg, queueCfg, extensionCfg, processors, err = unitToExporterConfig( + outputUnit, + comp.OutputName, + exporterType, + logger, + ) + if err != nil { + return nil, nil, nil, nil, err + } + + return exporterCfg, queueCfg, extensionCfg, processors, nil } // getSignalForComponent returns the otel signal for the given component. Currently, this is always logs, even for diff --git a/internal/pkg/otel/translate/otelconfig_test.go b/internal/pkg/otel/translate/otelconfig_test.go index 073eae06524..de27006f9b9 100644 --- a/internal/pkg/otel/translate/otelconfig_test.go +++ b/internal/pkg/otel/translate/otelconfig_test.go @@ -407,7 +407,12 @@ func TestGetOtelConfig(t *testing.T) { expectedExtensionConfig := func(extra ...extraParams) map[string]any { finalOutput := map[string]any{ + "auth": map[string]any{ + "password": "password", + "username": "elastic", + }, "continue_on_error": true, + "endpoints": []string{"http://localhost:9200"}, "idle_connection_timeout": "3s", "proxy_disable": false, "proxy_url": "https://example.com", @@ -592,6 +597,9 @@ func TestGetOtelConfig(t *testing.T) { // expects component id expectedHeartbeatReceiverConfig := func(id string) map[string]any { cfg := beatReceiverBaseConfig(id, "heartbeat", "synthetics/http") + cfg["monitor_state"] = map[string]any{ + "elasticsearch": "beatsauth/_agent-component/default", + } cfg["heartbeat"] = map[string]any{ "monitors": []map[string]any{ { @@ -2080,7 +2088,9 @@ func TestGetOtelConfig(t *testing.T) { "heartbeatreceiver/_agent-component/heartbeat-default/heartbeat-unit-test-1": expectedHeartbeatReceiverConfig("heartbeat-default"), }, "service": map[string]any{ - "extensions": []any{"beatsauth/_agent-component/default"}, + "extensions": []any{ + "beatsauth/_agent-component/default", + }, "pipelines": map[string]any{ "logs/_agent-component/heartbeat-default": map[string][]string{ "exporters": {"elasticsearch/_agent-component/default"}, @@ -3541,6 +3551,7 @@ func TestGetReceiversConfigForComponent(t *testing.T) { } } +<<<<<<< HEAD // TestGetReceiversConfigForComponentNoEnabledStreams verifies that a component with no // enabled streams (either no input units, or input units with nil config) falls back to // a no-op receiver instead of an error, so the pipeline stays valid and the component @@ -3608,14 +3619,135 @@ func TestGetReceiversConfigForComponentNoEnabledStreams(t *testing.T) { }, }, expectedReceiverID: GetReceiverID(nopType, "nil-config-test-id"), +======= +func TestGetReceiversConfigForComponentHeartbeatElasticsearchAuth(t *testing.T) { + newHeartbeatComponent := func(outputType string, singleReceiver bool) *component.Component { + return &component.Component{ + ID: "heartbeat-auth-test-id", + InputType: "synthetics/http", + OutputType: outputType, + OutputName: "default", + InputSpec: &component.InputRuntimeSpec{ + BinaryName: "elastic-otel-collector", + Spec: component.InputSpec{ + Name: "synthetics/http", + Command: &component.CommandSpec{ + Args: []string{"heartbeat"}, + }, + SingleReceiver: singleReceiver, + }, + }, + Units: []component.Unit{ + { + ID: "heartbeat-auth-test-id-unit", + Type: client.UnitTypeInput, + Config: component.MustExpectedConfig(map[string]any{ + "id": "test", + "use_output": "default", + "type": "synthetics/http", + "streams": []any{ + map[string]any{ + "id": "http-1", + "data_stream": map[string]any{ + "dataset": "synthetics.http", + }, + "urls": []any{"https://example.com/one"}, + "schedule": "@every 5s", + }, + map[string]any{ + "id": "http-2", + "data_stream": map[string]any{ + "dataset": "synthetics.http", + }, + "urls": []any{"https://example.com/two"}, + "schedule": "@every 10s", + }, + }, + }), + }, + }, + } + } + + tests := []struct { + name string + outputType string + singleReceiver bool + expectedReceiverIDs []string + expectedAuth string + }{ + { + name: "elasticsearch per-stream receivers", + outputType: "elasticsearch", + singleReceiver: false, + expectedReceiverIDs: []string{ + "heartbeatreceiver/_agent-component/heartbeat-auth-test-id/unit-http-1", + "heartbeatreceiver/_agent-component/heartbeat-auth-test-id/unit-http-2", + }, + expectedAuth: "beatsauth/_agent-component/default", + }, + { + name: "elasticsearch single receiver", + outputType: "elasticsearch", + singleReceiver: true, + expectedReceiverIDs: []string{ + "heartbeatreceiver/_agent-component/heartbeat-auth-test-id/single", + }, + expectedAuth: "beatsauth/_agent-component/default", + }, + { + name: "logstash", + outputType: "logstash", + singleReceiver: false, + expectedReceiverIDs: []string{ + "heartbeatreceiver/_agent-component/heartbeat-auth-test-id/unit-http-1", + "heartbeatreceiver/_agent-component/heartbeat-auth-test-id/unit-http-2", + }, + }, + { + name: "kafka", + outputType: "kafka", + singleReceiver: false, + expectedReceiverIDs: []string{ + "heartbeatreceiver/_agent-component/heartbeat-auth-test-id/unit-http-1", + "heartbeatreceiver/_agent-component/heartbeat-auth-test-id/unit-http-2", + }, +>>>>>>> fe0cdc3 (Restore Heartbeat monitor state in OTel mode (#16902)) }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { +<<<<<<< HEAD result, err := getReceiversConfigForComponent(tt.component, nil, nil) require.NoError(t, err) assert.Equal(t, map[string]any{tt.expectedReceiverID.String(): map[string]any{}}, result) +======= + result, err := getReceiversConfigForComponent( + newHeartbeatComponent(tt.outputType, tt.singleReceiver), + &info.AgentInfo{}, + nil, + nil, + ) + require.NoError(t, err, "heartbeat receiver translation must succeed") + require.Len(t, result, len(tt.expectedReceiverIDs), "translation must generate the expected receiver count") + + for _, receiverID := range tt.expectedReceiverIDs { + require.Contains(t, result, receiverID, "translation must generate receiver %q", receiverID) + } + + for receiverID, rawConfig := range result { + receiverConfig, ok := rawConfig.(map[string]any) + require.True(t, ok, "receiver %q config must be a map", receiverID) + if tt.expectedAuth == "" { + assert.NotContains(t, receiverConfig, "monitor_state", "receiver %q must omit monitor state for %s output", receiverID, tt.outputType) + continue + } + monitorState, ok := receiverConfig["monitor_state"].(map[string]any) + require.True(t, ok, "receiver %q monitor state config must be a map", receiverID) + assert.Equal(t, tt.expectedAuth, monitorState["elasticsearch"], "receiver %q must reference the output-scoped Elasticsearch auth extension", receiverID) + } +>>>>>>> fe0cdc3 (Restore Heartbeat monitor state in OTel mode (#16902)) }) } } @@ -4263,6 +4395,7 @@ func TestUnitToExporterConfig(t *testing.T) { expectedExtensionCfg: map[string]any{ "beatsauth/_agent-component/default": map[string]any{ "continue_on_error": true, + "endpoints": []string{"http://es:9200"}, "idle_connection_timeout": "3s", "proxy_disable": false, "timeout": "1m30s", @@ -4302,6 +4435,7 @@ func TestUnitToExporterConfig(t *testing.T) { expectedExtensionCfg: map[string]any{ "beatsauth/_agent-component/default": map[string]any{ "continue_on_error": true, + "endpoints": []string{"http://es:9200"}, "idle_connection_timeout": "3s", "proxy_disable": false, "timeout": "1m30s", @@ -4333,6 +4467,7 @@ func TestUnitToExporterConfig(t *testing.T) { expectedExtensionCfg: map[string]any{ "beatsauth/_agent-component/default": map[string]any{ "continue_on_error": true, + "endpoints": []string{"http://es:9200"}, "idle_connection_timeout": "3s", "proxy_disable": false, "timeout": "1m30s", @@ -4368,6 +4503,7 @@ func TestUnitToExporterConfig(t *testing.T) { expectedExtensionCfg: map[string]any{ "beatsauth/_agent-component/default": map[string]any{ "continue_on_error": true, + "endpoints": []string{"http://es:9200"}, "idle_connection_timeout": "3s", "proxy_disable": false, "timeout": "5m", diff --git a/internal/pkg/otel/translate/output_elasticsearch.go b/internal/pkg/otel/translate/output_elasticsearch.go index aa7eeb34e0d..13600b9e133 100644 --- a/internal/pkg/otel/translate/output_elasticsearch.go +++ b/internal/pkg/otel/translate/output_elasticsearch.go @@ -8,6 +8,7 @@ import ( "encoding/base64" "errors" "fmt" + "maps" "net/http" "net/url" "slices" @@ -16,6 +17,7 @@ import ( "github.com/go-viper/mapstructure/v2" otelcomponent "go.opentelemetry.io/collector/component" + "github.com/elastic/beats/v7/libbeat/cloudid" "github.com/elastic/beats/v7/libbeat/common" "github.com/elastic/beats/v7/libbeat/outputs" "github.com/elastic/beats/v7/libbeat/outputs/elasticsearch" @@ -137,6 +139,14 @@ var defaultOptions = esToOTelOptions{ func ESToOTelConfig(output *config.C, outputName string, logger *logp.Logger) (exporterCfg map[string]any, processorCfg map[string]any, extensionCfg map[string]any, err error) { escfg := defaultOptions + // Cloud resolution returns a copy, but effective queue settings must be + // written back for unitToExporterConfig. + originalOutput := output + output, err = resolveElasticsearchOutputCloudConfig(output) + if err != nil { + return nil, nil, nil, err + } + // check for unsupported config err = checkUnsupportedConfig(output) if err != nil { @@ -213,6 +223,19 @@ func ESToOTelConfig(output *config.C, outputName string, logger *logp.Logger) (e } } + // unitToExporterConfig promotes the effective output queue into the receiver + // configuration after translation. Preserve that write-back while keeping + // Cloud ID resolution isolated from the policy-derived output config. + if output.HasField("queue") { + queueConfig, err := output.Child("queue", -1) + if err != nil { + return nil, nil, nil, fmt.Errorf("failed reading effective output queue config: %w", err) + } + if err := originalOutput.SetChild("queue", -1, queueConfig); err != nil { + return nil, nil, nil, fmt.Errorf("failed updating effective output queue config: %w", err) + } + } + unpackedMap := make(map[string]any) // unpack and validate ES config if err := output.Unpack(&unpackedMap); err != nil { @@ -238,7 +261,7 @@ func ESToOTelConfig(output *config.C, outputName string, logger *logp.Logger) (e return nil, nil, nil, err } - hosts, err := getURL(escfg, output) + hosts, err := getURL(escfg.ElasticsearchConfig, output) if err != nil { return nil, nil, nil, fmt.Errorf("error creating hosts:%w", err) } @@ -401,7 +424,7 @@ func getRetryConfig(escfg esToOTelOptions) map[string]any { return retryCfg } -func getURL(escfg esToOTelOptions, output *config.C) ([]string, error) { +func getURL(escfg elasticsearch.ElasticsearchConfig, output *config.C) ([]string, error) { // Create url using host name, protocol and path outputHosts, err := outputs.ReadHostList(output) if err != nil { @@ -414,29 +437,98 @@ func getURL(escfg esToOTelOptions, output *config.C) ([]string, error) { if err != nil { return nil, fmt.Errorf("cannot generate ES URL from host %w", err) } + hostURL, err := url.Parse(esURL) + if err != nil { + return nil, fmt.Errorf("cannot parse generated Elasticsearch URL: %w", err) + } + if hostURL.User != nil { + return nil, errors.New("credentials in Elasticsearch host URLs are unsupported; configure username and password separately") + } if !slices.Contains(hosts, esURL) { hosts = append(hosts, esURL) } } if len(escfg.Params) != 0 { - // convert params to map[string][]string - params := make(map[string][]string, 0) - for key, value := range escfg.Params { - params[key] = []string{value} - } - - decodedParam := url.Values(params) - // It is enough to add params as encoded query to any one host - // Elasticsearch exporter will make sure to add these for every outgoing request + // Each endpoint may be selected independently, so every URL needs the output parameters. for i := range hosts { - hosts[i] = strings.Join([]string{hosts[i], decodedParam.Encode()}, "?") + hostURL, err := url.Parse(hosts[i]) + if err != nil { + return nil, fmt.Errorf("cannot parse generated Elasticsearch URL %q: %w", hosts[i], err) + } + query := hostURL.Query() + for key, value := range escfg.Params { + query.Set(key, value) + } + hostURL.RawQuery = query.Encode() + hosts[i] = hostURL.String() } } return hosts, nil } +// resolveElasticsearchOutputCloudConfig returns an independently owned, +// environment-resolved output config and applies output-scoped Cloud ID fields +// without changing the policy-derived source map. +func resolveElasticsearchOutputCloudConfig(output *config.C) (*config.C, error) { + var resolvedMap map[string]any + if err := output.Unpack(&resolvedMap); err != nil { + return nil, fmt.Errorf("failed resolving Elasticsearch output config: %w", err) + } + resolvedOutput, err := config.NewConfigFrom(resolvedMap) + if err != nil { + return nil, fmt.Errorf("failed copying Elasticsearch output config: %w", err) + } + + cloudID, err := firstConfiguredString(resolvedOutput, "cloud_id", "cloud.id") + if err != nil { + return nil, err + } + cloudAuth, err := firstConfiguredString(resolvedOutput, "cloud_auth", "cloud.auth") + if err != nil { + return nil, err + } + if cloudID == "" { + if cloudAuth != "" { + return nil, errors.New("cloud_auth is configured but cloud_id is empty") + } + return resolvedOutput, nil + } + + cloudConfig, err := cloudid.NewCloudID(cloudID, cloudAuth) + if err != nil { + return nil, fmt.Errorf("invalid cloud_id: %w", err) + } + resolvedMap["hosts"] = []string{cloudConfig.ElasticsearchURL()} + if cloudAuth != "" { + resolvedMap["username"] = cloudConfig.Username() + resolvedMap["password"] = cloudConfig.Password() + } + + resolvedOutput, err = config.NewConfigFrom(resolvedMap) + if err != nil { + return nil, fmt.Errorf("failed applying cloud_id to Elasticsearch output config: %w", err) + } + return resolvedOutput, nil +} + +func firstConfiguredString(cfg *config.C, fields ...string) (string, error) { + for _, field := range fields { + if !cfg.HasField(field) { + continue + } + value, err := cfg.String(field, -1) + if err != nil { + return "", fmt.Errorf("%s must be a string: %w", field, err) + } + if value != "" { + return value, nil + } + } + return "", nil +} + // getBeatsAuthExtensionID returns the id for beatsauth extension // outputName here is name of the output defined in elastic-agent.yml. For ex: default, monitoring func getBeatsAuthExtensionID(outputName string) otelcomponent.ID { @@ -444,8 +536,8 @@ func getBeatsAuthExtensionID(outputName string) otelcomponent.ID { return otelcomponent.NewIDWithName(otelcomponent.MustNewType(BeatsAuthExtensionType), extensionName) } -// getBeatsAuthExtensionConfig sets http transport settings on beatsauth -// this is only required for elasticsearch output +// getBeatsAuthExtensionConfig translates an Elasticsearch output into the +// beatsauth configuration shared by the Elasticsearch exporter and Heartbeat. func getBeatsAuthExtensionConfig(outputCfg *config.C) (map[string]any, error) { authSettings := beatsauthextension.BeatsAuthConfig{ Transport: elasticsearch.ESDefaultTransportSettings(), @@ -485,6 +577,48 @@ func getBeatsAuthExtensionConfig(outputCfg *config.C) (map[string]any, error) { // required to make the extension not cause the collector to fail and exit on startup newMap["continue_on_error"] = true + esConfig := elasticsearch.DefaultConfig() + if err := outputCfg.Unpack(&esConfig); err != nil { + return nil, fmt.Errorf("failed unpacking Elasticsearch connection config: %w", err) + } + if err := esConfig.Validate(); err != nil { + return nil, fmt.Errorf("invalid Elasticsearch connection config: %w", err) + } + + if outputCfg.HasField("hosts") || outputCfg.HasField("cloud_id") || outputCfg.HasField("cloud.id") { + endpoints, err := getURL(esConfig, outputCfg) + if err != nil { + return nil, fmt.Errorf("error creating beatsauth endpoints: %w", err) + } + newMap["endpoints"] = endpoints + } + + auth := map[string]any{} + if esConfig.Username != "" || esConfig.Password != "" { + if esConfig.Username == "" || esConfig.Password == "" { + return nil, errors.New("username and password must be configured together for the beatsauth extension") + } + auth["username"] = esConfig.Username + auth["password"] = esConfig.Password + } + if esConfig.APIKey != "" { + auth["api_key"] = base64.StdEncoding.EncodeToString([]byte(esConfig.APIKey)) + } + if len(esConfig.Headers) > 0 { + headerNames := slices.Sorted(maps.Keys(esConfig.Headers)) + headers := make([]map[string]string, 0, len(headerNames)) + for _, name := range headerNames { + headers = append(headers, map[string]string{ + "key": name, + "value": esConfig.Headers[name], + }) + } + auth["headers"] = headers + } + if len(auth) > 0 { + newMap["auth"] = auth + } + return newMap, nil } diff --git a/internal/pkg/otel/translate/output_elasticsearch_test.go b/internal/pkg/otel/translate/output_elasticsearch_test.go index 41e4524eaad..fd2d2e33801 100644 --- a/internal/pkg/otel/translate/output_elasticsearch_test.go +++ b/internal/pkg/otel/translate/output_elasticsearch_test.go @@ -14,12 +14,15 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + otelcomponent "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/confmap" "gopkg.in/yaml.v2" + "github.com/elastic/elastic-agent-client/v7/pkg/client" "github.com/elastic/elastic-agent-libs/config" "github.com/elastic/elastic-agent-libs/logp" "github.com/elastic/elastic-agent-libs/logp/logptest" + "github.com/elastic/elastic-agent/pkg/component" ) func TestGetRetryConfig(t *testing.T) { @@ -816,6 +819,21 @@ func TestToOTelConfig_CheckUnsupported(t *testing.T) { } } +func TestESToOTelConfigRejectsHostURLCredentials(t *testing.T) { + cfg := config.MustNewConfigFrom(map[string]any{ + "hosts": []any{"https://user:secret@es.example:9200"}, + }) + + _, _, _, err := ESToOTelConfig(cfg, "", logp.NewNopLogger()) + require.ErrorContains( + t, + err, + "credentials in Elasticsearch host URLs are unsupported; configure username and password separately", + "URL-embedded credentials must be rejected during translation", + ) + assert.NotContains(t, err.Error(), "secret", "translation error must not expose the URL password") +} + func TestCalcNamedPresetSizing(t *testing.T) { cases := []struct { name string @@ -918,6 +936,174 @@ func compareAndAssert(t *testing.T, expectedOutput *confmap.Conf, gotOutput *con assert.Equal(t, string(want), string(got)) } +func TestGetBeatsAuthExtensionConfigIncludesEndpointsAndAuthentication(t *testing.T) { + t.Setenv("ELASTICSEARCH_AUTH_HOST", "es.example") + + source := map[string]any{ + "hosts": []any{ + "${ELASTICSEARCH_AUTH_HOST}:9200", + "es-secondary.example:9201", + }, + "protocol": "https", + "path": "/elastic", + "parameters": map[string]any{"routing": "state loader"}, + "username": "heartbeat", + "password": "secret", + "headers": map[string]any{"X-State-Loader": "true"}, + "proxy_url": "http://proxy.example:8080", + "idle_connection_timeout": "17s", + "ssl.certificate_authorities": "testdata/certs/rootCA.crt", + "ssl.certificate": "testdata/certs/client.crt", + "ssl.key": "testdata/certs/client-unencrypted.key", + "ssl.verification_mode": "strict", + "bulk_max_size": 123, + "compression_level": 9, + "index": "exporter-only", + "pipeline": "exporter-only", + "timeout": "42s", + } + + cfg, err := config.NewConfigFrom(source) + require.NoError(t, err, "source output config must be valid") + + got, err := getBeatsAuthExtensionConfig(cfg) + require.NoError(t, err, "beatsauth config must translate") + + assert.Equal( + t, + []string{ + "https://es.example:9200/elastic?routing=state+loader", + "https://es-secondary.example:9201/elastic?routing=state+loader", + }, + got["endpoints"], + "beatsauth must contain resolved endpoints", + ) + + assert.Equal( + t, + map[string]any{ + "headers": []map[string]string{{ + "key": "X-State-Loader", + "value": "true", + }}, + "password": "secret", + "username": "heartbeat", + }, + got["auth"], + "beatsauth must own output authentication and headers", + ) +} + +func TestESToOTelConfigCloudID(t *testing.T) { + // Decoded Base64: example.test$elasticsearch$kibana + const encodedCloudID = "cloudidtest:ZXhhbXBsZS50ZXN0JGVsYXN0aWNzZWFyY2gka2liYW5h" + t.Setenv("ELASTICSEARCH_AUTH_CLOUD_ID", encodedCloudID) + + tests := []struct { + name string + output map[string]any + }{ + { + name: "Cloud ID only", + output: map[string]any{ + "cloud_id": "${ELASTICSEARCH_AUTH_CLOUD_ID}", + "cloud_auth": "cloud-user:cloud-password", + }, + }, + { + name: "Cloud ID overrides hosts and credentials", + output: map[string]any{ + "hosts": []any{"https://other.example:9200"}, + "username": "other-user", + "password": "other-password", + "cloud_id": "${ELASTICSEARCH_AUTH_CLOUD_ID}", + "cloud_auth": "cloud-user:cloud-password", + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + exporter, _, extensions, err := ESToOTelConfig( + config.MustNewConfigFrom(test.output), + "default", + logp.NewNopLogger(), + ) + require.NoError(t, err, "Cloud ID output config must translate") + + expectedEndpoints := []string{"https://elasticsearch.example.test:443"} + assert.Equal(t, expectedEndpoints, exporter["endpoints"], "exporter must use the Cloud ID endpoint") + assert.Equal(t, "cloud-user", exporter["user"], "exporter must use the Cloud auth username") + assert.Equal(t, "cloud-password", exporter["password"], "exporter must use the Cloud auth password") + + beatsAuthID := getBeatsAuthExtensionID("default").String() + beatsAuth, ok := extensions[beatsAuthID].(map[string]any) + require.True(t, ok, "translation must generate the output-scoped beatsauth extension") + assert.Equal(t, expectedEndpoints, beatsAuth["endpoints"], "beatsauth must use the same Cloud ID endpoint as the exporter") + + auth, ok := beatsAuth["auth"].(map[string]any) + require.True(t, ok, "beatsauth authentication config must be a map") + assert.Equal(t, "cloud-user", auth["username"], "beatsauth must use the Cloud auth username") + assert.Equal(t, "cloud-password", auth["password"], "beatsauth must use the Cloud auth password") + }) + } +} + +func TestHeartbeatElasticsearchAuthDelegatesTransportSettings(t *testing.T) { + const ( + outputName = "default" + trustedFingerprint = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + caSHA256 = "GkPh2Lqh6eDoIatcr5AlZTAIKcIz/AWC61lrWgRwwe8=" + ) + output := map[string]any{ + "hosts": []any{"localhost:9200"}, + "preset": "throughput", + "proxy_disable": true, + "proxy_headers": map[string]any{"X-Proxy": "value"}, + "ssl.ca_sha256": []any{caSHA256}, + "ssl.ca_trusted_fingerprint": trustedFingerprint, + "ssl.verification_mode": "certificate", + } + comp := &component.Component{ + ID: "heartbeat-default", + InputType: "synthetics/http", + OutputType: "elasticsearch", + OutputName: outputName, + InputSpec: &component.InputRuntimeSpec{ + BinaryName: "elastic-otel-collector", + Spec: component.InputSpec{ + Command: &component.CommandSpec{Args: []string{"heartbeat"}}, + }, + }, + Units: []component.Unit{{ + ID: "heartbeat-default", + Type: client.UnitTypeOutput, + Config: component.MustExpectedConfig(output), + }}, + } + + _, _, extensions, _, err := getExporterConfigForComponent( + comp, + otelcomponent.MustNewType("elasticsearch"), + logp.NewNopLogger(), + ) + require.NoError(t, err, "Heartbeat translation must accept transport and TLS settings") + + beatsAuthID := getBeatsAuthExtensionID(outputName).String() + beatsAuth, ok := extensions[beatsAuthID].(map[string]any) + require.True(t, ok, "Heartbeat translation must generate the output-scoped beatsauth extension") + assert.Equal(t, []string{"http://localhost:9200"}, beatsAuth["endpoints"], "beatsauth must contain output endpoints") + assert.Equal(t, "15s", beatsAuth["idle_connection_timeout"], "beatsauth must retain the effective throughput-preset idle timeout") + assert.Equal(t, true, beatsAuth["proxy_disable"], "beatsauth must retain proxy_disable") + assert.Equal(t, map[string]any{"X-Proxy": "value"}, beatsAuth["proxy_headers"], "beatsauth must retain proxy_headers") + + tlsConfig, ok := beatsAuth["ssl"].(map[string]any) + require.True(t, ok, "beatsauth must retain TLS settings") + assert.Equal(t, trustedFingerprint, tlsConfig["ca_trusted_fingerprint"], "beatsauth must retain the trusted CA fingerprint") + assert.Equal(t, []any{caSHA256}, tlsConfig["ca_sha256"], "beatsauth must retain CA SHA-256 pins") + assert.Equal(t, uint64(2), tlsConfig["verification_mode"], "beatsauth must retain certificate verification mode") +} + func TestGetBeatsAuthExtensionConfig(t *testing.T) { tests := []struct { name string @@ -949,6 +1135,21 @@ func TestGetBeatsAuthExtensionConfig(t *testing.T) { "timeout": "2m0s", }, }, + { + name: "with API key", + outputCfg: map[string]any{ + "api_key": "id:key", + }, + expected: map[string]any{ + "auth": map[string]any{ + "api_key": "aWQ6a2V5", + }, + "continue_on_error": true, + "idle_connection_timeout": "3s", + "proxy_disable": false, + "timeout": "1m30s", + }, + }, { name: "with ssl enabled", outputCfg: map[string]any{ diff --git a/internal/pkg/otel/translate/testdata/certs/client-unencrypted.key b/internal/pkg/otel/translate/testdata/certs/client-unencrypted.key new file mode 100644 index 00000000000..f6347bffd53 --- /dev/null +++ b/internal/pkg/otel/translate/testdata/certs/client-unencrypted.key @@ -0,0 +1,28 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDAVGPlx4U2BpWf +QlyMNraLMjdJAo4PjO2GrDbwg2cAO4QFbMECEiNHakvuJ3zVVDO+HsBdkLWr8nO4 +iXmZDokfDrOrANJuqq16p022soC8pJQz9uIBWTnxDGd/wdofi4H+V5uaMhw961sg +B7GREyBWNRBQzhcFyQEPXkR1/G52PcuzM5H9cnOSy7jc62g8Pkk8c2eZu3ADmvgW +SH0b5pFUIvKsq068QjKPqoHYXn38d/SSeCX57tzKsj+mBzp0cr1f9jeXmKeu68wP +YG14aj9WmmY6ICAPvqPFBKNLhXn2xPlZzv93zjiUR5bnitenVxvsmwjn5XvlgH56 +/fh3Y3aPAgMBAAECggEAKbvmNX03BcMmAnn29SIGOGw8HOamBu/QtvF1tnj9B8ri +Wf8AXr+q0htZwKLm7q+nzrCDk4oMMfSZcci7DyBdVtTs3cV+5C67GCtnrKZNUyHv +WttOrXY8IXdMmidpeoDeQ1+lTy9ie3kvu+KPgGiDEtHO6Yne6w1z4m7VMjkFizh6 +Y5sVPGTV1anoiO5tpW/D/Pshh/u+ZVsaeIE0iKV2NACJoMC0opsXBslldBDvXIaV +ZhpEnr5v3CO8i3roq2qp4Bplfyy8g89KXerg6G4JxM0NSafuWwGC/13chHSw3ke1 +5odqnnwUyJ+MNvzyH0CPzF56vE3hFe6byeG3rD2euQKBgQD+MPtpvYGZfvMdVKNu +zms4s9CLcoM6lJXD72xL73x4MUcPQLOfk2YpCLDuVadCA8jBvL7d0OjulYbjJNCX +XZH2CITtTPzDEn+hfxKcy4Jd2M53yMQvpr55nmysEp+juuhkAo/xlXgGOcL3nq7o +hBLEAMy2NKwkszt1VLyZaD9SPQKBgQDBsrmb9INYJsCboA/VydKtzMB7Nnrck4S6 +1BOsEp5JkepHPC92yolPCI94hJlTdISbt69nbcCGDvD87j2Z2UVP4zOfxT/SGHmF +LgLXgqzVCYcgvpBXZey9rPWvEPwQG/0ODgva7GxHnmVbP0LrQ4ynnX6FMsWaBYFd +K/0eEwY0uwKBgQCieGpqBr+sfbEk4TFpJLTx1DUKvJHWQpyLVSAyVQuIw254+FEX +QR5+QdjdLZAvqL2L33lbzCjmPlquGpzc8ujVilJ0Xs38XXmInvElmQpls6sccw26 +q2h50eICBhFVlKTvL5gTwQarbAYLQbjoU2qvLxepqncRKiJp91Ro9XHrvQKBgG9K +mFiiEcFZartAKTkF4BXaGhHxSIBqBg4ugisQ+3975icNzpurXV9apMxzK4GG5hZu +YMrFhaPA+/fnjt9RtgBjo6q986BsTY4W1K0suM8izVAkDd0Zg/+rW/I9iQZcfnZP +3cHoq4Iu4T+fRnzUcAFyfVpcxKptVVnKR4G7Hoq3AoGBAPrrQtt4QvmAxPknKFgO +mDke0HqyWowuMkAHoVLL3VUaH8hrI1FA+oWEXpor4VqguB8D1SWb0qAJRF7pIxoE +m8TtceUhSOnXNrrO5agyMRmL0aYf8D425ot/uwTiSkOd4bdFeEaYs0ahHosxHq2N +me1zqwZ6EX7XHaa6j1mx9tcX +-----END RSA PRIVATE KEY----- diff --git a/testing/integration/ess/heartbeat_monitoring_test.go b/testing/integration/ess/heartbeat_monitoring_test.go index af3437375ef..741d1a27e7c 100644 --- a/testing/integration/ess/heartbeat_monitoring_test.go +++ b/testing/integration/ess/heartbeat_monitoring_test.go @@ -149,6 +149,7 @@ func (runner *HeartbeatRunner) validateHeartbeatEvents(t *testing.T, ctx context {"exists", "field", "monitor.status"}, {"exists", "field", "state.id"}, {"exists", "field", "state.started_at"}, + {"exists", "field", "state.checks"}, }) query["query"].(map[string]interface{})["bool"].(map[string]interface{})["filter"] = map[string]any{ "range": map[string]any{ @@ -168,7 +169,7 @@ func (runner *HeartbeatRunner) validateHeartbeatEvents(t *testing.T, ctx context func (runner *HeartbeatRunner) TestBeatsMetrics() { t := runner.T() - ctx, cancel := context.WithTimeout(t.Context(), 20*time.Minute) + ctx, cancel := context.WithTimeout(t.Context(), 60*time.Minute) defer cancel() agentStatus, err := runner.agentFixture.ExecStatus(ctx) @@ -198,20 +199,7 @@ func (runner *HeartbeatRunner) TestBeatsMetrics() { processDoc = runner.validateHeartbeatEvents(t, ctx, agentStatus.Info.ID, testStart) t.Run("restores monitor state from Elasticsearch after restart", func(t *testing.T) { - stateIDBefore := heartbeatStateField(t, processDoc, "state.id") - stateStartedAtBefore := heartbeatStateField(t, processDoc, "state.started_at") - - require.NoError(t, runner.agentFixture.ExecRestart(ctx), "could not restart agent") - restartedAt := time.Now() - require.EventuallyWithT(t, func(collect *assert.CollectT) { - assert.NoError(collect, runner.agentFixture.IsHealthy(ctx)) - }, 2*time.Minute, 5*time.Second, "agent did not become healthy after restart") - - afterRestartDoc := runner.validateHeartbeatEvents(t, ctx, agentStatus.Info.ID, restartedAt) - assert.Equal(t, stateIDBefore, heartbeatStateField(t, afterRestartDoc, "state.id"), - "Heartbeat should continue the monitor state loaded from Elasticsearch") - assert.Equal(t, stateStartedAtBefore, heartbeatStateField(t, afterRestartDoc, "state.started_at"), - "Heartbeat should preserve the monitor state start time loaded from Elasticsearch") + runner.validateMonitorStateAfterRestart(t, ctx, agentStatus.Info.ID, processDoc) }) }) @@ -245,6 +233,10 @@ func (runner *HeartbeatRunner) TestBeatsMetrics() { }, 2*time.Minute, 5*time.Second, "heartbeat component should be running as beats receiver") otelDoc = runner.validateHeartbeatEvents(t, ctx, agentStatus.Info.ID, otelSince) + + t.Run("restores monitor state from Elasticsearch after restart", func(t *testing.T) { + runner.validateMonitorStateAfterRestart(t, ctx, agentStatus.Info.ID, otelDoc) + }) }) t.Run("compare", func(t *testing.T) { @@ -256,6 +248,49 @@ func (runner *HeartbeatRunner) TestBeatsMetrics() { }) } +func (runner *HeartbeatRunner) validateMonitorStateAfterRestart( + t *testing.T, + ctx context.Context, + agentID string, + beforeRestartDoc mapstr.M, +) { + t.Helper() + + stateIDBefore := heartbeatStateField(t, beforeRestartDoc, "state.id") + stateStartedAtBefore := heartbeatStateField(t, beforeRestartDoc, "state.started_at") + stateChecksBefore := heartbeatStateChecks(t, beforeRestartDoc) + + require.NoError(t, runner.agentFixture.ExecRestart(ctx), "could not restart agent") + restartedAt := time.Now() + require.EventuallyWithT( + t, + func(collect *assert.CollectT) { + assert.NoError(collect, runner.agentFixture.IsHealthy(ctx)) + }, + 2*time.Minute, 5*time.Second, "agent did not become healthy after restart") + + afterRestartDoc := runner.validateHeartbeatEvents(t, ctx, agentID, restartedAt) + + assert.Equal( + t, + stateIDBefore, + heartbeatStateField(t, afterRestartDoc, "state.id"), + "Heartbeat should continue the monitor state loaded from Elasticsearch", + ) + assert.Equal( + t, + stateStartedAtBefore, + heartbeatStateField(t, afterRestartDoc, "state.started_at"), + "Heartbeat should preserve the monitor state start time loaded from Elasticsearch", + ) + assert.Greater( + t, + heartbeatStateChecks(t, afterRestartDoc), + stateChecksBefore, + "Heartbeat should continue incrementing the restored monitor state checks", + ) +} + func heartbeatStateField(t *testing.T, doc mapstr.M, field string) interface{} { t.Helper() value, err := doc.GetValue(field) @@ -263,6 +298,14 @@ func heartbeatStateField(t *testing.T, doc mapstr.M, field string) interface{} { return value } +func heartbeatStateChecks(t *testing.T, doc mapstr.M) int { + t.Helper() + value := heartbeatStateField(t, doc, "state.checks") + checks, ok := value.(float64) + require.True(t, ok, "heartbeat state.checks has type %T, expected float64", value) + return int(checks) +} + // scheduleMissingErr is the Permanent failure message emitted by the OTel // heartbeatreceiver when Fleet browser.network / browser.screenshot streams // (which have no schedule) are treated as monitors. See elastic-agent#15968. From 1880dca2e43d86d3406b71a6ed8b09ef63eb5ff6 Mon Sep 17 00:00:00 2001 From: Tiago Queiroz Date: Mon, 26 Oct 2026 20:58:26 -0400 Subject: [PATCH 2/2] Fix merge conflicts Assisted-by: gpt-5.6-terra-high --- .../pkg/otel/translate/otelconfig_test.go | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/internal/pkg/otel/translate/otelconfig_test.go b/internal/pkg/otel/translate/otelconfig_test.go index de27006f9b9..62ec333c6a1 100644 --- a/internal/pkg/otel/translate/otelconfig_test.go +++ b/internal/pkg/otel/translate/otelconfig_test.go @@ -3551,7 +3551,6 @@ func TestGetReceiversConfigForComponent(t *testing.T) { } } -<<<<<<< HEAD // TestGetReceiversConfigForComponentNoEnabledStreams verifies that a component with no // enabled streams (either no input units, or input units with nil config) falls back to // a no-op receiver instead of an error, so the pipeline stays valid and the component @@ -3619,7 +3618,18 @@ func TestGetReceiversConfigForComponentNoEnabledStreams(t *testing.T) { }, }, expectedReceiverID: GetReceiverID(nopType, "nil-config-test-id"), -======= + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result, err := getReceiversConfigForComponent(tt.component, nil, nil) + require.NoError(t, err) + assert.Equal(t, map[string]any{tt.expectedReceiverID.String(): map[string]any{}}, result) + }) + } +} + func TestGetReceiversConfigForComponentHeartbeatElasticsearchAuth(t *testing.T) { newHeartbeatComponent := func(outputType string, singleReceiver bool) *component.Component { return &component.Component{ @@ -3712,20 +3722,13 @@ func TestGetReceiversConfigForComponentHeartbeatElasticsearchAuth(t *testing.T) "heartbeatreceiver/_agent-component/heartbeat-auth-test-id/unit-http-1", "heartbeatreceiver/_agent-component/heartbeat-auth-test-id/unit-http-2", }, ->>>>>>> fe0cdc3 (Restore Heartbeat monitor state in OTel mode (#16902)) }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { -<<<<<<< HEAD - result, err := getReceiversConfigForComponent(tt.component, nil, nil) - require.NoError(t, err) - assert.Equal(t, map[string]any{tt.expectedReceiverID.String(): map[string]any{}}, result) -======= result, err := getReceiversConfigForComponent( newHeartbeatComponent(tt.outputType, tt.singleReceiver), - &info.AgentInfo{}, nil, nil, ) @@ -3747,7 +3750,6 @@ func TestGetReceiversConfigForComponentHeartbeatElasticsearchAuth(t *testing.T) require.True(t, ok, "receiver %q monitor state config must be a map", receiverID) assert.Equal(t, tt.expectedAuth, monitorState["elasticsearch"], "receiver %q must reference the output-scoped Elasticsearch auth extension", receiverID) } ->>>>>>> fe0cdc3 (Restore Heartbeat monitor state in OTel mode (#16902)) }) } }