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 C# Downloads
bool success = false;
Chilkat.StringBuilder stringCompare = new Chilkat.StringBuilder();
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Private credentials; do not put this file in public web content or source control.
Chilkat.JsonObject credentials = new Chilkat.JsonObject();
credentials.Strict = true;
success = credentials.LoadFile("qa_data/aws/sns.json");
if (success != true) {
Debug.WriteLine("Could not load private SNS credentials.");
return;
}
stringCompare.SetString(credentials.StringOf("access_key"));
bool stringMatch1 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("access_key") != 1) || (stringMatch1 == true)) {
Debug.WriteLine("Missing or invalid access_key.");
return;
}
stringCompare.SetString(credentials.StringOf("secret_key"));
bool stringMatch2 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("secret_key") != 1) || (stringMatch2 == true)) {
Debug.WriteLine("Missing or invalid secret_key.");
return;
}
string region = "us-west-2";
Chilkat.StringBuilder endpoint = new Chilkat.StringBuilder();
endpoint.Append("sns.");
endpoint.Append(region);
endpoint.Append(".amazonaws.com");
Chilkat.AuthAws aws = new Chilkat.AuthAws();
aws.AccessKey = credentials.StringOf("access_key");
aws.SecretKey = credentials.StringOf("secret_key");
aws.Region = region;
aws.ServiceName = "sns";
aws.SignatureVersion = 4;
Chilkat.Rest rest = new Chilkat.Rest();
rest.ConnectTimeoutMs = 20000;
rest.IdleTimeoutMs = 60000;
rest.VerboseLogging = false;
success = rest.SetAuthAws(aws);
if (success != true) {
Debug.WriteLine("Could not configure AWS signing.");
return;
}
if (credentials.HasMember("session_token") == true) {
stringCompare.SetString(credentials.StringOf("session_token"));
bool stringMatch3 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("session_token") != 1) || (stringMatch3 == true)) {
Debug.WriteLine("session_token must be a nonempty string when supplied.");
return;
}
}
Chilkat.Xml xml = new Chilkat.Xml();
xml.Strict = true;
string value;
string responseXml;
string topicArn = "arn:aws:sns:us-west-2:123456789012:chilkat-standard-example";
Chilkat.StringBuilder topic = new Chilkat.StringBuilder();
topic.Append(topicArn);
Chilkat.StringBuilder arnPrefix = new Chilkat.StringBuilder();
arnPrefix.Append("arn:aws:sns:");
arnPrefix.Append(region);
arnPrefix.Append(":");
if (topic.StartsWith(arnPrefix.GetAsString(),true) != true) {
Debug.WriteLine("Select an SNS topic ARN in the configured region and commercial AWS partition.");
return;
}
// Explicit certificate verification; keep this Socket alive while Rest uses it.
Chilkat.Socket connection = new Chilkat.Socket();
connection.RequireSslCertVerify = true;
connection.MaxReadIdleMs = 60000;
connection.MaxSendIdleMs = 60000;
success = connection.Connect(endpoint.GetAsString(),443,true,20000);
if (success != true) {
Debug.WriteLine("TLS connection failed; inspect diagnostics privately.");
return;
}
success = rest.UseConnection(connection,true);
if (success != true) {
Debug.WriteLine("Could not attach TLS connection.");
return;
}
success = rest.ClearAllQueryParams();
if (success != true) {
Debug.WriteLine("Could not clear parameters from the previous request.");
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("Action","GetTopicAttributes");
if (success != true) {
Debug.WriteLine("Could not set Action.");
return;
}
success = rest.AddQueryParam("Version","2010-03-31");
if (success != true) {
Debug.WriteLine("Could not set Version.");
return;
}
// 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) {
Debug.WriteLine("Could not set X-Amz-Security-Token.");
return;
}
}
success = rest.AddQueryParam("TopicArn",topicArn);
if (success != true) {
Debug.WriteLine("Could not set TopicArn.");
return;
}
responseXml = rest.FullRequestFormUrlEncoded("POST","/");
if (rest.LastMethodSuccess != true) {
Debug.WriteLine("Request did not complete. Inspect diagnostics privately.");
return;
}
success = xml.LoadXml(responseXml);
if (rest.ResponseStatusCode != 200) {
Debug.WriteLine("SNS HTTP status: " + Convert.ToString(rest.ResponseStatusCode));
if (success == true) {
value = xml.GetChildContent("Error|Code");
if (xml.LastMethodSuccess == true) {
Debug.WriteLine("AWS error code: " + value);
}
value = xml.GetChildContent("RequestId");
if (xml.LastMethodSuccess == true) {
Debug.WriteLine("AWS request ID: " + value);
}
}
// Full messages, headers, and signing diagnostics may contain private data.
return;
}
if (success != true) {
Debug.WriteLine("Expected a well-formed XML response.");
return;
}
stringCompare.SetString(xml.Tag);
bool stringMatch4 = stringCompare.ContentsEqual("GetTopicAttributesResponse",true);
if (stringMatch4 != true) {
Debug.WriteLine("Unexpected SNS response element.");
return;
}
value = xml.GetChildContent("ResponseMetadata|RequestId");
stringCompare.SetString(value);
bool stringMatch5 = stringCompare.ContentsEqual("",true);
if ((xml.LastMethodSuccess != true) || (stringMatch5 == true)) {
Debug.WriteLine("Missing or empty ResponseMetadata|RequestId.");
return;
}
Debug.WriteLine("AWS request ID: " + value);
if (xml.HasChildWithTag("GetTopicAttributesResult") != true) {
Debug.WriteLine("Missing result.");
return;
}
Chilkat.JsonObject attributes = new Chilkat.JsonObject();
int mapIndex = 0;
while ((mapIndex < xml.NumChildrenAt("GetTopicAttributesResult|Attributes"))) {
xml.I = mapIndex;
value = xml.GetChildContent("GetTopicAttributesResult|Attributes|entry[i]|key");
stringCompare.SetString(value);
bool stringMatch6 = stringCompare.ContentsEqual("",true);
if ((xml.LastMethodSuccess != true) || (stringMatch6 == true)) {
Debug.WriteLine("Missing or empty GetTopicAttributesResult|Attributes|entry[i]|key.");
return;
}
string mapKey = value;
value = xml.GetChildContent("GetTopicAttributesResult|Attributes|entry[i]|value");
if (xml.LastMethodSuccess != true) {
Debug.WriteLine("Missing map value.");
return;
}
success = attributes.AppendString(mapKey,value);
if (success != true) {
Debug.WriteLine("Invalid or duplicate map entry.");
return;
}
mapIndex = mapIndex + 1;
}
if (attributes.JsonTypeOf("Policy") != 1) {
Debug.WriteLine("Missing policy; refusing to replace it with a new default.");
return;
}
Chilkat.JsonObject policy = new Chilkat.JsonObject();
policy.Strict = true;
success = policy.Load(attributes.StringOf("Policy"));
if (success != true) {
Debug.WriteLine("Existing policy is not valid JSON.");
return;
}
if (policy.JsonTypeOf("Statement") != 4) {
Debug.WriteLine("This example requires a Statement array; normalize other policy shapes separately.");
return;
}
Chilkat.JsonArray statements = new Chilkat.JsonArray();
success = policy.ArrayOf2("Statement",statements);
if (success != true) {
Debug.WriteLine("Could not read statements.");
return;
}
int statementIndex = 0;
while ((statementIndex < statements.Size)) {
policy.I = statementIndex;
if (policy.JsonTypeOf("Statement[i]") != 3) {
Debug.WriteLine("Malformed existing statement.");
return;
}
stringCompare.SetString(policy.StringOf("Statement[i].Sid"));
bool stringMatch7 = stringCompare.ContentsEqual("AllowOrderBucketPublish",true);
if (stringMatch7 == true) {
Debug.WriteLine("The chosen Sid already exists; inspect it before making another change.");
return;
}
statementIndex = statementIndex + 1;
}
Chilkat.JsonObject newStatement = new Chilkat.JsonObject();
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 (success != true) {
Debug.WriteLine("Could not construct JSON.");
return;
}
Chilkat.StringBuilder bucketArn = new Chilkat.StringBuilder();
bucketArn.Append("arn:aws:s3:");
bucketArn.Append("::example-order-events");
success = newStatement.UpdateString("Condition.ArnEquals.aws:SourceArn",bucketArn.GetAsString());
if (success != true) {
Debug.WriteLine("Could not set source bucket.");
return;
}
success = newStatement.UpdateString("Resource",topicArn);
if (success != true) {
Debug.WriteLine("Could not set resource.");
return;
}
success = statements.AddObjectCopyAt(-1,newStatement);
if (success != true) {
Debug.WriteLine("Could not append policy statement.");
return;
}
success = rest.ClearAllQueryParams();
if (success != true) {
Debug.WriteLine("Could not clear parameters from the previous request.");
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("Action","SetTopicAttributes");
if (success != true) {
Debug.WriteLine("Could not set Action.");
return;
}
success = rest.AddQueryParam("Version","2010-03-31");
if (success != true) {
Debug.WriteLine("Could not set Version.");
return;
}
// 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) {
Debug.WriteLine("Could not set X-Amz-Security-Token.");
return;
}
}
success = rest.AddQueryParam("TopicArn",topicArn);
if (success != true) {
Debug.WriteLine("Could not set TopicArn.");
return;
}
success = rest.AddQueryParam("AttributeName","Policy");
if (success != true) {
Debug.WriteLine("Could not set AttributeName.");
return;
}
success = rest.AddQueryParam("AttributeValue",policy.Emit());
if (success != true) {
Debug.WriteLine("Could not set AttributeValue.");
return;
}
responseXml = rest.FullRequestFormUrlEncoded("POST","/");
if (rest.LastMethodSuccess != true) {
Debug.WriteLine("Request did not complete. Its outcome may be uncertain; reconcile before retrying.");
return;
}
success = xml.LoadXml(responseXml);
if (rest.ResponseStatusCode != 200) {
Debug.WriteLine("SNS HTTP status: " + Convert.ToString(rest.ResponseStatusCode));
if (success == true) {
value = xml.GetChildContent("Error|Code");
if (xml.LastMethodSuccess == true) {
Debug.WriteLine("AWS error code: " + value);
}
value = xml.GetChildContent("RequestId");
if (xml.LastMethodSuccess == true) {
Debug.WriteLine("AWS request ID: " + value);
}
}
// Full messages, headers, and signing diagnostics may contain private data.
return;
}
if (success != true) {
Debug.WriteLine("Expected a well-formed XML response.");
return;
}
stringCompare.SetString(xml.Tag);
bool stringMatch8 = stringCompare.ContentsEqual("SetTopicAttributesResponse",true);
if (stringMatch8 != true) {
Debug.WriteLine("Unexpected SNS response element.");
return;
}
value = xml.GetChildContent("ResponseMetadata|RequestId");
stringCompare.SetString(value);
bool stringMatch9 = stringCompare.ContentsEqual("",true);
if ((xml.LastMethodSuccess != true) || (stringMatch9 == true)) {
Debug.WriteLine("Missing or empty ResponseMetadata|RequestId.");
return;
}
Debug.WriteLine("AWS request ID: " + value);
Debug.WriteLine("Example completed.");