Sample code for 30+ languages & platforms
Delphi DLL Requires Chilkat v11.6.0+

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 Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
stringCompare: HCkStringBuilder;
batch: HCkJsonObject;
count: Integer;
allowedTopic: PWideChar;
certPrefix: PWideChar;
seenMessages: HCkHashtable;
envelope: HCkJsonObject;
now: HCkDateTime;
envelopeIndex: Integer;
fieldNames: HCkHashtable;
fieldIndex: Integer;
fieldName: PWideChar;
stringMatch1: Boolean;
stringMatch2: Boolean;
stringMatch3: Boolean;
stringMatch4: Boolean;
stringMatch5: Boolean;
stringMatch6: Boolean;
stringMatch7: Boolean;
stringMatch8: Boolean;
messageType: PWideChar;
stringMatch9: Boolean;
stringMatch10: Boolean;
stringMatch11: Boolean;
stringMatch12: Boolean;
signatureVersion: PWideChar;
stringMatch13: Boolean;
stringMatch14: Boolean;
hashAlgorithm: PWideChar;
stringMatch15: Boolean;
stringMatch16: Boolean;
stringMatch17: Boolean;
stringMatch18: Boolean;
timestamp: HCkDateTime;
ageSeconds: Integer;
certUrl: HCkStringBuilder;
prefix: HCkStringBuilder;
filenameChars: HCkStringBuilder;
charIndex: Integer;
http: HCkHttp;
maxCertBytes: Cardinal;
certPem: PWideChar;
signingCert: HCkCert;
chain: HCkCertChain;
roots: HCkTrustedRoots;
certIndex: Integer;
chainCert: HCkCert;
validFrom: HCkDateTime;
validTo: HCkDateTime;
canonical: HCkStringBuilder;
stringMatch19: Boolean;
stringMatch20: Boolean;
publicKey: HCkPublicKey;
rsa: HCkRsa;
identity: HCkJsonObject;
duplicateKey: PWideChar;

begin
success := False;

stringCompare := CkStringBuilder_Create();
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
//  File format: {"messages":[<SNS envelope>, ...]}. Do not store untrusted files publicly.

batch := CkJsonObject_Create();
CkJsonObject_putStrict(batch,True);
success := CkJsonObject_LoadFile(batch,'qa_data/aws/sns_notifications.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not parse notification envelopes.');
    Exit;
  end;
if (CkJsonObject_JsonTypeOf(batch,'messages') <> 4) then
  begin
    Memo1.Lines.Add('Expected a messages array.');
    Exit;
  end;
count := CkJsonObject_SizeOfArray(batch,'messages');
if ((count < 1) or (count > 100)) then
  begin
    Memo1.Lines.Add('Use 1 to 100 envelopes per verification batch.');
    Exit;
  end;
allowedTopic := 'arn:aws:sns:us-west-2:123456789012:chilkat-standard-example';
certPrefix := 'https://sns.us-west-2.amazonaws.com/SimpleNotificationService-';
//  Pin the expected topic and matching regional SNS host in application configuration.
seenMessages := CkHashtable_Create();
envelope := CkJsonObject_Create();
now := CkDateTime_Create();
success := CkDateTime_SetFromCurrentSystemTime(now);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not read current time.');
    Exit;
  end;
