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(cfn): honour KeySpec and update semantics on AWS::KMS::Key (#1304)
Michael Smithe392df15787b
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 7fb79bda..9a310b8e 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -3209,28 +3209,119 @@ def _iam_managed_policy_delete(physical_id, props):# --- KMS resource provisioners ----def _kms_key_create(logical_id, props, stack_name):- key_id = new_uuid()- arn = f"arn:aws:kms:{get_region()}:{get_account_id()}:key/{key_id}"- _kms._keys[key_id] = {- "KeyId": key_id,- "Arn": arn,- "KeyState": "Enabled",- "Enabled": True,- "KeySpec": "SYMMETRIC_DEFAULT",+# AWS::KMS::Key refuses to update four properties in place: "If you change the+# value of the KeySpec, KeyUsage, Origin, or MultiRegion properties of an+# existing KMS key, the update request fails, regardless of the value of the+# UpdateReplacePolicy attribute." Defaults matter here — omitting KeyUsage and+# spelling out ENCRYPT_DECRYPT are the same key, not a change.+_KMS_IMMUTABLE_PROPS = {+ "KeySpec": "SYMMETRIC_DEFAULT",+ "KeyUsage": "ENCRYPT_DECRYPT",+ "Origin": "AWS_KMS",+ "MultiRegion": False,+}+++def _kms_tags(props):+ """CloudFormation tags are {Key, Value}; the KMS API stores {TagKey, TagValue}."""+ return [+ {"TagKey": t.get("Key", ""), "TagValue": t.get("Value", "")}+ for t in (props.get("Tags") or [])+ ]+++def _kms_create_key_payload(props):+ """Translate AWS::KMS::Key template properties into a CreateKey request.++ CloudFormation spells the policy ``KeyPolicy`` and accepts it as a JSON+ object; CreateKey takes a ``Policy`` string. The rest share their names.+ """+ payload = {+ "KeySpec": props.get(+ "KeySpec", props.get("CustomerMasterKeySpec", "SYMMETRIC_DEFAULT")+ ),"KeyUsage": props.get("KeyUsage", "ENCRYPT_DECRYPT"),"Description": props.get("Description", ""),- "CreationDate": __import__("time").time(),- "Origin": "AWS_KMS",- "_symmetric_key": __import__("os").urandom(32),- "EncryptionAlgorithms": ["SYMMETRIC_DEFAULT"],- "SigningAlgorithms": [],+ "Tags": _kms_tags(props),}- return key_id, {"Arn": arn, "KeyId": key_id}+ policy = props.get("KeyPolicy")+ if policy is not None:+ payload["Policy"] = policy if isinstance(policy, str) else json.dumps(policy)+ if props.get("Origin"):+ payload["Origin"] = props["Origin"]+ if props.get("MultiRegion"):+ payload["MultiRegion"] = True+ return payload+++def _kms_apply_key_props(rec, props):+ """Apply the template properties CreateKey has no parameter for."""+ # "When Enabled is true, the key state of the KMS key is Enabled. When+ # Enabled is false, the key state of the KMS key is Disabled. The default+ # value is true." A key already scheduled for deletion is left alone.+ if rec.get("KeyState") != "PendingDeletion":+ if props.get("Enabled") is False:+ rec["Enabled"] = False+ rec["KeyState"] = "Disabled"+ else:+ rec["Enabled"] = True+ rec["KeyState"] = "Enabled"+ # "By default, automatic key rotation is not enabled." The rotation period+ # defaults to 365 days.+ if props.get("EnableKeyRotation"):+ rec["KeyRotationEnabled"] = True+ rec["RotationPeriodInDays"] = props.get("RotationPeriodInDays", 365)+ else:+ rec["KeyRotationEnabled"] = False+++def _kms_key_create(logical_id, props, stack_name):+ status, _headers, body = _kms._create_key(_kms_create_key_payload(props))+ if status != 200:+ # Fail the stack rather than provisioning a key of a different type than+ # the template asked for — a silently symmetric key only surfaces later,+ # as an UnsupportedOperationException from Sign.+ raise Exception(+ f"AWS::KMS::Key {logical_id}: {json.loads(body).get('message')}"+ )+ rec = _kms._resolve_key(json.loads(body)["KeyMetadata"]["KeyId"])+ _kms_apply_key_props(rec, props)+ return rec["KeyId"], {"Arn": rec["Arn"], "KeyId": rec["KeyId"]}+++def _kms_key_update(physical_id, old_props, new_props, stack_name):+ rec = _kms._resolve_key(physical_id)+ if not rec:+ # The key went away outside CloudFormation; provision a replacement+ # rather than failing the stack update.+ return _kms_key_create(physical_id, new_props, stack_name)++ for prop, default in _KMS_IMMUTABLE_PROPS.items():+ if old_props.get(prop, default) != new_props.get(prop, default):+ raise Exception(+ f"AWS::KMS::Key {physical_id}: {prop} cannot be changed after "+ "the KMS key is created"+ )++ rec["Description"] = new_props.get("Description", "")+ policy = new_props.get("KeyPolicy")+ if policy is not None:+ rec["Policy"] = policy if isinstance(policy, str) else json.dumps(policy)+ rec["Tags"] = _kms_tags(new_props)+ _kms_apply_key_props(rec, new_props)+ return physical_id, {"Arn": rec["Arn"], "KeyId": rec["KeyId"]}def _kms_key_delete(physical_id, props):- _kms._keys.pop(physical_id, None)+ # "When you remove a KMS key from a CloudFormation stack, AWS KMS schedules+ # the KMS key for deletion and starts the mandatory waiting period." The key+ # stays resolvable in PendingDeletion state, where cryptographic operations+ # correctly fail, instead of vanishing.+ if _kms._resolve_key(physical_id):+ _kms._schedule_key_deletion({+ "KeyId": physical_id,+ "PendingWindowInDays": props.get("PendingWindowInDays", 30),+ })def _kms_alias_create(logical_id, props, stack_name):@@ -5442,7 +5533,11 @@ _RESOURCE_HANDLERS = {"AWS::ElasticLoadBalancingV2::ListenerRule": {"create": _elbv2_listener_rule_create, "delete": _elbv2_listener_rule_delete},"AWS::CodeBuild::Project": {"create": _codebuild_project_create, "delete": _codebuild_project_delete},"AWS::IAM::ManagedPolicy": {"create": _iam_managed_policy_create, "delete": _iam_managed_policy_delete},- "AWS::KMS::Key": {"create": _kms_key_create, "delete": _kms_key_delete},+ "AWS::KMS::Key": {+ "create": _kms_key_create,+ "update": _kms_key_update,+ "delete": _kms_key_delete,+ },"AWS::KMS::Alias": {"create": _kms_alias_create, "delete": _kms_alias_delete},"AWS::EC2::VPC": {"create": _ec2_vpc_create, "delete": _ec2_vpc_delete},"AWS::EC2::VPCEndpoint": {diff --git a/ministack/services/kms.py b/ministack/services/kms.pyindex b6451aa4..4e559297 100644--- a/ministack/services/kms.py+++ b/ministack/services/kms.py@@ -185,7 +185,7 @@ def _arn(key_id):def _key_metadata(rec):- return {+ meta = {"KeyId": rec["KeyId"],"Arn": rec["Arn"],"CreationDate": rec["CreationDate"],@@ -200,6 +200,11 @@ def _key_metadata(rec):"EncryptionAlgorithms": rec.get("EncryptionAlgorithms", []),"SigningAlgorithms": rec.get("SigningAlgorithms", []),}+ # "This value is present only when the KMS key is scheduled for deletion,+ # that is, when its KeyState is PendingDeletion."+ if "DeletionDate" in rec:+ meta["DeletionDate"] = rec["DeletionDate"]+ return metadef _key_ref_from_arn(key_id_or_arn):@@ -312,13 +317,12 @@ def _create_key(data):rec["_symmetric_key"] = os.urandom(32)rec["EncryptionAlgorithms"] = ["SYMMETRIC_DEFAULT"]rec["SigningAlgorithms"] = []- elif key_spec in ("RSA_2048", "RSA_4096"):+ elif key_spec in ("RSA_2048", "RSA_3072", "RSA_4096"):err = _require_crypto("CreateKey")if err:return err- bits = 2048 if key_spec == "RSA_2048" else 4096private_key = rsa.generate_private_key(- public_exponent=65537, key_size=bits+ public_exponent=65537, key_size=int(key_spec.split("_")[1]))rec["_private_key"] = private_keyrec["_public_key_der"] = private_key.public_key().public_bytes(@@ -898,8 +902,7 @@ def _generate_data_key_pair_common(data, action):and nothing else.KeyPairSpec follows the real AWS enum, minus SM2 (which _create_key does not- implement either). Note this is a superset of _create_key's asymmetric specs:- _create_key still lacks RSA_3072, a pre-existing gap not repeated here.+ implement either). The asymmetric specs now match _create_key's exactly."""key_id = data.get("KeyId", "")rec = _resolve_key(key_id)diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 4dd327c2..58140f45 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -7332,3 +7332,222 @@ def test_cfn_s3tables_table_schema_from_iceberg_metadata(cfn, s3tables):cfn.delete_stack(StackName=stack_name)_wait_stack(cfn, stack_name)+++# ── AWS::KMS::Key ───────────────────────────────────────────────────────────+# Property names, defaults and update behaviour follow the resource reference:+# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-key.html++# The Id is deliberately not "key-default-1" — that is what CreateKey generates+# when no policy is supplied, so a default would satisfy the assertion below even+# if the template's KeyPolicy were dropped on the floor.+_KMS_KEY_POLICY = {+ "Version": "2012-10-17",+ "Id": "cfn-supplied-key-policy",+ "Statement": [+ {+ "Sid": "Enable IAM User Permissions",+ "Effect": "Allow",+ "Principal": {"AWS": "arn:aws:iam::000000000000:root"},+ "Action": "kms:*",+ "Resource": "*",+ }+ ],+}+++def _kms_key_template(props):+ return json.dumps(+ {+ "Resources": {"Key": {"Type": "AWS::KMS::Key", "Properties": props}},+ "Outputs": {+ "KeyRef": {"Value": {"Ref": "Key"}},+ "KeyArn": {"Value": {"Fn::GetAtt": ["Key", "Arn"]}},+ },+ }+ )+++def _kms_stack_outputs(cfn, stack_name):+ stack = cfn.describe_stacks(StackName=stack_name)["Stacks"][0]+ return {o["OutputKey"]: o["OutputValue"] for o in stack.get("Outputs", [])}+++def test_cfn_kms_key_asymmetric_key_spec_is_honored(cfn, kms_client):+ """An RSA_2048 SIGN_VERIFY key declared in a template must actually sign.++ The provisioner used to hardcode SYMMETRIC_DEFAULT, so the stack reached+ CREATE_COMPLETE and DescribeKey reported KeyUsage=SIGN_VERIFY while the key+ underneath was symmetric — Sign then failed with UnsupportedOperationException.+ """+ stack_name = f"cfn-kms-rsa-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(+ StackName=stack_name,+ TemplateBody=_kms_key_template(+ {+ "KeySpec": "RSA_2048",+ "KeyUsage": "SIGN_VERIFY",+ "Description": "signing key",+ "KeyPolicy": _KMS_KEY_POLICY,+ }+ ),+ )+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")++ out = _kms_stack_outputs(cfn, stack_name)+ meta = kms_client.describe_key(KeyId=out["KeyArn"])["KeyMetadata"]+ assert meta["KeySpec"] == "RSA_2048"+ assert meta["KeyUsage"] == "SIGN_VERIFY"+ assert "RSASSA_PSS_SHA_256" in meta["SigningAlgorithms"]+ # Ref returns the key id; GetAtt exposes Arn and KeyId.+ assert out["KeyRef"] == meta["KeyId"]+ assert out["KeyArn"] == meta["Arn"]++ message = b"cfn-kms-parity"+ signature = kms_client.sign(+ KeyId=out["KeyArn"],+ Message=message,+ MessageType="RAW",+ SigningAlgorithm="RSASSA_PSS_SHA_256",+ )["Signature"]+ assert kms_client.verify(+ KeyId=out["KeyArn"],+ Message=message,+ MessageType="RAW",+ Signature=signature,+ SigningAlgorithm="RSASSA_PSS_SHA_256",+ )["SignatureValid"]+ assert kms_client.get_public_key(KeyId=out["KeyArn"])["PublicKey"]++ # The key policy is CFN's `KeyPolicy`, stored as the API's `Policy`.+ policy = json.loads(+ kms_client.get_key_policy(KeyId=out["KeyArn"], PolicyName="default")["Policy"]+ )+ assert policy["Id"] == "cfn-supplied-key-policy"++ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+++def test_cfn_kms_key_tags_rotation_and_enabled(cfn, kms_client):+ """Tags, EnableKeyRotation and Enabled:false are applied at create time."""+ stack_name = f"cfn-kms-props-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(+ StackName=stack_name,+ TemplateBody=_kms_key_template(+ {+ "KeyPolicy": _KMS_KEY_POLICY,+ "Enabled": False,+ "EnableKeyRotation": True,+ "RotationPeriodInDays": 180,+ # CloudFormation tags are Key/Value; KMS stores TagKey/TagValue.+ "Tags": [{"Key": "env", "Value": "test"}],+ }+ ),+ )+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")++ arn = _kms_stack_outputs(cfn, stack_name)["KeyArn"]+ meta = kms_client.describe_key(KeyId=arn)["KeyMetadata"]+ assert meta["KeySpec"] == "SYMMETRIC_DEFAULT"+ assert meta["KeyState"] == "Disabled"+ assert meta["Enabled"] is False++ rotation = kms_client.get_key_rotation_status(KeyId=arn)+ assert rotation["KeyRotationEnabled"] is True+ assert rotation["RotationPeriodInDays"] == 180++ tags = kms_client.list_resource_tags(KeyId=arn)["Tags"]+ assert tags == [{"TagKey": "env", "TagValue": "test"}]++ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+++def test_cfn_kms_key_mutable_property_updates_in_place(cfn, kms_client):+ """Description is 'Update requires: No interruption' — the key is not replaced."""+ stack_name = f"cfn-kms-upd-{_uuid_mod.uuid4().hex[:8]}"+ props = {"KeySpec": "RSA_2048", "KeyUsage": "SIGN_VERIFY", "Description": "v1"}+ cfn.create_stack(StackName=stack_name, TemplateBody=_kms_key_template(props))+ _wait_stack(cfn, stack_name)+ original_id = _kms_stack_outputs(cfn, stack_name)["KeyRef"]++ cfn.update_stack(+ StackName=stack_name,+ TemplateBody=_kms_key_template({**props, "Description": "v2"}),+ )+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")++ assert _kms_stack_outputs(cfn, stack_name)["KeyRef"] == original_id+ meta = kms_client.describe_key(KeyId=original_id)["KeyMetadata"]+ assert meta["Description"] == "v2"+ # The key material survived the update — signatures stay verifiable.+ assert meta["KeySpec"] == "RSA_2048"++ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+++def test_cfn_kms_key_immutable_property_change_is_rejected(cfn, kms_client):+ """"If you change the value of the KeySpec ... the update request fails."++ Without an update handler the engine falls back to `create`, minting a fresh+ key pair and silently invalidating every signature made with the old one.+ """+ stack_name = f"cfn-kms-immut-{_uuid_mod.uuid4().hex[:8]}"+ props = {"KeySpec": "RSA_2048", "KeyUsage": "SIGN_VERIFY"}+ cfn.create_stack(StackName=stack_name, TemplateBody=_kms_key_template(props))+ _wait_stack(cfn, stack_name)+ original_id = _kms_stack_outputs(cfn, stack_name)["KeyRef"]++ cfn.update_stack(+ StackName=stack_name,+ TemplateBody=_kms_key_template({**props, "KeySpec": "RSA_4096"}),+ )+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] != "UPDATE_COMPLETE"++ # The original key is untouched: same id, same spec, still usable.+ meta = kms_client.describe_key(KeyId=original_id)["KeyMetadata"]+ assert meta["KeySpec"] == "RSA_2048"+ assert meta["KeyState"] == "Enabled"++ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+++def test_cfn_kms_key_unsupported_key_spec_fails_the_stack(cfn):+ """An unimplemented spec must fail the stack, not quietly become symmetric."""+ stack_name = f"cfn-kms-hmac-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(+ StackName=stack_name,+ TemplateBody=_kms_key_template(+ {"KeySpec": "HMAC_256", "KeyUsage": "GENERATE_VERIFY_MAC"}+ ),+ )+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] != "CREATE_COMPLETE"++ cfn.delete_stack(StackName=stack_name)+++def test_cfn_kms_key_delete_schedules_deletion(cfn, kms_client):+ """Removing a key from a stack schedules deletion; it does not vanish."""+ stack_name = f"cfn-kms-del-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(+ StackName=stack_name,+ TemplateBody=_kms_key_template({"PendingWindowInDays": 7}),+ )+ _wait_stack(cfn, stack_name)+ key_id = _kms_stack_outputs(cfn, stack_name)["KeyRef"]++ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)++ meta = kms_client.describe_key(KeyId=key_id)["KeyMetadata"]+ assert meta["KeyState"] == "PendingDeletion"+ assert meta["Enabled"] is False+ assert "DeletionDate" in metadiff --git a/tests/test_kms.py b/tests/test_kms.pyindex 2e98a5f9..91e97e79 100644--- a/tests/test_kms.py+++ b/tests/test_kms.py@@ -1308,3 +1308,26 @@ def test_kms_disabled_key_blocks_encrypt(kms_client):kms_client.disable_key(KeyId=key_id)with pytest.raises(kms_client.exceptions.DisabledException):kms_client.encrypt(KeyId=key_id, Plaintext=b"test")+++def test_kms_create_key_rsa_3072_signs(kms_client):+ """RSA_3072 is in the CreateKey KeySpec enum and GenerateDataKeyPair already+ produced RSA_3072 pairs; CreateKey used to reject it."""+ meta = kms_client.create_key(KeySpec="RSA_3072", KeyUsage="SIGN_VERIFY")["KeyMetadata"]+ assert meta["KeySpec"] == "RSA_3072"+ assert "RSASSA_PSS_SHA_256" in meta["SigningAlgorithms"]++ message = b"rsa-3072-message"+ signature = kms_client.sign(+ KeyId=meta["KeyId"],+ Message=message,+ MessageType="RAW",+ SigningAlgorithm="RSASSA_PSS_SHA_256",+ )["Signature"]+ assert kms_client.verify(+ KeyId=meta["KeyId"],+ Message=message,+ MessageType="RAW",+ Signature=signature,+ SigningAlgorithm="RSASSA_PSS_SHA_256",+ )["SignatureValid"]