Skip to content

fix(errors): serialize errors in each service's wire protocol (#392) - #415

Merged
scttfrdmn merged 3 commits into
mainfrom
fix/392-error-codes
Jul 31, 2026
Merged

scttfrdmn merged 3 commits into
mainfrom
fix/392-error-codes

Conversation

@scttfrdmn

Copy link
Copy Markdown
Owner

Closes #392

What the issue reported vs. what was actually wrong

The issue describes four independent per-service typos. Three of the four were one defect in the server's shared writeError.

writeError emitted a Code member for every JSON service. botocore's BaseJSONParser._do_error_parse does:

code = body.get('__type', response_code and str(response_code))

It reads __type and falls back to the stringified HTTP status. It never reads Code. So SSM's ParameterNotFound — which the plugin was already setting correctly — was discarded on the wire, and the caller saw Error.Code == "404". Every except ClientError branch comparing against a symbolic code silently stopped matching. This affected all ~30 JSON-RPC services, not just the one reported.

Lambda was a second and worse case. Lambda is REST-JSON but sends Content-Type: application/json, which fails the application/x-amz-json prefix test — so its errors were emitted as XML, a shape its SDK cannot parse at all.

The fix

The protocol cannot be sniffed from the request:

  • IAM sends x-amz-json-1.1 inbound but answers errors in XML.
  • Lambda's inbound application/json is indistinguishable from a plain JSON body.

So the service name selects it. emulator/error_protocol.go adds one dispatch layer over three shapes:

Protocol Where the code goes Parser that reads it
Query / ec2 / REST-XML <ErrorResponse><Error><Code> QueryParser, BaseXMLResponseParser
JSON-RPC 1.0/1.1 body __type BaseJSONParser
REST-JSON x-amzn-errortype header RestJSONParser._inject_error_code

Every entry in the classification table is the protocol field of that service's model in botocore/data/<service>/<version>/service-2.json — the same value that selects the SDK's parser, so the table and the parser cannot disagree. Services not yet classified keep the previous Content-Type sniff, so this adds no behavior change for them.

The JSON bodies retain Code/Message alongside __type/message so callers already reading Code keep working.

The other three, all verified against AWS docs

  • IAM — wire codes drop the Exception suffix that the API model's shape names carry: NoSuchEntity, EntityAlreadyExists, MalformedPolicyDocument, DeleteConflict, LimitExceeded (44 call sites). This is not a blanket suffix-strip: ValidationError and AccessDeniedException are already correct per IAM's CommonErrors, and Lambda genuinely does use ResourceNotFoundException on the wire. Neither service's spelling can be inferred from the other, which is why each was checked individually.
  • S3 — GetObject/HeadObject went straight to the object lookup, so a GET against a bucket that was never created reported NoSuchKey. That conflates two conditions a caller must distinguish: a deleted bucket (fatal misconfiguration) from an unwritten object (ordinary cache miss). New bucketMissingResponse helper reserves its error return for a state-store failure, so that is propagated rather than reported as a missing bucket.
  • docs/services.md — auditing my own table against botocore turned up two errors in the generator's hand-maintained protocol column: ACM was listed as Query (it is JSON-RPC) and RAM as JSON (it is REST-JSON). Both corrected; the matrix is regenerated.

Tests

emulator/error_protocol_test.go, 13 tests. The ones that matter most pin the exact regressions:

  • TestJSONRPCError_CarriesTypeMember asserts __type == "ParameterNotFound" and != "404" — the status must never be the thing a caller matches on.
  • TestRESTJSONError_IsNotXML asserts a Lambda error body contains no <ErrorResponse.
  • TestIAMError_DropsExceptionSuffix pins NoSuchEntity against API_GetRole.html.
  • TestS3GetObject_MissingKeyInExistingBucketIsNoSuchKey is the guard on the other side — the bucket fix must not turn every miss into NoSuchBucket.
  • TestErrorProtocolFor_Classification pins each protocol per service, including the nine JSON-RPC services whose ...Gateway/...Service target prefixes make them look REST-shaped, plus both fallback branches.

Three IAM test assertions changed: they had encoded the bug, asserting the old ...Exception spellings.

Gates

go build ✅ · go vet ✅ · golangci-lint run ./... 0 issues ✅ · make test (race) ✅ · test/e2e ✅ · make docs-reference-check ✅ · make scan-fs 0 vulns ✅

errorProtocolFor is at 100% coverage. The residual uncovered lines are the json.Marshal/xml.Marshal error guards, unreachable for map[string]string and all-string structs; they exist so writeError's http.Error fallback stays reachable.

