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(cfn): AWS::CloudFront::KeyalueStore provisioner + KVS ImportSource + engine in-place update dispatch (#546)
Nahuel Nucera17a10ef46124
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 48171093..d8777c7e 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -95,6 +95,21 @@ def _delete_resource(resource_type: str, physical_id: str, props: dict):resource_type, physical_id)+def _update_resource(resource_type: str, physical_id: str, old_props: dict,+ new_props: dict, stack_name: str) -> tuple:+ """Update a provisioned resource in place when the type provides an ``update``+ handler. Falls back to ``create`` (which provisioners are expected to+ implement idempotently) when no explicit update handler is registered.+ Returns (physical_id, attributes).+ """+ handler = _RESOURCE_HANDLERS.get(resource_type)+ if handler and "update" in handler:+ return handler["update"](physical_id, old_props, new_props, stack_name)+ # No update handler — fall through to create. Most resource types make+ # their create idempotent; CFN never sees a fresh physical id this way.+ return _provision_resource(resource_type, physical_id, new_props, stack_name)++# ===========================================================================# Resource Provisioners# ===========================================================================@@ -2692,6 +2707,49 @@ def _cf_distribution_delete(physical_id, props):_cf._distributions.pop(physical_id, None)+# ---------------------------------------------------------------------------+# CloudFront KeyValueStore (management plane)+# ---------------------------------------------------------------------------++def _cf_kvs_create(logical_id, props, stack_name):+ name = props.get("Name") or _physical_name(stack_name, logical_id, max_len=64)+ arn = _cf._kvs_arn(name)+ if name not in _cf._kvstores:+ _cf._kvstores[name] = {+ "Id": new_uuid(),+ "Name": name,+ "Comment": props.get("Comment", ""),+ "ARN": arn,+ "Status": "READY",+ "LastModifiedTime": now_iso(),+ "ETag": new_uuid(),+ }+ record = _cf._kvstores[name]+ # Return refs the spec exposes via Fn::GetAtt: Arn, Id, Status.+ return name, {"Arn": arn, "Id": record["Id"], "Status": record["Status"]}+++def _cf_kvs_update(physical_id, old_props, new_props, stack_name):+ """Update the KVS record (Comment is the only mutable field per AWS spec).++ Name and ImportSource are create-only — a name change requires replacement,+ handled at the CFN engine level by destroy+create.+ """+ record = _cf._kvstores.get(physical_id)+ if not record:+ # KVS was deleted out-of-band — recreate to converge to the new state.+ return _cf_kvs_create(physical_id, new_props, stack_name)+ if "Comment" in new_props:+ record["Comment"] = new_props["Comment"] or ""+ record["ETag"] = new_uuid()+ record["LastModifiedTime"] = now_iso()+ return physical_id, {"Arn": record["ARN"], "Id": record["Id"], "Status": record["Status"]}+++def _cf_kvs_delete(physical_id, props):+ _cf._kvstores.pop(physical_id, None)++# ---------------------------------------------------------------------------# RDS DBCluster# ---------------------------------------------------------------------------@@ -2992,6 +3050,7 @@ _RESOURCE_HANDLERS = {"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},+ "AWS::CloudFront::KeyValueStore": {"create": _cf_kvs_create, "update": _cf_kvs_update, "delete": _cf_kvs_delete},"AWS::CloudWatch::Alarm": {"create": _cw_metric_alarm_create, "delete": _cw_metric_alarm_delete},"AWS::RDS::DBCluster": {"create": _rds_db_cluster_create, "delete": _rds_db_cluster_delete},# EventBridge Schedulerdiff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.pyindex b0c8b333..8d0420cc 100644--- a/ministack/services/cloudformation/stacks.py+++ b/ministack/services/cloudformation/stacks.py@@ -18,7 +18,7 @@ from .engine import (_resolve_refs,_topological_sort,)-from .provisioners import REGION, _delete_resource, _provision_resource+from .provisioners import REGION, _delete_resource, _provision_resource, _update_resourcelogger = logging.getLogger("cloudformation")@@ -114,9 +114,23 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,_add_event(stack_id, stack_name, logical_id, resource_type,f"{status_prefix}_IN_PROGRESS")- physical_id, attrs = _provision_resource(- resource_type, logical_id, resolved_props, stack_name+ # On stack update, route previously-provisioned resources through+ # the type's update handler when one exists; otherwise fall back+ # to (idempotent) create. New resources go straight to create.+ prev_resource = (+ previous_stack.get("_resources", {}).get(logical_id)+ if is_update and previous_stack else None)+ if prev_resource:+ old_pid = prev_resource.get("PhysicalResourceId", logical_id)+ old_props = prev_resource.get("Properties", {})+ physical_id, attrs = _update_resource(+ resource_type, old_pid, old_props, resolved_props, stack_name+ )+ else:+ physical_id, attrs = _provision_resource(+ resource_type, logical_id, resolved_props, stack_name+ )except Exception as exc:logger.error("Failed to provision %s (%s): %s",logical_id, resource_type, exc)diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.pyindex dffb4336..bcdb5be4 100644--- a/ministack/services/cloudfront.py+++ b/ministack/services/cloudfront.py@@ -1245,6 +1245,19 @@ def _create_kvs(headers, body):now = _now_iso()arn = _kvs_arn(name)+ # Optional ImportSource (create-only) — AWS spec: structure with required+ # SourceType + SourceARN. We accept and round-trip the values; data import+ # itself is not performed (no S3 fetch). Recorded so callers that+ # describe the store can see what was requested.+ import_source = None+ imp_el = _find(el, "ImportSource")+ if imp_el is not None:+ src_type = _text(imp_el, "SourceType") or ""+ src_arn = _text(imp_el, "SourceARN") or ""+ if not src_type or not src_arn:+ return _error("InvalidArgument", "ImportSource requires SourceType and SourceARN.", 400)+ import_source = {"SourceType": src_type, "SourceARN": src_arn}+kvs = {"Id": kvs_id,"Name": name,@@ -1253,6 +1266,7 @@ def _create_kvs(headers, body):"Status": "READY","LastModifiedTime": now,"ETag": etag,+ "ImportSource": import_source,}_kvstores[name] = kvsdiff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 7c72238b..786c263c 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -2656,3 +2656,74 @@ def test_cfn_apigwv2_full_http_api_stack_invokes_lambda(cfn, apigw, lam):cfn.delete_stack(StackName=stack_name)_wait_stack(cfn, stack_name)lam.delete_function(FunctionName=fname)+++# ---------------------------------------------------------------------------+# AWS::CloudFront::KeyValueStore — covers create, in-place update via+# UpdateStack (Comment change), and stack-delete teardown.+# ---------------------------------------------------------------------------++_KVS_TEMPLATE_V1 = """+AWSTemplateFormatVersion: '2010-09-09'+Resources:+ EdgeRoutes:+ Type: AWS::CloudFront::KeyValueStore+ Properties:+ Name: %(name)s+ Comment: initial+Outputs:+ KvsArn:+ Value: !GetAtt EdgeRoutes.Arn+ KvsId:+ Value: !GetAtt EdgeRoutes.Id+"""++_KVS_TEMPLATE_V2 = """+AWSTemplateFormatVersion: '2010-09-09'+Resources:+ EdgeRoutes:+ Type: AWS::CloudFront::KeyValueStore+ Properties:+ Name: %(name)s+ Comment: updated by UpdateStack+Outputs:+ KvsArn:+ Value: !GetAtt EdgeRoutes.Arn+"""+++def test_cfn_cloudfront_keyvaluestore_create_update_delete(cfn, cloudfront):+ """AWS::CloudFront::KeyValueStore: create via CFN, update Comment via+ UpdateStack (in-place; AWS spec only allows Comment to change), describe+ through the native CloudFront API to confirm the new Comment, then+ delete via the stack."""+ stack_name = f"e2e-kvs-{_uuid_mod.uuid4().hex[:8]}"+ kvs_name = f"cfnkvs-{_uuid_mod.uuid4().hex[:8]}"++ cfn.create_stack(StackName=stack_name, TemplateBody=_KVS_TEMPLATE_V1 % {"name": kvs_name})+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE"++ # Outputs carry the ARN + Id from the provisioner.+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}+ assert outputs["KvsArn"].endswith(f":key-value-store/{kvs_name}")+ assert outputs["KvsId"]++ # Native describe sees the create-time Comment.+ desc = cloudfront.describe_key_value_store(Name=kvs_name)+ assert desc["KeyValueStore"]["Comment"] == "initial"++ # UpdateStack changes the Comment in place — same physical name, no replacement.+ cfn.update_stack(StackName=stack_name, TemplateBody=_KVS_TEMPLATE_V2 % {"name": kvs_name})+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE"++ desc = cloudfront.describe_key_value_store(Name=kvs_name)+ assert desc["KeyValueStore"]["Comment"] == "updated by UpdateStack"++ # Stack delete cleans up the KVS.+ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+ with pytest.raises(ClientError) as exc:+ cloudfront.describe_key_value_store(Name=kvs_name)+ assert exc.value.response["Error"]["Code"] == "EntityNotFound"diff --git a/tests/test_cloudfront.py b/tests/test_cloudfront.pyindex c4775cab..a88e4589 100644--- a/tests/test_cloudfront.py+++ b/tests/test_cloudfront.py@@ -829,3 +829,31 @@ def test_kvs_delete_in_use(cloudfront):cloudfront.delete_key_value_store(Name=kvs_name, IfMatch=kvs_etag)assert exc.value.response["Error"]["Code"] == "CannotDeleteEntityWhileInUse"assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409+++def test_kvs_create_with_import_source(cloudfront):+ """ImportSource (create-only optional input, AWS spec requires SourceType ++ SourceARN) is accepted and round-tripped. Ministack records it but does not+ actually fetch from S3 — same stance as other side-effect creates."""+ name = f"kvs-imp-{_uuid_mod.uuid4().hex[:8]}"+ bucket_arn = "arn:aws:s3:::seed-bucket/initial.json"+ resp = cloudfront.create_key_value_store(+ Name=name,+ Comment="seeded from S3",+ ImportSource={"SourceType": "S3", "SourceARN": bucket_arn},+ )+ assert resp["KeyValueStore"]["Name"] == name+ assert resp["KeyValueStore"]["Status"] == "READY"+++def test_kvs_create_with_import_source_missing_field_rejected(cloudfront):+ """ImportSource requires both SourceType and SourceARN per AWS spec; either+ missing is InvalidArgument."""+ name = f"kvs-impbad-{_uuid_mod.uuid4().hex[:8]}"+ with pytest.raises(ClientError) as exc:+ cloudfront.create_key_value_store(+ Name=name,+ Comment="bad import",+ ImportSource={"SourceType": "S3", "SourceARN": ""},+ )+ assert exc.value.response["Error"]["Code"] == "InvalidArgument"