Skip to content

fix(cli): mask sensitive values in API error output - #232

Open
TristanSpeakEasy wants to merge 5 commits into
mainfrom
fix/cli-redact-error-bodies
Open

TristanSpeakEasy wants to merge 5 commits into
mainfrom
fix/cli-redact-error-bodies

Conversation

@TristanSpeakEasy

@TristanSpeakEasy TristanSpeakEasy commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Why

--debug masks values the API description marks sensitive (x-speakeasy-param-sensitive, format: password) when it logs a response body. The normal error output did not: when an API error body echoed a sensitive value, it was printed as-is in the pretty Details: block, the error message line, and the -o json / agent-mode error envelope.

What changed

  • Classify now passes the error body through the SDK's redact.ResponseBody, the same masking --debug uses. The operation comes from the response's request context, or from the command when the error carries no HTTP response (for example typed error models that keep only their schema fields). Operations split per request content type generate one SDK method per variant, and the masking rules are keyed by that method's ID, so such commands now carry a speakeasy_sdk_operation annotation that the lookup prefers over the original speakeasy_operation. Other commands are unchanged.
  • The error message and the envelope error text are held to the same redaction when they fall back to the error's own text: a raw body embedded in that text is replaced by the masked body, a typed error model's JSON rendering is replaced by the masked body, and any other occurrence of a value that masking replaced is masked too (for example a typed error whose Error() returns a single sensitive message field).
  • When the error has no response body but is a generated error model, the model's own fields are checked against the operation's sensitive fields for that last step.
  • Generated only when the document has sensitive values (hasAnyRedactGraphs); other CLIs are unchanged.
  • Successful command output is unchanged and still shows decoded values.
  • Like --debug, a body that cannot be parsed for an operation with sensitive response values is masked as a whole.
  • Test fixtures (CLI-only): cliSensitiveResponseGet gains a 400 response that reuses its sensitive schema; cliSensitiveErrorMessageGet returns a 400 whose x-speakeasy-error-message field is sensitive; cliSensitiveSplitResponsePost is split into form and multipart methods and returns a sensitive 400.

Testing

  • New TestErrorOutputRedactsSensitiveResponseFields (pretty, -o json, agent mode): a 400 echoing a sensitive value never shows it, while the unmarked sibling stays readable. It failed in all three modes before the change.
  • New TestRedactedMessageDropsMaskedValues for the message fallback cases, including a message that is a masked field and values under a masked subtree.
  • New TestErrorOutputRedactsSensitiveErrorMessageField (pretty, -o json, agent mode) and TestErrorOutputRedactsSensitiveFieldsOfSplitOperation (both split commands). Each fails with its part of the fix removed.
  • TARGET=review make test-cli, TARGET=primary make test-cli, make check-template-cli, npm run format, go test ./pkg/generate/snapshots/ -run TestSnapCLI and git diff --check pass.

Public-safety check

  • This change contains no credentials, customer documents, private repository URLs, private filesystem paths, or unredacted private logs.
  • Title, body, comments, and commit messages name no customers or customer-derived identifiers, private paths or trackers, or workflow provenance, and are understandable without private context (.claude/skills/public-repo-communication/SKILL.md).
  • Generated fixtures and review SDK changes are public-safe.
  • I reviewed git diff --check.

Summary by cubic

Masks API-marked sensitive values in CLI error output, matching --debug. Previously, echoed values could appear in the Details: block, fallback error messages, and -o json or agent-mode envelopes; successful output is unchanged.

  • Redacts error bodies using the operation's schema, including commands for operations split by request content type.
  • Also scrubs fallback error text and machine-readable error fields, preserving numeric spelling.
  • Only generated CLIs with sensitive values are affected.

Written for commit 2fb4fb2. Summary will update on new commits.

View guided diff Turn on auto-fix

@TristanSpeakEasy
TristanSpeakEasy requested a review from a team as a code owner November 23, 2026 02:28

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

All reported issues were addressed across 8 files

Shadow auto-approve: would not auto-approve because issues were found.

View guided diff | Turn on auto-fix | Re-trigger cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

All reported issues were addressed across 9 files (changes from recent commits).

Shadow auto-approve: would not auto-approve because issues were found.

View guided diff | Turn on auto-fix | Re-trigger cubic

@2ynn 2ynn left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Two remaining paths where a schema-marked sensitive value can still reach error output; details inline.

Comment on lines +316 to +326
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 message

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could redactedMessage also cover a typed error whose Error() returns a single message field rather than JSON? templateErrorMessage generates exactly that for a field marked x-speakeasy-error-message (or a nested/inferred message path).

To reproduce, give an operation a typed JSON 400 response with this schema:

type: object
required: [detail, name]
properties:
  detail:
    type: string
    x-speakeasy-error-message: true
    x-speakeasy-param-sensitive: true
  name:
    type: string

