Sub topic 13
Letting SNS write to SQS: queue access policies
This chapter assumes you can create an SQS queue and an SNS topic with boto3 and read an IAM policy document. Fan-out, which a later chapter covers, depends on the permission described here.
Why a subscription is not enough
When you subscribe a queue to a topic, SNS becomes a sender that needs permission to call sqs:SendMessage on your queue. SNS does not use your IAM user or role for this. It acts as the AWS service principal sns.amazonaws.com. The queue must therefore carry a resource-based policy, also called a queue access policy, that allows that principal.
Without the policy, the subscription still gets created and publish still succeeds. SNS fails to deliver in the background, and the queue stays empty. This is the most common fan-out mistake. It produces no exception in your code.
Anatomy of the policy
A queue policy is a JSON document with one or more statements. A statement for SNS has four parts:
| Element | Value | Purpose |
|---|---|---|
| `Effect` | `Allow` | Grants the action. |
| `Principal` | `{"Service": "sns.amazonaws.com"}` | Names SNS as the caller. |
| `Action` | `sqs:SendMessage` | The only operation SNS needs. |
| `Condition` | `ArnEquals` on `aws:SourceArn` | Limits the grant to specific topics. |
The condition is the part that is easy to leave out. The principal sns.amazonaws.com stands for the SNS service as a whole. SNS topics owned by any account could be written to your queue if the statement had no condition. Pinning aws:SourceArn to your topic's ARN means only that topic can send. This prevents the confused deputy problem, where a trusted service is tricked into acting for someone who should not have access.
Applying the policy with boto3
The policy goes in the queue attribute Policy. The helper below builds the statement for one or more topics and applies it.
import json
import boto3
sqs = boto3.client("sqs")
def allow_topics(queue_url, topic_arns):
"""Let the given SNS topics send messages to the queue."""
queue_arn = sqs.get_queue_attributes(
QueueUrl=queue_url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
policy = {
"Version": "2012-10-17",
"Statement": [{
"Sid": "AllowSnsTopics",
"Effect": "Allow",
"Principal": {"Service": "sns.amazonaws.com"},
"Action": "sqs:SendMessage",
"Resource": queue_arn,
"Condition": {"ArnEquals": {"aws:SourceArn": topic_arns}},
}],
}
sqs.set_queue_attributes(
QueueUrl=queue_url, Attributes={"Policy": json.dumps(policy)}
)
queue_url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
sns = boto3.client("sns")
topic_arn = sns.create_topic(Name="order-events")["TopicArn"]
allow_topics(queue_url, [topic_arn])ArnEquals accepts a list, so one statement can cover several topics. Use the exact ARN. A wildcard such as arn:aws:sns:us-east-1:111122223333:* allows every topic in the account, which is rarely what you want.
Setting the policy replaces the old one
set_queue_attributes overwrites the whole Policy attribute. If the queue already has statements, for example one that lets a producer role send directly, read the existing policy with get_queue_attributes, add your statement, and write the merged document back. Otherwise you silently remove the earlier permissions.
Verifying that delivery works
Check the permission end to end instead of trusting the policy text. Subscribe the queue, publish a test message, and receive it. With raw message delivery off, the queue body is the SNS JSON envelope, so the test below reads the Message field.
import json
import boto3
sns = boto3.client("sns")
sqs = boto3.client("sqs")
queue_url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
queue_arn = sqs.get_queue_attributes(
QueueUrl=queue_url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
topic_arn = sns.create_topic(Name="order-events")["TopicArn"]
sns.subscribe(TopicArn=topic_arn, Protocol="sqs", Endpoint=queue_arn)
sns.publish(TopicArn=topic_arn, Message=json.dumps({"check": "policy"}))
resp = sqs.receive_message(
QueueUrl=queue_url, MaxNumberOfMessages=1, WaitTimeSeconds=10
)
messages = resp.get("Messages", [])
if messages:
envelope = json.loads(messages[0]["Body"])
print("delivered:", envelope["Message"])
else:
print("nothing arrived: check the queue policy and the topic ARN")An empty result after the wait almost always means the policy is missing or names the wrong topic.
Cross-account and encrypted queues
Two situations need more than the basic statement.
- Cross-account delivery. If the topic and queue are in different accounts, the queue policy must still allow the topic's ARN in
aws:SourceArn. The subscription must also be confirmed by the queue's owner. A queue and topic in different Regions can be subscribed too, as long as the queue policy names the topic ARN. - Server-side encryption with a customer managed KMS key. SNS must be allowed to use the key, or the queue rejects its messages. The key policy needs a statement that lets
sns.amazonaws.comcallkms:GenerateDataKeyandkms:Decrypt. The default AWS managed key for SQS (alias/aws/sqs) cannot be modified to allow this, so use a customer managed key for encrypted fan-out. The chapter on encryption covers this in detail.
Troubleshooting checklist
- Confirm the subscription exists and is not pending confirmation. Use
list_subscriptions_by_topic. - Read the queue's
Policyattribute and compare theaws:SourceArnvalue with the topic ARN character by character, including Region and account ID. - Check that
Resourceis the queue's ARN, not its URL. - Look at the SNS CloudWatch metric
NumberOfNotificationsFailedfor the topic. A rising value means delivery is being rejected. - If the queue uses a customer managed KMS key, check the key policy.
Exercise
You subscribed an SQS queue to an SNS topic, and publish returns a message ID, but the queue never receives anything. Name the most likely cause and the two parts of the queue policy statement that must be correct to fix it.
Show answer
The queue has no resource-based policy allowing SNS to send to it. The statement needs the principal {"Service": "sns.amazonaws.com"} with the action sqs:SendMessage on the queue's ARN, and a condition ArnEquals on aws:SourceArn that matches the topic's ARN exactly.