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

Visual Basic 6.0
Dim success As Long
success = 0

Dim stringCompare As New ChilkatStringBuilder
'  Assumes Chilkat is unlocked. See Global Unlock Sample.
'  Private credentials; do not put this file in public web content or source control.
Dim credentials As New ChilkatJsonObject
credentials.Strict = 1
success = credentials.LoadFile("qa_data/aws/sns.json")
If (success <> 1) Then
    Debug.Print "Could not load private SNS credentials."
    Exit Sub
End If

success = stringCompare.SetString(credentials.StringOf("access_key"))
Dim stringMatch1 As Long
stringMatch1 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("access_key") <> 1) Or (stringMatch1 = 1)) Then
    Debug.Print "Missing or invalid access_key."
    Exit Sub
End If

success = stringCompare.SetString(credentials.StringOf("secret_key"))
Dim stringMatch2 As Long
stringMatch2 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("secret_key") <> 1) Or (stringMatch2 = 1)) Then
    Debug.Print "Missing or invalid secret_key."
    Exit Sub
End If

Dim region As String
region = "us-west-2"
Dim endpoint As New ChilkatStringBuilder
success = endpoint.Append("sns.")
success = endpoint.Append(region)
success = endpoint.Append(".amazonaws.com")
Dim aws As New ChilkatAuthAws
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "sns"
aws.SignatureVersion = 4
Dim rest As New ChilkatRest
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = 0
success = rest.SetAuthAws(aws)
If (success <> 1) Then
    Debug.Print "Could not configure AWS signing."
    Exit Sub
End If

If (credentials.HasMember("session_token") = 1) Then
    success = stringCompare.SetString(credentials.StringOf("session_token"))
    Dim stringMatch3 As Long
    stringMatch3 = stringCompare.ContentsEqual("",1)
    If ((credentials.JsonTypeOf("session_token") <> 1) Or (stringMatch3 = 1)) Then
        Debug.Print "session_token must be a nonempty string when supplied."
        Exit Sub
    End If

End If

Dim xml As New ChilkatXml
xml.Strict = 1
Dim value As String
Dim responseXml As String
Dim topicArn As String
topicArn = "arn:aws:sns:us-west-2:123456789012:chilkat-standard-example"
Dim topic As New ChilkatStringBuilder
success = topic.Append(topicArn)
Dim arnPrefix As New ChilkatStringBuilder
success = arnPrefix.Append("arn:aws:sns:")
success = arnPrefix.Append(region)
success = arnPrefix.Append(":")
If (topic.StartsWith(arnPrefix.GetAsString(),1) <> 1) Then
    Debug.Print "Select an SNS topic ARN in the configured region and commercial AWS partition."
    Exit Sub
End If

'  Explicit certificate verification; keep this Socket alive while Rest uses it.
Dim connection As New ChilkatSocket
connection.RequireSslCertVerify = 1
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,1,20000)
If (success <> 1) Then
    Debug.Print "TLS connection failed; inspect diagnostics privately."
    Exit Sub
End If

success = rest.UseConnection(connection,1)
If (success <> 1) Then
    Debug.Print "Could not attach TLS connection."
    Exit Sub
End If

success = rest.ClearAllQueryParams()
If (success <> 1) Then
    Debug.Print "Could not clear parameters from the previous request."
    Exit Sub
End If

'  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 <> 1) Then
    Debug.Print "Could not set Action."
    Exit Sub
End If

success = rest.AddQueryParam("Version","2010-03-31")
If (success <> 1) Then
    Debug.Print "Could not set Version."
    Exit Sub
End If

'  Include temporary credentials in the signed form body on every request.
If (credentials.HasMember("session_token") = 1) Then
    success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"))
    If (success <> 1) Then
        Debug.Print "Could not set X-Amz-Security-Token."
        Exit Sub
    End If

End If

success = rest.AddQueryParam("TopicArn",topicArn)
If (success <> 1) Then
    Debug.Print "Could not set TopicArn."
    Exit Sub
End If

responseXml = rest.FullRequestFormUrlEncoded("POST","/")
If (rest.LastMethodSuccess <> 1) Then
    Debug.Print "Request did not complete. Inspect diagnostics privately."
    Exit Sub
End If

success = xml.LoadXml(responseXml)
If (rest.ResponseStatusCode <> 200) Then
    Debug.Print "SNS HTTP status: " & rest.ResponseStatusCode
    If (success = 1) Then
        value = xml.GetChildContent("Error|Code")
        If (xml.LastMethodSuccess = 1) Then
            Debug.Print "AWS error code: " & value
        End If

        value = xml.GetChildContent("RequestId")
        If (xml.LastMethodSuccess = 1) Then
            Debug.Print "AWS request ID: " & value
        End If

    End If

    '  Full messages, headers, and signing diagnostics may contain private data.
    Exit Sub
End If

If (success <> 1) Then
    Debug.Print "Expected a well-formed XML response."
    Exit Sub
End If

success = stringCompare.SetString(xml.Tag)
Dim stringMatch4 As Long
stringMatch4 = stringCompare.ContentsEqual("GetTopicAttributesResponse",1)
If (stringMatch4 <> 1) Then
    Debug.Print "Unexpected SNS response element."
    Exit Sub
End If

value = xml.GetChildContent("ResponseMetadata|RequestId")
success = stringCompare.SetString(value)
Dim stringMatch5 As Long
stringMatch5 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch5 = 1)) Then
    Debug.Print "Missing or empty ResponseMetadata|RequestId."
    Exit Sub
End If

Debug.Print "AWS request ID: " & value
If (xml.HasChildWithTag("GetTopicAttributesResult") <> 1) Then
    Debug.Print "Missing result."
    Exit Sub
End If

Dim attributes As New ChilkatJsonObject
Dim mapIndex As Long
mapIndex = 0
Do While (mapIndex < xml.NumChildrenAt("GetTopicAttributesResult|Attributes"))
    xml.I = mapIndex
    value = xml.GetChildContent("GetTopicAttributesResult|Attributes|entry[i]|key")
    success = stringCompare.SetString(value)
    Dim stringMatch6 As Long
    stringMatch6 = stringCompare.ContentsEqual("",1)
    If ((xml.LastMethodSuccess <> 1) Or (stringMatch6 = 1)) Then
        Debug.Print "Missing or empty GetTopicAttributesResult|Attributes|entry[i]|key."
        Exit Sub
    End If

    Dim mapKey As String
    mapKey = value
    value = xml.GetChildContent("GetTopicAttributesResult|Attributes|entry[i]|value")
    If (xml.LastMethodSuccess <> 1) Then
        Debug.Print "Missing map value."
        Exit Sub
    End If

    success = attributes.AppendString(mapKey,value)
    If (success <> 1) Then
        Debug.Print "Invalid or duplicate map entry."
        Exit Sub
    End If

    mapIndex = mapIndex + 1
Loop
If (attributes.JsonTypeOf("Policy") <> 1) Then
    Debug.Print "Missing policy; refusing to replace it with a new default."
    Exit Sub
End If

Dim policy As New ChilkatJsonObject
policy.Strict = 1
success = policy.Load(attributes.StringOf("Policy"))
If (success <> 1) Then
    Debug.Print "Existing policy is not valid JSON."
    Exit Sub
End If

If (policy.JsonTypeOf("Statement") <> 4) Then
    Debug.Print "This example requires a Statement array; normalize other policy shapes separately."
    Exit Sub
End If

Dim statements As New ChilkatJsonArray
success = policy.ArrayOf2("Statement",statements)
If (success <> 1) Then
    Debug.Print "Could not read statements."
    Exit Sub
End If

Dim statementIndex As Long
statementIndex = 0
Do While (statementIndex < statements.Size)
    policy.I = statementIndex
    If (policy.JsonTypeOf("Statement[i]") <> 3) Then
        Debug.Print "Malformed existing statement."
        Exit Sub
    End If

    success = stringCompare.SetString(policy.StringOf("Statement[i].Sid"))
    Dim stringMatch7 As Long
    stringMatch7 = stringCompare.ContentsEqual("AllowOrderBucketPublish",1)
    If (stringMatch7 = 1) Then
        Debug.Print "The chosen Sid already exists; inspect it before making another change."
        Exit Sub
    End If

    statementIndex = statementIndex + 1
