Skip to content

feat(protocol): shape errors by the request's protocol (#757, #758) - #790

Merged
scttfrdmn merged 1 commit into
mainfrom
feat/757-758-protocol
Sep 10, 2026
Merged

scttfrdmn merged 1 commit into
mainfrom
feat/757-758-protocol

Conversation

@scttfrdmn

Copy link
Copy Markdown
Owner

Second of four PRs for v0.110.0. Records the wire protocol a caller used and shapes errors to follow it, closing the error half of #757 and all of #758. CloudWatch's successful responses are still XML on every protocol — that is #785, the next PR.

Closes #758

The problem, measured

CloudWatch's service shape carries aws.protocols#awsQuery, aws.protocols#awsJson1_0, smithy.protocols#rpcv2Cbor and aws.protocols#awsQueryCompatible at once, and its clients disagree about which to use. Substrate classified error protocol per service, so one answer went to all three. Measured against a main build, a refused SetAlarmState:

Client Before After
aws-sdk-go-v2 v1.47.0 / cloudwatch v1.72.0 deserialization failed, unexpected minor value 28 — not an APIError at all InvalidParameterValue: AlarmName is required, deserialized into types.InvalidParameterValueException
AWS CLI 2.36 / boto3 An error occurred (400) — the stringified status, with the XML leaking into the message botocore.errorfactory.InvalidParameterValueException, code InvalidParameterValue
raw Query client correct byte-identical

unexpected minor value 28 is the < of <ErrorResponse> (0x3C — major 1, additional info 28, which is reserved) being read as a CBOR head.

What changed

emulator/protocol.go (new) — exported WireProtocol (WireQuery as the zero value, WireJSONRPC, WireRPCV2CBOR) and a pure, total detectWireProtocol. Signals in the order a conformant client makes them available: the required Smithy-Protocol: rpc-v2-cbor header, then a /service/…/operation/… path with a CBOR Content-Type (a prefix before /service is permitted, so the tail decides), then X-Amz-Target, then application/x-amz-json. Also detectQueryMode and rpcV2CBORTargetConflict.

emulator/types.go / parser.go — AWSRequest gains exported Protocol WireProtocol and QueryMode bool, set during parsing so authorization, fault injection, the plugin and the error serializer all agree about what arrived. Exported so a third-party plugin can serve CBOR too. Additive: WireQuery is the zero value, so an in-process AWSRequest built by hand still reads as Query.

emulator/error_protocol.go — errProtoRPCV2CBOR, an errorWireContext carrying the protocol/service/query-mode the two newer arms need, and errorProtocolForRequest. The set of services the request may reclassify is enumerated, one member:

var multiProtocolServices = map[string]bool{"monitoring": true}

Deciding by Content-Type is exactly what #392 removed — a REST-JSON service sends a bare application/json, indistinguishable from a plain JSON body — so letting the request speak for a single-protocol service would reclassify Lambda's errors as Query and undo that fix. TestErrorProtocolForRequest pins the asymmetry in both directions (lambda, s3, ec2, iam are not reclassified by a CBOR or JSON-target header).

emulator/cloudwatch_errors.go (new) — CloudWatch's 17 error shapes, each read off codegen/sdk-codegen/aws-models/cloudwatch.json in aws-sdk-go-v2. The Query code (aws.protocols#awsQueryError.code) maps to the shape ID, the fault (smithy.api#error), the status (smithy.api#httpError) and the casing of the message member, which the model spells Message on InternalServiceFault and message on InvalidParameterValueException. A CBOR client deserializes by exact member name, so guessing loses the message.

An unmodeled code passes through unqualified. That covers every code the pipeline itself raises — AccessDenied, InternalFailure, InvalidAction, InvalidClientTokenId, ThrottlingException, UnknownOperationException — and is safe because a reference client sanitizes __type by taking the text after #, so an unqualified value yields the same discriminant a qualified one would.

