Sample code for 30+ languages & platforms
Lua 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 Lua Downloads

Lua
local chilkat = require("chilkat")

local stringCompare = chilkat.StringBuilder.new()
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
-- Private credentials; do not put this file in public web content or source control.
local credentials = chilkat.JsonObject.new()
credentials.strict = true
local success = credentials:load_file("qa_data/aws/sns.json")
if not success then
    print("Could not load private SNS credentials.")
    return
end

stringCompare:set_string(credentials:string_of("access_key"))
local stringMatch1 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("access_key") ~= 1) or (stringMatch1) then
    print("Missing or invalid access_key.")
    return
end

stringCompare:set_string(credentials:string_of("secret_key"))
local stringMatch2 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("secret_key") ~= 1) or (stringMatch2) then
    print("Missing or invalid secret_key.")
    return
end

local region = "us-west-2"
local endpoint = chilkat.StringBuilder.new()
endpoint:append("sns.")
endpoint:append(region)
endpoint:append(".amazonaws.com")
local aws = chilkat.AuthAws.new()
aws.access_key = credentials:string_of("access_key")
aws.secret_key = credentials:string_of("secret_key")
aws.region = region
aws.service_name = "sns"
aws.signature_version = 4
local rest = chilkat.Rest.new()
rest.connect_timeout_ms = 20000
rest.idle_timeout_ms = 60000
rest.verbose_logging = false
success = rest:set_auth_aws(aws)
if not success then
    print("Could not configure AWS signing.")
    return
end

if credentials:has_member("session_token") then
    stringCompare:set_string(credentials:string_of("session_token"))
    local stringMatch3 = stringCompare:contents_equal("", true)
    if (credentials:json_type_of("session_token") ~= 1) or (stringMatch3) then
        print("session_token must be a nonempty string when supplied.")
        return
    end
end

local xml = chilkat.Xml.new()
xml.strict = true
local value = ""
local topicArn = "arn:aws:sns:us-west-2:123456789012:chilkat-standard-example"
local topic = chilkat.StringBuilder.new()
topic:append(topicArn)
local arnPrefix = chilkat.StringBuilder.new()
arnPrefix:append("arn:aws:sns:")
arnPrefix:append(region)
arnPrefix:append(":")
if not topic:starts_with(arnPrefix:get_as_string(), true) then
    print("Select an SNS topic ARN in the configured region and commercial AWS partition.")
    return
end

-- Explicit certificate verification; keep this Socket alive while Rest uses it.
local connection = chilkat.Socket.new()
connection.require_ssl_cert_verify = true
connection.max_read_idle_ms = 60000
connection.max_send_idle_ms = 60000
success = connection:connect(endpoint:get_as_string(), 443, true, 20000)
if not success then
    print("TLS connection failed; inspect diagnostics privately.")
    return
end

success = rest:use_connection(connection, true)
if not success then
    print("Could not attach TLS connection.")
    return
end

success = rest:clear_all_query_params()
if not success then
    print("Could not clear parameters from the previous request.")
    return
end

-- 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:add_query_param("Action", "GetTopicAttributes")
if not success then
    print("Could not set Action.")
    return
end

success = rest:add_query_param("Version", "2010-03-31")
if not success then
    print("Could not set Version.")
    return
end

-- Include temporary credentials in the signed form body on every request.
if credentials:has_member("session_token") then
    success = rest:add_query_param("X-Amz-Security-Token", credentials:string_of("session_token"))
    if not success then
        print("Could not set X-Amz-Security-Token.")
        return
    end
end

success = rest:add_query_param("TopicArn", topicArn)
if not success then
    print("Could not set TopicArn.")
    return
end

local responseXml = rest:full_request_form_url_encoded("POST", "/")
if not rest.last_method_success then
    print("Request did not complete. Inspect diagnostics privately.")
    return
end

success = xml:load_xml(responseXml)
if rest.response_status_code ~= 200 then
    print("SNS HTTP status: " .. rest.response_status_code)
    if success then
        value = xml:get_child_content("Error|Code")
        if xml.last_method_success then
            print("AWS error code: " .. value)
        end

        value = xml:get_child_content("RequestId")
        if xml.last_method_success then
            print("AWS request ID: " .. value)
        end
    end

    -- Full messages, headers, and signing diagnostics may contain private data.
    return
end

if not success then
    print("Expected a well-formed XML response.")
    return
end

stringCompare:set_string(xml.tag)
local stringMatch4 = stringCompare:contents_equal("GetTopicAttributesResponse", true)
if not stringMatch4 then
    print("Unexpected SNS response element.")
    return
end

value = xml:get_child_content("ResponseMetadata|RequestId")
stringCompare:set_string(value)
local stringMatch5 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch5) then
    print("Missing or empty ResponseMetadata|RequestId.")
    return
end

print("AWS request ID: " .. value)
if not xml:has_child_with_tag("GetTopicAttributesResult") then
    print("Missing result.")
    return
end

