Skip to content

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

release v1.3.13 (#452)

Nahuel Nucera5873b427dd47
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f751ed85..fcfc8a53 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,26 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.3.13] — 2026-04-24
+
+### Added
+- **CloudFront Functions API (stub)** — `CreateFunction`, `DescribeFunction`, `GetFunction`, `ListFunctions`, `PublishFunction`, `UpdateFunction`, `DeleteFunction` under `/2020-05-31/function*`. Covers Terraform `aws_cloudfront_function` (create + publish + read + delete) and attaching a function ARN to distribution cache behaviors. Limitations: in-memory only; no `TestFunction`; `KeyValueStoreAssociations` not modelled; no execution at the edge; `DescribeFunction` requires the `Stage` query parameter (`DEVELOPMENT` \| `LIVE`); `UpdateFunction` invalidates the emulated LIVE revision until the next `PublishFunction`. Contributed by @david-hay.
+- **CloudFront `CreateDistributionWithTags`** — accepts the `DistributionConfigWithTags` wrapper body shape (Terraform `aws_cloudfront_distribution` with `tags`). Contributed by @david-hay.
+- **API Gateway v1 stage method-settings via JSON Patch** — `UpdateStage` now honours paths of the form `/{resourcePath}/{httpMethod}/metrics/enabled`, `…/logging/loglevel`, `…/throttling/burstLimit`, etc., mapping them into `stage.methodSettings[{resourcePath}/{httpMethod}]` with AWS-shaped defaults. Unblocks Terraform `aws_api_gateway_method_settings`. Contributed by @david-hay.
+- **API Gateway execute-api for `provided.*` / Image / non-Python-Node runtimes** — AWS_PROXY integrations now dispatch through the central `_execute_function` path, so Go / Rust / Java Lambdas actually execute (v1 and v2) instead of returning a canned mock. Contributed by @david-hay and @bognari.
+- **Lambda → CloudWatch Logs for API Gateway-triggered invocations** — every execute-api invoke now emits the standard `START RequestId:` / handler stdout+stderr / `END RequestId:` / `REPORT RequestId:` sequence to `/aws/lambda/{FunctionName}`, so Metric Filters and subscription filters that watch APIGW-behind-Lambda traffic trigger correctly. Contributed by @bognari.
+
+### Fixed
+- **S3 Control `TagResource` silently dropped tags** — the handler only had `GET`/`PUT`/`DELETE` branches and parsed bodies as JSON, but AWS SDK Go v2 (used by terraform-aws-provider v6+) sends `POST` with an XML `TagResourceRequest`. Tags posted by Terraform's `aws_s3_bucket.tags` + `default_tags` were returning 2xx but never persisted, producing perpetual drift. Handler now accepts both POST and PUT, and parses both XML and JSON request bodies. Reported by @whittin3.
+- **IAM `GetPolicy` / `ListPolicies` omitted `Tags`** — `_managed_policy_xml()` never emitted a `<Tags>` block even though `TagPolicy` stored them correctly; Terraform refreshed `tags_all = {}` and replanned `default_tags` on every apply. Also fixed `_create_policy` silently dropping `Tags` passed on create. Same bug class as `_user_xml` (#441). Reported by @whittin3.
+- **EC2 tag-drift across 10+ resource types** — fourteen hardcoded `<tagSet/>` emissions in `ec2.py` were dropping tags for Network Interfaces, VPC Endpoints, NAT Gateways, Network ACLs, VPC Peering Connections, DHCP Options, Egress-Only Internet Gateways, Managed Prefix Lists, VPN Gateways, and Customer Gateways. Every `Describe*` for those resources returned empty tags regardless of what was stored. All now route through `_tag_set_xml(resource_id)`; three create paths (VPC Peering, DHCP Options, Egress-Only IGW) additionally gained missing `_parse_tag_specs` hooks so `TagSpecifications` on create is honoured.
+
+### Changed
+- **Lambda warm-worker stderr drain is bounded, not a fixed sleep** — the 50ms `time.sleep` added alongside the API Gateway → CloudWatch Logs fix was paid by every warm invocation regardless of whether the handler emitted log output. Replaced with a bounded drain that polls the stderr queue at 1ms intervals, exits ~5ms after the last line arrives (or ~50ms if the handler emitted nothing at all), and caps at 250ms absolute. Typical overhead drops from 50ms to 1–10ms per invoke.
+- **API Gateway proxy error-shaping shares a helper** — both v1 and v2 now call `lambda_svc.lambda_execute_result_to_api_proxy_response(...)` when converting an `_execute_function` result to the AWS_PROXY envelope. Gains correct `429 Too Many Requests` responses on `ConcurrentInvocationLimitExceeded` throttles (previously returned 502), and keeps v1/v2 response shapes aligned.
+
+---
+
## [1.3.12] — 2026-04-24
### Added
diff --git a/ministack/app.py b/ministack/app.py
index 6b37e130..35d478b2 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -638,15 +638,39 @@ async def _handle_s3_control_request(path: str, method: str, body: bytes, query_
"x-amzn-requestid": request_id,
}, xml_body
- if method == "PUT":
+ if method in ("POST", "PUT"):
+ # AWS SDK Go v2 (used by terraform-aws-provider v6+) sends
+ # TagResource as POST with an XML TagResourceRequest body. Older
+ # SDKs used PUT with JSON. Accept both methods + both body shapes
+ # so we don't silently drop tags (#447).
+ new_tags: dict = {}
try:
- payload = json.loads(body) if body else {}
- new_tags = {t["Key"]: t["Value"] for t in payload.get("Tags", [])}
+ if body:
+ raw = body if isinstance(body, str) else body.decode("utf-8", errors="replace")
+ stripped = raw.lstrip()
+ if stripped.startswith("<"):
+ # XML: <TagResourceRequest><Tags><Tag><Key>..</Key><Value>..</Value></Tag>...</Tags></TagResourceRequest>
+ from xml.etree.ElementTree import fromstring
+ root = fromstring(raw)
+ def _local(el):
+ t = el.tag
+ return t.split("}")[-1] if "}" in t else t
+ for child in root.iter():
+ if _local(child) != "Tag":
+ continue
+ key_el = next((c for c in child if _local(c) == "Key"), None)
+ val_el = next((c for c in child if _local(c) == "Value"), None)
+ if key_el is not None and key_el.text:
+ new_tags[key_el.text] = (val_el.text or "") if val_el is not None else ""
+ elif stripped.startswith("{"):
+ payload = json.loads(stripped)
+ new_tags = {t["Key"]: t["Value"] for t in payload.get("Tags", [])}
+ except Exception as e:
+ logger.warning("S3 Control TagResource parse error: %s", e)
+ if new_tags:
existing = _get_module("s3")._bucket_tags.get(bucket_name, {})
existing.update(new_tags)
_get_module("s3")._bucket_tags[bucket_name] = existing
- except Exception as e:
- logger.warning("S3 Control TagResource parse error: %s", e)
return 204, {"x-amzn-requestid": request_id}, b""
if method == "DELETE":
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.py
index 24f08816..94d08475 100644
--- a/ministack/core/lambda_runtime.py
+++ b/ministack/core/lambda_runtime.py
@@ -515,6 +515,46 @@ class Worker:
pass
return "\n".join(lines)
+ def _drain_stderr_bounded(
+ self,
+ first_line_wait: float = 0.050,
+ idle_confirm: float = 0.005,
+ hard_cap: float = 0.250,
+ ) -> str:
+ """Drain stderr with bounded waits — replaces a blanket ``time.sleep(0.05)``
+ that penalised every warm-pool invocation regardless of whether the
+ handler emitted any log output.
+
+ Three exit conditions, in order of likelihood:
+ 1. **Quiescence after a line**: after the first line arrives, exit
+ once the queue has been empty for ``idle_confirm`` seconds
+ (default 5ms). Typical completion is 1–10ms per invocation.
+ 2. **Nothing emitted**: if no line has arrived within
+ ``first_line_wait`` (default 50ms), assume the handler didn't
+ log and bail. Matches the pre-existing worst-case budget.
+ 3. **Hard cap**: 250ms absolute ceiling in case of a pathologically
+ slow/contended pipe; protects against unbounded blocking.
+
+ The polling interval is 1ms, keeping CPU overhead trivial."""
+ lines = []
+ start = time.time()
+ last_received_at = None
+ while True:
+ elapsed = time.time() - start
+ if elapsed >= hard_cap:
+ break
+ try:
+ lines.append(self._stderr_queue.get_nowait())
+ last_received_at = time.time()
+ except queue.Empty:
+ if last_received_at is not None:
+ if time.time() - last_received_at >= idle_confirm:
+ break
+ elif elapsed >= first_line_wait:
+ break
+ time.sleep(0.001)
+ return "\n".join(lines)
+
def invoke(self, event: dict, request_id: str) -> dict:
with self._lock:
cold = self._cold
@@ -578,10 +618,9 @@ class Worker:
if response.get("status") == "error":
self._proc = None
response["cold_start"] = cold
- # Brief pause so in-flight stderr lines from the OS pipe buffer
- # reach the queue before we drain it.
- time.sleep(0.05)
- response["log"] = self._drain_stderr()
+ # Bounded drain — replaces the fixed 50ms sleep that was paid
+ # by every warm invocation. Typical completion is 1–10ms.
+ response["log"] = self._drain_stderr_bounded()
return response
def kill(self):
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index 24e24286..e68f356c 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -523,14 +523,12 @@ async def _invoke_lambda_proxy(integration, api_id, stage, path, method, headers
# Route through the central _execute_function dispatcher so CloudWatch
# Logs emission and Docker log output work for API Gateway invocations.
+ # Response shaping (throttle→429, error→502, body→envelope) goes through
+ # the shared helper so v1/v2 stay consistent and we get 429s on
+ # ConcurrentInvocationLimitExceeded.
exec_record = {"config": func_config, "code_zip": func_data.get("code_zip")}
result = await asyncio.to_thread(lambda_svc._execute_function, exec_record, event)
- if result.get("error"):
- error_msg = result.get("body", {})
- if isinstance(error_msg, dict):
- error_msg = error_msg.get("errorMessage", "Lambda invocation error")
- return 502, {"Content-Type": "application/json"}, json.dumps({"message": error_msg}).encode()
- lambda_response = result.get("body", {})
+ lambda_response, _ = lambda_svc.lambda_execute_result_to_api_proxy_response(result)
status = lambda_response.get("statusCode", 200)
resp_headers = {"Content-Type": "application/json"}
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index 9a533ee7..08161c58 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -444,14 +444,17 @@ async def _call_lambda(func_name, event, qualifier=None):
# Route through the central _execute_function dispatcher so CloudWatch
# Logs emission and Docker log output work for API Gateway invocations.
+ # Response shaping (throttle→429, error→502, body→envelope) goes through
+ # the shared helper so v1/v2 stay consistent.
exec_record = {"config": func_config, "code_zip": func_data.get("code_zip")}
result = await asyncio.to_thread(lambda_svc._execute_function, exec_record, event)
- if result.get("error"):
- error_msg = result.get("body", {})
- if isinstance(error_msg, dict):
- error_msg = error_msg.get("errorMessage", "Lambda invocation error")
- return None, error_msg
- return result.get("body", {}), None
+ lambda_response, _ = lambda_svc.lambda_execute_result_to_api_proxy_response(result)
+ # On error the helper returns {statusCode: 502, body: <msg>}; preserve
+ # the _call_lambda contract of (None, error_msg) so callers that check
+ # for error strings keep working.
+ if result.get("error") and lambda_response and lambda_response.get("statusCode") == 502:
+ return None, str(lambda_response.get("body") or "Lambda invocation error")
+ return lambda_response, None
# ---- Persistence hooks ----
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index 41f63ba0..c5d153a3 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -2193,7 +2193,7 @@ def _eni_fields_xml(eni, tag="item"):
</item>
</privateIpAddressesSet>
{attachment}
- <tagSet/>
+ {_tag_set_xml(eni['NetworkInterfaceId'])}
</{tag}>"""
@@ -2209,7 +2209,7 @@ def _vpce_fields_xml(ep, tag="item"):
<ownerId>{ep['OwnerId']}</ownerId>
<routeTableIdSet>{rtb_ids}</routeTableIdSet>
<subnetIdSet>{subnet_ids}</subnetIdSet>
- <tagSet/>
+ {_tag_set_xml(ep['VpcEndpointId'])}
</{tag}>"""
@@ -2512,7 +2512,7 @@ def _create_nat_gateway(params):
<connectivityType>{connectivity}</connectivityType>
<createTime>{_now_ts()}</createTime>
<natGatewayAddressSet/>
- <tagSet/>
+ {_tag_set_xml(nat_id)}
</natGateway>"""
return _xml(200, "CreateNatGatewayResponse", inner)
@@ -2584,7 +2584,7 @@ def _create_network_acl(params):
<default>false</default>
<entrySet/>
<associationSet/>
- <tagSet/>
+ {_tag_set_xml(acl_id)}
<ownerId>{get_account_id()}</ownerId>
</networkAcl>"""
return _xml(200, "CreateNetworkAclResponse", inner)
@@ -2623,7 +2623,7 @@ def _describe_network_acls(params):
<default>{'true' if acl['IsDefault'] else 'false'}</default>
<entrySet>{entries}</entrySet>
<associationSet>{assocs}</associationSet>
- <tagSet/>
+ {_tag_set_xml(acl['NetworkAclId'])}
<ownerId>{acl['OwnerId']}</ownerId>
</item>"""
return _xml(200, "DescribeNetworkAclsResponse",
@@ -2783,12 +2783,14 @@ def _create_vpc_peering_connection(params):
"Tags": [],
}
_vpc_peering[pcx_id] = record
+ # TagSpecifications support for aws_vpc_peering_connection.tags on create.
+ _parse_tag_specs(params, "vpc-peering-connection", pcx_id)
inner = f"""<vpcPeeringConnection>
<vpcPeeringConnectionId>{pcx_id}</vpcPeeringConnectionId>
<requesterVpcInfo><vpcId>{vpc_id}</vpcId><ownerId>{get_account_id()}</ownerId><region>{get_region()}</region></requesterVpcInfo>
<accepterVpcInfo><vpcId>{peer_vpc_id}</vpcId><ownerId>{peer_owner_id}</ownerId><region>{peer_region}</region></accepterVpcInfo>
<status><code>pending-acceptance</code></status>
- <tagSet/>
+ {_tag_set_xml(pcx_id)}
</vpcPeeringConnection>"""
return _xml(200, "CreateVpcPeeringConnectionResponse", inner)
@@ -2805,7 +2807,7 @@ def _accept_vpc_peering_connection(params):
<requesterVpcInfo><vpcId>{pcx['RequesterVpcInfo']['VpcId']}</vpcId><ownerId>{pcx['RequesterVpcInfo']['OwnerId']}</ownerId><region>{pcx['RequesterVpcInfo']['Region']}</region></requesterVpcInfo>
<accepterVpcInfo><vpcId>{pcx['AccepterVpcInfo']['VpcId']}</vpcId><ownerId>{pcx['AccepterVpcInfo']['OwnerId']}</ownerId><region>{pcx['AccepterVpcInfo']['Region']}</region></accepterVpcInfo>
<status><code>active</code></status>
- <tagSet/>
+ {_tag_set_xml(pcx_id)}
</vpcPeeringConnection>"""
return _xml(200, "AcceptVpcPeeringConnectionResponse", inner)
@@ -2826,7 +2828,7 @@ def _describe_vpc_peering_connections(params):
<requesterVpcInfo><vpcId>{pcx['RequesterVpcInfo']['VpcId']}</vpcId><ownerId>{pcx['RequesterVpcInfo']['OwnerId']}</ownerId><region>{pcx['RequesterVpcInfo']['Region']}</region></requesterVpcInfo>
<accepterVpcInfo><vpcId>{pcx['AccepterVpcInfo']['VpcId']}</vpcId><ownerId>{pcx['AccepterVpcInfo']['OwnerId']}</ownerId><region>{pcx['AccepterVpcInfo']['Region']}</region></accepterVpcInfo>
<status><code>{pcx['Status']['Code']}</code><message>{pcx['Status']['Message']}</message></status>
- <tagSet/>
+ {_tag_set_xml(pcx['VpcPeeringConnectionId'])}
</item>"""
return _xml(200, "DescribeVpcPeeringConnectionsResponse",
f"<vpcPeeringConnectionSet>{items}</vpcPeeringConnectionSet>")
@@ -2878,11 +2880,12 @@ def _create_dhcp_options(params):
<key>{c['Key']}</key>
<valueSet>{"".join(f'<item><value>{v}</value></item>' for v in c['Values'])}</valueSet>
</item>""" for c in configs)
+ _parse_tag_specs(params, "dhcp-options", dopt_id)
inner = f"""<dhcpOptions>
<dhcpOptionsId>{dopt_id}</dhcpOptionsId>
<dhcpConfigurationSet>{configs_xml}</dhcpConfigurationSet>
<ownerId>{get_account_id()}</ownerId>
- <tagSet/>
+ {_tag_set_xml(dopt_id)}
</dhcpOptions>"""
return _xml(200, "CreateDhcpOptionsResponse", inner)
@@ -2914,7 +2917,7 @@ def _describe_dhcp_options(params):
<dhcpOptionsId>{dopt['DhcpOptionsId']}</dhcpOptionsId>
<dhcpConfigurationSet>{configs_xml}</dhcpConfigurationSet>
<ownerId>{dopt['OwnerId']}</ownerId>
- <tagSet/>
+ {_tag_set_xml(dopt['DhcpOptionsId'])}
</item>"""
return _xml(200, "DescribeDhcpOptionsResponse", f"<dhcpOptionsSet>{items}</dhcpOptionsSet>")
@@ -2947,6 +2950,7 @@ def _create_egress_only_igw(params):
_egress_igws[eigw_id] = record
if tags:
_tags[eigw_id] = tags
+ _parse_tag_specs(params, "egress-only-internet-gateway", eigw_id)
inner = f"""<egressOnlyInternetGateway>
<egressOnlyInternetGatewayId>{eigw_id}</egressOnlyInternetGatewayId>
<attachmentSet>
@@ -2955,7 +2959,7 @@ def _create_egress_only_igw(params):
<state>attached</state>
</item>
</attachmentSet>
- <tagSet/>
+ {_tag_set_xml(eigw_id)}
</egressOnlyInternetGateway>"""
return _xml(200, "CreateEgressOnlyInternetGatewayResponse", inner)
@@ -2974,7 +2978,7 @@ def _describe_egress_only_igws(params):
<state>{eigw['State']}</state>
</item>
</attachmentSet>
- <tagSet/>
+ {_tag_set_xml(eigw['EgressOnlyInternetGatewayId'])}
</item>"""
return _xml(200, "DescribeEgressOnlyInternetGatewaysResponse",
f"<egressOnlyInternetGatewaySet>{items}</egressOnlyInternetGatewaySet>")
@@ -3186,7 +3190,7 @@ def _prefix_list_xml(pl, tag="item"):
<version>{pl.get('Version',1)}</version>
<prefixListArn>{pl.get('PrefixListArn','')}</prefixListArn>
<ownerId>{pl.get('OwnerId', get_account_id())}</ownerId>
- <tagSet/>
+ {_tag_set_xml(pl['PrefixListId'])}
</{tag}>"""
@@ -3268,7 +3272,7 @@ def _vgw_xml(vgw, tag="item"):
<availabilityZone>{vgw.get('AvailabilityZone','')}</availabilityZone>
<amazonSideAsn>{vgw.get('AmazonSideAsn','64512')}</amazonSideAsn>
<attachments>{attachments}</attachments>
- <tagSet/>
+ {_tag_set_xml(vgw['VpnGatewayId'])}
</{tag}>"""
@@ -3344,7 +3348,7 @@ def _cgw_xml(cgw, tag="item"):
<ipAddress>{cgw['IpAddress']}</ipAddress>
<type>{cgw['Type']}</type>
<state>{cgw['State']}</state>
- <tagSet/>
+ {_tag_set_xml(cgw['CustomerGatewayId'])}
</{tag}>"""
diff --git a/ministack/services/iam.py b/ministack/services/iam.py
index ebf1d1d6..bd786500 100644
--- a/ministack/services/iam.py
+++ b/ministack/services/iam.py
@@ -300,6 +300,8 @@ def _create_policy(p):
f"A policy called {name} already exists.", ns="iam")
doc = _p(p, "PolicyDocument")
description = _p(p, "Description", "")
+ # #445 (follow-up): CreatePolicy accepts Tags — honour them on create.
+ create_tags = _extract_tags(p)
policy_id = _gen_id("ANPA")
version_id = "v1"
_policies[arn] = {
@@ -313,7 +315,7 @@ def _create_policy(p):
"IsAttachable": True,
"Path": path,
"Description": description,
- "Tags": [],
+ "Tags": list(create_tags or []),
"Versions": {
version_id: {
"Document": doc,
@@ -1468,6 +1470,16 @@ def _managed_policy_xml(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 ""
+ # Tags emission mirrors _user_xml / _role_xml (#445). TagPolicy mutates
+ # _policies[arn]["Tags"]; without this block GetPolicy/ListPolicies drop
+ # them and Terraform re-adds default_tags on every apply.
+ tags_xml = ""
+ if pol.get("Tags"):
+ tag_members = "".join(
+ f"<member><Key>{t['Key']}</Key><Value>{t['Value']}</Value></member>"
+ for t in pol["Tags"]
+ )
+ tags_xml = f"<Tags>{tag_members}</Tags>"
return (f"<PolicyName>{pol['PolicyName']}</PolicyName>"
f"<Arn>{arn}</Arn>"
f"<PolicyId>{pol['PolicyId']}</PolicyId>"
@@ -1477,7 +1489,8 @@ def _managed_policy_xml(arn):
f"<CreateDate>{pol['CreateDate']}</CreateDate>"
f"<UpdateDate>{pol.get('UpdateDate', pol['CreateDate'])}</UpdateDate>"
f"<Path>{pol.get('Path', '/')}</Path>"
- f"{description_xml}")
+ f"{description_xml}"
+ f"{tags_xml}")
def _group_xml(name):
diff --git a/pyproject.toml b/pyproject.toml
index c763d8ec..ed4f5651 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.3.12"
+version = "1.3.13"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_iam.py b/tests/test_iam.py
index 444faa8b..68d40fd7 100644
--- a/tests/test_iam.py
+++ b/tests/test_iam.py
@@ -310,6 +310,35 @@ def test_iam_policy_tags(iam):
tags2 = iam.list_policy_tags(PolicyArn=arn)
assert not any(t["Key"] == "env" for t in tags2["Tags"])
+
+def test_iam_policy_tags_serialized_in_get_policy(iam):
+ """Regression for #445: _managed_policy_xml must emit Tags so GetPolicy /
+ ListPolicies surface them. Without this block, Terraform's aws_iam_policy
+ refresh sees tags_all={} and replans default_tags on every apply — same
+ bug class as #441 (user tags) and #438 (policy description)."""
+ import uuid as _u
+ name = f"tagged-serialize-{_u.uuid4().hex[:8]}"
+ resp = iam.create_policy(
+ PolicyName=name,
+ PolicyDocument=json.dumps({"Version": "2012-10-17",
+ "Statement": [{"Effect": "Allow", "Action": "*", "Resource": "*"}]}),
+ Tags=[{"Key": "Team", "Value": "platform"}],
+ )
+ arn = resp["Policy"]["Arn"]
+ # CreatePolicy response must carry Tags.
+ create_tags = {t["Key"]: t["Value"] for t in resp["Policy"].get("Tags") or []}
+ assert create_tags.get("Team") == "platform", f"CreatePolicy dropped Tags: {resp['Policy']}"
+ # GetPolicy (separate endpoint, uses _managed_policy_xml) must too.
+ got = iam.get_policy(PolicyArn=arn)
+ got_tags = {t["Key"]: t["Value"] for t in got["Policy"].get("Tags") or []}
+ assert got_tags.get("Team") == "platform", f"GetPolicy dropped Tags: {got['Policy']}"
+ # TagPolicy after-the-fact must also round-trip via GetPolicy.
+ iam.tag_policy(PolicyArn=arn, Tags=[{"Key": "Env", "Value": "dev"}])
+ got2 = iam.get_policy(PolicyArn=arn)
+ got2_tags = {t["Key"]: t["Value"] for t in got2["Policy"].get("Tags") or []}
+ assert got2_tags == {"Team": "platform", "Env": "dev"}
+ iam.delete_policy(PolicyArn=arn)
+
def test_iam_update_role(iam):
iam.create_role(
RoleName="test-update-role",
diff --git a/tests/test_s3.py b/tests/test_s3.py
index 749901e7..0d4769de 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -353,6 +353,54 @@ def test_s3_control_list_tags_for_resource(s3):
tags = {t["Key"]: t["Value"] for t in resp.get("Tags", [])}
assert tags.get("name") == "ministack-test"
+def test_s3_control_tag_resource_post_xml_stores_tags(s3):
+ """Regression for #447: S3Control TagResource must accept POST with an XML
+ TagResourceRequest body (what AWS SDK Go v2 / terraform-aws-provider v6+
+ send) and persist the tags. Previously the handler only had GET/PUT/DELETE
+ and parsed bodies as JSON, silently dropping all tags.
+ """
+ import urllib.request, urllib.parse
+ bkt = "intg-s3control-tag-post"
+ s3.create_bucket(Bucket=bkt)
+ arn = urllib.parse.quote(f"arn:aws:s3:::{bkt}", safe="")
+ xml_body = (
+ '<TagResourceRequest xmlns="http://awss3control.amazonaws.com/doc/2018-08-20/">'
+ "<Tags>"
+ "<Tag><Key>demo:environment</Key><Value>repro</Value></Tag>"
+ "<Tag><Key>demo:owner</Key><Value>ministack</Value></Tag>"
+ "</Tags>"
+ "</TagResourceRequest>"
+ ).encode()
+ req = urllib.request.Request(
+ f"http://localhost:4566/v20180820/tags/{arn}",
+ method="POST",
+ data=xml_body,
+ headers={
+ "x-amz-account-id": "000000000000",
+ "Content-Type": "application/xml",
+ },
+ )
+ with urllib.request.urlopen(req) as r:
+ assert r.status in (200, 204)
+
+ # Visible via the regular S3 API (same _bucket_tags dict)
+ got = s3.get_bucket_tagging(Bucket=bkt)
+ tags = {t["Key"]: t["Value"] for t in got["TagSet"]}
+ assert tags["demo:environment"] == "repro"
+ assert tags["demo:owner"] == "ministack"
+
+ # And via S3 Control GET /v20180820/tags/{arn}
+ get_req = urllib.request.Request(
+ f"http://localhost:4566/v20180820/tags/{arn}",
+ method="GET",
+ headers={"x-amz-account-id": "000000000000"},
+ )
+ with urllib.request.urlopen(get_req) as r:
+ body = r.read().decode()
+ assert "demo:environment" in body
+ assert "repro" in body
+
+
def test_s3_control_list_tags_via_s3_control_host(s3):
"""S3 Control requests via s3-control.localhost host must not be intercepted by S3 vhost."""
import urllib.request, urllib.parse