The query-compatibility bridge. X-Amzn-Query-Mode: true was read nowhere; it now produces x-amzn-query-error: <Code>;Sender|Receiver on both the CBOR and the JSON-RPC arm (awsQueryCompatible applies to awsJson1_0 too). With both halves in place the CLI raises the typed exception from __type and displays the Query code from the header, which is exactly the split the trait exists to bridge.

The malformed combination is refused. A request declaring Smithy-Protocol: rpc-v2-cbor and carrying a target header gets a shaped 400 rather than http.Error's plain text. Substrate routes on X-Amz-Target before anything else, so honoring it would mean invoking whatever the target named while answering in the serialization the path asked for. The spec mandates the rejection without naming a code; substrate answers SerializationException and the doc comment says that this is substrate's choice.

monitoring leaves server.go's query→JSON body reconstruction. It was already a no-op (a CBOR request has no form body, so req.Params is empty and the guard never fires) but it said the opposite of what #785 needs.

#758 — sso is JSON RPC, not REST-JSON. The plugin emulates sso-admin: it dispatches on X-Amz-Target with the SWBExternalService prefix, and sso-admin's model is "protocol": "json", "jsonVersion": "1.1". Both consequences of reading it as the unrelated sso service are fixed — errors move from an x-amzn-errortype header botocore's JSON parser never reads to the body's __type, and successes move from application/json to application/x-amz-json-1.1. No test asserted either value, which is how both survived #561's routing fix.

Provenance

  • The shape ID / Query code mapping, per-shape message casing, fault and status come from the AWS-published Smithy model in aws-sdk-go-v2, not the CloudWatch API reference, which documents only the Query codes (InvalidParameterValue, never InvalidParameterValueException) and nothing about member casing.
  • queryError.httpResponseCode equals httpError for every CloudWatch shape, so there is no status divergence to reconcile. The plan assumed there might be; there is not. (The protocol test suite does construct one, but only in a synthetic service.)
  • X-Amzn-Query-Mode / x-amzn-query-error are normative but appear in neither the rpcv2Cbor spec page nor the awsQueryCompatible trait docs — only in smithy-aws-protocol-tests/model/rpcv2Cbor/query-compatible.smithy. Both reference clients send the request header, which is the corroboration.
  • ThrottlingException is 400 for CloudWatch, not 429 (CommonErrors.html), and takes the pass-through path.
  • The SerializationException code for the malformed-request refusal is substrate's choice; the spec mandates the rejection and names no code.

Compatibility

  • CloudWatch error bodies differ by client. CBOR clients get CBOR, JSON-RPC clients get JSON with the shape ID in __type, and a raw Query client is byte-identical. Verified below.
  • sso error bodies change from REST-JSON to JSON-RPC, and sso success Content-Type from application/json to application/x-amz-json-1.1.
  • AWSRequest gains two exported fields. Additive; a third-party plugin compiles unchanged and reads as Query without setting them.
  • accessDeniedCodeFor("monitoring", …) stays AccessDenied on every protocol. No query-protocol service models an access-denied shape, CloudWatch's model declares nothing to contradict the observed value, and a code that changed with the caller's serialization would be harder to assert against. The doc comment says so.

Verification

Both toolchains, each command's exit code read separately:

gofmt -l .                            clean
go build ./... ; go vet ./...         clean
golangci-lint run ./...               0 issues
make test                             (go1.27.1)  PASS
GOTOOLCHAIN=go1.26.6 make test        PASS
GOTOOLCHAIN=go1.26.6 make coverage    emulator 83.5%, total 83.0%  (unchanged)
make docs-reference-check              PASS  (sso row REST/JSON -> JSON)
make docs-versions                     PASS
npm --prefix docs run build            PASS, anchor diff empty
go vet -C test/e2e ./... && go test -C test/e2e ./...   PASS

Live proof, substrate server --address :4678, before-binary built from a detached worktree at main:

