Skip to content

fix(cfn): read Mappings and resolve FindInMap, GetAZs, Cidr and the pseudo-parameters (#522) - #535

Merged
scttfrdmn merged 1 commit into
mainfrom
fix/522-mappings-intrinsics
Aug 3, 2026
Merged

scttfrdmn merged 1 commit into
mainfrom
fix/522-mappings-intrinsics

Conversation

@scttfrdmn

Copy link
Copy Markdown
Owner

Part 1 of #522. Does not close it — Fn::ImportValue is deliberately split out; see What this leaves below.

The defect

cfnTemplate had no Mappings field, so the section every region→AMI template carries was discarded at parse time and Fn::FindInMap fell through to the JSON-encoding fallback. The near-universal

ImageId: !FindInMap [RegionMap, !Ref 'AWS::Region', AMI]

reached RunInstances as the literal string {"Fn::FindInMap":["RegionMap",...]} and the instance launched, the resource reporting CREATE_COMPLETE. Same shape as #516/#517/#521/#526/#527: substrate returns 200 while the observable a caller parses is wrong.

What resolves now

Mappings + Fn::FindInMap — all three levels, including the nested-key form the reference leads with (!FindInMap [Arch2AMI, !Ref 'AWS::Region', !FindInMap [Type2Arch, !Ref InstanceType, Arch]]). A leaf may be a string or a list, since "the values can be of type String or List", so a list-valued lookup splices into a list-valued property and is rejoined on commas in a scalar one. The optional fourth argument is honored, spelled exactly {DefaultValue: …} — a map with any other key is not a default and the lookup fails as it would without one, rather than substrate guessing at the intent.

A lookup that misses fails the resource. CREATE_FAILED with a ResourceStatusReason naming the intrinsic and the key that missed; the rest of the stack still deploys, per #519. That is the point of modelling Mappings rather than tolerating it — a nonsense ImageId reported as success is the defect.

Reporting it needed a new channel, because a resolver returns a string and in that type "no such key" and "the key held an empty string" are the same value. cfnContext now accumulates failures, drained per resource onto DeployedResource.Error — which DescribeStackResources already derives CREATE_FAILED from (cloudformation_plugin.go:474). deployResource is split into that drain plus dispatchResource, so the ~100-arm type switch is renamed rather than edited.

Fn::GetAZs derives from ec2SeededAZSuffixes, the same list EC2's DescribeAvailabilityZones answers from, rather than carrying a second one — a subnet in a zone the emulator does not report is not something a caller can query, and two independent lists is how that happens.

Fn::Cidr for IPv4 and IPv6 via net/netip (the mask comes from the parsed block's address family; both of the reference's examples are asserted). An impossible request fails the resource rather than returning a short list, since !Select [3, !Cidr [...]] reads an empty string out of a short list and deploys.

The four remaining pseudo-parameters. AWS::Partition/AWS::URLSuffix follow the region; AWS::NotificationARNs is an empty list (accurate — substrate has no notification model); AWS::StackId now shares its builder with the wire's cfnStackID, so a consumer that captures StackId from CreateStack and compares it against a property built from AWS::StackId finds one ARN for one stack. Two builders would have been the same divergence #517 fixed for the caller's account.

What this leaves

Fn::ImportValue is still unresolved and #522 stays open for it. Per the plan's own stated trigger — "if PR 3 grows past PR 1+2 combined, split Fn::ImportValue out" — it needs an export registry populated from Outputs.*.Export.Name (Export is absent from cfnOutput today) plus a refusal to delete a stack whose export is imported. That is a new cross-stack model, not another resolver, and it ships as a follow-up PR. Fn::ImportValue is deliberately not admitted to cfnIntrinsicNames here: doing so would make resolveNested resolve it to the empty string, which is worse than the current JSON-literal fallback.

Verification

gofmt, go build, go vet, golangci-lint (0 issues), make test (race), docs reference/versions checks, npm --prefix docs run build, test/e2e vet+test — all green.

End to end over the wire against substrate server, region matched to the signed request:

$ aws cloudformation describe-stack-resources --stack-name mappings522b \
    --query 'StackResources[].[LogicalResourceId,ResourceStatus]'
VPC       CREATE_COMPLETE
Subnet    CREATE_COMPLETE
Instance  CREATE_COMPLETE

$ aws ec2 describe-vpcs --query 'Vpcs[].CidrBlock'          # !FindInMap
10.42.0.0/16
$ aws ec2 describe-subnets --query 'Subnets[].[CidrBlock,AvailabilityZone]'
10.42.2.0/24   us-east-1b       # !Select [2, !Cidr [...]] and !Select [1, !GetAZs '']
$ aws ec2 describe-availability-zones --query 'AvailabilityZones[].ZoneName'
us-east-1a  us-east-1b  us-east-1c     # the same zones — they agree
$ aws ec2 describe-instances --query 'Reservations[].Instances[].ImageId'
ami-0abcdef1234567890                   # the mapped AMI, not a JSON literal

And the failure path, with the rest of the stack unaffected:

$ aws cloudformation describe-stack-resources --stack-name badmap522 \
    --query 'StackResources[].[LogicalResourceId,ResourceStatus,ResourceStatusReason]'
Good  CREATE_COMPLETE  None
Bad   CREATE_FAILED    Fn::FindInMap: mapping "RegionMap" has no top-level key "us-east-1"

Mutation testing

21 mutants, all CAUGHT, no survivors and no equivalents — including the plan's nominated highest-value one (Fn::FindInMap falling back to the JSON literal instead of failing the resource), the failure channel going silent, Fn::GetAZs inventing its own zone list, Fn::Cidr assuming IPv4, and cfnStackID diverging from cfnStackARN.

The pass exposed three test-design gaps, each closed by a test rather than argued away as equivalent:

  • The resolved shape inside a structured property was unasserted. A scalar context rejoins a list, so "resolved to a list" and "resolved to a comma-joined string" are the same observable there — cfnListValuedIntrinsic could return a constant and nothing failed. TestCFN_ListValuedShapeInsideAStructuredProperty asserts the JSON shape a member receives, which is also where AWS::NotificationARNs being an empty array rather than a one-element [""] becomes visible.
  • A failure being inherited by a later resource was unasserted. The channel is state on the shared context, so the drain is what keeps it per-resource; getting it wrong would report every later resource CREATE_FAILED and send a consumer chasing the wrong one.
  • A condition's failure had no attribution test. Conditions are evaluated once before any resource deploys, and !Not [!Equals [!FindInMap [M, K1, K2], '']] is conventional — so a failing lookup there records against a context with nothing to blame. Dropping it is deliberate (DescribeStackResources has no row for a condition); blaming the first resource is the bug the pre-drain prevents.

Refs #522

…seudo-parameters (#522)

A template's Mappings section was discarded at parse time — cfnTemplate had no
field for it — so Fn::FindInMap fell back to its JSON encoding and the
near-universal `ImageId: !FindInMap [RegionMap, !Ref 'AWS::Region', AMI]` reached
RunInstances as the literal `{"Fn::FindInMap":[...]}` while the instance launched
and the resource reported CREATE_COMPLETE.

Mappings is now read and all three levels resolve, including the nested-key form
the reference leads with, a list-valued leaf (spliced in a list context, rejoined
on commas in a scalar one), and the optional {DefaultValue: ...} fourth argument.

A lookup that misses fails the resource — CREATE_FAILED with a
ResourceStatusReason naming the intrinsic and the key — rather than falling back
to the literal, which is the whole point of modelling Mappings rather than
tolerating it. Reporting it needed a new channel, since a resolver returns a
string in which "no such key" and "the key held an empty string" are the same
value: cfnContext accumulates failures, drained per resource onto
DeployedResource.Error, which DescribeStackResources already derives
CREATE_FAILED from. deployResource is split into that drain plus dispatchResource
so the ~100-arm type switch is untouched.

Fn::GetAZs derives from the same seeded zone list EC2's
DescribeAvailabilityZones answers from rather than carrying a second one, so a
subnet placed with !Select over !GetAZs names a zone the caller can then query.
Fn::Cidr handles IPv4 and IPv6 via net/netip — the mask comes from the parsed
block's address family — and refuses an impossible request rather than returning
a short list a !Select would read an empty string out of.

The four remaining pseudo-parameters resolve: AWS::Partition and AWS::URLSuffix
follow the region, AWS::NotificationARNs is an empty list, and AWS::StackId
shares its builder with the wire's cfnStackID so the ARN a template reads about
itself is the one CreateStack returned.

Fn::ImportValue remains unresolved and #522 stays open for it: it needs an export
registry across stacks and a refusal to delete an imported-from stack, which is a
cross-stack model rather than another resolver.

21 mutants run against the new code; all caught, no survivors. Three test-design
gaps the pass exposed are closed by tests: the resolved *shape* inside a
structured property (invisible in a scalar context, which rejoins), a failure not
being inherited by a later resource, and a condition's failure not being blamed on
the first resource.
@codecov

codecov Bot commented Aug 3, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.51685% with 24 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
emulator/betty_cfn.go 86.44% 15 Missing and 9 partials ⚠️

📢 Thoughts on this report? Let us know!

@scttfrdmn
scttfrdmn merged commit ef9550f into main Aug 3, 2026
16 checks passed
@scttfrdmn
scttfrdmn deleted the fix/522-mappings-intrinsics branch August 3, 2026 09:34
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