Amazon SNS: Verify HTTPS Notifications and Detect Batch Duplicates
See more Amazon SNS Examples
Verify an SNS HTTPS delivery envelope before processing it. Delivery signatures use RSA, not the SigV4 used to call the SNS API.
Reads a private file shaped as {"messages":[SNS-envelope,...]}. Verifies Notifications and both confirmation types, including optional Subject, exact LF canonicalization, RSA/SHA-256 signature version 2, and SHA-1 version 1 compatibility. It pins an expected topic and regional HTTPS certificate source, disallows redirects and unusual certificate paths, validates chain signatures/root trust/validity dates, and checks a configurable timestamp window. Provision required intermediates and approved roots; never accept roots from an incoming envelope. The checks are not an online certificate-revocation service or a general-purpose PKIX policy engine.
Duplicate detection uses (TopicArn, MessageId) and lasts only within this batch; the example performs no business side effects. For an HTTP receiver, enforce request-size limits before JSON parsing, persist a unique inbox key and accepted payload transactionally, acknowledge only durable acceptance, and process idempotently. Choose timestamp retention to cover the intended delivery/replay window; the illustrative 24-hour bound may reject deliberately replayed old messages. Confirm only subscriptions the application requested, using the verified Token and a configured API endpoint; it never follows SubscribeURL or automatically resubscribes.
AWS signature verification guidance
Chilkat Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
var success = false;
final stringCompare = CkStringBuilder();
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// File format: {"messages":[<SNS envelope>, ...]}. Do not store untrusted files publicly.
final batch = CkJsonObject();
batch.strict = true;
success = true;
try {
batch.loadFile('qa_data/aws/sns_notifications.json');
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not parse notification envelopes.');
return;
}
if (batch.jsonTypeOf('messages') != 4) {
print('Expected a messages array.');
return;
}
final count = batch.sizeOfArray('messages');
if ((count < 1) || (count > 100)) {
print('Use 1 to 100 envelopes per verification batch.');
return;
}
final allowedTopic = 'arn:aws:sns:us-west-2:123456789012:chilkat-standard-example';
final certPrefix = 'https://sns.us-west-2.amazonaws.com/SimpleNotificationService-';
// Pin the expected topic and matching regional SNS host in application configuration.
final seenMessages = CkHashtable();
final envelope = CkJsonObject();
final now = CkDateTime();
success = true;
try {
now.setFromCurrentSystemTime();
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not read current time.');
return;
}
var envelopeIndex = 0;
while (envelopeIndex < count) {
batch.i = envelopeIndex;
success = true;
try {
batch.objectOf2('messages[i]', envelope);
} on ChilkatException {
success = false;
}
if (!success) {
print('Expected a JSON object envelope.');
return;
}
final fieldNames = CkHashtable();
var fieldIndex = 0;
while (fieldIndex < envelope.size) {
final fieldName = envelope.nameAt(fieldIndex);
if (fieldNames.contains(fieldName)) {
print('Duplicate envelope field.');
return;
}
success = true;
try {
fieldNames.addStr(fieldName, 'seen');
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not track envelope fields.');
return;
}
fieldIndex++;
}
stringCompare.setString(envelope.stringOf('Type'));
final stringMatch1 = stringCompare.contentsEqual('', true);
if ((envelope.jsonTypeOf('Type') != 1) || (stringMatch1)) {
print('Missing or invalid Type.');
return;
}
stringCompare.setString(envelope.stringOf('MessageId'));
final stringMatch2 = stringCompare.contentsEqual('', true);
if ((envelope.jsonTypeOf('MessageId') != 1) || (stringMatch2)) {
print('Missing or invalid MessageId.');
return;
}
stringCompare.setString(envelope.stringOf('Message'));
final stringMatch3 = stringCompare.contentsEqual('', true);
if ((envelope.jsonTypeOf('Message') != 1) || (stringMatch3)) {
print('Missing or invalid Message.');
return;
}
stringCompare.setString(envelope.stringOf('Timestamp'));
final stringMatch4 = stringCompare.contentsEqual('', true);
if ((envelope.jsonTypeOf('Timestamp') != 1) || (stringMatch4)) {
print('Missing or invalid Timestamp.');
return;
}
stringCompare.setString(envelope.stringOf('TopicArn'));
final stringMatch5 = stringCompare.contentsEqual('', true);
if ((envelope.jsonTypeOf('TopicArn') != 1) || (stringMatch5)) {
print('Missing or invalid TopicArn.');
return;
}
stringCompare.setString(envelope.stringOf('SignatureVersion'));
final stringMatch6 = stringCompare.contentsEqual('', true);
if ((envelope.jsonTypeOf('SignatureVersion') != 1) || (stringMatch6)) {
print('Missing or invalid SignatureVersion.');
return;
}
stringCompare.setString(envelope.stringOf('Signature'));
final stringMatch7 = stringCompare.contentsEqual('', true);
if ((envelope.jsonTypeOf('Signature') != 1) || (stringMatch7)) {
print('Missing or invalid Signature.');
return;
}
stringCompare.setString(envelope.stringOf('SigningCertURL'));
final stringMatch8 = stringCompare.contentsEqual('', true);
if ((envelope.jsonTypeOf('SigningCertURL') != 1) || (stringMatch8)) {
print('Missing or invalid SigningCertURL.');
return;
}
final messageType = envelope.stringOf('Type');
stringCompare.setString(messageType);
final stringMatch9 = stringCompare.contentsEqual('Notification', true);
stringCompare.setString(messageType);
final stringMatch10 = stringCompare.contentsEqual('SubscriptionConfirmation', true);
stringCompare.setString(messageType);
final stringMatch11 = stringCompare.contentsEqual('UnsubscribeConfirmation', true);
if ((!stringMatch9) && ((!stringMatch10) && (!stringMatch11))) {
print('Unsupported SNS message type.');
return;
}
stringCompare.setString(envelope.stringOf('TopicArn'));
final stringMatch12 = stringCompare.contentsEqual(allowedTopic, true);
if (!stringMatch12) {
print('Unexpected SNS topic.');
return;
}
final signatureVersion = envelope.stringOf('SignatureVersion');
stringCompare.setString(signatureVersion);
final stringMatch13 = stringCompare.contentsEqual('1', true);
stringCompare.setString(signatureVersion);
final stringMatch14 = stringCompare.contentsEqual('2', true);
if ((!stringMatch13) && (!stringMatch14)) {
print('Unsupported delivery signature version.');
return;
}
var hashAlgorithm = 'sha256';
stringCompare.setString(signatureVersion);
final stringMatch15 = stringCompare.contentsEqual('1', true);
if (stringMatch15) {
hashAlgorithm = 'sha1';
}
stringCompare.setString(messageType);
final stringMatch16 = stringCompare.contentsEqual('Notification', true);
if (!stringMatch16) {
stringCompare.setString(envelope.stringOf('SubscribeURL'));
final stringMatch17 = stringCompare.contentsEqual('', true);
stringCompare.setString(envelope.stringOf('Token'));
final stringMatch18 = stringCompare.contentsEqual('', true);
if ((envelope.jsonTypeOf('SubscribeURL') != 1) || ((stringMatch17) || ((envelope.jsonTypeOf('Token') != 1) || (stringMatch18)))) {
print('Confirmation envelope is missing fields.');
return;
}
}
if (envelope.hasMember('Subject')) {
if (envelope.jsonTypeOf('Subject') != 1) {
print('Subject must be a string when present.');
return;
}
}
final timestamp = CkDateTime();
success = true;
try {
timestamp.setFromTimestamp(envelope.stringOf('Timestamp'));
} on ChilkatException {
success = false;
}
if (!success) {
print('Invalid notification timestamp.');
return;
}
final ageSeconds = now.diffSeconds(timestamp);
if ((ageSeconds < -300) || (ageSeconds > 86400)) {
print('Notification outside the configured 24-hour age / 5-minute clock-skew window.');
return;
}
final certUrl = CkStringBuilder();
certUrl.append(envelope.stringOf('SigningCertURL'));
final prefix = CkStringBuilder();
prefix.append(certPrefix);
if ((!certUrl.startsWith(certPrefix, true)) || ((!certUrl.endsWith('.pem', true)) || (certUrl.length <= prefix.length + 4))) {
print('Untrusted signing-certificate URL.');
return;
}
// Only a flat SNS certificate filename is allowed: no query, fragment, escapes,
// userinfo, alternate port, path traversal, or redirect destination.
final filenameChars = CkStringBuilder();
filenameChars.append('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_');
var charIndex = prefix.length;
while (charIndex < certUrl.length - 4) {
if (!filenameChars.contains(certUrl.getRange(charIndex, 1, false), true)) {
print('Invalid signing-certificate filename.');
return;
}
charIndex++;
}
final http = CkHttp();
http.requireSslCertVerify = true;
http.followRedirects = false;
http.connectTimeout = 20;
http.readTimeout = 30;
final maxCertBytes = 65536;
http.maxResponseSize = maxCertBytes;
http.verboseLogging = false;
final certPem = http.quickGetStr(certUrl.getAsString());
if ((!http.lastMethodSuccess) || (http.lastStatus != 200)) {
print('Could not retrieve the certificate securely from the pinned SNS endpoint.');
return;
}
final signingCert = CkCert();
success = true;
try {
signingCert.loadPem(certPem);
} on ChilkatException {
success = false;
}
if (!success) {
print('Invalid signing certificate.');
return;
}
final chain = CkCertChain();
success = true;
try {
signingCert.buildCertChain(chain);
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not build signing-certificate chain.');
return;
}
if (!chain.reachesRoot) {
print('Incomplete signing-certificate chain; provision trusted intermediates.');
return;
}
final roots = CkTrustedRoots();
roots.trustSystemCaRoots = true;
if (!chain.isRootTrusted(roots)) {
print('Untrusted signing-certificate root.');
return;
}
success = chain.verifyCertSignatures();
if (!success) {
print('Invalid certificate-chain signatures.');
return;
}
var certIndex = 0;
final chainCert = CkCert();
while (certIndex < chain.numCerts) {
success = true;
try {
chain.certAt(certIndex, chainCert);
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not read chain certificate.');
return;
}
final validFrom = CkDateTime();
final validTo = CkDateTime();
success = true;
try {
validFrom.setFromRfc822(chainCert.validFromStr);
} on ChilkatException {
success = false;
}
if (!success) {
print('Invalid certificate validity start.');
return;
}
success = true;
try {
validTo.setFromRfc822(chainCert.validToStr);
} on ChilkatException {
success = false;
}
if (!success) {
print('Invalid certificate validity end.');
return;
}
if ((now.diffSeconds(validFrom) < 0) || (now.diffSeconds(validTo) > 0)) {
print('Certificate outside its validity period.');
return;
}
certIndex++;
}
final canonical = CkStringBuilder();
canonical.appendLine('Message', false);
canonical.appendLine(envelope.stringOf('Message'), false);
canonical.appendLine('MessageId', false);
canonical.appendLine(envelope.stringOf('MessageId'), false);
stringCompare.setString(messageType);
final stringMatch19 = stringCompare.contentsEqual('Notification', true);
if (stringMatch19) {
if (envelope.hasMember('Subject')) {
canonical.appendLine('Subject', false);
canonical.appendLine(envelope.stringOf('Subject'), false);
}
} else {
canonical.appendLine('SubscribeURL', false);
canonical.appendLine(envelope.stringOf('SubscribeURL'), false);
}
canonical.appendLine('Timestamp', false);
canonical.appendLine(envelope.stringOf('Timestamp'), false);
stringCompare.setString(messageType);
final stringMatch20 = stringCompare.contentsEqual('Notification', true);
if (!stringMatch20) {
canonical.appendLine('Token', false);
canonical.appendLine(envelope.stringOf('Token'), false);
}
canonical.appendLine('TopicArn', false);
canonical.appendLine(envelope.stringOf('TopicArn'), false);
canonical.appendLine('Type', false);
canonical.appendLine(envelope.stringOf('Type'), false);
final publicKey = CkPublicKey();
success = true;
try {
signingCert.getPublicKey(publicKey);
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not extract signing public key.');
return;
}
final rsa = CkRsa();
rsa.charset = 'utf-8';
rsa.encodingMode = 'base64';
rsa.littleEndian = false;
success = true;
try {
rsa.usePublicKey(publicKey);
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not configure verification key.');
return;
}
success = true;
try {
rsa.verifyStringENC(canonical.getAsString(), hashAlgorithm, envelope.stringOf('Signature'));
} on ChilkatException {
success = false;
}
if (!success) {
print('SNS delivery signature is invalid.');
return;
}
// Use a JSON-encoded composite key to avoid ambiguous concatenation.
final identity = CkJsonObject();
success = true;
try {
identity.updateString('topic', allowedTopic);
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not form duplicate key.');
return;
}
success = true;
try {
identity.updateString('id', envelope.stringOf('MessageId'));
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not form duplicate key.');
return;
}
final duplicateKey = identity.emit();
if (seenMessages.contains(duplicateKey)) {
print('Verified duplicate skipped: ${envelope.stringOf('MessageId')}');
} else {
success = true;
try {
seenMessages.addStr(duplicateKey, 'verified');
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not track duplicate key.');
return;
}
print('Verified $messageType / ${envelope.stringOf('MessageId')}');
// Notification: durably enqueue/process only after verification.
// SubscriptionConfirmation: submit the verified Token to the configured SNS
// endpoint only if this is a subscription your application requested.
// UnsubscribeConfirmation: record status; do not automatically resubscribe.
// Never follow SubscribeURL merely because it appeared in an envelope.
}
envelopeIndex++;
}
print('All envelopes verified; duplicate detection was limited to this batch.');
}