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
fix(cloudformation): return API Gateway v2 stage name from Ref (#2164)
Matúš Čongrády3c6ec8f3268c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6428f250..ac302dcc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **Cognito — token lifetimes follow the app client** — access and ID tokens, `ExpiresIn` and the `/oauth2/token` `expires_in` were always one hour; they now follow the client's `AccessTokenValidity`, `IdTokenValidity` and `TokenValidityUnits` (one hour when unset, as on AWS), a client created without the two validities no longer reports `60` for them, and an expired token is refused by API Gateway's Cognito and JWT authorizers and, with `AUTH=true`, an expired access token by Cognito with `Access Token has expired`. Contributed by @iot-rocket.- **Cognito — access tokens are verified under `AUTH=true`** — `GetUser` and the other calls that take an `AccessToken` accepted any JWT carrying a user's `sub`, including an ID token, a token with an altered payload and a token revoked by `GlobalSignOut`, `AdminUserGlobalSignOut` or `RevokeToken`; with `AUTH=true` they now answer `NotAuthorizedException` with `Invalid Access Token`, `Could not verify signature for Access Token` or `Access Token has been revoked`, as AWS does. Contributed by @iot-rocket.+- **CloudFormation — API Gateway v2 stage `Ref`** — `Ref` returned `<apiId>/<stageName>`, causing an `AWS::ApiGatewayV2::ApiMapping` using the reference as its `Stage` to fail with `Invalid stage identifier specified`; new stages now return the stage name. Stage updates, replacement on `ApiId` or `StageName` changes, and deletion use the resolved resource properties, including for stacks with legacy physical IDs.- **IAM / CloudFormation — user and role tag keys** — IAM user and role tag keys now compare without case while preserving their spelling. Create and tag operations reject duplicate keys, untag operations match keys regardless of case, and CloudFormation validates duplicate keys and merges stack tags accordingly. User tag updates also compare keys without case. Other resource types retain case-sensitive tag handling.- **Signer — signing material checks in `PutSigningProfile` under `AUTH=true`** — `PutSigningProfile` accepted any certificate ARN, or no `signingMaterial` at all, on every platform; with `AUTH=true` the IoT and FreeRTOS platforms now refuse a profile without `signingMaterial` and a certificate ARN that is malformed, in another region or account, unknown to ACM or not issued, and the Lambda and Notation platforms refuse any `signingMaterial`, with AWS's errors. Contributed by @iot-rocket.diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 031812c8..074c6587 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -10220,8 +10220,9 @@ def _apigw_v2_stage_create(logical_id, props, stack_name):**_apigw_v2_stage_props(props),}_apigw_v2._stages.setdefault(api_id, {})[stage_name] = stage- physical_id = f"{api_id}/{stage_name}"- return physical_id, {"StageName": stage_name}+ # Ref uses the physical ID and AWS returns only the stage name. ApiId+ # stays in the resolved properties for update and delete, as for v1 stages.+ return stage_name, {"StageName": stage_name}def _apigw_v2_stage_update(physical_id, old_props, new_props, stack_name, logical_id=None):@@ -10235,13 +10236,15 @@ def _apigw_v2_stage_update(physical_id, old_props, new_props, stack_name, logicathrough the service's own API. A property the template drops reverts tothe create's default. ApiId and StageName require replacement: the newstage is created before the old one is removed."""- api_id, _, stage_name = physical_id.partition("/")+ api_id = old_props.get("ApiId", "")+ stage_name = old_props.get("StageName", "$default")stage = _apigw_v2._stages.get(api_id, {}).get(stage_name)replaced = _rename_replacement(physical_id, old_props, new_props, stack_name, logical_id,(new_props.get("ApiId", ""), new_props.get("StageName", "$default")),(api_id, stage_name) if stage else None,_apigw_v2_stage_create, _apigw_v2_stage_delete,+ delete_when_id_unchanged=True,)if replaced is not None:return replaced@@ -10249,15 +10252,16 @@ def _apigw_v2_stage_update(physical_id, old_props, new_props, stack_name, logicaif resp[0] >= 400:raise ValueError(f"AWS::ApiGatewayV2::Stage update failed: {resp[2]!r}")_reconcile_tag_map(stage.setdefault("tags", {}), old_props, new_props)+ # Keep legacy api/name physical IDs on in-place updates: changing the ID+ # alone would make the engine delete the still-current stage as a predecessor.return physical_id, {"StageName": stage_name}def _apigw_v2_stage_delete(physical_id, props):- parts = physical_id.split("/", 1)- if len(parts) == 2:- api_id, stage_name = parts- stages = _apigw_v2._stages.get(api_id, {})- stages.pop(stage_name, None)+ api_id = props.get("ApiId", "")+ stage_name = props.get("StageName", "$default")+ stages = _apigw_v2._stages.get(api_id, {})+ stages.pop(stage_name, None)# ---------------------------------------------------------------------------diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 324b55ef..549e2894 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -12772,6 +12772,7 @@ def test_cfn_apigwv2_stage_updates_in_place(cfn, apigw):stack = _wait_stack(cfn, stack_name)assert stack["StackStatus"] == "CREATE_COMPLETE"api_id, stage_ref = _output(stack, "ApiId"), _output(stack, "StageRef")+ assert stage_ref == "dev"before = apigw.get_stage(ApiId=api_id, StageName="dev")assert before["AutoDeploy"] is Truetime.sleep(1.1)@@ -12795,13 +12796,115 @@ def test_cfn_apigwv2_stage_updates_in_place(cfn, apigw):auto_deploy=False))stack = _wait_stack(cfn, stack_name)assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")- assert _output(stack, "StageRef") != stage_ref+ assert _output(stack, "StageRef") == "prod"assert apigw.get_stage(ApiId=api_id, StageName="prod")["Description"] == "second"assert [s["StageName"] for s in apigw.get_stages(ApiId=api_id)["Items"]] == ["prod"]finally:_delete_cfn_test_stack(cfn, stack_name)[email protected]("stage_name", ["prod", "$default"])+def test_cfn_apigwv2_stage_ref_returns_stage_name(cfn, apigw, stage_name):+ stack_name = f"cfn-apigwv2-stage-ref-{_uuid_mod.uuid4().hex[:8]}"+ template = f"""+Resources:+ Api:+ Type: AWS::ApiGatewayV2::Api+ Properties: {{Name: {stack_name}, ProtocolType: HTTP}}+ Stage:+ Type: AWS::ApiGatewayV2::Stage+ Properties: {{ApiId: !Ref Api, StageName: '{stage_name}'}}+Outputs:+ ApiId: {{Value: !Ref Api}}+ StageRef: {{Value: !Ref Stage}}+ StageSub: {{Value: !Sub '${{Stage}}'}}+"""+ cfn.create_stack(StackName=stack_name, TemplateBody=template)+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", _stack_event_reasons(cfn, stack_name)+ assert _output(stack, "StageRef") == stage_name+ assert _output(stack, "StageSub") == stage_name+ assert apigw.get_stage(ApiId=_output(stack, "ApiId"),+ StageName=_output(stack, "StageRef"))["StageName"] == stage_name+ # Stage drift has no reader yet; changing its identity must preserve+ # the existing NOT_CHECKED behavior when checking the stack.+ assert _detect(cfn, stack_name)["StackDriftStatus"] == "IN_SYNC"+ detail = cfn.describe_stack_resource(StackName=stack_name, LogicalResourceId="Stage")+ assert detail["StackResourceDetail"]["DriftInformation"]["StackResourceDriftStatus"] == "NOT_CHECKED"+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+++def test_cfn_apigwv2_stage_api_replacement_and_delete(cfn, apigw):+ """An ApiId change replaces even when Ref stays prod; deleting the stack+ removes the stage without relying on deletion of its owning API."""+ stack_name = f"cfn-apigwv2-stage-api-{_uuid_mod.uuid4().hex[:8]}"+ apis = [apigw.create_api(Name=f"{stack_name}-{i}", ProtocolType="HTTP")["ApiId"] for i in range(2)]++ def template(api_id):+ return json.dumps({+ "Resources": {"Stage": {"Type": "AWS::ApiGatewayV2::Stage", "Properties": {+ "ApiId": api_id, "StageName": "prod", "Description": "stage"}}},+ "Outputs": {"StageRef": {"Value": {"Ref": "Stage"}}},+ })++ try:+ cfn.create_stack(StackName=stack_name, TemplateBody=template(apis[0]))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", _stack_event_reasons(cfn, stack_name)+ assert _output(stack, "StageRef") == "prod"++ # A later failure must leave the predecessor on the original API.+ cfn.update_stack(StackName=stack_name,+ TemplateBody=_cfn_with_failing_resource(template(apis[1]), "Stage"))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", _stack_event_reasons(cfn, stack_name)+ assert apigw.get_stage(ApiId=apis[0], StageName="prod")["Description"] == "stage"+ _assert_apigwv2_api_not_found(lambda: apigw.get_stage(ApiId=apis[1], StageName="prod"))++ cfn.update_stack(StackName=stack_name, TemplateBody=template(apis[1]))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", _stack_event_reasons(cfn, stack_name)+ assert _output(stack, "StageRef") == "prod"+ assert apigw.get_stage(ApiId=apis[1], StageName="prod")["Description"] == "stage"+ _assert_apigwv2_api_not_found(lambda: apigw.get_stage(ApiId=apis[0], StageName="prod"))+ _delete_cfn_test_stack(cfn, stack_name)+ _assert_apigwv2_api_not_found(lambda: apigw.get_stage(ApiId=apis[1], StageName="prod"))+ assert all(apigw.get_api(ApiId=api)["ApiId"] == api for api in apis)+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ for api in apis:+ apigw.delete_api(ApiId=api)++[email protected]("replacement", [None, {"ApiId": "new-api"}, {"StageName": "beta"}])+def test_cfn_apigwv2_stage_legacy_physical_id_lifecycle(monkeypatch, replacement):+ """Old persisted api/name IDs still address the stage for updates and deletes."""+ from ministack.services import apigateway+ from ministack.services.cloudformation import provisioners++ monkeypatch.setattr(apigateway, "_stages", {})+ monkeypatch.setattr(apigateway, "_apis", {"legacy-api": {"apiId": "legacy-api", "protocolType": "HTTP"}})+ props = {"ApiId": "legacy-api", "StageName": "prod", "Description": "before"}+ provisioners._apigw_v2_stage_create("Stage", props, "legacy-stack")+ stage = apigateway._stages["legacy-api"]["prod"]+ legacy_id = "legacy-api/prod"+ updated = {**props, "Description": "after"}+ physical_id, _ = provisioners._apigw_v2_stage_update(legacy_id, props, updated, "legacy-stack")+ assert physical_id == legacy_id # Avoid treating migration as replacement cleanup.+ assert apigateway._stages["legacy-api"]["prod"] is stage+ assert stage["description"] == "after"+ if replacement:+ new_props = {**updated, **replacement}+ physical_id, _ = provisioners._apigw_v2_stage_update(physical_id, updated, new_props, "legacy-stack")+ assert physical_id == new_props["StageName"]+ assert "prod" not in apigateway._stages["legacy-api"]+ updated = new_props+ provisioners._apigw_v2_stage_delete(physical_id, updated)+ assert apigateway._stages[updated["ApiId"]] == {}++def test_cfn_apigwv2_full_http_api_stack(cfn, apigw):"""Full HTTP API stack with Api + Stage + Integration + Route deploys and cleans up."""template = {@@ -34624,7 +34727,7 @@ def _cfn_apigwv2_domain_template(domain, key):"DomainNameConfigurations": [{"EndpointType": "REGIONAL", "CertificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/11111111-2222-3333-4444-555555555555"}]}},"Mapping": {"Type": "AWS::ApiGatewayV2::ApiMapping", "DependsOn": ["Stage"], "Properties": {- "DomainName": {"Ref": "Domain"}, "ApiId": {"Ref": "Api"}, "Stage": "prod", "ApiMappingKey": key}},+ "DomainName": {"Ref": "Domain"}, "ApiId": {"Ref": "Api"}, "Stage": {"Ref": "Stage"}, "ApiMappingKey": key}},},"Outputs": {"Domain": {"Value": {"Ref": "Domain"}},@@ -34652,6 +34755,7 @@ def test_cfn_apigwv2_domain_name_and_api_mapping(cfn, apigw):mapping_id = _output(stack, "Mapping")assert _output(stack, "MappingId") == mapping_idassert apigw.get_api_mapping(DomainName=domain, ApiMappingId=mapping_id)["ApiMappingKey"] == "v1"+ assert apigw.get_api_mapping(DomainName=domain, ApiMappingId=mapping_id)["Stage"] == "prod"# ApiMappingKey updates in place.cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_apigwv2_domain_template(domain, "v2"))