Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(ec2, ssm) templates (#1707)

Nahuel Nucera060ec05f8397
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 0217f1db..97db7ecd 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -2726,6 +2726,10 @@ def _cwlogs_create(logical_id, props, stack_name):
"arn": arn,
"creationTime": int(time.time() * 1000),
"retentionInDays": int(retention) if retention else None,
+ # DescribeLogGroups reports the class on every group; the API's
+ # default when the template names none is STANDARD.
+ "logGroupClass": props.get("LogGroupClass") or "STANDARD",
+ "kmsKeyId": props.get("KmsKeyId") or None,
"tags": _tag_map(props.get("Tags")),
"streams": {},
"subscriptionFilters": {},
@@ -2748,6 +2752,10 @@ def _cwlogs_update(physical_id, old_props, new_props, stack_name, logical_id=Non
return replaced
retention = new_props.get("RetentionInDays")
group["retentionInDays"] = int(retention) if retention else None
+ # LogGroupClass and KmsKeyId are Mutable on the resource reference; the
+ # API refuses a class change after creation, so the record keeps the one
+ # it was created with and only the key moves.
+ group["kmsKeyId"] = new_props.get("KmsKeyId") or None
_reconcile_tag_map(group.setdefault("tags", {}), old_props, new_props)
return name, {"Arn": group["arn"]}
diff --git a/ministack/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.py
index d1ccc9c6..61119763 100644
--- a/ministack/services/cloudwatch_logs.py
+++ b/ministack/services/cloudwatch_logs.py
@@ -343,6 +343,12 @@ async def handle_request(method, path, headers, body, query_params):
# Log groups
# ---------------------------------------------------------------------------
+# The log classes CreateLogGroup takes; "If you omit this parameter, the
+# default of STANDARD is used" and "The value of logGroupClass can't be
+# changed after a log group is created".
+_LOG_GROUP_CLASSES = ("STANDARD", "INFREQUENT_ACCESS", "DELIVERY")
+
+
def _create_log_group(data):
name = data.get("logGroupName")
if not name:
@@ -352,10 +358,20 @@ def _create_log_group(data):
"ResourceAlreadyExistsException",
f"The specified log group already exists: {name}", 400,
)
+ group_class = data.get("logGroupClass") or "STANDARD"
+ if group_class not in _LOG_GROUP_CLASSES:
+ return error_response_json(
+ "InvalidParameterException",
+ f"1 validation error detected: Value '{group_class}' at 'logGroupClass' "
+ "failed to satisfy constraint: Member must satisfy enum value set: "
+ f"[{', '.join(_LOG_GROUP_CLASSES)}]", 400,
+ )
_log_groups[name] = {
"arn": _make_group_arn(name),
"creationTime": int(time.time() * 1000),
"retentionInDays": None,
+ "logGroupClass": group_class,
+ "kmsKeyId": data.get("kmsKeyId") or None,
"tags": dict(data.get("tags", {})),
"subscriptionFilters": {},
"streams": {},
@@ -410,9 +426,16 @@ def _describe_log_groups(data):
for s in g["streams"].values()
),
"metricFilterCount": sum(1 for k in _metric_filters if k[0] == n),
+ # Always reported: every log group has a class, and a consumer
+ # that reads it back (Terraform's aws_cloudwatch_log_group) plans
+ # a replacement when the member is missing. A group created before
+ # the field was stored reads as the default.
+ "logGroupClass": g.get("logGroupClass") or "STANDARD",
}
if g.get("retentionInDays") is not None:
entry["retentionInDays"] = g["retentionInDays"]
+ if g.get("kmsKeyId"):
+ entry["kmsKeyId"] = g["kmsKeyId"]
groups.append(entry)
resp: dict = {"logGroups": groups}
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index bf7576ec..9cd3d766 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -4242,10 +4242,26 @@ def _sg_xml(sg):
def _perm_xml(r):
+ def _range_desc(entry):
+ return (f"<description>{_esc(entry['Description'])}</description>"
+ if isinstance(entry, dict) and entry.get("Description") else "")
+
ranges = "".join(
- f"<item><cidrIp>{ip['CidrIp']}</cidrIp></item>"
+ f"<item><cidrIp>{ip['CidrIp']}</cidrIp>{_range_desc(ip)}</item>"
for ip in r.get("IpRanges", [])
)
+ # Every family the permission carries is reported: the members are
+ # ipv6Ranges (cidrIpv6) and prefixListIds (prefixListId) on IpPermission,
+ # and a read that omits them makes a configured IPv6 or prefix-list rule
+ # invisible, so Terraform re-applies it on every plan.
+ ranges6 = "".join(
+ f"<item><cidrIpv6>{_esc(ip6['CidrIpv6'])}</cidrIpv6>{_range_desc(ip6)}</item>"
+ for ip6 in r.get("Ipv6Ranges", []) if isinstance(ip6, dict) and ip6.get("CidrIpv6")
+ )
+ prefixes = "".join(
+ f"<item><prefixListId>{_esc(pl['PrefixListId'])}</prefixListId>{_range_desc(pl)}</item>"
+ for pl in r.get("PrefixListIds", []) if isinstance(pl, dict) and pl.get("PrefixListId")
+ )
groups = ""
for pair in r.get("UserIdGroupPairs", []):
if isinstance(pair, dict):
@@ -4264,7 +4280,8 @@ def _perm_xml(r):
<ipProtocol>{r.get('IpProtocol','-1')}</ipProtocol>
{from_port}{to_port}
<ipRanges>{ranges}</ipRanges>
- <ipv6Ranges/><prefixListIds/><groups>{groups}</groups>
+ <ipv6Ranges>{ranges6}</ipv6Ranges>
+ <prefixListIds>{prefixes}</prefixListIds><groups>{groups}</groups>
</item>"""
@@ -6416,6 +6433,23 @@ def _parse_lt_data(params, prefix="LaunchTemplateData"):
ebs_opt = _p(params, f"{prefix}.EbsOptimized")
if ebs_opt:
data["EbsOptimized"] = ebs_opt.lower() == "true"
+ # MetadataOptions — the IMDS settings of
+ # LaunchTemplateInstanceMetadataOptionsRequest. Dropping them made every
+ # refresh report them as newly added.
+ metadata = {}
+ for member in ("HttpTokens", "HttpEndpoint", "HttpProtocolIpv6", "InstanceMetadataTags"):
+ value = _p(params, f"{prefix}.MetadataOptions.{member}")
+ if value:
+ metadata[member] = value
+ hop_limit = _p(params, f"{prefix}.MetadataOptions.HttpPutResponseHopLimit")
+ if hop_limit:
+ metadata["HttpPutResponseHopLimit"] = int(hop_limit)
+ if metadata:
+ data["MetadataOptions"] = metadata
+ # InstanceInitiatedShutdownBehavior (stop | terminate)
+ shutdown = _p(params, f"{prefix}.InstanceInitiatedShutdownBehavior")
+ if shutdown:
+ data["InstanceInitiatedShutdownBehavior"] = shutdown
return data
@@ -6499,6 +6533,23 @@ def _lt_data_xml(data):
xml += f"<tagSpecificationSet>{inner}</tagSpecificationSet>"
if data.get("Monitoring"):
xml += f"<monitoring><enabled>{str(data['Monitoring'].get('Enabled', False)).lower()}</enabled></monitoring>"
+ if data.get("MetadataOptions"):
+ mo = data["MetadataOptions"]
+ # The response shape carries a State the request has no member for;
+ # a template's options are in effect as stored, so it reads applied.
+ inner = f"<state>{_esc(mo.get('State', 'applied'))}</state>"
+ for member, tag in (("HttpTokens", "httpTokens"),
+ ("HttpPutResponseHopLimit", "httpPutResponseHopLimit"),
+ ("HttpEndpoint", "httpEndpoint"),
+ ("HttpProtocolIpv6", "httpProtocolIpv6"),
+ ("InstanceMetadataTags", "instanceMetadataTags")):
+ if mo.get(member) is not None:
+ inner += f"<{tag}>{_esc(str(mo[member]))}</{tag}>"
+ xml += f"<metadataOptions>{inner}</metadataOptions>"
+ if data.get("InstanceInitiatedShutdownBehavior"):
+ xml += ("<instanceInitiatedShutdownBehavior>"
+ f"{_esc(data['InstanceInitiatedShutdownBehavior'])}"
+ "</instanceInitiatedShutdownBehavior>")
return xml
diff --git a/ministack/services/ssm.py b/ministack/services/ssm.py
index ac2fe77f..160e87d3 100644
--- a/ministack/services/ssm.py
+++ b/ministack/services/ssm.py
@@ -296,7 +296,12 @@ def _put_parameter(data):
stored_value = value
if param_type == "SecureString":
- key_id = data.get("KeyId", "alias/aws/ssm")
+ # "If you don't specify a key ID, the system uses the default key
+ # associated with your Amazon Web Services account" — an AWS managed
+ # key, whose alias has the form aws/<service-name> and which the API
+ # names with the alias/ prefix (KMS concepts: alias/aws/s3 is the S3
+ # one). An empty KeyId on the request is the same as none.
+ key_id = data.get("KeyId") or "alias/aws/ssm"
stored_value = f"ENCRYPTED:{base64.b64encode(value.encode()).decode()}"
else:
key_id = ""
@@ -517,6 +522,13 @@ def _describe_parameters(data):
"Tier": param.get("Tier", "Standard"),
"AllowedPattern": param.get("AllowedPattern", ""),
}
+ # ParameterMetadata.KeyId is "the alias of the KMS key used to encrypt
+ # the parameter. Applies to SecureString parameters only", so it is
+ # reported for those and omitted for the rest. A caller that reads it
+ # back (Terraform's aws_ssm_parameter) plans the same in-place update
+ # on every run while the member is missing.
+ if param.get("KeyId"):
+ desc["KeyId"] = param["KeyId"]
if param.get("Policies"):
desc["Policies"] = param["Policies"]
results.append(desc)
@@ -591,6 +603,9 @@ def _get_parameter_history(data):
"Labels": entry.get("Labels", []),
"Policies": entry.get("Policies", []),
}
+ # ParameterHistory carries the same member as ParameterMetadata.
+ if entry.get("KeyId"):
+ out["KeyId"] = entry["KeyId"]
if with_decryption or entry["Type"] != "SecureString":
out["Value"] = entry.get("OriginalValue", entry["Value"])
else:
diff --git a/tests/test_cloudwatch_logs.py b/tests/test_cloudwatch_logs.py
index f4052e6e..45f39a6b 100644
--- a/tests/test_cloudwatch_logs.py
+++ b/tests/test_cloudwatch_logs.py
@@ -641,6 +641,59 @@ def test_logs_describe_includes_log_group_arn_without_star(logs):
assert ":*" not in described["logGroupArn"].split("log-group:")[-1]
+def test_logs_describe_reports_the_log_group_class(logs):
+ """DescribeLogGroups reports logGroupClass on every group: the member is
+ on the LogGroup shape, CreateLogGroup takes it, and "if you omit this
+ parameter, the default of STANDARD is used". A consumer that reads it
+ back (Terraform's aws_cloudwatch_log_group) plans a replacement when the
+ member is missing. Reported by @edersonbrilhante."""
+ import uuid as _uuid
+
+ default_group = f"/intg/lg-class/{_uuid.uuid4().hex[:8]}"
+ ia_group = f"/intg/lg-class-ia/{_uuid.uuid4().hex[:8]}"
+ logs.create_log_group(logGroupName=default_group)
+ logs.create_log_group(logGroupName=ia_group, logGroupClass="INFREQUENT_ACCESS")
+ try:
+ described = logs.describe_log_groups(logGroupNamePrefix=default_group)["logGroups"][0]
+ assert described["logGroupClass"] == "STANDARD"
+ described = logs.describe_log_groups(logGroupNamePrefix=ia_group)["logGroups"][0]
+ assert described["logGroupClass"] == "INFREQUENT_ACCESS"
+ finally:
+ logs.delete_log_group(logGroupName=default_group)
+ logs.delete_log_group(logGroupName=ia_group)
+
+
+def test_logs_create_log_group_refuses_an_unknown_class(logs):
+ """logGroupClass is an enum of three values."""
+ import uuid as _uuid
+
+ group = f"/intg/lg-class-bad/{_uuid.uuid4().hex[:8]}"
+ with pytest.raises(ClientError) as exc:
+ logs.create_log_group(logGroupName=group, logGroupClass="ARCHIVE")
+ assert exc.value.response["Error"]["Code"] == "InvalidParameterException"
+ assert "logGroupClass" in exc.value.response["Error"]["Message"]
+
+
+def test_logs_describe_reports_the_kms_key(logs):
+ """kmsKeyId is on the LogGroup shape and CreateLogGroup takes it; it is
+ reported only when the group has one."""
+ import uuid as _uuid
+
+ key_arn = f"arn:aws:kms:us-east-1:000000000000:key/{_uuid.uuid4()}"
+ group = f"/intg/lg-kms/{_uuid.uuid4().hex[:8]}"
+ plain = f"/intg/lg-nokms/{_uuid.uuid4().hex[:8]}"
+ logs.create_log_group(logGroupName=group, kmsKeyId=key_arn)
+ logs.create_log_group(logGroupName=plain)
+ try:
+ described = logs.describe_log_groups(logGroupNamePrefix=group)["logGroups"][0]
+ assert described["kmsKeyId"] == key_arn
+ described = logs.describe_log_groups(logGroupNamePrefix=plain)["logGroups"][0]
+ assert "kmsKeyId" not in described
+ finally:
+ logs.delete_log_group(logGroupName=group)
+ logs.delete_log_group(logGroupName=plain)
+
+
def test_logs_start_live_tail_receives_put_events(logs):
"""StartLiveTail stays open and receives matching PutLogEvents until disconnect."""
import threading
diff --git a/tests/test_ec2.py b/tests/test_ec2.py
index 66860125..ad5bab51 100644
--- a/tests/test_ec2.py
+++ b/tests/test_ec2.py
@@ -673,6 +673,47 @@ def test_ec2_sg_authorize_revoke_ingress(ec2):
ec2.delete_security_group(GroupId=sg_id)
+def test_ec2_describe_security_groups_reports_every_range_family(ec2):
+ """DescribeSecurityGroups reports each family the permission carries.
+ IpPermission has ipRanges, ipv6Ranges and prefixListIds, and each range
+ carries its description; the read rendered the last two as empty
+ elements, so a configured IPv6 or prefix-list rule was invisible and
+ Terraform planned the same egress update on every run.
+ Reported by @edersonbrilhante."""
+ import uuid as _uuid
+
+ suffix = _uuid.uuid4().hex[:8]
+ sg_id = ec2.create_security_group(
+ GroupName=f"qa-ec2-sg-families-{suffix}", Description="families")["GroupId"]
+ try:
+ # The shape Terraform's egress block sends for a dual-stack allow-all.
+ ec2.revoke_security_group_egress(GroupId=sg_id, IpPermissions=[
+ {"IpProtocol": "-1", "IpRanges": [{"CidrIp": "0.0.0.0/0"}]}])
+ ec2.authorize_security_group_egress(GroupId=sg_id, IpPermissions=[{
+ "IpProtocol": "-1",
+ "IpRanges": [{"CidrIp": "0.0.0.0/0", "Description": "all v4"}],
+ "Ipv6Ranges": [{"CidrIpv6": "::/0", "Description": "all v6"}],
+ }])
+ ec2.authorize_security_group_ingress(GroupId=sg_id, IpPermissions=[{
+ "IpProtocol": "tcp", "FromPort": 443, "ToPort": 443,
+ "Ipv6Ranges": [{"CidrIpv6": "2001:db8::/32"}],
+ }])
+
+ described = ec2.describe_security_groups(GroupIds=[sg_id])["SecurityGroups"][0]
+
+ egress = described["IpPermissionsEgress"]
+ assert len(egress) == 1, egress
+ assert egress[0]["IpRanges"] == [{"CidrIp": "0.0.0.0/0", "Description": "all v4"}]
+ assert egress[0]["Ipv6Ranges"] == [{"CidrIpv6": "::/0", "Description": "all v6"}]
+
+ ingress = described["IpPermissions"]
+ assert len(ingress) == 1, ingress
+ assert ingress[0]["Ipv6Ranges"] == [{"CidrIpv6": "2001:db8::/32"}]
+ assert ingress[0]["IpRanges"] == []
+ finally:
+ ec2.delete_security_group(GroupId=sg_id)
+
+
def test_ec2_revoke_security_group_egress_returns_revoked_rules(ec2):
sg_id = ec2.create_security_group(GroupName="qa-ec2-sg-revoke-egress", Description="egress")["GroupId"]
@@ -2654,6 +2695,56 @@ def test_ec2_launch_template_with_block_devices(ec2):
ec2.delete_launch_template(LaunchTemplateId=lt_id)
+def test_ec2_launch_template_keeps_metadata_options_and_shutdown_behavior(ec2):
+ """A template's IMDS settings and shutdown behaviour survive the read.
+ RequestLaunchTemplateData carries MetadataOptions and
+ InstanceInitiatedShutdownBehavior, and the response shape reports both
+ (metadataOptions, instanceInitiatedShutdownBehavior); the parser dropped
+ them, so every Terraform refresh reported them as newly added.
+ Reported by @edersonbrilhante."""
+ import uuid as _uuid
+
+ name = f"qa-lt-metadata-{_uuid.uuid4().hex[:8]}"
+ created = ec2.create_launch_template(
+ LaunchTemplateName=name,
+ LaunchTemplateData={
+ "InstanceInitiatedShutdownBehavior": "terminate",
+ "MetadataOptions": {
+ "HttpEndpoint": "enabled",
+ "HttpPutResponseHopLimit": 2,
+ "HttpTokens": "required",
+ "HttpProtocolIpv6": "enabled",
+ "InstanceMetadataTags": "disabled",
+ },
+ },
+ )["LaunchTemplate"]
+ try:
+ versions = ec2.describe_launch_template_versions(
+ LaunchTemplateId=created["LaunchTemplateId"])["LaunchTemplateVersions"]
+ data = versions[0]["LaunchTemplateData"]
+ assert data["InstanceInitiatedShutdownBehavior"] == "terminate"
+ options = data["MetadataOptions"]
+ assert options["HttpEndpoint"] == "enabled"
+ assert options["HttpPutResponseHopLimit"] == 2
+ assert options["HttpTokens"] == "required"
+ assert options["HttpProtocolIpv6"] == "enabled"
+ assert options["InstanceMetadataTags"] == "disabled"
+ # The response shape carries a State the request has no member for.
+ assert options["State"] == "applied"
+
+ # A new version keeps its own options, so a refresh of either is stable.
+ ec2.create_launch_template_version(
+ LaunchTemplateId=created["LaunchTemplateId"],
+ LaunchTemplateData={"MetadataOptions": {"HttpTokens": "optional"}})
+ latest = ec2.describe_launch_template_versions(
+ LaunchTemplateId=created["LaunchTemplateId"], Versions=["2"],
+ )["LaunchTemplateVersions"][0]["LaunchTemplateData"]
+ assert latest["MetadataOptions"]["HttpTokens"] == "optional"
+ assert "InstanceInitiatedShutdownBehavior" not in latest
+ finally:
+ ec2.delete_launch_template(LaunchTemplateId=created["LaunchTemplateId"])
+
+
def test_ec2_launch_template_not_found(ec2):
"""Describe/delete a non-existent template should fail."""
with pytest.raises(ClientError) as exc:
diff --git a/tests/test_ssm.py b/tests/test_ssm.py
index 3b7d33e7..63048aa0 100644
--- a/tests/test_ssm.py
+++ b/tests/test_ssm.py
@@ -254,6 +254,48 @@ def test_ssm_secure_string_not_decrypted_by_default(ssm):
assert resp2["Parameter"]["Value"] == "mysecret"
+def test_ssm_describe_parameters_reports_the_key_for_a_secure_string(ssm):
+ """ParameterMetadata.KeyId is "the alias of the AWS KMS key used to
+ encrypt the parameter. Applies to SecureString parameters only", so
+ DescribeParameters reports it for a SecureString and omits it for the
+ rest. Without it Terraform's aws_ssm_parameter records an empty key_id
+ and plans the same in-place update on every run.
+ Reported by @edersonbrilhante."""
+ import uuid as _uuid
+
+ suffix = _uuid.uuid4().hex[:8]
+ default_key = f"/qa/ssm/keyid/default-{suffix}"
+ custom_key = f"/qa/ssm/keyid/custom-{suffix}"
+ plain = f"/qa/ssm/keyid/plain-{suffix}"
+ custom = "arn:aws:kms:us-east-1:000000000000:key/11111111-2222-3333-4444-555555555555"
+ ssm.put_parameter(Name=default_key, Value="s", Type="SecureString")
+ ssm.put_parameter(Name=custom_key, Value="s", Type="SecureString", KeyId=custom)
+ ssm.put_parameter(Name=plain, Value="p", Type="String")
+ try:
+ def described(name):
+ found = ssm.describe_parameters(
+ ParameterFilters=[{"Key": "Name", "Values": [name]}])["Parameters"]
+ assert found, name
+ return found[0]
+
+ # No KeyId on the request: the account's default SSM key, an AWS
+ # managed key, whose alias has the form aws/<service-name>.
+ assert described(default_key)["KeyId"] == "alias/aws/ssm"
+ assert described(custom_key)["KeyId"] == custom
+ assert "KeyId" not in described(plain)
+
+ # ParameterHistory carries the same member.
+ history = ssm.get_parameter_history(Name=default_key)["Parameters"]
+ assert history[-1]["KeyId"] == "alias/aws/ssm"
+ assert "KeyId" not in ssm.get_parameter_history(Name=plain)["Parameters"][-1]
+
+ # GetParameter's Parameter shape has no KeyId member.
+ assert "KeyId" not in ssm.get_parameter(Name=default_key)["Parameter"]
+ finally:
+ for name in (default_key, custom_key, plain):
+ ssm.delete_parameter(Name=name)
+
+
def test_ssm_get_parameters_by_path_root_non_recursive(ssm):
"""GetParametersByPath with Path=/ and Recursive=False should only return top-level params."""
ssm.put_parameter(Name="/toplevel", Value="top", Type="String", Overwrite=True)