Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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
4 changes: 2 additions & 2 deletions internal/pkg/api/handleAck.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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;
Expand Down
137 changes: 76 additions & 61 deletions internal/pkg/policy/policy_output.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Comment on lines +328 to +332
}
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,
Expand All @@ -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 {
Expand Down Expand Up @@ -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,
},
})
}
Expand Down
Loading
Loading