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..740b857f03 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; diff --git a/internal/pkg/policy/policy_output.go b/internal/pkg/policy/policy_output.go index 8a4ec70111..343f8bc0c7 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 { @@ -576,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 0d54d350c0..b696f6692c 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" @@ -90,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) } @@ -103,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) @@ -121,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) } @@ -138,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) } @@ -151,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) @@ -786,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"]) @@ -794,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"]) @@ -1034,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", @@ -1074,3 +1080,145 @@ func TestPolicyRemoteESOutputPrepare(t *testing.T) { bulker.AssertExpectations(t) }) } + +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"` +} + +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) { + body, ok := args.Get(3).([]byte) + require.True(t, ok) + var u agentUpdateScript + require.NoError(t, json.Unmarshal(body, &u)) + updates = append(updates, u) + }). + Return(nil) + return &updates +} + +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() + updates := captureAgentUpdates(t, bulker, "agent1") + + agent := &model.Agent{ + Id: "agent1", + Outputs: map[string]*model.PolicyOutput{ + "default": {APIKey: secretRef, APIKeyID: "key1", Type: OutputTypeElasticsearch}, + "remote": { + APIKeyID: "remoteKey1", + Type: OutputTypeElasticsearch, + ToRetireAPIKeyIds: []model.ToRetireAPIKeyIdsItems{{ID: "oldRemoteKey", Output: "remote"}}, + }, + }, + } + outputMap := map[string]map[string]any{ + "kafka": {"type": OutputTypeKafka}, + } + + output := Output{Name: "kafka", Type: OutputTypeKafka} + require.NoError(t, output.Prepare(t.Context(), logger, bulker, agent, outputMap)) + + 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: secretID, + }, 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 of output changed from elasticsearch to logstash is parked on itself", func(t *testing.T) { + logger := testlog.SetLogger(t) + bulker := ftesting.NewMockBulk() + updates := captureAgentUpdates(t, bulker, "agent1") + + agent := &model.Agent{ + Id: "agent1", + Outputs: map[string]*model.PolicyOutput{ + "default": { + APIKey: secretRef, + APIKeyID: "key1", + PermissionsHash: "hash1", + Type: OutputTypeElasticsearch, + ToRetireAPIKeyIds: []model.ToRetireAPIKeyIdsItems{{ID: "oldKey", Output: "default"}}, + }, + }, + } + outputMap := map[string]map[string]any{ + "default": {"type": OutputTypeLogstash}, + } + + 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, secretID, 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("logstash output without a previous key needs no update", func(t *testing.T) { + logger := testlog.SetLogger(t) + bulker := ftesting.NewMockBulk() + agent := &model.Agent{Id: "agent1"} + outputMap := map[string]map[string]any{ + "ls": {"type": OutputTypeLogstash}, + } + + output := Output{Name: "ls", Type: OutputTypeLogstash} + require.NoError(t, output.Prepare(t.Context(), logger, bulker, agent, outputMap)) + + 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) + }) +}