-
Notifications
You must be signed in to change notification settings - Fork 81
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add /api/fleet/agents/:id/audit/unenroll
endpoint
#3818
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
a9ab996
Add schema definitions and auto generated code
michel-laterman 360d12d
Add boilerplate for new endpoint
michel-laterman 19ad629
Audit unenroll endpoint logic
michel-laterman 4855f5b
Don't set inactive state
michel-laterman ecdee7f
fix e2e tests
michel-laterman b933d9d
Fix typo in ErrAuditUnenrollReason message
michel-laterman File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
36 changes: 36 additions & 0 deletions
36
changelog/fragments/1723590385-Add-audit-unenroll-API.yaml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
# Kind can be one of: | ||
# - breaking-change: a change to previously-documented behavior | ||
# - deprecation: functionality that is being removed in a later release | ||
# - bug-fix: fixes a problem in a previous version | ||
# - enhancement: extends functionality but does not break or fix existing behavior | ||
# - feature: new functionality | ||
# - known-issue: problems that we are aware of in a given version | ||
# - security: impacts on the security of a product or a user’s deployment. | ||
# - upgrade: important information for someone upgrading from a prior version | ||
# - other: does not fit into any of the other categories | ||
kind: feature | ||
|
||
# Change summary; a 80ish characters long description of the change. | ||
summary: Add audit/unenroll API | ||
|
||
# Long description; in case the summary is not enough to describe the change | ||
# this field accommodate a description without length limits. | ||
# NOTE: This field will be rendered only for breaking-change and known-issue kinds at the moment. | ||
description: | | ||
Add the /api/fleet/agents/:id/audit/unenroll API that elastic-agent | ||
and Endpoint instances may use to annotate the agent document when | ||
the agent is uninstalled or Endpoint detects it is in an orphaned | ||
state. | ||
|
||
# Affected component; a word indicating the component this changeset affects. | ||
component: | ||
|
||
# PR URL; optional; the PR number that added the changeset. | ||
# If not present is automatically filled by the tooling finding the PR where this changelog fragment has been added. | ||
# NOTE: the tooling supports backports, so it's able to fill the original PR number instead of the backport PR number. | ||
# Please provide it if you are adding a fragment for a different PR. | ||
pr: https://github.com/elastic/fleet-server/pull/3818 | ||
|
||
# Issue URL; optional; the GitHub issue related to this changeset (either closes or is part of). | ||
# If not present is automatically filled by the tooling with the issue linked to the PR number. | ||
issue: https://github.com/elastic/elastic-agent/issues/484 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,122 @@ | ||
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
// or more contributor license agreements. Licensed under the Elastic License; | ||
// you may not use this file except in compliance with the Elastic License. | ||
|
||
package api | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"fmt" | ||
"net/http" | ||
"time" | ||
|
||
"github.com/elastic/fleet-server/v7/internal/pkg/bulk" | ||
"github.com/elastic/fleet-server/v7/internal/pkg/cache" | ||
"github.com/elastic/fleet-server/v7/internal/pkg/config" | ||
"github.com/elastic/fleet-server/v7/internal/pkg/dl" | ||
"github.com/elastic/fleet-server/v7/internal/pkg/model" | ||
|
||
"github.com/miolini/datacounter" | ||
"github.com/rs/zerolog" | ||
"go.elastic.co/apm/v2" | ||
) | ||
|
||
var ErrAuditUnenrollReason = fmt.Errorf("agent document contains audit_unenroll_reason attribute") | ||
|
||
type AuditT struct { | ||
cfg *config.Server | ||
bulk bulk.Bulk | ||
cache cache.Cache | ||
} | ||
|
||
func NewAuditT(cfg *config.Server, bulker bulk.Bulk, cache cache.Cache) *AuditT { | ||
return &AuditT{ | ||
cfg: cfg, | ||
bulk: bulker, | ||
cache: cache, | ||
} | ||
} | ||
|
||
func (audit *AuditT) handleUnenroll(zlog zerolog.Logger, w http.ResponseWriter, r *http.Request, id string) error { | ||
agent, err := authAgent(r, &id, audit.bulk, audit.cache) | ||
if err != nil { | ||
return err | ||
} | ||
zlog = zlog.With().Str(LogAccessAPIKeyID, agent.AccessAPIKeyID).Logger() | ||
ctx := zlog.WithContext(r.Context()) | ||
r = r.WithContext(ctx) | ||
|
||
return audit.unenroll(zlog, w, r, agent) | ||
} | ||
|
||
func (audit *AuditT) unenroll(zlog zerolog.Logger, w http.ResponseWriter, r *http.Request, agent *model.Agent) error { | ||
if agent.AuditUnenrolledReason != "" { | ||
return ErrAuditUnenrollReason | ||
} | ||
|
||
req, err := audit.validateUnenrollRequest(zlog, w, r) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
if err := audit.markUnenroll(r.Context(), zlog, req, agent); err != nil { | ||
return err | ||
} | ||
|
||
span, _ := apm.StartSpan(r.Context(), "response", "write") | ||
defer span.End() | ||
w.WriteHeader(http.StatusOK) | ||
return nil | ||
} | ||
|
||
func (audit *AuditT) validateUnenrollRequest(zlog zerolog.Logger, w http.ResponseWriter, r *http.Request) (*AuditUnenrollRequest, error) { | ||
span, _ := apm.StartSpan(r.Context(), "validateRequest", "validate") | ||
defer span.End() | ||
|
||
body := r.Body | ||
if audit.cfg.Limits.AuditUnenrollLimit.MaxBody > 0 { | ||
body = http.MaxBytesReader(w, body, audit.cfg.Limits.AuditUnenrollLimit.MaxBody) | ||
} | ||
readCounter := datacounter.NewReaderCounter(body) | ||
|
||
var req AuditUnenrollRequest | ||
dec := json.NewDecoder(readCounter) | ||
if err := dec.Decode(&req); err != nil { | ||
return nil, &BadRequestErr{msg: "unable to decode audit/unenroll request", nextErr: err} | ||
} | ||
|
||
switch req.Reason { | ||
case Uninstall, Orphaned, KeyRevoked: | ||
default: | ||
return nil, &BadRequestErr{msg: "audit/unenroll request invalid reason"} | ||
} | ||
|
||
cntAuditUnenroll.bodyIn.Add(readCounter.Count()) | ||
zlog.Trace().Msg("Audit unenroll request") | ||
return &req, nil | ||
} | ||
|
||
func (audit *AuditT) markUnenroll(ctx context.Context, zlog zerolog.Logger, req *AuditUnenrollRequest, agent *model.Agent) error { | ||
span, ctx := apm.StartSpan(ctx, "auditUnenroll", "process") | ||
defer span.End() | ||
|
||
now := time.Now().UTC().Format(time.RFC3339) | ||
doc := bulk.UpdateFields{ | ||
dl.FieldUnenrolledAt: now, | ||
dl.FieldUpdatedAt: now, | ||
dl.FieldAuditUnenrolledTime: req.Timestamp, | ||
dl.FieldAuditUnenrolledReason: req.Reason, | ||
} | ||
body, err := doc.Marshal() | ||
if err != nil { | ||
return fmt.Errorf("auditUnenroll marshal: %w", err) | ||
} | ||
|
||
if err := audit.bulk.Update(ctx, dl.FleetAgents, agent.Id, body, bulk.WithRefresh(), bulk.WithRetryOnConflict(3)); err != nil { | ||
return fmt.Errorf("auditUnenroll update: %w", err) | ||
} | ||
|
||
zlog.Info().Msg("audit unenroll successful") | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,136 @@ | ||
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
// or more contributor license agreements. Licensed under the Elastic License; | ||
// you may not use this file except in compliance with the Elastic License. | ||
|
||
package api | ||
|
||
import ( | ||
"context" | ||
"io" | ||
"net/http" | ||
"net/http/httptest" | ||
"strings" | ||
"testing" | ||
"time" | ||
|
||
"github.com/elastic/fleet-server/v7/internal/pkg/config" | ||
"github.com/elastic/fleet-server/v7/internal/pkg/dl" | ||
"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" | ||
"github.com/stretchr/testify/mock" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func Test_Audit_validateUnenrollRequst(t *testing.T) { | ||
tests := []struct { | ||
name string | ||
req *http.Request | ||
cfg *config.Server | ||
valid *AuditUnenrollRequest | ||
err error | ||
}{{ | ||
name: "ok", | ||
req: &http.Request{ | ||
Body: io.NopCloser(strings.NewReader(`{"reason":"uninstall", "timestamp": "2024-01-01T12:00:00.000Z"}`)), | ||
}, | ||
cfg: &config.Server{}, | ||
valid: &AuditUnenrollRequest{ | ||
Reason: Uninstall, | ||
Timestamp: time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC), | ||
}, | ||
err: nil, | ||
}, { | ||
name: "not json object", | ||
req: &http.Request{ | ||
Body: io.NopCloser(strings.NewReader(`{"invalidJson":}`)), | ||
}, | ||
cfg: &config.Server{}, | ||
valid: nil, | ||
err: &BadRequestErr{msg: "unable to decode audit/unenroll request"}, | ||
}, { | ||
name: "bad reason", | ||
req: &http.Request{ | ||
Body: io.NopCloser(strings.NewReader(`{"reason":"bad reason", "timestamp": "2024-01-01T12:00:00.000Z"}`)), | ||
}, | ||
cfg: &config.Server{}, | ||
valid: nil, | ||
err: &BadRequestErr{msg: "audit/unenroll request invalid reason"}, | ||
}, { | ||
name: "too large", | ||
req: &http.Request{ | ||
Body: io.NopCloser(strings.NewReader(`{"reason":"uninstalled", "timestamp": "2024-01-01T12:00:00.000Z"}`)), | ||
}, | ||
cfg: &config.Server{ | ||
Limits: config.ServerLimits{ | ||
AuditUnenrollLimit: config.Limit{ | ||
MaxBody: 10, | ||
}, | ||
}, | ||
}, | ||
valid: nil, | ||
err: &BadRequestErr{msg: "unable to decode audit/unenroll request"}, | ||
}} | ||
|
||
for _, tc := range tests { | ||
t.Run(tc.name, func(t *testing.T) { | ||
audit := AuditT{cfg: tc.cfg} | ||
w := httptest.NewRecorder() | ||
|
||
r, err := audit.validateUnenrollRequest(testlog.SetLogger(t), w, tc.req) | ||
if tc.err != nil { | ||
require.EqualError(t, err, tc.err.Error()) | ||
} else { | ||
require.NoError(t, err) | ||
} | ||
require.Equal(t, tc.valid, r) | ||
}) | ||
} | ||
} | ||
|
||
func Test_Audit_markUnenroll(t *testing.T) { | ||
agent := &model.Agent{ | ||
ESDocument: model.ESDocument{ | ||
Id: "test-id", | ||
}, | ||
} | ||
bulker := ftesting.NewMockBulk() | ||
bulker.On("Update", mock.Anything, dl.FleetAgents, agent.Id, mock.Anything, mock.Anything, mock.Anything).Return(nil) | ||
audit := AuditT{bulk: bulker} | ||
logger := testlog.SetLogger(t) | ||
err := audit.markUnenroll(context.Background(), logger, &AuditUnenrollRequest{Reason: Uninstall, Timestamp: time.Now().UTC()}, agent) | ||
require.NoError(t, err) | ||
bulker.AssertExpectations(t) | ||
} | ||
|
||
func Test_Audit_unenroll(t *testing.T) { | ||
t.Run("agent has audit_unenroll_reason", func(t *testing.T) { | ||
agent := &model.Agent{ | ||
AuditUnenrolledReason: string(Uninstall), | ||
} | ||
audit := &AuditT{} | ||
err := audit.unenroll(testlog.SetLogger(t), nil, nil, agent) | ||
require.EqualError(t, err, ErrAuditUnenrollReason.Error()) | ||
}) | ||
|
||
t.Run("ok", func(t *testing.T) { | ||
agent := &model.Agent{ | ||
ESDocument: model.ESDocument{ | ||
Id: "test-id", | ||
}, | ||
} | ||
bulker := ftesting.NewMockBulk() | ||
bulker.On("Update", mock.Anything, dl.FleetAgents, agent.Id, mock.Anything, mock.Anything, mock.Anything).Return(nil) | ||
|
||
audit := &AuditT{ | ||
bulk: bulker, | ||
cfg: &config.Server{}, | ||
} | ||
req := &http.Request{ | ||
Body: io.NopCloser(strings.NewReader(`{"reason": "uninstall", "timestamp": "2024-01-01T12:00:00.000Z"}`)), | ||
} | ||
err := audit.unenroll(testlog.SetLogger(t), httptest.NewRecorder(), req, agent) | ||
require.NoError(t, err) | ||
bulker.AssertExpectations(t) | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Seems this will return a 500 error back to the caller, is that the correct error in the case its a conflict? Should it instead be the same conflict error in the case the field is set? I don't know if we want the caller to error.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's detected much earlier on line 54 of
handleAudit.go
https://github.com/elastic/fleet-server/pull/3818/files/#diff-bca31366226def7a73d6e6b142a9e17bbb4c2375a8f0fa16c5c81d4e6a374f13R54-R56