Skip to content

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

fix(aws) update parity (#623)

Nahuel Nucera1050beee206d
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index ad620ba3..a8d14e8e 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -1185,6 +1185,44 @@ def _apigw_method_delete(physical_id, props):
_apigw_v1._delete_method(api_id, resource_id, http_method)
+# --- API Gateway Authorizer ---
+
+def _apigw_authorizer_create(logical_id, props, stack_name):
+ """Provision an AWS::ApiGateway::Authorizer.
+
+ Maps CFN properties to the existing apigateway_v1 authorizer store:
+ Name, Type (TOKEN / REQUEST / COGNITO_USER_POOLS), AuthorizerUri,
+ AuthorizerCredentials, IdentitySource, IdentityValidationExpression,
+ AuthorizerResultTtlInSeconds, ProviderARNs, RestApiId. ``AuthType`` is
+ documented in the AWS CFN spec as informational only; the underlying
+ apigateway_v1._create_authorizer record does not currently expose it,
+ so the field is dropped here.
+ """
+ api_id = props.get("RestApiId", "")
+ data = {
+ "name": props.get("Name", logical_id),
+ "type": props.get("Type", "TOKEN"),
+ "authorizerUri": props.get("AuthorizerUri", ""),
+ "authorizerCredentials": props.get("AuthorizerCredentials"),
+ "identitySource": props.get("IdentitySource", "method.request.header.Authorization"),
+ "identityValidationExpression": props.get("IdentityValidationExpression", ""),
+ "authorizerResultTtlInSeconds": props.get("AuthorizerResultTtlInSeconds", 300),
+ "providerARNs": props.get("ProviderARNs", []),
+ }
+ status, headers, body = _apigw_v1._create_authorizer(api_id, data)
+ if status >= 400:
+ raise ValueError(f"AWS::ApiGateway::Authorizer create failed: {body!r}")
+ authorizer = json.loads(body) if isinstance(body, (bytes, bytearray)) else json.loads(body)
+ authorizer_id = authorizer.get("id", "")
+ return authorizer_id, {"AuthorizerId": authorizer_id}
+
+
+def _apigw_authorizer_delete(physical_id, props):
+ api_id = props.get("RestApiId", "")
+ authorizers = _apigw_v1._authorizers_v1.get(api_id, {})
+ authorizers.pop(physical_id, None)
+
+
# --- API Gateway Deployment ---
def _apigw_deployment_create(logical_id, props, stack_name):
@@ -3162,6 +3200,7 @@ _RESOURCE_HANDLERS = {
"AWS::ApiGateway::RestApi": {"create": _apigw_rest_api_create, "delete": _apigw_rest_api_delete},
"AWS::ApiGateway::Resource": {"create": _apigw_resource_create, "delete": _apigw_resource_delete},
"AWS::ApiGateway::Method": {"create": _apigw_method_create, "delete": _apigw_method_delete},
+ "AWS::ApiGateway::Authorizer": {"create": _apigw_authorizer_create, "delete": _apigw_authorizer_delete},
"AWS::ApiGateway::Deployment": {"create": _apigw_deployment_create, "delete": _apigw_deployment_delete},
"AWS::ApiGateway::Stage": {"create": _apigw_stage_create, "delete": _apigw_stage_delete},
"AWS::Lambda::EventSourceMapping": {"create": _lambda_esm_create, "delete": _lambda_esm_delete},
diff --git a/ministack/services/eventbridge.py b/ministack/services/eventbridge.py
index 67b9ea03..95f45813 100644
--- a/ministack/services/eventbridge.py
+++ b/ministack/services/eventbridge.py
@@ -942,7 +942,7 @@ def _invoke_target(target, event, rule):
if ":lambda:" in arn or ":function:" in arn:
_dispatch_to_lambda(arn, event_payload)
elif ":sqs:" in arn:
- _dispatch_to_sqs(arn, event_payload)
+ _dispatch_to_sqs(arn, event_payload, target.get("SqsParameters") or {})
elif ":sns:" in arn:
_dispatch_to_sns(arn, event_payload)
else:
@@ -1013,7 +1013,16 @@ def _dispatch_to_lambda(arn, payload):
logger.info("EventBridge → Lambda %s: dispatched", func_name)
-def _dispatch_to_sqs(arn, payload):
+def _dispatch_to_sqs(arn, payload, sqs_parameters=None):
+ """Dispatch an EventBridge event to an SQS queue.
+
+ ``sqs_parameters`` carries the target's ``SqsParameters`` block from the
+ rule definition. For FIFO target queues, ``SqsParameters.MessageGroupId``
+ is required by AWS and must be stamped on the delivered message; for
+ standard queues it is ignored. Real EventBridge also derives a
+ content-based ``MessageDeduplicationId`` for FIFO queues when content
+ deduplication is enabled — we mirror that here.
+ """
from ministack.services import sqs as _sqs
queue_name = arn.split(":")[-1]
@@ -1023,10 +1032,11 @@ def _dispatch_to_sqs(arn, payload):
logger.warning("EventBridge → SQS: queue %s not found", queue_name)
return
+ sqs_parameters = sqs_parameters or {}
msg_id = new_uuid()
md5 = hashlib.md5(payload.encode()).hexdigest()
now = time.time()
- queue["messages"].append({
+ msg = {
"id": msg_id,
"body": payload,
"md5_body": md5,
@@ -1040,7 +1050,25 @@ def _dispatch_to_sqs(arn, payload):
"SenderId": "AROAEXAMPLE",
"SentTimestamp": str(int(now * 1000)),
},
- })
+ }
+ if queue.get("is_fifo"):
+ group_id = sqs_parameters.get("MessageGroupId") or ""
+ if not group_id:
+ logger.warning(
+ "EventBridge → SQS %s is FIFO but target SqsParameters.MessageGroupId is empty; "
+ "real AWS would refuse to deliver. Generating a fallback so the message is not lost.",
+ queue_name,
+ )
+ group_id = "ministack-eventbridge-default"
+ msg["group_id"] = group_id
+ # Mirror real EventBridge: derive a content-based dedup ID when none is
+ # supplied so retries are idempotent within the FIFO dedup window.
+ msg["dedup_id"] = hashlib.sha256(payload.encode()).hexdigest()
+ # Maintain sequence numbering so subsequent ReceiveMessage calls see
+ # the same ordering as native SQS FIFO deliveries.
+ queue["fifo_seq"] = queue.get("fifo_seq", 0) + 1
+ msg["seq"] = str(queue["fifo_seq"]).zfill(20)
+ queue["messages"].append(msg)
if hasattr(_sqs, "_ensure_msg_fields"):
_sqs._ensure_msg_fields(queue["messages"][-1])
logger.info("EventBridge → SQS %s", queue_name)
diff --git a/ministack/services/sns.py b/ministack/services/sns.py
index fdbf54aa..804392dd 100644
--- a/ministack/services/sns.py
+++ b/ministack/services/sns.py
@@ -553,6 +553,16 @@ def _publish(params):
topic = _topics[topic_arn]
msg_attrs = _parse_message_attributes(params)
+
+ # AWS rejects Publish requests whose Message + MessageAttributes exceed
+ # 256 KiB. Real-AWS error code is InvalidParameter (400).
+ if _message_payload_size(message, msg_attrs) > _SNS_MAX_PAYLOAD_BYTES:
+ return _error(
+ "InvalidParameter",
+ f"Invalid parameter: Message too long. Maximum size is {_SNS_MAX_PAYLOAD_BYTES} bytes.",
+ 400,
+ )
+
fifo = _is_fifo_topic(topic)
# ── FIFO validation, deduplication, and sequencing ──
@@ -678,6 +688,19 @@ def _publish_batch(params):
group_id = entry.get("message_group_id", "")
entry_dedup_id = entry.get("message_dedup_id", "")
+ # Per-entry payload size check: real AWS surfaces each oversized entry
+ # as a per-entry failure rather than failing the whole batch.
+ if _message_payload_size(message, msg_attrs) > _SNS_MAX_PAYLOAD_BYTES:
+ failed += (
+ "<member>"
+ f"<Id>{_xml_escape(eid)}</Id>"
+ f"<Code>InvalidParameter</Code>"
+ f"<Message>Invalid parameter: Message too long. Maximum size is {_SNS_MAX_PAYLOAD_BYTES} bytes.</Message>"
+ f"<SenderFault>true</SenderFault>"
+ "</member>"
+ )
+ continue
+
# ── FIFO per-entry validation ──
if fifo:
if not group_id:
@@ -1124,6 +1147,28 @@ def _refresh_subscription_counts(topic: dict):
topic["attributes"]["SubscriptionsPending"] = str(pending)
+_SNS_MAX_PAYLOAD_BYTES = 262144 # 256 KiB, per AWS SNS Publish docs
+
+
+def _message_payload_size(message: str, attrs: dict) -> int:
+ """Return the byte size of a Publish payload (Message + MessageAttributes).
+
+ Subject is intentionally excluded — AWS docs limit it to 100 chars but
+ don't count it toward the 256 KiB Publish size limit.
+ """
+ total = len((message or "").encode("utf-8"))
+ for name, attr in (attrs or {}).items():
+ total += len(name.encode("utf-8"))
+ total += len((attr.get("DataType") or "").encode("utf-8"))
+ sv = attr.get("StringValue")
+ if sv:
+ total += len(sv.encode("utf-8"))
+ bv = attr.get("BinaryValue")
+ if bv:
+ total += len(bv) if isinstance(bv, (bytes, bytearray)) else len(bv.encode("utf-8"))
+ return total
+
+
def _parse_message_attributes(params) -> dict:
"""Parse MessageAttributes.entry.N.Name / .Value.DataType / .Value.StringValue"""
attrs = {}
diff --git a/ministack/services/sqs.py b/ministack/services/sqs.py
index 09f27d4b..367dc923 100644
--- a/ministack/services/sqs.py
+++ b/ministack/services/sqs.py
@@ -270,6 +270,20 @@ def _act_send_message(data: dict, qurl: str) -> dict:
raise _Err("MissingParameter",
"The request must contain the parameter MessageBody.")
+ # AWS SQS rejects messages exceeding the queue's MaximumMessageSize attribute
+ # (default 262144 bytes; configurable up to 1 MiB / 1048576). Real AWS error
+ # is InvalidParameterValue (400) with the queue-configured limit in the message.
+ try:
+ max_size = int(q["attributes"].get("MaximumMessageSize", "262144"))
+ except (TypeError, ValueError):
+ max_size = 262144
+ body_bytes = len(body_text.encode("utf-8"))
+ if body_bytes > max_size:
+ raise _Err(
+ "InvalidParameterValue",
+ f"One or more parameters are invalid. Reason: Message must be shorter than {max_size} bytes.",
+ )
+
delay = int(data.get("DelaySeconds")
or q["attributes"].get("DelaySeconds", "0"))
msg_attrs = data.get("MessageAttributes") or {}
@@ -507,6 +521,102 @@ def _act_set_queue_attributes(data: dict, qurl: str) -> dict:
return {}
+# ── AddPermission / RemovePermission ───────────────────────
+#
+# AddPermission appends a Statement to the queue's IAM resource policy
+# (stored as the ``Policy`` queue attribute, exactly the same JSON shape
+# that ``SetQueueAttributes`` accepts and ``GetQueueAttributes`` returns).
+# RemovePermission removes the Statement whose ``Sid`` matches the
+# supplied Label. Both surface the result through the existing Policy
+# attribute, so consumers that read it via ``GetQueueAttributes`` see
+# the change.
+
+def _act_add_permission(data: dict, qurl: str) -> dict:
+ url = data.get("QueueUrl", qurl)
+ q = _get_q(url)
+ label = data.get("Label") or ""
+ if not label:
+ raise _Err("MissingParameter",
+ "The request must contain the parameter Label.")
+ account_ids = data.get("AWSAccountIds") or []
+ if isinstance(account_ids, str):
+ account_ids = [account_ids]
+ actions = data.get("Actions") or []
+ if isinstance(actions, str):
+ actions = [actions]
+ if not account_ids:
+ raise _Err("MissingParameter",
+ "The request must contain the parameter AWSAccountIds.")
+ if not actions:
+ raise _Err("MissingParameter",
+ "The request must contain the parameter Actions.")
+
+ queue_arn = q["attributes"].get("QueueArn")
+ raw = q["attributes"].get("Policy") or ""
+ try:
+ policy = json.loads(raw) if raw else {}
+ except (TypeError, json.JSONDecodeError):
+ policy = {}
+ policy.setdefault("Version", "2012-10-17")
+ policy.setdefault("Id", f"{queue_arn}/SQSDefaultPolicy")
+ statements = policy.setdefault("Statement", [])
+ if isinstance(statements, dict):
+ statements = [statements]
+ policy["Statement"] = statements
+
+ # AWS rejects a duplicate Label with InvalidParameterValue.
+ if any(s.get("Sid") == label for s in statements):
+ raise _Err(
+ "InvalidParameterValue",
+ f"Value {label} for parameter Label is invalid. Reason: Already exists.",
+ )
+
+ # AWS canonical Policy shape per the SQS developer guide:
+ # Principal.AWS holds bare 12-digit account IDs; Action uses the
+ # lowercase IAM namespace prefix `sqs:`.
+ statements.append({
+ "Sid": label,
+ "Effect": "Allow",
+ "Principal": {"AWS": list(account_ids)},
+ "Action": [a if a.startswith("sqs:") else f"sqs:{a[4:]}" if a.startswith("SQS:") else f"sqs:{a}" for a in actions],
+ "Resource": queue_arn,
+ })
+ q["attributes"]["Policy"] = json.dumps(policy)
+ q["attributes"]["LastModifiedTimestamp"] = str(int(time.time()))
+ return {}
+
+
+def _act_remove_permission(data: dict, qurl: str) -> dict:
+ url = data.get("QueueUrl", qurl)
+ q = _get_q(url)
+ label = data.get("Label") or ""
+ if not label:
+ raise _Err("MissingParameter",
+ "The request must contain the parameter Label.")
+
+ raw = q["attributes"].get("Policy") or ""
+ if not raw:
+ # Real AWS is idempotent — no policy means nothing to remove, no error.
+ return {}
+ try:
+ policy = json.loads(raw)
+ except (TypeError, json.JSONDecodeError):
+ return {}
+ statements = policy.get("Statement") or []
+ if isinstance(statements, dict):
+ statements = [statements]
+ remaining = [s for s in statements if s.get("Sid") != label]
+ if remaining:
+ policy["Statement"] = remaining
+ q["attributes"]["Policy"] = json.dumps(policy)
+ else:
+ # No statements left — drop the Policy attribute entirely so
+ # GetQueueAttributes reflects "no policy" the way AWS does.
+ q["attributes"].pop("Policy", None)
+ q["attributes"]["LastModifiedTimestamp"] = str(int(time.time()))
+ return {}
+
+
# ── PurgeQueue ──────────────────────────────────────────────
def _act_purge_queue(data: dict, qurl: str) -> dict:
@@ -614,6 +724,8 @@ _HANDLERS.update({
"ChangeMessageVisibilityBatch": _act_change_visibility_batch,
"GetQueueAttributes": _act_get_queue_attributes,
"SetQueueAttributes": _act_set_queue_attributes,
+ "AddPermission": _act_add_permission,
+ "RemovePermission": _act_remove_permission,
"PurgeQueue": _act_purge_queue,
"SendMessageBatch": _act_send_message_batch,
"DeleteMessageBatch": _act_delete_message_batch,
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index f4614c50..1d272975 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -3014,3 +3014,45 @@ def test_cfn_lambda_s3_ref_bucket_has_code_size(cfn, lam, s3):
cfn.delete_stack(StackName=stack_name)
_wait_stack(cfn, stack_name)
+
+
+# -- AWS::ApiGateway::Authorizer ---------------------------------------
+
+
+def test_cfn_apigateway_authorizer_provisions(cfn):
+ """AWS::ApiGateway::Authorizer was previously not registered in the
+ CFN resource handler map, so stacks that declared a custom authorizer
+ failed with `Unsupported resource type`. The handler now provisions
+ the authorizer against the existing apigateway_v1 store."""
+ stack_name = f"intg-cfn-authz-{_uuid_mod.uuid4().hex[:8]}"
+ template = {
+ "Resources": {
+ "Api": {
+ "Type": "AWS::ApiGateway::RestApi",
+ "Properties": {"Name": "intg-authz-api"},
+ },
+ "Auth": {
+ "Type": "AWS::ApiGateway::Authorizer",
+ "Properties": {
+ "Name": "intg-token-authz",
+ "Type": "TOKEN",
+ "RestApiId": {"Ref": "Api"},
+ "AuthorizerUri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:noop/invocations",
+ "IdentitySource": "method.request.header.Authorization",
+ "AuthorizerResultTtlInSeconds": 300,
+ },
+ },
+ },
+ "Outputs": {
+ "AuthorizerId": {"Value": {"Ref": "Auth"}},
+ },
+ }
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+
+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack.get("Outputs", [])}
+ assert outputs.get("AuthorizerId"), "AuthorizerId output should be populated"
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
diff --git a/tests/test_eventbridge.py b/tests/test_eventbridge.py
index df7e56c1..5b53aff2 100644
--- a/tests/test_eventbridge.py
+++ b/tests/test_eventbridge.py
@@ -1500,3 +1500,47 @@ def test_scheduler_first_sight_with_recent_creation_time_waits(isolated_schedule
_eb._targets._data[_STATE_KEY] = list(_DUMMY_TARGET)
_eb._tick_scheduled_rules()
isolated_scheduler.assert_not_called()
+
+
+# -- EventBridge → FIFO SQS target requires MessageGroupId --------------
+
+
+def test_eventbridge_dispatch_to_fifo_sqs_stamps_message_group_id(eb, sqs):
+ """When a rule's target is a FIFO SQS queue, EventBridge must read
+ SqsParameters.MessageGroupId from the target spec and stamp it on the
+ delivered message. Before this fix MS dropped MessageGroupId at
+ dispatch, so FIFO targets received messages with no group_id."""
+ q_url = sqs.create_queue(
+ QueueName=f"intg-eb-fifo-{_uuid_mod.uuid4().hex[:8]}.fifo",
+ Attributes={"FifoQueue": "true", "ContentBasedDeduplication": "true"},
+ )["QueueUrl"]
+ q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+
+ rule_name = f"intg-eb-fifo-rule-{_uuid_mod.uuid4().hex[:8]}"
+ eb.put_rule(Name=rule_name, EventPattern=json.dumps({"source": ["app.test"]}))
+ eb.put_targets(
+ Rule=rule_name,
+ Targets=[{
+ "Id": "1",
+ "Arn": q_arn,
+ "SqsParameters": {"MessageGroupId": "orders"},
+ }],
+ )
+ eb.put_events(Entries=[{
+ "Source": "app.test",
+ "DetailType": "Order",
+ "Detail": json.dumps({"orderId": "o1"}),
+ }])
+
+ # FIFO queues require MessageGroupId; ReceiveMessage with the attribute name
+ # surfaces it.
+ time.sleep(0.5)
+ resp = sqs.receive_message(
+ QueueUrl=q_url,
+ MaxNumberOfMessages=10,
+ AttributeNames=["MessageGroupId"],
+ )
+ msgs = resp.get("Messages") or []
+ assert msgs, "FIFO queue received no messages from EventBridge"
+ attrs = msgs[0].get("Attributes", {})
+ assert attrs.get("MessageGroupId") == "orders"
diff --git a/tests/test_sns.py b/tests/test_sns.py
index d8eae6e5..b37b50ba 100644
--- a/tests/test_sns.py
+++ b/tests/test_sns.py
@@ -1239,3 +1239,53 @@ def test_sns_http_subscription_basic_auth_userinfo(sns):
finally:
httpd.shutdown()
httpd.server_close()
+
+
+# -- 256 KiB payload limit (AWS Publish docs) --------------------------
+
+
+def test_sns_publish_rejects_message_over_256_kib(sns):
+ """SNS Publish rejects payloads (Message + MessageAttributes) over
+ 256 KiB with InvalidParameter (400). Before this fix MS silently
+ accepted oversized payloads locally while real AWS rejected."""
+ topic_arn = sns.create_topic(Name=f"intg-sns-size-{_uuid_mod.uuid4().hex[:8]}")["TopicArn"]
+ oversized = "x" * (262144 + 1)
+ with pytest.raises(ClientError) as exc:
+ sns.publish(TopicArn=topic_arn, Message=oversized)
+ assert exc.value.response["Error"]["Code"] == "InvalidParameter"
+
+
+def test_sns_publish_attributes_count_toward_size_limit(sns):
+ """A Message that fits under 256 KiB on its own but is pushed past the
+ limit by MessageAttributes must still be rejected."""
+ topic_arn = sns.create_topic(Name=f"intg-sns-size-attr-{_uuid_mod.uuid4().hex[:8]}")["TopicArn"]
+ msg = "x" * 250000
+ big_attr_value = "y" * 20000
+ with pytest.raises(ClientError) as exc:
+ sns.publish(
+ TopicArn=topic_arn,
+ Message=msg,
+ MessageAttributes={
+ "k1": {"DataType": "String", "StringValue": big_attr_value},
+ },
+ )
+ assert exc.value.response["Error"]["Code"] == "InvalidParameter"
+
+
+def test_sns_publish_batch_rejects_oversized_entry_per_entry(sns):
+ """PublishBatch surfaces each oversized entry as a per-entry failure
+ rather than failing the whole batch."""
+ topic_arn = sns.create_topic(Name=f"intg-sns-batch-size-{_uuid_mod.uuid4().hex[:8]}")["TopicArn"]
+ resp = sns.publish_batch(
+ TopicArn=topic_arn,
+ PublishBatchRequestEntries=[
+ {"Id": "ok", "Message": "small"},
+ {"Id": "too-big", "Message": "x" * (262144 + 1)},
+ ],
+ )
+ ok_ids = [r["Id"] for r in resp.get("Successful", [])]
+ failed_ids = [r["Id"] for r in resp.get("Failed", [])]
+ assert "ok" in ok_ids
+ assert "too-big" in failed_ids
+ failed = next(r for r in resp["Failed"] if r["Id"] == "too-big")
+ assert failed["Code"] == "InvalidParameter"
diff --git a/tests/test_sqs.py b/tests/test_sqs.py
index 76c199a2..3aadae6b 100644
--- a/tests/test_sqs.py
+++ b/tests/test_sqs.py
@@ -584,3 +584,97 @@ def test_sqs_bare_queue_name_as_url(sqs):
assert len(msgs) == 2
bodies = sorted(m["Body"] for m in msgs)
assert bodies == ["via-name", "via-url"]
+
+
+# -- AWS-parity gaps from competitor audit ------------------------------
+# Three regressions, all surfaced when comparing MS behaviour against the
+# AWS SQS API reference: SendMessage size enforcement, AddPermission,
+# RemovePermission.
+
+
+def test_sqs_send_message_rejects_oversized_body(sqs):
+ """SendMessage must reject bodies exceeding the queue's MaximumMessageSize
+ attribute with InvalidParameterValue (400). MaximumMessageSize defaults to
+ 262144 (256 KiB) per AWS. Before this fix MS silently accepted oversized
+ messages locally while real AWS rejected — masking client bugs."""
+ import pytest as _pytest
+
+ q = sqs.create_queue(QueueName="intg-sqs-size-default")["QueueUrl"]
+ body = "x" * (262144 + 1)
+ with _pytest.raises(ClientError) as exc:
+ sqs.send_message(QueueUrl=q, MessageBody=body)
+ assert exc.value.response["Error"]["Code"] == "InvalidParameterValue"
+
+
+def test_sqs_send_message_respects_configured_maximum_message_size(sqs):
+ """A queue with a tighter MaximumMessageSize must reject bodies that fit
+ in the default 262144 but exceed the configured value."""
+ import pytest as _pytest
+
+ q = sqs.create_queue(
+ QueueName="intg-sqs-size-tight",
+ Attributes={"MaximumMessageSize": "1024"},
+ )["QueueUrl"]
+ body = "x" * 2048
+ with _pytest.raises(ClientError) as exc:
+ sqs.send_message(QueueUrl=q, MessageBody=body)
+ assert exc.value.response["Error"]["Code"] == "InvalidParameterValue"
+ assert "1024" in exc.value.response["Error"]["Message"]
+
+
+def test_sqs_add_permission_appends_policy_statement(sqs):
+ """AddPermission appends an Allow statement to the queue's Policy
+ attribute matching the AWS resource-policy shape."""
+ q = sqs.create_queue(QueueName="intg-sqs-addperm-basic")["QueueUrl"]
+ sqs.add_permission(
+ QueueUrl=q,
+ Label="perm-1",
+ AWSAccountIds=["123456789012"],
+ Actions=["SendMessage", "ReceiveMessage"],
+ )
+ attrs = sqs.get_queue_attributes(QueueUrl=q, AttributeNames=["Policy"])
+ policy = json.loads(attrs["Attributes"]["Policy"])
+ assert policy["Version"] == "2012-10-17"
+ sids = [s["Sid"] for s in policy["Statement"]]
+ assert "perm-1" in sids
+ stmt = next(s for s in policy["Statement"] if s["Sid"] == "perm-1")
+ assert stmt["Effect"] == "Allow"
+ # AWS canonical Policy shape: bare 12-digit account ID, lowercase sqs: prefix.
+ assert "123456789012" in stmt["Principal"]["AWS"]
+ assert "sqs:SendMessage" in stmt["Action"]
+
+
+def test_sqs_add_permission_rejects_duplicate_label(sqs):
+ """Real AWS rejects duplicate Labels with InvalidParameterValue."""
+ import pytest as _pytest
+
+ q = sqs.create_queue(QueueName="intg-sqs-addperm-dup")["QueueUrl"]
+ sqs.add_permission(
+ QueueUrl=q, Label="dup", AWSAccountIds=["111111111111"],
+ Actions=["SendMessage"],
+ )
+ with _pytest.raises(ClientError) as exc:
+ sqs.add_permission(
+ QueueUrl=q, Label="dup", AWSAccountIds=["222222222222"],
+ Actions=["ReceiveMessage"],
+ )
+ assert exc.value.response["Error"]["Code"] == "InvalidParameterValue"
+
+
+def test_sqs_remove_permission_drops_matching_statement(sqs):
+ """RemovePermission removes only the statement with the matching Label."""
+ q = sqs.create_queue(QueueName="intg-sqs-remperm")["QueueUrl"]
+ sqs.add_permission(
+ QueueUrl=q, Label="keep", AWSAccountIds=["111111111111"],
+ Actions=["SendMessage"],
+ )
+ sqs.add_permission(
+ QueueUrl=q, Label="drop", AWSAccountIds=["222222222222"],
+ Actions=["ReceiveMessage"],
+ )
+ sqs.remove_permission(QueueUrl=q, Label="drop")
+ attrs = sqs.get_queue_attributes(QueueUrl=q, AttributeNames=["Policy"])
+ policy = json.loads(attrs["Attributes"]["Policy"])
+ sids = [s["Sid"] for s in policy["Statement"]]
+ assert "keep" in sids
+ assert "drop" not in sids