Reported as four per-service typos; three were one defect in the server's
shared error writer.

writeError emitted a "Code" member for every JSON service. botocore's
BaseJSONParser._do_error_parse reads "__type" and falls back to the
stringified HTTP status -- it never reads "Code". SSM's already-correct
ParameterNotFound was therefore discarded and callers saw
Error.Code == "404", silently defeating every `except ClientError` branch
that compares against a symbolic code. That affected all ~30 JSON-RPC
services, not just the one reported.

Lambda was worse: it is REST-JSON but sends Content-Type application/json,
which failed the "application/x-amz-json" prefix test, so its errors were
emitted as XML -- a shape its SDK cannot parse at all.

The protocol cannot be sniffed from the request. IAM sends x-amz-json-1.1
inbound yet answers errors in XML, and Lambda's inbound application/json is
indistinguishable from a plain JSON body. So the service name now selects
it, via a table whose every entry is the "protocol" field of that service's
model in botocore/data -- the same value that picks the SDK's parser.
Unclassified services keep the old Content-Type sniff.

Also fixed, from the same issue:

- IAM wire codes drop the Exception suffix that the API model's shape names
  carry: NoSuchEntity, EntityAlreadyExists, MalformedPolicyDocument,
  DeleteConflict, LimitExceeded. Not a blanket rule -- ValidationError and
  AccessDeniedException were already right per IAM's CommonErrors, and
  Lambda genuinely uses ResourceNotFoundException, so neither service's
  spelling can be inferred from the other.
- S3 GetObject/HeadObject report NoSuchBucket for a missing bucket instead
  of NoSuchKey, which conflated a deleted bucket with an unwritten object.
- The service reference had ACM as Query and RAM as JSON; both were wrong in
  the opposite direction (ACM is JSON-RPC, RAM is REST-JSON).

Verified against the AWS API references and botocore's parsers.py rather
than inferred, since a misclassification reproduces exactly the
wrong-wire-shape bug this fixes.
@scttfrdmn scttfrdmn added this to the v0.78.0 milestone Jul 31, 2026
@scttfrdmn scttfrdmn added type: bug Something is not working correctly area: iam Issues relating to the iam component area: s3 Issues relating to the s3 component labels Jul 31, 2026
@codecov

codecov Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.73554% with 10 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
emulator/error_protocol.go 87.50% 3 Missing and 3 partials ⚠️
emulator/server.go 71.42% 3 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