Have a stub server return HTTP 400 with Content-Type: application/json and {"detail":"secret-value","name":"visible"}, then invoke that command with --agent-mode.

  • Expected: detail is masked, name is kept, and secret-value appears in no output field.
  • Actual: the body is masked to {"detail":"(sensitive)","name":"visible"}, but the typed error's Error() returns secret-value. classificationMessage falls back to err.Error() because the masked body has no message/error key, and this helper returns it unchanged because it is neither the whole raw body nor valid JSON.

The leaked value then lands in:

Agent mode always takes this path (shouldClassifyError); pretty and -o json take it when classified errors are enabled. The compatibility rendering of an object-shaped body prints the masked RawBody and is not affected. The final credential scrub does not help either, since a schema-marked response value is not a registered credential.

One option that does not depend on how Error() is shaped: collect the string leaves that differ between the raw and redacted bodies, and replace each of them in the fallback message. Deriving the message from the redacted body would also work. Either way, a regression with the schema above in agent mode and in classified pretty/JSON output would cover it; TestRedactedMessageDropsMaskedValues currently has no case where the message is a sensitive leaf.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 14be773. After the existing body-substring and JSON checks, redactedMessage now collects every scalar value that masking replaced (walking the raw and masked bodies together, including everything under a subtree masked as a whole). It then replaces each one wherever it appears in the message, longest first, so this no longer depends on how Error() is shaped. The envelope error text goes through the same step. One more case surfaced while reproducing: in SDKs whose typed errors carry no HTTP metadata, the CLI never sees a response body, so there is nothing to compare. For that case the generated error model itself is encoded and masked against the operation to find the values to scrub. Classification is unchanged. Regression: cliSensitiveErrorMessageGet uses your schema, and TestErrorOutputRedactsSensitiveErrorMessageField covers pretty, -o json and agent mode. TestRedactedMessageDropsMaskedValues gains a sensitive-leaf case. Both fail with the change removed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks, field-level masking now covers the detail example. One case is still open: when the response schema is itself marked x-speakeasy-param-sensitive, redact.ResponseBody returns the bare text (sensitive). That isn't JSON, so maskedBodyValues finds nothing to replace, and redactedMessage returns the typed error's Error() text unchanged.

To reproduce, move x-speakeasy-param-sensitive: true from detail up to CliSensitiveErrorMessage, keep detail as x-speakeasy-error-message, and return {"detail":"secret-value","name":"visible"} with HTTP 400. The body prints as (sensitive), but message and the envelope's error still show secret-value.

Could redactedMessage treat a redacted body that changed and is no longer valid JSON as fully masked, and return it as the message? The errorModelJSON branch at L284-L286 needs the same handling.

Comment on lines +304 to +307
if redact.Operation(ctx) == "" && cmd != nil {
ctx = redact.WithOperation(ctx, cmd.Annotations["speakeasy_operation"])
}
return string(redact.ResponseBody(ctx, contentType, []byte(body)))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

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

For an in-band error with no HTTP response:

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@AshGodfrey AshGodfrey left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The body masking looks right. Two paths still print an unmasked value at 27ea886, both already raised in the open review threads:

  • Single-field error messages. A typed error whose Error() returns one message field (templateErrorMessage) is passed through by redactedMessage when that field is the sensitive one: the text neither contains the raw body nor parses as JSON. The value then shows in the message line and in the envelope's error.
  • Fallback operation lookup. speakeasy_operation holds OriginalID, while the redact graphs are keyed by op.ID. They differ for operations split per request content type, so an error with no HTTP response (an in-band stream error, for example) misses the graph and its body is returned unmasked.

For the first, deriving the message from the masked body whenever masking changed something would be sturdier than matching on the error text.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

All reported issues were addressed across 8 files (changes from recent commits).

Shadow auto-approve: would not auto-approve because issues were found.
Tip: Review your code locally with the cubic CLI to iterate faster.

View guided diff | Turn on auto-fix | Re-trigger cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

All reported issues were addressed across 5 files (changes from recent commits).

Shadow auto-approve: would not auto-approve because issues were found.

View guided diff | Turn on auto-fix | Re-trigger cubic

…bodies

# Conflicts:
#	zSDKs/sdk-cli/.speakeasy/gen.lock
Comment on lines +342 to +345
func scrubMaskedValues(text string, masked []maskedBodyValue) string {
for _, value := range masked {
text = strings.ReplaceAll(text, value.raw, value.redacted)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

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

@2ynn
2ynn disabled auto-merge November 24, 2026 18:51
@2ynn

2ynn commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

I've approved this to unblock the PR. These three open review comments still deserve attention:

  • Whole-body masking: when the entire response schema is sensitive, the body is masked but the typed error message can still expose sensitive values.
  • Declared intent commands: errors without an HTTP response can miss the redaction lookup for split operations because these commands lack the SDK operation annotation.
  • Repeated replacements: scrubbing can replace text inside masks inserted earlier, causing excessive message growth and potentially exhausting memory.

@TristanSpeakEasy I trust your judgement on how best to handle these, including whether to address them here or in a follow-up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants