Skip to content

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

fix/tags-alias-contenthandling

Nahuel99020ebc02bc376
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index d6bfc878..f0435f3e 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -730,6 +730,10 @@ def _create_integration(api_id, data):
"requestParameters": data.get("requestParameters", {}),
"requestTemplates": data.get("requestTemplates", {}),
"responseParameters": data.get("responseParameters", {}),
+ # #439: contentHandlingStrategy (CONVERT_TO_TEXT | CONVERT_TO_BINARY)
+ # is accepted on Create/Update and echoed back by Get; Terraform's
+ # aws_apigatewayv2_integration otherwise plans to re-add it on every apply.
+ "contentHandlingStrategy": data.get("contentHandlingStrategy"),
}
_integrations.setdefault(api_id, {})[int_id] = integration
return _apigw_response(integration, 201)
@@ -752,7 +756,8 @@ def _update_integration(api_id, int_id, data):
return _apigw_error("NotFoundException", f"Integration {int_id} not found", 404)
for k in ("integrationType", "integrationUri", "integrationMethod",
"payloadFormatVersion", "timeoutInMillis", "connectionType",
- "description", "requestParameters", "requestTemplates", "responseParameters"):
+ "description", "requestParameters", "requestTemplates", "responseParameters",
+ "contentHandlingStrategy"):
if k in data:
integration[k] = data[k]
return _apigw_response(integration)
diff --git a/ministack/services/iam.py b/ministack/services/iam.py
index f13d849e..ebf1d1d6 100644
--- a/ministack/services/iam.py
+++ b/ministack/services/iam.py
@@ -299,6 +299,7 @@ def _create_policy(p):
return _error(409, "EntityAlreadyExists",
f"A policy called {name} already exists.", ns="iam")
doc = _p(p, "PolicyDocument")
+ description = _p(p, "Description", "")
policy_id = _gen_id("ANPA")
version_id = "v1"
_policies[arn] = {
@@ -311,6 +312,7 @@ def _create_policy(p):
"AttachmentCount": 0,
"IsAttachable": True,
"Path": path,
+ "Description": description,
"Tags": [],
"Versions": {
version_id: {
@@ -1422,11 +1424,20 @@ def _extract_tag_keys(p):
def _user_xml(name):
u = _users[name]
+ # Tags are emitted when present (#441). _role_xml follows the same pattern.
+ tags_xml = ""
+ if u.get("Tags"):
+ tag_members = "".join(
+ f"<member><Key>{t['Key']}</Key><Value>{t['Value']}</Value></member>"
+ for t in u["Tags"]
+ )
+ tags_xml = f"<Tags>{tag_members}</Tags>"
return (f"<UserName>{u['UserName']}</UserName>"
f"<UserId>{u['UserId']}</UserId>"
f"<Arn>{u['Arn']}</Arn>"
f"<Path>{u['Path']}</Path>"
- f"<CreateDate>{u['CreateDate']}</CreateDate>")
+ f"<CreateDate>{u['CreateDate']}</CreateDate>"
+ f"{tags_xml}")
def _role_xml(name):
@@ -1454,6 +1465,9 @@ def _role_xml(name):
def _managed_policy_xml(arn):
pol = _policies[arn]
+ # Description is omitted when empty to match real AWS (#438).
+ description = pol.get("Description") or ""
+ description_xml = f"<Description>{description}</Description>" if description else ""
return (f"<PolicyName>{pol['PolicyName']}</PolicyName>"
f"<Arn>{arn}</Arn>"
f"<PolicyId>{pol['PolicyId']}</PolicyId>"
@@ -1462,7 +1476,8 @@ def _managed_policy_xml(arn):
f"<IsAttachable>true</IsAttachable>"
f"<CreateDate>{pol['CreateDate']}</CreateDate>"
f"<UpdateDate>{pol.get('UpdateDate', pol['CreateDate'])}</UpdateDate>"
- f"<Path>{pol.get('Path', '/')}</Path>")
+ f"<Path>{pol.get('Path', '/')}</Path>"
+ f"{description_xml}")
def _group_xml(name):
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index b4844533..24b6225a 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -2880,8 +2880,12 @@ def _create_alias(func_name: str, data: dict):
"Description": data.get("Description", ""),
"RevisionId": new_uuid(),
}
+ # #440: Terraform sends RoutingConfig={"AdditionalVersionWeights": {}} even
+ # when no weighted routing is declared. Only store (and echo back) when
+ # the weights map is non-empty — real AWS omits RoutingConfig from
+ # responses when no weights are configured.
rc = data.get("RoutingConfig")
- if rc:
+ if rc and rc.get("AdditionalVersionWeights"):
alias["RoutingConfig"] = rc
func["aliases"][alias_name] = alias
return json_response(alias, 201)
@@ -2918,9 +2922,18 @@ def _update_alias(func_name: str, alias_name: str, data: dict):
f"Alias not found: {_func_arn(func_name)}:{alias_name}",
404,
)
- for key in ("FunctionVersion", "Description", "RoutingConfig"):
+ for key in ("FunctionVersion", "Description"):
if key in data:
alias[key] = data[key]
+ # #440: same rule as CreateAlias — empty AdditionalVersionWeights means
+ # "no weighted routing"; store only when non-empty, and remove an existing
+ # RoutingConfig if the caller clears it.
+ if "RoutingConfig" in data:
+ rc = data["RoutingConfig"]
+ if rc and rc.get("AdditionalVersionWeights"):
+ alias["RoutingConfig"] = rc
+ else:
+ alias.pop("RoutingConfig", None)
alias["RevisionId"] = new_uuid()
return json_response(alias)
@@ -3068,7 +3081,24 @@ def _get_policy(func_name: str, query_params: dict | None = None):
# ---------------------------------------------------------------------------
+def _esm_id_from_arn(resource_arn: str) -> str | None:
+ """Return the ESM UUID if the ARN points to an event-source-mapping, else None."""
+ if ":event-source-mapping:" in resource_arn:
+ return resource_arn.rsplit(":", 1)[-1]
+ return None
+
+
def _list_tags(resource_arn: str):
+ esm_id = _esm_id_from_arn(resource_arn)
+ if esm_id is not None:
+ esm = _esms.get(esm_id)
+ if not esm:
+ return error_response_json(
+ "ResourceNotFoundException",
+ f"The resource you requested does not exist.",
+ 404,
+ )
+ return json_response({"Tags": esm.get("Tags", {})})
func_name = _resolve_name(resource_arn)
if func_name not in _functions:
return error_response_json(
@@ -3080,6 +3110,17 @@ def _list_tags(resource_arn: str):
def _tag_resource(resource_arn: str, data: dict):
+ esm_id = _esm_id_from_arn(resource_arn)
+ if esm_id is not None:
+ esm = _esms.get(esm_id)
+ if not esm:
+ return error_response_json(
+ "ResourceNotFoundException",
+ f"The resource you requested does not exist.",
+ 404,
+ )
+ esm.setdefault("Tags", {}).update(data.get("Tags", {}))
+ return 204, {}, b""
func_name = _resolve_name(resource_arn)
if func_name not in _functions:
return error_response_json(
@@ -3092,13 +3133,6 @@ def _tag_resource(resource_arn: str, data: dict):
def _untag_resource(resource_arn: str, query_params: dict):
- func_name = _resolve_name(resource_arn)
- if func_name not in _functions:
- return error_response_json(
- "ResourceNotFoundException",
- f"Function not found: {resource_arn}",
- 404,
- )
raw = query_params.get("tagKeys", query_params.get("TagKeys", []))
if isinstance(raw, list):
tag_keys = raw
@@ -3106,6 +3140,28 @@ def _untag_resource(resource_arn: str, query_params: dict):
tag_keys = [raw]
else:
tag_keys = []
+
+ esm_id = _esm_id_from_arn(resource_arn)
+ if esm_id is not None:
+ esm = _esms.get(esm_id)
+ if not esm:
+ return error_response_json(
+ "ResourceNotFoundException",
+ f"The resource you requested does not exist.",
+ 404,
+ )
+ tags = esm.setdefault("Tags", {})
+ for k in tag_keys:
+ tags.pop(k.strip(), None)
+ return 204, {}, b""
+
+ func_name = _resolve_name(resource_arn)
+ if func_name not in _functions:
+ return error_response_json(
+ "ResourceNotFoundException",
+ f"Function not found: {resource_arn}",
+ 404,
+ )
tags = _functions[func_name].setdefault("tags", {})
for k in tag_keys:
tags.pop(k.strip(), None)
@@ -3609,6 +3665,11 @@ def _create_esm(data: dict):
}
if ":sqs:" not in event_source_arn:
esm["StartingPosition"] = data.get("StartingPosition", "LATEST")
+ # #442: Tags are accepted on CreateEventSourceMapping. Stored inline on
+ # the ESM record; surfaced via _list_tags for the ESM ARN.
+ tags = data.get("Tags") or {}
+ if tags:
+ esm["Tags"] = dict(tags)
_esms[esm_id] = esm
_ensure_poller()
return json_response(_esm_response(esm), 202)
diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.py
index 61c8d5bb..9129bf1f 100644
--- a/tests/test_apigatewayv2.py
+++ b/tests/test_apigatewayv2.py
@@ -780,6 +780,29 @@ def test_apigw_update_integration(apigw):
integ = apigw.get_integration(ApiId=api_id, IntegrationId=integ_id)
assert "new-fn" in integ["IntegrationUri"]
+
+def test_apigw_integration_content_handling_strategy_roundtrip(apigw):
+ """Regression for #439: contentHandlingStrategy must survive Create and Update.
+ Without this, Terraform replans the field on every apply and the runtime
+ silently misses CONVERT_TO_TEXT / CONVERT_TO_BINARY payload translation."""
+ api_id = apigw.create_api(Name="qa-apigw-chs", ProtocolType="HTTP")["ApiId"]
+ integ_id = apigw.create_integration(
+ ApiId=api_id,
+ IntegrationType="AWS_PROXY",
+ IntegrationUri="arn:aws:lambda:us-east-1:000000000000:function:chs-fn",
+ ContentHandlingStrategy="CONVERT_TO_TEXT",
+ )["IntegrationId"]
+ integ = apigw.get_integration(ApiId=api_id, IntegrationId=integ_id)
+ assert integ.get("ContentHandlingStrategy") == "CONVERT_TO_TEXT"
+
+ apigw.update_integration(
+ ApiId=api_id,
+ IntegrationId=integ_id,
+ ContentHandlingStrategy="CONVERT_TO_BINARY",
+ )
+ integ = apigw.get_integration(ApiId=api_id, IntegrationId=integ_id)
+ assert integ.get("ContentHandlingStrategy") == "CONVERT_TO_BINARY"
+
def test_apigw_delete_route_v2(apigw):
"""DeleteRoute removes the route from GetRoutes."""
api_id = apigw.create_api(Name="qa-apigw-del-route", ProtocolType="HTTP")["ApiId"]
diff --git a/tests/test_iam.py b/tests/test_iam.py
index 5311dc72..444faa8b 100644
--- a/tests/test_iam.py
+++ b/tests/test_iam.py
@@ -114,6 +114,40 @@ def test_iam_get_policy(iam):
resp = iam.get_policy(PolicyArn=arn)
assert resp["Policy"]["PolicyName"] == "iam-test-policy"
+
+def test_iam_policy_description_roundtrip(iam):
+ """Regression for #438: CreatePolicy(Description=...) must survive GetPolicy.
+ Without this, Terraform force-replaces every aws_iam_policy with a description
+ on every warm boot because `description` is ForceNew in the provider."""
+ import uuid as _u
+ name = f"desc-policy-{_u.uuid4().hex[:8]}"
+ created = iam.create_policy(
+ PolicyName=name,
+ Description="managed by ministack regression test",
+ PolicyDocument='{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"*","Resource":"*"}]}',
+ )
+ assert created["Policy"].get("Description") == "managed by ministack regression test"
+ fetched = iam.get_policy(PolicyArn=created["Policy"]["Arn"])
+ assert fetched["Policy"].get("Description") == "managed by ministack regression test"
+ iam.delete_policy(PolicyArn=created["Policy"]["Arn"])
+
+
+def test_iam_user_tags_serialized_in_get_user(iam):
+ """Regression for #441: GetUser must include Tags set via TagUser / CreateUser.
+ _user_xml previously omitted <Tags>, so Terraform's refresh saw empty tags
+ and re-added default_tags on every apply."""
+ import uuid as _u
+ name = f"tag-user-{_u.uuid4().hex[:8]}"
+ iam.create_user(UserName=name, Tags=[{"Key": "Team", "Value": "core"}])
+ resp = iam.get_user(UserName=name)
+ tags = {t["Key"]: t["Value"] for t in resp["User"].get("Tags", [])}
+ assert tags.get("Team") == "core"
+ iam.tag_user(UserName=name, Tags=[{"Key": "Env", "Value": "dev"}])
+ resp = iam.get_user(UserName=name)
+ tags = {t["Key"]: t["Value"] for t in resp["User"].get("Tags", [])}
+ assert tags == {"Team": "core", "Env": "dev"}
+ iam.delete_user(UserName=name)
+
def test_iam_attach_role_policy(iam):
policy_arn = "arn:aws:iam::000000000000:policy/iam-test-policy"
iam.attach_role_policy(RoleName="iam-test-role", PolicyArn=policy_arn)
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 55b3cad9..53f00729 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -976,6 +976,95 @@ def test_lambda_alias_crud(lam):
aliases2 = lam.list_aliases(FunctionName="qa-lam-alias")["Aliases"]
assert not any(a["Name"] == "prod" for a in aliases2)
+
+def test_lambda_alias_no_phantom_routing_config(lam):
+ """Regression for #440: when Terraform sends RoutingConfig with an empty
+ AdditionalVersionWeights map (its default payload when no weighted routing
+ is declared), ministack must NOT echo RoutingConfig back — real AWS omits
+ the field. Otherwise Terraform plans to remove the block on every apply."""
+ code = _zip_lambda("def handler(e,c): return 'v1'")
+ fn = "qa-lam-alias-rc"
+ lam.create_function(
+ FunctionName=fn,
+ Runtime="python3.12",
+ Role="arn:aws:iam::000000000000:role/r",
+ Handler="index.handler",
+ Code={"ZipFile": code},
+ )
+ lam.publish_version(FunctionName=fn)
+ # CreateAlias with the exact payload terraform-provider-aws sends when
+ # there is no `routing_config` block in HCL — outer dict present, inner
+ # weights empty.
+ created = lam.create_alias(
+ FunctionName=fn,
+ Name="live",
+ FunctionVersion="1",
+ RoutingConfig={"AdditionalVersionWeights": {}},
+ )
+ assert "RoutingConfig" not in created, f"phantom RoutingConfig echoed back: {created.get('RoutingConfig')!r}"
+ fetched = lam.get_alias(FunctionName=fn, Name="live")
+ assert "RoutingConfig" not in fetched, f"phantom RoutingConfig on GetAlias: {fetched.get('RoutingConfig')!r}"
+
+ # But a real weighted config MUST survive.
+ lam.publish_version(FunctionName=fn)
+ updated = lam.update_alias(
+ FunctionName=fn,
+ Name="live",
+ RoutingConfig={"AdditionalVersionWeights": {"2": 0.1}},
+ )
+ assert updated["RoutingConfig"]["AdditionalVersionWeights"] == {"2": 0.1}
+
+ # Clearing it back to empty removes it.
+ cleared = lam.update_alias(
+ FunctionName=fn,
+ Name="live",
+ RoutingConfig={"AdditionalVersionWeights": {}},
+ )
+ assert "RoutingConfig" not in cleared
+
+ lam.delete_function(FunctionName=fn)
+
+
+def test_lambda_event_source_mapping_tags(lam, sqs):
+ """Regression for #442: CreateEventSourceMapping accepts Tags; ListTags
+ returns them by ESM ARN. Without this, Terraform replans tags on every apply."""
+ code = _zip_lambda("def handler(e,c): return 'ok'")
+ fn = "qa-esm-tags-fn"
+ lam.create_function(
+ FunctionName=fn,
+ Runtime="python3.12",
+ Role="arn:aws:iam::000000000000:role/r",
+ Handler="index.handler",
+ Code={"ZipFile": code},
+ )
+ q = sqs.create_queue(QueueName="qa-esm-tags-queue")
+ q_arn = sqs.get_queue_attributes(QueueUrl=q["QueueUrl"], AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+
+ esm = lam.create_event_source_mapping(
+ FunctionName=fn,
+ EventSourceArn=q_arn,
+ Tags={"Team": "billing", "Env": "prod"},
+ )
+ esm_arn = f"arn:aws:lambda:us-east-1:000000000000:event-source-mapping:{esm['UUID']}"
+ tags = lam.list_tags(Resource=esm_arn)["Tags"]
+ assert tags == {"Team": "billing", "Env": "prod"}
+
+ # TagResource / UntagResource must also work on an ESM ARN.
+ lam.tag_resource(Resource=esm_arn, Tags={"Team": "platform"})
+ tags = lam.list_tags(Resource=esm_arn)["Tags"]
+ assert tags["Team"] == "platform"
+ assert tags["Env"] == "prod"
+
+ lam.untag_resource(Resource=esm_arn, TagKeys=["Env"])
+ tags = lam.list_tags(Resource=esm_arn)["Tags"]
+ assert "Env" not in tags
+ assert tags["Team"] == "platform"
+
+ lam.delete_event_source_mapping(UUID=esm["UUID"])
+ lam.delete_function(FunctionName=fn)
+ sqs.delete_queue(QueueUrl=q["QueueUrl"])
+
+
def test_lambda_publish_version_snapshot(lam):
"""PublishVersion creates a numbered version snapshot."""
code = _zip_lambda("def handler(e,c): return 'v1'")