From cd330b9fd4e5184ea49e16b141b0b2aac2b7cb40 Mon Sep 17 00:00:00 2001 From: Tristan Cartledge Date: Mon, 23 Nov 2026 12:28:09 +1000 Subject: [PATCH 1/4] fix(cli): mask sensitive values in API error output --- .changesets/1795400400-5d2c8a17.yaml | 10 ++++ .../internal/output/classify.go.stmpl | 53 ++++++++++++++++++- .../internal/output/output_test.go.stmpl | 19 +++++++ .../tests/primary/diagnostics_test.go.stmpl | 22 ++++++++ .../primary/cli-sensitive-body-fields.yaml | 9 +++- zSDKs/sdk-cli/.speakeasy/gen.lock | 4 +- zSDKs/sdk-cli/internal/output/classify.go | 29 +++++++++- zSDKs/sdk-cli/internal/output/output_test.go | 19 +++++++ 8 files changed, 158 insertions(+), 7 deletions(-) create mode 100644 .changesets/1795400400-5d2c8a17.yaml diff --git a/.changesets/1795400400-5d2c8a17.yaml b/.changesets/1795400400-5d2c8a17.yaml new file mode 100644 index 000000000..708aa6411 --- /dev/null +++ b/.changesets/1795400400-5d2c8a17.yaml @@ -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" diff --git a/templates/templates/cli/auxiliary/internal/output/classify.go.stmpl b/templates/templates/cli/auxiliary/internal/output/classify.go.stmpl index 5c816959b..9269887e0 100644 --- a/templates/templates/cli/auxiliary/internal/output/classify.go.stmpl +++ b/templates/templates/cli/auxiliary/internal/output/classify.go.stmpl @@ -15,6 +15,9 @@ import ( "{{getGolangPackage}}/internal/clierrors" "{{getGolangPackage}}/internal/flagutil" + {{- if hasAnyRedactGraphs}} + "{{getGolangPackage}}/internal/sdk/redact" + {{- end}} "{{getGolangPackage}}/internal/sdk/sdkinternal/utils" ) @@ -184,9 +187,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), Origin: ErrorOriginAPI, } var origin interface{ ErrorOrigin() ErrorOrigin } @@ -272,11 +276,56 @@ func Classify(cmd *cobra.Command, err error) Classification { } } - c.Message = classificationMessage(bodyMap, errorObject, err, c.RawBody) + c.Message = redactedMessage(classificationMessage(bodyMap, errorObject, err, c.RawBody), rawBody, c.RawBody) 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 { + ctx = redact.WithOperation(ctx, cmd.Annotations["speakeasy_operation"]) + } + return string(redact.ResponseBody(ctx, contentType, []byte(body))) + {{- 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, and fallback errors embed the raw body. +func redactedMessage(message, rawBody, redactedBody string) string { + if redactedBody == rawBody { + return message + } + if strings.Contains(message, rawBody) { + return strings.ReplaceAll(message, rawBody, redactedBody) + } + if isValidJSON(message) { + return redactedBody + } + return message +} + func parseClassificationBody(raw string, c *Classification) (map[string]any, map[string]any) { if raw == "" { return nil, map[string]any{} diff --git a/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl b/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl index d14ff15e4..899493736 100644 --- a/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl +++ b/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl @@ -728,6 +728,25 @@ 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) + } + }) + } +} + func TestScrubJSONDocumentMasksDecodedValues(t *testing.T) { t.Cleanup(config.Reset) config.RegisterSecret(`example"secret`) diff --git a/templates/templates/cli/tests/primary/diagnostics_test.go.stmpl b/templates/templates/cli/tests/primary/diagnostics_test.go.stmpl index c04141a7d..b57f35785 100644 --- a/templates/templates/cli/tests/primary/diagnostics_test.go.stmpl +++ b/templates/templates/cli/tests/primary/diagnostics_test.go.stmpl @@ -666,6 +666,28 @@ func TestDebugRedactsSensitiveResponseFields(t *testing.T) { assert.Contains(t, h.GetStderr(), "visible-name") assert.Contains(t, h.GetStdout(), "canary-response", "decoded output keeps the value") } + +func TestErrorOutputRedactsSensitiveResponseFields(t *testing.T) { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"name":"visible-name","value":"canary-error"}`)) + })) + defer s.Close() + for _, args := range [][]string{ + {"--output-format", "pretty"}, + {"--output-format", "json"}, + {"--agent-mode"}, + } { + t.Run(strings.Join(args, " "), func(t *testing.T) { + h := NewCLITestHarness(t) + err := h.RunWithServer(s.URL, append(args, "response-bodies", "cli-sensitive-response-get")) + require.Error(t, err) + assert.NotContains(t, h.GetStdout()+h.GetStderr(), "canary-error") + assert.Contains(t, h.GetStderr(), "visible-name") + }) + } +} {{- if hasRootVersionFlag}} func TestRootVersionFlagMatchesVersionCommand(t *testing.T) { diff --git a/tests/specs/fragments/primary/cli-sensitive-body-fields.yaml b/tests/specs/fragments/primary/cli-sensitive-body-fields.yaml index 645b47ba7..2a680759a 100644 --- a/tests/specs/fragments/primary/cli-sensitive-body-fields.yaml +++ b/tests/specs/fragments/primary/cli-sensitive-body-fields.yaml @@ -278,7 +278,8 @@ paths: description: >- Response body with a field marked sensitive beside an unmarked one. Debug output must redact the marked value in the logged response while - keeping its sibling readable. + keeping its sibling readable. The error response reuses the schema so + error output is held to the same redaction. tags: - responseBodies responses: @@ -288,6 +289,12 @@ paths: application/json: schema: $ref: "#/components/schemas/CliSensitiveResponse" + "400": + description: Rejected request echoing the sensitive field + content: + application/json: + schema: + $ref: "#/components/schemas/CliSensitiveResponse" components: schemas: CliSensitiveBodyFields: diff --git a/zSDKs/sdk-cli/.speakeasy/gen.lock b/zSDKs/sdk-cli/.speakeasy/gen.lock index ab5cf9ff3..e808a956a 100644 --- a/zSDKs/sdk-cli/.speakeasy/gen.lock +++ b/zSDKs/sdk-cli/.speakeasy/gen.lock @@ -274,7 +274,7 @@ trackedFiles: internal/output/binary.go: last_write_checksum: sha1:6fd77172cad1bd29dc9f157b931345f96a172223 internal/output/classify.go: - last_write_checksum: sha1:cc4f38eeacdf495b1ae8b35a84a85f11a073cc5f + last_write_checksum: sha1:e7e061022aa2d0c66f1a0641860ff9420d281639 internal/output/color.go: last_write_checksum: sha1:c6f41f9691f6209f480d153c15c3424d8ca5883d internal/output/errortable.go: @@ -290,7 +290,7 @@ trackedFiles: internal/output/output.go: last_write_checksum: sha1:13f7704704fd7026b9127d8e82b229c2eed5570c internal/output/output_test.go: - last_write_checksum: sha1:bacc361dd459c538ad644813313e47cae16032ce + last_write_checksum: sha1:acaecfb6bc5066632cda572db32252484c9db88e internal/output/outputitems.go: last_write_checksum: sha1:d327eee8d9a395821fef201257e033bae50cda51 internal/output/paginated.go: diff --git a/zSDKs/sdk-cli/internal/output/classify.go b/zSDKs/sdk-cli/internal/output/classify.go index 04d9dfdde..f0a5f0a20 100644 --- a/zSDKs/sdk-cli/internal/output/classify.go +++ b/zSDKs/sdk-cli/internal/output/classify.go @@ -174,9 +174,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), Origin: ErrorOriginAPI, } var origin interface{ ErrorOrigin() ErrorOrigin } @@ -262,11 +263,35 @@ func Classify(cmd *cobra.Command, err error) Classification { } } - c.Message = classificationMessage(bodyMap, errorObject, err, c.RawBody) + c.Message = redactedMessage(classificationMessage(bodyMap, errorObject, err, c.RawBody), rawBody, c.RawBody) 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 { + return body +} + +// 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, and fallback errors embed the raw body. +func redactedMessage(message, rawBody, redactedBody string) string { + if redactedBody == rawBody { + return message + } + if strings.Contains(message, rawBody) { + return strings.ReplaceAll(message, rawBody, redactedBody) + } + if isValidJSON(message) { + return redactedBody + } + return message +} + func parseClassificationBody(raw string, c *Classification) (map[string]any, map[string]any) { if raw == "" { return nil, map[string]any{} diff --git a/zSDKs/sdk-cli/internal/output/output_test.go b/zSDKs/sdk-cli/internal/output/output_test.go index 06f299f52..332d60961 100644 --- a/zSDKs/sdk-cli/internal/output/output_test.go +++ b/zSDKs/sdk-cli/internal/output/output_test.go @@ -751,6 +751,25 @@ func TestAsyncFailureScrubsResolvedCredentials(t *testing.T) { } } +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) + } + }) + } +} + func TestScrubJSONDocumentMasksDecodedValues(t *testing.T) { t.Cleanup(config.Reset) config.RegisterSecret(`example"secret`) From 27ea886554e30e11c677bc9d62059f457f92fa02 Mon Sep 17 00:00:00 2001 From: Tristan Cartledge Date: Mon, 23 Nov 2026 13:39:14 +1000 Subject: [PATCH 2/4] fix(cli): redact the error text used in structured error envelopes --- .../auxiliary/internal/output/agentmode.go.stmpl | 2 +- .../cli/auxiliary/internal/output/classify.go.stmpl | 8 +++++++- .../cli/auxiliary/internal/output/output.go.stmpl | 10 +++++----- .../auxiliary/internal/output/output_test.go.stmpl | 13 +++++++++++++ zSDKs/sdk-cli/.speakeasy/gen.lock | 8 ++++---- zSDKs/sdk-cli/internal/output/agentmode.go | 2 +- zSDKs/sdk-cli/internal/output/classify.go | 8 +++++++- zSDKs/sdk-cli/internal/output/output.go | 10 +++++----- zSDKs/sdk-cli/internal/output/output_test.go | 13 +++++++++++++ 9 files changed, 56 insertions(+), 18 deletions(-) diff --git a/templates/templates/cli/auxiliary/internal/output/agentmode.go.stmpl b/templates/templates/cli/auxiliary/internal/output/agentmode.go.stmpl index 4e0c672d8..3f5a79028 100644 --- a/templates/templates/cli/auxiliary/internal/output/agentmode.go.stmpl +++ b/templates/templates/cli/auxiliary/internal/output/agentmode.go.stmpl @@ -213,7 +213,7 @@ func CLIError(cmd *cobra.Command, err error) error { } envelope := map[string]interface{}{ - "error": err.Error(), + "error": redactedErrorText(err, classification), "exit_code": ExitCodeFor(classification), } mergeMachineErrorFields(envelope, err) diff --git a/templates/templates/cli/auxiliary/internal/output/classify.go.stmpl b/templates/templates/cli/auxiliary/internal/output/classify.go.stmpl index 9269887e0..5fd453c1f 100644 --- a/templates/templates/cli/auxiliary/internal/output/classify.go.stmpl +++ b/templates/templates/cli/auxiliary/internal/output/classify.go.stmpl @@ -314,7 +314,7 @@ func redactErrorBody(cmd *cobra.Command, err error, body string) string { // re-exposing what body redaction masked: typed error models render their // fields as JSON, and fallback errors embed the raw body. func redactedMessage(message, rawBody, redactedBody string) string { - if redactedBody == rawBody { + if redactedBody == rawBody || rawBody == "" { return message } if strings.Contains(message, rawBody) { @@ -326,6 +326,12 @@ func redactedMessage(message, rawBody, redactedBody string) string { return message } +// 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 redactedMessage(err.Error(), extractErrorBody(err), classification.RawBody) +} + func parseClassificationBody(raw string, c *Classification) (map[string]any, map[string]any) { if raw == "" { return nil, map[string]any{} diff --git a/templates/templates/cli/auxiliary/internal/output/output.go.stmpl b/templates/templates/cli/auxiliary/internal/output/output.go.stmpl index 11ab42833..936baddee 100644 --- a/templates/templates/cli/auxiliary/internal/output/output.go.stmpl +++ b/templates/templates/cli/auxiliary/internal/output/output.go.stmpl @@ -693,7 +693,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 } @@ -705,7 +705,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 } @@ -736,7 +736,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)}, "", " ") } colorFlag, _ := flagutil.GetStringFlag(cmd, "color") printScrubbedJSON(out, jsonData, ShouldColorize(colorFlag)) @@ -781,7 +781,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, @@ -800,7 +800,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 != "" { diff --git a/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl b/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl index 899493736..e03eb6371 100644 --- a/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl +++ b/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl @@ -745,6 +745,19 @@ func TestRedactedMessageDropsMaskedValues(t *testing.T) { } }) } + if got := redactedMessage("request failed", "", redacted); got != "request failed" { + t.Fatalf("a message with no source body must be kept, 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) { diff --git a/zSDKs/sdk-cli/.speakeasy/gen.lock b/zSDKs/sdk-cli/.speakeasy/gen.lock index e808a956a..2c7695328 100644 --- a/zSDKs/sdk-cli/.speakeasy/gen.lock +++ b/zSDKs/sdk-cli/.speakeasy/gen.lock @@ -264,7 +264,7 @@ trackedFiles: internal/interactive/policy_test.go: last_write_checksum: sha1:770e41163c2746f200544c985e26c7be16aaedb9 internal/output/agentmode.go: - last_write_checksum: sha1:5c19eac15b8750087844d4a47c97ae5d997d473e + last_write_checksum: sha1:9ab31a176de1826142ec48f627935f8116158c72 internal/output/artifact.go: last_write_checksum: sha1:6f1f9f12fe4a10fb0fdc7cc47a9f8e8a92011bf4 internal/output/artifact_test.go: @@ -274,7 +274,7 @@ trackedFiles: internal/output/binary.go: last_write_checksum: sha1:6fd77172cad1bd29dc9f157b931345f96a172223 internal/output/classify.go: - last_write_checksum: sha1:e7e061022aa2d0c66f1a0641860ff9420d281639 + last_write_checksum: sha1:e485499a974252b71e0e197d85d22d88d2d83e7f internal/output/color.go: last_write_checksum: sha1:c6f41f9691f6209f480d153c15c3424d8ca5883d internal/output/errortable.go: @@ -288,9 +288,9 @@ trackedFiles: internal/output/outcome.go: last_write_checksum: sha1:0ea32db0867358ff91cd5fe6d24de400d09b4fc3 internal/output/output.go: - last_write_checksum: sha1:13f7704704fd7026b9127d8e82b229c2eed5570c + last_write_checksum: sha1:f05fd1e8abf0921f0328fd53bd4b268698786845 internal/output/output_test.go: - last_write_checksum: sha1:acaecfb6bc5066632cda572db32252484c9db88e + last_write_checksum: sha1:026ab5bb98201cd9cf394effbd961b7d7ca428d5 internal/output/outputitems.go: last_write_checksum: sha1:d327eee8d9a395821fef201257e033bae50cda51 internal/output/paginated.go: diff --git a/zSDKs/sdk-cli/internal/output/agentmode.go b/zSDKs/sdk-cli/internal/output/agentmode.go index 4b411759f..3e0ee189a 100644 --- a/zSDKs/sdk-cli/internal/output/agentmode.go +++ b/zSDKs/sdk-cli/internal/output/agentmode.go @@ -142,7 +142,7 @@ func CLIError(cmd *cobra.Command, err error) error { } envelope := map[string]interface{}{ - "error": err.Error(), + "error": redactedErrorText(err, classification), "exit_code": ExitCodeFor(classification), } mergeMachineErrorFields(envelope, err) diff --git a/zSDKs/sdk-cli/internal/output/classify.go b/zSDKs/sdk-cli/internal/output/classify.go index f0a5f0a20..82803b9bb 100644 --- a/zSDKs/sdk-cli/internal/output/classify.go +++ b/zSDKs/sdk-cli/internal/output/classify.go @@ -280,7 +280,7 @@ func redactErrorBody(cmd *cobra.Command, err error, body string) string { // re-exposing what body redaction masked: typed error models render their // fields as JSON, and fallback errors embed the raw body. func redactedMessage(message, rawBody, redactedBody string) string { - if redactedBody == rawBody { + if redactedBody == rawBody || rawBody == "" { return message } if strings.Contains(message, rawBody) { @@ -292,6 +292,12 @@ func redactedMessage(message, rawBody, redactedBody string) string { return message } +// 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 redactedMessage(err.Error(), extractErrorBody(err), classification.RawBody) +} + func parseClassificationBody(raw string, c *Classification) (map[string]any, map[string]any) { if raw == "" { return nil, map[string]any{} diff --git a/zSDKs/sdk-cli/internal/output/output.go b/zSDKs/sdk-cli/internal/output/output.go index 163cca2e1..9cde22125 100644 --- a/zSDKs/sdk-cli/internal/output/output.go +++ b/zSDKs/sdk-cli/internal/output/output.go @@ -689,7 +689,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 } @@ -701,7 +701,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 } @@ -732,7 +732,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)}, "", " ") } colorFlag, _ := flagutil.GetStringFlag(cmd, "color") printScrubbedJSON(out, jsonData, ShouldColorize(colorFlag)) @@ -777,7 +777,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, @@ -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 != "" { diff --git a/zSDKs/sdk-cli/internal/output/output_test.go b/zSDKs/sdk-cli/internal/output/output_test.go index 332d60961..9917bdf0c 100644 --- a/zSDKs/sdk-cli/internal/output/output_test.go +++ b/zSDKs/sdk-cli/internal/output/output_test.go @@ -768,6 +768,19 @@ func TestRedactedMessageDropsMaskedValues(t *testing.T) { } }) } + if got := redactedMessage("request failed", "", redacted); got != "request failed" { + t.Fatalf("a message with no source body must be kept, 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) { From 14be773b6a7a8c9f928b429b66296e670116cfe4 Mon Sep 17 00:00:00 2001 From: Tristan Cartledge Date: Tue, 24 Nov 2026 09:24:20 +1000 Subject: [PATCH 3/4] fix(cli): mask sensitive values in single-field error messages and split operations --- .../internal/output/classify.go.stmpl | 114 +++++++++++++++++- .../internal/output/output_test.go.stmpl | 8 ++ templates/templates/cli/opcmd.go.stmpl | 6 + .../tests/primary/diagnostics_test.go.stmpl | 43 +++++++ .../primary/cli-sensitive-body-fields.yaml | 62 ++++++++++ zSDKs/sdk-cli/.speakeasy/gen.lock | 4 +- zSDKs/sdk-cli/internal/output/classify.go | 108 ++++++++++++++++- zSDKs/sdk-cli/internal/output/output_test.go | 8 ++ 8 files changed, 342 insertions(+), 11 deletions(-) diff --git a/templates/templates/cli/auxiliary/internal/output/classify.go.stmpl b/templates/templates/cli/auxiliary/internal/output/classify.go.stmpl index 5fd453c1f..0918de682 100644 --- a/templates/templates/cli/auxiliary/internal/output/classify.go.stmpl +++ b/templates/templates/cli/auxiliary/internal/output/classify.go.stmpl @@ -9,6 +9,8 @@ import ( "io" "net" "net/url" + "reflect" + "sort" "strings" "github.com/spf13/cobra" @@ -79,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 { @@ -276,7 +279,13 @@ func Classify(cmd *cobra.Command, err error) Classification { } } - c.Message = redactedMessage(classificationMessage(bodyMap, errorObject, err, c.RawBody), rawBody, 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 } @@ -302,7 +311,11 @@ func redactErrorBody(cmd *cobra.Command, err error, body string) string { } } if redact.Operation(ctx) == "" && cmd != nil { - ctx = redact.WithOperation(ctx, cmd.Annotations["speakeasy_operation"]) + 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))) {{- else}} @@ -312,7 +325,7 @@ func redactErrorBody(cmd *cobra.Command, err error, body string) string { // 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, and fallback errors embed the raw body. +// 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 @@ -323,13 +336,104 @@ func redactedMessage(message, rawBody, redactedBody string) string { if isValidJSON(message) { return redactedBody } - return message + 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) + } + 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 { + var raw, redacted any + if json.Unmarshal([]byte(rawBody), &raw) != nil || json.Unmarshal([]byte(redactedBody), &redacted) != nil { + 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 +} + +func jsonScalarTexts(value any) []string { + switch typed := value.(type) { + case nil: + return nil + case string: + return []string{typed} + 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 redactedMessage(err.Error(), extractErrorBody(err), classification.RawBody) + return scrubMaskedValues(redactedMessage(err.Error(), extractErrorBody(err), classification.RawBody), classification.maskedValues) } func parseClassificationBody(raw string, c *Classification) (map[string]any, map[string]any) { diff --git a/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl b/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl index e03eb6371..4318ba32a 100644 --- a/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl +++ b/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl @@ -748,6 +748,14 @@ func TestRedactedMessageDropsMaskedValues(t *testing.T) { 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) + } } func TestStructuredErrorEnvelopeRedactsNonObjectBodyErrorText(t *testing.T) { diff --git a/templates/templates/cli/opcmd.go.stmpl b/templates/templates/cli/opcmd.go.stmpl index a077925cd..7b00ccbe4 100644 --- a/templates/templates/cli/opcmd.go.stmpl +++ b/templates/templates/cli/opcmd.go.stmpl @@ -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}}" @@ -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}} diff --git a/templates/templates/cli/tests/primary/diagnostics_test.go.stmpl b/templates/templates/cli/tests/primary/diagnostics_test.go.stmpl index b57f35785..860826e06 100644 --- a/templates/templates/cli/tests/primary/diagnostics_test.go.stmpl +++ b/templates/templates/cli/tests/primary/diagnostics_test.go.stmpl @@ -688,6 +688,49 @@ func TestErrorOutputRedactsSensitiveResponseFields(t *testing.T) { }) } } + +func TestErrorOutputRedactsSensitiveErrorMessageField(t *testing.T) { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"detail":"canary-message","name":"visible-name"}`)) + })) + defer s.Close() + for _, args := range [][]string{ + {"--output-format", "pretty"}, + {"--output-format", "json"}, + {"--agent-mode"}, + } { + t.Run(strings.Join(args, " "), func(t *testing.T) { + h := NewCLITestHarness(t) + err := h.RunWithServer(s.URL, append(args, "response-bodies", "cli-sensitive-error-message-get")) + require.Error(t, err) + assert.NotContains(t, h.GetStdout()+h.GetStderr(), "canary-message") + assert.Contains(t, h.GetStderr(), redact.Mask) + }) + } +} + +func TestErrorOutputRedactsSensitiveFieldsOfSplitOperation(t *testing.T) { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"name":"visible-name","value":"canary-split"}`)) + })) + defer s.Close() + for name, command := range map[string][]string{ + "form": {"cli-sensitive-split-response-post-form", "--name", "n", "--value", "v"}, + "multipart": {"cli-sensitive-split-response-post-multipart", "--label", "l"}, + } { + t.Run(name, func(t *testing.T) { + h := NewCLITestHarness(t) + err := h.RunWithServer(s.URL, append([]string{"--agent-mode", "response-bodies"}, command...)) + require.Error(t, err) + assert.NotContains(t, h.GetStdout()+h.GetStderr(), "canary-split") + assert.Contains(t, h.GetStderr(), "visible-name") + }) + } +} {{- if hasRootVersionFlag}} func TestRootVersionFlagMatchesVersionCommand(t *testing.T) { diff --git a/tests/specs/fragments/primary/cli-sensitive-body-fields.yaml b/tests/specs/fragments/primary/cli-sensitive-body-fields.yaml index 2a680759a..0efd4df04 100644 --- a/tests/specs/fragments/primary/cli-sensitive-body-fields.yaml +++ b/tests/specs/fragments/primary/cli-sensitive-body-fields.yaml @@ -295,6 +295,58 @@ paths: application/json: schema: $ref: "#/components/schemas/CliSensitiveResponse" + /anything/cli/sensitiveErrorMessage: + get: + x-speakeasy-exclude-test-sdk: [csharp, go, javav2, mcp-typescript, php, postman, pythonv2, ruby, terraform, typescriptv2, unity] + operationId: cliSensitiveErrorMessageGet + description: >- + Error response whose designated error-message field is itself marked + sensitive. Error output must mask it in the reported message as well + as in the body, while keeping its unmarked sibling readable. + tags: + - responseBodies + responses: + "200": + description: OK + "400": + description: Rejected request whose message is sensitive + content: + application/json: + schema: + $ref: "#/components/schemas/CliSensitiveErrorMessage" + /anything/cli/sensitiveSplitResponse: + post: + x-speakeasy-exclude-test-sdk: [csharp, go, javav2, mcp-typescript, php, postman, pythonv2, ruby, terraform, typescriptv2, unity] + operationId: cliSensitiveSplitResponsePost + description: >- + Operation split into one generated method per request content type + (form and multipart, no JSON), whose error response marks a field + sensitive. Error output must mask it whichever generated method the + command calls. + tags: + - responseBodies + requestBody: + required: true + content: + application/x-www-form-urlencoded: + schema: + $ref: "#/components/schemas/CliPlainBodyFields" + multipart/form-data: + schema: + type: object + required: [label] + properties: + label: + type: string + responses: + "200": + description: OK + "400": + description: Rejected request echoing the sensitive field + content: + application/json: + schema: + $ref: "#/components/schemas/CliSensitiveResponse" components: schemas: CliSensitiveBodyFields: @@ -569,6 +621,16 @@ components: properties: label: type: string + CliSensitiveErrorMessage: + type: object + required: [detail, name] + properties: + detail: + type: string + x-speakeasy-error-message: true + x-speakeasy-param-sensitive: true + name: + type: string CliSensitiveResponse: type: object required: diff --git a/zSDKs/sdk-cli/.speakeasy/gen.lock b/zSDKs/sdk-cli/.speakeasy/gen.lock index 2c7695328..8d1411cf8 100644 --- a/zSDKs/sdk-cli/.speakeasy/gen.lock +++ b/zSDKs/sdk-cli/.speakeasy/gen.lock @@ -274,7 +274,7 @@ trackedFiles: internal/output/binary.go: last_write_checksum: sha1:6fd77172cad1bd29dc9f157b931345f96a172223 internal/output/classify.go: - last_write_checksum: sha1:e485499a974252b71e0e197d85d22d88d2d83e7f + last_write_checksum: sha1:82f52ea41b7b4e604721cf4688550f7308f02258 internal/output/color.go: last_write_checksum: sha1:c6f41f9691f6209f480d153c15c3424d8ca5883d internal/output/errortable.go: @@ -290,7 +290,7 @@ trackedFiles: internal/output/output.go: last_write_checksum: sha1:f05fd1e8abf0921f0328fd53bd4b268698786845 internal/output/output_test.go: - last_write_checksum: sha1:026ab5bb98201cd9cf394effbd961b7d7ca428d5 + last_write_checksum: sha1:93e9bc94488084c2c7b69a33cf28002def59192e internal/output/outputitems.go: last_write_checksum: sha1:d327eee8d9a395821fef201257e033bae50cda51 internal/output/paginated.go: diff --git a/zSDKs/sdk-cli/internal/output/classify.go b/zSDKs/sdk-cli/internal/output/classify.go index 82803b9bb..fa5558b75 100644 --- a/zSDKs/sdk-cli/internal/output/classify.go +++ b/zSDKs/sdk-cli/internal/output/classify.go @@ -11,6 +11,8 @@ import ( "io" "net" "net/url" + "reflect" + "sort" "strings" "github.com/spf13/cobra" @@ -74,6 +76,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 { @@ -263,7 +266,13 @@ func Classify(cmd *cobra.Command, err error) Classification { } } - c.Message = redactedMessage(classificationMessage(bodyMap, errorObject, err, c.RawBody), rawBody, 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 } @@ -278,7 +287,7 @@ func redactErrorBody(cmd *cobra.Command, err error, body string) string { // 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, and fallback errors embed the raw body. +// 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 @@ -289,13 +298,104 @@ func redactedMessage(message, rawBody, redactedBody string) string { if isValidJSON(message) { return redactedBody } - return message + 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) + } + 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(), "openapi/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 { + var raw, redacted any + if json.Unmarshal([]byte(rawBody), &raw) != nil || json.Unmarshal([]byte(redactedBody), &redacted) != nil { + 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 +} + +func jsonScalarTexts(value any) []string { + switch typed := value.(type) { + case nil: + return nil + case string: + return []string{typed} + 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 redactedMessage(err.Error(), extractErrorBody(err), classification.RawBody) + return scrubMaskedValues(redactedMessage(err.Error(), extractErrorBody(err), classification.RawBody), classification.maskedValues) } func parseClassificationBody(raw string, c *Classification) (map[string]any, map[string]any) { diff --git a/zSDKs/sdk-cli/internal/output/output_test.go b/zSDKs/sdk-cli/internal/output/output_test.go index 9917bdf0c..83d1d5386 100644 --- a/zSDKs/sdk-cli/internal/output/output_test.go +++ b/zSDKs/sdk-cli/internal/output/output_test.go @@ -771,6 +771,14 @@ func TestRedactedMessageDropsMaskedValues(t *testing.T) { 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) + } } func TestStructuredErrorEnvelopeRedactsNonObjectBodyErrorText(t *testing.T) { From 5eb9a06d2504ee64443de3d53b4af9fc445b4d56 Mon Sep 17 00:00:00 2001 From: Tristan Cartledge Date: Tue, 24 Nov 2026 11:10:42 +1000 Subject: [PATCH 4/4] fix(cli): keep number spelling when masking values in error messages --- .../internal/output/classify.go.stmpl | 19 +++++++++++++++++-- .../internal/output/output_test.go.stmpl | 5 +++++ zSDKs/sdk-cli/.speakeasy/gen.lock | 4 ++-- zSDKs/sdk-cli/internal/output/classify.go | 19 +++++++++++++++++-- zSDKs/sdk-cli/internal/output/output_test.go | 5 +++++ 5 files changed, 46 insertions(+), 6 deletions(-) diff --git a/templates/templates/cli/auxiliary/internal/output/classify.go.stmpl b/templates/templates/cli/auxiliary/internal/output/classify.go.stmpl index 0918de682..6e1cca1cf 100644 --- a/templates/templates/cli/auxiliary/internal/output/classify.go.stmpl +++ b/templates/templates/cli/auxiliary/internal/output/classify.go.stmpl @@ -370,8 +370,9 @@ 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 { - var raw, redacted any - if json.Unmarshal([]byte(rawBody), &raw) != nil || json.Unmarshal([]byte(redactedBody), &redacted) != nil { + raw, rawOK := decodeJSONKeepingNumbers(rawBody) + redacted, redactedOK := decodeJSONKeepingNumbers(redactedBody) + if !rawOK || !redactedOK { return nil } var out []maskedBodyValue @@ -407,12 +408,26 @@ func maskedBodyValues(rawBody, redactedBody string) []maskedBodyValue { 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 { diff --git a/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl b/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl index 4318ba32a..e7fe335fe 100644 --- a/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl +++ b/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl @@ -756,6 +756,11 @@ func TestRedactedMessageDropsMaskedValues(t *testing.T) { 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) { diff --git a/zSDKs/sdk-cli/.speakeasy/gen.lock b/zSDKs/sdk-cli/.speakeasy/gen.lock index 8d1411cf8..86429be4d 100644 --- a/zSDKs/sdk-cli/.speakeasy/gen.lock +++ b/zSDKs/sdk-cli/.speakeasy/gen.lock @@ -274,7 +274,7 @@ trackedFiles: internal/output/binary.go: last_write_checksum: sha1:6fd77172cad1bd29dc9f157b931345f96a172223 internal/output/classify.go: - last_write_checksum: sha1:82f52ea41b7b4e604721cf4688550f7308f02258 + last_write_checksum: sha1:23015bf4e1fe7d0eb842306521d495ad3680940c internal/output/color.go: last_write_checksum: sha1:c6f41f9691f6209f480d153c15c3424d8ca5883d internal/output/errortable.go: @@ -290,7 +290,7 @@ trackedFiles: internal/output/output.go: last_write_checksum: sha1:f05fd1e8abf0921f0328fd53bd4b268698786845 internal/output/output_test.go: - last_write_checksum: sha1:93e9bc94488084c2c7b69a33cf28002def59192e + last_write_checksum: sha1:2fb5c79e9c9156c3e94cb8e8600fc4cc8507d110 internal/output/outputitems.go: last_write_checksum: sha1:d327eee8d9a395821fef201257e033bae50cda51 internal/output/paginated.go: diff --git a/zSDKs/sdk-cli/internal/output/classify.go b/zSDKs/sdk-cli/internal/output/classify.go index fa5558b75..d67b31b12 100644 --- a/zSDKs/sdk-cli/internal/output/classify.go +++ b/zSDKs/sdk-cli/internal/output/classify.go @@ -332,8 +332,9 @@ 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 { - var raw, redacted any - if json.Unmarshal([]byte(rawBody), &raw) != nil || json.Unmarshal([]byte(redactedBody), &redacted) != nil { + raw, rawOK := decodeJSONKeepingNumbers(rawBody) + redacted, redactedOK := decodeJSONKeepingNumbers(redactedBody) + if !rawOK || !redactedOK { return nil } var out []maskedBodyValue @@ -369,12 +370,26 @@ func maskedBodyValues(rawBody, redactedBody string) []maskedBodyValue { 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 { diff --git a/zSDKs/sdk-cli/internal/output/output_test.go b/zSDKs/sdk-cli/internal/output/output_test.go index 83d1d5386..c08e1a21f 100644 --- a/zSDKs/sdk-cli/internal/output/output_test.go +++ b/zSDKs/sdk-cli/internal/output/output_test.go @@ -779,6 +779,11 @@ func TestRedactedMessageDropsMaskedValues(t *testing.T) { 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) {