From 0544dc9f591c9fcf9c7f5cc02b76a7a866931427 Mon Sep 17 00:00:00 2001 From: Khushi Jain Date: Thu, 26 Nov 2026 09:59:59 +0530 Subject: [PATCH 1/5] Retire API keys of ES output when user switch to non-ES output --- ...n-output-changes-to-logstash-or-kafka.yaml | 7 + internal/pkg/api/handleAck.go | 105 +--------- internal/pkg/api/handleAck_test.go | 6 +- internal/pkg/api/handleCheckin.go | 7 +- internal/pkg/api/handleCheckin_test.go | 93 +++++++++ internal/pkg/policy/policy_output.go | 15 +- internal/pkg/policy/policy_output_test.go | 140 ++++++++++++++ internal/pkg/policy/retire_outputs.go | 179 ++++++++++++++++++ 8 files changed, 439 insertions(+), 113 deletions(-) create mode 100644 changelog/fragments/1795667311-retire-output-api-keys-when-an-output-changes-to-logstash-or-kafka.yaml create mode 100644 internal/pkg/policy/retire_outputs.go diff --git a/changelog/fragments/1795667311-retire-output-api-keys-when-an-output-changes-to-logstash-or-kafka.yaml b/changelog/fragments/1795667311-retire-output-api-keys-when-an-output-changes-to-logstash-or-kafka.yaml new file mode 100644 index 0000000000..2f6abd46d4 --- /dev/null +++ b/changelog/fragments/1795667311-retire-output-api-keys-when-an-output-changes-to-logstash-or-kafka.yaml @@ -0,0 +1,7 @@ +kind: bug-fix +summary: Retire output API keys when an output changes to Logstash or Kafka +description: >- + Fleet Server now retires the API keys of agent outputs that are removed or changed + to an output type without API keys, such as Logstash or Kafka. Previously, these + keys could remain valid after the policy change. +component: fleet-server diff --git a/internal/pkg/api/handleAck.go b/internal/pkg/api/handleAck.go index 3083e4836d..f3463937ac 100644 --- a/internal/pkg/api/handleAck.go +++ b/internal/pkg/api/handleAck.go @@ -362,7 +362,7 @@ func (ack *AckT) handleAckEvents(ctx context.Context, zlog zerolog.Logger, agent // Process policy acks if len(policyAcks) > 0 { - if err := ack.handlePolicyChange(ctx, zlog, agent, policyAcks...); err != nil { + if err := ack.handleAckForPolicyChange(ctx, zlog, agent, policyAcks...); err != nil { for _, idx := range policyIdxs { setError(idx, err) } @@ -442,7 +442,7 @@ func (ack *AckT) handleActionResult(ctx context.Context, zlog zerolog.Logger, ag return nil } -func (ack *AckT) handlePolicyChange(ctx context.Context, zlog zerolog.Logger, agent *model.Agent, actionIds ...string) error { +func (ack *AckT) handleAckForPolicyChange(ctx context.Context, zlog zerolog.Logger, agent *model.Agent, actionIds ...string) error { span, ctx := apm.StartSpan(ctx, "ackPolicyChanges", "process") defer span.End() // If more than one, pick the winner; @@ -567,8 +567,8 @@ func updateAPIKey(ctx context.Context, // Process retirement records regardless of whether an active key is present. // This handles entries that park records without a live replacement key — e.g., // an mOTLP→external OTLP transition where the output survives but the key is retired. - invalidateAPIKeys(ctx, zlog, bulk, toRetireAPIKeyIDs, apiKeyID) - deleteRetiredSecrets(ctx, zlog, bulk, toRetireAPIKeyIDs) + policy.InvalidateAPIKeys(ctx, zlog, bulk, toRetireAPIKeyIDs, apiKeyID) + policy.DeleteRetiredSecrets(ctx, zlog, bulk, toRetireAPIKeyIDs) return nil } @@ -635,7 +635,7 @@ func cleanRoles(roles json.RawMessage) (json.RawMessage, int, error) { } func (ack *AckT) invalidateAPIKeys(ctx context.Context, zlog zerolog.Logger, toRetireAPIKeyIDs []model.ToRetireAPIKeyIdsItems, skip string) { - invalidateAPIKeys(ctx, zlog, ack.bulk, toRetireAPIKeyIDs, skip) + policy.InvalidateAPIKeys(ctx, zlog, ack.bulk, toRetireAPIKeyIDs, skip) } // handleUnenroll performs the terminal invalidation shared by the legacy @@ -662,7 +662,7 @@ func (ack *AckT) handleUnenroll(ctx context.Context, zlog zerolog.Logger, agent allSecretItems = append(allSecretItems, model.ToRetireAPIKeyIdsItems{SecretID: secretID}) } } - deleteRetiredSecrets(ctx, zlog, ack.bulk, allSecretItems) + policy.DeleteRetiredSecrets(ctx, zlog, ack.bulk, allSecretItems) // unenrolled_at is always stamped here, paired with active: false. The // pending-uninstall step keeps the agent active and deliberately does not set @@ -761,7 +761,7 @@ func (ack *AckT) handleUninstallPending(ctx context.Context, zlog zerolog.Logger secretItems = append(secretItems, model.ToRetireAPIKeyIdsItems{SecretID: secretID}) } } - deleteRetiredSecrets(ctx, zlog, ack.bulk, secretItems) + policy.DeleteRetiredSecrets(ctx, zlog, ack.bulk, secretItems) // Clear the (now-invalidated) output key fields on the agent document so that, // when the agent re-enrolls, policy preparation regenerates fresh keys instead @@ -908,94 +908,3 @@ func makeUpdatePolicyBody(policyID string, newRev int64) []byte { return buf.Bytes() } - -// invalidateAPIKeys retires the given API keys against the correct cluster. -// -// Each item's Output field names the output the key belongs to. -// An empty Output routes directly to the primary cluster (bulk). -// A non-empty Output triggers a remote-bulker lookup: GetBulker is tried first (hot path), -// then CreateAndGetBulker via QueryOutputFromPolicy (cold/restart path). If neither resolves -// a bulker, the primary cluster is used as a fallback — correct for local outputs (elasticsearch, -// otlp) and benign for unreachable remote outputs (primary returns "not found" rather than -// silently dropping the request). -// -// This mirrors the fail-safe pattern in updateAPIKey, which starts with the primary bulker -// and only upgrades to a remote one when available. -func invalidateAPIKeys(ctx context.Context, zlog zerolog.Logger, bulk bulk.Bulk, toRetireAPIKeyIDs []model.ToRetireAPIKeyIdsItems, skip string) { - ids := make([]string, 0, len(toRetireAPIKeyIDs)) - remoteIds := make(map[string][]string) - for _, k := range toRetireAPIKeyIDs { - if k.ID == skip || k.ID == "" { - continue - } - // Route by output_type when available. OTLP keys are always on the primary cluster - // so they go directly into the primary bucket. All other types — including - // "elasticsearch", which the agent doc uses for both local and remote ES after - // normalization — stay on the name-based path so existing routing is preserved - // for records that predate this field or that cannot be distinguished from remote ES. - switch k.OutputType { - case policy.OutputTypeOTLP: - ids = append(ids, k.ID) - default: - if k.Output != "" { - if remoteIds[k.Output] == nil { - remoteIds[k.Output] = make([]string, 0) - } - remoteIds[k.Output] = append(remoteIds[k.Output], k.ID) - } else { - ids = append(ids, k.ID) - } - } - } - if len(ids) > 0 { - zlog.Info().Strs("fleet.policy.apiKeyIDsToRetire", ids).Msg("Invalidate old API keys") - if err := bulk.APIKeyInvalidate(ctx, ids...); err != nil { - zlog.Warn().Err(err).Strs("ids", ids).Msg("Failed to invalidate API keys. API keys will be orphaned.") - } - } - // using remote es bulker to invalidate api key - for outputName, outputIds := range remoteIds { - outputBulk := bulk.GetBulker(outputName) - usedPrimaryFallback := false - - var outputPolicy *model.Policy - if outputBulk == nil { - // read output config from .fleet-policies, not filtering by policy id as agent could be reassigned - var err error - outputPolicy, err = dl.QueryOutputFromPolicy(ctx, bulk, outputName) - if err != nil || outputPolicy == nil { - zlog.Warn().Err(err).Str(ecs.PolicyOutputName, outputName).Any("ids", outputIds).Msg("Output policy not found, falling back to primary cluster for key invalidation") - } else { - outputBulk, _, err = bulk.CreateAndGetBulker(ctx, zlog, outputName, outputPolicy.Data.Outputs) - if err != nil { - zlog.Warn().Err(err).Str(ecs.PolicyOutputName, outputName).Any("ids", outputIds).Msg("Failed to recreate output bulker, falling back to primary cluster for key invalidation") - } - } - } - if outputBulk == nil { - if outputPolicy != nil && outputPolicy.Data.Outputs[outputName]["type"] == policy.OutputTypeRemoteElasticsearch { - zlog.Warn().Str(ecs.PolicyOutputName, outputName).Any("ids", outputIds). - Msg("Cannot invalidate remote ES API keys: remote cluster unreachable, API keys will be orphaned") - continue - } - outputBulk = bulk - usedPrimaryFallback = true - } - if err := outputBulk.APIKeyInvalidate(ctx, outputIds...); err != nil { - zlog.Warn().Err(err).Strs("ids", outputIds).Str(ecs.PolicyOutputName, outputName). - Bool("fallback_to_primary", usedPrimaryFallback). - Msg("Failed to invalidate output API keys. API keys will be orphaned.") - } - } -} - -func deleteRetiredSecrets(ctx context.Context, zlog zerolog.Logger, bulk bulk.Bulk, toRetireAPIKeyIDs []model.ToRetireAPIKeyIdsItems) { - for _, k := range toRetireAPIKeyIDs { - if k.SecretID == "" { - continue - } - if err := bulk.DeleteSecret(ctx, k.SecretID); err != nil { - zlog.Warn().Err(err).Str("secret_id", k.SecretID).Msg("Failed to delete retired output API key secret") - } - } -} diff --git a/internal/pkg/api/handleAck_test.go b/internal/pkg/api/handleAck_test.go index 8f9a3216ee..581dfceb09 100644 --- a/internal/pkg/api/handleAck_test.go +++ b/internal/pkg/api/handleAck_test.go @@ -1268,7 +1268,7 @@ func TestDeleteRetiredSecrets(t *testing.T) { {ID: "key-3"}, // no SecretID — plaintext key, no cleanup needed } - deleteRetiredSecrets(context.Background(), testlog.SetLogger(t), bulker, items) + policy.DeleteRetiredSecrets(context.Background(), testlog.SetLogger(t), bulker, items) bulker.AssertExpectations(t) bulker.AssertNotCalled(t, "DeleteSecret", mock.Anything, "") }) @@ -1282,7 +1282,7 @@ func TestDeleteRetiredSecrets(t *testing.T) { } // Should not panic or propagate the error. - deleteRetiredSecrets(context.Background(), testlog.SetLogger(t), bulker, items) + policy.DeleteRetiredSecrets(context.Background(), testlog.SetLogger(t), bulker, items) bulker.AssertExpectations(t) }) @@ -1292,7 +1292,7 @@ func TestDeleteRetiredSecrets(t *testing.T) { {ID: "key-1"}, {ID: "key-2"}, } - deleteRetiredSecrets(context.Background(), testlog.SetLogger(t), bulker, items) + policy.DeleteRetiredSecrets(context.Background(), testlog.SetLogger(t), bulker, items) bulker.AssertNotCalled(t, "DeleteSecret", mock.Anything, mock.Anything) }) } diff --git a/internal/pkg/api/handleCheckin.go b/internal/pkg/api/handleCheckin.go index 61321bf611..cd3192b193 100644 --- a/internal/pkg/api/handleCheckin.go +++ b/internal/pkg/api/handleCheckin.go @@ -210,7 +210,7 @@ func invalidateAPIKeysOfInactiveAgent(ctx context.Context, zlog zerolog.Logger, } } zlog.Info().Any("fleet.policy.apiKeyIDsToRetire", remoteAPIKeys).Msg("handleCheckin invalidate remote API keys") - invalidateAPIKeys(ctx, zlog, bulker, remoteAPIKeys, "") + policy.InvalidateAPIKeys(ctx, zlog, bulker, remoteAPIKeys, "") } // isInvalidAPIKeyErr reports whether err represents an invalid or disabled API key @@ -1231,6 +1231,11 @@ func processPolicy(ctx context.Context, zlog zerolog.Logger, bulker bulk.Bulk, a pp.SecretKeys = append(pp.SecretKeys, "outputs."+name+"."+key) } } + // Retire keys before preparing outputs, as no output with API keys may be left + // to prepare when the policy switched to logstash or kafka. + if err := policy.RetireRemovedOutputs(ctx, zlog, bulker, agent, pp.Policy.Data.Outputs); err != nil { + return nil, nil, fmt.Errorf("failed to retire removed outputs: %w", err) + } // Iterate through the policy outputs and prepare them for _, policyOutput := range pp.Outputs { if err := policyOutput.Prepare(ctx, zlog, bulker, agent, pp.Policy.Data.Outputs, policy.WithOutputSecretCandidateCollector(secretCandidateCollector)); err != nil { diff --git a/internal/pkg/api/handleCheckin_test.go b/internal/pkg/api/handleCheckin_test.go index c333d39880..c0a3e911a0 100644 --- a/internal/pkg/api/handleCheckin_test.go +++ b/internal/pkg/api/handleCheckin_test.go @@ -2032,6 +2032,99 @@ func TestProcessPolicyRemoteESServiceTokenSecretPaths(t *testing.T) { assert.Equal(t, policy.OutputTypeElasticsearch, remotePolicy["type"]) } +func TestProcessPolicyOutputChangedToLogstashIsParkedOnSurvivor(t *testing.T) { + logger := testlog.SetLogger(t) + + const policyPayload = `{ + "id": "es-and-logstash", + "revision": 2, + "outputs": { + "default": { + "type": "elasticsearch", + "hosts": ["https://local.es.example:443"] + }, + "es2": { + "type": "logstash", + "hosts": ["logstash.example:5044"] + } + }, + "output_permissions": { + "default": { + "_fallback": { + "cluster": ["monitor"], + "indices": [{"names": ["logs-*", "metrics-*"], "privileges": ["auto_configure", "create_doc"]}] + } + } + }, + "inputs": [] +}` + + var d model.PolicyData + require.NoError(t, json.Unmarshal([]byte(policyPayload), &d)) + + bulker := ftesting.NewMockBulk() + pp, err := policy.NewParsedPolicy(t.Context(), bulker, model.Policy{ + PolicyID: "policy1", + RevisionIdx: 2, + Data: &d, + }) + require.NoError(t, err) + defaultOut := pp.Outputs["default"] + require.NotNil(t, defaultOut.Role) + + var updates []string + bulker.On("Update", mock.Anything, dl.FleetAgents, "agent1", mock.Anything, mock.Anything). + Run(func(args mock.Arguments) { + updates = append(updates, string(args.Get(3).([]byte))) + }). + Return(nil) + + agent := &model.Agent{ + Id: "agent1", + Outputs: map[string]*model.PolicyOutput{ + "default": { + APIKey: "key1:value", + APIKeyID: "key1", + PermissionsHash: defaultOut.Role.Sha2, + Type: policy.OutputTypeElasticsearch, + }, + // es2 was an elasticsearch output in the previous revision. + "es2": { + APIKey: "key2:value", + APIKeyID: "key2", + PermissionsHash: "previous-hash", + Type: policy.OutputTypeElasticsearch, + }, + }, + } + + _, _, err = processPolicy(t.Context(), logger, bulker, agent, pp, true, nil) + require.NoError(t, err) + + assert.Contains(t, agent.Outputs, "default") + assert.NotContains(t, agent.Outputs, "es2") + + // es2's key is parked on default, then es2 is removed from the agent document. + require.Len(t, updates, 2) + var park struct { + Script struct { + Params struct { + OutputName string `json:"output_name"` + ToRetire model.ToRetireAPIKeyIdsItems `json:"to_retire_api_key_ids"` + } `json:"params"` + } `json:"script"` + } + require.NoError(t, json.Unmarshal([]byte(updates[0]), &park)) + assert.Equal(t, "default", park.Script.Params.OutputName) + assert.Equal(t, "key2", park.Script.Params.ToRetire.ID) + assert.Equal(t, "es2", park.Script.Params.ToRetire.Output) + assert.Equal(t, policy.OutputTypeElasticsearch, park.Script.Params.ToRetire.OutputType) + assert.Contains(t, updates[0], "to_retire_api_key_ids.add(params.to_retire_api_key_ids)") + assert.Contains(t, updates[1], `"output_name":"es2"`) + assert.Contains(t, updates[1], "remove(params.output_name)") + bulker.AssertNotCalled(t, "APIKeyInvalidate", mock.Anything, mock.Anything) +} + // TestProcessPolicyPrunesAgentPinnedInputsSecretPaths ensures inputs pinned to other // agents are not delivered and that secret_paths follow the shifted input/stream indexes. func TestProcessPolicyPrunesAgentPinnedInputsSecretPaths(t *testing.T) { diff --git a/internal/pkg/policy/policy_output.go b/internal/pkg/policy/policy_output.go index 8a4ec70111..2bde88901f 100644 --- a/internal/pkg/policy/policy_output.go +++ b/internal/pkg/policy/policy_output.go @@ -645,7 +645,8 @@ func agentDocOutputType(t string) string { return t } -// retireRemovedOutputs retires all outputs present in agent.Outputs but absent from outputMap. +// retireRemovedOutputs retires all outputs present in agent.Outputs but absent from outputMap, +// or that no longer have API keys in outputMap (e.g. an elasticsearch output changed to logstash). // For each, it parks a retirement record on survivingOutputName and removes the stale doc entry. // // This is called once per surviving output, so the in-memory delete is essential: without it @@ -665,7 +666,7 @@ func retireRemovedOutputs( outputMap map[string]map[string]any, ) error { for agentOutputName, agentOutput := range agent.Outputs { - if _, stillInPolicy := outputMap[agentOutputName]; stillInPolicy { + if output, ok := outputMap[agentOutputName]; ok && hasAPIKeys(output) { continue } @@ -688,15 +689,7 @@ func retireRemovedOutputs( return r.ID == agentOutput.APIKeyID }) if agentOutput.APIKeyID != "" && !alreadyParked { - retiring := model.ToRetireAPIKeyIdsItems{ - ID: agentOutput.APIKeyID, - RetiredAt: time.Now().UTC().Format(time.RFC3339), - Output: agentOutputName, - OutputType: agentOutput.Type, - } - if secretID, ok := secret.ParseSecretReference(agentOutput.APIKey); ok { - retiring.SecretID = secretID - } + retiring := retirementRecord(agentOutputName, agentOutput, time.Now().UTC().Format(time.RFC3339)) if err := parkRetirementRecord(ctx, zlog, bulker, agent.Id, survivingOutputName, retiring); err != nil { return err } diff --git a/internal/pkg/policy/policy_output_test.go b/internal/pkg/policy/policy_output_test.go index 0d54d350c0..07ca499371 100644 --- a/internal/pkg/policy/policy_output_test.go +++ b/internal/pkg/policy/policy_output_test.go @@ -19,6 +19,7 @@ import ( "github.com/elastic/elastic-agent-client/v7/pkg/client" "github.com/elastic/fleet-server/v7/internal/pkg/bulk" "github.com/elastic/fleet-server/v7/internal/pkg/dl" + "github.com/elastic/fleet-server/v7/internal/pkg/es" "github.com/elastic/fleet-server/v7/internal/pkg/model" ftesting "github.com/elastic/fleet-server/v7/internal/pkg/testing" testlog "github.com/elastic/fleet-server/v7/internal/pkg/testing/log" @@ -1074,3 +1075,142 @@ func TestPolicyRemoteESOutputPrepare(t *testing.T) { bulker.AssertExpectations(t) }) } + +func TestRetireRemovedOutputs(t *testing.T) { + t.Run("retirement is left to Prepare while an output with API keys remains", func(t *testing.T) { + logger := testlog.SetLogger(t) + bulker := ftesting.NewMockBulk() + agent := &model.Agent{ + Outputs: map[string]*model.PolicyOutput{ + "default": {APIKeyID: "key1", Type: OutputTypeElasticsearch}, + "remote": {APIKeyID: "remoteKey1", Type: OutputTypeElasticsearch}, + }, + } + outputMap := map[string]map[string]any{ + "default": {"type": OutputTypeElasticsearch}, + } + + err := RetireRemovedOutputs(t.Context(), logger, bulker, agent, outputMap) + require.NoError(t, err) + + assert.Len(t, agent.Outputs, 2) + bulker.AssertNotCalled(t, "Update", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) + bulker.AssertNotCalled(t, "APIKeyInvalidate", mock.Anything, mock.Anything) + }) + + t.Run("keys are invalidated immediately when policy switches to logstash only", func(t *testing.T) { + logger := testlog.SetLogger(t) + bulker := ftesting.NewMockBulk() + remoteBulker := ftesting.NewMockBulk() + + bulker.On("GetBulker", "default").Return(nil) + bulker.On("GetBulker", "remote").Return(remoteBulker) + // the local output is not found in any policy, so its key falls back to the primary cluster + bulker.On("Search", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&es.ResultT{}, nil) + bulker.On("APIKeyInvalidate", mock.Anything, []string{"key1"}).Return(nil).Once() + remoteBulker.On("APIKeyInvalidate", mock.Anything, []string{"remoteKey1"}).Return(nil).Once() + bulker.On("DeleteSecret", mock.Anything, "secret1").Return(nil).Once() + // one update per removed output to delete it from the agent document + bulker.On("Update", mock.Anything, dl.FleetAgents, "agent1", mock.Anything, mock.Anything).Return(nil).Twice() + + agent := &model.Agent{ + ESDocument: model.ESDocument{Id: "agent1"}, + Outputs: map[string]*model.PolicyOutput{ + "default": {APIKey: "$co.elastic.secret{secret1}", APIKeyID: "key1", Type: OutputTypeElasticsearch}, + "remote": {APIKeyID: "remoteKey1", Type: OutputTypeElasticsearch}, + }, + } + outputMap := map[string]map[string]any{ + "ls": {"type": OutputTypeLogstash}, + } + + err := RetireRemovedOutputs(t.Context(), logger, bulker, agent, outputMap) + require.NoError(t, err) + + assert.Empty(t, agent.Outputs) + bulker.AssertExpectations(t) + remoteBulker.AssertExpectations(t) + }) + + t.Run("key is invalidated immediately when output type changes from elasticsearch to logstash", func(t *testing.T) { + logger := testlog.SetLogger(t) + bulker := ftesting.NewMockBulk() + + bulker.On("GetBulker", "default").Return(nil) + bulker.On("Search", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&es.ResultT{}, nil) + // the pending key from a previous rotation is invalidated as well + bulker.On("APIKeyInvalidate", mock.Anything, []string{"oldKey"}).Return(nil).Once() + bulker.On("APIKeyInvalidate", mock.Anything, []string{"key1"}).Return(nil).Once() + bulker.On("Update", mock.Anything, dl.FleetAgents, "agent1", mock.Anything, mock.Anything).Return(nil).Once() + + agent := &model.Agent{ + ESDocument: model.ESDocument{Id: "agent1"}, + Outputs: map[string]*model.PolicyOutput{ + "default": { + APIKeyID: "key1", + Type: OutputTypeElasticsearch, + ToRetireAPIKeyIds: []model.ToRetireAPIKeyIdsItems{{ID: "oldKey"}}, + }, + }, + } + outputMap := map[string]map[string]any{ + "default": {"type": OutputTypeLogstash}, + } + + err := RetireRemovedOutputs(t.Context(), logger, bulker, agent, outputMap) + require.NoError(t, err) + + assert.Empty(t, agent.Outputs) + bulker.AssertExpectations(t) + }) +} + +func TestRetireRemovedOutputsTypeChange(t *testing.T) { + t.Run("output changed to logstash is parked on surviving output", func(t *testing.T) { + logger := testlog.SetLogger(t) + bulker := ftesting.NewMockBulk() + // one update to park the key on the survivor and one to delete the changed output + bulker.On("Update", mock.Anything, dl.FleetAgents, "agent1", mock.Anything, mock.Anything).Return(nil).Twice() + + agent := &model.Agent{ + ESDocument: model.ESDocument{Id: "agent1"}, + Outputs: map[string]*model.PolicyOutput{ + "default": {APIKeyID: "key1", Type: OutputTypeElasticsearch}, + "es2": {APIKeyID: "key2", Type: OutputTypeElasticsearch}, + }, + } + outputMap := map[string]map[string]any{ + "default": {"type": OutputTypeElasticsearch}, + "es2": {"type": OutputTypeLogstash}, + } + + err := retireRemovedOutputs(t.Context(), logger, bulker, agent, "default", outputMap) + require.NoError(t, err) + + assert.Contains(t, agent.Outputs, "default") + assert.NotContains(t, agent.Outputs, "es2") + bulker.AssertExpectations(t) + bulker.AssertNotCalled(t, "APIKeyInvalidate", mock.Anything, mock.Anything) + }) + + t.Run("output without type is kept", func(t *testing.T) { + logger := testlog.SetLogger(t) + bulker := ftesting.NewMockBulk() + + agent := &model.Agent{ + ESDocument: model.ESDocument{Id: "agent1"}, + Outputs: map[string]*model.PolicyOutput{ + "default": {APIKeyID: "key1", Type: OutputTypeElasticsearch}, + }, + } + outputMap := map[string]map[string]any{ + "default": {}, + } + + err := retireRemovedOutputs(t.Context(), logger, bulker, agent, "default", outputMap) + require.NoError(t, err) + + assert.Contains(t, agent.Outputs, "default") + bulker.AssertNotCalled(t, "Update", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) + }) +} diff --git a/internal/pkg/policy/retire_outputs.go b/internal/pkg/policy/retire_outputs.go new file mode 100644 index 0000000000..3d4f67be68 --- /dev/null +++ b/internal/pkg/policy/retire_outputs.go @@ -0,0 +1,179 @@ +// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one +// or more contributor license agreements. Licensed under the Elastic License 2.0; +// you may not use this file except in compliance with the Elastic License 2.0. + +package policy + +import ( + "context" + "fmt" + "maps" + "slices" + "time" + + "github.com/rs/zerolog" + + "github.com/elastic/fleet-server/v7/internal/pkg/bulk" + "github.com/elastic/fleet-server/v7/internal/pkg/dl" + "github.com/elastic/fleet-server/v7/internal/pkg/logger/ecs" + "github.com/elastic/fleet-server/v7/internal/pkg/model" + "github.com/elastic/fleet-server/v7/internal/pkg/secret" +) + +// RetireRemovedOutputs retires the API keys of all agent outputs when the policy has +// no output with API keys left, e.g. when it switched to logstash or kafka. The keys +// are invalidated immediately, as there is no remaining output to park them on until ack. +// Otherwise, removed outputs are retired while preparing the remaining outputs, see +// retireRemovedOutputs. +func RetireRemovedOutputs(ctx context.Context, zlog zerolog.Logger, bulker bulk.Bulk, agent *model.Agent, outputMap map[string]map[string]any) error { + if len(agent.Outputs) == 0 { + return nil + } + for _, output := range outputMap { + if hasAPIKeys(output) { + return nil + } + } + + names := slices.Sorted(maps.Keys(agent.Outputs)) + + retiredAt := time.Now().UTC().Format(time.RFC3339) + toRetire := make([]model.ToRetireAPIKeyIdsItems, 0, len(names)) + for _, name := range names { + out := agent.Outputs[name] + toRetire = append(toRetire, out.ToRetireAPIKeyIds...) + if out.APIKeyID == "" { + continue + } + zlog.Info().Str(ecs.APIKeyID, out.APIKeyID).Str(ecs.PolicyOutputName, name).Msg("Output removed, retiring API key") + toRetire = append(toRetire, retirementRecord(name, out, retiredAt)) + } + InvalidateAPIKeys(ctx, zlog, bulker, toRetire, "") + DeleteRetiredSecrets(ctx, zlog, bulker, toRetire) + + for _, name := range names { + body, err := renderRemoveOutputPainlessScript(name) + if err != nil { + return fmt.Errorf("could not create request body to update agent: %w", err) + } + if err := bulker.Update(ctx, dl.FleetAgents, agent.Id, body, bulk.WithRefresh(), bulk.WithRetryOnConflict(3)); err != nil { + zlog.Error().Err(err).Msg("fail update agent record") + return fmt.Errorf("fail update agent record: %w", err) + } + delete(agent.Outputs, name) + } + return nil +} + +// retirementRecord returns the record used to retire the active API key of an agent output. +func retirementRecord(outputName string, out *model.PolicyOutput, retiredAt string) model.ToRetireAPIKeyIdsItems { + record := model.ToRetireAPIKeyIdsItems{ + ID: out.APIKeyID, + RetiredAt: retiredAt, + Output: outputName, + OutputType: out.Type, + } + if secretID, ok := secret.ParseSecretReference(out.APIKey); ok { + record.SecretID = secretID + } + return record +} + +// hasAPIKeys reports whether the policy output may have per-agent API keys. Outputs +// without a type are assumed to have them, so that their keys are never retired by mistake. +func hasAPIKeys(output map[string]any) bool { + t, _ := output[FieldOutputType].(string) + return t == "" || t == OutputTypeElasticsearch || t == OutputTypeRemoteElasticsearch || t == OutputTypeOTLP +} + +// InvalidateAPIKeys retires the given API keys against the correct cluster. +// +// Each item's Output field names the output the key belongs to. +// An empty Output routes directly to the primary cluster (bulk). +// A non-empty Output triggers a remote-bulker lookup: GetBulker is tried first (hot path), +// then CreateAndGetBulker via QueryOutputFromPolicy (cold/restart path). If neither resolves +// a bulker, the primary cluster is used as a fallback — correct for local outputs (elasticsearch, +// otlp) and benign for unreachable remote outputs (primary returns "not found" rather than +// silently dropping the request). +// +// This mirrors the fail-safe pattern in updateAPIKey, which starts with the primary bulker +// and only upgrades to a remote one when available. +func InvalidateAPIKeys(ctx context.Context, zlog zerolog.Logger, bulk bulk.Bulk, toRetireAPIKeyIDs []model.ToRetireAPIKeyIdsItems, skip string) { + ids := make([]string, 0, len(toRetireAPIKeyIDs)) + remoteIds := make(map[string][]string) + for _, k := range toRetireAPIKeyIDs { + if k.ID == skip || k.ID == "" { + continue + } + // Route by output_type when available. OTLP keys are always on the primary cluster + // so they go directly into the primary bucket. All other types — including + // "elasticsearch", which the agent doc uses for both local and remote ES after + // normalization — stay on the name-based path so existing routing is preserved + // for records that predate this field or that cannot be distinguished from remote ES. + switch k.OutputType { + case OutputTypeOTLP: + ids = append(ids, k.ID) + default: + if k.Output != "" { + if remoteIds[k.Output] == nil { + remoteIds[k.Output] = make([]string, 0) + } + remoteIds[k.Output] = append(remoteIds[k.Output], k.ID) + } else { + ids = append(ids, k.ID) + } + } + } + if len(ids) > 0 { + zlog.Info().Strs("fleet.policy.apiKeyIDsToRetire", ids).Msg("Invalidate old API keys") + if err := bulk.APIKeyInvalidate(ctx, ids...); err != nil { + zlog.Warn().Err(err).Strs("ids", ids).Msg("Failed to invalidate API keys. API keys will be orphaned.") + } + } + // using remote es bulker to invalidate api key + for outputName, outputIds := range remoteIds { + outputBulk := bulk.GetBulker(outputName) + usedPrimaryFallback := false + + var outputPolicy *model.Policy + if outputBulk == nil { + // read output config from .fleet-policies, not filtering by policy id as agent could be reassigned + var err error + outputPolicy, err = dl.QueryOutputFromPolicy(ctx, bulk, outputName) + if err != nil || outputPolicy == nil { + zlog.Warn().Err(err).Str(ecs.PolicyOutputName, outputName).Any("ids", outputIds).Msg("Output policy not found, falling back to primary cluster for key invalidation") + } else { + outputBulk, _, err = bulk.CreateAndGetBulker(ctx, zlog, outputName, outputPolicy.Data.Outputs) + if err != nil { + zlog.Warn().Err(err).Str(ecs.PolicyOutputName, outputName).Any("ids", outputIds).Msg("Failed to recreate output bulker, falling back to primary cluster for key invalidation") + } + } + } + if outputBulk == nil { + if outputPolicy != nil && outputPolicy.Data.Outputs[outputName]["type"] == OutputTypeRemoteElasticsearch { + zlog.Warn().Str(ecs.PolicyOutputName, outputName).Any("ids", outputIds). + Msg("Cannot invalidate remote ES API keys: remote cluster unreachable, API keys will be orphaned") + continue + } + outputBulk = bulk + usedPrimaryFallback = true + } + if err := outputBulk.APIKeyInvalidate(ctx, outputIds...); err != nil { + zlog.Warn().Err(err).Strs("ids", outputIds).Str(ecs.PolicyOutputName, outputName). + Bool("fallback_to_primary", usedPrimaryFallback). + Msg("Failed to invalidate output API keys. API keys will be orphaned.") + } + } +} + +// DeleteRetiredSecrets deletes the fleet secrets of the given retired API keys. +func DeleteRetiredSecrets(ctx context.Context, zlog zerolog.Logger, bulk bulk.Bulk, toRetireAPIKeyIDs []model.ToRetireAPIKeyIdsItems) { + for _, k := range toRetireAPIKeyIDs { + if k.SecretID == "" { + continue + } + if err := bulk.DeleteSecret(ctx, k.SecretID); err != nil { + zlog.Warn().Err(err).Str("secret_id", k.SecretID).Msg("Failed to delete retired output API key secret") + } + } +} From e74ada5ba353b3fd5a201417dc491e05b4fee85b Mon Sep 17 00:00:00 2001 From: Khushi Jain Date: Thu, 26 Nov 2026 11:55:03 +0530 Subject: [PATCH 2/5] only invalidate the key after ack --- internal/pkg/api/handleAck.go | 101 ++++++++++- internal/pkg/api/handleAck_test.go | 6 +- internal/pkg/api/handleCheckin.go | 7 +- internal/pkg/api/handleCheckin_test.go | 93 ---------- internal/pkg/policy/policy_output.go | 133 +++++++++------ internal/pkg/policy/policy_output_test.go | 197 +++++++++++----------- internal/pkg/policy/retire_outputs.go | 179 -------------------- 7 files changed, 277 insertions(+), 439 deletions(-) delete mode 100644 internal/pkg/policy/retire_outputs.go diff --git a/internal/pkg/api/handleAck.go b/internal/pkg/api/handleAck.go index f3463937ac..740b857f03 100644 --- a/internal/pkg/api/handleAck.go +++ b/internal/pkg/api/handleAck.go @@ -567,8 +567,8 @@ func updateAPIKey(ctx context.Context, // Process retirement records regardless of whether an active key is present. // This handles entries that park records without a live replacement key — e.g., // an mOTLP→external OTLP transition where the output survives but the key is retired. - policy.InvalidateAPIKeys(ctx, zlog, bulk, toRetireAPIKeyIDs, apiKeyID) - policy.DeleteRetiredSecrets(ctx, zlog, bulk, toRetireAPIKeyIDs) + invalidateAPIKeys(ctx, zlog, bulk, toRetireAPIKeyIDs, apiKeyID) + deleteRetiredSecrets(ctx, zlog, bulk, toRetireAPIKeyIDs) return nil } @@ -635,7 +635,7 @@ func cleanRoles(roles json.RawMessage) (json.RawMessage, int, error) { } func (ack *AckT) invalidateAPIKeys(ctx context.Context, zlog zerolog.Logger, toRetireAPIKeyIDs []model.ToRetireAPIKeyIdsItems, skip string) { - policy.InvalidateAPIKeys(ctx, zlog, ack.bulk, toRetireAPIKeyIDs, skip) + invalidateAPIKeys(ctx, zlog, ack.bulk, toRetireAPIKeyIDs, skip) } // handleUnenroll performs the terminal invalidation shared by the legacy @@ -662,7 +662,7 @@ func (ack *AckT) handleUnenroll(ctx context.Context, zlog zerolog.Logger, agent allSecretItems = append(allSecretItems, model.ToRetireAPIKeyIdsItems{SecretID: secretID}) } } - policy.DeleteRetiredSecrets(ctx, zlog, ack.bulk, allSecretItems) + deleteRetiredSecrets(ctx, zlog, ack.bulk, allSecretItems) // unenrolled_at is always stamped here, paired with active: false. The // pending-uninstall step keeps the agent active and deliberately does not set @@ -761,7 +761,7 @@ func (ack *AckT) handleUninstallPending(ctx context.Context, zlog zerolog.Logger secretItems = append(secretItems, model.ToRetireAPIKeyIdsItems{SecretID: secretID}) } } - policy.DeleteRetiredSecrets(ctx, zlog, ack.bulk, secretItems) + deleteRetiredSecrets(ctx, zlog, ack.bulk, secretItems) // Clear the (now-invalidated) output key fields on the agent document so that, // when the agent re-enrolls, policy preparation regenerates fresh keys instead @@ -908,3 +908,94 @@ func makeUpdatePolicyBody(policyID string, newRev int64) []byte { return buf.Bytes() } + +// invalidateAPIKeys retires the given API keys against the correct cluster. +// +// Each item's Output field names the output the key belongs to. +// An empty Output routes directly to the primary cluster (bulk). +// A non-empty Output triggers a remote-bulker lookup: GetBulker is tried first (hot path), +// then CreateAndGetBulker via QueryOutputFromPolicy (cold/restart path). If neither resolves +// a bulker, the primary cluster is used as a fallback — correct for local outputs (elasticsearch, +// otlp) and benign for unreachable remote outputs (primary returns "not found" rather than +// silently dropping the request). +// +// This mirrors the fail-safe pattern in updateAPIKey, which starts with the primary bulker +// and only upgrades to a remote one when available. +func invalidateAPIKeys(ctx context.Context, zlog zerolog.Logger, bulk bulk.Bulk, toRetireAPIKeyIDs []model.ToRetireAPIKeyIdsItems, skip string) { + ids := make([]string, 0, len(toRetireAPIKeyIDs)) + remoteIds := make(map[string][]string) + for _, k := range toRetireAPIKeyIDs { + if k.ID == skip || k.ID == "" { + continue + } + // Route by output_type when available. OTLP keys are always on the primary cluster + // so they go directly into the primary bucket. All other types — including + // "elasticsearch", which the agent doc uses for both local and remote ES after + // normalization — stay on the name-based path so existing routing is preserved + // for records that predate this field or that cannot be distinguished from remote ES. + switch k.OutputType { + case policy.OutputTypeOTLP: + ids = append(ids, k.ID) + default: + if k.Output != "" { + if remoteIds[k.Output] == nil { + remoteIds[k.Output] = make([]string, 0) + } + remoteIds[k.Output] = append(remoteIds[k.Output], k.ID) + } else { + ids = append(ids, k.ID) + } + } + } + if len(ids) > 0 { + zlog.Info().Strs("fleet.policy.apiKeyIDsToRetire", ids).Msg("Invalidate old API keys") + if err := bulk.APIKeyInvalidate(ctx, ids...); err != nil { + zlog.Warn().Err(err).Strs("ids", ids).Msg("Failed to invalidate API keys. API keys will be orphaned.") + } + } + // using remote es bulker to invalidate api key + for outputName, outputIds := range remoteIds { + outputBulk := bulk.GetBulker(outputName) + usedPrimaryFallback := false + + var outputPolicy *model.Policy + if outputBulk == nil { + // read output config from .fleet-policies, not filtering by policy id as agent could be reassigned + var err error + outputPolicy, err = dl.QueryOutputFromPolicy(ctx, bulk, outputName) + if err != nil || outputPolicy == nil { + zlog.Warn().Err(err).Str(ecs.PolicyOutputName, outputName).Any("ids", outputIds).Msg("Output policy not found, falling back to primary cluster for key invalidation") + } else { + outputBulk, _, err = bulk.CreateAndGetBulker(ctx, zlog, outputName, outputPolicy.Data.Outputs) + if err != nil { + zlog.Warn().Err(err).Str(ecs.PolicyOutputName, outputName).Any("ids", outputIds).Msg("Failed to recreate output bulker, falling back to primary cluster for key invalidation") + } + } + } + if outputBulk == nil { + if outputPolicy != nil && outputPolicy.Data.Outputs[outputName]["type"] == policy.OutputTypeRemoteElasticsearch { + zlog.Warn().Str(ecs.PolicyOutputName, outputName).Any("ids", outputIds). + Msg("Cannot invalidate remote ES API keys: remote cluster unreachable, API keys will be orphaned") + continue + } + outputBulk = bulk + usedPrimaryFallback = true + } + if err := outputBulk.APIKeyInvalidate(ctx, outputIds...); err != nil { + zlog.Warn().Err(err).Strs("ids", outputIds).Str(ecs.PolicyOutputName, outputName). + Bool("fallback_to_primary", usedPrimaryFallback). + Msg("Failed to invalidate output API keys. API keys will be orphaned.") + } + } +} + +func deleteRetiredSecrets(ctx context.Context, zlog zerolog.Logger, bulk bulk.Bulk, toRetireAPIKeyIDs []model.ToRetireAPIKeyIdsItems) { + for _, k := range toRetireAPIKeyIDs { + if k.SecretID == "" { + continue + } + if err := bulk.DeleteSecret(ctx, k.SecretID); err != nil { + zlog.Warn().Err(err).Str("secret_id", k.SecretID).Msg("Failed to delete retired output API key secret") + } + } +} diff --git a/internal/pkg/api/handleAck_test.go b/internal/pkg/api/handleAck_test.go index 581dfceb09..8f9a3216ee 100644 --- a/internal/pkg/api/handleAck_test.go +++ b/internal/pkg/api/handleAck_test.go @@ -1268,7 +1268,7 @@ func TestDeleteRetiredSecrets(t *testing.T) { {ID: "key-3"}, // no SecretID — plaintext key, no cleanup needed } - policy.DeleteRetiredSecrets(context.Background(), testlog.SetLogger(t), bulker, items) + deleteRetiredSecrets(context.Background(), testlog.SetLogger(t), bulker, items) bulker.AssertExpectations(t) bulker.AssertNotCalled(t, "DeleteSecret", mock.Anything, "") }) @@ -1282,7 +1282,7 @@ func TestDeleteRetiredSecrets(t *testing.T) { } // Should not panic or propagate the error. - policy.DeleteRetiredSecrets(context.Background(), testlog.SetLogger(t), bulker, items) + deleteRetiredSecrets(context.Background(), testlog.SetLogger(t), bulker, items) bulker.AssertExpectations(t) }) @@ -1292,7 +1292,7 @@ func TestDeleteRetiredSecrets(t *testing.T) { {ID: "key-1"}, {ID: "key-2"}, } - policy.DeleteRetiredSecrets(context.Background(), testlog.SetLogger(t), bulker, items) + deleteRetiredSecrets(context.Background(), testlog.SetLogger(t), bulker, items) bulker.AssertNotCalled(t, "DeleteSecret", mock.Anything, mock.Anything) }) } diff --git a/internal/pkg/api/handleCheckin.go b/internal/pkg/api/handleCheckin.go index cd3192b193..61321bf611 100644 --- a/internal/pkg/api/handleCheckin.go +++ b/internal/pkg/api/handleCheckin.go @@ -210,7 +210,7 @@ func invalidateAPIKeysOfInactiveAgent(ctx context.Context, zlog zerolog.Logger, } } zlog.Info().Any("fleet.policy.apiKeyIDsToRetire", remoteAPIKeys).Msg("handleCheckin invalidate remote API keys") - policy.InvalidateAPIKeys(ctx, zlog, bulker, remoteAPIKeys, "") + invalidateAPIKeys(ctx, zlog, bulker, remoteAPIKeys, "") } // isInvalidAPIKeyErr reports whether err represents an invalid or disabled API key @@ -1231,11 +1231,6 @@ func processPolicy(ctx context.Context, zlog zerolog.Logger, bulker bulk.Bulk, a pp.SecretKeys = append(pp.SecretKeys, "outputs."+name+"."+key) } } - // Retire keys before preparing outputs, as no output with API keys may be left - // to prepare when the policy switched to logstash or kafka. - if err := policy.RetireRemovedOutputs(ctx, zlog, bulker, agent, pp.Policy.Data.Outputs); err != nil { - return nil, nil, fmt.Errorf("failed to retire removed outputs: %w", err) - } // Iterate through the policy outputs and prepare them for _, policyOutput := range pp.Outputs { if err := policyOutput.Prepare(ctx, zlog, bulker, agent, pp.Policy.Data.Outputs, policy.WithOutputSecretCandidateCollector(secretCandidateCollector)); err != nil { diff --git a/internal/pkg/api/handleCheckin_test.go b/internal/pkg/api/handleCheckin_test.go index c0a3e911a0..c333d39880 100644 --- a/internal/pkg/api/handleCheckin_test.go +++ b/internal/pkg/api/handleCheckin_test.go @@ -2032,99 +2032,6 @@ func TestProcessPolicyRemoteESServiceTokenSecretPaths(t *testing.T) { assert.Equal(t, policy.OutputTypeElasticsearch, remotePolicy["type"]) } -func TestProcessPolicyOutputChangedToLogstashIsParkedOnSurvivor(t *testing.T) { - logger := testlog.SetLogger(t) - - const policyPayload = `{ - "id": "es-and-logstash", - "revision": 2, - "outputs": { - "default": { - "type": "elasticsearch", - "hosts": ["https://local.es.example:443"] - }, - "es2": { - "type": "logstash", - "hosts": ["logstash.example:5044"] - } - }, - "output_permissions": { - "default": { - "_fallback": { - "cluster": ["monitor"], - "indices": [{"names": ["logs-*", "metrics-*"], "privileges": ["auto_configure", "create_doc"]}] - } - } - }, - "inputs": [] -}` - - var d model.PolicyData - require.NoError(t, json.Unmarshal([]byte(policyPayload), &d)) - - bulker := ftesting.NewMockBulk() - pp, err := policy.NewParsedPolicy(t.Context(), bulker, model.Policy{ - PolicyID: "policy1", - RevisionIdx: 2, - Data: &d, - }) - require.NoError(t, err) - defaultOut := pp.Outputs["default"] - require.NotNil(t, defaultOut.Role) - - var updates []string - bulker.On("Update", mock.Anything, dl.FleetAgents, "agent1", mock.Anything, mock.Anything). - Run(func(args mock.Arguments) { - updates = append(updates, string(args.Get(3).([]byte))) - }). - Return(nil) - - agent := &model.Agent{ - Id: "agent1", - Outputs: map[string]*model.PolicyOutput{ - "default": { - APIKey: "key1:value", - APIKeyID: "key1", - PermissionsHash: defaultOut.Role.Sha2, - Type: policy.OutputTypeElasticsearch, - }, - // es2 was an elasticsearch output in the previous revision. - "es2": { - APIKey: "key2:value", - APIKeyID: "key2", - PermissionsHash: "previous-hash", - Type: policy.OutputTypeElasticsearch, - }, - }, - } - - _, _, err = processPolicy(t.Context(), logger, bulker, agent, pp, true, nil) - require.NoError(t, err) - - assert.Contains(t, agent.Outputs, "default") - assert.NotContains(t, agent.Outputs, "es2") - - // es2's key is parked on default, then es2 is removed from the agent document. - require.Len(t, updates, 2) - var park struct { - Script struct { - Params struct { - OutputName string `json:"output_name"` - ToRetire model.ToRetireAPIKeyIdsItems `json:"to_retire_api_key_ids"` - } `json:"params"` - } `json:"script"` - } - require.NoError(t, json.Unmarshal([]byte(updates[0]), &park)) - assert.Equal(t, "default", park.Script.Params.OutputName) - assert.Equal(t, "key2", park.Script.Params.ToRetire.ID) - assert.Equal(t, "es2", park.Script.Params.ToRetire.Output) - assert.Equal(t, policy.OutputTypeElasticsearch, park.Script.Params.ToRetire.OutputType) - assert.Contains(t, updates[0], "to_retire_api_key_ids.add(params.to_retire_api_key_ids)") - assert.Contains(t, updates[1], `"output_name":"es2"`) - assert.Contains(t, updates[1], "remove(params.output_name)") - bulker.AssertNotCalled(t, "APIKeyInvalidate", mock.Anything, mock.Anything) -} - // TestProcessPolicyPrunesAgentPinnedInputsSecretPaths ensures inputs pinned to other // agents are not delivered and that secret_paths follow the shifted input/stream indexes. func TestProcessPolicyPrunesAgentPinnedInputsSecretPaths(t *testing.T) { diff --git a/internal/pkg/policy/policy_output.go b/internal/pkg/policy/policy_output.go index 2bde88901f..61cbeb0886 100644 --- a/internal/pkg/policy/policy_output.go +++ b/internal/pkg/policy/policy_output.go @@ -115,10 +115,14 @@ func (p *Output) Prepare(ctx context.Context, zlog zerolog.Logger, bulker bulk.B } case OutputTypeLogstash: zlog.Debug().Msg("preparing logstash output") - zlog.Info().Msg("no actions required for logstash output preparation") + if err := p.prepareWithoutAPIKey(ctx, zlog, bulker, agent, outputMap); err != nil { + return fmt.Errorf("failed to prepare logstash output %q: %w", p.Name, err) + } case OutputTypeKafka: zlog.Debug().Msg("preparing kafka output") - zlog.Info().Msg("no actions required for kafka output preparation") + if err := p.prepareWithoutAPIKey(ctx, zlog, bulker, agent, outputMap); err != nil { + return fmt.Errorf("failed to prepare kafka output %q: %w", p.Name, err) + } case OutputTypeOTLP: zlog.Debug().Msg("preparing OTLP output") if err := p.prepareOTLP(ctx, zlog, bulker, agent, outputMap, cfg.secretCandidateCollector); err != nil { @@ -290,6 +294,67 @@ func (p *Output) prepareElasticsearch( return nil } +// prepareWithoutAPIKey prepares an output that has no per-agent API key, such as a +// logstash, kafka or external OTLP output. Keys of removed outputs, and the previous key +// of this output if it used to have one (e.g. elasticsearch → logstash), are parked on +// this output's agent doc entry and retired once the agent acks the new policy, so the +// agent can keep using them until it has switched outputs. +func (p *Output) prepareWithoutAPIKey( + ctx context.Context, + zlog zerolog.Logger, + bulker bulk.Bulk, + agent *model.Agent, + outputMap map[string]map[string]any) error { + // Ensure an in-memory entry exists so retireRemovedOutputs can park records for + // any concurrently removed outputs onto this surviving output's agent doc entry. + if agent.Outputs == nil { + agent.Outputs = map[string]*model.PolicyOutput{} + } + if _, ok := agent.Outputs[p.Name]; !ok { + agent.Outputs[p.Name] = &model.PolicyOutput{} + } + if err := retireRemovedOutputs(ctx, zlog, bulker, agent, p.Name, outputMap); err != nil { + return err + } + + prev := agent.Outputs[p.Name] + if prev.APIKeyID == "" && prev.APIKey == "" { + return nil + } + // The output had an API key before, e.g. mOTLP → external OTLP or elasticsearch → logstash: + // park a retirement record on this entry and clear the active key fields. The entry + // persists so the ack/checkin gate can retire the key — the same deferred pattern used + // by retireRemovedOutputs for surviving outputs. + retiring := model.ToRetireAPIKeyIdsItems{ + ID: prev.APIKeyID, + RetiredAt: time.Now().UTC().Format(time.RFC3339), + Output: p.Name, + OutputType: prev.Type, + } + if secretID, ok := secret.ParseSecretReference(prev.APIKey); ok { + retiring.SecretID = secretID + } + fields := map[string]any{ + dl.FieldPolicyOutputToRetireAPIKeyIDs: retiring, + dl.FieldPolicyOutputAPIKeyID: "", + dl.FieldPolicyOutputAPIKey: "", + dl.FieldPolicyOutputPermissionsHash: "", + } + body, err := renderUpdatePainlessScript(p.Name, fields) + if err != nil { + return fmt.Errorf("could not render update script to retire previous output API key: %w", err) + } + if err = bulker.Update(ctx, dl.FleetAgents, agent.Id, body, bulk.WithRefresh(), bulk.WithRetryOnConflict(3)); err != nil { + zlog.Error().Err(err).Msg("fail to park retirement record for previous output API key") + return fmt.Errorf("fail update agent record: %w", err) + } + prev.ToRetireAPIKeyIds = append(prev.ToRetireAPIKeyIds, retiring) + prev.APIKeyID = "" + prev.APIKey = "" + prev.PermissionsHash = "" + return nil +} + func (p *Output) prepareOTLP( ctx context.Context, zlog zerolog.Logger, @@ -301,54 +366,7 @@ func (p *Output) prepareOTLP( // Only mOTLP outputs carry an output_permissions block and need API key management. if p.Role == nil { zlog.Debug().Msg("no output permissions for OTLP output; skipping API key management") - - // Ensure an in-memory entry exists so retireRemovedOutputs can park records for - // any concurrently removed outputs onto this surviving output's agent doc entry. - if agent.Outputs == nil { - agent.Outputs = map[string]*model.PolicyOutput{} - } - if _, ok := agent.Outputs[p.Name]; !ok { - agent.Outputs[p.Name] = &model.PolicyOutput{} - } - if err := retireRemovedOutputs(ctx, zlog, bulker, agent, p.Name, outputMap); err != nil { - return err - } - - prev := agent.Outputs[p.Name] - if prev.APIKeyID == "" && prev.APIKey == "" { - return nil - } - // mOTLP → external transition: park a retirement record on this entry and clear the - // active key fields. The entry persists so the ack/checkin gate can retire the key — - // the same deferred pattern used by retireRemovedOutputs for surviving outputs. - retiring := model.ToRetireAPIKeyIdsItems{ - ID: prev.APIKeyID, - RetiredAt: time.Now().UTC().Format(time.RFC3339), - Output: p.Name, - OutputType: prev.Type, - } - if secretID, ok := secret.ParseSecretReference(prev.APIKey); ok { - retiring.SecretID = secretID - } - fields := map[string]any{ - dl.FieldPolicyOutputToRetireAPIKeyIDs: retiring, - dl.FieldPolicyOutputAPIKeyID: "", - dl.FieldPolicyOutputAPIKey: "", - dl.FieldPolicyOutputPermissionsHash: "", - } - body, err := renderUpdatePainlessScript(p.Name, fields) - if err != nil { - return fmt.Errorf("could not render update script for mOTLP→external transition: %w", err) - } - if err = bulker.Update(ctx, dl.FleetAgents, agent.Id, body, bulk.WithRefresh(), bulk.WithRetryOnConflict(3)); err != nil { - zlog.Error().Err(err).Msg("fail to park retirement record for mOTLP→external transition") - return fmt.Errorf("fail update agent record: %w", err) - } - prev.ToRetireAPIKeyIds = append(prev.ToRetireAPIKeyIds, retiring) - prev.APIKeyID = "" - prev.APIKey = "" - prev.PermissionsHash = "" - return nil + return p.prepareWithoutAPIKey(ctx, zlog, bulker, agent, outputMap) } if _, ok := outputMap[p.Name]; !ok { @@ -645,8 +663,7 @@ func agentDocOutputType(t string) string { return t } -// retireRemovedOutputs retires all outputs present in agent.Outputs but absent from outputMap, -// or that no longer have API keys in outputMap (e.g. an elasticsearch output changed to logstash). +// retireRemovedOutputs retires all outputs present in agent.Outputs but absent from outputMap. // For each, it parks a retirement record on survivingOutputName and removes the stale doc entry. // // This is called once per surviving output, so the in-memory delete is essential: without it @@ -666,7 +683,7 @@ func retireRemovedOutputs( outputMap map[string]map[string]any, ) error { for agentOutputName, agentOutput := range agent.Outputs { - if output, ok := outputMap[agentOutputName]; ok && hasAPIKeys(output) { + if _, stillInPolicy := outputMap[agentOutputName]; stillInPolicy { continue } @@ -689,7 +706,15 @@ func retireRemovedOutputs( return r.ID == agentOutput.APIKeyID }) if agentOutput.APIKeyID != "" && !alreadyParked { - retiring := retirementRecord(agentOutputName, agentOutput, time.Now().UTC().Format(time.RFC3339)) + retiring := model.ToRetireAPIKeyIdsItems{ + ID: agentOutput.APIKeyID, + RetiredAt: time.Now().UTC().Format(time.RFC3339), + Output: agentOutputName, + OutputType: agentOutput.Type, + } + if secretID, ok := secret.ParseSecretReference(agentOutput.APIKey); ok { + retiring.SecretID = secretID + } if err := parkRetirementRecord(ctx, zlog, bulker, agent.Id, survivingOutputName, retiring); err != nil { return err } diff --git a/internal/pkg/policy/policy_output_test.go b/internal/pkg/policy/policy_output_test.go index 07ca499371..44966e8495 100644 --- a/internal/pkg/policy/policy_output_test.go +++ b/internal/pkg/policy/policy_output_test.go @@ -10,6 +10,8 @@ import ( "context" "encoding/json" "errors" + "maps" + "slices" "testing" "github.com/stretchr/testify/assert" @@ -19,7 +21,6 @@ import ( "github.com/elastic/elastic-agent-client/v7/pkg/client" "github.com/elastic/fleet-server/v7/internal/pkg/bulk" "github.com/elastic/fleet-server/v7/internal/pkg/dl" - "github.com/elastic/fleet-server/v7/internal/pkg/es" "github.com/elastic/fleet-server/v7/internal/pkg/model" ftesting "github.com/elastic/fleet-server/v7/internal/pkg/testing" testlog "github.com/elastic/fleet-server/v7/internal/pkg/testing/log" @@ -91,7 +92,7 @@ func TestPolicyLogstashOutputPrepare(t *testing.T) { }, } - err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]any{}) + err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]any{po.Name: {"type": po.Type}}) require.Nil(t, err, "expected prepare to pass") bulker.AssertExpectations(t) } @@ -104,7 +105,7 @@ func TestPolicyLogstashOutputPrepareNoRole(t *testing.T) { Role: nil, } - err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]any{}) + err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]any{po.Name: {"type": po.Type}}) // No permissions are required by logstash currently require.Nil(t, err, "expected prepare to pass") bulker.AssertExpectations(t) @@ -122,7 +123,7 @@ func TestPolicyDefaultLogstashOutputPrepare(t *testing.T) { }, } - err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]any{}) + err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]any{po.Name: {"type": po.Type}}) require.Nil(t, err, "expected prepare to pass") bulker.AssertExpectations(t) } @@ -139,7 +140,7 @@ func TestPolicyKafkaOutputPrepare(t *testing.T) { }, } - err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]any{}) + err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]any{po.Name: {"type": po.Type}}) require.Nil(t, err, "expected prepare to pass") bulker.AssertExpectations(t) } @@ -152,7 +153,7 @@ func TestPolicyKafkaOutputPrepareNoRole(t *testing.T) { Role: nil, } - err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]any{}) + err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]any{po.Name: {"type": po.Type}}) // No permissions are required by kafka currently require.Nil(t, err, "expected prepare to pass") bulker.AssertExpectations(t) @@ -1076,80 +1077,92 @@ func TestPolicyRemoteESOutputPrepare(t *testing.T) { }) } -func TestRetireRemovedOutputs(t *testing.T) { - t.Run("retirement is left to Prepare while an output with API keys remains", func(t *testing.T) { - logger := testlog.SetLogger(t) - bulker := ftesting.NewMockBulk() - agent := &model.Agent{ - Outputs: map[string]*model.PolicyOutput{ - "default": {APIKeyID: "key1", Type: OutputTypeElasticsearch}, - "remote": {APIKeyID: "remoteKey1", Type: OutputTypeElasticsearch}, - }, - } - outputMap := map[string]map[string]any{ - "default": {"type": OutputTypeElasticsearch}, - } - - err := RetireRemovedOutputs(t.Context(), logger, bulker, agent, outputMap) - require.NoError(t, err) +type agentUpdateScript struct { + Script struct { + Source string `json:"source"` + Params struct { + OutputName string `json:"output_name"` + ToRetire *model.ToRetireAPIKeyIdsItems `json:"to_retire_api_key_ids"` + APIKeyID *string `json:"api_key_id"` + } `json:"params"` + } `json:"script"` +} - assert.Len(t, agent.Outputs, 2) - bulker.AssertNotCalled(t, "Update", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) - bulker.AssertNotCalled(t, "APIKeyInvalidate", mock.Anything, mock.Anything) - }) +func captureAgentUpdates(t *testing.T, bulker *ftesting.MockBulk, agentID string) *[]agentUpdateScript { + t.Helper() + var updates []agentUpdateScript + bulker.On("Update", mock.Anything, dl.FleetAgents, agentID, mock.Anything, mock.Anything). + Run(func(args mock.Arguments) { + var u agentUpdateScript + require.NoError(t, json.Unmarshal(args.Get(3).([]byte), &u)) + updates = append(updates, u) + }). + Return(nil) + return &updates +} - t.Run("keys are invalidated immediately when policy switches to logstash only", func(t *testing.T) { +func TestPolicyOutputPrepareWithoutAPIKey(t *testing.T) { + t.Run("removed outputs are parked on the kafka output when no output with API keys is left", func(t *testing.T) { logger := testlog.SetLogger(t) bulker := ftesting.NewMockBulk() - remoteBulker := ftesting.NewMockBulk() - - bulker.On("GetBulker", "default").Return(nil) - bulker.On("GetBulker", "remote").Return(remoteBulker) - // the local output is not found in any policy, so its key falls back to the primary cluster - bulker.On("Search", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&es.ResultT{}, nil) - bulker.On("APIKeyInvalidate", mock.Anything, []string{"key1"}).Return(nil).Once() - remoteBulker.On("APIKeyInvalidate", mock.Anything, []string{"remoteKey1"}).Return(nil).Once() - bulker.On("DeleteSecret", mock.Anything, "secret1").Return(nil).Once() - // one update per removed output to delete it from the agent document - bulker.On("Update", mock.Anything, dl.FleetAgents, "agent1", mock.Anything, mock.Anything).Return(nil).Twice() + updates := captureAgentUpdates(t, bulker, "agent1") agent := &model.Agent{ ESDocument: model.ESDocument{Id: "agent1"}, Outputs: map[string]*model.PolicyOutput{ "default": {APIKey: "$co.elastic.secret{secret1}", APIKeyID: "key1", Type: OutputTypeElasticsearch}, - "remote": {APIKeyID: "remoteKey1", Type: OutputTypeElasticsearch}, + "remote": { + APIKeyID: "remoteKey1", + Type: OutputTypeElasticsearch, + ToRetireAPIKeyIds: []model.ToRetireAPIKeyIdsItems{{ID: "oldRemoteKey", Output: "remote"}}, + }, }, } outputMap := map[string]map[string]any{ - "ls": {"type": OutputTypeLogstash}, + "kafka": {"type": OutputTypeKafka}, } - err := RetireRemovedOutputs(t.Context(), logger, bulker, agent, outputMap) - require.NoError(t, err) + output := Output{Name: "kafka", Type: OutputTypeKafka} + require.NoError(t, output.Prepare(t.Context(), logger, bulker, agent, outputMap)) - assert.Empty(t, agent.Outputs) - bulker.AssertExpectations(t) - remoteBulker.AssertExpectations(t) + parked := map[string]model.ToRetireAPIKeyIdsItems{} + var removed []string + for _, u := range *updates { + if u.Script.Params.ToRetire != nil { + assert.Equal(t, "kafka", u.Script.Params.OutputName) + parked[u.Script.Params.ToRetire.ID] = *u.Script.Params.ToRetire + continue + } + assert.Contains(t, u.Script.Source, "remove(params.output_name)") + removed = append(removed, u.Script.Params.OutputName) + } + assert.ElementsMatch(t, []string{"default", "remote"}, removed) + require.Len(t, parked, 3) + assert.Equal(t, model.ToRetireAPIKeyIdsItems{ + ID: "key1", RetiredAt: parked["key1"].RetiredAt, Output: "default", OutputType: OutputTypeElasticsearch, SecretID: "secret1", + }, parked["key1"]) + assert.Equal(t, "remote", parked["remoteKey1"].Output) + assert.Equal(t, "remote", parked["oldRemoteKey"].Output) + + assert.Equal(t, []string{"kafka"}, slices.Sorted(maps.Keys(agent.Outputs))) + bulker.AssertNotCalled(t, "APIKeyInvalidate", mock.Anything, mock.Anything) + bulker.AssertNotCalled(t, "DeleteSecret", mock.Anything, mock.Anything) }) - t.Run("key is invalidated immediately when output type changes from elasticsearch to logstash", func(t *testing.T) { + t.Run("key of output changed from elasticsearch to logstash is parked on itself", func(t *testing.T) { logger := testlog.SetLogger(t) bulker := ftesting.NewMockBulk() - - bulker.On("GetBulker", "default").Return(nil) - bulker.On("Search", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&es.ResultT{}, nil) - // the pending key from a previous rotation is invalidated as well - bulker.On("APIKeyInvalidate", mock.Anything, []string{"oldKey"}).Return(nil).Once() - bulker.On("APIKeyInvalidate", mock.Anything, []string{"key1"}).Return(nil).Once() - bulker.On("Update", mock.Anything, dl.FleetAgents, "agent1", mock.Anything, mock.Anything).Return(nil).Once() + updates := captureAgentUpdates(t, bulker, "agent1") agent := &model.Agent{ ESDocument: model.ESDocument{Id: "agent1"}, Outputs: map[string]*model.PolicyOutput{ "default": { + APIKey: "$co.elastic.secret{secret1}", APIKeyID: "key1", + PermissionsHash: "hash1", Type: OutputTypeElasticsearch, - ToRetireAPIKeyIds: []model.ToRetireAPIKeyIdsItems{{ID: "oldKey"}}, + ToRetireAPIKeyIds: []model.ToRetireAPIKeyIdsItems{{ID: "oldKey", Output: "default"}}, }, }, } @@ -1157,60 +1170,46 @@ func TestRetireRemovedOutputs(t *testing.T) { "default": {"type": OutputTypeLogstash}, } - err := RetireRemovedOutputs(t.Context(), logger, bulker, agent, outputMap) - require.NoError(t, err) - - assert.Empty(t, agent.Outputs) - bulker.AssertExpectations(t) - }) -} - -func TestRetireRemovedOutputsTypeChange(t *testing.T) { - t.Run("output changed to logstash is parked on surviving output", func(t *testing.T) { - logger := testlog.SetLogger(t) - bulker := ftesting.NewMockBulk() - // one update to park the key on the survivor and one to delete the changed output - bulker.On("Update", mock.Anything, dl.FleetAgents, "agent1", mock.Anything, mock.Anything).Return(nil).Twice() - - agent := &model.Agent{ - ESDocument: model.ESDocument{Id: "agent1"}, - Outputs: map[string]*model.PolicyOutput{ - "default": {APIKeyID: "key1", Type: OutputTypeElasticsearch}, - "es2": {APIKeyID: "key2", Type: OutputTypeElasticsearch}, - }, - } - outputMap := map[string]map[string]any{ - "default": {"type": OutputTypeElasticsearch}, - "es2": {"type": OutputTypeLogstash}, - } - - err := retireRemovedOutputs(t.Context(), logger, bulker, agent, "default", outputMap) - require.NoError(t, err) - - assert.Contains(t, agent.Outputs, "default") - assert.NotContains(t, agent.Outputs, "es2") - bulker.AssertExpectations(t) + output := Output{Name: "default", Type: OutputTypeLogstash} + require.NoError(t, output.Prepare(t.Context(), logger, bulker, agent, outputMap)) + + require.Len(t, *updates, 1) + park := (*updates)[0].Script.Params + assert.Equal(t, "default", park.OutputName) + require.NotNil(t, park.ToRetire) + assert.Equal(t, "key1", park.ToRetire.ID) + assert.Equal(t, "secret1", park.ToRetire.SecretID) + assert.Equal(t, OutputTypeElasticsearch, park.ToRetire.OutputType) + require.NotNil(t, park.APIKeyID) + assert.Empty(t, *park.APIKeyID) + + out := agent.Outputs["default"] + require.NotNil(t, out) + assert.Empty(t, out.APIKeyID) + assert.Empty(t, out.APIKey) + assert.Empty(t, out.PermissionsHash) + require.Len(t, out.ToRetireAPIKeyIds, 2) + assert.Equal(t, "oldKey", out.ToRetireAPIKeyIds[0].ID) + assert.Equal(t, "key1", out.ToRetireAPIKeyIds[1].ID) + + // the next check-in finds no active key left to retire + require.NoError(t, output.Prepare(t.Context(), logger, bulker, agent, outputMap)) + assert.Len(t, *updates, 1) bulker.AssertNotCalled(t, "APIKeyInvalidate", mock.Anything, mock.Anything) }) - t.Run("output without type is kept", func(t *testing.T) { + t.Run("logstash output without a previous key needs no update", func(t *testing.T) { logger := testlog.SetLogger(t) bulker := ftesting.NewMockBulk() - - agent := &model.Agent{ - ESDocument: model.ESDocument{Id: "agent1"}, - Outputs: map[string]*model.PolicyOutput{ - "default": {APIKeyID: "key1", Type: OutputTypeElasticsearch}, - }, - } + agent := &model.Agent{ESDocument: model.ESDocument{Id: "agent1"}} outputMap := map[string]map[string]any{ - "default": {}, + "ls": {"type": OutputTypeLogstash}, } - err := retireRemovedOutputs(t.Context(), logger, bulker, agent, "default", outputMap) - require.NoError(t, err) + output := Output{Name: "ls", Type: OutputTypeLogstash} + require.NoError(t, output.Prepare(t.Context(), logger, bulker, agent, outputMap)) - assert.Contains(t, agent.Outputs, "default") + assert.Equal(t, []string{"ls"}, slices.Sorted(maps.Keys(agent.Outputs))) bulker.AssertNotCalled(t, "Update", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) }) } diff --git a/internal/pkg/policy/retire_outputs.go b/internal/pkg/policy/retire_outputs.go deleted file mode 100644 index 3d4f67be68..0000000000 --- a/internal/pkg/policy/retire_outputs.go +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one -// or more contributor license agreements. Licensed under the Elastic License 2.0; -// you may not use this file except in compliance with the Elastic License 2.0. - -package policy - -import ( - "context" - "fmt" - "maps" - "slices" - "time" - - "github.com/rs/zerolog" - - "github.com/elastic/fleet-server/v7/internal/pkg/bulk" - "github.com/elastic/fleet-server/v7/internal/pkg/dl" - "github.com/elastic/fleet-server/v7/internal/pkg/logger/ecs" - "github.com/elastic/fleet-server/v7/internal/pkg/model" - "github.com/elastic/fleet-server/v7/internal/pkg/secret" -) - -// RetireRemovedOutputs retires the API keys of all agent outputs when the policy has -// no output with API keys left, e.g. when it switched to logstash or kafka. The keys -// are invalidated immediately, as there is no remaining output to park them on until ack. -// Otherwise, removed outputs are retired while preparing the remaining outputs, see -// retireRemovedOutputs. -func RetireRemovedOutputs(ctx context.Context, zlog zerolog.Logger, bulker bulk.Bulk, agent *model.Agent, outputMap map[string]map[string]any) error { - if len(agent.Outputs) == 0 { - return nil - } - for _, output := range outputMap { - if hasAPIKeys(output) { - return nil - } - } - - names := slices.Sorted(maps.Keys(agent.Outputs)) - - retiredAt := time.Now().UTC().Format(time.RFC3339) - toRetire := make([]model.ToRetireAPIKeyIdsItems, 0, len(names)) - for _, name := range names { - out := agent.Outputs[name] - toRetire = append(toRetire, out.ToRetireAPIKeyIds...) - if out.APIKeyID == "" { - continue - } - zlog.Info().Str(ecs.APIKeyID, out.APIKeyID).Str(ecs.PolicyOutputName, name).Msg("Output removed, retiring API key") - toRetire = append(toRetire, retirementRecord(name, out, retiredAt)) - } - InvalidateAPIKeys(ctx, zlog, bulker, toRetire, "") - DeleteRetiredSecrets(ctx, zlog, bulker, toRetire) - - for _, name := range names { - body, err := renderRemoveOutputPainlessScript(name) - if err != nil { - return fmt.Errorf("could not create request body to update agent: %w", err) - } - if err := bulker.Update(ctx, dl.FleetAgents, agent.Id, body, bulk.WithRefresh(), bulk.WithRetryOnConflict(3)); err != nil { - zlog.Error().Err(err).Msg("fail update agent record") - return fmt.Errorf("fail update agent record: %w", err) - } - delete(agent.Outputs, name) - } - return nil -} - -// retirementRecord returns the record used to retire the active API key of an agent output. -func retirementRecord(outputName string, out *model.PolicyOutput, retiredAt string) model.ToRetireAPIKeyIdsItems { - record := model.ToRetireAPIKeyIdsItems{ - ID: out.APIKeyID, - RetiredAt: retiredAt, - Output: outputName, - OutputType: out.Type, - } - if secretID, ok := secret.ParseSecretReference(out.APIKey); ok { - record.SecretID = secretID - } - return record -} - -// hasAPIKeys reports whether the policy output may have per-agent API keys. Outputs -// without a type are assumed to have them, so that their keys are never retired by mistake. -func hasAPIKeys(output map[string]any) bool { - t, _ := output[FieldOutputType].(string) - return t == "" || t == OutputTypeElasticsearch || t == OutputTypeRemoteElasticsearch || t == OutputTypeOTLP -} - -// InvalidateAPIKeys retires the given API keys against the correct cluster. -// -// Each item's Output field names the output the key belongs to. -// An empty Output routes directly to the primary cluster (bulk). -// A non-empty Output triggers a remote-bulker lookup: GetBulker is tried first (hot path), -// then CreateAndGetBulker via QueryOutputFromPolicy (cold/restart path). If neither resolves -// a bulker, the primary cluster is used as a fallback — correct for local outputs (elasticsearch, -// otlp) and benign for unreachable remote outputs (primary returns "not found" rather than -// silently dropping the request). -// -// This mirrors the fail-safe pattern in updateAPIKey, which starts with the primary bulker -// and only upgrades to a remote one when available. -func InvalidateAPIKeys(ctx context.Context, zlog zerolog.Logger, bulk bulk.Bulk, toRetireAPIKeyIDs []model.ToRetireAPIKeyIdsItems, skip string) { - ids := make([]string, 0, len(toRetireAPIKeyIDs)) - remoteIds := make(map[string][]string) - for _, k := range toRetireAPIKeyIDs { - if k.ID == skip || k.ID == "" { - continue - } - // Route by output_type when available. OTLP keys are always on the primary cluster - // so they go directly into the primary bucket. All other types — including - // "elasticsearch", which the agent doc uses for both local and remote ES after - // normalization — stay on the name-based path so existing routing is preserved - // for records that predate this field or that cannot be distinguished from remote ES. - switch k.OutputType { - case OutputTypeOTLP: - ids = append(ids, k.ID) - default: - if k.Output != "" { - if remoteIds[k.Output] == nil { - remoteIds[k.Output] = make([]string, 0) - } - remoteIds[k.Output] = append(remoteIds[k.Output], k.ID) - } else { - ids = append(ids, k.ID) - } - } - } - if len(ids) > 0 { - zlog.Info().Strs("fleet.policy.apiKeyIDsToRetire", ids).Msg("Invalidate old API keys") - if err := bulk.APIKeyInvalidate(ctx, ids...); err != nil { - zlog.Warn().Err(err).Strs("ids", ids).Msg("Failed to invalidate API keys. API keys will be orphaned.") - } - } - // using remote es bulker to invalidate api key - for outputName, outputIds := range remoteIds { - outputBulk := bulk.GetBulker(outputName) - usedPrimaryFallback := false - - var outputPolicy *model.Policy - if outputBulk == nil { - // read output config from .fleet-policies, not filtering by policy id as agent could be reassigned - var err error - outputPolicy, err = dl.QueryOutputFromPolicy(ctx, bulk, outputName) - if err != nil || outputPolicy == nil { - zlog.Warn().Err(err).Str(ecs.PolicyOutputName, outputName).Any("ids", outputIds).Msg("Output policy not found, falling back to primary cluster for key invalidation") - } else { - outputBulk, _, err = bulk.CreateAndGetBulker(ctx, zlog, outputName, outputPolicy.Data.Outputs) - if err != nil { - zlog.Warn().Err(err).Str(ecs.PolicyOutputName, outputName).Any("ids", outputIds).Msg("Failed to recreate output bulker, falling back to primary cluster for key invalidation") - } - } - } - if outputBulk == nil { - if outputPolicy != nil && outputPolicy.Data.Outputs[outputName]["type"] == OutputTypeRemoteElasticsearch { - zlog.Warn().Str(ecs.PolicyOutputName, outputName).Any("ids", outputIds). - Msg("Cannot invalidate remote ES API keys: remote cluster unreachable, API keys will be orphaned") - continue - } - outputBulk = bulk - usedPrimaryFallback = true - } - if err := outputBulk.APIKeyInvalidate(ctx, outputIds...); err != nil { - zlog.Warn().Err(err).Strs("ids", outputIds).Str(ecs.PolicyOutputName, outputName). - Bool("fallback_to_primary", usedPrimaryFallback). - Msg("Failed to invalidate output API keys. API keys will be orphaned.") - } - } -} - -// DeleteRetiredSecrets deletes the fleet secrets of the given retired API keys. -func DeleteRetiredSecrets(ctx context.Context, zlog zerolog.Logger, bulk bulk.Bulk, toRetireAPIKeyIDs []model.ToRetireAPIKeyIdsItems) { - for _, k := range toRetireAPIKeyIDs { - if k.SecretID == "" { - continue - } - if err := bulk.DeleteSecret(ctx, k.SecretID); err != nil { - zlog.Warn().Err(err).Str("secret_id", k.SecretID).Msg("Failed to delete retired output API key secret") - } - } -} From 81c830db34e2fdd3165c4d87a7bb7e357bdf6d07 Mon Sep 17 00:00:00 2001 From: Khushi Jain Date: Thu, 26 Nov 2026 12:04:04 +0530 Subject: [PATCH 3/5] fix lint --- internal/pkg/policy/policy_output.go | 19 ++++++++----------- internal/pkg/policy/policy_output_test.go | 15 ++++++++++----- 2 files changed, 18 insertions(+), 16 deletions(-) diff --git a/internal/pkg/policy/policy_output.go b/internal/pkg/policy/policy_output.go index 61cbeb0886..343f8bc0c7 100644 --- a/internal/pkg/policy/policy_output.go +++ b/internal/pkg/policy/policy_output.go @@ -594,23 +594,20 @@ ctx._source['outputs'][params.output_name].%s=params.%s;`, field, field) maps.Copy(params, fields) params["output_name"] = outputName - body, err := json.Marshal(map[string]any{ - "script": map[string]any{ - "lang": "painless", - "source": source.String(), - "params": params, - }, - }) - - return body, err + return renderPainlessScript(source.String(), params) } func renderRemoveOutputPainlessScript(outputName string) ([]byte, error) { + return renderPainlessScript("ctx._source['outputs'].remove(params.output_name)", map[string]any{"output_name": outputName}) +} + +// renderPainlessScript renders the body of an update request running the painless source with params. +func renderPainlessScript(source string, params map[string]any) ([]byte, error) { return json.Marshal(map[string]any{ "script": map[string]any{ "lang": "painless", - "source": "ctx._source['outputs'].remove(params.output_name)", - "params": map[string]any{"output_name": outputName}, + "source": source, + "params": params, }, }) } diff --git a/internal/pkg/policy/policy_output_test.go b/internal/pkg/policy/policy_output_test.go index 44966e8495..aa5eab1523 100644 --- a/internal/pkg/policy/policy_output_test.go +++ b/internal/pkg/policy/policy_output_test.go @@ -1093,8 +1093,10 @@ func captureAgentUpdates(t *testing.T, bulker *ftesting.MockBulk, agentID string var updates []agentUpdateScript bulker.On("Update", mock.Anything, dl.FleetAgents, agentID, mock.Anything, mock.Anything). Run(func(args mock.Arguments) { + body, ok := args.Get(3).([]byte) + require.True(t, ok) var u agentUpdateScript - require.NoError(t, json.Unmarshal(args.Get(3).([]byte), &u)) + require.NoError(t, json.Unmarshal(body, &u)) updates = append(updates, u) }). Return(nil) @@ -1102,6 +1104,9 @@ func captureAgentUpdates(t *testing.T, bulker *ftesting.MockBulk, agentID string } func TestPolicyOutputPrepareWithoutAPIKey(t *testing.T) { + const secretID = "secret1" + secretRef := "$co.elastic.secret{" + secretID + "}" + t.Run("removed outputs are parked on the kafka output when no output with API keys is left", func(t *testing.T) { logger := testlog.SetLogger(t) bulker := ftesting.NewMockBulk() @@ -1110,7 +1115,7 @@ func TestPolicyOutputPrepareWithoutAPIKey(t *testing.T) { agent := &model.Agent{ ESDocument: model.ESDocument{Id: "agent1"}, Outputs: map[string]*model.PolicyOutput{ - "default": {APIKey: "$co.elastic.secret{secret1}", APIKeyID: "key1", Type: OutputTypeElasticsearch}, + "default": {APIKey: secretRef, APIKeyID: "key1", Type: OutputTypeElasticsearch}, "remote": { APIKeyID: "remoteKey1", Type: OutputTypeElasticsearch, @@ -1139,7 +1144,7 @@ func TestPolicyOutputPrepareWithoutAPIKey(t *testing.T) { assert.ElementsMatch(t, []string{"default", "remote"}, removed) require.Len(t, parked, 3) assert.Equal(t, model.ToRetireAPIKeyIdsItems{ - ID: "key1", RetiredAt: parked["key1"].RetiredAt, Output: "default", OutputType: OutputTypeElasticsearch, SecretID: "secret1", + ID: "key1", RetiredAt: parked["key1"].RetiredAt, Output: "default", OutputType: OutputTypeElasticsearch, SecretID: secretID, }, parked["key1"]) assert.Equal(t, "remote", parked["remoteKey1"].Output) assert.Equal(t, "remote", parked["oldRemoteKey"].Output) @@ -1158,7 +1163,7 @@ func TestPolicyOutputPrepareWithoutAPIKey(t *testing.T) { ESDocument: model.ESDocument{Id: "agent1"}, Outputs: map[string]*model.PolicyOutput{ "default": { - APIKey: "$co.elastic.secret{secret1}", + APIKey: secretRef, APIKeyID: "key1", PermissionsHash: "hash1", Type: OutputTypeElasticsearch, @@ -1178,7 +1183,7 @@ func TestPolicyOutputPrepareWithoutAPIKey(t *testing.T) { assert.Equal(t, "default", park.OutputName) require.NotNil(t, park.ToRetire) assert.Equal(t, "key1", park.ToRetire.ID) - assert.Equal(t, "secret1", park.ToRetire.SecretID) + assert.Equal(t, secretID, park.ToRetire.SecretID) assert.Equal(t, OutputTypeElasticsearch, park.ToRetire.OutputType) require.NotNil(t, park.APIKeyID) assert.Empty(t, *park.APIKeyID) From 1fa1011ebd6858c587c65a2b0bcb1e583182b213 Mon Sep 17 00:00:00 2001 From: Khushi Jain Date: Thu, 26 Nov 2026 12:46:13 +0530 Subject: [PATCH 4/5] fix lint --- internal/pkg/policy/policy_output_test.go | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/internal/pkg/policy/policy_output_test.go b/internal/pkg/policy/policy_output_test.go index aa5eab1523..2afeeba6d4 100644 --- a/internal/pkg/policy/policy_output_test.go +++ b/internal/pkg/policy/policy_output_test.go @@ -788,7 +788,9 @@ func TestPolicyOTLPOutputPrepareRetiresRemovedOutput(t *testing.T) { // If there were pending records, verify the first call transferred one of them. if len(tc.pendingRecords) > 0 { - transferParams := parseParkParams(t, bulker.Calls[0].Arguments.Get(3).([]byte)) + transferBody, ok := bulker.Calls[0].Arguments.Get(3).([]byte) + require.True(t, ok, "first Update body must be []byte") + transferParams := parseParkParams(t, transferBody) transferRecord, ok := transferParams[dl.FieldPolicyOutputToRetireAPIKeyIDs].(map[string]any) require.True(t, ok, "first Update must be a transfer of the pending record") assert.Equal(t, pendingKeyID, transferRecord["id"]) @@ -796,7 +798,9 @@ func TestPolicyOTLPOutputPrepareRetiresRemovedOutput(t *testing.T) { // The second-to-last call parks the removed output's active key onto the incoming output. // Requirement (a): this call precedes the remove — enforced by NotBefore above. - parkParams := parseParkParams(t, bulker.Calls[tc.wantCalls-2].Arguments.Get(3).([]byte)) + parkBody, ok := bulker.Calls[tc.wantCalls-2].Arguments.Get(3).([]byte) + require.True(t, ok, "park Update body must be []byte") + parkParams := parseParkParams(t, parkBody) parkRecord, ok := parkParams[dl.FieldPolicyOutputToRetireAPIKeyIDs].(map[string]any) require.True(t, ok, "park body must contain a retirement record map") assert.Equal(t, removedKeyID, parkRecord["id"]) @@ -1036,7 +1040,7 @@ func TestPolicyRemoteESOutputPrepare(t *testing.T) { logger := testlog.SetLogger(t) bulker := ftesting.NewMockBulk() var apiKey *bulk.APIKey = nil - var err error = errors.New("error connecting") + err := errors.New("error connecting") outputBulker := ftesting.NewMockBulk() outputBulker.On("APIKeyCreate", From a718680ed9505236644c46fb0ec6436e8eea3e9c Mon Sep 17 00:00:00 2001 From: Khushi Jain Date: Thu, 26 Nov 2026 14:45:05 +0530 Subject: [PATCH 5/5] make check ci --- internal/pkg/policy/policy_output_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/pkg/policy/policy_output_test.go b/internal/pkg/policy/policy_output_test.go index 2afeeba6d4..b696f6692c 100644 --- a/internal/pkg/policy/policy_output_test.go +++ b/internal/pkg/policy/policy_output_test.go @@ -1117,7 +1117,7 @@ func TestPolicyOutputPrepareWithoutAPIKey(t *testing.T) { updates := captureAgentUpdates(t, bulker, "agent1") agent := &model.Agent{ - ESDocument: model.ESDocument{Id: "agent1"}, + Id: "agent1", Outputs: map[string]*model.PolicyOutput{ "default": {APIKey: secretRef, APIKeyID: "key1", Type: OutputTypeElasticsearch}, "remote": { @@ -1164,7 +1164,7 @@ func TestPolicyOutputPrepareWithoutAPIKey(t *testing.T) { updates := captureAgentUpdates(t, bulker, "agent1") agent := &model.Agent{ - ESDocument: model.ESDocument{Id: "agent1"}, + Id: "agent1", Outputs: map[string]*model.PolicyOutput{ "default": { APIKey: secretRef, @@ -1210,7 +1210,7 @@ func TestPolicyOutputPrepareWithoutAPIKey(t *testing.T) { t.Run("logstash output without a previous key needs no update", func(t *testing.T) { logger := testlog.SetLogger(t) bulker := ftesting.NewMockBulk() - agent := &model.Agent{ESDocument: model.ESDocument{Id: "agent1"}} + agent := &model.Agent{Id: "agent1"} outputMap := map[string]map[string]any{ "ls": {"type": OutputTypeLogstash}, }