Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat: CloudFormation provisioners for ApiGatewayV2 Integration + Route (#480)
Michael Smith12ce8d14c59a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dfd47956..f9d9f734 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Added+- **CloudFormation ApiGatewayV2 Integration + Route provisioners** — `AWS::ApiGatewayV2::Integration` and `AWS::ApiGatewayV2::Route` are now supported as CloudFormation resource types. This completes the API Gateway V2 CloudFormation surface alongside the existing `Api` and `Stage` provisioners, enabling full CDK HTTP API deployments (`HttpApi.addRoutes()`) to ministack. Both provisioners support `Fn::GetAtt` (`IntegrationId`, `RouteId`) and idempotent delete.- **Step Functions alias API** — `CreateStateMachineAlias`, `UpdateStateMachineAlias`, `DeleteStateMachineAlias`, `DescribeStateMachineAlias`, `ListStateMachineAliases`, plus `DescribeStateMachine` support for alias ARNs (`arn:…:stateMachine:<name>:<aliasName>`). Aliases let callers address a state machine by a stable pointer whose `routingConfiguration` distributes invocations across one or two versions by weight. Validation matches AWS: alias name regex `^[0-9A-Za-z_-]+$` length 1-80, routing 1-2 entries with int `weight` in `[0, 100]` summing to 100, no duplicate version ARNs, every referenced version must exist on the same state machine. `DeleteStateMachineVersion` now scans for alias references and raises `ConflictException` when an alias still routes to the version — the alias-awareness cross-check deferred from the versioning PR. Same terraform-provider-aws v6 motivation — the provider unconditionally calls `ListStateMachineAliases` on every `aws_sfn_state_machine` refresh, so without this any `terraform plan` returned `InvalidAction`.- **Step Functions versioning API** — `PublishStateMachineVersion`, `DeleteStateMachineVersion`, `ListStateMachineVersions`, plus `DescribeStateMachine` support for qualified version ARNs (`arn:…:stateMachine:<name>:<N>`) returning the snapshot captured at publish time. `CreateStateMachine` now accepts the `publish=True` parameter, returning `stateMachineVersionArn` for the auto-published v1 in the same call. AWS-style optimistic concurrency via `revisionId`: every Create/Update rotates the state machine's `revisionId`, and `PublishStateMachineVersion`'s optional `revisionId` is treated as a precondition — supplying a stale value raises `ConflictException`. Version numbers are monotonic per state machine and never reused after delete (a `lastVersionNumber` high-water mark on the base state machine enforces this, matching AWS's documented behaviour). Without these actions, terraform-provider-aws v6 fails on every `aws_sfn_state_machine` refresh because it unconditionally calls `ListStateMachineVersions` regardless of whether versioning was opted into.- **CloudWatch Logs Delivery API** — `PutDeliverySource` / `GetDeliverySource` / `DeleteDeliverySource` / `DescribeDeliverySources`, `PutDeliveryDestination` / `GetDeliveryDestination` / `DeleteDeliveryDestination` / `DescribeDeliveryDestinations`, and `CreateDelivery` / `GetDelivery` / `DeleteDelivery` / `DescribeDeliveries` (12 actions total). This is the 2023-era replacement for subscription filters that vended-logs producers (Bedrock, AppSync, CodeWhisperer, …) use to ship logs into S3, CloudWatch Logs, or Firehose. Server-derived fields match AWS's contract: `service` is computed from a delivery source's `resourceArn` (e.g. `arn:aws:bedrock:…` → `bedrock`) and `deliveryDestinationType` from a destination's `destinationResourceArn` (`s3` → `S3`, `logs` → `CWL`, `firehose` → `FH`); callers cannot override either. `outputFormat` is validated against the AWS enum (`json` / `plain` / `w3c` / `raw` / `parquet`). `CreateDelivery` requires the `deliveryDestinationArn` to resolve to an already-registered destination (instead of silently defaulting to `CWL`) and rejects duplicate `(deliverySourceName, deliveryDestinationArn)` pairs with `ConflictException`, matching AWS's one-Delivery-per-pair contract.diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 0747297c..2c767d20 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -2532,6 +2532,71 @@ def _apigw_v2_stage_delete(physical_id, props):stages.pop(stage_name, None)+# ---------------------------------------------------------------------------+# ApiGatewayV2 Integration+# ---------------------------------------------------------------------------++def _apigw_v2_integration_create(logical_id, props, stack_name):+ api_id = props.get("ApiId", "")+ int_id = new_uuid()[:8]+ integration = {+ "integrationId": int_id,+ "integrationType": props.get("IntegrationType", "AWS_PROXY"),+ "integrationUri": props.get("IntegrationUri", ""),+ "integrationMethod": props.get("IntegrationMethod", "POST"),+ "payloadFormatVersion": props.get("PayloadFormatVersion", "2.0"),+ "timeoutInMillis": props.get("TimeoutInMillis", 30000),+ "connectionType": props.get("ConnectionType", "INTERNET"),+ "connectionId": props.get("ConnectionId", ""),+ "description": props.get("Description", ""),+ "requestParameters": props.get("RequestParameters", {}),+ "requestTemplates": props.get("RequestTemplates", {}),+ "responseParameters": props.get("ResponseParameters", {}),+ "contentHandlingStrategy": props.get("ContentHandlingStrategy"),+ }+ _apigw_v2._integrations.setdefault(api_id, {})[int_id] = integration+ physical_id = f"{api_id}/{int_id}"+ return physical_id, {"IntegrationId": int_id}+++def _apigw_v2_integration_delete(physical_id, props):+ parts = physical_id.split("/", 1)+ if len(parts) == 2:+ api_id, int_id = parts+ integrations = _apigw_v2._integrations.get(api_id, {})+ integrations.pop(int_id, None)+++# ---------------------------------------------------------------------------+# ApiGatewayV2 Route+# ---------------------------------------------------------------------------++def _apigw_v2_route_create(logical_id, props, stack_name):+ api_id = props.get("ApiId", "")+ route_id = new_uuid()[:8]+ route = {+ "routeId": route_id,+ "routeKey": props.get("RouteKey", "$default"),+ "target": props.get("Target", ""),+ "authorizationType": props.get("AuthorizationType", "NONE"),+ "apiKeyRequired": props.get("ApiKeyRequired", False),+ "operationName": props.get("OperationName", ""),+ "requestModels": props.get("RequestModels", {}),+ "requestParameters": props.get("RequestParameters", {}),+ }+ _apigw_v2._routes.setdefault(api_id, {})[route_id] = route+ physical_id = f"{api_id}/{route_id}"+ return physical_id, {"RouteId": route_id}+++def _apigw_v2_route_delete(physical_id, props):+ parts = physical_id.split("/", 1)+ if len(parts) == 2:+ api_id, route_id = parts+ routes = _apigw_v2._routes.get(api_id, {})+ routes.pop(route_id, None)++# ---------------------------------------------------------------------------# SES EmailIdentity# ---------------------------------------------------------------------------@@ -2898,6 +2963,8 @@ _RESOURCE_HANDLERS = {"AWS::Route53::RecordSet": {"create": _r53_record_set_create, "delete": _r53_record_set_delete},"AWS::ApiGatewayV2::Api": {"create": _apigw_v2_api_create, "delete": _apigw_v2_api_delete},"AWS::ApiGatewayV2::Stage": {"create": _apigw_v2_stage_create, "delete": _apigw_v2_stage_delete},+ "AWS::ApiGatewayV2::Integration": {"create": _apigw_v2_integration_create, "delete": _apigw_v2_integration_delete},+ "AWS::ApiGatewayV2::Route": {"create": _apigw_v2_route_create, "delete": _apigw_v2_route_delete},"AWS::SES::EmailIdentity": {"create": _ses_email_identity_create, "delete": _ses_email_identity_delete},"AWS::WAFv2::WebACL": {"create": _waf_web_acl_create, "delete": _waf_web_acl_delete},"AWS::CloudFront::Distribution": {"create": _cf_distribution_create, "delete": _cf_distribution_delete},diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex f4f30f92..f2356c68 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -2158,3 +2158,277 @@ Outputs:)assert with_resp["UserPoolClient"].get("ClientSecret"), "GenerateSecret=true should produce a non-empty ClientSecret"assert not without_resp["UserPoolClient"].get("ClientSecret"), "GenerateSecret=false should leave ClientSecret empty"+++# ---------------------------------------------------------------------------+# ApiGatewayV2 Integration + Route provisioners+# ---------------------------------------------------------------------------++def test_cfn_apigwv2_integration_basic(cfn, apigw):+ """CFN stack with ApiGatewayV2 Api + Integration deploys successfully."""+ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "HttpApi": {+ "Type": "AWS::ApiGatewayV2::Api",+ "Properties": {+ "Name": "cfn-apigwv2-int-t01",+ "ProtocolType": "HTTP",+ },+ },+ "Integration": {+ "Type": "AWS::ApiGatewayV2::Integration",+ "Properties": {+ "ApiId": {"Ref": "HttpApi"},+ "IntegrationType": "AWS_PROXY",+ "IntegrationUri": "arn:aws:lambda:us-east-1:000000000000:function:dummy",+ "PayloadFormatVersion": "2.0",+ },+ },+ },+ }+ stack_name = "cfn-apigwv2-int-t01"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE"++ # Verify integration exists via ApiGatewayV2 API+ resources = cfn.describe_stack_resources(StackName=stack_name)["StackResources"]+ api_res = [r for r in resources if r["ResourceType"] == "AWS::ApiGatewayV2::Api"][0]+ api_id = api_res["PhysicalResourceId"]++ integrations = apigw.get_integrations(ApiId=api_id)["Items"]+ assert len(integrations) == 1+ assert integrations[0]["IntegrationType"] == "AWS_PROXY"+ assert integrations[0]["PayloadFormatVersion"] == "2.0"++ # Delete and verify cleanup+ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+ assert apigw.get_integrations(ApiId=api_id)["Items"] == []+++def test_cfn_apigwv2_route_basic(cfn, apigw):+ """CFN stack with ApiGatewayV2 Api + Integration + Route deploys successfully."""+ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "HttpApi": {+ "Type": "AWS::ApiGatewayV2::Api",+ "Properties": {+ "Name": "cfn-apigwv2-route-t01",+ "ProtocolType": "HTTP",+ },+ },+ "Integration": {+ "Type": "AWS::ApiGatewayV2::Integration",+ "Properties": {+ "ApiId": {"Ref": "HttpApi"},+ "IntegrationType": "AWS_PROXY",+ "IntegrationUri": "arn:aws:lambda:us-east-1:000000000000:function:dummy",+ "PayloadFormatVersion": "2.0",+ },+ },+ "DefaultRoute": {+ "Type": "AWS::ApiGatewayV2::Route",+ "Properties": {+ "ApiId": {"Ref": "HttpApi"},+ "RouteKey": "ANY /{proxy+}",+ "Target": {"Fn::Join": ["/", ["integrations", {"Ref": "Integration"}]]},+ },+ },+ },+ }+ stack_name = "cfn-apigwv2-route-t01"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE"++ # Verify route exists via ApiGatewayV2 API+ resources = cfn.describe_stack_resources(StackName=stack_name)["StackResources"]+ api_res = [r for r in resources if r["ResourceType"] == "AWS::ApiGatewayV2::Api"][0]+ api_id = api_res["PhysicalResourceId"]++ routes = apigw.get_routes(ApiId=api_id)["Items"]+ assert len(routes) == 1+ assert routes[0]["RouteKey"] == "ANY /{proxy+}"+ assert "integrations/" in routes[0].get("Target", "")++ # Delete and verify cleanup+ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+ assert apigw.get_routes(ApiId=api_id)["Items"] == []+++def test_cfn_apigwv2_integration_getatt(cfn, apigw):+ """Fn::GetAtt on IntegrationId resolves correctly."""+ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "HttpApi": {+ "Type": "AWS::ApiGatewayV2::Api",+ "Properties": {+ "Name": "cfn-apigwv2-int-t02",+ "ProtocolType": "HTTP",+ },+ },+ "Integration": {+ "Type": "AWS::ApiGatewayV2::Integration",+ "Properties": {+ "ApiId": {"Ref": "HttpApi"},+ "IntegrationType": "AWS_PROXY",+ "IntegrationUri": "arn:aws:lambda:us-east-1:000000000000:function:dummy",+ "PayloadFormatVersion": "2.0",+ },+ },+ },+ "Outputs": {+ "IntegrationId": {"Value": {"Fn::GetAtt": ["Integration", "IntegrationId"]}},+ "ApiId": {"Value": {"Ref": "HttpApi"}},+ },+ }+ stack_name = "cfn-apigwv2-int-t02"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE"++ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack.get("Outputs", [])}+ assert "IntegrationId" in outputs+ assert len(outputs["IntegrationId"]) == 8 # UUID[:8]++ # Verify the integration ID matches what the API returns+ integrations = apigw.get_integrations(ApiId=outputs["ApiId"])["Items"]+ assert integrations[0]["IntegrationId"] == outputs["IntegrationId"]++ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+++def test_cfn_apigwv2_route_getatt(cfn, apigw):+ """Fn::GetAtt on RouteId resolves correctly."""+ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "HttpApi": {+ "Type": "AWS::ApiGatewayV2::Api",+ "Properties": {+ "Name": "cfn-apigwv2-route-t02",+ "ProtocolType": "HTTP",+ },+ },+ "MyRoute": {+ "Type": "AWS::ApiGatewayV2::Route",+ "Properties": {+ "ApiId": {"Ref": "HttpApi"},+ "RouteKey": "GET /health",+ },+ },+ },+ "Outputs": {+ "RouteId": {"Value": {"Fn::GetAtt": ["MyRoute", "RouteId"]}},+ "ApiId": {"Value": {"Ref": "HttpApi"}},+ },+ }+ stack_name = "cfn-apigwv2-route-t02"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE"++ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack.get("Outputs", [])}+ assert "RouteId" in outputs+ assert len(outputs["RouteId"]) == 8 # UUID[:8]++ # Verify the route ID matches what the API returns+ routes = apigw.get_routes(ApiId=outputs["ApiId"])["Items"]+ assert routes[0]["RouteId"] == outputs["RouteId"]++ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+++def test_cfn_apigwv2_integration_idempotent_delete(cfn):+ """Deleting a stack with an integration twice does not crash."""+ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "HttpApi": {+ "Type": "AWS::ApiGatewayV2::Api",+ "Properties": {"Name": "cfn-apigwv2-int-t03", "ProtocolType": "HTTP"},+ },+ "Integration": {+ "Type": "AWS::ApiGatewayV2::Integration",+ "Properties": {+ "ApiId": {"Ref": "HttpApi"},+ "IntegrationType": "AWS_PROXY",+ "IntegrationUri": "arn:aws:lambda:us-east-1:000000000000:function:dummy",+ },+ },+ },+ }+ stack_name = "cfn-apigwv2-int-t03"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))+ _wait_stack(cfn, stack_name)++ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)++ # Second delete should not raise+ cfn.delete_stack(StackName=stack_name)+++def test_cfn_apigwv2_full_http_api_stack(cfn, apigw):+ """Full HTTP API stack with Api + Stage + Integration + Route deploys and cleans up."""+ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "HttpApi": {+ "Type": "AWS::ApiGatewayV2::Api",+ "Properties": {"Name": "cfn-apigwv2-full-t01", "ProtocolType": "HTTP"},+ },+ "Stage": {+ "Type": "AWS::ApiGatewayV2::Stage",+ "Properties": {+ "ApiId": {"Ref": "HttpApi"},+ "StageName": "$default",+ "AutoDeploy": True,+ },+ },+ "Integration": {+ "Type": "AWS::ApiGatewayV2::Integration",+ "Properties": {+ "ApiId": {"Ref": "HttpApi"},+ "IntegrationType": "AWS_PROXY",+ "IntegrationUri": "arn:aws:lambda:us-east-1:000000000000:function:my-handler",+ "PayloadFormatVersion": "2.0",+ },+ },+ "ProxyRoute": {+ "Type": "AWS::ApiGatewayV2::Route",+ "Properties": {+ "ApiId": {"Ref": "HttpApi"},+ "RouteKey": "ANY /{proxy+}",+ "Target": {"Fn::Join": ["/", ["integrations", {"Ref": "Integration"}]]},+ },+ },+ },+ }+ stack_name = "cfn-apigwv2-full-t01"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE"++ resources = cfn.describe_stack_resources(StackName=stack_name)["StackResources"]+ api_res = [r for r in resources if r["ResourceType"] == "AWS::ApiGatewayV2::Api"][0]+ api_id = api_res["PhysicalResourceId"]++ # All four resource types should exist+ assert len(apigw.get_integrations(ApiId=api_id)["Items"]) == 1+ assert len(apigw.get_routes(ApiId=api_id)["Items"]) == 1+ assert len(apigw.get_stages(ApiId=api_id)["Items"]) == 1++ # Delete and verify all resources cleaned up+ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)++ assert apigw.get_integrations(ApiId=api_id)["Items"] == []+ assert apigw.get_routes(ApiId=api_id)["Items"] == []