

# Amazon SNS security
<a name="security"></a>

The AWS [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) applies to data protection in . As described in this model, AWS is responsible for protecting the global infrastructure that runs all of the AWS Cloud. You are responsible for maintaining control over your content that is hosted on this infrastructure. This content includes the security configuration and management tasks for the AWS services that you use. For more information about data privacy, see the [Data Privacy FAQ](https://aws.amazon.com/compliance/data-privacy-faq). For information about data protection in Europe, see the [AWS Shared Responsibility Model and GDPR](https://aws.amazon.com/blogs/security/the-aws-shared-responsibility-model-and-gdpr/) blog post on the *AWS Security Blog*.

For data protection purposes, we recommend that you protect AWS account credentials and set up individual user accounts with AWS Identity and Access Management (IAM). That way each user is given only the permissions necessary to fulfill their job duties. We also recommend that you secure your data in the following ways:
+ Use multi-factor authentication (MFA) with each account.
+ Use SSL/TLS to communicate with AWS resources. We recommend TLS 1.2 or later.
+ Set up API and user activity logging with AWS CloudTrail.
+ Use AWS encryption solutions, along with all default security controls within AWS services.
+ Use advanced managed security services such as Amazon Macie, which assists in discovering and securing personal data that is stored in Amazon S3.
+ If you require FIPS 140-2 validated cryptographic modules when accessing AWS through a command line interface or an API, use a FIPS endpoint. For more information about the available FIPS endpoints, see [Federal Information Processing Standard (FIPS) 140-2](https://aws.amazon.com/compliance/fips/).
+ Message data protection
  + Message data protection is a new major feature of Amazon SNS
  + Use MDP to scan message for confidential or sensitive information
  + Provide message auditing to all content flowing through the topic
  + Provide content access controls to messages published to the topic and messages delivered by the topic

**Important**  
We strongly recommend that you never put confidential or sensitive information, such as your customers' email addresses, into tags or free-form fields such as a Name field. This includes when you work with Amazon SNS or other Amazon Web Services using the console, API, AWS CLI, or AWS SDKs. Any data that you enter into tags or free-form fields used for names may be used for billing or diagnostic logs. If you provide a URL to an external server, we strongly recommend that you do not include credentials information in the URL to validate your request to that server.

# Amazon SNS data encryption
<a name="sns-data-encryption"></a>

Data protection refers to protecting data while in-transit (as it travels to and from Amazon SNS) and at rest (while it is stored on disks in Amazon SNS data centers). You can protect data in transit using Secure Sockets Layer (SSL) or client-side encryption. By default, Amazon SNS stores messages and files using disk encryption. You can protect data at rest by requesting Amazon SNS to encrypt your messages before saving them to the encrypted file system in its data centers. Amazon SNS recommends using SSE for optimized data encryption.

# Securing Amazon SNS data with server-side encryption
<a name="sns-server-side-encryption"></a>

Server-side encryption (SSE) lets you store sensitive data in encrypted topics by protecting the contents of messages in Amazon SNS topics using keys managed in AWS Key Management Service (AWS KMS).

SSE encrypts messages as soon as Amazon SNS receives them. The messages are stored in encrypted form, and only decrypted when they are sent.
+ For information about managing SSE using the AWS Management Console or the AWS SDK for Java (by setting the `KmsMasterKeyId` attribute using the `[CreateTopic](https://docs.aws.amazon.com/sns/latest/api/API_CreateTopic.html)` and `[SetTopicAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetTopicAttributes.html)` API actions), see [Setting up Amazon SNS topic encryption with server-side encryption](sns-enable-encryption-for-topic.md). 
+ For information about creating encrypted topics using CloudFormation (by setting the `KmsMasterKeyId` property using the `[AWS::SNS::Topic](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sns-topic.html)` resource), see the *AWS CloudFormation User Guide*.

**Important**  
All requests to topics with SSE enabled must use HTTPS and [Signature Version 4](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html).  
For information about compatibility of other services with encrypted topics, see your service documentation.  
Amazon SNS only supports symmetric encryption KMS keys. You cannot use any other type of KMS key to encrypt your service resources. For help determining whether a KMS key is a symmetric encryption key, see [Identifying asymmetric KMS keys](https://docs.aws.amazon.com/kms/latest/developerguide/find-symm-asymm.html).

AWS KMS combines secure, highly available hardware and software to provide a key management system scaled for the cloud. When you use Amazon SNS with AWS KMS, the [data keys](#sse-key-terms) that encrypt your message data are also encrypted and stored with the data they protect.

The following are benefits of using AWS KMS:
+ You can create and manage the [AWS KMS key](#sse-key-terms) yourself.
+ You can also use AWS-managed KMS keys for Amazon SNS, which are unique for each account and region.
+ The AWS KMS security standards can help you meet encryption-related compliance requirements.

For more information, see [What is AWS Key Management Service?](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) in the *AWS Key Management Service Developer Guide*.

## Encryption scope
<a name="what-does-sse-encrypt"></a>

SSE encrypts the body of a message in an Amazon SNS topic.

SSE doesn't encrypt the following:
+ Topic metadata (topic name and attributes)
+ Message metadata (subject, message ID, timestamp, and attributes)
+ Data protection policy 
+ Per-topic metrics

**Note**  
A message is encrypted only if it is sent after the encryption of a topic is enabled. Amazon SNS doesn't encrypt backlogged messages.
Any encrypted message remains encrypted even if the encryption of its topic is disabled.

## Key terms
<a name="sse-key-terms"></a>

The following key terms can help you better understand the functionality of SSE. For detailed descriptions, see the *[Amazon Simple Notification Service API Reference](https://docs.aws.amazon.com/sns/latest/api/)*.

**Data key**  
The data encryption key (DEK) responsible for encrypting the contents of Amazon SNS messages.  
For more information, see [Data Keys](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#data-keys) in the *AWS Key Management Service Developer Guide* and [Envelope Encryption](https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/how-it-works.html#envelope-encryption) in the *AWS Encryption SDK Developer Guide*.

**AWS KMS key ID**  
The alias, alias ARN, key ID, or key ARN of an AWS KMS key, or a custom AWS KMS—in your account or in another account. While the alias of the AWS managed AWS KMS for Amazon SNS is always `alias/aws/sns`, the alias of a custom AWS KMS can, for example, be `alias/MyAlias`. You can use these AWS KMS keys to protect the messages in Amazon SNS topics.   
Keep the following in mind:  
+ The first time you use the AWS Management Console to specify the AWS managed KMS for Amazon SNS for a topic, AWS KMS creates the AWS managed KMS for Amazon SNS.
+ Alternatively, the first time you use the `Publish` action on a topic with SSE enabled, AWS KMS creates the AWS managed KMS for Amazon SNS.
You can create AWS KMS keys, define the policies that control how AWS KMS keys can be used, and audit AWS KMS usage using the **AWS KMS keys** section of the AWS KMS console or the `[CreateKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html)` AWS KMS action. For more information, see [AWS KMS keys](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#master_keys) and [Creating Keys](https://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html) in the *AWS Key Management Service Developer Guide*. For more examples of AWS KMS identifiers, see [KeyId](https://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html#API_DescribeKey_RequestParameters) in the *AWS Key Management Service API Reference*. For information about finding AWS KMS identifiers, see [Find the Key ID and ARN](https://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html#find-cmk-id-arn) in the *AWS Key Management Service Developer Guide*.  
There are additional charges for using AWS KMS. For more information, see [Estimating AWS KMS costs](sns-key-management.md#sse-estimate-kms-usage-costs) and [AWS Key Management Service Pricing](https://aws.amazon.com/kms/pricing).

# Managing Amazon SNS encryption keys and costs
<a name="sns-key-management"></a>

The following sections provide information about working with keys managed in AWS Key Management Service (AWS KMS).

**Note**  
Amazon SNS only supports symmetric encryption KMS keys. You cannot use any other type of KMS key to encrypt your service resources. For help determining whether a KMS key is a symmetric encryption key, see [Identifying asymmetric KMS keys](https://docs.aws.amazon.com/kms/latest/developerguide/find-symm-asymm.html).

## Estimating AWS KMS costs
<a name="sse-estimate-kms-usage-costs"></a>

To predict costs and better understand your AWS bill, you might want to know how often Amazon SNS uses your AWS KMS key.

**Note**  
Although the following formula can give you a very good idea of expected costs, actual costs might be higher because of the distributed nature of Amazon SNS.

To calculate the number of API requests (`R`) *per topic*, use the following formula:

```
R = B / D * (2 * P)
```

`B` is the billing period (in seconds).

`D` is the data key reuse period (in seconds—Amazon SNS reuses a data key for up to 5 minutes).

`P` is the number of publishing [principals](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Principal) that send to the Amazon SNS topic.

The following are example calculations. For exact pricing information, see [AWS Key Management Service Pricing](https://aws.amazon.com/kms/pricing/).

### Example 1: Calculating the number of AWS KMS API calls for 1 publisher and 1 topic
<a name="example-1-topic-1-publisher"></a>

This example assumes the following:
+ The billing period is January 1-31 (2,678,400 seconds).
+ The data key reuse period is 5 minutes (300 seconds).
+ There is 1 topic.
+ There is 1 publishing principal.

```
2,678,400 / 300 * (2 * 1) = 17,856
```

### Example 2: Calculating the number of AWS KMS API calls for multiple publishers and 2 topics
<a name="example-2-topics-multiple-publishers"></a>

This example assumes the following:
+ The billing period is February 1-28 (2,419,200 seconds).
+ The data key reuse period is 5 minutes (300 seconds).
+ There are 2 topics.
+ The first topic has 3 publishing principals.
+ The second topic has 5 publishing principals.

```
(2,419,200 / 300 * (2 * 3)) + (2,419,200 / 300 * (2 * 5)) = 129,024
```

## Configuring AWS KMS permissions
<a name="sns-what-permissions-for-sse"></a>

Before you can use SSE, you must configure AWS KMS key policies to allow encryption of topics and encryption and decryption of messages. For examples and more information about AWS KMS permissions, see [AWS KMS API Permissions: Actions and Resources Reference](https://docs.aws.amazon.com/kms/latest/developerguide/kms-api-permissions-reference.html) in the *AWS Key Management Service Developer Guide*. For details on how to set up an Amazon SNS topic with server-side encryption, see [Additional information](sns-enable-encryption-for-topic.md#set-up-topic-with-sse).

**Note**  
You can also manage permissions for symmetric encryption KMS keys using IAM policies. For more information, see [Using IAM Policies with AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/iam-policies.html).  
While you can configure global permissions to send to and receive from Amazon SNS, AWS KMS requires explicitly naming the full ARN of KMSs in specific regions in the `Resource` section of an IAM policy.

You must also ensure that the key policies of the AWS KMS key allow the necessary permissions. To do this, name the principals that produce and consume encrypted messages in Amazon SNS as users in the KMS key policy. 

Alternatively, you can specify the required AWS KMS actions and KMS ARN in an IAM policy assigned to the principals that publish and subscribe to receive encrypted messages in Amazon SNS. For more information, see [Managing Access to AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/control-access-overview.html#managing-access) in the *AWS Key Management Service Developer Guide*.

If selecting a customer-managed key for your Amazon SNS topic and you are using aliases to control access to KMS keys using IAM policies or KMS key policies with the condition key `kms:ResourceAliases`, ensure that the customer-managed key that is selected also has an alias associated. For more information on using alias to control access to KMS keys, see [Using aliases to control access to KMS keys](https://docs.aws.amazon.com/kms/latest/developerguide/alias-authorization.html) in the *AWS Key Management Service Developer Guide*.

### Allow a user to send messages to a topic with SSE
<a name="send-to-encrypted-topic"></a>

The publisher must have the `kms:GenerateDataKey*` and `kms:Decrypt` permissions for the AWS KMS key.

```
{
  "Statement": [{
    "Effect": "Allow",
    "Action": [
      "kms:GenerateDataKey*",
      "kms:Decrypt"
    ],
    "Resource": "arn:aws:kms:us-east-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab"
  }, {
    "Effect": "Allow",
    "Action": [
      "sns:Publish"
    ],
    "Resource": "arn:aws:sns:*:123456789012:MyTopic"
  }]
}
```

### Enable compatibility between event sources from AWS services and encrypted topics
<a name="compatibility-with-aws-services"></a>

Several AWS services publish events to Amazon SNS topics. To allow these event sources to work with encrypted topics, you must perform the following steps.

1. Use a customer managed key. For more information, see [Creating Keys](https://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html) in the *AWS Key Management Service Developer Guide*.

1. To allow the AWS service to have the `kms:GenerateDataKey*` and `kms:Decrypt` permissions, add the following statement to the KMS policy.

   ```
   {
     "Statement": [{
       "Effect": "Allow",
       "Principal": {
         "Service": "service.amazonaws.com"
       },
       "Action": [
         "kms:GenerateDataKey*",
         "kms:Decrypt"
       ],
       "Resource": "*"
     }]
   }
   ```    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/sns/latest/dg/sns-key-management.html)
**Note**  
Some Amazon SNS event sources require you to provide an IAM role (rather than the service principal) in the AWS KMS key policy:  
[Amazon EC2 Auto Scaling](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ASGettingNotifications.html)
[Amazon Elastic Transcoder](https://docs.aws.amazon.com/elastictranscoder/latest/developerguide/notifications.html)
[AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/approvals.html#approvals-configuration-options)
[AWS Config](https://docs.aws.amazon.com/config/latest/developerguide/notifications-for-AWS-Config.html)
[AWS Elastic Beanstalk](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.managing.sns.html)
[AWS IoT](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sns-rule.html)
[EC2 Image Builder](https://docs.aws.amazon.com/imagebuilder/latest/userguide/ibhow-integrations.html#integ-sns-encrypted)

1. Add the `aws:SourceAccount` and `aws:SourceArn` condition keys to the KMS resource policy to further protect the KMS key from [confused deputy](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html) attacks. Refer to service specific documentation list (above) for exact details in each case.
**Important**  
Adding the `aws:SourceAccount`, `aws:SourceArn`, and `aws:SourceOrgID` to a AWS KMS policy is not supported for EventBridge-to-encrypted topics.

   ```
   {
     "Effect": "Allow",
     "Principal": {
       "Service": "service.amazonaws.com"
     },
     "Action": [
       "kms:GenerateDataKey*",
       "kms:Decrypt"
     ],
     "Resource": "*",
     "Condition": {
       "StringEquals": {
         "aws:SourceAccount": "customer-account-id"
       },
       "ArnLike": {
         "aws:SourceArn": "arn:aws:service:region:customer-account-id:resource-type:customer-resource-id"
       }
     }
   }
   ```

1. [Enable SSE for your topic](sns-enable-encryption-for-topic.md) using your KMS.

1. Provide the ARN of the encrypted topic to the event source.

## AWS KMS errors
<a name="sse-troubleshooting-errors"></a>

When you work with Amazon SNS and AWS KMS, you might encounter errors. The following list describes the errors and possible troubleshooting solutions.

**KMSAccessDeniedException**  
The ciphertext references a key that doesn't exist or that you don't have access to.  
HTTP Status Code: 400

**KMSDisabledException**  
The request was rejected because the specified KMS isn't enabled.  
HTTP Status Code: 400

**KMSInvalidStateException**  
The request was rejected because the state of the specified resource isn't valid for this request. For more information, see [Key states of AWS KMS keys](https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) in the *AWS Key Management Service Developer Guide*.  
HTTP Status Code: 400

**KMSNotFoundException**  
The request was rejected because the specified entity or resource can't be found.  
HTTP Status Code: 400

**KMSOptInRequired**  
The AWS access key ID needs a subscription for the service.  
HTTP Status Code: 403

**KMSThrottlingException**  
The request was denied due to request throttling. For more information about throttling, see [Quotas](https://docs.aws.amazon.com/kms/latest/developerguide/limits.html#requests-per-second) in the *AWS Key Management Service Developer Guide*.  
HTTP Status Code: 400

# Setting up Amazon SNS topic encryption with server-side encryption
<a name="sns-enable-encryption-for-topic"></a>

Amazon SNS supports server-side encryption (SSE) to protect the contents of messages using AWS Key Management Service (AWS KMS). Follow the instructions below to enable SSE using the Amazon SNS console or CDK.

## Option 1: Enable encryption using the AWS Management Console
<a name="enable-encryption-console"></a>

1. Sign in to the [Amazon SNS console](https://console.aws.amazon.com/sns/home).

1. Navigate to the **Topics** page, select your **topic**, and choose **Edit**.

1. Expand the **Encryption** section and do the following: 
   + Toggle encryption to **Enable**.
   + Select the **AWS managed SNS Key** (alias/aws/sns) as the encryption key. This is selected by default.

1. Choose **Save changes**.

**Note**  
The AWS managed key is automatically created if it doesn’t already exist.
If you don’t see the key or have insufficient permissions, ask your administrator for `kms:ListAliases` and `kms:DescribeKey`.

## Option 2: Enable encryption using AWS CDK
<a name="enable-encryption-cdk"></a>

To use the AWS managed SNS  key in your CDK application, add the following snippet:

```
import software.amazon.awscdk.services.sns.*;
import software.amazon.awscdk.services.kms.*;
import software.amazon.awscdk.core.*;

public class SnsEncryptionExample extends Stack {
    public SnsEncryptionExample(final Construct scope, final String id) {
        super(scope, id);

        // Define the managed SNS key
        IKey snsKey = Alias.fromAliasName(this, "helloKey", "alias/aws/sns");

        // Create the SNS Topic with encryption enabled
        Topic.Builder.create(this, "MyEncryptedTopic")
            .masterKey(snsKey)
            .build();
    }
}
```

## Additional information
<a name="set-up-topic-with-sse"></a>
+ **Custom KMS key** – You can specify a custom key if required. In the Amazon SNS console, select your custom KMS key from the list or enter the ARN.
+ **Permissions for custom KMS keys** – If using a custom KMS key, include the following in the key policy to allow Amazon SNS to encrypt and decrypt messages:

```
{ 
    "Effect": "Allow", 
    "Principal": { 
        "Service": "sns.amazonaws.com" 
     },
    "Action": [
        "kms:Decrypt",
        "kms:GenerateDataKey"
    ],
    "Resource": "*",
    "Condition": {
        "ArnLike": { 
            "aws:SourceArn": "arn:aws:service:region:customer-account-id:resource-type/customer-resource-id" 
        },
        "StringEquals": { 
            "kms:EncryptionContext:aws:sns:topicArn": "arn:aws:sns:your_region:customer-account-id:your_sns_topic_name" 
        }
    }
}
```

## Impact on consumers
<a name="enable-encryption-impact-on-consumers"></a>

Enabling SSE does not change how subscribers consume messages. AWS manages encryption and decryption transparently. Messages remain encrypted at rest and are automatically decrypted before delivery to subscribers. For optimal security, AWS recommends enabling HTTPS for all endpoints to ensure secure transmission of messages.

# Setting up Amazon SNS topic encryption with encrypted Amazon SQS queue subscription
<a name="sns-enable-encryption-for-topic-sqs-queue-subscriptions"></a>

You can enable server-side encryption (SSE) for a topic to protect its data. To allow Amazon SNS to send messages to encrypted Amazon SQS queues, the customer managed key associated with the Amazon SQS queue must have a policy statement that grants Amazon SNS service-principal access to the AWS KMS API actions `GenerateDataKey` and `Decrypt`. For more information about using SSE, see [Securing Amazon SNS data with server-side encryption](sns-server-side-encryption.md).

This topic explains how to enable SSE for an Amazon SNS topic with an encrypted Amazon SQS queue subscription using the AWS Management Console.

## Step 1: Create a custom KMS key
<a name="create-custom-cmk"></a>

1. Sign in to the [AWS KMS console](https://console.aws.amazon.com/kms/) with a user that has at least the `AWSKeyManagementServicePowerUser` policy.

1. Choose **Create a key**.

1. To create a symmetric encryption KMS key, for **Key type** choose **Symmetric**.

   For information about how to create an asymmetric KMS key in the AWS KMS console, see [Creating asymmetric KMS keys (console)](https://docs.aws.amazon.com/kms/latest/developerguide/asymm-create-key.html#create-asymmetric-keys-console).

1. In **Key usage**, the **Encrypt and decrypt** option is selected for you.

   For information about how to create KMS keys that generate and verify MAC codes, see [Creating HMAC KMS keys](https://docs.aws.amazon.com/kms/latest/developerguide/hmac-create-key.html).

   For information about the **Advanced options**, see [Special-purpose keys](https://docs.aws.amazon.com/kms/latest/developerguide/key-types.html).

1. Choose **Next**.

1. Type an alias for the KMS key. The alias name cannot begin with **aws/**. The **aws/** prefix is reserved by Amazon Web Services to represent AWS managed keys in your account.
**Note**  
Adding, deleting, or updating an alias can allow or deny permission to the KMS key. For details, see [ABAC for AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/abac.html) and [Using aliases to control access to KMS keys](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#hmac-key-concept).

   An alias is a display name that you can use to identify the KMS key. We recommend that you choose an alias that indicates the type of data you plan to protect or the application you plan to use with the KMS key.

   Aliases are required when you create a KMS key in the AWS Management Console. They are optional when you use the [CreateKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html) operation.

1. (Optional) Type a description for the KMS key.

   You can add a description now or update it any time unless the [key state](https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) is `Pending Deletion` or `Pending Replica Deletion`. To add, change, or delete the description of an existing customer managed key, [edit the description](https://docs.aws.amazon.com/kms/latest/developerguide/editing-keys.html) in the AWS Management Console or use the [UpdateKeyDescription](https://docs.aws.amazon.com/kms/latest/APIReference/API_UpdateKeyDescription.html) operation.

1. (Optional) Type a tag key and an optional tag value. To add more than one tag to the KMS key, choose **Add tag**.
**Note**  
Tagging or untagging a KMS key can allow or deny permission to the KMS key. For details, see [ABAC for AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/abac.html) and [Using tags to control access to KMS keys](https://docs.aws.amazon.com/kms/latest/developerguide/tag-authorization.html).

   When you add tags to your AWS resources, AWS generates a cost allocation report with usage and costs aggregated by tags. Tags can also be used to control access to a KMS key. For information about tagging KMS keys, see [Tagging keys](https://docs.aws.amazon.com/kms/latest/developerguide/tagging-keys.html) and [ABAC for AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/abac.html).

1. Choose **Next**.

1. Select the IAM users and roles that can administer the KMS key.
**Note**  
This key policy gives the AWS account full control of this KMS key. It allows account administrators to use IAM policies to give other principals permission to manage the KMS key. For details, see [Default key policy](https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-default.html).  
   
IAM best practices discourage the use of IAM users with long-term credentials. Whenever possible, use IAM roles, which provide temporary credentials. For details, see [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the IAM User Guide.

1. (Optional) To prevent the selected IAM users and roles from deleting this KMS key, in the **Key deletion** section at the bottom of the page, clear the **Allow key administrators to delete this key** check box.

1. Choose **Next**.

1. Select the IAM users and roles that can use the key in [cryptographic operations](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#cryptographic-operations). Choose **Next**.

1. On the **Review and edit key policy** page, add the following statement to the key policy, and then choose **Finish**.

   ```
   {
       "Sid": "Allow Amazon SNS to use this key",
       "Effect": "Allow",
       "Principal": {
           "Service": "sns.amazonaws.com"
       },
       "Action": [
           "kms:Decrypt",
           "kms:GenerateDataKey*"
       ],
       "Resource": "*"
   }
   ```

Your new customer managed key appears in the list of keys.

## Step 2: Create an encrypted Amazon SNS topic
<a name="create-encrypted-topic"></a>

1. Sign in to the [Amazon SNS console](https://console.aws.amazon.com/sns/home).

1. On the navigation panel, choose **Topics**.

1. Choose **Create topic**.

1. On the **Create new topic** page, for **Name**, enter a topic name (for example, `MyEncryptedTopic`) and then choose **Create topic**.

1. Expand the **Encryption** section and do the following: 

   1. Choose **Enable server-side encryption**.

   1. Specify the customer managed key. For more information, see [Key terms](sns-server-side-encryption.md#sse-key-terms).

      For each customer managed key type, the **Description**, **Account**, and customer managed key **ARN** are displayed.
**Important**  
If you aren't the owner of the customer managed key, or if you log in with an account that doesn't have the `kms:ListAliases` and `kms:DescribeKey` permissions, you won't be able to view information about the customer managed key on the Amazon SNS console.  
Ask the owner of the customer managed key to grant you these permissions. For more information, see the [AWS KMS API Permissions: Actions and Resources Reference](https://docs.aws.amazon.com/kms/latest/developerguide/kms-api-permissions-reference.html) in the *AWS Key Management Service Developer Guide*.

   1. For **customer managed key**, choose **MyCustomKey** [which you created earlier](#create-custom-cmk) and then choose **Enable server-side encryption**.

1. Choose **Save changes**.

   SSE is enabled for your topic and the **MyTopic** page is displayed.

   The topic's **Encryption** status, AWS **Account**, **customer managed key**, customer managed key **ARN**, and **Description** are displayed on the **Encryption** tab.

Your new encrypted topic appears in the list of topics.

## Step 3: Create and subscribe encrypted Amazon SQS queues
<a name="create-encrypted-queue"></a>

1. Sign in to the [Amazon SQS console](https://console.aws.amazon.com/sqs/).

1. Choose **Create New Queue**.

1. On the **Create New Queue** page, do the following:

   1. Enter a **Queue Name** (for example, `MyEncryptedQueue1`).

   1. Choose **Standard Queue**, and then choose **Configure Queue**.

   1. Choose **Use SSE**.

   1. For **AWS KMS key**, choose **MyCustomKey** [which you created earlier](#create-custom-cmk), and then choose **Create Queue**.

1. Repeat the process to create a second queue (for example, named `MyEncryptedQueue2`).

   Your new encrypted queues appear in the list of queues.

1. On the Amazon SQS console, choose `MyEncryptedQueue1` and `MyEncryptedQueue2` and then choose **Queue Actions**, **Subscribe Queues to SNS Topic**.

1. In the **Subscribe to a Topic** dialog box, for **Choose a Topic** select **MyEncryptedTopic**, and then choose **Subscribe**.

   Your encrypted queues' subscriptions to your encrypted topic are displayed in the **Topic Subscription Result** dialog box.

1. Choose **OK**.

## Step 4: Publish a message to your encrypted topic
<a name="publish-to-encrypted-topic"></a>

1. Sign in to the [Amazon SNS console](https://console.aws.amazon.com/sns/home).

1. On the navigation panel, choose **Topics**.

1. From the list of topics, choose **MyEncryptedTopic** and then choose **Publish message**.

1. On the **Publish a message** page, do the following:

   1. (Optional) In the **Message details** section, enter the **Subject** (for example, `Testing message publishing`).

   1. In the **Message body** section, enter the message body (for example, `My message body is encrypted at rest.`).

   1. Choose **Publish message**.

Your message is published to your subscribed encrypted queues.

## Step 5: Verify message delivery
<a name="verify-message-delivery"></a>

1. Sign in to the [Amazon SQS console](https://console.aws.amazon.com/sqs/).

1. From the list of queues, choose **MyEncryptedQueue1** and then choose **Send and receive messages**.

1. On the **Send and receive messages in MyEncryptedQueue1** page, choose **Poll for messages**.

   The message [that you sent earlier](#publish-to-encrypted-topic) is displayed.

1. Choose **More Details** to view your message.

1. When you're finished, choose **Close**.

1. Repeat the process for **MyEncryptedQueue2**.

# Securing Amazon SNS traffic with VPC endpoints
<a name="sns-internetwork-traffic-privacy"></a>

An Amazon Virtual Private Cloud (Amazon VPC) endpoint for Amazon SNS is a logical entity within a VPC that allows connectivity only to Amazon SNS. The VPC routes requests to Amazon SNS and routes responses back to the VPC. The following sections provide information about working with VPC endpoints and creating VPC endpoint policies.

If you use Amazon Virtual Private Cloud (Amazon VPC) to host your AWS resources, you can establish a private connection between your VPC and Amazon SNS. With this connection, you can publish messages to your Amazon SNS topics without sending them through the public internet.

Amazon VPC is an AWS service that you can use to launch AWS resources in a virtual network that you define. With a VPC, you have control over your network settings, such the IP address range, subnets, route tables, and network gateways. To connect your VPC to Amazon SNS, you define an *interface VPC endpoint*. This type of endpoint enables you to connect your VPC to AWS services. The endpoint provides reliable, scalable connectivity to Amazon SNS without requiring an internet gateway, network address translation (NAT) instance, or VPN connection. For more information, see [Access an AWS service using an interface VPC endpoint](https://docs.aws.amazon.com/vpc/latest/userguide/vpce-interface.html) in the *Amazon VPC User Guide*.

The information in this section is for users of Amazon VPC. For more information, and to get started with creating a VPC, see [Plan your VPC](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-getting-started.html) in the *Amazon VPC User Guide*.

**Note**  
VPC endpoints don't allow you to subscribe an Amazon SNS topic to a private IP address.

# Creating an Amazon VPC endpoint for Amazon SNS
<a name="sns-vpc-create-endpoint"></a>

To publish messages to your Amazon SNS topics from an Amazon VPC, create an interface VPC endpoint. Then, you can publish messages to your topics while keeping the traffic within the network that you manage with the VPC.

Use the following information to create the endpoint and test the connection between your VPC and Amazon SNS. Or, for a walkthrough that helps you start from scratch, see [Publishing an Amazon SNS message from Amazon VPC](sns-vpc-tutorial.md).

## Creating the endpoint
<a name="sns-vpc-endpoint-create"></a>

You can create an Amazon SNS endpoint in your VPC using the AWS Management Console, the AWS CLI, an AWS SDK, the Amazon SNS API, or AWS CloudFormation.

For information about creating and configuring an endpoint using the Amazon VPC console or the AWS CLI, see [Creating an Interface Endpoint](https://docs.aws.amazon.com/vpc/latest/userguide/vpce-interface.html#create-interface-endpoint) in the *Amazon VPC User Guide*.

**Important**  
You can use Amazon Virtual Private Cloud only with HTTPS Amazon SNS endpoints.  
When you create an endpoint, specify Amazon SNS as the service that you want your VPC to connect to. In the Amazon VPC console, service names vary based on the region. For example, if you choose US East (N. Virginia), the service name is **com.amazonaws.us-east-1.sns**.  
When you configure Amazon SNS to send messages from Amazon VPC, you must enable private DNS and specify endpoints in the format `sns.us-east-2.amazonaws.com`.  
Private DNS doesn't support legacy endpoints such as `queue.amazonaws.com` or `us-east-2.queue.amazonaws.com`.

For information about creating and configuring an endpoint using AWS CloudFormation, see the [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html) resource in the *AWS CloudFormation User Guide*.

## Testing the connection between your VPC and Amazon SNS
<a name="sns-vpc-publish"></a>

After you create an endpoint for Amazon SNS, you can publish messages from your VPC to your Amazon SNS topics. To test this connection, do the following:

1. Connect to an Amazon EC2 instance that resides in your VPC. For information about connecting, see [Connect to Your Linux Instance](https://docs.aws.amazon.com/AWSEC2/latest/DeveloperGuide/AccessingInstances.html) or [Connecting to Your Windows Instance](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/connecting_to_windows_instance.html) in the Amazon EC2 documentation.

   For example, to connect to a Linux instance using an SSH client, run the following command from a terminal:

   ```
   $ ssh -i ec2-key-pair.pem ec2-user@instance-hostname
   ```

   Where:
   + *ec2-key-pair.pem* is the file that contains the key pair that Amazon EC2 provided when you created the instance.
   + *instance-hostname* is the public hostname of the instance. To get the hostname in the [Amazon EC2 console](https://console.aws.amazon.com/ec2): Choose **Instances**, choose your instance, and find the value for **Public DNS**.

1. From your instance, use the Amazon SNS [https://docs.aws.amazon.com/cli/latest/reference/sns/publish.html](https://docs.aws.amazon.com/cli/latest/reference/sns/publish.html) command with the AWS CLI. You can send a simple message to a topic with the following command:

   ```
   $ aws sns publish --region aws-region --topic-arn sns-topic-arn --message "Hello"
   ```

   Where:
   + *aws-region* is the AWS Region that the topic is located in.
   + *sns-topic-arn* is the Amazon Resource Name (ARN) of the topic. To get the ARN from the [Amazon SNS console](https://console.aws.amazon.com/sns/home): Choose **Topics**, find your topic, and find the value in the **ARN** column.

   If the message is successfully received by Amazon SNS, the terminal prints a message ID, like the following:

   ```
   {
      "MessageId": "6c96dfff-0fdf-5b37-88d7-8cba910a8b64"
   }
   ```

# Creating an Amazon VPC endpoint policy for Amazon SNS
<a name="sns-vpc-endpoint-policy"></a>

You can create a policy for Amazon VPC endpoints for Amazon SNS in which you specify the following:
+ The principal that can perform actions.
+ The actions that can be performed.
+ The resources on which actions can be performed.

For more information, see [Controlling Access to Services with VPC Endpoints](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints-access.html) in the *Amazon VPC User Guide*.

The following example VPC endpoint policy specifies that the IAM user `MyUser` is allowed to publish to the Amazon SNS topic `MyTopic`.

```
{
  "Statement": [{
    "Action": ["sns:Publish"],
    "Effect": "Allow",
    "Resource": "arn:aws:sns:us-east-2:123456789012:MyTopic",
    "Principal": {
      "AWS": "arn:aws:iam:123456789012:user/MyUser"
    }
  }]
}
```

The following are denied:
+ Other Amazon SNS API actions, such as `sns:Subscribe` and `sns:Unsubscribe`.
+ Other IAM users and rules which attempt to use this VPC endpoint.
+ `MyUser` publishing to a different Amazon SNS topic.

**Note**  
The IAM user can still use other Amazon SNS API actions from *outside* the VPC.

# Publishing an Amazon SNS message from Amazon VPC
<a name="sns-vpc-tutorial"></a>

This section describes how to publish to an Amazon SNS topic while keeping the messages secure in a private network. You publish a message from an Amazon EC2 instance that's hosted in Amazon Virtual Private Cloud (Amazon VPC). The message stays within the AWS network without traveling the public internet. By publishing messages privately from a VPC, you can improve the security of the traffic between your applications and Amazon SNS. This security is important when you publish personally identifiable information (PII) about your customers, or when your application is subject to market regulations. For example, publishing privately is helpful if you have a healthcare system that must comply with the Health Insurance Portability and Accountability Act (HIPAA), or a financial system that must comply with the Payment Card Industry Data Security Standard (PCI DSS).

The general steps are as follows:
+ Use an AWS CloudFormation template to automatically create a temporary private network in your AWS account.
+ Create a VPC endpoint that connects the VPC with Amazon SNS.
+ Log in to an Amazon EC2 instance and publish a message privately to an Amazon SNS topic.
+ Verify that the message was delivered successfully.
+ Delete the resources that you created during this process so that they don't remain in your AWS account.

The following diagram depicts the private network that you create in your AWS account as you complete these steps:

![\[The architecture of the private network that you create with these steps.\]](http://docs.aws.amazon.com/sns/latest/dg/images/vpce-tutorial-architecture.png)


This network consists of a VPC that contains an Amazon EC2 instance. The instance connects to Amazon SNS through an *interface VPC endpoint*. This type of endpoint connects to services that are powered by AWS PrivateLink. With this connection established, you can log in to the Amazon EC2 instance and publish messages to the Amazon SNS topic, even though the network is disconnected from the public internet. The topic fans out the messages that it receives to two subscribing AWS Lambda functions. These functions log the messages that they receive in Amazon CloudWatch Logs.

It takes about 20 minutes to complete these steps.

**Topics**
+ [

## Before you begin
](#sns-vpc-prereqs)
+ [Step 1: Create a key pair](#sns-vpc-keypair)
+ [Step 2: Create resources](#sns-vpc-resources)
+ [Step 3: Check the internet connection for your instance](#sns-vpc-connection)
+ [Step 4: Create an endpoint](#sns-vpc-endpoint)
+ [Step 5: Publish a message](#sns-vpc-publish)
+ [Step 6: Verify](#sns-vpc-verify)
+ [Step 7: Clean up](#sns-vpc-delete)
+ [

## Related resources
](#sns-vpc-resources-related)

## Before you begin
<a name="sns-vpc-prereqs"></a>

Before you start, you need an Amazon Web Services (AWS) account. When you sign up, your account is automatically signed up for all services in AWS, including Amazon SNS and Amazon VPC. If you haven't created an account already, go to [https://aws.amazon.com/](https://aws.amazon.com/), and then choose **Create a Free Account**.

## Step 1: Create an Amazon EC2 key pair
<a name="sns-vpc-keypair"></a>

A *key pair* is used to log in to an Amazon EC2 instance. It consists of a public key that's used to encrypt your login information, and a private key that's used to decrypt it. When you create a key pair, you download a copy of the private key. Later, you use the key pair to log in to an Amazon EC2 instance. To log in, you specify the name of the key pair, and you provide the private key.

**To create the key pair**

1. Sign in to the AWS Management Console and open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation menu on the left, find the **Network & Security** section. Then, choose **Key Pairs**.

1. Choose **Create Key Pair**.

1. In the **Create Key Pair** window, for **Key pair name**, type **VPCE-Tutorial-KeyPair**. Then, choose **Create**.  
![\[The Create Key Pair window with the text "VPCE-Tutorial-KeyPair" in the Key pair name field.\]](http://docs.aws.amazon.com/sns/latest/dg/images/vpce-tutorial-key-pair.png)

1. The private key file is automatically downloaded by your browser. Save it in a safe place. Amazon EC2 gives the file an extension of `.pem`. 

1. (Optional) If you're using an SSH client on a Mac or Linux computer to connect to your instance, use the `chmod` command to set the permissions of your private key file so that only you can read it:

   1. Open a terminal and navigate to the directory that contains the private key: 

      ```
      $ cd /filepath_to_private_key/
      ```

   1. Set the permissions using the following command:

      ```
      $ chmod 400 VPCE-Tutorial-KeyPair.pem
      ```

## Step 2: Create the AWS resources
<a name="sns-vpc-resources"></a>

To set up the infrastructure, you use an CloudFormation *template*. A template is a file that acts as a blueprint for building AWS resources, such as Amazon EC2 instances and Amazon SNS topics. The template for this process is provided on GitHub for you to download. 

You provide the template to CloudFormation, and CloudFormation provisions the resources that you need as a *stack* in your AWS account. A stack is a collection of resources that you manage as a single unit. When you finish these steps, you can use CloudFormation to delete all of the resources in the stack at once. These resources don't remain in your AWS account, unless you want them to.

The stack for this process includes the following resources:
+ A VPC and the associated networking resources, including a subnet, a security group, an internet gateway, and a route table.
+ An Amazon EC2 instance that's launched into the subnet in the VPC.
+ An Amazon SNS topic.
+ Two AWS Lambda functions. These functions receive messages that are published to the Amazon SNS topic, and they log events in CloudWatch Logs.
+ Amazon CloudWatch metrics and logs.
+ An IAM role that allows the Amazon EC2 instance to use Amazon SNS, and an IAM role that allows the Lambda functions to write to CloudWatch logs.

**To create the AWS resources**

1. Download the [template file](https://github.com/aws-samples/aws-sns-samples/blob/master/templates/SNS-VPCE-Tutorial-CloudFormation.template) from the GitHub website.

1. Sign in to the [CloudFormation console](https://console.aws.amazon.com/cloudformation).

1. Choose **Create Stack**.

1. On the **Select Template** page, choose **Upload a template to Amazon S3**, choose the file, and choose **Next**.

1. On the **Specify Details** page, specify stack and key names:

   1. For **Stack name**, type **VPCE-Tutorial-Stack**.

   1. For **KeyName**, choose **VPCE-Tutorial-KeyPair**.

   1. For **SSHLocation**, keep the default value of **0.0.0.0/0**.  
![\[The Specify Details page displaying populated value fields for Stack name, KeyName, and SSHLocation.\]](http://docs.aws.amazon.com/sns/latest/dg/images/vpce-tutorial-stack-name.png)

   1. Choose **Next**.

1. On the **Options** page, keep all of the default values, and choose **Next**.

1. On the **Review** page, verify the stack details.

1. Under **Capabilities**, acknowledge that CloudFormation might create IAM resources with custom names.

1. Choose **Create**.

   The CloudFormation console opens the **Stacks** page. The VPCE-Tutorial-Stack has a status of **CREATE\$1IN\$1PROGRESS**. In a few minutes, after the creation process completes, the status changes to **CREATE\$1COMPLETE**.  
![\[The CloudFormation stack with a status of CREATE_COMPLETE.\]](http://docs.aws.amazon.com/sns/latest/dg/images/vpce-tutorial-stack-create-complete.png)
**Tip**  
Choose the **Refresh** button to see the latest stack status.

## Step 3: Confirm that your Amazon EC2 instance lacks internet access
<a name="sns-vpc-connection"></a>

The Amazon EC2 instance that was launched in your VPC in the previous step lacks internet access. It disallows outbound traffic, and it's unable to publish messages to Amazon SNS. Verify this by logging in to the instance. Then, attempt to connect to a public endpoint, and attempt to message Amazon SNS.

At this point, the publish attempt fails. In a later step, after you create a VPC endpoint for Amazon SNS, your publish attempt succeeds.

**To connect to your Amazon EC2 instance**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation menu on the left, find the **Instances** section. Then, choose **Instances**.

1. In the list of instances, select **VPCE-Tutorial-EC2Instance**.

1. Copy the hostname that's provided in the **Public DNS** column.  
![\[Details about the Amazon EC2 instance launched by CloudFormation.\]](http://docs.aws.amazon.com/sns/latest/dg/images/vpce-tutorial-instance-details.png)

1. Open a terminal. From the directory that contains the key pair, connect to the instance using the following command, where *instance-hostname* is the hostname that you copied from the Amazon EC2 console:

   ```
   $ ssh -i VPCE-Tutorial-KeyPair.pem ec2-user@instance-hostname
   ```

**To verify that the instance lacks internet connectivity**
+ In your terminal, attempt to connect to any public endpoint, such as amazon.com:

  ```
  $ ping amazon.com
  ```

  Because the connection attempt fails, you can cancel at any time (Ctrl \$1 C on Windows or Command \$1 C on macOS).

**To verify that the instance lacks connectivity to Amazon SNS**

1. Sign in to the [Amazon SNS console](https://console.aws.amazon.com/sns/home).

1. In the navigation menu on the left, choose **Topics**.

1. On the **Topics** page, copy the Amazon Resource Name (ARN) for the topic **VPCE-Tutorial-Topic**.

1. In your terminal, attempt to publish a message to the topic:

   ```
   $ aws sns publish --region aws-region --topic-arn sns-topic-arn --message "Hello"
   ```

   Because the publish attempt fails, you can cancel at any time.

## Step 4: Create an Amazon VPC endpoint for Amazon SNS
<a name="sns-vpc-endpoint"></a>

To connect the VPC to Amazon SNS, you define an interface VPC endpoint. After you add the endpoint, you can log in to the Amazon EC2 instance in your VPC, and from there you can use the Amazon SNS API. You can publish messages to the topic, and the messages are published privately. They stay within the AWS network, and they don't travel the public internet.

**Note**  
The instance still lacks access to other AWS services and endpoints on the internet.

**To create the endpoint**

1. Open the Amazon VPC console at [https://console.aws.amazon.com/vpc/](https://console.aws.amazon.com/vpc/).

1. In the navigation menu on the left, choose **Endpoints**.

1. Choose **Create Endpoint**.

1. On the **Create Endpoint** page, for **Service category**, keep the default choice of **AWS services**.

1. For **Service Name**, choose the service name for Amazon SNS.

   The service names vary based on the chosen region. For example, if you chose US East (N. Virginia), the service name is **com.amazonaws.*us-east-1*.sns**.

1. For **VPC**, choose the VPC that has the name **VPCE-Tutorial-VPC**.  
![\[The VPC menu on the Create Endpoint page.\]](http://docs.aws.amazon.com/sns/latest/dg/images/vpce-tutorial-create-endpoint-vpc.png)

1. For **Subnets**, choose the subnet that has *VPCE-Tutorial-Subnet* in the subnet ID.  
![\[The subnets on the Create Endpoints page.\]](http://docs.aws.amazon.com/sns/latest/dg/images/vpce-tutorial-create-endpoint-subnet.png)

1. For **Enable Private DNS Name**, select **Enable for this endpoint**.

1. For **Security group**, choose **Select security group**, and choose **VPCE-Tutorial-SecurityGroup**.  
![\[The security groups on the Create Endpoints page.\]](http://docs.aws.amazon.com/sns/latest/dg/images/vpce-tutorial-create-endpoint-security-group.png)

1. Choose **Create endpoint**. The Amazon VPC console confirms that a VPC endpoint was created.  
![\[The confirmation message displayed after you create an endpoint.\]](http://docs.aws.amazon.com/sns/latest/dg/images/vpce-tutorial-create-endpoint-confirmation.png)

1. Choose **Close**. 

   The Amazon VPC console opens the **Endpoints** page. The new endpoint has a status of **pending**. In a few minutes, after the creation process completes, the status changes to **available**.  
![\[The VPC endpoint with a status of available.\]](http://docs.aws.amazon.com/sns/latest/dg/images/vpce-tutorial-create-endpoint-status-available.png)

## Step 5: Publish a message to your Amazon SNS topic
<a name="sns-vpc-publish"></a>

Now that your VPC includes an endpoint for Amazon SNS, you can log in to the Amazon EC2 instance and publish messages to the topic.

**To publish a message**

1. If your terminal is no longer connected to your Amazon EC2 instance, connect again:

   ```
   $ ssh -i VPCE-Tutorial-KeyPair.pem ec2-user@instance-hostname
   ```

1. Run the same command that you did previously to publish a message to your Amazon SNS topic. This time, the publish attempt succeeds, and Amazon SNS returns a message ID:

   ```
   $ aws sns publish --region aws-region --topic-arn sns-topic-arn --message "Hello"
   
   
   {
       "MessageId": "5b111270-d169-5be6-9042-410dfc9e86de"
   }
   ```

## Step 6: Verify your message deliveries
<a name="sns-vpc-verify"></a>

When the Amazon SNS topic receives a message, it fans out the message by sending it to the two subscribing Lambda functions. When these functions receive the message, they log the event to CloudWatch logs. To verify that your message delivery succeeded, check that the functions were invoked, and check that the CloudWatch logs were updated.

**To verify that the Lambda functions were invoked**

1. Open the AWS Lambda console at [https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/).

1. On the **Functions** page, choose **VPCE-Tutorial-Lambda-1**.

1. Choose **Monitoring**.

1. Check the **Invocation count** graph. This graph shows the number of times that the Lambda function has been run.

   The invocation count matches the number of times you published a message to the topic.  
![\[The Invocation count graph in the Lambda console.\]](http://docs.aws.amazon.com/sns/latest/dg/images/vpce-tutorial-lambda-invocation-count.png)

**To verify that the CloudWatch logs were updated**

1. Open the CloudWatch console at [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/).

1. In the navigation menu on the left, choose **Logs**.

1. Check the logs that were written by the Lambda functions:

   1. Choose the **/aws/lambda/VPCE-Tutorial-Lambda-1/** log group.

   1. Choose the log stream.

   1. Check that the log includes the entry `From SNS: Hello`.  
![\[The CloudWatch log includes the entry "From SNS: Hello".\]](http://docs.aws.amazon.com/sns/latest/dg/images/vpce-tutorial-cloudwatch-log.png)

   1. Choose **Log Groups** at the top of the console to return the **Log Groups** page. Then, repeat the preceding steps for the /aws/lambda/VPCE-Tutorial-Lambda-2/ log group.

Congratulations\$1 By adding an endpoint for Amazon SNS to a VPC, you were able to publish a message to a topic from within the network that's managed by the VPC. The message was published privately without being exposed to the public internet.

## Step 7: Clean up
<a name="sns-vpc-delete"></a>

Unless you want to retain the resources that you created, you can delete them now. By deleting AWS resources that you're no longer using, you prevent unnecessary charges to your AWS account. 

First, delete your VPC endpoint using the Amazon VPC console. Then, delete the other resources that you created by deleting the stack in the CloudFormation console. When you delete a stack, CloudFormation removes the stack's resources from your AWS account.

**To delete your VPC endpoint**

1. Open the Amazon VPC console at [https://console.aws.amazon.com/vpc/](https://console.aws.amazon.com/vpc/).

1. In the navigation menu on the left, choose **Endpoints**.

1. Select the endpoint that you created.

1. Choose **Actions**, and then choose **Delete Endpoint**.

1. In the **Delete Endpoint** window, choose **Yes, Delete**.

   The endpoint status changes to **deleting**. When the deletion completes, the endpoint is removed from the page.

**To delete your CloudFormation stack**

1. Open the CloudFormation console at [https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/).

1. Select the stack **VPCE-Tutorial-Stack**.

1. Choose **Actions**, and then choose **Delete Stack**.

1. In the **Delete Stack** window, choose **Yes, Delete**.

   The stack status changes to **DELETE\$1IN\$1PROGRESS**. When the deletion completes, the stack is removed from the page.

## Related resources
<a name="sns-vpc-resources-related"></a>

For more information, see the following resources.
+ [AWS Security Blog: Securing messages published to Amazon SNS with AWS PrivateLink ](https://aws.amazon.com/blogs/security/securing-messages-published-to-amazon-sns-with-aws-privatelink/)
+ [What Is Amazon VPC?](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Introduction.html)
+ [VPC Endpoints](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints.html)
+ [What Is Amazon EC2?](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html)
+ [CloudFormation Concepts](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-concepts.html)

# Connect to Amazon SNS using Dual-stack (IPv4 and IPv6) endpoints
<a name="sns-dual-stack"></a>

 Dual-stack endpoints support both IPv4 and IPv6 traffic. When you make a request to a dual-stack endpoint, the endpoint URL resolves to an IPv4 or an IPv6 address. For more information on dual-stack and FIPS endpoints, see the [SDK Reference guide](https://docs.aws.amazon.com/sdkref/latest/guide/feature-endpoints.html). 

 Amazon SNS supports Regional dual-stack endpoints, which means that you must specify the AWS Region as part of the endpoint name. Dual-stack endpoint names use the following naming convention: `sns.Region.amazonaws.com`. For example, the dual-stack endpoint name for the `eu-west-1` Region is `sns.eu-west-1.amazonaws.com`. 

For the full list of Amazon SNS endpoints, see the [AWS General Reference](https://docs.aws.amazon.com/general/latest/gr/sns.html). 

# Enhancing Amazon SNS security with Message Data Protection
<a name="sns-message-data-protection"></a>

**Important**  
Amazon SNS message data protection will no longer be available to new customers starting April 30, 2026. For more information and guidance on alternatives, see [Amazon SNS message data protection availability change](https://docs.aws.amazon.com/sns/latest/dg/sns-message-data-protection-availability-change.html).
+ [Message Data Protection](message-data-protection.md) is a feature in Amazon SNS used to define your own rules and policies to audit and control the content for data in motion, as opposed to data at rest.
+ Message Data Protection provides governance, compliance, and auditing services for enterprise applications that are message-centric, so data ingress and egress can be controlled by the Amazon SNS topic owner, and content flows can be tracked and logged.
+ You can write payload-based governance rules to stop unauthorized payload content from entering your message streams.
+ You can grant different content-access permissions to individual subscribers, and audit the entire content-flow process.

# Identity and access management in Amazon SNS
<a name="security-iam"></a>

Access to Amazon SNS requires credentials that AWS can use to authenticate your requests. These credentials must have permissions to access AWS resources, such an Amazon SNS topics and messages. The following sections provide details on how you can use [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) and Amazon SNS to help secure your resources by controlling access to them. 

AWS Identity and Access Management (IAM) is an AWS service that helps an administrator securely control access to AWS resources. IAM administrators control who can be *authenticated* (signed in) and *authorized* (have permissions) to use Amazon SNS resources. IAM is an AWS service that you can use with no additional charge.

## Audience
<a name="security_iam_audience"></a>

How you use AWS Identity and Access Management (IAM) differs based on your role:
+ **Service user** - request permissions from your administrator if you cannot access features (see [Troubleshooting Amazon Simple Notification Service identity and access](security_iam_troubleshoot.md))
+ **Service administrator** - determine user access and submit permission requests (see [How Amazon SNS works with IAM](security_iam_service-with-iam.md))
+ **IAM administrator** - write policies to manage access (see [Identity-based policy examples for Amazon Simple Notification Service](security_iam_id-based-policy-examples.md))

## Authenticating with identities
<a name="security_iam_authentication"></a>

Authentication is how you sign in to AWS using your identity credentials. You must be authenticated as the AWS account root user, an IAM user, or by assuming an IAM role.

You can sign in as a federated identity using credentials from an identity source like AWS IAM Identity Center (IAM Identity Center), single sign-on authentication, or Google/Facebook credentials. For more information about signing in, see [How to sign in to your AWS account](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

For programmatic access, AWS provides an SDK and CLI to cryptographically sign requests. For more information, see [AWS Signature Version 4 for API requests](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html) in the *IAM User Guide*.

### AWS account root user
<a name="security_iam_authentication-rootuser"></a>

 When you create an AWS account, you begin with one sign-in identity called the AWS account *root user* that has complete access to all AWS services and resources. We strongly recommend that you don't use the root user for everyday tasks. For tasks that require root user credentials, see [Tasks that require root user credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks) in the *IAM User Guide*. 

### Federated identity
<a name="security_iam_authentication-federated"></a>

As a best practice, require human users to use federation with an identity provider to access AWS services using temporary credentials.

A *federated identity* is a user from your enterprise directory, web identity provider, or Directory Service that accesses AWS services using credentials from an identity source. Federated identities assume roles that provide temporary credentials.

For centralized access management, we recommend AWS IAM Identity Center. For more information, see [What is IAM Identity Center?](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) in the *AWS IAM Identity Center User Guide*.

### IAM users and groups
<a name="security_iam_authentication-iamuser"></a>

An *[IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html)* is an identity with specific permissions for a single person or application. We recommend using temporary credentials instead of IAM users with long-term credentials. For more information, see [Require human users to use federation with an identity provider to access AWS using temporary credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#bp-users-federation-idp) in the *IAM User Guide*.

An [https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) specifies a collection of IAM users and makes permissions easier to manage for large sets of users. For more information, see [Use cases for IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/gs-identities-iam-users.html) in the *IAM User Guide*.

### IAM roles
<a name="security_iam_authentication-iamrole"></a>

An *[IAM role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html)* is an identity with specific permissions that provides temporary credentials. You can assume a role by [switching from a user to an IAM role (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-console.html) or by calling an AWS CLI or AWS API operation. For more information, see [Methods to assume a role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage-assume.html) in the *IAM User Guide*.

IAM roles are useful for federated user access, temporary IAM user permissions, cross-account access, cross-service access, and applications running on Amazon EC2. For more information, see [Cross account resource access in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-cross-account-resource-access.html) in the *IAM User Guide*.

## Managing access using policies
<a name="security_iam_access-manage"></a>

You control access in AWS by creating policies and attaching them to AWS identities or resources. A policy defines permissions when associated with an identity or resource. AWS evaluates these policies when a principal makes a request. Most policies are stored in AWS as JSON documents. For more information about JSON policy documents, see [Overview of JSON policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json) in the *IAM User Guide*.

Using policies, administrators specify who has access to what by defining which **principal** can perform **actions** on what **resources**, and under what **conditions**.

By default, users and roles have no permissions. An IAM administrator creates IAM policies and adds them to roles, which users can then assume. IAM policies define permissions regardless of the method used to perform the operation.

### Identity-based policies
<a name="security_iam_access-manage-id-based-policies"></a>

Identity-based policies are JSON permissions policy documents that you attach to an identity (user, group, or role). These policies control what actions identities can perform, on which resources, and under what conditions. To learn how to create an identity-based policy, see [Define custom IAM permissions with customer managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html) in the *IAM User Guide*.

Identity-based policies can be *inline policies* (embedded directly into a single identity) or *managed policies* (standalone policies attached to multiple identities). To learn how to choose between managed and inline policies, see [Choose between managed policies and inline policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-choosing-managed-or-inline.html) in the *IAM User Guide*.

### Resource-based policies
<a name="security_iam_access-manage-resource-based-policies"></a>

Resource-based policies are JSON policy documents that you attach to a resource. Examples include IAM *role trust policies* and Amazon S3 *bucket policies*. In services that support resource-based policies, service administrators can use them to control access to a specific resource. You must [specify a principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html) in a resource-based policy.

Resource-based policies are inline policies that are located in that service. You can't use AWS managed policies from IAM in a resource-based policy.

### Other policy types
<a name="security_iam_access-manage-other-policies"></a>

AWS supports additional policy types that can set the maximum permissions granted by more common policy types:
+ **Permissions boundaries** – Set the maximum permissions that an identity-based policy can grant to an IAM entity. For more information, see [Permissions boundaries for IAM entities](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) in the *IAM User Guide*.
+ **Service control policies (SCPs)** – Specify the maximum permissions for an organization or organizational unit in AWS Organizations. For more information, see [Service control policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html) in the *AWS Organizations User Guide*.
+ **Resource control policies (RCPs)** – Set the maximum available permissions for resources in your accounts. For more information, see [Resource control policies (RCPs)](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_rcps.html) in the *AWS Organizations User Guide*.
+ **Session policies** – Advanced policies passed as a parameter when creating a temporary session for a role or federated user. For more information, see [Session policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) in the *IAM User Guide*.

### Multiple policy types
<a name="security_iam_access-manage-multiple-policies"></a>

When multiple types of policies apply to a request, the resulting permissions are more complicated to understand. To learn how AWS determines whether to allow a request when multiple policy types are involved, see [Policy evaluation logic](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html) in the *IAM User Guide*.

## Access control
<a name="access-control"></a>

Amazon SNS has its own resource-based permissions system that uses policies written in the same language used for AWS Identity and Access Management (IAM) policies. This means that you can achieve similar things with Amazon SNS policies and IAM policies.

**Note**  
It is important to understand that all AWS accounts can delegate their permissions to users under their accounts. Cross-account access allows you to share access to your AWS resources without having to manage additional users. For information about using cross-account access, see [Enabling Cross-Account Access](https://docs.aws.amazon.com/IAM/latest/UserGuide/Delegation.html) in the *IAM User Guide*.

# Amazon SNS access control use cases
<a name="sns-when-to-use-access-control"></a>

You have a great deal of flexibility in how you grant or deny access to a resource. However, the typical use cases are fairly simple: 
+ You want to grant another AWS account a particular type of topic action (for example, Publish). For more information, see [Grant AWS account access to a topic](sns-access-policy-use-cases.md#sns-grant-aws-account-access-to-topic).
+ You want to limit subscriptions to your topic to only the HTTPS protocol. For more information, see [Limit subscriptions to HTTPS](sns-access-policy-use-cases.md#sns-limit-subscriptions-to-https).
+ You want to allow Amazon SNS to publish messages to your Amazon SQS queue. For more information, see [Publish messages to an Amazon SQS queue](sns-access-policy-use-cases.md#sns-publish-messages-to-sqs-queue).

# Key Amazon SNS access policy concepts
<a name="sns-access-policy-language-key-concepts"></a>

The following sections describe the concepts you need to understand to use the access policy language. They're presented in a logical order, with the first terms you need to know at the top of the list.

## Permission
<a name="permissions"></a>

A *permission* is the concept of allowing or disallowing some kind of access to a particular resource. Permissions essentially follow this form: "A is/isn't allowed to do B to C where D applies." For example, *Jane* (A) has permission to *publish* (B) to *TopicA* (C) as long as *she uses the HTTP protocol* (D). Whenever Jane publishes to TopicA, the service checks to see if she has permission and if the request satisfies the conditions set forth in the permission.

## Statement
<a name="statement"></a>

A *statement* is the formal description of a single permission, written in the access policy language. You always write a statement as part of a broader container document known as a *policy* (see the next concept).

## Policy
<a name="policy"></a>

A *policy* is a document (written in the access policy language) that acts as a container for one or more statements. For example, a policy could have two statements in it: one that states that Jane can subscribe using the email protocol, and another that states that Bob cannot publish to Topic A. As shown in the following figure, an equivalent scenario would be to have two policies, one that states that Jane can subscribe using the email protocol, and another that states that Bob cannot publish to Topic A.

![\[Compares two ways of organizing policy statements in Amazon SNS. On the left, a single policy (Policy A) contains two statements. On the right, the same two statements are split between two policies, with each policy containing one statement. The diagram illustrates that these two approaches are equivalent in terms of how permissions are defined and enforced.\]](http://docs.aws.amazon.com/sns/latest/dg/images/AccessPolicyLanguage_Statement_and_Policy.gif)


Only ASCII characters are allowed in policy documents. You can utilize `aws:SourceAccount` and `aws:SourceOwner` to work around the scenario where you need to plug-in other AWS services' ARNs that contain non-ASCII characters. See the difference between [`aws:SourceAccount` versus `aws:SourceOwner`](sns-access-policy-use-cases.md#source-account-versus-source-owner).



## Issuer
<a name="issuer"></a>

The *issuer* is the person who writes a policy to grant permissions for a resource. The issuer (by definition) is always the resource owner. AWS does not permit AWS service users to create policies for resources they don't own. If John is the resource owner, AWS authenticates John's identity when he submits the policy he's written to grant permissions for that resource.

## Principal
<a name="principal"></a>

The *principal* is the person or persons who receive the permission in the policy. The principal is A in the statement "A has permission to do B to C where D applies." In a policy, you can set the principal to "anyone" (that is, you can specify a wildcard to represent all people). You might do this, for example, if you don't want to restrict access based on the actual identity of the requester, but instead on some other identifying characteristic such as the requester's IP address.

## Action
<a name="action"></a>

The *action* is the activity the principal has permission to perform. The action is B in the statement "A has permission to do B to C where D applies." Typically, the action is just the operation in the request to AWS. For example, Jane sends a request to Amazon SNS with `Action``=Subscribe`. You can specify one or multiple actions in a policy.

## Resource
<a name="resource"></a>

The *resource* is the object the principal is requesting access to. The resource is C in the statement "A has permission to do B to C where D applies."

## Conditions and keys
<a name="conditions"></a>

The *conditions* are any restrictions or details about the permission. The condition is D in the statement "A has permission to do B to C where D applies." The part of the policy that specifies the conditions can be the most detailed and complex of all the parts. Typical conditions are related to:
+ Date and time (for example, the request must arrive before a specific day)
+ IP address (for example, the requester's IP address must be part of a particular CIDR range)

A *key* is the specific characteristic that is the basis for access restriction. For example, the date and time of request.

You use both *conditions* and *keys* together to express the restriction. The easiest way to understand how you actually implement a restriction is with an example: If you want to restrict access to before May 30, 2010, you use the condition called `DateLessThan`. You use the key called `aws:CurrentTime` and set it to the value `2010-05-30T00:00:00Z`. AWS defines the conditions and keys you can use. The AWS service itself (for example, Amazon SQS or Amazon SNS) might also define service-specific keys. For more information, see [Amazon SNS API permissions: Actions and resources reference](sns-access-policy-language-api-permissions-reference.md).

## Requester
<a name="requester"></a>

The *requester* is the person who sends a request to an AWS service and asks for access to a particular resource. The requester sends a request to AWS that essentially says: "Will you allow me to do B to C where D applies?"

## Evaluation
<a name="evaluation"></a>

*Evaluation* is the process the AWS service uses to determine if an incoming request should be denied or allowed based on the applicable policies. For information about the evaluation logic, see [Evaluation logic](sns-access-policy-language-evaluation-logic.md).

## Effect
<a name="effect"></a>

The *effect* is the result that you want a policy statement to return at evaluation time. You specify this value when you write the statements in a policy, and the possible values are *deny* and *allow*.

For example, you could write a policy that has a statement that *denies* all requests that come from Antarctica (effect=deny given that the request uses an IP address allocated to Antarctica). Alternately, you could write a policy that has a statement that *allows* all requests that *don't* come from Antarctica (effect=allow given that the request doesn't come from Antarctica). Although the two statements sound like they do the same thing, in the access policy language logic, they are different. For more information, see [Evaluation logic](sns-access-policy-language-evaluation-logic.md).

Although there are only two possible values you can specify for the effect (allow or deny), there can be three different results at policy evaluation time: *default deny*, *allow*, or *explicit deny*. For more information, see the following concepts and [Evaluation logic](sns-access-policy-language-evaluation-logic.md).

## Default deny
<a name="Define_SoftDeny"></a>

A *default deny* is the default result from a policy in the absence of an allow or explicit deny. 

## Allow
<a name="allow"></a>

An *allow* results from a statement that has effect=allow, assuming any stated conditions are met. Example: Allow requests if they are received before 1:00 p.m. on April 30, 2010. An allow overrides all default denies, but never an explicit deny.

## Explicit deny
<a name="Define_HardDeny"></a>

An *explicit deny* results from a statement that has effect=deny, assuming any stated conditions are met. Example: Deny all requests if they are from Antarctica. Any request that comes from Antarctica will always be denied no matter what any other policies might allow.

# Amazon SNS access control architecture overview
<a name="sns-access-policy-language-architectural-overview"></a>

The following figure and table describe the main components that interact to provide access control for your resources.

![\[The flow of access control within an AWS service. It shows how you, as the resource owner, manage your resources (such as Amazon SQS queues) through policies. These policies are evaluated by the AWS service's access policy language evaluation code to determine whether incoming requests from requesters should be granted or denied access to the resources. The diagram includes numbered elements that correspond to the resource owner, resources, policies, incoming requests, and evaluation logic.\]](http://docs.aws.amazon.com/sns/latest/dg/images/AccessPolicyLanguage_Arch_Overview.gif)



|  |  | 
| --- |--- |
| 1 |  You, the resource owner.  | 
| 2 |  Your resources (contained within the AWS service; for example, Amazon SQS queues).  | 
| 3 |  Your policies. Typically you have one policy per resource, although you could have multiple. The AWS service itself provides an API you use to upload and manage your policies.  | 
| 4 |  Requesters and their incoming requests to the AWS service.  | 
| 5 |  The access policy language evaluation code. This is the set of code within the AWS service that evaluates incoming requests against the applicable policies and determines whether the requester is allowed access to the resource. For information about how the service makes the decision, see [Evaluation logic](sns-access-policy-language-evaluation-logic.md).  | 

# Using the Access Policy Language in Amazon SNS
<a name="sns-access-policy-language-using"></a>

The following figure and table describe the general process of how access control works with the access policy language. 

![\[The six-step process of how access control works with the access policy language in AWS. It starts with writing a policy for your resource, adding it to the system, and then proceeds through the stages of a requester making a request, the AWS service evaluating the applicable policies, and finally, the service either granting or denying the request based on the evaluation.\]](http://docs.aws.amazon.com/sns/latest/dg/images/AccessPolicyLanguage_Basic_Flow.gif)



**Process for using access control with the Access Policy Language**  

|  |  | 
| --- |--- |
|  1  |  You write a policy for your resource. For example, you write a policy to specify permissions for your Amazon SNS topics.  | 
|  2  |  You upload your policy to AWS. The AWS service itself provides an API you use to upload your policies. For example, you use the Amazon SNS `SetTopicAttributes` action to upload a policy for a particular Amazon SNS topic.  | 
|  3  |  Someone sends a request to use your resource. For example, a user sends a request to Amazon SNS to use one of your topics.   | 
|  4  |  The AWS service determines which policies are applicable to the request. For example, Amazon SNS looks at all the available Amazon SNS policies and determines which ones are applicable (based on what the resource is, who the requester is, etc.).  | 
|  5  |  The AWS service evaluates the policies. For example, Amazon SNS evaluates the policies and determines if the requester is allowed to use your topic or not. For information about the decision logic, see [Evaluation logic](sns-access-policy-language-evaluation-logic.md).  | 
|  6  |  The AWS service either denies the request or continues to process it.  For example, based on the policy evaluation result, the service either returns an "Access denied" error to the requester or continues to process the request.  | 

# Evaluation logic
<a name="sns-access-policy-language-evaluation-logic"></a>

The goal at evaluation time is to decide whether a grant request should be allowed or denied. The evaluation logic follows several basic rules:
+ By default, all requests to use your resource coming from anyone but you are denied
+ An allow overrides any default denies
+ An explicit deny overrides any allows
+ The order in which the policies are evaluated is not important

The following flow chart and discussion describe in more detail how the decision is made.

![\[Illustrates the decision-making process used by AWS to determine whether a request to access a resource should be allowed or denied. It begins with a default deny, checks for any explicit deny in the applicable policies, then looks for any allow instructions, and finally, if no allow is found, the request is denied by default.\]](http://docs.aws.amazon.com/sns/latest/dg/images/AccessPolicyLanguage_Evaluation_Flow.gif)



|  |  | 
| --- |--- |
| 1 |  The decision starts with a default deny.  | 
| 2 |   The enforcement code then evaluates all the policies that are applicable to the request (based on the resource, principal, action, and conditions).  The order in which the enforcement code evaluates the policies is not important.  | 
| 3 |   In all those policies, the enforcement code looks for an explicit deny instruction that would apply to the request. If it finds even one, the enforcement code returns a decision of "deny" and the process is finished (this is an explicit deny; for more information, see [Explicit deny](sns-access-policy-language-key-concepts.md#Define_HardDeny)).  | 
| 4 |  If no explicit deny is found, the enforcement code looks for any "allow" instructions that would apply to the request. If it finds even one, the enforcement code returns a decision of "allow" and the process is done (the service continues to process the request).   | 
| 5 |  If no allow is found, then the final decision is "deny" (because there was no explicit deny or allow, this is considered a *default deny* (for more information, see [Default deny](sns-access-policy-language-key-concepts.md#Define_SoftDeny)).  | 

## The interplay of explicit and default denials
<a name="denials"></a>

A policy results in a default deny if it doesn't directly apply to the request. For example, if a user requests to use Amazon SNS, but the policy on the topic doesn't refer to the user's AWS account at all, then that policy results in a default deny.

A policy also results in a default deny if a condition in a statement isn't met. If all conditions in the statement are met, then the policy results in either an allow or an explicit deny, based on the value of the Effect element in the policy. Policies don't specify what to do if a condition isn't met, and so the default result in that case is a default deny.

For example, let's say you want to prevent requests coming in from Antarctica. You write a policy (called Policy A1) that allows a request only if it doesn't come from Antarctica. The following diagram illustrates the policy.

![\[Illustrates a policy (Policy A1) that allows a request if it does not come from Antarctica. It shows the condition that the request must not originate from Antarctica for the "Allow" effect to apply; otherwise, the default action is to deny the request.\]](http://docs.aws.amazon.com/sns/latest/dg/images/AccessPolicyLanguage_Allow_Override_1.gif)


If someone sends a request from the U.S., the condition is met (the request is not from Antarctica). Therefore, the request is allowed. But, if someone sends a request from Antarctica, the condition isn't met, and the policy's result is therefore a default deny. 

You could turn the result into an explicit deny by rewriting the policy (named Policy A2) as in the following diagram. Here, the policy explicitly denies a request if it comes from Antarctica.

![\[Illustrates a policy (Policy A2) that explicitly denies a request if it comes from Antarctica. It shows that when the condition is met (the request originates from Antarctica), the policy results in an explicit denial, meaning the request is always denied under these circumstances.\]](http://docs.aws.amazon.com/sns/latest/dg/images/AccessPolicyLanguage_Allow_Override_2.gif)


If someone sends a request from Antarctica, the condition is met, and the policy's result is therefore an explicit deny.

The distinction between a default deny and an explicit deny is important because a default deny can be overridden by an allow, but an explicit deny can't. For example, let's say there's another policy that allows requests if they arrive on June 1, 2010. How does this policy affect the overall outcome when coupled with the policy restricting access from Antarctica? We'll compare the overall outcome when coupling the date-based policy (we'll call Policy B) with the preceding policies A1 and A2. Scenario 1 couples Policy A1 with Policy B, and Scenario 2 couples Policy A2 with Policy B. The following figure and discussion show the results when a request comes in from Antarctica on June 1, 2010.

![\[Compares two scenarios where a policy restricts access based on the request's origin (Antarctica) and the request date (June 1, 2010). In Scenario 1, the combination of policies results in a default deny being overridden by an allow, permitting the request. In Scenario 2, an explicit deny from one policy overrides an allow from another, resulting in the request being denied.\]](http://docs.aws.amazon.com/sns/latest/dg/images/AccessPolicyLanguage_Allow_Override.gif)


In Scenario 1, Policy A1 returns a default deny, as described earlier in this section. Policy B returns an allow because the policy (by definition) allows requests that come in on June 1, 2010. The allow from Policy B overrides the default deny from Policy A1, and the request is therefore allowed.

In Scenario 2, Policy A2 returns an explicit deny, as described earlier in this section. Again, Policy B returns an allow. The explicit deny from Policy A2 overrides the allow from Policy B, and the request is therefore denied.

# Example cases for Amazon SNS access control
<a name="sns-access-policy-use-cases"></a>

This section describes a few examples of typical use cases for access control.

## Grant AWS account access to a topic
<a name="sns-grant-aws-account-access-to-topic"></a>

Let's say you have a topic in Amazon SNS, and you want to allow one or more AWS accounts to perform a specific action on that topic, such as publishing messages. You can accomplish this by using the Amazon SNS API action `AddPermission`.

The `AddPermission` action allows you to specify a topic, a list of AWS account IDs, a list of actions, and a label. Amazon SNS then automatically generates and adds a new policy statement to the topic's access control policy. You don’t need to write the policy statement yourself—Amazon SNS handles this for you. If you need to remove the policy later, you can do so by calling `RemovePermission` and providing the label you used when adding the permission.

For example, if you call `AddPermission` on the topic arn:aws:sns:us-east-2:444455556666:MyTopic, specify AWS account ID 1111-2222-3333, the `Publish` action, and the label `grant-1234-publish`, Amazon SNS will generate and insert the following policy statement into the topic’s access control policy:

```
{
  "Statement": [{
    "Sid": "grant-1234-publish",
    "Effect": "Allow",
    "Principal": {
      "AWS": "111122223333"
    },
    "Action": ["sns:Publish"],
    "Resource": "arn:aws:sns:us-east-2:444455556666:MyTopic"
  }]
}
```

After this statement is added, the AWS account 1111-2222-3333 will have permission to publish messages to the topic.

**Additional information:**
+ **Custom policy management:** While `AddPermission` is convenient for granting permissions, it's often useful to manually manage the topic's access control policy for more complex scenarios, such as adding conditions or granting permissions to specific IAM roles or services. You can do this by using the `SetTopicAttributes` API to update the policy attribute directly.
+ **Security best practices:** Be cautious when granting permissions to ensure that only trusted AWS accounts or entities have access to your Amazon SNS topics. Regularly review and audit the policies attached to your topics to maintain security.
+ **Policy limits:** Keep in mind that there are limits to the size and complexity of Amazon SNS policies. If you need to add many permissions or complex conditions, ensure that your policy stays within these limits.

## Limit subscriptions to HTTPS
<a name="sns-limit-subscriptions-to-https"></a>

To restrict the notification delivery protocol for your Amazon SNS topic to HTTPS, you must create a custom policy. The `AddPermission` action in Amazon SNS does not allow you to specify protocol restrictions when granting access to your topic. Therefore, you need to manually write a policy that enforces this restriction and then use the `SetTopicAttributes` action to apply the policy to your topic.

Here’s how you can create a policy that limits subscriptions to HTTPS:

1. **Write the Policy.** The policy must specify the AWS account ID that you want to grant access to and enforce the condition that only HTTPS subscriptions are allowed. Below is an example policy that grants the AWS account ID 1111-2222-3333 permission to subscribe to the topic, but only if the protocol used is HTTPS.

   ```
   {
     "Statement": [{
       "Sid": "Statement1",
       "Effect": "Allow",
       "Principal": {
         "AWS": "111122223333"
       },
       "Action": ["sns:Subscribe"],
       "Resource": "arn:aws:sns:us-east-2:444455556666:MyTopic",
       "Condition": {
         "StringEquals": {
           "sns:Protocol": "https"
         }
       }
     }]
   }
   ```

1. **Apply the Policy.** Use the `SetTopicAttributes` action in the Amazon SNS API to apply this policy to your topic. Set the `Policy` attribute of the topic to the JSON policy you created.

   ```
   snsClient.setTopicAttributes(SetTopicAttributesRequest.builder()
           .topicArn("arn:aws:sns:us-east-2:444455556666:MyTopic")
           .attributeName("Policy")
           .attributeValue(jsonPolicyString)  // The JSON policy as a string
           .build());
   ```

**Additional information:**
+ **Customizing access control.** This approach allows you to enforce more granular access controls, such as restricting subscription protocols, which is not possible through the `AddPermission` action alone. Custom policies provide flexibility for scenarios requiring specific conditions, such as protocol enforcement or IP address restrictions.
+ **Security best practices.** Limiting subscriptions to HTTPS enhances the security of your notifications by ensuring that data in transit is encrypted. Regularly review your topic policies to ensure they meet your security and compliance requirements.
+ **Policy testing.** Before applying the policy in a production environment, test it in a development environment to ensure it behaves as expected. This helps prevent accidental access issues or unintended restrictions.

## Publish messages to an Amazon SQS queue
<a name="sns-publish-messages-to-sqs-queue"></a>

To publish messages from your Amazon SNS topic to an Amazon SQS queue, you need to configure the correct permissions on the Amazon SQS queue. While both Amazon SNS and Amazon SQS use AWS’s access control policy language, you must explicitly set a policy on the Amazon SQS queue to allow messages to be sent from the Amazon SNS topic.

You can achieve this by using the `SetQueueAttributes` action to apply a custom policy to the Amazon SQS queue. Unlike Amazon SNS, Amazon SQS does not support the `AddPermission` action for creating policy statements with conditions. Therefore, you must write the policy manually.

The following is an example of an Amazon SQS policy that grants Amazon SNS permission to send messages to your queue. Note that this policy is associated with the Amazon SQS queue, not the Amazon SNS topic. The actions specified are Amazon SQS actions, and the resource is the Amazon Resource Name (ARN) of the queue. You can retrieve the queue's ARN by using the `GetQueueAttributes` action.

```
{
  "Statement": [{
    "Sid": "Allow-SNS-SendMessage",
    "Effect": "Allow",
    "Principal": {
      "Service": "sns.amazonaws.com"
    },
    "Action": ["sqs:SendMessage"],
    "Resource": "arn:aws:sqs:us-east-2:444455556666:MyQueue",
    "Condition": {
      "ArnEquals": {
        "aws:SourceArn": "arn:aws:sns:us-east-2:444455556666:MyTopic"
      }
    }
  }]
}
```

This policy uses the `aws:SourceArn` condition to restrict access to the SQS queue based on the source of the messages being sent. This ensures that only messages originating from the specified SNS topic (in this case, arn:aws:sns:us-east-2:444455556666:MyTopic) are allowed to be delivered to the queue.

**Additional information:**
+ **Queue ARN.** Ensure you retrieve the correct ARN of your Amazon SQS queue using the `GetQueueAttributes` action. This ARN is essential for setting the correct permissions.
+ **Security best practices.** When setting up policies, always follow the principle of least privilege. Grant only the necessary permissions to the Amazon SNS topic to interact with the Amazon SQS queue, and regularly review your policies to ensure they are up-to-date and secure
+ **Default policies in Amazon SNS.** Amazon SNS doesn't automatically grant a default policy that allows other AWS services or accounts to access newly created topics. By default, Amazon SNS topics are created with no permissions, meaning they are private and only accessible to the account that created them. To enable access for other AWS services, accounts, or principals, you must explicitly define and attach an access policy to the topic. This aligns with the principle of least privilege, ensuring that no unintended access is granted by default.
+ **Testing and validation.** After setting the policy, test the integration by publishing messages to the Amazon SNS topic and verifying that they are successfully delivered to the Amazon SQS queue. This helps confirm that the policy is correctly configured.

## Allow Amazon S3 event notifications to publish to a topic
<a name="sns-allow-s3-bucket-to-publish-to-topic"></a>

To allow an Amazon S3 bucket from another AWS account to publish event notifications to your Amazon SNS topic, you need to configure the topic's access policy accordingly. This involves writing a custom policy that grants permission to the Amazon S3 service from the specific AWS account and then applying this policy to your Amazon SNS topic.

Here’s how you can set it up:

1. **Write the policy.** The policy should grant the Amazon S3 service (s3.amazonaws.com) the necessary permissions to publish to your Amazon SNS topic. You will use the `SourceAccount` condition to ensure that only the specified AWS account, which owns the Amazon S3 bucket, can publish notifications to your topic.

   The following is an example policy:

   ```
   {
     "Statement": [{
       "Effect": "Allow",
        "Principal": { 
         "Service": "s3.amazonaws.com" 
       },
       "Action": "sns:Publish",
       "Resource": "arn:aws:sns:us-east-2:111122223333:MyTopic",
       "Condition": {
         "StringEquals": {
           "AWS:SourceAccount": "444455556666"
         }       
       }
     }]
   }
   ```
   + **Topic owner** – 111122223333 is the AWS account ID that owns the Amazon SNS topic.
   + **Amazon S3 bucket owner **– 444455556666 is the AWS account ID that owns the Amazon S3 bucket sending notifications.

1. **Apply the Policy.** Use the `SetTopicAttributes` action to set this policy on your Amazon SNS topic. This will update the topic’s access control to include the permissions specified in your custom policy.

   ```
   snsClient.setTopicAttributes(SetTopicAttributesRequest.builder()
           .topicArn("arn:aws:sns:us-east-2:111122223333:MyTopic")
           .attributeName("Policy")
           .attributeValue(jsonPolicyString)  // The JSON policy as a string
           .build());
   ```

**Additional information:**
+ **Using `SourceAccount` condition.** The `SourceAccount` condition ensures that only events originating from the specified AWS account (444455556666 in this case) can trigger the Amazon SNS topic. This is a security measure to prevent unauthorized accounts from sending notifications to your topic.
+ **Other services supporting `SourceAccount`.** The `SourceAccount` condition is supported by the following services. It’s crucial to use this condition when you want to restrict access to your Amazon SNS topic based on the originating account.
  + Amazon API Gateway
  + Amazon CloudWatch
  + Amazon DevOps Guru
  + Amazon EventBridge
  + Amazon GameLift Servers
  + Amazon Pinpoint SMS and Voice API
  + Amazon RDS
  + Amazon Redshift
  + Amazon Glacier
  + Amazon SES
  + Amazon Simple Storage Service
  + AWS CodeCommit
  + Directory Service
  + AWS Lambda
  + AWS Systems Manager Incident Manager
+ **Testing and validation.** After applying the policy, test the setup by triggering an event in the Amazon S3 bucket and confirming that it successfully publishes to your Amazon SNS topic. This will help ensure that your policy is correctly configured.
+ **Security best practices.** Regularly review and audit your Amazon SNS topic policies to ensure they comply with your security requirements. Limiting access to only trusted accounts and services is essential for maintaining secure operations.

## Allow Amazon SES to publish to a topic that is owned by another account
<a name="sns-allow-specified-service-to-publish-to-topic"></a>

You can allow another AWS service to publish to a topic that is owned by another AWS account. Suppose that you signed into the 111122223333 account, opened Amazon SES, and created an email. To publish notifications about this email to a Amazon SNS topic that the 444455556666 account owns, you'd create a policy like the following. To do so, you need to provide information about the principal (the other service) and each resource's ownership. The `Resource` statement provides the topic ARN, which includes the account ID of the topic owner, 444455556666. The `"aws:SourceOwner": "111122223333"` statement specifies that your account owns the email. 

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Id": "__default_policy_ID",
  "Statement": [
    {
      "Sid": "__default_statement_ID",
      "Effect": "Allow",
      "Principal": {
        "Service": "ses.amazonaws.com"
      },
      "Action": "sns:Publish",
      "Resource": "arn:aws:sns:us-east-2:444455556666:MyTopic",
      "Condition": {
        "StringEquals": {
          "aws:SourceOwner": "111122223333"
        }
      }
    }
  ]
}
```

------

When publishing events to Amazon SNS, the following services support `aws:SourceOwner`:
+ Amazon API Gateway
+ Amazon CloudWatch
+ Amazon DevOps Guru
+ Amazon GameLift Servers
+ Amazon Pinpoint SMS and Voice API
+ Amazon RDS
+ Amazon Redshift
+ Amazon SES
+ AWS CodeCommit
+ Directory Service
+ AWS Lambda
+ AWS Systems Manager Incident Manager

## `aws:SourceAccount` versus `aws:SourceOwner`
<a name="source-account-versus-source-owner"></a>

**Important**  
`aws:SourceOwner` is deprecated and new services can integrate with Amazon SNS only through `aws:SourceArn` and `aws:SourceAccount`. Amazon SNS still maintains backward compatibility for existing services that are currently supporting `aws:SourceOwner`.

The `aws:SourceAccount` and `aws:SourceOwner` condition keys are each set by some AWS services when they publish to an Amazon SNS topic. When supported, the value will be the 12-digit AWS account ID on whose behalf the service is publishing data. Some services support one, and some support the other.
+ See [Allow Amazon S3 event notifications to publish to a topic](#sns-allow-s3-bucket-to-publish-to-topic) for how Amazon S3 notifications use `aws:SourceAccount` and a list of AWS services that support that condition.
+ See [Allow Amazon SES to publish to a topic that is owned by another account](#sns-allow-specified-service-to-publish-to-topic) for how Amazon SES uses `aws:SourceOwner` and a list of AWS services that support that condition.

## Allow accounts in an organization in AWS Organizations to publish to a topic in a different account
<a name="sns-allow-organization-to-publish-to-topic-in-another-account"></a>

The AWS Organizations service helps you to centrally manage billing, control access and security, and share resources across your AWS accounts. 

You can find your organization ID in the [ Organizations console](https://console.aws.amazon.com/organizations/). For more information, see [ Viewing details of an organization from the management account](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_details.html#orgs_view_org). 

In this example, any AWS account in organization `myOrgId` can publish to Amazon SNS topic `MyTopic` in account `444455556666`. The policy checks the organization ID value using the `aws:PrincipalOrgID` global condition key.

```
{
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "sns:Publish",
            "Resource": "arn:aws:sns:us-east-2:444455556666:MyTopic",
            "Condition": {
                "StringEquals": {
                    "aws:PrincipalOrgID": "myOrgId"
                }
            }
        }
    ]
}
```

## Allow any CloudWatch alarm to publish to a topic in a different account
<a name="sns-allow-cloudwatch-alarm-to-publish-to-topic-in-another-account"></a>

Use the following steps to invoke an Amazon SNS topic with a CloudWatch alarm across different AWS accounts. This example uses two accounts:
+ **Account A** is used to create the CloudWatch alarm.
+ **Account B** is used to create an SNS topic.

**Create an SNS topic in account B**

1. Sign in to the [Amazon SNS console](https://console.aws.amazon.com/sns/home).

1. In the navigation pane, choose **Topics**, and then choose **Create topic**.

1. Choose **Standard** for the topic type, and then create a name for the topic.

1. Choose **Create topic**, and then copy the **ARN** of the topic.

1. In the navigation pane, choose **Subscriptions**, and then choose **Create subscription**.

1. Add the topic's ARN in the **Topic ARN** section, choose **Email** as the protocol, and then **enter an email address**.

1. Choose **Create subscription**, and then check your email to **confirm the subscription**.

**Create a CloudWatch alarm in account A**

1. Open the CloudWatch console at [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/).

1. In the navigation pane, choose **Alarms**, and then choose **Create alarms**.

1. If you haven't already created an alarm, create one now. Otherwise, select your **metric**, and then provide details for the threshold and comparison parameters.

1. From **Configure Actions**, under **Notifications**, choose **Use topic ARN to notify other accounts**, and then enter the **topic ARN** from Account B.

1. Create a name for the alarm, and then choose **Create alarm**.

**Update the access policy of the SNS topic in account B**

1. Sign in to the [Amazon SNS console](https://console.aws.amazon.com/sns/home).

1. In the navigation pane, choose **Topics**, and then select the topic.

1. Choose **Edit**, and then add the following to the policy:

**Note**  
Replace the example values in the policy below with your own. 

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Id": "__default_policy_ID",
    "Statement": [
        {
            "Sid": "__default_statement_ID",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": [
                "SNS:GetTopicAttributes",
                "SNS:SetTopicAttributes",
                "SNS:AddPermission",
                "SNS:RemovePermission",
                "SNS:DeleteTopic",
                "SNS:Subscribe",
                "SNS:ListSubscriptionsByTopic",
                "SNS:Publish"
            ],
            "Resource": "arn:aws:cloudwatch:us-west-1:111122223333:alarm:",
            "Condition": {
                "ArnLike": {
                    "aws:SourceArn": "arn:aws:cloudwatch:us-west-1:111122223333:alarm:"
                }
            }
        }
    ]
}
```

------

**Test the alarm**

To test the alarm, either change the alarm threshold based on the metric data points, or manually change the alarm state. When you change the alarm threshold or alarm state, you receive an email notification.

**Workaround for using a local Amazon SNS topic and forwarding messages**

Use the following steps to enable cross-account Amazon SNS notifications for CloudWatch Alarms:

1. Create an [**Amazon SNS topic**](sns-create-topic.md) in the same account as the **CloudWatch alarm** (111122223333).

1. Subscribe a [**Lambda function**](lambda-console.md) or an [Amazon EventBridge rule](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-s3-object-created-tutorial.html) to that Amazon SNS topic.

1. The Lambda function or EventBridge rule can then publish the message to the Amazon SNS topic in the target account (444455556666).

## Restrict publication to an Amazon SNS topic only from a specific VPC endpoint
<a name="sns-restrict-publication-only-from-specified-vpc-endpoint"></a>

In this case, the topic in account 444455556666 is allowed to publish only from the VPC endpoint with the ID `vpce-1ab2c34d`.

```
{
  "Statement": [{
    "Effect": "Deny",
    "Principal": "*",
    "Action": "sns:Publish",
    "Resource": "arn:aws:sns:us-east-2:444455556666:MyTopic",
    "Condition": {
      "StringNotEquals": {
        "aws:sourceVpce": "vpce-1ab2c34d"
      }
    }
  }]
}
```

# How Amazon SNS works with IAM
<a name="security_iam_service-with-iam"></a>

Before you use IAM to manage access to Amazon SNS, learn what IAM features are available to use with Amazon SNS.






**IAM features you can use with Amazon Simple Notification Service**  

| IAM feature | Amazon SNS support | 
| --- | --- | 
|  [Identity-based policies](security-iam.md#security_iam_service-with-iam-id-based-policies)  |   Yes  | 
|  [Resource-based policies](security-iam.md#security_iam_service-with-iam-resource-based-policies)  |  Yes  | 
|  [Policy actions](security-iam.md#security_iam_service-with-iam-id-based-policies-actions)  |   Yes  | 
|  [Policy resources](security-iam.md#security_iam_service-with-iam-id-based-policies-resources)  |   Yes  | 
|  [Policy condition keys (service-specific)](security-iam.md#security_iam_service-with-iam-id-based-policies-conditionkeys)  |   Yes  | 
|  [ACLs](security-iam.md#security_iam_service-with-iam-acls)  |   No   | 
|  [ABAC (tags in policies)](security-iam.md#security_iam_service-with-iam-tags)  |   Partial  | 
|  [Temporary credentials](security-iam.md#security_iam_service-with-iam-roles-tempcreds)  |   Yes  | 
|  [Principal permissions](security-iam.md#security_iam_service-with-iam-principal-permissions)  |   Yes  | 
|  [Service roles](security-iam.md#security_iam_service-with-iam-roles-service)  |   Yes  | 
|  [Service-linked roles](security-iam.md#security_iam_service-with-iam-roles-service-linked)  |   No   | 

To get a high-level view of how Amazon SNS and other AWS services work with most IAM features, see [AWS services that work with IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html) in the *IAM User Guide*.

# AWS managed policies for Amazon Simple Notification Service
<a name="security-iam-awsmanpol"></a>



An AWS managed policy is a standalone policy that is created and administered by AWS. AWS managed policies are designed to provide permissions for many common use cases so that you can start assigning permissions to users, groups, and roles.

Keep in mind that AWS managed policies might not grant least-privilege permissions for your specific use cases because they're available for all AWS customers to use. We recommend that you reduce permissions further by defining [ customer managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#customer-managed-policies) that are specific to your use cases.

You cannot change the permissions defined in AWS managed policies. If AWS updates the permissions defined in an AWS managed policy, the update affects all principal identities (users, groups, and roles) that the policy is attached to. AWS is most likely to update an AWS managed policy when a new AWS service is launched or new API operations become available for existing services.

For more information, see [AWS managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#aws-managed-policies) in the *IAM User Guide*.

 





## AWS managed policy: AmazonSNSFullAccess
<a name="security-iam-awsmanpol-AmazonSNSFullAccess"></a>

`AmazonSNSFullAccess` provides full access to Amazon SNS using the AWS Management Console. This policy also includes the following read and write actions for AWS End User Messaging SMS when called using Amazon SNS. You can attach this policy to your users, groups, or roles.

**Permissions details**

The following permissions apply only when using the Amazon SNS APIs:
+ `sns:*` – Allows full permissions to perform any action related to Amazon SNS. This wildcard (\$1) means that the user can execute all possible Amazon SNS actions.
+ `sms-voice:DescribeVerifiedDestinationNumbers` – Allows you to retrieve a list of phone numbers that have been verified for sending SMS messages within the AWS account.
+ `sms-voice:CreateVerifiedDestinationNumber` – Allows you to verify a new phone number for use with SMS messaging services within AWS.
+ `sms-voice:SendDestinationNumberVerificationCode` – Allows you to send a verification code to a phone number that is in the process of being verified for SMS messaging within AWS. 
+ `sms-voice:SendTextMessage` – Allows you to create a new text message and send it to a recipient's phone number. `SendTextMessage` only sends an SMS message to one recipient each time it's invoked.
+ `sms-voice:DeleteVerifiedDestinationNumber` – Allows you to remove a phone number from the list of verified numbers within the AWS account
+ `sms-voice:VerifyDestinationNumber` – Allows you to initiate and complete the verification process for a phone number to be used for SMS messaging services within AWS.
+ `sms-voice:DescribeAccountAttributes` – Allows you to retrieve detailed information about the account-level attributes related to SMS messaging services within AWS.
+ `sms-voice:DescribeSpendLimits` – Allows you to retrieve information about the spending limits associated with SMS messaging services within the AWS account
+ `sms-voice:DescribePhoneNumbers` – Allows you to retrieve detailed information about the phone numbers associated with SMS messaging services within the AWS account 
+ `sms-voice:SetTextMessageSpendLimitOverride` – Allows you to set or override the spending limit for SMS text messaging within the AWS account
+ `sms-voice:DescribeOptedOutNumbers` – Allows you to retrieve a list of phone numbers that have opted out of receiving SMS messages from your AWS account.
+ `sms-voice:DeleteOptedOutNumber` – Allows you to remove a phone number from the list of opted-out numbers within the AWS account

**`AmazonSNSFullAccess` example policy**

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "SNSFullAccess",
            "Effect": "Allow",
            "Action": "sns:*",
            "Resource": "*"
        },
        {
            "Sid": "SMSAccessViaSNS",
            "Effect": "Allow",
            "Action": [
                "sms-voice:DescribeVerifiedDestinationNumbers",
                "sms-voice:CreateVerifiedDestinationNumber",
                "sms-voice:SendDestinationNumberVerificationCode",
                "sms-voice:SendTextMessage",
                "sms-voice:DeleteVerifiedDestinationNumber",
                "sms-voice:VerifyDestinationNumber",
                "sms-voice:DescribeAccountAttributes",
                "sms-voice:DescribeSpendLimits",
                "sms-voice:DescribePhoneNumbers",
                "sms-voice:SetTextMessageSpendLimitOverride",
                "sms-voice:DescribeOptedOutNumbers",
                "sms-voice:DeleteOptedOutNumber"
            ],
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "aws:CalledViaLast": "sns.amazonaws.com"
                }
            }
        }
    ]
}
```

------

To view the permissions for this policy, see [AmazonSNSFullAccess](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonSNSFullAccess.html) in the *AWS Managed Policy Reference*.

## AWS managed policy: AmazonSNSReadOnlyAccess
<a name="security-iam-awsmanpol-AmazonSNSReadOnlyAccess"></a>

`AmazonSNSReadOnlyAccess` provides read-only access to Amazon SNS using the AWS Management Console. This policy also includes the following read-only actions for AWS End User Messaging SMS when called using Amazon SNS. You can attach this policy to your users, groups, and roles.

**Permissions details**

The following permissions apply only when using the Amazon SNS APIs:
+ `sns:GetTopicAttributes` – Allows you to retrieve the attributes of an Amazon SNS topic. This includes information such as the topic's ARN (Amazon Resource Name), the list of subscribers, delivery policies, access control policies, and any other metadata associated with the topic.
+ `sns:List*` – Allows you to perform any operation that begins with `List` for Amazon SNS resources. This includes permissions to list various elements related to Amazon SNS, such as:
  + `sns:ListTopics` – Allows you to retrieve a list of all Amazon SNS topics in the AWS account.
  + `sns:ListSubscriptions` – Allows you to retrieve a list of all subscriptions to Amazon SNS topics.
  + `sns:ListSubscriptionsByTopic` – Allows you to list all subscriptions for a specific Amazon SNS topic.
  + `sns:ListPlatformApplications` – Allows you to list all platform applications that are created for mobile push notifications.
  + `sns:ListEndpointsByPlatformApplication` – Allows you to list all endpoints associated with a platform application.
+ `sns:CheckIfPhoneNumberIsOptedOut` – Allows you to check whether a specific phone number has opted out of receiving SMS messages through Amazon SNS.
+ `sns:GetEndpointAttributes` – Allows you to retrieve the attributes of an endpoint associated with an Amazon SNS platform application. This could include attributes such as the endpoint's enabled status, custom user data, and any other metadata associated with the endpoint.
+ `sns:GetDataProtectionPolicy` – Allows you to retrieve the data protection policy associated with an Amazon SNS topic.
+ `sns:GetPlatformApplicationAttributes` – Allows you to retrieve the attributes of an Amazon SNS platform application. Platform applications are used in Amazon SNS to send push notifications to mobile devices through services such as Apple Push Notification Service (APNS) or Firebase Cloud Messaging (FCM).
+ `sns:GetSMSAttributes` – Allows you to retrieve the default SMS settings for the AWS account. 
+ `sns:GetSMSSandboxAccountStatus` – Allows you to retrieve the current status of the SMS sandbox for your AWS account.
+ `sns:GetSubscriptionAttributes` – Allows you to retrieve the attributes of a specific subscription to an Amazon SNS topic.
+ `sms-voice:DescribeVerifiedDestinationNumbers` – Allows you to view or retrieve a list of phone numbers that have been verified for sending SMS messages within the AWS account
+ `sms-voice:DescribeAccountAttributes` – Allows you to view or retrieve information about the account-level attributes related to SMS messaging services within AWS.
+ `sms-voice:DescribeSpendLimits` – Allows you to view or retrieve information about the spending limits associated with SMS messaging services within your AWS account
+ `sms-voice:DescribePhoneNumbers` – Allows you to view or retrieve information about the phone numbers that are used for SMS messaging services within the AWS account
+ `sms-voice:DescribeOptedOutNumbers` – Allows you to view or retrieve a list of phone numbers that have opted out of receiving SMS messages from your AWS account

**`AmazonSNSReadOnlyAccess` example policy**

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "SNSReadOnlyAccess",
            "Effect": "Allow",
            "Action": [
                "sns:GetTopicAttributes",
                "sns:List*",
                "sns:CheckIfPhoneNumberIsOptedOut",
                "sns:GetEndpointAttributes",
                "sns:GetDataProtectionPolicy",
                "sns:GetPlatformApplicationAttributes",
                "sns:GetSMSAttributes",
                "sns:GetSMSSandboxAccountStatus",
                "sns:GetSubscriptionAttributes"
            ],
            "Resource": "*"
        },
        {
            "Sid": "SMSAccessViaSNS",
            "Effect": "Allow",
            "Action": [
                "sms-voice:DescribeVerifiedDestinationNumbers",
                "sms-voice:DescribeAccountAttributes",
                "sms-voice:DescribeSpendLimits",
                "sms-voice:DescribePhoneNumbers",
                "sms-voice:DescribeOptedOutNumbers"
            ],
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "aws:CalledViaLast": "sns.amazonaws.com"
                }
            }
        }
    ]
}
```

------

To view the permissions for this policy, see [AmazonSNSFullAccess](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonSNSFullAccess.html) in the *AWS Managed Policy Reference*.

## Amazon SNS updates to AWS managed policies
<a name="security-iam-awsmanpol-updates"></a>



View details about updates to AWS managed policies for Amazon SNS since this service began tracking these changes. For automatic alerts about changes to this page, subscribe to the RSS feed on the Amazon SNS Document history page.




| Change | Description | Date | 
| --- | --- | --- | 
|   [AmazonSNSFullAccess](#security-iam-awsmanpol-AmazonSNSFullAccess) – Update to an existing policy  |  Amazon SNS added new permissions to allow full access to Amazon SNS using the AWS Management Console.  | 09/24/2024 | 
|  [AmazonSNSReadOnlyAccess](#security-iam-awsmanpol-AmazonSNSReadOnlyAccess) – Update to an existing policy  |  Amazon SNS added new permissions to allow read-only access to Amazon SNS using the AWS Management Console.  | 09/24/2024 | 
|  Amazon SNS started tracking changes  |  Amazon SNS started tracking changes for its AWS managed policies.  | 08/27/2024 | 

## Policy actions for Amazon SNS
<a name="security_iam_service-with-iam-id-based-policies-actions"></a>

**Supports policy actions:** Yes

Administrators can use AWS JSON policies to specify who has access to what. That is, which **principal** can perform **actions** on what **resources**, and under what **conditions**.

The `Action` element of a JSON policy describes the actions that you can use to allow or deny access in a policy. Include actions in a policy to grant permissions to perform the associated operation.



To see a list of Amazon SNS actions, see [Resources Defined by Amazon Simple Notification Service](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonsns.html) in the *Service Authorization Reference*.

Policy actions in Amazon SNS use the following prefix before the action:

```
sns
```

To specify multiple actions in a single statement, separate them with commas.

```
"Action": [
      "sns:action1",
      "sns:action2"
         ]
```





To view examples of Amazon SNS identity-based policies, see [Identity-based policy examples for Amazon Simple Notification Service](security_iam_id-based-policy-examples.md).

## Policy resources for Amazon SNS
<a name="security_iam_service-with-iam-id-based-policies-resources"></a>

**Supports policy resources:** Yes

Administrators can use AWS JSON policies to specify who has access to what. That is, which **principal** can perform **actions** on what **resources**, and under what **conditions**.

The `Resource` JSON policy element specifies the object or objects to which the action applies. As a best practice, specify a resource using its [Amazon Resource Name (ARN)](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html). For actions that don't support resource-level permissions, use a wildcard (\$1) to indicate that the statement applies to all resources.

```
"Resource": "*"
```

To see a list of Amazon SNS resource types and their ARNs, see [Actions Defined by Amazon Simple Notification Service](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonsns.html) in the *Service Authorization Reference*. To learn with which actions you can specify the ARN of each resource, see [Resources Defined by Amazon Simple Notification Service](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonsns.html).





To view examples of Amazon SNS identity-based policies, see [Identity-based policy examples for Amazon Simple Notification Service](security_iam_id-based-policy-examples.md).

## Policy condition keys for Amazon SNS
<a name="security_iam_service-with-iam-id-based-policies-conditionkeys"></a>

**Supports service-specific policy condition keys:** Yes

Administrators can use AWS JSON policies to specify who has access to what. That is, which **principal** can perform **actions** on what **resources**, and under what **conditions**.

The `Condition` element specifies when statements execute based on defined criteria. You can create conditional expressions that use [condition operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html), such as equals or less than, to match the condition in the policy with values in the request. To see all AWS global condition keys, see [AWS global condition context keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html) in the *IAM User Guide*.

To see a list of Amazon SNS condition keys, see [Condition Keys for Amazon Simple Notification Service](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonsns.html) in the *Service Authorization Reference*. To learn with which actions and resources you can use a condition key, see [Resources Defined by Amazon Simple Notification Service](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonsns.html).

To view examples of Amazon SNS identity-based policies, see [Identity-based policy examples for Amazon Simple Notification Service](security_iam_id-based-policy-examples.md).

## ACLs in Amazon SNS
<a name="security_iam_service-with-iam-acls"></a>

**Supports ACLs:** No 

Access control lists (ACLs) control which principals (account members, users, or roles) have permissions to access a resource. ACLs are similar to resource-based policies, although they do not use the JSON policy document format.

## ABAC with Amazon SNS
<a name="security_iam_service-with-iam-tags"></a>

**Supports ABAC (tags in policies):** Partial

Attribute-based access control (ABAC) is an authorization strategy that defines permissions based on attributes called tags. You can attach tags to IAM entities and AWS resources, then design ABAC policies to allow operations when the principal's tag matches the tag on the resource.

To control access based on tags, you provide tag information in the [condition element](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html) of a policy using the `aws:ResourceTag/key-name`, `aws:RequestTag/key-name`, or `aws:TagKeys` condition keys.

If a service supports all three condition keys for every resource type, then the value is **Yes** for the service. If a service supports all three condition keys for only some resource types, then the value is **Partial**.

For more information about ABAC, see [Define permissions with ABAC authorization](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction_attribute-based-access-control.html) in the *IAM User Guide*. To view a tutorial with steps for setting up ABAC, see [Use attribute-based access control (ABAC)](https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html) in the *IAM User Guide*.

## Using temporary credentials with Amazon SNS
<a name="security_iam_service-with-iam-roles-tempcreds"></a>

**Supports temporary credentials:** Yes

Temporary credentials provide short-term access to AWS resources and are automatically created when you use federation or switch roles. AWS recommends that you dynamically generate temporary credentials instead of using long-term access keys. For more information, see [Temporary security credentials in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) and [AWS services that work with IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html) in the *IAM User Guide*.

## Cross-service principal permissions for Amazon SNS
<a name="security_iam_service-with-iam-principal-permissions"></a>

**Supports forward access sessions (FAS):** Yes

 Forward access sessions (FAS) use the permissions of the principal calling an AWS service, combined with the requesting AWS service to make requests to downstream services. For policy details when making FAS requests, see [Forward access sessions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_forward_access_sessions.html). 

## Service roles for Amazon SNS
<a name="security_iam_service-with-iam-roles-service"></a>

**Supports service roles:** Yes

 A service role is an [IAM role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) that a service assumes to perform actions on your behalf. An IAM administrator can create, modify, and delete a service role from within IAM. For more information, see [Create a role to delegate permissions to an AWS service](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html) in the *IAM User Guide*. 

**Warning**  
Changing the permissions for a service role might break Amazon SNS functionality. Edit service roles only when Amazon SNS provides guidance to do so.

## Service-linked roles for Amazon SNS
<a name="security_iam_service-with-iam-roles-service-linked"></a>

**Supports service-linked roles:** No 

 A service-linked role is a type of service role that is linked to an AWS service. The service can assume the role to perform an action on your behalf. Service-linked roles appear in your AWS account and are owned by the service. An IAM administrator can view, but not edit the permissions for service-linked roles. 

For details about creating or managing service-linked roles, see [AWS services that work with IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html). Find a service in the table that includes a `Yes` in the **Service-linked role** column. Choose the **Yes** link to view the service-linked role documentation for that service.

# Identity-based policy examples for Amazon Simple Notification Service
<a name="security_iam_id-based-policy-examples"></a>

By default, users and roles don't have permission to create or modify Amazon SNS resources. To grant users permission to perform actions on the resources that they need, an IAM administrator can create IAM policies.

To learn how to create an IAM identity-based policy by using these example JSON policy documents, see [Create IAM policies (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create-console.html) in the *IAM User Guide*.

For details about actions and resource types defined by Amazon SNS, including the format of the ARNs for each of the resource types, see [Actions, Resources, and Condition Keys for Amazon Simple Notification Service](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonsns.html) in the *Service Authorization Reference*.

## Policy best practices
<a name="security_iam_service-with-iam-policy-best-practices"></a>

Identity-based policies determine whether someone can create, access, or delete Amazon SNS resources in your account. These actions can incur costs for your AWS account. When you create or edit identity-based policies, follow these guidelines and recommendations:
+ **Get started with AWS managed policies and move toward least-privilege permissions** – To get started granting permissions to your users and workloads, use the *AWS managed policies* that grant permissions for many common use cases. They are available in your AWS account. We recommend that you reduce permissions further by defining AWS customer managed policies that are specific to your use cases. For more information, see [AWS managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#aws-managed-policies) or [AWS managed policies for job functions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_job-functions.html) in the *IAM User Guide*.
+ **Apply least-privilege permissions** – When you set permissions with IAM policies, grant only the permissions required to perform a task. You do this by defining the actions that can be taken on specific resources under specific conditions, also known as *least-privilege permissions*. For more information about using IAM to apply permissions, see [ Policies and permissions in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) in the *IAM User Guide*.
+ **Use conditions in IAM policies to further restrict access** – You can add a condition to your policies to limit access to actions and resources. For example, you can write a policy condition to specify that all requests must be sent using SSL. You can also use conditions to grant access to service actions if they are used through a specific AWS service, such as CloudFormation. For more information, see [ IAM JSON policy elements: Condition](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html) in the *IAM User Guide*.
+ **Use IAM Access Analyzer to validate your IAM policies to ensure secure and functional permissions** – IAM Access Analyzer validates new and existing policies so that the policies adhere to the IAM policy language (JSON) and IAM best practices. IAM Access Analyzer provides more than 100 policy checks and actionable recommendations to help you author secure and functional policies. For more information, see [Validate policies with IAM Access Analyzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-policy-validation.html) in the *IAM User Guide*.
+ **Require multi-factor authentication (MFA)** – If you have a scenario that requires IAM users or a root user in your AWS account, turn on MFA for additional security. To require MFA when API operations are called, add MFA conditions to your policies. For more information, see [ Secure API access with MFA](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html) in the *IAM User Guide*.

For more information about best practices in IAM, see [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the *IAM User Guide*.

## Using the Amazon SNS console
<a name="security_iam_id-based-policy-examples-console"></a>

To access the Amazon Simple Notification Service console, you must have a minimum set of permissions. These permissions must allow you to list and view details about the Amazon SNS resources in your AWS account. If you create an identity-based policy that is more restrictive than the minimum required permissions, the console won't function as intended for entities (users or roles) with that policy.

You don't need to allow minimum console permissions for users that are making calls only to the AWS CLI or the AWS API. Instead, allow access to only the actions that match the API operation that they're trying to perform.

To ensure that users and roles can still use the Amazon SNS console, also attach the Amazon SNS `ConsoleAccess` or `ReadOnly` AWS managed policy to the entities. For more information, see [Adding permissions to a user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_change-permissions.html#users_change_permissions-add-console) in the *IAM User Guide*.

## Other policy types
<a name="security_iam_access-manage-other-policies"></a>

AWS supports additional policy types that can set the maximum permissions granted by more common policy types:
+ **Permissions boundaries** – Set the maximum permissions that an identity-based policy can grant to an IAM entity. For more information, see [Permissions boundaries for IAM entities](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) in the *IAM User Guide*.
+ **Service control policies (SCPs)** – Specify the maximum permissions for an organization or organizational unit in AWS Organizations. For more information, see [Service control policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html) in the *AWS Organizations User Guide*.
+ **Resource control policies (RCPs)** – Set the maximum available permissions for resources in your accounts. For more information, see [Resource control policies (RCPs)](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_rcps.html) in the *AWS Organizations User Guide*.
+ **Session policies** – Advanced policies passed as a parameter when creating a temporary session for a role or federated user. For more information, see [Session policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) in the *IAM User Guide*.

## Multiple policy types
<a name="security_iam_access-manage-multiple-policies"></a>

When multiple types of policies apply to a request, the resulting permissions are more complicated to understand. To learn how AWS determines whether to allow a request when multiple policy types are involved, see [Policy evaluation logic](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html) in the *IAM User Guide*.

## Allow users to view their own permissions
<a name="security_iam_id-based-policy-examples-view-own-permissions"></a>

This example shows how you might create a policy that allows IAM users to view the inline and managed policies that are attached to their user identity. This policy includes permissions to complete this action on the console or programmatically using the AWS CLI or AWS API.

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "ViewOwnUserInfo",
            "Effect": "Allow",
            "Action": [
                "iam:GetUserPolicy",
                "iam:ListGroupsForUser",
                "iam:ListAttachedUserPolicies",
                "iam:ListUserPolicies",
                "iam:GetUser"
            ],
            "Resource": ["arn:aws:iam::*:user/${aws:username}"]
        },
        {
            "Sid": "NavigateInConsole",
            "Effect": "Allow",
            "Action": [
                "iam:GetGroupPolicy",
                "iam:GetPolicyVersion",
                "iam:GetPolicy",
                "iam:ListAttachedGroupPolicies",
                "iam:ListGroupPolicies",
                "iam:ListPolicyVersions",
                "iam:ListPolicies",
                "iam:ListUsers"
            ],
            "Resource": "*"
        }
    ]
}
```

## Identity-based policies for Amazon SNS
<a name="security_iam_service-with-iam-id-based-policies"></a>

**Supports identity-based policies:** Yes

Identity-based policies are JSON permissions policy documents that you can attach to an identity, such as an IAM user, group of users, or role. These policies control what actions users and roles can perform, on which resources, and under what conditions. To learn how to create an identity-based policy, see [Define custom IAM permissions with customer managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html) in the *IAM User Guide*.

With IAM identity-based policies, you can specify allowed or denied actions and resources as well as the conditions under which actions are allowed or denied. To learn about all of the elements that you can use in a JSON policy, see [IAM JSON policy elements reference](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html) in the *IAM User Guide*.

### Identity-based policy examples for Amazon SNS
<a name="security_iam_service-with-iam-id-based-policies-examples"></a>



To view examples of Amazon SNS identity-based policies, see [Identity-based policy examples for Amazon Simple Notification Service](security_iam_id-based-policy-examples.md).

## Resource-based policies within Amazon SNS
<a name="security_iam_service-with-iam-resource-based-policies"></a>


|  |  | 
| --- |--- |
|  Supports resource-based policies  |  Yes  | 

Resource-based policies are JSON policy documents that you attach to a resource. Examples of resource-based policies are IAM *role trust policies* and Amazon S3 *bucket policies*. In services that support resource-based policies, service administrators can use them to control access to a specific resource. For the resource where the policy is attached, the policy defines what actions a specified principal can perform on that resource and under what conditions. You must [specify a principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html) in a resource-based policy. Principals can include accounts, users, roles, federated users, or AWS services.

To enable cross-account access, you can specify an entire account or IAM entities in another account as the principal in a resource-based policy. For more information, see [Cross account resource access in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-cross-account-resource-access.html) in the *IAM User Guide*.

# Using identity-based policies with Amazon SNS
<a name="sns-using-identity-based-policies"></a>

Amazon Simple Notification Service integrates with AWS Identity and Access Management (IAM) so that you can specify which Amazon SNS actions a user in your AWS account can perform with Amazon SNS resources. You can specify a particular topic in the policy. For example, you could use variables when creating an IAM policy that grants certain users in your organization permission to use the `Publish` action with specific topics in your AWS account. For more information, see [Policy Variables](https://docs.aws.amazon.com/IAM/latest/UserGuide/PolicyVariables.html) in the *Using IAM* guide.

**Important**  
Using Amazon SNS with IAM doesn't change how you use Amazon SNS. There are no changes to Amazon SNS actions, and no new Amazon SNS actions related to users and access control.

For examples of policies that cover Amazon SNS actions and resources, see [Example policies for Amazon SNS](#sns-example-policies).

## IAM and Amazon SNS policies together
<a name="iam-and-sns-policies"></a>

You use an IAM policy to restrict your users' access to Amazon SNS actions and topics. An IAM policy can restrict access only to users within your AWS account, not to other AWS accounts.

You use an Amazon SNS policy with a particular topic to restrict who can work with that topic (for example, who can publish messages to it, who can subscribe to it, etc.). Amazon SNS policies can grant access to other AWS accounts, or to users within your own AWS account.

To grant your users permissions for your Amazon SNS topics, you can use IAM policies, Amazon SNS policies, or both. For the most part, you can achieve the same results with either. For example, the following diagram shows an IAM policy and an Amazon SNS policy that are equivalent. The IAM policy allows the Amazon SNS `Subscribe` action for the topic called topic\$1xyz in your AWS account The IAM policy is attached to the users Bob and Susan (which means that Bob and Susan have the permissions stated in the policy). The Amazon SNS policy likewise grants Bob and Susan permission to access `Subscribe` for topic\$1xyz.

![\[Compares an IAM policy and an Amazon SNS policy, showing that both policies grant equivalent permissions to two users, Bob and Susan, allowing them to subscribe to a specific Amazon SNS topic within an AWS account. The key difference highlighted is that Amazon SNS policies can grant permissions to users across different AWS accounts, whereas IAM policies cannot.\]](http://docs.aws.amazon.com/sns/latest/dg/images/SNS_EquivalentPolicies.png)


**Note**  
The preceding example shows simple policies with no conditions. You could specify a particular condition in either policy and get the same result.

There is one difference between AWS IAM and Amazon SNS policies: The Amazon SNS policy system lets you grant permission to other AWS accounts, whereas the IAM policy doesn't. 

It's up to you how you use both of the systems together to manage your permissions, based on your needs. The following examples show how the two policy systems work together.

**Example 1**  
In this example, both an IAM policy and an Amazon SNS policy apply to Bob. The IAM policy grants him permission for `Subscribe` on any of the AWS account's topics, whereas the Amazon SNS policy grants him permission to use `Publish` on a specific topic (topic\$1xyz). The following diagram illustrates the concept.  

![\[Shows how both an IAM policy and an Amazon SNS policy apply to the user Bob, with the IAM policy allowing him to subscribe to any topic in the AWS account, and the Amazon SNS policy granting him permission to publish messages to a specific topic named "topic_xyz." The diagram emphasizes the distinction between general permissions granted by the IAM policy and specific permissions granted by the Amazon SNS policy for a particular topic.\]](http://docs.aws.amazon.com/sns/latest/dg/images/SNS_UnionOfPolicies.png)

If Bob were to send a request to subscribe to any topic in the AWS account, the IAM policy would allow the action. If Bob were to send a request to publish a message to topic\$1xyz, the Amazon SNS policy would allow the action.  
 

**Example 2**  
In this example, we build on example 1 (where Bob has two policies that apply to him). Let's say that Bob publishes messages to topic\$1xyz that he shouldn't have, so you want to entirely remove his ability to publish to topics. The easiest thing to do is to add an IAM policy that denies him access to the `Publish` action on all topics. This third policy overrides the Amazon SNS policy that originally gave him permission to publish to topic\$1xyz, because an explicit deny always overrides an allow (for more information about policy evaluation logic, see [Evaluation logic](sns-access-policy-language-evaluation-logic.md)). The following diagram illustrates the concept.  

![\[Illustration of how adding an IAM policy that denies the "Publish" action for all topics can override an existing Amazon SNS policy that allowed the user Bob to publish to a specific topic, "topic_xyz." The IAM deny policy takes precedence over the Amazon SNS policy, effectively preventing Bob from publishing to any topic, including "topic_xyz."\]](http://docs.aws.amazon.com/sns/latest/dg/images/SNS_DenyOverride.png)


For examples of policies that cover Amazon SNS actions and resources, see [Example policies for Amazon SNS](#sns-example-policies).

## Amazon SNS resource ARN format
<a name="sns-arn-format"></a>

For Amazon SNS, topics are the only resource type you can specify in a policy. The following is the Amazon Resource Name (ARN) format for topics.

```
arn:aws:sns:region:account_ID:topic_name
```

For more information about ARNs, go to [ARNs](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html#Identifiers_ARNs) in *IAM User Guide*.

**Example**  
The following is an ARN for a topic named MyTopic in the us-east-2 region, belonging to AWS account 123456789012.   

```
arn:aws:sns:us-east-2:123456789012:MyTopic
```

**Example**  
If you had a topic named MyTopic in each of the different Regions that Amazon SNS supports, you could specify the topics with the following ARN.   

```
arn:aws:sns:*:123456789012:MyTopic
```

You can use \$1 and ? wildcards in the topic name. For example, the following could refer to all the topics created by Bob that he has prefixed with `bob_`.

```
arn:aws:sns:*:123456789012:bob_*
```

As a convenience to you, when you create a topic, Amazon SNS returns the topic's ARN in the response.

## Amazon SNS API actions
<a name="sns-api-actions"></a>

In an IAM policy, you can specify any actions that Amazon SNS offers. However, the `ConfirmSubscription` and `Unsubscribe` actions do not require authentication, which means that even if you specify those actions in a policy, IAM won't restrict users' access to those actions.

Each action you specify in a policy must be prefixed with the lowercase string `sns:`. To specify all Amazon SNS actions, for example, you would use `sns:*`. For a list of the actions, go to the [Amazon Simple Notification Service API Reference](https://docs.aws.amazon.com/sns/latest/api/). 

## Amazon SNS policy keys
<a name="sns-policy-keys"></a>

Amazon SNS implements the following AWS wide policy keys, plus some service-specific keys.

For a list of condition keys supported by each AWS service, see [Actions, resources, and condition keys for AWS services](https://docs.aws.amazon.com/service-authorization/latest/reference/reference_policies_actions-resources-contextkeys.html) in the *IAM User Guide*. For a list of condition keys that can be used in multiple AWS services, see [AWS global condition context keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html) in the *IAM User Guide*.

Amazon SNS uses the following service-specific keys. Use these keys in policies that restrict access to `Subscribe` requests.
+ **sns:endpoint—**The URL, email address, or ARN from a `Subscribe` request or a previously confirmed subscription. Use with string conditions (see [Example policies for Amazon SNS](#sns-example-policies)) to restrict access to specific endpoints (for example, \$1@yourcompany.com).
+ **sns:protocol—**The `protocol` value from a `Subscribe` request or a previously confirmed subscription. Use with string conditions (see [Example policies for Amazon SNS](#sns-example-policies)) to restrict publication to specific delivery protocols (for example, https). 

## Example policies for Amazon SNS
<a name="sns-example-policies"></a>

This section shows several simple policies for controlling user access to Amazon SNS.

**Note**  
In the future, Amazon SNS might add new actions that should logically be included in one of the following policies, based on the policy’s stated goals. 

**Example 1: Allow a group to create and manage topics**  
In this example, we create a policy that grants access to `CreateTopic`, `ListTopics`, `SetTopicAttributes`, and `DeleteTopic`.  

```
{
  "Statement": [{
    "Effect": "Allow",
    "Action": ["sns:CreateTopic", "sns:ListTopics", "sns:SetTopicAttributes", "sns:DeleteTopic"],
    "Resource": "*"
  }]
}
```

**Example 2: Allow the IT group to publish messages to a particular topic**  
In this example, we create a group for IT, and assign a policy that grants access to `Publish` on the specific topic of interest.  

```
{
  "Statement": [{
    "Effect": "Allow",
    "Action": "sns:Publish",
    "Resource": "arn:aws:sns:*:123456789012:MyTopic"
  }]
}
```

**Example 3: Give users in the AWS account ability to subscribe to topics**  
In this example, we create a policy that grants access to the `Subscribe`action, with string matching conditions for the `sns:Protocol` and `sns:Endpoint` policy keys.  

```
{
  "Statement": [{
    "Effect": "Allow",
    "Action": ["sns:Subscribe"],
    "Resource": "*",
    "Condition": {
      "StringLike": {
        "sns:Endpoint": "*@example.com"
      },
      "StringEquals": {
        "sns:Protocol": "email"
      }
    }
  }]
}
```

**Example 4: Allow a partner to publish messages to a particular topic**  
You can use an Amazon SNS policy or an IAM policy to allow a partner to publish to a specific topic. If your partner has an AWS account, it might be easier to use an Amazon SNS policy. However, anyone in the partner's company who possesses the AWS security credentials could publish messages to the topic. This example assumes that you want to limit access to a particular person (or application). To do this you need to treat the partner like a user within your own company, and use a IAM policy instead of an Amazon SNS policy.  
For this example, we create a group called WidgetCo that represents the partner company; we create a user for the specific person (or application) at the partner company who needs access; and then we put the user in the group.   
We then attach a policy that grants the group `Publish` access on the specific topic named *WidgetPartnerTopic*.   
We also want to prevent the WidgetCo group from doing anything else with topics, so we add a statement that denies permission to any Amazon SNS actions other than `Publish` on any topics other than WidgetPartnerTopic. This is necessary only if there's a broad policy elsewhere in the system that grants users wide access to Amazon SNS.   

```
{
  "Statement": [{
      "Effect": "Allow",
      "Action": "sns:Publish",
      "Resource": "arn:aws:sns:*:123456789012:WidgetPartnerTopic"
    },
    {
      "Effect": "Deny",
      "NotAction": "sns:Publish",
      "NotResource": "arn:aws:sns:*:123456789012:WidgetPartnerTopic"
    }
  ]
}
```

## Amazon SNS Policies for Email Endpoints
<a name="sns-email-endpoints"></a>

Amazon SNS normalizes email addresses in endpoint access policies by removing leading and trailing whitespace, converting all characters to lowercase, and normalizing special characters and escape sequences. Because of that, you must use lowercase email addresses in your policy definitions to ensure proper matching of subscription requests. 

Example policy:

```
{
    "Condition": {
        "StringEquals": {
            "sns:Endpoint": "user.name@example.com"
        }
    }
}
```

The following email addresses match the above condition:
+ `user.name@example.com`
+ `USER.NAME@EXAMPLE.COM`
+ `User.N\ame@Example.com`

## Amazon SNS policies for HTTP/HTTPs endpoints
<a name="sns-http-https-endpoints"></a>

Amazon SNS normalizes HTTP/HTTPs endpoints in endpoint access policies by converting the scheme and hostname to lowercase while preserving the port, path, query parameters, and fragments exactly. Because of that, you must use lowercase scheme and hostname in your policy definitions to ensure proper matching of subscription requests. 

```
{
    "Condition": {
        "StringEquals": {
            "sns:Endpoint": "https://example.com:443/path?A=B"
        }
    }
}
```

The following HTTP/HTTPs match the above condition:
+ `HTTPS://EXAMPLE.COM:443/path?A=B`
+ `HTTPS://example.com:443/path?A=B`
+ `HTTPS://ExAmPlE.cOm:443/path?A=B`

# Managing custom Amazon SNS IAM policies
<a name="sns-sms-custom-policies"></a>

Custom IAM policies allow you to specify permissions for individual IAM users, groups, or roles, granting or restricting access to specific AWS resources and actions. When managing Amazon SNS resources, custom IAM policies allow you to tailor access permissions according to your organization's security and operational requirements.

Use the following steps to manage custom IAM policies for Amazon SNS:

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. From the navigation pane, choose **Policies**.

1. To create a new custom IAM policy, choose **Create policy** and choose **SNS**. To edit an existing policy, select the policy from the list and choose **Edit policy**.

1. In the policy editor, define the **permissions** for accessing Amazon SNS resources. You can specify **actions**, **resources**, and **conditions** based on your specific requirements.

1. To grant permissions for Amazon SNS actions, include relevant Amazon SNS actions such as `sns:Publish`, `sns:Subscribe`, and `sns:DeleteTopic` in your IAM policy. Define the ARN (Amazon Resource Name) of the Amazon SNS topics to which the permissions apply.

1. Specify the IAM **users**, **groups**, or **roles** to which the policy should be attached. You can attach the policy directly to IAM users or groups, or associate it with IAM roles used by AWS services or applications.

1. Review the IAM policy configuration to ensure it aligns with your access control requirements. Once verified, **save** the policy changes.

1. Attach the **custom IAM policy** to the relevant IAM users, groups, or roles within your AWS account. This grants them the permissions defined in the policy for managing Amazon SNS resources.

# Using temporary security credentials with Amazon SNS
<a name="sns-using-temporary-credentials"></a>

AWS Identity and Access Management (IAM) allows you to grant temporary security credentials to users and applications that need access to your AWS resources. These temporary security credentials are primarily used for IAM roles and federated access via industry-standard protocols such as SAML and OpenID Connect (OIDC).

To effectively manage access to AWS resources, it's essential to understand the following key concepts:
+ **IAM Roles** – Roles are used to delegate access to AWS resources. Roles can be assumed by entities such as Amazon EC2 instances, Lambda functions, or users from other AWS accounts.
+ **Federated Users** – These are users authenticated via external identity providers (IdPs) using SAML or OIDC. Federated access is recommended for human users, while IAM roles should be used for software applications.
+ **Roles Anywhere** – For external applications requiring AWS access, you can use IAM Roles Anywhere to securely manage access without creating long-term credentials.

You can use temporary security credentials to make requests to Amazon SNS. The SDKs and API libraries compute the necessary signature using these credentials to authenticate your requests. Requests with expired credentials will be denied by Amazon SNS.

For more information on temporary security credentials, refer to [Using IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) and [Providing access to externally authenticated users (identity federation)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_federated-users.html) in the *IAM User Guide*.

**Example HTTPS request example**  
The following example demonstrates how to authenticate an Amazon SNS request using temporary security credentials obtained from AWS Security Token Service (STS).  

```
https://sns.us-east-2.amazonaws.com/
?Action=CreateTopic
&Name=My-Topic
&SignatureVersion=4
&SignatureMethod=AWS4-HMAC-SHA256
&Timestamp=2023-07-05T12:00:00Z
&X-Amz-Security-Token=SecurityTokenValue
&X-Amz-Date=20230705T120000Z
&X-Amz-Credential=<your-access-key-id>/20230705/us-east-2/sns/aws4_request
&X-Amz-SignedHeaders=host
&X-Amz-Signature=<signature-value>
```

**Steps to authenticate the request**

1. **Obtain Temporary Security Credentials** – Use AWS STS to assume a role or get federated user credentials. This will provide you with an access key ID, secret access key, and security token.

1. **Construct the Request** – Include the required parameters for your Amazon SNS action (for example, CreateTopic), and ensure you use HTTPS for secure communication.

1. **Sign the Request** – Use the AWS Signature Version 4 process to sign your request. This involves creating a canonical request, string-to-sign, and then calculating the signature. For more on AWS Signature Version 4, see [Use Signature Version 4 signing](https://docs.aws.amazon.com/ebs/latest/userguide/ebsapis-using-sigv4.html) in the *Amazon EBS User Guide*.

1. **Send the Request** – Include the X-Amz-Security-Token in your request header to pass the temporary security credentials to Amazon SNS.

# Amazon SNS API permissions: Actions and resources reference
<a name="sns-access-policy-language-api-permissions-reference"></a>

The following list grants information specific to the Amazon SNS implementation of access control:
+ Each policy must cover only a single topic (when writing a policy, don't include statements that cover different topics)
+ Each policy must have a unique policy `Id`
+ Each statement in a policy must have a unique statement `sid`

## Policy quotas
<a name="sns-policy-quotas"></a>

The following table lists the maximum quotas for a policy statement.


| Name | Maximum quota | 
| --- | --- | 
|  Bytes  |  30 kb  | 
|  Statements  |  100  | 
|  Principals  |  1 to 200 (0 is invalid.)  | 
|  Resource  |  1 (0 is invalid. The value must match the ARN of the policy's topic.)  | 

## Valid Amazon SNS policy actions
<a name="sns-valid-policy-actions"></a>

Amazon SNS supports the actions shown in the following table.


| Action | Description | 
| --- | --- | 
| sns:AddPermission | Grants permission to add permissions to the topic policy. | 
| sns:DeleteTopic | Grants permission to delete a topic. | 
| sns:GetDataProtectionPolicy | Grants permission to retrieve a topic's data protection policy.  | 
| sns:GetTopicAttributes  | Grants permission to receive all of the topic attributes. | 
| sns:ListSubscriptionsByTopic | Grants permission to retrieve all the subscriptions to a specific topic. | 
| sns:ListTagsForResource | Grants permission to list all tags added to a specific topic. | 
| sns:Publish  | Grants permission to both publish and publish batch to a topic or endpoint. For more information, see [Publish](https://docs.aws.amazon.com/sns/latest/api/API_Publish.html) and [PublishBatch](https://docs.aws.amazon.com/sns/latest/api/API_BatchPublish.html) in the Amazon Simple Notification Service API Reference. | 
| sns:PutDataProtectionPolicy | Grants permission to set a topic's data protection policy. | 
| sns:RemovePermission  | Grants permission to remove any permissions in the topic policy. | 
| sns:SetTopicAttributes  | Grants permission to set a topic's attributes. | 
| sns:Subscribe  | Grants permission to subscribe to a topic. | 

## Service-specific keys
<a name="sns-service-specific-keys"></a>

Amazon SNS uses the following service-specific keys. You can use these in policies that restrict access to `Subscribe` requests.
+ **sns:endpoint—**The URL, email address, or ARN from a `Subscribe` request or a previously confirmed subscription. Use with string conditions (see [Example policies for Amazon SNS](sns-using-identity-based-policies.md#sns-example-policies)) to restrict access to specific endpoints (for example, \$1@example.com).
+ **sns:protocol—**The `protocol` value from a `Subscribe` request or a previously confirmed subscription. Use with string conditions (see [Example policies for Amazon SNS](sns-using-identity-based-policies.md#sns-example-policies)) to restrict publication to specific delivery protocols (for example, https).

**Important**  
When you use a policy to control access by sns:Endpoint, be aware that DNS issues might affect the endpoint's name resolution in the future.

# Troubleshooting Amazon Simple Notification Service identity and access
<a name="security_iam_troubleshoot"></a>

Use the following information to help you diagnose and fix common issues that you might encounter when working with Amazon SNS and IAM.

## I am not authorized to perform an action in Amazon SNS
<a name="security_iam_troubleshoot-no-permissions"></a>

If you receive an error that you're not authorized to perform an action, your policies must be updated to allow you to perform the action.

The following example error occurs when the `mateojackson` user tries to use the console to view details about a fictional `my-example-widget` resource but does not have the fictional `sns:GetWidget` permissions.

```
User: arn:aws:iam::123456789012:user/mateojackson is not authorized to perform: sns:GetWidget on resource: my-example-widget
```

In this case, Mateo's policy must be updated to allow him to access the `my-example-widget` resource using the `sns:GetWidget` action.

If you need help, contact your AWS administrator. Your administrator is the person who provided you with your sign-in credentials.

## I am not authorized to perform iam:PassRole
<a name="security_iam_troubleshoot-passrole"></a>

If you receive an error that you're not authorized to perform the `iam:PassRole` action, your policies must be updated to allow you to pass a role to Amazon SNS.

Some AWS services allow you to pass an existing role to that service instead of creating a new service role or service-linked role. To do this, you must have permissions to pass the role to the service.

The following example error occurs when an IAM user named `marymajor` tries to use the console to perform an action in Amazon SNS. However, the action requires the service to have permissions that are granted by a service role. Mary does not have permissions to pass the role to the service.

```
User: arn:aws:iam::123456789012:user/marymajor is not authorized to perform: iam:PassRole
```

In this case, Mary's policies must be updated to allow her to perform the `iam:PassRole` action.

If you need help, contact your AWS administrator. Your administrator is the person who provided you with your sign-in credentials.

## I want to allow people outside of my AWS account to access my Amazon SNS resources
<a name="security_iam_troubleshoot-cross-account-access"></a>

You can create a role that users in other accounts or people outside of your organization can use to access your resources. You can specify who is trusted to assume the role. For services that support resource-based policies or access control lists (ACLs), you can use those policies to grant people access to your resources.

To learn more, consult the following:
+ To learn whether Amazon SNS supports these features, see [How Amazon SNS works with IAM](security_iam_service-with-iam.md).
+ To learn how to provide access to your resources across AWS accounts that you own, see [Providing access to an IAM user in another AWS account that you own](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_aws-accounts.html) in the *IAM User Guide*.
+ To learn how to provide access to your resources to third-party AWS accounts, see [Providing access to AWS accounts owned by third parties](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_third-party.html) in the *IAM User Guide*.
+ To learn how to provide access through identity federation, see [Providing access to externally authenticated users (identity federation)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_federated-users.html) in the *IAM User Guide*.
+ To learn the difference between using roles and resource-based policies for cross-account access, see [Cross account resource access in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-cross-account-resource-access.html) in the *IAM User Guide*.

# Logging and monitoring in Amazon SNS
<a name="sns-logging-monitoring"></a>

Amazon SNS allows you to track and monitor messaging activity by logging API calls with CloudTrail and monitoring topics with CloudWatch. These tools help you gain insights into message delivery, troubleshoot issues, and ensure the health of your messaging workflows. This topic covers the following:
+ [Logging AWS SNS API calls using AWS CloudTrail](logging-using-cloudtrail.md). This logging enables you to track the actions performed on your Amazon SNS topics, such as topic creation, subscription management, and message publishing. By analyzing CloudTrail logs, you can identify who made specific API requests and when those requests were made, helping you audit and troubleshoot your Amazon SNS usage.
+ [Monitoring Amazon SNS topics using CloudWatch](sns-monitoring-using-cloudwatch.md). CloudWatch provides metrics that allow you to observe the performance and health of your Amazon SNS topics in real time. Set up alarms based on these metrics, enabling you to respond promptly to any anomalies, such as delivery failures or high message latency. This monitoring capability ensures that you can maintain the reliability of your SNS-based messaging system by proactively addressing potential issues.

# Logging AWS SNS API calls using AWS CloudTrail
<a name="logging-using-cloudtrail"></a>

AWS SNS is integrated with [AWS CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html), a service that provides a record of actions taken by a user, role, or an AWS service. CloudTrail captures all API calls for SNS as events. The calls captured include calls from the SNS console and code calls to the SNS API operations. Using the information collected by CloudTrail, you can determine the request that was made to SNS, the IP address from which the request was made, when it was made, and additional details.

Every event or log entry contains information about who generated the request. The identity information helps you determine the following:
+ Whether the request was made with root user or user credentials.
+ Whether the request was made on behalf of an IAM Identity Center user.
+ Whether the request was made with temporary security credentials for a role or federated user.
+ Whether the request was made by another AWS service.

CloudTrail is active in your AWS account when you create the account and you automatically have access to the CloudTrail **Event history**. The CloudTrail **Event history** provides a viewable, searchable, downloadable, and immutable record of the past 90 days of recorded management events in an AWS Region. For more information, see [Working with CloudTrail Event history](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/view-cloudtrail-events.html) in the *AWS CloudTrail User Guide*. There are no CloudTrail charges for viewing the **Event history**.

For an ongoing record of events in your AWS account past 90 days, create a trail or a [CloudTrail Lake](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-lake.html) event data store.

**CloudTrail trails**  
A *trail* enables CloudTrail to deliver log files to an Amazon S3 bucket. All trails created using the AWS Management Console are multi-Region. You can create a single-Region or a multi-Region trail by using the AWS CLI. Creating a multi-Region trail is recommended because you capture activity in all AWS Regions in your account. If you create a single-Region trail, you can view only the events logged in the trail's AWS Region. For more information about trails, see [Creating a trail for your AWS account](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-create-and-update-a-trail.html) and [Creating a trail for an organization](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/creating-trail-organization.html) in the *AWS CloudTrail User Guide*.  
You can deliver one copy of your ongoing management events to your Amazon S3 bucket at no charge from CloudTrail by creating a trail, however, there are Amazon S3 storage charges. For more information about CloudTrail pricing, see [AWS CloudTrail Pricing](https://aws.amazon.com/cloudtrail/pricing/). For information about Amazon S3 pricing, see [Amazon S3 Pricing](https://aws.amazon.com/s3/pricing/).

**CloudTrail Lake event data stores**  
*CloudTrail Lake* lets you run SQL-based queries on your events. CloudTrail Lake converts existing events in row-based JSON format to [ Apache ORC](https://orc.apache.org/) format. ORC is a columnar storage format that is optimized for fast retrieval of data. Events are aggregated into *event data stores*, which are immutable collections of events based on criteria that you select by applying [advanced event selectors](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-lake-concepts.html#adv-event-selectors). The selectors that you apply to an event data store control which events persist and are available for you to query. For more information about CloudTrail Lake, see [Working with AWS CloudTrail Lake](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-lake.html) in the *AWS CloudTrail User Guide*.  
CloudTrail Lake event data stores and queries incur costs. When you create an event data store, you choose the [pricing option](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-lake-manage-costs.html#cloudtrail-lake-manage-costs-pricing-option) you want to use for the event data store. The pricing option determines the cost for ingesting and storing events, and the default and maximum retention period for the event data store. For more information about CloudTrail pricing, see [AWS CloudTrail Pricing](https://aws.amazon.com/cloudtrail/pricing/).

## SNS data events in CloudTrail
<a name="cloudtrail-data-events"></a>

[Data events](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-data-events-with-cloudtrail.html#logging-data-events) provide information about the resource operations performed on or in a resource (for example, reading or writing to an Amazon S3 object). These are also known as data plane operations. Data events are often high-volume activities. By default, CloudTrail doesn’t log data events. The CloudTrail **Event history** doesn't record data events.

Additional charges apply for data events. For more information about CloudTrail pricing, see [AWS CloudTrail Pricing](https://aws.amazon.com/cloudtrail/pricing/).

You can log data events for the SNS resource types by using the CloudTrail console, AWS CLI, or CloudTrail API operations. For more information about how to log data events, see [Logging data events with the AWS Management Console](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-data-events-with-cloudtrail.html#logging-data-events-console) and [Logging data events with the AWS Command Line Interface](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-data-events-with-cloudtrail.html#creating-data-event-selectors-with-the-AWS-CLI) in the *AWS CloudTrail User Guide*.

The following table lists the SNS resource types for which you can log data events. The **Data event type (console)** column shows the value to choose from the **Data event type** list on the CloudTrail console. The **resources.type value** column shows the `resources.type` value, which you would specify when configuring advanced event selectors using the AWS CLI or CloudTrail APIs. The **Data APIs logged to CloudTrail** column shows the API calls logged to CloudTrail for the resource type. 


| Data event type (console) | resources.type value | Data APIs logged to CloudTrail | 
| --- | --- | --- | 
| SNS topic |  [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sns-topic.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sns-topic.html)  | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/sns/latest/dg/logging-using-cloudtrail.html) | 
| SNS platform endpoint |  AWS::SNS::PlatformEndpoint  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/sns/latest/dg/logging-using-cloudtrail.html)  | 

**Note**  
SNS resource type `AWS::SNS::PhoneNumber` is not logged by CloudTrail.

You can configure advanced event selectors to filter on the `eventName`, `readOnly`, and `resources.ARN` fields to log only those events that are important to you. For more information about these fields, see [https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_AdvancedFieldSelector.html](https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_AdvancedFieldSelector.html) in the *AWS CloudTrail API Reference*.

For information about logging data events, see Logging data events with the AWS Management Console and Logging data events with the AWS CLI in the CloudTrail User Guide.

## SNS management events in CloudTrail
<a name="cloudtrail-management-events"></a>

[Management events](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-management-events-with-cloudtrail.html#logging-management-events) provide information about management operations that are performed on resources in your AWS account. These are also known as control plane operations. By default, CloudTrail logs management events.

AWS SNS logs the following SNS control plane operations to CloudTrail as *management events*.
+ `[AddPermission](https://docs.aws.amazon.com/sns/latest/api/API_AddPermission.html)`
+ `[CheckIfPhoneNumberIsOptedOut](https://docs.aws.amazon.com/sns/latest/api/API_CheckIfPhoneNumberIsOptedOut.html)`
+ `[ConfirmSubscription](https://docs.aws.amazon.com/sns/latest/api/API_ConfirmSubscription.html)`
+ `[CreatePlatformApplication](https://docs.aws.amazon.com/sns/latest/api/API_CreatePlatformApplication.html)`
+ `[CreatePlatformEndpoint](https://docs.aws.amazon.com/sns/latest/api/API_CreatePlatformEndpoint.html)`
+ `[CreateSMSSandboxPhoneNumber](https://docs.aws.amazon.com/sns/latest/api/API_CreateSMSSandboxPhoneNumber.html)`
+ `[CreateTopic](https://docs.aws.amazon.com/sns/latest/api/API_CreateTopic.html)`
+ `[DeleteEndpoint](https://docs.aws.amazon.com/sns/latest/api/API_DeleteEndpoint.html)`
+ `[DeletePlatformApplication](https://docs.aws.amazon.com/sns/latest/api/API_DeletePlatformApplication.html)`
+ `[DeleteSMSSandboxPhoneNumber](https://docs.aws.amazon.com/sns/latest/api/API_DeleteSMSSandboxPhoneNumber.html)`
+ `[DeleteTopic](https://docs.aws.amazon.com/sns/latest/api/API_DeleteTopic.html)`
+ `[GetDataProtectionPolicy](https://docs.aws.amazon.com/sns/latest/api/API_GetDataProtectionPolicy.html)`
+ `[GetEndpointAttributes](https://docs.aws.amazon.com/sns/latest/api/API_GetEndpointAttributes.html)`
+ `[GetPlatformApplicationAttributes](https://docs.aws.amazon.com/sns/latest/api/API_GetPlatformApplicationAttributes.html)`
+ `[GetSMSAttributes](https://docs.aws.amazon.com/sns/latest/api/API_GetSMSAttributes.html)`
+ `[GetSMSSandboxAccountStatus](https://docs.aws.amazon.com/sns/latest/api/API_GetSMSSandboxAccountStatus.html)`
+ `[GetSubscriptionAttributes](https://docs.aws.amazon.com/sns/latest/api/API_GetSubscriptionAttributes.html)`
+ `[GetTopicAttributes](https://docs.aws.amazon.com/sns/latest/api/API_GetTopicAttributes.html)`
+ `[ListEndpointsByPlatformApplication](https://docs.aws.amazon.com/sns/latest/api/API_ListEndpointsByPlatformApplication.html)`
+ `[ListOriginationNumbers](https://docs.aws.amazon.com/sns/latest/api/API_ListOriginationNumbers.html)`
+ `[ListPhoneNumbersOptedOut](https://docs.aws.amazon.com/sns/latest/api/API_ListPhoneNumbersOptedOut.html)`
+ `[ListPlatformApplications](https://docs.aws.amazon.com/sns/latest/api/API_ListPlatformApplications.html)`
+ `[ListSMSSandboxPhoneNumbers](https://docs.aws.amazon.com/sns/latest/api/API_ListSMSSandboxPhoneNumbers.html)`
+ `[ListSubscriptions](https://docs.aws.amazon.com/sns/latest/api/API_ListSubscriptions.html)`
+ `[ListSubscriptionsByTopic](https://docs.aws.amazon.com/sns/latest/api/API_ListSubscriptionsByTopic.html)`
+ `[ListTagsForResource](https://docs.aws.amazon.com/sns/latest/api/API_ListTagsForResource.html)`
+ `[ListTopics](https://docs.aws.amazon.com/sns/latest/api/API_ListTopics.html)`
+ `[OptInPhoneNumber](https://docs.aws.amazon.com/sns/latest/api/API_OptInPhoneNumber.html)`
+ `[PutDataProtectionPolicy](https://docs.aws.amazon.com/sns/latest/api/API_PutDataProtectionPolicy.html)`
+ `[RemovePermission](https://docs.aws.amazon.com/sns/latest/api/API_RemovePermission.html)`
+ `[SetEndpointAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetEndpointAttributes.html)`
+ `[SetPlatformApplicationAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetPlatformApplicationAttributes.html)`
+ `[SetSMSAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetSMSAttributes.html)`
+ `[SetSubscriptionAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetSubscriptionAttributes.html)`
+ `[SetTopicAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetTopicAttributes.html)`
+ `[Subscribe](https://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html)`
+ `[TagResource](https://docs.aws.amazon.com/sns/latest/api/API_TagResource.html)`
+ `[Unsubscribe](https://docs.aws.amazon.com/sns/latest/api/API_Unsubscribe.html)`
+ `[UntagResource](https://docs.aws.amazon.com/sns/latest/api/API_UntagResource.html)`
+ `[VerifySMSSandboxPhoneNumber](https://docs.aws.amazon.com/sns/latest/api/API_VerifySMSSandboxPhoneNumber.html)`

**Note**  
When you are not logged in to Amazon Web Services (unauthenticated mode) and either the [https://docs.aws.amazon.com/sns/latest/api/API_ConfirmSubscription.html](https://docs.aws.amazon.com/sns/latest/api/API_ConfirmSubscription.html) or [https://docs.aws.amazon.com/sns/latest/api/API_Unsubscribe.html](https://docs.aws.amazon.com/sns/latest/api/API_Unsubscribe.html) actions are invoked, then they will not be logged to CloudTrail. Such as, when you choose the provided link in an email notification to confirm a pending subscription to a topic, the `ConfirmSubscription` action is invoked in unauthenticated mode. In this example, the `ConfirmSubscription` action would not be logged to CloudTrail.

## SNS event examples
<a name="cloudtrail-event-examples"></a>

An event represents a single request from any source and includes information about the requested API operation, the date and time of the operation, request parameters, and so on. CloudTrail log files aren't an ordered stack trace of the public API calls, so events don't appear in any specific order.

The following example shows a CloudTrail event that demonstrates the **`ListTopics`**, `CreateTopic`, and `DeleteTopic` actions.

```
{
  "Records": [
    {
      "eventVersion": "1.02",
      "userIdentity": {
        "type": "IAMUser",
        "userName": "Bob",
        "principalId": "EX_PRINCIPAL_ID",
        "arn": "arn:aws:iam::123456789012:user/Bob",
        "accountId": "123456789012",
        "accessKeyId": "AKIAIOSFODNN7EXAMPLE"
      },
      "eventTime": "2014-09-30T00:00:00Z",
      "eventSource": "sns.amazonaws.com",
      "eventName": "ListTopics",
      "awsRegion": "us-west-2",
      "sourceIPAddress": "127.0.0.1",
      "userAgent": "aws-sdk-java/unknown-version",
      "requestParameters": {
        "nextToken": "ABCDEF1234567890EXAMPLE=="
      },
      "responseElements": null,
      "requestID": "example1-b9bb-50fa-abdb-80f274981d60",
      "eventID": "example0-09a3-47d6-a810-c5f9fd2534fe",
      "eventType": "AwsApiCall",
      "recipientAccountId": "123456789012"
    },
    {
      "eventVersion": "1.02",
      "userIdentity": {
        "type": "IAMUser",
        "userName": "Bob",
        "principalId": "EX_PRINCIPAL_ID",
        "arn": "arn:aws:iam::123456789012:user/Bob",
        "accountId": "123456789012",
        "accessKeyId": "AKIAIOSFODNN7EXAMPLE"
      },
      "eventTime": "2014-09-30T00:00:00Z",
      "eventSource": "sns.amazonaws.com",
      "eventName": "CreateTopic",
      "awsRegion": "us-west-2",
      "sourceIPAddress": "127.0.0.1",
      "userAgent": "aws-sdk-java/unknown-version",
      "requestParameters": {
        "name": "hello"
      },
      "responseElements": {
        "topicArn": "arn:aws:sns:us-west-2:123456789012:hello-topic"
      },
      "requestID": "example7-5cd3-5323-8a00-f1889011fee9",
      "eventID": "examplec-4f2f-4625-8378-130ac89660b1",
      "eventType": "AwsApiCall",
      "recipientAccountId": "123456789012"
    },
    {
      "eventVersion": "1.02",
      "userIdentity": {
        "type": "IAMUser",
        "userName": "Bob",
        "principalId": "EX_PRINCIPAL_ID",
        "arn": "arn:aws:iam::123456789012:user/Bob",
        "accountId": "123456789012",
        "accessKeyId": "AKIAIOSFODNN7EXAMPLE"
      },
      "eventTime": "2014-09-30T00:00:00Z",
      "eventSource": "sns.amazonaws.com",
      "eventName": "DeleteTopic",
      "awsRegion": "us-west-2",
      "sourceIPAddress": "127.0.0.1",
      "userAgent": "aws-sdk-java/unknown-version",
      "requestParameters": {
        "topicArn": "arn:aws:sns:us-west-2:123456789012:hello-topic"
      },
      "responseElements": null,
      "requestID": "example5-4faa-51d5-aab2-803a8294388d",
      "eventID": "example8-6443-4b4d-abfd-1b867280d964",
      "eventType": "AwsApiCall",
      "recipientAccountId": "123456789012"
    }
  ]
}
```

The following example shows a CloudTrail event that demonstrates the `Publish` action.

```
{
  "eventVersion": "1.09",
  "userIdentity": {
    "type": "AssumedRole",
    "principalId": "EX_PRINCIPAL_ID",
    "arn": "arn:aws:iam::123456789012:user/Bob",
    "accountId": "123456789012",
    "accessKeyId": "AKIAIOSFODNN7EXAMPLE",
    "sessionContext": {
      "sessionIssuer": {
        "type": "Role",
        "principalId": "AKIAIOSFODNN7EXAMPLE",
        "arn": "arn:aws:iam::123456789012:role/Admin",
        "accountId": "123456789012",
        "userName": "ExampleUser"
      },
      "attributes": {
        "creationDate": "2023-08-21T16:44:05Z",
        "mfaAuthenticated": "false"
      }
    }
  },
  "eventTime": "2023-08-21T16:48:37Z",
  "eventSource": "sns.amazonaws.com",
  "eventName": "Publish",
  "awsRegion": "us-east-1",
  "sourceIPAddress": "192.0.2.0",
  "userAgent": "aws-cli/1.29.16 md/Botocore#1.31.16 ua/2.0 os/linux#5.4.250-173.369.amzn2int.x86_64 md/arch#x86_64 lang/python#3.8.17 md/pyimpl#CPython cfg/retry-mode#legacy botocore/1.31.16",
  "requestParameters": {
    "topicArn": "arn:aws:sns:us-east-1:123456789012:ExampleSNSTopic",
    "message": "HIDDEN_DUE_TO_SECURITY_REASONS",
    "subject": "HIDDEN_DUE_TO_SECURITY_REASONS",
    "messageStructure": "json",
    "messageAttributes": "HIDDEN_DUE_TO_SECURITY_REASONS"
  },
  "responseElements": {
    "messageId": "0787cd1e-d92b-521c-a8b4-90434e8ef840"
  },
  "requestID": "0a8ab208-11bf-5e01-bd2d-ef55861b545d",
  "eventID": "bb3496d4-5252-4660-9c28-3c6aebdb21c0",
  "readOnly": false,
  "resources": [
    {
      "accountId": "123456789012",
      "type": "AWS::SNS::Topic",
      "ARN": "arn:aws:sns:us-east-1:123456789012:ExampleSNSTopic"
    }
  ],
  "eventType": "AwsApiCall",
  "managementEvent": false,
  "recipientAccountId": "123456789012",
  "eventCategory": "Data",
  "tlsDetails": {
    "tlsVersion": "TLSv1.2",
    "cipherSuite": "ECDHE-RSA-AES128-GCM-SHA256",
    "clientProvidedHostHeader": "sns.us-east-1.amazonaws.com"
  }
}
```

The following example shows a CloudTrail event that demonstrates the `PublishBatch` action.

```
{
  "eventVersion": "1.09",
  "userIdentity": {
    "type": "AssumedRole",
    "principalId": "EX_PRINCIPAL_ID",
    "arn": "arn:aws:iam::123456789012:user/Bob",
    "accountId": "123456789012",
    "accessKeyId": "AKIAIOSFODNN7EXAMPLE",
    "sessionContext": {
      "sessionIssuer": {
        "type": "Role",
        "principalId": "AKIAIOSFODNN7EXAMPLE",
        "arn": "arn:aws:iam::123456789012:role/Admin",
        "accountId": "123456789012",
        "userName": "ExampleUser"
      },
      "attributes": {
        "creationDate": "2023-08-21T19:20:49Z",
        "mfaAuthenticated": "false"
      }
    }
  },
  "eventTime": "2023-08-21T19:22:01Z",
  "eventSource": "sns.amazonaws.com",
  "eventName": "PublishBatch",
  "awsRegion": "us-east-1",
  "sourceIPAddress": "192.0.2.0",
  "userAgent": "aws-cli/1.29.16 md/Botocore#1.31.16 ua/2.0 os/linux#5.4.250-173.369.amzn2int.x86_64 md/arch#x86_64 lang/python#3.8.17 md/pyimpl#CPython cfg/retry-mode#legacy botocore/1.31.16",
  "requestParameters": {
    "topicArn": "arn:aws:sns:us-east-1:123456789012:ExampleSNSTopic",
    "publishBatchRequestEntries": [
      {
        "id": "1",
        "message": "HIDDEN_DUE_TO_SECURITY_REASONS"
      },
      {
        "id": "2",
        "message": "HIDDEN_DUE_TO_SECURITY_REASONS"
      }
    ]
  },
  "responseElements": {
    "successful": [
      {
        "id": "1",
        "messageId": "30d68101-a64a-5573-9e10-dc5c1dd3af2f"
      },
      {
        "id": "2",
        "messageId": "c0aa0c5c-561d-5455-b6c4-5101ed84de09"
      }
    ],
    "failed": []
  },
  "requestID": "e2cdf7f3-1b35-58ad-ac9e-aaaea0ace2f1",
  "eventID": "10da9a14-0154-4ab6-b3a5-1825b229a7ed",
  "readOnly": false,
  "resources": [
    {
      "accountId": "123456789012",
      "type": "AWS::SNS::Topic",
      "ARN": "arn:aws:sns:us-east-1:123456789012:ExampleSNSTopic"
    }
  ],
  "eventType": "AwsApiCall",
  "managementEvent": false,
  "recipientAccountId": "123456789012",
  "eventCategory": "Data",
  "tlsDetails": {
    "tlsVersion": "TLSv1.2",
    "cipherSuite": "ECDHE-RSA-AES128-GCM-SHA256",
    "clientProvidedHostHeader": "sns.us-east-1.amazonaws.com"
  }
}
```

For information about CloudTrail record contents, see [CloudTrail record contents](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-event-reference-record-contents.html) in the *AWS CloudTrail User Guide*.

# Monitoring Amazon SNS topics using CloudWatch
<a name="sns-monitoring-using-cloudwatch"></a>

Amazon SNS and Amazon CloudWatch are integrated so you can collect, view, and analyze metrics for every active Amazon SNS notification. Once you have configured CloudWatch for Amazon SNS, you can gain better insight into the performance of your Amazon SNS topics, push notifications, and SMS deliveries. For example, you can set an alarm to send you an email notification if a specified threshold is met for an Amazon SNS metric, such as `NumberOfNotificationsFailed`. For a list of all the metrics that Amazon SNS sends to CloudWatch, see [Amazon SNS metrics](#sns-metrics). For more information about Amazon SNS push notifications, see [Sending mobile push notifications with Amazon SNS](sns-mobile-application-as-subscriber.md). 

**Note**  
The metrics you configure with CloudWatch for your Amazon SNS topics are automatically collected and pushed to CloudWatch at *1-minute* intervals. These metrics are gathered on all topics that meet the CloudWatch guidelines for being active. A topic is considered active by CloudWatch for up to six hours from the last activity (that is, any API call) on the topic.   
There is no charge for the Amazon SNS metrics reported in CloudWatch; they are provided as part of the Amazon SNS service.

## View CloudWatch metrics for Amazon SNS
<a name="view-cloudwatch-metrics"></a>

You can monitor metrics for Amazon SNS using the CloudWatch console, CloudWatch's own command line interface (CLI), or programmatically using the CloudWatch API. The following procedures show you how to access the metrics using the AWS Management Console.

**To view metrics using the CloudWatch console**

1. Sign in to the [CloudWatch console](https://console.aws.amazon.com/cloudwatch).

1. On the navigation panel, choose **Metrics**.

1. On the **All metrics** tab, choose **SNS**, and then choose one of the following dimensions:
   + **Country, SMS Type**
   + **PhoneNumber**
   + **Topic Metrics**
   + **Metrics with no dimensions**

1. To view more detail, choose a specific item. For example, if you choose **Topic Metrics** and then choose **NumberOfMessagesPublished**, the average number of published Amazon SNS messages for a 1-minute period throughout the time range of 6 hours is displayed.

1. To view Amazon SNS usage metrics, on the **All metrics** tab, choose **Usage**, and select the **target Amazon SNS usage metric** (for example, `NumberOfMessagesPublishedPerAccount`).

## Set CloudWatch alarms for Amazon SNS metrics
<a name="SNS_AlarmMetrics"></a>

CloudWatch also allows you to set alarms when a threshold is met for a metric. For example, you could set an alarm for the metric, **NumberOfNotificationsFailed**, so that when your specified threshold number is met within the sampling period, then an email notification would be sent to inform you of the event.

**To set alarms using the CloudWatch console**

1. Sign in to the AWS Management Console and open the CloudWatch console at [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/).

1.  Choose **Alarms**, and then choose the **Create Alarm** button. This launches the **Create Alarm** wizard. 

1.  Scroll through the Amazon SNS metrics to locate the metric you want to place an alarm on. Select the metric to create an alarm on and choose **Continue**. 

1. Fill in the **Name**, **Description**, **Threshold**, and **Time** values for the metric, and then choose **Continue**. 

1. Choose **Alarm** as the alarm state. If you want CloudWatch to send you an email when the alarm state is reached, choose either an existing Amazon SNS topic or choose **Create New Email Topic**. If you choose **Create New Email Topic**, you can set the name and email addresses for a new topic. This list will be saved and appear in the drop-down box for future alarms. Choose **Continue**. 
**Note**  
If you use **Create New Email Topic** to create a new Amazon SNS topic, the email addresses must be verified before they will receive notifications. Emails are sent only when the alarm enters an alarm state. If this alarm state change happens before the email addresses are verified, they will not receive a notification. 

1. At this point, the **Create Alarm** wizard gives you a chance to review the alarm you’re about to create. If you need to make any changes, you can use the **Edit** links on the right. Once you are satisfied, choose **Create Alarm**. 

For more information about using CloudWatch and alarms, see the [CloudWatch Documentation](https://aws.amazon.com/documentation/cloudwatch).

## Amazon SNS metrics
<a name="sns-metrics"></a>

Amazon SNS sends the following metrics to CloudWatch.


| Namespace | Metric | Description | 
| --- | --- | --- | 
| AWS/SNS |  NumberOfMessagesPublished  |  The number of messages published to your Amazon SNS topics. **Units:** Count **Valid dimensions:** Application, PhoneNumber, Platform, and TopicName **Valid statistics:** Sum  | 
| AWS/SNS |  NumberOfNotificationsDelivered  |  The number of messages successfully delivered from your Amazon SNS topics to subscribing endpoints. For a delivery attempt to succeed, the endpoint's subscription must accept the message. A subscription accepts a message if a.) it lacks a filter policy or b.) its filter policy includes attributes that match those assigned to the message. If the subscription rejects the message, the delivery attempt isn't counted for this metric. **Units:** Count **Valid dimensions:** Application, PhoneNumber, Platform, and TopicName **Valid statistics:** Sum  | 
| AWS/SNS |  NumberOfNotificationsFailed  |  The number of messages that Amazon SNS failed to deliver.  For Amazon SQS, email, SMS, or mobile push endpoints, the metric increments by 1 when Amazon SNS stops attempting message deliveries. For HTTP or HTTPS endpoints, the metric includes every failed delivery attempt, including retries that follow the initial attempt. For all other endpoints, the count increases by 1 when the message fails to deliver (regardless of the number of attempts). This metric does not include messages that were rejected by subscription filter policies. You can control the number of retries for HTTP endpoints. For more information, see [Amazon SNS message delivery retries](sns-message-delivery-retries.md). **Units:** Count **Valid dimensions:** Application, PhoneNumber, Platform, and TopicName **Valid statistics:** Sum, Average  | 
| AWS/SNS | NumberOfNotificationsFilteredOut |  The number of messages that were rejected by subscription filter policies. A filter policy rejects a message when the message attributes don't match the policy attributes. **Units:** Count **Valid dimensions:** Application, PhoneNumber, Platform, and TopicName **Valid statistics:** Sum, Average  | 
| AWS/SNS | NumberOfNotificationsFilteredOut-MessageAttributes | The number of messages that were rejected by subscription filter policies for attribute-based filtering. **Units:** Count **Valid dimensions:** Application, PhoneNumber, Platform, and TopicName **Valid statistics:** Sum, Average  | 
| AWS/SNS | NumberOfNotificationsFilteredOut-MessageBody |  The number of messages that were rejected by subscription filter policies for payload-based filtering.  **Units:** Count **Valid dimensions:** Application, PhoneNumber, Platform, and TopicName **Valid statistics:** Sum, Average  | 
| AWS/SNS | NumberOfNotificationsFilteredOut-InvalidAttributes |  The number of messages that were rejected by subscription filter policies because the messages' attributes are invalid – for example, because the attribute JSON is incorrectly formatted. **Units:** Count **Valid dimensions:** Application, PhoneNumber, Platform, and TopicName **Valid statistics:** Sum, Average  | 
| AWS/SNS | NumberOfNotificationsFilteredOut-NoMessageAttributes |  The number of messages that were rejected by subscription filter policies because the messages have no attributes. **Units:** Count **Valid dimensions:** Application, PhoneNumber, Platform, and TopicName **Valid statistics:** Sum, Average  | 
| AWS/SNS | NumberOfNotificationsFilteredOut-InvalidMessageBody |  The number of messages that were rejected by subscription filter policies because the message body is invalid for filtering – for example, invalid JSON message body. **Units:** Count **Valid dimensions:** Application, PhoneNumber, Platform, and TopicName **Valid statistics:** Sum, Average  | 
| AWS/SNS |  NumberOfNotificationsRedrivenToDlq  |  The number of messages that have been moved to a dead-letter queue. **Units: **Count **Valid dimensions:** Application, PhoneNumber, Platform, and TopicName **Valid statistics:** Sum, Average | 
| AWS/SNS |  NumberOfNotificationsFailedToRedriveToDlq  |  The number of messages that couldn't be moved to a dead-letter queue. **Units:** Count **Valid dimensions:** Application, PhoneNumber, Platform, and TopicName **Valid statistics:** Sum, Average | 
| AWS/SNS |  PublishSize  |  The size of messages published. **Units:** Bytes **Valid dimensions:** Application, PhoneNumber, Platform, and TopicName **Valid statistics:** Minimum, Maximum, Average and Count  | 
| AWS/SNS | SMSMonthToDateSpentUSD |  The charges you have accrued since the start of the current calendar month for sending SMS messages. You can set an alarm for this metric to know when your month-to-date charges are close to the monthly SMS spend quota for your account. When Amazon SNS determines that sending an SMS message would incur a cost that exceeds this quota, it stops publishing SMS messages within minutes. For information about setting your monthly SMS spend quota, or for information about requesting a spend quota increase with AWS, see [Setting SMS messaging preferences in Amazon SNS](sms_preferences.md). **Units:** USD **Valid dimensions:** None **Valid statistics:** Sum  | 
| AWS/SNS |  SMSSuccessRate  |  The rate of successful SMS message deliveries. **Units:** Count **Valid dimensions:** PhoneNumber **Valid statistics:** Sum, Average, Data Samples  | 

## Dimensions for Amazon SNS metrics
<a name="sns-metric-dimensions"></a>

Amazon Simple Notification Service sends the following dimensions to CloudWatch.


|  Dimension  |  Description  | 
| --- | --- | 
|  Application  |  Filters on application objects, which represent an app and device registered with one of the supported push notification services, such as APNs and FCM.  | 
|  Application,Platform  |  Filters on application and platform objects, where the platform objects are for the supported push notification services, such as APNs and FCM.  | 
| Country |  Filters on the destination country or region of an SMS message. The country or region is represented by its ISO 3166-1 alpha-2 code.  | 
|  PhoneNumber  |  Filters on the phone number when you publish SMS directly to a phone number (without a topic).  | 
|  Platform  |  Filters on platform objects for the push notification services, such as APNs and FCM.  | 
|  TopicName  |  Filters on Amazon SNS topic names.  | 
| SMSType |  Filters on the message type of SMS message. Can be *promotional* or *transactional*.  | 

## Amazon SNS usage metrics
<a name="sns-usage-metrics"></a>

Amazon Simple Notification Service sends the following usage metrics to CloudWatch.


|  Namespace  |  Service  | Metric | Resource | Type | Description | 
| --- | --- | --- | --- | --- | --- | 
| AWS/Usage | SNS | ResourceCount | NumberOfMessagesPublishedPerAccount | Resource |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/sns/latest/dg/sns-monitoring-using-cloudwatch.html)  | 
| AWS/Usage | SNS | ResourceCount | ApproximateNumberOfTopics | Resource |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/sns/latest/dg/sns-monitoring-using-cloudwatch.html)  | 
| AWS/Usage | SNS | ResourceCount | ApproximateNumberOfFilterPolicies | Resource |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/sns/latest/dg/sns-monitoring-using-cloudwatch.html)  | 
| AWS/Usage | SNS | ResourceCount | ApproximateNumberOfPendingSubscriptions | Resource |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/sns/latest/dg/sns-monitoring-using-cloudwatch.html)  | 
| AWS/Usage | SNS | CallCount |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/sns/latest/dg/sns-monitoring-using-cloudwatch.html)  | API |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/sns/latest/dg/sns-monitoring-using-cloudwatch.html)  | 

# Compliance validation for Amazon SNS
<a name="compliance-validation"></a>

To learn whether an AWS service is within the scope of specific compliance programs, see [AWS services in Scope by Compliance Program](https://aws.amazon.com/compliance/services-in-scope/) and choose the compliance program that you are interested in. For general information, see [AWS Compliance Programs](https://aws.amazon.com/compliance/programs/).

You can download third-party audit reports using AWS Artifact. For more information, see [Downloading Reports in AWS Artifact](https://docs.aws.amazon.com/artifact/latest/ug/downloading-documents.html).

Your compliance responsibility when using AWS services is determined by the sensitivity of your data, your company's compliance objectives, and applicable laws and regulations. For more information about your compliance responsibility when using AWS services, see [AWS Security Documentation](https://docs.aws.amazon.com/security/).

# Resilience in Amazon SNS
<a name="disaster-recovery-resiliency"></a>

Resilience in Amazon SNS is ensured through leveraging the AWS global infrastructure, which revolves around AWS Regions and Availability Zones. AWS Regions offer physically separated and isolated Availability Zones connected by low-latency, high-throughput, and highly redundant networking. This architecture allows for seamless failover between Availability Zones without interruption, making applications and databases inherently more fault tolerant and scalable compared to traditional data center infrastructures. By using Availability Zones, Amazon SNS subscribers benefit from enhanced availability and reliability, guaranteeing message delivery despite potential disruptions. For more information about AWS Regions and Availability Zones, see [AWS Global Infrastructure](https://aws.amazon.com/about-aws/global-infrastructure/).

Additionally, subscriptions to Amazon SNS topics can be configured with delivery retries and dead-letter queues, enabling automatic handling of transient failures and ensuring messages reliably reach their intended destinations. 

Amazon SNS also supports message filtering and message attributes, which lets you tailor resilience strategies to their specific use cases, enhancing the overall robustness of your applications.

# Infrastructure security in Amazon SNS
<a name="infrastructure-security"></a>

As a managed service, Amazon SNS is protected by the AWS global network security procedures found in the [Best Practices for Security, Identity, & Compliance](https://aws.amazon.com/architecture/security-identity-compliance) documentation.

Use AWS API actions to access Amazon SNS through the network. Clients must support Transport Layer Security (TLS) 1.2 or later. Clients must also support cipher suites with Perfect Forward Secrecy (PFS), such as Ephemeral Diffie-Hellman (DHE) or Elliptic Curve Ephemeral Diffie-Hellman (ECDHE).

You must sign requests using both an access key ID and a secret access key associated with an IAM principal. Alternatively, you can use the [AWS Security Token Service](https://docs.aws.amazon.com/STS/latest/APIReference/Welcome.html) (AWS STS) to generate temporary security credentials for signing requests.

You can call these API actions from any network location, but Amazon SNS supports resource-based access policies, which can include restrictions based on the source IP address. You can also use Amazon SNS policies to control access from specific Amazon VPC endpoints or specific VPCs. This effectively isolates network access to a given Amazon SNS topic from only the specific VPC within the AWS network. For more information, see [Restrict publication to an Amazon SNS topic only from a specific VPC endpoint](sns-access-policy-use-cases.md#sns-restrict-publication-only-from-specified-vpc-endpoint).

# Amazon SNS security best practices
<a name="sns-security-best-practices"></a>

AWS provides many security features for Amazon SNS. Review these security features in the context of your own security policy.

**Note**  
The guidance for these security features applies to common use cases and implementations. We recommend that you review these best practices in the context of your specific use case, architecture, and threat model.

## Preventative best practices
<a name="preventative-best-practices"></a>

The following are preventative security best practices for Amazon SNS.

**Topics**
+ [

### Ensure topics aren't publicly accessible
](#ensure-topics-not-publicly-accessible)
+ [

### Implement least-privilege access
](#implement-least-privilege-access)
+ [

### Use IAM roles for applications and AWS services which require Amazon SNS access
](#use-iam-roles-for-applications-aws-services-which-require-access)
+ [

### Implement server-side encryption
](#implement-server-side-encryption)
+ [

### Enforce encryption of data in transit
](#enforce-encryption-data-in-transit)
+ [

### Consider using VPC endpoints to access Amazon SNS
](#consider-using-vpc-endpoints-access-sns)
+ [

### Ensure subscriptions are not configured to deliver to raw http endpoints
](#http-subscription-configuration)
+ [

### Enforce authentication on unsubscribe
](#enforce-authentication-on-unsubscribe)

### Ensure topics aren't publicly accessible
<a name="ensure-topics-not-publicly-accessible"></a>

Unless you explicitly require anyone on the internet to be able to read or write to your Amazon SNS topic, you should ensure that your topic isn't publicly accessible (accessible by everyone in the world or by any authenticated AWS user).
+ Avoid creating policies with `Principal` set to `""`.
+ Avoid using a wildcard (`*`). Instead, name a specific user or users.

### Implement least-privilege access
<a name="implement-least-privilege-access"></a>

When you grant permissions, you decide who receives them, which topics the permissions are for, and specific API actions that you want to allow for these topics. Implementing the principle of least privilege is important to reducing security risks. It also helps to reduce the negative effect of errors or malicious intent.

Follow the standard security advice of granting least privilege. That is, grant only the permissions required to perform a specific task. You can implement least privilege by using a combination of security policies pertaining to user access.

Amazon SNS uses the publisher-subscriber model, requiring three types of user account access:
+ **Administrators** – Access to creating, modifying, and deleting topics. Administrators also control topic policies.
+ **Publishers** – Access to sending messages to topics.
+ **Subscribers** – Access to subscribing to topics.

For more information, see the following sections:
+ [Identity and access management in Amazon SNS](security-iam.md)
+ [Amazon SNS API permissions: Actions and resources reference](sns-access-policy-language-api-permissions-reference.md)

### Use IAM roles for applications and AWS services which require Amazon SNS access
<a name="use-iam-roles-for-applications-aws-services-which-require-access"></a>

For applications or AWS services, such as Amazon EC2, to access Amazon SNS topics, they must use valid AWS credentials in their AWS API requests. Because these credentials aren't rotated automatically, you shouldn't store AWS credentials directly in the application or EC2 instance.

You should use an IAM role to manage temporary credentials for applications or services that need to access Amazon SNS. When you use a role, you don't need to distribute long-term credentials (such as a username, password, and access keys) to an EC2 instance or AWS service, such as AWS Lambda. Instead, the role supplies temporary permissions that applications can use when they make calls to other AWS resources.

For more information, see [IAM Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) and [Common Scenarios for Roles: Users, Applications, and Services](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios.html) in the *IAM User Guide*.

### Implement server-side encryption
<a name="implement-server-side-encryption"></a>

To mitigate data leakage issues, use encryption at rest to encrypt your messages using a key stored in a different location from the location that stores your messages. Server-side encryption (SSE) provides data encryption at rest. Amazon SNS encrypts your data at the message level when it stores it, and decrypts the messages for you when you access them. SSE uses keys managed in AWS Key Management Service. When you authenticate your request and have access permissions, there is no difference between accessing encrypted and unencrypted topics.

For more information, see [Securing Amazon SNS data with server-side encryption](sns-server-side-encryption.md) and [Managing Amazon SNS encryption keys and costs](sns-key-management.md).

### Enforce encryption of data in transit
<a name="enforce-encryption-data-in-transit"></a>

It's possible, but not recommended, to publish messages that are not encrypted during transit by using HTTP. However, when a topic is encrypted at rest using AWS KMS, it is required to use HTTPS for publishing messages to ensure encryption both at rest and in transit. While the topic does not automatically reject HTTP messages, using HTTPS is necessary to maintain the security standards.

AWS recommends that you use HTTPS instead of HTTP. When you use HTTPS, messages are automatically encrypted during transit, even if the SNS topic itself isn't encrypted. Without HTTPS, a network-based attacker can eavesdrop on network traffic or manipulate it using an attack such as man-in-the-middle.

To enforce only encrypted connections over HTTPS, add the [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Boolean](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Boolean) condition in the IAM policy that's attached to unencrypted SNS topics. This forces message publishers to use HTTPS instead of HTTP. You can use the following example policy as a guide:

------
#### [ JSON ]

****  

```
{
    "Id": "ExamplePolicy",
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowPublishThroughSSLOnly",
            "Action": "SNS:Publish",
            "Effect": "Deny",
            "Resource": [
                "arn:aws:sns:us-east-1:111122223333:test-topic"
            ],
            "Condition": {
                "Bool": {
                    "aws:SecureTransport": "false"
                }
            },
            "Principal": "*"
        }
    ]
}
```

------

### Consider using VPC endpoints to access Amazon SNS
<a name="consider-using-vpc-endpoints-access-sns"></a>

If you have topics that you must be able to interact with, but these topics must absolutely not be exposed to the internet, use VPC endpoints to limit topic access to only the hosts within a particular VPC. You can use topic policies to control access to topics from specific Amazon VPC endpoints or from specific VPCs.

Amazon SNS VPC endpoints provide two ways to control access to your messages:
+ You can control the requests, users, or groups that are allowed through a specific VPC endpoint.
+ You can control which VPCs or VPC endpoints have access to your topic using a topic policy.

For more information, see [Creating the endpoint](sns-vpc-create-endpoint.md#sns-vpc-endpoint-create) and [Creating an Amazon VPC endpoint policy for Amazon SNS](sns-vpc-endpoint-policy.md).

### Ensure subscriptions are not configured to deliver to raw http endpoints
<a name="http-subscription-configuration"></a>

Avoid configuring subscriptions to deliver to a raw http endpoints. Always have subscriptions delivering to an endpoint domain name. For example, a subscription configured to deliver to an endpoint, `http://1.2.3.4/my-path`, should be changed to `http://my.domain.name/my-path`.

### Enforce authentication on unsubscribe
<a name="enforce-authentication-on-unsubscribe"></a>

 Unless you are required to allow unauthenticated unsubscribe, like in cases of easy unsubscribe for email or SMS, you must enforce authentication for unsubscribing from a topic. This is in alignment with the [ least-privilege access control recommendation ](#implement-least-privilege-access). 

 You can set `AuthenticateOnUnsubscribe` to `True` while confirming a subscription. Failing to set the `AuthenticateOnUnsubscribe` flag to `True` when confirming a Amazon SNS subscription, can cause unsubscribe requests to succeed, even if they are unauthenticated. For more information, see Amazon SNS API reference for [ConfirmSubscription](https://docs.aws.amazon.com/sns/latest/api/API_ConfirmSubscription.html), or the [ Python example in the Amazon Q Detector Library](https://docs.aws.amazon.com/codeguru/detector-library/python/sns-unauthenticated-unsubscribe/). 

 For example, to confirm an email subscription using AWS CLI, copy the link from “Confirm Subscription” text in the email notification. That URL will give you required information to call the below AWS CLI command. 

```
aws sns confirm-subscription --region us-west-2 \
    --topic-arn sns-topic-arn \
    --token token-from-subscribe-notification \
    --authenticate-on-unsubscribe true
```

 Where: 
+  aws-region is the AWS Region that the topic is located in. This is also available in the topic ARN. 
+  sns-topic-arn is the ARN of the topic. This is the text after “TopicArn=” and before “&Token” in the confirm subscription URL. 
+  token-from-subscribe-notification is the UUID string after “Token=” and before “&Endpoint” in the confirm subscription URL. 

 The following is an example URL: 

```
        https://sns.us-west-2.amazonaws.com/confirmation.html?TopicArn=arn:aws:sns:us-west-2:123456789012:sns-topic&Token=a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1&Endpoint=email@address.com
```