local attributes = chilkat.JsonObject.new()
local mapIndex = 0
while mapIndex < xml:num_children_at("GetTopicAttributesResult|Attributes") do
    xml.i = mapIndex
    value = xml:get_child_content("GetTopicAttributesResult|Attributes|entry[i]|key")
    stringCompare:set_string(value)
    local stringMatch6 = stringCompare:contents_equal("", true)
    if (not xml.last_method_success) or (stringMatch6) then
        print("Missing or empty GetTopicAttributesResult|Attributes|entry[i]|key.")
        return
    end

    local mapKey = value
    value = xml:get_child_content("GetTopicAttributesResult|Attributes|entry[i]|value")
    if not xml.last_method_success then
        print("Missing map value.")
        return
    end

    success = attributes:append_string(mapKey, value)
    if not success then
        print("Invalid or duplicate map entry.")
        return
    end

    mapIndex = mapIndex + 1
end

if attributes:json_type_of("Policy") ~= 1 then
    print("Missing policy; refusing to replace it with a new default.")
    return
end

local policy = chilkat.JsonObject.new()
policy.strict = true
success = policy:load(attributes:string_of("Policy"))
if not success then
    print("Existing policy is not valid JSON.")
    return
end

if policy:json_type_of("Statement") ~= 4 then
    print("This example requires a Statement array; normalize other policy shapes separately.")
    return
end

local statements = chilkat.JsonArray.new()
success = policy:array_of2("Statement", statements)
if not success then
    print("Could not read statements.")
    return
end

local statementIndex = 0
while statementIndex < statements.size do
    policy.i = statementIndex
    if policy:json_type_of("Statement[i]") ~= 3 then
        print("Malformed existing statement.")
        return
    end

    stringCompare:set_string(policy:string_of("Statement[i].Sid"))
    local stringMatch7 = stringCompare:contents_equal("AllowOrderBucketPublish", true)
    if stringMatch7 then
        print("The chosen Sid already exists; inspect it before making another change.")
        return
    end

    statementIndex = statementIndex + 1
end

local newStatement = chilkat.JsonObject.new()
newStatement.strict = true
success = newStatement:load("{\"Sid\":\"AllowOrderBucketPublish\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"s3.amazonaws.com\"},\"Action\":\"sns:Publish\",\"Resource\":\"placeholder\",\"Condition\":{\"ArnEquals\":{\"aws:SourceArn\":\"placeholder\"},\"StringEquals\":{\"aws:SourceAccount\":\"123456789012\"}}}")
if not success then
    print("Could not construct JSON.")
    return
end

local bucketArn = chilkat.StringBuilder.new()
bucketArn:append("arn:aws:s3:")
bucketArn:append("::example-order-events")
success = newStatement:update_string("Condition.ArnEquals.aws:SourceArn", bucketArn:get_as_string())
if not success then
    print("Could not set source bucket.")
    return
end

success = newStatement:update_string("Resource", topicArn)
if not success then
    print("Could not set resource.")
    return
end

success = statements:add_object_copy_at(-1, newStatement)
if not success then
    print("Could not append policy statement.")
    return
end

success = rest:clear_all_query_params()
if not success then
    print("Could not clear parameters from the previous request.")
    return
end

-- 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:add_query_param("Action", "SetTopicAttributes")
if not success then
    print("Could not set Action.")
    return
end

success = rest:add_query_param("Version", "2010-03-31")
if not success then
    print("Could not set Version.")
    return
end

-- Include temporary credentials in the signed form body on every request.
if credentials:has_member("session_token") then
    success = rest:add_query_param("X-Amz-Security-Token", credentials:string_of("session_token"))
    if not success then
        print("Could not set X-Amz-Security-Token.")
        return
    end
end

success = rest:add_query_param("TopicArn", topicArn)
if not success then
    print("Could not set TopicArn.")
    return
end

success = rest:add_query_param("AttributeName", "Policy")
if not success then
    print("Could not set AttributeName.")
    return
end

success = rest:add_query_param("AttributeValue", policy:emit())
if not success then
    print("Could not set AttributeValue.")
    return
end

responseXml = rest:full_request_form_url_encoded("POST", "/")
if not rest.last_method_success then
    print("Request did not complete. Its outcome may be uncertain; reconcile before retrying.")
    return
end

success = xml:load_xml(responseXml)
if rest.response_status_code ~= 200 then
    print("SNS HTTP status: " .. rest.response_status_code)
    if success then
        value = xml:get_child_content("Error|Code")
        if xml.last_method_success then
            print("AWS error code: " .. value)
        end

        value = xml:get_child_content("RequestId")
        if xml.last_method_success then
            print("AWS request ID: " .. value)
        end
    end

    -- Full messages, headers, and signing diagnostics may contain private data.
    return
end

if not success then
    print("Expected a well-formed XML response.")
    return
end

stringCompare:set_string(xml.tag)
local stringMatch8 = stringCompare:contents_equal("SetTopicAttributesResponse", true)
if not stringMatch8 then
    print("Unexpected SNS response element.")
    return
end

value = xml:get_child_content("ResponseMetadata|RequestId")
stringCompare:set_string(value)
local stringMatch9 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch9) then
    print("Missing or empty ResponseMetadata|RequestId.")
    return
end

print("AWS request ID: " .. value)
print("Example completed.")