Sample code for 30+ languages & platforms
Unicode C++ Requires Chilkat v11.6.0+

Amazon SNS: Add a Restricted S3 Publisher to an Existing Topic Policy

See more Amazon SNS Examples

Uses the current Amazon SNS Query API (Version=2010-03-31) through Chilkat.Rest and AuthAws, with HTTPS, Signature Version 4, and service sns. The API version date remains current. Action and input parameters are URL-encoded into a POST body, avoiding message text and recipient addresses in the URL. Set the actual region once; other AWS partitions need their documented endpoint suffix and ARN partition.

Load private qa_data/aws/sns.json with nonempty string fields access_key, secret_key, and session_token when using temporary credentials. Prefer short-lived role credentials. This sample does not discover profiles, obtain credentials, or refresh them automatically. The session token is included in the signed form body on every request. A Socket explicitly enables TLS certificate verification before passing the connection to Rest.

Checks setup calls, transport completion, HTTP status, XML parsing, result root, and required fields. Normal output includes identifiers, not full messages or headers. Keep detailed diagnostics private. For retryable failures, use bounded backoff with jitter in the application; these examples do not automatically retry writes. A Publish timeout can leave an accepted message and retrying a standard-topic/SMS publish can duplicate it. A returned MessageId confirms SNS acceptance, not subscriber or handset delivery.

Reads and preserves the existing policy and appends one uniquely named statement, constrained to a particular S3 bucket and source account. Replace both placeholders with the actual bucket owner details. An existing matching Sid causes a stop for review rather than an overwrite. The sample supports Statement arrays and rejects other shapes. SetTopicAttributes replaces the policy as a whole and has no conditional version check; serialize policy writers externally to avoid lost concurrent updates. Configure S3 notifications separately. KMS permissions are separate when the topic is encrypted.

Required IAM actions: sns:GetTopicAttributes, sns:SetTopicAttributes. Related SQS/KMS permissions are separate.

AWS references: GetTopicAttributes SetTopicAttributes

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkAuthAwsW.h>
#include <CkRestW.h>
#include <CkXmlW.h>
#include <CkSocketW.h>
#include <CkJsonArrayW.h>