…ath (#392)

The rename from NoSuchEntityException to NoSuchEntity touched 25 branches but
only 3 had a test asserting the code. An untested rename is the same silent
failure #392 exists to remove: the response still looks like an error, so a
test that checks only the HTTP status stays green while the SDK's typed
exception never fires.

Drives all 22 previously-untested branches through the API — tagging, inline
policies, permissions boundaries, instance profiles — asserting the exact Code
string SDKs map to a typed exception. Codes verified against the IAM API
reference (TagUser, DeleteInstanceProfile): NoSuchEntity 404, DeleteConflict
409, EntityAlreadyExists 409, MalformedPolicyDocument 400.

Also asserts a state-store failure in S3's bucket lookup surfaces as 500 rather
than NoSuchBucket. Those are opposite signals — NoSuchBucket tells a caller to
stop retrying, a store failure is transient — so reporting one for the other
would send a consumer down a permanent-failure path over a blip.

newS3TestServer gains a state-injectable variant so both share one setup path.

Patch coverage 66.94% -> 93.38%; the remainder is marshal-failure branches on
map[string]string, which cannot fail.
@scttfrdmn
scttfrdmn merged commit 611446f into main Jul 31, 2026
15 checks passed
scttfrdmn added a commit that referenced this pull request Jul 31, 2026
The merge took this branch's coverage matrix, which predates #415's correction
of RAM's protocol from JSON to REST/JSON. Regenerated from the plugin registry,
which is what docs-reference-check compares against.
scttfrdmn added a commit that referenced this pull request Jul 31, 2026
…pus (#401) (#418)

* fix(parser): validate the region parsed from Host and handle api.* hosts (#403)

extractRegionFromHost returned "pricing" for api.pricing.us-east-1.amazonaws.com.
With ".amazonaws.com" stripped, parts is [api, pricing, us-east-1]: the s3 loop
does not fire, parts[1] is not "execute-api", so it fell through to the
"<service>.<region>" assumption and returned parts[1] — the second label of a
three-label host.

The reported symptom is one host layout, but the shape of the bug is the whole
function failing open: it returned whichever label sat where a region usually
sits, so a caller could not tell a parse failure from a real region. Every
candidate is now checked against the shape of a region code — two-letter
geography, one or two lowercase words, trailing ordinal — covering the
four-segment partition forms (us-gov-west-1) as well as the ordinary ones.
A layout that does not match yields "", which routes the request through the
fallbacks extractRegion already had: the SigV4 credential scope, then
defaultRegion.

Two hosts that look like they should now fail keep working, and deliberately so:
my-lb-1234.us-east-1.elb.amazonaws.com and my-domain.us-east-1.es.amazonaws.com
carry a genuine region in the second label, and the shape check passes it.

Refs #401, whose acceptance criteria include this fix.

* feat(pricing): emulate the Price List Query API over a real offer corpus (#401)

Adds a `pricing` plugin serving GetProducts, DescribeServices and
GetAttributeValues over `api.pricing.{region}` and
`X-Amz-Target: AWSPriceListService.{Op}`. This is the server side of pricing —
for consumers that query AWS rates at runtime — and is the inverse of the
existing cost-tracking provider, which consumes the public offer index to price
substrate's own simulated usage.

The offer corpus is seven Amazon S3 SKUs copied verbatim from the live
AmazonS3/current/us-east-1 offer file (version 20260728131000). It is small on
purpose: each SKU reproduces a response shape callers get wrong, and a tidied-up
fixture would let a consumer's parser pass its tests and then misbehave against
the real API.

  - PriceList elements are JSON documents encoded as strings, not objects.
  - pricePerUnit, beginRange and endRange are strings with trailing zeros.
  - productFamily is absent from most products — 315 of the 381 in the real file
    omit it — so a filter on it misses the majority of SKUs, while usagetype
    reaches every one.
  - TimedStorage-ByteHrs carries three priceDimensions, the last with
    endRange "Inf"; reading only the first reports the 50 TB rate as the only
    rate.

Two of those shapes are the reporter's own bugs, now reproducible: their static
table had Requests-Tier1 10x low (it is "0.0000050000" per request with
unit Requests — $0.005 per 1,000, so dividing by 1,000 again is 1,000x off), and
filtering productFamily=Storage with volumeType="Glacier Deep Archive" returns
*only* TimedStorage-GDA-Staging at $0.021/GB-Mo, 21x the $0.00099 archive rate.
Verified against the live offer file: no TimedStorage-GDA-ByteHrs SKU exists in
it at all, so that filter cannot return the rate a caller expects; the nearest
$0.00099 SKU is Intelligent-Tiering's TimedStorage-INT-DAA-ByteHrs.

Filter.Type covers the full documented enum (TERM_MATCH, EQUALS, CONTAINS,
ANY_OF, NONE_OF), not just TERM_MATCH. MaxResults bounds are per-operation
(1-100 for GetProducts/DescribeServices, 1-10000 for GetAttributeValues) and an
out-of-range value is InvalidParameterException rather than a silent clamp. An
unknown ServiceCode is NotFoundException rather than an empty PriceList that
would read as "AWS has no such price" — a false alarm is visible, a false empty
is not.

Failures are seedable via POST/DELETE /v1/pricing/query-failures, keyed by
operation or the "*" wildcard. Pricing is the kind of dependency whose failure
should degrade a caller rather than stop it, and that property is only testable
if the failure can be produced on demand. The seed endpoint rejects any code
outside the seven the API documents, because a typo'd code would seed an error no
SDK catch branch matches: the fallback path would go untested while the seed
appeared to work.

AWS hosts this API in exactly three regions — us-east-1, ap-south-1 and
eu-central-1 (the issue named two). Substrate serves every region from one
endpoint, so it cannot reproduce a hostname that fails to resolve; a request
signed for any other region is rejected with SubstrateInvalidPricingEndpoint,
deliberately not an AWS code, and documented as a divergence rather than parity.

Also fixes the service half of the api.<service>.<region> host layout, the
companion to the region fix in #403: the first label yielded a service literally
named "api", so these endpoints could not route to any plugin. api.ecr.* and
api.sagemaker.* were affected too, having been reachable only via X-Amz-Target.

Refs #401.

* docs: regenerate the service reference after merging main (#401)

The merge took this branch's coverage matrix, which predates #415's correction
of RAM's protocol from JSON to REST/JSON. Regenerated from the plugin registry,
which is what docs-reference-check compares against.
@scttfrdmn
scttfrdmn deleted the fix/392-error-codes branch August 1, 2026 01:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: iam Issues relating to the iam component area: s3 Issues relating to the s3 component type: bug Something is not working correctly

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Error.Code returns HTTP status or wrong spelling for SSM/Lambda/IAM/S3 not-found

1 participant