envelopeIndex := 0;
while (envelopeIndex < count) do
  begin
    CkJsonObject_putI(batch,envelopeIndex);
    success := CkJsonObject_ObjectOf2(batch,'messages[i]',envelope);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Expected a JSON object envelope.');
        Exit;
      end;
    fieldNames := CkHashtable_Create();
    fieldIndex := 0;
    while (fieldIndex < CkJsonObject_getSize(envelope)) do
      begin
        fieldName := CkJsonObject__nameAt(envelope,fieldIndex);
        if (CkHashtable_Contains(fieldNames,fieldName) = True) then
          begin
            Memo1.Lines.Add('Duplicate envelope field.');
            Exit;
          end;
        success := CkHashtable_AddStr(fieldNames,fieldName,'seen');
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not track envelope fields.');
            Exit;
          end;
        fieldIndex := fieldIndex + 1;
      end;

    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(envelope,'Type'));
    stringMatch1 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(envelope,'Type') <> 1) or (stringMatch1 = True)) then
      begin
        Memo1.Lines.Add('Missing or invalid Type.');
        Exit;
      end;
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(envelope,'MessageId'));
    stringMatch2 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(envelope,'MessageId') <> 1) or (stringMatch2 = True)) then
      begin
        Memo1.Lines.Add('Missing or invalid MessageId.');
        Exit;
      end;
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(envelope,'Message'));
    stringMatch3 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(envelope,'Message') <> 1) or (stringMatch3 = True)) then
      begin
        Memo1.Lines.Add('Missing or invalid Message.');
        Exit;
      end;
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(envelope,'Timestamp'));
    stringMatch4 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(envelope,'Timestamp') <> 1) or (stringMatch4 = True)) then
      begin
        Memo1.Lines.Add('Missing or invalid Timestamp.');
        Exit;
      end;
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(envelope,'TopicArn'));
    stringMatch5 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(envelope,'TopicArn') <> 1) or (stringMatch5 = True)) then
      begin
        Memo1.Lines.Add('Missing or invalid TopicArn.');
        Exit;
      end;
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(envelope,'SignatureVersion'));
    stringMatch6 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(envelope,'SignatureVersion') <> 1) or (stringMatch6 = True)) then
      begin
        Memo1.Lines.Add('Missing or invalid SignatureVersion.');
        Exit;
      end;
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(envelope,'Signature'));
    stringMatch7 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(envelope,'Signature') <> 1) or (stringMatch7 = True)) then
      begin
        Memo1.Lines.Add('Missing or invalid Signature.');
        Exit;
      end;
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(envelope,'SigningCertURL'));
    stringMatch8 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(envelope,'SigningCertURL') <> 1) or (stringMatch8 = True)) then
      begin
        Memo1.Lines.Add('Missing or invalid SigningCertURL.');
        Exit;
      end;
    messageType := CkJsonObject__stringOf(envelope,'Type');
    CkStringBuilder_SetString(stringCompare,messageType);
    stringMatch9 := CkStringBuilder_ContentsEqual(stringCompare,'Notification',True);
    CkStringBuilder_SetString(stringCompare,messageType);
    stringMatch10 := CkStringBuilder_ContentsEqual(stringCompare,'SubscriptionConfirmation',True);
    CkStringBuilder_SetString(stringCompare,messageType);
    stringMatch11 := CkStringBuilder_ContentsEqual(stringCompare,'UnsubscribeConfirmation',True);
    if ((stringMatch9 <> True) and (stringMatch10 <> True) and (stringMatch11 <> True)) then
      begin
        Memo1.Lines.Add('Unsupported SNS message type.');
        Exit;
      end;
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(envelope,'TopicArn'));
    stringMatch12 := CkStringBuilder_ContentsEqual(stringCompare,allowedTopic,True);
    if (stringMatch12 <> True) then
      begin
        Memo1.Lines.Add('Unexpected SNS topic.');
        Exit;
      end;
    signatureVersion := CkJsonObject__stringOf(envelope,'SignatureVersion');
    CkStringBuilder_SetString(stringCompare,signatureVersion);
    stringMatch13 := CkStringBuilder_ContentsEqual(stringCompare,'1',True);
    CkStringBuilder_SetString(stringCompare,signatureVersion);
    stringMatch14 := CkStringBuilder_ContentsEqual(stringCompare,'2',True);
    if ((stringMatch13 <> True) and (stringMatch14 <> True)) then
      begin
        Memo1.Lines.Add('Unsupported delivery signature version.');
        Exit;
      end;
    hashAlgorithm := 'sha256';
    CkStringBuilder_SetString(stringCompare,signatureVersion);
    stringMatch15 := CkStringBuilder_ContentsEqual(stringCompare,'1',True);
    if (stringMatch15 = True) then
      begin
        hashAlgorithm := 'sha1';
      end;
    CkStringBuilder_SetString(stringCompare,messageType);
    stringMatch16 := CkStringBuilder_ContentsEqual(stringCompare,'Notification',True);
    if (stringMatch16 <> True) then
      begin
        CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(envelope,'SubscribeURL'));
        stringMatch17 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
        CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(envelope,'Token'));
        stringMatch18 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
        if ((CkJsonObject_JsonTypeOf(envelope,'SubscribeURL') <> 1) or (stringMatch17 = True) or (CkJsonObject_JsonTypeOf(envelope,'Token') <> 1) or (stringMatch18 = True)) then
          begin
            Memo1.Lines.Add('Confirmation envelope is missing fields.');
            Exit;
          end;
      end;
    if (CkJsonObject_HasMember(envelope,'Subject') = True) then
      begin
        if (CkJsonObject_JsonTypeOf(envelope,'Subject') <> 1) then
          begin
            Memo1.Lines.Add('Subject must be a string when present.');
            Exit;
          end;
      end;
    timestamp := CkDateTime_Create();
    success := CkDateTime_SetFromTimestamp(timestamp,CkJsonObject__stringOf(envelope,'Timestamp'));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Invalid notification timestamp.');
        Exit;
      end;
    ageSeconds := CkDateTime_DiffSeconds(now,timestamp);
    if ((ageSeconds < -300) or (ageSeconds > 86400)) then
      begin
        Memo1.Lines.Add('Notification outside the configured 24-hour age / 5-minute clock-skew window.');
        Exit;
      end;
    certUrl := CkStringBuilder_Create();
    CkStringBuilder_Append(certUrl,CkJsonObject__stringOf(envelope,'SigningCertURL'));
    prefix := CkStringBuilder_Create();
    CkStringBuilder_Append(prefix,certPrefix);
    if ((CkStringBuilder_StartsWith(certUrl,certPrefix,True) <> True) or (CkStringBuilder_EndsWith(certUrl,'.pem',True) <> True) or (CkStringBuilder_getLength(certUrl) <= CkStringBuilder_getLength(prefix) + 4)) then
      begin
        Memo1.Lines.Add('Untrusted signing-certificate URL.');
        Exit;
      end;
    //  Only a flat SNS certificate filename is allowed: no query, fragment, escapes,
    //  userinfo, alternate port, path traversal, or redirect destination.
    filenameChars := CkStringBuilder_Create();
    CkStringBuilder_Append(filenameChars,'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_');
    charIndex := CkStringBuilder_getLength(prefix);
    while (charIndex < CkStringBuilder_getLength(certUrl) - 4) do
      begin
        if (CkStringBuilder_Contains(filenameChars,CkStringBuilder__getRange(certUrl,charIndex,1,False),True) <> True) then
          begin
            Memo1.Lines.Add('Invalid signing-certificate filename.');
            Exit;
          end;
        charIndex := charIndex + 1;
      end;

    http := CkHttp_Create();
    CkHttp_putRequireSslCertVerify(http,True);
    CkHttp_putFollowRedirects(http,False);
    CkHttp_putConnectTimeout(http,20);
    CkHttp_putReadTimeout(http,30);
    maxCertBytes := 65536;
    CkHttp_putMaxResponseSize(http,maxCertBytes);
    CkHttp_putVerboseLogging(http,False);
    certPem := CkHttp__quickGetStr(http,CkStringBuilder__getAsString(certUrl));
    if ((CkHttp_getLastMethodSuccess(http) <> True) or (CkHttp_getLastStatus(http) <> 200)) then
      begin
        Memo1.Lines.Add('Could not retrieve the certificate securely from the pinned SNS endpoint.');
        Exit;
      end;
    signingCert := CkCert_Create();
    success := CkCert_LoadPem(signingCert,certPem);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Invalid signing certificate.');
        Exit;
      end;
    chain := CkCertChain_Create();
    success := CkCert_BuildCertChain(signingCert,chain);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not build signing-certificate chain.');
        Exit;
      end;
    if (CkCertChain_getReachesRoot(chain) <> True) then
      begin
        Memo1.Lines.Add('Incomplete signing-certificate chain; provision trusted intermediates.');
        Exit;
      end;
    roots := CkTrustedRoots_Create();
    CkTrustedRoots_putTrustSystemCaRoots(roots,True);
    if (CkCertChain_IsRootTrusted(chain,roots) <> True) then
      begin
        Memo1.Lines.Add('Untrusted signing-certificate root.');
        Exit;
      end;
    success := CkCertChain_VerifyCertSignatures(chain);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Invalid certificate-chain signatures.');
        Exit;
      end;
    certIndex := 0;
    chainCert := CkCert_Create();
    while (certIndex < CkCertChain_getNumCerts(chain)) do
      begin
        success := CkCertChain_CertAt(chain,certIndex,chainCert);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not read chain certificate.');
            Exit;
          end;
        validFrom := CkDateTime_Create();
        validTo := CkDateTime_Create();
        success := CkDateTime_SetFromRfc822(validFrom,CkCert__validFromStr(chainCert));
        if (success <> True) then
          begin
            Memo1.Lines.Add('Invalid certificate validity start.');
            Exit;
          end;
        success := CkDateTime_SetFromRfc822(validTo,CkCert__validToStr(chainCert));
        if (success <> True) then
          begin
            Memo1.Lines.Add('Invalid certificate validity end.');
            Exit;
          end;
        if ((CkDateTime_DiffSeconds(now,validFrom) < 0) or (CkDateTime_DiffSeconds(now,validTo) > 0)) then
          begin
            Memo1.Lines.Add('Certificate outside its validity period.');
            Exit;
          end;
        certIndex := certIndex + 1;
      end;

    canonical := CkStringBuilder_Create();
    CkStringBuilder_AppendLine(canonical,'Message',False);
    CkStringBuilder_AppendLine(canonical,CkJsonObject__stringOf(envelope,'Message'),False);
    CkStringBuilder_AppendLine(canonical,'MessageId',False);
    CkStringBuilder_AppendLine(canonical,CkJsonObject__stringOf(envelope,'MessageId'),False);
    CkStringBuilder_SetString(stringCompare,messageType);
    stringMatch19 := CkStringBuilder_ContentsEqual(stringCompare,'Notification',True);
    if (stringMatch19 = True) then
      begin
        if (CkJsonObject_HasMember(envelope,'Subject') = True) then
          begin
            CkStringBuilder_AppendLine(canonical,'Subject',False);
            CkStringBuilder_AppendLine(canonical,CkJsonObject__stringOf(envelope,'Subject'),False);
          end;
      end
    else
      begin
        CkStringBuilder_AppendLine(canonical,'SubscribeURL',False);
        CkStringBuilder_AppendLine(canonical,CkJsonObject__stringOf(envelope,'SubscribeURL'),False);
      end;
    CkStringBuilder_AppendLine(canonical,'Timestamp',False);
    CkStringBuilder_AppendLine(canonical,CkJsonObject__stringOf(envelope,'Timestamp'),False);
    CkStringBuilder_SetString(stringCompare,messageType);
    stringMatch20 := CkStringBuilder_ContentsEqual(stringCompare,'Notification',True);
    if (stringMatch20 <> True) then
      begin
        CkStringBuilder_AppendLine(canonical,'Token',False);
        CkStringBuilder_AppendLine(canonical,CkJsonObject__stringOf(envelope,'Token'),False);
      end;
    CkStringBuilder_AppendLine(canonical,'TopicArn',False);
    CkStringBuilder_AppendLine(canonical,CkJsonObject__stringOf(envelope,'TopicArn'),False);
    CkStringBuilder_AppendLine(canonical,'Type',False);
    CkStringBuilder_AppendLine(canonical,CkJsonObject__stringOf(envelope,'Type'),False);
    publicKey := CkPublicKey_Create();
    success := CkCert_GetPublicKey(signingCert,publicKey);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not extract signing public key.');
        Exit;
      end;
    rsa := CkRsa_Create();
    CkRsa_putCharset(rsa,'utf-8');
    CkRsa_putEncodingMode(rsa,'base64');
    CkRsa_putLittleEndian(rsa,False);
    success := CkRsa_UsePublicKey(rsa,publicKey);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not configure verification key.');
        Exit;
      end;
    success := CkRsa_VerifyStringENC(rsa,CkStringBuilder__getAsString(canonical),hashAlgorithm,CkJsonObject__stringOf(envelope,'Signature'));
    if (success <> True) then
      begin
        Memo1.Lines.Add('SNS delivery signature is invalid.');
        Exit;
      end;
    //  Use a JSON-encoded composite key to avoid ambiguous concatenation.
    identity := CkJsonObject_Create();
    success := CkJsonObject_UpdateString(identity,'topic',allowedTopic);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not form duplicate key.');
        Exit;
      end;
    success := CkJsonObject_UpdateString(identity,'id',CkJsonObject__stringOf(envelope,'MessageId'));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not form duplicate key.');
        Exit;
      end;
    duplicateKey := CkJsonObject__emit(identity);
    if (CkHashtable_Contains(seenMessages,duplicateKey) = True) then
      begin
        Memo1.Lines.Add('Verified duplicate skipped: ' + CkJsonObject__stringOf(envelope,'MessageId'));
      end
    else
      begin
        success := CkHashtable_AddStr(seenMessages,duplicateKey,'verified');
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not track duplicate key.');
            Exit;
          end;
        Memo1.Lines.Add('Verified ' + messageType + ' / ' + CkJsonObject__stringOf(envelope,'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.
      end;
    envelopeIndex := envelopeIndex + 1;
  end;

Memo1.Lines.Add('All envelopes verified; duplicate detection was limited to this batch.');

CkStringBuilder_Dispose(stringCompare);
CkJsonObject_Dispose(batch);
CkHashtable_Dispose(seenMessages);
CkJsonObject_Dispose(envelope);
CkDateTime_Dispose(now);
    CkHashtable_Dispose(fieldNames);
    CkDateTime_Dispose(timestamp);
    CkStringBuilder_Dispose(certUrl);
    CkStringBuilder_Dispose(prefix);
    CkStringBuilder_Dispose(filenameChars);
    CkHttp_Dispose(http);
    CkCert_Dispose(signingCert);
    CkCertChain_Dispose(chain);
    CkTrustedRoots_Dispose(roots);
    CkCert_Dispose(chainCert);
        CkDateTime_Dispose(validFrom);
        CkDateTime_Dispose(validTo);
    CkStringBuilder_Dispose(canonical);
    CkPublicKey_Dispose(publicKey);
    CkRsa_Dispose(rsa);
    CkJsonObject_Dispose(identity);