Skip to content

CloudFormation: StackDeployer.dispatch hardcodes account/region, so stack-created EC2 and ECS resources are invisible to the caller #517

Closed

Description

@scttfrdmn

Second of two CFN issues found after #483 landed; the other is #516 (YAML short-form
intrinsics). This one is narrower and the fix looks mechanical.

The defect

A stack reports CREATE_COMPLETE with plausible physical IDs for resources the caller
cannot then find. Against ghcr.io/scttfrdmn/substrate:0.87.0:

sts:GetCallerIdentity account : 000000000000
stack ARN                     : arn:aws:cloudformation:us-east-1:000000000000:stack/acct/5f87f914-...

AWS::EC2::Instance  CREATE_COMPLETE  phys=i-248298e0ac468538

describe_instances()                            -> 0 reservations
describe_instances(InstanceIds=["i-2482..."])   -> InvalidInstanceID.NotFound
control: run_instances() called directly        -> 1 reservation, visible immediately

Same for AWS::EC2::LaunchTemplate (describe_launch_templates → empty),
AWS::ECS::Cluster (list_clusters → []), AWS::ECS::TaskDefinition and
AWS::Logs::LogGroup (describe_log_groups → []). Tried in every region.
AWS::IAM::Role and AWS::IAM::InstanceProfile are visible.

Cause: StackDeployer.dispatch synthesises the identity

emulator/betty_cfn.go:2847 builds a fresh RequestContext from package constants
instead of threading the inbound request's:

reqCtx := &RequestContext{
    RequestID: generateRequestID(),
    AccountID: testAccountID,   // parser.go:12 -> "123456789012"
    Region:    defaultRegion,   // parser.go:18 -> "us-east-1"
    Timestamp: d.tc.Now(),
    Metadata:  map[string]interface{}{"stream_id": streamID},
}

The caller is 000000000000, so the write and the read address different partitions
and the read correctly reports nothing. This is the same partitioning behaviour as
#391, just reached from the deployer rather than from a client.

