Repository navigation
fix(cli): mask sensitive values in API error output #232
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
cd330b9
27ea886
14be773
5eb9a06
2fb4fb2
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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 |
|---|---|---|
|
|
@@ -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), | ||
|
TristanSpeakEasy marked this conversation as resolved.
Resolved
|
||
| 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))) | ||
|
Comment on lines
+313
to
+320
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
The two differ when an operation is split into request serialization variants (operations.go#L75-L94). For example, For an in-band error with no HTTP response: raw := `{"detail":"secret-value"}`
err := &StreamEventError{Body: raw}
got := redactErrorBody(cmd, err, raw)
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.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The |
||
| {{- 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Each Suggestion: remove duplicate values, build a single |
||
| 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{} | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.