AWS - SNS

Amazon Web Services Simple Notification Service (SNS).

IT Services · AWS - SNS

Details

IDAWS - SNS
ProviderAmazon
CategoryIT Services
From Version6.5.0
Docker Imagedemisto/boto3py3:1.0.0.10221838
Supported ModulesAgentix XSIAM

README

Amazon Web Services Simple Notification Service (SNS)

For more information regarding the AWS SNS service, please visit the official documentation found here.

For detailed instructions about setting up authentication, see: AWS Integrations - Authentication.

Configure AWS - SNS in Cortex

Parameter Description Required
AWS Default Region   True
Role Arn When using Access Key and Secret Key, there is no need to use Role Arn False
Role Session Name   False
Access Key   True
Secret Key   True
Role Session Duration   False
Timeout The time in seconds till a timeout exception is reached. You can specify just the read timeout (for example 60) or also the connect timeout followed after a comma (for example 60,10). If a connect timeout is not specified, a default of 10 second will be used. False
Retries The maximum number of retry attempts when connection or throttling errors are encountered. Set to 0 to disable retries. The default value is 5 and the limit is 10. Note: Increasing the number of retries will increase the execution time. False
AWS STS Regional Endpoints Sets the AWS_STS_REGIONAL_ENDPOINTS environment variable to specify the AWS STS endpoint resolution logic. By default, this option is set to “legacy” in AWS. Leave empty if the environment variable is already set using server configuration. False
Use system proxy settings   False
Trust any certificate (not secure)   False

Commands

You can execute these commands from the CLI, as part of an automation, or in a playbook.
After you successfully execute a command, a DBot message appears in the War Room with the command details.

aws-sns-create-subscription


Subscribes an endpoint to an Amazon SNS topic. If the endpoint type is HTTP/S or email, or if the endpoint and the topic are not in the same Amazon Web Services account, the endpoint owner must run the ConfirmSubscription action to confirm the subscription.

Base Command

aws-sns-create-subscription

Input

Argument Name Description Required
topicArn The ARN of the topic you want to subscribe to. Required
protocol The protocol that you want to use. Possible values are: http, https, email, email-json, sms, sqs, application, lambda, firehose. Required
endpoint The endpoint that you want to receive notifications. Optional
returnSubscriptionArn Sets whether the response from the Subscribe request includes the subscription ARN, even if the subscription is not yet confirmed. Possible values are: True, False. Optional
deliveryPolicy The policy that defines how Amazon SNS retries failed deliveries to HTTP/S endpoints. Optional
filterPolicy The simple JSON object that lets your subscriber receive only a subset of messages, rather than receiving every message published to the topic. Optional
rawMessageDelivery When set to true , enables raw message delivery to Amazon SQS or HTTP/S endpoints. Possible values are: True, False. Optional
redrivePolicy When specified, sends undeliverable messages to the specified Amazon SQS dead-letter queue. Optional
subscriptionRoleArn The ARN of the IAM role that has the following: 1. Permission to write to the Kinesis Data Firehose delivery stream 2. Amazon SNS listed as a trusted entity. Optional
region The AWS Region, if not specified the default region will be used. Optional
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

Path Type Description
AWS.SNS.Subscriptions.SubscriptionArn string The Subscription Arn

Command Example


#### Human Readable Output

### aws-sns-list-topics

***
Returns a list of the requester's topics.

#### Base Command

`aws-sns-list-topics`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| nextToken | Token returned by the previous ListTopics request. | Optional |
| region | The AWS Region, if not specified the default region will be used. | Optional |
| roleArn | The Amazon Resource Name (ARN) of the role to assume. | Optional |
| roleSessionName | An identifier for the assumed role session. | Optional |
| roleSessionDuration | The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. | Optional |

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| AWS.SNS.Topics.TopicArn | string | The Topic ARN |

#### Command Example

Human Readable Output

aws-sns-send-message


Sends a message to an Amazon SNS topic, a text message (SMS message) directly to a phone number, or a message to a mobile platform endpoint (when you specify the TargetArn ).

