Skip to content

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

fix(sqs): remove policy attributes explicitly set to an empty string (#2227)

Kinone9a10d3a7bb8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bef2d23e..7f325333 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+
+- **SQS — empty policy updates** — `SetQueueAttributes` removes `Policy`, `RedrivePolicy`, and `RedriveAllowPolicy` when explicitly set to an empty string, so Terraform policy deletion succeeds and subsequent attribute reads omit the removed policy. Invalid nonempty redrive policies and numeric attributes are still rejected before any attributes change.
- **AppSync Events event payloads**: deliver each WebSocket data frame with a string `event` field, matching observed AWS behavior. HTTP and WebSocket publish batches still produce one frame per event.
- **CloudFront — function status follows publish and association** — `DescribeFunction` and `ListFunctions` reported the `DEVELOPMENT` stage as `UNPUBLISHED` even after `PublishFunction`, so Terraform's `aws_cloudfront_function.status`, which reads that stage, never left `UNPUBLISHED`; once the current development version is published it now reports `UNASSOCIATED`, or `ASSOCIATED` while a distribution's cache behavior references the function, and an `UpdateFunction` makes it `UNPUBLISHED` again until the next publish. Contributed by @fabio-andre-rodrigues.
- **Step Functions — JSONata Fail and Wait fields are evaluated** — a JSONata Fail state raised its `Error` and `Cause` expressions as literal text, a JSONata Wait failed on a `Seconds` expression, ignored a `Timestamp` expression and dropped its `Output` and `Assign`, and JSONPath `ErrorPath`/`CausePath` were ignored; they are now evaluated, with AWS's `States.QueryEvaluationError` or `States.Runtime` for a result of the wrong type, a `Seconds` that is not a non-negative integer and an unparsable `Timestamp`.
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index 2e4d80d6..9527647f 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -940,11 +940,17 @@ def _act_set_queue_attributes(data: dict, qurl: str) -> dict:
url = data.get("QueueUrl", qurl)
q = _get_q(url, "sqs:SetQueueAttributes")
incoming = data.get("Attributes") or {}
- if "RedrivePolicy" in incoming:
+ if "RedrivePolicy" in incoming and incoming["RedrivePolicy"] != "":
_validate_redrive_policy(str(incoming["RedrivePolicy"]))
_validate_numeric_attrs(incoming)
for k, v in incoming.items():
- q["attributes"][k] = str(v)
+ if k in {"Policy", "RedrivePolicy", "RedriveAllowPolicy"} and v == "":
+ # Terraform deletes standalone policy resources with an empty
+ # attribute value. Reads must then omit the removed attribute.
+ q["attributes"].pop(k, None)
+ logger.debug("Removed queue attribute %s from %s", k, url)
+ else:
+ q["attributes"][k] = str(v)
q["attributes"]["LastModifiedTimestamp"] = str(int(time.time()))
return {}
diff --git a/tests/test_sqs_policy_removal.py b/tests/test_sqs_policy_removal.py
new file mode 100644
index 00000000..f8227a53
--- /dev/null
+++ b/tests/test_sqs_policy_removal.py
@@ -0,0 +1,99 @@
+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
+"""Terraform removes queue policies with explicit empty attribute values."""
+
+import asyncio
+import copy
+import json
+import xml.etree.ElementTree as ET
+from urllib.parse import urlencode
+
+import pytest
+
+from ministack.core.responses import AccountRegionScopedDict
+from ministack.services import sqs
+
+
+def queue(monkeypatch):
+ monkeypatch.setattr(sqs, "_queues", AccountRegionScopedDict())
+ monkeypatch.setattr(sqs, "_queue_name_to_url", AccountRegionScopedDict())
+ url = sqs._act_create_queue({"QueueName": "policy-removal"}, "")["QueueUrl"]
+ dlq = sqs._act_create_queue({"QueueName": "policy-removal-dlq"}, "")["QueueUrl"]
+ arn = sqs._act_get_queue_attributes({"QueueUrl": dlq}, "")["Attributes"]["QueueArn"]
+ policies = {
+ "Policy": json.dumps({"Version": "2012-10-17", "Statement": []}),
+ "RedrivePolicy": json.dumps({"deadLetterTargetArn": arn, "maxReceiveCount": "3"}),
+ "RedriveAllowPolicy": json.dumps({"redrivePermission": "denyAll"}),
+ }
+ sqs._act_set_queue_attributes({"QueueUrl": url, "Attributes": policies}, "")
+ return url, policies
+
+
+def _request(protocol, action, url, attributes=None, names=None):
+ if protocol == "json":
+ data = {"QueueUrl": url}
+ if attributes is not None:
+ data["Attributes"] = attributes
+ if names is not None:
+ data["AttributeNames"] = names
+ headers = {"x-amz-target": f"AmazonSQS.{action}"}
+ body = json.dumps(data).encode()
+ else:
+ data = {"Action": action, "QueueUrl": url}
+ for i, (key, value) in enumerate((attributes or {}).items(), 1):
+ data[f"Attribute.{i}.Name"] = key
+ data[f"Attribute.{i}.Value"] = value
+ for i, name in enumerate(names or [], 1):
+ data[f"AttributeName.{i}"] = name
+ headers = {"content-type": "application/x-www-form-urlencoded"}
+ body = urlencode(data).encode()
+ return asyncio.run(sqs.handle_request("POST", "/", headers, body, {}))
+
+
+def _read(protocol, url, names):
+ status, _, body = _request(protocol, "GetQueueAttributes", url, names=names)
+ assert status == 200
+ if protocol == "json":
+ return json.loads(body)["Attributes"]
+ ns = "{http://queue.amazonaws.com/doc/2012-11-05/}"
+ return {entry.findtext(f"{ns}Name"): entry.findtext(f"{ns}Value")
+ for entry in ET.fromstring(body).iter(f"{ns}Attribute")}
+
+
[email protected]("protocol", ["json", "query"])
[email protected]("attribute", ["Policy", "RedrivePolicy", "RedriveAllowPolicy"])
+def test_empty_policy_removes_attribute_from_all_and_specific_reads(queue, protocol, attribute):
+ url, policies = queue
+ assert _read(protocol, url, [attribute]) == {attribute: policies[attribute]}
+ for _ in range(2):
+ status, _, body = _request(protocol, "SetQueueAttributes", url, {attribute: ""})
+ assert status == 200, body
+ assert _read(protocol, url, [attribute]) == {}
+ remaining = _read(protocol, url, ["All"])
+ assert attribute not in remaining
+ for other in policies.keys() - {attribute}:
+ assert remaining[other] == policies[other]
+ assert remaining["VisibilityTimeout"] == "30"
+
+
[email protected]("invalid", [{"RedrivePolicy": "not-json"},
+ {"RedrivePolicy": '"double-encoded"'},
+ {"VisibilityTimeout": "-1"}])
+def test_invalid_update_preserves_all_attributes(queue, invalid):
+ url, _ = queue
+ before = copy.deepcopy(sqs._queues[url])
+ status, _, body = _request("json", "SetQueueAttributes", url, {"Policy": "", **invalid})
+ assert status == 400
+ assert json.loads(body)["__type"] == "InvalidAttributeValue"
+ assert sqs._queues[url] == before
+
+
+def test_removed_policies_remain_absent_after_persistence_round_trip(queue):
+ url, policies = queue
+ assert _request("json", "SetQueueAttributes", url, dict.fromkeys(policies, ""))[0] == 200
+ state = sqs.get_state()
+ sqs._queues.clear()
+ sqs._queue_name_to_url.clear()
+ sqs.load_persisted_state(state)
+ assert policies.keys().isdisjoint(_read("json", url, ["All"]))
+ assert _read("json", url, ["QueueArn"])["QueueArn"].endswith(":policy-removal")