From bafd5441c3cf68dcf8174d17741753f516123c41 Mon Sep 17 00:00:00 2001 From: Andreas Grub Date: Thu, 12 Nov 2026 00:00:57 +0100 Subject: [PATCH 1/6] feat(client): claim a run and report its source steps and artifacts through the run client A building block runner works with client.Client.BuildingBlockRun: Claim hands it the next run with the run token, the inputs and the implementation, and sends the version of the HTTP client's user agent as X-Meshcloud-Runner-Version. RegisterSource, UpdateSourceSteps, DownloadArtifact and UploadArtifact address a run by its uuid, because the API key of a runner may not read a run. The names follow the operations of the meshObject API. Co-Authored-By: Claude Fable 5.2 --- client/building_block_run.go | 120 ++++++++++++++++++-- client/building_block_run_implementation.go | 77 +++++++++++++ client/building_block_run_source.go | 103 +++++++++++++++++ client/client.go | 2 +- client/http/auth.go | 4 + 5 files changed, 295 insertions(+), 11 deletions(-) create mode 100644 client/building_block_run_implementation.go create mode 100644 client/building_block_run_source.go diff --git a/client/building_block_run.go b/client/building_block_run.go index d9324d13..f3cd3889 100644 --- a/client/building_block_run.go +++ b/client/building_block_run.go @@ -2,16 +2,28 @@ package client import ( "context" + "encoding/json/jsontext" + "errors" + "fmt" + "io" "time" + "github.com/meshcloud/meshstack-cli/client/http" + "github.com/meshcloud/meshstack-cli/client/types/enum" "github.com/meshcloud/meshstack-cli/client/types/hal" + "github.com/meshcloud/meshstack-cli/internal/json" ) +const buildingBlockRunApiVersion = "v1" + +// MeshBuildingBlockRun keeps apiVersion and kind, because a runner passes the run on as it came. type MeshBuildingBlockRun struct { - Metadata MeshBuildingBlockRunMetadata `json:"metadata"` - Spec MeshBuildingBlockRunSpec `json:"spec"` - Status string `json:"status"` - Links hal.Links `json:"_links,omitzero"` + ApiVersion string `json:"apiVersion"` + Kind string `json:"kind"` + Metadata MeshBuildingBlockRunMetadata `json:"metadata"` + Spec MeshBuildingBlockRunSpec `json:"spec"` + Status string `json:"status"` + Links hal.Links `json:"_links,omitzero"` } func (run MeshBuildingBlockRun) IsRunning() bool { @@ -27,6 +39,9 @@ type MeshBuildingBlockRunSpec struct { RunNumber int `json:"runNumber"` Behavior string `json:"behavior"` BuildingBlock MeshBuildingBlockRunBuildingBlock `json:"buildingBlock"` + Definition MeshBuildingBlockRunDefinition `json:"buildingBlockDefinition"` + RunToken string `json:"runToken"` + Trigger *MeshBuildingBlockRunTrigger `json:"trigger,omitzero"` } type MeshBuildingBlockRunBuildingBlock struct { @@ -35,18 +50,103 @@ type MeshBuildingBlockRunBuildingBlock struct { } type MeshBuildingBlockRunBuildingBlockSpec struct { - DisplayName string `json:"displayName"` - TargetRef MeshBuildingBlockV2TargetRef `json:"targetRef"` - WorkspaceIdentifier string `json:"workspaceIdentifier"` - ProjectIdentifier string `json:"projectIdentifier,omitempty"` - FullPlatformIdentifier string `json:"fullPlatformIdentifier,omitempty"` + DisplayName string `json:"displayName"` + TargetRef MeshBuildingBlockV2TargetRef `json:"targetRef"` + WorkspaceIdentifier string `json:"workspaceIdentifier"` + ProjectIdentifier string `json:"projectIdentifier,omitempty"` + FullPlatformIdentifier string `json:"fullPlatformIdentifier,omitempty"` + Inputs []MeshBuildingBlockRunInput `json:"inputs"` + ParentBuildingBlocks []MeshBuildingBlockRunParentBlock `json:"parentBuildingBlocks"` +} + +type MeshBuildingBlockRunParentBlock struct { + BuildingBlockUuid string `json:"buildingBlockUuid"` + DefinitionUuid string `json:"definitionUuid"` +} + +type MeshBuildingBlockRunInput struct { + Key string `json:"key"` + // Value holds an int64 for an INTEGER and a []string for a MULTI_SELECT. + Value any `json:"value"` + Type enum.Entry[MeshBuildingBlockIOType] `json:"type"` + IsSensitive bool `json:"isSensitive"` + Env bool `json:"isEnvironment"` +} + +func (i *MeshBuildingBlockRunInput) UnmarshalJSONFrom(dec *jsontext.Decoder) error { + type wire MeshBuildingBlockRunInput + var target struct { + wire + + Value jsontext.Value `json:"value"` + } + if err := json.UnmarshalDecode(dec, &target, dec.Options()); err != nil { + return err + } + *i = MeshBuildingBlockRunInput(target.wire) + switch i.Type { + case MeshBuildingBlockIOTypeInteger: + i.Value = int64(0) + case MeshBuildingBlockIOTypeMultiSelect: + i.Value = []string(nil) + } + if err := json.Unmarshal(target.Value, &i.Value, dec.Options()); err != nil { + return fmt.Errorf("input %s: %w", i.Key, err) + } + return nil +} + +type MeshBuildingBlockRunDefinition struct { + Uuid string `json:"uuid"` + Spec MeshBuildingBlockRunDefinitionSpec `json:"spec"` +} + +type MeshBuildingBlockRunDefinitionSpec struct { + WorkspaceIdentifier string `json:"workspaceIdentifier"` + Version int `json:"version"` + Implementation MeshBuildingBlockRunImplementation `json:"implementation"` +} + +type MeshBuildingBlockRunTrigger struct { + Reason string `json:"reason"` + Author MeshObjectAuthor `json:"author"` } type MeshBuildingBlockRunFilter struct { BuildingBlockUuid string `json:"buildingBlockUuid,omitzero"` } -type MeshBuildingBlockRunClient = MeshObjectReadOnlyClient[MeshBuildingBlockRun, MeshBuildingBlockRunFilter] +var ErrNoRunToClaim = errors.New("no run to claim") + +type MeshBuildingBlockRunClient interface { + MeshObjectReadOnlyClient[MeshBuildingBlockRun, MeshBuildingBlockRunFilter] + + Claim(ctx context.Context, runnerUuid string) (MeshBuildingBlockRun, error) + // RegisterSource takes a 409 as success: the source was registered before. + RegisterSource(ctx context.Context, runUuid string, registration MeshBuildingBlockRunSourceRegistration) error + UpdateSourceSteps(ctx context.Context, runUuid, sourceId string, update MeshBuildingBlockRunStatusUpdate) (MeshBuildingBlockRunStatusUpdateResult, error) + // DownloadArtifact writes the artifact of the run that this run applies. + DownloadArtifact(ctx context.Context, runUuid string, w io.Writer) error + UploadArtifact(ctx context.Context, runUuid, path string) error +} + +type meshBuildingBlockRunClient struct { + meshObjectClient[MeshBuildingBlockRun, MeshBuildingBlockRunFilter] +} + +func (c meshBuildingBlockRunClient) Claim(ctx context.Context, runnerUuid string) (MeshBuildingBlockRun, error) { + run, err := c.unmarshalJsonBody[MeshBuildingBlockRun](c.do(ctx, http.MethodPost, c.collection.JoinPath("create"), + http.WithUrlQuery(map[string]string{"forRunnerUuid": runnerUuid}), + http.WithContentType(c.mediaType), + http.WithHeader("X-Meshcloud-Runner-Version", c.client.UserAgentVersion()))) + switch { + case isNotFound(err): + return run, ErrNoRunToClaim + case err == nil && run.Metadata.Uuid == "": + return run, errors.New("the claimed run has no uuid") + } + return run, err +} // MeshBuildingBlockRunApproval names the plan, because meshStack replaces it when a waiting run is planned again. type MeshBuildingBlockRunApproval struct { diff --git a/client/building_block_run_implementation.go b/client/building_block_run_implementation.go new file mode 100644 index 00000000..2cd549e1 --- /dev/null +++ b/client/building_block_run_implementation.go @@ -0,0 +1,77 @@ +package client + +import ( + "github.com/meshcloud/meshstack-cli/client/types/enum" + "github.com/meshcloud/meshstack-cli/client/types/polymorph" +) + +type MeshBuildingBlockRunImplementationType string + +var ( + MeshBuildingBlockRunImplementationTypes = enum.Enum[MeshBuildingBlockRunImplementationType]{} + MeshBuildingBlockRunImplementationTypeManual = MeshBuildingBlockRunImplementationTypes.Entry("MANUAL") + MeshBuildingBlockRunImplementationTypeTerraform = MeshBuildingBlockRunImplementationTypes.Entry("TERRAFORM") + MeshBuildingBlockRunImplementationTypeGithubWorkflow = MeshBuildingBlockRunImplementationTypes.Entry("GITHUB_WORKFLOW") + MeshBuildingBlockRunImplementationTypeGitlabCiCd = MeshBuildingBlockRunImplementationTypes.Entry("GITLAB_CICD") + MeshBuildingBlockRunImplementationTypeAzureDevops = MeshBuildingBlockRunImplementationTypes.Entry("AZURE_DEVOPS") +) + +type MeshBuildingBlockRunImplementation struct { + polymorph.Polymorph[MeshBuildingBlockRunImplementation, MeshBuildingBlockRunImplementationType] + + Manual *MeshBuildingBlockRunManualImplementation `polymorph:"MANUAL,inline"` + Terraform *MeshBuildingBlockRunTerraformImplementation `polymorph:"TERRAFORM,inline"` + GithubWorkflow *MeshBuildingBlockRunGithubImplementation `polymorph:"GITHUB_WORKFLOW,inline"` + GitlabCiCd *MeshBuildingBlockRunGitlabImplementation `polymorph:"GITLAB_CICD,inline"` + AzureDevops *MeshBuildingBlockRunAzureDevopsImplementation `polymorph:"AZURE_DEVOPS,inline"` +} + +type MeshBuildingBlockRunManualImplementation struct{} + +type MeshBuildingBlockRunTerraformImplementation struct { + TerraformVersion string `json:"terraformVersion"` + RepositoryUrl string `json:"repositoryUrl"` + RepositoryPath *string `json:"repositoryPath,omitzero"` + RefName *string `json:"refName,omitzero"` + SshPrivateKey *string `json:"sshPrivateKey,omitzero"` + KnownHost *MeshBuildingBlockRunKnownHost `json:"knownHost,omitzero"` + UseMeshHttpBackendFallback bool `json:"useMeshHttpBackendFallback"` + PreRunScript *string `json:"preRunScript,omitzero"` + Async bool `json:"async"` +} + +type MeshBuildingBlockRunKnownHost struct { + Host string `json:"host"` + KeyType string `json:"keyType"` + KeyValue string `json:"keyValue"` +} + +type MeshBuildingBlockRunGithubImplementation struct { + GithubBaseUrl string `json:"githubBaseUrl"` + Owner string `json:"owner"` + AppId string `json:"appId"` + AppPem string `json:"appPem"` + Repository string `json:"repository"` + Branch string `json:"branch"` + ApplyWorkflow string `json:"applyWorkflow"` + DestroyWorkflow *string `json:"destroyWorkflow,omitzero"` + Async bool `json:"async"` + OmitRunObjectInput bool `json:"omitRunObjectInput"` +} + +type MeshBuildingBlockRunGitlabImplementation struct { + GitlabBaseUrl string `json:"gitlabBaseUrl"` + ProjectId string `json:"projectId"` + RefName string `json:"refName"` + PipelineTriggerToken string `json:"pipelineTriggerToken"` +} + +type MeshBuildingBlockRunAzureDevopsImplementation struct { + AzureDevOpsBaseUrl string `json:"azureDevOpsBaseUrl"` + Organization string `json:"organization"` + Project string `json:"project"` + PipelineId string `json:"pipelineId"` + PersonalAccessToken string `json:"personalAccessToken"` + Async bool `json:"async"` + RefName *string `json:"refName,omitzero"` +} diff --git a/client/building_block_run_source.go b/client/building_block_run_source.go new file mode 100644 index 00000000..f02179ed --- /dev/null +++ b/client/building_block_run_source.go @@ -0,0 +1,103 @@ +package client + +import ( + "context" + "errors" + "fmt" + "io" + "time" + + "github.com/meshcloud/meshstack-cli/client/http" + "github.com/meshcloud/meshstack-cli/client/types/enum" +) + +type MeshBuildingBlockRunSourceRegistration struct { + Source MeshBuildingBlockRunSource `json:"source"` + Steps []MeshBuildingBlockRunStepRegistration `json:"steps"` +} + +type MeshBuildingBlockRunSource struct { + Id string `json:"id"` + ExternalId *string `json:"externalId,omitzero"` + ExternalUrl *string `json:"externalUrl,omitzero"` +} + +type MeshBuildingBlockRunStepRegistration struct { + Id string `json:"id"` + DisplayName string `json:"displayName"` + Status *string `json:"status"` +} + +type MeshBuildingBlockRunStatusUpdate struct { + BlockRunId string `json:"blockRunId,omitzero"` + Source string `json:"source,omitzero"` + Type enum.Entry[MeshBuildingBlockRunImplementationType] `json:"type,omitempty"` + Status *string `json:"status"` + CreatedOn time.Time `json:"createdOn,omitzero"` + Summary *string `json:"summary"` + Steps []MeshBuildingBlockRunStepStatusUpdate `json:"steps"` + ChangesDetected *bool `json:"changesDetected,omitzero"` +} + +type MeshBuildingBlockRunStepStatusUpdate struct { + Id string `json:"id"` + DisplayName string `json:"displayName"` + Status *string `json:"status,omitzero"` + UserMessage *string `json:"userMessage,omitzero"` + SystemMessage *string `json:"systemMessage,omitzero"` + Outputs map[string]MeshBuildingBlockRunOutput `json:"outputs,omitempty"` +} + +type MeshBuildingBlockRunOutput struct { + Value any `json:"value"` + Type string `json:"type"` + Sensitive bool `json:"isSensitive"` +} + +type MeshBuildingBlockRunStatusUpdateResult struct { + Abort bool `json:"runAborted"` +} + +const maxArtifactBytes = 128 << 20 + +func (c meshBuildingBlockRunClient) RegisterSource(ctx context.Context, runUuid string, registration MeshBuildingBlockRunSourceRegistration) error { + err := http.IgnoreResponse(c.do(ctx, http.MethodPost, c.collection.JoinPath(runUuid, "status", "source"), + http.WithJsonRequest(registration, c.mediaType), http.Retryable(http.RetryOnTransient))) + if httpErr, ok := errors.AsType[http.Error](err); ok && httpErr.IsConflict() { + return nil + } + return err +} + +func (c meshBuildingBlockRunClient) UpdateSourceSteps(ctx context.Context, runUuid, sourceId string, update MeshBuildingBlockRunStatusUpdate) (MeshBuildingBlockRunStatusUpdateResult, error) { + return http.UnmarshalJsonBody[MeshBuildingBlockRunStatusUpdateResult](c.do(ctx, http.MethodPatch, c.collection.JoinPath(runUuid, "status", "source", sourceId), + http.WithJsonRequest(update, c.mediaType), http.Retryable(http.RetryOnTransient))) +} + +func (c meshBuildingBlockRunClient) DownloadArtifact(ctx context.Context, runUuid string, w io.Writer) error { + body, err := c.do(ctx, http.MethodGet, c.collection.JoinPath(runUuid, "artifact"), http.WithHeader("Accept", "application/octet-stream")) + if err != nil { + return err + } + _, err = io.Copy(&cappedWriter{w, maxArtifactBytes}, body) + return errors.Join(err, body.Close()) +} + +func (c meshBuildingBlockRunClient) UploadArtifact(ctx context.Context, runUuid, path string) error { + return http.IgnoreResponse(c.do(ctx, http.MethodPut, c.collection.JoinPath(runUuid, "artifact"), + http.WithFileRequest(path, ""), http.WithHeader("Accept", "*/*"))) +} + +type cappedWriter struct { + io.Writer + + remaining int64 +} + +func (w *cappedWriter) Write(p []byte) (int, error) { + if int64(len(p)) > w.remaining { + return 0, fmt.Errorf("the artifact exceeds %d bytes", maxArtifactBytes) + } + w.remaining -= int64(len(p)) + return w.Writer.Write(p) +} diff --git a/client/client.go b/client/client.go index 1e31bde2..5d9a17b8 100644 --- a/client/client.go +++ b/client/client.go @@ -52,7 +52,7 @@ func New(ctx context.Context, endpoint xurl.URL, client http.Client, auth http.A return Client{ ApiKey: newMeshObjectClient[MeshApiKey, NoFilter](ctx, c, endpoint, "v1-preview"), BuildingBlockV2: newMeshObjectClient[MeshBuildingBlockV2, MeshBuildingBlockV2Filter](ctx, c, endpoint, buildingBlockV2ApiVersion), - BuildingBlockRun: newMeshObjectClient[MeshBuildingBlockRun, MeshBuildingBlockRunFilter](ctx, c, endpoint, "v1"), + BuildingBlockRun: meshBuildingBlockRunClient{newMeshObjectClient[MeshBuildingBlockRun, MeshBuildingBlockRunFilter](ctx, c, endpoint, buildingBlockRunApiVersion)}, BuildingBlockDefinition: newMeshObjectClient[MeshBuildingBlockDefinition, MeshBuildingBlockDefinitionFilter](ctx, c, endpoint, "v1"), BuildingBlockDefinitionVersion: newMeshObjectClient[MeshBuildingBlockDefinitionVersion, MeshBuildingBlockDefinitionVersionFilter](ctx, c, endpoint, "v1"), BuildingBlockRunner: newMeshObjectClient[MeshBuildingBlockRunner, MeshBuildingBlockRunnerFilter](ctx, c, endpoint, "v1-preview"), diff --git a/client/http/auth.go b/client/http/auth.go index 1d13d28b..7afe4988 100644 --- a/client/http/auth.go +++ b/client/http/auth.go @@ -61,6 +61,10 @@ func (c AuthorizedClient) String() string { return "authorized client " + c.client.userAgent.String() } +func (c AuthorizedClient) UserAgentVersion() string { + return c.client.userAgent.Version +} + func (c AuthorizedClient) ProxyTransport() gohttp.RoundTripper { return proxyTransport{c} } From ad27b0eb27708f974f7231b0e6f62de4d3a1b7d9 Mon Sep 17 00:00:00 2001 From: Andreas Grub Date: Thu, 12 Nov 2026 00:01:01 +0100 Subject: [PATCH 2/6] feat(client): tell whether an HTTP error is temporary http.Error.IsTemporary is true for 408, 423, 429 and every 5xx, so that a caller that polls, as a runner does for a pipeline run, knows when to go on. Co-Authored-By: Claude Fable 5.2 --- client/http/http_error.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/client/http/http_error.go b/client/http/http_error.go index 754d4a99..73e706a4 100644 --- a/client/http/http_error.go +++ b/client/http/http_error.go @@ -99,6 +99,14 @@ func (e Error) IsLocked() bool { return e.StatusCode == gohttp.StatusLocked } +func (e Error) IsTemporary() bool { + switch e.StatusCode { + case gohttp.StatusRequestTimeout, gohttp.StatusLocked, gohttp.StatusTooManyRequests: + return true + } + return e.StatusCode >= gohttp.StatusInternalServerError +} + func (e Error) body() (body errorBody, ok bool) { if err := json.Unmarshal(e.ResponseBody, &body); err != nil { return errorBody{}, false From 023bd40fd38f8cd955d0e37d7dc8d48006a8a4c3 Mon Sep 17 00:00:00 2001 From: Andreas Grub Date: Thu, 12 Nov 2026 05:58:50 +0100 Subject: [PATCH 3/6] feat(client): retry a refused connection A refused connection is retried under every policy and for every method, because the server received nothing. A runner started together with meshStack then waits for its API, and a client outlasts a restart of meshStack. Each retry logs a warning, so a person who gave a wrong endpoint sees why the command waits and can stop it. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.2 --- client/http/http_client_test.go | 27 ++++++++++++++++++++------- client/http/retry.go | 6 ++---- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/client/http/http_client_test.go b/client/http/http_client_test.go index 4431902b..3bb56d92 100644 --- a/client/http/http_client_test.go +++ b/client/http/http_client_test.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "log/slog" + "net" gohttp "net/http" "net/http/httptest" "net/url" @@ -14,7 +15,6 @@ import ( "path/filepath" "strings" "sync/atomic" - "syscall" "testing" "time" @@ -165,15 +165,28 @@ func TestRetry(t *testing.T) { assert.Equal(t, int32(1), backoff.calls.Load()) }) - t.Run("a refused connection is not retried", func(t *testing.T) { + t.Run("a refused connection is retried for any method", func(t *testing.T) { backoff := reset(gohttp.StatusOK) - server.proxy.Stop() - t.Cleanup(func() { require.NoError(t, server.proxy.Start()) }) + listener, err := new(net.ListenConfig).Listen(t.Context(), "tcp", "127.0.0.1:0") + require.NoError(t, err) + address := listener.Addr().String() + require.NoError(t, listener.Close()) + backoff.onRetry = func() { + started := httptest.NewUnstartedServer(gohttp.NotFoundHandler()) + require.NoError(t, started.Listener.Close()) + started.Listener, err = new(net.ListenConfig).Listen(t.Context(), "tcp", address) + require.NoError(t, err) + started.Start() + t.Cleanup(started.Close) + } - err := IgnoreResponse(client.DoRequest(t.Context(), MethodGet, server.Url, backoff.option())) + err = IgnoreResponse(client.DoRequest(t.Context(), MethodPost, &url.URL{Scheme: "http", Host: address}, + WithJsonRequest(map[string]string{"key": "value"}, ""), backoff.option())) - require.ErrorIs(t, err, syscall.ECONNREFUSED) - assert.Zero(t, backoff.calls.Load()) + httpErr, ok := errors.AsType[Error](err) + require.True(t, ok, "%v", err) + assert.Equal(t, gohttp.StatusNotFound, httpErr.StatusCode) + assert.Equal(t, int32(1), backoff.calls.Load()) }) t.Run("a server that does not answer is given up after stallTimeout, and not retried", func(t *testing.T) { diff --git a/client/http/retry.go b/client/http/retry.go index 202efa77..7de20ae5 100644 --- a/client/http/retry.go +++ b/client/http/retry.go @@ -40,7 +40,8 @@ func (on RetryOn) backoff(resp *gohttp.Response, err error, backoff retryBackoff } switch { case err != nil: - if on&RetryOnBrokenConnection != 0 && isBrokenConnection(err) { + // A refused connection is retried under every policy, because the server received nothing. + if errors.Is(err, syscall.ECONNREFUSED) || on&RetryOnBrokenConnection != 0 && isBrokenConnection(err) { return backoff } return nil @@ -111,9 +112,6 @@ type retryRoundTripper struct { func (r retryRoundTripper) RoundTrip(req *gohttp.Request) (*gohttp.Response, error) { retryOpts := requestOptionsFrom(req).retry on := retryOpts.policy(req.Method) - if on == 0 { - return r.next.RoundTrip(req) - } req = makeRequestBodyRetryable(req) for attempt := 1; ; attempt++ { resp, err := r.next.RoundTrip(req) From 018389d9192337276e936278c59b2cd22e783536 Mon Sep 17 00:00:00 2001 From: Andreas Grub Date: Thu, 12 Nov 2026 06:00:50 +0100 Subject: [PATCH 4/6] feat(client): redact secrets in logged request and response bodies by JSON pointer A debug log shows a JSON body indented, with the value at each redacted JSON pointer replaced by "[REDACTED]", and applies one-token pointers to the fields of a url-encoded form. Every request redacts the plaintext of a secret and the clientSecret of an API key; http.WithRedactedJsonPointers adds the tokens of an OIDC grant, the access token of an API key login and the run token of a claimed run. Co-Authored-By: Claude Opus 5.5 --- client/building_block_run.go | 3 +- client/http/http_client.go | 4 +- client/http/logging.go | 142 ++++++++++++++++-- client/http/logging_test.go | 83 ++++++++-- client/http/options.go | 20 ++- .../http/testdata/logged_body_redacted.json | 14 ++ .../logged_body_redacted_at_any_depth.json | 11 ++ internal/auth/credential/apikey.go | 1 + internal/oidc/client.go | 3 +- 9 files changed, 245 insertions(+), 36 deletions(-) create mode 100644 client/http/testdata/logged_body_redacted.json create mode 100644 client/http/testdata/logged_body_redacted_at_any_depth.json diff --git a/client/building_block_run.go b/client/building_block_run.go index f3cd3889..8e305a39 100644 --- a/client/building_block_run.go +++ b/client/building_block_run.go @@ -138,7 +138,8 @@ func (c meshBuildingBlockRunClient) Claim(ctx context.Context, runnerUuid string run, err := c.unmarshalJsonBody[MeshBuildingBlockRun](c.do(ctx, http.MethodPost, c.collection.JoinPath("create"), http.WithUrlQuery(map[string]string{"forRunnerUuid": runnerUuid}), http.WithContentType(c.mediaType), - http.WithHeader("X-Meshcloud-Runner-Version", c.client.UserAgentVersion()))) + http.WithHeader("X-Meshcloud-Runner-Version", c.client.UserAgentVersion()), + http.WithRedactedJsonPointers("/spec/runToken"))) switch { case isNotFound(err): return run, ErrNoRunToClaim diff --git a/client/http/http_client.go b/client/http/http_client.go index a32c9fa5..6ca9d1db 100644 --- a/client/http/http_client.go +++ b/client/http/http_client.go @@ -97,7 +97,7 @@ func (c Client) DoRequest(ctx context.Context, method string, url *url.URL, opti if opts.responseHeader != nil { *opts.responseHeader = res.Header } - body := newLoggedBody(ctx, "response body", newStallGuardedBody(res.Body, cancel)) + body := newLoggedBody(ctx, "response body", newStallGuardedBody(res.Body, cancel), opts.redactedJsonPointers) if isSuccess(res.StatusCode) { return body, nil } @@ -130,7 +130,7 @@ func (opts requestOptions) newRequest(ctx context.Context, method string, url *u return nil, fmt.Errorf("cannot build request body: %w", err) } } - req.Body = newLoggedBody(ctx, "request body", req.Body) + req.Body = newLoggedBody(ctx, "request body", req.Body, opts.redactedJsonPointers) slog.DebugContext(ctx, "request", "url", req.URL.String(), "method", req.Method, "headers", loggedHeaders(req.Header)) return req, nil } diff --git a/client/http/logging.go b/client/http/logging.go index 467b7b52..b96e9d08 100644 --- a/client/http/logging.go +++ b/client/http/logging.go @@ -4,17 +4,27 @@ import ( "bytes" "context" "encoding" + "encoding/json/jsontext" "errors" "fmt" "io" "log/slog" "maps" gohttp "net/http" + "net/url" + "regexp" "slices" "strings" "unicode/utf8" ) +const ( + redactedMarker = `"[REDACTED]"` + truncatedMarker = "[TRUNCATED]" + anyJsonField = "*" + anyJsonFields = "**" +) + // loggedHeaders is the request's headers with the bearer token taken out. Both methods produce // that redacted form, because both are reached: the CLI's sink formats with %v and calls String, // while terraform's sink encodes the fields as JSON and would otherwise walk this map itself and @@ -48,7 +58,7 @@ const loggedBodyLimit = 1024 var errClosedEarly = errors.New("closed before its end") // A goroutine owns the logged bytes, because the transport may close a body while it reads it. -func newLoggedBody(ctx context.Context, message string, body io.ReadCloser) io.ReadCloser { +func newLoggedBody(ctx context.Context, message string, body io.ReadCloser, redacted redactedJsonPointers) io.ReadCloser { if body == nil || body == gohttp.NoBody || !slog.Default().Enabled(ctx, slog.LevelDebug) { return body } @@ -58,7 +68,7 @@ func newLoggedBody(ctx context.Context, message string, body io.ReadCloser) io.R defer close(logged) head, err := io.ReadAll(io.LimitReader(tap, loggedBodyLimit+1)) _ = tap.Close() - slog.DebugContext(ctx, message, "body", loggedBody{head, err}) + slog.DebugContext(ctx, message, "body", loggedBody{head, err, redacted}) }() return tappedBody{body, tapped, logged} } @@ -90,8 +100,9 @@ func (b tappedBody) Close() error { // Without MarshalText terraform's JSON log would show a loggedBody as {}. type loggedBody struct { // head holds one byte more than loggedBodyLimit when the body was longer. - head []byte - err error + head []byte + err error + redacted redactedJsonPointers } var ( @@ -104,18 +115,31 @@ func (b loggedBody) MarshalText() ([]byte, error) { } func (b loggedBody) String() string { - text := b.head[:min(len(b.head), loggedBodyLimit)] - switch { - case len(text) == 0 && b.err == nil: + data := b.head[:min(len(b.head), loggedBodyLimit)] + if len(data) == 0 && b.err == nil { return "" - case isBinary(text): - return "" + } + text, jsonErr := b.redacted.pretty(data) + if text == "" && jsonErr != nil { + if isBinary(data) { + return "" + } + // An OIDC grant sends a url-encoded form, and a gateway answers with plain text. + text, jsonErr = string(data), nil + if _, err := url.ParseQuery(text); err == nil { + text = b.redacted.redactForm(text) + } + } + switch { case len(b.head) > loggedBodyLimit: - return string(text) + " [TRUNCATED]" + return text + " " + truncatedMarker case b.err != nil: return fmt.Sprintf("%s\n", text, b.err) + case jsonErr != nil: + return fmt.Sprintf("%s\n", text, jsonErr) + default: + return text } - return string(text) } // isBinary ignores an incomplete rune at the end, which the cap can cut. @@ -128,3 +152,99 @@ func isBinary(data []byte) bool { } return !utf8.Valid(data) || bytes.IndexByte(data, 0) >= 0 } + +// redactedJsonPointers are JSON Pointers (RFC 6901) in which anyJsonField matches one token and +// anyJsonFields any number of them, so /**/plaintext matches every plaintext. +type redactedJsonPointers []jsontext.Pointer + +func (r redactedJsonPointers) redacts(at jsontext.Pointer) bool { + tokens := slices.Collect(at.Tokens()) + return slices.ContainsFunc(r, func(pointer jsontext.Pointer) bool { + return matchTokens(slices.Collect(pointer.Tokens()), tokens) + }) +} + +func matchTokens(want, got []string) bool { + switch { + case len(want) == 0: + return len(got) == 0 + case want[0] == anyJsonFields: + return matchTokens(want[1:], got) || len(got) > 0 && matchTokens(want, got[1:]) + case len(got) == 0: + return false + default: + return (want[0] == anyJsonField || want[0] == got[0]) && matchTokens(want[1:], got[1:]) + } +} + +var formField = regexp.MustCompile(`(^|&)([^&=]*)=[^&]*`) + +// redactForm reads the name of each url-encoded field as a pointer of one token, such as /refresh_token. +func (r redactedJsonPointers) redactForm(text string) string { + return formField.ReplaceAllStringFunc(text, func(field string) string { + parts := formField.FindStringSubmatch(field) + name, err := url.QueryUnescape(parts[2]) + if err != nil || !r.redacts(jsontext.Pointer("").AppendToken(name)) { + return field + } + return parts[1] + parts[2] + "=" + redactedMarker + }) +} + +// pretty writes numbers as they arrived, so that they keep their text, and stops after the last +// complete token, so that a truncated body still shows. +func (r redactedJsonPointers) pretty(data []byte) (string, error) { + var out strings.Builder + + newline := func(depth int) { + out.WriteString("\n" + strings.Repeat(" ", depth)) + } + decoder := jsontext.NewDecoder(bytes.NewReader(data)) + for { + depth := decoder.StackDepth() + container, read := decoder.StackIndex(depth) + kind := decoder.PeekKind() + var raw []byte + switch kind { + case jsontext.KindInvalid: + if _, err := decoder.ReadToken(); !errors.Is(err, io.EOF) { + return out.String(), err + } + return out.String(), nil + case jsontext.KindBeginObject, jsontext.KindEndObject, jsontext.KindBeginArray, jsontext.KindEndArray: + if _, err := decoder.ReadToken(); err != nil { + return out.String(), err + } + raw = []byte{byte(kind)} + default: + var err error + if raw, err = decoder.ReadValue(); err != nil { + return out.String(), err + } + } + + isEnd := kind == jsontext.KindEndObject || kind == jsontext.KindEndArray + isName := container == jsontext.KindBeginObject && read%2 == 0 && !isEnd + switch { + case isEnd && read > 0: + newline(depth - 1) + case isEnd || depth == 0: + case container == jsontext.KindBeginObject && !isName: + out.WriteString(": ") + default: + if read > 0 { + out.WriteByte(',') + } + newline(depth) + } + out.Write(raw) + + // After an object name, StackPointer points to the member's value. + if isName && r.redacts(decoder.StackPointer()) { + out.WriteString(": " + redactedMarker) + if err := decoder.SkipValue(); err != nil { + return out.String(), err + } + } + } +} diff --git a/client/http/logging_test.go b/client/http/logging_test.go index 4cb316d0..6c62fe8f 100644 --- a/client/http/logging_test.go +++ b/client/http/logging_test.go @@ -2,6 +2,8 @@ package http import ( "bytes" + _ "embed" + "encoding/json/jsontext" "errors" "fmt" "io" @@ -16,17 +18,65 @@ import ( "github.com/meshcloud/meshstack-cli/internal/logs" ) +var ( + //go:embed testdata/logged_body_redacted.json + loggedBodyRedacted string + //go:embed testdata/logged_body_redacted_at_any_depth.json + loggedBodyRedactedAtAnyDepth string +) + func TestLoggedBody(t *testing.T) { - render := func(body string) string { + render := func(body string, redacted ...jsontext.Pointer) string { head := []byte(body) - return loggedBody{head: head[:min(len(head), loggedBodyLimit+1)]}.String() + return loggedBody{head: head[:min(len(head), loggedBodyLimit+1)], redacted: redacted}.String() } + const secret = "s3cr3t" + + t.Run("JSON is indented, and a pointer redacts the whole value", func(t *testing.T) { + assert.Equal(t, strings.TrimSuffix(loggedBodyRedacted, "\n"), + render(`{"items":[{"secret":"`+secret+`","name":"a"},{"secret":{"nested":"`+secret+`"}}],"config":{"key":"`+secret+`"},"at":1234567890123456789,"empty":{}}`, + "/items/*/secret", "/config")) + }) + + t.Run("a ** token matches at any depth", func(t *testing.T) { + assert.Equal(t, strings.TrimSuffix(loggedBodyRedactedAtAnyDepth, "\n"), + render(`{"plaintext":"`+secret+`","inputs":[{"value":{"plaintext":"`+secret+`","hash":"h"}}]}`, "/**/plaintext")) + }) + + t.Run("a url-encoded form redacts the field a one-token pointer names", func(t *testing.T) { + assert.Equal(t, `grant_type=refresh_token&refresh_token="[REDACTED]"&client_id=an-id`, + render(`grant_type=refresh_token&refresh_token=`+secret+`&client_id=an-id`, "/refresh_token")) + }) + + t.Run("plain text is shown as it came", func(t *testing.T) { + assert.Equal(t, "Bad Gateway", render("Bad Gateway")) + }) + + t.Run("binary content shows only its length", func(t *testing.T) { + assert.Equal(t, "", render(strings.Repeat("\x00\xff", 1500))) + }) + + t.Run("an empty body says so", func(t *testing.T) { + assert.Equal(t, "", render("")) + }) + + t.Run("broken JSON shows what decoded before the error", func(t *testing.T) { + assert.Equal(t, //nolint:testifylint // the rendering itself is tested + "{\n \"name\": \"a\"\n", render(`{"name":"a",`)) + }) + + t.Run("a body beyond the cap ends with the marker", func(t *testing.T) { + rendered := render(`{"token":"`+strings.Repeat(secret, loggedBodyLimit)+`"}`, "/token") + assert.Equal(t, //nolint:testifylint // the rendering itself is tested + "{\n \"token\": \"[REDACTED]\" [TRUNCATED]", rendered, + "a value the cap cut is redacted all the same") + + assert.True(t, strings.HasSuffix(render(strings.Repeat("ä", loggedBodyLimit)), "[TRUNCATED]"), + "a rune the cap cut in half does not make the text binary") + }) +} - assert.Equal(t, "Bad Gateway", render("Bad Gateway")) - assert.Equal(t, "", render(strings.Repeat("\x00\xff", 1500))) - assert.Equal(t, "", render("")) - assert.True(t, strings.HasSuffix(render(strings.Repeat("ä", loggedBodyLimit)), "[TRUNCATED]"), - "a rune the cap cut in half does not make the text binary") +func TestLoggedBodyIncomplete(t *testing.T) { assert.Equal(t, "partial\n", loggedBody{head: []byte("partial"), err: errors.New("connection lost")}.String()) } @@ -44,19 +94,20 @@ func TestLoggedRequest(t *testing.T) { const secret = "supersecret" client := NewClient(testUserAgent).WithAuthorization(BearerToken(secret)) - t.Run("both bodies are logged, and the bearer token is not", func(t *testing.T) { + t.Run("both bodies are logged redacted", func(t *testing.T) { captured := logs.Capture(t) - answer.status, answer.body = gohttp.StatusOK, `{"name":"answered"}` + answer.status, answer.body = gohttp.StatusOK, `{"token":"`+secret+`","name":"answered"}` _, err := UnmarshalJsonBody[map[string]string](client.DoRequest(t.Context(), MethodPost, server.Url, - WithJsonRequest(map[string]string{"name": "asked"}, ""))) + WithJsonRequest(map[string]string{"secret": secret}, ""), + WithRedactedJsonPointers("/secret", "/token"))) require.NoError(t, err) assert.Equal(t, []string{ fmt.Sprintf(`level=DEBUG msg=request url=%s method=POST headers="Accept=application/json\nAuthorization=[REDACTED]\nContent-Type=application/json\nUser-Agent=meshstack-cli/test"`, server.Url), - `level=DEBUG msg="request body" body="{\"name\":\"asked\"}"`, - `level=DEBUG msg=response status=200 headers="Content-Length=19\nContent-Type=text/plain; charset=utf-8"`, - `level=DEBUG msg="response body" body="{\"name\":\"answered\"}"`, + `level=DEBUG msg="request body" body="{\n \"secret\": \"[REDACTED]\"\n}"`, + `level=DEBUG msg=response status=200 headers="Content-Length=41\nContent-Type=text/plain; charset=utf-8"`, + `level=DEBUG msg="response body" body="{\n \"token\": \"[REDACTED]\",\n \"name\": \"answered\"\n}"`, }, captured.Lines(slog.LevelDebug)) }) @@ -66,7 +117,7 @@ func TestLoggedRequest(t *testing.T) { _ = IgnoreResponse(client.DoRequest(t.Context(), MethodGet, server.Url)) - assert.Contains(t, captured.String(), answer.body[:loggedBodyLimit]+" [TRUNCATED]") + assert.Contains(t, captured.String(), answer.body[:loggedBodyLimit]+" "+truncatedMarker) }) // The Terraform provider's sink encodes attributes as JSON. @@ -84,7 +135,7 @@ func TestLoggedRequest(t *testing.T) { logged := written.String() assert.NotContains(t, logged, secret) assert.Contains(t, logged, "Authorization=[REDACTED]") - assert.Contains(t, logged, `\"asked\":\"for\"`, "the request body") - assert.Contains(t, logged, `\"answer\":\"served\"`, "the response body") + assert.Contains(t, logged, `\"asked\": \"for\"`, "the request body") + assert.Contains(t, logged, `\"answer\": \"served\"`, "the response body") }) } diff --git a/client/http/options.go b/client/http/options.go index e1a56563..dbe824e2 100644 --- a/client/http/options.go +++ b/client/http/options.go @@ -20,11 +20,12 @@ type ( RequestOption func(opts *requestOptions) requestOptions struct { - requestModifiers []requestModifier - retry retryOptions - noRedirects bool - setBody requestModifier - responseHeader *gohttp.Header + requestModifiers []requestModifier + retry retryOptions + noRedirects bool + setBody requestModifier + redactedJsonPointers redactedJsonPointers + responseHeader *gohttp.Header } requestModifier func(req *gohttp.Request) error ) @@ -44,6 +45,7 @@ func newRequestOptions(options []RequestOption) requestOptions { maxRetries: 16, backoff: exponentialBackoff{MinWait: 1 * time.Second, MaxWait: 30 * time.Second}, }, + redactedJsonPointers: redactedJsonPointers{"/**/plaintext", "/**/clientSecret"}, } for _, option := range options { option(&opts) @@ -84,6 +86,14 @@ func WithoutRedirects() RequestOption { } } +// WithRedactedJsonPointers hides the values at these pointers in the debug log of the request and +// its response, on top of the defaults. +func WithRedactedJsonPointers(pointers ...jsontext.Pointer) RequestOption { + return func(opts *requestOptions) { + opts.redactedJsonPointers = append(opts.redactedJsonPointers, pointers...) + } +} + func WithCapturedResponseHeader(header *gohttp.Header) RequestOption { return func(opts *requestOptions) { opts.responseHeader = header diff --git a/client/http/testdata/logged_body_redacted.json b/client/http/testdata/logged_body_redacted.json new file mode 100644 index 00000000..1e110063 --- /dev/null +++ b/client/http/testdata/logged_body_redacted.json @@ -0,0 +1,14 @@ +{ + "items": [ + { + "secret": "[REDACTED]", + "name": "a" + }, + { + "secret": "[REDACTED]" + } + ], + "config": "[REDACTED]", + "at": 1234567890123456789, + "empty": {} +} diff --git a/client/http/testdata/logged_body_redacted_at_any_depth.json b/client/http/testdata/logged_body_redacted_at_any_depth.json new file mode 100644 index 00000000..b3bbe628 --- /dev/null +++ b/client/http/testdata/logged_body_redacted_at_any_depth.json @@ -0,0 +1,11 @@ +{ + "plaintext": "[REDACTED]", + "inputs": [ + { + "value": { + "plaintext": "[REDACTED]", + "hash": "h" + } + } + ] +} diff --git a/internal/auth/credential/apikey.go b/internal/auth/credential/apikey.go index 8e9c91d7..124cc333 100644 --- a/internal/auth/credential/apikey.go +++ b/internal/auth/credential/apikey.go @@ -50,6 +50,7 @@ func (apiKey *ApiKey) RefreshCachedToken(ctx context.Context, client http.Client }](client.DoRequest(ctx, http.MethodPost, loginEndpoint, http.Retryable(http.RetryOnTransient), http.WithJsonRequest(payload, "application/json"), + http.WithRedactedJsonPointers("/access_token"), )) if httpError, ok := errors.AsType[http.Error](err); ok && httpError.IsUnauthorized() { diff --git a/internal/oidc/client.go b/internal/oidc/client.go index 460f35b2..a7a8ac44 100644 --- a/internal/oidc/client.go +++ b/internal/oidc/client.go @@ -115,7 +115,8 @@ func (c Client) doPost[R any](ctx context.Context, endpoint *url.URL, payload ma } func (c Client) post(ctx context.Context, endpoint *url.URL, payload map[string]any) (io.ReadCloser, error) { - body, err := c.DoRequest(ctx, http.MethodPost, endpoint, http.WithFormRequest(payload)) + body, err := c.DoRequest(ctx, http.MethodPost, endpoint, http.WithFormRequest(payload), + http.WithRedactedJsonPointers("/code", "/code_verifier", "/refresh_token", "/access_token", "/id_token", "/id_token_hint")) if httpErr, ok := errors.AsType[http.Error](err); ok { var protocolErr protocolError if unmarshalErr := json.UnmarshalRead(bytes.NewReader(httpErr.ResponseBody), &protocolErr); unmarshalErr != nil { From 15add9c0ba7819b524605427c4ed1be868087707 Mon Sep 17 00:00:00 2001 From: Andreas Grub Date: Thu, 12 Nov 2026 21:20:46 +0100 Subject: [PATCH 5/6] refactor(client): leave the format of an error body to the caller of client/http http.Error now shows the body as it came, and BodyAsJson reads it into the type the caller expects. client.MeshObjectError reads the error body of meshStack and keeps what wraps the http.Error, such as the authorization of a 403. internal/oidc reads its OAuth error itself. meshstack api no longer writes the body of a failed answer to stdout; the error says what meshStack answered. Co-Authored-By: Claude Opus 5.5 --- client/error.go | 63 ++++++++++++++++++ client/http/http_client.go | 78 +++++++++++------------ client/http/http_error.go | 65 ++----------------- client/http/http_error_test.go | 46 +++---------- client/mesh_info.go | 3 +- client/meshobject.go | 3 +- cmd/api/api.go | 32 +++------- cmd/api/api_test.go | 17 +++-- cmd/buildingblock/abort_run.go | 3 +- cmd/buildingblock/tfstate/tfstate_test.go | 4 +- internal/apidocs/store.go | 2 +- internal/auth/credential/apikey.go | 10 +-- internal/oidc/client.go | 17 +++-- internal/tfstate/proxy.go | 3 +- internal/tfstate/store.go | 4 +- skills/meshstack-cli/SKILL.md | 4 +- 16 files changed, 162 insertions(+), 192 deletions(-) create mode 100644 client/error.go diff --git a/client/error.go b/client/error.go new file mode 100644 index 00000000..a3977913 --- /dev/null +++ b/client/error.go @@ -0,0 +1,63 @@ +package client + +import ( + "errors" + "fmt" + "strings" + + "github.com/meshcloud/meshstack-cli/client/http" +) + +// MeshObjectError is the body of every error response of meshStack, the 401 of a request without +// credentials included. +type MeshObjectError struct { + Http http.Error `json:"-"` + ErrorCode string `json:"errorCode"` + Message string `json:"message"` + ErrorId string `json:"errorId"` + ClientVersionHint string `json:"clientVersionHint"` + + // err keeps what wraps the http.Error, such as the authorization of a 403. + err error +} + +// MeshObjectErrorOf turns an error that holds an http.Error into a MeshObjectError, and returns any +// other error as it is. +func MeshObjectErrorOf(err error) error { + httpErr, ok := errors.AsType[http.Error](err) + if !ok { + return err + } + meshErr, _ := httpErr.BodyAsJson[MeshObjectError]() + meshErr.Http, meshErr.err = httpErr, err + return meshErr +} + +// Error puts the clientVersionHint on a line of its own. +func (e MeshObjectError) Error() string { + message := fmt.Sprintf("meshStack answered HTTP %d", e.Http.StatusCode) + if e.Message != "" { + message += ": " + e.Message + } + var details []string + if e.ErrorCode != "" { + details = append(details, "errorCode "+e.ErrorCode) + } + if e.ErrorId != "" { + details = append(details, "errorId "+e.ErrorId) + } + if len(details) > 0 { + message += " (" + strings.Join(details, ", ") + ")" + } + if e.ClientVersionHint != "" { + message += "\n" + e.ClientVersionHint + } + if e.Http.Method != "" { + message = e.Http.Method + " " + e.Http.Url + ": " + message + } + return strings.Replace(e.err.Error(), e.Http.Error(), message, 1) +} + +func (e MeshObjectError) Unwrap() error { + return e.err +} diff --git a/client/http/http_client.go b/client/http/http_client.go index 6ca9d1db..909b3984 100644 --- a/client/http/http_client.go +++ b/client/http/http_client.go @@ -40,11 +40,45 @@ func NewClient(userAgent UserAgent) Client { return Client{userAgent} } +// DoRequest leaves the body to the caller. +func (c Client) DoRequest(ctx context.Context, method string, url *url.URL, options ...RequestOption) (io.ReadCloser, error) { + opts := newRequestOptions(slices.Insert(options, 0, WithHeader("User-Agent", c.userAgent.String()))) + ctx, cancel := context.WithCancelCause(ctx) + req, err := opts.newRequest(ctx, method, url) + if err != nil { + cancel(nil) + return nil, err + } + res, err := goClient.Do(req) //nolint:bodyclose // the returned body closes it, or the error path below + if err != nil { + cancel(nil) + return nil, err + } + slog.DebugContext(ctx, "response", "status", res.StatusCode, "headers", loggedHeaders(res.Header)) + if opts.responseHeader != nil { + *opts.responseHeader = res.Header + } + body := newLoggedBody(ctx, "response body", newStallGuardedBody(res.Body, cancel), opts.redactedJsonPointers) + if statusCode := res.StatusCode; statusCode >= 200 && statusCode <= 299 { + return body, nil + } + responseBody, err := ReadAllBody(body, nil) + if err != nil { + return nil, fmt.Errorf("cannot read response body, status code %d: %w", res.StatusCode, err) + } + return nil, Error{ + Method: res.Request.Method, + Url: res.Request.URL.Redacted(), + StatusCode: res.StatusCode, + ResponseBody: responseBody, + } +} + func (c Client) String() string { return "unauthorized client " + c.userAgent.String() } -// UnmarshalJsonBody closes the body. +// UnmarshalJsonBody closes the body, and ignores it for a T of struct{}. func UnmarshalJsonBody[T any](body io.ReadCloser, err error, unmarshalers ...*json.Unmarshalers) (result T, _ error) { if _, ignored := any(result).(struct{}); ignored { return result, IgnoreResponse(body, err) @@ -67,6 +101,7 @@ func ReadAllBody(body io.ReadCloser, err error) ([]byte, error) { return data, errors.Join(err, body.Close()) } +// IgnoreResponse drains the body, so that the connection can be reused. func IgnoreResponse(body io.ReadCloser, err error) error { if err != nil { return err @@ -77,43 +112,6 @@ func IgnoreResponse(body io.ReadCloser, err error) error { return errors.Join(err, body.Close()) } -// DoRequest leaves the body to the caller. A non-2xx status is an Error that carries the response body, -// because an OIDC endpoint answers a refusal with an error document and that document is the only -// thing saying which refusal it was. -func (c Client) DoRequest(ctx context.Context, method string, url *url.URL, options ...RequestOption) (io.ReadCloser, error) { - opts := newRequestOptions(slices.Insert(options, 0, WithHeader("User-Agent", c.userAgent.String()))) - ctx, cancel := context.WithCancelCause(ctx) - req, err := opts.newRequest(ctx, method, url) - if err != nil { - cancel(nil) - return nil, err - } - res, err := goClient.Do(req) //nolint:bodyclose // the returned body closes it, or the error path below - if err != nil { - cancel(nil) - return nil, err - } - slog.DebugContext(ctx, "response", "status", res.StatusCode, "headers", loggedHeaders(res.Header)) - if opts.responseHeader != nil { - *opts.responseHeader = res.Header - } - body := newLoggedBody(ctx, "response body", newStallGuardedBody(res.Body, cancel), opts.redactedJsonPointers) - if isSuccess(res.StatusCode) { - return body, nil - } - responseBody, err := io.ReadAll(body) - _ = body.Close() - if err != nil { - return nil, fmt.Errorf("cannot read response body, status code %d: %w", res.StatusCode, err) - } - return nil, Error{ - Method: res.Request.Method, - Url: res.Request.URL.Redacted(), - StatusCode: res.StatusCode, - ResponseBody: responseBody, - } -} - // newRequest opens the body after every modifier, so that a modifier's error leaves none open. func (opts requestOptions) newRequest(ctx context.Context, method string, url *url.URL) (*gohttp.Request, error) { req, err := gohttp.NewRequestWithContext(opts.requestContext(ctx), method, url.String(), nil) @@ -134,7 +132,3 @@ func (opts requestOptions) newRequest(ctx context.Context, method string, url *u slog.DebugContext(ctx, "request", "url", req.URL.String(), "method", req.Method, "headers", loggedHeaders(req.Header)) return req, nil } - -func isSuccess(statusCode int) bool { - return statusCode >= 200 && statusCode <= 299 -} diff --git a/client/http/http_error.go b/client/http/http_error.go index 73e706a4..1cde19fd 100644 --- a/client/http/http_error.go +++ b/client/http/http_error.go @@ -14,16 +14,11 @@ type Error struct { ResponseBody []byte } -// Error describes the response from its fields, with the clientVersionHint on a line of its own. A -// response of another format is shown as it came. +// Error shows the body as it came, as only the caller knows the format of an error body. func (e Error) Error() string { - message := e.Summary() - body, ok := e.body() - switch { - case !ok: - message = fmt.Sprintf("%s, but the response is not in the expected error format: '%s'", message, string(e.ResponseBody)) - case body.ClientVersionHint != "": - message += "\n" + body.ClientVersionHint + message := fmt.Sprintf("HTTP %d", e.StatusCode) + if body := strings.TrimSpace(string(e.ResponseBody)); body != "" { + message += ": " + body } if e.Method == "" { return message @@ -31,48 +26,9 @@ func (e Error) Error() string { return e.Method + " " + e.Url + ": " + message } -// Summary is Error without the clientVersionHint and without a body of an unexpected format. -func (e Error) Summary() string { - summary := fmt.Sprintf("meshStack answered HTTP %d", e.StatusCode) - body, ok := e.body() - if !ok { - return summary - } - if body.Message != "" { - summary += ": " + body.Message - } - var details []string - if body.ErrorCode != "" { - details = append(details, "errorCode "+body.ErrorCode) - } - if body.ErrorId != "" { - details = append(details, "errorId "+body.ErrorId) - } - if len(details) > 0 { - summary += " (" + strings.Join(details, ", ") + ")" - } - return summary -} - -// errorBody is the body of every error response of meshStack, the 401 of a request without -// credentials included. -type errorBody struct { - ErrorCode string `json:"errorCode"` - Message string `json:"message"` - ErrorId string `json:"errorId"` - ClientVersionHint string `json:"clientVersionHint"` -} - -func (e Error) ErrorCode() string { - body, _ := e.body() - return body.ErrorCode -} - -// ClientVersionHint is what meshStack tells a client that is too old for it, and is empty for any other -// response. -func (e Error) ClientVersionHint() string { - body, _ := e.body() - return body.ClientVersionHint +func (e Error) BodyAsJson[T any]() (out T, err error) { + err = json.Unmarshal(e.ResponseBody, &out) + return } func (e Error) IsClientError() bool { @@ -106,10 +62,3 @@ func (e Error) IsTemporary() bool { } return e.StatusCode >= gohttp.StatusInternalServerError } - -func (e Error) body() (body errorBody, ok bool) { - if err := json.Unmarshal(e.ResponseBody, &body); err != nil { - return errorBody{}, false - } - return body, body.ErrorCode != "" || body.Message != "" -} diff --git a/client/http/http_error_test.go b/client/http/http_error_test.go index e868ccca..44947620 100644 --- a/client/http/http_error_test.go +++ b/client/http/http_error_test.go @@ -4,43 +4,17 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) -func TestErrorIsReadFromTheFieldsOfTheBody(t *testing.T) { - t.Run("shows the clientVersionHint on a line of its own", func(t *testing.T) { - err := Error{StatusCode: 404, ResponseBody: []byte( - `{"errorCode":"NoHandlerFound","message":"not found","errorId":"abc","clientVersionHint":"Upgrade to v0.9.0."}`)} +func TestError_ShowsTheBodyAsItCame(t *testing.T) { + err := Error{Method: MethodPost, Url: "https://id.example.com/token", StatusCode: 401, ResponseBody: []byte(`{"error":"invalid_client"}` + "\n")} - assert.Equal(t, "Upgrade to v0.9.0.", err.ClientVersionHint()) - assert.Equal(t, "NoHandlerFound", err.ErrorCode()) - assert.Equal(t, "meshStack answered HTTP 404: not found (errorCode NoHandlerFound, errorId abc)\nUpgrade to v0.9.0.", err.Error()) - }) - - t.Run("ignores a field it does not know", func(t *testing.T) { - err := Error{StatusCode: 409, ResponseBody: []byte(`{"errorCode":"X","message":"m","other":1}`)} - - assert.Equal(t, "meshStack answered HTTP 409: m (errorCode X)", err.Error()) - }) - - t.Run("shows no hint where there is none", func(t *testing.T) { - err := Error{StatusCode: 422, ResponseBody: []byte( - `{"errorCode":"Invalid","message":"bad","errorId":"x1"}`)} - - assert.Empty(t, err.ClientVersionHint()) - assert.Equal(t, "meshStack answered HTTP 422: bad (errorCode Invalid, errorId x1)", err.Error()) - }) - - for name, body := range map[string]string{ - "no JSON": `Bad Gateway`, - "no body": ``, - "an empty object": `{}`, - } { - t.Run("shows the raw body for "+name, func(t *testing.T) { - err := Error{StatusCode: 502, ResponseBody: []byte(body)} - - assert.Empty(t, err.ClientVersionHint()) - assert.Equal(t, "meshStack answered HTTP 502, but the response is not in the expected error format: '"+body+"'", err.Error()) - assert.Equal(t, "meshStack answered HTTP 502", err.Summary()) - }) - } + assert.Equal(t, `POST https://id.example.com/token: HTTP 401: {"error":"invalid_client"}`, err.Error()) + assert.Equal(t, "HTTP 502", Error{StatusCode: 502}.Error()) + body, bodyErr := err.BodyAsJson[struct { + Error string `json:"error"` + }]() + require.NoError(t, bodyErr) + assert.Equal(t, "invalid_client", body.Error) } diff --git a/client/mesh_info.go b/client/mesh_info.go index 8c0846cb..678e0b74 100644 --- a/client/mesh_info.go +++ b/client/mesh_info.go @@ -45,7 +45,8 @@ func NewMeshInfoClient(client http.Client, endpoint xurl.URL) MeshInfoClient { } func (c meshInfoClient) Read(ctx context.Context) (MeshInfo, error) { - return http.UnmarshalJsonBody[MeshInfo](c.DoRequest(ctx, http.MethodGet, c.Endpoint.JoinPath("/mesh/info"), http.WithHeader("Accept", "application/json"))) + body, err := c.DoRequest(ctx, http.MethodGet, c.Endpoint.JoinPath("/mesh/info"), http.WithHeader("Accept", "application/json")) + return http.UnmarshalJsonBody[MeshInfo](body, MeshObjectErrorOf(err)) } func (info MeshInfo) CheckVersion() error { diff --git a/client/meshobject.go b/client/meshobject.go index acdf8935..cdd8ef8d 100644 --- a/client/meshobject.go +++ b/client/meshobject.go @@ -127,7 +127,8 @@ func pluralizeKind(kind string) string { } func (c meshObjectClient[M, Filter]) do(ctx context.Context, method string, target *url.URL, options ...http.RequestOption) (io.ReadCloser, error) { - return c.client.DoRequest(ctx, method, target, slices.Insert(options, 0, http.WithHeader("Accept", c.mediaType))...) + body, err := c.client.DoRequest(ctx, method, target, slices.Insert(options, 0, http.WithHeader("Accept", c.mediaType))...) + return body, MeshObjectErrorOf(err) } // followLink sends the bearer token only to the origin of the endpoint. diff --git a/cmd/api/api.go b/cmd/api/api.go index d204d5e9..fd015a6a 100644 --- a/cmd/api/api.go +++ b/cmd/api/api.go @@ -33,7 +33,7 @@ Use this command for everything that the other commands do not cover. For a path --%[1]s sends a JSON file as the request body, or stdin for '-'. If the API docs list no version for the path, the command sets the Accept and Content-Type headers to application/json. If the command cannot download the API docs, it sets only the Content-Type header to application/json. -If the response status is not 2xx, the command still prints the response body, and then fails. +If the response status is not 2xx, the command prints nothing and fails with an error that shows what meshStack answered. To see what the API docs say about the request, run the same command line with 'api' replaced by 'api-docs'.`, requestJsonFlagName), Example: ` meshstack api '/api/meshobjects/meshtenants?workspaceIdentifier=my-workspace' @@ -78,16 +78,9 @@ To see what the API docs say about the request, run the same command line with ' options = append(options, http.WithHeader(key, values...)) } answer, err := http.ReadAllBody(meshStack.HttpClient.DoRequest(ctx, r.method, meshStack.Endpoint.JoinPath(r.target.Path), options...)) - if httpErr, ok := errors.AsType[client.HttpError](err); ok { - if writeErr := writeAnswer(cmd.OutOrStdout(), httpErr.ResponseBody); writeErr != nil { - return writeErr - } - // The body is on stdout already, so the error says only what it adds. - if r.docsHelpWith(httpErr) { - return withHint(fmt.Sprintf("%s. Run %s to see what the API expects", - httpErr.Summary(), docsCommand(cmd, args)), httpErr) - } - return withHint(strings.Replace(err.Error(), httpErr.Error(), httpErr.Summary(), 1), httpErr) + err = client.MeshObjectErrorOf(err) + if meshErr, ok := errors.AsType[client.MeshObjectError](err); ok && r.docsHelpWith(meshErr) { + return fmt.Errorf("%w\nRun %s to see what the API expects", err, docsCommand(cmd, args)) } if err != nil { return err @@ -103,26 +96,17 @@ To see what the API docs say about the request, run the same command line with ' // docsHelpWith is false for a 404 of a path meshStack serves nothing at, and of an object missing at a // documented path: the API docs say nothing about either. -func (r *request) docsHelpWith(httpErr client.HttpError) bool { +func (r *request) docsHelpWith(meshErr client.MeshObjectError) bool { switch { - case !httpErr.IsClientError(), httpErr.IsUnauthorized(), httpErr.IsForbidden(): + case !meshErr.Http.IsClientError(), meshErr.Http.IsUnauthorized(), meshErr.Http.IsForbidden(): return false - case httpErr.IsNotFound(): - return !r.documented && httpErr.ErrorCode() != noHandlerFound + case meshErr.Http.IsNotFound(): + return !r.documented && meshErr.ErrorCode != noHandlerFound default: return true } } -// withHint adds the hint on a line of its own. Stdout carries the raw body, which the error does not -// repeat. -func withHint(message string, httpErr client.HttpError) error { - if hint := httpErr.ClientVersionHint(); hint != "" { - message += "\n" + hint - } - return errors.New(message) -} - // noHandlerFound is the errorCode of meshStack's answer to a path it serves nothing at. const noHandlerFound = "NoHandlerFound" diff --git a/cmd/api/api_test.go b/cmd/api/api_test.go index 7d57fbb1..06cda8a4 100644 --- a/cmd/api/api_test.go +++ b/cmd/api/api_test.go @@ -126,18 +126,18 @@ func TestApi(t *testing.T) { } }) - t.Run("writes the body of a failed answer, and fails with a hint to api-docs on a client error", func(t *testing.T) { + t.Run("fails with the error of meshStack, and with a hint to api-docs on a client error", func(t *testing.T) { for status, wantError := range map[int]string{ - gohttp.StatusConflict: "meshStack answered HTTP 409: still in use. Run meshstack api-docs /api/x -H 'Accept: application/json' -X POST to see what the API expects", - gohttp.StatusBadGateway: "meshStack answered HTTP 502: still in use", - gohttp.StatusForbidden: "auth manual for " + meshStack.URL + ": meshStack answered HTTP 403: still in use", + gohttp.StatusConflict: "POST " + meshStack.URL + "/api/x: meshStack answered HTTP 409: still in use\nRun meshstack api-docs /api/x -H 'Accept: application/json' -X POST to see what the API expects", + gohttp.StatusBadGateway: "POST " + meshStack.URL + "/api/x: meshStack answered HTTP 502: still in use", + gohttp.StatusForbidden: "auth manual for " + meshStack.URL + ": POST " + meshStack.URL + "/api/x: meshStack answered HTTP 403: still in use", } { meshStack.answer(status, `{"message":"still in use"}`) stdout, err := meshStack.run(t, api.New(), "", "-X", "POST", "/api/x", "-H", "Accept: application/json") require.EqualError(t, err, wantError) - assert.JSONEq(t, "{\n \"message\": \"still in use\"\n}\n", stdout) + assert.Empty(t, stdout) } }) @@ -146,16 +146,15 @@ func TestApi(t *testing.T) { _, err := meshStack.run(t, api.New(), "", "/api/x", "-H", "Accept: application/json") - require.EqualError(t, err, "meshStack answered HTTP 404: gone (errorCode NotFound). Run meshstack api-docs /api/x -X GET -H 'Accept: application/json' to see what the API expects") + require.EqualError(t, err, "GET "+meshStack.URL+"/api/x: meshStack answered HTTP 404: gone (errorCode NotFound)\nRun meshstack api-docs /api/x -X GET -H 'Accept: application/json' to see what the API expects") }) t.Run("adds the clientVersionHint of a failed answer to the error", func(t *testing.T) { meshStack.answer(gohttp.StatusNotFound, `{"errorCode":"NoHandlerFound","message":"no handler","errorId":"abc","clientVersionHint":"Upgrade the meshStack CLI to v0.9.0."}`) - stdout, err := meshStack.run(t, api.New(), "", "/api/x", "-H", "Accept: application/json") + _, err := meshStack.run(t, api.New(), "", "/api/x", "-H", "Accept: application/json") - require.EqualError(t, err, "meshStack answered HTTP 404: no handler (errorCode NoHandlerFound, errorId abc)\nUpgrade the meshStack CLI to v0.9.0.") - assert.Contains(t, stdout, "clientVersionHint") + require.EqualError(t, err, "GET "+meshStack.URL+"/api/x: meshStack answered HTTP 404: no handler (errorCode NoHandlerFound, errorId abc)\nUpgrade the meshStack CLI to v0.9.0.") }) t.Run("asks for the media type the API docs list for a path of no version", func(t *testing.T) { diff --git a/cmd/buildingblock/abort_run.go b/cmd/buildingblock/abort_run.go index 3b73b79d..c308814e 100644 --- a/cmd/buildingblock/abort_run.go +++ b/cmd/buildingblock/abort_run.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "log/slog" - gohttp "net/http" "github.com/spf13/cobra" @@ -78,7 +77,7 @@ func (a runAction) abort(ctx context.Context) error { return nil } err = run.Abort(ctx) - if httpErr, ok := errors.AsType[client.HttpError](err); ok && httpErr.StatusCode == gohttp.StatusConflict { + if httpErr, ok := errors.AsType[client.HttpError](err); ok && httpErr.IsConflict() { return fmt.Errorf("run %s can no longer be aborted", run.Metadata.Uuid) } if err != nil { diff --git a/cmd/buildingblock/tfstate/tfstate_test.go b/cmd/buildingblock/tfstate/tfstate_test.go index 8084af15..cbfbabd8 100644 --- a/cmd/buildingblock/tfstate/tfstate_test.go +++ b/cmd/buildingblock/tfstate/tfstate_test.go @@ -255,7 +255,7 @@ func TestTfstate(t *testing.T) { require.NoError(t, ran.err) assert.Contains(t, ran.log, "level=WARN") - assert.Contains(t, ran.log, "meshStack answered HTTP 500") + assert.Contains(t, ran.log, "answered HTTP 500") }) t.Run("a refusal of meshStack says which rights the state takes", func(t *testing.T) { @@ -266,7 +266,7 @@ func TestTfstate(t *testing.T) { err := execChild(t, "GET").err require.Error(t, err) - assert.Contains(t, err.Error(), "meshStack answered HTTP 403") + assert.Contains(t, err.Error(), "answered HTTP 403") assert.Contains(t, err.Error(), "MANAGED_TFSTATE_LIST") assert.Contains(t, err.Error(), "meshstack login --apikey") }) diff --git a/internal/apidocs/store.go b/internal/apidocs/store.go index 92a4da2a..6d5f2d69 100644 --- a/internal/apidocs/store.go +++ b/internal/apidocs/store.go @@ -61,7 +61,7 @@ func (s store) load(ctx context.Context, client http.Client, endpoint xurl.URL) slog.DebugContext(ctx, fmt.Sprintf("The API docs of %s are up to date", endpoint)) return parse(url, storedDocument) // A meshStack from before /api/openapi answers 401. - case isHttpErr && (httpErr.StatusCode == gohttp.StatusUnauthorized || httpErr.StatusCode == gohttp.StatusNotFound): + case isHttpErr && (httpErr.IsUnauthorized() || httpErr.IsNotFound()): return openapi.Spec{}, fallbackError{fmt.Errorf("%s serves no API docs", endpoint)} case err != nil && storedDocument != nil: slog.WarnContext(ctx, fmt.Sprintf("Cannot load the API docs from %s, so this command reads the ones stored before: %s", url, err)) diff --git a/internal/auth/credential/apikey.go b/internal/auth/credential/apikey.go index 124cc333..1710bb79 100644 --- a/internal/auth/credential/apikey.go +++ b/internal/auth/credential/apikey.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" + meshstackclient "github.com/meshcloud/meshstack-cli/client" "github.com/meshcloud/meshstack-cli/client/http" "github.com/meshcloud/meshstack-cli/client/types/xurl" "github.com/meshcloud/meshstack-cli/internal/oidc/jwt" @@ -45,13 +46,14 @@ func (apiKey *ApiKey) RefreshCachedToken(ctx context.Context, client http.Client ClientSecret string `json:"clientSecret"` }{apiKey.ClientId, apiKey.ClientSecret} - answer, err := http.UnmarshalJsonBody[struct { - AccessToken jwt.JWT `json:"access_token"` - }](client.DoRequest(ctx, http.MethodPost, loginEndpoint, + body, err := client.DoRequest(ctx, http.MethodPost, loginEndpoint, http.Retryable(http.RetryOnTransient), http.WithJsonRequest(payload, "application/json"), http.WithRedactedJsonPointers("/access_token"), - )) + ) + answer, err := http.UnmarshalJsonBody[struct { + AccessToken jwt.JWT `json:"access_token"` + }](body, meshstackclient.MeshObjectErrorOf(err)) if httpError, ok := errors.AsType[http.Error](err); ok && httpError.IsUnauthorized() { return fmt.Errorf("api key %s at %s refused: %w; check the secret, or issue a new key in meshPanel", apiKey.ClientId, loginEndpoint, err) diff --git a/internal/oidc/client.go b/internal/oidc/client.go index a7a8ac44..77053dd3 100644 --- a/internal/oidc/client.go +++ b/internal/oidc/client.go @@ -1,7 +1,6 @@ package oidc import ( - "bytes" "context" "errors" "fmt" @@ -12,7 +11,6 @@ import ( "github.com/meshcloud/meshstack-cli/client/http" "github.com/meshcloud/meshstack-cli/client/types/xurl" - "github.com/meshcloud/meshstack-cli/internal/json" "github.com/meshcloud/meshstack-cli/internal/oidc/jwt" "github.com/meshcloud/meshstack-cli/internal/oidc/scope" ) @@ -118,20 +116,25 @@ func (c Client) post(ctx context.Context, endpoint *url.URL, payload map[string] body, err := c.DoRequest(ctx, http.MethodPost, endpoint, http.WithFormRequest(payload), http.WithRedactedJsonPointers("/code", "/code_verifier", "/refresh_token", "/access_token", "/id_token", "/id_token_hint")) if httpErr, ok := errors.AsType[http.Error](err); ok { - var protocolErr protocolError - if unmarshalErr := json.UnmarshalRead(bytes.NewReader(httpErr.ResponseBody), &protocolErr); unmarshalErr != nil { - return body, errors.Join(httpErr, unmarshalErr) + if protocolErr, parseErr := httpErr.BodyAsJson[protocolError](); parseErr == nil && protocolErr.Code != "" { + protocolErr.http = httpErr + return body, protocolErr } - return body, errors.Join(httpErr, protocolErr) } return body, err } +// protocolError is an OAuth 2.0 error response (RFC 6749, section 5.2). type protocolError struct { + http http.Error Code string `json:"error"` Description string `json:"error_description"` } func (e protocolError) Error() string { - return fmt.Sprintf("%s: %s", e.Code, e.Description) + return fmt.Sprintf("%s %s: HTTP %d: %s: %s", e.http.Method, e.http.Url, e.http.StatusCode, e.Code, e.Description) +} + +func (e protocolError) Unwrap() error { + return e.http } diff --git a/internal/tfstate/proxy.go b/internal/tfstate/proxy.go index 09b172f5..59ac8e51 100644 --- a/internal/tfstate/proxy.go +++ b/internal/tfstate/proxy.go @@ -306,8 +306,7 @@ func (p *Proxy) failOrPassLock(w gohttp.ResponseWriter, r *gohttp.Request, err e p.fail(w, r, err) return } - var holder LockInfo - _ = json.Unmarshal(httpErr.ResponseBody, &holder) + holder, _ := httpErr.BodyAsJson[LockInfo]() slog.WarnContext(r.Context(), fmt.Sprintf("meshStack refused to %s the state of building block %s, because %q holds the lock %s", action, p.Store.BuildingBlock, holder.Who, holder.ID)) passLock(w, httpErr) diff --git a/internal/tfstate/store.go b/internal/tfstate/store.go index 1660e835..c19cd198 100644 --- a/internal/tfstate/store.go +++ b/internal/tfstate/store.go @@ -9,6 +9,7 @@ import ( "fmt" "net/url" + "github.com/meshcloud/meshstack-cli/client" "github.com/meshcloud/meshstack-cli/client/http" "github.com/meshcloud/meshstack-cli/client/types/xurl" "github.com/meshcloud/meshstack-cli/internal/json" @@ -92,7 +93,8 @@ func (s Store) do(ctx context.Context, method string, target *url.URL, opts ...h // A 423 goes back to tofu at once, which names the holder of the lock and waits itself. opts = append(opts, http.Retryable(http.RetryOnBusy)) } - return http.ReadAllBody(s.client.DoRequest(ctx, method, target, opts...)) + body, err := s.client.DoRequest(ctx, method, target, opts...) + return http.ReadAllBody(body, client.MeshObjectErrorOf(err)) } func (s Store) wrap(action string, err error) error { diff --git a/skills/meshstack-cli/SKILL.md b/skills/meshstack-cli/SKILL.md index ae65d3d6..4677a451 100644 --- a/skills/meshstack-cli/SKILL.md +++ b/skills/meshstack-cli/SKILL.md @@ -402,8 +402,8 @@ current login. A full URL, such as a self link, chooses its origin as the endpoi where `MESHSTACK_ENDPOINT` names another one. For a meshObject endpoint it picks the latest API version, sets the `Accept` and `Content-Type` headers and fills in a missing `apiVersion` and `kind` of the body itself; `--api-version` picks another version. Leave the version out unless you need an older one, so the -command keeps working when a preview version becomes GA. An answer outside 2xx still prints its -body, but the command fails. +command keeps working when a preview version becomes GA. For an answer outside 2xx the command +prints nothing on stdout and fails with an error that shows what meshStack answered. Do not read the OpenAPI document yourself — it is about 1 MB. Ask `api-docs`, which reads the document the endpoint serves at `/api/openapi`, so it describes the API of that meshStack. It needs From ebc066e65eaef519bf1aab00859ccb2c88553b1b Mon Sep 17 00:00:00 2001 From: Andreas Grub Date: Wed, 25 Nov 2026 12:36:42 +0100 Subject: [PATCH 6/6] test: let the tf-block-runner clone the tfstate module from the local checkout The Go runner clones a commit of a local repository, so the test runs a head that is not pushed. Co-Authored-By: Claude Fable 5.2 --- cmd/internal/testacc/tfstate_test.go | 26 +++++--------------------- 1 file changed, 5 insertions(+), 21 deletions(-) diff --git a/cmd/internal/testacc/tfstate_test.go b/cmd/internal/testacc/tfstate_test.go index bc0caf6f..3e5a0d84 100644 --- a/cmd/internal/testacc/tfstate_test.go +++ b/cmd/internal/testacc/tfstate_test.go @@ -191,9 +191,10 @@ func bootstrapBuildingBlock(t *testing.T, c *cli, workspaceManager string) boots t.Helper() runId := "cli-" + strings.ToLower(rand.Text()[:8]) dir := copyTestdata(t, "bootstrap") + repositoryUrl, ref := localRepository(t) vars := []string{ "-var", "profile=" + defaultProfile, "-var", "run_id=" + runId, "-var", "workspace_manager=" + workspaceManager, - "-var", "repository_url=" + repositoryUrl, "-var", "git_ref=" + runnerRef(t), + "-var", "repository_url=" + repositoryUrl, "-var", "git_ref=" + ref, } c.tofu(t, dir, append([]string{"init", "-input=false"}, vars...)...) @@ -225,27 +226,10 @@ func bootstrapBuildingBlock(t *testing.T, c *cli, workspaceManager string) boots return bootstrappedBlock{} } -const repositoryUrl = "https://github.com/meshcloud/meshstack-cli.git" - -// runnerRef names the commit whose testdata/buildingblock the tf-block-runner runs, so that a branch -// tests its own module. The runner clones only the branches and tags of GitHub, so for the merge -// commit of a pull request, which meshfed-release's satellite lane tests, it takes the pull request's head. -func runnerRef(t *testing.T) string { +// localRepository lets the tf-block-runner clone the committed HEAD, so that a branch tests its own module. +func localRepository(t *testing.T) (url, ref string) { t.Helper() - head := git(t, "rev-parse", "HEAD") - remote := map[string]string{} - for line := range strings.Lines(git(t, "ls-remote", repositoryUrl)) { - sha, ref, _ := strings.Cut(strings.TrimSpace(line), "\t") - remote[ref] = sha - } - for ref, sha := range remote { - if pull, isMerge := strings.CutSuffix(ref, "/merge"); isMerge && strings.HasPrefix(ref, "refs/pull/") && sha == head { - return remote[pull+"/head"] - } - } - output, err := exec.CommandContext(t.Context(), "git", "fetch", "--dry-run", "--depth=1", repositoryUrl, head).CombinedOutput() - require.NoErrorf(t, err, "push HEAD %s first, as the tf-block-runner checks it out from %s:\n%s", head, repositoryUrl, output) - return head + return "file://" + git(t, "rev-parse", "--show-toplevel"), git(t, "rev-parse", "HEAD") } func git(t *testing.T, args ...string) string {