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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changesets/1795400400-5d2c8a17.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
id: 1795400400-5d2c8a17
features:
- core
targets:
- cli
type: fix
bump: patch
description: mask values marked sensitive in API error bodies shown by pretty and machine error output, matching --debug
author: TristanSpeakEasy
date: "2026-11-23"
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ func CLIError(cmd *cobra.Command, err error) error {
}

envelope := map[string]interface{}{
"error": err.Error(),
"error": redactedErrorText(err, classification),
Comment thread
TristanSpeakEasy marked this conversation as resolved.
Resolved
"exit_code": ExitCodeFor(classification),
}
mergeMachineErrorFields(envelope, err)
Expand Down
178 changes: 176 additions & 2 deletions templates/templates/cli/auxiliary/internal/output/classify.go.stmpl
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,17 @@ import (
"io"
"net"
"net/url"
"reflect"
"sort"
"strings"

"github.com/spf13/cobra"

"{{getGolangPackage}}/internal/clierrors"
"{{getGolangPackage}}/internal/flagutil"
{{- if hasAnyRedactGraphs}}
"{{getGolangPackage}}/internal/sdk/redact"
{{- end}}
"{{getGolangPackage}}/internal/sdk/sdkinternal/utils"
)

Expand Down Expand Up @@ -76,6 +81,7 @@ type Classification struct {
// because the request carried no credential; hints declared for the
// permission reason do not apply to that caller.
credentialsMissing bool
maskedValues []maskedBodyValue
}

type errorRule struct {
Expand Down Expand Up @@ -184,9 +190,10 @@ func Classify(cmd *cobra.Command, err error) Classification {
err = flagutil.WithCLIValidation(err)
}

rawBody := extractErrorBody(err)
c := Classification{
StatusCode: extractErrorStatusCode(err),
RawBody: extractErrorBody(err),
RawBody: redactErrorBody(cmd, err, rawBody),
Comment thread
TristanSpeakEasy marked this conversation as resolved.
Resolved
Origin: ErrorOriginAPI,
}
var origin interface{ ErrorOrigin() ErrorOrigin }
Expand Down Expand Up @@ -272,11 +279,178 @@ func Classify(cmd *cobra.Command, err error) Classification {
}
}

c.Message = classificationMessage(bodyMap, errorObject, err, c.RawBody)
c.maskedValues = maskedBodyValues(rawBody, c.RawBody)
if rawBody == "" {
if model := errorModelJSON(err); model != "" {
c.maskedValues = maskedBodyValues(model, redactErrorBody(cmd, err, model))
}
}
c.Message = scrubMaskedValues(redactedMessage(classificationMessage(bodyMap, errorObject, err, c.RawBody), rawBody, c.RawBody), c.maskedValues)
c.Hints = assembleHints(cmd, err, c, bodyMap, errorObject, ruleHints, useReasonRule)
return c
}