Base Command

aws-sns-send-message

Input

Argument Name Description Required
topicArn The topic you want to publish to. If you don’t specify a value for the TopicArn parameter, you must specify a value for the PhoneNumber or TargetArn parameters. Optional
targetArn If you don’t specify a value for the TargetArn parameter, you must specify a value for the PhoneNumber or TopicArn parameters. Optional
phoneNumber The phone number to which you want to deliver an SMS message. Use E.164 format. Optional
message The message you want to send. Required
subject Optional parameter to be used as the “Subject” line when the message is delivered to email endpoints. Optional
messageStructure Set MessageStructure to json if you want to send a different message for each protocol. Optional
messageDeduplicationId This parameter applies only to FIFO (first-in-first-out) topics. Optional
messageGroupId This parameter applies only to FIFO (first-in-first-out) topics. Optional
region The AWS Region, if not specified the default region will be used. Optional
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

Path Type Description
AWS.SNS.SentMessages string Unique identifier assigned to the published message.

Command Example


#### Human Readable Output

### aws-sns-create-topic

***
Creates a new a topic to which notifications can be published. You can specify the attribute to create FIFO topic.

#### Base Command

`aws-sns-create-topic`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| topicName | The name of the new topic. | Required |
| deliveryPolicy | The policy that defines how Amazon SNS retries failed deliveries to HTTP/S endpoints. | Optional |
| displayName | The display name to use for a topic with SMS subscriptions. | Optional |
| fifoTopic | Set to true to create a FIFO topic. Possible values are: true, false. | Optional |
| policy | The policy that defines who can access your topic. By default, only the topic owner can publish or subscribe to the topic. | Optional |
| kmsMasterKeyId | The ID of an Amazon Web Services managed customer master key (CMK) for Amazon SNS or a custom CMK. | Optional |
| contentBasedDeduplication | Enables content-based deduplication. Possible values are: True, False. | Optional |
| region | The AWS Region, if not specified the default region will be used. | Optional |
| roleArn | The Amazon Resource Name (ARN) of the role to assume. | Optional |
| roleSessionName | An identifier for the assumed role session. | Optional |
| roleSessionDuration | The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. | Optional |

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| AWS.SNS.Topic.TopicArn | unknown | The ARN of the created Amazon SNS topic. |

#### Command Example

Human Readable Output

aws-sns-delete-topic


Deletes a topic and all its subscriptions.

Base Command

aws-sns-delete-topic

Input

Argument Name Description Required
topicArn The ARN of the topic you want to delete. Required
region The AWS Region, if not specified the default region will be used. Optional
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

There is no context output for this command.

Command Example


#### Human Readable Output

### aws-sns-list-subscriptions-by-topic

***
Returns a list of the subscriptions to a specific topic. Each call returns a limited list of subscriptions, up to 100.

#### Base Command

`aws-sns-list-subscriptions-by-topic`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| topicArn | The ARN of the topic for which you wish to find subscriptions. | Required |
| nextToken | Token returned by the previous ListTopics request. | Optional |
| region | The AWS Region, if not specified the default region will be used. | Optional |
| roleArn | The Amazon Resource Name (ARN) of the role to assume. | Optional |
| roleSessionName | An identifier for the assumed role session. | Optional |
| roleSessionDuration | The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. | Optional |

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| AWS.SNS.Subscriptions.SubscriptionArn | unknown | The Subscription Arn |

#### Command Example

Human Readable Output

Configuration parameters

  • defaultRegion — AWS Default Region (required)
  • roleArn — Role Arn
  • roleSessionName — Role Session Name
  • credentials — Access Key (required)
  • sessionDuration — Role Session Duration
  • timeout — Timeout
  • retries — Retries
  • sts_regional_endpoint — AWS STS Regional Endpoints
  • proxy — Use system proxy settings
  • insecure — Trust any certificate (not secure)