The resource handlers are all correct — deployEC2Instance (betty_cfn.go:2040)
really does dispatch RunInstances with ImageId, InstanceType, SubnetId,
security groups and (since #388) an instance profile. The instance is created; it just
lands somewhere the caller cannot see.

CloudFormationPlugin itself threads reqCtx.Region and reqCtx.AccountID properly
(cloudformation_plugin.go:1046), which is exactly why the stack is visible while
its resources are not, and why the ARN says 000000000000 while its contents live
in 123456789012.

That split also explains a red herring I chased first: because global services survive
the crossing and regional ones do not, it looks like AWS::IAM::* is implemented and
AWS::EC2::* is stubbed. Both are implemented.

Fix looks like passing the inbound *RequestContext (or at minimum its AccountID
and Region) through Deploy into dispatch rather than constructing one. Betty's
in-process callers presumably want the same, since they can specify a region too.

Secondary: DeleteStack does not delete the stack's resources

create_stack (AWS::S3::Bucket)  -> CREATE_COMPLETE, bucket present in list_buckets
delete_stack + waiter           -> OK
describe_stacks(StackName=...)  -> ValidationError: does not exist        [correct]
list_buckets()                  -> the bucket is STILL PRESENT

Same for AWS::IAM::Role — the role outlives its stack. Real CFN deletes a stack's
resources with the stack. The stack-record deletion is right; the resource sweep is
missing. Happy to split this out if you'd rather track it separately.

Why it matters

In parsl-aws-provider, DetachedMode
provisions its bastion as a stack whose template is AWS::EC2::Instance +
AWS::EC2::LaunchTemplate + AWS::IAM::Role + AWS::IAM::InstanceProfile, then calls
describe_instances on the instance it just created — so the two affected types are
exactly the two that matter, and the read is the next thing the code does. Together with
#516 this is what keeps two integration files on moto
(parsl-aws-provider#183).

Worth stressing that #483 was still a real unblock: the CFN API surface works, and a
skip in that suite lifted itself on the bump because it probes /_localstack/health
rather than hardcoding. The suite is green at 131 passed on 0.87.0.

Reproduce

import boto3, json
E = "http://localhost:4566"
cf  = boto3.client("cloudformation", endpoint_url=E, region_name="us-east-1")
ec2 = boto3.client("ec2", endpoint_url=E, region_name="us-east-1")
sts = boto3.client("sts", endpoint_url=E, region_name="us-east-1")

print("caller:", sts.get_caller_identity()["Account"])            # 000000000000
tpl = json.dumps({"Resources": {"I": {"Type": "AWS::EC2::Instance", "Properties": {
    "ImageId": "ami-12345678", "InstanceType": "t3.micro"}}}})
cf.create_stack(StackName="acct", TemplateBody=tpl)
cf.get_waiter("stack_create_complete").wait(StackName="acct")

phys = cf.describe_stack_resources(StackName="acct")["StackResources"][0]["PhysicalResourceId"]
print("phys:", phys)                                              # i-...
print("visible:", len(ec2.describe_instances()["Reservations"]))   # 0
ec2.describe_instances(InstanceIds=[phys])                         # InvalidInstanceID.NotFound

Activity

  1. added
    type: bug
    priority: high
    on Aug 2, 2026
  2. added this to the v0.87.1 milestone on Aug 3, 2026
  3. added a commit that references this issue on Aug 3, 2026
  4. scttfrdmn commented on Aug 3, 2026

    @scttfrdmn
    OwnerAuthor

    Confirmed, fixed, and released in v0.87.1 (PR #524). Your read of StackDeployer.dispatch was exactly right, and the summary you gave — the write went to substrate's defaults while every read was correctly scoped to the caller — is the whole bug.

    Your red herring deserves a plain answer

    You suspected AWS::EC2::* was stubbed while AWS::IAM::* worked, and said you were not sure why. Both families are fully implemented. The asymmetry is real but it is a state-key partition split:

    • S3 keys buckets bucket:<name> and IAM keys roles role:<name> — unpartitioned. A resource written under the wrong identity is still found by a read under the right one, so those two crossed the partition boundary invisibly.
    • EC2 keys instances instance:<account>/<region>/<id>, ECS clusters embed the account and region, Logs groups likewise, and DynamoDB (table:<account>/<name>), SQS (queue:<account>/<name>) and SNS (topic:<account>/<region>/<name>) too. Those do not cross.

    So the resources you could not find were being created correctly and stored one partition over. DescribeInstances returning nothing was the right answer to the question it was asked.

    That split is also why this got through #483's review. The shared-state test I wrote there asserted a bucket through S3 and a role through IAM — the only two services in the registry that could not have seen this bug. The new test file leads with that, and every case in it uses a partitioned service, in a non-default region, because partitioning is the mechanism and a test in us-east-1 under 123456789012 proves nothing.

    A second hardcode neither of us named

    buildCFNContext was also called with the package constants, in two places. So a template whose bucket name is {"Fn::Sub": "b-${AWS::AccountId}-${AWS::Region}"} resolved to substrate's account and region rather than yours — a wrong physical name, which is a different failure from a misplaced resource and would have survived a fix to dispatch alone. Three drift comparators read their own partitioned keys directly as well; a wrong-partition existence check reports DELETED for a healthy resource, and a wrong-partition comparator finds nothing to compare and reports no difference at all, which no IN_SYNC assertion can distinguish from drift working. Six sites in total.

    Not the signature change you expected

    You suggested threading the request context into Deploy. That is the right instinct but Deploy has 145 test call sites across 8 files, plus 13 BettyClient.Deploy sites — a parameter would churn all of them and bury the fix. Instead identity rides on the deployer as an explicit account and region defaulting to today's constants, set through an option following the repo's existing CostControllerOption/EventStoreOption precedent, and the CloudFormation plugin builds a deployer carrying the requesting caller's identity for every path that deploys or reads a resource. A deployer is six pointer copies with no I/O, so one per deploying request is cheaper than making a single deployer's identity mutable and therefore racy.

    Two strings rather than a whole *RequestContext, deliberately: a deployer holding one would carry a single request's ID and timestamp across every resource it deploys, and would tempt a future reader into propagating the principal, which is a separate decision (#411). Because the default is unchanged, no existing caller behaves differently.

    My own #483 comment was wrong about this

    The comment I left on the stack-ARN builder in #483 documented the deployer/request identity disagreement as a discrepancy confined to the two pseudo-parameters. That understated it badly — it was a partition split that made stack-created EC2, ECS and Logs resources unreachable by the caller who created them. Written and shipped by me, and it is what a reader of that file would have been told if they went looking for exactly this. Rewritten to say what the split actually was.

    DeleteStack

    Split out as you offered — #518. It is bigger than it looks: 113 resource types need a per-type delete dispatcher, DeletionPolicy is not modelled at all (no field on the resource struct, zero occurrences repo-wide), deletion has to run in reverse dependency order, and a bucket sweep inherits #508's leak, where DeleteBucket already leaves every sub-resource behind. The two want designing together. The docs claim that DeleteStack deletes the stack's resources was false and is corrected in this release, independent of the sweep.

    Verified

    Your reproduction, re-run against a binary built from the v0.87.1 tag rather than main: an unsigned caller (000000000000) creates a stack with an AWS::EC2::Instance, describe-stack-resources reports CREATE_COMPLETE with i-…, describe-instances finds it, describe-instances --instance-ids i-… returns it, and --region eu-west-1 describe-instances returns zero — so the partitioning that caused this still holds, which is the point.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority: hightype: bug

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions