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

Ruby
require 'chilkat'

success = false

stringCompare = Chilkat::CkStringBuilder.new()
#  Assumes Chilkat is unlocked. See Global Unlock Sample.
#  Private credentials; do not put this file in public web content or source control.
credentials = Chilkat::CkJsonObject.new()
credentials.put_Strict(true)
success = credentials.LoadFile("qa_data/aws/sns.json")
if (success != true)
    print "Could not load private SNS credentials." + "\n";
    exit
end

stringCompare.SetString(credentials.stringOf("access_key"))
stringMatch1 = stringCompare.ContentsEqual("",true)
if ((credentials.JsonTypeOf("access_key") != 1) or (stringMatch1 == true))
    print "Missing or invalid access_key." + "\n";
    exit
end

stringCompare.SetString(credentials.stringOf("secret_key"))
stringMatch2 = stringCompare.ContentsEqual("",true)
if ((credentials.JsonTypeOf("secret_key") != 1) or (stringMatch2 == true))
    print "Missing or invalid secret_key." + "\n";
    exit
end

region = "us-west-2"
endpoint = Chilkat::CkStringBuilder.new()
endpoint.Append("sns.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
aws = Chilkat::CkAuthAws.new()
aws.put_AccessKey(credentials.stringOf("access_key"))
aws.put_SecretKey(credentials.stringOf("secret_key"))
aws.put_Region(region)
aws.put_ServiceName("sns")
aws.put_SignatureVersion(4)
rest = Chilkat::CkRest.new()
rest.put_ConnectTimeoutMs(20000)
rest.put_IdleTimeoutMs(60000)
rest.put_VerboseLogging(false)
success = rest.SetAuthAws(aws)
if (success != true)
    print "Could not configure AWS signing." + "\n";
    exit
end

if (credentials.HasMember("session_token") == true)
    stringCompare.SetString(credentials.stringOf("session_token"))
    stringMatch3 = stringCompare.ContentsEqual("",true)
    if ((credentials.JsonTypeOf("session_token") != 1) or (stringMatch3 == true))
        print "session_token must be a nonempty string when supplied." + "\n";
        exit
    end

end

xml = Chilkat::CkXml.new()
xml.put_Strict(true)

topicArn = "arn:aws:sns:us-west-2:123456789012:chilkat-standard-example"
topic = Chilkat::CkStringBuilder.new()
topic.Append(topicArn)
arnPrefix = Chilkat::CkStringBuilder.new()
arnPrefix.Append("arn:aws:sns:")
arnPrefix.Append(region)
arnPrefix.Append(":")
if (topic.StartsWith(arnPrefix.getAsString(),true) != true)
    print "Select an SNS topic ARN in the configured region and commercial AWS partition." + "\n";
    exit
end

#  Explicit certificate verification; keep this Socket alive while Rest uses it.
connection = Chilkat::CkSocket.new()
connection.put_RequireSslCertVerify(true)
connection.put_MaxReadIdleMs(60000)
connection.put_MaxSendIdleMs(60000)
success = connection.Connect(endpoint.getAsString(),443,true,20000)
if (success != true)
    print "TLS connection failed; inspect diagnostics privately." + "\n";
    exit
end

success = rest.UseConnection(connection,true)
if (success != true)
    print "Could not attach TLS connection." + "\n";
    exit
end

success = rest.ClearAllQueryParams()
if (success != true)
    print "Could not clear parameters from the previous request." + "\n";
    exit
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.AddQueryParam("Action","GetTopicAttributes")
if (success != true)
    print "Could not set Action." + "\n";
    exit
end

success = rest.AddQueryParam("Version","2010-03-31")
if (success != true)
    print "Could not set Version." + "\n";
    exit
end

#  Include temporary credentials in the signed form body on every request.
if (credentials.HasMember("session_token") == true)
    success = rest.AddQueryParam("X-Amz-Security-Token",credentials.stringOf("session_token"))
    if (success != true)
        print "Could not set X-Amz-Security-Token." + "\n";
        exit
    end

end

success = rest.AddQueryParam("TopicArn",topicArn)
if (success != true)
    print "Could not set TopicArn." + "\n";
    exit
end

responseXml = rest.fullRequestFormUrlEncoded("POST","/")
if (rest.get_LastMethodSuccess() != true)
    print "Request did not complete. Inspect diagnostics privately." + "\n";
    exit
end

success = xml.LoadXml(responseXml)
if (rest.get_ResponseStatusCode() != 200)
    print "SNS HTTP status: " + rest.get_ResponseStatusCode().to_s() + "\n";
    if (success == true)
        value = xml.getChildContent("Error|Code")
        if (xml.get_LastMethodSuccess() == true)
            print "AWS error code: " + value + "\n";
        end

        value = xml.getChildContent("RequestId")
        if (xml.get_LastMethodSuccess() == true)
            print "AWS request ID: " + value + "\n";
        end

    end

    #  Full messages, headers, and signing diagnostics may contain private data.
    exit
end

if (success != true)
    print "Expected a well-formed XML response." + "\n";
    exit
end

stringCompare.SetString(xml.tag())
stringMatch4 = stringCompare.ContentsEqual("GetTopicAttributesResponse",true)
if (stringMatch4 != true)
    print "Unexpected SNS response element." + "\n";
    exit
end

value = xml.getChildContent("ResponseMetadata|RequestId")
stringCompare.SetString(value)
stringMatch5 = stringCompare.ContentsEqual("",true)
if ((xml.get_LastMethodSuccess() != true) or (stringMatch5 == true))
    print "Missing or empty ResponseMetadata|RequestId." + "\n";
    exit
end

print "AWS request ID: " + value + "\n";
if (xml.HasChildWithTag("GetTopicAttributesResult") != true)
    print "Missing result." + "\n";
    exit
end

attributes = Chilkat::CkJsonObject.new()
mapIndex = 0
while (mapIndex < xml.NumChildrenAt("GetTopicAttributesResult|Attributes"))
    xml.put_I(mapIndex)
    value = xml.getChildContent("GetTopicAttributesResult|Attributes|entry[i]|key")
    stringCompare.SetString(value)
    stringMatch6 = stringCompare.ContentsEqual("",true)
    if ((xml.get_LastMethodSuccess() != true) or (stringMatch6 == true))
        print "Missing or empty GetTopicAttributesResult|Attributes|entry[i]|key." + "\n";
        exit
    end

    mapKey = value
    value = xml.getChildContent("GetTopicAttributesResult|Attributes|entry[i]|value")
    if (xml.get_LastMethodSuccess() != true)
        print "Missing map value." + "\n";
        exit
    end

    success = attributes.AppendString(mapKey,value)
    if (success != true)
        print "Invalid or duplicate map entry." + "\n";
        exit
    end

    mapIndex = mapIndex + 1
end
if (attributes.JsonTypeOf("Policy") != 1)
    print "Missing policy; refusing to replace it with a new default." + "\n";
    exit
end

policy = Chilkat::CkJsonObject.new()
policy.put_Strict(true)
success = policy.Load(attributes.stringOf("Policy"))
if (success != true)
    print "Existing policy is not valid JSON." + "\n";
    exit
end

if (policy.JsonTypeOf("Statement") != 4)
    print "This example requires a Statement array; normalize other policy shapes separately." + "\n";
    exit
end

statements = Chilkat::CkJsonArray.new()
success = policy.ArrayOf2("Statement",statements)
if (success != true)
    print "Could not read statements." + "\n";
    exit
end

statementIndex = 0
while (statementIndex < statements.get_Size())
    policy.put_I(statementIndex)
    if (policy.JsonTypeOf("Statement[i]") != 3)
        print "Malformed existing statement." + "\n";
        exit
    end

    stringCompare.SetString(policy.stringOf("Statement[i].Sid"))
    stringMatch7 = stringCompare.ContentsEqual("AllowOrderBucketPublish",true)
    if (stringMatch7 == true)
        print "The chosen Sid already exists; inspect it before making another change." + "\n";
        exit
    end

    statementIndex = statementIndex + 1
end
newStatement = Chilkat::CkJsonObject.new()
newStatement.put_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 (success != true)
    print "Could not construct JSON." + "\n";
    exit
end

bucketArn = Chilkat::CkStringBuilder.new()
bucketArn.Append("arn:aws:s3:")
bucketArn.Append("::example-order-events")
success = newStatement.UpdateString("Condition.ArnEquals.aws:SourceArn",bucketArn.getAsString())
if (success != true)
    print "Could not set source bucket." + "\n";
    exit
end

success = newStatement.UpdateString("Resource",topicArn)
if (success != true)
    print "Could not set resource." + "\n";
    exit
end

success = statements.AddObjectCopyAt(-1,newStatement)
if (success != true)
    print "Could not append policy statement." + "\n";
    exit
end

success = rest.ClearAllQueryParams()
if (success != true)
    print "Could not clear parameters from the previous request." + "\n";
    exit
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.AddQueryParam("Action","SetTopicAttributes")
if (success != true)
    print "Could not set Action." + "\n";
    exit
end

success = rest.AddQueryParam("Version","2010-03-31")
if (success != true)
    print "Could not set Version." + "\n";
    exit
end

#  Include temporary credentials in the signed form body on every request.
if (credentials.HasMember("session_token") == true)
    success = rest.AddQueryParam("X-Amz-Security-Token",credentials.stringOf("session_token"))
    if (success != true)
        print "Could not set X-Amz-Security-Token." + "\n";
        exit
    end

end

success = rest.AddQueryParam("TopicArn",topicArn)
if (success != true)
    print "Could not set TopicArn." + "\n";
    exit
end

success = rest.AddQueryParam("AttributeName","Policy")
if (success != true)
    print "Could not set AttributeName." + "\n";
    exit
end

success = rest.AddQueryParam("AttributeValue",policy.emit())
if (success != true)
    print "Could not set AttributeValue." + "\n";
    exit
end

responseXml = rest.fullRequestFormUrlEncoded("POST","/")
if (rest.get_LastMethodSuccess() != true)
    print "Request did not complete. Its outcome may be uncertain; reconcile before retrying." + "\n";
    exit
end

success = xml.LoadXml(responseXml)
if (rest.get_ResponseStatusCode() != 200)
    print "SNS HTTP status: " + rest.get_ResponseStatusCode().to_s() + "\n";
    if (success == true)
        value = xml.getChildContent("Error|Code")
        if (xml.get_LastMethodSuccess() == true)
            print "AWS error code: " + value + "\n";
        end

        value = xml.getChildContent("RequestId")
        if (xml.get_LastMethodSuccess() == true)
            print "AWS request ID: " + value + "\n";
        end

    end

    #  Full messages, headers, and signing diagnostics may contain private data.
    exit
end

if (success != true)
    print "Expected a well-formed XML response." + "\n";
    exit
end

stringCompare.SetString(xml.tag())
stringMatch8 = stringCompare.ContentsEqual("SetTopicAttributesResponse",true)
if (stringMatch8 != true)
    print "Unexpected SNS response element." + "\n";
    exit
end

value = xml.getChildContent("ResponseMetadata|RequestId")
stringCompare.SetString(value)
stringMatch9 = stringCompare.ContentsEqual("",true)
if ((xml.get_LastMethodSuccess() != true) or (stringMatch9 == true))
    print "Missing or empty ResponseMetadata|RequestId." + "\n";
    exit
end

print "AWS request ID: " + value + "\n";
print "Example completed." + "\n";