Repository navigation
fix(cli): mask sensitive values in API error output - #232
TristanSpeakEasy wants to merge 5 commits into
Conversation
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Two remaining paths where a schema-marked sensitive value can still reach error output; details inline.
| 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 |
There was a problem hiding this comment.
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: stringHave 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:
detailis masked,nameis kept, andsecret-valueappears in no output field. - Actual: the body is masked to
{"detail":"(sensitive)","name":"visible"}, but the typed error'sError()returnssecret-value.classificationMessagefalls back toerr.Error()because the masked body has nomessage/errorkey, and this helper returns it unchanged because it is neither the whole raw body nor valid JSON.
The leaked value then lands in:
- the classified envelope's
message(output.go.stmpl#L817) - the pretty headline
Error (<type>): secret-value(output.go.stmpl#L753)
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| if redact.Operation(ctx) == "" && cmd != nil { | ||
| ctx = redact.WithOperation(ctx, cmd.Annotations["speakeasy_operation"]) | ||
| } | ||
| return string(redact.ResponseBody(ctx, contentType, []byte(body))) |
There was a problem hiding this comment.
Could this fallback use the generated SDK operation ID rather than the command's speakeasy_operation annotation?
- The annotation stores
OriginalID(opcmd.go.stmpl#L76). - The redaction graphs are keyed by
op.ID(redact.ts#L35-L44), which is also what the SDK puts on the request context (method.go.stmpl#L174).
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:
gotis(sensitive), because the stream response graph masks the whole stream when it contains a sensitive value. - Actual: the lookup on
createWidgetfinds no graph, soredact.ResponseBodyreturns the original JSON withsecret-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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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 byredactedMessagewhen 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'serror. - Fallback operation lookup.
speakeasy_operationholdsOriginalID, while the redact graphs are keyed byop.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.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
| func scrubMaskedValues(text string, masked []maskedBodyValue) string { | ||
| for _, value := range masked { | ||
| text = strings.ReplaceAll(text, value.raw, value.redacted) | ||
| } |
There was a problem hiding this comment.
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.
|
I've approved this to unblock the PR. These three open review comments still deserve attention:
@TristanSpeakEasy I trust your judgement on how best to handle these, including whether to address them here or in a follow-up. |
Why
--debugmasks 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 prettyDetails:block, the error message line, and the-o json/ agent-mode error envelope.What changed
Classifynow passes the error body through the SDK'sredact.ResponseBody, the same masking--debuguses. 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 aspeakeasy_sdk_operationannotation that the lookup prefers over the originalspeakeasy_operation. Other commands are unchanged.errortext 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 whoseError()returns a single sensitive message field).hasAnyRedactGraphs); other CLIs are unchanged.--debug, a body that cannot be parsed for an operation with sensitive response values is masked as a whole.cliSensitiveResponseGetgains a400response that reuses its sensitive schema;cliSensitiveErrorMessageGetreturns a400whosex-speakeasy-error-messagefield is sensitive;cliSensitiveSplitResponsePostis split into form and multipart methods and returns a sensitive400.Testing
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.TestRedactedMessageDropsMaskedValuesfor the message fallback cases, including a message that is a masked field and values under a masked subtree.TestErrorOutputRedactsSensitiveErrorMessageField(pretty,-o json, agent mode) andTestErrorOutputRedactsSensitiveFieldsOfSplitOperation(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 TestSnapCLIandgit diff --checkpass.Public-safety check
.claude/skills/public-repo-communication/SKILL.md).git diff --check.Summary by cubic
Masks API-marked sensitive values in CLI error output, matching
--debug. Previously, echoed values could appear in theDetails:block, fallback error messages, and-o jsonor agent-mode envelopes; successful output is unchanged.errorfields, preserving numeric spelling.Written for commit 2fb4fb2. Summary will update on new commits.