// redactErrorBody masks the values the operation's schema marks sensitive in
// an error response body, as --debug does when logging it. The operation comes
// from the response's request, or from the command when the error carries no
// response.
func redactErrorBody(cmd *cobra.Command, err error, body string) string {
{{- if hasAnyRedactGraphs}}
if body == "" {
return body
}
ctx := context.Background()
contentType := ""
for current := err; current != nil; current = errors.Unwrap(current) {
if res := extractHTTPResponse(current); res != nil {
contentType = res.Header.Get("Content-Type")
if res.Request != nil {
ctx = res.Request.Context()
}
break
}
}
if redact.Operation(ctx) == "" && cmd != nil {
operation := cmd.Annotations["speakeasy_sdk_operation"]
if operation == "" {
operation = cmd.Annotations["speakeasy_operation"]
}
ctx = redact.WithOperation(ctx, operation)
}
return string(redact.ResponseBody(ctx, contentType, []byte(body)))
Comment on lines +313 to +320

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this fallback use the generated SDK operation ID rather than the command's speakeasy_operation annotation?

The two differ when an operation is split into request serialization variants (operations.go#L75-L94). For example, operationId: createWidget with both application/x-www-form-urlencoded and multipart/form-data request bodies, no JSON variant, and an SSE response with a schema-marked sensitive field. Generation emits graphs for createWidget_form and createWidget_multipart, but the annotation is createWidget.

For an in-band error with no HTTP response:

raw := `{"detail":"secret-value"}`
err := &StreamEventError{Body: raw}
got := redactErrorBody(cmd, err, raw)
  • Expected: got is (sensitive), because the stream response graph masks the whole stream when it contains a sensitive value.
  • Actual: the lookup on createWidget finds no graph, so redact.ResponseBody returns the original JSON with secret-value.

This only affects errors without a retained HTTP request; ordinary HTTP errors already carry the suffixed ID on their request context. Storing the selected SDK operation ID in its own annotation, or mapping the original ID to the variant the command calls, would fix it. Worth adding this multi-content, no-response case next to the existing unsplit HTTP regression.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 14be773. Commands for operations split per request content type (where the SDK ID differs from the original operationId) now carry a speakeasy_sdk_operation annotation with op.ID, and the fallback lookup prefers it over speakeasy_operation. Every other command is unchanged. Regression: cliSensitiveSplitResponsePost has form and multipart bodies (no JSON) and a sensitive 400. TestErrorOutputRedactsSensitiveFieldsOfSplitOperation runs both split commands in agent mode. The primary SDK's typed errors carry no response, so this goes through the same no-response fallback as an in-band stream error. It fails when the new annotation is ignored.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The opcmd.go.stmpl change covers raw and promoted commands. Declared intent commands still set only speakeasy_operation: {{$c.OpID}}, which is OriginalID (intentcmd.go.stmpl#L49, intents.ts#L1303), even though they run a split method's RunFunc. An intent with op: createWidget (or op: createWidget_form) on an operation that only has form and multipart bodies therefore misses the redaction lookup whenever the error has no HTTP response, such as an in-band StreamEventError. Could the intent template also emit speakeasy_sdk_operation when found.op.GetID() !== found.op.OriginalID?

{{- else}}
return body
{{- end}}
}

// redactedMessage keeps a message taken from the error's own text from
// re-exposing what body redaction masked: typed error models render their
// fields as JSON or as a single field, and fallback errors embed the raw body.
func redactedMessage(message, rawBody, redactedBody string) string {
if redactedBody == rawBody || rawBody == "" {
return message
}
if strings.Contains(message, rawBody) {
return strings.ReplaceAll(message, rawBody, redactedBody)
}
if isValidJSON(message) {
return redactedBody
}
return scrubMaskedValues(message, maskedBodyValues(rawBody, redactedBody))
}

func scrubMaskedValues(text string, masked []maskedBodyValue) string {
for _, value := range masked {
text = strings.ReplaceAll(text, value.raw, value.redacted)
}
Comment on lines +342 to +345

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each strings.ReplaceAll here also scans masks that earlier replacements inserted, and the result is scrubbed a second time at L288 (and in redactedErrorText). A sensitive value that occurs inside (sensitive) therefore grows on every pass. For example, a typed error {"message":"status failed","secrets":["s","s","s","s","s","s","s","s"]}, with sensitive string items in secrets, turns status failed into a 1.3 MB message, and 16 items would exhaust memory.

Suggestion: remove duplicate values, build a single strings.NewReplacer from the longest-first list (it does one pass and doesn't rescan what it inserted), and apply it once per message. A test that scrubbing twice gives the same output as scrubbing once would cover this.

return text
}

// errorModelJSON encodes a generated error model that carries no response
// body, so its fields can still be checked against the operation's sensitive
// fields.
func errorModelJSON(err error) string {
for current := err; current != nil; current = errors.Unwrap(current) {
v := reflect.ValueOf(current)
if v.Kind() != reflect.Ptr || v.IsNil() || v.Elem().Kind() != reflect.Struct {
continue
}
if !strings.HasPrefix(v.Elem().Type().PkgPath(), "{{getGolangPackage}}/internal/sdk/models/") {
continue
}
if data, marshalErr := json.Marshal(current); marshalErr == nil {
return string(data)
}
}
return ""
}

type maskedBodyValue struct{ raw, redacted string }

// maskedBodyValues lists the scalar values of rawBody that redaction replaced,
// longest first so a value never shadows a longer one containing it.
func maskedBodyValues(rawBody, redactedBody string) []maskedBodyValue {
raw, rawOK := decodeJSONKeepingNumbers(rawBody)
redacted, redactedOK := decodeJSONKeepingNumbers(redactedBody)
if !rawOK || !redactedOK {
return nil
}
var out []maskedBodyValue
var walk func(raw, redacted any)
walk = func(raw, redacted any) {
if mask, ok := redacted.(string); ok {
if _, rawIsString := raw.(string); !rawIsString || raw != mask {
for _, leaf := range jsonScalarTexts(raw) {
if leaf != "" && leaf != mask {
out = append(out, maskedBodyValue{raw: leaf, redacted: mask})
}
}
}
return
}
switch rawValue := raw.(type) {
case map[string]any:
redactedMap, _ := redacted.(map[string]any)
for key, value := range rawValue {
walk(value, redactedMap[key])
}
case []any:
redactedList, _ := redacted.([]any)
for i, value := range rawValue {
if i < len(redactedList) {
walk(value, redactedList[i])
}
}
}
}
walk(raw, redacted)
sort.SliceStable(out, func(i, j int) bool { return len(out[i].raw) > len(out[j].raw) })
return out
}

// decodeJSONKeepingNumbers keeps each number's original spelling, which is how
// it appears in an error's text.
func decodeJSONKeepingNumbers(body string) (any, bool) {
decoder := json.NewDecoder(strings.NewReader(body))
decoder.UseNumber()
var value any
if err := decoder.Decode(&value); err != nil {
return nil, false
}
return value, true
}

func jsonScalarTexts(value any) []string {
switch typed := value.(type) {
case nil:
return nil
case string:
return []string{typed}
case json.Number:
return []string{typed.String()}
case map[string]any:
var out []string
for _, member := range typed {
out = append(out, jsonScalarTexts(member)...)
}
return out
case []any:
var out []string
for _, item := range typed {
out = append(out, jsonScalarTexts(item)...)
}
return out
default:
return []string{fmt.Sprint(typed)}
}
}

// redactedErrorText is err's own text with any response body it embeds
// replaced by the classification's redacted copy.
func redactedErrorText(err error, classification Classification) string {
return scrubMaskedValues(redactedMessage(err.Error(), extractErrorBody(err), classification.RawBody), classification.maskedValues)
}

func parseClassificationBody(raw string, c *Classification) (map[string]any, map[string]any) {
if raw == "" {
return nil, map[string]any{}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -692,7 +692,7 @@ func renderUnclassifiedStructuredAPIError(cmd *cobra.Command, out io.Writer, err
}
envelope = object
} else {
wrapped := map[string]interface{}{"error": err.Error(), "body": parsed}
wrapped := map[string]interface{}{"error": redactedErrorText(err, classification), "body": parsed}
if statusCode != 0 {
wrapped["status_code"] = statusCode
}
Expand All @@ -704,7 +704,7 @@ func renderUnclassifiedStructuredAPIError(cmd *cobra.Command, out io.Writer, err
}
}
if envelope == nil {
wrapped := map[string]interface{}{"error": err.Error()}
wrapped := map[string]interface{}{"error": redactedErrorText(err, classification)}
if statusCode != 0 {
wrapped["status_code"] = statusCode
}
Expand Down Expand Up @@ -735,7 +735,7 @@ func renderUnclassifiedStructuredAPIError(cmd *cobra.Command, out io.Writer, err
}
jsonData, marshalErr := json.MarshalIndent(envelope, "", " ")
if marshalErr != nil {
jsonData, _ = json.MarshalIndent(map[string]interface{}{"error": err.Error(), "exit_code": ExitCodeFor(classification)}, "", " ")
jsonData, _ = json.MarshalIndent(map[string]interface{}{"error": redactedErrorText(err, classification), "exit_code": ExitCodeFor(classification)}, "", " ")
}
printScrubbedJSON(out, jsonData, stderrColorize(cmd))
}
Expand Down Expand Up @@ -778,7 +778,7 @@ func renderStructuredError(cmd *cobra.Command, out io.Writer, err error, classif
jsonData, marshalErr := json.MarshalIndent(envelope, "", " ")
if marshalErr != nil {
jsonData, _ = json.MarshalIndent(map[string]interface{}{
"error": err.Error(),
"error": redactedErrorText(err, classification),
"error_type": string(classification.Type),
"exit_code": ExitCodeFor(classification),
"message": classification.Message,
Expand All @@ -796,7 +796,7 @@ func classifiedErrorEnvelope(err error, classification Classification) map[strin
envelope[key] = value
}
} else {
envelope = map[string]interface{}{"error": err.Error()}
envelope = map[string]interface{}{"error": redactedErrorText(err, classification)}
if classification.Body != nil {
envelope["body"] = classification.Body
} else if classification.RawBody != "" {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,51 @@ func TestAsyncFailureScrubsResolvedCredentials(t *testing.T) {
}
{{- end}}

func TestRedactedMessageDropsMaskedValues(t *testing.T) {
raw := `{"name":"n","value":"secret-value"}`
redacted := `{"name":"n","value":"(sensitive)"}`
for name, tc := range map[string]struct {
message, redacted, want string
}{
"embedded raw body": {message: "API error occurred: Status 400\n" + raw, redacted: redacted, want: "API error occurred: Status 400\n" + redacted},
"typed model JSON": {message: `{"value":"secret-value","name":"n"}`, redacted: redacted, want: redacted},
"message from body field": {message: "request rejected", redacted: redacted, want: "request rejected"},
"nothing masked": {message: raw, redacted: raw, want: raw},
} {
t.Run(name, func(t *testing.T) {
if got := redactedMessage(tc.message, raw, tc.redacted); got != tc.want {
t.Fatalf("got %q; want %q", got, tc.want)
}
})
}
if got := redactedMessage("request failed", "", redacted); got != "request failed" {
t.Fatalf("a message with no source body must be kept, got %q", got)
}
if got := redactedMessage("secret-value", raw, redacted); got != "(sensitive)" {
t.Fatalf("a message that is a masked field must be masked, got %q", got)
}
nested := `{"outer":{"token":"abc-secret","codes":[123456]}}`
nestedRedacted := `{"outer":"(sensitive)"}`
if got := redactedMessage("rejected abc-secret with 123456", nested, nestedRedacted); got != "rejected (sensitive) with (sensitive)" {
t.Fatalf("values under a masked subtree must be masked, got %q", got)
}
numbers := `{"id":9007199254740993,"rate":1.50,"name":"n"}`
numbersRedacted := `{"id":"(sensitive)","rate":"(sensitive)","name":"n"}`
if got := redactedMessage("id 9007199254740993 at 1.50", numbers, numbersRedacted); got != "id (sensitive) at (sensitive)" {
t.Fatalf("masked numbers must keep their original spelling, got %q", got)
}
}

func TestStructuredErrorEnvelopeRedactsNonObjectBodyErrorText(t *testing.T) {
raw := `["secret-value"]`
classification := Classification{RawBody: `["(sensitive)"]`, Body: []interface{}{"(sensitive)"}}
envelope := classifiedErrorEnvelope(errors.New(raw), classification)
text, _ := envelope["error"].(string)
if strings.Contains(text, "secret-value") || text != classification.RawBody {
t.Fatalf("error text = %q; want the redacted body", text)
}
}

func TestScrubJSONDocumentMasksDecodedValues(t *testing.T) {
t.Cleanup(config.Reset)
config.RegisterSecret(`example"secret`)
Expand Down
6 changes: 6 additions & 0 deletions templates/templates/cli/opcmd.go.stmpl
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ func {{$initFuncName}}(parent *cobra.Command) error {
parent.Annotations = map[string]string{}
}
parent.Annotations["speakeasy_operation"] = "{{escapeGoString $op.OriginalID}}"
{{- if ne $op.ID $op.OriginalID}}
parent.Annotations["speakeasy_sdk_operation"] = "{{escapeGoString $op.ID}}"
{{- end}}
parent.Annotations["speakeasy_cli_promoted"] = "true"
{{- if and $cliOp $cliOp.StreamSelect}}
parent.Annotations["speakeasy_stream_select"] = "{{escapeGoString $cliOp.StreamSelect}}"
Expand Down Expand Up @@ -74,6 +77,9 @@ func {{$initFuncName}}(parent *cobra.Command) error {
{{- end}}
Annotations: map[string]string{
"speakeasy_operation": "{{escapeGoString $op.OriginalID}}",
{{- if ne $op.ID $op.OriginalID}}
"speakeasy_sdk_operation": "{{escapeGoString $op.ID}}",
{{- end}}
{{- if and $cliOp $cliOp.StreamSelect}}
"speakeasy_stream_select": "{{escapeGoString $cliOp.StreamSelect}}",
{{- if $cliOp.StreamMetadataJSON}}
Expand Down
Loading
Loading