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

CkPython
import sys
import chilkat

success = False

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

batch = chilkat.CkJsonObject()
batch.put_Strict(True)
success = batch.LoadFile("qa_data/aws/sns_notifications.json")
if (success != True):
    print("Could not parse notification envelopes.")
    sys.exit()

if (batch.JsonTypeOf("messages") != 4):
    print("Expected a messages array.")
    sys.exit()

count = batch.SizeOfArray("messages")
if ((count < 1) or (count > 100)):
    print("Use 1 to 100 envelopes per verification batch.")
    sys.exit()

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 = chilkat.CkHashtable()
envelope = chilkat.CkJsonObject()
now = chilkat.CkDateTime()
success = now.SetFromCurrentSystemTime()
if (success != True):
    print("Could not read current time.")
    sys.exit()

envelopeIndex = 0
while (envelopeIndex < count) :
    batch.put_I(envelopeIndex)
    success = batch.ObjectOf2("messages[i]",envelope)
    if (success != True):
        print("Expected a JSON object envelope.")
        sys.exit()

    fieldNames = chilkat.CkHashtable()
    fieldIndex = 0
    while (fieldIndex < envelope.get_Size()) :
        fieldName = envelope.nameAt(fieldIndex)
        if (fieldNames.Contains(fieldName) == True):
            print("Duplicate envelope field.")
            sys.exit()

        success = fieldNames.AddStr(fieldName,"seen")
        if (success != True):
            print("Could not track envelope fields.")
            sys.exit()

        fieldIndex = fieldIndex + 1

    stringCompare.SetString(envelope.stringOf("Type"))
    stringMatch1 = stringCompare.ContentsEqual("",True)
    if ((envelope.JsonTypeOf("Type") != 1) or (stringMatch1 == True)):
        print("Missing or invalid Type.")
        sys.exit()

    stringCompare.SetString(envelope.stringOf("MessageId"))
    stringMatch2 = stringCompare.ContentsEqual("",True)
    if ((envelope.JsonTypeOf("MessageId") != 1) or (stringMatch2 == True)):
        print("Missing or invalid MessageId.")
        sys.exit()

    stringCompare.SetString(envelope.stringOf("Message"))
    stringMatch3 = stringCompare.ContentsEqual("",True)
    if ((envelope.JsonTypeOf("Message") != 1) or (stringMatch3 == True)):
        print("Missing or invalid Message.")
        sys.exit()

    stringCompare.SetString(envelope.stringOf("Timestamp"))
    stringMatch4 = stringCompare.ContentsEqual("",True)
    if ((envelope.JsonTypeOf("Timestamp") != 1) or (stringMatch4 == True)):
        print("Missing or invalid Timestamp.")
        sys.exit()

    stringCompare.SetString(envelope.stringOf("TopicArn"))
    stringMatch5 = stringCompare.ContentsEqual("",True)
    if ((envelope.JsonTypeOf("TopicArn") != 1) or (stringMatch5 == True)):
        print("Missing or invalid TopicArn.")
        sys.exit()

    stringCompare.SetString(envelope.stringOf("SignatureVersion"))
    stringMatch6 = stringCompare.ContentsEqual("",True)
    if ((envelope.JsonTypeOf("SignatureVersion") != 1) or (stringMatch6 == True)):
        print("Missing or invalid SignatureVersion.")
        sys.exit()

    stringCompare.SetString(envelope.stringOf("Signature"))
    stringMatch7 = stringCompare.ContentsEqual("",True)
    if ((envelope.JsonTypeOf("Signature") != 1) or (stringMatch7 == True)):
        print("Missing or invalid Signature.")
        sys.exit()

    stringCompare.SetString(envelope.stringOf("SigningCertURL"))
    stringMatch8 = stringCompare.ContentsEqual("",True)
    if ((envelope.JsonTypeOf("SigningCertURL") != 1) or (stringMatch8 == True)):
        print("Missing or invalid SigningCertURL.")
        sys.exit()

    messageType = envelope.stringOf("Type")
    stringCompare.SetString(messageType)
    stringMatch9 = stringCompare.ContentsEqual("Notification",True)
    stringCompare.SetString(messageType)
    stringMatch10 = stringCompare.ContentsEqual("SubscriptionConfirmation",True)
    stringCompare.SetString(messageType)
    stringMatch11 = stringCompare.ContentsEqual("UnsubscribeConfirmation",True)
    if ((stringMatch9 != True) and (stringMatch10 != True) and (stringMatch11 != True)):
        print("Unsupported SNS message type.")
        sys.exit()

    stringCompare.SetString(envelope.stringOf("TopicArn"))
    stringMatch12 = stringCompare.ContentsEqual(allowedTopic,True)
    if (stringMatch12 != True):
        print("Unexpected SNS topic.")
        sys.exit()

    signatureVersion = envelope.stringOf("SignatureVersion")
    stringCompare.SetString(signatureVersion)
    stringMatch13 = stringCompare.ContentsEqual("1",True)
    stringCompare.SetString(signatureVersion)
    stringMatch14 = stringCompare.ContentsEqual("2",True)
    if ((stringMatch13 != True) and (stringMatch14 != True)):
        print("Unsupported delivery signature version.")
        sys.exit()

    hashAlgorithm = "sha256"
    stringCompare.SetString(signatureVersion)
    stringMatch15 = stringCompare.ContentsEqual("1",True)
    if (stringMatch15 == True):
        hashAlgorithm = "sha1"

    stringCompare.SetString(messageType)
    stringMatch16 = stringCompare.ContentsEqual("Notification",True)
    if (stringMatch16 != True):
        stringCompare.SetString(envelope.stringOf("SubscribeURL"))
        stringMatch17 = stringCompare.ContentsEqual("",True)
        stringCompare.SetString(envelope.stringOf("Token"))
        stringMatch18 = stringCompare.ContentsEqual("",True)
        if ((envelope.JsonTypeOf("SubscribeURL") != 1) or (stringMatch17 == True) or (envelope.JsonTypeOf("Token") != 1) or (stringMatch18 == True)):
            print("Confirmation envelope is missing fields.")
            sys.exit()

    if (envelope.HasMember("Subject") == True):
        if (envelope.JsonTypeOf("Subject") != 1):
            print("Subject must be a string when present.")
            sys.exit()

    timestamp = chilkat.CkDateTime()
    success = timestamp.SetFromTimestamp(envelope.stringOf("Timestamp"))
    if (success != True):
        print("Invalid notification timestamp.")
        sys.exit()

    ageSeconds = now.DiffSeconds(timestamp)
    if ((ageSeconds < -300) or (ageSeconds > 86400)):
        print("Notification outside the configured 24-hour age / 5-minute clock-skew window.")
        sys.exit()

    certUrl = chilkat.CkStringBuilder()
    certUrl.Append(envelope.stringOf("SigningCertURL"))
    prefix = chilkat.CkStringBuilder()
    prefix.Append(certPrefix)
    if ((certUrl.StartsWith(certPrefix,True) != True) or (certUrl.EndsWith(".pem",True) != True) or (certUrl.get_Length() <= prefix.get_Length() + 4)):
        print("Untrusted signing-certificate URL.")
        sys.exit()

    #  Only a flat SNS certificate filename is allowed: no query, fragment, escapes,
    #  userinfo, alternate port, path traversal, or redirect destination.
    filenameChars = chilkat.CkStringBuilder()
    filenameChars.Append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_")
    charIndex = prefix.get_Length()
    while (charIndex < certUrl.get_Length() - 4) :
        if (filenameChars.Contains(certUrl.getRange(charIndex,1,False),True) != True):
            print("Invalid signing-certificate filename.")
            sys.exit()

        charIndex = charIndex + 1

    http = chilkat.CkHttp()
    http.put_RequireSslCertVerify(True)
    http.put_FollowRedirects(False)
    http.put_ConnectTimeout(20)
    http.put_ReadTimeout(30)
    maxCertBytes = 65536
    http.put_MaxResponseSize(maxCertBytes)
    http.put_VerboseLogging(False)
    certPem = http.quickGetStr(certUrl.getAsString())
    if ((http.get_LastMethodSuccess() != True) or (http.get_LastStatus() != 200)):
        print("Could not retrieve the certificate securely from the pinned SNS endpoint.")
        sys.exit()

    signingCert = chilkat.CkCert()
    success = signingCert.LoadPem(certPem)
    if (success != True):
        print("Invalid signing certificate.")
        sys.exit()

    chain = chilkat.CkCertChain()
    success = signingCert.BuildCertChain(chain)
    if (success != True):
        print("Could not build signing-certificate chain.")
        sys.exit()

    if (chain.get_ReachesRoot() != True):
        print("Incomplete signing-certificate chain; provision trusted intermediates.")
        sys.exit()

    roots = chilkat.CkTrustedRoots()
    roots.put_TrustSystemCaRoots(True)
    if (chain.IsRootTrusted(roots) != True):
        print("Untrusted signing-certificate root.")
        sys.exit()

    success = chain.VerifyCertSignatures()
    if (success != True):
        print("Invalid certificate-chain signatures.")
        sys.exit()

    certIndex = 0
    chainCert = chilkat.CkCert()
    while (certIndex < chain.get_NumCerts()) :
        success = chain.CertAt(certIndex,chainCert)
        if (success != True):
            print("Could not read chain certificate.")
            sys.exit()

        validFrom = chilkat.CkDateTime()
        validTo = chilkat.CkDateTime()
        success = validFrom.SetFromRfc822(chainCert.validFromStr())
        if (success != True):
            print("Invalid certificate validity start.")
            sys.exit()

        success = validTo.SetFromRfc822(chainCert.validToStr())
        if (success != True):
            print("Invalid certificate validity end.")
            sys.exit()

        if ((now.DiffSeconds(validFrom) < 0) or (now.DiffSeconds(validTo) > 0)):
            print("Certificate outside its validity period.")
            sys.exit()

        certIndex = certIndex + 1

    canonical = chilkat.CkStringBuilder()
    canonical.AppendLine("Message",False)
    canonical.AppendLine(envelope.stringOf("Message"),False)
    canonical.AppendLine("MessageId",False)
    canonical.AppendLine(envelope.stringOf("MessageId"),False)
    stringCompare.SetString(messageType)
    stringMatch19 = stringCompare.ContentsEqual("Notification",True)
    if (stringMatch19 == True):
        if (envelope.HasMember("Subject") == True):
            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)
    stringMatch20 = stringCompare.ContentsEqual("Notification",True)
    if (stringMatch20 != True):
        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)
    publicKey = chilkat.CkPublicKey()
    success = signingCert.GetPublicKey(publicKey)
    if (success != True):
        print("Could not extract signing public key.")
        sys.exit()

    rsa = chilkat.CkRsa()
    rsa.put_Charset("utf-8")
    rsa.put_EncodingMode("base64")
    rsa.put_LittleEndian(False)
    success = rsa.UsePublicKey(publicKey)
    if (success != True):
        print("Could not configure verification key.")
        sys.exit()

    success = rsa.VerifyStringENC(canonical.getAsString(),hashAlgorithm,envelope.stringOf("Signature"))
    if (success != True):
        print("SNS delivery signature is invalid.")
        sys.exit()

    #  Use a JSON-encoded composite key to avoid ambiguous concatenation.
    identity = chilkat.CkJsonObject()
    success = identity.UpdateString("topic",allowedTopic)
    if (success != True):
        print("Could not form duplicate key.")
        sys.exit()

    success = identity.UpdateString("id",envelope.stringOf("MessageId"))
    if (success != True):
        print("Could not form duplicate key.")
        sys.exit()

    duplicateKey = identity.emit()
    if (seenMessages.Contains(duplicateKey) == True):
        print("Verified duplicate skipped: " + envelope.stringOf("MessageId"))
    else:
        success = seenMessages.AddStr(duplicateKey,"verified")
        if (success != True):
            print("Could not track duplicate key.")
            sys.exit()

        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 = envelopeIndex + 1

print("All envelopes verified; duplicate detection was limited to this batch.")