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