Repository navigation
fix(errors): serialize errors in each service's wire protocol (#392) - #415
Merged
Merged
Conversation
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.
Codecov Report❌ Patch coverage is
📢 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.
# Conflicts: # CHANGELOG.md
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.writeErroremitted aCodemember for every JSON service. botocore'sBaseJSONParser._do_error_parsedoes:It reads
__typeand falls back to the stringified HTTP status. It never readsCode. So SSM'sParameterNotFound— which the plugin was already setting correctly — was discarded on the wire, and the caller sawError.Code == "404". Everyexcept ClientErrorbranch 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 theapplication/x-amz-jsonprefix 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:
x-amz-json-1.1inbound but answers errors in XML.application/jsonis indistinguishable from a plain JSON body.So the service name selects it.
emulator/error_protocol.goadds one dispatch layer over three shapes:<ErrorResponse><Error><Code>QueryParser,BaseXMLResponseParser__typeBaseJSONParserx-amzn-errortypeheaderRestJSONParser._inject_error_codeEvery entry in the classification table is the
protocolfield of that service's model inbotocore/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/Messagealongside__type/messageso callers already readingCodekeep working.The other three, all verified against AWS docs
Exceptionsuffix that the API model's shape names carry:NoSuchEntity,EntityAlreadyExists,MalformedPolicyDocument,DeleteConflict,LimitExceeded(44 call sites). This is not a blanket suffix-strip:ValidationErrorandAccessDeniedExceptionare already correct per IAM'sCommonErrors, and Lambda genuinely does useResourceNotFoundExceptionon the wire. Neither service's spelling can be inferred from the other, which is why each was checked individually.GetObject/HeadObjectwent straight to the object lookup, so a GET against a bucket that was never created reportedNoSuchKey. That conflates two conditions a caller must distinguish: a deleted bucket (fatal misconfiguration) from an unwritten object (ordinary cache miss). NewbucketMissingResponsehelper 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_CarriesTypeMemberasserts__type == "ParameterNotFound"and!= "404"— the status must never be the thing a caller matches on.TestRESTJSONError_IsNotXMLasserts a Lambda error body contains no<ErrorResponse.TestIAMError_DropsExceptionSuffixpinsNoSuchEntityagainstAPI_GetRole.html.TestS3GetObject_MissingKeyInExistingBucketIsNoSuchKeyis the guard on the other side — the bucket fix must not turn every miss intoNoSuchBucket.TestErrorProtocolFor_Classificationpins each protocol per service, including the nine JSON-RPC services whose...Gateway/...Servicetarget prefixes make them look REST-shaped, plus both fallback branches.Three IAM test assertions changed: they had encoded the bug, asserting the old
...Exceptionspellings.Gates
go build✅ ·go vet✅ ·golangci-lint run ./...0 issues ✅ ·make test(race) ✅ ·test/e2e✅ ·make docs-reference-check✅ ·make scan-fs0 vulns ✅errorProtocolForis at 100% coverage. The residual uncovered lines are thejson.Marshal/xml.Marshalerror guards, unreachable formap[string]stringand all-string structs; they exist sowriteError'shttp.Errorfallback stays reachable.