From f64f608165ffa561e13d724eebad91e03cc4abfe Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Thu, 26 Nov 2026 11:17:08 +0000 Subject: [PATCH 1/4] deps(deploy-engine-client): update blueprint, blueprint-state and common to their latest releases Brings in blueprint v0.57.0, blueprint-state v0.13.1 and common v0.6.0, which the following commits need for the state housekeeping and audit record cleanup types. --- libs/deploy-engine-client/go.mod | 10 +++++----- libs/deploy-engine-client/go.sum | 24 ++++++++++++------------ 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/libs/deploy-engine-client/go.mod b/libs/deploy-engine-client/go.mod index a1aeab8e..49676842 100644 --- a/libs/deploy-engine-client/go.mod +++ b/libs/deploy-engine-client/go.mod @@ -1,12 +1,12 @@ module github.com/newstack-cloud/bluelink/libs/deploy-engine-client -go 1.25.0 +go 1.26.0 require ( github.com/gorilla/mux v1.8.1 - github.com/newstack-cloud/bluelink/libs/blueprint v0.54.0 - github.com/newstack-cloud/bluelink/libs/blueprint-state v0.9.1 - github.com/newstack-cloud/bluelink/libs/common v0.4.0 + github.com/newstack-cloud/bluelink/libs/blueprint v0.57.0 + github.com/newstack-cloud/bluelink/libs/blueprint-state v0.13.1 + github.com/newstack-cloud/bluelink/libs/common v0.6.0 github.com/r3labs/sse/v2 v2.10.0 github.com/stretchr/testify v1.12.1 go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 @@ -29,7 +29,7 @@ require ( go.uber.org/multierr v1.10.0 // indirect go.uber.org/zap v1.28.0 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect - golang.org/x/net v0.52.0 // indirect + golang.org/x/net v0.60.0 // indirect gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/libs/deploy-engine-client/go.sum b/libs/deploy-engine-client/go.sum index a5104c6a..2d39ac70 100644 --- a/libs/deploy-engine-client/go.sum +++ b/libs/deploy-engine-client/go.sum @@ -26,12 +26,12 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/matoous/go-nanoid/v2 v2.1.0 h1:P64+dmq21hhWdtvZfEAofnvJULaRR1Yib0+PnU669bE= github.com/matoous/go-nanoid/v2 v2.1.0/go.mod h1:KlbGNQ+FhrUNIHUxZdL63t7tl4LaPkZNpUULS8H4uVM= -github.com/newstack-cloud/bluelink/libs/blueprint v0.54.0 h1:atFcZB+S9g1pZJ+RUwppSv3PtBxFPUy/8hkak00IcyM= -github.com/newstack-cloud/bluelink/libs/blueprint v0.54.0/go.mod h1:IzAGdeIgsxVNhqa6fO0wmkD8xbTviEruMgHgXk33j2k= -github.com/newstack-cloud/bluelink/libs/blueprint-state v0.9.1 h1:WymyISfFNk9C+hO+gDuefOJOnWHaXecPeMHIkG3CxBg= -github.com/newstack-cloud/bluelink/libs/blueprint-state v0.9.1/go.mod h1:3V+FF4CaMMqwdrKv4geYnmzDfkbqG6oNK/BQFm4GDKc= -github.com/newstack-cloud/bluelink/libs/common v0.4.0 h1:E72YAjex+VydpaYJXaAwlqeII7jVugEKsfVjHFLaJJY= -github.com/newstack-cloud/bluelink/libs/common v0.4.0/go.mod h1:09jWAU7PMDJSW0zokebgDZCr59Gg4JpqgF0Yq6kQ8gY= +github.com/newstack-cloud/bluelink/libs/blueprint v0.57.0 h1:rR2uq9HFvBP9hoP2PehWPsjiYzQ6WaYmHCjAJ7TDeXw= +github.com/newstack-cloud/bluelink/libs/blueprint v0.57.0/go.mod h1:IzAGdeIgsxVNhqa6fO0wmkD8xbTviEruMgHgXk33j2k= +github.com/newstack-cloud/bluelink/libs/blueprint-state v0.13.1 h1:YQl/wRThtElL03HiqkiVbszT7VdNX424wcEZs+4Q7gs= +github.com/newstack-cloud/bluelink/libs/blueprint-state v0.13.1/go.mod h1:Wqd5tZicpwwVOqKEJj4/oyNhEyxvf/frFIWgMEfthOM= +github.com/newstack-cloud/bluelink/libs/common v0.6.0 h1:sITqsLAkYUbNmwuVuJ1/M8uzloZ4k56OcVPfgiwx0G4= +github.com/newstack-cloud/bluelink/libs/common v0.6.0/go.mod h1:a8xXIgLy0loEE/62oaiGyGxFH7z63xUefLnzZZRk8Gs= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -71,16 +71,16 @@ go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/net v0.0.0-20191116160921-f9c825593386/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0= -golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw= +golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= +golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= -golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8= -golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= gopkg.in/cenkalti/backoff.v1 v1.1.0 h1:Arh75ttbsvlpVA7WtVpH4u9h6Zl46xuptxqLxPiSo4Y= gopkg.in/cenkalti/backoff.v1 v1.1.0/go.mod h1:J6Vskwqd+OMVJl8C33mmtxTBs2gyzfv7UDAkHu8BrjI= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= From 0915339c4ec30d06014b86f9fc6c5316b3d02cc2 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Thu, 26 Nov 2026 14:11:11 +0000 Subject: [PATCH 2/4] feat(deploy-engine-client): add state housekeeping and audit record cleanup --- libs/deploy-engine-client/client.go | 46 ++++++++++++++ .../client_cleanup_audit_records_test.go | 63 +++++++++++++++++++ .../client_state_housekeeping_test.go | 63 +++++++++++++++++++ libs/deploy-engine-client/client_test.go | 10 +++ .../testutils/stub_deploy_engine_server.go | 60 +++++++++--------- 5 files changed, 212 insertions(+), 30 deletions(-) create mode 100644 libs/deploy-engine-client/client_cleanup_audit_records_test.go create mode 100644 libs/deploy-engine-client/client_state_housekeeping_test.go diff --git a/libs/deploy-engine-client/client.go b/libs/deploy-engine-client/client.go index 41a2de3a..5d12f5f6 100644 --- a/libs/deploy-engine-client/client.go +++ b/libs/deploy-engine-client/client.go @@ -993,6 +993,48 @@ func (c *Client) CleanupReconciliationResults( return resp.Data, nil } +// RunStateHousekeeping triggers the upkeep the state backend needs on its own storage, +// such as reclaiming storage that interrupted writes left behind. +// This is an asynchronous operation that returns immediately after triggering it. +// What housekeeping involves is up to the backend. A backend that needs none still +// starts an operation, which completes having deleted nothing. +// +// Poll the operation with GetCleanupOperation or WaitForCleanupCompletion using +// manage.CleanupTypeStateHousekeeping. +// +// This is the `POST {baseURL}/v1/state/housekeeping` API endpoint. +func (c *Client) RunStateHousekeeping( + ctx context.Context, +) (*manage.CleanupOperation, error) { + url := fmt.Sprintf("%s/v1/state/housekeeping", c.endpoint) + resp := &types.CleanupOperationResponse{} + err := c.startCleanupOperation(ctx, url, resp) + if err != nil { + return nil, err + } + return resp.Data, nil +} + +// CleanupAuditRecords triggers cleanup of old audit records. +// This is an asynchronous operation that returns immediately after triggering the cleanup. +// Audit records older than the configured retention period will be removed. +// +// Poll the operation with GetCleanupOperation or WaitForCleanupCompletion using +// manage.CleanupTypeAuditRecords. +// +// This is the `POST {baseURL}/v1/audit/records/cleanup` API endpoint. +func (c *Client) CleanupAuditRecords( + ctx context.Context, +) (*manage.CleanupOperation, error) { + url := fmt.Sprintf("%s/v1/audit/records/cleanup", c.endpoint) + resp := &types.CleanupOperationResponse{} + err := c.startCleanupOperation(ctx, url, resp) + if err != nil { + return nil, err + } + return resp.Data, nil +} + // GetCleanupOperation retrieves the status of a cleanup operation by ID. // This is used to poll the status of an asynchronous cleanup operation. func (c *Client) GetCleanupOperation( @@ -1023,6 +1065,10 @@ func (c *Client) cleanupStatusURL(cleanupType manage.CleanupType, operationID st return fmt.Sprintf("%s/v1/deployments/changes/cleanup/%s", c.endpoint, operationID) case manage.CleanupTypeReconciliationResults: return fmt.Sprintf("%s/v1/deployments/reconciliation-results/cleanup/%s", c.endpoint, operationID) + case manage.CleanupTypeAuditRecords: + return fmt.Sprintf("%s/v1/audit/records/cleanup/%s", c.endpoint, operationID) + case manage.CleanupTypeStateHousekeeping: + return fmt.Sprintf("%s/v1/state/housekeeping/%s", c.endpoint, operationID) default: return "" } diff --git a/libs/deploy-engine-client/client_cleanup_audit_records_test.go b/libs/deploy-engine-client/client_cleanup_audit_records_test.go new file mode 100644 index 00000000..cb8d39fc --- /dev/null +++ b/libs/deploy-engine-client/client_cleanup_audit_records_test.go @@ -0,0 +1,63 @@ +// Tests for the CleanupAuditRecords method in the DeployEngine client. +package deployengine + +import ( + "context" + "net/http" + "time" + + "github.com/newstack-cloud/bluelink/libs/blueprint-state/manage" + "github.com/newstack-cloud/bluelink/libs/deploy-engine-client/errors" +) + +func (s *ClientSuite) Test_cleanup_audit_records() { + client := s.createAPIKeyClient(testAPIKey) + + operation, err := client.CleanupAuditRecords(context.Background()) + s.Require().NoError(err) + + s.Assert().Equal("test-cleanup-operation-id", operation.ID) + s.Assert().Equal(manage.CleanupTypeAuditRecords, operation.CleanupType) + s.Assert().Equal(manage.CleanupOperationStatusRunning, operation.Status) +} + +func (s *ClientSuite) Test_cleanup_audit_records_fails_for_unauthorised_client() { + client := s.createAPIKeyClient("invalid-api-key") + + _, err := client.CleanupAuditRecords(context.Background()) + s.Require().Error(err) + + clientErr, isClientErr := err.(*errors.ClientError) + s.Require().True(isClientErr) + s.Assert().Equal(http.StatusUnauthorized, clientErr.StatusCode) +} + +func (s *ClientSuite) Test_get_audit_records_cleanup_operation() { + client := s.createAPIKeyClient(testAPIKey) + + operation, err := client.GetCleanupOperation( + context.Background(), + manage.CleanupTypeAuditRecords, + "test-operation-id", + ) + s.Require().NoError(err) + + s.Assert().Equal("test-operation-id", operation.ID) + s.Assert().Equal(manage.CleanupTypeAuditRecords, operation.CleanupType) + s.Assert().Equal(int64(42), operation.ItemsDeleted) +} + +func (s *ClientSuite) Test_wait_for_audit_records_cleanup_completion() { + client := s.createAPIKeyClient(testAPIKey) + + operation, err := client.WaitForCleanupCompletion( + context.Background(), + manage.CleanupTypeAuditRecords, + "test-operation-id", + time.Millisecond, + ) + s.Require().NoError(err) + + s.Assert().Equal(manage.CleanupTypeAuditRecords, operation.CleanupType) + s.Assert().Equal(manage.CleanupOperationStatusCompleted, operation.Status) +} diff --git a/libs/deploy-engine-client/client_state_housekeeping_test.go b/libs/deploy-engine-client/client_state_housekeeping_test.go new file mode 100644 index 00000000..f3eec14a --- /dev/null +++ b/libs/deploy-engine-client/client_state_housekeeping_test.go @@ -0,0 +1,63 @@ +// Tests for the RunStateHousekeeping method in the DeployEngine client. +package deployengine + +import ( + "context" + "net/http" + "time" + + "github.com/newstack-cloud/bluelink/libs/blueprint-state/manage" + "github.com/newstack-cloud/bluelink/libs/deploy-engine-client/errors" +) + +func (s *ClientSuite) Test_run_state_housekeeping() { + client := s.createAPIKeyClient(testAPIKey) + + operation, err := client.RunStateHousekeeping(context.Background()) + s.Require().NoError(err) + + s.Assert().Equal("test-cleanup-operation-id", operation.ID) + s.Assert().Equal(manage.CleanupTypeStateHousekeeping, operation.CleanupType) + s.Assert().Equal(manage.CleanupOperationStatusRunning, operation.Status) +} + +func (s *ClientSuite) Test_run_state_housekeeping_fails_for_unauthorised_client() { + client := s.createAPIKeyClient("invalid-api-key") + + _, err := client.RunStateHousekeeping(context.Background()) + s.Require().Error(err) + + clientErr, isClientErr := err.(*errors.ClientError) + s.Require().True(isClientErr) + s.Assert().Equal(http.StatusUnauthorized, clientErr.StatusCode) +} + +func (s *ClientSuite) Test_get_state_housekeeping_operation() { + client := s.createAPIKeyClient(testAPIKey) + + operation, err := client.GetCleanupOperation( + context.Background(), + manage.CleanupTypeStateHousekeeping, + "test-operation-id", + ) + s.Require().NoError(err) + + s.Assert().Equal("test-operation-id", operation.ID) + s.Assert().Equal(manage.CleanupTypeStateHousekeeping, operation.CleanupType) + s.Assert().Equal(manage.CleanupOperationStatusCompleted, operation.Status) +} + +func (s *ClientSuite) Test_wait_for_state_housekeeping_completion() { + client := s.createAPIKeyClient(testAPIKey) + + operation, err := client.WaitForCleanupCompletion( + context.Background(), + manage.CleanupTypeStateHousekeeping, + "test-operation-id", + time.Millisecond, + ) + s.Require().NoError(err) + + s.Assert().Equal(manage.CleanupTypeStateHousekeeping, operation.CleanupType) + s.Assert().Equal(manage.CleanupOperationStatusCompleted, operation.Status) +} diff --git a/libs/deploy-engine-client/client_test.go b/libs/deploy-engine-client/client_test.go index bddb493f..97d133f6 100644 --- a/libs/deploy-engine-client/client_test.go +++ b/libs/deploy-engine-client/client_test.go @@ -231,6 +231,16 @@ func (s *ClientSuite) Test_fails_to_setup_client_due_to_failing_oauth_provider_t ) } +func (s *ClientSuite) createAPIKeyClient(apiKey string) *Client { + client, err := NewClient( + WithClientEndpoint(s.deployEngineServer.URL), + WithClientAuthMethod(AuthMethodAPIKey), + WithClientAPIKey(apiKey), + ) + s.Require().NoError(err) + return client +} + func (s *ClientSuite) prepareTestSocketDir() { workingDir, err := os.Getwd() s.Require().NoError(err) diff --git a/libs/deploy-engine-client/internal/testutils/stub_deploy_engine_server.go b/libs/deploy-engine-client/internal/testutils/stub_deploy_engine_server.go index 0df8135d..98f1c1ca 100644 --- a/libs/deploy-engine-client/internal/testutils/stub_deploy_engine_server.go +++ b/libs/deploy-engine-client/internal/testutils/stub_deploy_engine_server.go @@ -84,7 +84,7 @@ func CreateDeployEngineServer( router.HandleFunc( "/v1/validations/cleanup", - ctrl.cleanupBlueprintValidationsHandler, + ctrl.cleanupHandler(manage.CleanupTypeValidations), ).Methods("POST") router.HandleFunc( @@ -109,7 +109,7 @@ func CreateDeployEngineServer( router.HandleFunc( "/v1/deployments/changes/cleanup", - ctrl.cleanupChangesetsHandler, + ctrl.cleanupHandler(manage.CleanupTypeChangesets), ).Methods("POST") router.HandleFunc( @@ -149,7 +149,7 @@ func CreateDeployEngineServer( router.HandleFunc( "/v1/events/cleanup", - ctrl.cleanupEventsHandler, + ctrl.cleanupHandler(manage.CleanupTypeEvents), ).Methods("POST") router.HandleFunc( @@ -169,7 +169,7 @@ func CreateDeployEngineServer( router.HandleFunc( "/v1/deployments/reconciliation-results/cleanup", - ctrl.cleanupReconciliationResultsHandler, + ctrl.cleanupHandler(manage.CleanupTypeReconciliationResults), ).Methods("POST") router.HandleFunc( @@ -177,6 +177,26 @@ func CreateDeployEngineServer( ctrl.getCleanupStatusHandler(manage.CleanupTypeReconciliationResults), ).Methods("GET") + router.HandleFunc( + "/v1/audit/records/cleanup", + ctrl.cleanupHandler(manage.CleanupTypeAuditRecords), + ).Methods("POST") + + router.HandleFunc( + "/v1/audit/records/cleanup/{id}", + ctrl.getCleanupStatusHandler(manage.CleanupTypeAuditRecords), + ).Methods("GET") + + router.HandleFunc( + "/v1/state/housekeeping", + ctrl.cleanupHandler(manage.CleanupTypeStateHousekeeping), + ).Methods("POST") + + router.HandleFunc( + "/v1/state/housekeeping/{id}", + ctrl.getCleanupStatusHandler(manage.CleanupTypeStateHousekeeping), + ).Methods("GET") + if serverConfig.UseUnixDomainSocket { return NewUnixDomainSocketServer( serverConfig.UnixDomainSocketPath, @@ -291,13 +311,6 @@ func (c *stubDeployEngineController) streamBlueprintValidationEventsHandler( streamEvents(w, c.stubValidationEvents, failStream) } -func (c *stubDeployEngineController) cleanupBlueprintValidationsHandler( - w http.ResponseWriter, - r *http.Request, -) { - c.writeCleanupOperationResponse(w, manage.CleanupTypeValidations) -} - func (c *stubDeployEngineController) createChangesetHandler( w http.ResponseWriter, r *http.Request, @@ -585,25 +598,12 @@ func (c *stubDeployEngineController) handlePostErrorTriggers( return false } -func (c *stubDeployEngineController) cleanupChangesetsHandler( - w http.ResponseWriter, - r *http.Request, -) { - c.writeCleanupOperationResponse(w, manage.CleanupTypeChangesets) -} - -func (c *stubDeployEngineController) cleanupEventsHandler( - w http.ResponseWriter, - r *http.Request, -) { - c.writeCleanupOperationResponse(w, manage.CleanupTypeEvents) -} - -func (c *stubDeployEngineController) cleanupReconciliationResultsHandler( - w http.ResponseWriter, - r *http.Request, -) { - c.writeCleanupOperationResponse(w, manage.CleanupTypeReconciliationResults) +func (c *stubDeployEngineController) cleanupHandler( + cleanupType manage.CleanupType, +) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + c.writeCleanupOperationResponse(w, cleanupType) + } } func (c *stubDeployEngineController) writeCleanupOperationResponse( From a893f5546f2da349864d2cad6ac14173dbf6daf7 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Sun, 29 Nov 2026 12:56:22 +0000 Subject: [PATCH 3/4] feat(deploy-engine-client): add audit trail queries --- libs/deploy-engine-client/client.go | 96 +++++++ .../client_audit_records_test.go | 237 ++++++++++++++++++ libs/deploy-engine-client/client_test.go | 21 ++ .../testutils/stub_deploy_engine_server.go | 140 ++++++++++- .../deploy-engine-client/types/audit_types.go | 46 ++++ 5 files changed, 527 insertions(+), 13 deletions(-) create mode 100644 libs/deploy-engine-client/client_audit_records_test.go create mode 100644 libs/deploy-engine-client/types/audit_types.go diff --git a/libs/deploy-engine-client/client.go b/libs/deploy-engine-client/client.go index 5d12f5f6..0bf85ad9 100644 --- a/libs/deploy-engine-client/client.go +++ b/libs/deploy-engine-client/client.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "net/http" + "net/url" "strconv" "time" @@ -1035,6 +1036,101 @@ func (c *Client) CleanupAuditRecords( return resp.Data, nil } +// QueryAuditRecords reads a page of the deploy engine's audit trail, oldest first, +// narrowed by the query's filters. A nil query reads the first page of the whole trail +// with the engine's default limit. +// +// A page is the complete answer only when its HasMore is false. To read on, pass the +// page's NextCursor as the After field of the next query, keeping the other filters. +// +// A filter the engine rejects, such as an unknown outcome, a negative bound or a limit +// above 1000, returns a ClientError that errors.IsValidationError reports. Negative +// values are sent rather than dropped, so a bad bound is never read as no bound. +// +// This is the `GET {baseURL}/v1/audit/records` API endpoint. +func (c *Client) QueryAuditRecords( + ctx context.Context, + query *types.AuditRecordQuery, +) (*types.AuditRecordsPage, error) { + recordsURL := fmt.Sprintf("%s/v1/audit/records", c.endpoint) + page := &types.AuditRecordsPage{} + err := c.getResourceWithQueryParams( + ctx, + recordsURL, + buildAuditRecordQueryParams(query), + page, + ) + if err != nil { + return nil, err + } + if page.HasMore && page.NextCursor == nil { + // Without a cursor the rest of the trail cannot be read, and returning the page + // would leave a caller nothing to tell it from a complete answer. + return nil, createDeserialiseError( + "audit records page reports more records but has no cursor to read them", + ) + } + return page, nil +} + +func buildAuditRecordQueryParams(query *types.AuditRecordQuery) map[string]string { + queryParams := map[string]string{} + if query == nil { + return queryParams + } + if query.From != 0 { + queryParams["from"] = strconv.FormatInt(query.From, 10) + } + if query.To != 0 { + queryParams["to"] = strconv.FormatInt(query.To, 10) + } + if query.After != nil { + queryParams["afterTimestamp"] = strconv.FormatInt(query.After.AfterTimestamp, 10) + queryParams["afterId"] = query.After.AfterID + } + if query.Action != "" { + queryParams["action"] = query.Action + } + if query.PrincipalSubject != "" { + queryParams["principalSubject"] = query.PrincipalSubject + } + if query.Outcome != "" { + queryParams["outcome"] = query.Outcome + } + if query.Limit != 0 { + queryParams["limit"] = strconv.Itoa(query.Limit) + } + return queryParams +} + +// GetAuditRecord retrieves a single audit record by ID. +// An unknown ID returns a ClientError that errors.IsNotFoundError reports. +// +// This is the `GET {baseURL}/v1/audit/records/{id}` API endpoint. +func (c *Client) GetAuditRecord( + ctx context.Context, + recordID string, +) (*manage.AuditRecord, error) { + recordURL := fmt.Sprintf( + "%s/v1/audit/records/%s", + c.endpoint, + url.PathEscape(recordID), + ) + record := &manage.AuditRecord{} + err := c.getResource(ctx, recordURL, record) + if err != nil { + return nil, err + } + if record.ID != recordID { + // An ID such as "." is cleaned out of the path by the engine's router, which + // redirects the request to another endpoint that also answers 200. + return nil, createDeserialiseError( + fmt.Sprintf("response does not hold the requested audit record %q", recordID), + ) + } + return record, nil +} + // GetCleanupOperation retrieves the status of a cleanup operation by ID. // This is used to poll the status of an asynchronous cleanup operation. func (c *Client) GetCleanupOperation( diff --git a/libs/deploy-engine-client/client_audit_records_test.go b/libs/deploy-engine-client/client_audit_records_test.go new file mode 100644 index 00000000..b62d64f0 --- /dev/null +++ b/libs/deploy-engine-client/client_audit_records_test.go @@ -0,0 +1,237 @@ +// Tests for the QueryAuditRecords and GetAuditRecord methods in the DeployEngine client. +package deployengine + +import ( + "context" + "net/http" + "net/url" + + "github.com/newstack-cloud/bluelink/libs/blueprint-state/manage" + "github.com/newstack-cloud/bluelink/libs/deploy-engine-client/errors" + "github.com/newstack-cloud/bluelink/libs/deploy-engine-client/internal/testutils" + "github.com/newstack-cloud/bluelink/libs/deploy-engine-client/types" +) + +func (s *ClientSuite) Test_query_audit_records() { + client := s.createAPIKeyClient(testAPIKey) + + page, err := client.QueryAuditRecords(context.Background(), nil) + s.Require().NoError(err) + + s.Require().Len(page.Records, 2) + s.Assert().Equal(testutils.StubAuditRecordID, page.Records[0].ID) + s.Assert().Equal("instance.destroy", page.Records[0].Action) + s.Assert().Equal(manage.OutcomeSuccess, page.Records[0].Outcome) + s.Assert().Equal(testutils.StubSecondAuditRecordID, page.Records[1].ID) + s.Assert().False(page.HasMore) + s.Assert().Nil(page.NextCursor) + s.Assert().Empty(s.lastAuditQuery) +} + +func (s *ClientSuite) Test_query_audit_records_sends_every_filter() { + client := s.createAPIKeyClient(testAPIKey) + + _, err := client.QueryAuditRecords(context.Background(), &types.AuditRecordQuery{ + From: 1700000000, + To: 1700003600, + After: &types.AuditRecordCursor{ + AfterTimestamp: 1700000100, + AfterID: "test-after-id", + }, + Action: "instance.destroy", + PrincipalSubject: "test-principal", + Outcome: manage.OutcomeFailure, + Limit: 50, + }) + s.Require().NoError(err) + + s.Assert().Equal(url.Values{ + "from": {"1700000000"}, + "to": {"1700003600"}, + "afterTimestamp": {"1700000100"}, + "afterId": {"test-after-id"}, + "action": {"instance.destroy"}, + "principalSubject": {"test-principal"}, + "outcome": {"failure"}, + "limit": {"50"}, + }, s.lastAuditQuery) +} + +func (s *ClientSuite) Test_query_audit_records_leaves_unset_filters_out() { + client := s.createAPIKeyClient(testAPIKey) + + _, err := client.QueryAuditRecords(context.Background(), &types.AuditRecordQuery{ + Action: "instance.destroy", + }) + s.Require().NoError(err) + + s.Assert().Equal(url.Values{"action": {"instance.destroy"}}, s.lastAuditQuery) +} + +func (s *ClientSuite) Test_query_audit_records_pages_with_the_next_cursor() { + client := s.createAPIKeyClient(testAPIKey) + + page, err := client.QueryAuditRecords(context.Background(), &types.AuditRecordQuery{ + Limit: 1, + }) + s.Require().NoError(err) + + s.Require().Len(page.Records, 1) + s.Assert().True(page.HasMore) + s.Require().NotNil(page.NextCursor) + s.Assert().Equal(testutils.StubAuditRecordID, page.NextCursor.AfterID) + s.Assert().Equal(page.Records[0].Timestamp, page.NextCursor.AfterTimestamp) + + _, err = client.QueryAuditRecords(context.Background(), &types.AuditRecordQuery{ + After: page.NextCursor, + Limit: 1, + }) + s.Require().NoError(err) + + s.Assert().Equal(testutils.StubAuditRecordID, s.lastAuditQuery.Get("afterId")) +} + +func (s *ClientSuite) Test_query_audit_records_reports_a_rejected_filter() { + client := s.createAPIKeyClient(testAPIKey) + + _, err := client.QueryAuditRecords(context.Background(), &types.AuditRecordQuery{ + Outcome: "unknown", + }) + s.Require().Error(err) + + clientErr, isValidationErr := errors.IsValidationError(err) + s.Require().True(isValidationErr) + s.Assert().Equal(http.StatusBadRequest, clientErr.StatusCode) + s.Assert().Contains(clientErr.Message, "outcome") +} + +func (s *ClientSuite) Test_query_audit_records_fails_for_unauthorised_client() { + client := s.createAPIKeyClient("invalid-api-key") + + _, err := client.QueryAuditRecords(context.Background(), nil) + s.Require().Error(err) + + clientErr, isClientErr := err.(*errors.ClientError) + s.Require().True(isClientErr) + s.Assert().Equal(http.StatusUnauthorized, clientErr.StatusCode) +} + +func (s *ClientSuite) Test_get_audit_record() { + client := s.createAPIKeyClient(testAPIKey) + + record, err := client.GetAuditRecord(context.Background(), testutils.StubAuditRecordID) + s.Require().NoError(err) + + s.Assert().Equal(testutils.StubAuditRecordID, record.ID) + s.Assert().Equal("instance.destroy", record.Action) + s.Assert().Equal("test-principal", record.PrincipalSubject) +} + +func (s *ClientSuite) Test_get_audit_record_reports_an_unknown_id_as_not_found() { + client := s.createAPIKeyClient(testAPIKey) + + _, err := client.GetAuditRecord(context.Background(), "missing-record-id") + s.Require().Error(err) + + clientErr, isNotFound := errors.IsNotFoundError(err) + s.Require().True(isNotFound) + s.Assert().Contains(clientErr.Message, "missing-record-id") +} + +func (s *ClientSuite) Test_get_audit_record_escapes_the_id() { + client := s.createAPIKeyClient(testAPIKey) + + // Unescaped, everything from the "?" would be sent as a query string, and the + // request would fetch the stub's record instead of looking up this ID. + _, err := client.GetAuditRecord( + context.Background(), + testutils.StubAuditRecordID+"?limit=1", + ) + s.Require().Error(err) + + _, isNotFound := errors.IsNotFoundError(err) + s.Assert().True(isNotFound) +} + +func (s *ClientSuite) Test_get_audit_record_fails_for_unauthorised_client() { + client := s.createAPIKeyClient("invalid-api-key") + + _, err := client.GetAuditRecord(context.Background(), testutils.StubAuditRecordID) + s.Require().Error(err) + + clientErr, isClientErr := err.(*errors.ClientError) + s.Require().True(isClientErr) + s.Assert().Equal(http.StatusUnauthorized, clientErr.StatusCode) +} + +func (s *ClientSuite) Test_query_audit_records_sends_negative_values_for_the_engine_to_reject() { + client := s.createAPIKeyClient(testAPIKey) + + _, err := client.QueryAuditRecords(context.Background(), &types.AuditRecordQuery{ + From: -1, + To: -1, + Limit: -5, + }) + s.Require().NoError(err) + + s.Assert().Equal(url.Values{ + "from": {"-1"}, + "to": {"-1"}, + "limit": {"-5"}, + }, s.lastAuditQuery) +} + +func (s *ClientSuite) Test_query_audit_records_fails_for_a_page_with_more_records_and_no_cursor() { + client := s.createAPIKeyClient(testAPIKey) + + _, err := client.QueryAuditRecords(context.Background(), &types.AuditRecordQuery{ + Action: testutils.StubMissingCursorAction, + }) + s.Require().Error(err) + + _, isDeserialiseErr := err.(*errors.DeserialiseError) + s.Assert().True(isDeserialiseErr) +} + +func (s *ClientSuite) Test_get_audit_record_fails_when_the_response_holds_another_record() { + client := s.createAPIKeyClient(testAPIKey) + + // The router cleans "." out of the path and redirects the request to the query + // endpoint, which answers 200 with a page rather than a record. + _, err := client.GetAuditRecord(context.Background(), ".") + s.Require().Error(err) + + _, isDeserialiseErr := err.(*errors.DeserialiseError) + s.Assert().True(isDeserialiseErr) +} + +func (s *ClientSuite) Test_get_audit_record_fails_due_to_invalid_json_response() { + client := s.createNoRetryAPIKeyClient() + + _, err := client.GetAuditRecord(context.Background(), deserialiseErrorTriggerID) + s.Require().Error(err) + + _, isDeserialiseErr := err.(*errors.DeserialiseError) + s.Assert().True(isDeserialiseErr) +} + +func (s *ClientSuite) Test_get_audit_record_fails_due_to_internal_server_error() { + client := s.createNoRetryAPIKeyClient() + + _, err := client.GetAuditRecord(context.Background(), internalServerErrorTriggerID) + s.Require().Error(err) + + clientErr, isClientErr := err.(*errors.ClientError) + s.Require().True(isClientErr) + s.Assert().Equal(http.StatusInternalServerError, clientErr.StatusCode) +} + +func (s *ClientSuite) Test_get_audit_record_fails_due_to_network_error() { + client := s.createNoRetryAPIKeyClient() + + _, err := client.GetAuditRecord(context.Background(), networkErrorTriggerID) + s.Require().Error(err) + + _, isRequestErr := err.(*errors.RequestError) + s.Assert().True(isRequestErr) +} diff --git a/libs/deploy-engine-client/client_test.go b/libs/deploy-engine-client/client_test.go index 97d133f6..6d54a525 100644 --- a/libs/deploy-engine-client/client_test.go +++ b/libs/deploy-engine-client/client_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "net/http/httptest" + "net/url" "os" "path" "testing" @@ -58,6 +59,7 @@ type ClientSuite struct { stubChangeStagingEvents []*manage.Event stubDriftDetectedEvents []*manage.Event stubDeploymentEvents []*manage.Event + lastAuditQuery url.Values suite.Suite } @@ -99,6 +101,7 @@ func (s *ClientSuite) SetupSuite() { DeserialiseErrorTriggerID: deserialiseErrorTriggerID, FailingStreamTriggerID: failingStreamTriggerID, DriftDetectedChangesetID: driftDetectedChangesetID, + AuditQueryRecorder: s.recordAuditQuery, }, s.stubValidationEvents, s.stubChangeStagingEvents, @@ -124,6 +127,7 @@ func (s *ClientSuite) SetupSuite() { DeserialiseErrorTriggerID: deserialiseErrorTriggerID, FailingStreamTriggerID: failingStreamTriggerID, DriftDetectedChangesetID: driftDetectedChangesetID, + AuditQueryRecorder: s.recordAuditQuery, UseUnixDomainSocket: true, UnixDomainSocketPath: s.testSocketPath, }, @@ -231,6 +235,10 @@ func (s *ClientSuite) Test_fails_to_setup_client_due_to_failing_oauth_provider_t ) } +func (s *ClientSuite) recordAuditQuery(query url.Values) { + s.lastAuditQuery = query +} + func (s *ClientSuite) createAPIKeyClient(apiKey string) *Client { client, err := NewClient( WithClientEndpoint(s.deployEngineServer.URL), @@ -241,6 +249,19 @@ func (s *ClientSuite) createAPIKeyClient(apiKey string) *Client { return client } +// Retries are turned off so an error the stub server triggers reaches the test +// on the first attempt. +func (s *ClientSuite) createNoRetryAPIKeyClient() *Client { + client, err := NewClient( + WithClientEndpoint(s.deployEngineServer.URL), + WithClientAuthMethod(AuthMethodAPIKey), + WithClientAPIKey(testAPIKey), + WithClientHTTPRoundTripper(testutils.CreateDefaultTransport), + ) + s.Require().NoError(err) + return client +} + func (s *ClientSuite) prepareTestSocketDir() { workingDir, err := os.Getwd() s.Require().NoError(err) diff --git a/libs/deploy-engine-client/internal/testutils/stub_deploy_engine_server.go b/libs/deploy-engine-client/internal/testutils/stub_deploy_engine_server.go index 98f1c1ca..21505ba2 100644 --- a/libs/deploy-engine-client/internal/testutils/stub_deploy_engine_server.go +++ b/libs/deploy-engine-client/internal/testutils/stub_deploy_engine_server.go @@ -9,6 +9,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "net/url" "slices" "strings" "time" @@ -46,6 +47,9 @@ type TestServerConfig struct { DriftDetectedChangesetID string UseUnixDomainSocket bool UnixDomainSocketPath string + // Called with the query parameters of each audit trail query the server receives, + // so tests can check how a client encoded its filters. + AuditQueryRecorder func(query url.Values) } func CreateDeployEngineServer( @@ -187,6 +191,16 @@ func CreateDeployEngineServer( ctrl.getCleanupStatusHandler(manage.CleanupTypeAuditRecords), ).Methods("GET") + router.HandleFunc( + "/v1/audit/records", + ctrl.queryAuditRecordsHandler, + ).Methods("GET") + + router.HandleFunc( + "/v1/audit/records/{id}", + ctrl.getAuditRecordHandler, + ).Methods("GET") + router.HandleFunc( "/v1/state/housekeeping", ctrl.cleanupHandler(manage.CleanupTypeStateHousekeeping), @@ -782,22 +796,11 @@ func writeUnprocessableEntityError(w http.ResponseWriter) { }, }, } - bodyBytes, _ := json.Marshal(response) - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusUnprocessableEntity) - w.Write(bodyBytes) + writeJSON(w, http.StatusUnprocessableEntity, response) } func writeInternalServerError(w http.ResponseWriter) { - response := errors.Response{ - Message: "an unexpected error occurred", - } - bodyBytes, _ := json.Marshal(response) - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusInternalServerError) - w.Write(bodyBytes) + writeJSONError(w, http.StatusInternalServerError, "an unexpected error occurred") } // Decodes a JSON request body into the provided payload @@ -946,3 +949,114 @@ func NewInstanceState(id string, name string, status core.InstanceStatus) *state ChildBlueprints: map[string]*state.InstanceState{}, } } + +const ( + // StubAuditRecordID is the ID of the first audit record the stub server holds, + // the only one it serves by ID. + StubAuditRecordID = "test-audit-record-id-1" + // StubSecondAuditRecordID is the ID of the second audit record the stub server holds. + StubSecondAuditRecordID = "test-audit-record-id-2" + // StubMissingCursorAction is an action filter that makes the stub server answer a + // query with a page that reports more records but carries no cursor. + StubMissingCursorAction = "test.missing-cursor" +) + +// The stub's trail holds two records. A query for a limit of 1 gets the first with a +// cursor to the second, so a client's paging can be exercised. +func (c *stubDeployEngineController) queryAuditRecordsHandler( + w http.ResponseWriter, + r *http.Request, +) { + params := r.URL.Query() + if c.serverConfig.AuditQueryRecorder != nil { + c.serverConfig.AuditQueryRecorder(params) + } + + outcome := params.Get("outcome") + if outcome != "" && outcome != manage.OutcomeSuccess && outcome != manage.OutcomeFailure { + writeJSONError( + w, + http.StatusBadRequest, + "the \"outcome\" query parameter must be \"success\" or \"failure\"", + ) + return + } + + records := c.stubAuditRecords() + response := map[string]any{"records": records, "hasMore": false} + if params.Get("action") == StubMissingCursorAction { + response["hasMore"] = true + } + if params.Get("limit") == "1" { + response["records"] = records[:1] + response["hasMore"] = true + response["nextCursor"] = map[string]any{ + "afterTimestamp": records[0].Timestamp, + "afterId": records[0].ID, + } + } + + writeJSON(w, http.StatusOK, response) +} + +func (c *stubDeployEngineController) getAuditRecordHandler( + w http.ResponseWriter, + r *http.Request, +) { + id := mux.Vars(r)["id"] + exitEarly := c.handleIDErrorTriggers(w, id, http.StatusOK) + if exitEarly { + return + } + + if id != StubAuditRecordID { + writeJSONError( + w, + http.StatusNotFound, + fmt.Sprintf("audit record with ID %s not found", id), + ) + return + } + + writeJSON(w, http.StatusOK, c.stubAuditRecords()[0]) +} + +func (c *stubDeployEngineController) stubAuditRecords() []*manage.AuditRecord { + timestamp := c.clock.Now().Unix() + return []*manage.AuditRecord{ + { + ID: StubAuditRecordID, + Timestamp: timestamp, + Action: "instance.destroy", + Target: "test-instance-id", + Outcome: manage.OutcomeSuccess, + StatusCode: http.StatusAccepted, + Method: http.MethodPost, + Path: "/v1/deployments/instances/test-instance-id/destroy", + PrincipalMethod: "apiKey", + PrincipalSubject: "test-principal", + }, + { + ID: StubSecondAuditRecordID, + Timestamp: timestamp, + Action: "instance.create", + Outcome: manage.OutcomeFailure, + StatusCode: http.StatusConflict, + Method: http.MethodPost, + Path: "/v1/deployments/instances", + PrincipalMethod: "apiKey", + PrincipalSubject: "test-principal", + }, + } +} + +func writeJSON(w http.ResponseWriter, statusCode int, body any) { + bodyBytes, _ := json.Marshal(body) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(statusCode) + w.Write(bodyBytes) +} + +func writeJSONError(w http.ResponseWriter, statusCode int, message string) { + writeJSON(w, statusCode, errors.Response{Message: message}) +} diff --git a/libs/deploy-engine-client/types/audit_types.go b/libs/deploy-engine-client/types/audit_types.go new file mode 100644 index 00000000..ed17922d --- /dev/null +++ b/libs/deploy-engine-client/types/audit_types.go @@ -0,0 +1,46 @@ +package types + +import "github.com/newstack-cloud/bluelink/libs/blueprint-state/manage" + +// AuditRecordQuery narrows a read of the deploy engine's audit trail. +// A zero-valued field leaves that filter out of the query. Any other value is sent +// as given, so the engine rejects a negative bound or limit rather than ignoring it. +type AuditRecordQuery struct { + // From bounds the query to records at or after this unix timestamp in seconds. + // Inclusive. + From int64 + // To bounds the query to records before this unix timestamp in seconds. + // Exclusive. + To int64 + // After resumes the listing immediately after a record already read. + // Pass the NextCursor of the previous page. The engine ignores a cursor whose + // AfterTimestamp is zero and starts the listing again at From. + After *AuditRecordCursor + // Action restricts the query to a single action name, such as "instance.destroy". + Action string + // PrincipalSubject restricts the query to the actions of one principal. + PrincipalSubject string + // Outcome restricts the query to manage.OutcomeSuccess or manage.OutcomeFailure. + Outcome string + // Limit caps the number of records returned. Zero applies the engine's default + // (manage.DefaultAuditQueryLimit). The engine rejects a limit above 1000. + Limit int +} + +// AuditRecordCursor resumes an audit trail listing after a record. +type AuditRecordCursor struct { + AfterTimestamp int64 `json:"afterTimestamp"` + AfterID string `json:"afterId"` +} + +// AuditRecordsPage holds a page of the audit trail. +type AuditRecordsPage struct { + // Records are the matching records, oldest first. + Records []*manage.AuditRecord `json:"records"` + // HasMore says whether the trail holds further records matching the query + // beyond this page. A page is the whole answer only when this is false. + HasMore bool `json:"hasMore"` + // NextCursor resumes the listing immediately after this page, + // and is nil when nothing follows it. + NextCursor *AuditRecordCursor `json:"nextCursor,omitempty"` +} From c75e74fde1b3498def398e1470296d56f764b5c2 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 30 Nov 2026 08:52:48 +0000 Subject: [PATCH 4/4] feat(deploy-engine-client): report the instances behind name and change set conflicts --- .../client_instance_conflicts_test.go | 126 ++++++++++++++++++ libs/deploy-engine-client/error_helpers.go | 2 + libs/deploy-engine-client/errors/errors.go | 46 +++++++ .../testutils/stub_deploy_engine_server.go | 100 ++++++++++++++ 4 files changed, 274 insertions(+) create mode 100644 libs/deploy-engine-client/client_instance_conflicts_test.go diff --git a/libs/deploy-engine-client/client_instance_conflicts_test.go b/libs/deploy-engine-client/client_instance_conflicts_test.go new file mode 100644 index 00000000..18178c7e --- /dev/null +++ b/libs/deploy-engine-client/client_instance_conflicts_test.go @@ -0,0 +1,126 @@ +// Tests for the 409 responses the DeployEngine client reports when a create, update or +// destroy conflicts with an existing instance or with the instance a change set was staged for. +package deployengine + +import ( + "context" + "net/http" + + "github.com/newstack-cloud/bluelink/libs/deploy-engine-client/errors" + "github.com/newstack-cloud/bluelink/libs/deploy-engine-client/internal/testutils" + "github.com/newstack-cloud/bluelink/libs/deploy-engine-client/types" +) + +func (s *ClientSuite) Test_create_blueprint_instance_reports_the_instance_holding_the_name() { + _, err := s.createInstance(&types.BlueprintInstancePayload{ + InstanceName: testutils.StubTakenInstanceName, + }) + s.Require().Error(err) + + clientErr, isAlreadyExists := errors.IsInstanceAlreadyExistsError(err) + s.Require().True(isAlreadyExists) + s.Assert().Equal(http.StatusConflict, clientErr.StatusCode) + s.Assert().Equal(testutils.StubNameHolderInstanceID, clientErr.InstanceID) + s.Assert().Empty(clientErr.ChangesetInstanceID) +} + +func (s *ClientSuite) Test_create_blueprint_instance_reports_a_name_conflict_without_the_holder() { + _, err := s.createInstance(&types.BlueprintInstancePayload{ + InstanceName: testutils.StubTakenNameHolderGoneInstanceName, + }) + s.Require().Error(err) + + clientErr, isAlreadyExists := errors.IsInstanceAlreadyExistsError(err) + s.Require().True(isAlreadyExists) + s.Assert().Empty(clientErr.InstanceID) + + _, isMismatch := errors.IsChangesetInstanceMismatchError(err) + s.Assert().False(isMismatch) +} + +func (s *ClientSuite) Test_create_blueprint_instance_reports_a_change_set_staged_for_another_instance() { + _, err := s.createInstance(&types.BlueprintInstancePayload{ + InstanceName: "test-new-instance", + ChangeSetID: testutils.StubOtherInstanceChangesetID, + }) + s.Require().Error(err) + + clientErr, isMismatch := errors.IsChangesetInstanceMismatchError(err) + s.Require().True(isMismatch) + s.Assert().Equal(http.StatusConflict, clientErr.StatusCode) + s.Assert().Equal(testutils.StubChangesetInstanceID, clientErr.ChangesetInstanceID) + s.Assert().Empty(clientErr.InstanceID) + + _, isDriftBlocked := errors.IsDriftBlockedError(err) + s.Assert().False(isDriftBlocked) + _, isAlreadyExists := errors.IsInstanceAlreadyExistsError(err) + s.Assert().False(isAlreadyExists) +} + +func (s *ClientSuite) Test_update_blueprint_instance_reports_a_change_set_staged_for_a_new_instance() { + client := s.createAPIKeyClient(testAPIKey) + + _, err := client.UpdateBlueprintInstance( + context.Background(), + "test-instance-100", + &types.BlueprintInstancePayload{ + BlueprintDocumentInfo: types.BlueprintDocumentInfo{FileSourceScheme: "file"}, + ChangeSetID: testutils.StubNewInstanceChangesetID, + }, + ) + s.Require().Error(err) + + clientErr, isMismatch := errors.IsChangesetInstanceMismatchError(err) + s.Require().True(isMismatch) + s.Assert().Equal("test-instance-100", clientErr.InstanceID) + s.Assert().Empty(clientErr.ChangesetInstanceID) +} + +func (s *ClientSuite) Test_destroy_blueprint_instance_reports_a_change_set_staged_for_another_instance() { + client := s.createAPIKeyClient(testAPIKey) + + _, err := client.DestroyBlueprintInstance( + context.Background(), + "test-instance-100", + &types.DestroyBlueprintInstancePayload{ + ChangeSetID: testutils.StubOtherInstanceChangesetID, + }, + ) + s.Require().Error(err) + + clientErr, isMismatch := errors.IsChangesetInstanceMismatchError(err) + s.Require().True(isMismatch) + s.Assert().Equal("test-instance-100", clientErr.InstanceID) + s.Assert().Equal(testutils.StubChangesetInstanceID, clientErr.ChangesetInstanceID) +} + +func (s *ClientSuite) Test_update_blueprint_instance_still_reports_drift_as_drift() { + client := s.createAPIKeyClient(testAPIKey) + + _, err := client.UpdateBlueprintInstance( + context.Background(), + "test-instance-100", + &types.BlueprintInstancePayload{ + BlueprintDocumentInfo: types.BlueprintDocumentInfo{FileSourceScheme: "file"}, + ChangeSetID: testutils.StubDriftBlockedChangesetID, + }, + ) + s.Require().Error(err) + + clientErr, isDriftBlocked := errors.IsDriftBlockedError(err) + s.Require().True(isDriftBlocked) + s.Assert().Equal(testutils.StubDriftBlockedChangesetID, clientErr.DriftBlockedResponse.ChangesetID) + s.Assert().NotNil(clientErr.DriftBlockedResponse.ReconciliationResult) + + _, isMismatch := errors.IsChangesetInstanceMismatchError(err) + s.Assert().False(isMismatch) + _, isAlreadyExists := errors.IsInstanceAlreadyExistsError(err) + s.Assert().False(isAlreadyExists) +} + +func (s *ClientSuite) createInstance( + payload *types.BlueprintInstancePayload, +) (*types.BlueprintInstanceResponse, error) { + payload.FileSourceScheme = "file" + return s.createAPIKeyClient(testAPIKey).CreateBlueprintInstance(context.Background(), payload) +} diff --git a/libs/deploy-engine-client/error_helpers.go b/libs/deploy-engine-client/error_helpers.go index 7ed607e2..fbad0fae 100644 --- a/libs/deploy-engine-client/error_helpers.go +++ b/libs/deploy-engine-client/error_helpers.go @@ -81,5 +81,7 @@ func createClientError(resp *http.Response) *errors.ClientError { Code: errResp.Code, ValidationErrors: errResp.Errors, ValidationDiagnostics: errResp.Diagnostics, + InstanceID: errResp.InstanceID, + ChangesetInstanceID: errResp.ChangesetInstanceID, } } diff --git a/libs/deploy-engine-client/errors/errors.go b/libs/deploy-engine-client/errors/errors.go index ad4d703d..cff7df87 100644 --- a/libs/deploy-engine-client/errors/errors.go +++ b/libs/deploy-engine-client/errors/errors.go @@ -93,6 +93,17 @@ type ClientError struct { // is blocked due to drift detection. Contains the reconciliation result // and changeset ID for continuing after reconciliation. DriftBlockedResponse *types.DriftBlockedResponse + // InstanceID is set on a 409 to the instance the conflict involves. For + // ErrorCodeInstanceAlreadyExists, it is the instance that holds the requested name, + // and is empty when that instance was removed before the engine could look it up. + // The name has then most likely been freed, and as nothing was deployed, retrying + // the create is safe and may succeed. + // For ErrorCodeChangesetInstanceMismatch, it is the instance the change set was + // applied to, and is empty when the change set was applied to a new instance. + InstanceID string + // ChangesetInstanceID is set for ErrorCodeChangesetInstanceMismatch to the instance + // the change set was staged for, and is empty when it was staged for a new instance. + ChangesetInstanceID string } // ValidationError is a struct that represents a validation error @@ -110,6 +121,10 @@ type Response struct { Code string `json:"code,omitempty"` Errors []*ValidationError `json:"errors,omitempty"` Diagnostics []*core.Diagnostic `json:"validationDiagnostics,omitempty"` + // InstanceID and ChangesetInstanceID are set on 409 responses, + // as ClientError describes. + InstanceID string `json:"instanceId,omitempty"` + ChangesetInstanceID string `json:"changesetInstanceId,omitempty"` } func (e *ClientError) Error() string { @@ -211,3 +226,34 @@ func IsDeployChangesetError(err error) (*ClientError, bool) { } return nil, false } + +// ErrorCodeInstanceAlreadyExists is the error code returned with a 409 when a request +// to create a blueprint instance names an instance that already exists. +// ClientError.InstanceID holds the ID of the existing instance when the engine found it, +// so a caller can update that instance instead. +const ErrorCodeInstanceAlreadyExists = "INSTANCE_ALREADY_EXISTS" + +// IsInstanceAlreadyExistsError checks if the error is a client error +// indicating that the instance name given to create a blueprint instance is in use. +func IsInstanceAlreadyExistsError(err error) (*ClientError, bool) { + if clientErr, ok := err.(*ClientError); ok { + return clientErr, clientErr.Code == ErrorCodeInstanceAlreadyExists + } + return nil, false +} + +// ErrorCodeChangesetInstanceMismatch is the error code returned with a 409 when a +// deploy or destroy uses a change set staged for a different target: another instance, +// a new instance when the target exists, or an existing instance when the request +// creates one. +// ClientError.ChangesetInstanceID and ClientError.InstanceID hold the two instances. +const ErrorCodeChangesetInstanceMismatch = "CHANGESET_INSTANCE_MISMATCH" + +// IsChangesetInstanceMismatchError checks if the error is a client error +// indicating that a change set was used with an instance it wasn't staged for. +func IsChangesetInstanceMismatchError(err error) (*ClientError, bool) { + if clientErr, ok := err.(*ClientError); ok { + return clientErr, clientErr.Code == ErrorCodeChangesetInstanceMismatch + } + return nil, false +} diff --git a/libs/deploy-engine-client/internal/testutils/stub_deploy_engine_server.go b/libs/deploy-engine-client/internal/testutils/stub_deploy_engine_server.go index 21505ba2..de70c842 100644 --- a/libs/deploy-engine-client/internal/testutils/stub_deploy_engine_server.go +++ b/libs/deploy-engine-client/internal/testutils/stub_deploy_engine_server.go @@ -242,6 +242,7 @@ type postRequestPayload struct { // InstanceName is the user-defined name for the blueprint instance. // This is used when creating a new blueprint instance. InstanceName string `json:"instanceName"` + ChangeSetID string `json:"changeSetId"` } func (c *stubDeployEngineController) createBlueprintValidationHandler( @@ -436,6 +437,10 @@ func (c *stubDeployEngineController) createBlueprintInstanceHandler( return } + if handleCreateConflictTriggers(w, payload) { + return + } + // Use the provided instance name from the payload if available, // otherwise fall back to a default test name. instanceName := payload.InstanceName @@ -471,6 +476,15 @@ func (c *stubDeployEngineController) updateBlueprintInstanceHandler( return } + payload := &postRequestPayload{} + if decodeRequestBody(w, r, payload) { + return + } + + if handleUpdateConflictTriggers(w, id, payload.ChangeSetID) { + return + } + blueprintInstance := NewInstanceState(id, "test-instance-name", core.InstanceStatusDeploying) // Wrap response with lastEventId @@ -549,6 +563,20 @@ func (c *stubDeployEngineController) destroyBlueprintInstanceHandler( return } + payload := &postRequestPayload{} + if decodeRequestBody(w, r, payload) { + return + } + + if payload.ChangeSetID == StubOtherInstanceChangesetID { + writeConflictError(w, map[string]any{ + "code": errors.ErrorCodeChangesetInstanceMismatch, + "changesetInstanceId": StubChangesetInstanceID, + "instanceId": id, + }) + return + } + blueprintInstance := NewInstanceState(id, "test-instance-name", core.InstanceStatusDestroying) // Wrap response with lastEventId @@ -1057,6 +1085,78 @@ func writeJSON(w http.ResponseWriter, statusCode int, body any) { w.Write(bodyBytes) } +// The fields go at the top level of the body, beside the message, as the engine writes them. +func writeConflictError(w http.ResponseWriter, fields map[string]any) { + body := map[string]any{"message": "conflict"} + for key, value := range fields { + body[key] = value + } + writeJSON(w, http.StatusConflict, body) +} + func writeJSONError(w http.ResponseWriter, statusCode int, message string) { writeJSON(w, statusCode, errors.Response{Message: message}) } + +const ( + // StubTakenInstanceName is an instance name that the stub server answers a create + // with as already in use, held by StubNameHolderInstanceID. + StubTakenInstanceName = "test-taken-instance-name" + // StubNameHolderInstanceID is the instance that holds StubTakenInstanceName. + StubNameHolderInstanceID = "test-name-holder-instance-id" + // StubTakenNameHolderGoneInstanceName is an instance name that the stub server + // answers a create with as in use, without the holder's ID, as the engine does when + // the holder is removed before it can be looked up. + StubTakenNameHolderGoneInstanceName = "test-taken-instance-name-holder-gone" + // StubOtherInstanceChangesetID is a change set the stub server reports as staged for + // StubChangesetInstanceID when a create or destroy uses it. + StubOtherInstanceChangesetID = "test-other-instance-changeset-id" + // StubChangesetInstanceID is the instance StubOtherInstanceChangesetID was staged for. + StubChangesetInstanceID = "test-changeset-instance-id" + // StubNewInstanceChangesetID is a change set the stub server reports as staged for a + // new instance when an update uses it. + StubNewInstanceChangesetID = "test-new-instance-changeset-id" + // StubDriftBlockedChangesetID is a change set the stub server answers an update with + // as blocked by drift. + StubDriftBlockedChangesetID = "test-drift-blocked-changeset-id" +) + +func handleCreateConflictTriggers(w http.ResponseWriter, payload *postRequestPayload) bool { + switch { + case payload.InstanceName == StubTakenInstanceName: + writeConflictError(w, map[string]any{ + "code": errors.ErrorCodeInstanceAlreadyExists, + "instanceId": StubNameHolderInstanceID, + }) + case payload.InstanceName == StubTakenNameHolderGoneInstanceName: + writeConflictError(w, map[string]any{"code": errors.ErrorCodeInstanceAlreadyExists}) + case payload.ChangeSetID == StubOtherInstanceChangesetID: + writeConflictError(w, map[string]any{ + "code": errors.ErrorCodeChangesetInstanceMismatch, + "changesetInstanceId": StubChangesetInstanceID, + }) + default: + return false + } + return true +} + +func handleUpdateConflictTriggers(w http.ResponseWriter, instanceID string, changesetID string) bool { + switch changesetID { + case StubNewInstanceChangesetID: + writeConflictError(w, map[string]any{ + "code": errors.ErrorCodeChangesetInstanceMismatch, + "instanceId": instanceID, + }) + case StubDriftBlockedChangesetID: + writeJSON(w, http.StatusConflict, map[string]any{ + "message": "drift detected", + "instanceId": instanceID, + "changesetId": StubDriftBlockedChangesetID, + "reconciliationResult": stubReconciliationCheckResult(instanceID), + }) + default: + return false + } + return true +}