void ChilkatSample(void)
    {
    bool success = false;

    CkStringBuilderW stringCompare;
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    //  Private credentials; do not put this file in public web content or source control.
    CkJsonObjectW credentials;
    credentials.put_Strict(true);
    success = credentials.LoadFile(L"qa_data/aws/sns.json");
    if (success != true) {
        wprintf(L"Could not load private SNS credentials.\n");
        return;
    }

    stringCompare.SetString(credentials.stringOf(L"access_key"));
    bool stringMatch1 = stringCompare.ContentsEqual(L"",true);
    if ((credentials.JsonTypeOf(L"access_key") != 1) || (stringMatch1 == true)) {
        wprintf(L"Missing or invalid access_key.\n");
        return;
    }

    stringCompare.SetString(credentials.stringOf(L"secret_key"));
    bool stringMatch2 = stringCompare.ContentsEqual(L"",true);
    if ((credentials.JsonTypeOf(L"secret_key") != 1) || (stringMatch2 == true)) {
        wprintf(L"Missing or invalid secret_key.\n");
        return;
    }

    const wchar_t *region = L"us-west-2";
    CkStringBuilderW endpoint;
    endpoint.Append(L"sns.");
    endpoint.Append(region);
    endpoint.Append(L".amazonaws.com");
    CkAuthAwsW aws;
    aws.put_AccessKey(credentials.stringOf(L"access_key"));
    aws.put_SecretKey(credentials.stringOf(L"secret_key"));
    aws.put_Region(region);
    aws.put_ServiceName(L"sns");
    aws.put_SignatureVersion(4);
    CkRestW rest;
    rest.put_ConnectTimeoutMs(20000);
    rest.put_IdleTimeoutMs(60000);
    rest.put_VerboseLogging(false);
    success = rest.SetAuthAws(aws);
    if (success != true) {
        wprintf(L"Could not configure AWS signing.\n");
        return;
    }

    if (credentials.HasMember(L"session_token") == true) {
        stringCompare.SetString(credentials.stringOf(L"session_token"));
        bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
        if ((credentials.JsonTypeOf(L"session_token") != 1) || (stringMatch3 == true)) {
            wprintf(L"session_token must be a nonempty string when supplied.\n");
            return;
        }

    }

    CkXmlW xml;
    xml.put_Strict(true);
    const wchar_t *value = 0;
    const wchar_t *responseXml = 0;
    const wchar_t *topicArn = L"arn:aws:sns:us-west-2:123456789012:chilkat-standard-example";
    CkStringBuilderW topic;
    topic.Append(topicArn);
    CkStringBuilderW arnPrefix;
    arnPrefix.Append(L"arn:aws:sns:");
    arnPrefix.Append(region);
    arnPrefix.Append(L":");
    if (topic.StartsWith(arnPrefix.getAsString(),true) != true) {
        wprintf(L"Select an SNS topic ARN in the configured region and commercial AWS partition.\n");
        return;
    }

    //  Explicit certificate verification; keep this Socket alive while Rest uses it.
    CkSocketW connection;
    connection.put_RequireSslCertVerify(true);
    connection.put_MaxReadIdleMs(60000);
    connection.put_MaxSendIdleMs(60000);
    success = connection.Connect(endpoint.getAsString(),443,true,20000);
    if (success != true) {
        wprintf(L"TLS connection failed; inspect diagnostics privately.\n");
        return;
    }

    success = rest.UseConnection(connection,true);
    if (success != true) {
        wprintf(L"Could not attach TLS connection.\n");
        return;
    }

    success = rest.ClearAllQueryParams();
    if (success != true) {
        wprintf(L"Could not clear parameters from the previous request.\n");
        return;
    }

    //  Build a fresh form for each request; do not retain parameters from a previous action.
    //  AddQueryParam encodes raw values into the POST body. Do not pre-encode them.
    success = rest.AddQueryParam(L"Action",L"GetTopicAttributes");
    if (success != true) {
        wprintf(L"Could not set Action.\n");
        return;
    }

    success = rest.AddQueryParam(L"Version",L"2010-03-31");
    if (success != true) {
        wprintf(L"Could not set Version.\n");
        return;
    }

    //  Include temporary credentials in the signed form body on every request.
    if (credentials.HasMember(L"session_token") == true) {
        success = rest.AddQueryParam(L"X-Amz-Security-Token",credentials.stringOf(L"session_token"));
        if (success != true) {
            wprintf(L"Could not set X-Amz-Security-Token.\n");
            return;
        }

    }

    success = rest.AddQueryParam(L"TopicArn",topicArn);
    if (success != true) {
        wprintf(L"Could not set TopicArn.\n");
        return;
    }

    responseXml = rest.fullRequestFormUrlEncoded(L"POST",L"/");
    if (rest.get_LastMethodSuccess() != true) {
        wprintf(L"Request did not complete. Inspect diagnostics privately.\n");
        return;
    }

    success = xml.LoadXml(responseXml);
    if (rest.get_ResponseStatusCode() != 200) {
        wprintf(L"SNS HTTP status: %d\n",rest.get_ResponseStatusCode());
        if (success == true) {
            value = xml.getChildContent(L"Error|Code");
            if (xml.get_LastMethodSuccess() == true) {
                wprintf(L"AWS error code: %s\n",value);
            }

            value = xml.getChildContent(L"RequestId");
            if (xml.get_LastMethodSuccess() == true) {
                wprintf(L"AWS request ID: %s\n",value);
            }

        }

        //  Full messages, headers, and signing diagnostics may contain private data.
        return;
    }

    if (success != true) {
        wprintf(L"Expected a well-formed XML response.\n");
        return;
    }

    stringCompare.SetString(xml.tag());
    bool stringMatch4 = stringCompare.ContentsEqual(L"GetTopicAttributesResponse",true);
    if (stringMatch4 != true) {
        wprintf(L"Unexpected SNS response element.\n");
        return;
    }

    value = xml.getChildContent(L"ResponseMetadata|RequestId");
    stringCompare.SetString(value);
    bool stringMatch5 = stringCompare.ContentsEqual(L"",true);
    if ((xml.get_LastMethodSuccess() != true) || (stringMatch5 == true)) {
        wprintf(L"Missing or empty ResponseMetadata|RequestId.\n");
        return;
    }

    wprintf(L"AWS request ID: %s\n",value);
    if (xml.HasChildWithTag(L"GetTopicAttributesResult") != true) {
        wprintf(L"Missing result.\n");
        return;
    }

    CkJsonObjectW attributes;
    int mapIndex = 0;
    while ((mapIndex < xml.NumChildrenAt(L"GetTopicAttributesResult|Attributes"))) {
        xml.put_I(mapIndex);
        value = xml.getChildContent(L"GetTopicAttributesResult|Attributes|entry[i]|key");
        stringCompare.SetString(value);
        bool stringMatch6 = stringCompare.ContentsEqual(L"",true);
        if ((xml.get_LastMethodSuccess() != true) || (stringMatch6 == true)) {
            wprintf(L"Missing or empty GetTopicAttributesResult|Attributes|entry[i]|key.\n");
            return;
        }

        const wchar_t *mapKey = value;
        value = xml.getChildContent(L"GetTopicAttributesResult|Attributes|entry[i]|value");
        if (xml.get_LastMethodSuccess() != true) {
            wprintf(L"Missing map value.\n");
            return;
        }

        success = attributes.AppendString(mapKey,value);
        if (success != true) {
            wprintf(L"Invalid or duplicate map entry.\n");
            return;
        }

        mapIndex = mapIndex + 1;
    }

    if (attributes.JsonTypeOf(L"Policy") != 1) {
        wprintf(L"Missing policy; refusing to replace it with a new default.\n");
        return;
    }

    CkJsonObjectW policy;
    policy.put_Strict(true);
    success = policy.Load(attributes.stringOf(L"Policy"));
    if (success != true) {
        wprintf(L"Existing policy is not valid JSON.\n");
        return;
    }

    if (policy.JsonTypeOf(L"Statement") != 4) {
        wprintf(L"This example requires a Statement array; normalize other policy shapes separately.\n");
        return;
    }

    CkJsonArrayW statements;
    success = policy.ArrayOf2(L"Statement",statements);
    if (success != true) {
        wprintf(L"Could not read statements.\n");
        return;
    }

    int statementIndex = 0;
    while ((statementIndex < statements.get_Size())) {
        policy.put_I(statementIndex);
        if (policy.JsonTypeOf(L"Statement[i]") != 3) {
            wprintf(L"Malformed existing statement.\n");
            return;
        }

        stringCompare.SetString(policy.stringOf(L"Statement[i].Sid"));
        bool stringMatch7 = stringCompare.ContentsEqual(L"AllowOrderBucketPublish",true);
        if (stringMatch7 == true) {
            wprintf(L"The chosen Sid already exists; inspect it before making another change.\n");
            return;
        }

        statementIndex = statementIndex + 1;
    }

    CkJsonObjectW newStatement;
    newStatement.put_Strict(true);
    success = newStatement.Load(L"{\"Sid\":\"AllowOrderBucketPublish\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"s3.amazonaws.com\"},\"Action\":\"sns:Publish\",\"Resource\":\"placeholder\",\"Condition\":{\"ArnEquals\":{\"aws:SourceArn\":\"placeholder\"},\"StringEquals\":{\"aws:SourceAccount\":\"123456789012\"}}}");
    if (success != true) {
        wprintf(L"Could not construct JSON.\n");
        return;
    }

    CkStringBuilderW bucketArn;
    bucketArn.Append(L"arn:aws:s3:");
    bucketArn.Append(L"::example-order-events");
    success = newStatement.UpdateString(L"Condition.ArnEquals.aws:SourceArn",bucketArn.getAsString());
    if (success != true) {
        wprintf(L"Could not set source bucket.\n");
        return;
    }

    success = newStatement.UpdateString(L"Resource",topicArn);
    if (success != true) {
        wprintf(L"Could not set resource.\n");
        return;
    }

    success = statements.AddObjectCopyAt(-1,newStatement);
    if (success != true) {
        wprintf(L"Could not append policy statement.\n");
        return;
    }

    success = rest.ClearAllQueryParams();
    if (success != true) {
        wprintf(L"Could not clear parameters from the previous request.\n");
        return;
    }

    //  Build a fresh form for each request; do not retain parameters from a previous action.
    //  AddQueryParam encodes raw values into the POST body. Do not pre-encode them.
    success = rest.AddQueryParam(L"Action",L"SetTopicAttributes");
    if (success != true) {
        wprintf(L"Could not set Action.\n");
        return;
    }

    success = rest.AddQueryParam(L"Version",L"2010-03-31");
    if (success != true) {
        wprintf(L"Could not set Version.\n");
        return;
    }

    //  Include temporary credentials in the signed form body on every request.
    if (credentials.HasMember(L"session_token") == true) {
        success = rest.AddQueryParam(L"X-Amz-Security-Token",credentials.stringOf(L"session_token"));
        if (success != true) {
            wprintf(L"Could not set X-Amz-Security-Token.\n");
            return;
        }

    }

    success = rest.AddQueryParam(L"TopicArn",topicArn);
    if (success != true) {
        wprintf(L"Could not set TopicArn.\n");
        return;
    }

    success = rest.AddQueryParam(L"AttributeName",L"Policy");
    if (success != true) {
        wprintf(L"Could not set AttributeName.\n");
        return;
    }

    success = rest.AddQueryParam(L"AttributeValue",policy.emit());
    if (success != true) {
        wprintf(L"Could not set AttributeValue.\n");
        return;
    }

    responseXml = rest.fullRequestFormUrlEncoded(L"POST",L"/");
    if (rest.get_LastMethodSuccess() != true) {
        wprintf(L"Request did not complete. Its outcome may be uncertain; reconcile before retrying.\n");
        return;
    }

    success = xml.LoadXml(responseXml);
    if (rest.get_ResponseStatusCode() != 200) {
        wprintf(L"SNS HTTP status: %d\n",rest.get_ResponseStatusCode());
        if (success == true) {
            value = xml.getChildContent(L"Error|Code");
            if (xml.get_LastMethodSuccess() == true) {
                wprintf(L"AWS error code: %s\n",value);
            }

            value = xml.getChildContent(L"RequestId");
            if (xml.get_LastMethodSuccess() == true) {
                wprintf(L"AWS request ID: %s\n",value);
            }

        }

        //  Full messages, headers, and signing diagnostics may contain private data.
        return;
    }

    if (success != true) {
        wprintf(L"Expected a well-formed XML response.\n");
        return;
    }

    stringCompare.SetString(xml.tag());
    bool stringMatch8 = stringCompare.ContentsEqual(L"SetTopicAttributesResponse",true);
    if (stringMatch8 != true) {
        wprintf(L"Unexpected SNS response element.\n");
        return;
    }

    value = xml.getChildContent(L"ResponseMetadata|RequestId");
    stringCompare.SetString(value);
    bool stringMatch9 = stringCompare.ContentsEqual(L"",true);
    if ((xml.get_LastMethodSuccess() != true) || (stringMatch9 == true)) {
        wprintf(L"Missing or empty ResponseMetadata|RequestId.\n");
        return;
    }

    wprintf(L"AWS request ID: %s\n",value);
    wprintf(L"Example completed.\n");
    }