Loop
Dim newStatement As New ChilkatJsonObject
newStatement.Strict = 1
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 <> 1) Then
    Debug.Print "Could not construct JSON."
    Exit Sub
End If

Dim bucketArn As New ChilkatStringBuilder
success = bucketArn.Append("arn:aws:s3:")
success = bucketArn.Append("::example-order-events")
success = newStatement.UpdateString("Condition.ArnEquals.aws:SourceArn",bucketArn.GetAsString())
If (success <> 1) Then
    Debug.Print "Could not set source bucket."
    Exit Sub
End If

success = newStatement.UpdateString("Resource",topicArn)
If (success <> 1) Then
    Debug.Print "Could not set resource."
    Exit Sub
End If

success = statements.AddObjectCopyAt(-1,newStatement)
If (success <> 1) Then
    Debug.Print "Could not append policy statement."
    Exit Sub
End If

success = rest.ClearAllQueryParams()
If (success <> 1) Then
    Debug.Print "Could not clear parameters from the previous request."
    Exit Sub
End If

'  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 <> 1) Then
    Debug.Print "Could not set Action."
    Exit Sub
End If

success = rest.AddQueryParam("Version","2010-03-31")
If (success <> 1) Then
    Debug.Print "Could not set Version."
    Exit Sub
End If

'  Include temporary credentials in the signed form body on every request.
If (credentials.HasMember("session_token") = 1) Then
    success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"))
    If (success <> 1) Then
        Debug.Print "Could not set X-Amz-Security-Token."
        Exit Sub
    End If

End If

success = rest.AddQueryParam("TopicArn",topicArn)
If (success <> 1) Then
    Debug.Print "Could not set TopicArn."
    Exit Sub
End If

success = rest.AddQueryParam("AttributeName","Policy")
If (success <> 1) Then
    Debug.Print "Could not set AttributeName."
    Exit Sub
End If

success = rest.AddQueryParam("AttributeValue",policy.Emit())
If (success <> 1) Then
    Debug.Print "Could not set AttributeValue."
    Exit Sub
End If

responseXml = rest.FullRequestFormUrlEncoded("POST","/")
If (rest.LastMethodSuccess <> 1) Then
    Debug.Print "Request did not complete. Its outcome may be uncertain; reconcile before retrying."
    Exit Sub
End If

success = xml.LoadXml(responseXml)
If (rest.ResponseStatusCode <> 200) Then
    Debug.Print "SNS HTTP status: " & rest.ResponseStatusCode
    If (success = 1) Then
        value = xml.GetChildContent("Error|Code")
        If (xml.LastMethodSuccess = 1) Then
            Debug.Print "AWS error code: " & value
        End If

        value = xml.GetChildContent("RequestId")
        If (xml.LastMethodSuccess = 1) Then
            Debug.Print "AWS request ID: " & value
        End If

    End If

    '  Full messages, headers, and signing diagnostics may contain private data.
    Exit Sub
End If

If (success <> 1) Then
    Debug.Print "Expected a well-formed XML response."
    Exit Sub
End If

success = stringCompare.SetString(xml.Tag)
Dim stringMatch8 As Long
stringMatch8 = stringCompare.ContentsEqual("SetTopicAttributesResponse",1)
If (stringMatch8 <> 1) Then
    Debug.Print "Unexpected SNS response element."
    Exit Sub
End If

value = xml.GetChildContent("ResponseMetadata|RequestId")
success = stringCompare.SetString(value)
Dim stringMatch9 As Long
stringMatch9 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch9 = 1)) Then
    Debug.Print "Missing or empty ResponseMetadata|RequestId."
    Exit Sub
End If

Debug.Print "AWS request ID: " & value
Debug.Print "Example completed."