Commands (6)

  • aws-sns-create-subscription

    Subscribes an endpoint to an Amazon SNS topic. If the endpoint type is HTTP/S or email, or if the endpoint and the topic are not in the same Amazon Web Services account, the endpoint owner must run the ConfirmSubscription action to confirm the subscription.

  • aws-sns-create-topic

    Creates a new a topic to which notifications can be published. You can specify the attribute to create FIFO topic.

  • aws-sns-delete-topic

    Deletes a topic and all its subscriptions.

  • aws-sns-list-subscriptions-by-topic

    Returns a list of the subscriptions to a specific topic. Each call returns a limited list of subscriptions, up to 100.

  • aws-sns-list-topics

    Returns a list of the requester's topics.

  • aws-sns-send-message

    Sends a message to an Amazon SNS topic, a text message (SMS message) directly to a phone number, or a message to a mobile platform endpoint (when you specify the TargetArn ).

import pytest
from AWSSNS import create_subscription, create_topic, delete_topic, list_subscriptions_by_topic, list_topics, send_message


@pytest.fixture
def mock_tableToMarkdown(mocker):
    return mocker.patch("AWSSNS.tableToMarkdown")


@pytest.fixture
def sns_client(mocker):
    return mocker.Mock()


def test_create_subscription_success(sns_client):
    """
    Given a mocked SNS clien
    When create_subscription is called with valid args
    Then check the client called subscribe with expected args
    """
    args = {
        "topicArn": "topic",
        "protocol": "https",
        "returnSubscriptionArn": "true",
        "deliveryPolicy": "test_delivery",
        "filterPolicy": "test_filter",
        "rawMessageDelivery": "true",
        "redrivePolicy": "test_redrive",
        "subscriptionRoleArn": "test_role",
    }
    sns_client.subscribe.side_effect = [{"SubscriptionArn": "test_arn"}]
    result = create_subscription(args, sns_client)
    assert result["EntryContext"]["AWS.SNS.Subscriptions"] == {"SubscriptionArn": "test_arn"}


def test_send_message_success(sns_client):
    """
    Given a mocked SNS client
    When send_message is called with valid args
    Then send_message should call the correct SNS client methods
    """
    args = {
        "message": "hello",
        "topicArn": "topic123",
        "targetArn": "target123",
        "phoneNumber": "1234567890",
        "subject": "test_subject",
        "messageStructure": "test_structure",
        "messageDeduplicationId": "test_msg_app_ip",
        "messageGroupId": "test_msg_group_id",
    }
    sns_client.publish.side_effect = [{"MessageId": "test_msg_id"}]
    result = send_message(args, sns_client)
    assert result["EntryContext"]["AWS.SNS.SentMessages"][0] == {"MessageId": "test_msg_id"}


def test_send_message_failure(sns_client):
    """
    Given a mocked SNS client configured to raise an exception
    When send_message is called
    Then an error message should return
    """
    sns_client.publish.side_effect = Exception("Error!")

    send_message_res = send_message({}, sns_client)

    assert send_message_res["Contents"] == "Error!"


def test_create_topic_success(sns_client):
    """
    Given a mocked SNS client
    When create_topic is called with a valid topic name
    Then the create_topic method should call create_topic on the client with the correct args
    """
    topic_name = "test_topic"
    args = {
        "topicName": topic_name,
        "deliveryPolicy": "test_delivery",
        "displayName": "test_display",
        "fifoTopic": "true",
        "policy": "test_policy",
        "kmsMasterKeyId": "test_kms",
        "contentBasedDeduplication": "true",
    }
    sns_client.create_topic.side_effect = [{"TopicArn": topic_name}]
    result = create_topic(args, sns_client)
    assert result["EntryContext"] == {"AWS.SNS.Topic": {"ARN": topic_name}}


def test_create_topic_failure(sns_client):
    """
    Given a mocked SNS client configured to raise an exception
    When create_topic is called
    Then an error message should return
    """
    sns_client.create_topic.side_effect = Exception("Error creating topic")
    args = {"topicName": "test_topic"}
    result = create_topic(args, sns_client)
    assert result["Contents"] == "Error creating topic"


