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/agentmode.go.stmpl b/templates/templates/cli/auxiliary/internal/output/agentmode.go.stmpl index 8110cda4f..70a361fc5 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 5c816959b..6e1cca1cf 100644 --- a/templates/templates/cli/auxiliary/internal/output/classify.go.stmpl +++ b/templates/templates/cli/auxiliary/internal/output/classify.go.stmpl @@ -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" ) @@ -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 { @@ -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), Origin: ErrorOriginAPI, } var origin interface{ ErrorOrigin() ErrorOrigin } @@ -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))) + {{- 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) + } + 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{} diff --git a/templates/templates/cli/auxiliary/internal/output/output.go.stmpl b/templates/templates/cli/auxiliary/internal/output/output.go.stmpl index a2adfa4f0..fbb08aff7 100644 --- a/templates/templates/cli/auxiliary/internal/output/output.go.stmpl +++ b/templates/templates/cli/auxiliary/internal/output/output.go.stmpl @@ -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 } @@ -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 } @@ -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)) } @@ -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, @@ -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/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl b/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl index 192103a79..4fff5372d 100644 --- a/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl +++ b/templates/templates/cli/auxiliary/internal/output/output_test.go.stmpl @@ -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`) 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 c04141a7d..860826e06 100644 --- a/templates/templates/cli/tests/primary/diagnostics_test.go.stmpl +++ b/templates/templates/cli/tests/primary/diagnostics_test.go.stmpl @@ -666,6 +666,71 @@ 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") + }) + } +} + +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 645b47ba7..0efd4df04 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,64 @@ paths: application/json: schema: $ref: "#/components/schemas/CliSensitiveResponse" + "400": + description: Rejected request echoing the sensitive field + content: + 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: @@ -562,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 0a5f3e9d7..e21bfa326 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:ffd19c97443e3b2bb46ad202c147a84427741df2 + last_write_checksum: sha1:82dd548507c3b764e47c04d32aa9c4c8b1ba5cd3 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:cc4f38eeacdf495b1ae8b35a84a85f11a073cc5f + last_write_checksum: sha1:23015bf4e1fe7d0eb842306521d495ad3680940c internal/output/color.go: last_write_checksum: sha1:6aacc252a32e7eea5821058a68cc43c83a73dafd 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:617373186e1b32165d572ce7fb626c50c6c76946 + last_write_checksum: sha1:ffb45941e7afb2ff2ff233d691a324ebffb85f2e internal/output/output_test.go: - last_write_checksum: sha1:33584d773c2e520c16a71c8d1e50a4cb7f5788e9 + last_write_checksum: sha1:c4b9c4988a897620c5ac2f824d1b94598e9dd9f3 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 75dbebbfd..2cefbe5ab 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 04d9dfdde..d67b31b12 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 { @@ -174,9 +177,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 +266,153 @@ 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 { + 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 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) + } + 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 { + 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{} diff --git a/zSDKs/sdk-cli/internal/output/output.go b/zSDKs/sdk-cli/internal/output/output.go index 8834f62aa..2e655a326 100644 --- a/zSDKs/sdk-cli/internal/output/output.go +++ b/zSDKs/sdk-cli/internal/output/output.go @@ -688,7 +688,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 } @@ -700,7 +700,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 } @@ -731,7 +731,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)) } @@ -774,7 +774,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, @@ -792,7 +792,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 540436762..70c0bac26 100644 --- a/zSDKs/sdk-cli/internal/output/output_test.go +++ b/zSDKs/sdk-cli/internal/output/output_test.go @@ -776,6 +776,51 @@ 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) + } + }) + } + 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`)