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
CloudFormation: support API Gateway (v1) API keys and usage plans (#1425)
ryan-bennettb0bad6789b84
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1d96d2d0..6a18c2ce 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Added+- **CloudFormation — API Gateway (v1) API keys and usage plans** — `AWS::ApiGateway::ApiKey`, `AWS::ApiGateway::UsagePlan`, and `AWS::ApiGateway::UsagePlanKey` failed stack creation with `Unsupported resource type`, even though the runtime `CreateApiKey` / `CreateUsagePlan` APIs were already served. The three resource types now provision through those same stores: an `ApiKey` supports a pinned `Value`, `Enabled`, and `StageKeys`, updates `Name` / `Description` / `Enabled` in place, and exposes both `Ref` and `Fn::GetAtt APIKeyId` as the key id; a `UsagePlan` maps `Throttle` / `Quota` / `ApiStages` and returns its id via `Ref` and `Fn::GetAtt Id`; a `UsagePlanKey` associates a key with a plan and is torn down from the plan on delete. This unblocks CDK `RestApi` / `ApiKey` constructs and Terraform `aws_api_gateway_api_key` deployed through CloudFormation. Contributed by @ryan-bennett.- **AWS IoT Jobs — control plane and device data plane** — `CreateJob` fell through to `Unsupported IoT path` and the `iot-jobs-data` endpoint did not exist, so device OTA loops could not be rehearsed locally. The `iot` service now serves the nine job operations and a new `iot-jobs-data` service the four device ones (incl. the `$next` sentinel), sharing one store and the AWS execution state machine. A `documentSource` job gets a placeholder, not the S3 object. Contributed by @iot-rocket.### Fixed- **CloudFormation — `AWS::IoT::Policy` updates apply instead of rolling the stack back** — the type had a create and a delete but no update handler, so a stack update fell through to create, hit `ResourceAlreadyExistsException` on the policy it had provisioned itself, and rolled back with the document unchanged: an IoT policy could be deployed once and never edited again. A changed `PolicyDocument` is now a no-interruption update stored as a new policy version and made the default, so `Ref` keeps naming the same policy and `GetPolicy` returns the new document; a changed `PolicyName` is a replacement, creating the policy under the new name and removing the old one. Because IoT caps a policy at five versions, the update prunes the oldest non-default versions before storing a new document, as the CloudFormation handler does on AWS.diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 7068d9db..7c959fc8 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -2296,6 +2296,163 @@ def _apigw_stage_delete(physical_id, props):_apigw_v1._delete_stage(api_id, stage_name)+# --- API Gateway ApiKey / UsagePlan (v1) ---++def _apigw_tag_map(raw):+ """Normalize CFN ``Tags`` (a map, or a list of {Key, Value}) to a dict."""+ if isinstance(raw, dict):+ return dict(raw)+ return {t["Key"]: t["Value"] for t in raw or []}+++def _apigw_throttle(raw):+ """Map a CFN ThrottleSettings block to the API Gateway wire shape."""+ if not raw:+ return {}+ out = {}+ if "BurstLimit" in raw:+ out["burstLimit"] = raw["BurstLimit"]+ if "RateLimit" in raw:+ out["rateLimit"] = raw["RateLimit"]+ return out+++def _apigw_quota(raw):+ """Map a CFN QuotaSettings block to the API Gateway wire shape."""+ if not raw:+ return {}+ out = {}+ for cfn_key, api_key in (("Limit", "limit"), ("Offset", "offset"), ("Period", "period")):+ if cfn_key in raw:+ out[api_key] = raw[cfn_key]+ return out+++def _apigw_api_key_create(logical_id, props, stack_name):+ """Provision an ``AWS::ApiGateway::ApiKey``.++ Ref returns the generated key id; ``Fn::GetAtt APIKeyId`` returns the same+ id, matching the AWS CloudFormation resource contract. The runtime create+ always mints a fresh value, so an explicit ``Value`` is applied afterwards+ to honor a caller-pinned key.+ """+ data = {+ "name": props.get("Name") or _physical_name(stack_name, logical_id),+ "description": props.get("Description", ""),+ "enabled": props.get("Enabled", True),+ "stageKeys": [+ {"restApiId": sk.get("RestApiId", ""), "stageName": sk.get("StageName", "")}+ for sk in props.get("StageKeys", [])+ ],+ "tags": _apigw_tag_map(props.get("Tags")),+ }+ status, _headers, body = _apigw_v1._create_api_key(data)+ if status >= 400:+ raise ValueError(f"AWS::ApiGateway::ApiKey create failed: {body!r}")+ api_key = json.loads(body)+ key_id = api_key.get("id", "")+ value = props.get("Value")+ if value:+ stored = _apigw_v1._api_keys.get(key_id)+ if stored is not None:+ stored["value"] = value+ customer_id = props.get("CustomerId")+ if customer_id:+ stored = _apigw_v1._api_keys.get(key_id)+ if stored is not None:+ stored["customerId"] = customer_id+ return key_id, {"APIKeyId": key_id}+++def _apigw_api_key_update(physical_id, old_props, new_props, stack_name):+ # Value is immutable in CloudFormation; changing it replaces the key.+ # Everything else updates the existing record in place.+ if old_props.get("Value") != new_props.get("Value"):+ _apigw_v1._delete_api_key(physical_id)+ return _apigw_api_key_create(physical_id, new_props, stack_name)+ key = _apigw_v1._api_keys.get(physical_id)+ if key is None:+ return _apigw_api_key_create(physical_id, new_props, stack_name)+ if new_props.get("Name"):+ key["name"] = new_props["Name"]+ key["description"] = new_props.get("Description", "")+ key["enabled"] = new_props.get("Enabled", True)+ key["customerId"] = new_props.get("CustomerId", key.get("customerId", ""))+ key["lastUpdatedDate"] = _apigw_v1._now_unix()+ return physical_id, {"APIKeyId": physical_id}+++def _apigw_api_key_delete(physical_id, props):+ # _delete_api_key is idempotent — a missing key returns a 404 tuple that we+ # ignore, so repeated or post-reset deletes converge cleanly.+ _apigw_v1._delete_api_key(physical_id)+++def _apigw_usage_plan_body(props):+ return {+ "description": props.get("Description", ""),+ "apiStages": [+ {+ "apiId": stage.get("ApiId", ""),+ "stage": stage.get("Stage", ""),+ "throttle": stage.get("Throttle", {}),+ }+ for stage in props.get("ApiStages", [])+ ],+ "throttle": _apigw_throttle(props.get("Throttle")),+ "quota": _apigw_quota(props.get("Quota")),+ "tags": _apigw_tag_map(props.get("Tags")),+ }+++def _apigw_usage_plan_create(logical_id, props, stack_name):+ """Provision an ``AWS::ApiGateway::UsagePlan``.++ Ref and ``Fn::GetAtt Id`` both return the generated usage plan id.+ """+ data = {"name": props.get("UsagePlanName") or _physical_name(stack_name, logical_id)}+ data.update(_apigw_usage_plan_body(props))+ status, _headers, body = _apigw_v1._create_usage_plan(data)+ if status >= 400:+ raise ValueError(f"AWS::ApiGateway::UsagePlan create failed: {body!r}")+ plan = json.loads(body)+ plan_id = plan.get("id", "")+ return plan_id, {"Id": plan_id}+++def _apigw_usage_plan_update(physical_id, old_props, new_props, stack_name):+ plan = _apigw_v1._usage_plans.get(physical_id)+ if plan is None:+ return _apigw_usage_plan_create(physical_id, new_props, stack_name)+ if new_props.get("UsagePlanName"):+ plan["name"] = new_props["UsagePlanName"]+ plan.update(_apigw_usage_plan_body(new_props))+ return physical_id, {"Id": physical_id}+++def _apigw_usage_plan_delete(physical_id, props):+ _apigw_v1._delete_usage_plan(physical_id)+++def _apigw_usage_plan_key_create(logical_id, props, stack_name):+ """Provision an ``AWS::ApiGateway::UsagePlanKey`` (associate a key with a plan).++ Ref returns the API key id; the delete handler reads the usage plan id back+ from the resource's own properties, so the physical id need not encode it.+ """+ plan_id = props.get("UsagePlanId", "")+ key_id = props.get("KeyId", "")+ data = {"keyId": key_id, "keyType": props.get("KeyType", "API_KEY")}+ status, _headers, body = _apigw_v1._create_usage_plan_key(plan_id, data)+ if status >= 400:+ raise ValueError(f"AWS::ApiGateway::UsagePlanKey create failed: {body!r}")+ return key_id, {}+++def _apigw_usage_plan_key_delete(physical_id, props):+ _apigw_v1._delete_usage_plan_key(props.get("UsagePlanId", ""), props.get("KeyId", ""))++# --- API Gateway BasePathMapping ---def _apigw_base_path_mapping_identity(props):@@ -5793,6 +5950,20 @@ _RESOURCE_HANDLERS = {"AWS::ApiGateway::Authorizer": {"create": _apigw_authorizer_create, "delete": _apigw_authorizer_delete},"AWS::ApiGateway::Deployment": {"create": _apigw_deployment_create, "delete": _apigw_deployment_delete},"AWS::ApiGateway::Stage": {"create": _apigw_stage_create, "delete": _apigw_stage_delete},+ "AWS::ApiGateway::ApiKey": {+ "create": _apigw_api_key_create,+ "update": _apigw_api_key_update,+ "delete": _apigw_api_key_delete,+ },+ "AWS::ApiGateway::UsagePlan": {+ "create": _apigw_usage_plan_create,+ "update": _apigw_usage_plan_update,+ "delete": _apigw_usage_plan_delete,+ },+ "AWS::ApiGateway::UsagePlanKey": {+ "create": _apigw_usage_plan_key_create,+ "delete": _apigw_usage_plan_key_delete,+ },"AWS::ApiGateway::BasePathMapping": {"create": _apigw_base_path_mapping_create,"update": _apigw_base_path_mapping_update,diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 2bc7bb62..6925ebcb 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -6617,6 +6617,162 @@ def test_cfn_apigateway_documentation_version_lifecycle(cfn, apigw_v1):apigw_v1.delete_rest_api(restApiId=api_id)+def test_cfn_apigateway_api_key_lifecycle(cfn, apigw_v1):+ """ApiKey supports create, a pinned Value, Ref/GetAtt, in-place update, delete.++ Regression: the resource type previously failed stack creation with+ ``Unsupported resource type: AWS::ApiGateway::ApiKey``.+ """+ suffix = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-api-key-{suffix}"+ pinned_value = f"pinnedkeyvalue{suffix}0000000000"+ stack_deleted = False++ def template(description, enabled):+ return {+ "Resources": {+ "ApiKey": {+ "Type": "AWS::ApiGateway::ApiKey",+ "Properties": {+ "Name": f"key-{suffix}",+ "Description": description,+ "Enabled": enabled,+ "Value": pinned_value,+ },+ },+ },+ "Outputs": {+ "RefId": {"Value": {"Ref": "ApiKey"}},+ "GetAttId": {"Value": {"Fn::GetAtt": ["ApiKey", "APIKeyId"]}},+ },+ }++ def physical_id():+ detail = cfn.describe_stack_resource(+ StackName=stack_name,+ LogicalResourceId="ApiKey",+ )["StackResourceDetail"]+ return detail["PhysicalResourceId"]++ try:+ cfn.create_stack(+ StackName=stack_name,+ TemplateBody=json.dumps(template("Created", True)),+ )+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")++ created_id = physical_id()+ outputs = {item["OutputKey"]: item["OutputValue"] for item in stack["Outputs"]}+ assert outputs == {"RefId": created_id, "GetAttId": created_id}++ created = apigw_v1.get_api_key(apiKey=created_id, includeValue=True)+ assert created["name"] == f"key-{suffix}"+ assert created["description"] == "Created"+ assert created["enabled"] is True+ assert created["value"] == pinned_value++ # Description and Enabled update in place without replacing the key.+ cfn.update_stack(+ StackName=stack_name,+ TemplateBody=json.dumps(template("Updated", False)),+ )+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ assert physical_id() == created_id+ updated = apigw_v1.get_api_key(apiKey=created_id)+ assert updated["description"] == "Updated"+ assert updated["enabled"] is False++ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+ stack_deleted = True+ with pytest.raises(ClientError):+ apigw_v1.get_api_key(apiKey=created_id)+ finally:+ if not stack_deleted:+ try:+ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+ except ClientError:+ pass+++def test_cfn_apigateway_usage_plan_and_key_lifecycle(cfn, apigw_v1):+ """UsagePlan and UsagePlanKey provision, expose ids, associate a key, and delete.++ Regression: both resource types previously failed stack creation with+ ``Unsupported resource type``.+ """+ suffix = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-usage-plan-{suffix}"+ stack_deleted = False++ template = {+ "Resources": {+ "ApiKey": {+ "Type": "AWS::ApiGateway::ApiKey",+ "Properties": {"Name": f"plan-key-{suffix}", "Enabled": True},+ },+ "UsagePlan": {+ "Type": "AWS::ApiGateway::UsagePlan",+ "Properties": {+ "UsagePlanName": f"plan-{suffix}",+ "Description": "integration plan",+ "Throttle": {"BurstLimit": 20, "RateLimit": 10},+ "Quota": {"Limit": 1000, "Period": "MONTH"},+ },+ },+ "UsagePlanKey": {+ "Type": "AWS::ApiGateway::UsagePlanKey",+ "Properties": {+ "KeyId": {"Ref": "ApiKey"},+ "KeyType": "API_KEY",+ "UsagePlanId": {"Ref": "UsagePlan"},+ },+ },+ },+ "Outputs": {+ "PlanRef": {"Value": {"Ref": "UsagePlan"}},+ "PlanGetAtt": {"Value": {"Fn::GetAtt": ["UsagePlan", "Id"]}},+ "KeyRef": {"Value": {"Ref": "ApiKey"}},+ "PlanKeyRef": {"Value": {"Ref": "UsagePlanKey"}},+ },+ }++ try:+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ outputs = {item["OutputKey"]: item["OutputValue"] for item in stack["Outputs"]}++ plan_id = outputs["PlanRef"]+ assert outputs["PlanGetAtt"] == plan_id+ # UsagePlanKey Ref is the associated API key id.+ assert outputs["PlanKeyRef"] == outputs["KeyRef"]++ plan = apigw_v1.get_usage_plan(usagePlanId=plan_id)+ assert plan["name"] == f"plan-{suffix}"+ assert plan["throttle"] == {"burstLimit": 20, "rateLimit": 10}+ assert plan["quota"]["limit"] == 1000 and plan["quota"]["period"] == "MONTH"++ keys = apigw_v1.get_usage_plan_keys(usagePlanId=plan_id)["items"]+ assert [k["id"] for k in keys] == [outputs["KeyRef"]]++ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+ stack_deleted = True+ with pytest.raises(ClientError):+ apigw_v1.get_usage_plan(usagePlanId=plan_id)+ finally:+ if not stack_deleted:+ try:+ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+ except ClientError:+ pass++# ---------------------------------------------------------------------------# ApiGatewayV1 Integration with OpenAPI spec parsing# ---------------------------------------------------------------------------