def test_delete_topic_success(sns_client):
    """
    Given a mocked SNS client
    When delete_topic is called with a valid topic ARN
    Then delete_topic should call delete_topic on the client
    """
    topic_arn = {"topicArn": "topic_arn"}
    response = {"ResponseMetadata": {"HTTPStatusCode": 200}}
    sns_client.delete_topic.side_effect = [response]
    result = delete_topic(topic_arn, sns_client)
    assert result == "The Topic has been deleted"
    sns_client.delete_topic.assert_called_with(TopicArn="topic_arn")


def test_delete_topic_invalid_arn(sns_client):
    """
    Given a mocked SNS client
    When delete_topic is called with an invalid ARN and throws exception
    Then delete_topic should return an error with the exception message
    """
    invalid_arn = {"topicArn": "invalidarn"}
    sns_client.delete_topic.side_effect = [Exception("Invalid ARN")]

    result = delete_topic(invalid_arn, sns_client)
    assert result["Contents"] == "Invalid ARN"


def test_list_subscriptions_by_topic_with_topic_arn(sns_client):
    """
    Given a mock SNS client
    When list_subscriptions_by_topic is called with a topic ARN
    Then the client's list_subscriptions_by_topic method is called with the topic ARN
    """
    topic_arn = "arn:aws:sns:us-east-1:123456789012:some-topic"
    sns_client.list_subscriptions_by_topic.side_effect = [{"Subscriptions": [{"SubscriptionArn": "sub_arn"}]}]
    result = list_subscriptions_by_topic({"topicArn": topic_arn}, sns_client)
    assert result["EntryContext"]["AWS.SNS.Subscriptions"] == [{"SubscriptionArn": "sub_arn"}]
    sns_client.list_subscriptions_by_topic.assert_called_with(TopicArn=topic_arn)


def test_list_subscriptions_by_topic_with_next_token(sns_client):
    """
    Given a mock SNS client
    When list_subscriptions_by_topic is called with a next token
    Then the client's list_subscriptions_by_topic method is called with the next token
    """
    next_token = "some-token"
    sns_client.list_subscriptions_by_topic.side_effect = [{"Subscriptions": [{"SubscriptionArn": next_token}]}]
    result = list_subscriptions_by_topic({"nextToken": next_token}, sns_client)
    assert result["EntryContext"]["AWS.SNS.Subscriptions"] == [{"SubscriptionArn": next_token}]
    sns_client.list_subscriptions_by_topic.assert_called_with(NextToken=next_token)


def test_list_subscriptions_by_topic_with_no_args(sns_client):
    """
    Given a mock SNS client
    When list_subscriptions_by_topic is called without arguments
    Then the client's list_subscriptions_by_topic method is called without arguments
    """
    list_subscriptions_by_topic({}, sns_client)
    sns_client.list_subscriptions_by_topic.assert_called_with()


def test_list_topics_success(sns_client):
    """
    Given a mocked SNS client
    When list_topics is called with the client
    Then return a list of topic ARNs
    """
    sns_client.list_topics.return_value = {"Topics": ["topic1"]}

    result = list_topics({}, sns_client)

    assert result["EntryContext"]["AWS.SNS.Topics"][0]["TopicArn"] == "topic1"


def test_list_topics_with_next_token(sns_client):
    """
    Given a mocked SNS client
    When list_topics is called with a nextToken
    Then return a list of topic ARNs
    """
    sns_client.list_topics.return_value = {"Topics": ["topic2"]}

    args = {"nextToken": "token123"}
    result = list_topics(args, sns_client)

    assert result["EntryContext"]["AWS.SNS.Topics"][0]["TopicArn"] == "topic2"


def test_list_topics_client_error(sns_client):
    """
    Given a mocked SNS client
    When the client raises an exception
    Then raise the exception
    """
    error_message = "Some error"
    sns_client.list_topics.side_effect = Exception(error_message)

    result = list_topics({}, sns_client)
    assert result["Contents"] == error_message