BEFORE  Go SDK   <-- text/xml <ErrorResponse>...
                 deserialization failed, unexpected minor value 28
                 NOT an APIError — the SDK could not read the error at all
BEFORE  AWS CLI  An error occurred (400) ... <ErrorResponse>...

AFTER   Go SDK   <-- Content-Type: application/cbor
                     Smithy-Protocol: rpc-v2-cbor
                     X-Amzn-Query-Error: InvalidParameterValue;Sender
                     a2 66 __type 78 37 com.amazonaws.cloudwatch#InvalidParameterValueException
                           67 message 75 AlarmName is required
                 APIError code="InvalidParameterValue" fault=client
                 deserialized as the MODELED shape InvalidParameterValueException
AFTER   AWS CLI  X-Amzn-Errortype: com.amazonaws.cloudwatch#InvalidParameterValueException
                 X-Amzn-Query-Error: InvalidParameterValue;Sender
                 botocore.errorfactory.InvalidParameterValueException
                 An error occurred (InvalidParameterValue) ... AlarmName is required
AFTER   Query    byte-identical to BEFORE

Also verified live: the rpc-v2-cbor + X-Amz-Target combination answers a CBOR SerializationException 400 with Smithy-Protocol echoed; sso errors answer application/x-amz-json-1.1 with __type in the body; sso successes answer the versioned Content-Type; and a CloudWatch Query ListMetrics is unchanged.

Tests

emulator/protocol_test.go — 13 classification cases built from the requests the three real clients actually send (captured from a running emulator, not invented), plus the nil-request totality property, the zero-value property, query-mode parsing, the target-conflict check on both header spellings, and end-to-end assertions that ParseAWSRequest records both fields.

emulator/cloudwatch_errors_test.go — all 17 shapes with their four model facts restated, a closed-table assertion so a row added without a model behind it fails, the fallback for all seven pipeline codes, the #392 non-reclassification guard, and the CBOR/JSON error documents including the members that must not be present.


Part of #785 / milestone v0.110.0. Next: PR 3/4 makes CloudWatch's success responses follow the protocol too.

Record the wire protocol a caller used on AWSRequest and let the error
serializer follow it, for the one service whose model declares several.

CloudWatch carries awsQuery, awsJson1_0, rpcv2Cbor and awsQueryCompatible
on one service shape, and its clients disagree about which to send. Before
this change a refused SetAlarmState reached aws-sdk-go-v2 as
"deserialization failed, unexpected minor value 28" and the AWS CLI as
"An error occurred (400)"; both now report InvalidParameterValue, and the
Go SDK deserializes the modeled InvalidParameterValueException.

Which services may be reclassified by their caller is an enumerated set of
one, not a Content-Type sniff — deciding by Content-Type is what #392
removed, and letting the request speak for a single-protocol service would
reclassify Lambda's REST-JSON errors as Query.

cloudwatch_errors.go holds CloudWatch's 17 error shapes read off the
AWS-published Smithy model: Query code to shape ID, fault, status, and the
casing of the message member, which the model spells Message on some shapes
and message on others. X-Amzn-Query-Mode is honored with an
x-amzn-query-error response header. A request declaring rpc-v2-cbor and a
target header is refused with a shaped SerializationException.

sso is JSON 1.1, not REST-JSON: the plugin emulates sso-admin, and both its
error shape and its success Content-Type followed from reading it as the
unrelated sso service.

Closes #758
@codecov

codecov Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.63636% with 7 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
emulator/server.go 33.33% 6 Missing ⚠️
emulator/error_protocol.go 97.61% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@scttfrdmn scttfrdmn added this to the v0.110.0 milestone Sep 10, 2026
@scttfrdmn
scttfrdmn merged commit ae8d706 into main Sep 10, 2026
17 checks passed
@scttfrdmn
scttfrdmn deleted the feat/757-758-protocol branch September 10, 2026 23:57
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.

1 participant